sandforge 1.84.1 → 1.86.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/lib/{chunk-S42RBRH2.mjs → chunk-22L43JMK.mjs} +1 -1
- package/lib/{chunk-Y2DRK37K.mjs → chunk-2LSGWTWX.mjs} +1 -1
- package/lib/{chunk-24RFOFYT.mjs → chunk-2YJJTQNC.mjs} +1 -1
- package/lib/chunk-34SMB5PA.mjs +10 -0
- package/lib/chunk-35B73566.mjs +7 -0
- package/lib/{chunk-3TZSBHEY.mjs → chunk-35IJ4WEU.mjs} +1 -1
- package/lib/chunk-3EHPAFKV.mjs +7 -0
- package/lib/{chunk-6YL7BNYD.mjs → chunk-3HAVVEXF.mjs} +1 -1
- package/lib/{chunk-6JWWSDM6.mjs → chunk-3I6FXFCN.mjs} +1 -1
- package/lib/{chunk-WUUKFE2U.mjs → chunk-3KJCSYXY.mjs} +1 -1
- package/lib/{chunk-2HVOZUM4.mjs → chunk-3L6DVNCR.mjs} +1 -1
- package/lib/chunk-3LRFPGYZ.mjs +7 -0
- package/lib/{chunk-GWZRR3MM.mjs → chunk-3MVWGL5A.mjs} +1 -1
- package/lib/{chunk-KGU4SVIT.mjs → chunk-4CSBZZAL.mjs} +1 -1
- package/lib/{chunk-JE6SCT6R.mjs → chunk-4NSXPONF.mjs} +1 -1
- package/lib/{chunk-UIOMAX56.mjs → chunk-4VLP6RHC.mjs} +1 -1
- package/lib/{chunk-YA6ATMTB.mjs → chunk-4XROG5CT.mjs} +1 -1
- package/lib/chunk-54V4FVEY.mjs +7 -0
- package/lib/chunk-55OJJT2Q.mjs +7 -0
- package/lib/{chunk-6QE6R6RL.mjs → chunk-5EHHQ5UX.mjs} +1 -1
- package/lib/{chunk-FITPY3L4.mjs → chunk-5JMQXHJ2.mjs} +1 -1
- package/lib/{chunk-W6PN6TJG.mjs → chunk-65AMXOQU.mjs} +1 -1
- package/lib/{chunk-3Q353S2R.mjs → chunk-6HHSAPIM.mjs} +1 -1
- package/lib/chunk-6KVBCFVS.mjs +7 -0
- package/lib/chunk-6NG7C2U3.mjs +476 -0
- package/lib/chunk-6ROL3KBM.mjs +7 -0
- package/lib/{chunk-2JDAOWUW.mjs → chunk-72AWCN7U.mjs} +1 -1
- package/lib/{chunk-JLSIWO4Z.mjs → chunk-7KHA5UIQ.mjs} +1 -1
- package/lib/chunk-7O6EFNQS.mjs +10 -0
- package/lib/{chunk-WWTCWWZI.mjs → chunk-A2CH2QGX.mjs} +1 -1
- package/lib/chunk-A2TXLAC3.mjs +276 -0
- package/lib/chunk-ALWVNR34.mjs +7 -0
- package/lib/{chunk-D4GF4FAB.mjs → chunk-ATBQIE2V.mjs} +1 -1
- package/lib/{chunk-NED4MBIM.mjs → chunk-ATQML7ZK.mjs} +1 -1
- package/lib/chunk-AVY742BJ.mjs +7 -0
- package/lib/{chunk-YWEQQL3C.mjs → chunk-AXTB2HJS.mjs} +1 -1
- package/lib/chunk-BBZUGKBZ.mjs +10 -0
- package/lib/chunk-BIDXK7KA.mjs +7 -0
- package/lib/{chunk-O677VOGO.mjs → chunk-BLMJ4WVI.mjs} +1 -1
- package/lib/{chunk-RE7RYF3B.mjs → chunk-BNHJCJJM.mjs} +1 -1
- package/lib/{chunk-5M5FQ7RP.mjs → chunk-BNPQEQXC.mjs} +1 -1
- package/lib/chunk-C5AUNG6T.mjs +37 -0
- package/lib/{chunk-ETDCBLGU.mjs → chunk-C5EQ7GFC.mjs} +1 -1
- package/lib/{chunk-MJZU3U5O.mjs → chunk-C7CKDZMC.mjs} +61 -61
- package/lib/{chunk-HCGXK7G7.mjs → chunk-CB4U22NR.mjs} +1 -1
- package/lib/chunk-CJAWKLAL.mjs +7 -0
- package/lib/chunk-CL75DEMQ.mjs +9 -0
- package/lib/{chunk-VCUXCK36.mjs → chunk-CLUNF4FK.mjs} +1 -1
- package/lib/chunk-CSMGP53U.mjs +7 -0
- package/lib/{chunk-7YNM6KFZ.mjs → chunk-CT324C7I.mjs} +1 -1
- package/lib/{chunk-7UVKIWKV.mjs → chunk-CZXDJXQP.mjs} +1 -1
- package/lib/{chunk-43TOMFV4.mjs → chunk-D2X6U3MS.mjs} +1 -1
- package/lib/{chunk-M6K34KGF.mjs → chunk-DAUX63UB.mjs} +1 -1
- package/lib/chunk-DB7JNALQ.mjs +10 -0
- package/lib/chunk-DDNCJVZ2.mjs +17 -0
- package/lib/{chunk-FP7CYB2F.mjs → chunk-DLSU66MY.mjs} +1 -1
- package/lib/{chunk-JKJ74BX5.mjs → chunk-DO6PSHQZ.mjs} +1 -1
- package/lib/{chunk-MDMPJEV3.mjs → chunk-DUBECLZV.mjs} +1 -1
- package/lib/{chunk-KZTZDC7H.mjs → chunk-DYHF6DNT.mjs} +1 -1
- package/lib/chunk-E5FSPXYH.mjs +930 -0
- package/lib/{chunk-Q7GIJBCD.mjs → chunk-EGL3I3IX.mjs} +1 -1
- package/lib/chunk-EIYMQPMG.mjs +7 -0
- package/lib/{chunk-RHNTHGNU.mjs → chunk-EUIALBMX.mjs} +1 -1
- package/lib/{chunk-NCZKWSC7.mjs → chunk-FI3R5ZOQ.mjs} +1 -1
- package/lib/{chunk-PAXNWTYK.mjs → chunk-FM4QCTO7.mjs} +1 -1
- package/lib/{chunk-HV7VPEXP.mjs → chunk-FRSIEASH.mjs} +1 -1
- package/lib/{chunk-QAFPQ3YB.mjs → chunk-FV6MOSHD.mjs} +1 -1
- package/lib/chunk-FYG47CNA.mjs +7 -0
- package/lib/chunk-GB6W4Q56.mjs +7 -0
- package/lib/chunk-GEV2DCMK.mjs +7 -0
- package/lib/{chunk-NSQWI7ZY.mjs → chunk-GFB2DNCB.mjs} +1 -1
- package/lib/chunk-GFGMGFSH.mjs +7 -0
- package/lib/{chunk-RGUQOSBU.mjs → chunk-GIFQXB2Q.mjs} +1 -1
- package/lib/{chunk-JAEDM4SI.mjs → chunk-GP5J3DGS.mjs} +1 -1
- package/lib/chunk-GQZEX7LH.mjs +231 -0
- package/lib/{chunk-JSAJS3MY.mjs → chunk-GYDTM62J.mjs} +1 -1
- package/lib/{chunk-OPMO6I45.mjs → chunk-GYFIXUJG.mjs} +1 -1
- package/lib/chunk-GZW2GNFK.mjs +7 -0
- package/lib/chunk-H6BHWAX7.mjs +8 -0
- package/lib/{chunk-EAC5QCE3.mjs → chunk-HDDJ3CVN.mjs} +1 -1
- package/lib/{chunk-5SMWFNE7.mjs → chunk-HDWB4ZOG.mjs} +1 -1
- package/lib/chunk-HGVPBJR6.mjs +7 -0
- package/lib/{chunk-BBRWFKS5.mjs → chunk-HLROVOR6.mjs} +1 -1
- package/lib/{chunk-LKTNQEBS.mjs → chunk-HUOR4M2L.mjs} +1 -1
- package/lib/chunk-HZCS6EED.mjs +8 -0
- package/lib/{chunk-36JOHEJL.mjs → chunk-HZUI56KZ.mjs} +1 -1
- package/lib/chunk-IAB5H7WN.mjs +7 -0
- package/lib/{chunk-X4BXESMQ.mjs → chunk-IQ5UKRHU.mjs} +1 -1
- package/lib/{chunk-54WZUS7J.mjs → chunk-IRQ4WANV.mjs} +1 -1
- package/lib/{chunk-5IZTFMJM.mjs → chunk-IT3DGX37.mjs} +1 -1
- package/lib/chunk-J347SPU6.mjs +49 -0
- package/lib/{chunk-QO53K5W2.mjs → chunk-JANBNTR5.mjs} +1 -1
- package/lib/chunk-JFXQZPRY.mjs +9 -0
- package/lib/{chunk-KAZS5Z6W.mjs → chunk-JRLYWVF4.mjs} +1 -1
- package/lib/{chunk-GKY2JMHY.mjs → chunk-JSNMUTY6.mjs} +1 -1
- package/lib/chunk-JTNJKSAA.mjs +7 -0
- package/lib/{chunk-7WATA4SB.mjs → chunk-JV2LAKWQ.mjs} +1 -1
- package/lib/{chunk-WAPSSYMT.mjs → chunk-JV7K2ZHK.mjs} +1 -1
- package/lib/{chunk-ZBAWJUG2.mjs → chunk-K4TQ7YHX.mjs} +1 -1
- package/lib/chunk-K5PUMHZU.mjs +7 -0
- package/lib/chunk-KH4KLCYG.mjs +7 -0
- package/lib/{chunk-OLCVHL7I.mjs → chunk-KQVLZVOP.mjs} +1 -1
- package/lib/chunk-KWUS7UAV.mjs +19 -0
- package/lib/{chunk-JGZPD4IM.mjs → chunk-L6G73FXM.mjs} +1 -1
- package/lib/{chunk-BAWCOKRW.mjs → chunk-LG466Q5H.mjs} +1 -1
- package/lib/{chunk-GMIGWR6U.mjs → chunk-LHNAR6FC.mjs} +1 -1
- package/lib/chunk-LT4GHEI2.mjs +7 -0
- package/lib/{chunk-EC72TIEG.mjs → chunk-MR262Y3B.mjs} +1 -1
- package/lib/{chunk-LA4KIATH.mjs → chunk-NCCHOV2N.mjs} +1 -1
- package/lib/chunk-NICRSGLS.mjs +7 -0
- package/lib/chunk-NV5QA2HY.mjs +7 -0
- package/lib/{chunk-PR3XCSPO.mjs → chunk-O3GIN5TU.mjs} +1 -1
- package/lib/chunk-O6FHK6NQ.mjs +13 -0
- package/lib/{chunk-M4BLK6HJ.mjs → chunk-O7YIEFG7.mjs} +1 -1
- package/lib/chunk-OCUVAA5E.mjs +7 -0
- package/lib/chunk-OLCS7JCT.mjs +14 -0
- package/lib/chunk-ON7Y63FK.mjs +9 -0
- package/lib/{chunk-N4WPCWJO.mjs → chunk-OO2WY3UB.mjs} +1 -1
- package/lib/{chunk-MSIEU5MR.mjs → chunk-OT2NHL2V.mjs} +1 -1
- package/lib/{chunk-6WX5ZU7Q.mjs → chunk-P2M5ZXWU.mjs} +1 -1
- package/lib/{chunk-GNRSF65U.mjs → chunk-P4YOHLZ4.mjs} +1 -1
- package/lib/chunk-PBHDPTT6.mjs +343 -0
- package/lib/chunk-PE7CHD2W.mjs +7 -0
- package/lib/{chunk-PBY2O6OF.mjs → chunk-PIQ2I67B.mjs} +1 -1
- package/lib/chunk-PKYDNZJK.mjs +7 -0
- package/lib/chunk-PVZ72OOQ.mjs +7 -0
- package/lib/chunk-QACFTHJM.mjs +8 -0
- package/lib/{chunk-J3DND3BC.mjs → chunk-QGVL5EW3.mjs} +1 -1
- package/lib/chunk-QHE2RUWX.mjs +7 -0
- package/lib/{chunk-QKEKG2LD.mjs → chunk-RCW5BZNW.mjs} +1 -1
- package/lib/{chunk-4JE4BYXK.mjs → chunk-RJ6HHG7J.mjs} +1 -1
- package/lib/{chunk-ZQWIVYVM.mjs → chunk-RPTEEI4R.mjs} +1 -1
- package/lib/chunk-RQW5S67A.mjs +7 -0
- package/lib/chunk-RTCMYMED.mjs +7 -0
- package/lib/chunk-RWVX7XSD.mjs +7 -0
- package/lib/{chunk-WY5V5PR3.mjs → chunk-RZOINFNL.mjs} +1 -1
- package/lib/chunk-SOOTWGMQ.mjs +7 -0
- package/lib/chunk-STQ2JMIZ.mjs +7 -0
- package/lib/{chunk-6PD6K7LP.mjs → chunk-SUIPDW5O.mjs} +1 -1
- package/lib/{chunk-TNT27RBG.mjs → chunk-SZOJ7BEJ.mjs} +1 -1
- package/lib/{chunk-4EOHEDFP.mjs → chunk-T542Z54E.mjs} +1 -1
- package/lib/chunk-TAN2CIRI.mjs +21 -0
- package/lib/{chunk-A3MYSOOC.mjs → chunk-TCNBINOG.mjs} +1 -1
- package/lib/chunk-TFDF3DBN.mjs +7 -0
- package/lib/chunk-TICZXC53.mjs +9 -0
- package/lib/chunk-TLX45X5U.mjs +7 -0
- package/lib/{chunk-QTG6LUZT.mjs → chunk-TMIV3IWH.mjs} +1 -1
- package/lib/chunk-TQ6HEJ73.mjs +11 -0
- package/lib/chunk-TTU5EQZ6.mjs +7 -0
- package/lib/chunk-TYUYPFDJ.mjs +7 -0
- package/lib/chunk-TZXYVMZC.mjs +7 -0
- package/lib/chunk-UCUFLFNK.mjs +7 -0
- package/lib/chunk-UK3QLBHW.mjs +7 -0
- package/lib/{chunk-IZGCEOYO.mjs → chunk-UM2B4GR7.mjs} +1 -1
- package/lib/chunk-UZFTTNOP.mjs +7 -0
- package/lib/chunk-V3AXSKSU.mjs +7 -0
- package/lib/chunk-VA6EEI6X.mjs +21 -0
- package/lib/{chunk-OFTT7J2M.mjs → chunk-VFKG2G37.mjs} +1 -1
- package/lib/chunk-VJNEW5MQ.mjs +7 -0
- package/lib/{chunk-L53JWJ3S.mjs → chunk-VKREON6Q.mjs} +1 -1
- package/lib/{chunk-NOBQTEQD.mjs → chunk-VNNDYPBL.mjs} +1 -1
- package/lib/{chunk-ZJW6YOMV.mjs → chunk-VRBETPHY.mjs} +1 -1
- package/lib/{chunk-EPFCERGL.mjs → chunk-VT6P3X6R.mjs} +1 -1
- package/lib/{chunk-ZV7ZFQQC.mjs → chunk-VUTQY76O.mjs} +1 -1
- package/lib/chunk-WF5S4FW5.mjs +7 -0
- package/lib/{chunk-Z4LKKOFY.mjs → chunk-WJGK6VGU.mjs} +1 -1
- package/lib/{chunk-5CRLRHOJ.mjs → chunk-WJHMB3SL.mjs} +1 -1
- package/lib/{chunk-OUZQPYT3.mjs → chunk-WQCXOZEJ.mjs} +1 -1
- package/lib/{chunk-L2E5WBGD.mjs → chunk-WVVFR4E3.mjs} +1 -1
- package/lib/{chunk-PWRJRL5U.mjs → chunk-XBYXT74L.mjs} +1 -1
- package/lib/chunk-XJE3LJHP.mjs +7 -0
- package/lib/{chunk-CPQIZGG5.mjs → chunk-XV4CVZYD.mjs} +1 -1
- package/lib/chunk-Y37ED7AS.mjs +7 -0
- package/lib/{chunk-YTLUYSMF.mjs → chunk-YGBNZYT4.mjs} +1 -1
- package/lib/{chunk-4CVUUVGJ.mjs → chunk-YGTOX7IL.mjs} +1 -1
- package/lib/{chunk-OMNMLKDT.mjs → chunk-YJ27WHKR.mjs} +1 -1
- package/lib/chunk-YRULC27A.mjs +7 -0
- package/lib/{chunk-RMFU4BAL.mjs → chunk-YSVAHT4Q.mjs} +4 -4
- package/lib/chunk-YTOTMJTY.mjs +15 -0
- package/lib/{chunk-B63POIPQ.mjs → chunk-YZKZC62O.mjs} +1 -1
- package/lib/{chunk-DPMRIMUC.mjs → chunk-YZQN7BRB.mjs} +1 -1
- package/lib/{chunk-7SQSWVAU.mjs → chunk-Z5IUK2QO.mjs} +1 -1
- package/lib/{chunk-M2ABR4JM.mjs → chunk-ZEGSMW5A.mjs} +1 -1
- package/lib/{chunk-PR42EZSR.mjs → chunk-ZIKLQZBG.mjs} +1 -1
- package/lib/chunk-ZVU7MD2S.mjs +7 -0
- package/lib/sandforge-autopilot.mjs +33 -27
- package/lib/sandforge-backup.mjs +19 -19
- package/lib/sandforge-checkpoint.mjs +1 -1
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +32 -14
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +11 -13
- package/lib/sandforge-env.mjs +105 -105
- package/lib/sandforge-frozen.mjs +1 -1
- package/lib/sandforge-mcp.mjs +2 -2
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +13 -13
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +13 -15
- package/lib/sandforge.mjs +1 -1
- package/lib/sf/sandforge/dataops.mjs +2 -2
- package/lib/sfPlugin.mjs +1 -1
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
- package/lib/chunk-23SEDORH.mjs +0 -11
- package/lib/chunk-26POJDIT.mjs +0 -7
- package/lib/chunk-2AZQHBEF.mjs +0 -7
- package/lib/chunk-2METQHGG.mjs +0 -7
- package/lib/chunk-2WFIVO4F.mjs +0 -13
- package/lib/chunk-2YHZBUZE.mjs +0 -7
- package/lib/chunk-326AJTIU.mjs +0 -272
- package/lib/chunk-3PVRGTVK.mjs +0 -7
- package/lib/chunk-5XTUSN72.mjs +0 -8
- package/lib/chunk-6I6TWNV5.mjs +0 -7
- package/lib/chunk-6O222PW6.mjs +0 -7
- package/lib/chunk-6ZLKIT3H.mjs +0 -7
- package/lib/chunk-7QYHEHMA.mjs +0 -9
- package/lib/chunk-B3FBHVNN.mjs +0 -21
- package/lib/chunk-BEA27DLS.mjs +0 -7
- package/lib/chunk-BRY3PLIZ.mjs +0 -7
- package/lib/chunk-CBH3TOWK.mjs +0 -341
- package/lib/chunk-CVHNXJH3.mjs +0 -7
- package/lib/chunk-DGDRQRCW.mjs +0 -7
- package/lib/chunk-DUN2EPRC.mjs +0 -7
- package/lib/chunk-E3A3LOCY.mjs +0 -7
- package/lib/chunk-F2424IKX.mjs +0 -7
- package/lib/chunk-F3AQW6IU.mjs +0 -7
- package/lib/chunk-FNJ4SGWO.mjs +0 -7
- package/lib/chunk-GOOVPVWX.mjs +0 -7
- package/lib/chunk-H2BHESDA.mjs +0 -9
- package/lib/chunk-H4CGM6YO.mjs +0 -7
- package/lib/chunk-HIDW7FNV.mjs +0 -9
- package/lib/chunk-HSBXRQTI.mjs +0 -7
- package/lib/chunk-HUZPBE47.mjs +0 -7
- package/lib/chunk-I6E6T6YY.mjs +0 -7
- package/lib/chunk-IUM4NFKI.mjs +0 -10
- package/lib/chunk-IVFVNNGB.mjs +0 -37
- package/lib/chunk-JCFBFF4Y.mjs +0 -7
- package/lib/chunk-JTJK2D36.mjs +0 -7
- package/lib/chunk-KB4ZHM4Q.mjs +0 -10
- package/lib/chunk-KJWFYBMU.mjs +0 -15
- package/lib/chunk-LC3NDW4N.mjs +0 -7
- package/lib/chunk-OM5NORJG.mjs +0 -7
- package/lib/chunk-OVNMB6Q2.mjs +0 -7
- package/lib/chunk-PEDQPM2P.mjs +0 -926
- package/lib/chunk-PH7SP4YK.mjs +0 -21
- package/lib/chunk-PMN4PAC3.mjs +0 -19
- package/lib/chunk-PMWAFDUB.mjs +0 -48
- package/lib/chunk-PPLVFX6N.mjs +0 -7
- package/lib/chunk-PZBZ7MNC.mjs +0 -7
- package/lib/chunk-QROPNEGY.mjs +0 -14
- package/lib/chunk-RGBGUCJA.mjs +0 -156
- package/lib/chunk-RKTFFCNS.mjs +0 -7
- package/lib/chunk-ROV3QXEF.mjs +0 -475
- package/lib/chunk-RT47RKLY.mjs +0 -7
- package/lib/chunk-SI267LYR.mjs +0 -8
- package/lib/chunk-SRPWW4A2.mjs +0 -10
- package/lib/chunk-T3G6VZNS.mjs +0 -7
- package/lib/chunk-T63U4OZJ.mjs +0 -7
- package/lib/chunk-TEIBWMJM.mjs +0 -7
- package/lib/chunk-TW3N6W5Z.mjs +0 -7
- package/lib/chunk-UBIKR5VO.mjs +0 -7
- package/lib/chunk-UI3JQVRU.mjs +0 -8
- package/lib/chunk-UX3BVH2Y.mjs +0 -7
- package/lib/chunk-VINGECAJ.mjs +0 -10
- package/lib/chunk-VOXJHJIE.mjs +0 -7
- package/lib/chunk-WB2RIVO3.mjs +0 -7
- package/lib/chunk-WXDLQT2O.mjs +0 -10
- package/lib/chunk-XBQGZGWR.mjs +0 -7
- package/lib/chunk-XGGOUNPP.mjs +0 -7
- package/lib/chunk-XKWW3GKF.mjs +0 -7
- package/lib/chunk-YHR4WQPR.mjs +0 -7
- package/lib/chunk-ZQQXSCVI.mjs +0 -7
- package/lib/chunk-ZRUDYB7O.mjs +0 -7
package/lib/chunk-6I6TWNV5.mjs
DELETED
|
@@ -1,7 +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{c as gt,d as Ns,e as xs,f as ht}from"./chunk-QAFPQ3YB.mjs";import{b as mt,c as yt,d as nn,e as rn,f as Ks,g as sn}from"./chunk-4EOHEDFP.mjs";import{b as Hs,d as Ys}from"./chunk-JKJ74BX5.mjs";import{a as Js,c as Vs}from"./chunk-PR42EZSR.mjs";import{a as ze,b as Ds,c as Ls,d as $s,f as Bs,g as _s,h as Ws,i as Gs,j as Us,l as Q,n as en,o as tn,p as zs,q as qs,s as qe}from"./chunk-UX3BVH2Y.mjs";import{Dc as Lr}from"./chunk-XGGOUNPP.mjs";import{a as ve,c as Zt}from"./chunk-BOGNK4LV.mjs";import{G as ys,H as ws,Ha as ks,Ia as Os,M as Ss,N as bs,P as Rs,Pa as As,Qa as Cs,Ra as Ps,Sa as Is,Ta as Es,Va as Ts,Wa as Ms,Ya as Fs,ab as js,bb as vs,h as fs,j as Qt}from"./chunk-IVFVNNGB.mjs";import{k as ms}from"./chunk-6JWWSDM6.mjs";import{j as $r,p as qr}from"./chunk-VINGECAJ.mjs";import{F as xr,M as Dr,l as Vt,q as Nr}from"./chunk-H4CGM6YO.mjs";import{l as gs,m as hs}from"./chunk-TEIBWMJM.mjs";import{l as Ir}from"./chunk-YDXMTWAT.mjs";import{f as Kr,h as Hr,i as Ue,k as Yr}from"./chunk-26POJDIT.mjs";import{a as Xt}from"./chunk-QSRAEUGZ.mjs";import{h as Ur,j as zr}from"./chunk-FP7CYB2F.mjs";import{b as Yt,c as Ge,d as ee}from"./chunk-JAEDM4SI.mjs";import{f as Br,g as _r}from"./chunk-LC3NDW4N.mjs";import{Hb as Ne,Ib as pt,Jb as ft,Kc as ps,Ya as Vr,Za as Xr,ec as ss,gb as Zr,hb as Qr,hc as is,ic as os,j as Wr,jb as we,kc as as,lb as dt,mb as es,nb as ct,o as Gr,ob as ts,oc as ds,pb as ns,pc as cs,qb as lt,rb as ut,tb as rs,uc as ls,vc as us,wc as xe}from"./chunk-KB4ZHM4Q.mjs";import{q as Jr}from"./chunk-3Q353S2R.mjs";import{b as Zn,f as Qn}from"./chunk-INIT2UKJ.mjs";import{a as kr,d as Or,e as Ar,f as Cr,g as Pr}from"./chunk-D4GF4FAB.mjs";import{a as Er,b as at,d as Tr,e as Mr,f as Fr,g as jr,h as vr}from"./chunk-CVHNXJH3.mjs";import{A as Pe,B as gr,C as qt,D as ot,E as Kt,G as Ht,H as hr,I as mr,J as je,n as rr,o as Fe,q as sr,r as ir,s as or,t as ar,u as dr,v as cr,w as lr,y as fr,z as We}from"./chunk-YA6ATMTB.mjs";import{a as er}from"./chunk-EADHKH3A.mjs";import{F as X,G as oe,I as zt,N as Vn,P as Xn,f as it,g as Yn,m as Jn,r as Ut}from"./chunk-TNT27RBG.mjs";import{f as Hn,h as ye}from"./chunk-TZE3Y7IQ.mjs";import{b as K}from"./chunk-CA5NAXSU.mjs";import{c as yr,d as wr,f as Sr,h as br,j as Rr,k as Jt}from"./chunk-S42RBRH2.mjs";import{a as tr,w as nr}from"./chunk-ICIYL45C.mjs";import{c as ur,d as pr}from"./chunk-WUUKFE2U.mjs";import{Ec as Me,Fc as ge,Jc as nt,Rd as Kn,Uc as rt,Vb as Ln,Wb as et,Zc as Bn,ee as Gt,fd as st,g as xn,gc as $n,i as Wt,j as Dn,k as fe,kd as _n,ld as Wn,md as Gn,nd as Un,od as zn,pd as qn,vc as tt}from"./chunk-PMWAFDUB.mjs";import{b as _e,k as $t,l as Bt,u as vn,v as Nn,z as _t}from"./chunk-WZQEK4WT.mjs";var wt=class{classify(e){let t=et(e.statusCode),r=this.getSuggestedAction(e.statusCode,t);return{originalError:e,classification:t,suggestedAction:r}}classifyBatch(e){let t=e.map(a=>this.classify(a)),r={auth:0,permission:0,schema:0,data:0,validation:0,limit:0,network:0,trigger:0,reference:0,unknown:0},s={},i=0;for(let a of t){a.classification.retryable&&i++;let d=a.classification.category??"unknown";r[d]=(r[d]??0)+1,s[a.originalError.statusCode]=(s[a.originalError.statusCode]??0)+1}let o={totalErrors:e.length,retryableCount:i,nonRetryableCount:e.length-i,byCategory:r,byErrorCode:s,sampleErrors:e.slice(0,5)};return{classified:t,summary:o}}isRetryable(e){return et(e).retryable}hasBlockingError(e){return e.some(t=>et(t.statusCode).blockAll===!0)}get knownErrorCount(){return Object.keys(Ln).length}getSuggestedAction(e,t){return t.suggestUpsert?"Consider using upsert with external ID":t.suggestTruncate?"Truncate field values to fit within limits":t.blockAll?"Operation blocked: resolve storage/limit issue first":t.strategy==="reauth_then_retry"?"Re-authenticate and retry":t.strategy==="reduce_batch"?"Reduce batch size and retry":t.retryable?`Retry after ${t.delay??0}ms`:`Fix ${e} error and retry manually`}};function to(n,e){return new Promise(t=>{if(e?.aborted){t();return}let r=()=>{clearTimeout(s),e?.removeEventListener("abort",r),t()},s=setTimeout(r,n);e?.addEventListener("abort",r,{once:!0})})}var St=class{constructor(e={}){this.options=e;this.strategy=new Er({...e.retryConfig,jitter:e.retryConfig?.jitter??!0}),this.classifier=new wt}options;strategy;classifier;async execute(e){let t=this.strategy.getConfig(),r,s=0;for(let i=0;i<=t.maxRetries;i++)try{return{success:!0,result:await e(),attempts:i+1,totalDelay:s}}catch(o){r=o instanceof Error?o:new Error(String(o));let a=no(o),d=this.classifier.classify(a);if(!d.classification.retryable)return{success:!1,error:r,attempts:i+1,totalDelay:s};if(i<t.maxRetries){let c={success:!1,error:r,attempts:i+1,totalDelay:s,cancelled:!0};if(this.options.signal?.aborted)return c;let l=this.strategy.calculateDelay(i);if(this.options.onRetry?.(i,d,l),s+=l,await to(l,this.options.signal),this.options.signal?.aborted)return{...c,totalDelay:s}}}return{success:!1,error:r,attempts:t.maxRetries+1,totalDelay:s}}async executeBatch(e,t){let r=[...e],s=[],i=[],o=0,a=this.options.retryConfig?.maxRetries??3;for(;r.length>0&&o<=a;){let d=await t(r);s.push(...d.successes);let c=[];for(let l of d.failures)this.classifier.classify(l.error).classification.retryable&&o<a?c.push(l.record):i.push(l);if(r=c,r.length>0){let l=this.options.retryConfig?.initialDelay??1e3,u=this.options.retryConfig?.maxDelay??3e4,f=l*Math.pow(2,o);await new Promise(p=>setTimeout(p,Math.min(f,u))),o++}}return{successes:s,failures:i}}getClassifier(){return this.classifier}getStrategy(){return this.strategy}};function no(n){if(typeof n!="object"||n===null)return{statusCode:"UNKNOWN_ERROR",message:String(n)};let e=n,t=[e.errorCode,e.statusCode,e.name].find(s=>typeof s=="string"&&s.length>0&&s!=="Error"),r=e.fields??e.data?.fields;return{statusCode:t??"UNKNOWN_ERROR",errorCode:typeof e.errorCode=="string"?e.errorCode:void 0,message:typeof e.message=="string"?e.message:String(n),fields:Array.isArray(r)?r.filter(s=>typeof s=="string"):void 0}}var ro=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function so(n){if(n===!0||n==="true")return!0;if(n===!1||n==="false")return!1}async function io(n,e,t,r=()=>Date.now()){let s=await Ir(n,e,{now:r,successfulOnly:!0});return s.state==="running"?{state:"running"}:s.state!=="ended"?s:{state:"ended",created:(s.results.successfulResults??[]).flatMap(o=>{let a=o.sf__Id;return typeof a!="string"||!ro.test(a)?[]:t&&so(o.sf__Created)!==!0?[]:[a]}),...typeof s.info.systemModstamp=="string"?{at:s.info.systemModstamp}:{}}}async function md(n,e,t,r,s=()=>new Date){let i,o=()=>(i??=(async()=>{if(!r)return 0;try{let d=s().getTime(),c=Date.parse(await r());return Number.isFinite(c)?c-(d+s().getTime())/2:0}catch{return 0}})(),i),a=[];for(let d of e.jobs??[]){if(d.job===void 0)continue;let c={job:d.job,objectApiName:d.objectApiName},l=await io(t,d.job,d.upsert===!0,()=>s().getTime());if(l.state==="running"||l.state==="unread"){a.push({...c,read:l,answered:!1});continue}let u=s().toISOString();l.state==="ended"&&l.at!==void 0&&Number.isFinite(Date.parse(l.at))?u=new Date(Date.parse(l.at)-await o()).toISOString():e.lastWrittenAt!==void 0&&(u=e.lastWrittenAt);let f=l.state==="ended"?l.created:[],p=await n.answerInFlight(e.runId,d.objectApiName,f,u,d.job);a.push({...c,read:l,answered:p})}return a}function yd(n,e){return e.map(({job:t,read:r})=>{let s=`${n}, job ${t}`;switch(r.state){case"ended":return`[INFO] ${s}: the job no line of the run answered ended in the org; ${r.created.length} record(s) it created kept with the run`;case"never-closed":return`[INFO] ${s}: the job was never closed, and wrote nothing`;case"running":return`[INFO] ${s}: the job is still running in the org; read again later`;default:return`[WARN] ${s}: the job could not be read back: ${r.reason}`}})}var Le=5e3,an=200,bt=_e().refine(n=>Ge(n),"not a record id"),oo=Bt({sourceOrgId:_e().min(1).max(200),targetOrgId:_e().min(1).max(200),objectApiName:_e().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),kind:vn(["document","attachment"]),sourceId:bt,targetId:bt,sourceVersionId:bt.optional(),sourceModifiedAt:_t.datetime().optional(),linked:$t(bt).max(an),copiedAt:_t.datetime()}),ao=Bt({version:Nn(1),entries:$t(oo).max(Le)});function Zs(n){if(n==null)return{kind:"none"};let e=ao.safeParse(n);if(e.success)return{kind:"stored",map:e.data};let t=e.error.issues[0];return{kind:"unreadable",issue:`${t.path.join(".")||"map"}: ${t.message}`}}function Td(n,e,t){return n?n.check({orgId:e,orgTier:Bn(t),operation:"delete",objectName:"Attachment",recordCount:1,module:"sync"}).allowed:!1}var ue=class extends Error{constructor(e){super(e),this.name="SyncFilesRefusedError"}},Ke=class extends Error{};function co(){return{copied:0,versions:0,bytes:0,links:0,unchanged:0,tooLarge:0,pastRunCap:0,external:0,recordNotWritten:0,failed:0}}function te(n,e){let t=n[e];return typeof t=="string"&&t!==""?t:void 0}function Rt(n,e){let t=n;for(let r of e.split(".")){if(typeof t!="object"||t===null)return null;t=t[r]}return Kt(t)}function De(n,e){return e==null?n:n===void 0||Date.parse(e)>Date.parse(n)?e:n}function lo(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0}function He(n,e,t){return`${n}|${e}|${t}`}function uo(n,e){let t=e.load(n.id);if(t===null)throw new ue("Files are copied by a saved configuration only: it keeps which file it copied where, so that running it again copies none of them twice. Save the configuration, then run it. Nothing was read or written.");if(t.kind==="unreadable")throw new ue(`The record of the files this configuration copied could not be read (${t.issue}), so a run could copy them a second time. Turn the files off, or save the configuration again under a new name. Nothing was read or written.`);let r=new Map;if(t.kind==="stored")for(let s of t.map.entries)r.set(He(s.sourceOrgId,s.targetOrgId,s.sourceId),s);return r}var on="ContentDocument.LatestPublishedVersion.SystemModstamp";async function po(n,e,t,r){let s=rt(t.objectApiName),i=t.where?.trim()?` WHERE (${Hn(t.where)})`:"",o=`SELECT Id FROM ${s}${i}`,a=qt(r),d=new Set,c,l=await n.copy.queryRecords(e.sourceOrgId,`SELECT LinkedEntityId, SystemModstamp, ${on} FROM ContentDocumentLink WHERE LinkedEntityId IN (${o}) AND (SystemModstamp > ${a} OR ${on} > ${a})`);for(let f of l){let p=te(f,"LinkedEntityId");p&&Ge(p)&&d.add(p),c=De(De(c,Rt(f,"SystemModstamp")),Rt(f,on))}let u=await n.copy.queryRecords(e.sourceOrgId,`SELECT ParentId, LastModifiedDate FROM Attachment WHERE ParentId IN (${o}) AND LastModifiedDate > ${a}`);for(let f of u){let p=te(f,"ParentId");p&&Ge(p)&&d.add(p),c=De(c,Rt(f,"LastModifiedDate"))}return{ids:[...d],...c!==void 0?{newest:c}:{}}}async function fo(n,e,t){let r=new Map;for(let s of ee(t)){let i=await n.copy.queryRecords(e.sourceOrgId,`SELECT Id, LastModifiedDate FROM Attachment WHERE Id IN (${s})`);for(let o of i){let a=te(o,"Id"),d=Kt(o.LastModifiedDate);a&&d&&r.set(a,d)}}return r}function go(n,e,t){return e===void 0||n.targetId===n.sourceId?!1:n.sourceModifiedAt!==void 0?n.sourceModifiedAt!==e:t!==void 0&&Date.parse(e)>Date.parse(t)}async function ho(n,e,t,r,s,i){let o=[...s.values()].filter(l=>l.kind==="document"&&l.objectApiName===t&&l.sourceOrgId===e.sourceOrgId&&l.targetOrgId===e.targetOrgId&&!i.has(l.sourceId)).map(l=>l.sourceId),a=qt(r),d=[],c;for(let l of ee(o)){let u=await n.copy.queryRecords(e.sourceOrgId,`SELECT Id, ContentDocumentId, Title, PathOnClient, ContentSize, ContentLocation, SystemModstamp FROM ContentVersion WHERE ContentDocumentId IN (${l}) AND IsLatest = true AND SystemModstamp > ${a}`);for(let f of u){c=De(c,Rt(f,"SystemModstamp"));let p=te(f,"ContentDocumentId"),h=te(f,"Id");if(!p||!h||(te(f,"ContentLocation")??"S")!=="S")continue;let y=te(f,"Title")??p;d.push({objectApiName:"ContentDocument",sourceId:p,body:{objectApiName:"ContentVersion",id:h},name:y,bytes:lo(f,"ContentSize"),hosts:[],fields:{Title:y,PathOnClient:te(f,"PathOnClient")??y}})}}return{files:d,...c!==void 0?{newest:c}:{}}}async function mo(n,e,t,r){let s=new Map,i=new Date().toISOString(),o=(l,u,f)=>({sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:t,kind:l,sourceId:u,targetId:u,linked:[],copiedAt:i,...f}),a=r.filter(l=>l.objectApiName==="ContentDocument").map(l=>l.sourceId);for(let l of ee(a)){let u=await n.copy.queryRecords(e.targetOrgId,`SELECT Id, LatestPublishedVersionId FROM ContentDocument WHERE Id IN (${l})`);for(let f of u){let p=te(f,"Id");if(!p)continue;let h=te(f,"LatestPublishedVersionId");s.set(p,o("document",p,h?{sourceVersionId:h}:{}))}}let d=[...s.keys()];for(let l of ee(d)){let u=await n.copy.queryRecords(e.targetOrgId,`SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN (${l})`);for(let f of u){let p=te(f,"ContentDocumentId"),h=te(f,"LinkedEntityId"),y=p?s.get(p):void 0;y&&h&&Ge(h)&&y.linked.length<an&&y.linked.push(h)}}let c=r.filter(l=>l.objectApiName==="Attachment").map(l=>l.sourceId);for(let l of ee(c)){let u=await n.copy.queryRecords(e.targetOrgId,`SELECT Id FROM Attachment WHERE Id IN (${l})`);for(let f of u){let p=te(f,"Id");p&&s.set(p,o("attachment",p,{}))}}return s}async function Qs(n){let{config:e,option:t,objects:r,deps:s}=n,i=uo(e,s.store),o;try{o=await Ss(s.copy,e.targetOrgId)}catch(p){throw new ue(`The file storage the target has left could not be read (${K(p)}), so the files could not be measured against it. Nothing was written.`)}let a=t.maxFileSizeMB*1048576,d=t.maxRunMB*1048576,c=0,l=0,u=new Set,f={objects:new Map,storage:{remainingBytes:o,plannedBytes:0}};for(let{objectConfig:p,changedSince:h,filesSeen:y}of r){if(p.operation==="delete")continue;let m=p.objectApiName,b=await s.sourceIds(p,h),S=[],R=h===void 0?void 0:y!==void 0&&Date.parse(y)>Date.parse(h)?gr(y):h,k=h===void 0?void 0:y,g=new Map;if(R!==void 0)try{let j=new Set(b),x=await po(s,e,p,R);k=De(k,x.newest);let _=x.ids.filter(z=>!j.has(z));if(_.length>0){let z=n.tie?await n.tie(p,_):{held:new Map};g=z.held;let H=_.filter(G=>!g.has(G)).length;H>0&&S.push(`${H} record(s) whose files changed since the last run, and nothing else of them, could not be tied to their copy in the target`+(z.refused?` (${z.refused})`:"")+": their new files are copied when the record changes, or on a full read.")}}catch(j){throw new ue(`${m}: the files its records gained since the last run could not be looked up (${K(j)}). Run it again, or turn the files off. Nothing was written.`)}let w=[...b,...g.keys()],M=await ys({scope:new Map([[m,w]]),sourceOrgId:e.sourceOrgId,maxFileBytes:a,queryRecords:s.copy.queryRecords});if(ws(M)){let j=new Set(M.errors.flatMap(x=>x.samples.flatMap(_=>_.messages)));throw new ue(`${m}: the files of its records could not all be looked up in the source (${[...j].join("; ")}). Run it again, or turn the files off. Nothing was written.`)}let A=co();for(let j of M.leftOut)j.reason==="too-large"?A.tooLarge++:j.reason==="external"&&A.external++;A.tooLarge>0&&S.push(`${A.tooLarge} file(s) larger than ${t.maxFileSizeMB} MB were not copied.`);let O=M.files,E=[],F=new Map;try{if(R!==void 0){let _=new Set(O.map(H=>H.sourceId)),z=await ho(s,e,m,R,i,_);k=De(k,z.newest);for(let H of z.files)H.bytes>a?A.tooLarge++:O=[...O,H]}let j=O.filter(_=>!i.has(He(e.sourceOrgId,e.targetOrgId,_.sourceId)));if(j.length>0)for(let[_,z]of await mo(s,e,m,j))i.set(He(e.sourceOrgId,e.targetOrgId,_),z),E.push(z);let x=O.filter(_=>_.objectApiName==="Attachment");x.length>0&&(F=await fo(s,e,x.map(_=>_.sourceId)))}catch(j){throw new ue(`${m}: the files an earlier run copied could not be looked up (${K(j)}), so a run could copy them twice. Nothing was written.`)}let N=[],$=new Map,T=0,v=0;for(let j of O){if(u.has(j.sourceId)){A.unchanged++,N.push(j);continue}let x=i.get(He(e.sourceOrgId,e.targetOrgId,j.sourceId)),_=x?.kind==="attachment"&&go(x,F.get(j.sourceId),h);if(_&&!s.deleteFromTarget){v++;continue}if(x&&!_&&(x.kind==="attachment"||x.sourceVersionId===j.body.id)){A.unchanged++,x.kind==="document"&&N.push({...j,into:{documentId:x.targetId,linked:x.linked,unchanged:!0}});continue}if(!x&&l>=Le-i.size){T++,A.pastRunCap++;continue}if(c+j.bytes>d){A.pastRunCap++;continue}c+=j.bytes,A.bytes+=j.bytes,u.add(j.sourceId),x&&_?(A.replaced=(A.replaced??0)+1,$.set(j.sourceId,x.targetId),N.push(j)):x?(A.versions++,N.push({...j,into:{documentId:x.targetId,linked:x.linked}})):(l++,A.copied++,N.push(j))}A.pastRunCap>T&&S.push(`${A.pastRunCap-T} file(s) past the ${t.maxRunMB} MB a run copies were not copied: the next run copies them.`),v>0&&S.push(`${v} legacy attachment(s) the source changed since they were copied were left as copied: replacing one deletes its earlier copy, and this run may not delete in the target.`),T>0&&S.push(`${T} file(s) were not copied: this configuration keeps the record of ${Le} copied files at most, which it holds already. Removing an earlier run of it frees the entries of the files that run copied: Remove what this run created on its History entry, or --remove on the command line.`),f.objects.set(m,{scope:new Set(w),files:N,outcome:A,notes:S,shared:E,held:g,replacing:$,attachmentsChangedAt:F,...k!==void 0?{filesSeen:k}:{}})}return f.storage={remainingBytes:o,plannedBytes:c,...c>o?{shortfall:`The files to copy take ${st(c)} and the target has ${st(Math.max(0,o))} of file storage left. Lower the largest file or the most a run copies, or leave the files out.`}:{}},f}function yo(n){return n.flatMap(e=>e.samples.map(t=>`${e.objectApiName}: ${t.recordSummary}: ${t.messages.join("; ")}`))}async function ei(n){let{config:e,option:t,objectApiName:r,planned:s,written:i,deps:o,signal:a}=n,d={...s.outcome,copied:0,versions:0,bytes:0,...s.outcome.replaced!==void 0?{replaced:0}:{}},c=[...s.notes],l=[...i.keys()].filter(g=>!s.scope.has(g)).length;l>0&&c.push(`${l} record(s) written were not in the source when the files were looked up: their files are copied by the next run.`);try{for(let g of s.shared)o.store.record(e.id,g)}catch(g){c.push(`The files the target already held could not be recorded (${K(g)}): the next run looks them up again.`)}if(s.files.length===0)return{outcome:d,notes:c,unplanned:l,cancelled:!1};let u=o.store.load(e.id),f=new Map((u?.kind==="stored"?u.map.entries:[]).filter(g=>g.sourceOrgId===e.sourceOrgId&&g.targetOrgId===e.targetOrgId).map(g=>[g.sourceId,g])),p=s.files.map(g=>{let w=g.into?void 0:f.get(g.sourceId);return w&&w.kind==="document"?{...g,into:{documentId:w.targetId,linked:w.linked,unchanged:!0}}:g}),h=bs({files:p.filter(g=>!g.into?.unchanged),leftOut:[],errors:[]},t.maxFileSizeMB*1048576),y=[],m,b=!1,S=[],R={ids:[],note:void 0},k=(g,w)=>{let M=He(e.sourceOrgId,e.targetOrgId,g.sourceId),A=[...new Set([...g.into?.linked??[],...w.linked])].slice(0,an),O=g.objectApiName==="ContentDocument",E=s.replacing.get(g.sourceId),F=s.attachmentsChangedAt.get(g.sourceId);w.asVersion?(d.versions++,d.bytes+=g.bytes):E!==void 0?(d.replaced=(d.replaced??0)+1,d.bytes+=g.bytes):g.into?.unchanged||(d.copied++,d.bytes+=g.bytes),!w.asVersion&&!g.into&&n.onCreated?.(O?"ContentDocument":"Attachment",w.targetId);try{o.store.record(e.id,{sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:r,kind:O?"document":"attachment",sourceId:g.sourceId,targetId:w.targetId,...O?{sourceVersionId:g.body.id}:{},...!O&&F!==void 0?{sourceModifiedAt:F}:{},linked:A,copiedAt:new Date().toISOString()}),E!==void 0&&E!==w.targetId&&S.push(E)}catch(N){m=`${K(N)} (${M})`}};try{await Rs({files:p,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:g=>i.has(g)||s.held.has(g),get:g=>i.get(g)??s.held.get(g),add:()=>{}},deps:o.copy,report:h,errors:y,waitIfPaused:async()=>{if(m!==void 0)throw new Ke;if(await n.waitIfPaused?.(),a?.aborted)throw new Ke},onProgress:g=>{g.status==="running"&&o.onProgress?.(g.progress,`${r}: ${g.message}`)},onCopied:k})}catch(g){if(!(g instanceof Ke))throw g;b=m===void 0}finally{S.length>0&&(R=await wo(o,S))}return d.links=h.links,d.failed=h.objects.reduce((g,w)=>g+w.failed,0)+R.ids.length,d.recordNotWritten=h.leftOut.filter(g=>g.reason==="record-not-created").length,c.push(...yo(y)),R.note!==void 0&&c.push(R.note),d.recordNotWritten>0&&c.push(`${d.recordNotWritten} file(s) were not copied: no record they hang on was written.`),m!==void 0&&(d.failed++,c.push(`A copied file could not be recorded, so no more files were copied: ${m}. Check the copies of the last files in the target before running it again.`)),{outcome:d,notes:c,unplanned:l,cancelled:b}}var Xs=200;async function wo(n,e){let t=[],r=new Set;for(let s=0;s<e.length;s+=Xs){let i=e.slice(s,s+Xs);try{let o=await n.deleteFromTarget?.("Attachment",i)??[];i.forEach((a,d)=>{let c=o[d];c?.success||(t.push(a),r.add(c?.errors.join("; ")||"The target gave no reason."))})}catch(o){t.push(...i),r.add(K(o))}}return t.length===0?{ids:[],note:void 0}:{ids:t,note:`${t.length} earlier copy(ies) of an attachment replaced could not be deleted from the target (${[...r].join("; ")}): the record holds the new copy and the old one, ${t.join(", ")}.`}}function Md(n){let e=t=>{let r=n[t];if(!r)throw new Error(`No connection for the org ${t}.`);return r};return{queryRecords:async(t,r)=>(await er(e(t).pages,r)).records,readFileBody:(t,r,s)=>As(e(t).transport,r,s),insertFile:(t,r,s)=>Cs(e(t).transport,r,s),insertRecords:async(t,r,s)=>Rr(await e(t).create(r,s),r).map(i=>({id:i.id,success:i.success,errors:i.errors})),remainingFileStorageMB:t=>Ps(e(t).transport)}}function Fd(n){let e=0,t=0,r=0;for(let s of n)e+=s.copied+s.versions+(s.replaced??0),t+=s.bytes,r+=s.tooLarge+s.pastRunCap;return`${e} file(s), ${st(t)} copied, ${r} skipped past the caps`}var dn="sync:config:",ti="syncConfigs",Je="sync:delta:",cn="syncDelta",kt="sync:files:",ni="syncFiles",ri=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${dn}${e.id}`,e,ti)}load(e){return this.configStore.get(`${dn}${e}`)}isSaved(e){return this.load(e)!==void 0}deltaStore(){return{load:e=>this.isSaved(e)?this.loadDelta(e):null,record:(e,t)=>this.recordWatermark(e,t)}}fileStore(){return{load:e=>this.isSaved(e)?this.loadFiles(e):null,record:(e,t)=>this.recordFile(e,t)}}list(){let e=this.configStore.getByCategory(ti);return Object.values(e).sort((r,s)=>s.updatedAt.localeCompare(r.updatedAt))}delete(e){return this.configStore.delete(`${Je}${e}`),this.configStore.delete(`${kt}${e}`),this.configStore.delete(`${dn}${e}`)}loadDelta(e){return fr(this.configStore.get(`${Je}${e}`))}recordWatermark(e,t){let r=this.loadDelta(e),o={version:1,entries:[...(r.kind==="stored"?r.state.entries:[]).filter(a=>a.sourceOrgId!==t.sourceOrgId||a.targetOrgId!==t.targetOrgId||a.objectApiName!==t.objectApiName),t],...r.kind==="stored"&&r.state.resetAt?{resetAt:r.state.resetAt}:{}};this.configStore.set(`${Je}${e}`,o,cn)}loadFiles(e){return Zs(this.configStore.get(`${kt}${e}`))}recordFile(e,t){let r=this.loadFiles(e);if(r.kind==="unreadable")throw new Error(`the record of copied files does not read: ${r.issue}`);let i=(r.kind==="stored"?r.map.entries:[]).filter(a=>a.sourceOrgId!==t.sourceOrgId||a.targetOrgId!==t.targetOrgId||a.sourceId!==t.sourceId);if(i.length>=Le)throw new Error(`the record of copied files holds ${Le} files already`);let o={version:1,entries:[...i,t]};this.configStore.set(`${kt}${e}`,o,ni)}forgetFiles(e,t,r){let s=this.loadFiles(e);if(s.kind!=="stored"||r.length===0)return[];let i=new Set(r.map(d=>d.slice(0,15))),o=[],a=s.map.entries.filter(d=>{let c=d.sourceOrgId===t.sourceOrgId&&d.targetOrgId===t.targetOrgId&&i.has(d.targetId.slice(0,15));return c&&o.push(d),!c});if(o.length>0){let d={version:1,entries:a};this.configStore.set(`${kt}${e}`,d,ni)}return o}markRemoved(e,t,r,s){let i=this.loadDelta(e);if(i.kind!=="stored"||r.length===0)return[];let o=[],a=i.state.entries.map(d=>d.sourceOrgId!==t.sourceOrgId||d.targetOrgId!==t.targetOrgId||!r.includes(d.objectApiName)?d:(o.push(d.objectApiName),{...d,removedAt:s}));if(o.length>0){let d={...i.state,entries:a};this.configStore.set(`${Je}${e}`,d,cn)}return o}clearDelta(e){let t=this.loadDelta(e),r=t.kind==="stored"?t.state.entries.length:0,s={version:1,entries:[],resetAt:new Date().toISOString()};return this.configStore.set(`${Je}${e}`,s,cn),r}};async function So(n,e,t){let r=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let{objectApiName:i,ids:o}of e){let a=ye(i);for(let d of ee(o)){if(t?.aborted)return;let c=await n.queryDeleted(`SELECT Id, CreatedDate FROM ${a} WHERE Id IN (${d})`);for(let l of c.records){let u=Date.parse(String(l.CreatedDate??""));Number.isFinite(u)&&(r=Math.min(r,u),s=Math.max(s,u))}}}if(!(!Number.isFinite(r)||!Number.isFinite(s)))return{first:new Date(r).toISOString(),last:new Date(s).toISOString()}}async function Wd(n,e){let t=s=>({note:`What the duplicate rules of the target reported of the run could not be read (${K(s)}): the empty DuplicateRecordSet records it left, if any, stay.`}),r=new Set;try{for(let{ids:s}of e)for(let i of ee(s)){let{records:o}=await n.query(`SELECT DuplicateRecordSetId FROM DuplicateRecordItem WHERE RecordId IN (${i})`);for(let a of o){let d=a.DuplicateRecordSetId;typeof d=="string"&&r.add(d)}}}catch(s){return{take:async()=>t(s)}}return{take:async(s=[])=>{let i=new Set(s.map(l=>l.slice(0,15))),o=[...r].filter(l=>!i.has(l.slice(0,15)));if(o.length===0)return{};let a=new Set;try{for(let l of ee(o)){let{records:u}=await n.query(`SELECT DuplicateRecordSetId FROM DuplicateRecordItem WHERE DuplicateRecordSetId IN (${l})`);for(let f of u)a.add(String(f.DuplicateRecordSetId))}}catch(l){return t(l)}let d=o.filter(l=>!a.has(l));if(d.length===0)return{};let c={objectApiName:"DuplicateRecordSet",planned:d.length,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],unchecked:[],reasons:[]};for(let l=0;l<d.length;l+=Yt){let u=d.slice(l,l+Yt);for(let f of await Nr(n,c.objectApiName,u))f.kind==="deleted"?c.deleted+=1:f.kind==="gone"?c.alreadyGone+=1:(c.refused+=1,c.reasons.includes(f.reason)||c.reasons.push(f.reason))}return{object:c}}}}async function bo(n,e){if(!n||!e)return n;let t=Date.parse(e.at),r=Date.parse(e.lastAt??""),s=Date.parse(n.first),i=Date.parse(n.last);if(!Number.isFinite(s)||!Number.isFinite(i)||!Number.isFinite(t)&&!Number.isFinite(r))return n;let o=await si(e);if(o===void 0)return n;let a=Number.isFinite(t)?Math.min(s,t+o):s,d=Number.isFinite(r)?Math.max(i,r+o):i;return a===s&&d===i?n:{first:a===s?n.first:new Date(a).toISOString(),last:d===i?n.last:new Date(d).toISOString()}}async function si(n){let e=n.now??(()=>new Date);try{let t=e().getTime(),r=Date.parse(await n.serverTime());return Number.isFinite(r)?r-(t+e().getTime())/2:void 0}catch{return}}async function Ro(n){if(!n)return;let e=Date.parse(n.at);if(!Number.isFinite(e))return;let t=Date.parse(n.lastAt??""),r=await si(n);if(r===void 0)return;let s=Number.isFinite(t)?Math.max(e,t):e;return{first:new Date(e+r).toISOString(),last:new Date(s+r).toISOString()}}var ko=50,Oo=3,ii=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function Ao(n,e,t,r){let s=Date.parse(t.first)-Is,i=Date.parse(t.last)+Es;if(!Number.isFinite(s)||!Number.isFinite(i))return;let o=new Map,a=0;for(let{objectApiName:d,ids:c}of e){if(a>=Oo||o.size>1||r?.aborted)break;let l=c.slice(0,ko);if(l.length===0)continue;let u;try{let[p]=ee(l,l.length);u=(await n.query(`SELECT Id, LastModifiedById, LastModifiedDate FROM ${ye(d)} WHERE Id IN (${p})`)).records}catch{continue}let f=!1;for(let p of u){let{LastModifiedById:h,LastModifiedDate:y}=p??{},m=typeof y=="string"?Date.parse(y):Number.NaN;typeof h!="string"||!ii.test(h)||!(m>=s&&m<=i)||(o.has(h.slice(0,15))||o.set(h.slice(0,15),h),f=!0)}f&&a++}return o.size===1?[...o.values()][0]:void 0}async function Gd(n,e,t,r,s,i,o){let a=e.some(({ids:p})=>p.length>0),d=a?await bo(await So(n,e,r),s):await Ro(s),c=o.runUserId!==void 0&&ii.test(o.runUserId)?o.runUserId:void 0,l=n.query?.bind(n),u=!c&&!a&&d&&l?await Ao({query:l},i,d,r):void 0,f=i.filter(({ids:p})=>p.length>0);return{writtenBetween:d,created:e,remap:new Set([...e,...i].flatMap(({ids:p})=>p.map(h=>h.slice(0,15)))),automation:Ts(t),...c?{runUserId:c}:{},...u?{user:u}:{},ties:{...o.ties,...f.length>0?{writtenOver:f}:{}},...r?{signal:r}:{}}}var Ot={status:"cancelled",objects:[],unread:[],handWork:[]};function Xd(n,e,t){return{...Dr(n,e),counts:Ms(zr(Ur(n),t))}}async function Zd(n,e){let t=Date.parse(n.writtenBetween?.first??""),r=Date.parse(n.writtenBetween?.last??"");if(!Number.isFinite(t)||!Number.isFinite(r))return n;let{created:s}=n,i=new Set(s.flatMap(({ids:c})=>c.map(l=>l.slice(0,15)))),o=await xr(e,{has:c=>i.has(c),start:t,end:r,...n.runUserId?{user:n.runUserId.slice(0,15)}:{}},s.filter(c=>c.objectApiName==="Quote").flatMap(({ids:c})=>c),new Set(s.map(c=>c.objectApiName))),a=new Set(o.flatMap(c=>c.copies.map(l=>l.id.slice(0,15))));if(a.size===0)return n;let{remap:d}=n;return{...n,remap:{has:c=>d.has(c)||a.has(c)}}}async function Qd(n){let e,t,r;try{let o=await n.input();"refused"in o?r={...Ot,status:"refused",refusal:o.refused}:t=Fs(n.org,o,{...n.options,approve:async a=>{let{check:d,decision:c}=await Lr(n.guard,{...n.guardOf,objectName:vs(a).join(", "),recordCount:js(a)});if(e=c,c==="refused")return`Operation blocked by Production Guard: ${d.blockedReason??d.impactSummary}`;if(c==="declined")return"Operation cancelled by user (confirmation declined)."}})}catch(o){r={...Ot,status:"failure",refusal:K(o)}}let s=async o=>{if(!t||r)return!1;try{return await o(t)}catch(a){return r={...t.result(),status:"failure",refusal:K(a)},!1}},i;return{automationMade:t?.automationMade??new Set,ask:async()=>{await s(async o=>(await o.ask(),!1))},get takes(){return r?[]:t?.takes??[]},first:o=>s(a=>a.first(o)),afterRemoval:o=>s(a=>a.afterRemoval(o)),result:()=>r??t?.result()??Ot,settle:()=>(i??=(async()=>{let o=r??t?.result()??Ot;return n.onGuardDecision(o,e),t&&(t.made.size>0||t.late.size>0||t.gone.size>0)&&await n.keepMade?.(t.made,t.late,t.gone).catch(()=>{}),o})(),i)}}function ec(n){return n?"GUARD_BLOCKED":"SWEEP_REFUSED"}var oi=6e4;function Io(n,e){return e.filter(t=>(t.ids.length>0||t.idsUntold===!0)&&Eo(n,t)).map(t=>({ids:[...t.ids],...t.idsUntold?{idsUntold:!0}:{}}))}function Eo(n,e){let t=Date.parse(n?.first??""),r=Math.max(t,Date.parse(n?.last??""));return!Number.isFinite(t)||!Number.isFinite(r)?!1:Number.isFinite(e.from)&&Number.isFinite(e.to)&&e.from<=r+9e5+oi&&Math.max(e.from,e.to)>=t-2e3-oi}var To=new Set(["autopilot_execute","anonymize_execute","subject_erase","backup_restore","checkpoint_rewind","checkpoint_undo","frozen_load"]);function tc(n,e){return n.filter(t=>To.has(t.action)&&t.action!==e&&t.outcome!=="stopped").map(t=>{let r=Date.parse(t.timestamp);return{ids:[],idsUntold:!0,from:r,to:r}})}function Mo(n){let e=Date.parse(n.firstWrittenAt??n.startedAt),t=Date.parse(n.lastWriteAt??n.lastWrittenAt??n.end?.at??n.startedAt);return{ids:[...n.created,...n.overwritten??[]].flatMap(({ids:r})=>r),from:e,to:Number.isFinite(t)?t:e}}function Fo(n,e,t){return n.filter(r=>r.targetOrgId===e&&r.runId!==t).map(Mo)}async function nc(n,e,t,r){let s=await r(n.targetOrgId,e).catch(()=>[]),i=jo(n.removal?.removalSpans),o=n.removal?.madeEarlier,a=n.removal?.lateEarlier;return{otherRuns:Io(e,[...Fo(t,n.targetOrgId,n.runId),...s]),...i?{removalBegan:i}:{},...o&&o.length>0?{madeEarlier:o}:{},...a&&a.length>0?{lateEarlier:a}:{}}}function rc(n,e,t,r=[]){let s=[...r],i=Xt(n.madeEarlier,e,s),o=Xt(n.lateEarlier,t,s),a={...n};return delete a.madeEarlier,delete a.lateEarlier,{...a,...i.length>0?{madeEarlier:i}:{},...o.length>0?{lateEarlier:o}:{}}}function jo(n){let e;for(let t of n??[]){let r=Date.parse(t.first);Number.isFinite(r)&&(!e||r<e.at)&&(e={at:r,first:t.first})}return e?.first}var ae=class extends Error{constructor(t,r,s){super(t);this.result=r;this.cause=s;this.name="SyncRunFailure"}result;cause},$e=class extends ae{constructor(t,r,s){super(t,r);this.code=s;this.name="SyncRunRefused"}code};function oc(n){return typeof n!="number"||!Number.isFinite(n)?5e4:Math.min(5e4,Math.max(1,Math.floor(n)))}var vo=/\b(QUERY_TIMEOUT|OPERATION_TOO_LARGE)\b/;function ln(n){return vo.test(n)?" Salesforce gave up on the count: filter the object on an indexed field (CreatedDate, SystemModstamp, Id, Name or an External ID) or on a narrower range of CreatedDate, then run it again. A user with View All Data reads the source without its sharing, which is what slows such a count most.":""}var No={raise:"the sandforge.sync.maxRecordsPerObject setting",sample:"Forge, with Depth ALL and Records per object set to A sample that fits the target"};function xo(n,e,t){let r=e<5e4?`raise ${t.raise} (50000 at most), or `:"";return n==="target"?`To compare every record, ${r}narrow the object's filter.`:`To copy the rest, ${r}read it in slices: a filter on CreatedDate, one range per run. To copy a sample of the source that fits the target instead, use ${t.sample}.`}function ac(n){let e=n.cutAtReadCap??[];if(!(n.readCap===void 0||e.length===0))return`the read of the source stopped at ${n.readCap} records of ${e.join(", ")} (sandforge.sync.maxRecordsPerObject): the run copied part of ${e.length===1?"it":"each"}. `+xo("source",n.readCap,No)}var Do=2e3,Lo=5e3,At=class{chunkSize;pollIntervalMs;signal;constructor(e={}){this.chunkSize=e.chunkSize??Do,this.pollIntervalMs=e.pollIntervalMs??Lo,this.signal=e.signal}async executeChunked(e,t,r,s,i,o){if(!e.bulkManager.canStartNewJob())throw new Error("Maximum concurrent bulk jobs reached");let a=e.connection.bulk2.createJob({operation:r,object:t,...o?{externalIdFieldName:o}:{}}),d=a.id??`bulk-${crypto.randomUUID()}`,c={id:d,operation:r,object:t,state:"UploadComplete",numberRecordsProcessed:0,numberRecordsFailed:0,totalProcessingTime:0,createdDate:new Date().toISOString(),totalRecords:i};e.bulkManager.registerJob(c);try{await a.open();let l=Ar(a);l!==void 0&&e.onOpened?.(l);let u=[];for await(let w of s){if(this.signal?.aborted)break;for(let M of w)u.push(M);e.onProgress?.(u.length,i)}let f,p=0;if(this.signal?.aborted||(f=kr(r,u,o),await a.uploadData(f.text),p=u.length),this.signal?.aborted||f===void 0)return await Pr(a),e.bulkManager.updateJobState(d,"Aborted"),this.buildAbortedResult(p);await a.close();let h=await a.check();for(;h.state==="InProgress"||h.state==="UploadComplete";)e.bulkManager.updateJobState(d,h.state),e.onProgress?.(h.numberRecordsProcessed??0,i),await new Promise(w=>setTimeout(w,this.pollIntervalMs)),h=await a.check();let y=await a.getAllResults(),m=Or(y,f,Cr(h)),b=m.outcomes,S=[],R=[],k=m.unattributedSuccessIds.length;for(let w of b)w.success?(k++,w.id!==void 0&&S.push(w.id)):R.push(w.error??"Unknown error");S.push(...m.unattributedSuccessIds),R.push(...m.unattributedFailures);let g=h.state==="JobComplete"?"JobComplete":"Failed";return e.bulkManager.updateJobState(d,g),e.bulkManager.updateJobCounts(d,h.numberRecordsProcessed??i,R.length),{totalRecords:p,successCount:k,failureCount:R.length,successIds:S,errors:R,aborted:!1,outcomes:b,...m.unattributedSuccessIds.length>0?{unmatchedIds:m.unattributedSuccessIds}:{}}}catch(l){throw e.bulkManager.updateJobState(d,"Failed"),l}}async*createChunkGenerator(e,t){let r=t??this.chunkSize;for(let s=0;s<e.length;s+=r)yield e.slice(s,s+r)}buildAbortedResult(e){return{totalRecords:e,successCount:0,failureCount:0,successIds:[],errors:[],aborted:!0}}};var $o=1e4,ai=fe.REST_API_BATCH_SIZE;function Bo(n){return!n.success&&n.errors.some(e=>e.startsWith("DUPLICATES_DETECTED"))}function _o(n){return!n.success&&Tr(n.errors,n.errorDetails)}function Wo(n,e){let[t,...r]=n.errors;return t===void 0?n:{...n,errors:[Fr(t,e),...r]}}function un(n){return typeof n.created=="boolean"?{created:n.created}:{}}function li(n){return n.some(e=>e.fields.length>0)?{errorDetails:n}:{}}function di(n){let e=n===void 0?void 0:wr(n);return e?li([e]):{}}function pn(n,e){return n!=="insert"&&n!=="upsert"?[]:e.flatMap(t=>t.success&&typeof t.id=="string"&&t.id!==""&&(n==="insert"||t.created===!0)?[t.id]:[])}function Go(n,e){return!n||!e?n??e:{before:async(t,r,s,i)=>await n.before?.(t,r,s,i)??await e.before?.(t,r,s,i),sending:(t,r,s)=>{n.sending(t,r,s),e.sending(t,r,s)},opened:(t,r,s,i)=>{n.opened?.(t,r,s,i),e.opened?.(t,r,s,i)},answered:(t,r,s,i)=>{n.answered(t,r,s,i),e.answered(t,r,s,i)}}}function Sc(n,e){let t=r=>r==="insert"||r==="upsert";return{...e?{before:(r,s,i,o)=>e.before(r,s,i,o)}:{},sending:(r,s,i)=>{t(s)?n.sending?.(r,i,s==="upsert"?{upsert:!0}:void 0):n.writing?.(r,i)},opened:(r,s,i,o)=>{t(s)&&n.sending?.(r,i,{job:o,...s==="upsert"?{upsert:!0}:{}})},answered:(r,s,i)=>{t(s)?n.answered?.(r,pn(s,i)):i.length>0&&n.writing?.(r,i.length),e?.answered(r,s,i)}}}var ci=class{constructor(e){this.deps=e;this.wait=e.wait??(t=>Mr(t,e.signal)),this.retryOp=new St({retryConfig:e.retryConfig,signal:e.signal,onRetry:(t,r,s)=>{e.log(`[RETRY] sync attempt=${t} code=${r.originalError.statusCode} delay=${s}ms`)}})}deps;retryOp;wait;async insert(e,t,r,s){let i=Go(this.deps.calls,s),o=l=>this.deps.connection.sobject(e).create(l,{headers:tt()}),a="Insert failed after retries",d=await this.tryStreaming("insert",e,t,void 0,i)??await this.tryBulk("insert",e,t,void 0,i),c=d?await this.duplicatesAgain("insert",e,t,d,o,a,i):await this.executeRestBatches("insert",e,t,r,o,a,i);return this.locksAgain("insert",e,t,c,o,a,i)}async upsert(e,t,r,s){let i=c=>this.deps.connection.sobject(e).upsert(c,t,{headers:tt()}),o="Upsert failed after retries",a=await this.tryStreaming("upsert",e,r,t)??await this.tryBulk("upsert",e,r,t),d=a?await this.duplicatesAgain("upsert",e,r,a,i,o,this.deps.calls,t):await this.executeRestBatches("upsert",e,r,s,i,o,this.deps.calls,t);return this.locksAgain("upsert",e,r,d,i,o,this.deps.calls,t)}async update(e,t,r){let s=d=>this.deps.connection.sobject(e).update(d,{headers:tt()}),i="Update failed after retries",o=await this.tryStreaming("update",e,t)??await this.tryBulk("update",e,t),a=o?await this.duplicatesAgain("update",e,t,o,s,i):await this.executeRestBatches("update",e,t,r,s,i);return this.locksAgain("update",e,t,a,s,i)}async delete(e,t,r){let s=d=>this.deps.connection.sobject(e).destroy(d),i="Delete failed after retries",o=t.map(d=>({Id:d})),a=await this.tryBulk("delete",e,o)??await this.executeRestBatches("delete",e,t,r,s,i);return this.locksAgain("delete",e,t,a,s,i)}async tryStreaming(e,t,r,s,i=this.deps.calls){if(r.length<=$o)return;if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new Q(t);let o=await this.refusedBefore(i,t,e,r,s);if(o)return o;let a=new At({signal:this.deps.signal});i?.sending(t,e,r.length);let d={connection:Vt(this.deps.connection),bulkManager:this.deps.bulkManager,onProgress:(u,f)=>{this.deps.onProgress(u,f,`Streaming ${e} ${t}`)},onOpened:u=>i?.opened?.(t,e,r.length,u)},c=await a.executeChunked(d,t,e,a.createChunkGenerator(r),r.length,s);if(c.aborted)throw i?.answered(t,e,[]),new Q(t);this.logUnmatched(`Streaming ${e} ${t}`,c.unmatchedIds);let l=(c.outcomes??[]).map(u=>this.withExistingRecord(t,{id:u.id,success:u.success,errors:u.success?[]:[u.error??"Streaming error"],...un(u),...u.success?{}:di(u.error)}));return i?.answered(t,e,l),l}async tryBulk(e,t,r,s,i=this.deps.calls){if(!this.deps.bulkExecutor.shouldUseBulkApi(r.length))return;if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new Q(t);let o={connection:Vt(this.deps.connection),bulkManager:this.deps.bulkManager,onProgress:(l,u)=>{this.deps.onProgress(l,u,`Bulk ${e} ${t}`)},signal:this.deps.signal,onOpened:l=>i?.opened?.(t,e,r.length,l)},a=await this.refusedBefore(i,t,e,r,s);if(a)return a;i?.sending(t,e,r.length);let d=await this.deps.bulkExecutor.executeBulk(o,t,e,r,s);if(d.aborted)throw i?.answered(t,e,[]),new Q(t);this.logUnmatched(`Bulk ${e} ${t}`,d.unmatchedIds);let c=d.outcomes.map(l=>this.withExistingRecord(t,{id:l.id,success:l.success,errors:l.success?[]:[l.error??"Bulk error"],...un(l),...l.success?{}:di(l.error)}));return i?.answered(t,e,c),c}async refusedBefore(e,t,r,s,i){if(r==="delete"||!e?.before)return;let o=await e.before(t,r,s,i);if(o!==void 0)return this.deps.log(`[WARN] ${r} ${t}: ${s.length} row(s) not sent: ${o}`),s.map(()=>({success:!1,errors:[o]}))}async duplicatesAgain(e,t,r,s,i,o,a=this.deps.calls,d){let c=s.flatMap((p,h)=>h<r.length&&Bo(p)?[h]:[]);if(c.length===0||this.deps.signal?.aborted)return s;let l;try{l=await this.executeRestBatches(e,t,c.map(p=>r[p]),ai,i,o,a,d,c)}catch(p){if(!(p instanceof Q))throw p;l=p.written}let u=[...s];l.forEach((p,h)=>{u[c[h]]=p});let f=l.filter(p=>p.success).length;return this.deps.log(`[INFO] ${e} ${t}: ${c.length} row(s) a duplicate rule refused in the Bulk API job, which cannot carry the header that lets a rule's matches be saved, went again through REST with it: ${f} saved`+(l.length<c.length?`, ${c.length-l.length} not sent (cancelled)`:"")),u}async locksAgain(e,t,r,s,i,o,a=this.deps.calls,d){let c=new Map,l=await jr({outcomes:s.slice(0,r.length),locked:_o,written:p=>p.success,send:async p=>{let h;try{h=await this.executeRestBatches(e,t,p.map(y=>r[y]),ai,i,o,a,d,p)}catch(y){if(!(y instanceof Q))throw y;h=y.written}for(let y of p.slice(0,h.length))c.set(y,(c.get(y)??0)+1);return h},note:Wo,wait:p=>this.wait(p),stopped:()=>this.deps.signal?.aborted===!0}),u=vr("row(s)",l);return u===void 0?s:(this.deps.log(`[INFO] ${e} ${t}: ${u}`),[...l.outcomes.map((p,h)=>{let y=c.get(h);return y===void 0?p:{...p,lockResends:y}}),...s.slice(r.length)])}logUnmatched(e,t){t&&t.length>0&&this.deps.log(`[WARN] ${e}: the job wrote ${t.length} record(s) no row was matched to: ${t.join(", ")}`)}withExistingRecord(e,t){if(t.success)return t;let r=Jt(t,this.deps.keyPrefixOf?.(e));return r.kind==="linked"?{...t,existingId:r.id}:t}async executeRestBatches(e,t,r,s,i,o,a=this.deps.calls,d,c){let l=[];for(let u=0;u<r.length;u+=s){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new Q(t,l);let f=r.slice(u,u+s);if(e!=="delete"){let y=await this.refusedBefore(a,t,e,f,d);if(y){l.push(...y);continue}if(this.deps.signal?.aborted)throw new Q(t,l)}a?.sending(t,e,f.length);let p=await this.retryOp.execute(()=>i(f));if(p.cancelled)throw a?.answered(t,e,[],c&&[]),new Q(t,l);let h=[];if(p.success&&p.result)for(let y of Array.isArray(p.result)?p.result:[p.result])h.push(this.restOutcome(t,y));else h.push(...f.map(()=>({success:!1,errors:[p.error?.message??o]})));l.push(...h),a?.answered(t,e,h,c?.slice(u,u+f.length))}return l}restOutcome(e,t){if(t.success)return{id:t.id,success:!0,errors:[],...un(t)};let r=t.errors??[],s=r.map(Sr),i={id:t.id,success:!1,errors:[s[0]??"Unknown error"],...li(r.map(yr))},o=Jt({success:!1,errors:s,duplicateMatchIds:r.flatMap(a=>br(a,e))},this.deps.keyPrefixOf?.(e));return o.kind==="linked"?{...i,existingId:o.id}:i}};function ui(n,e){if(n.operation==="delete")return[];let t=pr(n.fieldMappings,n.excludedFields??[]),r=new Set([...ur(n.fieldMappings),...n.addOnFields.map(i=>i.fieldApiName.toLowerCase())]),s=i=>!t.has(i.toLowerCase())||r.has(i.toLowerCase());return(e.fields??[]).flatMap(i=>i.isReference&&i.createable&&i.name!=="RecordTypeId"&&(i.referenceTo?.length??0)>0&&s(i.name)?[{field:i.name,referenceTo:i.referenceTo??[]}]:[])}function pi(n,e){let t=[...n].sort((R,k)=>R.insertOrder-k.insertOrder),r=new Map(t.map((R,k)=>[R.objectApiName,k])),s=new Set(t.filter(R=>R.operation!=="delete").map(R=>R.objectApiName)),i=new Map([...s].map(R=>[R.toLowerCase(),R])),o=[],a=new Set;for(let R of t){let k=R.objectApiName;if(s.has(k))for(let{field:g,referenceTo:w}of e.get(k)??[])for(let M of w){let A=i.get(M.toLowerCase());if(A===void 0||A===k)continue;let O=`${A}>${k}`;a.has(O)||(a.add(O),o.push({parent:A,child:k,field:g}))}}let d=Uo(t.map(R=>R.objectApiName),o),c=new Map;d.forEach((R,k)=>{for(let g of R)c.set(g,k)});let l=d.map(R=>[...R].sort((k,g)=>(r.get(k)??0)-(r.get(g)??0))),u=l.map(R=>r.get(R[0])??0),f=l.map(()=>new Set);for(let{parent:R,child:k}of o){let g=c.get(R)??0,w=c.get(k)??0;g!==w&&f[w].add(g)}let p=new Set,h=[];for(;p.size<l.length;){let R;if(l.forEach((k,g)=>{p.has(g)||[...f[g]].some(w=>!p.has(w))||(R===void 0||u[g]<u[R])&&(R=g)}),R===void 0)break;p.add(R),h.push(...l[R])}let y=new Map(t.map(R=>[R.objectApiName,R])),m=h.flatMap(R=>{let k=y.get(R);return k?[k]:[]}),b=new Map(h.map((R,k)=>[R,k])),S=[];for(let R of m){let k=R.objectApiName,g=o.filter(w=>w.child===k&&(r.get(w.parent)??0)>(r.get(k)??0)&&(b.get(w.parent)??0)<(b.get(k)??0)).sort((w,M)=>(b.get(M.parent)??0)-(b.get(w.parent)??0));g.length>0&&S.push({objectApiName:k,after:g[0].parent,field:g[0].field})}return{ordered:m,order:{objects:h,moved:S,cycles:l.filter(R=>R.length>1)}}}function Uo(n,e){let t=new Map(n.map(l=>[l,[]]));for(let{parent:l,child:u}of e)t.get(l)?.push(u);let r=0,s=new Map,i=new Map,o=[],a=new Set,d=[],c=l=>{s.set(l,r),i.set(l,r),r++,o.push(l),a.add(l);for(let p of t.get(l)??[])s.has(p)?a.has(p)&&i.set(l,Math.min(i.get(l)??0,s.get(p)??0)):(c(p),i.set(l,Math.min(i.get(l)??0,i.get(p)??0)));if(i.get(l)!==s.get(l))return;let u=[],f;do{if(f=o.pop(),f===void 0)break;a.delete(f),u.push(f)}while(f!==l);d.push(u)};for(let l of n)s.has(l)||c(l);return d}var zo=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,de=n=>n.toLowerCase();function Ct(n){return n==="insert"||n==="upsert"}function qo(n,e){let t=de(e);if(n.addOnFields.some(s=>de(s.fieldApiName)===t)||n.transformRules.some(s=>s.field&&de(s.field)===t))return;let r=n.fieldMappings.find(s=>s.type!=="exclude"&&de(s.targetField)===t);return r?(r.type==="direct"||r.type==="rename")&&(r.transformRules??[]).length===0?r.sourceField:void 0:e}function Ko(n){return n!==void 0&&[...n.source.active].some(e=>!n.target.active.has(e))}async function fi(n){let e=new Map,t=new ze(n.earlier),r=new Set,s=new Set([...n.leftOut].map(de)),i,o=async l=>{let u=await n.read(l);return u.length>0&&mt(l.objectApiName,u)&&(i=await n.standardPricebooks?.(),i&&t.noteMatched(i.source,i.target)),u},a=n.matched,d=(l,u)=>{a&&u>0&&a.set(l,(a.get(l)??0)+u)},c=(l,u)=>{let f=i?.source;return l===ge&&f!==void 0?u.filter(p=>p.Id===f).length:0};for(let l of n.ordered){let u=l.objectApiName;if(s.has(de(u))){if(!Ct(l.operation))continue;let A=await o(l);for(let O of A){let E=O.Id;typeof E=="string"&&E!==""&&t.noteRefused(E,u)}d(u,c(u,A)),r.add(de(u));continue}if(l.operation==="delete")continue;let f=(n.lookups.get(u)??[]).flatMap(({field:A,referenceTo:O})=>{let F=O.filter(N=>de(N)!==de(u)&&r.has(de(N))).length>0?qo(l,A):void 0;return F!==void 0?[{field:A,source:F}]:[]}),p=a!==void 0&&Ct(l.operation),h=p&&u===ge&&await n.standardPricebooks?.()!==void 0,y=p&&u===Me&&await n.standardPricebooks?.()?await n.currencies?.():void 0,m=Ko(y);if(f.length===0&&!h&&!m)continue;let b=new Map,S=A=>{let O=`${A.parent}|${A.field}`,E=b.get(O);E?E.rows++:b.set(O,{...A,rows:1})},R=n.copied?.get(u),k=(await o(l)).filter(A=>{let O=A.Id;return!(R&&typeof O=="string"&&R.has(O.slice(0,15)))}),g=new Map;for(let A of f.length>0?k:[]){let O=A.Id,E=f.find(({source:N})=>{let $=A[N];return typeof $=="string"&&zo.test($)&&t.refusedObjectOf($)!==void 0});if(!E)continue;let F={parent:t.refusedObjectOf(A[E.source])??"",field:E.field};S(F),typeof O=="string"&&O!==""&&g.set(O,F),Ct(l.operation)&&typeof O=="string"&&O!==""&&t.noteRefused(O,u)}if(h&&d(u,c(u,k)),m){let A=yt(Me,{records:k,sources:k,sourceIds:k.map(E=>typeof E.Id=="string"?E.Id:void 0)},i,y,E=>t.refusedObjectOf(E)!==void 0),O=0;for(let[E,F]of A.standsFor){if(g.has(E))continue;let N=t.refusedObjectOf(F)!==void 0?g.get(F):void 0;if(N){S(N),g.set(E,N),t.noteRefused(E,u);continue}O++}d(u,O)}let w=[...b.values()],M=w.reduce((A,O)=>A+O.rows,0);M>0&&(e.set(u,{objectApiName:u,rows:M,parent:w[0].parent,field:w[0].field,parents:w}),Ct(l.operation)&&r.add(de(u)))}return e}var gi=Symbol("not written");function Ho(n,e){if(n==="delete")return{rules:[],onChange:[]};let t=[],r=[];for(let{onChangeOnly:s,...i}of e)s&&n==="insert"?r.push(i.name):t.push(i);return{rules:t,onChange:r}}function Yo(n){return`${n.length} active validation rule(s) of the target left out of what may refuse these inserts: their formula holds only on a change of a record (ISCHANGED, PRIORVALUE, NOT(ISNEW())), which an insert never is \u2014 ${n.join(", ")}`}var Jo=/^012000000000000(AAA)?$/;function Vo(n){let e=n.RecordTypeId;return typeof e=="string"&&e.length>=15&&!Jo.test(e)}function hn(n){let e=n?.[tr];return typeof e=="string"&&e!==""}async function hi(n,e,t,r){let s=e.some(Vo)?await n.recordTypes():void 0,i=t.some(hn)||e.some(hn)?await n.currencies():void 0,o=n.later?.get(r),a=n.recordTypesUnderTheLease?.get(r);return{links:n.links,sources:t,...s?{recordTypes:s}:{},...i?{currencies:i,currencyChangesById:n.currencyChangesById}:{},...n.contactPoints?{contactPoints:n.contactPoints}:{},...o&&o.size>0?{later:o}:{},...a?{recordTypesUnderTheLease:a}:{},...n.createdWithoutRecordType?{createdWithoutRecordType:n.createdWithoutRecordType}:{}}}function fn(n){let e=new Map;for(let t of n?.cycles??[])t.forEach((r,s)=>{s<t.length-1&&e.set(r,new Set(t.slice(s+1)))});return e}function Xo(n,e,t){return{...n,...e.set?{lookupsSetAfter:{...e.set,after:[...t]}}:{},...e.leftOut.length>0?{lookupsLeftOut:[...n.lookupsLeftOut??[],...e.leftOut]}:{}}}function mi(n,e){return e.flatMap((t,r)=>{let s=n[r];return t.success&&s!==void 0?[s]:[]})}function yi(n,e){let t=e.encryptedLeftOut??[];return t.length>0?{...n,encryptedLeftOut:[...t]}:n}function re(n){return n.slice(0,15)}function Zo(n,e){if(!e)return n;if(e.unread!==void 0)return{...n,errors:[...n.errors,`The contact roles the platform wrote with the run's opportunities were not looked up, so written as read: an opportunity may hold the role of its contact twice. ${e.unread}`]};let{records:t,given:r,refusal:s,alike:i}=e,o=i!==void 0?{...n,errors:[...n.errors,Vn(i)]}:n;return t===0?o:{...o,skipped:o.skipped+t,writtenByThePlatform:{records:t,given:r,...s!==void 0?{refusal:s}:{}}}}function Qo(n,e,t){if(n.objectApiName!==X||!ce(n.operation)||!t.sentWithAContact||e.records.length===0)return{prepared:e,linked:0};let r=a=>typeof a=="string"&&a!==""?t.targetOf(a):void 0,s=e.records.map((a,d)=>({OpportunityId:r(a.OpportunityId),[oe]:r(a[oe]),IsPrimary:e.sources[d]?.IsPrimary??a.IsPrimary})),i=new Set(zt(s,a=>t.contactSentWith(a)));if(i.size===0)return{prepared:e,linked:0};for(let a of i){t.roleLinkedFor(String(s[a].OpportunityId));let d=e.sourceIds[a];d!==void 0&&t.noteWritten(d,d)}let o=(a,d)=>!i.has(d);return{prepared:{...e,records:e.records.filter(o),sourceIds:e.sourceIds.filter(o),sources:e.sources.filter(o),unsettled:e.unsettled.length===e.records.length?e.unsettled.filter(o):e.unsettled},linked:i.size}}var ea=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,gn=200;function ta(n,e,t){let r=c=>{let l=t?.fields?.find(u=>u.name===c);return l?.nillable===!1&&l.defaultedOnCreate!==!0},s=[],i=new Set,o=new Set,a=0;for(let[c,l]of n){let u=e[c]==="insert"?l.filter(r):[];if(u.length>0){s.push(c);for(let f of u)i.add(f);continue}a++;for(let f of l)o.add(f)}let d=[];return a>0&&d.push(`${a} record(s) would be written without ${[...o].sort().join(", ")}: a lookup held an id from the source org that the target does not have, which the run learns from its first refusal and sends the record again without the lookups it did not settle.`),s.length>0&&d.push(`${s.length} record(s) would be refused: a lookup held an id from the source org that the target does not have, and sent again without the lookups the run did not settle, the record lacks ${[...i].sort().join(", ")}, which the target requires (REQUIRED_FIELD_MISSING).`),{refused:s,notes:d}}function na(n){return`${n} record(s) would be linked to the contact role the platform writes with their opportunity, for its contact, not written.`}function mn(n){let e=n.alreadyLinked,t=n.alreadyCopied-e;return{...t>0?{alreadyCopied:t}:{},...e>0?{alreadyLinked:e}:{}}}function ra(n,e){return e.alreadyCopied===0?n:{...n,skipped:n.skipped+e.alreadyCopied,...mn(e)}}function wi(n,e){return`What earlier runs of this configuration copied could not be read (${n}), and ${e.map(t=>t.objectApiName).join(", ")} ${e.length===1?"is":"are"} inserted: the records they copied would be copied a second time. Nothing was written.`}var sa="SYNC_EARLIER_UNREAD",ia=new Set(["account","contact"]);function ce(n){return n==="insert"||n==="upsert"}function oa(n,e,t=[],r=new Set){if(e<=0||!ce(n.operation))return;let s=n.objectApiName.toLowerCase(),i=new Set([...r].map(c=>c.toLowerCase())),o=t.flatMap(({referenceTo:c})=>c.map(l=>l.toLowerCase())),a=o.includes(s),d=o.some(c=>i.has(c));if(!(!a&&!d))return{...a?{within:e}:{},...d?{cycle:e}:{}}}function Si(n,e,t,r=new Map,s=new Set,i=new Map,o=new Map,a=new Set,d,c={}){let l=0,u=0,f=n.map(g=>{let w=g.objectApiName,M=e.get(w)??{rows:0},A=t.get(w)??new Set,O=A.size,E=Math.min(O,M.rows),F=Math.min([...A].filter(x=>a.has(x)).length,E);u+=F,l+=E-F;let $=(r.has(w)?0:i.get(w)?.rows??0)+(o.get(w)??0),T=c.keys?.get(w),v=Math.max(0,M.rows-O-$),j=oa(g,v,c.lookups?.get(w),c.later?.get(w));return{objectApiName:w,operation:g.operation,rows:v,...M.personAccounts!==void 0?{personAccounts:M.personAccounts}:{},batchSize:g.batchSize,...T?{overwriteKey:T}:{},...j?{lookupPasses:j}:{}}}),p=f.flatMap(g=>{let w=r.get(g.objectApiName);return w?[{...g,why:w.why,...w.key?{key:w.key}:{}}]:[]}),h=f.find(g=>g.objectApiName===X),y=h&&d!==void 0?Math.min(d,h.rows):0;h&&y>0&&(h.rows-=y);let m=f.filter(g=>!r.has(g.objectApiName)),b=m.filter(g=>g.rows>0&&ce(g.operation)&&s.has(g.objectApiName)).length,S=[...i.values()].filter(({objectApiName:g})=>!r.has(g)),R=d===void 0?aa(n,m):0,k=m.filter(g=>c.typed?.has(g.objectApiName)).length;return{objects:m,alreadyCopied:l,...u>0?{alreadyLinked:u}:{},...p.length>0?{unwritable:p}:{},...S.length>0?{heldBack:S}:{},...b>0?{readBack:b}:{},...R>0?{rolesByThePlatform:R}:{},...y>0?{rolesLinked:y}:{},...k>0?{describedAgain:k}:{}}}var Ee="Opportunity";function aa(n,e){let t=o=>e.find(a=>a.objectApiName===o&&ce(a.operation)),r=t(Ee),s=t(X);return!r||!s||n.find(o=>o.objectApiName===Ee)?.excludedFields.includes(oe)?0:Math.min(r.rows,s.rows)}function da(n,e,t){return{objectApiName:n.objectApiName,operation:n.operation,processed:0,success:0,failed:0,skipped:t,conflictCount:0,errors:[`${e.message} Left out of the run, as confirmed before it wrote.`]}}function bi(n,e,t){if(ce(e.operation))for(let r of t){let s=r?.Id;typeof s=="string"&&s!==""&&n.noteRefused(s,e.objectApiName)}}function Pt(n,e,t){let r=[];for(let[s,i]of t){let o=n.targetOf(i);o!==void 0?n.noteMatched(s,o):ce(e.operation)&&n.refusedObjectOf(i)!==void 0&&(n.noteRefused(s,e.objectApiName),r.push(s))}return r}function Ri(n,e,t){let r=nn(e,t),s=sn(n,{...e,prices:r});return t.length===0?s:{...s,processed:s.processed+t.length,failed:s.failed+t.length,errors:[...s.errors,rn(n.objectApiName,t.length)]}}function ki(n){let e=Wn(n.objects);return e.length>0?`${Gn(e)} Nothing was read or written.`:void 0}function Oi(n){let e=zn(n.objects);return e.length>0?`${qn(e)} Nothing was read or written.`:void 0}var Ai=class{deps;constructor(e){this.deps=e}async execute(e){let t=Date.now(),r=`sync-${Date.now()}`,s=[],i=ki(e);if(i!==void 0)throw new $e(i,{...se(e.id,r,[],t,"failure"),error:i},_n);let o=Oi(e);if(o!==void 0)throw new $e(o,{...se(e.id,r,[],t,"failure"),error:o},Un);let{ordered:a,order:d,refused:c,typed:l,lookups:u,keys:f}=await this.writeOrderOf(e.objects),p=fn(d),h=this.deps.queryTargetRows?l:new Set,y=this.deltaLoadOf(e),m=(C,P)=>new $e(C,{...se(e.id,r,[],t,"failure"),error:C},P),b;try{b=await this.planFiles(e,a,y)}catch(C){let P=C instanceof Error?C.message:String(C);throw new ae(P,se(e.id,r,[],t,"failure"),C)}if(b?.storage.shortfall)throw new ae(`${b.storage.shortfall} Nothing was written.`,{...se(e.id,r,[],t,"failure"),files:b.storage});let S=await this.earlierLinks(e),R=a.filter(C=>C.operation==="insert");if(S.unread!==void 0&&R.length>0)throw m(wi(S.unread,R),sa);let k;try{k=await this.alreadyCopiedOf(e,a,S.links)}catch(C){let P=`What earlier runs of this configuration copied could not be looked up in the target (${C instanceof Error?C.message:String(C)}), so nothing was written.`;throw new ae(P,{...se(e.id,r,[],t,"failure"),error:P},C)}let g=await this.countRun(e,a,y,this.deps.writeGate!==void 0);if(this.deps.writeGate&&"unread"in g){let C=`The records to write could not be counted (${g.unread}), so nothing was written.`+ln(g.unread);throw new ae(C,{...se(e.id,r,[],t,"failure"),error:C})}let w=new Map,M=this.standardPricebooksOnce(),A=this.currenciesOnce(),O=y===void 0?new Map:void 0;if(this.deps.writeGate&&"counted"in g){let C;try{C=await this.heldBackOfRun(e,a,c,u,y,S.links,k,M,A,O)}catch(B){let q=B instanceof Error?B.message:String(B);throw new ae(q,{...se(e.id,r,[],t,"failure"),error:q},B)}let P=Si(a,g.counted,k,c,h,C.heldBack,C.matched,S.linked,await this.rolesLinkedAtTheGate(e,a,c,C.heldBack,k,S.links,O),{keys:f,...this.deps.describeTargetFieldsAgain?{typed:l}:{},lookups:u,later:p}),{answer:D}=await this.deps.writeGate.hold(P);if(!D.go)throw m(D.message,D.code);for(let B of P.unwritable??[])w.set(B.objectApiName,B.rows)}let E=this.deps.leaseOfTheGate?.(),F=E&&E.assigned>0?await this.recordTypesReadAgain(a.map(C=>C.objectApiName).filter(C=>l.has(C)&&!w.has(C))):void 0,N=new Map,$=async()=>{let C=E;E=void 0,await C?.giveBack().catch(()=>{});for(let[P,D]of await this.readBackRecordTypes(N))for(let B=s.length-1;B>=0;B--)if(s[B].objectApiName===P){s[B]={...s[B],recordTypeGiven:D};break}},T=new ze(S.links),v=this.recordTypesOnce(),j=new Map,x=Gs(e),_=this.deps.idMap,z={sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId},H=Promise.resolve(),G,ne=(C,P,D)=>{if(!_)return;let B=ca(C.operation,P,D);for(let[q,Y]of[[B.written,!1],[B.linked,!0]])q.length!==0&&(H=H.then(()=>_.record(e.id,z,C.objectApiName,q,Y).catch(pe=>{G??=pe instanceof Error?pe.message:String(pe)})))},Te=0,Se=(C,P)=>{if(P.length===0)return;this.deps.creations?.deleted?.(C,P),Te+=P.length,T.noteDeleted(P);let D=_?.forget?.bind(_);D&&(H=H.then(()=>D(e.id,z,P).then(()=>{},B=>{G??=B instanceof Error?B.message:String(B)})))},V=this.deps.creations,be=new Map,ie=0,I=(C,P)=>{if(!V)return;let D=pn(C.operation,P);if(D.length===0)return;let B=C.objectApiName;V.noteUnanswered?V.noteUnanswered(B,D):V.note(B,D),be.set(B,(be.get(B)??0)+D.length)},W=(C,P)=>{V&&(V.note(C,[P]),ie++)},Z=!1,he=!1,Be=!1,Ji=async C=>{let P=await V?.flush();await H;let D=[];return S.unread!==void 0&&!Be&&(Be=!0,D.push(`What earlier runs of this configuration wrote could not be read (${S.unread}): a lookup at a record one of them wrote went as the source holds it.`)),P!==void 0&&!Z&&(Z=!0,D.push(`What this run created could not all be kept (${P}): removing the run may leave some of it in the target.`)),G!==void 0&&!he&&(he=!0,D.push(`Which record of the target each record this run wrote became could not all be kept (${G}): a later run may send a lookup at one of them as the source holds it.`)),D.length===0?C:{...C,errors:[...C.errors,...D]}},le=async C=>{s.push(await Ji(C))},Re=new Map,Vi=new Set((d?.cycles??[]).map(C=>C[C.length-1])),Cn=(C,P)=>{for(let D=s.length-1;D>=0;D--)if(s[D].objectApiName===C){s[D]=Xo(s[D],P,[...p.get(C)??[]]);return}},Xe=new Map,Xi=(C,P)=>{for(let D=s.length-1;D>=0;D--)if(s[D].objectApiName===C){s[D]={...s[D],errors:[...s[D].errors,P]};return}},Ft=(C,P,D)=>{for(let B=s.length-1;B>=0;B--){let q=s[B];if(q.objectApiName!==C)continue;if(!q.delta)return;let Y=(q.delta.lookupsOwed??0)+P;s[B]={...q,delta:{...q.delta,...D!==void 0?{recorded:D}:{},...Y>0?{lookupsOwed:Y}:{}}};return}},Zi=async()=>{for(let[C,P]of[...Re]){Re.delete(C),await this.deps.pauseGate?.whilePaused(this.deps.signal);let D=this.deps.signal?.aborted?{leftOut:tn(P.pending),unset:en(P.pending)}:await this.deps.dataSync.setLookups(P.objectConfig,P.pending,T,!0);"set"in D&&D.set&&V?.touched?.(C,D.set.records),Cn(C,D);let B=Xe.get(C);if(Xe.delete(C),D.unset===0){let q=B?.();q!==void 0&&Ft(C,0,q)}else Ft(C,D.unset)}},jt=()=>{for(let[C,P]of[...Re])Re.delete(C),Xe.delete(C),Cn(C,{leftOut:tn(P.pending)}),Ft(C,en(P.pending))},Ze=C=>{let P=Us(x,C.objectResults.some(Y=>Y.success>0)),D={...C,...b?{files:b.storage}:{},...P?{contactPoints:P}:{}},B=V?.overwrittenCount?.()??0,q=V?.deleted?Te:0;return!V||be.size===0&&ie===0&&B===0&&q===0?D:{...D,created:{runId:V.runId,objects:[...be].map(([Y,pe])=>({objectApiName:Y,count:pe})),files:ie,...B>0?{overwritten:B}:{},...q>0?{deleted:q}:{}}}},Pn="counted"in g?[...g.counted.values()].reduce((C,{rows:P})=>C+P,0):void 0,vt=this.isGrappeActive(Pn);vt&&this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:r,totalPartitions:a.length,totalRecords:Pn}});let In=()=>{if(!vt)return;let C=0,P=0;for(let D of s)C+=D.processed,P+=D.failed;this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:r,totalProcessed:C,totalFailed:P}})},ke=async(C,P)=>(jt(),await $(),In(),await V?.flush(),await H,Ze(ua(e.id,r,s,t,C,P))),Nt=0;for(let[C,P]of a.entries()){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return ke(a.slice(C));let D=c.get(P.objectApiName),B=w.get(P.objectApiName);if(D&&B!==void 0){let L=da(P,D,B);try{await this.noteLeftOutRefused(e,P,y,{links:T,...S.linked?{earlierLinked:S.linked}:{},recordTypes:v,currencies:A,currencyChangesById:j,standardPricebooks:M,...O?{gateReads:O}:{}},k.get(P.objectApiName))}catch(U){let me=U instanceof Error?U.message:String(U);throw await le({...L,errors:[...L.errors,me]}),jt(),new ae(me,Ze(se(e.id,r,s,t,"failure")),U)}await le(L);continue}let q=new it,{plan:Y,mark:pe}=await this.readPlan(e,P,y),Oe={changedSince:Y?.read==="delta"?Pe(Y.since):void 0,rows:0,cut:!1},Ae=(L,U)=>Y?{...L,delta:je(Y,Oe.rows,U)}:L,Qe=b?.objects.get(P.objectApiName),xt=Qe?new Map:void 0,Dt;try{Dt=await this.syncObject(e,P,q,{links:T,...S.linked?{earlierLinked:S.linked}:{},recordTypes:v,currencies:A,currencyChangesById:j,standardPricebooks:M,...x?{contactPoints:x}:{},later:p,...F?{recordTypesUnderTheLease:F}:{},createdWithoutRecordType:N,...O?{gateReads:O}:{}},Y?Oe:void 0,xt,V||_?(L,U)=>{I(P,L),ne(P,L,U)}:void 0,k.get(P.objectApiName),(p.get(P.objectApiName)?.size??0)>0?L=>{let U=Re.get(P.objectApiName);U?U.pending.push(...L):Re.set(P.objectApiName,{objectConfig:P,pending:L})}:void 0)}catch(L){if(L instanceof Q){let U=Ie(qe(P.objectApiName,P.operation,L.written,L.notes,L.lookupsLeftOut,L.writtenWithoutFields),q);return(U.processed>0||U.skipped>0)&&await le(Ae(U)),ke(a.slice(C))}throw await le(Ae(Ie({...It(P),failed:1,errors:[L instanceof Error?L.message:String(L)]},q))),jt(),new ae(L instanceof Error?L.message:String(L),Ze(se(e.id,r,s,t,"failure")),L)}if(Dt===gi){let L=Ie(It(P),q);return L.skipped>0&&await le(Ae(L)),ke(a.slice(C))}let J=Dt,En=!0;if(Qe&&xt&&e.files){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return await le(Ae(J)),ke(a.slice(C+1),Ci(P));let L=await ei({config:e,option:e.files,objectApiName:P.objectApiName,planned:Qe,written:xt,deps:this.deps.files,signal:this.deps.signal,waitIfPaused:()=>this.deps.pauseGate?.whilePaused(this.deps.signal)??Promise.resolve(),onCreated:W});if(J={...J,files:L.outcome,errors:[...J.errors,...L.notes]},En=L.outcome.failed===0&&L.outcome.pastRunCap===0&&L.unplanned===0,L.cancelled)return await le(Ae(J)),ke(a.slice(C+1),Ci(P))}let Ce;if(Y?.read==="delta"&&e.propagateDeletes===!0&&Oe.changedSince){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return await le(Ae(J)),ke(a.slice(C));try{Ce=await this.carryDeletions(P,Oe.changedSince,L=>Se(P.objectApiName,L))}catch(L){if(!(L instanceof Q))throw L;let U=qe(P.objectApiName,"delete",L.written);return await le(Ae({...J,errors:[...J.errors,...U.errors,...L.notes]},{deleted:U.success,deleteFailed:U.failed,notes:[],complete:!1})),ke(a.slice(C))}J={...J,errors:[...J.errors,...Ce.notes]}}let Tn=Oe.lookupsUnset??0,eo=J.failed===0&&En&&!Oe.cut&&Tn===0&&(Ce===void 0||Ce.deleteFailed===0&&Ce.error===void 0&&Ce.complete),Mn=(L,U,me)=>{let jn=Qe?.filesSeen;try{return this.deps.deltaStore?.record(e.id,{sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:P.objectApiName,watermark:L,fingerprint:U,recordedAt:new Date().toISOString(),...jn!==void 0?{filesSeen:jn}:{}}),L}catch(Lt){me(`The watermark could not be saved, so the next run reads from the previous one: ${Lt instanceof Error?Lt.message:String(Lt)}`);return}},Fn;if(Y&&pe!==null&&eo){let{fingerprint:L}=Y,U=P.objectApiName;Re.has(U)?Xe.set(U,()=>Mn(pe,L,me=>Xi(U,me))):Fn=Mn(pe,L,me=>{J={...J,errors:[...J.errors,me]}})}Y&&(J={...J,delta:je(Y,Oe.rows,Ce,Fn,Tn)}),await le(J),Vi.has(P.objectApiName)&&await Zi(),vt&&(Nt++,this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:`sync-partition-${Nt}`,percentage:Math.round(Nt/a.length*100),processedRecords:J.processed}}))}await $();let Qi=Pi(s);return In(),await V?.flush(),await H,Ze(se(e.id,r,s,t,Qi))}async recordTypesReadAgain(e){let t=this.deps.describeTargetFieldsAgain,r=new Map;return t&&await Promise.all(e.map(async s=>{try{r.set(s,(await t(s)).recordTypes??[])}catch{}})),r}async readBackRecordTypes(e){let t=this.deps.queryTargetRows,r=new Map;return await Promise.all([...e].map(async([s,{given:i,types:o,ids:a}])=>{if(!t||a.length===0){r.set(s,i);return}try{let d=await t(gs(s,a));r.set(s,{...i,readBack:hs(d,o)})}catch(d){let c=d instanceof Error?d.message:String(d);r.set(s,{...i,readBack:{read:0,types:[],unread:c}})}})),r}async earlierLinks(e){let t=this.deps.idMap;if(!t)return{};try{let r={sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId},s=await t.load(e.id,r);if(!s)return{};let i=await t.linked?.(e.id,r);return{links:s,...i!==void 0&&i.size>0?{linked:i}:{}}}catch(r){return{unread:r instanceof Error?r.message:String(r)}}}recordTypesOnce(){let e;return()=>{let t=this.deps.recordTypes;return t?(e??=t().catch(r=>{throw new Error(`The record types of the two orgs could not be read, so none of these records was sent: ${r instanceof Error?r.message:String(r)}`)}),e):Promise.resolve(void 0)}}currenciesOnce(){let e;return()=>{let t=this.deps.currencies;return t?(e??=t().catch(()=>{}),e):Promise.resolve(void 0)}}standardPricebooksOnce(){let e;return()=>{let t=this.deps.standardPricebooks;return t?(e??=t().catch(()=>{}),e):Promise.resolve(void 0)}}async pricesSettled(e,t,r){let s=e.objectApiName,i=e.operation!=="delete"&&mt(s,t.sources)?await r.standardPricebooks?.():void 0;i&&r.links.noteMatched(i.source,i.target);let o=i&&s===Me&&t.sources.some(hn)?await r.currencies():void 0;return yt(s,t,i,o,a=>r.links.refusedObjectOf(a)!==void 0)}deltaLoadOf(e){if(e.mode==="delta")return!this.deps.deltaStore||!this.deps.deltaReads?null:this.deps.deltaStore.load(e.id)}async readPlan(e,t,r){if(r===void 0)return{plan:null,mark:null};let s=We(e,t,r),i=this.deps.deltaReads;if(!i||s.read==="full"&&s.reason==="not_saved")return{plan:s,mark:null};try{return{plan:s,mark:await i.latestModstamp(t.objectApiName)}}catch{return{plan:{read:"full",reason:"no_modstamp",fingerprint:s.fingerprint},mark:null}}}async carryDeletions(e,t,r){let s=await this.tallyObjectDeletions(e,t);if("error"in s)return{deleted:0,deleteFailed:0,error:s.error,notes:[s.error],complete:!1};let{tally:i,notes:o}=s;if(i.ids.length===0)return{deleted:0,deleteFailed:0,notes:o,complete:!i.truncated};let a={...e,operation:"delete",fieldMappings:[],transformRules:[],addOnFields:[]},d;try{d=await this.deps.dataSync.write(a,i.ids.map(l=>({Id:l})))}catch(l){throw l instanceof Q&&r(mi(i.ids,l.written)),l}r(mi(i.ids,d.outcomes));let c=qe(e.objectApiName,"delete",d.outcomes,d.notes);return{deleted:c.success,deleteFailed:c.failed,notes:[...c.errors,...o],complete:!i.truncated}}async tallyObjectDeletions(e,t){let r=this.deps.deltaReads;if(!r)return{error:"Deletions need the source's recycle bin, and none was given."};let s=Ht(e);if("refused"in s)return{error:s.refused};let i=ot(e.where,t)??"";try{let o=await hr(r,e,s,i,a=>{if(s.sourceField==="Id")return a.Id;let d=this.deps.fieldMapping.apply(a,e.fieldMappings,e.excludedFields);return this.deps.transformPipeline.transformRecord(d,e)[s.keyField]});return{tally:o,notes:mr(o,s.keyField)}}catch(o){if(this.deps.signal?.aborted)throw new Q(e.objectApiName,[]);return{error:`The source's deletions could not be read, so none was carried; the next run looks for them again: ${o instanceof Error?o.message:String(o)}`}}}async countRun(e,t,r,s){let i=this.deps.countSource;if(!s&&!this.deps.grappeConfig?.enabled||!i)return{none:!0};let o=new Map;try{for(let a of t){let d=r===void 0?null:We(e,a,r),c=d?.read==="delta"?{changedSince:Pe(d.since)}:void 0,l=c?await i(e.sourceOrgId,a,c):await i(e.sourceOrgId,a);if(!Number.isFinite(l)||l<0)throw new Error(`the source answered no count of ${a.objectApiName}`);let u=s&&l>0&&this.deps.countPersonAccounts&&ia.has(a.objectApiName.toLowerCase())?await this.deps.countPersonAccounts(a,c):void 0;o.set(a.objectApiName,{rows:l,...u!==void 0&&u>0?{personAccounts:u}:{}})}}catch(a){return{unread:a instanceof Error?a.message:String(a)}}return{counted:o}}async alreadyCopiedOf(e,t,r){let s=new Map,i=this.deps.readSourceIds,o=this.deps.findInTarget;if(!r||r.size===0||!i||!o)return s;for(let a of t){if(a.operation!=="insert")continue;if(this.deps.signal?.aborted)break;let d=new Map;for(let f of await i(a)){let p=r.get(re(f));p!==void 0&&d.set(re(f),p)}if(d.size===0)continue;let c=await o(e.targetOrgId,a,"Id",[...new Set(d.values())]),l=new Set([...c.keys()].map(f=>f.slice(0,15))),u=new Set;for(let[f,p]of d)l.has(p.slice(0,15).toLowerCase())&&u.add(f);u.size>0&&s.set(a.objectApiName,u)}return s}async writeOrderOf(e){let t=this.deps.describeTargetFields,r=new Map,s=new Set,i=new Map;if(!t)return{ordered:[...e].sort((d,c)=>d.insertOrder-c.insertOrder),refused:r,typed:s,lookups:new Map,keys:i};let o=new Map,a=[];for(let d of e){if(d.operation==="delete"){a.push(d);continue}let c=await Ws(t,d.objectApiName,d.operation,d.externalIdField);"refused"in c&&r.set(d.objectApiName,c.refused);let l="target"in c&&c.target?_s(Bs(d,c.target),c.target):d;a.push(l),!("refused"in c)&&(l.operation==="update"||l.operation==="upsert"||l.objectApiName===X)&&i.set(d.objectApiName,xs(l.operation==="upsert"?l.externalIdField??"Id":"Id","target"in c?c.target:void 0)),"target"in c&&c.target&&(o.set(d.objectApiName,ui(l,c.target)),ce(d.operation)&&(c.target.recordTypes??[]).some(u=>!u.master)&&s.add(d.objectApiName))}return{...pi(a,o),refused:r,typed:s,lookups:o,keys:i}}async heldBackOfRun(e,t,r,s,i,o,a,d,c,l){let u=new Map,f=t.some(h=>ce(h.operation)&&(h.objectApiName===ge||h.objectApiName===Me));return r.size===0&&!f?{heldBack:new Map,matched:u}:{heldBack:await fi({ordered:t,lookups:s,leftOut:new Set(r.keys()),...o?{earlier:o}:{},copied:a,standardPricebooks:d,currencies:c,matched:u,read:async h=>{let y=i===void 0?null:We(e,h,i);if(y?.read==="delta")return this.deps.querySource(e.sourceOrgId,h,{changedSince:Pe(y.since)});let m=await this.deps.querySource(e.sourceOrgId,h);return l?.set(h.objectApiName,m),m}}),matched:u}}async rolesLinkedAtTheGate(e,t,r,s,i,o,a){let d=m=>t.find(b=>b.objectApiName===m),c=d(Ee),l=d(X);if(!c||!l||!ce(l.operation))return;if(!this.deps.queryTargetRows||c.excludedFields.includes(oe))return 0;if(!a||c.operation!=="insert")return;let u=m=>m.fieldMappings.length===0&&m.addOnFields.length===0&&m.transformRules.length===0;if(!u(c)||!u(l)||[Ee,X,Ut].some(m=>r.has(m)||s.has(m)))return;let p=await this.deps.describeTargetFields?.(Ee).catch(()=>{});if(!p)return;if(!p.creatable.has(oe))return 0;let h=async m=>{let b=a.get(m.objectApiName);if(b)return b;let S=await this.deps.querySource(e.sourceOrgId,m);return a.set(m.objectApiName,S),S},y=m=>typeof m.Id=="string"&&m.Id!==""?m.Id:void 0;try{let m=new Set([...o?.keys()??[]].map(re)),b=d(Ut);if(b&&ce(b.operation)&&t.indexOf(b)<t.indexOf(c))for(let g of await h(b)){let w=y(g);w&&m.add(re(w))}let S=g=>i.get(g)??new Set,R=new Map;for(let g of await h(c)){let w=y(g),M=g[oe];!w||typeof M!="string"||M===""||S(Ee).has(re(w))||!m.has(re(M))||R.set(re(w),M)}if(R.size===0)return 0;let k=(await h(l)).filter(g=>{let w=y(g);return w!==void 0&&!S(X).has(re(w))});return zt(k,g=>R.get(re(g))).length}catch{return}}isGrappeActive(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&e!==void 0&&e>=t.autoActivateThreshold)}async simulate(e){let t=ki(e);if(t!==void 0)throw new Error(t);let r=Oi(e);if(r!==void 0)throw new Error(r);let s=Date.now(),i=[],{ordered:o,order:a,refused:d,typed:c,lookups:l,keys:u}=await this.writeOrderOf(e.objects),f,p,h,y=await this.validationRulesOf(o),m=(F={})=>({configId:e.id,operationId:`sync-simulation-${s}`,direction:e.direction,conflictStrategy:e.conflictStrategy,objects:i,duration:Date.now()-s,timestamp:new Date().toISOString(),...f?{files:f.storage}:{},...y.unread!==void 0?{validationRulesUnread:y.unread}:{},...a?{writeOrder:a}:{},...p?{writeCheck:p}:{},...h!==void 0?{writeCheckUnread:h}:{},...F}),b=this.deltaLoadOf(e);try{f=await this.planFiles(e,o,b)}catch(F){return this.deps.signal?.aborted?m({cancelled:!0}):m({error:F instanceof Error?F.message:String(F)})}let S=await this.earlierLinks(e),R=o.filter(F=>F.operation==="insert");if(S.unread!==void 0&&R.length>0)return m({error:wi(S.unread,R)});let k;try{k=await this.alreadyCopiedOf(e,o,S.links)}catch(F){return this.deps.signal?.aborted?m({cancelled:!0}):m({error:F instanceof Error?F.message:String(F)})}let g=this.deps.writeGate,w=this.standardPricebooksOnce(),M=this.currenciesOnce(),A=b===void 0?new Map:void 0,O=g?await this.countRun(e,o,b,!0):void 0;if(g&&O&&"unread"in O&&(h=`${O.unread}${ln(O.unread)}`),g&&O&&"counted"in O)try{let F=await this.heldBackOfRun(e,o,d,l,b,S.links,k,w,M,A);p=await g.measure(Si(o,O.counted,k,d,this.deps.queryTargetRows?c:new Set,F.heldBack,F.matched,S.linked,await this.rolesLinkedAtTheGate(e,o,d,F.heldBack,k,S.links,A),{keys:u,typed:c,lookups:l,later:fn(a)}))}catch(F){h=F instanceof Error?F.message:String(F)}let E={links:new ze(S.links),...S.linked?{earlierLinked:S.linked}:{},recordTypes:this.recordTypesOnce(),currencies:M,currencyChangesById:new Map,standardPricebooks:w,later:fn(a),...A?{gateReads:A}:{}};for(let[F,N]of o.entries()){if(this.deps.signal?.aborted)return m({cancelled:!0});this.deps.onSimulationProgress?.(F,o.length,N.objectApiName);try{let $=await this.simulateObject(e,N,b,E,k.get(N.objectApiName),d.get(N.objectApiName)),T=f?.objects.get(N.objectApiName),{rules:v,onChange:j}=Ho(N.operation,y.byObject.get(N.objectApiName)??[]),x=[...$.notes,...T?.notes??[],...j.length>0?[Yo(j)]:[]];i.push({...$,...T?{files:T.outcome}:{},notes:x,...v.length>0?{validationRules:v}:{}})}catch($){return this.deps.signal?.aborted?m({cancelled:!0}):m({error:$ instanceof Error?$.message:String($),failedObject:N.objectApiName})}}if(p){let F=new Set([...p.objects.map(G=>G.objectApiName),...(p.rolesLinked??0)>0?[X]:[]]),N=i.filter(G=>F.has(G.objectApiName)).reduce((G,ne)=>G+(ne.operation==="delete"?ne.delete:ne.insert+ne.update),0),$={...p};delete $.rolesByThePlatform,delete $.rolesLinked;let T=i.filter(G=>F.has(G.objectApiName)).reduce((G,ne)=>G+(ne.writtenByThePlatform??0),0),v=(p.rolesLinked??0)-T,j=p.total+v,x=j-N,_={objectApiName:X,rows:0},z=$.objects.some(G=>G.objectApiName===X)?$.objects:[...$.objects,_],H=j>0&&N===0;p={...$,objects:z.map(G=>G.objectApiName===X?{...G,rows:Math.max(0,G.rows+v)}:G).filter(G=>G.rows>0),total:j,...T>0?{rolesLinked:T}:{},...x>0?{notWritten:x}:{},...H?{total:0}:{},...H&&$.verdict==="writes"?{verdict:"nothing"}:{}}}return m()}async validationRulesOf(e){let t=this.deps.readValidationRules,r=e.filter(i=>i.operation!=="delete").map(i=>i.objectApiName),s=new Map;if(!t||r.length===0)return{byObject:s};try{for(let{objectApiName:i,...o}of await t(r))s.set(i,[...s.get(i)??[],o]);return{byObject:s}}catch(i){return{byObject:s,unread:i instanceof Error?i.message:String(i)}}}async simulateObject(e,t,r,s,i,o){let a=this.deps.findInTarget;if(!a)throw new Error("A simulation needs to look records up in the target org.");let d=new it,{plan:c}=await this.readPlan(e,t,r),l={changedSince:c?.read==="delta"?Pe(c.since):void 0,rows:0,cut:!1},u=await this.prepare(e,t,d,c?l:void 0,i,s.gateReads,s.earlierLinked),f=u.records.length>0?await this.pricesSettled(t,u,s):void 0,p=f?{...u,...f}:u;if(o&&p.records.length>0){bi(s.links,t,p.sources);let I=f?Pt(s.links,t,f.standsFor):[];return yi({objectApiName:t.objectApiName,operation:t.operation,read:p.read,insert:0,update:0,delete:0,skipped:p.alreadyCopied,...mn(p),refused:p.records.length+I.length,conflicts:0,conflictFields:[],notes:[o.message]},p)}let h=Qo(t,p,s.links),y=h.prepared,m=null;if(y.records.length>0&&this.deps.describeTargetFields)try{let I=await this.deps.describeTargetFields(t.objectApiName);m=I.creatable.size>0?I:null}catch{m=null}let b=await hi(s,y.records,y.sources,t.objectApiName),S=$s({config:{...t,fieldMappings:[],addOnFields:[]},records:y.records,target:m,run:b}),R=S.sentAt.map(I=>y.records[I]),k=rr(t),g=new Map;if(k!==null){let I=new Map;for(let W of R){let Z=W[k],he=Fe(Z);he!==null&&I.set(he,Z)}I.size>0&&(g=await a(e.targetOrgId,t,k,[...I.values()]))}let w=R.map(I=>ir(t,I,g)),M=t.operation==="upsert"&&k!==null&&k.toLowerCase()!=="id"?ar(k,R.map(I=>Fe(I[k])),w,or(R.length,t.batchSize,this.deps.bulkThreshold??fe.REST_API_BATCH_SIZE)):void 0;for(let I of M?.updated??[])w[I]="update";let A=w.flatMap((I,W)=>(I==="insert"||I==="update")&&M?.refused.has(W)!==!0?[W]:[]),O=m?.fields!==void 0&&A.length>0?cr(t.objectApiName,A.map(I=>({payload:S.payloads[I],source:y.sources[S.sentAt[I]]??{},creates:w[I]==="insert"})),m.fields):{refused:new Set,notes:[],refusedFor:[]},E=new Set([...[...O.refused].map(I=>A[I]),...M?.refused??[]]),F=await this.lookupsTheTargetLacks(A.filter(I=>!E.has(I)),S.payloads,S.settled,m),N=ta(F,w,m);for(let I of N.refused)E.add(I);let $=A.filter(I=>w[I]==="insert"&&!E.has(I)),T=t.operation==="insert"?(m?.fields??[]).filter(I=>I.unique===!0&&I.createable):[],v=new Map;for(let I of T){let W=new Map;for(let Z of $){let he=S.payloads[Z][I.name],Be=Fe(he);Be!==null&&W.set(Be,he)}W.size!==0&&v.set(I.name,await a(e.targetOrgId,t,I.name,[...W.values()]))}let j=lr($.map(I=>S.payloads[I]),v);for(let I of j.refused)E.add($[I]);let x=new Set([...j.linked].map(I=>$[I])),_=R.flatMap((I,W)=>E.has(W)||x.has(W)?[]:[W]),z=new Set(_.map(I=>S.sentAt[I])),H=y.unsettled.filter((I,W)=>z.has(W)),G=dr({objectConfig:t,read:y.read,records:_.map(I=>R[I]),leftOut:d.counts(t.objectApiName),inTarget:g,simulated:_.map(I=>w[I]),conflicts:y.conflicts,unsettled:H,matchField:y.matchField,writable:m?.creatable??null}),ne=t.operation==="insert"||t.operation==="upsert",Te=I=>{let W=y.sources[I]?.Id;return typeof W=="string"&&W!==""?W:void 0},Se=[];if(t.operation!=="delete"){for(let{index:I}of S.held){let W=Te(I);W&&ne&&s.links.noteRefused(W,t.objectApiName)}if(S.sentAt.forEach((I,W)=>{let Z=Te(I);Z&&(E.has(W)||sr.has(w[W])?ne&&s.links.noteRefused(Z,t.objectApiName):s.links.noteWritten(Z,Z))}),t.objectApiName===Ee&&ne)for(let I of _){let W=Te(S.sentAt[I]),Z=S.payloads[I]?.[oe];w[I]!=="insert"||!W||typeof Z!="string"||Z===""||s.links.noteSentWithContact(W,Z)}f&&(Se=Pt(s.links,t,f.standsFor))}let V=Ds(t.objectApiName,_.flatMap(I=>{let W=w[I]==="insert"?S.withoutRecordType.get(S.sentAt[I]):void 0;return W?[W]:[]}),Ls(m?.recordTypes??[],b.recordTypes)),be=[...M?.refusedFor??[],...O.refusedFor,...j.refusedFor],ie={...G,skipped:G.skipped+x.size+y.alreadyCopied+h.linked,...mn(y),...h.linked>0?{writtenByThePlatform:h.linked}:{},...y.encryptedLeftOut?{encryptedLeftOut:[...y.encryptedLeftOut]}:{},...V?{recordTypeGiven:V}:{},refused:G.refused+S.held.length+E.size+Se.length,...be.length>0?{refusedFor:be}:{},notes:[...f?.standardMatched?[Ks]:[],...ms(f?nn(f,Se):[]).map(I=>`${I}.`),...h.linked>0?[na(h.linked)]:[],...G.notes,...M?.notes??[],...S.notes,...Se.length>0?[rn(t.objectApiName,Se.length)]:[],...S.currencies.map(I=>`${nr(I)}.`),...O.notes,...N.notes,...j.notes]};if(!c)return ie;if(c.read==="delta"&&e.propagateDeletes===!0&&l.changedSince){let I=await this.tallyObjectDeletions(t,l.changedSince);if("error"in I)return{...ie,notes:[...ie.notes,I.error],delta:je(c,l.rows,{deleted:0,deleteFailed:0,error:I.error})};let W=I.tally.ids.length;return{...ie,delete:ie.delete+W,notes:[...ie.notes,...I.notes],delta:je(c,l.rows,{deleted:W,deleteFailed:0})}}return{...ie,delta:je(c,l.rows)}}async lookupsTheTargetLacks(e,t,r,s){let i=this.deps.queryTargetRows,o=new Map;if(!i||!s?.fields||s.references.size===0)return o;let a=new Map,d=new Map;for(let u of e){let f=t[u]??{},p=[];for(let[h,y]of Object.entries(f)){if(h==="RecordTypeId"||!s.references.has(h)||r[u]?.has(h)||typeof y!="string"||!ea.test(y))continue;p.push({field:h,id:y});let m=s.fields.find(b=>b.name===h)?.referenceTo??[];for(let b of m)d.set(b,(d.get(b)??new Set).add(y))}p.length>0&&a.set(u,p)}if(a.size===0)return o;let c=new Set,l=new Set;for(let[u,f]of d){let p=[...f];for(let[h,y]of ee(p,gn).entries())try{let m=await i(`SELECT Id FROM ${ye(u)} WHERE Id IN (${y})`);for(let b of m){let S=b.Id;typeof S=="string"&&c.add(S.slice(0,15))}}catch{let m=h*gn;for(let b of p.slice(m,m+gn))l.add(b.slice(0,15))}}for(let[u,f]of a)f.some(({id:h})=>!c.has(h.slice(0,15))&&!l.has(h.slice(0,15)))&&o.set(u,f.map(({field:h})=>h).sort());return o}async noteLeftOutRefused(e,t,r,s,i){if(!ce(t.operation))return;let{plan:o}=await this.readPlan(e,t,r),a={changedSince:o?.read==="delta"?Pe(o.since):void 0,rows:0,cut:!1},d=await this.prepare(e,t,new it,o?a:void 0,i,s.gateReads,s.earlierLinked);if(d.records.length===0)return;let c=await this.pricesSettled(t,d,s);bi(s.links,t,c.sources),Pt(s.links,t,c.standsFor)}async syncObject(e,t,r,s,i,o,a,d,c){let l=await this.prepare(e,t,r,i,d,s.gateReads,s.earlierLinked),u=await this.rolesWrittenWithTheirOpportunity(t,l,s,a),f=u.prepared,p=w=>Zo(yi(ra(w,f),f),u.said);if(f.records.length===0)return p(Ie(It(t),r));let h=await this.pricesSettled(t,f,s),{records:y,sourceIds:m,sources:b}=h;if(y.length===0)return p(Ie(sn(It(t),h),r));let S={...await hi(s,y,b,t.objectApiName),...h.standardFirst>0?{standardFirst:h.standardFirst}:{}},R=()=>Pt(s.links,t,h.standsFor);if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return gi;if(o||a||c||i){let w=M=>{M.forEach((A,O)=>{let E=m[O];o&&A.success&&A.id&&E&&o.set(E,A.id)}),a?.(M,m)};try{let{outcomes:M,notes:A,currencies:O,lookupsLeftOut:E,writtenWithoutFields:F,lookupsToSet:N,lookupsUnset:$}=await this.deps.dataSync.write({...t,fieldMappings:[],addOnFields:[]},y,S);i&&$!==void 0&&(i.lookupsUnset=$),w(M);let T=R();return N&&c?.(N),p(Ie(Ri(qs(qe(t.objectApiName,t.operation,M,A,E,F),O),h,T),r))}catch(M){throw M instanceof Q&&w(M.written),M}}let k=await this.deps.dataSync.sync({...t,fieldMappings:[],addOnFields:[]},y,S),g=R();return p(Ie(Ri(k,h,g),r))}async rolesWrittenWithTheirOpportunity(e,t,r,s){let i=this.deps.queryTargetRows;if(e.objectApiName!==X||e.operation!=="insert"&&e.operation!=="upsert"||!i||!r.links.sentWithAContact||t.records.length===0)return{prepared:t};let o=g=>typeof g=="string"&&g!==""?r.links.targetOf(g):void 0,a=t.records.map((g,w)=>({OpportunityId:o(g.OpportunityId),[oe]:o(g[oe]),IsPrimary:t.sources[w]?.IsPrimary??g.IsPrimary})),d=await this.deps.describeTargetFields?.(X).catch(()=>{}),c=g=>g!=="Id"&&g!=="OpportunityId"&&g!==oe&&(d?.creatable.has(g)??!0),l=[...new Set(t.records.flatMap(g=>Object.keys(g)))].filter(c),u;try{u=await Xn(async g=>await i(g),a,g=>r.links.contactSentWith(g),l)}catch(g){return{prepared:t,said:{records:0,given:0,unread:g instanceof Error?g.message:String(g)}}}let{found:f,alike:p}=u;for(let g of p)r.links.roleLinkedFor(String(a[g].OpportunityId));let h=p.length>0?{alike:p.length}:{};if(f.size===0)return p.length>0?{prepared:t,said:{records:0,given:0,...h}}:{prepared:t};let y=[];for(let[g,w]of f){let M=Object.entries(t.records[g]??{}).filter(([A,O])=>c(A)&&O!==null&&O!==void 0&&String(w[A]??"")!==String(O));M.length>0&&y.push({Id:String(w.Id),...Object.fromEntries(M)})}let m=0,b;if(y.length>0)try{let g=await this.deps.dataSync.updateRecords(X,y,e.batchSize);y.forEach((w,M)=>{let A=g[M];A?.success?m++:b??=`${String(w.Id)}: ${A?.errors[0]??"not updated"}`})}catch(g){b=g instanceof Error?g.message:String(g)}let S=[],R=[];for(let[g,w]of f){let M=t.sourceIds[g],A=String(w.Id);r.links.roleLinkedFor(String(a[g].OpportunityId)),M!==void 0&&(r.links.noteWritten(M,A),S.push(M),R.push({success:!1,errors:[],existingId:A}))}s?.(R,S);let k=(g,w)=>!f.has(w);return{prepared:{...t,records:t.records.filter(k),sourceIds:t.sourceIds.filter(k),sources:t.sources.filter(k)},said:{records:f.size,given:m,...b!==void 0?{refusal:b}:{},...h}}}async prepare(e,t,r,s,i,o,a){let d=s?void 0:o?.get(t.objectApiName);d&&o?.delete(t.objectApiName);let c=s?await this.deps.querySource(e.sourceOrgId,t,{changedSince:s.changedSince,onBoundReached:()=>{s.cut=!0}}):d??await this.deps.querySource(e.sourceOrgId,t);s&&(s.rows=c.length);let l=t.externalIdField??"Id",u=this.deps.maskedSourceFields,p=(c.length>0&&u?await u(t.objectApiName).catch(()=>[]):[]).filter(O=>c.some(E=>Object.prototype.hasOwnProperty.call(E,O)));for(let O of c)for(let E of p)delete O[E];let h=p.length>0?{encryptedLeftOut:p}:{},y=t.operation==="insert"||t.operation==="upsert",m=y?r.keep(t.objectApiName,c):c,b=i&&i.size>0&&t.operation==="insert"?m.filter(O=>!(typeof O.Id=="string"&&i.has(re(O.Id)))):m,S=m.length-b.length,R=S>0&&a&&a.size>0?m.filter(O=>typeof O.Id=="string"&&i?.has(re(O.Id))===!0&&a.has(re(O.Id))).length:0;if(b.length===0)return{read:c.length,records:[],sourceIds:[],sources:[],conflicts:[],unsettled:[],matchField:l,alreadyCopied:S,alreadyLinked:R,...h};let g=b.map(O=>{let E=this.deps.fieldMapping.apply(O,t.fieldMappings,t.excludedFields);return this.deps.transformPipeline.transformRecord(E,t)}).map(O=>{let E=this.deps.fieldMapping.applyAddOns(O,t.addOnFields);return y?la(t.objectApiName,E):E}),w=g,M=[],A=t.operation==="upsert"||t.operation==="update";if(e.direction==="bidirectional"&&A){let O=await this.deps.queryTarget(e.targetOrgId,t);for(let E of O)for(let F of p)delete E[F];if(M=this.deps.conflictResolver.detectConflicts(g,O,l),M.length>0){let E=this.deps.conflictResolver.resolve(M,e.conflictStrategy),F=new Map(E.map(N=>[N.recordId,N.resolvedValues]));w=g.map(N=>{let $=String(N[l]??""),T=F.get($);return T?{...N,...T}:N})}}return{read:c.length,records:w,sourceIds:b.map(O=>typeof O.Id=="string"?O.Id:void 0),sources:b,conflicts:M,unsettled:g,matchField:l,alreadyCopied:S,alreadyLinked:R,...h}}async planFiles(e,t,r){let s=e.files;if(!s)return;let i=this.deps.files;if(!i)throw new ue("This session cannot copy files: it reads no file content or file storage. Nothing was read or written.");return Qs({config:e,option:s,deps:i,tie:(o,a)=>this.tieToTarget(e,o,a),objects:t.map(o=>{let a=r===void 0?null:We(e,o,r);return{objectConfig:o,...a?.read==="delta"?{changedSince:Pe(a.since),...a.filesSeen!==void 0?{filesSeen:a.filesSeen}:{}}:{}}})})}async tieToTarget(e,t,r){let s=this.deps.deltaReads,i=this.deps.files;if(!s||!i)return{held:new Map,refused:"the target cannot be asked"};let o=Ht(t);if("refused"in o)return{held:new Map,refused:o.refused};let a=t.objectApiName,d=new Map;if(o.sourceField==="Id")for(let u of r)d.set(u,u);else{let u=rt(a),f=ye(o.sourceField);for(let p of ee(r)){let h=await i.copy.queryRecords(e.sourceOrgId,`SELECT Id, ${f} FROM ${u} WHERE Id IN (${p})`);for(let y of h){let m=this.deps.fieldMapping.apply(y,t.fieldMappings,t.excludedFields),b=this.deps.transformPipeline.transformRecord(m,t)[o.keyField];typeof y.Id=="string"&&Fe(b)!==null&&d.set(y.Id,b)}}}if(d.size===0)return{held:new Map};let c=await s.targetIdsByKey(a,o.keyField,[...new Set(d.values())]),l=new Map;for(let[u,f]of d){let p=c.get(Fe(f))??[];p.length===1&&l.set(u,p[0])}return{held:l}}};function ca(n,e,t){let r=[],s=[];return n!=="insert"&&n!=="upsert"?{written:r,linked:s}:(e.forEach((i,o)=>{let a=t[o];if(a===void 0)return;if(i.success&&typeof i.id=="string"&&i.id!==""){r.push([a,i.id]);return}let d=zs(n,i);d!==void 0&&s.push([a,d])}),{written:r,linked:s})}function la(n,e){let t=Jn(n,e);if(t.length===0)return e;let r={...e};for(let s of t)delete r[s];return r}function Ie(n,e){let t=e.counts();return t.length===0?n:{...n,skipped:n.skipped+t.reduce((r,{count:s})=>r+s,0),errors:[...n.errors,...t.map(({why:r,count:s})=>Yn(s,r))]}}function It(n){return{objectApiName:n.objectApiName,operation:n.operation,processed:0,success:0,failed:0,skipped:0,conflictCount:0,errors:[]}}function ua(n,e,t,r,s,i){let o=Pi(t)==="failure"?"failure":"partial",a=s.map(c=>c.objectApiName),d=a.length>0?`Cancelled before ${a.join(", ")} ${a.length===1?"was":"were"} synced.`:"Cancelled.";return{...se(n,e,t,r,o),cancelled:!0,error:i?`${i} ${a.length>0?d:""}`.trim():d}}function Ci(n){return`Cancelled while the files of ${n.objectApiName} were copied: those copied stay in the target, the others are copied by the next run.`}function Pi(n){return n.length===0?"success":n.every(r=>r.failed>0&&r.success===0)?"failure":n.some(r=>r.failed>0||pa(r.delta)||(r.files?.failed??0)>0)?"partial":"success"}function pa(n){return n!==void 0&&(n.deleteFailed>0||n.deletionError!==void 0)}function se(n,e,t,r,s){let i=0,o=0,a=0,d=0;for(let c of t)i+=c.processed,o+=c.success,a+=c.failed,d+=c.skipped;return{configId:n,operationId:e,status:s,objectResults:t,totalProcessed:i,totalSuccess:o,totalFailed:a,totalSkipped:d,duration:Date.now()-r,timestamp:new Date().toISOString()}}var fa=2;async function Ii(n,e,t,r,s=()=>!1){let i=t.rows;if(!i||i.length!==e.length||t.stopped)return{result:t,unsent:[]};let o=[...i],a=[...e],d=e.map(()=>[]),c=[],l=!1;for(let f=0;f<fa&&!s();f++){let p=[],h=[],y=[];if(o.forEach((S,R)=>{if(S.id)return;let k=Kr(S.errorDetails,a[R],void 0);!k||k.some(({field:g})=>r.has(g))||(p.push(R),h.push(Hr(a[R],k)),y.push(k))}),p.length===0)break;let m;try{m=await n(h)}catch(S){let R=[...new Set(y.flat().map(({field:k})=>k))].sort();c.push(`${p.length} record(s) refused on ${R.join(", ")} could not be written again without ${R.length===1?"it":"them"}: ${K(S)}`);break}if(ga(m,h.length).forEach((S,R)=>{let k=p[R];o[k]=S,a[k]=h[R],d[k].push(...y[R])}),m.stopped){l=!0;break}}let u;return o.forEach((f,p)=>{!f.id||d[p].length===0||(u=Ue(u,{rows:1,fields:d[p].map(h=>({...h,rows:1}))}))}),{result:{successIds:o.flatMap(f=>f.id?[f.id]:[]),errors:o.flatMap(f=>f.id?[]:[f.error??"Unknown insert error"]),rows:o,...l?{stopped:!0}:{}},...u?{written:u}:{},unsent:c}}function ga(n,e){if(n.rows&&(n.rows.length===e||n.stopped))return n.rows.slice(0,e);let t=[...n.successIds.map(s=>({id:s})),...n.errors.map(s=>({error:s}))];return(e===1?t:t.map(s=>({...s,unmatched:!0}))).slice(0,e)}var ha=1e4,ma=5e5,Sn=200;function Tt(n){let e=Math.floor(ma/Math.max(1,n.fieldRules.length));return Math.max(Sn,Math.min(ha,e))}var Ei=class{deps;constructor(e){this.deps=e}async execute(e,t,r){let s=r??this.deps.generateId(),i=Date.now(),o=this.deps.validator.validate(e);if(!o.valid)return vi(e.id,s,o.errors.map(l=>l.message),this.deps.now());let a=await Ys(e.relations,{...this.deps.describeKeyPrefix?{keyPrefixOf:this.deps.describeKeyPrefix}:{},...this.deps.readPresentParentIds?{presentIds:this.deps.readPresentParentIds}:{}});if(a.length>0)return vi(e.id,s,a,this.deps.now());let d=e.objects.reduce((l,u)=>l+u.recordCount,0);return this.shouldActivateGrappe(d)?this.executeWithGrappe(e,t,s,i):this.executeSequential(e,t,s,i)}preview(e){return this.deps.planBuilder.build(e)}shouldActivateGrappe(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&this.deps.grappeAdapter&&e>=t.autoActivateThreshold)}reportProgress(e,t,r,s=0){let i=t.reduce((o,a)=>o+a.recordsCreated+a.recordsFailed,s);this.deps.onProgress?.({objectApiName:e,processedRecords:i,totalRecords:r,percentage:Math.round(i/Math.max(r,1)*100)})}async executeSequential(e,t,r,s){let i=Ti(e,this.platformRolesOf(t),this.deps.onRowIds),o=this.deps.referenceLinker.resolveInsertOrder(e.objects,i.relations),a=e.objects.reduce((d,c)=>d+c.recordCount,0);for(let d of o){if(this.deps.signal?.aborted)return this.stoppedResult(e,r,i,s);let c=await this.readyToWrite(d,i,a);if(!c)continue;let l={},u={successIds:[],errors:[]},f={result:u,unsent:[]},p=Mi(c),h=0,y=0,m=!1,b=Tt(c.config);for await(let S of this.slicesOf(c,i,b,l)){if(this.deps.signal?.aborted){m=!0;break}h>0&&this.reportProgress(d.objectApiName,i.objectResults,a,u.successIds.length+u.errors.length);let R=await this.insert(t,d,S,c,i);if(h++,Fi(p,c.config.rows,y,S.length,R.result),y+=S.length,Ea(f,R),R.result.stopped){m=!0;break}}if(h>0&&Et(i,d,wn(u,c),[...c.notes,...yn(f)],l,p),m)return this.stoppedResult(e,r,i,s)}return this.ended(e,r,i,s)}async ended(e,t,r,s){let i,o=!1;try{i=await this.deps.knowledge?.({ids:ba(r),results:r.objectResults})}catch(l){o=!0,i={skipped:`The articles were neither published nor linked: ${K(l)}`}}let a=ji(e.id,t,r.objectResults,s,this.deps.now());if(!i)return a;let d=o||[i.publish,i.links].some(l=>(l?.notDone.length??0)>0),c=this.deps.signal?.aborted===!0;return{...a,knowledge:i,...(d||c)&&a.status==="success"?{status:"partial"}:{},...c?{cancelled:!0}:{}}}async readyToWrite(e,t,r){let s=Wt(e.objectApiName,t.relations),i=Dn(e,t.relations).filter(m=>t.wroteNothing.has(m));if(i.length>0)return Ve(t,e.objectApiName,`Skipped: ${i.join(", ")} wrote no records, so there is nothing for ${e.objectApiName} to point at.`);let o=await this.closedObject(e.objectApiName);if(o)return Ve(t,e.objectApiName,o,e.optional===!0);this.reportProgress(e.objectApiName,t.objectResults,r);let a=Li(e,s),{config:d,dropped:c}=await Ni(a,this.deps.describeCreateableFields),l=await this.whyDropped(e.objectApiName,c),u=m=>m.fieldRules.length===0&&bn(m.rows).length===0;if(u(d)&&!u(a))return Ve(t,e.objectApiName,`Skipped: none of the fields the template names can be written (${l.join("; ")}).`);let{config:f,filled:p}=await xi(await this.withTheOrgsPicklistValues(d),s,this.deps.describeRequiredFields),h=await this.matchStandardPricebook(f,t);if(h)return Ve(t,e.objectApiName,h);let y;if(s){let m=await this.placeChildren(f,s,t);if("skipped"in m)return Ve(t,e.objectApiName,m.skipped);if(m.parentIds.length===0&&m.unwritten){let{lines:b,keys:S}=m.unwritten;return Et(t,e,{successIds:[],errors:b},[],{},S),null}y=m}return{relation:s,config:y?{...f,recordCount:y.parentIds.length,...y.rows?{rows:y.rows}:{}}:f,placed:y,...f.rows?{lengths:await this.fieldLengths(e.objectApiName)}:{},notes:[...l.map(m=>`Written without ${m}.`),...p.length>0?[`Written with ${p.join(", ")}, which this org requires and the template names no rule for.`]:[],...y?.notes??[]]}}async placeChildren(e,t,r){let{childObject:s,lookupField:i,parentObject:o}=t;if(!await this.orgTakesField(s,i))return{skipped:`Skipped: this org does not let a seed write ${s}.${i}, the lookup the relation fills.`};if(t.distribution.mode==="byKey")return Sa(e.rows??[],t,r.keys.get(o));let a=r.existingIds,d;if(t.parents.kind==="generated")d=a.get(o)??[];else if(t.parents.kind==="records")d=[...t.parents.ids];else{let f=this.deps.readExistingParentIds;if(!f)return{skipped:`Skipped: this run cannot read the ${o} records already in the org, so ${s} has nothing to point at.`};try{d=await f(o,t.parents.where,t.parents.limit)}catch(p){return{skipped:`Skipped: reading the ${o} records already in the org failed (${K(p)}), so ${s} has nothing to point at.`}}}if(d.length===0){let f=t.parents.kind==="existing"?t.parents.where?.trim():"";return{skipped:`Skipped: ${t.parents.kind==="generated"?`${o} wrote no records`:`no ${o} record in the org matches ${f?`"${f}"`:"the relation"}`}, so there is nothing for ${s} to point at.`}}let c=xn(t.distribution,d.length,this.deps.random),l=c.reduce((f,p)=>f+p,0),u=[];for(let[f,p]of c.entries())for(let h=0;h<p&&u.length<e.recordCount;h++)u.push(d[f]);return u.length===0?{skipped:`Skipped: the relation gives none of the ${d.length} ${o} records a ${s}.`}:{parentIds:u,notes:l>u.length?[`Stopped at ${u.length} ${s} records, the most the template asks for: the relation spreads ${l} over ${d.length} ${o} records.`]:[]}}async*slicesOf(e,t,r,s){let i=e.config.recordCount,o=Math.max(1,Math.floor(r)),a=0;do{let d=Math.max(0,Math.min(o,i-a)),c=Aa(e.config,e.relation)?Ca(d):await this.deps.fieldMapper.mapFields(d===i?e.config:{...e.config,recordCount:d},t.existingIds,l=>{s.aiFallback=Ia(s.aiFallback,l)},a,e.lengths);Pa(c,e.relation,e.placed,a),yield c,a+=d}while(a<i)}async insert(e,t,r,s,i){let o=f=>this.deps.insert(e,t.objectApiName,f,t.batchSize),a=t.objectApiName===X?await i.platformRoles.link(r):new Map,d=a.size>0?r.filter((f,p)=>!a.has(p)):r,c=d.length===0&&r.length>0?{successIds:[],errors:[],rows:[]}:await o(d),l=await Ii(o,d,c,ya(s),()=>this.deps.signal?.aborted===!0);t.objectApiName===Js&&i.platformRoles.opportunitiesWritten(d,l.result);let u=a.size>0?Ra(l,r.length,a):l;return c.notes&&c.notes.length>0?{...u,notes:c.notes}:u}platformRolesOf(e){return new Vs({orgId:e,readTarget:this.deps.readTarget,update:this.deps.update,stopped:()=>this.deps.signal?.aborted===!0})}async closedObject(e){if(!this.deps.objectAccess)return;let t;try{t=await this.deps.objectAccess(e)}catch{return}if(t.access==="createable")return;let r=t.reason?` (${t.reason})`:"";return t.access==="absent"?`Skipped: this org has no ${e} object${r}.`:`Skipped: the user this seed runs as may not create ${e} records${r}`+(t.reason?".":`: give that user Create on ${e} in a permission set.`)}async withTheOrgsPicklistValues(e){if(!this.deps.describePicklistValues||!e.fieldRules.some(i=>i.ruleType==="picklist_random"))return e;let t;try{t=await this.deps.describePicklistValues(e.objectApiName)}catch{return e}let r=!1,s=e.fieldRules.map(i=>{let o=t.get(i.fieldApiName),a=i.config.picklistValues;if(i.ruleType!=="picklist_random"||!o?.length||!a)return i;let d=a.filter(c=>o.includes(c));return d.length===a.length?i:(r=!0,{...i,config:{...i.config,picklistValues:d.length?d:[...o]}})});return r?{...e,fieldRules:s}:e}async matchStandardPricebook(e,t){if(!e.fieldRules.some(o=>nt(o,t.written))||t.existingIds.has(ge))return;let r=this.deps.readExistingParentIds,s=`${e.objectApiName} points at the org's standard price book`;if(!r)return`Skipped: ${s}, and this run cannot read it.`;let i;try{i=await r(ge,"IsStandard = true",1)}catch(o){return`Skipped: ${s}, and reading it failed (${K(o)}).`}if(i.length===0)return`Skipped: ${s}, and the org shows this user no standard price book (Pricebook2): give that user Read on Price Books in a permission set.`;t.existingIds.set(ge,i)}async orgTakesField(e,t){if(!this.deps.describeCreateableFields)return!0;try{return(await this.deps.describeCreateableFields(e)).has(t)}catch{return!0}}async whyDropped(e,t){if(t.length===0)return[];let r=new Set;try{this.deps.describeVisibleFields&&(r=await this.deps.describeVisibleFields(e))}catch{}let s;try{this.deps.describeComputedFields&&(s=await this.deps.describeComputedFields(e))}catch{}let i=t.filter(c=>r.has(c)&&s?.has(c)===!0),o=t.filter(c=>r.has(c)&&s?.has(c)!==!0),a=t.filter(c=>!r.has(c)),d=(c,l,u)=>c.length===1?l:u;return[...a.length>0?[`${a.join(", ")}: this org does not have ${d(a,"that field","those fields")}, or field-level security hides ${d(a,"it","them")} from the user SandForge connects as`]:[],...i.length>0?[`${i.join(", ")}: ${d(i,"a formula or auto-number field","formula or auto-number fields")}, which the org fills itself and no user sets: take ${d(i,"its rule","their rules")} out of the template`]:[],...o.length>0?[`${o.join(", ")}: ${d(o,"it exists","they exist")}, but the user SandForge connects as may not set ${d(o,"it","them")}`+(s!==void 0?`: give that user Edit on ${d(o,"it","them")} (field-level security, in a permission set)`:`: give that user Edit on ${d(o,"it","them")} (field-level security, in a permission set), unless it is a formula or auto-number field, whose rule comes out of the template`)]:[]]}async fieldLengths(e){if(!this.deps.describeFieldLengths)return new Map;try{return await this.deps.describeFieldLengths(e)}catch{return new Map}}async executeWithGrappe(e,t,r,s){let o=this.deps.grappeAdapter.partition(e),a=o.reduce((y,m)=>y+m.recordCount,0);this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:r,totalPartitions:o.length,totalRecords:a}});let d=Ti(e,this.platformRolesOf(t),this.deps.onRowIds),c=this.deps.referenceLinker.resolveInsertOrder(e.objects,d.relations),l=[],u=0,f=this.deps.grappeConfig?.grappeSize??2e3,p=()=>{let y=d.objectResults.reduce((b,S)=>b+S.recordsCreated,0),m=d.objectResults.reduce((b,S)=>b+S.recordsFailed,0);this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:r,totalProcessed:y,totalFailed:m}})},h=()=>(p(),this.stoppedResult(e,r,d,s));for(let y of c){if(this.deps.signal?.aborted)return h();let m=Math.ceil(y.recordCount/f),b=await this.readyToWrite(y,d,a);if(!b){u=this.settleUnusedPartitions(o,u,m,0);continue}let S={},R=Math.max(1,Math.ceil(b.config.recordCount/f)),k=0,g=0,w=[],M=[],A={result:{successIds:[],errors:[]},unsent:[]},O,E=Mi(b),F=0,N=-1;for await(let $ of this.slicesOf(b,d,f,S)){if(N++,this.deps.signal?.aborted){O=N;break}N>0&&this.reportProgress(y.objectApiName,d.objectResults,a,k+g);let T=Date.now(),v=o[u]?.id??this.deps.generateId(),j=await this.insert(t,y,$,b,d),x=j.result;Fi(E,b.config.rows,F,$.length,x),F+=$.length,j.written&&(A.written=Ue(A.written,j.written)),A.unsent.push(...j.unsent);for(let z of j.notes??[])(A.notes??[]).includes(z)||(A.notes=[...A.notes??[],z]);k+=x.successIds.length,g+=x.errors.length,w.push(...x.errors),M.push(...x.successIds),l.push({grappeId:v,status:x.errors.length===0?"success":x.successIds.length>0?"partial":"failure",processedRecords:$.length,successCount:x.successIds.length,failureCount:x.errors.length,errors:x.errors,duration:Date.now()-T}),u++;let _=Math.round(u/Math.max(o.length,1)*100);if(this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:v,percentage:_,processedRecords:k+g}}),x.stopped){O=N+1;break}}if(O!==void 0)return O>0&&Et(d,y,wn({successIds:M,errors:w},b),[...b.notes,...yn(A)],S,E),h();u=this.settleUnusedPartitions(o,u,m-R,k+g),Et(d,y,wn({successIds:M,errors:w},b),[...b.notes,...yn(A)],S,E)}return p(),this.ended(e,r,d,s)}stoppedResult(e,t,r,s){let i=ji(e.id,t,r.objectResults,s,this.deps.now());return{...i,status:i.status==="success"?"partial":i.status,cancelled:!0}}settleUnusedPartitions(e,t,r,s){let i=t;for(let o=r;o>0;o--){let a=e[i]?.id??this.deps.generateId();i++,this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:a,percentage:Math.round(i/Math.max(e.length,1)*100),processedRecords:s}})}return i}};function Ti(n,e,t){return{relations:n.relations??[],written:new Set(n.objects.map(r=>r.objectApiName)),existingIds:new Map,wroteNothing:new Set,keys:new Map,...t?{onRowIds:t}:{},platformRoles:e,objectResults:[]}}function ya(n){return new Set(["RecordTypeId",...n.relation?[n.relation.lookupField]:[],...n.config.fieldRules.filter(e=>e.ruleType==="reference").map(e=>e.fieldApiName)])}function yn(n){return[...n.notes??[],...n.written?[Yr(n.written)]:[],...n.unsent]}function Ve(n,e,t,r=!1){let s=Ta(e,t);return n.objectResults.push(r?{...s,optional:!0}:s),n.wroteNothing.add(e),null}function Et(n,e,t,r,s,i){i&&(n.keys.set(e.objectApiName,i),n.onRowIds?.(e.objectApiName,wa(i)));let o=n.platformRoles.resultOf(e.objectApiName),a=[...t.successIds,...o.linkedIds];n.existingIds.set(e.objectApiName,a),e.recordCount>0&&a.length===0&&n.wroteNothing.add(e.objectApiName),n.objectResults.push({objectApiName:e.objectApiName,recordsCreated:t.successIds.length,recordsFailed:t.errors.length,createdIds:t.successIds,errors:[...t.errors,...r,...o.notes],...s,...o.writtenByThePlatform?{writtenByThePlatform:o.writtenByThePlatform}:{}})}function wa(n){let e={};for(let[t,r]of n)"id"in r&&(e[t]=r.id);return e}function Sa(n,e,t){let{childObject:r,parentObject:s}=e;if(!t)return{skipped:`Skipped: ${r} is placed by key, and ${s} wrote no rows to place it under.`};let i=[],o=[],a=[],d=new Map;for(let c of n){let l=c.parentKey,u=l===void 0?void 0:t.get(l);if(u&&"id"in u){i.push(u.id),o.push(c);continue}let f=l===void 0?`it names no ${s} row`:`its ${s} ${l} ${u?u.why:`is no ${s} row this run wrote`}`;a.push(`${r} ${c.key} not written: ${f}.`),d.set(c.key,{why:`was not written, as ${f}`})}return{parentIds:i,notes:[],rows:o,unwritten:{lines:a,keys:d}}}function ba(n){let e=new Map;for(let[t,r]of n.keys){let s=new Map;for(let[i,o]of r)"id"in o&&s.set(i,o.id);e.set(t,s)}return e}function Mi(n){if(n.config.rows)return new Map(n.placed?.unwritten?.keys??[])}function Fi(n,e,t,r,s){if(!n||!e)return;let i=s.rows&&(s.rows.length===r||s.stopped)?s.rows:void 0;for(let o=0;o<r;o++){let a=e[t+o];if(!a)continue;let d=i?.[o];i?d?d.id&&d.unmatched?n.set(a.key,{why:"has no id this run can tell: the org did not say which of the ids it answered is its"}):d.id?n.set(a.key,{id:d.id}):n.set(a.key,{why:`was refused (${d.error??"Unknown insert error"})`}):n.set(a.key,{why:"was not sent: the run was stopped before it"}):n.set(a.key,{why:"has no id this run can tell: the insert did not answer record by record"})}}function wn(n,e){let t=e.placed?.unwritten?.lines??[];return t.length===0?n:{...n,errors:[...n.errors,...t]}}function Ra(n,e,t){let r=n.result.rows;if(!r)return n;let s=[],i=0;for(let o=0;o<e;o++){let a=t.get(o);if(a){s.push({id:String(a.Id)});continue}let d=r[i++];if(!d)break;s.push(d)}return{...n,result:{...n.result,rows:s}}}function bn(n){return[...new Set((n??[]).flatMap(e=>Object.keys(e.values)))]}function ka(n){return!n||n.length===0?[]:bn(n).filter(e=>n.every(t=>e in t.values))}function Oa(n,e){return e.size===0?[...n]:n.map(t=>({...t,values:Object.fromEntries(Object.entries(t.values).filter(([r])=>!e.has(r)))}))}async function Ni(n,e){if(!e)return{config:n,dropped:[]};let t;try{t=await e(n.objectApiName)}catch{return{config:n,dropped:[]}}let r=n.fieldRules.filter(a=>a.ruleType==="reference"||t.has(a.fieldApiName)),s=bn(n.rows).filter(a=>!t.has(a));if(r.length===n.fieldRules.length&&s.length===0)return{config:n,dropped:[]};let i=[...new Set([...n.fieldRules.filter(a=>!r.includes(a)).map(a=>a.fieldApiName),...s])],o=n.rows&&Oa(n.rows,new Set(s));return{config:{...n,fieldRules:r,...o?{rows:o}:{}},dropped:i}}async function xi(n,e,t){if(!t)return{config:n,filled:[]};let r;try{r=await t(n.objectApiName)}catch{return{config:n,filled:[]}}let s=new Set([...n.fieldRules.map(o=>o.fieldApiName),...ka(n.rows),...e?[e.lookupField]:[]]),i=[];for(let o of r){if(s.has(o.fieldApiName))continue;let a=$n(o);a.ruleType==="static"&&a.config.staticValue===void 0||i.push({fieldApiName:o.fieldApiName,fieldType:o.type,...a})}return i.length===0?{config:n,filled:[]}:{config:{...n,fieldRules:[...n.fieldRules,...i]},filled:i.map(o=>o.fieldApiName)}}async function Di(n,e,t){let r=Wt(n.objectApiName,e),{config:s}=await Ni(Li(n,r),t.describeCreateableFields),{config:i}=await xi(s,r,t.describeRequiredFields);return Tt(i)}function Li(n,e){if(!e)return n;let t=n.fieldRules.filter(r=>r.fieldApiName!==e.lookupField);return t.length===n.fieldRules.length?n:{...n,fieldRules:t}}function Aa(n,e){return e!==void 0&&n.fieldRules.length===0&&!n.rows}function Ca(n){return Array.from({length:n},()=>({}))}function Pa(n,e,t,r=0){if(!(!e||!t))for(let[s,i]of n.entries())i[e.lookupField]=t.parentIds[r+s]}function Ia(n,e){return n?{fields:[...new Set([...n.fields,...e.fields])],reason:n.reason==="no-answer"&&e.reason==="no-answer"?"no-answer":"short-answer"}:e}function Ea(n,e){for(let t of e.result.successIds)n.result.successIds.push(t);for(let t of e.result.errors)n.result.errors.push(t);e.written&&(n.written=Ue(n.written,e.written)),n.unsent.push(...e.unsent);for(let t of e.notes??[])(n.notes??[]).includes(t)||(n.notes=[...n.notes??[],t])}function Ta(n,e){return{objectApiName:n,recordsCreated:0,recordsFailed:0,createdIds:[],errors:[e]}}function ji(n,e,t,r,s){let i=t.reduce((d,c)=>d+c.recordsCreated,0),o=t.reduce((d,c)=>d+c.recordsFailed,0),a=t.some(d=>!d.optional&&d.recordsCreated===0&&d.recordsFailed===0&&d.errors.length>0);return{templateId:n,operationId:e,status:Ma(i,o,a),objectResults:t,totalRecordsCreated:i,totalRecordsFailed:o,duration:Date.now()-r,timestamp:s}}function Ma(n,e,t){return e===0&&!t?"success":n===0?"failure":"partial"}function vi(n,e,t,r){return{templateId:n,operationId:e,status:"failure",objectResults:[{objectApiName:"validation",recordsCreated:0,recordsFailed:0,createdIds:[],errors:t}],totalRecordsCreated:0,totalRecordsFailed:0,duration:0,timestamp:r}}var Fa=200,ja=1,va=1,Rn=2,Na=2,_i=3,xa=1,Da=200,La="Campaign";function Wi(n,e){if(!n)return;let t=e.toLowerCase();for(let[r,s]of n)if(r.toLowerCase()===t)return s}function $a(n,e){let t=Math.max(1,Math.floor(e)),r=[],s=0;do{let i=Math.max(0,Math.min(t,n-s));r.push(i),s+=i}while(s<n);return r}function Ba(n,e={}){let t=e.bulkThreshold??Fa,r=!1;return n.objects.flatMap(i=>{let o=Wi(e.duplicateRules,i.objectApiName),a=o===!1&&!ks.has(i.objectApiName),d=e.partition??e.slices?.get(i.objectApiName)??Tt(i);return $a(i.recordCount,d).map(c=>{let l=we([{rows:c,perCall:i.batchSize}]);if(c<=t||(r=!0,o===!0))return l;let u=we([{rows:c,bulk:!0}]);return a?u:Math.max(u,l)})}).reduce((i,o)=>i+o,0)+(r?ja:0)+we(Ga(n))}function _a(n,e={}){return Ba(n,e)+Wa(n,e)}function Wa(n,e={}){let t=new Set(n.objects.map(i=>i.objectApiName)),r=n.objects.some(i=>i.fieldRules.some(o=>nt(o,t))),s=(n.relations??[]).reduce((i,{parents:o})=>o.kind==="existing"?i+we([{rows:0,readRows:o.limit}]):o.kind==="records"?i+Math.ceil(o.ids.length/Hs):i,0);return va+n.objects.length+Rn+(t.has(La)?Rn+1:0)+s+(r?xa:0)+(e.typedFirst?Na:0)+_i+Math.max(0,e.sentBefore??0)+Math.max(0,e.automationRead??0)+Math.max(0,e.slicesRead??0)}async function gl(n,e,t){let r=new Map;if(t!==void 0)return r;for(let s of n.objects)s.recordCount<=Sn||r.set(s.objectApiName,await Di(s,n.relations,e));return r}function hl(n,e){return n?.enabled&&e.objects.reduce((r,s)=>r+s.recordCount,0)>=n.autoActivateThreshold?n.grappeSize:void 0}function Mt(n,e){return n.reduce((t,{objectApiName:r,rows:s,perCall:i,deletes:o})=>{if(s<=e.threshold)return t+we([{rows:s,perCall:i??e.perCall}]);let a=o===!0||Wi(e.duplicateRules,r)===!1?0:s;return t+we([{rows:s,bulk:!0},{rows:a}])},0)}function kn(n=0,e=0){return _i+Rn+Math.max(0,n)+Math.max(0,e)}function ml(n,e){let t=i=>n.find(o=>o.objectApiName===i)?.rows??0,r=Math.min(t("Opportunity"),t("OpportunityContactRole")),s=n.filter(({objectApiName:i})=>e.secondPass?.has(i)===!0).map(({rows:i})=>({rows:i}));return Mt(n,e)+(r>0?Math.ceil(r/Da)+Mt([{objectApiName:"OpportunityContactRole",rows:r}],e):0)+we(s)+kn(n.length,e.automationRead)}function Ga(n){let e=r=>n.objects.find(s=>s.objectApiName===r)?.recordCount??0,t=Math.min(e("OpportunityContactRole"),e("Opportunity"));return t>0?[{rows:t},{rows:t}]:[]}function Ua(n,e){return n.objects.reduce((t,r)=>t+Vr(r.objectApiName,{rows:r.recordCount,personAccounts:e.includes(r.objectApiName)?r.recordCount:0}),0)}function wl(n,e){let t=n.automationStarts??[],r=t.filter(a=>a.why!=="leftEmpty"),s=n.automationAtMostMB!==void 0&&n.automationAtMostMB>0&&r.length>0?` (${xe(n.automationAtMostMB)} MB of it at most: ${r.map(a=>`${$i(a)} ${Bi(a)}`).join("; ")})`:"",i=`data storage: about ${xe(n.estimateMB)} MB to write`+(n.automationMB!==void 0&&n.automationMB>0?`, about ${xe(n.automationMB)} MB of it for what the target's automation creates under them${s}`:""),o=t.filter(a=>a.why==="leftEmpty").map(a=>`; nothing counted for ${$i(a)}: it ${Bi(a)}`).join("");return n.verdict==="unread"?`${i}; what ${e} has left could not be read (${n.unread})${o}`:`${i}, ${e} has ${n.remainingMB} MB left of ${n.maxMB} MB`+ft(pt(n),e)+(n.verdict==="near"?": close to what it has left":"")+o}function $i(n){return`${n.name} on ${n.objectApiName}`}function Bi(n){let e=n.why==="leftEmpty"?"which the seed leaves empty":n.why==="automationMayFill"?"which the seed leaves empty and the target's automation may fill first":"which the seed may leave empty";return`starts only on a record whose ${n.fields.join(" and ")} ${n.fields.length===1?"is":"are"} filled, ${e}`}var Sl="SEED_STORAGE_EXCEEDED";async function bl(n,e,t,r,s,i={},o={},a={perRecord:[]}){let d={storageBytes:Ua(e,t)},c;try{c=await Zr(n)}catch(w){c={unread:K(w)}}let l=new Map(e.objects.map(w=>[w.objectApiName,w.recordCount])),u=w=>l.get(w)??0,f=Qt(a,u),p=a.atMost?Qt({perRecord:a.atMost},u):0,h=Ne(d,c,f),m={...h.verdict==="exceeds"&&p>0&&Ne(d,c,f-p).verdict!=="exceeds"?{...h,verdict:"near"}:h,...p>0?{automationAtMostMB:p/1048576}:{},...a.starts&&a.starts.length>0?{automationStarts:a.starts}:{}},b="unread"in c?await Qr(n).catch(w=>({unread:K(w)})):c.dailyApiRequests,S=dt({run:_a(e,o),...lt(s),...i},b),R=ut(s);if(R)return{check:m,api:S,refusal:R.message,refusedFor:"checkpoint",checkpointRefusal:R.refusal};let k=ps(m,r);if(k)return{check:m,api:S,refusal:`${k} Nothing was written.`,refusedFor:"storage"};let g=ct(S,r,at);return g?{check:m,api:S,refusal:g,refusedFor:"apiRequests"}:{check:m,api:S}}function Rl(n,e){let{check:t,api:r}=n,s=r.parts??{},i={checkpoint:s.checkpoint??0,mute:s.mute??0,readBack:s.readBack??0,deliverability:s.deliverability??0,fit:s.fit??0};return fs({storage:t.verdict==="unread"?{unread:t.unread}:{maxMB:t.maxMB,remainingMB:t.remainingMB,...t.uncountedWrites?{uncountedWrites:t.uncountedWrites}:{}},...e!==void 0?{withinMB:e}:{},api:r.verdict==="unread"?{unread:r.unread}:{max:r.max,remaining:r.remaining},otherRequests:i})}function za(n){return n==="insert"||n==="upsert"}function qi(n){return n==="update"||n==="upsert"}function qa(n){return Xr(n.objects.filter(e=>za(e.operation)).map(({objectApiName:e,rows:t,personAccounts:r})=>({objectApiName:e,rows:[],counted:{rows:t,...r!==void 0?{personAccounts:r}:{}}})))}var Ki=fe.REST_API_BATCH_SIZE;function Ka(n,e){return Mt(n.filter(t=>t.rows>0).map(({objectApiName:t,operation:r,rows:s,batchSize:i})=>({objectApiName:t,rows:s,...i!==void 0?{perCall:i}:{},...r==="delete"?{deletes:!0}:{}})),{threshold:e.bulkThreshold??Ki,...e.duplicateRules?{duplicateRules:e.duplicateRules}:{}})}var Ha="Opportunity",Ya="OpportunityContactRole",Ja=200,Va={update:{characters:gt,wide:!0},upsert:{characters:Ns(),wide:!0}},Xa=2,Gi=Array.from({length:Xa},()=>1),Za={characters:gt,wide:!1},Qa=1;function ed(n,e=[]){let t=Math.min(Math.max(0,n),5e4),r=e.reduce((s,i)=>s+Math.ceil(t/Math.max(1,i)),0);return Qa+Math.max(1,Math.ceil(t/qr))+r}function td(n,e){let[,...t]=Zn(e.length>0?e:["Id"]);return t.map(r=>Qn(n,r))}function An(n,e){let t=Math.max(1,Math.floor(e));return Array.from({length:Math.ceil(Math.max(0,n)/t)},(r,s)=>Math.min(t,n-s*t))}function Ui(n,e){if(n.rows<=(e.bulkThreshold??Ki))return An(n.rows,n.batchSize??fe.REST_API_BATCH_SIZE);let t=e.duplicateRules?[...e.duplicateRules].find(([r])=>r.toLowerCase()===n.objectApiName.toLowerCase())?.[1]:void 0;return[n.rows,...t===!1?[]:An(n.rows,fe.REST_API_BATCH_SIZE)]}function nd(n,e){let t=0,r=!1;for(let[d,c]of e.targetHeld??[])t+=ed(c,e.targetGroups?.get(d));for(let d of n.objects){if(d.rows<=0||d.operation==="delete")continue;t+=Gi.length;let{within:c=0,cycle:l=0}=d.lookupPasses??{};for(let[u,f]of[[c,[]],[l,[1]]]){if(u<=0)continue;let p=[...Ui({...d,rows:u},e),...f];r=!0,t+=p.length+ht(p,Za)}d.operation!=="update"&&d.operation!=="upsert"||(r=!0,t+=ht([...Ui(d,e),...Gi],d.overwriteKey??Va[d.operation]))}let s=d=>n.objects.find(c=>c.objectApiName===d&&(c.operation==="insert"||c.operation==="upsert")),i=s(Ha),o=s(Ya),a=i&&o?Math.min(i.rows,o.rows+(n.rolesLinked??0)):0;if(o&&a>0){let d=An(a,o.batchSize??fe.REST_API_BATCH_SIZE);r=!0,t+=Math.ceil(a/Ja)+d.length+ht(d,{characters:gt,wide:o.overwriteKey?.wide??!0})}return r&&(t+=1),e.leaseAssigns===!0&&(t+=Math.max(0,n.describedAgain??0)),t}function Hi(n){let e=new Map;for(let{objectApiName:t,operation:r}of n.objects){let s=e.get(t)??new Set;(r==="insert"||r==="upsert")&&s.add("insert"),(r==="update"||r==="upsert")&&s.add("update"),r==="delete"&&s.add("delete"),e.set(t,s)}return(t,r)=>e.get(t)?.has(r)===!0}function Yi(n,e){let t=new Set(e);return{...n,objectsRead:n.objectsRead.filter(r=>t.has(r)),objects:n.objects.filter(r=>t.has(r.objectApiName))}}function rd(n){let e;return t=>{if(e&&t.every(s=>e?.objects.includes(s)))return e.answer.then(s=>Yi(s,t));let r=n(t);return e??={objects:[...t],answer:r},r}}function Bl(n,e){if(n.direction==="bidirectional")return async t=>{let r=n.objects.find(i=>i.objectApiName===t),s=ot(r?.where,void 0);return e(`SELECT COUNT() FROM ${ye(t)}${s?` WHERE ${s}`:""}`)}}async function sd(n,e,t){let r=new Set((n.heldBack??[]).filter(({rows:o})=>o>0).map(({objectApiName:o})=>o)),s=new Map,i=new Map;for(let{objectApiName:o,operation:a,rows:d}of n.objects){if(!qi(a)||s.has(o)||d<=0&&!r.has(o))continue;let c=await e(o).catch(()=>5e4);s.set(o,Number.isFinite(c)&&c>=0?c:5e4);let l=await t?.(o).catch(()=>{}),u=l?td(o,l):[];u.length>0&&i.set(o,u)}return{held:s,groups:i}}async function zi(n,e){let t=qa(n),r=n.objects.filter(T=>T.rows>0).map(({objectApiName:T,rows:v})=>({objectApiName:T,rows:v})).sort((T,v)=>v.rows-T.rows||T.objectApiName.localeCompare(v.objectApiName)),s=r.reduce((T,v)=>T+v.rows,0),i=n.objects.filter(T=>qi(T.operation)).reduce((T,v)=>T+v.rows,0),o=Ne(t,{maxMB:0,remainingMB:0}),a=[],d,c=s>0?rd(e.readAutomation):e.readAutomation,l,u,f,p=Hi(n),h;if(s>0){let T=n.objects.filter(v=>v.rows>0).map(v=>v.objectApiName);if(h=await c(T).catch(v=>({unread:v instanceof Error?v.message:String(v)})),e.checkpointFirst){let v="objects"in h?Gt(h,void 0,p):{firing:[]};try{l=await e.checkpointFirst.scope(T,v)}catch(j){u=Jr(j)}}}let y={unread:"not read"};if(s>0){let T=await e.readStorage().catch(v=>({unread:v instanceof Error?v.message:String(v)}));y="unread"in T?await e.readApiBudget().catch(v=>({unread:v instanceof Error?v.message:String(v)})):T.dailyApiRequests,t.totalRows>0&&(o=Ne(t,T))}if(t.totalRows>0){let T=await ss({plan:t,objects:t.objects.map(v=>v.objectApiName),readAutomation:c,readLimits:e.readLimits});a=T.checks,d=T.unread}h!==void 0&&(f=await _r({...e.emails,read:h,writes:p,readDeliverability:e.readDeliverability,run:"sync"}));let m=s>0&&e.countTarget?await sd(n,e.countTarget,e.targetFields):void 0,b=cs(f?.ofRun),S=e.sentBefore?.(),R=s===0?0:S!==void 0?Math.max(0,S-(b.deliverability??0)):kn(0,h!==void 0?ds(h):0)+(m?.held.size??0),k=h!==void 0?Os(h):void 0,g=s===0?0:nd(n,{bulkThreshold:e.bulkThreshold,duplicateRules:k,leaseAssigns:(e.mutePlan?.()?.assign.length??0)>0,...m?{targetHeld:m.held,targetGroups:m.groups}:{}}),w=dt({run:Ka(n.objects,{bulkThreshold:e.bulkThreshold,duplicateRules:k})+R+g,...lt(l),...Gr(e.mutePlan?.()),...n.readBack!==void 0&&n.readBack>0?{readBack:n.readBack}:{},...b},y),M=e.confirmAboveRecords,A=M>0&&s>M?M:void 0,O=(n.unwritable??[]).map(({objectApiName:T,rows:v,why:j,key:x})=>({...x!==void 0?{key:x}:{},objectApiName:T,rows:v,why:j})),E=(n.heldBack??[]).map(({objectApiName:T,rows:v,parent:j,field:x,parents:_})=>({objectApiName:T,rows:v,parent:j,field:x,..._!==void 0?{parents:_.map(z=>({...z}))}:{}})),F=f?.gate,N=s===0?O.length>0?"refused":"writes":o.verdict==="exceeds"||w.verdict==="exceeds"||u!==void 0||l?.refusal!==void 0?"refused":A!==void 0||O.length>0||t.totalRows>0&&o.verdict!=="fits"||a.some(T=>T.verdict!=="fits")||d!==void 0||l!==void 0||F?.verdict==="asks"?"asks":"writes";return{check:{objects:r,total:s,alreadyCopied:n.alreadyCopied,...(n.alreadyLinked??0)>0?{alreadyLinked:n.alreadyLinked}:{},...i>0?{overwrites:i}:{},...(n.rolesByThePlatform??0)>0?{rolesByThePlatform:n.rolesByThePlatform}:{},...(n.rolesLinked??0)>0?{rolesLinked:n.rolesLinked}:{},...A!==void 0?{aboveRecords:A}:{},storage:o.verdict==="unread"?{verdict:"unread",estimateMB:o.estimateMB,unread:o.unread}:t.totalRows===0?{verdict:"fits",estimateMB:0}:{verdict:o.verdict,estimateMB:o.estimateMB,maxMB:o.maxMB,remainingMB:o.remainingMB},emails:a.map(T=>({limit:T.limit,emails:T.emails,verdict:T.verdict,...T.remaining!==void 0?{remaining:T.remaining}:{},...T.max!==void 0?{max:T.max}:{},...T.alertsCounted?{alertsCounted:!0}:{},objects:T.objects.map(({objectApiName:v,perRecord:j})=>({objectApiName:v,perRecord:j})),...T.unread!==void 0?{unread:T.unread}:{}})),...d!==void 0?{emailsUnread:d}:{},...F?.deliverability?{deliverability:F.deliverability}:{},...O.length>0?{unwritable:O}:{},...E.length>0?{heldBack:E}:{},...s>0?{apiRequests:w.verdict==="unread"?{verdict:"unread",estimate:w.estimate,unread:w.unread}:{verdict:w.verdict,estimate:w.estimate,remaining:w.remaining,max:w.max}}:{},verdict:N,...u!==void 0?{checkpointUnread:u}:{}},plan:t,storage:o,emails:a,api:w,...l!==void 0?{checkpoint:l}:{},...u!==void 0?{checkpointFailed:u}:{},...f!==void 0?{runEmails:f}:{},emailsAccepted:e.emails.accepted}}function id(n,e){let{check:t,storage:r,emails:s,plan:i,api:o}=n,a=[],d=t.unwritable??[];if(d.length>0&&(e.policy!=="ask"||t.total===0)&&a.push({code:"SYNC_TARGET_UNWRITABLE",message:dd(d,e.org,t.heldBack)}),t.total===0)return a;if(n.checkpointFailed!==void 0)a.push({code:ns,message:n.checkpointFailed});else{let l=ut(n.checkpoint);l&&a.push(l)}i.totalRows>0&&r.verdict==="exceeds"&&a.push({code:"SYNC_STORAGE_EXCEEDED",message:`The records to write take about ${xe(r.estimateMB)} MB of data storage, and ${e.org} has ${r.remainingMB} MB left of ${r.maxMB} MB${ft(pt(r),e.org)}: leave objects out, narrow their filters, or free data storage in ${e.org}. To copy a sample of the source that fits ${e.org} instead, use Forge with Depth ALL and a sample that fits the target (sandforge clone --depth all --fit share). Nothing was written.`});let c=ct(o,e.org,at);if(c&&a.push({code:es,message:c}),e.policy!=="ask"){let l=as(s,e.org);l&&a.push({code:"SYNC_EMAILS_EXCEEDED",message:`${l} Nothing was written.`});let u=n.runEmails?.gate,f=u?.stop;f&&a.push({code:f.code,message:Zt(f.message,"sync",e.emailsLiftedBy),...ve(u,!1)})}return a}async function od(n,e){let{check:t,storage:r,emails:s,api:i}=n,[o]=id(n,e);if(o)return{go:!1,...o};if(t.total===0)return{go:!0,asked:!1};let a=n.runEmails?.gate;if(e.policy!=="ask")return{go:!0,asked:!1,...ve(a,n.emailsAccepted)};let d=t.unwritable??[];if(t.verdict==="writes")return{go:!0,asked:!1,...ve(a,!1)};let c=$r(e.orgTier),l=s.filter(h=>h.verdict==="exceeds").map(is),u=s.filter(h=>h.verdict==="unread").map(os),f=e.confirm?await e.confirm({stage:"write",module:"sync",org:e.org,orgTier:e.orgTier,objects:t.objects,total:t.total,...t.aboveRecords!==void 0?{aboveRecords:t.aboveRecords}:{},...c!==void 0&&t.total>c?{largeVolume:c}:{},storage:us(r),counted:!0,...t.overwrites!==void 0?{overwrites:t.overwrites}:{},...l.length>0?{emails:l}:{},...u.length>0?{emailsUnread:u}:{},...t.emailsUnread!==void 0?{emailsUncounted:t.emailsUnread}:{},...t.alreadyCopied>0?{alreadyCopied:t.alreadyCopied}:{},...(t.alreadyLinked??0)>0?{alreadyLinked:t.alreadyLinked}:{},...(t.rolesLinked??0)>0?{rolesLinked:t.rolesLinked}:{},...d.length>0?{unwritable:d}:{},...t.heldBack!==void 0&&t.heldBack.length>0?{heldBack:t.heldBack}:{},...ts(i),...n.checkpoint!==void 0?{checkpoint:n.checkpoint}:{},...a?.confirmation}):"unavailable";if(f==="confirmed")return{go:!0,asked:!0,...ve(a,a?.verdict==="asks")};let p=ve(a,!1);return f==="declined"?{go:!1,code:"SYNC_WRITE_DECLINED",message:"The sync was cancelled before it wrote anything. Nothing was written.",...p}:{go:!1,code:"SYNC_CONFIRMATION_UNAVAILABLE",message:"The sync needed a confirmation before it wrote, and there was no one to ask. Nothing was written.",...p}}var ad={notInTarget:n=>`${n} has no such object, or the user the run writes as cannot see it`,notCreateable:n=>`the user the run writes as may not create its records in ${n}`,notUpdateable:n=>`the user the run writes as may not edit its records in ${n}`,unread:n=>`${n} did not describe it, so what it takes could not be told`,notAKey:(n,e)=>`its upsert matches on ${e??"a field"}, neither an External ID nor an idLookup field in ${n}`};function dd(n,e,t=[]){let r=n.map(({objectApiName:b,rows:S,why:R,key:k})=>`${b} (${S} record${S===1?"":"s"}): ${ad[R](e,k)}`).join("; "),s=n.length===1?"it":"them",i=n.filter(({why:b})=>b==="notAKey"),o=n.filter(({why:b})=>b!=="notAKey"),a=i.length>0&&o.length>0,d=b=>b.map(({objectApiName:S})=>S).join(" and "),c=`give the user SandForge writes as access to ${a?d(o):s} in ${e}`,l=`match ${a?`${d(i)} `:""}on an External ID field of ${e}`,u=a?`${c}, or ${l}`:i.length>0?`or ${l}`:`or ${c}`,f=new Set(n.map(({objectApiName:b})=>b)),p=({parent:b,field:S})=>`whose ${S} names ${/^[aeiou]/i.test(b)?"an":"a"} ${b} record `+(f.has(b)?"left out":"held back"),h=t.flatMap(({objectApiName:b,rows:S,parent:R,field:k,parents:g})=>(g??[{parent:R,field:k,rows:S}]).map(w=>`${w.rows} ${b} record${w.rows===1?"":"s"}, ${p(w)}`)).join("; "),y=n.filter(({why:b})=>b==="notInTarget"),m=y.length>0?` Where ${e} has not ${d(y)}, Compare deploys ${y.length===1?"it":"them"} from the source: tick Data Model, compare, then Deploy from Diff.`:"";return`${e} would take no record of ${n.length===1?"one object":`${n.length} objects`} the sync writes \u2014 ${r}.`+(h!==""?` Left out, ${s==="it"?"it holds":"they hold"} back ${h}.`:"")+` Leave ${s} out of the run, ${u}.${m} Nothing was written.`}function _l(n,e){return{measure:async t=>(await zi(t,n)).check,hold:async t=>{let r=await zi(t,n),s=await od(r,e);return{check:r.check,answer:await cd(r,s,n.checkpointFirst)}}}}async function cd(n,e,t){let r=n.checkpoint;if(!e.go||r===void 0||t===void 0)return e;let s=await rs(()=>t.take(r));return"stop"in s?{go:!1,...s.stop}:{...e,checkpoint:s.checkpoint}}function Wl(n,e){return e==="insert"||e==="update"||e==="delete"}function Gl(n,e,t,r,s){let i,o,a,d,c=n(async u=>{let f=i?.automation;return f&&u.every(p=>f.objectsRead.includes(p))?Yi(f,u):e(u)},()=>i?.plan),l=u=>{if(!Wr(u))throw u;return{go:!1,code:u.code,message:u.message}};return{gate:{measure:u=>c.measure(u),hold:async u=>{let f=u.objects.filter(h=>h.rows>0).map(h=>h.objectApiName);if(!i&&f.length>0){d=await e(f).catch(h=>({unread:h instanceof Error?h.message:String(h)}));try{i=await t(d),a=i.muted}catch(h){return{check:await c.measure(u),answer:l(h)}}}let p=await c.hold(u);if(p.answer.go&&i?.prepared&&!o){try{o=await i.prepared.acquire(r),a=o.outcome}catch(R){let{checkpoint:k}=p.answer;return{check:p.check,answer:{...l(R),...k?{checkpoint:k}:{}}}}let{checkpoint:h,emails:y}=p.answer,{deliverability:m}=p.check,b=Hi(u),S=i.plan&&d&&"objects"in d?ls({planned:m?.senders??[],held:Kn(Gt(d,Br(i.plan,o.outcome),b),{writes:b}),...m?{reading:m.reading}:{},accepted:y?.accepted===!0,target:s.target,run:"sync"}):void 0;if(S)return{check:p.check,answer:{go:!1,code:S.code,message:Zt(S.message,"sync",s.liftedBy),...h?{checkpoint:h}:{},...y?{emails:y}:{}}}}return p}},release:async()=>(o&&(a=await o.release()),a),lease:()=>{let u=o;if(u)return{assigned:u.outcome.assigned.length,giveBack:async()=>(a=await u.release(),a)}}}}export{St as a,At as b,md as c,yd as d,Td as e,Md as f,Fd as g,ri as h,So as i,Wd as j,Gd as k,Xd as l,Zd as m,Qd as n,ec as o,Io as p,Eo as q,tc as r,Fo as s,nc as t,rc as u,jo as v,ae as w,$e as x,ui as y,pi as z,oc as A,No as B,xo as C,ac as D,pn as E,Sc as F,ci as G,Ai as H,Ei as I,Wi as J,_a as K,gl as L,hl as M,Mt as N,kn as O,ml as P,Ua as Q,wl as R,Sl as S,bl as T,Rl as U,Bl as V,zi as W,id as X,od as Y,dd as Z,_l as _,cd as $,Wl as aa,Gl as ba};
|
package/lib/chunk-6O222PW6.mjs
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
-
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
-
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
-
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
-
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-OM5NORJG.mjs";import"./chunk-Q7GIJBCD.mjs";import"./chunk-YHR4WQPR.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-YDXMTWAT.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-26POJDIT.mjs";import"./chunk-KB4ZHM4Q.mjs";import"./chunk-23SEDORH.mjs";import"./chunk-W6PN6TJG.mjs";import"./chunk-3Q353S2R.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-RHNTHGNU.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-Q7TLC3I2.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-D4GF4FAB.mjs";import"./chunk-CVHNXJH3.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-M6K34KGF.mjs";import"./chunk-TNT27RBG.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-S42RBRH2.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-PMWAFDUB.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{h as ACTIVE_DUPLICATE_RULES_SOQL,a as FORMULAS_BOUND,c as FORMULAS_IN_COMPOSITES_BOUND,b as FORMULA_REQUESTS_BOUND,o as TargetGapReader,i as bypassesOf,j as callsEstimateOf,f as fieldLabelsSoql,p as gapAnsweredBy,d as gapFieldOf,r as gapLines,q as gapsWithAnswers,l as readActiveValidationRules,m as readValidationRuleBypasses,k as toolingQueriesOver,n as toolingValidationRules,g as validationFormulaSoql,e as validationRulesSoql};
|
package/lib/chunk-6ZLKIT3H.mjs
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
-
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
-
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
-
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
-
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a,b,c,d}from"./chunk-JGZPD4IM.mjs";import"./chunk-L2E5WBGD.mjs";import"./chunk-H33DVU3D.mjs";import"./chunk-KGU4SVIT.mjs";import"./chunk-LC3NDW4N.mjs";import"./chunk-KB4ZHM4Q.mjs";import"./chunk-23SEDORH.mjs";import"./chunk-W6PN6TJG.mjs";import"./chunk-3Q353S2R.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-RHNTHGNU.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-Q7TLC3I2.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-D4GF4FAB.mjs";import"./chunk-CVHNXJH3.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-M6K34KGF.mjs";import"./chunk-TNT27RBG.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-S42RBRH2.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-PMWAFDUB.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{b as auditRequestsOf,a as auditsAskedOf,c as findingsOf,d as readAudits};
|
package/lib/chunk-7QYHEHMA.mjs
DELETED
|
@@ -1,9 +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{i as E}from"./chunk-WXDLQT2O.mjs";import{b as j,c as S,e as U,m as O,n as P,o as C}from"./chunk-HIDW7FNV.mjs";import{h as B}from"./chunk-M6K34KGF.mjs";import{da as N}from"./chunk-TNT27RBG.mjs";import{Nd as A,Vd as y}from"./chunk-PMWAFDUB.mjs";var h="No record was written.",l=e=>e.toLocaleString("en-US"),D=e=>e.toDelete.createdSince+e.toDelete.broughtBackSince+e.toDelete.comesBackWithParent,$=e=>e.toBringBack.inBin+e.toBringBack.withParent+e.toBringBack.deletedWhileTaken,k=e=>e.toRecreate??0,v=e=>e.toBringBack.carriers??0;function L(e){let n=t=>D(t)+t.toGiveBack.records+$(t)+v(t)+k(t)>0,o=e.objects.filter(n).map(t=>t.objectApiName),a=e.files;return a!==void 0&&a.unlink+a.relink+a.updateLinks>0&&o.push(B),o}function M(e){return e.objects.reduce((n,o)=>({toDelete:n.toDelete+D(o),toGiveBack:n.toGiveBack+o.toGiveBack.records,toBringBack:n.toBringBack+$(o),toRecreate:n.toRecreate+k(o)}),{toDelete:0,toGiveBack:0,toBringBack:0,toRecreate:0})}function te(e,n){let o=new Set(n.objects),a=new Map(n.acts.map(i=>[i.objectApiName,i]));return{...E(e,o),objects:e.objects.filter(i=>o.has(i.objectApiName)||a.has(i.objectApiName)).map(i=>{let s=a.get(i.objectApiName),r=o.has(i.objectApiName);return{...i,toDelete:{createdSince:s?.toDelete??0,broughtBackSince:0,comesBackWithParent:0},toGiveBack:{...i.toGiveBack,records:s?.toGiveBack??0},toBringBack:{inBin:s?.toBringBack??0,withParent:0,deletedWhileTaken:0,...r&&i.toBringBack.carriers!==void 0?{carriers:i.toBringBack.carriers}:{}},toRecreate:s?.toRecreate??0,cannotUndo:r?i.cannotUndo:[],unexplained:r?i.unexplained:0}}),undoCannot:[...n.undoCannot]}}function W(e){let n=e.objects.filter(t=>D(t)+v(t)>0).map(t=>t.objectApiName),o=e.files,a=(t,i)=>i>0?[...t,B]:t;return{bringBack:e.objects.filter(t=>$(t)+v(t)>0).map(t=>t.objectApiName),recreate:a(e.objects.filter(t=>k(t)>0).map(t=>t.objectApiName),o?.relink??0),giveBack:a(e.objects.filter(t=>j(t)+U(t)>0).map(t=>t.objectApiName),o?.updateLinks??0),setToDraft:e.objects.filter(t=>S(t)>0).map(t=>t.objectApiName),delete:a(n,o?.unlink??0)}}function z(e){return new Set(e.map(n=>`${n.objectApiName}
|
|
8
|
-
${n.kind}
|
|
9
|
-
${n.name}`)).size}function ne(e,n,o,a=!1){let t=(c,f)=>(c??[]).includes(f),i=o.filter(c=>!t(n.recreate,c)),s=o.filter(c=>N[c]!==void 0&&!t(n.giveBack,c)),r=new Set(e.objectsRead),d=[...i,...s];return{fired:y(e,{recreate:i,giveBack:s}),blind:d.length>0&&(!a&&A(e.unread)||d.some(c=>!r.has(c)))}}var T={limit:e=>`this step's limit of ${l(e)}`,mutes:!1,lift:{acceptAutomation:"turn on muteAutomation in the step for what a bypass keeps quiet, or acceptAutomation to let it run, and confirm it again to rewind all the same",acceptEmails:"turn on acceptEmails in the step and confirm it again to rewind all the same",acceptNoUndo:"turn on acceptNoUndo in the step and confirm it again to rewind all the same",acceptRecreate:"turn on acceptRecreate in the step and confirm it again to rewind all the same",acceptUnseen:"turn on acceptUnseen in the step and confirm it again to rewind all the same",maxRecords:"preview the rewind, then raise the step's maxRecords to what it rewinds and confirm it again",refuseWhenActive:"run it once they are done, or turn off refuseWhenActive in the step and confirm it again"}},oe={...T,lift:{...T.lift,acceptAutomation:"turn on acceptAutomation in the step to let what no bypass keeps quiet run, and confirm it again to rewind all the same"}},H=[{reason:"onlyWithParent",words:"Salesforce undeletes them only with their parent, which stays"},{reason:"deletedBeforeParent",words:"deleted before a record they point at, which the rewind deletes next, Salesforce cannot bring them back after that"}],Y="Add --accept-emails to rewind all the same";function q(e,n,o,a,t){let{automation:i,deliverability:s}=n;if(!i||!s)return;let r=W(n.diff),{refusal:d}=C({act:"rewind",orgName:e,automation:i,steps:r,accepted:o.acceptEmails===!0,mayMute:t,...P({automation:i,steps:r}),reading:s.reading});if(!d)return;let c=a.acceptEmails;return{...d,message:d.message.replace(Y,`${c.charAt(0).toUpperCase()}${c.slice(1)}`)}}function ie(e,n,o,a,t="the user SandForge connects as",i=!1){return _(e,n,o,a,t,i)[0]}function _(e,n,o,a,t="the user SandForge connects as",i=!1){let s=[],{diff:r,automation:d}=n;if(r.undoCannot.length>0&&!o.acceptNoUndo){let u=H.flatMap(({reason:w,words:g})=>{let R=r.undoCannot.filter(b=>(b.reason??"onlyWithParent")===w);if(R.length===0)return[];let F=R.reduce((b,G)=>b+G.count,0),I=[...new Set(R.map(b=>b.objectApiName))].join(", ");return[`Undo couldn't bring back ${l(F)} ${I} record(s) this rewind deletes: ${g}.`]});s.push({code:"NO_UNDO",message:`${u.join(" ")} Rewind refused; ${a.acceptNoUndo}. ${h}`})}let c=r.objects.filter(u=>k(u)>0);if(c.length>0&&!o.acceptRecreate){let u=c.reduce((w,g)=>w+k(g),0);s.push({code:"RECREATE",message:`${l(u)} ${c.map(w=>w.objectApiName).join(", ")} record(s) deleted since are no longer in the recycle bin, or Salesforce keeps them there for good: this rewind makes them again from the checkpoint, with new Ids. Anything outside Salesforce that names their old Ids \u2014 an integration, a link, a report filter \u2014 no longer finds them. Rewind refused; ${a.acceptRecreate}. ${h}`})}let f=r.unseen??[];if(f.length>0&&o.acceptUnseen!==!0){let u=f.map(({objectApiName:w,children:g,records:R})=>`Deleting ${l(R)} ${w} record(s) created since also deletes what ${t} can't see under them in ${g.join(", ")}: Rewind can't count those.`);s.push({code:"UNSEEN",message:`${u.join(" ")} Rewind refused; ${a.acceptUnseen}. ${h}`})}if(!d)return s;let m=K(e,n,o,a),p=q(e,n,o,a,i);return[...s,...m?[m]:[],...p?[p]:[]]}function K(e,n,o,a){let{diff:t,automation:i,emailsUncounted:s}=n;if(!i||o.acceptAutomation)return;let r=W(t),d=y(i,r);if(d.length===0&&!A(i.unread)&&s===void 0)return;let c=[...new Set(d.map(u=>u.objectApiName))],f=(r.recreate??[]).some(u=>u!==B)?"makes them again, ":"",m=d.length>0?`${z(d)} flow(s), trigger(s) or rule(s) of ${c.join(", ")} run as the rewind brings records back, ${f}gives them their values back or deletes them`:"what runs as the rewind writes could not all be read, so automation may run",p=s!==void 0?`The emails it sends as the rewind writes were not counted against its daily limits, as what sends them was not read (${s}). `:"";return{code:"AUTOMATION",message:`${e}: ${m}. ${p}Rewind refused; ${a.acceptAutomation}. `+h}}var x=e=>e.slice(0,15);async function ae(e){return(await J(e))[0]}async function J(e){let{orgName:n,preview:o,bounds:a,words:t}=e,{diff:i}=o;if(L(i).length===0)return[];let s=[],r=M(i),d=r.toDelete+r.toGiveBack+r.toBringBack+r.toRecreate;if(a.maxRecords!==void 0&&d>a.maxRecords){let f=[`${l(r.toDelete)} to delete`,`${l(r.toGiveBack)} to give back`,`${l(r.toBringBack)} to bring back`,...r.toRecreate>0?[`${l(r.toRecreate)} to make again`]:[]];s.push({code:"TOO_MANY_TO_REWIND",message:`The rewind of ${n} would rewind ${l(d)} records (${f.join(", ")}), past ${t.limit(a.maxRecords)}. Rewind refused; ${t.lift.maxRecords}. `+h})}if(a.refuseWhenActive&&i.activeLastHour.length>0){let f=new Set((await e.writers()).map(x)),m=new Set(i.activeLastHour.map(x).filter(p=>!f.has(p)));if(m.size>0){let p=m.size===1?"1 person":`${l(m.size)} people`;s.push({code:"PEOPLE_ACTIVE",message:`${p} other than the user the rewind writes as changed records of the checkpoint's objects in ${n} in the hour before the rewind read it: it would take their work back. Rewind refused; ${t.lift.refuseWhenActive}. `+h})}}let c=O("rewind",o.emails??[],n);return[...s,..._(n,o,e.accepted,t.lift,e.user,t.mutes),...c?[c]:[]]}function re(e,n,o){let a=n.map(t=>`${t.objectApiName} (${l(t.records)})`).join(", ");return{code:"UNDELETABLE_UNATTENDED",message:`The user SandForge connects to ${e} as may not delete the ${a} record(s) this rewind deletes. With nobody to ask whether to delete the rest, the deletion was left untouched. Give the user Delete on those objects, or rewind from the Checkpoints page, which asks. `+(o?"What the rewind's first pass wrote stays: its result says what, and Undo takes it back.":h)}}function se(e,n){return{code:"NOT_CONFIRMED",message:`Rewind step "${e}" has `+(n?"not been confirmed since it was changed":"never been confirmed")+": open it and type the org's alias, or, for an org that has none, its name or Organization Id. "+h}}export{L as a,M as b,te as c,W as d,z as e,ne as f,T as g,oe as h,ie as i,ae as j,J as k,re as l,se as m};
|