sandforge 1.83.0 → 1.84.1
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-23SEDORH.mjs +11 -0
- package/lib/{chunk-I5C4O3VA.mjs → chunk-24RFOFYT.mjs} +1 -1
- package/lib/chunk-26POJDIT.mjs +7 -0
- package/lib/{chunk-WJAZ5LHL.mjs → chunk-2AZQHBEF.mjs} +1 -1
- package/lib/{chunk-IHGYJZZ2.mjs → chunk-2HVOZUM4.mjs} +1 -1
- package/lib/{chunk-3V4YH5KO.mjs → chunk-2JDAOWUW.mjs} +1 -1
- package/lib/{chunk-BNKT3R3F.mjs → chunk-2METQHGG.mjs} +1 -1
- package/lib/chunk-2WFIVO4F.mjs +13 -0
- package/lib/chunk-2YHZBUZE.mjs +7 -0
- package/lib/{chunk-7DPHZWA4.mjs → chunk-326AJTIU.mjs} +14 -14
- package/lib/{chunk-UIR77ZJD.mjs → chunk-36JOHEJL.mjs} +1 -1
- package/lib/chunk-3PVRGTVK.mjs +7 -0
- package/lib/{chunk-2WMKJVD2.mjs → chunk-3Q353S2R.mjs} +1 -1
- package/lib/chunk-3TZSBHEY.mjs +7 -0
- package/lib/{chunk-T36DZJPH.mjs → chunk-43TOMFV4.mjs} +1 -1
- package/lib/{chunk-XAMMIPZ4.mjs → chunk-4CVUUVGJ.mjs} +1 -1
- package/lib/{chunk-6YC2ELCU.mjs → chunk-4EOHEDFP.mjs} +1 -1
- package/lib/{chunk-ZB5E7NHU.mjs → chunk-4JE4BYXK.mjs} +1 -1
- package/lib/{chunk-JREKJO3D.mjs → chunk-54WZUS7J.mjs} +1 -1
- package/lib/{chunk-CGZGL6VT.mjs → chunk-5CRLRHOJ.mjs} +1 -1
- package/lib/{chunk-UOHZW2L4.mjs → chunk-5IZTFMJM.mjs} +1 -1
- package/lib/{chunk-6VOQFISN.mjs → chunk-5M5FQ7RP.mjs} +1 -1
- package/lib/{chunk-U4YFYSF3.mjs → chunk-5SMWFNE7.mjs} +1 -1
- package/lib/{chunk-HQZUQXDC.mjs → chunk-5XTUSN72.mjs} +1 -1
- package/lib/chunk-6I6TWNV5.mjs +7 -0
- package/lib/{chunk-QLRWU3MB.mjs → chunk-6JWWSDM6.mjs} +1 -1
- package/lib/chunk-6O222PW6.mjs +7 -0
- package/lib/{chunk-J3TIHLWG.mjs → chunk-6PD6K7LP.mjs} +1 -1
- package/lib/{chunk-ISAUCWYK.mjs → chunk-6QE6R6RL.mjs} +1 -1
- package/lib/{chunk-2KTGDYUH.mjs → chunk-6WX5ZU7Q.mjs} +1 -1
- package/lib/{chunk-XAUQXYPW.mjs → chunk-6YL7BNYD.mjs} +1 -1
- package/lib/chunk-6ZLKIT3H.mjs +7 -0
- package/lib/{chunk-XKFHTBAB.mjs → chunk-7QYHEHMA.mjs} +1 -1
- package/lib/chunk-7SQSWVAU.mjs +9 -0
- package/lib/{chunk-NNV7IGM7.mjs → chunk-7UVKIWKV.mjs} +1 -1
- package/lib/{chunk-RZKJQOOC.mjs → chunk-7WATA4SB.mjs} +1 -1
- package/lib/{chunk-DMT5SCO3.mjs → chunk-7YNM6KFZ.mjs} +1 -1
- package/lib/{chunk-TMIESDE5.mjs → chunk-A3MYSOOC.mjs} +1 -1
- package/lib/chunk-AL4C3GFT.mjs +7 -0
- package/lib/chunk-B3FBHVNN.mjs +21 -0
- package/lib/{chunk-CDWZGQAJ.mjs → chunk-B63POIPQ.mjs} +1 -1
- package/lib/{chunk-YEVB7LVK.mjs → chunk-BAWCOKRW.mjs} +1 -1
- package/lib/{chunk-FVLFO2S6.mjs → chunk-BBRWFKS5.mjs} +1 -1
- package/lib/chunk-BEA27DLS.mjs +7 -0
- package/lib/chunk-BRY3PLIZ.mjs +7 -0
- package/lib/chunk-CBH3TOWK.mjs +341 -0
- package/lib/{chunk-7V2UYZ6S.mjs → chunk-CPQIZGG5.mjs} +1 -1
- package/lib/chunk-CVHNXJH3.mjs +7 -0
- package/lib/{chunk-ZOSESZ22.mjs → chunk-D4GF4FAB.mjs} +1 -1
- package/lib/chunk-DGDRQRCW.mjs +7 -0
- package/lib/{chunk-2N73W63D.mjs → chunk-DPMRIMUC.mjs} +1 -1
- package/lib/chunk-DUN2EPRC.mjs +7 -0
- package/lib/chunk-E3A3LOCY.mjs +7 -0
- package/lib/{chunk-KWAVSZ2B.mjs → chunk-EAC5QCE3.mjs} +1 -1
- package/lib/{chunk-JUOQUG7U.mjs → chunk-EC72TIEG.mjs} +1 -1
- package/lib/chunk-EPFCERGL.mjs +7 -0
- package/lib/{chunk-6KOUYHEY.mjs → chunk-ETDCBLGU.mjs} +1 -1
- package/lib/{chunk-2R6GFNKF.mjs → chunk-F3AQW6IU.mjs} +1 -1
- package/lib/{chunk-AHUGG3WU.mjs → chunk-FITPY3L4.mjs} +1 -1
- package/lib/chunk-FNJ4SGWO.mjs +7 -0
- package/lib/{chunk-EOQON3E5.mjs → chunk-FP7CYB2F.mjs} +1 -1
- package/lib/{chunk-262TP6UU.mjs → chunk-GKY2JMHY.mjs} +1 -1
- package/lib/{chunk-JBWJ6UEZ.mjs → chunk-GMIGWR6U.mjs} +1 -1
- package/lib/{chunk-OS5GE52G.mjs → chunk-GNRSF65U.mjs} +1 -1
- package/lib/chunk-GOOVPVWX.mjs +7 -0
- package/lib/{chunk-DB5RVDC5.mjs → chunk-GWZRR3MM.mjs} +1 -1
- package/lib/{chunk-SX6QWYCQ.mjs → chunk-H2BHESDA.mjs} +2 -2
- package/lib/chunk-H4CGM6YO.mjs +7 -0
- package/lib/{chunk-NFEBX75O.mjs → chunk-HCGXK7G7.mjs} +1 -1
- package/lib/{chunk-4X5D3MSV.mjs → chunk-HIDW7FNV.mjs} +1 -1
- package/lib/chunk-HSBXRQTI.mjs +7 -0
- package/lib/chunk-HUZPBE47.mjs +7 -0
- package/lib/{chunk-F5SBGJWW.mjs → chunk-HV7VPEXP.mjs} +1 -1
- package/lib/chunk-I6E6T6YY.mjs +7 -0
- package/lib/chunk-IUM4NFKI.mjs +10 -0
- package/lib/chunk-IVFVNNGB.mjs +37 -0
- package/lib/{chunk-L4MSL4U7.mjs → chunk-IZGCEOYO.mjs} +1 -1
- package/lib/{chunk-E3RQ575Y.mjs → chunk-J3DND3BC.mjs} +1 -1
- package/lib/{chunk-MJD6CPZZ.mjs → chunk-JAEDM4SI.mjs} +1 -1
- package/lib/chunk-JCFBFF4Y.mjs +7 -0
- package/lib/{chunk-U2CTKIPE.mjs → chunk-JE6SCT6R.mjs} +1 -1
- package/lib/{chunk-XJICAOAQ.mjs → chunk-JGZPD4IM.mjs} +1 -1
- package/lib/{chunk-XCJUNX63.mjs → chunk-JKJ74BX5.mjs} +1 -1
- package/lib/{chunk-WAYQLQAD.mjs → chunk-JLSIWO4Z.mjs} +1 -1
- package/lib/{chunk-D7XUNWWU.mjs → chunk-JSAJS3MY.mjs} +1 -1
- package/lib/chunk-JTJK2D36.mjs +7 -0
- package/lib/{chunk-OTJH6AEA.mjs → chunk-KAZS5Z6W.mjs} +1 -1
- package/lib/chunk-KB4ZHM4Q.mjs +10 -0
- package/lib/{chunk-N2HYG3BL.mjs → chunk-KGU4SVIT.mjs} +1 -1
- package/lib/{chunk-FKCIGJOI.mjs → chunk-KJWFYBMU.mjs} +2 -2
- package/lib/{chunk-KXUOHACP.mjs → chunk-KZTZDC7H.mjs} +1 -1
- package/lib/{chunk-S4PRKKGC.mjs → chunk-L2E5WBGD.mjs} +1 -1
- package/lib/{chunk-X2XZQ434.mjs → chunk-L53JWJ3S.mjs} +1 -1
- package/lib/{chunk-CQAFVEKP.mjs → chunk-LA4KIATH.mjs} +6 -6
- package/lib/chunk-LC3NDW4N.mjs +7 -0
- package/lib/{chunk-4V3QO7HF.mjs → chunk-LKTNQEBS.mjs} +1 -1
- package/lib/chunk-M2ABR4JM.mjs +7 -0
- package/lib/{chunk-3CM7LAPE.mjs → chunk-M4BLK6HJ.mjs} +1 -1
- package/lib/{chunk-Z3MGN42K.mjs → chunk-M6K34KGF.mjs} +1 -1
- package/lib/{chunk-TUPZY2QJ.mjs → chunk-MDMPJEV3.mjs} +1 -1
- package/lib/{chunk-BVZ5H3N4.mjs → chunk-MJZU3U5O.mjs} +68 -63
- package/lib/{chunk-OUU47Y7A.mjs → chunk-MSIEU5MR.mjs} +1 -1
- package/lib/{chunk-QQDZQCO2.mjs → chunk-N4WPCWJO.mjs} +1 -1
- package/lib/{chunk-MTM4KG3T.mjs → chunk-NCZKWSC7.mjs} +1 -1
- package/lib/{chunk-Y7YUNRKK.mjs → chunk-NED4MBIM.mjs} +1 -1
- package/lib/{chunk-QKJXIY6L.mjs → chunk-NOBQTEQD.mjs} +1 -1
- package/lib/{chunk-WBELLGNE.mjs → chunk-NSQWI7ZY.mjs} +1 -1
- package/lib/{chunk-BPHTA6KP.mjs → chunk-O677VOGO.mjs} +1 -1
- package/lib/chunk-OFTT7J2M.mjs +7 -0
- package/lib/{chunk-JH4ZTVQN.mjs → chunk-OLCVHL7I.mjs} +1 -1
- package/lib/chunk-OM5NORJG.mjs +7 -0
- package/lib/{chunk-QP3JLFIO.mjs → chunk-OMNMLKDT.mjs} +1 -1
- package/lib/{chunk-WABXKL4N.mjs → chunk-OPMO6I45.mjs} +1 -1
- package/lib/{chunk-7ZBDACVG.mjs → chunk-OUZQPYT3.mjs} +1 -1
- package/lib/chunk-OVNMB6Q2.mjs +7 -0
- package/lib/{chunk-DKDKCGXV.mjs → chunk-PAXNWTYK.mjs} +1 -1
- package/lib/{chunk-GLN4PI5P.mjs → chunk-PBY2O6OF.mjs} +1 -1
- package/lib/chunk-PEDQPM2P.mjs +926 -0
- package/lib/chunk-PH7SP4YK.mjs +21 -0
- package/lib/{chunk-BT43WSOS.mjs → chunk-PMN4PAC3.mjs} +1 -1
- package/lib/chunk-PMWAFDUB.mjs +48 -0
- package/lib/chunk-PPLVFX6N.mjs +7 -0
- package/lib/{chunk-L3I6DAHX.mjs → chunk-PR3XCSPO.mjs} +1 -1
- package/lib/{chunk-WZN36ACK.mjs → chunk-PR42EZSR.mjs} +1 -1
- package/lib/{chunk-NDFFIJL5.mjs → chunk-PWRJRL5U.mjs} +1 -1
- package/lib/{chunk-NS6ONPWL.mjs → chunk-Q7GIJBCD.mjs} +1 -1
- package/lib/chunk-Q7TLC3I2.mjs +7 -0
- package/lib/{chunk-ALBY5SOH.mjs → chunk-QAFPQ3YB.mjs} +1 -1
- package/lib/{chunk-KKS2KFBT.mjs → chunk-QKEKG2LD.mjs} +1 -1
- package/lib/{chunk-OOIDCHBQ.mjs → chunk-QO53K5W2.mjs} +2 -2
- package/lib/{chunk-HVX2AFYW.mjs → chunk-QTG6LUZT.mjs} +1 -1
- package/lib/{chunk-K7G3W7XH.mjs → chunk-RE7RYF3B.mjs} +1 -1
- package/lib/{chunk-JIPT5FUD.mjs → chunk-RGBGUCJA.mjs} +1 -1
- package/lib/{chunk-GT5ZKU6V.mjs → chunk-RGUQOSBU.mjs} +1 -1
- package/lib/{chunk-VXZ5PTOM.mjs → chunk-RHNTHGNU.mjs} +1 -1
- package/lib/chunk-RKTFFCNS.mjs +7 -0
- package/lib/chunk-RMFU4BAL.mjs +28 -0
- package/lib/{chunk-DNQKVCUV.mjs → chunk-ROV3QXEF.mjs} +11 -11
- package/lib/chunk-RT47RKLY.mjs +7 -0
- package/lib/{chunk-ISOSTAJR.mjs → chunk-S42RBRH2.mjs} +1 -1
- package/lib/{chunk-27BBEGUD.mjs → chunk-SI267LYR.mjs} +1 -1
- package/lib/chunk-T3G6VZNS.mjs +7 -0
- package/lib/chunk-TNT27RBG.mjs +7 -0
- package/lib/chunk-UBIKR5VO.mjs +7 -0
- package/lib/chunk-UI3JQVRU.mjs +8 -0
- package/lib/{chunk-RVCPQVKM.mjs → chunk-UIOMAX56.mjs} +1 -1
- package/lib/chunk-UX3BVH2Y.mjs +7 -0
- package/lib/{chunk-L4RJX7DG.mjs → chunk-VCUXCK36.mjs} +1 -1
- package/lib/chunk-VINGECAJ.mjs +10 -0
- package/lib/chunk-VOXJHJIE.mjs +7 -0
- package/lib/chunk-W6PN6TJG.mjs +7 -0
- package/lib/{chunk-D6JT4PAB.mjs → chunk-WAPSSYMT.mjs} +1 -1
- package/lib/{chunk-7BQMBXKX.mjs → chunk-WUUKFE2U.mjs} +1 -1
- package/lib/chunk-WWTCWWZI.mjs +7 -0
- package/lib/chunk-WXDLQT2O.mjs +10 -0
- package/lib/{chunk-TCEXCHXR.mjs → chunk-WY5V5PR3.mjs} +1 -1
- package/lib/chunk-X4BXESMQ.mjs +7 -0
- package/lib/chunk-XBQGZGWR.mjs +7 -0
- package/lib/{chunk-AXFD2OH6.mjs → chunk-XGGOUNPP.mjs} +1 -1
- package/lib/chunk-XKWW3GKF.mjs +7 -0
- package/lib/{chunk-PDRXM5WN.mjs → chunk-Y2DRK37K.mjs} +1 -1
- package/lib/{chunk-ZXOUWHYE.mjs → chunk-YA6ATMTB.mjs} +1 -1
- package/lib/{chunk-54HYHHVL.mjs → chunk-YDXMTWAT.mjs} +1 -1
- package/lib/chunk-YHR4WQPR.mjs +7 -0
- package/lib/{chunk-LWES2KZE.mjs → chunk-YTLUYSMF.mjs} +1 -1
- package/lib/{chunk-2K5BYZQM.mjs → chunk-YWEQQL3C.mjs} +1 -1
- package/lib/{chunk-C6RKM4BB.mjs → chunk-Z4LKKOFY.mjs} +1 -1
- package/lib/chunk-ZBAWJUG2.mjs +7 -0
- package/lib/{chunk-446GBKAC.mjs → chunk-ZJW6YOMV.mjs} +1 -1
- package/lib/chunk-ZQQXSCVI.mjs +7 -0
- package/lib/{chunk-L6CLN664.mjs → chunk-ZQWIVYVM.mjs} +1 -1
- package/lib/{chunk-CXKZ6TYV.mjs → chunk-ZV7ZFQQC.mjs} +1 -1
- package/lib/sandforge-autopilot.mjs +25 -25
- package/lib/sandforge-backup.mjs +1 -1
- 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 +52 -21
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +1 -1
- package/lib/sandforge-env.mjs +95 -95
- package/lib/sandforge-frozen.mjs +1 -1
- package/lib/sandforge-mcp.mjs +12 -12
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +1 -1
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +1 -1
- package/lib/sandforge.mjs +1 -1
- package/lib/sf/sandforge/compare.mjs +2 -2
- package/lib/sfPlugin.mjs +1 -1
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
- package/lib/chunk-2ADSD5WK.mjs +0 -7
- package/lib/chunk-2GSMHGIV.mjs +0 -7
- package/lib/chunk-36Y225OM.mjs +0 -7
- package/lib/chunk-3OVTKRS4.mjs +0 -7
- package/lib/chunk-4GCYGQXD.mjs +0 -7
- package/lib/chunk-4JKR4PTZ.mjs +0 -8
- package/lib/chunk-5OGNK3JP.mjs +0 -37
- package/lib/chunk-6QSHWIZI.mjs +0 -48
- package/lib/chunk-77IVKH7R.mjs +0 -7
- package/lib/chunk-77MZRBWX.mjs +0 -7
- package/lib/chunk-7WSQ65WG.mjs +0 -9
- package/lib/chunk-A32ISQ6M.mjs +0 -28
- package/lib/chunk-AG24QMSY.mjs +0 -7
- package/lib/chunk-BH76USTQ.mjs +0 -11
- package/lib/chunk-BZ24IAP5.mjs +0 -7
- package/lib/chunk-CN5HGFG4.mjs +0 -7
- package/lib/chunk-CTPLYUXA.mjs +0 -7
- package/lib/chunk-DIGUC7S4.mjs +0 -341
- package/lib/chunk-DSR2MSBH.mjs +0 -7
- package/lib/chunk-ETNQHIDI.mjs +0 -9
- package/lib/chunk-FBXH4VRQ.mjs +0 -7
- package/lib/chunk-FYWNSMOZ.mjs +0 -10
- package/lib/chunk-GEEWPTV5.mjs +0 -7
- package/lib/chunk-GTRU5AV5.mjs +0 -7
- package/lib/chunk-I3ZO76LL.mjs +0 -21
- package/lib/chunk-ISA2NYJV.mjs +0 -7
- package/lib/chunk-IXIY6Q4M.mjs +0 -7
- package/lib/chunk-JAV6F6OA.mjs +0 -7
- package/lib/chunk-JYUMD357.mjs +0 -7
- package/lib/chunk-L47JCNP3.mjs +0 -7
- package/lib/chunk-LI2XNV7F.mjs +0 -7
- package/lib/chunk-LP2D3JJP.mjs +0 -7
- package/lib/chunk-LYOGCIYD.mjs +0 -925
- package/lib/chunk-N5UIE4IR.mjs +0 -7
- package/lib/chunk-O7GCCRPW.mjs +0 -7
- package/lib/chunk-OO24ZYYJ.mjs +0 -7
- package/lib/chunk-OS6HFJ7L.mjs +0 -7
- package/lib/chunk-P6WRYJN3.mjs +0 -7
- package/lib/chunk-PGRY365W.mjs +0 -7
- package/lib/chunk-PPGDAUEQ.mjs +0 -7
- package/lib/chunk-Q4PPI3KG.mjs +0 -7
- package/lib/chunk-QFTF2PGS.mjs +0 -21
- package/lib/chunk-QO4MPHZD.mjs +0 -7
- package/lib/chunk-QXB6U3ZP.mjs +0 -7
- package/lib/chunk-R3OM3X4L.mjs +0 -8
- package/lib/chunk-R7GKMAT4.mjs +0 -7
- package/lib/chunk-SCKUIE3R.mjs +0 -7
- package/lib/chunk-SU65Z2BA.mjs +0 -7
- package/lib/chunk-T7DDS4UQ.mjs +0 -7
- package/lib/chunk-TQJ5NPRC.mjs +0 -7
- package/lib/chunk-VZLJZEV2.mjs +0 -7
- package/lib/chunk-W3BQGMTR.mjs +0 -7
- package/lib/chunk-WXU6ZJIV.mjs +0 -7
- package/lib/chunk-X4HZD5U2.mjs +0 -7
- package/lib/chunk-X6XNTOGO.mjs +0 -7
- package/lib/chunk-XMQ5R6TC.mjs +0 -10
- package/lib/chunk-XPXEQKLR.mjs +0 -7
- package/lib/chunk-YBZIDW6W.mjs +0 -7
- package/lib/chunk-ZCOSME6P.mjs +0 -7
- package/lib/chunk-ZTHC42X6.mjs +0 -7
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a,b}from"./chunk-
|
|
7
|
+
import{a,b}from"./chunk-PBY2O6OF.mjs";import"./chunk-PMWAFDUB.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as DataPlanBuilder,b as resolveInsertOrder};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-
|
|
7
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-OMNMLKDT.mjs";import"./chunk-ZV7ZFQQC.mjs";import"./chunk-UV74P4H2.mjs";import"./chunk-KGU4SVIT.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{p as ObservedUsersRunStore,c as RECOVERY_CATEGORY,h as USERS_RUN_NOT_FOUND,i as USERS_RUN_REPLACED,a as awaitingAddressesOf,m as changingUsersOf,k as choicesKeyOf,l as planSignatureOf,f as readSavedTesters,d as recoveryTestersKey,b as recoveryUsersOf,j as replacedRunOf,g as saveTesters,e as savedTestersSchema,o as usersAuditObjectsOf,n as usersDoneOf};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a,b,c,d}from"./chunk-
|
|
7
|
+
import{a,b,c,d}from"./chunk-Z4LKKOFY.mjs";import"./chunk-2HVOZUM4.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-PMWAFDUB.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as StepCancelledError,d as StepExecutor,b as delayMs,c as waitedWords};
|
|
@@ -4,5 +4,5 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{b as $e}from"./chunk-
|
|
7
|
+
import{b as $e}from"./chunk-Q7GIJBCD.mjs";import{a as We}from"./chunk-M6P5ZZLE.mjs";import{c as ke,d as Ge}from"./chunk-NED4MBIM.mjs";import{d as _e,z as Le}from"./chunk-KGU4SVIT.mjs";import{a as Me}from"./chunk-VV3B6IC3.mjs";import{a as k}from"./chunk-4TLYUZD5.mjs";import{m as qe}from"./chunk-RHNTHGNU.mjs";import{a as re,b as De}from"./chunk-Q7TLC3I2.mjs";import{b as xe}from"./chunk-EADHKH3A.mjs";import{a as H,c as Ae,g as oe,j as Pe,n as Ne}from"./chunk-M6K34KGF.mjs";import{a as Te,h as q}from"./chunk-TZE3Y7IQ.mjs";import{a as je,b as x}from"./chunk-CA5NAXSU.mjs";import{Ac as ee,Bc as te,ca as Ie,ja as Fe,wa as ve,za as ue,zc as Z}from"./chunk-PMWAFDUB.mjs";import{b as Ce,e as Ee,i as Re,k as Se,l as de}from"./chunk-WZQEK4WT.mjs";import{appendFile as tt}from"node:fs/promises";var fe=new Set(["Task","Event"]),rt=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ot="an emptying";function nt(t){let e=q(t.objectApiName),o=fe.has(t.objectApiName),r=[...t.filter!==void 0&&t.filter.trim()!==""?[`(${t.filter})`]:[],...o?["IsDeleted = false"]:[]];return{soql:`SELECT Id FROM ${e}${r.length>0?` WHERE ${r.join(" AND ")}`:""}`,scanAll:o}}async function zt(t,e,o,r={}){let n=()=>r.signal?.aborted===!0,c=[];await Le(e);for(let a of o){let{soql:d,scanAll:u}=nt(a),m={objectApiName:a.objectApiName,count:0};if(c.push(m),n())return{stopped:!0,read:c};let R=ke(e,a.objectApiName),i=!0,h=0,b=await t.query(d,{scanAll:u});for(;;){let S=b.records.map(y=>{let C=y.Id;if(typeof C!="string"||!rt.test(C))throw new Error(`The org answered a ${a.objectApiName} row with no record id: its ids are not read.`);return C});if((S.length>0||i)&&(await tt(R,S.map(y=>`${y}
|
|
8
8
|
`).join(""),{encoding:"utf8",mode:_e,flag:i?"w":"a"}),i=!1),m.count+=S.length,r.onPage?.(a.objectApiName,m.count),h=S.length===0?h+1:0,b.done||!b.nextRecordsUrl)break;if(h>=xe)throw new Error(`The org kept answering empty pages of ${a.objectApiName} without saying it was done: ${m.count} id(s) read, the rest not.`);if(n())return{stopped:!0,read:c};b=await t.queryMore(b.nextRecordsUrl)}}return{stopped:!1,spool:await Ge(e,c,ot)}}function ne(t,e,o){return e.nillable!==!1||e.referenceTo.length!==1?!1:e.isMasterDetail||(o??[]).some(r=>r.isCascadeDelete&&r.childSObject===t&&r.field===e.name)}var V=.001,ge=.01,st=50,it=5,at=2,ct=4;function lt(t){return t.level===0||t.recordCount>0||t.status==="error"||t.recordCountUnknown===!0}function Be(t){return t.inputMode==="record"&&typeof t.recordId=="string"&&t.recordId!==""}function pe(t){if(!Fe(t)||t.inputMode!=="soql")return;let e=Ie(t.soqlQuery??"");return e?{where:e.where,limit:e.limit}:void 0}function dt(t,e,o){let r=[];o===0&&Be(t)&&r.push(`Id = '${Te(t.recordId??"")}'`);let n=o===0?pe(t):void 0;n?.where&&r.push(`(${n.where})`);let c=t.objectSoqlFilters?.[e];return c&&r.push(`(${c})`),`SELECT COUNT() FROM ${q(e)}${r.length>0?` WHERE ${r.join(" AND ")}`:""}`}var me=typeof setImmediate=="function"?()=>new Promise(t=>setImmediate(t)):()=>new Promise(t=>setTimeout(t,0)),A=class extends Error{constructor(){super("Discovery cancelled"),this.name="DiscoveryCancelled"}};function M(t,e){return e?e.aborted?Promise.reject(new A):new Promise((o,r)=>{let n=()=>r(new A);e.addEventListener("abort",n,{once:!0}),t().then(c=>{e.removeEventListener("abort",n),o(c)},c=>{e.removeEventListener("abort",n),r(c)})}):t()}function ut(t){return t.fieldCount>0||t.piiFields.length>0}function ft(t,e){if(t.type!=="master-detail")return t;let o=(e.get(t.targetObject)?.fields??[]).filter(n=>n.referenceTo.includes(t.sourceObject)),r=e.get(t.sourceObject)?.childRelationships;return o.some(n=>ne(t.targetObject,n,r))?t:{...t,type:"lookup"}}function Y(){return{nodes:[],edges:[],totalRecords:0,estimatedSizeMB:0,estimatedDurationSeconds:0,truncated:!1}}var Ue=class{deps;constructor(e){this.deps=e}async discover(e,o){if(e.inputMode==="org"||e.depth==="all")return ze(this.deps,e,o);let r=o?.signal;if(r?.aborted)return Y();o?.onProgress?.({phase:"resolving-root",discoveredCount:0,queueRemaining:1});let n=Date.now(),c;try{c=await this.resolveRootObject(e,r)}catch(g){if(g instanceof A)return Y();throw g}let a=Date.now();a-n>2e3&&k.warn(`[forge-discover] resolveRootObject took ${a-n}ms (cold path, consider verifying describeGlobal cache state)`);let d=this.resolveMaxDepth(e),u=o?.maxNodes??st,m=u,R=u*at,i=new Set,h=[],b=u*ct,S=0,y=0,C=new Set,I=[],$=new Map,N=new Map,L=()=>S+y+w.length<m&&I.length+y+w.length<b,W=(g,j)=>{i.has(g)||h.push([g,j]),i.add(g)},D=g=>{i.delete(g)&&(h=h.filter(([j])=>j!==g))},U=new Map,B=(g,j,P,F)=>{if(H(g.sourceObject)||H(g.targetObject)||g.sourceObject===g.targetObject)return;let s=`${g.sourceObject}|${g.targetObject}`,l=U.get(s)??new Map;(P!==void 0||!l.has(j))&&l.set(j,{settable:P,insertOnly:F}),U.set(s,l);let p=$.get(s);if(!p){$.set(s,g);return}let f=g.type==="master-detail"&&p.type==="lookup"?g:p,v=p.required===!0||g.required===!0;$.set(s,v?{...f,required:v}:f)},w=[[c,0]];for(C.add(c);w.length>0&&!r?.aborted;){await me();let g=m-S;if(g<=0)break;let j=Math.min(6,g,w.length),P=w.splice(0,j),F=await Promise.all(P.map(async([s,l])=>{let p,f=!1,v=dt(e,s,l);try{let[E,Q]=await Promise.all([M(()=>this.deps.describeObject(e.sourceOrgId,s,r),r),M(()=>this.deps.queryCount(e.sourceOrgId,v,r),r).catch(_=>{if(_ instanceof A)throw _;return p=x(_),f=se(_),-1})]);return{objectName:s,depth:l,describe:E,recordCount:Q,countError:p,countRefused:f}}catch(E){return E instanceof A||r?.aborted?{objectName:s,depth:l,describe:null,recordCount:-1,cancelled:!0}:{objectName:s,depth:l,describe:null,recordCount:-1,describeError:x(E)}}}));y=F.length;for(let s of F){if(y--,s.cancelled)continue;let{objectName:l,depth:p,describe:f,recordCount:v,countError:E,countRefused:Q,describeError:_}=s;if(!f){I.push({objectApiName:l,recordCount:0,fieldCount:0,status:"error",progress:0,included:!1,piiFields:[],anonymizeFields:[],level:p,successCount:0,failureCount:0,errors:[`Describe unavailable: ${_??"unknown error"}`],createableFieldCount:0,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}),S++,o?.onProgress?.({phase:"object",objectApiName:l,discoveredCount:I.length,queueRemaining:w.length});continue}N.set(l,f);let ie=v<0,ae=ie&&Q!==!0,ce=ie&&!ae,le=p===0?pe(e)?.limit:void 0,J=ie?0:typeof le=="number"&&Number.isFinite(le)?Math.min(v,le):v,Je=p===0&&(Be(e)||pe(e)!==void 0),be=this.deps.detectPII(f.fields),Ke=f.fields.filter(O=>O.type!=="id").length,Oe={objectApiName:l,...f.label?{label:f.label}:{},recordCount:J,...ae?{recordCountUnknown:!0}:{},fieldCount:f.fields.length,status:ce?"error":"idle",progress:0,included:ce?!1:ae||Je||!e.skipEmpty||J>0,piiFields:be,anonymizeFields:e.anonymizePII?be:[],level:p,successCount:0,failureCount:0,errors:ce?[`Record count unavailable: ${E??"unknown error"}`]:[],createableFieldCount:Ke,estimatedSizeMB:J*V,estimatedApiCalls:Math.ceil(J/200),batchStrategy:"auto"};I.push(Oe);let ye=lt(Oe);if(ye&&S++,p<d&&ye){for(let O of f.fields){if(O.referenceTo.length===0)continue;let we=ee(O),K=we&&Z(l,O.name,O.nillable),Ze=te(O);for(let T of O.referenceTo){B({sourceObject:T,targetObject:l,relationshipName:O.relationshipName??O.name,type:O.isMasterDetail?"master-detail":"lookup",required:K},O.name,we,Ze);let et=i.has(T);(!C.has(T)||K&&et)&&!H(T)&&(L()?(C.add(T),D(T),K?w.unshift([T,p+1]):w.push([T,p+1])):K&&m<R?(C.add(T),D(T),m++,w.unshift([T,p+1])):(C.add(T),W(T,p+1)))}}for(let O of f.childRelationships)B({sourceObject:l,targetObject:O.childSObject,relationshipName:O.relationshipName,type:O.isCascadeDelete?"master-detail":"lookup"},O.field,void 0,void 0),!C.has(O.childSObject)&&!H(O.childSObject)&&(C.add(O.childSObject),L()?w.push([O.childSObject,p+1]):W(O.childSObject,p+1))}o?.onProgress?.({phase:"object",objectApiName:l,discoveredCount:I.length,queueRemaining:w.length})}for(;h.length>0&&L();){let[s,l]=h.shift();i.delete(s),w.push([s,l])}}let z=I.reduce((g,j)=>g+j.recordCount,0),G=[...$].map(([g,j])=>{let P=[...U.get(g)?.values()??[]],F=ft(j,N);return P.length>0&&P.every(s=>s.settable===!1)&&(F={...F,settable:!1}),P.some(s=>s.insertOnly===!0)&&(F={...F,insertOnly:!0}),F});return{nodes:I,edges:G,totalRecords:z,estimatedSizeMB:z*V,estimatedDurationSeconds:z*ge,truncated:h.length>0}}personalFields(e){return this.deps.detectPII(e)}async readPersonalFields(e,o,r){let n=e.nodes.filter(a=>!ut(a)&&a.status!=="error"),c=new Map;for(let a=0;a<n.length&&!r?.aborted;a+=6)await Promise.all(n.slice(a,a+6).map(async({objectApiName:d})=>{try{let u=await this.deps.describeObject(o.sourceOrgId,d,r),m=this.deps.detectPII(u.fields);m.length>0&&c.set(d,m)}catch(u){k.warn(`[forge] personal fields of ${d} not read: ${x(u)}`)}}));return c.size===0?e:{...e,nodes:e.nodes.map(a=>{let d=c.get(a.objectApiName);return d?{...a,piiFields:d,anonymizeFields:o.anonymizePII?[...d]:[]}:a})}}async resolveRootObject(e,o){if(e.inputMode==="record"&&e.recordId){let r=e.recordId.substring(0,3),c=(await M(()=>this.deps.describeGlobal(e.sourceOrgId,o),o)).find(a=>a.keyPrefix===r);if(!c)throw new Error(`No object found for record ID prefix "${r}". The ID may not belong to any accessible object in this org.`);return c.name}if(e.inputMode==="soql"&&e.soqlQuery)return pt(e.soqlQuery);throw new Error(`Cannot resolve root object for inputMode "${e.inputMode}". Provide a valid recordId (for "record" mode) or soqlQuery (for "soql" mode).`)}resolveMaxDepth(e){switch(e.depth){case"direct":return 1;case"full":return it;case"custom":return Math.max(1,Math.min(10,e.customDepth??3));case"all":throw new Error("A clone of the whole org is discovered without a walk (WholeOrgDiscovery)")}}};function pt(t){let e=t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/--[^\n]*/g,"");for(let r=0;r<32;r++){let n=e.replace(/\([^()]*\)/g,"");if(n===e)break;e=n}let o=/\bFROM\s+(\w+)/i.exec(e);if(!o)throw new Error('Could not parse object name from SOQL query. Ensure the query uses standard "SELECT ... FROM ObjectName" syntax.');return q(o[1])}var gt={clone:"write",empty:"delete"},mt=["settings","definition"],ht=new Set(["contentworkspace"]);function bt(t){if(t.name.includes("__"))return!1;let e=t.name.toLowerCase();return ht.has(e)||mt.some(o=>e.endsWith(o))?!0:t.createable===!1&&e!==oe.toLowerCase()}function Ot(t,e){return t.objectApiName<e.objectApiName?-1:t.objectApiName>e.objectApiName?1:0}function yt(t,e,o,r={}){let n=Ne(t,{mode:"everything",access:gt[o],...r.excluded!==void 0?{excluded:r.excluded}:{},...r.customSettings!==void 0?{customSettings:r.customSettings}:{}},e),c=new Map(t.map(u=>[u.name.toLowerCase(),u])),a=[],d=[];for(let u of n.candidates){let m=c.get(u.toLowerCase());m!==void 0&&bt(m)?d.push({objectApiName:u,reason:"configuration"}):a.push(u)}return d.length===0?n:{...n,candidates:a,leftOut:[...n.leftOut,...d].sort(Ot)}}var wt=new Set([oe,Pe].map(t=>t.toLowerCase())),Qe="withTheirRecords",Ct="noLayout";function Et(t){switch(t){case"configuration":return{reason:"setup"};case"chatter":case"history":case"sharing":case"changeEvent":case"unsupportedKind":case"customSetting":case"files":case"setup":case"platformCreated":case"metadata":case"notWritable":case"excludedByUser":return{reason:t};case"heldWithFiles":return{reason:"files",detail:Qe};case"notFound":case"notCustomSetting":return{reason:"missingInTarget"}}}function Rt(t){switch(t){case"platform":return{reason:"platformCreated"};case"setup":return{reason:"setup"};case"feature":case"parent":return{reason:"notWritable",detail:t};case"user":return{reason:"notWritable"}}}function St(t){if(t.createable!==!0||t.queryable!==!0)return;let e=t.updateable===!0,o=t.deletable===!0;if(!(e&&o))return!e&&!o?{reason:"createOnly"}:{reason:"createOnly",detail:e?Ft:It}}var It="noEdit",Ft="noDelete";function vt(t,e){return t.objectApiName<e.objectApiName?-1:t.objectApiName>e.objectApiName?1:0}function He(t,e,o,r={}){let n=yt(e,o,"clone",r),c=new Map(t.map(i=>[i.name.toLowerCase(),i])),a=new Map(e.map(i=>[i.name.toLowerCase(),i])),d=[],u=[],m=new Set,R=(i,h,b)=>{m.add(i.toLowerCase()),u.push({objectApiName:i,reason:h,...b!==void 0?{detail:b}:{}})};for(let i of t)a.has(i.name.toLowerCase())||R(i.name,"missingInTarget");for(let i of n.leftOut){let h=i.objectApiName.toLowerCase(),b=c.get(h);if(!b||m.has(h))continue;let S=a.get(h),y=Et(i.reason),C=h!==oe.toLowerCase();y.reason==="notWritable"&&C&&S?.createable!==!0&&r.createFacts&&(y=Rt(We(b.name,r.createFacts))),y.reason==="notWritable"&&C&&S&&(y=St(S)??y);let I=i.reason==="setup"&&S?.layoutable===!1&&!Ae(i.objectApiName);R(b.name,y.reason,I?Ct:y.detail??i.detail)}for(let i of n.candidates){let h=i.toLowerCase(),b=c.get(h);b&&(b.queryable!==!0?R(b.name,"notQueryable"):wt.has(h)?R(b.name,"files",Qe):d.push(b.name))}return d.sort(),u.sort(vt),{candidates:d,leftOut:u}}var he=1950,Xe=2e4,jt=1e6,Dt=18,Tt=200,At=new Set(["QUERY_TIMEOUT","OPERATION_TOO_LARGE","REQUEST_LIMIT_EXCEEDED","REQUEST_RUNNING_TOO_LONG","SERVER_UNAVAILABLE","UNKNOWN_EXCEPTION"]);function se(t){if(t instanceof Me||De(t))return!1;let e=je(x(t));return e===void 0?!1:!At.has(e)&&!e.startsWith("ERROR_HTTP_")}function Pt(t,e){let o=fe.has(t),r=[...e?[`(${e})`]:[],...o?["IsDeleted = false"]:[]];return{soql:`SELECT COUNT() FROM ${q(t)}${r.length>0?` WHERE ${r.join(" AND ")}`:""}`,all:o}}async function Ve(t,e){let o=0,r=!1,n=()=>r,c=async()=>{for(;!r&&o<t.length;){let a=o++;try{await e(t[a],a,n)}catch(d){throw r=!0,d}}};await Promise.all(Array.from({length:Math.min(6,t.length)},c))}async function Nt(t,e){try{return await t()}catch(o){if(o instanceof A||re(o)||se(o))throw o;return k.warn(`[forge-discover] whole org: describe of ${e} unanswered, asked again: ${x(o)}`),t()}}function Ye(t){if(!(t<=ue))throw new Error(`The source org lists ${t} objects a clone of the whole org leaves out, more than the ${ue} one graph says. Nothing was written. Clone the org in parts instead: a run from a record or from a query for each part.`)}var xt=de({name:Ce().min(1),count:Ee().int().nonnegative()});function Mt(t){let e=de({sObjects:Se(Re())}).safeParse(t);if(!e.success)return;let o=new Map;for(let r of e.data.sObjects){let n=xt.safeParse(r);n.success&&o.set(n.data.name,n.data.count)}return o}function _t(t){let e=new Map;for(let[o,r]of t)for(let n of r.fields){if(n.referenceTo.length===0)continue;let c=ee(n),a=c&&Z(o,n.name,n.nillable),d=te(n);for(let u of n.referenceTo){if(u===o||!t.has(u))continue;let m=`${u}|${o}`,R={sourceObject:u,targetObject:o,relationshipName:n.relationshipName??n.name,type:ne(o,n,t.get(u)?.childRelationships)?"master-detail":"lookup",required:a},i=e.get(m);if(!i){e.set(m,{edge:R,noneSettable:!c,insertOnly:d});continue}let h=R.type==="master-detail"&&i.edge.type==="lookup"?R:i.edge;i.edge={...h,required:i.edge.required===!0||a},i.noneSettable=i.noneSettable&&!c,i.insertOnly=i.insertOnly||d}}return[...e.values()].map(({edge:o,noneSettable:r,insertOnly:n})=>({...o,...r?{settable:!1}:{},...n?{insertOnly:!0}:{}}))}function Lt(t,e){let o=e.filter(qe),r=$e(t,o).reverse(),n=new Map;r.forEach((d,u)=>{for(let m of d)n.set(m,u)});let c=new Map;for(let d of o){let u=c.get(d.targetObject)??[];u.push(d.sourceObject),c.set(d.targetObject,u)}let a=r.map(()=>0);return r.forEach((d,u)=>{for(let m of d)for(let R of c.get(m)??[]){let i=n.get(R);i!==void 0&&i!==u&&(a[u]=Math.max(a[u],a[i]+1))}}),new Map(t.map(d=>[d,Math.min(Dt,1+a[n.get(d)??0])]))}async function ze(t,e,o){let r=ve(e);if(r!==void 0)throw new Error(r);let n=o?.signal;if(n?.aborted)return Y();try{return await kt(t,e,o)}catch(c){if(c instanceof A||n?.aborted)return Y();throw c}}async function kt(t,e,o){let r=o?.signal,n=s=>o?.onProgress?.(s),c=Date.now(),a=s=>l=>{if(l instanceof A)throw l;return k.warn(`[forge-discover] whole org: ${x(l)}`),s},{toolingObjects:d,recordCounts:u,createFacts:m}=t;n({phase:"listing",discoveredCount:0,queueRemaining:0});let[R,i,h,b,S]=await Promise.all([M(()=>t.describeGlobal(e.sourceOrgId,r),r),M(()=>t.describeGlobal(e.targetOrgId,r),r),d?M(()=>d(e.targetOrgId,r),r).catch(a([])):Promise.resolve([]),m?M(()=>m(e.targetOrgId),r).catch(a(void 0)):Promise.resolve(void 0),u?M(()=>u(e.sourceOrgId,r),r).catch(a(void 0)):Promise.resolve(void 0)]),y=Mt(S),C=e.excludedObjects??[],{candidates:I,leftOut:$}=He(R,i,h,{...b?{createFacts:b}:{},...C.length>0?{excluded:C}:{}}),N=[...$];Ye(N.length);let L=I.map(()=>{}),W=0;n({phase:"counting",discoveredCount:0,queueRemaining:I.length,total:I.length}),await Ve(I,async(s,l,p)=>{let f=y?.get(s),v=e.objectSoqlFilters?.[s];if(f!==void 0&&f>jt&&!v)L[l]={objectApiName:s,rows:f,approximate:!0};else try{let{soql:E,all:Q}=Pt(s,v),_=await M(()=>t.queryCount(e.sourceOrgId,E,r,Q?{all:!0}:void 0),r);if(p())return;_>0?L[l]={objectApiName:s,rows:_}:N.push({objectApiName:s,reason:"empty"})}catch(E){if(E instanceof A||re(E))throw E;if(p())return;se(E)?N.push({objectApiName:s,reason:"unreadable",detail:x(E)}):(k.warn(`[forge-discover] whole org: ${s} not counted, kept: ${x(E)}`),L[l]=f!==void 0&&f>0&&!v?{objectApiName:s,rows:f,approximate:!0}:{objectApiName:s,rows:0,unknown:!0})}W++,n({phase:"counting",objectApiName:s,discoveredCount:W,queueRemaining:I.length-W,total:I.length})});let D=L.filter(s=>s!==void 0);if(D.length>he)throw new Error(`The source org holds records in ${D.length} objects a clone of the whole org would take, more than the ${he} one run writes. Nothing was written. Leave ${D.length-he} of them out or more, or clone the org in parts instead: a run from a record or from a query for each part.`);let U=D.map(()=>{}),B=0;n({phase:"describing",discoveredCount:0,queueRemaining:D.length,total:D.length}),await Ve(D,async({objectApiName:s},l,p)=>{try{let f=await Nt(()=>M(()=>t.describeObject(e.sourceOrgId,s,r),r),s);if(p())return;U[l]=f}catch(f){if(f instanceof A||re(f))throw f;if(p())return;N.push({objectApiName:s,reason:"notDescribed",detail:x(f)})}B++,n({phase:"describing",objectApiName:s,discoveredCount:B,queueRemaining:D.length-B,total:D.length})}),await me();let w=new Map,z=new Map;D.forEach((s,l)=>{let p=U[l];p&&(w.set(s.objectApiName,p),z.set(s.objectApiName,s))});let G=_t(w);if(G.length>Xe)throw new Error(`The ${w.size} objects of the source org a clone of the whole org would take relate ${G.length} pairs of objects, more than the ${Xe} one run writes in order. Nothing was written. Clone the org in parts instead: a run from a record or from a query for each part.`);let g=[...w.keys()],j=Lt(g,G),P=g.map(s=>{let l=w.get(s),p=z.get(s),f=p.rows,v=t.detectPII(l.fields);return{objectApiName:s,...l.label?{label:l.label}:{},recordCount:f,...p.approximate?{recordCountApproximate:!0}:{},...p.unknown?{recordCountUnknown:!0}:{},fieldCount:l.fields.length,status:"idle",progress:0,included:!0,piiFields:v,anonymizeFields:e.anonymizePII?[...v]:[],level:j.get(s)??1,successCount:0,failureCount:0,errors:[],createableFieldCount:l.fields.filter(E=>E.type!=="id").length,estimatedSizeMB:f*V,estimatedApiCalls:Math.ceil(f/Tt),batchStrategy:"auto"}});Ye(N.length);let F=P.reduce((s,l)=>s+l.recordCount,0);return N.sort((s,l)=>s.objectApiName<l.objectApiName?-1:s.objectApiName>l.objectApiName?1:0),k.info(`[forge-discover] whole org: ${P.length} object(s), ${G.length} relation(s), ${N.length} left out, ${F} record(s), in ${Date.now()-c}ms`),{nodes:P,edges:G,totalRecords:F,estimatedSizeMB:F*V,estimatedDurationSeconds:F*ge,truncated:!1,leftOut:N}}export{fe as a,ot as b,zt as c,ne as d,st as e,it as f,at as g,lt as h,ut as i,Ue as j,yt as k,he as l,Xe as m,se as n,Ve as o,Mt as p,ze as q};
|
|
@@ -0,0 +1,7 @@
|
|
|
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};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{r as L}from"./chunk-ICIYL45C.mjs";import{Ec as C,Gc as R,Lc as S,Mc as m,Pc as b}from"./chunk-
|
|
7
|
+
import{r as L}from"./chunk-ICIYL45C.mjs";import{Ec as C,Gc as R,Lc as S,Mc as m,Pc as b}from"./chunk-PMWAFDUB.mjs";var A="PricebookEntryId",F=Object.fromEntries([["OpportunityLineItem","Opportunity"],["QuoteLineItem","Quote"],["OrderItem","Order"],["ContractLineItem","ServiceContract"]].map(([e,o])=>[e,{record:o,field:L[e]}]));function K(e,o,c){if(!e.has(C))return[];let t=new Map;for(let{sourceObject:n,targetObject:a}of c)t.set(n,[...t.get(n)??[],a]);let i=n=>{let a=new Set,l=[C];for(;l.length>0;){let u=l.pop();if(u===n)return!0;a.has(u)||(a.add(u),l.push(...t.get(u)??[]))}return!1};return[...new Set(o.flatMap(n=>F[n]?.record??[]))].filter(n=>e.has(n)&&!i(n)).map(n=>({sourceObject:n,targetObject:C,relationshipName:`${n}Before${C}`,type:"lookup",required:!0}))}function k(e,o){return[e[R],e[S],o?e[m]:""].map(c=>String(c??"")).join("|")}function h(e,o){return`${e}|${o}`}function Y(e){return h([e.book,e.product,e.model].join("|"),e.currency)}function v(e){let o=e[b];return typeof o=="string"&&o!==""?o:void 0}function x(e){let o=e.wanted??new Map,c=e.prices.flatMap(i=>{let d=i.Id,n=v(i);if(typeof d!="string"||n===void 0)return[];let a=e.writtenIn(n),l=new Set(o.get(d)??[]);l.size===0&&!e.active.has(n)&&a!==void 0&&l.add(a);let u=i[R]===e.standardBookId;return[{row:i,id:d,read:n,alone:a,own:l,standard:u}]}),t=new Map;for(let{row:i,read:d,alone:n,own:a,standard:l}of c){if(l)continue;let u=a.size>0?a:n!==void 0?[n]:[],w=h(k({...i,[R]:e.standardBookId},e.sellingModels),d),p=t.get(w)??new Set;for(let y of u)p.add(y);t.set(w,p)}return c.map(({row:i,id:d,read:n,alone:a,own:l,standard:u})=>{let w=k(i,e.sellingModels),p=new Set(o.get(d)??[]);if(u)for(let y of t.get(h(w,n))??[])p.add(y);if(p.size===0)for(let y of l)p.add(y);return{row:i,id:d,key:w,read:n,alone:a,targets:[...p]}})}function _(e,o){let c=new Map;for(let t of e){if(t.alone!==t.read||!o.has(t.read))continue;let i=h(t.key,t.read);c.has(i)||c.set(i,t)}return c}function W(e){let o=x(e),c=_(o,e.active),t=new Map;for(let{row:i,key:d,targets:n}of o)for(let a of n){let l=h(d,a);c.has(l)||t.has(l)||t.set(l,{book:String(i[R]??""),product:String(i[S]??""),model:e.sellingModels?String(i[m]??""):"",currency:a})}return[...t.values()]}function G(e,o){let c=x(e),t=_(c,e.active),i=new Map(c.map(r=>[r.id,r.key])),d=new Map;for(let r of o){let s=r.Id,f=v(r);if(typeof s!="string"||f===void 0||e.writtenIn(f)!==f)continue;let g=k(r,e.sellingModels),P=h(g,f);if(t.has(P))continue;let M=d.get(P);M!==void 0&&!(r.IsActive===!0&&M.IsActive!==!0)||(d.set(P,r),i.set(s,g))}let n=new Map,a=new Set,l=new Set,u=new Map,w=new Set,p=[],y=(r,s,f)=>{s!==r.read&&p.push({from:r.read,to:s,how:f,forLines:s!==r.alone})},E=[];for(let r of c)for(let s of r.targets){let f=h(r.key,s),g=t.get(f);if(g){n.set(f,g.id),a.add(g.id),g!==r&&y(r,s,"replaced");continue}let P=d.get(f);if(P){n.set(f,String(P.Id)),l.add(P),y(r,s,"replaced");continue}E.push({price:r,to:s})}for(let{price:r,to:s}of E){let f=h(r.key,s);n.has(f)?y(r,s,"replaced"):!a.has(r.id)&&!w.has(r.id)?(w.add(r.id),n.set(f,r.id),s!==r.alone&&u.set(r.id,s),y(r,s,"converted")):y(r,s,"none")}let O=new Map,I=[],B=new Map(c.map(r=>[r.row,r]));for(let r of e.prices){let s=B.get(r);if(!s||s.targets.length===0||a.has(s.id)||w.has(s.id)){I.push(r);continue}let f=s.targets.map(g=>n.get(h(s.key,g))).find(g=>g!==void 0&&g!==s.id);if(f===void 0){I.push(r);continue}O.set(s.id,f)}I.push(...o.filter(r=>l.has(r)));for(let r of c){if(r.targets.length>0||r.alone===void 0)continue;let s=h(r.key,r.alone);n.has(s)||n.set(s,r.id)}return{rows:I,standsFor:O,convertedInto:u,written:n,keys:i,said:p}}function N(e){let o=new Map;for(let{from:c,to:t,how:i,forLines:d}of e){let n=[c,t,i,d?"lines":""].join("|"),a=o.get(n)??{from:c,to:t,how:i,forLines:d,prices:0};a.prices++,o.set(n,a)}return[...o.values()]}function $(e){let o=new Map;for(let{from:c,to:t,prices:i}of e){let d=`${c} \u2192 ${t}`;o.set(d,(o.get(d)??0)+i)}return[...o].map(([c,t])=>`${t} ${c}`).join(", ")}function H(e){return T(N(e))}function T(e){let o=(t,i)=>e.filter(d=>d.forLines===t&&d.how===i);return[[o(!1,"replaced"),"price(s) in a currency the target does not hold active replaced by the source's own price in the currency written, for the same product and price book"],[o(!1,"converted"),"no price in the currency written in the source for the same product and price book, written in it at the amount converted at the source's rates"],[o(!0,"replaced"),"price(s) replaced by the source's own price in the currency of the record their lines belong to, for the same product and price book"],[o(!0,"converted"),"no price in the currency of the record their lines belong to in the source for the same product and price book, written in it at its amount converted"],[e.filter(t=>t.how==="none"),"no price in the currency of the record their lines belong to in the source for the same product and price book, and the price goes in another currency for other lines: the target refuses the lines of a record in it"]].filter(([t])=>t.length>0).map(([t,i])=>`${$(t)}: ${i}`)}export{A as a,F as b,K as c,k as d,h as e,Y as f,W as g,G as h,N as i,H as j,T as k};
|
|
@@ -0,0 +1,7 @@
|
|
|
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};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a as n,b as p,h as a}from"./chunk-BWWQXU2B.mjs";import{a as o}from"./chunk-EADHKH3A.mjs";import{q as d}from"./chunk-
|
|
7
|
+
import{a as n,b as p,h as a}from"./chunk-BWWQXU2B.mjs";import{a as o}from"./chunk-EADHKH3A.mjs";import{q as d}from"./chunk-TNT27RBG.mjs";var R=`SELECT Id FROM RecordType WHERE SobjectType = '${d}' AND IsPersonType = true`;async function S(i,t){let[y,c]=await Promise.all([o(i,n).then(({records:e})=>p(e)),o(t,n).then(({records:e})=>p(e))]),r;try{let{records:e}=await o(t,R);r=new Set(e.flatMap(s=>typeof s.Id=="string"?[s.Id.slice(0,15)]:[]))}catch{r=void 0}return{mappings:new a().buildMapping(y,c),source:y,target:c,...r?{personTypes:r}:{}}}export{S as a};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a}from"./chunk-
|
|
7
|
+
import{a}from"./chunk-PAXNWTYK.mjs";import"./chunk-PMWAFDUB.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as SeedValidator};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a}from"./chunk-
|
|
7
|
+
import{a}from"./chunk-6PD6K7LP.mjs";import"./chunk-BWWQXU2B.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-TNT27RBG.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-PMWAFDUB.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as readSyncRecordTypes};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{b as N,e as k}from"./chunk-
|
|
7
|
+
import{b as N,e as k}from"./chunk-BBRWFKS5.mjs";import{l as y}from"./chunk-FQGHL7GR.mjs";var S=class{deps;constructor(t){this.deps=t}async mapFields(t,n,r,i=0,a){let{recordCount:s,fieldRules:f,rows:d}=t;if(s<=0||f.length===0&&!d)return[];let u=f.filter(o=>o.ruleType==="ai_generate"),g=f.filter(o=>o.ruleType==="faker"),R=N(),O=f.filter(o=>o.ruleType!=="ai_generate"&&o.ruleType!=="faker").map(o=>G(o,R)),p=u.length>0?await this.deps.aiGenerator.generate(u,s):[],b=g.length>0?this.deps.fakerFallback.generate(g,s,i):[],m=I(u,p,s),V=m?this.deps.fakerFallback.generate(u.map(q),s,i):[];m&&r?.({fields:C(u,p,s),reason:p.length===0?"no-answer":"short-answer"});let D=[...u,...g],x=this.deps.random??Math.random,_=E(t),F=d?P(f,R,a):void 0,w=[];for(let o=0;o<s;o++){let l={};for(let c of O)l[c.fieldApiName]=L(c,i+o,n,x);p[o]&&Object.assign(l,p[o]);for(let c of m?u:[])(l[c.fieldApiName]===void 0||l[c.fieldApiName]===null)&&(l[c.fieldApiName]=V[o]?.[c.fieldApiName]??null);b[o]&&Object.assign(l,b[o]);for(let c of D)l[c.fieldApiName]=M(l[c.fieldApiName],c.config.maxLength);_&&typeof l[h]=="string"&&(l[T]=this.deps.fakerFallback.dateOf(j.test(l[h])?"pastDate":"futureDate"));let A=d?.[i+o];A&&F&&Object.assign(l,F(A)),w.push(l)}return w}};function P(e,t,n){let r=new Set(e.filter(a=>a.fieldType?.toLowerCase()==="phone").map(a=>a.fieldApiName)),i=new Map(e.flatMap(a=>a.config.maxLength!==void 0?[[a.fieldApiName,a.config.maxLength]]:[]));return a=>{let s=k(a.values,r,t);for(let[f,d]of Object.entries(s))s[f]=M(d,n?.get(f)??i.get(f));return s}}var h="StageName",T="CloseDate",j=/closed/i;function E(e){return e.objectApiName!=="Opportunity"?!1:e.fieldRules.find(n=>n.fieldApiName===T)?.ruleType==="faker"&&e.fieldRules.some(n=>n.fieldApiName===h)}function G(e,t){let n=e.config.picklistValues;if(e.ruleType!=="picklist_random"||!n)return e;let r=new Set(e.fieldType?.toLowerCase()==="phone"?[e.fieldApiName]:[]),i=n.map(a=>{let s=k({[e.fieldApiName]:a},r,t)[e.fieldApiName];return typeof s=="string"?s:a});return{...e,config:{...e.config,picklistValues:i}}}function M(e,t){if(typeof e!="string"||t===void 0||t<=0||e.length<=t)return e;let n=e.slice(0,t);if(/\s/.test(e.charAt(t)))return n.trimEnd();let r=n.search(/\s\S*$/);return r>0?n.slice(0,r).trimEnd():n}function C(e,t,n){return e.filter(r=>Array.from({length:n},(i,a)=>t[a]?.[r.fieldApiName]).some(i=>i==null)).map(r=>r.fieldApiName)}function I(e,t,n){return e.length===0?!1:t.length<n?!0:t.some(r=>e.some(i=>r[i.fieldApiName]===void 0||r[i.fieldApiName]===null))}function q(e){return{fieldApiName:e.fieldApiName,ruleType:"faker",config:{fakerMethod:"sentence"}}}function L(e,t,n,r=Math.random){switch(e.ruleType){case"static":return e.config.staticValue??null;case"random":return $(e,r);case"sequence":return U(e,t);case"picklist_random":return v(e,r);case"reference":return z(e,n,r);case"formula":return e.config.formula??null;case"regex":return Y(e,t);case"from_csv":return null;default:return null}}function $(e,t){let n=e.config.minValue??0,r=e.config.maxValue??1e3;return Math.floor(n+t()*(r-n+1))}function U(e,t){let n=e.config.sequenceStart??1,r=e.config.sequenceStep??1;return`${e.config.sequencePrefix??""}${n+t*r}`}function Y(e,t){let n=e.config.regexPattern;return n?y(n,t):null}function v(e,t){let n=e.config.picklistValues;if(!n||n.length===0)return null;let r=Math.floor(t()*n.length);return n[r]}function z(e,t,n){let r=e.config.referenceObject;if(!r)return null;let i=t.get(r);if(!i||i.length===0)return null;let a=Math.floor(n()*i.length);return i[a]}export{S as a,L as b};
|
|
@@ -0,0 +1,7 @@
|
|
|
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};
|
|
@@ -4,6 +4,6 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{i as E}from"./chunk-
|
|
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
8
|
${n.kind}
|
|
9
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};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{a as d,b as g,c as f}from"./chunk-W6PN6TJG.mjs";import{a as s,b as a}from"./chunk-Q7TLC3I2.mjs";function c(n,t,e){if(!g(t))return;let o=t.edition?`IsSandbox false, edition ${t.edition}`:"IsSandbox false, and no edition",r=e.action==="write"?`${e.tool} writes to sandboxes and Developer Edition orgs only. Nothing was written`:`${e.tool} deletes from sandboxes and Developer Edition orgs only. Nothing was deleted`;return`${n} is a production org (its Organization record says ${o}): ${r}; ${e.readOnly}, which only reads, runs against it.`}function p(n,t,e){let o=t instanceof Error?t.message:String(t),r=`Nothing was ${e.action==="write"?"written":"deleted"}.`,i=`${e.tool} ${e.action==="write"?"writes to":"deletes from"} no org it cannot tell from a production one`;return s(t)?`${n} refused the session sf gave for it (${o}), and ${i}. "sf org display --target-org ${n}" says what sf holds for it; "sf org login web --alias ${n}" signs in again (in a CI job, "sf org login jwt" or "sf org login sfdx-url"); then run the command again. ${r}`:a(t)?`${n} did not answer (${o}), and ${i}. Run the command again once it answers. ${r}`:f(t)?`${n} would not show its Organization record (${o}), and ${i}. Reading it takes the View Setup and Configuration permission: give it to the user the alias signs in as, or name an alias of a user who has it. ${r}`:`${n} did not say what org it is (${o}), and ${i}. ${r}`}var u=1;async function y(n,t,e){let o;try{o=await d(n)}catch(i){process.stderr.write(`${p(t,i,e)}
|
|
8
|
+
`),process.exit(u)}let r=c(t,o,e);return r!==void 0&&(process.stderr.write(`${r}
|
|
9
|
+
`),process.exit(u)),o}export{c as a,p as b,y as c};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{j as g}from"./chunk-
|
|
7
|
+
import{j as g}from"./chunk-PMWAFDUB.mjs";var f=class{link(n,r,i,t){return t.length===0?n:n.map(o=>({...o,[r]:t[Math.floor(Math.random()*t.length)]}))}resolveInsertOrder(n,r=[]){let i=new Map;for(let e of n)i.set(e.objectApiName,e);let t=new Set,o=new Set,d=[];function c(e){if(t.has(e))return;if(o.has(e))throw new Error(`Circular dependency detected involving: ${e}`);o.add(e);let s=i.get(e);if(s){let p=g(s,r);for(let j of p)c(j);d.push(s)}o.delete(e),t.add(e)}for(let e of n)c(e.objectApiName);return d}};export{f as a};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a,b}from"./chunk-
|
|
7
|
+
import{a,b}from"./chunk-KAZS5Z6W.mjs";import"./chunk-BBRWFKS5.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-PMWAFDUB.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as ScenarioCompileError,b as compileScenario};
|