sandforge 1.82.0 → 1.84.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-23SEDORH.mjs +11 -0
- package/lib/{chunk-7WSLT5VX.mjs → chunk-24RFOFYT.mjs} +1 -1
- package/lib/chunk-26POJDIT.mjs +7 -0
- package/lib/{chunk-SFGZFB4F.mjs → chunk-2AZQHBEF.mjs} +1 -1
- package/lib/{chunk-6VSZNZHH.mjs → chunk-2HVOZUM4.mjs} +1 -1
- package/lib/{chunk-XFU3HRUV.mjs → chunk-2JDAOWUW.mjs} +1 -1
- package/lib/{chunk-BNKT3R3F.mjs → chunk-2METQHGG.mjs} +1 -1
- package/lib/chunk-2WFIVO4F.mjs +13 -0
- package/lib/chunk-2YHZBUZE.mjs +7 -0
- package/lib/{chunk-SZGGFST2.mjs → chunk-326AJTIU.mjs} +14 -14
- package/lib/{chunk-Q6SXNKV2.mjs → chunk-36JOHEJL.mjs} +1 -1
- package/lib/chunk-3PVRGTVK.mjs +7 -0
- package/lib/{chunk-VZVICK7Q.mjs → chunk-3Q353S2R.mjs} +1 -1
- package/lib/chunk-3TZSBHEY.mjs +7 -0
- package/lib/{chunk-UHFLKP26.mjs → chunk-43TOMFV4.mjs} +1 -1
- package/lib/{chunk-XK5W7BVE.mjs → chunk-4CVUUVGJ.mjs} +1 -1
- package/lib/{chunk-VYOYXTCU.mjs → chunk-4EOHEDFP.mjs} +1 -1
- package/lib/{chunk-EOFO3PHS.mjs → chunk-4JE4BYXK.mjs} +1 -1
- package/lib/{chunk-7EYQYZJP.mjs → chunk-54WZUS7J.mjs} +1 -1
- package/lib/chunk-5CRLRHOJ.mjs +7 -0
- package/lib/{chunk-FA4ZKDCU.mjs → chunk-5IZTFMJM.mjs} +1 -1
- package/lib/chunk-5M5FQ7RP.mjs +7 -0
- package/lib/{chunk-3HROD5RE.mjs → chunk-5SMWFNE7.mjs} +1 -1
- package/lib/{chunk-YAIIRFKJ.mjs → chunk-5XTUSN72.mjs} +1 -1
- package/lib/chunk-6I6TWNV5.mjs +7 -0
- package/lib/{chunk-PYRZFUVU.mjs → chunk-6JWWSDM6.mjs} +1 -1
- package/lib/chunk-6O222PW6.mjs +7 -0
- package/lib/{chunk-2UU42PTD.mjs → chunk-6PD6K7LP.mjs} +1 -1
- package/lib/{chunk-GGUOIDWP.mjs → chunk-6QE6R6RL.mjs} +1 -1
- package/lib/{chunk-DJCGURW7.mjs → chunk-6WX5ZU7Q.mjs} +1 -1
- package/lib/{chunk-DT3T7FRD.mjs → chunk-6YL7BNYD.mjs} +1 -1
- package/lib/chunk-6ZLKIT3H.mjs +7 -0
- package/lib/{chunk-CBL42DUU.mjs → chunk-7QYHEHMA.mjs} +1 -1
- package/lib/chunk-7SQSWVAU.mjs +9 -0
- package/lib/{chunk-ZUBBEP75.mjs → chunk-7UVKIWKV.mjs} +1 -1
- package/lib/{chunk-TWV4A5RK.mjs → chunk-7WATA4SB.mjs} +1 -1
- package/lib/chunk-7YNM6KFZ.mjs +7 -0
- package/lib/chunk-A3MYSOOC.mjs +7 -0
- package/lib/chunk-AL4C3GFT.mjs +7 -0
- package/lib/chunk-B3FBHVNN.mjs +21 -0
- package/lib/{chunk-27Z76O2O.mjs → chunk-B63POIPQ.mjs} +1 -1
- package/lib/{chunk-RTWYLOCA.mjs → chunk-BAWCOKRW.mjs} +1 -1
- package/lib/{chunk-NWOI25WY.mjs → chunk-BBRWFKS5.mjs} +1 -1
- package/lib/chunk-BEA27DLS.mjs +7 -0
- package/lib/chunk-BRY3PLIZ.mjs +7 -0
- package/lib/chunk-CBH3TOWK.mjs +341 -0
- package/lib/chunk-CPQIZGG5.mjs +7 -0
- package/lib/chunk-CVHNXJH3.mjs +7 -0
- package/lib/{chunk-HFUDCNU5.mjs → chunk-D4GF4FAB.mjs} +1 -1
- package/lib/chunk-DGDRQRCW.mjs +7 -0
- package/lib/{chunk-YAJQS3OL.mjs → chunk-DPMRIMUC.mjs} +1 -1
- package/lib/chunk-DUN2EPRC.mjs +7 -0
- package/lib/chunk-E3A3LOCY.mjs +7 -0
- package/lib/{chunk-TMA34QMA.mjs → chunk-EAC5QCE3.mjs} +1 -1
- package/lib/{chunk-VQJMP3DC.mjs → chunk-EC72TIEG.mjs} +1 -1
- package/lib/chunk-EPFCERGL.mjs +7 -0
- package/lib/{chunk-3MGMNK3Q.mjs → chunk-ETDCBLGU.mjs} +1 -1
- package/lib/{chunk-LXDSRP2W.mjs → chunk-F3AQW6IU.mjs} +1 -1
- package/lib/{chunk-A65ADTCR.mjs → chunk-FITPY3L4.mjs} +1 -1
- package/lib/chunk-FNJ4SGWO.mjs +7 -0
- package/lib/{chunk-SAMWHL22.mjs → chunk-FP7CYB2F.mjs} +1 -1
- package/lib/{chunk-JLZRZL5E.mjs → chunk-GKY2JMHY.mjs} +1 -1
- package/lib/chunk-GMIGWR6U.mjs +7 -0
- package/lib/{chunk-AUS6NFLZ.mjs → chunk-GNRSF65U.mjs} +1 -1
- package/lib/chunk-GOOVPVWX.mjs +7 -0
- package/lib/{chunk-PPHVWUFY.mjs → chunk-GWZRR3MM.mjs} +1 -1
- package/lib/{chunk-JH27IKCO.mjs → chunk-H2BHESDA.mjs} +2 -2
- package/lib/chunk-H33DVU3D.mjs +7 -0
- package/lib/chunk-H4CGM6YO.mjs +7 -0
- package/lib/{chunk-WOOUISSO.mjs → chunk-HCGXK7G7.mjs} +1 -1
- package/lib/{chunk-VZT4E2OJ.mjs → chunk-HIDW7FNV.mjs} +1 -1
- package/lib/chunk-HSBXRQTI.mjs +7 -0
- package/lib/chunk-HUZPBE47.mjs +7 -0
- package/lib/chunk-HV7VPEXP.mjs +7 -0
- package/lib/chunk-I6E6T6YY.mjs +7 -0
- package/lib/chunk-IUM4NFKI.mjs +10 -0
- package/lib/chunk-IVFVNNGB.mjs +37 -0
- package/lib/{chunk-5K2I2DMP.mjs → chunk-IZGCEOYO.mjs} +1 -1
- package/lib/{chunk-ZHIZY3ZC.mjs → chunk-J3DND3BC.mjs} +1 -1
- package/lib/{chunk-VPDEJGPS.mjs → chunk-JAEDM4SI.mjs} +1 -1
- package/lib/chunk-JCFBFF4Y.mjs +7 -0
- package/lib/{chunk-GBGHJTPC.mjs → chunk-JE6SCT6R.mjs} +1 -1
- package/lib/chunk-JGZPD4IM.mjs +7 -0
- package/lib/{chunk-C3LNYAVJ.mjs → chunk-JKJ74BX5.mjs} +1 -1
- package/lib/{chunk-EEFUE2ES.mjs → chunk-JLSIWO4Z.mjs} +1 -1
- package/lib/{chunk-3CX7GPCR.mjs → chunk-JSAJS3MY.mjs} +1 -1
- package/lib/chunk-JTJK2D36.mjs +7 -0
- package/lib/{chunk-V3R45ZWT.mjs → chunk-KAZS5Z6W.mjs} +1 -1
- package/lib/chunk-KB4ZHM4Q.mjs +10 -0
- package/lib/{chunk-J24TIGSI.mjs → chunk-KGU4SVIT.mjs} +1 -1
- package/lib/chunk-KJWFYBMU.mjs +15 -0
- package/lib/{chunk-H4JUYUSL.mjs → chunk-KZTZDC7H.mjs} +1 -1
- package/lib/chunk-L2E5WBGD.mjs +8 -0
- package/lib/{chunk-XU25YA46.mjs → chunk-L53JWJ3S.mjs} +1 -1
- package/lib/{chunk-Y4TDVDP2.mjs → chunk-LA4KIATH.mjs} +6 -6
- package/lib/chunk-LC3NDW4N.mjs +7 -0
- package/lib/{chunk-GCGHHN4K.mjs → chunk-LKTNQEBS.mjs} +1 -1
- package/lib/chunk-M2ABR4JM.mjs +7 -0
- package/lib/{chunk-3C2ZZIFN.mjs → chunk-M4BLK6HJ.mjs} +1 -1
- package/lib/{chunk-L4INJ5TZ.mjs → chunk-M6K34KGF.mjs} +1 -1
- package/lib/chunk-MDMPJEV3.mjs +7 -0
- package/lib/{chunk-32EUNQT6.mjs → chunk-MJZU3U5O.mjs} +68 -63
- package/lib/{chunk-PBE44M2Y.mjs → chunk-MSIEU5MR.mjs} +1 -1
- package/lib/{chunk-NLB3RGIY.mjs → chunk-N4WPCWJO.mjs} +1 -1
- package/lib/{chunk-SNEOKYV7.mjs → chunk-NCZKWSC7.mjs} +1 -1
- package/lib/{chunk-6KP6WETK.mjs → chunk-NED4MBIM.mjs} +1 -1
- package/lib/chunk-NOBQTEQD.mjs +7 -0
- package/lib/{chunk-RCYEBY42.mjs → chunk-NSQWI7ZY.mjs} +1 -1
- package/lib/{chunk-DBBPDSFN.mjs → chunk-O677VOGO.mjs} +1 -1
- package/lib/chunk-OFTT7J2M.mjs +7 -0
- package/lib/{chunk-C2N2TNEU.mjs → chunk-OLCVHL7I.mjs} +1 -1
- package/lib/chunk-OM5NORJG.mjs +7 -0
- package/lib/chunk-OMNMLKDT.mjs +7 -0
- package/lib/{chunk-CELEBWEZ.mjs → chunk-OPMO6I45.mjs} +1 -1
- package/lib/{chunk-LHU6CPGE.mjs → chunk-OUZQPYT3.mjs} +1 -1
- package/lib/chunk-OVNMB6Q2.mjs +7 -0
- package/lib/{chunk-6GQUZ4IP.mjs → chunk-PAXNWTYK.mjs} +1 -1
- package/lib/{chunk-XSKPYGMT.mjs → chunk-PBY2O6OF.mjs} +1 -1
- package/lib/chunk-PEDQPM2P.mjs +926 -0
- package/lib/chunk-PH7SP4YK.mjs +21 -0
- package/lib/{chunk-3SKLBRPL.mjs → chunk-PMN4PAC3.mjs} +1 -1
- package/lib/chunk-PMWAFDUB.mjs +48 -0
- package/lib/chunk-PPLVFX6N.mjs +7 -0
- package/lib/{chunk-STRMWSIQ.mjs → chunk-PR3XCSPO.mjs} +1 -1
- package/lib/{chunk-GJ6SZVHT.mjs → chunk-PR42EZSR.mjs} +1 -1
- package/lib/{chunk-YMDFF657.mjs → chunk-PWRJRL5U.mjs} +1 -1
- package/lib/{chunk-Q3DY7TO2.mjs → chunk-Q7GIJBCD.mjs} +1 -1
- package/lib/chunk-Q7TLC3I2.mjs +7 -0
- package/lib/{chunk-ZXFL2MSN.mjs → chunk-QAFPQ3YB.mjs} +1 -1
- package/lib/{chunk-T7WREYA5.mjs → chunk-QKEKG2LD.mjs} +1 -1
- package/lib/chunk-QO53K5W2.mjs +9 -0
- package/lib/{chunk-MUEQRIK7.mjs → chunk-QTG6LUZT.mjs} +1 -1
- package/lib/{chunk-KP5G6FUC.mjs → chunk-RE7RYF3B.mjs} +1 -1
- package/lib/{chunk-FOIWWK7G.mjs → chunk-RGBGUCJA.mjs} +1 -1
- package/lib/{chunk-DWMRIWV5.mjs → chunk-RGUQOSBU.mjs} +1 -1
- package/lib/{chunk-7PY3VQP3.mjs → chunk-RHNTHGNU.mjs} +1 -1
- package/lib/chunk-RKTFFCNS.mjs +7 -0
- package/lib/chunk-RMFU4BAL.mjs +28 -0
- package/lib/{chunk-KKOA62S4.mjs → chunk-ROV3QXEF.mjs} +14 -13
- package/lib/chunk-RT47RKLY.mjs +7 -0
- package/lib/{chunk-ZUTUYBNW.mjs → chunk-S42RBRH2.mjs} +1 -1
- package/lib/{chunk-Z42PHCVZ.mjs → chunk-SI267LYR.mjs} +1 -1
- package/lib/chunk-T3G6VZNS.mjs +7 -0
- package/lib/chunk-TNT27RBG.mjs +7 -0
- package/lib/chunk-UBIKR5VO.mjs +7 -0
- package/lib/chunk-UI3JQVRU.mjs +8 -0
- package/lib/{chunk-YT22LMF7.mjs → chunk-UIOMAX56.mjs} +1 -1
- package/lib/chunk-UX3BVH2Y.mjs +7 -0
- package/lib/chunk-VCUXCK36.mjs +7 -0
- package/lib/chunk-VINGECAJ.mjs +10 -0
- package/lib/chunk-VOXJHJIE.mjs +7 -0
- package/lib/chunk-W6PN6TJG.mjs +7 -0
- package/lib/{chunk-FKK5YBGZ.mjs → chunk-WAPSSYMT.mjs} +1 -1
- package/lib/{chunk-PR74GYVI.mjs → chunk-WUUKFE2U.mjs} +1 -1
- package/lib/chunk-WWTCWWZI.mjs +7 -0
- package/lib/chunk-WXDLQT2O.mjs +10 -0
- package/lib/chunk-WY5V5PR3.mjs +7 -0
- package/lib/chunk-X4BXESMQ.mjs +7 -0
- package/lib/chunk-XBQGZGWR.mjs +7 -0
- package/lib/chunk-XGGOUNPP.mjs +7 -0
- package/lib/chunk-XKWW3GKF.mjs +7 -0
- package/lib/{chunk-JJITOWZK.mjs → chunk-Y2DRK37K.mjs} +1 -1
- package/lib/{chunk-XZISAZA6.mjs → chunk-YA6ATMTB.mjs} +1 -1
- package/lib/{chunk-54HYHHVL.mjs → chunk-YDXMTWAT.mjs} +1 -1
- package/lib/chunk-YHR4WQPR.mjs +7 -0
- package/lib/{chunk-KJYEQHYP.mjs → chunk-YTLUYSMF.mjs} +1 -1
- package/lib/chunk-YWEQQL3C.mjs +8 -0
- package/lib/{chunk-PWVDNN2C.mjs → chunk-Z4LKKOFY.mjs} +1 -1
- package/lib/chunk-ZBAWJUG2.mjs +7 -0
- package/lib/{chunk-XO5FBOQF.mjs → chunk-ZJW6YOMV.mjs} +1 -1
- package/lib/chunk-ZQQXSCVI.mjs +7 -0
- package/lib/{chunk-47UHTN3Q.mjs → chunk-ZQWIVYVM.mjs} +1 -1
- package/lib/chunk-ZV7ZFQQC.mjs +9 -0
- package/lib/sandforge-autopilot.mjs +25 -25
- package/lib/sandforge-backup.mjs +1 -1
- package/lib/sandforge-checkpoint.mjs +1 -1
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +52 -21
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +4 -4
- package/lib/sandforge-env.mjs +106 -107
- package/lib/sandforge-frozen.mjs +1 -1
- package/lib/sandforge-mcp.mjs +12 -12
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +1 -1
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +21 -23
- package/lib/sandforge.mjs +1 -1
- package/lib/sf/sandforge/compare.mjs +2 -2
- package/lib/sfPlugin.mjs +1 -1
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
- package/lib/chunk-2JZGCCPG.mjs +0 -9
- package/lib/chunk-3HEMJTAP.mjs +0 -925
- package/lib/chunk-3XG25GTF.mjs +0 -7
- package/lib/chunk-42BFLWHR.mjs +0 -7
- package/lib/chunk-466F37VD.mjs +0 -7
- package/lib/chunk-4JKR4PTZ.mjs +0 -8
- package/lib/chunk-52EXDVPN.mjs +0 -7
- package/lib/chunk-7CVDVBEE.mjs +0 -7
- package/lib/chunk-7LKI7OAS.mjs +0 -7
- package/lib/chunk-7SDZR6SR.mjs +0 -7
- package/lib/chunk-A32ISQ6M.mjs +0 -28
- package/lib/chunk-A7JJWOLT.mjs +0 -7
- package/lib/chunk-BMTNTBBM.mjs +0 -7
- package/lib/chunk-BN33LVPQ.mjs +0 -7
- package/lib/chunk-BZ24IAP5.mjs +0 -7
- package/lib/chunk-CCEH7L53.mjs +0 -7
- package/lib/chunk-CV47FDQW.mjs +0 -7
- package/lib/chunk-CZLJZQCS.mjs +0 -7
- package/lib/chunk-DIL62SUN.mjs +0 -7
- package/lib/chunk-DIS254AN.mjs +0 -7
- package/lib/chunk-FZF23M6R.mjs +0 -7
- package/lib/chunk-G2JR3F63.mjs +0 -7
- package/lib/chunk-GGNUACTY.mjs +0 -7
- package/lib/chunk-GHPR5UVV.mjs +0 -7
- package/lib/chunk-HIHCYMSL.mjs +0 -7
- package/lib/chunk-HKUWHVI7.mjs +0 -9
- package/lib/chunk-HQQVANWQ.mjs +0 -20
- package/lib/chunk-IRZJU2PG.mjs +0 -22
- package/lib/chunk-ISSP2FZ5.mjs +0 -7
- package/lib/chunk-IVZJSDJD.mjs +0 -7
- package/lib/chunk-JESRFE2Z.mjs +0 -11
- package/lib/chunk-JFNLKHY6.mjs +0 -8
- package/lib/chunk-JKT5YAQ2.mjs +0 -7
- package/lib/chunk-JQZTMFO7.mjs +0 -7
- package/lib/chunk-KIMQQ6JQ.mjs +0 -7
- package/lib/chunk-LAUOSXMN.mjs +0 -341
- package/lib/chunk-MKTXJCXN.mjs +0 -10
- package/lib/chunk-O2PUGRNW.mjs +0 -10
- package/lib/chunk-O4BROUGM.mjs +0 -7
- package/lib/chunk-P55MKIZX.mjs +0 -37
- package/lib/chunk-P63WJMXQ.mjs +0 -7
- package/lib/chunk-PE435FVH.mjs +0 -15
- package/lib/chunk-PPGDAUEQ.mjs +0 -7
- package/lib/chunk-QAPVKPEC.mjs +0 -7
- package/lib/chunk-RLWB7F26.mjs +0 -7
- package/lib/chunk-RYRMUPMY.mjs +0 -7
- package/lib/chunk-SCKUIE3R.mjs +0 -7
- package/lib/chunk-SU65Z2BA.mjs +0 -7
- package/lib/chunk-TCBAE65A.mjs +0 -7
- package/lib/chunk-WEMLDUQA.mjs +0 -7
- package/lib/chunk-WSUKC2U3.mjs +0 -7
- package/lib/chunk-WT3SCUHS.mjs +0 -7
- package/lib/chunk-YGJF55VJ.mjs +0 -7
- package/lib/chunk-YH4DYI6D.mjs +0 -7
- package/lib/chunk-ZQO5PDX5.mjs +0 -48
- package/lib/chunk-ZUOPC4W2.mjs +0 -7
package/lib/chunk-P55MKIZX.mjs
DELETED
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
-
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
-
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
-
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
-
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{C as ts,r as Jo}from"./chunk-O2PUGRNW.mjs";import{A as hn,B as wn,H as ce,I as No,J as St,R as Eo,e as yt,m as So,v as Ao,w as ko,x as Io}from"./chunk-7SDZR6SR.mjs";import{e as ps,h as ms}from"./chunk-TEIBWMJM.mjs";import{a as Fo,b as Po}from"./chunk-T63U4OZJ.mjs";import{a as et,d as Xo,i as es,o as Ne}from"./chunk-YAIIRFKJ.mjs";import{a as vo}from"./chunk-YYZL7UGV.mjs";import{a as ho,l as Ro}from"./chunk-54HYHHVL.mjs";import{d as To}from"./chunk-QIRO4HTE.mjs";import{b as jo}from"./chunk-QSRAEUGZ.mjs";import{d as gs}from"./chunk-JH27IKCO.mjs";import{t as Oe}from"./chunk-SAMWHL22.mjs";import{a as Mo,c as Lo,d as At,e as je,f as _o,g as Do,h as kt,i as Bo,j as $o,k as Wo,l as qo,m as zo,n as Uo,o as se,p as ie,q as It,r as we,s as Vo}from"./chunk-4JKR4PTZ.mjs";import{d as yn,z as Go}from"./chunk-J24TIGSI.mjs";import{a as mo,b as Me,c as go,d as X,h as pe}from"./chunk-VPDEJGPS.mjs";import{a as po}from"./chunk-5LFSFYFJ.mjs";import{Db as is,Eb as as,J as Zo,K as Sn,L as Qo,Pa as Ee,Qa as ns,Ra as ye,ab as Te,db as rs,eb as os,f as to,oc as ds,pc as cs,uc as ls,vc as us,wc as fs,xc as me,zb as ss}from"./chunk-JFNLKHY6.mjs";import{b as Ot}from"./chunk-VV3B6IC3.mjs";import{f as Et}from"./chunk-7PY3VQP3.mjs";import{a as no,b as ro,c as fn,e as oo,f as so,g as io,i as pn,j as ao}from"./chunk-INIT2UKJ.mjs";import{a as bo,c as gn,j as Oo}from"./chunk-HFUDCNU5.mjs";import{f as uo,g as fo}from"./chunk-XZISAZA6.mjs";import{a as q,b as le,c as jt,d as bn,e as Ho,f as Nt,g as Ko,h as Rn,i as Yo}from"./chunk-TQ2TQHTT.mjs";import{g as lo}from"./chunk-OHEOJISY.mjs";import{a as Co,b as xo}from"./chunk-PC247GKX.mjs";import{c as co}from"./chunk-EADHKH3A.mjs";import{b as Xr,r as eo}from"./chunk-L4INJ5TZ.mjs";import{A as Wr,B as ln,C as qr,F as zr,G as un,J as Ur,K as Vr,O as Gr,R as Jr,S as Hr,T as Kr,U as Yr,V as Zr,W as Qr,e as cn,q as de,r as oe,s as xe,x as Br,y as $r}from"./chunk-KIMQQ6JQ.mjs";import{a as Ce,h as J}from"./chunk-TZE3Y7IQ.mjs";import{a as wt,b as H}from"./chunk-CA5NAXSU.mjs";import{a as bt,c as mn,f as wo,i as Rt,k as yo}from"./chunk-ZUTUYBNW.mjs";import{Aa as Tr,Ba as Fr,Ca as Pr,Cc as ht,O as Ze,T as sn,Uc as Se,Ya as vr,_ as an,fc as Cr,hd as Lr,lc as xr,mc as Mr,nc as Qe,oc as pt,rc as Xe,sc as dn,tc as mt,td as _r,ua as Re,ud as Dr,va as Er,yc as ve,zc as gt}from"./chunk-ZQO5PDX5.mjs";import{b as W,e as te,f as Ke,i as Ie,k as Z,l as V,m as rn,r as Nr,s as on,u as Pe,v as Ye}from"./chunk-WZQEK4WT.mjs";var Le=.5;function xu(n){return`Salesforce can take several minutes to count a load in what ${n} says it has left: a run started sooner after another may read room it no longer has`}function ws(n){if("unread"in n.storage)return n.withinMB===void 0?{unread:n.storage.unread}:hs(n,Math.floor(Math.max(0,n.withinMB)*1048576),{share:Ee,roundingMB:Le,withinMB:n.withinMB,limitedBy:"within"});let{remainingMB:e,maxMB:t}=n.storage,r=Ee*Math.max(0,e-Le)*1048576,o=n.withinMB!==void 0?Math.max(0,n.withinMB)*1048576:1/0,s=o<r?"within":"storage",i={remainingMB:e,maxMB:t,share:Ee,roundingMB:Le,...n.withinMB!==void 0?{withinMB:n.withinMB}:{},limitedBy:s},a=Math.floor(Math.min(r,o));return hs(n,a,i)}function ys(n,e){return e.bytesLimit==="within"&&e.storageBytes!==void 0&&n>e.storageBytes?"storage":e.bytesLimit}function hs(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-Te*n.api.max-r));return{bytes:e,terms:t,runRequests:o}}var wa=/__e$/i,ya=/Share$/;function Mu(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(wa.test(d))continue;if(ya.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 Lu(n,e){return n.perRecord.reduce((t,r)=>t+r.bytes*Math.max(0,e(r.objectApiName,r.act)),0)}function _u(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 bs(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 Du(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 ba,readFileSync as Ra,writeFileSync as Sa}from"node:fs";function qu(n){let e={getData:()=>ba(n)?JSON.parse(Ra(n,"utf8")):{},setData:r=>Sa(n,JSON.stringify(r,null,2),{encoding:"utf8",mode:384})},t=new ts(e);return t.initialize(),t}var On="User",Oa="005",Ss=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function Aa(n,e,t=Xr){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 Rs=1e5;async function Ju(n){let{known:e,ownerMappings:t={},mapped:r,refused:o,inactive:s}=n,i=n.lookups.filter(m=>Aa(m,n.outsideTheRun,n.neverCopied)),a=new Map,d=new Set;for(let m of i)for(let h of n.rows){let w=h[m.name];if(typeof w!="string"||!Ss.test(w)||m.name==="OwnerId"&&t[w]!==void 0||r?.(w)===!0||(d.add(w),e.has(w)))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(w))}let c=new Set,f=new Set,u=new Set;for(let[m,h]of a){let w=s!==void 0&&m===On,y=w?"Id, IsActive":"Id";for(let R of X([...h]))try{let O=await n.query(`SELECT ${y} FROM ${J(m)} WHERE Id IN (${R})`);for(let g of O){let b=g.Id;typeof b=="string"&&(c.add(b),c.add(b.slice(0,15)),w&&g.IsActive===!1&&(u.add(b),u.add(b.slice(0,15))))}}catch{for(let O of h)f.add(O);o?.add(m);break}}let p=new Map;for(let m of a.values())for(let h of m)c.has(h)||c.has(h.slice(0,15))?p.set(h,!0):!f.has(h)&&!p.has(h)&&p.set(h,!1);for(let[m,h]of p){if(e.size>=Rs)break;e.set(m,h)}if(s&&u.size>0){let m=[...a.get(On)??[]].filter(h=>u.has(h)||u.has(h.slice(0,15)));for(let h of[...u,...m]){if(s.size>=Rs)break;s.add(h)}}let l=new Set;for(let m of d)(p.get(m)??e.get(m))===!1&&l.add(m);return l}function Hu(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 ka="SELECT PermissionsUpdateWithInactiveOwner FROM UserPermissionAccess";async function Ia(n){try{let[e]=await n(ka);return e?.PermissionsUpdateWithInactiveOwner===!0}catch{return!1}}function Ku(n){let e;return()=>(e??=Ia(n),e)}async function Os(n,e){let t=new Map;for(let[i,a]of Object.entries(n)){if(!Ss.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+=Me){let a=s.slice(i,i+Me),[d]=X(a.map(({user:u})=>u)),c;try{c=await e(`SELECT Id, Name, IsActive FROM ${On} WHERE Id IN (${d})`)}catch{continue}let f=new Set;for(let u of c){let p=u.Id;if(typeof p!="string"||(f.add(p.slice(0,15)),u.IsActive!==!1))continue;let l=t.get(p.slice(0,15));if(!l)continue;let m=u.Name;r.push({user:l.user,...typeof m=="string"&&m!==""?{name:m}:{},sources:l.sources})}for(let{user:u,sources:p}of a)u.startsWith(Oa)&&!f.has(u.slice(0,15))&&o.push({user:u,sources:p})}return{inactive:r,unknown:o}}var Tt=10,An="Nothing was read or written.",Xu="Nothing was written.";function As(n,e=An){let t=n.slice(0,Tt).map(({user:o,name:s,sources:i})=>`${s!==void 0?`${s} (${o})`:o}, given the records of `+i.join(", ")).join("; "),r=n.length-Tt;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 ja(n,e=An){let t=n.slice(0,Tt).map(({user:o,sources:s})=>`${o}, given the records of ${s.join(", ")}`).join("; "),r=n.length-Tt;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 ef(n,e,t=An){let{inactive:r,unknown:o}=await Os(n,e);if(o.length>0){let s=ja(o,t);return new me(fs,r.length>0?`${s.slice(0,-t.length)}${As(r,t)}`:s)}return r.length>0?new me(us,As(r,t)):void 0}import{createHash as Na}from"node:crypto";var js={ContentVersion:"VersionData",Attachment:"Body"},Ea=3,ks=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 Is(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0}function kn(n,e,t){return{objectApiName:n,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:e,messages:[H(t)]}]}}async function cf(n){let{scope:e,sourceOrgId:t,maxFileBytes:r,queryRecords:o}=n,s=new Map;for(let u of e.values())for(let p of u)s.has(p)||s.set(p,s.size);let i={files:[],leftOut:[],errors:[]},a=[...s.keys()];if(a.length===0)return i;let d=u=>s.get(u)??Number.MAX_SAFE_INTEGER,c=new Map;try{for(let u of X(a)){let p=await o(t,`SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility FROM ContentDocumentLink WHERE LinkedEntityId IN (${u})`);for(let l of p){let m=Y(l,"ContentDocumentId"),h=Y(l,"LinkedEntityId");if(!m||!h||!s.has(h))continue;let w=c.get(m)??[];w.some(y=>y.id===h)||w.push({id:h,shareType:Y(l,"ShareType"),visibility:Y(l,"Visibility")}),c.set(m,w)}}}catch(u){i.errors.push(kn("ContentDocument","(links of the records in scope)",u))}let f=[];try{for(let u of X([...c.keys()])){let p=await o(t,`SELECT Id, ContentDocumentId, Title, PathOnClient, ContentSize, ContentLocation, SharingPrivacy FROM ContentVersion WHERE ContentDocumentId IN (${u}) AND IsLatest = true`);for(let l of p){let m=Y(l,"ContentDocumentId"),h=Y(l,"Id"),w=m?c.get(m):void 0;if(!m||!h||!w)continue;let y=Y(l,"Title")??m;f.push({external:(Y(l,"ContentLocation")??"S")!=="S",file:{objectApiName:"ContentDocument",sourceId:m,body:{objectApiName:"ContentVersion",id:h},name:y,bytes:Is(l,"ContentSize"),hosts:[...w].sort((R,O)=>d(R.id)-d(O.id)),fields:{Title:y,PathOnClient:Y(l,"PathOnClient")??y,...Y(l,"SharingPrivacy")==="P"?{SharingPrivacy:"P"}:{}}}})}}}catch(u){i.errors.push(kn("ContentDocument","(latest versions of the files)",u))}try{for(let u of X(a)){let p=await o(t,`SELECT Id, ParentId, Name, ContentType, BodyLength, IsPrivate FROM Attachment WHERE ParentId IN (${u})`);for(let l of p){let m=Y(l,"Id"),h=Y(l,"ParentId");if(!m||!h||!s.has(h))continue;let w=Y(l,"Name")??m;f.push({external:!1,file:{objectApiName:"Attachment",sourceId:m,body:{objectApiName:"Attachment",id:m},name:w,bytes:Is(l,"BodyLength"),hosts:[{id:h}],fields:{Name:w,...Y(l,"ContentType")?{ContentType:Y(l,"ContentType")}:{},IsPrivate:l.IsPrivate===!0}}})}}}catch(u){i.errors.push(kn("Attachment","(attachments of the records in scope)",u))}f.sort((u,p)=>d(u.file.hosts[0].id)-d(p.file.hosts[0].id));for(let{file:u,external:p}of f){let l=p?"external":u.bytes>r?"too-large":void 0;l?i.leftOut.push({objectApiName:u.objectApiName,sourceId:u.sourceId,name:u.name,bytes:u.bytes,reason:l}):i.files.push(u)}return i}function lf(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 uf(n){let{files:e,targetOrgId:t,copiedBefore:r,queryRecords:o}=n,s={files:[],errors:[]},i=new Map;for(let l of e){let m=r(l.sourceId);m&&i.set(l.sourceId,m)}if(i.size===0)return{...s,files:[...e]};let a=new Map,d,c=new Map;for(let[l,m]of i)m.objectApiName==="ContentVersion"&&c.set(m.targetId,l),m.objectApiName==="ContentDocument"&&a.set(l,m.targetId);try{for(let l of X([...c.keys()])){let m=await o(t,`SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id IN (${l})`);for(let h of m){let w=Y(h,"Id"),y=Y(h,"ContentDocumentId"),R=w?c.get(w):void 0;R&&y&&a.set(R,y)}}}catch(l){d=H(l)}let f=new Map,u;try{for(let l of X([...new Set(a.values())])){let m=await o(t,`SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN (${l})`);for(let h of m){let w=Y(h,"ContentDocumentId"),y=Y(h,"LinkedEntityId");w&&y&&f.set(w,[...f.get(w)??[],y])}}}catch(l){u=H(l)}let p=(l,m)=>{s.errors.push({objectApiName:"ContentDocument",stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`${l.name} (${Se(l.bytes)})`,messages:[m]}]})};for(let l of e){let m=i.get(l.sourceId);if(!m){s.files.push(l);continue}if(l.body.objectApiName==="Attachment")continue;let h=a.get(l.sourceId);if(!h){p(l,`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(u){p(l,`Copied by the run this one takes up; its links could not be read (${u}): it is not linked to the records it lacks.`);continue}s.files.push({...l,into:{documentId:h,linked:f.get(h)??[],unchanged:!0}})}return s}function ff(n){return{objectApiName:"__files__",stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(files)",messages:[n]}]}}function pf(n){return n.reduce((e,t)=>e+t.bytes,0)}function mf(n,e){return n<=e?null:`The files to copy take ${Se(n)} and the target has ${Se(Math.max(0,e))} of file storage left. Lower the largest file copied, or leave the files out.`}async function gf(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 hf(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 In(n,e){let t=n==="Attachment"?"attachment":"file";return e===1?t:`${t}s`}function wf(n){return`[dry-run] ${n.objectApiName}: ${n.planned} ${In(n.objectApiName,n.planned)} would be copied (${Se(n.plannedBytes)})`}function Ta(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:Na("md5").update(Buffer.from(e,"base64")).digest("hex"),ContentSize:n.bytes}}function Fa(n){let e={};for(let[t,r]of Object.entries(n))t!=="SharingPrivacy"&&(e[t]=r);return e}async function yf(n){let{files:e,sourceOrgId:t,targetOrgId:r,remapper:o,deps:s,report:i,errors:a,onProgress:d,onCopied:c}=n,f=0,u=g=>{let b=i.objects.find(A=>A.objectApiName===g);return b||(b={objectApiName:g,planned:0,plannedBytes:0,copied:0,failed:0},i.objects.push(b)),b},p=(g,b)=>a.find(A=>A.objectApiName===g&&A.stage===b),l=new Map,m=(g,b,A=1)=>{let N=`${g}/${b}`;l.set(N,(l.get(N)??0)+A);let x=p(g,b);x&&(x.attemptedCount+=A)},h=(g,b,A,N,x=!1)=>{let v=p(g,b);v||(v={objectApiName:g,stage:b,failedCount:0,attemptedCount:l.get(`${g}/${b}`)??0,samples:[]},a.push(v)),x||(v.failedCount++,f++),v.samples.length<Ea&&v.samples.push({recordSummary:A,messages:[N]})},w=(g,b,A)=>{h(g.objectApiName,b,`${g.name} (${Se(g.bytes)})`,A),u(g.objectApiName).failed++},y=async(g,b,A)=>{let N=A.flatMap(v=>{let P=o.get(v.id);return P?[{ContentDocumentId:b,LinkedEntityId:P,ShareType:v.shareType??"V",Visibility:v.visibility??"AllUsers"}]:[]});if(N.length===0)return[];let x=[];m("ContentDocumentLink","insert",N.length);try{let v=await s.insertRecords(r,"ContentDocumentLink",N);N.forEach((P,k)=>{let j=v[k];if(j?.success){i.links++,x.push(P.LinkedEntityId);return}h("ContentDocumentLink","insert",g.name,j?.errors.join("; ")||"The target gave no reason.")})}catch(v){for(let P=0;P<N.length;P++)h("ContentDocumentLink","insert",g.name,H(v))}return x},R=e.filter(g=>!(g.body.objectApiName==="ContentVersion"&&g.into?.unchanged)).length,O=0;for(let g of e){await n.waitIfPaused();let b=g.hosts.filter(I=>o.isCreated(I.id)),A=g.body.objectApiName==="ContentVersion"?g.into:void 0,N=A?b.filter(I=>{let C=o.get(I.id);return C!==void 0&&!A.linked.includes(C)}):[];if(A?.unchanged){let I=await y(g,A.documentId,N);I.length>0&&c?.(g,{targetId:A.documentId,linked:I,asVersion:!1});continue}let x=O++,v=b.length>0?o.get(b[0].id):void 0;if(!v&&!A){i.leftOut.push({objectApiName:g.objectApiName,sourceId:g.sourceId,name:g.name,bytes:g.bytes,reason:"record-not-created"});continue}d({objectName:g.objectApiName,status:"running",progress:Math.round(x/R*100),message:`Copying ${In(g.objectApiName,1)} ${x+1} of ${R} (${Se(g.bytes)})`});let P;m(g.objectApiName,"query");try{P=await s.readFileBody(t,g.body.objectApiName,g.body.id)}catch(I){w(g,"query",H(I));continue}let k=Buffer.byteLength(P,"base64");if(k!==g.bytes){w(g,"query",`Read ${k} bytes of the ${g.bytes} the source reports: the file was not written.`);continue}let j=A?{...Fa(g.fields),VersionData:P,ContentDocumentId:A.documentId}:g.body.objectApiName==="ContentVersion"?{...g.fields,VersionData:P,FirstPublishLocationId:v}:{...g.fields,Body:P,ParentId:v},M;m(g.objectApiName,"insert");let D=n.calls?.sending(g.body.objectApiName,[{sourceId:g.sourceId,payload:Ta(g,P,v)}]),E=()=>{D!==void 0&&n.calls?.answered(D)};try{M=await s.insertFile(r,g.body.objectApiName,j)}catch(I){vo(I)!=="may-have-written"&&E(),w(g,"insert",H(I));continue}if(!M.success||!M.id){E(),w(g,"insert",M.errors.join("; ")||"The target gave no reason.");continue}if(u(g.objectApiName).copied++,g.body.objectApiName==="Attachment"){o.add(g.sourceId,M.id,"Attachment"),E(),o.persist?.(),c?.(g,{targetId:M.id,linked:v?[v]:[],asVersion:!1});continue}if(A){o.add(g.sourceId,A.documentId,"ContentDocument"),E(),o.persist?.();let I=await y(g,A.documentId,N);c?.(g,{targetId:A.documentId,linked:I,asVersion:!0});continue}o.add(g.sourceId,M.id,"ContentVersion"),E(),o.persist?.();let F;try{let I=await s.queryRecords(r,`SELECT ContentDocumentId FROM ContentVersion WHERE Id = '${Ce(M.id)}'`);F=I[0]?Y(I[0],"ContentDocumentId"):void 0}catch{F=void 0}if(!F){h("ContentDocument","query",`${g.name} (${Se(g.bytes)})`,`Copied as ContentVersion ${M.id}, but its document could not be read back: the run keeps the version, which a removal of the run takes with its document, and links it to no other record.`,!0);continue}o.add(g.sourceId,F,"ContentDocument"),o.persist?.();let S=await y(g,F,b.slice(1));c?.(g,{targetId:F,linked:v?[v,...S]:S,asVersion:!1})}for(let g of i.objects)d({objectName:g.objectApiName,status:g.failed>0&&g.copied===0?"error":"done",progress:100,message:`Copied ${g.copied} ${In(g.objectApiName,g.copied)} of ${g.planned}`+(g.failed>0?`, ${g.failed} failed`:"")});return f}function If(n,e,t={},r){if(!n)return;let o={};for(let s of e.nodes)es(s)&&(o[s.objectApiName]=[...s.anonymizeFields]);return{fields:o,methods:{...t},...r?{personalFieldsOf:r}:{}}}var Pa=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,va=/@example\.com$/i,jn="@example.invalid",Ca=64,xa=new Set(["fake","mask","preserve_format","shuffle"]);function Ma(n,e,t){return typeof n!="string"||n===""?n:Pa.test(n)?e.email(n.replace(va,jn),t):`${n.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,Ca).replace(/^[._]+|[._]+$/g,"")||"anonymized"}${jn}`}var Ns=class{smartAnonymizer;contactPoints;constructor(e,t){this.smartAnonymizer=new To(e),this.contactPoints=new ms(t)}categorizeField(e,t){let r=t.toLowerCase();if(r==="email")return"email";if(r==="phone")return"phone";let o=Po(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"||Fo(e)?"name":s.includes("street")||s.includes("address")||s.includes("city")||s.includes("state")||s.includes("postalcode")||s.includes("zip")||s.includes("country")?"address":s.includes("ssn")||s.includes("national_id")||s.includes("passport")||s.includes("driver")||s.includes("license")?"ssn_id":s.includes("credit")||s.includes("card")||s.includes("cvv")||s.includes("iban")||s.includes("routing")||s.includes("bank")?"financial":"other"}getDefaultMethod(e){return{email:"fake",phone:"mask",name:"fake",address:"fake",ssn_id:"redact",financial:"hash",other:"nullify"}[e]}getDefaults(){return{email:"fake",phone:"mask",name:"fake",address:"fake",ssn_id:"redact",financial:"hash",other:"nullify"}}anonymize(e){if(e.fields.length===0)return e.records;let t={...this.getDefaults(),...e.methods},r=e.records.map((a,d)=>({...a,Id:e.sourceIds[d]??""})),o=this.anonymizeRecords(r,e.fields,t,e.objectApiName),s=e.fields.filter(a=>this.categorizeField(a.name,a.type)==="email"),i=xa.has(t.phone)?e.fields.filter(a=>this.categorizeField(a.name,a.type)==="phone"):[];return o.map((a,d)=>{let c=e.records[d],f={...a};for(let u of s)f[u.name]=this.undeliverable(f[u.name],u);for(let u of i)f[u.name]=this.fictionalNumber(c[u.name],f[u.name],u);return"Id"in c?f.Id=c.Id:delete f.Id,f})}undeliverable(e,t){let r=t.length!==void 0&&t.length>0?t.length:void 0;return t.type.toLowerCase()==="email"?Ma(e,this.contactPoints,r??ps):typeof e!="string"?e:this.contactPoints.addressesIn(e.replace(/@example\.com(?![\w.-])/gi,jn),r)}fictionalNumber(e,t,r){if(typeof e!="string")return t;if(!/\d/.test(e))return e;let o=r.length!==void 0&&r.length>0?r.length:void 0;return this.contactPoints.phone(e,o)}anonymizeRecords(e,t,r,o){let s=t.map(a=>{let d=this.categorizeField(a.name,a.type);return{objectApiName:o,fieldApiName:a.name,method:r[d],piiCategory:"PII",aiConfidence:1,userOverridden:!1}}),i=e.map(a=>({...a}));return this.smartAnonymizer.anonymize(i,s,o)}};var Es=new WeakMap;function Nf(n,e){typeof n=="object"&&n!==null&&Es.set(n,e)}function Ef(n){return typeof n=="object"&&n!==null?Es.get(n):void 0}var Nn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Ts=/^[A-Za-z][A-Za-z0-9_]*$/;function tt(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"||!Nn.test(r))&&!(typeof o!="string"||!Nn.test(o)))return{tag:t,sourceId:r,targetId:o,object:typeof s=="string"&&Ts.test(s)?s:""}}function _e(n){if(!n.startsWith(`["${kt}"`))return;let e;try{e=JSON.parse(n)}catch{return}if(!Array.isArray(e))return;let[,t,r]=e;if(!(typeof t!="string"||!Ts.test(t)||!Array.isArray(r)))return{object:t,ids:r.filter(o=>typeof o=="string"&&Nn.test(o))}}function nt(n){return n.slice(0,15)}var rt=class{offsets=new Float64Array(64);lengths=new Uint16Array(64);size=0;push(e,t){if(this.size===this.offsets.length){let r=new Float64Array(this.size*2);r.set(this.offsets),this.offsets=r;let o=new Uint16Array(this.size*2);o.set(this.lengths),this.lengths=o}this.offsets[this.size]=e,this.lengths[this.size]=t,this.size++}offsetAt(e){return this.offsets[e]}lengthAt(e){return this.lengths[e]}},be=class{capacity=1024;used=0;h1=new Uint32Array(this.capacity);h2=new Uint32Array(this.capacity);taken=new Uint8Array(this.capacity);add(e){let t=se(e),r=ie(e);if(this.slotOf(t,r)>=0)return;this.used+1>this.capacity*.6&&this.grow();let o=this.freeSlotFor(r);this.h1[o]=t,this.h2[o]=r,this.taken[o]=1,this.used++}has(e){return this.slotOf(se(e),ie(e))>=0}get size(){return this.used}slotOf(e,t){let r=this.capacity-1;for(let o=t&r;;o=o+1&r){if(this.taken[o]===0)return-1;if(this.h1[o]===e&&this.h2[o]===t)return o}}freeSlotFor(e){let t=this.capacity-1,r=e&t;for(;this.taken[r]!==0;)r=r+1&t;return r}grow(){let{h1:e,h2:t,taken:r}=this;this.capacity*=2,this.h1=new Uint32Array(this.capacity),this.h2=new Uint32Array(this.capacity),this.taken=new Uint8Array(this.capacity);for(let o=0;o<r.length;o++){if(r[o]===0)continue;let s=this.freeSlotFor(t[o]);this.h1[s]=e[o],this.h2[s]=t[o],this.taken[s]=1}}},La=2e3,ot=class n{constructor(e,t,r,o,s){this.file=e;this.all=t;this.mine=r;this.firstInPart=o;this.unattributed=s}file;all;mine;firstInPart;unattributed;static read(e,t){let r=(f,u)=>tt(e.read(f,u).toString("utf8"))?.sourceId??"",o=new It(r),s=new It(r),i=new rt,a=new rt,d=!1,c=-1;for(let f of we(e)){if(!d){if(!f.text.startsWith('{"run":'))return;d=!0;continue}if(f.text.startsWith('{"part":')){c++;continue}if(f.text.startsWith('{"object":'))return;if(c===t&&_e(f.text)){a.push(f.offset,f.length);continue}let u=tt(f.text);if(!u)continue;let p=se(u.sourceId),l=ie(u.sourceId);if(o.put(o.find(u.sourceId,p,l),p,l,f.offset,f.length,0),c!==t)continue;let m=s.find(u.sourceId,p,l);m<0&&i.push(f.offset,f.length);let h=u.tag==="c"&&u.object!=="";s.put(m,p,l,f.offset,f.length,h?1:0)}return d?new n(e,o,s,i,a):void 0}mappingAt(e,t){return tt(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 rt;i.push(o.latest.offset,o.latest.length),e.set(s.object,i)}return e}runRecords(e,t=La){let{file:r}=this,o=(h,w)=>tt(r.read(h,w).toString("utf8")),s=(h,w)=>{let y=o(h,w);return y?nt(y.targetId):""},i=new It(s),a=this.createdByObject(),d=[];for(let h of[...a.keys()].reverse()){let w=a.get(h);if(!w)continue;let y=0;for(let R=w.size-1;R>=0;R--){let O=w.offsetAt(R),g=o(O,w.lengthAt(R));if(!g||g.object==="")continue;let b=nt(g.targetId),A=se(b),N=ie(b),x=i.find(b,A,N);x>=0||(i.put(x,A,N,O,w.lengthAt(R),0),(!e||e.has(b))&&y++)}y>0&&d.push({objectApiName:h,count:y})}let c=(h,w)=>{let y=i.find(h,se(h),ie(h),w);return y>=0&&(w===void 0||i.offsetOf(y)===w)&&(!e||e.has(h))},f=h=>_e(r.read(this.unattributed.offsetAt(h),this.unattributed.lengthAt(h)).toString("utf8")),u=new be,p=this.unattributed.size,l=new Map;for(let h=0;h<p;h++){let w=f(h);if(w)for(let y of w.ids){let R=nt(y);u.has(R)||i.find(R,se(R),ie(R))>=0||(u.add(R),(!e||e.has(R))&&l.set(w.object,(l.get(w.object)??0)+1))}}for(let[h,w]of l){let y=d.find(R=>R.objectApiName===h);y?y.count+=w:d.unshift({objectApiName:h,count:w})}let m=h=>u.size>0&&u.has(h)&&(!e||e.has(h));return{objects:d,pages:async function*(h){let w=a.get(h),y=[];if(w)for(let R=w.size-1;R>=0;R--){let O=w.offsetAt(R),g=o(O,w.lengthAt(R));if(!g||g.object==="")continue;let b=nt(g.targetId);c(b,O)&&(y.push(g.targetId),y.length>=t&&(yield y,y=[]))}if(l.has(h)){let R=new be;for(let O=0;O<p;O++){let g=f(O);if(g?.object===h)for(let b of g.ids){let A=nt(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:h=>c(h)||m(h)}}*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=tt(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 Ae=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,st=/^[A-Za-z][A-Za-z0-9_]*$/,_a=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/,Da=255,Ba=40,$a=2*6e4,Wa=10*6e4;function $f(n){let[e]=n;return e?Object.keys(e).filter(t=>t!=="Id"&&st.test(t)).filter(t=>n.every(r=>qa(r[t]))).sort().slice(0,Ba):[]}function qa(n){return typeof n=="string"?n.trim()!==""&&n.length<=Da:typeof n=="number"?Number.isFinite(n):typeof n=="boolean"}function za(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(Ae.test(e))return e.slice(0,15);if(_a.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 Tn(n,e){return Fn(e.map(t=>`${t}${za(n[t])}`).join(""))}function Fn(n){return se(n).toString(36).padStart(7,"0")+ie(n).toString(36).padStart(7,"0")}function Wf(n){let e=bo("insert",n);return e.rows.map(t=>Fn(gn(e.columns.map((r,o)=>[r,t[o]??""]))))}var Ua=/^sf__/;function Fs(n){let e=[];for(let[t,r]of Object.entries(n))Ua.test(t)||e.push([t,typeof r=="string"?r:r==null?"":String(r)]);return Fn(gn(e))}function vs(n,e){return Tn(n,[e])}function Va(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"||!st.test(o)||typeof s!="string"||!Ae.test(s))return!1;e[r].owes.push({field:o,sourceRefId:s,...i===1?{insertOnly:!0}:{}})}return!0}function En(n){if(!n.startsWith(`["${At}"`))return;let e;try{e=JSON.parse(n)}catch{return}if(!Array.isArray(e)||e.length<6)return;let[,t,r,o,s,i,a,d]=e;if(typeof t!="string"||typeof r!="string"||!st.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"&&st.test(p))||d!==void 0&&(typeof d!="string"||!st.test(d)))return;let f=[];for(let p of i){if(!Array.isArray(p)||p.length<2)return;let[l,m,h,w]=p;if(typeof l!="string"||!Ae.test(l)||typeof m!="string"||h!==void 0&&typeof h!="string"||w!==void 0&&typeof w!="string")return;f.push({sourceId:l,fingerprint:m,owes:[],...typeof h=="string"&&h!==""?{externalKey:h}:{},...typeof w=="string"&&w!==""?{jobKey:w}:{}})}let u=a!==void 0;if(!(u&&!Va(a,f)))return{callId:t,objectApiName:r,at:c,fields:s,rows:f,owesKept:u,...typeof d=="string"?{upsertField:d}:{}}}function Cs(n){if(n.startsWith(`["${je}"`))try{let e=JSON.parse(n);return Array.isArray(e)&&typeof e[1]=="string"?e[1]:void 0}catch{return}}function Ga(n){if(n.startsWith(`["${Do}"`))try{let e=JSON.parse(n);return Array.isArray(e)&&typeof e[1]=="string"?e[1]:void 0}catch{return}}function Ja(n){if(n.startsWith(`["${_o}"`))try{let e=JSON.parse(n);if(!Array.isArray(e))return;let[,t,r]=e;return typeof t!="string"||typeof r!="string"||r===""?void 0:{callId:t,jobId:r}}catch{return}}function Ha(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"||!Ae.test(t)||!Ae.test(r)?void 0:{sourceId:t,targetId:r,object:typeof o=="string"?o:""}}catch{return}}function Ka(n){let e=/"(?:startedAt|at)":"([^"]{10,40})"/.exec(n);return e?Date.parse(e[1]):Number.NaN}function qf(n){return{queryPages:e=>co({query:async t=>n.query(t),queryMore:async t=>n.queryMore(t)},e),userId:async()=>(await n.identity()).user_id,serverTime:async()=>(await n.soap.getServerTimestamp()).timestamp,readJob:e=>Ro(So(n),e)}}function Ya(){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 Ps(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function Pn(n,e,t){return[JSON.stringify(["c",e.sourceId,t,n.objectApiName,n.owesKept?Wo:$o]),...e.owes.map(({field:r,sourceRefId:o,insertOnly:s})=>Uo({objectApiName:n.objectApiName,newId:t,sourceId:e.sourceId,fieldName:r,sourceRefId:o,...s?{insertOnly:s}:{}}))]}function Za(n,e,t,r){let{call:o,rows:s,read:i}=n,{objectApiName:a}=o,d=JSON.stringify([je,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(u=>u.jobKey!==void 0)?Qa(o,s,i.results,e,t,r):Xa(o,s,i.results,e,t,r),f=Date.parse(i.info.systemModstamp??"");return!n.endKept&&c.taken.length>0&&Number.isFinite(f)&&c.lines.unshift(qo(o.callId,n.jobId,new Date(f).toISOString(),new Date(f-n.ahead).toISOString())),c}function Qa(n,e,t,r,o,s){let{objectApiName:i}=n,a=new Map,d=new Set;for(let O of t.successfulResults??[]){let g=O.sf__Id,b=Fs(O);if(typeof g!="string"||!Ae.test(g)){d.add(b);continue}let A=g.slice(0,15);r.has(A)&&!o.has(A)||a.set(b,[...a.get(b)??[],g])}let c=new Set,f=t.unprocessedRecords;for(let O of[...t.failedResults??[],...Array.isArray(f)?f:[]])c.add(Fs(O));let u=new Map;for(let O of e){let g=O.jobKey??"";u.set(g,[...u.get(g)??[],O])}let p=[],l=[],m=[],h=0,w=!1,y=0;for(let[O,g]of u){let b=a.get(O)??[];a.delete(O);let A=d.delete(O);if(g.length===1&&b.length===1&&!A){p.push(...Pn(n,g[0],b[0])),l.push(b[0]),K(s.found,i);continue}if(b.length>0||A){K(s.uncertain,i,g.length),g.length>1&&K(s.untold??=[],i,g.length),A||(y+=g.length),m.push(...b),w=!0;continue}if(g.length>1||c.has(O)){K(s.notFound,i,g.length);continue}h+=g.length}let R=d.size>0;for(let O of a.values())m.push(...O),O.length>0&&(R=!0);return h>0&&(K(R?s.uncertain:s.notFound,i,h),R&&(w=!0,d.size===0&&(y+=h))),y>0&&K(s.ofEndedJobs??=[],i,y),p.push(...xs(n,m,o,w,s)),{lines:p,taken:[...l,...m]}}function xs(n,e,t,r,o){e.length>0&&K(o.unattributed??=[],n.objectApiName,e.length);let s=e.filter(i=>!t.has(i.slice(0,15)));return[...s.length>0?[JSON.stringify([kt,n.objectApiName,s])]:[],...r?[]:[JSON.stringify([je,n.callId])]]}function Xa(n,e,t,r,o,s){let{objectApiName:i}=n,a=n.upsertField,d=new Map;for(let w of t.successfulResults??[]){let y=w.sf__Id;if(typeof y!="string"||!Ae.test(y))continue;let R=y.slice(0,15);if(r.has(R)&&!o.has(R)||a!==void 0&&String(w.sf__Created).toLowerCase()!=="true")continue;let O=a!==void 0?vs(w,a):Tn(w,n.fields);d.set(O,[...d.get(O)??[],y])}let c=new Map;for(let w of e){let y=a!==void 0?w.externalKey??"":w.fingerprint;c.set(y,[...c.get(y)??[],w])}let f=[],u=[],p=[],l=0,m=!1;for(let[w,y]of c){let R=w===""?[]:d.get(w)??[];if(d.delete(w),R.length===0){l+=y.length;continue}if(y.length===1&&R.length===1){f.push(...Pn(n,y[0],R[0])),u.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 h=!1;for(let w of d.values())p.push(...w),w.length>0&&(h=!0);return l>0&&(K(h?s.uncertain:s.notFound,i,l),h&&(m=!0,K(s.ofEndedJobs??=[],i,l))),f.push(...xs(n,p,o,m,s)),{lines:f,taken:[...u,...p]}}function Ms(n){let e=new Set;for(let t of we(n)){let r=Cs(t.text);if(r!==void 0)e.delete(r);else{let o=t.text.startsWith(`["${At}"`)?En(t.text):void 0;o&&e.add(o.callId)}}return e.size}async function Ls(n,e,t=()=>new Date){let r=Ya(),o=new Map,s=new Map,i=new Set,a=Number.NEGATIVE_INFINITY;for(let g of we(n)){let b=Cs(g.text);if(b!==void 0){o.delete(b);continue}let A=Ja(g.text);if(A){s.set(A.callId,A.jobId);continue}let N=Ga(g.text);if(N!==void 0){i.add(N);continue}if(g.text.startsWith(`["${At}"`)){let x=En(g.text);x&&(o.set(x.callId,{offset:g.offset,length:g.length}),a=Math.max(a,x.at));continue}if(g.text.startsWith("{")){let x=Ka(g.text);Number.isFinite(x)&&(a=Math.max(a,x))}}if(o.size===0)return r;let d=[];for(let{offset:g,length:b}of o.values()){let A=En(n.read(g,b).toString("utf8"));A&&d.push(A)}r.calls=d.length;let c=new Set(d.map(g=>g.objectApiName)),f=new Set(d.flatMap(g=>g.rows.map(b=>b.sourceId)));r.lookedFor=f;let u=new Set,p=new be,l=new be;for(let g of we(n)){let b=_e(g.text);if(b){if(c.has(b.object))for(let N of b.ids)p.add(N.slice(0,15)),l.add(N.slice(0,15));continue}let A=Ha(g.text);A&&(f.has(A.sourceId)&&u.add(A.sourceId),(A.object===""||c.has(A.object))&&p.add(A.targetId.slice(0,15)))}let m=0;if(e.serverTime)try{let g=t().getTime(),b=Date.parse(await e.serverTime());Number.isFinite(b)&&(m=b-(g+t().getTime())/2)}catch{}let h,w,y=[],R=e.readJob?.bind(e),O=new Set;if(R)for(let g of d){let b=s.get(g.callId);if(b===void 0)continue;O.add(g.callId);let A=g.rows.filter(x=>!u.has(x.sourceId));if(A.length===0){y.push(JSON.stringify([je,g.callId]));continue}let N=Za({call:g,rows:A,jobId:b,read:await R(b),ahead:m,endKept:i.has(g.callId)},p,l,r);y.push(...N.lines);for(let x of N.taken)p.add(x.slice(0,15))}for(let g of c){let b=d.filter(S=>S.objectApiName===g&&!O.has(S.callId));if(b.length===0)continue;let A=b.map(S=>({call:S,rows:S.rows.filter(I=>!u.has(I.sourceId))})),N=A.reduce((S,{rows:I})=>S+I.length,0);if(N===0){for(let{call:S}of A)y.push(JSON.stringify([je,S.callId]));continue}let x=new Map;for(let S of b)x.set(S.fields.join(","),S.fields);let v=[...new Set(b.flatMap(S=>S.upsertField?[S.upsertField]:[]))],P=[...new Set([...b.flatMap(S=>S.fields),...v])].sort(),k;try{if(h===void 0&&w===void 0)try{h=await e.userId()}catch(L){w=H(L)}if(h===void 0)throw new Error(`the user the run writes as is not known: ${w}`);let S=Math.min(...b.map(L=>L.at))+m-$a,I=a+m+Wa,C=P.includes("CreatedDate")?"SystemModstamp":"CreatedDate",B=P.includes("CreatedById")?"":`CreatedById = '${h}' AND `,T=`SELECT ${["Id",...P.filter(L=>L!=="Id")].join(", ")} FROM ${J(g)} WHERE ${B}${C} >= ${Ps(S)} AND ${C} <= ${Ps(I)} ORDER BY Id`;k=[];for await(let L of e.queryPages(T))for(let _ of L){let $=_.Id;if(typeof $!="string"||!Ae.test($)||p.has($.slice(0,15)))continue;let U=new Map;for(let[fe,ft]of x)U.set(fe,Tn(_,ft));let Q=new Map;for(let fe of v)Q.set(fe,vs(_,fe));k.push({id:$,fingerprints:U,externalKeys:Q,taken:!1})}}catch(S){r.unread.push({objectApiName:g,reason:H(S)}),K(r.uncertain,g,N);continue}k.sort((S,I)=>S.id<I.id?-1:S.id>I.id?1:0);let j=new Map;for(let S of x.keys()){let I=new Map;for(let C of k){let B=C.fingerprints.get(S)??"",T=I.get(B)??[];T.push(C),I.set(B,T)}j.set(S,I)}let M=(S,I,C)=>{C.taken=!0,y.push(...Pn(S,I,C.id)),K(r.found,g)},D=new Set;for(let{call:S,rows:I}of A){let C=S.upsertField;if(C===void 0)continue;let B=new Map;for(let L of k){let _=L.externalKeys.get(C);L.taken||_===void 0||B.set(_,[...B.get(_)??[],L])}let T=new Map;for(let L of I){let _=L.externalKey??"";T.set(_,[...T.get(_)??[],L])}for(let[L,_]of T){let $=L===""?[]:B.get(L)??[];if(L===""||_.length>1||$.length>1){K(r.uncertain,g,_.length),D.add(S.callId);continue}$.length===1?M(S,_[0],$[0]):K(r.notFound,g)}}let E=[];for(let{call:S,rows:I}of A){if(S.upsertField!==void 0)continue;let C=S.fields.join(","),B=new Map;for(let T of I){let L=B.get(T.fingerprint)??[];L.push(T),B.set(T.fingerprint,L)}for(let[T,L]of B){let _=(j.get(C)?.get(T)??[]).filter($=>!$.taken);if(_.length>L.length){for(let $ of L)E.push({callId:S.callId,sourceId:$.sourceId});D.add(S.callId);continue}_.forEach(($,U)=>M(S,L[U],$));for(let $ of L.slice(_.length))E.push({callId:S.callId,sourceId:$.sourceId})}}let F=k.some(S=>!S.taken);for(let S of E)F||D.has(S.callId)?(K(r.uncertain,g),D.add(S.callId)):K(r.notFound,g);for(let{call:S}of A)D.has(S.callId)||y.push(JSON.stringify([je,S.callId]))}return y.length>0&&n.append(`${y.join(`
|
|
11
|
-
`)}
|
|
12
|
-
`),r}function zf(n,e,t="resume"){if(n.calls===0)return[];let r=s=>s.map(({objectApiName:i,rows:a})=>`${a} ${i}`).join(", "),o=[`${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}`];n.found.length>0&&o.push(t==="resume"?` found in ${e}, kept as written by the run and not written again: ${r(n.found)}`:` found in ${e}, kept as written by the run and removed with its records: ${r(n.found)}`),n.notFound.length>0&&o.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&&o.push(` may already be in ${e}: ${r(n.uncertain)}`);for(let s of n.underway??[])o.push(` ${td(s,t)}`);for(let{objectApiName:s,rows:i}of n.untold??[])o.push(` ${s}: ${i} 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&&o.push(` written by a Bulk API job and matched to no row, kept as written by the run${t==="resume"?"":" and removed with its records"}: `+r(n.unattributed??[]));for(let{objectApiName:s,reason:i}of n.unread)o.push(` ${s} could not be read in ${e}: ${i}`);return o}function ed(n){return Math.max(1,Math.ceil(n/6e4))}function td(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?`, in about ${ed(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 nd(n){return n.uncertain.reduce((e,{rows:t})=>e+t,0)}function Uf(n){let e=(n.ofEndedJobs??[]).reduce((t,{rows:r})=>t+r,0);return Math.max(0,nd(n)-e)}import{createReadStream as rd}from"node:fs";import{appendFile as od,mkdir as sd,readdir as id,rename as ad,rm as _s}from"node:fs/promises";import*as ae from"node:path";import{createInterface as dd}from"node:readline";var cd=10*6e4;function tp(n){return new Mn({storagePath:n,appendFile:(e,t)=>od(e,t,"utf8"),readLines:e=>ld(e),mkdir:async e=>{await sd(e,{recursive:!0})},rm:e=>_s(e,{force:!0}),rename:(e,t)=>ad(e,t),listFiles:e=>id(e).catch(t=>{if(t.code==="ENOENT")return[];throw t}),openRunFile:e=>Mo(e),rmDir:e=>_s(e,{recursive:!0,force:!0})})}async function*ld(n){let e=rd(n,{encoding:"utf8"}),t=dd({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 np=5e4,rp=2e3,ee=W().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),Ct=W().regex(/^[A-Za-z][A-Za-z0-9_]*$/),ud=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:Pr.optional()}),fd=V({graph:Tr,config:Er,anonymizationRules:Fr.optional()});function Ds(n){let e=ud.safeParse(n);if(!e.success)return;let t=fd.safeParse(n.startedWith);return{...e.data,...t.success?{startedWith:t.data}:{}}}var Ft=V({run:V({journalId:W().min(1).max(200),targetOrgId:W().min(1).max(128),startedAt:W().min(1).max(40),resume:Ie().optional(),runUserId:Ie().optional()})}),Bs=V({objectApiName:W().regex(/^[A-Za-z][A-Za-z0-9_]*$/),reason:W().max(2e3),...vr}),$s=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(Bs),notHeld:Z(Bs)})}),pd=V({part:V({n:te().int().nonnegative(),startedAt:W().max(40).optional()})}),vn=V({end:V({status:Pe(["success","cancelled","failure","interrupted"]),forgeId:W().min(1).max(200),at:W().max(40).optional()})}),md=V({object:Ct,created:Z(Nr([ee,ee]))});function Cn(n){return ee.safeParse(n).success?n:void 0}function De(n){return n.replace(/\.ndjson$/,"")+".end.json"}function Pt(n){return n.replace(/\.ndjson$/,"")+".checkpoint.json"}function vt(n,e){return`${n.replace(/\.ndjson$/,"")}.part${e}.left`}function Ws(n,e){return`${n.replace(/\.ndjson$/,"")}.part${e}.stamps`}var gd=W().max(40).refine(n=>Number.isFinite(Date.parse(n)),"not a date"),Be=1e4;function hd(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 xn(n){return n.replace(/[^A-Za-z0-9_-]/g,"_")}var Mn=class{constructor(e){this.deps=e;this.dir=ae.join(e.storagePath,"forge-runs")}deps;dir;get storagePath(){return this.deps.storagePath}pathOf(e){return ae.join(this.dir,`${xn(e)}.ndjson`)}filePath(e){return this.pathOf(e)}async begin(e,t,r,o,s){await this.deps.mkdir(this.dir);let i=Cn(s),a={run:{journalId:e,targetOrgId:t,startedAt:r.toISOString(),...o?{resume:o}:{},...i?{runUserId:i}:{}}};await this.deps.appendFile(this.filePath(e),`${JSON.stringify(a)}
|
|
13
|
-
`)}async keepCheckpoint(e,t){let r=$s.safeParse({checkpoint:t});if(!r.success)return;let o=Pt(this.filePath(e));await this.deps.rm(o),await this.deps.appendFile(o,`${JSON.stringify(r.data)}
|
|
14
|
-
`)}async checkpointAt(e){for await(let t of this.deps.readLines(Pt(e)))if(t.trim()!=="")try{let r=$s.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 Vo.open(this.deps.openRunFile(e))}reconcile(e,t){return this.reconcileAt(this.filePath(e),t)}async reconcileAt(e,t){let r=this.deps.openRunFile(e);try{return await Ls(r,t)}finally{r.close()}}writeBoundsAt(e,t){let r=this.deps.openRunFile(e);try{let o,s,i,a,d=-1,c,f,u=Number.NEGATIVE_INFINITY,p=Number.NEGATIVE_INFINITY,l=Number.NEGATIVE_INFINITY,m=new Map;for(let w of we(r)){let y=/"(?:startedAt|at)":"([^"]{10,40})"/.exec(w.text)?.[1],R=w.text.startsWith('["x"')?/^\["x","[^"]*","[^"]*","([^"]+)"/.exec(w.text)?.[1]:void 0,O=zo(w.text);for(let v of[y,R,O?.at]){let P=v===void 0?Number.NaN:Date.parse(v);Number.isFinite(P)&&(u=Math.max(u,P))}if(O){let v=Date.parse(O.orgAt);Number.isFinite(v)&&(p=Math.max(p,v),d===t&&(l=Math.max(l,v)));continue}if(w.text.startsWith('{"part":')&&d++,!w.text.startsWith('["c"')&&!w.text.startsWith('["p"')&&!w.text.startsWith('["g"'))continue;let g;try{g=JSON.parse(w.text)}catch{continue}if(!Array.isArray(g))continue;let[b,A,N,x]=g;if(b==="c"){if(!ee.safeParse(N).success||!Ct.safeParse(x).success)continue;let v={objectApiName:String(x),id:String(N)};o??=v,s=v,d===t&&(i??=v,a=v),m.set(String(N).slice(0,3),String(x))}else if(b==="g"){if(!ee.safeParse(N).success||!Ct.safeParse(A).success)continue;c={objectApiName:String(A),id:String(N)},f=void 0}else ee.safeParse(A).success&&(f=String(A))}let h=f?m.get(f.slice(0,3)):void 0;return f&&h&&(c={objectApiName:h,id:f}),{...o?{first:o}:{},...s?{lastCreated:s}:{},...i?{firstInPart:i}:{},...a?{lastCreatedInPart:a}:{},...c?{lastUpdated:c}:{},...Number.isFinite(u)?{lastAt:new Date(u).toISOString()}:{},...Number.isFinite(p)?{jobEnded:new Date(p).toISOString()}:{},...Number.isFinite(l)?{jobEndedInPart:new Date(l).toISOString()}:{}}}finally{r.close()}}writtenBetween(e,t,r,o="run"){return this.writtenBetweenAt(this.filePath(e),t,r,o)}async writtenBetweenAt(e,t,r,o="run"){let s=this.writeBoundsAt(e,r),{firstInPart:i,lastCreatedInPart:a,lastAt:d}=s,[c,f,u]=o==="part"?[i,a,void 0]:[s.first,s.lastCreated,s.lastUpdated];if(!c||!f)return;let p=async({objectApiName:O,id:g},b)=>{try{let N=(await t.query(`SELECT ${b} FROM ${J(O)} WHERE Id = '${g}'`)).records[0]?.[b],x=typeof N=="string"?Date.parse(N):Number.NaN;return Number.isFinite(x)?x:void 0}catch{return}},l=d===void 0?Number.NaN:Date.parse(d)+cd,m=await p(c,"CreatedDate")??(i&&i.id!==c.id?await p(i,"CreatedDate"):void 0),h=[],w=a?.id!==f.id?a:void 0;for(let O of[f,w]){let g=O?await p(O,"CreatedDate"):void 0;if(O&&g!==void 0&&m!==void 0&&g<m){let b=await p(O,"SystemModstamp");g=b!==void 0&&b>=m&&(!Number.isFinite(l)||b<=l)?b:void 0}g!==void 0&&h.push(g)}let y=h.length>0?Math.max(...h):void 0;if(m===void 0||y===void 0||y<m)return;if(u){let O=await p(u,"LastModifiedDate");O!==void 0&&O>y&&(!Number.isFinite(l)||O<=l)&&(y=O)}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 Ms(t)}finally{t.close()}}stop(e,t,r){return this.stopAt(this.filePath(e),t,r)}async stopAt(e,t,r){let o=`${JSON.stringify({end:{status:t,forgeId:r,at:new Date().toISOString()}})}
|
|
15
|
-
`;await this.deps.appendFile(e,o),await this.deps.rm(De(e)),await this.deps.appendFile(De(e),o)}resuming(e){return this.resumingAt(this.filePath(e))}resumingAt(e){return this.deps.rm(De(e))}lastEnd(e){return this.lastEndAt(this.filePath(e))}async lastEndAt(e){for await(let t of this.deps.readLines(De(e)))if(t.trim()!=="")try{let r=vn.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=Ft.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=vn.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=Ft.safeParse(JSON.parse(i));if(!a.success||a.data.run.journalId!==e)return[]}catch{return[]}o=!0;continue}if(i.startsWith('{"part":')){if(s++,s>t)break;continue}if(!(s!==t||!(i.startsWith('["p"')||i.startsWith('["g"'))))try{let a=JSON.parse(i);if(!Array.isArray(a))continue;let d=a[0]==="p"?a[1]:a[2];ee.safeParse(d).success&&r.add(String(d))}catch{}}return[...r]}async end(e){let t=this.filePath(e);await this.deps.rm(t),await this.deps.rm(De(t)),await this.deps.rm(Pt(t));let r=`${ae.basename(t).replace(/\.ndjson$/,"")}.part`;for(let o of await this.deps.listFiles(this.dir))o.startsWith(r)&&(o.endsWith(".left")||o.endsWith(".stamps"))&&await this.deps.rm(ae.join(this.dir,o));await this.deps.rmDir?.(gs(this.deps.storagePath,e))}fileNameOf(e){return`${xn(e)}.ndjson`}async present(e){let t=new Set(await this.deps.listFiles(this.dir));return new Set(e.filter(r=>t.has(this.fileNameOf(r))))}async endedFiles(){let e=await this.deps.listFiles(this.dir),t=new Set(e.filter(r=>r.endsWith(".end.json")));return e.filter(r=>r.endsWith(".ndjson")&&t.has(r.replace(/\.ndjson$/,".end.json")))}async forgetFile(e){let t=ae.join(this.dir,e),r=await this.headAt(t);r?await this.end(r.journalId):(await this.deps.rm(t),await this.deps.rm(De(t)),await this.deps.rm(Pt(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=vt(this.filePath(e),t);await this.deps.rm(o);for(let s=0;s<r.length;s+=Be)await this.deps.appendFile(o,`${r.slice(s,s+Be).join(`
|
|
16
|
-
`)}
|
|
17
|
-
`);r.length===0&&await this.deps.appendFile(o,"")}async recordsOf(e,t,r=!1){if(!await this.head(e))return;let o=r?void 0:await this.leftKeysOf(e,t),s=this.deps.openRunFile(this.filePath(e)),i=ot.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=ot.read(r,t);if(!o){r.close();return}return{rows:o.idMapRows(),close:()=>r.close()}}async leftKeysOf(e,t){let r=vt(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(ae.basename(r)))return;let s=new be;for await(let i of this.deps.readLines(r)){let a=i.trim();ee.safeParse(a).success&&s.add(a.slice(0,15))}return s}async keepLeftPages(e,t,r){let o=vt(this.filePath(e),t),s=this.deps.rename,i=s?`${o}.next`:o;await this.deps.rm(i),await this.deps.appendFile(i,"");let a=new Map;for await(let{objectApiName:d,ids:c}of r)if(c.length!==0){a.set(d,(a.get(d)??0)+c.length);for(let f=0;f<c.length;f+=Be)await this.deps.appendFile(i,`${c.slice(f,f+Be).join(`
|
|
18
|
-
`)}
|
|
19
|
-
`)}return s&&await s(i,o),[...a].map(([d,c])=>({objectApiName:d,count:c}))}async stampsOf(e,t){let r=Ws(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(ae.basename(r)))return{};let s={};for await(let i of this.deps.readLines(r)){let[a,d]=i.trim().split(" ");ee.safeParse(a).success&&gd.safeParse(d).success&&(s[a]=d)}return s}async keepStamps(e,t,r){if(Object.keys(r).length===0)return;let o=Ws(this.filePath(e),t),s=Object.entries({...await this.stampsOf(e,t),...r}),i=this.deps.rename,a=i?`${o}.next`:o;await this.deps.rm(a);for(let d=0;d<s.length;d+=Be){let c=s.slice(d,d+Be).map(([f,u])=>`${f} ${u}`);await this.deps.appendFile(a,`${c.join(`
|
|
20
|
-
`)}
|
|
21
|
-
`)}i&&await i(a,o)}async leftOf(e,t){let r=vt(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(ae.basename(r)))return;let s=[];for await(let i of this.deps.readLines(r)){let a=i.trim();ee.safeParse(a).success&&s.push(a)}return s}async head(e){let t=await this.headAt(this.filePath(e));return t?.journalId===e?t:void 0}async headAt(e){for await(let t of this.deps.readLines(e)){if(t.trim()==="")continue;let r;try{r=JSON.parse(t)}catch{return}let o=Ft.safeParse(r);if(!o.success)return;let{resume:s,runUserId:i,...a}=o.data.run,d=Ds(s),c=Cn(i);return{...a,...d?{resume:d}:{},...c?{runUserId:c}:{}}}}async read(e){let t=await this.deps.listFiles(this.dir),r=`${xn(e)}.ndjson`;if(!t.includes(r))return;let o=await this.readAt(ae.join(this.dir,r));return o?.journalId===e?o:void 0}readAt(e,t="last"){return this.readFile(e,t)}async leftOver(e=new Set){let t=[],r=await this.deps.listFiles(this.dir),o=new Set(r.filter(s=>s.endsWith(".end.json")));for(let s of r){if(!s.endsWith(".ndjson")||o.has(s.replace(/\.ndjson$/,".end.json")))continue;let i=await this.readFile(ae.join(this.dir,s),"last");!i||e.has(i.journalId)||i.lastEnd||t.push(i)}return t}static planOf(e,t=e.journalId){let r=hd(e.created,e.unattributed);if(r.length!==0)return{forgeId:t,targetOrgId:e.targetOrgId,timestamp:e.startedAt,duration:0,status:"partial",objects:r,linked:0}}forget(e){return this.end(e)}async readFile(e,t){let r,o=0,s,i,a,d=new Map,c=new Map,f=new Set,u,p=()=>{o++,i=s,s=void 0,t==="last"&&(d=new Map,c=new Map,f=new Set)},l=()=>typeof t!="number"||o-1===t;for await(let N of this.deps.readLines(e)){if(N.trim()==="")continue;let x;try{x=JSON.parse(N)}catch{continue}if(!r){let j=Ft.safeParse(x);if(!j.success)return;r=j.data.run;continue}if(Array.isArray(x)){let j=_e(N);if(j){if(!l())continue;let S=c.get(j.object)??new Set;for(let I of j.ids)S.add(I);c.set(j.object,S);continue}let[M,D,E,F]=x;if(M===Bo){l()&&ee.safeParse(D).success&&f.add(String(D));continue}if(M!=="c"&&M!=="e"&&M!=="u"||!l()||!ee.safeParse(D).success||!ee.safeParse(E).success)continue;d.set(String(D),{targetId:String(E),object:typeof F=="string"&&Ct.safeParse(F).success?F:"",created:M==="c"});continue}if(typeof x=="object"&&x!==null&&"roots"in x){u=Lo(x.roots)??u;continue}let v=pd.safeParse(x);if(v.success){p(),a=v.data.part.startedAt;continue}let P=vn.safeParse(x);if(P.success){s=P.data.end;continue}let k=md.safeParse(x);if(k.success){if(o===0&&p(),!l())continue;for(let[j,M]of k.data.created)d.set(j,{targetId:M,object:k.data.object,created:!0})}}if(!r)return;let m=Ds(r.resume),h=Cn(r.runUserId),w=await this.checkpointAt(e),y={},R=new Map,O=[];for(let[N,{targetId:x,object:v,created:P}]of d){if(!v)continue;if(y[N]=x,!P){O.push(N);continue}let k=R.get(v)??[];k.push(N),R.set(v,k)}let g=[...R].map(([N,x])=>({objectApiName:N,sourceIds:x})),b=new Set([...d.values()].filter(({created:N})=>N).map(({targetId:N})=>N.slice(0,15))),A=[...c].map(([N,x])=>({objectApiName:N,ids:[...x].filter(v=>!b.has(v.slice(0,15)))})).filter(({ids:N})=>N.length>0);return{journalId:r.journalId,targetOrgId:r.targetOrgId,startedAt:r.startedAt,...m?{resume:m}:{},...h?{runUserId:h}:{},...w?{checkpoint:w}:{},...u?{roots:u}:{},parts:o,partStartedAt:a??r.startedAt,...s?{lastEnd:s}:{},...i?{endBefore:i}:{},created:Lr({idRemapTable:y,idRemapExisting:O,idRemapCreated:g}),remap:{table:y,createdByObject:g,linked:O,...O.some(N=>f.has(N))?{withTheirRecord:O.filter(N=>f.has(N))}:{}},...A.length>0?{unattributed:A}:{}}}};import{randomBytes as wd}from"node:crypto";import{chmod as yd,open as bd,readFile as Rd,readdir as Sd,rename as Od,rm as qs,stat as Ad}from"node:fs/promises";import{dirname as kd,join as _n}from"node:path";var Id=1440*6e4,jd="forge-roots",Nd=/^[A-Za-z0-9_-]{1,128}$/,We=class extends Error{constructor(t,r){super(r);this.fault=t;this.name="RootPlanError"}fault},Ed=rn({where:W().min(1).max(512).optional(),orderBy:W().min(1).max(200).optional(),limit:te().int().min(1).max(an).optional()}),zs=rn({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:Ed.optional(),from:Pe(["query","records"]),readAt:W().refine(n=>Number.isFinite(Date.parse(n)),"not a date"),ids:Z(W().refine(Qo,"not a record id")).max(an),sha256:W().regex(/^[0-9a-f]{64}$/)});function Us(n){return _n(n,jd)}function up(n,e){if(!Nd.test(e))throw new We("gone","Not the fingerprint of a setup of a run.");return _n(Us(n),`${e}.json`)}function Ln(n){let e=n?.code;return e==="ENOENT"||e==="ENOTDIR"}async function fp(n,e){let t=Zo(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:Sn(t)},o=zs.parse(r);await Go(kd(n));let s=`${n}.${process.pid}-${wd(4).toString("hex")}.tmp`;try{let i=await bd(s,"wx",yn);try{await i.writeFile(`${JSON.stringify(o)}
|
|
22
|
-
`,"utf8")}finally{await i.close()}await yd(s,yn),await Od(s,n)}catch(i){throw await qs(s,{force:!0}),i}return o}async function Td(n){let e;try{e=await Rd(n,"utf8")}catch(r){throw Ln(r)?new We("gone",`No plan of roots is at ${n}.`):r}let t;try{t=zs.parse(JSON.parse(e))}catch{throw new We("changed",`The plan of roots at ${n} no longer reads as one.`)}if(Sn(t.ids)!==t.sha256)throw new We("changed",`The ids of the plan of roots at ${n} are no longer those it was kept with.`);return t}function pp(n,e){return e.getTime()-Date.parse(n.readAt)}async function mp(n,e){let t=Us(n),r;try{r=await Sd(t)}catch(s){if(Ln(s))return 0;throw s}let o=0;for(let s of r){let i=_n(t,s),a;try{a=Date.parse((await Td(i)).readAt)}catch{try{a=(await Ad(i)).mtimeMs}catch(d){if(Ln(d))continue;throw d}}e.getTime()-a<Id||(await qs(i,{force:!0}),o++)}return o}import{createHash as Fd}from"node:crypto";function Pd(n,e){return Gs(n,e,t=>t.included||_r(t))}function vd(n,e){if(n!==void 0)return{...Bn(n),...e?{planSha256:e}:{}}}function Bn(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??Re.seed,draw:n.draw??Re.draw,parents:n.parents??Re.parents,children:n.children??Re.children,floor:n.floor??Re.floor,whole:[...new Set(n.whole??[])].sort(),...n.window?{window:Cd(n.window)}:{},...e.length>0?{rootWhere:Object.fromEntries(e)}:{},...t.length>0?{strata:t}:{}}}function Cd(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 xt(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Vs(n){if(!xt(n))return n;let e=typeof n.planSha256=="string"?n.planSha256:void 0;return vd(n,e)}function xd(n){if(!xt(n))return n;let e=n.config;return{...n,..."sample"in n?{sample:Vs(n.sample)}:{},..."roots"in n?{roots:Md(n.roots)}:{},...xt(e)&&"sample"in e?{config:{...e,sample:Vs(e.sample)}}:{}}}function Md(n){if(!xt(n))return n;let{objectApiName:e,sha256:t}=n;return typeof e!="string"||typeof t!="string"?n:{objectApiName:e,sha256:t}}function yp(n,e,t){return n===Pd(e,t)||n===Gs(e,t,r=>r.included)}function Gs(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 Fd("sha256").update(Dn({nodes:r,edges:o,setup:xd(e)})).digest("hex")}function Dn(n){return Array.isArray(n)?`[${n.map(e=>Dn(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)}:${Dn(r)}`).join(",")}}`:JSON.stringify(n??null)}function Ap(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:Bn(n.sample)}:Object.values(e).some(t=>t.length>0)?e:void 0}var Wn=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},Ld="NOTHING_TO_CLONE";function kp(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:Ld,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 Ip(n){return n instanceof Wn||n instanceof Error&&n.name==="WholeOrgDryRunStop"&&"dryRun"in n}function $n(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 jp(n){return{api:n.targetRequests,wholeOrg:{source:n.sourceRequests,...n.bulkBatches?{bulkBatches:n.bulkBatches}:{},cost:{durationSeconds:n.durationSeconds}}}}function _d(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:Dd(n.roots)}:{}}}function Dd(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 Np(n){let{run:e,measures:t,plan:r,budget:o}=n,s=new Set(r.objects.filter(({rows:h})=>h>0).map(({objectApiName:h})=>h)),i=t.writes.filter(({rows:h})=>h>0),a=h=>i.reduce((w,y)=>w+y[h],0),d=a("jobs"),c=[...s].filter(h=>eo(h)!==void 0).sort(),f=is(e.graph.nodes,s,e.anonymizePII),u=n.files&&"check"in n.files?n.files:void 0,p=u?.check,l=t.contactPointsBlanked??0,m=o.wholeOrg.bulkBatches;return{source:e.source,leftOut:as(e.graph).objects.length,...e.carried?{carried:e.carried}:{},...n.sample?{sample:_d(n.sample,n.now??Date.now())}:{},targetApi:$n(o.api),sourceApi:$n(o.wholeOrg.source),...d>0?{bulk:{jobs:d,jobRows:a("jobRows"),restRows:a("restRows"),...m?{batches:$n(m)}:{}}}:{},durationSeconds:o.wholeOrg.cost.durationSeconds,restObjects:i.filter(h=>h.jobs===0).map(h=>h.objectApiName),...u&&p&&p.verdict!=="unread"?{fileStorage:{files:u.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}:{},...l>0?{contactPointsBlanked:l}:{},...f.length>0?{personalAsIs:f}:{}}}var Bd=10*6e4,$d=3e4,Wd=5e3,Js=500,qd=new Set(["JobComplete","Failed","Aborted"]),Hs=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>Js&&this.kept.splice(0,this.kept.length-Js)}since(e,t){return this.kept.filter(({seq:r,job:o})=>r>e&&o.orgId===t).map(({job:r})=>({...r}))}async stillRunning(e,t){let r=this.options.now??(()=>Date.now()),o=this.options.sleep??(c=>new Promise(f=>setTimeout(f,c))),s=this.options.pollDelay??Oo,i=r()+(this.options.waitMs??Bd),a=e.filter(c=>c.jobId===void 0),d=e.filter(c=>!!c.jobId);for(let c=0;d.length>0;c++){let f=new Ot(Math.max(1,Math.min($d,i-r())));d=(await Promise.all(d.map(async l=>{t?.();let m=await f.withTimeout("forge:lost-bulk-job",()=>this.stateOf(l.orgId,l.jobId)).catch(()=>{});return m!==void 0&&qd.has(m)?void 0:l}))).filter(l=>l!==void 0);let p=i-r()-Wd;if(d.length===0||p<=0)break;await o(Math.min(s(c),p))}return[...a,...d]}};function Pp(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 zd="SELECT SobjectType FROM DuplicateRule WHERE IsActive = true",Cp=new Set(["Account","Contact","Lead"]);function xp(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 Mp(n){try{let e=await n.query(zd);return new Set(e.records.flatMap(t=>typeof t.SobjectType=="string"?[t.SobjectType]:[]))}catch{return}}var Ks=class{constructor(e=3){this.maxDiscoveries=e}maxDiscoveries;discoveries=new Map;awaitingGuard=new Map;run=null;beginDiscovery(e,t,r){let o=[],s=c=>{this.discoveries.delete(c.requestId),c.stop="superseded",o.push(c)},i=this.discoveries.get(e);i&&s(i);let a=[...this.discoveries.values()].filter(c=>!c.controller.signal.aborted);for(;a.length>=this.maxDiscoveries;){let c=a.shift();c&&s(c)}let d={requestId:e,controller:t,operationId:r};return this.discoveries.set(e,d),{discovery:d,superseded:o}}endDiscovery(e){this.discoveries.get(e.requestId)===e&&this.discoveries.delete(e.requestId)}awaitGuard(e,t){return this.awaitingGuard.set(e,t),()=>{this.awaitingGuard.get(e)===t&&this.awaitingGuard.delete(e)}}beginRun(e,t){this.run={requestId:e,controller:t}}endRun(e){this.run?.requestId===e&&(this.run=null)}resolve(e){let t=e===void 0?this.onlyLive():this.named(e);return"refused"in t?t:(t.kind==="discovery"&&(this.discoveries.delete(t.discovery.requestId),t.discovery.stop="stopped"),{stops:t})}stop(e,t){let r=this.resolve(e);if("refused"in r)return r;let o=r.stops;return o.kind==="discovery"?t.discovery(o.discovery):o.kind==="awaiting-guard"?o.controller.abort():t.run(),r}named(e){let t=this.discoveries.get(e);if(t)return{kind:"discovery",discovery:t};let r=this.awaitingGuard.get(e);return r?{kind:"awaiting-guard",controller:r}:this.run?.requestId===e?{kind:"run"}:{refused:"none"}}onlyLive(){let e=[...[...this.discoveries.values()].filter(t=>!t.controller.signal.aborted).map(t=>({kind:"discovery",discovery:t})),...[...this.awaitingGuard.values()].filter(t=>!t.signal.aborted).map(t=>({kind:"awaiting-guard",controller:t})),...this.run&&!this.run.controller.signal.aborted?[{kind:"run"}]:[]];return e.length===0?{refused:"none"}:e.length>1?{refused:"several",live:e.length}:e[0]}};function qn(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 l of[...n.get(p)??[]].sort())n.has(l)&&(t.has(l)?s.has(l)&&r.set(p,Math.min(r.get(p)??0,t.get(l)??0)):(d(l),r.set(p,Math.min(r.get(p)??0,r.get(l)??0))));if(r.get(p)===t.get(p)){let l=[],m;do{if(m=o.pop(),m===void 0)break;s.delete(m),i.set(m,a.length),l.push(m)}while(m!==p);a.push(l.sort())}};for(let p of[...n.keys()].sort())t.has(p)||d(p);let c=a.map((p,l)=>{let m=new Set;for(let h of p)for(let w of n.get(h)??[]){let y=i.get(w);y!==void 0&&y!==l&&m.add(y)}return m}),f=new Set,u=[];for(;f.size<a.length;){let p=a.map((l,m)=>({component:l,i:m})).filter(({i:l})=>!f.has(l)&&[...c[l]].every(m=>f.has(m))).sort((l,m)=>l.component[0].localeCompare(m.component[0]));for(let{component:l,i:m}of p)f.add(m),u.push(l)}return u}function zn(n,e){let t=new Set(n),r=new Map(n.map(s=>[s,new Set([...e.get(s)??[]].filter(i=>t.has(i)))])),o=[];for(;;){let s=[...r.entries()].filter(([,i])=>i.size===0).map(([i])=>i).sort();if(s.length===0)break;for(let i of s){o.push(i),r.delete(i);for(let a of r.values())a.delete(i)}}return[...o,...[...r.keys()].sort()]}function Ud(n,e,t){let r=new Set(n),o=new Map;for(let s of e){if(!r.has(s.to)||!r.has(s.from))continue;let i=t(s.to)?.find(d=>d.name===s.fieldApiName),a=i!==void 0&&pt(i);!s.required&&!xr(s.to,s.fieldApiName)&&!a||o.set(s.to,(o.get(s.to)??new Set).add(s.from))}return o}function Vd(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:qn(o)}}function Bp(n,e,t){return n.flatMap(r=>{let{groups:o,within:s}=Vd(r,e);return o.flatMap(i=>i.length>1?zn(i,Ud(i,s,t)):i)})}var Gd=100,Jd=.25,Hd=2048;function Fe(n,e){return typeof n!="string"||n===""?!1:e.prefix===void 0||e.prefix!==null&&n.startsWith(e.prefix)}function Kd(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=Un(o.objectApiName,a)||pt(a);for(let c of a.referenceTo)c===o.objectApiName||!e.has(c)||(s.add(c),d&&i.add(c))}t.set(o.objectApiName,s),r.set(o.objectApiName,i)}return qn(t).flatMap(o=>o.length>1?zn(o,r):o)}function Un(n,e){return Mr(n,e.name,e.nillable)}function Yd(n){let e=new Map(n.objects.map(l=>[l.objectApiName,l])),t=new Map;for(let l of e.keys())n.referenceData?.has(l)&&t.set(l,"referenceData");for(let l of n.whole??[])e.has(l)&&!t.has(l)&&t.set(l,"asked");let r=Jd*Math.max(0,n.roomBytes),o=l=>l.rows===void 0?void 0:n.wholeBytes(l.objectApiName,l.rows),s=[...e.values()].filter(l=>Et.has(l.objectApiName)&&!t.has(l.objectApiName)),i=s.reduce((l,m)=>{let h=o(m);return l===void 0||h===void 0?void 0:l+h},0);if(s.length>0&&i!==void 0&&i<=r&&s.every(l=>n.maxRecordsPerObject===void 0||(l.rows??0)<=n.maxRecordsPerObject))for(let l of s)t.set(l.objectApiName,"catalog");let d=Math.max(Gd,Math.floor(.01*Math.max(0,n.roomBytes)/Hd)),c=l=>e.has(l)&&!t.has(l),f=new Set;for(let l of e.values())if(c(l.objectApiName)){for(let m of l.fields)if(Qe(m))for(let h of m.referenceTo)h!==l.objectApiName&&f.add(h)}let u=[...e.values()].filter(l=>!t.has(l.objectApiName)&&!Et.has(l.objectApiName)&&l.rows!==void 0&&l.rows>0&&l.rows<=d&&(n.maxRecordsPerObject===void 0||l.rows<=n.maxRecordsPerObject)&&f.has(l.objectApiName)).map(l=>({object:l,bytes:o(l)??1/0})).sort((l,m)=>l.bytes-m.bytes||(l.object.objectApiName<m.object.objectApiName?-1:1)),p=0;for(let{object:l,bytes:m}of u){if(p+m>r)break;l.fields.some(w=>Qe(w)&&Un(l.objectApiName,w)&&w.referenceTo.some(y=>c(y)))||(t.set(l.objectApiName,"smallParent"),p+=m)}return t}function Mt(n){let e=new Map(n.objects.map(u=>[u.objectApiName,u])),t=Yd(n),r=[...t.values()].includes("catalog"),o=new Map;for(let u of e.keys()){let p=t.get(u);o.set(u,p!==void 0?{kind:"whole",why:p}:{kind:"drawn",rooted:!(Et.has(u)&&!r)})}let s=n.order?[...n.order]:Kd(n.objects),i=new Map(s.map((u,p)=>[u,p])),a=(u,p)=>(i.get(u)??1/0)<(i.get(p)??1/0),d=u=>{let p=o.get(u);return p?.kind==="drawn"&&p.rooted},c=new Map,f=new Map;for(let u of[...e.values()].sort((p,l)=>p.objectApiName<l.objectApiName?-1:1)){let p=u.objectApiName,l=[];for(let m of[...u.fields].sort((h,w)=>h.name<w.name?-1:1)){if(m.referenceTo.length===0||!Qe(m))continue;let h=Un(p,m),w=m.referenceTo.length>1;for(let y of[...m.referenceTo].sort()){let R=o.get(y),O=Xo(p,m,e.get(y)?.childRelationships),g=n.excluded?.get(y),b=v=>w?{prefix:v??null}:{};if(!R){h&&n.excluded?.has(y)&&l.push({objectApiName:p,field:m.name,parent:y,target:"excluded",carries:!1,owed:!1,required:h,masterDetail:O,...b(g)});continue}let A=y===p,N=A||!a(y,p),x={objectApiName:p,field:m.name,parent:y,target:R.kind==="whole"?"whole":"drawn",carries:!A&&d(y)&&d(p)&&(h||!N),owed:N,required:h,masterDetail:O,...b(e.get(y)?.keyPrefix)};if(l.push(x),x.carries){let v=f.get(y)??[];v.push(x),f.set(y,v)}}}c.set(p,l)}return{classes:o,whole:[...t.entries()].map(([u,p])=>({objectApiName:u,why:p})).sort((u,p)=>u.objectApiName<p.objectApiName?-1:1),linksOf:c,carriersInto:f,order:s}}function Vn(n,e){return[...new Set((n.linksOf.get(e)??[]).map(t=>t.field))].sort()}function Ys(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 Zs(n,e,t,r){return(n.linksOf.get(e)??[]).find(o=>o.field===t&&Fe(r,o))}var ge=2e3,Qd=500,Hn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Xd=et;function qe(n){return n.length===0?"":` WHERE ${n.join(" AND ")}`}function ze(n){return no(n)+2*(n.match(/'/g)?.length??0)}function Qs(n,e,t){let r=ze(n)+ze(t),o=ze(", "),s=[],i=[],a=r;for(let d of e){let c=ze(`'${d}'`);i.length>0&&(a+o+c>14e3||i.length>=Qd)&&(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 it(n){let e=new Set,t=[];for(let r of n){if(!Hn.test(r))continue;let o=q(r);e.has(o)||(e.add(o),t.push(r))}return t}function Lt(n){return wt(H(n))==="QUERY_TIMEOUT"}var ec=new Set(["MALFORMED_QUERY","INVALID_FIELD"]);function Xs(n){let e=wt(H(n));return e!==void 0&&ec.has(e)}var tc=new Set(["MALFORMED_QUERY","INVALID_FIELD","EXCEEDED_MAX_SEMIJOIN_SUBSELECTS"]),nc="SAMPLE_DRAW_INVALID";function rc(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 he="CreatedDate",oc="LastModifiedDate",ei="SystemModstamp";function ri(n){return n.replace(/'(?:[^'\\]|\\.)*'/g,"''")}function sc(n){return/\(\s*SELECT\b/i.test(ri(n))}function ic(n){let e=0,t="";for(let r of ri(n))r==="("&&e++,t+=e===0?r:" ",r===")"&&(e=Math.max(0,e-1));return/\bOR\b/i.test(t)}function ti(n){let e=n.trim();return sc(e)&&!ic(e)?e:`(${e})`}function oi(n){return n==null||n===""}function Jn(n){return oi(n)?null:typeof n=="boolean"?n:String(n)}function at(n){return n===null?"\0":`${typeof n}:${String(n)}`}function ac(n,e){return e===null?`${n} = null`:typeof e=="boolean"?`${n} = ${String(e)}`:`${n} = '${Ce(e)}'`}function dc(n){let e=n.trim();return/[.!?]$/.test(e)?e:`${e}.`}function cc(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 _t=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()!==""?[ti(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(O=>({field:this.fieldOf(r,O.field),prefixes:O.drawnPrefixes===void 0?void 0:[...O.drawnPrefixes]})),i=o?[]:s.filter(O=>O.prefixes===void 0),a=s.filter(O=>!i.includes(O)),d=(O,g)=>!oi(O)&&(g===void 0||g.some(b=>String(O).startsWith(b))),c=t.natural?void 0:e.window,f=c?this.fieldOf(r,c.field):void 0,u=c?.field===oc,p=c!==void 0&&u&&o,l=c&&f&&!p?[...c.from!==void 0?[`${f} >= ${Oe(c.from)}`]:[],...c.to!==void 0?[`${f} < ${Oe(c.to)}`]:[],...u&&c.from!==void 0&&this.lists(r,ei)?[`${ei} >= ${Oe(c.from)}`]:[]]:[],m=t.natural||e.where?.trim()===""?void 0:e.where,h=e.stratifiedBy!==void 0&&(t.stratum!==void 0||t.values)?this.fieldOf(r,e.stratifiedBy):void 0,w=t.stratum?.value===null,y=t.stratum!==void 0&&h!==void 0&&!(w&&o)?[ac(h,t.stratum.value)]:[],R=[];return p&&c&&f&&R.push(O=>cc(O[f],c)),w&&o&&h!==void 0&&R.push(O=>Jn(O[h])===null),{object:r,select:this.columnsOf(r,[...a.map(O=>O.field),...p&&f?[f]:[],...h!==void 0&&(t.values||w&&o)?[h]:[]]),terms:[...this.termsOf(r),...i.map(O=>`${O.field} = null`),...l,...m!==void 0?[ti(m)]:[],...y],held:i.length>0||u&&l.length>0||w&&y.length>0,tested:a.length>0||R.length>0,isRoot:O=>!a.some(g=>d(O[g.field],g.prefixes))&&R.every(g=>g(O))}}async countRoots(e){let t=new Array(e.length),r=0;return await Ne(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=>[at(a.value),a.rows]))),r++,this.progress("counting",{objectApiName:o.objectApiName,done:r,total:e.length})}),t}async countRootsOf(e){let t=e.objectApiName,r=this.readOptionsOf(t);e.stratifiedBy!==void 0&&this.refuseUngroupedStratum(e,e.stratifiedBy);let o=!1;for(;;){let s=this.rootShapeOf(e),i;try{i=e.stratifiedBy===void 0?{rows:await this.count(`SELECT COUNT() FROM ${s.object}${qe(s.terms)}`,r)}:await this.countByStratum(e,e.stratifiedBy,s,r)}catch(d){if(o||!s.held||!Lt(d))throw this.drawRefusalOf(e,d);o=!0,this.slow.add(t);continue}let a=this.restricts(e)?await this.countInTheSource(e,{terms:s.terms,rows:i.rows,exact:!s.tested}):void 0;return{objectApiName:t,rows:i.rows,exact:!s.tested,...o?{timedOut:!0}:{},...i.strata?{strata:i.strata}:{},...a?{inTheSource:a}:{}}}}restricts(e){return e.window!==void 0||e.where!==void 0&&e.where.trim()!==""}async countInTheSource(e,t){let r=this.readOptionsOf(e.objectApiName),o=this.slow.has(e.objectApiName);for(;;){let s=this.rootShapeOf(e,{natural:!0,slow:o});if(s.terms.join(`
|
|
23
|
-
`)===t.terms.join(`
|
|
24
|
-
`))return{rows:t.rows,exact:t.exact};try{return{rows:await this.count(`SELECT COUNT() FROM ${s.object}${qe(s.terms)}`,r),exact:!s.tested}}catch(i){if(o||!s.held||!Lt(i))throw i;o=!0}}}async countByStratum(e,t,r,o){let s=this.fieldOf(r.object,t),i=`SELECT ${s}, COUNT(Id) n FROM ${r.object}${qe(r.terms)} GROUP BY ${s}`,a=[],d=0;try{for await(let f of this.pages(i,o)){if(d++,d>1)break;for(let u of f)a.push(u)}}catch(f){if(d===0)throw f;d=2}if(d>1||a.length>=ge)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 ${ge}, and this one ${d>1?"had more after it":`held ${a.length}`}.`);let c=[];for(let f of a){let u=Number(f.n);Number.isFinite(u)&&c.push({value:Jn(f[s]),rows:u})}return{rows:c.reduce((f,u)=>f+u.rows,0),strata:c}}refuseUngroupedStratum(e,t){if(this.options.countsBy?.(e.objectApiName,t)===!1)throw this.drawRefused(e,"strata",`The source's describe says the records of ${e.objectApiName} are not counted by ${t}.`)}drawRefusalOf(e,t){let r=H(t),o=wt(r);return o===void 0||!tc.has(o)||!this.restricts(e)&&e.stratifiedBy===void 0?t:this.drawRefused(e,rc(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(nc,[dc(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 Ne(e,async o=>{this.counted.get(o.objectApiName)!==0&&await this.scanRoots(o,t),r++,this.progress("drawing",{objectApiName:o.objectApiName,done:r,total:e.length})})}async scanRoots(e,t){let r=this.readOptionsOf(e.objectApiName),o=e.stratifiedBy;for(;;){let s=this.rootShapeOf(e,o===void 0?{}:{values:!0}),i=`SELECT ${s.select.join(", ")} FROM ${s.object}${qe(s.terms)}`,a=!1;try{for await(let d of this.pages(i,r)){a=!0;let c=d.filter(s.isRoot);if(o===void 0){let f=c.map(u=>String(u.Id));f.length>0&&await t(e.objectApiName,f);continue}for(let{value:f,ids:u}of fc(c,o))await t(e.objectApiName,u,f)}return}catch(d){if(a||!s.held||!Lt(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 Ne(e,async(i,a)=>{let d=i.objectApiName;if(this.counted.get(d)!==0){let c=o[a].by;if(typeof i.take=="number")i.take>0&&await this.rootsByDate(i,t,c,i.take,void 0,r);else{let f=this.countedStrata.get(d);for(let u of i.take)u.take<=0||f?.get(at(u.value))===0||await this.rootsByDate(i,t,c,u.take,u,r)}}s++,this.progress("drawing",{objectApiName:d,done:s,total:e.length})}),o}orderedBy(e){return this.lists(e,he)&&this.options.sorts?.(e,he)!==!1?"created":"id"}async rootsByDate(e,t,r,o,s,i){let a=e.objectApiName,d=this.readOptionsOf(a),c=0,f;for(;c<o;){let u=this.rootShapeOf(e,s===void 0?{}:{stratum:s}),p=u.tested?ge:Math.min(ge,o-c),l=r==="created"?this.columnsOf(a,[...u.select,he]):u.select,{after:m,order:h}=uc(r,t,f),w=`SELECT ${l.join(", ")} FROM ${u.object}${qe([...u.terms,...m])} ORDER BY ${h} LIMIT ${p}`,y;try{y=await this.gather(w,d)}catch(O){if(!u.held||!Lt(O))throw O;this.slow.add(a);continue}let R=y.filter(u.isRoot).map(O=>String(O.Id)).slice(0,o-c);if(c+=R.length,R.length>0&&await(s===void 0?i(a,R):i(a,R,s.value)),y.length<p)return;f=pc(a,y[y.length-1],r)}}async readParents(e){let t=new Array(e.length);return await Ne(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=it(e.ids),s=this.readOptionsOf(t),i=await this.byList(t,r,"Id",o,this.termsOf(t),s),a=new Set(i.map(p=>q(String(p.Id)))),d=o.filter(p=>!a.has(q(p))),c=this.options.filterOf?.(t),f=[];if(d.length>0&&c!==void 0&&c.trim()!==""){let p=et.has(t)?["IsDeleted = false"]:[];f=await this.byList(t,r,"Id",d,p,s)}let u=new Set(f.map(p=>q(String(p.Id))));return{objectApiName:e.objectApiName,rows:i,columns:r,absent:d.filter(p=>!u.has(q(p))),outsideFilter:f}}async readStandardPrices(e,t){let r=it(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"&&Hn.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=it(t),i=it(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 ${fn(t).join(", ")} FROM ${e} WHERE ${a}`,c=[];for(let f of Qs(d,o,")")){let u=`SELECT ${t.join(", ")} FROM ${e} WHERE ${a}${f.map(p=>`'${p}'`).join(", ")})`;for(let p of await pn(u,l=>this.gather(l,i)))c.push(p)}return c}async readChildren(e){let t=new Array(e.length);return await Ne(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?[he]:[]]),d=it(e.parentIds),c=this.readOptionsOf(t),f=this.termsOf(t),u=new Map,p={objectApiName:t,field:r,rows:[],columns:a,cut:[],counts:new Map,newestBy:s},l=()=>{for(let b of d)p.counts.set(b,u.get(q(b))??0);return p};if(d.length===0)return p;if(o==="all"){let b=Gn(await this.byList(t,a,r,d,f,c),r,1/0,s);p.rows=b.rows;for(let[A,N]of b.counts)u.set(A,N);return l()}let m=[...f,`${r} IN (`].join(" AND "),h={head:`SELECT ${r}, COUNT(Id) n FROM ${t} WHERE ${m}`,tail:`) GROUP BY ${r}`},w={head:`SELECT ${fn(a).join(", ")} FROM ${t} WHERE ${m}`,tail:")"},y=ze(h.head+h.tail)>ze(w.head+w.tail)?h:w,R=[],O=[];for(let b of Qs(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,h,r,b,c);if(A===void 0){R.push(...b);continue}for(let N of A)N.rows>o?O.push(N):R.push(N.parentId)}let g=Gn(await this.byList(t,a,r,R,f,c),r,o,s);p.rows.push(...g.rows),p.cut.push(...g.cut);for(let[b,A]of g.counts)u.set(b,A);for(let b of O){let A=`SELECT ${a.join(", ")} FROM ${t} WHERE ${[...f,`${r} = '${b.parentId}'`].join(" AND ")} ORDER BY ${lc(s)} LIMIT ${o}`,N;try{N=await pn(A,x=>this.gather(x,c))}catch(x){if(!Xs(x))throw x;let v=Gn(await this.byList(t,a,r,[b.parentId],f,c),r,o,s);p.rows.push(...v.rows),p.cut.push(...v.cut);for(let[P,k]of v.counts)u.set(P,k);continue}p.rows.push(...N),p.cut.push({parentId:b.parentId,rows:Math.max(0,b.rows-N.length)}),u.set(q(b.parentId),b.rows)}return l()}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(!Xs(c))throw c;this.ungrouped.add(e);return}let d=[];for(let c of a){let f=c[r],u=Number(c.n);typeof f=="string"&&Number.isFinite(u)&&d.push({parentId:f,rows:u})}return d}async readWhole(e,t){await Ne(e,async r=>{let o=J(r.objectApiName),s=this.columnsOf(o,r.columns),i=this.readOptionsOf(o),a=`SELECT ${s.join(", ")} FROM ${o}${qe(this.termsOf(o))}`;for await(let d of ao(a,c=>this.pages(c,i),c=>this.gather(c,i)))await t(r.objectApiName,d)})}};function lc(n){return n==="created"?`${he} DESC, Id DESC`:"Id DESC"}function uc(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=`${he} ${s}, Id ${s}`;return t?{after:[`(${he} ${o} ${t.at} OR (${he} = ${t.at} AND Id ${o} '${t.id}'))`],order:i}:{after:[],order:i}}function fc(n,e){let t=new Map;for(let r of n){let o=Jn(r[e]),s=at(o),i=t.get(s)??{value:o,ids:[]};i.ids.push(String(r.Id)),t.set(s,i)}return[...t.values()]}function pc(n,e,t){let r=e.Id;if(typeof r!="string"||!Hn.test(r))throw new Error(`A record of ${n} came back without its id.`);if(t==="id")return{at:"",id:r};let o=e[he];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:Oe(o),id:r}}function ni(n){let e=n[he],t=typeof e=="string"?Date.parse(e):Number.NaN;return Number.isFinite(t)?t:void 0}function mc(n,e){let t=ni(n),r=ni(e);return t!==r?t===void 0?1:r===void 0?-1:r-t:le(String(e.Id),String(n.Id))}function Gn(n,e,t,r){let o=new Map;for(let d of n){let c=d[e];if(typeof c!="string")continue;let f=q(c),u=o.get(f);u?u.rows.push(d):o.set(f,{parentId:c,rows:[d]})}let s=[],i=[],a=new Map;for(let[d,{parentId:c,rows:f}]of o)f.sort(r==="created"?mc:(u,p)=>le(String(p.Id),String(u.Id))),s.push(...f.slice(0,t)),f.length>t&&i.push({parentId:c,rows:f.length-t}),a.set(d,f.length);return{rows:s,cut:i,counts:a}}function Dt(n,e,t=0){if(n.rows<=0)return 0;if(e==="uniform")return Math.ceil(n.rows/ge);let r=(s,i)=>Math.ceil(Math.min(Math.max(0,s),i)/ge);if(typeof t=="number")return r(t,n.rows);let o=new Map((n.strata??[]).map(s=>[at(s.value),s.rows]));return t.reduce((s,i)=>s+r(i.take,o.get(at(i.value))??i.take),0)}function em(n){let e=J(n.objectApiName),t=n.columns.some(p=>p.toLowerCase()==="systemmodstamp"),r=ro(n.columns,t?["Id","SystemModstamp"]:["Id"]),o=Math.max(0,n.planRows),s=Math.max(0,n.sourceRows),i=r.map(p=>so(e,p)),a=i.reduce((p,l)=>p+Math.ceil(o/l),0),d=Math.max(1,Math.ceil(s/ge)),c=Math.floor(s/ge),f=s%ge,u=d+i.slice(1).reduce((p,l)=>p+c*Math.ceil(ge/l)+(f>0?Math.ceil(f/l):0),0);return Xd.has(e)?{by:"cursor",requests:u,byIds:a,byCursor:u,cursorAlone:!0}:a<=u?{by:"ids",requests:a,byIds:a,byCursor:u}:{by:"cursor",requests:u,byIds:a,byCursor:u}}var gc=new Set(["BusinessHours","OperatingHours"]);function hc(n){let{storage:e,withinMB:t}=n,r=new Map;for(let d of n.automation??[])r.set(d.objectApiName,(r.get(d.objectApiName)??0)+d.bytes);let o=r.size>0?{automationBytes:d=>r.get(d)??0}:{};if("unread"in e){if(t===void 0)return;let d=Math.floor(Math.max(0,t)*1048576);return{budget:{bytes:d,withinMB:t,limitedBy:"within"},bytesLimit:"within",roomBytes:d,...o}}let s=ws({storage:e,...t!==void 0?{withinMB:t}:{}});if("unread"in s)return;let i=s.terms.limitedBy==="within"?"within":"storage",a=Math.floor(Ee*Math.max(0,e.remainingMB-Le)*1048576);return{budget:{bytes:s.bytes,remainingMB:e.remainingMB,maxMB:e.maxMB,share:Ee,roundingMB:Le,...t!==void 0?{withinMB:t}:{},limitedBy:i},bytesLimit:i,roomBytes:a,storageBytes:a,...o}}function wc(n,e){let t=n.nodes.filter(o=>o.included&&!Dr(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 cm(n){let e=n.options??{},t=wc(n.graph,new Set(n.excludedObjects??[])),r=t.reduce((m,h)=>m+ye(h.objectApiName,{rows:h.rows??0}),0),o=ss({storageBytes:r},n.storage),s=hc({storage:n.storage,...e.withinMB!==void 0?{withinMB:e.withinMB}:{}}),i=Mt({objects:t,referenceData:gc,...e.whole?{whole:e.whole}:{},roomBytes:s?.roomBytes??0,...n.maxRecordsPerObject!==void 0?{maxRecordsPerObject:n.maxRecordsPerObject}:{},wholeBytes:(m,h)=>ye(m,{rows:h})}),a=e.draw??Re.draw,d=s?Nt(s.budget.bytes,e.maxTotal):0,c=t.filter(m=>{let h=i.classes.get(m.objectApiName);return h?.kind==="drawn"&&h.rooted}),f=new Set(Object.keys(e.rootWhere??{}).map(m=>m.toLowerCase())),u=m=>e.window!==void 0||f.has(m.toLowerCase()),p=c.reduce((m,h)=>{let y=(i.linksOf.get(h.objectApiName)??[]).some(R=>R.carries&&R.required)?0:h.rows??0;return m+1+(u(h.objectApiName)?1:0)+Dt({objectApiName:h.objectApiName,rows:y,exact:!1},a,Math.min(y,d))},0),l=e.window!==void 0||f.size>0;return{wholeOrg:o,...s?{budget:s.budget}:{},whole:i.whole.filter(m=>m.why!=="asked"),planReads:{source:yc(p,n.source),seconds:p*Jo,...l?{atMost:!0}:{}}}}function yc(n,e){if("unread"in e)return{verdict:"unread",estimate:n,unread:e.unread};let t=rs(n,e);if(t.verdict==="unread")return t;let r=n>Math.floor(Te*e.remaining);return{...t,verdict:r?"exceeds":t.verdict}}var si=V({value:W(),validFor:Z(te().int().nonnegative()).optional()}).loose(),ii=V({controllerValues:on(W(),te().int().nonnegative()).optional(),defaultValue:si.nullable().optional(),values:Z(si)}).loose(),bc=V({picklistFieldValues:on(W(),Ie())}).loose(),Rc=/^[A-Za-z][A-Za-z0-9_]*$/,Sc=/^012[A-Za-z0-9]{12}([A-Za-z0-9]{3})?$/;function Oc(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 Ac(n){let e=bc.parse(n),t=new Map;for(let[r,o]of Object.entries(e.picklistFieldValues)){let s=ii.safeParse(o);s.success&&t.set(r,Oc(s.data))}return t}function kc(n){return ii.parse(n).values.map(e=>e.value)}function ai(n,e,t,r){for(let s of r===void 0?[e]:[e,r])if(!Rc.test(s))throw new Error(`Not an API name: "${s}"`);if(!Sc.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 um(n,e,t){return Ac(await n.request(ai(n,e,t)))}async function fm(n,e,t,r){return kc(await n.request(ai(n,e,t,r)))}var Ic=V({FileStorageMB:V({Remaining:te()}).loose()}).loose(),jc=Z(V({errorCode:W().optional(),message:W().optional()}).loose());function Nc(n){if(!(n instanceof Error))return new Error(String(n));try{let e=jc.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 wm(n,e,t){if(!go(t))throw new Error(`Not a record id: ${t}`);try{let r=await n.request({method:"GET",url:`/sobjects/${e}/${t}/${js[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 Nc(r)}}async function ym(n,e,t){try{let r=await n.request({method:"POST",url:`/sobjects/${e}`,body:JSON.stringify(t),headers:{"content-type":"application/json"}}),o=Rt(r,e);return{id:o.id,success:o.success,errors:o.errors}}catch(r){return{id:"",success:!1,errors:[wo(r)]}}}async function bm(n){return Ic.parse(await n.request({method:"GET",url:"/limits"})).FileStorageMB.Remaining}var Pc=["Task","Event","FeedItem","FeedComment","EmailMessage","ContentDocumentLink","Note","CaseComment"],li=["Account","Contact","Lead","Opportunity","Case","Campaign","Contract","Order","Asset","Product2"],Yn=["User","Group","GroupMember","PermissionSet","PermissionSetAssignment","PermissionSetGroup","RecordType","Profile","UserRole"],vc=1e3,Cc=6e4,Kn=1e4,xc=300,di=2e3,Mc=50,Lc=3,ui=3,_c=5,Dc=new Set(["flows","processes","triggers","conditions","definitions"]),fi=new Set(["OwnerId","CreatedById","LastModifiedById","RecordTypeId"]),dt=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function z(n){return n.slice(0,15)}function ne(n){return typeof n=="string"?Date.parse(n):Number.NaN}function Ue(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function Bc(n){let e=ne(n?.first),t=ne(n?.last);if(!(!Number.isFinite(e)||!Number.isFinite(t)))return{from:Math.floor((e-vc)/1e3)*1e3,to:Math.ceil((Math.max(e,t)+Cc)/1e3)*1e3}}function vm(n){if("error"in n)return{creates:[],gaps:{flowsNotRead:0,triggers:0,error:n.error}};let e=[],t=0,r=0;for(let s of n.objects){for(let i of[...s.flows,...s.processes??[]])if(i.startsOn!=="delete"){i.condition!=="read"&&t++;for(let a of i.creates??[])e.some(d=>d.toLowerCase()===a.toLowerCase())||e.push(a)}r+=s.triggers.filter(i=>i.events.some(a=>a!=="beforeDelete"&&a!=="afterDelete")).length}let o=n.unread.filter(s=>Dc.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 Cm(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 $c(n,e,t){let r=new Map,o=0,s;for(let{objectApiName:i,ids:a}of e){if(o>=Lc||r.size>1||t())break;let d=a.slice(0,Mc);if(d.length!==0)try{let[c]=X(d,d.length),f=await n.queryDeleted(`SELECT CreatedById FROM ${J(i)} WHERE Id IN (${c})`),u=!1;for(let p of f.records){let l=p?.CreatedById;typeof l=="string"&&dt.test(l)&&(r.has(z(l))||r.set(z(l),l),u=!0)}u&&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 Wc(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 qc(n){return n.queryable!==!1&&n.deletable!==!1&&n.createable!==!1&&n.layoutable!==!1&&!Yn.some(e=>e.toLowerCase()===n.name.toLowerCase())}async function pi(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:zc(t)}}function zc(n){return n.fields.filter(e=>e.type==="reference"&&!fi.has(e.name)&&!((e.referenceTo??[]).length>0&&(e.referenceTo??[]).every(t=>Yn.includes(t)))).map(e=>e.name)}function Uc(n,e){return`CreatedById = '${n}' AND CreatedDate >= ${Ue(e.from)} AND CreatedDate <= ${Ue(e.to)}`}function mi(n,e){return n.length===1?Uc(n[0],e):`CreatedById IN (${n.map(t=>`'${t}'`).join(", ")}) AND CreatedDate >= ${Ue(e.from)} AND CreatedDate <= ${Ue(e.to)}`}async function gi(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=Bc(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&&dt.test(e.runUserId)?e.runUserId:void 0,d=e.user!==void 0&&dt.test(e.user)?e.user:void 0,c=e.created.some(u=>u.ids.length>0),f=a?{user:a}:c?await $c(n,e.created,r):d!==void 0?{user:d}:{refusal:"The run created nothing, and none of the records it wrote over still says, in its window, who last modified it: the user it wrote as cannot be told, and nothing is swept."};return"refusal"in f?(o.refusal=f.refusal,s.stopped=r(),s):el(n,e,e.ties,f.user,s,i,t)}function Vc(n){return n.map(e=>`${e.objectApiName}: ${e.count}`).join(", ")}async function Gc(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 Jc(n){try{return(await n.query("SELECT Id FROM User WHERE UserType = 'AutomatedProcess'")).records.map(t=>t?.Id).filter(t=>typeof t=="string"&&dt.test(t))}catch{return[]}}async function Hc(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(u=>u!==void 0).map(J))],d=async u=>(await n.query(u)).records.filter(p=>typeof p=="object"&&p!==null),c=[],f;for(;;){if(s())return{rows:c,overBound:!1,stopped:!0};let u=`SELECT ${a.join(", ")} FROM ${i} WHERE ${mi([...t.values()],r)}${f?` AND Id > '${f}'`:""} ORDER BY Id LIMIT ${di}`,p;try{let l=oo(u);p=l?await io(await d(l.first),l,d):await d(u)}catch(l){return{reason:H(l)}}for(let l of p){if(typeof l.Id!="string")continue;f=l.Id;let m=typeof l.CreatedById=="string"?z(l.CreatedById):"",h=ne(l.CreatedDate);if(!t.has(m)||!(h>=r.from&&h<=r.to)||o(z(l.Id)))continue;let w=e.modifiedBy?l[e.modifiedBy]:void 0,y=e.nameField?l[e.nameField]:void 0,R=[];for(let O of e.references){let g=l[O];typeof g=="string"&&dt.test(g)&&R.push({field:O,key:z(g)})}if(c.push({id:l.Id,modified:ne(l[e.modified]),created:h,creator:m,references:R,...typeof w=="string"?{modifiedBy:z(w)}:{},...typeof y=="string"&&y.trim()!==""?{name:y.trim().slice(0,80)}:{}}),c.length>Kn)return{rows:c.slice(0,Kn),overBound:!0,stopped:!1}}if(p.length<di)return{rows:c,overBound:!1,stopped:!1}}}function Kc(n){let e=new Map,t=o=>{let s=o.toLowerCase(),i=e.get(s);return i||(i=(async()=>yt.parse(await n.describe(o)))(),i.catch(()=>{}),e.set(s,i)),i},r=async o=>{try{return await t(o)}catch{return}};return{of:t,now:r,async relation(o,s,i){let a=(await r(o))?.childRelationships?.find(d=>d.childSObject.toLowerCase()===s.toLowerCase()&&d.field===i);return{cascade:a?.cascadeDelete===!0,restricted:a?.restrictedDelete===!0}}}}async function Yc(n,e,t,r,o,s){let i=await Wc(n),a=l=>i?i.get(l.toLowerCase()):{name:l},d=[],c=[],f=l=>d.some(m=>m.toLowerCase()===l.toLowerCase()),u=l=>Yn.some(m=>m.toLowerCase()===l.toLowerCase()),p=(l,m)=>{if(f(l)||u(l))return;let h=a(l)?.name;if(!h){m&&o.unread.push({objectApiName:l,reason:"The org has no such object."});return}if(d.length>=xc){c.includes(h)||c.push(h);return}d.push(h)};for(let l of e)p(l,!0);for(let l of Pc)p(l,!1);for(let l of t)p(l,!0);for(let l of li)p(l,!1);for(let l of e){if(s())return;for(let m of(await r.now(l))?.childRelationships??[]){let h=a(m.childSObject);h&&qc(h)&&!f(h.name)&&p(h.name,!1)}}return{looked:d,notLooked:c}}async function Zc(n,e,t,r,o,s,i){let a=[],d=new Map([...r.keys()].map(c=>[c.toLowerCase(),c]));for(let c of e){let f=((await o.now(c))?.fields??[]).filter(u=>u.type==="reference"&&!fi.has(u.name));for(let u of f)for(let p of u.referenceTo??[]){let l=d.get(p.toLowerCase());if(!l)continue;let m=(r.get(l)??[]).map(y=>y.id),{restricted:h}=await o.relation(l,c,u.name),w=J(u.name);for(let y of X(m)){if(i())return;let R;try{R=(await n.query(`SELECT Id, ${w} FROM ${J(c)} WHERE ${w} IN (${y})`)).records}catch(O){s.unread.push({objectApiName:c,reason:`What its ${u.name} points at among the records found could not be read (${H(O)}): what only it ties is left as tied to nothing.`});continue}for(let O of R){let{Id:g,[u.name]:b}=O??{};typeof g!="string"||typeof b!="string"||t.has(z(g))&&a.push({from:z(g),to:z(b),restricted:h})}}}}return a}async function Qc(n,e,t,r){let o=new Map;for(let s of t){let i=e.get(s);i?.kind==="created"&&o.set(i.objectApiName,[...o.get(i.objectApiName)??[],i.id])}for(let[s,i]of o)for(let a of X(i)){if(r())return!1;try{let d=await n.queryDeleted(`SELECT Id, CreatedDate FROM ${J(s)} WHERE Id IN (${a})`);for(let c of d.records){let{Id:f,CreatedDate:u}=c??{},p=typeof f=="string"?e.get(z(f)):void 0,l=ne(u);p&&Number.isFinite(l)&&(p.from=l,p.to=l)}}catch{}}return!0}function Xc(n,e,t,r,o,s){let{listing:i}=r,a=new Set(li.map(l=>l.toLowerCase())),d=[],c=[],f=["made","madeOver","late","untied"];for(let[l,m]of n){let h=[],w=0;for(let b of m){let A=e.get(z(b.id));if(A){if(A.class==="untied"&&a.has(l.toLowerCase())){w++;continue}h.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(w>0&&i.handWork.push({objectApiName:l,count:w}),h.length===0)continue;let y={made:0,madeOver:0,late:0,untied:0},R=0,O=0,g={};for(let b of h)y[b.class]++,b.sameSave&&R++,Bt(b,o,s)&&(O++,g[b.class]=(g[b.class]??0)+1);i.found.push({objectApiName:l,count:h.length,names:f.flatMap(b=>h.filter(A=>A.class===b)).flatMap(b=>b.name?[b.name]:[]).slice(0,ui),classes:{...y,...R>0?{sameSave:R}:{},...O>0?{changed:O,changedIn:g}:{}}}),y.untied>0&&d.push({objectApiName:l,count:y.untied}),y.late>0&&c.push({objectApiName:l,count:y.late}),r.rows.set(l,h)}let u=[];i.handWork.length>0&&u.push(`The run's user created records in the run's window tied to nothing of the run, on objects people make by hand (${Vc(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(l=>l.ids.length>0||l.idsUntold===!0).length;p>0&&u.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.`),u.length>0&&u.push("The runs of another machine, or of a CI, in the same window are not seen."),i.untied={objects:d,...u.length>0?{refusal:u.join(" ")}:{}},i.late=c}async function el(n,e,t,r,o,s,i){let{listing:a}=o,d=()=>e.signal?.aborted===!0,c=()=>(o.stopped=!0,o),f=ne(e.writtenBetween?.first),u=Math.max(f,ne(e.writtenBetween?.last)),p=Math.min(Number.POSITIVE_INFINITY,...[t.removalBegan,...i.map(T=>T.first)].map(ne).filter(Number.isFinite)),l=Math.ceil((u+9e5)/1e3)*1e3,m={from:s.from,to:Math.max(s.to,Math.min(l,Math.floor(p/1e3)*1e3))},h=new Map,w={from:f,to:u};for(let{objectApiName:T,ids:L}of e.created)for(let _ of L)h.set(z(_),{kind:"created",objectApiName:T,id:_,from:Number.NaN,to:Number.NaN});for(let{objectApiName:T,ids:L,between:_}of t.writtenOver??[]){let $=ne(_?.first),U=ne(_?.last);for(let Q of L)h.has(z(Q))||h.set(z(Q),{kind:"overwritten",objectApiName:T,id:Q,from:$,to:U})}let y=[...new Set([...e.created,...t.writtenOver??[]].filter(T=>T.ids.length>0).map(T=>T.objectApiName))],R=new Set([...(t.otherRuns??[]).flatMap(T=>T.ids.map(z)),...(t.leased??[]).map(z)]),O=T=>e.remap.has(T)||h.has(T)||R.has(T),g=await Jc(n),b=new Map([[z(r),r]]);for(let T of g)b.has(z(T))||b.set(z(T),T);let A=new Set(g.map(z).filter(T=>T!==z(r))),N=Kc(n),x=await Yc(n,y,e.automation.creates,N,a,d);if(!x)return c();let{looked:v,notLooked:P}=x;a.looked=v,P.length>0&&(a.notLooked=P);let k=await Gc(n,v.map(T=>`SELECT COUNT() FROM ${J(T)} WHERE ${mi([...b.values()],m)}`),d);if(d())return c();let j=new Map,M=[];for(let[T,L]of v.entries()){let _=k[T];if(_===void 0)return c();if(_===0)continue;if(d())return c();let $=await pi(L,N.of);if("reason"in $){a.unread.push({objectApiName:L,reason:$.reason});continue}if(typeof _=="object"){a.unread.push({objectApiName:L,reason:_.reason});continue}let U=await Hc(n,$,b,m,O,d);if("reason"in U){a.unread.push({objectApiName:L,reason:U.reason});continue}if(U.stopped)return c();U.overBound?M.push({objectApiName:L,count:U.rows.length,names:U.rows.flatMap(Q=>Q.name?[Q.name]:[]).slice(0,ui),overBound:!0}):U.rows.length>0&&j.set(L,U.rows)}let D=new Map;for(let{part:T,created:L}of e.otherParts??[])for(let{objectApiName:_,ids:$}of L)for(let U of $)D.set(z(U),{part:T,objectApiName:_});let E=new Map;for(let[T,L]of D.size>0?[...j]:[]){let _=[];for(let $ of L){let U,Q=!1;for(let ke of $.references){let jr=h.get(ke.key)??D.get(ke.key);if(!jr)continue;let{cascade:ha}=await N.relation(jr.objectApiName,T,ke.field);ha&&(h.has(ke.key)?Q=!0:U??=D.get(ke.key)?.part)}if(U===void 0||Q){_.push($);continue}let fe=E.get(U)??[],ft=fe.find(ke=>ke.objectApiName===T);ft?ft.count++:fe.push({objectApiName:T,count:1}),E.set(U,fe)}_.length>0?j.set(T,_):j.delete(T)}E.size>0&&(a.otherParts=[...E].map(([T,L])=>({part:T,objects:L})));let F=new Map;for(let[T,L]of h)F.set(T,L.objectApiName);for(let[T,L]of j)for(let _ of L)F.set(z(_.id),T);let S=[],I=new Set;for(let[T,L]of j)for(let _ of L){let $=[];for(let U of _.references){let Q=F.get(U.key);if(!Q)continue;h.has(U.key)&&I.add(U.key);let{cascade:fe}=await N.relation(Q,T,U.field);$.push({key:U.key,cascade:fe})}S.push({key:z(_.id),created:_.created,automatedProcess:A.has(_.creator),references:$})}let C=await Zc(n,y,h,j,N,a,d);if(!C)return c();for(let T of C)I.add(T.from);if(!await Qc(n,h,I,d))return c();let B=jo({anchors:h,candidates:S,pointers:C,runSpan:w,window:s,removalBegan:p,madeEarlier:new Set((t.madeEarlier??[]).map(z)),lateEarlier:new Set((t.lateEarlier??[]).map(z))});return Xc(j,B,t,o,u,i),d()?c():(await tl(n,N,o,{user:r,span:m,lastWrite:u,removalSpans:i,isRun:T=>h.has(T)||e.remap.has(T)}),a.found.push(...M),t.muted&&(a.muted=t.muted),o.ordering={query:T=>n.query(T),queryDeleted:T=>n.queryDeleted(T),describe:async T=>await N.now(T)??n.describe(T),describeGlobal:()=>n.describeGlobal(),destroy:(T,L)=>n.destroy(T,L),update:(T,L)=>n.update(T,L),serverTime:()=>n.serverTime(),userId:()=>n.userId()},o)}var ci={untied:0,late:1,madeOver:2,made:3};async function tl(n,e,t,r){let o=new Map;for(let l of t.rows.values())for(let m of l)o.set(z(m.id),m);if(o.size===0||t.rows.has(ce))return;let s=(await No(n,{has:l=>o.has(l)||r.isRun(l),start:r.span.from,end:r.span.to,user:r.user})).filter(l=>!r.isRun(z(l.id))&&l.names.some(m=>o.has(m)));if(s.length===0)return;let i=await pi(ce,e.of);if("reason"in i){t.listing.unread.push({objectApiName:ce,reason:i.reason});return}let a=new Map,d=s.map(l=>{let m=l.names.flatMap(R=>{let O=o.get(R);return O?[O]:[]});a.set(l.id,m.map(R=>z(R.id)));let h=m.reduce((R,O)=>ci[O.class]<ci[R]?O.class:R,"made"),w=Math.max(...m.map(R=>R.created)),y=l.modifiedBy!==void 0&&z(l.modifiedBy)===z(r.user)&&l.modified<=w+6e4;return{id:l.id,created:l.created,modified:y?Math.min(l.modified,l.created):l.modified,...l.modifiedBy!==void 0?{modifiedBy:z(l.modifiedBy)}:{},class:h,turn:"before"}});t.rows.set(ce,d),t.reports=a;let c={made:0,madeOver:0,late:0,untied:0},f=0,u={};for(let l of d)c[l.class]++,Bt(l,r.lastWrite,r.removalSpans)&&(f++,u[l.class]=(u[l.class]??0)+1);let{listing:p}=t;p.found.push({objectApiName:ce,count:d.length,names:[],classes:{...c,...f>0?{changed:f,changedIn:u}:{}}}),c.late>0&&(p.late=[...p.late??[],{objectApiName:ce,count:c.late}]),c.untied>0&&p.untied&&(p.untied={...p.untied,objects:[...p.untied.objects,{objectApiName:ce,count:c.untied}]})}function Bt(n,e,t){let r=Math.max(e,n.created)+2e3;return!(n.modified<=r)&&!nl(n,t)}function nl(n,e){return n.modifiedBy!==void 0&&e.some(t=>n.modifiedBy===z(t.userId)&&n.modified>=ne(t.first)&&n.modified<=ne(t.last))}async function xm(n,e,t=[]){return(await gi(n,e,t)).listing}function rl(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 Mm(n,e,t){let r=()=>e.signal?.aborted===!0,o=ho(),s=new Set,i=new Set,a=new Set,d=new Set,c=[],f="new",u,p,l,m=new Map,h={unread:[],handWork:[]},w=new Map,y=new Map,R=async(P,k)=>{let j=P.lastWrite??Number.NaN,M=new Set,D=new Map;for(let[C,B]of k){let T=B.filter(L=>t.includeChanged||!Bt(L,j,t.removalSpans)).map(L=>L.id);for(let L of T)M.add(L);D.set(C,T)}if(M.size===0||!P.window)return;let E=new Set(e.created.flatMap(({ids:C})=>C.map(z))),F=P.ordering??n,S=Eo(F,{runStart:P.window.from,runEnd:j,runRecords:{has:C=>E.has(C)},taken:M,removalSpans:t.removalSpans,includeChanged:t.includeChanged,...e.runUserId?{runUserId:e.runUserId}:{}}),I=await hn(F,[...k.keys()].map(C=>({objectApiName:C})));for(let{objectApiName:C}of I){if(C===ce)continue;let B=D.get(C)??[];if(B.length===0)continue;if(r())return;let T=await S(C,B);T.reason!==void 0&&y.set(C,T.reason);for(let L of B)T.held.has(z(L))&&(M.delete(L),w.set(L,T.holders))}O(P,k,M)},O=(P,k,j)=>{let M=P.reports;if(!M)return;let D=new Set([...k].filter(([E])=>E!==ce).flatMap(([,E])=>E.filter(F=>j.has(F.id)).map(F=>z(F.id))));for(let E of k.get(ce)??[])w.has(E.id)||(M.get(E.id)??[]).every(F=>D.has(F))||(j.delete(E.id),w.set(E.id,["DuplicateRecordItem"]))},g=(P,k)=>{P.result.alreadyGone++,P.along.has(k)&&(P.result.withRemoval=(P.result.withRemoval??0)+1)},b=(P,k,j)=>{k.forEach((M,D)=>{let E=j[D];if((E.lockResends!==void 0||P.lockResent.has(M))&&P.lockResent.set(M,E.kind),E.kind==="refused"){P.refused.set(M,E.reason),E.limit&&P.limited.add(M);return}P.refused.delete(M),P.limited.delete(M),d.add(M),E.kind==="deleted"?P.result.deleted++:g(P,M)})},A=async(P,k,j)=>{for(let M=0;M<k.length;M+=Me){if(r())return!1;let D=k.slice(M,M+Me),E=P.result.deleted,F=await Ao(n,P.result.objectApiName,D,o,{stopped:r,settle:(S,I)=>b(P,S,[...I])});if(j&&P.result.deleted>E){let S=P.result.deleted-E;P.result.afterRemoval=(P.result.afterRemoval??0)+S,j==="under"&&(P.result.afterRemovalUnder=(P.result.afterRemovalUnder??0)+S)}if(F)return!1}return!0},N=()=>c.reduce((P,k)=>P+k.result.deleted,0),x=async()=>{let P=h.left??[];if(P.length===0||!l)return;let k=l.rows,j=[],M=[];for(let E of P){let F=[],S=[];for(let I of E.objects){let C=(k.get(I.objectApiName)??[]).filter(L=>L.class===E.class).map(L=>L.id),B=r()?[]:(await wn(C,L=>pe(n,I.objectApiName,[],L),()=>!0)).gone;for(let L of B)d.add(L);let T=Math.min(B.length,I.count);I.count>T&&F.push({...I,count:I.count-T}),T>0&&S.push({objectApiName:I.objectApiName,count:T})}F.length>0&&j.push({...E,objects:F}),S.length>0&&M.push({class:E.class,objects:S})}if(M.length===0)return;let D={...h};delete D.left,h={...D,...j.length>0?{left:j}:{},goneAlong:M}},v=()=>(p??=(async()=>{let P=await gi(n,e,t.removalSpans);l=P;let{listing:k}=P;if(h={...k.window?{window:k.window}:{},unread:[...k.unread,...k.found.filter(E=>E.overBound).map(E=>({objectApiName:E.objectApiName,reason:`More than ${Kn} records created by the run's user in the window: none is swept, as that many are more than the run\u2019s side effects come to.`}))],...k.automationGaps?{automationGaps:k.automationGaps}:{},handWork:k.handWork},P.stopped){f="cancelled";return}for(let E of P.rows.values())for(let F of E)F.class==="made"||F.class==="madeOver"?i.add(F.id):F.class==="late"&&a.add(F.id);if(k.refusal!==void 0){f="refused",u=k.refusal;return}let j=t.sweepUntied===!0&&k.untied?.refusal===void 0,M=E=>E.class==="made"||E.class==="madeOver"||E.class==="late"&&t.sweepLate===!0||E.class==="untied"&&j;if(m=new Map([...P.rows].map(([E,F])=>[E,F.filter(M)]).filter(([,E])=>E.length>0)),await R(P,m),r()){f="cancelled";return}if(t.approve&&m.size>0){let E=await t.approve(k);if(E!==void 0){f="refused",u=E;return}}let D=rl(k,t);D.length>0&&(h={...h,left:D}),f="asked"})(),p);return{automationMade:s,made:i,late:a,gone:d,get listing(){return l&&!l.stopped?l.listing:void 0},get takes(){return f==="asked"?[...m.keys()]:[]},ask:v,async first(P){if(P&&(o=P),await v(),f!=="asked"||!l)return!1;let k=l,j=m,M=k.lastWrite??Number.NaN,D=await hn(k.ordering??n,[...j.keys()].map(F=>({objectApiName:F}))),E=[];for(let{objectApiName:F}of D){let S=j.get(F)??[],I={result:{objectApiName:F,found:S.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(I);let C=[];for(let B of S){if(Bt(B,M,t.removalSpans)&&!t.includeChanged){I.result.keptChanged++;continue}let T=w.get(B.id);if(T){I.result.keptDependents=(I.result.keptDependents??0)+1,I.result.heldBy=[...new Set([...I.result.heldBy??[],...T])];continue}s.add(B.id),B.turn==="before"?C.push(B.id):I.later.push(B.id),B.turn==="with"&&I.along.add(B.id)}E.push([I,C])}for(let[F,S]of E)if(!await A(F,S))return f="cancelled",N()>0;return f="first",N()>0},async afterRemoval(P){if(P&&(o=P),f!=="first")return!1;let k=N();for(let j of c){let M=j.later.splice(0),D=M.filter(F=>j.along.has(F)),E=M.filter(F=>!j.along.has(F));if(!await A(j,E,"pointedAt")||!await A(j,D,"under"))return f="cancelled",N()>k}if(N()>0)for(let j of c){let M=[...j.refused.keys()].filter(D=>!j.limited.has(D));if(!await A(j,M))return f="cancelled",N()>k}for(let j of c){if(r())break;let{gone:M}=await wn([...j.refused.keys()],D=>pe(n,j.result.objectApiName,[],D),()=>!0);for(let D of M)j.refused.delete(D),j.lockResent.has(D)&&j.lockResent.set(D,"gone"),g(j,D),d.add(D)}return await x(),f="done",N()>k},result(){if(f==="refused")return{status:"refused",refusal:u??"",objects:[],...h};if(f==="new"||f==="asked")return{status:"cancelled",objects:[],...h};let P=c.map(({result:j,refused:M,lockResent:D})=>{j.refused=M.size;let E=y.get(j.objectApiName);return j.reasons=[...new Set([...E!==void 0&&(j.keptDependents??0)>0?[`What hangs from them could not be read, and they were kept: ${E}`]:[],...ko(j.objectApiName,o),...Io(D.values()),...M.values()])].slice(0,_c),j}),k=c.some(j=>j.later.length>0);return{status:ol(P,f==="cancelled",k,sl(h,t)),objects:P,...h}}}}function ol(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 sl(n,e){return(n.left??[]).some(t=>t.class==="late"&&e.sweepLate===!0||t.class==="untied"&&e.sweepUntied===!0)}function Lm(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 _m(n){return n.objects.filter(e=>e.deleted+e.refused>0).map(e=>({...to(e.objectApiName),deleted:e.deleted,failed:e.refused}))}function Dm(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 Bm(n){return n.found.reduce((e,t)=>e+t.count,0)}function $m(n){return n.found.map(e=>e.objectApiName)}var il=15e3,zm=2,al=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function dl(n,e){try{let{user_id:t}=await new Ot(il).withTimeout(`${e} run user`,async()=>n());return typeof t=="string"&&al.test(t)?t:void 0}catch{return}}function Um(n,e,t){n?.runUser&&dl(e,t).then(r=>{r!==void 0&&n.runUser?.(r)})}var Qn=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},cl=1440*60*1e3,hi=2,Ri=new Set(["picklist","boolean","reference"]),ll=6,Zn=12;function ul(n){return n.replace(/'(?:[^'\\]|\\.)*'/g,"''")}function wi(n){return n===void 0?0:ul(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 $t(n){if(n.length===0)return"none";let e=n.slice(0,Zn).join(", ");return n.length>Zn?`${e} and ${n.length-Zn} more`:e}function fl(n,e){if(n.lastDays!==void 0&&n.from===void 0&&n.to===void 0)return{window:{field:n.field,from:Oe(e-n.lastDays*cl),lastDays:n.lastDays}};let t=s=>{if(s!==void 0)try{return Oe(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 yi(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 Si(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 pl(n,e){let t=(n.fieldsOf(e)??[]).filter(s=>s.groupable!==!1&&Ri.has(s.type??"")&&Si(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,ll)}function Wt(n,e){let t=pl(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 bi(n,e,t){let r=n.fieldsOf(e),o=Ve(r,t);if(!o)return{problem:`${e} has no field ${t}. ${Wt(n,e)}`};if(!Ri.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. `)+Wt(n,e)};let s=Si(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. `+Wt(n,e)}:o.groupable===!1?{problem:`The source does not group ${e} by ${o.name}, which its strata are counted by. ${Wt(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 Oi(n){let{links:e,options:t}=n,r=[],o;if(t.window!==void 0){let w=fl(t.window,n.now);"problem"in w?r.push(w.problem):o=w.window}let s=[...e.classes].filter(([,w])=>w.kind==="drawn"&&w.rooted).map(([w])=>w).sort(),i=s.filter(w=>!yi(e,w)),a=new Map([...e.classes.keys()].map(w=>[w.toLowerCase(),w])),d=new Map([...n.excluded??[]].map(w=>[w.toLowerCase(),w])),c=(w,y)=>{let R=y==="where"?"filter on its roots":"strata",O=a.get(w.toLowerCase()),g=O===void 0?void 0:e.classes.get(O);if(O===void 0||g===void 0){let A=d.get(w.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.`:`${w} is no object of the run, and takes no ${R}. The objects whose roots are drawn are ${$t(i)}.`);return}if(g.kind==="whole"){r.push(`Every record of ${O} 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 ${$t(i)}.`));return}if(!g.rooted){r.push(`${O} 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 ${$t(i)}.`);return}let b=yi(e,O);if(b){r.push(`Every record of ${O} 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 ${O} WHERE \u2026)".`:`Stratify the roots of ${b.parent} instead.`));return}return O},f=new Map;for(let[w,y]of Object.entries(t.rootWhere??{})){let R=c(w,"where");if(R===void 0)continue;if(f.has(R)){r.push(`The roots of ${R} are given two filters: give one.`);continue}let O=wi(n.filterOf?.(R))+wi(y);if(O>hi){r.push(`A statement of ${R} takes ${hi} semi-joins at most (IN (SELECT \u2026)), and its filter and the filter on its roots hold ${O}: write one of them without, or fold them into fewer.`);continue}f.set(R,y.trim())}let u,p=new Map;for(let w of t.strata??[]){let y=w.indexOf(".");if(y<0){u=w;continue}let R=c(w.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,w.slice(y+1))}}let l=new Map;for(let[w,y]of p){let R=bi(n,w,y);"problem"in R?r.push(R.problem):l.set(w,R.field)}if(u!==void 0){let w=!1;for(let y of i){if(p.has(y))continue;let R=n.fieldsOf(y),O=Ve(R,u);if(!O||O.groupable===!1||Ve(R,"Id")?.aggregatable===!1)continue;w=!0;let g=bi(n,y,O.name);"problem"in g?r.push(`${g.problem} Or name each object ${u} stratifies, as Object.${u}.`):l.set(y,g.field)}w||r.push(`No object whose roots are drawn \u2014 ${$t(i)} \u2014 has a field ${u} it groups by. Name the object and its field, as ${i[0]??"Account"}.RecordTypeId.`)}if(r.length>0)throw new Qn(r);let m=[],h=new Map;for(let w of s){let y=f.get(w),R=l.get(w),O={objectApiName:w,...y!==void 0?{where:y}:{},...R!==void 0?{stratifiedBy:R}:{}};o!==void 0&&(Ve(n.fieldsOf(w),o.field)?O.window={field:o.field,...o.from!==void 0?{from:o.from}:{},...o.to!==void 0?{to:o.to}:{}}:(O.notWindowed=!0,m.push(w))),h.set(w,O)}return{...o!==void 0?{window:o}:{},objects:h,notWindowed:m,where:[...f].map(([w,y])=>({objectApiName:w,where:y})).sort((w,y)=>w.objectApiName<y.objectApiName?-1:1),restricted:o!==void 0||f.size>0,stratified:l.size>0}}function Ai(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 ml(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 gl=1e6,Xn=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},er=class extends Error{constructor(){super("The sample was cancelled before it was drawn. Nothing was written."),this.name="SampleCancelled"}},hl="AccountId",tr=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}},qt=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(q(t))}isAbsent(e,t){return this.absent.get(e)?.has(q(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===hl&&e.parent===de&&this.rows[t].personAccount===!0}requiredOf(e){let t=this.objectOf[e],{refs:r,also:o}=this.rows[e],s=[],i;for(let a of this.links.linksOf.get(t)??[]){if(!this.requiredHere(a,e))continue;let d=r[a.field];Fe(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];Fe(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(!Fe(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(q(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(l=>this.rows[l].id).sort(le);this.checkSignal();let c=await this.reader.children(i,d,a),f=new Map;for(let l of c.rows){let m=l.refs[i.field];if(typeof m!="string"||m==="")continue;let h=o.parents.get(q(m));if(h===void 0)continue;let w=f.get(h)??new Map;w.has(q(l.id))||w.set(q(l.id),l),f.set(h,w)}let u=new Map;for(let[l,m]of c.counts??[])u.set(q(l),m);let p=this.cuts.get(r)??new Map;for(let[l,m]of[...f].sort(([h],[w])=>h-w)){let h=[...m.values()].sort(ml),w=a==="all"?h:h.slice(0,a),y=this.below.get(l)??[];for(let O of w){let g=this.register(i.objectApiName,O);y.push({child:g,relation:r}),this.descended[g]||this.toDescend.push(g)}this.below.set(l,y);let R=u.get(q(this.rows[l].id))??m.size;R>w.length&&p.set(l,R-w.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
|
-
${q(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(q(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(q(r)),this.absent.set(e,o);let s=`${e}
|
|
26
|
-
${q(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=q(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??gl;if(this.rows.length>a)throw new Xn(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 er}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 tr;for(let c=0;c<t;c++){let f=this.rootOf[c];f>=0&&!e.has(f)&&(r[c]=f,i.push(f,c))}let a=new Uint8Array(t);for(;i.size>0;){let[c,f]=i.pop();if(!(a[f]||c>r[f]||!this.alive(f))){a[f]=1;for(let{child:u,relation:p}of this.below.get(f)??[])c<r[u]?(r[u]=c,s[u]=p,i.push(c,u)):c===r[u]&&p<(s[u]??"")&&(s[u]=p)}}let d=new Float64Array(r);for(let c=0;c<t;c++)this.whole[c]&&(d[c]=-1),d[c]!==1/0&&i.push(d[c],c),o[c]=s[c];for(a.fill(0);i.size>0;){let[c,f]=i.pop();if(!(a[f]||c>d[f]||!this.alive(f))){a[f]=1;for(let{row:u,field:p}of this.upTargets(f)){let l=`${this.objectOf[f]}.${p}`;c<d[u]?(d[u]=c,o[u]=l,i.push(c,u)):c===d[u]&&o[u]!==void 0&&l<o[u]&&(o[u]=l)}}}return{threshold:d,above:r,via:o}}};var ji={bytes:(n,e)=>e.bytes??ns(n,e.personAccount?{IsPersonAccount:!0}:{}),wholeBytes:(n,e)=>ye(n,{rows:e})},wl=[{objectApiName:oe,field:"AccountId",writes:"AccountContactRelation",ownField:"ContactId",pairField:"AccountId"},{objectApiName:"Opportunity",field:"ContactId",writes:"OpportunityContactRole",ownField:"OpportunityId",pairField:"ContactId"}],yl=.1,bl=256,Rl=5;function nr(n,e){return e<0?-1/0:e===1/0?1/0:n[e].rank}function Ni(n,e){let t=n.rows[e];return t.matched||n.objectOf[e]===oe&&t.personAccount===!0?0:1}function Sl(n,e,t){let r=new Map,{links:o}=n,s=t.filter(i=>o.classes.has(i.writes)&&(o.linksOf.get(i.objectApiName)??[]).some(a=>a.field===i.field));if(s.length===0)return r;for(let i=0;i<n.rows.length;i++)if(n.alive(i))for(let a of s){if(n.objectOf[i]!==a.objectApiName)continue;let d=n.rows[i];if(a.objectApiName===oe&&d.personAccount)continue;let c=d.refs[a.field],f=Zs(o,a.objectApiName,a.field,c);if(!f||typeof c!="string")continue;let u=n.rowOf(f.parent,c);if(u===void 0||!n.alive(u))continue;let p=Math.max(e.threshold[i],e.threshold[u]);p!==1/0&&r.set(`${a.writes}
|
|
29
|
-
${q(d.id)}
|
|
30
|
-
${q(c)}`,{objectApiName:a.writes,threshold:p,rows:[]})}for(let i=0;i<n.rows.length;i++)if(n.alive(i))for(let a of s){if(n.objectOf[i]!==a.writes)continue;let{refs:d}=n.rows[i],c=d[a.ownField],f=d[a.pairField];if(typeof c!="string"||typeof f!="string")continue;let u=r.get(`${a.writes}
|
|
31
|
-
${q(c)}
|
|
32
|
-
${q(f)}`);u&&u.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 Ol(n,e,t){let{measure:r,draw:o}=t,s=[],i=new Float64Array(n.rows.length),a=new Map,d=(u,p)=>{u>=0&&u!==1/0&&a.set(u,(a.get(u)??0)+p)},c=Sl(n,e,t.platformPairs??wl),f=new Set;for(let u of c.values())u.rows.length>0&&f.add(u.rows[0]);for(let u=0;u<n.rows.length;u++){if(!n.alive(u))continue;let p=n.objectOf[u],l=n.rows[u],m=f.has(u)?0:Ni(n,u),w=(l.matched||f.has(u)?0:r.bytes(p,l))+m*(r.roomBytes?.(p)??0);i[u]=w;let y=e.threshold[u];y!==1/0&&(s.push({rank:nr(o.roots,y),bytes:w,records:m,objectApiName:p}),d(y,w))}for(let u of c.values()){let p=r.bytes(u.objectApiName,{id:"",refs:{}});s.push({rank:nr(o.roots,u.threshold),bytes:p,records:0,objectApiName:u.objectApiName}),d(u.threshold,p)}for(let[u,p]of n.links.classes){if(p.kind!=="whole"||n.wasReadWhole(u))continue;let l=t.sourceRows.get(u)??0,m=p.why==="referenceData",h=m?0:l;s.push({rank:-1/0,bytes:(m?0:r.wholeBytes(u,l))+h*(r.roomBytes?.(u)??0),records:h,objectApiName:u})}return s.sort((u,p)=>u.rank-p.rank),{items:s,rowBytes:i,parts:a,pairs:c}}function Ei(n,e,t){let r=0,o=0,s=new Map;for(let i of n){if(i.rank>e)break;r+=i.bytes,o+=i.records,t&&i.records>0&&s.set(i.objectApiName,(s.get(i.objectApiName)??0)+i.records)}return{bytes:r,records:o,written:s}}function zt(n,e,t){let r=Ei(n,e,t.requests!==void 0);return r.bytes>t.bytes?ys(r.bytes,t):t.maxTotal!==void 0&&r.records>t.maxTotal?"maxTotal":t.requests?.(r.written)}function ki(n,e,t){let r=yl*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=Ti(n);for(s!==void 0&&o.add(s);;){let i=n.thresholds(t),a=Ol(n,i,e),d=[...a.parts].filter(([c,f])=>f>r&&!t.has(c)&&!o.has(c)).map(([c])=>c);if(d.length===0)return{thresholds:i,weighed:a};for(let c of d)t.add(c)}}function Ti(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 Ii(n,e,t,r){let o=Ei(e,t,!1),s=new Map;for(let i of e){if(i.rank>t)break;let a=s.get(i.objectApiName)??{rows:0,storageBytes:0};a.rows+=i.records,a.storageBytes+=i.bytes,s.set(i.objectApiName,a)}return{kind:"cannotFit",limitedBy:zt(e,t,r)??r.bytesLimit,rows:o.records,storageBytes:o.bytes,heaviest:[...s].sort(([i,a],[d,c])=>c.storageBytes-a.storageBytes||(i<d?-1:i>d?1:0)).slice(0,Rl).map(([i,a])=>({objectApiName:i,...a,...n.links.classes.get(i)?.kind==="whole"?{whole:!0}:{}}))}}async function Fi(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 qt(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=bl,d=ki(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=ki(o,t,s),zt(d.weighed.items,e[i-1].rank,r)!==void 0)break}return t.onStep?.("fitting",o.rows.length),Al(o,d,s,t,e.slice(0,i),i===e.length)}function Al(n,e,t,r,o,s){let{bounds:i,draw:a}=r,{items:d}=e.weighed,c=[...new Set(o.map(w=>w.rank))].sort((w,y)=>w-y),f=a.floor>0&&c[0]===0?c:[-1/0,...c],u=bs(f.length,w=>zt(d,f[w-1],i)===void 0);if(u===0)return Ii(n,d,f[0],i);let p=f[u-1],l=Ti(n);if(l!==void 0&&o[l].rank>p)return{...Ii(n,d,o[l].rank,i),noRoot:!0};let m=Il(n,e,t,r,p),h=u<f.length?zt(d,f[u],i)??i.bytesLimit:!s||a.beyond!==1/0?a.heldBy:m.heavyRoots.length>0?"heavyRoots":a.restricted===!0?"draw":"whole";return{kind:"sample",share:h==="whole"||h==="heavyRoots"||h==="draw"?1:Math.max(0,p),limitedBy:h,wholeOrgFits:kl(n,r),...m}}function kl(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 Il(n,e,t,r,o){let{links:s}=n,{thresholds:i,weighed:a}=e,d=r.draw.roots,c=k=>nr(d,k),f=k=>n.alive(k)&&c(i.threshold[k])<=o,u=k=>{if(n.whole[k])return"whole";let j=n.rootOf[k];return j>=0&&!t.has(j)&&c(j)<=o?"root":c(i.above[k])<=o?"below":"parent"},p=new Map,l=k=>{let j=p.get(k);return j||(j={objectApiName:k,sourceRows:r.sourceRows.get(k)??0,kept:0,roots:0,below:0,asParents:0},s.classes.get(k)?.kind==="whole"&&(j.whole=!0),p.set(k,j)),j},m=new Map,h=new Map,w=new Map,y=new Map,R=new Map,O=new Set;for(let k of a.pairs.values())k.rows.length>0&&O.add(k.rows[0]);let g=0,b=0,A=0,N=k=>r.measure.roomBytes?.(k)??0;for(let k=0;k<n.rows.length;k++){let j=n.objectOf[k];if(!n.alive(k)){let F=n.dead[k];if(n.out[k]||F===void 0||c(i.threshold[k])>o)continue;let S=`${j}
|
|
33
|
-
${F}`,I=y.get(S)??{objectApiName:j,rows:0,reason:F};I.rows++,y.set(S,I);continue}if(!f(k))continue;let M=n.rows[k],D=m.get(j)??[];D.push(M.id),m.set(j,D),b+=a.rowBytes[k];let E=O.has(k)?0:Ni(n,k);if(g+=E,A+=E*N(j),M.personAccount&&(j===de||j===oe)&&w.set(j,(w.get(j)??0)+1),!M.matched){let F=l(j);F.kept++;let S=u(k);if(S==="root"){F.roots++;let I=h.get(j)??new Set;I.add(q(M.id)),h.set(j,I)}else S==="below"?F.below++:S==="parent"&&F.asParents++}for(let F of s.linksOf.get(j)??[]){if(F.target==="excluded"||F.target==="whole"&&!n.wasReadWhole(F.parent))continue;let S=M.refs[F.field];if(!Fe(S,F))continue;let I=n.rowOf(F.parent,S);if(I!==void 0&&f(I))continue;let C=`${j}
|
|
34
|
-
${F.field}`,B=R.get(C)??{objectApiName:j,field:F.field,rows:0};B.rows++,R.set(C,B)}}for(let[k,j]of s.classes){if(j.kind!=="whole"||n.wasReadWhole(k))continue;let M=r.sourceRows.get(k)??0,D=l(k);D.kept=M,j.why!=="referenceData"&&(g+=M,b+=r.measure.wholeBytes(k,M)+M*N(k),A+=M*N(k))}let x=new Map;for(let k of a.pairs.values()){if(c(k.threshold)>o)continue;let j=x.get(k.objectApiName)??{objectApiName:k.objectApiName,inPlan:0,beyond:0};k.rows.length>0&&f(k.rows[0])?j.inPlan++:j.beyond++,b+=r.measure.bytes(k.objectApiName,{id:"",refs:{}}),x.set(k.objectApiName,j)}for(let[k,j]of n.cut){let M=0;for(let[F,S]of j)f(F)&&c(i.above[F])<=o&&(M+=S);if(M===0)continue;let D=k.indexOf("."),E=l(k.slice(0,D));E.childrenCut=[...E.childrenCut??[],{field:k.slice(D+1),rows:M}]}let v=[...p.values()].filter(k=>k.kept>0).sort((k,j)=>j.kept-k.kept||(k.objectApiName<j.objectApiName?-1:1)),P=[...s.classes].filter(([k,j])=>{let M=r.sourceRows.get(k)??0;return j.kind==="drawn"&&M>0&&(p.get(k)?.kept??0)===0}).map(([k])=>({objectApiName:k,sourceRows:r.sourceRows.get(k)??0})).sort((k,j)=>k.objectApiName<j.objectApiName?-1:1);return{rows:v.reduce((k,j)=>k+j.kept,0),storageBytes:b,automationBytes:A,written:g,objects:v,heavyRoots:Nl(n,e,t,d,o),dropped:[...y.values()].sort(rr(k=>k.reason)),leftEmpty:[...R.values()].sort(rr(k=>k.field)),noRecordDrawn:P,partialMasters:jl(s,p,r.sourceRows),ids:new Map([...m].map(([k,j])=>[k,j.sort(le)])),rootIds:h,personAccounts:w,byThePlatform:[...x.values()].sort((k,j)=>k.objectApiName<j.objectApiName?-1:1)}}function jl(n,e,t){let r=[];for(let[o,s]of n.linksOf){if(n.classes.get(o)?.kind!=="drawn")continue;let i=e.get(o)?.kept??0;for(let a of s){if(!a.masterDetail||a.target==="excluded"||a.parent===o)continue;let d=e.get(a.parent);if(!d||d.kept===0)continue;let c={objectApiName:a.parent,details:o,field:a.field};if(a.target==="whole"){let f=t.get(o)??0;i<f&&r.push({...c,kept:i,sourceRows:f})}else a.carries&&d.asParents>0&&r.push({...c,asParents:d.asParents})}}return r.sort(rr(o=>`${o.details}
|
|
35
|
-
${o.field}`))}function rr(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 Nl(n,e,t,r,o){let s=[...t].filter(a=>r[a].rank<=o).sort((a,d)=>a-d);if(s.length===0)return[];let i=[];for(let a of s){let d=new Set(t);d.delete(a);let c=n.thresholds(d),f=0,u=new Map;for(let m=0;m<n.rows.length;m++){if(!n.alive(m)||c.threshold[m]!==a)continue;f++;let h=c.via[m];h!==void 0&&u.set(h,(u.get(h)??0)+e.weighed.rowBytes[m])}let[p]=[...u].sort(([m,h],[w,y])=>y-h||(m<w?-1:m>w?1:0))[0]??[`${r[a].objectApiName}.Id`],l=p.indexOf(".");i.push({objectApiName:r[a].objectApiName,id:r[a].id,rows:f,relation:{objectApiName:p.slice(0,l),field:p.slice(l+1)}})}return i}var Pi=50;function or(n){return n===null?"none":typeof n=="boolean"?n?"true":"false":`=${n}`}function vi(n,e){return(n+.5)/Math.max(e,n+1)}function Ci(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 Ut=class{constructor(e){this.input=e;for(let t of e.strata){let r=or(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 Rn,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=or(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 Rn,read:[]},this.strata.set(r,o)),o.scanned++,o.heap.push({objectApiName:this.input.objectApiName,id:e,rank:jt(this.input.seed,e)}),o.heap.size>o.take&&o.heap.pop()}read(e,t){let r=this.strata.get(or(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(Ko).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:vi(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,vi(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-Pi;return{objectApiName:this.input.objectApiName,field:this.input.field,values:r.slice(0,Pi).map(s=>s.entry),...o>0?{more:o}:{}}}};var xi=class extends Error{constructor(t,r,o){super(r);this.code=t;this.heaviest=o;this.name="SampleRefusedError"}code;heaviest},sr=[mt,ve,ht,gt,"IsActive"];function Mi(n){return n===!0||n==="true"}function Vt(n){return typeof n=="string"&&n!==""?n:null}function El(n){let e=n.CreatedDate,t=typeof e=="string"?Date.parse(e):Number.NaN;return Number.isFinite(t)?t:void 0}function Li(n){let e=t=>{let r=n[t];return typeof r=="string"?q(r):""};return[e(mt),e(ve),e(gt)].join(`
|
|
36
|
-
`)}function _i(n){let e=t=>{let r=n[t];return typeof r=="string"?r:""};return[q(e(ve)),e(ht),q(e(gt))].join(`
|
|
37
|
-
`)}var ir=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===de||e===oe)&&t.push("IsPersonAccount"),e===Xe&&t.push(...sr),e===dn&&t.push("IsStandard"),t}rowOf(e,t,r=!1){let o={};for(let a of Vn(this.links,e))o[a]=Vt(t[a]);let s=t.RecordTypeId,i=El(t);return{id:String(t.Id),refs:o,...typeof s=="string"||s===null?{recordTypeId:Vt(s)}:{},...(e===de||e===oe)&&Mi(t.IsPersonAccount)?{personAccount:!0}:{},...e===dn&&Mi(t.IsStandard)?{matched:!0}:{},...r?{outsideFilter:!0}:{},...i!==void 0?{created:i}:{}}}async sampleRowsOf(e,t,r=[]){let o=[...t.map(f=>this.rowOf(e,f)),...r.map(f=>this.rowOf(e,f,!0))];if(e!==Xe||t.length===0)return o;let s=[...new Set(t.flatMap(f=>{let u=Vt(f[ve]);return u?[u]:[]}))],i=await this.reader.readStandardPrices(s,sr.slice(1)),a=new Set(i.map(f=>q(String(f.Id)))),d=new Map;for(let f of i)d.set(_i(f),String(f.Id));let c=await this.pricesWrittenFor(t);return o.map((f,u)=>{let p=t[u];if(p===void 0)return f;let l=[];a.has(q(f.id))||l.push({objectApiName:Xe,id:d.get(_i(p))??null});let m=c.get(f.id);return m!==void 0&&l.push({objectApiName:Xe,id:m}),l.length>0?{...f,also:l}:f})}async pricesWrittenFor(e){let t=new Map,r=this.priceCurrencyWrittenIn;if(!r)return t;let o=new Map;for(let s of e){let i=s[ht];if(typeof i!="string")continue;let a=r(i);a===void 0||a===i||o.set(a,[...o.get(a)??[],s])}for(let[s,i]of o){let a=f=>i.flatMap(u=>{let p=Vt(u[f]);return p?[p]:[]}),d=await this.reader.readPricesIn(s,a(ve),a(mt),sr),c=new Map(d.map(f=>[Li(f),String(f.Id)]));for(let f of i){let u=c.get(Li(f));u!==void 0&&t.set(String(f.Id),u)}}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 Tl(n,e){let{empty:t,told:r}=Ys(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 Fl(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 Pl(n,e,t){let r=[...n.window?[Fl(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 vl(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 wg(n){let{options:e,budget:t}=n,r=S=>n.averageBytes?.get(S),o=(S,I)=>{let C=r(S);return C!==void 0?I*C:ye(S,{rows:I})},s=new Map(n.objects.flatMap(S=>S.rows===void 0?[]:[[S.objectApiName,S.rows]])),i=Mt({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:(S,I)=>o(S,I)}),a=Oi({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:S=>n.fieldsOf(S),...n.filterOf?{filterOf:n.filterOf}:{}}),d=(S,I)=>n.fieldsOf(S)?.find(C=>C.name.toLowerCase()===I.toLowerCase()),c=new _t(n.source,{fieldsOf:S=>n.fieldsOf(S)?.map(I=>I.name),...n.filterOf?{filterOf:n.filterOf}:{},countsBy:(S,I)=>{let C=d(S,"Id")?.aggregatable,B=d(S,I)?.groupable;return C===!1||B===!1?!1:C===!0&&B===!0?!0:void 0},sorts:(S,I)=>d(S,I)?.sortable,...n.onProgress?{onProgress:n.onProgress}:{},...n.signal?{signal:n.signal}:{}}),f=[...i.classes].filter(([,S])=>S.kind==="drawn"&&S.rooted).map(([S])=>S).sort(),u=f.filter(S=>a.objects.get(S)?.notWindowed!==!0).map(S=>{let I=a.objects.get(S);return{objectApiName:S,carriers:Tl(i,S),...I?.window?{window:I.window}:{},...I?.where!==void 0?{where:I.where}:{},...I?.stratifiedBy!==void 0?{stratifiedBy:I.stratifiedBy}:{}}}),p=await c.countRoots(u),l=Nt(t.budget.bytes,t.budget.maxTotal),m=new Map;p.forEach((S,I)=>{let C=u[I].stratifiedBy;if(C===void 0||!S.strata)return;let B=Ci(S.strata.map(T=>T.rows),l,e.floor);m.set(S.objectApiName,new Ut({objectApiName:S.objectApiName,field:C,strata:S.strata.map((T,L)=>({value:T.value,roots:T.rows,take:B[L]})),draw:e.draw,seed:e.seed,floor:e.floor}))});let h=S=>m.get(S.objectApiName)?.reads()??Math.min(S.rows,l),w=p.reduce((S,I)=>S+Dt(I,e.draw,h(I)),0),y=n.sourceRequestsLeft;if(y!==void 0&&c.requests+w>Math.floor(Te*y)){let S=c.requests+w;throw new me(os,`Drawing the sample reads about ${S} 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. ${vl(e.draw,a)}`,void 0,void 0,void 0,{api:{kind:"requests",org:"source",estimate:S,remaining:y,drawing:{share:Te,draw:e.draw,...a.restricted?{restricted:!0}:{}}}})}let R=new Yo(l,e.floor),O=[],g=new Map,b=new Map;if(e.draw==="uniform")await c.drawUniform(u,(S,I,C)=>{g.set(S,(g.get(S)??0)+I.length);let B=m.get(S);if(B){for(let T of I)B.scanned(T,C??null);return}for(let T of I)R.offer(S,T,jt(e.seed,T))});else{let S=new Map(p.map(C=>[C.objectApiName,C.rows]));O=(await c.drawByDate(p.map((C,B)=>({...u[B],take:h(C)})),e.draw,(C,B,T)=>{let L=m.get(C);if(L){L.read(T??null,B);return}let _=b.get(C)??0;for(let $ of B)R.offer(C,$,bn(_,S.get(C)??0)),_++;b.set(C,_)})).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,l);B<C.rows&&(b.get(C.objectApiName)??0)>=B&&R.leftUnread(bn(B,C.rows))}}for(let S of m.values()){for(let I of S.ranked())R.offer(S.objectApiName,I.id,I.rank,I.stratum);R.leftUnread(S.firstUnread)}let A=R.drawn();if(a.restricted&&A.length===0)throw Pl(a,p,c.requests);let{maxTotal:N}=t.budget,x=N!==void 0&&N<Math.floor(t.budget.bytes/Ho)?"maxTotal":t.bytesLimit,v=new ir(c,i,s,n.priceCurrencyWrittenIn),P=await Fi({links:i,reader:v,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:(S,I)=>I.bytes??r(S)??ji.bytes(S,I),wholeBytes:o,...t.automationBytes?{roomBytes:t.automationBytes}:{}},bounds:{bytes:t.budget.bytes,bytesLimit:t.bytesLimit,...t.storageBytes!==void 0?{storageBytes:t.storageBytes}:{},...N!==void 0?{maxTotal:N}:{},...t.requests?{requests:t.requests}:{}},roomBytes:t.roomBytes,onStep:(S,I)=>n.onProgress?.({step:S,rows:I,requests:c.requests})}),k=[...new Set([...e.draw==="recent"?O:[],...v.cappedByIds])].sort(),j=e.draw==="oldest"?[...O].sort():[],M=new Map,D=new Set;for(let S of f){let I=a.objects.get(S);if(!I||I.window===void 0&&I.where===void 0&&!I.notWindowed)continue;let C=p.find(_=>_.objectApiName===S),B=_=>{let $=b.get(S)??0;return!m.has(S)&&$<Math.min(_.rows,l)?$:void 0},T=I.notWindowed||!C?0:e.draw==="uniform"?g.get(S)??0:C.exact&&C.timedOut!==!0?C.rows:B(C),L=C?.inTheSource?.exact===!0?C.inTheSource.rows:void 0;M.set(S,{...T!==void 0?{inTheDraw:T}:{},...L!==void 0?{inTheSource:L}:{}}),T===0&&(I.notWindowed||(L??C?.inTheSource?.rows??0)>0)&&D.add(S)}let E;if(a.restricted||a.stratified){let S=[];for(let I of m.values()){let C=P.kind==="sample"?P.rootIds.get(I.objectApiName):void 0,B=await n.labelsOf?.(I.objectApiName,I.field);S.push(I.report(T=>C?.has(q(T))===!0,B))}E={...Ai(a),...S.length>0?{strata:S}:{}}}let F;if(e.floor>0&&m.size>0){let S=0,I=0;for(let C of m.values())for(let B of C.reads())S++,I+=Math.min(B.roots,e.floor);S>0&&(F={roots:I,values:S})}return{links:i,cut:P,planRequests:c.requests,newestByIds:k,oldestByIds:j,...E?{roots:E}:{},rootsCounted:M,noRootInTheDraw:D,...F?{strataFloors:F}:{}}}function Di(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 yg(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 Cl=30*6e4,xl=16,Ml=["map_value","leave_empty","set_default","truncate","map_record_type","exclude_object","skip_rows","ignore"];function Og(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 Bi=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<=xl)break;this.tried.delete(s)}}before(e,t=Date.now()){let r=this.tried.get(e),o=a=>a===void 0||t-a>Cl||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 Ll(n){let e={flow:0,trigger:0,process:0,workflowRule:0,unread:[]};if(!("automation"in n))return{...e,unread:["automation"]};for(let t of ds(n.automation))e[t.kind]++;return e.unread=ls(n.automation).map(t=>t.part),e}function _l(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 cs(n.automation,r))t[o.kind]++;return t}function Dl(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 Ml.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 Bl(n){let e=n.objects.reduce((r,o)=>r+o.sourceRows,0)+n.noRecordDrawn.reduce((r,o)=>r+o.sourceRows,0),t=Di(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 $i=class{constructor(e,t){this.config=e;this.before=t}config;before;confirmed=[];fired;firedOnUpdate;deliverability;sampleFit;automationRead(e,t=[]){this.fired=Ll(e),this.firedOnUpdate=_l(e,t)}emailsRead(e){this.deliverability=e}confirm(e){this.confirmed.includes(e)||this.confirmed.push(e)}sampled(e){this.sampleFit=Bl(e)}fit(){return this.sampleFit?{...this.sampleFit}:void 0}context(e){let t=Dl(this.config,e);return{anonymized:this.config.anonymizePII,contactPoints:this.config.keepContactPoints===!0?"kept":"neutralized",...this.before,...this.fired?{firedOnInsert:{...this.fired,unread:[...this.fired.unread]}}:{},...this.firedOnUpdate?{firedOnUpdate:{...this.firedOnUpdate}}:{},...this.confirmed.length>0?{confirmed:[...this.confirmed]}:{},...t.length>0?{decisions:t}:{},...this.deliverability!==void 0?{deliverability:this.deliverability}:{}}}};var $l=V({...Co,journalId:W().min(1).max(200),ranFrom:Pe(["commandLine","editor"]),target:W().min(1).max(255).optional(),resumes:Ke().optional(),removes:Ke().optional()}),Wi=xo(n=>{let e=$l.safeParse(n);return e.success?e.data:void 0});function qi(n){return`${n.replace(/\.ndjson$/,"")}.lock`}function zi({version:n,token:e,...t}){return t}function Ig(n,e,t={}){let r=Wi.acquire(qi(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:zi(r.busy)}:r}function jg(n,e={}){let t=Wi.holder(qi(n),e);return t!==void 0?zi(t):void 0}function Ng(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 Eg(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 Wl="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ql="RHZ",zl=/[A-Za-z0-9]{3}RHZ[A-Za-z0-9]{12}/g,ar="000",Ui=62**8;function Gt(n,e){let t=n!==null&&/^[A-Za-z0-9]{3}$/.test(n)?n:ar,r="";for(let s=e;r.length===0||s>0;s=Math.floor(s/62))r=Wl[s%62]+r;let o=bt(`${t}${ql}${r.padStart(9,"0")}`);if(o===void 0)throw new Error(`No placeholder id for record ${e}`);return o}var Jt=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:Gt(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=$r(r);if(s)return this.personContactsOf(s,c=>e(t,Br(c),o));let i=Yr(r);if(i)return this.ownersOf(i,c=>e(t,Kr(c),o));let a=Qr(r);if(a)return this.teamOf(a,c=>e(t,Zr(a.objectApiName,a.fields,c)),()=>e(t,Hr));let d=Vr(r);return d?this.rolesOf(d,c=>e(t,Ur(c,d.fields),o)):this.namesAPlaceholder(r)?[]:e(t,r,o)}}async rolesOf(e,t){let r=e.opportunities.filter(d=>!this.rowOf(d)),o=r.length>0?await t(r):[],s=e.opportunities.flatMap(d=>{let c=this.rowOf(d),f=c?.objectApiName==="Opportunity"?c.fields[un]:void 0;return c&&typeof f=="string"&&f!==""?[{id:d,row:c,contact:f}]:[]});if(s.length===0)return o;let i=await this.prefixOf(zr),a=new Date().toISOString();return[...o,...s.map(({id:d,row:c,contact:f})=>{let u=Gt(i,Ui+this.platformTeam.size+this.platformRoles.size);return this.platformRoles.set(u.slice(0,15),c),Gr({...Object.fromEntries(e.fields.map(p=>[p,null])),Id:u,OpportunityId:d,[un]:f,...e.fields.includes("IsPrimary")?{IsPrimary:!0}:{}},a)})]}async ownersOf(e,t){let r=e.filter(i=>!this.rowOf(i)),o=r.length>0?await t(r):[],s=[];for(let i of e){let a=await this.ownerOf(i);a!==void 0&&s.push({Id:i,OwnerId:a})}return[...o,...s]}async teamOf(e,t,r){let{objectApiName:o,fields:s,opportunities:i}=e,a=i.filter(w=>!this.rowOf(w)),d=a.length>0?await t(a):[],c=i.filter(w=>this.rowOf(w)?.objectApiName==="Opportunity");if(c.length===0)return d;let f=qr[o],u=o===ln,p=u?(await r()).flatMap(w=>typeof w.Id=="string"&&(w.IsTotalValidated===!0||w.IsTotalValidated==="true")?[w.Id]:[]):[void 0],l=await this.prefixOf(u?ln:Wr),m=Jr[o]??{},h=[];for(let w of c){let y=await this.ownerOf(w);if(y!==void 0)for(let R of p){let O=Gt(l,Ui+this.platformTeam.size+this.platformRoles.size);this.platformTeam.set(O.slice(0,15),this.rowOf(w)),h.push({Id:O,OpportunityId:w,[f]:y,...R!==void 0?{SplitTypeId:R}:{},...Object.fromEntries(s.map(g=>[g,m[g]??null]))})}}return[...d,...h]}async ownerOf(e){let t=this.rowOf(e);if(t?.objectApiName!=="Opportunity")return;let r=t.fields.OwnerId;return typeof r=="string"&&r!==""?r:(this.writesAs??=this.runningUser?this.runningUser().catch(()=>{}):Promise.resolve(void 0),this.writesAs)}async personContactsOf(e,t){let r=e.filter(a=>!this.rowOf(a)),o=r.length>0?await t(r):[],s=e.flatMap(a=>this.rowOf(a)?.objectApiName===de?[a]:[]);if(s.length===0)return o;let i=await this.prefixOf(oe);return[...o,...s.map(a=>{let d=this.rowOf(a);if("Name"in d.fields)return{Id:a,[xe]:null};let c=Gt(i,d.seq);return this.personContacts.set(c.slice(0,15),d),{Id:a,[xe]:c}})]}namesAPlaceholder(e){for(let[t]of e.matchAll(zl))if(this.rowOf(t)||this.personContactOf(t)||this.platformTeam.has(t.slice(0,15))||this.platformRoles.has(t.slice(0,15)))return!0;return!1}prefixOf(e){let t=this.prefixes.get(e);return t||(t=this.keyPrefixOf(e).catch(()=>null),this.prefixes.set(e,t)),t}};function vg(n,e){return{queryRecords:e.guardQueries(n.queryRecords),describeFields:n.describeFields,isObjectCreatable:n.isObjectCreatable,describeObject:n.describeObject,recordTypePicklists:n.recordTypePicklists,batchStrategy:n.batchStrategy,anonymize:n.anonymize,requestsSent:n.requestsSent,insertRecords:e.insertRecords,updateRecords:e.updateRecords}}var Ji="UNKNOWN_ERROR",Hi="INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST",Ul=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"]),Vi=new Set(["FIELD_CUSTOM_VALIDATION_EXCEPTION","INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST","FIELD_FILTER_VALIDATION_EXCEPTION"]),Vl=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"]}]]),dr="FIELD_CUSTOM_VALIDATION_EXCEPTION";function Mg(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!==dr||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 Ht(n,e){let t=n.detail?.[e];return typeof t=="number"?t:0}function Gi(n){let e=n.detail?.fields;return Array.isArray(e)?e:[]}function Jl(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 Hl(n,e){if(Ul.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 Kl(n,e){let t=n.fields.RecordTypeId;return typeof t=="string"?e.get(t.slice(0,15)):void 0}function Yl(n,e,t,r){let{row:o}=n,s=e.fields[0],i=t===Cr?"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 Zl(n,e,t,r,o){let{row:s}=n,i=e.statusCode||Ji,a=Hl(s,e),d=n.onUpdate?void 0:Gl(s.objectApiName,e,o),c=l=>{let m=l===void 0?void 0:s.fields[l];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}:{},...Vi.has(i)&&l!==void 0&&!n.onUpdate?{writtenWithoutTheField:!0}:{}}};if(n.onUpdate){let l=e.fields[0];return[{id:Ze("rehearsal_update_refusal",s.objectApiName,l,void 0,i),kind:"rehearsal_update_refusal",severity:"warning",source:"rehearsal",objectApiName:s.objectApiName,...l!==void 0?{field:l}:{},value:i,rows:1,detail:c(l),decisions:["exclude_object","ignore"]}]}if(n.linked)return[Yl(n,e,i,c)];let f=Vl.get(i);if(f&&e.fields.length>0)return(f.kind==="required_field_missing"?e.fields:e.fields.slice(0,1)).map(m=>{let h=s.fields[m],w=f.kind==="picklist_value_refused",y=w?Kl(s,t):void 0,R=w&&typeof h=="string"?h:void 0,O=R!==void 0?Jl(r.get(s.objectApiName)?.get(m),R,y):void 0;return{id:Ze(f.kind,s.objectApiName,m,y,R),kind:f.kind,severity:f.severity,source:"rehearsal",objectApiName:s.objectApiName,field:m,...y!==void 0?{recordType:y}:{},...R!==void 0?{value:R}:{},rows:1,detail:{...c(m),...O!==void 0?{reason:O}:{}},decisions:[...f.decisions],...f.severity==="warning"?{defaultDecision:"leave_empty"}:{}}});let u=e.fields[0],p=u!==void 0&&Vi.has(i);return[{id:Ze("rehearsal_refusal",s.objectApiName,u,void 0,i),kind:"rehearsal_refusal",severity:p?"warning":"blocking",source:"rehearsal",objectApiName:s.objectApiName,...u!==void 0?{field:u}:{},value:i,rows:1,detail:c(u),decisions:u!==void 0?["leave_empty","exclude_object","ignore"]:["exclude_object","ignore"],...p?{defaultDecision:"leave_empty"}:{}}]}function Ki(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:Ji,message:"",fields:[]}],a=sn(...i.map(d=>Zl(s,d,e,t,r)));for(let d of a){let c=o.get(d.id);if(!c){o.set(d.id,d);continue}let f=Math.max(Ht(c,"valueLength"),Ht(d,"valueLength"));o.set(d.id,{...c,rows:c.rows+1,detail:{...d.detail,...c.detail,rowsOfTheRun:Ht(c,"rowsOfTheRun")+Ht(d,"rowsOfTheRun"),fields:[...new Set([...Gi(c),...Gi(d)])],...f>0?{valueLength:f}:{}}})}}return sn([...o.values()])}function Ql(n){return n!=null&&n!==""}function Xl(n){let e=n.fields.RecordTypeId,t=Object.keys(n.fields).filter(r=>r!=="attributes"&&Ql(n.fields[r])).sort();return[n.objectApiName,typeof e=="string"?e:"",t.join(",")].join("|")}function Yi(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=Xl(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 eu(n){let e=n.fields.Status;return[n.objectApiName,Object.keys(n.fields).sort().join(","),typeof e=="string"?e:""].join("|")}function Zi(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=eu(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 Qi(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 u of Object.values(a.fields)){let p=e(u);p&&p.seq!==a.seq&&d.add(p.seq);let l=p?void 0:t(u);l&&l.seq!==a.seq&&r.has(l.seq)&&(d.add(l.seq),c.add(l.seq))}let f=[...d].sort((u,p)=>u-p);o.set(a.seq,f),c.size>0&&i.set(a.seq,[...c].sort((u,p)=>u-p)),s.set(a.seq,f.reduce((u,p)=>Math.max(u,(s.get(p)??0)+1),0))}return{bySeq:r,parents:o,levels:s,...i.size>0?{personContactsNamed:i}:{}}}function Xi(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 cr(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 ur=5,fr=25,tu=200,nu=10,ru="PROCESSING_HALTED",ou="SandForge_Rehearsal_Rollback__c";function pr(n,e=0){return Math.max(0,fr-n-e-1)}function Xt(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 ea(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([...Xt(n.collections.flatMap(a=>a.seqs),e),...t.flatMap(a=>a.contacts??[])]),i=[];for(let a of s){let d=o.get(a),c=r.get(a),f=d??(c===void 0?void 0:"id"in c?-1:o.get(c.seq));f!==void 0&&i.push({account:a,after:f})}return i.sort((a,d)=>a.after-d.after||a.account-d.account)}function su(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>=tu||d&&i.size>=nu)&&(s={level:n,seqs:[]},i=new Set,o.push(s)),s.seqs.push(a.seq),i.add(a.objectApiName)}return o}function lr(n,e){return[...n.keys()].sort((t,r)=>t-r).flatMap(t=>su(t,n.get(t)??[],e))}function en(n,e){let t=f=>e.levels.get(f)??0,r=[...n].sort((f,u)=>t(u.seq)-t(f.seq)||f.seq-u.seq),o=[],s=[],i=new Set,a=new Map,d=(f,u)=>{let p=new Map([...f].map(([l,m])=>[l,new Set(m)]));for(let l of u){let m=p.get(t(l))??new Set;m.add(l),p.set(t(l),m)}return p},c=f=>{let u=lr(f,e.bySeq).length,p=Xt([...f.values()].flatMap(l=>[...l]),e).length;return u<=ur&&u+p<fr};for(let f of r){if(i.has(f.seq))continue;let u=[f.seq,...Ge(f.seq,e)],p=d(new Map,u);if(!c(p)){s.push(f.seq);continue}let l=d(a,u);c(l)?a=l:(o.push({collections:lr(a,e.bySeq)}),a=p);for(let m of u)i.add(m)}return a.size>0&&o.push({collections:lr(a,e.bySeq)}),{calls:o,beyond:s.sort((f,u)=>f-u)}}function Zt(n){return`rows${n}`}function mr(n){return`update${n}`}var ta="rollback";function Qt(n){return`contact${n}`}function iu(n,e,t){let r=o=>t.filter(s=>s.after===o).map(s=>Qt(s.account));return[...r(-1),...n.collections.flatMap((o,s)=>[Zt(s),...r(s)]),...Array.from({length:e},(o,s)=>mr(s)),ta]}function na(n,e,t,r,o,s=[],i=new Map,a={of:()=>{},reads:[]}){let{reads:d}=a;if(s.length>pr(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 ${fr} subrequests`);let c=new Map;n.collections.forEach((g,b)=>g.seqs.forEach((A,N)=>c.set(A,`@{${Zt(b)}[${N}].id}`)));let f=g=>{let b=c.get(g.seq);if(b!==void 0)return b;let A=i.get(g.seq);if(A!==void 0)return"id"in A?A.id:c.get(A.seq)},u=new Set(d.map(g=>g.account)),p=g=>{let b=t(g);if(b){let N=f(b);return N===void 0?void 0:{sent:N}}let A=a.of(g);return A?u.has(A.seq)?{sent:`@{${Qt(A.seq)}.${xe}}`}:void 0:{sent:g}},l=g=>g.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=(g,b)=>({method:"POST",url:`${r}/composite/sobjects`,referenceId:Zt(b),body:{allOrNone:!1,records:l(g).map(A=>{let N={attributes:{type:A.objectApiName}};for(let[x,v]of Object.entries(A.fields)){if(x==="attributes"||x==="Id")continue;let P=p(v);if(P===void 0)throw new Error(`${A.objectApiName} row ${A.seq} names a record the run creates that its call does not hold`);N[x]=P.sent}return N})},httpHeaders:{...o}}),h=({account:g})=>{let b=e.bySeq.get(g),A=b?f(b):void 0;if(A===void 0)throw new Error("A read of a person account's contact names an account its call does not hold");return{method:"GET",url:`${r}/sobjects/${de}/${A}?fields=${xe}`,referenceId:Qt(g)}},w=g=>d.filter(b=>b.after===g).map(h),y=[...w(-1),...n.collections.flatMap((g,b)=>[m(g,b),...w(b)])];s.forEach((g,b)=>{let A=c.get(g.rowSeq);if(A===void 0)throw new Error(`An update of ${g.objectApiName} names a record its call does not create`);let N={};for(let[x,v]of Object.entries(g.fields)){if(x==="attributes"||x==="Id")continue;let P=p(v);if(P===void 0)throw new Error(`An update of ${g.objectApiName} names a record the run creates that its call does not hold`);N[x]=P.sent}y.push({method:"PATCH",url:`${r}/sobjects/${g.objectApiName}/${A}`,referenceId:mr(b),body:N,httpHeaders:{...o}})});let R=n.collections[0]?.seqs[0],O=R===void 0?void 0:e.bySeq.get(R);if(!O)throw new Error("A rehearsal call holds no row");return y.push({method:"PATCH",url:`${r}/sobjects/${O.objectApiName}/${au(O.placeholderId)}`,referenceId:ta,body:{[ou]:!0}}),{allOrNone:!0,collateSubrequests:!1,compositeRequest:y}}function au(n){return bt(`${n.slice(0,3)}000000000000`)??"000000000000000AAA"}var du=V({body:Ie(),httpStatusCode:te(),referenceId:W().optional()}).loose(),cu=V({compositeResponse:Z(du)}).loose(),Yt=Z(V({errorCode:W().optional(),statusCode:W().optional()}).loose()),lu=Z(V({success:Ke()}).loose());function Kt(n){let e=Yt.safeParse(n.body);return n.httpStatusCode>=400&&e.success&&e.data.length>0&&e.data.every(t=>(t.errorCode??t.statusCode)===ru)}function ra(n,e,t=0,r=()=>{},o=[]){let s=cu.safeParse(n);if(!s.success)throw new Error("The target answered the rehearsal with no composite answer");let i=s.data.compositeResponse,a=iu(e,t,o),d=a.length,c=i[d-1];if(i.length!==d||!c)throw new Error(`The target answered ${i.length} subrequests of the ${d} the rehearsal sent`);let f=i.findIndex((m,h)=>m.referenceId!==void 0&&m.referenceId!==a[h]);if(f!==-1)throw new Error(`The target ran the rehearsal's subrequests out of the order sent (${String(i[f]?.referenceId)} in place of ${a[f]}): no verdict can be read from it`);let u=m=>i[a.indexOf(m)];for(let{account:m}of o){let h=u(Qt(m));if(h.httpStatusCode<400||Kt(h))continue;let w=Yt.safeParse(h.body),y=w.success?w.data[0]?.errorCode??w.data[0]?.statusCode:"";throw new Error(`The target refused to read back the contact the platform wrote with a person account (status ${h.httpStatusCode}${y?`, ${y}`:""}): no verdict can be read past it`)}let p=e.collections.map((m,h)=>{let w=u(Zt(h));if(Kt(w))return{kind:"halted"};let y=lu.safeParse(w.body);if(w.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((O,g)=>Rt(O,r(m.seqs[g])??""))}}let R=Yt.safeParse(w.body);if(w.httpStatusCode>=400&&R.success&&R.data.length>0)return{kind:"refused",errors:R.data.map(mn)};throw new Error(`The target answered a request of the rehearsal with status ${w.httpStatusCode}`)}),l=Array.from({length:t},(m,h)=>{let w=u(mr(h));if(Kt(w))return{kind:"halted"};if(w.httpStatusCode<400)return{kind:"saved"};let y=Yt.safeParse(w.body);if(y.success&&y.data.length>0)return{kind:"refused",errors:y.data.map(mn)};throw new Error(`The target answered an update of the rehearsal with status ${w.httpStatusCode}`)});if(c.httpStatusCode<400)return{kind:"not_rolled_back",ids:p.flatMap(m=>m.kind==="rows"?m.outcomes.filter(h=>h.success).map(h=>h.id):[])};if(Kt(c)&&gr(p)===-1&&!l.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:l}}function gr(n){return n.findIndex(e=>e.kind==="refused"||e.kind==="rows"&&e.outcomes.some(t=>!t.success))}function oa(n,e,t=()=>{}){let r=new Map,o=gr(e);return n.collections.forEach((s,i)=>{if(o!==-1&&i>o)return;let a=e[i];s.seqs.forEach((d,c)=>{if(a.kind==="refused"){r.set(d,{passed:!1,errors:a.errors});return}let f=a.kind==="rows"?a.outcomes[c]:void 0;if(!f||f.success){r.set(d,{passed:!0});return}let u=yo(f,t(d));r.set(d,{passed:!1,errors:f.errorDetails??[],...u.kind==="linked"?{linkedTo:u.id}:{}})})}),r}function sa(n,e){let t=new Map;if(gr(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 uu(n,e){let t=e.targetRecordTypes;if(!t)return n;let r=new Set(n.flatMap(s=>s.recordType!==void 0&&lo(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?uo(i):void 0)}return n.map(s=>fo(s,o.get(s.objectApiName)))}async function fu(n,e){let t=[...new Set(n.filter(({errors:r})=>r.some(o=>o.statusCode===dr)).map(({row:r})=>r.objectApiName))];if(t.length===0||!e.validationRules)return[];try{return await e.validationRules(t)}catch{return[]}}async function pu(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!==Hi||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 hr=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},tn=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 mu(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 ia(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 gu(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 hu(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 wr(n,e,t){let r=new Set(n.collections.flatMap(i=>i.seqs)),o=new Set(Xt(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>pr(n.collections.length,o.size+a.length))break;for(let d of a)o.add(d);s.push(i)}return s}function aa(n,e){let t=o=>{let s=cr(o.flatMap(d=>d.needs.flatMap(c=>{let f=e.bySeq.get(c);return f?[f]:[]})),e),i=en(s,e),[a]=i.calls;return i.calls.length===1&&i.beyond.length===0&&a&&wr(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 wu(n,e,t){let r=[...e],o=i=>{let a=new Set(wr(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}=aa(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 Hg(n){let e=new Jt(n.keyPrefixOf,n.runningUser);await n.prepare(e);let t=e.rows,r=E=>e.rowOf(E),o=E=>e.personContactOf(E),s=Qi(t,r,o),i=Yi(t),a=Zi(e.updated.flatMap(E=>{let F=hu(E,r,o);return F?[F]:[]})),d=a.updates,c=cr([...i.rows,...d.flatMap(E=>E.needs.flatMap(F=>{let S=s.bySeq.get(F);return S?[S]:[]}))],s),f=E=>i.standsFor.get(E)??1,u=E=>{let F=s.bySeq.get(E)?.placeholderId.slice(0,3);return F===void 0||F===ar?null:F},p=new Map,l=new Map,m=new Map,h=new Map,w=new Map,y=s,R=en(c,s);for(let E of R.beyond)l.set(E,"beyond_a_call");let O=wu(R.calls,d,s),g=O*ur,b=0;if(O>0){if(n.signal?.aborted)throw new tn(0);n.onProgress?.({phase:"confirming",calls:O}),await n.confirm({rows:t.length,sampled:c.length,updates:ia(d).map(({objectApiName:E,count:F})=>({objectApiName:E,updates:F})),calls:O,maxCalls:g,objects:ia(c).map(({objectApiName:E,count:F})=>({objectApiName:E,rows:F}))})}let A=E=>{let F=p.get(E);return F?.passed===!1&&F.linkedTo===void 0},N=E=>[E,...Ge(E,y)].some(A),x=E=>{if(w.has(E.rowSeq))return"record_linked";for(let F of E.needs){if(N(F))return"parent_refused";let S=l.get(F);if(S)return S}};for(;;){if(n.signal?.aborted)throw new tn(b);let E=c.filter(_=>p.has(_.seq)||l.has(_.seq)?!1:Ge(_.seq,y).some(A)?(l.set(_.seq,"parent_refused"),!1):!0),F=d.filter(_=>{if(m.has(_.seq)||h.has(_.seq))return!1;let $=x(_);return $?(h.set(_.seq,$),!1):!0});if(E.length===0&&F.length===0)break;if(b>=g){for(let _ of E)l.set(_.seq,"call_budget");for(let _ of F)h.set(_.seq,"call_budget");break}let S;if(E.length>0){let _=en(E,y);for(let $ of _.beyond)l.set($,"beyond_a_call");S=_.calls[0]}else{let _=aa(F,y);for(let $ of _.beyond)h.set($.seq,"beyond_a_call");S=_.call}if(!S)continue;let I=wr(S,F.filter(_=>!h.has(_.seq)),y);b++,n.onProgress?.({phase:"rehearsing",call:b,calls:Math.max(O,b)});let C=ea(S,y,I,w),B=na(S,s,r,n.apiPath,n.writeHeaders,I,w,{of:o,reads:C}),T=ra(await n.composite(B),S,I.length,_=>s.bySeq.get(_)?.objectApiName,C);if(T.kind==="not_rolled_back")throw new hr(T.ids,mu(T.ids,t));let L=new Map;for(let[_,$]of oa(S,T.collections,u))p.set(_,$),!$.passed&&$.linkedTo!==void 0&&L.set(_,gu($.linkedTo,S,T.collections));for(let[_,$]of sa(I,T))m.set(_,$);if(L.size>0){for(let[_,$]of L)w.set(_,$);y=Xi(s,w),d=d.map(_=>({..._,needs:_.needs.flatMap($=>{let U=w.get($);return U===void 0?[$]:"seq"in U?[U.seq]:[]})}))}}let v=[],P=0,k=0;for(let E of c){let F=p.get(E.seq);if(!F)continue;if(F.passed){P++;continue}let S=F.linkedTo!==void 0;S&&k++,v.push({row:E,errors:F.errors,standsFor:f(E.seq),...S?{linked:!0}:{}})}let j=0,M=0;for(let E of d){let F=m.get(E.seq),S=s.bySeq.get(E.rowSeq);if(!F||!S)continue;let I=a.standsFor.get(E.seq)??1;if(M+=I,F.passed){j++;continue}v.push({row:{...S,fields:{...S.fields,...E.fields}},errors:F.errors,standsFor:I,onUpdate:!0})}let D=new Map;for(let[E,F]of l){let I=`${s.bySeq.get(E)?.objectApiName??""}|${F}`;D.set(I,(D.get(I)??0)+1)}return{gaps:await uu(Ki(v,n.recordTypeNames,await pu(v,n),await fu(v,n)),n),rows:t.length,sampled:c.length,judged:p.size,passed:P,linked:k,notJudged:l.size,notJudgedWhy:[...D].map(([E,F])=>{let[S,I]=E.split("|");return{objectApiName:S,rows:F,reason:I}}),updates:e.updates,updatesJudged:m.size,updatesPassed:j,updatesNotRehearsed:e.updates-M,calls:b,plannedCalls:O}}var yu="QuoteLineItem",yr="Quote",nn="Opportunity",br="OpportunityLineItem",Or="SyncedQuoteId",Ar="QuoteId",kr="OpportunityLineItemId",Sr=new Set(["Id",Ar,kr]);function ct(n){return n.slice(0,15)}function Rr(n,e){let t=n[e];return typeof t=="string"&&t!==""?ct(t):void 0}function Zg(n,e){return!n.has(nn)||!n.has(yr)||!n.has(br)?[]:e.get(nn)?.some(r=>r.name===Or)!==!0?[]:[{sourceObject:yr,targetObject:br,relationshipName:`${yr}Before${br}`,type:"lookup",required:!0}]}function bu(n,e,t){let r=[...Sr,...t.filter(s=>!Sr.has(s))].map(J).join(", "),o=s=>s.map(i=>`'${Ce(i)}'`).join(", ");return`SELECT ${r} FROM ${yu} WHERE ${Ar} IN (${o(n)}) AND ${kr} IN (${o(e)})`}var Ru=200;function Su(n,e){let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t}async function Qg(n,e,t){let r=[],o=[...new Set(e.map(s=>s.product))];for(let s of Su(o,Ru)){let i=new Set(s.map(ct)),a=[...new Set(e.filter(d=>i.has(ct(d.product))).map(d=>d.quote))];r.push(...await n(bu(a,s,t)))}return r}function Xg(n,e,t){let r=new Map;for(let s of e){let i=Rr(s,"Id"),a=Rr(s,Ar),d=Rr(s,kr);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(`${ct(s.quote)}:${ct(s.product)}`)?.shift();i&&o.set(s.index,i)}return o}var da=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;function Ou(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(da.test(n)&&da.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 eh(n,e,t,r=new Set){let o={};for(let[s,i]of Object.entries(n))Sr.has(s)||r.has(s)||!t(s)||Ou(i,e[s])||(o[s]=i??null);return o}function th(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 Au=2e3,ku=3,Iu=20,lt=20;function uh(n,e){let t=mo(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 po(n.limitInfo,e),{totalSize:o.totalSize,records:o.records}},serverTime:async()=>(await n.soap.getServerTimestamp()).timestamp}}function ca(n,e,t){return`${n}:${e.slice(0,15)}:${t}`}function la(n,e){return`${n}.${e}`}var ju=[{modified:"LastModifiedDate",by:"LastModifiedById",created:!0},{modified:"LastModifiedDate",by:"LastModifiedById"},{modified:"SystemModstamp",created:!0},{modified:"SystemModstamp"},{}],ue="CreatedById",He="CreatedDate",Nu=V({sobjects:Z(V({name:W(),keyPrefix:W().nullish()}).loose())}).loose(),Eu=n=>new Promise(e=>setTimeout(e,n));function G(n){return n.slice(0,15)}function ua(n){return n.slice(0,3)}function fa(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function Tu(n,e,t){let r=n[ue],o=ut(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 ut(n){return typeof n=="string"?Date.parse(n):Number.NaN}function Je(n){return typeof n.Id=="string"?n.Id:void 0}function Ir(n){return Array.isArray(n)?`[${n.map(Ir).join(",")}]`:typeof n=="object"&&n!==null?`{${Object.entries(n).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${Ir(r)}`).join(",")}}`:JSON.stringify(n)}var pa=class{constructor(e){this.deps=e}deps;describes=new Map;async verify(e,t={}){let r=t.now??(()=>new Date),o=t.sleep??Eu,s=t.intervalMs??Au,i=Math.max(1,t.maxAttempts??ku),a=t.linkSample??Iu,d=await this.runEnd(e),c=this.deps.source,f="unavailable"in c?c.unavailable:void 0,u=new Map;if(!("unavailable"in c))for(let b of e.records)u.set(b.objectApiName,await this.linkPlan(c,e,b,a));let p=null,l=null,m=[],h=0,w=this.explaining(e,d),y=w.window?await this.runUser(e):void 0,R=await this.writtenByThePlatformAlone(e,w);for(let b=1;b<=i;b++){h=b,await o(s),m=[];for(let N of e.records)m.push(await this.read(e,N,d,u.get(N.objectApiName),w,y));for(let N of R)m.push(await this.readWrittenByThePlatform(N,w,y));let A=Ir(m);if(p!==null&&A===p){l=m;break}p=A}let O=(l??m).map(Pu),g=e.roots?Fu(e,e.roots,l??m):void 0;return{verdict:vu(l!==null,O,f),verifiedAt:r().toISOString(),attempts:h,objects:O,...f!==void 0?{linksUnchecked:f}:{},...g?{roots:g}:{}}}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=ut(await r.call(this.deps.target));Number.isFinite(s)&&(t=s-(o+Date.now())/2)}catch{}}return e.runRecordedAt.getTime()+t+St}explaining(e,t){let r=new Set;for(let{objectApiName:c,field:f,recordIds:u}of e.leftEmptyByFilter??[])for(let p of u)r.add(ca(c,p,f));let o=new Set(Object.entries(e.leftEmptyByTheRun??{}).flatMap(([c,f])=>f.map(u=>la(c,u)))),s=[...new Set((e.withTheirRecord??[]).flatMap(c=>{let f=e.remapTable[c];return f===void 0?[]:[f]}))],i=e.runStartedAt?.getTime()??Number.NaN,a=Number.isFinite(i)&&Number.isFinite(t),d={from:i-St,to:t+St};return{emptiedByFilter:r,emptiedByTheRun:o,withTheirRecord:s,createdByRun:new Set(Object.values(e.remapTable).map(G)),...a?{window:d,counted:e.runEndedAt?{from:d.from,to:t}:d}:{}}}async setByAutomation(e,t,r){let o=r.window,s=e.filter(({link:f,createdBy:u})=>o!==void 0&&typeof u=="string"&&f.found!==null&&!r.createdByRun.has(G(f.found)));if(!o||s.length===0)return{explained:[],broken:e.map(({link:f})=>f)};let i=new Map,a=new Map;for(let{link:f}of s){let u=await this.objectOfId(t.referenceTo?.get(f.field)??[],f.found);u!==void 0&&a.set(u,[...a.get(u)??[],f.found])}for(let[f,u]of a)try{let p=await pe(this.deps.target,f,[ue,He],[...new Set(u)]);for(let l of p){let m=Je(l);m&&i.set(G(m),l)}}catch{}let d=[],c=[];for(let f of e){let{link:u,createdBy:p}=f,l=u.found===null?void 0:i.get(G(u.found)),m=ut(l?.[He]);s.includes(f)&&typeof p=="string"&&typeof l?.[ue]=="string"&&G(l[ue])===G(p)&&m>=o.from&&m<=o.to?d.push({...u,cause:"automation"}):c.push(u)}return{explained:d,broken:c}}async objectOfId(e,t){if(e.length===1)return e[0];for(let r of e)try{if((await this.describe(this.deps.target,"target",r)).keyPrefix===t.slice(0,3))return r}catch{}}describe(e,t,r){let o=`${t}:${r}`,s=this.describes.get(o);return s||(s=e.describe(r),this.describes.set(o,s)),s.then(i=>yt.parse(i))}async linkPlan(e,t,r,o){let s=r.objectApiName,i={fields:[],expected:new Map,sample:[]};try{let[a,d]=await Promise.all([this.describe(this.deps.target,"target",s),this.describe(e,"source",s)]),c=new Set(a.fields.filter(g=>g.type==="reference"&&(g.createable===!0||g.updateable===!0)).map(g=>g.name)),f=new Set(t.fieldExclusions?.[s]??[]),u=t.fieldMappings?.[s]??{},p=d.fields.filter(g=>g.type==="reference"&&!f.has(g.name)).map(g=>({from:g.name,to:u[g.name]??g.name})).filter(({to:g})=>c.has(g)&&!f.has(g));if(p.length===0)return i;let l=new Map,m=new Map;for(let[g,b]of Object.entries(t.remapTable))l.set(G(b),g),m.set(G(g),b);let h=r.ids.slice(0,o).filter(g=>l.has(G(g)));if(h.length===0)return i;let w=await pe(e,s,p.map(g=>g.from),h.map(g=>l.get(G(g)))),y=new Map;for(let g of w){let b=Je(g),A=b?m.get(G(b)):void 0;if(!A)continue;let N=[];for(let{from:x,to:v}of p){let P=g[x],k=typeof P=="string"?m.get(G(P)):void 0;k&&N.push({field:v,expected:k})}N.length>0&&y.set(G(A),N)}let R=[...new Set([...y.values()].flat().map(g=>g.field))],O=new Map(a.fields.filter(g=>R.includes(g.name)).map(g=>[g.name,g.referenceTo??[]]));return{fields:R,expected:y,sample:R.length>0?h:[],referenceTo:O,createdBy:a.fields.some(g=>g.name===ue)}}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,[ue],[r]),s=o?.[ue];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 ${ue} = '${t}' AND ${He} >= ${fa(r.from)} AND ${He} <= ${fa(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(ua)),o=[...new Set(t.withTheirRecord.map(ua))].filter(i=>!r.has(i)),s=this.deps.target.describeGlobal;if(o.length===0||!s)return[];try{let{sobjects:i}=Nu.parse(await s.call(this.deps.target));return o.flatMap(a=>{let d=i.find(c=>c.keyPrefix===a);return d?[{objectApiName:d.name,prefix:a}]:[]})}catch{return[]}}async readWrittenByThePlatform(e,t,r){let o={objectApiName:e.objectApiName,expected:0,present:0,deletedIds:[],notVisibleIds:[],changed:[],linksChecked:0,broken:[],explained:[],withTheirRecord:await this.withTheirRecordThere({objectApiName:e.objectApiName,ids:[]},t,e.prefix)};if(r!==void 0&&t.counted){let s=await this.countInTheWindow(e.objectApiName,r,t.counted);s!==void 0&&(o.createdInTheWindow=s)}return o}async read(e,t,r,o,s,i){let a=t.objectApiName,d={objectApiName:a,expected:t.ids.length,present:0,deletedIds:[],notVisibleIds:[],changed:[],linksChecked:0,broken:[],explained:[],withTheirRecord:0,...o?.unchecked!==void 0?{linksUnchecked:o.unchecked}:{}},c,f={},u,p=a===cn.objectApiName?cn:void 0;for(let y of ju)try{let R=[y.modified,y.by,...y.created?[He,ue,...p?[p.field]:[]]:[]].filter(O=>!!O);c=await pe(this.deps.target,a,R,t.ids),f=y;break}catch(R){u??=H(R)}if(!c)return{...d,error:u??"The org gave no reason."};let l=new Map;for(let y of c){let R=Je(y);R&&l.set(G(R),y)}let m=t.ids.filter(y=>!l.has(G(y))),h=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 O=y.found.get(G(R));O==="deleted"?d.deletedIds.push(R):O==="there"?h++:d.notVisibleIds.push(R)}}if(d.present=l.size+h,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 O=h,g=0;for(let b of l.values())Tu(b,i,y)!==!1&&(O++,p&&b[p.field]===p.value&&g++);if(d.ofTheRunInTheWindow=O,p){let b=await this.countInTheWindow(a,i,y,p);b!==void 0&&b>g&&(d.postedWithTheirRecord=b-g)}}}let w=new Map(Object.entries(e.removalStamps??{}).map(([y,R])=>[G(y),ut(R)]));if(f.modified&&Number.isFinite(r))for(let y of t.ids){let R=l.get(G(y));if(!R)continue;let O=ut(R[f.modified]);if(!Number.isFinite(O)||O<=r||O<=(w.get(G(y))??Number.NaN))continue;let g=f.by?R[f.by]:void 0;d.changed.push({recordId:y,modifiedAt:String(R[f.modified]),...typeof g=="string"?{modifiedById:g}:{}})}if(o&&o.sample.length>0)try{let y=await pe(this.deps.target,a,o.createdBy?[...o.fields,ue]:o.fields,o.sample),R=new Set(e.writtenWithout?.[a]??[]),O=[];for(let g of y){let b=Je(g);if(b)for(let{field:A,expected:N}of o.expected.get(G(b))??[]){let x=g[A],v=typeof x=="string"&&x!==""?x:null;if(v!==null&&G(v)===G(N)){d.linksChecked++;continue}if(v===null&&s.emptiedByFilter.has(ca(a,b,A))){d.linksChecked++,d.explained.push({recordId:b,field:A,expected:N,found:v,cause:"lookup-filter"});continue}if(v===null&&s.emptiedByTheRun.has(la(a,A))){d.linksChecked++,d.explained.push({recordId:b,field:A,expected:N,found:v,cause:"run"});continue}if(v===null&&R.has(A))continue;d.linksChecked++;let P={recordId:b,field:A,expected:N,found:v};v===null?d.broken.push(P):O.push({link:P,createdBy:g[ue]})}}if(O.length>0){let{explained:g,broken:b}=await this.setByAutomation(O,o,s);d.explained.push(...g),d.broken.push(...b)}}catch(y){d.linksUnchecked=H(y)}return d}async recycleBin(e,t){let r=new Map;try{let o=J(e);for(let s of X(t)){let i=await this.deps.target.queryAll(`SELECT Id, IsDeleted FROM ${o} WHERE Id IN (${s})`);for(let a of i.records){if(typeof a!="object"||a===null)continue;let d=a,c=Je(d);if(!c)continue;let f=d.IsDeleted===!0||d.IsDeleted==="true";r.set(G(c),f?"deleted":"there")}}}catch(o){return{unread:H(o)}}return{found:r}}};function Fu(n,e,t){let r=t.find(d=>d.objectApiName===e.objectApiName);if(r?.error!==void 0)return;let o=new Set(n.records.filter(d=>d.objectApiName===e.objectApiName).flatMap(d=>d.ids.map(G))),s=new Set([...r?.deletedIds??[],...r?.notVisibleIds??[]].map(G)),i=0,a=0;for(let d of e.sourceIds){let c=n.remapTable[d];if(c===void 0)continue;i++;let f=G(c);(!o.has(f)||r!==void 0&&!s.has(f))&&a++}return{inTarget:a,of:i}}function Pu(n){let e=n.explained.filter(s=>s.cause==="run").length,t=n.postedWithTheirRecord??0,r=n.withTheirRecord+t,o=(n.ofTheRunInTheWindow??n.present)+r;return{objectApiName:n.objectApiName,expected:n.expected,present:n.present,deleted:n.deletedIds.length,notVisible:n.notVisibleIds.length,changed:n.changed.length,changedRecords:n.changed.slice(0,lt),deletedIds:n.deletedIds.slice(0,lt),notVisibleIds:n.notVisibleIds.slice(0,lt),linksChecked:n.linksChecked,linksBroken:n.broken.length,brokenLinks:n.broken.slice(0,lt),...n.explained.length>0?{linksLeftEmptyByFilter:n.explained.filter(s=>s.cause==="lookup-filter").length,linksSetByAutomation:n.explained.filter(s=>s.cause==="automation").length,...e>0?{linksLeftEmptyByTheRun:e}:{},explainedLinks:n.explained.slice(0,lt)}:{},...n.error!==void 0?{error:n.error}:{},...n.linksUnchecked!==void 0?{linksUnchecked:n.linksUnchecked}:{},...n.recycleBinUnread!==void 0?{recycleBinUnread:n.recycleBinUnread}:{},...r>0?{withTheirRecord:r}:{},...n.createdInTheWindow!==void 0&&n.createdInTheWindow>o?{moreInTheWindow:n.createdInTheWindow-o}:{}}}function vu(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 fh(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 ph(n){return n?{[nn]:[Or]}:{}}function mh(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 ma=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 ga=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{qn as a,zn as b,Ud as c,Vd as d,Bp as e,xu as f,ws as g,Mu as h,Lu as i,_u as j,bs as k,Du as l,qu as m,ma as n,yu as o,nn as p,br as q,Or as r,Ar as s,kr as t,Zg as u,Qg as v,Xg as w,eh as x,th as y,Ju as z,Hu as A,Ku as B,Xu as C,ef as D,ks as E,cf as F,lf as G,uf as H,ff as I,pf as J,mf as K,gf as L,hf as M,wf as N,yf as O,If as P,Ns as Q,Nf as R,Ef as S,Xn as T,er as U,em as V,xi as W,wg as X,Di as Y,yg as Z,$f as _,Tn as $,Wf as aa,vs as ba,qf as ca,zf as da,nd as ea,Uf as fa,cd as ga,tp as ha,np as ia,rp as ja,hd as ka,Mn as la,Id as ma,We as na,Us as oa,up as pa,fp as qa,Td as ra,pp as sa,mp as ta,ga as ua,Pd as va,vd as wa,yp as xa,Ap as ya,Wn as za,kp as Aa,Ip as Ba,jp as Ca,Np as Da,Hs as Ea,Pp as Fa,Cp as Ga,xp as Ha,Mp as Ia,Ks as Ja,hc as Ka,cm as La,um as Ma,fm as Na,wm as Oa,ym as Pa,bm as Qa,vc as Ra,Cc as Sa,xc as Ta,vm as Ua,Cm as Va,xm as Wa,Mm as Xa,Lm as Ya,_m as Za,Dm as _a,Bm as $a,$m as ab,zm as bb,dl as cb,Um as db,Og as eb,Bi as fb,$i as gb,Ig as hb,jg as ib,Ng as jb,Eg as kb,vg as lb,Mg as mb,hr as nb,tn as ob,Hg as pb,uh as qb,pa as rb,fh as sb,ph as tb,mh as ub};
|
package/lib/chunk-P63WJMXQ.mjs
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
-
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
-
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
-
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
-
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{b as a,c as b,d as c}from"./chunk-BN33LVPQ.mjs";import"./chunk-3XG25GTF.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-54HYHHVL.mjs";import"./chunk-WSUKC2U3.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-HFUDCNU5.mjs";import"./chunk-KIMQQ6JQ.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-ZUTUYBNW.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{c as CycleFkPass,b as RecordsOwingAcrossParts,a as patchCycleFkUpdates};
|