sandforge 1.80.0 → 1.82.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 +48 -0
- package/bin/sandforge-pipeline.mjs +12 -0
- package/bin/sandforge-users.mjs +12 -0
- package/lib/{chunk-J525F5KI.mjs → chunk-27Z76O2O.mjs} +1 -1
- package/lib/chunk-2JZGCCPG.mjs +9 -0
- package/lib/{chunk-ELFXJHU7.mjs → chunk-2UU42PTD.mjs} +1 -1
- package/lib/{chunk-N652NMZ4.mjs → chunk-32EUNQT6.mjs} +52 -52
- package/lib/chunk-3C2ZZIFN.mjs +7 -0
- package/lib/chunk-3CX7GPCR.mjs +7 -0
- package/lib/chunk-3HEMJTAP.mjs +925 -0
- package/lib/{chunk-BY2HJFFG.mjs → chunk-3HROD5RE.mjs} +1 -1
- package/lib/{chunk-OHWNPXWW.mjs → chunk-3MGMNK3Q.mjs} +1 -1
- package/lib/{chunk-PZPJKATS.mjs → chunk-3SKLBRPL.mjs} +8 -8
- package/lib/chunk-3XG25GTF.mjs +7 -0
- package/lib/chunk-42BFLWHR.mjs +7 -0
- package/lib/chunk-466F37VD.mjs +7 -0
- package/lib/chunk-47UHTN3Q.mjs +7 -0
- package/lib/chunk-4JKR4PTZ.mjs +8 -0
- package/lib/{chunk-COFG7Q6R.mjs → chunk-52EXDVPN.mjs} +1 -1
- package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
- package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
- package/lib/chunk-5K2I2DMP.mjs +11 -0
- package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
- package/lib/{chunk-BV6VTP3J.mjs → chunk-6GQUZ4IP.mjs} +1 -1
- package/lib/chunk-6KP6WETK.mjs +9 -0
- package/lib/{chunk-MJVTDA5Q.mjs → chunk-6VSZNZHH.mjs} +1 -1
- package/lib/{chunk-XUWL6ZPC.mjs → chunk-7CVDVBEE.mjs} +1 -1
- package/lib/{chunk-UCD54V2M.mjs → chunk-7EYQYZJP.mjs} +1 -1
- package/lib/{chunk-5K5VLULK.mjs → chunk-7LKI7OAS.mjs} +1 -1
- package/lib/chunk-7PY3VQP3.mjs +7 -0
- package/lib/chunk-7SDZR6SR.mjs +7 -0
- package/lib/chunk-7WSLT5VX.mjs +8 -0
- package/lib/chunk-A32ISQ6M.mjs +28 -0
- package/lib/{chunk-M3ROUWDX.mjs → chunk-A65ADTCR.mjs} +1 -1
- package/lib/chunk-A7JJWOLT.mjs +7 -0
- package/lib/chunk-AUS6NFLZ.mjs +8 -0
- package/lib/chunk-BMTNTBBM.mjs +7 -0
- package/lib/{chunk-SOU4FRYN.mjs → chunk-BN33LVPQ.mjs} +1 -1
- package/lib/chunk-BNKT3R3F.mjs +7 -0
- package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
- package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
- package/lib/{chunk-WA7EYLAQ.mjs → chunk-C2N2TNEU.mjs} +1 -1
- package/lib/{chunk-BKDV4ENO.mjs → chunk-C3LNYAVJ.mjs} +1 -1
- package/lib/{chunk-XLXIPIEW.mjs → chunk-CBL42DUU.mjs} +1 -1
- package/lib/chunk-CCEH7L53.mjs +7 -0
- package/lib/chunk-CELEBWEZ.mjs +7 -0
- package/lib/chunk-CV47FDQW.mjs +7 -0
- package/lib/{chunk-2UZPIMUC.mjs → chunk-CZLJZQCS.mjs} +1 -1
- package/lib/chunk-DBBPDSFN.mjs +7 -0
- package/lib/chunk-DIL62SUN.mjs +7 -0
- package/lib/chunk-DIS254AN.mjs +7 -0
- package/lib/{chunk-BTWDMNN3.mjs → chunk-DJCGURW7.mjs} +1 -1
- package/lib/{chunk-F6GUDTOB.mjs → chunk-DT3T7FRD.mjs} +1 -1
- package/lib/{chunk-IGYH7GMA.mjs → chunk-DWMRIWV5.mjs} +1 -1
- package/lib/{chunk-YRQGKDHM.mjs → chunk-EEFUE2ES.mjs} +1 -1
- package/lib/{chunk-FGRG7ANU.mjs → chunk-EOFO3PHS.mjs} +1 -1
- package/lib/{chunk-KBJ5VERV.mjs → chunk-FA4ZKDCU.mjs} +1 -1
- package/lib/{chunk-WU3GLFZO.mjs → chunk-FKK5YBGZ.mjs} +1 -1
- package/lib/chunk-FOIWWK7G.mjs +156 -0
- package/lib/chunk-FZF23M6R.mjs +7 -0
- package/lib/chunk-G2JR3F63.mjs +7 -0
- package/lib/{chunk-JEERQRLW.mjs → chunk-GBGHJTPC.mjs} +1 -1
- package/lib/{chunk-3RZQZHEB.mjs → chunk-GCGHHN4K.mjs} +1 -1
- package/lib/{chunk-RPI7LRTW.mjs → chunk-GGNUACTY.mjs} +1 -1
- package/lib/{chunk-EMNC6YI4.mjs → chunk-GGUOIDWP.mjs} +1 -1
- package/lib/chunk-GHPR5UVV.mjs +7 -0
- package/lib/{chunk-X5JYBPXP.mjs → chunk-GJ6SZVHT.mjs} +1 -1
- package/lib/{chunk-W622GUAW.mjs → chunk-H4JUYUSL.mjs} +1 -1
- package/lib/{chunk-XAMBCQPU.mjs → chunk-H4OBZIX3.mjs} +1 -1
- package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
- package/lib/{chunk-L77FJZEP.mjs → chunk-HFUDCNU5.mjs} +1 -1
- package/lib/chunk-HIHCYMSL.mjs +7 -0
- package/lib/chunk-HKUWHVI7.mjs +9 -0
- package/lib/chunk-HQQVANWQ.mjs +20 -0
- package/lib/chunk-ICIYL45C.mjs +7 -0
- package/lib/chunk-IRZJU2PG.mjs +22 -0
- package/lib/chunk-ISSP2FZ5.mjs +7 -0
- package/lib/chunk-IVZJSDJD.mjs +7 -0
- package/lib/chunk-J24TIGSI.mjs +10 -0
- package/lib/{chunk-UNJA4J37.mjs → chunk-JESRFE2Z.mjs} +4 -4
- package/lib/chunk-JFNLKHY6.mjs +8 -0
- package/lib/chunk-JH27IKCO.mjs +9 -0
- package/lib/chunk-JJITOWZK.mjs +7 -0
- package/lib/{chunk-E5AHXLS6.mjs → chunk-JKT5YAQ2.mjs} +1 -1
- package/lib/{chunk-IWDREM66.mjs → chunk-JLZRZL5E.mjs} +1 -1
- package/lib/{chunk-FPKYYFM7.mjs → chunk-JPEVIXNH.mjs} +1 -1
- package/lib/chunk-JQZTMFO7.mjs +7 -0
- package/lib/chunk-KIMQQ6JQ.mjs +7 -0
- package/lib/{chunk-MILU7WFN.mjs → chunk-KJYEQHYP.mjs} +1 -1
- package/lib/chunk-KKOA62S4.mjs +474 -0
- package/lib/chunk-KP5G6FUC.mjs +7 -0
- package/lib/{chunk-JWTSEDIQ.mjs → chunk-L4INJ5TZ.mjs} +1 -1
- package/lib/{chunk-OLSGVAIL.mjs → chunk-LAUOSXMN.mjs} +53 -53
- package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
- package/lib/{chunk-KDGMAGQR.mjs → chunk-LHU6CPGE.mjs} +1 -1
- package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
- package/lib/chunk-LXDSRP2W.mjs +7 -0
- package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
- package/lib/{chunk-TTKXMDBN.mjs → chunk-MKTXJCXN.mjs} +4 -4
- package/lib/chunk-MUEQRIK7.mjs +9 -0
- package/lib/{chunk-IOIWJ3DJ.mjs → chunk-NLB3RGIY.mjs} +1 -1
- package/lib/{chunk-O2HDYYUV.mjs → chunk-NWOI25WY.mjs} +1 -1
- package/lib/chunk-O2PUGRNW.mjs +10 -0
- package/lib/chunk-O4BROUGM.mjs +7 -0
- package/lib/chunk-OETEC3P7.mjs +7 -0
- package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
- package/lib/chunk-P55MKIZX.mjs +37 -0
- package/lib/chunk-P63WJMXQ.mjs +7 -0
- package/lib/chunk-PBE44M2Y.mjs +7 -0
- package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
- package/lib/chunk-PE435FVH.mjs +15 -0
- package/lib/chunk-PPGDAUEQ.mjs +7 -0
- package/lib/{chunk-SE4QEZUG.mjs → chunk-PPHVWUFY.mjs} +1 -1
- package/lib/{chunk-CU2INBND.mjs → chunk-PR74GYVI.mjs} +1 -1
- package/lib/chunk-PWVDNN2C.mjs +7 -0
- package/lib/{chunk-6XYKJSGX.mjs → chunk-PYRZFUVU.mjs} +1 -1
- package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
- package/lib/{chunk-DYFALGRT.mjs → chunk-Q3DY7TO2.mjs} +1 -1
- package/lib/{chunk-BGUEWRK2.mjs → chunk-Q6SXNKV2.mjs} +1 -1
- package/lib/chunk-QAPVKPEC.mjs +7 -0
- package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
- package/lib/{chunk-TSLJUSLW.mjs → chunk-RCYEBY42.mjs} +1 -1
- package/lib/chunk-RLWB7F26.mjs +7 -0
- package/lib/{chunk-FXXLX4O6.mjs → chunk-RTWYLOCA.mjs} +1 -1
- package/lib/chunk-RYRMUPMY.mjs +7 -0
- package/lib/chunk-SAMWHL22.mjs +13 -0
- package/lib/{chunk-IZQZ6ZUF.mjs → chunk-SFGZFB4F.mjs} +1 -1
- package/lib/{chunk-FKG7Q3WH.mjs → chunk-SNEOKYV7.mjs} +1 -1
- package/lib/{chunk-3TJON4F3.mjs → chunk-STRMWSIQ.mjs} +1 -1
- package/lib/chunk-SZGGFST2.mjs +272 -0
- package/lib/{chunk-SOGQW4IG.mjs → chunk-T7WREYA5.mjs} +1 -1
- package/lib/{chunk-NTFIRZP6.mjs → chunk-TCBAE65A.mjs} +1 -1
- package/lib/{chunk-KYEDBS54.mjs → chunk-TEIBWMJM.mjs} +1 -1
- package/lib/{chunk-YKKRIEH4.mjs → chunk-TMA34QMA.mjs} +1 -1
- package/lib/chunk-TQ2TQHTT.mjs +9 -0
- package/lib/{chunk-HEKAZJRH.mjs → chunk-TWV4A5RK.mjs} +1 -1
- package/lib/{chunk-CEX3NEZL.mjs → chunk-UHFLKP26.mjs} +1 -1
- package/lib/chunk-UV74P4H2.mjs +7 -0
- package/lib/{chunk-WR4Q363I.mjs → chunk-V3R45ZWT.mjs} +1 -1
- package/lib/{chunk-GSKCGQIP.mjs → chunk-VPDEJGPS.mjs} +1 -1
- package/lib/{chunk-HLWMJF6Y.mjs → chunk-VQJMP3DC.mjs} +1 -1
- package/lib/chunk-VV3B6IC3.mjs +7 -0
- package/lib/{chunk-PJ5I73CK.mjs → chunk-VYOYXTCU.mjs} +1 -1
- package/lib/{chunk-NZC67CGR.mjs → chunk-VZT4E2OJ.mjs} +1 -1
- package/lib/{chunk-AEKONPF4.mjs → chunk-VZVICK7Q.mjs} +1 -1
- package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
- package/lib/chunk-WEMLDUQA.mjs +7 -0
- package/lib/{chunk-MYW5QNGI.mjs → chunk-WOOUISSO.mjs} +1 -1
- package/lib/{chunk-G35N4P7D.mjs → chunk-WSUKC2U3.mjs} +1 -1
- package/lib/{chunk-ZVAED4QV.mjs → chunk-WT3SCUHS.mjs} +1 -1
- package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
- package/lib/{chunk-DBB3EMIN.mjs → chunk-XFU3HRUV.mjs} +1 -1
- package/lib/chunk-XK5W7BVE.mjs +7 -0
- package/lib/{chunk-2GTBABKU.mjs → chunk-XO5FBOQF.mjs} +1 -1
- package/lib/{chunk-CHYDMRSV.mjs → chunk-XSKPYGMT.mjs} +1 -1
- package/lib/chunk-XU25YA46.mjs +9 -0
- package/lib/chunk-XZISAZA6.mjs +7 -0
- package/lib/chunk-Y4TDVDP2.mjs +13 -0
- package/lib/chunk-YAIIRFKJ.mjs +8 -0
- package/lib/{chunk-LKQ5RKIV.mjs → chunk-YAJQS3OL.mjs} +1 -1
- package/lib/{chunk-74Q6DORA.mjs → chunk-YGJF55VJ.mjs} +1 -1
- package/lib/chunk-YH4DYI6D.mjs +7 -0
- package/lib/chunk-YMDFF657.mjs +10 -0
- package/lib/{chunk-2BA2XKAY.mjs → chunk-YT22LMF7.mjs} +1 -1
- package/lib/{chunk-IG2MTQRP.mjs → chunk-Z42PHCVZ.mjs} +1 -1
- package/lib/{chunk-2NBYT7GR.mjs → chunk-ZHIZY3ZC.mjs} +1 -1
- package/lib/chunk-ZQO5PDX5.mjs +48 -0
- package/lib/chunk-ZRUDYB7O.mjs +7 -0
- package/lib/{chunk-BXU6WFMH.mjs → chunk-ZUBBEP75.mjs} +1 -1
- package/lib/chunk-ZUOPC4W2.mjs +7 -0
- package/lib/{chunk-GGD7ON3M.mjs → chunk-ZUTUYBNW.mjs} +1 -1
- package/lib/{chunk-MHMH6MTP.mjs → chunk-ZXFL2MSN.mjs} +1 -1
- package/lib/sandforge-autopilot.mjs +11 -11
- package/lib/sandforge-backup.mjs +63 -32
- package/lib/sandforge-checkpoint.mjs +1 -348
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +1 -1
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +11 -11
- package/lib/sandforge-env.mjs +186 -140
- package/lib/sandforge-frozen.mjs +1 -266
- package/lib/sandforge-mcp.mjs +33 -14
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +88 -0
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +157 -0
- package/lib/sandforge.mjs +1 -22
- package/lib/sf/sandforge/autopilot.mjs +20 -0
- package/lib/sf/sandforge/backup.mjs +20 -0
- package/lib/sf/sandforge/checkpoint.mjs +20 -0
- package/lib/sf/sandforge/cleanup.mjs +20 -0
- package/lib/sf/sandforge/clone.mjs +20 -0
- package/lib/sf/sandforge/compare.mjs +20 -0
- package/lib/sf/sandforge/dataops.mjs +20 -0
- package/lib/sf/sandforge/empty.mjs +20 -0
- package/lib/sf/sandforge/env.mjs +20 -0
- package/lib/sf/sandforge/frozen.mjs +20 -0
- package/lib/sf/sandforge/hardis-commands.mjs +20 -0
- package/lib/sf/sandforge/index.mjs +20 -0
- package/lib/sf/sandforge/mcp.mjs +20 -0
- package/lib/sf/sandforge/monitor.mjs +20 -0
- package/lib/sf/sandforge/pipeline.mjs +20 -0
- package/lib/sf/sandforge/seed.mjs +20 -0
- package/lib/sf/sandforge/sync.mjs +20 -0
- package/lib/sf/sandforge/users.mjs +20 -0
- package/lib/sfHelpHook.mjs +7 -0
- package/lib/sfPlugin.mjs +11 -0
- package/oclif.manifest.json +1 -0
- package/package.json +18 -3
- package/lib/chunk-2CNCDM56.mjs +0 -7
- package/lib/chunk-3F6Q5E7I.mjs +0 -14
- package/lib/chunk-4VS2V6WU.mjs +0 -25
- package/lib/chunk-5P4PHJRL.mjs +0 -9
- package/lib/chunk-5TC3QB4U.mjs +0 -10
- package/lib/chunk-7ABODJ4G.mjs +0 -7
- package/lib/chunk-7EGQP6S4.mjs +0 -7
- package/lib/chunk-7FFGJWHN.mjs +0 -7
- package/lib/chunk-7YDNUBO5.mjs +0 -7
- package/lib/chunk-A527W53V.mjs +0 -7
- package/lib/chunk-ADOAS63R.mjs +0 -7
- package/lib/chunk-B5QQJ4SI.mjs +0 -7
- package/lib/chunk-CION3VMZ.mjs +0 -7
- package/lib/chunk-CSBS5U5I.mjs +0 -7
- package/lib/chunk-DB7RBE5D.mjs +0 -7
- package/lib/chunk-E5ZB3LU5.mjs +0 -7
- package/lib/chunk-EFR2Y7E4.mjs +0 -7
- package/lib/chunk-EHQ3FX6X.mjs +0 -7
- package/lib/chunk-EQNW3UC2.mjs +0 -7
- package/lib/chunk-F43REJDZ.mjs +0 -10
- package/lib/chunk-GSG7WZHM.mjs +0 -7
- package/lib/chunk-HOJYWTP7.mjs +0 -20
- package/lib/chunk-HS4YRX4J.mjs +0 -7
- package/lib/chunk-I7O6C2B5.mjs +0 -8
- package/lib/chunk-IFETCRWE.mjs +0 -10
- package/lib/chunk-IQXHJEYB.mjs +0 -7
- package/lib/chunk-JPUR2CFX.mjs +0 -10
- package/lib/chunk-K327QKMD.mjs +0 -7
- package/lib/chunk-KRCA6IPH.mjs +0 -8
- package/lib/chunk-LPBMBW3O.mjs +0 -13
- package/lib/chunk-LWW4U276.mjs +0 -7
- package/lib/chunk-MFG4MUIO.mjs +0 -9
- package/lib/chunk-MJU2PGZQ.mjs +0 -15
- package/lib/chunk-OAZRPP4I.mjs +0 -7
- package/lib/chunk-OO6CLPEH.mjs +0 -7
- package/lib/chunk-OPXCV2KL.mjs +0 -7
- package/lib/chunk-P33PSCXK.mjs +0 -7
- package/lib/chunk-Q3DM32KF.mjs +0 -11
- package/lib/chunk-QR3WELJQ.mjs +0 -7
- package/lib/chunk-QWT2C74M.mjs +0 -7
- package/lib/chunk-R3X3LV64.mjs +0 -14
- package/lib/chunk-RMBPOTD7.mjs +0 -7
- package/lib/chunk-SIHORWVK.mjs +0 -7
- package/lib/chunk-T62WNR54.mjs +0 -7
- package/lib/chunk-TTFDUKUS.mjs +0 -47
- package/lib/chunk-VE6XKGGD.mjs +0 -7
- package/lib/chunk-VGW4MXXZ.mjs +0 -7
- package/lib/chunk-VS7ZXUII.mjs +0 -824
- package/lib/chunk-VXQLDM4R.mjs +0 -7
- package/lib/chunk-VYXMVJL5.mjs +0 -7
- package/lib/chunk-W7U5E5ZL.mjs +0 -9
- package/lib/chunk-WXAQ7FK3.mjs +0 -115
- package/lib/chunk-YS4G22C2.mjs +0 -7
- package/lib/chunk-ZM6OJGIG.mjs +0 -7
- package/lib/chunk-ZUTYVST5.mjs +0 -7
package/lib/chunk-VS7ZXUII.mjs
DELETED
|
@@ -1,824 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
-
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
-
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
-
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
-
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{b as ka,c as bp,d as Rp}from"./chunk-SOU4FRYN.mjs";import{b as Tf}from"./chunk-E5AHXLS6.mjs";import{d as qi,k as lu,o as uu,q as Hi,r as pu}from"./chunk-OO6CLPEH.mjs";import{a as ap}from"./chunk-YS4G22C2.mjs";import{a as dp}from"./chunk-QROPNEGY.mjs";import{b as yr,e as qn}from"./chunk-BZ24IAP5.mjs";import{a as Qt}from"./chunk-SCKUIE3R.mjs";import{a as so,c as xt,d as $n,e as si,f as xn,g as io,h as ii,j as ai}from"./chunk-AV5SWEHP.mjs";import{$ as Ep,A as Xn,Aa as Hp,B as Ce,Ba as Kp,C as lp,Ca as Vp,Cb as Af,D as rs,Da as Jp,Db as Ba,E as Ra,Ea as Yp,Eb as jf,F as Oa,Fa as Qp,Fb as vf,G as up,Ga as Ia,H as pp,Ha as Ea,Hb as La,I as fp,Ia as $a,Ib as Wa,J as hp,Ja as Xp,Jb as If,K as gp,Ka as xa,Kb as Ef,L as mp,La as Dt,Lb as $f,M as wp,Ma as Zp,Mb as xf,N as yp,O as Zn,Oa as ef,P as os,Q as wn,R as Op,Ra as Pa,S as kp,Sa as tf,T as Sp,Ta as nf,U as Sa,Ua as rf,V as Tp,Va as Ca,W as Ap,Wa as of,X as jp,Y as vp,Ya as sf,Z as Ip,Za as af,_ as Ta,_a as df,aa as $p,ba as le,ca as Tt,cb as cf,da as xp,db as lf,ea as Aa,eb as Fa,fa as Pp,ga as Cp,gb as uf,h as zu,ha as Fp,i as la,ia as Np,ib as pf,ja as ss,jb as ff,ka as Mp,kb as hf,l as Gu,la as ja,lb as gf,ma as er,mb as mf,n as qu,na as Bp,nb as Na,oa as Lp,ob as wf,pa as Wp,pb as yf,qb as Ma,rb as bf,s as Hu,sa as Dp,sb as Rf,ta as _p,tb as Of,ua as tr,ub as kf,v as Ku,va as Up,w as Vu,wa as va,x as Ju,xa as zp,y as ba,ya as Gp,yb as Sf,z as cp,za as qp}from"./chunk-4VS2V6WU.mjs";import{e as Yu,f as Qu,g as ua,h as Zo,i as ep,j as tp,k as np,l as rp,m as op,n as fa,o as Qn}from"./chunk-KYEDBS54.mjs";import{a as Er,b as ns,c as sp,d as ip,e as ha,f as ga,g as ma,h as wa,j as ya}from"./chunk-6XYKJSGX.mjs";import{c as pa,e as es,f as Xu,g as Zu,h as ts}from"./chunk-K2FBZIXY.mjs";import{a as xi,b as yl,c as bl,d as Rl,f as Tr,g as $o,h as Pi,n as El}from"./chunk-F43REJDZ.mjs";import{$ as yu,C as Ei,H as Io,N as Kn,O as wl,P as Sr,Q as Eo,U as Sl,V as Tl,Z as wu,a as Cc,m as Ii}from"./chunk-JPUR2CFX.mjs";import{c as qo,m as bu}from"./chunk-LPBMBW3O.mjs";import{a as jl,b as xo,c as vl,d as Il}from"./chunk-T63U4OZJ.mjs";import{d as Al}from"./chunk-DBFJB2B6.mjs";import{h as Ci}from"./chunk-PZPJKATS.mjs";import{a as $i}from"./chunk-QSRAEUGZ.mjs";import{a as au}from"./chunk-DYFALGRT.mjs";import{b as du,c as Gi,e as cu}from"./chunk-M6P5ZZLE.mjs";import{a as eu,b as vr,c as tu,d as Go,f as nu,g as ru,h as zi,i as ou,j as su,k as iu}from"./chunk-7FFGJWHN.mjs";import{h as Zl,i as Ui,j as zo}from"./chunk-G35N4P7D.mjs";import{a as $l}from"./chunk-YYZL7UGV.mjs";import{a as ll,c as ji,g as ul,h as pl,i as fl}from"./chunk-SAR5622P.mjs";import{a as Rc,b as En,c as pn}from"./chunk-KDGMAGQR.mjs";import{B as Vn,s as Fi,t as Ar,v as Fl,w as Po,y as Ni,z as Mi}from"./chunk-MFG4MUIO.mjs";import{a as Gc,b as qc,c as Pn,d as rl,e as ol,h as sl,i as il,j as al,k as dl,l as cl,m as Ai}from"./chunk-EQNW3UC2.mjs";import{d as Cn}from"./chunk-GSKCGQIP.mjs";import{g as oo}from"./chunk-HS4YRX4J.mjs";import{a as ze,i as Hc,k as mo,n as wo,o as Kc,p as yo,q as Vc,r as bo,s as Jc,t as Yc,u as Ro,v as Qc,w as Oo}from"./chunk-ZUTYVST5.mjs";import{a as Ol,d as kl}from"./chunk-TUACWKIH.mjs";import{$ as Eu,$a as da,Ba as sa,C as ku,D as Ho,E as Su,Ea as Bu,Fa as Lu,Ia as Xt,K as Ko,L as Ir,M as Yi,Ma as Wu,Oa as Du,P as Vo,Pa as Xo,Q as Tu,S as mn,Ta as St,V as Au,W as ju,Wa as ia,X as vu,Xa as aa,Y as Iu,Ya as _u,Z as Qi,_ as Xi,_a as Uu,aa as $u,ab as ca,ba as xu,c as yi,da as Jo,e as Fc,ea as Pu,fa as Yo,g as go,ga as Cu,ha as Fu,i as Nc,ia as Nu,j as bi,ja as Qo,k as Ri,ka as Zi,l as Mc,m as Oi,n as ki,pa as ea,r as xl,ra as ta,s as Pl,sa as na,w as Cl,wa as ra,xa as oa,y as Yn,ya as Mu}from"./chunk-VYXMVJL5.mjs";import{i as Vi,q as Ji,r as Ru,s as Ou}from"./chunk-AEKONPF4.mjs";import{a as fo,b as ho,c as Or,e as Pc}from"./chunk-JWTSEDIQ.mjs";import{a as nt}from"./chunk-4TLYUZD5.mjs";import{A as Jl,Aa as mu,B as Wo,C as Wi,D as Yl,E as Wt,F as Do,G as gn,H as Di,I as Ql,J as jr,K as Xl,L as _o,M as Fn,a as Nl,aa as fu,b as Co,c as Jn,ca as hu,d as Ml,e as Bl,ea as Ki,f as Fo,g as Ll,h as No,i as Mo,j as Wl,k as Bi,l as Li,m as Dl,n as _l,o as Ul,p as hn,q as zl,r as Bo,s as Gl,t as Je,u as ql,v as Hl,w as Lo,wa as gu,y as Kl,z as Vl}from"./chunk-CION3VMZ.mjs";import{b as Xc,c as To,d as Zc,e as el,f as tl,g as Ao,i as nl,l as jo,m as vo}from"./chunk-WIO4XO4F.mjs";import{a as Ti,c as zc}from"./chunk-EADHKH3A.mjs";import{a as ko,b as So}from"./chunk-GCOB7K5N.mjs";import{a as kr,c as Bc,d as Si,e as Lc,f as Wc,g as Dc,h as _c,j as Uc}from"./chunk-INIT2UKJ.mjs";import{a as yc}from"./chunk-SU65Z2BA.mjs";import{a as Uo,b as _i}from"./chunk-HF6LAK3G.mjs";import{$ as wi,B as ui,C as uo,D as Hn,E as Ue,F as Pe,G as pi,H as Rr,K as fi,L as hi,M as Ic,P as gi,W as mi,aa as Ec,b as je,c as st,ca as $c,e as kc,f as Sc,g as Tc,h as Ac,ia as xc,ja as po,l as jc,m as di,n as co,o as ci,p as ye,q as he,r as br,s as fn,t as lo,v as li,y as vc}from"./chunk-A527W53V.mjs";import{a as ao,h as Me}from"./chunk-TZE3Y7IQ.mjs";import{c as hl,f as gl,j as vi,k as ml}from"./chunk-GGD7ON3M.mjs";import{b as Y}from"./chunk-CA5NAXSU.mjs";import{a as bc,c as Oc,g as Pf}from"./chunk-MTMH6H2A.mjs";import{Cb as Ze,Db as pr,E as In,F as Xr,Fb as fr,Gc as mr,Hb as We,Hc as hc,Ib as Rt,Jb as Ot,Jc as gc,Kb as ti,Lb as lt,M as nc,Nb as dc,Ob as kt,Pb as Bt,Pc as ni,Q as rc,Qb as hr,Rb as Lt,Sb as ut,T as Zr,Tb as gr,U as oc,Ub as cc,Uc as ri,Xb as lc,Xc as mc,Y as un,Yb as uc,Z as sc,aa as ei,ad as wc,ed as wr,fa as ic,fd as no,gc as Gn,ic as eo,kd as ro,ld as oi,uc as pc,vc as fc,xb as ur,zb as ac,zc as to}from"./chunk-TTFDUKUS.mjs";import{A as W}from"./chunk-7EANH5PY.mjs";import{createHash as ry,randomUUID as Es}from"node:crypto";import{existsSync as Sn,readFileSync as kn,readdirSync as oy,renameSync as jg,rmSync as $d,statSync as vg,writeFileSync as Ig}from"node:fs";import{homedir as sy}from"node:os";import{basename as iy,dirname as ay,join as $s,resolve as Ct,sep as dy}from"node:path";function nr(){let r=process.env[ap]?.trim();return r===void 0||r===""?void 0:r}function Zt(){return nr()?.startsWith("sandforge env")===!0}function yn(r,e){return Zt()?e:r}var im=new Map([["sandforge env",["--sweep","--include-changed"]],["sandforge env, relayed by sandforge mcp",["--include-changed"]],["sandforge mcp",["--mute-automation","--leave-undeletable","--store","--include-changed"]]]);function ht(r){let e=nr();return e===void 0||im.get(e)?.includes(r)===!0}function bn(r,e){return ht(r)?r:e===void 0?`this script's own ${r}`:`this script's own ${e} with ${r}`}import{createReadStream as am,existsSync as dm}from"node:fs";import{createInterface as cm}from"node:readline";var Cf=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function lm(r){let e=[],t=cm({input:am(r,"utf8"),crlfDelay:1/0}),n=(o,s)=>{typeof s!="string"||!Number.isFinite(Date.parse(s))||(o.endedAt===void 0||Date.parse(s)>Date.parse(o.endedAt))&&(o.endedAt=s)};for await(let o of t){let s=e.at(-1);if(o.startsWith('{"part":')){try{let{part:p}=JSON.parse(o),f=typeof p?.startedAt=="string"?p.startedAt:void 0;e.push({...f?{startedAt:f}:{},wrote:[]})}catch{e.push({wrote:[]})}continue}if(!s)continue;if(o.startsWith('{"end":')){try{n(s,JSON.parse(o).end?.at)}catch{}continue}let i=bu(o);if(i){n(s,i.at),(s.jobEndedAt===void 0||Date.parse(i.orgAt)>Date.parse(s.jobEndedAt))&&(s.jobEndedAt=i.orgAt);continue}if(!o.startsWith('["x"')&&!o.startsWith('["p"')&&!o.startsWith('["g"'))continue;let a;try{a=JSON.parse(o)}catch{continue}if(!Array.isArray(a))continue;let[d,c,l,u]=a;d==="x"?n(s,u):d==="p"&&typeof c=="string"&&Cf.test(c)?s.wrote.push(c):d==="g"&&typeof l=="string"&&Cf.test(l)&&s.wrote.push(l)}return e}async function Ff(r,e){if(!dm(r))return[];let t;try{t=await lm(r)}catch{return[]}let n=[];for(let[o,s]of t.entries()){let i=await e.readAt(r,o).catch(()=>{});if(!i)return[];n.push({part:o,created:i.created,linked:i.remap.linked.flatMap(a=>{let d=i.remap.table[a];return d!==void 0?[d]:[]}),wrote:s.wrote,...s.startedAt?{startedAt:s.startedAt}:{},...s.endedAt?{endedAt:s.endedAt}:{},...s.jobEndedAt?{jobEndedAt:s.jobEndedAt}:{}})}return n}function Nn(r){let e=Date.parse(r.endedAt??"");if(!Number.isFinite(e))return;let t=Date.parse(r.startedAt??""),n=Date.parse(r.jobEndedAt??"");return{runRecordedAt:new Date(e),runDurationMs:Number.isFinite(t)&&t<=e?e-t:0,endedByItsWrites:!0,...Number.isFinite(n)?{writtenUntil:new Date(n)}:{}}}function rr(r,e){return r.flatMap(t=>{if(t.part<=e||t.wrote.length===0&&t.linked.length===0)return[];let n=Nn(t);return n?[{span:{runRecordedAt:n.runRecordedAt,runDurationMs:n.runDurationMs},wrote:t.wrote,linked:t.linked}]:[]})}function Mn(r){return r.flatMap(e=>e.ids)}function en(r,e){if(e===void 0)return r.map(n=>({...n,ids:[...n.ids]}));let t=new Set(e.map(n=>n.slice(0,15)));return r.flatMap(n=>{let o=n.ids.filter(s=>t.has(s.slice(0,15)));return o.length>0?[{objectApiName:n.objectApiName,ids:o}]:[]})}function Fe(r,e=Date.now()){return Math.max(0,e-r)}var Da=class{listenerMap=new Map;on(e,t){let n=this.listenerMap.get(e);return n||(n=new Set,this.listenerMap.set(e,n)),n.add(t),()=>{n.delete(t)}}emit(e,t){let n=this.listenerMap.get(e);if(n)for(let o of n)try{o(t)}catch(s){nt.warn("Event listener threw an error",{eventType:String(e),error:Y(s)})}}removeAllListeners(){this.listenerMap.clear()}};var $r=class r{constructor(e){this.store=e}store;map=new Map;existing=new Set;updated=new Set;objectOf=new Map;aliases=new Map;createdKeys=new Set;alias(e,t){e!==t&&this.aliases.set(e,t)}add(e,t,n){if(this.store){this.store.setMapping("created",e,t,n);return}this.forgetCreated(e),this.createdKeys.add(t.slice(0,15)),this.map.set(e,t),this.existing.delete(e),this.updated.delete(e),this.label(e,n)}addUpdated(e,t,n){if(this.store){this.store.setMapping("updated",e,t,n);return}this.forgetCreated(e),this.map.set(e,t),this.existing.delete(e),this.updated.add(e),this.label(e,n)}addExisting(e,t,n){if(this.store){this.store.setMapping("existing",e,t,n);return}this.forgetCreated(e),this.map.set(e,t),this.existing.add(e),this.updated.delete(e),this.label(e,n)}countsByObject(){if(this.store)return this.store.countsByObject();let e=new Map;for(let[t,n]of this.objectOf){let o=e.get(n)??{objectApiName:n,created:0,linked:0,updated:0};this.existing.has(t)?o.linked++:this.updated.has(t)?o.updated++:o.created++,e.set(n,o)}return[...e.values()].map(({updated:t,...n})=>t>0?{...n,updated:t}:n)}createdByObject(){let e=new Map;if(this.store){for(let{kind:t,sourceId:n,objectApiName:o,earlier:s}of this.store.mappings()){if(t!=="created"||s||!o)continue;let i=e.get(o)??[];i.push(n),e.set(o,i)}return[...e].map(([t,n])=>({objectApiName:t,sourceIds:n}))}for(let[t,n]of this.objectOf){if(this.existing.has(t)||this.updated.has(t))continue;let o=e.get(n)??[];o.push(t),e.set(n,o)}return[...e].map(([t,n])=>({objectApiName:t,sourceIds:n}))}forgetCreated(e){let t=this.map.get(e);t!==void 0&&!this.existing.has(e)&&!this.updated.has(e)&&this.createdKeys.delete(t.slice(0,15))}createdTarget(e){return this.store?this.store.createdTarget(e):this.createdKeys.has(e.slice(0,15))}label(e,t){t?this.objectOf.set(e,t):this.objectOf.delete(e)}isExisting(e){if(this.store){let t=this.store.mapping(e);return t!==void 0&&(t.kind==="existing"||t.earlier)}return this.existing.has(e)}isCreated(e){if(this.store){let t=this.store.mapping(e);return t!==void 0&&t.kind==="created"&&!t.earlier}return this.map.has(e)&&!this.existing.has(e)&&!this.updated.has(e)}wasCreated(e){return this.store?this.store.mapping(e)?.kind==="created":this.isCreated(e)}existingSourceIds(){return this.store?[...this.store.mappings()].filter(({kind:e,earlier:t})=>e==="existing"||t).map(({sourceId:e})=>e):[...this.existing]}updatedSourceIds(){return this.store?[...this.store.mappings()].filter(({kind:e,earlier:t})=>e==="updated"&&!t).map(({sourceId:e})=>e):[...this.updated]}get(e){let t=this.aliases.get(e)??e;return this.store?this.store.targetOf(t):this.map.get(t)}remapRecord(e,t){let n={...e};for(let o of t){let s=n[o];if(typeof s=="string"){let i=this.aliases.size>0?this.aliases.get(s)??s:s,a=this.store?this.store.targetOf(i):this.map.get(i);a!==void 0&&(n[o]=a)}}return n}persist(){this.store?.flush()}get count(){return this.store?this.store.mappedSize:this.map.size}clear(){this.aliases.clear(),this.map.clear(),this.existing.clear(),this.updated.clear(),this.objectOf.clear(),this.createdKeys.clear()}toJSON(){let e={};if(this.store){for(let{sourceId:t,targetId:n}of this.store.mappings())e[t]=n;return e}for(let[t,n]of this.map)e[t]=n;return e}static fromJSON(e){let t=new r;for(let[n,o]of Object.entries(e))n==="__proto__"||n==="constructor"||n==="prototype"||typeof o=="string"&&t.add(n,o);return t}};var pm={BusinessHours:"Name",OperatingHours:"Name",ServiceTerritory:"Name"},is=class{constructor(e){this.query=e}query;async resolve(e,t,n,o){if(t.length===0)return{mappings:[],unmatched:[]};let s=o??pm[e]??"Name",i=Me(e),a=Me(s),d=new Map;for(let b of t){let S=b.Id,R=b[s];typeof S=="string"&&typeof R=="string"&&R&&d.set(S,R)}if(d.size===0)return{mappings:[],unmatched:t.map(b=>({sourceId:typeof b.Id=="string"?b.Id:"",matchValue:typeof b[s]=="string"?b[s]:null})).filter(b=>b.sourceId.length>0)};let c=`SELECT Id, ${a} FROM ${i} WHERE ${a} IN (`,l=kr(`${c})`),u=kr(", "),p=new Map,f=[],h=l,g=async()=>{if(f.length===0)return;let b=`${c}${f.join(", ")})`;f=[],h=l;for(let S of await this.query(n,b)){let R=S.Id,k=S[s];typeof R=="string"&&typeof k=="string"&&p.set(k,R)}};for(let b of new Set(d.values())){let S=`'${ao(b)}'`,R=(f.length>0?u:0)+kr(S);f.length>=zl||f.length>0&&h+R>14e3?(await g(),h+=kr(S)):h+=R,f.push(S)}await g();let m=[],w=[];for(let[b,S]of d){let R=p.get(S);R?m.push({sourceId:b,targetId:R,matchedBy:s,matchValue:S}):w.push({sourceId:b,matchValue:S})}return{mappings:m,unmatched:w}}};function _a(r,e){let t=new Set(r.filter(s=>s.createable).map(s=>s.name)),n=new Set(r.filter(s=>s.updateable!==!1).map(s=>s.name)),o=new Map;for(let s of r)s.picklistValues&&s.picklistValues.length>0&&o.set(s.name,new Set(s.picklistValues));return{creatable:t,updateable:n,picklistValuesByField:o.size>0?o:null,picklistFields:Nl(r,e),fields:r}}async function tn(r,e,t){return _a(await r(e,t),t)}function Ua(r,e,t){return e?e.has(t??r.name):r.updateable!==!1}function or(r,e){let t=new Set;for(let n of r)e.has(n)&&t.add(n);return t}var fm=new Map;function Nf(r){let{objectApiName:e,records:t,fieldInfos:n,remapper:o,referenceFallback:s,failedObjects:i,writtenObjects:a,neverCopied:d,ownerMappings:c,resolvedLookups:l,targetLacks:u,inactiveOwners:p,excludedFields:f,fieldRename:h,creatableFields:g,updatableFields:m,picklistValuesByField:w,picklistFields:b,recordTypeValues:S,businessAccounts:R,contactPoints:k,decide:I,currencies:O,currencyFields:A=fm,parentCurrencies:x,pricedIn:j,outsideTheSample:E}=r,$=n.filter(H=>H.isReference).map(H=>H.name),L=new Set($),Q=k?.forObject(e,n,h),G=H=>g.has(H.name)||h[H.name]!==void 0,V=new Set(n.filter(H=>H.isReference&&(H.referenceTo??[]).some(pe=>i?.has(pe))).map(H=>H.name)),q=new Set(n.filter(H=>{let pe=H.referenceTo??[];return H.isReference&&pe.length===1&&a?.has(pe[0])===!0}).map(H=>H.name)),me=Pc(n.filter(H=>H.isReference),d),de=b??new Map;return t.map(H=>{let pe=[],ue=[],be=[],ne=l?.get(H);for(let M of n){if(!M.isReference||f.has(M.name)||ne?.[M.name]!==void 0)continue;let $e=G(M),ve=Ua(M,m,h[M.name]);if(!$e&&!ve)continue;let Ne=H[M.name];if(E&&M.name!=="RecordTypeId"&&typeof Ne=="string"&&Ne!==""&&!o.get(Ne)&&E(M,Ne)){ue.push(M.name),be.push(h[M.name]??M.name);continue}if(s!=="nullify"&&!V.has(M.name)&&!q.has(M.name)||M.name==="RecordTypeId"||me.has(M.name))continue;let ke=H[M.name];typeof ke!="string"||!ke||$e&&o.get(ke)||(ue.push(M.name),pe.push({field:h[M.name]??M.name,sourceRefId:ke,targetObjects:M.referenceTo??[],...ve?{}:{insertOnly:!0}}))}let K=$.filter(M=>M!=="RecordTypeId"),Z=o.remapRecord(H,K);for(let M of ue)Z[M]=null;for(let[M,$e]of Object.entries(ne??{}))Z[M]=$e;let U=Z.OwnerId,se=!1;typeof U=="string"&&c[U]&&(Z.OwnerId=c[U],se=!0);let Se=lo(Z,R?.has(H)===!0),ge={},Te=new Set,De=[],_=[],P;for(let M of Object.keys(Z)){if(f.has(M))continue;let $e=h[M];if($e){Z[M]!==null&&(ge[$e]=Z[M]),Te.add($e);continue}if(!g.has(M))continue;if(ne?.[M]!==void 0){ge[M]=ne[M];continue}if(M!=="RecordTypeId"&&me.has(M)&&!(M==="OwnerId"&&se)){if(s!=="keep")continue;let Ne=Z[M];if(typeof Ne=="string"&&u?.has(Ne)){De.push(M);continue}if(M==="OwnerId"&&typeof Ne=="string"&&p?.has(Ne)){P=Ne;continue}}else if(s==="keep"&&M!=="RecordTypeId"&&L.has(M)){let Ne=Z[M];if(typeof Ne=="string"&&u?.has(Ne)){_.push(M);continue}}if(eo(e,M,Se))continue;let ve=Z[M];ve!==null&&(ge[M]=ve)}let z=ge.RecordTypeId;I?.(ge,typeof z=="string"?z:void 0);for(let M of cc(e,ge))delete ge[M];let ee;O&&!Te.has(ze)?ee=yo(ge,{read:H[ze],currencyFields:A,recordTypeDefault:Jn(S,z)?.picklists.get(ze)?.defaultValue,ratesOn:mo(e,H),pricedIn:j?.(H)},O):x&&(ee=Yc(ge,{read:H[ze],parent:Jc(e,H,$,x.changeOf),currencyFields:A},x.currencies));let X=Co(ge,w,de,Jn(S,z),Te),_e=jc(e,ge);for(let M of _e)delete ge[M];return Q?.(ge),{source:H,cleaned:ge,nullifiedFks:pe.filter(M=>!_e.includes(M.field)),picklistChanges:X,...ee?{currencyChange:ee}:{},...De.length>0?{lookupsNotCarried:De}:{},..._.length>0?{lookupsOutsideTheRun:_}:{},...be.length>0?{lookupsOutsideTheSample:be}:{},...P!==void 0?{ownerInactive:P}:{}}})}var hm=/^[a-zA-Z0-9]{15}([a-zA-Z0-9]{3})?$/,Mf=Symbol("left to the platform"),as=class{constructor(e){this.deps=e}deps;expansionsUsed=0;failedOrphans=new Set;expansionErrors=[];pastTheCap=new Map;cap=0;async expandForNode(e){if(!e.enabled)return;this.cap=e.maxExpansions;let{fieldInfos:t,records:n,remapper:o,scopeCache:s}=e,i=new Map,a=t.filter(u=>u.isReference&&u.nillable===!1&&u.name!=="RecordTypeId");for(let u of n)for(let p of a){let f=u[p.name];if(typeof f!="string"||!f||o.get(f)||e.leftToThePlatform?.has(f))continue;let h=await this.parentObjectOf(e,p,f);if(!h)continue;let g=`${h}::${f}`;i.has(g)||i.set(g,{object:h,sourceId:f})}let d=4,c=[];for(let[,u]of i){let p=`${u.object}::${u.sourceId}`;if(!this.failedOrphans.has(p)&&!o.get(u.sourceId)){if(this.expansionsUsed+c.length>=e.maxExpansions){this.pastTheCap.set(p,u.object);continue}c.push({...u,cacheKey:p})}}let l=[c.filter(u=>u.object!==he),c.filter(u=>u.object===he)];for(let u of l){let p=[];for(let f=0;f<u.length;f+=d){let h=u.slice(f,f+d).filter(g=>!o.get(g.sourceId));await Promise.all(h.map(async g=>{try{let m=await this.expandSingleOrphanParent(e,g.object,g.sourceId);if(m===Mf)return;m&&"id"in m?(this.expansionsUsed++,this.pastTheCap.delete(g.cacheKey),m.existing?o.addExisting(g.sourceId,m.id,g.object):(o.add(g.sourceId,m.id,g.object),m.owedStatus&&e.oweStatus?.(g.object,m.id,m.owedStatus),m.callId!==void 0&&e.calls?.answered(m.callId),o.persist()),s&&s.add(g.object,[g.sourceId]),g.object===ye&&fn(m.source)&&p.push(m.source)):(this.failedOrphans.add(g.cacheKey),this.expansionErrors.length<3&&this.expansionErrors.push({recordSummary:`${g.object}/${g.sourceId}`,messages:m&&m.refused.length>0?m.refused:["Orphan parent expansion produced no new id"]}))}catch(m){this.failedOrphans.add(g.cacheKey),this.expansionErrors.length<3&&this.expansionErrors.push({recordSummary:`${g.object}/${g.sourceId}`,messages:[Y(m)]})}}))}p.length>0&&await e.linkPersonContacts?.(p)}}async parentObjectOf(e,t,n){let o=t.referenceTo??[],s=o.filter(a=>!fo(a)),i;return o.length===1?i=s[0]:s.length>0&&(i=await e.objectOf?.(n,s)),i===e.node.objectApiName?void 0:i}capReport(){return this.pastTheCap.size===0?null:{cap:this.cap,notCopied:this.pastTheCap.size,objects:[...new Set(this.pastTheCap.values())]}}buildErrorReport(){return this.failedOrphans.size===0?null:{objectApiName:"__expandOrphanParents__",stage:"insert",failedCount:this.failedOrphans.size,attemptedCount:this.expansionsUsed+this.failedOrphans.size,samples:this.expansionErrors}}async expandSingleOrphanParent(e,t,n){let{sourceOrgId:o,targetOrgId:s,recordTypeMappings:i,recordTypeMapper:a}=e,{anonymize:d,withoutFileContent:c,startAsDraft:l,leftToThePlatform:u}=e;if(!hm.test(n))throw new Error(`Invalid Salesforce record ID for orphan expansion: "${n}"`);let p=Me(t),f=await this.deps.describeFields(o,p),h=c?c(p,f):f,g=Wt(h,e.fieldExclusions?.[p]);g.length===0&&g.push("Id");let m=`SELECT ${g.join(", ")} FROM ${p} WHERE Id = '${ao(n)}'`,w=await this.deps.queryRecords(o,m);if(w.length===0)return null;if(u&&u.keep(p,w).length===0)return Mf;let b=w[0],S=fn(b),R=S?await e.personAccountsInTarget?.():void 0;if(p===he&&S&&R!==!1&&e.contactOnItsOwn?.(n)!==!0)throw new Error("Not copied: a person account's contact is written by the platform with its account, never on its own");let k=null;try{k=_a(await this.deps.describeFields(s,p),p)}catch(U){nt.warn(`[forge] orphan-parent target describe failed for ${t}: ${U instanceof Error?U.message:String(U)}. Falling back to source createable.`)}let I=new Set(h.filter(U=>U.createable).map(U=>U.name)),O=k?or(I,k.creatable):I,A=new Set(e.fieldExclusions?.[p]??[]),x=e.fieldMappings?.[p]??{},j=new Set,E=new Set(await e.maskedFieldsOf?.(p).catch(()=>[])??[]),$=[],L=O.has("RecordTypeId")&&!A.has("RecordTypeId")&&x.RecordTypeId===void 0,Q=p===ye&&S&&(e.businessAccountsAmong?(await e.businessAccountsAmong([b],L)).has(b):R===!1),G=lo(b,Q),V={};for(let U of h){let se=U.name;if(A.has(se))continue;let Se=b[se];if(Se==null)continue;if(E.has(se)){(x[se]!==void 0||O.has(se))&&$.push(se);continue}if(U.isReference&&typeof Se=="string"&&se!=="RecordTypeId")continue;let ge=x[se];if(ge){V[ge]=Se,j.add(ge);continue}O.has(se)&&(eo(p,se,G)||(V[se]=Se))}if(e.contactPoints?.forObject(p,h,x)?.(V),k){let U=new Set([...O].filter(se=>!A.has(se)&&!x[se]));await this.checkPicklists(e,p,b,V,k,U,j)}let q=a&&i?a.apply([V],i,U=>es(p,U))[0]:V,me=d?d(p,q,n,h):q,de=l?await l(p,me):void 0,H=await this.insertParent(e,p,n,me),pe=H.written,ue=H.callId;if(!pe)return null;let be=pe.success?void 0:ru(pe,me,void 0),ne=pe.errors;if(be){let U=await this.insertParent(e,p,n,Zl(me,be));if(!U.written)return{refused:["No result returned for record",zi(be,ne)]};pe=U.written,ue=U.callId}if(pe.success)return $.length>0&&e.onMaskedLeftOut?.(p,$),be&&e.onWrittenWithoutFields?.(p,{rows:1,fields:be.map(U=>({...U,rows:1}))}),{id:pe.id,existing:!1,owedStatus:de,source:b,...ue!==void 0?{callId:ue}:{}};let K=this.deps.describeObject?await this.deps.describeObject(s,p).then(U=>U.keyPrefix,()=>null):null,Z=ml(pe,K);return Z.kind==="linked"?{id:Z.id,existing:!0,source:b}:{refused:be?[...pe.errors,zi(be,ne)]:pe.errors}}async insertParent(e,t,n,o){let s=e.calls?.sending(t,[{sourceId:n,payload:o}]),i;try{i=(await this.deps.insertRecords(e.targetOrgId,t,[o]))[0]}catch(a){throw s!==void 0&&$l(a)!=="may-have-written"&&e.calls?.answered(s),a}return s===void 0?{written:i}:i?.success?{written:i,callId:s}:(e.calls?.answered(s),{written:i})}async checkPicklists(e,t,n,o,s,i,a){let d=e.recordTypePicklists?await e.recordTypePicklists.forRows({objectApiName:t,rows:[n],fields:s.picklistFields,written:f=>i.has(f),recordTypeMappings:e.recordTypeMappings,withoutRecordTypes:!s.fields.some(f=>f.name==="RecordTypeId")}):void 0;for(let f of d?.notes??[])e.onRecordTypeNote?.(t,f);let c=o.RecordTypeId,l=n[ze],u=e.currencies&&i.has(ze)&&typeof l=="string"&&l!==""?await e.currencies():void 0;if(u){let f=yo(o,{read:l,currencyFields:wo(s.fields),recordTypeDefault:Jn(d?.byRecordType,c)?.picklists.get(ze)?.defaultValue,ratesOn:mo(t,n)},u);e.currencyChanges?.add(t,f);let h=n.Id;f&&typeof h=="string"&&e.currencyChangesById?.set(h,f)}let p=Co(o,s.picklistValuesByField,s.picklistFields,Jn(d?.byRecordType,c),a);e.picklistChanges?.add(t,p)}};async function*ds(r,e){let t=e!==void 0&&Number.isFinite(e)&&e>=1?Math.floor(e):0,n=0,o=[];for await(let s of r){if(t===0){if(s.length===0&&n>0)continue;n++,yield s;continue}for(o=o.length===0?[...s]:[...o,...s];o.length>=t;)n++,yield o.slice(0,t),o=o.slice(t)}(o.length>0||n===0)&&(yield o)}function _t(r,e,t,n,o,s){let{queryPages:i}=r;if(i)return ds(s?.all?i(e,t,s):i(e,t),n);if(s?.all)throw new Error("The deps read no archived row: no cursor to read through queryAll.");return ds((async function*(){yield await r.queryRecords(e,t,o)})(),n)}function Lf(r){let e=async(...n)=>{let[o,s,...i]=n,a=Si(s),d=Lc(s,a===void 0?void 0:["Id",a.stamp]);if(!d)return r.queryRecords(...n);let c=await r.queryRecords(o,d.first,...i),l=u=>r.queryRecords(o,u);return a===void 0?Dc(c,d,l):_c(c,d,l,a)},t=(n,o,s)=>Uc(o,i=>(s?.all?r.queryPages?.(n,i,s):r.queryPages?.(n,i))??Bf(),s?.all?i=>gm(r.queryPages?.(n,i,s)??Bf()):i=>r.queryRecords(n,i),Si(o));return new Proxy(r,{get(n,o,s){return o==="queryRecords"?e:o==="queryPages"?n.queryPages?t:void 0:Reflect.get(n,o,s)}})}async function gm(r){let e=[];for await(let t of r)for(let n of t)e.push(n);return e}async function*Bf(){}function ls(r,e,t={},n){if(!r)return;let o={};for(let s of e.nodes)Vu(s)&&(o[s.objectApiName]=[...s.anonymizeFields]);return{fields:o,methods:{...t},...n?{personalFieldsOf:n}:{}}}var mm=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,wm=/@example\.com$/i,za="@example.invalid",ym=64,bm=new Set(["fake","mask","preserve_format","shuffle"]);function Rm(r,e,t){return typeof r!="string"||r===""?r:mm.test(r)?e.email(r.replace(wm,za),t):`${r.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,ym).replace(/^[._]+|[._]+$/g,"")||"anonymized"}${za}`}var cs=class{smartAnonymizer;contactPoints;constructor(e,t){this.smartAnonymizer=new Al(e),this.contactPoints=new Zo(t)}categorizeField(e,t){let n=t.toLowerCase();if(n==="email")return"email";if(n==="phone")return"phone";let o=xo(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"||jl(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},n=e.records.map((a,d)=>({...a,Id:e.sourceIds[d]??""})),o=this.anonymizeRecords(n,e.fields,t,e.objectApiName),s=e.fields.filter(a=>this.categorizeField(a.name,a.type)==="email"),i=bm.has(t.phone)?e.fields.filter(a=>this.categorizeField(a.name,a.type)==="phone"):[];return o.map((a,d)=>{let c=e.records[d],l={...a};for(let u of s)l[u.name]=this.undeliverable(l[u.name],u);for(let u of i)l[u.name]=this.fictionalNumber(c[u.name],l[u.name],u);return"Id"in c?l.Id=c.Id:delete l.Id,l})}undeliverable(e,t){let n=t.length!==void 0&&t.length>0?t.length:void 0;return t.type.toLowerCase()==="email"?Rm(e,this.contactPoints,n??Yu):typeof e!="string"?e:this.contactPoints.addressesIn(e.replace(/@example\.com(?![\w.-])/gi,za),n)}fictionalNumber(e,t,n){if(typeof e!="string")return t;if(!/\d/.test(e))return e;let o=n.length!==void 0&&n.length>0?n.length:void 0;return this.contactPoints.phone(e,o)}anonymizeRecords(e,t,n,o){let s=t.map(a=>{let d=this.categorizeField(a.name,a.type);return{objectApiName:o,fieldApiName:a.name,method:n[d],piiCategory:"PII",aiConfidence:1,userOverridden:!1}}),i=e.map(a=>({...a}));return this.smartAnonymizer.anonymize(i,s,o)}};function Om(r,e){return r.created!==e.created?r.created===void 0?1:e.created===void 0?-1:e.created-r.created:Tt(e.id,r.id)}var km=1e6,xr=class extends Error{constructor(t,n){super(`Drawing the sample read ${t} records, more than the ${n} 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=n;this.name="SampleTooLarge"}rows;most},Pr=class extends Error{constructor(){super("The sample was cancelled before it was drawn. Nothing was written."),this.name="SampleCancelled"}},Sm="AccountId",Ga=class{values=[];rows=[];get size(){return this.rows.length}push(e,t){let{values:n,rows:o}=this;n.push(e),o.push(t);let s=o.length-1;for(;s>0;){let i=s-1>>1;if(n[i]<=n[s])break;[n[s],n[i]]=[n[i],n[s]],[o[s],o[i]]=[o[i],o[s]],s=i}}pop(){let{values:e,rows:t}=this,n=[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 n}},us=class{constructor(e,t,n){this.links=e;this.reader=t;this.options=n}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(le(t))}isAbsent(e,t){return this.absent.get(e)?.has(le(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 n of t)n.target==="whole"&&e.add(n.parent);for(let[t,n]of this.links.classes){if(n.kind!=="whole"||n.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 n=new Map;e.forEach((o,s)=>{let i=n.get(o.objectApiName)??[];i.push({id:o.id,index:t+s}),n.set(o.objectApiName,i)});for(let[o,s]of[...n].sort(([i],[a])=>i<a?-1:1)){let i=s.filter(({id:a})=>this.rowOf(o,a)===void 0).map(({id:a})=>a).sort(Tt);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===he&&e.field===Sm&&e.parent===ye&&this.rows[t].personAccount===!0}requiredOf(e){let t=this.objectOf[e],{refs:n,also:o}=this.rows[e],s=[],i;for(let a of this.links.linksOf.get(t)??[]){if(!this.requiredHere(a,e))continue;let d=n[a.field];tr(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:n}=this.rows[e],o=[];for(let s of this.links.linksOf.get(t)??[]){if(s.target!=="drawn"||this.requiredHere(s,e))continue;let i=n[s.field];tr(i,s)&&o.push({objectApiName:s.parent,id:i})}return o}upTargets(e){let t=this.objectOf[e],{refs:n,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=n[i.field];if(!tr(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:n}=this.requiredOf(e);n&&this.kill(e,n);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 n of t)if(!(this.descended[n]||!this.alive(n))){this.descended[n]=!0;for(let o of this.links.carriersInto.get(this.objectOf[n])??[]){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(le(this.rows[n].id),n)}}if(e.size===0)return!1;for(let[n,o]of[...e].sort(([s],[i])=>s<i?-1:1)){let s=n.indexOf("."),i={objectApiName:n.slice(0,s),field:n.slice(s+1),parents:[...o.objects].sort(),masterDetail:o.masterDetail},a=i.masterDetail?"all":this.options.children,d=[...o.parents.values()].map(f=>this.rows[f].id).sort(Tt);this.checkSignal();let c=await this.reader.children(i,d,a),l=new Map;for(let f of c.rows){let h=f.refs[i.field];if(typeof h!="string"||h==="")continue;let g=o.parents.get(le(h));if(g===void 0)continue;let m=l.get(g)??new Map;m.has(le(f.id))||m.set(le(f.id),f),l.set(g,m)}let u=new Map;for(let[f,h]of c.counts??[])u.set(le(f),h);let p=this.cuts.get(n)??new Map;for(let[f,h]of[...l].sort(([g],[m])=>g-m)){let g=[...h.values()].sort(Om),m=a==="all"?g:g.slice(0,a),w=this.below.get(f)??[];for(let S of m){let R=this.register(i.objectApiName,S);w.push({child:R,relation:n}),this.descended[R]||this.toDescend.push(R)}this.below.set(f,w);let b=u.get(le(this.rows[f].id))??h.size;b>m.length&&p.set(f,b-m.length)}p.size>0&&this.cuts.set(n,p),this.told()}return!0}need(e,t){let n=this.rowOf(t.objectApiName,t.id);if(n!==void 0){this.tie(n,e);return}if(this.isAbsent(t.objectApiName,t.id)){this.kill(e,"noParentInSource");return}let o=`${t.objectApiName}
|
|
8
|
-
${le(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(le(e.id),e.id),this.pending.set(e.objectApiName,t)}async readPending(){let e=[...this.pending].sort(([t],[n])=>t<n?-1:1);this.pending.clear();for(let[t,n]of e){let o=[...n.values()].sort(Tt);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 n of t){if(this.rowOf(e,n)!==void 0)continue;let o=this.absent.get(e)??new Set;o.add(le(n)),this.absent.set(e,o);let s=`${e}
|
|
9
|
-
${le(n)}`;for(let i of this.waiting.get(s)??[])this.kill(i,"noParentInSource");this.waiting.delete(s)}}register(e,t){let n=this.index.get(e);n||(n=new Map,this.index.set(e,n));let o=le(t.id),s=n.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),n.set(o,i);let a=this.options.maxRows??km;if(this.rows.length>a)throw new xr(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}
|
|
10
|
-
${o}`);if(d){this.waiting.delete(`${e}
|
|
11
|
-
${o}`);for(let c of d)this.tie(i,c)}return i}tie(e,t){let n=this.needs.get(e)??[];n.push(t),this.needs.set(e,n),this.alive(e)||this.kill(t,this.out[e]?"outsideFilter":"withoutParent")}kill(e,t){if(!this.alive(e))return;this.dead[e]=t;let n=[e];for(;n.length>0;){let o=n.pop(),s=this.out[o]?"outsideFilter":"withoutParent";for(let i of this.needs.get(o)??[])this.alive(i)&&(this.dead[i]=s,n.push(i))}}checkSignal(){if(this.options.signal?.aborted)throw new Pr}told(){this.options.onRows?.(this.rows.length)}thresholds(e=new Set){let t=this.rows.length,n=new Float64Array(t).fill(1/0),o=new Array(t),s=new Array(t),i=new Ga;for(let c=0;c<t;c++){let l=this.rootOf[c];l>=0&&!e.has(l)&&(n[c]=l,i.push(l,c))}let a=new Uint8Array(t);for(;i.size>0;){let[c,l]=i.pop();if(!(a[l]||c>n[l]||!this.alive(l))){a[l]=1;for(let{child:u,relation:p}of this.below.get(l)??[])c<n[u]?(n[u]=c,s[u]=p,i.push(c,u)):c===n[u]&&p<(s[u]??"")&&(s[u]=p)}}let d=new Float64Array(n);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,l]=i.pop();if(!(a[l]||c>d[l]||!this.alive(l))){a[l]=1;for(let{row:u,field:p}of this.upTargets(l)){let f=`${this.objectOf[l]}.${p}`;c<d[u]?(d[u]=c,o[u]=f,i.push(c,u)):c===d[u]&&o[u]!==void 0&&f<o[u]&&(o[u]=f)}}}return{threshold:d,above:n,via:o}}};var _f={bytes:(r,e)=>e.bytes??ku(r,e.personAccount?{IsPersonAccount:!0}:{}),wholeBytes:(r,e)=>Ho(r,{rows:e})},Tm=[{objectApiName:he,field:"AccountId",writes:"AccountContactRelation",ownField:"ContactId",pairField:"AccountId"},{objectApiName:"Opportunity",field:"ContactId",writes:"OpportunityContactRole",ownField:"OpportunityId",pairField:"ContactId"}],Am=.1,jm=256,vm=5;function qa(r,e){return e<0?-1/0:e===1/0?1/0:r[e].rank}function Uf(r,e){let t=r.rows[e];return t.matched||r.objectOf[e]===he&&t.personAccount===!0?0:1}function Im(r,e,t){let n=new Map,{links:o}=r,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 n;for(let i=0;i<r.rows.length;i++)if(r.alive(i))for(let a of s){if(r.objectOf[i]!==a.objectApiName)continue;let d=r.rows[i];if(a.objectApiName===he&&d.personAccount)continue;let c=d.refs[a.field],l=Gp(o,a.objectApiName,a.field,c);if(!l||typeof c!="string")continue;let u=r.rowOf(l.parent,c);if(u===void 0||!r.alive(u))continue;let p=Math.max(e.threshold[i],e.threshold[u]);p!==1/0&&n.set(`${a.writes}
|
|
12
|
-
${le(d.id)}
|
|
13
|
-
${le(c)}`,{objectApiName:a.writes,threshold:p,rows:[]})}for(let i=0;i<r.rows.length;i++)if(r.alive(i))for(let a of s){if(r.objectOf[i]!==a.writes)continue;let{refs:d}=r.rows[i],c=d[a.ownField],l=d[a.pairField];if(typeof c!="string"||typeof l!="string")continue;let u=n.get(`${a.writes}
|
|
14
|
-
${le(c)}
|
|
15
|
-
${le(l)}`);u&&u.rows.push(i)}for(let i of n.values())i.rows.sort((a,d)=>e.threshold[a]-e.threshold[d]||Tt(r.rows[a].id,r.rows[d].id));return n}function Em(r,e,t){let{measure:n,draw:o}=t,s=[],i=new Float64Array(r.rows.length),a=new Map,d=(u,p)=>{u>=0&&u!==1/0&&a.set(u,(a.get(u)??0)+p)},c=Im(r,e,t.platformPairs??Tm),l=new Set;for(let u of c.values())u.rows.length>0&&l.add(u.rows[0]);for(let u=0;u<r.rows.length;u++){if(!r.alive(u))continue;let p=r.objectOf[u],f=r.rows[u],h=l.has(u)?0:Uf(r,u),m=(f.matched||l.has(u)?0:n.bytes(p,f))+h*(n.roomBytes?.(p)??0);i[u]=m;let w=e.threshold[u];w!==1/0&&(s.push({rank:qa(o.roots,w),bytes:m,records:h,objectApiName:p}),d(w,m))}for(let u of c.values()){let p=n.bytes(u.objectApiName,{id:"",refs:{}});s.push({rank:qa(o.roots,u.threshold),bytes:p,records:0,objectApiName:u.objectApiName}),d(u.threshold,p)}for(let[u,p]of r.links.classes){if(p.kind!=="whole"||r.wasReadWhole(u))continue;let f=t.sourceRows.get(u)??0,h=p.why==="referenceData",g=h?0:f;s.push({rank:-1/0,bytes:(h?0:n.wholeBytes(u,f))+g*(n.roomBytes?.(u)??0),records:g,objectApiName:u})}return s.sort((u,p)=>u.rank-p.rank),{items:s,rowBytes:i,parts:a,pairs:c}}function zf(r,e,t){let n=0,o=0,s=new Map;for(let i of r){if(i.rank>e)break;n+=i.bytes,o+=i.records,t&&i.records>0&&s.set(i.objectApiName,(s.get(i.objectApiName)??0)+i.records)}return{bytes:n,records:o,written:s}}function ps(r,e,t){let n=zf(r,e,t.requests!==void 0);return n.bytes>t.bytes?zu(n.bytes,t):t.maxTotal!==void 0&&n.records>t.maxTotal?"maxTotal":t.requests?.(n.written)}function Wf(r,e,t){let n=Am*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=Gf(r);for(s!==void 0&&o.add(s);;){let i=r.thresholds(t),a=Em(r,i,e),d=[...a.parts].filter(([c,l])=>l>n&&!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 Gf(r){let e;for(let t=0;t<r.rows.length;t++){let n=r.rootOf[t];n>=0&&r.alive(t)&&(e===void 0||n<e)&&(e=n)}return e}function Df(r,e,t,n){let o=zf(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:ps(e,t,n)??n.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,vm).map(([i,a])=>({objectApiName:i,...a,...r.links.classes.get(i)?.kind==="whole"?{whole:!0}:{}}))}}async function qf(r){let e=r.draw.roots.filter(c=>c.rank<r.draw.beyond),t={...r,draw:{...r.draw,roots:e}},{bounds:n}=t,o=new us(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=jm,d=Wf(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=Wf(o,t,s),ps(d.weighed.items,e[i-1].rank,n)!==void 0)break}return t.onStep?.("fitting",o.rows.length),$m(o,d,s,t,e.slice(0,i),i===e.length)}function $m(r,e,t,n,o,s){let{bounds:i,draw:a}=n,{items:d}=e.weighed,c=[...new Set(o.map(m=>m.rank))].sort((m,w)=>m-w),l=a.floor>0&&c[0]===0?c:[-1/0,...c],u=Gu(l.length,m=>ps(d,l[m-1],i)===void 0);if(u===0)return Df(r,d,l[0],i);let p=l[u-1],f=Gf(r);if(f!==void 0&&o[f].rank>p)return{...Df(r,d,o[f].rank,i),noRoot:!0};let h=Pm(r,e,t,n,p),g=u<l.length?ps(d,l[u],i)??i.bytesLimit:!s||a.beyond!==1/0?a.heldBy:h.heavyRoots.length>0?"heavyRoots":"whole";return{kind:"sample",share:g==="whole"||g==="heavyRoots"?1:Math.max(0,p),limitedBy:g,wholeOrgFits:xm(r,n),...h}}function xm(r,e){let t=0,n=0,o=new Map;for(let[i,a]of r.links.classes){let d=e.sourceRows.get(i)??0;a.kind==="whole"&&a.why==="referenceData"||(t+=e.measure.wholeBytes(i,d),n+=d,o.set(i,d))}let{bounds:s}=e;return t<=s.bytes&&(s.maxTotal===void 0||n<=s.maxTotal)&&s.requests?.(o)===void 0}function Pm(r,e,t,n,o){let{links:s}=r,{thresholds:i,weighed:a}=e,d=n.draw.roots,c=j=>qa(d,j),l=j=>r.alive(j)&&c(i.threshold[j])<=o,u=j=>{if(r.whole[j])return"whole";let E=r.rootOf[j];return E>=0&&!t.has(E)&&c(E)<=o?"root":c(i.above[j])<=o?"below":"parent"},p=new Map,f=j=>{let E=p.get(j);return E||(E={objectApiName:j,sourceRows:n.sourceRows.get(j)??0,kept:0,roots:0,below:0,asParents:0},s.classes.get(j)?.kind==="whole"&&(E.whole=!0),p.set(j,E)),E},h=new Map,g=new Map,m=new Map,w=new Map,b=new Set;for(let j of a.pairs.values())j.rows.length>0&&b.add(j.rows[0]);let S=0,R=0,k=0,I=j=>n.measure.roomBytes?.(j)??0;for(let j=0;j<r.rows.length;j++){let E=r.objectOf[j];if(!r.alive(j)){let G=r.dead[j];if(r.out[j]||G===void 0||c(i.threshold[j])>o)continue;let V=`${E}
|
|
16
|
-
${G}`,q=m.get(V)??{objectApiName:E,rows:0,reason:G};q.rows++,m.set(V,q);continue}if(!l(j))continue;let $=r.rows[j],L=h.get(E)??[];L.push($.id),h.set(E,L),R+=a.rowBytes[j];let Q=b.has(j)?0:Uf(r,j);if(S+=Q,k+=Q*I(E),$.personAccount&&(E===ye||E===he)&&g.set(E,(g.get(E)??0)+1),!$.matched){let G=f(E);G.kept++;let V=u(j);V==="root"?G.roots++:V==="below"?G.below++:V==="parent"&&G.asParents++}for(let G of s.linksOf.get(E)??[]){if(G.target==="excluded"||G.target==="whole"&&!r.wasReadWhole(G.parent))continue;let V=$.refs[G.field];if(!tr(V,G))continue;let q=r.rowOf(G.parent,V);if(q!==void 0&&l(q))continue;let me=`${E}
|
|
17
|
-
${G.field}`,de=w.get(me)??{objectApiName:E,field:G.field,rows:0};de.rows++,w.set(me,de)}}for(let[j,E]of s.classes){if(E.kind!=="whole"||r.wasReadWhole(j))continue;let $=n.sourceRows.get(j)??0,L=f(j);L.kept=$,E.why!=="referenceData"&&(S+=$,R+=n.measure.wholeBytes(j,$)+$*I(j),k+=$*I(j))}let O=new Map;for(let j of a.pairs.values()){if(c(j.threshold)>o)continue;let E=O.get(j.objectApiName)??{objectApiName:j.objectApiName,inPlan:0,beyond:0};j.rows.length>0&&l(j.rows[0])?E.inPlan++:E.beyond++,R+=n.measure.bytes(j.objectApiName,{id:"",refs:{}}),O.set(j.objectApiName,E)}for(let[j,E]of r.cut){let $=0;for(let[G,V]of E)l(G)&&c(i.above[G])<=o&&($+=V);if($===0)continue;let L=j.indexOf("."),Q=f(j.slice(0,L));Q.childrenCut=[...Q.childrenCut??[],{field:j.slice(L+1),rows:$}]}let A=[...p.values()].filter(j=>j.kept>0).sort((j,E)=>E.kept-j.kept||(j.objectApiName<E.objectApiName?-1:1)),x=[...s.classes].filter(([j,E])=>{let $=n.sourceRows.get(j)??0;return E.kind==="drawn"&&$>0&&(p.get(j)?.kept??0)===0}).map(([j])=>({objectApiName:j,sourceRows:n.sourceRows.get(j)??0})).sort((j,E)=>j.objectApiName<E.objectApiName?-1:1);return{rows:A.reduce((j,E)=>j+E.kept,0),storageBytes:R,automationBytes:k,written:S,objects:A,heavyRoots:Fm(r,e,t,d,o),dropped:[...m.values()].sort(Ha(j=>j.reason)),leftEmpty:[...w.values()].sort(Ha(j=>j.field)),noRecordDrawn:x,partialMasters:Cm(s,p,n.sourceRows),ids:new Map([...h].map(([j,E])=>[j,E.sort(Tt)])),personAccounts:g,byThePlatform:[...O.values()].sort((j,E)=>j.objectApiName<E.objectApiName?-1:1)}}function Cm(r,e,t){let n=[];for(let[o,s]of r.linksOf){if(r.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 l=t.get(o)??0;i<l&&n.push({...c,kept:i,sourceRows:l})}else a.carries&&d.asParents>0&&n.push({...c,asParents:d.asParents})}}return n.sort(Ha(o=>`${o.details}
|
|
18
|
-
${o.field}`))}function Ha(r){return(e,t)=>{if(e.objectApiName!==t.objectApiName)return e.objectApiName<t.objectApiName?-1:1;let n=r(e),o=r(t);return n<o?-1:n>o?1:0}}function Fm(r,e,t,n,o){let s=[...t].filter(a=>n[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=r.thresholds(d),l=0,u=new Map;for(let h=0;h<r.rows.length;h++){if(!r.alive(h)||c.threshold[h]!==a)continue;l++;let g=c.via[h];g!==void 0&&u.set(g,(u.get(g)??0)+e.weighed.rowBytes[h])}let[p]=[...u].sort(([h,g],[m,w])=>w-g||(h<m?-1:h>m?1:0))[0]??[`${n[a].objectApiName}.Id`],f=p.indexOf(".");i.push({objectApiName:n[a].objectApiName,id:n[a].id,rows:l,relation:{objectApiName:p.slice(0,f),field:p.slice(f+1)}})}return i}var Rn=class extends Error{constructor(t,n,o){super(n);this.code=t;this.heaviest=o;this.name="SampleRefusedError"}code;heaviest},Ka=[Ot,kt,ut,Bt,"IsActive"];function Hf(r){return r===!0||r==="true"}function fs(r){return typeof r=="string"&&r!==""?r:null}function Nm(r){let e=r.CreatedDate,t=typeof e=="string"?Date.parse(e):Number.NaN;return Number.isFinite(t)?t:void 0}function Kf(r){let e=t=>{let n=r[t];return typeof n=="string"?le(n):""};return[e(Ot),e(kt),e(Bt)].join(`
|
|
19
|
-
`)}function Vf(r){let e=t=>{let n=r[t];return typeof n=="string"?n:""};return[le(e(kt)),e(ut),le(e(Bt))].join(`
|
|
20
|
-
`)}var Va=class{constructor(e,t,n,o){this.reader=e;this.links=t;this.sourceRows=n;this.priceCurrencyWrittenIn=o}reader;links;sourceRows;priceCurrencyWrittenIn;cappedByIds=new Set;columnsOf(e){let t=[...va(this.links,e),"RecordTypeId"];return(e===ye||e===he)&&t.push("IsPersonAccount"),e===We&&t.push(...Ka),e===Rt&&t.push("IsStandard"),t}rowOf(e,t,n=!1){let o={};for(let a of va(this.links,e))o[a]=fs(t[a]);let s=t.RecordTypeId,i=Nm(t);return{id:String(t.Id),refs:o,...typeof s=="string"||s===null?{recordTypeId:fs(s)}:{},...(e===ye||e===he)&&Hf(t.IsPersonAccount)?{personAccount:!0}:{},...e===Rt&&Hf(t.IsStandard)?{matched:!0}:{},...n?{outsideFilter:!0}:{},...i!==void 0?{created:i}:{}}}async sampleRowsOf(e,t,n=[]){let o=[...t.map(l=>this.rowOf(e,l)),...n.map(l=>this.rowOf(e,l,!0))];if(e!==We||t.length===0)return o;let s=[...new Set(t.flatMap(l=>{let u=fs(l[kt]);return u?[u]:[]}))],i=await this.reader.readStandardPrices(s,Ka.slice(1)),a=new Set(i.map(l=>le(String(l.Id)))),d=new Map;for(let l of i)d.set(Vf(l),String(l.Id));let c=await this.pricesWrittenFor(t);return o.map((l,u)=>{let p=t[u];if(p===void 0)return l;let f=[];a.has(le(l.id))||f.push({objectApiName:We,id:d.get(Vf(p))??null});let h=c.get(l.id);return h!==void 0&&f.push({objectApiName:We,id:h}),f.length>0?{...l,also:f}:l})}async pricesWrittenFor(e){let t=new Map,n=this.priceCurrencyWrittenIn;if(!n)return t;let o=new Map;for(let s of e){let i=s[ut];if(typeof i!="string")continue;let a=n(i);a===void 0||a===i||o.set(a,[...o.get(a)??[],s])}for(let[s,i]of o){let a=l=>i.flatMap(u=>{let p=fs(u[l]);return p?[p]:[]}),d=await this.reader.readPricesIn(s,a(kt),a(Ot),Ka),c=new Map(d.map(l=>[Kf(l),String(l.Id)]));for(let l of i){let u=c.get(Kf(l));u!==void 0&&t.set(String(l.Id),u)}}return t}async rows(e,t){let[n]=await this.reader.readParents([{objectApiName:e,ids:t,columns:this.columnsOf(e)}]);return n?this.sampleRowsOf(e,n.rows,n.outsideFilter):[]}async children(e,t,n){let[o]=await this.reader.readChildren([{objectApiName:e.objectApiName,field:e.field,parentIds:t,columns:this.columnsOf(e.objectApiName),cap:n,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)}],(n,o)=>{for(let s of o)t.push(s)}),this.sampleRowsOf(e,t)}};function Mm(r,e){let{empty:t,told:n}=zp(r,e),o=r.linksOf.get(e)??[];return[...t.map(s=>({field:s})),...n.map(s=>({field:s,drawnPrefixes:new Set(o.flatMap(i=>i.field===s&&i.carries&&typeof i.prefix=="string"?[i.prefix]:[]))}))]}async function Jf(r){let{options:e,budget:t}=r,n=O=>r.averageBytes?.get(O),o=(O,A)=>{let x=n(O);return x!==void 0?A*x:Ho(O,{rows:A})},s=new Map(r.objects.flatMap(O=>O.rows===void 0?[]:[[O.objectApiName,O.rows]])),i=Up({objects:r.objects,order:r.order,...r.excluded?{excluded:r.excluded}:{},...r.referenceData?{referenceData:r.referenceData}:{},...e.whole?{whole:e.whole}:{},roomBytes:t.roomBytes,...r.maxRecordsPerObject!==void 0?{maxRecordsPerObject:r.maxRecordsPerObject}:{},wholeBytes:(O,A)=>o(O,A)}),a=(O,A)=>r.fieldsOf(O)?.find(x=>x.name.toLowerCase()===A.toLowerCase()),d=new qp(r.source,{fieldsOf:O=>r.fieldsOf(O)?.map(A=>A.name),...r.filterOf?{filterOf:r.filterOf}:{},countsBy:(O,A)=>{let x=a(O,"Id")?.aggregatable,j=a(O,A)?.groupable;return x===!1||j===!1?!1:x===!0&&j===!0?!0:void 0},sorts:(O,A)=>a(O,A)?.sortable,...r.onProgress?{onProgress:r.onProgress}:{},...r.signal?{signal:r.signal}:{}}),l=[...i.classes].filter(([,O])=>O.kind==="drawn"&&O.rooted).map(([O])=>O).sort().map(O=>({objectApiName:O,carriers:Mm(i,O)})),u=await d.countRoots(l),p=Cp(t.budget.bytes,t.budget.maxTotal),f=u.map(O=>Math.min(O.rows,p)),h=u.reduce((O,A,x)=>O+Hp(A,e.draw,f[x],d.readsNewestApart(A.objectApiName)),0),g=r.sourceRequestsLeft;if(g!==void 0&&d.requests+h>Math.floor(Yi*g)){let O=d.requests+h;throw new St(Vo,`Drawing the sample reads about ${O} requests of the source, more than a tenth of the ${g} it has left today. Nothing was written, and no id was read past the counts. `+(e.draw==="uniform"?"Draw the most recent records (--fit-draw recent), or narrow the large objects (--filter).":"Narrow the large objects (--filter), or draw it once the source has more to spare."),void 0,void 0,void 0,{api:{kind:"requests",org:"source",estimate:O,remaining:g,drawing:{share:Yi,draw:e.draw}}})}let m=new Fp(p,e.floor),w=[];if(e.draw==="uniform")await d.drawUniform(l,(O,A)=>{for(let x of A)m.offer(O,x,xp(e.seed,x))});else{let O=new Map(u.map(j=>[j.objectApiName,j.rows])),A=new Map;w=(await d.drawRecent(l.map((j,E)=>({...j,take:f[E]})),(j,E)=>{let $=A.get(j)??0;for(let L of E)m.offer(j,L,Aa($,O.get(j)??0)),$++;A.set(j,$)})).filter(j=>j.by==="id").map(j=>j.objectApiName),u.forEach((j,E)=>{let $=f[E];$<j.rows&&(A.get(j.objectApiName)??0)>=$&&m.leftUnread(Aa($,j.rows))})}let{maxTotal:b}=t.budget,S=b!==void 0&&b<Math.floor(t.budget.bytes/Pp)?"maxTotal":t.bytesLimit,R=new Va(d,i,s,r.priceCurrencyWrittenIn),k=await qf({links:i,reader:R,draw:{roots:m.drawn(),beyond:m.beyond,heldBy:S,floor:e.floor},sourceRows:s,options:{parents:e.parents,children:e.children,...r.recordTypeVerdict?{recordTypeVerdict:r.recordTypeVerdict}:{},...r.maxRows!==void 0?{maxRows:r.maxRows}:{},...r.signal?{signal:r.signal}:{}},measure:{bytes:(O,A)=>A.bytes??n(O)??_f.bytes(O,A),wholeBytes:o,...t.automationBytes?{roomBytes:t.automationBytes}:{}},bounds:{bytes:t.budget.bytes,bytesLimit:t.bytesLimit,...t.storageBytes!==void 0?{storageBytes:t.storageBytes}:{},...b!==void 0?{maxTotal:b}:{},...t.requests?{requests:t.requests}:{}},roomBytes:t.roomBytes,onStep:(O,A)=>r.onProgress?.({step:O,rows:A,requests:d.requests})}),I=[...new Set([...w,...R.cappedByIds])].sort();return{links:i,cut:k,planRequests:d.requests,newestByIds:I}}function Yf(r,e,t){let{cut:n,links:o}=r;return{seed:e.seed,draw:e.draw,floor:e.floor,parents:e.parents,children:e.children,share:n.share,budget:{...t,...n.automationBytes>0?{automationMB:n.automationBytes/1048576}:{},limitedBy:n.limitedBy},rows:n.rows,storageBytes:n.storageBytes,objects:n.objects,whole:o.whole,heavyRoots:n.heavyRoots,dropped:n.dropped,leftEmpty:n.leftEmpty,noRecordDrawn:n.noRecordDrawn,...n.partialMasters.length>0?{partialMasters:n.partialMasters}:{},planRequests:{source:r.planRequests},...r.newestByIds.length>0?{newestByIds:[...r.newestByIds]}:{}}}var Oe=class extends Error{constructor(e){super(e),this.name="ForgeAbortedError"}},hd=vr,Lm={OpportunityLineItem:{object:"OpportunityLineItemSchedule",lookup:"OpportunityLineItemId"}},Pt=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Xf=2e3;function Wm(){return{pages:0,rows:0,sent:0,succeeded:0,updated:0,linked:0,linkedToCreated:0,failed:0,alreadyExists:0,unidentified:0,writtenBefore:0,withTheirAccount:0,withTheirEmail:0,teamOwners:0,teamOthers:0,teamValues:{notKept:new Map,unread:new Map},rolesOfTheirOpportunity:0,rolesGiven:0,personContactsUnlinked:0,sentOnTheirOwn:0,onTheirOwnWhy:"",withoutParent:0,withoutParentGroups:new Map,rowsLeft:()=>0,held:new Map,heldWholeRows:0,picklists:new Fo,currencies:new Ro,lookupsNotCarried:new Map,lookupsOutsideTheRun:new Map,ownersInactive:0}}function Zf(r){return r.succeeded+r.updated+r.linked+r.writtenBefore+r.withTheirAccount+r.withTheirEmail+r.teamOwners+r.teamOthers+r.rolesOfTheirOpportunity}function eh(r){return[wi(r.flagsNotKept),Gh(r.teamValues)].flatMap(e=>e?[`, ${e}`]:[]).join("")}function Ja(r,e){for(let{count:t,why:n}of e)r.held.set(n,(r.held.get(n)??0)+t)}function Ya(r){return[...r.held].map(([e,t])=>({count:t,why:e}))}var Dm=5e3,_m=2e3,th="afterTask",Qa=3,nh=1e3,Ln=2e3;function Cr(r,e,t){return{objectApiName:r,recordCount:0,fieldCount:e.length,status:"idle",progress:0,included:!0,piiFields:[],anonymizeFields:[],level:t,successCount:0,failureCount:0,errors:[],createableFieldCount:e.filter(n=>n.createable).length,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}}function Um(r){return r.some(e=>e.isReference&&(e.referenceTo??[]).includes(We))}function Dh(r,e){let t=[];for(let n of e){let o=n.referenceTo??[];if(!n.isReference||o.length!==1||!Ze(r,n.name,n.nillable))continue;let[s]=o;s!==r&&!Je.has(s)&&t.push(s)}return t}function zm(r,e,t){return Dh(r,e).find(n=>t.has(n))}function Gm(r,e,t){let n=t.scopeCache;if(!n)return[];let o=new Set(t.graph.edges.filter(i=>i.targetObject===r).map(i=>i.sourceObject)),s=new Set;for(let i of e)if(i.isReference)for(let a of i.referenceTo??[])a!==r&&o.has(a)&&t.readObjects.has(a)&&!Je.has(a)&&!t.config.referenceDataObjects.has(a)&&!n.isRead(a)&&s.add(a);return[...s]}var qm=3,Hm=10,Km=5;function Vm(r,e){let t=e.rows.filter(({objectApiName:s,row:i})=>{let a=i.Id;return typeof a!="string"||!r.heldForExclusions.get(s)?.has(a)});if(t.length===e.rows.length)return e;let n=new Set,o=new Set;for(let{objectApiName:s,row:i,field:a}of t)n.add(String(i[a])),o.add(s);return{ids:n,neededBy:o,rows:t}}function rh(r,e){let t=r.readAsParents.get(e);return!t||t.count===0?"":`, ${t.count} read by id for the ${[...t.neededBy].sort().join(", ")} records that cannot be written without ${t.count===1?"it":"them"}`}function oh(r,e){let t=r.get(e)??new Set;if(!r.isRead(e))return new Set(t);let n=r.scopeOf(e);return new Set([...t].filter(o=>!n?.has(o)))}function Fr(r,e){for(let t of e){let n=t.Id;typeof n=="string"&&n!==""&&r.idsRead.add(n)}}function sh(r,e){let t=e!==void 0&&e>0?Math.floor(e):0;return t>0?Math.min(r.recordCount,t):r.recordCount}function ys(r){let e=r.maxRecordsPerObject;return e!==void 0&&e>0&&Math.floor(e)>0?Math.floor(e):void 0}var Jm={storage:{past:"past the data storage the target has left",more:", or free data storage in the target"},within:{past:"past the MB it may take (--fit-within)",more:", or let it take more (--fit-within)"},maxTotal:{past:"past the records it may write (--max-total)",more:", or raise --max-total"},targetRequests:{past:"past the API requests the target has left today",more:", or run it once the target has more to spare"},bulkBatches:{past:"past the Bulk API batches the target has left today",more:", or run it once the target has more to spare"},sourceRequests:{past:"past the API requests the source has left today",more:", or run it once the source has more to spare"},heavyRoots:{past:"past what the sample may take",more:""},whole:{past:"past what the sample may take",more:""}};function ih(r,e){let t=r/1048576*100;return(e==="up"?Math.ceil(t):Math.floor(t))/100}var cd=class extends Rn{constructor(t,n,o){super("SAMPLE_CANNOT_FIT",t,n);this.sample=o}sample},ah=3;function Ym(r,e){let t=e.slice(0,ah).map(({sourceId:i,matchValue:a})=>({recordSummary:`Id=${i} matchValue=${a??"null"}`,messages:[a===null?`This ${r} has no name to find it by in the target org: the records that point at it are not linked to one.`:`No ${r} of the target org is named "${a}": the records that point at it are not linked to one. Create a ${r} of that name in the target\u2019s Setup, or rename one of the target\u2019s to it, then run again.`]})),n=e.slice(ah);if(n.length===0)return t;let o=n.map(({matchValue:i})=>i===null?"no name":`"${i}"`),s=o.length===1?o[0]:`${o.slice(0,-1).join(", ")} or ${o.at(-1)}`;return[...t,{recordSummary:`${n.length} more`,messages:[`No ${r} of the target org is named ${s} either.`]}]}function Qm(r){let e=r.orphanExpander.capReport();return e?{orphanParentsCapped:e}:{}}function dh(r){let e=ys(r.config);return e!==void 0&&r.cappedObjects.size>0?{cappedObjects:{perObject:e,objects:[...r.cappedObjects]}}:{}}function Xm(r){return r.errors.length===0?"excluded":`excluded: ${r.errors.join("; ").replace(/\s+/g," ").trim()}`}function Zm(r,e,t){let n=t.filter(d=>d.isReference),o=d=>n.filter(c=>(c.referenceTo??[]).includes(d)),s=d=>{let c=o(d);return c.length>0&&c.every(l=>(l.referenceTo??[]).length>1)},i=d=>{let c=o(d);return c.length>0&&c.every(l=>l.nillable===!0)},a=new Set(Wo(e,new Map([[r,t]])).edges.filter(d=>d.targetObject===r&&(d.required===!0||d.type==="master-detail"&&!i(d.sourceObject))&&Jl(d)&&!s(d.sourceObject)).map(d=>d.sourceObject));for(let d of n){let c=d.referenceTo??[];c.length!==1||!pr(d)||!Ze(r,d.name,d.nillable)||a.add(c[0])}return a.delete(r),[...a]}function ew(r,e){return ld(Br(r.values()),e)}function Br(r,e=new Map){for(let{field:t,parentObject:n,notInTarget:o,reason:s,recordType:i}of r){let a=`${t}|${n}|${o===!0?"outside":""}|${s??""}`,d=e.get(a)??{field:t,parentObject:n,...o?{notInTarget:o}:{},...s!==void 0?{reason:s}:{},...i?{recordType:i}:{},count:0};d.count++,e.set(a,d)}return e}function ld(r,e){return[...r.values()].sort((t,n)=>n.count-t.count).slice(0,3).map(({field:t,parentObject:n,notInTarget:o,reason:s,recordType:i,count:a})=>({recordSummary:i?`RecordType=${i.developerName} (${a} record${a===1?"":"s"})`:`${t} \u2192 ${n} (${a} record${a===1?"":"s"})`,messages:i?[vo({...i,recordCount:a})]:[s!==void 0?`Not written: ${s}`:o?`Not written: ${t} may not be left empty, and the target holds no ${n} record of the id it names, outside the run.`:`Not written: ${t} may not be left empty, and the ${n} it points at `+(e.has(n)?"failed in this run.":"was not written by this run.")]}))}var tw=3,ch=5e4;function nw(r,e){return!e||e.size===0?0:r.reduce((t,{node:n,read:o})=>t+(o>0?(e.get(n.objectApiName)??0)*Math.ceil(o/Ln):0),0)}var lh={field:"",parentObject:"",reason:"the source does not hold it"};function Xa(r,e){return`${r} may not be left empty, and names a ${e} record the source does not hold`}function rw(r,e){return`${r} may not be left empty, and names a ${e} record outside the sample: changed since the sample`}function ow(r,e){return`${r} may not be left empty, and names a ${e} record gone from the source since the sample`}function uh(r,e){return`${r} may not be left empty, and names a ${e} record left aside`}function sw(r,e,t,n=()=>!0){return t.flatMap(o=>{let s=o.referenceTo??[],[i]=s;return o.isReference&&s.length===1&&i!==e&&n(o.name)&&r.writtenObjects.has(i)&&!r.config.referenceDataObjects.has(i)&&r.turnsEnded.has(i)&&Ze(e,o.name,o.nillable)?[{field:o.name,parent:i}]:[]})}var iw="held back for a record type closed to the user the run writes as",aw="held back for a record type the target has none of";function ph(r){let e=0,t=0,n=0;for(let o of r)o.recordType?.unmapped?t++:o.recordType?e++:n++;return[...e>0?[{count:e,why:iw}]:[],...t>0?[{count:t,why:aw}]:[],...n>0?[{count:n,why:ud}]:[]]}function fh(r,e){return e<=0?{}:r.every(t=>t.unmapped)?{recordTypeNotInTarget:e}:{heldBack:e}}function hh(r,e){return Ai(r.unmapped?"record_type_unmapped":"record_type_unavailable",r.objectApiName,r.developerName,r.recordCount,qh(e))}function dw(r,e,t){let n=r.leftAside.get(e)??new Map;Br(t,n),r.leftAside.set(e,n)}function cw(r,e){return[...r.leftAside.get(e)?.values()??[]].map(({count:t,reason:n})=>`, ${t} left aside: ${n??""}`).join("")}function lw(r){return[...r.leftAside].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t.values()].sort((n,o)=>o.count-n.count).slice(0,3).map(({field:n,parentObject:o,reason:s,count:i})=>({recordSummary:`${n} \u2192 ${o} (${i} record${i===1?"":"s"})`,messages:[`Left aside, not written: ${s??""}`]}))}))}function bs(r,e){return r.leftToThePlatform.counts(e).map(({why:t,count:n})=>`, ${Sc(n,t)}`).join("")+cw(r,e)}function uw(r){return[...pw(r),...lw(r)]}function pw(r){let e=new Map;for(let{objectApiName:t,why:n,count:o}of r.leftToThePlatform.counts())e.set(t,[...e.get(t)??[],{recordSummary:Tc(o,n),messages:[Ac(n)]}]);return[...e].map(([t,n])=>({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:n}))}function Lr(r){return r==="not-creatable"?", which the target org takes no insert of":r==="not-in-target"?", which the target org does not have":", excluded from this run"}function fw(r){let e=new Map([[void 0,new Set],["not-creatable",new Set],["not-in-target",new Set]]);for(let{excluded:t,target:n}of r)e.get(n)?.add(t);return[...e].filter(([,t])=>t.size>0).map(([t,n])=>`${[...n].sort().join(", ")}${Lr(t)}`).join("; ")}function hw({field:r,excluded:e,through:t,namedBy:n,target:o}){return n!==void 0?`Not written: the only records that name it are ${n} records held back for ${e}${Lr(o)}.`:t!==void 0?`Not written: ${r} may not be left empty, and the ${t} it names is held back for ${e}${Lr(o)}.`:o==="not-creatable"?`Not written: ${r} may not be left empty, and the target org takes no insert of ${e}.`:o==="not-in-target"?`Not written: ${r} may not be left empty, and the target org does not have ${e}.`:e===Lt?`Not written: a price sold under a selling model needs its product's option for that model, and ${e} is excluded from this run.`:`Not written: ${r} may not be left empty, and ${e} is excluded from this run.`}var ud="held back for want of their parent",gh=" \u2014 the records that cannot be written without one of those not written are held back",mh={accountNotWritten:"not sent: a person account's contact goes in with its account, which this run did not write",contactNotFound:"not sent: a person account's contact goes in with its account, and the one the platform wrote was not found"};function Rs(r){let e=new Map;for(let{excluded:n,namedBy:o,target:s}of r){let i=o!==void 0,a=`${i?"named":"needing"}|${s??""}`,d=e.get(a)??{namedOnly:i,target:s,objects:[]};d.objects.push(n),e.set(a,d)}let t=({namedOnly:n,target:o})=>(n?3:0)+(o===void 0?0:o==="not-creatable"?1:2);return[...e.values()].sort((n,o)=>t(n)-t(o)).map(({namedOnly:n,target:o,objects:s})=>{let i=`${[...new Set(s)].sort().join(", ")}${Lr(o)}`;return{count:s.length,why:n?`held back, named only by records held back for ${i}`:`held back for want of ${i}`}})}function Gt(r,e){return Rs(r.heldForExclusions.get(e)?.values()??[])}function Wn(r){return r.reduce((e,t)=>e+t.count,0)}function rn(r){return r.map(({count:e,why:t})=>`, ${e} of them ${t}`).join("")}function Os(r,e=!1){let t=Wn(r);if(t===0)return"";let n=`, ${t} ${e?"more ":""}failed`;return r.length===1?`${n}, ${r[0].why}`:n+rn(r)}function wh(r,e){return bs(r,e)+Os(Gt(r,e))}function gw(r){return[...r.heldForExclusions].map(([e,t])=>{let n=new Map;for(let o of t.values()){let s=`${o.field}|${o.through??""}|${o.namedBy??""}|${o.excluded}|`+(o.target??""),i=n.get(s)??{...o,count:0};i.count++,n.set(s,i)}return{objectApiName:e,stage:"scope",failedCount:t.size,attemptedCount:0,samples:[...n.values()].sort((o,s)=>s.count-o.count).slice(0,3).map(o=>{let s=`${o.count} record${o.count===1?"":"s"}`;return{recordSummary:o.namedBy!==void 0?`named by ${o.namedBy}.${o.field} (${s})`:`${o.field} \u2192 ${o.through??o.excluded} (${s})`,messages:[hw(o)]}})}})}function mw(r,e){for(let[t,n]of r.heldForExclusions){let o=n.get(e);if(o)return{objectApiName:t,why:o}}}function yh(r,e,t){for(let n of t){let o=e[n.name];if(typeof o!="string"||o===""||r.remapper.get(o))continue;let s=mw(r,o);if(s){let{excluded:i,target:a}=s.why;return{field:n.name,excluded:i,through:s.objectApiName,...a?{target:a}:{}}}}}function On(r,e,t=[]){let n=e+Wn(t);return`Held back ${r}, nothing written, ${n} failed${rn(t)}`}function bh(r){return r>0?`, ${r} ${r===1?"person account's contact":"person accounts' contacts"} sent on their own: the target wrote none with their account`:""}function Nr(r,e,t){t<=0||r.writtenByThePlatform.set(e,(r.writtenByThePlatform.get(e)??0)+t)}function pd(r,e){return r.writtenBefore.from==="resume"?`${e} already in the target, written before the run stopped`:`${e} already in the target from the run retried`}function _h(r,e){let t=Math.min(r,Math.max(0,e)),n=r-t;return(n>0?`, ${n} linked to records already in the target`:"")+(t>0?`, ${t} linked to records the run created (the target refused them as copies of those)`:"")}var ww=3;function Za(r,e,t){let n=r.dryRun?"would be inserted":"succeeded",o=e.updated>0?`, ${e.updated} updated through their external id`:"",s=_h(e.linked,e.linkedToCreated),i=e.withTheirAccount>0?`, ${e.withTheirAccount} written by the platform with their person account`:"",a=e.withTheirEmail>0?`, ${e.withTheirEmail} written by the platform with their email`:"",d=Uh(e.teamOwners,e.teamOthers)+zh(e.rolesOfTheirOpportunity,e.rolesGiven),c=e.writtenBefore>0?`, ${pd(r,e.writtenBefore)}`:"",l=e.unidentified>0?` (${e.unidentified} already in the target without Salesforce naming the record \u2014 their children lose the link)`:"";return`${e.succeeded} ${n}${o}${s}${a}${i}${d}${c}, ${e.failed+Wn(t)} failed${l}${rn(t)}`}function Uh(r,e){return(r>0?`, ${r} written by the platform with their opportunity, for its owner`:"")+(e>0?`, ${e} on the team of their opportunity in the target already`:"")}function zh(r,e){if(r===0)return"";let t=e>0?`, ${e} given the source's fields ${e===1?"it":"they"} lacked`:"";return`, ${r} written by the platform with their opportunity, for its contact${t}`}function yw(r,e,t){e.forEach(({source:n},o)=>{let s=n.Id,i=t[o]?.[Pe];typeof s=="string"&&(typeof i=="string"&&i!==""?r.contactSentWith.set(s,i):r.contactSentWith.delete(s))})}function bw(r,e){for(let t of["notKept","unread"])for(let[n,o]of e[t])r[t].set(n,(r[t].get(n)??0)+o)}function Gh(r){return[...[...r.notKept].map(([e,t])=>`${t} linked without the source's ${e}: the target's record keeps its own`),...[...r.unread].map(([e,t])=>`${t} linked whose ${e} was not read: the platform writes the record with the opportunity, which a dry run does not write`)].join(", ")}function Mr(r,e,t=!0){let n=[...e.values()].filter(d=>d.namedBy===void 0),o=[...e.values()].filter(d=>d.namedBy!==void 0),s=[...e.values()].every(d=>d.target===void 0),i=d=>s?[...new Set(d.map(c=>c.excluded))].sort().join(", "):fw(d),a=o.length===0?`every record needs ${i(n)}`:n.length===0?`the only records that name its records are held back for ${i(o)}`:`${n.length} of its records need ${i(n)}, and the only records that name the rest are held back for ${i(o)}`;return`${On(r,e.size)}: ${a}${s?", excluded from this run":""}.`+(t?" Objects that cannot be written without it will be skipped.":"")}function Rh(r){let e=new Map(r.readAtItsTurn);for(let[s,i]of r.preread)e.set(s,i);let t=new Map,n=[];for(let[s,{records:i,fieldInfos:a}]of e){let d=a.filter(u=>u.isReference),c=Je.has(s),l=r.scopeCache?.reachedOf(s);for(let u of i){let p=u.Id,f={row:u,lookups:d};c&&typeof p=="string"&&p!==r.config.rootRecordId&&l?.has(p)!==!0?t.set(p,f):n.push(f)}}let o=new Set;for(let s=n.pop();s;s=n.pop())for(let i of s.lookups){let a=s.row[i.name];if(typeof a!="string"||a===""||o.has(a))continue;o.add(a);let d=t.get(a);d&&n.push(d)}return o}function Oh(r,e,t,n){let o=r.namedByRowsHeldBack.get(t);if(!(!o||n.has(t)||t===r.config.rootRecordId)&&!(t===r.standardPricebookId||r.config.writtenBefore.has(t))&&r.scopeCache?.reachedOf(e)?.has(t)!==!0)return o}function kh(r){for(let[e,t]of Object.entries(fr))if(t.object===r)return{parent:e,lookup:t.lookup}}function Rw(r,e){return e.filter(t=>t.isReference&&Ze(r,t.name,t.nillable)).map(t=>t.name)}function Ow(r){return r.isScoped===!0||r.files!==void 0||r.beforeWrite!==void 0}function ed(r){return r.size===0?"":`, written without a lookup naming a record the target does not hold, which the platform fills (the owner with the user the run writes as): ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}`}function Sh(r,e){for(let{lookupsNotCarried:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function td(r){return r.size===0?"":`, written without ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}: the target holds no record of these ids, outside the run`}function nd(r,e){for(let{lookupsOutsideTheRun:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function kw(r){return[...r.lookupsOutsideTheRun].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t].sort(([,n],[,o])=>o.rows-n.rows).map(([n,{parent:o,rows:s}])=>({recordSummary:`${n} \u2192 ${o} (${s} record${s===1?"":"s"})`,messages:[`Written without ${n}: the target holds no record of these ids, outside the run.`]}))}))}var Th=10;function rd(r){return r===0?"":`, written with the user the run writes as for owner on ${r}: the target holds their owner inactive`}function Ah(r){return r.filter(({ownerInactive:e})=>e!==void 0).length}function Sw(r,e,t){let n=r.ownersInactive.get(e);for(let{ownerInactive:o}of t)o!==void 0&&(n??={rows:0,owners:new Set},n.rows+=1,n.owners.add(o));n&&r.ownersInactive.set(e,n)}function Tw(r){return[...r.ownersInactive].map(([e,{rows:t,owners:n}])=>{let o=[...n],s=o.slice(0,Th).join(", "),i=o.length-Th;return{objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`OwnerId \u2192 User (${t} record${t===1?"":"s"})`,messages:[`Written with the user the run writes as for owner: the target holds these owners inactive (${i>0?`${s}, and ${i} more`:s}) and that user may not give a record an inactive owner (Update Records with Inactive Owners). Map them to an active user under Owners (Review \u2192 Controls, or --owner-map on the command line) to give the records to that user.`]}]}})}function hs(r){return`${r} on a case waiting for ${r===1?"its task":"their tasks"}`}function od(r,e,t){t<=0||r.notSent.set(e,(r.notSent.get(e)??0)+t)}function Aw(r,e,t,n){return{...r,status:t&&r.status!=="error"?"stopped":r.status,message:`${r.message}; ${t?"stopped: ":""}${e} not sent${n}`}}function Bn(r,e){r.store?r.store.withTheirRecord(e):r.withTheirRecord.add(e)}function jw(r,e){return r.store?r.store.markedWithTheirRecord(e):r.withTheirRecord.has(e)}function vw(r){return r.store?[...r.store.withTheirRecordIds()]:[...r.withTheirRecord]}var ks=class extends Error{constructor(e,t){super(`Internal error: ${e} holds more rows than a clone of the whole org reads whole${t===void 0?"":` (${t})`}, which its gate should have refused before anything was written. The run stopped rather than write part of it: raise sandforge.forge.maxRecordsPerObject, or leave the object out.`),this.name="WholeReadPastBoundError"}},jh="files",sd=200,Iw=Ln,id=[{object:"ContentVersion",counted:"ContentDocument",size:"ContentSize",where:"IsLatest = true AND ContentLocation = 'S'"},{object:"Attachment",counted:"Attachment",size:"BodyLength",where:""}];function vh(r,e){let t=r.objects.find(n=>n.objectApiName===e);return t||(t={objectApiName:e,planned:0,plannedBytes:0,copied:0,failed:0},r.objects.push(t)),t}function Ew(r,e){let t=[];for(let n of e){let o=n.Id,s=n.ParentId;if(typeof o!="string"||typeof s!="string"||!r.remapper.wasCreated(s))continue;let i=n.Name,a=typeof i=="string"&&i!==""?i:o,d=n.ContentType,c=n.BodyLength;t.push({objectApiName:"Attachment",sourceId:o,body:{objectApiName:"Attachment",id:o},name:a,bytes:typeof c=="number"&&Number.isFinite(c)?c:0,hosts:[{id:s}],fields:{Name:a,...typeof d=="string"&&d!==""?{ContentType:d}:{},IsPrivate:n.IsPrivate===!0}})}return t}function Ih(r){return r?.errorCode==="INVALID_QUERY_LOCATOR"||Y(r).includes("INVALID_QUERY_LOCATOR")}function Eh(r){if(yc(r))return!0;let{errorCode:e,statusCode:t}=r??{};return e==="SERVER_UNAVAILABLE"||t===502||t===503||t===504?!0:Y(r).includes("SERVER_UNAVAILABLE")}function $h(r){return new Promise(e=>setTimeout(e,r))}function $w(r,e){return e?r?`(${r}) AND ${e.where}`:e.where:r}function gs(r,e){return ho(e)?Or(e)?!0:!r.writtenObjects.has(e):!1}function nn(r,e){let t=e.Id;return typeof t=="string"&&r.writtenBefore.has(t)}function xh(r,e){if(e!==void 0&&r.recordTypeDecisions.get(e)?.to!==null)return r.recordTypeMappings?.find(t=>t.sourceId===e)?.developerName}function xw(r){let e=(r?.recordTypes??[]).filter(t=>!t.master);if(!e.some(t=>t.namespacePrefix===void 0))return e.map(Zc)}function qh(r){return(r?.recordTypes??[]).filter(e=>e.available&&e.active&&!e.master).map(e=>e.developerName)}var Ph=200,Ch=200,Fh=/[\u0000-\u001f]/;function ad(r,e){return!lt(e)||r.pricesSwappedSaid.length===0?"":`, ${ya(r.pricesSwappedSaid).join("; ")}`}var Pw=/^012000000000000(AAA)?$/;function Nh(r){return(e,t)=>{for(let n of Object.keys(t))n!=="Id"&&r.patched(String(t.Id),n)}}var Cw=["insert","upsert"],Fw=["insert","upsert","update"];function Mh(r,e){let t="";for(let n of Cw){let o=r.splitting.sizes.report({objectApiName:e,op:n});if(!o||o.to>=o.from)continue;let s=`${n}\0${e}`,i=o.rows-(r.smallerCallsSaid.get(s)??0);i<=0||(r.smallerCallsSaid.set(s,o.rows),t+=`, ${i} sent ${o.to} at a time after the target's automation hit a Salesforce limit`)}return t}function Nw(r,e){let{objectApiName:t}=r,n=r.op==="update"?"lookup updates":"records",o=r.alone+r.notSplit+r.keptWhole,s=r.to<r.from&&r.rows>0?`${t}: ${r.rows} ${n} sent ${r.to} at a time`:`${t}: ${o} ${n} refused for a Salesforce limit`;return{objectApiName:t,stage:"scope",failedCount:0,attemptedCount:r.rows,samples:[{recordSummary:s,messages:[ul(r),...r.notSplit>0?[pl(r.notSplit,e,"run")]:[]]}]}}function Mw(r){return Fw.flatMap(e=>r.splitting.sizes.reports(e).filter(t=>t.rows+t.alone+t.notSplit+t.keptWhole>0).map(t=>Nw(t,fl(r.splitting.allowance,{objectApiName:t.objectApiName,op:e}))))}function ms(r){return{sending:(e,t,n,o)=>{let s=t.map(({payload:d})=>d),i=Vp(s),a=o===!0&&n===void 0?Yp(s):[];return r.sent(e,i,t.flatMap(({sourceId:d,payload:c,owes:l},u)=>d===void 0?[]:[{sourceId:d,fingerprint:Jp(c,i),owes:l,...n!==void 0?{externalKey:Qp(c,n)}:{},...a[u]!==void 0?{jobKey:a[u]}:{}}]),new Date,n)},answered:e=>r.answered(e),opened:(e,t)=>r.jobOpened(e,t),unattributed:(e,t)=>r.createdUnattributed(e,t)}}function Bh(r){let e=new Map;for(let{objectApiName:t,id:n,status:o}of r){let s=e.get(t)??[];s.push({id:n,status:o}),e.set(t,s)}return e}var Bw=[["CreatedDate","LastModifiedDate","SystemModstamp"],["SystemModstamp"]],Lw=new Set(["CreatedDate","LastModifiedDate"]),Ww=new Set(["string","textarea","email","phone","url","picklist","multipicklist","combobox","encryptedstring"]);function Dw(r){return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function ws(r){return typeof r=="string"?Date.parse(r):Number.NaN}var Lh="005",fd=class{ids=new Set;issued=0;idFor(e){this.issued++;let n=`${e&&/^[A-Za-z0-9]{3}$/.test(e)?e:"000"}SIM${String(this.issued).padStart(12,"0")}`;return this.ids.add(n),n}has(e){return this.ids.has(e)}};function _w(r,e,t){return{...r,bulkWriteRecords:void 0,insertRecords:async(n,o,s)=>{let i=await t(n,o);return s.map(()=>({id:e.idFor(i),success:!0,errors:[]}))}}}function Uw(r,e,t){if(!r||!e)return"notRead";let n=r.source.RecordTypeId;return typeof n=="string"&&n!==""&&t.get(n)?.to===null?"decidedDefault":"RecordTypeId"in r.source&&pa(n)?"masterInSource":"notRead"}function zw(r,e){return{objectApiName:r,rows:e.rows,why:{...e.why},...e.predicted?{predicted:{...e.predicted}}:{},...e.readBack?{readBack:{...e.readBack,types:e.readBack.types.map(t=>({...t}))}}:{}}}function dd(r,e){return[r[kt],e?r[Bt]:"",r[ut]].map(t=>String(t??"")).join("|")}function Wh(r,e){let t=new Set(e??[]);return r.filter(n=>n.createable&&n.queryable&&!n.isReference&&!t.has(n.name)&&(n.type===void 0||Ww.has(n.type)))}var Gw=200,qw="the standard price of its product, which it may not go without, changed since the sample";function Hw(r){return r?{sample:r}:{}}function Kw(r){let e=r.options;return{seed:e.seed??un.seed,draw:e.draw??un.draw,parents:e.parents??un.parents,children:e.children??un.children,floor:e.floor??un.floor,...e.whole&&e.whole.length>0?{whole:[...e.whole]}:{}}}var sr=class{deps;isPaused=!1;pauseResolve=null;isAborted=!1;bulkCancel=new AbortController;sampling=new AbortController;running=null;constructor(e){this.deps=Lf(e)}summarySoFar(){return this.running?this.summaryOf(this.running):void 0}pause(){this.isPaused||(this.isPaused=!0)}resume(){this.isPaused=!1;let e=this.pauseResolve;this.pauseResolve=null,e?.()}abort(){this.isAborted=!0,this.bulkCancel.abort(),this.sampling.abort();let e=this.pauseResolve;this.pauseResolve=null,this.isPaused=!1,e?.()}async bulkTransportOf(e,t){if(e.writeApi!=="auto"||e.dryRun||!this.deps.bulkWriteRecords)return;let n=await this.deps.duplicateRuleObjects?.(t).catch(()=>{}),o=n??_i;return nt.info(`[forge] writing through the Bulk API: a job per ${vr} rows of an object from ${2e3}, one at a time on a job limiter of the run's own; by REST: ${[...Uo,...o].join(", ")}`+(n?"":" (the target did not say which objects its duplicate rules watch)")),this.bulkCancel=new AbortController,this.isAborted&&this.bulkCancel.abort(),{signal:this.bulkCancel.signal,restOnly:new Set([...Uo,...o]),bulkUnsupported:new Set,manager:new Cc(1)}}bulkUpdatesOf(e){let{bulk:t}=e,n=this.deps.bulkWriteRecords;return!t||!n?{}:{bulkUpdate:(o,s)=>n(e.targetOrgId,o,"update",s,{bulkManager:t.manager,signal:t.signal}),restOnly:t.restOnly,bulkUnsupported:t.bulkUnsupported}}async waitIfPaused(){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. No further batches will be processed.");if(this.isPaused&&(await new Promise(e=>{this.pauseResolve=e}),this.isAborted))throw new Oe("Forge execution was aborted while paused. No further batches will be processed.")}anonymizeRows(e,t,n,o,s,i){let a=e.config.anonymization;if(!e.anonymize||!a)return n;let d=a.fields[t]??this.detectedPersonalFields(e,a,t,s);if(d.length===0)return n;let c=new Map(s.map(l=>[l.name,l]));return e.anonymize({objectApiName:t,records:n,sourceIds:o,fields:d.map(l=>{let u=c.get(l);return{name:i[l]??l,type:u?.type??"",...u?.length!==void 0?{length:u.length}:{}}}),methods:a.methods})}detectedPersonalFields(e,t,n,o){let s=e.detectedPersonalFields.get(n);if(s)return s;let i=t.personalFieldsOf?.(o.map(a=>({name:a.name,type:a.type??""})))??[];return e.detectedPersonalFields.set(n,i),i}async fieldExclusionsOfTheSource(e,t,n){let o=Object.keys(e);if(o.length===0)return{exclusions:{},unmatched:[]};let s=t.nodes.map(a=>a.objectApiName),i=new Map;for(let a of o){let d=s.find(c=>c.toLowerCase()===a.toLowerCase())??a;if(!i.has(d))try{let c=await this.deps.describeFields(n,d);i.set(d,c.map(l=>l.name))}catch(c){i.set(d,Qn(c)?void 0:null)}}return Do(e,s,a=>i.has(a)?i.get(a):null)}fileCopyUnwired(){let{readFileBody:e,insertFile:t,remainingFileStorageMB:n}=this.deps;return e&&t&&n?null:"This session cannot copy files: it reads no file content or file storage. Nothing was read or written."}fileCopyDeps(){let{readFileBody:e,insertFile:t,remainingFileStorageMB:n}=this.deps;return!e||!t||!n?null:{queryRecords:(o,s)=>this.deps.queryRecords(o,s),readFileBody:e,insertFile:t,insertRecords:this.deps.insertRecords,remainingFileStorageMB:n}}anonymizerForRun(){if(this.deps.anonymize)return this.deps.anonymize;let e=new cs;return t=>e.anonymize(t)}async execute(e,t,n,o,s){this.isAborted=!1,this.isPaused=!1,this.pauseResolve=null;let i=this.deps.requestsSent?.(),a=_l(s);if(a.files){let A=Xr(a.anonymization!==void 0,a.files.acceptedAsIs);if(A)throw new wn(A,"FILES_NOT_ACCEPTED");let x=this.fileCopyUnwired();if(x)throw new wn(x,"FILES_NOT_COPYABLE")}let d=await os(a.ownerMappings,A=>this.deps.queryRecords(n,A),Zn);if(d)throw d;let c=new Map,l=await this.recordTypeDecisionsOf(s?.decisions?.recordTypeMappings??[],t,n,c),u=await this.fieldExclusionsOfTheSource(a.fieldExclusions,e,t),p={...a,fieldExclusions:u.exclusions,...l.bySource.size===0?{}:{recordTypeMappings:Dl(a.recordTypeMappings,l),recordTypeDecisions:l.bySource}},f=p.dryRun?new fd:null,h=p.excludedObjects,g=await this.withWhatStatusesNeed(Lo(e,h),t,h),m=p.isScoped?await this.withWhatItsRecordsComeWith(g.graph,t,h):g.graph,w=await this.withSellingModelOptions(await this.withTheCatalogItNeeds(m,t,h),t,h),b=this.deps.recordTypePicklists,S=p.dryRun?void 0:p.stream?.store,R=new Date;S?.beginPart(R);let k=ll(),I=await this.bulkTransportOf(p,n),O={...I?{bulk:I}:{},config:p,sourceOrgId:t,targetOrgId:n,graph:w,onProgress:o,remapper:new $r(S),scopeCache:p.isScoped?new cp:null,scopedBuilder:p.isScoped?new hn:null,recordTypeMapper:p.recordTypeMappings?new ts:null,referenceDataMapper:new is((A,x)=>this.deps.queryRecords(A,x)),orphanExpander:new as(f?_w(this.deps,f,async(A,x)=>this.deps.describeObject?this.deps.describeObject(A,x).then(j=>j.keyPrefix,()=>null):null):this.deps),batchWriter:new su(this.deps,this.deps.batchStrategy,void 0,k),splitting:k,smallerCallsSaid:new Map,failedObjects:new Set,failedInPart:new Set,heldInTheOrg:new Map,leftAside:new Map,turnsEnded:new Set,notCreatable:new Set,notInTarget:new Set,errors:[],truncatedObjects:new Set,cappedObjects:new Set,fieldExclusionsUnmatched:u.unmatched,pendingFkUpdates:[],owedToRowsWrittenBefore:[],deferredNodes:[],turnsAhead:new Set,waitingFor:new Map,readAgainUnder:new Map,askedForRowsThatNeedThem:new Map,targetHolds:new Map,targetReadsRefused:new Set,inactiveUsers:new Set,writesInactiveOwners:yp(A=>this.deps.queryRecords(n,A)),ownersInactive:new Map,lookupsOutsideTheRun:new Map,parentsOutside:new Map,readAsParents:new Map,idsRead:S?{add:A=>S.noteRead(A),has:A=>S.wasRead(A)}:new Set,catalogNodes:[],preread:new Map,readByObject:new Map,notSent:new Map,failedReads:new Set,sourceKeyPrefixes:new Map,cursors:new Map,counted:new Map,tableRecordTypes:new Map,keyPrefixesAsked:new Set,readObjects:new Set(w.nodes.filter(A=>A.included).map(A=>A.objectApiName)),writtenObjects:new Set,sellingModels:w.nodes.some(A=>A.included&&A.objectApiName===hr),standardPricebookId:null,existingRecords:[],lifecycles:new Map,deferredStatuses:[],...S?{store:S}:{},secondPassInStore:!1,statusesGiven:!1,leftDrafts:new Set,statusChildren:g.added,pastDraft:new Map,heldForExclusions:new Map,namedByRowsHeldBack:new Map,readAtItsTurn:new Map,statusChildrenRead:new Map,anonymize:p.anonymization?this.anonymizerForRun():null,contactPoints:p.keepContactPoints?null:new Zo(void 0,{upsertKeys:p.upsertMode==="auto"}),detectedPersonalFields:new Map,fileScope:new Map,files:null,fileContentFieldsLeftOut:new Map,maskedSourceFields:Tl(Sl(A=>this.deps.queryRecords(t,A)),async A=>({fields:await this.deps.describeFields(t,A)})),encryptedFieldsLeftOut:new Map,recordTypePicklists:new Ml(b&&((A,x)=>b(n,A,x))),picklistChanges:new Fo,currencyChanges:new Ro,currencyChangesById:new Map,recordTypesGiven:new Map,recordTypesUnderTheLease:new Map,pricesSwappedSaid:[],prices:{standsFor:new Map,convertedInto:new Map,written:new Map,keys:new Map},readsEverythingFirst:!1,writtenWithoutFields:new Map,leftEmptyByFilter:new Map,contactsOnTheirOwn:new Set,withTheirRecord:new Set,startedAt:R,writtenByThePlatform:new Map,contactSentWith:new Map,leftToThePlatform:new kc,emailsAfterTheirTask:[],taskTurnOver:!1,emailsInTwoPasses:!1,emailsLeftForTheirTask:0,emailsFirstPassRan:!1,syncedQuotesLeft:0,requestsBefore:i,simulated:f,gaps:p.dryRun?new ol:null,decisionsApplied:new Bi,mayHaveBeenWritten:new Map,sourceRecordTypes:new Map,recordTypeRows:c,successCount:0,updatedCount:0,linkedCount:0,linkedToCreatedCount:0,wouldInsertCount:0,failedCount:0,skippedCount:0};for(let[A,x]of p.writtenBefore)O.remapper.addExisting(A,x);for(let{decision:A,reason:x}of l.unresolved)O.errors.push({objectApiName:A.object,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(record type ${A.from} \u2192 ${A.to??"the default"})`,messages:[`The decision was not applied: ${x}.`]}]});this.running=O;try{return await this.runPasses(O)}catch(A){throw this.endBeforeTheEmailsThatWaited(O,O.emailsAfterTheirTask.length+O.emailsLeftForTheirTask,A instanceof Oe),this.saySyncedQuotesLeft(O),await this.readWrittenBetween(O),this.reportDraftsLeft(O),S?.settleReads(),Ep(A,this.summaryOf(O)),A}finally{this.running===O&&(this.running=null),S?.settleReads(),S?.flush()}}async recordTypeDecisionsOf(e,t,n,o){if(e.length===0)return Li([],[]);let s=this.deps.describeObject,i=async(c,l)=>s?s(c,l).then(u=>this.namedRecordTypes(o,c,u.recordTypes),()=>[]):[],a=[...new Set(e.map(c=>c.object))],d=await Promise.all(a.map(async c=>({objectApiName:c,source:await i(t,c),target:await i(n,c)})));return Li(e,d)}async namedRecordTypes(e,t,n){if(!n.some(s=>!s.master))return n;let o=e.get(t);return o||(o=this.deps.queryRecords(t,ko).then(s=>So(s),()=>[]),e.set(t,o)),To(n,await o)}async targetObjectInfoOf(e,t){let n=await this.objectInfoOf(e.targetOrgId,t);return!n||!(e.gaps!==null||n.recordTypes.some(s=>!s.available&&!s.master)||e.config.decisions.namesARecordTypeBare(t))?n:{...n,recordTypes:await this.namedRecordTypes(e.recordTypeRows,e.targetOrgId,n.recordTypes)}}async withMaskedLeftOut(e,t,n,o,s){if(o.length===0)return n;let i=await e.maskedSourceFields(t).catch(()=>[]),a=i.filter(d=>!n.has(d)&&s(d)&&o.some(c=>c[d]!==null&&c[d]!==void 0));return this.noteEncryptedLeftOut(e,t,a),i.length>0?new Set([...n,...i]):n}noteEncryptedLeftOut(e,t,n){if(n.length===0)return;let o=e.encryptedFieldsLeftOut.get(t)??new Set;for(let s of n)o.add(s);e.encryptedFieldsLeftOut.set(t,o)}withoutFileContent(e,t,n,o){let s=n.filter(i=>In(i)&&i.createable);if(o&&s.length>0){let i=e.fileContentFieldsLeftOut.get(t)??new Set;for(let a of s)i.add(a.name);e.fileContentFieldsLeftOut.set(t,i)}return n.filter(i=>!In(i))}async readWrittenBetween(e){if(e.config.dryRun||e.writtenBetween)return;if(e.config.stream?.everything===!0&&e.store){await this.readWrittenBetweenByObject(e,e.store);return}let t=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let{objectApiName:o,sourceIds:s}of e.remapper.createdByObject()){let i=s.flatMap(d=>{let c=e.remapper.get(d);return c?[c]:[]});if(i.length===0)continue;let a=await this.auditDatesCopied(e,o);for(let d of Cn(i)){let c=await this.writtenDatesOf(e.targetOrgId,o,d);if(!c)return;for(let l of c){let u=ws(l.SystemModstamp),p=g=>{let m=a?Number.NaN:ws(l[g]);return Number.isFinite(m)?m:u},f=p("CreatedDate"),h=p("LastModifiedDate");Number.isFinite(f)&&(t=Math.min(t,f)),Number.isFinite(h)&&(n=Math.max(n,h))}}}Number.isFinite(t)&&Number.isFinite(n)&&(e.writtenBetween={first:new Date(t).toISOString(),last:new Date(Math.max(t,n)).toISOString()})}async readWrittenBetweenByObject(e,t){let n=Dw(e.startedAt.getTime()-xa),o=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY,i=!1;for(let{objectApiName:a,created:d}of t.countsByObject()){if(d===0)continue;let c=Me(a),u=[...await this.auditDatesCopied(e,a)?[]:[`SELECT MIN(CreatedDate) f, MAX(SystemModstamp) l FROM ${c} WHERE CreatedDate >= ${n}`],`SELECT MIN(SystemModstamp) f, MAX(SystemModstamp) l FROM ${c} WHERE SystemModstamp >= ${n}`],p=!1;for(let f of u)try{let[h]=await this.deps.queryRecords(e.targetOrgId,f),g=ws(h?.f),m=ws(h?.l);Number.isFinite(g)&&(o=Math.min(o,g)),Number.isFinite(m)&&(s=Math.max(s,m)),p=!0;break}catch{}p||(i=!0)}i&&(o=Math.min(o,e.startedAt.getTime()),s=Math.max(s,Date.now()+xa)),Number.isFinite(o)&&Number.isFinite(s)&&(e.writtenBetween={first:new Date(o).toISOString(),last:new Date(Math.max(o,s)).toISOString()})}async writtenDatesOf(e,t,n){let o=Me(t);for(let s of Bw)try{return await this.deps.queryRecords(e,`SELECT Id, ${s.join(", ")} FROM ${o} WHERE Id IN (${n})`)}catch{}}async auditDatesCopied(e,t){let n=o=>o.some(s=>Lw.has(s.name)&&s.createable);try{let[o,s]=await Promise.all([this.deps.describeFields(e.sourceOrgId,t),this.deps.describeFields(e.targetOrgId,t)]);return n(o)&&n(s)}catch{return!0}}async runPasses(e){let{config:t,graph:n,sourceOrgId:o,targetOrgId:s,onProgress:i}=e;e.scopeCache&&t.rootRecordId&&t.rootObjectApiName&&e.scopeCache.add(t.rootObjectApiName,[t.rootRecordId]);let a=Kl(n,t.isScoped?t.rootObjectApiName:void 0),d=this.streamsTheRun(e),c=!d&&Ow(t);e.readsEverythingFirst=c,e.emailsInTwoPasses=d&&t.stream?.everything===!0,e.secondPassInStore=e.store!==void 0&&!c,c&&e.store&&e.pendingFkUpdates.push(...e.store.owedLeftByEarlierParts());let l=c?a:await this.singlePassOrder(e);if(c&&e.scopeCache)for(let S of l)S.included&&e.turnsAhead.add(S.objectApiName);if(n.nodes.some(S=>lt(S.objectApiName)))try{let[S,R]=await Promise.all([this.deps.queryRecords(o,ti),this.deps.queryRecords(s,ti)]),k=S[0]?.Id,I=R[0]?.Id;typeof k=="string"&&typeof I=="string"&&(e.standardPricebookId=k,e.remapper.addExisting(k,I),e.scopeCache?.add(Rt,[k]),e.readObjects.add(Rt),n.nodes.some(O=>O.included&&O.objectApiName===Rt)||e.scopeCache?.addRead(Rt,[]))}catch(S){e.errors.push({objectApiName:We,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(standard price book lookup)",messages:[Y(S)]}]})}let u=new Map,p=this.deps.isObjectCreatable;if(p){let S=[...new Set(a.filter(R=>R.included&&!t.referenceDataObjects.has(R.objectApiName)).map(R=>R.objectApiName))];for(let R=0;R<S.length&&!this.isAborted;R+=6){let k=S.slice(R,R+6),I=await Promise.allSettled(k.map(async O=>p(s,O)));k.forEach((O,A)=>u.set(O,I[A]))}}for(let[S,R]of u)R.status!=="rejected"||!Qn(R.reason)||(e.notInTarget.add(S),e.readObjects.delete(S),e.turnsAhead.delete(S));for(let S of n.nodes){let R=u.get(S.objectApiName);!S.included||R?.status==="fulfilled"&&!R.value||e.notInTarget.has(S.objectApiName)||e.writtenObjects.add(S.objectApiName)}d&&await this.planTheSample(e,l),d&&t.beforeWrite&&await this.countBeforeWrite(e,l);for(let S of l){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");if(!S.included){e.skippedCount++,i({objectName:S.objectApiName,status:"skipped",progress:100,message:`Skipped ${S.objectApiName} (${Xm(S)})`});continue}if(e.notInTarget.has(S.objectApiName)){this.reportNotInTarget(S,e),await this.endTurn(S.objectApiName,e);continue}if(await this.skipForFailedParent(S,e)){await this.endTurn(S.objectApiName,e);continue}let R=u.get(S.objectApiName);if(R)if(R.status==="fulfilled")R.value||e.notCreatable.add(S.objectApiName);else{let k=R.reason;e.errors.push({objectApiName:S.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed)",messages:[`isObjectCreatable check failed: ${k instanceof Error?k.message:String(k)}`]}]})}c?await this.readInTurn(S,e):d&&this.streamsNode(S,e)?(await this.streamNode(S,e),e.turnsEnded.add(S.objectApiName),S.objectApiName===st&&await this.writeEmailsAfterTheirTask(e)):(await this.readNode(S,e,!1,!0)&&await this.writeNode(S,e),e.turnsEnded.add(S.objectApiName),S.objectApiName===st&&await this.writeEmailsAfterTheirTask(e),S.objectApiName===ye&&await this.mapContactsOfPersonAccounts(e),this.releaseRows(e,S.objectApiName))}let f=Vl(e.deferredNodes.splice(0,e.deferredNodes.length),e.catalogNodes,n.edges),h=f.map(S=>Je.has(S.objectApiName)).lastIndexOf(!0);for(let[S,R]of f.entries()){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");await this.skipForFailedParent(R,e)||(c?(e.scopeCache&&Je.has(R.objectApiName)&&(this.holdBackWhatHeldRowsCost(e),this.leaveOutWhatOnlyRowsHeldBackName(e,R.objectApiName)),await this.readNode(R,e,!1,!1),await this.readUnderWhatWaited(R.objectApiName,e,h>=0&&S>h?"after the catalog":"before the catalog")):await this.readNode(R,e,!1,!0)&&(await this.writeNode(R,e),e.turnsEnded.add(R.objectApiName),this.releaseRows(e,R.objectApiName)))}await this.readCatalogAgain(e,h<0?[]:f.slice(h+1));for(let S of[...e.preread.keys()])this.releaseRows(e,S,!0);if(c){do this.holdBackWhatHeldRowsCost(e);while(this.holdBackWhatOnlyRowsHeldBackName(e));if(await this.readParentsOutsideTheGraph(e))do this.holdBackWhatHeldRowsCost(e);while(this.holdBackWhatOnlyRowsHeldBackName(e))}let g=t.stream?.everything===!0,m=t.files&&!g?await this.prepareFiles(e):[];if(c&&t.beforeWrite){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");let S=await this.pricesTheGateCounts(e),R=dh(e).cappedObjects,k=await this.withoutWhatTheTargetHoldsByValue(e,await this.withoutWhatThePlatformWrites(e,await Promise.all([...e.preread].map(([A,x])=>this.toWriteAtTheGate(e,A,x,lt(A)?S:0))))),I=t.dryRun?0:await this.readBackRequests(e,k),O=await t.beforeWrite({objects:k,...R?{capped:R}:{},...I>0?{readBack:I}:{},dryRun:t.dryRun});await this.afterTheGate(e,O,k)}if(c)for(let S of this.writeOrderOf(e)){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");let R=e.preread.get(S.objectApiName);if(R&&!await this.skipForFailedParent(S,e,R.fieldInfos,R.records)&&(await this.writeNode(S,e),S.objectApiName===st&&await this.writeEmailsAfterTheirTask(e),S.objectApiName===ye&&await this.mapContactsOfPersonAccounts(e),e.pendingFkUpdates.push(...this.owedNowWritten(e)),e.pendingFkUpdates.length>0&&!t.dryRun)){let k=e.pendingFkUpdates.splice(0,e.pendingFkUpdates.length),I=[],O=await ka({pendingFkUpdates:k,remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:s,enabled:!0,onProgress:i,deferUnresolved:!0,stillPending:I,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:this.patchedInTheJournal(e),onAnswered:()=>e.store?.flush(),onRefusedByFilter:(A,x,j)=>this.noteLeftEmptyByFilter(e,A,x,j),...this.secondPassOfTheSample(e)});O&&e.errors.push(O),e.pendingFkUpdates.push(...I)}}await this.writeEmailsAfterTheirTask(e),e.pendingFkUpdates.push(...this.owedNowWritten(e));let w=e.secondPassInStore?await this.secondPassFromTheJournal(e):await ka({pendingFkUpdates:this.sayLookupsOutsideTheClone(e,e.pendingFkUpdates),remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:s,enabled:!t.dryRun,onProgress:i,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:this.patchedInTheJournal(e),onAnswered:()=>e.store?.flush(),onRefusedByFilter:(S,R,k)=>this.noteLeftEmptyByFilter(e,S,R,k),...this.secondPassOfTheSample(e)});if(w&&e.errors.push(w),this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");m.length>0&&!t.dryRun?await this.writeFiles(e,m):g&&t.files&&!t.dryRun&&await this.copyFilesOfTheOrg(e,t.files.maxFileBytes),this.reportDraftsExclusionsLeave(e),await this.restoreStatuses(e),await this.giveTheLeaseBack(e);let b=e.orphanExpander.buildErrorReport();return b&&e.errors.push(b),this.saySyncedQuotesLeft(e),await this.readWrittenBetween(e),await this.readBackRecordTypes(e),this.summaryOf(e)}async afterTheGate(e,t,n){let o=t?t.splitAllowance:void 0;o!==void 0&&e.splitting.allowance.limitTo(o);let s=t?t.lease:void 0;s&&(e.lease=s,s.assigned>0&&await this.readAgainUnderTheLease(e,n))}async readAgainUnderTheLease(e,t){let n=this.deps.describeObjectAgain;if(!n)return;let o=await Promise.all(t.map(async({objectApiName:s,rows:i,counted:a})=>{if(!await this.mayGoWithoutRecordType(e,s,i,a))return[];try{let d=await n(e.targetOrgId,s);return[[s,d.recordTypes]]}catch{return[]}}));for(let[s,i]of o.flat())e.recordTypesUnderTheLease.set(s,i)}async mayGoWithoutRecordType(e,t,n,o){if(n.length===0&&(o?.rows??0)===0||!(await this.objectInfoOf(e.targetOrgId,t))?.recordTypes.some(d=>!d.master))return!1;if(n.length===0)return!0;let{config:i}=e;return!(e.preread.get(t)?.createableSet.has("RecordTypeId")===!0&&!(i.fieldExclusions[t]??[]).includes("RecordTypeId")&&i.fieldMappings[t]?.RecordTypeId===void 0)||n.some(d=>{let c=d.RecordTypeId;return typeof c!="string"||pa(c)||i.recordTypeDecisions.get(c)?.to===null})}async readBackRequests(e,t){let o=(await Promise.all(t.map(({objectApiName:i,rows:a,counted:d})=>this.mayGoWithoutRecordType(e,i,a,d)))).filter(Boolean).length,s=e.recordTypeRows.has(e.targetOrgId)&&!e.config.dryRun;return o>0&&!s?o+1:o}async giveTheLeaseBack(e){let t=e.lease;if(t){e.lease=void 0;try{await t.giveBack()}catch(n){nt.warn(`[forge] the mute's lease was not given back as the writes ended: ${Y(n)}`)}}}async readBackRecordTypes(e){e.simulated||await Promise.all([...e.recordTypesGiven].map(async([t,n])=>{if(n.ids.length!==0)try{let o=await this.deps.queryRecords(e.targetOrgId,rp(t,n.ids));n.readBack=op(o,n.types)}catch(o){n.readBack={read:0,types:[],unread:Y(o)}}}))}async recordTypeCounter(e,t,n,o){let s=e.recordTypesUnderTheLease.get(t)??n?.recordTypes??[];if(!s.some(c=>!c.master))return;let i=await this.namedRecordTypes(e.recordTypeRows,e.targetOrgId,s),a=tp(ep(i)),d=e.config.recordTypeDecisions;return(c,l)=>{let u=e.recordTypesGiven.get(t);u||(u={rows:0,why:{},...a?{predicted:a}:{},types:i,ids:[]},e.recordTypesGiven.set(t,u));let p=Uw(c,o,d);u.rows++,u.why[p]=(u.why[p]??0)+1,l!==void 0&&u.ids.length<np&&u.ids.push(l)}}streamsTheRun(e){let{config:t,graph:n}=e;return t.stream===void 0||t.isScoped?!1:t.stream.everything===!0?!0:t.files===void 0&&!n.nodes.some(o=>o.included&&o.objectApiName===je)}async keysOfTheTable(e,t,n){let{config:o,sourceOrgId:s}=e;if(o.upsertMode!=="auto"||!this.deps.upsertRecords||e.simulated)return;let i=t.objectApiName,a={unique:new Set,sent:new Set};try{n.described??=await this.deps.describeFields(s,i);let d=new Set(o.fieldExclusions[i]??[]),c=o.fieldMappings[i]??{},l=n.described.filter(w=>w.externalId===!0&&w.createable&&w.queryable&&!d.has(w.name)&&c[w.name]===void 0);if(l.length===0)return a;let u=n.described.find(w=>w.name==="Id"),p=gn({node:t,edges:e.graph.edges,fieldInfos:[...u?[u]:[],...l],scopedBuilder:null,scopeCache:null,extraWhere:this.filterOf(e,i),maxRecordsPerObject:this.readBound(e,t),inIdOrder:{}});if(p.kind!=="query"||p.statements.length!==1)return a;let f=p.limit??1/0,h=new Map(l.map(w=>[w.name,new Set])),g=0,m=_t(this.deps,s,p.statements[0],o.stream?.pageSize,void 0,this.readOptionsOf(e,i));try{for await(let w of m){for(let b of w){if(g>=f)break;g++;for(let[S,R]of h){let k=b[S];typeof k!="string"||k.length===0||R.has(k)?h.delete(S):R.add(k)}}if(g>=f||h.size===0||this.isAborted)break}}finally{await m.return(void 0)}return{unique:new Set(h.keys()),sent:a.sent}}catch(d){return nt.warn(`[forge] upsert: the external ids of ${i} could not be read \u2014 inserting it: `+Y(d)),a}}streamsNode(e,t){let n=e.objectApiName;return!Je.has(n)&&!lt(n)&&(n!==st||t.config.stream?.everything===!0)&&!t.config.referenceDataObjects.has(n)}releaseRows(e,t,n=!1){if(e.config.stream?.everything!==!0||!n&&(Je.has(t)||lt(t)))return;let o=e.preread.get(t);!o||o.records.length===0||e.preread.set(t,{...o,records:[]})}readsArchived(e,t){return e.config.stream?.everything===!0&&qu.has(t)}filterOf(e,t){let n=e.config.objectSoqlFilters?.[t];return this.readsArchived(e,t)?n?`(${n}) AND IsDeleted = false`:"IsDeleted = false":n}readOptionsOf(e,t){return this.readsArchived(e,t)?{all:!0}:void 0}async readWholeOf(e,t,n,o){let s=this.readOptionsOf(e,t);if(!s)return this.deps.queryRecords(e.sourceOrgId,n,o);let i=[],a=_t(this.deps,e.sourceOrgId,n,void 0,void 0,s);for await(let d of a)for(let c of d)i.push(c);return i}readBound(e,t){if(e.sample?.drawn.has(t.objectApiName))return;let n=e.config.maxRecordsPerObject,o=n!==void 0&&n>0?Math.floor(n):void 0,s=this.streamsNode(t,e)?e.config.stream?.ceiling:void 0;return o===void 0?s:s===void 0?o:Math.min(o,s)}async planTheSample(e,t){let{config:n,store:o}=e,s=n.stream?.everything===!0?n.stream.sample:void 0,i=o?.samplePlan;if(!s){if(i)throw new Rn("SAMPLE_PLAN_MISMATCH","The run this one resumes copied a sample of the whole org: resume it as a sample. "+Zn);return}let a;if(i)try{a=await er.open(i.dir,{sha256:i.sha256})}catch(d){throw d instanceof ss?new Rn("SAMPLE_PLAN_GONE",`The plan of the sample the run resumes is ${d.refusal==="gone"?"no longer on this machine":"no longer as it was drawn"}: it cannot go on with the same records. ${Zn} Copy a new sample rather than resume this one.`):d}else{if(o?.resumes)throw new Rn("SAMPLE_PLAN_MISMATCH",`The run this one resumes copied every record of the whole org, not a sample: resume it as it was set up. ${Zn}`);a=s.plan??await this.drawThePlan(e,t,s)}o&&!i&&o.nameSamplePlan({dir:a.dir,sha256:a.sha256}),e.sample=await this.runSampleOf(e,a)}async drawThePlan(e,t,n){let{config:o,sourceOrgId:s}=e,i=Kw(n),a=t.filter(R=>R.included&&(e.writtenObjects.has(R.objectApiName)||o.referenceDataObjects.has(R.objectApiName))),d=new Map;for(let R of a)d.set(R.objectApiName,await this.deps.describeFields(s,R.objectApiName));let c=(R,k)=>k.nillable===!1&&e.graph.edges.some(I=>I.type==="master-detail"&&I.targetObject===R&&(k.referenceTo??[]).includes(I.sourceObject)),l=[],u=new Map;for(let R of a){let k=R.objectApiName,I=new Set(o.fieldExclusions[k]??[]),O=(d.get(k)??[]).filter(A=>A.isReference&&!I.has(A.name)).map(A=>({name:A.name,referenceTo:A.referenceTo??[],isMasterDetail:c(k,A),...A.nillable!==void 0?{nillable:A.nillable}:{},createable:A.createable,...A.updateable!==void 0?{updateable:A.updateable}:{}}));if(l.push({objectApiName:k,rows:R.recordCount,keyPrefix:(await this.objectInfoOf(s,k))?.keyPrefix??e.sourceKeyPrefixes.get(k)??null,fields:O}),this.streamsNode(R,e)&&!o.referenceDataObjects.has(k)){let A=await this.recordTypesOfTable(e,R);A&&A.closedInSource.length>0&&u.set(k,{closed:new Set(A.closedInSource.map(le)),lacking:new Set(A.lackingInSource.map(le))})}}let p=await n.budget(),f=e.standardPricebookId&&a.some(R=>lt(R.objectApiName))?await this.runCurrencies(e):void 0,h=f&&this.priceCurrencyWrittenIn(e,f.target),g=new Map;if(a.some(R=>R.objectApiName===je)){let R=await this.averageEmailBytes(e,d.get(je)??[]);R!==void 0&&g.set(je,R)}let m=h?R=>f.target.active.has(R)?void 0:h(R):void 0;this.sampling=new AbortController,this.isAborted&&this.sampling.abort();let w;try{w=await Jf({source:{pages:(R,k)=>_t(this.deps,s,R,void 0,void 0,k),count:async(R,k)=>{let I=this.deps.countRecords;if(I)return k?I(s,R,k):I(s,R);let O=0,A=R.replace(/^SELECT COUNT\(\) FROM /,"SELECT Id FROM ");for await(let x of _t(this.deps,s,A,void 0,void 0,k))O+=x.length;return O}},objects:l,order:a.map(R=>R.objectApiName),excluded:new Map([...o.excludedObjects].map(R=>[R,null])),referenceData:o.referenceDataObjects,fieldsOf:R=>d.get(R)?.filter(k=>k.queryable).map(k=>({name:k.name,...k.groupable!==void 0?{groupable:k.groupable}:{},...k.sortable!==void 0?{sortable:k.sortable}:{},...k.aggregatable!==void 0?{aggregatable:k.aggregatable}:{}})),filterOf:R=>o.objectSoqlFilters?.[R],options:i,budget:p,...o.stream?.wholeReadBound!==void 0?{maxRecordsPerObject:o.stream.wholeReadBound}:{},recordTypeVerdict:(R,k)=>{let I=u.get(R),O=le(k);return I?.lacking.has(O)?"recordTypeNotInTarget":I?.closed.has(O)?"heldBack":void 0},...n.sourceRequestsLeft!==void 0?{sourceRequestsLeft:n.sourceRequestsLeft}:{},...n.maxRows!==void 0?{maxRows:n.maxRows}:{},...m?{priceCurrencyWrittenIn:m}:{},...g.size>0?{averageBytes:g}:{},signal:this.sampling.signal,...n.onProgress?{onProgress:n.onProgress}:{}})}catch(R){throw R instanceof xr?new Rn("SAMPLE_TOO_LARGE",R.message):R instanceof Pr||this.isAborted?new Oe("Forge execution was aborted by user request. Remaining objects were not processed."):R}let{cut:b}=w;if(b.kind==="cannotFit"){let R=b.heaviest.map(x=>`${x.objectApiName} (${x.rows} records${x.whole?", copied whole":""})`).join(", "),k=b.noRoot?"the objects copied whole and the first root drawn with the records it brings":"the objects copied whole and the roots kept of each object",I=b.noRoot?"Leave objects out (--exclude-object)":"Keep no root of each object (--fit-floor 0), leave objects out (--exclude-object)",O=Jm[b.limitedBy],A=b.limitedBy==="storage"||b.limitedBy==="within";throw new cd(`No sample of the whole org fits: ${k} take ${b.rows} records, ${(b.storageBytes/1048576).toFixed(1)} MB, ${O.past}; the heaviest are ${R}. ${Zn} ${I}${O.more}.`,b.heaviest,{limitedBy:b.limitedBy,...A?{needMB:ih(b.storageBytes,"up"),budgetMB:ih(b.limitedBy==="storage"&&p.storageBytes!==void 0?p.storageBytes:p.budget.bytes,"down")}:{},heaviest:b.heaviest.map(x=>x.objectApiName)})}let S=Yf({...w,cut:b},i,p.budget);return Bp(n.keepAt,{sourceOrgId:s,fingerprint:n.fingerprint,drawnAt:new Date,drawnBy:o.dryRun?"dryRun":"run",sample:S,...w.newestByIds.length>0?{newestByIds:w.newestByIds}:{},ids:[...b.ids].map(([R,k])=>({objectApiName:R,ids:k})),counts:{personAccounts:Object.fromEntries(b.personAccounts),byThePlatform:b.byThePlatform.map(R=>({...R}))}})}async averageEmailBytes(e,t){let n=Wh(t,e.config.fieldExclusions[je]);if(n.length===0)return;let o=this.filterOf(e,je);try{let s=await this.readWholeOf(e,je,`SELECT Id, ${n.map(a=>a.name).join(", ")} FROM ${je}${o?` WHERE ${o}`:""} LIMIT ${Gw}`);if(s.length===0)return;let i=0;for(let a of s)for(let[d,c]of Object.entries(a))d!=="Id"&&typeof c=="string"&&(i+=Buffer.byteLength(c,"utf8"));return Math.ceil(i/s.length)}catch(s){nt.warn("[forge] the size of the emails could not be read before the sample was drawn: "+Y(s));return}}async runSampleOf(e,t){let{manifest:n}=t,o=new Set(n.sample.whole.map(d=>d.objectApiName)),s=new Set([...e.writtenObjects].filter(d=>!o.has(d)&&!e.config.referenceDataObjects.has(d))),i=new Map,a=new Map;for(let d of s){let c=new Set;for await(let p of t.ids(d))for(let f of p)c.add(le(f));i.set(d,c);let u=c.values().next().value?.slice(0,3)??(await this.objectInfoOf(e.sourceOrgId,d))?.keyPrefix??e.sourceKeyPrefixes.get(d);u&&a.set(d,u)}return{plan:t,report:{...n.sample,plan:t.place},drawn:s,ids:i,prefixes:a,counts:n.counts??{personAccounts:{},byThePlatform:[]},gone:new Map,changed:new Map,leftEmpty:new Map,reads:new Map,withoutStandard:new Set}}drawnObjectNamed(e,t,n){let o=t.filter(s=>e.drawn.has(s));if(o.length!==0)return t.length===1?o[0]:o.find(s=>{let i=e.prefixes.get(s);return i!==void 0&&n.startsWith(i)})}inThePlan(e,t,n){return e.ids.get(t)?.has(le(n))===!0}outsideTheSample(e,t,n){let o=e.sample;if(!o)return!1;let s=this.drawnObjectNamed(o,t,n);return s===void 0?!1:!this.inThePlan(o,s,n)||o.gone.get(s)?.has(le(n))===!0}secondPassOfTheSample(e){let t=e.sample;return t?{outsideTheSample:n=>{let o=n.sourceRefId,s=[...t.drawn].find(i=>{let a=t.prefixes.get(i);return a!==void 0&&o.startsWith(a)});return s!==void 0&&this.outsideTheSample(e,[s],o)},onLeftOutsideTheSample:(n,o)=>this.noteLeftOutsideTheSample(e,n,o)}:{}}noteLeftOutsideTheSample(e,t,n){let o=e.sample;if(!o)return;let s=o.leftEmpty.get(t)??new Map;s.set(n,(s.get(n)??0)+1),o.leftEmpty.set(t,s)}async countToWriteOfThePlan(e,t,n){let o=t.objectApiName,s=e.config.stream?.resumeAfter.get(o),i=n.ids.get(o)??new Set,a=s&&Pt.test(s.lastId)?s.lastId:void 0,d=R=>a===void 0||Tt(R,a)>0,c=0;if(!s?.done)for(let R of i)d(R)&&c++;let l=Math.min(c,await this.writtenBeforeOf(e,t,s)),u=e.standardPricebookId,p=o===Rt&&u&&i.has(le(u))&&d(u)&&!e.config.writtenBefore.has(u)?Math.min(1,c-l):0,f=Math.max(0,c-l-p),h=Math.min(f,n.counts.personAccounts[o]??0),g=0;o===he&&h>0&&await this.personAccountsInTarget(e)===!0&&(g=h);let m=n.counts.byThePlatform.find(R=>R.objectApiName===o);m&&(g+=Math.min(f-g,m.inPlan)),f-=g;let w=R=>n.report.dropped.filter(k=>k.objectApiName===o&&k.reason===R).reduce((k,I)=>k+I.rows,0),b={...l>0?{writtenBefore:l}:{},...p>0?{linkedToTarget:p}:{},...g>0?{byThePlatform:g}:{},...w("noParentInSource")>0?{noParentInSource:w("noParentInSource")}:{},...w("outsideFilter")>0?{outsideFilter:w("outsideFilter")}:{}},S=o===he&&g>0?0:h;return{read:c,counted:{rows:f,...S>0?{personAccounts:Math.min(S,f)}:{}},...Object.keys(b).length>0?{leftOut:b}:{}}}async readOfThePlan(e,t,n,o){let s=n.objectApiName,i=t.reads.get(s);if(i)return i;let a=await this.deps.describeFields(e.sourceOrgId,s),d=Kp({objectApiName:s,columns:Wt(a.filter(c=>!In(c)),e.config.fieldExclusions[s]),sourceRows:n.recordCount,planRows:o});return t.reads.set(s,d),d}planRowsAfter(e,t,n){let o=e.ids.get(t);if(!o)return 0;if(n===void 0)return o.size;let s=0;for(let i of o)Tt(i,n)>0&&s++;return s}async*pagesOfThePlanByIds(e,t,n,o,s,i=!1){let a=Me(n),d=this.filterOf(e,a),c=Math.max(1,Wc(a,Bc(o),d?`(${d})`:void 0));for await(let l of t.plan.ids(a,{...s!==void 0?{after:s}:{},size:c})){if(this.isAborted)return;let u=l.filter(h=>Pt.test(h));if(u.length===0)continue;let p=`SELECT ${o.join(", ")} FROM ${a} WHERE ${d?`(${d}) AND `:""}Id IN (${u.map(h=>`'${h}'`).join(", ")})`,f=await this.readWholeOf(e,a,p);if(f.sort((h,g)=>Tt(String(h.Id),String(g.Id))),i){let h=new Set(f.map(m=>le(String(m.Id)))),g=t.gone.get(a)??new Set;for(let m of u)h.has(le(m))||g.add(le(m));g.size>0&&t.gone.set(a,g)}yield f}}async rowsOfThePlan(e,t,n,o,s,i=!1){let a=[];for await(let d of this.pagesOfThePlanByIds(e,t,n,o,s,i))for(let c of d)a.push(c);return a}async*pagesOfThePlan(e,t,n,o,s){let i=n.objectApiName,a=o.lastId??o.resumeAfter,d=await this.readOfThePlan(e,t,n,this.planRowsAfter(t,i,a)),c=/^SELECT (.+?) FROM /.exec(s)?.[1]?.split(", ")??["Id"],l=d.by==="ids"?this.pagesOfThePlanByIds(e,t,i,c,a,!0):this.cursorKeptToThePlan(e,t,i,s,a);yield*ds(l,e.config.stream?.writeWindow??e.config.stream?.pageSize)}async*cursorKeptToThePlan(e,t,n,o,s){let i=t.ids.get(n)??new Set,a=new Set,d=_t(this.deps,e.sourceOrgId,o,void 0,()=>e.truncatedObjects.add(n),this.readOptionsOf(e,n));try{for await(let l of d){let u=l.filter(p=>{let f=le(String(p.Id));return i.has(f)?(a.add(f),!0):!1});u.length>0&&(yield u)}}finally{await d.return(void 0)}let c=t.gone.get(n)??new Set;for(let l of i)!a.has(l)&&(s===void 0||Tt(l,s)>0)&&c.add(l);c.size>0&&t.gone.set(n,c)}sampleResultOf(e){let t=e.sample;if(!t||e.simulated)return;let n=new Map(e.remapper.countsByObject().map(s=>[s.objectApiName,s])),o=t.report;return{seed:o.seed,draw:o.draw,share:o.share,sha256:o.plan.sha256,drawnAt:o.plan.drawnAt,drawnBy:o.plan.drawnBy,objects:o.objects.map(s=>{let i=n.get(s.objectApiName),a=i?i.created+(i.linked??0):0,d=e.store?.earlierRecordsOf(s.objectApiName)??0;return{...s,written:Math.min(s.kept,a+d),goneSinceTheSample:t.gone.get(s.objectApiName)?.size??0,changedSinceTheSample:t.changed.get(s.objectApiName)??0}}),...t.leftEmpty.size>0?{leftEmpty:[...t.leftEmpty].flatMap(([s,i])=>[...i].map(([a,d])=>({objectApiName:s,field:a,rows:d})))}:{}}}async countBeforeWrite(e,t){let{config:n}=e,o=n.beforeWrite;if(!o)return;let s=n.stream?.everything===!0,i=[],a=[],d=new Set,c=[],l=[];for(let I of t){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");let O=I.objectApiName;if(!I.included||!e.writtenObjects.has(O))continue;let A=s&&!this.streamsNode(I,e);if(n.referenceDataObjects.has(O)){A&&c.push({objectApiName:O,rows:await this.rowsOf(e,I)});continue}let{read:x,counted:j,leftOut:E,capped:$,partial:L}=e.sample?.drawn.has(O)?await this.countToWriteOfThePlan(e,I,e.sample):await this.countToWrite(e,I);e.counted.set(O,x),$&&a.push(O),L&&d.add(O),A&&!e.sample?.drawn.has(O)&&c.push({objectApiName:O,rows:x}),s&&l.push({node:I,read:x,whole:A}),i.push({objectApiName:O,rows:[],counted:j,...E?{leftOut:E}:{}})}let u=e.sample?.drawn.has(Ue)?void 0:i.find(I=>I.objectApiName===Ue),p=i.find(I=>I.objectApiName===Ce),f=u?await this.rolesThePlatformWritesOfTheTables(e,t,i,d):void 0;if(u&&f!==void 0&&f>0){let I=Math.min(f,u.counted.rows);u.counted={...u.counted,rows:u.counted.rows-I},u.leftOut={...u.leftOut,byThePlatform:I}}let h=p?.leftOut?.writtenBefore??0,g=u?this.rolesThePlatformMayWriteOfTheCounts(e,u.counted.rows,(f===void 0?p?.counted.rows??0:0)+h):0;if(u&&g>0&&(u.mayBeByThePlatform=f!==void 0?{rows:g,before:!0}:{rows:g}),this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");let m=s?await this.heldAtTheGate(e,t,i):void 0;m&&(m.requests+=await this.pricesReplacedAtTheGate(e,i));let w=s?await this.measureTheWholeOrg(e,i,c,l,m):void 0,b=w&&e.sample?{...w,sample:{report:e.sample.report,byThePlatform:e.sample.counts.byThePlatform}}:w;if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");let S=ys(n),R=n.dryRun&&!s?0:await this.readBackRequests(e,i),k=await o({objects:i,...S!==void 0&&a.length>0?{capped:{perObject:S,objects:a}}:{},...R>0?{readBack:R}:{},...b?{wholeOrg:b}:{},dryRun:n.dryRun});await this.afterTheGate(e,k,i)}async heldAtTheGate(e,t,n){let{config:o}=e,s=t.filter(h=>h.included&&e.writtenObjects.has(h.objectApiName)&&!o.referenceDataObjects.has(h.objectApiName)),i=new Map(s.map((h,g)=>[h.objectApiName,g])),a=new Map,d=new Map,c=new Map,l=ch,u=(h,g,m)=>{let w=a.get(h)??new Map;w.has(g)||l<=0||(w.set(g,m),a.set(h,w),l--)},p={requests:0,lookups:new Map},f=async(h,g)=>{let m=await this.idsUnder(e,h,g);return p.requests+=Math.max(1,Math.ceil((m?.length??0)/Ln)),m};for(let h of s){if(this.isAborted)break;let g=h.objectApiName;if(e.sample?.drawn.has(g))continue;if(l>0&&this.streamsNode(h,e)){let w=await this.recordTypesOfTable(e,h);if(w&&w.closed.length>0&&this.typesHeldRowByRow(e,w)){let b=new Set(w.lackingInSource);for(let[S,R]of[[w.closedInSource.filter(k=>!b.has(k)),d],[w.lackingInSource,c]]){let k=S.map(O=>`'${O}'`).join(", ");if(!k)continue;let I=a.get(g)?.size??0;for(let O of await f(g,`RecordTypeId IN (${k})`)??[])u(g,O,"held");R.set(g,(a.get(g)?.size??0)-I)}}}let m=await this.deps.describeFields(e.sourceOrgId,g).catch(()=>[]);for(let w of m){let[b]=w.referenceTo??[],S=b===void 0?void 0:i.get(b);if(!w.isReference||(w.referenceTo??[]).length!==1||S===void 0||S>=(i.get(g)??0)||!w.createable||(o.fieldExclusions[g]??[]).includes(w.name)||!Ze(g,w.name,w.nillable)||(p.lookups.set(g,(p.lookups.get(g)??0)+1),l<=0))continue;let R=Me(w.name),k=await f(g,`${R} != null AND ${R} NOT IN (SELECT Id FROM ${Me(b)})`);for(let x of k??[])u(g,x,{field:w.name,parentObject:b,reason:Xa(w.name,b)});let I=a.get(b);if(!I||I.size===0)continue;let O=[...I].filter(([,x])=>x==="held").map(([x])=>x),A=[...I].filter(([,x])=>x!=="held").map(([x])=>x);for(let[x,j]of[[O,"held"],[A,{field:w.name,parentObject:b,reason:uh(w.name,b)}]])for(let E of Cn(x)){if(l<=0)break;for(let $ of await f(g,`${R} IN (${E})`)??[])u(g,$,j)}}}for(let h of n){let g=a.get(h.objectApiName);if(!g||g.size===0)continue;let m=d.get(h.objectApiName)??0,w=c.get(h.objectApiName)??0,b=[...g.values()].filter(I=>I==="held").length,S=g.size-b,R=Math.max(0,h.counted.rows-g.size),k=h.counted.personAccounts;h.counted={rows:R,...k!==void 0&&Math.min(k,R)>0?{personAccounts:Math.min(k,R)}:{}},h.leftOut={...h.leftOut,...m>0?{heldBack:(h.leftOut?.heldBack??0)+m}:{},...w>0?{recordTypeNotInTarget:(h.leftOut?.recordTypeNotInTarget??0)+w}:{},...b-m-w>0?{withoutParent:b-m-w}:{},...S>0?{noParentInSource:S}:{}}}for(let h of a.values())for(let[g,m]of h)e.heldInTheOrg.set(g,m);return p}async pricesReplacedAtTheGate(e,t){let n=t.find(g=>g.objectApiName===We);if(!n||n.counted.rows<=0||!e.standardPricebookId||(e.counted.get(We)??0)>ch)return 0;let o=await this.deps.describeFields(e.sourceOrgId,We).catch(()=>[]);if(!o.some(g=>g.name===ut))return 0;let s=["Id",Ot,kt,ut,...o.some(g=>g.name==="IsActive")?["IsActive"]:[],...e.sellingModels&&o.some(g=>g.name===Bt)?[Bt]:[]],i=this.filterOf(e,We),a=e.sample,d;try{d=a?.drawn.has(We)?await this.rowsOfThePlan(e,a,We,s):await this.readWholeOf(e,We,`SELECT ${s.join(", ")} FROM ${We}`+(i?` WHERE ${i}`:""))}catch(g){return nt.warn(`[forge] the prices replaced in another currency could not be counted at the gate: ${Y(g)}`),1}let c=Math.max(1,Math.ceil(d.length/Ln)),l=e.currencies===void 0,u=d.filter(g=>!e.heldInTheOrg.has(String(g.Id))),p=await this.priceCurrencyInput(e,u,o),f=c+(l&&e.currencies!==void 0?tw:0);if(!p)return f;let h=Math.min(n.counted.rows,wa(p,[]).standsFor.size);return h===0||(n.counted={...n.counted,rows:n.counted.rows-h},n.leftOut={...n.leftOut,currencyReplaced:h}),f}async idsUnder(e,t,n){let o=e.config.stream?.resumeAfter.get(t),s=this.filterOf(e,t),i=[...s?[`(${s})`]:[],...o&&Pt.test(o.lastId)?[`Id > '${o.lastId}'`]:[],n];try{return(await this.readWholeOf(e,t,`SELECT Id FROM ${Me(t)} WHERE ${i.join(" AND ")}`)).map(d=>String(d.Id))}catch(a){nt.warn(`[forge] the ${t} records held back could not be counted at the gate: ${Y(a)}`);return}}async measureTheWholeOrg(e,t,n,o,s){let{config:i}=e,a=i.stream?.wholeReadBound,d=a===void 0?[]:n.filter(({rows:w})=>w>a).map(({objectApiName:w,rows:b})=>({objectApiName:w,rows:b,bound:a})),c=new Set(o.filter(w=>w.whole).map(w=>w.node.objectApiName)),{writes:l,restOnly:u}=await this.writesOfTheWholeOrg(e,t,c),p=o.find(({node:w})=>w.objectApiName===je&&w.included),f=t.find(w=>w.objectApiName===je)?.counted?.rows??0,h=p&&f>0?await this.emailBytesOf(e,p.node):void 0,g=i.files?await this.filesOfTheOrg(e,i.files.maxFileBytes):void 0,m=i.keepContactPoints?0:await this.phoneNumbersPastTheFiction(e,o);return{writes:l,...u?{restOnly:u}:{},...h!==void 0?{emailTextBytes:h}:{},...i.files?{files:g??{unmeasured:!0}}:{},sourceReads:await this.sourceReadsOf(e,o,n,g)+nw(o,s?.lookups),...s&&s.requests>0?{heldReads:s.requests}:{},...d.length>0?{readWholeOver:d}:{},...m>0?{contactPointsBlanked:m}:{}}}async writesOfTheWholeOrg(e,t,n){let{config:o}=e,s=o.writeApi==="auto"&&this.deps.bulkWriteRecords!==void 0,i=e.bulk?.restOnly??new Set;if(s&&!e.bulk){let c=await this.deps.duplicateRuleObjects?.(e.targetOrgId).catch(()=>{});i=new Set([...Uo,...c??_i])}let a=o.stream?.writeWindow??o.stream?.pageSize??Ln,d=t.map(({objectApiName:c,counted:l})=>{let u=Math.max(0,l?.rows??0),p=s&&!i.has(c),f=n.has(c)?[u]:[...Array.from({length:Math.floor(u/a)},()=>a),...u%a>0?[u%a]:[]],h=0,g=0;for(let m of p?f:[])for(let w=0;w<m;w+=vr){let b=Math.min(vr,m-w);b<2e3||(h++,g+=b)}return{objectApiName:c,rows:u,jobs:h,jobRows:g,restRows:u-g}});return s?{writes:d,restOnly:i}:{writes:d}}async sourceReadsOf(e,t,n,o){let s=c=>Math.max(1,Math.ceil(Math.max(0,c)/Ln)),i=new Map;for(let{node:c,read:l}of t)i.set(c.objectApiName,l);for(let{objectApiName:c,rows:l}of n)i.set(c,l);let a=0;for(let[c,l]of i){let u=t.find(p=>p.node.objectApiName===c)?.node;a+=e.sample?.drawn.has(c)&&u?(await this.readOfThePlan(e,e.sample,u,l)).requests:s(l)}let d=t.find(({node:c})=>c.objectApiName===je);if(d&&d.read>0&&t.some(({node:c})=>c.objectApiName===st)){let c=await this.countOf(e,je,"ActivityId != null");a+=s(Math.min(c??d.read,d.read))}if(e.config.files){let c=o?.count??0;a+=id.length+Math.ceil(c/Ln),a+=Math.ceil(c/sd)+c}return a}async rowsOf(e,t){return await this.countOf(e,t.objectApiName)??t.recordCount}async countOf(e,t,n){let o=this.deps.countRecords;if(!o)return;let s=this.filterOf(e,t),i=[...s?[`(${s})`]:[],...n?[n]:[]],a=i.length>0?` WHERE ${i.join(" AND ")}`:"",d=`SELECT COUNT() FROM ${Me(t)}${a}`,c=this.readOptionsOf(e,t);try{return await(c?o(e.sourceOrgId,d,c):o(e.sourceOrgId,d))}catch{return}}async emailBytesOf(e,t){let n=t.objectApiName;try{let o=await this.deps.describeFields(e.sourceOrgId,n),s=Wh(o,e.config.fieldExclusions[n]);if(s.length===0)return 0;let i=e.sample;if(i?.drawn.has(n)){let h=0,g=await this.rowsOfThePlan(e,i,n,["Id",...s.map(m=>m.name)],e.config.stream?.resumeAfter.get(n)?.lastId);for(let m of g)for(let[w,b]of Object.entries(m))w!=="Id"&&typeof b=="string"&&(h+=Buffer.byteLength(b,"utf8"));return h}let a=e.config.stream?.resumeAfter.get(n),d=this.filterOf(e,n),c=[...d?[`(${d})`]:[],...a&&Pt.test(a.lastId)?[`Id > '${a.lastId}'`]:[]],l=c.length>0?` WHERE ${c.join(" AND ")}`:"",u=["Id",...s.map(h=>h.name)].join(", "),p=0,f=_t(this.deps,e.sourceOrgId,`SELECT ${u} FROM ${Me(n)}${l} ORDER BY Id`,e.config.stream?.pageSize,void 0,this.readOptionsOf(e,n));try{for await(let h of f){for(let g of h)for(let[m,w]of Object.entries(g))m!=="Id"&&typeof w=="string"&&(p+=Buffer.byteLength(w,"utf8"));if(this.isAborted)break}}finally{await f.return(void 0)}return p}catch(o){nt.warn("[forge] the size of the emails could not be read \u2014 measured by their count: "+Y(o));return}}async filesOfTheOrg(e,t){let n=0,o=0,s=0;for(let{object:i,size:a,where:d}of id){let c=[d,`${a} <= ${t}`].filter(Boolean).join(" AND "),l=[d,`${a} > ${t}`].filter(Boolean).join(" AND "),u=await this.sumOfFiles(e,i,a,c);if(!u)return;n+=u.bytes,o+=u.count;let p=await this.deps.countRecords?.(e.sourceOrgId,`SELECT COUNT() FROM ${i} WHERE ${l}`).catch(()=>{});s+=p??0}return{bytes:n,count:o,overCeiling:s}}async sumOfFiles(e,t,n,o){try{let[s]=await this.deps.queryRecords(e.sourceOrgId,`SELECT SUM(${n}) total, COUNT(Id) n FROM ${t} WHERE ${o}`),i=Number(s?.total??0),a=Number(s?.n??0);if(Number.isFinite(i)&&Number.isFinite(a))return{bytes:i,count:a}}catch{}try{let s=0,i=0,a=_t(this.deps,e.sourceOrgId,`SELECT Id, ${n} FROM ${t} WHERE ${o} ORDER BY Id`,e.config.stream?.pageSize);try{for await(let d of a){for(let c of d){let l=c[n];s+=typeof l=="number"&&Number.isFinite(l)?l:0,i++}if(this.isAborted)break}}finally{await a.return(void 0)}return{bytes:s,count:i}}catch(s){nt.warn(`[forge] the files of ${t} could not be measured: ${Y(s)}`);return}}async phoneNumbersPastTheFiction(e,t){let n=0;for(let{node:o,read:s}of t){if(s===0||this.isAborted)continue;let i=o.objectApiName,a=new Set(e.config.fieldExclusions[i]??[]),c=(await this.deps.describeFields(e.sourceOrgId,i).catch(()=>[])).filter(l=>l.createable&&!a.has(l.name));for(let l of ua(c)){if(l.kind!=="phone")continue;let u=await this.countOf(e,i,`${Me(l.name)} != null`);n+=Math.min(u??s,s)}}return Math.max(0,n-Qu)}async countToWrite(e,t){let n=t.objectApiName,o=this.streamsNode(t,e),s=o?e.config.stream?.resumeAfter.get(n):void 0,i=this.filterOf(e,n),a=this.readOptionsOf(e,n),d=this.deps.countRecords,c=async V=>{if(!d)return;let q=[...i?[`(${i})`]:[],...V?[V]:[],...s&&Pt.test(s.lastId)?[`Id > '${s.lastId}'`]:[]],me=q.length>0?` WHERE ${q.join(" AND ")}`:"",de=`SELECT COUNT() FROM ${Me(n)}${me}`;try{return await(a?d(e.sourceOrgId,de,a):d(e.sourceOrgId,de))}catch{return}},l=this.readBound(e,t),u=l===void 0?void 0:Math.max(0,l-(s?.read??0)),p=await c(),f=p??t.recordCount,h=u===void 0?f:Math.min(f,u),g=ys(e.config),m=g===void 0?void 0:Math.max(0,g-(s?.read??0)),w=m!==void 0&&u===m&&f>m,b=o?await this.recordTypesOfTable(e,t):void 0;if(b&&b.closed.length>0&&!this.typesHeldRowByRow(e,b))return{read:h,counted:{rows:0},...h>0?{leftOut:fh(b.closed,h)}:{}};let S=Math.min(h,await this.writtenBeforeOf(e,t,s)),R=n===Rt?Math.min(h-S,await this.standardBookOfTheTable(e,c)):0,k=h-S-R,I=S>0||R>0?{...S>0?{writtenBefore:S}:{},...R>0?{linkedToTarget:R}:{}}:void 0,O=V=>V===void 0?{rows:k}:{rows:k,personAccounts:V},A=h<f,x=V=>({read:h,counted:O(V),...I?{leftOut:I}:{},...w?{capped:!0}:{},...A?{partial:!0}:{}});if(n!==ye&&n!==he||!(await this.deps.describeFields(e.sourceOrgId,n).catch(()=>[])).some(V=>V.name==="IsPersonAccount"))return x();let E=await c("IsPersonAccount = true"),$=E===void 0?void 0:Math.min(E,k);if(n!==he||E===void 0||p===void 0)return x($);let L=await this.personContactsTakenAsBusinessAtTheGate(e,c);if(L===void 0)return x($);let Q=Math.max(0,E-L-(p-h)-S);if(Q===0)return x($);let G=($??0)-Q;return{read:h,counted:{rows:k-Q,...G>0?{personAccounts:G}:{}},leftOut:{...I,byThePlatform:Q},...w?{capped:!0}:{},...A?{partial:!0}:{}}}async standardBookOfTheTable(e,t){let n=e.standardPricebookId;return!n||!Pt.test(n)||e.config.writtenBefore.has(n)?0:this.filterOf(e,Rt)?Math.min(1,await t(`Id = '${n}'`)??0):1}async personContactsTakenAsBusinessAtTheGate(e,t){if(await this.personAccountsInTarget(e)!==!0)return;let n=await this.personRecordTypesInTarget(e);if(!n)return 0;let{config:o}=e;if(!((await this.deps.describeFields(e.sourceOrgId,ye).catch(()=>[])).some(d=>d.name==="RecordTypeId"&&d.createable)&&!(o.fieldExclusions[ye]??[]).includes("RecordTypeId")&&o.fieldMappings[ye]?.RecordTypeId===void 0)){let d=fa((await this.objectInfoOf(e.targetOrgId,ye))?.recordTypes);return d!==void 0&&!n.has(d.slice(0,15))?void 0:0}let a=(o.recordTypeMappings??[]).filter(d=>!n.has(d.targetId.slice(0,15))).map(d=>d.sourceId);if(a.length===0)return 0;if(a.every(d=>Pt.test(d)))return t(`IsPersonAccount = true AND Account.RecordTypeId IN (${a.map(d=>`'${d}'`).join(", ")})`)}async idsTheTargetLacks(e,t,n,o){return mp({lookups:t.filter(s=>s.isReference&&o(s.name)),rows:n,ownerMappings:e.config.ownerMappings,outsideTheRun:s=>this.isOutsideTheRun(e,s),mapped:s=>e.remapper.get(s)!==void 0,known:e.targetHolds,refused:e.targetReadsRefused,inactive:e.inactiveUsers,query:s=>this.deps.queryRecords(e.targetOrgId,s),neverCopied:s=>gs(e,s)})}async inactiveOwnersToLeaveOut(e,t,n){if(!n||e.inactiveUsers.size===0)return;let o=wp(t,e.inactiveUsers,e.config.ownerMappings);if(o.size!==0&&!await e.writesInactiveOwners())return o}isOutsideTheRun(e,t){return!e.writtenObjects.has(t)&&!e.failedObjects.has(t)&&!e.notInTarget.has(t)}noteLookupsOutsideTheRun(e,t,n,o){let s=nd(new Map,o);if(s.size===0)return;let i=e.lookupsOutsideTheRun.get(t)??new Map;for(let[a,d]of s){let c=n.find(u=>u.name===a)?.referenceTo?.[0]??a,l=i.get(a)??{parent:c,rows:0};l.rows+=d,i.set(a,l)}e.lookupsOutsideTheRun.set(t,i)}async rowsWhoseParentTheTargetLacks(e,t,n,o,s){let i=new Map,{config:a}=t;if(a.referenceFallback!=="keep"||a.expandOrphanParents)return i;let d=n.filter(l=>{let u=l.referenceTo??[];return l.isReference&&s(l.name)&&u.length===1&&!gs(t,u[0])&&this.isOutsideTheRun(t,u[0])&&Ze(e.objectApiName,l.name,l.nillable)});if(d.length===0||o.length===0)return i;let c=await this.idsTheTargetLacks(t,d,o,()=>!0);return c.size===0||o.forEach((l,u)=>{for(let p of d){let f=l[p.name];if(!(typeof f!="string"||!c.has(f)||t.remapper.get(f))){i.set(u,{field:p.name,parentObject:(p.referenceTo??[])[0],notInTarget:!0});return}}}),i}rowsOfClosedTypes(e,t,n,o){let{config:s}=e,i=new Map(o.map(c=>[c.recordTypeId,c])),a=n.map(c=>({RecordTypeId:s.recordTypeDecisions.get(String(c.RecordTypeId))?.to===null?void 0:c.RecordTypeId}));e.recordTypeMapper&&s.recordTypeMappings&&(a=e.recordTypeMapper.apply(a,s.recordTypeMappings));let d=new Map;return n.forEach((c,l)=>{let u=a[l]?.RecordTypeId,p=typeof u=="string"?i.get(u):void 0;p&&d.set(c,{field:"RecordTypeId",parentObject:p.developerName,recordType:{...p,objectApiName:t.objectApiName}})}),d}async rowsHeldInTheWholeOrg(e,t,n,o,s){let i=new Map,a=new Map;if(t.config.stream?.everything!==!0||o.length===0)return{held:i,aside:a};let d=sw(t,e.objectApiName,n,s),c=new Set,l=new Map;o.forEach((u,p)=>{let f=t.heldInTheOrg.get(String(u.Id));if(f!==void 0&&f!=="held"){a.set(p,f);return}if(t.sample?.withoutStandard.has(le(String(u.Id)))){i.set(p,{field:kt,parentObject:We,reason:qw}),c.add(p);return}for(let{field:h,parent:g}of d){let m=u[h];if(typeof m!="string"||m===""||t.remapper.get(m))continue;let w=t.sample;if(w?.drawn.has(g)){this.inThePlan(w,g,m)?w.gone.get(g)?.has(le(m))?a.set(p,{field:h,parentObject:g,reason:ow(h,g)}):i.set(p,{field:h,parentObject:g}):(i.set(p,{field:h,parentObject:g,reason:rw(h,g)}),c.add(p));return}let b=t.heldInTheOrg.get(m);if(b==="held"){i.set(p,{field:h,parentObject:g});return}if(b){let R=b===lh?Xa(h,g):uh(h,g);a.set(p,{field:h,parentObject:g,reason:R});return}let S=l.get(g)??new Map;S.set(m,[...S.get(m)??[],{index:p,field:h}]),l.set(g,S)}});for(let[u,p]of l){let f=await this.idsInTheSource(t,u,[...p.keys()]);for(let[h,g]of p){let m=f===void 0||f.has(h.slice(0,15));m||t.heldInTheOrg.set(h,lh);for(let{index:w,field:b}of g)i.has(w)||a.has(w)||(m?i.set(w,{field:b,parentObject:u}):a.set(w,{field:b,parentObject:u,reason:Xa(b,u)}))}}for(let u of i.keys())a.delete(u);if(c.size>0&&t.sample){let u=e.objectApiName;t.sample.changed.set(u,(t.sample.changed.get(u)??0)+c.size)}return{held:i,aside:a}}async idsInTheSource(e,t,n){let o=new Set;try{for(let s of Cn(n)){let i=await this.deps.queryRecords(e.sourceOrgId,`SELECT Id FROM ${Me(t)} WHERE Id IN (${s})`);for(let a of i)o.add(String(a.Id).slice(0,15))}return o}catch(s){nt.warn(`[forge] whether the source holds the ${t} records named could not be read: ${Y(s)}`);return}}async writtenBeforeOf(e,t,n){let{writtenBefore:o}=e.config,s=t.objectApiName,i=e.store?.earlierRecordsOf(s,n!==void 0)??0;if(e.store&&i>0)return i;if(o.size===0||n)return 0;let a=(await this.objectInfoOf(e.sourceOrgId,s))?.keyPrefix??e.sourceKeyPrefixes.get(s);if(!a)return 0;let d=[];for(let f of o.keys())f.startsWith(a)&&d.push(f);let c=e.config.objectSoqlFilters?.[s],l=this.deps.countRecords;if(!c||d.length===0||!l)return d.length;let u=this.readOptionsOf(e,s),p=this.filterOf(e,s)??c;try{let f=0;for(let h of Cn(d)){let g=`SELECT COUNT() FROM ${Me(s)} WHERE (${p}) AND Id IN (${h})`;f+=await(u?l(e.sourceOrgId,g,u):l(e.sourceOrgId,g))}return f}catch{return d.length}}async streamNode(e,t,n){let o=e.objectApiName,s=o===je&&t.emailsInTwoPasses&&!n;s&&(t.emailsFirstPassRan=!0);let i=t.config.stream?.resumeAfter.get(qo(o,n?.name)),a={ended:!1,taken:0,read:i?.read??0,...i?{resumeAfter:i.lastId,lastId:i.lastId}:{},carry:Wm(),...n?{pass:n}:{}},d=n?void 0:this.readBound(t,e);if(i?.done||d!==void 0&&a.read>=d)return;let c=n?void 0:await this.recordTypesOfTable(t,e);if(c&&c.closed.length>0&&!this.typesHeldRowByRow(t,c)){let p=d===void 0?c.rows:Math.min(c.rows,d-a.read);this.holdBackTableForRecordTypes(e,t,c,p);return}let l=n?n.expected:t.counted.get(o)??sh(e,d);a.carry.rowsLeft=n?()=>Math.max(0,l-a.carry.rows):()=>Math.max(0,l-(a.read-(i?.read??0)));let u=n?.stopped??`Stopped ${e.objectApiName}`;t.cursors.set(o,a);try{let p=n?void 0:await this.keysOfTheTable(t,e,a);for(p&&(a.carry.tableKeys=p);;){if(this.isAborted)throw a.carry.pages>0&&a.carry.rowsLeft()>0?this.stopStreamedNode(e,t,a.carry,0,u):a.carry.pages>0&&!(n&&a.carry.rows===0)&&this.endStreamedNode(e,t,a.carry,this.endOfAStreamedNode(t,o,n)),new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");if(!await this.readNode(e,t,!1,!0))break;let f=n?t.preread.get(o)?.records??[]:void 0;if(await this.writeNode(e,t,f,a.carry),o===ye&&await this.mapContactsOfPersonAccounts(t),s&&await this.linkTasksOfTheEmailsWritten(t),await this.tellPage(t,e,a),a.ended)break}}finally{t.cursors.delete(o),await a.pages?.return(void 0)}t.store&&a.ended&&!a.failed&&a.lastId!==void 0&&t.store.checkpoint(o,{lastId:a.lastId,read:a.read,done:!0},n?.name),a.carry.pages>0&&!a.failed&&!(n&&a.carry.rows===0)&&this.endStreamedNode(e,t,a.carry,this.endOfAStreamedNode(t,o,n)),this.releaseRows(t,o)}endOfAStreamedNode(e,t,n){if(n)return{...n.end,again:!0};if(t!==je||!e.emailsInTwoPasses)return{};let o=e.emailsLeftForTheirTask;return{say:this.endOfTheEmails(e,!1),...o>0?{note:`, ${hs(o)}`}:{}}}recordTypesOfTable(e,t){let n=t.objectApiName,o=e.tableRecordTypes.get(n);return o||(o=this.countRecordTypesOfTable(e,t),e.tableRecordTypes.set(n,o)),o}async countRecordTypesOfTable(e,t){let{config:n,sourceOrgId:o,targetOrgId:s}=e,i=t.objectApiName,a=await this.targetObjectInfoOf(e,i),d={closed:[],rows:0,target:a,closedInSource:[],lackingInSource:[]};if(!a||!a.recordTypes.some(c=>!c.available&&!c.master)&&!await this.mayLackRecordTypes(e,i,a)||(n.fieldExclusions[i]??[]).includes("RecordTypeId")||n.fieldMappings[i]?.RecordTypeId)return d;try{let[c,l]=await Promise.all([this.deps.describeFields(o,i),tn(this.deps.describeFields,s,i).catch(()=>{})]);if(!c.some(j=>j.name==="RecordTypeId"&&j.createable)||l&&!l.creatable.has("RecordTypeId"))return d;let p=n.stream?.resumeAfter.get(i),f=this.filterOf(e,i),h=[...f?[`(${f})`]:[],...p&&Pt.test(p.lastId)?[`Id > '${p.lastId}'`]:[]],g=h.length>0?` WHERE ${h.join(" AND ")}`:"",m=`FROM ${Me(i)}${g}`,w=await this.readWholeOf(e,i,`SELECT RecordTypeId, COUNT(Id) n ${m} GROUP BY RecordTypeId`),b=w.reduce((j,E)=>j+(typeof E.n=="number"&&E.n>0?E.n:0),0),S=nl(w),R=async j=>[...tl(i,j,a.recordTypes),...await this.typesTheTargetLacks(e,i,j,a)],k=await R(this.recordTypesAsSent(e,S)),I=j=>{let E=new Set(j.map($=>$.recordTypeId));return[...S.keys()].filter($=>[...this.recordTypesAsSent(e,[[$,1]]).keys()].some(L=>E.has(L)))},O=(j,E)=>({closed:j,rows:E,target:a,closedInSource:I(j),lackingInSource:I(j.filter($=>$.unmapped))}),A=this.readBound(e,t),x=A===void 0?void 0:Math.max(0,A-(p?.read??0));if(k.length>0&&x!==void 0&&b>x){let j=await this.recordTypesOfTheRowsRead(e,i,m,x);if(j)return O(await R(this.recordTypesAsSent(e,j.counts)),j.rows)}return O(k,b)}catch{return}}recordTypesAsSent(e,t){let{config:n}=e,o=new Map;for(let[s,i]of t){if(n.recordTypeDecisions.get(s)?.to===null)continue;let a=s;e.recordTypeMapper&&n.recordTypeMappings&&(a=e.recordTypeMapper.apply([{RecordTypeId:s}],n.recordTypeMappings)[0]?.RecordTypeId),typeof a=="string"&&o.set(a,(o.get(a)??0)+i)}return o}async typesTheTargetLacks(e,t,n,o){if(!e.recordTypeMapper||!e.config.recordTypeMappings)return[];if(!o||o.recordTypes.length===0)return[];if(Ao(t,n,o.recordTypes,[]).length===0)return[];let i=await this.sourceRecordTypesOf(e,t);return e.gaps?.knowRecordTypes(t,"source",i),Ao(t,n,o.recordTypes,i)}async mayLackRecordTypes(e,t,n){if(!e.recordTypeMapper||!e.config.recordTypeMappings||n.recordTypes.length===0)return!1;let s=((await this.objectInfoOf(e.sourceOrgId,t))?.recordTypes??[]).filter(a=>!a.master);if(s.length===0)return!1;let i=this.recordTypesAsSent(e,s.map(a=>[a.recordTypeId,1]));return Ao(t,i,n.recordTypes,[]).length>0}async recordTypesOfTheRowsRead(e,t,n,o){let s=!1;try{let i=await this.readWholeOf(e,t,`SELECT RecordTypeId ${n} ORDER BY Id LIMIT ${o}`,()=>{s=!0});if(s)return;let a=new Map;for(let d of i){let c=d.RecordTypeId;typeof c=="string"&&c!==""&&a.set(c,(a.get(c)??0)+1)}return{counts:a,rows:i.length}}catch{return}}typesHeldRowByRow(e,t){if(e.config.stream?.everything!==!0)return!1;let n=t.closed.reduce((o,s)=>o+s.recordCount,0);return t.rows>n}holdBackTableForRecordTypes(e,t,n,o){let s=e.objectApiName;t.gaps?.knowRecordTypes(s,"target",n.target?.recordTypes??[]);for(let i of n.closed)t.gaps?.add(hh(i,n.target));t.failedObjects.add(s),t.failedCount+=o,t.errors.push({objectApiName:s,stage:"scope",failedCount:o,attemptedCount:0,samples:n.closed.map(i=>({recordSummary:`RecordType=${i.developerName} (${i.recordCount} record${i.recordCount===1?"":"s"})`,messages:[vo(i)]}))}),t.onProgress({objectName:s,status:"error",progress:100,message:`${On(s,o,Gt(t,s))}: `+n.closed.map(jo).join(" ")+" Objects that cannot be written without it will be skipped."})}async nextPage(e,t,n,o,s){if(n.ended)return[];let i=e.sample?.drawn.has(t.objectApiName)?e.sample:void 0,a=p=>i?this.pagesOfThePlan(e,i,t,n,p):_t(this.deps,e.sourceOrgId,p,e.config.stream?.writeWindow??e.config.stream?.pageSize,()=>e.truncatedObjects.add(t.objectApiName),this.readOptionsOf(e,t.objectApiName));n.pages??=a(o);let d=e.config.stream?.everything===!0?Qa:0,c;for(let p=0;;p++)try{c=await n.pages.next();break}catch(f){let h=Ih(f);if(!h&&!Eh(f)||p>=d||this.isAborted)throw f;let g=n.lastId===void 0?o:s?.(n.lastId);if(g===void 0)throw f;h||await $h(nh*2**p),nt.warn(`[forge] ${t.objectApiName}: the source ${h?"let its cursor expire":"did not answer"} after ${n.read} row(s) \u2014 reading on from the last one (${p+1}/${d}): `+Y(f)),n.pages=a(g)}if(c.done)return n.ended=!0,[];n.taken++;let l=c.value;n.room!==void 0&&(l.length>n.room&&(l=l.slice(0,n.room),n.ended=!0,(n.cutBy==="cap"?e.cappedObjects:e.truncatedObjects).add(t.objectApiName)),n.room-=l.length),n.read+=l.length;let u=l[l.length-1]?.Id;return typeof u=="string"&&(n.lastId=u),l}async readWhole(e,t,n){let o=e.sample;if(o?.drawn.has(t)){let d=/^SELECT (.+?) FROM /.exec(n)?.[1]?.split(", ")??["Id"];return this.rowsOfThePlan(e,o,t,d,void 0,!0)}let s=!1,i=()=>{s=!0,e.truncatedObjects.add(t)},a=await this.readWholeRows(e,n,i);if(s&&e.config.stream?.everything===!0)throw new ks(t,e.config.stream.wholeReadBound);return a}async readWholeRows(e,t,n){let{stream:o}=e.config,s=o?.pageSize;if(s===void 0||!this.deps.queryPages)return this.deps.queryRecords(e.sourceOrgId,t,n);let i=(o?.everything===!0?o.wholeReadBound:o?.ceiling)??5e4,a=[],d=_t(this.deps,e.sourceOrgId,t,s);try{for await(let c of d)if(a.push(...c),a.length>i)return n(),a.slice(0,i)}finally{await d.return(void 0)}return a}pagedLimit(e,t){let n=ys(e.config),o=n===void 0?void 0:n-t.read,s=e.config.stream?.ceiling,i=s===void 0?void 0:s-t.read;if(i===void 0&&o===void 0)return;let a=i!==void 0&&(o===void 0||i<o);return t.room=Math.max(0,(a?i:o)??0),t.cutBy=a?"ceiling":"cap",Math.max(1,t.room)}async tellPage(e,t,n){e.store&&n.lastId!==void 0&&e.store.checkpoint(t.objectApiName,{lastId:n.lastId,read:n.read},n.pass?.name);let o=e.config.stream?.onPage;if(!o)return;let s=e.preread.get(t.objectApiName)?.records??[],i=e.simulated?[]:s.flatMap(a=>{let d=a.Id;if(typeof d!="string"||!e.remapper.isCreated(d))return[];let c=e.remapper.get(d);return c?[{sourceId:d,targetId:c}]:[]});await o({objectApiName:t.objectApiName,...n.lastId!==void 0&&!n.pass?{checkpoint:{lastId:n.lastId,read:n.read}}:{},created:i})}endStreamedNode(e,t,n,o={}){let{config:s}=t,i=o.say??t.onProgress,a=e.objectApiName;this.mergePageReports(t,a,n),this.saySentOnTheirOwn(t,n.sentOnTheirOwn,n.onTheirOwnWhy);let d=o.again?[]:Gt(t,a),c=o.again?void 0:t.heldForExclusions.get(a),l=[...Ya(n),...d],u=Wn(l),p=A=>{t.failedObjects.add(a),i({objectName:a,status:"error",progress:100,message:A})};if(n.heldWhole!==void 0){p(`${On(a,n.heldWholeRows,d)}: ${n.heldWhole} Objects that cannot be written without it will be skipped.`);return}if(n.rows===0&&c&&c.size>0){p(Mr(a,c));return}let f=Zf(n);if(n.personContactsUnlinked>0&&n.withTheirAccount===0&&n.sent===0&&n.writtenBefore===0&&n.withoutParent===0){p(`${On(a,n.personContactsUnlinked,d)}: every record is a person account's contact, which the platform writes with its account, and the run has none of them in the target. Objects that cannot be written without it will be skipped.`);return}if(f===0&&n.failed===0&&n.sent===0&&n.withoutParent>0){p(`${On(a,n.withoutParent,d)}: every record points at a parent this run did not write. Objects that cannot be written without it will be skipped.`);return}let h=f+n.failed,g=h>0?n.failed/h:0,m=n.failed>0&&n.alreadyExists===n.failed,w=n.failed>0&&!m&&(f===0||g>.5),b=No(n.picklists.list())+Oo(n.currencies.list())+ed(n.lookupsNotCarried)+rd(n.ownersInactive)+td(n.lookupsOutsideTheRun)+ad(t,a),S=zo(n.writtenWithoutFields),R=Mh(t,a),k=rh(t,a),I=bh(n.sentOnTheirOwn);if(w){f>0&&t.failedInPart.add(a),p(f===0?`Failed all ${a} records: ${n.failed+u} failed${rn(l)}${I}${b}${k}`:`${n.failed+u}/${h+u} ${a} records failed (>50%)${rn(l)}${I}${b}${S}${R}${k}`+gh);return}let O=eh(n);i({objectName:a,status:"done",progress:100,message:`${o.label??`${s.dryRun?"Simulated":"Completed"} ${a}`}: ${Za(s,n,l)}${o.note??""}${I}${O}${b}${S}${R}${bs(t,a)}${k}`})}stopStreamedNode(e,t,n,o,s){let i=e.objectApiName,a=o+n.rowsLeft();od(t,i,a),this.mergePageReports(t,i,n),this.saySentOnTheirOwn(t,n.sentOnTheirOwn,n.onTheirOwnWhy);let d=[...Ya(n),...Gt(t,i)],c=Zf(n),l=c+n.failed,u=n.failed>0&&n.alreadyExists!==n.failed&&(c===0||n.failed/l>.5);u&&t.failedObjects.add(i),u&&c>0&&t.failedInPart.add(i),t.onProgress({objectName:i,status:u?"error":"stopped",progress:100,message:`${s}: ${Za(t.config,n,d)}, ${a} not sent${bh(n.sentOnTheirOwn)}${eh(n)}${No(n.picklists.list())}${Oo(n.currencies.list())}${ed(n.lookupsNotCarried)}${rd(n.ownersInactive)}${td(n.lookupsOutsideTheRun)}${ad(t,i)}${zo(n.writtenWithoutFields)}${bs(t,i)}`})}mergePageReports(e,t,n){if(n.withoutParent>0&&!n.withoutParentSaid){let i={objectApiName:t,stage:"scope",failedCount:n.withoutParent,attemptedCount:0,samples:ld(n.withoutParentGroups,e.failedObjects)},a=e.errors.findIndex(d=>d.objectApiName===t&&d.stage==="insert");a===-1?e.errors.push(i):e.errors.splice(a,0,i),n.withoutParentSaid=!0}let o=e.errors.filter(i=>i.objectApiName===t&&i.stage==="insert");if(o.length>0){let[i]=o,a={...i,failedCount:o.reduce((l,u)=>l+u.failedCount,0),attemptedCount:n.succeeded+n.updated+n.linked+n.failed,samples:o.flatMap(l=>l.samples).slice(0,ww)},d=e.errors.indexOf(i),c=e.errors.filter(l=>!o.includes(l));c.splice(d,0,a),e.errors.splice(0,e.errors.length,...c)}let s=e.existingRecords.filter(i=>i.objectApiName===t);if(s.length>1){let i=s.reduce((l,u)=>l+(u.linkedToCreated??0),0),a={objectApiName:t,linked:s.reduce((l,u)=>l+u.linked,0),...i>0?{linkedToCreated:i}:{},unidentified:s.reduce((l,u)=>l+u.unidentified,0)},d=e.existingRecords.indexOf(s[0]),c=e.existingRecords.filter(l=>!s.includes(l));c.splice(d,0,a),e.existingRecords.splice(0,e.existingRecords.length,...c)}}async startAsDrafts(e,t,n){let o=new Map;if(e.config.dryRun)return o;let s=await this.lifecycleOf(e,t);return s&&n.forEach((i,a)=>{let d=po(i.Status,s);d&&(o.set(a,String(i.Status)),i.Status=d)}),o}async oweStatusesFoundAfterStop(e,t,n){let{store:o}=e;if(!o)return;let s=n.filter(a=>{let d=a.Id;return typeof d=="string"&&o.wasFoundAfterStop(d)});if(s.length===0)return;let i=await this.lifecycleOf(e,t);if(i)for(let a of s){if(!po(a.Status,i))continue;let d=e.config.writtenBefore.get(String(a.Id));d&&this.oweStatus(e,t,d,String(a.Status))}}async lifecycleOf(e,t){let n=$c[t];if(!n||!this.deps.updateRecords)return;let o=e.lifecycles.get(t);return o||(o=xc(s=>this.deps.queryRecords(e.targetOrgId,s),n),e.lifecycles.set(t,o)),o}async notePastDraft(e,t,n){if(!([...e.statusChildren.values()].some(({parent:a})=>a===t)||e.config.excludedObjects.size>0&&fr[t]!==void 0))return;let s=await this.lifecycleOf(e,t);if(!s)return;let i=e.pastDraft.get(t)??new Map;for(let a of n){let d=a.Id;typeof d=="string"&&po(a.Status,s)&&i.set(d,String(a.Status))}e.pastDraft.set(t,i)}async restoreStatuses(e){let t=this.deps.updateRecords;if(t&&e.store){await this.restoreStatusesFromTheJournal(e,t);return}if(!t||e.deferredStatuses.length===0)return;let n=e.deferredStatuses.splice(0,e.deferredStatuses.length);for(let[o,s]of Bh(n)){let i=0,a=[];for(let d=0;d<s.length;d+=Go.rest){let c=s.slice(d,d+Go.rest),l;try{l=await t(e.targetOrgId,o,c.map(({id:u,status:p})=>({Id:u,Status:p})))}catch(u){l=c.map(({id:p})=>({id:p,success:!1,errors:[Y(u)]}))}c.forEach(({id:u,status:p},f)=>{let h=l[f];h?.success||(i++,a.length<3&&a.push({recordSummary:`${o} ${u} Status=${p}`,messages:h?.errors??["No result returned for the status update"]}))})}e.onProgress({objectName:o,status:i>0?"error":"done",progress:100,message:`Restored the status of ${s.length-i}/${s.length} ${o} records written as drafts`}),i>0&&e.errors.push({objectApiName:o,stage:"insert",failedCount:i,attemptedCount:s.length,samples:a})}}async restoreStatusesFromTheJournal(e,t){let{store:n}=e;if(!n||e.statusesGiven||n.statusesOwed().size===0)return;e.statusesGiven=!0;let o=new Map,s=new Map,i=async a=>{let d=s.get(a)??[];if(s.set(a,[]),d.length===0)return;let c=o.get(a);if(!c)return;let l;try{l=await t(e.targetOrgId,a,d.map(({id:u,status:p})=>({Id:u,Status:p})))}catch(u){l=d.map(({id:p})=>({id:p,success:!1,errors:[Y(u)]}))}d.forEach(({id:u,status:p},f)=>{let h=l[f];if(h?.success){n.gaveStatus(a,u);return}c.failed++,c.samples.length<3&&c.samples.push({recordSummary:`${a} ${u} Status=${p}`,messages:h?.errors??["No result returned for the status update"]})})};for(let{objectApiName:a,id:d,status:c}of n.statusLines()){if(e.leftDrafts.has(d)||n.statusGiven(d))continue;let l=o.get(a)??{entries:0,failed:0,samples:[]};l.entries++,o.set(a,l);let u=s.get(a)??[];u.push({id:d,status:c}),s.set(a,u),u.length>=Go.rest&&await i(a)}for(let[a,{entries:d,failed:c,samples:l}]of o)await i(a),e.onProgress({objectName:a,status:c>0?"error":"done",progress:100,message:`Restored the status of ${d-c}/${d} ${a} records written as drafts`}),c>0&&e.errors.push({objectApiName:a,stage:"insert",failedCount:c,attemptedCount:d,samples:l})}reportDraftsExclusionsLeave(e){let t=e.config.excludedObjects;if(t.size===0)return;let n=new Set;for(let[s,i]of Object.entries(fr)){let a=e.pastDraft.get(s);if(!a||a.size===0)continue;let d=e.statusChildrenRead.get(s),c=[];for(let[l,u]of a){let p=e.remapper.get(l);if(!e.config.dryRun&&!p)continue;let f;if(t.has(i.object))f=`${i.object} is excluded from this run`;else if(d&&!d.kept.has(l)){let g=d.held.get(l);g&&(f=`none of its ${i.object} records can be written without ${g.excluded}`+(g.target?Lr(g.target):", which is excluded from this run"))}if(!f)continue;p&&n.add(p);let h=p!==void 0&&!e.simulated?.has(p)?p:l;c.push({recordSummary:`${s} ${h} Status=${u}`,messages:[`Left a draft: the platform gives ${s} this status only with ${i.object} records under it, and ${f}.`]})}c.length!==0&&e.errors.push({objectApiName:s,stage:"insert",failedCount:c.length,attemptedCount:c.length,samples:c.slice(0,3)})}if(n.size===0)return;for(let s of n)e.leftDrafts.add(s);let o=e.deferredStatuses.splice(0,e.deferredStatuses.length);e.deferredStatuses.push(...o.filter(({id:s})=>!n.has(s)))}reportDraftsLeft(e){if(e.store){if(e.statusesGiven)return;e.statusesGiven=!0;for(let[n,{count:o,samples:s}]of e.store.statusesOwed())e.errors.push({objectApiName:n,stage:"insert",failedCount:o,attemptedCount:o,samples:s.map(({id:i,status:a})=>({recordSummary:`${n} ${i} Status=${a}`,messages:["Written as a draft, and the run stopped before giving it this status back: it stays a draft."]}))});return}let t=e.deferredStatuses.splice(0,e.deferredStatuses.length);for(let[n,o]of Bh(t))e.errors.push({objectApiName:n,stage:"insert",failedCount:o.length,attemptedCount:o.length,samples:o.slice(0,3).map(({id:s,status:i})=>({recordSummary:`${n} ${s} Status=${i}`,messages:["Written as a draft, and the run stopped before giving it this status back: it stays a draft."]}))})}async skipForFailedParent(e,t,n,o){let s=l=>Zm(e.objectApiName,t.graph,l).filter(u=>t.failedObjects.has(u)&&!t.failedInPart.has(u)),i=s(n??[]);if(i.length===0)return!1;if(!n)try{if(i=s(await this.deps.describeFields(t.sourceOrgId,e.objectApiName)),i.length===0)return!1}catch{}t.skippedCount++,t.failedObjects.add(e.objectApiName);let a=o?.filter(l=>!nn(t.config,l)).length??t.counted.get(e.objectApiName);a!==0&&(t.failedCount+=a??0,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:a??0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:[...i.map(l=>`Not written: its records cannot be written without ${l}, which failed in this run.`),...a===void 0?["Skipped before its records were read: how many there were is not known."]:[]]}]}));let d=Gt(t,e.objectApiName),c=(a??0)+Wn(d);return t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (parent failed)`+(c>0?`: ${c} failed${rn(d)}`:"")}),!0}async rowsWithoutTheirParent(e,t,n,o){let s=new Map;o.forEach((l,u)=>{for(let p of n){let[f]=p.referenceTo??[];if(!p.isReference||(p.referenceTo??[]).length!==1||f===e.objectApiName||!t.failedInPart.has(f)||!Ze(e.objectApiName,p.name,p.nillable))continue;let h=l[p.name];if(typeof h=="string"&&h&&!t.remapper.get(h)){s.set(u,{field:p.name,parentObject:f});return}}});let i=n.filter(l=>l.isReference&&(l.referenceTo??[]).length>1&&Ze(e.objectApiName,l.name,l.nillable)),a=[];if(o.forEach((l,u)=>{for(let p of i){let f=l[p.name];typeof f=="string"&&f&&!t.remapper.get(f)&&a.push({index:u,field:p.name,id:f})}}),a.length===0)return s;let d=new Set(t.graph.nodes.filter(l=>l.included).map(l=>l.objectApiName));d.delete(e.objectApiName);let c=await this.sourceKeyPrefixes(t,new Set(i.flatMap(l=>(l.referenceTo??[]).filter(u=>d.has(u)))));for(let{index:l,field:u,id:p}of a){let f=c.get(p.slice(0,3));f&&!s.has(l)&&s.set(l,{field:u,parentObject:f})}return s}async sourceKeyPrefixes(e,t){let n=[];for(let s of t){if(e.sourceKeyPrefixes.has(s))continue;let i=e.preread.get(s)?.records.find(a=>typeof a.Id=="string");i?e.sourceKeyPrefixes.set(s,String(i.Id).slice(0,3)):n.push(s)}for(let s=0;s<n.length;s+=6){let i=n.slice(s,s+6),a=await Promise.all(i.map(d=>this.objectInfoOf(e.sourceOrgId,d)));i.forEach((d,c)=>{let l=a[c]?.keyPrefix;l&&e.sourceKeyPrefixes.set(d,l)})}let o=new Map;for(let s of t){let i=e.sourceKeyPrefixes.get(s);i&&!o.has(i)&&o.set(i,s)}return o}async keyPrefixesNamedBy(e,t){let n=new Set(e.graph.nodes.map(s=>s.objectApiName)),o=new Set;for(let s of t){let i=s.isReference?s.referenceTo??[]:[];if(!(i.length<2))for(let a of i)n.has(a)&&!e.keyPrefixesAsked.has(a)&&o.add(a)}if(o.size>0){for(let s of o)e.keyPrefixesAsked.add(s);await this.sourceKeyPrefixes(e,o)}return e.sourceKeyPrefixes}async excludedByKeyPrefix(e,t,n){let o=e.config.excludedObjects;if(o.size===0)return new Map;let s=new Set;for(let d of n){let c=d.isReference?d.referenceTo??[]:[];if(!(c.length<2||!Ze(t,d.name,d.nillable)))for(let l of c)o.has(l)&&s.add(l)}let i=new Set([...s].filter(d=>!e.keyPrefixesAsked.has(d)));if(i.size>0){for(let d of i)e.keyPrefixesAsked.add(d);await this.sourceKeyPrefixes(e,i)}let a=new Map;for(let d of s){let c=e.sourceKeyPrefixes.get(d);c&&!a.has(c)&&a.set(c,d)}return a}async objectOfSourceId(e,t,n){let o=t.slice(0,3),s=n.find(l=>e.sourceKeyPrefixes.get(l)===o);if(s)return s;let i=new Set(e.graph.nodes.map(l=>l.objectApiName)),a=n.filter(l=>!e.sourceKeyPrefixes.has(l)),d=a.filter(l=>!i.has(l)),c=[a.filter(l=>i.has(l))];for(let l=0;l<d.length;l+=6)c.push(d.slice(l,l+6));for(let l of c){let u=(await this.sourceKeyPrefixes(e,new Set(l))).get(o);if(u)return u}}writeOrderOf(e){return this.orderByFields(e,new Map([...e.preread].map(([t,n])=>[t,n.fieldInfos])))}orderByFields(e,t){let n=e.parentsOutside.size>0?{...e.graph,nodes:[...e.graph.nodes,...e.parentsOutside.values()]}:e.graph,o=new Set(n.nodes.filter(c=>c.included).map(c=>c.objectApiName)),s=[],i=[];for(let[c,l]of t){Um(l)&&i.push(c);for(let u of l)if(!(!u.isReference||!pr(u)||!Ze(c,u.name,u.nillable)))for(let p of u.referenceTo??[])p===c||!o.has(p)||s.push({sourceObject:p,targetObject:c,relationshipName:u.name,type:"lookup",required:!0})}let a=Yl(o,i),d=t.get(We)?.some(c=>c.name===ut);return Wi(Wo(n,t),[...s,...a,...d?sp(o,i,[...s,...a]):[],...di(o),...li(o,t),...up(o,t),...gi(o)])}async singlePassOrder(e){let t=e.graph.nodes.filter(o=>o.included);if(!t.some(o=>lt(o.objectApiName))){let o=new Set(t.map(i=>i.objectApiName)),s=new Map;return o.has(ye)&&o.has(he)&&(await Promise.allSettled([ye,he].map(a=>this.deps.describeFields(e.sourceOrgId,a)))).forEach((a,d)=>{a.status==="fulfilled"&&s.set([ye,he][d],a.value)}),Wi(Wo(e.graph,s),[...di(o),...li(o,s),...gi(o)])}let n=new Map;for(let o=0;o<t.length&&!this.isAborted;o+=6){let s=t.slice(o,o+6);(await Promise.allSettled(s.map(a=>this.deps.describeFields(e.sourceOrgId,a.objectApiName)))).forEach((a,d)=>{a.status==="fulfilled"&&n.set(s[d].objectApiName,a.value)})}return this.orderByFields(e,n)}async withWhatStatusesNeed(e,t,n){let o=new Set(e.nodes.map(d=>d.objectApiName)),s=new Map,i=[],a=[];for(let d of e.nodes){if(this.isAborted)break;let c=fr[d.objectApiName];if(!d.included||!c||o.has(c.object)||s.has(c.object)||n.has(c.object))continue;let l;try{l=await this.deps.describeFields(t,c.object)}catch{continue}let u=l.find(p=>p.name===c.lookup&&p.isReference&&(p.referenceTo??[]).includes(d.objectApiName));u&&(s.set(c.object,{parent:d.objectApiName,lookup:c.lookup}),i.push(Cr(c.object,l,d.level+1)),a.push({sourceObject:d.objectApiName,targetObject:c.object,relationshipName:u.name,type:"lookup",required:Ze(c.object,u.name,u.nillable)}))}return s.size===0?{graph:e,added:s}:{graph:{...e,nodes:[...e.nodes,...i],edges:[...e.edges,...a]},added:s}}async withWhatItsRecordsComeWith(e,t,n){let o=new Set(e.nodes.map(a=>a.objectApiName)),s=[],i=[];for(let a of e.nodes){if(this.isAborted)break;let d=Lm[a.objectApiName];if(!a.included||!d||o.has(d.object)||n.has(d.object))continue;let c;try{c=await this.deps.describeFields(t,d.object)}catch{continue}let l=c.find(u=>u.name===d.lookup&&u.isReference&&(u.referenceTo??[]).includes(a.objectApiName));l&&(o.add(d.object),s.push(Cr(d.object,c,a.level+1)),i.push({sourceObject:a.objectApiName,targetObject:d.object,relationshipName:l.name,type:"lookup",required:Ze(d.object,l.name,l.nillable)}))}return s.length===0?e:{...e,nodes:[...e.nodes,...s],edges:[...e.edges,...i]}}async withTheCatalogItNeeds(e,t,n){let o=Hl(e,n);if(o.size===0)return e;let s=new Set(e.edges.map(l=>`${l.sourceObject}|${l.targetObject}`)),i=new Map,a=new Map,d=[],c=e.nodes.filter(l=>l.included);for(;c.length>0&&!this.isAborted;){let l=[];for(let u=0;u<c.length&&!this.isAborted;u+=6){let p=c.slice(u,u+6);(await Promise.allSettled(p.map(({objectApiName:h})=>this.deps.describeFields(t,h)))).forEach((h,g)=>{if(h.status!=="fulfilled")return;let{objectApiName:m,level:w}=p[g];a.set(m,h.value);for(let b of h.value){let S=b.referenceTo??[];if(!b.isReference||S.length!==1)continue;let[R]=S;R===m||!(o.has(R)||i.has(R))||ql(m,b)&&(o.delete(R)&&(i.set(R,w+1),l.push({objectApiName:R,level:w+1})),!s.has(`${R}|${m}`)&&(s.add(`${R}|${m}`),d.push({sourceObject:R,targetObject:m,relationshipName:b.name,type:"lookup",required:Ze(m,b.name,b.nillable)})))}})}c=l}return i.size===0?e:{...e,nodes:[...e.nodes,...[...i].map(([l,u])=>Cr(l,a.get(l)??[],u))],edges:[...e.edges,...d]}}async withSellingModelOptions(e,t,n){let o=l=>e.nodes.find(u=>u.included&&u.objectApiName===l),s=o(Bo),i=o(hr);if(!o(We)||!s||!i||n.has(Lt)||e.nodes.some(l=>l.objectApiName===Lt))return e;let a;try{a=await this.deps.describeFields(t,Lt)}catch{return e}let d=Cr(Lt,a,Math.max(s.level,i.level)+1),c=(l,u)=>({sourceObject:l,targetObject:Lt,relationshipName:u,type:"lookup",required:!0});return{...e,nodes:[...e.nodes,d],edges:[...e.edges,c(Bo,"Product2Id"),c(hr,"ProductSellingModelId")]}}summaryOf(e){let t=this.deps.requestsSent?.(),{simulated:n}=e,o=e.config.stream?.summaryBound;if(e.store&&o!==void 0&&e.remapper.count>o)return this.summaryOfTheJournal(e,t);let s=e.remapper.toJSON();if(n)for(let[c,l]of Object.entries(s))n.has(l)&&delete s[c];let i=c=>c in s,a=vw(e),d=[...e.mayHaveBeenWritten].map(([c,l])=>({objectApiName:c,sourceIds:[...l]}));return{successCount:e.successCount,updatedCount:e.updatedCount,linkedCount:e.linkedCount,...e.linkedToCreatedCount>0&&!n?{linkedToCreatedCount:e.linkedToCreatedCount}:{},wouldInsertCount:e.wouldInsertCount,failedCount:e.failedCount,skippedCount:e.skippedCount,remapCount:Object.keys(s).length,errors:[...e.errors,...gw(e),...uw(e),...kw(e),...Tw(e),...Mw(e)],truncatedObjects:[...e.truncatedObjects],...dh(e),...e.fieldExclusionsUnmatched.length>0?{fieldExclusionsUnmatched:[...e.fieldExclusionsUnmatched]}:{},...Qm(e),remapTable:s,existingRecords:[...e.existingRecords],existingSourceIds:e.remapper.existingSourceIds().filter(i),updatedSourceIds:e.remapper.updatedSourceIds().filter(i),...a.length>0&&!n?{withTheirRecordSourceIds:a}:{},...e.writtenByThePlatform.size>0?{writtenByThePlatform:[...e.writtenByThePlatform].map(([c,l])=>({objectApiName:c,rows:l}))}:{},...e.leftEmptyByFilter.size>0&&!n?{lookupsLeftEmptyByFilter:[...e.leftEmptyByFilter].flatMap(([c,l])=>[...l].map(([u,{records:p,ids:f}])=>({objectApiName:c,field:u,records:p,recordIds:[...f]})))}:{},remapByObject:n?[]:e.remapper.countsByObject(),...e.notSent.size>0?{notSentByObject:[...e.notSent].map(([c,l])=>({objectApiName:c,notSent:l}))}:{},createdByObject:n?[]:e.remapper.createdByObject(),readByObject:[...e.readByObject].map(([c,l])=>({objectApiName:c,read:l})),failedReads:[...e.failedReads],...e.files?{files:structuredClone(e.files)}:{},...e.fileContentFieldsLeftOut.size>0?{fileContentFieldsLeftOut:[...e.fileContentFieldsLeftOut].map(([c,l])=>({objectApiName:c,fields:[...l].sort()}))}:{},...e.encryptedFieldsLeftOut.size>0?{encryptedFieldsLeftOut:[...e.encryptedFieldsLeftOut].map(([c,l])=>({objectApiName:c,fields:[...l].sort()}))}:{},...e.picklistChanges.size>0?{picklistValuesChanged:e.picklistChanges.list()}:{},...e.currencyChanges.size>0?{currenciesReplaced:e.currencyChanges.list()}:{},...e.recordTypesGiven.size>0?{recordTypesGiven:[...e.recordTypesGiven].map(([c,l])=>zw(c,l))}:{},...e.writtenWithoutFields.size>0?{writtenWithoutFields:[...e.writtenWithoutFields].map(([c,{rows:l,fields:u}])=>({objectApiName:c,rows:l,fields:u.map(p=>({...p}))}))}:{},contactPoints:e.contactPoints?e.contactPoints.report():{neutralized:!1,fields:[],values:0},...e.writtenBetween?{writtenBetween:{...e.writtenBetween}}:{},...e.requestsBefore!==void 0&&t!==void 0?{apiCalls:t-e.requestsBefore}:{},...n?{dryRun:!0}:{},...e.gaps?{gaps:e.gaps.list(e.config.decisions.ignoredGaps)}:{},...e.decisionsApplied.size>0?{decisionsApplied:e.decisionsApplied.list()}:{},...d.length>0?{mayHaveBeenWritten:d}:{},...Hw(this.sampleResultOf(e))}}summaryOfTheJournal(e,t){let n=this.summaryOf({...e,config:{...e.config,stream:e.config.stream&&{...e.config.stream,summaryBound:void 0}},remapper:new $r,store:void 0,withTheirRecord:new Set,linkedToCreatedCount:0}),o=e.store?.withTheirRecordCount??0,s=e.store?.linkedToCreatedCount()??0;return{...n,remapCount:e.remapper.count,...o>0?{withTheirRecordCount:o}:{},...s>0?{linkedToCreatedCount:s}:{},remapByObject:e.remapper.countsByObject(),...e.requestsBefore!==void 0&&t!==void 0?{apiCalls:t-e.requestsBefore}:{},remapInJournal:!0}}async prepareFiles(e){let{config:t,onProgress:n}=e,o=t.files,s=this.fileCopyDeps();if(!o||!s)return[];let i=await Op({scope:e.fileScope,sourceOrgId:e.sourceOrgId,maxFileBytes:o.maxFileBytes,queryRecords:s.queryRecords}),a=kp(i);if(a&&!t.dryRun)throw new wn(`${a} Nothing was written.`,"FILES_UNREAD");e.errors.push(...i.errors);let d=await this.filesCopiedBefore(e,i.files,s),c={...i,files:d.filter(f=>f.into?.unchanged!==!0)},l;if(c.files.length>0)try{l=await jp(s,e.targetOrgId)}catch(f){let h=`The file storage the target has left could not be read (${Y(f)}), so the files could not be checked against it.`;if(!t.dryRun)throw new wn(`${h} Nothing was written.`,"FILE_STORAGE_UNREAD");e.errors.push(Sa(h))}e.files=vp(c,o.maxFileBytes,l),a&&(e.files.lookupFailure=a);let u=Tp(c.files),p=l===void 0?null:Ap(u,l);if(p&&l!==void 0&&!t.dryRun)throw new wn(`${p} Nothing was written.`,"FILE_STORAGE_EXCEEDED",{neededBytes:u,remainingBytes:l});if(p&&e.errors.push(Sa(p)),t.dryRun){e.files.wouldCopy=c.files.map(({objectApiName:f,sourceId:h,name:g,bytes:m})=>({objectApiName:f,sourceId:h,name:g,bytes:m}));for(let f of e.files.objects)n({objectName:f.objectApiName,status:"done",progress:100,message:Ip(f)});return[]}return d}async filesCopiedBefore(e,t,n){let{store:o}=e;if(!o||e.config.dryRun)return t;let s=await Sp({files:t,targetOrgId:e.targetOrgId,copiedBefore:i=>{let a=o.mapping(i);return a?.earlier&&a.kind==="created"&&a.objectApiName?{objectApiName:a.objectApiName,targetId:a.targetId}:void 0},queryRecords:n.queryRecords});return e.errors.push(...s.errors),s.files}async writeFiles(e,t){let n=this.fileCopyDeps();if(!n||!e.files)return;let{remapper:o}=e;e.failedCount+=await Ta({files:t,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:s=>o.wasCreated(s),get:s=>o.get(s),add:(s,i,a)=>o.add(s,i,a),persist:()=>o.persist()},deps:n,report:e.files,errors:e.errors,waitIfPaused:()=>this.waitIfPaused(),onProgress:e.onProgress,...e.store?{calls:ms(e.store)}:{}})}async copyFilesOfTheOrg(e,t){let n=this.fileCopyDeps();if(!n)return;e.files??={maxFileBytes:t,objects:[],links:0,leftOut:[]};let o=e.files,s=0,i=(d,c)=>e.onProgress({objectName:d,status:"running",progress:50,message:c}),a=e.config.stream?.pageSize??Iw;for(let d of id){let{counted:c}=d,l=e.config.stream?.resumeAfter.get(qo(c,jh));if(l?.done)continue;let p=`SELECT ${d.object==="ContentVersion"?"Id, ContentDocumentId, Title, PathOnClient, ContentSize, SharingPrivacy":"Id, ParentId, Name, ContentType, BodyLength, IsPrivate"} FROM ${d.object} WHERE `+[d.where,`${d.size} <= ${t}`].filter(Boolean).join(" AND "),f=l?.read??0,h=l&&Pt.test(l.lastId)?l.lastId:void 0;for(let g=!1;!g;){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");let m=await this.filesPageAfter(e,c,p,h,a);if(!m)break;g=m.length<a;let w=!0;for(let S=0;S<m.length;S+=sd){let R=m.slice(S,S+sd),k=d.object==="ContentVersion"?await this.documentsOnTheRunsRecords(e,R):Ew(e,R);if(!k){w=!1;break}if(k.length===0)continue;let I=await this.filesCopiedBefore(e,k,n);for(let A of I){if(A.into?.unchanged)continue;let x=vh(o,A.objectApiName);x.planned++,x.plannedBytes+=A.bytes}s+=I.filter(A=>A.into?.unchanged).length,e.failedCount+=await Ta({files:I,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:A=>e.remapper.wasCreated(A),get:A=>e.remapper.get(A),add:(A,x,j)=>e.remapper.add(A,x,j),persist:()=>e.remapper.persist()},deps:n,report:o,errors:e.errors,waitIfPaused:()=>this.waitIfPaused(),onProgress:()=>{},...e.store?{calls:ms(e.store)}:{}});let O=vh(o,c);i(c,`Copying files: ${O.copied} of ${O.planned} copied so far`)}if(!w)break;f+=m.length;let b=m[m.length-1]?.Id;typeof b=="string"&&(h=b),h!==void 0&&e.store?.checkpoint(c,{lastId:h,read:f,...g?{done:!0}:{}},jh)}}for(let d of o.objects){let c=d.objectApiName==="Attachment"?"attachment":"file";e.onProgress({objectName:d.objectApiName,status:d.failed>0&&d.copied===0?"error":"done",progress:100,message:`Copied ${d.copied} ${c}${d.copied===1?"":"s"} of ${d.planned}`+(d.failed>0?`, ${d.failed} failed`:"")})}s>0&&nt.info(`[forge] ${s} file(s) copied by the run this one takes up: linked to the records they lacked`)}async filesPageAfter(e,t,n,o,s){let i=n+(o?` AND Id > '${o}'`:"")+` ORDER BY Id LIMIT ${s}`;try{return await this.readOnPassingFailure(t,()=>this.deps.queryRecords(e.sourceOrgId,i))}catch(a){e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:o?`(files after ${o})`:"(files)",messages:[`Not read, so not copied \u2014 a run taken up reads them again: ${Y(a)}`]}]});return}}async readOnPassingFailure(e,t){for(let n=0;;n++)try{return await t()}catch(o){let s=Ih(o);if(!s&&!Eh(o)||n>=Qa||this.isAborted)throw o;s||await $h(nh*2**n),nt.warn(`[forge] ${e}: the source ${s?"let its cursor expire":"did not answer"} \u2014 asking again (${n+1}/${Qa}): ${Y(o)}`)}}async documentsOnTheRunsRecords(e,t){let n=new Map;for(let d of t){let c=d.ContentDocumentId;typeof c=="string"&&Pt.test(c)&&n.set(c,d)}if(n.size===0)return[];let o=new Map,s=d=>{e.errors.push({objectApiName:"ContentDocument",stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(links of ${n.size} files)`,messages:[d]}]})},i=!1;try{let d=await this.readOnPassingFailure("ContentDocumentLink",()=>this.deps.queryRecords(e.sourceOrgId,`SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility FROM ContentDocumentLink WHERE ContentDocumentId IN (${[...n.keys()].map(c=>`'${c}'`).join(", ")})`,()=>i=!0));for(let c of d){let l=c.ContentDocumentId,u=c.LinkedEntityId;if(typeof l!="string"||typeof u!="string"||!e.remapper.wasCreated(u))continue;let p=o.get(l)??[];if(p.some(g=>g.id===u))continue;let f=c.ShareType,h=c.Visibility;p.push({id:u,...typeof f=="string"?{shareType:f}:{},...typeof h=="string"?{visibility:h}:{}}),o.set(l,p)}}catch(d){s(`Not read, so not copied \u2014 a run taken up reads them again: ${Y(d)}`);return}i&&s("More links than the source reads at once: the files were copied onto the records of the run among those read, and may lack a link to the others.");let a=[];for(let[d,c]of o){let l=n.get(d),u=l?.Id;if(!l||typeof u!="string")continue;let p=l.Title,f=typeof p=="string"&&p!==""?p:d,h=l.PathOnClient,g=l.ContentSize;a.push({objectApiName:"ContentDocument",sourceId:d,body:{objectApiName:"ContentVersion",id:u},name:f,bytes:typeof g=="number"&&Number.isFinite(g)?g:0,hosts:c,fields:{Title:f,PathOnClient:typeof h=="string"&&h!==""?h:f,...l.SharingPrivacy==="P"?{SharingPrivacy:"P"}:{}}})}return a}async readInTurn(e,t){t.turnsAhead.delete(e.objectApiName),await this.readNode(e,t,!0,!1),![...t.waitingFor.values()].some(o=>o.includes(e))&&(await this.readUnderWhatWaited(e.objectApiName,t,"at its turn"),await this.endTurn(e.objectApiName,t))}async readUnderWhatWaited(e,t,n){let o=t.scopeCache,s=t.readAgainUnder.get(e);if(!(!o||!s||!o.isRead(e))){t.readAgainUnder.delete(e);for(let{node:i,fieldInfos:a,whileWaiting:d}of s){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");t.failedObjects.has(i.objectApiName)||n==="at its turn"&&!d||n==="after the catalog"&&!d&&!Dh(i.objectApiName,a).includes(e)||await this.readAgainUnderRowsOf(t,i,[...a],e)&&await this.readUnderRowsAdded(i.objectApiName,t,1)}}}async readAgainUnderRowsOf(e,t,n,o){let s=gn({node:t,edges:e.graph.edges,fieldInfos:n,scopedBuilder:e.scopedBuilder,scopeCache:e.scopeCache,rootObjectApiName:e.config.rootObjectApiName,rootRecordId:e.config.rootRecordId,extraWhere:e.config.objectSoqlFilters?.[t.objectApiName],fieldsLeftOut:e.config.fieldExclusions[t.objectApiName],readObjects:e.readObjects,catalog:Je,under:new Set([o])});return s.kind!=="query"?!1:(await this.readMore(e,t,n,s.statements,`under the ${o} records read after it`)).length>0}async readUnderRowsAdded(e,t,n){let o=t.scopeCache;if(!o||n>=qm)return;let{config:s}=t,i=new Set(t.graph.edges.filter(a=>a.sourceObject===e&&a.targetObject!==e).map(a=>a.targetObject));for(let a of t.graph.nodes){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");let d=a.objectApiName;if(!a.included||!i.has(d)||!o.isRead(d)||d===s.rootObjectApiName||Je.has(d)||s.referenceDataObjects.has(d)||t.failedObjects.has(d)||t.notCreatable.has(d))continue;let c=await this.fieldsReadAgain(t,a);!c||!await this.readAgainUnderRowsOf(t,a,c.fields,e)||(c.described&&this.withoutFileContent(t,d,c.described,!0),await this.readUnderRowsAdded(d,t,n+1))}}async readWhatTheyCannotBeWrittenWithout(e,t,n,o){let s=e.scopeCache;if(!s||o.length===0)return;let{config:i}=e,a=new Set(i.fieldExclusions[t]??[]),d=new Map;for(let c of n){let l=c.referenceTo??[];if(!c.isReference||l.length!==1||a.has(c.name)||!pr(c)||!Ze(t,c.name,c.nillable))continue;let[u]=l;if(u===t||u===i.rootObjectApiName||Je.has(u)||i.referenceDataObjects.has(u)||!e.readObjects.has(u)||e.failedObjects.has(u)||e.notCreatable.has(u)||!s.isRead(u))continue;let p=s.scopeOf(u),f=e.askedForRowsThatNeedThem.get(u),h=e.heldForExclusions.get(u);for(let g of o){let m=g[c.name];typeof m!="string"||m===""||p?.has(m)||f?.has(m)||h?.has(m)||e.remapper.get(m)||e.leftToThePlatform.has(m)||d.set(u,(d.get(u)??new Set).add(m))}}for(let[c,l]of d){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");let u=e.graph.nodes.find(m=>m.included&&m.objectApiName===c);if(!u)continue;let p=e.askedForRowsThatNeedThem.get(c)??new Set;for(let m of l)p.add(m);e.askedForRowsThatNeedThem.set(c,p);let f=await this.fieldsReadAgain(e,u);if(!f)continue;let h=Wt(f.fields,i.fieldExclusions[c]);(await this.readMore(e,u,f.fields,new hn().buildById({objectApiName:c,selectFields:h.length>0?h:["Id"],ids:l,extraWhere:i.objectSoqlFilters?.[c]}),`which the ${t} records read after it cannot be written without`)).length!==0&&(f.described&&this.withoutFileContent(e,c,f.described,!0),await this.readUnderRowsAdded(c,e,0))}}async readParentsOutsideTheGraph(e){let{config:t}=e;if(!e.scopeCache||t.referenceFallback!=="nullify")return!1;let n=new Map(e.graph.nodes.map(d=>[d.objectApiName,d])),o=new Map,s=new Map,i=!1,a=[...e.preread].filter(([d])=>!e.failedObjects.has(d)).map(([d,c])=>({objectApiName:d,fieldInfos:c.fieldInfos,records:c.records}));for(let d=0;d<Km&&a.length>0;d++){let c=this.parentsWanted(e,a,d>0,n);c.size>0&&(i=!0);let l=[];for(let[p,f]of c){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");let h=await this.refusalOf(e,p,n.get(p),o);h?await this.holdBackForARefusedParent(e,p,h,f,s):l.push([p,f])}let u=[];for(let[p,f]of l){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");let h=Vm(e,f);if(h.ids.size===0)continue;let g=await this.readParentsById(e,p,n.get(p),h);g&&u.push(g)}a=u}return i}parentsWanted(e,t,n,o){let{config:s}=e,i=new Map,a=new Map,d=c=>{let l=a.get(c);return l||(l=new Set((e.preread.get(c)?.records??[]).flatMap(u=>typeof u.Id=="string"?[u.Id]:[])),a.set(c,l)),l};for(let{objectApiName:c,fieldInfos:l,records:u}of t){let p=new Set(s.fieldExclusions[c]??[]);for(let f of l){let h=f.referenceTo??[];if(!f.isReference||h.length!==1||p.has(f.name)||!pr(f)||!Ze(c,f.name,f.nillable))continue;let[g]=h;if(g===c||g===s.rootObjectApiName||Je.has(g)||s.referenceDataObjects.has(g)||s.excludedObjects.has(g)||gs(e,g))continue;let m=o.get(g);if(m&&(!n||!m.included||e.failedObjects.has(g)))continue;let w=e.askedForRowsThatNeedThem.get(g),b=e.heldForExclusions.get(g);for(let S of u){let R=S[f.name];if(typeof R!="string"||R===""||nn(s,S)||e.remapper.get(R)||e.leftToThePlatform.has(R)||w?.has(R)||b?.has(R)||d(g).has(R))continue;let k=i.get(g);k||(k={ids:new Set,neededBy:new Set,rows:[]},i.set(g,k)),k.ids.add(R),k.neededBy.add(c),k.rows.push({objectApiName:c,row:S,field:f.name})}}}return i}async refusalOf(e,t,n,o){if(n)return e.notInTarget.has(t)?"not-in-target":e.notCreatable.has(t)?"not-creatable":void 0;let s=o.get(t);if(s!==void 0)return s??void 0;let i,a=this.deps.isObjectCreatable;if(a)try{await a(e.targetOrgId,t)||(i="not-creatable")}catch(d){Qn(d)?i="not-in-target":e.errors.push({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed)",messages:[`isObjectCreatable check failed: ${d instanceof Error?d.message:String(d)}`]}]})}return o.set(t,i??null),i}async holdBackForARefusedParent(e,t,n,o,s){let i=new Map;for(let{objectApiName:a,row:d,field:c}of o.rows){let l=d.Id;if(typeof l!="string"||i.get(a)?.has(l)||!await this.carriesTheLookup(e,a,c,s))continue;let u=i.get(a)??new Map;u.set(l,{row:d,why:{field:c,excluded:t,target:n}}),i.set(a,u)}for(let[a,d]of i){let c=e.preread.get(a);if(!c)continue;let l=c.records.filter(u=>typeof u.Id!="string"||!d.has(u.Id));this.holdBackRowsRead(e,a,c,l,[...d].map(([u,{row:p,why:f}])=>({id:u,row:p,why:f})))}}async carriesTheLookup(e,t,n,o){if(e.config.fieldMappings[t]?.[n])return!0;let s=o.get(t);if(s===void 0){try{s=await tn(this.deps.describeFields,e.targetOrgId,t)}catch{s=null}o.set(t,s)}return s===null||s.creatable.has(n)}async readParentsById(e,t,n,o){let{config:s}=e,i=[...o.neededBy].sort().join(", "),a=s.maxRecordsPerObject?Math.floor(s.maxRecordsPerObject):0,d=a>0?a-(e.readByObject.get(t)??0):0;if(a>0&&d<=0){o.ids.size>0&&e.cappedObjects.add(t);return}let c=e.preread.get(t),l,u;if(c)l=[...c.fieldInfos];else{try{u=await this.deps.describeFields(e.sourceOrgId,t)}catch(O){e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(describe, for the ${i} records that cannot be written without its records)`,messages:[Y(O)]}]});return}l=u.filter(O=>!In(O))}let p=e.askedForRowsThatNeedThem.get(t)??new Set;for(let O of o.ids)p.add(O);e.askedForRowsThatNeedThem.set(t,p);let f=Wt(l,s.fieldExclusions[t]),h=new hn().buildById({objectApiName:t,selectFields:f.length>0?f:["Id"],ids:o.ids,extraWhere:s.objectSoqlFilters?.[t]}),g;try{g=await jr(d>0?Di(h,d,{byIdCount:h.length}):{kind:"query",statements:h,byIdCount:h.length},O=>this.deps.queryRecords(e.sourceOrgId,O,()=>e.truncatedObjects.add(t)),void 0,()=>e.cappedObjects.add(t))}catch(O){if(O instanceof Oe)throw O;e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(read by id, for the ${i} records that cannot be written without them)`,messages:[Y(O)]}]});return}Fr(e,g);let m=new Set((c?.records??[]).flatMap(O=>typeof O.Id=="string"?[O.Id]:[])),w=g.filter(O=>typeof O.Id!="string"||!m.has(O.Id)),b=O=>(e.graph.nodes.find(A=>A.objectApiName===O)??e.parentsOutside.get(O))?.level??0,S=n??e.parentsOutside.get(t)??Cr(t,l,1+Math.max(0,...[...o.neededBy].map(b))),R=new Set(e.heldForExclusions.get(t)?.keys()??[]);this.holdBackWhatExclusionsCost(e,S,l,w,void 0,await this.excludedByKeyPrefix(e,t,l));let k=[...e.heldForExclusions.get(t)??[]].filter(([O])=>!R.has(O));if(this.leaveToThePlatform(e,t,w,l),w.length===0&&k.length===0)return;let I=c?.createableSet??new Set(l.filter(O=>O.createable).map(O=>O.name));if(w.length>0){e.preread.set(t,c?{...c,records:[...c.records,...w]}:{fieldInfos:l,createableSet:I,records:w,targetSetsPending:null}),u&&this.withoutFileContent(e,t,u,!0),n?c||e.skippedCount--:(e.parentsOutside.set(t,S),e.writtenObjects.add(t));let O=w.find(x=>typeof x.Id=="string")?.Id;typeof O=="string"&&!e.sourceKeyPrefixes.has(t)&&e.sourceKeyPrefixes.set(t,O.slice(0,3));let A=e.readAsParents.get(t)??{count:0,neededBy:new Set};A.count+=w.length;for(let x of o.neededBy)A.neededBy.add(x);e.readAsParents.set(t,A)}else if(!n){let O=e.heldForExclusions.get(t);O&&e.onProgress({objectName:t,status:"error",progress:100,message:Mr(t,O,!1)})}if(e.readByObject.set(t,(e.readByObject.get(t)??0)+w.length+k.length),s.dryRun){let O=w.length>0?await this.writtenWithTheirAccountOnADryRun(e,t,w,I):0,A=c?"more ":"";e.onProgress({objectName:t,status:"running",progress:0,message:`[dry-run] ${t}: ${w.length-O} ${A}record(s) would be inserted`+(O>0?`, ${O} ${A}would be written by the platform with ${Hn(t)}`:"")+`, which the ${i} records cannot be written without: read by id, nothing read under them`+Os(Rs(k.map(([,x])=>x)),c!==void 0)})}return w.length>0?{objectApiName:t,fieldInfos:l,records:w}:void 0}async endTurn(e,t){t.turnsAhead.delete(e);let n=t.waitingFor.get(e);if(n){t.waitingFor.delete(e);for(let o of n){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");await this.readInTurn(o,t)}}}async readNode(e,t,n,o){let{config:s,sourceOrgId:i,targetOrgId:a,onProgress:d,remapper:c}=t;t.readAtItsTurn.delete(e.objectApiName);let l=t.cursors.get(e.objectApiName);try{(!l||l.taken===0)&&d({objectName:e.objectApiName,status:"scanning",progress:0,message:`Querying ${e.objectApiName} records...`});let u=l?.described??await this.deps.describeFields(i,e.objectApiName);l&&(l.described=u);let p=u.filter($=>!In($)),f=new Set(p.filter($=>$.createable).map($=>$.name));if(await this.skipForFailedParent(e,t,p))return!1;if(n&&e.objectApiName!==s.rootObjectApiName){let $=zm(e.objectApiName,p,t.turnsAhead);if($)return t.waitingFor.set($,[...t.waitingFor.get($)??[],e]),!1}let h={node:e,edges:t.graph.edges,fieldInfos:p,scopedBuilder:t.scopedBuilder,scopeCache:t.scopeCache,rootObjectApiName:s.rootObjectApiName,rootRecordId:s.rootRecordId,extraWhere:$w(this.filterOf(t,e.objectApiName),l?.pass),fieldsLeftOut:s.fieldExclusions[e.objectApiName],maxRecordsPerObject:l?t.sample?.drawn.has(e.objectApiName)?void 0:this.pagedLimit(t,l):s.maxRecordsPerObject,...l?{inIdOrder:l.resumeAfter!==void 0?{afterId:l.resumeAfter}:{}}:{},readObjects:t.readObjects,catalog:Je,rootReadAgain:!n&&e.objectApiName===s.rootObjectApiName},g=gn(h);if(n&&this.waitsForWhatPointsAtIt(e,g,t))return t.catalogNodes.push({node:e,fieldInfos:p}),!1;if(g.kind==="skip"){if(n&&g.reason===Ul)return t.deferredNodes.push(e),!1;let $=t.heldForExclusions.get(e.objectApiName);return $&&$.size>0?(t.readByObject.set(e.objectApiName,$.size),d({objectName:e.objectApiName,status:"error",progress:100,message:Mr(e.objectApiName,$,!1)}),!1):(t.skippedCount++,d({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (out of scope: ${g.reason})`}),!1)}if(t.notCreatable.has(e.objectApiName)){let $=gn({...h,maxRecordsPerObject:1}),L=$.kind==="query"?await jr($,Q=>this.deps.queryRecords(i,Q)):[];return this.reportNotCreatable(e,t,L.length>0),!1}let w=o&&!s.referenceDataObjects.has(e.objectApiName)?l?.targetSets??tn(this.deps.describeFields,a,e.objectApiName).then($=>({ok:!0,sets:$}),$=>({ok:!1,error:$})):null;l&&(l.targetSets=w);let b=t.scopeCache?new Set:void 0,S=l?$=>{let L=gn({...h,maxRecordsPerObject:l.room===void 0?void 0:Math.max(1,l.room),inIdOrder:{afterId:$}});return L.kind==="query"&&L.statements.length===1?L.statements[0]:void 0}:void 0,R=await jr(g,$=>l?this.nextPage(t,e,l,$,S):this.readWhole(t,e.objectApiName,$),b,()=>t.cappedObjects.add(e.objectApiName));if(l?.ended&&R.length===0&&l.taken>0)return!1;let k=l?.pass?R.filter(l.pass.keep):R;Fr(t,k),this.keepWhatStatusesNeed(t,e,k,b);let I=this.holdBackWhatExclusionsCost(t,e,p,k,b,await this.excludedByKeyPrefix(t,e.objectApiName,p));b&&t.scopeCache?.addReached(e.objectApiName,b);let O=k.find($=>typeof $.Id=="string")?.Id;if(typeof O=="string"&&!t.sourceKeyPrefixes.has(e.objectApiName)&&t.sourceKeyPrefixes.set(e.objectApiName,O.slice(0,3)),s.referenceDataObjects.has(e.objectApiName)){t.readByObject.set(e.objectApiName,k.length);let $=await t.referenceDataMapper.resolve(e.objectApiName,k,a);for(let L of $.mappings)c.addExisting(L.sourceId,L.targetId);return $.unmatched.length>0&&t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:$.unmatched.length,attemptedCount:k.length,referenceData:!0,samples:Ym(e.objectApiName,$.unmatched)}),t.scopeCache&&Xl(t.scopeCache,e.objectApiName,k),t.linkedCount+=$.mappings.length,d({objectName:e.objectApiName,status:"done",progress:100,message:`Mapped ${e.objectApiName} via reference-data lookup: ${$.mappings.length} resolved, ${$.unmatched.length} unmatched`}),!1}if(this.leaveToThePlatform(t,e.objectApiName,k,p),e.objectApiName===Rt&&t.standardPricebookId){let $=t.standardPricebookId,L=k.filter(Q=>Q.Id!==$);L.length!==k.length&&(k.length=0,k.push(...L))}let A=t.scopeCache;if(n&&A&&Je.has(e.objectApiName))return _o(A,e.objectApiName,k,p,{settle:!1,keyPrefixes:await this.keyPrefixesNamedBy(t,p)}),t.catalogNodes.push({node:e,fieldInfos:p}),t.readAtItsTurn.set(e.objectApiName,{records:k,fieldInfos:p}),!1;let x=t.heldForExclusions.get(e.objectApiName);if(I>0&&k.length===0&&x&&!l)return t.failedObjects.add(e.objectApiName),t.readByObject.set(e.objectApiName,x.size),d({objectName:e.objectApiName,status:"error",progress:100,message:Mr(e.objectApiName,x)}),!1;if(lt(e.objectApiName)&&t.standardPricebookId){await this.addStandardPricebookEntries(e,t,k,p);let $=t.sample;if($?.drawn.has(e.objectApiName)){let Q=k.filter(q=>this.inThePlan($,e.objectApiName,String(q.Id)));k.length=0,k.push(...Q);let G=t.standardPricebookId,V=new Set(k.filter(q=>q[Ot]===G).map(q=>dd(q,t.sellingModels)));for(let q of k)q[Ot]!==G&&(V.has(dd(q,t.sellingModels))||$.withoutStandard.add(le(String(q.Id))))}t.readsEverythingFirst||await this.pricesInTheCurrencyWritten(e,t,k,p);let L=gr(k,{sellingModel:t.sellingModels});L.length!==k.length&&(k.length=0,k.push(...L))}t.scopeCache&&_o(t.scopeCache,e.objectApiName,k,p,{keyPrefixes:await this.keyPrefixesNamedBy(t,p)}),await this.notePastDraft(t,e.objectApiName,k);let j=e.objectApiName===s.rootObjectApiName||Je.has(e.objectApiName)?[]:Gm(e.objectApiName,p,t),E=new Set(n?[...t.waitingFor.values()].flat().map($=>$.objectApiName):[]);for(let $ of j){let L=t.readAgainUnder.get($)??[];t.readAgainUnder.set($,[...L,{node:e,fieldInfos:p,whileWaiting:E.has($)}])}if(s.files&&s.stream?.everything!==!0){let $=k.flatMap(L=>typeof L.Id=="string"&&!s.writtenBefore.retried(L.Id)?[L.Id]:[]);t.fileScope.set(e.objectApiName,$)}if(this.withoutFileContent(t,e.objectApiName,u,k.length>0),l&&(l.carry.rows+=k.length),l?.pass||t.readByObject.set(e.objectApiName,(l?l.carry.rows:k.length)+(x?.size??0)),t.preread.set(e.objectApiName,{fieldInfos:p,createableSet:f,records:k,targetSetsPending:w}),s.dryRun){let $=await this.writtenWithTheirAccountOnADryRun(t,e.objectApiName,k,f),L=k.length-$;d({objectName:e.objectApiName,status:"running",progress:0,message:`[dry-run] ${e.objectApiName}: ${L} record(s) would be inserted`+($>0?`, ${$} would be written by the platform with ${Hn(e.objectApiName)}`:"")+wh(t,e.objectApiName)})}return await this.readWhatTheyCannotBeWrittenWithout(t,e.objectApiName,p,k),!0}catch(u){if(u instanceof Oe||u instanceof ks)throw u;if(t.notCreatable.has(e.objectApiName))return this.reportNotCreatable(e,t,!0),!1;t.failedObjects.add(e.objectApiName),t.failedReads.add(e.objectApiName),l&&(l.failed=!0);let p=s.isScoped?0:Math.max(0,sh(e,s.maxRecordsPerObject)-(l?.read??0));return t.failedCount+=p,t.errors.push({objectApiName:e.objectApiName,stage:"query",failedCount:p,attemptedCount:p,samples:[{recordSummary:"(stage failed before insert)",messages:[Y(u)]}]}),d({objectName:e.objectApiName,status:"error",progress:100,message:`Error on ${e.objectApiName}: ${Y(u)}`}),!1}}holdBackWhatExclusionsCost(e,t,n,o,s,i){let a=e.config.excludedObjects;if(a.size===0)return 0;let d=t.objectApiName,c=n.filter(R=>R.isReference&&Ze(d,R.name,R.nillable)),l=c.filter(R=>{let k=R.referenceTo??[];return k.length===1&&k[0]!==d&&a.has(k[0])}),u=c.filter(R=>{let k=R.referenceTo??[];return k.length>1&&k.some(I=>a.has(I))}),p=d===We&&e.sellingModels&&a.has(Lt),f=kh(d),h=c.length>0&&e.heldForExclusions.size>0;if(l.length===0&&u.length===0&&!h&&!p&&!f)return 0;let g=R=>{for(let O of l){let A=R[O.name];if(typeof A=="string"&&A!==""&&!e.remapper.get(A))return{field:O.name,excluded:(O.referenceTo??[])[0]}}for(let O of u){let A=R[O.name];if(typeof A!="string"||A===""||e.remapper.get(A))continue;let x=i.get(A.slice(0,3));if(x!==void 0&&(O.referenceTo??[]).includes(x))return{field:O.name,excluded:x}}let k=h?yh(e,R,c):void 0;if(k)return k;let I=R[Bt];if(p&&typeof I=="string"&&I!=="")return{field:Bt,excluded:Lt}},m=e.heldForExclusions.get(d)??new Map,w=f?e.statusChildrenRead.get(f.parent)??{kept:new Set,held:new Map}:void 0,b=[];for(let R of o){let k=g(R),I=f?R[f.lookup]:void 0;if(!k){b.push(R),w&&typeof I=="string"&&w.kept.add(I);continue}w&&typeof I=="string"&&!w.held.has(I)&&w.held.set(I,k);let O=R.Id;typeof O=="string"&&(s?.delete(O),!m.has(O)&&(m.set(O,k),e.failedCount++))}w&&f&&e.statusChildrenRead.set(f.parent,w),m.size>0&&e.heldForExclusions.set(d,m);let S=o.length-b.length;return S>0&&(o.length=0,o.push(...b)),S}holdBackWhatHeldRowsCost(e){let{config:t}=e;if(e.heldForExclusions.size!==0)for(let n=!0;n&&!this.isAborted;){n=!1;for(let[o,s]of[...e.preread]){let i=s.fieldInfos.filter(c=>c.isReference&&Ze(o,c.name,c.nillable));if(i.length===0)continue;let a=[],d=[];for(let c of s.records){let l=c.Id,u=typeof l=="string"&&!nn(t,c)?yh(e,c,i):void 0;typeof l=="string"&&u?d.push({id:l,row:c,why:u}):a.push(c)}d.length!==0&&(n=!0,this.holdBackRowsRead(e,o,s,a,d))}}}holdBackWhatOnlyRowsHeldBackName(e){if(!e.scopeCache||e.namedByRowsHeldBack.size===0)return!1;let t=Rh(e),n=!1;for(let[o,s]of[...e.preread]){if(!Je.has(o))continue;let i=[],a=[];for(let d of s.records){let c=d.Id,l=typeof c=="string"?Oh(e,o,c,t):void 0;typeof c=="string"&&l?a.push({id:c,row:d,why:l}):i.push(d)}a.length!==0&&(n=!0,this.holdBackRowsRead(e,o,s,i,a))}return n}leaveOutWhatOnlyRowsHeldBackName(e,t){let n=e.scopeCache,o=n?.get(t);if(!n||!o||o.size===0||e.namedByRowsHeldBack.size===0)return;let s=Rh(e),i=e.heldForExclusions.get(t)??new Map,a=[];for(let d of o){let c=Oh(e,t,d,s);c&&(a.push(d),!i.has(d)&&(i.set(d,c),e.failedCount++))}a.length!==0&&(e.heldForExclusions.set(t,i),n.forget(t,a))}holdBackRowsRead(e,t,n,o,s){let{config:i,onProgress:a}=e,d=e.heldForExclusions.get(t)??new Map;for(let{id:p,why:f}of s)d.set(p,f);e.heldForExclusions.set(t,d),e.failedCount+=s.length;let c=n.fieldInfos.filter(p=>p.isReference);for(let{row:p,why:f}of s)for(let h of c){let g=p[h.name];typeof g!="string"||g===""||e.namedByRowsHeldBack.has(g)||e.namedByRowsHeldBack.set(g,{field:h.name,excluded:f.excluded,namedBy:t})}let l=new Set(s.map(({id:p})=>p)),u=e.fileScope.get(t)??[];if(u.length>0&&e.fileScope.set(t,u.filter(p=>!l.has(p))),this.noteStatusRowsHeld(e,t,o,s),i.dryRun&&a({objectName:t,status:"running",progress:0,message:`[dry-run] ${t}: ${s.length} fewer would be inserted`+Os(Rs(s.map(({why:p})=>p)))}),o.length>0){e.preread.set(t,{...n,records:o});return}e.preread.delete(t),e.failedObjects.add(t),a({objectName:t,status:"error",progress:100,message:Mr(t,d)})}noteStatusRowsHeld(e,t,n,o){let s=kh(t);if(!s)return;let i=e.statusChildrenRead.get(s.parent),a=new Map(i?.held??[]);for(let{row:c,why:l}of o){let u=c[s.lookup];typeof u=="string"&&!a.has(u)&&a.set(u,l)}let d=new Set;for(let c of n){let l=c[s.lookup];typeof l=="string"&&d.add(l)}e.statusChildrenRead.set(s.parent,{kept:d,held:a})}keepWhatStatusesNeed(e,t,n,o){let s=e.statusChildren.get(t.objectApiName);if(!s)return;let i=e.pastDraft.get(s.parent),a=[];for(let d of n){let c=d[s.lookup];typeof c=="string"&&i?.has(c)===!0?a.push(d):typeof d.Id=="string"&&o?.delete(d.Id)}a.length!==n.length&&(n.length=0,n.push(...a))}leaveToThePlatform(e,t,n,o){let s=e.leftToThePlatform.keep(t,n,Rw(t,o)),i=n.length-s.length;return i>0&&(n.length=0,n.push(...s)),i}leaveWhatHangsFromThePlatform(e,t,n,o){let s=[...o],i=this.leaveToThePlatform(e,t.objectApiName,s,n),a=e.readByObject.get(t.objectApiName);return i>0&&a!==void 0&&e.readByObject.set(t.objectApiName,a-i),s}holdEmailsForTheirTask(e,t){if(e.taskTurnOver||!e.graph.nodes.some(s=>s.included&&s.objectApiName===st))return t;let n=e.readsEverythingFirst?new Set((e.preread.get(st)?.records??[]).map(s=>String(s.Id))):void 0,o=[];for(let s of t)co(s)&&(n===void 0||n.has(String(s.ActivityId)))?e.emailsInTwoPasses?e.emailsLeftForTheirTask++:e.emailsAfterTheirTask.push(s):o.push(s);return o}async writeEmailsAfterTheirTask(e){if(e.emailsInTwoPasses){await this.streamEmailsAfterTheirTask(e);return}e.taskTurnOver=!0;let t=e.emailsAfterTheirTask.splice(0,e.emailsAfterTheirTask.length),n=e.graph.nodes.find(o=>o.objectApiName===je);n&&t.length>0&&!this.isAborted&&(e.emailsAllWaiting=void 0,await this.writeNode(n,e,t)),this.endBeforeTheEmailsThatWaited(e,t.length,this.isAborted)}async streamEmailsAfterTheirTask(e){if(e.taskTurnOver)return;e.taskTurnOver=!0;let t=e.emailsLeftForTheirTask;e.emailsLeftForTheirTask=0;let n=e.graph.nodes.find(l=>l.included&&l.objectApiName===je),o=e.config.stream?.resumeAfter,s=o?.has(je)===!0||o?.has(qo(je,th))===!0;if(!(n!==void 0&&e.emailsFirstPassRan&&(t>0||s)&&!e.failedObjects.has(je)&&e.graph.nodes.some(l=>l.included&&l.objectApiName===st))||this.isAborted){this.endBeforeTheEmailsThatWaited(e,t,this.isAborted);return}let a=e.emailsWrittenFirst!==void 0,d=e.config.dryRun?"Simulated":"Completed";try{await this.streamNode(n,e,{name:th,where:"ActivityId != null",keep:l=>co(l),expected:t,stopped:`Stopped ${je} after their task`,end:{say:this.endOfTheEmails(e,!0),label:a?"after their task":`${d} ${je} after their task`}})}catch(l){throw e.emailsWrittenFirst=void 0,l}let c=e.emailsWrittenFirst;c&&(e.emailsWrittenFirst=void 0,e.onProgress(c))}endBeforeTheEmailsThatWaited(e,t,n){let o=e.emailsWrittenFirst??e.emailsAllWaiting;e.emailsWrittenFirst=void 0,e.emailsAllWaiting=void 0,o&&(od(e,je,t),e.onProgress(Aw(o,t,n,wh(e,je))))}endOfTheEmails(e,t){return n=>{if(n.status!=="done"&&n.status!=="error"&&n.status!=="stopped"){e.onProgress(n);return}if(!t){if(e.emailsAfterTheirTask.length===0&&e.emailsLeftForTheirTask===0){e.onProgress(n);return}e.emailsWrittenFirst=n,e.onProgress({...n,status:"running"});return}let o=e.emailsWrittenFirst;e.emailsWrittenFirst=void 0,e.onProgress(o?{...n,status:o.status==="error"?"error":n.status,message:`${o.message}; ${n.message}`}:n)}}async linkTasksWrittenWithEmails(e,t){if(e.emailsInTwoPasses)return this.tasksLinkedBeforeTheirTurn(e,t);let n=new Map;for(let c of e.preread.get(je)?.records??[]){let l=c.ActivityId,u=c.Id;if(typeof l!="string"||l===""||typeof u!="string"||!e.remapper.isCreated(u))continue;let p=e.remapper.get(u);p&&n.set(l,p)}let o=[...new Set(t.flatMap(c=>n.get(String(c.Id))??[]))];if(o.length===0)return{rows:t,linked:0};let s,{simulated:i}=e;try{s=i?new Map(o.map(c=>[c,i.idFor(null)])):await ci(c=>this.deps.queryRecords(e.targetOrgId,c),o)}catch(c){return e.errors.push({objectApiName:st,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(tasks the platform wrote with the emails)",messages:[`Not looked up, so written as read: ${Y(c)}`]}]}),{rows:t,linked:0}}let a=t.filter(c=>{let l=String(c.Id),u=n.get(l),p=u===void 0?void 0:s.get(u);return p===void 0?!0:(e.remapper.addExisting(l,p,st),Bn(e,l),!1)}),d=t.length-a.length;return d>0&&(e.linkedCount+=d),Nr(e,st,d),{rows:a,linked:d}}tasksLinkedBeforeTheirTurn(e,t){let n=t.filter(s=>{let i=s.Id;return typeof i!="string"||e.remapper.get(i)===void 0}),o=t.length-n.length;return o>0&&(e.linkedCount+=o),Nr(e,st,o),{rows:n,linked:o}}async linkTasksOfTheEmailsWritten(e){let t=new Map;for(let i of e.preread.get(je)?.records??[]){let a=i.ActivityId,d=i.Id;if(typeof a!="string"||a===""||typeof d!="string"||co(i)||!e.remapper.isCreated(d))continue;let c=e.remapper.get(d);c&&t.set(c,a)}if(t.size===0)return;let n=[...t.keys()],{simulated:o}=e,s;try{s=o?new Map(n.map(i=>[i,o.idFor(null)])):await ci(i=>this.deps.queryRecords(e.targetOrgId,i),n)}catch(i){if(e.emailTasksNotLookedUp)return;e.emailTasksNotLookedUp=!0,e.errors.push({objectApiName:st,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(tasks the platform wrote with the emails)",messages:[`Not looked up, so written as read: ${Y(i)}`]}]});return}for(let[i,a]of s){let d=t.get(i);d===void 0||e.remapper.get(d)!==void 0||(e.remapper.addExisting(d,a,st),Bn(e,d))}}async teamOfTheOpportunities(e,t,n,o,s){let i={notKept:new Map,unread:new Map};if(!uo(t)||n.length===0)return{rows:n,lookups:new Map,held:new Map,linked:0,owners:0,values:i};let{config:a,remapper:d,simulated:c}=e,l=ui[t],u=a.decisions.defaultOf(t,l),p=c?await this.writesAs(e):void 0,f=await mi(t,n,{source:w=>this.deps.queryRecords(e.sourceOrgId,w),target:w=>this.deps.queryRecords(e.targetOrgId,w),targetIdOf:w=>d.get(w),mappedUser:w=>a.ownerMappings[w],...u!==void 0?{defaultUser:u}:{},written:s,...c?{simulated:{ownerOf:w=>a.ownerMappings[w]??(p??=c.idFor(Lh)),idFor:()=>c.idFor(o)}}:{}});f.defaulted.size>0&&u!==void 0&&e.decisionsApplied.add({kind:"set_default",objectApiName:t,field:l,to:u},f.defaulted.size);for(let[,{field:w,parentObject:b}]of f.held)b==="User"&&e.gaps?.add({kind:"required_field_missing",severity:"blocking",objectApiName:t,field:w,rows:1,detail:{type:"reference"},decisions:[...rl.required_field_missing??[]]});let h=0,g=0;for(let[w,{id:b,owners:S,notKept:R,unread:k=[]}]of f.linked){let I=String(w.Id);d.addExisting(I,b,t),d.isCreated(String(w.OpportunityId))&&(Bn(e,I),g++),S&&h++;for(let O of R)i.notKept.set(O,(i.notKept.get(O)??0)+1);for(let O of k)i.unread.set(O,(i.unread.get(O)??0)+1)}let m=f.linked.size;return m>0&&(e.linkedCount+=m),Nr(e,t,g),m>g&&e.existingRecords.push({objectApiName:t,linked:m-g,unidentified:0}),{rows:m>0?n.filter(w=>!f.linked.has(w)):n,lookups:f.lookups,held:f.held,linked:m,owners:h,values:i}}async takeTheSyncCopies(e,t,n,o,s){let i={taken:0,given:0};if(!e.readsEverythingFirst)return i;let{remapper:a,simulated:d,config:c}=e,l=g=>a.wasCreated(g)||c.writtenBefore.has(g),u=[];if(t.forEach(({source:g},m)=>{let w=g[Ra],b=g[Oa];if(typeof w!="string"||typeof b!="string"||!l(w)||!l(b))return;let S=a.get(w),R=a.get(b);S&&R&&u.push({index:m,quote:S,product:R})}),u.length===0)return i;let p=g=>s.updatable?s.updatable.has(g):s.fields?.find(m=>m.name===g)?.updateable!==!1,f;if(d)f=this.copiesASimulationFinds(e,t,u,s.keyPrefix);else{let g=S=>s.fields===void 0||s.fields.some(R=>R.name===S&&R.queryable!==!1),m=[...new Set(u.flatMap(({index:S})=>Object.keys(n[S]??{})))].filter(S=>p(S)&&g(S)),w;try{w=await pp(S=>this.deps.queryRecords(e.targetOrgId,S),u,m)}catch(S){return e.errors.push({objectApiName:Xn,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(quote lines the platform copied from their opportunity products)",messages:[`Not looked up, so written as read: a quote that syncs with its opportunity may hold a line twice. ${Y(S)}`]}]}),i}let b=new Set;for(let S of o){let R=a.get(String(S.Id));R&&b.add(R.slice(0,15))}f=fp(u,w,b)}if(f.size===0)return i;let h=d?0:await this.giveTheCopiesTheirFields(e,t,n,f,p);for(let[g,m]of f){let w=t[g],b=typeof w.source.Id=="string"?w.source.Id:void 0,S=String(m.Id);b!==void 0&&a.add(b,S,Xn),w.nullifiedFks.length>0&&this.oweToTheSecondPass(e,w.nullifiedFks.map(R=>({objectApiName:Xn,newId:S,sourceId:b,fieldName:R.field,sourceRefId:R.sourceRefId,...R.insertOnly?{insertOnly:!0}:{}})))}a.persist();for(let g of[...f.keys()].sort((m,w)=>w-m))t.splice(g,1),n.splice(g,1);return{taken:f.size,given:h}}copiesASimulationFinds(e,t,n,o){let s=new Map,{simulated:i}=e;if(!i)return s;let a=u=>typeof u=="string"&&u!==""?u.slice(0,15):void 0,d=new Map;for(let u of e.pendingFkUpdates){let p=a(u.sourceId),f=a(u.sourceRefId);u.objectApiName===Ce&&u.fieldName===rs&&p&&f&&d.set(p,f)}if(d.size===0)return s;let c=new Map;for(let u of e.preread.get(lp)?.records??[]){let p=a(u.Id),f=a(u.OpportunityId);p&&f&&c.set(p,f)}let l=new Set;for(let{index:u}of n){let{source:p}=t[u],f=a(p[Oa]),h=a(p[Ra]),g=f?c.get(f):void 0;!f||!h||!g||d.get(g)!==h||l.has(f)||(l.add(f),s.set(u,{Id:i.idFor(o)}))}return s}async giveTheCopiesTheirFields(e,t,n,o,s,i={objectApiName:Xn,recordSummary:"(quote lines the platform copied from their opportunity products)",leftAs:"Taken, and left as the platform copied them, without the fields of the source's lines"}){let a=[];for(let[u,p]of o){let f=new Set(t[u].nullifiedFks.map(g=>g.field)),h=hp(n[u]??{},p,s,f);Object.keys(h).length>0&&a.push({Id:p.Id,...h})}if(a.length===0)return 0;let d=this.deps.updateRecords,c=[],l=0;for(let u=0;u<a.length;u+=Ch){let p=a.slice(u,u+Ch);if(!d||this.isAborted){c.push(`${p.length} not sent: ${d?"the run was cancelled first":"the run sends no update"}`);continue}try{let f=await d(e.targetOrgId,i.objectApiName,p);p.forEach((h,g)=>{let m=f[g];m?.success?l++:c.push(`${String(h.Id)}: ${m?.errors.join("; ")??"no answer"}`)})}catch(f){c.push(`${p.length} not updated: ${Y(f)}`)}}return c.length>0&&e.errors.push({objectApiName:i.objectApiName,stage:"insert",failedCount:0,attemptedCount:a.length,samples:[{recordSummary:i.recordSummary,messages:[`${i.leftAs}: ${c.slice(0,3).join(" | ")}`]}]}),l}async linkTheRolesThePlatformWrote(e,t,n,o){let s={linked:0,given:0};if(t.length===0)return s;let{remapper:i,simulated:a,config:d}=e,c=new Map;if(d.writtenBefore.size>0&&t.forEach(({source:w},b)=>{let S=w.OpportunityId,R=n[b]?.[Pe];typeof S!="string"||typeof R!="string"||R===""||pi(w)&&d.writtenBefore.has(S)&&c.set(S,R)}),e.contactSentWith.size===0&&c.size===0)return s;let l=Rr(t.map(({source:w},b)=>({OpportunityId:w.OpportunityId,[Pe]:n[b]?.[Pe],IsPrimary:w.IsPrimary})),w=>i.isCreated(w)?e.contactSentWith.get(w):c.get(w));if(l.length===0)return s;let u=w=>o.updatable?o.updatable.has(w):o.fields?.find(b=>b.name===w)?.updateable!==!1,p=a?l.filter(w=>i.isCreated(String(t[w].source.OpportunityId))):[],f=l.filter(w=>!p.includes(w)),h=new Map(p.map(w=>[w,{Id:a?.idFor(o.keyPrefix)??""}]));if(f.length>0){let w=O=>o.fields===void 0||o.fields.some(A=>A.name===O&&A.queryable!==!1),b=a?[]:[...new Set(f.flatMap(O=>Object.keys(n[O]??{})))].filter(O=>u(O)&&w(O)),S=new Map(f.map(O=>[O,{opportunity:String(i.get(String(t[O].source.OpportunityId))),contact:String(n[O]?.[Pe])}])),R;try{R=await fi(O=>this.deps.queryRecords(e.targetOrgId,O),[...new Set([...S.values()].map(({opportunity:O})=>O))],b)}catch(O){e.errors.push({objectApiName:Ue,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contact roles the platform wrote with their opportunities)",messages:[`Not looked up, so written as read: an opportunity may hold the role of its contact twice. ${Y(O)}`]}]}),R=[]}let{found:k,alike:I}=hi(S,R);for(let[O,A]of k)h.set(O,A);if(I.length>0){for(let O of I)e.contactSentWith.delete(String(t[O].source.OpportunityId));e.errors.push({objectApiName:Ue,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contact roles the platform wrote with their opportunities)",messages:[Ic(I.length)]}]})}}if(h.size===0)return s;let g=a?0:await this.giveTheCopiesTheirFields(e,t,n,h,u,{objectApiName:Ue,recordSummary:"(contact roles the platform wrote with their opportunities)",leftAs:"Linked, and left as the platform wrote them, without the fields of the source's roles"}),m=0;for(let[w,b]of h){let S=t[w],R=typeof S.source.Id=="string"?S.source.Id:void 0,k=String(b.Id);if(R===void 0)continue;let I=String(S.source.OpportunityId);e.contactSentWith.delete(I),i.addExisting(R,k,Ue),i.wasCreated(I)&&(Bn(e,R),m++),S.nullifiedFks.length>0&&this.oweToTheSecondPass(e,S.nullifiedFks.map(O=>({objectApiName:Ue,newId:k,sourceId:R,fieldName:O.field,sourceRefId:O.sourceRefId,...O.insertOnly?{insertOnly:!0}:{}})))}i.persist();for(let w of[...h.keys()].sort((b,S)=>S-b))t.splice(w,1),n.splice(w,1);return e.linkedCount+=h.size,Nr(e,Ue,m),h.size>m&&e.existingRecords.push({objectApiName:Ue,linked:h.size-m,unidentified:0}),{linked:h.size,given:g}}async mapContactsOfPersonAccounts(e,t=e.preread.get(ye)?.records??[]){let n=new Map;for(let i of t){let a=i[br],d=i.Id;if(typeof a!="string"||a===""||typeof d!="string"||e.remapper.get(a))continue;let c=e.remapper.get(d);c&&n.set(c,{contact:a,account:d})}if(n.size===0||await this.personAccountsInTarget(e)===!1)return;let{simulated:o}=e;if(o){for(let[,{contact:i,account:a}]of n)e.contactsOnTheirOwn.has(i)||(e.remapper.addExisting(i,o.idFor(null)),e.remapper.isCreated(a)&&Bn(e,i));return}let s;try{s=await vc(i=>this.deps.queryRecords(e.targetOrgId,i),[...n.keys()])}catch(i){e.errors.push({objectApiName:ye,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contacts the platform wrote with the person accounts)",messages:[`Not looked up, so what points at them is left empty: ${Y(i)}`]}]});return}for(let[i,{contact:a,account:d}]of n){let c=s.get(i);if(!c){e.contactsOnTheirOwn.add(a);continue}e.remapper.addExisting(a,c),e.remapper.isCreated(d)&&Bn(e,a)}}writesAs(e){let{runningUser:t}=this.deps;return e.writesAs??=t?t(e.targetOrgId).then(n=>typeof n=="string"&&n!==""?n:void 0,()=>{}):Promise.resolve(void 0),e.writesAs}personAccountsInTarget(e){return e.personAccountsInTarget??=this.deps.describeFields(e.targetOrgId,ye).then(t=>t.some(n=>n.name===br),()=>{}),e.personAccountsInTarget}personRecordTypesInTarget(e){return e.personRecordTypes??=this.deps.queryRecords(e.targetOrgId,`SELECT Id, IsPersonType FROM RecordType WHERE SobjectType = '${ye}'`).then(t=>t.length===0?void 0:new Set(t.filter(n=>n.IsPersonType===!0||n.IsPersonType==="true").map(n=>String(n.Id).slice(0,15))),()=>{}),e.personRecordTypes}async takenAsBusinessAccounts(e,t,n){let o=t.filter(fn);if(o.length===0)return new Set;let s=await this.personAccountsInTarget(e);if(s!==!0)return new Set(s===!1?o:[]);let i=await this.personRecordTypesInTarget(e);if(!i)return new Set;let a=new Map((e.config.recordTypeMappings??[]).map(l=>[l.sourceId,l.targetId])),d=l=>{let u=l.RecordTypeId;return n&&typeof u=="string"&&u!==""?u:void 0},c=o.some(l=>d(l)===void 0)?fa((await this.objectInfoOf(e.targetOrgId,ye))?.recordTypes):void 0;return new Set(o.filter(l=>{let u=d(l),p=u===void 0?c:a.get(u);return p!==void 0&&!i.has(p.slice(0,15))}))}async noteContactsOfBusinessAccounts(e,t,n){let o=n.has("RecordTypeId")&&!(e.config.fieldExclusions[ye]??[]).includes("RecordTypeId")&&e.config.fieldMappings[ye]?.RecordTypeId===void 0;for(let s of await this.takenAsBusinessAccounts(e,t,o)){let i=s[br];typeof i=="string"&&i!==""&&e.contactsOnTheirOwn.add(i)}}async writtenWithTheirAccountOnADryRun(e,t,n,o){if(uo(t)){let i=new Set((e.preread.get("Opportunity")?.records??[]).filter(a=>!nn(e.config,a)).map(a=>String(a.Id)));return n.length===0||i.size===0?0:(await this.teamThePlatformWrites(e,t,n,i)).size}if(t===Ue)return(await this.rolesThePlatformWritesOfTheRead(e,e.preread.get(Ce)?.records??[],e.preread.get(he)?.records??[],n)).size;if(t===ye)return await this.noteContactsOfBusinessAccounts(e,n,o),0;if(t!==he)return 0;let s=n.filter(i=>fn(i)&&!e.contactsOnTheirOwn.has(String(i.Id))).length;return s>0&&await this.personAccountsInTarget(e)!==!1?s:0}async personContactsOnTheirOwn(e,t){if(t.length===0)return{rows:new Set,why:""};let n=await this.personAccountsInTarget(e);return{rows:new Set(t.filter(i=>n===!1||e.contactsOnTheirOwn.has(String(i.Id)))),why:n===!1?"the target has no person accounts":"their account is no person account in the target"}}saySentOnTheirOwn(e,t,n){t!==0&&e.errors.push({objectApiName:he,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`IsPersonAccount=true (${t} record${t===1?"":"s"})`,messages:[`Sent as contacts of their own: ${n}, and wrote no contact with it.`]}]})}linkPersonContacts(e,t){let n=0,o=0,s=0,i=0;for(let c of t){let l=String(c.Id),u=e.remapper.get(l);if(u){e.remapper.addExisting(l,u,he),n++,jw(e,l)&&o++;continue}let p=c.AccountId;typeof p=="string"&&e.remapper.get(p)?i++:s++}n>0&&(e.linkedCount+=n),Nr(e,he,o),n>o&&e.existingRecords.push({objectApiName:he,linked:n-o,unidentified:0});let a=[...s>0?[{count:s,why:mh.accountNotWritten}]:[],...i>0?[{count:i,why:mh.contactNotFound}]:[]],d=s+i;return d>0&&(e.failedCount+=d,e.errors.push({objectApiName:he,stage:"scope",failedCount:d,attemptedCount:0,samples:a.map(({count:c,why:l})=>({recordSummary:`IsPersonAccount=true (${c} record${c===1?"":"s"})`,messages:[`Not written: ${l.replace(/^not sent: /,"")}.`]}))})),{linked:n,notSent:a}}reportNotCreatable(e,t,n){t.skippedCount++,n&&t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:["Object is not createable on target org"]}]}),t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:n?`Skipped ${e.objectApiName} (target org rejects inserts on this entity)`:`Skipped ${e.objectApiName} (target org rejects inserts on this entity; the clone holds none of its records)`})}reportNotInTarget(e,t){t.skippedCount++,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:["Object is not in the target org, or the user the run writes as cannot see it: none of its records can be written there"]}]}),t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (not in the target org)`})}waitsForWhatPointsAtIt(e,t,n){return!n.scopeCache||!Je.has(e.objectApiName)?!1:t.kind==="skip"||!Ql(t)}async readCatalogAgain(e,t){let n=e.scopeCache;if(!n)return;let{config:o}=e,s=Gl.flatMap(d=>e.catalogNodes.filter(({node:c})=>c.objectApiName===d)).filter(({node:d})=>!e.failedObjects.has(d.objectApiName)&&!e.notCreatable.has(d.objectApiName)&&!o.referenceDataObjects.has(d.objectApiName));if(!s.some(({node:d})=>oh(n,d.objectApiName).size>0))return;let i=new Map([...n.entries()].map(([d,c])=>[d,new Set(c)])),a=new Set;for(let{node:d,fieldInfos:c}of s){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");let l=d.objectApiName,u=[...c],p=o.objectSoqlFilters?.[l],f=async m=>l===Rt&&e.standardPricebookId?m.filter(w=>w.Id!==e.standardPricebookId):lt(l)&&e.standardPricebookId?(await this.addStandardPricebookEntries(d,e,m,u),e.readsEverythingFirst||await this.pricesInTheCurrencyWritten(d,e,m,u),gr(m,{sellingModel:e.sellingModels})):m;if(l===Lt){if(!a.has(Bo)&&!a.has(hr))continue;let m=gn({node:d,edges:e.graph.edges,fieldInfos:u,scopedBuilder:e.scopedBuilder,scopeCache:n,rootObjectApiName:o.rootObjectApiName,rootRecordId:o.rootRecordId,extraWhere:p,fieldsLeftOut:o.fieldExclusions[l],readObjects:e.readObjects,catalog:Je});if(m.kind!=="query")continue;(await this.readMore(e,d,u,m.statements,"named by records read after the catalog",f)).length>0&&a.add(l);continue}let h=Wt(u,o.fieldExclusions[l]),g=new Set;for(let m=0;m<Hm;m++){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");let w=[...oh(n,l)].filter(S=>!g.has(S));if(w.length===0)break;for(let S of w)g.add(S);if((await this.readMore(e,d,u,new hn().buildById({objectApiName:l,selectFields:h.length>0?h:["Id"],ids:new Set(w),extraWhere:p}),m===0?"named by records read after the catalog":"named by its own records read before them",f)).length===0)break;a.add(l)}}a.size>0&&await this.readAfterTheCatalogAgain(e,t,i)}async readAfterTheCatalogAgain(e,t,n){let o=e.scopeCache;if(!o)return;let{config:s}=e,i=new Set;for(let a of t){if(this.isAborted)throw new Oe("Forge execution was aborted by user request. Remaining objects were not processed.");let d=a.objectApiName;if(e.failedObjects.has(d)||e.notCreatable.has(d)||s.referenceDataObjects.has(d))continue;let c=n.get(d),l=o.isRead(d)?o.scopeOf(d):void 0,u=new Set([...o.get(d)??[]].filter(b=>!c?.has(b)&&!l?.has(b))),p=new Set(e.graph.edges.filter(b=>b.targetObject===d&&i.has(b.sourceObject)).map(b=>b.sourceObject));if(u.size===0&&p.size===0)continue;let f=await this.fieldsReadAgain(e,a);if(!f)continue;let{fields:h}=f,g=s.objectSoqlFilters?.[d],m=[];if(u.size>0){let b=Wt(h,s.fieldExclusions[d]);m.push(...new hn().buildById({objectApiName:d,selectFields:b.length>0?b:["Id"],ids:u,extraWhere:g}))}if(p.size>0){let b=gn({node:a,edges:e.graph.edges,fieldInfos:h,scopedBuilder:e.scopedBuilder,scopeCache:o,rootObjectApiName:s.rootObjectApiName,rootRecordId:s.rootRecordId,extraWhere:g,fieldsLeftOut:s.fieldExclusions[d],readObjects:e.readObjects,catalog:Je,under:p});b.kind==="query"&&m.push(...b.statements)}m.length===0||(await this.readMore(e,a,h,m,"for what the catalog read again brought")).length===0||(i.add(d),f.described&&this.withoutFileContent(e,d,f.described,!0))}}async fieldsReadAgain(e,t){let n=e.preread.get(t.objectApiName);if(n)return{fields:[...n.fieldInfos]};try{let o=await this.deps.describeFields(e.sourceOrgId,t.objectApiName);return{fields:o.filter(s=>!In(s)),described:o}}catch{return}}async readMore(e,t,n,o,s,i=async a=>a){let a=e.scopeCache;if(!a)return[];let{config:d}=e,c=t.objectApiName,l=d.maxRecordsPerObject?Math.floor(d.maxRecordsPerObject):0,u=l>0?l-(e.readByObject.get(c)??0):0;if(l>0&&u<=0)return o.length>0&&e.cappedObjects.add(c),[];let p=a.isRead(c),f=new Set(p?a.scopeOf(c)??[]:[]),h=m=>typeof m.Id!="string"||!f.has(m.Id),g;try{let m=await jr(u>0?Di(o,u,{byIdCount:o.length}):{kind:"query",statements:o,byIdCount:o.length},E=>this.deps.queryRecords(e.sourceOrgId,E,()=>e.truncatedObjects.add(c)),void 0,()=>e.cappedObjects.add(c));Fr(e,m);let w=m.filter(h);this.keepWhatStatusesNeed(e,t,w,void 0);let b=e.heldForExclusions.get(c),S=0;for(let E of b?w:[]){let $=E.Id;typeof $!="string"||b?.get($)?.namedBy===void 0||(b.delete($),S++)}S>0&&(b?.size===0&&e.heldForExclusions.delete(c),e.failedCount-=S,e.readByObject.set(c,(e.readByObject.get(c)??S)-S));let R=new Set(e.heldForExclusions.get(c)?.keys()??[]);this.holdBackWhatExclusionsCost(e,t,n,w,void 0,await this.excludedByKeyPrefix(e,c,n));let k=[...e.heldForExclusions.get(c)??[]].filter(([E])=>!R.has(E));if(this.leaveToThePlatform(e,c,w,n),g=(await i(w)).filter(h),_o(a,c,g,n,{settle:!1,keyPrefixes:await this.keyPrefixesNamedBy(e,n)}),a.addReadAgain(c,g.flatMap(E=>typeof E.Id=="string"?[E.Id]:[])),await this.notePastDraft(e,c,g),g.length===0&&k.length===0)return[];if(d.files&&d.stream?.everything!==!0){let E=g.flatMap($=>typeof $.Id=="string"?[$.Id]:[]);e.fileScope.set(c,[...e.fileScope.get(c)??[],...E])}p||e.skippedCount--;let I=e.preread.get(c),O=I?.records??[],A=lt(c)?gr([...O,...g],{sellingModel:e.sellingModels}):[...O,...g],x=A.length-O.length,j=I?.createableSet??new Set(n.filter(E=>E.createable).map(E=>E.name));if(e.preread.set(c,I?{...I,records:A}:{fieldInfos:n,createableSet:j,records:A,targetSetsPending:null}),e.readByObject.set(c,(e.readByObject.get(c)??0)+x+k.length),d.dryRun){let E=await this.writtenWithTheirAccountOnADryRun(e,c,lt(c)?[]:g,j);e.onProgress({objectName:c,status:"running",progress:0,message:`[dry-run] ${c}: ${x-E} more record(s) would be inserted`+(E>0?`, ${E} more would be written by the platform with ${Hn(c)}`:"")+`, ${s}`+Os(Rs(k.map(([,$])=>$)),!0)})}}catch(m){if(m instanceof Oe)throw m;return e.errors.push({objectApiName:c,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(more rows, ${s})`,messages:[Y(m)]}]}),[]}return await this.readWhatTheyCannotBeWrittenWithout(e,c,n,g),g}async addStandardPricebookEntries(e,t,n,o){let s=t.standardPricebookId;if(!s)return;let i=l=>dd(l,t.sellingModels),a=new Set,d=new Set,c=new Set;for(let l of n){let u=l.Id;if(typeof u=="string"&&c.add(u),l[Ot]===s)continue;let p=l[kt];typeof p=="string"&&p&&(a.add(p),d.add(i(l)))}if(a.size!==0)try{let l=new hn().buildJoining({objectApiName:e.objectApiName,selectFields:Wt(o,t.config.fieldExclusions[e.objectApiName]),split:{field:kt,ids:a},whole:{field:Ot,ids:new Set([s])}}),u=0;for(let p of l)for(let f of await this.deps.queryRecords(t.sourceOrgId,p)){let h=f.Id;typeof h=="string"&&c.has(h)||d.has(i(f))&&(n.push(f),Fr(t,[f]),u++)}u>0&&t.onProgress({objectName:e.objectApiName,status:"scanning",progress:50,message:`Added ${u} standard price book entr${u===1?"y":"ies"} the custom prices depend on`})}catch(l){t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(standard price book entries)",messages:[Y(l)]}]})}}async pricesInTheCurrencyWritten(e,t,n,o,s){let i=await this.priceCurrencyInput(t,n,o);if(!i)return;let a={...i,...s?{wanted:s}:{}},d=s?t.pricesTheGateCounted:void 0,c=ma(a).filter(g=>!d||d.has(ga(g))),l=[],u=[...new Set(c.map(({currency:g})=>g))].filter(g=>/^[A-Z]{3}$/.test(g));if(u.length>0)try{let g=new hn().buildJoining({objectApiName:e.objectApiName,selectFields:Wt(o,t.config.fieldExclusions[e.objectApiName]),split:{field:kt,ids:new Set(c.map(({product:m})=>m).filter(m=>m!==""))},whole:{field:Ot,ids:new Set(c.map(({book:m})=>m).filter(m=>m!==""))},extraWhere:`${ut} IN (${u.map(m=>`'${m}'`).join(", ")})`});for(let m of g)l.push(...await this.deps.queryRecords(t.sourceOrgId,m))}catch(g){t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(prices in the currency written)",messages:[Y(g)]}]});return}let p=t.sample;if(p?.drawn.has(e.objectApiName)){let g=l.filter(m=>this.inThePlan(p,e.objectApiName,String(m.Id)));l.length=0,l.push(...g)}let f=wa(a,d?l.filter(g=>d.has(ha(ip(g,t.sellingModels),String(g[ut])))):l),h=new Set(n);n.length=0,n.push(...f.rows),Fr(t,f.rows.filter(g=>!h.has(g)));for(let[g,m]of f.standsFor)t.remapper.alias(g,m),t.prices.standsFor.set(g,m);for(let[g,m]of t.prices.standsFor){let w=f.standsFor.get(m);w!==void 0&&(t.remapper.alias(g,w),t.prices.standsFor.set(g,w))}for(let[g,m]of f.convertedInto)t.prices.convertedInto.set(g,m);for(let[g,m]of f.written)t.prices.written.set(g,m);for(let[g,m]of f.keys)t.prices.keys.set(g,m);t.pricesSwappedSaid.push(...f.said),!(f.said.length===0||s)&&t.onProgress({objectName:e.objectApiName,status:"scanning",progress:50,message:ya(f.said).join("; ")})}async priceCurrencyInput(e,t,n){let{standardPricebookId:o}=e;if(!o||!n.some(d=>d.name===ut)||!t.some(d=>typeof d[ut]=="string"))return;let s=await this.runCurrencies(e);if(!s)return;let{target:i}=s,a=this.priceCurrencyWrittenIn(e,i);return{prices:t,standardBookId:o,sellingModels:e.sellingModels,writtenIn:a,active:i.active}}priceCurrencyWrittenIn(e,t){return n=>{let o={[ut]:n};e.config.decisions.applyToRow(We,o,void 0,new Bi);let s=o[ut];return typeof s=="string"&&t.active.has(s)?s:Kc(void 0,t)?.to}}async pricesTheGateCounts(e){let t=e.preread.get(We);if(!t||!e.readsEverythingFirst)return 0;let n=await this.priceCurrencyInput(e,t.records,t.fieldInfos);if(!n)return 0;let o=ma({...n,wanted:this.currenciesTheirLinesMayWant(e,t.records,n.active)});return e.pricesTheGateCounted=new Set(o.map(ga)),o.length}currenciesTheirLinesMayWant(e,t,n){let o=new Set(t.flatMap(d=>typeof d.Id=="string"?[d.Id]:[])),{decisions:s}=e.config,i=d=>{if(s.changesRowsOf(d))return!0;if(!bo(d))return!1;let c=e.preread.get(d)?.fieldInfos.find(l=>l.name===Vc[d])?.referenceTo?.[0];return c===void 0||i(c)},a=new Map;for(let[d,{record:c,field:l}]of Object.entries(ns)){let u=i(c);for(let p of e.preread.get(d)?.records??[]){let f=p[Er];if(typeof f!="string"||typeof p[l]!="string")continue;let h=e.prices.standsFor.get(f)??f;if(!o.has(h))continue;let g=p[ze],m=!u&&typeof g=="string"&&n.has(g)?[g]:[...n],w=a.get(h)??new Set;for(let b of m)w.add(b);a.set(h,w)}}return a}currenciesTheirLinesWant(e,t){let n=new Set(t.flatMap(s=>typeof s.Id=="string"?[s.Id]:[])),o=new Map;for(let[s,{field:i}]of Object.entries(ns))for(let a of e.preread.get(s)?.records??[]){let d=a[Er];if(typeof d!="string")continue;let c=e.prices.standsFor.get(d)??d;if(!n.has(c))continue;let l=this.currencyTheirRecordWentIn(e,a,i);if(l===void 0)continue;let u=o.get(c)??new Set;u.add(l),o.set(c,u)}return o}currencyTheirRecordWentIn(e,t,n){let o=t[n];if(typeof o!="string"||e.remapper.get(o)===void 0)return;let s=e.currencyChangesById.get(o)?.to;if(s!==void 0)return s;let i=t[ze];return typeof i=="string"&&i!==""?i:void 0}pricedInTheirRecordsCurrency(e,t,n){let o=ns[t]?.field;return o===void 0||e.prices.written.size===0?n:n.map(s=>{let i=s[Er];if(typeof i!="string")return s;let a=e.prices.standsFor.get(i)??i,d=e.prices.keys.get(a),c=d?this.currencyTheirRecordWentIn(e,s,o):void 0;if(d===void 0||c===void 0)return s;let l=e.prices.written.get(ha(d,c));return l===void 0||l===a||l===i||e.remapper.get(l)===void 0?s:{...s,[Er]:l}})}async objectInfoOf(e,t){if(!this.deps.describeObject)return null;try{return await this.deps.describeObject(e,t)}catch{return null}}async toWriteAtTheGate(e,t,n,o=0){let s=n.records.filter(l=>!nn(e.config,l)),i=n.records.length-s.length,a=s.length>0?await this.heldBackAtTheGate(e,t,n,s):[],d=a.length>0,c={...i>0?{writtenBefore:i}:{},...d?fh(a,s.length):{}};return{objectApiName:t,rows:d?[]:s,...Object.keys(c).length>0?{leftOut:c}:{},...o>0&&!d?{mayAdd:o}:{}}}async withoutWhatThePlatformWrites(e,t){let n=l=>t.find(u=>u.objectApiName===l)?.rows??[],o=new Map,s=new Set(n("Opportunity").map(l=>String(l.Id)));for(let l of t)if(!(!uo(l.objectApiName)||l.rows.length===0)){if(s.size===0)break;o.set(l.objectApiName,await this.teamThePlatformWrites(e,l.objectApiName,l.rows,s))}let i=await this.personContactsThePlatformWrites(e,n(ye),n(he));i.size>0&&o.set(he,i);let a=await this.rolesThePlatformWritesOfTheRead(e,n(Ce),n(he),n(Ue)),d=await this.rolesOfOpportunitiesWrittenBefore(e,n(Ue).filter(l=>!a.has(l))),c=new Set([...a,...d.linked]);return c.size>0&&o.set(Ue,c),t.map(l=>{let u=o.get(l.objectApiName),p=l.objectApiName===Ue&&d.mayBe>0?{mayBeByThePlatform:{rows:d.mayBe,before:!0}}:{};return!u||u.size===0?{...l,...p}:{...l,rows:l.rows.filter(f=>!u.has(f)),leftOut:{...l.leftOut,byThePlatform:u.size},...p}})}async withoutWhatTheTargetHoldsByValue(e,t){let{config:n}=e,o=[];for(let s of t){let{objectApiName:i,rows:a}=s,d=e.preread.get(i);if(a.length===0||s.counted||!d){o.push(s);continue}let c=await(d.targetSetsPending??tn(this.deps.describeFields,e.targetOrgId,i).then(k=>({ok:!0,sets:k}),k=>({ok:!1,error:k})));if(!c.ok){o.push(s);continue}let l=or(d.createableSet,c.sets.creatable),u=new Set(n.fieldExclusions[i]??[]),p=n.fieldMappings[i]??{},f=new Set(Object.values(p)),h=new Set(await e.maskedSourceFields(i).catch(()=>[])),g=n.anonymization,m=new Set(e.anonymize&&g?g.fields[i]??this.detectedPersonalFields(e,g,i,d.fieldInfos):[]),w=new Set(e.contactPoints?ua(d.fieldInfos).map(({name:k})=>k):[]),b=n.decisions.truncatedFieldsOf(i),S=c.sets.fields.filter(({name:k,unique:I,externalId:O})=>I===!0&&l.has(k)&&!(n.upsertMode==="auto"&&O===!0)&&!u.has(k)&&p[k]===void 0&&!f.has(k)&&!h.has(k)&&!m.has(k)&&!w.has(k)&&!b.has(k)&&!(i===ye&&k.endsWith("__pc"))),R=new Map;for(let k of S){let{name:I}=k,O=new Map;for(let j of a){let E=j[I];if(typeof E!="string"||E===""||Fh.test(E))continue;let $=Pn(k,E);O.has($)||O.set($,E)}let A=[...O.values()];if(A.length===0)continue;let x=new Set;try{let j=Me(i),E=Me(I);for(let $ of Cn(A,Ph)){let L=await this.deps.queryRecords(e.targetOrgId,`SELECT ${E} FROM ${j} WHERE ${E} IN (${$})`);for(let Q of L){let G=Q[I];typeof G=="string"&&x.add(Pn(k,G))}}}catch{continue}for(let j of a){let E=j[I];typeof E=="string"&&x.has(Pn(k,E))&&!R.has(j)&&R.set(j,I)}}if(R.size===0){o.push(s);continue}o.push({...s,rows:a.filter(k=>!R.has(k)),leftOut:{...s.leftOut,linkedByValue:{rows:R.size,fields:[...new Set(R.values())]}}})}return o}async rolesOfOpportunitiesWrittenBefore(e,t){let{config:n}=e,o={linked:new Set,mayBe:0};if(n.writtenBefore.size===0)return o;let s=l=>l.slice(0,15),i=new Map;for(let l of t){let u=l.OpportunityId,p=l[Pe];typeof u!="string"||typeof p!="string"||p===""||pi(l)&&n.writtenBefore.has(u)&&i.set(s(u),p)}if(i.size===0)return o;let a=Rr(t,l=>i.get(s(l))),d=l=>typeof l=="string"&&l!==""?n.writtenBefore.get(l)??e.remapper.get(l):void 0,c=new Map;for(let l of a){let u=d(t[l].OpportunityId),p=d(t[l][Pe]);u!==void 0&&p!==void 0&&c.set(l,{opportunity:u,contact:p})}if(c.size===0)return{...o,mayBe:a.length};try{let l=await fi(p=>this.deps.queryRecords(e.targetOrgId,p),[...new Set([...c.values()].map(({opportunity:p})=>p))]),{found:u}=hi(c,l);return{linked:new Set([...u.keys()].map(p=>t[p])),mayBe:a.length-c.size}}catch{return{...o,mayBe:a.length}}}async rolesThePlatformWritesOfTheTables(e,t,n,o){let{config:s}=e,i=new Set(n.map(l=>l.objectApiName));if(!i.has(Ce)||(s.fieldExclusions[Ce]??[]).includes(Pe)||s.fieldMappings[Ce]?.[Pe]!==void 0)return 0;if([Ce,Ue,he].some(l=>o.has(l)))return;let d=l=>t.findIndex(u=>u.objectApiName===l),c=i.has(he)&&d(he)<d(Ce);try{if(!(await this.deps.describeFields(e.sourceOrgId,Ce)).some(k=>k.name===Pe&&k.createable)||!(await tn(this.deps.describeFields,e.targetOrgId,Ce)).creatable.has(Pe))return 0;let p=k=>s.objectSoqlFilters?.[k],f=s.stream?.resumeAfter.get(Ue),h=p(Ce),g=p(he),m=[...p(Ue)?[`(${p(Ue)})`]:[],`Opportunity.${Pe} != null`,...f&&Pt.test(f.lastId)?[`Id > '${f.lastId}'`]:[],...h?[`OpportunityId IN (SELECT Id FROM ${Ce} WHERE (${h}))`]:[],...c&&g?[`${Pe} IN (SELECT Id FROM ${he} WHERE (${g}))`]:[]],w=await this.deps.queryRecords(e.sourceOrgId,`SELECT Id, OpportunityId, ${Pe}, IsPrimary, Opportunity.${Pe} FROM ${Ue} WHERE ${m.join(" AND ")} ORDER BY Id LIMIT ${Xf+1}`);if(w.length>Xf)return;let b=k=>c||s.writtenBefore.has(k)||e.remapper.get(k)!==void 0,S=k=>{let I=k.Opportunity,O=I!==null&&typeof I=="object"?I[Pe]:void 0;return typeof O=="string"&&O!==""?O:void 0},R=new Map;for(let k of w){let I=k.OpportunityId,O=S(k);typeof I!="string"||O===void 0||s.writtenBefore.has(I)||!b(O)||R.set(I.slice(0,15),O)}return Rr(w,k=>R.get(k.slice(0,15))).length}catch{return}}rolesThePlatformMayWriteOfTheCounts(e,t,n){let{config:o}=e;return(o.fieldExclusions[Ce]??[]).includes(Pe)||o.fieldMappings[Ce]?.[Pe]!==void 0?0:Math.min(t,n)}async rolesThePlatformWritesOfTheRead(e,t,n,o){if(o.length===0||t.length===0)return new Set;let{config:s,remapper:i}=e;if((s.fieldExclusions[Ce]??[]).includes(Pe)||s.fieldMappings[Ce]?.[Pe]!==void 0)return new Set;let a=e.preread.get(Ce);if(!a?.createableSet.has(Pe))return new Set;let d=await(a.targetSetsPending??tn(this.deps.describeFields,e.targetOrgId,Ce).then(p=>({ok:!0,sets:p}),p=>({ok:!1,error:p})));if(!d.ok||!d.sets.creatable.has(Pe))return new Set;let c=p=>p.slice(0,15),l=new Set(n.map(p=>c(String(p.Id)))),u=new Map;for(let p of t){let f=p.Id,h=p[Pe];typeof f!="string"||typeof h!="string"||h===""||nn(s,p)||!l.has(c(h))&&i.get(h)===void 0||u.set(c(f),h)}return u.size===0?new Set:new Set(Rr(o,p=>u.get(c(p))).map(p=>o[p]))}async teamThePlatformWrites(e,t,n,o){let{config:s}=e,i=s.decisions.defaultOf(t,ui[t]),a=await this.writesAs(e);try{let d=await mi(t,n,{source:c=>this.deps.queryRecords(e.sourceOrgId,c),target:c=>this.deps.queryRecords(e.targetOrgId,c),targetIdOf:c=>o.has(c)?c:void 0,mappedUser:c=>s.ownerMappings[c],...i!==void 0?{defaultUser:i}:{},written:[],simulated:{ownerOf:c=>s.ownerMappings[c]??a??`${Lh}gate`,idFor:()=>""}});return new Set(d.linked.keys())}catch{return new Set}}async personContactsThePlatformWrites(e,t,n){let o=n.filter(d=>fn(d)&&!e.contactsOnTheirOwn.has(String(d.Id)));if(o.length===0)return new Set;if(await this.personAccountsInTarget(e)===!1)return new Set;let i=(e.preread.get(ye)?.createableSet??new Set).has("RecordTypeId")&&!(e.config.fieldExclusions[ye]??[]).includes("RecordTypeId")&&e.config.fieldMappings[ye]?.RecordTypeId===void 0,a=new Set([...await this.takenAsBusinessAccounts(e,t,i)].map(d=>String(d[br])));return new Set(o.filter(d=>!a.has(String(d.Id))))}async heldBackAtTheGate(e,t,n,o){let s=e.graph.nodes.find(l=>l.objectApiName===t);if(!s)return[];let i=await this.objectInfoOf(e.targetOrgId,t);if(!i||i.recordTypes.length===0)return[];if(!(e.recordTypeMapper!==null&&e.config.recordTypeMappings!==void 0)&&!i.recordTypes.some(l=>!l.available&&!l.master))return[];let d=await(n.targetSetsPending??tn(this.deps.describeFields,e.targetOrgId,t).then(l=>({ok:!0,sets:l}),l=>({ok:!1,error:l}))),c=d.ok?or(n.createableSet,d.sets.creatable):n.createableSet;return this.recordTypesHeldBack(s,o,i,c,e)}async recordTypesHeldBack(e,t,n,o,s){let{config:i}=s;if(!n||n.recordTypes.length===0)return[];if(!o.has("RecordTypeId"))return[];if((i.fieldExclusions[e.objectApiName]??[]).includes("RecordTypeId"))return[];if(i.fieldMappings[e.objectApiName]?.RecordTypeId)return[];let a=t.map(c=>({RecordTypeId:i.recordTypeDecisions.get(String(c.RecordTypeId))?.to===null?void 0:c.RecordTypeId}));s.recordTypeMapper&&i.recordTypeMappings&&(a=s.recordTypeMapper.apply(a,i.recordTypeMappings));let d=new Map;for(let c of a){let l=c.RecordTypeId;typeof l=="string"&&d.set(l,(d.get(l)??0)+1)}return[...el(e.objectApiName,a,n.recordTypes),...await this.typesTheTargetLacks(s,e.objectApiName,d,n)]}oweToTheSecondPass(e,t){let n=this.withoutSyncedQuotes(e,t);if(e.secondPassInStore&&e.store){for(let o of n)e.store.owe(o);return}if(e.store)for(let o of n)e.store.owe(o);e.pendingFkUpdates.push(...n)}withoutSyncedQuotes(e,t){if(e.config.stream?.everything!==!0)return t;let n=t.filter(o=>o.objectApiName!==Ce||o.fieldName!==rs);return e.syncedQuotesLeft+=t.length-n.length,n.length===t.length?t:n}saySyncedQuotesLeft(e){let t=e.syncedQuotesLeft;t!==0&&(e.syncedQuotesLeft=0,e.errors.push({objectApiName:Ce,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(${Ce}.${rs})`,messages:[`Left empty on ${t} opportunit${t===1?"y":"ies"}: filled in, the target syncs the quote at once and writes its lines over the opportunity's products the run copied. Start the sync in the target to fill it in.`]}]}))}patchedInTheJournal(e){let{store:t}=e;if(!(!t||e.secondPassInStore))return Nh(t)}oweStatus(e,t,n,o){e.store?e.store.oweStatus(t,n,o):e.deferredStatuses.push({objectApiName:t,id:n,status:o})}countWrites(e,t,n){e.simulated?e.wouldInsertCount+=n.successCount:e.successCount+=n.successCount,e.updatedCount+=n.updatedCount,n.mayHaveBeenWritten&&n.mayHaveBeenWritten.length>0&&e.mayHaveBeenWritten.set(t,[...e.mayHaveBeenWritten.get(t)??[],...n.mayHaveBeenWritten]),e.linkedCount+=n.linkedExistingCount,e.linkedToCreatedCount+=n.linkedToCreatedCount??0,e.failedCount+=n.failureCount,this.oweToTheSecondPass(e,n.pendingFkUpdates),n.writtenWithoutFields&&this.countWrittenWithoutFields(e,t,n.writtenWithoutFields);for(let{field:o,recordId:s}of n.leftEmptyByFilter??[])this.noteLeftEmptyByFilter(e,t,o,s);for(let o of n.withTheirRecord??[])Bn(e,o);(n.linkedExistingCount>0||n.unidentifiedExistingCount>0)&&e.existingRecords.push({objectApiName:t,linked:n.linkedExistingCount,...n.linkedToCreatedCount?{linkedToCreated:n.linkedToCreatedCount}:{},unidentified:n.unidentifiedExistingCount}),n.failureCount>0&&e.errors.push({objectApiName:t,stage:"insert",failedCount:n.failureCount,attemptedCount:n.successCount+n.updatedCount+n.linkedExistingCount+n.failureCount,samples:n.errorSamples})}countWrittenWithoutFields(e,t,n){e.writtenWithoutFields.set(t,Ui(e.writtenWithoutFields.get(t),n))}noteLeftEmptyByFilter(e,t,n,o){let s=e.leftEmptyByFilter.get(t);s||(s=new Map,e.leftEmptyByFilter.set(t,s));let i=s.get(n)??{records:0,ids:[]};i.records++,i.ids.length<Dm&&i.ids.push(o),s.set(n,i)}sayRecordTypeNote(e,t,n){e.errors.push({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:[Bl(n)]})}oweLookupsOfRowsWrittenBefore(e,t,n,o,s){let{config:i}=e,a=new Set(e.graph.nodes.filter(u=>u.included).map(u=>u.objectApiName)),d=new Set(i.fieldExclusions[t.objectApiName]??[]),c=i.fieldMappings[t.objectApiName]??{},l=o.filter(u=>u.isReference&&u.name!=="RecordTypeId"&&!d.has(u.name)&&Ua(u,s,c[u.name])&&(u.referenceTo??[]).some(p=>a.has(p)));if(l.length!==0)for(let u of n){let p=u.Id;if(typeof p!="string")continue;let f=i.writtenBefore.get(p);if(f)for(let h of l){let g=u[h.name];if(typeof g!="string"||!g||i.writtenBefore.has(g)&&!e.store?.owesUntold(p))continue;let[m]=this.withoutSyncedQuotes(e,[{objectApiName:t.objectApiName,newId:f,sourceId:p,fieldName:c[h.name]??h.name,sourceRefId:g}]);m&&(e.secondPassInStore&&e.store?e.store.owe(m,!0):e.owedToRowsWrittenBefore.push(m))}}}owedNowWritten(e){if(e.owedToRowsWrittenBefore.length===0)return[];let t=[],n=[];for(let o of e.owedToRowsWrittenBefore)e.remapper.get(o.sourceRefId)?t.push(o):n.push(o);return e.owedToRowsWrittenBefore=n,t}sayLookupsOutsideTheClone(e,t){let n=new Map,o=this.keepLookupsInTheClone(e,t,n);return this.sayLeftEmpty(e,n),o}keepLookupsInTheClone(e,t,n){let o=[];for(let s of t){if(e.remapper.get(s.sourceRefId)||e.idsRead.has(s.sourceRefId)){o.push(s);continue}let i=this.objectPointedAt(e,s);if(i!==void 0&&(e.failedObjects.has(i)||e.notCreatable.has(i)||e.notInTarget.has(i))){o.push(s);continue}let a=n.get(s.objectApiName)??new Map,d=`${s.fieldName}|${i??""}`,c=a.get(d)??{field:s.fieldName,parent:i,count:0};c.count++,a.set(d,c),n.set(s.objectApiName,a)}return o}sayLeftEmpty(e,t){for(let[n,o]of t)e.errors.push({objectApiName:n,stage:"scope",failedCount:0,attemptedCount:0,samples:[...o.values()].sort((s,i)=>i.count-s.count).slice(0,3).map(({field:s,parent:i,count:a})=>({recordSummary:`${i===void 0?s:`${s} \u2192 ${i}`} (${a} record${a===1?"":"s"})`,messages:[`Written with the lookup empty: the ${i===void 0?"":`${i} `}record it points at is not in the clone.`]}))})}async secondPassFromTheJournal(e){let{store:t}=e;if(!t)return null;let n=new Rp({remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:e.targetOrgId,enabled:!e.config.dryRun,onProgress:e.onProgress,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:Nh(t),onAnswered:()=>t.flush(),onRefusedByFilter:(u,p,f)=>this.noteLeftEmptyByFilter(e,u,p,f),...this.secondPassOfTheSample(e)}),o=new Map,s=e.config.stream?.secondPassPageSize??_m,i=e.pendingFkUpdates.splice(0,e.pendingFkUpdates.length),a=u=>t.wasPatched(u.newId,u.fieldName),d=new bp;for(let u of i)d.note(0,u.newId);let c=1;for(let u of t.owedPages(s)){for(let{update:p}of u)a(p)||d.note(c,p.newId);c++}let l=u=>d.spans(u.newId);await n.patch(this.keepLookupsInTheClone(e,i,o),l);for(let u of t.owedPages(s)){let p=u.filter(({update:f,toRowWrittenBefore:h})=>!a(f)&&(!h||e.remapper.get(f.sourceRefId)!==void 0)).map(({update:f})=>f);await n.patch(this.keepLookupsInTheClone(e,p,o),l)}return await n.sendHeld(),this.sayLeftEmpty(e,o),n.finish()}objectPointedAt(e,t){let n=e.config.fieldMappings[t.objectApiName]??{},s=e.preread.get(t.objectApiName)?.fieldInfos.find(a=>a.isReference&&(n[a.name]??a.name)===t.fieldName)?.referenceTo??[];if(s.length===1)return s[0];let i=t.sourceRefId.slice(0,3);return s.find(a=>e.sourceKeyPrefixes.get(a)===i)}applyRecordTypeDecisions(e,t,n,o){let{config:s}=e,i=new Map,a=e.recordTypeMapper&&s.recordTypeMappings?new Set(s.recordTypeMappings.map(d=>d.sourceId)):void 0;return o.forEach((d,c)=>{let l=n[c]?.cleaned.RecordTypeId;if(typeof l!="string"||l===""||!("RecordTypeId"in d))return;let u=s.recordTypeDecisions.get(l);if(u){u.to===null&&delete d.RecordTypeId,e.decisionsApplied.add({kind:"map_record_type",objectApiName:t,from:u.from,...u.to!==null?{to:u.to}:{}});return}!e.simulated||!a||Pw.test(l)||a.has(l)||i.set(l,(i.get(l)??0)+1)}),i}simulateWrite(e,t,n,o,s,i,a,d,c=new Map){let{simulated:l}=e;if(!l)return;let u=t.objectApiName,p=new Set,f=0;i({objectName:u,status:"running",progress:0,recordCount:n.records.length,message:`Simulating the write of ${n.records.length} ${u} records: nothing is sent...`});for(let[h,g]of n.cleaned.entries()){let m=n.records[h]??{},w=d?il(u,m,g.source,d):[];if(w.length>0){s.failureCount++,s.errorSamples.length<3&&s.errorSamples.push({recordSummary:iu(m),messages:[`REQUIRED_FIELD_MISSING: Required fields are missing: [${w.map(k=>k.name).join(", ")}]`]});continue}let b=l.idFor(o),S=typeof g.source.Id=="string"?g.source.Id:void 0,R=c.get(m);if(R!==void 0){s.linkedExistingCount++,f++,p.add(R),S!==void 0&&e.remapper.addExisting(S,b,u);continue}s.successCount++,a&&!nu(n.records[h]??{})&&a(g),S!==void 0&&e.remapper.add(S,b,u);for(let k of g.nullifiedFks)s.pendingFkUpdates.push({objectApiName:u,newId:b,sourceId:S,fieldName:k.field,sourceRefId:k.sourceRefId,...k.insertOnly?{insertOnly:!0}:{}})}f>0&&i({objectName:u,status:"running",progress:0,message:`[dry-run] ${u}: ${f} fewer would be inserted, linked to the record${f===1?"":"s"} the target holds under the same ${[...p].join(", ")}, which its refusal of the row names`})}holdBackSkippedRows(e,t,n,o,s){let{config:i}=e;if(!i.decisions.skipsRowsOf(t.objectApiName))return n;let a=new Set(i.fieldExclusions[t.objectApiName]??[]),d=new Map(Object.entries(i.fieldMappings[t.objectApiName]??{}).map(([u,p])=>[p,u])),c=n.filter(u=>{let p=u.RecordTypeId;return!i.decisions.holdsBack(t.objectApiName,f=>{let h=d.get(f)??f;return a.has(h)?void 0:u[h]},xh(i,typeof p=="string"?p:void 0),e.decisionsApplied,s)}),l=n.length-c.length;return l>0&&o({objectName:t.objectApiName,status:"running",progress:0,message:`${t.objectApiName}: ${l} record${l===1?"":"s"} held back, as decided on the gaps`}),c}async findGaps(e,t,n){let{gaps:o}=e;if(!o)return new Map;let s=t.objectApiName,i=new Map([...n.recordTypes?.values()??[]].map(d=>[d.recordType,d]));for(let{picklistChanges:d=[]}of n.cleanedRecords){let c=sl(s,d,l=>{if(l.recordType!==void 0)return i.get(l.recordType)?.picklists.get(l.field)?.values;let u=n.picklistValuesByField?.get(l.field);return u?[...u]:void 0});for(let l of c)o.add(l)}if(n.unmapped.size>0){let d=await this.sourceRecordTypesOf(e,s);o.knowRecordTypes(s,"source",d);for(let[c,l]of n.unmapped){let u=d.find(p=>p.recordTypeId.slice(0,15)===c.slice(0,15))?.developerName??c;o.add(Ai("record_type_unmapped",s,u,l,qh(n.targetObject)))}}let a=n.targetFields;return a?(al({objectApiName:s,rows:n.recordsToInsert.map((d,c)=>{let l=n.cleanedRecords[c]?.cleaned.RecordTypeId;return{payload:d,source:n.cleanedRecords[c]?.source??{},typed:typeof l=="string"&&n.recordTypes?.has(l)===!0}}),targetFields:a,picklistValuesByField:n.picklistValuesByField,picklistFields:n.picklistFields??new Map},o),await this.currencyGaps(e,s,a,n.cleanedRecords),this.uniqueValueGaps(e,s,a,n.recordsToInsert)):new Map}sourceRecordTypesOf(e,t){let n=e.sourceRecordTypes.get(t);if(!n){let o=this.deps.describeObject;n=o?o(e.sourceOrgId,t).then(s=>this.namedRecordTypes(e.recordTypeRows,e.sourceOrgId,s.recordTypes),()=>[]):Promise.resolve([]),e.sourceRecordTypes.set(t,n)}return n}currenciesFor(e,t,n,o){return t?.some(i=>i.name===ze&&i.createable)===!0&&o(ze)&&n.some(i=>typeof i[ze]=="string"&&i[ze]!=="")?this.runCurrencies(e):Promise.resolve(void 0)}async parentCurrenciesFor(e,t,n,o){if(e.currencyChangesById.size===0)return;let s=n?.find(a=>a.name===ze);if(!s||s.createable&&!bo(t)||!o.some(a=>typeof a[ze]=="string"&&a[ze]!==""))return;let i=await e.currencies;return{changeOf:a=>e.currencyChangesById.get(a),...i?{currencies:i}:{}}}runCurrencies(e){let t=this.deps.queryTooling;return e.currencies??=Hc(n=>this.deps.queryRecords(e.sourceOrgId,n),n=>this.deps.queryRecords(e.targetOrgId,n),t?{source:n=>t(e.sourceOrgId,n),target:n=>t(e.targetOrgId,n)}:{}),e.currencies}async currencyGaps(e,t,n,o){if(!n.some(d=>d.name===ze&&d.createable))return;let s=new Map,i=new Map;for(let{source:d,currencyChange:c}of o){let l=d[ze];if(typeof l!="string"||l===""||(s.set(l,(s.get(l)??0)+1),!c||c.chosenBy==="decision"))continue;let u=i.get(l)??{to:new Set,fields:new Set,kept:!1};u.to.add(c.to);for(let p of c.fields)u.fields.add(p);c.notConverted&&(u.kept=!0),i.set(l,u)}if(s.size===0)return;let a=(await e.currencies)?.target.active;if(!(!a||a.size===0))for(let[d,c]of s){if(a.has(d))continue;let l=i.get(d);e.gaps?.add(dl(t,d,c,l&&{to:[...l.to].sort(),converted:[...l.fields].sort(),asRead:l.kept}))}}async uniqueValueGaps(e,t,n,o){let s=new Map,i=n.filter(a=>a.unique===!0&&a.createable&&!(e.config.upsertMode==="auto"&&a.externalId===!0));for(let a of i){let d=new Map;for(let p of o){let f=p[a.name];if(typeof f!="string"||f===""||Fh.test(f))continue;let h=Pn(a,f),g=d.get(h);g?g.rows++:d.set(h,{value:f,rows:1})}if(d.size===0)continue;let c=new Set;try{let p=Me(t),f=Me(a.name),h=[...d.values()].map(({value:g})=>g);for(let g of Cn(h,Ph)){let m=await this.deps.queryRecords(e.targetOrgId,`SELECT ${f} FROM ${p} WHERE ${f} IN (${g})`);for(let w of m){let b=w[a.name];typeof b=="string"&&c.add(Pn(a,b))}}}catch{continue}let l=0,u=0;for(let[p,{rows:f}]of d)c.has(p)&&(l+=f,u++);l>0&&e.gaps?.add(cl(t,a.name,l,u));for(let p of o){let f=p[a.name];typeof f=="string"&&c.has(Pn(a,f))&&!s.has(p)&&s.set(p,a.name)}}return s}async writeNode(e,t,n,o){let{config:s,sourceOrgId:i,targetOrgId:a,remapper:d}=t;o&&o.pages++;let c=e.objectApiName===je?this.endOfTheEmails(t,n!==void 0):t.onProgress,l=s.dryRun?"Simulated":"Completed",u=n===void 0?`${l} ${e.objectApiName}`:t.emailsWrittenFirst?"after their task":`${l} ${e.objectApiName} after their task`,p=n===void 0?`Stopped ${e.objectApiName}`:t.emailsWrittenFirst&&!o?"stopped after their task":`Stopped ${e.objectApiName} after their task`,f=t.preread.get(e.objectApiName);if(!f)return;let{fieldInfos:h,createableSet:g,targetSetsPending:m}=f;if(lt(e.objectApiName)&&t.readsEverythingFirst&&n===void 0&&!o){await this.pricesInTheCurrencyWritten(e,t,f.records,h,this.currenciesTheirLinesWant(t,f.records));let x=gr(f.records,{sellingModel:t.sellingModels});x.length!==f.records.length&&(f.records.length=0,f.records.push(...x))}let w=n??f.records,b=w.filter(x=>nn(s,x)),S=e.objectApiName===he?w.filter(x=>fn(x)&&!nn(s,x)):[],R=await this.personContactsOnTheirOwn(t,S),k=new Set(S.filter(x=>!R.rows.has(x))),I=b.length>0||k.size>0?w.filter(x=>!nn(s,x)&&!k.has(x)):w,O=I,A=[];try{let x=null,j,E=null,$,L,Q=await(m??tn(this.deps.describeFields,a,e.objectApiName).then(v=>({ok:!0,sets:v}),v=>({ok:!1,error:v})));if(Q.ok)x=Q.sets.creatable,j=Q.sets.updateable,E=Q.sets.picklistValuesByField,$=Q.sets.picklistFields,L=Q.sets.fields;else{let v=Q.error;t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed \u2014 falling back to source schema)",messages:[v instanceof Error?v.message:String(v)]}]})}let G=x?or(g,x):g,V=this.linkPersonContacts(t,[...k]);if(o&&(o.withTheirAccount+=V.linked,Ja(o,V.notSent),V.linked===0&&(o.personContactsUnlinked+=k.size)),k.size>0&&V.linked===0&&I.length===0&&b.length===0){if(o)return;t.failedObjects.add(e.objectApiName),c({objectName:e.objectApiName,status:"error",progress:100,message:`${On(e.objectApiName,k.size,Gt(t,e.objectApiName))}: every record is a person account's contact, which the platform writes with its account, and the run has none of them in the target. Objects that cannot be written without it will be skipped.`});return}if(b.length>0&&(t.linkedCount+=b.length,o&&(o.writtenBefore+=b.length),this.oweLookupsOfRowsWrittenBefore(t,e,b,h,j),await this.oweStatusesFoundAfterStop(t,e.objectApiName,b),I.length===0&&k.size===0)){o||c({objectName:e.objectApiName,status:"done",progress:100,message:`${u}: 0 succeeded, ${pd(s,b.length)}, 0 failed`});return}let q=await this.targetObjectInfoOf(t,e.objectApiName),me=xw(q);t.gaps?.knowRecordTypes(e.objectApiName,"target",q?.recordTypes??[]);let de=await this.recordTypesHeldBack(e,I,q,G,t),H=de.length>0&&s.stream?.everything===!0?this.rowsOfClosedTypes(t,e,I,de):void 0,pe=H!==void 0&&H.size>0&&(o!==void 0||H.size<I.length);if(pe){O=I.filter(D=>!H.has(D)),t.failedCount+=H.size;for(let D of H.keys())t.heldInTheOrg.set(String(D.Id),"held");let v=[...H.values()];if(A.push(...v),o?(o.withoutParent+=v.length,Br(v,o.withoutParentGroups),Ja(o,ph(v))):t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:v.length,attemptedCount:0,samples:ld(Br(v),t.failedObjects)}),o&&O.length===0)return}else if(o?.heldWhole!==void 0&&de.length===0){t.failedCount+=I.length,o.heldWholeRows+=I.length;return}if(de.length>0&&!pe){for(let D of de)t.gaps?.add(hh(D,q));if(t.failedObjects.add(e.objectApiName),t.failedCount+=I.length,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:I.length,attemptedCount:0,samples:de.map(D=>({recordSummary:`RecordType=${D.developerName} (${D.recordCount} record${D.recordCount===1?"":"s"})`,messages:[vo(D)]}))}),o){o.heldWhole??=de.map(jo).join(" "),o.heldWholeRows+=I.length;return}let v=Gt(t,e.objectApiName);c({objectName:e.objectApiName,status:"error",progress:100,message:`${On(e.objectApiName,I.length,v)}: `+de.map(jo).join(" ")+" Objects that cannot be written without it will be skipped."});return}O=this.holdBackSkippedRows(t,e,O,c,me),O=this.leaveWhatHangsFromThePlatform(t,e,h,O);let ue=0;if(e.objectApiName===je&&n===void 0){let v=this.holdEmailsForTheirTask(t,O);if(ue=O.length-v.length,O=v,ue>0&&O.length===0){let D={objectName:e.objectApiName,status:"running",progress:0,message:`${e.objectApiName}: ${hs(ue)}`};c(D),o||(t.emailsAllWaiting={...D,status:"done",progress:100});return}}let be=0;if(e.objectApiName===st){let v=await this.linkTasksWrittenWithEmails(t,O);O=v.rows,be=v.linked,o&&(o.withTheirEmail+=v.linked)}let ne=new Set(s.fieldExclusions[e.objectApiName]??[]),K=s.fieldMappings[e.objectApiName]??{},Z=await this.teamOfTheOpportunities(t,e.objectApiName,O,q?.keyPrefix,h.flatMap(v=>!v.isReference&&G.has(v.name)&&!ne.has(v.name)&&K[v.name]===void 0?[v.name]:[]));O=Z.rows,o&&(o.teamOwners+=Z.owners,o.teamOthers+=Z.linked-Z.owners,bw(o.teamValues,Z.values));let U=await this.rowsWithoutTheirParent(e,t,h,O);for(let[v,D]of await this.rowsWhoseParentTheTargetLacks(e,t,h,O,fe=>G.has(fe)&&!ne.has(fe)&&K[fe]===void 0))U.has(v)||U.set(v,D);let se=await this.rowsHeldInTheWholeOrg(e,t,h,O,v=>G.has(v)&&!ne.has(v)&&K[v]===void 0);for(let[v,D]of se.held)U.has(v)||U.set(v,D);if(se.aside.size>0){for(let ce of U.keys())se.aside.delete(ce);dw(t,e.objectApiName,se.aside.values()),O.forEach((ce,Ie)=>{let Le=se.aside.get(Ie);Le&&t.heldInTheOrg.set(String(ce.Id),Le)});let v=O.filter((ce,Ie)=>!se.aside.has(Ie)),D=new Map;O.forEach((ce,Ie)=>{se.aside.has(Ie)||D.set(Ie,D.size)});let fe=new Map;for(let[ce,Ie]of U){let Le=D.get(ce);Le!==void 0&&fe.set(Le,Ie)}U.clear();for(let[ce,Ie]of fe)U.set(ce,Ie);O=v}if(O.forEach((v,D)=>{let fe=Z.held.get(v);fe&&!U.has(D)&&U.set(D,{field:fe.field,parentObject:fe.parentObject,reason:fe.why})}),U.size>0&&(s.stream?.everything===!0&&O.forEach((v,D)=>{U.has(D)&&t.heldInTheOrg.set(String(v.Id),"held")}),O=O.filter((v,D)=>!U.has(D)),t.failedCount+=U.size,o?(o.withoutParent+=U.size,Br(U.values(),o.withoutParentGroups),Ja(o,[{count:U.size,why:ud}])):t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:U.size,attemptedCount:0,samples:ew(U,t.failedObjects)}),O.length===0&&Z.linked===0)){if(o)return;t.failedObjects.add(e.objectApiName);let v=ue===0?Gt(t,e.objectApiName):[];c({objectName:e.objectApiName,status:"error",progress:100,message:`${On(e.objectApiName,U.size,v)}: every record points at a parent this run did not write. Objects that cannot be written without it will be skipped.`});return}await t.orphanExpander.expandForNode({node:e,fieldInfos:h,records:O,sourceOrgId:i,targetOrgId:a,remapper:d,scopeCache:t.scopeCache,recordTypeMappings:s.recordTypeMappings,recordTypeMapper:t.recordTypeMapper,enabled:s.expandOrphanParents,maxExpansions:s.maxOrphanParentExpansions,anonymize:t.anonymize?(v,D,fe,ce)=>this.anonymizeRows(t,v,[D],[fe],ce,{})[0]:void 0,contactPoints:t.contactPoints??void 0,withoutFileContent:(v,D)=>this.withoutFileContent(t,v,D,!0),startAsDraft:async(v,D)=>(await this.startAsDrafts(t,v,[D])).get(0),oweStatus:(v,D,fe)=>this.oweStatus(t,v,D,fe),objectOf:(v,D)=>this.objectOfSourceId(t,v,D),leftToThePlatform:t.leftToThePlatform,recordTypePicklists:t.recordTypePicklists,onRecordTypeNote:(v,D)=>this.sayRecordTypeNote(t,v,D),picklistChanges:t.picklistChanges,currencies:()=>this.runCurrencies(t),currencyChanges:t.currencyChanges,currencyChangesById:t.currencyChangesById,onWrittenWithoutFields:(v,D)=>this.countWrittenWithoutFields(t,v,D),linkPersonContacts:v=>this.mapContactsOfPersonAccounts(t,v),personAccountsInTarget:()=>this.personAccountsInTarget(t),fieldExclusions:s.fieldExclusions,fieldMappings:s.fieldMappings,maskedFieldsOf:v=>t.maskedSourceFields(v),onMaskedLeftOut:(v,D)=>this.noteEncryptedLeftOut(t,v,D),businessAccountsAmong:(v,D)=>this.takenAsBusinessAccounts(t,v,D),contactOnItsOwn:v=>t.contactsOnTheirOwn.has(v),...t.store?{calls:ms(t.store)}:{}}),O=this.leaveWhatHangsFromThePlatform(t,e,h,O);let Se=s.fieldMappings[e.objectApiName]??{},ge=await this.withMaskedLeftOut(t,e.objectApiName,new Set(s.fieldExclusions[e.objectApiName]??[]),O,v=>G.has(v)||Se[v]!==void 0),Te=$?await t.recordTypePicklists.forRows({objectApiName:e.objectApiName,rows:O,fields:$,written:v=>G.has(v)&&!ge.has(v)&&Se[v]===void 0,recordTypeMappings:s.recordTypeMappings,withoutRecordTypes:L!==void 0&&!L.some(v=>v.name==="RecordTypeId")}):void 0;for(let v of Te?.notes??[])this.sayRecordTypeNote(t,e.objectApiName,v);let De=G.has("RecordTypeId")&&!ge.has("RecordTypeId")&&Se.RecordTypeId===void 0,_=e.objectApiName===ye?await this.takenAsBusinessAccounts(t,O,De):void 0,P=bo(e.objectApiName)?void 0:await this.currenciesFor(t,L,O,v=>G.has(v)&&!ge.has(v)&&Se[v]===void 0),z=P?void 0:await this.parentCurrenciesFor(t,e.objectApiName,L,O);O=this.pricedInTheirRecordsCurrency(t,e.objectApiName,O);let ee=lt(e.objectApiName)?v=>t.prices.convertedInto.get(String(v.Id)):void 0,X=s.referenceFallback==="keep"?await this.idsTheTargetLacks(t,h,O,v=>G.has(v)&&!ge.has(v)&&Se[v]===void 0):void 0,_e=s.referenceFallback==="keep"?await this.inactiveOwnersToLeaveOut(t,O,G.has("OwnerId")&&!ge.has("OwnerId")&&Se.OwnerId===void 0):void 0,M=Nf({objectApiName:e.objectApiName,records:O,...ee?{pricedIn:ee}:{},fieldInfos:h,remapper:d,referenceFallback:s.referenceFallback,failedObjects:t.failedObjects,writtenObjects:t.writtenObjects,neverCopied:v=>gs(t,v),ownerMappings:s.ownerMappings,...Z.lookups.size>0?{resolvedLookups:Z.lookups}:{},...X&&X.size>0?{targetLacks:X}:{},..._e?{inactiveOwners:_e}:{},...t.sample?{outsideTheSample:(v,D)=>this.outsideTheSample(t,v.referenceTo??[],D)}:{},excludedFields:ge,fieldRename:Se,creatableFields:G,updatableFields:j,picklistValuesByField:E,picklistFields:$,recordTypeValues:Te?.byRecordType,businessAccounts:_,contactPoints:t.contactPoints??void 0,decide:(v,D)=>s.decisions.applyToRow(e.objectApiName,v,xh(s,D),t.decisionsApplied,me),...P||z?{currencyFields:wo(L??[])}:{},...P?{currencies:P}:{},...z?{parentCurrencies:z}:{}}),$e=new Fo,ve=new Ro;for(let{picklistChanges:v=[],currencyChange:D,source:fe}of M){$e.add(e.objectApiName,v),t.picklistChanges.add(e.objectApiName,v),o?.picklists.add(e.objectApiName,v),ve.add(e.objectApiName,D),t.currencyChanges.add(e.objectApiName,D),o?.currencies.add(e.objectApiName,D);let ce=fe.Id;D&&typeof ce=="string"&&t.currencyChangesById.set(ce,D)}let Ne=No($e.list())+Oo(ve.list())+ed(Sh(new Map,M))+rd(Ah(M))+td(nd(new Map,M))+(o?"":ad(t,e.objectApiName));o&&(Sh(o.lookupsNotCarried,M),nd(o.lookupsOutsideTheRun,M),o.ownersInactive+=Ah(M)),this.noteLookupsOutsideTheRun(t,e.objectApiName,h,M);for(let v of M)for(let D of v.lookupsOutsideTheSample??[])this.noteLeftOutsideTheSample(t,e.objectApiName,D);Sw(t,e.objectApiName,M);let ke=M.map(v=>v.cleaned);t.recordTypeMapper&&s.recordTypeMappings&&(ke=t.recordTypeMapper.apply(ke,s.recordTypeMappings,v=>es(e.objectApiName,v)));let Tn=this.applyRecordTypeDecisions(t,e.objectApiName,M,ke);ke=this.anonymizeRows(t,e.objectApiName,ke,M.map(v=>String(v.source.Id??"")),h,s.fieldMappings[e.objectApiName]??{});let Ht=new Map((L??[]).flatMap(v=>v.length!==void 0&&v.length>0?[[v.name,v.length]]:[]));if(s.decisions.truncatedFieldsOf(e.objectApiName).size>0)for(let v of ke)s.decisions.truncate(e.objectApiName,v,Ht,t.decisionsApplied);let et=new Map;t.gaps&&(et=await this.findGaps(t,e,{cleanedRecords:M,recordsToInsert:ke,targetFields:L,targetObject:q,picklistValuesByField:E,picklistFields:$,recordTypes:Te?.byRecordType,unmapped:Tn}));let gt=e.objectApiName===Xn?await this.takeTheSyncCopies(t,M,ke,b,{fields:L,updatable:j,keyPrefix:q?.keyPrefix}):{taken:0,given:0};e.objectApiName===Ce&&yw(t,M,ke);let pt=e.objectApiName===Ue?await this.linkTheRolesThePlatformWrote(t,M,ke,{fields:L,updatable:j,keyPrefix:q?.keyPrefix}):{linked:0,given:0},dn=await this.startAsDrafts(t,e.objectApiName,ke),rt=new Map;if(t.store)for(let[v,D]of dn){let fe=M[v];fe&&rt.set(fe,D)}let ot=[];if(lt(e.objectApiName)&&t.standardPricebookId){let v=M.map((ce,Ie)=>Ie),{standard:D,custom:fe}=dc(v.map(ce=>({index:ce,[Ot]:M[ce].source[Ot]})),t.standardPricebookId);for(let ce of[D,fe])ce.length!==0&&ot.push({records:ce.map(Ie=>ke[Ie.index]),cleaned:ce.map(Ie=>M[Ie.index])})}ot.length===0&&(ke.length>0||gt.taken===0&&pt.linked===0)&&ot.push({records:ke,cleaned:M});let Ye=await this.recordTypeCounter(t,e.objectApiName,q,De),Ae=ou();Ae.successCount+=gt.taken;let mt;try{for(let v of ot){if(t.simulated){this.simulateWrite(t,e,v,q?.keyPrefix,Ae,c,Ye,L,et);continue}await t.batchWriter.writeNode({node:e,records:v.records,cleanedRecords:v.cleaned,fieldInfos:h,creatableFields:G,upsertMode:s.upsertMode,...o?.tableKeys?{tableKeys:o.tableKeys}:{},targetOrgId:a,targetKeyPrefix:q?.keyPrefix,picklistFields:$,remapper:d,...t.store?{oweLookups:D=>this.oweToTheSecondPass(t,D)}:{},...t.store?{calls:ms(t.store)}:{},...rt.size>0?{onWritten:(D,fe)=>{let ce=rt.get(D);ce!==void 0&&(rt.delete(D),this.oweStatus(t,e.objectApiName,fe,ce))}}:{},...Ye?{onCreatedWithoutRecordType:Ye}:{},...Object.keys(s.ownerMappings).length>0?{ownersMapped:new Set(Object.values(s.ownerMappings).map(D=>D.slice(0,15)))}:{},...t.bulk?{bulk:t.bulk}:{},waitIfPaused:()=>this.waitIfPaused(),stopped:()=>this.isAborted,onProgress:c},Ae)}}catch(v){if(!(v instanceof Oe))throw v;mt=v}finally{for(let[v,D]of dn){let fe=M[v];if(fe&&t.store&&!rt.has(fe))continue;let ce=fe?.source.Id;if(typeof ce!="string")continue;let Ie=d.get(ce);!Ie||d.isExisting(ce)||this.oweStatus(t,e.objectApiName,Ie,D)}this.countWrites(t,e.objectApiName,Ae)}let B=Ae.successCount,J=Ae.updatedCount,ie=Ae.linkedExistingCount,Re=Ae.failureCount,re=Ae.unidentifiedExistingCount;if(o){let v=ot.reduce((Le,vn)=>Le+vn.records.length,0),D=ot.flatMap(Le=>Le.cleaned);o.sent+=v,o.succeeded+=B,o.updated+=J,o.linked+=ie,o.linkedToCreated+=Ae.linkedToCreatedCount??0,o.failed+=Re,o.alreadyExists+=Ae.alreadyExistsCount,o.unidentified+=re,o.rolesOfTheirOpportunity+=pt.linked,o.rolesGiven+=pt.given,o.writtenWithoutFields=Ae.writtenWithoutFields?Ui(o.writtenWithoutFields,Ae.writtenWithoutFields):o.writtenWithoutFields,Ae.flagsNotKept&&(o.flagsNotKept=Ec(o.flagsNotKept,Ae.flagsNotKept));let fe=mt?v-(B+J+ie+Re):0,ce=D.slice(0,v-fe).filter(Le=>R.rows.has(Le.source)).length;o.sentOnTheirOwn+=ce,ce>0&&(o.onTheirOwnWhy=R.why);let Ie=[...Ya(o),...Gt(t,e.objectApiName)];if(mt)throw this.stopStreamedNode(e,t,o,fe,p),mt;c({objectName:e.objectApiName,status:"running",progress:0,message:`${e.objectApiName}, page ${o.pages}: ${Za(s,o,Ie)}`});return}let oe=B+J+ie+b.length+V.linked+Z.linked+pt.linked,Qe=oe+Re,we=Qe>0?Re/Qe:0,Be=Re>0&&Ae.alreadyExistsCount===Re,He=Re>0&&!Be&&(oe===0||we>.5),wt=_h(ie,Ae.linkedToCreatedCount??0),_n=J>0?`, ${J} updated through their external id`:"",An=re>0?` (${re} already in the target without Salesforce naming the record \u2014 their children lose the link)`:"",At=v=>[...ph(A),...U.size>0?[{count:U.size,why:ud}]:[],...V.notSent,...v?Gt(t,e.objectApiName):[]],Kt=At(ue===0),Ft=be>0?`, ${be} written by the platform with their email`:"",tt=V.linked>0?`, ${V.linked} written by the platform with their person account`:"",cn=Uh(Z.owners,Z.linked-Z.owners)+zh(pt.linked,pt.given),Xe=ot.flatMap(v=>v.cleaned),jt=v=>Xe.slice(0,v).filter(D=>R.rows.has(D.source)).length,dt=v=>v>0?`, ${v} ${v===1?"person account's contact":"person accounts' contacts"} sent on their own: the target wrote none with their account`:"",yt=dt(jt(Xe.length)),Ge=b.length>0?`, ${pd(s,b.length)}`:"",Vt=ue>0?`, ${hs(ue)}`:"",bt=[wi(Ae.flagsNotKept),Gh(Z.values)].flatMap(v=>v?[`, ${v}`]:[]).join(""),Un=zo(Ae.writtenWithoutFields),jn=Mh(t,e.objectApiName),qr=bs(t,e.objectApiName),Nt=n===void 0?rh(t,e.objectApiName):"",ar=s.dryRun?"would be inserted":"succeeded",zs=gt.taken>0?` (${gp(gt.taken,gt.given,s.dryRun)})`:"",Hr=v=>`${B} ${ar}${zs}${_n}${wt}${Ft}${tt}${cn}${Ge}, ${Re+Wn(v)} failed${An}${rn(v)}`,Gs=`${yt}${Vt}${bt}${Ne}${Un}${jn}${ue===0?qr:""}${Nt}`;if(mt){let v=ot.reduce((Ie,Le)=>Ie+Le.records.length,0),D=v-(B+J+ie+Re)+ue;od(t,e.objectApiName,D);let fe=ue>0?` (${hs(ue)})`:"",ce=jt(v-D+ue);throw this.saySentOnTheirOwn(t,ce,R.why),(n===void 0?t.onProgress:c)({objectName:e.objectApiName,status:He?"error":"stopped",progress:100,message:`${p}: ${Hr(At(!0))}, ${D} not sent${fe}${dt(ce)}${bt}${Ne}${Un}${jn}${qr}`}),mt}if(this.saySentOnTheirOwn(t,jt(Xe.length),R.why),He){t.failedObjects.add(e.objectApiName),oe>0&&t.failedInPart.add(e.objectApiName);let v=Wn(Kt);c({objectName:e.objectApiName,status:"error",progress:100,message:oe===0?`Failed all ${e.objectApiName} records: ${Re+v} failed${rn(Kt)}${yt}${Ne}${Nt}`:`${Re+v}/${Qe+v} ${e.objectApiName} records failed (>50%)${rn(Kt)}${yt}${Ne}${Un}${jn}${Nt}${gh}`})}else c({objectName:e.objectApiName,status:"done",progress:100,message:`${u}: ${Hr(Kt)}${Gs}`})}catch(x){if(x instanceof Oe)throw x;t.failedObjects.add(e.objectApiName),t.failedCount+=O.length,t.errors.push({objectApiName:e.objectApiName,stage:"query",failedCount:O.length,attemptedCount:O.length,samples:[{recordSummary:"(stage failed before insert)",messages:[Y(x)]}]}),c({objectName:e.objectApiName,status:"error",progress:100,message:`Error on ${e.objectApiName}: ${Y(x)}`})}}};function Vw(r,e){if(r.sample===void 0){if(e===void 0)return;throw new Error("A sample was handed to a run whose config copies every record, or walks from a record: run it as its config says, or ask the sample in its config. Nothing was read or written.")}if(r.inputMode!=="org"||e===void 0)throw new Error("The config asks a sample of the whole org, and the run was handed nothing to keep or take up its plan with: it would have copied every record. Nothing was read or written.");return{...e,options:r.sample}}function gd(r,e,t,n){let o=t?.recordTypeMappings,s=ls(e.anonymizePII,r,t?.anonymizationRules,n),i=t?.files?{maxFileBytes:t.files.maxFileSizeMB*1048576,acceptedAsIs:t.files.acceptedAsIs}:void 0,a=t?.writtenBefore,d=t?.beforeWrite,c=e.inputMode==="org",l=t?.stream,u=Vw(e,l?.sample),p=c?{...l,everything:!0,writeWindow:hd,secondPassPageSize:hd,ceiling:void 0,wholeReadBound:l?.wholeReadBound??l?.ceiling??ro,...u?{sample:u}:{}}:l,f=[...new Set([...r.nodes.filter(hc).map(S=>S.objectApiName),...e.excludedObjects??[]])],h=f.length>0?f:void 0,g=e.dryRun===!0?!0:void 0,m=Mo(e),w=e.keepContactPoints===!0?!0:void 0;return e.inputMode==="record"&&typeof e.recordId=="string"?{rootRecordId:e.recordId,rootObjectApiName:r.nodes[0]?.objectApiName,expandOrphanParents:e.expandOrphanParents,maxRecordsPerObject:e.maxRecordsPerObject,fieldExclusions:e.fieldExclusions,excludedObjects:h,ownerMappings:e.ownerMappings,objectSoqlFilters:e.objectSoqlFilters,fieldMappings:e.fieldMappings,recordTypeMappings:o,anonymization:s,keepContactPoints:w,files:i,writtenBefore:a,beforeWrite:d,stream:p,dryRun:g,decisions:m}:e.maxRecordsPerObject!=null||e.fieldExclusions||h||e.ownerMappings||e.objectSoqlFilters||e.fieldMappings||o||s||w||i||a||d||p||g||m?{maxRecordsPerObject:c?void 0:e.maxRecordsPerObject,...c?{writeApi:"auto"}:{},fieldExclusions:e.fieldExclusions,excludedObjects:h,ownerMappings:e.ownerMappings,objectSoqlFilters:e.objectSoqlFilters,fieldMappings:e.fieldMappings,recordTypeMappings:o,anonymization:s,keepContactPoints:w,files:i,writtenBefore:a,beforeWrite:d,stream:p,dryRun:g,decisions:m}:void 0}var Dr="--checkpoint-first",md={switches:[Dr],values:["--checkpoint-keep-days","--checkpoint-exclude-object"]},Jw=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function Kh(r){return[` --checkpoint-first ${r.step??""}take a checkpoint of what ${r.run} writes before its`," first write: each object it writes, and each the"," target's flows that still run create as it writes"," them, held whole, as every checkpoint holds an object."," Its cost is that of the tables, not of the records",` written, and is said first. A rewind to it takes ${r.run}`," back (sandforge checkpoint rewind), and the work of"," anyone else on those objects since with it. Refused",` \u2014 another run writing, a limit, the disk \u2014 ${r.run}`," writes nothing, exit 1; deleted again when it writes",` nothing; with ${r.simulation}, says what it would hold and`," cost, and takes nothing (default: off)",...(r.note??[]).map(t=>` ${t}`)," --checkpoint-keep-days <n>"," the days that checkpoint is kept on this machine,"," 0 to 3650, 0 until it is deleted (default: 7)"," --checkpoint-exclude-object <ApiName>"," leave an object out of that checkpoint, named; a"," rewind leaves its records as they are; repeat for more"].join(`
|
|
21
|
-
`)}function Wr(r){process.stderr.write(`${r}
|
|
22
|
-
`),process.exit(2)}function Vh(r,e=[]){let t=a=>{let d=[];for(let c=0;c<r.length;c++)r[c]===a&&c+1<r.length&&d.push(r[c+1]);return d},n=t("--checkpoint-keep-days"),o=t("--checkpoint-exclude-object");if(!r.includes(Dr)){let a=[...n.length>0?["--checkpoint-keep-days"]:[],...o.length>0?["--checkpoint-exclude-object"]:[]];a.length>0&&Wr(`${a.join(" and ")} ${a.length===1?"goes":"go"} with ${Dr}, which takes the checkpoint they set. Run with --help.`);return}for(let{flag:a,why:d}of e)r.includes(a)&&Wr(`${Dr} does not go with ${a}: ${d}`);n.length>1&&Wr(`--checkpoint-keep-days is given ${n.length} times: give it once.`);let s;if(n.length===1){let a=n[0];s=/^\d{1,4}$/.test(a)?Number(a):Number.NaN;try{Vi(s,void 0)}catch{Wr(`--checkpoint-keep-days takes a whole number of days from 0 to 3650, not "${a}".`)}}let i=[];for(let a of o)Jw.test(a)||Wr(`--checkpoint-exclude-object takes an object's API name, not "${a}".`),i.some(d=>d.toLowerCase()===a.toLowerCase())||i.push(a);return{...s!==void 0?{keepDays:s}:{},...i.length>0?{excluded:i}:{}}}function Hh(r,e){return r!==void 0&&r.length>=15&&r.slice(0,15)===e.slice(0,15)}function Yw(r){let e=r.self??Ol,t=r.elsewhere??(s=>kl(s,e)),n=`A SandForge run is writing to ${r.orgName}: start this run once it has ended. No record was read.`,o=s=>s.writer!==void 0&&s.writer.pid===e.pid&&Date.parse(s.writer.hostStartedAt)===Date.parse(e.startedAt);return async s=>{let i=r.envLock?.(s);if(i!==void 0)return`${i}: start this run once it has ended. No record was read.`;for(let a of r.runs)for(let d of await a.list()){if(d.end!==void 0||!(Hh(d.targetOrganizationId,s)||Hh(d.targetOrgId,s)||d.targetOrgId===r.alias))continue;let l=r.own?.runId!==void 0&&d.runId===r.own.runId;if(o(d)?!l:t(d))return n}}}function Jh(r,e){return{id:e.id,orgType:uc({isScratch:r.scratch===!0,isSandbox:e.sandbox,edition:e.edition}),...e.edition!==void 0?{edition:e.edition}:{}}}function Qw(r){let e=r.reason==="notAFolder"?"it is a file, not a folder":r.reason==="otherOwner"?"another user of this machine owns it, and could read and replace the checkpoints in it":`it could not be made${r.detail!==void 0?` (${r.detail})`:""}`;return`the checkpoints cannot be kept in ${r.path}: ${e}`}function Xw(r){let e=-1;return({percentage:t})=>{let n=Math.floor(t/10);n<=e||(e=n,r(` ${Ou(t)}`))}}function Yh(r){let e,t=()=>e??=(async()=>{let{join:o}=await import("node:path"),{takeOrgOf:s}=await import("./chunk-CSBS5U5I.mjs"),{openCheckpointStore:i}=await import("./chunk-GSG7WZHM.mjs"),{nodeSyncRunCreations:a}=await import("./chunk-VE6XKGGD.mjs"),{nodeSeedRunCreations:d}=await import("./chunk-2UZPIMUC.mjs"),{envLockHolder:c,envLockLine:l}=await import("./chunk-HLWMJF6Y.mjs"),u=i({root:r.storeRoot??o(r.journalDir,"checkpoints"),...r.locksDir!==void 0?{locksDir:r.locksDir}:{}});if("refusal"in u)throw new Error(Qw(u.refusal));let{store:p}=u,{session:f}=r,h=r.connect(f),g={id:r.org.id,alias:f.alias,username:f.username,instanceUrl:f.instanceUrl,orgType:r.org.orgType,metadata:{apiVersion:h.version,...r.org.edition!==void 0?{edition:r.org.edition}:{}}},m={log:w=>{w.startsWith("[WARN] ")&&r.say(`warning: ${w.slice(7)}`)},orgManager:{getOrg:w=>w===g.id?g:void 0},orgRegistry:{getCredentials:async w=>w===g.id?{accessToken:f.accessToken,instanceUrl:f.instanceUrl}:void 0}};return{deps:{org:s(h),store:p,handler:m,runWriting:Yw({orgName:f.alias,alias:f.alias,runs:[a(r.journalDir),d(r.journalDir)],envLock:w=>{let b=c(p.locksDir,w);return b!==void 0?l(b):void 0},...r.own?{own:r.own}:{}}),...r.freeBytes?{freeBytes:r.freeBytes}:{}},org:{orgId:r.org.id,orgName:f.alias,alias:f.alias,username:f.username,instanceUrl:f.instanceUrl,registered:{orgType:r.org.orgType,...r.org.edition!==void 0?{metadata:{edition:r.org.edition}}:{}}}}})(),n=o=>({module:r.module,written:o.written,running:o.running,request:r.request,operationId:r.operationId,tool:"cli",keepDays:Vi(r.request.keepDays,void 0)});return{async scope(o){let s=await import("./chunk-IOIWJ3DJ.mjs"),{deps:i,org:a}=await t();return s.scopeBeforeRun(i,a,n(o))},async take(o,s,i={}){let a=await import("./chunk-IOIWJ3DJ.mjs"),{deps:d,org:c}=await t();return a.takeBeforeRun({...d,...i.signal?{signal:i.signal}:{},onProgress:Xw(r.say)},c,n(o),s)},async settle(o,s){let i=await import("./chunk-IOIWJ3DJ.mjs"),{deps:a}=await t(),d=await i.settleBeforeRun(a.store,o,s);return d.notDeleted!==void 0&&r.say(`warning: ${d.notDeleted}`),d.info}}}function wd(r){return El(r).map(e=>` ${e}`)}var Zw=new Set(["TOO_MANY_RECORDS","API_BUDGET","DISK"]);function Ss(r){let e=r.message.replace(/\s*No record was read\.$/,""),t=Zw.has(r.code)?"leave an object out of it (--checkpoint-exclude-object <ApiName>), ":"";return`The checkpoint before the run was refused: ${e} Fix what refuses it, ${t}or run without ${Dr} to write without one.`}function yd(r){return r.code!==mn?Au:r.refusal!==void 0?`${Ss(r.refusal)} Nothing was written.`:r.message}function ey(r){return r===null?"kept until it is deleted":`kept until ${r.slice(0,10)}`}function Qh(r,e,t){return[`checkpoint before the run: ${r.checkpointId} '${r.name}', ${r.objects.length} object(s), ${r.records} record(s), ${ey(r.expiresAt)}`,` rewind to it: ${Qt("checkpoint")} rewind --org ${e} --checkpoint ${r.checkpointId}${t?" --mute-automation":""}`,...r.notHeld.map(({objectApiName:n,reason:o})=>` not in the checkpoint: ${n} \u2014 ${o}`)]}function bd(r){return r.state==="deleted"?[Ru]:[]}async function $S(r,e,t,n,o){try{let s=await r.settle(e,t);for(let i of bd(s))o(i);return s}catch(s){return o(`warning: the checkpoint '${e.name}' taken before the run, which wrote nothing, could not be deleted (${s instanceof Error?s.message:String(s)}): delete it with ${Qt("checkpoint")} delete --org ${n} --checkpoint ${e.checkpointId}`),e}}var Ts="--leave-undeletable",Rd="UNDELETABLE_NOT_LEFT";function ty(r,e){let t=r.map(o=>`${o.objectApiName} (${o.records} records)`).join(", "),n=ht(Ts)?`run again with ${Ts}`:`run ${bn(Ts,"removal")}`;return{code:Rd,message:`The user SandForge connects as may not delete the records of ${t} in ${e}. Nothing was removed. Give that user Delete on those objects, or ${n} to remove the rest and leave them.`}}function Xh(r,e,t,n=o=>process.stderr.write(`${o}
|
|
23
|
-
`)){return async o=>{if(!r)return t(ty(o,e)),!1;let s=o.map(i=>`${i.objectApiName} (${i.records} records)`).join(", ");return n(`The user SandForge connects as may not delete the records of ${s} in ${e}.`),n(`Those stay, with the records they hang from; the rest is removed (${Ts}).`),!0}}function Zh(r,e){let t;return async n=>{let o=await r.describeObject?.(e,n);return!o||!o.recordTypes.some(s=>!s.master)?o?.recordTypes:(t??=r.queryRecords(e,ko).then(So,()=>[]),To(o.recordTypes,await t))}}var Wd=`sandforge clone \u2014 Forge a clone of one record, or of whole tables, from a source org
|
|
24
|
-
to a target sandbox, or remove what a run of it created.
|
|
25
|
-
|
|
26
|
-
Usage:
|
|
27
|
-
npx sandforge clone \\
|
|
28
|
-
--record <id> --source <alias> --target <alias> [options]
|
|
29
|
-
npx sandforge clone \\
|
|
30
|
-
--object <ApiName> [--where <condition>] [--object <ApiName> [--where <condition>]]... \\
|
|
31
|
-
--source <alias> --target <alias> [options]
|
|
32
|
-
npx sandforge clone \\
|
|
33
|
-
--depth all --source <alias> --target <alias> [--fit share] [--dry-run] [--yes]
|
|
34
|
-
[options]
|
|
35
|
-
npx sandforge clone \\
|
|
36
|
-
--remove <summary.json> --target <alias> [--include-changed] [--accept-automation]
|
|
37
|
-
[--mute-automation] [--leave-undeletable] [--json]
|
|
38
|
-
[--preview] [--sweep | --sweep-list] [--sweep-late] [--sweep-untied] [--sweep-user <id>]
|
|
39
|
-
[--audit <file>]
|
|
40
|
-
npx sandforge clone \\
|
|
41
|
-
--verify <summary.json> --target <alias> [--source <alias>] [--json] [--audit <file>]
|
|
42
|
-
|
|
43
|
-
The target must be a sandbox or a Developer Edition org (a Trailhead
|
|
44
|
-
playground is one). Its Organization record says which, and any other
|
|
45
|
-
org, an org whose edition it does not say included, is refused as a
|
|
46
|
-
production org before anything is written or deleted. --dry-run and
|
|
47
|
-
--list-objects only read, and run against any org.
|
|
48
|
-
|
|
49
|
-
Before it reads a row, the clone says what the target runs on the objects
|
|
50
|
-
it writes: its active record-triggered flows, Apex triggers, Process
|
|
51
|
-
Builder processes and workflow rules, per object and write, with what of
|
|
52
|
-
them sends messages (SENDS MESSAGES) or runs after commit; its assignment
|
|
53
|
-
and duplicate rules; and what keeps a flow from starting for the user the
|
|
54
|
-
run writes as, and whether that user holds it (with --json, under
|
|
55
|
-
targetAutomation). When any of them fires as the clone inserts its
|
|
56
|
-
records, or as it updates those it writes a second time \u2014 a lookup
|
|
57
|
-
filled in once its record exists, an order or a contract given back its
|
|
58
|
-
status \u2014 or the target would not say what it runs, nothing is written
|
|
59
|
-
unless --accept-automation is given. A bypass the user does not hold is
|
|
60
|
-
given with the permission set of the target that holds it, which
|
|
61
|
-
--mute-automation assigns for the run alone, under a lease.
|
|
62
|
-
|
|
63
|
-
It then says what the target holds against the rows, read from its
|
|
64
|
-
metadata: its active validation rules and what keeps them quiet, its
|
|
65
|
-
active duplicate rules and whether each blocks an insert or lets it
|
|
66
|
-
through, the fields only the target requires that the clone does not
|
|
67
|
-
write, the lookup filters of the lookups it writes, and the daily API
|
|
68
|
-
requests the target has left against those the run takes (with --json,
|
|
69
|
-
under targetGaps). A gap a decision of --config or --template answers \u2014
|
|
70
|
-
a default given to a field only the target requires \u2014 is said answered
|
|
71
|
-
by it, as Review shows it decided, and no longer BLOCKING (answeredBy,
|
|
72
|
-
with --json). None of it stops the clone. With --dry-run --json,
|
|
73
|
-
adminChanges lists, for whoever administers the target, the changes to its
|
|
74
|
-
metadata that would let the rows go in as they are \u2014 a picklist value to
|
|
75
|
-
add to a record type, a field to lengthen, a rule to turn off \u2014 grouped by
|
|
76
|
-
object and record type, each with its step in Setup; the clone makes none.
|
|
77
|
-
|
|
78
|
-
Once every row is read and before the first is written, the clone counts
|
|
79
|
-
the records it is about to write, per object, and the data storage they
|
|
80
|
-
take by the sizes Salesforce documents, and the daily API requests they
|
|
81
|
-
take, with those of a checkpoint taken first and of the record types read
|
|
82
|
-
back after. It writes nothing past --max-total, nor more than the target's
|
|
83
|
-
data storage or its daily API requests have left. It says the emails the
|
|
84
|
-
target's flows send as the records go in, against the daily limits it has
|
|
85
|
-
left \u2014 a Developer Edition's email alerts counted against its single emails
|
|
86
|
-
too \u2014 and writes nothing past them: a record whose flow fails in the save
|
|
87
|
-
is refused there, and the org's own emails stop for the day. What sends
|
|
88
|
-
and could not be read \u2014 a flow's definition refused or past the read's
|
|
89
|
-
bound, a flow a package installed, which the org lets no one read \u2014 is
|
|
90
|
-
said not counted (with --dry-run --json, under writePlan.emailsUncounted),
|
|
91
|
-
and refuses nothing: --accept-automation already covers it.
|
|
92
|
-
|
|
93
|
-
Required:
|
|
94
|
-
--record <id> Source record ID (any object type \u2014 prefix detected automatically);
|
|
95
|
-
may come from --template instead; --object (below)
|
|
96
|
-
clones whole tables instead
|
|
97
|
-
--source <alias> sf CLI alias of the source org
|
|
98
|
-
--target <alias> sf CLI alias of the target sandbox
|
|
99
|
-
|
|
100
|
-
Clone whole tables, in place of --record:
|
|
101
|
-
--object <ApiName> a table to clone; repeat for more. The first is where
|
|
102
|
-
discovery starts, and each other must be in its graph
|
|
103
|
-
(--depth, --max-nodes): a parent one of them points at,
|
|
104
|
-
or a child that hangs from one. Every other object
|
|
105
|
-
discovery reaches is left out. A table no clone
|
|
106
|
-
writes \u2014 users and their access, setup, a record's
|
|
107
|
-
history, feed or sharing rows, a file \u2014 is refused
|
|
108
|
-
before a row is read (TABLE_NEVER_CLONED), exit 2.
|
|
109
|
-
--where <condition> the rows of the --object before it: a SOQL condition,
|
|
110
|
-
written without WHERE (default: every row)
|
|
111
|
-
It narrows that table alone: every other --object is
|
|
112
|
-
read whole, whatever rows the first keeps. To hold a
|
|
113
|
-
table to the rows of another, give it a --where of
|
|
114
|
-
its own that names them, e.g. --object Account
|
|
115
|
-
--where "Industry = 'Energy'" --object Contact
|
|
116
|
-
--where "AccountId IN (SELECT Id FROM Account WHERE
|
|
117
|
-
Industry = 'Energy')".
|
|
118
|
-
The run is the panel's run of a query: each table read
|
|
119
|
-
with the org's cursor in the order of its ids and
|
|
120
|
-
written a page at a time, so the run holds a page of
|
|
121
|
-
rows whatever a table holds, and keeps what it wrote in
|
|
122
|
-
its journal as it goes; --resume reads each table after
|
|
123
|
-
the last row the run wrote. Parents go before the tables
|
|
124
|
-
that point at them, their lookups given the records the
|
|
125
|
-
run created. With --upsert, every page of a table goes
|
|
126
|
-
by one external id, the first whose value each row
|
|
127
|
-
the run reads of it holds and no two share. A run that
|
|
128
|
-
copies files (--files) reads each table whole. Not
|
|
129
|
-
with --record, --expand-orphans or --rehearse. With
|
|
130
|
-
--template, the template's choices go with the
|
|
131
|
-
tables, its record or query aside.
|
|
132
|
-
|
|
133
|
-
Clone the whole org, in place of --record:
|
|
134
|
-
--depth all every object of the source the target can take, from
|
|
135
|
-
no record and no table, each read a page at a time in
|
|
136
|
-
the order of its ids and written ten thousand records
|
|
137
|
-
at a time: as a Bulk API job from 2000 of them, by REST
|
|
138
|
-
under that and for an object no job writes (an active
|
|
139
|
-
duplicate rule watches it, the Bulk API refuses it).
|
|
140
|
-
What it leaves out is said with why: setup, metadata,
|
|
141
|
-
what only the platform writes, what the target cannot
|
|
142
|
-
take, an empty table. Past 1950 objects or 20000 pairs
|
|
143
|
-
of related objects, discovery refuses it, never cuts it.
|
|
144
|
-
Its dry run stops at the write gate once the source is
|
|
145
|
-
counted, and reads no row: per object the records it
|
|
146
|
-
would insert and how many go in jobs, the API requests
|
|
147
|
-
of both orgs, the Bulk API batches, the data and file
|
|
148
|
-
storage, what it leaves out and why, the personal
|
|
149
|
-
fields it copies as they are, and each refusal a real
|
|
150
|
-
run would meet, exit 1 when there is one (with --json,
|
|
151
|
-
under wholeOrg and wouldBeRefused).
|
|
152
|
-
A real run asks before its first write, naming the
|
|
153
|
-
records and objects, the requests and batches, the
|
|
154
|
-
objects of managed packages (the mute reaches none of
|
|
155
|
-
what they run), the phone numbers it writes empty and
|
|
156
|
-
the personal fields it copies as they are: --yes writes
|
|
157
|
-
without the question; with no terminal to answer it,
|
|
158
|
-
the run is refused (CONFIRMATION_UNAVAILABLE). It keeps
|
|
159
|
-
its journal, which --resume takes it up from and
|
|
160
|
-
--remove takes it back from, and exits 3 when the
|
|
161
|
-
target refused part of it. --max-total holds it as any
|
|
162
|
-
run: give it what the dry run counted. --exclude-object
|
|
163
|
-
leaves an object out, --filter narrows one; --files,
|
|
164
|
-
off unless given, copies the org's files. Not with
|
|
165
|
-
--record, --object, --where, --template, --custom-depth,
|
|
166
|
-
--max-nodes, --max, --expand-orphans, --rehearse or
|
|
167
|
-
--upsert.
|
|
168
|
-
--no-anonymize with --depth all, copy the personal data as the source
|
|
169
|
-
holds it, a production org's too
|
|
170
|
-
--yes with --depth all, write without the question
|
|
171
|
-
|
|
172
|
-
Copy a sample of the whole org that fits the target, with --depth all:
|
|
173
|
-
--fit share rather than every record, a sample: roots drawn of
|
|
174
|
-
each object, each with its children and the records
|
|
175
|
-
it names, none without a record it cannot be written
|
|
176
|
-
without; the largest share of the roots that fits
|
|
177
|
-
what the target has left \u2014 80 % of the data storage
|
|
178
|
-
its /limits say, half a MB off for their rounding,
|
|
179
|
-
less what its automation still running creates
|
|
180
|
-
under the records \u2014 and --max-total, its default
|
|
181
|
-
of 10000 too: raise it to take more. The reference
|
|
182
|
-
data go whole. Small parents and the price catalog
|
|
183
|
-
go whole while they fit a quarter of the room the
|
|
184
|
-
target has, 80 % of what it has left once half a MB
|
|
185
|
-
is off, whatever --fit-within and --max-total ask;
|
|
186
|
-
a root that would bring in more than a tenth of that
|
|
187
|
-
room by itself is set aside and named (heavy roots
|
|
188
|
-
set aside:). Drawn before the gate, from ids,
|
|
189
|
-
lookups and the few values that decide what it
|
|
190
|
-
keeps \u2014 record types, creation dates \u2014, the plan
|
|
191
|
-
is kept on disk, the ids of each object and no
|
|
192
|
-
value: a dry run's in forge-samples/ under the
|
|
193
|
-
journal directory for a day, a run's beside its
|
|
194
|
-
journal. The gate counts the plan, and the run
|
|
195
|
-
writes its records and no other: a lookup to a
|
|
196
|
-
record outside it is written empty and said, a
|
|
197
|
-
record gone from the source since is said apart,
|
|
198
|
-
one whose parent changed since is held back and
|
|
199
|
-
failed. The dry run says the sample
|
|
200
|
-
(sample:), per object what it keeps and how, what
|
|
201
|
-
goes whole (whole:), the roots set aside (heavy
|
|
202
|
-
roots set aside:), what it leaves out and why (not
|
|
203
|
-
in the sample:), the lookups left empty (left
|
|
204
|
-
empty:) and its plan (sample plan: <folder>); with
|
|
205
|
-
--json under wholeOrg.sample, a run's under sample,
|
|
206
|
-
and what it wrote of the plan under result.sample.
|
|
207
|
-
Not with --files or --list-objects.
|
|
208
|
-
--fit-within <MB> take no more than this many MB of the target
|
|
209
|
-
--fit-seed <n> the seed the roots are drawn by (default: 1)
|
|
210
|
-
The same seed and setup draw the same records.
|
|
211
|
-
--fit-draw uniform|recent
|
|
212
|
-
uniform spreads the roots over each object, reading
|
|
213
|
-
the id of every root; recent takes the newest by
|
|
214
|
-
creation date, reading only those it keeps
|
|
215
|
-
(default: uniform)
|
|
216
|
-
--fit-parents all|required
|
|
217
|
-
all copies a record outside the sample that an
|
|
218
|
-
optional lookup names, without its children;
|
|
219
|
-
required writes such a lookup empty (default: all)
|
|
220
|
-
--fit-children <n>|all most children a record brings through each relation,
|
|
221
|
-
the newest; a master record brings every detail
|
|
222
|
-
(default: 100)
|
|
223
|
-
--fit-whole <Object> copy this object whole (repeatable)
|
|
224
|
-
--fit-floor <n> roots kept of each object whatever the share
|
|
225
|
-
(default: 1)
|
|
226
|
-
--fit-plan <folder> write the records of the plan a dry run drew, as its
|
|
227
|
-
line sample plan: printed it, within a day: refused
|
|
228
|
-
when drawn of another org or with other flags, or
|
|
229
|
-
changed since (SAMPLE_PLAN_MISMATCH), or not there
|
|
230
|
-
(SAMPLE_PLAN_GONE), exit 2. The run moves it beside
|
|
231
|
-
its journal; one that writes nothing puts it back.
|
|
232
|
-
Not with --resume, which writes the plan its journal
|
|
233
|
-
names: gone, SAMPLE_PLAN_GONE, exit 2.
|
|
234
|
-
Refused, exit 1: a target that would not say its
|
|
235
|
-
storage, with neither --fit-within nor --max-total
|
|
236
|
-
(SAMPLE_STORAGE_UNREAD); the objects copied whole
|
|
237
|
-
and the floors alone past what it may take, the
|
|
238
|
-
heaviest named (SAMPLE_CANNOT_FIT; with --json,
|
|
239
|
-
refused.sample names what held it, limitedBy, and
|
|
240
|
-
of a bound in MB the needMB and budgetMB); more
|
|
241
|
-
than a million records to hold (SAMPLE_TOO_LARGE); the
|
|
242
|
-
roots' ids past a tenth of the source's requests
|
|
243
|
-
left today (API_BUDGET_EXCEEDED); a target that has
|
|
244
|
-
less room than the plan was fitted to: simulate
|
|
245
|
-
again (STORAGE_EXCEEDED).
|
|
246
|
-
|
|
247
|
-
Options:
|
|
248
|
-
--depth <mode> direct | full | custom | all (default: custom)
|
|
249
|
-
--custom-depth <n> traversal depth when --depth is custom (default: 5)
|
|
250
|
-
--max <n> max records cloned per object (default: unlimited)
|
|
251
|
-
--list-objects print the objects discovery reached, then stop
|
|
252
|
-
Answers "why was my object not cloned?" \u2014 an object
|
|
253
|
-
absent from this list was never in the graph. With
|
|
254
|
-
--json, stdout carries them as JSON: each object's
|
|
255
|
-
record count, depth and whether it is included, and
|
|
256
|
-
whether the graph was truncated.
|
|
257
|
-
--max-nodes <n> objects discovery may reach (default: 50)
|
|
258
|
-
Raise it when the summary says TRUNCATED and an
|
|
259
|
-
object you expected is missing, e.g. the lines of an
|
|
260
|
-
Opportunity's quotes. The prices, products, price
|
|
261
|
-
books and selling models the lines use come whatever
|
|
262
|
-
the cap, as do the items of an activated order and
|
|
263
|
-
the schedules of an opportunity's products. Each
|
|
264
|
-
parent a record reached cannot be written without
|
|
265
|
-
takes the cap one object further, up to twice it.
|
|
266
|
-
An empty table takes no place under it, and nothing
|
|
267
|
-
is reached through it; discovery reads four times
|
|
268
|
-
the cap in objects at most.
|
|
269
|
-
--anonymize anonymize PII fields (default: off)
|
|
270
|
-
With --depth all, on unless --no-anonymize when the
|
|
271
|
-
source's Organization record says a production org.
|
|
272
|
-
--keep-contact-points write emails and phone numbers as read (default: off)
|
|
273
|
-
Off, every record is written with its email addresses
|
|
274
|
-
under .invalid and its phone numbers in a fictional
|
|
275
|
-
range, anonymized or not, so what the target's flows
|
|
276
|
-
and email alerts send to them reaches no one. On,
|
|
277
|
-
they may reach the real people the records name.
|
|
278
|
-
--dry-run skip writes, surface scoped queries (default: off)
|
|
279
|
-
It reads the automation and counts the records as a
|
|
280
|
-
real run does, and says what would stop that run,
|
|
281
|
-
each under the code that run is refused with: a real
|
|
282
|
-
run would be refused (CODE): ... With --json, under
|
|
283
|
-
wouldBeRefused, and the codes under wouldBeRefusedCodes.
|
|
284
|
-
--rehearse have the target judge the rows, keep none (default: off)
|
|
285
|
-
Reads and prepares every row as a real run would,
|
|
286
|
-
then creates a sample of them in the target \u2014 every
|
|
287
|
-
row up to 200, one per object, record type and set of
|
|
288
|
-
fields given a value past it, with the records they
|
|
289
|
-
name \u2014 in composite calls that each fail on purpose,
|
|
290
|
-
so that every write is rolled back. Prints each
|
|
291
|
-
refusal (status code, field, rows) and what could not
|
|
292
|
-
be judged (with --json, under rehearsal). The target's
|
|
293
|
-
automation runs inside each call: emails, @future and
|
|
294
|
-
Queueable jobs, platform events published after
|
|
295
|
-
commit and the asynchronous paths of Flows never
|
|
296
|
-
leave it; platform events published immediately and
|
|
297
|
-
callouts do. Refused against a production org, and,
|
|
298
|
-
like a real run, without --accept-automation when the
|
|
299
|
-
target runs automation on insert. Not with --dry-run,
|
|
300
|
-
--upsert, --files, --remap-csv or --list-objects.
|
|
301
|
-
--accept-automation write although the target runs flows or Apex
|
|
302
|
-
triggers as the clone inserts, or as it updates the
|
|
303
|
-
records it inserted, or could not say what it runs
|
|
304
|
-
(default: off)
|
|
305
|
-
--accept-emails write although the target delivers every email of
|
|
306
|
-
what still runs as the clone writes, or would not say
|
|
307
|
-
whether it does; --accept-automation never stands for
|
|
308
|
-
it. Asked only when what still runs sends one: flows,
|
|
309
|
-
processes and workflow rules with an email action,
|
|
310
|
-
those whose definition was not read, and the
|
|
311
|
-
assignment rules --apply-assignment-rules applies,
|
|
312
|
-
whatever --mute-automation leaves. Whether the org
|
|
313
|
-
delivers them is read with one line of anonymous Apex
|
|
314
|
-
that sends nothing,
|
|
315
|
-
Messaging.reserveSingleEmailCapacity(1), as the user
|
|
316
|
-
the run writes as, never in a production org; on
|
|
317
|
-
System email only or No access, none of them goes
|
|
318
|
-
out, the org still counts them against its daily
|
|
319
|
-
limits, and nothing is asked. What an Apex trigger
|
|
320
|
-
sends is read nowhere (default: off)
|
|
321
|
-
--mute-automation mute the target's automation for the run through its
|
|
322
|
-
own bypass: assign the user the run writes as, for the
|
|
323
|
-
run alone, the permission sets holding the custom
|
|
324
|
-
permissions its flows, processes and workflow rules
|
|
325
|
-
test to stay quiet, and take them back as it ends.
|
|
326
|
-
What no bypass keeps quiet (an Apex trigger, a managed
|
|
327
|
-
package's flow) still runs, and still needs
|
|
328
|
-
--accept-automation. Refused on a production org and
|
|
329
|
-
for a user who cannot assign permission sets, exit 1;
|
|
330
|
-
a dry run says what would be muted and assigns nothing
|
|
331
|
-
(default: off)
|
|
332
|
-
${Kh({run:"the run",simulation:"--dry-run"})}
|
|
333
|
-
--max-total <n> most records the run may write in all (default: 10000)
|
|
334
|
-
Counted once every row is read: past it, nothing is
|
|
335
|
-
written. --max caps each object, this the whole run.
|
|
336
|
-
--max-records-per-object <n>
|
|
337
|
-
most records one read of an object takes
|
|
338
|
-
(default: 50000)
|
|
339
|
-
An object with more is read to it and said
|
|
340
|
-
TRUNCATED. A clone of a record holds what it reads,
|
|
341
|
-
so a higher number takes more memory; 1000000 at most.
|
|
342
|
-
--upsert use external Id upsert when available (default: insert)
|
|
343
|
-
Skips DUPLICATE_VALUE on re-runs of the same source records.
|
|
344
|
-
--expand-orphans single-hop expand orphan parent FKs (default: off)
|
|
345
|
-
Clones missing parents (out-of-graph) so child FKs resolve.
|
|
346
|
-
--max-orphans <n> with --expand-orphans, most parents from outside the
|
|
347
|
-
run it copies, 1 to 1000 (default: 20)
|
|
348
|
-
Past it, the rows that cannot be written without one
|
|
349
|
-
are refused, and the summary says how many parents
|
|
350
|
-
were left and of which objects.
|
|
351
|
-
--apply-assignment-rules
|
|
352
|
-
apply the target's assignment rules (default: off)
|
|
353
|
-
Off, every write says Sforce-Auto-Assign: FALSE and
|
|
354
|
-
keeps the owner the run sets. On, the target's active
|
|
355
|
-
assignment rules may give the Cases, Leads and
|
|
356
|
-
Accounts the run writes another owner, and mail them.
|
|
357
|
-
--skip-preflight skip pre-execute target row count (default: off)
|
|
358
|
-
The preflight queries each object on target so the user
|
|
359
|
-
can see existing volume before pressing through.
|
|
360
|
-
--json emit JSON summary on stdout (CI mode) (default: off)
|
|
361
|
-
stdout then carries the JSON alone, and every other
|
|
362
|
-
line goes to stderr. Saved to a file, the summary is
|
|
363
|
-
what --remove takes the run back from. With
|
|
364
|
-
--list-objects, the JSON is the objects of the graph.
|
|
365
|
-
A run refused before its first write prints
|
|
366
|
-
"refused": {"code", "message"} instead, the code its
|
|
367
|
-
line names: refused (MAX_TOTAL_EXCEEDED): ..., each
|
|
368
|
-
other reason under "alsoRefused", on a line of its own.
|
|
369
|
-
How a run ended is under result.status: success,
|
|
370
|
-
partial or failure, as its status: line says it.
|
|
371
|
-
--fail-on-partial exit 3, not 0, when the run wrote some records and
|
|
372
|
-
the target refused others (default: off)
|
|
373
|
-
--summary <file> write the summary to <file> as the run goes
|
|
374
|
-
The JSON --json prints, written after each object
|
|
375
|
-
with what the run has created so far ("running":
|
|
376
|
-
true), then whole once it ends. Ctrl-C stops the run
|
|
377
|
-
between two calls to the org and writes what it had
|
|
378
|
-
created by then ("interrupted": true), as --json then
|
|
379
|
-
prints it: --remove takes the run back from either.
|
|
380
|
-
A file already there is not overwritten. Not with
|
|
381
|
-
--list-objects or --rehearse.
|
|
382
|
-
--resume <journal|id> take up where it stopped a run that did not end \u2014 a
|
|
383
|
-
Ctrl-C, a failure, a process killed \u2014 from its journal:
|
|
384
|
-
its file, or its run id in the journal directory. Each
|
|
385
|
-
record that run wrote is linked to and never written
|
|
386
|
-
again, the lookups and statuses it still owed are
|
|
387
|
-
given, and the rest is written. The same record, orgs,
|
|
388
|
-
depth, choices and flags as the run it takes up, or it
|
|
389
|
-
is refused; a run that ended is refused too. Every run
|
|
390
|
-
that writes keeps its journal there (see
|
|
391
|
-
SANDFORGE_JOURNAL_DIR), and says where as it starts.
|
|
392
|
-
The calls the run had under way when it stopped are
|
|
393
|
-
looked for in the target first: a row found there is
|
|
394
|
-
kept as written by the run, never sent again; one the
|
|
395
|
-
target may hold already stops the resume before it
|
|
396
|
-
writes (see --write-uncertain).
|
|
397
|
-
Not with --dry-run, --rehearse or --list-objects.
|
|
398
|
-
--write-uncertain with --resume: write all the same the rows of a call
|
|
399
|
-
under way when the run stopped that the target may
|
|
400
|
-
already hold, records the resume cannot tell from
|
|
401
|
-
them being there \u2014 each may then be there twice.
|
|
402
|
-
--exclude <obj.field> skip a field on an object during clone (repeatable)
|
|
403
|
-
e.g. --exclude Account.Description --exclude Account.NumberOfEmployees
|
|
404
|
-
Matched whatever its case. One that names no object
|
|
405
|
-
or field of the source refuses the run before a row
|
|
406
|
-
is read, exit 2, naming the field nearest it
|
|
407
|
-
(FIELD_EXCLUSION_UNMATCHED); a dry run says it, as
|
|
408
|
-
the summary's result.fieldExclusionsUnmatched does.
|
|
409
|
-
--exclude-object <obj> leave an object out of the clone (repeatable)
|
|
410
|
-
e.g. --exclude-object PricebookEntry
|
|
411
|
-
Out whether discovery reaches it or the run would
|
|
412
|
-
add it past the cap. What it costs is said, not
|
|
413
|
-
written: the records that cannot be written without
|
|
414
|
-
one of its records, and the orders left drafts.
|
|
415
|
-
--owner-map <src=tgt> remap OwnerId from source User Id to target User Id (repeatable)
|
|
416
|
-
e.g. --owner-map 005AB...=005XY...
|
|
417
|
-
Useful when source records were authored by users
|
|
418
|
-
that don't exist on the target sandbox (ex-employees).
|
|
419
|
-
A target user the target holds inactive is refused
|
|
420
|
-
before anything is read (OWNER_MAP_INACTIVE), and
|
|
421
|
-
one it holds no user of (OWNER_MAP_UNKNOWN).
|
|
422
|
-
--filter <obj=where> per-object SOQL WHERE filter (repeatable)
|
|
423
|
-
e.g. --filter "Case=Status = 'Open' AND CreatedDate > LAST_N_DAYS:30"
|
|
424
|
-
Lets BAs narrow a clone to a subset without changing
|
|
425
|
-
graph topology. Filter is appended via AND (...) to
|
|
426
|
-
the scope-derived clause. Max 512 chars per filter,
|
|
427
|
-
max 50 filters total.
|
|
428
|
-
--map <obj.src=tgt> per-object source\u2192target field rename (repeatable)
|
|
429
|
-
e.g. --map Account.Region__c=Region__pc
|
|
430
|
-
Handles schema drift between source and target
|
|
431
|
-
(managed-package re-key, namespace change). The
|
|
432
|
-
source field is dropped and the value written to
|
|
433
|
-
the target field name on insert.
|
|
434
|
-
--config <file.json> the run's choices from a JSON file: the decisions
|
|
435
|
-
taken in Review's Gaps row (picklistValueMappings,
|
|
436
|
-
recordTypeMappings, defaultValues, truncateFields,
|
|
437
|
-
skippedRows, ignoredGaps), the fields and objects
|
|
438
|
-
left out (fieldExclusions, excludedObjects), the
|
|
439
|
-
filters (objectSoqlFilters) and the mappings
|
|
440
|
-
(ownerMappings, fieldMappings), as a Forge config
|
|
441
|
-
names them. Checked as the panel checks a run's
|
|
442
|
-
config; any other key is refused. The flags above
|
|
443
|
-
win over the file: their exclusions are added, their
|
|
444
|
-
filters and mappings replace the file's for the same
|
|
445
|
-
object, user or field.
|
|
446
|
-
--template <file.json> a template the Template tab exported: its decisions,
|
|
447
|
-
exclusions, filters and mappings, as --config takes
|
|
448
|
-
them, and its depth, caps, anonymization, contact
|
|
449
|
-
points and orphan parents, each unless its flag is
|
|
450
|
-
given. Its record is cloned when --record is not
|
|
451
|
-
given; a template of a query needs --record, or
|
|
452
|
-
--object. Not with --config.
|
|
453
|
-
--remap-csv <file> write the source\u2192target ID remap table to a CSV
|
|
454
|
-
file (header: sourceId,targetId). BA reconciliation:
|
|
455
|
-
"where did source X go on the target sandbox?"
|
|
456
|
-
--files copy the files of the cloned records (default: off)
|
|
457
|
-
Salesforce Files (the latest version of each) and
|
|
458
|
-
attachments, after the records they hang on. The
|
|
459
|
-
total is checked against the target's file storage
|
|
460
|
-
before anything is written: past it, refused
|
|
461
|
-
(FILE_STORAGE_EXCEEDED), as when that storage could
|
|
462
|
-
not be read (FILE_STORAGE_UNREAD) or the files not
|
|
463
|
-
all looked up (FILES_UNREAD).
|
|
464
|
-
--max-file-size <MB> largest file --files copies, 1 to 35 (default: 10)
|
|
465
|
-
A larger file is left out and listed, never cut.
|
|
466
|
-
--files-as-is accept that files are copied as they are: their
|
|
467
|
-
content cannot be anonymized. Required with --files
|
|
468
|
-
when --anonymize is on.
|
|
469
|
-
--audit <file> record the run in an audit trail kept in <file>
|
|
470
|
-
The entry the panel keeps in Reports -> Audit trail:
|
|
471
|
-
per object the records created, updated and lost,
|
|
472
|
-
the orgs, the outcome, the user as a hash of the
|
|
473
|
-
username, and, for a run refused before it wrote,
|
|
474
|
-
the code of what refused it. Counts only, never a
|
|
475
|
-
value of a record. Each run adds its entry to the
|
|
476
|
-
file; a dry run, --list-objects and --rehearse write
|
|
477
|
-
nothing, and add none.
|
|
478
|
-
-h, --help show this help and exit
|
|
479
|
-
|
|
480
|
-
Remove what a run created:
|
|
481
|
-
--remove <file> the summary a run printed with --json, saved to a file,
|
|
482
|
-
or the journal of a run: every part of it, the run it
|
|
483
|
-
took up and each time it was taken up
|
|
484
|
-
Deletes from --target the records that run created,
|
|
485
|
-
as the wizard removes a run from Recent runs: children
|
|
486
|
-
first, never a record the target already held, and a
|
|
487
|
-
record kept while records that stay depend on it. The
|
|
488
|
-
target must be the org the run wrote to. A dry run's
|
|
489
|
-
summary is refused: it created nothing.
|
|
490
|
-
What a removal wrote to the records it left is kept
|
|
491
|
-
beside the summary, clone-summary.removals.json for
|
|
492
|
-
clone-summary.json, and the next --remove of that
|
|
493
|
-
summary reads it: what a removal wrote is no change
|
|
494
|
-
since the run. Keep that file with the summary.
|
|
495
|
-
A summary of a run past 50 000 records keeps their ids
|
|
496
|
-
in its journal, which the removal reads them from.
|
|
497
|
-
Of a run stopped and taken up with --resume, one
|
|
498
|
-
summary per part, it is kept beside the journal too:
|
|
499
|
-
the removal of any part, or of the journal, reads what
|
|
500
|
-
the others wrote, and once a part's own records are
|
|
501
|
-
gone, takes what an earlier removal of another part
|
|
502
|
-
left. What the run wrote to a record of another part
|
|
503
|
-
is no change since the run. The journal's removal
|
|
504
|
-
takes the parts the last first, each read against
|
|
505
|
-
its own span: what someone changed, or made, between
|
|
506
|
-
two parts stays.
|
|
507
|
-
--include-changed remove also the records changed since the run, and
|
|
508
|
-
what was added to them since (default: kept)
|
|
509
|
-
--accept-automation delete although the target runs flows, Apex triggers,
|
|
510
|
-
processes or workflow rules as the records go, those
|
|
511
|
-
--sweep deletes included \u2014 before or after a delete,
|
|
512
|
-
or as an activated order is set back to Draft for
|
|
513
|
-
its delete \u2014 or could not say what it runs
|
|
514
|
-
(default: off)
|
|
515
|
-
--mute-automation mute the target's automation for the removal through
|
|
516
|
-
its own bypass, as for a run: the permission sets
|
|
517
|
-
holding the bypasses of what fires as the records go,
|
|
518
|
-
those --sweep deletes included, assigned to the user
|
|
519
|
-
it deletes as, for the removal alone, and taken back
|
|
520
|
-
as it ends; what no bypass keeps quiet still needs
|
|
521
|
-
--accept-automation (default: off)
|
|
522
|
-
--leave-undeletable remove the rest when the user the removal runs as
|
|
523
|
-
may not delete the records of some objects of the
|
|
524
|
-
run, leaving those with what they hang from; without
|
|
525
|
-
it the removal stops before its first delete and
|
|
526
|
-
names them (default: off)
|
|
527
|
-
--preview say what the removal would do, and do nothing: per
|
|
528
|
-
object the records it would delete, those gone
|
|
529
|
-
already, those changed since the run and who changed
|
|
530
|
-
them, those it could not see, and what a removal run
|
|
531
|
-
now would be refused for, each under the code it is
|
|
532
|
-
refused with: a removal would be refused (CODE): ...,
|
|
533
|
-
with --json the codes under "refusalCodes", in the
|
|
534
|
-
order of "refusals". It reads the records, as
|
|
535
|
-
the removal reads them before its first delete, and
|
|
536
|
-
writes nothing: not to the org, not beside the
|
|
537
|
-
summary. With --sweep, it lists what the sweep would
|
|
538
|
-
take, and reads what fires on it with the run's own.
|
|
539
|
-
Not with --sweep-list or --audit.
|
|
540
|
-
A removal takes no --dry-run: one that did not read
|
|
541
|
-
it would delete for real.
|
|
542
|
-
--sweep before the run's records go, delete too what the
|
|
543
|
-
target's automation made for the run, that the run's
|
|
544
|
-
id map does not hold: what the run's user created
|
|
545
|
-
under the run's records, what they point at, or what
|
|
546
|
-
hangs from those, three links at most, at most a
|
|
547
|
-
minute after the record it is tied to \u2014 in the
|
|
548
|
-
objects the run wrote and their children, tasks,
|
|
549
|
-
events, feed, email messages, notes, case comments,
|
|
550
|
-
and the objects the target's flows create. What a
|
|
551
|
-
record of the run points at by a lookup the org
|
|
552
|
-
refuses the delete for (an asset its case names)
|
|
553
|
-
goes once that record is gone. Listed and kept: what
|
|
554
|
-
is tied to the run but came later, up to 15 minutes,
|
|
555
|
-
or as the org's Automated Process user; and what the
|
|
556
|
-
run's user created in the run's window, a second
|
|
557
|
-
before its first write to a minute after its last,
|
|
558
|
-
tied to nothing of it.
|
|
559
|
-
What anyone changed more than 2 s after the run's
|
|
560
|
-
last write, and after its own creation, stays \u2014 the
|
|
561
|
-
run's user and its automation too \u2014 unless
|
|
562
|
-
--include-changed, and the sweep then ends partial,
|
|
563
|
-
exit 3; a change made before the run's last write
|
|
564
|
-
reads as unchanged. Runs alone when an earlier
|
|
565
|
-
--remove took every record of the run. Of a clone of
|
|
566
|
-
the whole org, the removal says the sweep is off
|
|
567
|
-
unless given: the run's window spans hours, and a
|
|
568
|
-
sweep looks at 300 objects at most
|
|
569
|
-
(default: off)
|
|
570
|
-
--sweep-late with --sweep, take too what it lists as made late;
|
|
571
|
-
with --sweep-list, say what it would take
|
|
572
|
-
--sweep-untied with --sweep, take too what it lists as tied to
|
|
573
|
-
nothing of the run; with --sweep-list, say what it
|
|
574
|
-
would take; refused when another run of this
|
|
575
|
-
machine wrote to the target in the run's window, or
|
|
576
|
-
when that user created records there on objects
|
|
577
|
-
neither the run nor the automation reaches (hand
|
|
578
|
-
work, likely)
|
|
579
|
-
--sweep-user <id> with --sweep or --sweep-list, the user the run wrote as,
|
|
580
|
-
for a run whose summary does not keep it: the sweep
|
|
581
|
-
reads it otherwise from the run's records, and is
|
|
582
|
-
refused when none is left or several users made them
|
|
583
|
-
--sweep-list list what --sweep would delete, per object with a few
|
|
584
|
-
names and how many it ties to the run, and delete
|
|
585
|
-
nothing, the run's records included; exit 3, as a
|
|
586
|
-
refused --sweep, when it says the sweep is refused
|
|
587
|
-
What a sweep leaves, and why: what another user
|
|
588
|
-
created, a colleague's or an integration's; what is
|
|
589
|
-
tied to nothing, unless --sweep-untied; what came
|
|
590
|
-
more than 15 minutes after its record, or after the
|
|
591
|
-
removal began, which cannot be told from work done
|
|
592
|
-
by hand; what anyone changed after the run's last
|
|
593
|
-
write, the run's own user included, unless
|
|
594
|
-
--include-changed; what the
|
|
595
|
-
automation changed or deleted rather than created,
|
|
596
|
-
which a checkpoint taken before the run takes back;
|
|
597
|
-
what left the org (emails, outbound messages); more
|
|
598
|
-
than 10 000 records of one object; and what the
|
|
599
|
-
panel, another machine or a CI wrote meanwhile, which
|
|
600
|
-
a sweep does not see
|
|
601
|
-
--json print what became of the records as JSON on stdout,
|
|
602
|
-
every other line on stderr; refused before its first
|
|
603
|
-
delete, "refused": {"code", "message"}, the code its
|
|
604
|
-
line names: refused (CODE): ... \u2014 a production org
|
|
605
|
-
(PRODUCTION_TARGET), what fires as it deletes
|
|
606
|
-
(AUTOMATION_NOT_ACCEPTED), its mute (MUTE_PRODUCTION,
|
|
607
|
-
MUTE_NO_RIGHT, MUTE_FAILED), objects its user may not
|
|
608
|
-
delete (UNDELETABLE_NOT_LEFT), an org that is not the
|
|
609
|
-
one the run wrote to (OTHER_ORG, its --preview too)
|
|
610
|
-
--audit <file> record the removal, and the sweep, in the audit trail
|
|
611
|
-
kept in <file>
|
|
612
|
-
|
|
613
|
-
Verify what a run created:
|
|
614
|
-
--verify <file> the summary a run printed with --json, saved to a file,
|
|
615
|
-
or the journal of a run, every part of it
|
|
616
|
-
Reads back from --target every record the run created,
|
|
617
|
-
after a pause and again until two readings agree (three
|
|
618
|
-
at most, two seconds apart): those there, those in the
|
|
619
|
-
recycle bin, those neither, out of the user's sight;
|
|
620
|
-
checks on twenty records of each object that the
|
|
621
|
-
lookups the run set point at the ids their parents got,
|
|
622
|
-
reading the source records in --source; and lists the
|
|
623
|
-
records changed since the run, which --remove keeps
|
|
624
|
-
unless --include-changed. Only reads, from either org.
|
|
625
|
-
Exits 0 when VERIFIED, 3 when PARTIAL (a record not
|
|
626
|
-
there, a lookup that does not hold, or a part that could
|
|
627
|
-
not be checked) and 4 when UNSTABLE (no two readings
|
|
628
|
-
agreed: something still writes to the records).
|
|
629
|
-
--source <alias> the org the run read from (default: the summary's)
|
|
630
|
-
A lookup the clone left out with --exclude reads as
|
|
631
|
-
one left empty.
|
|
632
|
-
--json print the verification as JSON on stdout, every other
|
|
633
|
-
line on stderr; refused for an org that is not the
|
|
634
|
-
one the run wrote to, exit 1, "refused": {"code",
|
|
635
|
-
"message"}, the code its line names: refused
|
|
636
|
-
(OTHER_ORG): ...
|
|
637
|
-
--audit <file> record the verification in the audit trail kept in
|
|
638
|
-
<file>
|
|
639
|
-
|
|
640
|
-
Environment:
|
|
641
|
-
SANDFORGE_FORGE_PAGE_SIZE=<n>
|
|
642
|
-
a diagnostic: read every statement through the org's
|
|
643
|
-
cursor and hand it on in pages of <n> rows, as a run of
|
|
644
|
-
whole tables reads, to see a clone's paged read against
|
|
645
|
-
a real org. Not a setting: an org answers in pages of
|
|
646
|
-
200 to 2000 rows, and a page of <n> is cut from them.
|
|
647
|
-
SANDFORGE_JOURNAL_DIR=<dir>
|
|
648
|
-
where every run that writes keeps its journal, in
|
|
649
|
-
<dir>/forge-runs/ (default: ~/.sandforge)
|
|
650
|
-
What the run wrote, read and still owes, line by line
|
|
651
|
-
as it goes, ids only: what --resume takes a run up
|
|
652
|
-
from, and what --remove takes it back from however it
|
|
653
|
-
ended.
|
|
654
|
-
|
|
655
|
-
Exit codes:
|
|
656
|
-
0 the clone ran, a run the target refused some records of too unless
|
|
657
|
-
--fail-on-partial; the rehearsal ran, whatever it found refused; the removal
|
|
658
|
-
took every record it set out to take; the preview said what a removal
|
|
659
|
-
would do, refusals included
|
|
660
|
-
1 the clone or the removal could not run; the clone produced only failures,
|
|
661
|
-
or its files were refused; --resume could not take the run up
|
|
662
|
-
(RESUME_UNAVAILABLE, RESUME_TARGET_CHANGED, RESUME_CHANGED,
|
|
663
|
-
RESUME_UNCERTAIN); the target is a production org; the target
|
|
664
|
-
runs automation on insert or on the updates the clone makes after its
|
|
665
|
-
inserts, or the removal's deletes fire automation, and
|
|
666
|
-
--accept-automation was not given; the target delivers the emails of
|
|
667
|
-
what still runs, or would not say whether it does, and --accept-emails
|
|
668
|
-
was not given (EMAILS_NOT_ACCEPTED); the checkpoint asked first was
|
|
669
|
-
refused or could not be taken (CHECKPOINT_REFUSED); the run would write
|
|
670
|
-
more than --max-total records, more than the target's data storage
|
|
671
|
-
has left or more emails than it has left today, or would take more API
|
|
672
|
-
requests than it has left today (nothing is written or deleted then);
|
|
673
|
-
a clone of the whole org nobody answered the question of
|
|
674
|
-
(CONFIRMATION_UNAVAILABLE) or that was declined (WRITE_DECLINED), or
|
|
675
|
-
whose dry run says a real run would be refused; a sample of it that
|
|
676
|
-
could not be drawn (SAMPLE_STORAGE_UNREAD, SAMPLE_CANNOT_FIT,
|
|
677
|
-
SAMPLE_TOO_LARGE)
|
|
678
|
-
2 a bad command line, an --exclude that names no field of the source
|
|
679
|
-
(FIELD_EXCLUSION_UNMATCHED), an --object no clone writes
|
|
680
|
-
(TABLE_NEVER_CLONED), or a summary --remove cannot take a run back from, or
|
|
681
|
-
a file beside it that is not what a removal kept there; the plan of a
|
|
682
|
-
sample --fit-plan gives or --resume takes up gone, or drawn of another
|
|
683
|
-
org or setup (SAMPLE_PLAN_GONE, SAMPLE_PLAN_MISMATCH)
|
|
684
|
-
3 the run was partial and --fail-on-partial was given, or was a clone of
|
|
685
|
-
the whole org; the removal left
|
|
686
|
-
records of the run in the org: kept, or refused, or found neither in the
|
|
687
|
-
org nor in its recycle bin, as the user it ran as sees them; or the sweep
|
|
688
|
-
was refused, or did not take all it was asked to (a --sweep-untied
|
|
689
|
-
refused included)
|
|
690
|
-
130 Ctrl-C stopped the clone: the summary says what it created by then
|
|
691
|
-
143 a SIGTERM stopped it \u2014 a CI job cancelled or timed out \u2014, 129 a SIGHUP:
|
|
692
|
-
as Ctrl-C does, the summary and the journal say what it created
|
|
693
|
-
`,Gr=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,at=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function cy(r,e){return r.verdict==="unread"?` API requests: about ${r.estimate}; what ${e} has left today could not be read (${r.unread})`:` API requests: about ${r.estimate}, of the ${r.remaining} ${e} has left of its ${r.max} a day`+(r.verdict==="exceeds"?": more than it has left":r.verdict==="near"?": it would leave less than a tenth of them":"")}var ly={"validation-rule":"a validation rule refused it","restricted-picklist":"a restricted picklist refused its value","lookup-filter":"a lookup filter refused the record it names","inactive-owner":"the target holds the owner it names inactive"},uy={inputMode:"--record",recordId:"--record",depth:"--depth",customDepth:"--custom-depth",maxRecordsPerObject:"--max",sourceOrgId:"--source",targetOrgId:"--target",fieldExclusions:"--exclude",ownerMappings:"--owner-map",objectSoqlFilters:"--filter",fieldMappings:"--map",soqlQuery:"--object",sample:"--fit"},Eg=["fieldExclusions","excludedObjects","ownerMappings","objectSoqlFilters","fieldMappings","picklistValueMappings","recordTypeMappings","defaultValues","truncateFields","skippedRows","ignoredGaps"],py=W.strictObject(sc.pick(Object.fromEntries(Eg.map(r=>[r,!0]))).shape);function fy(r){let e=r;for(let t="";t!==e;)t=e,e=e.replace(/\([^()]*\)/g," ");return/\bFROM\s+([A-Za-z][A-Za-z0-9_]*)/i.exec(e)?.[1]}function hy(r){let e=[];function t(n){process.stderr.write(`${n}
|
|
694
|
-
`),process.exit(2)}for(let n=0;n<r.length;n++){let o=r[n];if(o!=="--object"&&o!=="--where")continue;let s=r[n+1];if((s===void 0||s.startsWith("--"))&&t(o==="--object"?"--object takes the API name of a table to clone.":"--where takes a SOQL condition, written without WHERE."),n++,o==="--object"){at.test(s)||t(`Invalid --object value "${s}" (must match SObject API name pattern)`),e.some(a=>a.objectApiName===s)&&t(`--object ${s} is named twice.`),e.push({objectApiName:s});continue}let i=e.at(-1);i?i.where!==void 0?t(`--object ${i.objectApiName} is given two --where: join them with AND.`):s.trim()===""?t(`--where for ${i.objectApiName} is empty.`):i.where=s.trim():t("--where filters the --object before it: name the table first.")}return e.length>0?e:void 0}function Dd(r){let[e]=r;return`SELECT Id FROM ${e.objectApiName}${e.where?` WHERE ${e.where}`:""}`}function gy(r,e){let t=new Set(e.map(n=>n.objectApiName));return r.nodes.map(n=>n.objectApiName).filter(n=>!t.has(n))}function my(r,e){let t=new Set(r.nodes.map(n=>n.objectApiName));return e.map(n=>n.objectApiName).filter(n=>!t.has(n))}function wy(r){if(!Or(r))return;let e=Zt(),t=e?`the table ${r}`:`--object ${r}`;return ac(r)?`${t}: a file goes with the record it hangs on, never as a table of its own. Leave it out${e?"":", and give --files to copy the files of the records cloned"}.`:`${t}: no clone writes it \u2014 users and their access, metadata, a record's history, feed or sharing rows, and the records the platform keeps for itself are not data a copy carries. Leave it out.`}var yy=10;function by(r,e){let t=r.filter(i=>fo(i)&&!Or(i)),n=r.filter(i=>!t.includes(i)),o=i=>e.env?`the table${i.length===1?"":"s"} ${i.join(", ")}`:`--object ${i.join(", ")}`,s=[];if(n.length>0){let i=n.length===1,d=[...e.depth!=="custom"||e.customDepth<yy?[e.env?"the resource's depth":"--depth"]:[],...e.truncated?[e.env?"the resource's maxNodes":"--max-nodes"]:[]],c=e.depth==="custom"?String(e.customDepth):e.depth;s.push(`${o(n)}: discovery from ${e.root} did not reach ${i?"it":"them"} (${e.objects} object(s), depth ${c}${e.truncated?", cut at its cap":""}): name first a table it hangs from or points at`+(d.length>0?`, or raise ${d.join(" or ")}.`:`; no lookup joins ${i?"it":"them"} to ${e.root} within the deepest walk, so clone ${i?"it":"them"} in a run of ${i?"its":"their"} own.`))}return t.length>0&&s.push(`${o(t)}: discovery does not walk into the objects of a managed package's namespace, whose configuration hangs off standard records: name ${t.length===1?"it":"one of them"} first, the table discovery starts from, or clone it in a run of its own.`),s.join(`
|
|
695
|
-
`)}function Ry(r,e,t){return r==="record"?"--template: the template clones from a record it does not name: give --record.":`--template: the template clones from a query, which the command runs as whole tables: give ${e!==void 0?`--object ${e}${t!==void 0?` --where "${t}"`:""}`:"--object <ApiName> --where <condition>"} with --template, its root under the query's condition, and an --object for each other table to clone; or --record to clone one record with its choices.`}function Oy(r){return`Missing ${[...r.includes("what to clone")?["what to clone: --record <id> for one record, --object <ApiName> for whole tables, or --depth all for the whole org"]:[],...r.filter(t=>t.startsWith("--")).map(t=>`${t} <alias>`)].join("; ")}. Run with --help for usage.`}var ng=1e3;function ky(r,e){if(!e.given)return;e.expands||(process.stderr.write(`--max-orphans goes with --expand-orphans: it bounds the parents from outside the run that one copies.
|
|
696
|
-
`),process.exit(2));let t=Number(r);return(r===void 0||!/^\d{1,4}$/.test(r)||t<1||t>ng)&&(process.stderr.write(`--max-orphans takes a whole number of parents, 1 to ${ng}, not "${r??""}".
|
|
697
|
-
`),process.exit(2)),t}function Sy(r,e){let t=r.tables??[],n=[...new Set([...r.excludedObjects,...gy(e,t)])];return{inputMode:"soql",soqlQuery:Dd(t),depth:r.depth,...r.depth==="custom"?{customDepth:r.customDepth}:{},sourceOrgId:r.source,targetOrgId:r.target,anonymizePII:r.anonymize,skipEmpty:!0,batchSize:"auto",...r.maxRecordsPerObject!==void 0?{maxRecordsPerObject:r.maxRecordsPerObject}:{},...Object.keys(r.fieldExclusions).length>0?{fieldExclusions:r.fieldExclusions}:{},...n.length>0?{excludedObjects:n}:{},...Object.keys(r.ownerMappings).length>0?{ownerMappings:r.ownerMappings}:{},...Object.keys(r.objectSoqlFilters).length>0?{objectSoqlFilters:r.objectSoqlFilters}:{},...Object.keys(r.fieldMappings).length>0?{fieldMappings:r.fieldMappings}:{},...r.keepContactPoints?{keepContactPoints:!0}:{},...r.applyAssignmentRules?{applyAssignmentRules:!0}:{},...r.dryRun?{dryRun:!0}:{},...r.decisions}}function Ty(r,e,t,n,o){let s=gd(t,e,{recordTypeMappings:n,anonymizationRules:r.anonymizationRules,...r.files?{files:r.files}:{},stream:{ceiling:r.readCeiling,...r.pageSize!==void 0?{pageSize:r.pageSize}:{}}},o)??{};return r.upsert?{...s,upsertMode:"auto"}:s}function rg(r){return r.depth==="all"?{inputMode:"org"}:r.tables?{inputMode:"soql",soqlQuery:Dd(r.tables)}:{inputMode:"record",recordId:r.record}}function Ay(r){return r.depth==="all"?"the whole org":r.tables?`tables=${r.tables.map(e=>e.where?`${e.objectApiName} (${e.where})`:e.objectApiName).join(", ")}`:`record=${r.record??""}`}var Od=12;function jy(r){if(r.record)return r.record;let e=(r.objects??[]).map(n=>n.objectApiName),t=e.length<=Od?e.join(", "):`${e.slice(0,Od).join(", ")} and ${e.length-Od} more object(s)`;return r.wholeOrg?e.length>0?`the whole org (${t})`:"the whole org":e.length>0?t:"the run"}function vy(r){return{inputMode:"org",depth:"all",sourceOrgId:r.source,targetOrgId:r.target,anonymizePII:r.anonymize,skipEmpty:!0,batchSize:"auto",...Object.keys(r.fieldExclusions).length>0?{fieldExclusions:r.fieldExclusions}:{},...r.excludedObjects.length>0?{excludedObjects:r.excludedObjects}:{},...Object.keys(r.ownerMappings).length>0?{ownerMappings:r.ownerMappings}:{},...Object.keys(r.objectSoqlFilters).length>0?{objectSoqlFilters:r.objectSoqlFilters}:{},...Object.keys(r.fieldMappings).length>0?{fieldMappings:r.fieldMappings}:{},...r.keepContactPoints?{keepContactPoints:!0}:{},...r.applyAssignmentRules?{applyAssignmentRules:!0}:{},...r.dryRun?{dryRun:!0}:{},...r.decisions,...r.sample?{sample:$g(r.sample)}:{}}}function $g(r){let e={...r.options};return delete e.plan,e}function Iy(r,e,t,n,o,s){return gd(t,e,{recordTypeMappings:n,anonymizationRules:r.anonymizationRules,...r.files?{files:r.files}:{},stream:{wholeReadBound:r.readCeiling,...r.pageSize!==void 0?{pageSize:r.pageSize}:{},...s?{sample:s}:{}}},o)??{}}function Ey(r,e){return e.size===0?r:{...r,nodes:r.nodes.map(t=>e.has(t.objectApiName)?{...t,included:!1,leftOutByUser:!0}:t)}}var og=1e6;function $y(r,e){if(e.length>og)return{refusal:[`${r}: the file is larger than ${og} bytes`]};let t;try{t=JSON.parse(e.replace(/^\uFEFF/,""))}catch{return{refusal:[`${r}: the file is not JSON`]}}let n=s=>s.issues.map(i=>{let a=i.path.map(String).join(".");return`${r}${a?` (${a})`:""}: ${i.message}`});if(r==="--template"){let s=ic.safeParse(t);return s.success?{file:{kind:"template",template:s.data}}:{refusal:n(s.error)}}let o=py.safeParse(t);return o.success?{file:{kind:"config",config:o.data}}:{refusal:[...n(o.error),`${r} takes ${Eg.join(", ")}; the other choices have flags of their own.`]}}var _d=["--fit-within","--fit-seed","--fit-draw","--fit-parents","--fit-children","--fit-whole","--fit-floor","--fit-plan"],xy={switches:["--list-objects","--anonymize","--keep-contact-points","--dry-run","--rehearse","--accept-automation","--accept-emails","--mute-automation","--upsert","--expand-orphans","--apply-assignment-rules","--skip-preflight","--json","--fail-on-partial","--write-uncertain","--files","--files-as-is","--no-anonymize","--yes",...md.switches,"--include-changed"],values:["--record","--source","--target","--object","--where","--depth","--custom-depth","--max","--max-nodes","--max-total","--max-records-per-object","--max-orphans","--summary","--resume","--exclude","--exclude-object","--owner-map","--filter","--map","--config","--template","--remap-csv","--max-file-size","--audit","--fit",..._d,...md.values]},Py=[["--record","it starts from no record"],["--object","it starts from no table: --exclude-object leaves one out"],["--where","it starts from no table: --filter narrows an object"],["--template","a template holds the choices of a walk from its record or query: give them with --config"],["--custom-depth","it walks no depth"],["--max-nodes","it takes every object it can, and is refused past 1950 rather than cut"],["--max","it copies every row of what it takes: --filter narrows an object, and --fit share copies a sample of the org that fits the target, none of its records without those they name"],["--expand-orphans","every parent it reaches is in the org it copies"],["--max-orphans","every parent it reaches is in the org it copies"],["--rehearse","a rehearsal holds every row it prepares: --dry-run counts what a real run would write and says what would refuse it, writing nothing"],["--upsert",`its writes go as Bulk API jobs that insert. To copy the org again without its records twice: --resume <journal> takes up a run that stopped, writing nothing it wrote; --remove <summary> takes back a run that ended before the copy is made again; or ${Qt("empty")} --target <alias> --objects <A,B> --dry-run says what emptying the target's objects would delete, every record of them`]];function Cy(r,e){if(!e){let n=["--yes","--no-anonymize"].filter(o=>r(o));if(n.length===0)return;process.stderr.write(`${n.join(" and ")} ${n.length===1?"goes":"go"} with --depth all: no other clone asks before it writes, and none anonymizes unless --anonymize is given.
|
|
698
|
-
`),process.exit(2)}let t=Py.filter(([n])=>r(n));if(r("--anonymize")&&r("--no-anonymize")&&t.push(["--anonymize","it is given --no-anonymize too: give one of them"]),t.length!==0){for(let[n,o]of t)process.stderr.write(`--depth all clones the whole org, and does not go with ${n}: ${o}.
|
|
699
|
-
`);process.exit(2)}}var Fy=_d.filter(r=>r!=="--fit-whole"),sg=1e4,ig=1e6,ag=1e6,Ny="sample.json";function My(r,e){let t=b=>(process.stderr.write(`${b}
|
|
700
|
-
`),process.exit(2)),n=b=>r.flatMap((S,R)=>S===b&&R+1<r.length?[r[R+1]]:[]),o=b=>r.includes(b),s=_d.filter(b=>o(b));if(!o("--fit"))return s.length===0?void 0:t(`${s.join(", ")} ${s.length===1?"goes":"go"} with --depth all --fit share: ${s.length===1?"it sets":"they set"} how a sample of the whole org is drawn, and the line asks for none.`);let i=n("--fit");if(i.length!==1||i[0]!=="share")return t(`--fit takes share, once, not "${i.join(" ")}".`);if(!e.wholeOrg)return t("--fit share goes with --depth all: it copies a sample of the whole org that fits the target. A clone of a record or of tables reads what it reaches: --max caps each object.");if(o("--files"))return t("--fit share copies no files: the sample goes without the files of its records, and --files does not go with it. Leave out --files.");if(o("--list-objects"))return t("--list-objects lists the objects of the graph and draws no sample: leave out --fit share.");if(o("--fit-plan")&&o("--resume"))return t("--fit-plan does not go with --resume: a run taken up writes the plan its journal names, the one it began with.");for(let b of Fy)n(b).length>1&&t(`${b} is given twice: give it once.`);let a=b=>n(b)[0],d={maxTotal:e.maxTotal},c=a("--fit-within");if(c!==void 0){let b=Number(c);(!/^\d+(?:\.\d+)?$/.test(c)||b<=0||b>ag)&&t(`--fit-within takes a number of MB above 0, up to ${ag}, not "${c}".`),d.withinMB=b}let l=a("--fit-seed");l!==void 0&&(/^\d{1,15}$/.test(l)||t(`--fit-seed takes a whole number, 0 or more, not "${l}".`),d.seed=Number(l));let u=a("--fit-draw");u!==void 0&&(u!=="uniform"&&u!=="recent"&&t(`--fit-draw takes uniform, the roots spread over each object by the seed, or recent, the newest by their creation date, not "${u}".`),d.draw=u);let p=a("--fit-parents");p!==void 0&&(p!=="all"&&p!=="required"&&t(`--fit-parents takes all, the records an optional lookup names copied without their children, or required, such a lookup left empty, not "${p}".`),d.parents=p);let f=a("--fit-children");if(f!==void 0){let b=Number(f);f==="all"?d.children="all":/^\d{1,7}$/.test(f)&&b>=1&&b<=ig?d.children=b:t(`--fit-children takes a whole number of children from 1 to ${ig}, or all, not "${f}".`)}let h=[];for(let b of n("--fit-whole"))at.test(b)||t(`Invalid --fit-whole value "${b}" (must match SObject API name pattern)`),h.includes(b)||h.push(b);let g=h.filter(b=>e.excludedObjects.includes(b));g.length>0&&t(`--fit-whole and --exclude-object both name ${g.join(", ")}: the sample would copy whole an object the run leaves out. Give each to one of them.`),h.length>0&&(d.whole=h);let m=a("--fit-floor");if(m!==void 0){let b=Number(m);(!/^\d{1,5}$/.test(m)||b>sg)&&t(`--fit-floor takes a whole number of records from 0 to ${sg}, not "${m}".`),d.floor=b}let w=a("--fit-plan");if(w!==void 0){let b=Ct(w);d.plan=iy(b)===Ny?ay(b):b}return{options:d,maxTotalGiven:e.maxTotalGiven}}function By(r,e=process.env){let t=r.slice(2);(t.includes("-h")||t.includes("--help"))&&(process.stdout.write(Wd),process.exit(0)),bc(t,xy);let n=(P,z)=>{let ee=t.indexOf(P);return ee>=0&&ee+1<t.length?t[ee+1]:z},o=P=>t.includes(P);o("--config")&&o("--template")&&(process.stderr.write(`--config and --template: give one of them.
|
|
701
|
-
`),process.exit(2));let s=o("--template")?"--template":o("--config")?"--config":void 0,i=s?n(s):void 0,a;if(s){(!i||i.startsWith("--"))&&(process.stderr.write(`${s} takes the path of a JSON file.
|
|
702
|
-
`),process.exit(2));let P;try{P=kn(i,"utf8")}catch(ee){process.stderr.write(`${s}: cannot read ${i}: ${Y(ee)}
|
|
703
|
-
`),process.exit(2)}let z=$y(s,P);if("refusal"in z){for(let ee of z.refusal)process.stderr.write(`${ee}
|
|
704
|
-
`);process.exit(2)}a=z.file}let d=a?.kind==="template"?a.template:void 0,c=n("--depth")==="all";Cy(o,c);let l=a?.kind==="template"?{...a.template.config}:a?.config??{},u=d?.config.soqlQuery!==void 0?fy(d.config.soqlQuery):void 0,p=u!==void 0?l.objectSoqlFilters?.[u]:void 0;if(u!==void 0&&l.objectSoqlFilters?.[u]!==void 0){let P={...l.objectSoqlFilters};delete P[u],l.objectSoqlFilters=P}let f=hy(t);if(f){let P=["--record","--expand-orphans","--max-orphans","--rehearse"].filter(z=>o(z));if(P.length>0){let z=P.includes("--rehearse")?" --dry-run reads the tables and counts what a real run would write, and says what would refuse it, writing nothing.":"";process.stderr.write(`--object clones whole tables, as the panel runs a query: it does not go with ${P.join(", ")}, which ${P.length===1?"goes":"go"} with a clone of one record (--record).${z}
|
|
705
|
-
`),process.exit(2)}d?.config.expandOrphanParents===!0&&(process.stderr.write(`--template: the template brings orphan parents (expandOrphanParents), which go with a clone of one record (--record), not with --object.
|
|
706
|
-
`),process.exit(2))}let h=d?.config.inputMode==="record"?d.config.recordId:void 0;d&&!f&&!o("--record")&&!h&&(process.stderr.write(`${Ry(d.config.inputMode,u,p)}
|
|
707
|
-
`),process.exit(2));let g=f||c?void 0:n("--record")??h,m=n("--source"),w=n("--target"),b=[...!g&&!f&&!c?["what to clone"]:[],...m?[]:["--source"],...w?[]:["--target"]];(b.length>0||!m||!w)&&(process.stderr.write(`${Oy(b)}
|
|
708
|
-
`),process.exit(2)),o("--include-changed")&&(process.stderr.write(`--include-changed goes with --remove.
|
|
709
|
-
`),process.exit(2));let S=["--dry-run","--upsert","--files","--remap-csv","--list-objects"].filter(P=>o(P));o("--rehearse")&&S.length>0&&(process.stderr.write(`--rehearse does not go with ${S.join(", ")}.
|
|
710
|
-
`),process.exit(2));let R=Ky(t),k=Vh(t,[{flag:"--rehearse",why:"a rehearsal keeps nothing it creates in the target, and there is nothing to take back."},{flag:"--list-objects",why:"it lists the objects of the graph, and writes nothing."},{flag:"--resume",why:"a run taken up is the run its first part began, and a checkpoint taken now would hold what that part wrote: rewind to the one it took, if it took one."}]),I=n("--depth")??d?.config.depth??"custom",O=n("--custom-depth")??(d?.config.customDepth!==void 0?String(d.config.customDepth):"5"),A=n("--max")??(d?.config.maxRecordsPerObject!==void 0?String(d.config.maxRecordsPerObject):void 0),x=n("--max-nodes")??(d?.config.maxNodes!==void 0?String(d.config.maxNodes):void 0),j=n("--max-total"),E=n("--max-records-per-object"),$=P=>{let z=[];for(let ee=0;ee<t.length;ee++)t[ee]===P&&ee+1<t.length&&z.push(t[ee+1]);return z},L=Object.fromEntries(Object.entries(l.fieldExclusions??{}).map(([P,z])=>[P,[...z]]));for(let P of $("--exclude")){let z=P.indexOf(".");(z<=0||z===P.length-1)&&(process.stderr.write(`Invalid --exclude value "${P}" (expected Object.field)
|
|
711
|
-
`),process.exit(2));let ee=P.slice(0,z),X=P.slice(z+1);(!at.test(ee)||!at.test(X))&&(process.stderr.write(`Invalid --exclude name in "${P}" (must match SObject API name pattern)
|
|
712
|
-
`),process.exit(2));let _e=L[ee]??=[];_e.includes(X)||_e.push(X)}let Q=[...l.excludedObjects??[]];for(let P of $("--exclude-object"))at.test(P)||(process.stderr.write(`Invalid --exclude-object value "${P}" (must match SObject API name pattern)
|
|
713
|
-
`),process.exit(2)),Q.includes(P)||Q.push(P);let G={...l.ownerMappings};for(let P of $("--owner-map")){let z=P.indexOf("=");(z<=0||z===P.length-1)&&(process.stderr.write(`Invalid --owner-map value "${P}" (expected sourceId=targetId)
|
|
714
|
-
`),process.exit(2));let ee=P.slice(0,z),X=P.slice(z+1);(!Gr.test(ee)||!Gr.test(X))&&(process.stderr.write(`Invalid --owner-map IDs in "${P}" (must be 15 or 18 char Salesforce IDs)
|
|
715
|
-
`),process.exit(2)),G[ee]=X}let V={...l.objectSoqlFilters};for(let P of $("--filter")){let z=P.indexOf("=");(z<=0||z===P.length-1)&&(process.stderr.write(`Invalid --filter value "${P}" (expected Object=where-clause)
|
|
716
|
-
`),process.exit(2));let ee=P.slice(0,z),X=P.slice(z+1);X.length>512&&(process.stderr.write(`--filter where-clause for "${ee}" exceeds 512 chars
|
|
717
|
-
`),process.exit(2)),/--|\/\*|\*\/|;\s*$/.test(X)&&(process.stderr.write(`--filter where-clause for "${ee}" contains forbidden tokens (--, /*, */, trailing ;)
|
|
718
|
-
`),process.exit(2)),V[ee]=X}let q=new Set($("--filter").map(P=>P.slice(0,P.indexOf("="))));for(let P of f??[])P.where!==void 0&&(q.has(P.objectApiName)&&(process.stderr.write(`--where and --filter both filter ${P.objectApiName}: give one of them.
|
|
719
|
-
`),process.exit(2)),P.where.length>512&&(process.stderr.write(`--where for "${P.objectApiName}" exceeds 512 chars
|
|
720
|
-
`),process.exit(2)),/--|\/\*|\*\/|;\s*$/.test(P.where)&&(process.stderr.write(`--where for "${P.objectApiName}" contains forbidden tokens (--, /*, */, trailing ;)
|
|
721
|
-
`),process.exit(2)),V[P.objectApiName]=P.where);let me=Object.fromEntries(Object.entries(l.fieldMappings??{}).map(([P,z])=>[P,{...z}]));for(let P of $("--map")){let z=P.indexOf("."),ee=P.indexOf("=");(z<=0||ee<=z+1||ee===P.length-1)&&(process.stderr.write(`Invalid --map value "${P}" (expected Object.sourceField=targetField)
|
|
722
|
-
`),process.exit(2));let X=P.slice(0,z),_e=P.slice(z+1,ee),M=P.slice(ee+1);(!at.test(_e)||!at.test(M))&&(process.stderr.write(`Invalid --map field name in "${P}" (must match SObject API name pattern)
|
|
723
|
-
`),process.exit(2)),(me[X]??={})[_e]=M}let de=O?Number(O):5,H=A?Number(A):void 0,pe=x?Number(x):void 0;pe!==void 0&&(!Number.isInteger(pe)||pe<1)&&(process.stderr.write(`--max-nodes takes a whole number of objects, 1 or more.
|
|
724
|
-
`),process.exit(2));let ue=ky(n("--max-orphans"),{given:o("--max-orphans"),expands:o("--expand-orphans")||d?.config.expandOrphanParents===!0}),be=j===void 0?Yn:Number(j);(!Number.isInteger(be)||be<1)&&(process.stderr.write(`--max-total takes a whole number of records, 1 or more.
|
|
725
|
-
`),process.exit(2));let ne=E===void 0?ro:Number(E);(!Number.isInteger(ne)||ne<1||ne>oi)&&(process.stderr.write(`--max-records-per-object takes a whole number of records, 1 to ${oi}.
|
|
726
|
-
`),process.exit(2));let K=e.SANDFORGE_FORGE_PAGE_SIZE,Z=K===void 0||K===""?void 0:Number(K);Z!==void 0&&(!Number.isInteger(Z)||Z<1)&&(process.stderr.write(`SANDFORGE_FORGE_PAGE_SIZE takes a whole number of rows, 1 or more.
|
|
727
|
-
`),process.exit(2));let U=o("--anonymize")||d?.config.anonymizePII===!0,se=o("--keep-contact-points")||d?.config.keepContactPoints===!0,Se=Jy(t,U),ge=Mo(l),Te=My(t,{wholeOrg:c,maxTotal:be,maxTotalGiven:j!==void 0,excludedObjects:Q}),_=(c?ei:ei.safeExtend({depth:oc})).safeParse({...c?{inputMode:"org"}:f?{inputMode:"soql",soqlQuery:Dd(f)}:{inputMode:"record",recordId:g},depth:I,customDepth:I==="custom"?de:void 0,sourceOrgId:m,targetOrgId:w,anonymizePII:U,keepContactPoints:se,skipEmpty:!0,batchSize:"auto",maxRecordsPerObject:H,fieldExclusions:L,excludedObjects:Q,ownerMappings:G,objectSoqlFilters:V,fieldMappings:me,...ge,...Te?{sample:Te.options}:{}});if(!_.success){for(let P of _.error.issues){let[z,...ee]=P.path.map(String),X=uy[z??""]??(s&&z?`${s} ${z}`:z??"arguments"),_e=ee.length>0?` (${ee.join(".")})`:"";process.stderr.write(`Invalid ${X}${_e}: ${P.message}
|
|
728
|
-
`)}process.exit(2)}return{record:g,tables:f,source:m,target:w,depth:_.data.depth,customDepth:de,maxNodes:pe,maxRecordsPerObject:H,anonymize:U,anonymizeGiven:o("--anonymize")||o("--no-anonymize"),yes:o("--yes"),keepContactPoints:_.data.keepContactPoints===!0,dryRun:o("--dry-run"),listObjects:o("--list-objects"),upsert:o("--upsert"),expandOrphans:o("--expand-orphans")||d?.config.expandOrphanParents===!0,...ue!==void 0?{maxOrphans:ue}:{},applyAssignmentRules:o("--apply-assignment-rules")||d?.config.applyAssignmentRules===!0,skipPreflight:o("--skip-preflight"),json:o("--json"),failOnPartial:o("--fail-on-partial"),summary:R,fieldExclusions:L,excludedObjects:Q,ownerMappings:G,objectSoqlFilters:V,fieldMappings:me,remapCsv:Vy(t),files:Se,acceptAutomation:o("--accept-automation"),acceptEmails:o("--accept-emails"),muteAutomation:o("--mute-automation"),...k!==void 0?{checkpointFirst:k}:{},maxTotal:be,readCeiling:ne,...Z!==void 0?{pageSize:Z}:{},rehearse:o("--rehearse"),decisions:ge,anonymizationRules:{...d?.anonymization?.rules},anonymizeFields:d?.anonymization?.fields,choicesFrom:s&&i?{flag:s,path:i}:void 0,audit:Ud(t),resume:Dy(t),writeUncertain:Ly(t),...Te?{sample:Te}:{}}}function Ly(r){return r.includes("--write-uncertain")?(r.includes("--resume")||(process.stderr.write(`--write-uncertain goes with --resume: it writes the rows of a call under way when the run stopped that the target may already hold.
|
|
729
|
-
`),process.exit(2)),!0):!1}function Wy(r,e){let t=$a(r),n=l=>(l??[]).reduce((u,p)=>u+p.rows,0),o=r.uncertain.map(({objectApiName:l,rows:u})=>`${u} ${l}`).join(", "),s=r.underway??[],i=n(r.untold),a=n(r.ofEndedJobs)-i,d=t-n(s)-i-a,c=[`${t} row(s) may already be in ${e} (${o}), sent by insert calls the run had under way when it stopped, their answer never kept.`];for(let l of s){let u=`${l.rows} of them went in Bulk API job ${l.jobId} (${l.objectApiName}), which ${e} holds ${l.state??"not ended"}`+(l.processed!==void 0?`, ${l.processed} row(s) processed`:"");c.push(l.state==="Open"?`${u}: the run stopped before it closed it, and closed, it would still write them.`:`${u}: ${e} writes it to its end whatever became of the run.`)}i>0&&c.push(`${i} of them went in a Bulk API job that wrote records the journal cannot tell apart, several rows under one fingerprint: none of those records is linked to a row, and each is kept as written by the run, for --remove to take back.`),a>0&&c.push(`${a} of them went in a Bulk API job that wrote records whose values are not what the run sent: none is taken for one of them, and each is kept as written by the run.`),d>0&&c.push(`${d} of them went in calls whose records ${e} holds and the resume cannot tell from them, or could not read.`),c.push("Nothing was written.");for(let l of s)c.push(l.state==="Open"?`Run the same --resume again ${l.openUntil!==void 0?`from ${l.openUntil}`+(l.graceLeftMs!==void 0?`, in about ${Math.max(1,Math.ceil(l.graceLeftMs/6e4))} minute(s)`:""):"an hour after the job was opened"}: it aborts job ${l.jobId} if it is open still, then writes its rows.`:`Run the same --resume again once job ${l.jobId} has ended: it reads what the job wrote, row by row.`);return i+a+d>0&&c.push(`Look at the records of those objects the run's user created in ${e} as the run stopped; run the same --resume with --write-uncertain to write those rows all the same (one already there is then there twice), or --remove the run.`),c.join(" ")}function Dy(r){let e=r.indexOf("--resume");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--resume takes the journal of the run to take up, or its run id.
|
|
730
|
-
`),process.exit(2));let n=["--dry-run","--rehearse","--list-objects"].filter(o=>r.includes(o));return n.length>0&&(process.stderr.write(`--resume takes a run up and writes: it does not go with ${n.join(", ")}.
|
|
731
|
-
`),process.exit(2)),t}function qt(r=process.env){let e=r.SANDFORGE_JOURNAL_DIR;return e!==void 0&&e.trim()!==""?Ct(e):$s(sy(),".sandforge")}function dg(r,e){return r.endsWith(".ndjson")||/[\\/]/.test(r)?Ct(r):e.pathOf(r)}function cg(r,e,t={}){return{...r.sample?{sample:tf(r.sample.options,t.planSha256),...t.sourceOrgId?{sourceOrgId:t.sourceOrgId.slice(0,15)}:{}}:{},source:r.source,targetOrgId:e.slice(0,15),record:r.record,...r.tables?{tables:r.tables}:{},depth:r.depth,customDepth:r.depth==="custom"?r.customDepth:null,maxNodes:r.maxNodes??null,maxRecordsPerObject:r.maxRecordsPerObject??null,anonymize:r.anonymize,keepContactPoints:r.keepContactPoints,upsert:r.upsert,expandOrphans:r.expandOrphans,...r.maxOrphans!==void 0?{maxOrphans:r.maxOrphans}:{},applyAssignmentRules:r.applyAssignmentRules,fieldExclusions:r.fieldExclusions,excludedObjects:r.excludedObjects,ownerMappings:r.ownerMappings,objectSoqlFilters:r.objectSoqlFilters,fieldMappings:r.fieldMappings,decisions:r.decisions??null,anonymizationRules:r.anonymizationRules,anonymizeFields:r.anonymizeFields??null,files:r.files??null,readCeiling:r.depth==="all"?null:r.readCeiling}}async function _y(r,e,t){let n=await r.headAt(e);if(!n)return{code:"RESUME_UNAVAILABLE",message:`--resume ${e}: there is no journal of a run there. Every run that writes says its journal as it starts (journal: \u2026), under SANDFORGE_JOURNAL_DIR when it is set: give that file, or its run id. Nothing was written.`};if(!n.resume)return{code:"RESUME_UNAVAILABLE",message:`--resume ${e}: the journal does not say how its run was set up, and the run cannot be taken up: --remove ${e} takes back what it wrote, then run the clone again. Nothing was written.`};if((await r.lastEndAt(e))?.status==="success")return{code:"RESUME_UNAVAILABLE",message:`--resume ${e}: the run ended, and there is nothing of it to take up.`};if(n.targetOrgId.slice(0,15)!==t.targetOrgId.slice(0,15))return{code:"RESUME_TARGET_CHANGED",message:`${t.target} is not the org the run to take up wrote to (${n.targetOrgId}): it is taken up there only. Nothing was written.`};let s=t.setup,i=qy(r,e),a=t.sample?.asked===!0;if(i===void 0&&a)return{code:Yo,message:`--resume ${e}: the run to take up copied every record of the whole org, not a sample: take it up without --fit share and its --fit-* flags. Nothing was written.`};if(i!==void 0&&!a)return{code:Yo,message:`--resume ${e}: the run to take up copied a sample of the whole org: take it up with --fit share and the --fit-* flags it ran with. Nothing was written.`};if(i!==void 0&&t.sample){let d;try{d=await er.open(i.dir,{sha256:i.sha256})}catch(c){let l=Qo(c,"resume");if(!l)throw c;return{code:l.code,message:l.message.replace(/ Nothing was written\.$/,` It was in ${i.dir}. Nothing was written.`)}}d.manifest.drawnBy==="dryRun"&&(s=t.sample.setupWith(d.sha256))}if(!nf(n.resume.fingerprint,t.graph,s))return{code:"RESUME_CHANGED",message:`The clone is set up otherwise than the run to take up: ${Gy(n.resume,t)}. Give the same record or tables, orgs, depth, choices and flags it ran with; or take back what it wrote with --remove ${e}, and run the clone again as it is now. Nothing was written.`}}var Uy={sourceOrgId:"--source",depth:"--depth",customDepth:"--custom-depth",soqlQuery:"the first --object and its --where",anonymizePII:"--anonymize",keepContactPoints:"--keep-contact-points",maxRecordsPerObject:"--max",objectSoqlFilters:"--filter or --where",excludedObjects:"--exclude-object",fieldExclusions:"--exclude",fieldMappings:"--map",ownerMappings:"--owner-map",applyAssignmentRules:"--apply-assignment-rules",sample:"--fit and its --fit-* flags",picklistValueMappings:"the decisions of --config or --template",recordTypeMappings:"the decisions of --config or --template",defaultValues:"the decisions of --config or --template",truncateFields:"the decisions of --config or --template",skippedRows:"the decisions of --config or --template",ignoredGaps:"the decisions of --config or --template"},zy=new Set(["inputMode","targetOrgId","skipEmpty","batchSize","dryRun"]);function Gy(r,e){let t=[];r.recordId!==void 0&&e.record!==void 0&&r.recordId.slice(0,15)!==e.record.slice(0,15)&&t.push(`--record (${r.recordId} then, ${e.record} now)`);let n=r.startedWith;if(n&&e.config){let o={...n.config},s={...e.config},i=[...new Set([...Object.keys(o),...Object.keys(s)])].filter(f=>!zy.has(f)&&f!=="recordId"),a=new Set;for(let f of i)JSON.stringify(o[f]??null)!==JSON.stringify(s[f]??null)&&a.add(Uy[f]??f);a.size>0&&t.push(`${[...a].join(", ")} differ`);let d=f=>new Set(f.nodes.filter(h=>h.included||mr(h)).map(h=>h.objectApiName)),c=d(n.graph),l=d(e.graph),u=[...c].filter(f=>!l.has(f)),p=[...l].filter(f=>!c.has(f));u.length>0&&t.push(`it took ${an(u)}, which this one leaves`),p.length>0&&t.push(`this one takes ${an(p)}, which it left`)}return t.length>0?t.join("; "):"what differs is among what its journal does not keep: --upsert, --expand-orphans, --max-orphans, --max-nodes, --max-records-per-object, --files, --keep-contact-points, --exclude, --exclude-object, --owner-map, --map and the choices of --config or --template"}function qy(r,e){let t=r.openAt(e);try{return t.samplePlan}finally{t.close()}}function Ud(r){let e=r.indexOf("--audit");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--audit takes the file the audit trail is kept in.
|
|
732
|
-
`),process.exit(2));try{ba(t)}catch(n){process.stderr.write(`--audit ${t} is not an audit trail the command can add to (${Y(n)}): give another file, or move it.
|
|
733
|
-
`),process.exit(2)}return t}function Hy(r,e){return{configStore:ba(r),orgManager:{getOrg:t=>e.get(t)},log:t=>process.stderr.write(`${t}
|
|
734
|
-
`)}}function xs(r,e,t){if(r)try{Fc(Hy(r,e),t)}catch(n){process.stderr.write(`The run's entry could not be added to the audit trail in ${r} (${Y(n)}).
|
|
735
|
-
`)}}function Ky(r){let e=r.indexOf("--summary");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--summary takes the file to write the summary to.
|
|
736
|
-
`),process.exit(2));let n=["--list-objects","--rehearse"].filter(o=>r.includes(o));return n.length>0&&(process.stderr.write(`--summary does not go with ${n.join(", ")}.
|
|
737
|
-
`),process.exit(2)),Sn(t)&&(process.stderr.write(`--summary ${t} exists, and is not overwritten: it may be the summary of an earlier run, which --remove takes that run back from. Give another file, or move it.
|
|
738
|
-
`),process.exit(2)),t}function Vy(r){let e=r.indexOf("--remap-csv");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--remap-csv takes the .csv file to write the id table to.
|
|
739
|
-
`),process.exit(2));let n=Ct(process.cwd(),t),o=Ct(process.cwd());return n===o||n.startsWith(o+dy)||(process.stderr.write(`--remap-csv must stay inside cwd: "${t}" resolves outside ${o}
|
|
740
|
-
`),process.exit(2)),n.toLowerCase().endsWith(".csv")||(process.stderr.write(`--remap-csv must use a .csv extension: "${t}"
|
|
741
|
-
`),process.exit(2)),Sn(n)&&(process.stderr.write(`--remap-csv refuses to overwrite existing file: "${n}". Give another file, or move it.
|
|
742
|
-
`),process.exit(2)),n}function Jy(r,e){let t=r.includes("--files"),n=r.includes("--files-as-is"),o=r.indexOf("--max-file-size"),s=o>=0?r[o+1]:void 0;if(!t){(n||o>=0)&&(process.stderr.write(`--files-as-is and --max-file-size go with --files.
|
|
743
|
-
`),process.exit(2));return}let i=o>=0?Number(s):10;return(!Number.isInteger(i)||i<1||i>35)&&(process.stderr.write(`--max-file-size takes a whole number of MB from 1 to ${35}, the most one call to Salesforce carries.
|
|
744
|
-
`),process.exit(2)),Xr(e,n)&&(process.stderr.write(`--anonymize anonymizes the records, and the content of a file cannot be anonymized: add --files-as-is to accept that files are copied as they are, or leave out --files.
|
|
745
|
-
`),process.exit(2)),{maxFileSizeMB:i,acceptedAsIs:n}}function Yy(r){let e=Gc(r.fields);return r.fields.map(t=>({name:t.name,type:t.type,queryable:!0,createable:t.createable??!1,isReference:t.type==="reference",referenceTo:(t.referenceTo??[]).filter(n=>typeof n=="string"),nillable:t.nillable??!0,picklistValues:(t.picklistValues??[]).filter(n=>n?.active!==!1&&typeof n?.value=="string").map(n=>n.value),restrictedPicklist:t.restrictedPicklist===!0,...t.controllerName?{controllerName:t.controllerName}:{},defaultedOnCreate:t.defaultedOnCreate===!0,externalId:t.externalId===!0,updateable:t.updateable!==!1,...t.length>0?{length:t.length}:{},...qc(t,e),...typeof t.groupable=="boolean"?{groupable:t.groupable}:{},...typeof t.sortable=="boolean"?{sortable:t.sortable}:{},...typeof t.aggregatable=="boolean"?{aggregatable:t.aggregatable}:{}}))}function Qy(r){return{name:r.name,fields:r.fields.map(e=>({name:e.name,type:String(e.type),referenceTo:(e.referenceTo??[]).filter(t=>typeof t=="string"),relationshipName:e.relationshipName??null,isMasterDetail:e.cascadeDelete===!0,nillable:e.nillable!==!1,createable:e.createable!==!1,updateable:e.updateable!==!1})),childRelationships:r.childRelationships.map(e=>({childSObject:e.childSObject,field:e.field,relationshipName:e.relationshipName??"",isCascadeDelete:!!e.cascadeDelete}))}}async function Xy(r,e,t){let n="SELECT Id, Name, DeveloperName, NamespacePrefix, SobjectType FROM RecordType WHERE IsActive = true",o=async l=>(await Ti({query:async u=>l.query(u),queryMore:async u=>l.queryMore(u)},n)).records,[s,i]=await Promise.all([o(r),o(e)]),a=l=>({id:l.Id,name:l.Name,developerName:l.DeveloperName,namespacePrefix:l.NamespacePrefix?l.NamespacePrefix:null,sobjectType:l.SobjectType}),[d,c]=[s.map(a),i.map(a)];for(let l of Xu(d,c))t?.(Zu(l));return new ts().buildMapping(d,c)}function Zy(r){let e=new Map;return(t,n)=>{let o=`${t}::${n}`,s=e.get(o);if(s)return s;let i=r(t,n);return e.set(o,i),i.catch(()=>{e.get(o)===i&&e.delete(o)}),i}}async function kd(r,e,t=!1){let n=t?await r.sobject(e).describe():await r.describe$(e);return{keyPrefix:n.keyPrefix??null,recordTypes:Xc(n.recordTypeInfos)}}function RA(r){return go(r)==="failure"}var Sd={masterInSource:"on Master in the source",notRead:"whose record type the run does not write",decidedDefault:"sent to the default by your decision",dropped:"whose record type the target lacks or keeps from the user"};function xd({developerName:r,label:e}){return e!==""&&e!==r?`${r} (${e})`:r}function Td(r,e){let{predicted:t}=r;if(!t)return`${e} on Master, which the target gives a record sent without one for the user the run writes as`;let n=xd(t);return t.basis==="userDefault"?`${e} as ${n}, the default record type of the user the run writes as`:`${e} as ${n}, the only other ${r.objectApiName} record type open to the user the run writes as, whose describe names Master the default`}function eb(r,e){let t=e.read<r.rows?`${e.read} of ${r.rows}`:`${e.read}`,n=r.predicted?.developerName??"Master",[o,...s]=e.types;if(o&&s.length===0&&o.developerName===n)return`went in as ${xd(o)}, read back on ${t}`;if(!o)return`none of them found as they were read back (asked of ${t})`;let i=e.types.map(a=>`${a.rows} ${xd(a)}`).join(", ");return`read back on ${t}: ${i}; the describe said ${n}: an automation of the target sets the record type`}function tb(r,e){if(r.length===0)return[];let t=[`record types the target ${e?"would give":"gave"} the records created without one (${r.length} object(s)):`];for(let n of r){let o=Object.keys(Sd).filter(d=>(n.why[d]??0)>0),s=o.length===1?` ${Sd[o[0]]}`:o.length>1?` (${o.map(d=>`${n.why[d]} ${Sd[d]}`).join(", ")})`:"",{readBack:i}=n,a=e?Td(n,"would go in"):i?i.unread!==void 0?`${Td(n,"went in, its describe says,")}; the record types they hold could not be read back: ${i.unread}`:eb(n,i):Td(n,"went in, its describe says,");t.push(` ${n.objectApiName} ${n.rows} record(s)${s}: ${a}`)}return t}function nb(r,e){let t=Gn(r.maxFileBytes),n=[`files (up to ${t} each):`];r.lookupFailure&&n.push(` ${r.lookupFailure}`," A real run stops here, before writing anything.");for(let o of r.objects){let s=Gn(o.plannedBytes);n.push(e?` ${o.objectApiName} ${o.planned} would be copied (${s}, dry run, nothing written)`:` ${o.objectApiName} ${o.copied} of ${o.planned} copied (${s})`+(o.failed>0?`, ${o.failed} failed`:""))}if(r.objects.length===0&&!r.lookupFailure&&n.push(" none to copy"),e&&r.wouldCopy&&r.wouldCopy.length>0){n.push(` would copy (${r.wouldCopy.length}):`);for(let o of r.wouldCopy)n.push(` ${o.objectApiName} ${o.name} ${Gn(o.bytes)}`)}if(r.links>0&&n.push(` links to other cloned records: ${r.links}`),r.remainingStorageBytes!==void 0&&n.push(` target file storage left: ${Gn(r.remainingStorageBytes)}`),r.leftOut.length>0){n.push(` left out (${r.leftOut.length}):`);for(let o of r.leftOut){let s=o.reason==="too-large"?`larger than ${t}`:o.reason==="external"?"kept outside Salesforce":"its records were not created by this run";n.push(` ${o.objectApiName} ${o.name} ${Gn(o.bytes)} \u2014 ${s}`)}}return n}function xg(r,e){let t=r.truncatedObjects??[];if(t.length!==0)return{...e!==void 0?{perObject:e}:{},objects:[...t]}}function rb(r){let e=new Map;for(let{objectApiName:i,rows:a}of r.writtenByThePlatform??[]){let d=Hn(i);e.set(d,(e.get(d)??0)+a)}let t=[...e.values()].reduce((i,a)=>i+a,0),n=r.linkedToCreatedCount??0;if(t===0&&n===0)return`linked: ${r.linkedCount} (already in the target, not created)`;let o=r.linkedCount-t-n,s=[...o>0?[`${o} already in the target, not created`]:[],...n>0?[`${n} to records the run created, the target refusing them as copies of those`]:[],...[...e].map(([i,a])=>`${a} written by the platform with ${i}`)];return`linked: ${r.linkedCount} (${s.join("; ")})`}var Ad="FIELD_EXCLUSION_UNMATCHED";function Pg(r){let e=`${yn("--exclude","the exclusion")} ${r.objectApiName}.${r.field}`;return r.missing==="object"?`${e}: the source has no object ${r.objectApiName}`:`${e}: ${r.objectApiName} has no field ${r.field}`+(r.nearest!==void 0?` (${r.nearest}?)`:"")}function ob(r){return[`left nothing out, naming no field of the source (${r.length}):`,...r.map(e=>` ${Pg(e)}`)]}function lg(r,e){let t=Zt()?" of the template the resource names":e?` of --exclude, or of the fieldExclusions of ${e.flag} ${e.path}`:"";return`${r.map(Pg).join("; ")}: ${r.length===1?"it leaves":"they leave"} nothing out, and the field the run was asked to keep back would be written with every row. Name the field as the source does \u2014 whatever its case \u2014 or leave the exclusion out${t}. Nothing was read or written.`}async function sb(r,e,t){let n=Object.keys(r);if(n.length===0)return[];let o=e.nodes.map(i=>i.objectApiName),s=new Map;for(let i of n){let a=o.find(d=>d.toLowerCase()===i.toLowerCase())??i;if(!s.has(a))try{s.set(a,await t(a))}catch(d){s.set(a,Qn(d)?void 0:null)}}return Do(r,o,i=>s.has(i)?s.get(i):null).unmatched}function ib(r){let e=Zt()?"":" (--max-orphans raises it)";return`parents from outside the run not copied: ${r.notCopied} past the ${r.cap} --expand-orphans copies at most${e}, of ${r.objects.join(", ")}; the rows that cannot be written without one were refused`}function ug(r,e=!1,t,n=!1){let o=[`success: ${r.successCount}`,...r.wouldInsertCount>0?[`would be inserted: ${r.wouldInsertCount} (dry run, nothing written)`]:[],...r.updatedCount>0?[`updated: ${r.updatedCount} (matched by their external id, not created)`]:[],rb(r),`failed: ${r.failedCount}`+(r.failedReads.length>0?` (read failed: ${r.failedReads.join(", ")})`:""),`skipped: ${r.skippedCount}`,`remaps: ${r.remapCount}`,...r.apiCalls!==void 0?[`calls: ${r.apiCalls} (requests the run sent to both orgs)`]:[]];if(r.existingRecords.length>0){o.push("",`already in the target (${r.existingRecords.length} object(s)):`);for(let h of r.existingRecords){let g=h.linkedToCreated??0,m=[...h.linked-g>0||g===0?[`${h.linked-g} linked`]:[],...g>0?[`${g} linked to records the run created (refused as copies of those)`]:[]];h.unidentified>0&&m.push(`${h.unidentified} not identified \u2014 their children lost the link`),o.push(` ${h.objectApiName} ${m.join(", ")}`)}}if(r.cappedObjects){let{perObject:h,objects:g}=r.cappedObjects;o.push("",`stopped at ${h} records per object (${yn("--max","maxRecordsPerObject")}), the source holding more, which were not cloned (${g.length} object(s)):`,...g.map(m=>` ${m}`))}let s=xg(r,t);if(s){let h=s.perObject!==void 0?`${s.perObject} `:"",g=Zt()?"":" (--max-records-per-object)";o.push("",`TRUNCATED at ${h}records per object${g}, the source holding more, which were not cloned (${s.objects.length} object(s)):`,...s.objects.map(m=>` ${m}`))}let i=r.fieldExclusionsUnmatched??[];i.length>0&&o.push("",...ob(i)),r.orphanParentsCapped&&o.push("",ib(r.orphanParentsCapped)),r.files&&o.push("",...nb(r.files,e));let a=r.fileContentFieldsLeftOut??[];if(a.length>0){o.push("",`left empty, as they hold a file's content (${a.length} object(s)):`);for(let{objectApiName:h,fields:g}of a)o.push(` ${h} ${g.join(", ")}`)}let d=r.encryptedFieldsLeftOut??[];if(d.length>0){o.push("",`left out, encrypted and read masked: the user the source is read as lacks View Encrypted Data, and the masks are not copied (${d.length} object(s)):`);for(let{objectApiName:h,fields:g}of d)o.push(` ${h} ${g.join(", ")}`)}let c=r.picklistValuesChanged??[];if(c.length>0){let h=new Set(c.map(g=>g.objectApiName)).size;o.push("",`picklist values not written as read (${h} object(s)):`);for(let g of c)o.push(` ${g.objectApiName} ${Ll(g)}`)}let l=r.currenciesReplaced??[];if(l.length>0){let h=new Set(l.map(g=>g.objectApiName)).size;o.push("",`written in another currency (${h} object(s)):`);for(let g of l)o.push(` ${g.objectApiName} ${Qc(g)}`)}let u=tb(r.recordTypesGiven??[],e);u.length>0&&(o.push("",...u),e&&n&&o.push(" the permission sets a real run assigns to mute the automation may open other record types to the user it writes as: it reads them again once assigned, and its summary says what the target gave"));let p=r.writtenWithoutFields??[];if(p.length>0){o.push("",`written again without a field the target refused (${p.length} object(s)):`);for(let{objectApiName:h,fields:g}of p)for(let{field:m,refusedBy:w="validation-rule",reason:b,rows:S}of g)o.push(` ${h}.${m} ${S} record(s) \u2014 ${ly[w]} \u2014 ${b}`)}r.contactPoints&&o.push("",...ub(r.contactPoints,e));let f=r.mayHaveBeenWritten??[];if(f.length>0){o.push("",`may be in the target, under ids the run never learned (${yn("--remove","destroy")} cannot reach them):`);for(let{objectApiName:h,sourceIds:g}of f)o.push(` ${h} ${g.length} record(s)`)}if(r.decisionsApplied&&r.decisionsApplied.length>0&&o.push("",...lb(r.decisionsApplied)),r.gaps&&o.push("",...db(r.gaps)),r.errors.length>0){o.push("",`errors (${r.errors.length} object(s)):`);for(let h of r.errors){o.push(` [${h.stage}] ${h.objectApiName} ${h.failedCount}/${h.attemptedCount}`);for(let g of h.samples){o.push(` ${g.recordSummary}`);for(let m of g.messages)o.push(` \u2514 ${m}`)}}}return o}function ab(r){let e=r.detail??{},t=[];typeof e.longest=="number"&&typeof e.length=="number"&&t.push(`longest ${e.longest} of ${e.length} characters`),typeof e.precision=="number"&&t.push(`precision ${e.precision}, scale ${String(e.scale??0)}`),typeof e.replacement=="string"&&t.push(`written as "${e.replacement}"`);let n=e.amountsConverted;Array.isArray(n)&&n.length>0&&t.push(`amounts converted into it: ${n.join(", ")}`),e.amountsAsRead===!0&&t.push("amounts written as read, no rate converts them"),typeof e.colliding=="number"&&t.push(`${e.colliding} value(s) already in the target`),e.linkedToTheRecordItNames===!0&&t.push("a real run links each row to the record the target holds");let o=e.mapTo;return Array.isArray(o)&&o.length>0&&t.push(`may map to ${o.join(", ")}`),e.ignored===!0&&t.push("ignored"),t.length>0?` (${t.join("; ")})`:""}function db(r){return r.length===0?["gaps: none found (dry run: nothing the target would refuse or change)"]:[`gaps the target holds against the rows (${r.length}, dry run):`,...r.map(e=>{let t=e.field?`${e.objectApiName}.${e.field}`:e.objectApiName,n=e.value!==void 0?` "${e.value}"`:"",o=e.recordType!==void 0?` (record type ${e.recordType})`:"";return` [${e.severity}] ${t} ${e.kind}${n}${o}: ${e.rows} record(s)${ab(e)}`})]}function cb(r){if(!r.choicesFrom)return[];let e=[Zt()?"choices from the resource in the file:":`choices from ${r.choicesFrom.flag} ${r.choicesFrom.path}, the flags over it:`],t=Object.entries(r.fieldExclusions).flatMap(([a,d])=>d.map(c=>`${a}.${c}`));t.length>0&&e.push(` fields left out: ${t.join(", ")}`),r.excludedObjects.length>0&&e.push(` objects left out: ${r.excludedObjects.join(", ")}`);for(let[a,d]of Object.entries(r.objectSoqlFilters))e.push(` filter ${a}: ${d}`);let n=Object.keys(r.ownerMappings).length;n>0&&e.push(` owners mapped: ${n}`);for(let[a,d]of Object.entries(r.fieldMappings))for(let[c,l]of Object.entries(d))e.push(` renamed: ${a}.${c} \u2192 ${l}`);let o=r.decisions,s=a=>a!==void 0?` (record type ${a})`:"",i=[...(o?.picklistValueMappings??[]).map(a=>` ${a.object}.${a.field} ${a.to===null?"leave_empty":"map_value"} "${a.from}"${a.to!==null?` \u2192 "${a.to}"`:""}${s(a.recordType)}`),...(o?.recordTypeMappings??[]).map(a=>` ${a.object} map_record_type "${a.from}" \u2192 ${a.to===null?"the default":`"${a.to}"`}`),...(o?.defaultValues??[]).map(a=>` ${a.object}.${a.field} set_default "${String(a.value)}"`),...(o?.truncateFields??[]).map(a=>` ${a.object}.${a.field} truncate`),...(o?.skippedRows??[]).map(a=>{let d=nc(a.gapId),c=Wl(a);return` ${a.object}.${d?.field??"?"} skip_rows "${d?.value??""}"${s(d?.recordType)}`+(c!==void 0?`: ignored, ${c}`:"")}),...(o?.ignoredGaps??[]).map(a=>` ignore ${a}`)];return i.length>0&&e.push(` decisions (${i.length}):`,...i),e}function lb(r){return[`decisions applied (${r.length}):`,...r.map(e=>{let t=e.field?`${e.objectApiName}.${e.field}`:e.objectApiName,n=e.from!==void 0?` "${e.from}"`:"",o=e.to!==void 0?` \u2192 "${e.to}"`:"",s=e.recordType!==void 0?` (record type ${e.recordType})`:"";return` ${t} ${e.kind}${n}${o}${s}: ${e.rows} record(s)`})]}function ub(r,e){if(!r.neutralized)return[`contact points: written as read (${yn("--keep-contact-points","keepContactPoints")}): the target's flows and email alerts may reach the people the records name`];let t=e?"would be neutralized (dry run, nothing written)":"neutralized";return[`contact points: ${r.values} value(s) in ${r.fields.length} field(s) ${t} \u2014 emails under .invalid, phone numbers in a fictional range`,...r.fields.map(({objectApiName:n,field:o,values:s})=>` ${n}.${o} ${s}`),...r.numbersExhausted?[` ${r.numbersExhausted} phone number(s) left out, their field empty: the 10 000 fictional numbers were all given to other numbers of the run`]:[]]}function pb(r){return r.flatMap(({objectApiName:e,fields:t})=>t.flatMap(n=>{if(n.externalId!==!0||n.createable===!1)return[];let o=xo(n.name,String(n.type).toLowerCase());return o?[{objectApiName:e,field:n.name,kind:o}]:[]}))}function fb(r,e){return r.length===0?[]:[`upsert keys: --upsert matches the records of ${e} by these external ids, which the run writes neutralized (emails under .invalid, phone numbers in a fictional range): a record of ${e} holding the real address or number is not matched, and the run creates another beside it; one an earlier run wrote neutralized is. --keep-contact-points matches the real ones`,...r.map(({objectApiName:t,field:n,kind:o})=>` ${t}.${n} (${o})`)]}function hb(r,e,t,n){if(!r)return{};let o=gc(rc(e.gaps,t??[]).filter(s=>!Zr(s,n)));return o.length>0?{adminChanges:o}:{}}function gb(r,e){let t=xg(r,e);return{successCount:r.successCount,updatedCount:r.updatedCount,linkedCount:r.linkedCount,...r.linkedToCreatedCount?{linkedToCreatedCount:r.linkedToCreatedCount}:{},...r.writtenByThePlatform?{writtenByThePlatform:r.writtenByThePlatform}:{},wouldInsertCount:r.wouldInsertCount,failedCount:r.failedCount,skippedCount:r.skippedCount,remapCount:r.remapCount,existingRecords:r.existingRecords,errors:r.errors.map(n=>({objectApiName:n.objectApiName,stage:n.stage,failedCount:n.failedCount,attemptedCount:n.attemptedCount,samples:n.samples,...n.referenceData===!0?{referenceData:!0}:{},...n.skipped===!0?{skipped:!0}:{}})),remapTable:r.remapTable,existingSourceIds:r.existingSourceIds,updatedSourceIds:r.updatedSourceIds,createdByObject:r.createdByObject,...r.withTheirRecordSourceIds?{withTheirRecordSourceIds:r.withTheirRecordSourceIds}:{},...r.writtenBetween?{writtenBetween:r.writtenBetween}:{},readByObject:r.readByObject,failedReads:r.failedReads,...r.cappedObjects?{cappedObjects:r.cappedObjects}:{},...t?{truncatedObjects:t}:{},...r.fieldExclusionsUnmatched?{fieldExclusionsUnmatched:r.fieldExclusionsUnmatched}:{},...r.orphanParentsCapped?{orphanParentsCapped:r.orphanParentsCapped}:{},...r.files?{files:r.files}:{},...r.fileContentFieldsLeftOut?{fileContentFieldsLeftOut:r.fileContentFieldsLeftOut}:{},...r.encryptedFieldsLeftOut?{encryptedFieldsLeftOut:r.encryptedFieldsLeftOut}:{},...r.picklistValuesChanged?{picklistValuesChanged:r.picklistValuesChanged}:{},...r.currenciesReplaced?{currenciesReplaced:r.currenciesReplaced}:{},...r.recordTypesGiven?{recordTypesGiven:r.recordTypesGiven}:{},...r.writtenWithoutFields?{writtenWithoutFields:r.writtenWithoutFields}:{},...r.lookupsLeftEmptyByFilter?{lookupsLeftEmptyByFilter:r.lookupsLeftEmptyByFilter}:{},...r.contactPoints?{contactPoints:r.contactPoints}:{},...r.apiCalls!==void 0?{apiCalls:r.apiCalls}:{},...r.gaps?{gaps:r.gaps}:{},...r.decisionsApplied?{decisionsApplied:r.decisionsApplied}:{},...r.mayHaveBeenWritten?{mayHaveBeenWritten:r.mayHaveBeenWritten}:{},...r.remapInJournal?{remapInJournal:!0}:{},...r.remapInJournal?{createdCountByObject:r.remapByObject.filter(({created:n})=>n>0).map(({objectApiName:n,created:o})=>({objectApiName:n,created:o}))}:{},...r.sample?{sample:Nb(r.sample)}:{}}}function mb(r){if(r.status==="running"&&r.message.startsWith("[dry-run] "))return` ${r.message}`;if(r.status==="scanning")return r.progress>0&&r.message?` ${r.message}`:void 0;if(!(r.status!=="done"&&r.status!=="error"&&r.status!=="skipped"&&r.status!=="stopped"))return r.message?` ${r.message}`:void 0}function wb(r){let e=new Set(r.nodes.filter(mr).map(n=>n.objectApiName)),t=!1;return n=>{if(n.status==="skipped"&&e.size>1&&e.has(n.objectName)){if(t)return;t=!0;let o=ht("--list-objects")?"; --list-objects names them":"";return` Skipped ${e.size} objects (excluded: empty tables${o})`}return mb(n)}}function yb(r,e,t){let n=new Set(r.nodes.map(f=>f.objectApiName)),o=r.nodes.filter(f=>f.included).length,s=r.edges.filter(f=>n.has(f.sourceObject)&&n.has(f.targetObject)).length,i=r.nodes.length-r.nodes.filter(Ku).length,a=i>0?` (${i} empty, taking no place under it)`:"",d=r.nodes.length-i>t?" (raised for the parents their records cannot be written without)":"",{refused:c,unanswered:l}=Ng(r),u=c.length>0?`, ${c.length} not counted (${an(c)})`:"",p=l.length>0?`, ${l.length} of them kept though their count got no answer (${an(l)})`:"";return`graph: ${r.nodes.length} objects at a cap of ${t}${a}${d}, ${o} included${p}${u}; ${r.edges.length} lookups, ${s} between these objects; ${e.waves.length} waves, ${e.cycleResolutions.length} cycles`+(r.truncated?" (TRUNCATED)":"")}var Cg={missingInTarget:"missing in the target",notQueryable:"not queryable",empty:"empty",unreadable:"unreadable",notWritable:"not writable in the target",createOnly:"creatable but not editable or deletable in the target",setup:"setup",platformCreated:"written by the platform alone",metadata:"metadata",chatter:"Chatter",history:"history",sharing:"sharing",changeEvent:"change events",unsupportedKind:"of a kind no clone writes",customSetting:"custom settings",files:"files, copied with --files",excludedByUser:"left out by --exclude-object",notDescribed:"not described"};function bb(r,e,t){let n=r.nodes.filter(a=>a.included).length,{objects:o,counts:s}=Jo(r),i=s.map(({reason:a,count:d})=>`${d} ${Cg[a]}`).join(", ");return`graph: the whole of ${t}, ${n} object(s) to copy, ${o.length} left out${i?` (${i})`:""}; ${r.edges.length} lookups; ${e.waves.length} waves, ${e.cycleResolutions.length} cycles`}var Rb={listing:()=>"discovery: listing the objects of both orgs\u2026",counting:r=>`discovery: counting the records of ${r??"each"} object(s)\u2026`,describing:r=>`discovery: describing the ${r??""} object(s) that hold records\u2026`};async function Ob(r,e,t){let n;try{return await r.discover(e,{onProgress:o=>{if(o.phase===n)return;n=o.phase;let s=Rb[o.phase];s&&t(s(o.total))}})}catch(o){process.stderr.write(`The whole org could not be discovered: ${Y(o)}
|
|
746
|
-
`),process.exit(1)}}function jd(r,e,t){let{estimate:n,remaining:o,max:s}=e;return o===void 0||s===void 0?` ${r} of ${t}: about ${n}; what it has left today could not be read`+(e.unread?` (${e.unread})`:""):` ${r} of ${t}: about ${n}, of the ${o} it has left of its ${s} a day`+(e.near?": it would leave less than a tenth of them":"")}var pg=10;function an(r){let e=r.length-pg;return e>0?`${r.slice(0,pg).join(", ")} and ${e} more`:r.join(", ")}function kb(r,e,t,n=[]){let{source:o,bulk:s}=r,i=n.filter(({jobs:m})=>m>0),a=i.length>0?` (${an(i.map(m=>`${m.objectApiName}: ${m.jobs} of ${m.jobRows}`))}; rows of a job carrying the same values go by REST instead)`:"",d=[` writes: ${s?.jobs??0} Bulk API job(s) of ${s?.jobRows??0} record(s) at most${a}, ${s?.restRows??0} record(s) by REST, ${r.restObjects.length} object(s) by REST alone; about ${Math.max(1,Math.round(r.durationSeconds/60))} minute(s) one after another`,jd("API requests",r.targetApi,t),...s?.batches?[jd("Bulk API batches",s.batches,t)]:[],jd("API requests",r.sourceApi,o),...r.discovery?[` of them, sent already by discovery: ${r.discovery.target} of ${t}'s and ${r.discovery.source} of ${o}'s`]:[]],c=r.fileStorage;c&&d.push(` files: ${c.files} file(s), about ${Xt(c.estimateMB)} MB of file storage, of the ${c.remainingMB} MB ${t} has left of ${c.maxMB} MB`+(c.overCeiling>0?`; ${c.overCeiling} past the largest file copied, left out`:""));let l=e.map(({reason:m,count:w})=>`${w} ${Cg[m]}`).join(", ");d.push(` left out of ${o}: ${r.leftOut} object(s)${l?`: ${l}`:""}`);let{carried:u}=r,p=u?[["read through a filter",u.filters],["left out by name",u.excluded],["with rows held back by a decision",u.heldBack],["copied without some of their fields",u.fieldsLeftOut]]:[];for(let[m,w]of p)w.length>0&&d.push(` ${m}: ${an(w)}`);let f=r.personalAsIs??[],h=f.reduce((m,{fields:w})=>m+w.length,0);d.push(h>0?` personal data: ${h} field(s) of ${f.length} object(s) copied as ${o} holds them: `+an(f.map(({objectApiName:m,fields:w})=>`${m} (${w.join(", ")})`)):" personal data: no personal field copied as it is");let g=r.managedPackages??[];return g.length>0&&d.push(` managed packages: ${g.length} object(s) written, whose triggers and flows no mute reaches: ${an(g)}`),r.contactPointsBlanked!==void 0&&d.push(` phone numbers: up to ${r.contactPointsBlanked} past the fictional range go in empty`),d}function Sb(r,e,t){return`discovery: ${r.source} API request(s) sent to ${e} and ${r.target} to ${t}, before any row is read`}function _r(r,e,t){let n=(o,s)=>{if(!o)return{sent:s};let{parts:i,...a}=o;return{...a,...i?{parts:i}:{},sent:s}};return{target:n(e.target,r.target),source:n(e.source,r.source),...t?{discovery:t}:{}}}function Tb(r,e,t,n){let{source:o,bulk:s}=r,i=e.objects.filter(({rows:f})=>f>0).length,a=r.managedPackages??[],d=r.personalAsIs??[],c=d.reduce((f,{fields:h})=>f+h.length,0),l=r.sample;return[(l&&n?`a sample of ${o}: ${e.totalRows} record(s) of ${i} object(s) (of ${l.sourceRows} in ${o}) into ${t}, about ${Xt(l.storageMB)} MB`+(zd(n.budget)?` of the ${Xt(l.budgetMB)} MB it may take`:"")+(l.automationMB!==void 0?`, ${Xt(l.automationMB)} MB of it for what the target's automation creates`:"")+`; ${Gd(l)}, ${Bs(l.share)} % of the roots; drawn at ${l.drawnAt} by ${l.drawnBy==="dryRun"?"a dry run":"this run"}; ${s?.jobs??0} Bulk API job(s) among them`:void 0)??`${e.totalRows} record(s) of ${i} object(s) of ${o} into ${t}, ${s?.jobs??0} Bulk API job(s) among them`,`about ${r.targetApi.estimate} of ${t}'s API requests`+(s?.batches?` and ${s.batches.estimate} of its Bulk API batches`:"")+` and ${r.sourceApi.estimate} of ${o}'s`,...a.length>0?[`${a.length} object(s) of managed packages, whose triggers and flows no mute reaches (${an(a)})`]:[],...r.contactPointsBlanked!==void 0?[`up to ${r.contactPointsBlanked} phone number(s) written empty`]:[],c>0?`${c} personal field(s) of ${d.length} object(s) copied as they are`:"no personal field copied as it is"].join("; ")}function fg(r,e=!1){let t=" \u2014 or leave objects out (--exclude-object), narrow them (--filter)"+(e?".":", or copy a sample of the org that fits the target (--fit share, its dry run first).");return r.replaceAll("turn the copy of files off on Review","leave out --files").replaceAll("leave the object out on Review","leave it out with --exclude-object").replaceAll("the sandforge.forge.maxRecordsPerObject setting lets a run hold at once: raise the setting","--max-records-per-object lets a run hold at once: raise it").replaceAll(" \u2014 or leave objects out.",t).replaceAll(" \u2014 or write fewer records.",t)}function Ab(r,e,t=!1){return`The clone of the whole org would write ${r} records, more than the ${e} --max-total holds it to: give --max-total the count its dry run says, `+(t?"":"copy a sample of the org that fits the target and --max-total (--fit share, its dry run first), ")+"or leave objects out (--exclude-object) or narrow them (--filter)."}function jb(r,e){if(r.verdict==="exceeds")return`The records to write take ${$u(r)}, and ${e} has ${r.remainingMB} MB left of ${r.maxMB} MB: copy a sample of the org that fits it (--fit share, its dry run first), leave objects out (--exclude-object) or narrow them (--filter), or free data storage in ${e}.`}var vb=2*1024;function Ib(r){let{storage:e,sample:t,target:n}=r,{withinMB:o}=t.options,s=t.options.maxTotal??Yn,i=Fu({storage:e,bounds:{...o!==void 0?{withinMB:o}:{},...t.maxTotalGiven?{maxTotal:s}:{}},target:n});if(i)throw St.of(i);let a=r.automation?{automation:r.automation}:{},d=Fa({storage:e,...o!==void 0?{withinMB:o}:{},...a});if(d)return{...d,budget:{...d.budget,maxTotal:s}};let c=Fa({storage:{maxMB:0,remainingMB:0},...a});return{budget:{bytes:Number.MAX_SAFE_INTEGER,maxTotal:s,limitedBy:"maxTotal"},bytesLimit:"within",roomBytes:s*vb,...c?.automationBytes?{automationBytes:c.automationBytes}:{}}}function zd(r){return r.remainingMB!==void 0||r.withinMB!==void 0}function Bs(r){return String(Number((r*100).toPrecision(2)))}function Gd(r){return r.draw==="recent"?"the newest by creation date":`seed ${r.seed}, spread over the org`}function Eb(r,e,t){let{budget:n}=r;switch(n.limitedBy){case"heavyRoots":return`every root fits but ${r.heavyRoots.length} heavy root(s) set aside below, each past a tenth of the room ${t} has: they alone keep the sample from every root`;case"storage":return`limited by the data storage ${t} has left`;case"within":return`limited by --fit-within ${n.withinMB??""}`.trimEnd();case"maxTotal":return`limited by --max-total ${n.maxTotal??Yn}`;case"targetRequests":return`limited by the daily API requests ${t} has left`;case"bulkBatches":return`limited by the daily Bulk API batches ${t} has left`;case"sourceRequests":return`limited by the daily API requests ${e} has left`;case"whole":return"every record of the org fits: leave out --fit share to copy the whole org"}}function $b(r){let e=`${r.details} records (${r.details}.${r.field})`;return r.asParents!==void 0?`the ${r.asParents} brought in as parents keep only the ${e} drawn on their own: if they total them (an amount, a roll-up summary), the total counts only those`:`keeps ${r.kept??0} of its ${r.sourceRows??0} ${e} in the sample: if it totals them (an amount, a roll-up summary), the total counts only those`}function xb(r,e){let{budget:t}=r,n=`about ${Xt(r.storageBytes/1048576)} MB`;if(!zd(t))return`${n}, held to ${t.maxTotal??Yn} records (--max-total): ${e} would not say its data storage`;let o=`${n} of the ${Xt(t.bytes/1048576)} MB the sample may take`;if(t.remainingMB===void 0)return`${o} (--fit-within ${t.withinMB}; ${e} would not say its data storage)`;let s=[`${Bs(t.share??0)} % of the ${t.remainingMB} MB ${e} has left`+(t.maxMB!==void 0?` of ${t.maxMB} MB`:""),...t.roundingMB!==void 0?[`${t.roundingMB} MB off for rounding`]:[],...t.automationMB!==void 0&&t.automationMB>0?[`${Xt(t.automationMB)} MB for what its automation creates`]:[],...t.withinMB!==void 0?[`--fit-within ${t.withinMB}`]:[]];return`${o} (${s.join(", ")})`}var Fg={referenceData:"reference data, matched by name",catalog:"the price catalog",smallParent:"a small parent",asked:"--fit-whole"};function Pb(r,e,t){switch(r){case"noParentInSource":return`a lookup they may not leave empty names a record ${e} does not hold`;case"outsideFilter":return"a lookup they may not leave empty names a record outside its object's filter";case"excludedObject":return"a lookup they may not leave empty names a record of an object left out";case"withoutParent":return"a record they cannot be written without is left out itself";case"heldBack":return"their record type is closed to the user the run writes as";case"recordTypeNotInTarget":return`their record type is one ${t} has none of`}}function Cb(r,e){if(r.whole){let t=e.find(n=>n.objectApiName===r.objectApiName)?.why;return`copied whole${t?` (${Fg[t]})`:""}`}return`${r.roots} drawn, ${r.below} under a parent, ${r.asParents} as parents`}function Fb(r,e){let{source:t,target:n}=e,o=r.objects.reduce((d,c)=>d+c.sourceRows,0)+r.noRecordDrawn.reduce((d,c)=>d+c.sourceRows,0),s=[`sample: ${r.rows} of ${o} record(s) of ${t}, of ${r.objects.length} object(s): ${Bs(r.share)} % of the roots of each object (${Gd(r)}), with the records they reach and name; ${xb(r,n)}; ${Eb(r,t,n)}`];for(let d of r.objects){let c=(d.childrenCut??[]).map(({field:u,rows:p})=>`${u} ${p}`),l=(r.partialMasters??[]).filter(u=>u.objectApiName===d.objectApiName);s.push(` ${d.objectApiName}: ${d.kept} of ${d.sourceRows} (${Cb(d,r.whole)})`+(c.length>0?`; left by the cap of ${r.children} children a record, by the lookup naming their parent: ${c.join(", ")}`:"")+l.map(u=>`; ${$b(u)}`).join(""))}if(r.whole.length>0&&s.push(`whole: ${r.whole.map(({objectApiName:d,why:c})=>`${d} (${Fg[c]})`).join(", ")}`),r.newestByIds&&r.newestByIds.length>0&&s.push(`newest by the order of their ids, the org sorting none of their creation dates \u2014 ids follow it within a load only: ${r.newestByIds.join(", ")}`),r.heavyRoots.length>0){s.push(`heavy roots set aside, each bringing in more than a tenth of the room ${n} has:`);for(let{objectApiName:d,id:c,rows:l,relation:u}of r.heavyRoots)s.push(` ${d} ${c}: ${l} record(s) through ${u.objectApiName}.${u.field}`)}if(r.dropped.length>0){s.push("not in the sample, never sent:");for(let{objectApiName:d,rows:c,reason:l}of r.dropped)s.push(` ${d}: ${c}, ${Pb(l,t,n)}`)}if(r.leftEmpty.length>0){s.push("left empty, their record outside the sample:");for(let{objectApiName:d,field:c,rows:l}of r.leftEmpty)s.push(` ${d}.${c}: ${l} record(s)`)}if(r.noRecordDrawn.length>0){s.push(`no record drawn, ${t} holding some:`);for(let{objectApiName:d,sourceRows:c}of r.noRecordDrawn)s.push(` ${d}: ${c} in ${t}`)}let{plan:i}=r,a=i.drawnBy==="run"?"by this run":e.dryRun?e.replayed===!0?"by a dry run, said again by this one (--fit-plan)":"by this dry run":"by a dry run, written by this run (--fit-plan)";return s.push(`sample plan: ${i.path} (sha256 ${i.sha256}, drawn ${i.drawnAt} ${a})`,` drawing it sent ${r.planRequests.source} request(s) to ${t}`+(e.dryRun&&i.drawnBy==="dryRun"?`; --fit-plan ${i.path} writes these records, within a day`:"")),s}function hg(r){let{budget:e,plan:t}=r;return{seed:r.seed,draw:r.draw,share:r.share,floor:r.floor,parents:r.parents,children:r.children,budget:{bytes:zd(e)?e.bytes:null,...e.remainingMB!==void 0?{remainingMB:e.remainingMB}:{},...e.maxMB!==void 0?{maxMB:e.maxMB}:{},...e.share!==void 0?{share:e.share}:{},...e.roundingMB!==void 0?{roundingMB:e.roundingMB}:{},...e.automationMB!==void 0?{automationMB:e.automationMB}:{},...e.withinMB!==void 0?{withinMB:e.withinMB}:{},...e.maxTotal!==void 0?{maxTotal:e.maxTotal}:{},limitedBy:e.limitedBy},rows:r.rows,storageBytes:r.storageBytes,objects:r.objects.map(n=>({objectApiName:n.objectApiName,sourceRows:n.sourceRows,kept:n.kept,roots:n.roots,below:n.below,asParents:n.asParents,...n.whole?{whole:!0}:{},...n.childrenCut&&n.childrenCut.length>0?{childrenCut:n.childrenCut.map(({field:o,rows:s})=>({field:o,rows:s}))}:{}})),whole:r.whole.map(({objectApiName:n,why:o})=>({objectApiName:n,why:o})),heavyRoots:r.heavyRoots.map(({objectApiName:n,id:o,rows:s,relation:i})=>({objectApiName:n,id:o,rows:s,relation:{objectApiName:i.objectApiName,field:i.field}})),dropped:r.dropped.map(({objectApiName:n,rows:o,reason:s})=>({objectApiName:n,rows:o,reason:s})),leftEmpty:r.leftEmpty.map(({objectApiName:n,field:o,rows:s})=>({objectApiName:n,field:o,rows:s})),noRecordDrawn:r.noRecordDrawn.map(({objectApiName:n,sourceRows:o})=>({objectApiName:n,sourceRows:o})),partialMasters:(r.partialMasters??[]).map(n=>({...n})),...r.newestByIds&&r.newestByIds.length>0?{newestByIds:[...r.newestByIds]}:{},planRequests:{source:r.planRequests.source},plan:{path:t.path,sha256:t.sha256,drawnAt:t.drawnAt,drawnBy:t.drawnBy,...t.drawnAgain?{drawnAgain:t.drawnAgain}:{}}}}function Nb(r){return{seed:r.seed,draw:r.draw,share:r.share,sha256:r.sha256,drawnAt:r.drawnAt,objects:r.objects.map(e=>({objectApiName:e.objectApiName,sourceRows:e.sourceRows,kept:e.kept,roots:e.roots,below:e.below,asParents:e.asParents,...e.whole?{whole:!0}:{},written:e.written,goneSinceTheSample:e.goneSinceTheSample,changedSinceTheSample:e.changedSinceTheSample})),...r.leftEmpty&&r.leftEmpty.length>0?{leftEmpty:r.leftEmpty.map(({objectApiName:e,field:t,rows:n})=>({objectApiName:e,field:t,rows:n}))}:{}}}function Mb(r,e){let t=[`sample (${Gd(r)}, ${Bs(r.share)} % of the roots of each object; plan sha256 ${r.sha256}, drawn ${r.drawnAt}):`];for(let n of r.objects){let o=n.whole?"copied whole":`${n.roots} drawn, ${n.below} under a parent, ${n.asParents} as parents`;t.push(` ${n.objectApiName}: ${n.written} written of ${n.kept} in the sample (${o}) of ${n.sourceRows} in ${e}`+(n.goneSinceTheSample>0?`; ${n.goneSinceTheSample} gone from ${e} since the sample, not written`:"")+(n.changedSinceTheSample>0?`; ${n.changedSinceTheSample} changed since the sample: a record they cannot be written without is no longer the one the plan named, held back (failed)`:""))}for(let{objectApiName:n,field:o,rows:s}of r.leftEmpty??[])t.push(` left empty, their record outside the sample: ${n}.${o} ${s}`);return t}function Bb(r,e,t){let n=e.draw??un.draw,o=e.maxTotal??Yn,s=0;for(let i of r.nodes){if(!i.included||i.recordCount<=0)continue;let a=n==="uniform"?i.recordCount:Math.min(i.recordCount,o),d=Math.ceil(a/Lb);s+=1+d+(n==="uniform"?0:Math.max(0,d-1))}return`sample: drawing it reads at most about ${s} request(s) of ${t} for the roots, by discovery's counts (${n==="uniform"?"every root's id, spread over the org":"the newest by creation date, those it may keep"}); the records they reach and name are read on top, and said once drawn`}var Lb=2e3,Wb={counting:"counting the roots of each object",drawing:"reading the ids of the roots",closing:"closing the sample over the records they reach and name",fitting:"cutting it to what the target may take",saving:"keeping its plan"};function Db(r){let e;return t=>{t.step!==e&&(e=t.step,r(`sampling: ${Wb[t.step]}\u2026 (${t.requests} request(s) so far)`))}}function gg(r){return r===Cu||r===Yo?2:1}function _b(r){let e=0,t=0,n=0,o=0;for(let s of r.nodes)s.included?e++:mr(s)?t++:s.status==="error"||s.errors.length>0?n++:o++;return{included:e,emptyTables:t,notCounted:n,leftOut:o}}function Ng(r){let e=[],t=[];for(let n of r.nodes)n.included&&n.recordCountUnknown===!0?t.push(n.objectApiName):!n.included&&!mr(n)&&(n.status==="error"||n.errors.length>0)&&e.push(n.objectApiName);return{refused:e,unanswered:t}}function As(r,e){let{refused:t,unanswered:n}=Ng(r);return{nodes:r.nodes.length,..._b(r),...t.length>0?{notCountedObjects:t}:{},...n.length>0?{uncountedObjects:n}:{},edges:r.edges.length,waves:e.waves.length,cycles:e.cycleResolutions.length,truncated:r.truncated??!1}}function Ub(r){return[...r.nodes].sort((e,t)=>e.objectApiName.localeCompare(t.objectApiName)).map(e=>({objectApiName:e.objectApiName,recordCount:e.recordCount,depth:e.level,included:e.included}))}function mg(r,e,t,n){return{rootRecordId:r.record,rootObjectApiName:e.nodes[0]?.objectApiName??"",dryRun:r.dryRun,recordTypeMappings:t,maxRecordsPerObject:r.maxRecordsPerObject,referenceFallback:"nullify",upsertMode:r.upsert?"auto":void 0,expandOrphanParents:r.expandOrphans,...r.maxOrphans!==void 0?{maxOrphanParentExpansions:r.maxOrphans}:{},fieldExclusions:Object.keys(r.fieldExclusions).length>0?r.fieldExclusions:void 0,excludedObjects:r.excludedObjects.length>0?r.excludedObjects:void 0,ownerMappings:Object.keys(r.ownerMappings).length>0?r.ownerMappings:void 0,objectSoqlFilters:Object.keys(r.objectSoqlFilters).length>0?r.objectSoqlFilters:void 0,fieldMappings:Object.keys(r.fieldMappings).length>0?r.fieldMappings:void 0,anonymization:ls(r.anonymize,e,r.anonymizationRules,n),keepContactPoints:r.keepContactPoints,decisions:r.decisions,files:r.files?{maxFileBytes:r.files.maxFileSizeMB*1048576,acceptedAsIs:r.files.acceptedAsIs}:void 0,stream:{ceiling:r.readCeiling,...r.pageSize!==void 0?{pageSize:r.pageSize}:{}}}}function zb(r,e){return e?{...r,stream:{...r.stream,store:e,summaryBound:Zp}}:r}function Gb(r,e){if(!e)return r;let t=new Map(e.map(n=>[n.objectApiName,n.fieldNames]));return{...r,nodes:r.nodes.map(n=>{let o=t.get(n.objectApiName);if(!o)return n;let s=new Set(n.piiFields);return{...n,anonymizeFields:o.filter(i=>s.has(i))}})}}function Ls(r){return new gu({query:async(e,t)=>Fn({query:async n=>r.query(n),queryMore:async n=>r.queryMore(n)},t),toolingQuery:async(e,t)=>Fn({query:async n=>r.tooling.query(n),queryMore:async n=>r.tooling.queryMore(n)},t),toolingQueries:async(e,t)=>hu(await r.request({method:"POST",url:"/tooling/composite",body:JSON.stringify(fu(`/services/data/v${r.version}`,t)),headers:{"Content-Type":"application/json"}}),t.length),toolingRetrieves:(e,t)=>Ki(r)(t)})}function qb(r,e,t){let n=o=>{let s=r.get(o);if(!s)throw new Error(`No connection for ${o}`);return s};return new uu({query:async(o,s)=>Fn({query:async i=>n(o).query(i),queryMore:async i=>n(o).queryMore(i)},s),toolingQuery:async(o,s)=>Fn({query:async i=>n(o).tooling.query(i),queryMore:async i=>n(o).tooling.queryMore(i)},s),describeFields:async(o,s)=>{let i=!t.has(`${o}::${s}`),a=await e(o,s);return{sent:i,createable:a.createable!==!1,fields:a.fields.map(qi)}},readDuplicateRules:async(o,s)=>{let i=await n(o).metadata.read("DuplicateRule",s);return Array.isArray(i)?i:[i]},readLimits:async o=>n(o).request({method:"GET",url:"/limits"}),toolingQueries:async(o,s)=>lu(n(o))(s),toolingRetrieves:(o,s)=>Ki(n(o))(s)})}async function on(r){let t=(await r.query("SELECT Id, IsSandbox FROM Organization LIMIT 1")).records[0];if(typeof t?.Id!="string")throw new Error("The org gave no Organization record: whether it is a sandbox cannot be told.");if(t.IsSandbox===!0)return{id:t.Id,sandbox:!0};try{let o=(await r.query("SELECT OrganizationType FROM Organization LIMIT 1")).records[0]?.OrganizationType;return typeof o=="string"&&o!==""?{id:t.Id,sandbox:!1,edition:o}:{id:t.Id,sandbox:!1}}catch{return{id:t.Id,sandbox:!1}}}function zr(r,e,t){if(e.sandbox||lc(e.edition))return;let n=t==="clone"?"sandforge clone writes to sandboxes and Developer Edition orgs only. Nothing was written; --dry-run, which only reads, runs against it.":"sandforge clone removes records from sandboxes and Developer Edition orgs only. Nothing was deleted.",o=e.edition?`IsSandbox false, edition ${e.edition}`:"IsSandbox false, and no edition";return`${r} is a production org (its Organization record says ${o}): ${n}`}var Hb={parent_refused:"a record it names was refused",beyond_a_call:"the records it needs are more, or deeper, than one call holds",call_budget:"the calls ran out before its turn"};function Kb(r,e){let t=r.updates.reduce((n,o)=>n+o.updates,0);return[`rehearsal: ${r.sampled} of the ${r.rows} record(s) the run would create, created in ${e} and rolled back with each call`,...t>0?[` and ${t} update(s) the run makes after its inserts, each in the call that creates its record: ${r.updates.map(n=>`${n.objectApiName} ${n.updates}`).join(", ")}`]:[],` ${r.calls} composite call(s), ${r.maxCalls} at most if a call stops at a refused record`,...r.objects.map(({objectApiName:n,rows:o})=>` ${n.padEnd(40)} ${o}`)]}function Vb(r,e,t={}){let n=r.updatesJudged>0?`; ${r.updatesJudged} update(s) judged, ${r.updatesPassed} would save, ${r.updatesJudged-r.updatesPassed} refused`:"",o=r.linked??0,s=o>0?`${o} linked to a record the target holds, `:"",i=[`rehearsed in ${e}: ${r.judged} judged, ${r.passed} would save, ${s}${r.judged-r.passed-o} refused, ${r.notJudged} not judged${n} (${r.calls} call(s), every write rolled back)`];for(let a of r.gaps){let d=typeof a.detail?.statusCode=="string"?a.detail.statusCode:a.value,c=a.field?`.${a.field}`:"",l=a.kind==="picklist_value_refused"&&a.value?` "${a.value}"`:"",u=a.recordType?` (record type ${a.recordType})`:"",p=a.detail?.rowsOfTheRun,f=typeof p=="number"&&p>a.rows?`, ${p} in the run`:"";if(a.kind==="rehearsal_update_refusal"){i.push(` refused on update ${a.objectApiName}${c}: ${d}, ${a.rows} update(s)${f} (the record goes in without what the update gives it)`);continue}let h=Zr(a,t.lifted);if(h){i.push(` refused ${a.objectApiName}${c}: ${d}, ${a.rows} row(s)${f}, validation rule "${String(a.detail?.rule)}": the mute lifts it (${h.permission}, in ${h.permissionSet}), which the rehearsal ran without; a real run under it writes the row whole`);continue}i.push(` ${a.severity==="blocking"?"REFUSED":"refused"} ${a.objectApiName}${c}${l}${u}: ${d}, ${a.rows} row(s)${f}`+(a.detail?.writtenWithoutTheField===!0?" (a real run writes it again without the field)":"")+(a.detail?.linkedToTheRecordItNames===!0?" (a real run links it to the record the target holds)":""))}for(let{objectApiName:a,rows:d,reason:c}of r.notJudgedWhy)i.push(` not judged ${a}: ${d} row(s), ${Hb[c]}`);return r.updatesNotRehearsed>0&&i.push(` not rehearsed: ${r.updatesNotRehearsed} of the ${r.updates} update(s) the run makes after its inserts`),i}function Jb(r,e){return{...r,gaps:r.gaps.map(t=>{let n=Zr(t,e);return n?{...t,detail:{...t.detail,liftedByPermission:n.permission,liftedByPermissionSet:n.permissionSet}}:t})}}var Yb=new Set(["--remove","--target","--preview","--include-changed","--json","--accept-automation","--leave-undeletable","--sweep","--sweep-list","--sweep-late","--sweep-untied","--audit","--mute-automation","--sweep-user"]),Qb=new Set(["--remove","--target","--audit","--sweep-user"]);function Xb(r){let e=r.slice(2);(e.includes("-h")||e.includes("--help"))&&(process.stdout.write(Wd),process.exit(0));let t=c=>{let l=e.indexOf(c),u=l>=0?e[l+1]:void 0;return u!==void 0&&!u.startsWith("--")?u:void 0},n=c=>e.includes(c);for(let c=0;c<e.length;c++){let l=e[c];if(Qb.has(l)){e[c+1]!==void 0&&!e[c+1].startsWith("--")&&c++;continue}l==="--dry-run"&&(process.stderr.write(`--remove does not take --dry-run: a removal that did not read it would delete for real. --preview says what the removal would do, and writes nothing. Run with --help for usage.
|
|
747
|
-
`),process.exit(2)),Yb.has(l)||(process.stderr.write(`--remove takes --target, --preview, --include-changed, --accept-automation, --mute-automation, --leave-undeletable, --sweep, --sweep-late, --sweep-untied, --sweep-list, --sweep-user, --json and --audit, not "${l}". Run with --help for usage.
|
|
748
|
-
`),process.exit(2))}let o=t("--remove"),s=t("--target");(!o||!s)&&(process.stderr.write(`--remove takes the file a run printed its --json summary to, and --target the org the run wrote to. Run with --help for usage.
|
|
749
|
-
`),process.exit(2)),n("--sweep")&&n("--sweep-list")&&(process.stderr.write(`--sweep deletes and --sweep-list only lists: give one of them. Run with --help for usage.
|
|
750
|
-
`),process.exit(2));let i=["--sweep-list",...n("--sweep")?[]:Gg,"--audit"].filter(c=>n(c));n("--preview")&&i.length>0&&(process.stderr.write(`--preview writes nothing: give it without ${i.join(", ")}. Run with --help for usage.
|
|
751
|
-
`),process.exit(2));let a=RR(e);"refusal"in a&&(process.stderr.write(`${a.refusal} Run with --help for usage.
|
|
752
|
-
`),process.exit(2));let d=Zb(t("--sweep-user"),n("--sweep-user"),{sweeps:n("--sweep")||n("--sweep-list")});return{summaryPath:o,target:s,includeChanged:n("--include-changed"),json:n("--json"),acceptAutomation:n("--accept-automation"),muteAutomation:n("--mute-automation"),leaveUndeletable:n("--leave-undeletable"),sweep:n("--sweep"),sweepList:n("--sweep-list"),...a,audit:Ud(e),...n("--preview")?{preview:!0}:{},...d!==void 0?{sweepUser:d}:{}}}function Zb(r,e,t){if(e)return t.sweeps||(process.stderr.write(`--sweep-user goes with --sweep or --sweep-list: it names the user the run wrote as, whose records the sweep looks for. Run with --help for usage.
|
|
753
|
-
`),process.exit(2)),(r===void 0||!Gr.test(r)||!r.startsWith("005"))&&(process.stderr.write(`--sweep-user takes the id of a user, 005 and 12 or 15 more letters and digits, not "${r??""}". Run with --help for usage.
|
|
754
|
-
`),process.exit(2)),r}function Pd(r,e){if(!(r===void 0||e.kept||e.given)&&/user the run wrote as|different users/.test(r))return` --sweep-user <id> names the user the run wrote as, which its summary does not keep: "sf org display user --target-org ${e.target}" gives the id of the user sf signs in as, the one a run of this machine wrote as`}var it=W.string().regex(Gr,"not a Salesforce id"),js=W.iso.datetime(),wg=W.object({objectApiName:W.string().regex(at,"not an API name"),kind:W.enum(["flow","trigger","process","workflowRule"]),name:W.string().max(255)}),eR=W.object({silenced:W.array(wg.extend({permission:W.string().max(255)})),stillRan:W.array(wg.extend({why:W.enum(["noBypass","managedPackage","notRead","noPermissionSet"])}))});function OA(...r){for(let e of r)if(typeof e=="string"&&Gr.test(e))return e}var Mg=W.object({tool:W.literal("sandforge-clone"),version:W.literal(1),source:W.string(),target:W.string().min(1),targetOrgId:it.optional(),record:W.string().optional(),objects:W.array(W.object({objectApiName:W.string().regex(at,"not an API name"),where:W.string().max(512).optional()})).max(2e3).optional(),wholeOrg:W.literal(!0).optional(),dryRun:W.literal(!1),elapsedMs:W.number().transform(r=>Math.max(0,r)),finishedAt:js.optional(),journal:W.string().min(1).max(4096).optional(),part:W.number().int().nonnegative().optional(),result:W.object({remapInJournal:W.literal(!0).optional(),remapTable:W.record(it,it),existingSourceIds:W.array(it),updatedSourceIds:W.array(it),createdByObject:W.array(W.object({objectApiName:W.string().regex(at,"not an API name"),sourceIds:W.array(it)})),withTheirRecordSourceIds:W.array(it).optional(),unattributed:W.array(W.object({objectApiName:W.string().regex(at,"not an API name"),ids:W.array(it)})).optional(),writtenBetween:W.object({first:js,last:js}).optional(),mayHaveBeenWritten:W.array(W.object({objectApiName:W.string().regex(at,"not an API name"),sourceIds:W.array(it)})).optional(),runUserId:it.optional()}),mutedAutomation:eR.optional().catch(void 0)});async function Cd(r,e,t,n=Dt(qt())){let o=e.indexOf(`
|
|
755
|
-
`),s=o>=0?e.slice(0,o):e;if(/^\{"run":/.test(s))return tR(r,t,n);let i=nR(e);if("refusal"in i)return i;let{journal:a,part:d}=i.summary,c=a!==void 0&&d!==void 0?await n.readAt(a,d):void 0;if(!c){if(!i.summary.result.remapInJournal)return i;let l=(i.summary.objects??[]).map(u=>u.objectApiName);return a===void 0||d===void 0?{refusal:"keeps the ids of its records in a journal it does not name. "+yg(t,l)}:{refusal:`keeps the ids of its records in ${a}, which cannot be read. `+yg(t,l)}}return{summary:{...i.summary,result:{...i.summary.result,remapTable:c.remap.table,existingSourceIds:c.remap.linked,updatedSourceIds:[],createdByObject:c.remap.createdByObject,...c.remap.withTheirRecord?{withTheirRecordSourceIds:c.remap.withTheirRecord}:{},...c.unattributed?{unattributed:c.unattributed}:{}}}}}function yg(r,e=[]){let t=e.length>0?e.join(","):"<its objects>";return`Its records can no longer be removed or verified from here. A checkpoint taken before the run takes ${r} back: ${Qt("checkpoint")} list --org ${r} names them, ${Qt("checkpoint")} rewind --org ${r} --checkpoint <id> rewinds to one. Without one, ${Qt("empty")} --target ${r} --objects ${t} --dry-run says what emptying its objects would delete: every record of them, not only the run's.`}async function tR(r,e,t){let n=await t.readAt(r,"all");if(!n)return{refusal:"is not the journal of a run."};let s=(await t.lastEndAt(r))?.at??vg(r).mtime.toISOString(),i=Date.parse(s)-Date.parse(n.startedAt),a=n.resume?.startedWith,d=n.resume?.recordId??a?.config.recordId,c=!d&&a?.config.inputMode==="org",l=!d&&a&&(a.config.inputMode==="soql"||c)?a.graph.nodes.filter(p=>p.included).map(({objectApiName:p})=>{let f=a.config.objectSoqlFilters?.[p];return f!==void 0?{objectApiName:p,where:f}:{objectApiName:p}}):void 0,u=Mg.safeParse({tool:"sandforge-clone",version:1,source:n.resume?.sourceOrgId??"",target:e,targetOrgId:n.targetOrgId,record:d??(l?void 0:""),...l?{objects:l}:{},...c?{wholeOrg:!0}:{},dryRun:!1,elapsedMs:Number.isFinite(i)&&i>0?i:0,finishedAt:s,journal:r,result:{remapTable:n.remap.table,existingSourceIds:n.remap.linked,updatedSourceIds:[],createdByObject:n.remap.createdByObject,...n.remap.withTheirRecord?{withTheirRecordSourceIds:n.remap.withTheirRecord}:{},...n.runUserId?{runUserId:n.runUserId}:{},...n.unattributed?{unattributed:n.unattributed}:{}}});return u.success?{summary:u.data}:{refusal:`is a journal the command cannot take a run back from: ${u.error.issues.slice(0,5).map(f=>`${f.path.map(String).join(".")||"the journal"}: ${f.message}`).join("; ")}.`}}function nR(r){let e;try{e=JSON.parse(r)}catch(a){return{refusal:`is not JSON (${a instanceof Error?a.message:String(a)}).`}}let n=W.object({tool:W.literal("sandforge-clone"),dryRun:W.boolean()}).safeParse(e);if(!n.success)return{refusal:"is not a summary sandforge clone printed with --json."};if(n.data.dryRun)return{refusal:"is the summary of a dry run, which wrote nothing to the target: there is nothing of it to remove."};let o=ii(e,"sandforge-clone");if(o)return{refusal:ai(o)};if(!W.object({result:W.object({createdByObject:W.array(W.unknown())})}).safeParse(e).success)return{refusal:"does not say which records the run created (createdByObject): it was printed before the summary said so, and the records the run created cannot be told from those the target already held. sandforge cleanup remains for such a run."};let i=Mg.safeParse(e);return i.success?{summary:i.data}:{refusal:`is not a summary a removal can read: ${i.error.issues.slice(0,5).map(d=>`${d.path.map(String).join(".")||"the summary"}: ${d.message}`).join("; ")}.`}}function qd(r){let{result:e}=r,t=pc({idRemapTable:e.remapTable,idRemapExisting:[...e.existingSourceIds,...e.updatedSourceIds],idRemapCreated:e.createdByObject});return ef(t,e.unattributed)}function Bg(r){return`${fc({idRemapTable:r.result.remapTable,idRemapExisting:r.result.existingSourceIds,idRemapCreated:r.result.createdByObject,idRemapWithTheirRecord:r.result.withTheirRecordSourceIds}).length+r.result.updatedSourceIds.length} record(s) the target already held, which the run linked to or wrote over, stay`}function rR(r,e,t){let n=e.reduce((s,i)=>s+i.ids.length,0),o=r.result.writtenBetween?.last??r.finishedAt;return[`the clone of ${jy(r)} wrote to ${t.target}${o?` until ${o}`:""}; a removal deletes the ${n} record(s) it created, children first:`,...e.map(s=>` ${s.objectApiName}: ${s.ids.length}`),...sR(e),Bg(r),t.includeChanged?"records changed since the run go too, and what was added to them since":`records changed since the run stay, as do those records added since depend on (${bn("--include-changed","removal")} takes them)`]}function oR(r){return r.flatMap(({part:e,plan:t})=>[`then the ${Mn(t).length} record(s) of the run's part ${e.part} (its summary's "part") an earlier --remove of that part left, once these are gone:`,...t.map(n=>` ${n.objectApiName}: ${n.ids.length}`)])}function sR(r){let e=new Set(r.filter(n=>n.ids.length>0).map(n=>n.objectApiName)),t=e.has("QuoteLineItem")||e.has("OpportunityLineItem");return!e.has("Quote")||!t?[]:[" and the lines the platform copied between a quote the run synced and its opportunity, read as the removal begins and counted apart (--preview counts them)"]}function Lg(r){let e=r.platformCopies??0;if(e<=0)return"";let t=r.planned-e;return r.objectApiName===Io?` (${t>0?`${t} the run wrote, and `:""}${e} the target's duplicate rules made of the run's records)`:` (${t} the run wrote, and ${e} the platform copied between the quote the run synced and its opportunity)`}function iR(r,e="run"){let t=r.tookAlong,n=r.cameAlong;return[...t&&t.count>0?[` took along ${t.count} record(s) that were not the ${e}'s, added or changed since it: ${t.objects.join(", ")}`]:[],...n&&n.count>0?[` took along ${n.count} record(s) the ${e} did not write that came with its records, made as it wrote: ${n.objects.join(", ")}`]:[]]}function aR(r){return[r.deleted>0?`${r.deleted} deleted`:"",r.alreadyGone>0?`${r.alreadyGone} already gone`:"",(r.notVisible??0)>0?`${r.notVisible} not visible to this user (neither found nor in the recycle bin)`:"",r.keptChanged>0?`${r.keptChanged} kept, changed since the run`:"",r.keptDependents>0?`${r.keptDependents} kept for records that stay`+(r.heldBy.length>0?` (${r.heldBy.join(", ")})`:""):"",r.refused>0?`${r.refused} refused`:"",(r.notReached??0)>0?`${r.notReached} not reached`:""].filter(Boolean).join(", ")}function dR(r){let e=r.count>r.names.length?", \u2026":"";return`${r.count} file(s) attached to them stay in the org, as the run did not create them: ${r.names.join(", ")}${e}`}function cR(r,e,t=0){let n=[...new Set(e.flatMap(o=>o.unchecked))];return[`removal: ${r.toUpperCase()}`,...e.flatMap(o=>[` ${o.objectApiName}: ${aR(o)||"nothing"} of ${o.planned}${Lg(o)}`,...iR(o),...o.reasons.map(s=>` ${s}`),...o.filesLeft&&o.filesLeft.count>0?[` ${dR(o.filesLeft)}`]:[]]),...n.length>0?[`not checked, deleted with their parent: ${n.join(", ")}`]:[],...t>0?[`not reachable: ${t} record(s) a call of the run may have written before its answer was lost may be in the org, under ids the run never learned`]:[]]}function Wg(r){let e=r.automationGaps;return e?[...e.error?[` the target's automation could not all be read (${e.error}): what it creates may be missed`]:[],...e.flowsNotRead>0?[` ${e.flowsNotRead} flow(s) on the run's objects not read: what they create is not looked at`]:[],...e.triggers>0?[` ${e.triggers} Apex trigger(s) on the run's objects: what they create no metadata says`]:[]]:[]}function Dg(r){return[...r.unread.map(e=>` not looked at: ${e.objectApiName}: ${e.reason}`),...r.handWork.map(e=>` created by the run's user in the window, where neither the run nor its automation writes: ${e.objectApiName}: ${e.count} (left)`)]}var bg=10;function lR(r,e,t=!1){return ht("--max-total")?`The run would write ${r} records, more than --max-total ${e}: narrow the clone (--max, --exclude-object, --filter), or raise --max-total.`:nr()?.startsWith("sandforge env")===!0?t?`The run would write ${r} records, more than the ${e} the resource's maxTotal holds it to: narrow the resource in the file, or raise its maxTotal.`:`The run would write ${r} records, more than the ${e} its plan counted: the source holds more records than when it was planned. Plan again.`:`The run would write ${r} records, more than the ${e} ${bn("--max-total")} holds it to: narrow the clone with this script's own --max, --exclude-object or --filter, or raise its --max-total.`}function sn(r){return ht(r)?r:`this script's own removal with ${r==="--sweep-list"||r==="--sweep"?"":"--sweep "}${r}`}function Fd(r){let e=nr();return e===void 0?`${r} takes them`:`${e} keeps them; ${sn(r)} takes them`}function Ps(r){let e=r.length-bg;return`${r.slice(0,bg).join(", ")}${e>0?` and ${e} more`:""}`}function Dn(r){return r.map(e=>`${e.objectApiName}: ${e.count}`).join(", ")}function uR(r,e){let t=r.changed??0;return[r.made>0?`${r.made} made for the run`+((r.sameSave??0)>0?` (${r.sameSave} in the same save)`:""):"",r.madeOver>0?`${r.madeOver} under records the run wrote over`:"",r.late>0?`${r.late} late`:"",r.untied>0?`${r.untied} tied to nothing of the run`:"",t>0?`${t} of them changed since the run${e.includeChanged===!0?"":", kept"}`:""].filter(Boolean).join(", ")}function Ur(r,e,t){return r[e]-(t.includeChanged===!0?0:r.changedIn?.[e]??0)}function pR(r,e){let t=e.sweepUntied===!0&&r.untied?.refusal===void 0;return r.found.reduce((n,o)=>{let s=o.classes;return s?n+Ur(s,"made",e)+Ur(s,"madeOver",e)+(e.sweepLate===!0?Ur(s,"late",e):0)+(t?Ur(s,"untied",e):0):n},0)}function Rg(r,e,t,n){return t.flatMap(o=>{let s=r.found.find(a=>a.objectApiName===o.objectApiName)?.classes,i=s?Math.min(o.count,Ur(s,e,n)):o.count;return i>0?[{objectApiName:o.objectApiName,count:i}]:[]})}function fR(r,e,t){let n=[],o=r.late??[];if(o.length>0&&e.sweepLate!==!0)n.push(`kept, made late \u2014 tied to the run but created more than a minute after the record it hangs from, or by the org's Automated Process user: ${Dn(o)} (${Fd("--sweep-late")})`);else if(t&&e.sweepLate===!0){let i=Rg(r,"late",o,e);n.push("with --sweep-late, it would delete too what was made late: "+(i.length>0?Dn(i):o.length>0?"none":"none found"))}let s=r.untied;if(s&&s.objects.length>0){if(s.refusal!==void 0)n.push(`kept, tied to nothing of the run: ${Dn(s.objects)} \u2014 --sweep-untied is refused: ${s.refusal}`);else if(e.sweepUntied!==!0)n.push(`kept, created as the run's user in its window but tied to nothing of it: ${Dn(s.objects)} (${Fd("--sweep-untied")})`);else if(t){let i=Rg(r,"untied",s.objects,e);n.push("with --sweep-untied, it would delete too what is tied to nothing of the run: "+(i.length>0?Dn(i):"none"))}}else t&&e.sweepUntied===!0&&n.push(s?.refusal!==void 0?`with --sweep-untied, it would delete nothing tied to nothing of the run: --sweep-untied is refused: ${s.refusal}`:"with --sweep-untied, it would delete too what is tied to nothing of the run: none found");if(r.notLooked&&r.notLooked.length>0&&n.push(`not looked at, past the ${Na} objects a sweep counts: `+Ps(r.notLooked)),r.muted){let{silenced:i,stillRan:a}=r.muted;n.push(`the run's mute kept ${i.length} automation(s) quiet; `+(a.length>0?`what still ran may have made what is listed: ${Ps(a.map(d=>`${d.name} (${d.objectApiName})`))}`:"nothing of what the run fired still ran"))}return t&&n.push(...hR(r,e)),n}function hR(r,e){let t=s=>r.found.some(i=>!i.overBound&&(i.classes?.[s]??0)>0),n=t("made")||t("madeOver"),o=[n?_g:"",e.sweepLate===!0&&t("late")?`under ${n?"them":"the run's records"} within a quarter of an hour with --sweep-late`:"",e.sweepUntied===!0&&r.untied?.refusal===void 0&&t("untied")?"anywhere in the run's window with --sweep-untied":""].filter(Boolean);return o.length===0?[]:[`${Ug(`${o.join(", or ")}${o.length>1?",":""}`)}: check the names before a --sweep`]}var _g="under the run's records within a minute of them";function Ug(r){return`a record made by hand as the run's user ${r} reads as the automation's, and one changed by hand before the run's last write as unchanged`}function vs(r,e,t,n=t===void 0){let o=pR(r,t??{}),s=r.found.reduce((a,d)=>a+d.count,0),i=r.found.some(a=>a.overBound)?" or more":"";return[r.window?`a sweep looks in ${e} for what the run's user created from ${r.window.from} to ${r.window.to} that the run's id map does not hold, in: ${Ps(r.looked)}`:`a sweep of ${e} cannot tell the window the run wrote in`,...r.found.length>0?[`it found ${s}${i} record(s) and would delete `+(o>0?`${o} of them, children first`:"none of them")+"; per object, all it found:",...r.found.map(a=>` ${a.objectApiName}: ${a.count}`+(a.overBound?" or more (over the bound: none would be deleted)":"")+(a.classes?` \u2014 ${uR(a.classes,t??{})}`:"")+(a.names.length>0?` (${a.names.join(", ")}${a.count>a.names.length?", \u2026":""})`:""))]:r.window?["it finds nothing to delete"]:[],...fR(r,t??{},n),...Wg(r),...Dg(r),...r.refusal?[`sweep refused: ${r.refusal}`]:[]]}function gR(r,e){let t=r?.listing;return e===void 0&&t?.refusal===void 0?t:void 0}function vd(r,e){let t=r.reduce((g,m)=>g+(m.heldByAutomation??0),0);if(t===0)return[];let n=Math.min(t,r.reduce((g,m)=>g+(m.heldByAutomationAfterRun??0),0)),o=Math.min(t,r.reduce((g,m)=>g+(m.heldByAutomationAlong??0),0)),s=mR(t,o),i=[...new Set(r.flatMap(g=>g.automationHolders??[]))],a=i.length>0?` (${Ps(i)})`:"",d=`likely by the target's automation${a}`,c=`delete them by hand, then remove the run again; ${bn("--preview","removal")} says what of it their delete leaves changed since, which ${bn("--include-changed","removal")} takes`;if(e.part===void 0&&e.sweep!==!0&&e.windowUntold===!0)return[`${t} record(s) of the run kept for records created under them as its user, within a minute of them, ${d}: a sweep cannot take them, as it cannot tell the window the run wrote in now \u2014 ${c}`];let l=e.part!==void 0?"that part's last write":e.inParts===!0?"the last write of the run's part that wrote them":"the run's last write",u=n===0?"during the run, as its user":n===t?`as its user after ${l}, within a minute of them`:`as its user during the run or, under ${n} of them, after ${l}, within a minute of them`,p=e.part===void 0?"of the run":`of the run's part ${e.part} (its summary's "part")`,f=`${t} record(s) ${p} kept for records created under them ${u}, `+(n===0?d:`by the target's automation or by hand${a}`),h=Ug(_g);if(e.part!==void 0){let g=m=>`${nr()===void 0?"--remove":"this script's own removal"} of part ${e.part}'s summary with ${m}`;return[`${f}: `+(e.sweep===!0?"this removal's sweep looked in its own part's window alone, and did not see them; ":"a sweep of this summary looks in its own part's window alone, and leaves them; ")+`${g("--sweep")} ${s} (${g("--sweep-list")} shows them; ${h}: check the names before it), or ${c}`]}return[e.sweep===!0?`${f}: the sweep left them \u2014 ${sn("--sweep-list")} says why; ${sn("--sweep-late")} takes those it lists as late, ${bn("--include-changed","removal")} those changed after the run's last write`:`${f}: ${sn("--sweep")} ${s} (${sn("--sweep-list")} shows them); ${h}: check the names before `+(ht("--sweep")?"a --sweep":sn("--sweep"))]}function mR(r,e){let t="the removal deletes those, and the org takes them along";return e<=0?"takes them first":e>=r?`takes them with the run's records they hang from: ${t}`:`takes them first, but for those under ${e} of the run's records, which go with them: ${t}`}var zg={late:"made late",untied:"tied to nothing of the run"};function wR(r){return r.map(({class:e,objects:t,option:n,refusal:o})=>{let s=` left, ${zg[e]}: ${Dn(t)}`;return o!==void 0?`${s} \u2014 ${n} is refused: ${o}`:`${s} (${Fd(n)})`})}function yR(r){return[`sweep: ${r.status.toUpperCase()}`,...r.objects.flatMap(e=>{let t=e.afterRemoval??0,n=Math.min(e.afterRemovalUnder??0,t),o=e.withRemoval??0,s=[t-n>0?`${t-n} once the records of the run that point at them were gone`:"",n>0?`${n} once the removal was through: the org had not taken them along with the records of the run they hung from`:""].filter(Boolean),i=[e.deleted>0?`${e.deleted} deleted`+(s.length>0?` (${s.join("; ")})`:""):"",e.alreadyGone>0?`${e.alreadyGone} already gone`+(o>0?` (${o} with the records of the run they hung from, as the removal deleted those: the org took them along)`:""):"",e.keptChanged>0?`${e.keptChanged} kept, changed since the run`:"",(e.keptDependents??0)>0?`${e.keptDependents} kept for records that stay`+((e.heldBy??[]).length>0?` (${(e.heldBy??[]).join(", ")})`:""):"",e.refused>0?`${e.refused} refused`:""].filter(Boolean).join(", ");return[` ${e.objectApiName}: ${i||"nothing"} of ${e.found}`,...e.reasons.map(a=>` ${a}`)]}),...wR(r.left??[]),...(r.goneAlong??[]).map(({class:e,objects:t})=>` ${zg[e]}, no longer in the org once the records of the run were gone: ${Dn(t)}`),...Wg(r),...Dg(r),...r.refusal?[` ${r.refusal}`]:[]]}function bR(r){return Ws(r).flatMap(e=>[...Mn(e.created),...e.linked])}function Ws(r){let e=r?.part;return e===void 0?[]:(r?.parts??[]).filter(t=>t.part!==e)}function Is(r,e){let t=new Set(r?.earlier?.partsRemoved??[]);return Ws(r).flatMap(n=>{let o=(e?.otherParts??[]).filter(({part:i})=>i===n.part).flatMap(({objects:i})=>i).reduce((i,a)=>i+a.count,0),s=Mn(en(n.created,r?.earlier?.removalLeft)).length+o;return s===0?[]:[`a sweep of this summary leaves the ${s} record(s) of the run's part ${n.part} (its summary's "part"), the run's own, never the target's automation's: `+(t.has(n.part)?"an earlier --remove of that part left them, which the removal of this summary takes up once its own records are gone":"--remove of that part's summary takes them")]})}async function Nd(r,e,t,n,o,{signal:s,ofTheRun:i,user:a}={}){let d;try{d=await Ls(r).read(e,n.map(u=>u.objectApiName))}catch(u){d={error:Y(u)}}let c=t.result.runUserId??a,l=Ws(i).map(({part:u,created:p})=>({part:u,created:p}));return{writtenBetween:t.result.writtenBetween,created:n,remap:new Set([...Object.values(t.result.remapTable),...bR(i)].map(u=>u.slice(0,15))),...l.length>0?{otherParts:l}:{},automation:wf(d),...c?{runUserId:c}:{},ties:o,...s?{signal:s}:{}}}var Gg=["--sweep-late","--sweep-untied"];function RR(r){let e=Gg.filter(t=>r.includes(t));return e.length>0&&!r.includes("--sweep")&&!r.includes("--sweep-list")?{refusal:`${e.join(" and ")} ${e.length===1?"takes":"take"} more of what --sweep lists: give ${e.length===1?"it":"them"} with --sweep, or with --sweep-list to see what ${e.length===1?"it":"they"} would take.`}:{...r.includes("--sweep-late")?{sweepLate:!0}:{},...r.includes("--sweep-untied")?{sweepUntied:!0}:{}}}function OR(r){return{...r.sweepLate?{sweepLate:!0}:{},...r.sweepUntied?{sweepUntied:!0}:{}}}function kR(r){return r?{sweep:e=>r.first(e),automationMade:r.automationMade,afterRemoval:e=>r.afterRemoval(e)}:{}}function Md(r,e,t){let n=Kn(r,e),o=Object.create(n);return o.counts=yf(yu(wu(r),t)),o}function kA(r){let e=Date.parse(r.firstWrittenAt??r.startedAt),t=Date.parse(r.end?.at??r.lastWriteAt??r.lastWrittenAt??"");return Number.isFinite(e)&&Number.isFinite(t)?{from:e,to:Math.max(e,t)}:void 0}function Id(r,e){return r!==void 0&&r.length>=15&&r.slice(0,15)===e.slice(0,15)}async function SR(r){let e=r.journalDir??qt(),t=new Set(r.own.ids.map(c=>c.slice(0,15))),n=(c,l)=>!r.span||!Number.isFinite(c)||!Number.isFinite(l)||c<=r.span.to+mf&&l>=r.span.from-gf,o=[],s=c=>{c.length===0||c.some(l=>t.has(l.slice(0,15)))||o.push({ids:[...c]})},i=$s(e,"forge-runs"),a=[];try{a=oy(i).filter(c=>c.endsWith(".ndjson"))}catch{}let d=Dt(e);for(let c of a){let l=$s(i,c);if(!(r.own.journal!==void 0&&Ct(r.own.journal)===Ct(l)))try{let u=await d.headAt(l);if(!u||!Id(u.targetOrgId,r.organizationId))continue;let p=await d.lastEndAt(l),f=Date.parse(p?.at??"")||vg(l).mtimeMs;if(!n(Date.parse(u.startedAt),f))continue;let h=await d.readAt(l,"all");s(h?.created.flatMap(g=>g.ids)??[])}catch{}}for(let c of r.own.otherParts??[])n(c.from,c.to)&&s(c.ids);for(let c of[Ci(e),Ci(e,Tf)]){let l=[];try{l=await c.list()}catch{continue}for(let u of l){if(r.own.runId!==void 0&&u.runId===r.own.runId||!(Id(u.targetOrganizationId,r.organizationId)||u.targetOrganizationId===void 0&&(Id(u.targetOrgId,r.organizationId)||r.alias!==void 0&&u.targetOrgId===r.alias)))continue;let f=Date.parse(u.firstWrittenAt??u.startedAt),h=u.end?Date.parse(u.end.at):Date.parse(u.lastWriteAt??u.lastWrittenAt??"")||Date.now();n(f,h)&&s([...u.created,...u.overwritten??[]].flatMap(g=>g.ids))}}return o}function TR(r){let e=r.removalSpans?.map(t=>t.first).filter(t=>Number.isFinite(Date.parse(t))).sort((t,n)=>Date.parse(t)-Date.parse(n))[0];return{otherRuns:r.otherRuns,...r.muted?{muted:{silenced:r.muted.silenced,stillRan:r.muted.stillRan}}:{},...e!==void 0?{removalBegan:e}:{},...r.made&&r.made.length>0?{madeEarlier:r.made}:{},...r.late&&r.late.length>0?{lateEarlier:r.late}:{}}}async function qg(r,e,t,n,o,s){let i=Date.parse(t.finishedAt??""),a=Ws(s).map(d=>({ids:Mn(d.created),from:Date.parse(d.startedAt??""),to:Date.parse(d.endedAt??"")}));return TR({otherRuns:await SR({organizationId:r,alias:e,span:Number.isFinite(i)?{from:i-t.elapsedMs,to:i}:void 0,own:{...t.journal!==void 0?{journal:t.journal}:{},ids:n.flatMap(d=>d.ids),...a.length>0?{otherParts:a}:{}}}),...t.mutedAutomation?{muted:t.mutedAutomation}:{},...o?{removalSpans:o.removalSpans}:{},...o?.made?{made:o.made}:{},...o?.late?{late:o.late}:{}})}var Og=3;function Ds(r){return/\.json$/i.test(r)?r.replace(/\.json$/i,".removals.json"):`${r}.removals.json`}function _s(r){let e=r.flatMap(t=>t.ids.map(n=>n.slice(0,15))).sort();return ry("sha256").update(e.join(",")).digest("hex")}var Ed=W.string().refine(r=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:?\d{2})$/.test(r)&&Number.isFinite(Date.parse(r)),"not a date"),AR=W.object({tool:W.literal("sandforge-clone"),version:W.literal(1),run:W.string(),removalStamps:W.record(it,Ed),removalSpans:W.array(W.object({first:Ed,last:Ed,userId:it})),removalLeft:W.array(it).optional(),sweep:W.object({sweptAt:js,deleted:W.number().int().nonnegative(),keptChanged:W.number().int().nonnegative(),refused:W.number().int().nonnegative()}).optional(),made:W.array(it).max(1e4*100).optional(),late:W.array(it).max(1e4*100).optional(),partsRemoved:W.array(W.number().int().nonnegative()).max(1e4).optional()});function Us(r,e){if(r===void 0)return{};let t;try{t=JSON.parse(r)}catch{}let n=W.object({tool:W.literal("sandforge-clone"),run:W.string()}).safeParse(t);if(!n.success)return{refusal:"is not the record of removals sandforge clone keeps there, and is not overwritten: move it, as the removal keeps there what it leaves on the records of the run."};if(n.data.run!==e)return{otherRun:!0};let o=AR.safeParse(t);if(!o.success)return{refusal:`is not a record of removals a removal can read: ${o.error.issues.slice(0,5).map(f=>`${f.path.map(String).join(".")||"the file"}: ${f.message}`).join("; ")}.`};let{removalStamps:s,removalSpans:i,removalLeft:a,sweep:d,made:c,late:l,partsRemoved:u}=o.data;return{earlier:{removalStamps:s,removalSpans:i,...a?{removalLeft:a}:{},...d?{sweep:d}:{},...c?{made:c}:{},...l?{late:l}:{},...u?{partsRemoved:u}:{}}}}function jR(r,e,t,n=[],o,s=[],i=[],a=[]){let d=new Set(t.gone??[]),c=[...a],l=$i(e?.made,s,c),u=$i(e?.late,i,c),p=l.join()!==(e?.made??[]).join()||u.join()!==(e?.late??[]).join();if(Object.keys(t.stamps).length===0&&!t.span&&d.size===0&&!o&&!p)return;let f=o??e?.sweep,h=d.size>0?n.flatMap(({ids:g})=>g.filter(m=>!d.has(m))):e?.removalLeft;return{tool:"sandforge-clone",version:1,run:r,removalStamps:{...e?.removalStamps,...t.stamps},removalSpans:[...e?.removalSpans??[],...t.span?[t.span]:[]],...h?{removalLeft:h}:{},...f?{sweep:f}:{},...l.length>0?{made:l}:{},...u.length>0?{late:u}:{},...e?.partsRemoved?{partsRemoved:e.partsRemoved}:{}}}async function Hg(r,e=Dt(qt())){let t=r.journal;if(t===void 0||!Sn(t))return;let n=await Ff(t,e),o=n.length>1?await e.readAt(t,"all"):void 0;if(!o)return;let s=Ds(t),i;try{i=kn(s,"utf8")}catch(c){if(c?.code!=="ENOENT")return{refusal:`${s} cannot be read: ${c instanceof Error?c.message:String(c)}`}}let a=_s(o.created),d=Us(i,a);return"refusal"in d?{refusal:`${s} ${d.refusal}`}:{parts:n,...r.part!==void 0?{part:r.part}:{},file:s,key:a,created:o.created,...d.earlier?{earlier:d.earlier}:{}}}function Kg(r){let e=new Set(r.earlier?.partsRemoved??[]);return r.parts.flatMap(t=>{if(t.part===r.part||!e.has(t.part))return[];let n=en(t.created,r.earlier?.removalLeft);return n.length>0?[{part:t,plan:n}]:[]})}function Vg(r,e){if(!(r.parts.length<2))return[...r.parts].sort((t,n)=>n.part-t.part).flatMap(t=>{let n=en(e,Mn(t.created));return n.length>0?[{part:t,plan:n}]:[]})}function vR(r,e){let t=[...new Set(e.flatMap(s=>s.keptDependents>0?s.heldBy:[]))],n=new Set(r.earlier?.partsRemoved??[]),o=s=>en(s.created,r.earlier?.removalLeft).map(i=>i.objectApiName);return r.parts.flatMap(s=>{if(s.part===r.part||n.has(s.part))return[];let i=new Set(Eo(o(s),r.parts.flatMap(d=>d.part===s.part?[]:o(d)))),a=t.filter(d=>i.has(d));return a.length>0?[{part:s.part,objects:a}]:[]})}function kg(r){return r.map(({part:e,objects:t})=>`of what this removal kept for records that stay, what the run's part ${e} (its summary's "part") holds \u2014 its ${t.join(", ")} records \u2014 goes with --remove of that part's summary, once that part's own records are gone, without --include-changed`)}function Jg(r,e,t){return r.parts.flatMap(n=>{if(n.part===e)return[];let o=en(n.created,r.earlier?.removalLeft),s=Nn(n);if(o.length===0||!s)return[];let i=rr(r.parts,n.part);return[{part:n.part,alongside:{plan:o,span:s,...Object.keys(t).length>0?{removalStamps:t}:{},...i.length>0?{laterParts:i}:{}}}]})}function Yg(r){return r?.part===void 0?[]:[...new Set(r.parts.flatMap(e=>e.part===r.part?[]:en(e.created,r.earlier?.removalLeft).map(t=>t.objectApiName)))]}function IR(r,e){let t=r.earlier,n=[...new Set([...t?.partsRemoved??[],...e.parts])].sort((i,a)=>i-a);if(Object.keys(e.stamps).length===0&&e.spans.length===0&&e.gone.length===0&&n.length===(t?.partsRemoved?.length??0))return;let o=new Set(e.gone.map(i=>i.slice(0,15))),s=(t?.removalLeft??Mn(r.created)).filter(i=>!o.has(i.slice(0,15)));return{tool:"sandforge-clone",version:1,run:r.key,removalStamps:{...t?.removalStamps,...e.stamps},removalSpans:Tr(t?.removalSpans,e.spans),removalLeft:s,...t?.sweep?{sweep:t.sweep}:{},...t?.made?{made:t.made}:{},...t?.late?{late:t.late}:{},partsRemoved:n}}function ER(r){let e={};for(let o of r)for(let s of[...o.otherPartStamps??[],o.stamps])Object.assign(e,s);let n=r.flatMap(o=>o.span?[o.span]:[]).reduce((o,s)=>o?{...o,first:Date.parse(s.first)<Date.parse(o.first)?s.first:o.first,last:Date.parse(s.last)>Date.parse(o.last)?s.last:o.last}:s,void 0);return{stamps:e,...n?{span:n}:{},gone:r.flatMap(o=>o.gone)}}function Qg(r,e){return e?{...r,removalStamps:{...r?.removalStamps,...e.removalStamps},removalSpans:Tr(r?.removalSpans,e.removalSpans)}:r}function Bd(r,e){let t=`${r}.${process.pid}.tmp`;try{Ig(t,JSON.stringify(e,null,2)+`
|
|
756
|
-
`,"utf8"),jg(t,r);return}catch(n){try{$d(t,{force:!0})}catch{}return n instanceof Error?n.message:String(n)}}async function $R(r=process.argv){let e=Date.now(),t=Xb(r),n=B=>t.json?console.error(B):console.log(B),o;try{o=kn(t.summaryPath,"utf8")}catch(B){process.stderr.write(`--remove ${t.summaryPath} cannot be read: ${B instanceof Error?B.message:String(B)}
|
|
757
|
-
`),process.exit(2)}let s=await Cd(t.summaryPath,o,t.target);if("refusal"in s&&(process.stderr.write(`--remove ${t.summaryPath} ${s.refusal}
|
|
758
|
-
`),process.exit(2)),t.preview)return FR(t,s.summary,n,e);let i,a=async()=>{if(!i){let B=await En(t.target),J=pn(B);i={session:B,conn:J,org:await on(J)}}return i},d=s.summary.journal;if(d!==void 0&&Sn(d)&&Dt(qt()).callsInFlightAt(d)>0){let{conn:B,org:J}=await a();s.summary.targetOrgId!==void 0&&!Fs(s.summary.targetOrgId,J.id)&&Tn(Ht(s.summary.targetOrgId));let ie=await Dt(qt()).reconcileAt(d,Ia(B));for(let oe of Ea(ie,t.target,"removal"))n(oe);let Re=(ie.underway??[]).reduce((oe,{rows:Qe})=>oe+Qe,0),re=Xp(ie)-Re;re>0&&n(` the journal names none of the ${re} row(s) that may be in ${t.target}: they stay, and ${sn("--sweep-list")} shows what the run's user created in the run's window`),s=await Cd(t.summaryPath,kn(t.summaryPath,"utf8"),t.target),"refusal"in s&&(process.stderr.write(`--remove ${t.summaryPath} ${s.refusal}
|
|
759
|
-
`),process.exit(2))}let{summary:c}=s;c.targetOrgId===void 0&&c.target!==t.target&&(process.stderr.write(`The run wrote to ${c.target}, and its records are removed from that org only: give --target ${c.target}.
|
|
760
|
-
`),process.exit(2));let l=(c.result.mayHaveBeenWritten??[]).reduce((B,{sourceIds:J})=>B+J.length,0),u=0,p,f,h,g=[],m=!1,w=!1,b,S=B=>{let J={sweep:t.sweep,windowUntold:m,inParts:w};return b?[...vd(b.own,J),...b.others.flatMap(({part:ie,objects:Re})=>vd(Re,{...J,part:ie}))]:vd(B,J)},R=(B,J,ie,Re,re)=>{if(t.json){process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"remove",summary:t.summaryPath,target:t.target,...ie?{targetOrgId:ie}:{},includeChanged:t.includeChanged,result:{status:B,planned:J.reduce((oe,Qe)=>oe+Qe.planned,0),objects:J,...l>0?{mayHaveBeenWritten:l}:{},...u>0?{removedEarlier:u}:{},...re?{sweep:re}:{},...p?{sweepListing:p}:{},...Sg(c,t)!==void 0?{wholeOrgNotSwept:!0}:{},...f?{mutedAutomation:f}:{},...g.length>0?{heldByOtherParts:g}:{}},...Re?{removalsFile:Re}:{},elapsedMs:Fe(e)},null,2)+`
|
|
761
|
-
`);for(let oe of S(J))console.error(oe);for(let oe of kg(g))console.error(oe);return}if(J.length>0||!re)for(let oe of cR(B,J,l))console.log(oe);if(re)for(let oe of yR(re))console.log(oe);for(let oe of S(J))console.log(oe);for(let oe of kg(g))console.log(oe);Re&&console.log(`what this removal left on the run's records is kept in ${Re}, which the next --remove of this summary reads`),console.log(`
|
|
762
|
-
done in ${Fe(e)}ms`)},k=qd(c);if(k.length===0){n("The run created no record: there is nothing of it to remove."),R("success",[]);return}let I=_s(k),O=Ds(t.summaryPath),A;try{A=kn(O,"utf8")}catch(B){B?.code!=="ENOENT"&&(process.stderr.write(`${O} cannot be read: ${B instanceof Error?B.message:String(B)}
|
|
763
|
-
`),process.exit(2))}let x=Us(A,I);"refusal"in x&&(process.stderr.write(`${O} ${x.refusal}
|
|
764
|
-
`),process.exit(2));let{otherRun:j,earlier:E}=x,$=await Hg(c);$&&"refusal"in $&&(process.stderr.write(`${$.refusal}
|
|
765
|
-
`),process.exit(2)),w=$!==void 0;let L=$&&Ct(O)!==Ct($.file)?$:void 0,Q=Qg(E,L?.earlier);n(`sandforge clone --remove ${t.summaryPath} from ${t.target}`);let G=Sg(c,t);G!==void 0&&n(G);let V=to({objects:k,removalLeft:E?.removalLeft}),q=en(V,L?.earlier?.removalLeft),me=B=>B.reduce((J,ie)=>J+ie.ids.length,0);u=me(k)-me(q),me(k)>me(V)&&n(`${me(k)-me(V)} record(s) removed by an earlier --remove of this summary`),me(V)>me(q)&&n(`${me(V)-me(q)} record(s) removed by an earlier --remove of the run's other part or of its journal`);let de=L?Kg(L):[],H=$&&!("refusal"in $)&&!L?$:void 0,pe=H?Vg(H,q):void 0,ue=t.includeChanged&&c.result.runUserId!==void 0;if(q.length===0&&de.length===0&&!t.sweep&&!t.sweepList&&!ue){n("nothing left of the run to remove"),R("success",[]);return}let{session:be,conn:ne,org:K}=await a(),Z=new Map([[K.id,{alias:t.target,username:be.username}]]),U=`sandforge-clone-${Es()}`,se,Se=B=>xs(t.audit,Z,{action:"cleanup_delete",module:"forge",operationId:U,orgId:K.id,...B,...f?{muted:no(f)}:{}}),ge=t.sweepList?void 0:zr(t.target,K,"remove");ge&&ke({code:"PRODUCTION_TARGET",message:ge}),c.targetOrgId!==void 0&&!Fs(c.targetOrgId,K.id)&&Tn(Ht(c.targetOrgId));let Te=c.result.writtenBetween===void 0?c:void 0;c=await Cs(ne,c);let De=()=>qg(K.id,t.target,c,k,Q,L);if(t.sweepList){let B=await Ma(Md(ne,"sandforge clone --sweep-list"),await Nd(ne,t.target,c,k,await De(),{ofTheRun:L,...t.sweepUser!==void 0?{user:t.sweepUser}:{}}),Q?.removalSpans??[]);for(let ie of vs(B,t.target,t,!0))n(ie);let J=Pd(B.refusal,{kept:c.result.runUserId!==void 0,given:t.sweepUser!==void 0,target:t.target});J!==void 0&&n(J);for(let ie of Is(L,B))n(ie);t.json?process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"sweep-list",summary:t.summaryPath,target:t.target,targetOrgId:K.id,listing:B,elapsedMs:Fe(e)},null,2)+`
|
|
766
|
-
`):console.log(`
|
|
767
|
-
done in ${Fe(e)}ms`),B.refusal!==void 0&&process.exit(Og);return}let _=c.result.runUserId,P=new AbortController,z=()=>P.abort(),ee=q.length>0||de.length>0||ue;q.length>0||de.length>0?Ne():n(ue?"nothing left of the run's own records to remove: the duplicate record sets the target's rules made of them are read again, and taken changed since the run":"nothing left of the run to remove");let X=t.sweep?bf(Md(ne,"sandforge clone --sweep",P.signal),await Nd(ne,t.target,c,k,await De(),{signal:P.signal,ofTheRun:L,...t.sweepUser!==void 0?{user:t.sweepUser}:{}}),{includeChanged:t.includeChanged,removalSpans:Q?.removalSpans??[],...OR(t),approve:async B=>{p=B,n("");for(let ie of vs(B,t.target,t))n(ie);let J=Pd(B.refusal,{kept:c.result.runUserId!==void 0,given:t.sweepUser!==void 0,target:t.target});J!==void 0&&n(J);for(let ie of Is(L,B))n(ie)}}):void 0;if(X){let B=qn(z);try{await X.ask()}finally{B()}let J=gR(X,p);if(J){p=J,n("");for(let ie of vs(J,t.target,t))n(ie);for(let ie of Is(L,J))n(ie)}}let _e=X?.takes??[];(ee||_e.length>0)&&!P.signal.aborted&&await et(_e);let M,$e=[];if(ee)M=await pt(),M.stoppedForUndeletable&&(h&&ke(h),process.exit(1));else if(X){let B=await gt(),J=qn(z);try{await X.first(),await X.afterRemoval()}finally{if(J(),B){f=await B.release();for(let ie of Vn(f,t.target))n(ie)}}}let ve=X?.result();ve&&xs(t.audit,Z,{action:"cleanup_delete",module:"forge",operationId:`${U}-sweep`,orgId:K.id,outcome:ve.status==="refused"?"stopped":ve.status,...ve.status==="refused"?{code:"SWEEP_REFUSED"}:{},objects:Of(ve),details:kf(ve,I),...!ee&&f?{muted:no(f)}:{}});function Ne(){for(let B of rR(c,q,t))n(B);for(let B of oR(de))n(B);E?n(`what earlier removals of this summary left on the run's records, read from ${O}, is not a change since the run`):j&&n(`${O} is of another run: it is not read, and what this removal leaves on the records, if anything, takes its place`),L?.earlier&&n(`what the removals of the run's other part or of its journal left on its records, read from ${L.file}, is no change since the run`)}function ke(B){return Se({outcome:"stopped",code:B.code}),Tn(B)}function Tn(B){return process.stderr.write(`${xt(B)}
|
|
768
|
-
`),t.json&&process.stdout.write(io({tool:"sandforge-clone",summary:t.summaryPath,target:t.target,elapsedMs:Fe(e)},B)),process.exit(1)}function Ht(B){return{code:so,message:`${t.target} is not the org the run wrote to (${B}), and its records are removed from that org only. Nothing was deleted.`}}async function et(B){let J=[...new Set([...q,...de.flatMap(we=>we.plan)].map(we=>we.objectApiName))],ie=[...new Set([...Eo(J,Yg(L),{userKept:_!==void 0}),...J.length===0&&ue?[Io]:[],...B])],Re=Ei(J),re=await Ls(ne).read(t.target,ie);n("");for(let we of ca(re,t.target,ie.length,Re))n(we);if(t.muteAutomation){let we=new Set(Re);try{se=await Mi(async()=>Fi(ne),re,{writes:(Be,He)=>He==="delete"||He==="update"&&we.has(Be)}),f=se.muted;for(let Be of Vn(se.muted,t.target))n(` ${Be}`)}catch(Be){if(!Ar(Be))throw Be;ke(Be.refusal)}}let oe=se?.automation??re,Qe=da(oe,t.target,{drafted:Re,assign:Xo(oe,ri(oe,Re)),mayMute:se===void 0&&ht("--mute-automation")});Qe&&!t.acceptAutomation&&ke({code:"AUTOMATION_NOT_ACCEPTED",message:Qe})}async function gt(){let B=se?.prepared&&!P.signal.aborted?await se.prepared.acquire(`sandforge clone --remove ${U}`).catch(J=>{if(!Ar(J))throw J;return ke(J.refusal)}):void 0;return B&&(f=B.outcome),B}async function pt(){let B,J=qn(z),ie=c.result.writtenBetween,Re=ie?{runStartedAt:new Date(ie.first),runEndedAt:new Date(ie.last)}:{runDurationMs:c.elapsedMs,...c.finishedAt?{runRecordedAt:new Date(c.finishedAt)}:{}},re=wl,oe=[],Qe=Xh(t.leaveUndeletable,t.target,tt=>{h=tt}),[we,...Be]=pe??[],He=L??(we?H:void 0),wt=L?.part??we?.part.part,_n=He&&wt!==void 0?Jg(He,wt,Q?.removalStamps??{}):[],An=He&&wt!==void 0?rr(He.parts,wt):[];try{if(q.length>0||ue){let Xe=we?we.plan:q;re=await Sr(Kn(ne,"sandforge clone --remove"),Xe,{...(we&&Nn(we.part))??Re,...Q?{removalStamps:Q.removalStamps,removalSpans:Q.removalSpans}:{},...kR(X),..._?{runUserId:_}:{},...An.length>0?{laterParts:An}:{},..._n.length>0?{otherParts:_n.map(jt=>jt.alongside)}:{},includeChanged:t.includeChanged,onUndeletable:Qe,beforeFirstWrite:async()=>{B=await gt()},signal:P.signal})}else B=await gt();let tt={...Q?.removalStamps,...re.stamps};for(let Xe of re.otherPartStamps??[])Object.assign(tt,Xe);let cn=[...wt!==void 0?[{part:wt,plan:we?we.plan:q}]:[],...[...Be,...de].map(Xe=>({part:Xe.part.part,plan:Xe.plan}))];for(let{part:Xe,plan:jt}of[...Be,...de]){if(re.stoppedForUndeletable||re.cancelled||P.signal.aborted)break;let dt=Nn(Xe)??(we?Re:void 0);if(!dt)continue;let yt=Tr(Q?.removalSpans,[re,...$e].flatMap(bt=>bt.span?[bt.span]:[])),Ge=rr(He?.parts??[],Xe.part),Vt=await Sr(Kn(ne,"sandforge clone --remove"),jt,{...dt,removalStamps:tt,removalSpans:yt,..._?{runUserId:_}:{},...Ge.length>0?{laterParts:Ge}:{},otherPartRecords:cn.flatMap(bt=>bt.part===Xe.part?[]:bt.plan),includeChanged:t.includeChanged,onUndeletable:Qe,signal:P.signal});Object.assign(tt,Vt.stamps),$e.push(Vt),L&&oe.push({part:Xe.part,objects:Vt.objects})}}finally{if(J(),B){f=await B.release();for(let tt of Vn(f,t.target))n(tt)}}if(oe.length>0&&(b={own:re.objects,others:oe}),re.stoppedForUndeletable)return re;let At=Q?.removalSpans.at(-1)?.last,Kt=$o(re.objects,...$e.map(tt=>tt.objects)),Ft=re.cancelled||$e.some(tt=>tt.cancelled);return Se({outcome:bl({status:xi(Kt,Ft)}),objects:Rl(Kt),...At?{leftBy:At}:{}}),re}let dn=ve&&Rf(ve,new Date().toISOString(),Q?.sweep),rt=jR(I,Q,M&&pe?ER([M,...$e]):M??{stamps:{}},q,dn,X?.made??[],X?.late??[],X?.gone??[]);rt&&$&&!L&&(rt.partsRemoved=$.parts.map(B=>B.part));let ot=rt?Bd(O,rt):void 0;if(ot&&process.stderr.write(`What this removal left on the run's records could not be kept in ${O} (${ot}): a later --remove of this summary may keep a record this removal wrote to as changed since the run, which --include-changed then takes.
|
|
769
|
-
`),L?.part!==void 0&&M&&!M.stoppedForUndeletable){let B=[M,...$e],J={};for(let re of B)for(let oe of[re.stamps,...re.otherPartStamps??[]])Object.assign(J,oe);let ie=IR(L,{stamps:J,spans:B.flatMap(re=>re.span?[re.span]:[]),gone:B.flatMap(re=>re.gone),parts:[L.part,...de.map(re=>re.part.part)]}),Re=ie?Bd(L.file,ie):void 0;Re&&process.stderr.write(`What this removal left on the run's records could not be kept in ${L.file} (${Re}): a later --remove of the run's other part or of its journal may keep a record this removal wrote to as changed since the run, which --include-changed then takes.
|
|
770
|
-
`)}let Ye=$o(M?.objects??[],...$e.map(B=>B.objects)),Ae=M?.cancelled===!0||$e.some(B=>B.cancelled),mt=yl(M?xi(Ye,Ae):"success",ve);L?.part!==void 0&&(g=vR(L,Ye)),Te&&!t.sweep&&Ye.some(B=>(B.heldByAutomation??0)>0)&&(m=(await Cs(ne,Te)).result.writtenBetween===void 0),R(mt,Ye,K.id,rt&&!ot?O:void 0,ve),mt!=="success"&&process.exit(Og)}var xR="not read by a preview: what the target's automation does as the records go \u2014 a trigger or a flow that deletes, keeps or creates other records \u2014 and what hangs from them, which a removal reads at each object\u2019s turn: a record kept for records that stay is counted with those to delete";function PR(r){return`${JSON.stringify({tool:"sandforge-clone",version:1,action:"remove-preview",summary:r.summary,target:r.target,...r.targetOrgId!==void 0?{targetOrgId:r.targetOrgId}:{},includeChanged:r.includeChanged,preview:r.preview,...r.sweepListing?{sweepListing:r.sweepListing}:{},refusals:r.refusals.map(({message:e})=>e),refusalCodes:r.refusals.map(({code:e})=>e),notes:r.notes,elapsedMs:r.elapsedMs},null,2)}
|
|
771
|
-
`}function CR(r,e,t,n){let o=i=>r.userNames[i]??i,s=["preview: what a removal would do; nothing was written"];for(let i of r.objects){let a=[i.toDelete>0?`${i.toDelete} to delete`:"",n&&i.changedSince>0?`${i.changedSince} of them changed since the run`:"",i.alreadyGone>0?`${i.alreadyGone} gone already`:"",i.notVisible>0?`${i.notVisible} not visible`:"",i.keptChanged>0?`${i.keptChanged} kept, changed since the run`:"",i.undeletable>0?`${i.undeletable} left, the user may not delete them`:"",i.unread>0?`${i.unread} left, not read`:""].filter(Boolean);s.push(` ${i.objectApiName}: ${a.join(", ")||"nothing"} of ${i.planned}${Lg(i)}`);let d=Object.entries(i.changedBy).sort((c,l)=>l[1]-c[1]);d.length>0&&s.push(` last changed by: ${d.map(([c,l])=>`${o(c)} ${l}`).join(" \xB7 ")}`);for(let c of i.reasons)s.push(` ${c}`)}for(let i of e)s.push($n(i,"a removal"));return[...s,...t]}async function FR(r,e,t,n){let o=e,s=[],i,a=(_,P,z)=>{if(s.push(xR),r.json){process.stdout.write(PR({summary:r.summaryPath,target:r.target,...z!==void 0?{targetOrgId:z}:{},includeChanged:r.includeChanged,preview:_,refusals:P,notes:s,elapsedMs:Fe(n),...i?{sweepListing:i}:{}}));return}t("");for(let ee of CR(_,P,s,r.includeChanged))t(ee);t(`
|
|
772
|
-
done in ${Fe(n)}ms`)};t(`sandforge clone --remove ${r.summaryPath} --preview of ${r.target}`),o.targetOrgId===void 0&&o.target!==r.target&&(process.stderr.write(`The run wrote to ${o.target}, and its records are read in that org only: give --target ${o.target}.
|
|
773
|
-
`),process.exit(2));let d=o.journal;d!==void 0&&Sn(d)&&Dt(qt()).callsInFlightAt(d)>0&&s.push("the run's journal names calls under way when it stopped: a removal looks for their rows in the target first and removes those it finds with the rest; this preview counts only what the summary names");let c=(o.result.mayHaveBeenWritten??[]).reduce((_,{sourceIds:P})=>_+P.length,0);c>0&&s.push(`${c} record(s) a call of the run may have written before its answer was lost may be in the org, under ids the run never learned: no removal reaches them`);let l=qd(o);if(l.length===0){s.push("The run created no record: there is nothing of it to remove."),a({planned:0,objects:[],userNames:{}},[]);return}let u=Ds(r.summaryPath),p;try{p=kn(u,"utf8")}catch(_){_?.code!=="ENOENT"&&(process.stderr.write(`${u} cannot be read: ${_ instanceof Error?_.message:String(_)}
|
|
774
|
-
`),process.exit(2))}let f=Us(p,_s(l));"refusal"in f&&(process.stderr.write(`${u} ${f.refusal}
|
|
775
|
-
`),process.exit(2));let h=await Hg(o);h&&"refusal"in h&&(process.stderr.write(`${h.refusal}
|
|
776
|
-
`),process.exit(2));let g=h&&Ct(u)!==Ct(h.file)?h:void 0,m=Qg(f.earlier,g?.earlier),w=to({objects:l,removalLeft:f.earlier?.removalLeft}),b=en(w,g?.earlier?.removalLeft),S=g?Kg(g):[],R=_=>_.reduce((P,z)=>P+z.ids.length,0);R(l)>R(w)&&s.push(`${R(l)-R(w)} record(s) removed by an earlier --remove of this summary`),R(w)>R(b)&&s.push(`${R(w)-R(b)} record(s) removed by an earlier --remove of the run's other part or of its journal`);for(let{part:_,plan:P}of S)s.push(`with them, ${R(P)} record(s) of the run's part ${_.part} an earlier --remove of that part left, read against that part, once these are gone`);let k=r.includeChanged&&o.result.runUserId!==void 0;if(b.length===0&&S.length===0&&!r.sweep&&!k){s.push("nothing left of the run to remove"),a({planned:0,objects:[],userNames:{}},[]);return}let I=await En(r.target),O=pn(I),A=await on(O);if(o.targetOrgId!==void 0&&!Fs(o.targetOrgId,A.id)){let _={code:so,message:`${r.target} is not the org the run wrote to (${o.targetOrgId}): its records are read in that org only. Nothing of the run was read.`};process.stderr.write(`${xt(_)}
|
|
777
|
-
`),r.json&&process.stdout.write(io({tool:"sandforge-clone",action:"remove-preview",summary:r.summaryPath,target:r.target,elapsedMs:Fe(n)},_)),process.exit(1)}let x=[],j=zr(r.target,A,"remove");if(j&&x.push({code:"PRODUCTION_TARGET",message:j}),o=await Cs(O,o),r.sweep){i=await Ma(Md(O,"sandforge clone --remove --preview --sweep"),await Nd(O,r.target,o,l,await qg(A.id,r.target,o,l,m,g),{ofTheRun:g,...r.sweepUser!==void 0?{user:r.sweepUser}:{}}),m?.removalSpans??[]),t("");for(let P of vs(i,r.target,r,!0))t(P);let _=Pd(i.refusal,{kept:o.result.runUserId!==void 0,given:r.sweepUser!==void 0,target:r.target});_!==void 0&&t(_);for(let P of Is(g,i))t(P)}let E=[...new Set([...b,...S.flatMap(_=>_.plan)].map(_=>_.objectApiName))],$=i?mc(i,r):[],L=[...new Set([...Eo(E,Yg(g),{userKept:o.result.runUserId!==void 0}),...E.length===0&&k?[Io]:[],...$])],Q=Ei(E),G=await Ls(O).read(r.target,L);t("");for(let _ of ca(G,r.target,L.length,Q))t(_);let V=da(G,r.target,{drafted:Q,assign:Xo(G,ri(G,Q)),mayMute:!r.muteAutomation&&ht("--mute-automation")});if(V&&!r.acceptAutomation&&x.push({code:"AUTOMATION_NOT_ACCEPTED",message:V}),b.length===0&&S.length===0&&!k){s.push("nothing left of the run to remove"),a({planned:0,objects:[],userNames:{}},x,A.id);return}b.length===0&&S.length===0&&s.push("nothing left of the run's own records to remove: the duplicate record sets the target's rules made of them are read again, and taken changed since the run");let q=new AbortController,me,de=qn(_=>{me=_,q.abort()}),H=o.result.writtenBetween,pe=H?{runStartedAt:new Date(H.first),runEndedAt:new Date(H.last)}:{runDurationMs:o.elapsedMs,...o.finishedAt?{runRecordedAt:new Date(o.finishedAt)}:{}},ue,be=[],[ne,...K]=(h&&!g?Vg(h,b):[])??[],Z=g??(ne?h:void 0),U=g?.part??ne?.part.part,se=Z&&U!==void 0?rr(Z.parts,U):[],Se=Z&&U!==void 0?Jg(Z,U,m?.removalStamps??{}):[],ge=[...U!==void 0?[{part:U,plan:ne?ne.plan:b}]:[],...[...K,...S].map(_=>({part:_.part.part,plan:_.plan}))];try{ue=await Sr(Kn(O,"sandforge clone --remove --preview"),ne?ne.plan:b,{...(ne&&Nn(ne.part))??pe,...m?{removalStamps:m.removalStamps,removalSpans:m.removalSpans}:{},...se.length>0?{laterParts:se}:{},...Se.length>0?{otherParts:Se.map(_=>_.alongside)}:{},...o.result.runUserId?{runUserId:o.result.runUserId}:{},includeChanged:r.includeChanged,previewOnly:!0,signal:q.signal});for(let{part:_,plan:P}of[...K,...S]){let z=Nn(_)??(ne?pe:void 0);if(!z||!ue.preview||q.signal.aborted)continue;let ee=rr(Z?.parts??[],_.part);be.push(await Sr(Kn(O,"sandforge clone --remove --preview"),P,{...z,...m?{removalStamps:m.removalStamps,removalSpans:m.removalSpans}:{},...ee.length>0?{laterParts:ee}:{},...o.result.runUserId?{runUserId:o.result.runUserId}:{},otherPartRecords:ge.flatMap(X=>X.part===_.part?[]:X.plan),includeChanged:r.includeChanged,previewOnly:!0,signal:q.signal}))}}finally{de()}let Te=ue.preview&&be.every(_=>_.preview)?{objects:Pi(ue.preview.objects,...be.map(_=>_.preview?.objects??[])),userNames:Object.assign({},ue.preview.userNames,...be.map(_=>_.preview?.userNames??{}))}:void 0;Te||(process.stderr.write(`interrupted: the preview stopped before it was through, and wrote nothing
|
|
778
|
-
`),process.exit(yr(me??"SIGINT")));let De=[ue,...be].flatMap(_=>_.undeletable??[]);if(De.length>0&&!r.leaveUndeletable){let _=De.map(P=>`${P.objectApiName} (${P.records} records)`).join(", ");x.push({code:Rd,message:`The user SandForge connects as may not delete the records of ${_} in ${r.target}: a removal stops before its first delete, unless given --leave-undeletable, which removes the rest and leaves those.`})}(b.length>0||S.length>0)&&s.push(Bg(o)),a({planned:R(b)+S.reduce((_,P)=>_+R(P.plan),0),objects:Te.objects,...De.length>0?{undeletable:De}:{},userNames:Te.userNames},x,A.id)}async function Cs(r,e,t=Dt(qt())){if(e.result.writtenBetween||e.journal===void 0||!Sn(e.journal))return e;let n={query:(s=>r.query(s,{scanAll:!0}))},o=await t.writtenBetweenAt(e.journal,r)??await t.writtenBetweenAt(e.journal,n);return o?{...e,result:{...e.result,writtenBetween:o}}:e}function Fs(r,e){return r.slice(0,15)===e.slice(0,15)}var NR=new Set(["--verify","--target","--source","--json","--audit"]),MR=new Set(["--verify","--target","--source","--audit"]);function BR(r){let e=r.slice(2);(e.includes("-h")||e.includes("--help"))&&(process.stdout.write(Wd),process.exit(0));let t=s=>{let i=e.indexOf(s),a=i>=0?e[i+1]:void 0;return a!==void 0&&!a.startsWith("--")?a:void 0};for(let s=0;s<e.length;s++){let i=e[s];if(MR.has(i)){e[s+1]!==void 0&&!e[s+1].startsWith("--")&&s++;continue}NR.has(i)||(process.stderr.write(`--verify takes --target, --source, --json and --audit, not "${i}". Run with --help for usage.
|
|
779
|
-
`),process.exit(2))}let n=t("--verify"),o=t("--target");return(!n||!o||e.includes("--source")&&!t("--source"))&&(process.stderr.write(`--verify takes the file a run printed its --json summary to, --target the org the run wrote to, and --source, when given, the org it read from. Run with --help for usage.
|
|
780
|
-
`),process.exit(2)),{summaryPath:n,target:o,source:t("--source"),json:e.includes("--json"),audit:Ud(e)}}var LR=W.object({result:W.object({writtenWithoutFields:W.array(W.object({objectApiName:W.string().regex(at),fields:W.array(W.object({field:W.string().regex(at)}))}))})}),WR=W.object({result:W.object({lookupsLeftEmptyByFilter:W.array(W.object({objectApiName:W.string().regex(at),field:W.string().regex(at),records:W.number().int().nonnegative(),recordIds:W.array(it)}))})}),DR={verified:0,partial:3,unstable:4};function _R(r,e){let t=[r.verdict==="unstable"?`verification: UNSTABLE \u2014 no two of ${r.attempts} readings of ${e} agreed: something still writes to the run's records; verify again once it is done`:`verification: ${r.verdict.toUpperCase()} (${r.attempts} readings of ${e})`],n=[];for(let s of r.objects){if(s.error!==void 0){t.push(` ${s.objectApiName}: not read (${s.error})`);continue}let i=[s.deleted>0?`${s.deleted} in the recycle bin`:"",s.notVisible>0?`${s.notVisible} neither there nor in the recycle bin, out of sight`:""].filter(Boolean),a=s.linksLeftEmptyByFilter??0,d=s.linksSetByAutomation??0,c=s.linksLeftEmptyByTheRun??0,l=[c>0?`${c} left empty by the run, as it said`:"",a>0?`${a} left empty by the target's lookup filter, as the run said`:"",d>0?`${d} set by the target's automation during the run`:""].filter(Boolean),u=s.linksChecked-s.linksBroken-a-d-c,p=s.withTheirRecord??0,f=s.linksUnchecked!==void 0?`lookups not checked (${s.linksUnchecked})`:s.linksChecked===0?"no lookup the run set to check":s.linksBroken===0&&l.length===0?`lookups: ${s.linksChecked} checked, all hold`:`lookups: ${s.linksChecked} checked, `+[...s.linksBroken>0?[`${s.linksBroken} do not hold`]:[`${u} hold`],...l].join(", ");t.push(s.expected===0&&p>0?` ${s.objectApiName}: none written by the run, and ${p} written by the platform with their record there`:` ${s.objectApiName}: ${s.present} of ${s.expected} there`+(i.length>0?`, ${i.join(", ")}`:"")+(p>0?`, and ${p} written by the platform with their record`:"")+`; ${f}`);for(let h of s.brokenLinks)t.push(h.found===null?` ${h.recordId}: ${h.field} is empty, the run set it to ${h.expected}`:` ${h.recordId}: ${h.field} points at ${h.found}, the run set it to ${h.expected}`);for(let h of s.explainedLinks??[])t.push(h.cause==="automation"?` ${h.recordId}: ${h.field} points at ${h.found??""}, which the target's automation created during the run; the run set it to ${h.expected}`:h.cause==="run"?` ${h.recordId}: ${h.field} is empty: left empty by the run, as it said, rather than set to ${h.expected}`:` ${h.recordId}: ${h.field} is empty: the target's lookup filter refused ${h.expected}, and the run left it empty`);s.recycleBinUnread!==void 0&&t.push(` the recycle bin could not be read (${s.recycleBinUnread})`),(s.moreInTheWindow??0)>0&&t.push(` ${s.moreInTheWindow} more ${s.objectApiName} record(s) were created in ${e} during the run by the run's user than the run wrote`+(p>0?" and the platform wrote with its records":"")+": the target's automation, another session writing as that user, or a call written twice");for(let h of s.changedRecords)n.push(` ${s.objectApiName} ${h.recordId}: modified ${h.modifiedAt}`+(h.modifiedById?` by ${h.modifiedById}`:""))}let o=r.objects.reduce((s,i)=>s+i.changed,0);return o>0&&t.push(`changed since the run: ${o} record(s), which --remove keeps unless --include-changed`,...n),r.linksUnchecked!==void 0&&t.push(`lookups not checked: ${r.linksUnchecked}`),t}async function UR(r=process.argv){let e=Date.now(),t=BR(r),n=E=>t.json?console.error(E):console.log(E),o;try{o=kn(t.summaryPath,"utf8")}catch(E){process.stderr.write(`--verify ${t.summaryPath} cannot be read: ${E instanceof Error?E.message:String(E)}
|
|
781
|
-
`),process.exit(2)}let s;try{s=JSON.parse(o)}catch{}W.object({tool:W.literal("sandforge-clone"),dryRun:W.literal(!0)}).safeParse(s).success&&(process.stderr.write(`--verify ${t.summaryPath} is the summary of a dry run, which wrote nothing to the target: there is nothing of it to verify.
|
|
782
|
-
`),process.exit(2));let a=ii(s,"sandforge-clone");a&&(process.stderr.write(`--verify ${t.summaryPath} ${ai(a,"verify")}
|
|
783
|
-
`),process.exit(2));let d=await Cd(t.summaryPath,o,t.target);"refusal"in d&&(process.stderr.write(`--verify ${t.summaryPath} ${d.refusal}
|
|
784
|
-
`),process.exit(2));let{summary:c}=d;c.targetOrgId===void 0&&c.target!==t.target&&(process.stderr.write(`The run wrote to ${c.target}, and its records are verified in that org only: give --target ${c.target}.
|
|
785
|
-
`),process.exit(2));let l=qd(c);if(l.length===0){n("The run created no record: there is nothing of it to verify.");return}let u,p=Ds(t.summaryPath),f;try{f=kn(p,"utf8")}catch{}let h=Us(f,_s(l)),g=l;if("refusal"in h)n(`${p} ${h.refusal}`);else if(u=h.earlier?.removalStamps,g=to({objects:l,removalLeft:h.earlier?.removalLeft}),g.length===0){n("An earlier --remove of this summary took every record the run created: there is nothing of it to verify.");return}let m=LR.safeParse(s),w=WR.safeParse(s);n(`sandforge clone --verify ${t.summaryPath} in ${t.target}`);let b=await En(t.target),S=pn(b),R=await on(S);if(c.targetOrgId!==void 0&&!Fs(c.targetOrgId,R.id)){let E={code:so,message:`${t.target} is not the org the run wrote to (${c.targetOrgId}), and its records are verified in that org only. Nothing of the run was read.`};process.stderr.write(`${xt(E)}
|
|
786
|
-
`),t.json&&process.stdout.write(io({tool:"sandforge-clone",action:"verify",summary:t.summaryPath,target:t.target,elapsedMs:Fe(e)},E)),process.exit(1)}c=await Cs(S,c);let k=t.source??c.source,I;try{I=Wa(pn(await En(k)),"sandforge clone --verify source")}catch(E){I={unavailable:`the org the run read from, ${k}, could not be reached: ${Y(E)}`}}let O=new Map([[R.id,{alias:t.target,username:b.username}]]),A=E=>xs(t.audit,O,{action:"forge_verify",module:"forge",operationId:`sandforge-clone-${Es()}`,orgId:R.id,...E}),x;try{x=await new If({target:Wa(S,"sandforge clone --verify"),source:I}).verify({records:g,remapTable:c.result.remapTable,...c.result.writtenBetween?{runStartedAt:new Date(c.result.writtenBetween.first),runEndedAt:new Date(c.result.writtenBetween.last)}:c.finishedAt?{runRecordedAt:new Date(c.finishedAt)}:{},...u?{removalStamps:u}:{},...m.success?{writtenWithout:xf(m.data.result.writtenWithoutFields)}:{},...w.success?{leftEmptyByFilter:w.data.result.lookupsLeftEmptyByFilter}:{},leftEmptyByTheRun:$f(c.wholeOrg===!0),...c.result.withTheirRecordSourceIds?{withTheirRecord:c.result.withTheirRecordSourceIds}:{}})}catch(E){throw A({outcome:"failure"}),E}if(A({outcome:x.verdict==="verified"?"success":"partial",verdict:x.verdict,details:Ef(x)}),t.json)process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"verify",summary:t.summaryPath,target:t.target,targetOrgId:R.id,source:k,result:x,elapsedMs:Fe(e)},null,2)+`
|
|
787
|
-
`);else{for(let E of _R(x,t.target))console.log(E);console.log(`
|
|
788
|
-
done in ${Fe(e)}ms`)}let j=DR[x.verdict];j!==0&&process.exit(j)}var zR=new Set(["done","error","stopped"]);function GR(r){return r?`interrupted: the clone stopped before it was through; ${r} says what it created, and --remove ${r} takes it back`:"interrupted: the clone stopped before it was through; the summary above says what it created, and --remove takes it back from that summary saved to a file (--json)"}function Sg(r,e){if(!(r.wholeOrg!==!0||e.sweep||e.sweepList))return`the sweep is off for a clone of the whole org: its window spans the hours the run wrote in, and a sweep looks at ${Na} objects at most; ${sn("--sweep-list")} lists what the target's automation made for it, and ${sn("--sweep")} takes it`}var Tg="ROOT_NEVER_CREATED",qR="TABLE_NEVER_CLONED",Ld="No record was read or written.";async function HR(r,e,t){let n=[];for(let i of r)try{await t.createable(i.objectApiName)===!1&&n.push(i)}catch{}if(n.length===0)return;let o=n.find(i=>ho(i.objectApiName));if(o){let i=o.objectApiName;return{code:Tg,message:`${o.named}: SandForge never copies ${i} records, setup or the platform's own, and ${e}'s user may not create them: a clone has nothing to write of what it starts from. ${Ld}`}}let s;try{s=await t.whyNot(n.map(i=>i.objectApiName))}catch{return}for(let i of n){let a=s.get(i.objectApiName);if(a===void 0||!du(a))continue;let d=i.objectApiName,c=a==="platform"?"the platform writes them itself":"not even one with Modify All Data: they are setup the org keeps as records, or the platform's own";return{code:Tg,message:`${i.named}: no user can create ${d} records in ${e}, ${c}, and a clone has nothing to write of what it starts from. ${Ld}`}}}async function KR(r,e){if(r.tables)return r.tables.map(({objectApiName:i})=>({objectApiName:i,named:`--object ${i}`}));let t=r.record??"";if(t==="")return[];let n=t.slice(0,3),o;try{o=await e(r.source)}catch{return[]}let s=o.find(i=>i.keyPrefix===n)?.name;return s?[{objectApiName:s,named:`--record ${t} (a ${s})`}]:[]}function Ag(r,e,t){let n=o=>{let s=r.get(o);if(!s)throw new Error(`No connection for ${o}`);return s};return{describeFields:async(o,s)=>{let i=!t.has(`${o}::${s}`);return{fields:(await e(o,s)).fields.map(qi),sent:i}},query:async(o,s)=>Fn({query:async i=>n(o).query(i),queryMore:async i=>n(o).queryMore(i)},s)}}function ir(r,e){let t=r.get(e);if(!t)throw new Error(`No connection for ${e}`);return t}var VR=new Set(["Lead","Case"]);function JR(r,e,t,n){return{bulkWriteRecords:async(o,s,i,a,d)=>{if(e.dryRun)throw new Error("A dry run sends no Bulk API job.");if(e.applyAssignmentRules&&VR.has(s))return{answers:[],rows:[],unmatchedIds:[],untouched:{reason:"the run applies the target's assignment rules, which a job cannot",unsupported:!0},requests:0};try{let c=await tu(Ii(ir(r,o)),d.bulkManager,s,i,a,{...d.externalIdField?{externalIdField:d.externalIdField}:{},...d.signal?{signal:d.signal}:{},...d.onOpened?{onOpened:d.onOpened}:{}});return(c.unmatchedIds.length>0||c.answers.some(l=>l.success))&&n(),c}catch(c){throw c instanceof eu&&(n(),t?.note({orgId:o,objectApiName:s,...c.jobId?{jobId:c.jobId}:{}})),c}},duplicateRuleObjects:async o=>cf(ir(r,o))}}async function YR(r,e,t){let n=r?.since(0,e)??[];if(!r||n.length===0)return[];t(`waiting for ${n.length} Bulk API job(s) the run could not read back to end, before the mute is given back\u2026`);let o=await r.stillRunning(n);if(o.length>0){let s=o.map(i=>`${i.objectApiName}${i.jobId?` (${i.jobId})`:""}`).join(", ");t(`warning: ${o.length} Bulk API job(s) were still running as the mute was given back: ${s}; their records may have gone in with the target's automation on`)}return o}async function QR(r,e,t){let n=r.get(e);if(!n)throw new Error(`No connection for ${e}`);return Fn({query:async o=>n.tooling.query(o),queryMore:async o=>n.tooling.queryMore(o)},t)}async function XR(r=process.argv){if(r.slice(2).includes("--verify"))return UR(r);if(r.slice(2).includes("--remove"))return $R(r);let e={};try{await ZR(r,e)}finally{e.release?.()}}var Ns=class extends Error{constructor(e){super(e),this.name="CheckpointTakeInterrupted"}},Ms=class extends Error{constructor(e){super(e),this.name="QuestionInterrupted"}};async function ZR(r,e){let t=Date.now(),n=By(r),o=n.depth==="all",s=y=>n.json?console.error(y):console.log(y);s(`sandforge clone ${n.source} -> ${n.target} ${Ay(n)}`);for(let y of cb(n))s(y);if(n.resume&&n.files===void 0){let y=Dt(qt()),T=await y.headAt(dg(n.resume,y));T?.resume?.files&&(n={...n,files:T.resume.files},s("files: copied as the run taken up was begun, with --files"))}let i=await En(n.source),a=await En(n.target),d,c=()=>d??=new Af({...rg(n),depth:n.depth,sourceOrgId:n.source,targetOrgId:n.target,anonymizePII:n.anonymize,keepContactPoints:n.keepContactPoints,skipEmpty:!0,batchSize:"auto",excludedObjects:n.excludedObjects,...n.decisions},{reviewSkipped:!0}),l=new Map;l.set(n.source,pn(i)),l.set(n.target,pn(a));let u=new Map([...l].map(([y,T])=>[y,[oo(T)]])),p=y=>(u.get(y)??[]).reduce((T,F)=>T+F(),0),f,h=new Map,g,m=`sandforge-clone-${Es()}`,w,b=y=>{if(f===void 0||n.dryRun||n.listObjects||n.rehearse)return;let T=d?.fit();xs(n.audit,h,{action:"forge_execute",module:"forge",operationId:m,orgId:f,...y,...w?{muted:no(w)}:{},...T?{fit:T}:{}})},S;if(!n.dryRun&&!n.listObjects){let y=await on(l.get(n.target));S=y,f=y.id,h.set(y.id,{alias:n.target,username:a.username}),n.audit&&!n.rehearse&&(g=(await on(l.get(n.source))).id,h.set(g,{alias:n.source,username:i.username}));let T=zr(n.target,y,"clone");T&&(b({outcome:"stopped",code:"PRODUCTION_TARGET",context:c().context()}),process.stderr.write(`${T}
|
|
789
|
-
`),process.exit(1))}let R;if(o){let y=await on(l.get(n.source));R=y.id;let T=zr(n.source,y,"clone")!==void 0;T&&!n.anonymizeGiven&&(n={...n,anonymize:!0},n.files&&!n.files.acceptedAsIs&&(process.stderr.write(`--files: ${n.source} is a production org, whose personal data a clone of the whole org anonymizes unless --no-anonymize is given, and the content of a file cannot be anonymized: add --files-as-is to accept that files are copied as they are, give --no-anonymize, or leave out --files.
|
|
790
|
-
`),process.exit(2))),s(n.anonymize?`anonymize: on${T&&!n.anonymizeGiven?`, ${n.source} being a production org (--no-anonymize copies its personal data as it is)`:""}`:`anonymize: off, the personal data copied as ${n.source} holds it`)}if(!n.listObjects){let y=await os(n.ownerMappings,async T=>(await l.get(n.target).query(T)).records);if(y){b({outcome:"stopped",code:y.code,context:c().context()});let T={code:y.code,message:y.message};process.stderr.write(`${xt(T)}
|
|
791
|
-
`),n.json&&process.stdout.write(xn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:_r({target:p(n.target),source:p(n.source)},{})},T)),process.exit(1)}}let k=n.checkpointFirst?Yh({module:"forge",operationId:m,request:n.checkpointFirst,session:a,org:Jh(a,S??await on(l.get(n.target))),connect:y=>{let T=pn(y);return u.get(n.target)?.push(oo(T)),T},journalDir:qt(),say:s}):void 0,I=[...l.values()].map(oo),O=()=>I.reduce((y,T)=>y+T(),0),A={...rg(n),depth:n.depth,customDepth:n.depth==="custom"?n.customDepth:void 0,sourceOrgId:n.source,targetOrgId:n.target,anonymizePII:n.anonymize,skipEmpty:!0,batchSize:"auto",...(n.tables||o)&&Object.keys(n.objectSoqlFilters).length>0?{objectSoqlFilters:n.objectSoqlFilters}:{},...o&&n.excludedObjects.length>0?{excludedObjects:n.excludedObjects}:{}},x=new Il,j=new Set,E=Zy(async(y,T)=>{j.add(`${y}::${T}`);let F=l.get(y);if(!F)throw new Error(`No connection for ${y}`);return F.sobject(T).describe()}),$=new Map,L={describeObject:async(y,T)=>Qy(await E(y,T)),queryCount:async(y,T,F,N)=>{let C=l.get(y);if(!C)throw new Error(`No connection for ${y}`);return(await C.query(T,N?.all?{scanAll:!0}:void 0)).totalSize},detectPII:y=>vl(x,y),describeGlobal:y=>{let T=$.get(y);if(!T){let F=l.get(y);if(!F)throw new Error(`No connection for ${y}`);T=F.describeGlobal().then(N=>N.sobjects.map(C=>o?{name:C.name,keyPrefix:C.keyPrefix??null,queryable:C.queryable,createable:C.createable,updateable:C.updateable,deletable:C.deletable,customSetting:C.customSetting,layoutable:C.layoutable}:{name:C.name,keyPrefix:C.keyPrefix??null})),$.set(y,T)}return T},...o?{toolingObjects:async y=>{let T=l.get(y);if(!T)throw new Error(`No connection for ${y}`);return(await T.tooling.describeGlobal()).sobjects.map(F=>F.name)},recordCounts:async y=>{let T=l.get(y);if(!T)throw new Error(`No connection for ${y}`);return T.request(`/services/data/v${T.version}/limits/recordCount`)},createFacts:async y=>(await Gi(Ag(l,E,j),y)).facts}:{}},Q=await KR(n,L.describeGlobal),G=await HR(Q,n.target,{createable:async y=>(await E(n.target,y)).createable!==!1,whyNot:y=>cu((T,F)=>QR(l,T,F),async T=>(await Gi(Ag(l,E,j),T)).facts)(n.target,y)});G&&(b({outcome:"stopped",code:G.code,context:c().context()}),process.stderr.write(`${xt(G)}
|
|
792
|
-
`),n.json&&process.stdout.write(`${JSON.stringify({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,refused:G,elapsedMs:Fe(t)},null,2)}
|
|
793
|
-
`),process.exit(1));let V=(n.tables??[]).flatMap(({objectApiName:y})=>{let T=wy(y);return T!==void 0?[T]:[]});if(V.length>0){let y={code:qR,message:`${V.join(" ")} ${Ld}`};b({outcome:"stopped",code:y.code,context:c().context()}),process.stderr.write(`${xt(y)}
|
|
794
|
-
`),n.json&&process.stdout.write(xn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t)},y)),process.exit(2)}s("discovery\u2026");let q=new Ju(L),me={source:p(n.source),target:p(n.target)},de=o?await Ob(q,A,s):await q.discover(A,n.maxNodes===void 0?void 0:{maxNodes:n.maxNodes}),H={source:p(n.source)-me.source,target:p(n.target)-me.target};o&&s(Sb(H,n.source,n.target));let pe=o?void 0:de.nodes[0]?.objectApiName;pe!==void 0&&n.excludedObjects.includes(pe)&&(process.stderr.write(`${yn(`--exclude-object ${pe}`,`the resource's template leaves out ${pe}`)}: the ${n.tables?"first table":"record"} to clone is of this object, and nothing would be left to clone.
|
|
795
|
-
`),process.exit(2));let ue=n.tables?my(de,n.tables):[];ue.length>0&&(process.stderr.write(`${by(ue,{root:pe??n.tables?.[0]?.objectApiName??"",objects:de.nodes.length,depth:n.depth,customDepth:n.customDepth,truncated:de.truncated===!0,env:Zt()})}
|
|
796
|
-
`),process.exit(2));let be=n.tables?Sy(n,de):o?vy(n):A,ne=be.excludedObjects??n.excludedObjects,K=o?Ey(de,new Set(ne)):Gb(Lo(de,new Set(ne)),n.anonymizeFields),Z=new au().generate(K);if(s(o?bb(K,Z,n.source):yb(K,Z,n.maxNodes??Hu)),n.listObjects){let y=Ub(K),T=y.map(F=>` ${F.objectApiName.padEnd(42)}${String(F.recordCount).padStart(8)} depth ${F.depth}${F.included?"":" (excluded)"}`);s(`
|
|
797
|
-
objects in the graph (${K.nodes.length}):`),s(T.join(`
|
|
798
|
-
`)),K.truncated&&s(`
|
|
799
|
-
The graph was truncated: discovery stopped before it had walked everything. Raise --max-nodes if an object you need is missing.`),n.json&&process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"list-objects",source:n.source,target:n.target,...n.tables?{tables:n.tables}:o?{wholeOrg:!0}:{record:n.record},graph:As(K,Z),objects:y,...o?{leftOut:Jo(K)}:{},elapsedMs:Fe(t)},null,2)+`
|
|
800
|
-
`);return}let U=await sb(n.fieldExclusions,K,async y=>(await E(n.source,y)).fields.map(T=>T.name)),se=U.length>0?{code:Ad,message:lg(U,n.choicesFrom).replace(/ Nothing was read or written\.$/,"")}:void 0;if(se!==void 0&&!n.dryRun){b({outcome:"stopped",code:Ad,context:c().context()});let y={code:Ad,message:lg(U,n.choicesFrom)};process.stderr.write(`${xt(y)}
|
|
801
|
-
`),n.json&&process.stdout.write(xn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:_r({target:p(n.target),source:p(n.source)},{},o?H:void 0)},y)),process.exit(2)}se!==void 0&&s(` ${$n(se)}`);let Se=o?of(K):void 0;Se&&(b({outcome:"stopped",code:Se.code,context:c().context()}),process.stderr.write(`${xt(Se)}
|
|
802
|
-
`),n.json&&process.stdout.write(xn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:_r({target:p(n.target),source:p(n.source)},{},H)},Se)),process.exit(1));let ge=y=>(b({outcome:"stopped",code:y.code,context:c().context()}),process.stderr.write(`${xt(y)}
|
|
803
|
-
`),n.json&&process.stdout.write(xn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:_r({target:p(n.target),source:p(n.source)},{},H)},y)),process.exit(gg(y.code))),Te=qt(),De="",_;if(n.sample){let y=f??(await on(l.get(n.target))).id,T={...R?{sourceOrgId:R}:{}};De=Pa(K,cg(n,y,T)),await _p(Te,new Date).catch(()=>0);let F=n.sample.options.plan;if(F!==void 0)try{if(_=await er.open(F,{sourceOrgId:n.source,fingerprint:De}),_.ageMs(new Date)>=Np)throw new ss("gone","The plan of this sample is a day old or more.")}catch(N){let C=Qo(N,"replay");if(!C)throw N;ge({code:C.code,message:C.message.replace(/ Nothing was written\.$/,` Given: ${F}. Nothing was written.`)})}}let P=!n.dryRun&&!n.rehearse?Dt(Te):void 0,z=(y,T)=>cg(n,y,{...R?{sourceOrgId:R}:{},...T?{planSha256:T}:{}}),ee=f!==void 0?Pa(K,z(f,_?.sha256)):"",X,_e,M=n.muteAutomation;if(P&&f!==void 0&&n.resume){X=dg(n.resume,P);let y=f,T=await _y(P,X,{target:n.target,targetOrgId:f,graph:K,setup:z(f),sample:{asked:n.sample!==void 0,setupWith:N=>z(y,N)},config:be,...n.record?{record:n.record}:{}});T&&ge(T),_e=await P.lastEndAt(X),(await P.headAt(X))?.resume?.muteAutomation===!0&&(M=!0),s(`taking up the run of ${X}`);let F=await P.reconcileAt(X,Ia(l.get(n.target)));for(let N of Ea(F,n.target))s(N);$a(F)>0&&!n.writeUncertain&&ge({code:"RESUME_UNCERTAIN",message:Wy(F,n.target)})}let $e=new lf,ve=new AbortController,Ne={},ke,Tn=y=>{ke=y,process.stderr.write(`
|
|
804
|
-
interrupted: the clone stops after the call under way, and says what it created (Ctrl-C again ends it at once)
|
|
805
|
-
`),$e.stop(void 0,{discovery:()=>{},run:()=>{ve.abort(),Ne.executor?.abort()}})};if(!n.dryRun&&!n.rehearse&&!n.listObjects){$e.beginRun(m,ve);let y=qn(Tn);e.release=()=>{y(),$e.endRun(m)}}let Ht=async y=>{ve.signal.aborted&&(b({outcome:"stopped",code:yi,context:c().context()}),await y?.(),s("interrupted: the clone stopped before it wrote anything"),process.exit(yr(ke??"SIGINT")))},et=await Ls(l.get(n.target)).readForGraph(n.target,K,new Set(ne));s("");for(let y of mu(et,n.target,{applyAssignmentRules:n.applyAssignmentRules,mayMute:ht("--mute-automation"),mayApplyAssignmentRules:ht("--apply-assignment-rules")}))s(y);let gt=wc(et,new Set(ne));for(let y of _u(gt,n.target,et.unread,yn("--remove","destroy, or a replace")))s(y);s(n.keepContactPoints?`contact points: written as read (${yn("--keep-contact-points","keepContactPoints")})`:"contact points: neutralized before writing (emails under .invalid, phone numbers in a fictional range)");let pt=await qb(l,E,j).read(n.source,n.target,K,{inputMode:A.inputMode,recordId:A.recordId,maxRecordsPerObject:n.maxRecordsPerObject,fieldExclusions:n.fieldExclusions,fieldMappings:n.fieldMappings,excludedObjects:ne}),dn={...n.decisions,fieldExclusions:n.fieldExclusions,excludedObjects:ne},rt=Wu(K,{leftOut:new Set(ne),upsert:n.upsert}),ot=new Set(rt.map(y=>y.objectApiName)),Ye=(y,T)=>T==="insert"||T==="update"&&ot.has(y),Ae=M?Fl(et,Ye).plan.alsoLifts:void 0;s("");for(let y of pu(pt,n.target,{decisions:dn,...Ae?{lifted:Ae}:{}}))s(y);let mt=n.upsert&&!n.keepContactPoints?pb(await Promise.all(K.nodes.filter(y=>y.included).map(async({objectApiName:y})=>({objectApiName:y,fields:await E(n.source,y).then(T=>T.fields).catch(()=>[])})))):[];for(let y of fb(mt,n.target))s(y);let B,J,ie={},Re=()=>({apiRequests:_r({target:p(n.target),source:p(n.source)},ie,o?H:void 0)}),re=(y,T=[],F=1)=>{for(let N of[y,...T])process.stderr.write(`${xt(N)}
|
|
806
|
-
`);return n.json&&process.stdout.write(xn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),...Re()},y,T)),process.exit(F)};if(M){n.muteAutomation||s(" mute: the run taken up was muted, and so is this part of it");try{B=await Mi(async()=>Fi(l.get(n.target)),et,{writes:Ye});for(let y of Vn(B.muted,n.target))s(` ${y}`)}catch(y){if(!Ar(y))throw y;n.dryRun||(b({outcome:"stopped",code:y.code,context:c().context()}),re(y.refusal)),J=y.refusal,s(` ${$n(y.refusal)}`)}}let oe=B?.automation??et,Qe=Uu(oe,n.target,{updated:rt,assign:Xo(oe,Du(oe,rt.map(y=>y.objectApiName))),mayMute:!M&&ht("--mute-automation")});c().automationRead({automation:oe},rt),Qe&&n.acceptAutomation&&c().confirm("automation");let we=n.rehearse?void 0:await Cl({read:et,...B?.plan?{plan:B.plan}:{},writes:Ye,applyAssignmentRules:n.applyAssignmentRules,readDeliverability:async()=>{let y=l.get(n.target),T=S??await on(y);return zr(n.target,T,"clone")!==void 0?xl:Pl(y)},accepted:n.acceptEmails,target:n.target,run:"clone",keepsAddresses:n.keepContactPoints,mayMute:!M&&ht("--mute-automation")});we?.gate.line!==void 0&&s(` ${we.gate.line}`),c().emailsRead(we?.gate.audit),we?.gate.verdict==="asks"&&n.acceptEmails&&c().confirm("emails");let Be=we?.gate.stop,He=[...se!==void 0?[se]:[],...J!==void 0?[J]:[]],wt=Qe!==void 0&&!n.acceptAutomation;(wt||Be)&&!n.dryRun&&(b({outcome:"stopped",code:wt?"AUTOMATION_NOT_ACCEPTED":Mu,context:c().context()}),wt&&re({code:"AUTOMATION_NOT_ACCEPTED",message:Qe},Be?[Be]:[]),Be&&re(Be)),wt&&(He.push({code:"AUTOMATION_NOT_ACCEPTED",message:Qe}),s(" a real run would be refused (AUTOMATION_NOT_ACCEPTED): it writes nothing without --accept-automation: see what fires as it inserts and updates, or could not be read, above")),Be&&(He.push(Be),s(` ${$n(Be)}`)),await Ht(),s("record-type mapping\u2026");let _n=O(),An=[],At=await Xy(l.get(n.source),l.get(n.target),y=>An.push(y)),Kt=O()-_n;s(`record-types: ${At.length} mappings`);for(let y of An)s(` warning: ${y}`);await Ht();let Ft={statements:0,pages:0},tt=!1,cn=y=>(y.some(T=>T.success)&&(tt=!0),y),Xe=o?new df(async(y,T)=>(await Ii(ir(l,y)).bulk2.job("ingest",{id:T}).check()).state):void 0,jt={...o?JR(l,n,Xe,()=>tt=!0):{},queryRecords:async(y,T,F)=>{let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);let{records:C,truncated:te}=await Ti({query:async Ee=>N.query(Ee),queryMore:async Ee=>N.queryMore(Ee)},T,n.readCeiling);return te&&F?.(),C},queryPages:(y,T,F)=>{let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);return Ft.statements++,zc({query:async C=>(Ft.pages++,N.query(C)),queryAll:async C=>(Ft.pages++,N.query(C,{scanAll:!0})),queryMore:async C=>(Ft.pages++,N.queryMore(C))},T,F)},countRecords:async(y,T,F)=>{let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);return(await N.query(T,F?.all?{scanAll:!0}:void 0)).totalSize},queryTooling:async(y,T)=>{let F=l.get(y);if(!F)throw new Error(`No connection for ${y}`);return(await F.tooling.query(T)).records},insertRecords:async(y,T,F)=>{if(n.dryRun)return F.map(()=>({id:"",success:!0,errors:[]}));let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);let C=await N.sobject(T).create(F,{headers:ur({applyAssignmentRules:n.applyAssignmentRules})});return cn(vi(C,T))},updateRecords:async(y,T,F)=>{if(n.dryRun)return[];let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);let C=await N.sobject(T).update(F,{headers:ur({applyAssignmentRules:n.applyAssignmentRules})}),te=Array.isArray(C)?C:[C];return cn(te.map((Ee,Mt)=>({id:Ee.id??F[Mt].Id??"",success:Ee.success,errors:(Ee.errors??[]).map(gl),errorDetails:(Ee.errors??[]).map(hl)})))},describeFields:async(y,T)=>Yy(await E(y,T)),isObjectCreatable:async(y,T)=>(await E(y,T)).createable!==!1,describeObject:async(y,T)=>{let F=l.get(y);if(!F)throw new Error(`No connection for ${y}`);return kd(F,T)},describeObjectAgain:async(y,T)=>{let F=l.get(y);if(!F)throw new Error(`No connection for ${y}`);return kd(F,T,!0)},recordTypePicklists:async(y,T,F)=>{let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);return uf(N,T,F)},upsertRecords:async(y,T,F,N)=>{if(n.dryRun)return N.map(()=>({id:"",success:!0,errors:[]}));let C=l.get(y);if(!C)throw new Error(`No connection for ${y}`);let te=await C.sobject(T).upsert(N,F,{headers:ur({applyAssignmentRules:n.applyAssignmentRules})});return cn(vi(te,T))},readFileBody:async(y,T,F)=>{let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);return pf(N,T,F)},insertFile:async(y,T,F)=>{if(n.dryRun)return{id:"",success:!0,errors:[]};let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);let[C]=cn([await ff(N,T,F)]);return C},remainingFileStorageMB:async y=>{let T=l.get(y);if(!T)throw new Error(`No connection for ${y}`);return hf(T)},requestsSent:O,runningUser:async y=>{let T=l.get(y);if(!T)throw new Error(`No connection for ${y}`);return(await T.identity()).user_id}};if(n.rehearse){let y=l.get(n.target),T=ur({applyAssignmentRules:n.applyAssignmentRules});s(`
|
|
807
|
-
rehearsing\u2026 (the rows are read and prepared as the run would; nothing stays in the target)`);let F;try{F=await La({prepare:async C=>{await new sr(Ba(jt,C)).execute(K,n.source,n.target,()=>{},{...mg(n,K,At,te=>q.personalFields(te)),dryRun:!1,files:void 0})},keyPrefixOf:async C=>(await kd(y,C)).keyPrefix,runningUser:async()=>(await y.identity()).user_id,composite:C=>y.request({method:"POST",url:"/composite",body:JSON.stringify(C),headers:{"Content-Type":"application/json",...T}}),apiPath:`/services/data/v${y.version}`,writeHeaders:T,recordTypeNames:new Map(At.map(C=>[C.targetId.slice(0,15),C.developerName])),targetRecordTypes:Zh(jt,n.target),targetFields:C=>jt.describeFields(n.target,C),validationRules:async()=>jf(pt.gaps),confirm:async C=>{s("");for(let te of Kb(C,n.target))s(te)},onProgress:C=>{C.phase==="rehearsing"&&s(` call ${C.call} of ${C.calls}\u2026`)}})}catch(C){throw C instanceof vf&&(process.stderr.write(`${C.message}
|
|
808
|
-
`),process.exit(1)),C}let N=Fe(t);s("");for(let C of Vb(F,n.target,Ae?{lifted:Ae}:{}))s(C);n.json?process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"rehearse",source:n.source,target:n.target,...f?{targetOrgId:f}:{},record:n.record,graph:As(K,Z),targetAutomation:et,rehearsal:Jb(F,Ae),elapsedMs:N},null,2)+`
|
|
809
|
-
`):console.log(`
|
|
810
|
-
done in ${N}ms`);return}if(!n.skipPreflight){s(`
|
|
811
|
-
preflight (target row counts)\u2026`);let y=l.get(n.target),T=K.nodes.slice(0,30),F=[];for(let C of T)try{let te=await y.query(`SELECT COUNT() FROM ${C.objectApiName}`);F.push({name:C.objectApiName,existing:te.totalSize})}catch{F.push({name:C.objectApiName,existing:-1})}let N=F.filter(C=>C.existing>0);if(N.length===0)s(" target is empty for all sampled objects.");else{let C=N.sort((te,Ee)=>Ee.existing-te.existing).slice(0,10);s(` ${N.length}/${F.length} sampled objects have existing rows. Top 10:`);for(let te of C){let Ee=te.existing>1e3?" \u26A0":"";s(` ${te.name.padEnd(40)} ${String(te.existing).padStart(8)}${Ee}`)}K.nodes.length>T.length&&s(` (sampled first ${T.length}/${K.nodes.length} nodes; --skip-preflight to bypass)`)}}await Ht();let dt=l.get(n.target),yt,Ge,Vt=[],bt={},Un,jn,qr=async(y,T)=>{if(!k||T.totalRows===0)return;let F=new Set(T.objects.map(({objectApiName:C})=>C)),N={written:y.objects.map(({objectApiName:C})=>C).filter(C=>F.has(C)),running:{firing:wr(oe,void 0,Ye).firing}};try{Ge={ask:N,estimate:await k.scope(N)};return}catch(C){return Ji(C).replace(/ Nothing was written\.$/,"")}},Nt=y=>({unread:Y(y)}),ar=()=>({target:Math.max(0,p(n.target)-(we?.ofRun.read?.requests??0)),source:p(n.source)}),zs=async y=>{let T=y.wholeOrg;if(!T)throw new Error("A clone of the whole org reached its write gate without what it measured of both orgs, which its gate weighs it on. Nothing was written.");let F=vu(T.readWholeOver);if(F&&!y.dryRun)throw St.of({...F,message:fg(F.message,T.sample!==void 0)});let N=xu(y.objects,T),C=la({firing:wr(oe,void 0,Ye).firing},(ae,It)=>Ye(ae,It)).perRecord,te=T.sample?.report;te&&(jn=te,c().sampled(te));let Ee=await qr(y,N),Mt=[...ot],ct,vt,Ke,ft,Jt;if(y.dryRun)ct=await Pu({objects:y.objects,measures:T,graph:K,anonymizePII:n.anonymize,updatedAfterInsert:Mt,...Ge?{checkpoint:Ge.estimate}:{},...y.readBack!==void 0?{readBack:y.readBack}:{},mute:Po(B?.plan),deliverability:we?.ofRun.read?.requests??0,sentBefore:ar,...te?{sample:te}:{},automation:C,target:{org:n.target,limits:dt},source:{org:n.source,limits:ir(l,n.source)}}),vt=sf(ct),Ke=ct.storage,ft=ct.files,Jt=ct.wouldBeRefused;else{let ae=await Ko(dt).catch(Nt),It="unread"in ae?await Ir(dt).catch(Nt):ae.dailyApiRequests;Ke=Xi(N,ae,Eu(N,C));let Qr=ia(Ke,n.target),Xs=te?Nu({sample:te,storage:ae,target:n.target}):void 0,Zs=Iu(T.files,ae,n.target);ft=Zs.files;let sm=await Ir(ir(l,n.source)).catch(Nt),tc=ar(),lr=Qi({plan:N,updatedAfterInsert:Mt,...y.readBack!==void 0?{readBack:y.readBack}:{},...Ge?{checkpoint:Ge.estimate}:{},mute:Po(B?.plan),...sa(we?.ofRun),sentBefore:tc.target,budget:It,target:n.target,wholeOrg:{measures:T,bulkBatches:"unread"in ae?ae:ae.dailyBulkApiBatches,sourceBudget:sm,source:n.source,sourceSentBefore:tc.source}});vt={api:lr.api,wholeOrg:lr.wholeOrg},Jt=[...Xs?[Xs]:[],...Xs===void 0&&Qr!==void 0&&Ke.verdict==="exceeds"?[{code:"STORAGE_EXCEEDED",message:`${Qr} Nothing was written.`,storage:{estimateMB:Number(Xt(Ke.estimateMB)),remainingMB:Ke.remainingMB}}]:[],...Zs.stop?[Zs.stop]:[],...lr.stop?[lr.stop]:[],...lr.alsoRefused??[]]}let Yr=te?void 0:jb(Ke,n.target);Yr!==void 0&&(Jt=Jt.map(ae=>ae.code==="STORAGE_EXCEEDED"?{...ae,message:`${Yr} Nothing was written.`}:ae));let cr={...af({run:{source:n.source,graph:K,anonymizePII:n.anonymize,...Hr()},measures:T,plan:N,budget:vt,...ft?{files:ft}:{},...te?{sample:te,now:Date.now()}:{}}),discovery:H};if(ie={target:vt.api,source:vt.wholeOrg.source},Un={...ct?{dry:ct}:{},question:cr},s(""),te)for(let ae of Fb(te,{source:n.source,target:n.target,dryRun:y.dryRun===!0,replayed:n.sample?.options.plan!==void 0}))s(ae);for(let ae of aa(N,Ke,n.target))s(ae);for(let ae of kb(cr,Jo(K).counts,n.target,T.writes))s(ae);if(Ge)for(let ae of wd(Ge.estimate))s(ae);let Yt=ni(oe),xe;if(Yt.length>0){let ae=await Zi(dt).catch(Nt),It=ea(N,Yt,ae);for(let Qr of oa(It,n.target))s(Qr);xe=ra(It,n.target)}let Ve=na(oe,ta(N));Ve!==void 0&&s(` emails: not counted, ${Ve} could not be read`);let qe=ae=>fg(ae,te!==void 0).replace(/ Nothing was written\.$/,""),Ys=[...N.totalRows>n.maxTotal?[{code:"MAX_TOTAL_EXCEEDED",message:Ab(N.totalRows,n.maxTotal,te!==void 0)}]:[],...Ee!==void 0?[{code:mn,message:Ee}]:[],...Jt.map(ae=>({code:ae.code,message:ae.code===mn&&ae.refusal!==void 0?Ss(ae.refusal):qe(ae.message),stop:ae})),...xe!==void 0?[{code:"EMAILS_EXCEEDED",message:xe}]:[]];if(ct){for(let{code:ae,message:It}of Ys)s(` ${$n({code:ae,message:It})}`);throw He.push(...Ys.map(({code:ae,message:It})=>({code:ae,message:It}))),yt={totalRows:N.totalRows,storageBytes:N.storageBytes,objects:N.objects,...N.leftOut?{leftOut:N.leftOut}:{}},new Ca(ct)}let Qs=ae=>`${ae} Nothing was written.`,[zn,...om]=Ys;if(zn)throw Vt=om.map(({code:ae,message:It})=>({code:ae,message:Qs(It)})),zn.stop?St.of({...zn.stop,message:Qs(zn.message)}):new St(zn.code,Qs(zn.message));bt=ji(vt.api),await Gs(cr,N,te)},Hr=()=>{let y=rf(be);return y?{carried:y}:{}},Gs=async(y,T,F)=>{let N=Tb(y,T,n.target,F);if(n.yes){s(` --yes: written without the question: ${N}`),c().confirm("volume");return}if(process.stdin.isTTY!==!0)throw new St("CONFIRMATION_UNAVAILABLE",`A clone of the whole org asks before it writes ${N}, and no terminal is there to answer: give --yes to write it. Nothing was written.`);let C=await dp(`Write ${N}?`,void 0,ve.signal);if(ve.signal.aborted)throw new Ms("interrupted at its question: the clone stopped before it wrote anything");if(!C)throw new St("WRITE_DECLINED","The clone of the whole org was declined at its question. Nothing was written.");c().confirm("volume")},v=async y=>{if(o)return zs(y);let T=Su(y.objects),F;try{F=await Ko(dt)}catch(xe){F={unread:Y(xe)}}let N=Xi(T,F);s("");for(let xe of aa(T,N,n.target))s(xe);let C="unread"in F?await Ir(dt).catch(xe=>({unread:Y(xe)})):F.dailyApiRequests,te;if(k&&T.totalRows>0){let xe=new Set(T.objects.map(({objectApiName:qe})=>qe)),Ve={written:y.objects.map(({objectApiName:qe})=>qe).filter(qe=>xe.has(qe)),running:{firing:wr(oe,void 0,Ye).firing}};try{Ge={ask:Ve,estimate:await k.scope(Ve)}}catch(qe){te=Ji(qe).replace(/ Nothing was written\.$/,"")}}let Ee=Qi({plan:T,updatedAfterInsert:[...ot],...y.readBack!==void 0?{readBack:y.readBack}:{},...Ge?{checkpoint:Ge.estimate}:{},mute:Po(B?.plan),...sa(we?.ofRun),sentBefore:ar().target,budget:C,target:n.target});if(bt=ji(Ee.api),ie={target:Ee.api},s(cy(Ee.api,n.target)),Ge)for(let xe of wd(Ge.estimate))s(xe);let Mt=ni(oe),ct,vt;if(Mt.length>0){let xe=await Zi(dt).catch(qe=>({unread:Y(qe)})),Ve=ea(T,Mt,xe);for(let qe of oa(Ve,n.target))s(qe);ct=ra(Ve,n.target),vt=Ve.map(qe=>({limit:qe.limit,emails:qe.emails}))}let Ke=na(oe,ta(T));Ke!==void 0&&s(` emails: not counted, ${Ke} could not be read`);let ft=T.totalRows>n.maxTotal?lR(T.totalRows,n.maxTotal,n.dryRun):void 0,Jt=ia(N,n.target),Yr=te??(Ee.stop?.refusal!==void 0?Ss(Ee.stop.refusal):void 0),cr=Tu(Ee.api,n.target)?.replace(/ Nothing was written\.$/,""),Yt=[[mn,Yr],["MAX_TOTAL_EXCEEDED",ft],["STORAGE_EXCEEDED",Jt],["EMAILS_EXCEEDED",ct],[Vo,cr]].flatMap(([xe,Ve])=>Ve!==void 0?[{code:xe,message:Ve}]:[]);if(y.dryRun){for(let qe of Yt)s(` ${$n(qe)}`);He.push(...Yt);let xe=Be&&we?Bu(we.ofRun.senders,T):[],Ve=Lu(xe);Ve!==void 0&&s(Ve),yt={totalRows:T.totalRows,storageBytes:T.storageBytes,objects:T.objects,...T.leftOut?{leftOut:T.leftOut}:{},...vt!==void 0?{emails:vt}:{},...Ke!==void 0?{emailsUncounted:Ke}:{},...xe.length>0?{emailSendersOfNothingWritten:xe}:{}};return}if(Yt.length>0){let xe=Ve=>`${Ve} Nothing was written.`;throw Vt=Yt.slice(1).map(({code:Ve,message:qe})=>({code:Ve,message:xe(qe)})),new St(Yt[0].code,xe(Yt[0].message))}},D=n.dryRun||n.rehearse?void 0:await Sf(()=>dt.identity(),"sandforge clone");s(`
|
|
812
|
-
executing\u2026 (${n.dryRun?"DRY-RUN":"REAL"}${n.tables?", WHOLE TABLES":""}${o?", WHOLE ORG":""}${n.upsert?", UPSERT":""}${n.expandOrphans?", EXPAND-ORPHANS":""}${n.applyAssignmentRules?", ASSIGNMENT-RULES":""}${n.files?", FILES":""}${n.pageSize!==void 0?`, READ IN PAGES OF ${n.pageSize}`:""})`);let fe=y=>y.apiCalls===void 0?y:{...y,apiCalls:y.apiCalls+Kt},ce=(y,T,F={},N)=>({tool:"sandforge-clone",version:1,source:n.source,target:n.target,...f?{targetOrgId:f}:{},...n.tables?{objects:n.tables}:o?{wholeOrg:!0}:{record:n.record},dryRun:n.dryRun,upsert:n.upsert,expandOrphans:n.expandOrphans,applyAssignmentRules:n.applyAssignmentRules,files:n.files!==void 0,...n.choicesFrom?{choices:{from:n.choicesFrom.flag,file:n.choicesFrom.path,...n.decisions?{decisions:n.decisions}:{}}}:{},graph:As(K,Z),...jn?{sample:hg(jn)}:{},targetAutomation:we?.ofRun.read?{...et,deliverability:we.ofRun.read.reading}:et,...w?{mutedAutomation:w}:n.dryRun?Ni(B):{},...Re(),removalRisks:gt,targetGaps:Hi(pt,dn),...hb(n.dryRun,pt,y.gaps,Ae),...mt.length>0?{neutralizedUpsertKeys:mt}:{},result:{...N?{status:N}:{},...gb(y,n.readCeiling),...D?{runUserId:D}:{}},...n.dryRun&&yt!==void 0?{writePlan:yt}:{},...Hd(),...n.dryRun?si(He):{},elapsedMs:Fe(t,T.getTime()),finishedAt:T.toISOString(),...X&&ln?{journal:X}:{},...Hs()!==void 0?{part:Hs()}:{},...Vs.length>0?{bulkJobsPastMute:Vs}:{},...F}),Ie=y=>{let T=Un?.question;return{tool:"sandforge-clone",version:1,source:n.source,target:n.target,dryRun:!0,anonymize:n.anonymize,files:n.files!==void 0,graph:As(K,Z),result:{wouldInsertCount:yt?.totalRows??y.totalRows,failedCount:0},...yt!==void 0?{writePlan:yt}:{},targetAutomation:we?.ofRun.read?{...et,deliverability:we.ofRun.read.reading}:et,...Ni(B),removalRisks:gt,targetGaps:Hi(pt,dn),wholeOrg:{...y.sample?{sample:hg(y.sample)}:{},wouldInsert:y.wouldInsert,totalRows:y.totalRows,requests:{target:y.targetRequests,source:y.sourceRequests},...y.bulkBatches?{bulkBatches:y.bulkBatches}:{},storage:y.storage,...y.files?{files:y.files}:{},durationSeconds:y.durationSeconds,leftOut:y.leftOut,personalAsIs:y.personalAsIs,managedPackages:T?.managedPackages??[],...T?.contactPointsBlanked!==void 0?{contactPointsBlanked:T.contactPointsBlanked}:{},...T?.carried?{carried:T.carried}:{}},...Hd(),...Re(),...si(He),elapsedMs:Fe(t)}},Le,vn,Hd=()=>{let y=n.dryRun?Ge?.estimate:vn??Le;return y!==void 0?{checkpoint:y}:{}},qs=async()=>{if(!(!k||!Le||vn)){try{vn=await k.settle(Le,tt)}catch(y){vn=Le,s(`warning: the checkpoint '${Le.name}' taken before the run, which wrote nothing, could not be deleted (${Y(y)}): delete it with ${Qt("checkpoint")} delete --org ${n.target} --checkpoint ${Le.checkpointId}`)}for(let y of bd(vn))s(y)}},ln,Et;P&&f!==void 0&&(X&&n.resume?(await P.resumingAt(X),Et=(await P.headAt(X))?.journalId):(Et=`sandforge-clone-${new Date(t).toISOString().replace(/[:.]/g,"-")}-${Es().slice(0,8)}`,X=P.pathOf(Et),await P.begin(Et,f,new Date,{sourceOrgId:n.source,fingerprint:ee,targetSalesforceOrgId:f,...n.record?{recordId:n.record}:{},...n.muteAutomation?{muteAutomation:!0}:{},...n.files?{files:n.files}:{},startedWith:{graph:K,config:be}},D)),ln=P.openAt(X),s(Zt()?`journal: ${X}`:`journal: ${X} (--resume ${X} takes the run up if it stops)`));let Hs=()=>ln&&ln.partCount>0?ln.partCount-1:void 0,Xg=async()=>{if(!n.sample||n.dryRun||n.resume||Et===void 0)return;let y=ja(Te,Et);if(_&&Sn(y)&&!Sn(_.dir))try{jg(y,_.dir);return}catch{}await Dp(y)},dr=async(y,T)=>{if(!P||!X||!ln)return;ln.close();let F=X;try{!T&&_e?await P.stopAt(F,_e.status,_e.forgeId):!T&&!n.resume?($d(F,{force:!0}),$d(F.replace(/\.ndjson$/,".end.json"),{force:!0}),await Xg()):await P.stopAt(F,y,`${Et??"run"}#${Hs()??0}`)}catch(N){process.stderr.write(`The journal ${F} could not be ended (${Y(N)}).
|
|
813
|
-
`)}},Kd;if(n.sample){let y=n.sample,T=_;if(_&&!n.dryRun&&Et!==void 0)try{T=await Wp(_,Te,Et)}catch(C){await dr("failure",!1),process.stderr.write(`The plan of --fit-plan ${_.dir} could not be moved beside the run's journal (${Y(C)}): keep it in ${$s(Te,"forge-samples")}, where its dry run put it. Nothing was written.
|
|
814
|
-
`),process.exit(1)}if(T)s(`sample: takes up the plan ${T.dir}, drawn ${T.manifest.drawnAt}: no root is drawn again`);else if(n.resume)s("sample: the run taken up goes on with the plan its journal names");else{s(Bb(K,y.options,n.source));let C=n.dryRun?void 0:await Lp(Te,De,new Date).catch(()=>{});C instanceof er&&s(` a dry run drew a plan of this setup at ${C.manifest.drawnAt}: this run draws its own; --fit-plan ${C.dir} writes that one's records instead`)}let F=la({firing:wr(oe,void 0,Ye).firing},(C,te)=>Ye(C,te)).perRecord,N=T||n.resume?void 0:await Ir(ir(l,n.source)).catch(Nt);Kd={options:$g(y),budget:async()=>Ib({storage:await Ko(dt).catch(Nt),sample:y,target:n.target,automation:F}),keepAt:n.dryRun||Et===void 0?Mp(Te,De):ja(Te,Et),fingerprint:De,...T?{plan:T}:{},...N&&"remaining"in N?{sourceRequestsLeft:N.remaining}:{},onProgress:Db(s)}}let $t,Zg=wb(K),Ks=new sr(jt),Vd=!1,Kr=y=>{if(!n.summary)return;let T=Bd(n.summary,y);T&&!Vd&&(Vd=!0,process.stderr.write(`The summary could not be written to ${n.summary} (${T}).
|
|
815
|
-
`))},Jd=-1,em=()=>{let y=Ks.summarySoFar();if(!y)return;let T=y.successCount+y.linkedCount+y.updatedCount+y.failedCount;T!==Jd&&(Jd=T,Kr(ce(fe(y),new Date,{running:!0})))};Ne.executor=Ks,await Ht(()=>dr("cancelled",!1));let Vr,Vs=[],tm,Yd=()=>tm??=YR(Xe,n.target,s).then(y=>{Vs=y.map(({objectApiName:T,jobId:F})=>({objectApiName:T,...F?{jobId:F}:{}}))}),nm=async y=>{if(await v(y),y.dryRun||n.dryRun)return;if(k&&Ge&&!Le){let N=Ge,C=await ju(()=>k.take(N.ask,N.estimate,{signal:ve.signal}));if("stop"in C)throw C.stop.code!==mn?new Ns(yd(C.stop)):new St(mn,yd(C.stop));Le=C.checkpoint;for(let te of Qh(C.checkpoint,n.target,M))s(te)}if(!B?.prepared||Vr)return bt;let T=await B.prepared.acquire(`sandforge clone ${t}`).catch(async N=>{if(!Ar(N))throw N;return b({outcome:"stopped",code:N.code,context:c().context()}),await qs(),re(N.refusal)});Vr=T,w=T.outcome;let F=we?.afterLease(T.outcome,n.acceptEmails);if(F)throw new St(F.code,F.message);return{...bt,lease:{assigned:T.outcome.assigned.length,giveBack:async()=>(await Yd(),T.release())}}};try{let y=await Ks.execute(K,n.source,n.target,T=>{let F=Zg(T);F&&s(F),n.summary&&zR.has(T.status)&&em()},zb({...o?Iy(n,be,K,At,T=>q.personalFields(T),Kd):n.tables?Ty(n,be,K,At,T=>q.personalFields(T)):mg(n,K,At,T=>q.personalFields(T)),beforeWrite:nm},ln)).finally(async()=>{if(Vr){await Yd(),w=await Vr.release();for(let T of Vn(w,n.target))s(T)}});$t=fe(y),await qs(),n.pageSize!==void 0&&s(`read in pages of ${n.pageSize}: ${Ft.statements} statement(s) through the org's cursor, ${Ft.pages} page(s) answered`)}catch(y){if(y instanceof Ca){let ft=Ie(y.dryRun);n.json?process.stdout.write(`${JSON.stringify(ft,null,2)}
|
|
816
|
-
`):console.log(`
|
|
817
|
-
done in ${ft.elapsedMs}ms`),He.length>0&&process.exit(1);return}(y instanceof Ns||y instanceof Ms)&&(b({outcome:"stopped",code:yi,context:c().context()}),await dr("cancelled",!1),s(y.message),process.exit(yr(ke??"SIGINT"))),await qs();let T=y instanceof St?y:n.sample?Qo(y,n.resume?"resume":"draw"):void 0,F=y instanceof wn?y:void 0,N=T??F,C=N?void 0:$p(y),te=C?bi(C):void 0,Ee=te?Ri(te):[],Mt=ke!==void 0||y instanceof Oe,ct=N?"stopped":Mt?Mc(C,Ee):"failure";b({outcome:ct,...N?{code:N.code}:ct==="stopped"?{code:Nc}:{},...te?{objects:Ee,...g?{source:{origin:"org",orgId:g}}:{},carried:ki(te)}:{},...Oi(C?.contactPoints),context:c().context(C?.decisionsApplied)});let vt=C!==void 0&&C.successCount+C.updatedCount+C.linkedCount>0;if(await dr(Mt?"cancelled":"failure",vt),N){let ft={code:N.code,message:N.message,...T?.sample?{sample:T.sample}:{}};re(ft,T?Vt:[],gg(N.code))}let Ke=C;if(Ke&&(ke!==void 0||y instanceof Oe)){let ft=ce(fe(Ke),new Date,{interrupted:!0});if(Kr(ft),n.json)process.stdout.write(JSON.stringify(ft,null,2)+`
|
|
818
|
-
`);else{console.log("");for(let Jt of ug(Ke,n.dryRun,n.readCeiling))console.log(Jt)}s(GR(n.summary)),process.exit(yr(ke??"SIGINT"))}throw Ke&&Kr(ce(fe(Ke),new Date,{error:Y(y)})),y}finally{e.release?.()}await dr("success",!0);let Qd=bi($t),Jr=go($t);b({outcome:Jr,objects:Ri(Qd),...g?{source:{origin:"org",orgId:g}}:{},carried:ki(Qd),...Oi($t.contactPoints),context:c().context($t.decisionsApplied)});let Xd=new Date,rm=Fe(t,Xd.getTime()),Zd=ce($t,Xd,{},Jr);Kr(Zd);let Js;if(n.remapCsv){let y=["sourceId,targetId"];for(let[T,F]of Object.entries($t.remapTable))y.push(`"${T.replace(/"/g,'""')}","${F.replace(/"/g,'""')}"`);try{Ig(n.remapCsv,y.join(`
|
|
819
|
-
`)+`
|
|
820
|
-
`,{encoding:"utf8",flag:"wx"}),s(`remap-csv: wrote ${Object.keys($t.remapTable).length} mappings to ${n.remapCsv}`)}catch(T){Js=T?.code==="EEXIST"?`--remap-csv refuses to overwrite existing file: "${n.remapCsv}"`:`--remap-csv ${n.remapCsv} could not be written: ${Y(T)}`}}if(n.json)process.stdout.write(JSON.stringify(Zd,null,2)+`
|
|
821
|
-
`);else{console.log(""),console.log(`status: ${Jr}`);let y=(B?.plan?.assign.length??0)>0;for(let T of ug($t,n.dryRun,n.readCeiling,y))console.log(T);if($t.sample){console.log("");for(let T of Mb($t.sample,n.source))console.log(T)}console.log(`
|
|
822
|
-
done in ${rm}ms`)}Js!==void 0&&(process.stderr.write(`${Js}: the summary names what the run created.
|
|
823
|
-
`),process.exit(1));let ec=Oc(Jr,n.failOnPartial||o);ec!==0&&process.exit(ec)}function eO(r){return r instanceof Rc?{line:r.message,exitCode:1}:r instanceof Error&&r.message.startsWith("Invalid SF org alias:")?{line:r.message,exitCode:2}:{line:`FATAL: ${r instanceof Error?r.stack??r.message:String(r)}`,exitCode:1}}/sandforge-clone\.[cm]?[jt]s$/.test(process.argv[1]??"")&&(Pf(),XR().catch(r=>{let e=eO(r);process.stderr.write(`${e.line}
|
|
824
|
-
`),process.exit(e.exitCode)}));export{Da as a,nr as b,ht as c,bn as d,Fe as e,Dr as f,md as g,Kh as h,Vh as i,Jh as j,Yh as k,wd as l,Ss as m,yd as n,Qh as o,bd as p,$S as q,Rd as r,Xh as s,cy as t,fy as u,Dd as v,gy as w,my as x,wy as y,by as z,Ry as A,Oy as B,Sy as C,Ty as D,rg as E,Ay as F,jy as G,vy as H,Iy as I,Ey as J,$y as K,My as L,By as M,Wy as N,qt as O,dg as P,cg as Q,_y as R,Gy as S,Hy as T,Yy as U,Qy as V,Xy as W,Zy as X,kd as Y,RA as Z,tb as _,nb as $,Ad as aa,Pg as ba,ob as ca,lg as da,sb as ea,ib as fa,ug as ga,db as ha,cb as ia,lb as ja,ub as ka,pb as la,fb as ma,hb as na,gb as oa,mb as pa,wb as qa,yb as ra,bb as sa,kb as ta,Sb as ua,_r as va,Tb as wa,fg as xa,Ab as ya,Ib as za,Fb as Aa,hg as Ba,Nb as Ca,Mb as Da,Bb as Ea,Db as Fa,gg as Ga,_b as Ha,Ng as Ia,Ub as Ja,mg as Ka,zb as La,Gb as Ma,Ls as Na,qb as Oa,on as Pa,zr as Qa,Kb as Ra,Vb as Sa,Xb as Ta,Pd as Ua,eR as Va,OA as Wa,Cd as Xa,yg as Ya,nR as Za,qd as _a,rR as $a,oR as ab,sR as bb,Lg as cb,iR as db,cR as eb,lR as fb,sn as gb,vs as hb,gR as ib,vd as jb,yR as kb,bR as lb,Is as mb,Nd as nb,Gg as ob,RR as pb,OR as qb,kR as rb,Md as sb,kA as tb,SR as ub,TR as vb,Ds as wb,_s as xb,Us as yb,jR as zb,Hg as Ab,Kg as Bb,Vg as Cb,Jg as Db,IR as Eb,ER as Fb,Qg as Gb,Bd as Hb,$R as Ib,xR as Jb,PR as Kb,CR as Lb,Cs as Mb,BR as Nb,_R as Ob,UR as Pb,GR as Qb,Sg as Rb,Tg as Sb,qR as Tb,HR as Ub,JR as Vb,YR as Wb,XR as Xb,eO as Yb};
|