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-SAHGDSZQ.mjs
DELETED
|
@@ -1,37 +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{E as os,s as Yo}from"./chunk-TG52WNGV.mjs";import{A as yn,G as ce,H as To,I as St,Q as Fo,e as yt,l as Ao,u as Io,v as jo,w as No,z as wn}from"./chunk-CSSOLHE3.mjs";import{e as Rs,h as Ss}from"./chunk-TEIBWMJM.mjs";import{a as vo,b as Co}from"./chunk-T63U4OZJ.mjs";import{a as et,d as ns,i as rs,o as Te}from"./chunk-5EESNYE3.mjs";import{a as xo}from"./chunk-YYZL7UGV.mjs";import{a as yo,l as Oo}from"./chunk-YDXMTWAT.mjs";import{d as Po}from"./chunk-QIRO4HTE.mjs";import{b as Eo}from"./chunk-QSRAEUGZ.mjs";import{e as Os}from"./chunk-B5A4JHNN.mjs";import{t as Ae}from"./chunk-YGE4AUXG.mjs";import{a as _o,b as Do,d as Bo,e as At,f as Ee,g as $o,h as Wo,i as kt,j as qo,k as Uo,l as zo,m as Vo,n as Go,o as Jo,p as se,q as ie,r as It,s as we,t as Ho}from"./chunk-RFD6NPWJ.mjs";import{d as bn,z as Ko}from"./chunk-SF52ZSIV.mjs";import{a as ho,b as Le,c as wo,d as X,h as fe}from"./chunk-P6A22FMQ.mjs";import{a as go}from"./chunk-5LFSFYFJ.mjs";import{Ac as hs,Fc as ws,Gc as ys,Hc as bs,Ib as us,Ic as pe,Ob as ls,P as es,Pb as fs,Q as On,Qb as ps,R as ts,Va as Fe,Wa as tt,Xa as Tt,Ya as ss,Za as ye,jb as ke,mb as is,nb as as,xc as ms,yb as ds,zb as cs,zc as gs}from"./chunk-O3ZQSWDN.mjs";import{b as no,k as ro}from"./chunk-DNE7JI3A.mjs";import{b as Ot}from"./chunk-VV3B6IC3.mjs";import{f as Et}from"./chunk-AX3YF7SC.mjs";import{a as oo,b as so,c as pn,e as io,f as ao,g as co,i as mn,j as uo}from"./chunk-INIT2UKJ.mjs";import{a as So,c as hn,j as ko}from"./chunk-JBOGAUGH.mjs";import{f as po,g as mo}from"./chunk-TWYNQ2OO.mjs";import{a as U,b as ue,c as jt,d as Rn,e as Zo,f as Nt,g as Qo,h as Sn,i as Xo}from"./chunk-TQ2TQHTT.mjs";import{g as fo}from"./chunk-OHEOJISY.mjs";import{c as lo}from"./chunk-EADHKH3A.mjs";import{b as eo,r as to}from"./chunk-FG4Y4ZVL.mjs";import{A as qr,B as ln,C as Ur,F as zr,G as fn,J as Vr,K as Gr,O as Jr,R as Hr,S as Kr,T as Yr,U as Zr,V as Qr,W as Xr,e as un,q as de,r as oe,s as Me,x as $r,y as Wr}from"./chunk-Z354SAEF.mjs";import{a as xe,h as J}from"./chunk-TZE3Y7IQ.mjs";import{a as wt,b as H}from"./chunk-CA5NAXSU.mjs";import{a as Mo,b as Lo}from"./chunk-PC247GKX.mjs";import{a as bt,c as gn,f as bo,i as Rt,k as Ro}from"./chunk-THYQOG24.mjs";import{Aa as Fr,Ac as Qe,Ba as Pr,Bc as pt,Ca as vr,Ec as Xe,Fc as cn,Gc as mt,Hd as Dr,Id as Br,Lc as Ce,Mc as gt,O as Ze,Pc as ht,T as an,Ya as Cr,_ as dn,fd as Oe,sc as xr,ua as Se,va as Tr,vd as _r,yc as Mr,zc as Lr}from"./chunk-CRPLDXJU.mjs";import{b as W,e as te,f as Ke,i as Ne,k as Z,l as V,m as on,r as Er,s as sn,u as ve,v as Ye}from"./chunk-WZQEK4WT.mjs";function Gl(n){return`Salesforce can take several minutes to count a load in what ${n} says it has left: what runs from this machine wrote to it in the last ${no} minutes, or are still writing, and it has not counted yet is taken off, a load from anywhere else is not`}function Jl(n){return n.uncountedMB!==void 0&&n.uncountedMB>0?`, ${ms(n.uncountedMB)} MB for what runs from this machine wrote to it, or are still writing, that Salesforce has not counted yet`:""}function ks(n){if("unread"in n.storage)return n.withinMB===void 0?{unread:n.storage.unread}:As(n,Math.floor(Math.max(0,n.withinMB)*1048576),{share:Fe,roundingMB:tt,withinMB:n.withinMB,limitedBy:"within"});let{remainingMB:e,maxMB:t,uncountedWrites:r}=n.storage,o=Fe*Tt(n.storage)*1048576,s=n.withinMB!==void 0?Math.max(0,n.withinMB)*1048576:1/0,i=s<o?"within":"storage",a={remainingMB:e,maxMB:t,share:Fe,roundingMB:tt,...r?{uncountedMB:r.mb}:{},...n.withinMB!==void 0?{withinMB:n.withinMB}:{},limitedBy:i},d=Math.floor(Math.min(o,s));return As(n,d,a)}function Is(n,e){return e.bytesLimit==="within"&&e.storageBytes!==void 0&&n>e.storageBytes?"storage":e.bytesLimit}function As(n,e,t){if(!n.api)return{bytes:e,terms:t};if("unread"in n.api)return{bytes:e,terms:t,requestsUnread:n.api.unread};let r=Object.values(n.otherRequests??{}).reduce((s,i)=>s+Math.max(0,i??0),0),o=Math.max(0,Math.floor(n.api.remaining-ke*n.api.max-r));return{bytes:e,terms:t,runRequests:o}}var ja=/__e$/i,Na=/Share$/;function Hl(n,e){let t=new Map,r=new Map,o=(i,a)=>{let d=`${i}
|
|
8
|
-
${a}`,c=t.get(d);return c||(c={objectApiName:i,act:a,bytes:0,creates:[]},t.set(d,c)),c},s=i=>{r.set(`${i.objectApiName}
|
|
9
|
-
${i.kind}
|
|
10
|
-
${i.name}`,i)};for(let i of n.firing){let a=i.write;if(!(a!=="insert"&&a!=="update")&&e(i.objectApiName,a)){if(i.kind==="trigger"||!i.flow){s({objectApiName:i.objectApiName,kind:"trigger",name:i.name});continue}if(i.flow.condition!=="read"){s({objectApiName:i.objectApiName,kind:"notRead",name:i.name});continue}for(let d of i.flow.creates??[]){if(ja.test(d))continue;if(Na.test(d)){s({objectApiName:i.objectApiName,kind:"share",name:d});continue}let c=o(i.objectApiName,a);c.bytes+=ye(d,{rows:1}),c.creates.push({objectApiName:d,by:i.name})}}}return{perRecord:[...t.values()].filter(i=>i.bytes>0),notCounted:[...r.values()]}}function Kl(n,e){return n.perRecord.reduce((t,r)=>t+r.bytes*Math.max(0,e(r.objectApiName,r.act)),0)}function Yl(n,e,t){return{budgetMB:Math.max(0,n.bytes-e)/1048576,...n.terms,automationMB:e/1048576,...t.notCounted.length>0?{notCounted:t.notCounted.map(r=>({...r}))}:{}}}function js(n,e){if(!e(1))return 0;if(e(n))return n;let t=1,r=n;for(;r-t>1;){let o=Math.floor((t+r)/2);e(o)?t=o:r=o}return t}function Zl(n,e){let t=Math.max(0,Math.floor(n)),r=Math.min(t,Math.max(0,Math.floor(e))),o=[];if(r===0)return o;for(let s=0;s<t;s++)Math.floor((s+1)*r/t)>Math.floor(s*r/t)&&o.push(s);return o}import{existsSync as Ea,readFileSync as Ta,writeFileSync as Fa}from"node:fs";function tf(n){let e={getData:()=>Ea(n)?JSON.parse(Ta(n,"utf8")):{},setData:r=>Fa(n,JSON.stringify(r,null,2),{encoding:"utf8",mode:384})},t=new os(e);return t.initialize(),t}var An="User",Pa="005",Es=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function va(n,e,t=eo){let r=n.referenceTo??[];return n.name==="RecordTypeId"||r.length===0?!1:r.every(o=>t(o))?!0:r.length===1&&e?.(r[0])===!0}var Ns=1e5;async function af(n){let{known:e,ownerMappings:t={},mapped:r,refused:o,inactive:s}=n,i=n.lookups.filter(m=>va(m,n.outsideTheRun,n.neverCopied)),a=new Map,d=new Set;for(let m of i)for(let g of n.rows){let h=g[m.name];if(typeof h!="string"||!Es.test(h)||m.name==="OwnerId"&&t[h]!==void 0||r?.(h)===!0||(d.add(h),e.has(h)))continue;let y=m.referenceTo??[];if(!y.some(R=>o?.has(R)===!0))for(let R of y)a.set(R,(a.get(R)??new Set).add(h))}let c=new Set,f=new Set,l=new Set;for(let[m,g]of a){let h=s!==void 0&&m===An,y=h?"Id, IsActive":"Id";for(let R of X([...g]))try{let S=await n.query(`SELECT ${y} FROM ${J(m)} WHERE Id IN (${R})`);for(let w of S){let b=w.Id;typeof b=="string"&&(c.add(b),c.add(b.slice(0,15)),h&&w.IsActive===!1&&(l.add(b),l.add(b.slice(0,15))))}}catch{for(let S of g)f.add(S);o?.add(m);break}}let p=new Map;for(let m of a.values())for(let g of m)c.has(g)||c.has(g.slice(0,15))?p.set(g,!0):!f.has(g)&&!p.has(g)&&p.set(g,!1);for(let[m,g]of p){if(e.size>=Ns)break;e.set(m,g)}if(s&&l.size>0){let m=[...a.get(An)??[]].filter(g=>l.has(g)||l.has(g.slice(0,15)));for(let g of[...l,...m]){if(s.size>=Ns)break;s.add(g)}}let u=new Set;for(let m of d)(p.get(m)??e.get(m))===!1&&u.add(m);return u}function df(n,e,t={}){let r=new Set;if(e.size===0)return r;for(let o of n){let s=o.OwnerId;typeof s!="string"||!s||t[s]===void 0&&e.has(s)&&r.add(s)}return r}var Ca="SELECT PermissionsUpdateWithInactiveOwner FROM UserPermissionAccess";async function xa(n){try{let[e]=await n(Ca);return e?.PermissionsUpdateWithInactiveOwner===!0}catch{return!1}}function cf(n){let e;return()=>(e??=xa(n),e)}async function Ts(n,e){let t=new Map;for(let[i,a]of Object.entries(n)){if(!Es.test(a))continue;let d=a.slice(0,15),c=t.get(d)??{user:a,sources:[]};c.sources.push(i),t.set(d,c)}let r=[],o=[],s=[...t.values()];for(let i=0;i<s.length;i+=Le){let a=s.slice(i,i+Le),[d]=X(a.map(({user:l})=>l)),c;try{c=await e(`SELECT Id, Name, IsActive FROM ${An} WHERE Id IN (${d})`)}catch{continue}let f=new Set;for(let l of c){let p=l.Id;if(typeof p!="string"||(f.add(p.slice(0,15)),l.IsActive!==!1))continue;let u=t.get(p.slice(0,15));if(!u)continue;let m=l.Name;r.push({user:u.user,...typeof m=="string"&&m!==""?{name:m}:{},sources:u.sources})}for(let{user:l,sources:p}of a)l.startsWith(Pa)&&!f.has(l.slice(0,15))&&o.push({user:l,sources:p})}return{inactive:r,unknown:o}}var Ft=10,kn="Nothing was read or written.",pf="Nothing was written.";function Fs(n,e=kn){let t=n.slice(0,Ft).map(({user:o,name:s,sources:i})=>`${s!==void 0?`${s} (${o})`:o}, given the records of `+i.join(", ")).join("; "),r=n.length-Ft;return`Owners given to users the target holds inactive: ${t}${r>0?`; and ${r} more`:""}. The target refuses a record owned by an inactive user, and the run will not give it to the user it writes as instead of the one chosen. Give those records to an active user under Owners (Review \u2192 Controls, or --owner-map on the command line), or reactivate the user in the target. `+e}function Ma(n,e=kn){let t=n.slice(0,Ft).map(({user:o,sources:s})=>`${o}, given the records of ${s.join(", ")}`).join("; "),r=n.length-Ft;return`Owners given to users the target does not hold: ${t}${r>0?`; and ${r} more`:""}. The target refuses a record owned by a user it does not hold (INVALID_CROSS_REFERENCE_KEY), and the run will not give it to the user it writes as instead of the one chosen. Give those records to a user of the target under Owners (Review \u2192 Controls, or --owner-map on the command line). `+e}async function mf(n,e,t=kn){let{inactive:r,unknown:o}=await Ts(n,e);if(o.length>0){let s=Ma(o,t);return new pe(bs,r.length>0?`${s.slice(0,-t.length)}${Fs(r,t)}`:s)}return r.length>0?new pe(ys,Fs(r,t)):void 0}import{createHash as La}from"node:crypto";var Cs={ContentVersion:"VersionData",Attachment:"Body"},_a=3,Ps=class extends Error{constructor(t,r,o){super(t);this.code=r;this.storage=o;this.name="ForgeFilesRefusedError"}code;storage};function Y(n,e){let t=n[e];return typeof t=="string"&&t!==""?t:void 0}function vs(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0}function In(n,e,t){return{objectApiName:n,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:e,messages:[H(t)]}]}}async function Of(n){let{scope:e,sourceOrgId:t,maxFileBytes:r,queryRecords:o}=n,s=new Map;for(let l of e.values())for(let p of l)s.has(p)||s.set(p,s.size);let i={files:[],leftOut:[],errors:[]},a=[...s.keys()];if(a.length===0)return i;let d=l=>s.get(l)??Number.MAX_SAFE_INTEGER,c=new Map;try{for(let l of X(a)){let p=await o(t,`SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility FROM ContentDocumentLink WHERE LinkedEntityId IN (${l})`);for(let u of p){let m=Y(u,"ContentDocumentId"),g=Y(u,"LinkedEntityId");if(!m||!g||!s.has(g))continue;let h=c.get(m)??[];h.some(y=>y.id===g)||h.push({id:g,shareType:Y(u,"ShareType"),visibility:Y(u,"Visibility")}),c.set(m,h)}}}catch(l){i.errors.push(In("ContentDocument","(links of the records in scope)",l))}let f=[];try{for(let l of X([...c.keys()])){let p=await o(t,`SELECT Id, ContentDocumentId, Title, PathOnClient, ContentSize, ContentLocation, SharingPrivacy FROM ContentVersion WHERE ContentDocumentId IN (${l}) AND IsLatest = true`);for(let u of p){let m=Y(u,"ContentDocumentId"),g=Y(u,"Id"),h=m?c.get(m):void 0;if(!m||!g||!h)continue;let y=Y(u,"Title")??m;f.push({external:(Y(u,"ContentLocation")??"S")!=="S",file:{objectApiName:"ContentDocument",sourceId:m,body:{objectApiName:"ContentVersion",id:g},name:y,bytes:vs(u,"ContentSize"),hosts:[...h].sort((R,S)=>d(R.id)-d(S.id)),fields:{Title:y,PathOnClient:Y(u,"PathOnClient")??y,...Y(u,"SharingPrivacy")==="P"?{SharingPrivacy:"P"}:{}}}})}}}catch(l){i.errors.push(In("ContentDocument","(latest versions of the files)",l))}try{for(let l of X(a)){let p=await o(t,`SELECT Id, ParentId, Name, ContentType, BodyLength, IsPrivate FROM Attachment WHERE ParentId IN (${l})`);for(let u of p){let m=Y(u,"Id"),g=Y(u,"ParentId");if(!m||!g||!s.has(g))continue;let h=Y(u,"Name")??m;f.push({external:!1,file:{objectApiName:"Attachment",sourceId:m,body:{objectApiName:"Attachment",id:m},name:h,bytes:vs(u,"BodyLength"),hosts:[{id:g}],fields:{Name:h,...Y(u,"ContentType")?{ContentType:Y(u,"ContentType")}:{},IsPrivate:u.IsPrivate===!0}}})}}}catch(l){i.errors.push(In("Attachment","(attachments of the records in scope)",l))}f.sort((l,p)=>d(l.file.hosts[0].id)-d(p.file.hosts[0].id));for(let{file:l,external:p}of f){let u=p?"external":l.bytes>r?"too-large":void 0;u?i.leftOut.push({objectApiName:l.objectApiName,sourceId:l.sourceId,name:l.name,bytes:l.bytes,reason:u}):i.files.push(l)}return i}function Af(n){return n.errors.length===0?null:`The files of the records to clone could not all be looked up in the source (${[...new Set(n.errors.flatMap(t=>t.samples.flatMap(r=>r.messages)))].join("; ")}). Run it again, or leave the files out.`}async function kf(n){let{files:e,targetOrgId:t,copiedBefore:r,queryRecords:o}=n,s={files:[],errors:[]},i=new Map;for(let u of e){let m=r(u.sourceId);m&&i.set(u.sourceId,m)}if(i.size===0)return{...s,files:[...e]};let a=new Map,d,c=new Map;for(let[u,m]of i)m.objectApiName==="ContentVersion"&&c.set(m.targetId,u),m.objectApiName==="ContentDocument"&&a.set(u,m.targetId);try{for(let u of X([...c.keys()])){let m=await o(t,`SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id IN (${u})`);for(let g of m){let h=Y(g,"Id"),y=Y(g,"ContentDocumentId"),R=h?c.get(h):void 0;R&&y&&a.set(R,y)}}}catch(u){d=H(u)}let f=new Map,l;try{for(let u of X([...new Set(a.values())])){let m=await o(t,`SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN (${u})`);for(let g of m){let h=Y(g,"ContentDocumentId"),y=Y(g,"LinkedEntityId");h&&y&&f.set(h,[...f.get(h)??[],y])}}}catch(u){l=H(u)}let p=(u,m)=>{s.errors.push({objectApiName:"ContentDocument",stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`${u.name} (${Oe(u.bytes)})`,messages:[m]}]})};for(let u of e){let m=i.get(u.sourceId);if(!m){s.files.push(u);continue}if(u.body.objectApiName==="Attachment")continue;let g=a.get(u.sourceId);if(!g){p(u,`Copied as ContentVersion ${m.targetId} by the run this one takes up, and its document still cannot be read back`+(d?` (${d})`:"")+": the file is not copied again, nor linked to the records it lacks.");continue}if(l){p(u,`Copied by the run this one takes up; its links could not be read (${l}): it is not linked to the records it lacks.`);continue}s.files.push({...u,into:{documentId:g,linked:f.get(g)??[],unchanged:!0}})}return s}function If(n){return{objectApiName:"__files__",stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(files)",messages:[n]}]}}function jf(n){return n.reduce((e,t)=>e+t.bytes,0)}function Nf(n,e){return n<=e?null:`The files to copy take ${Oe(n)} and the target has ${Oe(Math.max(0,e))} of file storage left. Lower the largest file copied, or leave the files out.`}async function Ef(n,e){let t=await n.remainingFileStorageMB(e);if(!Number.isFinite(t))throw new Error("The target did not say how much file storage it has left.");return t*1048576}function Tf(n,e,t){let r=[];for(let o of n.files){let s=r.find(i=>i.objectApiName===o.objectApiName);s||(s={objectApiName:o.objectApiName,planned:0,plannedBytes:0,copied:0,failed:0},r.push(s)),s.planned++,s.plannedBytes+=o.bytes}return{maxFileBytes:e,objects:r,links:0,leftOut:[...n.leftOut],...t===void 0?{}:{remainingStorageBytes:t}}}function jn(n,e){let t=n==="Attachment"?"attachment":"file";return e===1?t:`${t}s`}function Ff(n){return`[dry-run] ${n.objectApiName}: ${n.planned} ${jn(n.objectApiName,n.planned)} would be copied (${Oe(n.plannedBytes)})`}function Da(n,e,t){return n.body.objectApiName==="Attachment"?{Name:n.fields.Name??n.name,BodyLength:n.bytes,ParentId:t}:{Title:n.fields.Title??n.name,Checksum:La("md5").update(Buffer.from(e,"base64")).digest("hex"),ContentSize:n.bytes}}function Ba(n){let e={};for(let[t,r]of Object.entries(n))t!=="SharingPrivacy"&&(e[t]=r);return e}async function Pf(n){let{files:e,sourceOrgId:t,targetOrgId:r,remapper:o,deps:s,report:i,errors:a,onProgress:d,onCopied:c}=n,f=0,l=w=>{let b=i.objects.find(A=>A.objectApiName===w);return b||(b={objectApiName:w,planned:0,plannedBytes:0,copied:0,failed:0},i.objects.push(b)),b},p=(w,b)=>a.find(A=>A.objectApiName===w&&A.stage===b),u=new Map,m=(w,b,A=1)=>{let j=`${w}/${b}`;u.set(j,(u.get(j)??0)+A);let L=p(w,b);L&&(L.attemptedCount+=A)},g=(w,b,A,j,L=!1)=>{let v=p(w,b);v||(v={objectApiName:w,stage:b,failedCount:0,attemptedCount:u.get(`${w}/${b}`)??0,samples:[]},a.push(v)),L||(v.failedCount++,f++),v.samples.length<_a&&v.samples.push({recordSummary:A,messages:[j]})},h=(w,b,A)=>{g(w.objectApiName,b,`${w.name} (${Oe(w.bytes)})`,A),l(w.objectApiName).failed++},y=async(w,b,A)=>{let j=A.flatMap(v=>{let P=o.get(v.id);return P?[{ContentDocumentId:b,LinkedEntityId:P,ShareType:v.shareType??"V",Visibility:v.visibility??"AllUsers"}]:[]});if(j.length===0)return[];let L=[];m("ContentDocumentLink","insert",j.length);try{let v=await s.insertRecords(r,"ContentDocumentLink",j);j.forEach((P,k)=>{let N=v[k];if(N?.success){i.links++,L.push(P.LinkedEntityId);return}g("ContentDocumentLink","insert",w.name,N?.errors.join("; ")||"The target gave no reason.")})}catch(v){for(let P=0;P<j.length;P++)g("ContentDocumentLink","insert",w.name,H(v))}return L},R=e.filter(w=>!(w.body.objectApiName==="ContentVersion"&&w.into?.unchanged)).length,S=0;for(let w of e){await n.waitIfPaused();let b=w.hosts.filter(O=>o.isCreated(O.id)),A=w.body.objectApiName==="ContentVersion"?w.into:void 0,j=A?b.filter(O=>{let C=o.get(O.id);return C!==void 0&&!A.linked.includes(C)}):[];if(A?.unchanged){let O=await y(w,A.documentId,j);O.length>0&&c?.(w,{targetId:A.documentId,linked:O,asVersion:!1});continue}let L=S++,v=b.length>0?o.get(b[0].id):void 0;if(!v&&!A){i.leftOut.push({objectApiName:w.objectApiName,sourceId:w.sourceId,name:w.name,bytes:w.bytes,reason:"record-not-created"});continue}d({objectName:w.objectApiName,status:"running",progress:Math.round(L/R*100),message:`Copying ${jn(w.objectApiName,1)} ${L+1} of ${R} (${Oe(w.bytes)})`});let P;m(w.objectApiName,"query");try{P=await s.readFileBody(t,w.body.objectApiName,w.body.id)}catch(O){h(w,"query",H(O));continue}let k=Buffer.byteLength(P,"base64");if(k!==w.bytes){h(w,"query",`Read ${k} bytes of the ${w.bytes} the source reports: the file was not written.`);continue}let N=A?{...Ba(w.fields),VersionData:P,ContentDocumentId:A.documentId}:w.body.objectApiName==="ContentVersion"?{...w.fields,VersionData:P,FirstPublishLocationId:v}:{...w.fields,Body:P,ParentId:v},M;m(w.objectApiName,"insert");let D=n.calls?.sending(w.body.objectApiName,[{sourceId:w.sourceId,payload:Da(w,P,v)}]),E=()=>{D!==void 0&&n.calls?.answered(D)};try{M=await s.insertFile(r,w.body.objectApiName,N)}catch(O){xo(O)!=="may-have-written"&&E(),h(w,"insert",H(O));continue}if(!M.success||!M.id){E(),h(w,"insert",M.errors.join("; ")||"The target gave no reason.");continue}if(l(w.objectApiName).copied++,w.body.objectApiName==="Attachment"){o.add(w.sourceId,M.id,"Attachment"),E(),o.persist?.(),c?.(w,{targetId:M.id,linked:v?[v]:[],asVersion:!1});continue}if(A){o.add(w.sourceId,A.documentId,"ContentDocument"),E(),o.persist?.();let O=await y(w,A.documentId,j);c?.(w,{targetId:A.documentId,linked:O,asVersion:!0});continue}o.add(w.sourceId,M.id,"ContentVersion"),E(),o.persist?.();let T;try{let O=await s.queryRecords(r,`SELECT ContentDocumentId FROM ContentVersion WHERE Id = '${xe(M.id)}'`);T=O[0]?Y(O[0],"ContentDocumentId"):void 0}catch{T=void 0}if(!T){g("ContentDocument","query",`${w.name} (${Oe(w.bytes)})`,`Copied as ContentVersion ${M.id}, but its document could not be read back: the run keeps the version, which a removal of the run takes with its document, and links it to no other record.`,!0);continue}o.add(w.sourceId,T,"ContentDocument"),o.persist?.();let I=await y(w,T,b.slice(1));c?.(w,{targetId:T,linked:v?[v,...I]:I,asVersion:!1})}for(let w of i.objects)d({objectName:w.objectApiName,status:w.failed>0&&w.copied===0?"error":"done",progress:100,message:`Copied ${w.copied} ${jn(w.objectApiName,w.copied)} of ${w.planned}`+(w.failed>0?`, ${w.failed} failed`:"")});return f}function Df(n,e,t={},r){if(!n)return;let o={};for(let s of e.nodes)rs(s)&&(o[s.objectApiName]=[...s.anonymizeFields]);return{fields:o,methods:{...t},...r?{personalFieldsOf:r}:{}}}var $a=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Wa=/@example\.com$/i,Nn="@example.invalid",qa=64,Ua=new Set(["fake","mask","preserve_format","shuffle"]);function za(n,e,t){return typeof n!="string"||n===""?n:$a.test(n)?e.email(n.replace(Wa,Nn),t):`${n.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,qa).replace(/^[._]+|[._]+$/g,"")||"anonymized"}${Nn}`}var xs=class{smartAnonymizer;contactPoints;constructor(e,t){this.smartAnonymizer=new Po(e),this.contactPoints=new Ss(t)}categorizeField(e,t){let r=t.toLowerCase();if(r==="email")return"email";if(r==="phone")return"phone";let o=Co(e,t);if(o)return o;let s=e.toLowerCase();return s.includes("email")?"email":s.includes("phone")||s.includes("fax")||s.includes("mobile")?"phone":s.includes("firstname")||s.includes("lastname")||s==="name"||vo(e)?"name":s.includes("street")||s.includes("address")||s.includes("city")||s.includes("state")||s.includes("postalcode")||s.includes("zip")||s.includes("country")?"address":s.includes("ssn")||s.includes("national_id")||s.includes("passport")||s.includes("driver")||s.includes("license")?"ssn_id":s.includes("credit")||s.includes("card")||s.includes("cvv")||s.includes("iban")||s.includes("routing")||s.includes("bank")?"financial":"other"}getDefaultMethod(e){return{email:"fake",phone:"mask",name:"fake",address:"fake",ssn_id:"redact",financial:"hash",other:"nullify"}[e]}getDefaults(){return{email:"fake",phone:"mask",name:"fake",address:"fake",ssn_id:"redact",financial:"hash",other:"nullify"}}anonymize(e){if(e.fields.length===0)return e.records;let t={...this.getDefaults(),...e.methods},r=e.records.map((a,d)=>({...a,Id:e.sourceIds[d]??""})),o=this.anonymizeRecords(r,e.fields,t,e.objectApiName),s=e.fields.filter(a=>this.categorizeField(a.name,a.type)==="email"),i=Ua.has(t.phone)?e.fields.filter(a=>this.categorizeField(a.name,a.type)==="phone"):[];return o.map((a,d)=>{let c=e.records[d],f={...a};for(let l of s)f[l.name]=this.undeliverable(f[l.name],l);for(let l of i)f[l.name]=this.fictionalNumber(c[l.name],f[l.name],l);return"Id"in c?f.Id=c.Id:delete f.Id,f})}undeliverable(e,t){let r=t.length!==void 0&&t.length>0?t.length:void 0;return t.type.toLowerCase()==="email"?za(e,this.contactPoints,r??Rs):typeof e!="string"?e:this.contactPoints.addressesIn(e.replace(/@example\.com(?![\w.-])/gi,Nn),r)}fictionalNumber(e,t,r){if(typeof e!="string")return t;if(!/\d/.test(e))return e;let o=r.length!==void 0&&r.length>0?r.length:void 0;return this.contactPoints.phone(e,o)}anonymizeRecords(e,t,r,o){let s=t.map(a=>{let d=this.categorizeField(a.name,a.type);return{objectApiName:o,fieldApiName:a.name,method:r[d],piiCategory:"PII",aiConfidence:1,userOverridden:!1}}),i=e.map(a=>({...a}));return this.smartAnonymizer.anonymize(i,s,o)}};var Ms=new WeakMap;function $f(n,e){typeof n=="object"&&n!==null&&Ms.set(n,e)}function Wf(n){return typeof n=="object"&&n!==null?Ms.get(n):void 0}var En=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Ls=/^[A-Za-z][A-Za-z0-9_]*$/;function nt(n){if(!n.startsWith('["'))return;let e;try{e=JSON.parse(n)}catch{return}if(!Array.isArray(e))return;let[t,r,o,s]=e;if(!(t!=="c"&&t!=="e"&&t!=="u")&&!(typeof r!="string"||!En.test(r))&&!(typeof o!="string"||!En.test(o)))return{tag:t,sourceId:r,targetId:o,object:typeof s=="string"&&Ls.test(s)?s:""}}function _e(n){if(!n.startsWith(`["${kt}"`))return;let e;try{e=JSON.parse(n)}catch{return}if(!Array.isArray(e))return;let[,t,r]=e;if(!(typeof t!="string"||!Ls.test(t)||!Array.isArray(r)))return{object:t,ids:r.filter(o=>typeof o=="string"&&En.test(o))}}function rt(n){return n.slice(0,15)}var ot=class{offsets=new Float64Array(64);lengths=new Uint16Array(64);size=0;push(e,t){if(this.size===this.offsets.length){let r=new Float64Array(this.size*2);r.set(this.offsets),this.offsets=r;let o=new Uint16Array(this.size*2);o.set(this.lengths),this.lengths=o}this.offsets[this.size]=e,this.lengths[this.size]=t,this.size++}offsetAt(e){return this.offsets[e]}lengthAt(e){return this.lengths[e]}},be=class{capacity=1024;used=0;h1=new Uint32Array(this.capacity);h2=new Uint32Array(this.capacity);taken=new Uint8Array(this.capacity);add(e){let t=se(e),r=ie(e);if(this.slotOf(t,r)>=0)return;this.used+1>this.capacity*.6&&this.grow();let o=this.freeSlotFor(r);this.h1[o]=t,this.h2[o]=r,this.taken[o]=1,this.used++}has(e){return this.slotOf(se(e),ie(e))>=0}get size(){return this.used}slotOf(e,t){let r=this.capacity-1;for(let o=t&r;;o=o+1&r){if(this.taken[o]===0)return-1;if(this.h1[o]===e&&this.h2[o]===t)return o}}freeSlotFor(e){let t=this.capacity-1,r=e&t;for(;this.taken[r]!==0;)r=r+1&t;return r}grow(){let{h1:e,h2:t,taken:r}=this;this.capacity*=2,this.h1=new Uint32Array(this.capacity),this.h2=new Uint32Array(this.capacity),this.taken=new Uint8Array(this.capacity);for(let o=0;o<r.length;o++){if(r[o]===0)continue;let s=this.freeSlotFor(t[o]);this.h1[s]=e[o],this.h2[s]=t[o],this.taken[s]=1}}},Va=2e3,st=class n{constructor(e,t,r,o,s){this.file=e;this.all=t;this.mine=r;this.firstInPart=o;this.unattributed=s}file;all;mine;firstInPart;unattributed;static read(e,t){let r=(f,l)=>nt(e.read(f,l).toString("utf8"))?.sourceId??"",o=new It(r),s=new It(r),i=new ot,a=new ot,d=!1,c=-1;for(let f of we(e)){if(!d){if(!f.text.startsWith('{"run":'))return;d=!0;continue}if(f.text.startsWith('{"part":')){c++;continue}if(f.text.startsWith('{"object":'))return;if(c===t&&_e(f.text)){a.push(f.offset,f.length);continue}let l=nt(f.text);if(!l)continue;let p=se(l.sourceId),u=ie(l.sourceId);if(o.put(o.find(l.sourceId,p,u),p,u,f.offset,f.length,0),c!==t)continue;let m=s.find(l.sourceId,p,u);m<0&&i.push(f.offset,f.length);let g=l.tag==="c"&&l.object!=="";s.put(m,p,u,f.offset,f.length,g?1:0)}return d?new n(e,o,s,i,a):void 0}mappingAt(e,t){return nt(this.file.read(e,t).toString("utf8"))}wordsOn(e){let t=se(e),r=ie(e),o=this.all.find(e,t,r),s=this.mine.find(e,t,r);return{latest:o>=0?{offset:this.all.offsetOf(o),length:this.all.lengthOf(o)}:void 0,createdByThePart:s>=0&&this.mine.codeOf(s)===1,inThePart:s>=0?{offset:this.mine.offsetOf(s),length:this.mine.lengthOf(s)}:void 0}}createdByObject(){let e=new Map;for(let t=0;t<this.firstInPart.size;t++){let r=this.mappingAt(this.firstInPart.offsetAt(t),this.firstInPart.lengthAt(t));if(!r)continue;let o=this.wordsOn(r.sourceId);if(!o.createdByThePart||!o.latest||!o.inThePart)continue;let s=this.mappingAt(o.inThePart.offset,o.inThePart.length);if(!s)continue;let i=e.get(s.object)??new ot;i.push(o.latest.offset,o.latest.length),e.set(s.object,i)}return e}runRecords(e,t=Va){let{file:r}=this,o=(g,h)=>nt(r.read(g,h).toString("utf8")),s=(g,h)=>{let y=o(g,h);return y?rt(y.targetId):""},i=new It(s),a=this.createdByObject(),d=[];for(let g of[...a.keys()].reverse()){let h=a.get(g);if(!h)continue;let y=0;for(let R=h.size-1;R>=0;R--){let S=h.offsetAt(R),w=o(S,h.lengthAt(R));if(!w||w.object==="")continue;let b=rt(w.targetId),A=se(b),j=ie(b),L=i.find(b,A,j);L>=0||(i.put(L,A,j,S,h.lengthAt(R),0),(!e||e.has(b))&&y++)}y>0&&d.push({objectApiName:g,count:y})}let c=(g,h)=>{let y=i.find(g,se(g),ie(g),h);return y>=0&&(h===void 0||i.offsetOf(y)===h)&&(!e||e.has(g))},f=g=>_e(r.read(this.unattributed.offsetAt(g),this.unattributed.lengthAt(g)).toString("utf8")),l=new be,p=this.unattributed.size,u=new Map;for(let g=0;g<p;g++){let h=f(g);if(h)for(let y of h.ids){let R=rt(y);l.has(R)||i.find(R,se(R),ie(R))>=0||(l.add(R),(!e||e.has(R))&&u.set(h.object,(u.get(h.object)??0)+1))}}for(let[g,h]of u){let y=d.find(R=>R.objectApiName===g);y?y.count+=h:d.unshift({objectApiName:g,count:h})}let m=g=>l.size>0&&l.has(g)&&(!e||e.has(g));return{objects:d,pages:async function*(g){let h=a.get(g),y=[];if(h)for(let R=h.size-1;R>=0;R--){let S=h.offsetAt(R),w=o(S,h.lengthAt(R));if(!w||w.object==="")continue;let b=rt(w.targetId);c(b,S)&&(y.push(w.targetId),y.length>=t&&(yield y,y=[]))}if(u.has(g)){let R=new be;for(let S=0;S<p;S++){let w=f(S);if(w?.object===g)for(let b of w.ids){let A=rt(b);R.has(A)||!m(A)||i.find(A,se(A),ie(A))>=0||(R.add(A),y.push(b),y.length>=t&&(yield y,y=[]))}}}y.length>0&&(yield y)},has:g=>c(g)||m(g)}}*idMapRows(){let e=new Map;for(let[r,o]of this.createdByObject())for(let s=0;s<o.size;s++){let i=this.mappingAt(o.offsetAt(s),o.lengthAt(s));i&&e.set(i.sourceId.slice(0,3),r)}let t=new Uint8Array(Math.ceil(this.all.slots/8));for(let r of we(this.file)){let o=nt(r.text);if(!o)continue;let s=this.all.find(o.sourceId,se(o.sourceId),ie(o.sourceId));if(s<0||(t[s>>3]&1<<(s&7))!==0)continue;t[s>>3]|=1<<(s&7);let i=this.wordsOn(o.sourceId);if(!i.latest)continue;let a=this.mappingAt(i.latest.offset,i.latest.length);if(!a||a.object==="")continue;yield{objectApiName:(i.createdByThePart&&i.inThePart?this.mappingAt(i.inThePart.offset,i.inThePart.length):void 0)?.object??e.get(a.sourceId.slice(0,3)),sourceId:a.sourceId,targetId:a.targetId,outcome:i.createdByThePart?"created":"linked to existing"}}}};var Ie=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,it=/^[A-Za-z][A-Za-z0-9_]*$/,Ga=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/,Ja=255,Ha=40,Ka=2*6e4,Ya=10*6e4;function Xf(n){let[e]=n;return e?Object.keys(e).filter(t=>t!=="Id"&&it.test(t)).filter(t=>n.every(r=>Za(r[t]))).sort().slice(0,Ha):[]}function Za(n){return typeof n=="string"?n.trim()!==""&&n.length<=Ja:typeof n=="number"?Number.isFinite(n):typeof n=="boolean"}function Qa(n){if(typeof n=="boolean")return n?"true":"false";if(typeof n=="number")return Number.isFinite(n)?String(n):"";if(typeof n!="string")return"";let e=n.trim();if(Ie.test(e))return e.slice(0,15);if(Ga.test(e)){let r=Date.parse(e);if(Number.isFinite(r))return new Date(r).toISOString()}if(e!==""&&Number.isFinite(Number(e)))return String(Number(e));let t=e.replace(/\s+/g," ").toLowerCase();return t.includes(";")?t.split(";").map(r=>r.trim()).sort().join(";"):t}function Fn(n,e){return Pn(e.map(t=>`${t}${Qa(n[t])}`).join(""))}function Pn(n){return se(n).toString(36).padStart(7,"0")+ie(n).toString(36).padStart(7,"0")}function ep(n){let e=So("insert",n);return e.rows.map(t=>Pn(hn(e.columns.map((r,o)=>[r,t[o]??""]))))}var Xa=/^sf__/;function _s(n){let e=[];for(let[t,r]of Object.entries(n))Xa.test(t)||e.push([t,typeof r=="string"?r:r==null?"":String(r)]);return Pn(hn(e))}function Bs(n,e){return Fn(n,[e])}function ed(n,e){if(!Array.isArray(n))return!1;for(let t of n){if(!Array.isArray(t)||t.length<4)return!1;let[r,o,s,i]=t;if(typeof r!="number"||!Number.isInteger(r)||!e[r]||typeof o!="string"||!it.test(o)||typeof s!="string"||!Ie.test(s))return!1;e[r].owes.push({field:o,sourceRefId:s,...i===1?{insertOnly:!0}:{}})}return!0}function Tn(n){if(!n.startsWith(`["${At}"`))return;let e;try{e=JSON.parse(n)}catch{return}if(!Array.isArray(e)||e.length<6)return;let[,t,r,o,s,i,a,d]=e;if(typeof t!="string"||typeof r!="string"||!it.test(r)||typeof o!="string")return;let c=Date.parse(o);if(!Number.isFinite(c)||!Array.isArray(s)||!Array.isArray(i)||!s.every(p=>typeof p=="string"&&it.test(p))||d!==void 0&&(typeof d!="string"||!it.test(d)))return;let f=[];for(let p of i){if(!Array.isArray(p)||p.length<2)return;let[u,m,g,h]=p;if(typeof u!="string"||!Ie.test(u)||typeof m!="string"||g!==void 0&&typeof g!="string"||h!==void 0&&typeof h!="string")return;f.push({sourceId:u,fingerprint:m,owes:[],...typeof g=="string"&&g!==""?{externalKey:g}:{},...typeof h=="string"&&h!==""?{jobKey:h}:{}})}let l=a!==void 0;if(!(l&&!ed(a,f)))return{callId:t,objectApiName:r,at:c,fields:s,rows:f,owesKept:l,...typeof d=="string"?{upsertField:d}:{}}}function $s(n){if(n.startsWith(`["${Ee}"`))try{let e=JSON.parse(n);return Array.isArray(e)&&typeof e[1]=="string"?e[1]:void 0}catch{return}}function td(n){if(n.startsWith(`["${Wo}"`))try{let e=JSON.parse(n);return Array.isArray(e)&&typeof e[1]=="string"?e[1]:void 0}catch{return}}function nd(n){if(n.startsWith(`["${$o}"`))try{let e=JSON.parse(n);if(!Array.isArray(e))return;let[,t,r]=e;return typeof t!="string"||typeof r!="string"||r===""?void 0:{callId:t,jobId:r}}catch{return}}function rd(n){if(!(!n.startsWith('["c"')&&!n.startsWith('["e"')&&!n.startsWith('["u"')))try{let e=JSON.parse(n);if(!Array.isArray(e))return;let[,t,r,o]=e;return typeof t!="string"||typeof r!="string"||!Ie.test(t)||!Ie.test(r)?void 0:{sourceId:t,targetId:r,object:typeof o=="string"?o:""}}catch{return}}function od(n){let e=/"(?:startedAt|at)":"([^"]{10,40})"/.exec(n);return e?Date.parse(e[1]):Number.NaN}function tp(n,e={}){return{queryPages:t=>lo({query:async r=>n.query(r),queryMore:async r=>n.queryMore(r)},t),userId:async()=>(await n.identity()).user_id,serverTime:async()=>(await n.soap.getServerTimestamp()).timestamp,readJob:t=>Oo(Ao(n),t,e.leaveOpen?{leaveOpen:!0}:{})}}function sd(){return{calls:0,found:[],notFound:[],uncertain:[],unread:[]}}function K(n,e,t=1){if(t<=0)return;let r=n.find(o=>o.objectApiName===e);r?r.rows+=t:n.push({objectApiName:e,rows:t})}function Ds(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function vn(n,e,t){return[JSON.stringify(["c",e.sourceId,t,n.objectApiName,n.owesKept?zo:Uo]),...e.owes.map(({field:r,sourceRefId:o,insertOnly:s})=>Jo({objectApiName:n.objectApiName,newId:t,sourceId:e.sourceId,fieldName:r,sourceRefId:o,...s?{insertOnly:s}:{}}))]}function id(n,e,t,r){let{call:o,rows:s,read:i}=n,{objectApiName:a}=o,d=JSON.stringify([Ee,o.callId]);if(i.state==="never-closed")return K(r.notFound,a,s.length),{lines:[d],taken:[]};if(i.state==="running")return K(r.uncertain,a,s.length),(r.underway??=[]).push({objectApiName:a,jobId:n.jobId,rows:s.length,...i.info?{state:i.info.state}:{},...i.info?.numberRecordsProcessed!==void 0?{processed:i.info.numberRecordsProcessed}:{},...i.openUntil?{openUntil:i.openUntil}:{},...i.graceLeftMs!==void 0?{graceLeftMs:i.graceLeftMs}:{}}),{lines:[],taken:[]};if(i.state==="unread")return r.unread.push({objectApiName:a,reason:i.reason}),K(r.uncertain,a,s.length),{lines:[],taken:[]};let c=o.upsertField===void 0&&s.every(l=>l.jobKey!==void 0)?ad(o,s,i.results,e,t,r):dd(o,s,i.results,e,t,r),f=Date.parse(i.info.systemModstamp??"");return!n.endKept&&c.taken.length>0&&Number.isFinite(f)&&c.lines.unshift(Vo(o.callId,n.jobId,new Date(f).toISOString(),new Date(f-n.ahead).toISOString())),c}function ad(n,e,t,r,o,s){let{objectApiName:i}=n,a=new Map,d=new Set;for(let S of t.successfulResults??[]){let w=S.sf__Id,b=_s(S);if(typeof w!="string"||!Ie.test(w)){d.add(b);continue}let A=w.slice(0,15);r.has(A)&&!o.has(A)||a.set(b,[...a.get(b)??[],w])}let c=new Set,f=t.unprocessedRecords;for(let S of[...t.failedResults??[],...Array.isArray(f)?f:[]])c.add(_s(S));let l=new Map;for(let S of e){let w=S.jobKey??"";l.set(w,[...l.get(w)??[],S])}let p=[],u=[],m=[],g=0,h=!1,y=0;for(let[S,w]of l){let b=a.get(S)??[];a.delete(S);let A=d.delete(S);if(w.length===1&&b.length===1&&!A){p.push(...vn(n,w[0],b[0])),u.push(b[0]),K(s.found,i);continue}if(b.length>0||A){K(s.uncertain,i,w.length),w.length>1&&K(s.untold??=[],i,w.length),A||(y+=w.length),m.push(...b),h=!0;continue}if(w.length>1||c.has(S)){K(s.notFound,i,w.length);continue}g+=w.length}let R=d.size>0;for(let S of a.values())m.push(...S),S.length>0&&(R=!0);return g>0&&(K(R?s.uncertain:s.notFound,i,g),R&&(h=!0,d.size===0&&(y+=g))),y>0&&K(s.ofEndedJobs??=[],i,y),p.push(...Ws(n,m,o,h,s)),{lines:p,taken:[...u,...m]}}function Ws(n,e,t,r,o){e.length>0&&K(o.unattributed??=[],n.objectApiName,e.length);let s=e.filter(i=>!t.has(i.slice(0,15)));return[...s.length>0?[JSON.stringify([kt,n.objectApiName,s])]:[],...r?[]:[JSON.stringify([Ee,n.callId])]]}function dd(n,e,t,r,o,s){let{objectApiName:i}=n,a=n.upsertField,d=new Map;for(let h of t.successfulResults??[]){let y=h.sf__Id;if(typeof y!="string"||!Ie.test(y))continue;let R=y.slice(0,15);if(r.has(R)&&!o.has(R)||a!==void 0&&String(h.sf__Created).toLowerCase()!=="true")continue;let S=a!==void 0?Bs(h,a):Fn(h,n.fields);d.set(S,[...d.get(S)??[],y])}let c=new Map;for(let h of e){let y=a!==void 0?h.externalKey??"":h.fingerprint;c.set(y,[...c.get(y)??[],h])}let f=[],l=[],p=[],u=0,m=!1;for(let[h,y]of c){let R=h===""?[]:d.get(h)??[];if(d.delete(h),R.length===0){u+=y.length;continue}if(y.length===1&&R.length===1){f.push(...vn(n,y[0],R[0])),l.push(R[0]),K(s.found,i);continue}K(s.uncertain,i,y.length),K(s.ofEndedJobs??=[],i,y.length),y.length>1&&K(s.untold??=[],i,y.length),p.push(...R),m=!0}let g=!1;for(let h of d.values())p.push(...h),h.length>0&&(g=!0);return u>0&&(K(g?s.uncertain:s.notFound,i,u),g&&(m=!0,K(s.ofEndedJobs??=[],i,u))),f.push(...Ws(n,p,o,m,s)),{lines:f,taken:[...l,...p]}}function qs(n){let e=new Set;for(let t of we(n)){let r=$s(t.text);if(r!==void 0)e.delete(r);else{let o=t.text.startsWith(`["${At}"`)?Tn(t.text):void 0;o&&e.add(o.callId)}}return e.size}async function Us(n,e,t=()=>new Date,r={}){let o=sd(),s=new Map,i=new Map,a=new Set,d=Number.NEGATIVE_INFINITY;for(let b of we(n)){let A=$s(b.text);if(A!==void 0){s.delete(A);continue}let j=nd(b.text);if(j){i.set(j.callId,j.jobId);continue}let L=td(b.text);if(L!==void 0){a.add(L);continue}if(b.text.startsWith(`["${At}"`)){let v=Tn(b.text);v&&(s.set(v.callId,{offset:b.offset,length:b.length}),d=Math.max(d,v.at));continue}if(b.text.startsWith("{")){let v=od(b.text);Number.isFinite(v)&&(d=Math.max(d,v))}}if(s.size===0)return o;let c=[];for(let{offset:b,length:A}of s.values()){let j=Tn(n.read(b,A).toString("utf8"));j&&c.push(j)}o.calls=c.length;let f=new Set(c.map(b=>b.objectApiName)),l=new Set(c.flatMap(b=>b.rows.map(A=>A.sourceId)));o.lookedFor=l;let p=new Set,u=new be,m=new be;for(let b of we(n)){let A=_e(b.text);if(A){if(f.has(A.object))for(let L of A.ids)u.add(L.slice(0,15)),m.add(L.slice(0,15));continue}let j=rd(b.text);j&&(l.has(j.sourceId)&&p.add(j.sourceId),(j.object===""||f.has(j.object))&&u.add(j.targetId.slice(0,15)))}let g=0;if(e.serverTime)try{let b=t().getTime(),A=Date.parse(await e.serverTime());Number.isFinite(A)&&(g=A-(b+t().getTime())/2)}catch{}let h,y,R=[],S=e.readJob?.bind(e),w=new Set;if(S)for(let b of c){let A=i.get(b.callId);if(A===void 0)continue;w.add(b.callId);let j=b.rows.filter(v=>!p.has(v.sourceId));if(j.length===0){R.push(JSON.stringify([Ee,b.callId]));continue}let L=id({call:b,rows:j,jobId:A,read:await S(A),ahead:g,endKept:a.has(b.callId)},u,m,o);R.push(...L.lines);for(let v of L.taken)u.add(v.slice(0,15))}for(let b of f){let A=c.filter(O=>O.objectApiName===b&&!w.has(O.callId));if(A.length===0)continue;let j=A.map(O=>({call:O,rows:O.rows.filter(C=>!p.has(C.sourceId))})),L=j.reduce((O,{rows:C})=>O+C.length,0);if(L===0){for(let{call:O}of j)R.push(JSON.stringify([Ee,O.callId]));continue}let v=new Map;for(let O of A)v.set(O.fields.join(","),O.fields);let P=[...new Set(A.flatMap(O=>O.upsertField?[O.upsertField]:[]))],k=[...new Set([...A.flatMap(O=>O.fields),...P])].sort(),N;try{if(h===void 0&&y===void 0)try{h=await e.userId()}catch(x){y=H(x)}if(h===void 0)throw new Error(`the user the run writes as is not known: ${y}`);let O=Math.min(...A.map(x=>x.at))+g-Ka,C=d+g+Ya,B=k.includes("CreatedDate")?"SystemModstamp":"CreatedDate",F=k.includes("CreatedById")?"":`CreatedById = '${h}' AND `,_=`SELECT ${["Id",...k.filter(x=>x!=="Id")].join(", ")} FROM ${J(b)} WHERE ${F}${B} >= ${Ds(O)} AND ${B} <= ${Ds(C)} ORDER BY Id`;N=[];for await(let x of e.queryPages(_))for(let $ of x){let q=$.Id;if(typeof q!="string"||!Ie.test(q)||u.has(q.slice(0,15)))continue;let Q=new Map;for(let[je,he]of v)Q.set(je,Fn($,he));let Re=new Map;for(let je of P)Re.set(je,Bs($,je));N.push({id:q,fingerprints:Q,externalKeys:Re,taken:!1})}}catch(O){o.unread.push({objectApiName:b,reason:H(O)}),K(o.uncertain,b,L);continue}N.sort((O,C)=>O.id<C.id?-1:O.id>C.id?1:0);let M=new Map;for(let O of v.keys()){let C=new Map;for(let B of N){let F=B.fingerprints.get(O)??"",_=C.get(F)??[];_.push(B),C.set(F,_)}M.set(O,C)}let D=(O,C,B)=>{B.taken=!0,R.push(...vn(O,C,B.id)),K(o.found,b)},E=new Set;for(let{call:O,rows:C}of j){let B=O.upsertField;if(B===void 0)continue;let F=new Map;for(let x of N){let $=x.externalKeys.get(B);x.taken||$===void 0||F.set($,[...F.get($)??[],x])}let _=new Map;for(let x of C){let $=x.externalKey??"";_.set($,[..._.get($)??[],x])}for(let[x,$]of _){let q=x===""?[]:F.get(x)??[];if(x===""||$.length>1||q.length>1){K(o.uncertain,b,$.length),E.add(O.callId);continue}q.length===1?D(O,$[0],q[0]):K(o.notFound,b)}}let T=[];for(let{call:O,rows:C}of j){if(O.upsertField!==void 0)continue;let B=O.fields.join(","),F=new Map;for(let _ of C){let x=F.get(_.fingerprint)??[];x.push(_),F.set(_.fingerprint,x)}for(let[_,x]of F){let $=(M.get(B)?.get(_)??[]).filter(q=>!q.taken);if($.length>x.length){for(let q of x)T.push({callId:O.callId,sourceId:q.sourceId});E.add(O.callId);continue}$.forEach((q,Q)=>D(O,x[Q],q));for(let q of x.slice($.length))T.push({callId:O.callId,sourceId:q.sourceId})}}let I=N.some(O=>!O.taken);for(let O of T)I||E.has(O.callId)?(K(o.uncertain,b),E.add(O.callId)):K(o.notFound,b);for(let{call:O}of j)E.has(O.callId)||R.push(JSON.stringify([Ee,O.callId]))}return R.length>0&&r.keep!==!1&&n.append(`${R.join(`
|
|
11
|
-
`)}
|
|
12
|
-
`),o}function np(n,e,t="resume"){if(n.calls===0)return[];let r=i=>i.map(({objectApiName:a,rows:d})=>`${d} ${a}`).join(", "),o={resume:"kept as written by the run and not written again",removal:"kept as written by the run and removed with its records",preview:"which a removal keeps as written by the run and removes with its records, not counted here"}[t],s=[`${n.calls} insert or upsert call(s) were under way when the run stopped, their answer never kept: their rows were looked for in ${e}`+(t==="preview"?", as a removal looks for them first":"")];n.found.length>0&&s.push(` found in ${e}, ${o}: ${r(n.found)}`),n.notFound.length>0&&s.push(t==="resume"?` not in ${e}, written by the resume: ${r(n.notFound)}`:` not in ${e}, nothing of them to remove: ${r(n.notFound)}`),n.uncertain.length>0&&s.push(` may already be in ${e}: ${r(n.uncertain)}`);for(let i of n.underway??[])s.push(` ${ud(i,t==="resume"?"resume":"removal")}`);for(let{objectApiName:i,rows:a}of n.untold??[])s.push(` ${i}: ${a} row(s) the journal cannot tell apart, several under one fingerprint, under which the Bulk API job wrote records: none of those records is linked to a row`);(n.unattributed??[]).length>0&&s.push(` written by a Bulk API job and matched to no row, ${t==="resume"?"kept as written by the run":o}: `+r(n.unattributed??[]));for(let{objectApiName:i,reason:a}of n.unread)s.push(` ${i} could not be read in ${e}: ${a}`);return s}function cd(n){return Math.max(1,Math.ceil(n/6e4))}function ud(n,e){let t=`${n.objectApiName}: Bulk API job ${n.jobId} is ${n.state??"not ended"}`+(n.processed!==void 0?`, ${n.processed} row(s) processed`:"");if(n.state==="Open"){let r=n.openUntil!==void 0?` from ${n.openUntil}`+(n.graceLeftMs!==void 0&&n.graceLeftMs>0?`, in about ${cd(n.graceLeftMs)} minute(s),`:""):" an hour after it was opened";return`${t}: the run stopped before it closed it, and closed, it would still write them; ${e==="resume"?"a resume":"a removal"}${r} aborts it if it is open still`+(e==="resume"?", then writes its rows":"")}return`${t}: the org writes it to its end whatever became of the run; `+(e==="resume"?"a resume once it has ended reads what it wrote":"a removal once it has ended takes what it wrote")}function ld(n){return n.uncertain.reduce((e,{rows:t})=>e+t,0)}function rp(n){let e=(n.ofEndedJobs??[]).reduce((t,{rows:r})=>t+r,0);return Math.max(0,ld(n)-e)}import{createReadStream as fd}from"node:fs";import{appendFile as pd,chmod as md,mkdir as gd,readdir as hd,rename as wd,rm as zs}from"node:fs/promises";import*as ae from"node:path";import{createInterface as yd}from"node:readline";var bd=10*6e4,Vs=448;function mp(n){return new Ln({storagePath:n,appendFile:(e,t)=>pd(e,t,{encoding:"utf8",mode:_o}),readLines:e=>Rd(e),mkdir:async e=>{await gd(e,{recursive:!0,mode:Vs}),process.platform!=="win32"&&await md(e,Vs).catch(t=>{if(t.code!=="EPERM")throw t})},rm:e=>zs(e,{force:!0}),rename:(e,t)=>wd(e,t),listFiles:e=>hd(e).catch(t=>{if(t.code==="ENOENT")return[];throw t}),openRunFile:e=>Do(e),rmDir:e=>zs(e,{recursive:!0,force:!0})})}async function*Rd(n){let e=fd(n,{encoding:"utf8"}),t=yd({input:e,crlfDelay:1/0});try{for await(let r of t)yield r}catch(r){if(r.code!=="ENOENT")throw r}finally{t.close(),e.destroy()}}var gp=5e4,hp=2e3,ee=W().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),xt=W().regex(/^[A-Za-z][A-Za-z0-9_]*$/),Sd=V({sourceOrgId:W().min(1).max(128),fingerprint:W().regex(/^[a-f0-9]{64}$/),targetSalesforceOrgId:ee.optional(),recordId:ee.optional(),muteAutomation:Ye(!0).optional(),files:vr.optional()}),Od=V({graph:Fr,config:Tr,anonymizationRules:Pr.optional()});function Gs(n){let e=Sd.safeParse(n);if(!e.success)return;let t=Od.safeParse(n.startedWith);return{...e.data,...t.success?{startedWith:t.data}:{}}}var Pt=V({run:V({journalId:W().min(1).max(200),targetOrgId:W().min(1).max(128),startedAt:W().min(1).max(40),resume:Ne().optional(),runUserId:Ne().optional()})}),Js=V({objectApiName:W().regex(/^[A-Za-z][A-Za-z0-9_]*$/),reason:W().max(2e3),...Cr}),Hs=V({checkpoint:V({state:Ye("taken"),checkpointId:W().min(1).max(200),name:W().max(500),takenAt:W().min(1).max(40),expiresAt:W().min(1).max(40).nullable(),objects:Z(W().regex(/^[A-Za-z][A-Za-z0-9_]*$/)),records:te().nonnegative(),bytes:te().nonnegative(),requests:te().nonnegative(),added:Z(Js),notHeld:Z(Js)})}),Ad=V({part:V({n:te().int().nonnegative(),startedAt:W().max(40).optional()})}),Cn=V({end:V({status:ve(["success","cancelled","failure","interrupted"]),forgeId:W().min(1).max(200),at:W().max(40).optional()})}),kd=V({object:xt,created:Z(Er([ee,ee]))});function xn(n){return ee.safeParse(n).success?n:void 0}function De(n){return n.replace(/\.ndjson$/,"")+".end.json"}function vt(n){return n.replace(/\.ndjson$/,"")+".checkpoint.json"}function Ct(n,e){return`${n.replace(/\.ndjson$/,"")}.part${e}.left`}function Ks(n,e){return`${n.replace(/\.ndjson$/,"")}.part${e}.stamps`}var Id=W().max(40).refine(n=>Number.isFinite(Date.parse(n)),"not a date"),Be=1e4;function jd(n,e){let t=n.map(s=>({...s,ids:[...s.ids]}));if(!e||e.length===0)return t;let r=new Set(n.flatMap(({ids:s})=>s.map(i=>i.slice(0,15)))),o=[];for(let{objectApiName:s,ids:i}of e){let a=i.filter(c=>!r.has(c.slice(0,15)));for(let c of a)r.add(c.slice(0,15));if(a.length===0)continue;let d=t.find(c=>c.objectApiName===s);d?d.ids.push(...a):o.push({objectApiName:s,ids:a})}return[...o,...t]}function Mn(n){return n.replace(/[^A-Za-z0-9_-]/g,"_")}var Ln=class{constructor(e){this.deps=e;this.dir=ae.join(e.storagePath,"forge-runs")}deps;dir;get storagePath(){return this.deps.storagePath}pathOf(e){return ae.join(this.dir,`${Mn(e)}.ndjson`)}filePath(e){return this.pathOf(e)}async begin(e,t,r,o,s){await this.deps.mkdir(this.dir);let i=xn(s),a={run:{journalId:e,targetOrgId:t,startedAt:r.toISOString(),...o?{resume:o}:{},...i?{runUserId:i}:{}}};await this.deps.appendFile(this.filePath(e),`${JSON.stringify(a)}
|
|
13
|
-
`)}async keepCheckpoint(e,t){let r=Hs.safeParse({checkpoint:t});if(!r.success)return;let o=vt(this.filePath(e));await this.deps.rm(o),await this.deps.appendFile(o,`${JSON.stringify(r.data)}
|
|
14
|
-
`)}async checkpointAt(e){for await(let t of this.deps.readLines(vt(e)))if(t.trim()!=="")try{let r=Hs.safeParse(JSON.parse(t));return r.success?r.data.checkpoint:void 0}catch{return}}open(e){return this.openAt(this.filePath(e))}openAt(e){return Ho.open(this.deps.openRunFile(e))}reconcile(e,t){return this.reconcileAt(this.filePath(e),t)}async reconcileAt(e,t,r={}){let o=this.deps.openRunFile(e);try{return await Us(o,t,void 0,r)}finally{o.close()}}writeBoundsAt(e,t){let r=this.deps.openRunFile(e);try{let o,s,i,a,d=-1,c,f,l=Number.NEGATIVE_INFINITY,p=Number.NEGATIVE_INFINITY,u=Number.NEGATIVE_INFINITY,m=new Map;for(let h of we(r)){let y=/"(?:startedAt|at)":"([^"]{10,40})"/.exec(h.text)?.[1],R=h.text.startsWith('["x"')?/^\["x","[^"]*","[^"]*","([^"]+)"/.exec(h.text)?.[1]:void 0,S=Go(h.text);for(let v of[y,R,S?.at]){let P=v===void 0?Number.NaN:Date.parse(v);Number.isFinite(P)&&(l=Math.max(l,P))}if(S){let v=Date.parse(S.orgAt);Number.isFinite(v)&&(p=Math.max(p,v),d===t&&(u=Math.max(u,v)));continue}if(h.text.startsWith('{"part":')&&d++,!h.text.startsWith('["c"')&&!h.text.startsWith('["p"')&&!h.text.startsWith('["g"'))continue;let w;try{w=JSON.parse(h.text)}catch{continue}if(!Array.isArray(w))continue;let[b,A,j,L]=w;if(b==="c"){if(!ee.safeParse(j).success||!xt.safeParse(L).success)continue;let v={objectApiName:String(L),id:String(j)};o??=v,s=v,d===t&&(i??=v,a=v),m.set(String(j).slice(0,3),String(L))}else if(b==="g"){if(!ee.safeParse(j).success||!xt.safeParse(A).success)continue;c={objectApiName:String(A),id:String(j)},f=void 0}else ee.safeParse(A).success&&(f=String(A))}let g=f?m.get(f.slice(0,3)):void 0;return f&&g&&(c={objectApiName:g,id:f}),{...o?{first:o}:{},...s?{lastCreated:s}:{},...i?{firstInPart:i}:{},...a?{lastCreatedInPart:a}:{},...c?{lastUpdated:c}:{},...Number.isFinite(l)?{lastAt:new Date(l).toISOString()}:{},...Number.isFinite(p)?{jobEnded:new Date(p).toISOString()}:{},...Number.isFinite(u)?{jobEndedInPart:new Date(u).toISOString()}:{}}}finally{r.close()}}writtenBetween(e,t,r,o="run"){return this.writtenBetweenAt(this.filePath(e),t,r,o)}async writtenBetweenAt(e,t,r,o="run"){let s=this.writeBoundsAt(e,r),{firstInPart:i,lastCreatedInPart:a,lastAt:d}=s,[c,f,l]=o==="part"?[i,a,void 0]:[s.first,s.lastCreated,s.lastUpdated];if(!c||!f)return;let p=async({objectApiName:S,id:w},b)=>{try{let j=(await t.query(`SELECT ${b} FROM ${J(S)} WHERE Id = '${w}'`)).records[0]?.[b],L=typeof j=="string"?Date.parse(j):Number.NaN;return Number.isFinite(L)?L:void 0}catch{return}},u=d===void 0?Number.NaN:Date.parse(d)+bd,m=await p(c,"CreatedDate")??(i&&i.id!==c.id?await p(i,"CreatedDate"):void 0),g=[],h=a?.id!==f.id?a:void 0;for(let S of[f,h]){let w=S?await p(S,"CreatedDate"):void 0;if(S&&w!==void 0&&m!==void 0&&w<m){let b=await p(S,"SystemModstamp");w=b!==void 0&&b>=m&&(!Number.isFinite(u)||b<=u)?b:void 0}w!==void 0&&g.push(w)}let y=g.length>0?Math.max(...g):void 0;if(m===void 0||y===void 0||y<m)return;if(l){let S=await p(l,"LastModifiedDate");S!==void 0&&S>y&&(!Number.isFinite(u)||S<=u)&&(y=S)}let R=Date.parse((o==="part"?s.jobEndedInPart:s.jobEnded)??"");return Number.isFinite(R)&&R>y&&(y=R),{first:new Date(m).toISOString(),last:new Date(y).toISOString()}}callsInFlight(e){return this.callsInFlightAt(this.filePath(e))}callsInFlightAt(e){let t=this.deps.openRunFile(e);try{return qs(t)}finally{t.close()}}stop(e,t,r){return this.stopAt(this.filePath(e),t,r)}async stopAt(e,t,r){let o=`${JSON.stringify({end:{status:t,forgeId:r,at:new Date().toISOString()}})}
|
|
15
|
-
`;await this.deps.appendFile(e,o),await this.deps.rm(De(e)),await this.deps.appendFile(De(e),o)}resuming(e){return this.resumingAt(this.filePath(e))}resumingAt(e){return this.deps.rm(De(e))}lastEnd(e){return this.lastEndAt(this.filePath(e))}async lastEndAt(e){for await(let t of this.deps.readLines(De(e)))if(t.trim()!=="")try{let r=Cn.safeParse(JSON.parse(t));return r.success?r.data.end:void 0}catch{return}}async partsOf(e){let t=new Set,r;for await(let o of this.deps.readLines(this.filePath(e)))if(o.trim()!==""){if(!r){try{let s=Pt.safeParse(JSON.parse(o));if(!s.success||s.data.run.journalId!==e)return[];r=s.data.run}catch{return[]}continue}if(o.startsWith('{"end":'))try{let s=Cn.safeParse(JSON.parse(o));s.success&&t.add(s.data.end.forgeId)}catch{}}return[...t]}async wroteIn(e,t){let r=new Set,o=!1,s=-1;for await(let i of this.deps.readLines(this.filePath(e)))if(i.trim()!==""){if(!o){try{let a=Pt.safeParse(JSON.parse(i));if(!a.success||a.data.run.journalId!==e)return[]}catch{return[]}o=!0;continue}if(i.startsWith('{"part":')){if(s++,s>t)break;continue}if(!(s!==t||!(i.startsWith('["p"')||i.startsWith('["g"'))))try{let a=JSON.parse(i);if(!Array.isArray(a))continue;let d=a[0]==="p"?a[1]:a[2];ee.safeParse(d).success&&r.add(String(d))}catch{}}return[...r]}async end(e){let t=this.filePath(e);await this.deps.rm(t),await this.deps.rm(De(t)),await this.deps.rm(vt(t));let r=`${ae.basename(t).replace(/\.ndjson$/,"")}.part`;for(let o of await this.deps.listFiles(this.dir))o.startsWith(r)&&(o.endsWith(".left")||o.endsWith(".stamps"))&&await this.deps.rm(ae.join(this.dir,o));await this.deps.rmDir?.(Os(this.deps.storagePath,e))}fileNameOf(e){return`${Mn(e)}.ndjson`}async present(e){let t=new Set(await this.deps.listFiles(this.dir));return new Set(e.filter(r=>t.has(this.fileNameOf(r))))}async endedFiles(){let e=await this.deps.listFiles(this.dir),t=new Set(e.filter(r=>r.endsWith(".end.json")));return e.filter(r=>r.endsWith(".ndjson")&&t.has(r.replace(/\.ndjson$/,".end.json")))}async forgetFile(e){let t=ae.join(this.dir,e),r=await this.headAt(t);r?await this.end(r.journalId):(await this.deps.rm(t),await this.deps.rm(De(t)),await this.deps.rm(vt(t)))}async idsOf(e,t){let r=this.filePath(e),o=await this.readAt(r,"all");if(o?.journalId!==e)return;let s=await this.readAt(r,t);if(!s)return;let i=new Set(s.remap.createdByObject.flatMap(({sourceIds:a})=>a));return{table:o.remap.table,createdByObject:s.remap.createdByObject,existing:Object.keys(o.remap.table).filter(a=>!i.has(a)),...s.remap.withTheirRecord?{withTheirRecord:s.remap.withTheirRecord}:{}}}async keepLeft(e,t,r){let o=Ct(this.filePath(e),t);await this.deps.rm(o);for(let s=0;s<r.length;s+=Be)await this.deps.appendFile(o,`${r.slice(s,s+Be).join(`
|
|
16
|
-
`)}
|
|
17
|
-
`);r.length===0&&await this.deps.appendFile(o,"")}async recordsOf(e,t,r=!1){if(!await this.head(e))return;let o=r?void 0:await this.leftKeysOf(e,t),s=this.deps.openRunFile(this.filePath(e)),i=st.read(s,t);if(!i){s.close();return}return{records:i.runRecords(o),close:()=>s.close()}}async idMapRowsOf(e,t){if(!await this.head(e))return;let r=this.deps.openRunFile(this.filePath(e)),o=st.read(r,t);if(!o){r.close();return}return{rows:o.idMapRows(),close:()=>r.close()}}async leftKeysOf(e,t){let r=Ct(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(ae.basename(r)))return;let s=new be;for await(let i of this.deps.readLines(r)){let a=i.trim();ee.safeParse(a).success&&s.add(a.slice(0,15))}return s}async keepLeftPages(e,t,r){let o=Ct(this.filePath(e),t),s=this.deps.rename,i=s?`${o}.next`:o;await this.deps.rm(i),await this.deps.appendFile(i,"");let a=new Map;for await(let{objectApiName:d,ids:c}of r)if(c.length!==0){a.set(d,(a.get(d)??0)+c.length);for(let f=0;f<c.length;f+=Be)await this.deps.appendFile(i,`${c.slice(f,f+Be).join(`
|
|
18
|
-
`)}
|
|
19
|
-
`)}return s&&await s(i,o),[...a].map(([d,c])=>({objectApiName:d,count:c}))}async stampsOf(e,t){let r=Ks(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(ae.basename(r)))return{};let s={};for await(let i of this.deps.readLines(r)){let[a,d]=i.trim().split(" ");ee.safeParse(a).success&&Id.safeParse(d).success&&(s[a]=d)}return s}async keepStamps(e,t,r){if(Object.keys(r).length===0)return;let o=Ks(this.filePath(e),t),s=Object.entries({...await this.stampsOf(e,t),...r}),i=this.deps.rename,a=i?`${o}.next`:o;await this.deps.rm(a);for(let d=0;d<s.length;d+=Be){let c=s.slice(d,d+Be).map(([f,l])=>`${f} ${l}`);await this.deps.appendFile(a,`${c.join(`
|
|
20
|
-
`)}
|
|
21
|
-
`)}i&&await i(a,o)}async leftOf(e,t){let r=Ct(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(ae.basename(r)))return;let s=[];for await(let i of this.deps.readLines(r)){let a=i.trim();ee.safeParse(a).success&&s.push(a)}return s}async head(e){let t=await this.headAt(this.filePath(e));return t?.journalId===e?t:void 0}async headAt(e){for await(let t of this.deps.readLines(e)){if(t.trim()==="")continue;let r;try{r=JSON.parse(t)}catch{return}let o=Pt.safeParse(r);if(!o.success)return;let{resume:s,runUserId:i,...a}=o.data.run,d=Gs(s),c=xn(i);return{...a,...d?{resume:d}:{},...c?{runUserId:c}:{}}}}async read(e){let t=await this.deps.listFiles(this.dir),r=`${Mn(e)}.ndjson`;if(!t.includes(r))return;let o=await this.readAt(ae.join(this.dir,r));return o?.journalId===e?o:void 0}readAt(e,t="last"){return this.readFile(e,t)}async leftOver(e=new Set){let t=[],r=await this.deps.listFiles(this.dir),o=new Set(r.filter(s=>s.endsWith(".end.json")));for(let s of r){if(!s.endsWith(".ndjson")||o.has(s.replace(/\.ndjson$/,".end.json")))continue;let i=await this.readFile(ae.join(this.dir,s),"last");!i||e.has(i.journalId)||i.lastEnd||t.push(i)}return t}static planOf(e,t=e.journalId){let r=jd(e.created,e.unattributed);if(r.length!==0)return{forgeId:t,targetOrgId:e.targetOrgId,timestamp:e.startedAt,duration:0,status:"partial",objects:r,linked:0}}forget(e){return this.end(e)}async readFile(e,t){let r,o=0,s,i,a,d=new Map,c=new Map,f=new Set,l,p=()=>{o++,i=s,s=void 0,t==="last"&&(d=new Map,c=new Map,f=new Set)},u=()=>typeof t!="number"||o-1===t;for await(let j of this.deps.readLines(e)){if(j.trim()==="")continue;let L;try{L=JSON.parse(j)}catch{continue}if(!r){let N=Pt.safeParse(L);if(!N.success)return;r=N.data.run;continue}if(Array.isArray(L)){let N=_e(j);if(N){if(!u())continue;let I=c.get(N.object)??new Set;for(let O of N.ids)I.add(O);c.set(N.object,I);continue}let[M,D,E,T]=L;if(M===qo){u()&&ee.safeParse(D).success&&f.add(String(D));continue}if(M!=="c"&&M!=="e"&&M!=="u"||!u()||!ee.safeParse(D).success||!ee.safeParse(E).success)continue;d.set(String(D),{targetId:String(E),object:typeof T=="string"&&xt.safeParse(T).success?T:"",created:M==="c"});continue}if(typeof L=="object"&&L!==null&&"roots"in L){l=Bo(L.roots)??l;continue}let v=Ad.safeParse(L);if(v.success){p(),a=v.data.part.startedAt;continue}let P=Cn.safeParse(L);if(P.success){s=P.data.end;continue}let k=kd.safeParse(L);if(k.success){if(o===0&&p(),!u())continue;for(let[N,M]of k.data.created)d.set(N,{targetId:M,object:k.data.object,created:!0})}}if(!r)return;let m=Gs(r.resume),g=xn(r.runUserId),h=await this.checkpointAt(e),y={},R=new Map,S=[];for(let[j,{targetId:L,object:v,created:P}]of d){if(!v)continue;if(y[j]=L,!P){S.push(j);continue}let k=R.get(v)??[];k.push(j),R.set(v,k)}let w=[...R].map(([j,L])=>({objectApiName:j,sourceIds:L})),b=new Set([...d.values()].filter(({created:j})=>j).map(({targetId:j})=>j.slice(0,15))),A=[...c].map(([j,L])=>({objectApiName:j,ids:[...L].filter(v=>!b.has(v.slice(0,15)))})).filter(({ids:j})=>j.length>0);return{journalId:r.journalId,targetOrgId:r.targetOrgId,startedAt:r.startedAt,...m?{resume:m}:{},...g?{runUserId:g}:{},...h?{checkpoint:h}:{},...l?{roots:l}:{},parts:o,partStartedAt:a??r.startedAt,...s?{lastEnd:s}:{},...i?{endBefore:i}:{},created:_r({idRemapTable:y,idRemapExisting:S,idRemapCreated:w}),remap:{table:y,createdByObject:w,linked:S,...S.some(j=>f.has(j))?{withTheirRecord:S.filter(j=>f.has(j))}:{}},...A.length>0?{unattributed:A}:{}}}};import{randomBytes as Nd}from"node:crypto";import{chmod as Ed,open as Td,readFile as Fd,readdir as Pd,rename as vd,rm as Ys,stat as Cd}from"node:fs/promises";import{dirname as xd,join as Dn}from"node:path";var Md=1440*6e4,Ld="forge-roots",_d=/^[A-Za-z0-9_-]{1,128}$/,We=class extends Error{constructor(t,r){super(r);this.fault=t;this.name="RootPlanError"}fault},Dd=on({where:W().min(1).max(512).optional(),orderBy:W().min(1).max(200).optional(),limit:te().int().min(1).max(dn).optional()}),Zs=on({version:Ye(1),sourceOrgId:W().min(1).max(128),fingerprint:W().max(128),objectApiName:W().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),query:Dd.optional(),from:ve(["query","records"]),readAt:W().refine(n=>Number.isFinite(Date.parse(n)),"not a date"),ids:Z(W().refine(ts,"not a record id")).max(dn),sha256:W().regex(/^[0-9a-f]{64}$/)});function Qs(n){return Dn(n,Ld)}function kp(n,e){if(!_d.test(e))throw new We("gone","Not the fingerprint of a setup of a run.");return Dn(Qs(n),`${e}.json`)}function _n(n){let e=n?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Ip(n,e){let t=es(e.ids),r={version:1,sourceOrgId:e.sourceOrgId,fingerprint:e.fingerprint,objectApiName:e.objectApiName,...e.query!==void 0?{query:{...e.query}}:{},from:e.from,readAt:e.readAt,ids:t,sha256:On(t)},o=Zs.parse(r);await Ko(xd(n));let s=`${n}.${process.pid}-${Nd(4).toString("hex")}.tmp`;try{let i=await Td(s,"wx",bn);try{await i.writeFile(`${JSON.stringify(o)}
|
|
22
|
-
`,"utf8")}finally{await i.close()}await Ed(s,bn),await vd(s,n)}catch(i){throw await Ys(s,{force:!0}),i}return o}async function Bd(n){let e;try{e=await Fd(n,"utf8")}catch(r){throw _n(r)?new We("gone",`No plan of roots is at ${n}.`):r}let t;try{t=Zs.parse(JSON.parse(e))}catch{throw new We("changed",`The plan of roots at ${n} no longer reads as one.`)}if(On(t.ids)!==t.sha256)throw new We("changed",`The ids of the plan of roots at ${n} are no longer those it was kept with.`);return t}function jp(n,e){return e.getTime()-Date.parse(n.readAt)}async function Np(n,e){let t=Qs(n),r;try{r=await Pd(t)}catch(s){if(_n(s))return 0;throw s}let o=0;for(let s of r){let i=Dn(t,s),a;try{a=Date.parse((await Bd(i)).readAt)}catch{try{a=(await Cd(i)).mtimeMs}catch(d){if(_n(d))continue;throw d}}e.getTime()-a<Md||(await Ys(i,{force:!0}),o++)}return o}import{createHash as $d}from"node:crypto";function Wd(n,e){return ei(n,e,t=>t.included||Dr(t))}function qd(n,e){if(n!==void 0)return{...$n(n),...e?{planSha256:e}:{}}}function $n(n){let e=Object.entries(n.rootWhere??{}).map(([r,o])=>[r,o.trim()]),t=[...new Set(n.strata??[])].sort();return{...n.withinMB!==void 0?{withinMB:n.withinMB}:{},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{},seed:n.seed??Se.seed,draw:n.draw??Se.draw,parents:n.parents??Se.parents,children:n.children??Se.children,floor:n.floor??Se.floor,whole:[...new Set(n.whole??[])].sort(),...n.window?{window:Ud(n.window)}:{},...e.length>0?{rootWhere:Object.fromEntries(e)}:{},...t.length>0?{strata:t}:{}}}function Ud(n){return{field:n.field,...n.from!==void 0?{from:n.from}:{},...n.to!==void 0?{to:n.to}:{},...n.lastDays!==void 0?{lastDays:n.lastDays}:{}}}function Mt(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Xs(n){if(!Mt(n))return n;let e=typeof n.planSha256=="string"?n.planSha256:void 0;return qd(n,e)}function zd(n){if(!Mt(n))return n;let e=n.config;return{...n,..."sample"in n?{sample:Xs(n.sample)}:{},..."roots"in n?{roots:Vd(n.roots)}:{},...Mt(e)&&"sample"in e?{config:{...e,sample:Xs(e.sample)}}:{}}}function Vd(n){if(!Mt(n))return n;let{objectApiName:e,sha256:t}=n;return typeof e!="string"||typeof t!="string"?n:{objectApiName:e,sha256:t}}function Pp(n,e,t){return n===Wd(e,t)||n===ei(e,t,r=>r.included)}function ei(n,e,t){let r=n.nodes.map(s=>({objectApiName:s.objectApiName,included:t(s),anonymizeFields:[...s.anonymizeFields??[]].sort()})).sort((s,i)=>s.objectApiName.localeCompare(i.objectApiName)),o=n.edges.map(s=>({sourceObject:s.sourceObject,targetObject:s.targetObject,relationshipName:s.relationshipName,required:s.required===!0})).sort((s,i)=>`${s.sourceObject}|${s.targetObject}|${s.relationshipName}`.localeCompare(`${i.sourceObject}|${i.targetObject}|${i.relationshipName}`));return $d("sha256").update(Bn({nodes:r,edges:o,setup:zd(e)})).digest("hex")}function Bn(n){return Array.isArray(n)?`[${n.map(e=>Bn(e??null)).join(",")}]`:n!==null&&typeof n=="object"?`{${Object.entries(n).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>`${JSON.stringify(t)}:${Bn(r)}`).join(",")}}`:JSON.stringify(n??null)}function Lp(n){let e={filters:Object.keys(n.objectSoqlFilters??{}).sort(),excluded:[...new Set(n.excludedObjects??[])].sort(),heldBack:[...new Set((n.skippedRows??[]).map(t=>t.object))].sort(),fieldsLeftOut:Object.entries(n.fieldExclusions??{}).filter(([,t])=>t.length>0).map(([t])=>t).sort()};return n.sample?{...e,sample:$n(n.sample)}:Object.values(e).some(t=>t.length>0)?e:void 0}var qn=class extends Error{constructor(t){super("The dry run of a clone of the whole org stops at its write gate: nothing was read past the counts, nothing written.");this.dryRun=t;this.name="WholeOrgDryRunStop"}dryRun},Gd="NOTHING_TO_CLONE";function _p(n){if(n.nodes.some(t=>t.included))return;let e=new Set([...n.nodes.filter(t=>t.leftOutByUser===!0).map(t=>t.objectApiName),...(n.leftOut??[]).filter(t=>t.reason==="excludedByUser").map(t=>t.objectApiName)]).size;return{code:Gd,message:e>0?`Nothing to clone: every object of the source that holds records is left out, ${e} of them by name. Leave fewer out. Nothing was written.`:"Nothing to clone: no object of the source holds records the target can take. Nothing was written."}}function Dp(n){return n instanceof qn||n instanceof Error&&n.name==="WholeOrgDryRunStop"&&"dryRun"in n}function Wn(n){return n.verdict==="unread"?{estimate:n.estimate,unread:n.unread}:{estimate:n.estimate,remaining:n.remaining,max:n.max,...n.verdict==="near"?{near:!0}:{}}}function Bp(n){return{api:n.targetRequests,wholeOrg:{source:n.sourceRequests,...n.bulkBatches?{bulkBatches:n.bulkBatches}:{},cost:{durationSeconds:n.durationSeconds}}}}function Jd(n,e){let t=a=>a.reduce((d,c)=>d+c.rows,0),r=n.objects.reduce((a,d)=>a+d.sourceRows,0)+n.noRecordDrawn.reduce((a,d)=>a+d.sourceRows,0),o=t(n.leftEmpty),{plan:s}=n,i=Date.parse(s.drawnAt);return{rows:n.rows,objects:n.objects.length,sourceRows:r,storageMB:n.storageBytes/1048576,budgetMB:n.budget.bytes/1048576,...n.budget.automationMB!==void 0&&n.budget.automationMB>0?{automationMB:n.budget.automationMB}:{},seed:n.seed,draw:n.draw,share:n.share,limitedBy:n.budget.limitedBy,parents:n.parents,children:n.children,drawnAt:s.drawnAt,drawnBy:s.drawnBy,...s.drawnBy==="dryRun"&&Number.isFinite(i)?{minutesBefore:Math.max(1,Math.ceil((e-i)/6e4))}:{},...s.drawnAgain?{drawnAgain:s.drawnAgain}:{},...s.ofTheRunRetried?{ofTheRunRetried:!0}:{},...o>0?{leftEmpty:o}:{},...n.heavyRoots.length>0?{heavyRoots:n.heavyRoots.length}:{},...n.noRecordDrawn.length>0?{noRecordDrawn:n.noRecordDrawn.length}:{},...n.newestByIds&&n.newestByIds.length>0?{newestByIds:[...n.newestByIds]}:{},...n.oldestByIds&&n.oldestByIds.length>0?{oldestByIds:[...n.oldestByIds]}:{},...n.roots?{roots:Hd(n.roots)}:{}}}function Hd(n){return{...n.window?{window:{...n.window}}:{},...n.where&&n.where.length>0?{where:n.where.map(({objectApiName:e,where:t})=>({objectApiName:e,where:t}))}:{},...n.strata&&n.strata.length>0?{strata:n.strata.map(({objectApiName:e,field:t,values:r,more:o})=>({objectApiName:e,field:t,values:r.length+(o??0)}))}:{},...n.notWindowed&&n.notWindowed.length>0?{notWindowed:[...n.notWindowed]}:{}}}function $p(n){let{run:e,measures:t,plan:r,budget:o}=n,s=new Set(r.objects.filter(({rows:g})=>g>0).map(({objectApiName:g})=>g)),i=t.writes.filter(({rows:g})=>g>0),a=g=>i.reduce((h,y)=>h+y[g],0),d=a("jobs"),c=[...s].filter(g=>to(g)!==void 0).sort(),f=ls(e.graph.nodes,s,e.anonymizePII),l=n.files&&"check"in n.files?n.files:void 0,p=l?.check,u=t.contactPointsBlanked??0,m=o.wholeOrg.bulkBatches;return{source:e.source,leftOut:fs(e.graph).objects.length,...e.carried?{carried:e.carried}:{},...n.sample?{sample:Jd(n.sample,n.now??Date.now())}:{},targetApi:Wn(o.api),sourceApi:Wn(o.wholeOrg.source),...d>0?{bulk:{jobs:d,jobRows:a("jobRows"),restRows:a("restRows"),...m?{batches:Wn(m)}:{}}}:{},durationSeconds:o.wholeOrg.cost.durationSeconds,restObjects:i.filter(g=>g.jobs===0).map(g=>g.objectApiName),...l&&p&&p.verdict!=="unread"?{fileStorage:{files:l.count,estimateMB:p.estimateMB,overCeiling:t.files&&"overCeiling"in t.files?t.files.overCeiling:0,remainingMB:p.remainingMB,maxMB:p.maxMB,...p.verdict==="near"?{near:!0}:{}}}:{},...c.length>0?{managedPackages:c}:{},...u>0?{contactPointsBlanked:u}:{},...f.length>0?{personalAsIs:f}:{}}}var Kd=10*6e4,Yd=3e4,Zd=5e3,ti=500,Qd=new Set(["JobComplete","Failed","Aborted"]),ni=class{constructor(e,t={}){this.stateOf=e;this.options=t}stateOf;options;kept=[];noted=0;get count(){return this.noted}note(e){this.noted++,this.kept.push({seq:this.noted,job:{...e}}),this.kept.length>ti&&this.kept.splice(0,this.kept.length-ti)}since(e,t){return this.kept.filter(({seq:r,job:o})=>r>e&&o.orgId===t).map(({job:r})=>({...r}))}async stillRunning(e,t){let r=this.options.now??(()=>Date.now()),o=this.options.sleep??(c=>new Promise(f=>setTimeout(f,c))),s=this.options.pollDelay??ko,i=r()+(this.options.waitMs??Kd),a=e.filter(c=>c.jobId===void 0),d=e.filter(c=>!!c.jobId);for(let c=0;d.length>0;c++){let f=new Ot(Math.max(1,Math.min(Yd,i-r())));d=(await Promise.all(d.map(async u=>{t?.();let m=await f.withTimeout("forge:lost-bulk-job",()=>this.stateOf(u.orgId,u.jobId)).catch(()=>{});return m!==void 0&&Qd.has(m)?void 0:u}))).filter(u=>u!==void 0);let p=i-r()-Zd;if(d.length===0||p<=0)break;await o(Math.min(s(c),p))}return[...a,...d]}};function zp(n){let e=new Map;for(let{objectApiName:t,jobId:r}of n)e.set(t,[...e.get(t)??[],{recordSummary:r?`Bulk API job ${r}`:"Bulk API job (the org gave no id)",messages:[r?"Still being written by the org when the run gave back the mute of its automation, after waiting for it: the rows it wrote from then went in with the flows, triggers and rules the mute kept quiet. Look the job up in the target\u2019s Bulk Data Load Jobs.":"Closed before the org gave its id, so it could not be waited for: the rows it wrote after the run gave back the mute of its automation went in with the flows, triggers and rules the mute kept quiet."]}]);return[...e].map(([t,r])=>({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:r}))}var Xd="SELECT SobjectType FROM DuplicateRule WHERE IsActive = true",Gp=new Set(["Account","Contact","Lead"]);function Jp(n){if(typeof n.unread=="string")return;let e=n;if(e.unread.some(o=>o.part==="duplicateRules"))return;let t=new Map(e.objects.map(o=>[o.objectApiName.toLowerCase(),o.duplicateRules])),r=new Map;for(let o of e.objectsRead){let s=o.toLowerCase();if(!t.has(s)){r.set(o,!1);continue}let i=t.get(s);i!==void 0&&r.set(o,i.length>0)}return r}async function Hp(n){try{let e=await n.query(Xd);return new Set(e.records.flatMap(t=>typeof t.SobjectType=="string"?[t.SobjectType]:[]))}catch{return}}var ri=class{constructor(e=3){this.maxDiscoveries=e}maxDiscoveries;discoveries=new Map;awaitingGuard=new Map;run=null;beginDiscovery(e,t,r){let o=[],s=c=>{this.discoveries.delete(c.requestId),c.stop="superseded",o.push(c)},i=this.discoveries.get(e);i&&s(i);let a=[...this.discoveries.values()].filter(c=>!c.controller.signal.aborted);for(;a.length>=this.maxDiscoveries;){let c=a.shift();c&&s(c)}let d={requestId:e,controller:t,operationId:r};return this.discoveries.set(e,d),{discovery:d,superseded:o}}endDiscovery(e){this.discoveries.get(e.requestId)===e&&this.discoveries.delete(e.requestId)}awaitGuard(e,t){return this.awaitingGuard.set(e,t),()=>{this.awaitingGuard.get(e)===t&&this.awaitingGuard.delete(e)}}beginRun(e,t){this.run={requestId:e,controller:t}}endRun(e){this.run?.requestId===e&&(this.run=null)}resolve(e){let t=e===void 0?this.onlyLive():this.named(e);return"refused"in t?t:(t.kind==="discovery"&&(this.discoveries.delete(t.discovery.requestId),t.discovery.stop="stopped"),{stops:t})}stop(e,t){let r=this.resolve(e);if("refused"in r)return r;let o=r.stops;return o.kind==="discovery"?t.discovery(o.discovery):o.kind==="awaiting-guard"?o.controller.abort():t.run(),r}named(e){let t=this.discoveries.get(e);if(t)return{kind:"discovery",discovery:t};let r=this.awaitingGuard.get(e);return r?{kind:"awaiting-guard",controller:r}:this.run?.requestId===e?{kind:"run"}:{refused:"none"}}onlyLive(){let e=[...[...this.discoveries.values()].filter(t=>!t.controller.signal.aborted).map(t=>({kind:"discovery",discovery:t})),...[...this.awaitingGuard.values()].filter(t=>!t.signal.aborted).map(t=>({kind:"awaiting-guard",controller:t})),...this.run&&!this.run.controller.signal.aborted?[{kind:"run"}]:[]];return e.length===0?{refused:"none"}:e.length>1?{refused:"several",live:e.length}:e[0]}};function Un(n){let e=0,t=new Map,r=new Map,o=[],s=new Set,i=new Map,a=[],d=p=>{t.set(p,e),r.set(p,e),e++,o.push(p),s.add(p);for(let u of[...n.get(p)??[]].sort())n.has(u)&&(t.has(u)?s.has(u)&&r.set(p,Math.min(r.get(p)??0,t.get(u)??0)):(d(u),r.set(p,Math.min(r.get(p)??0,r.get(u)??0))));if(r.get(p)===t.get(p)){let u=[],m;do{if(m=o.pop(),m===void 0)break;s.delete(m),i.set(m,a.length),u.push(m)}while(m!==p);a.push(u.sort())}};for(let p of[...n.keys()].sort())t.has(p)||d(p);let c=a.map((p,u)=>{let m=new Set;for(let g of p)for(let h of n.get(g)??[]){let y=i.get(h);y!==void 0&&y!==u&&m.add(y)}return m}),f=new Set,l=[];for(;f.size<a.length;){let p=a.map((u,m)=>({component:u,i:m})).filter(({i:u})=>!f.has(u)&&[...c[u]].every(m=>f.has(m))).sort((u,m)=>u.component[0].localeCompare(m.component[0]));for(let{component:u,i:m}of p)f.add(m),l.push(u)}return l}function zn(n,e){let t=new Set(n),r=new Map(n.map(s=>[s,new Set([...e.get(s)??[]].filter(i=>t.has(i)))])),o=[];for(;;){let s=[...r.entries()].filter(([,i])=>i.size===0).map(([i])=>i).sort();if(s.length===0)break;for(let i of s){o.push(i),r.delete(i);for(let a of r.values())a.delete(i)}}return[...o,...[...r.keys()].sort()]}function ec(n,e,t){let r=new Set(n),o=new Map;for(let s of e){if(!r.has(s.to)||!r.has(s.from))continue;let i=t(s.to)?.find(d=>d.name===s.fieldApiName),a=i!==void 0&&pt(i);!s.required&&!Mr(s.to,s.fieldApiName)&&!a||o.set(s.to,(o.get(s.to)??new Set).add(s.from))}return o}function tc(n,e){let t=new Set(n),r=e.filter(s=>s.from!==s.to&&t.has(s.from)&&t.has(s.to)),o=new Map(n.map(s=>[s,new Set]));for(let s of r)o.get(s.to)?.add(s.from);return{within:r,deps:o,groups:Un(o)}}function Qp(n,e,t){return n.flatMap(r=>{let{groups:o,within:s}=tc(r,e);return o.flatMap(i=>i.length>1?zn(i,ec(i,s,t)):i)})}var nc=100,rc=.25,oc=2048;function Pe(n,e){return typeof n!="string"||n===""?!1:e.prefix===void 0||e.prefix!==null&&n.startsWith(e.prefix)}function sc(n){let e=new Set(n.map(o=>o.objectApiName)),t=new Map,r=new Map;for(let o of n){let s=new Set,i=new Set;for(let a of o.fields){if(a.referenceTo.length===0||!Qe(a))continue;let d=Vn(o.objectApiName,a)||pt(a);for(let c of a.referenceTo)c===o.objectApiName||!e.has(c)||(s.add(c),d&&i.add(c))}t.set(o.objectApiName,s),r.set(o.objectApiName,i)}return Un(t).flatMap(o=>o.length>1?zn(o,r):o)}function Vn(n,e){return Lr(n,e.name,e.nillable)}function ic(n){let e=new Map(n.objects.map(u=>[u.objectApiName,u])),t=new Map;for(let u of e.keys())n.referenceData?.has(u)&&t.set(u,"referenceData");for(let u of n.whole??[])e.has(u)&&!t.has(u)&&t.set(u,"asked");let r=rc*Math.max(0,n.roomBytes),o=u=>u.rows===void 0?void 0:n.wholeBytes(u.objectApiName,u.rows),s=[...e.values()].filter(u=>Et.has(u.objectApiName)&&!t.has(u.objectApiName)),i=s.reduce((u,m)=>{let g=o(m);return u===void 0||g===void 0?void 0:u+g},0);if(s.length>0&&i!==void 0&&i<=r&&s.every(u=>n.maxRecordsPerObject===void 0||(u.rows??0)<=n.maxRecordsPerObject))for(let u of s)t.set(u.objectApiName,"catalog");let d=Math.max(nc,Math.floor(.01*Math.max(0,n.roomBytes)/oc)),c=u=>e.has(u)&&!t.has(u),f=new Set;for(let u of e.values())if(c(u.objectApiName)){for(let m of u.fields)if(Qe(m))for(let g of m.referenceTo)g!==u.objectApiName&&f.add(g)}let l=[...e.values()].filter(u=>!t.has(u.objectApiName)&&!Et.has(u.objectApiName)&&u.rows!==void 0&&u.rows>0&&u.rows<=d&&(n.maxRecordsPerObject===void 0||u.rows<=n.maxRecordsPerObject)&&f.has(u.objectApiName)).map(u=>({object:u,bytes:o(u)??1/0})).sort((u,m)=>u.bytes-m.bytes||(u.object.objectApiName<m.object.objectApiName?-1:1)),p=0;for(let{object:u,bytes:m}of l){if(p+m>r)break;u.fields.some(h=>Qe(h)&&Vn(u.objectApiName,h)&&h.referenceTo.some(y=>c(y)))||(t.set(u.objectApiName,"smallParent"),p+=m)}return t}function Lt(n){let e=new Map(n.objects.map(l=>[l.objectApiName,l])),t=ic(n),r=[...t.values()].includes("catalog"),o=new Map;for(let l of e.keys()){let p=t.get(l);o.set(l,p!==void 0?{kind:"whole",why:p}:{kind:"drawn",rooted:!(Et.has(l)&&!r)})}let s=n.order?[...n.order]:sc(n.objects),i=new Map(s.map((l,p)=>[l,p])),a=(l,p)=>(i.get(l)??1/0)<(i.get(p)??1/0),d=l=>{let p=o.get(l);return p?.kind==="drawn"&&p.rooted},c=new Map,f=new Map;for(let l of[...e.values()].sort((p,u)=>p.objectApiName<u.objectApiName?-1:1)){let p=l.objectApiName,u=[];for(let m of[...l.fields].sort((g,h)=>g.name<h.name?-1:1)){if(m.referenceTo.length===0||!Qe(m))continue;let g=Vn(p,m),h=m.referenceTo.length>1;for(let y of[...m.referenceTo].sort()){let R=o.get(y),S=ns(p,m,e.get(y)?.childRelationships),w=n.excluded?.get(y),b=v=>h?{prefix:v??null}:{};if(!R){g&&n.excluded?.has(y)&&u.push({objectApiName:p,field:m.name,parent:y,target:"excluded",carries:!1,owed:!1,required:g,masterDetail:S,...b(w)});continue}let A=y===p,j=A||!a(y,p),L={objectApiName:p,field:m.name,parent:y,target:R.kind==="whole"?"whole":"drawn",carries:!A&&d(y)&&d(p)&&(g||!j),owed:j,required:g,masterDetail:S,...b(e.get(y)?.keyPrefix)};if(u.push(L),L.carries){let v=f.get(y)??[];v.push(L),f.set(y,v)}}}c.set(p,u)}return{classes:o,whole:[...t.entries()].map(([l,p])=>({objectApiName:l,why:p})).sort((l,p)=>l.objectApiName<p.objectApiName?-1:1),linksOf:c,carriersInto:f,order:s}}function Gn(n,e){return[...new Set((n.linksOf.get(e)??[]).map(t=>t.field))].sort()}function oi(n,e){let t=(n.linksOf.get(e)??[]).filter(s=>s.carries),r=new Set,o=new Set;for(let s of t)(s.prefix===void 0?r:o).add(s.field);return{empty:[...r].sort(),told:[...o].sort()}}function si(n,e,t,r){return(n.linksOf.get(e)??[]).find(o=>o.field===t&&Pe(r,o))}var me=2e3,dc=500,Kn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,cc=et;function qe(n){return n.length===0?"":` WHERE ${n.join(" AND ")}`}function Ue(n){return oo(n)+2*(n.match(/'/g)?.length??0)}function ii(n,e,t){let r=Ue(n)+Ue(t),o=Ue(", "),s=[],i=[],a=r;for(let d of e){let c=Ue(`'${d}'`);i.length>0&&(a+o+c>14e3||i.length>=dc)&&(s.push(i),i=[],a=r),a+=(i.length>0?o:0)+c,i.push(d)}return i.length>0&&s.push(i),s}function at(n){let e=new Set,t=[];for(let r of n){if(!Kn.test(r))continue;let o=U(r);e.has(o)||(e.add(o),t.push(r))}return t}function _t(n){return wt(H(n))==="QUERY_TIMEOUT"}var uc=new Set(["MALFORMED_QUERY","INVALID_FIELD"]);function ai(n){let e=wt(H(n));return e!==void 0&&uc.has(e)}var lc=new Set(["MALFORMED_QUERY","INVALID_FIELD","EXCEEDED_MAX_SEMIJOIN_SUBSELECTS"]),fc="SAMPLE_DRAW_INVALID";function pc(n,e,t){if(n.where===void 0)return"strata";if(n.stratifiedBy===void 0||e==="EXCEEDED_MAX_SEMIJOIN_SUBSELECTS")return"where";if(/can ?not be grouped/i.test(t))return"strata";let r=/No such column '([^']+)'/i.exec(t)?.[1]?.toLowerCase();if(r===void 0)return"either";let o=a=>a.toLowerCase().split(/\W+/).includes(r),s=o(n.where),i=o(n.stratifiedBy);return s===i?"either":s?"where":"strata"}var ge="CreatedDate",mc="LastModifiedDate",di="SystemModstamp";function li(n){return n.replace(/'(?:[^'\\]|\\.)*'/g,"''")}function gc(n){return/\(\s*SELECT\b/i.test(li(n))}function hc(n){let e=0,t="";for(let r of li(n))r==="("&&e++,t+=e===0?r:" ",r===")"&&(e=Math.max(0,e-1));return/\bOR\b/i.test(t)}function ci(n){let e=n.trim();return gc(e)&&!hc(e)?e:`(${e})`}function fi(n){return n==null||n===""}function Hn(n){return fi(n)?null:typeof n=="boolean"?n:String(n)}function dt(n){return n===null?"\0":`${typeof n}:${String(n)}`}function wc(n,e){return e===null?`${n} = null`:typeof e=="boolean"?`${n} = ${String(e)}`:`${n} = '${xe(e)}'`}function yc(n){let e=n.trim();return/[.!?]$/.test(e)?e:`${e}.`}function bc(n,e){let t=typeof n=="string"?Date.parse(n):Number.NaN;return!Number.isFinite(t)||e.from!==void 0&&t<Date.parse(e.from)?!1:e.to===void 0||t<Date.parse(e.to)}var Dt=class{constructor(e,t){this.source=e;this.options=t}source;options;sent=0;rowsRead=0;slow=new Set;ungrouped=new Set;counted=new Map;countedStrata=new Map;standardBook;get requests(){return this.sent}async*pages(e,t){this.options.signal?.throwIfAborted();let r=0;try{for await(let o of this.source.pages(e,t))r++,this.sent++,this.rowsRead+=o.length,yield o}catch(o){throw this.sent++,o}r===0&&this.sent++}async gather(e,t){let r=[];for await(let o of this.pages(e,t))for(let s of o)r.push(s);return r}async count(e,t){this.options.signal?.throwIfAborted();try{return await this.source.count(e,t)}finally{this.sent++}}progress(e,t){this.options.onProgress?.({step:e,rows:this.rowsRead,requests:this.sent,...t})}columnsOf(e,t){let r=this.options.fieldsOf(e);if(r===void 0)throw new Error(`No describe of ${e}: its records cannot be read for a sample.`);let o=new Set(r.map(a=>a.toLowerCase())),s=["Id"],i=new Set(["id"]);for(let a of t){let d=a.toLowerCase();i.has(d)||!o.has(d)||(i.add(d),s.push(J(a)))}return s}readOptionsOf(e){return et.has(e)?{all:!0}:void 0}termsOf(e){let t=this.options.filterOf?.(e);return[...t!==void 0&&t.trim()!==""?[ci(t)]:[],...et.has(e)?["IsDeleted = false"]:[]]}lists(e,t){let r=t.toLowerCase();return(this.options.fieldsOf(e)??[]).some(o=>o.toLowerCase()===r)}fieldOf(e,t){if((this.options.fieldsOf(e)??[]).find(s=>s.toLowerCase()===t.toLowerCase())===void 0)throw new Error(`${e}.${t} is no field of the source's describe.`);return J(t)}rootShapeOf(e,t={}){let r=J(e.objectApiName),o=t.slow??this.slow.has(r),s=e.carriers.map(S=>({field:this.fieldOf(r,S.field),prefixes:S.drawnPrefixes===void 0?void 0:[...S.drawnPrefixes]})),i=o?[]:s.filter(S=>S.prefixes===void 0),a=s.filter(S=>!i.includes(S)),d=(S,w)=>!fi(S)&&(w===void 0||w.some(b=>String(S).startsWith(b))),c=t.natural?void 0:e.window,f=c?this.fieldOf(r,c.field):void 0,l=c?.field===mc,p=c!==void 0&&l&&o,u=c&&f&&!p?[...c.from!==void 0?[`${f} >= ${Ae(c.from)}`]:[],...c.to!==void 0?[`${f} < ${Ae(c.to)}`]:[],...l&&c.from!==void 0&&this.lists(r,di)?[`${di} >= ${Ae(c.from)}`]:[]]:[],m=t.natural||e.where?.trim()===""?void 0:e.where,g=e.stratifiedBy!==void 0&&(t.stratum!==void 0||t.values)?this.fieldOf(r,e.stratifiedBy):void 0,h=t.stratum?.value===null,y=t.stratum!==void 0&&g!==void 0&&!(h&&o)?[wc(g,t.stratum.value)]:[],R=[];return p&&c&&f&&R.push(S=>bc(S[f],c)),h&&o&&g!==void 0&&R.push(S=>Hn(S[g])===null),{object:r,select:this.columnsOf(r,[...a.map(S=>S.field),...p&&f?[f]:[],...g!==void 0&&(t.values||h&&o)?[g]:[]]),terms:[...this.termsOf(r),...i.map(S=>`${S.field} = null`),...u,...m!==void 0?[ci(m)]:[],...y],held:i.length>0||l&&u.length>0||h&&y.length>0,tested:a.length>0||R.length>0,isRoot:S=>!a.some(w=>d(S[w.field],w.prefixes))&&R.every(w=>w(S))}}async countRoots(e){let t=new Array(e.length),r=0;return await Te(e,async(o,s)=>{let i=await this.countRootsOf(o);t[s]=i,this.counted.set(o.objectApiName,i.rows),i.strata&&this.countedStrata.set(o.objectApiName,new Map(i.strata.map(a=>[dt(a.value),a.rows]))),r++,this.progress("counting",{objectApiName:o.objectApiName,done:r,total:e.length})}),t}async countRootsOf(e){let t=e.objectApiName,r=this.readOptionsOf(t);e.stratifiedBy!==void 0&&this.refuseUngroupedStratum(e,e.stratifiedBy);let o=!1;for(;;){let s=this.rootShapeOf(e),i;try{i=e.stratifiedBy===void 0?{rows:await this.count(`SELECT COUNT() FROM ${s.object}${qe(s.terms)}`,r)}:await this.countByStratum(e,e.stratifiedBy,s,r)}catch(d){if(o||!s.held||!_t(d))throw this.drawRefusalOf(e,d);o=!0,this.slow.add(t);continue}let a=this.restricts(e)?await this.countInTheSource(e,{terms:s.terms,rows:i.rows,exact:!s.tested}):void 0;return{objectApiName:t,rows:i.rows,exact:!s.tested,...o?{timedOut:!0}:{},...i.strata?{strata:i.strata}:{},...a?{inTheSource:a}:{}}}}restricts(e){return e.window!==void 0||e.where!==void 0&&e.where.trim()!==""}async countInTheSource(e,t){let r=this.readOptionsOf(e.objectApiName),o=this.slow.has(e.objectApiName);for(;;){let s=this.rootShapeOf(e,{natural:!0,slow:o});if(s.terms.join(`
|
|
23
|
-
`)===t.terms.join(`
|
|
24
|
-
`))return{rows:t.rows,exact:t.exact};try{return{rows:await this.count(`SELECT COUNT() FROM ${s.object}${qe(s.terms)}`,r),exact:!s.tested}}catch(i){if(o||!s.held||!_t(i))throw i;o=!0}}}async countByStratum(e,t,r,o){let s=this.fieldOf(r.object,t),i=`SELECT ${s}, COUNT(Id) n FROM ${r.object}${qe(r.terms)} GROUP BY ${s}`,a=[],d=0;try{for await(let f of this.pages(i,o)){if(d++,d>1)break;for(let l of f)a.push(l)}}catch(f){if(d===0)throw f;d=2}if(d>1||a.length>=me)throw this.drawRefused(e,"strata",`${e.objectApiName}.${t} has too many values among the roots of the draw to stratify them: the source counts them in one answer of fewer than ${me}, and this one ${d>1?"had more after it":`held ${a.length}`}.`);let c=[];for(let f of a){let l=Number(f.n);Number.isFinite(l)&&c.push({value:Hn(f[s]),rows:l})}return{rows:c.reduce((f,l)=>f+l.rows,0),strata:c}}refuseUngroupedStratum(e,t){if(this.options.countsBy?.(e.objectApiName,t)===!1)throw this.drawRefused(e,"strata",`The source's describe says the records of ${e.objectApiName} are not counted by ${t}.`)}drawRefusalOf(e,t){let r=H(t),o=wt(r);return o===void 0||!lc.has(o)||!this.restricts(e)&&e.stratifiedBy===void 0?t:this.drawRefused(e,pc(e,o,r),`The source refused to count the roots of ${e.objectApiName} in the draw: ${r}`)}drawRefused(e,t,r){let o=e.objectApiName,s=[];return e.where!==void 0&&t!=="strata"&&s.push(`The source reads the condition of its roots (--fit-where ${o}=\u2026) as it is written: its fields are those of the object, and with the filter it holds two semi-joins at most, none in parentheses an OR is part of.`),e.stratifiedBy!==void 0&&t!=="where"&&s.push(`Stratify ${o} by a field of few values the source groups by \u2014 a picklist, a checkbox, a record type or an owner (--fit-strata ${o}.<Field>) \u2014, or narrow its roots first (--fit-where ${o}=\u2026).`),new pe(fc,[yc(r),`Nothing was written, and the counts sent ${this.sent} request(s) of the source.`,...s].join(" "),void 0,void 0,void 0,{sample:{requests:this.sent}})}async drawUniform(e,t){let r=0;await Te(e,async o=>{this.counted.get(o.objectApiName)!==0&&await this.scanRoots(o,t),r++,this.progress("drawing",{objectApiName:o.objectApiName,done:r,total:e.length})})}async scanRoots(e,t){let r=this.readOptionsOf(e.objectApiName),o=e.stratifiedBy;for(;;){let s=this.rootShapeOf(e,o===void 0?{}:{values:!0}),i=`SELECT ${s.select.join(", ")} FROM ${s.object}${qe(s.terms)}`,a=!1;try{for await(let d of this.pages(i,r)){a=!0;let c=d.filter(s.isRoot);if(o===void 0){let f=c.map(l=>String(l.Id));f.length>0&&await t(e.objectApiName,f);continue}for(let{value:f,ids:l}of Oc(c,o))await t(e.objectApiName,l,f)}return}catch(d){if(a||!s.held||!_t(d))throw d;this.slow.add(e.objectApiName)}}}async drawByDate(e,t,r){let o=e.map(i=>({objectApiName:i.objectApiName,by:this.orderedBy(i.objectApiName)})),s=0;return await Te(e,async(i,a)=>{let d=i.objectApiName;if(this.counted.get(d)!==0){let c=o[a].by;if(typeof i.take=="number")i.take>0&&await this.rootsByDate(i,t,c,i.take,void 0,r);else{let f=this.countedStrata.get(d);for(let l of i.take)l.take<=0||f?.get(dt(l.value))===0||await this.rootsByDate(i,t,c,l.take,l,r)}}s++,this.progress("drawing",{objectApiName:d,done:s,total:e.length})}),o}orderedBy(e){return this.lists(e,ge)&&this.options.sorts?.(e,ge)!==!1?"created":"id"}async rootsByDate(e,t,r,o,s,i){let a=e.objectApiName,d=this.readOptionsOf(a),c=0,f;for(;c<o;){let l=this.rootShapeOf(e,s===void 0?{}:{stratum:s}),p=l.tested?me:Math.min(me,o-c),u=r==="created"?this.columnsOf(a,[...l.select,ge]):l.select,{after:m,order:g}=Sc(r,t,f),h=`SELECT ${u.join(", ")} FROM ${l.object}${qe([...l.terms,...m])} ORDER BY ${g} LIMIT ${p}`,y;try{y=await this.gather(h,d)}catch(S){if(!l.held||!_t(S))throw S;this.slow.add(a);continue}let R=y.filter(l.isRoot).map(S=>String(S.Id)).slice(0,o-c);if(c+=R.length,R.length>0&&await(s===void 0?i(a,R):i(a,R,s.value)),y.length<p)return;f=Ac(a,y[y.length-1],r)}}async readParents(e){let t=new Array(e.length);return await Te(e,async(r,o)=>{t[o]=await this.parentsOf(r)}),t}async parentsOf(e){let t=J(e.objectApiName),r=this.columnsOf(t,e.columns),o=at(e.ids),s=this.readOptionsOf(t),i=await this.byList(t,r,"Id",o,this.termsOf(t),s),a=new Set(i.map(p=>U(String(p.Id)))),d=o.filter(p=>!a.has(U(p))),c=this.options.filterOf?.(t),f=[];if(d.length>0&&c!==void 0&&c.trim()!==""){let p=et.has(t)?["IsDeleted = false"]:[];f=await this.byList(t,r,"Id",d,p,s)}let l=new Set(f.map(p=>U(String(p.Id))));return{objectApiName:e.objectApiName,rows:i,columns:r,absent:d.filter(p=>!l.has(U(p))),outsideFilter:f}}async readStandardPrices(e,t){let r=at(e);if(r.length===0)return[];if(this.standardBook===void 0){let[i]=await this.gather("SELECT Id FROM Pricebook2 WHERE IsStandard = true"),a=i?.Id;this.standardBook=typeof a=="string"&&Kn.test(a)?a:null}if(this.standardBook===null)return[];let o=this.columnsOf("PricebookEntry",["Product2Id",...t]),s=[...this.termsOf("PricebookEntry"),`Pricebook2Id = '${this.standardBook}'`];return this.byList("PricebookEntry",o,"Product2Id",r,s,void 0)}async readPricesIn(e,t,r,o){if(!/^[A-Z]{3}$/.test(e))return[];let s=at(t),i=at(r);if(s.length===0||i.length===0)return[];let a=this.columnsOf("PricebookEntry",["Product2Id","Pricebook2Id",...o]),d=[...this.termsOf("PricebookEntry"),`Pricebook2Id IN (${i.map(c=>`'${c}'`).join(", ")})`,`CurrencyIsoCode = '${e}'`];return this.byList("PricebookEntry",a,"Product2Id",s,d,void 0)}async byList(e,t,r,o,s,i){let a=[...s,`${r} IN (`].join(" AND "),d=`SELECT ${pn(t).join(", ")} FROM ${e} WHERE ${a}`,c=[];for(let f of ii(d,o,")")){let l=`SELECT ${t.join(", ")} FROM ${e} WHERE ${a}${f.map(p=>`'${p}'`).join(", ")})`;for(let p of await mn(l,u=>this.gather(u,i)))c.push(p)}return c}async readChildren(e){let t=new Array(e.length);return await Te(e,async(r,o)=>{t[o]=await this.childrenOf(r)}),t}async childrenOf(e){let t=J(e.objectApiName),r=this.fieldOf(t,e.field),o=e.cap,s=this.orderedBy(t),i=o!=="all"&&s==="created",a=this.columnsOf(t,[r,...e.columns,...i?[ge]:[]]),d=at(e.parentIds),c=this.readOptionsOf(t),f=this.termsOf(t),l=new Map,p={objectApiName:t,field:r,rows:[],columns:a,cut:[],counts:new Map,newestBy:s},u=()=>{for(let b of d)p.counts.set(b,l.get(U(b))??0);return p};if(d.length===0)return p;if(o==="all"){let b=Jn(await this.byList(t,a,r,d,f,c),r,1/0,s);p.rows=b.rows;for(let[A,j]of b.counts)l.set(A,j);return u()}let m=[...f,`${r} IN (`].join(" AND "),g={head:`SELECT ${r}, COUNT(Id) n FROM ${t} WHERE ${m}`,tail:`) GROUP BY ${r}`},h={head:`SELECT ${pn(a).join(", ")} FROM ${t} WHERE ${m}`,tail:")"},y=Ue(g.head+g.tail)>Ue(h.head+h.tail)?g:h,R=[],S=[];for(let b of ii(y.head,d,y.tail)){let A=e.sourceRows<=o*b.length||this.ungrouped.has(t)||this.options.countsBy?.(t,r)===!1?void 0:await this.countedByParent(t,g,r,b,c);if(A===void 0){R.push(...b);continue}for(let j of A)j.rows>o?S.push(j):R.push(j.parentId)}let w=Jn(await this.byList(t,a,r,R,f,c),r,o,s);p.rows.push(...w.rows),p.cut.push(...w.cut);for(let[b,A]of w.counts)l.set(b,A);for(let b of S){let A=`SELECT ${a.join(", ")} FROM ${t} WHERE ${[...f,`${r} = '${b.parentId}'`].join(" AND ")} ORDER BY ${Rc(s)} LIMIT ${o}`,j;try{j=await mn(A,L=>this.gather(L,c))}catch(L){if(!ai(L))throw L;let v=Jn(await this.byList(t,a,r,[b.parentId],f,c),r,o,s);p.rows.push(...v.rows),p.cut.push(...v.cut);for(let[P,k]of v.counts)l.set(P,k);continue}p.rows.push(...j),p.cut.push({parentId:b.parentId,rows:Math.max(0,b.rows-j.length)}),l.set(U(b.parentId),b.rows)}return u()}async countedByParent(e,t,r,o,s){let i=`${t.head}${o.map(c=>`'${c}'`).join(", ")}${t.tail}`,a;try{a=await this.gather(i,s)}catch(c){if(!ai(c))throw c;this.ungrouped.add(e);return}let d=[];for(let c of a){let f=c[r],l=Number(c.n);typeof f=="string"&&Number.isFinite(l)&&d.push({parentId:f,rows:l})}return d}async readWhole(e,t){await Te(e,async r=>{let o=J(r.objectApiName),s=this.columnsOf(o,r.columns),i=this.readOptionsOf(o),a=`SELECT ${s.join(", ")} FROM ${o}${qe(this.termsOf(o))}`;for await(let d of uo(a,c=>this.pages(c,i),c=>this.gather(c,i)))await t(r.objectApiName,d)})}};function Rc(n){return n==="created"?`${ge} DESC, Id DESC`:"Id DESC"}function Sc(n,e,t){let r=e==="recent",o=r?"<":">",s=r?"DESC":"ASC";if(n==="id")return{after:t?[`Id ${o} '${t.id}'`]:[],order:`Id ${s}`};let i=`${ge} ${s}, Id ${s}`;return t?{after:[`(${ge} ${o} ${t.at} OR (${ge} = ${t.at} AND Id ${o} '${t.id}'))`],order:i}:{after:[],order:i}}function Oc(n,e){let t=new Map;for(let r of n){let o=Hn(r[e]),s=dt(o),i=t.get(s)??{value:o,ids:[]};i.ids.push(String(r.Id)),t.set(s,i)}return[...t.values()]}function Ac(n,e,t){let r=e.Id;if(typeof r!="string"||!Kn.test(r))throw new Error(`A record of ${n} came back without its id.`);if(t==="id")return{at:"",id:r};let o=e[ge];if(typeof o!="string"||!Number.isFinite(Date.parse(o)))throw new Error(`A record of ${n} came back without the date it was made.`);return{at:Ae(o),id:r}}function ui(n){let e=n[ge],t=typeof e=="string"?Date.parse(e):Number.NaN;return Number.isFinite(t)?t:void 0}function kc(n,e){let t=ui(n),r=ui(e);return t!==r?t===void 0?1:r===void 0?-1:r-t:ue(String(e.Id),String(n.Id))}function Jn(n,e,t,r){let o=new Map;for(let d of n){let c=d[e];if(typeof c!="string")continue;let f=U(c),l=o.get(f);l?l.rows.push(d):o.set(f,{parentId:c,rows:[d]})}let s=[],i=[],a=new Map;for(let[d,{parentId:c,rows:f}]of o)f.sort(r==="created"?kc:(l,p)=>ue(String(p.Id),String(l.Id))),s.push(...f.slice(0,t)),f.length>t&&i.push({parentId:c,rows:f.length-t}),a.set(d,f.length);return{rows:s,cut:i,counts:a}}function Bt(n,e,t=0){if(n.rows<=0)return 0;if(e==="uniform")return Math.ceil(n.rows/me);let r=(s,i)=>Math.ceil(Math.min(Math.max(0,s),i)/me);if(typeof t=="number")return r(t,n.rows);let o=new Map((n.strata??[]).map(s=>[dt(s.value),s.rows]));return t.reduce((s,i)=>s+r(i.take,o.get(dt(i.value))??i.take),0)}function pm(n){let e=J(n.objectApiName),t=n.columns.some(p=>p.toLowerCase()==="systemmodstamp"),r=so(n.columns,t?["Id","SystemModstamp"]:["Id"]),o=Math.max(0,n.planRows),s=Math.max(0,n.sourceRows),i=r.map(p=>ao(e,p)),a=i.reduce((p,u)=>p+Math.ceil(o/u),0),d=Math.max(1,Math.ceil(s/me)),c=Math.floor(s/me),f=s%me,l=d+i.slice(1).reduce((p,u)=>p+c*Math.ceil(me/u)+(f>0?Math.ceil(f/u):0),0);return cc.has(e)?{by:"cursor",requests:l,byIds:a,byCursor:l,cursorAlone:!0}:a<=l?{by:"ids",requests:a,byIds:a,byCursor:l}:{by:"cursor",requests:l,byIds:a,byCursor:l}}var Ic=new Set(["BusinessHours","OperatingHours"]);function pi(n,e){if(!(!n||"unread"in n))return Math.floor(n.remaining-ke*n.max-e)}function jc(n){let e=pi(n.requests,Math.max(0,n.sentBefore??0)+ps),t=pi(n.bulkBatches,0);if(e===void 0&&t===void 0)return;let r=n.updatedAfterInsert?{updatedAfterInsert:n.updatedAfterInsert}:{};return o=>{let s=[...o].map(([i,a])=>({objectApiName:i,rows:a,storageBytes:0}));if(e!==void 0&&ds({plan:{objects:s},...r,bulk:{}}).run>e)return"targetRequests";if(t!==void 0&&cs({plan:{objects:s},...r,measures:{}}).bulkBatches>t)return"bulkBatches"}}function Nc(n){let{storage:e,withinMB:t}=n,r=new Map;for(let c of n.automation??[])r.set(c.objectApiName,(r.get(c.objectApiName)??0)+c.bytes);let o=n.allowances?jc(n.allowances):void 0,s={...r.size>0?{automationBytes:c=>r.get(c)??0}:{},...o?{requests:o}:{}};if("unread"in e){if(t===void 0)return;let c=Math.floor(Math.max(0,t)*1048576);return{budget:{bytes:c,withinMB:t,limitedBy:"within"},bytesLimit:"within",roomBytes:c,...s}}let i=ks({storage:e,...t!==void 0?{withinMB:t}:{}});if("unread"in i)return;let a=i.terms.limitedBy==="within"?"within":"storage",d=Math.floor(Fe*Tt(e)*1048576);return{budget:{bytes:i.bytes,remainingMB:e.remainingMB,maxMB:e.maxMB,share:Fe,roundingMB:tt,...i.terms.uncountedMB!==void 0?{uncountedMB:i.terms.uncountedMB}:{},...t!==void 0?{withinMB:t}:{},limitedBy:a},bytesLimit:a,roomBytes:d,storageBytes:d,...s}}function Ec(n,e){let t=n.nodes.filter(o=>o.included&&!Br(o)&&!e.has(o.objectApiName)),r=new Set(t.map(o=>o.objectApiName));return t.map(o=>({objectApiName:o.objectApiName,rows:o.recordCountUnknown===!0?void 0:o.recordCount,fields:n.edges.filter(s=>s.targetObject===o.objectApiName&&r.has(s.sourceObject)).map((s,i)=>({name:`${s.relationshipName||s.sourceObject}${i}`,referenceTo:[s.sourceObject],isMasterDetail:s.type==="master-detail",nillable:s.required!==!0&&s.type!=="master-detail",createable:s.settable!==!1,updateable:s.settable!==!1}))}))}function Om(n){let e=n.options??{},t=Ec(n.graph,new Set(n.excludedObjects??[])),r=t.reduce((m,g)=>m+ye(g.objectApiName,{rows:g.rows??0}),0),o=us({storageBytes:r},n.storage),s=Nc({storage:n.storage,...e.withinMB!==void 0?{withinMB:e.withinMB}:{}}),i=Lt({objects:t,referenceData:Ic,...e.whole?{whole:e.whole}:{},roomBytes:s?.roomBytes??0,...n.maxRecordsPerObject!==void 0?{maxRecordsPerObject:n.maxRecordsPerObject}:{},wholeBytes:(m,g)=>ye(m,{rows:g})}),a=e.draw??Se.draw,d=s?Nt(s.budget.bytes,e.maxTotal):0,c=t.filter(m=>{let g=i.classes.get(m.objectApiName);return g?.kind==="drawn"&&g.rooted}),f=new Set(Object.keys(e.rootWhere??{}).map(m=>m.toLowerCase())),l=m=>e.window!==void 0||f.has(m.toLowerCase()),p=c.reduce((m,g)=>{let y=(i.linksOf.get(g.objectApiName)??[]).some(R=>R.carries&&R.required)?0:g.rows??0;return m+1+(l(g.objectApiName)?1:0)+Bt({objectApiName:g.objectApiName,rows:y,exact:!1},a,Math.min(y,d))},0),u=e.window!==void 0||f.size>0;return{wholeOrg:o,...s?{budget:s.budget}:{},whole:i.whole.filter(m=>m.why!=="asked"),planReads:{source:Tc(p,n.source),seconds:p*Yo,...u?{atMost:!0}:{}}}}function Tc(n,e){if("unread"in e)return{verdict:"unread",estimate:n,unread:e.unread};let t=is(n,e);if(t.verdict==="unread")return t;let r=n>Math.floor(ke*e.remaining);return{...t,verdict:r?"exceeds":t.verdict}}var mi=V({value:W(),validFor:Z(te().int().nonnegative()).optional()}).loose(),gi=V({controllerValues:sn(W(),te().int().nonnegative()).optional(),defaultValue:mi.nullable().optional(),values:Z(mi)}).loose(),Fc=V({picklistFieldValues:sn(W(),Ne())}).loose(),Pc=/^[A-Za-z][A-Za-z0-9_]*$/,vc=/^012[A-Za-z0-9]{12}([A-Za-z0-9]{3})?$/;function Cc(n){let e=n.values.map(s=>s.value),t=n.defaultValue?.value??null,r=Object.entries(n.controllerValues??{});if(r.length===0)return{values:e,defaultValue:t};let o=new Map;for(let[s,i]of r)o.set(s,new Set(n.values.filter(a=>(a.validFor??[]).includes(i)).map(a=>a.value)));return{values:e,defaultValue:t,allowedByControllingValue:o}}function xc(n){let e=Fc.parse(n),t=new Map;for(let[r,o]of Object.entries(e.picklistFieldValues)){let s=gi.safeParse(o);s.success&&t.set(r,Cc(s.data))}return t}function Mc(n){return gi.parse(n).values.map(e=>e.value)}function hi(n,e,t,r){for(let s of r===void 0?[e]:[e,r])if(!Pc.test(s))throw new Error(`Not an API name: "${s}"`);if(!vc.test(t))throw new Error(`Not a record type id: "${t}"`);let o=`/services/data/v${n.version}/ui-api/object-info/${e}/picklist-values/${t}`;return r===void 0?o:`${o}/${r}`}async function km(n,e,t){return xc(await n.request(hi(n,e,t)))}async function Im(n,e,t,r){return Mc(await n.request(hi(n,e,t,r)))}var Lc=V({FileStorageMB:V({Remaining:te()}).loose()}).loose(),_c=Z(V({errorCode:W().optional(),message:W().optional()}).loose());function Dc(n){if(!(n instanceof Error))return new Error(String(n));try{let e=_c.safeParse(JSON.parse(Buffer.from(n.message,"base64").toString("utf8"))),t=e.success?e.data[0]:void 0;if(t?.message)return new Error(t.errorCode?`${t.errorCode}: ${t.message}`:t.message)}catch{}return n}async function Fm(n,e,t){if(!wo(t))throw new Error(`Not a record id: ${t}`);try{let r=await n.request({method:"GET",url:`/sobjects/${e}/${t}/${Cs[e]}`},{encoding:"base64",responseType:"application/octet-stream"});if(typeof r!="string")throw new Error("The org answered with no file content.");return r}catch(r){throw Dc(r)}}async function Pm(n,e,t){try{let r=await n.request({method:"POST",url:`/sobjects/${e}`,body:JSON.stringify(t),headers:{"content-type":"application/json"}}),o=Rt(r,e);return{id:o.id,success:o.success,errors:o.errors}}catch(r){return{id:"",success:!1,errors:[bo(r)]}}}async function vm(n){return Lc.parse(await n.request({method:"GET",url:"/limits"})).FileStorageMB.Remaining}var qc=["Task","Event","FeedItem","FeedComment","EmailMessage","ContentDocumentLink","Note","CaseComment"],bi=["Account","Contact","Lead","Opportunity","Case","Campaign","Contract","Order","Asset","Product2"],Zn=["User","Group","GroupMember","PermissionSet","PermissionSetAssignment","PermissionSetGroup","RecordType","Profile","UserRole"],Uc=1e3,zc=6e4,Yn=1e4,Vc=300,wi=2e3,Gc=50,Jc=3,Ri=3,Hc=5,Kc=new Set(["flows","processes","triggers","conditions","definitions"]),Si=new Set(["OwnerId","CreatedById","LastModifiedById","RecordTypeId"]),ct=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function z(n){return n.slice(0,15)}function ne(n){return typeof n=="string"?Date.parse(n):Number.NaN}function ze(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function Yc(n){let e=ne(n?.first),t=ne(n?.last);if(!(!Number.isFinite(e)||!Number.isFinite(t)))return{from:Math.floor((e-Uc)/1e3)*1e3,to:Math.ceil((Math.max(e,t)+zc)/1e3)*1e3}}function Vm(n){if("error"in n)return{creates:[],gaps:{flowsNotRead:0,triggers:0,error:n.error}};let e=[],t=0,r=0;for(let s of n.objects){for(let i of[...s.flows,...s.processes??[]])if(i.startsOn!=="delete"){i.condition!=="read"&&t++;for(let a of i.creates??[])e.some(d=>d.toLowerCase()===a.toLowerCase())||e.push(a)}r+=s.triggers.filter(i=>i.events.some(a=>a!=="beforeDelete"&&a!=="afterDelete")).length}let o=n.unread.filter(s=>Kc.has(s.part)).map(s=>s.reason);return t===0&&r===0&&o.length===0?{creates:e}:{creates:e,gaps:{flowsNotRead:t,triggers:r,...o.length>0?{error:[...new Set(o)].join("; ")}:{}}}}function Gm(n){return e=>Promise.all(e.map(async t=>{let r=n.lane({oneRow:!0});try{let o=await r.query(t);return o.totalSize??o.records.length}catch(o){return{reason:H(o)}}finally{r.close()}}))}async function Zc(n,e,t){let r=new Map,o=0,s;for(let{objectApiName:i,ids:a}of e){if(o>=Jc||r.size>1||t())break;let d=a.slice(0,Gc);if(d.length!==0)try{let[c]=X(d,d.length),f=await n.queryDeleted(`SELECT CreatedById FROM ${J(i)} WHERE Id IN (${c})`),l=!1;for(let p of f.records){let u=p?.CreatedById;typeof u=="string"&&ct.test(u)&&(r.has(z(u))||r.set(z(u),u),l=!0)}l&&o++}catch(c){s??=H(c)}}return r.size===1?{user:[...r.values()][0]}:r.size>1?{refusal:`The run's records were created by ${r.size} different users: whose records came with the run cannot be told, and nothing is swept.`}:{refusal:`The user the run wrote as could not be read: none of its records is left in the org or its recycle bin to tell it${s?` (${s})`:""}. Nothing is swept.`}}async function Qc(n){try{let e=await n.describeGlobal(),t=Array.isArray(e?.sobjects)?e.sobjects:[],r=new Map;for(let o of t){let s=o??{};if(typeof s.name!="string")continue;let i=a=>typeof s[a]=="boolean"?{[a]:s[a]}:{};r.set(s.name.toLowerCase(),{name:s.name,...i("queryable"),...i("deletable"),...i("createable"),...i("layoutable")})}return r}catch{return}}function Xc(n){return n.queryable!==!1&&n.deletable!==!1&&n.createable!==!1&&n.layoutable!==!1&&!Zn.some(e=>e.toLowerCase()===n.name.toLowerCase())}async function Oi(n,e){let t;try{t=await e(n)}catch(i){return{reason:H(i)}}if(t.queryable===!1)return{reason:"The org does not let it be queried."};if(t.deletable!==!0)return{reason:"The org does not let its records be deleted."};let r=new Set(t.fields.map(i=>i.name));if(!r.has("CreatedById")||!r.has("CreatedDate"))return{reason:"It keeps no creator or creation date to tell what the run\u2019s user created in the window: its records go with the records they belong to."};let o=r.has("LastModifiedDate")?"LastModifiedDate":r.has("SystemModstamp")?"SystemModstamp":"CreatedDate",s=t.fields.find(i=>i.nameField===!0)?.name;return{name:t.name,modified:o,...r.has("LastModifiedById")?{modifiedBy:"LastModifiedById"}:{},...s&&s!=="Id"?{nameField:s}:{},references:eu(t)}}function eu(n){return n.fields.filter(e=>e.type==="reference"&&!Si.has(e.name)&&!((e.referenceTo??[]).length>0&&(e.referenceTo??[]).every(t=>Zn.includes(t)))).map(e=>e.name)}function tu(n,e){return`CreatedById = '${n}' AND CreatedDate >= ${ze(e.from)} AND CreatedDate <= ${ze(e.to)}`}function Ai(n,e){return n.length===1?tu(n[0],e):`CreatedById IN (${n.map(t=>`'${t}'`).join(", ")}) AND CreatedDate >= ${ze(e.from)} AND CreatedDate <= ${ze(e.to)}`}async function ki(n,e,t=[]){let r=()=>e.signal?.aborted===!0,o={looked:[],found:[],unread:[],handWork:[],...e.automation.gaps?{automationGaps:e.automation.gaps}:{}},s={listing:o,rows:new Map,stopped:!1},i=Yc(e.writtenBetween);if(!i)return o.refusal="The target did not date this run\u2019s writes: the window its automation wrote in cannot be told, and nothing is swept.",s;s.window=i,s.lastWrite=Math.max(ne(e.writtenBetween?.first),ne(e.writtenBetween?.last)),o.window={from:ze(i.from),to:ze(i.to)};let a=e.runUserId!==void 0&&ct.test(e.runUserId)?e.runUserId:void 0,d=e.user!==void 0&&ct.test(e.user)?e.user:void 0,c=e.created.some(l=>l.ids.length>0),f=a?{user:a}:c?await Zc(n,e.created,r):d!==void 0?{user:d}:{refusal:"The run created nothing, and none of the records it wrote over still says, in its window, who last modified it: the user it wrote as cannot be told, and nothing is swept."};return"refusal"in f?(o.refusal=f.refusal,s.stopped=r(),s):lu(n,e,e.ties,f.user,s,i,t)}function nu(n){return n.map(e=>`${e.objectApiName}: ${e.count}`).join(", ")}async function ru(n,e,t){if(e.length===0)return[];if(n.counts)try{return await n.counts(e)}catch(o){let s=H(o);return e.map(()=>({reason:s}))}let r=[];for(let o of e){if(t()){r.push(void 0);continue}try{r.push((await n.query(o)).totalSize)}catch(s){r.push({reason:H(s)})}}return r}async function ou(n){try{return(await n.query("SELECT Id FROM User WHERE UserType = 'AutomatedProcess'")).records.map(t=>t?.Id).filter(t=>typeof t=="string"&&ct.test(t))}catch{return[]}}async function su(n,e,t,r,o,s){let i=J(e.name),a=[...new Set(["Id","CreatedById","CreatedDate",e.modified,e.modifiedBy,e.nameField,...e.references].filter(l=>l!==void 0).map(J))],d=async l=>(await n.query(l)).records.filter(p=>typeof p=="object"&&p!==null),c=[],f;for(;;){if(s())return{rows:c,overBound:!1,stopped:!0};let l=`SELECT ${a.join(", ")} FROM ${i} WHERE ${Ai([...t.values()],r)}${f?` AND Id > '${f}'`:""} ORDER BY Id LIMIT ${wi}`,p;try{let u=io(l);p=u?await co(await d(u.first),u,d):await d(l)}catch(u){return{reason:H(u)}}for(let u of p){if(typeof u.Id!="string")continue;f=u.Id;let m=typeof u.CreatedById=="string"?z(u.CreatedById):"",g=ne(u.CreatedDate);if(!t.has(m)||!(g>=r.from&&g<=r.to)||o(z(u.Id)))continue;let h=e.modifiedBy?u[e.modifiedBy]:void 0,y=e.nameField?u[e.nameField]:void 0,R=[];for(let S of e.references){let w=u[S];typeof w=="string"&&ct.test(w)&&R.push({field:S,key:z(w)})}if(c.push({id:u.Id,modified:ne(u[e.modified]),created:g,creator:m,references:R,...typeof h=="string"?{modifiedBy:z(h)}:{},...typeof y=="string"&&y.trim()!==""?{name:y.trim().slice(0,80)}:{}}),c.length>Yn)return{rows:c.slice(0,Yn),overBound:!0,stopped:!1}}if(p.length<wi)return{rows:c,overBound:!1,stopped:!1}}}function iu(n){let e=new Map,t=o=>{let s=o.toLowerCase(),i=e.get(s);return i||(i=(async()=>yt.parse(await n.describe(o)))(),i.catch(()=>{}),e.set(s,i)),i},r=async o=>{try{return await t(o)}catch{return}};return{of:t,now:r,async relation(o,s,i){let a=(await r(o))?.childRelationships?.find(d=>d.childSObject.toLowerCase()===s.toLowerCase()&&d.field===i);return{cascade:a?.cascadeDelete===!0,restricted:a?.restrictedDelete===!0}}}}async function au(n,e,t,r,o,s){let i=await Qc(n),a=u=>i?i.get(u.toLowerCase()):{name:u},d=[],c=[],f=u=>d.some(m=>m.toLowerCase()===u.toLowerCase()),l=u=>Zn.some(m=>m.toLowerCase()===u.toLowerCase()),p=(u,m)=>{if(f(u)||l(u))return;let g=a(u)?.name;if(!g){m&&o.unread.push({objectApiName:u,reason:"The org has no such object."});return}if(d.length>=Vc){c.includes(g)||c.push(g);return}d.push(g)};for(let u of e)p(u,!0);for(let u of qc)p(u,!1);for(let u of t)p(u,!0);for(let u of bi)p(u,!1);for(let u of e){if(s())return;for(let m of(await r.now(u))?.childRelationships??[]){let g=a(m.childSObject);g&&Xc(g)&&!f(g.name)&&p(g.name,!1)}}return{looked:d,notLooked:c}}async function du(n,e,t,r,o,s,i){let a=[],d=new Map([...r.keys()].map(c=>[c.toLowerCase(),c]));for(let c of e){let f=((await o.now(c))?.fields??[]).filter(l=>l.type==="reference"&&!Si.has(l.name));for(let l of f)for(let p of l.referenceTo??[]){let u=d.get(p.toLowerCase());if(!u)continue;let m=(r.get(u)??[]).map(y=>y.id),{restricted:g}=await o.relation(u,c,l.name),h=J(l.name);for(let y of X(m)){if(i())return;let R;try{R=(await n.query(`SELECT Id, ${h} FROM ${J(c)} WHERE ${h} IN (${y})`)).records}catch(S){s.unread.push({objectApiName:c,reason:`What its ${l.name} points at among the records found could not be read (${H(S)}): what only it ties is left as tied to nothing.`});continue}for(let S of R){let{Id:w,[l.name]:b}=S??{};typeof w!="string"||typeof b!="string"||t.has(z(w))&&a.push({from:z(w),to:z(b),restricted:g})}}}}return a}async function cu(n,e,t,r){let o=new Map;for(let s of t){let i=e.get(s);i?.kind==="created"&&o.set(i.objectApiName,[...o.get(i.objectApiName)??[],i.id])}for(let[s,i]of o)for(let a of X(i)){if(r())return!1;try{let d=await n.queryDeleted(`SELECT Id, CreatedDate FROM ${J(s)} WHERE Id IN (${a})`);for(let c of d.records){let{Id:f,CreatedDate:l}=c??{},p=typeof f=="string"?e.get(z(f)):void 0,u=ne(l);p&&Number.isFinite(u)&&(p.from=u,p.to=u)}}catch{}}return!0}function uu(n,e,t,r,o,s){let{listing:i}=r,a=new Set(bi.map(u=>u.toLowerCase())),d=[],c=[],f=["made","madeOver","late","untied"];for(let[u,m]of n){let g=[],h=0;for(let b of m){let A=e.get(z(b.id));if(A){if(A.class==="untied"&&a.has(u.toLowerCase())){h++;continue}g.push({id:b.id,modified:b.modified,created:b.created,class:A.class,sameSave:A.sameSave,turn:A.turn,...b.modifiedBy!==void 0?{modifiedBy:b.modifiedBy}:{},...b.name!==void 0?{name:b.name}:{}})}}if(h>0&&i.handWork.push({objectApiName:u,count:h}),g.length===0)continue;let y={made:0,madeOver:0,late:0,untied:0},R=0,S=0,w={};for(let b of g)y[b.class]++,b.sameSave&&R++,$t(b,o,s)&&(S++,w[b.class]=(w[b.class]??0)+1);i.found.push({objectApiName:u,count:g.length,names:f.flatMap(b=>g.filter(A=>A.class===b)).flatMap(b=>b.name?[b.name]:[]).slice(0,Ri),classes:{...y,...R>0?{sameSave:R}:{},...S>0?{changed:S,changedIn:w}:{}}}),y.untied>0&&d.push({objectApiName:u,count:y.untied}),y.late>0&&c.push({objectApiName:u,count:y.late}),r.rows.set(u,g)}let l=[];i.handWork.length>0&&l.push(`The run's user created records in the run's window tied to nothing of the run, on objects people make by hand (${nu(i.handWork)}): hand work, likely, in the same span. They are left, and so is everything tied to nothing: what was made by hand could not be told from what the automation made.`);let p=(t.otherRuns??[]).filter(u=>u.ids.length>0||u.idsUntold===!0).length;p>0&&l.push(`${p===1?"Another run":`${p} other runs`} of this machine wrote to the target in this run\u2019s window: what is tied to nothing of this run may be theirs, and is left.`),l.length>0&&l.push("The runs of another machine, or of a CI, in the same window are not seen."),i.untied={objects:d,...l.length>0?{refusal:l.join(" ")}:{}},i.late=c}async function lu(n,e,t,r,o,s,i){let{listing:a}=o,d=()=>e.signal?.aborted===!0,c=()=>(o.stopped=!0,o),f=ne(e.writtenBetween?.first),l=Math.max(f,ne(e.writtenBetween?.last)),p=Math.min(Number.POSITIVE_INFINITY,...[t.removalBegan,...i.map(F=>F.first)].map(ne).filter(Number.isFinite)),u=Math.ceil((l+9e5)/1e3)*1e3,m={from:s.from,to:Math.max(s.to,Math.min(u,Math.floor(p/1e3)*1e3))},g=new Map,h={from:f,to:l};for(let{objectApiName:F,ids:_}of e.created)for(let x of _)g.set(z(x),{kind:"created",objectApiName:F,id:x,from:Number.NaN,to:Number.NaN});for(let{objectApiName:F,ids:_,between:x}of t.writtenOver??[]){let $=ne(x?.first),q=ne(x?.last);for(let Q of _)g.has(z(Q))||g.set(z(Q),{kind:"overwritten",objectApiName:F,id:Q,from:$,to:q})}let y=[...new Set([...e.created,...t.writtenOver??[]].filter(F=>F.ids.length>0).map(F=>F.objectApiName))],R=new Set([...(t.otherRuns??[]).flatMap(F=>F.ids.map(z)),...(t.leased??[]).map(z)]),S=F=>e.remap.has(F)||g.has(F)||R.has(F),w=await ou(n),b=new Map([[z(r),r]]);for(let F of w)b.has(z(F))||b.set(z(F),F);let A=new Set(w.map(z).filter(F=>F!==z(r))),j=iu(n),L=await au(n,y,e.automation.creates,j,a,d);if(!L)return c();let{looked:v,notLooked:P}=L;a.looked=v,P.length>0&&(a.notLooked=P);let k=await ru(n,v.map(F=>`SELECT COUNT() FROM ${J(F)} WHERE ${Ai([...b.values()],m)}`),d);if(d())return c();let N=new Map,M=[];for(let[F,_]of v.entries()){let x=k[F];if(x===void 0)return c();if(x===0)continue;if(d())return c();let $=await Oi(_,j.of);if("reason"in $){a.unread.push({objectApiName:_,reason:$.reason});continue}if(typeof x=="object"){a.unread.push({objectApiName:_,reason:x.reason});continue}let q=await su(n,$,b,m,S,d);if("reason"in q){a.unread.push({objectApiName:_,reason:q.reason});continue}if(q.stopped)return c();q.overBound?M.push({objectApiName:_,count:q.rows.length,names:q.rows.flatMap(Q=>Q.name?[Q.name]:[]).slice(0,Ri),overBound:!0}):q.rows.length>0&&N.set(_,q.rows)}let D=new Map;for(let{part:F,created:_}of e.otherParts??[])for(let{objectApiName:x,ids:$}of _)for(let q of $)D.set(z(q),{part:F,objectApiName:x});let E=new Map;for(let[F,_]of D.size>0?[...N]:[]){let x=[];for(let $ of _){let q,Q=!1;for(let he of $.references){let Nr=g.get(he.key)??D.get(he.key);if(!Nr)continue;let{cascade:Ia}=await j.relation(Nr.objectApiName,F,he.field);Ia&&(g.has(he.key)?Q=!0:q??=D.get(he.key)?.part)}if(q===void 0||Q){x.push($);continue}let Re=E.get(q)??[],je=Re.find(he=>he.objectApiName===F);je?je.count++:Re.push({objectApiName:F,count:1}),E.set(q,Re)}x.length>0?N.set(F,x):N.delete(F)}E.size>0&&(a.otherParts=[...E].map(([F,_])=>({part:F,objects:_})));let T=new Map;for(let[F,_]of g)T.set(F,_.objectApiName);for(let[F,_]of N)for(let x of _)T.set(z(x.id),F);let I=[],O=new Set;for(let[F,_]of N)for(let x of _){let $=[];for(let q of x.references){let Q=T.get(q.key);if(!Q)continue;g.has(q.key)&&O.add(q.key);let{cascade:Re}=await j.relation(Q,F,q.field);$.push({key:q.key,cascade:Re})}I.push({key:z(x.id),created:x.created,automatedProcess:A.has(x.creator),references:$})}let C=await du(n,y,g,N,j,a,d);if(!C)return c();for(let F of C)O.add(F.from);if(!await cu(n,g,O,d))return c();let B=Eo({anchors:g,candidates:I,pointers:C,runSpan:h,window:s,removalBegan:p,madeEarlier:new Set((t.madeEarlier??[]).map(z)),lateEarlier:new Set((t.lateEarlier??[]).map(z))});return uu(N,B,t,o,l,i),d()?c():(await fu(n,j,o,{user:r,span:m,lastWrite:l,removalSpans:i,isRun:F=>g.has(F)||e.remap.has(F)}),a.found.push(...M),t.muted&&(a.muted=t.muted),o.ordering={query:F=>n.query(F),queryDeleted:F=>n.queryDeleted(F),describe:async F=>await j.now(F)??n.describe(F),describeGlobal:()=>n.describeGlobal(),destroy:(F,_)=>n.destroy(F,_),update:(F,_)=>n.update(F,_),serverTime:()=>n.serverTime(),userId:()=>n.userId()},o)}var yi={untied:0,late:1,madeOver:2,made:3};async function fu(n,e,t,r){let o=new Map;for(let u of t.rows.values())for(let m of u)o.set(z(m.id),m);if(o.size===0||t.rows.has(ce))return;let s=(await To(n,{has:u=>o.has(u)||r.isRun(u),start:r.span.from,end:r.span.to,user:r.user})).filter(u=>!r.isRun(z(u.id))&&u.names.some(m=>o.has(m)));if(s.length===0)return;let i=await Oi(ce,e.of);if("reason"in i){t.listing.unread.push({objectApiName:ce,reason:i.reason});return}let a=new Map,d=s.map(u=>{let m=u.names.flatMap(R=>{let S=o.get(R);return S?[S]:[]});a.set(u.id,m.map(R=>z(R.id)));let g=m.reduce((R,S)=>yi[S.class]<yi[R]?S.class:R,"made"),h=Math.max(...m.map(R=>R.created)),y=u.modifiedBy!==void 0&&z(u.modifiedBy)===z(r.user)&&u.modified<=h+6e4;return{id:u.id,created:u.created,modified:y?Math.min(u.modified,u.created):u.modified,...u.modifiedBy!==void 0?{modifiedBy:z(u.modifiedBy)}:{},class:g,turn:"before"}});t.rows.set(ce,d),t.reports=a;let c={made:0,madeOver:0,late:0,untied:0},f=0,l={};for(let u of d)c[u.class]++,$t(u,r.lastWrite,r.removalSpans)&&(f++,l[u.class]=(l[u.class]??0)+1);let{listing:p}=t;p.found.push({objectApiName:ce,count:d.length,names:[],classes:{...c,...f>0?{changed:f,changedIn:l}:{}}}),c.late>0&&(p.late=[...p.late??[],{objectApiName:ce,count:c.late}]),c.untied>0&&p.untied&&(p.untied={...p.untied,objects:[...p.untied.objects,{objectApiName:ce,count:c.untied}]})}function $t(n,e,t){let r=Math.max(e,n.created)+2e3;return!(n.modified<=r)&&!pu(n,t)}function pu(n,e){return n.modifiedBy!==void 0&&e.some(t=>n.modifiedBy===z(t.userId)&&n.modified>=ne(t.first)&&n.modified<=ne(t.last))}async function Jm(n,e,t=[]){return(await ki(n,e,t)).listing}function mu(n,e){let t=[],r=n.late??[];r.length>0&&e.sweepLate!==!0&&t.push({class:"late",objects:r,option:"--sweep-late"});let{objects:o=[],refusal:s}=n.untied??{};return o.length>0&&(e.sweepUntied!==!0||s!==void 0)&&t.push({class:"untied",objects:o,option:"--sweep-untied",...s!==void 0?{refusal:s}:{}}),t}function Hm(n,e,t){let r=()=>e.signal?.aborted===!0,o=yo(),s=new Set,i=new Set,a=new Set,d=new Set,c=[],f="new",l,p,u,m=new Map,g={unread:[],handWork:[]},h=new Map,y=new Map,R=async(P,k)=>{let N=P.lastWrite??Number.NaN,M=new Set,D=new Map;for(let[C,B]of k){let F=B.filter(_=>t.includeChanged||!$t(_,N,t.removalSpans)).map(_=>_.id);for(let _ of F)M.add(_);D.set(C,F)}if(M.size===0||!P.window)return;let E=new Set(e.created.flatMap(({ids:C})=>C.map(z))),T=P.ordering??n,I=Fo(T,{runStart:P.window.from,runEnd:N,runRecords:{has:C=>E.has(C)},taken:M,removalSpans:t.removalSpans,includeChanged:t.includeChanged,...e.runUserId?{runUserId:e.runUserId}:{}}),O=await wn(T,[...k.keys()].map(C=>({objectApiName:C})));for(let{objectApiName:C}of O){if(C===ce)continue;let B=D.get(C)??[];if(B.length===0)continue;if(r())return;let F=await I(C,B);F.reason!==void 0&&y.set(C,F.reason);for(let _ of B)F.held.has(z(_))&&(M.delete(_),h.set(_,F.holders))}S(P,k,M)},S=(P,k,N)=>{let M=P.reports;if(!M)return;let D=new Set([...k].filter(([E])=>E!==ce).flatMap(([,E])=>E.filter(T=>N.has(T.id)).map(T=>z(T.id))));for(let E of k.get(ce)??[])h.has(E.id)||(M.get(E.id)??[]).every(T=>D.has(T))||(N.delete(E.id),h.set(E.id,["DuplicateRecordItem"]))},w=(P,k)=>{P.result.alreadyGone++,P.along.has(k)&&(P.result.withRemoval=(P.result.withRemoval??0)+1)},b=(P,k,N)=>{k.forEach((M,D)=>{let E=N[D];if((E.lockResends!==void 0||P.lockResent.has(M))&&P.lockResent.set(M,E.kind),E.kind==="refused"){P.refused.set(M,E.reason),E.limit&&P.limited.add(M);return}P.refused.delete(M),P.limited.delete(M),d.add(M),E.kind==="deleted"?P.result.deleted++:w(P,M)})},A=async(P,k,N)=>{for(let M=0;M<k.length;M+=Le){if(r())return!1;let D=k.slice(M,M+Le),E=P.result.deleted,T=await Io(n,P.result.objectApiName,D,o,{stopped:r,settle:(I,O)=>b(P,I,[...O])});if(N&&P.result.deleted>E){let I=P.result.deleted-E;P.result.afterRemoval=(P.result.afterRemoval??0)+I,N==="under"&&(P.result.afterRemovalUnder=(P.result.afterRemovalUnder??0)+I)}if(T)return!1}return!0},j=()=>c.reduce((P,k)=>P+k.result.deleted,0),L=async()=>{let P=g.left??[];if(P.length===0||!u)return;let k=u.rows,N=[],M=[];for(let E of P){let T=[],I=[];for(let O of E.objects){let C=(k.get(O.objectApiName)??[]).filter(_=>_.class===E.class).map(_=>_.id),B=r()?[]:(await yn(C,_=>fe(n,O.objectApiName,[],_),()=>!0)).gone;for(let _ of B)d.add(_);let F=Math.min(B.length,O.count);O.count>F&&T.push({...O,count:O.count-F}),F>0&&I.push({objectApiName:O.objectApiName,count:F})}T.length>0&&N.push({...E,objects:T}),I.length>0&&M.push({class:E.class,objects:I})}if(M.length===0)return;let D={...g};delete D.left,g={...D,...N.length>0?{left:N}:{},goneAlong:M}},v=()=>(p??=(async()=>{let P=await ki(n,e,t.removalSpans);u=P;let{listing:k}=P;if(g={...k.window?{window:k.window}:{},unread:[...k.unread,...k.found.filter(E=>E.overBound).map(E=>({objectApiName:E.objectApiName,reason:`More than ${Yn} records created by the run's user in the window: none is swept, as that many are more than the run\u2019s side effects come to.`}))],...k.automationGaps?{automationGaps:k.automationGaps}:{},handWork:k.handWork},P.stopped){f="cancelled";return}for(let E of P.rows.values())for(let T of E)T.class==="made"||T.class==="madeOver"?i.add(T.id):T.class==="late"&&a.add(T.id);if(k.refusal!==void 0){f="refused",l=k.refusal;return}let N=t.sweepUntied===!0&&k.untied?.refusal===void 0,M=E=>E.class==="made"||E.class==="madeOver"||E.class==="late"&&t.sweepLate===!0||E.class==="untied"&&N;if(m=new Map([...P.rows].map(([E,T])=>[E,T.filter(M)]).filter(([,E])=>E.length>0)),await R(P,m),r()){f="cancelled";return}if(t.approve&&m.size>0){let E=await t.approve(k);if(E!==void 0){f="refused",l=E;return}}let D=mu(k,t);D.length>0&&(g={...g,left:D}),f="asked"})(),p);return{automationMade:s,made:i,late:a,gone:d,get listing(){return u&&!u.stopped?u.listing:void 0},get takes(){return f==="asked"?[...m.keys()]:[]},ask:v,async first(P){if(P&&(o=P),await v(),f!=="asked"||!u)return!1;let k=u,N=m,M=k.lastWrite??Number.NaN,D=await wn(k.ordering??n,[...N.keys()].map(T=>({objectApiName:T}))),E=[];for(let{objectApiName:T}of D){let I=N.get(T)??[],O={result:{objectApiName:T,found:I.length,deleted:0,alreadyGone:0,keptChanged:0,refused:0,reasons:[]},refused:new Map,limited:new Set,later:[],along:new Set,lockResent:new Map};c.push(O);let C=[];for(let B of I){if($t(B,M,t.removalSpans)&&!t.includeChanged){O.result.keptChanged++;continue}let F=h.get(B.id);if(F){O.result.keptDependents=(O.result.keptDependents??0)+1,O.result.heldBy=[...new Set([...O.result.heldBy??[],...F])];continue}s.add(B.id),B.turn==="before"?C.push(B.id):O.later.push(B.id),B.turn==="with"&&O.along.add(B.id)}E.push([O,C])}for(let[T,I]of E)if(!await A(T,I))return f="cancelled",j()>0;return f="first",j()>0},async afterRemoval(P){if(P&&(o=P),f!=="first")return!1;let k=j();for(let N of c){let M=N.later.splice(0),D=M.filter(T=>N.along.has(T)),E=M.filter(T=>!N.along.has(T));if(!await A(N,E,"pointedAt")||!await A(N,D,"under"))return f="cancelled",j()>k}if(j()>0)for(let N of c){let M=[...N.refused.keys()].filter(D=>!N.limited.has(D));if(!await A(N,M))return f="cancelled",j()>k}for(let N of c){if(r())break;let{gone:M}=await yn([...N.refused.keys()],D=>fe(n,N.result.objectApiName,[],D),()=>!0);for(let D of M)N.refused.delete(D),N.lockResent.has(D)&&N.lockResent.set(D,"gone"),w(N,D),d.add(D)}return await L(),f="done",j()>k},result(){if(f==="refused")return{status:"refused",refusal:l??"",objects:[],...g};if(f==="new"||f==="asked")return{status:"cancelled",objects:[],...g};let P=c.map(({result:N,refused:M,lockResent:D})=>{N.refused=M.size;let E=y.get(N.objectApiName);return N.reasons=[...new Set([...E!==void 0&&(N.keptDependents??0)>0?[`What hangs from them could not be read, and they were kept: ${E}`]:[],...jo(N.objectApiName,o),...No(D.values()),...M.values()])].slice(0,Hc),N}),k=c.some(N=>N.later.length>0);return{status:gu(P,f==="cancelled",k,hu(g,t)),objects:P,...g}}}}function gu(n,e,t=!1,r=!1){return e?"cancelled":t||r||n.some(s=>s.keptChanged+(s.keptDependents??0)+s.refused>0)?n.some(s=>s.deleted>0)?"partial":"failure":"success"}function hu(n,e){return(n.left??[]).some(t=>t.class==="late"&&e.sweepLate===!0||t.class==="untied"&&e.sweepUntied===!0)}function Km(n,e,t){if(n.status==="refused")return;let r=o=>n.objects.reduce((s,i)=>s+o(i),0);return{sweptAt:e,deleted:(t?.deleted??0)+r(o=>o.deleted),keptChanged:r(o=>o.keptChanged),refused:r(o=>o.refused)}}function Ym(n){return n.objects.filter(e=>e.deleted+e.refused>0).map(e=>({...ro(e.objectApiName),deleted:e.deleted,failed:e.refused}))}function Zm(n,e){let t=r=>n.objects.reduce((o,s)=>o+r(s),0);return{sweep:!0,forgeId:e,found:t(r=>r.found),deleted:t(r=>r.deleted),keptChanged:t(r=>r.keptChanged),refused:t(r=>r.refused),handWork:n.handWork.reduce((r,o)=>r+o.count,0)}}function Qm(n){return n.found.reduce((e,t)=>e+t.count,0)}function Xm(n){return n.found.map(e=>e.objectApiName)}var wu=15e3,ng=2,yu=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function bu(n,e){try{let{user_id:t}=await new Ot(wu).withTimeout(`${e} run user`,async()=>n());return typeof t=="string"&&yu.test(t)?t:void 0}catch{return}}function rg(n,e,t){n?.runUser&&bu(e,t).then(r=>{r!==void 0&&n.runUser?.(r)})}var Xn=class extends pe{constructor(t){super("SAMPLE_DRAW_INVALID",`${t.join(" ")} Nothing was written, and no root was counted or read: the requests sent before the draw were discovery\u2019s and the target\u2019s.`,void 0,void 0,void 0,{sample:{requests:0}});this.problems=t}problems},Ru=1440*60*1e3,Ii=2,Ti=new Set(["picklist","boolean","reference"]),Su=6,Qn=12;function Ou(n){return n.replace(/'(?:[^'\\]|\\.)*'/g,"''")}function ji(n){return n===void 0?0:Ou(n).match(/\(\s*SELECT\b/gi)?.length??0}function Ve(n,e){let t=e.toLowerCase();return n?.find(r=>r.name.toLowerCase()===t)}function Wt(n){if(n.length===0)return"none";let e=n.slice(0,Qn).join(", ");return n.length>Qn?`${e} and ${n.length-Qn} more`:e}function Au(n,e){if(n.lastDays!==void 0&&n.from===void 0&&n.to===void 0)return{window:{field:n.field,from:Ae(e-n.lastDays*Ru),lastDays:n.lastDays}};let t=s=>{if(s!==void 0)try{return Ae(s)}catch{return null}},r=t(n.from),o=t(n.to);return r===null||o===null?{problem:`The window's bound ${r===null?n.from:n.to} is no instant: write it in UTC, as 2025-07-01T00:00:00Z.`}:r!==void 0&&o!==void 0&&Date.parse(r)>=Date.parse(o)?{problem:`The window starts at ${r} and ends before it, at ${o}: its start is before its end.`}:{window:{field:n.field,...r!==void 0?{from:r}:{},...o!==void 0?{to:o}:{}}}}function Ni(n,e){let t=(n.linksOf.get(e)??[]).find(r=>r.carries&&r.required&&r.prefix===void 0);return t?{field:t.field,parent:t.parent}:void 0}function Fi(n,e,t){let r=t.toLowerCase(),o=(n.linksOf.get(e)??[]).find(s=>s.carries&&s.field.toLowerCase()===r);return o?{parent:o.parent}:void 0}function ku(n,e){let t=(n.fieldsOf(e)??[]).filter(s=>s.groupable!==!1&&Ti.has(s.type??"")&&Fi(n.links,e,s.name)===void 0),r=["RecordTypeId","OwnerId"].flatMap(s=>{let i=Ve(t,s);return i?[i.name]:[]}),o=t.filter(s=>s.type==="picklist").map(s=>s.name).sort();return[...r,...o].slice(0,Su)}function qt(n,e){let t=ku(n,e);return"Its roots are stratified by a field of few values \u2014 a picklist, a checkbox, the record type (RecordTypeId) or the owner (OwnerId)"+(t.length>0?`: of ${e}, ${t.join(", ")}.`:".")}function Ei(n,e,t){let r=n.fieldsOf(e),o=Ve(r,t);if(!o)return{problem:`${e} has no field ${t}. ${qt(n,e)}`};if(!Ti.has(o.type??""))return{problem:(o.type?`${e}.${o.name} is a ${o.type} field, of too many values to stratify by. `:`The describe does not say what type ${e}.${o.name} is, and a stratum is of a known few. `)+qt(n,e)};let s=Fi(n.links,e,o.name);return s?{problem:`${e}.${o.name} names the ${s.parent} a record of ${e} comes under, and a root of ${e} never fills it: it stratifies nothing. `+qt(n,e)}:o.groupable===!1?{problem:`The source does not group ${e} by ${o.name}, which its strata are counted by. ${qt(n,e)}`}:Ve(r,"Id")?.aggregatable===!1?{problem:`The source does not count the records of ${e} by a field (COUNT(Id)), which its strata are counted by: its roots cannot be stratified.`}:{field:o.name}}function Pi(n){let{links:e,options:t}=n,r=[],o;if(t.window!==void 0){let h=Au(t.window,n.now);"problem"in h?r.push(h.problem):o=h.window}let s=[...e.classes].filter(([,h])=>h.kind==="drawn"&&h.rooted).map(([h])=>h).sort(),i=s.filter(h=>!Ni(e,h)),a=new Map([...e.classes.keys()].map(h=>[h.toLowerCase(),h])),d=new Map([...n.excluded??[]].map(h=>[h.toLowerCase(),h])),c=(h,y)=>{let R=y==="where"?"filter on its roots":"strata",S=a.get(h.toLowerCase()),w=S===void 0?void 0:e.classes.get(S);if(S===void 0||w===void 0){let A=d.get(h.toLowerCase());r.push(A!==void 0?`${A} is left out of the run (--exclude-object), and has no root to draw: take it out of one option or the other.`:`${h} is no object of the run, and takes no ${R}. The objects whose roots are drawn are ${Wt(i)}.`);return}if(w.kind==="whole"){r.push(`Every record of ${S} comes, as the sample copies it whole: it has no root drawn, and takes no ${R}. `+(y==="where"?"--filter leaves records of it out of the copy.":`The objects whose roots are drawn are ${Wt(i)}.`));return}if(!w.rooted){r.push(`${S} has no root of its own: its records come as the records the sample keeps name them, and it takes no ${R}. The objects whose roots are drawn are ${Wt(i)}.`);return}let b=Ni(e,S);if(b){r.push(`Every record of ${S} comes under the ${b.parent} it cannot be written without (${b.field}): it has no root, and takes no ${R}. `+(y==="where"?`Filter the roots of ${b.parent} instead: --fit-where "${b.parent}=Id IN (SELECT ${b.field} FROM ${S} WHERE \u2026)".`:`Stratify the roots of ${b.parent} instead.`));return}return S},f=new Map;for(let[h,y]of Object.entries(t.rootWhere??{})){let R=c(h,"where");if(R===void 0)continue;if(f.has(R)){r.push(`The roots of ${R} are given two filters: give one.`);continue}let S=ji(n.filterOf?.(R))+ji(y);if(S>Ii){r.push(`A statement of ${R} takes ${Ii} semi-joins at most (IN (SELECT \u2026)), and its filter and the filter on its roots hold ${S}: write one of them without, or fold them into fewer.`);continue}f.set(R,y.trim())}let l,p=new Map;for(let h of t.strata??[]){let y=h.indexOf(".");if(y<0){l=h;continue}let R=c(h.slice(0,y),"strata");if(R!==void 0){if(p.has(R)){r.push(`The roots of ${R} are stratified by one field at most: give one.`);continue}p.set(R,h.slice(y+1))}}let u=new Map;for(let[h,y]of p){let R=Ei(n,h,y);"problem"in R?r.push(R.problem):u.set(h,R.field)}if(l!==void 0){let h=!1;for(let y of i){if(p.has(y))continue;let R=n.fieldsOf(y),S=Ve(R,l);if(!S||S.groupable===!1||Ve(R,"Id")?.aggregatable===!1)continue;h=!0;let w=Ei(n,y,S.name);"problem"in w?r.push(`${w.problem} Or name each object ${l} stratifies, as Object.${l}.`):u.set(y,w.field)}h||r.push(`No object whose roots are drawn \u2014 ${Wt(i)} \u2014 has a field ${l} it groups by. Name the object and its field, as ${i[0]??"Account"}.RecordTypeId.`)}if(r.length>0)throw new Xn(r);let m=[],g=new Map;for(let h of s){let y=f.get(h),R=u.get(h),S={objectApiName:h,...y!==void 0?{where:y}:{},...R!==void 0?{stratifiedBy:R}:{}};o!==void 0&&(Ve(n.fieldsOf(h),o.field)?S.window={field:o.field,...o.from!==void 0?{from:o.from}:{},...o.to!==void 0?{to:o.to}:{}}:(S.notWindowed=!0,m.push(h))),g.set(h,S)}return{...o!==void 0?{window:o}:{},objects:g,notWindowed:m,where:[...f].map(([h,y])=>({objectApiName:h,where:y})).sort((h,y)=>h.objectApiName<y.objectApiName?-1:1),restricted:o!==void 0||f.size>0,stratified:u.size>0}}function vi(n){return{...n.window!==void 0?{window:n.window}:{},...n.notWindowed.length>0?{notWindowed:[...n.notWindowed]}:{},...n.where.length>0?{where:n.where.map(e=>({...e}))}:{}}}function Iu(n,e){return n.created!==e.created?n.created===void 0?1:e.created===void 0?-1:e.created-n.created:ue(e.id,n.id)}var ju=1e6,er=class extends Error{constructor(t,r){super(`Drawing the sample read ${t} records, more than the ${r} it holds at once. Nothing was written. Lower the bound (--fit-within or --max-total), or leave objects out (--exclude-object) or narrow them (--filter).`);this.rows=t;this.most=r;this.name="SampleTooLarge"}rows;most},tr=class extends Error{constructor(){super("The sample was cancelled before it was drawn. Nothing was written."),this.name="SampleCancelled"}},Nu="AccountId",nr=class{values=[];rows=[];get size(){return this.rows.length}push(e,t){let{values:r,rows:o}=this;r.push(e),o.push(t);let s=o.length-1;for(;s>0;){let i=s-1>>1;if(r[i]<=r[s])break;[r[s],r[i]]=[r[i],r[s]],[o[s],o[i]]=[o[i],o[s]],s=i}}pop(){let{values:e,rows:t}=this,r=[e[0],t[0]],o=e.pop(),s=t.pop();if(t.length>0){e[0]=o,t[0]=s;let i=0;for(;;){let a=2*i+1,d=a+1,c=i;if(a<t.length&&e[a]<e[c]&&(c=a),d<t.length&&e[d]<e[c]&&(c=d),c===i)break;[e[i],e[c]]=[e[c],e[i]],[t[i],t[c]]=[t[c],t[i]],i=c}}return r}},Ut=class{constructor(e,t,r){this.links=e;this.reader=t;this.options=r}links;reader;options;rows=[];objectOf=[];rootOf=[];whole=[];dead=[];out=[];index=new Map;absent=new Map;wholeRead=new Set;below=new Map;cuts=new Map;needs=new Map;waiting=new Map;pending=new Map;upCursor=0;optionalCursor=0;descended=[];toDescend=[];rowOf(e,t){return this.index.get(e)?.get(U(t))}isAbsent(e,t){return this.absent.get(e)?.has(U(t))===!0}wasReadWhole(e){return this.wholeRead.has(e)}alive(e){return this.dead[e]===void 0}get cut(){return this.cuts}belowOf(e){return this.below.get(e)??[]}async openWhole(){let e=new Set;for(let t of this.links.linksOf.values())for(let r of t)r.target==="whole"&&e.add(r.parent);for(let[t,r]of this.links.classes){if(r.kind!=="whole"||r.why==="referenceData"||!(this.links.linksOf.get(t)??[]).some(i=>i.target==="drawn"&&(i.required||this.options.parents==="all"))&&!e.has(t))continue;this.checkSignal();let s=await this.reader.whole(t);this.wholeRead.add(t);for(let i of s){let a=this.register(t,i);this.whole[a]=!0}this.told()}await this.close()}async addRoots(e,t){let r=new Map;e.forEach((o,s)=>{let i=r.get(o.objectApiName)??[];i.push({id:o.id,index:t+s}),r.set(o.objectApiName,i)});for(let[o,s]of[...r].sort(([i],[a])=>i<a?-1:1)){let i=s.filter(({id:a})=>this.rowOf(o,a)===void 0).map(({id:a})=>a).sort(ue);if(i.length>0){this.checkSignal();let a=await this.reader.rows(o,i);for(let d of a)this.register(o,d);this.markAbsent(o,i),this.told()}for(let{id:a,index:d}of s){let c=this.rowOf(o,a);c===void 0||this.rootOf[c]>=0||(this.rootOf[c]=d,this.toDescend.push(c))}}await this.close()}async close(){for(;;)if(await this.readUp(),!await this.readOptionalParents()&&!await this.readDown())return}requiredHere(e,t){return e.required?!0:e.objectApiName===oe&&e.field===Nu&&e.parent===de&&this.rows[t].personAccount===!0}requiredOf(e){let t=this.objectOf[e],{refs:r,also:o}=this.rows[e],s=[],i;for(let a of this.links.linksOf.get(t)??[]){if(!this.requiredHere(a,e))continue;let d=r[a.field];Pe(d,a)&&(a.target==="excluded"?i??="excludedObject":(a.target==="drawn"||this.wholeRead.has(a.parent))&&s.push({objectApiName:a.parent,id:d}))}for(let a of o??[])a.id===null?i??="noParentInSource":this.readable(a.objectApiName)&&s.push({objectApiName:a.objectApiName,id:a.id});return{named:s,...i?{dies:i}:{}}}readable(e){let t=this.links.classes.get(e);return t!==void 0&&(t.kind==="drawn"||this.wholeRead.has(e))}optionalOf(e){let t=this.objectOf[e],{refs:r}=this.rows[e],o=[];for(let s of this.links.linksOf.get(t)??[]){if(s.target!=="drawn"||this.requiredHere(s,e))continue;let i=r[s.field];Pe(i,s)&&o.push({objectApiName:s.parent,id:i})}return o}upTargets(e){let t=this.objectOf[e],{refs:r,also:o}=this.rows[e],s=[];for(let i of this.links.linksOf.get(t)??[]){if(i.target==="excluded"||i.target==="whole"&&!this.wholeRead.has(i.parent)||!this.requiredHere(i,e)&&this.options.parents!=="all")continue;let a=r[i.field];if(!Pe(a,i))continue;let d=this.rowOf(i.parent,a);d!==void 0&&s.push({row:d,field:i.field})}for(let i of o??[]){if(i.id===null||!this.readable(i.objectApiName))continue;let a=this.rowOf(i.objectApiName,i.id);a!==void 0&&s.push({row:a,field:`(${i.objectApiName})`})}return s}async readUp(){for(;;){for(;this.upCursor<this.rows.length;this.upCursor++){let e=this.upCursor,{named:t,dies:r}=this.requiredOf(e);r&&this.kill(e,r);for(let o of t)this.need(e,o)}if(this.pending.size===0)return;await this.readPending()}}async readOptionalParents(){if(this.options.parents!=="all")return!1;for(;this.optionalCursor<this.upCursor;this.optionalCursor++){let e=this.optionalCursor;if(this.alive(e))for(let t of this.optionalOf(e))this.ask(t)}return this.pending.size===0?!1:(await this.readPending(),!0)}async readDown(){let e=new Map,t=this.toDescend;this.toDescend=[];for(let r of t)if(!(this.descended[r]||!this.alive(r))){this.descended[r]=!0;for(let o of this.links.carriersInto.get(this.objectOf[r])??[]){let s=`${o.objectApiName}.${o.field}`,i=e.get(s);i||(i={masterDetail:o.masterDetail,parents:new Map,objects:new Set},e.set(s,i)),i.objects.add(o.parent),i.parents.set(U(this.rows[r].id),r)}}if(e.size===0)return!1;for(let[r,o]of[...e].sort(([s],[i])=>s<i?-1:1)){let s=r.indexOf("."),i={objectApiName:r.slice(0,s),field:r.slice(s+1),parents:[...o.objects].sort(),masterDetail:o.masterDetail},a=i.masterDetail?"all":this.options.children,d=[...o.parents.values()].map(u=>this.rows[u].id).sort(ue);this.checkSignal();let c=await this.reader.children(i,d,a),f=new Map;for(let u of c.rows){let m=u.refs[i.field];if(typeof m!="string"||m==="")continue;let g=o.parents.get(U(m));if(g===void 0)continue;let h=f.get(g)??new Map;h.has(U(u.id))||h.set(U(u.id),u),f.set(g,h)}let l=new Map;for(let[u,m]of c.counts??[])l.set(U(u),m);let p=this.cuts.get(r)??new Map;for(let[u,m]of[...f].sort(([g],[h])=>g-h)){let g=[...m.values()].sort(Iu),h=a==="all"?g:g.slice(0,a),y=this.below.get(u)??[];for(let S of h){let w=this.register(i.objectApiName,S);y.push({child:w,relation:r}),this.descended[w]||this.toDescend.push(w)}this.below.set(u,y);let R=l.get(U(this.rows[u].id))??m.size;R>h.length&&p.set(u,R-h.length)}p.size>0&&this.cuts.set(r,p),this.told()}return!0}need(e,t){let r=this.rowOf(t.objectApiName,t.id);if(r!==void 0){this.tie(r,e);return}if(this.isAbsent(t.objectApiName,t.id)){this.kill(e,"noParentInSource");return}let o=`${t.objectApiName}
|
|
25
|
-
${U(t.id)}`,s=this.waiting.get(o)??[];s.push(e),this.waiting.set(o,s),this.ask(t)}ask(e){if(this.rowOf(e.objectApiName,e.id)!==void 0||this.isAbsent(e.objectApiName,e.id))return;let t=this.pending.get(e.objectApiName)??new Map;t.set(U(e.id),e.id),this.pending.set(e.objectApiName,t)}async readPending(){let e=[...this.pending].sort(([t],[r])=>t<r?-1:1);this.pending.clear();for(let[t,r]of e){let o=[...r.values()].sort(ue);this.checkSignal();let s=await this.reader.rows(t,o);for(let i of s)this.register(t,i);this.markAbsent(t,o),this.told()}}markAbsent(e,t){for(let r of t){if(this.rowOf(e,r)!==void 0)continue;let o=this.absent.get(e)??new Set;o.add(U(r)),this.absent.set(e,o);let s=`${e}
|
|
26
|
-
${U(r)}`;for(let i of this.waiting.get(s)??[])this.kill(i,"noParentInSource");this.waiting.delete(s)}}register(e,t){let r=this.index.get(e);r||(r=new Map,this.index.set(e,r));let o=U(t.id),s=r.get(o);if(s!==void 0)return s;let i=this.rows.length;this.rows.push(t),this.objectOf.push(e),this.rootOf.push(-1),this.whole.push(!1),this.dead.push(void 0),this.out.push(!1),this.descended.push(!1),r.set(o,i);let a=this.options.maxRows??ju;if(this.rows.length>a)throw new er(this.rows.length,a);if(t.outsideFilter)this.out[i]=!0,this.kill(i,"outsideFilter");else if(typeof t.recordTypeId=="string"&&t.recordTypeId!==""){let c=this.options.recordTypeVerdict?.(e,t.recordTypeId);c&&this.kill(i,c)}let d=this.waiting.get(`${e}
|
|
27
|
-
${o}`);if(d){this.waiting.delete(`${e}
|
|
28
|
-
${o}`);for(let c of d)this.tie(i,c)}return i}tie(e,t){let r=this.needs.get(e)??[];r.push(t),this.needs.set(e,r),this.alive(e)||this.kill(t,this.out[e]?"outsideFilter":"withoutParent")}kill(e,t){if(!this.alive(e))return;this.dead[e]=t;let r=[e];for(;r.length>0;){let o=r.pop(),s=this.out[o]?"outsideFilter":"withoutParent";for(let i of this.needs.get(o)??[])this.alive(i)&&(this.dead[i]=s,r.push(i))}}checkSignal(){if(this.options.signal?.aborted)throw new tr}told(){this.options.onRows?.(this.rows.length)}thresholds(e=new Set){let t=this.rows.length,r=new Float64Array(t).fill(1/0),o=new Array(t),s=new Array(t),i=new nr;for(let c=0;c<t;c++){let f=this.rootOf[c];f>=0&&!e.has(f)&&(r[c]=f,i.push(f,c))}let a=new Uint8Array(t);for(;i.size>0;){let[c,f]=i.pop();if(!(a[f]||c>r[f]||!this.alive(f))){a[f]=1;for(let{child:l,relation:p}of this.below.get(f)??[])c<r[l]?(r[l]=c,s[l]=p,i.push(c,l)):c===r[l]&&p<(s[l]??"")&&(s[l]=p)}}let d=new Float64Array(r);for(let c=0;c<t;c++)this.whole[c]&&(d[c]=-1),d[c]!==1/0&&i.push(d[c],c),o[c]=s[c];for(a.fill(0);i.size>0;){let[c,f]=i.pop();if(!(a[f]||c>d[f]||!this.alive(f))){a[f]=1;for(let{row:l,field:p}of this.upTargets(f)){let u=`${this.objectOf[f]}.${p}`;c<d[l]?(d[l]=c,o[l]=u,i.push(c,l)):c===d[l]&&o[l]!==void 0&&u<o[l]&&(o[l]=u)}}}return{threshold:d,above:r,via:o}}};var Mi={bytes:(n,e)=>e.bytes??ss(n,e.personAccount?{IsPersonAccount:!0}:{}),wholeBytes:(n,e)=>ye(n,{rows:e})},Eu=[{objectApiName:oe,field:"AccountId",writes:"AccountContactRelation",ownField:"ContactId",pairField:"AccountId"},{objectApiName:"Opportunity",field:"ContactId",writes:"OpportunityContactRole",ownField:"OpportunityId",pairField:"ContactId"}],Tu=.1,Fu=256,Pu=5;function rr(n,e){return e<0?-1/0:e===1/0?1/0:n[e].rank}function Li(n,e){let t=n.rows[e];return t.matched||t.replaced||n.objectOf[e]===oe&&t.personAccount===!0?0:1}function vu(n,e,t){let r=new Map,{links:o}=n,s=t.filter(i=>o.classes.has(i.writes)&&(o.linksOf.get(i.objectApiName)??[]).some(a=>a.field===i.field));if(s.length===0)return r;for(let i=0;i<n.rows.length;i++)if(n.alive(i))for(let a of s){if(n.objectOf[i]!==a.objectApiName)continue;let d=n.rows[i];if(a.objectApiName===oe&&d.personAccount)continue;let c=d.refs[a.field],f=si(o,a.objectApiName,a.field,c);if(!f||typeof c!="string")continue;let l=n.rowOf(f.parent,c);if(l===void 0||!n.alive(l))continue;let p=Math.max(e.threshold[i],e.threshold[l]);p!==1/0&&r.set(`${a.writes}
|
|
29
|
-
${U(d.id)}
|
|
30
|
-
${U(c)}`,{objectApiName:a.writes,threshold:p,rows:[]})}for(let i=0;i<n.rows.length;i++)if(n.alive(i))for(let a of s){if(n.objectOf[i]!==a.writes)continue;let{refs:d}=n.rows[i],c=d[a.ownField],f=d[a.pairField];if(typeof c!="string"||typeof f!="string")continue;let l=r.get(`${a.writes}
|
|
31
|
-
${U(c)}
|
|
32
|
-
${U(f)}`);l&&l.rows.push(i)}for(let i of r.values())i.rows.sort((a,d)=>e.threshold[a]-e.threshold[d]||ue(n.rows[a].id,n.rows[d].id));return r}function Cu(n,e,t){let{measure:r,draw:o}=t,s=[],i=new Float64Array(n.rows.length),a=new Map,d=(l,p)=>{l>=0&&l!==1/0&&a.set(l,(a.get(l)??0)+p)},c=vu(n,e,t.platformPairs??Eu),f=new Set;for(let l of c.values())l.rows.length>0&&f.add(l.rows[0]);for(let l=0;l<n.rows.length;l++){if(!n.alive(l))continue;let p=n.objectOf[l],u=n.rows[l],m=f.has(l)?0:Li(n,l),h=(u.matched||u.replaced||f.has(l)?0:r.bytes(p,u))+m*(r.roomBytes?.(p)??0);i[l]=h;let y=e.threshold[l];y!==1/0&&(s.push({rank:rr(o.roots,y),bytes:h,records:m,objectApiName:p}),d(y,h))}for(let l of c.values()){let p=r.bytes(l.objectApiName,{id:"",refs:{}});s.push({rank:rr(o.roots,l.threshold),bytes:p,records:0,objectApiName:l.objectApiName}),d(l.threshold,p)}for(let[l,p]of n.links.classes){if(p.kind!=="whole"||n.wasReadWhole(l))continue;let u=t.sourceRows.get(l)??0,m=p.why==="referenceData",g=m?0:u;s.push({rank:-1/0,bytes:(m?0:r.wholeBytes(l,u))+g*(r.roomBytes?.(l)??0),records:g,objectApiName:l})}return s.sort((l,p)=>l.rank-p.rank),{items:s,rowBytes:i,parts:a,pairs:c}}function _i(n,e,t){let r=0,o=0,s=new Map;for(let i of n){if(i.rank>e)break;r+=i.bytes,o+=i.records,t&&i.records>0&&s.set(i.objectApiName,(s.get(i.objectApiName)??0)+i.records)}return{bytes:r,records:o,written:s}}function zt(n,e,t){let r=_i(n,e,t.requests!==void 0);return r.bytes>t.bytes?Is(r.bytes,t):t.maxTotal!==void 0&&r.records>t.maxTotal?"maxTotal":t.requests?.(r.written)}function Ci(n,e,t){let r=Tu*Math.max(0,e.roomBytes),o=new Set;e.draw.floor>0&&e.draw.roots.forEach((i,a)=>{i.rank===0&&o.add(a)});let s=Di(n);for(s!==void 0&&o.add(s);;){let i=n.thresholds(t),a=Cu(n,i,e),d=[...a.parts].filter(([c,f])=>f>r&&!t.has(c)&&!o.has(c)).map(([c])=>c);if(d.length===0)return{thresholds:i,weighed:a};for(let c of d)t.add(c)}}function Di(n){let e;for(let t=0;t<n.rows.length;t++){let r=n.rootOf[t];r>=0&&n.alive(t)&&(e===void 0||r<e)&&(e=r)}return e}function xi(n,e,t,r){let o=_i(e,t,!1),s=new Map;for(let i of e){if(i.rank>t)break;let a=s.get(i.objectApiName)??{rows:0,storageBytes:0};a.rows+=i.records,a.storageBytes+=i.bytes,s.set(i.objectApiName,a)}return{kind:"cannotFit",limitedBy:zt(e,t,r)??r.bytesLimit,rows:o.records,storageBytes:o.bytes,heaviest:[...s].sort(([i,a],[d,c])=>c.storageBytes-a.storageBytes||(i<d?-1:i>d?1:0)).slice(0,Pu).map(([i,a])=>({objectApiName:i,...a,...n.links.classes.get(i)?.kind==="whole"?{whole:!0}:{}}))}}async function Bi(n){let e=n.draw.roots.filter(c=>c.rank<n.draw.beyond),t={...n,draw:{...n.draw,roots:e}},{bounds:r}=t,o=new Ut(t.links,t.reader,{...t.options,onRows:c=>{t.options.onRows?.(c),t.onStep?.("closing",c)}});await o.openWhole();let s=new Set,i=0,a=Fu,d=Ci(o,t,s);for(;i<e.length;){let c=Math.min(e.length,i+a);for(;c<e.length&&e[c].rank===e[c-1].rank;)c++;if(await o.addRoots(e.slice(i,c),i),i=c,a*=2,d=Ci(o,t,s),zt(d.weighed.items,e[i-1].rank,r)!==void 0)break}return t.onStep?.("fitting",o.rows.length),xu(o,d,s,t,e.slice(0,i),i===e.length)}function xu(n,e,t,r,o,s){let{bounds:i,draw:a}=r,{items:d}=e.weighed,c=[...new Set(o.map(h=>h.rank))].sort((h,y)=>h-y),f=a.floor>0&&c[0]===0?c:[-1/0,...c],l=js(f.length,h=>zt(d,f[h-1],i)===void 0);if(l===0)return xi(n,d,f[0],i);let p=f[l-1],u=Di(n);if(u!==void 0&&o[u].rank>p)return{...xi(n,d,o[u].rank,i),noRoot:!0};let m=Lu(n,e,t,r,p),g=l<f.length?zt(d,f[l],i)??i.bytesLimit:!s||a.beyond!==1/0?a.heldBy:m.heavyRoots.length>0?"heavyRoots":a.restricted===!0?"draw":"whole";return{kind:"sample",share:g==="whole"||g==="heavyRoots"||g==="draw"?1:Math.max(0,p),limitedBy:g,wholeOrgFits:Mu(n,r),...m}}function Mu(n,e){let t=0,r=0,o=new Map;for(let[i,a]of n.links.classes){let d=e.sourceRows.get(i)??0;a.kind==="whole"&&a.why==="referenceData"||(t+=e.measure.wholeBytes(i,d),r+=d,o.set(i,d))}let{bounds:s}=e;return t<=s.bytes&&(s.maxTotal===void 0||r<=s.maxTotal)&&s.requests?.(o)===void 0}function Lu(n,e,t,r,o){let{links:s}=n,{thresholds:i,weighed:a}=e,d=r.draw.roots,c=k=>rr(d,k),f=k=>n.alive(k)&&c(i.threshold[k])<=o,l=k=>{if(n.whole[k])return"whole";let N=n.rootOf[k];return N>=0&&!t.has(N)&&c(N)<=o?"root":c(i.above[k])<=o?"below":"parent"},p=new Map,u=k=>{let N=p.get(k);return N||(N={objectApiName:k,sourceRows:r.sourceRows.get(k)??0,kept:0,roots:0,below:0,asParents:0},s.classes.get(k)?.kind==="whole"&&(N.whole=!0),p.set(k,N)),N},m=new Map,g=new Map,h=new Map,y=new Map,R=new Map,S=new Set;for(let k of a.pairs.values())k.rows.length>0&&S.add(k.rows[0]);let w=0,b=0,A=0,j=k=>r.measure.roomBytes?.(k)??0;for(let k=0;k<n.rows.length;k++){let N=n.objectOf[k];if(!n.alive(k)){let T=n.dead[k];if(n.out[k]||T===void 0||c(i.threshold[k])>o)continue;let I=`${N}
|
|
33
|
-
${T}`,O=y.get(I)??{objectApiName:N,rows:0,reason:T};O.rows++,y.set(I,O);continue}if(!f(k))continue;let M=n.rows[k],D=m.get(N)??[];D.push(M.id),m.set(N,D),b+=a.rowBytes[k];let E=S.has(k)?0:Li(n,k);if(w+=E,A+=E*j(N),M.personAccount&&(N===de||N===oe)&&h.set(N,(h.get(N)??0)+1),!M.matched){let T=u(N);T.kept++;let I=l(k);if(I==="root"){T.roots++;let O=g.get(N)??new Set;O.add(U(M.id)),g.set(N,O)}else I==="below"?T.below++:I==="parent"&&T.asParents++}for(let T of s.linksOf.get(N)??[]){if(T.target==="excluded"||T.target==="whole"&&!n.wasReadWhole(T.parent))continue;let I=M.refs[T.field];if(!Pe(I,T))continue;let O=n.rowOf(T.parent,I);if(O!==void 0&&f(O))continue;let C=`${N}
|
|
34
|
-
${T.field}`,B=R.get(C)??{objectApiName:N,field:T.field,rows:0};B.rows++,R.set(C,B)}}for(let[k,N]of s.classes){if(N.kind!=="whole"||n.wasReadWhole(k))continue;let M=r.sourceRows.get(k)??0,D=u(k);D.kept=M,N.why!=="referenceData"&&(w+=M,b+=r.measure.wholeBytes(k,M)+M*j(k),A+=M*j(k))}let L=new Map;for(let k of a.pairs.values()){if(c(k.threshold)>o)continue;let N=L.get(k.objectApiName)??{objectApiName:k.objectApiName,inPlan:0,beyond:0};k.rows.length>0&&f(k.rows[0])?N.inPlan++:N.beyond++,b+=r.measure.bytes(k.objectApiName,{id:"",refs:{}}),L.set(k.objectApiName,N)}for(let[k,N]of n.cut){let M=0;for(let[T,I]of N)f(T)&&c(i.above[T])<=o&&(M+=I);if(M===0)continue;let D=k.indexOf("."),E=u(k.slice(0,D));E.childrenCut=[...E.childrenCut??[],{field:k.slice(D+1),rows:M}]}let v=[...p.values()].filter(k=>k.kept>0).sort((k,N)=>N.kept-k.kept||(k.objectApiName<N.objectApiName?-1:1)),P=[...s.classes].filter(([k,N])=>{let M=r.sourceRows.get(k)??0;return N.kind==="drawn"&&M>0&&(p.get(k)?.kept??0)===0}).map(([k])=>({objectApiName:k,sourceRows:r.sourceRows.get(k)??0})).sort((k,N)=>k.objectApiName<N.objectApiName?-1:1);return{rows:v.reduce((k,N)=>k+N.kept,0),storageBytes:b,automationBytes:A,written:w,objects:v,heavyRoots:Du(n,e,t,d,o),dropped:[...y.values()].sort(or(k=>k.reason)),leftEmpty:[...R.values()].sort(or(k=>k.field)),noRecordDrawn:P,partialMasters:_u(s,p,r.sourceRows),ids:new Map([...m].map(([k,N])=>[k,N.sort(ue)])),rootIds:g,personAccounts:h,byThePlatform:[...L.values()].sort((k,N)=>k.objectApiName<N.objectApiName?-1:1)}}function _u(n,e,t){let r=[];for(let[o,s]of n.linksOf){if(n.classes.get(o)?.kind!=="drawn")continue;let i=e.get(o)?.kept??0;for(let a of s){if(!a.masterDetail||a.target==="excluded"||a.parent===o)continue;let d=e.get(a.parent);if(!d||d.kept===0)continue;let c={objectApiName:a.parent,details:o,field:a.field};if(a.target==="whole"){let f=t.get(o)??0;i<f&&r.push({...c,kept:i,sourceRows:f})}else a.carries&&d.asParents>0&&r.push({...c,asParents:d.asParents})}}return r.sort(or(o=>`${o.details}
|
|
35
|
-
${o.field}`))}function or(n){return(e,t)=>{if(e.objectApiName!==t.objectApiName)return e.objectApiName<t.objectApiName?-1:1;let r=n(e),o=n(t);return r<o?-1:r>o?1:0}}function Du(n,e,t,r,o){let s=[...t].filter(a=>r[a].rank<=o).sort((a,d)=>a-d);if(s.length===0)return[];let i=[];for(let a of s){let d=new Set(t);d.delete(a);let c=n.thresholds(d),f=0,l=new Map;for(let m=0;m<n.rows.length;m++){if(!n.alive(m)||c.threshold[m]!==a)continue;f++;let g=c.via[m];g!==void 0&&l.set(g,(l.get(g)??0)+e.weighed.rowBytes[m])}let[p]=[...l].sort(([m,g],[h,y])=>y-g||(m<h?-1:m>h?1:0))[0]??[`${r[a].objectApiName}.Id`],u=p.indexOf(".");i.push({objectApiName:r[a].objectApiName,id:r[a].id,rows:f,relation:{objectApiName:p.slice(0,u),field:p.slice(u+1)}})}return i}var $i=50;function sr(n){return n===null?"none":typeof n=="boolean"?n?"true":"false":`=${n}`}function Wi(n,e){return(n+.5)/Math.max(e,n+1)}function qi(n,e,t){let r=n.reduce((s,i)=>s+Math.max(0,i),0),o=Math.max(0,e)+n.length;return n.map(s=>s<=0?0:Math.min(s,Math.ceil(o*s/r)+1+Math.max(0,t)))}var Vt=class{constructor(e){this.input=e;for(let t of e.strata){let r=sr(t.value),o=this.strata.get(r);if(o){o.counted+=Math.max(0,t.roots),o.take+=Math.max(0,t.take);continue}this.strata.set(r,{key:r,value:t.value,counted:Math.max(0,t.roots),scanned:0,take:Math.max(0,t.take),heap:new Sn,read:[]})}}input;strata=new Map;get objectApiName(){return this.input.objectApiName}get field(){return this.input.field}reads(){return[...this.strata.values()].filter(e=>e.take>0).sort((e,t)=>e.key<t.key?-1:e.key>t.key?1:0).map(e=>({value:e.value,key:e.key,roots:e.counted,take:e.take}))}scanned(e,t){let r=sr(t),o=this.strata.get(r);o||(o={key:r,value:t,counted:0,scanned:0,take:Math.max(0,this.input.floor)+2,heap:new Sn,read:[]},this.strata.set(r,o)),o.scanned++,o.heap.push({objectApiName:this.input.objectApiName,id:e,rank:jt(this.input.seed,e)}),o.heap.size>o.take&&o.heap.pop()}read(e,t){let r=this.strata.get(sr(e));if(!r)throw new Error(`${this.input.objectApiName}.${this.input.field} was not counted with that value: its roots are not read.`);r.read.push(...t)}rootsOf(e){return this.input.draw==="uniform"?e.scanned:e.counted}orderOf(e){return this.input.draw!=="uniform"?e.read:[...e.heap.values()].sort(Qo).map(t=>t.id)}ranked(){let e=[];for(let t of this.strata.values()){let r=this.rootsOf(t);this.orderOf(t).forEach((o,s)=>{e.push({id:o,rank:Wi(s,r),stratum:t.key})})}return e}get firstUnread(){let e=1/0;for(let t of this.strata.values()){let r=this.input.draw==="uniform";if(!(r?t.scanned>t.take:t.read.length>=t.take&&t.take<t.counted))continue;let s=r?t.take:t.read.length;e=Math.min(e,Wi(s,this.rootsOf(t)))}return e}report(e,t){let r=[...this.strata.values()].map(s=>{let i=t?.(s.value);return{key:s.key,entry:{value:s.value,...i!==void 0?{label:i}:{},roots:this.rootsOf(s),kept:this.orderOf(s).filter(a=>e(a)).length}}}).sort((s,i)=>s.entry.roots!==i.entry.roots?i.entry.roots-s.entry.roots:s.key<i.key?-1:s.key>i.key?1:0),o=r.length-$i;return{objectApiName:this.input.objectApiName,field:this.input.field,values:r.slice(0,$i).map(s=>s.entry),...o>0?{more:o}:{}}}};var Ui=class extends Error{constructor(t,r,o){super(r);this.code=t;this.heaviest=o;this.name="SampleRefusedError"}code;heaviest},ir=[mt,Ce,ht,gt,"IsActive"];function zi(n){return n===!0||n==="true"}function Gt(n){return typeof n=="string"&&n!==""?n:null}function Bu(n){let e=n.CreatedDate,t=typeof e=="string"?Date.parse(e):Number.NaN;return Number.isFinite(t)?t:void 0}function Vi(n){let e=t=>{let r=n[t];return typeof r=="string"?U(r):""};return[e(mt),e(Ce),e(gt)].join(`
|
|
36
|
-
`)}function Gi(n){let e=t=>{let r=n[t];return typeof r=="string"?r:""};return[U(e(Ce)),e(ht),U(e(gt))].join(`
|
|
37
|
-
`)}var ar=class{constructor(e,t,r,o){this.reader=e;this.links=t;this.sourceRows=r;this.priceCurrencyWrittenIn=o}reader;links;sourceRows;priceCurrencyWrittenIn;cappedByIds=new Set;columnsOf(e){let t=[...Gn(this.links,e),"RecordTypeId"];return(e===de||e===oe)&&t.push("IsPersonAccount"),e===Xe&&t.push(...ir),e===cn&&t.push("IsStandard"),t}rowOf(e,t,r=!1){let o={};for(let a of Gn(this.links,e))o[a]=Gt(t[a]);let s=t.RecordTypeId,i=Bu(t);return{id:String(t.Id),refs:o,...typeof s=="string"||s===null?{recordTypeId:Gt(s)}:{},...(e===de||e===oe)&&zi(t.IsPersonAccount)?{personAccount:!0}:{},...e===cn&&zi(t.IsStandard)?{matched:!0}:{},...r?{outsideFilter:!0}:{},...i!==void 0?{created:i}:{}}}async sampleRowsOf(e,t,r=[]){let o=[...t.map(f=>this.rowOf(e,f)),...r.map(f=>this.rowOf(e,f,!0))];if(e!==Xe||t.length===0)return o;let s=[...new Set(t.flatMap(f=>{let l=Gt(f[Ce]);return l?[l]:[]}))],i=await this.reader.readStandardPrices(s,ir.slice(1)),a=new Set(i.map(f=>U(String(f.Id)))),d=new Map;for(let f of i)d.set(Gi(f),String(f.Id));let c=await this.pricesWrittenFor(t);return o.map((f,l)=>{let p=t[l];if(p===void 0)return f;let u=[];a.has(U(f.id))||u.push({objectApiName:Xe,id:d.get(Gi(p))??null});let m=c.get(f.id);return m!==void 0&&u.push({objectApiName:Xe,id:m}),u.length===0?f:{...f,also:u,...m!==void 0?{replaced:!0}:{}}})}async pricesWrittenFor(e){let t=new Map,r=this.priceCurrencyWrittenIn;if(!r)return t;let o=new Map;for(let s of e){let i=s[ht];if(typeof i!="string")continue;let a=r(i);a===void 0||a===i||o.set(a,[...o.get(a)??[],s])}for(let[s,i]of o){let a=f=>i.flatMap(l=>{let p=Gt(l[f]);return p?[p]:[]}),d=await this.reader.readPricesIn(s,a(Ce),a(mt),ir),c=new Map(d.map(f=>[Vi(f),String(f.Id)]));for(let f of i){let l=c.get(Vi(f));l!==void 0&&t.set(String(f.Id),l)}}return t}async rows(e,t){let[r]=await this.reader.readParents([{objectApiName:e,ids:t,columns:this.columnsOf(e)}]);return r?this.sampleRowsOf(e,r.rows,r.outsideFilter):[]}async children(e,t,r){let[o]=await this.reader.readChildren([{objectApiName:e.objectApiName,field:e.field,parentIds:t,columns:this.columnsOf(e.objectApiName),cap:r,sourceRows:this.sourceRows.get(e.objectApiName)??Number.MAX_SAFE_INTEGER}]);return o?(o.newestBy==="id"&&o.cut.some(s=>s.rows>0)&&this.cappedByIds.add(e.objectApiName),{rows:await this.sampleRowsOf(e.objectApiName,o.rows),counts:o.counts}):{rows:[]}}async whole(e){let t=[];return await this.reader.readWhole([{objectApiName:e,columns:this.columnsOf(e)}],(r,o)=>{for(let s of o)t.push(s)}),this.sampleRowsOf(e,t)}};function $u(n,e){let{empty:t,told:r}=oi(n,e),o=n.linksOf.get(e)??[];return[...t.map(s=>({field:s})),...r.map(s=>({field:s,drawnPrefixes:new Set(o.flatMap(i=>i.field===s&&i.carries&&typeof i.prefix=="string"?[i.prefix]:[]))}))]}function Wu(n){let e=n.field==="LastModifiedDate"?"last modified":"made";if(n.lastDays!==void 0)return`roots ${e} in the last ${n.lastDays} days`+(n.from!==void 0?`, from ${n.from}`:"");let t=n.from!==void 0?` from ${n.from}`:"",r=n.to!==void 0?` to before ${n.to}`:"";return`roots ${e}${t}${r}`}function qu(n,e,t){let r=[...n.window?[Wu(n.window)]:[],...n.where.map(({objectApiName:i,where:a})=>`${i} where ${a}`)],o=e.filter(i=>(i.inTheSource?.rows??0)>0).map(i=>`${i.objectApiName} ${i.inTheSource?.exact===!1?"at most ":""}${i.inTheSource?.rows??0}`),s=[...n.window?["widen the window (--fit-window)"]:[],...n.where.length>0?["loosen the filters on the roots (--fit-where)"]:[],"draw without them"].join(", or ");return new pe("SAMPLE_DRAW_EMPTY",`No object has a root in the draw: ${r.join("; ")}.`+(n.notWindowed.length>0?` The window does not date ${n.notWindowed.join(", ")}, which have no root in it.`:"")+(o.length>0?` The source holds roots outside them: ${o.join(", ")}.`:"")+` Nothing was written, and the counts sent ${t} request(s) of the source. ${s.charAt(0).toUpperCase()}${s.slice(1)}.`,void 0,void 0,void 0,{sample:{requests:t}})}function Uu(n,e){let t=e.restricted?"narrow the window or the filters on the roots (--fit-window, --fit-where)":"draw among fewer roots (--fit-window, --fit-where)";return n==="uniform"?`Draw the most recent records (--fit-draw recent) or the oldest (--fit-draw oldest), ${t}, or narrow the large objects (--filter).`:`${t.charAt(0).toUpperCase()}${t.slice(1)}`+(e.stratified?", stratify fewer objects (--fit-strata)":"")+", narrow the large objects (--filter), or draw it once the source has more to spare."}async function Fg(n){let{options:e,budget:t}=n,r=I=>n.averageBytes?.get(I),o=(I,O)=>{let C=r(I);return C!==void 0?O*C:ye(I,{rows:O})},s=new Map(n.objects.flatMap(I=>I.rows===void 0?[]:[[I.objectApiName,I.rows]])),i=Lt({objects:n.objects,order:n.order,...n.excluded?{excluded:n.excluded}:{},...n.referenceData?{referenceData:n.referenceData}:{},...e.whole?{whole:e.whole}:{},roomBytes:t.roomBytes,...n.maxRecordsPerObject!==void 0?{maxRecordsPerObject:n.maxRecordsPerObject}:{},wholeBytes:(I,O)=>o(I,O)}),a=Pi({options:{...e.window?{window:e.window}:{},...e.rootWhere?{rootWhere:e.rootWhere}:{},...e.strata?{strata:e.strata}:{}},now:n.now??Date.now(),links:i,...n.excluded?{excluded:n.excluded.keys()}:{},fieldsOf:I=>n.fieldsOf(I),...n.filterOf?{filterOf:n.filterOf}:{}}),d=(I,O)=>n.fieldsOf(I)?.find(C=>C.name.toLowerCase()===O.toLowerCase()),c=new Dt(n.source,{fieldsOf:I=>n.fieldsOf(I)?.map(O=>O.name),...n.filterOf?{filterOf:n.filterOf}:{},countsBy:(I,O)=>{let C=d(I,"Id")?.aggregatable,B=d(I,O)?.groupable;return C===!1||B===!1?!1:C===!0&&B===!0?!0:void 0},sorts:(I,O)=>d(I,O)?.sortable,...n.onProgress?{onProgress:n.onProgress}:{},...n.signal?{signal:n.signal}:{}}),f=[...i.classes].filter(([,I])=>I.kind==="drawn"&&I.rooted).map(([I])=>I).sort(),l=f.filter(I=>a.objects.get(I)?.notWindowed!==!0).map(I=>{let O=a.objects.get(I);return{objectApiName:I,carriers:$u(i,I),...O?.window?{window:O.window}:{},...O?.where!==void 0?{where:O.where}:{},...O?.stratifiedBy!==void 0?{stratifiedBy:O.stratifiedBy}:{}}}),p=await c.countRoots(l),u=Nt(t.budget.bytes,t.budget.maxTotal),m=new Map;p.forEach((I,O)=>{let C=l[O].stratifiedBy;if(C===void 0||!I.strata)return;let B=qi(I.strata.map(F=>F.rows),u,e.floor);m.set(I.objectApiName,new Vt({objectApiName:I.objectApiName,field:C,strata:I.strata.map((F,_)=>({value:F.value,roots:F.rows,take:B[_]})),draw:e.draw,seed:e.seed,floor:e.floor}))});let g=I=>m.get(I.objectApiName)?.reads()??Math.min(I.rows,u),h=p.reduce((I,O)=>I+Bt(O,e.draw,g(O)),0),y=n.sourceRequestsLeft;if(y!==void 0&&c.requests+h>Math.floor(ke*y)){let I=c.requests+h;throw new pe(as,`Drawing the sample reads about ${I} requests of the source, more than a tenth of the ${y} it has left today. Nothing was written, and no id was read past the counts. ${Uu(e.draw,a)}`,void 0,void 0,void 0,{api:{kind:"requests",org:"source",estimate:I,remaining:y,drawing:{share:ke,draw:e.draw,...a.restricted?{restricted:!0}:{}}}})}let R=new Xo(u,e.floor),S=[],w=new Map,b=new Map;if(e.draw==="uniform")await c.drawUniform(l,(I,O,C)=>{w.set(I,(w.get(I)??0)+O.length);let B=m.get(I);if(B){for(let F of O)B.scanned(F,C??null);return}for(let F of O)R.offer(I,F,jt(e.seed,F))});else{let I=new Map(p.map(C=>[C.objectApiName,C.rows]));S=(await c.drawByDate(p.map((C,B)=>({...l[B],take:g(C)})),e.draw,(C,B,F)=>{let _=m.get(C);if(_){_.read(F??null,B);return}let x=b.get(C)??0;for(let $ of B)R.offer(C,$,Rn(x,I.get(C)??0)),x++;b.set(C,x)})).filter(C=>C.by==="id").map(C=>C.objectApiName);for(let C of p){if(m.has(C.objectApiName))continue;let B=Math.min(C.rows,u);B<C.rows&&(b.get(C.objectApiName)??0)>=B&&R.leftUnread(Rn(B,C.rows))}}for(let I of m.values()){for(let O of I.ranked())R.offer(I.objectApiName,O.id,O.rank,O.stratum);R.leftUnread(I.firstUnread)}let A=R.drawn();if(a.restricted&&A.length===0)throw qu(a,p,c.requests);let{maxTotal:j}=t.budget,L=j!==void 0&&j<Math.floor(t.budget.bytes/Zo)?"maxTotal":t.bytesLimit,v=new ar(c,i,s,n.priceCurrencyWrittenIn),P=await Bi({links:i,reader:v,draw:{roots:A,beyond:R.beyond,heldBy:L,floor:e.floor,...a.restricted?{restricted:!0}:{}},sourceRows:s,options:{parents:e.parents,children:e.children,...n.recordTypeVerdict?{recordTypeVerdict:n.recordTypeVerdict}:{},...n.maxRows!==void 0?{maxRows:n.maxRows}:{},...n.signal?{signal:n.signal}:{}},measure:{bytes:(I,O)=>O.bytes??r(I)??Mi.bytes(I,O),wholeBytes:o,...t.automationBytes?{roomBytes:t.automationBytes}:{}},bounds:{bytes:t.budget.bytes,bytesLimit:t.bytesLimit,...t.storageBytes!==void 0?{storageBytes:t.storageBytes}:{},...j!==void 0?{maxTotal:j}:{},...t.requests?{requests:t.requests}:{}},roomBytes:t.roomBytes,onStep:(I,O)=>n.onProgress?.({step:I,rows:O,requests:c.requests})}),k=[...new Set([...e.draw==="recent"?S:[],...v.cappedByIds])].sort(),N=e.draw==="oldest"?[...S].sort():[],M=new Map,D=new Set;for(let I of f){let O=a.objects.get(I);if(!O||O.window===void 0&&O.where===void 0&&!O.notWindowed)continue;let C=p.find(x=>x.objectApiName===I),B=x=>{let $=b.get(I)??0;return!m.has(I)&&$<Math.min(x.rows,u)?$:void 0},F=O.notWindowed||!C?0:e.draw==="uniform"?w.get(I)??0:C.exact&&C.timedOut!==!0?C.rows:B(C),_=C?.inTheSource?.exact===!0?C.inTheSource.rows:void 0;M.set(I,{...F!==void 0?{inTheDraw:F}:{},..._!==void 0?{inTheSource:_}:{}}),F===0&&(O.notWindowed||(_??C?.inTheSource?.rows??0)>0)&&D.add(I)}let E;if(a.restricted||a.stratified){let I=[];for(let O of m.values()){let C=P.kind==="sample"?P.rootIds.get(O.objectApiName):void 0,B=await n.labelsOf?.(O.objectApiName,O.field);I.push(O.report(F=>C?.has(U(F))===!0,B))}E={...vi(a),...I.length>0?{strata:I}:{}}}let T;if(e.floor>0&&m.size>0){let I=0,O=0;for(let C of m.values())for(let B of C.reads())I++,O+=Math.min(B.roots,e.floor);I>0&&(T={roots:O,values:I})}return{links:i,cut:P,planRequests:c.requests,newestByIds:k,oldestByIds:N,...E?{roots:E}:{},rootsCounted:M,noRootInTheDraw:D,...T?{strataFloors:T}:{}}}function Ji(n){if(!n)return;let e=(n.where??[]).map(o=>o.objectApiName),t=(n.strata??[]).map(o=>`${o.objectApiName}.${o.field}`),r={...n.window?{window:{...n.window}}:{},...e.length>0?{whereObjects:e}:{},...t.length>0?{strataFields:t}:{}};return Object.keys(r).length>0?r:void 0}function Pg(n,e,t){let{cut:r,links:o}=n;return{seed:e.seed,draw:e.draw,floor:e.floor,parents:e.parents,children:e.children,share:r.share,budget:{...t,...r.automationBytes>0?{automationMB:r.automationBytes/1048576}:{},limitedBy:r.limitedBy},rows:r.rows,storageBytes:r.storageBytes,objects:r.objects.map(s=>{let i=n.rootsCounted.get(s.objectApiName);return i?{...s,...i.inTheSource!==void 0?{rootsInTheSource:i.inTheSource}:{},...i.inTheDraw!==void 0?{rootsInTheDraw:i.inTheDraw}:{}}:s}),whole:o.whole,heavyRoots:r.heavyRoots,dropped:r.dropped,leftEmpty:r.leftEmpty,noRecordDrawn:r.noRecordDrawn.map(s=>n.noRootInTheDraw.has(s.objectApiName)?{...s,noRootInTheDraw:!0}:s),...n.roots?{roots:n.roots}:{},...r.partialMasters.length>0?{partialMasters:r.partialMasters}:{},planRequests:{source:n.planRequests},...n.newestByIds.length>0?{newestByIds:[...n.newestByIds]}:{},...n.oldestByIds.length>0?{oldestByIds:[...n.oldestByIds]}:{}}}var zu=30*6e4,Vu=16,Gu=["map_value","leave_empty","set_default","truncate","map_record_type","exclude_object","skip_rows","ignore"];function Mg(n,e){return JSON.stringify([e.sourceOrgId,e.targetOrgId,e.inputMode,e.recordId??null,e.soqlQuery??null,e.templateId??null,e.aiPrompt??null,n.nodes.map(t=>t.objectApiName).sort(),...e.queryScope==="records"?["records"]:[]])}var Hi=class{tried=new Map;note(e,t,r=Date.now()){let o=this.tried.get(t)??{};this.tried.delete(t),this.tried.set(t,{...o,[e]:r});for(let s of this.tried.keys()){if(this.tried.size<=Vu)break;this.tried.delete(s)}}before(e,t=Date.now()){let r=this.tried.get(e),o=a=>a===void 0||t-a>zu||t<a?void 0:Math.max(1,Math.ceil((t-a)/6e4)),s=o(r?.simulation),i=o(r?.rehearsal);return{...s!==void 0?{simulatedMinutesBefore:s}:{},...i!==void 0?{rehearsedMinutesBefore:i}:{}}}};function Ju(n){let e={flow:0,trigger:0,process:0,workflowRule:0,unread:[]};if(!("automation"in n))return{...e,unread:["automation"]};for(let t of gs(n.automation))e[t.kind]++;return e.unread=ws(n.automation).map(t=>t.part),e}function Hu(n,e){let t={flow:0,trigger:0,process:0,workflowRule:0};if(!("automation"in n))return t;let r=e.map(o=>o.objectApiName);for(let o of hs(n.automation,r))t[o.kind]++;return t}function Ku(n,e=[]){let t=new Map,r=(i,a)=>{a>0&&t.set(i,(t.get(i)??0)+a)},o=n.picklistValueMappings??[];r("map_value",o.filter(i=>i.to!==null).length),r("leave_empty",o.filter(i=>i.to===null).length),r("leave_empty",Object.values(n.fieldExclusions??{}).reduce((i,a)=>i+a.length,0)),r("set_default",n.defaultValues?.length??0),r("truncate",n.truncateFields?.length??0),r("map_record_type",n.recordTypeMappings?.length??0),r("exclude_object",n.excludedObjects?.length??0),r("skip_rows",n.skippedRows?.length??0),r("ignore",n.ignoredGaps?.length??0);let s=new Map;for(let i of e)s.set(i.kind,(s.get(i.kind)??0)+i.rows);return Gu.filter(i=>t.has(i)||s.has(i)).map(i=>({kind:i,count:t.get(i)??0,...s.has(i)?{rows:s.get(i)}:{}}))}function Yu(n){let e=n.objects.reduce((r,o)=>r+o.sourceRows,0)+n.noRecordDrawn.reduce((r,o)=>r+o.sourceRows,0),t=Ji(n.roots);return{module:"forge",share:n.share,...n.budget.withinMB!==void 0?{withinMB:n.budget.withinMB}:{},seed:n.seed,draw:n.draw,limitedBy:n.budget.limitedBy,...t?{roots:t}:{},kept:n.rows,inSource:e}}var Ki=class{constructor(e,t){this.config=e;this.before=t}config;before;confirmed=[];fired;firedOnUpdate;deliverability;sampleFit;automationRead(e,t=[]){this.fired=Ju(e),this.firedOnUpdate=Hu(e,t)}emailsRead(e){this.deliverability=e}confirm(e){this.confirmed.includes(e)||this.confirmed.push(e)}sampled(e){this.sampleFit=Yu(e)}fit(){return this.sampleFit?{...this.sampleFit}:void 0}context(e){let t=Ku(this.config,e);return{anonymized:this.config.anonymizePII,contactPoints:this.config.keepContactPoints===!0?"kept":"neutralized",...this.before,...this.fired?{firedOnInsert:{...this.fired,unread:[...this.fired.unread]}}:{},...this.firedOnUpdate?{firedOnUpdate:{...this.firedOnUpdate}}:{},...this.confirmed.length>0?{confirmed:[...this.confirmed]}:{},...t.length>0?{decisions:t}:{},...this.deliverability!==void 0?{deliverability:this.deliverability}:{}}}};var Zu=V({...Mo,journalId:W().min(1).max(200),ranFrom:ve(["commandLine","editor"]),target:W().min(1).max(255).optional(),resumes:Ke().optional(),removes:Ke().optional()}),Yi=Lo(n=>{let e=Zu.safeParse(n);return e.success?e.data:void 0});function Zi(n){return`${n.replace(/\.ndjson$/,"")}.lock`}function Qi({version:n,token:e,...t}){return t}function Dg(n,e,t={}){let r=Yi.acquire(Zi(n),o=>({...o,journalId:e.journalId.slice(0,200),ranFrom:e.ranFrom,...e.target!==void 0&&e.target!==""?{target:e.target.slice(0,255)}:{},...e.resumes?{resumes:!0}:{},...e.removes?{removes:!0}:{}}),t);return"busy"in r?{busy:Qi(r.busy)}:r}function Bg(n,e={}){let t=Yi.holder(Zi(n),e);return t!==void 0?Qi(t):void 0}function $g(n){let e=n.ranFrom==="commandLine"?"from the command line":"in VS Code";if(n.removes){let o=n.target!==void 0?` from ${n.target}`:"";return`a removal of the run ${n.journalId} deletes what it wrote${o}: started ${e} at ${n.acquiredAt} (process ${n.pid} on ${n.host})`}let t=n.target!==void 0?` to ${n.target}`:"",r=n.resumes?", taking up an earlier part of it":"";return`the run ${n.journalId} still writes this journal: started ${e}${t} at ${n.acquiredAt} (process ${n.pid} on ${n.host})${r}`}function Wg(n){return n.removes&&n.ranFrom==="editor"?"let it end on the Forge page that removes it":n.ranFrom==="commandLine"?"stop it with Ctrl-C in the terminal it runs in, or let it end":"stop it on the Forge page that runs it, or let it end"}var Qu="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Xu="RHZ",el=/[A-Za-z0-9]{3}RHZ[A-Za-z0-9]{12}/g,dr="000",Xi=62**8;function Jt(n,e){let t=n!==null&&/^[A-Za-z0-9]{3}$/.test(n)?n:dr,r="";for(let s=e;r.length===0||s>0;s=Math.floor(s/62))r=Qu[s%62]+r;let o=bt(`${t}${Xu}${r.padStart(9,"0")}`);if(o===void 0)throw new Error(`No placeholder id for record ${e}`);return o}var Ht=class{constructor(e,t){this.keyPrefixOf=e;this.runningUser=t}keyPrefixOf;runningUser;rows=[];updated=[];byId=new Map;personContacts=new Map;platformTeam=new Map;platformRoles=new Map;prefixes=new Map;writesAs;insertRecords=async(e,t,r)=>{let o=await this.prefixOf(t);return r.map(s=>{let i=this.rows.length,a={seq:i,objectApiName:t,fields:{...s},placeholderId:Jt(o,i)};return this.rows.push(a),this.byId.set(a.placeholderId.slice(0,15),a),{id:a.placeholderId,success:!0,errors:[]}})};get updates(){return this.updated.length}updateRecords=async(e,t,r)=>r.map(o=>{let s=typeof o.Id=="string"?o.Id:"",i={};for(let[a,d]of Object.entries(o))a!=="Id"&&a!=="attributes"&&(i[a]=d);return this.updated.push({seq:this.updated.length,objectApiName:t,recordId:s,fields:i}),{id:s,success:!0,errors:[]}});rowOf(e){if(!(typeof e!="string"||e.length!==15&&e.length!==18))return this.byId.get(e.slice(0,15))}personContactOf(e){if(!(typeof e!="string"||e.length!==15&&e.length!==18))return this.personContacts.get(e.slice(0,15))}guardQueries(e){return async(t,r,o)=>{let s=Wr(r);if(s)return this.personContactsOf(s,c=>e(t,$r(c),o));let i=Zr(r);if(i)return this.ownersOf(i,c=>e(t,Yr(c),o));let a=Xr(r);if(a)return this.teamOf(a,c=>e(t,Qr(a.objectApiName,a.fields,c)),()=>e(t,Kr));let d=Gr(r);return d?this.rolesOf(d,c=>e(t,Vr(c,d.fields),o)):this.namesAPlaceholder(r)?[]:e(t,r,o)}}async rolesOf(e,t){let r=e.opportunities.filter(d=>!this.rowOf(d)),o=r.length>0?await t(r):[],s=e.opportunities.flatMap(d=>{let c=this.rowOf(d),f=c?.objectApiName==="Opportunity"?c.fields[fn]:void 0;return c&&typeof f=="string"&&f!==""?[{id:d,row:c,contact:f}]:[]});if(s.length===0)return o;let i=await this.prefixOf(zr),a=new Date().toISOString();return[...o,...s.map(({id:d,row:c,contact:f})=>{let l=Jt(i,Xi+this.platformTeam.size+this.platformRoles.size);return this.platformRoles.set(l.slice(0,15),c),Jr({...Object.fromEntries(e.fields.map(p=>[p,null])),Id:l,OpportunityId:d,[fn]:f,...e.fields.includes("IsPrimary")?{IsPrimary:!0}:{}},a)})]}async ownersOf(e,t){let r=e.filter(i=>!this.rowOf(i)),o=r.length>0?await t(r):[],s=[];for(let i of e){let a=await this.ownerOf(i);a!==void 0&&s.push({Id:i,OwnerId:a})}return[...o,...s]}async teamOf(e,t,r){let{objectApiName:o,fields:s,opportunities:i}=e,a=i.filter(h=>!this.rowOf(h)),d=a.length>0?await t(a):[],c=i.filter(h=>this.rowOf(h)?.objectApiName==="Opportunity");if(c.length===0)return d;let f=Ur[o],l=o===ln,p=l?(await r()).flatMap(h=>typeof h.Id=="string"&&(h.IsTotalValidated===!0||h.IsTotalValidated==="true")?[h.Id]:[]):[void 0],u=await this.prefixOf(l?ln:qr),m=Hr[o]??{},g=[];for(let h of c){let y=await this.ownerOf(h);if(y!==void 0)for(let R of p){let S=Jt(u,Xi+this.platformTeam.size+this.platformRoles.size);this.platformTeam.set(S.slice(0,15),this.rowOf(h)),g.push({Id:S,OpportunityId:h,[f]:y,...R!==void 0?{SplitTypeId:R}:{},...Object.fromEntries(s.map(w=>[w,m[w]??null]))})}}return[...d,...g]}async ownerOf(e){let t=this.rowOf(e);if(t?.objectApiName!=="Opportunity")return;let r=t.fields.OwnerId;return typeof r=="string"&&r!==""?r:(this.writesAs??=this.runningUser?this.runningUser().catch(()=>{}):Promise.resolve(void 0),this.writesAs)}async personContactsOf(e,t){let r=e.filter(a=>!this.rowOf(a)),o=r.length>0?await t(r):[],s=e.flatMap(a=>this.rowOf(a)?.objectApiName===de?[a]:[]);if(s.length===0)return o;let i=await this.prefixOf(oe);return[...o,...s.map(a=>{let d=this.rowOf(a);if("Name"in d.fields)return{Id:a,[Me]:null};let c=Jt(i,d.seq);return this.personContacts.set(c.slice(0,15),d),{Id:a,[Me]:c}})]}namesAPlaceholder(e){for(let[t]of e.matchAll(el))if(this.rowOf(t)||this.personContactOf(t)||this.platformTeam.has(t.slice(0,15))||this.platformRoles.has(t.slice(0,15)))return!0;return!1}prefixOf(e){let t=this.prefixes.get(e);return t||(t=this.keyPrefixOf(e).catch(()=>null),this.prefixes.set(e,t)),t}};function Vg(n,e){return{queryRecords:e.guardQueries(n.queryRecords),describeFields:n.describeFields,isObjectCreatable:n.isObjectCreatable,describeObject:n.describeObject,recordTypePicklists:n.recordTypePicklists,batchStrategy:n.batchStrategy,anonymize:n.anonymize,requestsSent:n.requestsSent,insertRecords:e.insertRecords,updateRecords:e.updateRecords}}var na="UNKNOWN_ERROR",ra="INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST",tl=new Set(["STRING_TOO_LONG","INVALID_EMAIL_ADDRESS","INVALID_TYPE_ON_FIELD_IN_RECORD","NUMBER_OUTSIDE_VALID_RANGE","MALFORMED_ID","INVALID_ID_FIELD","DUPLICATE_VALUE"]),ea=new Set(["FIELD_CUSTOM_VALIDATION_EXCEPTION","INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST","FIELD_FILTER_VALIDATION_EXCEPTION"]),nl=new Map([["REQUIRED_FIELD_MISSING",{kind:"required_field_missing",severity:"blocking",decisions:["set_default","exclude_object"]}],["INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST",{kind:"picklist_value_refused",severity:"warning",decisions:["map_value","leave_empty","ignore"]}],["STRING_TOO_LONG",{kind:"value_too_long",severity:"blocking",decisions:["truncate","leave_empty","exclude_object"]}],["NUMBER_OUTSIDE_VALID_RANGE",{kind:"number_out_of_range",severity:"blocking",decisions:["leave_empty","exclude_object"]}],["DUPLICATE_VALUE",{kind:"unique_value_collision",severity:"warning",decisions:["leave_empty","exclude_object","ignore"]}],["FIELD_FILTER_VALIDATION_EXCEPTION",{kind:"lookup_filter",severity:"warning",decisions:["leave_empty","ignore"]}]]),cr="FIELD_CUSTOM_VALIDATION_EXCEPTION";function Hg(n){return n.flatMap(e=>{let t=e.detail?.rule,r=e.detail?.message;return e.kind!=="validation_rule"||typeof t!="string"||typeof r!="string"?[]:[{objectApiName:e.objectApiName,name:t,message:r,...e.field!==void 0?{field:e.field}:{}}]})}function rl(n,e,t){if(e.statusCode!==cr||e.message.trim()==="")return;let r=e.fields[0]?.toLowerCase(),o=t.filter(s=>s.objectApiName.toLowerCase()===n.toLowerCase()&&s.message.trim()===e.message.trim()&&(s.field===void 0||r===void 0||s.field.toLowerCase()===r));return o.length===1?o[0].name:void 0}function Kt(n,e){let t=n.detail?.[e];return typeof t=="number"?t:0}function ta(n){let e=n.detail?.fields;return Array.isArray(e)?e:[]}function ol(n,e,t){if(!n)return;let r=new Set(n.values);if(e.split(";").some(o=>!r.has(o)))return"not-in-target";if(n.controllerName===void 0)return t!==void 0?"record-type":void 0}function sl(n,e){if(tl.has(e.statusCode)||e.message==="")return;let t=e.message;for(let r of Object.values(n.fields))typeof r=="string"&&r.length>=3&&(t=t.split(r).join("\u2026"));return t}function il(n,e){let t=n.fields.RecordTypeId;return typeof t=="string"?e.get(t.slice(0,15)):void 0}function al(n,e,t,r){let{row:o}=n,s=e.fields[0],i=t===xr?"unique_value_collision":"rehearsal_refusal";return{id:Ze(i,o.objectApiName,s,void 0,i==="rehearsal_refusal"?t:void 0),kind:i,severity:"warning",source:"rehearsal",objectApiName:o.objectApiName,...s!==void 0?{field:s}:{},...i==="rehearsal_refusal"?{value:t}:{},rows:1,detail:{...r(s),linkedToTheRecordItNames:!0},decisions:s!==void 0?["leave_empty","exclude_object","ignore"]:["exclude_object","ignore"],defaultDecision:"ignore"}}function dl(n,e,t,r,o){let{row:s}=n,i=e.statusCode||na,a=sl(s,e),d=n.onUpdate?void 0:rl(s.objectApiName,e,o),c=u=>{let m=u===void 0?void 0:s.fields[u];return{statusCode:i,fields:[...e.fields],...a!==void 0?{message:a}:{},...d!==void 0?{rule:d}:{},rowsOfTheRun:n.standsFor,...i==="STRING_TOO_LONG"&&typeof m=="string"?{valueLength:m.length}:{},...ea.has(i)&&u!==void 0&&!n.onUpdate?{writtenWithoutTheField:!0}:{}}};if(n.onUpdate){let u=e.fields[0];return[{id:Ze("rehearsal_update_refusal",s.objectApiName,u,void 0,i),kind:"rehearsal_update_refusal",severity:"warning",source:"rehearsal",objectApiName:s.objectApiName,...u!==void 0?{field:u}:{},value:i,rows:1,detail:c(u),decisions:["exclude_object","ignore"]}]}if(n.linked)return[al(n,e,i,c)];let f=nl.get(i);if(f&&e.fields.length>0)return(f.kind==="required_field_missing"?e.fields:e.fields.slice(0,1)).map(m=>{let g=s.fields[m],h=f.kind==="picklist_value_refused",y=h?il(s,t):void 0,R=h&&typeof g=="string"?g:void 0,S=R!==void 0?ol(r.get(s.objectApiName)?.get(m),R,y):void 0;return{id:Ze(f.kind,s.objectApiName,m,y,R),kind:f.kind,severity:f.severity,source:"rehearsal",objectApiName:s.objectApiName,field:m,...y!==void 0?{recordType:y}:{},...R!==void 0?{value:R}:{},rows:1,detail:{...c(m),...S!==void 0?{reason:S}:{}},decisions:[...f.decisions],...f.severity==="warning"?{defaultDecision:"leave_empty"}:{}}});let l=e.fields[0],p=l!==void 0&&ea.has(i);return[{id:Ze("rehearsal_refusal",s.objectApiName,l,void 0,i),kind:"rehearsal_refusal",severity:p?"warning":"blocking",source:"rehearsal",objectApiName:s.objectApiName,...l!==void 0?{field:l}:{},value:i,rows:1,detail:c(l),decisions:l!==void 0?["leave_empty","exclude_object","ignore"]:["exclude_object","ignore"],...p?{defaultDecision:"leave_empty"}:{}}]}function oa(n,e=new Map,t=new Map,r=[]){let o=new Map;for(let s of n){let i=s.errors.length>0?s.errors:[{statusCode:na,message:"",fields:[]}],a=an(...i.map(d=>dl(s,d,e,t,r)));for(let d of a){let c=o.get(d.id);if(!c){o.set(d.id,d);continue}let f=Math.max(Kt(c,"valueLength"),Kt(d,"valueLength"));o.set(d.id,{...c,rows:c.rows+1,detail:{...d.detail,...c.detail,rowsOfTheRun:Kt(c,"rowsOfTheRun")+Kt(d,"rowsOfTheRun"),fields:[...new Set([...ta(c),...ta(d)])],...f>0?{valueLength:f}:{}}})}}return an([...o.values()])}function cl(n){return n!=null&&n!==""}function ul(n){let e=n.fields.RecordTypeId,t=Object.keys(n.fields).filter(r=>r!=="attributes"&&cl(n.fields[r])).sort();return[n.objectApiName,typeof e=="string"?e:"",t.join(",")].join("|")}function sa(n){if(n.length<=200)return{rows:[...n],standsFor:new Map(n.map(r=>[r.seq,1]))};let e=new Map,t=new Map;for(let r of n){let o=ul(r),s=e.get(o);if(s){t.set(s.seq,(t.get(s.seq)??1)+1);continue}e.set(o,r),t.set(r.seq,1)}return{rows:[...e.values()],standsFor:t}}function ll(n){let e=n.fields.Status;return[n.objectApiName,Object.keys(n.fields).sort().join(","),typeof e=="string"?e:""].join("|")}function ia(n){if(n.length<=19)return{updates:[...n],standsFor:new Map(n.map(r=>[r.seq,1]))};let e=new Map,t=new Map;for(let r of n){let o=ll(r),s=e.get(o);if(s){t.set(s.seq,(t.get(s.seq)??1)+1);continue}e.set(o,r),t.set(r.seq,1)}return{updates:[...e.values()],standsFor:t}}function aa(n,e,t=()=>{}){let r=new Map(n.map(a=>[a.seq,a])),o=new Map,s=new Map,i=new Map;for(let a of[...n].sort((d,c)=>d.seq-c.seq)){let d=new Set,c=new Set;for(let l of Object.values(a.fields)){let p=e(l);p&&p.seq!==a.seq&&d.add(p.seq);let u=p?void 0:t(l);u&&u.seq!==a.seq&&r.has(u.seq)&&(d.add(u.seq),c.add(u.seq))}let f=[...d].sort((l,p)=>l-p);o.set(a.seq,f),c.size>0&&i.set(a.seq,[...c].sort((l,p)=>l-p)),s.set(a.seq,f.reduce((l,p)=>Math.max(l,(s.get(p)??0)+1),0))}return{bySeq:r,parents:o,levels:s,...i.size>0?{personContactsNamed:i}:{}}}function da(n,e){if(e.size===0)return n;let t=new Map;for(let[o,s]of n.parents){let i=new Set;for(let a of s){let d=e.get(a);d===void 0?i.add(a):"seq"in d&&d.seq!==o&&i.add(d.seq)}t.set(o,[...i].sort((a,d)=>a-d))}let r=new Map;for(let o of[...n.bySeq.keys()].sort((s,i)=>s-i))r.set(o,(t.get(o)??[]).reduce((s,i)=>Math.max(s,(r.get(i)??0)+1),0));return{bySeq:n.bySeq,parents:t,levels:r,...n.personContactsNamed?{personContactsNamed:n.personContactsNamed}:{}}}function Ge(n,e){let t=new Set,r=[...e.parents.get(n)??[]];for(let o=r.shift();o!==void 0;o=r.shift())t.has(o)||(t.add(o),r.push(...e.parents.get(o)??[]));return[...t]}function ur(n,e){let t=new Set;for(let r of n){t.add(r.seq);for(let o of Ge(r.seq,e))t.add(o)}return[...t].sort((r,o)=>r-o).flatMap(r=>{let o=e.bySeq.get(r);return o?[o]:[]})}var fr=5,pr=25,fl=200,pl=10,ml="PROCESSING_HALTED",gl="SandForge_Rehearsal_Rollback__c";function mr(n,e=0){return Math.max(0,pr-n-e-1)}function en(n,e){let t=new Set;for(let r of n)for(let o of e.personContactsNamed?.get(r)??[])t.add(o);return[...t]}function ca(n,e,t=[],r=new Map){let o=new Map;n.collections.forEach((a,d)=>a.seqs.forEach(c=>o.set(c,d)));let s=new Set([...en(n.collections.flatMap(a=>a.seqs),e),...t.flatMap(a=>a.contacts??[])]),i=[];for(let a of s){let d=o.get(a),c=r.get(a),f=d??(c===void 0?void 0:"id"in c?-1:o.get(c.seq));f!==void 0&&i.push({account:a,after:f})}return i.sort((a,d)=>a.after-d.after||a.account-d.account)}function hl(n,e,t){let r=[...e].flatMap(a=>{let d=t.get(a);return d?[d]:[]}).sort((a,d)=>a.objectApiName.localeCompare(d.objectApiName)||a.seq-d.seq),o=[],s,i=new Set;for(let a of r){let d=!i.has(a.objectApiName);(!s||s.seqs.length>=fl||d&&i.size>=pl)&&(s={level:n,seqs:[]},i=new Set,o.push(s)),s.seqs.push(a.seq),i.add(a.objectApiName)}return o}function lr(n,e){return[...n.keys()].sort((t,r)=>t-r).flatMap(t=>hl(t,n.get(t)??[],e))}function tn(n,e){let t=f=>e.levels.get(f)??0,r=[...n].sort((f,l)=>t(l.seq)-t(f.seq)||f.seq-l.seq),o=[],s=[],i=new Set,a=new Map,d=(f,l)=>{let p=new Map([...f].map(([u,m])=>[u,new Set(m)]));for(let u of l){let m=p.get(t(u))??new Set;m.add(u),p.set(t(u),m)}return p},c=f=>{let l=lr(f,e.bySeq).length,p=en([...f.values()].flatMap(u=>[...u]),e).length;return l<=fr&&l+p<pr};for(let f of r){if(i.has(f.seq))continue;let l=[f.seq,...Ge(f.seq,e)],p=d(new Map,l);if(!c(p)){s.push(f.seq);continue}let u=d(a,l);c(u)?a=u:(o.push({collections:lr(a,e.bySeq)}),a=p);for(let m of l)i.add(m)}return a.size>0&&o.push({collections:lr(a,e.bySeq)}),{calls:o,beyond:s.sort((f,l)=>f-l)}}function Qt(n){return`rows${n}`}function gr(n){return`update${n}`}var ua="rollback";function Xt(n){return`contact${n}`}function wl(n,e,t){let r=o=>t.filter(s=>s.after===o).map(s=>Xt(s.account));return[...r(-1),...n.collections.flatMap((o,s)=>[Qt(s),...r(s)]),...Array.from({length:e},(o,s)=>gr(s)),ua]}function la(n,e,t,r,o,s=[],i=new Map,a={of:()=>{},reads:[]}){let{reads:d}=a;if(s.length>mr(n.collections.length,d.length))throw new Error(`A rehearsal call of ${n.collections.length} Collections request(s) has no room for ${s.length} update(s): a call holds ${pr} subrequests`);let c=new Map;n.collections.forEach((w,b)=>w.seqs.forEach((A,j)=>c.set(A,`@{${Qt(b)}[${j}].id}`)));let f=w=>{let b=c.get(w.seq);if(b!==void 0)return b;let A=i.get(w.seq);if(A!==void 0)return"id"in A?A.id:c.get(A.seq)},l=new Set(d.map(w=>w.account)),p=w=>{let b=t(w);if(b){let j=f(b);return j===void 0?void 0:{sent:j}}let A=a.of(w);return A?l.has(A.seq)?{sent:`@{${Xt(A.seq)}.${Me}}`}:void 0:{sent:w}},u=w=>w.seqs.map(b=>{let A=e.bySeq.get(b);if(!A)throw new Error(`Row ${b} is not among the rows the run creates`);return A}),m=(w,b)=>({method:"POST",url:`${r}/composite/sobjects`,referenceId:Qt(b),body:{allOrNone:!1,records:u(w).map(A=>{let j={attributes:{type:A.objectApiName}};for(let[L,v]of Object.entries(A.fields)){if(L==="attributes"||L==="Id")continue;let P=p(v);if(P===void 0)throw new Error(`${A.objectApiName} row ${A.seq} names a record the run creates that its call does not hold`);j[L]=P.sent}return j})},httpHeaders:{...o}}),g=({account:w})=>{let b=e.bySeq.get(w),A=b?f(b):void 0;if(A===void 0)throw new Error("A read of a person account's contact names an account its call does not hold");return{method:"GET",url:`${r}/sobjects/${de}/${A}?fields=${Me}`,referenceId:Xt(w)}},h=w=>d.filter(b=>b.after===w).map(g),y=[...h(-1),...n.collections.flatMap((w,b)=>[m(w,b),...h(b)])];s.forEach((w,b)=>{let A=c.get(w.rowSeq);if(A===void 0)throw new Error(`An update of ${w.objectApiName} names a record its call does not create`);let j={};for(let[L,v]of Object.entries(w.fields)){if(L==="attributes"||L==="Id")continue;let P=p(v);if(P===void 0)throw new Error(`An update of ${w.objectApiName} names a record the run creates that its call does not hold`);j[L]=P.sent}y.push({method:"PATCH",url:`${r}/sobjects/${w.objectApiName}/${A}`,referenceId:gr(b),body:j,httpHeaders:{...o}})});let R=n.collections[0]?.seqs[0],S=R===void 0?void 0:e.bySeq.get(R);if(!S)throw new Error("A rehearsal call holds no row");return y.push({method:"PATCH",url:`${r}/sobjects/${S.objectApiName}/${yl(S.placeholderId)}`,referenceId:ua,body:{[gl]:!0}}),{allOrNone:!0,collateSubrequests:!1,compositeRequest:y}}function yl(n){return bt(`${n.slice(0,3)}000000000000`)??"000000000000000AAA"}var bl=V({body:Ne(),httpStatusCode:te(),referenceId:W().optional()}).loose(),Rl=V({compositeResponse:Z(bl)}).loose(),Zt=Z(V({errorCode:W().optional(),statusCode:W().optional()}).loose()),Sl=Z(V({success:Ke()}).loose());function Yt(n){let e=Zt.safeParse(n.body);return n.httpStatusCode>=400&&e.success&&e.data.length>0&&e.data.every(t=>(t.errorCode??t.statusCode)===ml)}function fa(n,e,t=0,r=()=>{},o=[]){let s=Rl.safeParse(n);if(!s.success)throw new Error("The target answered the rehearsal with no composite answer");let i=s.data.compositeResponse,a=wl(e,t,o),d=a.length,c=i[d-1];if(i.length!==d||!c)throw new Error(`The target answered ${i.length} subrequests of the ${d} the rehearsal sent`);let f=i.findIndex((m,g)=>m.referenceId!==void 0&&m.referenceId!==a[g]);if(f!==-1)throw new Error(`The target ran the rehearsal's subrequests out of the order sent (${String(i[f]?.referenceId)} in place of ${a[f]}): no verdict can be read from it`);let l=m=>i[a.indexOf(m)];for(let{account:m}of o){let g=l(Xt(m));if(g.httpStatusCode<400||Yt(g))continue;let h=Zt.safeParse(g.body),y=h.success?h.data[0]?.errorCode??h.data[0]?.statusCode:"";throw new Error(`The target refused to read back the contact the platform wrote with a person account (status ${g.httpStatusCode}${y?`, ${y}`:""}): no verdict can be read past it`)}let p=e.collections.map((m,g)=>{let h=l(Qt(g));if(Yt(h))return{kind:"halted"};let y=Sl.safeParse(h.body);if(h.httpStatusCode<400&&y.success){if(y.data.length!==m.seqs.length)throw new Error(`The target answered ${y.data.length} rows of the ${m.seqs.length} a request sent`);return{kind:"rows",outcomes:y.data.map((S,w)=>Rt(S,r(m.seqs[w])??""))}}let R=Zt.safeParse(h.body);if(h.httpStatusCode>=400&&R.success&&R.data.length>0)return{kind:"refused",errors:R.data.map(gn)};throw new Error(`The target answered a request of the rehearsal with status ${h.httpStatusCode}`)}),u=Array.from({length:t},(m,g)=>{let h=l(gr(g));if(Yt(h))return{kind:"halted"};if(h.httpStatusCode<400)return{kind:"saved"};let y=Zt.safeParse(h.body);if(y.success&&y.data.length>0)return{kind:"refused",errors:y.data.map(gn)};throw new Error(`The target answered an update of the rehearsal with status ${h.httpStatusCode}`)});if(c.httpStatusCode<400)return{kind:"not_rolled_back",ids:p.flatMap(m=>m.kind==="rows"?m.outcomes.filter(g=>g.success).map(g=>g.id):[])};if(Yt(c)&&hr(p)===-1&&!u.some(m=>m.kind==="refused"))throw new Error("The target stopped the rehearsal at a request whose answer names no refusal");return{kind:"rolled_back",collections:p,updates:u}}function hr(n){return n.findIndex(e=>e.kind==="refused"||e.kind==="rows"&&e.outcomes.some(t=>!t.success))}function pa(n,e,t=()=>{}){let r=new Map,o=hr(e);return n.collections.forEach((s,i)=>{if(o!==-1&&i>o)return;let a=e[i];s.seqs.forEach((d,c)=>{if(a.kind==="refused"){r.set(d,{passed:!1,errors:a.errors});return}let f=a.kind==="rows"?a.outcomes[c]:void 0;if(!f||f.success){r.set(d,{passed:!0});return}let l=Ro(f,t(d));r.set(d,{passed:!1,errors:f.errorDetails??[],...l.kind==="linked"?{linkedTo:l.id}:{}})})}),r}function ma(n,e){let t=new Map;if(hr(e.collections)!==-1)return t;for(let[r,o]of n.entries()){let s=e.updates[r];if(s?.kind==="refused"){t.set(o.seq,{passed:!1,errors:s.errors});break}t.set(o.seq,{passed:!0})}return t}async function Ol(n,e){let t=e.targetRecordTypes;if(!t)return n;let r=new Set(n.flatMap(s=>s.recordType!==void 0&&fo(s.recordType).namespacePrefix?[s.objectApiName]:[]));if(r.size===0)return n;let o=new Map;for(let s of r){let i=await t(s).catch(()=>{});o.set(s,i?po(i):void 0)}return n.map(s=>mo(s,o.get(s.objectApiName)))}async function Al(n,e){let t=[...new Set(n.filter(({errors:r})=>r.some(o=>o.statusCode===cr)).map(({row:r})=>r.objectApiName))];if(t.length===0||!e.validationRules)return[];try{return await e.validationRules(t)}catch{return[]}}async function kl(n,e){let t=new Map;for(let{row:s,errors:i,onUpdate:a}of n)if(!a)for(let d of i){let c=d.fields[0];d.statusCode!==ra||c===void 0||t.set(s.objectApiName,(t.get(s.objectApiName)??new Set).add(c))}let r=new Map,o=e.targetFields;if(!o)return r;for(let[s,i]of t){let a;try{a=await o(s)}catch{continue}let d=new Map;for(let c of a)!i.has(c.name)||!c.picklistValues||d.set(c.name,{values:c.picklistValues,...c.controllerName?{controllerName:c.controllerName}:{}});r.set(s,d)}return r}var wr=class extends Error{constructor(t,r=[]){super(`A rehearsal call was not rolled back: the ${t.length} record(s) it created stay in the target (${t.join(", ")}). The rehearsal stopped there; remove them from the target.`);this.ids=t;this.objects=r;this.name="RehearsalNotRolledBackError"}ids;objects},nn=class extends Error{constructor(t){super(t>0?`The rehearsal was cancelled after ${t} call(s), each rolled back whole: nothing stays in the target.`:"The rehearsal was cancelled before its first call. Nothing was sent to the target.");this.calls=t;this.name="RehearsalCancelledError"}calls};function Il(n,e){let t=new Map;for(let o of e)t.set(o.placeholderId.slice(0,3),o.objectApiName);let r=new Map;for(let o of n){let s=t.get(o.slice(0,3))??o.slice(0,3);r.set(s,(r.get(s)??0)+1)}return[...r].map(([o,s])=>({objectApiName:o,created:s}))}function ga(n){let e=new Map;for(let{objectApiName:t}of n)e.set(t,(e.get(t)??0)+1);return[...e].map(([t,r])=>({objectApiName:t,count:r})).sort((t,r)=>r.count-t.count||t.objectApiName.localeCompare(r.objectApiName))}function jl(n,e,t){let r=n.slice(0,15);for(let[o,s]of e.collections.entries()){let i=t[o];if(i?.kind==="rows")for(let[a,d]of i.outcomes.entries()){let c=s.seqs[a];if(d.success&&d.id.slice(0,15)===r&&c!==void 0)return{seq:c}}}return{id:n}}function Nl(n,e,t){let r=e(n.recordId);if(!r)return;let o=new Set([r.seq]),s=new Set;for(let i of Object.values(n.fields)){let a=e(i);a&&o.add(a.seq);let d=a?void 0:t(i);d&&(o.add(d.seq),s.add(d.seq))}return{seq:n.seq,objectApiName:n.objectApiName,rowSeq:r.seq,fields:n.fields,needs:[...o],...s.size>0?{contacts:[...s]}:{}}}function yr(n,e,t){let r=new Set(n.collections.flatMap(i=>i.seqs)),o=new Set(en(r,t)),s=[];for(let i of e){if(!i.needs.every(d=>r.has(d)))continue;let a=(i.contacts??[]).filter(d=>!o.has(d));if(s.length+1>mr(n.collections.length,o.size+a.length))break;for(let d of a)o.add(d);s.push(i)}return s}function ha(n,e){let t=o=>{let s=ur(o.flatMap(d=>d.needs.flatMap(c=>{let f=e.bySeq.get(c);return f?[f]:[]})),e),i=tn(s,e),[a]=i.calls;return i.calls.length===1&&i.beyond.length===0&&a&&yr(a,o,e).length===o.length?a:void 0},r=[];for(let[o,s]of n.entries()){let i=[s],a=t(i);if(!a){r.push(s);continue}for(let d of n.slice(o+1)){let c=t([...i,d]);c&&(i=[...i,d],a=c)}return{call:a,beyond:r}}return{beyond:r}}function El(n,e,t){let r=[...e],o=i=>{let a=new Set(yr(i,r,t));return r=r.filter(d=>!a.has(d)),a.size};for(let i of n)o(i);let s=0;for(;r.length>0;){let{call:i,beyond:a}=ha(r,t),d=new Set(a);if(r=r.filter(c=>!d.has(c)),!i||o(i)===0)break;s++}return n.length+s}async function ah(n){let e=new Ht(n.keyPrefixOf,n.runningUser);await n.prepare(e);let t=e.rows,r=E=>e.rowOf(E),o=E=>e.personContactOf(E),s=aa(t,r,o),i=sa(t),a=ia(e.updated.flatMap(E=>{let T=Nl(E,r,o);return T?[T]:[]})),d=a.updates,c=ur([...i.rows,...d.flatMap(E=>E.needs.flatMap(T=>{let I=s.bySeq.get(T);return I?[I]:[]}))],s),f=E=>i.standsFor.get(E)??1,l=E=>{let T=s.bySeq.get(E)?.placeholderId.slice(0,3);return T===void 0||T===dr?null:T},p=new Map,u=new Map,m=new Map,g=new Map,h=new Map,y=s,R=tn(c,s);for(let E of R.beyond)u.set(E,"beyond_a_call");let S=El(R.calls,d,s),w=S*fr,b=0;if(S>0){if(n.signal?.aborted)throw new nn(0);n.onProgress?.({phase:"confirming",calls:S}),await n.confirm({rows:t.length,sampled:c.length,updates:ga(d).map(({objectApiName:E,count:T})=>({objectApiName:E,updates:T})),calls:S,maxCalls:w,objects:ga(c).map(({objectApiName:E,count:T})=>({objectApiName:E,rows:T}))})}let A=E=>{let T=p.get(E);return T?.passed===!1&&T.linkedTo===void 0},j=E=>[E,...Ge(E,y)].some(A),L=E=>{if(h.has(E.rowSeq))return"record_linked";for(let T of E.needs){if(j(T))return"parent_refused";let I=u.get(T);if(I)return I}};for(;;){if(n.signal?.aborted)throw new nn(b);let E=c.filter(x=>p.has(x.seq)||u.has(x.seq)?!1:Ge(x.seq,y).some(A)?(u.set(x.seq,"parent_refused"),!1):!0),T=d.filter(x=>{if(m.has(x.seq)||g.has(x.seq))return!1;let $=L(x);return $?(g.set(x.seq,$),!1):!0});if(E.length===0&&T.length===0)break;if(b>=w){for(let x of E)u.set(x.seq,"call_budget");for(let x of T)g.set(x.seq,"call_budget");break}let I;if(E.length>0){let x=tn(E,y);for(let $ of x.beyond)u.set($,"beyond_a_call");I=x.calls[0]}else{let x=ha(T,y);for(let $ of x.beyond)g.set($.seq,"beyond_a_call");I=x.call}if(!I)continue;let O=yr(I,T.filter(x=>!g.has(x.seq)),y);b++,n.onProgress?.({phase:"rehearsing",call:b,calls:Math.max(S,b)});let C=ca(I,y,O,h),B=la(I,s,r,n.apiPath,n.writeHeaders,O,h,{of:o,reads:C}),F=fa(await n.composite(B),I,O.length,x=>s.bySeq.get(x)?.objectApiName,C);if(F.kind==="not_rolled_back")throw new wr(F.ids,Il(F.ids,t));let _=new Map;for(let[x,$]of pa(I,F.collections,l))p.set(x,$),!$.passed&&$.linkedTo!==void 0&&_.set(x,jl($.linkedTo,I,F.collections));for(let[x,$]of ma(O,F))m.set(x,$);if(_.size>0){for(let[x,$]of _)h.set(x,$);y=da(s,h),d=d.map(x=>({...x,needs:x.needs.flatMap($=>{let q=h.get($);return q===void 0?[$]:"seq"in q?[q.seq]:[]})}))}}let v=[],P=0,k=0;for(let E of c){let T=p.get(E.seq);if(!T)continue;if(T.passed){P++;continue}let I=T.linkedTo!==void 0;I&&k++,v.push({row:E,errors:T.errors,standsFor:f(E.seq),...I?{linked:!0}:{}})}let N=0,M=0;for(let E of d){let T=m.get(E.seq),I=s.bySeq.get(E.rowSeq);if(!T||!I)continue;let O=a.standsFor.get(E.seq)??1;if(M+=O,T.passed){N++;continue}v.push({row:{...I,fields:{...I.fields,...E.fields}},errors:T.errors,standsFor:O,onUpdate:!0})}let D=new Map;for(let[E,T]of u){let O=`${s.bySeq.get(E)?.objectApiName??""}|${T}`;D.set(O,(D.get(O)??0)+1)}return{gaps:await Ol(oa(v,n.recordTypeNames,await kl(v,n),await Al(v,n)),n),rows:t.length,sampled:c.length,judged:p.size,passed:P,linked:k,notJudged:u.size,notJudgedWhy:[...D].map(([E,T])=>{let[I,O]=E.split("|");return{objectApiName:I,rows:T,reason:O}}),updates:e.updates,updatesJudged:m.size,updatesPassed:N,updatesNotRehearsed:e.updates-M,calls:b,plannedCalls:S}}var Tl="QuoteLineItem",br="Quote",rn="Opportunity",Rr="OpportunityLineItem",Ar="SyncedQuoteId",kr="QuoteId",Ir="OpportunityLineItemId",Or=new Set(["Id",kr,Ir]);function ut(n){return n.slice(0,15)}function Sr(n,e){let t=n[e];return typeof t=="string"&&t!==""?ut(t):void 0}function uh(n,e){return!n.has(rn)||!n.has(br)||!n.has(Rr)?[]:e.get(rn)?.some(r=>r.name===Ar)!==!0?[]:[{sourceObject:br,targetObject:Rr,relationshipName:`${br}Before${Rr}`,type:"lookup",required:!0}]}function Fl(n,e,t){let r=[...Or,...t.filter(s=>!Or.has(s))].map(J).join(", "),o=s=>s.map(i=>`'${xe(i)}'`).join(", ");return`SELECT ${r} FROM ${Tl} WHERE ${kr} IN (${o(n)}) AND ${Ir} IN (${o(e)})`}var Pl=200;function vl(n,e){let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t}async function lh(n,e,t){let r=[],o=[...new Set(e.map(s=>s.product))];for(let s of vl(o,Pl)){let i=new Set(s.map(ut)),a=[...new Set(e.filter(d=>i.has(ut(d.product))).map(d=>d.quote))];r.push(...await n(Fl(a,s,t)))}return r}function fh(n,e,t){let r=new Map;for(let s of e){let i=Sr(s,"Id"),a=Sr(s,kr),d=Sr(s,Ir);if(!i||!a||!d||t.has(i))continue;let c=`${a}:${d}`;r.set(c,[...r.get(c)??[],s])}let o=new Map;for(let s of n){let i=r.get(`${ut(s.quote)}:${ut(s.product)}`)?.shift();i&&o.set(s.index,i)}return o}var wa=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;function Cl(n,e){let t=r=>r==null||r==="";if(t(n)||t(e))return t(n)&&t(e);if(n===e)return!0;if(typeof n=="number"||typeof e=="number"){let r=Number(n),o=Number(e);return Number.isFinite(r)&&Number.isFinite(o)&&r===o}if(typeof n=="string"&&typeof e=="string"){if(wa.test(n)&&wa.test(e)){let r=Date.parse(n),o=Date.parse(e);return Number.isFinite(r)&&r===o}return!1}return String(n)===String(e)}function ph(n,e,t,r=new Set){let o={};for(let[s,i]of Object.entries(n))Or.has(s)||r.has(s)||!t(s)||Cl(i,e[s])||(o[s]=i??null);return o}function mh(n,e,t){let r=n===1,o=`the platform's ${r?"copy":"copies"} of ${r?"its":"their"} opportunity product${r?"":"s"}`,s=e>0?`, ${e} given the fields the copy lacked`:"";return`${n} of them ${t?"would be ":""}${o}, made as the quote syncs with its opportunity: taken rather than written twice${s}`}var xl=2e3,Ml=3,Ll=20,lt=20;function kh(n,e){let t=ho(n,e);return{query:r=>t.query(r),describe:r=>t.describe(r),describeGlobal:()=>t.describeGlobal(),queryAll:async r=>{let o=await n.query(r,{scanAll:!0});return go(n.limitInfo,e),{totalSize:o.totalSize,records:o.records}},serverTime:async()=>(await n.soap.getServerTimestamp()).timestamp}}function ya(n,e,t){return`${n}:${e.slice(0,15)}:${t}`}function ba(n,e){return`${n}.${e}`}var _l=[{modified:"LastModifiedDate",by:"LastModifiedById",created:!0},{modified:"LastModifiedDate",by:"LastModifiedById"},{modified:"SystemModstamp",created:!0},{modified:"SystemModstamp"},{}],le="CreatedById",He="CreatedDate",Dl=V({sobjects:Z(V({name:W(),keyPrefix:W().nullish()}).loose())}).loose(),Bl=n=>new Promise(e=>setTimeout(e,n));function G(n){return n.slice(0,15)}function Ra(n){return n.slice(0,3)}function Sa(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function $l(n,e,t){let r=n[le],o=ft(n[He]);if(typeof r!="string"||!Number.isFinite(o))return;let s=i=>Math.floor(i/1e3)*1e3;return G(r)===G(e)&&s(o)>=s(t.from)&&s(o)<=s(t.to)}function ft(n){return typeof n=="string"?Date.parse(n):Number.NaN}function Je(n){return typeof n.Id=="string"?n.Id:void 0}function jr(n){return Array.isArray(n)?`[${n.map(jr).join(",")}]`:typeof n=="object"&&n!==null?`{${Object.entries(n).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${jr(r)}`).join(",")}}`:JSON.stringify(n)}var Oa=class{constructor(e){this.deps=e}deps;describes=new Map;async verify(e,t={}){let r=t.now??(()=>new Date),o=t.sleep??Bl,s=t.intervalMs??xl,i=Math.max(1,t.maxAttempts??Ml),a=t.linkSample??Ll,d=await this.runEnd(e),c=this.deps.source,f="unavailable"in c?c.unavailable:void 0,l=new Map;if(!("unavailable"in c))for(let b of e.records)l.set(b.objectApiName,await this.linkPlan(c,e,b,a));let p=null,u=null,m=[],g=0,h=this.explaining(e,d),y=h.window?await this.runUser(e):void 0,R=await this.writtenByThePlatformAlone(e,h);for(let b=1;b<=i;b++){g=b,await o(s),m=[];for(let j of e.records)m.push(await this.read(e,j,d,l.get(j.objectApiName),h,y));for(let j of R)m.push(await this.readWrittenByThePlatform(j,h,y));let A=jr(m);if(p!==null&&A===p){u=m;break}p=A}let S=(u??m).map(ql),w=e.roots?Wl(e,e.roots,u??m):void 0;return{verdict:Ul(u!==null,S,f),verifiedAt:r().toISOString(),attempts:g,objects:S,...f!==void 0?{linksUnchecked:f}:{},...w?{roots:w}:{}}}async runEnd(e){if(e.runEndedAt)return e.runEndedAt.getTime();if(!e.runRecordedAt)return Number.NaN;let t=0,r=this.deps.target.serverTime;if(r){let o=Date.now();try{let s=ft(await r.call(this.deps.target));Number.isFinite(s)&&(t=s-(o+Date.now())/2)}catch{}}return e.runRecordedAt.getTime()+t+St}explaining(e,t){let r=new Set;for(let{objectApiName:c,field:f,recordIds:l}of e.leftEmptyByFilter??[])for(let p of l)r.add(ya(c,p,f));let o=new Set(Object.entries(e.leftEmptyByTheRun??{}).flatMap(([c,f])=>f.map(l=>ba(c,l)))),s=[...new Set((e.withTheirRecord??[]).flatMap(c=>{let f=e.remapTable[c];return f===void 0?[]:[f]}))],i=e.runStartedAt?.getTime()??Number.NaN,a=Number.isFinite(i)&&Number.isFinite(t),d={from:i-St,to:t+St};return{emptiedByFilter:r,emptiedByTheRun:o,withTheirRecord:s,createdByRun:new Set(Object.values(e.remapTable).map(G)),...a?{window:d,counted:e.runEndedAt?{from:d.from,to:t}:d}:{}}}async setByAutomation(e,t,r){let o=r.window,s=e.filter(({link:f,createdBy:l})=>o!==void 0&&typeof l=="string"&&f.found!==null&&!r.createdByRun.has(G(f.found)));if(!o||s.length===0)return{explained:[],broken:e.map(({link:f})=>f)};let i=new Map,a=new Map;for(let{link:f}of s){let l=await this.objectOfId(t.referenceTo?.get(f.field)??[],f.found);l!==void 0&&a.set(l,[...a.get(l)??[],f.found])}for(let[f,l]of a)try{let p=await fe(this.deps.target,f,[le,He],[...new Set(l)]);for(let u of p){let m=Je(u);m&&i.set(G(m),u)}}catch{}let d=[],c=[];for(let f of e){let{link:l,createdBy:p}=f,u=l.found===null?void 0:i.get(G(l.found)),m=ft(u?.[He]);s.includes(f)&&typeof p=="string"&&typeof u?.[le]=="string"&&G(u[le])===G(p)&&m>=o.from&&m<=o.to?d.push({...l,cause:"automation"}):c.push(l)}return{explained:d,broken:c}}async objectOfId(e,t){if(e.length===1)return e[0];for(let r of e)try{if((await this.describe(this.deps.target,"target",r)).keyPrefix===t.slice(0,3))return r}catch{}}describe(e,t,r){let o=`${t}:${r}`,s=this.describes.get(o);return s||(s=e.describe(r),this.describes.set(o,s)),s.then(i=>yt.parse(i))}async linkPlan(e,t,r,o){let s=r.objectApiName,i={fields:[],expected:new Map,sample:[]};try{let[a,d]=await Promise.all([this.describe(this.deps.target,"target",s),this.describe(e,"source",s)]),c=new Set(a.fields.filter(w=>w.type==="reference"&&(w.createable===!0||w.updateable===!0)).map(w=>w.name)),f=new Set(t.fieldExclusions?.[s]??[]),l=t.fieldMappings?.[s]??{},p=d.fields.filter(w=>w.type==="reference"&&!f.has(w.name)).map(w=>({from:w.name,to:l[w.name]??w.name})).filter(({to:w})=>c.has(w)&&!f.has(w));if(p.length===0)return i;let u=new Map,m=new Map;for(let[w,b]of Object.entries(t.remapTable))u.set(G(b),w),m.set(G(w),b);let g=r.ids.slice(0,o).filter(w=>u.has(G(w)));if(g.length===0)return i;let h=await fe(e,s,p.map(w=>w.from),g.map(w=>u.get(G(w)))),y=new Map;for(let w of h){let b=Je(w),A=b?m.get(G(b)):void 0;if(!A)continue;let j=[];for(let{from:L,to:v}of p){let P=w[L],k=typeof P=="string"?m.get(G(P)):void 0;k&&j.push({field:v,expected:k})}j.length>0&&y.set(G(A),j)}let R=[...new Set([...y.values()].flat().map(w=>w.field))],S=new Map(a.fields.filter(w=>R.includes(w.name)).map(w=>[w.name,w.referenceTo??[]]));return{fields:R,expected:y,sample:R.length>0?g:[],referenceTo:S,createdBy:a.fields.some(w=>w.name===le)}}catch(a){return{...i,unchecked:H(a)}}}async runUser(e){for(let t of e.records){let r=t.ids[0];if(r!==void 0)try{let[o]=await fe(this.deps.target,t.objectApiName,[le],[r]),s=o?.[le];if(typeof s=="string"&&/^[A-Za-z0-9]{15,18}$/.test(s))return s}catch{}}}async countInTheWindow(e,t,r,o){try{return(await this.deps.target.query(`SELECT COUNT() FROM ${J(e)} WHERE ${le} = '${t}' AND ${He} >= ${Sa(r.from)} AND ${He} <= ${Sa(r.to)}`+(o?` AND ${J(o.field)} = '${o.value}'`:""))).totalSize}catch{return}}async withTheirRecordThere(e,t,r=e.ids[0]?.slice(0,3)){if(r===void 0)return 0;let o=new Set(e.ids.map(G)),s=t.withTheirRecord.filter(i=>i.slice(0,3)===r&&!o.has(G(i)));if(s.length===0)return 0;try{let i=await fe(this.deps.target,e.objectApiName,[],s);return new Set(i.map(Je).filter(a=>a!==void 0).map(G)).size}catch{return 0}}async writtenByThePlatformAlone(e,t){let r=new Set(e.records.flatMap(i=>i.ids.slice(0,1)).map(Ra)),o=[...new Set(t.withTheirRecord.map(Ra))].filter(i=>!r.has(i)),s=this.deps.target.describeGlobal;if(o.length===0||!s)return[];try{let{sobjects:i}=Dl.parse(await s.call(this.deps.target));return o.flatMap(a=>{let d=i.find(c=>c.keyPrefix===a);return d?[{objectApiName:d.name,prefix:a}]:[]})}catch{return[]}}async readWrittenByThePlatform(e,t,r){let o={objectApiName:e.objectApiName,expected:0,present:0,deletedIds:[],notVisibleIds:[],changed:[],linksChecked:0,broken:[],explained:[],withTheirRecord:await this.withTheirRecordThere({objectApiName:e.objectApiName,ids:[]},t,e.prefix)};if(r!==void 0&&t.counted){let s=await this.countInTheWindow(e.objectApiName,r,t.counted);s!==void 0&&(o.createdInTheWindow=s)}return o}async read(e,t,r,o,s,i){let a=t.objectApiName,d={objectApiName:a,expected:t.ids.length,present:0,deletedIds:[],notVisibleIds:[],changed:[],linksChecked:0,broken:[],explained:[],withTheirRecord:0,...o?.unchecked!==void 0?{linksUnchecked:o.unchecked}:{}},c,f={},l,p=a===un.objectApiName?un:void 0;for(let y of _l)try{let R=[y.modified,y.by,...y.created?[He,le,...p?[p.field]:[]]:[]].filter(S=>!!S);c=await fe(this.deps.target,a,R,t.ids),f=y;break}catch(R){l??=H(R)}if(!c)return{...d,error:l??"The org gave no reason."};let u=new Map;for(let y of c){let R=Je(y);R&&u.set(G(R),y)}let m=t.ids.filter(y=>!u.has(G(y))),g=0;if(m.length>0){let y=await this.recycleBin(a,m);if("unread"in y)d.notVisibleIds=m,d.recycleBinUnread=y.unread;else for(let R of m){let S=y.found.get(G(R));S==="deleted"?d.deletedIds.push(R):S==="there"?g++:d.notVisibleIds.push(R)}}if(d.present=u.size+g,d.withTheirRecord=await this.withTheirRecordThere(t,s),i!==void 0&&s.counted){let y=s.counted,R=await this.countInTheWindow(a,i,y);if(R!==void 0){d.createdInTheWindow=R;let S=g,w=0;for(let b of u.values())$l(b,i,y)!==!1&&(S++,p&&b[p.field]===p.value&&w++);if(d.ofTheRunInTheWindow=S,p){let b=await this.countInTheWindow(a,i,y,p);b!==void 0&&b>w&&(d.postedWithTheirRecord=b-w)}}}let h=new Map(Object.entries(e.removalStamps??{}).map(([y,R])=>[G(y),ft(R)]));if(f.modified&&Number.isFinite(r))for(let y of t.ids){let R=u.get(G(y));if(!R)continue;let S=ft(R[f.modified]);if(!Number.isFinite(S)||S<=r||S<=(h.get(G(y))??Number.NaN))continue;let w=f.by?R[f.by]:void 0;d.changed.push({recordId:y,modifiedAt:String(R[f.modified]),...typeof w=="string"?{modifiedById:w}:{}})}if(o&&o.sample.length>0)try{let y=await fe(this.deps.target,a,o.createdBy?[...o.fields,le]:o.fields,o.sample),R=new Set(e.writtenWithout?.[a]??[]),S=[];for(let w of y){let b=Je(w);if(b)for(let{field:A,expected:j}of o.expected.get(G(b))??[]){let L=w[A],v=typeof L=="string"&&L!==""?L:null;if(v!==null&&G(v)===G(j)){d.linksChecked++;continue}if(v===null&&s.emptiedByFilter.has(ya(a,b,A))){d.linksChecked++,d.explained.push({recordId:b,field:A,expected:j,found:v,cause:"lookup-filter"});continue}if(v===null&&s.emptiedByTheRun.has(ba(a,A))){d.linksChecked++,d.explained.push({recordId:b,field:A,expected:j,found:v,cause:"run"});continue}if(v===null&&R.has(A))continue;d.linksChecked++;let P={recordId:b,field:A,expected:j,found:v};v===null?d.broken.push(P):S.push({link:P,createdBy:w[le]})}}if(S.length>0){let{explained:w,broken:b}=await this.setByAutomation(S,o,s);d.explained.push(...w),d.broken.push(...b)}}catch(y){d.linksUnchecked=H(y)}return d}async recycleBin(e,t){let r=new Map;try{let o=J(e);for(let s of X(t)){let i=await this.deps.target.queryAll(`SELECT Id, IsDeleted FROM ${o} WHERE Id IN (${s})`);for(let a of i.records){if(typeof a!="object"||a===null)continue;let d=a,c=Je(d);if(!c)continue;let f=d.IsDeleted===!0||d.IsDeleted==="true";r.set(G(c),f?"deleted":"there")}}}catch(o){return{unread:H(o)}}return{found:r}}};function Wl(n,e,t){let r=t.find(d=>d.objectApiName===e.objectApiName);if(r?.error!==void 0)return;let o=new Set(n.records.filter(d=>d.objectApiName===e.objectApiName).flatMap(d=>d.ids.map(G))),s=new Set([...r?.deletedIds??[],...r?.notVisibleIds??[]].map(G)),i=0,a=0;for(let d of e.sourceIds){let c=n.remapTable[d];if(c===void 0)continue;i++;let f=G(c);(!o.has(f)||r!==void 0&&!s.has(f))&&a++}return{inTarget:a,of:i}}function ql(n){let e=n.explained.filter(s=>s.cause==="run").length,t=n.postedWithTheirRecord??0,r=n.withTheirRecord+t,o=(n.ofTheRunInTheWindow??n.present)+r;return{objectApiName:n.objectApiName,expected:n.expected,present:n.present,deleted:n.deletedIds.length,notVisible:n.notVisibleIds.length,changed:n.changed.length,changedRecords:n.changed.slice(0,lt),deletedIds:n.deletedIds.slice(0,lt),notVisibleIds:n.notVisibleIds.slice(0,lt),linksChecked:n.linksChecked,linksBroken:n.broken.length,brokenLinks:n.broken.slice(0,lt),...n.explained.length>0?{linksLeftEmptyByFilter:n.explained.filter(s=>s.cause==="lookup-filter").length,linksSetByAutomation:n.explained.filter(s=>s.cause==="automation").length,...e>0?{linksLeftEmptyByTheRun:e}:{},explainedLinks:n.explained.slice(0,lt)}:{},...n.error!==void 0?{error:n.error}:{},...n.linksUnchecked!==void 0?{linksUnchecked:n.linksUnchecked}:{},...n.recycleBinUnread!==void 0?{recycleBinUnread:n.recycleBinUnread}:{},...r>0?{withTheirRecord:r}:{},...n.createdInTheWindow!==void 0&&n.createdInTheWindow>o?{moreInTheWindow:n.createdInTheWindow-o}:{}}}function Ul(n,e,t){return n?e.some(o=>o.error!==void 0||o.linksUnchecked!==void 0||o.deleted>0||o.notVisible>0||o.linksBroken>0||(o.moreInTheWindow??0)>0)||t!==void 0?"partial":"verified":"unstable"}function Ih(n){let e=s=>n.objects.reduce((i,a)=>i+s(a),0),t=e(s=>s.linksLeftEmptyByFilter??0),r=e(s=>s.linksSetByAutomation??0),o=e(s=>s.linksLeftEmptyByTheRun??0);return{expected:e(s=>s.expected),present:e(s=>s.present),deleted:e(s=>s.deleted),notVisible:e(s=>s.notVisible),changed:e(s=>s.changed),linksChecked:e(s=>s.linksChecked),linksBroken:e(s=>s.linksBroken),...t>0?{linksLeftEmptyByFilter:t}:{},...r>0?{linksSetByAutomation:r}:{},...o>0?{linksLeftEmptyByTheRun:o}:{},attempts:n.attempts}}function jh(n){return n?{[rn]:[Ar]}:{}}function Nh(n){let e={};for(let{objectApiName:t,fields:r}of n){let o=e[t]??=[];for(let{field:s}of r)o.includes(s)||o.push(s)}return e}var Aa=class{map=new Map;readScopes=new Map;reached=new Map;add(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r));for(let o of t)o&&r.add(o)}addRead(e,t){this.add(e,t),this.readScopes.set(e,new Set(this.map.get(e)))}addReadAgain(e,t){let r=[...t].filter(o=>o);this.add(e,r),this.readScopes.set(e,new Set([...this.readScopes.get(e)??[],...r]))}forget(e,t){let r=this.map.get(e);if(r)for(let o of t)r.delete(o)}get(e){return this.map.get(e)}scopeOf(e){return this.readScopes.get(e)??this.map.get(e)}isRead(e){return this.readScopes.has(e)}addReached(e,t){let r=this.reached.get(e);r||(r=new Set,this.reached.set(e,r));for(let o of t)o&&r.add(o)}reachedOf(e){return this.reached.get(e)}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}get size(){let e=0;for(let t of this.map.values())e+=t.size;return e}get objectCount(){let e=0;for(let t of this.map.values())t.size>0&&e++;return e}entries(){return this.map.entries()}clear(){this.map.clear(),this.readScopes.clear(),this.reached.clear()}};var ka=class{cache=new Map;sizeMap=new Map;maxSize;defaultTtl;maxSizeBytes;currentBytes=0;releaseExpired;releaseTimer;constructor(e){this.maxSize=e?.maxSize??100,this.defaultTtl=e?.defaultTtl??3e5,this.maxSizeBytes=e?.maxSizeBytes??5242880,this.releaseExpired=e?.releaseExpired===!0}get(e){let t=this.cache.get(e);if(t){if(this.isExpired(t)){this.deleteEntry(e);return}return t.accessCount++,t.lastAccessedAt=Date.now(),t.data}}set(e,t,r){this.cache.has(e)&&this.removeSize(e);let o=this.maxSizeBytes<Number.POSITIVE_INFINITY,s=o?this.estimateSize(t):0;if(this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictLRU(),o)for(;this.cache.size>0&&this.currentBytes+s>this.maxSizeBytes;)this.evictLRU();this.cache.set(e,{data:t,cachedAt:Date.now(),ttl:r??this.defaultTtl,accessCount:1,lastAccessedAt:Date.now()}),o&&(this.sizeMap.set(e,s),this.currentBytes+=s),this.releaseExpired&&this.scheduleRelease()}has(e){let t=this.cache.get(e);return t?this.isExpired(t)?(this.deleteEntry(e),!1):!0:!1}invalidate(e){return this.cache.has(e)?(this.deleteEntry(e),!0):!1}invalidateByPrefix(e){let t=0;for(let r of this.cache.keys())r.startsWith(e)&&(this.deleteEntry(r),t++);return t}clear(){this.cache.clear(),this.sizeMap.clear(),this.currentBytes=0,clearTimeout(this.releaseTimer),this.releaseTimer=void 0}get size(){return this.cache.size}get activeSize(){let e=0;for(let t of this.cache.values())this.isExpired(t)||e++;return e}get estimatedBytes(){return this.currentBytes}keys(){let e=[];for(let[t,r]of this.cache)this.isExpired(r)||e.push(t);return e}purgeExpired(){let e=0;for(let[t,r]of this.cache)this.isExpired(r)&&(this.deleteEntry(t),e++);return e}scheduleRelease(){if(this.releaseTimer!==void 0)return;let e=1/0;for(let r of this.cache.values())e=Math.min(e,r.cachedAt+r.ttl);if(e===1/0)return;let t=setTimeout(()=>{this.releaseTimer=void 0,this.purgeExpired(),this.scheduleRelease()},Math.max(0,e-Date.now())+1);t.unref?.(),this.releaseTimer=t}isExpired(e){return Date.now()-e.cachedAt>e.ttl}evictLRU(){let e,t=1/0;for(let[r,o]of this.cache)o.lastAccessedAt<t&&(t=o.lastAccessedAt,e=r);e&&this.deleteEntry(e)}deleteEntry(e){this.cache.delete(e),this.removeSize(e)}removeSize(e){let t=this.sizeMap.get(e);t!==void 0&&(this.currentBytes-=t,this.sizeMap.delete(e))}estimateSize(e){if(e==null)return 16;if(typeof e=="string")return e.length*2;if(typeof e=="number"||typeof e=="boolean")return 8;if(typeof e!="object")return 64;let t=e;if(Array.isArray(t.fields)||Array.isArray(t.childRelationships)){let r=512;if(Array.isArray(t.fields))for(let o of t.fields)r+=this.estimateEntrySize(o,250);if(Array.isArray(t.childRelationships))for(let o of t.childRelationships)r+=this.estimateEntrySize(o,100);return r}return Array.isArray(e)?e.length*64+64:Object.keys(e).length*64+128}estimateEntrySize(e,t){if(e==null||typeof e!="object")return 16;let r=t;for(let o of Object.values(e))if(typeof o=="string")r+=16+o.length*2;else if(typeof o=="number"||typeof o=="boolean")r+=8;else if(Array.isArray(o)){r+=16;for(let s of o)r+=typeof s=="string"?16+s.length*2:this.estimateEntrySize(s,64)}else r+=16;return r}};export{Un as a,zn as b,ec as c,tc as d,Qp as e,Gl as f,Jl as g,ks as h,Hl as i,Kl as j,Yl as k,js as l,Zl as m,tf as n,Aa as o,Tl as p,rn as q,Rr as r,Ar as s,kr as t,Ir as u,uh as v,lh as w,fh as x,ph as y,mh as z,af as A,df as B,cf as C,pf as D,mf as E,Ps as F,Of as G,Af as H,kf as I,If as J,jf as K,Nf as L,Ef as M,Tf as N,Ff as O,Pf as P,Df as Q,xs as R,$f as S,Wf as T,er as U,tr as V,pm as W,Ui as X,Fg as Y,Ji as Z,Pg as _,Xf as $,Fn as aa,ep as ba,Bs as ca,tp as da,np as ea,ld as fa,rp as ga,bd as ha,mp as ia,gp as ja,hp as ka,jd as la,Ln as ma,Md as na,We as oa,Qs as pa,kp as qa,Ip as ra,Bd as sa,jp as ta,Np as ua,ka as va,Wd as wa,qd as xa,Pp as ya,Lp as za,qn as Aa,_p as Ba,Dp as Ca,Bp as Da,$p as Ea,ni as Fa,zp as Ga,Gp as Ha,Jp as Ia,Hp as Ja,ri as Ka,Nc as La,Om as Ma,km as Na,Im as Oa,Fm as Pa,Pm as Qa,vm as Ra,Uc as Sa,zc as Ta,Vc as Ua,Vm as Va,Gm as Wa,Jm as Xa,Hm as Ya,Km as Za,Ym as _a,Zm as $a,Qm as ab,Xm as bb,ng as cb,bu as db,rg as eb,Mg as fb,Hi as gb,Ki as hb,Dg as ib,Bg as jb,$g as kb,Wg as lb,Vg as mb,Hg as nb,wr as ob,nn as pb,ah as qb,kh as rb,Oa as sb,Ih as tb,jh as ub,Nh as vb};
|
package/lib/chunk-SRPWW4A2.mjs
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
-
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
-
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
-
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
-
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a as C}from"./chunk-4TLYUZD5.mjs";import{createHash as v}from"node:crypto";var I=new Set(["unmanaged","beta","released"]);function _(c){let{namespacePrefix:a,manageableState:n}=c;return typeof a!="string"||a===""?!1:typeof n!="string"||!I.has(n)}function S(c){let a;try{a=JSON.parse(c)}catch{return!1}return typeof a!="object"||a===null?!1:_(a)}function x(c,a){let n=new Set;for(let t of[c,a])for(let[o,i]of t)S(i)&&n.add(o);let s=t=>new Map([...t].filter(([o])=>!n.has(o)));return{source:s(c),target:s(a),leftOut:n.size}}var N={components:500,seconds:90},k=4,B=3,D=30,w=240,b=class{fetchMetadata;diffEngine;reader;budget;now;constructor(a,n,s,t={}){this.fetchMetadata=a,this.diffEngine=n,this.reader=s,this.budget=t.budget??N,this.now=t.now??Date.now}async compare(a,n,s,t={includeManaged:!0},o){let i=[],d=0;for(let e of s){o?.throwIfAborted();let[p,r]=await Promise.all([this.fetchMetadata(a,e),this.fetchMetadata(n,e)]);if(t.includeManaged){i.push({componentType:e,source:p,target:r});continue}let{source:f,target:g,leftOut:h}=x(p,r);d+=h,i.push({componentType:e,source:f,target:g})}let l=O(i,e=>this.reader.batchSize(e),this.budget.components),m=await this.readPlanned(a,n,l.toRead,o);o?.throwIfAborted();let u=[];for(let{componentType:e,source:p,target:r}of i)u.push(...this.judge(e,p,r,l.toRead.get(e)??[],l.notCompared.get(e)??new Map,m.get(e)));return{items:u,managedLeftOut:d}}async readPlanned(a,n,s,t){let i=this.now()+this.budget.seconds*1e3,d=new Map,l=[];for(let[e,p]of s){let r={source:new Map,target:new Map,unread:new Set};d.set(e,r);let f=this.reader.batchSize(e)??p.length;for(let g=0;g<p.length;g+=f){let h=p.slice(g,g+f);l.push(async()=>{if(t?.throwIfAborted(),this.now()>=i){for(let M of h)r.unread.add(M);return}let[P,A]=await Promise.all([this.readOne(a,e,h,t),this.readOne(n,e,h,t)]);for(let[M,y]of P)r.source.set(M,y);for(let[M,y]of A)r.target.set(M,y)})}}let m=0,u=async()=>{for(;m<l.length;){let e=l[m];m+=1,await e()}};return await Promise.all(Array.from({length:Math.min(k,l.length)},u)),d}async readOne(a,n,s,t){try{return await this.reader.read(a,n,s)}catch(o){return t?.throwIfAborted(),C.warn(`[compare] reading ${s.length} ${n} failed: ${o instanceof Error?o.message:String(o)}`),new Map}}judge(a,n,s,t,o,i){let d=new Map(n),l=new Map(s),m=new Map,u=new Map(o);for(let e of t){let p=i?.source.get(e),r=i?.target.get(e);i?.unread.has(e)?u.set(e,"over_budget"):p===null||r===null?u.set(e,"unreadable"):p===void 0||r===void 0?u.set(e,"read_failed"):(d.set(e,T(p)),l.set(e,T(r)),m.set(e,{source:p,target:r}))}return this.diffEngine.diff(d,l,a,u).map(e=>{let p=[n,s].some(f=>{let g=f.get(e.fullName);return g!==void 0&&S(g)}),r=p?{...e,managed:p}:e;if(r.status==="modified"){let f=m.get(r.fullName),g=f?F(f.source,f.target):void 0;return{...r,sourceValue:g?.source,targetValue:g?.target}}return r.status==="unchanged"?{...r,sourceValue:void 0,targetValue:void 0}:r})}};function O(c,a,n){let s=new Map,t=new Map,o=[],i=[];for(let{componentType:u,source:e,target:p}of c){let r=[...e.keys()].filter(g=>p.has(g)).sort(),f=new Map;if(t.set(u,f),a(u)===void 0){for(let g of r)f.set(g,"unreadable");o.push([]),i.push([]);continue}o.push(r.filter(g=>e.get(g)!==p.get(g))),i.push(r.filter(g=>e.get(g)===p.get(g)))}let d=R(o.map(u=>u.length),n),l=d.reduce((u,e)=>u+e,0),m=R(i.map(u=>u.length),n-l);return c.forEach(({componentType:u},e)=>{let p=t.get(u)??new Map,r=[...o[e].slice(0,d[e]),...i[e].slice(0,m[e])];for(let f of o[e].slice(d[e]))p.set(f,"over_budget");for(let f of i[e].slice(m[e]))p.set(f,"over_budget");r.length>0&&s.set(u,r)}),{toRead:s,notCompared:t}}function R(c,a){let n=c.map(()=>0),s=c.map((i,d)=>d).sort((i,d)=>c[i]-c[d]),t=Math.max(0,a),o=s.length;for(let i of s){let d=Math.min(c[i],Math.floor(t/o));n[i]=d,t-=d,o-=1}return n}function T(c){return v("sha256").update(c).digest("hex")}function F(c,a){let n=c.split(`
|
|
8
|
-
`),s=a.split(`
|
|
9
|
-
`),t=0;for(;t<n.length&&t<s.length&&n[t]===s[t];)t+=1;let o=Math.max(0,t-B);return{source:E(n,o),target:E(s,o)}}function E(c,a){let n=Math.min(c.length,a+D),s=String(n).length,t=c.slice(a,n).map((o,i)=>{let d=o.length>w?`${o.slice(0,w)}\u2026`:o;return`${String(a+i+1).padStart(s)}\u2502 ${d}`});return a>0&&t.unshift("\u2026"),n<c.length&&t.push("\u2026"),t.join(`
|
|
10
|
-
`)}export{_ as a,S as b,N as c,b as d,O as e,F as f};
|