sandforge 1.84.1 → 1.86.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/lib/{chunk-S42RBRH2.mjs → chunk-22L43JMK.mjs} +1 -1
- package/lib/{chunk-Y2DRK37K.mjs → chunk-2LSGWTWX.mjs} +1 -1
- package/lib/{chunk-24RFOFYT.mjs → chunk-2YJJTQNC.mjs} +1 -1
- package/lib/chunk-34SMB5PA.mjs +10 -0
- package/lib/chunk-35B73566.mjs +7 -0
- package/lib/{chunk-3TZSBHEY.mjs → chunk-35IJ4WEU.mjs} +1 -1
- package/lib/chunk-3EHPAFKV.mjs +7 -0
- package/lib/{chunk-6YL7BNYD.mjs → chunk-3HAVVEXF.mjs} +1 -1
- package/lib/{chunk-6JWWSDM6.mjs → chunk-3I6FXFCN.mjs} +1 -1
- package/lib/{chunk-WUUKFE2U.mjs → chunk-3KJCSYXY.mjs} +1 -1
- package/lib/{chunk-2HVOZUM4.mjs → chunk-3L6DVNCR.mjs} +1 -1
- package/lib/chunk-3LRFPGYZ.mjs +7 -0
- package/lib/{chunk-GWZRR3MM.mjs → chunk-3MVWGL5A.mjs} +1 -1
- package/lib/{chunk-KGU4SVIT.mjs → chunk-4CSBZZAL.mjs} +1 -1
- package/lib/{chunk-JE6SCT6R.mjs → chunk-4NSXPONF.mjs} +1 -1
- package/lib/{chunk-UIOMAX56.mjs → chunk-4VLP6RHC.mjs} +1 -1
- package/lib/{chunk-YA6ATMTB.mjs → chunk-4XROG5CT.mjs} +1 -1
- package/lib/chunk-54V4FVEY.mjs +7 -0
- package/lib/chunk-55OJJT2Q.mjs +7 -0
- package/lib/{chunk-6QE6R6RL.mjs → chunk-5EHHQ5UX.mjs} +1 -1
- package/lib/{chunk-FITPY3L4.mjs → chunk-5JMQXHJ2.mjs} +1 -1
- package/lib/{chunk-W6PN6TJG.mjs → chunk-65AMXOQU.mjs} +1 -1
- package/lib/{chunk-3Q353S2R.mjs → chunk-6HHSAPIM.mjs} +1 -1
- package/lib/chunk-6KVBCFVS.mjs +7 -0
- package/lib/chunk-6NG7C2U3.mjs +476 -0
- package/lib/chunk-6ROL3KBM.mjs +7 -0
- package/lib/{chunk-2JDAOWUW.mjs → chunk-72AWCN7U.mjs} +1 -1
- package/lib/{chunk-JLSIWO4Z.mjs → chunk-7KHA5UIQ.mjs} +1 -1
- package/lib/chunk-7O6EFNQS.mjs +10 -0
- package/lib/{chunk-WWTCWWZI.mjs → chunk-A2CH2QGX.mjs} +1 -1
- package/lib/chunk-A2TXLAC3.mjs +276 -0
- package/lib/chunk-ALWVNR34.mjs +7 -0
- package/lib/{chunk-D4GF4FAB.mjs → chunk-ATBQIE2V.mjs} +1 -1
- package/lib/{chunk-NED4MBIM.mjs → chunk-ATQML7ZK.mjs} +1 -1
- package/lib/chunk-AVY742BJ.mjs +7 -0
- package/lib/{chunk-YWEQQL3C.mjs → chunk-AXTB2HJS.mjs} +1 -1
- package/lib/chunk-BBZUGKBZ.mjs +10 -0
- package/lib/chunk-BIDXK7KA.mjs +7 -0
- package/lib/{chunk-O677VOGO.mjs → chunk-BLMJ4WVI.mjs} +1 -1
- package/lib/{chunk-RE7RYF3B.mjs → chunk-BNHJCJJM.mjs} +1 -1
- package/lib/{chunk-5M5FQ7RP.mjs → chunk-BNPQEQXC.mjs} +1 -1
- package/lib/chunk-C5AUNG6T.mjs +37 -0
- package/lib/{chunk-ETDCBLGU.mjs → chunk-C5EQ7GFC.mjs} +1 -1
- package/lib/{chunk-MJZU3U5O.mjs → chunk-C7CKDZMC.mjs} +61 -61
- package/lib/{chunk-HCGXK7G7.mjs → chunk-CB4U22NR.mjs} +1 -1
- package/lib/chunk-CJAWKLAL.mjs +7 -0
- package/lib/chunk-CL75DEMQ.mjs +9 -0
- package/lib/{chunk-VCUXCK36.mjs → chunk-CLUNF4FK.mjs} +1 -1
- package/lib/chunk-CSMGP53U.mjs +7 -0
- package/lib/{chunk-7YNM6KFZ.mjs → chunk-CT324C7I.mjs} +1 -1
- package/lib/{chunk-7UVKIWKV.mjs → chunk-CZXDJXQP.mjs} +1 -1
- package/lib/{chunk-43TOMFV4.mjs → chunk-D2X6U3MS.mjs} +1 -1
- package/lib/{chunk-M6K34KGF.mjs → chunk-DAUX63UB.mjs} +1 -1
- package/lib/chunk-DB7JNALQ.mjs +10 -0
- package/lib/chunk-DDNCJVZ2.mjs +17 -0
- package/lib/{chunk-FP7CYB2F.mjs → chunk-DLSU66MY.mjs} +1 -1
- package/lib/{chunk-JKJ74BX5.mjs → chunk-DO6PSHQZ.mjs} +1 -1
- package/lib/{chunk-MDMPJEV3.mjs → chunk-DUBECLZV.mjs} +1 -1
- package/lib/{chunk-KZTZDC7H.mjs → chunk-DYHF6DNT.mjs} +1 -1
- package/lib/chunk-E5FSPXYH.mjs +930 -0
- package/lib/{chunk-Q7GIJBCD.mjs → chunk-EGL3I3IX.mjs} +1 -1
- package/lib/chunk-EIYMQPMG.mjs +7 -0
- package/lib/{chunk-RHNTHGNU.mjs → chunk-EUIALBMX.mjs} +1 -1
- package/lib/{chunk-NCZKWSC7.mjs → chunk-FI3R5ZOQ.mjs} +1 -1
- package/lib/{chunk-PAXNWTYK.mjs → chunk-FM4QCTO7.mjs} +1 -1
- package/lib/{chunk-HV7VPEXP.mjs → chunk-FRSIEASH.mjs} +1 -1
- package/lib/{chunk-QAFPQ3YB.mjs → chunk-FV6MOSHD.mjs} +1 -1
- package/lib/chunk-FYG47CNA.mjs +7 -0
- package/lib/chunk-GB6W4Q56.mjs +7 -0
- package/lib/chunk-GEV2DCMK.mjs +7 -0
- package/lib/{chunk-NSQWI7ZY.mjs → chunk-GFB2DNCB.mjs} +1 -1
- package/lib/chunk-GFGMGFSH.mjs +7 -0
- package/lib/{chunk-RGUQOSBU.mjs → chunk-GIFQXB2Q.mjs} +1 -1
- package/lib/{chunk-JAEDM4SI.mjs → chunk-GP5J3DGS.mjs} +1 -1
- package/lib/chunk-GQZEX7LH.mjs +231 -0
- package/lib/{chunk-JSAJS3MY.mjs → chunk-GYDTM62J.mjs} +1 -1
- package/lib/{chunk-OPMO6I45.mjs → chunk-GYFIXUJG.mjs} +1 -1
- package/lib/chunk-GZW2GNFK.mjs +7 -0
- package/lib/chunk-H6BHWAX7.mjs +8 -0
- package/lib/{chunk-EAC5QCE3.mjs → chunk-HDDJ3CVN.mjs} +1 -1
- package/lib/{chunk-5SMWFNE7.mjs → chunk-HDWB4ZOG.mjs} +1 -1
- package/lib/chunk-HGVPBJR6.mjs +7 -0
- package/lib/{chunk-BBRWFKS5.mjs → chunk-HLROVOR6.mjs} +1 -1
- package/lib/{chunk-LKTNQEBS.mjs → chunk-HUOR4M2L.mjs} +1 -1
- package/lib/chunk-HZCS6EED.mjs +8 -0
- package/lib/{chunk-36JOHEJL.mjs → chunk-HZUI56KZ.mjs} +1 -1
- package/lib/chunk-IAB5H7WN.mjs +7 -0
- package/lib/{chunk-X4BXESMQ.mjs → chunk-IQ5UKRHU.mjs} +1 -1
- package/lib/{chunk-54WZUS7J.mjs → chunk-IRQ4WANV.mjs} +1 -1
- package/lib/{chunk-5IZTFMJM.mjs → chunk-IT3DGX37.mjs} +1 -1
- package/lib/chunk-J347SPU6.mjs +49 -0
- package/lib/{chunk-QO53K5W2.mjs → chunk-JANBNTR5.mjs} +1 -1
- package/lib/chunk-JFXQZPRY.mjs +9 -0
- package/lib/{chunk-KAZS5Z6W.mjs → chunk-JRLYWVF4.mjs} +1 -1
- package/lib/{chunk-GKY2JMHY.mjs → chunk-JSNMUTY6.mjs} +1 -1
- package/lib/chunk-JTNJKSAA.mjs +7 -0
- package/lib/{chunk-7WATA4SB.mjs → chunk-JV2LAKWQ.mjs} +1 -1
- package/lib/{chunk-WAPSSYMT.mjs → chunk-JV7K2ZHK.mjs} +1 -1
- package/lib/{chunk-ZBAWJUG2.mjs → chunk-K4TQ7YHX.mjs} +1 -1
- package/lib/chunk-K5PUMHZU.mjs +7 -0
- package/lib/chunk-KH4KLCYG.mjs +7 -0
- package/lib/{chunk-OLCVHL7I.mjs → chunk-KQVLZVOP.mjs} +1 -1
- package/lib/chunk-KWUS7UAV.mjs +19 -0
- package/lib/{chunk-JGZPD4IM.mjs → chunk-L6G73FXM.mjs} +1 -1
- package/lib/{chunk-BAWCOKRW.mjs → chunk-LG466Q5H.mjs} +1 -1
- package/lib/{chunk-GMIGWR6U.mjs → chunk-LHNAR6FC.mjs} +1 -1
- package/lib/chunk-LT4GHEI2.mjs +7 -0
- package/lib/{chunk-EC72TIEG.mjs → chunk-MR262Y3B.mjs} +1 -1
- package/lib/{chunk-LA4KIATH.mjs → chunk-NCCHOV2N.mjs} +1 -1
- package/lib/chunk-NICRSGLS.mjs +7 -0
- package/lib/chunk-NV5QA2HY.mjs +7 -0
- package/lib/{chunk-PR3XCSPO.mjs → chunk-O3GIN5TU.mjs} +1 -1
- package/lib/chunk-O6FHK6NQ.mjs +13 -0
- package/lib/{chunk-M4BLK6HJ.mjs → chunk-O7YIEFG7.mjs} +1 -1
- package/lib/chunk-OCUVAA5E.mjs +7 -0
- package/lib/chunk-OLCS7JCT.mjs +14 -0
- package/lib/chunk-ON7Y63FK.mjs +9 -0
- package/lib/{chunk-N4WPCWJO.mjs → chunk-OO2WY3UB.mjs} +1 -1
- package/lib/{chunk-MSIEU5MR.mjs → chunk-OT2NHL2V.mjs} +1 -1
- package/lib/{chunk-6WX5ZU7Q.mjs → chunk-P2M5ZXWU.mjs} +1 -1
- package/lib/{chunk-GNRSF65U.mjs → chunk-P4YOHLZ4.mjs} +1 -1
- package/lib/chunk-PBHDPTT6.mjs +343 -0
- package/lib/chunk-PE7CHD2W.mjs +7 -0
- package/lib/{chunk-PBY2O6OF.mjs → chunk-PIQ2I67B.mjs} +1 -1
- package/lib/chunk-PKYDNZJK.mjs +7 -0
- package/lib/chunk-PVZ72OOQ.mjs +7 -0
- package/lib/chunk-QACFTHJM.mjs +8 -0
- package/lib/{chunk-J3DND3BC.mjs → chunk-QGVL5EW3.mjs} +1 -1
- package/lib/chunk-QHE2RUWX.mjs +7 -0
- package/lib/{chunk-QKEKG2LD.mjs → chunk-RCW5BZNW.mjs} +1 -1
- package/lib/{chunk-4JE4BYXK.mjs → chunk-RJ6HHG7J.mjs} +1 -1
- package/lib/{chunk-ZQWIVYVM.mjs → chunk-RPTEEI4R.mjs} +1 -1
- package/lib/chunk-RQW5S67A.mjs +7 -0
- package/lib/chunk-RTCMYMED.mjs +7 -0
- package/lib/chunk-RWVX7XSD.mjs +7 -0
- package/lib/{chunk-WY5V5PR3.mjs → chunk-RZOINFNL.mjs} +1 -1
- package/lib/chunk-SOOTWGMQ.mjs +7 -0
- package/lib/chunk-STQ2JMIZ.mjs +7 -0
- package/lib/{chunk-6PD6K7LP.mjs → chunk-SUIPDW5O.mjs} +1 -1
- package/lib/{chunk-TNT27RBG.mjs → chunk-SZOJ7BEJ.mjs} +1 -1
- package/lib/{chunk-4EOHEDFP.mjs → chunk-T542Z54E.mjs} +1 -1
- package/lib/chunk-TAN2CIRI.mjs +21 -0
- package/lib/{chunk-A3MYSOOC.mjs → chunk-TCNBINOG.mjs} +1 -1
- package/lib/chunk-TFDF3DBN.mjs +7 -0
- package/lib/chunk-TICZXC53.mjs +9 -0
- package/lib/chunk-TLX45X5U.mjs +7 -0
- package/lib/{chunk-QTG6LUZT.mjs → chunk-TMIV3IWH.mjs} +1 -1
- package/lib/chunk-TQ6HEJ73.mjs +11 -0
- package/lib/chunk-TTU5EQZ6.mjs +7 -0
- package/lib/chunk-TYUYPFDJ.mjs +7 -0
- package/lib/chunk-TZXYVMZC.mjs +7 -0
- package/lib/chunk-UCUFLFNK.mjs +7 -0
- package/lib/chunk-UK3QLBHW.mjs +7 -0
- package/lib/{chunk-IZGCEOYO.mjs → chunk-UM2B4GR7.mjs} +1 -1
- package/lib/chunk-UZFTTNOP.mjs +7 -0
- package/lib/chunk-V3AXSKSU.mjs +7 -0
- package/lib/chunk-VA6EEI6X.mjs +21 -0
- package/lib/{chunk-OFTT7J2M.mjs → chunk-VFKG2G37.mjs} +1 -1
- package/lib/chunk-VJNEW5MQ.mjs +7 -0
- package/lib/{chunk-L53JWJ3S.mjs → chunk-VKREON6Q.mjs} +1 -1
- package/lib/{chunk-NOBQTEQD.mjs → chunk-VNNDYPBL.mjs} +1 -1
- package/lib/{chunk-ZJW6YOMV.mjs → chunk-VRBETPHY.mjs} +1 -1
- package/lib/{chunk-EPFCERGL.mjs → chunk-VT6P3X6R.mjs} +1 -1
- package/lib/{chunk-ZV7ZFQQC.mjs → chunk-VUTQY76O.mjs} +1 -1
- package/lib/chunk-WF5S4FW5.mjs +7 -0
- package/lib/{chunk-Z4LKKOFY.mjs → chunk-WJGK6VGU.mjs} +1 -1
- package/lib/{chunk-5CRLRHOJ.mjs → chunk-WJHMB3SL.mjs} +1 -1
- package/lib/{chunk-OUZQPYT3.mjs → chunk-WQCXOZEJ.mjs} +1 -1
- package/lib/{chunk-L2E5WBGD.mjs → chunk-WVVFR4E3.mjs} +1 -1
- package/lib/{chunk-PWRJRL5U.mjs → chunk-XBYXT74L.mjs} +1 -1
- package/lib/chunk-XJE3LJHP.mjs +7 -0
- package/lib/{chunk-CPQIZGG5.mjs → chunk-XV4CVZYD.mjs} +1 -1
- package/lib/chunk-Y37ED7AS.mjs +7 -0
- package/lib/{chunk-YTLUYSMF.mjs → chunk-YGBNZYT4.mjs} +1 -1
- package/lib/{chunk-4CVUUVGJ.mjs → chunk-YGTOX7IL.mjs} +1 -1
- package/lib/{chunk-OMNMLKDT.mjs → chunk-YJ27WHKR.mjs} +1 -1
- package/lib/chunk-YRULC27A.mjs +7 -0
- package/lib/{chunk-RMFU4BAL.mjs → chunk-YSVAHT4Q.mjs} +4 -4
- package/lib/chunk-YTOTMJTY.mjs +15 -0
- package/lib/{chunk-B63POIPQ.mjs → chunk-YZKZC62O.mjs} +1 -1
- package/lib/{chunk-DPMRIMUC.mjs → chunk-YZQN7BRB.mjs} +1 -1
- package/lib/{chunk-7SQSWVAU.mjs → chunk-Z5IUK2QO.mjs} +1 -1
- package/lib/{chunk-M2ABR4JM.mjs → chunk-ZEGSMW5A.mjs} +1 -1
- package/lib/{chunk-PR42EZSR.mjs → chunk-ZIKLQZBG.mjs} +1 -1
- package/lib/chunk-ZVU7MD2S.mjs +7 -0
- package/lib/sandforge-autopilot.mjs +33 -27
- package/lib/sandforge-backup.mjs +19 -19
- package/lib/sandforge-checkpoint.mjs +1 -1
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +32 -14
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +11 -13
- package/lib/sandforge-env.mjs +105 -105
- package/lib/sandforge-frozen.mjs +1 -1
- package/lib/sandforge-mcp.mjs +2 -2
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +13 -13
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +13 -15
- package/lib/sandforge.mjs +1 -1
- package/lib/sf/sandforge/dataops.mjs +2 -2
- package/lib/sfPlugin.mjs +1 -1
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
- package/lib/chunk-23SEDORH.mjs +0 -11
- package/lib/chunk-26POJDIT.mjs +0 -7
- package/lib/chunk-2AZQHBEF.mjs +0 -7
- package/lib/chunk-2METQHGG.mjs +0 -7
- package/lib/chunk-2WFIVO4F.mjs +0 -13
- package/lib/chunk-2YHZBUZE.mjs +0 -7
- package/lib/chunk-326AJTIU.mjs +0 -272
- package/lib/chunk-3PVRGTVK.mjs +0 -7
- package/lib/chunk-5XTUSN72.mjs +0 -8
- package/lib/chunk-6I6TWNV5.mjs +0 -7
- package/lib/chunk-6O222PW6.mjs +0 -7
- package/lib/chunk-6ZLKIT3H.mjs +0 -7
- package/lib/chunk-7QYHEHMA.mjs +0 -9
- package/lib/chunk-B3FBHVNN.mjs +0 -21
- package/lib/chunk-BEA27DLS.mjs +0 -7
- package/lib/chunk-BRY3PLIZ.mjs +0 -7
- package/lib/chunk-CBH3TOWK.mjs +0 -341
- package/lib/chunk-CVHNXJH3.mjs +0 -7
- package/lib/chunk-DGDRQRCW.mjs +0 -7
- package/lib/chunk-DUN2EPRC.mjs +0 -7
- package/lib/chunk-E3A3LOCY.mjs +0 -7
- package/lib/chunk-F2424IKX.mjs +0 -7
- package/lib/chunk-F3AQW6IU.mjs +0 -7
- package/lib/chunk-FNJ4SGWO.mjs +0 -7
- package/lib/chunk-GOOVPVWX.mjs +0 -7
- package/lib/chunk-H2BHESDA.mjs +0 -9
- package/lib/chunk-H4CGM6YO.mjs +0 -7
- package/lib/chunk-HIDW7FNV.mjs +0 -9
- package/lib/chunk-HSBXRQTI.mjs +0 -7
- package/lib/chunk-HUZPBE47.mjs +0 -7
- package/lib/chunk-I6E6T6YY.mjs +0 -7
- package/lib/chunk-IUM4NFKI.mjs +0 -10
- package/lib/chunk-IVFVNNGB.mjs +0 -37
- package/lib/chunk-JCFBFF4Y.mjs +0 -7
- package/lib/chunk-JTJK2D36.mjs +0 -7
- package/lib/chunk-KB4ZHM4Q.mjs +0 -10
- package/lib/chunk-KJWFYBMU.mjs +0 -15
- package/lib/chunk-LC3NDW4N.mjs +0 -7
- package/lib/chunk-OM5NORJG.mjs +0 -7
- package/lib/chunk-OVNMB6Q2.mjs +0 -7
- package/lib/chunk-PEDQPM2P.mjs +0 -926
- package/lib/chunk-PH7SP4YK.mjs +0 -21
- package/lib/chunk-PMN4PAC3.mjs +0 -19
- package/lib/chunk-PMWAFDUB.mjs +0 -48
- package/lib/chunk-PPLVFX6N.mjs +0 -7
- package/lib/chunk-PZBZ7MNC.mjs +0 -7
- package/lib/chunk-QROPNEGY.mjs +0 -14
- package/lib/chunk-RGBGUCJA.mjs +0 -156
- package/lib/chunk-RKTFFCNS.mjs +0 -7
- package/lib/chunk-ROV3QXEF.mjs +0 -475
- package/lib/chunk-RT47RKLY.mjs +0 -7
- package/lib/chunk-SI267LYR.mjs +0 -8
- package/lib/chunk-SRPWW4A2.mjs +0 -10
- package/lib/chunk-T3G6VZNS.mjs +0 -7
- package/lib/chunk-T63U4OZJ.mjs +0 -7
- package/lib/chunk-TEIBWMJM.mjs +0 -7
- package/lib/chunk-TW3N6W5Z.mjs +0 -7
- package/lib/chunk-UBIKR5VO.mjs +0 -7
- package/lib/chunk-UI3JQVRU.mjs +0 -8
- package/lib/chunk-UX3BVH2Y.mjs +0 -7
- package/lib/chunk-VINGECAJ.mjs +0 -10
- package/lib/chunk-VOXJHJIE.mjs +0 -7
- package/lib/chunk-WB2RIVO3.mjs +0 -7
- package/lib/chunk-WXDLQT2O.mjs +0 -10
- package/lib/chunk-XBQGZGWR.mjs +0 -7
- package/lib/chunk-XGGOUNPP.mjs +0 -7
- package/lib/chunk-XKWW3GKF.mjs +0 -7
- package/lib/chunk-YHR4WQPR.mjs +0 -7
- package/lib/chunk-ZQQXSCVI.mjs +0 -7
- package/lib/chunk-ZRUDYB7O.mjs +0 -7
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{I as us,w as ns}from"./chunk-7O6EFNQS.mjs";import{A as bn,G as ue,H as Lo,I as Ot,Q as Do,e as bt,l as Po,u as Co,v as xo,w as Mo,z as yn}from"./chunk-3LRFPGYZ.mjs";import{e as Ns,i as Es}from"./chunk-AVY742BJ.mjs";import{b as _o}from"./chunk-QSRAEUGZ.mjs";import{a as et,d as ds,k as cs,q as Te}from"./chunk-HZCS6EED.mjs";import{a as go,c as ho}from"./chunk-NV5QA2HY.mjs";import{a as Bo}from"./chunk-YYZL7UGV.mjs";import{a as jo,l as Fo}from"./chunk-YDXMTWAT.mjs";import{b as Io}from"./chunk-PVZ72OOQ.mjs";import{d as wo}from"./chunk-QIRO4HTE.mjs";import{d as po,e as mo}from"./chunk-TYUYPFDJ.mjs";import{e as Ts}from"./chunk-TICZXC53.mjs";import{t as ke}from"./chunk-DLSU66MY.mjs";import{a as qo,b as zo,d as Uo,e as kt,f as Ee,g as Vo,h as Go,i as It,j as Jo,k as Ho,l as Ko,m as Yo,n as Zo,o as Qo,p as Xo,q as se,r as ie,s as jt,t as we,u as es}from"./chunk-H6BHWAX7.mjs";import{d as Rn,z as ts}from"./chunk-4CSBZZAL.mjs";import{a as bo,b as _e,c as Ro,d as X,h as pe}from"./chunk-GP5J3DGS.mjs";import{a as yo}from"./chunk-5LFSFYFJ.mjs";import{$a as Ft,Cb as ms,Cc as Ss,Db as gs,Eb as hs,Ec as Os,Fc as As,Kc as ks,Lc as Is,Mc as js,Nb as ws,Nc as me,T as is,Tb as ys,U as An,Ub as bs,V as as,Vb as Rs,Za as Fe,_a as tt,ab as ls,bb as ye,ob as be,rb as fs,sb as ps}from"./chunk-OLCS7JCT.mjs";import{b as oo,l as so}from"./chunk-TQ6HEJ73.mjs";import{b as At}from"./chunk-VV3B6IC3.mjs";import{f as Tt}from"./chunk-EUIALBMX.mjs";import{a as io,b as ao,c as mn,e as co,f as uo,g as lo,i as gn,j as fo}from"./chunk-INIT2UKJ.mjs";import{a as To,c as wn,j as vo}from"./chunk-ATBQIE2V.mjs";import{f as Ao,g as ko}from"./chunk-4XROG5CT.mjs";import{a as z,b as le,c as Nt,d as Sn,e as rs,f as Et,g as os,h as On,i as ss}from"./chunk-TQ2TQHTT.mjs";import{g as Oo}from"./chunk-OHEOJISY.mjs";import{c as So}from"./chunk-EADHKH3A.mjs";import{b as no,r as ro}from"./chunk-DAUX63UB.mjs";import{A as Ur,B as fn,C as Vr,F as Gr,G as pn,J as Jr,K as Hr,O as Kr,R as Yr,S as Zr,T as Qr,U as Xr,V as eo,W as to,e as ln,q as ce,r as oe,s as Me,x as qr,y as zr}from"./chunk-SZOJ7BEJ.mjs";import{a as xe,h as J}from"./chunk-TZE3Y7IQ.mjs";import{a as yt,b as H}from"./chunk-CA5NAXSU.mjs";import{a as $o,b as Wo}from"./chunk-PC247GKX.mjs";import{a as Rt,c as hn,f as No,i as St,k as Eo}from"./chunk-22L43JMK.mjs";import{$a as Lr,Da as xr,Ea as Mr,Ed as Wr,Fa as _r,Fc as Br,Gc as $r,Hc as Qe,Ic as mt,Lc as Xe,Mc as un,Nc as gt,O as Ze,Sc as Ce,T as dn,Tc as ht,Wc as wt,X as Pr,Y as vr,ba as cn,nd as Ae,xa as Oe,ya as Cr,zc as Dr}from"./chunk-J347SPU6.mjs";import{b as W,e as te,f as Ke,i as Ne,k as Z,l as V,m as sn,r as Fr,s as an,u as ve,v as Ye}from"./chunk-WZQEK4WT.mjs";function of(n){return`Salesforce can take several minutes to count a load in what ${n} says it has left: what runs from this machine wrote to it in the last ${oo} minutes, or are still writing, and it has not counted yet is taken off, a load from anywhere else is not`}function sf(n){return n.uncountedMB!==void 0&&n.uncountedMB>0?`, ${Ss(n.uncountedMB)} MB for what runs from this machine wrote to it, or are still writing, that Salesforce has not counted yet`:""}function Ps(n){if("unread"in n.storage)return n.withinMB===void 0?{unread:n.storage.unread}:Fs(n,Math.floor(Math.max(0,n.withinMB)*1048576),{share:Fe,roundingMB:tt,withinMB:n.withinMB,limitedBy:"within"});let{remainingMB:e,maxMB:t,uncountedWrites:r}=n.storage,o=Fe*Ft(n.storage)*1048576,s=n.withinMB!==void 0?Math.max(0,n.withinMB)*1048576:1/0,i=s<o?"within":"storage",a={remainingMB:e,maxMB:t,share:Fe,roundingMB:tt,...r?{uncountedMB:r.mb}:{},...n.withinMB!==void 0?{withinMB:n.withinMB}:{},limitedBy:i},d=Math.floor(Math.min(o,s));return Fs(n,d,a)}function vs(n,e){return e.bytesLimit==="within"&&e.storageBytes!==void 0&&n>e.storageBytes?"storage":e.bytesLimit}function Fs(n,e,t){if(!n.api)return{bytes:e,terms:t};if("unread"in n.api)return{bytes:e,terms:t,requestsUnread:n.api.unread};let r=Object.values(n.otherRequests??{}).reduce((s,i)=>s+Math.max(0,i??0),0),o=Math.max(0,Math.floor(n.api.remaining-be*n.api.max-r));return{bytes:e,terms:t,runRequests:o}}var xa=/__e$/i,Ma=/Share$/;function af(n,e){let t=new Map,r=new Map,o=(i,a)=>{let d=`${i}
|
|
8
|
+
${a}`,c=t.get(d);return c||(c={objectApiName:i,act:a,bytes:0,creates:[]},t.set(d,c)),c},s=i=>{r.set(`${i.objectApiName}
|
|
9
|
+
${i.kind}
|
|
10
|
+
${i.name}`,i)};for(let i of n.firing){let a=i.write;if(!(a!=="insert"&&a!=="update")&&e(i.objectApiName,a)){if(i.kind==="trigger"||!i.flow){s({objectApiName:i.objectApiName,kind:"trigger",name:i.name});continue}if(i.flow.condition!=="read"){s({objectApiName:i.objectApiName,kind:"notRead",name:i.name});continue}for(let d of i.flow.creates??[]){if(xa.test(d))continue;if(Ma.test(d)){s({objectApiName:i.objectApiName,kind:"share",name:d});continue}let c=o(i.objectApiName,a);c.bytes+=ye(d,{rows:1}),c.creates.push({objectApiName:d,by:i.name})}}}return{perRecord:[...t.values()].filter(i=>i.bytes>0),notCounted:[...r.values()]}}function df(n,e){return n.perRecord.reduce((t,r)=>t+r.bytes*Math.max(0,e(r.objectApiName,r.act)),0)}function cf(n,e,t){return{budgetMB:Math.max(0,n.bytes-e)/1048576,...n.terms,automationMB:e/1048576,...t.notCounted.length>0?{notCounted:t.notCounted.map(r=>({...r}))}:{}}}function Cs(n,e){if(!e(1))return 0;if(e(n))return n;let t=1,r=n;for(;r-t>1;){let o=Math.floor((t+r)/2);e(o)?t=o:r=o}return t}function uf(n,e){let t=Math.max(0,Math.floor(n)),r=Math.min(t,Math.max(0,Math.floor(e))),o=[];if(r===0)return o;for(let s=0;s<t;s++)Math.floor((s+1)*r/t)>Math.floor(s*r/t)&&o.push(s);return o}import{existsSync as _a,readFileSync as La,writeFileSync as Da}from"node:fs";function mf(n){let e={getData:()=>_a(n)?JSON.parse(La(n,"utf8")):{},setData:r=>Da(n,JSON.stringify(r,null,2),{encoding:"utf8",mode:384})},t=new us(e);return t.initialize(),t}var kn="User",Ba="005",Ms=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function $a(n,e,t=no){let r=n.referenceTo??[];return n.name==="RecordTypeId"||r.length===0?!1:r.every(o=>t(o))?!0:r.length===1&&e?.(r[0])===!0}var xs=1e5;async function bf(n){let{known:e,ownerMappings:t={},mapped:r,refused:o,inactive:s}=n,i=n.lookups.filter(m=>$a(m,n.outsideTheRun,n.neverCopied)),a=new Map,d=new Set;for(let m of i)for(let g of n.rows){let h=g[m.name];if(typeof h!="string"||!Ms.test(h)||m.name==="OwnerId"&&t[h]!==void 0||r?.(h)===!0||(d.add(h),e.has(h)))continue;let y=m.referenceTo??[];if(!y.some(R=>o?.has(R)===!0))for(let R of y)a.set(R,(a.get(R)??new Set).add(h))}let c=new Set,l=new Set,f=new Set;for(let[m,g]of a){let h=s!==void 0&&m===kn,y=h?"Id, IsActive":"Id";for(let R of X([...g]))try{let S=await n.query(`SELECT ${y} FROM ${J(m)} WHERE Id IN (${R})`);for(let w of S){let b=w.Id;typeof b=="string"&&(c.add(b),c.add(b.slice(0,15)),h&&w.IsActive===!1&&(f.add(b),f.add(b.slice(0,15))))}}catch{for(let S of g)l.add(S);o?.add(m);break}}let p=new Map;for(let m of a.values())for(let g of m)c.has(g)||c.has(g.slice(0,15))?p.set(g,!0):!l.has(g)&&!p.has(g)&&p.set(g,!1);for(let[m,g]of p){if(e.size>=xs)break;e.set(m,g)}if(s&&f.size>0){let m=[...a.get(kn)??[]].filter(g=>f.has(g)||f.has(g.slice(0,15)));for(let g of[...f,...m]){if(s.size>=xs)break;s.add(g)}}let u=new Set;for(let m of d)(p.get(m)??e.get(m))===!1&&u.add(m);return u}function Rf(n,e,t={}){let r=new Set;if(e.size===0)return r;for(let o of n){let s=o.OwnerId;typeof s!="string"||!s||t[s]===void 0&&e.has(s)&&r.add(s)}return r}var Wa="SELECT PermissionsUpdateWithInactiveOwner FROM UserPermissionAccess";async function qa(n){try{let[e]=await n(Wa);return e?.PermissionsUpdateWithInactiveOwner===!0}catch{return!1}}function Sf(n){let e;return()=>(e??=qa(n),e)}async function _s(n,e){let t=new Map;for(let[i,a]of Object.entries(n)){if(!Ms.test(a))continue;let d=a.slice(0,15),c=t.get(d)??{user:a,sources:[]};c.sources.push(i),t.set(d,c)}let r=[],o=[],s=[...t.values()];for(let i=0;i<s.length;i+=_e){let a=s.slice(i,i+_e),[d]=X(a.map(({user:f})=>f)),c;try{c=await e(`SELECT Id, Name, IsActive FROM ${kn} WHERE Id IN (${d})`)}catch{continue}let l=new Set;for(let f of c){let p=f.Id;if(typeof p!="string"||(l.add(p.slice(0,15)),f.IsActive!==!1))continue;let u=t.get(p.slice(0,15));if(!u)continue;let m=f.Name;r.push({user:u.user,...typeof m=="string"&&m!==""?{name:m}:{},sources:u.sources})}for(let{user:f,sources:p}of a)f.startsWith(Ba)&&!l.has(f.slice(0,15))&&o.push({user:f,sources:p})}return{inactive:r,unknown:o}}var Pt=10,In="Nothing was read or written.",If="Nothing was written.";function Ls(n,e=In){let t=n.slice(0,Pt).map(({user:o,name:s,sources:i})=>`${s!==void 0?`${s} (${o})`:o}, given the records of `+i.join(", ")).join("; "),r=n.length-Pt;return`Owners given to users the target holds inactive: ${t}${r>0?`; and ${r} more`:""}. The target refuses a record owned by an inactive user, and the run will not give it to the user it writes as instead of the one chosen. Give those records to an active user under Owners (Review \u2192 Controls, or --owner-map on the command line), or reactivate the user in the target. `+e}function za(n,e=In){let t=n.slice(0,Pt).map(({user:o,sources:s})=>`${o}, given the records of ${s.join(", ")}`).join("; "),r=n.length-Pt;return`Owners given to users the target does not hold: ${t}${r>0?`; and ${r} more`:""}. The target refuses a record owned by a user it does not hold (INVALID_CROSS_REFERENCE_KEY), and the run will not give it to the user it writes as instead of the one chosen. Give those records to a user of the target under Owners (Review \u2192 Controls, or --owner-map on the command line). `+e}async function jf(n,e,t=In){let{inactive:r,unknown:o}=await _s(n,e);if(o.length>0){let s=za(o,t);return new me(js,r.length>0?`${s.slice(0,-t.length)}${Ls(r,t)}`:s)}return r.length>0?new me(Is,Ls(r,t)):void 0}import{createHash as Ua}from"node:crypto";var $s={ContentVersion:"VersionData",Attachment:"Body"},Va=3,Ds=class extends Error{constructor(t,r,o){super(t);this.code=r;this.storage=o;this.name="ForgeFilesRefusedError"}code;storage};function Y(n,e){let t=n[e];return typeof t=="string"&&t!==""?t:void 0}function Bs(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0}function jn(n,e,t){return{objectApiName:n,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:e,messages:[H(t)]}]}}async function xf(n){let{scope:e,sourceOrgId:t,maxFileBytes:r,queryRecords:o}=n,s=new Map;for(let f of e.values())for(let p of f)s.has(p)||s.set(p,s.size);let i={files:[],leftOut:[],errors:[]},a=[...s.keys()];if(a.length===0)return i;let d=f=>s.get(f)??Number.MAX_SAFE_INTEGER,c=new Map;try{for(let f of X(a)){let p=await o(t,`SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility FROM ContentDocumentLink WHERE LinkedEntityId IN (${f})`);for(let u of p){let m=Y(u,"ContentDocumentId"),g=Y(u,"LinkedEntityId");if(!m||!g||!s.has(g))continue;let h=c.get(m)??[];h.some(y=>y.id===g)||h.push({id:g,shareType:Y(u,"ShareType"),visibility:Y(u,"Visibility")}),c.set(m,h)}}}catch(f){i.errors.push(jn("ContentDocument","(links of the records in scope)",f))}let l=[];try{for(let f of X([...c.keys()])){let p=await o(t,`SELECT Id, ContentDocumentId, Title, PathOnClient, ContentSize, ContentLocation, SharingPrivacy FROM ContentVersion WHERE ContentDocumentId IN (${f}) AND IsLatest = true`);for(let u of p){let m=Y(u,"ContentDocumentId"),g=Y(u,"Id"),h=m?c.get(m):void 0;if(!m||!g||!h)continue;let y=Y(u,"Title")??m;l.push({external:(Y(u,"ContentLocation")??"S")!=="S",file:{objectApiName:"ContentDocument",sourceId:m,body:{objectApiName:"ContentVersion",id:g},name:y,bytes:Bs(u,"ContentSize"),hosts:[...h].sort((R,S)=>d(R.id)-d(S.id)),fields:{Title:y,PathOnClient:Y(u,"PathOnClient")??y,...Y(u,"SharingPrivacy")==="P"?{SharingPrivacy:"P"}:{}}}})}}}catch(f){i.errors.push(jn("ContentDocument","(latest versions of the files)",f))}try{for(let f of X(a)){let p=await o(t,`SELECT Id, ParentId, Name, ContentType, BodyLength, IsPrivate FROM Attachment WHERE ParentId IN (${f})`);for(let u of p){let m=Y(u,"Id"),g=Y(u,"ParentId");if(!m||!g||!s.has(g))continue;let h=Y(u,"Name")??m;l.push({external:!1,file:{objectApiName:"Attachment",sourceId:m,body:{objectApiName:"Attachment",id:m},name:h,bytes:Bs(u,"BodyLength"),hosts:[{id:g}],fields:{Name:h,...Y(u,"ContentType")?{ContentType:Y(u,"ContentType")}:{},IsPrivate:u.IsPrivate===!0}}})}}}catch(f){i.errors.push(jn("Attachment","(attachments of the records in scope)",f))}l.sort((f,p)=>d(f.file.hosts[0].id)-d(p.file.hosts[0].id));for(let{file:f,external:p}of l){let u=p?"external":f.bytes>r?"too-large":void 0;u?i.leftOut.push({objectApiName:f.objectApiName,sourceId:f.sourceId,name:f.name,bytes:f.bytes,reason:u}):i.files.push(f)}return i}function Mf(n){return n.errors.length===0?null:`The files of the records to clone could not all be looked up in the source (${[...new Set(n.errors.flatMap(t=>t.samples.flatMap(r=>r.messages)))].join("; ")}). Run it again, or leave the files out.`}async function _f(n){let{files:e,targetOrgId:t,copiedBefore:r,queryRecords:o}=n,s={files:[],errors:[]},i=new Map;for(let u of e){let m=r(u.sourceId);m&&i.set(u.sourceId,m)}if(i.size===0)return{...s,files:[...e]};let a=new Map,d,c=new Map;for(let[u,m]of i)m.objectApiName==="ContentVersion"&&c.set(m.targetId,u),m.objectApiName==="ContentDocument"&&a.set(u,m.targetId);try{for(let u of X([...c.keys()])){let m=await o(t,`SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id IN (${u})`);for(let g of m){let h=Y(g,"Id"),y=Y(g,"ContentDocumentId"),R=h?c.get(h):void 0;R&&y&&a.set(R,y)}}}catch(u){d=H(u)}let l=new Map,f;try{for(let u of X([...new Set(a.values())])){let m=await o(t,`SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN (${u})`);for(let g of m){let h=Y(g,"ContentDocumentId"),y=Y(g,"LinkedEntityId");h&&y&&l.set(h,[...l.get(h)??[],y])}}}catch(u){f=H(u)}let p=(u,m)=>{s.errors.push({objectApiName:"ContentDocument",stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`${u.name} (${Ae(u.bytes)})`,messages:[m]}]})};for(let u of e){let m=i.get(u.sourceId);if(!m){s.files.push(u);continue}if(u.body.objectApiName==="Attachment")continue;let g=a.get(u.sourceId);if(!g){p(u,`Copied as ContentVersion ${m.targetId} by the run this one takes up, and its document still cannot be read back`+(d?` (${d})`:"")+": the file is not copied again, nor linked to the records it lacks.");continue}if(f){p(u,`Copied by the run this one takes up; its links could not be read (${f}): it is not linked to the records it lacks.`);continue}s.files.push({...u,into:{documentId:g,linked:l.get(g)??[],unchanged:!0}})}return s}function Lf(n){return{objectApiName:"__files__",stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(files)",messages:[n]}]}}function Df(n){return n.reduce((e,t)=>e+t.bytes,0)}function Bf(n,e){return n<=e?null:`The files to copy take ${Ae(n)} and the target has ${Ae(Math.max(0,e))} of file storage left. Lower the largest file copied, or leave the files out.`}async function $f(n,e){let t=await n.remainingFileStorageMB(e);if(!Number.isFinite(t))throw new Error("The target did not say how much file storage it has left.");return t*1048576}function Wf(n,e,t){let r=[];for(let o of n.files){let s=r.find(i=>i.objectApiName===o.objectApiName);s||(s={objectApiName:o.objectApiName,planned:0,plannedBytes:0,copied:0,failed:0},r.push(s)),s.planned++,s.plannedBytes+=o.bytes}return{maxFileBytes:e,objects:r,links:0,leftOut:[...n.leftOut],...t===void 0?{}:{remainingStorageBytes:t}}}function Nn(n,e){let t=n==="Attachment"?"attachment":"file";return e===1?t:`${t}s`}function qf(n){return`[dry-run] ${n.objectApiName}: ${n.planned} ${Nn(n.objectApiName,n.planned)} would be copied (${Ae(n.plannedBytes)})`}function Ga(n,e,t){return n.body.objectApiName==="Attachment"?{Name:n.fields.Name??n.name,BodyLength:n.bytes,ParentId:t}:{Title:n.fields.Title??n.name,Checksum:Ua("md5").update(Buffer.from(e,"base64")).digest("hex"),ContentSize:n.bytes}}function Ja(n){let e={};for(let[t,r]of Object.entries(n))t!=="SharingPrivacy"&&(e[t]=r);return e}async function zf(n){let{files:e,sourceOrgId:t,targetOrgId:r,remapper:o,deps:s,report:i,errors:a,onProgress:d,onCopied:c}=n,l=0,f=w=>{let b=i.objects.find(A=>A.objectApiName===w);return b||(b={objectApiName:w,planned:0,plannedBytes:0,copied:0,failed:0},i.objects.push(b)),b},p=(w,b)=>a.find(A=>A.objectApiName===w&&A.stage===b),u=new Map,m=(w,b,A=1)=>{let E=`${w}/${b}`;u.set(E,(u.get(E)??0)+A);let x=p(w,b);x&&(x.attemptedCount+=A)},g=(w,b,A,E,x=!1)=>{let T=p(w,b);T||(T={objectApiName:w,stage:b,failedCount:0,attemptedCount:u.get(`${w}/${b}`)??0,samples:[]},a.push(T)),x||(T.failedCount++,l++),T.samples.length<Va&&T.samples.push({recordSummary:A,messages:[E]})},h=(w,b,A)=>{g(w.objectApiName,b,`${w.name} (${Ae(w.bytes)})`,A),f(w.objectApiName).failed++},y=async(w,b,A)=>{let E=A.flatMap(T=>{let v=o.get(T.id);return v?[{ContentDocumentId:b,LinkedEntityId:v,ShareType:T.shareType??"V",Visibility:T.visibility??"AllUsers"}]:[]});if(E.length===0)return[];let x=[];m("ContentDocumentLink","insert",E.length);try{let T=await s.insertRecords(r,"ContentDocumentLink",E);E.forEach((v,I)=>{let N=T[I];if(N?.success){i.links++,x.push(v.LinkedEntityId);return}g("ContentDocumentLink","insert",w.name,N?.errors.join("; ")||"The target gave no reason.")})}catch(T){for(let v=0;v<E.length;v++)g("ContentDocumentLink","insert",w.name,H(T))}return x},R=e.filter(w=>!(w.body.objectApiName==="ContentVersion"&&w.into?.unchanged)).length,S=0;for(let w of e){await n.waitIfPaused();let b=w.hosts.filter(O=>o.isCreated(O.id)),A=w.body.objectApiName==="ContentVersion"?w.into:void 0,E=A?b.filter(O=>{let C=o.get(O.id);return C!==void 0&&!A.linked.includes(C)}):[];if(A?.unchanged){let O=await y(w,A.documentId,E);O.length>0&&c?.(w,{targetId:A.documentId,linked:O,asVersion:!1});continue}let x=S++,T=b.length>0?o.get(b[0].id):void 0;if(!T&&!A){i.leftOut.push({objectApiName:w.objectApiName,sourceId:w.sourceId,name:w.name,bytes:w.bytes,reason:"record-not-created"});continue}d({objectName:w.objectApiName,status:"running",progress:Math.round(x/R*100),message:`Copying ${Nn(w.objectApiName,1)} ${x+1} of ${R} (${Ae(w.bytes)})`});let v;m(w.objectApiName,"query");try{v=await s.readFileBody(t,w.body.objectApiName,w.body.id)}catch(O){h(w,"query",H(O));continue}let I=Buffer.byteLength(v,"base64");if(I!==w.bytes){h(w,"query",`Read ${I} bytes of the ${w.bytes} the source reports: the file was not written.`);continue}let N=A?{...Ja(w.fields),VersionData:v,ContentDocumentId:A.documentId}:w.body.objectApiName==="ContentVersion"?{...w.fields,VersionData:v,FirstPublishLocationId:T}:{...w.fields,Body:v,ParentId:T},_;m(w.objectApiName,"insert");let D=n.calls?.sending(w.body.objectApiName,[{sourceId:w.sourceId,payload:Ga(w,v,T)}]),j=()=>{D!==void 0&&n.calls?.answered(D)};try{_=await s.insertFile(r,w.body.objectApiName,N)}catch(O){Bo(O)!=="may-have-written"&&j(),h(w,"insert",H(O));continue}if(!_.success||!_.id){j(),h(w,"insert",_.errors.join("; ")||"The target gave no reason.");continue}if(f(w.objectApiName).copied++,w.body.objectApiName==="Attachment"){o.add(w.sourceId,_.id,"Attachment"),j(),o.persist?.(),c?.(w,{targetId:_.id,linked:T?[T]:[],asVersion:!1});continue}if(A){o.add(w.sourceId,A.documentId,"ContentDocument"),j(),o.persist?.();let O=await y(w,A.documentId,E);c?.(w,{targetId:A.documentId,linked:O,asVersion:!0});continue}o.add(w.sourceId,_.id,"ContentVersion"),j(),o.persist?.();let F;try{let O=await s.queryRecords(r,`SELECT ContentDocumentId FROM ContentVersion WHERE Id = '${xe(_.id)}'`);F=O[0]?Y(O[0],"ContentDocumentId"):void 0}catch{F=void 0}if(!F){g("ContentDocument","query",`${w.name} (${Ae(w.bytes)})`,`Copied as ContentVersion ${_.id}, but its document could not be read back: the run keeps the version, which a removal of the run takes with its document, and links it to no other record.`,!0);continue}o.add(w.sourceId,F,"ContentDocument"),o.persist?.();let k=await y(w,F,b.slice(1));c?.(w,{targetId:F,linked:T?[T,...k]:k,asVersion:!1})}for(let w of i.objects)d({objectName:w.objectApiName,status:w.failed>0&&w.copied===0?"error":"done",progress:100,message:`Copied ${w.copied} ${Nn(w.objectApiName,w.copied)} of ${w.planned}`+(w.failed>0?`, ${w.failed} failed`:"")});return l}import{createHmac as Ha,randomBytes as Ka}from"node:crypto";function Xf(n,e,t={},r,o){if(!n)return;let s={},i={};for(let c of e.nodes){cs(c)&&(s[c.objectApiName]=[...c.anonymizeFields]);let l=Object.entries(c.orgClassified??{});l.length>0&&(i[c.objectApiName]=Object.fromEntries(l.map(([f,p])=>[f,p.classification])))}let a=o==="everything",d=r?a?(c,l)=>ho(f=>r([...f]),l??"",c,"everything"):r:void 0;return{fields:s,methods:{...t},...Object.keys(i).length>0?{classes:i}:{},...d?{personalFieldsOf:d}:{},...a?{everything:!0}:{}}}var Ya=/(?:State|StateCode|Country|CountryCode)$/,Za=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Qa=/@example\.com$/i,En="@example.invalid",Xa=64,ed=new Set(["fake","mask","preserve_format","shuffle"]);function td(n,e,t){return typeof n!="string"||n===""?n:Za.test(n)?e.email(n.replace(Qa,En),t):`${n.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,Xa).replace(/^[._]+|[._]+$/g,"")||"anonymized"}${En}`}var Ws=class{smartAnonymizer;contactPoints;constructor(e,t){this.smartAnonymizer=new wo(e),this.contactPoints=new Es(t),this.redactionKey=t??Ka(32).toString("hex")}redactionKey;categorizeField(e,t,r){let o=this.categoryByNameAndType(e,t);return o==="other"&&r==="PCI"?"financial":o}categoryByNameAndType(e,t){let r=t.toLowerCase();if(r==="email")return"email";if(r==="phone")return"phone";let o=mo(e,t);if(o)return o;let s=e.toLowerCase();return s.includes("email")?"email":s.includes("phone")||s.includes("fax")||s.includes("mobile")?"phone":s.includes("firstname")||s.includes("lastname")||s==="name"||po(e)||s==="company"||s==="companyname"||s==="suppliedcompany"?"name":s.includes("street")||s.includes("address")||s.includes("city")||s.includes("state")||s.includes("postalcode")||s.includes("zip")||s.includes("country")?"address":s.includes("ssn")||s.includes("national_id")||s.includes("passport")||s.includes("driver")||s.includes("license")?"ssn_id":s.includes("credit")||s.includes("card")||s.includes("cvv")||s.includes("iban")||s.includes("routing")||s.includes("bank")?"financial":"other"}getDefaultMethod(e){return{email:"fake",phone:"mask",name:"fake",address:"fake",ssn_id:"redact",financial:"hash",other:"nullify"}[e]}getDefaults(){return{email:"fake",phone:"mask",name:"fake",address:"fake",ssn_id:"redact",financial:"hash",other:"nullify"}}anonymize(e){if(e.fields.length===0)return e.records;let t={...this.getDefaults(),...e.methods},r=e.records.map((a,d)=>({...a,Id:e.sourceIds[d]??""})),o=this.anonymizeRecords(r,e.fields,t,e.objectApiName),s=e.fields.filter(a=>this.categorizeField(a.name,a.type,a.classification)==="email"),i=ed.has(t.phone)?e.fields.filter(a=>this.categorizeField(a.name,a.type,a.classification)==="phone"):[];return o.map((a,d)=>{let c=e.records[d],l={...a};for(let f of s)l[f.name]=this.undeliverable(l[f.name],f);for(let f of i)l[f.name]=this.fictionalNumber(c[f.name],l[f.name],f);return e.everything===!0&&this.everythingOverrides(e,c,l),"Id"in c?l.Id=c.Id:delete l.Id,l})}everythingOverrides(e,t,r){let o=[];for(let d of e.fields){let c=go(e.objectApiName,{name:d.name,type:d.type});c==="birthdate"||c==="address"&&Ya.test(d.name)?r[d.name]=null:c==="free_text"&&o.push(d.name)}if(o.length===0)return;let s=new Set(o),i=e.fields.filter(d=>!s.has(d.name)).flatMap(d=>{let c=t[d.name];if(typeof c!="string"||c.trim()==="")return[];let l=r[d.name];return[{original:c,masked:typeof l=="string"?l:null}]}),a=d=>Ha("sha256",this.redactionKey).update(d).digest("hex");for(let d of o){let c=t[d];r[d]=typeof c=="string"?Io(c,{known:i,digest:a}):c}}undeliverable(e,t){let r=t.length!==void 0&&t.length>0?t.length:void 0;return t.type.toLowerCase()==="email"?td(e,this.contactPoints,r??Ns):typeof e!="string"?e:this.contactPoints.addressesIn(e.replace(/@example\.com(?![\w.-])/gi,En),r)}fictionalNumber(e,t,r){if(typeof e!="string")return t;if(!/\d/.test(e))return e;let o=r.length!==void 0&&r.length>0?r.length:void 0;return this.contactPoints.phone(e,o)}anonymizeRecords(e,t,r,o){let s=t.map(a=>{let d=this.categorizeField(a.name,a.type,a.classification);return{objectApiName:o,fieldApiName:a.name,method:r[d],piiCategory:"PII",aiConfidence:1,userOverridden:!1}}),i=e.map(a=>({...a}));return this.smartAnonymizer.anonymize(i,s,o)}};var qs=new WeakMap;function tp(n,e){typeof n=="object"&&n!==null&&qs.set(n,e)}function np(n){return typeof n=="object"&&n!==null?qs.get(n):void 0}function Tn(n){let e=0,t=new Map,r=new Map,o=[],s=new Set,i=new Map,a=[],d=p=>{t.set(p,e),r.set(p,e),e++,o.push(p),s.add(p);for(let u of[...n.get(p)??[]].sort())n.has(u)&&(t.has(u)?s.has(u)&&r.set(p,Math.min(r.get(p)??0,t.get(u)??0)):(d(u),r.set(p,Math.min(r.get(p)??0,r.get(u)??0))));if(r.get(p)===t.get(p)){let u=[],m;do{if(m=o.pop(),m===void 0)break;s.delete(m),i.set(m,a.length),u.push(m)}while(m!==p);a.push(u.sort())}};for(let p of[...n.keys()].sort())t.has(p)||d(p);let c=a.map((p,u)=>{let m=new Set;for(let g of p)for(let h of n.get(g)??[]){let y=i.get(h);y!==void 0&&y!==u&&m.add(y)}return m}),l=new Set,f=[];for(;l.size<a.length;){let p=a.map((u,m)=>({component:u,i:m})).filter(({i:u})=>!l.has(u)&&[...c[u]].every(m=>l.has(m))).sort((u,m)=>u.component[0].localeCompare(m.component[0]));for(let{component:u,i:m}of p)l.add(m),f.push(u)}return f}function Fn(n,e){let t=new Set(n),r=new Map(n.map(s=>[s,new Set([...e.get(s)??[]].filter(i=>t.has(i)))])),o=[];for(;;){let s=[...r.entries()].filter(([,i])=>i.size===0).map(([i])=>i).sort();if(s.length===0)break;for(let i of s){o.push(i),r.delete(i);for(let a of r.values())a.delete(i)}}return[...o,...[...r.keys()].sort()]}function nd(n,e,t){let r=new Set(n),o=new Map;for(let s of e){if(!r.has(s.to)||!r.has(s.from))continue;let i=t(s.to)?.find(d=>d.name===s.fieldApiName),a=i!==void 0&&mt(i);!s.required&&!Br(s.to,s.fieldApiName)&&!a||o.set(s.to,(o.get(s.to)??new Set).add(s.from))}return o}function rd(n,e){let t=new Set(n),r=e.filter(s=>s.from!==s.to&&t.has(s.from)&&t.has(s.to)),o=new Map(n.map(s=>[s,new Set]));for(let s of r)o.get(s.to)?.add(s.from);return{within:r,deps:o,groups:Tn(o)}}function sp(n,e,t){return n.flatMap(r=>{let{groups:o,within:s}=rd(r,e);return o.flatMap(i=>i.length>1?Fn(i,nd(i,s,t)):i)})}var od=100,sd=.25,id=2048;function Pe(n,e){return typeof n!="string"||n===""?!1:e.prefix===void 0||e.prefix!==null&&n.startsWith(e.prefix)}function ad(n){let e=new Set(n.map(o=>o.objectApiName)),t=new Map,r=new Map;for(let o of n){let s=new Set,i=new Set;for(let a of o.fields){if(a.referenceTo.length===0||!Qe(a))continue;let d=Pn(o.objectApiName,a)||mt(a);for(let c of a.referenceTo)c===o.objectApiName||!e.has(c)||(s.add(c),d&&i.add(c))}t.set(o.objectApiName,s),r.set(o.objectApiName,i)}return Tn(t).flatMap(o=>o.length>1?Fn(o,r):o)}function Pn(n,e){return $r(n,e.name,e.nillable)}function dd(n){let e=new Map(n.objects.map(u=>[u.objectApiName,u])),t=new Map;for(let u of e.keys())n.referenceData?.has(u)&&t.set(u,"referenceData");for(let u of n.whole??[])e.has(u)&&!t.has(u)&&t.set(u,"asked");let r=sd*Math.max(0,n.roomBytes),o=u=>u.rows===void 0?void 0:n.wholeBytes(u.objectApiName,u.rows),s=[...e.values()].filter(u=>Tt.has(u.objectApiName)&&!t.has(u.objectApiName)),i=s.reduce((u,m)=>{let g=o(m);return u===void 0||g===void 0?void 0:u+g},0);if(s.length>0&&i!==void 0&&i<=r&&s.every(u=>n.maxRecordsPerObject===void 0||(u.rows??0)<=n.maxRecordsPerObject))for(let u of s)t.set(u.objectApiName,"catalog");let d=Math.max(od,Math.floor(.01*Math.max(0,n.roomBytes)/id)),c=u=>e.has(u)&&!t.has(u),l=new Set;for(let u of e.values())if(c(u.objectApiName)){for(let m of u.fields)if(Qe(m))for(let g of m.referenceTo)g!==u.objectApiName&&l.add(g)}let f=[...e.values()].filter(u=>!t.has(u.objectApiName)&&!Tt.has(u.objectApiName)&&u.rows!==void 0&&u.rows>0&&u.rows<=d&&(n.maxRecordsPerObject===void 0||u.rows<=n.maxRecordsPerObject)&&l.has(u.objectApiName)).map(u=>({object:u,bytes:o(u)??1/0})).sort((u,m)=>u.bytes-m.bytes||(u.object.objectApiName<m.object.objectApiName?-1:1)),p=0;for(let{object:u,bytes:m}of f){if(p+m>r)break;u.fields.some(h=>Qe(h)&&Pn(u.objectApiName,h)&&h.referenceTo.some(y=>c(y)))||(t.set(u.objectApiName,"smallParent"),p+=m)}return t}function vt(n){let e=new Map(n.objects.map(f=>[f.objectApiName,f])),t=dd(n),r=[...t.values()].includes("catalog"),o=new Map;for(let f of e.keys()){let p=t.get(f);o.set(f,p!==void 0?{kind:"whole",why:p}:{kind:"drawn",rooted:!(Tt.has(f)&&!r)})}let s=n.order?[...n.order]:ad(n.objects),i=new Map(s.map((f,p)=>[f,p])),a=(f,p)=>(i.get(f)??1/0)<(i.get(p)??1/0),d=f=>{let p=o.get(f);return p?.kind==="drawn"&&p.rooted},c=new Map,l=new Map;for(let f of[...e.values()].sort((p,u)=>p.objectApiName<u.objectApiName?-1:1)){let p=f.objectApiName,u=[];for(let m of[...f.fields].sort((g,h)=>g.name<h.name?-1:1)){if(m.referenceTo.length===0||!Qe(m))continue;let g=Pn(p,m),h=m.referenceTo.length>1;for(let y of[...m.referenceTo].sort()){let R=o.get(y),S=ds(p,m,e.get(y)?.childRelationships),w=n.excluded?.get(y),b=T=>h?{prefix:T??null}:{};if(!R){g&&n.excluded?.has(y)&&u.push({objectApiName:p,field:m.name,parent:y,target:"excluded",carries:!1,owed:!1,required:g,masterDetail:S,...b(w)});continue}let A=y===p,E=A||!a(y,p),x={objectApiName:p,field:m.name,parent:y,target:R.kind==="whole"?"whole":"drawn",carries:!A&&d(y)&&d(p)&&(g||!E),owed:E,required:g,masterDetail:S,...b(e.get(y)?.keyPrefix)};if(u.push(x),x.carries){let T=l.get(y)??[];T.push(x),l.set(y,T)}}}c.set(p,u)}return{classes:o,whole:[...t.entries()].map(([f,p])=>({objectApiName:f,why:p})).sort((f,p)=>f.objectApiName<p.objectApiName?-1:1),linksOf:c,carriersInto:l,order:s}}function vn(n,e){return[...new Set((n.linksOf.get(e)??[]).map(t=>t.field))].sort()}function zs(n,e){let t=(n.linksOf.get(e)??[]).filter(s=>s.carries),r=new Set,o=new Set;for(let s of t)(s.prefix===void 0?r:o).add(s.field);return{empty:[...r].sort(),told:[...o].sort()}}function Us(n,e,t,r){return(n.linksOf.get(e)??[]).find(o=>o.field===t&&Pe(r,o))}var ae=2e3,ud=500,Mn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ld=et;function Le(n){return n.length===0?"":` WHERE ${n.join(" AND ")}`}function De(n){return io(n)+2*(n.match(/'/g)?.length??0)}function Vs(n,e,t){let r=De(n)+De(t),o=De(", "),s=[],i=[],a=r;for(let d of e){let c=De(`'${d}'`);i.length>0&&(a+o+c>14e3||i.length>=ud)&&(s.push(i),i=[],a=r),a+=(i.length>0?o:0)+c,i.push(d)}return i.length>0&&s.push(i),s}function nt(n){let e=new Set,t=[];for(let r of n){if(!Mn.test(r))continue;let o=z(r);e.has(o)||(e.add(o),t.push(r))}return t}function Ct(n){return yt(H(n))==="QUERY_TIMEOUT"}var fd=new Set(["MALFORMED_QUERY","INVALID_FIELD"]);function Gs(n){let e=yt(H(n));return e!==void 0&&fd.has(e)}var pd=new Set(["MALFORMED_QUERY","INVALID_FIELD","EXCEEDED_MAX_SEMIJOIN_SUBSELECTS"]),md="SAMPLE_DRAW_INVALID";function gd(n,e,t){if(n.where===void 0)return"strata";if(n.stratifiedBy===void 0||e==="EXCEEDED_MAX_SEMIJOIN_SUBSELECTS")return"where";if(/can ?not be grouped/i.test(t))return"strata";let r=/No such column '([^']+)'/i.exec(t)?.[1]?.toLowerCase();if(r===void 0)return"either";let o=a=>a.toLowerCase().split(/\W+/).includes(r),s=o(n.where),i=o(n.stratifiedBy);return s===i?"either":s?"where":"strata"}var ge="CreatedDate",hd="LastModifiedDate",Js="SystemModstamp";function Ys(n){return n.replace(/'(?:[^'\\]|\\.)*'/g,"''")}function wd(n){return/\(\s*SELECT\b/i.test(Ys(n))}function yd(n){let e=0,t="";for(let r of Ys(n))r==="("&&e++,t+=e===0?r:" ",r===")"&&(e=Math.max(0,e-1));return/\bOR\b/i.test(t)}function Hs(n){let e=n.trim();return wd(e)&&!yd(e)?e:`(${e})`}function Zs(n){return n==null||n===""}function xn(n){return Zs(n)?null:typeof n=="boolean"?n:String(n)}function rt(n){return n===null?"\0":`${typeof n}:${String(n)}`}function bd(n,e){return e===null?`${n} = null`:typeof e=="boolean"?`${n} = ${String(e)}`:`${n} = '${xe(e)}'`}function Rd(n){let e=n.trim();return/[.!?]$/.test(e)?e:`${e}.`}function Sd(n,e){let t=typeof n=="string"?Date.parse(n):Number.NaN;return!Number.isFinite(t)||e.from!==void 0&&t<Date.parse(e.from)?!1:e.to===void 0||t<Date.parse(e.to)}var xt=class{constructor(e,t){this.source=e;this.options=t}source;options;sent=0;rowsRead=0;slow=new Set;ungrouped=new Set;counted=new Map;countedStrata=new Map;standardBook;get requests(){return this.sent}async*pages(e,t){this.options.signal?.throwIfAborted();let r=0;try{for await(let o of this.source.pages(e,t))r++,this.sent++,this.rowsRead+=o.length,yield o}catch(o){throw this.sent++,o}r===0&&this.sent++}async gather(e,t){let r=[];for await(let o of this.pages(e,t))for(let s of o)r.push(s);return r}async count(e,t){this.options.signal?.throwIfAborted();try{return await this.source.count(e,t)}finally{this.sent++}}progress(e,t){this.options.onProgress?.({step:e,rows:this.rowsRead,requests:this.sent,...t})}columnsOf(e,t){let r=this.options.fieldsOf(e);if(r===void 0)throw new Error(`No describe of ${e}: its records cannot be read for a sample.`);let o=new Set(r.map(a=>a.toLowerCase())),s=["Id"],i=new Set(["id"]);for(let a of t){let d=a.toLowerCase();i.has(d)||!o.has(d)||(i.add(d),s.push(J(a)))}return s}readOptionsOf(e){return et.has(e)?{all:!0}:void 0}termsOf(e){let t=this.options.filterOf?.(e);return[...t!==void 0&&t.trim()!==""?[Hs(t)]:[],...et.has(e)?["IsDeleted = false"]:[]]}lists(e,t){let r=t.toLowerCase();return(this.options.fieldsOf(e)??[]).some(o=>o.toLowerCase()===r)}fieldOf(e,t){if((this.options.fieldsOf(e)??[]).find(s=>s.toLowerCase()===t.toLowerCase())===void 0)throw new Error(`${e}.${t} is no field of the source's describe.`);return J(t)}rootShapeOf(e,t={}){let r=J(e.objectApiName),o=t.slow??this.slow.has(r),s=e.carriers.map(S=>({field:this.fieldOf(r,S.field),prefixes:S.drawnPrefixes===void 0?void 0:[...S.drawnPrefixes]})),i=o?[]:s.filter(S=>S.prefixes===void 0),a=s.filter(S=>!i.includes(S)),d=(S,w)=>!Zs(S)&&(w===void 0||w.some(b=>String(S).startsWith(b))),c=t.natural?void 0:e.window,l=c?this.fieldOf(r,c.field):void 0,f=c?.field===hd,p=c!==void 0&&f&&o,u=c&&l&&!p?[...c.from!==void 0?[`${l} >= ${ke(c.from)}`]:[],...c.to!==void 0?[`${l} < ${ke(c.to)}`]:[],...f&&c.from!==void 0&&this.lists(r,Js)?[`${Js} >= ${ke(c.from)}`]:[]]:[],m=t.natural||e.where?.trim()===""?void 0:e.where,g=e.stratifiedBy!==void 0&&(t.stratum!==void 0||t.values)?this.fieldOf(r,e.stratifiedBy):void 0,h=t.stratum?.value===null,y=t.stratum!==void 0&&g!==void 0&&!(h&&o)?[bd(g,t.stratum.value)]:[],R=[];return p&&c&&l&&R.push(S=>Sd(S[l],c)),h&&o&&g!==void 0&&R.push(S=>xn(S[g])===null),{object:r,select:this.columnsOf(r,[...a.map(S=>S.field),...p&&l?[l]:[],...g!==void 0&&(t.values||h&&o)?[g]:[]]),terms:[...this.termsOf(r),...i.map(S=>`${S.field} = null`),...u,...m!==void 0?[Hs(m)]:[],...y],held:i.length>0||f&&u.length>0||h&&y.length>0,tested:a.length>0||R.length>0,isRoot:S=>!a.some(w=>d(S[w.field],w.prefixes))&&R.every(w=>w(S))}}async countRoots(e){let t=new Array(e.length),r=0;return await Te(e,async(o,s)=>{let i=await this.countRootsOf(o);t[s]=i,this.counted.set(o.objectApiName,i.rows),i.strata&&this.countedStrata.set(o.objectApiName,new Map(i.strata.map(a=>[rt(a.value),a.rows]))),r++,this.progress("counting",{objectApiName:o.objectApiName,done:r,total:e.length})}),t}async countRootsOf(e){let t=e.objectApiName,r=this.readOptionsOf(t);e.stratifiedBy!==void 0&&this.refuseUngroupedStratum(e,e.stratifiedBy);let o=!1;for(;;){let s=this.rootShapeOf(e),i;try{i=e.stratifiedBy===void 0?{rows:await this.count(`SELECT COUNT() FROM ${s.object}${Le(s.terms)}`,r)}:await this.countByStratum(e,e.stratifiedBy,s,r)}catch(d){if(o||!s.held||!Ct(d))throw this.drawRefusalOf(e,d);o=!0,this.slow.add(t);continue}let a=this.restricts(e)?await this.countInTheSource(e,{terms:s.terms,rows:i.rows,exact:!s.tested}):void 0;return{objectApiName:t,rows:i.rows,exact:!s.tested,...o?{timedOut:!0}:{},...i.strata?{strata:i.strata}:{},...a?{inTheSource:a}:{}}}}restricts(e){return e.window!==void 0||e.where!==void 0&&e.where.trim()!==""}async countInTheSource(e,t){let r=this.readOptionsOf(e.objectApiName),o=this.slow.has(e.objectApiName);for(;;){let s=this.rootShapeOf(e,{natural:!0,slow:o});if(s.terms.join(`
|
|
11
|
+
`)===t.terms.join(`
|
|
12
|
+
`))return{rows:t.rows,exact:t.exact};try{return{rows:await this.count(`SELECT COUNT() FROM ${s.object}${Le(s.terms)}`,r),exact:!s.tested}}catch(i){if(o||!s.held||!Ct(i))throw i;o=!0}}}async countByStratum(e,t,r,o){let s=this.fieldOf(r.object,t),i=`SELECT ${s}, COUNT(Id) n FROM ${r.object}${Le(r.terms)} GROUP BY ${s}`,a=[],d=0;try{for await(let l of this.pages(i,o)){if(d++,d>1)break;for(let f of l)a.push(f)}}catch(l){if(d===0)throw l;d=2}if(d>1||a.length>=ae)throw this.drawRefused(e,"strata",`${e.objectApiName}.${t} has too many values among the roots of the draw to stratify them: the source counts them in one answer of fewer than ${ae}, and this one ${d>1?"had more after it":`held ${a.length}`}.`);let c=[];for(let l of a){let f=Number(l.n);Number.isFinite(f)&&c.push({value:xn(l[s]),rows:f})}return{rows:c.reduce((l,f)=>l+f.rows,0),strata:c}}refuseUngroupedStratum(e,t){if(this.options.countsBy?.(e.objectApiName,t)===!1)throw this.drawRefused(e,"strata",`The source's describe says the records of ${e.objectApiName} are not counted by ${t}.`)}drawRefusalOf(e,t){let r=H(t),o=yt(r);return o===void 0||!pd.has(o)||!this.restricts(e)&&e.stratifiedBy===void 0?t:this.drawRefused(e,gd(e,o,r),`The source refused to count the roots of ${e.objectApiName} in the draw: ${r}`)}drawRefused(e,t,r){let o=e.objectApiName,s=[];return e.where!==void 0&&t!=="strata"&&s.push(`The source reads the condition of its roots (--fit-where ${o}=\u2026) as it is written: its fields are those of the object, and with the filter it holds two semi-joins at most, none in parentheses an OR is part of.`),e.stratifiedBy!==void 0&&t!=="where"&&s.push(`Stratify ${o} by a field of few values the source groups by \u2014 a picklist, a checkbox, a record type or an owner (--fit-strata ${o}.<Field>) \u2014, or narrow its roots first (--fit-where ${o}=\u2026).`),new me(md,[Rd(r),`Nothing was written, and the counts sent ${this.sent} request(s) of the source.`,...s].join(" "),void 0,void 0,void 0,{sample:{requests:this.sent}})}async drawUniform(e,t){let r=0;await Te(e,async o=>{this.counted.get(o.objectApiName)!==0&&await this.scanRoots(o,t),r++,this.progress("drawing",{objectApiName:o.objectApiName,done:r,total:e.length})})}async scanRoots(e,t){let r=this.readOptionsOf(e.objectApiName),o=e.stratifiedBy;for(;;){let s=this.rootShapeOf(e,o===void 0?{}:{values:!0}),i=`SELECT ${s.select.join(", ")} FROM ${s.object}${Le(s.terms)}`,a=!1;try{for await(let d of this.pages(i,r)){a=!0;let c=d.filter(s.isRoot);if(o===void 0){let l=c.map(f=>String(f.Id));l.length>0&&await t(e.objectApiName,l);continue}for(let{value:l,ids:f}of kd(c,o))await t(e.objectApiName,f,l)}return}catch(d){if(a||!s.held||!Ct(d))throw d;this.slow.add(e.objectApiName)}}}async drawByDate(e,t,r){let o=e.map(i=>({objectApiName:i.objectApiName,by:this.orderedBy(i.objectApiName)})),s=0;return await Te(e,async(i,a)=>{let d=i.objectApiName;if(this.counted.get(d)!==0){let c=o[a].by;if(typeof i.take=="number")i.take>0&&await this.rootsByDate(i,t,c,i.take,void 0,r);else{let l=this.countedStrata.get(d);for(let f of i.take)f.take<=0||l?.get(rt(f.value))===0||await this.rootsByDate(i,t,c,f.take,f,r)}}s++,this.progress("drawing",{objectApiName:d,done:s,total:e.length})}),o}orderedBy(e){return this.lists(e,ge)&&this.options.sorts?.(e,ge)!==!1?"created":"id"}async rootsByDate(e,t,r,o,s,i){let a=e.objectApiName,d=this.readOptionsOf(a),c=0,l;for(;c<o;){let f=this.rootShapeOf(e,s===void 0?{}:{stratum:s}),p=f.tested?ae:Math.min(ae,o-c),u=r==="created"?this.columnsOf(a,[...f.select,ge]):f.select,{after:m,order:g}=Ad(r,t,l),h=`SELECT ${u.join(", ")} FROM ${f.object}${Le([...f.terms,...m])} ORDER BY ${g} LIMIT ${p}`,y;try{y=await this.gather(h,d)}catch(S){if(!f.held||!Ct(S))throw S;this.slow.add(a);continue}let R=y.filter(f.isRoot).map(S=>String(S.Id)).slice(0,o-c);if(c+=R.length,R.length>0&&await(s===void 0?i(a,R):i(a,R,s.value)),y.length<p)return;l=Id(a,y[y.length-1],r)}}async readParents(e){let t=new Array(e.length);return await Te(e,async(r,o)=>{t[o]=await this.parentsOf(r)}),t}async parentsOf(e){let t=J(e.objectApiName),r=this.columnsOf(t,e.columns),o=nt(e.ids),s=this.readOptionsOf(t),i=await this.byList(t,r,"Id",o,this.termsOf(t),s),a=new Set(i.map(p=>z(String(p.Id)))),d=o.filter(p=>!a.has(z(p))),c=this.options.filterOf?.(t),l=[];if(d.length>0&&c!==void 0&&c.trim()!==""){let p=et.has(t)?["IsDeleted = false"]:[];l=await this.byList(t,r,"Id",d,p,s)}let f=new Set(l.map(p=>z(String(p.Id))));return{objectApiName:e.objectApiName,rows:i,columns:r,absent:d.filter(p=>!f.has(z(p))),outsideFilter:l}}async readStandardPrices(e,t){let r=nt(e);if(r.length===0)return[];if(this.standardBook===void 0){let[i]=await this.gather("SELECT Id FROM Pricebook2 WHERE IsStandard = true"),a=i?.Id;this.standardBook=typeof a=="string"&&Mn.test(a)?a:null}if(this.standardBook===null)return[];let o=this.columnsOf("PricebookEntry",["Product2Id",...t]),s=[...this.termsOf("PricebookEntry"),`Pricebook2Id = '${this.standardBook}'`];return this.byList("PricebookEntry",o,"Product2Id",r,s,void 0)}async readPricesIn(e,t,r,o){if(!/^[A-Z]{3}$/.test(e))return[];let s=nt(t),i=nt(r);if(s.length===0||i.length===0)return[];let a=this.columnsOf("PricebookEntry",["Product2Id","Pricebook2Id",...o]),d=[...this.termsOf("PricebookEntry"),`Pricebook2Id IN (${i.map(c=>`'${c}'`).join(", ")})`,`CurrencyIsoCode = '${e}'`];return this.byList("PricebookEntry",a,"Product2Id",s,d,void 0)}async byList(e,t,r,o,s,i){let a=[...s,`${r} IN (`].join(" AND "),d=`SELECT ${mn(t).join(", ")} FROM ${e} WHERE ${a}`,c=[];for(let l of Vs(d,o,")")){let f=`SELECT ${t.join(", ")} FROM ${e} WHERE ${a}${l.map(p=>`'${p}'`).join(", ")})`;for(let p of await gn(f,u=>this.gather(u,i)))c.push(p)}return c}async readChildren(e){let t=new Array(e.length);return await Te(e,async(r,o)=>{t[o]=await this.childrenOf(r)}),t}async childrenOf(e){let t=J(e.objectApiName),r=this.fieldOf(t,e.field),o=e.cap,s=this.orderedBy(t),i=o!=="all"&&s==="created",a=this.columnsOf(t,[r,...e.columns,...i?[ge]:[]]),d=nt(e.parentIds),c=this.readOptionsOf(t),l=this.termsOf(t),f=new Map,p={objectApiName:t,field:r,rows:[],columns:a,cut:[],counts:new Map,newestBy:s},u=()=>{for(let b of d)p.counts.set(b,f.get(z(b))??0);return p};if(d.length===0)return p;if(o==="all"){let b=Cn(await this.byList(t,a,r,d,l,c),r,1/0,s);p.rows=b.rows;for(let[A,E]of b.counts)f.set(A,E);return u()}let m=[...l,`${r} IN (`].join(" AND "),g={head:`SELECT ${r}, COUNT(Id) n FROM ${t} WHERE ${m}`,tail:`) GROUP BY ${r}`},h={head:`SELECT ${mn(a).join(", ")} FROM ${t} WHERE ${m}`,tail:")"},y=De(g.head+g.tail)>De(h.head+h.tail)?g:h,R=[],S=[];for(let b of Vs(y.head,d,y.tail)){let A=e.sourceRows<=o*b.length||this.ungrouped.has(t)||this.options.countsBy?.(t,r)===!1?void 0:await this.countedByParent(t,g,r,b,c);if(A===void 0){R.push(...b);continue}for(let E of A)E.rows>o?S.push(E):R.push(E.parentId)}let w=Cn(await this.byList(t,a,r,R,l,c),r,o,s);p.rows.push(...w.rows),p.cut.push(...w.cut);for(let[b,A]of w.counts)f.set(b,A);for(let b of S){let A=`SELECT ${a.join(", ")} FROM ${t} WHERE ${[...l,`${r} = '${b.parentId}'`].join(" AND ")} ORDER BY ${Od(s)} LIMIT ${o}`,E;try{E=await gn(A,x=>this.gather(x,c))}catch(x){if(!Gs(x))throw x;let T=Cn(await this.byList(t,a,r,[b.parentId],l,c),r,o,s);p.rows.push(...T.rows),p.cut.push(...T.cut);for(let[v,I]of T.counts)f.set(v,I);continue}p.rows.push(...E),p.cut.push({parentId:b.parentId,rows:Math.max(0,b.rows-E.length)}),f.set(z(b.parentId),b.rows)}return u()}async countedByParent(e,t,r,o,s){let i=`${t.head}${o.map(c=>`'${c}'`).join(", ")}${t.tail}`,a;try{a=await this.gather(i,s)}catch(c){if(!Gs(c))throw c;this.ungrouped.add(e);return}let d=[];for(let c of a){let l=c[r],f=Number(c.n);typeof l=="string"&&Number.isFinite(f)&&d.push({parentId:l,rows:f})}return d}async readWhole(e,t){await Te(e,async r=>{let o=J(r.objectApiName),s=this.columnsOf(o,r.columns),i=this.readOptionsOf(o),a=`SELECT ${s.join(", ")} FROM ${o}${Le(this.termsOf(o))}`;for await(let d of fo(a,c=>this.pages(c,i),c=>this.gather(c,i)))await t(r.objectApiName,d)})}};function Od(n){return n==="created"?`${ge} DESC, Id DESC`:"Id DESC"}function Ad(n,e,t){let r=e==="recent",o=r?"<":">",s=r?"DESC":"ASC";if(n==="id")return{after:t?[`Id ${o} '${t.id}'`]:[],order:`Id ${s}`};let i=`${ge} ${s}, Id ${s}`;return t?{after:[`(${ge} ${o} ${t.at} OR (${ge} = ${t.at} AND Id ${o} '${t.id}'))`],order:i}:{after:[],order:i}}function kd(n,e){let t=new Map;for(let r of n){let o=xn(r[e]),s=rt(o),i=t.get(s)??{value:o,ids:[]};i.ids.push(String(r.Id)),t.set(s,i)}return[...t.values()]}function Id(n,e,t){let r=e.Id;if(typeof r!="string"||!Mn.test(r))throw new Error(`A record of ${n} came back without its id.`);if(t==="id")return{at:"",id:r};let o=e[ge];if(typeof o!="string"||!Number.isFinite(Date.parse(o)))throw new Error(`A record of ${n} came back without the date it was made.`);return{at:ke(o),id:r}}function Ks(n){let e=n[ge],t=typeof e=="string"?Date.parse(e):Number.NaN;return Number.isFinite(t)?t:void 0}function jd(n,e){let t=Ks(n),r=Ks(e);return t!==r?t===void 0?1:r===void 0?-1:r-t:le(String(e.Id),String(n.Id))}function Cn(n,e,t,r){let o=new Map;for(let d of n){let c=d[e];if(typeof c!="string")continue;let l=z(c),f=o.get(l);f?f.rows.push(d):o.set(l,{parentId:c,rows:[d]})}let s=[],i=[],a=new Map;for(let[d,{parentId:c,rows:l}]of o)l.sort(r==="created"?jd:(f,p)=>le(String(p.Id),String(f.Id))),s.push(...l.slice(0,t)),l.length>t&&i.push({parentId:c,rows:l.length-t}),a.set(d,l.length);return{rows:s,cut:i,counts:a}}function Mt(n,e,t=0){if(n.rows<=0)return 0;if(e==="uniform")return Math.ceil(n.rows/ae);let r=(s,i)=>Math.ceil(Math.min(Math.max(0,s),i)/ae);if(typeof t=="number")return r(t,n.rows);let o=new Map((n.strata??[]).map(s=>[rt(s.value),s.rows]));return t.reduce((s,i)=>s+r(i.take,o.get(rt(i.value))??i.take),0)}function Qs(n){let e=J(n.objectApiName),t=n.columns.some(p=>p.toLowerCase()==="systemmodstamp"),r=ao(n.columns,t?["Id","SystemModstamp"]:["Id"]),o=Math.max(0,n.planRows),s=Math.max(0,n.sourceRows),i=r.map(p=>uo(e,p)),a=i.reduce((p,u)=>p+Math.ceil(o/u),0),d=Math.max(1,Math.ceil(s/ae)),c=Math.floor(s/ae),l=s%ae,f=d+i.slice(1).reduce((p,u)=>p+c*Math.ceil(ae/u)+(l>0?Math.ceil(l/u):0),0);return ld.has(e)?{by:"cursor",requests:f,byIds:a,byCursor:f,cursorAlone:!0}:a<=f?{by:"ids",requests:a,byIds:a,byCursor:f}:{by:"cursor",requests:f,byIds:a,byCursor:f}}var Nd=new Set(["BusinessHours","OperatingHours"]);function Xs(n,e){if(!(!n||"unread"in n))return Math.floor(n.remaining-be*n.max-e)}function Ed(n){let e=Xs(n.requests,Math.max(0,n.sentBefore??0)+Rs),t=Xs(n.bulkBatches,0);if(e===void 0&&t===void 0)return;let r=n.updatedAfterInsert?{updatedAfterInsert:n.updatedAfterInsert}:{};return(o,s)=>{let i=[...o].map(([d,c])=>({objectApiName:d,rows:c,storageBytes:0})),a=s?{restOnly:s}:{};if(e!==void 0&&gs({plan:{objects:i},...r,bulk:a}).run>e)return"targetRequests";if(t!==void 0&&hs({plan:{objects:i},...r,measures:a}).bulkBatches>t)return"bulkBatches"}}function Td(n){let e=Math.floor(n.left*(1-2*be)),t=new Map(n.objects.map(r=>[r.objectApiName,r]));return r=>{let o=0;for(let[s,i]of r){if(i<=0)continue;let a=t.get(s);o+=ms+(a?Qs({objectApiName:s,columns:a.columns,sourceRows:a.sourceRows,planRows:i}).requests:Math.ceil(i/ae))}return o>e?"sourceRequests":void 0}}function Ep(n,e){let t=n.requests,r=e.source?Td(e.source):void 0;return!t&&!r?n:{...n,requests:o=>t?.(o,e.restOnly)??r?.(o)}}function Fd(n){let{storage:e,withinMB:t}=n,r=new Map;for(let c of n.automation??[])r.set(c.objectApiName,(r.get(c.objectApiName)??0)+c.bytes);let o=n.allowances?Ed(n.allowances):void 0,s={...r.size>0?{automationBytes:c=>r.get(c)??0}:{},...o?{requests:o}:{}};if("unread"in e){if(t===void 0)return;let c=Math.floor(Math.max(0,t)*1048576);return{budget:{bytes:c,withinMB:t,limitedBy:"within"},bytesLimit:"within",roomBytes:c,...s}}let i=Ps({storage:e,...t!==void 0?{withinMB:t}:{}});if("unread"in i)return;let a=i.terms.limitedBy==="within"?"within":"storage",d=Math.floor(Fe*Ft(e)*1048576);return{budget:{bytes:i.bytes,remainingMB:e.remainingMB,maxMB:e.maxMB,share:Fe,roundingMB:tt,...i.terms.uncountedMB!==void 0?{uncountedMB:i.terms.uncountedMB}:{},...t!==void 0?{withinMB:t}:{},limitedBy:a},bytesLimit:a,roomBytes:d,storageBytes:d,...s}}function Pd(n,e){let t=n.nodes.filter(o=>o.included&&!vr(o)&&!e.has(o.objectApiName)),r=new Set(t.map(o=>o.objectApiName));return t.map(o=>({objectApiName:o.objectApiName,rows:o.recordCountUnknown===!0?void 0:o.recordCount,fields:n.edges.filter(s=>s.targetObject===o.objectApiName&&r.has(s.sourceObject)).map((s,i)=>({name:`${s.relationshipName||s.sourceObject}${i}`,referenceTo:[s.sourceObject],isMasterDetail:s.type==="master-detail",nillable:s.required!==!0&&s.type!=="master-detail",createable:s.settable!==!1,updateable:s.settable!==!1}))}))}function Tp(n){let e=n.options??{},t=Pd(n.graph,new Set(n.excludedObjects??[])),r=t.reduce((m,g)=>m+ye(g.objectApiName,{rows:g.rows??0}),0),o=ws({storageBytes:r},n.storage),s=Fd({storage:n.storage,...e.withinMB!==void 0?{withinMB:e.withinMB}:{}}),i=vt({objects:t,referenceData:Nd,...e.whole?{whole:e.whole}:{},roomBytes:s?.roomBytes??0,...n.maxRecordsPerObject!==void 0?{maxRecordsPerObject:n.maxRecordsPerObject}:{},wholeBytes:(m,g)=>ye(m,{rows:g})}),a=e.draw??Oe.draw,d=s?Et(s.budget.bytes,e.maxTotal):0,c=t.filter(m=>{let g=i.classes.get(m.objectApiName);return g?.kind==="drawn"&&g.rooted}),l=new Set(Object.keys(e.rootWhere??{}).map(m=>m.toLowerCase())),f=m=>e.window!==void 0||l.has(m.toLowerCase()),p=c.reduce((m,g)=>{let y=(i.linksOf.get(g.objectApiName)??[]).some(R=>R.carries&&R.required)?0:g.rows??0;return m+1+(f(g.objectApiName)?1:0)+Mt({objectApiName:g.objectApiName,rows:y,exact:!1},a,Math.min(y,d))},0),u=e.window!==void 0||l.size>0;return{wholeOrg:o,...s?{budget:s.budget}:{},whole:i.whole.filter(m=>m.why!=="asked"),planReads:{source:vd(p,n.source),seconds:p*ns,...u?{atMost:!0}:{}}}}function vd(n,e){if("unread"in e)return{verdict:"unread",estimate:n,unread:e.unread};let t=fs(n,e);if(t.verdict==="unread")return t;let r=n>Math.floor(be*e.remaining);return{...t,verdict:r?"exceeds":t.verdict}}var _n=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ei=/^[A-Za-z][A-Za-z0-9_]*$/;function ot(n){if(!n.startsWith('["'))return;let e;try{e=JSON.parse(n)}catch{return}if(!Array.isArray(e))return;let[t,r,o,s]=e;if(!(t!=="c"&&t!=="e"&&t!=="u")&&!(typeof r!="string"||!_n.test(r))&&!(typeof o!="string"||!_n.test(o)))return{tag:t,sourceId:r,targetId:o,object:typeof s=="string"&&ei.test(s)?s:""}}function Be(n){if(!n.startsWith(`["${It}"`))return;let e;try{e=JSON.parse(n)}catch{return}if(!Array.isArray(e))return;let[,t,r]=e;if(!(typeof t!="string"||!ei.test(t)||!Array.isArray(r)))return{object:t,ids:r.filter(o=>typeof o=="string"&&_n.test(o))}}function st(n){return n.slice(0,15)}var it=class{offsets=new Float64Array(64);lengths=new Uint16Array(64);size=0;push(e,t){if(this.size===this.offsets.length){let r=new Float64Array(this.size*2);r.set(this.offsets),this.offsets=r;let o=new Uint16Array(this.size*2);o.set(this.lengths),this.lengths=o}this.offsets[this.size]=e,this.lengths[this.size]=t,this.size++}offsetAt(e){return this.offsets[e]}lengthAt(e){return this.lengths[e]}},Re=class{capacity=1024;used=0;h1=new Uint32Array(this.capacity);h2=new Uint32Array(this.capacity);taken=new Uint8Array(this.capacity);add(e){let t=se(e),r=ie(e);if(this.slotOf(t,r)>=0)return;this.used+1>this.capacity*.6&&this.grow();let o=this.freeSlotFor(r);this.h1[o]=t,this.h2[o]=r,this.taken[o]=1,this.used++}has(e){return this.slotOf(se(e),ie(e))>=0}get size(){return this.used}slotOf(e,t){let r=this.capacity-1;for(let o=t&r;;o=o+1&r){if(this.taken[o]===0)return-1;if(this.h1[o]===e&&this.h2[o]===t)return o}}freeSlotFor(e){let t=this.capacity-1,r=e&t;for(;this.taken[r]!==0;)r=r+1&t;return r}grow(){let{h1:e,h2:t,taken:r}=this;this.capacity*=2,this.h1=new Uint32Array(this.capacity),this.h2=new Uint32Array(this.capacity),this.taken=new Uint8Array(this.capacity);for(let o=0;o<r.length;o++){if(r[o]===0)continue;let s=this.freeSlotFor(t[o]);this.h1[s]=e[o],this.h2[s]=t[o],this.taken[s]=1}}},Cd=2e3,at=class n{constructor(e,t,r,o,s){this.file=e;this.all=t;this.mine=r;this.firstInPart=o;this.unattributed=s}file;all;mine;firstInPart;unattributed;static read(e,t){let r=(l,f)=>ot(e.read(l,f).toString("utf8"))?.sourceId??"",o=new jt(r),s=new jt(r),i=new it,a=new it,d=!1,c=-1;for(let l of we(e)){if(!d){if(!l.text.startsWith('{"run":'))return;d=!0;continue}if(l.text.startsWith('{"part":')){c++;continue}if(l.text.startsWith('{"object":'))return;if(c===t&&Be(l.text)){a.push(l.offset,l.length);continue}let f=ot(l.text);if(!f)continue;let p=se(f.sourceId),u=ie(f.sourceId);if(o.put(o.find(f.sourceId,p,u),p,u,l.offset,l.length,0),c!==t)continue;let m=s.find(f.sourceId,p,u);m<0&&i.push(l.offset,l.length);let g=f.tag==="c"&&f.object!=="";s.put(m,p,u,l.offset,l.length,g?1:0)}return d?new n(e,o,s,i,a):void 0}mappingAt(e,t){return ot(this.file.read(e,t).toString("utf8"))}wordsOn(e){let t=se(e),r=ie(e),o=this.all.find(e,t,r),s=this.mine.find(e,t,r);return{latest:o>=0?{offset:this.all.offsetOf(o),length:this.all.lengthOf(o)}:void 0,createdByThePart:s>=0&&this.mine.codeOf(s)===1,inThePart:s>=0?{offset:this.mine.offsetOf(s),length:this.mine.lengthOf(s)}:void 0}}createdByObject(){let e=new Map;for(let t=0;t<this.firstInPart.size;t++){let r=this.mappingAt(this.firstInPart.offsetAt(t),this.firstInPart.lengthAt(t));if(!r)continue;let o=this.wordsOn(r.sourceId);if(!o.createdByThePart||!o.latest||!o.inThePart)continue;let s=this.mappingAt(o.inThePart.offset,o.inThePart.length);if(!s)continue;let i=e.get(s.object)??new it;i.push(o.latest.offset,o.latest.length),e.set(s.object,i)}return e}runRecords(e,t=Cd){let{file:r}=this,o=(g,h)=>ot(r.read(g,h).toString("utf8")),s=(g,h)=>{let y=o(g,h);return y?st(y.targetId):""},i=new jt(s),a=this.createdByObject(),d=[];for(let g of[...a.keys()].reverse()){let h=a.get(g);if(!h)continue;let y=0;for(let R=h.size-1;R>=0;R--){let S=h.offsetAt(R),w=o(S,h.lengthAt(R));if(!w||w.object==="")continue;let b=st(w.targetId),A=se(b),E=ie(b),x=i.find(b,A,E);x>=0||(i.put(x,A,E,S,h.lengthAt(R),0),(!e||e.has(b))&&y++)}y>0&&d.push({objectApiName:g,count:y})}let c=(g,h)=>{let y=i.find(g,se(g),ie(g),h);return y>=0&&(h===void 0||i.offsetOf(y)===h)&&(!e||e.has(g))},l=g=>Be(r.read(this.unattributed.offsetAt(g),this.unattributed.lengthAt(g)).toString("utf8")),f=new Re,p=this.unattributed.size,u=new Map;for(let g=0;g<p;g++){let h=l(g);if(h)for(let y of h.ids){let R=st(y);f.has(R)||i.find(R,se(R),ie(R))>=0||(f.add(R),(!e||e.has(R))&&u.set(h.object,(u.get(h.object)??0)+1))}}for(let[g,h]of u){let y=d.find(R=>R.objectApiName===g);y?y.count+=h:d.unshift({objectApiName:g,count:h})}let m=g=>f.size>0&&f.has(g)&&(!e||e.has(g));return{objects:d,pages:async function*(g){let h=a.get(g),y=[];if(h)for(let R=h.size-1;R>=0;R--){let S=h.offsetAt(R),w=o(S,h.lengthAt(R));if(!w||w.object==="")continue;let b=st(w.targetId);c(b,S)&&(y.push(w.targetId),y.length>=t&&(yield y,y=[]))}if(u.has(g)){let R=new Re;for(let S=0;S<p;S++){let w=l(S);if(w?.object===g)for(let b of w.ids){let A=st(b);R.has(A)||!m(A)||i.find(A,se(A),ie(A))>=0||(R.add(A),y.push(b),y.length>=t&&(yield y,y=[]))}}}y.length>0&&(yield y)},has:g=>c(g)||m(g)}}*idMapRows(){let e=new Map;for(let[r,o]of this.createdByObject())for(let s=0;s<o.size;s++){let i=this.mappingAt(o.offsetAt(s),o.lengthAt(s));i&&e.set(i.sourceId.slice(0,3),r)}let t=new Uint8Array(Math.ceil(this.all.slots/8));for(let r of we(this.file)){let o=ot(r.text);if(!o)continue;let s=this.all.find(o.sourceId,se(o.sourceId),ie(o.sourceId));if(s<0||(t[s>>3]&1<<(s&7))!==0)continue;t[s>>3]|=1<<(s&7);let i=this.wordsOn(o.sourceId);if(!i.latest)continue;let a=this.mappingAt(i.latest.offset,i.latest.length);if(!a||a.object==="")continue;yield{objectApiName:(i.createdByThePart&&i.inThePart?this.mappingAt(i.inThePart.offset,i.inThePart.length):void 0)?.object??e.get(a.sourceId.slice(0,3)),sourceId:a.sourceId,targetId:a.targetId,outcome:i.createdByThePart?"created":"linked to existing"}}}};var Ie=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,dt=/^[A-Za-z][A-Za-z0-9_]*$/,xd=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/,Md=255,_d=40,Ld=2*6e4,Dd=10*6e4;function Wp(n){let[e]=n;return e?Object.keys(e).filter(t=>t!=="Id"&&dt.test(t)).filter(t=>n.every(r=>Bd(r[t]))).sort().slice(0,_d):[]}function Bd(n){return typeof n=="string"?n.trim()!==""&&n.length<=Md:typeof n=="number"?Number.isFinite(n):typeof n=="boolean"}function $d(n){if(typeof n=="boolean")return n?"true":"false";if(typeof n=="number")return Number.isFinite(n)?String(n):"";if(typeof n!="string")return"";let e=n.trim();if(Ie.test(e))return e.slice(0,15);if(xd.test(e)){let r=Date.parse(e);if(Number.isFinite(r))return new Date(r).toISOString()}if(e!==""&&Number.isFinite(Number(e)))return String(Number(e));let t=e.replace(/\s+/g," ").toLowerCase();return t.includes(";")?t.split(";").map(r=>r.trim()).sort().join(";"):t}function Dn(n,e){return Bn(e.map(t=>`${t}${$d(n[t])}`).join(""))}function Bn(n){return se(n).toString(36).padStart(7,"0")+ie(n).toString(36).padStart(7,"0")}function qp(n){let e=To("insert",n);return e.rows.map(t=>Bn(wn(e.columns.map((r,o)=>[r,t[o]??""]))))}var Wd=/^sf__/;function ti(n){let e=[];for(let[t,r]of Object.entries(n))Wd.test(t)||e.push([t,typeof r=="string"?r:r==null?"":String(r)]);return Bn(wn(e))}function ri(n,e){return Dn(n,[e])}function qd(n,e){if(!Array.isArray(n))return!1;for(let t of n){if(!Array.isArray(t)||t.length<4)return!1;let[r,o,s,i]=t;if(typeof r!="number"||!Number.isInteger(r)||!e[r]||typeof o!="string"||!dt.test(o)||typeof s!="string"||!Ie.test(s))return!1;e[r].owes.push({field:o,sourceRefId:s,...i===1?{insertOnly:!0}:{}})}return!0}function Ln(n){if(!n.startsWith(`["${kt}"`))return;let e;try{e=JSON.parse(n)}catch{return}if(!Array.isArray(e)||e.length<6)return;let[,t,r,o,s,i,a,d]=e;if(typeof t!="string"||typeof r!="string"||!dt.test(r)||typeof o!="string")return;let c=Date.parse(o);if(!Number.isFinite(c)||!Array.isArray(s)||!Array.isArray(i)||!s.every(p=>typeof p=="string"&&dt.test(p))||d!==void 0&&(typeof d!="string"||!dt.test(d)))return;let l=[];for(let p of i){if(!Array.isArray(p)||p.length<2)return;let[u,m,g,h]=p;if(typeof u!="string"||!Ie.test(u)||typeof m!="string"||g!==void 0&&typeof g!="string"||h!==void 0&&typeof h!="string")return;l.push({sourceId:u,fingerprint:m,owes:[],...typeof g=="string"&&g!==""?{externalKey:g}:{},...typeof h=="string"&&h!==""?{jobKey:h}:{}})}let f=a!==void 0;if(!(f&&!qd(a,l)))return{callId:t,objectApiName:r,at:c,fields:s,rows:l,owesKept:f,...typeof d=="string"?{upsertField:d}:{}}}function oi(n){if(n.startsWith(`["${Ee}"`))try{let e=JSON.parse(n);return Array.isArray(e)&&typeof e[1]=="string"?e[1]:void 0}catch{return}}function zd(n){if(n.startsWith(`["${Go}"`))try{let e=JSON.parse(n);return Array.isArray(e)&&typeof e[1]=="string"?e[1]:void 0}catch{return}}function Ud(n){if(n.startsWith(`["${Vo}"`))try{let e=JSON.parse(n);if(!Array.isArray(e))return;let[,t,r]=e;return typeof t!="string"||typeof r!="string"||r===""?void 0:{callId:t,jobId:r}}catch{return}}function Vd(n){if(!(!n.startsWith('["c"')&&!n.startsWith('["e"')&&!n.startsWith('["u"')))try{let e=JSON.parse(n);if(!Array.isArray(e))return;let[,t,r,o]=e;return typeof t!="string"||typeof r!="string"||!Ie.test(t)||!Ie.test(r)?void 0:{sourceId:t,targetId:r,object:typeof o=="string"?o:""}}catch{return}}function Gd(n){let e=/"(?:startedAt|at)":"([^"]{10,40})"/.exec(n);return e?Date.parse(e[1]):Number.NaN}function zp(n,e={}){return{queryPages:t=>So({query:async r=>n.query(r),queryMore:async r=>n.queryMore(r)},t),userId:async()=>(await n.identity()).user_id,serverTime:async()=>(await n.soap.getServerTimestamp()).timestamp,readJob:t=>Fo(Po(n),t,e.leaveOpen?{leaveOpen:!0}:{})}}function Jd(){return{calls:0,found:[],notFound:[],uncertain:[],unread:[]}}function K(n,e,t=1){if(t<=0)return;let r=n.find(o=>o.objectApiName===e);r?r.rows+=t:n.push({objectApiName:e,rows:t})}function ni(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function $n(n,e,t){return[JSON.stringify(["c",e.sourceId,t,n.objectApiName,n.owesKept?Yo:Ko]),...e.owes.map(({field:r,sourceRefId:o,insertOnly:s})=>Xo({objectApiName:n.objectApiName,newId:t,sourceId:e.sourceId,fieldName:r,sourceRefId:o,...s?{insertOnly:s}:{}}))]}function Hd(n,e,t,r){let{call:o,rows:s,read:i}=n,{objectApiName:a}=o,d=JSON.stringify([Ee,o.callId]);if(i.state==="never-closed")return K(r.notFound,a,s.length),{lines:[d],taken:[]};if(i.state==="running")return K(r.uncertain,a,s.length),(r.underway??=[]).push({objectApiName:a,jobId:n.jobId,rows:s.length,...i.info?{state:i.info.state}:{},...i.info?.numberRecordsProcessed!==void 0?{processed:i.info.numberRecordsProcessed}:{},...i.openUntil?{openUntil:i.openUntil}:{},...i.graceLeftMs!==void 0?{graceLeftMs:i.graceLeftMs}:{}}),{lines:[],taken:[]};if(i.state==="unread")return r.unread.push({objectApiName:a,reason:i.reason}),K(r.uncertain,a,s.length),{lines:[],taken:[]};let c=o.upsertField===void 0&&s.every(f=>f.jobKey!==void 0)?Kd(o,s,i.results,e,t,r):Yd(o,s,i.results,e,t,r),l=Date.parse(i.info.systemModstamp??"");return!n.endKept&&c.taken.length>0&&Number.isFinite(l)&&c.lines.unshift(Zo(o.callId,n.jobId,new Date(l).toISOString(),new Date(l-n.ahead).toISOString())),c}function Kd(n,e,t,r,o,s){let{objectApiName:i}=n,a=new Map,d=new Set;for(let S of t.successfulResults??[]){let w=S.sf__Id,b=ti(S);if(typeof w!="string"||!Ie.test(w)){d.add(b);continue}let A=w.slice(0,15);r.has(A)&&!o.has(A)||a.set(b,[...a.get(b)??[],w])}let c=new Set,l=t.unprocessedRecords;for(let S of[...t.failedResults??[],...Array.isArray(l)?l:[]])c.add(ti(S));let f=new Map;for(let S of e){let w=S.jobKey??"";f.set(w,[...f.get(w)??[],S])}let p=[],u=[],m=[],g=0,h=!1,y=0;for(let[S,w]of f){let b=a.get(S)??[];a.delete(S);let A=d.delete(S);if(w.length===1&&b.length===1&&!A){p.push(...$n(n,w[0],b[0])),u.push(b[0]),K(s.found,i);continue}if(b.length>0||A){K(s.uncertain,i,w.length),w.length>1&&K(s.untold??=[],i,w.length),A||(y+=w.length),m.push(...b),h=!0;continue}if(w.length>1||c.has(S)){K(s.notFound,i,w.length);continue}g+=w.length}let R=d.size>0;for(let S of a.values())m.push(...S),S.length>0&&(R=!0);return g>0&&(K(R?s.uncertain:s.notFound,i,g),R&&(h=!0,d.size===0&&(y+=g))),y>0&&K(s.ofEndedJobs??=[],i,y),p.push(...si(n,m,o,h,s)),{lines:p,taken:[...u,...m]}}function si(n,e,t,r,o){e.length>0&&K(o.unattributed??=[],n.objectApiName,e.length);let s=e.filter(i=>!t.has(i.slice(0,15)));return[...s.length>0?[JSON.stringify([It,n.objectApiName,s])]:[],...r?[]:[JSON.stringify([Ee,n.callId])]]}function Yd(n,e,t,r,o,s){let{objectApiName:i}=n,a=n.upsertField,d=new Map;for(let h of t.successfulResults??[]){let y=h.sf__Id;if(typeof y!="string"||!Ie.test(y))continue;let R=y.slice(0,15);if(r.has(R)&&!o.has(R)||a!==void 0&&String(h.sf__Created).toLowerCase()!=="true")continue;let S=a!==void 0?ri(h,a):Dn(h,n.fields);d.set(S,[...d.get(S)??[],y])}let c=new Map;for(let h of e){let y=a!==void 0?h.externalKey??"":h.fingerprint;c.set(y,[...c.get(y)??[],h])}let l=[],f=[],p=[],u=0,m=!1;for(let[h,y]of c){let R=h===""?[]:d.get(h)??[];if(d.delete(h),R.length===0){u+=y.length;continue}if(y.length===1&&R.length===1){l.push(...$n(n,y[0],R[0])),f.push(R[0]),K(s.found,i);continue}K(s.uncertain,i,y.length),K(s.ofEndedJobs??=[],i,y.length),y.length>1&&K(s.untold??=[],i,y.length),p.push(...R),m=!0}let g=!1;for(let h of d.values())p.push(...h),h.length>0&&(g=!0);return u>0&&(K(g?s.uncertain:s.notFound,i,u),g&&(m=!0,K(s.ofEndedJobs??=[],i,u))),l.push(...si(n,p,o,m,s)),{lines:l,taken:[...f,...p]}}function ii(n){let e=new Set;for(let t of we(n)){let r=oi(t.text);if(r!==void 0)e.delete(r);else{let o=t.text.startsWith(`["${kt}"`)?Ln(t.text):void 0;o&&e.add(o.callId)}}return e.size}async function ai(n,e,t=()=>new Date,r={}){let o=Jd(),s=new Map,i=new Map,a=new Set,d=Number.NEGATIVE_INFINITY;for(let b of we(n)){let A=oi(b.text);if(A!==void 0){s.delete(A);continue}let E=Ud(b.text);if(E){i.set(E.callId,E.jobId);continue}let x=zd(b.text);if(x!==void 0){a.add(x);continue}if(b.text.startsWith(`["${kt}"`)){let T=Ln(b.text);T&&(s.set(T.callId,{offset:b.offset,length:b.length}),d=Math.max(d,T.at));continue}if(b.text.startsWith("{")){let T=Gd(b.text);Number.isFinite(T)&&(d=Math.max(d,T))}}if(s.size===0)return o;let c=[];for(let{offset:b,length:A}of s.values()){let E=Ln(n.read(b,A).toString("utf8"));E&&c.push(E)}o.calls=c.length;let l=new Set(c.map(b=>b.objectApiName)),f=new Set(c.flatMap(b=>b.rows.map(A=>A.sourceId)));o.lookedFor=f;let p=new Set,u=new Re,m=new Re;for(let b of we(n)){let A=Be(b.text);if(A){if(l.has(A.object))for(let x of A.ids)u.add(x.slice(0,15)),m.add(x.slice(0,15));continue}let E=Vd(b.text);E&&(f.has(E.sourceId)&&p.add(E.sourceId),(E.object===""||l.has(E.object))&&u.add(E.targetId.slice(0,15)))}let g=0;if(e.serverTime)try{let b=t().getTime(),A=Date.parse(await e.serverTime());Number.isFinite(A)&&(g=A-(b+t().getTime())/2)}catch{}let h,y,R=[],S=e.readJob?.bind(e),w=new Set;if(S)for(let b of c){let A=i.get(b.callId);if(A===void 0)continue;w.add(b.callId);let E=b.rows.filter(T=>!p.has(T.sourceId));if(E.length===0){R.push(JSON.stringify([Ee,b.callId]));continue}let x=Hd({call:b,rows:E,jobId:A,read:await S(A),ahead:g,endKept:a.has(b.callId)},u,m,o);R.push(...x.lines);for(let T of x.taken)u.add(T.slice(0,15))}for(let b of l){let A=c.filter(O=>O.objectApiName===b&&!w.has(O.callId));if(A.length===0)continue;let E=A.map(O=>({call:O,rows:O.rows.filter(C=>!p.has(C.sourceId))})),x=E.reduce((O,{rows:C})=>O+C.length,0);if(x===0){for(let{call:O}of E)R.push(JSON.stringify([Ee,O.callId]));continue}let T=new Map;for(let O of A)T.set(O.fields.join(","),O.fields);let v=[...new Set(A.flatMap(O=>O.upsertField?[O.upsertField]:[]))],I=[...new Set([...A.flatMap(O=>O.fields),...v])].sort(),N;try{if(h===void 0&&y===void 0)try{h=await e.userId()}catch(M){y=H(M)}if(h===void 0)throw new Error(`the user the run writes as is not known: ${y}`);let O=Math.min(...A.map(M=>M.at))+g-Ld,C=d+g+Dd,B=I.includes("CreatedDate")?"SystemModstamp":"CreatedDate",P=I.includes("CreatedById")?"":`CreatedById = '${h}' AND `,L=`SELECT ${["Id",...I.filter(M=>M!=="Id")].join(", ")} FROM ${J(b)} WHERE ${P}${B} >= ${ni(O)} AND ${B} <= ${ni(C)} ORDER BY Id`;N=[];for await(let M of e.queryPages(L))for(let $ of M){let q=$.Id;if(typeof q!="string"||!Ie.test(q)||u.has(q.slice(0,15)))continue;let Q=new Map;for(let[je,he]of T)Q.set(je,Dn($,he));let Se=new Map;for(let je of v)Se.set(je,ri($,je));N.push({id:q,fingerprints:Q,externalKeys:Se,taken:!1})}}catch(O){o.unread.push({objectApiName:b,reason:H(O)}),K(o.uncertain,b,x);continue}N.sort((O,C)=>O.id<C.id?-1:O.id>C.id?1:0);let _=new Map;for(let O of T.keys()){let C=new Map;for(let B of N){let P=B.fingerprints.get(O)??"",L=C.get(P)??[];L.push(B),C.set(P,L)}_.set(O,C)}let D=(O,C,B)=>{B.taken=!0,R.push(...$n(O,C,B.id)),K(o.found,b)},j=new Set;for(let{call:O,rows:C}of E){let B=O.upsertField;if(B===void 0)continue;let P=new Map;for(let M of N){let $=M.externalKeys.get(B);M.taken||$===void 0||P.set($,[...P.get($)??[],M])}let L=new Map;for(let M of C){let $=M.externalKey??"";L.set($,[...L.get($)??[],M])}for(let[M,$]of L){let q=M===""?[]:P.get(M)??[];if(M===""||$.length>1||q.length>1){K(o.uncertain,b,$.length),j.add(O.callId);continue}q.length===1?D(O,$[0],q[0]):K(o.notFound,b)}}let F=[];for(let{call:O,rows:C}of E){if(O.upsertField!==void 0)continue;let B=O.fields.join(","),P=new Map;for(let L of C){let M=P.get(L.fingerprint)??[];M.push(L),P.set(L.fingerprint,M)}for(let[L,M]of P){let $=(_.get(B)?.get(L)??[]).filter(q=>!q.taken);if($.length>M.length){for(let q of M)F.push({callId:O.callId,sourceId:q.sourceId});j.add(O.callId);continue}$.forEach((q,Q)=>D(O,M[Q],q));for(let q of M.slice($.length))F.push({callId:O.callId,sourceId:q.sourceId})}}let k=N.some(O=>!O.taken);for(let O of F)k||j.has(O.callId)?(K(o.uncertain,b),j.add(O.callId)):K(o.notFound,b);for(let{call:O}of E)j.has(O.callId)||R.push(JSON.stringify([Ee,O.callId]))}return R.length>0&&r.keep!==!1&&n.append(`${R.join(`
|
|
13
|
+
`)}
|
|
14
|
+
`),o}function Up(n,e,t="resume"){if(n.calls===0)return[];let r=i=>i.map(({objectApiName:a,rows:d})=>`${d} ${a}`).join(", "),o={resume:"kept as written by the run and not written again",removal:"kept as written by the run and removed with its records",preview:"which a removal keeps as written by the run and removes with its records, not counted here"}[t],s=[`${n.calls} insert or upsert call(s) were under way when the run stopped, their answer never kept: their rows were looked for in ${e}`+(t==="preview"?", as a removal looks for them first":"")];n.found.length>0&&s.push(` found in ${e}, ${o}: ${r(n.found)}`),n.notFound.length>0&&s.push(t==="resume"?` not in ${e}, written by the resume: ${r(n.notFound)}`:` not in ${e}, nothing of them to remove: ${r(n.notFound)}`),n.uncertain.length>0&&s.push(` may already be in ${e}: ${r(n.uncertain)}`);for(let i of n.underway??[])s.push(` ${Qd(i,t==="resume"?"resume":"removal")}`);for(let{objectApiName:i,rows:a}of n.untold??[])s.push(` ${i}: ${a} row(s) the journal cannot tell apart, several under one fingerprint, under which the Bulk API job wrote records: none of those records is linked to a row`);(n.unattributed??[]).length>0&&s.push(` written by a Bulk API job and matched to no row, ${t==="resume"?"kept as written by the run":o}: `+r(n.unattributed??[]));for(let{objectApiName:i,reason:a}of n.unread)s.push(` ${i} could not be read in ${e}: ${a}`);return s}function Zd(n){return Math.max(1,Math.ceil(n/6e4))}function Qd(n,e){let t=`${n.objectApiName}: Bulk API job ${n.jobId} is ${n.state??"not ended"}`+(n.processed!==void 0?`, ${n.processed} row(s) processed`:"");if(n.state==="Open"){let r=n.openUntil!==void 0?` from ${n.openUntil}`+(n.graceLeftMs!==void 0&&n.graceLeftMs>0?`, in about ${Zd(n.graceLeftMs)} minute(s),`:""):" an hour after it was opened";return`${t}: the run stopped before it closed it, and closed, it would still write them; ${e==="resume"?"a resume":"a removal"}${r} aborts it if it is open still`+(e==="resume"?", then writes its rows":"")}return`${t}: the org writes it to its end whatever became of the run; `+(e==="resume"?"a resume once it has ended reads what it wrote":"a removal once it has ended takes what it wrote")}function Xd(n){return n.uncertain.reduce((e,{rows:t})=>e+t,0)}function Vp(n){let e=(n.ofEndedJobs??[]).reduce((t,{rows:r})=>t+r,0);return Math.max(0,Xd(n)-e)}import{createReadStream as ec}from"node:fs";import{appendFile as tc,chmod as nc,mkdir as rc,readdir as oc,rename as sc,rm as di}from"node:fs/promises";import*as de from"node:path";import{createInterface as ic}from"node:readline";var ac=10*6e4,ci=448;function nm(n){return new Un({storagePath:n,appendFile:(e,t)=>tc(e,t,{encoding:"utf8",mode:qo}),readLines:e=>dc(e),mkdir:async e=>{await rc(e,{recursive:!0,mode:ci}),process.platform!=="win32"&&await nc(e,ci).catch(t=>{if(t.code!=="EPERM")throw t})},rm:e=>di(e,{force:!0}),rename:(e,t)=>sc(e,t),listFiles:e=>oc(e).catch(t=>{if(t.code==="ENOENT")return[];throw t}),openRunFile:e=>zo(e),rmDir:e=>di(e,{recursive:!0,force:!0})})}async function*dc(n){let e=ec(n,{encoding:"utf8"}),t=ic({input:e,crlfDelay:1/0});try{for await(let r of t)yield r}catch(r){if(r.code!=="ENOENT")throw r}finally{t.close(),e.destroy()}}var rm=5e4,om=2e3,ee=W().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),ct=W().regex(/^[A-Za-z][A-Za-z0-9_]*$/),cc=V({sourceOrgId:W().min(1).max(128),fingerprint:W().regex(/^[a-f0-9]{64}$/),targetSalesforceOrgId:ee.optional(),recordId:ee.optional(),muteAutomation:Ye(!0).optional(),files:_r.optional()}),uc=V({graph:xr,config:Cr,anonymizationRules:Mr.optional()});function ui(n){let e=cc.safeParse(n);if(!e.success)return;let t=uc.safeParse(n.startedWith);return{...e.data,...t.success?{startedWith:t.data}:{}}}var _t=V({run:V({journalId:W().min(1).max(200),targetOrgId:W().min(1).max(128),startedAt:W().min(1).max(40),resume:Ne().optional(),runUserId:Ne().optional()})}),li=V({objectApiName:W().regex(/^[A-Za-z][A-Za-z0-9_]*$/),reason:W().max(2e3),...Lr}),fi=V({checkpoint:V({state:Ye("taken"),checkpointId:W().min(1).max(200),name:W().max(500),takenAt:W().min(1).max(40),expiresAt:W().min(1).max(40).nullable(),objects:Z(W().regex(/^[A-Za-z][A-Za-z0-9_]*$/)),records:te().nonnegative(),bytes:te().nonnegative(),requests:te().nonnegative(),added:Z(li),notHeld:Z(li)})}),lc=V({part:V({n:te().int().nonnegative(),startedAt:W().max(40).optional()})}),Wn=V({end:V({status:ve(["success","cancelled","failure","interrupted"]),forgeId:W().min(1).max(200),at:W().max(40).optional()})}),fc=V({object:ct,created:Z(Fr([ee,ee]))});function qn(n){return ee.safeParse(n).success?n:void 0}function $e(n){return n.replace(/\.ndjson$/,"")+".end.json"}function Lt(n){return n.replace(/\.ndjson$/,"")+".checkpoint.json"}function Dt(n,e){return`${n.replace(/\.ndjson$/,"")}.part${e}.left`}function pi(n,e){return`${n.replace(/\.ndjson$/,"")}.part${e}.stamps`}var pc=W().max(40).refine(n=>Number.isFinite(Date.parse(n)),"not a date"),We=1e4;function mc(n,e){let t=n.map(s=>({...s,ids:[...s.ids]}));if(!e||e.length===0)return t;let r=new Set(n.flatMap(({ids:s})=>s.map(i=>i.slice(0,15)))),o=[];for(let{objectApiName:s,ids:i}of e){let a=i.filter(c=>!r.has(c.slice(0,15)));for(let c of a)r.add(c.slice(0,15));if(a.length===0)continue;let d=t.find(c=>c.objectApiName===s);d?d.ids.push(...a):o.push({objectApiName:s,ids:a})}return[...o,...t]}function zn(n){return n.replace(/[^A-Za-z0-9_-]/g,"_")}var Un=class{constructor(e){this.deps=e;this.dir=de.join(e.storagePath,"forge-runs")}deps;dir;get storagePath(){return this.deps.storagePath}pathOf(e){return de.join(this.dir,`${zn(e)}.ndjson`)}filePath(e){return this.pathOf(e)}async begin(e,t,r,o,s){await this.deps.mkdir(this.dir);let i=qn(s),a={run:{journalId:e,targetOrgId:t,startedAt:r.toISOString(),...o?{resume:o}:{},...i?{runUserId:i}:{}}};await this.deps.appendFile(this.filePath(e),`${JSON.stringify(a)}
|
|
15
|
+
`)}async keepCheckpoint(e,t){let r=fi.safeParse({checkpoint:t});if(!r.success)return;let o=Lt(this.filePath(e));await this.deps.rm(o),await this.deps.appendFile(o,`${JSON.stringify(r.data)}
|
|
16
|
+
`)}async checkpointAt(e){for await(let t of this.deps.readLines(Lt(e)))if(t.trim()!=="")try{let r=fi.safeParse(JSON.parse(t));return r.success?r.data.checkpoint:void 0}catch{return}}open(e){return this.openAt(this.filePath(e))}openAt(e){return es.open(this.deps.openRunFile(e))}reconcile(e,t){return this.reconcileAt(this.filePath(e),t)}async reconcileAt(e,t,r={}){let o=this.deps.openRunFile(e);try{return await ai(o,t,void 0,r)}finally{o.close()}}writeBoundsAt(e,t){let r=this.deps.openRunFile(e);try{let o,s,i,a,d=-1,c,l,f=Number.NEGATIVE_INFINITY,p=Number.NEGATIVE_INFINITY,u=Number.NEGATIVE_INFINITY,m=new Map;for(let h of we(r)){let y=/"(?:startedAt|at)":"([^"]{10,40})"/.exec(h.text)?.[1],R=h.text.startsWith('["x"')?/^\["x","[^"]*","[^"]*","([^"]+)"/.exec(h.text)?.[1]:void 0,S=Qo(h.text);for(let T of[y,R,S?.at]){let v=T===void 0?Number.NaN:Date.parse(T);Number.isFinite(v)&&(f=Math.max(f,v))}if(S){let T=Date.parse(S.orgAt);Number.isFinite(T)&&(p=Math.max(p,T),d===t&&(u=Math.max(u,T)));continue}if(h.text.startsWith('{"part":')&&d++,!h.text.startsWith('["c"')&&!h.text.startsWith('["p"')&&!h.text.startsWith('["g"'))continue;let w;try{w=JSON.parse(h.text)}catch{continue}if(!Array.isArray(w))continue;let[b,A,E,x]=w;if(b==="c"){if(!ee.safeParse(E).success||!ct.safeParse(x).success)continue;let T={objectApiName:String(x),id:String(E)};o??=T,s=T,d===t&&(i??=T,a=T),m.set(String(E).slice(0,3),String(x))}else if(b==="g"){if(!ee.safeParse(E).success||!ct.safeParse(A).success)continue;c={objectApiName:String(A),id:String(E)},l=void 0}else ee.safeParse(A).success&&(l=String(A))}let g=l?m.get(l.slice(0,3)):void 0;return l&&g&&(c={objectApiName:g,id:l}),{...o?{first:o}:{},...s?{lastCreated:s}:{},...i?{firstInPart:i}:{},...a?{lastCreatedInPart:a}:{},...c?{lastUpdated:c}:{},...Number.isFinite(f)?{lastAt:new Date(f).toISOString()}:{},...Number.isFinite(p)?{jobEnded:new Date(p).toISOString()}:{},...Number.isFinite(u)?{jobEndedInPart:new Date(u).toISOString()}:{}}}finally{r.close()}}writtenBetween(e,t,r,o="run"){return this.writtenBetweenAt(this.filePath(e),t,r,o)}async writtenBetweenAt(e,t,r,o="run"){let s=this.writeBoundsAt(e,r),{firstInPart:i,lastCreatedInPart:a,lastAt:d}=s,[c,l,f]=o==="part"?[i,a,void 0]:[s.first,s.lastCreated,s.lastUpdated];if(!c||!l)return;let p=async({objectApiName:S,id:w},b)=>{try{let E=(await t.query(`SELECT ${b} FROM ${J(S)} WHERE Id = '${w}'`)).records[0]?.[b],x=typeof E=="string"?Date.parse(E):Number.NaN;return Number.isFinite(x)?x:void 0}catch{return}},u=d===void 0?Number.NaN:Date.parse(d)+ac,m=await p(c,"CreatedDate")??(i&&i.id!==c.id?await p(i,"CreatedDate"):void 0),g=[],h=a?.id!==l.id?a:void 0;for(let S of[l,h]){let w=S?await p(S,"CreatedDate"):void 0;if(S&&w!==void 0&&m!==void 0&&w<m){let b=await p(S,"SystemModstamp");w=b!==void 0&&b>=m&&(!Number.isFinite(u)||b<=u)?b:void 0}w!==void 0&&g.push(w)}let y=g.length>0?Math.max(...g):void 0;if(m===void 0||y===void 0||y<m)return;if(f){let S=await p(f,"LastModifiedDate");S!==void 0&&S>y&&(!Number.isFinite(u)||S<=u)&&(y=S)}let R=Date.parse((o==="part"?s.jobEndedInPart:s.jobEnded)??"");return Number.isFinite(R)&&R>y&&(y=R),{first:new Date(m).toISOString(),last:new Date(y).toISOString()}}callsInFlight(e){return this.callsInFlightAt(this.filePath(e))}callsInFlightAt(e){let t=this.deps.openRunFile(e);try{return ii(t)}finally{t.close()}}stop(e,t,r){return this.stopAt(this.filePath(e),t,r)}async stopAt(e,t,r){let o=`${JSON.stringify({end:{status:t,forgeId:r,at:new Date().toISOString()}})}
|
|
17
|
+
`;await this.deps.appendFile(e,o),await this.deps.rm($e(e)),await this.deps.appendFile($e(e),o)}resuming(e){return this.resumingAt(this.filePath(e))}resumingAt(e){return this.deps.rm($e(e))}lastEnd(e){return this.lastEndAt(this.filePath(e))}async lastEndAt(e){for await(let t of this.deps.readLines($e(e)))if(t.trim()!=="")try{let r=Wn.safeParse(JSON.parse(t));return r.success?r.data.end:void 0}catch{return}}async partsOf(e){let t=new Set,r;for await(let o of this.deps.readLines(this.filePath(e)))if(o.trim()!==""){if(!r){try{let s=_t.safeParse(JSON.parse(o));if(!s.success||s.data.run.journalId!==e)return[];r=s.data.run}catch{return[]}continue}if(o.startsWith('{"end":'))try{let s=Wn.safeParse(JSON.parse(o));s.success&&t.add(s.data.end.forgeId)}catch{}}return[...t]}async wroteIn(e,t){let r=new Set,o=!1,s=-1;for await(let i of this.deps.readLines(this.filePath(e)))if(i.trim()!==""){if(!o){try{let a=_t.safeParse(JSON.parse(i));if(!a.success||a.data.run.journalId!==e)return[]}catch{return[]}o=!0;continue}if(i.startsWith('{"part":')){if(s++,s>t)break;continue}if(!(s!==t||!(i.startsWith('["p"')||i.startsWith('["g"'))))try{let a=JSON.parse(i);if(!Array.isArray(a))continue;let d=a[0]==="p"?a[1]:a[2];ee.safeParse(d).success&&r.add(String(d))}catch{}}return[...r]}async end(e){let t=this.filePath(e);await this.deps.rm(t),await this.deps.rm($e(t)),await this.deps.rm(Lt(t));let r=`${de.basename(t).replace(/\.ndjson$/,"")}.part`;for(let o of await this.deps.listFiles(this.dir))o.startsWith(r)&&(o.endsWith(".left")||o.endsWith(".stamps"))&&await this.deps.rm(de.join(this.dir,o));await this.deps.rmDir?.(Ts(this.deps.storagePath,e))}fileNameOf(e){return`${zn(e)}.ndjson`}async present(e){let t=new Set(await this.deps.listFiles(this.dir));return new Set(e.filter(r=>t.has(this.fileNameOf(r))))}async endedFiles(){let e=await this.deps.listFiles(this.dir),t=new Set(e.filter(r=>r.endsWith(".end.json")));return e.filter(r=>r.endsWith(".ndjson")&&t.has(r.replace(/\.ndjson$/,".end.json")))}async forgetFile(e){let t=de.join(this.dir,e),r=await this.headAt(t);r?await this.end(r.journalId):(await this.deps.rm(t),await this.deps.rm($e(t)),await this.deps.rm(Lt(t)))}async idsOf(e,t){let r=this.filePath(e),o=await this.readAt(r,"all");if(o?.journalId!==e)return;let s=await this.readAt(r,t);if(!s)return;let i=new Set(s.remap.createdByObject.flatMap(({sourceIds:a})=>a));return{table:o.remap.table,createdByObject:s.remap.createdByObject,existing:Object.keys(o.remap.table).filter(a=>!i.has(a)),...s.remap.withTheirRecord?{withTheirRecord:s.remap.withTheirRecord}:{}}}async keepLeft(e,t,r){let o=Dt(this.filePath(e),t);await this.deps.rm(o);for(let s=0;s<r.length;s+=We)await this.deps.appendFile(o,`${r.slice(s,s+We).join(`
|
|
18
|
+
`)}
|
|
19
|
+
`);r.length===0&&await this.deps.appendFile(o,"")}async recordsOf(e,t,r=!1){if(!await this.head(e))return;let o=r?void 0:await this.leftKeysOf(e,t),s=this.deps.openRunFile(this.filePath(e)),i=at.read(s,t);if(!i){s.close();return}return{records:i.runRecords(o),close:()=>s.close()}}async idMapRowsOf(e,t){if(!await this.head(e))return;let r=this.deps.openRunFile(this.filePath(e)),o=at.read(r,t);if(!o){r.close();return}return{rows:o.idMapRows(),close:()=>r.close()}}async leftKeysOf(e,t){let r=Dt(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(de.basename(r)))return;let s=new Re;for await(let i of this.deps.readLines(r)){let a=i.trim();ee.safeParse(a).success&&s.add(a.slice(0,15))}return s}async keepLeftPages(e,t,r){let o=Dt(this.filePath(e),t),s=this.deps.rename,i=s?`${o}.next`:o;await this.deps.rm(i),await this.deps.appendFile(i,"");let a=new Map;for await(let{objectApiName:d,ids:c}of r)if(c.length!==0){a.set(d,(a.get(d)??0)+c.length);for(let l=0;l<c.length;l+=We)await this.deps.appendFile(i,`${c.slice(l,l+We).join(`
|
|
20
|
+
`)}
|
|
21
|
+
`)}return s&&await s(i,o),[...a].map(([d,c])=>({objectApiName:d,count:c}))}async stampsOf(e,t){let r=pi(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(de.basename(r)))return{};let s={};for await(let i of this.deps.readLines(r)){let[a,d]=i.trim().split(" ");ee.safeParse(a).success&&pc.safeParse(d).success&&(s[a]=d)}return s}async keepStamps(e,t,r){if(Object.keys(r).length===0)return;let o=pi(this.filePath(e),t),s=Object.entries({...await this.stampsOf(e,t),...r}),i=this.deps.rename,a=i?`${o}.next`:o;await this.deps.rm(a);for(let d=0;d<s.length;d+=We){let c=s.slice(d,d+We).map(([l,f])=>`${l} ${f}`);await this.deps.appendFile(a,`${c.join(`
|
|
22
|
+
`)}
|
|
23
|
+
`)}i&&await i(a,o)}async leftOf(e,t){let r=Dt(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(de.basename(r)))return;let s=[];for await(let i of this.deps.readLines(r)){let a=i.trim();ee.safeParse(a).success&&s.push(a)}return s}async head(e){let t=await this.headAt(this.filePath(e));return t?.journalId===e?t:void 0}async headAt(e){for await(let t of this.deps.readLines(e)){if(t.trim()==="")continue;let r;try{r=JSON.parse(t)}catch{return}let o=_t.safeParse(r);if(!o.success)return;let{resume:s,runUserId:i,...a}=o.data.run,d=ui(s),c=qn(i);return{...a,...d?{resume:d}:{},...c?{runUserId:c}:{}}}}async read(e){let t=await this.deps.listFiles(this.dir),r=`${zn(e)}.ndjson`;if(!t.includes(r))return;let o=await this.readAt(de.join(this.dir,r));return o?.journalId===e?o:void 0}readAt(e,t="last"){return this.readFile(e,t)}async leftOver(e=new Set){let t=[],r=await this.deps.listFiles(this.dir),o=new Set(r.filter(s=>s.endsWith(".end.json")));for(let s of r){if(!s.endsWith(".ndjson")||o.has(s.replace(/\.ndjson$/,".end.json")))continue;let i=await this.readFile(de.join(this.dir,s),"last");!i||e.has(i.journalId)||i.lastEnd||t.push(i)}return t}static planOf(e,t=e.journalId){let r=mc(e.created,e.unattributed);if(r.length!==0)return{forgeId:t,targetOrgId:e.targetOrgId,timestamp:e.startedAt,duration:0,status:"partial",objects:r,linked:0}}forget(e){return this.end(e)}async readFile(e,t){let r,o=0,s,i,a,d=new Map,c=new Map,l=new Set,f=new Map,p,u=()=>{o++,i=s,s=void 0,t==="last"&&(d=new Map,c=new Map,l=new Set,f=new Map)},m=()=>typeof t!="number"||o-1===t;for await(let x of this.deps.readLines(e)){if(x.trim()==="")continue;let T;try{T=JSON.parse(x)}catch{continue}if(!r){let _=_t.safeParse(T);if(!_.success)return;r=_.data.run;continue}if(Array.isArray(T)){let _=Be(x);if(_){if(!m())continue;let O=c.get(_.object)??new Set;for(let C of _.ids)O.add(C);c.set(_.object,O);continue}let[D,j,F,k]=T;if(D===Jo){m()&&ee.safeParse(j).success&&l.add(String(j));continue}if(D===Ho){let[,O,C]=T;m()&&typeof O=="string"&&ct.safeParse(O).success&&typeof C=="number"&&Number.isSafeInteger(C)&&C>0&&f.set(O,(f.get(O)??0)+C);continue}if(D!=="c"&&D!=="e"&&D!=="u"||!m()||!ee.safeParse(j).success||!ee.safeParse(F).success)continue;d.set(String(j),{targetId:String(F),object:typeof k=="string"&&ct.safeParse(k).success?k:"",created:D==="c"});continue}if(typeof T=="object"&&T!==null&&"roots"in T){p=Uo(T.roots)??p;continue}let v=lc.safeParse(T);if(v.success){u(),a=v.data.part.startedAt;continue}let I=Wn.safeParse(T);if(I.success){s=I.data.end;continue}let N=fc.safeParse(T);if(N.success){if(o===0&&u(),!m())continue;for(let[_,D]of N.data.created)d.set(_,{targetId:D,object:N.data.object,created:!0})}}if(!r)return;let g=ui(r.resume),h=qn(r.runUserId),y=await this.checkpointAt(e),R={},S=new Map,w=[];for(let[x,{targetId:T,object:v,created:I}]of d){if(!v)continue;if(R[x]=T,!I){w.push(x);continue}let N=S.get(v)??[];N.push(x),S.set(v,N)}let b=[...S].map(([x,T])=>({objectApiName:x,sourceIds:T})),A=new Set([...d.values()].filter(({created:x})=>x).map(({targetId:x})=>x.slice(0,15))),E=[...c].map(([x,T])=>({objectApiName:x,ids:[...T].filter(v=>!A.has(v.slice(0,15)))})).filter(({ids:x})=>x.length>0);return{journalId:r.journalId,targetOrgId:r.targetOrgId,startedAt:r.startedAt,...g?{resume:g}:{},...h?{runUserId:h}:{},...y?{checkpoint:y}:{},...p?{roots:p}:{},parts:o,partStartedAt:a??r.startedAt,...s?{lastEnd:s}:{},...i?{endBefore:i}:{},created:Wr({idRemapTable:R,idRemapExisting:w,idRemapCreated:b}),remap:{table:R,createdByObject:b,linked:w,...w.some(x=>l.has(x))?{withTheirRecord:w.filter(x=>l.has(x))}:{}},...E.length>0?{unattributed:E}:{},...f.size>0?{writtenByThePlatform:[...f].map(([x,T])=>({objectApiName:x,rows:T}))}:{}}}};import{randomBytes as gc}from"node:crypto";import{chmod as hc,open as wc,readFile as yc,readdir as bc,rename as Rc,rm as mi,stat as Sc}from"node:fs/promises";import{dirname as Oc,join as Jn}from"node:path";var Ac=1440*6e4,kc="forge-roots",Ic=/^[A-Za-z0-9_-]{1,128}$/,ze=class extends Error{constructor(t,r){super(r);this.fault=t;this.name="RootPlanError"}fault},Vn=class extends Error{constructor(t,r,o){let s=r.length>3?`${r.slice(0,3).join(", ")} and ${r.length-3} more`:r.join(", ");super(`${s}: ${o instanceof Error?o.message:String(o)}`);this.removed=t;this.left=r;this.name="RootPlanSweepError"}removed;left},jc=sn({where:W().min(1).max(512).optional(),orderBy:W().min(1).max(200).optional(),limit:te().int().min(1).max(cn).optional()}),gi=sn({version:Ye(1),sourceOrgId:W().min(1).max(128),fingerprint:W().max(128),objectApiName:W().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),query:jc.optional(),from:ve(["query","records"]),readAt:W().refine(n=>Number.isFinite(Date.parse(n)),"not a date"),ids:Z(W().refine(as,"not a record id")).max(cn),sha256:W().regex(/^[0-9a-f]{64}$/)});function hi(n){return Jn(n,kc)}function fm(n,e){if(!Ic.test(e))throw new ze("gone","Not the fingerprint of a setup of a run.");return Jn(hi(n),`${e}.json`)}function Gn(n){let e=n?.code;return e==="ENOENT"||e==="ENOTDIR"}async function pm(n,e){let t=is(e.ids),r={version:1,sourceOrgId:e.sourceOrgId,fingerprint:e.fingerprint,objectApiName:e.objectApiName,...e.query!==void 0?{query:{...e.query}}:{},from:e.from,readAt:e.readAt,ids:t,sha256:An(t)},o=gi.parse(r);await ts(Oc(n));let s=`${n}.${process.pid}-${gc(4).toString("hex")}.tmp`;try{let i=await wc(s,"wx",Rn);try{await i.writeFile(`${JSON.stringify(o)}
|
|
24
|
+
`,"utf8")}finally{await i.close()}await hc(s,Rn),await Rc(s,n)}catch(i){throw await mi(s,{force:!0}),i}return o}async function Nc(n){let e;try{e=await yc(n,"utf8")}catch(r){throw Gn(r)?new ze("gone",`No plan of roots is at ${n}.`):r}let t;try{t=gi.parse(JSON.parse(e))}catch{throw new ze("changed",`The plan of roots at ${n} no longer reads as one.`)}if(An(t.ids)!==t.sha256)throw new ze("changed",`The ids of the plan of roots at ${n} are no longer those it was kept with.`);return t}function mm(n,e){return e.getTime()-Date.parse(n.readAt)}async function gm(n,e,t){let r=hi(n),o;try{o=await bc(r)}catch(d){if(Gn(d))return 0;throw d}let s=0,i=[],a;for(let d of o){let c=Jn(r,d);try{let l,f;try{let p=await Nc(c);l=Date.parse(p.readAt),f={roots:p.ids.length,readAt:p.readAt}}catch{l=(await Sc(c)).mtimeMs}if(e.getTime()-l<Ac)continue;await mi(c,{force:!0}),s++,f&&d.endsWith(".json")&&t?.(d.slice(0,-5),f)}catch(l){if(Gn(l))continue;i.push(d),a??=l}}if(i.length>0)throw new Vn(s,i,a);return s}import{createHash as Ec}from"node:crypto";function Tc(n,e){return yi(n,e,t=>t.included||Pr(t))}function Fc(n,e){if(n!==void 0)return{...Kn(n),...e?{planSha256:e}:{}}}function Kn(n){let e=Object.entries(n.rootWhere??{}).map(([r,o])=>[r,o.trim()]),t=[...new Set(n.strata??[])].sort();return{...n.withinMB!==void 0?{withinMB:n.withinMB}:{},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{},seed:n.seed??Oe.seed,draw:n.draw??Oe.draw,parents:n.parents??Oe.parents,children:n.children??Oe.children,floor:n.floor??Oe.floor,whole:[...new Set(n.whole??[])].sort(),...n.window?{window:Pc(n.window)}:{},...e.length>0?{rootWhere:Object.fromEntries(e)}:{},...t.length>0?{strata:t}:{}}}function Pc(n){return{field:n.field,...n.from!==void 0?{from:n.from}:{},...n.to!==void 0?{to:n.to}:{},...n.lastDays!==void 0?{lastDays:n.lastDays}:{}}}function Bt(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function wi(n){if(!Bt(n))return n;let e=typeof n.planSha256=="string"?n.planSha256:void 0;return Fc(n,e)}function vc(n){if(!Bt(n))return n;let e=n.config;return{...n,..."sample"in n?{sample:wi(n.sample)}:{},..."roots"in n?{roots:Cc(n.roots)}:{},...Bt(e)&&"sample"in e?{config:{...e,sample:wi(e.sample)}}:{}}}function Cc(n){if(!Bt(n))return n;let{objectApiName:e,sha256:t}=n;return typeof e!="string"||typeof t!="string"?n:{objectApiName:e,sha256:t}}function bm(n,e,t){return n===Tc(e,t)||n===yi(e,t,r=>r.included)}function yi(n,e,t){let r=n.nodes.map(s=>({objectApiName:s.objectApiName,included:t(s),anonymizeFields:[...s.anonymizeFields??[]].sort()})).sort((s,i)=>s.objectApiName.localeCompare(i.objectApiName)),o=n.edges.map(s=>({sourceObject:s.sourceObject,targetObject:s.targetObject,relationshipName:s.relationshipName,required:s.required===!0})).sort((s,i)=>`${s.sourceObject}|${s.targetObject}|${s.relationshipName}`.localeCompare(`${i.sourceObject}|${i.targetObject}|${i.relationshipName}`));return Ec("sha256").update(Hn({nodes:r,edges:o,setup:vc(e)})).digest("hex")}function Hn(n){return Array.isArray(n)?`[${n.map(e=>Hn(e??null)).join(",")}]`:n!==null&&typeof n=="object"?`{${Object.entries(n).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>`${JSON.stringify(t)}:${Hn(r)}`).join(",")}}`:JSON.stringify(n??null)}function km(n){let e={filters:Object.keys(n.objectSoqlFilters??{}).sort(),excluded:[...new Set(n.excludedObjects??[])].sort(),heldBack:[...new Set((n.skippedRows??[]).map(t=>t.object))].sort(),fieldsLeftOut:Object.entries(n.fieldExclusions??{}).filter(([,t])=>t.length>0).map(([t])=>t).sort()};return n.sample?{...e,sample:Kn(n.sample)}:Object.values(e).some(t=>t.length>0)?e:void 0}var Zn=class extends Error{constructor(t){super("The dry run of a clone of the whole org stops at its write gate: nothing was read past the counts, nothing written.");this.dryRun=t;this.name="WholeOrgDryRunStop"}dryRun},xc="NOTHING_TO_CLONE";function Im(n){if(n.nodes.some(t=>t.included))return;let e=new Set([...n.nodes.filter(t=>t.leftOutByUser===!0).map(t=>t.objectApiName),...(n.leftOut??[]).filter(t=>t.reason==="excludedByUser").map(t=>t.objectApiName)]).size;return{code:xc,message:e>0?`Nothing to clone: every object of the source that holds records is left out, ${e} of them by name. Leave fewer out. Nothing was written.`:"Nothing to clone: no object of the source holds records the target can take. Nothing was written."}}function jm(n){return n instanceof Zn||n instanceof Error&&n.name==="WholeOrgDryRunStop"&&"dryRun"in n}function Yn(n){return n.verdict==="unread"?{estimate:n.estimate,unread:n.unread}:{estimate:n.estimate,remaining:n.remaining,max:n.max,...n.verdict==="near"?{near:!0}:{}}}function Nm(n){return{api:n.targetRequests,wholeOrg:{source:n.sourceRequests,...n.bulkBatches?{bulkBatches:n.bulkBatches}:{},cost:{durationSeconds:n.durationSeconds}}}}function Mc(n,e){let t=a=>a.reduce((d,c)=>d+c.rows,0),r=n.objects.reduce((a,d)=>a+d.sourceRows,0)+n.noRecordDrawn.reduce((a,d)=>a+d.sourceRows,0),o=t(n.leftEmpty),{plan:s}=n,i=Date.parse(s.drawnAt);return{rows:n.rows,objects:n.objects.length,sourceRows:r,storageMB:n.storageBytes/1048576,budgetMB:n.budget.bytes/1048576,...n.budget.automationMB!==void 0&&n.budget.automationMB>0?{automationMB:n.budget.automationMB}:{},seed:n.seed,draw:n.draw,share:n.share,limitedBy:n.budget.limitedBy,parents:n.parents,children:n.children,drawnAt:s.drawnAt,drawnBy:s.drawnBy,...s.drawnBy==="dryRun"&&Number.isFinite(i)?{minutesBefore:Math.max(1,Math.ceil((e-i)/6e4))}:{},...s.drawnAgain?{drawnAgain:s.drawnAgain}:{},...s.ofTheRunRetried?{ofTheRunRetried:!0}:{},...o>0?{leftEmpty:o}:{},...n.heavyRoots.length>0?{heavyRoots:n.heavyRoots.length}:{},...n.noRecordDrawn.length>0?{noRecordDrawn:n.noRecordDrawn.length}:{},...n.newestByIds&&n.newestByIds.length>0?{newestByIds:[...n.newestByIds]}:{},...n.oldestByIds&&n.oldestByIds.length>0?{oldestByIds:[...n.oldestByIds]}:{},...n.roots?{roots:_c(n.roots)}:{}}}function _c(n){return{...n.window?{window:{...n.window}}:{},...n.where&&n.where.length>0?{where:n.where.map(({objectApiName:e,where:t})=>({objectApiName:e,where:t}))}:{},...n.strata&&n.strata.length>0?{strata:n.strata.map(({objectApiName:e,field:t,values:r,more:o})=>({objectApiName:e,field:t,values:r.length+(o??0)}))}:{},...n.notWindowed&&n.notWindowed.length>0?{notWindowed:[...n.notWindowed]}:{}}}function Em(n){let{run:e,measures:t,plan:r,budget:o}=n,s=new Set(r.objects.filter(({rows:g})=>g>0).map(({objectApiName:g})=>g)),i=t.writes.filter(({rows:g})=>g>0),a=g=>i.reduce((h,y)=>h+y[g],0),d=a("jobs"),c=[...s].filter(g=>ro(g)!==void 0).sort(),l=ys(e.graph.nodes,s,e.anonymizePII),f=n.files&&"check"in n.files?n.files:void 0,p=f?.check,u=t.contactPointsBlanked??0,m=o.wholeOrg.bulkBatches;return{source:e.source,leftOut:bs(e.graph).objects.length,...e.carried?{carried:e.carried}:{},...n.sample?{sample:Mc(n.sample,n.now??Date.now())}:{},targetApi:Yn(o.api),sourceApi:Yn(o.wholeOrg.source),...d>0?{bulk:{jobs:d,jobRows:a("jobRows"),restRows:a("restRows"),...m?{batches:Yn(m)}:{}}}:{},durationSeconds:o.wholeOrg.cost.durationSeconds,restObjects:i.filter(g=>g.jobs===0).map(g=>g.objectApiName),...f&&p&&p.verdict!=="unread"?{fileStorage:{files:f.count,estimateMB:p.estimateMB,overCeiling:t.files&&"overCeiling"in t.files?t.files.overCeiling:0,remainingMB:p.remainingMB,maxMB:p.maxMB,...p.verdict==="near"?{near:!0}:{}}}:{},...c.length>0?{managedPackages:c}:{},...u>0?{contactPointsBlanked:u}:{},...l.length>0?{personalAsIs:l}:{}}}var Lc=10*6e4,Dc=3e4,Bc=5e3,bi=500,$c=new Set(["JobComplete","Failed","Aborted"]),Ri=class{constructor(e,t={}){this.stateOf=e;this.options=t}stateOf;options;kept=[];noted=0;get count(){return this.noted}note(e){this.noted++,this.kept.push({seq:this.noted,job:{...e}}),this.kept.length>bi&&this.kept.splice(0,this.kept.length-bi)}since(e,t){return this.kept.filter(({seq:r,job:o})=>r>e&&o.orgId===t).map(({job:r})=>({...r}))}async stillRunning(e,t){let r=this.options.now??(()=>Date.now()),o=this.options.sleep??(c=>new Promise(l=>setTimeout(l,c))),s=this.options.pollDelay??vo,i=r()+(this.options.waitMs??Lc),a=e.filter(c=>c.jobId===void 0),d=e.filter(c=>!!c.jobId);for(let c=0;d.length>0;c++){let l=new At(Math.max(1,Math.min(Dc,i-r())));d=(await Promise.all(d.map(async u=>{t?.();let m=await l.withTimeout("forge:lost-bulk-job",()=>this.stateOf(u.orgId,u.jobId)).catch(()=>{});return m!==void 0&&$c.has(m)?void 0:u}))).filter(u=>u!==void 0);let p=i-r()-Bc;if(d.length===0||p<=0)break;await o(Math.min(s(c),p))}return[...a,...d]}};function vm(n){let e=new Map;for(let{objectApiName:t,jobId:r}of n)e.set(t,[...e.get(t)??[],{recordSummary:r?`Bulk API job ${r}`:"Bulk API job (the org gave no id)",messages:[r?"Still being written by the org when the run gave back the mute of its automation, after waiting for it: the rows it wrote from then went in with the flows, triggers and rules the mute kept quiet. Look the job up in the target\u2019s Bulk Data Load Jobs.":"Closed before the org gave its id, so it could not be waited for: the rows it wrote after the run gave back the mute of its automation went in with the flows, triggers and rules the mute kept quiet."]}]);return[...e].map(([t,r])=>({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:r}))}var Wc="SELECT SobjectType FROM DuplicateRule WHERE IsActive = true",xm=new Set(["Account","Contact","Lead"]);function Mm(n){if(typeof n.unread=="string")return;let e=n;if(e.unread.some(o=>o.part==="duplicateRules"))return;let t=new Map(e.objects.map(o=>[o.objectApiName.toLowerCase(),o.duplicateRules])),r=new Map;for(let o of e.objectsRead){let s=o.toLowerCase();if(!t.has(s)){r.set(o,!1);continue}let i=t.get(s);i!==void 0&&r.set(o,i.length>0)}return r}async function _m(n){try{let e=await n.query(Wc);return new Set(e.records.flatMap(t=>typeof t.SobjectType=="string"?[t.SobjectType]:[]))}catch{return}}var Si=class{constructor(e=3){this.maxDiscoveries=e}maxDiscoveries;discoveries=new Map;awaitingGuard=new Map;run=null;beginDiscovery(e,t,r){let o=[],s=c=>{this.discoveries.delete(c.requestId),c.stop="superseded",o.push(c)},i=this.discoveries.get(e);i&&s(i);let a=[...this.discoveries.values()].filter(c=>!c.controller.signal.aborted);for(;a.length>=this.maxDiscoveries;){let c=a.shift();c&&s(c)}let d={requestId:e,controller:t,operationId:r};return this.discoveries.set(e,d),{discovery:d,superseded:o}}endDiscovery(e){this.discoveries.get(e.requestId)===e&&this.discoveries.delete(e.requestId)}awaitGuard(e,t){return this.awaitingGuard.set(e,t),()=>{this.awaitingGuard.get(e)===t&&this.awaitingGuard.delete(e)}}beginRun(e,t){this.run={requestId:e,controller:t}}endRun(e){this.run?.requestId===e&&(this.run=null)}resolve(e){let t=e===void 0?this.onlyLive():this.named(e);return"refused"in t?t:(t.kind==="discovery"&&(this.discoveries.delete(t.discovery.requestId),t.discovery.stop="stopped"),{stops:t})}stop(e,t){let r=this.resolve(e);if("refused"in r)return r;let o=r.stops;return o.kind==="discovery"?t.discovery(o.discovery):o.kind==="awaiting-guard"?o.controller.abort():t.run(),r}named(e){let t=this.discoveries.get(e);if(t)return{kind:"discovery",discovery:t};let r=this.awaitingGuard.get(e);return r?{kind:"awaiting-guard",controller:r}:this.run?.requestId===e?{kind:"run"}:{refused:"none"}}onlyLive(){let e=[...[...this.discoveries.values()].filter(t=>!t.controller.signal.aborted).map(t=>({kind:"discovery",discovery:t})),...[...this.awaitingGuard.values()].filter(t=>!t.signal.aborted).map(t=>({kind:"awaiting-guard",controller:t})),...this.run&&!this.run.controller.signal.aborted?[{kind:"run"}]:[]];return e.length===0?{refused:"none"}:e.length>1?{refused:"several",live:e.length}:e[0]}};var Oi=V({value:W(),validFor:Z(te().int().nonnegative()).optional()}).loose(),Ai=V({controllerValues:an(W(),te().int().nonnegative()).optional(),defaultValue:Oi.nullable().optional(),values:Z(Oi)}).loose(),qc=V({picklistFieldValues:an(W(),Ne())}).loose(),zc=/^[A-Za-z][A-Za-z0-9_]*$/,Uc=/^012[A-Za-z0-9]{12}([A-Za-z0-9]{3})?$/;function Vc(n){let e=n.values.map(s=>s.value),t=n.defaultValue?.value??null,r=Object.entries(n.controllerValues??{});if(r.length===0)return{values:e,defaultValue:t};let o=new Map;for(let[s,i]of r)o.set(s,new Set(n.values.filter(a=>(a.validFor??[]).includes(i)).map(a=>a.value)));return{values:e,defaultValue:t,allowedByControllingValue:o}}function Gc(n){let e=qc.parse(n),t=new Map;for(let[r,o]of Object.entries(e.picklistFieldValues)){let s=Ai.safeParse(o);s.success&&t.set(r,Vc(s.data))}return t}function Jc(n){return Ai.parse(n).values.map(e=>e.value)}function ki(n,e,t,r){for(let s of r===void 0?[e]:[e,r])if(!zc.test(s))throw new Error(`Not an API name: "${s}"`);if(!Uc.test(t))throw new Error(`Not a record type id: "${t}"`);let o=`/services/data/v${n.version}/ui-api/object-info/${e}/picklist-values/${t}`;return r===void 0?o:`${o}/${r}`}async function Bm(n,e,t){return Gc(await n.request(ki(n,e,t)))}async function $m(n,e,t,r){return Jc(await n.request(ki(n,e,t,r)))}var Hc=V({FileStorageMB:V({Remaining:te()}).loose()}).loose(),Kc=Z(V({errorCode:W().optional(),message:W().optional()}).loose());function Yc(n){if(!(n instanceof Error))return new Error(String(n));try{let e=Kc.safeParse(JSON.parse(Buffer.from(n.message,"base64").toString("utf8"))),t=e.success?e.data[0]:void 0;if(t?.message)return new Error(t.errorCode?`${t.errorCode}: ${t.message}`:t.message)}catch{}return n}async function Vm(n,e,t){if(!Ro(t))throw new Error(`Not a record id: ${t}`);try{let r=await n.request({method:"GET",url:`/sobjects/${e}/${t}/${$s[e]}`},{encoding:"base64",responseType:"application/octet-stream"});if(typeof r!="string")throw new Error("The org answered with no file content.");return r}catch(r){throw Yc(r)}}async function Gm(n,e,t){try{let r=await n.request({method:"POST",url:`/sobjects/${e}`,body:JSON.stringify(t),headers:{"content-type":"application/json"}}),o=St(r,e);return{id:o.id,success:o.success,errors:o.errors}}catch(r){return{id:"",success:!1,errors:[No(r)]}}}async function Jm(n){return Hc.parse(await n.request({method:"GET",url:"/limits"})).FileStorageMB.Remaining}var eu=["Task","Event","FeedItem","FeedComment","EmailMessage","ContentDocumentLink","Note","CaseComment"],Ni=["Account","Contact","Lead","Opportunity","Case","Campaign","Contract","Order","Asset","Product2"],Xn=["User","Group","GroupMember","PermissionSet","PermissionSetAssignment","PermissionSetGroup","RecordType","Profile","UserRole"],tu=1e3,nu=6e4,Qn=1e4,ru=300,Ii=2e3,ou=50,su=3,Ei=3,iu=5,au=new Set(["flows","processes","triggers","conditions","definitions"]),Ti=new Set(["OwnerId","CreatedById","LastModifiedById","RecordTypeId"]),ut=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function U(n){return n.slice(0,15)}function ne(n){return typeof n=="string"?Date.parse(n):Number.NaN}function Ue(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function du(n){let e=ne(n?.first),t=ne(n?.last);if(!(!Number.isFinite(e)||!Number.isFinite(t)))return{from:Math.floor((e-tu)/1e3)*1e3,to:Math.ceil((Math.max(e,t)+nu)/1e3)*1e3}}function ig(n){if("error"in n)return{creates:[],gaps:{flowsNotRead:0,triggers:0,error:n.error}};let e=[],t=0,r=0;for(let s of n.objects){for(let i of[...s.flows,...s.processes??[]])if(i.startsOn!=="delete"){i.condition!=="read"&&t++;for(let a of i.creates??[])e.some(d=>d.toLowerCase()===a.toLowerCase())||e.push(a)}r+=s.triggers.filter(i=>i.events.some(a=>a!=="beforeDelete"&&a!=="afterDelete")).length}let o=n.unread.filter(s=>au.has(s.part)).map(s=>s.reason);return t===0&&r===0&&o.length===0?{creates:e}:{creates:e,gaps:{flowsNotRead:t,triggers:r,...o.length>0?{error:[...new Set(o)].join("; ")}:{}}}}function ag(n){return e=>Promise.all(e.map(async t=>{let r=n.lane({oneRow:!0});try{let o=await r.query(t);return o.totalSize??o.records.length}catch(o){return{reason:H(o)}}finally{r.close()}}))}async function cu(n,e,t){let r=new Map,o=0,s;for(let{objectApiName:i,ids:a}of e){if(o>=su||r.size>1||t())break;let d=a.slice(0,ou);if(d.length!==0)try{let[c]=X(d,d.length),l=await n.queryDeleted(`SELECT CreatedById FROM ${J(i)} WHERE Id IN (${c})`),f=!1;for(let p of l.records){let u=p?.CreatedById;typeof u=="string"&&ut.test(u)&&(r.has(U(u))||r.set(U(u),u),f=!0)}f&&o++}catch(c){s??=H(c)}}return r.size===1?{user:[...r.values()][0]}:r.size>1?{refusal:`The run's records were created by ${r.size} different users: whose records came with the run cannot be told, and nothing is swept.`}:{refusal:`The user the run wrote as could not be read: none of its records is left in the org or its recycle bin to tell it${s?` (${s})`:""}. Nothing is swept.`}}async function uu(n){try{let e=await n.describeGlobal(),t=Array.isArray(e?.sobjects)?e.sobjects:[],r=new Map;for(let o of t){let s=o??{};if(typeof s.name!="string")continue;let i=a=>typeof s[a]=="boolean"?{[a]:s[a]}:{};r.set(s.name.toLowerCase(),{name:s.name,...i("queryable"),...i("deletable"),...i("createable"),...i("layoutable")})}return r}catch{return}}function lu(n){return n.queryable!==!1&&n.deletable!==!1&&n.createable!==!1&&n.layoutable!==!1&&!Xn.some(e=>e.toLowerCase()===n.name.toLowerCase())}async function Fi(n,e){let t;try{t=await e(n)}catch(i){return{reason:H(i)}}if(t.queryable===!1)return{reason:"The org does not let it be queried."};if(t.deletable!==!0)return{reason:"The org does not let its records be deleted."};let r=new Set(t.fields.map(i=>i.name));if(!r.has("CreatedById")||!r.has("CreatedDate"))return{reason:"It keeps no creator or creation date to tell what the run\u2019s user created in the window: its records go with the records they belong to."};let o=r.has("LastModifiedDate")?"LastModifiedDate":r.has("SystemModstamp")?"SystemModstamp":"CreatedDate",s=t.fields.find(i=>i.nameField===!0)?.name;return{name:t.name,modified:o,...r.has("LastModifiedById")?{modifiedBy:"LastModifiedById"}:{},...s&&s!=="Id"?{nameField:s}:{},references:fu(t)}}function fu(n){return n.fields.filter(e=>e.type==="reference"&&!Ti.has(e.name)&&!((e.referenceTo??[]).length>0&&(e.referenceTo??[]).every(t=>Xn.includes(t)))).map(e=>e.name)}function pu(n,e){return`CreatedById = '${n}' AND CreatedDate >= ${Ue(e.from)} AND CreatedDate <= ${Ue(e.to)}`}function Pi(n,e){return n.length===1?pu(n[0],e):`CreatedById IN (${n.map(t=>`'${t}'`).join(", ")}) AND CreatedDate >= ${Ue(e.from)} AND CreatedDate <= ${Ue(e.to)}`}async function vi(n,e,t=[]){let r=()=>e.signal?.aborted===!0,o={looked:[],found:[],unread:[],handWork:[],...e.automation.gaps?{automationGaps:e.automation.gaps}:{}},s={listing:o,rows:new Map,stopped:!1},i=du(e.writtenBetween);if(!i)return o.refusal="The target did not date this run\u2019s writes: the window its automation wrote in cannot be told, and nothing is swept.",s;s.window=i,s.lastWrite=Math.max(ne(e.writtenBetween?.first),ne(e.writtenBetween?.last)),o.window={from:Ue(i.from),to:Ue(i.to)};let a=e.runUserId!==void 0&&ut.test(e.runUserId)?e.runUserId:void 0,d=e.user!==void 0&&ut.test(e.user)?e.user:void 0,c=e.created.some(f=>f.ids.length>0),l=a?{user:a}:c?await cu(n,e.created,r):d!==void 0?{user:d}:{refusal:"The run created nothing, and none of the records it wrote over still says, in its window, who last modified it: the user it wrote as cannot be told, and nothing is swept."};return"refusal"in l?(o.refusal=l.refusal,s.stopped=r(),s):Au(n,e,e.ties,l.user,s,i,t)}function mu(n){return n.map(e=>`${e.objectApiName}: ${e.count}`).join(", ")}async function gu(n,e,t){if(e.length===0)return[];if(n.counts)try{return await n.counts(e)}catch(o){let s=H(o);return e.map(()=>({reason:s}))}let r=[];for(let o of e){if(t()){r.push(void 0);continue}try{r.push((await n.query(o)).totalSize)}catch(s){r.push({reason:H(s)})}}return r}async function hu(n){try{return(await n.query("SELECT Id FROM User WHERE UserType = 'AutomatedProcess'")).records.map(t=>t?.Id).filter(t=>typeof t=="string"&&ut.test(t))}catch{return[]}}async function wu(n,e,t,r,o,s){let i=J(e.name),a=[...new Set(["Id","CreatedById","CreatedDate",e.modified,e.modifiedBy,e.nameField,...e.references].filter(f=>f!==void 0).map(J))],d=async f=>(await n.query(f)).records.filter(p=>typeof p=="object"&&p!==null),c=[],l;for(;;){if(s())return{rows:c,overBound:!1,stopped:!0};let f=`SELECT ${a.join(", ")} FROM ${i} WHERE ${Pi([...t.values()],r)}${l?` AND Id > '${l}'`:""} ORDER BY Id LIMIT ${Ii}`,p;try{let u=co(f);p=u?await lo(await d(u.first),u,d):await d(f)}catch(u){return{reason:H(u)}}for(let u of p){if(typeof u.Id!="string")continue;l=u.Id;let m=typeof u.CreatedById=="string"?U(u.CreatedById):"",g=ne(u.CreatedDate);if(!t.has(m)||!(g>=r.from&&g<=r.to)||o(U(u.Id)))continue;let h=e.modifiedBy?u[e.modifiedBy]:void 0,y=e.nameField?u[e.nameField]:void 0,R=[];for(let S of e.references){let w=u[S];typeof w=="string"&&ut.test(w)&&R.push({field:S,key:U(w)})}if(c.push({id:u.Id,modified:ne(u[e.modified]),created:g,creator:m,references:R,...typeof h=="string"?{modifiedBy:U(h)}:{},...typeof y=="string"&&y.trim()!==""?{name:y.trim().slice(0,80)}:{}}),c.length>Qn)return{rows:c.slice(0,Qn),overBound:!0,stopped:!1}}if(p.length<Ii)return{rows:c,overBound:!1,stopped:!1}}}function yu(n){let e=new Map,t=o=>{let s=o.toLowerCase(),i=e.get(s);return i||(i=(async()=>bt.parse(await n.describe(o)))(),i.catch(()=>{}),e.set(s,i)),i},r=async o=>{try{return await t(o)}catch{return}};return{of:t,now:r,async relation(o,s,i){let a=(await r(o))?.childRelationships?.find(d=>d.childSObject.toLowerCase()===s.toLowerCase()&&d.field===i);return{cascade:a?.cascadeDelete===!0,restricted:a?.restrictedDelete===!0}}}}async function bu(n,e,t,r,o,s){let i=await uu(n),a=u=>i?i.get(u.toLowerCase()):{name:u},d=[],c=[],l=u=>d.some(m=>m.toLowerCase()===u.toLowerCase()),f=u=>Xn.some(m=>m.toLowerCase()===u.toLowerCase()),p=(u,m)=>{if(l(u)||f(u))return;let g=a(u)?.name;if(!g){m&&o.unread.push({objectApiName:u,reason:"The org has no such object."});return}if(d.length>=ru){c.includes(g)||c.push(g);return}d.push(g)};for(let u of e)p(u,!0);for(let u of eu)p(u,!1);for(let u of t)p(u,!0);for(let u of Ni)p(u,!1);for(let u of e){if(s())return;for(let m of(await r.now(u))?.childRelationships??[]){let g=a(m.childSObject);g&&lu(g)&&!l(g.name)&&p(g.name,!1)}}return{looked:d,notLooked:c}}async function Ru(n,e,t,r,o,s,i){let a=[],d=new Map([...r.keys()].map(c=>[c.toLowerCase(),c]));for(let c of e){let l=((await o.now(c))?.fields??[]).filter(f=>f.type==="reference"&&!Ti.has(f.name));for(let f of l)for(let p of f.referenceTo??[]){let u=d.get(p.toLowerCase());if(!u)continue;let m=(r.get(u)??[]).map(y=>y.id),{restricted:g}=await o.relation(u,c,f.name),h=J(f.name);for(let y of X(m)){if(i())return;let R;try{R=(await n.query(`SELECT Id, ${h} FROM ${J(c)} WHERE ${h} IN (${y})`)).records}catch(S){s.unread.push({objectApiName:c,reason:`What its ${f.name} points at among the records found could not be read (${H(S)}): what only it ties is left as tied to nothing.`});continue}for(let S of R){let{Id:w,[f.name]:b}=S??{};typeof w!="string"||typeof b!="string"||t.has(U(w))&&a.push({from:U(w),to:U(b),restricted:g})}}}}return a}async function Su(n,e,t,r){let o=new Map;for(let s of t){let i=e.get(s);i?.kind==="created"&&o.set(i.objectApiName,[...o.get(i.objectApiName)??[],i.id])}for(let[s,i]of o)for(let a of X(i)){if(r())return!1;try{let d=await n.queryDeleted(`SELECT Id, CreatedDate FROM ${J(s)} WHERE Id IN (${a})`);for(let c of d.records){let{Id:l,CreatedDate:f}=c??{},p=typeof l=="string"?e.get(U(l)):void 0,u=ne(f);p&&Number.isFinite(u)&&(p.from=u,p.to=u)}}catch{}}return!0}function Ou(n,e,t,r,o,s){let{listing:i}=r,a=new Set(Ni.map(u=>u.toLowerCase())),d=[],c=[],l=["made","madeOver","late","untied"];for(let[u,m]of n){let g=[],h=0;for(let b of m){let A=e.get(U(b.id));if(A){if(A.class==="untied"&&a.has(u.toLowerCase())){h++;continue}g.push({id:b.id,modified:b.modified,created:b.created,class:A.class,sameSave:A.sameSave,turn:A.turn,...b.modifiedBy!==void 0?{modifiedBy:b.modifiedBy}:{},...b.name!==void 0?{name:b.name}:{}})}}if(h>0&&i.handWork.push({objectApiName:u,count:h}),g.length===0)continue;let y={made:0,madeOver:0,late:0,untied:0},R=0,S=0,w={};for(let b of g)y[b.class]++,b.sameSave&&R++,$t(b,o,s)&&(S++,w[b.class]=(w[b.class]??0)+1);i.found.push({objectApiName:u,count:g.length,names:l.flatMap(b=>g.filter(A=>A.class===b)).flatMap(b=>b.name?[b.name]:[]).slice(0,Ei),classes:{...y,...R>0?{sameSave:R}:{},...S>0?{changed:S,changedIn:w}:{}}}),y.untied>0&&d.push({objectApiName:u,count:y.untied}),y.late>0&&c.push({objectApiName:u,count:y.late}),r.rows.set(u,g)}let f=[];i.handWork.length>0&&f.push(`The run's user created records in the run's window tied to nothing of the run, on objects people make by hand (${mu(i.handWork)}): hand work, likely, in the same span. They are left, and so is everything tied to nothing: what was made by hand could not be told from what the automation made.`);let p=(t.otherRuns??[]).filter(u=>u.ids.length>0||u.idsUntold===!0).length;p>0&&f.push(`${p===1?"Another run":`${p} other runs`} of this machine wrote to the target in this run\u2019s window: what is tied to nothing of this run may be theirs, and is left.`),f.length>0&&f.push("The runs of another machine, or of a CI, in the same window are not seen."),i.untied={objects:d,...f.length>0?{refusal:f.join(" ")}:{}},i.late=c}async function Au(n,e,t,r,o,s,i){let{listing:a}=o,d=()=>e.signal?.aborted===!0,c=()=>(o.stopped=!0,o),l=ne(e.writtenBetween?.first),f=Math.max(l,ne(e.writtenBetween?.last)),p=Math.min(Number.POSITIVE_INFINITY,...[t.removalBegan,...i.map(P=>P.first)].map(ne).filter(Number.isFinite)),u=Math.ceil((f+9e5)/1e3)*1e3,m={from:s.from,to:Math.max(s.to,Math.min(u,Math.floor(p/1e3)*1e3))},g=new Map,h={from:l,to:f};for(let{objectApiName:P,ids:L}of e.created)for(let M of L)g.set(U(M),{kind:"created",objectApiName:P,id:M,from:Number.NaN,to:Number.NaN});for(let{objectApiName:P,ids:L,between:M}of t.writtenOver??[]){let $=ne(M?.first),q=ne(M?.last);for(let Q of L)g.has(U(Q))||g.set(U(Q),{kind:"overwritten",objectApiName:P,id:Q,from:$,to:q})}let y=[...new Set([...e.created,...t.writtenOver??[]].filter(P=>P.ids.length>0).map(P=>P.objectApiName))],R=new Set([...(t.otherRuns??[]).flatMap(P=>P.ids.map(U)),...(t.leased??[]).map(U)]),S=P=>e.remap.has(P)||g.has(P)||R.has(P),w=await hu(n),b=new Map([[U(r),r]]);for(let P of w)b.has(U(P))||b.set(U(P),P);let A=new Set(w.map(U).filter(P=>P!==U(r))),E=yu(n),x=await bu(n,y,e.automation.creates,E,a,d);if(!x)return c();let{looked:T,notLooked:v}=x;a.looked=T,v.length>0&&(a.notLooked=v);let I=await gu(n,T.map(P=>`SELECT COUNT() FROM ${J(P)} WHERE ${Pi([...b.values()],m)}`),d);if(d())return c();let N=new Map,_=[];for(let[P,L]of T.entries()){let M=I[P];if(M===void 0)return c();if(M===0)continue;if(d())return c();let $=await Fi(L,E.of);if("reason"in $){a.unread.push({objectApiName:L,reason:$.reason});continue}if(typeof M=="object"){a.unread.push({objectApiName:L,reason:M.reason});continue}let q=await wu(n,$,b,m,S,d);if("reason"in q){a.unread.push({objectApiName:L,reason:q.reason});continue}if(q.stopped)return c();q.overBound?_.push({objectApiName:L,count:q.rows.length,names:q.rows.flatMap(Q=>Q.name?[Q.name]:[]).slice(0,Ei),overBound:!0}):q.rows.length>0&&N.set(L,q.rows)}let D=new Map;for(let{part:P,created:L}of e.otherParts??[])for(let{objectApiName:M,ids:$}of L)for(let q of $)D.set(U(q),{part:P,objectApiName:M});let j=new Map;for(let[P,L]of D.size>0?[...N]:[]){let M=[];for(let $ of L){let q,Q=!1;for(let he of $.references){let Tr=g.get(he.key)??D.get(he.key);if(!Tr)continue;let{cascade:Ca}=await E.relation(Tr.objectApiName,P,he.field);Ca&&(g.has(he.key)?Q=!0:q??=D.get(he.key)?.part)}if(q===void 0||Q){M.push($);continue}let Se=j.get(q)??[],je=Se.find(he=>he.objectApiName===P);je?je.count++:Se.push({objectApiName:P,count:1}),j.set(q,Se)}M.length>0?N.set(P,M):N.delete(P)}j.size>0&&(a.otherParts=[...j].map(([P,L])=>({part:P,objects:L})));let F=new Map;for(let[P,L]of g)F.set(P,L.objectApiName);for(let[P,L]of N)for(let M of L)F.set(U(M.id),P);let k=[],O=new Set;for(let[P,L]of N)for(let M of L){let $=[];for(let q of M.references){let Q=F.get(q.key);if(!Q)continue;g.has(q.key)&&O.add(q.key);let{cascade:Se}=await E.relation(Q,P,q.field);$.push({key:q.key,cascade:Se})}k.push({key:U(M.id),created:M.created,automatedProcess:A.has(M.creator),references:$})}let C=await Ru(n,y,g,N,E,a,d);if(!C)return c();for(let P of C)O.add(P.from);if(!await Su(n,g,O,d))return c();let B=_o({anchors:g,candidates:k,pointers:C,runSpan:h,window:s,removalBegan:p,madeEarlier:new Set((t.madeEarlier??[]).map(U)),lateEarlier:new Set((t.lateEarlier??[]).map(U))});return Ou(N,B,t,o,f,i),d()?c():(await ku(n,E,o,{user:r,span:m,lastWrite:f,removalSpans:i,isRun:P=>g.has(P)||e.remap.has(P)}),a.found.push(..._),t.muted&&(a.muted=t.muted),o.ordering={query:P=>n.query(P),queryDeleted:P=>n.queryDeleted(P),describe:async P=>await E.now(P)??n.describe(P),describeGlobal:()=>n.describeGlobal(),destroy:(P,L)=>n.destroy(P,L),update:(P,L)=>n.update(P,L),serverTime:()=>n.serverTime(),userId:()=>n.userId()},o)}var ji={untied:0,late:1,madeOver:2,made:3};async function ku(n,e,t,r){let o=new Map;for(let u of t.rows.values())for(let m of u)o.set(U(m.id),m);if(o.size===0||t.rows.has(ue))return;let s=(await Lo(n,{has:u=>o.has(u)||r.isRun(u),start:r.span.from,end:r.span.to,user:r.user})).filter(u=>!r.isRun(U(u.id))&&u.names.some(m=>o.has(m)));if(s.length===0)return;let i=await Fi(ue,e.of);if("reason"in i){t.listing.unread.push({objectApiName:ue,reason:i.reason});return}let a=new Map,d=s.map(u=>{let m=u.names.flatMap(R=>{let S=o.get(R);return S?[S]:[]});a.set(u.id,m.map(R=>U(R.id)));let g=m.reduce((R,S)=>ji[S.class]<ji[R]?S.class:R,"made"),h=Math.max(...m.map(R=>R.created)),y=u.modifiedBy!==void 0&&U(u.modifiedBy)===U(r.user)&&u.modified<=h+6e4;return{id:u.id,created:u.created,modified:y?Math.min(u.modified,u.created):u.modified,...u.modifiedBy!==void 0?{modifiedBy:U(u.modifiedBy)}:{},class:g,turn:"before"}});t.rows.set(ue,d),t.reports=a;let c={made:0,madeOver:0,late:0,untied:0},l=0,f={};for(let u of d)c[u.class]++,$t(u,r.lastWrite,r.removalSpans)&&(l++,f[u.class]=(f[u.class]??0)+1);let{listing:p}=t;p.found.push({objectApiName:ue,count:d.length,names:[],classes:{...c,...l>0?{changed:l,changedIn:f}:{}}}),c.late>0&&(p.late=[...p.late??[],{objectApiName:ue,count:c.late}]),c.untied>0&&p.untied&&(p.untied={...p.untied,objects:[...p.untied.objects,{objectApiName:ue,count:c.untied}]})}function $t(n,e,t){let r=Math.max(e,n.created)+2e3;return!(n.modified<=r)&&!Iu(n,t)}function Iu(n,e){return n.modifiedBy!==void 0&&e.some(t=>n.modifiedBy===U(t.userId)&&n.modified>=ne(t.first)&&n.modified<=ne(t.last))}async function dg(n,e,t=[]){return(await vi(n,e,t)).listing}function ju(n,e){let t=[],r=n.late??[];r.length>0&&e.sweepLate!==!0&&t.push({class:"late",objects:r,option:"--sweep-late"});let{objects:o=[],refusal:s}=n.untied??{};return o.length>0&&(e.sweepUntied!==!0||s!==void 0)&&t.push({class:"untied",objects:o,option:"--sweep-untied",...s!==void 0?{refusal:s}:{}}),t}function cg(n,e,t){let r=()=>e.signal?.aborted===!0,o=jo(),s=new Set,i=new Set,a=new Set,d=new Set,c=[],l="new",f,p,u,m=new Map,g={unread:[],handWork:[]},h=new Map,y=new Map,R=async(v,I)=>{let N=v.lastWrite??Number.NaN,_=new Set,D=new Map;for(let[C,B]of I){let P=B.filter(L=>t.includeChanged||!$t(L,N,t.removalSpans)).map(L=>L.id);for(let L of P)_.add(L);D.set(C,P)}if(_.size===0||!v.window)return;let j=new Set(e.created.flatMap(({ids:C})=>C.map(U))),F=v.ordering??n,k=Do(F,{runStart:v.window.from,runEnd:N,runRecords:{has:C=>j.has(C)},taken:_,removalSpans:t.removalSpans,includeChanged:t.includeChanged,...e.runUserId?{runUserId:e.runUserId}:{}}),O=await yn(F,[...I.keys()].map(C=>({objectApiName:C})));for(let{objectApiName:C}of O){if(C===ue)continue;let B=D.get(C)??[];if(B.length===0)continue;if(r())return;let P=await k(C,B);P.reason!==void 0&&y.set(C,P.reason);for(let L of B)P.held.has(U(L))&&(_.delete(L),h.set(L,P.holders))}S(v,I,_)},S=(v,I,N)=>{let _=v.reports;if(!_)return;let D=new Set([...I].filter(([j])=>j!==ue).flatMap(([,j])=>j.filter(F=>N.has(F.id)).map(F=>U(F.id))));for(let j of I.get(ue)??[])h.has(j.id)||(_.get(j.id)??[]).every(F=>D.has(F))||(N.delete(j.id),h.set(j.id,["DuplicateRecordItem"]))},w=(v,I)=>{v.result.alreadyGone++,v.along.has(I)&&(v.result.withRemoval=(v.result.withRemoval??0)+1)},b=(v,I,N)=>{I.forEach((_,D)=>{let j=N[D];if((j.lockResends!==void 0||v.lockResent.has(_))&&v.lockResent.set(_,j.kind),j.kind==="refused"){v.refused.set(_,j.reason),j.limit&&v.limited.add(_);return}v.refused.delete(_),v.limited.delete(_),d.add(_),j.kind==="deleted"?v.result.deleted++:w(v,_)})},A=async(v,I,N)=>{for(let _=0;_<I.length;_+=_e){if(r())return!1;let D=I.slice(_,_+_e),j=v.result.deleted,F=await Co(n,v.result.objectApiName,D,o,{stopped:r,settle:(k,O)=>b(v,k,[...O])});if(N&&v.result.deleted>j){let k=v.result.deleted-j;v.result.afterRemoval=(v.result.afterRemoval??0)+k,N==="under"&&(v.result.afterRemovalUnder=(v.result.afterRemovalUnder??0)+k)}if(F)return!1}return!0},E=()=>c.reduce((v,I)=>v+I.result.deleted,0),x=async()=>{let v=g.left??[];if(v.length===0||!u)return;let I=u.rows,N=[],_=[];for(let j of v){let F=[],k=[];for(let O of j.objects){let C=(I.get(O.objectApiName)??[]).filter(L=>L.class===j.class).map(L=>L.id),B=r()?[]:(await bn(C,L=>pe(n,O.objectApiName,[],L),()=>!0)).gone;for(let L of B)d.add(L);let P=Math.min(B.length,O.count);O.count>P&&F.push({...O,count:O.count-P}),P>0&&k.push({objectApiName:O.objectApiName,count:P})}F.length>0&&N.push({...j,objects:F}),k.length>0&&_.push({class:j.class,objects:k})}if(_.length===0)return;let D={...g};delete D.left,g={...D,...N.length>0?{left:N}:{},goneAlong:_}},T=()=>(p??=(async()=>{let v=await vi(n,e,t.removalSpans);u=v;let{listing:I}=v;if(g={...I.window?{window:I.window}:{},unread:[...I.unread,...I.found.filter(j=>j.overBound).map(j=>({objectApiName:j.objectApiName,reason:`More than ${Qn} records created by the run's user in the window: none is swept, as that many are more than the run\u2019s side effects come to.`}))],...I.automationGaps?{automationGaps:I.automationGaps}:{},handWork:I.handWork},v.stopped){l="cancelled";return}for(let j of v.rows.values())for(let F of j)F.class==="made"||F.class==="madeOver"?i.add(F.id):F.class==="late"&&a.add(F.id);if(I.refusal!==void 0){l="refused",f=I.refusal;return}let N=t.sweepUntied===!0&&I.untied?.refusal===void 0,_=j=>j.class==="made"||j.class==="madeOver"||j.class==="late"&&t.sweepLate===!0||j.class==="untied"&&N;if(m=new Map([...v.rows].map(([j,F])=>[j,F.filter(_)]).filter(([,j])=>j.length>0)),await R(v,m),r()){l="cancelled";return}if(t.approve&&m.size>0){let j=await t.approve(I);if(j!==void 0){l="refused",f=j;return}}let D=ju(I,t);D.length>0&&(g={...g,left:D}),l="asked"})(),p);return{automationMade:s,made:i,late:a,gone:d,get listing(){return u&&!u.stopped?u.listing:void 0},get takes(){return l==="asked"?[...m.keys()]:[]},ask:T,async first(v){if(v&&(o=v),await T(),l!=="asked"||!u)return!1;let I=u,N=m,_=I.lastWrite??Number.NaN,D=await yn(I.ordering??n,[...N.keys()].map(F=>({objectApiName:F}))),j=[];for(let{objectApiName:F}of D){let k=N.get(F)??[],O={result:{objectApiName:F,found:k.length,deleted:0,alreadyGone:0,keptChanged:0,refused:0,reasons:[]},refused:new Map,limited:new Set,later:[],along:new Set,lockResent:new Map};c.push(O);let C=[];for(let B of k){if($t(B,_,t.removalSpans)&&!t.includeChanged){O.result.keptChanged++;continue}let P=h.get(B.id);if(P){O.result.keptDependents=(O.result.keptDependents??0)+1,O.result.heldBy=[...new Set([...O.result.heldBy??[],...P])];continue}s.add(B.id),B.turn==="before"?C.push(B.id):O.later.push(B.id),B.turn==="with"&&O.along.add(B.id)}j.push([O,C])}for(let[F,k]of j)if(!await A(F,k))return l="cancelled",E()>0;return l="first",E()>0},async afterRemoval(v){if(v&&(o=v),l!=="first")return!1;let I=E();for(let N of c){let _=N.later.splice(0),D=_.filter(F=>N.along.has(F)),j=_.filter(F=>!N.along.has(F));if(!await A(N,j,"pointedAt")||!await A(N,D,"under"))return l="cancelled",E()>I}if(E()>0)for(let N of c){let _=[...N.refused.keys()].filter(D=>!N.limited.has(D));if(!await A(N,_))return l="cancelled",E()>I}for(let N of c){if(r())break;let{gone:_}=await bn([...N.refused.keys()],D=>pe(n,N.result.objectApiName,[],D),()=>!0);for(let D of _)N.refused.delete(D),N.lockResent.has(D)&&N.lockResent.set(D,"gone"),w(N,D),d.add(D)}return await x(),l="done",E()>I},result(){if(l==="refused")return{status:"refused",refusal:f??"",objects:[],...g};if(l==="new"||l==="asked")return{status:"cancelled",objects:[],...g};let v=c.map(({result:N,refused:_,lockResent:D})=>{N.refused=_.size;let j=y.get(N.objectApiName);return N.reasons=[...new Set([...j!==void 0&&(N.keptDependents??0)>0?[`What hangs from them could not be read, and they were kept: ${j}`]:[],...xo(N.objectApiName,o),...Mo(D.values()),..._.values()])].slice(0,iu),N}),I=c.some(N=>N.later.length>0);return{status:Nu(v,l==="cancelled",I,Eu(g,t)),objects:v,...g}}}}function Nu(n,e,t=!1,r=!1){return e?"cancelled":t||r||n.some(s=>s.keptChanged+(s.keptDependents??0)+s.refused>0)?n.some(s=>s.deleted>0)?"partial":"failure":"success"}function Eu(n,e){return(n.left??[]).some(t=>t.class==="late"&&e.sweepLate===!0||t.class==="untied"&&e.sweepUntied===!0)}function ug(n,e,t){if(n.status==="refused")return;let r=o=>n.objects.reduce((s,i)=>s+o(i),0);return{sweptAt:e,deleted:(t?.deleted??0)+r(o=>o.deleted),keptChanged:r(o=>o.keptChanged),refused:r(o=>o.refused)}}function lg(n){return n.objects.filter(e=>e.deleted+e.refused>0).map(e=>({...so(e.objectApiName),deleted:e.deleted,failed:e.refused}))}function fg(n,e){let t=r=>n.objects.reduce((o,s)=>o+r(s),0);return{sweep:!0,forgeId:e,found:t(r=>r.found),deleted:t(r=>r.deleted),keptChanged:t(r=>r.keptChanged),refused:t(r=>r.refused),handWork:n.handWork.reduce((r,o)=>r+o.count,0)}}function pg(n){return n.found.reduce((e,t)=>e+t.count,0)}function mg(n){return n.found.map(e=>e.objectApiName)}var Tu=15e3,wg=2,Fu=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function Pu(n,e){try{let{user_id:t}=await new At(Tu).withTimeout(`${e} run user`,async()=>n());return typeof t=="string"&&Fu.test(t)?t:void 0}catch{return}}function yg(n,e,t){n?.runUser&&Pu(e,t).then(r=>{r!==void 0&&n.runUser?.(r)})}var tr=class extends me{constructor(t){super("SAMPLE_DRAW_INVALID",`${t.join(" ")} Nothing was written, and no root was counted or read: the requests sent before the draw were discovery\u2019s and the target\u2019s.`,void 0,void 0,void 0,{sample:{requests:0}});this.problems=t}problems},vu=1440*60*1e3,Ci=2,Li=new Set(["picklist","boolean","reference"]),Cu=6,er=12;function xu(n){return n.replace(/'(?:[^'\\]|\\.)*'/g,"''")}function xi(n){return n===void 0?0:xu(n).match(/\(\s*SELECT\b/gi)?.length??0}function Ve(n,e){let t=e.toLowerCase();return n?.find(r=>r.name.toLowerCase()===t)}function Wt(n){if(n.length===0)return"none";let e=n.slice(0,er).join(", ");return n.length>er?`${e} and ${n.length-er} more`:e}function Mu(n,e){if(n.lastDays!==void 0&&n.from===void 0&&n.to===void 0)return{window:{field:n.field,from:ke(e-n.lastDays*vu),lastDays:n.lastDays}};let t=s=>{if(s!==void 0)try{return ke(s)}catch{return null}},r=t(n.from),o=t(n.to);return r===null||o===null?{problem:`The window's bound ${r===null?n.from:n.to} is no instant: write it in UTC, as 2025-07-01T00:00:00Z.`}:r!==void 0&&o!==void 0&&Date.parse(r)>=Date.parse(o)?{problem:`The window starts at ${r} and ends before it, at ${o}: its start is before its end.`}:{window:{field:n.field,...r!==void 0?{from:r}:{},...o!==void 0?{to:o}:{}}}}function Mi(n,e){let t=(n.linksOf.get(e)??[]).find(r=>r.carries&&r.required&&r.prefix===void 0);return t?{field:t.field,parent:t.parent}:void 0}function Di(n,e,t){let r=t.toLowerCase(),o=(n.linksOf.get(e)??[]).find(s=>s.carries&&s.field.toLowerCase()===r);return o?{parent:o.parent}:void 0}function _u(n,e){let t=(n.fieldsOf(e)??[]).filter(s=>s.groupable!==!1&&Li.has(s.type??"")&&Di(n.links,e,s.name)===void 0),r=["RecordTypeId","OwnerId"].flatMap(s=>{let i=Ve(t,s);return i?[i.name]:[]}),o=t.filter(s=>s.type==="picklist").map(s=>s.name).sort();return[...r,...o].slice(0,Cu)}function qt(n,e){let t=_u(n,e);return"Its roots are stratified by a field of few values \u2014 a picklist, a checkbox, the record type (RecordTypeId) or the owner (OwnerId)"+(t.length>0?`: of ${e}, ${t.join(", ")}.`:".")}function _i(n,e,t){let r=n.fieldsOf(e),o=Ve(r,t);if(!o)return{problem:`${e} has no field ${t}. ${qt(n,e)}`};if(!Li.has(o.type??""))return{problem:(o.type?`${e}.${o.name} is a ${o.type} field, of too many values to stratify by. `:`The describe does not say what type ${e}.${o.name} is, and a stratum is of a known few. `)+qt(n,e)};let s=Di(n.links,e,o.name);return s?{problem:`${e}.${o.name} names the ${s.parent} a record of ${e} comes under, and a root of ${e} never fills it: it stratifies nothing. `+qt(n,e)}:o.groupable===!1?{problem:`The source does not group ${e} by ${o.name}, which its strata are counted by. ${qt(n,e)}`}:Ve(r,"Id")?.aggregatable===!1?{problem:`The source does not count the records of ${e} by a field (COUNT(Id)), which its strata are counted by: its roots cannot be stratified.`}:{field:o.name}}function Bi(n){let{links:e,options:t}=n,r=[],o;if(t.window!==void 0){let h=Mu(t.window,n.now);"problem"in h?r.push(h.problem):o=h.window}let s=[...e.classes].filter(([,h])=>h.kind==="drawn"&&h.rooted).map(([h])=>h).sort(),i=s.filter(h=>!Mi(e,h)),a=new Map([...e.classes.keys()].map(h=>[h.toLowerCase(),h])),d=new Map([...n.excluded??[]].map(h=>[h.toLowerCase(),h])),c=(h,y)=>{let R=y==="where"?"filter on its roots":"strata",S=a.get(h.toLowerCase()),w=S===void 0?void 0:e.classes.get(S);if(S===void 0||w===void 0){let A=d.get(h.toLowerCase());r.push(A!==void 0?`${A} is left out of the run (--exclude-object), and has no root to draw: take it out of one option or the other.`:`${h} is no object of the run, and takes no ${R}. The objects whose roots are drawn are ${Wt(i)}.`);return}if(w.kind==="whole"){r.push(`Every record of ${S} comes, as the sample copies it whole: it has no root drawn, and takes no ${R}. `+(y==="where"?"--filter leaves records of it out of the copy.":`The objects whose roots are drawn are ${Wt(i)}.`));return}if(!w.rooted){r.push(`${S} has no root of its own: its records come as the records the sample keeps name them, and it takes no ${R}. The objects whose roots are drawn are ${Wt(i)}.`);return}let b=Mi(e,S);if(b){r.push(`Every record of ${S} comes under the ${b.parent} it cannot be written without (${b.field}): it has no root, and takes no ${R}. `+(y==="where"?`Filter the roots of ${b.parent} instead: --fit-where "${b.parent}=Id IN (SELECT ${b.field} FROM ${S} WHERE \u2026)".`:`Stratify the roots of ${b.parent} instead.`));return}return S},l=new Map;for(let[h,y]of Object.entries(t.rootWhere??{})){let R=c(h,"where");if(R===void 0)continue;if(l.has(R)){r.push(`The roots of ${R} are given two filters: give one.`);continue}let S=xi(n.filterOf?.(R))+xi(y);if(S>Ci){r.push(`A statement of ${R} takes ${Ci} semi-joins at most (IN (SELECT \u2026)), and its filter and the filter on its roots hold ${S}: write one of them without, or fold them into fewer.`);continue}l.set(R,y.trim())}let f,p=new Map;for(let h of t.strata??[]){let y=h.indexOf(".");if(y<0){f=h;continue}let R=c(h.slice(0,y),"strata");if(R!==void 0){if(p.has(R)){r.push(`The roots of ${R} are stratified by one field at most: give one.`);continue}p.set(R,h.slice(y+1))}}let u=new Map;for(let[h,y]of p){let R=_i(n,h,y);"problem"in R?r.push(R.problem):u.set(h,R.field)}if(f!==void 0){let h=!1;for(let y of i){if(p.has(y))continue;let R=n.fieldsOf(y),S=Ve(R,f);if(!S||S.groupable===!1||Ve(R,"Id")?.aggregatable===!1)continue;h=!0;let w=_i(n,y,S.name);"problem"in w?r.push(`${w.problem} Or name each object ${f} stratifies, as Object.${f}.`):u.set(y,w.field)}h||r.push(`No object whose roots are drawn \u2014 ${Wt(i)} \u2014 has a field ${f} it groups by. Name the object and its field, as ${i[0]??"Account"}.RecordTypeId.`)}if(r.length>0)throw new tr(r);let m=[],g=new Map;for(let h of s){let y=l.get(h),R=u.get(h),S={objectApiName:h,...y!==void 0?{where:y}:{},...R!==void 0?{stratifiedBy:R}:{}};o!==void 0&&(Ve(n.fieldsOf(h),o.field)?S.window={field:o.field,...o.from!==void 0?{from:o.from}:{},...o.to!==void 0?{to:o.to}:{}}:(S.notWindowed=!0,m.push(h))),g.set(h,S)}return{...o!==void 0?{window:o}:{},objects:g,notWindowed:m,where:[...l].map(([h,y])=>({objectApiName:h,where:y})).sort((h,y)=>h.objectApiName<y.objectApiName?-1:1),restricted:o!==void 0||l.size>0,stratified:u.size>0}}function $i(n){return{...n.window!==void 0?{window:n.window}:{},...n.notWindowed.length>0?{notWindowed:[...n.notWindowed]}:{},...n.where.length>0?{where:n.where.map(e=>({...e}))}:{}}}function Lu(n,e){return n.created!==e.created?n.created===void 0?1:e.created===void 0?-1:e.created-n.created:le(e.id,n.id)}var Du=1e6,nr=class extends Error{constructor(t,r){super(`Drawing the sample read ${t} records, more than the ${r} it holds at once. Nothing was written. Lower the bound (--fit-within or --max-total), or leave objects out (--exclude-object) or narrow them (--filter).`);this.rows=t;this.most=r;this.name="SampleTooLarge"}rows;most},rr=class extends Error{constructor(){super("The sample was cancelled before it was drawn. Nothing was written."),this.name="SampleCancelled"}},Bu="AccountId",or=class{values=[];rows=[];get size(){return this.rows.length}push(e,t){let{values:r,rows:o}=this;r.push(e),o.push(t);let s=o.length-1;for(;s>0;){let i=s-1>>1;if(r[i]<=r[s])break;[r[s],r[i]]=[r[i],r[s]],[o[s],o[i]]=[o[i],o[s]],s=i}}pop(){let{values:e,rows:t}=this,r=[e[0],t[0]],o=e.pop(),s=t.pop();if(t.length>0){e[0]=o,t[0]=s;let i=0;for(;;){let a=2*i+1,d=a+1,c=i;if(a<t.length&&e[a]<e[c]&&(c=a),d<t.length&&e[d]<e[c]&&(c=d),c===i)break;[e[i],e[c]]=[e[c],e[i]],[t[i],t[c]]=[t[c],t[i]],i=c}}return r}},zt=class{constructor(e,t,r){this.links=e;this.reader=t;this.options=r}links;reader;options;rows=[];objectOf=[];rootOf=[];whole=[];dead=[];out=[];index=new Map;absent=new Map;wholeRead=new Set;below=new Map;cuts=new Map;needs=new Map;waiting=new Map;pending=new Map;upCursor=0;optionalCursor=0;descended=[];toDescend=[];rowOf(e,t){return this.index.get(e)?.get(z(t))}isAbsent(e,t){return this.absent.get(e)?.has(z(t))===!0}wasReadWhole(e){return this.wholeRead.has(e)}alive(e){return this.dead[e]===void 0}get cut(){return this.cuts}belowOf(e){return this.below.get(e)??[]}async openWhole(){let e=new Set;for(let t of this.links.linksOf.values())for(let r of t)r.target==="whole"&&e.add(r.parent);for(let[t,r]of this.links.classes){if(r.kind!=="whole"||r.why==="referenceData"||!(this.links.linksOf.get(t)??[]).some(i=>i.target==="drawn"&&(i.required||this.options.parents==="all"))&&!e.has(t))continue;this.checkSignal();let s=await this.reader.whole(t);this.wholeRead.add(t);for(let i of s){let a=this.register(t,i);this.whole[a]=!0}this.told()}await this.close()}async addRoots(e,t){let r=new Map;e.forEach((o,s)=>{let i=r.get(o.objectApiName)??[];i.push({id:o.id,index:t+s}),r.set(o.objectApiName,i)});for(let[o,s]of[...r].sort(([i],[a])=>i<a?-1:1)){let i=s.filter(({id:a})=>this.rowOf(o,a)===void 0).map(({id:a})=>a).sort(le);if(i.length>0){this.checkSignal();let a=await this.reader.rows(o,i);for(let d of a)this.register(o,d);this.markAbsent(o,i),this.told()}for(let{id:a,index:d}of s){let c=this.rowOf(o,a);c===void 0||this.rootOf[c]>=0||(this.rootOf[c]=d,this.toDescend.push(c))}}await this.close()}async close(){for(;;)if(await this.readUp(),!await this.readOptionalParents()&&!await this.readDown())return}requiredHere(e,t){return e.required?!0:e.objectApiName===oe&&e.field===Bu&&e.parent===ce&&this.rows[t].personAccount===!0}requiredOf(e){let t=this.objectOf[e],{refs:r,also:o}=this.rows[e],s=[],i;for(let a of this.links.linksOf.get(t)??[]){if(!this.requiredHere(a,e))continue;let d=r[a.field];Pe(d,a)&&(a.target==="excluded"?i??="excludedObject":(a.target==="drawn"||this.wholeRead.has(a.parent))&&s.push({objectApiName:a.parent,id:d}))}for(let a of o??[])a.id===null?i??="noParentInSource":this.readable(a.objectApiName)&&s.push({objectApiName:a.objectApiName,id:a.id});return{named:s,...i?{dies:i}:{}}}readable(e){let t=this.links.classes.get(e);return t!==void 0&&(t.kind==="drawn"||this.wholeRead.has(e))}optionalOf(e){let t=this.objectOf[e],{refs:r}=this.rows[e],o=[];for(let s of this.links.linksOf.get(t)??[]){if(s.target!=="drawn"||this.requiredHere(s,e))continue;let i=r[s.field];Pe(i,s)&&o.push({objectApiName:s.parent,id:i})}return o}upTargets(e){let t=this.objectOf[e],{refs:r,also:o}=this.rows[e],s=[];for(let i of this.links.linksOf.get(t)??[]){if(i.target==="excluded"||i.target==="whole"&&!this.wholeRead.has(i.parent)||!this.requiredHere(i,e)&&this.options.parents!=="all")continue;let a=r[i.field];if(!Pe(a,i))continue;let d=this.rowOf(i.parent,a);d!==void 0&&s.push({row:d,field:i.field})}for(let i of o??[]){if(i.id===null||!this.readable(i.objectApiName))continue;let a=this.rowOf(i.objectApiName,i.id);a!==void 0&&s.push({row:a,field:`(${i.objectApiName})`})}return s}async readUp(){for(;;){for(;this.upCursor<this.rows.length;this.upCursor++){let e=this.upCursor,{named:t,dies:r}=this.requiredOf(e);r&&this.kill(e,r);for(let o of t)this.need(e,o)}if(this.pending.size===0)return;await this.readPending()}}async readOptionalParents(){if(this.options.parents!=="all")return!1;for(;this.optionalCursor<this.upCursor;this.optionalCursor++){let e=this.optionalCursor;if(this.alive(e))for(let t of this.optionalOf(e))this.ask(t)}return this.pending.size===0?!1:(await this.readPending(),!0)}async readDown(){let e=new Map,t=this.toDescend;this.toDescend=[];for(let r of t)if(!(this.descended[r]||!this.alive(r))){this.descended[r]=!0;for(let o of this.links.carriersInto.get(this.objectOf[r])??[]){let s=`${o.objectApiName}.${o.field}`,i=e.get(s);i||(i={masterDetail:o.masterDetail,parents:new Map,objects:new Set},e.set(s,i)),i.objects.add(o.parent),i.parents.set(z(this.rows[r].id),r)}}if(e.size===0)return!1;for(let[r,o]of[...e].sort(([s],[i])=>s<i?-1:1)){let s=r.indexOf("."),i={objectApiName:r.slice(0,s),field:r.slice(s+1),parents:[...o.objects].sort(),masterDetail:o.masterDetail},a=i.masterDetail?"all":this.options.children,d=[...o.parents.values()].map(u=>this.rows[u].id).sort(le);this.checkSignal();let c=await this.reader.children(i,d,a),l=new Map;for(let u of c.rows){let m=u.refs[i.field];if(typeof m!="string"||m==="")continue;let g=o.parents.get(z(m));if(g===void 0)continue;let h=l.get(g)??new Map;h.has(z(u.id))||h.set(z(u.id),u),l.set(g,h)}let f=new Map;for(let[u,m]of c.counts??[])f.set(z(u),m);let p=this.cuts.get(r)??new Map;for(let[u,m]of[...l].sort(([g],[h])=>g-h)){let g=[...m.values()].sort(Lu),h=a==="all"?g:g.slice(0,a),y=this.below.get(u)??[];for(let S of h){let w=this.register(i.objectApiName,S);y.push({child:w,relation:r}),this.descended[w]||this.toDescend.push(w)}this.below.set(u,y);let R=f.get(z(this.rows[u].id))??m.size;R>h.length&&p.set(u,R-h.length)}p.size>0&&this.cuts.set(r,p),this.told()}return!0}need(e,t){let r=this.rowOf(t.objectApiName,t.id);if(r!==void 0){this.tie(r,e);return}if(this.isAbsent(t.objectApiName,t.id)){this.kill(e,"noParentInSource");return}let o=`${t.objectApiName}
|
|
25
|
+
${z(t.id)}`,s=this.waiting.get(o)??[];s.push(e),this.waiting.set(o,s),this.ask(t)}ask(e){if(this.rowOf(e.objectApiName,e.id)!==void 0||this.isAbsent(e.objectApiName,e.id))return;let t=this.pending.get(e.objectApiName)??new Map;t.set(z(e.id),e.id),this.pending.set(e.objectApiName,t)}async readPending(){let e=[...this.pending].sort(([t],[r])=>t<r?-1:1);this.pending.clear();for(let[t,r]of e){let o=[...r.values()].sort(le);this.checkSignal();let s=await this.reader.rows(t,o);for(let i of s)this.register(t,i);this.markAbsent(t,o),this.told()}}markAbsent(e,t){for(let r of t){if(this.rowOf(e,r)!==void 0)continue;let o=this.absent.get(e)??new Set;o.add(z(r)),this.absent.set(e,o);let s=`${e}
|
|
26
|
+
${z(r)}`;for(let i of this.waiting.get(s)??[])this.kill(i,"noParentInSource");this.waiting.delete(s)}}register(e,t){let r=this.index.get(e);r||(r=new Map,this.index.set(e,r));let o=z(t.id),s=r.get(o);if(s!==void 0)return s;let i=this.rows.length;this.rows.push(t),this.objectOf.push(e),this.rootOf.push(-1),this.whole.push(!1),this.dead.push(void 0),this.out.push(!1),this.descended.push(!1),r.set(o,i);let a=this.options.maxRows??Du;if(this.rows.length>a)throw new nr(this.rows.length,a);if(t.outsideFilter)this.out[i]=!0,this.kill(i,"outsideFilter");else if(typeof t.recordTypeId=="string"&&t.recordTypeId!==""){let c=this.options.recordTypeVerdict?.(e,t.recordTypeId);c&&this.kill(i,c)}let d=this.waiting.get(`${e}
|
|
27
|
+
${o}`);if(d){this.waiting.delete(`${e}
|
|
28
|
+
${o}`);for(let c of d)this.tie(i,c)}return i}tie(e,t){let r=this.needs.get(e)??[];r.push(t),this.needs.set(e,r),this.alive(e)||this.kill(t,this.out[e]?"outsideFilter":"withoutParent")}kill(e,t){if(!this.alive(e))return;this.dead[e]=t;let r=[e];for(;r.length>0;){let o=r.pop(),s=this.out[o]?"outsideFilter":"withoutParent";for(let i of this.needs.get(o)??[])this.alive(i)&&(this.dead[i]=s,r.push(i))}}checkSignal(){if(this.options.signal?.aborted)throw new rr}told(){this.options.onRows?.(this.rows.length)}thresholds(e=new Set){let t=this.rows.length,r=new Float64Array(t).fill(1/0),o=new Array(t),s=new Array(t),i=new or;for(let c=0;c<t;c++){let l=this.rootOf[c];l>=0&&!e.has(l)&&(r[c]=l,i.push(l,c))}let a=new Uint8Array(t);for(;i.size>0;){let[c,l]=i.pop();if(!(a[l]||c>r[l]||!this.alive(l))){a[l]=1;for(let{child:f,relation:p}of this.below.get(l)??[])c<r[f]?(r[f]=c,s[f]=p,i.push(c,f)):c===r[f]&&p<(s[f]??"")&&(s[f]=p)}}let d=new Float64Array(r);for(let c=0;c<t;c++)this.whole[c]&&(d[c]=-1),d[c]!==1/0&&i.push(d[c],c),o[c]=s[c];for(a.fill(0);i.size>0;){let[c,l]=i.pop();if(!(a[l]||c>d[l]||!this.alive(l))){a[l]=1;for(let{row:f,field:p}of this.upTargets(l)){let u=`${this.objectOf[l]}.${p}`;c<d[f]?(d[f]=c,o[f]=u,i.push(c,f)):c===d[f]&&o[f]!==void 0&&u<o[f]&&(o[f]=u)}}}return{threshold:d,above:r,via:o}}};var zi={bytes:(n,e)=>e.bytes??ls(n,e.personAccount?{IsPersonAccount:!0}:{}),wholeBytes:(n,e)=>ye(n,{rows:e})},$u=[{objectApiName:oe,field:"AccountId",writes:"AccountContactRelation",ownField:"ContactId",pairField:"AccountId"},{objectApiName:"Opportunity",field:"ContactId",writes:"OpportunityContactRole",ownField:"OpportunityId",pairField:"ContactId"}],Wu=.1,qu=256,zu=5;function sr(n,e){return e<0?-1/0:e===1/0?1/0:n[e].rank}function Ui(n,e){let t=n.rows[e];return t.matched||t.replaced||n.objectOf[e]===oe&&t.personAccount===!0?0:1}function Uu(n,e,t){let r=new Map,{links:o}=n,s=t.filter(i=>o.classes.has(i.writes)&&(o.linksOf.get(i.objectApiName)??[]).some(a=>a.field===i.field));if(s.length===0)return r;for(let i=0;i<n.rows.length;i++)if(n.alive(i))for(let a of s){if(n.objectOf[i]!==a.objectApiName)continue;let d=n.rows[i];if(a.objectApiName===oe&&d.personAccount)continue;let c=d.refs[a.field],l=Us(o,a.objectApiName,a.field,c);if(!l||typeof c!="string")continue;let f=n.rowOf(l.parent,c);if(f===void 0||!n.alive(f))continue;let p=Math.max(e.threshold[i],e.threshold[f]);p!==1/0&&r.set(`${a.writes}
|
|
29
|
+
${z(d.id)}
|
|
30
|
+
${z(c)}`,{objectApiName:a.writes,threshold:p,rows:[]})}for(let i=0;i<n.rows.length;i++)if(n.alive(i))for(let a of s){if(n.objectOf[i]!==a.writes)continue;let{refs:d}=n.rows[i],c=d[a.ownField],l=d[a.pairField];if(typeof c!="string"||typeof l!="string")continue;let f=r.get(`${a.writes}
|
|
31
|
+
${z(c)}
|
|
32
|
+
${z(l)}`);f&&f.rows.push(i)}for(let i of r.values())i.rows.sort((a,d)=>e.threshold[a]-e.threshold[d]||le(n.rows[a].id,n.rows[d].id));return r}function Vu(n,e,t){let{measure:r,draw:o}=t,s=[],i=new Float64Array(n.rows.length),a=new Map,d=(f,p)=>{f>=0&&f!==1/0&&a.set(f,(a.get(f)??0)+p)},c=Uu(n,e,t.platformPairs??$u),l=new Set;for(let f of c.values())f.rows.length>0&&l.add(f.rows[0]);for(let f=0;f<n.rows.length;f++){if(!n.alive(f))continue;let p=n.objectOf[f],u=n.rows[f],m=l.has(f)?0:Ui(n,f),h=(u.matched||u.replaced||l.has(f)?0:r.bytes(p,u))+m*(r.roomBytes?.(p)??0);i[f]=h;let y=e.threshold[f];y!==1/0&&(s.push({rank:sr(o.roots,y),bytes:h,records:m,objectApiName:p}),d(y,h))}for(let f of c.values()){let p=r.bytes(f.objectApiName,{id:"",refs:{}});s.push({rank:sr(o.roots,f.threshold),bytes:p,records:0,objectApiName:f.objectApiName}),d(f.threshold,p)}for(let[f,p]of n.links.classes){if(p.kind!=="whole"||n.wasReadWhole(f))continue;let u=t.sourceRows.get(f)??0,m=p.why==="referenceData",g=m?0:u;s.push({rank:-1/0,bytes:(m?0:r.wholeBytes(f,u))+g*(r.roomBytes?.(f)??0),records:g,objectApiName:f})}return s.sort((f,p)=>f.rank-p.rank),{items:s,rowBytes:i,parts:a,pairs:c}}function Vi(n,e,t){let r=0,o=0,s=new Map;for(let i of n){if(i.rank>e)break;r+=i.bytes,o+=i.records,t&&i.records>0&&s.set(i.objectApiName,(s.get(i.objectApiName)??0)+i.records)}return{bytes:r,records:o,written:s}}function Ut(n,e,t){let r=Vi(n,e,t.requests!==void 0);return r.bytes>t.bytes?vs(r.bytes,t):t.maxTotal!==void 0&&r.records>t.maxTotal?"maxTotal":t.requests?.(r.written)}function Wi(n,e,t){let r=Wu*Math.max(0,e.roomBytes),o=new Set;e.draw.floor>0&&e.draw.roots.forEach((i,a)=>{i.rank===0&&o.add(a)});let s=Gi(n);for(s!==void 0&&o.add(s);;){let i=n.thresholds(t),a=Vu(n,i,e),d=[...a.parts].filter(([c,l])=>l>r&&!t.has(c)&&!o.has(c)).map(([c])=>c);if(d.length===0)return{thresholds:i,weighed:a};for(let c of d)t.add(c)}}function Gi(n){let e;for(let t=0;t<n.rows.length;t++){let r=n.rootOf[t];r>=0&&n.alive(t)&&(e===void 0||r<e)&&(e=r)}return e}function qi(n,e,t,r){let o=Vi(e,t,!1),s=new Map;for(let i of e){if(i.rank>t)break;let a=s.get(i.objectApiName)??{rows:0,storageBytes:0};a.rows+=i.records,a.storageBytes+=i.bytes,s.set(i.objectApiName,a)}return{kind:"cannotFit",limitedBy:Ut(e,t,r)??r.bytesLimit,rows:o.records,storageBytes:o.bytes,heaviest:[...s].sort(([i,a],[d,c])=>c.storageBytes-a.storageBytes||(i<d?-1:i>d?1:0)).slice(0,zu).map(([i,a])=>({objectApiName:i,...a,...n.links.classes.get(i)?.kind==="whole"?{whole:!0}:{}}))}}async function Ji(n){let e=n.draw.roots.filter(c=>c.rank<n.draw.beyond),t={...n,draw:{...n.draw,roots:e}},{bounds:r}=t,o=new zt(t.links,t.reader,{...t.options,onRows:c=>{t.options.onRows?.(c),t.onStep?.("closing",c)}});await o.openWhole();let s=new Set,i=0,a=qu,d=Wi(o,t,s);for(;i<e.length;){let c=Math.min(e.length,i+a);for(;c<e.length&&e[c].rank===e[c-1].rank;)c++;if(await o.addRoots(e.slice(i,c),i),i=c,a*=2,d=Wi(o,t,s),Ut(d.weighed.items,e[i-1].rank,r)!==void 0)break}return t.onStep?.("fitting",o.rows.length),Gu(o,d,s,t,e.slice(0,i),i===e.length)}function Gu(n,e,t,r,o,s){let{bounds:i,draw:a}=r,{items:d}=e.weighed,c=[...new Set(o.map(h=>h.rank))].sort((h,y)=>h-y),l=a.floor>0&&c[0]===0?c:[-1/0,...c],f=Cs(l.length,h=>Ut(d,l[h-1],i)===void 0);if(f===0)return qi(n,d,l[0],i);let p=l[f-1],u=Gi(n);if(u!==void 0&&o[u].rank>p)return{...qi(n,d,o[u].rank,i),noRoot:!0};let m=Hu(n,e,t,r,p),g=f<l.length?Ut(d,l[f],i)??i.bytesLimit:!s||a.beyond!==1/0?a.heldBy:m.heavyRoots.length>0?"heavyRoots":a.restricted===!0?"draw":"whole";return{kind:"sample",share:g==="whole"||g==="heavyRoots"||g==="draw"?1:Math.max(0,p),limitedBy:g,wholeOrgFits:Ju(n,r),...m}}function Ju(n,e){let t=0,r=0,o=new Map;for(let[i,a]of n.links.classes){let d=e.sourceRows.get(i)??0;a.kind==="whole"&&a.why==="referenceData"||(t+=e.measure.wholeBytes(i,d),r+=d,o.set(i,d))}let{bounds:s}=e;return t<=s.bytes&&(s.maxTotal===void 0||r<=s.maxTotal)&&s.requests?.(o)===void 0}function Hu(n,e,t,r,o){let{links:s}=n,{thresholds:i,weighed:a}=e,d=r.draw.roots,c=I=>sr(d,I),l=I=>n.alive(I)&&c(i.threshold[I])<=o,f=I=>{if(n.whole[I])return"whole";let N=n.rootOf[I];return N>=0&&!t.has(N)&&c(N)<=o?"root":c(i.above[I])<=o?"below":"parent"},p=new Map,u=I=>{let N=p.get(I);return N||(N={objectApiName:I,sourceRows:r.sourceRows.get(I)??0,kept:0,roots:0,below:0,asParents:0},s.classes.get(I)?.kind==="whole"&&(N.whole=!0),p.set(I,N)),N},m=new Map,g=new Map,h=new Map,y=new Map,R=new Map,S=new Set;for(let I of a.pairs.values())I.rows.length>0&&S.add(I.rows[0]);let w=0,b=0,A=0,E=I=>r.measure.roomBytes?.(I)??0;for(let I=0;I<n.rows.length;I++){let N=n.objectOf[I];if(!n.alive(I)){let F=n.dead[I];if(n.out[I]||F===void 0||c(i.threshold[I])>o)continue;let k=`${N}
|
|
33
|
+
${F}`,O=y.get(k)??{objectApiName:N,rows:0,reason:F};O.rows++,y.set(k,O);continue}if(!l(I))continue;let _=n.rows[I],D=m.get(N)??[];D.push(_.id),m.set(N,D),b+=a.rowBytes[I];let j=S.has(I)?0:Ui(n,I);if(w+=j,A+=j*E(N),_.personAccount&&(N===ce||N===oe)&&h.set(N,(h.get(N)??0)+1),!_.matched){let F=u(N);F.kept++;let k=f(I);if(k==="root"){F.roots++;let O=g.get(N)??new Set;O.add(z(_.id)),g.set(N,O)}else k==="below"?F.below++:k==="parent"&&F.asParents++}for(let F of s.linksOf.get(N)??[]){if(F.target==="excluded"||F.target==="whole"&&!n.wasReadWhole(F.parent))continue;let k=_.refs[F.field];if(!Pe(k,F))continue;let O=n.rowOf(F.parent,k);if(O!==void 0&&l(O))continue;let C=`${N}
|
|
34
|
+
${F.field}`,B=R.get(C)??{objectApiName:N,field:F.field,rows:0};B.rows++,R.set(C,B)}}for(let[I,N]of s.classes){if(N.kind!=="whole"||n.wasReadWhole(I))continue;let _=r.sourceRows.get(I)??0,D=u(I);D.kept=_,N.why!=="referenceData"&&(w+=_,b+=r.measure.wholeBytes(I,_)+_*E(I),A+=_*E(I))}let x=new Map;for(let I of a.pairs.values()){if(c(I.threshold)>o)continue;let N=x.get(I.objectApiName)??{objectApiName:I.objectApiName,inPlan:0,beyond:0};I.rows.length>0&&l(I.rows[0])?N.inPlan++:N.beyond++,b+=r.measure.bytes(I.objectApiName,{id:"",refs:{}}),x.set(I.objectApiName,N)}for(let[I,N]of n.cut){let _=0;for(let[F,k]of N)l(F)&&c(i.above[F])<=o&&(_+=k);if(_===0)continue;let D=I.indexOf("."),j=u(I.slice(0,D));j.childrenCut=[...j.childrenCut??[],{field:I.slice(D+1),rows:_}]}let T=[...p.values()].filter(I=>I.kept>0).sort((I,N)=>N.kept-I.kept||(I.objectApiName<N.objectApiName?-1:1)),v=[...s.classes].filter(([I,N])=>{let _=r.sourceRows.get(I)??0;return N.kind==="drawn"&&_>0&&(p.get(I)?.kept??0)===0}).map(([I])=>({objectApiName:I,sourceRows:r.sourceRows.get(I)??0})).sort((I,N)=>I.objectApiName<N.objectApiName?-1:1);return{rows:T.reduce((I,N)=>I+N.kept,0),storageBytes:b,automationBytes:A,written:w,objects:T,heavyRoots:Yu(n,e,t,d,o),dropped:[...y.values()].sort(ir(I=>I.reason)),leftEmpty:[...R.values()].sort(ir(I=>I.field)),noRecordDrawn:v,partialMasters:Ku(s,p,r.sourceRows),ids:new Map([...m].map(([I,N])=>[I,N.sort(le)])),rootIds:g,personAccounts:h,byThePlatform:[...x.values()].sort((I,N)=>I.objectApiName<N.objectApiName?-1:1)}}function Ku(n,e,t){let r=[];for(let[o,s]of n.linksOf){if(n.classes.get(o)?.kind!=="drawn")continue;let i=e.get(o)?.kept??0;for(let a of s){if(!a.masterDetail||a.target==="excluded"||a.parent===o)continue;let d=e.get(a.parent);if(!d||d.kept===0)continue;let c={objectApiName:a.parent,details:o,field:a.field};if(a.target==="whole"){let l=t.get(o)??0;i<l&&r.push({...c,kept:i,sourceRows:l})}else a.carries&&d.asParents>0&&r.push({...c,asParents:d.asParents})}}return r.sort(ir(o=>`${o.details}
|
|
35
|
+
${o.field}`))}function ir(n){return(e,t)=>{if(e.objectApiName!==t.objectApiName)return e.objectApiName<t.objectApiName?-1:1;let r=n(e),o=n(t);return r<o?-1:r>o?1:0}}function Yu(n,e,t,r,o){let s=[...t].filter(a=>r[a].rank<=o).sort((a,d)=>a-d);if(s.length===0)return[];let i=[];for(let a of s){let d=new Set(t);d.delete(a);let c=n.thresholds(d),l=0,f=new Map;for(let m=0;m<n.rows.length;m++){if(!n.alive(m)||c.threshold[m]!==a)continue;l++;let g=c.via[m];g!==void 0&&f.set(g,(f.get(g)??0)+e.weighed.rowBytes[m])}let[p]=[...f].sort(([m,g],[h,y])=>y-g||(m<h?-1:m>h?1:0))[0]??[`${r[a].objectApiName}.Id`],u=p.indexOf(".");i.push({objectApiName:r[a].objectApiName,id:r[a].id,rows:l,relation:{objectApiName:p.slice(0,u),field:p.slice(u+1)}})}return i}var Hi=50;function ar(n){return n===null?"none":typeof n=="boolean"?n?"true":"false":`=${n}`}function Ki(n,e){return(n+.5)/Math.max(e,n+1)}function Yi(n,e,t){let r=n.reduce((s,i)=>s+Math.max(0,i),0),o=Math.max(0,e)+n.length;return n.map(s=>s<=0?0:Math.min(s,Math.ceil(o*s/r)+1+Math.max(0,t)))}var Vt=class{constructor(e){this.input=e;for(let t of e.strata){let r=ar(t.value),o=this.strata.get(r);if(o){o.counted+=Math.max(0,t.roots),o.take+=Math.max(0,t.take);continue}this.strata.set(r,{key:r,value:t.value,counted:Math.max(0,t.roots),scanned:0,take:Math.max(0,t.take),heap:new On,read:[]})}}input;strata=new Map;get objectApiName(){return this.input.objectApiName}get field(){return this.input.field}reads(){return[...this.strata.values()].filter(e=>e.take>0).sort((e,t)=>e.key<t.key?-1:e.key>t.key?1:0).map(e=>({value:e.value,key:e.key,roots:e.counted,take:e.take}))}scanned(e,t){let r=ar(t),o=this.strata.get(r);o||(o={key:r,value:t,counted:0,scanned:0,take:Math.max(0,this.input.floor)+2,heap:new On,read:[]},this.strata.set(r,o)),o.scanned++,o.heap.push({objectApiName:this.input.objectApiName,id:e,rank:Nt(this.input.seed,e)}),o.heap.size>o.take&&o.heap.pop()}read(e,t){let r=this.strata.get(ar(e));if(!r)throw new Error(`${this.input.objectApiName}.${this.input.field} was not counted with that value: its roots are not read.`);r.read.push(...t)}rootsOf(e){return this.input.draw==="uniform"?e.scanned:e.counted}orderOf(e){return this.input.draw!=="uniform"?e.read:[...e.heap.values()].sort(os).map(t=>t.id)}ranked(){let e=[];for(let t of this.strata.values()){let r=this.rootsOf(t);this.orderOf(t).forEach((o,s)=>{e.push({id:o,rank:Ki(s,r),stratum:t.key})})}return e}get firstUnread(){let e=1/0;for(let t of this.strata.values()){let r=this.input.draw==="uniform";if(!(r?t.scanned>t.take:t.read.length>=t.take&&t.take<t.counted))continue;let s=r?t.take:t.read.length;e=Math.min(e,Ki(s,this.rootsOf(t)))}return e}report(e,t){let r=[...this.strata.values()].map(s=>{let i=t?.(s.value);return{key:s.key,entry:{value:s.value,...i!==void 0?{label:i}:{},roots:this.rootsOf(s),kept:this.orderOf(s).filter(a=>e(a)).length}}}).sort((s,i)=>s.entry.roots!==i.entry.roots?i.entry.roots-s.entry.roots:s.key<i.key?-1:s.key>i.key?1:0),o=r.length-Hi;return{objectApiName:this.input.objectApiName,field:this.input.field,values:r.slice(0,Hi).map(s=>s.entry),...o>0?{more:o}:{}}}};var Zi=class extends Error{constructor(t,r,o){super(r);this.code=t;this.heaviest=o;this.name="SampleRefusedError"}code;heaviest},dr=[gt,Ce,wt,ht,"IsActive"];function Qi(n){return n===!0||n==="true"}function Gt(n){return typeof n=="string"&&n!==""?n:null}function Zu(n){let e=n.CreatedDate,t=typeof e=="string"?Date.parse(e):Number.NaN;return Number.isFinite(t)?t:void 0}function Xi(n){let e=t=>{let r=n[t];return typeof r=="string"?z(r):""};return[e(gt),e(Ce),e(ht)].join(`
|
|
36
|
+
`)}function ea(n){let e=t=>{let r=n[t];return typeof r=="string"?r:""};return[z(e(Ce)),e(wt),z(e(ht))].join(`
|
|
37
|
+
`)}var cr=class{constructor(e,t,r,o){this.reader=e;this.links=t;this.sourceRows=r;this.priceCurrencyWrittenIn=o}reader;links;sourceRows;priceCurrencyWrittenIn;cappedByIds=new Set;columnsOf(e){let t=[...vn(this.links,e),"RecordTypeId"];return(e===ce||e===oe)&&t.push("IsPersonAccount"),e===Xe&&t.push(...dr),e===un&&t.push("IsStandard"),t}rowOf(e,t,r=!1){let o={};for(let a of vn(this.links,e))o[a]=Gt(t[a]);let s=t.RecordTypeId,i=Zu(t);return{id:String(t.Id),refs:o,...typeof s=="string"||s===null?{recordTypeId:Gt(s)}:{},...(e===ce||e===oe)&&Qi(t.IsPersonAccount)?{personAccount:!0}:{},...e===un&&Qi(t.IsStandard)?{matched:!0}:{},...r?{outsideFilter:!0}:{},...i!==void 0?{created:i}:{}}}async sampleRowsOf(e,t,r=[]){let o=[...t.map(l=>this.rowOf(e,l)),...r.map(l=>this.rowOf(e,l,!0))];if(e!==Xe||t.length===0)return o;let s=[...new Set(t.flatMap(l=>{let f=Gt(l[Ce]);return f?[f]:[]}))],i=await this.reader.readStandardPrices(s,dr.slice(1)),a=new Set(i.map(l=>z(String(l.Id)))),d=new Map;for(let l of i)d.set(ea(l),String(l.Id));let c=await this.pricesWrittenFor(t);return o.map((l,f)=>{let p=t[f];if(p===void 0)return l;let u=[];a.has(z(l.id))||u.push({objectApiName:Xe,id:d.get(ea(p))??null});let m=c.get(l.id);return m!==void 0&&u.push({objectApiName:Xe,id:m}),u.length===0?l:{...l,also:u,...m!==void 0?{replaced:!0}:{}}})}async pricesWrittenFor(e){let t=new Map,r=this.priceCurrencyWrittenIn;if(!r)return t;let o=new Map;for(let s of e){let i=s[wt];if(typeof i!="string")continue;let a=r(i);a===void 0||a===i||o.set(a,[...o.get(a)??[],s])}for(let[s,i]of o){let a=l=>i.flatMap(f=>{let p=Gt(f[l]);return p?[p]:[]}),d=await this.reader.readPricesIn(s,a(Ce),a(gt),dr),c=new Map(d.map(l=>[Xi(l),String(l.Id)]));for(let l of i){let f=c.get(Xi(l));f!==void 0&&t.set(String(l.Id),f)}}return t}async rows(e,t){let[r]=await this.reader.readParents([{objectApiName:e,ids:t,columns:this.columnsOf(e)}]);return r?this.sampleRowsOf(e,r.rows,r.outsideFilter):[]}async children(e,t,r){let[o]=await this.reader.readChildren([{objectApiName:e.objectApiName,field:e.field,parentIds:t,columns:this.columnsOf(e.objectApiName),cap:r,sourceRows:this.sourceRows.get(e.objectApiName)??Number.MAX_SAFE_INTEGER}]);return o?(o.newestBy==="id"&&o.cut.some(s=>s.rows>0)&&this.cappedByIds.add(e.objectApiName),{rows:await this.sampleRowsOf(e.objectApiName,o.rows),counts:o.counts}):{rows:[]}}async whole(e){let t=[];return await this.reader.readWhole([{objectApiName:e,columns:this.columnsOf(e)}],(r,o)=>{for(let s of o)t.push(s)}),this.sampleRowsOf(e,t)}};function Qu(n,e){let{empty:t,told:r}=zs(n,e),o=n.linksOf.get(e)??[];return[...t.map(s=>({field:s})),...r.map(s=>({field:s,drawnPrefixes:new Set(o.flatMap(i=>i.field===s&&i.carries&&typeof i.prefix=="string"?[i.prefix]:[]))}))]}function Xu(n){let e=n.field==="LastModifiedDate"?"last modified":"made";if(n.lastDays!==void 0)return`roots ${e} in the last ${n.lastDays} days`+(n.from!==void 0?`, from ${n.from}`:"");let t=n.from!==void 0?` from ${n.from}`:"",r=n.to!==void 0?` to before ${n.to}`:"";return`roots ${e}${t}${r}`}function el(n,e,t){let r=[...n.window?[Xu(n.window)]:[],...n.where.map(({objectApiName:i,where:a})=>`${i} where ${a}`)],o=e.filter(i=>(i.inTheSource?.rows??0)>0).map(i=>`${i.objectApiName} ${i.inTheSource?.exact===!1?"at most ":""}${i.inTheSource?.rows??0}`),s=[...n.window?["widen the window (--fit-window)"]:[],...n.where.length>0?["loosen the filters on the roots (--fit-where)"]:[],"draw without them"].join(", or ");return new me("SAMPLE_DRAW_EMPTY",`No object has a root in the draw: ${r.join("; ")}.`+(n.notWindowed.length>0?` The window does not date ${n.notWindowed.join(", ")}, which have no root in it.`:"")+(o.length>0?` The source holds roots outside them: ${o.join(", ")}.`:"")+` Nothing was written, and the counts sent ${t} request(s) of the source. ${s.charAt(0).toUpperCase()}${s.slice(1)}.`,void 0,void 0,void 0,{sample:{requests:t}})}function tl(n,e){let t=e.restricted?"narrow the window or the filters on the roots (--fit-window, --fit-where)":"draw among fewer roots (--fit-window, --fit-where)";return n==="uniform"?`Draw the most recent records (--fit-draw recent) or the oldest (--fit-draw oldest), ${t}, or narrow the large objects (--filter).`:`${t.charAt(0).toUpperCase()}${t.slice(1)}`+(e.stratified?", stratify fewer objects (--fit-strata)":"")+", narrow the large objects (--filter), or draw it once the source has more to spare."}async function Vg(n){let{options:e,budget:t}=n,r=k=>n.averageBytes?.get(k),o=(k,O)=>{let C=r(k);return C!==void 0?O*C:ye(k,{rows:O})},s=new Map(n.objects.flatMap(k=>k.rows===void 0?[]:[[k.objectApiName,k.rows]])),i=vt({objects:n.objects,order:n.order,...n.excluded?{excluded:n.excluded}:{},...n.referenceData?{referenceData:n.referenceData}:{},...e.whole?{whole:e.whole}:{},roomBytes:t.roomBytes,...n.maxRecordsPerObject!==void 0?{maxRecordsPerObject:n.maxRecordsPerObject}:{},wholeBytes:(k,O)=>o(k,O)}),a=Bi({options:{...e.window?{window:e.window}:{},...e.rootWhere?{rootWhere:e.rootWhere}:{},...e.strata?{strata:e.strata}:{}},now:n.now??Date.now(),links:i,...n.excluded?{excluded:n.excluded.keys()}:{},fieldsOf:k=>n.fieldsOf(k),...n.filterOf?{filterOf:n.filterOf}:{}}),d=(k,O)=>n.fieldsOf(k)?.find(C=>C.name.toLowerCase()===O.toLowerCase()),c=new xt(n.source,{fieldsOf:k=>n.fieldsOf(k)?.map(O=>O.name),...n.filterOf?{filterOf:n.filterOf}:{},countsBy:(k,O)=>{let C=d(k,"Id")?.aggregatable,B=d(k,O)?.groupable;return C===!1||B===!1?!1:C===!0&&B===!0?!0:void 0},sorts:(k,O)=>d(k,O)?.sortable,...n.onProgress?{onProgress:n.onProgress}:{},...n.signal?{signal:n.signal}:{}}),l=[...i.classes].filter(([,k])=>k.kind==="drawn"&&k.rooted).map(([k])=>k).sort(),f=l.filter(k=>a.objects.get(k)?.notWindowed!==!0).map(k=>{let O=a.objects.get(k);return{objectApiName:k,carriers:Qu(i,k),...O?.window?{window:O.window}:{},...O?.where!==void 0?{where:O.where}:{},...O?.stratifiedBy!==void 0?{stratifiedBy:O.stratifiedBy}:{}}}),p=await c.countRoots(f),u=Et(t.budget.bytes,t.budget.maxTotal),m=new Map;p.forEach((k,O)=>{let C=f[O].stratifiedBy;if(C===void 0||!k.strata)return;let B=Yi(k.strata.map(P=>P.rows),u,e.floor);m.set(k.objectApiName,new Vt({objectApiName:k.objectApiName,field:C,strata:k.strata.map((P,L)=>({value:P.value,roots:P.rows,take:B[L]})),draw:e.draw,seed:e.seed,floor:e.floor}))});let g=k=>m.get(k.objectApiName)?.reads()??Math.min(k.rows,u),h=p.reduce((k,O)=>k+Mt(O,e.draw,g(O)),0),y=n.sourceRequestsLeft;if(y!==void 0&&c.requests+h>Math.floor(be*y)){let k=c.requests+h;throw new me(ps,`Drawing the sample reads about ${k} requests of the source, more than a tenth of the ${y} it has left today. Nothing was written, and no id was read past the counts. ${tl(e.draw,a)}`,void 0,void 0,void 0,{api:{kind:"requests",org:"source",estimate:k,remaining:y,drawing:{share:be,draw:e.draw,...a.restricted?{restricted:!0}:{}}}})}let R=new ss(u,e.floor),S=[],w=new Map,b=new Map;if(e.draw==="uniform")await c.drawUniform(f,(k,O,C)=>{w.set(k,(w.get(k)??0)+O.length);let B=m.get(k);if(B){for(let P of O)B.scanned(P,C??null);return}for(let P of O)R.offer(k,P,Nt(e.seed,P))});else{let k=new Map(p.map(C=>[C.objectApiName,C.rows]));S=(await c.drawByDate(p.map((C,B)=>({...f[B],take:g(C)})),e.draw,(C,B,P)=>{let L=m.get(C);if(L){L.read(P??null,B);return}let M=b.get(C)??0;for(let $ of B)R.offer(C,$,Sn(M,k.get(C)??0)),M++;b.set(C,M)})).filter(C=>C.by==="id").map(C=>C.objectApiName);for(let C of p){if(m.has(C.objectApiName))continue;let B=Math.min(C.rows,u);B<C.rows&&(b.get(C.objectApiName)??0)>=B&&R.leftUnread(Sn(B,C.rows))}}for(let k of m.values()){for(let O of k.ranked())R.offer(k.objectApiName,O.id,O.rank,O.stratum);R.leftUnread(k.firstUnread)}let A=R.drawn();if(a.restricted&&A.length===0)throw el(a,p,c.requests);let{maxTotal:E}=t.budget,x=E!==void 0&&E<Math.floor(t.budget.bytes/rs)?"maxTotal":t.bytesLimit,T=new cr(c,i,s,n.priceCurrencyWrittenIn),v=await Ji({links:i,reader:T,draw:{roots:A,beyond:R.beyond,heldBy:x,floor:e.floor,...a.restricted?{restricted:!0}:{}},sourceRows:s,options:{parents:e.parents,children:e.children,...n.recordTypeVerdict?{recordTypeVerdict:n.recordTypeVerdict}:{},...n.maxRows!==void 0?{maxRows:n.maxRows}:{},...n.signal?{signal:n.signal}:{}},measure:{bytes:(k,O)=>O.bytes??r(k)??zi.bytes(k,O),wholeBytes:o,...t.automationBytes?{roomBytes:t.automationBytes}:{}},bounds:{bytes:t.budget.bytes,bytesLimit:t.bytesLimit,...t.storageBytes!==void 0?{storageBytes:t.storageBytes}:{},...E!==void 0?{maxTotal:E}:{},...t.requests?{requests:t.requests}:{}},roomBytes:t.roomBytes,onStep:(k,O)=>n.onProgress?.({step:k,rows:O,requests:c.requests})}),I=[...new Set([...e.draw==="recent"?S:[],...T.cappedByIds])].sort(),N=e.draw==="oldest"?[...S].sort():[],_=new Map,D=new Set;for(let k of l){let O=a.objects.get(k);if(!O||O.window===void 0&&O.where===void 0&&!O.notWindowed)continue;let C=p.find(M=>M.objectApiName===k),B=M=>{let $=b.get(k)??0;return!m.has(k)&&$<Math.min(M.rows,u)?$:void 0},P=O.notWindowed||!C?0:e.draw==="uniform"?w.get(k)??0:C.exact&&C.timedOut!==!0?C.rows:B(C),L=C?.inTheSource?.exact===!0?C.inTheSource.rows:void 0;_.set(k,{...P!==void 0?{inTheDraw:P}:{},...L!==void 0?{inTheSource:L}:{}}),P===0&&(O.notWindowed||(L??C?.inTheSource?.rows??0)>0)&&D.add(k)}let j;if(a.restricted||a.stratified){let k=[];for(let O of m.values()){let C=v.kind==="sample"?v.rootIds.get(O.objectApiName):void 0,B=await n.labelsOf?.(O.objectApiName,O.field);k.push(O.report(P=>C?.has(z(P))===!0,B))}j={...$i(a),...k.length>0?{strata:k}:{}}}let F;if(e.floor>0&&m.size>0){let k=0,O=0;for(let C of m.values())for(let B of C.reads())k++,O+=Math.min(B.roots,e.floor);k>0&&(F={roots:O,values:k})}return{links:i,cut:v,planRequests:c.requests,newestByIds:I,oldestByIds:N,...j?{roots:j}:{},rootsCounted:_,noRootInTheDraw:D,...F?{strataFloors:F}:{}}}function ta(n){if(!n)return;let e=(n.where??[]).map(o=>o.objectApiName),t=(n.strata??[]).map(o=>`${o.objectApiName}.${o.field}`),r={...n.window?{window:{...n.window}}:{},...e.length>0?{whereObjects:e}:{},...t.length>0?{strataFields:t}:{}};return Object.keys(r).length>0?r:void 0}function Gg(n,e,t){let{cut:r,links:o}=n;return{seed:e.seed,draw:e.draw,floor:e.floor,parents:e.parents,children:e.children,share:r.share,budget:{...t,...r.automationBytes>0?{automationMB:r.automationBytes/1048576}:{},limitedBy:r.limitedBy},rows:r.rows,storageBytes:r.storageBytes,objects:r.objects.map(s=>{let i=n.rootsCounted.get(s.objectApiName);return i?{...s,...i.inTheSource!==void 0?{rootsInTheSource:i.inTheSource}:{},...i.inTheDraw!==void 0?{rootsInTheDraw:i.inTheDraw}:{}}:s}),whole:o.whole,heavyRoots:r.heavyRoots,dropped:r.dropped,leftEmpty:r.leftEmpty,noRecordDrawn:r.noRecordDrawn.map(s=>n.noRootInTheDraw.has(s.objectApiName)?{...s,noRootInTheDraw:!0}:s),...n.roots?{roots:n.roots}:{},...r.partialMasters.length>0?{partialMasters:r.partialMasters}:{},planRequests:{source:n.planRequests},...n.newestByIds.length>0?{newestByIds:[...n.newestByIds]}:{},...n.oldestByIds.length>0?{oldestByIds:[...n.oldestByIds]}:{}}}var nl=30*6e4,rl=16,ol=["map_value","leave_empty","set_default","truncate","map_record_type","exclude_object","skip_rows","ignore"];function Yg(n,e){return JSON.stringify([e.sourceOrgId,e.targetOrgId,e.inputMode,e.recordId??null,e.soqlQuery??null,e.templateId??null,e.aiPrompt??null,n.nodes.map(t=>t.objectApiName).sort(),...e.queryScope==="records"?["records"]:[]])}var na=class{tried=new Map;note(e,t,r=Date.now()){let o=this.tried.get(t)??{};this.tried.delete(t),this.tried.set(t,{...o,[e]:r});for(let s of this.tried.keys()){if(this.tried.size<=rl)break;this.tried.delete(s)}}before(e,t=Date.now()){let r=this.tried.get(e),o=a=>a===void 0||t-a>nl||t<a?void 0:Math.max(1,Math.ceil((t-a)/6e4)),s=o(r?.simulation),i=o(r?.rehearsal);return{...s!==void 0?{simulatedMinutesBefore:s}:{},...i!==void 0?{rehearsedMinutesBefore:i}:{}}}};function sl(n){let e={flow:0,trigger:0,process:0,workflowRule:0,unread:[]};if(!("automation"in n))return{...e,unread:["automation"]};for(let t of Os(n.automation))e[t.kind]++;return e.unread=ks(n.automation).map(t=>t.part),e}function il(n,e){let t={flow:0,trigger:0,process:0,workflowRule:0};if(!("automation"in n))return t;let r=e.map(o=>o.objectApiName);for(let o of As(n.automation,r))t[o.kind]++;return t}function al(n,e=[]){let t=new Map,r=(i,a)=>{a>0&&t.set(i,(t.get(i)??0)+a)},o=n.picklistValueMappings??[];r("map_value",o.filter(i=>i.to!==null).length),r("leave_empty",o.filter(i=>i.to===null).length),r("leave_empty",Object.values(n.fieldExclusions??{}).reduce((i,a)=>i+a.length,0)),r("set_default",n.defaultValues?.length??0),r("truncate",n.truncateFields?.length??0),r("map_record_type",n.recordTypeMappings?.length??0),r("exclude_object",n.excludedObjects?.length??0),r("skip_rows",n.skippedRows?.length??0),r("ignore",n.ignoredGaps?.length??0);let s=new Map;for(let i of e)s.set(i.kind,(s.get(i.kind)??0)+i.rows);return ol.filter(i=>t.has(i)||s.has(i)).map(i=>({kind:i,count:t.get(i)??0,...s.has(i)?{rows:s.get(i)}:{}}))}function dl(n){let e=n.objects.reduce((r,o)=>r+o.sourceRows,0)+n.noRecordDrawn.reduce((r,o)=>r+o.sourceRows,0),t=ta(n.roots);return{module:"forge",share:n.share,...n.budget.withinMB!==void 0?{withinMB:n.budget.withinMB}:{},seed:n.seed,draw:n.draw,limitedBy:n.budget.limitedBy,...t?{roots:t}:{},kept:n.rows,inSource:e}}var ra=class{constructor(e,t){this.config=e;this.before=t}config;before;confirmed=[];fired;firedOnUpdate;deliverability;sampleFit;automationRead(e,t=[]){this.fired=sl(e),this.firedOnUpdate=il(e,t)}emailsRead(e){this.deliverability=e}confirm(e){this.confirmed.includes(e)||this.confirmed.push(e)}sampled(e){this.sampleFit=dl(e)}fit(){return this.sampleFit?{...this.sampleFit}:void 0}context(e){let t=al(this.config,e);return{anonymized:this.config.anonymizePII,...this.config.anonymizePII&&this.config.anonymizationMode==="everything"?{anonymizationMode:"everything"}:{},contactPoints:this.config.keepContactPoints===!0?"kept":"neutralized",...this.before,...this.fired?{firedOnInsert:{...this.fired,unread:[...this.fired.unread]}}:{},...this.firedOnUpdate?{firedOnUpdate:{...this.firedOnUpdate}}:{},...this.confirmed.length>0?{confirmed:[...this.confirmed]}:{},...t.length>0?{decisions:t}:{},...this.deliverability!==void 0?{deliverability:this.deliverability}:{}}}};function Jt(n){return n.toLowerCase()}function Qg(n,e,t){let r=new Set(e.objects.filter(({rows:s})=>s>0).map(({objectApiName:s})=>Jt(s))),o=new Set;for(let{objectApiName:s,leftOut:i}of n)((i?.byThePlatform??0)>0||(i?.linkedByValue?.rows??0)>0)&&r.add(Jt(s)),(i?.writtenBefore??0)>0&&o.add(Jt(s));return(s,i)=>{if(!t(s,i))return!1;let a=Jt(s);return r.has(a)||i==="update"&&o.has(a)}}var cl=V({...$o,journalId:W().min(1).max(200),ranFrom:ve(["commandLine","editor"]),target:W().min(1).max(255).optional(),resumes:Ke().optional(),removes:Ke().optional()}),oa=Wo(n=>{let e=cl.safeParse(n);return e.success?e.data:void 0});function sa(n){return`${n.replace(/\.ndjson$/,"")}.lock`}function ia({version:n,token:e,...t}){return t}function th(n,e,t={}){let r=oa.acquire(sa(n),o=>({...o,journalId:e.journalId.slice(0,200),ranFrom:e.ranFrom,...e.target!==void 0&&e.target!==""?{target:e.target.slice(0,255)}:{},...e.resumes?{resumes:!0}:{},...e.removes?{removes:!0}:{}}),t);return"busy"in r?{busy:ia(r.busy)}:r}function nh(n,e={}){let t=oa.holder(sa(n),e);return t!==void 0?ia(t):void 0}function rh(n){let e=n.ranFrom==="commandLine"?"from the command line":"in VS Code";if(n.removes){let o=n.target!==void 0?` from ${n.target}`:"";return`a removal of the run ${n.journalId} deletes what it wrote${o}: started ${e} at ${n.acquiredAt} (process ${n.pid} on ${n.host})`}let t=n.target!==void 0?` to ${n.target}`:"",r=n.resumes?", taking up an earlier part of it":"";return`the run ${n.journalId} still writes this journal: started ${e}${t} at ${n.acquiredAt} (process ${n.pid} on ${n.host})${r}`}function oh(n){return n.removes&&n.ranFrom==="editor"?"let it end on the Forge page that removes it":n.ranFrom==="commandLine"?"stop it with Ctrl-C in the terminal it runs in, or let it end":"stop it on the Forge page that runs it, or let it end"}var ul="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ll="RHZ",fl=/[A-Za-z0-9]{3}RHZ[A-Za-z0-9]{12}/g,ur="000",aa=62**8;function Ht(n,e){let t=n!==null&&/^[A-Za-z0-9]{3}$/.test(n)?n:ur,r="";for(let s=e;r.length===0||s>0;s=Math.floor(s/62))r=ul[s%62]+r;let o=Rt(`${t}${ll}${r.padStart(9,"0")}`);if(o===void 0)throw new Error(`No placeholder id for record ${e}`);return o}var Kt=class{constructor(e,t){this.keyPrefixOf=e;this.runningUser=t}keyPrefixOf;runningUser;rows=[];updated=[];byId=new Map;personContacts=new Map;platformTeam=new Map;platformRoles=new Map;prefixes=new Map;writesAs;insertRecords=async(e,t,r)=>{let o=await this.prefixOf(t);return r.map(s=>{let i=this.rows.length,a={seq:i,objectApiName:t,fields:{...s},placeholderId:Ht(o,i)};return this.rows.push(a),this.byId.set(a.placeholderId.slice(0,15),a),{id:a.placeholderId,success:!0,errors:[]}})};get updates(){return this.updated.length}updateRecords=async(e,t,r)=>r.map(o=>{let s=typeof o.Id=="string"?o.Id:"",i={};for(let[a,d]of Object.entries(o))a!=="Id"&&a!=="attributes"&&(i[a]=d);return this.updated.push({seq:this.updated.length,objectApiName:t,recordId:s,fields:i}),{id:s,success:!0,errors:[]}});rowOf(e){if(!(typeof e!="string"||e.length!==15&&e.length!==18))return this.byId.get(e.slice(0,15))}personContactOf(e){if(!(typeof e!="string"||e.length!==15&&e.length!==18))return this.personContacts.get(e.slice(0,15))}guardQueries(e){return async(t,r,o)=>{let s=zr(r);if(s)return this.personContactsOf(s,c=>e(t,qr(c),o));let i=Xr(r);if(i)return this.ownersOf(i,c=>e(t,Qr(c),o));let a=to(r);if(a)return this.teamOf(a,c=>e(t,eo(a.objectApiName,a.fields,c)),()=>e(t,Zr));let d=Hr(r);return d?this.rolesOf(d,c=>e(t,Jr(c,d.fields),o)):this.namesAPlaceholder(r)?[]:e(t,r,o)}}async rolesOf(e,t){let r=e.opportunities.filter(d=>!this.rowOf(d)),o=r.length>0?await t(r):[],s=e.opportunities.flatMap(d=>{let c=this.rowOf(d),l=c?.objectApiName==="Opportunity"?c.fields[pn]:void 0;return c&&typeof l=="string"&&l!==""?[{id:d,row:c,contact:l}]:[]});if(s.length===0)return o;let i=await this.prefixOf(Gr),a=new Date().toISOString();return[...o,...s.map(({id:d,row:c,contact:l})=>{let f=Ht(i,aa+this.platformTeam.size+this.platformRoles.size);return this.platformRoles.set(f.slice(0,15),c),Kr({...Object.fromEntries(e.fields.map(p=>[p,null])),Id:f,OpportunityId:d,[pn]:l,...e.fields.includes("IsPrimary")?{IsPrimary:!0}:{}},a)})]}async ownersOf(e,t){let r=e.filter(i=>!this.rowOf(i)),o=r.length>0?await t(r):[],s=[];for(let i of e){let a=await this.ownerOf(i);a!==void 0&&s.push({Id:i,OwnerId:a})}return[...o,...s]}async teamOf(e,t,r){let{objectApiName:o,fields:s,opportunities:i}=e,a=i.filter(h=>!this.rowOf(h)),d=a.length>0?await t(a):[],c=i.filter(h=>this.rowOf(h)?.objectApiName==="Opportunity");if(c.length===0)return d;let l=Vr[o],f=o===fn,p=f?(await r()).flatMap(h=>typeof h.Id=="string"&&(h.IsTotalValidated===!0||h.IsTotalValidated==="true")?[h.Id]:[]):[void 0],u=await this.prefixOf(f?fn:Ur),m=Yr[o]??{},g=[];for(let h of c){let y=await this.ownerOf(h);if(y!==void 0)for(let R of p){let S=Ht(u,aa+this.platformTeam.size+this.platformRoles.size);this.platformTeam.set(S.slice(0,15),this.rowOf(h)),g.push({Id:S,OpportunityId:h,[l]:y,...R!==void 0?{SplitTypeId:R}:{},...Object.fromEntries(s.map(w=>[w,m[w]??null]))})}}return[...d,...g]}async ownerOf(e){let t=this.rowOf(e);if(t?.objectApiName!=="Opportunity")return;let r=t.fields.OwnerId;return typeof r=="string"&&r!==""?r:(this.writesAs??=this.runningUser?this.runningUser().catch(()=>{}):Promise.resolve(void 0),this.writesAs)}async personContactsOf(e,t){let r=e.filter(a=>!this.rowOf(a)),o=r.length>0?await t(r):[],s=e.flatMap(a=>this.rowOf(a)?.objectApiName===ce?[a]:[]);if(s.length===0)return o;let i=await this.prefixOf(oe);return[...o,...s.map(a=>{let d=this.rowOf(a);if("Name"in d.fields)return{Id:a,[Me]:null};let c=Ht(i,d.seq);return this.personContacts.set(c.slice(0,15),d),{Id:a,[Me]:c}})]}namesAPlaceholder(e){for(let[t]of e.matchAll(fl))if(this.rowOf(t)||this.personContactOf(t)||this.platformTeam.has(t.slice(0,15))||this.platformRoles.has(t.slice(0,15)))return!0;return!1}prefixOf(e){let t=this.prefixes.get(e);return t||(t=this.keyPrefixOf(e).catch(()=>null),this.prefixes.set(e,t)),t}};function dh(n,e){return{queryRecords:e.guardQueries(n.queryRecords),describeFields:n.describeFields,isObjectCreatable:n.isObjectCreatable,describeObject:n.describeObject,recordTypePicklists:n.recordTypePicklists,batchStrategy:n.batchStrategy,anonymize:n.anonymize,requestsSent:n.requestsSent,insertRecords:e.insertRecords,updateRecords:e.updateRecords}}var ua="UNKNOWN_ERROR",la="INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST",pl=new Set(["STRING_TOO_LONG","INVALID_EMAIL_ADDRESS","INVALID_TYPE_ON_FIELD_IN_RECORD","NUMBER_OUTSIDE_VALID_RANGE","MALFORMED_ID","INVALID_ID_FIELD","DUPLICATE_VALUE"]),da=new Set(["FIELD_CUSTOM_VALIDATION_EXCEPTION","INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST","FIELD_FILTER_VALIDATION_EXCEPTION"]),ml=new Map([["REQUIRED_FIELD_MISSING",{kind:"required_field_missing",severity:"blocking",decisions:["set_default","exclude_object"]}],["INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST",{kind:"picklist_value_refused",severity:"warning",decisions:["map_value","leave_empty","ignore"]}],["STRING_TOO_LONG",{kind:"value_too_long",severity:"blocking",decisions:["truncate","leave_empty","exclude_object"]}],["NUMBER_OUTSIDE_VALID_RANGE",{kind:"number_out_of_range",severity:"blocking",decisions:["leave_empty","exclude_object"]}],["DUPLICATE_VALUE",{kind:"unique_value_collision",severity:"warning",decisions:["leave_empty","exclude_object","ignore"]}],["FIELD_FILTER_VALIDATION_EXCEPTION",{kind:"lookup_filter",severity:"warning",decisions:["leave_empty","ignore"]}]]),lr="FIELD_CUSTOM_VALIDATION_EXCEPTION";function lh(n){return n.flatMap(e=>{let t=e.detail?.rule,r=e.detail?.message;return e.kind!=="validation_rule"||typeof t!="string"||typeof r!="string"?[]:[{objectApiName:e.objectApiName,name:t,message:r,...e.field!==void 0?{field:e.field}:{}}]})}function gl(n,e,t){if(e.statusCode!==lr||e.message.trim()==="")return;let r=e.fields[0]?.toLowerCase(),o=t.filter(s=>s.objectApiName.toLowerCase()===n.toLowerCase()&&s.message.trim()===e.message.trim()&&(s.field===void 0||r===void 0||s.field.toLowerCase()===r));return o.length===1?o[0].name:void 0}function Yt(n,e){let t=n.detail?.[e];return typeof t=="number"?t:0}function ca(n){let e=n.detail?.fields;return Array.isArray(e)?e:[]}function hl(n,e,t){if(!n)return;let r=new Set(n.values);if(e.split(";").some(o=>!r.has(o)))return"not-in-target";if(n.controllerName===void 0)return t!==void 0?"record-type":void 0}function wl(n,e){if(pl.has(e.statusCode)||e.message==="")return;let t=e.message;for(let r of Object.values(n.fields))typeof r=="string"&&r.length>=3&&(t=t.split(r).join("\u2026"));return t}function yl(n,e){let t=n.fields.RecordTypeId;return typeof t=="string"?e.get(t.slice(0,15)):void 0}function bl(n,e,t,r){let{row:o}=n,s=e.fields[0],i=t===Dr?"unique_value_collision":"rehearsal_refusal";return{id:Ze(i,o.objectApiName,s,void 0,i==="rehearsal_refusal"?t:void 0),kind:i,severity:"warning",source:"rehearsal",objectApiName:o.objectApiName,...s!==void 0?{field:s}:{},...i==="rehearsal_refusal"?{value:t}:{},rows:1,detail:{...r(s),linkedToTheRecordItNames:!0},decisions:s!==void 0?["leave_empty","exclude_object","ignore"]:["exclude_object","ignore"],defaultDecision:"ignore"}}function Rl(n,e,t,r,o){let{row:s}=n,i=e.statusCode||ua,a=wl(s,e),d=n.onUpdate?void 0:gl(s.objectApiName,e,o),c=u=>{let m=u===void 0?void 0:s.fields[u];return{statusCode:i,fields:[...e.fields],...a!==void 0?{message:a}:{},...d!==void 0?{rule:d}:{},rowsOfTheRun:n.standsFor,...i==="STRING_TOO_LONG"&&typeof m=="string"?{valueLength:m.length}:{},...da.has(i)&&u!==void 0&&!n.onUpdate?{writtenWithoutTheField:!0}:{}}};if(n.onUpdate){let u=e.fields[0];return[{id:Ze("rehearsal_update_refusal",s.objectApiName,u,void 0,i),kind:"rehearsal_update_refusal",severity:"warning",source:"rehearsal",objectApiName:s.objectApiName,...u!==void 0?{field:u}:{},value:i,rows:1,detail:c(u),decisions:["exclude_object","ignore"]}]}if(n.linked)return[bl(n,e,i,c)];let l=ml.get(i);if(l&&e.fields.length>0)return(l.kind==="required_field_missing"?e.fields:e.fields.slice(0,1)).map(m=>{let g=s.fields[m],h=l.kind==="picklist_value_refused",y=h?yl(s,t):void 0,R=h&&typeof g=="string"?g:void 0,S=R!==void 0?hl(r.get(s.objectApiName)?.get(m),R,y):void 0;return{id:Ze(l.kind,s.objectApiName,m,y,R),kind:l.kind,severity:l.severity,source:"rehearsal",objectApiName:s.objectApiName,field:m,...y!==void 0?{recordType:y}:{},...R!==void 0?{value:R}:{},rows:1,detail:{...c(m),...S!==void 0?{reason:S}:{}},decisions:[...l.decisions],...l.severity==="warning"?{defaultDecision:"leave_empty"}:{}}});let f=e.fields[0],p=f!==void 0&&da.has(i);return[{id:Ze("rehearsal_refusal",s.objectApiName,f,void 0,i),kind:"rehearsal_refusal",severity:p?"warning":"blocking",source:"rehearsal",objectApiName:s.objectApiName,...f!==void 0?{field:f}:{},value:i,rows:1,detail:c(f),decisions:f!==void 0?["leave_empty","exclude_object","ignore"]:["exclude_object","ignore"],...p?{defaultDecision:"leave_empty"}:{}}]}function fa(n,e=new Map,t=new Map,r=[]){let o=new Map;for(let s of n){let i=s.errors.length>0?s.errors:[{statusCode:ua,message:"",fields:[]}],a=dn(...i.map(d=>Rl(s,d,e,t,r)));for(let d of a){let c=o.get(d.id);if(!c){o.set(d.id,d);continue}let l=Math.max(Yt(c,"valueLength"),Yt(d,"valueLength"));o.set(d.id,{...c,rows:c.rows+1,detail:{...d.detail,...c.detail,rowsOfTheRun:Yt(c,"rowsOfTheRun")+Yt(d,"rowsOfTheRun"),fields:[...new Set([...ca(c),...ca(d)])],...l>0?{valueLength:l}:{}}})}}return dn([...o.values()])}function Sl(n){return n!=null&&n!==""}function Ol(n){let e=n.fields.RecordTypeId,t=Object.keys(n.fields).filter(r=>r!=="attributes"&&Sl(n.fields[r])).sort();return[n.objectApiName,typeof e=="string"?e:"",t.join(",")].join("|")}function pa(n){if(n.length<=200)return{rows:[...n],standsFor:new Map(n.map(r=>[r.seq,1]))};let e=new Map,t=new Map;for(let r of n){let o=Ol(r),s=e.get(o);if(s){t.set(s.seq,(t.get(s.seq)??1)+1);continue}e.set(o,r),t.set(r.seq,1)}return{rows:[...e.values()],standsFor:t}}function Al(n){let e=n.fields.Status;return[n.objectApiName,Object.keys(n.fields).sort().join(","),typeof e=="string"?e:""].join("|")}function ma(n){if(n.length<=19)return{updates:[...n],standsFor:new Map(n.map(r=>[r.seq,1]))};let e=new Map,t=new Map;for(let r of n){let o=Al(r),s=e.get(o);if(s){t.set(s.seq,(t.get(s.seq)??1)+1);continue}e.set(o,r),t.set(r.seq,1)}return{updates:[...e.values()],standsFor:t}}function ga(n,e,t=()=>{}){let r=new Map(n.map(a=>[a.seq,a])),o=new Map,s=new Map,i=new Map;for(let a of[...n].sort((d,c)=>d.seq-c.seq)){let d=new Set,c=new Set;for(let f of Object.values(a.fields)){let p=e(f);p&&p.seq!==a.seq&&d.add(p.seq);let u=p?void 0:t(f);u&&u.seq!==a.seq&&r.has(u.seq)&&(d.add(u.seq),c.add(u.seq))}let l=[...d].sort((f,p)=>f-p);o.set(a.seq,l),c.size>0&&i.set(a.seq,[...c].sort((f,p)=>f-p)),s.set(a.seq,l.reduce((f,p)=>Math.max(f,(s.get(p)??0)+1),0))}return{bySeq:r,parents:o,levels:s,...i.size>0?{personContactsNamed:i}:{}}}function ha(n,e){if(e.size===0)return n;let t=new Map;for(let[o,s]of n.parents){let i=new Set;for(let a of s){let d=e.get(a);d===void 0?i.add(a):"seq"in d&&d.seq!==o&&i.add(d.seq)}t.set(o,[...i].sort((a,d)=>a-d))}let r=new Map;for(let o of[...n.bySeq.keys()].sort((s,i)=>s-i))r.set(o,(t.get(o)??[]).reduce((s,i)=>Math.max(s,(r.get(i)??0)+1),0));return{bySeq:n.bySeq,parents:t,levels:r,...n.personContactsNamed?{personContactsNamed:n.personContactsNamed}:{}}}function Ge(n,e){let t=new Set,r=[...e.parents.get(n)??[]];for(let o=r.shift();o!==void 0;o=r.shift())t.has(o)||(t.add(o),r.push(...e.parents.get(o)??[]));return[...t]}function fr(n,e){let t=new Set;for(let r of n){t.add(r.seq);for(let o of Ge(r.seq,e))t.add(o)}return[...t].sort((r,o)=>r-o).flatMap(r=>{let o=e.bySeq.get(r);return o?[o]:[]})}var mr=5,gr=25,kl=200,Il=10,jl="PROCESSING_HALTED",Nl="SandForge_Rehearsal_Rollback__c";function hr(n,e=0){return Math.max(0,gr-n-e-1)}function tn(n,e){let t=new Set;for(let r of n)for(let o of e.personContactsNamed?.get(r)??[])t.add(o);return[...t]}function wa(n,e,t=[],r=new Map){let o=new Map;n.collections.forEach((a,d)=>a.seqs.forEach(c=>o.set(c,d)));let s=new Set([...tn(n.collections.flatMap(a=>a.seqs),e),...t.flatMap(a=>a.contacts??[])]),i=[];for(let a of s){let d=o.get(a),c=r.get(a),l=d??(c===void 0?void 0:"id"in c?-1:o.get(c.seq));l!==void 0&&i.push({account:a,after:l})}return i.sort((a,d)=>a.after-d.after||a.account-d.account)}function El(n,e,t){let r=[...e].flatMap(a=>{let d=t.get(a);return d?[d]:[]}).sort((a,d)=>a.objectApiName.localeCompare(d.objectApiName)||a.seq-d.seq),o=[],s,i=new Set;for(let a of r){let d=!i.has(a.objectApiName);(!s||s.seqs.length>=kl||d&&i.size>=Il)&&(s={level:n,seqs:[]},i=new Set,o.push(s)),s.seqs.push(a.seq),i.add(a.objectApiName)}return o}function pr(n,e){return[...n.keys()].sort((t,r)=>t-r).flatMap(t=>El(t,n.get(t)??[],e))}function nn(n,e){let t=l=>e.levels.get(l)??0,r=[...n].sort((l,f)=>t(f.seq)-t(l.seq)||l.seq-f.seq),o=[],s=[],i=new Set,a=new Map,d=(l,f)=>{let p=new Map([...l].map(([u,m])=>[u,new Set(m)]));for(let u of f){let m=p.get(t(u))??new Set;m.add(u),p.set(t(u),m)}return p},c=l=>{let f=pr(l,e.bySeq).length,p=tn([...l.values()].flatMap(u=>[...u]),e).length;return f<=mr&&f+p<gr};for(let l of r){if(i.has(l.seq))continue;let f=[l.seq,...Ge(l.seq,e)],p=d(new Map,f);if(!c(p)){s.push(l.seq);continue}let u=d(a,f);c(u)?a=u:(o.push({collections:pr(a,e.bySeq)}),a=p);for(let m of f)i.add(m)}return a.size>0&&o.push({collections:pr(a,e.bySeq)}),{calls:o,beyond:s.sort((l,f)=>l-f)}}function Xt(n){return`rows${n}`}function wr(n){return`update${n}`}var ya="rollback";function en(n){return`contact${n}`}function Tl(n,e,t){let r=o=>t.filter(s=>s.after===o).map(s=>en(s.account));return[...r(-1),...n.collections.flatMap((o,s)=>[Xt(s),...r(s)]),...Array.from({length:e},(o,s)=>wr(s)),ya]}function ba(n,e,t,r,o,s=[],i=new Map,a={of:()=>{},reads:[]}){let{reads:d}=a;if(s.length>hr(n.collections.length,d.length))throw new Error(`A rehearsal call of ${n.collections.length} Collections request(s) has no room for ${s.length} update(s): a call holds ${gr} subrequests`);let c=new Map;n.collections.forEach((w,b)=>w.seqs.forEach((A,E)=>c.set(A,`@{${Xt(b)}[${E}].id}`)));let l=w=>{let b=c.get(w.seq);if(b!==void 0)return b;let A=i.get(w.seq);if(A!==void 0)return"id"in A?A.id:c.get(A.seq)},f=new Set(d.map(w=>w.account)),p=w=>{let b=t(w);if(b){let E=l(b);return E===void 0?void 0:{sent:E}}let A=a.of(w);return A?f.has(A.seq)?{sent:`@{${en(A.seq)}.${Me}}`}:void 0:{sent:w}},u=w=>w.seqs.map(b=>{let A=e.bySeq.get(b);if(!A)throw new Error(`Row ${b} is not among the rows the run creates`);return A}),m=(w,b)=>({method:"POST",url:`${r}/composite/sobjects`,referenceId:Xt(b),body:{allOrNone:!1,records:u(w).map(A=>{let E={attributes:{type:A.objectApiName}};for(let[x,T]of Object.entries(A.fields)){if(x==="attributes"||x==="Id")continue;let v=p(T);if(v===void 0)throw new Error(`${A.objectApiName} row ${A.seq} names a record the run creates that its call does not hold`);E[x]=v.sent}return E})},httpHeaders:{...o}}),g=({account:w})=>{let b=e.bySeq.get(w),A=b?l(b):void 0;if(A===void 0)throw new Error("A read of a person account's contact names an account its call does not hold");return{method:"GET",url:`${r}/sobjects/${ce}/${A}?fields=${Me}`,referenceId:en(w)}},h=w=>d.filter(b=>b.after===w).map(g),y=[...h(-1),...n.collections.flatMap((w,b)=>[m(w,b),...h(b)])];s.forEach((w,b)=>{let A=c.get(w.rowSeq);if(A===void 0)throw new Error(`An update of ${w.objectApiName} names a record its call does not create`);let E={};for(let[x,T]of Object.entries(w.fields)){if(x==="attributes"||x==="Id")continue;let v=p(T);if(v===void 0)throw new Error(`An update of ${w.objectApiName} names a record the run creates that its call does not hold`);E[x]=v.sent}y.push({method:"PATCH",url:`${r}/sobjects/${w.objectApiName}/${A}`,referenceId:wr(b),body:E,httpHeaders:{...o}})});let R=n.collections[0]?.seqs[0],S=R===void 0?void 0:e.bySeq.get(R);if(!S)throw new Error("A rehearsal call holds no row");return y.push({method:"PATCH",url:`${r}/sobjects/${S.objectApiName}/${Fl(S.placeholderId)}`,referenceId:ya,body:{[Nl]:!0}}),{allOrNone:!0,collateSubrequests:!1,compositeRequest:y}}function Fl(n){return Rt(`${n.slice(0,3)}000000000000`)??"000000000000000AAA"}var Pl=V({body:Ne(),httpStatusCode:te(),referenceId:W().optional()}).loose(),vl=V({compositeResponse:Z(Pl)}).loose(),Qt=Z(V({errorCode:W().optional(),statusCode:W().optional()}).loose()),Cl=Z(V({success:Ke()}).loose());function Zt(n){let e=Qt.safeParse(n.body);return n.httpStatusCode>=400&&e.success&&e.data.length>0&&e.data.every(t=>(t.errorCode??t.statusCode)===jl)}function Ra(n,e,t=0,r=()=>{},o=[]){let s=vl.safeParse(n);if(!s.success)throw new Error("The target answered the rehearsal with no composite answer");let i=s.data.compositeResponse,a=Tl(e,t,o),d=a.length,c=i[d-1];if(i.length!==d||!c)throw new Error(`The target answered ${i.length} subrequests of the ${d} the rehearsal sent`);let l=i.findIndex((m,g)=>m.referenceId!==void 0&&m.referenceId!==a[g]);if(l!==-1)throw new Error(`The target ran the rehearsal's subrequests out of the order sent (${String(i[l]?.referenceId)} in place of ${a[l]}): no verdict can be read from it`);let f=m=>i[a.indexOf(m)];for(let{account:m}of o){let g=f(en(m));if(g.httpStatusCode<400||Zt(g))continue;let h=Qt.safeParse(g.body),y=h.success?h.data[0]?.errorCode??h.data[0]?.statusCode:"";throw new Error(`The target refused to read back the contact the platform wrote with a person account (status ${g.httpStatusCode}${y?`, ${y}`:""}): no verdict can be read past it`)}let p=e.collections.map((m,g)=>{let h=f(Xt(g));if(Zt(h))return{kind:"halted"};let y=Cl.safeParse(h.body);if(h.httpStatusCode<400&&y.success){if(y.data.length!==m.seqs.length)throw new Error(`The target answered ${y.data.length} rows of the ${m.seqs.length} a request sent`);return{kind:"rows",outcomes:y.data.map((S,w)=>St(S,r(m.seqs[w])??""))}}let R=Qt.safeParse(h.body);if(h.httpStatusCode>=400&&R.success&&R.data.length>0)return{kind:"refused",errors:R.data.map(hn)};throw new Error(`The target answered a request of the rehearsal with status ${h.httpStatusCode}`)}),u=Array.from({length:t},(m,g)=>{let h=f(wr(g));if(Zt(h))return{kind:"halted"};if(h.httpStatusCode<400)return{kind:"saved"};let y=Qt.safeParse(h.body);if(y.success&&y.data.length>0)return{kind:"refused",errors:y.data.map(hn)};throw new Error(`The target answered an update of the rehearsal with status ${h.httpStatusCode}`)});if(c.httpStatusCode<400)return{kind:"not_rolled_back",ids:p.flatMap(m=>m.kind==="rows"?m.outcomes.filter(g=>g.success).map(g=>g.id):[])};if(Zt(c)&&yr(p)===-1&&!u.some(m=>m.kind==="refused"))throw new Error("The target stopped the rehearsal at a request whose answer names no refusal");return{kind:"rolled_back",collections:p,updates:u}}function yr(n){return n.findIndex(e=>e.kind==="refused"||e.kind==="rows"&&e.outcomes.some(t=>!t.success))}function Sa(n,e,t=()=>{}){let r=new Map,o=yr(e);return n.collections.forEach((s,i)=>{if(o!==-1&&i>o)return;let a=e[i];s.seqs.forEach((d,c)=>{if(a.kind==="refused"){r.set(d,{passed:!1,errors:a.errors});return}let l=a.kind==="rows"?a.outcomes[c]:void 0;if(!l||l.success){r.set(d,{passed:!0});return}let f=Eo(l,t(d));r.set(d,{passed:!1,errors:l.errorDetails??[],...f.kind==="linked"?{linkedTo:f.id}:{}})})}),r}function Oa(n,e){let t=new Map;if(yr(e.collections)!==-1)return t;for(let[r,o]of n.entries()){let s=e.updates[r];if(s?.kind==="refused"){t.set(o.seq,{passed:!1,errors:s.errors});break}t.set(o.seq,{passed:!0})}return t}async function xl(n,e){let t=e.targetRecordTypes;if(!t)return n;let r=new Set(n.flatMap(s=>s.recordType!==void 0&&Oo(s.recordType).namespacePrefix?[s.objectApiName]:[]));if(r.size===0)return n;let o=new Map;for(let s of r){let i=await t(s).catch(()=>{});o.set(s,i?Ao(i):void 0)}return n.map(s=>ko(s,o.get(s.objectApiName)))}async function Ml(n,e){let t=[...new Set(n.filter(({errors:r})=>r.some(o=>o.statusCode===lr)).map(({row:r})=>r.objectApiName))];if(t.length===0||!e.validationRules)return[];try{return await e.validationRules(t)}catch{return[]}}async function _l(n,e){let t=new Map;for(let{row:s,errors:i,onUpdate:a}of n)if(!a)for(let d of i){let c=d.fields[0];d.statusCode!==la||c===void 0||t.set(s.objectApiName,(t.get(s.objectApiName)??new Set).add(c))}let r=new Map,o=e.targetFields;if(!o)return r;for(let[s,i]of t){let a;try{a=await o(s)}catch{continue}let d=new Map;for(let c of a)!i.has(c.name)||!c.picklistValues||d.set(c.name,{values:c.picklistValues,...c.controllerName?{controllerName:c.controllerName}:{}});r.set(s,d)}return r}var br=class extends Error{constructor(t,r=[]){super(`A rehearsal call was not rolled back: the ${t.length} record(s) it created stay in the target (${t.join(", ")}). The rehearsal stopped there; remove them from the target.`);this.ids=t;this.objects=r;this.name="RehearsalNotRolledBackError"}ids;objects},rn=class extends Error{constructor(t){super(t>0?`The rehearsal was cancelled after ${t} call(s), each rolled back whole: nothing stays in the target.`:"The rehearsal was cancelled before its first call. Nothing was sent to the target.");this.calls=t;this.name="RehearsalCancelledError"}calls};function Ll(n,e){let t=new Map;for(let o of e)t.set(o.placeholderId.slice(0,3),o.objectApiName);let r=new Map;for(let o of n){let s=t.get(o.slice(0,3))??o.slice(0,3);r.set(s,(r.get(s)??0)+1)}return[...r].map(([o,s])=>({objectApiName:o,created:s}))}function Aa(n){let e=new Map;for(let{objectApiName:t}of n)e.set(t,(e.get(t)??0)+1);return[...e].map(([t,r])=>({objectApiName:t,count:r})).sort((t,r)=>r.count-t.count||t.objectApiName.localeCompare(r.objectApiName))}function Dl(n,e,t){let r=n.slice(0,15);for(let[o,s]of e.collections.entries()){let i=t[o];if(i?.kind==="rows")for(let[a,d]of i.outcomes.entries()){let c=s.seqs[a];if(d.success&&d.id.slice(0,15)===r&&c!==void 0)return{seq:c}}}return{id:n}}function Bl(n,e,t){let r=e(n.recordId);if(!r)return;let o=new Set([r.seq]),s=new Set;for(let i of Object.values(n.fields)){let a=e(i);a&&o.add(a.seq);let d=a?void 0:t(i);d&&(o.add(d.seq),s.add(d.seq))}return{seq:n.seq,objectApiName:n.objectApiName,rowSeq:r.seq,fields:n.fields,needs:[...o],...s.size>0?{contacts:[...s]}:{}}}function Rr(n,e,t){let r=new Set(n.collections.flatMap(i=>i.seqs)),o=new Set(tn(r,t)),s=[];for(let i of e){if(!i.needs.every(d=>r.has(d)))continue;let a=(i.contacts??[]).filter(d=>!o.has(d));if(s.length+1>hr(n.collections.length,o.size+a.length))break;for(let d of a)o.add(d);s.push(i)}return s}function ka(n,e){let t=o=>{let s=fr(o.flatMap(d=>d.needs.flatMap(c=>{let l=e.bySeq.get(c);return l?[l]:[]})),e),i=nn(s,e),[a]=i.calls;return i.calls.length===1&&i.beyond.length===0&&a&&Rr(a,o,e).length===o.length?a:void 0},r=[];for(let[o,s]of n.entries()){let i=[s],a=t(i);if(!a){r.push(s);continue}for(let d of n.slice(o+1)){let c=t([...i,d]);c&&(i=[...i,d],a=c)}return{call:a,beyond:r}}return{beyond:r}}function $l(n,e,t){let r=[...e],o=i=>{let a=new Set(Rr(i,r,t));return r=r.filter(d=>!a.has(d)),a.size};for(let i of n)o(i);let s=0;for(;r.length>0;){let{call:i,beyond:a}=ka(r,t),d=new Set(a);if(r=r.filter(c=>!d.has(c)),!i||o(i)===0)break;s++}return n.length+s}async function kh(n){let e=new Kt(n.keyPrefixOf,n.runningUser);await n.prepare(e);let t=e.rows,r=j=>e.rowOf(j),o=j=>e.personContactOf(j),s=ga(t,r,o),i=pa(t),a=ma(e.updated.flatMap(j=>{let F=Bl(j,r,o);return F?[F]:[]})),d=a.updates,c=fr([...i.rows,...d.flatMap(j=>j.needs.flatMap(F=>{let k=s.bySeq.get(F);return k?[k]:[]}))],s),l=j=>i.standsFor.get(j)??1,f=j=>{let F=s.bySeq.get(j)?.placeholderId.slice(0,3);return F===void 0||F===ur?null:F},p=new Map,u=new Map,m=new Map,g=new Map,h=new Map,y=s,R=nn(c,s);for(let j of R.beyond)u.set(j,"beyond_a_call");let S=$l(R.calls,d,s),w=S*mr,b=0;if(S>0){if(n.signal?.aborted)throw new rn(0);n.onProgress?.({phase:"confirming",calls:S}),await n.confirm({rows:t.length,sampled:c.length,updates:Aa(d).map(({objectApiName:j,count:F})=>({objectApiName:j,updates:F})),calls:S,maxCalls:w,objects:Aa(c).map(({objectApiName:j,count:F})=>({objectApiName:j,rows:F}))})}let A=j=>{let F=p.get(j);return F?.passed===!1&&F.linkedTo===void 0},E=j=>[j,...Ge(j,y)].some(A),x=j=>{if(h.has(j.rowSeq))return"record_linked";for(let F of j.needs){if(E(F))return"parent_refused";let k=u.get(F);if(k)return k}};for(;;){if(n.signal?.aborted)throw new rn(b);let j=c.filter(M=>p.has(M.seq)||u.has(M.seq)?!1:Ge(M.seq,y).some(A)?(u.set(M.seq,"parent_refused"),!1):!0),F=d.filter(M=>{if(m.has(M.seq)||g.has(M.seq))return!1;let $=x(M);return $?(g.set(M.seq,$),!1):!0});if(j.length===0&&F.length===0)break;if(b>=w){for(let M of j)u.set(M.seq,"call_budget");for(let M of F)g.set(M.seq,"call_budget");break}let k;if(j.length>0){let M=nn(j,y);for(let $ of M.beyond)u.set($,"beyond_a_call");k=M.calls[0]}else{let M=ka(F,y);for(let $ of M.beyond)g.set($.seq,"beyond_a_call");k=M.call}if(!k)continue;let O=Rr(k,F.filter(M=>!g.has(M.seq)),y);b++,n.onProgress?.({phase:"rehearsing",call:b,calls:Math.max(S,b)});let C=wa(k,y,O,h),B=ba(k,s,r,n.apiPath,n.writeHeaders,O,h,{of:o,reads:C}),P=Ra(await n.composite(B),k,O.length,M=>s.bySeq.get(M)?.objectApiName,C);if(P.kind==="not_rolled_back")throw new br(P.ids,Ll(P.ids,t));let L=new Map;for(let[M,$]of Sa(k,P.collections,f))p.set(M,$),!$.passed&&$.linkedTo!==void 0&&L.set(M,Dl($.linkedTo,k,P.collections));for(let[M,$]of Oa(O,P))m.set(M,$);if(L.size>0){for(let[M,$]of L)h.set(M,$);y=ha(s,h),d=d.map(M=>({...M,needs:M.needs.flatMap($=>{let q=h.get($);return q===void 0?[$]:"seq"in q?[q.seq]:[]})}))}}let T=[],v=0,I=0;for(let j of c){let F=p.get(j.seq);if(!F)continue;if(F.passed){v++;continue}let k=F.linkedTo!==void 0;k&&I++,T.push({row:j,errors:F.errors,standsFor:l(j.seq),...k?{linked:!0}:{}})}let N=0,_=0;for(let j of d){let F=m.get(j.seq),k=s.bySeq.get(j.rowSeq);if(!F||!k)continue;let O=a.standsFor.get(j.seq)??1;if(_+=O,F.passed){N++;continue}T.push({row:{...k,fields:{...k.fields,...j.fields}},errors:F.errors,standsFor:O,onUpdate:!0})}let D=new Map;for(let[j,F]of u){let O=`${s.bySeq.get(j)?.objectApiName??""}|${F}`;D.set(O,(D.get(O)??0)+1)}return{gaps:await xl(fa(T,n.recordTypeNames,await _l(T,n),await Ml(T,n)),n),rows:t.length,sampled:c.length,judged:p.size,passed:v,linked:I,notJudged:u.size,notJudgedWhy:[...D].map(([j,F])=>{let[k,O]=j.split("|");return{objectApiName:k,rows:F,reason:O}}),updates:e.updates,updatesJudged:m.size,updatesPassed:N,updatesNotRehearsed:e.updates-_,calls:b,plannedCalls:S}}var Wl="QuoteLineItem",Sr="Quote",on="Opportunity",Or="OpportunityLineItem",Ir="SyncedQuoteId",jr="QuoteId",Nr="OpportunityLineItemId",kr=new Set(["Id",jr,Nr]);function lt(n){return n.slice(0,15)}function Ar(n,e){let t=n[e];return typeof t=="string"&&t!==""?lt(t):void 0}function Nh(n,e){return!n.has(on)||!n.has(Sr)||!n.has(Or)?[]:e.get(on)?.some(r=>r.name===Ir)!==!0?[]:[{sourceObject:Sr,targetObject:Or,relationshipName:`${Sr}Before${Or}`,type:"lookup",required:!0}]}function ql(n,e,t){let r=[...kr,...t.filter(s=>!kr.has(s))].map(J).join(", "),o=s=>s.map(i=>`'${xe(i)}'`).join(", ");return`SELECT ${r} FROM ${Wl} WHERE ${jr} IN (${o(n)}) AND ${Nr} IN (${o(e)})`}var zl=200;function Ul(n,e){let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t}async function Eh(n,e,t){let r=[],o=[...new Set(e.map(s=>s.product))];for(let s of Ul(o,zl)){let i=new Set(s.map(lt)),a=[...new Set(e.filter(d=>i.has(lt(d.product))).map(d=>d.quote))];r.push(...await n(ql(a,s,t)))}return r}function Th(n,e,t){let r=new Map;for(let s of e){let i=Ar(s,"Id"),a=Ar(s,jr),d=Ar(s,Nr);if(!i||!a||!d||t.has(i))continue;let c=`${a}:${d}`;r.set(c,[...r.get(c)??[],s])}let o=new Map;for(let s of n){let i=r.get(`${lt(s.quote)}:${lt(s.product)}`)?.shift();i&&o.set(s.index,i)}return o}var Ia=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;function Vl(n,e){let t=r=>r==null||r==="";if(t(n)||t(e))return t(n)&&t(e);if(n===e)return!0;if(typeof n=="number"||typeof e=="number"){let r=Number(n),o=Number(e);return Number.isFinite(r)&&Number.isFinite(o)&&r===o}if(typeof n=="string"&&typeof e=="string"){if(Ia.test(n)&&Ia.test(e)){let r=Date.parse(n),o=Date.parse(e);return Number.isFinite(r)&&r===o}return!1}return String(n)===String(e)}function Fh(n,e,t,r=new Set){let o={};for(let[s,i]of Object.entries(n))kr.has(s)||r.has(s)||!t(s)||Vl(i,e[s])||(o[s]=i??null);return o}function Ph(n,e,t){let r=n===1,o=`the platform's ${r?"copy":"copies"} of ${r?"its":"their"} opportunity product${r?"":"s"}`,s=e>0?`, ${e} given the fields the copy lacked`:"";return`${n} of them ${t?"would be ":""}${o}, made as the quote syncs with its opportunity: taken rather than written twice${s}`}var Gl=2e3,Jl=3,Hl=20,ft=20;function Wh(n,e){let t=bo(n,e);return{query:r=>t.query(r),describe:r=>t.describe(r),describeGlobal:()=>t.describeGlobal(),queryAll:async r=>{let o=await n.query(r,{scanAll:!0});return yo(n.limitInfo,e),{totalSize:o.totalSize,records:o.records}},serverTime:async()=>(await n.soap.getServerTimestamp()).timestamp}}function ja(n,e,t){return`${n}:${e.slice(0,15)}:${t}`}function Na(n,e){return`${n}.${e}`}var Kl=[{modified:"LastModifiedDate",by:"LastModifiedById",created:!0},{modified:"LastModifiedDate",by:"LastModifiedById"},{modified:"SystemModstamp",created:!0},{modified:"SystemModstamp"},{}],fe="CreatedById",He="CreatedDate",Yl=V({sobjects:Z(V({name:W(),keyPrefix:W().nullish()}).loose())}).loose(),Zl=n=>new Promise(e=>setTimeout(e,n));function G(n){return n.slice(0,15)}function Ea(n){return n.slice(0,3)}function Ta(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function Ql(n,e,t){let r=n[fe],o=pt(n[He]);if(typeof r!="string"||!Number.isFinite(o))return;let s=i=>Math.floor(i/1e3)*1e3;return G(r)===G(e)&&s(o)>=s(t.from)&&s(o)<=s(t.to)}function pt(n){return typeof n=="string"?Date.parse(n):Number.NaN}function Je(n){return typeof n.Id=="string"?n.Id:void 0}function Er(n){return Array.isArray(n)?`[${n.map(Er).join(",")}]`:typeof n=="object"&&n!==null?`{${Object.entries(n).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${Er(r)}`).join(",")}}`:JSON.stringify(n)}var Fa=class{constructor(e){this.deps=e}deps;describes=new Map;async verify(e,t={}){let r=t.now??(()=>new Date),o=t.sleep??Zl,s=t.intervalMs??Gl,i=Math.max(1,t.maxAttempts??Jl),a=t.linkSample??Hl,d=await this.runEnd(e),c=this.deps.source,l="unavailable"in c?c.unavailable:void 0,f=new Map;if(!("unavailable"in c))for(let b of e.records)f.set(b.objectApiName,await this.linkPlan(c,e,b,a));let p=null,u=null,m=[],g=0,h=this.explaining(e,d),y=h.window?await this.runUser(e):void 0,R=await this.writtenByThePlatformAlone(e,h);for(let b=1;b<=i;b++){g=b,await o(s),m=[];for(let E of e.records)m.push(await this.read(e,E,d,f.get(E.objectApiName),h,y));for(let E of R)m.push(await this.readWrittenByThePlatform(E,h,y));let A=Er(m);if(p!==null&&A===p){u=m;break}p=A}let S=(u??m).map(ef),w=e.roots?Xl(e,e.roots,u??m):void 0;return{verdict:tf(u!==null,S,l),verifiedAt:r().toISOString(),attempts:g,objects:S,...l!==void 0?{linksUnchecked:l}:{},...w?{roots:w}:{}}}async runEnd(e){if(e.runEndedAt)return e.runEndedAt.getTime();if(!e.runRecordedAt)return Number.NaN;let t=0,r=this.deps.target.serverTime;if(r){let o=Date.now();try{let s=pt(await r.call(this.deps.target));Number.isFinite(s)&&(t=s-(o+Date.now())/2)}catch{}}return e.runRecordedAt.getTime()+t+Ot}explaining(e,t){let r=new Set;for(let{objectApiName:c,field:l,recordIds:f}of e.leftEmptyByFilter??[])for(let p of f)r.add(ja(c,p,l));let o=new Set(Object.entries(e.leftEmptyByTheRun??{}).flatMap(([c,l])=>l.map(f=>Na(c,f)))),s=[...new Set((e.withTheirRecord??[]).flatMap(c=>{let l=e.remapTable[c];return l===void 0?[]:[l]}))],i=e.runStartedAt?.getTime()??Number.NaN,a=Number.isFinite(i)&&Number.isFinite(t),d={from:i-Ot,to:t+Ot};return{emptiedByFilter:r,emptiedByTheRun:o,withTheirRecord:s,createdByRun:new Set(Object.values(e.remapTable).map(G)),...a?{window:d,counted:e.runEndedAt?{from:d.from,to:t}:d}:{}}}async setByAutomation(e,t,r){let o=r.window,s=e.filter(({link:l,createdBy:f})=>o!==void 0&&typeof f=="string"&&l.found!==null&&!r.createdByRun.has(G(l.found)));if(!o||s.length===0)return{explained:[],broken:e.map(({link:l})=>l)};let i=new Map,a=new Map;for(let{link:l}of s){let f=await this.objectOfId(t.referenceTo?.get(l.field)??[],l.found);f!==void 0&&a.set(f,[...a.get(f)??[],l.found])}for(let[l,f]of a)try{let p=await pe(this.deps.target,l,[fe,He],[...new Set(f)]);for(let u of p){let m=Je(u);m&&i.set(G(m),u)}}catch{}let d=[],c=[];for(let l of e){let{link:f,createdBy:p}=l,u=f.found===null?void 0:i.get(G(f.found)),m=pt(u?.[He]);s.includes(l)&&typeof p=="string"&&typeof u?.[fe]=="string"&&G(u[fe])===G(p)&&m>=o.from&&m<=o.to?d.push({...f,cause:"automation"}):c.push(f)}return{explained:d,broken:c}}async objectOfId(e,t){if(e.length===1)return e[0];for(let r of e)try{if((await this.describe(this.deps.target,"target",r)).keyPrefix===t.slice(0,3))return r}catch{}}describe(e,t,r){let o=`${t}:${r}`,s=this.describes.get(o);return s||(s=e.describe(r),this.describes.set(o,s)),s.then(i=>bt.parse(i))}async linkPlan(e,t,r,o){let s=r.objectApiName,i={fields:[],expected:new Map,sample:[]};try{let[a,d]=await Promise.all([this.describe(this.deps.target,"target",s),this.describe(e,"source",s)]),c=new Set(a.fields.filter(w=>w.type==="reference"&&(w.createable===!0||w.updateable===!0)).map(w=>w.name)),l=new Set(t.fieldExclusions?.[s]??[]),f=t.fieldMappings?.[s]??{},p=d.fields.filter(w=>w.type==="reference"&&!l.has(w.name)).map(w=>({from:w.name,to:f[w.name]??w.name})).filter(({to:w})=>c.has(w)&&!l.has(w));if(p.length===0)return i;let u=new Map,m=new Map;for(let[w,b]of Object.entries(t.remapTable))u.set(G(b),w),m.set(G(w),b);let g=r.ids.slice(0,o).filter(w=>u.has(G(w)));if(g.length===0)return i;let h=await pe(e,s,p.map(w=>w.from),g.map(w=>u.get(G(w)))),y=new Map;for(let w of h){let b=Je(w),A=b?m.get(G(b)):void 0;if(!A)continue;let E=[];for(let{from:x,to:T}of p){let v=w[x],I=typeof v=="string"?m.get(G(v)):void 0;I&&E.push({field:T,expected:I})}E.length>0&&y.set(G(A),E)}let R=[...new Set([...y.values()].flat().map(w=>w.field))],S=new Map(a.fields.filter(w=>R.includes(w.name)).map(w=>[w.name,w.referenceTo??[]]));return{fields:R,expected:y,sample:R.length>0?g:[],referenceTo:S,createdBy:a.fields.some(w=>w.name===fe)}}catch(a){return{...i,unchecked:H(a)}}}async runUser(e){for(let t of e.records){let r=t.ids[0];if(r!==void 0)try{let[o]=await pe(this.deps.target,t.objectApiName,[fe],[r]),s=o?.[fe];if(typeof s=="string"&&/^[A-Za-z0-9]{15,18}$/.test(s))return s}catch{}}}async countInTheWindow(e,t,r,o){try{return(await this.deps.target.query(`SELECT COUNT() FROM ${J(e)} WHERE ${fe} = '${t}' AND ${He} >= ${Ta(r.from)} AND ${He} <= ${Ta(r.to)}`+(o?` AND ${J(o.field)} = '${o.value}'`:""))).totalSize}catch{return}}async withTheirRecordThere(e,t,r=e.ids[0]?.slice(0,3)){if(r===void 0)return 0;let o=new Set(e.ids.map(G)),s=t.withTheirRecord.filter(i=>i.slice(0,3)===r&&!o.has(G(i)));if(s.length===0)return 0;try{let i=await pe(this.deps.target,e.objectApiName,[],s);return new Set(i.map(Je).filter(a=>a!==void 0).map(G)).size}catch{return 0}}async writtenByThePlatformAlone(e,t){let r=new Set(e.records.flatMap(i=>i.ids.slice(0,1)).map(Ea)),o=[...new Set(t.withTheirRecord.map(Ea))].filter(i=>!r.has(i)),s=this.deps.target.describeGlobal;if(o.length===0||!s)return[];try{let{sobjects:i}=Yl.parse(await s.call(this.deps.target));return o.flatMap(a=>{let d=i.find(c=>c.keyPrefix===a);return d?[{objectApiName:d.name,prefix:a}]:[]})}catch{return[]}}async readWrittenByThePlatform(e,t,r){let o={objectApiName:e.objectApiName,expected:0,present:0,deletedIds:[],notVisibleIds:[],changed:[],linksChecked:0,broken:[],explained:[],withTheirRecord:await this.withTheirRecordThere({objectApiName:e.objectApiName,ids:[]},t,e.prefix)};if(r!==void 0&&t.counted){let s=await this.countInTheWindow(e.objectApiName,r,t.counted);s!==void 0&&(o.createdInTheWindow=s)}return o}async read(e,t,r,o,s,i){let a=t.objectApiName,d={objectApiName:a,expected:t.ids.length,present:0,deletedIds:[],notVisibleIds:[],changed:[],linksChecked:0,broken:[],explained:[],withTheirRecord:0,...o?.unchecked!==void 0?{linksUnchecked:o.unchecked}:{}},c,l={},f,p=a===ln.objectApiName?ln:void 0;for(let y of Kl)try{let R=[y.modified,y.by,...y.created?[He,fe,...p?[p.field]:[]]:[]].filter(S=>!!S);c=await pe(this.deps.target,a,R,t.ids),l=y;break}catch(R){f??=H(R)}if(!c)return{...d,error:f??"The org gave no reason."};let u=new Map;for(let y of c){let R=Je(y);R&&u.set(G(R),y)}let m=t.ids.filter(y=>!u.has(G(y))),g=0;if(m.length>0){let y=await this.recycleBin(a,m);if("unread"in y)d.notVisibleIds=m,d.recycleBinUnread=y.unread;else for(let R of m){let S=y.found.get(G(R));S==="deleted"?d.deletedIds.push(R):S==="there"?g++:d.notVisibleIds.push(R)}}if(d.present=u.size+g,d.withTheirRecord=await this.withTheirRecordThere(t,s),i!==void 0&&s.counted){let y=s.counted,R=await this.countInTheWindow(a,i,y);if(R!==void 0){d.createdInTheWindow=R;let S=g,w=0;for(let b of u.values())Ql(b,i,y)!==!1&&(S++,p&&b[p.field]===p.value&&w++);if(d.ofTheRunInTheWindow=S,p){let b=await this.countInTheWindow(a,i,y,p);b!==void 0&&b>w&&(d.postedWithTheirRecord=b-w)}}}let h=new Map(Object.entries(e.removalStamps??{}).map(([y,R])=>[G(y),pt(R)]));if(l.modified&&Number.isFinite(r))for(let y of t.ids){let R=u.get(G(y));if(!R)continue;let S=pt(R[l.modified]);if(!Number.isFinite(S)||S<=r||S<=(h.get(G(y))??Number.NaN))continue;let w=l.by?R[l.by]:void 0;d.changed.push({recordId:y,modifiedAt:String(R[l.modified]),...typeof w=="string"?{modifiedById:w}:{}})}if(o&&o.sample.length>0)try{let y=await pe(this.deps.target,a,o.createdBy?[...o.fields,fe]:o.fields,o.sample),R=new Set(e.writtenWithout?.[a]??[]),S=[];for(let w of y){let b=Je(w);if(b)for(let{field:A,expected:E}of o.expected.get(G(b))??[]){let x=w[A],T=typeof x=="string"&&x!==""?x:null;if(T!==null&&G(T)===G(E)){d.linksChecked++;continue}if(T===null&&s.emptiedByFilter.has(ja(a,b,A))){d.linksChecked++,d.explained.push({recordId:b,field:A,expected:E,found:T,cause:"lookup-filter"});continue}if(T===null&&s.emptiedByTheRun.has(Na(a,A))){d.linksChecked++,d.explained.push({recordId:b,field:A,expected:E,found:T,cause:"run"});continue}if(T===null&&R.has(A))continue;d.linksChecked++;let v={recordId:b,field:A,expected:E,found:T};T===null?d.broken.push(v):S.push({link:v,createdBy:w[fe]})}}if(S.length>0){let{explained:w,broken:b}=await this.setByAutomation(S,o,s);d.explained.push(...w),d.broken.push(...b)}}catch(y){d.linksUnchecked=H(y)}return d}async recycleBin(e,t){let r=new Map;try{let o=J(e);for(let s of X(t)){let i=await this.deps.target.queryAll(`SELECT Id, IsDeleted FROM ${o} WHERE Id IN (${s})`);for(let a of i.records){if(typeof a!="object"||a===null)continue;let d=a,c=Je(d);if(!c)continue;let l=d.IsDeleted===!0||d.IsDeleted==="true";r.set(G(c),l?"deleted":"there")}}}catch(o){return{unread:H(o)}}return{found:r}}};function Xl(n,e,t){let r=t.find(d=>d.objectApiName===e.objectApiName);if(r?.error!==void 0)return;let o=new Set(n.records.filter(d=>d.objectApiName===e.objectApiName).flatMap(d=>d.ids.map(G))),s=new Set([...r?.deletedIds??[],...r?.notVisibleIds??[]].map(G)),i=0,a=0;for(let d of e.sourceIds){let c=n.remapTable[d];if(c===void 0)continue;i++;let l=G(c);(!o.has(l)||r!==void 0&&!s.has(l))&&a++}return{inTarget:a,of:i}}function ef(n){let e=n.explained.filter(s=>s.cause==="run").length,t=n.postedWithTheirRecord??0,r=n.withTheirRecord+t,o=(n.ofTheRunInTheWindow??n.present)+r;return{objectApiName:n.objectApiName,expected:n.expected,present:n.present,deleted:n.deletedIds.length,notVisible:n.notVisibleIds.length,changed:n.changed.length,changedRecords:n.changed.slice(0,ft),deletedIds:n.deletedIds.slice(0,ft),notVisibleIds:n.notVisibleIds.slice(0,ft),linksChecked:n.linksChecked,linksBroken:n.broken.length,brokenLinks:n.broken.slice(0,ft),...n.explained.length>0?{linksLeftEmptyByFilter:n.explained.filter(s=>s.cause==="lookup-filter").length,linksSetByAutomation:n.explained.filter(s=>s.cause==="automation").length,...e>0?{linksLeftEmptyByTheRun:e}:{},explainedLinks:n.explained.slice(0,ft)}:{},...n.error!==void 0?{error:n.error}:{},...n.linksUnchecked!==void 0?{linksUnchecked:n.linksUnchecked}:{},...n.recycleBinUnread!==void 0?{recycleBinUnread:n.recycleBinUnread}:{},...r>0?{withTheirRecord:r}:{},...n.createdInTheWindow!==void 0&&n.createdInTheWindow>o?{moreInTheWindow:n.createdInTheWindow-o}:{}}}function tf(n,e,t){return n?e.some(o=>o.error!==void 0||o.linksUnchecked!==void 0||o.deleted>0||o.notVisible>0||o.linksBroken>0||(o.moreInTheWindow??0)>0)||t!==void 0?"partial":"verified":"unstable"}function qh(n){let e=s=>n.objects.reduce((i,a)=>i+s(a),0),t=e(s=>s.linksLeftEmptyByFilter??0),r=e(s=>s.linksSetByAutomation??0),o=e(s=>s.linksLeftEmptyByTheRun??0);return{expected:e(s=>s.expected),present:e(s=>s.present),deleted:e(s=>s.deleted),notVisible:e(s=>s.notVisible),changed:e(s=>s.changed),linksChecked:e(s=>s.linksChecked),linksBroken:e(s=>s.linksBroken),...t>0?{linksLeftEmptyByFilter:t}:{},...r>0?{linksSetByAutomation:r}:{},...o>0?{linksLeftEmptyByTheRun:o}:{},attempts:n.attempts}}function zh(n){return n?{[on]:[Ir]}:{}}function Uh(n){let e={};for(let{objectApiName:t,fields:r}of n){let o=e[t]??=[];for(let{field:s}of r)o.includes(s)||o.push(s)}return e}var Pa=class{map=new Map;readScopes=new Map;reached=new Map;add(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r));for(let o of t)o&&r.add(o)}addRead(e,t){this.add(e,t),this.readScopes.set(e,new Set(this.map.get(e)))}addReadAgain(e,t){let r=[...t].filter(o=>o);this.add(e,r),this.readScopes.set(e,new Set([...this.readScopes.get(e)??[],...r]))}forget(e,t){let r=this.map.get(e);if(r)for(let o of t)r.delete(o)}get(e){return this.map.get(e)}scopeOf(e){return this.readScopes.get(e)??this.map.get(e)}isRead(e){return this.readScopes.has(e)}addReached(e,t){let r=this.reached.get(e);r||(r=new Set,this.reached.set(e,r));for(let o of t)o&&r.add(o)}reachedOf(e){return this.reached.get(e)}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}get size(){let e=0;for(let t of this.map.values())e+=t.size;return e}get objectCount(){let e=0;for(let t of this.map.values())t.size>0&&e++;return e}entries(){return this.map.entries()}clear(){this.map.clear(),this.readScopes.clear(),this.reached.clear()}};var va=class{cache=new Map;sizeMap=new Map;maxSize;defaultTtl;maxSizeBytes;currentBytes=0;releaseExpired;releaseTimer;constructor(e){this.maxSize=e?.maxSize??100,this.defaultTtl=e?.defaultTtl??3e5,this.maxSizeBytes=e?.maxSizeBytes??5242880,this.releaseExpired=e?.releaseExpired===!0}get(e){let t=this.cache.get(e);if(t){if(this.isExpired(t)){this.deleteEntry(e);return}return t.accessCount++,t.lastAccessedAt=Date.now(),t.data}}set(e,t,r){this.cache.has(e)&&this.removeSize(e);let o=this.maxSizeBytes<Number.POSITIVE_INFINITY,s=o?this.estimateSize(t):0;if(this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictLRU(),o)for(;this.cache.size>0&&this.currentBytes+s>this.maxSizeBytes;)this.evictLRU();this.cache.set(e,{data:t,cachedAt:Date.now(),ttl:r??this.defaultTtl,accessCount:1,lastAccessedAt:Date.now()}),o&&(this.sizeMap.set(e,s),this.currentBytes+=s),this.releaseExpired&&this.scheduleRelease()}has(e){let t=this.cache.get(e);return t?this.isExpired(t)?(this.deleteEntry(e),!1):!0:!1}invalidate(e){return this.cache.has(e)?(this.deleteEntry(e),!0):!1}invalidateByPrefix(e){let t=0;for(let r of this.cache.keys())r.startsWith(e)&&(this.deleteEntry(r),t++);return t}clear(){this.cache.clear(),this.sizeMap.clear(),this.currentBytes=0,clearTimeout(this.releaseTimer),this.releaseTimer=void 0}get size(){return this.cache.size}get activeSize(){let e=0;for(let t of this.cache.values())this.isExpired(t)||e++;return e}get estimatedBytes(){return this.currentBytes}keys(){let e=[];for(let[t,r]of this.cache)this.isExpired(r)||e.push(t);return e}purgeExpired(){let e=0;for(let[t,r]of this.cache)this.isExpired(r)&&(this.deleteEntry(t),e++);return e}scheduleRelease(){if(this.releaseTimer!==void 0)return;let e=1/0;for(let r of this.cache.values())e=Math.min(e,r.cachedAt+r.ttl);if(e===1/0)return;let t=setTimeout(()=>{this.releaseTimer=void 0,this.purgeExpired(),this.scheduleRelease()},Math.max(0,e-Date.now())+1);t.unref?.(),this.releaseTimer=t}isExpired(e){return Date.now()-e.cachedAt>e.ttl}evictLRU(){let e,t=1/0;for(let[r,o]of this.cache)o.lastAccessedAt<t&&(t=o.lastAccessedAt,e=r);e&&this.deleteEntry(e)}deleteEntry(e){this.cache.delete(e),this.removeSize(e)}removeSize(e){let t=this.sizeMap.get(e);t!==void 0&&(this.currentBytes-=t,this.sizeMap.delete(e))}estimateSize(e){if(e==null)return 16;if(typeof e=="string")return e.length*2;if(typeof e=="number"||typeof e=="boolean")return 8;if(typeof e!="object")return 64;let t=e;if(Array.isArray(t.fields)||Array.isArray(t.childRelationships)){let r=512;if(Array.isArray(t.fields))for(let o of t.fields)r+=this.estimateEntrySize(o,250);if(Array.isArray(t.childRelationships))for(let o of t.childRelationships)r+=this.estimateEntrySize(o,100);return r}return Array.isArray(e)?e.length*64+64:Object.keys(e).length*64+128}estimateEntrySize(e,t){if(e==null||typeof e!="object")return 16;let r=t;for(let o of Object.values(e))if(typeof o=="string")r+=16+o.length*2;else if(typeof o=="number"||typeof o=="boolean")r+=8;else if(Array.isArray(o)){r+=16;for(let s of o)r+=typeof s=="string"?16+s.length*2:this.estimateEntrySize(s,64)}else r+=16;return r}};export{Tn as a,Fn as b,nd as c,rd as d,sp as e,of as f,sf as g,Ps as h,af as i,df as j,cf as k,Cs as l,uf as m,mf as n,Pa as o,Wl as p,on as q,Or as r,Ir as s,jr as t,Nr as u,Nh as v,Eh as w,Th as x,Fh as y,Ph as z,bf as A,Rf as B,Sf as C,If as D,jf as E,Ds as F,xf as G,Mf as H,_f as I,Lf as J,Df as K,Bf as L,$f as M,Wf as N,qf as O,zf as P,Xf as Q,Ws as R,tp as S,np as T,nr as U,rr as V,Qs as W,Zi as X,Vg as Y,ta as Z,Gg as _,Ep as $,Fd as aa,Tp as ba,Wp as ca,Dn as da,qp as ea,ri as fa,zp as ga,Up as ha,Xd as ia,Vp as ja,ac as ka,nm as la,rm as ma,om as na,mc as oa,Un as pa,Ac as qa,ze as ra,Vn as sa,hi as ta,fm as ua,pm as va,Nc as wa,mm as xa,gm as ya,va as za,Tc as Aa,Fc as Ba,bm as Ca,km as Da,Zn as Ea,Im as Fa,jm as Ga,Nm as Ha,Em as Ia,Ri as Ja,vm as Ka,xm as La,Mm as Ma,_m as Na,Si as Oa,Bm as Pa,$m as Qa,Vm as Ra,Gm as Sa,Jm as Ta,tu as Ua,nu as Va,ru as Wa,ig as Xa,ag as Ya,dg as Za,cg as _a,ug as $a,lg as ab,fg as bb,pg as cb,mg as db,wg as eb,Pu as fb,yg as gb,Yg as hb,na as ib,ra as jb,Qg as kb,th as lb,nh as mb,rh as nb,oh as ob,dh as pb,lh as qb,br as rb,rn as sb,kh as tb,Wh as ub,Fa as vb,qh as wb,zh as xb,Uh as yb};
|
|
@@ -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-5JMQXHJ2.mjs";import"./chunk-GP5J3DGS.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-J347SPU6.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as ARTICLE_VERSION_OBJECT,b as articleBodyFields,c as articleBodyOptions,d as seedKnowledge};
|