sandforge 1.79.0 → 1.80.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/lib/{chunk-JVL444U5.mjs → chunk-2BA2XKAY.mjs} +1 -1
- package/lib/chunk-2CNCDM56.mjs +7 -0
- package/lib/{chunk-W7KFAY55.mjs → chunk-2GTBABKU.mjs} +1 -1
- package/lib/{chunk-DLDX6RRC.mjs → chunk-2NBYT7GR.mjs} +1 -1
- package/lib/{chunk-HV2MXMGI.mjs → chunk-2UZPIMUC.mjs} +1 -1
- package/lib/chunk-3F6Q5E7I.mjs +14 -0
- package/lib/{chunk-PBI4BYWW.mjs → chunk-3RZQZHEB.mjs} +1 -1
- package/lib/{chunk-P7GSGFJO.mjs → chunk-3TJON4F3.mjs} +1 -1
- package/lib/chunk-4VS2V6WU.mjs +25 -0
- package/lib/{chunk-TQX3PURV.mjs → chunk-5K5VLULK.mjs} +1 -1
- package/lib/{chunk-MYTIL2JD.mjs → chunk-5TC3QB4U.mjs} +1 -1
- package/lib/{chunk-NM4MDLK4.mjs → chunk-6XYKJSGX.mjs} +1 -1
- package/lib/{chunk-RFEO2KAN.mjs → chunk-74Q6DORA.mjs} +1 -1
- package/lib/chunk-7ABODJ4G.mjs +7 -0
- package/lib/{chunk-ZPYJPGDK.mjs → chunk-7EGQP6S4.mjs} +1 -1
- package/lib/chunk-7FFGJWHN.mjs +7 -0
- package/lib/chunk-7YDNUBO5.mjs +7 -0
- package/lib/{chunk-CGWXQX75.mjs → chunk-A527W53V.mjs} +1 -1
- package/lib/chunk-ADOAS63R.mjs +7 -0
- package/lib/chunk-AEKONPF4.mjs +7 -0
- package/lib/{chunk-4HFRHFGQ.mjs → chunk-B5QQJ4SI.mjs} +1 -1
- package/lib/{chunk-2BVTCNWA.mjs → chunk-BGUEWRK2.mjs} +1 -1
- package/lib/{chunk-GNC27UEU.mjs → chunk-BKDV4ENO.mjs} +1 -1
- package/lib/{chunk-QRV2OSIS.mjs → chunk-BTWDMNN3.mjs} +1 -1
- package/lib/{chunk-FOVVHGEP.mjs → chunk-BV6VTP3J.mjs} +1 -1
- package/lib/{chunk-PZTSVQSF.mjs → chunk-BXU6WFMH.mjs} +1 -1
- package/lib/{chunk-ZQOZ4EFW.mjs → chunk-BY2HJFFG.mjs} +1 -1
- package/lib/{chunk-NZ5ZZLKS.mjs → chunk-CEX3NEZL.mjs} +1 -1
- package/lib/{chunk-HTJ5OGP5.mjs → chunk-CHYDMRSV.mjs} +1 -1
- package/lib/chunk-CION3VMZ.mjs +7 -0
- package/lib/chunk-COFG7Q6R.mjs +7 -0
- package/lib/chunk-CSBS5U5I.mjs +7 -0
- package/lib/{chunk-55HEMHEG.mjs → chunk-CU2INBND.mjs} +1 -1
- package/lib/chunk-DB7RBE5D.mjs +7 -0
- package/lib/{chunk-QPF6C5MX.mjs → chunk-DBB3EMIN.mjs} +1 -1
- package/lib/{chunk-F74IHMGL.mjs → chunk-DYFALGRT.mjs} +1 -1
- package/lib/{chunk-TEOLMRDO.mjs → chunk-E5AHXLS6.mjs} +1 -1
- package/lib/{chunk-LRFAIUN7.mjs → chunk-E5ZB3LU5.mjs} +1 -1
- package/lib/chunk-EFR2Y7E4.mjs +7 -0
- package/lib/chunk-EHQ3FX6X.mjs +7 -0
- package/lib/{chunk-RAAANPPG.mjs → chunk-ELFXJHU7.mjs} +1 -1
- package/lib/{chunk-BN7A4GRQ.mjs → chunk-EMNC6YI4.mjs} +1 -1
- package/lib/{chunk-HJC7AIBK.mjs → chunk-EQNW3UC2.mjs} +1 -1
- package/lib/{chunk-Z7X534S4.mjs → chunk-F43REJDZ.mjs} +2 -2
- package/lib/{chunk-QQZZMKU3.mjs → chunk-F6GUDTOB.mjs} +1 -1
- package/lib/{chunk-6EBMEGZB.mjs → chunk-FGRG7ANU.mjs} +1 -1
- package/lib/{chunk-4NAHW2D3.mjs → chunk-FKG7Q3WH.mjs} +1 -1
- package/lib/{chunk-7UQD6V6F.mjs → chunk-FPKYYFM7.mjs} +1 -1
- package/lib/{chunk-ZJKCWBRJ.mjs → chunk-FXXLX4O6.mjs} +1 -1
- package/lib/chunk-G35N4P7D.mjs +7 -0
- package/lib/{chunk-SIOZXPFG.mjs → chunk-GGD7ON3M.mjs} +1 -1
- package/lib/chunk-GSG7WZHM.mjs +7 -0
- package/lib/{chunk-OTWRDD6L.mjs → chunk-GSKCGQIP.mjs} +1 -1
- package/lib/{chunk-3CA767QB.mjs → chunk-HEKAZJRH.mjs} +1 -1
- package/lib/{chunk-4SNDMJP2.mjs → chunk-HLWMJF6Y.mjs} +1 -1
- package/lib/chunk-HOJYWTP7.mjs +20 -0
- package/lib/chunk-HS4YRX4J.mjs +7 -0
- package/lib/chunk-IFETCRWE.mjs +10 -0
- package/lib/{chunk-PUOX4NBJ.mjs → chunk-IG2MTQRP.mjs} +1 -1
- package/lib/{chunk-RACDTRZA.mjs → chunk-IGYH7GMA.mjs} +1 -1
- package/lib/{chunk-X65MT4W3.mjs → chunk-IOIWJ3DJ.mjs} +1 -1
- package/lib/{chunk-4U6NXJNL.mjs → chunk-IQXHJEYB.mjs} +1 -1
- package/lib/{chunk-P2PJYWGQ.mjs → chunk-IWDREM66.mjs} +1 -1
- package/lib/{chunk-ZOVSMN5C.mjs → chunk-IZQZ6ZUF.mjs} +1 -1
- package/lib/{chunk-XBG5SP6Q.mjs → chunk-J525F5KI.mjs} +1 -1
- package/lib/{chunk-5CD257T7.mjs → chunk-JEERQRLW.mjs} +1 -1
- package/lib/{chunk-6QSM2WIH.mjs → chunk-JPUR2CFX.mjs} +1 -1
- package/lib/chunk-JWTSEDIQ.mjs +7 -0
- package/lib/chunk-K327QKMD.mjs +7 -0
- package/lib/{chunk-J7HVXMSW.mjs → chunk-KBJ5VERV.mjs} +1 -1
- package/lib/chunk-KDGMAGQR.mjs +7 -0
- package/lib/chunk-KRCA6IPH.mjs +8 -0
- package/lib/chunk-KYEDBS54.mjs +7 -0
- package/lib/chunk-L5FGY6YA.mjs +7 -0
- package/lib/{chunk-PNCONNFJ.mjs → chunk-L77FJZEP.mjs} +1 -1
- package/lib/{chunk-3OHPD72J.mjs → chunk-LKQ5RKIV.mjs} +1 -1
- package/lib/{chunk-WJY54JO7.mjs → chunk-LPBMBW3O.mjs} +1 -1
- package/lib/{chunk-LV6G4XTK.mjs → chunk-LWW4U276.mjs} +1 -1
- package/lib/{chunk-IAZB4WIL.mjs → chunk-M3ROUWDX.mjs} +1 -1
- package/lib/chunk-MFG4MUIO.mjs +9 -0
- package/lib/{chunk-H45UXY6G.mjs → chunk-MHMH6MTP.mjs} +1 -1
- package/lib/{chunk-HCIDVIOW.mjs → chunk-MILU7WFN.mjs} +1 -1
- package/lib/chunk-MJU2PGZQ.mjs +15 -0
- package/lib/{chunk-HJKM3E56.mjs → chunk-MJVTDA5Q.mjs} +1 -1
- package/lib/{chunk-SBIMVCXT.mjs → chunk-MS4FJDFD.mjs} +9 -9
- package/lib/{chunk-3SRXFZSD.mjs → chunk-MYW5QNGI.mjs} +1 -1
- package/lib/{chunk-VHI54FBK.mjs → chunk-N652NMZ4.mjs} +26 -26
- package/lib/{chunk-3DCUADVK.mjs → chunk-NTFIRZP6.mjs} +1 -1
- package/lib/{chunk-342FN7AO.mjs → chunk-NZC67CGR.mjs} +1 -1
- package/lib/{chunk-RSYICMZG.mjs → chunk-O2HDYYUV.mjs} +1 -1
- package/lib/chunk-OAZRPP4I.mjs +7 -0
- package/lib/{chunk-BILZ3SSR.mjs → chunk-OHWNPXWW.mjs} +1 -1
- package/lib/chunk-OLSGVAIL.mjs +341 -0
- package/lib/chunk-OO6CLPEH.mjs +7 -0
- package/lib/chunk-OPXCV2KL.mjs +7 -0
- package/lib/chunk-P33PSCXK.mjs +7 -0
- package/lib/{chunk-AUTM6H6Z.mjs → chunk-PJ5I73CK.mjs} +1 -1
- package/lib/{chunk-NTDN2JQZ.mjs → chunk-PZPJKATS.mjs} +1 -1
- package/lib/{chunk-5QKTYCWE.mjs → chunk-Q3DM32KF.mjs} +1 -1
- package/lib/{chunk-K22PA4XL.mjs → chunk-QR3WELJQ.mjs} +1 -1
- package/lib/{chunk-42RER7V4.mjs → chunk-R3X3LV64.mjs} +1 -1
- package/lib/chunk-RMBPOTD7.mjs +7 -0
- package/lib/{chunk-IEYG5ATY.mjs → chunk-RPI7LRTW.mjs} +1 -1
- package/lib/{chunk-5MMXFWPD.mjs → chunk-SE4QEZUG.mjs} +1 -1
- package/lib/{chunk-ALJVEUUS.mjs → chunk-SIHORWVK.mjs} +1 -1
- package/lib/{chunk-AAVJ5XVX.mjs → chunk-SOGQW4IG.mjs} +1 -1
- package/lib/chunk-SOU4FRYN.mjs +7 -0
- package/lib/chunk-SU65Z2BA.mjs +7 -0
- package/lib/chunk-T62WNR54.mjs +7 -0
- package/lib/{chunk-5O6JOMHS.mjs → chunk-TSLJUSLW.mjs} +1 -1
- package/lib/chunk-TTFDUKUS.mjs +47 -0
- package/lib/{chunk-57VHUYNG.mjs → chunk-TTKXMDBN.mjs} +1 -1
- package/lib/chunk-UCD54V2M.mjs +7 -0
- package/lib/{chunk-TBZMC2VV.mjs → chunk-UNJA4J37.mjs} +1 -1
- package/lib/{chunk-NGSMZZDA.mjs → chunk-VE6XKGGD.mjs} +1 -1
- package/lib/chunk-VS7ZXUII.mjs +824 -0
- package/lib/{chunk-ALUFROGA.mjs → chunk-VXQLDM4R.mjs} +1 -1
- package/lib/chunk-VYXMVJL5.mjs +7 -0
- package/lib/{chunk-WFEB5X4U.mjs → chunk-W622GUAW.mjs} +1 -1
- package/lib/chunk-W7U5E5ZL.mjs +9 -0
- package/lib/{chunk-AR7BE5O2.mjs → chunk-WA7EYLAQ.mjs} +1 -1
- package/lib/{chunk-EQF2IJS2.mjs → chunk-WR4Q363I.mjs} +1 -1
- package/lib/{chunk-ZXH4MBWP.mjs → chunk-WU3GLFZO.mjs} +1 -1
- package/lib/chunk-WXAQ7FK3.mjs +115 -0
- package/lib/{chunk-YBU4Z4QV.mjs → chunk-X5JYBPXP.mjs} +1 -1
- package/lib/chunk-XAMBCQPU.mjs +7 -0
- package/lib/{chunk-LQ4DRFUH.mjs → chunk-XLXIPIEW.mjs} +1 -1
- package/lib/{chunk-H2PJNIYJ.mjs → chunk-XUWL6ZPC.mjs} +1 -1
- package/lib/{chunk-P42X3B4D.mjs → chunk-YKKRIEH4.mjs} +1 -1
- package/lib/chunk-YRQGKDHM.mjs +7 -0
- package/lib/chunk-ZM6OJGIG.mjs +7 -0
- package/lib/{chunk-SFURUNJM.mjs → chunk-ZVAED4QV.mjs} +1 -1
- package/lib/sandforge-autopilot.mjs +29 -24
- package/lib/sandforge-backup.mjs +25 -21
- package/lib/sandforge-checkpoint.mjs +15 -14
- package/lib/sandforge-cleanup.mjs +14 -10
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +9 -8
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +15 -15
- package/lib/sandforge-env.mjs +88 -88
- package/lib/sandforge-frozen.mjs +43 -34
- package/lib/sandforge-mcp.mjs +12 -12
- package/lib/sandforge-monitor.mjs +7 -7
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge.mjs +4 -4
- package/package.json +1 -1
- package/lib/chunk-2S5OMIIA.mjs +0 -7
- package/lib/chunk-36U7IQ6Y.mjs +0 -25
- package/lib/chunk-3F5YMM2F.mjs +0 -7
- package/lib/chunk-3RYLICRX.mjs +0 -7
- package/lib/chunk-4GL773D5.mjs +0 -7
- package/lib/chunk-4XZ5YT5O.mjs +0 -7
- package/lib/chunk-5AJRHRXA.mjs +0 -20
- package/lib/chunk-5HMAPZBV.mjs +0 -7
- package/lib/chunk-6LAXTAVN.mjs +0 -7
- package/lib/chunk-6MUEPV7M.mjs +0 -9
- package/lib/chunk-75ADZS6B.mjs +0 -7
- package/lib/chunk-B45CNPUX.mjs +0 -47
- package/lib/chunk-BS5T3MOQ.mjs +0 -7
- package/lib/chunk-D3QRXG63.mjs +0 -787
- package/lib/chunk-EEVVGGM6.mjs +0 -7
- package/lib/chunk-ENLBYECD.mjs +0 -7
- package/lib/chunk-EQOQASDQ.mjs +0 -7
- package/lib/chunk-FQBRBBY4.mjs +0 -7
- package/lib/chunk-GAM726CK.mjs +0 -7
- package/lib/chunk-HUMEKZT5.mjs +0 -8
- package/lib/chunk-I3JKJTLO.mjs +0 -110
- package/lib/chunk-KLX67VPL.mjs +0 -7
- package/lib/chunk-L776PUMV.mjs +0 -7
- package/lib/chunk-NEVXIGR6.mjs +0 -10
- package/lib/chunk-NHWE66K5.mjs +0 -7
- package/lib/chunk-OQOZAPCI.mjs +0 -7
- package/lib/chunk-PA3MKJVH.mjs +0 -7
- package/lib/chunk-RH3N2H7P.mjs +0 -7
- package/lib/chunk-SRQDABQ2.mjs +0 -15
- package/lib/chunk-SVS6UMDU.mjs +0 -323
- package/lib/chunk-TNXUU6W7.mjs +0 -14
- package/lib/chunk-VXHDBYMI.mjs +0 -7
- package/lib/chunk-WRU5FJFC.mjs +0 -7
- package/lib/chunk-X2PY6MWZ.mjs +0 -7
- package/lib/chunk-XEFDB2R4.mjs +0 -7
- package/lib/chunk-XETCPL7E.mjs +0 -7
- package/lib/chunk-Y5CGXLUB.mjs +0 -7
- package/lib/chunk-Y6J6QFI2.mjs +0 -7
- package/lib/chunk-YMJVMFPY.mjs +0 -7
- package/lib/chunk-YPSRZRIT.mjs +0 -7
- package/lib/chunk-YW2SBL4Z.mjs +0 -7
- package/lib/chunk-ZE6HKRR4.mjs +0 -9
- package/lib/chunk-ZLZRU6MO.mjs +0 -7
- package/lib/chunk-ZYEE34WO.mjs +0 -7
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{l as i}from"./chunk-
|
|
7
|
+
import{l as i}from"./chunk-F43REJDZ.mjs";function u(o,t){let n=e=>e==="production"?`${t} is taken for a production org, and this command writes to none`:void 0;return new i({requestConfirmation:(e,d)=>{let r=n(d);return r===void 0?Promise.resolve(!0):(o(`refused: ${r} (${e})`),Promise.resolve(!1))},declinesWithoutAsking:n})}export{u as a};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a,b,c,d,e}from"./chunk-
|
|
7
|
+
import{a,b,c,d,e}from"./chunk-CU2INBND.mjs";import"./chunk-YKKRIEH4.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as FieldMappingService,b as MOVES_ITS_SOURCE,e as mapFields,c as mappedTargets,d as notSentAsRead};
|
|
@@ -0,0 +1,25 @@
|
|
|
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{o as $o,s as ts}from"./chunk-F43REJDZ.mjs";import{A as bn,B as yn,H as pe,I as vo,J as Ft,R as xo,aa as zo,e as Ct,m as jo,qa as ct,ra as Qo,sa as Xo,ta as es,v as Co,w as Po,x as To}from"./chunk-JPUR2CFX.mjs";import{b as qo,d as Mt,e as _e,f as Uo,g as Wo,h as _t,i as Go,j as Vo,k as Jo,l as Ho,m as Ko,n as Yo,o as de,p as le,q as Dt,r as Oe,s as Zo}from"./chunk-LPBMBW3O.mjs";import{d as at,x as Me}from"./chunk-IFETCRWE.mjs";import{b as Fo}from"./chunk-QSRAEUGZ.mjs";import{b as Lo}from"./chunk-DYFALGRT.mjs";import{a as Bo}from"./chunk-M6P5ZZLE.mjs";import{a as Mo}from"./chunk-YYZL7UGV.mjs";import{a as Oo,l as Eo}from"./chunk-SAR5622P.mjs";import{f as wo,g as bo}from"./chunk-EQNW3UC2.mjs";import{a as Ro,b as Ge,c as So,d as ne,h as ye}from"./chunk-GSKCGQIP.mjs";import{a as yo}from"./chunk-5LFSFYFJ.mjs";import{a as Et}from"./chunk-HS4YRX4J.mjs";import{B as De,D as dt,Ka as is,La as as,M as Lt,O as ns,Qa as cs,Ra as ds,Sa as ls,Ta as Rn,_ as rs,ca as os,da as ss,f as io,o as _o,p as vt}from"./chunk-VYXMVJL5.mjs";import{a as it,b as to,c as no,g as Nt,j as ro,n as oo,r as so}from"./chunk-JWTSEDIQ.mjs";import{a as Ce}from"./chunk-4TLYUZD5.mjs";import{A as Do,t as xt}from"./chunk-CION3VMZ.mjs";import{b as go,c as mo}from"./chunk-EADHKH3A.mjs";import{g as ho}from"./chunk-GCOB7K5N.mjs";import{a as ao,b as co,c as gn,e as lo,f as uo,g as fo,i as mn,j as po}from"./chunk-INIT2UKJ.mjs";import{a as Br}from"./chunk-SU65Z2BA.mjs";import{a as ko,c as wn,j as No}from"./chunk-L77FJZEP.mjs";import{A as fn,B as Wr,E as Gr,F as pn,I as Vr,J as Jr,N as Hr,Q as Kr,R as Yr,S as Zr,T as Qr,U as Xr,V as eo,p as jt,q as $r,r as We,w as zr,x as qr,z as Ur}from"./chunk-A527W53V.mjs";import{a as Ue,h as V}from"./chunk-TZE3Y7IQ.mjs";import{a as Pt,c as hn,f as Ao,i as Tt,k as Io}from"./chunk-GGD7ON3M.mjs";import{a as st,b as U}from"./chunk-CA5NAXSU.mjs";import{Aa as vr,Bb as Mr,Cb as qe,Db as Se,Eb as je,Gc as Dr,Hc as Lr,L as ot,Q as ln,W as Er,X as jr,Y as Ee,Z as Nr,_ as Cr,ba as un,ca as Pr,da as Tr,ea as Fr,gc as Ne,uc as _r,vb as xr}from"./chunk-TTFDUKUS.mjs";import{b as q,e as H,f as Or,i as Re,k as J,l as z,o as Ar,r as Ir,s as rt,u as ve,v as xe,z as kr}from"./chunk-7EANH5PY.mjs";var Ve=.5;function pu(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 fs(n){if("unread"in n.storage)return n.withinMB===void 0?{unread:n.storage.unread}:us(n,Math.floor(Math.max(0,n.withinMB)*1048576),{share:De,roundingMB:Ve,withinMB:n.withinMB,limitedBy:"within"});let{remainingMB:e,maxMB:t}=n.storage,r=De*Math.max(0,e-Ve)*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:De,roundingMB:Ve,...n.withinMB!==void 0?{withinMB:n.withinMB}:{},limitedBy:s},a=Math.floor(Math.min(r,o));return us(n,a,i)}function gu(n,e){return e.bytesLimit==="within"&&e.storageBytes!==void 0&&n>e.storageBytes?"storage":e.bytesLimit}function us(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-Lt*n.api.max-r));return{bytes:e,terms:t,runRequests:o}}var Qi=/__e$/i,Xi=/Share$/;function mu(n,e){let t=new Map,r=new Map,o=(i,a)=>{let c=`${i}
|
|
8
|
+
${a}`,l=t.get(c);return l||(l={objectApiName:i,act:a,bytes:0,creates:[]},t.set(c,l)),l},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 c of i.flow.creates??[]){if(Qi.test(c))continue;if(Xi.test(c)){s({objectApiName:i.objectApiName,kind:"share",name:c});continue}let l=o(i.objectApiName,a);l.bytes+=dt(c,{rows:1}),l.creates.push({objectApiName:c,by:i.name})}}}return{perRecord:[...t.values()].filter(i=>i.bytes>0),notCounted:[...r.values()]}}function hu(n,e){return n.perRecord.reduce((t,r)=>t+r.bytes*Math.max(0,e(r.objectApiName,r.act)),0)}function wu(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 bu(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 yu(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{appendFile as ea}from"node:fs/promises";var Pe=new Set(["Task","Event"]),ta=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,na="an emptying";function ra(n){let e=V(n.objectApiName),t=Pe.has(n.objectApiName),r=[...n.filter!==void 0&&n.filter.trim()!==""?[`(${n.filter})`]:[],...t?["IsDeleted = false"]:[]];return{soql:`SELECT Id FROM ${e}${r.length>0?` WHERE ${r.join(" AND ")}`:""}`,scanAll:t}}async function ju(n,e,t,r={}){let o=()=>r.signal?.aborted===!0,s=[];await Me(e);for(let i of t){let{soql:a,scanAll:c}=ra(i),l={objectApiName:i.objectApiName,count:0};if(s.push(l),o())return{stopped:!0,read:s};let p=ct(e,i.objectApiName),u=!0,f=0,d=await n.query(a,{scanAll:c});for(;;){let m=d.records.map(h=>{let w=h.Id;if(typeof w!="string"||!ta.test(w))throw new Error(`The org answered a ${i.objectApiName} row with no record id: its ids are not read.`);return w});if((m.length>0||u)&&(await ea(p,m.map(h=>`${h}
|
|
11
|
+
`).join(""),{encoding:"utf8",mode:at,flag:u?"w":"a"}),u=!1),l.count+=m.length,r.onPage?.(i.objectApiName,l.count),f=m.length===0?f+1:0,d.done||!d.nextRecordsUrl)break;if(f>=go)throw new Error(`The org kept answering empty pages of ${i.objectApiName} without saying it was done: ${l.count} id(s) read, the rest not.`);if(o())return{stopped:!0,read:s};d=await n.queryMore(d.nextRecordsUrl)}}return{stopped:!1,spool:await Qo(e,s,na)}}function Je(n,e,t){return e.nillable!==!1||e.referenceTo.length!==1?!1:e.isMasterDetail||(t??[]).some(r=>r.isCascadeDelete&&r.childSObject===n&&r.field===e.name)}var oa={clone:"write",empty:"delete"},sa=["settings","definition"],ia=new Set(["contentworkspace"]);function aa(n){if(n.name.includes("__"))return!1;let e=n.name.toLowerCase();return ia.has(e)||sa.some(t=>e.endsWith(t))?!0:n.createable===!1&&e!==Nt.toLowerCase()}function ca(n,e){return n.objectApiName<e.objectApiName?-1:n.objectApiName>e.objectApiName?1:0}function da(n,e,t,r={}){let o=oo(n,{mode:"everything",access:oa[t],...r.excluded!==void 0?{excluded:r.excluded}:{},...r.customSettings!==void 0?{customSettings:r.customSettings}:{}},e),s=new Map(n.map(c=>[c.name.toLowerCase(),c])),i=[],a=[];for(let c of o.candidates){let l=s.get(c.toLowerCase());l!==void 0&&aa(l)?a.push({objectApiName:c,reason:"configuration"}):i.push(c)}return a.length===0?o:{...o,candidates:i,leftOut:[...o.leftOut,...a].sort(ca)}}var la=new Set([Nt,ro].map(n=>n.toLowerCase())),ps="withTheirRecords",ua="noLayout";function fa(n){switch(n){case"configuration":return{reason:"setup"};case"chatter":case"history":case"sharing":case"changeEvent":case"unsupportedKind":case"customSetting":case"files":case"setup":case"platformCreated":case"metadata":case"notWritable":case"excludedByUser":return{reason:n};case"heldWithFiles":return{reason:"files",detail:ps};case"notFound":case"notCustomSetting":return{reason:"missingInTarget"}}}function pa(n){switch(n){case"platform":return{reason:"platformCreated"};case"setup":return{reason:"setup"};case"feature":case"parent":return{reason:"notWritable",detail:n};case"user":return{reason:"notWritable"}}}function ga(n){if(n.createable!==!0||n.queryable!==!0)return;let e=n.updateable===!0,t=n.deletable===!0;if(!(e&&t))return!e&&!t?{reason:"createOnly"}:{reason:"createOnly",detail:e?ha:ma}}var ma="noEdit",ha="noDelete";function wa(n,e){return n.objectApiName<e.objectApiName?-1:n.objectApiName>e.objectApiName?1:0}function gs(n,e,t,r={}){let o=da(e,t,"clone",r),s=new Map(n.map(u=>[u.name.toLowerCase(),u])),i=new Map(e.map(u=>[u.name.toLowerCase(),u])),a=[],c=[],l=new Set,p=(u,f,d)=>{l.add(u.toLowerCase()),c.push({objectApiName:u,reason:f,...d!==void 0?{detail:d}:{}})};for(let u of n)i.has(u.name.toLowerCase())||p(u.name,"missingInTarget");for(let u of o.leftOut){let f=u.objectApiName.toLowerCase(),d=s.get(f);if(!d||l.has(f))continue;let m=i.get(f),h=fa(u.reason),w=f!==Nt.toLowerCase();h.reason==="notWritable"&&w&&m?.createable!==!0&&r.createFacts&&(h=pa(Bo(d.name,r.createFacts))),h.reason==="notWritable"&&w&&m&&(h=ga(m)??h);let b=u.reason==="setup"&&m?.layoutable===!1&&!no(u.objectApiName);p(d.name,h.reason,b?ua:h.detail??u.detail)}for(let u of o.candidates){let f=u.toLowerCase(),d=s.get(f);d&&(d.queryable!==!0?p(d.name,"notQueryable"):la.has(f)?p(d.name,"files",ps):a.push(d.name))}return a.sort(),c.sort(wa),{candidates:a,leftOut:c}}var Sn=1950,ms=2e4,ba=1e6,ya=18,Ra=200,Sa=new Set(["QUERY_TIMEOUT","OPERATION_TOO_LARGE","REQUEST_LIMIT_EXCEEDED","REQUEST_RUNNING_TOO_LONG","SERVER_UNAVAILABLE","UNKNOWN_EXCEPTION"]);function Bt(n){if(n instanceof _o||Br(n))return!1;let e=st(U(n));return e===void 0?!1:!Sa.has(e)&&!e.startsWith("ERROR_HTTP_")}function Oa(n,e){let t=Pe.has(n),r=[...e?[`(${e})`]:[],...t?["IsDeleted = false"]:[]];return{soql:`SELECT COUNT() FROM ${V(n)}${r.length>0?` WHERE ${r.join(" AND ")}`:""}`,all:t}}async function Ae(n,e){let t=0,r=!1,o=()=>r,s=async()=>{for(;!r&&t<n.length;){let i=t++;try{await e(n[i],i,o)}catch(a){throw r=!0,a}}};await Promise.all(Array.from({length:Math.min(6,n.length)},s))}async function Aa(n,e){try{return await n()}catch(t){if(t instanceof ae||Et(t)||Bt(t))throw t;return Ce.warn(`[forge-discover] whole org: describe of ${e} unanswered, asked again: ${U(t)}`),n()}}function hs(n){if(!(n<=un))throw new Error(`The source org lists ${n} objects a clone of the whole org leaves out, more than the ${un} one graph says. Nothing was written. Clone the org in parts instead: a run from a record or from a query for each part.`)}var Ia=z({name:q().min(1),count:H().int().nonnegative()});function ka(n){let e=z({sObjects:J(Re())}).safeParse(n);if(!e.success)return;let t=new Map;for(let r of e.data.sObjects){let o=Ia.safeParse(r);o.success&&t.set(o.data.name,o.data.count)}return t}function Ea(n){let e=new Map;for(let[t,r]of n)for(let o of r.fields){if(o.referenceTo.length===0)continue;let s=Se(o),i=s&&qe(t,o.name,o.nillable),a=je(o);for(let c of o.referenceTo){if(c===t||!n.has(c))continue;let l=`${c}|${t}`,p={sourceObject:c,targetObject:t,relationshipName:o.relationshipName??o.name,type:Je(t,o,n.get(c)?.childRelationships)?"master-detail":"lookup",required:i},u=e.get(l);if(!u){e.set(l,{edge:p,noneSettable:!s,insertOnly:a});continue}let f=p.type==="master-detail"&&u.edge.type==="lookup"?p:u.edge;u.edge={...f,required:u.edge.required===!0||i},u.noneSettable=u.noneSettable&&!s,u.insertOnly=u.insertOnly||a}}return[...e.values()].map(({edge:t,noneSettable:r,insertOnly:o})=>({...t,...r?{settable:!1}:{},...o?{insertOnly:!0}:{}}))}function ja(n,e){let t=e.filter(Do),r=Lo(n,t).reverse(),o=new Map;r.forEach((a,c)=>{for(let l of a)o.set(l,c)});let s=new Map;for(let a of t){let c=s.get(a.targetObject)??[];c.push(a.sourceObject),s.set(a.targetObject,c)}let i=r.map(()=>0);return r.forEach((a,c)=>{for(let l of a)for(let p of s.get(l)??[]){let u=o.get(p);u!==void 0&&u!==c&&(i[c]=Math.max(i[c],i[u]+1))}}),new Map(n.map(a=>[a,Math.min(ya,1+i[o.get(a)??0])]))}async function ws(n,e,t){let r=Cr(e);if(r!==void 0)throw new Error(r);let o=t?.signal;if(o?.aborted)return ut();try{return await Na(n,e,t)}catch(s){if(s instanceof ae||o?.aborted)return ut();throw s}}async function Na(n,e,t){let r=t?.signal,o=O=>t?.onProgress?.(O),s=Date.now(),i=O=>A=>{if(A instanceof ae)throw A;return Ce.warn(`[forge-discover] whole org: ${U(A)}`),O},{toolingObjects:a,recordCounts:c,createFacts:l}=n;o({phase:"listing",discoveredCount:0,queueRemaining:0});let[p,u,f,d,m]=await Promise.all([me(()=>n.describeGlobal(e.sourceOrgId,r),r),me(()=>n.describeGlobal(e.targetOrgId,r),r),a?me(()=>a(e.targetOrgId,r),r).catch(i([])):Promise.resolve([]),l?me(()=>l(e.targetOrgId),r).catch(i(void 0)):Promise.resolve(void 0),c?me(()=>c(e.sourceOrgId,r),r).catch(i(void 0)):Promise.resolve(void 0)]),h=ka(m),w=e.excludedObjects??[],{candidates:b,leftOut:S}=gs(p,u,f,{...d?{createFacts:d}:{},...w.length>0?{excluded:w}:{}}),I=[...S];hs(I.length);let g=b.map(()=>{}),y=0;o({phase:"counting",discoveredCount:0,queueRemaining:b.length,total:b.length}),await Ae(b,async(O,A,N)=>{let D=h?.get(O),$=e.objectSoqlFilters?.[O];if(D!==void 0&&D>ba&&!$)g[A]={objectApiName:O,rows:D,approximate:!0};else try{let{soql:E,all:x}=Oa(O,$),F=await me(()=>n.queryCount(e.sourceOrgId,E,r,x?{all:!0}:void 0),r);if(N())return;F>0?g[A]={objectApiName:O,rows:F}:I.push({objectApiName:O,reason:"empty"})}catch(E){if(E instanceof ae||Et(E))throw E;if(N())return;Bt(E)?I.push({objectApiName:O,reason:"unreadable",detail:U(E)}):(Ce.warn(`[forge-discover] whole org: ${O} not counted, kept: ${U(E)}`),g[A]=D!==void 0&&D>0&&!$?{objectApiName:O,rows:D,approximate:!0}:{objectApiName:O,rows:0,unknown:!0})}y++,o({phase:"counting",objectApiName:O,discoveredCount:y,queueRemaining:b.length-y,total:b.length})});let R=g.filter(O=>O!==void 0);if(R.length>Sn)throw new Error(`The source org holds records in ${R.length} objects a clone of the whole org would take, more than the ${Sn} one run writes. Nothing was written. Leave ${R.length-Sn} of them out or more, or clone the org in parts instead: a run from a record or from a query for each part.`);let j=R.map(()=>{}),v=0;o({phase:"describing",discoveredCount:0,queueRemaining:R.length,total:R.length}),await Ae(R,async({objectApiName:O},A,N)=>{try{let D=await Aa(()=>me(()=>n.describeObject(e.sourceOrgId,O,r),r),O);if(N())return;j[A]=D}catch(D){if(D instanceof ae||Et(D))throw D;if(N())return;I.push({objectApiName:O,reason:"notDescribed",detail:U(D)})}v++,o({phase:"describing",objectApiName:O,discoveredCount:v,queueRemaining:R.length-v,total:R.length})}),await An();let T=new Map,C=new Map;R.forEach((O,A)=>{let N=j[A];N&&(T.set(O.objectApiName,N),C.set(O.objectApiName,O))});let M=Ea(T);if(M.length>ms)throw new Error(`The ${T.size} objects of the source org a clone of the whole org would take relate ${M.length} pairs of objects, more than the ${ms} one run writes in order. Nothing was written. Clone the org in parts instead: a run from a record or from a query for each part.`);let P=[...T.keys()],_=ja(P,M),L=P.map(O=>{let A=T.get(O),N=C.get(O),D=N.rows,$=n.detectPII(A.fields);return{objectApiName:O,...A.label?{label:A.label}:{},recordCount:D,...N.approximate?{recordCountApproximate:!0}:{},...N.unknown?{recordCountUnknown:!0}:{},fieldCount:A.fields.length,status:"idle",progress:0,included:!0,piiFields:$,anonymizeFields:e.anonymizePII?[...$]:[],level:_.get(O)??1,successCount:0,failureCount:0,errors:[],createableFieldCount:A.fields.filter(E=>E.type!=="id").length,estimatedSizeMB:D*lt,estimatedApiCalls:Math.ceil(D/Ra),batchStrategy:"auto"}});hs(I.length);let k=L.reduce((O,A)=>O+A.recordCount,0);return I.sort((O,A)=>O.objectApiName<A.objectApiName?-1:O.objectApiName>A.objectApiName?1:0),Ce.info(`[forge-discover] whole org: ${L.length} object(s), ${M.length} relation(s), ${I.length} left out, ${k} record(s), in ${Date.now()-s}ms`),{nodes:L,edges:M,totalRecords:k,estimatedSizeMB:k*lt,estimatedDurationSeconds:k*On,truncated:!1,leftOut:I}}var lt=.001,On=.01,Ca=50,Pa=5,Ta=2,Fa=4;function va(n){return n.level===0||n.recordCount>0||n.status==="error"||n.recordCountUnknown===!0}function ys(n){return n.inputMode==="record"&&typeof n.recordId=="string"&&n.recordId!==""}function xa(n,e,t){let r=[];t===0&&ys(n)&&r.push(`Id = '${Ue(n.recordId??"")}'`);let o=n.objectSoqlFilters?.[e];return o&&r.push(`(${o})`),`SELECT COUNT() FROM ${V(e)}${r.length>0?` WHERE ${r.join(" AND ")}`:""}`}var An=typeof setImmediate=="function"?()=>new Promise(n=>setImmediate(n)):()=>new Promise(n=>setTimeout(n,0)),ae=class extends Error{constructor(){super("Discovery cancelled"),this.name="DiscoveryCancelled"}};function me(n,e){return e?e.aborted?Promise.reject(new ae):new Promise((t,r)=>{let o=()=>r(new ae);e.addEventListener("abort",o,{once:!0}),n().then(s=>{e.removeEventListener("abort",o),t(s)},s=>{e.removeEventListener("abort",o),r(s)})}):n()}function Ma(n){return n.fieldCount>0||n.piiFields.length>0}function _a(n,e){if(n.type!=="master-detail")return n;let t=(e.get(n.targetObject)?.fields??[]).filter(o=>o.referenceTo.includes(n.sourceObject)),r=e.get(n.sourceObject)?.childRelationships;return t.some(o=>Je(n.targetObject,o,r))?n:{...n,type:"lookup"}}function ut(){return{nodes:[],edges:[],totalRecords:0,estimatedSizeMB:0,estimatedDurationSeconds:0,truncated:!1}}var bs=class{deps;constructor(e){this.deps=e}async discover(e,t){if(e.inputMode==="org"||e.depth==="all")return ws(this.deps,e,t);let r=t?.signal;if(r?.aborted)return ut();t?.onProgress?.({phase:"resolving-root",discoveredCount:0,queueRemaining:1});let o=Date.now(),s;try{s=await this.resolveRootObject(e,r)}catch(P){if(P instanceof ae)return ut();throw P}let i=Date.now();i-o>2e3&&Ce.warn(`[forge-discover] resolveRootObject took ${i-o}ms (cold path, consider verifying describeGlobal cache state)`);let a=this.resolveMaxDepth(e),c=t?.maxNodes??Ca,l=c,p=c*Ta,u=new Set,f=[],d=c*Fa,m=0,h=0,w=new Set,b=[],S=new Map,I=new Map,g=()=>m+h+T.length<l&&b.length+h+T.length<d,y=(P,_)=>{u.has(P)||f.push([P,_]),u.add(P)},R=P=>{u.delete(P)&&(f=f.filter(([_])=>_!==P))},j=new Map,v=(P,_,L,k)=>{if(it(P.sourceObject)||it(P.targetObject)||P.sourceObject===P.targetObject)return;let O=`${P.sourceObject}|${P.targetObject}`,A=j.get(O)??new Map;(L!==void 0||!A.has(_))&&A.set(_,{settable:L,insertOnly:k}),j.set(O,A);let N=S.get(O);if(!N){S.set(O,P);return}let D=P.type==="master-detail"&&N.type==="lookup"?P:N,$=N.required===!0||P.required===!0;S.set(O,$?{...D,required:$}:D)},T=[[s,0]];for(w.add(s);T.length>0&&!r?.aborted;){await An();let P=l-m;if(P<=0)break;let _=Math.min(6,P,T.length),L=T.splice(0,_),k=await Promise.all(L.map(async([O,A])=>{let N,D=!1,$=xa(e,O,A);try{let[E,x]=await Promise.all([me(()=>this.deps.describeObject(e.sourceOrgId,O,r),r),me(()=>this.deps.queryCount(e.sourceOrgId,$,r),r).catch(F=>{if(F instanceof ae)throw F;return N=U(F),D=Bt(F),-1})]);return{objectName:O,depth:A,describe:E,recordCount:x,countError:N,countRefused:D}}catch(E){return E instanceof ae||r?.aborted?{objectName:O,depth:A,describe:null,recordCount:-1,cancelled:!0}:{objectName:O,depth:A,describe:null,recordCount:-1,describeError:U(E)}}}));h=k.length;for(let O of k){if(h--,O.cancelled)continue;let{objectName:A,depth:N,describe:D,recordCount:$,countError:E,countRefused:x,describeError:F}=O;if(!D){b.push({objectApiName:A,recordCount:0,fieldCount:0,status:"error",progress:0,included:!1,piiFields:[],anonymizeFields:[],level:N,successCount:0,failureCount:0,errors:[`Describe unavailable: ${F??"unknown error"}`],createableFieldCount:0,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}),m++,t?.onProgress?.({phase:"object",objectApiName:A,discoveredCount:b.length,queueRemaining:T.length});continue}I.set(A,D);let B=$<0,W=B&&x!==!0,X=B&&!W,te=B?0:$,ze=N===0&&ys(e),be=this.deps.detectPII(D.fields),At=D.fields.filter(Y=>Y.type!=="id").length,It={objectApiName:A,...D.label?{label:D.label}:{},recordCount:te,...W?{recordCountUnknown:!0}:{},fieldCount:D.fields.length,status:X?"error":"idle",progress:0,included:X?!1:W||ze||!e.skipEmpty||te>0,piiFields:be,anonymizeFields:e.anonymizePII?be:[],level:N,successCount:0,failureCount:0,errors:X?[`Record count unavailable: ${E??"unknown error"}`]:[],createableFieldCount:At,estimatedSizeMB:te*lt,estimatedApiCalls:Math.ceil(te/200),batchStrategy:"auto"};b.push(It);let Rr=va(It);if(Rr&&m++,N<a&&Rr){for(let Y of D.fields){if(Y.referenceTo.length===0)continue;let Sr=Se(Y),kt=Sr&&qe(A,Y.name,Y.nillable),Yi=je(Y);for(let ie of Y.referenceTo){v({sourceObject:ie,targetObject:A,relationshipName:Y.relationshipName??Y.name,type:Y.isMasterDetail?"master-detail":"lookup",required:kt},Y.name,Sr,Yi);let Zi=u.has(ie);(!w.has(ie)||kt&&Zi)&&!it(ie)&&(g()?(w.add(ie),R(ie),kt?T.unshift([ie,N+1]):T.push([ie,N+1])):kt&&l<p?(w.add(ie),R(ie),l++,T.unshift([ie,N+1])):(w.add(ie),y(ie,N+1)))}}for(let Y of D.childRelationships)v({sourceObject:A,targetObject:Y.childSObject,relationshipName:Y.relationshipName,type:Y.isCascadeDelete?"master-detail":"lookup"},Y.field,void 0,void 0),!w.has(Y.childSObject)&&!it(Y.childSObject)&&(w.add(Y.childSObject),g()?T.push([Y.childSObject,N+1]):y(Y.childSObject,N+1))}t?.onProgress?.({phase:"object",objectApiName:A,discoveredCount:b.length,queueRemaining:T.length})}for(;f.length>0&&g();){let[O,A]=f.shift();u.delete(O),T.push([O,A])}}let C=b.reduce((P,_)=>P+_.recordCount,0),M=[...S].map(([P,_])=>{let L=[...j.get(P)?.values()??[]],k=_a(_,I);return L.length>0&&L.every(O=>O.settable===!1)&&(k={...k,settable:!1}),L.some(O=>O.insertOnly===!0)&&(k={...k,insertOnly:!0}),k});return{nodes:b,edges:M,totalRecords:C,estimatedSizeMB:C*lt,estimatedDurationSeconds:C*On,truncated:f.length>0}}personalFields(e){return this.deps.detectPII(e)}async readPersonalFields(e,t,r){let o=e.nodes.filter(i=>!Ma(i)&&i.status!=="error"),s=new Map;for(let i=0;i<o.length&&!r?.aborted;i+=6)await Promise.all(o.slice(i,i+6).map(async({objectApiName:a})=>{try{let c=await this.deps.describeObject(t.sourceOrgId,a,r),l=this.deps.detectPII(c.fields);l.length>0&&s.set(a,l)}catch(c){Ce.warn(`[forge] personal fields of ${a} not read: ${U(c)}`)}}));return s.size===0?e:{...e,nodes:e.nodes.map(i=>{let a=s.get(i.objectApiName);return a?{...i,piiFields:a,anonymizeFields:t.anonymizePII?[...a]:[]}:i})}}async resolveRootObject(e,t){if(e.inputMode==="record"&&e.recordId){let r=e.recordId.substring(0,3),s=(await me(()=>this.deps.describeGlobal(e.sourceOrgId,t),t)).find(i=>i.keyPrefix===r);if(!s)throw new Error(`No object found for record ID prefix "${r}". The ID may not belong to any accessible object in this org.`);return s.name}if(e.inputMode==="soql"&&e.soqlQuery)return Da(e.soqlQuery);throw new Error(`Cannot resolve root object for inputMode "${e.inputMode}". Provide a valid recordId (for "record" mode) or soqlQuery (for "soql" mode).`)}resolveMaxDepth(e){switch(e.depth){case"direct":return 1;case"full":return Pa;case"custom":return Math.max(1,Math.min(10,e.customDepth??3));case"all":throw new Error("A clone of the whole org is discovered without a walk (WholeOrgDiscovery)")}}};function Da(n){let e=n.replace(/\/\*[\s\S]*?\*\//g,"").replace(/--[^\n]*/g,"");for(let r=0;r<32;r++){let o=e.replace(/\([^()]*\)/g,"");if(o===e)break;e=o}let t=/\bFROM\s+(\w+)/i.exec(e);if(!t)throw new Error('Could not parse object name from SOQL query. Ensure the query uses standard "SELECT ... FROM ObjectName" syntax.');return V(t[1])}import{existsSync as La,readFileSync as Ba,writeFileSync as $a}from"node:fs";function af(n){let e={getData:()=>La(n)?JSON.parse(Ba(n,"utf8")):{},setData:r=>$a(n,JSON.stringify(r,null,2),{encoding:"utf8",mode:384})},t=new $o(e);return t.initialize(),t}var In="User",za="005",Ss=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function qa(n,e,t=to){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 ff(n){let{known:e,ownerMappings:t={},mapped:r,refused:o,inactive:s}=n,i=n.lookups.filter(m=>qa(m,n.outsideTheRun,n.neverCopied)),a=new Map,c=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||(c.add(w),e.has(w)))continue;let b=m.referenceTo??[];if(!b.some(S=>o?.has(S)===!0))for(let S of b)a.set(S,(a.get(S)??new Set).add(w))}let l=new Set,p=new Set,u=new Set;for(let[m,h]of a){let w=s!==void 0&&m===In,b=w?"Id, IsActive":"Id";for(let S of ne([...h]))try{let I=await n.query(`SELECT ${b} FROM ${V(m)} WHERE Id IN (${S})`);for(let g of I){let y=g.Id;typeof y=="string"&&(l.add(y),l.add(y.slice(0,15)),w&&g.IsActive===!1&&(u.add(y),u.add(y.slice(0,15))))}}catch{for(let I of h)p.add(I);o?.add(m);break}}let f=new Map;for(let m of a.values())for(let h of m)l.has(h)||l.has(h.slice(0,15))?f.set(h,!0):!p.has(h)&&!f.has(h)&&f.set(h,!1);for(let[m,h]of f){if(e.size>=Rs)break;e.set(m,h)}if(s&&u.size>0){let m=[...a.get(In)??[]].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 d=new Set;for(let m of c)(f.get(m)??e.get(m))===!1&&d.add(m);return d}function pf(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 Ua="SELECT PermissionsUpdateWithInactiveOwner FROM UserPermissionAccess";async function Wa(n){try{let[e]=await n(Ua);return e?.PermissionsUpdateWithInactiveOwner===!0}catch{return!1}}function gf(n){let e;return()=>(e??=Wa(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 c=a.slice(0,15),l=t.get(c)??{user:a,sources:[]};l.sources.push(i),t.set(c,l)}let r=[],o=[],s=[...t.values()];for(let i=0;i<s.length;i+=Ge){let a=s.slice(i,i+Ge),[c]=ne(a.map(({user:u})=>u)),l;try{l=await e(`SELECT Id, Name, IsActive FROM ${In} WHERE Id IN (${c})`)}catch{continue}let p=new Set;for(let u of l){let f=u.Id;if(typeof f!="string"||(p.add(f.slice(0,15)),u.IsActive!==!1))continue;let d=t.get(f.slice(0,15));if(!d)continue;let m=u.Name;r.push({user:d.user,...typeof m=="string"&&m!==""?{name:m}:{},sources:d.sources})}for(let{user:u,sources:f}of a)u.startsWith(za)&&!p.has(u.slice(0,15))&&o.push({user:u,sources:f})}return{inactive:r,unknown:o}}var $t=10,kn="Nothing was read or written.",bf="Nothing was written.";function As(n,e=kn){let t=n.slice(0,$t).map(({user:o,name:s,sources:i})=>`${s!==void 0?`${s} (${o})`:o}, given the records of `+i.join(", ")).join("; "),r=n.length-$t;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 Ga(n,e=kn){let t=n.slice(0,$t).map(({user:o,sources:s})=>`${o}, given the records of ${s.join(", ")}`).join("; "),r=n.length-$t;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 yf(n,e,t=kn){let{inactive:r,unknown:o}=await Os(n,e);if(o.length>0){let s=Ga(o,t);return new Rn(ls,r.length>0?`${s.slice(0,-t.length)}${As(r,t)}`:s)}return r.length>0?new Rn(ds,As(r,t)):void 0}import{createHash as Va}from"node:crypto";var Es={ContentVersion:"VersionData",Attachment:"Body"},Ja=3,Is=class extends Error{constructor(t,r,o){super(t);this.code=r;this.storage=o;this.name="ForgeFilesRefusedError"}code;storage};function Q(n,e){let t=n[e];return typeof t=="string"&&t!==""?t:void 0}function ks(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0}function En(n,e,t){return{objectApiName:n,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:e,messages:[U(t)]}]}}async function jf(n){let{scope:e,sourceOrgId:t,maxFileBytes:r,queryRecords:o}=n,s=new Map;for(let u of e.values())for(let f of u)s.has(f)||s.set(f,s.size);let i={files:[],leftOut:[],errors:[]},a=[...s.keys()];if(a.length===0)return i;let c=u=>s.get(u)??Number.MAX_SAFE_INTEGER,l=new Map;try{for(let u of ne(a)){let f=await o(t,`SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility FROM ContentDocumentLink WHERE LinkedEntityId IN (${u})`);for(let d of f){let m=Q(d,"ContentDocumentId"),h=Q(d,"LinkedEntityId");if(!m||!h||!s.has(h))continue;let w=l.get(m)??[];w.some(b=>b.id===h)||w.push({id:h,shareType:Q(d,"ShareType"),visibility:Q(d,"Visibility")}),l.set(m,w)}}}catch(u){i.errors.push(En("ContentDocument","(links of the records in scope)",u))}let p=[];try{for(let u of ne([...l.keys()])){let f=await o(t,`SELECT Id, ContentDocumentId, Title, PathOnClient, ContentSize, ContentLocation, SharingPrivacy FROM ContentVersion WHERE ContentDocumentId IN (${u}) AND IsLatest = true`);for(let d of f){let m=Q(d,"ContentDocumentId"),h=Q(d,"Id"),w=m?l.get(m):void 0;if(!m||!h||!w)continue;let b=Q(d,"Title")??m;p.push({external:(Q(d,"ContentLocation")??"S")!=="S",file:{objectApiName:"ContentDocument",sourceId:m,body:{objectApiName:"ContentVersion",id:h},name:b,bytes:ks(d,"ContentSize"),hosts:[...w].sort((S,I)=>c(S.id)-c(I.id)),fields:{Title:b,PathOnClient:Q(d,"PathOnClient")??b,...Q(d,"SharingPrivacy")==="P"?{SharingPrivacy:"P"}:{}}}})}}}catch(u){i.errors.push(En("ContentDocument","(latest versions of the files)",u))}try{for(let u of ne(a)){let f=await o(t,`SELECT Id, ParentId, Name, ContentType, BodyLength, IsPrivate FROM Attachment WHERE ParentId IN (${u})`);for(let d of f){let m=Q(d,"Id"),h=Q(d,"ParentId");if(!m||!h||!s.has(h))continue;let w=Q(d,"Name")??m;p.push({external:!1,file:{objectApiName:"Attachment",sourceId:m,body:{objectApiName:"Attachment",id:m},name:w,bytes:ks(d,"BodyLength"),hosts:[{id:h}],fields:{Name:w,...Q(d,"ContentType")?{ContentType:Q(d,"ContentType")}:{},IsPrivate:d.IsPrivate===!0}}})}}}catch(u){i.errors.push(En("Attachment","(attachments of the records in scope)",u))}p.sort((u,f)=>c(u.file.hosts[0].id)-c(f.file.hosts[0].id));for(let{file:u,external:f}of p){let d=f?"external":u.bytes>r?"too-large":void 0;d?i.leftOut.push({objectApiName:u.objectApiName,sourceId:u.sourceId,name:u.name,bytes:u.bytes,reason:d}):i.files.push(u)}return i}function Nf(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 Cf(n){let{files:e,targetOrgId:t,copiedBefore:r,queryRecords:o}=n,s={files:[],errors:[]},i=new Map;for(let d of e){let m=r(d.sourceId);m&&i.set(d.sourceId,m)}if(i.size===0)return{...s,files:[...e]};let a=new Map,c,l=new Map;for(let[d,m]of i)m.objectApiName==="ContentVersion"&&l.set(m.targetId,d),m.objectApiName==="ContentDocument"&&a.set(d,m.targetId);try{for(let d of ne([...l.keys()])){let m=await o(t,`SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id IN (${d})`);for(let h of m){let w=Q(h,"Id"),b=Q(h,"ContentDocumentId"),S=w?l.get(w):void 0;S&&b&&a.set(S,b)}}}catch(d){c=U(d)}let p=new Map,u;try{for(let d of ne([...new Set(a.values())])){let m=await o(t,`SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN (${d})`);for(let h of m){let w=Q(h,"ContentDocumentId"),b=Q(h,"LinkedEntityId");w&&b&&p.set(w,[...p.get(w)??[],b])}}}catch(d){u=U(d)}let f=(d,m)=>{s.errors.push({objectApiName:"ContentDocument",stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`${d.name} (${Ne(d.bytes)})`,messages:[m]}]})};for(let d of e){let m=i.get(d.sourceId);if(!m){s.files.push(d);continue}if(d.body.objectApiName==="Attachment")continue;let h=a.get(d.sourceId);if(!h){f(d,`Copied as ContentVersion ${m.targetId} by the run this one takes up, and its document still cannot be read back`+(c?` (${c})`:"")+": the file is not copied again, nor linked to the records it lacks.");continue}if(u){f(d,`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({...d,into:{documentId:h,linked:p.get(h)??[],unchanged:!0}})}return s}function Pf(n){return{objectApiName:"__files__",stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(files)",messages:[n]}]}}function Tf(n){return n.reduce((e,t)=>e+t.bytes,0)}function Ff(n,e){return n<=e?null:`The files to copy take ${Ne(n)} and the target has ${Ne(Math.max(0,e))} of file storage left. Lower the largest file copied, or leave the files out.`}async function vf(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 xf(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 jn(n,e){let t=n==="Attachment"?"attachment":"file";return e===1?t:`${t}s`}function Mf(n){return`[dry-run] ${n.objectApiName}: ${n.planned} ${jn(n.objectApiName,n.planned)} would be copied (${Ne(n.plannedBytes)})`}function Ha(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:Va("md5").update(Buffer.from(e,"base64")).digest("hex"),ContentSize:n.bytes}}function Ka(n){let e={};for(let[t,r]of Object.entries(n))t!=="SharingPrivacy"&&(e[t]=r);return e}async function _f(n){let{files:e,sourceOrgId:t,targetOrgId:r,remapper:o,deps:s,report:i,errors:a,onProgress:c,onCopied:l}=n,p=0,u=g=>{let y=i.objects.find(R=>R.objectApiName===g);return y||(y={objectApiName:g,planned:0,plannedBytes:0,copied:0,failed:0},i.objects.push(y)),y},f=(g,y)=>a.find(R=>R.objectApiName===g&&R.stage===y),d=new Map,m=(g,y,R=1)=>{let j=`${g}/${y}`;d.set(j,(d.get(j)??0)+R);let v=f(g,y);v&&(v.attemptedCount+=R)},h=(g,y,R,j,v=!1)=>{let T=f(g,y);T||(T={objectApiName:g,stage:y,failedCount:0,attemptedCount:d.get(`${g}/${y}`)??0,samples:[]},a.push(T)),v||(T.failedCount++,p++),T.samples.length<Ja&&T.samples.push({recordSummary:R,messages:[j]})},w=(g,y,R)=>{h(g.objectApiName,y,`${g.name} (${Ne(g.bytes)})`,R),u(g.objectApiName).failed++},b=async(g,y,R)=>{let j=R.flatMap(T=>{let C=o.get(T.id);return C?[{ContentDocumentId:y,LinkedEntityId:C,ShareType:T.shareType??"V",Visibility:T.visibility??"AllUsers"}]:[]});if(j.length===0)return[];let v=[];m("ContentDocumentLink","insert",j.length);try{let T=await s.insertRecords(r,"ContentDocumentLink",j);j.forEach((C,M)=>{let P=T[M];if(P?.success){i.links++,v.push(C.LinkedEntityId);return}h("ContentDocumentLink","insert",g.name,P?.errors.join("; ")||"The target gave no reason.")})}catch(T){for(let C=0;C<j.length;C++)h("ContentDocumentLink","insert",g.name,U(T))}return v},S=e.filter(g=>!(g.body.objectApiName==="ContentVersion"&&g.into?.unchanged)).length,I=0;for(let g of e){await n.waitIfPaused();let y=g.hosts.filter(N=>o.isCreated(N.id)),R=g.body.objectApiName==="ContentVersion"?g.into:void 0,j=R?y.filter(N=>{let D=o.get(N.id);return D!==void 0&&!R.linked.includes(D)}):[];if(R?.unchanged){let N=await b(g,R.documentId,j);N.length>0&&l?.(g,{targetId:R.documentId,linked:N,asVersion:!1});continue}let v=I++,T=y.length>0?o.get(y[0].id):void 0;if(!T&&!R){i.leftOut.push({objectApiName:g.objectApiName,sourceId:g.sourceId,name:g.name,bytes:g.bytes,reason:"record-not-created"});continue}c({objectName:g.objectApiName,status:"running",progress:Math.round(v/S*100),message:`Copying ${jn(g.objectApiName,1)} ${v+1} of ${S} (${Ne(g.bytes)})`});let C;m(g.objectApiName,"query");try{C=await s.readFileBody(t,g.body.objectApiName,g.body.id)}catch(N){w(g,"query",U(N));continue}let M=Buffer.byteLength(C,"base64");if(M!==g.bytes){w(g,"query",`Read ${M} bytes of the ${g.bytes} the source reports: the file was not written.`);continue}let P=R?{...Ka(g.fields),VersionData:C,ContentDocumentId:R.documentId}:g.body.objectApiName==="ContentVersion"?{...g.fields,VersionData:C,FirstPublishLocationId:T}:{...g.fields,Body:C,ParentId:T},_;m(g.objectApiName,"insert");let L=n.calls?.sending(g.body.objectApiName,[{sourceId:g.sourceId,payload:Ha(g,C,T)}]),k=()=>{L!==void 0&&n.calls?.answered(L)};try{_=await s.insertFile(r,g.body.objectApiName,P)}catch(N){Mo(N)!=="may-have-written"&&k(),w(g,"insert",U(N));continue}if(!_.success||!_.id){k(),w(g,"insert",_.errors.join("; ")||"The target gave no reason.");continue}if(u(g.objectApiName).copied++,g.body.objectApiName==="Attachment"){o.add(g.sourceId,_.id,"Attachment"),k(),o.persist?.(),l?.(g,{targetId:_.id,linked:T?[T]:[],asVersion:!1});continue}if(R){o.add(g.sourceId,R.documentId,"ContentDocument"),k(),o.persist?.();let N=await b(g,R.documentId,j);l?.(g,{targetId:R.documentId,linked:N,asVersion:!0});continue}o.add(g.sourceId,_.id,"ContentVersion"),k(),o.persist?.();let O;try{let N=await s.queryRecords(r,`SELECT ContentDocumentId FROM ContentVersion WHERE Id = '${Ue(_.id)}'`);O=N[0]?Q(N[0],"ContentDocumentId"):void 0}catch{O=void 0}if(!O){h("ContentDocument","query",`${g.name} (${Ne(g.bytes)})`,`Copied as ContentVersion ${_.id}, but its document could not be read back: the run keeps the version, which a removal of the run takes with its document, and links it to no other record.`,!0);continue}o.add(g.sourceId,O,"ContentDocument"),o.persist?.();let A=await b(g,O,y.slice(1));l?.(g,{targetId:O,linked:T?[T,...A]:A,asVersion:!1})}for(let g of i.objects)c({objectName:g.objectApiName,status:g.failed>0&&g.copied===0?"error":"done",progress:100,message:`Copied ${g.copied} ${jn(g.objectApiName,g.copied)} of ${g.planned}`+(g.failed>0?`, ${g.failed} failed`:"")});return p}var js=new WeakMap;function Lf(n,e){typeof n=="object"&&n!==null&&js.set(n,e)}function Bf(n){return typeof n=="object"&&n!==null?js.get(n):void 0}import{createHash as xs,randomBytes as Ms}from"node:crypto";import{createReadStream as ec}from"node:fs";import{chmod as tc,copyFile as nc,open as rc,readFile as _s,readdir as Ds,rename as Ut,rm as $e,stat as Ls}from"node:fs/promises";import{join as he}from"node:path";import{createHash as Ya}from"node:crypto";function ce(n){return n.slice(0,15)}function Be(n,e){let t=ce(n),r=ce(e);return t<r?-1:t>r?1:0}var Za=2**21,Qa=2**53;function qf(n,e){let t=Ya("sha256").update(`${n}:${ce(e)}`).digest(),r=t.readUInt32BE(0),o=t.readUInt32BE(4)>>>11;return(r*Za+o)/Qa}function Uf(n,e){return n/Math.max(e,n+1)}var Xa=1024;function Cs(n,e){let t=Math.floor(Math.max(0,n)/Xa);return Math.max(1,Math.min(t,e??1/0))}function zt(n,e){return n.rank!==e.rank?n.rank<e.rank?-1:1:n.objectApiName!==e.objectApiName?n.objectApiName<e.objectApiName?-1:1:Be(n.id,e.id)}var qt=class{items=[];get size(){return this.items.length}peek(){return this.items[0]}push(e){let t=this.items;t.push(e);let r=t.length-1;for(;r>0;){let o=r-1>>1;if(zt(t[r],t[o])<=0)break;[t[r],t[o]]=[t[o],t[r]],r=o}}pop(){let e=this.items,t=e[0],r=e.pop();if(e.length===0||r===void 0)return t;e[0]=r;let o=0;for(;;){let s=2*o+1,i=s+1,a=o;if(s<e.length&&zt(e[s],e[a])>0&&(a=s),i<e.length&&zt(e[i],e[a])>0&&(a=i),a===o)break;[e[o],e[a]]=[e[a],e[o]],o=a}return t}values(){return this.items}};function Le(n){return`${n.objectApiName}
|
|
12
|
+
${ce(n.id)}`}var Ns=class{constructor(e,t){this.most=e;this.floor=t}most;floor;kept=new qt;floors=new Map;inKept=new Set;inFloor=new Set;letGo=1/0;offer(e,t,r){let o={objectApiName:e,id:t,rank:r},s=[];if(this.floor>0){let i=this.floors.get(e);if(i||(i=new qt,this.floors.set(e,i)),i.push(o),this.inFloor.add(Le(o)),i.size>this.floor){let a=i.pop();a&&(this.inFloor.delete(Le(a)),s.push(a))}}if(this.most>0){if(this.kept.push(o),this.inKept.add(Le(o)),this.kept.size>this.most){let i=this.kept.pop();i&&(this.inKept.delete(Le(i)),s.push(i))}}else s.push(o);for(let i of s){let a=Le(i);!this.inKept.has(a)&&!this.inFloor.has(a)&&(this.letGo=Math.min(this.letGo,i.rank))}}keeps(e,t){if(this.floor>0&&(this.floors.get(e)?.size??0)<this.floor||this.kept.size<this.most)return!0;let r=this.kept.peek();return r!==void 0&&t<r.rank}leftUnread(e){this.letGo=Math.min(this.letGo,e)}get beyond(){return this.letGo}drawn(){let e=new Map;for(let t of this.kept.values())e.set(Le(t),t);for(let t of this.floors.values())for(let r of t.values())e.set(Le(r),{...r,rank:0});return[...e.values()].sort(zt)}};var Bs=1440*6e4,oc="forge-samples",$s="forge-runs",Nn="sample.json",Ps="the run of this sample",sc=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,zs=/^[A-Za-z0-9_-]{1,128}$/,ue=class extends Error{constructor(t,r){super(r);this.refusal=t;this.name="SamplePlanError"}refusal};function Pn(n){return he(n,oc)}function ic(n,e){if(!zs.test(e))throw new ue("otherSetup","Not the fingerprint of a setup of a run.");return he(Pn(n),e)}function pt(n,e){return he(n,$s,`${e.replace(/[^A-Za-z0-9_-]/g,"_")}.sample`)}var oe=q().regex(/^[A-Za-z][A-Za-z0-9_]*$/),ee=H().int().nonnegative(),ac=z({seed:H().int().min(0),draw:Er,floor:ee,parents:jr,children:Ar([xe("all"),H().int().min(1)]),share:H().min(0).max(1),budget:z({bytes:H().nonnegative(),remainingMB:H().optional(),maxMB:H().optional(),share:H().optional(),roundingMB:H().optional(),automationMB:H().optional(),withinMB:H().optional(),maxTotal:H().optional(),limitedBy:ve(["storage","within","maxTotal","targetRequests","bulkBatches","sourceRequests","heavyRoots","whole"])}),rows:ee,storageBytes:H().nonnegative(),objects:J(z({objectApiName:oe,sourceRows:ee,kept:ee,roots:ee,below:ee,asParents:ee,whole:xe(!0).optional(),childrenCut:J(z({field:q(),rows:ee})).optional()})),whole:J(z({objectApiName:oe,why:ve(["referenceData","catalog","smallParent","asked"])})),heavyRoots:J(z({objectApiName:oe,id:q().regex(sc),rows:ee,relation:z({objectApiName:oe,field:q()})})),dropped:J(z({objectApiName:oe,rows:ee,reason:ve(["noParentInSource","outsideFilter","excludedObject","withoutParent","heldBack","recordTypeNotInTarget"])})),leftEmpty:J(z({objectApiName:oe,field:q(),rows:ee})),noRecordDrawn:J(z({objectApiName:oe,sourceRows:ee})),partialMasters:J(z({objectApiName:oe,details:oe,field:q(),kept:ee.optional(),sourceRows:ee.optional(),asParents:ee.optional()})).optional(),planRequests:z({source:ee}),newestByIds:J(oe).optional()}),cc=z({personAccounts:rt(oe,ee),byThePlatform:J(z({objectApiName:oe,inPlan:ee,beyond:ee}))}),Cn=z({version:xe(1),sourceOrgId:q().min(1),fingerprint:q().regex(zs),drawnAt:kr.datetime(),drawnBy:ve(["run","dryRun"]),sha256:q().regex(/^[0-9a-f]{64}$/),objects:J(z({objectApiName:oe,count:H().int().positive(),sha256:q().regex(/^[0-9a-f]{64}$/)})),sample:ac,newestByIds:J(oe).optional(),counts:cc.optional()});async function Ts(n){let e=xs("sha256");for await(let t of ec(n))e.update(t);return e.digest("hex")}function Fs(n){let e=xs("sha256"),t=[...n].sort((r,o)=>r.objectApiName<o.objectApiName?-1:r.objectApiName>o.objectApiName?1:0);for(let{objectApiName:r,count:o,sha256:s}of t)e.update(`${r} ${o} ${s}
|
|
13
|
+
`);return e.digest("hex")}async function dc(n,e){let t=await rc(n,"wx",at);try{await t.writeFile(e,"utf8"),await t.sync()}finally{await t.close()}}function Tn(n){let e=n?.code;return e==="ENOENT"||e==="ENOTDIR"}var Ke=class n{constructor(e,t,r){this.dir=e;this.manifest=t;this.spool=r}dir;manifest;spool;get sha256(){return this.manifest.sha256}get count(){return this.spool.count}countOf(e){return this.manifest.objects.find(t=>t.objectApiName===e)?.count??0}ageMs(e){return e.getTime()-Date.parse(this.manifest.drawnAt)}get place(){return{path:this.dir,sha256:this.manifest.sha256,drawnAt:this.manifest.drawnAt,drawnBy:this.manifest.drawnBy}}async*ids(e,t={}){let r=Math.max(1,Math.floor(t.size??2e3)),o=t.after,s=[];for await(let i of this.spool.pages(e,r))for(let a of i)o!==void 0&&Be(a,o)<=0||(s.push(a),s.length>=r&&(yield s,s=[]));s.length>0&&(yield s)}static async open(e,t={}){let r;try{r=JSON.parse(await _s(he(e,Nn),"utf8"))}catch(a){throw Tn(a)?new ue("gone","The plan of this sample is no longer on this machine."):new ue("changed","The plan of this sample does not read as one.")}let o=Cn.safeParse(r);if(!o.success)throw new ue("changed","The plan of this sample does not read as one.");let s=o.data,i;try{i=await es.open(e,Ps)}catch{throw new ue("changed","The ids of this sample are not as they were written.")}if(await n.holdToManifest(e,s,i),t.sourceOrgId!==void 0&&t.sourceOrgId!==s.sourceOrgId)throw new ue("otherOrg","This plan was drawn of another org.");if(t.fingerprint!==void 0&&t.fingerprint!==s.fingerprint)throw new ue("otherSetup","This plan was drawn for another setup of the run.");if(t.sha256!==void 0&&t.sha256!==s.sha256)throw new ue("otherSha","This is not the plan the run was drawn with.");return new n(e,s,i)}static async holdToManifest(e,t,r){let o=()=>new ue("changed","The ids of this sample are not as they were written."),s=r.objects.filter(i=>i.count>0);if(s.length!==t.objects.length)throw o();for(let i of t.objects){let a=s.find(l=>l.objectApiName===i.objectApiName);if(!a||a.count!==i.count)throw o();let c;try{c=await Ts(ct(e,i.objectApiName))}catch{throw o()}if(c!==i.sha256)throw o()}if(Fs(t.objects)!==t.sha256)throw o()}static async keep(e,t){let r=`${e}.${process.pid}-${Ms(4).toString("hex")}.tmp`;try{await Me(r);let o=new Xo(r,Ps);for(let{objectApiName:c,ids:l}of t.ids){let p=[...l].sort(Be);for(let u of p)await o.add(c,u)}let s=await o.finish(),i=[];for(let{objectApiName:c,count:l}of s.objects)l!==0&&i.push({objectApiName:c,count:l,sha256:await Ts(ct(r,c))});let a={version:1,sourceOrgId:t.sourceOrgId,fingerprint:t.fingerprint,drawnAt:t.drawnAt.toISOString(),drawnBy:t.drawnBy,sha256:Fs(i),objects:i,sample:t.sample,...t.newestByIds!==void 0&&t.newestByIds.length>0?{newestByIds:[...t.newestByIds]}:{},...t.counts?{counts:t.counts}:{}};Cn.parse(a),await dc(he(r,Nn),`${JSON.stringify(a)}
|
|
14
|
+
`),await $e(e,{recursive:!0,force:!0}),await Ut(r,e)}catch(o){throw await $e(r,{recursive:!0,force:!0}),o}return n.open(e)}};function Xf(n,e){return Ke.keep(n,e)}async function ep(n,e,t){let r;try{r=await Ke.open(ic(n,e),{fingerprint:e})}catch(o){if(o instanceof ue)return;throw o}return r.ageMs(t)>=Bs?"tooOld":r}async function tp(n,e,t){let r=pt(e,t);return await Me(he(e,$s)),await $e(r,{recursive:!0,force:!0}),await Ut(n.dir,r),Ke.open(r,{sha256:n.sha256})}async function np(n,e,t){let r=pt(n,e);return!await vs(r)||await vs(t)?!1:(await Me(Pn(n)),await Ut(r,t),!0)}async function rp(n,e,t){let r=pt(e,t),o=`${r}.${process.pid}-${Ms(4).toString("hex")}.tmp`;try{await Me(o);for(let s of await Ds(n.dir))await nc(he(n.dir,s),he(o,s)),await tc(he(o,s),at);await $e(r,{recursive:!0,force:!0}),await Ut(o,r)}catch(s){throw await $e(o,{recursive:!0,force:!0}),s}return Ke.open(r,{sha256:n.sha256})}async function vs(n){try{return await Ls(n),!0}catch(e){if(Tn(e))return!1;throw e}}async function op(n){await $e(n,{recursive:!0,force:!0})}async function sp(n,e){let t=Pn(n),r;try{r=await Ds(t)}catch(s){if(Tn(s))return 0;throw s}let o=0;for(let s of r){let i=he(t,s),a;try{let c=Cn.parse(JSON.parse(await _s(he(i,Nn),"utf8")));a=Date.parse(c.drawnAt)}catch{a=(await Ls(i)).mtimeMs}e.getTime()-a<Bs||(await $e(i,{recursive:!0,force:!0}),o++)}return o}var Fn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,qs=/^[A-Za-z][A-Za-z0-9_]*$/;function gt(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"||!Fn.test(r))&&!(typeof o!="string"||!Fn.test(o)))return{tag:t,sourceId:r,targetId:o,object:typeof s=="string"&&qs.test(s)?s:""}}function Ye(n){if(!n.startsWith(`["${_t}"`))return;let e;try{e=JSON.parse(n)}catch{return}if(!Array.isArray(e))return;let[,t,r]=e;if(!(typeof t!="string"||!qs.test(t)||!Array.isArray(r)))return{object:t,ids:r.filter(o=>typeof o=="string"&&Fn.test(o))}}function mt(n){return n.slice(0,15)}var ht=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]}},Ie=class{capacity=1024;used=0;h1=new Uint32Array(this.capacity);h2=new Uint32Array(this.capacity);taken=new Uint8Array(this.capacity);add(e){let t=de(e),r=le(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(de(e),le(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}}},lc=2e3,wt=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=(p,u)=>gt(e.read(p,u).toString("utf8"))?.sourceId??"",o=new Dt(r),s=new Dt(r),i=new ht,a=new ht,c=!1,l=-1;for(let p of Oe(e)){if(!c){if(!p.text.startsWith('{"run":'))return;c=!0;continue}if(p.text.startsWith('{"part":')){l++;continue}if(p.text.startsWith('{"object":'))return;if(l===t&&Ye(p.text)){a.push(p.offset,p.length);continue}let u=gt(p.text);if(!u)continue;let f=de(u.sourceId),d=le(u.sourceId);if(o.put(o.find(u.sourceId,f,d),f,d,p.offset,p.length,0),l!==t)continue;let m=s.find(u.sourceId,f,d);m<0&&i.push(p.offset,p.length);let h=u.tag==="c"&&u.object!=="";s.put(m,f,d,p.offset,p.length,h?1:0)}return c?new n(e,o,s,i,a):void 0}mappingAt(e,t){return gt(this.file.read(e,t).toString("utf8"))}wordsOn(e){let t=de(e),r=le(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 ht;i.push(o.latest.offset,o.latest.length),e.set(s.object,i)}return e}runRecords(e,t=lc){let{file:r}=this,o=(h,w)=>gt(r.read(h,w).toString("utf8")),s=(h,w)=>{let b=o(h,w);return b?mt(b.targetId):""},i=new Dt(s),a=this.createdByObject(),c=[];for(let h of[...a.keys()].reverse()){let w=a.get(h);if(!w)continue;let b=0;for(let S=w.size-1;S>=0;S--){let I=w.offsetAt(S),g=o(I,w.lengthAt(S));if(!g||g.object==="")continue;let y=mt(g.targetId),R=de(y),j=le(y),v=i.find(y,R,j);v>=0||(i.put(v,R,j,I,w.lengthAt(S),0),(!e||e.has(y))&&b++)}b>0&&c.push({objectApiName:h,count:b})}let l=(h,w)=>{let b=i.find(h,de(h),le(h),w);return b>=0&&(w===void 0||i.offsetOf(b)===w)&&(!e||e.has(h))},p=h=>Ye(r.read(this.unattributed.offsetAt(h),this.unattributed.lengthAt(h)).toString("utf8")),u=new Ie,f=this.unattributed.size,d=new Map;for(let h=0;h<f;h++){let w=p(h);if(w)for(let b of w.ids){let S=mt(b);u.has(S)||i.find(S,de(S),le(S))>=0||(u.add(S),(!e||e.has(S))&&d.set(w.object,(d.get(w.object)??0)+1))}}for(let[h,w]of d){let b=c.find(S=>S.objectApiName===h);b?b.count+=w:c.unshift({objectApiName:h,count:w})}let m=h=>u.size>0&&u.has(h)&&(!e||e.has(h));return{objects:c,pages:async function*(h){let w=a.get(h),b=[];if(w)for(let S=w.size-1;S>=0;S--){let I=w.offsetAt(S),g=o(I,w.lengthAt(S));if(!g||g.object==="")continue;let y=mt(g.targetId);l(y,I)&&(b.push(g.targetId),b.length>=t&&(yield b,b=[]))}if(d.has(h)){let S=new Ie;for(let I=0;I<f;I++){let g=p(I);if(g?.object===h)for(let y of g.ids){let R=mt(y);S.has(R)||!m(R)||i.find(R,de(R),le(R))>=0||(S.add(R),b.push(y),b.length>=t&&(yield b,b=[]))}}}b.length>0&&(yield b)},has:h=>l(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 Oe(this.file)){let o=gt(r.text);if(!o)continue;let s=this.all.find(o.sourceId,de(o.sourceId),le(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 Te=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,bt=/^[A-Za-z][A-Za-z0-9_]*$/,uc=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/,fc=255,pc=40,gc=2*6e4,mc=10*6e4;function wp(n){let[e]=n;return e?Object.keys(e).filter(t=>t!=="Id"&&bt.test(t)).filter(t=>n.every(r=>hc(r[t]))).sort().slice(0,pc):[]}function hc(n){return typeof n=="string"?n.trim()!==""&&n.length<=fc:typeof n=="number"?Number.isFinite(n):typeof n=="boolean"}function wc(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(Te.test(e))return e.slice(0,15);if(uc.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 xn(n,e){return Mn(e.map(t=>`${t}${wc(n[t])}`).join(""))}function Mn(n){return de(n).toString(36).padStart(7,"0")+le(n).toString(36).padStart(7,"0")}function bp(n){let e=ko("insert",n);return e.rows.map(t=>Mn(wn(e.columns.map((r,o)=>[r,t[o]??""]))))}var bc=/^sf__/;function Us(n){let e=[];for(let[t,r]of Object.entries(n))bc.test(t)||e.push([t,typeof r=="string"?r:r==null?"":String(r)]);return Mn(wn(e))}function Gs(n,e){return xn(n,[e])}function yc(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"||!bt.test(o)||typeof s!="string"||!Te.test(s))return!1;e[r].owes.push({field:o,sourceRefId:s,...i===1?{insertOnly:!0}:{}})}return!0}function vn(n){if(!n.startsWith(`["${Mt}"`))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,c]=e;if(typeof t!="string"||typeof r!="string"||!bt.test(r)||typeof o!="string")return;let l=Date.parse(o);if(!Number.isFinite(l)||!Array.isArray(s)||!Array.isArray(i)||!s.every(f=>typeof f=="string"&&bt.test(f))||c!==void 0&&(typeof c!="string"||!bt.test(c)))return;let p=[];for(let f of i){if(!Array.isArray(f)||f.length<2)return;let[d,m,h,w]=f;if(typeof d!="string"||!Te.test(d)||typeof m!="string"||h!==void 0&&typeof h!="string"||w!==void 0&&typeof w!="string")return;p.push({sourceId:d,fingerprint:m,owes:[],...typeof h=="string"&&h!==""?{externalKey:h}:{},...typeof w=="string"&&w!==""?{jobKey:w}:{}})}let u=a!==void 0;if(!(u&&!yc(a,p)))return{callId:t,objectApiName:r,at:l,fields:s,rows:p,owesKept:u,...typeof c=="string"?{upsertField:c}:{}}}function Vs(n){if(n.startsWith(`["${_e}"`))try{let e=JSON.parse(n);return Array.isArray(e)&&typeof e[1]=="string"?e[1]:void 0}catch{return}}function Rc(n){if(n.startsWith(`["${Wo}"`))try{let e=JSON.parse(n);return Array.isArray(e)&&typeof e[1]=="string"?e[1]:void 0}catch{return}}function Sc(n){if(n.startsWith(`["${Uo}"`))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 Oc(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"||!Te.test(t)||!Te.test(r)?void 0:{sourceId:t,targetId:r,object:typeof o=="string"?o:""}}catch{return}}function Ac(n){let e=/"(?:startedAt|at)":"([^"]{10,40})"/.exec(n);return e?Date.parse(e[1]):Number.NaN}function yp(n){return{queryPages:e=>mo({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=>Eo(jo(n),e)}}function Ic(){return{calls:0,found:[],notFound:[],uncertain:[],unread:[]}}function Z(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 Ws(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function _n(n,e,t){return[JSON.stringify(["c",e.sourceId,t,n.objectApiName,n.owesKept?Jo:Vo]),...e.owes.map(({field:r,sourceRefId:o,insertOnly:s})=>Yo({objectApiName:n.objectApiName,newId:t,sourceId:e.sourceId,fieldName:r,sourceRefId:o,...s?{insertOnly:s}:{}}))]}function kc(n,e,t,r){let{call:o,rows:s,read:i}=n,{objectApiName:a}=o,c=JSON.stringify([_e,o.callId]);if(i.state==="never-closed")return Z(r.notFound,a,s.length),{lines:[c],taken:[]};if(i.state==="running")return Z(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}),Z(r.uncertain,a,s.length),{lines:[],taken:[]};let l=o.upsertField===void 0&&s.every(u=>u.jobKey!==void 0)?Ec(o,s,i.results,e,t,r):jc(o,s,i.results,e,t,r),p=Date.parse(i.info.systemModstamp??"");return!n.endKept&&l.taken.length>0&&Number.isFinite(p)&&l.lines.unshift(Ho(o.callId,n.jobId,new Date(p).toISOString(),new Date(p-n.ahead).toISOString())),l}function Ec(n,e,t,r,o,s){let{objectApiName:i}=n,a=new Map,c=new Set;for(let I of t.successfulResults??[]){let g=I.sf__Id,y=Us(I);if(typeof g!="string"||!Te.test(g)){c.add(y);continue}let R=g.slice(0,15);r.has(R)&&!o.has(R)||a.set(y,[...a.get(y)??[],g])}let l=new Set,p=t.unprocessedRecords;for(let I of[...t.failedResults??[],...Array.isArray(p)?p:[]])l.add(Us(I));let u=new Map;for(let I of e){let g=I.jobKey??"";u.set(g,[...u.get(g)??[],I])}let f=[],d=[],m=[],h=0,w=!1,b=0;for(let[I,g]of u){let y=a.get(I)??[];a.delete(I);let R=c.delete(I);if(g.length===1&&y.length===1&&!R){f.push(..._n(n,g[0],y[0])),d.push(y[0]),Z(s.found,i);continue}if(y.length>0||R){Z(s.uncertain,i,g.length),g.length>1&&Z(s.untold??=[],i,g.length),R||(b+=g.length),m.push(...y),w=!0;continue}if(g.length>1||l.has(I)){Z(s.notFound,i,g.length);continue}h+=g.length}let S=c.size>0;for(let I of a.values())m.push(...I),I.length>0&&(S=!0);return h>0&&(Z(S?s.uncertain:s.notFound,i,h),S&&(w=!0,c.size===0&&(b+=h))),b>0&&Z(s.ofEndedJobs??=[],i,b),f.push(...Js(n,m,o,w,s)),{lines:f,taken:[...d,...m]}}function Js(n,e,t,r,o){e.length>0&&Z(o.unattributed??=[],n.objectApiName,e.length);let s=e.filter(i=>!t.has(i.slice(0,15)));return[...s.length>0?[JSON.stringify([_t,n.objectApiName,s])]:[],...r?[]:[JSON.stringify([_e,n.callId])]]}function jc(n,e,t,r,o,s){let{objectApiName:i}=n,a=n.upsertField,c=new Map;for(let w of t.successfulResults??[]){let b=w.sf__Id;if(typeof b!="string"||!Te.test(b))continue;let S=b.slice(0,15);if(r.has(S)&&!o.has(S)||a!==void 0&&String(w.sf__Created).toLowerCase()!=="true")continue;let I=a!==void 0?Gs(w,a):xn(w,n.fields);c.set(I,[...c.get(I)??[],b])}let l=new Map;for(let w of e){let b=a!==void 0?w.externalKey??"":w.fingerprint;l.set(b,[...l.get(b)??[],w])}let p=[],u=[],f=[],d=0,m=!1;for(let[w,b]of l){let S=w===""?[]:c.get(w)??[];if(c.delete(w),S.length===0){d+=b.length;continue}if(b.length===1&&S.length===1){p.push(..._n(n,b[0],S[0])),u.push(S[0]),Z(s.found,i);continue}Z(s.uncertain,i,b.length),Z(s.ofEndedJobs??=[],i,b.length),b.length>1&&Z(s.untold??=[],i,b.length),f.push(...S),m=!0}let h=!1;for(let w of c.values())f.push(...w),w.length>0&&(h=!0);return d>0&&(Z(h?s.uncertain:s.notFound,i,d),h&&(m=!0,Z(s.ofEndedJobs??=[],i,d))),p.push(...Js(n,f,o,m,s)),{lines:p,taken:[...u,...f]}}function Hs(n){let e=new Set;for(let t of Oe(n)){let r=Vs(t.text);if(r!==void 0)e.delete(r);else{let o=t.text.startsWith(`["${Mt}"`)?vn(t.text):void 0;o&&e.add(o.callId)}}return e.size}async function Ks(n,e,t=()=>new Date){let r=Ic(),o=new Map,s=new Map,i=new Set,a=Number.NEGATIVE_INFINITY;for(let g of Oe(n)){let y=Vs(g.text);if(y!==void 0){o.delete(y);continue}let R=Sc(g.text);if(R){s.set(R.callId,R.jobId);continue}let j=Rc(g.text);if(j!==void 0){i.add(j);continue}if(g.text.startsWith(`["${Mt}"`)){let v=vn(g.text);v&&(o.set(v.callId,{offset:g.offset,length:g.length}),a=Math.max(a,v.at));continue}if(g.text.startsWith("{")){let v=Ac(g.text);Number.isFinite(v)&&(a=Math.max(a,v))}}if(o.size===0)return r;let c=[];for(let{offset:g,length:y}of o.values()){let R=vn(n.read(g,y).toString("utf8"));R&&c.push(R)}r.calls=c.length;let l=new Set(c.map(g=>g.objectApiName)),p=new Set(c.flatMap(g=>g.rows.map(y=>y.sourceId)));r.lookedFor=p;let u=new Set,f=new Ie,d=new Ie;for(let g of Oe(n)){let y=Ye(g.text);if(y){if(l.has(y.object))for(let j of y.ids)f.add(j.slice(0,15)),d.add(j.slice(0,15));continue}let R=Oc(g.text);R&&(p.has(R.sourceId)&&u.add(R.sourceId),(R.object===""||l.has(R.object))&&f.add(R.targetId.slice(0,15)))}let m=0;if(e.serverTime)try{let g=t().getTime(),y=Date.parse(await e.serverTime());Number.isFinite(y)&&(m=y-(g+t().getTime())/2)}catch{}let h,w,b=[],S=e.readJob?.bind(e),I=new Set;if(S)for(let g of c){let y=s.get(g.callId);if(y===void 0)continue;I.add(g.callId);let R=g.rows.filter(v=>!u.has(v.sourceId));if(R.length===0){b.push(JSON.stringify([_e,g.callId]));continue}let j=kc({call:g,rows:R,jobId:y,read:await S(y),ahead:m,endKept:i.has(g.callId)},f,d,r);b.push(...j.lines);for(let v of j.taken)f.add(v.slice(0,15))}for(let g of l){let y=c.filter(A=>A.objectApiName===g&&!I.has(A.callId));if(y.length===0)continue;let R=y.map(A=>({call:A,rows:A.rows.filter(N=>!u.has(N.sourceId))})),j=R.reduce((A,{rows:N})=>A+N.length,0);if(j===0){for(let{call:A}of R)b.push(JSON.stringify([_e,A.callId]));continue}let v=new Map;for(let A of y)v.set(A.fields.join(","),A.fields);let T=[...new Set(y.flatMap(A=>A.upsertField?[A.upsertField]:[]))],C=[...new Set([...y.flatMap(A=>A.fields),...T])].sort(),M;try{if(h===void 0&&w===void 0)try{h=await e.userId()}catch(x){w=U(x)}if(h===void 0)throw new Error(`the user the run writes as is not known: ${w}`);let A=Math.min(...y.map(x=>x.at))+m-gc,N=a+m+mc,D=C.includes("CreatedDate")?"SystemModstamp":"CreatedDate",$=C.includes("CreatedById")?"":`CreatedById = '${h}' AND `,E=`SELECT ${["Id",...C.filter(x=>x!=="Id")].join(", ")} FROM ${V(g)} WHERE ${$}${D} >= ${Ws(A)} AND ${D} <= ${Ws(N)} ORDER BY Id`;M=[];for await(let x of e.queryPages(E))for(let F of x){let B=F.Id;if(typeof B!="string"||!Te.test(B)||f.has(B.slice(0,15)))continue;let W=new Map;for(let[te,ze]of v)W.set(te,xn(F,ze));let X=new Map;for(let te of T)X.set(te,Gs(F,te));M.push({id:B,fingerprints:W,externalKeys:X,taken:!1})}}catch(A){r.unread.push({objectApiName:g,reason:U(A)}),Z(r.uncertain,g,j);continue}M.sort((A,N)=>A.id<N.id?-1:A.id>N.id?1:0);let P=new Map;for(let A of v.keys()){let N=new Map;for(let D of M){let $=D.fingerprints.get(A)??"",E=N.get($)??[];E.push(D),N.set($,E)}P.set(A,N)}let _=(A,N,D)=>{D.taken=!0,b.push(..._n(A,N,D.id)),Z(r.found,g)},L=new Set;for(let{call:A,rows:N}of R){let D=A.upsertField;if(D===void 0)continue;let $=new Map;for(let x of M){let F=x.externalKeys.get(D);x.taken||F===void 0||$.set(F,[...$.get(F)??[],x])}let E=new Map;for(let x of N){let F=x.externalKey??"";E.set(F,[...E.get(F)??[],x])}for(let[x,F]of E){let B=x===""?[]:$.get(x)??[];if(x===""||F.length>1||B.length>1){Z(r.uncertain,g,F.length),L.add(A.callId);continue}B.length===1?_(A,F[0],B[0]):Z(r.notFound,g)}}let k=[];for(let{call:A,rows:N}of R){if(A.upsertField!==void 0)continue;let D=A.fields.join(","),$=new Map;for(let E of N){let x=$.get(E.fingerprint)??[];x.push(E),$.set(E.fingerprint,x)}for(let[E,x]of $){let F=(P.get(D)?.get(E)??[]).filter(B=>!B.taken);if(F.length>x.length){for(let B of x)k.push({callId:A.callId,sourceId:B.sourceId});L.add(A.callId);continue}F.forEach((B,W)=>_(A,x[W],B));for(let B of x.slice(F.length))k.push({callId:A.callId,sourceId:B.sourceId})}}let O=M.some(A=>!A.taken);for(let A of k)O||L.has(A.callId)?(Z(r.uncertain,g),L.add(A.callId)):Z(r.notFound,g);for(let{call:A}of R)L.has(A.callId)||b.push(JSON.stringify([_e,A.callId]))}return b.length>0&&n.append(`${b.join(`
|
|
15
|
+
`)}
|
|
16
|
+
`),r}function Rp(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(` ${Cc(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 Nc(n){return Math.max(1,Math.ceil(n/6e4))}function Cc(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 ${Nc(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 Pc(n){return n.uncertain.reduce((e,{rows:t})=>e+t,0)}function Sp(n){let e=(n.ofEndedJobs??[]).reduce((t,{rows:r})=>t+r,0);return Math.max(0,Pc(n)-e)}import{createReadStream as Tc}from"node:fs";import{appendFile as Fc,mkdir as vc,readdir as xc,rename as Mc,rm as Ys}from"node:fs/promises";import*as fe from"node:path";import{createInterface as _c}from"node:readline";var Dc=10*6e4;function Fp(n){return new $n({storagePath:n,appendFile:(e,t)=>Fc(e,t,"utf8"),readLines:e=>Lc(e),mkdir:async e=>{await vc(e,{recursive:!0})},rm:e=>Ys(e,{force:!0}),rename:(e,t)=>Mc(e,t),listFiles:e=>xc(e).catch(t=>{if(t.code==="ENOENT")return[];throw t}),openRunFile:e=>qo(e),rmDir:e=>Ys(e,{recursive:!0,force:!0})})}async function*Lc(n){let e=Tc(n,{encoding:"utf8"}),t=_c({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 vp=5e4,xp=2e3,re=q().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),Jt=q().regex(/^[A-Za-z][A-Za-z0-9_]*$/),Bc=z({sourceOrgId:q().min(1).max(128),fingerprint:q().regex(/^[a-f0-9]{64}$/),targetSalesforceOrgId:re.optional(),recordId:re.optional(),muteAutomation:xe(!0).optional(),files:Fr.optional()}),$c=z({graph:Pr,config:Nr,anonymizationRules:Tr.optional()});function Zs(n){let e=Bc.safeParse(n);if(!e.success)return;let t=$c.safeParse(n.startedWith);return{...e.data,...t.success?{startedWith:t.data}:{}}}var Wt=z({run:z({journalId:q().min(1).max(200),targetOrgId:q().min(1).max(128),startedAt:q().min(1).max(40),resume:Re().optional(),runUserId:Re().optional()})}),Qs=z({objectApiName:q().regex(/^[A-Za-z][A-Za-z0-9_]*$/),reason:q().max(2e3),...vr}),Xs=z({checkpoint:z({state:xe("taken"),checkpointId:q().min(1).max(200),name:q().max(500),takenAt:q().min(1).max(40),expiresAt:q().min(1).max(40).nullable(),objects:J(q().regex(/^[A-Za-z][A-Za-z0-9_]*$/)),records:H().nonnegative(),bytes:H().nonnegative(),requests:H().nonnegative(),added:J(Qs),notHeld:J(Qs)})}),zc=z({part:z({n:H().int().nonnegative(),startedAt:q().max(40).optional()})}),Dn=z({end:z({status:ve(["success","cancelled","failure","interrupted"]),forgeId:q().min(1).max(200),at:q().max(40).optional()})}),qc=z({object:Jt,created:J(Ir([re,re]))});function Ln(n){return re.safeParse(n).success?n:void 0}function Ze(n){return n.replace(/\.ndjson$/,"")+".end.json"}function Gt(n){return n.replace(/\.ndjson$/,"")+".checkpoint.json"}function Vt(n,e){return`${n.replace(/\.ndjson$/,"")}.part${e}.left`}function ei(n,e){return`${n.replace(/\.ndjson$/,"")}.part${e}.stamps`}var Uc=q().max(40).refine(n=>Number.isFinite(Date.parse(n)),"not a date"),Qe=1e4;function Wc(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(l=>!r.has(l.slice(0,15)));for(let l of a)r.add(l.slice(0,15));if(a.length===0)continue;let c=t.find(l=>l.objectApiName===s);c?c.ids.push(...a):o.push({objectApiName:s,ids:a})}return[...o,...t]}function Bn(n){return n.replace(/[^A-Za-z0-9_-]/g,"_")}var $n=class{constructor(e){this.deps=e;this.dir=fe.join(e.storagePath,"forge-runs")}deps;dir;get storagePath(){return this.deps.storagePath}pathOf(e){return fe.join(this.dir,`${Bn(e)}.ndjson`)}filePath(e){return this.pathOf(e)}async begin(e,t,r,o,s){await this.deps.mkdir(this.dir);let i=Ln(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)}
|
|
17
|
+
`)}async keepCheckpoint(e,t){let r=Xs.safeParse({checkpoint:t});if(!r.success)return;let o=Gt(this.filePath(e));await this.deps.rm(o),await this.deps.appendFile(o,`${JSON.stringify(r.data)}
|
|
18
|
+
`)}async checkpointAt(e){for await(let t of this.deps.readLines(Gt(e)))if(t.trim()!=="")try{let r=Xs.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 Zo.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 Ks(r,t)}finally{r.close()}}writeBoundsAt(e,t){let r=this.deps.openRunFile(e);try{let o,s,i,a,c=-1,l,p,u=Number.NEGATIVE_INFINITY,f=Number.NEGATIVE_INFINITY,d=Number.NEGATIVE_INFINITY,m=new Map;for(let w of Oe(r)){let b=/"(?:startedAt|at)":"([^"]{10,40})"/.exec(w.text)?.[1],S=w.text.startsWith('["x"')?/^\["x","[^"]*","[^"]*","([^"]+)"/.exec(w.text)?.[1]:void 0,I=Ko(w.text);for(let T of[b,S,I?.at]){let C=T===void 0?Number.NaN:Date.parse(T);Number.isFinite(C)&&(u=Math.max(u,C))}if(I){let T=Date.parse(I.orgAt);Number.isFinite(T)&&(f=Math.max(f,T),c===t&&(d=Math.max(d,T)));continue}if(w.text.startsWith('{"part":')&&c++,!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[y,R,j,v]=g;if(y==="c"){if(!re.safeParse(j).success||!Jt.safeParse(v).success)continue;let T={objectApiName:String(v),id:String(j)};o??=T,s=T,c===t&&(i??=T,a=T),m.set(String(j).slice(0,3),String(v))}else if(y==="g"){if(!re.safeParse(j).success||!Jt.safeParse(R).success)continue;l={objectApiName:String(R),id:String(j)},p=void 0}else re.safeParse(R).success&&(p=String(R))}let h=p?m.get(p.slice(0,3)):void 0;return p&&h&&(l={objectApiName:h,id:p}),{...o?{first:o}:{},...s?{lastCreated:s}:{},...i?{firstInPart:i}:{},...a?{lastCreatedInPart:a}:{},...l?{lastUpdated:l}:{},...Number.isFinite(u)?{lastAt:new Date(u).toISOString()}:{},...Number.isFinite(f)?{jobEnded:new Date(f).toISOString()}:{},...Number.isFinite(d)?{jobEndedInPart:new Date(d).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:c}=s,[l,p,u]=o==="part"?[i,a,void 0]:[s.first,s.lastCreated,s.lastUpdated];if(!l||!p)return;let f=async({objectApiName:S,id:I},g)=>{try{let R=(await t.query(`SELECT ${g} FROM ${V(S)} WHERE Id = '${I}'`)).records[0]?.[g],j=typeof R=="string"?Date.parse(R):Number.NaN;return Number.isFinite(j)?j:void 0}catch{return}},d=await f(l,"CreatedDate")??(i&&i.id!==l.id?await f(i,"CreatedDate"):void 0),m=[],h=a?.id!==p.id?a:void 0;for(let S of[p,h]){let I=S?await f(S,"CreatedDate"):void 0;I!==void 0&&m.push(I)}let w=m.length>0?Math.max(...m):void 0;if(d===void 0||w===void 0||w<d)return;if(u){let S=await f(u,"LastModifiedDate"),I=c===void 0?Number.NaN:Date.parse(c)+Dc;S!==void 0&&S>w&&(!Number.isFinite(I)||S<=I)&&(w=S)}let b=Date.parse((o==="part"?s.jobEndedInPart:s.jobEnded)??"");return Number.isFinite(b)&&b>w&&(w=b),{first:new Date(d).toISOString(),last:new Date(w).toISOString()}}callsInFlight(e){return this.callsInFlightAt(this.filePath(e))}callsInFlightAt(e){let t=this.deps.openRunFile(e);try{return Hs(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()}})}
|
|
19
|
+
`;await this.deps.appendFile(e,o),await this.deps.rm(Ze(e)),await this.deps.appendFile(Ze(e),o)}resuming(e){return this.resumingAt(this.filePath(e))}resumingAt(e){return this.deps.rm(Ze(e))}lastEnd(e){return this.lastEndAt(this.filePath(e))}async lastEndAt(e){for await(let t of this.deps.readLines(Ze(e)))if(t.trim()!=="")try{let r=Dn.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=Wt.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=Dn.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=Wt.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 c=a[0]==="p"?a[1]:a[2];re.safeParse(c).success&&r.add(String(c))}catch{}}return[...r]}async end(e){let t=this.filePath(e);await this.deps.rm(t),await this.deps.rm(Ze(t)),await this.deps.rm(Gt(t));let r=`${fe.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(fe.join(this.dir,o));await this.deps.rmDir?.(pt(this.deps.storagePath,e))}fileNameOf(e){return`${Bn(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=fe.join(this.dir,e),r=await this.headAt(t);r?await this.end(r.journalId):(await this.deps.rm(t),await this.deps.rm(Ze(t)),await this.deps.rm(Gt(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+=Qe)await this.deps.appendFile(o,`${r.slice(s,s+Qe).join(`
|
|
20
|
+
`)}
|
|
21
|
+
`);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=wt.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=wt.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(fe.basename(r)))return;let s=new Ie;for await(let i of this.deps.readLines(r)){let a=i.trim();re.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:c,ids:l}of r)if(l.length!==0){a.set(c,(a.get(c)??0)+l.length);for(let p=0;p<l.length;p+=Qe)await this.deps.appendFile(i,`${l.slice(p,p+Qe).join(`
|
|
22
|
+
`)}
|
|
23
|
+
`)}return s&&await s(i,o),[...a].map(([c,l])=>({objectApiName:c,count:l}))}async stampsOf(e,t){let r=ei(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(fe.basename(r)))return{};let s={};for await(let i of this.deps.readLines(r)){let[a,c]=i.trim().split(" ");re.safeParse(a).success&&Uc.safeParse(c).success&&(s[a]=c)}return s}async keepStamps(e,t,r){if(Object.keys(r).length===0)return;let o=ei(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 c=0;c<s.length;c+=Qe){let l=s.slice(c,c+Qe).map(([p,u])=>`${p} ${u}`);await this.deps.appendFile(a,`${l.join(`
|
|
24
|
+
`)}
|
|
25
|
+
`)}i&&await i(a,o)}async leftOf(e,t){let r=Vt(this.filePath(e),t);if(!(await this.deps.listFiles(this.dir)).includes(fe.basename(r)))return;let s=[];for await(let i of this.deps.readLines(r)){let a=i.trim();re.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=Wt.safeParse(r);if(!o.success)return;let{resume:s,runUserId:i,...a}=o.data.run,c=Zs(s),l=Ln(i);return{...a,...c?{resume:c}:{},...l?{runUserId:l}:{}}}}async read(e){let t=await this.deps.listFiles(this.dir),r=`${Bn(e)}.ndjson`;if(!t.includes(r))return;let o=await this.readAt(fe.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(fe.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=Wc(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,c=new Map,l=new Map,p=new Set,u=()=>{o++,i=s,s=void 0,t==="last"&&(c=new Map,l=new Map,p=new Set)},f=()=>typeof t!="number"||o-1===t;for await(let R of this.deps.readLines(e)){if(R.trim()==="")continue;let j;try{j=JSON.parse(R)}catch{continue}if(!r){let M=Wt.safeParse(j);if(!M.success)return;r=M.data.run;continue}if(Array.isArray(j)){let M=Ye(R);if(M){if(!f())continue;let O=l.get(M.object)??new Set;for(let A of M.ids)O.add(A);l.set(M.object,O);continue}let[P,_,L,k]=j;if(P===Go){f()&&re.safeParse(_).success&&p.add(String(_));continue}if(P!=="c"&&P!=="e"&&P!=="u"||!f()||!re.safeParse(_).success||!re.safeParse(L).success)continue;c.set(String(_),{targetId:String(L),object:typeof k=="string"&&Jt.safeParse(k).success?k:"",created:P==="c"});continue}let v=zc.safeParse(j);if(v.success){u(),a=v.data.part.startedAt;continue}let T=Dn.safeParse(j);if(T.success){s=T.data.end;continue}let C=qc.safeParse(j);if(C.success){if(o===0&&u(),!f())continue;for(let[M,P]of C.data.created)c.set(M,{targetId:P,object:C.data.object,created:!0})}}if(!r)return;let d=Zs(r.resume),m=Ln(r.runUserId),h=await this.checkpointAt(e),w={},b=new Map,S=[];for(let[R,{targetId:j,object:v,created:T}]of c){if(!v)continue;if(w[R]=j,!T){S.push(R);continue}let C=b.get(v)??[];C.push(R),b.set(v,C)}let I=[...b].map(([R,j])=>({objectApiName:R,sourceIds:j})),g=new Set([...c.values()].filter(({created:R})=>R).map(({targetId:R})=>R.slice(0,15))),y=[...l].map(([R,j])=>({objectApiName:R,ids:[...j].filter(v=>!g.has(v.slice(0,15)))})).filter(({ids:R})=>R.length>0);return{journalId:r.journalId,targetOrgId:r.targetOrgId,startedAt:r.startedAt,...d?{resume:d}:{},...m?{runUserId:m}:{},...h?{checkpoint:h}:{},parts:o,partStartedAt:a??r.startedAt,...s?{lastEnd:s}:{},...i?{endBefore:i}:{},created:_r({idRemapTable:w,idRemapExisting:S,idRemapCreated:I}),remap:{table:w,createdByObject:I,linked:S,...S.some(R=>p.has(R))?{withTheirRecord:S.filter(R=>p.has(R))}:{}},...y.length>0?{unattributed:y}:{}}}};import{createHash as Gc}from"node:crypto";function Vc(n,e){return ni(n,e,t=>t.included||Dr(t))}function Jc(n,e){if(n!==void 0)return{...Un(n),...e?{planSha256:e}:{}}}function Un(n){return{...n.withinMB!==void 0?{withinMB:n.withinMB}:{},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{},seed:n.seed??Ee.seed,draw:n.draw??Ee.draw,parents:n.parents??Ee.parents,children:n.children??Ee.children,floor:n.floor??Ee.floor,whole:[...new Set(n.whole??[])].sort()}}function zn(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function ti(n){if(!zn(n))return n;let e=typeof n.planSha256=="string"?n.planSha256:void 0;return Jc(n,e)}function Hc(n){if(!zn(n))return n;let e=n.config;return{...n,..."sample"in n?{sample:ti(n.sample)}:{},...zn(e)&&"sample"in e?{config:{...e,sample:ti(e.sample)}}:{}}}function Lp(n,e,t){return n===Vc(e,t)||n===ni(e,t,r=>r.included)}function ni(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 Gc("sha256").update(qn({nodes:r,edges:o,setup:Hc(e)})).digest("hex")}function qn(n){return Array.isArray(n)?`[${n.map(e=>qn(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)}:${qn(r)}`).join(",")}}`:JSON.stringify(n??null)}function Up(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:Un(n.sample)}:Object.values(e).some(t=>t.length>0)?e:void 0}var Gn=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},Kc="NOTHING_TO_CLONE";function Wp(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:Kc,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 Gp(n){return n instanceof Gn||n instanceof Error&&n.name==="WholeOrgDryRunStop"&&"dryRun"in n}function Wn(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 Vp(n){return{api:n.targetRequests,wholeOrg:{source:n.sourceRequests,...n.bulkBatches?{bulkBatches:n.bulkBatches}:{},cost:{durationSeconds:n.durationSeconds}}}}function Yc(n,e){let t=a=>a.reduce((c,l)=>c+l.rows,0),r=n.objects.reduce((a,c)=>a+c.sourceRows,0)+n.noRecordDrawn.reduce((a,c)=>a+c.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]}:{}}}function Jp(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,b)=>w+b[h],0),c=a("jobs"),l=[...s].filter(h=>so(h)!==void 0).sort(),p=os(e.graph.nodes,s,e.anonymizePII),u=n.files&&"check"in n.files?n.files:void 0,f=u?.check,d=t.contactPointsBlanked??0,m=o.wholeOrg.bulkBatches;return{source:e.source,leftOut:ss(e.graph).objects.length,...e.carried?{carried:e.carried}:{},...n.sample?{sample:Yc(n.sample,n.now??Date.now())}:{},targetApi:Wn(o.api),sourceApi:Wn(o.wholeOrg.source),...c>0?{bulk:{jobs:c,jobRows:a("jobRows"),restRows:a("restRows"),...m?{batches:Wn(m)}:{}}}:{},durationSeconds:o.wholeOrg.cost.durationSeconds,restObjects:i.filter(h=>h.jobs===0).map(h=>h.objectApiName),...u&&f&&f.verdict!=="unread"?{fileStorage:{files:u.count,estimateMB:f.estimateMB,overCeiling:t.files&&"overCeiling"in t.files?t.files.overCeiling:0,remainingMB:f.remainingMB,maxMB:f.maxMB,...f.verdict==="near"?{near:!0}:{}}}:{},...l.length>0?{managedPackages:l}:{},...d>0?{contactPointsBlanked:d}:{},...p.length>0?{personalAsIs:p}:{}}}var Zc=10*6e4,Qc=3e4,Xc=5e3,ri=500,ed=new Set(["JobComplete","Failed","Aborted"]),oi=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>ri&&this.kept.splice(0,this.kept.length-ri)}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??(l=>new Promise(p=>setTimeout(p,l))),s=this.options.pollDelay??No,i=r()+(this.options.waitMs??Zc),a=e.filter(l=>l.jobId===void 0),c=e.filter(l=>!!l.jobId);for(let l=0;c.length>0;l++){let p=new vt(Math.max(1,Math.min(Qc,i-r())));c=(await Promise.all(c.map(async d=>{t?.();let m=await p.withTimeout("forge:lost-bulk-job",()=>this.stateOf(d.orgId,d.jobId)).catch(()=>{});return m!==void 0&&ed.has(m)?void 0:d}))).filter(d=>d!==void 0);let f=i-r()-Xc;if(c.length===0||f<=0)break;await o(Math.min(s(l),f))}return[...a,...c]}};function Zp(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 td="SELECT SobjectType FROM DuplicateRule WHERE IsActive = true",Xp=new Set(["Account","Contact","Lead"]);function eg(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 tg(n){try{let e=await n.query(td);return new Set(e.records.flatMap(t=>typeof t.SobjectType=="string"?[t.SobjectType]:[]))}catch{return}}var si=class{constructor(e=3){this.maxDiscoveries=e}maxDiscoveries;discoveries=new Map;awaitingGuard=new Map;run=null;beginDiscovery(e,t,r){let o=[],s=l=>{this.discoveries.delete(l.requestId),l.stop="superseded",o.push(l)},i=this.discoveries.get(e);i&&s(i);let a=[...this.discoveries.values()].filter(l=>!l.controller.signal.aborted);for(;a.length>=this.maxDiscoveries;){let l=a.shift();l&&s(l)}let c={requestId:e,controller:t,operationId:r};return this.discoveries.set(e,c),{discovery:c,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 Vn(n){let e=0,t=new Map,r=new Map,o=[],s=new Set,i=new Map,a=[],c=f=>{t.set(f,e),r.set(f,e),e++,o.push(f),s.add(f);for(let d of[...n.get(f)??[]].sort())n.has(d)&&(t.has(d)?s.has(d)&&r.set(f,Math.min(r.get(f)??0,t.get(d)??0)):(c(d),r.set(f,Math.min(r.get(f)??0,r.get(d)??0))));if(r.get(f)===t.get(f)){let d=[],m;do{if(m=o.pop(),m===void 0)break;s.delete(m),i.set(m,a.length),d.push(m)}while(m!==f);a.push(d.sort())}};for(let f of[...n.keys()].sort())t.has(f)||c(f);let l=a.map((f,d)=>{let m=new Set;for(let h of f)for(let w of n.get(h)??[]){let b=i.get(w);b!==void 0&&b!==d&&m.add(b)}return m}),p=new Set,u=[];for(;p.size<a.length;){let f=a.map((d,m)=>({component:d,i:m})).filter(({i:d})=>!p.has(d)&&[...l[d]].every(m=>p.has(m))).sort((d,m)=>d.component[0].localeCompare(m.component[0]));for(let{component:d,i:m}of f)p.add(m),u.push(d)}return u}function Jn(n,e){let t=new Set(n),r=new Map(n.map(s=>[s,new Set([...e.get(s)??[]].filter(i=>t.has(i)))])),o=[];for(;;){let s=[...r.entries()].filter(([,i])=>i.size===0).map(([i])=>i).sort();if(s.length===0)break;for(let i of s){o.push(i),r.delete(i);for(let a of r.values())a.delete(i)}}return[...o,...[...r.keys()].sort()]}function nd(n,e,t){let r=new Set(n),o=new Map;for(let s of e){if(!r.has(s.to)||!r.has(s.from))continue;let i=t(s.to)?.find(c=>c.name===s.fieldApiName),a=i!==void 0&&je(i);!s.required&&!Mr(s.to,s.fieldApiName)&&!a||o.set(s.to,(o.get(s.to)??new Set).add(s.from))}return o}function rd(n,e){let t=new Set(n),r=e.filter(s=>s.from!==s.to&&t.has(s.from)&&t.has(s.to)),o=new Map(n.map(s=>[s,new Set]));for(let s of r)o.get(s.to)?.add(s.from);return{within:r,deps:o,groups:Vn(o)}}function sg(n,e,t){return n.flatMap(r=>{let{groups:o,within:s}=rd(r,e);return o.flatMap(i=>i.length>1?Jn(i,nd(i,s,t)):i)})}var od=100,sd=.25,id=2048;function ad(n,e){return typeof n!="string"||n===""?!1:e.prefix===void 0||e.prefix!==null&&n.startsWith(e.prefix)}function cd(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||!Se(a))continue;let c=Hn(o.objectApiName,a)||je(a);for(let l of a.referenceTo)l===o.objectApiName||!e.has(l)||(s.add(l),c&&i.add(l))}t.set(o.objectApiName,s),r.set(o.objectApiName,i)}return Vn(t).flatMap(o=>o.length>1?Jn(o,r):o)}function Hn(n,e){return qe(n,e.name,e.nillable)}function dd(n){let e=new Map(n.objects.map(d=>[d.objectApiName,d])),t=new Map;for(let d of e.keys())n.referenceData?.has(d)&&t.set(d,"referenceData");for(let d of n.whole??[])e.has(d)&&!t.has(d)&&t.set(d,"asked");let r=sd*Math.max(0,n.roomBytes),o=d=>d.rows===void 0?void 0:n.wholeBytes(d.objectApiName,d.rows),s=[...e.values()].filter(d=>xt.has(d.objectApiName)&&!t.has(d.objectApiName)),i=s.reduce((d,m)=>{let h=o(m);return d===void 0||h===void 0?void 0:d+h},0);if(s.length>0&&i!==void 0&&i<=r&&s.every(d=>n.maxRecordsPerObject===void 0||(d.rows??0)<=n.maxRecordsPerObject))for(let d of s)t.set(d.objectApiName,"catalog");let c=Math.max(od,Math.floor(.01*Math.max(0,n.roomBytes)/id)),l=d=>e.has(d)&&!t.has(d),p=new Set;for(let d of e.values())if(l(d.objectApiName)){for(let m of d.fields)if(Se(m))for(let h of m.referenceTo)h!==d.objectApiName&&p.add(h)}let u=[...e.values()].filter(d=>!t.has(d.objectApiName)&&!xt.has(d.objectApiName)&&d.rows!==void 0&&d.rows>0&&d.rows<=c&&(n.maxRecordsPerObject===void 0||d.rows<=n.maxRecordsPerObject)&&p.has(d.objectApiName)).map(d=>({object:d,bytes:o(d)??1/0})).sort((d,m)=>d.bytes-m.bytes||(d.object.objectApiName<m.object.objectApiName?-1:1)),f=0;for(let{object:d,bytes:m}of u){if(f+m>r)break;d.fields.some(w=>Se(w)&&Hn(d.objectApiName,w)&&w.referenceTo.some(b=>l(b)))||(t.set(d.objectApiName,"smallParent"),f+=m)}return t}function ii(n){let e=new Map(n.objects.map(u=>[u.objectApiName,u])),t=dd(n),r=[...t.values()].includes("catalog"),o=new Map;for(let u of e.keys()){let f=t.get(u);o.set(u,f!==void 0?{kind:"whole",why:f}:{kind:"drawn",rooted:!(xt.has(u)&&!r)})}let s=n.order?[...n.order]:cd(n.objects),i=new Map(s.map((u,f)=>[u,f])),a=(u,f)=>(i.get(u)??1/0)<(i.get(f)??1/0),c=u=>{let f=o.get(u);return f?.kind==="drawn"&&f.rooted},l=new Map,p=new Map;for(let u of[...e.values()].sort((f,d)=>f.objectApiName<d.objectApiName?-1:1)){let f=u.objectApiName,d=[];for(let m of[...u.fields].sort((h,w)=>h.name<w.name?-1:1)){if(m.referenceTo.length===0||!Se(m))continue;let h=Hn(f,m),w=m.referenceTo.length>1;for(let b of[...m.referenceTo].sort()){let S=o.get(b),I=Je(f,m,e.get(b)?.childRelationships),g=n.excluded?.get(b),y=T=>w?{prefix:T??null}:{};if(!S){h&&n.excluded?.has(b)&&d.push({objectApiName:f,field:m.name,parent:b,target:"excluded",carries:!1,owed:!1,required:h,masterDetail:I,...y(g)});continue}let R=b===f,j=R||!a(b,f),v={objectApiName:f,field:m.name,parent:b,target:S.kind==="whole"?"whole":"drawn",carries:!R&&c(b)&&c(f)&&(h||!j),owed:j,required:h,masterDetail:I,...y(e.get(b)?.keyPrefix)};if(d.push(v),v.carries){let T=p.get(b)??[];T.push(v),p.set(b,T)}}}l.set(f,d)}return{classes:o,whole:[...t.entries()].map(([u,f])=>({objectApiName:u,why:f})).sort((u,f)=>u.objectApiName<f.objectApiName?-1:1),linksOf:l,carriersInto:p,order:s}}function ug(n,e){return[...new Set((n.linksOf.get(e)??[]).map(t=>t.field))].sort()}function fg(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 pg(n,e,t,r){return(n.linksOf.get(e)??[]).find(o=>o.field===t&&ad(r,o))}var Fe=2e3,ud=500,Qn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,fd=Pe;function Ht(n){return n.length===0?"":` WHERE ${n.join(" AND ")}`}function Xe(n){return ao(n)+2*(n.match(/'/g)?.length??0)}function ai(n,e,t){let r=Xe(n)+Xe(t),o=Xe(", "),s=[],i=[],a=r;for(let c of e){let l=Xe(`'${c}'`);i.length>0&&(a+o+l>14e3||i.length>=ud)&&(s.push(i),i=[],a=r),a+=(i.length>0?o:0)+l,i.push(c)}return i.length>0&&s.push(i),s}function yt(n){let e=new Set,t=[];for(let r of n){if(!Qn.test(r))continue;let o=ce(r);e.has(o)||(e.add(o),t.push(r))}return t}function Kn(n){return st(U(n))==="QUERY_TIMEOUT"}var pd=new Set(["MALFORMED_QUERY","INVALID_FIELD"]);function ci(n){let e=st(U(n));return e!==void 0&&pd.has(e)}var we="CreatedDate";function gd(n){return n.replace(/'(?:[^'\\]|\\.)*'/g,"''")}function md(n){return/\(\s*SELECT\b/i.test(gd(n))}function hd(n){return n==null||n===""}var di=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;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 c=a.toLowerCase();i.has(c)||!o.has(c)||(i.add(c),s.push(V(a)))}return s}readOptionsOf(e){return Pe.has(e)?{all:!0}:void 0}termsOf(e){let t=this.options.filterOf?.(e);return[...t!==void 0&&t.trim()!==""?[`(${t})`]:[],...Pe.has(e)?["IsDeleted = false"]:[]]}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 V(t)}rootShapeOf(e){let t=V(e.objectApiName),r=this.slow.has(t),o=e.carriers.map(c=>({field:this.fieldOf(t,c.field),prefixes:c.drawnPrefixes===void 0?void 0:[...c.drawnPrefixes]})),s=r?[]:o.filter(c=>c.prefixes===void 0),i=o.filter(c=>!s.includes(c)),a=(c,l)=>!hd(c)&&(l===void 0||l.some(p=>String(c).startsWith(p)));return{object:t,select:this.columnsOf(t,i.map(c=>c.field)),terms:[...this.termsOf(t),...s.map(c=>`${c.field} = null`)],held:s.length>0,tested:i.length>0,isRoot:c=>!i.some(l=>a(c[l.field],l.prefixes))}}async countRoots(e){let t=new Array(e.length),r=0;return await Ae(e,async(o,s)=>{let i=await this.countRootsOf(o);t[s]=i,this.counted.set(o.objectApiName,i.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),o=this.rootShapeOf(e),s=a=>this.count(`SELECT COUNT() FROM ${a.object}${Ht(a.terms)}`,r);if(!this.slow.has(t))try{let a=await s(o);return{objectApiName:t,rows:a,exact:!o.tested}}catch(a){if(!o.held||!Kn(a))throw a;this.slow.add(t)}let i=await s(this.rootShapeOf(e));return{objectApiName:t,rows:i,exact:!1,timedOut:!0}}async drawUniform(e,t){let r=0;await Ae(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);for(;;){let o=this.rootShapeOf(e),s=`SELECT ${o.select.join(", ")} FROM ${o.object}${Ht(o.terms)}`,i=!1;try{for await(let a of this.pages(s,r)){i=!0;let c=a.filter(o.isRoot).map(l=>String(l.Id));c.length>0&&await t(e.objectApiName,c)}return}catch(a){if(i||!o.held||!Kn(a))throw a;this.slow.add(e.objectApiName)}}}async drawRecent(e,t){let r=e.map(s=>({objectApiName:s.objectApiName,by:this.newestBy(s.objectApiName)})),o=0;return await Ae(e,async(s,i)=>{s.take>0&&this.counted.get(s.objectApiName)!==0&&await this.newestRoots(s,r[i].by,t),o++,this.progress("drawing",{objectApiName:s.objectApiName,done:o,total:e.length})}),r}newestBy(e){return(this.options.fieldsOf(e)??[]).some(o=>o.toLowerCase()===we.toLowerCase())&&this.options.sorts?.(e,we)!==!1?"created":"id"}readsNewestApart(e){let t=this.options.filterOf?.(e);return this.newestBy(e)==="created"&&t!==void 0&&md(t)}async newestRoots(e,t,r){let o=e.objectApiName,s=this.readOptionsOf(o),i=this.readsNewestApart(o),a=0,c,l=!1;for(;a<e.take;){let p=this.rootShapeOf(e),u=p.tested?Fe:Math.min(Fe,e.take-a),f=t==="created"?this.columnsOf(o,[...p.select,we]):p.select,{after:d,order:m}=wd(t,c,i,l),h=`SELECT ${f.join(", ")} FROM ${p.object}${Ht([...p.terms,...d])} ORDER BY ${m} LIMIT ${u}`,w;try{w=await this.gather(h,s)}catch(I){if(!p.held||!Kn(I))throw I;this.slow.add(o);continue}let b=w.filter(p.isRoot).map(I=>String(I.Id)).slice(0,e.take-a);if(a+=b.length,b.length>0&&await r(o,b),w.length<u){if(!(i&&l))return;l=!1;continue}let S=w[w.length-1];c=bd(o,S,t),l=i}}async readParents(e){let t=new Array(e.length);return await Ae(e,async(r,o)=>{t[o]=await this.parentsOf(r)}),t}async parentsOf(e){let t=V(e.objectApiName),r=this.columnsOf(t,e.columns),o=yt(e.ids),s=this.readOptionsOf(t),i=await this.byList(t,r,"Id",o,this.termsOf(t),s),a=new Set(i.map(f=>ce(String(f.Id)))),c=o.filter(f=>!a.has(ce(f))),l=this.options.filterOf?.(t),p=[];if(c.length>0&&l!==void 0&&l.trim()!==""){let f=Pe.has(t)?["IsDeleted = false"]:[];p=await this.byList(t,r,"Id",c,f,s)}let u=new Set(p.map(f=>ce(String(f.Id))));return{objectApiName:e.objectApiName,rows:i,columns:r,absent:c.filter(f=>!u.has(ce(f))),outsideFilter:p}}async readStandardPrices(e,t){let r=yt(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"&&Qn.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=yt(t),i=yt(r);if(s.length===0||i.length===0)return[];let a=this.columnsOf("PricebookEntry",["Product2Id","Pricebook2Id",...o]),c=[...this.termsOf("PricebookEntry"),`Pricebook2Id IN (${i.map(l=>`'${l}'`).join(", ")})`,`CurrencyIsoCode = '${e}'`];return this.byList("PricebookEntry",a,"Product2Id",s,c,void 0)}async byList(e,t,r,o,s,i){let a=[...s,`${r} IN (`].join(" AND "),c=`SELECT ${gn(t).join(", ")} FROM ${e} WHERE ${a}`,l=[];for(let p of ai(c,o,")")){let u=`SELECT ${t.join(", ")} FROM ${e} WHERE ${a}${p.map(f=>`'${f}'`).join(", ")})`;for(let f of await mn(u,d=>this.gather(d,i)))l.push(f)}return l}async readChildren(e){let t=new Array(e.length);return await Ae(e,async(r,o)=>{t[o]=await this.childrenOf(r)}),t}async childrenOf(e){let t=V(e.objectApiName),r=this.fieldOf(t,e.field),o=e.cap,s=this.newestBy(t),i=o!=="all"&&s==="created",a=this.columnsOf(t,[r,...e.columns,...i?[we]:[]]),c=yt(e.parentIds),l=this.readOptionsOf(t),p=this.termsOf(t),u=new Map,f={objectApiName:t,field:r,rows:[],columns:a,cut:[],counts:new Map,newestBy:s},d=()=>{for(let y of c)f.counts.set(y,u.get(ce(y))??0);return f};if(c.length===0)return f;if(o==="all"){let y=Yn(await this.byList(t,a,r,c,p,l),r,1/0,s);f.rows=y.rows;for(let[R,j]of y.counts)u.set(R,j);return d()}let m=[...p,`${r} IN (`].join(" AND "),h={head:`SELECT ${r}, COUNT(Id) n FROM ${t} WHERE ${m}`,tail:`) GROUP BY ${r}`},w={head:`SELECT ${gn(a).join(", ")} FROM ${t} WHERE ${m}`,tail:")"},b=Xe(h.head+h.tail)>Xe(w.head+w.tail)?h:w,S=[],I=[];for(let y of ai(b.head,c,b.tail)){let R=e.sourceRows<=o*y.length||this.ungrouped.has(t)||this.options.countsBy?.(t,r)===!1?void 0:await this.countedByParent(t,h,r,y,l);if(R===void 0){S.push(...y);continue}for(let j of R)j.rows>o?I.push(j):S.push(j.parentId)}let g=Yn(await this.byList(t,a,r,S,p,l),r,o,s);f.rows.push(...g.rows),f.cut.push(...g.cut);for(let[y,R]of g.counts)u.set(y,R);for(let y of I){let R=`SELECT ${a.join(", ")} FROM ${t} WHERE ${[...p,`${r} = '${y.parentId}'`].join(" AND ")} ORDER BY ${Zn(s)} LIMIT ${o}`,j;try{j=await mn(R,v=>this.gather(v,l))}catch(v){if(!ci(v))throw v;let T=Yn(await this.byList(t,a,r,[y.parentId],p,l),r,o,s);f.rows.push(...T.rows),f.cut.push(...T.cut);for(let[C,M]of T.counts)u.set(C,M);continue}f.rows.push(...j),f.cut.push({parentId:y.parentId,rows:Math.max(0,y.rows-j.length)}),u.set(ce(y.parentId),y.rows)}return d()}async countedByParent(e,t,r,o,s){let i=`${t.head}${o.map(l=>`'${l}'`).join(", ")}${t.tail}`,a;try{a=await this.gather(i,s)}catch(l){if(!ci(l))throw l;this.ungrouped.add(e);return}let c=[];for(let l of a){let p=l[r],u=Number(l.n);typeof p=="string"&&Number.isFinite(u)&&c.push({parentId:p,rows:u})}return c}async readWhole(e,t){await Ae(e,async r=>{let o=V(r.objectApiName),s=this.columnsOf(o,r.columns),i=this.readOptionsOf(o),a=`SELECT ${s.join(", ")} FROM ${o}${Ht(this.termsOf(o))}`;for await(let c of po(a,l=>this.pages(l,i),l=>this.gather(l,i)))await t(r.objectApiName,c)})}};function Zn(n){return n==="created"?`${we} DESC, Id DESC`:"Id DESC"}function wd(n,e,t,r){let o=Zn("created");return n==="id"?{after:e?[`Id < '${e.id}'`]:[],order:Zn("id")}:e?t?r?{after:[`${we} = ${e.at}`,`Id < '${e.id}'`],order:"Id DESC"}:{after:[`${we} < ${e.at}`],order:o}:{after:[`(${we} < ${e.at} OR (${we} = ${e.at} AND Id < '${e.id}'))`],order:o}:{after:[],order:o}}function bd(n,e,t){let r=e.Id;if(typeof r!="string"||!Qn.test(r))throw new Error(`A record of ${n} came back without its id.`);if(t==="id")return{at:"",id:r};let o=e[we];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:zo(o),id:r}}function li(n){let e=n[we],t=typeof e=="string"?Date.parse(e):Number.NaN;return Number.isFinite(t)?t:void 0}function yd(n,e){let t=li(n),r=li(e);return t!==r?t===void 0?1:r===void 0?-1:r-t:Be(String(e.Id),String(n.Id))}function Yn(n,e,t,r){let o=new Map;for(let c of n){let l=c[e];if(typeof l!="string")continue;let p=ce(l),u=o.get(p);u?u.rows.push(c):o.set(p,{parentId:l,rows:[c]})}let s=[],i=[],a=new Map;for(let[c,{parentId:l,rows:p}]of o)p.sort(r==="created"?yd:(u,f)=>Be(String(f.Id),String(u.Id))),s.push(...p.slice(0,t)),p.length>t&&i.push({parentId:l,rows:p.length-t}),a.set(c,p.length);return{rows:s,cut:i,counts:a}}function ui(n,e,t=0,r=!1){if(n.rows<=0)return 0;if(e==="uniform")return Math.ceil(n.rows/Fe);let o=Math.ceil(Math.min(Math.max(0,t),n.rows)/Fe);return r?o+Math.max(0,o-1):o}function Og(n){let e=V(n.objectApiName),t=n.columns.some(f=>f.toLowerCase()==="systemmodstamp"),r=co(n.columns,t?["Id","SystemModstamp"]:["Id"]),o=Math.max(0,n.planRows),s=Math.max(0,n.sourceRows),i=r.map(f=>uo(e,f)),a=i.reduce((f,d)=>f+Math.ceil(o/d),0),c=Math.max(1,Math.ceil(s/Fe)),l=Math.floor(s/Fe),p=s%Fe,u=c+i.slice(1).reduce((f,d)=>f+l*Math.ceil(Fe/d)+(p>0?Math.ceil(p/d):0),0);return fd.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 Rd=new Set(["BusinessHours","OperatingHours"]);function Sd(n){let{storage:e,withinMB:t}=n,r=new Map;for(let c of n.automation??[])r.set(c.objectApiName,(r.get(c.objectApiName)??0)+c.bytes);let o=r.size>0?{automationBytes:c=>r.get(c)??0}:{};if("unread"in e){if(t===void 0)return;let c=Math.floor(Math.max(0,t)*1048576);return{budget:{bytes:c,withinMB:t,limitedBy:"within"},bytesLimit:"within",roomBytes:c,...o}}let s=fs({storage:e,...t!==void 0?{withinMB:t}:{}});if("unread"in s)return;let i=s.terms.limitedBy==="within"?"within":"storage",a=Math.floor(De*Math.max(0,e.remainingMB-Ve)*1048576);return{budget:{bytes:s.bytes,remainingMB:e.remainingMB,maxMB:e.maxMB,share:De,roundingMB:Ve,...t!==void 0?{withinMB:t}:{},limitedBy:i},bytesLimit:i,roomBytes:a,storageBytes:a,...o}}function Od(n,e){let t=n.nodes.filter(o=>o.included&&!Lr(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 Tg(n){let e=n.options??{},t=Od(n.graph,new Set(n.excludedObjects??[])),r=t.reduce((u,f)=>u+dt(f.objectApiName,{rows:f.rows??0}),0),o=rs({storageBytes:r},n.storage),s=Sd({storage:n.storage,...e.withinMB!==void 0?{withinMB:e.withinMB}:{}}),i=ii({objects:t,referenceData:Rd,...e.whole?{whole:e.whole}:{},roomBytes:s?.roomBytes??0,...n.maxRecordsPerObject!==void 0?{maxRecordsPerObject:n.maxRecordsPerObject}:{},wholeBytes:(u,f)=>dt(u,{rows:f})}),a=e.draw??Ee.draw,c=s?Cs(s.budget.bytes,e.maxTotal):0,p=t.filter(u=>{let f=i.classes.get(u.objectApiName);return f?.kind==="drawn"&&f.rooted}).reduce((u,f)=>{let m=(i.linksOf.get(f.objectApiName)??[]).some(h=>h.carries&&h.required)?0:f.rows??0;return u+1+ui({objectApiName:f.objectApiName,rows:m,exact:!1},a,Math.min(m,c))},0);return{wholeOrg:o,...s?{budget:s.budget}:{},whole:i.whole.filter(u=>u.why!=="asked"),planReads:{source:Ad(p,n.source),seconds:p*ts}}}function Ad(n,e){if("unread"in e)return{verdict:"unread",estimate:n,unread:e.unread};let t=ns(n,e);if(t.verdict==="unread")return t;let r=n>Math.floor(Lt*e.remaining);return{...t,verdict:r?"exceeds":t.verdict}}var fi=z({value:q(),validFor:J(H().int().nonnegative()).optional()}).loose(),pi=z({controllerValues:rt(q(),H().int().nonnegative()).optional(),defaultValue:fi.nullable().optional(),values:J(fi)}).loose(),Id=z({picklistFieldValues:rt(q(),Re())}).loose(),kd=/^[A-Za-z][A-Za-z0-9_]*$/,Ed=/^012[A-Za-z0-9]{12}([A-Za-z0-9]{3})?$/;function jd(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 Nd(n){let e=Id.parse(n),t=new Map;for(let[r,o]of Object.entries(e.picklistFieldValues)){let s=pi.safeParse(o);s.success&&t.set(r,jd(s.data))}return t}function Cd(n){return pi.parse(n).values.map(e=>e.value)}function gi(n,e,t,r){for(let s of r===void 0?[e]:[e,r])if(!kd.test(s))throw new Error(`Not an API name: "${s}"`);if(!Ed.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 vg(n,e,t){return Nd(await n.request(gi(n,e,t)))}async function xg(n,e,t,r){return Cd(await n.request(gi(n,e,t,r)))}var Pd=z({FileStorageMB:z({Remaining:H()}).loose()}).loose(),Td=J(z({errorCode:q().optional(),message:q().optional()}).loose());function Fd(n){if(!(n instanceof Error))return new Error(String(n));try{let e=Td.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 Bg(n,e,t){if(!So(t))throw new Error(`Not a record id: ${t}`);try{let r=await n.request({method:"GET",url:`/sobjects/${e}/${t}/${Es[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 Fd(r)}}async function $g(n,e,t){try{let r=await n.request({method:"POST",url:`/sobjects/${e}`,body:JSON.stringify(t),headers:{"content-type":"application/json"}}),o=Tt(r,e);return{id:o.id,success:o.success,errors:o.errors}}catch(r){return{id:"",success:!1,errors:[Ao(r)]}}}async function zg(n){return Pd.parse(await n.request({method:"GET",url:"/limits"})).FileStorageMB.Remaining}var _d=["Task","Event","FeedItem","FeedComment","EmailMessage","ContentDocumentLink","Note","CaseComment"],wi=["Account","Contact","Lead","Opportunity","Case","Campaign","Contract","Order","Asset","Product2"],er=["User","Group","GroupMember","PermissionSet","PermissionSetAssignment","PermissionSetGroup","RecordType","Profile","UserRole"],Dd=1e3,Ld=6e4,Xn=1e4,Bd=300,mi=2e3,$d=50,zd=3,bi=3,qd=5,Ud=new Set(["flows","processes","triggers","conditions","definitions"]),yi=new Set(["OwnerId","CreatedById","LastModifiedById","RecordTypeId"]),Rt=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function G(n){return n.slice(0,15)}function se(n){return typeof n=="string"?Date.parse(n):Number.NaN}function et(n){return new Date(n).toISOString().replace(/\.\d{3}Z$/,"Z")}function Wd(n){let e=se(n?.first),t=se(n?.last);if(!(!Number.isFinite(e)||!Number.isFinite(t)))return{from:Math.floor((e-Dd)/1e3)*1e3,to:Math.ceil((Math.max(e,t)+Ld)/1e3)*1e3}}function em(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(c=>c.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=>Ud.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 tm(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:U(o)}}finally{r.close()}}))}async function Gd(n,e,t){let r=new Map,o=0,s;for(let{objectApiName:i,ids:a}of e){if(o>=zd||r.size>1||t())break;let c=a.slice(0,$d);if(c.length!==0)try{let[l]=ne(c,c.length),p=await n.queryDeleted(`SELECT CreatedById FROM ${V(i)} WHERE Id IN (${l})`),u=!1;for(let f of p.records){let d=f?.CreatedById;typeof d=="string"&&Rt.test(d)&&(r.has(G(d))||r.set(G(d),d),u=!0)}u&&o++}catch(l){s??=U(l)}}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 Vd(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 Jd(n){return n.queryable!==!1&&n.deletable!==!1&&n.createable!==!1&&n.layoutable!==!1&&!er.some(e=>e.toLowerCase()===n.name.toLowerCase())}async function Ri(n,e){let t;try{t=await e(n)}catch(i){return{reason:U(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:Hd(t)}}function Hd(n){return n.fields.filter(e=>e.type==="reference"&&!yi.has(e.name)&&!((e.referenceTo??[]).length>0&&(e.referenceTo??[]).every(t=>er.includes(t)))).map(e=>e.name)}function Kd(n,e){return`CreatedById = '${n}' AND CreatedDate >= ${et(e.from)} AND CreatedDate <= ${et(e.to)}`}function Si(n,e){return n.length===1?Kd(n[0],e):`CreatedById IN (${n.map(t=>`'${t}'`).join(", ")}) AND CreatedDate >= ${et(e.from)} AND CreatedDate <= ${et(e.to)}`}async function Oi(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=Wd(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(se(e.writtenBetween?.first),se(e.writtenBetween?.last)),o.window={from:et(i.from),to:et(i.to)};let a=e.runUserId!==void 0&&Rt.test(e.runUserId)?e.runUserId:void 0,c=e.user!==void 0&&Rt.test(e.user)?e.user:void 0,l=e.created.some(u=>u.ids.length>0),p=a?{user:a}:l?await Gd(n,e.created,r):c!==void 0?{user:c}:{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 p?(o.refusal=p.refusal,s.stopped=r(),s):sl(n,e,e.ties,p.user,s,i,t)}function Yd(n){return n.map(e=>`${e.objectApiName}: ${e.count}`).join(", ")}async function Zd(n,e,t){if(e.length===0)return[];if(n.counts)try{return await n.counts(e)}catch(o){let s=U(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:U(s)})}}return r}async function Qd(n){try{return(await n.query("SELECT Id FROM User WHERE UserType = 'AutomatedProcess'")).records.map(t=>t?.Id).filter(t=>typeof t=="string"&&Rt.test(t))}catch{return[]}}async function Xd(n,e,t,r,o,s){let i=V(e.name),a=[...new Set(["Id","CreatedById","CreatedDate",e.modified,e.modifiedBy,e.nameField,...e.references].filter(u=>u!==void 0).map(V))],c=async u=>(await n.query(u)).records.filter(f=>typeof f=="object"&&f!==null),l=[],p;for(;;){if(s())return{rows:l,overBound:!1,stopped:!0};let u=`SELECT ${a.join(", ")} FROM ${i} WHERE ${Si([...t.values()],r)}${p?` AND Id > '${p}'`:""} ORDER BY Id LIMIT ${mi}`,f;try{let d=lo(u);f=d?await fo(await c(d.first),d,c):await c(u)}catch(d){return{reason:U(d)}}for(let d of f){if(typeof d.Id!="string")continue;p=d.Id;let m=typeof d.CreatedById=="string"?G(d.CreatedById):"",h=se(d.CreatedDate);if(!t.has(m)||!(h>=r.from&&h<=r.to)||o(G(d.Id)))continue;let w=e.modifiedBy?d[e.modifiedBy]:void 0,b=e.nameField?d[e.nameField]:void 0,S=[];for(let I of e.references){let g=d[I];typeof g=="string"&&Rt.test(g)&&S.push({field:I,key:G(g)})}if(l.push({id:d.Id,modified:se(d[e.modified]),created:h,creator:m,references:S,...typeof w=="string"?{modifiedBy:G(w)}:{},...typeof b=="string"&&b.trim()!==""?{name:b.trim().slice(0,80)}:{}}),l.length>Xn)return{rows:l.slice(0,Xn),overBound:!0,stopped:!1}}if(f.length<mi)return{rows:l,overBound:!1,stopped:!1}}}function el(n){let e=new Map,t=o=>{let s=o.toLowerCase(),i=e.get(s);return i||(i=(async()=>Ct.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(c=>c.childSObject.toLowerCase()===s.toLowerCase()&&c.field===i);return{cascade:a?.cascadeDelete===!0,restricted:a?.restrictedDelete===!0}}}}async function tl(n,e,t,r,o,s){let i=await Vd(n),a=d=>i?i.get(d.toLowerCase()):{name:d},c=[],l=[],p=d=>c.some(m=>m.toLowerCase()===d.toLowerCase()),u=d=>er.some(m=>m.toLowerCase()===d.toLowerCase()),f=(d,m)=>{if(p(d)||u(d))return;let h=a(d)?.name;if(!h){m&&o.unread.push({objectApiName:d,reason:"The org has no such object."});return}if(c.length>=Bd){l.includes(h)||l.push(h);return}c.push(h)};for(let d of e)f(d,!0);for(let d of _d)f(d,!1);for(let d of t)f(d,!0);for(let d of wi)f(d,!1);for(let d of e){if(s())return;for(let m of(await r.now(d))?.childRelationships??[]){let h=a(m.childSObject);h&&Jd(h)&&!p(h.name)&&f(h.name,!1)}}return{looked:c,notLooked:l}}async function nl(n,e,t,r,o,s,i){let a=[],c=new Map([...r.keys()].map(l=>[l.toLowerCase(),l]));for(let l of e){let p=((await o.now(l))?.fields??[]).filter(u=>u.type==="reference"&&!yi.has(u.name));for(let u of p)for(let f of u.referenceTo??[]){let d=c.get(f.toLowerCase());if(!d)continue;let m=(r.get(d)??[]).map(b=>b.id),{restricted:h}=await o.relation(d,l,u.name),w=V(u.name);for(let b of ne(m)){if(i())return;let S;try{S=(await n.query(`SELECT Id, ${w} FROM ${V(l)} WHERE ${w} IN (${b})`)).records}catch(I){s.unread.push({objectApiName:l,reason:`What its ${u.name} points at among the records found could not be read (${U(I)}): what only it ties is left as tied to nothing.`});continue}for(let I of S){let{Id:g,[u.name]:y}=I??{};typeof g!="string"||typeof y!="string"||t.has(G(g))&&a.push({from:G(g),to:G(y),restricted:h})}}}}return a}async function rl(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 ne(i)){if(r())return!1;try{let c=await n.queryDeleted(`SELECT Id, CreatedDate FROM ${V(s)} WHERE Id IN (${a})`);for(let l of c.records){let{Id:p,CreatedDate:u}=l??{},f=typeof p=="string"?e.get(G(p)):void 0,d=se(u);f&&Number.isFinite(d)&&(f.from=d,f.to=d)}}catch{}}return!0}function ol(n,e,t,r,o,s){let{listing:i}=r,a=new Set(wi.map(d=>d.toLowerCase())),c=[],l=[],p=["made","madeOver","late","untied"];for(let[d,m]of n){let h=[],w=0;for(let y of m){let R=e.get(G(y.id));if(R){if(R.class==="untied"&&a.has(d.toLowerCase())){w++;continue}h.push({id:y.id,modified:y.modified,created:y.created,class:R.class,sameSave:R.sameSave,turn:R.turn,...y.modifiedBy!==void 0?{modifiedBy:y.modifiedBy}:{},...y.name!==void 0?{name:y.name}:{}})}}if(w>0&&i.handWork.push({objectApiName:d,count:w}),h.length===0)continue;let b={made:0,madeOver:0,late:0,untied:0},S=0,I=0,g={};for(let y of h)b[y.class]++,y.sameSave&&S++,Kt(y,o,s)&&(I++,g[y.class]=(g[y.class]??0)+1);i.found.push({objectApiName:d,count:h.length,names:p.flatMap(y=>h.filter(R=>R.class===y)).flatMap(y=>y.name?[y.name]:[]).slice(0,bi),classes:{...b,...S>0?{sameSave:S}:{},...I>0?{changed:I,changedIn:g}:{}}}),b.untied>0&&c.push({objectApiName:d,count:b.untied}),b.late>0&&l.push({objectApiName:d,count:b.late}),r.rows.set(d,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 (${Yd(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 f=(t.otherRuns??[]).filter(d=>d.ids.length>0||d.idsUntold===!0).length;f>0&&u.push(`${f===1?"Another run":`${f} 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:c,...u.length>0?{refusal:u.join(" ")}:{}},i.late=l}async function sl(n,e,t,r,o,s,i){let{listing:a}=o,c=()=>e.signal?.aborted===!0,l=()=>(o.stopped=!0,o),p=se(e.writtenBetween?.first),u=Math.max(p,se(e.writtenBetween?.last)),f=Math.min(Number.POSITIVE_INFINITY,...[t.removalBegan,...i.map(E=>E.first)].map(se).filter(Number.isFinite)),d=Math.ceil((u+9e5)/1e3)*1e3,m={from:s.from,to:Math.max(s.to,Math.min(d,Math.floor(f/1e3)*1e3))},h=new Map,w={from:p,to:u};for(let{objectApiName:E,ids:x}of e.created)for(let F of x)h.set(G(F),{kind:"created",objectApiName:E,id:F,from:Number.NaN,to:Number.NaN});for(let{objectApiName:E,ids:x,between:F}of t.writtenOver??[]){let B=se(F?.first),W=se(F?.last);for(let X of x)h.has(G(X))||h.set(G(X),{kind:"overwritten",objectApiName:E,id:X,from:B,to:W})}let b=[...new Set([...e.created,...t.writtenOver??[]].filter(E=>E.ids.length>0).map(E=>E.objectApiName))],S=new Set([...(t.otherRuns??[]).flatMap(E=>E.ids.map(G)),...(t.leased??[]).map(G)]),I=E=>e.remap.has(E)||h.has(E)||S.has(E),g=await Qd(n),y=new Map([[G(r),r]]);for(let E of g)y.has(G(E))||y.set(G(E),E);let R=new Set(g.map(G).filter(E=>E!==G(r))),j=el(n),v=await tl(n,b,e.automation.creates,j,a,c);if(!v)return l();let{looked:T,notLooked:C}=v;a.looked=T,C.length>0&&(a.notLooked=C);let M=await Zd(n,T.map(E=>`SELECT COUNT() FROM ${V(E)} WHERE ${Si([...y.values()],m)}`),c);if(c())return l();let P=new Map,_=[];for(let[E,x]of T.entries()){let F=M[E];if(F===void 0)return l();if(F===0)continue;if(c())return l();let B=await Ri(x,j.of);if("reason"in B){a.unread.push({objectApiName:x,reason:B.reason});continue}if(typeof F=="object"){a.unread.push({objectApiName:x,reason:F.reason});continue}let W=await Xd(n,B,y,m,I,c);if("reason"in W){a.unread.push({objectApiName:x,reason:W.reason});continue}if(W.stopped)return l();W.overBound?_.push({objectApiName:x,count:W.rows.length,names:W.rows.flatMap(X=>X.name?[X.name]:[]).slice(0,bi),overBound:!0}):W.rows.length>0&&P.set(x,W.rows)}let L=new Map;for(let{part:E,created:x}of e.otherParts??[])for(let{objectApiName:F,ids:B}of x)for(let W of B)L.set(G(W),{part:E,objectApiName:F});let k=new Map;for(let[E,x]of L.size>0?[...P]:[]){let F=[];for(let B of x){let W,X=!1;for(let be of B.references){let At=h.get(be.key)??L.get(be.key);if(!At)continue;let{cascade:It}=await j.relation(At.objectApiName,E,be.field);It&&(h.has(be.key)?X=!0:W??=L.get(be.key)?.part)}if(W===void 0||X){F.push(B);continue}let te=k.get(W)??[],ze=te.find(be=>be.objectApiName===E);ze?ze.count++:te.push({objectApiName:E,count:1}),k.set(W,te)}F.length>0?P.set(E,F):P.delete(E)}k.size>0&&(a.otherParts=[...k].map(([E,x])=>({part:E,objects:x})));let O=new Map;for(let[E,x]of h)O.set(E,x.objectApiName);for(let[E,x]of P)for(let F of x)O.set(G(F.id),E);let A=[],N=new Set;for(let[E,x]of P)for(let F of x){let B=[];for(let W of F.references){let X=O.get(W.key);if(!X)continue;h.has(W.key)&&N.add(W.key);let{cascade:te}=await j.relation(X,E,W.field);B.push({key:W.key,cascade:te})}A.push({key:G(F.id),created:F.created,automatedProcess:R.has(F.creator),references:B})}let D=await nl(n,b,h,P,j,a,c);if(!D)return l();for(let E of D)N.add(E.from);if(!await rl(n,h,N,c))return l();let $=Fo({anchors:h,candidates:A,pointers:D,runSpan:w,window:s,removalBegan:f,madeEarlier:new Set((t.madeEarlier??[]).map(G)),lateEarlier:new Set((t.lateEarlier??[]).map(G))});return ol(P,$,t,o,u,i),c()?l():(await il(n,j,o,{user:r,span:m,lastWrite:u,removalSpans:i,isRun:E=>h.has(E)||e.remap.has(E)}),a.found.push(..._),t.muted&&(a.muted=t.muted),o.ordering={query:E=>n.query(E),queryDeleted:E=>n.queryDeleted(E),describe:async E=>await j.now(E)??n.describe(E),describeGlobal:()=>n.describeGlobal(),destroy:(E,x)=>n.destroy(E,x),update:(E,x)=>n.update(E,x),serverTime:()=>n.serverTime(),userId:()=>n.userId()},o)}var hi={untied:0,late:1,madeOver:2,made:3};async function il(n,e,t,r){let o=new Map;for(let d of t.rows.values())for(let m of d)o.set(G(m.id),m);if(o.size===0||t.rows.has(pe))return;let s=(await vo(n,{has:d=>o.has(d)||r.isRun(d),start:r.span.from,end:r.span.to,user:r.user})).filter(d=>!r.isRun(G(d.id))&&d.names.some(m=>o.has(m)));if(s.length===0)return;let i=await Ri(pe,e.of);if("reason"in i){t.listing.unread.push({objectApiName:pe,reason:i.reason});return}let a=new Map,c=s.map(d=>{let m=d.names.flatMap(S=>{let I=o.get(S);return I?[I]:[]});a.set(d.id,m.map(S=>G(S.id)));let h=m.reduce((S,I)=>hi[I.class]<hi[S]?I.class:S,"made"),w=Math.max(...m.map(S=>S.created)),b=d.modifiedBy!==void 0&&G(d.modifiedBy)===G(r.user)&&d.modified<=w+6e4;return{id:d.id,created:d.created,modified:b?Math.min(d.modified,d.created):d.modified,...d.modifiedBy!==void 0?{modifiedBy:G(d.modifiedBy)}:{},class:h,turn:"before"}});t.rows.set(pe,c),t.reports=a;let l={made:0,madeOver:0,late:0,untied:0},p=0,u={};for(let d of c)l[d.class]++,Kt(d,r.lastWrite,r.removalSpans)&&(p++,u[d.class]=(u[d.class]??0)+1);let{listing:f}=t;f.found.push({objectApiName:pe,count:c.length,names:[],classes:{...l,...p>0?{changed:p,changedIn:u}:{}}}),l.late>0&&(f.late=[...f.late??[],{objectApiName:pe,count:l.late}]),l.untied>0&&f.untied&&(f.untied={...f.untied,objects:[...f.untied.objects,{objectApiName:pe,count:l.untied}]})}function Kt(n,e,t){let r=Math.max(e,n.created)+2e3;return!(n.modified<=r)&&!al(n,t)}function al(n,e){return n.modifiedBy!==void 0&&e.some(t=>n.modifiedBy===G(t.userId)&&n.modified>=se(t.first)&&n.modified<=se(t.last))}async function nm(n,e,t=[]){return(await Oi(n,e,t)).listing}function cl(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 rm(n,e,t){let r=()=>e.signal?.aborted===!0,o=Oo(),s=new Set,i=new Set,a=new Set,c=new Set,l=[],p="new",u,f,d,m=new Map,h={unread:[],handWork:[]},w=new Map,b=new Map,S=async(C,M)=>{let P=C.lastWrite??Number.NaN,_=new Set,L=new Map;for(let[D,$]of M){let E=$.filter(x=>t.includeChanged||!Kt(x,P,t.removalSpans)).map(x=>x.id);for(let x of E)_.add(x);L.set(D,E)}if(_.size===0||!C.window)return;let k=new Set(e.created.flatMap(({ids:D})=>D.map(G))),O=C.ordering??n,A=xo(O,{runStart:C.window.from,runEnd:P,runRecords:{has:D=>k.has(D)},taken:_,removalSpans:t.removalSpans,includeChanged:t.includeChanged,...e.runUserId?{runUserId:e.runUserId}:{}}),N=await bn(O,[...M.keys()].map(D=>({objectApiName:D})));for(let{objectApiName:D}of N){if(D===pe)continue;let $=L.get(D)??[];if($.length===0)continue;if(r())return;let E=await A(D,$);E.reason!==void 0&&b.set(D,E.reason);for(let x of $)E.held.has(G(x))&&(_.delete(x),w.set(x,E.holders))}I(C,M,_)},I=(C,M,P)=>{let _=C.reports;if(!_)return;let L=new Set([...M].filter(([k])=>k!==pe).flatMap(([,k])=>k.filter(O=>P.has(O.id)).map(O=>G(O.id))));for(let k of M.get(pe)??[])w.has(k.id)||(_.get(k.id)??[]).every(O=>L.has(O))||(P.delete(k.id),w.set(k.id,["DuplicateRecordItem"]))},g=(C,M)=>{C.result.alreadyGone++,C.along.has(M)&&(C.result.withRemoval=(C.result.withRemoval??0)+1)},y=(C,M,P)=>{M.forEach((_,L)=>{let k=P[L];if((k.lockResends!==void 0||C.lockResent.has(_))&&C.lockResent.set(_,k.kind),k.kind==="refused"){C.refused.set(_,k.reason),k.limit&&C.limited.add(_);return}C.refused.delete(_),C.limited.delete(_),c.add(_),k.kind==="deleted"?C.result.deleted++:g(C,_)})},R=async(C,M,P)=>{for(let _=0;_<M.length;_+=Ge){if(r())return!1;let L=M.slice(_,_+Ge),k=C.result.deleted,O=await Co(n,C.result.objectApiName,L,o,{stopped:r,settle:(A,N)=>y(C,A,[...N])});if(P&&C.result.deleted>k){let A=C.result.deleted-k;C.result.afterRemoval=(C.result.afterRemoval??0)+A,P==="under"&&(C.result.afterRemovalUnder=(C.result.afterRemovalUnder??0)+A)}if(O)return!1}return!0},j=()=>l.reduce((C,M)=>C+M.result.deleted,0),v=async()=>{let C=h.left??[];if(C.length===0||!d)return;let M=d.rows,P=[],_=[];for(let k of C){let O=[],A=[];for(let N of k.objects){let D=(M.get(N.objectApiName)??[]).filter(x=>x.class===k.class).map(x=>x.id),$=r()?[]:(await yn(D,x=>ye(n,N.objectApiName,[],x),()=>!0)).gone;for(let x of $)c.add(x);let E=Math.min($.length,N.count);N.count>E&&O.push({...N,count:N.count-E}),E>0&&A.push({objectApiName:N.objectApiName,count:E})}O.length>0&&P.push({...k,objects:O}),A.length>0&&_.push({class:k.class,objects:A})}if(_.length===0)return;let L={...h};delete L.left,h={...L,...P.length>0?{left:P}:{},goneAlong:_}},T=()=>(f??=(async()=>{let C=await Oi(n,e,t.removalSpans);d=C;let{listing:M}=C;if(h={...M.window?{window:M.window}:{},unread:[...M.unread,...M.found.filter(k=>k.overBound).map(k=>({objectApiName:k.objectApiName,reason:`More than ${Xn} 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.`}))],...M.automationGaps?{automationGaps:M.automationGaps}:{},handWork:M.handWork},C.stopped){p="cancelled";return}for(let k of C.rows.values())for(let O of k)O.class==="made"||O.class==="madeOver"?i.add(O.id):O.class==="late"&&a.add(O.id);if(M.refusal!==void 0){p="refused",u=M.refusal;return}let P=t.sweepUntied===!0&&M.untied?.refusal===void 0,_=k=>k.class==="made"||k.class==="madeOver"||k.class==="late"&&t.sweepLate===!0||k.class==="untied"&&P;if(m=new Map([...C.rows].map(([k,O])=>[k,O.filter(_)]).filter(([,k])=>k.length>0)),await S(C,m),r()){p="cancelled";return}if(t.approve&&m.size>0){let k=await t.approve(M);if(k!==void 0){p="refused",u=k;return}}let L=cl(M,t);L.length>0&&(h={...h,left:L}),p="asked"})(),f);return{automationMade:s,made:i,late:a,gone:c,get listing(){return d&&!d.stopped?d.listing:void 0},get takes(){return p==="asked"?[...m.keys()]:[]},ask:T,async first(C){if(C&&(o=C),await T(),p!=="asked"||!d)return!1;let M=d,P=m,_=M.lastWrite??Number.NaN,L=await bn(M.ordering??n,[...P.keys()].map(O=>({objectApiName:O}))),k=[];for(let{objectApiName:O}of L){let A=P.get(O)??[],N={result:{objectApiName:O,found:A.length,deleted:0,alreadyGone:0,keptChanged:0,refused:0,reasons:[]},refused:new Map,limited:new Set,later:[],along:new Set,lockResent:new Map};l.push(N);let D=[];for(let $ of A){if(Kt($,_,t.removalSpans)&&!t.includeChanged){N.result.keptChanged++;continue}let E=w.get($.id);if(E){N.result.keptDependents=(N.result.keptDependents??0)+1,N.result.heldBy=[...new Set([...N.result.heldBy??[],...E])];continue}s.add($.id),$.turn==="before"?D.push($.id):N.later.push($.id),$.turn==="with"&&N.along.add($.id)}k.push([N,D])}for(let[O,A]of k)if(!await R(O,A))return p="cancelled",j()>0;return p="first",j()>0},async afterRemoval(C){if(C&&(o=C),p!=="first")return!1;let M=j();for(let P of l){let _=P.later.splice(0),L=_.filter(O=>P.along.has(O)),k=_.filter(O=>!P.along.has(O));if(!await R(P,k,"pointedAt")||!await R(P,L,"under"))return p="cancelled",j()>M}if(j()>0)for(let P of l){let _=[...P.refused.keys()].filter(L=>!P.limited.has(L));if(!await R(P,_))return p="cancelled",j()>M}for(let P of l){if(r())break;let{gone:_}=await yn([...P.refused.keys()],L=>ye(n,P.result.objectApiName,[],L),()=>!0);for(let L of _)P.refused.delete(L),P.lockResent.has(L)&&P.lockResent.set(L,"gone"),g(P,L),c.add(L)}return await v(),p="done",j()>M},result(){if(p==="refused")return{status:"refused",refusal:u??"",objects:[],...h};if(p==="new"||p==="asked")return{status:"cancelled",objects:[],...h};let C=l.map(({result:P,refused:_,lockResent:L})=>{P.refused=_.size;let k=b.get(P.objectApiName);return P.reasons=[...new Set([...k!==void 0&&(P.keptDependents??0)>0?[`What hangs from them could not be read, and they were kept: ${k}`]:[],...Po(P.objectApiName,o),...To(L.values()),..._.values()])].slice(0,qd),P}),M=l.some(P=>P.later.length>0);return{status:dl(C,p==="cancelled",M,ll(h,t)),objects:C,...h}}}}function dl(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 ll(n,e){return(n.left??[]).some(t=>t.class==="late"&&e.sweepLate===!0||t.class==="untied"&&e.sweepUntied===!0)}function om(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 sm(n){return n.objects.filter(e=>e.deleted+e.refused>0).map(e=>({...io(e.objectApiName),deleted:e.deleted,failed:e.refused}))}function im(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 am(n){return n.found.reduce((e,t)=>e+t.count,0)}function cm(n){return n.found.map(e=>e.objectApiName)}var ul=15e3,um=2,fl=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function pl(n,e){try{let{user_id:t}=await new vt(ul).withTimeout(`${e} run user`,async()=>n());return typeof t=="string"&&fl.test(t)?t:void 0}catch{return}}function fm(n,e,t){n?.runUser&&pl(e,t).then(r=>{r!==void 0&&n.runUser?.(r)})}var gl=30*6e4,ml=16,hl=["map_value","leave_empty","set_default","truncate","map_record_type","exclude_object","skip_rows","ignore"];function mm(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()])}var Ai=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<=ml)break;this.tried.delete(s)}}before(e,t=Date.now()){let r=this.tried.get(e),o=a=>a===void 0||t-a>gl||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 wl(n){let e={flow:0,trigger:0,process:0,workflowRule:0,unread:[]};if(!("automation"in n))return{...e,unread:["automation"]};for(let t of is(n.automation))e[t.kind]++;return e.unread=cs(n.automation).map(t=>t.part),e}function bl(n,e){let t={flow:0,trigger:0,process:0,workflowRule:0};if(!("automation"in n))return t;let r=e.map(o=>o.objectApiName);for(let o of as(n.automation,r))t[o.kind]++;return t}function yl(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 hl.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 Rl(n){let e=n.objects.reduce((t,r)=>t+r.sourceRows,0)+n.noRecordDrawn.reduce((t,r)=>t+r.sourceRows,0);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,kept:n.rows,inSource:e}}var Ii=class{constructor(e,t){this.config=e;this.before=t}config;before;confirmed=[];fired;firedOnUpdate;deliverability;sampleFit;automationRead(e,t=[]){this.fired=wl(e),this.firedOnUpdate=bl(e,t)}emailsRead(e){this.deliverability=e}confirm(e){this.confirmed.includes(e)||this.confirmed.push(e)}sampled(e){this.sampleFit=Rl(e)}fit(){return this.sampleFit?{...this.sampleFit}:void 0}context(e){let t=yl(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 Sl="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ol="RHZ",Al=/[A-Za-z0-9]{3}RHZ[A-Za-z0-9]{12}/g,tr="000",ki=62**8;function Yt(n,e){let t=n!==null&&/^[A-Za-z0-9]{3}$/.test(n)?n:tr,r="";for(let s=e;r.length===0||s>0;s=Math.floor(s/62))r=Sl[s%62]+r;let o=Pt(`${t}${Ol}${r.padStart(9,"0")}`);if(o===void 0)throw new Error(`No placeholder id for record ${e}`);return o}var Zt=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:Yt(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,c]of Object.entries(o))a!=="Id"&&a!=="attributes"&&(i[a]=c);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=qr(r);if(s)return this.personContactsOf(s,l=>e(t,zr(l),o));let i=Qr(r);if(i)return this.ownersOf(i,l=>e(t,Zr(l),o));let a=eo(r);if(a)return this.teamOf(a,l=>e(t,Xr(a.objectApiName,a.fields,l)),()=>e(t,Yr));let c=Jr(r);return c?this.rolesOf(c,l=>e(t,Vr(l,c.fields),o)):this.namesAPlaceholder(r)?[]:e(t,r,o)}}async rolesOf(e,t){let r=e.opportunities.filter(c=>!this.rowOf(c)),o=r.length>0?await t(r):[],s=e.opportunities.flatMap(c=>{let l=this.rowOf(c),p=l?.objectApiName==="Opportunity"?l.fields[pn]:void 0;return l&&typeof p=="string"&&p!==""?[{id:c,row:l,contact:p}]:[]});if(s.length===0)return o;let i=await this.prefixOf(Gr),a=new Date().toISOString();return[...o,...s.map(({id:c,row:l,contact:p})=>{let u=Yt(i,ki+this.platformTeam.size+this.platformRoles.size);return this.platformRoles.set(u.slice(0,15),l),Hr({...Object.fromEntries(e.fields.map(f=>[f,null])),Id:u,OpportunityId:c,[pn]:p,...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)),c=a.length>0?await t(a):[],l=i.filter(w=>this.rowOf(w)?.objectApiName==="Opportunity");if(l.length===0)return c;let p=Wr[o],u=o===fn,f=u?(await r()).flatMap(w=>typeof w.Id=="string"&&(w.IsTotalValidated===!0||w.IsTotalValidated==="true")?[w.Id]:[]):[void 0],d=await this.prefixOf(u?fn:Ur),m=Kr[o]??{},h=[];for(let w of l){let b=await this.ownerOf(w);if(b!==void 0)for(let S of f){let I=Yt(d,ki+this.platformTeam.size+this.platformRoles.size);this.platformTeam.set(I.slice(0,15),this.rowOf(w)),h.push({Id:I,OpportunityId:w,[p]:b,...S!==void 0?{SplitTypeId:S}:{},...Object.fromEntries(s.map(g=>[g,m[g]??null]))})}}return[...c,...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===jt?[a]:[]);if(s.length===0)return o;let i=await this.prefixOf($r);return[...o,...s.map(a=>{let c=this.rowOf(a);if("Name"in c.fields)return{Id:a,[We]:null};let l=Yt(i,c.seq);return this.personContacts.set(l.slice(0,15),c),{Id:a,[We]:l}})]}namesAPlaceholder(e){for(let[t]of e.matchAll(Al))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 ym(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 Ni="UNKNOWN_ERROR",Ci="INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST",Il=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"]),Ei=new Set(["FIELD_CUSTOM_VALIDATION_EXCEPTION","INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST","FIELD_FILTER_VALIDATION_EXCEPTION"]),kl=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"]}]]),nr="FIELD_CUSTOM_VALIDATION_EXCEPTION";function Om(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 El(n,e,t){if(e.statusCode!==nr||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 Qt(n,e){let t=n.detail?.[e];return typeof t=="number"?t:0}function ji(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 Nl(n,e){if(Il.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 Cl(n,e){let t=n.fields.RecordTypeId;return typeof t=="string"?e.get(t.slice(0,15)):void 0}function Pl(n,e,t,r){let{row:o}=n,s=e.fields[0],i=t===xr?"unique_value_collision":"rehearsal_refusal";return{id:ot(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 Tl(n,e,t,r,o){let{row:s}=n,i=e.statusCode||Ni,a=Nl(s,e),c=n.onUpdate?void 0:El(s.objectApiName,e,o),l=d=>{let m=d===void 0?void 0:s.fields[d];return{statusCode:i,fields:[...e.fields],...a!==void 0?{message:a}:{},...c!==void 0?{rule:c}:{},rowsOfTheRun:n.standsFor,...i==="STRING_TOO_LONG"&&typeof m=="string"?{valueLength:m.length}:{},...Ei.has(i)&&d!==void 0&&!n.onUpdate?{writtenWithoutTheField:!0}:{}}};if(n.onUpdate){let d=e.fields[0];return[{id:ot("rehearsal_update_refusal",s.objectApiName,d,void 0,i),kind:"rehearsal_update_refusal",severity:"warning",source:"rehearsal",objectApiName:s.objectApiName,...d!==void 0?{field:d}:{},value:i,rows:1,detail:l(d),decisions:["exclude_object","ignore"]}]}if(n.linked)return[Pl(n,e,i,l)];let p=kl.get(i);if(p&&e.fields.length>0)return(p.kind==="required_field_missing"?e.fields:e.fields.slice(0,1)).map(m=>{let h=s.fields[m],w=p.kind==="picklist_value_refused",b=w?Cl(s,t):void 0,S=w&&typeof h=="string"?h:void 0,I=S!==void 0?jl(r.get(s.objectApiName)?.get(m),S,b):void 0;return{id:ot(p.kind,s.objectApiName,m,b,S),kind:p.kind,severity:p.severity,source:"rehearsal",objectApiName:s.objectApiName,field:m,...b!==void 0?{recordType:b}:{},...S!==void 0?{value:S}:{},rows:1,detail:{...l(m),...I!==void 0?{reason:I}:{}},decisions:[...p.decisions],...p.severity==="warning"?{defaultDecision:"leave_empty"}:{}}});let u=e.fields[0],f=u!==void 0&&Ei.has(i);return[{id:ot("rehearsal_refusal",s.objectApiName,u,void 0,i),kind:"rehearsal_refusal",severity:f?"warning":"blocking",source:"rehearsal",objectApiName:s.objectApiName,...u!==void 0?{field:u}:{},value:i,rows:1,detail:l(u),decisions:u!==void 0?["leave_empty","exclude_object","ignore"]:["exclude_object","ignore"],...f?{defaultDecision:"leave_empty"}:{}}]}function Pi(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:Ni,message:"",fields:[]}],a=ln(...i.map(c=>Tl(s,c,e,t,r)));for(let c of a){let l=o.get(c.id);if(!l){o.set(c.id,c);continue}let p=Math.max(Qt(l,"valueLength"),Qt(c,"valueLength"));o.set(c.id,{...l,rows:l.rows+1,detail:{...c.detail,...l.detail,rowsOfTheRun:Qt(l,"rowsOfTheRun")+Qt(c,"rowsOfTheRun"),fields:[...new Set([...ji(l),...ji(c)])],...p>0?{valueLength:p}:{}}})}}return ln([...o.values()])}function Fl(n){return n!=null&&n!==""}function vl(n){let e=n.fields.RecordTypeId,t=Object.keys(n.fields).filter(r=>r!=="attributes"&&Fl(n.fields[r])).sort();return[n.objectApiName,typeof e=="string"?e:"",t.join(",")].join("|")}function Ti(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=vl(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 xl(n){let e=n.fields.Status;return[n.objectApiName,Object.keys(n.fields).sort().join(","),typeof e=="string"?e:""].join("|")}function Fi(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=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{updates:[...e.values()],standsFor:t}}function vi(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((c,l)=>c.seq-l.seq)){let c=new Set,l=new Set;for(let u of Object.values(a.fields)){let f=e(u);f&&f.seq!==a.seq&&c.add(f.seq);let d=f?void 0:t(u);d&&d.seq!==a.seq&&r.has(d.seq)&&(c.add(d.seq),l.add(d.seq))}let p=[...c].sort((u,f)=>u-f);o.set(a.seq,p),l.size>0&&i.set(a.seq,[...l].sort((u,f)=>u-f)),s.set(a.seq,p.reduce((u,f)=>Math.max(u,(s.get(f)??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 c=e.get(a);c===void 0?i.add(a):"seq"in c&&c.seq!==o&&i.add(c.seq)}t.set(o,[...i].sort((a,c)=>a-c))}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 tt(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 rr(n,e){let t=new Set;for(let r of n){t.add(r.seq);for(let o of tt(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 sr=5,ir=25,Ml=200,_l=10,Dl="PROCESSING_HALTED",Ll="SandForge_Rehearsal_Rollback__c";function ar(n,e=0){return Math.max(0,ir-n-e-1)}function rn(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 Mi(n,e,t=[],r=new Map){let o=new Map;n.collections.forEach((a,c)=>a.seqs.forEach(l=>o.set(l,c)));let s=new Set([...rn(n.collections.flatMap(a=>a.seqs),e),...t.flatMap(a=>a.contacts??[])]),i=[];for(let a of s){let c=o.get(a),l=r.get(a),p=c??(l===void 0?void 0:"id"in l?-1:o.get(l.seq));p!==void 0&&i.push({account:a,after:p})}return i.sort((a,c)=>a.after-c.after||a.account-c.account)}function Bl(n,e,t){let r=[...e].flatMap(a=>{let c=t.get(a);return c?[c]:[]}).sort((a,c)=>a.objectApiName.localeCompare(c.objectApiName)||a.seq-c.seq),o=[],s,i=new Set;for(let a of r){let c=!i.has(a.objectApiName);(!s||s.seqs.length>=Ml||c&&i.size>=_l)&&(s={level:n,seqs:[]},i=new Set,o.push(s)),s.seqs.push(a.seq),i.add(a.objectApiName)}return o}function or(n,e){return[...n.keys()].sort((t,r)=>t-r).flatMap(t=>Bl(t,n.get(t)??[],e))}function on(n,e){let t=p=>e.levels.get(p)??0,r=[...n].sort((p,u)=>t(u.seq)-t(p.seq)||p.seq-u.seq),o=[],s=[],i=new Set,a=new Map,c=(p,u)=>{let f=new Map([...p].map(([d,m])=>[d,new Set(m)]));for(let d of u){let m=f.get(t(d))??new Set;m.add(d),f.set(t(d),m)}return f},l=p=>{let u=or(p,e.bySeq).length,f=rn([...p.values()].flatMap(d=>[...d]),e).length;return u<=sr&&u+f<ir};for(let p of r){if(i.has(p.seq))continue;let u=[p.seq,...tt(p.seq,e)],f=c(new Map,u);if(!l(f)){s.push(p.seq);continue}let d=c(a,u);l(d)?a=d:(o.push({collections:or(a,e.bySeq)}),a=f);for(let m of u)i.add(m)}return a.size>0&&o.push({collections:or(a,e.bySeq)}),{calls:o,beyond:s.sort((p,u)=>p-u)}}function tn(n){return`rows${n}`}function cr(n){return`update${n}`}var _i="rollback";function nn(n){return`contact${n}`}function $l(n,e,t){let r=o=>t.filter(s=>s.after===o).map(s=>nn(s.account));return[...r(-1),...n.collections.flatMap((o,s)=>[tn(s),...r(s)]),...Array.from({length:e},(o,s)=>cr(s)),_i]}function Di(n,e,t,r,o,s=[],i=new Map,a={of:()=>{},reads:[]}){let{reads:c}=a;if(s.length>ar(n.collections.length,c.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 ${ir} subrequests`);let l=new Map;n.collections.forEach((g,y)=>g.seqs.forEach((R,j)=>l.set(R,`@{${tn(y)}[${j}].id}`)));let p=g=>{let y=l.get(g.seq);if(y!==void 0)return y;let R=i.get(g.seq);if(R!==void 0)return"id"in R?R.id:l.get(R.seq)},u=new Set(c.map(g=>g.account)),f=g=>{let y=t(g);if(y){let j=p(y);return j===void 0?void 0:{sent:j}}let R=a.of(g);return R?u.has(R.seq)?{sent:`@{${nn(R.seq)}.${We}}`}:void 0:{sent:g}},d=g=>g.seqs.map(y=>{let R=e.bySeq.get(y);if(!R)throw new Error(`Row ${y} is not among the rows the run creates`);return R}),m=(g,y)=>({method:"POST",url:`${r}/composite/sobjects`,referenceId:tn(y),body:{allOrNone:!1,records:d(g).map(R=>{let j={attributes:{type:R.objectApiName}};for(let[v,T]of Object.entries(R.fields)){if(v==="attributes"||v==="Id")continue;let C=f(T);if(C===void 0)throw new Error(`${R.objectApiName} row ${R.seq} names a record the run creates that its call does not hold`);j[v]=C.sent}return j})},httpHeaders:{...o}}),h=({account:g})=>{let y=e.bySeq.get(g),R=y?p(y):void 0;if(R===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/${jt}/${R}?fields=${We}`,referenceId:nn(g)}},w=g=>c.filter(y=>y.after===g).map(h),b=[...w(-1),...n.collections.flatMap((g,y)=>[m(g,y),...w(y)])];s.forEach((g,y)=>{let R=l.get(g.rowSeq);if(R===void 0)throw new Error(`An update of ${g.objectApiName} names a record its call does not create`);let j={};for(let[v,T]of Object.entries(g.fields)){if(v==="attributes"||v==="Id")continue;let C=f(T);if(C===void 0)throw new Error(`An update of ${g.objectApiName} names a record the run creates that its call does not hold`);j[v]=C.sent}b.push({method:"PATCH",url:`${r}/sobjects/${g.objectApiName}/${R}`,referenceId:cr(y),body:j,httpHeaders:{...o}})});let S=n.collections[0]?.seqs[0],I=S===void 0?void 0:e.bySeq.get(S);if(!I)throw new Error("A rehearsal call holds no row");return b.push({method:"PATCH",url:`${r}/sobjects/${I.objectApiName}/${zl(I.placeholderId)}`,referenceId:_i,body:{[Ll]:!0}}),{allOrNone:!0,collateSubrequests:!1,compositeRequest:b}}function zl(n){return Pt(`${n.slice(0,3)}000000000000`)??"000000000000000AAA"}var ql=z({body:Re(),httpStatusCode:H(),referenceId:q().optional()}).loose(),Ul=z({compositeResponse:J(ql)}).loose(),en=J(z({errorCode:q().optional(),statusCode:q().optional()}).loose()),Wl=J(z({success:Or()}).loose());function Xt(n){let e=en.safeParse(n.body);return n.httpStatusCode>=400&&e.success&&e.data.length>0&&e.data.every(t=>(t.errorCode??t.statusCode)===Dl)}function Li(n,e,t=0,r=()=>{},o=[]){let s=Ul.safeParse(n);if(!s.success)throw new Error("The target answered the rehearsal with no composite answer");let i=s.data.compositeResponse,a=$l(e,t,o),c=a.length,l=i[c-1];if(i.length!==c||!l)throw new Error(`The target answered ${i.length} subrequests of the ${c} the rehearsal sent`);let p=i.findIndex((m,h)=>m.referenceId!==void 0&&m.referenceId!==a[h]);if(p!==-1)throw new Error(`The target ran the rehearsal's subrequests out of the order sent (${String(i[p]?.referenceId)} in place of ${a[p]}): no verdict can be read from it`);let u=m=>i[a.indexOf(m)];for(let{account:m}of o){let h=u(nn(m));if(h.httpStatusCode<400||Xt(h))continue;let w=en.safeParse(h.body),b=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}${b?`, ${b}`:""}): no verdict can be read past it`)}let f=e.collections.map((m,h)=>{let w=u(tn(h));if(Xt(w))return{kind:"halted"};let b=Wl.safeParse(w.body);if(w.httpStatusCode<400&&b.success){if(b.data.length!==m.seqs.length)throw new Error(`The target answered ${b.data.length} rows of the ${m.seqs.length} a request sent`);return{kind:"rows",outcomes:b.data.map((I,g)=>Tt(I,r(m.seqs[g])??""))}}let S=en.safeParse(w.body);if(w.httpStatusCode>=400&&S.success&&S.data.length>0)return{kind:"refused",errors:S.data.map(hn)};throw new Error(`The target answered a request of the rehearsal with status ${w.httpStatusCode}`)}),d=Array.from({length:t},(m,h)=>{let w=u(cr(h));if(Xt(w))return{kind:"halted"};if(w.httpStatusCode<400)return{kind:"saved"};let b=en.safeParse(w.body);if(b.success&&b.data.length>0)return{kind:"refused",errors:b.data.map(hn)};throw new Error(`The target answered an update of the rehearsal with status ${w.httpStatusCode}`)});if(l.httpStatusCode<400)return{kind:"not_rolled_back",ids:f.flatMap(m=>m.kind==="rows"?m.outcomes.filter(h=>h.success).map(h=>h.id):[])};if(Xt(l)&&dr(f)===-1&&!d.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:f,updates:d}}function dr(n){return n.findIndex(e=>e.kind==="refused"||e.kind==="rows"&&e.outcomes.some(t=>!t.success))}function Bi(n,e,t=()=>{}){let r=new Map,o=dr(e);return n.collections.forEach((s,i)=>{if(o!==-1&&i>o)return;let a=e[i];s.seqs.forEach((c,l)=>{if(a.kind==="refused"){r.set(c,{passed:!1,errors:a.errors});return}let p=a.kind==="rows"?a.outcomes[l]:void 0;if(!p||p.success){r.set(c,{passed:!0});return}let u=Io(p,t(c));r.set(c,{passed:!1,errors:p.errorDetails??[],...u.kind==="linked"?{linkedTo:u.id}:{}})})}),r}function $i(n,e){let t=new Map;if(dr(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 Gl(n,e){let t=e.targetRecordTypes;if(!t)return n;let r=new Set(n.flatMap(s=>s.recordType!==void 0&&ho(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?wo(i):void 0)}return n.map(s=>bo(s,o.get(s.objectApiName)))}async function Vl(n,e){let t=[...new Set(n.filter(({errors:r})=>r.some(o=>o.statusCode===nr)).map(({row:r})=>r.objectApiName))];if(t.length===0||!e.validationRules)return[];try{return await e.validationRules(t)}catch{return[]}}async function Jl(n,e){let t=new Map;for(let{row:s,errors:i,onUpdate:a}of n)if(!a)for(let c of i){let l=c.fields[0];c.statusCode!==Ci||l===void 0||t.set(s.objectApiName,(t.get(s.objectApiName)??new Set).add(l))}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 c=new Map;for(let l of a)!i.has(l.name)||!l.picklistValues||c.set(l.name,{values:l.picklistValues,...l.controllerName?{controllerName:l.controllerName}:{}});r.set(s,c)}return r}var lr=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},sn=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 Hl(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 zi(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 Kl(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,c]of i.outcomes.entries()){let l=s.seqs[a];if(c.success&&c.id.slice(0,15)===r&&l!==void 0)return{seq:l}}}return{id:n}}function Yl(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 c=a?void 0:t(i);c&&(o.add(c.seq),s.add(c.seq))}return{seq:n.seq,objectApiName:n.objectApiName,rowSeq:r.seq,fields:n.fields,needs:[...o],...s.size>0?{contacts:[...s]}:{}}}function ur(n,e,t){let r=new Set(n.collections.flatMap(i=>i.seqs)),o=new Set(rn(r,t)),s=[];for(let i of e){if(!i.needs.every(c=>r.has(c)))continue;let a=(i.contacts??[]).filter(c=>!o.has(c));if(s.length+1>ar(n.collections.length,o.size+a.length))break;for(let c of a)o.add(c);s.push(i)}return s}function qi(n,e){let t=o=>{let s=rr(o.flatMap(c=>c.needs.flatMap(l=>{let p=e.bySeq.get(l);return p?[p]:[]})),e),i=on(s,e),[a]=i.calls;return i.calls.length===1&&i.beyond.length===0&&a&&ur(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 c of n.slice(o+1)){let l=t([...i,c]);l&&(i=[...i,c],a=l)}return{call:a,beyond:r}}return{beyond:r}}function Zl(n,e,t){let r=[...e],o=i=>{let a=new Set(ur(i,r,t));return r=r.filter(c=>!a.has(c)),a.size};for(let i of n)o(i);let s=0;for(;r.length>0;){let{call:i,beyond:a}=qi(r,t),c=new Set(a);if(r=r.filter(l=>!c.has(l)),!i||o(i)===0)break;s++}return n.length+s}async function Mm(n){let e=new Zt(n.keyPrefixOf,n.runningUser);await n.prepare(e);let t=e.rows,r=k=>e.rowOf(k),o=k=>e.personContactOf(k),s=vi(t,r,o),i=Ti(t),a=Fi(e.updated.flatMap(k=>{let O=Yl(k,r,o);return O?[O]:[]})),c=a.updates,l=rr([...i.rows,...c.flatMap(k=>k.needs.flatMap(O=>{let A=s.bySeq.get(O);return A?[A]:[]}))],s),p=k=>i.standsFor.get(k)??1,u=k=>{let O=s.bySeq.get(k)?.placeholderId.slice(0,3);return O===void 0||O===tr?null:O},f=new Map,d=new Map,m=new Map,h=new Map,w=new Map,b=s,S=on(l,s);for(let k of S.beyond)d.set(k,"beyond_a_call");let I=Zl(S.calls,c,s),g=I*sr,y=0;if(I>0){if(n.signal?.aborted)throw new sn(0);n.onProgress?.({phase:"confirming",calls:I}),await n.confirm({rows:t.length,sampled:l.length,updates:zi(c).map(({objectApiName:k,count:O})=>({objectApiName:k,updates:O})),calls:I,maxCalls:g,objects:zi(l).map(({objectApiName:k,count:O})=>({objectApiName:k,rows:O}))})}let R=k=>{let O=f.get(k);return O?.passed===!1&&O.linkedTo===void 0},j=k=>[k,...tt(k,b)].some(R),v=k=>{if(w.has(k.rowSeq))return"record_linked";for(let O of k.needs){if(j(O))return"parent_refused";let A=d.get(O);if(A)return A}};for(;;){if(n.signal?.aborted)throw new sn(y);let k=l.filter(F=>f.has(F.seq)||d.has(F.seq)?!1:tt(F.seq,b).some(R)?(d.set(F.seq,"parent_refused"),!1):!0),O=c.filter(F=>{if(m.has(F.seq)||h.has(F.seq))return!1;let B=v(F);return B?(h.set(F.seq,B),!1):!0});if(k.length===0&&O.length===0)break;if(y>=g){for(let F of k)d.set(F.seq,"call_budget");for(let F of O)h.set(F.seq,"call_budget");break}let A;if(k.length>0){let F=on(k,b);for(let B of F.beyond)d.set(B,"beyond_a_call");A=F.calls[0]}else{let F=qi(O,b);for(let B of F.beyond)h.set(B.seq,"beyond_a_call");A=F.call}if(!A)continue;let N=ur(A,O.filter(F=>!h.has(F.seq)),b);y++,n.onProgress?.({phase:"rehearsing",call:y,calls:Math.max(I,y)});let D=Mi(A,b,N,w),$=Di(A,s,r,n.apiPath,n.writeHeaders,N,w,{of:o,reads:D}),E=Li(await n.composite($),A,N.length,F=>s.bySeq.get(F)?.objectApiName,D);if(E.kind==="not_rolled_back")throw new lr(E.ids,Hl(E.ids,t));let x=new Map;for(let[F,B]of Bi(A,E.collections,u))f.set(F,B),!B.passed&&B.linkedTo!==void 0&&x.set(F,Kl(B.linkedTo,A,E.collections));for(let[F,B]of $i(N,E))m.set(F,B);if(x.size>0){for(let[F,B]of x)w.set(F,B);b=xi(s,w),c=c.map(F=>({...F,needs:F.needs.flatMap(B=>{let W=w.get(B);return W===void 0?[B]:"seq"in W?[W.seq]:[]})}))}}let T=[],C=0,M=0;for(let k of l){let O=f.get(k.seq);if(!O)continue;if(O.passed){C++;continue}let A=O.linkedTo!==void 0;A&&M++,T.push({row:k,errors:O.errors,standsFor:p(k.seq),...A?{linked:!0}:{}})}let P=0,_=0;for(let k of c){let O=m.get(k.seq),A=s.bySeq.get(k.rowSeq);if(!O||!A)continue;let N=a.standsFor.get(k.seq)??1;if(_+=N,O.passed){P++;continue}T.push({row:{...A,fields:{...A.fields,...k.fields}},errors:O.errors,standsFor:N,onUpdate:!0})}let L=new Map;for(let[k,O]of d){let N=`${s.bySeq.get(k)?.objectApiName??""}|${O}`;L.set(N,(L.get(N)??0)+1)}return{gaps:await Gl(Pi(T,n.recordTypeNames,await Jl(T,n),await Vl(T,n)),n),rows:t.length,sampled:l.length,judged:f.size,passed:C,linked:M,notJudged:d.size,notJudgedWhy:[...L].map(([k,O])=>{let[A,N]=k.split("|");return{objectApiName:A,rows:O,reason:N}}),updates:e.updates,updatesJudged:m.size,updatesPassed:P,updatesNotRehearsed:e.updates-_,calls:y,plannedCalls:I}}var Ql="QuoteLineItem",fr="Quote",an="Opportunity",pr="OpportunityLineItem",hr="SyncedQuoteId",wr="QuoteId",br="OpportunityLineItemId",mr=new Set(["Id",wr,br]);function St(n){return n.slice(0,15)}function gr(n,e){let t=n[e];return typeof t=="string"&&t!==""?St(t):void 0}function Lm(n,e){return!n.has(an)||!n.has(fr)||!n.has(pr)?[]:e.get(an)?.some(r=>r.name===hr)!==!0?[]:[{sourceObject:fr,targetObject:pr,relationshipName:`${fr}Before${pr}`,type:"lookup",required:!0}]}function Xl(n,e,t){let r=[...mr,...t.filter(s=>!mr.has(s))].map(V).join(", "),o=s=>s.map(i=>`'${Ue(i)}'`).join(", ");return`SELECT ${r} FROM ${Ql} WHERE ${wr} IN (${o(n)}) AND ${br} IN (${o(e)})`}var eu=200;function tu(n,e){let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t}async function Bm(n,e,t){let r=[],o=[...new Set(e.map(s=>s.product))];for(let s of tu(o,eu)){let i=new Set(s.map(St)),a=[...new Set(e.filter(c=>i.has(St(c.product))).map(c=>c.quote))];r.push(...await n(Xl(a,s,t)))}return r}function $m(n,e,t){let r=new Map;for(let s of e){let i=gr(s,"Id"),a=gr(s,wr),c=gr(s,br);if(!i||!a||!c||t.has(i))continue;let l=`${a}:${c}`;r.set(l,[...r.get(l)??[],s])}let o=new Map;for(let s of n){let i=r.get(`${St(s.quote)}:${St(s.product)}`)?.shift();i&&o.set(s.index,i)}return o}var Ui=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;function nu(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(Ui.test(n)&&Ui.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 zm(n,e,t,r=new Set){let o={};for(let[s,i]of Object.entries(n))mr.has(s)||r.has(s)||!t(s)||nu(i,e[s])||(o[s]=i??null);return o}function qm(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 ru=2e3,ou=3,su=20,Ot=20;function Zm(n,e){let t=Ro(n,e);return{query:r=>t.query(r),describe:r=>t.describe(r),describeGlobal:()=>t.describeGlobal(),queryAll:async r=>{let o=await n.query(r,{scanAll:!0});return yo(n.limitInfo,e),{totalSize:o.totalSize,records:o.records}},serverTime:async()=>(await n.soap.getServerTimestamp()).timestamp}}function Wi(n,e,t){return`${n}:${e.slice(0,15)}:${t}`}function Gi(n,e){return`${n}.${e}`}var iu=[{modified:"LastModifiedDate",by:"LastModifiedById"},{modified:"SystemModstamp"},{}],ke="CreatedById",cn="CreatedDate",au=z({sobjects:J(z({name:q(),keyPrefix:q().nullish()}).loose())}).loose(),cu=n=>new Promise(e=>setTimeout(e,n));function K(n){return n.slice(0,15)}function Vi(n){return n.slice(0,3)}function dn(n){return typeof n=="string"?Date.parse(n):Number.NaN}function nt(n){return typeof n.Id=="string"?n.Id:void 0}function yr(n){return Array.isArray(n)?`[${n.map(yr).join(",")}]`:typeof n=="object"&&n!==null?`{${Object.entries(n).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${yr(r)}`).join(",")}}`:JSON.stringify(n)}var Ji=class{constructor(e){this.deps=e}deps;describes=new Map;async verify(e,t={}){let r=t.now??(()=>new Date),o=t.sleep??cu,s=t.intervalMs??ru,i=Math.max(1,t.maxAttempts??ou),a=t.linkSample??su,c=await this.runEnd(e),l=this.deps.source,p="unavailable"in l?l.unavailable:void 0,u=new Map;if(!("unavailable"in l))for(let g of e.records)u.set(g.objectApiName,await this.linkPlan(l,e,g,a));let f=null,d=null,m=[],h=0,w=this.explaining(e,c),b=w.window?await this.runUser(e):void 0,S=await this.writtenByThePlatformAlone(e,w);for(let g=1;g<=i;g++){h=g,await o(s),m=[];for(let R of e.records)m.push(await this.read(e,R,c,u.get(R.objectApiName),w,b));for(let R of S)m.push(await this.readWrittenByThePlatform(R,w,b));let y=yr(m);if(f!==null&&y===f){d=m;break}f=y}let I=(d??m).map(du);return{verdict:lu(d!==null,I,p),verifiedAt:r().toISOString(),attempts:h,objects:I,...p!==void 0?{linksUnchecked:p}:{}}}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=dn(await r.call(this.deps.target));Number.isFinite(s)&&(t=s-(o+Date.now())/2)}catch{}}return e.runRecordedAt.getTime()+t+Ft}explaining(e,t){let r=new Set;for(let{objectApiName:l,field:p,recordIds:u}of e.leftEmptyByFilter??[])for(let f of u)r.add(Wi(l,f,p));let o=new Set(Object.entries(e.leftEmptyByTheRun??{}).flatMap(([l,p])=>p.map(u=>Gi(l,u)))),s=[...new Set((e.withTheirRecord??[]).flatMap(l=>{let p=e.remapTable[l];return p===void 0?[]:[p]}))],i=e.runStartedAt?.getTime()??Number.NaN,a=Number.isFinite(i)&&Number.isFinite(t),c={from:i-Ft,to:t+Ft};return{emptiedByFilter:r,emptiedByTheRun:o,withTheirRecord:s,createdByRun:new Set(Object.values(e.remapTable).map(K)),...a?{window:c,counted:e.runEndedAt?{from:c.from,to:t}:c}:{}}}async setByAutomation(e,t,r){let o=r.window,s=e.filter(({link:p,createdBy:u})=>o!==void 0&&typeof u=="string"&&p.found!==null&&!r.createdByRun.has(K(p.found)));if(!o||s.length===0)return{explained:[],broken:e.map(({link:p})=>p)};let i=new Map,a=new Map;for(let{link:p}of s){let u=await this.objectOfId(t.referenceTo?.get(p.field)??[],p.found);u!==void 0&&a.set(u,[...a.get(u)??[],p.found])}for(let[p,u]of a)try{let f=await ye(this.deps.target,p,[ke,cn],[...new Set(u)]);for(let d of f){let m=nt(d);m&&i.set(K(m),d)}}catch{}let c=[],l=[];for(let p of e){let{link:u,createdBy:f}=p,d=u.found===null?void 0:i.get(K(u.found)),m=dn(d?.[cn]);s.includes(p)&&typeof f=="string"&&typeof d?.[ke]=="string"&&K(d[ke])===K(f)&&m>=o.from&&m<=o.to?c.push({...u,cause:"automation"}):l.push(u)}return{explained:c,broken:l}}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=>Ct.parse(i))}async linkPlan(e,t,r,o){let s=r.objectApiName,i={fields:[],expected:new Map,sample:[]};try{let[a,c]=await Promise.all([this.describe(this.deps.target,"target",s),this.describe(e,"source",s)]),l=new Set(a.fields.filter(g=>g.type==="reference"&&(g.createable===!0||g.updateable===!0)).map(g=>g.name)),p=new Set(t.fieldExclusions?.[s]??[]),u=t.fieldMappings?.[s]??{},f=c.fields.filter(g=>g.type==="reference"&&!p.has(g.name)).map(g=>({from:g.name,to:u[g.name]??g.name})).filter(({to:g})=>l.has(g)&&!p.has(g));if(f.length===0)return i;let d=new Map,m=new Map;for(let[g,y]of Object.entries(t.remapTable))d.set(K(y),g),m.set(K(g),y);let h=r.ids.slice(0,o).filter(g=>d.has(K(g)));if(h.length===0)return i;let w=await ye(e,s,f.map(g=>g.from),h.map(g=>d.get(K(g)))),b=new Map;for(let g of w){let y=nt(g),R=y?m.get(K(y)):void 0;if(!R)continue;let j=[];for(let{from:v,to:T}of f){let C=g[v],M=typeof C=="string"?m.get(K(C)):void 0;M&&j.push({field:T,expected:M})}j.length>0&&b.set(K(R),j)}let S=[...new Set([...b.values()].flat().map(g=>g.field))],I=new Map(a.fields.filter(g=>S.includes(g.name)).map(g=>[g.name,g.referenceTo??[]]));return{fields:S,expected:b,sample:S.length>0?h:[],referenceTo:I,createdBy:a.fields.some(g=>g.name===ke)}}catch(a){return{...i,unchecked:U(a)}}}async runUser(e){for(let t of e.records){let r=t.ids[0];if(r!==void 0)try{let[o]=await ye(this.deps.target,t.objectApiName,[ke],[r]),s=o?.[ke];if(typeof s=="string"&&/^[A-Za-z0-9]{15,18}$/.test(s))return s}catch{}}}async countInTheWindow(e,t,r){let o=s=>new Date(s).toISOString().replace(/\.\d{3}Z$/,"Z");try{return(await this.deps.target.query(`SELECT COUNT() FROM ${V(e)} WHERE ${ke} = '${t}' AND ${cn} >= ${o(r.from)} AND ${cn} <= ${o(r.to)}`)).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(K)),s=t.withTheirRecord.filter(i=>i.slice(0,3)===r&&!o.has(K(i)));if(s.length===0)return 0;try{let i=await ye(this.deps.target,e.objectApiName,[],s);return new Set(i.map(nt).filter(a=>a!==void 0).map(K)).size}catch{return 0}}async writtenByThePlatformAlone(e,t){let r=new Set(e.records.flatMap(i=>i.ids.slice(0,1)).map(Vi)),o=[...new Set(t.withTheirRecord.map(Vi))].filter(i=>!r.has(i)),s=this.deps.target.describeGlobal;if(o.length===0||!s)return[];try{let{sobjects:i}=au.parse(await s.call(this.deps.target));return o.flatMap(a=>{let c=i.find(l=>l.keyPrefix===a);return c?[{objectApiName:c.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,c={objectApiName:a,expected:t.ids.length,present:0,deletedIds:[],notVisibleIds:[],changed:[],linksChecked:0,broken:[],explained:[],withTheirRecord:0,...o?.unchecked!==void 0?{linksUnchecked:o.unchecked}:{}},l,p={},u;for(let w of iu)try{let b=[w.modified,w.by].filter(S=>!!S);l=await ye(this.deps.target,a,b,t.ids),p=w;break}catch(b){u??=U(b)}if(!l)return{...c,error:u??"The org gave no reason."};let f=new Map;for(let w of l){let b=nt(w);b&&f.set(K(b),w)}let d=t.ids.filter(w=>!f.has(K(w))),m=0;if(d.length>0){let w=await this.recycleBin(a,d);if("unread"in w)c.notVisibleIds=d,c.recycleBinUnread=w.unread;else for(let b of d){let S=w.found.get(K(b));S==="deleted"?c.deletedIds.push(b):S==="there"?m++:c.notVisibleIds.push(b)}}if(c.present=f.size+m,c.withTheirRecord=await this.withTheirRecordThere(t,s),i!==void 0&&s.counted){let w=await this.countInTheWindow(a,i,s.counted);w!==void 0&&(c.createdInTheWindow=w)}let h=new Map(Object.entries(e.removalStamps??{}).map(([w,b])=>[K(w),dn(b)]));if(p.modified&&Number.isFinite(r))for(let w of t.ids){let b=f.get(K(w));if(!b)continue;let S=dn(b[p.modified]);if(!Number.isFinite(S)||S<=r||S<=(h.get(K(w))??Number.NaN))continue;let I=p.by?b[p.by]:void 0;c.changed.push({recordId:w,modifiedAt:String(b[p.modified]),...typeof I=="string"?{modifiedById:I}:{}})}if(o&&o.sample.length>0)try{let w=await ye(this.deps.target,a,o.createdBy?[...o.fields,ke]:o.fields,o.sample),b=new Set(e.writtenWithout?.[a]??[]),S=[];for(let I of w){let g=nt(I);if(g)for(let{field:y,expected:R}of o.expected.get(K(g))??[]){let j=I[y],v=typeof j=="string"&&j!==""?j:null;if(v!==null&&K(v)===K(R)){c.linksChecked++;continue}if(v===null&&s.emptiedByFilter.has(Wi(a,g,y))){c.linksChecked++,c.explained.push({recordId:g,field:y,expected:R,found:v,cause:"lookup-filter"});continue}if(v===null&&s.emptiedByTheRun.has(Gi(a,y))){c.linksChecked++,c.explained.push({recordId:g,field:y,expected:R,found:v,cause:"run"});continue}if(v===null&&b.has(y))continue;c.linksChecked++;let T={recordId:g,field:y,expected:R,found:v};v===null?c.broken.push(T):S.push({link:T,createdBy:I[ke]})}}if(S.length>0){let{explained:I,broken:g}=await this.setByAutomation(S,o,s);c.explained.push(...I),c.broken.push(...g)}}catch(w){c.linksUnchecked=U(w)}return c}async recycleBin(e,t){let r=new Map;try{let o=V(e);for(let s of ne(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 c=a,l=nt(c);if(!l)continue;let p=c.IsDeleted===!0||c.IsDeleted==="true";r.set(K(l),p?"deleted":"there")}}}catch(o){return{unread:U(o)}}return{found:r}}};function du(n){let e=n.explained.filter(r=>r.cause==="run").length,t=n.present+n.withTheirRecord;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,Ot),deletedIds:n.deletedIds.slice(0,Ot),notVisibleIds:n.notVisibleIds.slice(0,Ot),linksChecked:n.linksChecked,linksBroken:n.broken.length,brokenLinks:n.broken.slice(0,Ot),...n.explained.length>0?{linksLeftEmptyByFilter:n.explained.filter(r=>r.cause==="lookup-filter").length,linksSetByAutomation:n.explained.filter(r=>r.cause==="automation").length,...e>0?{linksLeftEmptyByTheRun:e}:{},explainedLinks:n.explained.slice(0,Ot)}:{},...n.error!==void 0?{error:n.error}:{},...n.linksUnchecked!==void 0?{linksUnchecked:n.linksUnchecked}:{},...n.recycleBinUnread!==void 0?{recycleBinUnread:n.recycleBinUnread}:{},...n.withTheirRecord>0?{withTheirRecord:n.withTheirRecord}:{},...n.createdInTheWindow!==void 0&&n.createdInTheWindow>t?{moreInTheWindow:n.createdInTheWindow-t}:{}}}function lu(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 Qm(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 Xm(n){return n?{[an]:[hr]}:{}}function eh(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 Hi=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 Ki=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{Vn as a,Jn as b,nd as c,rd as d,sg as e,pu as f,fs as g,gu as h,mu as i,hu as j,wu as k,bu as l,yu as m,Pe as n,na as o,ju as p,da as q,ka as r,Ca as s,Pa as t,Ta as u,va as v,Ma as w,bs as x,af as y,Hi as z,Ql as A,an as B,pr as C,hr as D,wr as E,br as F,Lm as G,Bm as H,$m as I,zm as J,qm as K,ff as L,pf as M,gf as N,bf as O,yf as P,Is as Q,jf as R,Nf as S,Cf as T,Pf as U,Tf as V,Ff as W,vf as X,xf as Y,Mf as Z,_f as _,Lf as $,Bf as aa,ce as ba,Be as ca,qf as da,Uf as ea,Xa as fa,Cs as ga,Ns as ha,Bs as ia,ue as ja,ic as ka,pt as la,Ke as ma,Xf as na,ep as oa,tp as pa,np as qa,rp as ra,op as sa,sp as ta,ad as ua,ii as va,ug as wa,fg as xa,pg as ya,di as za,ui as Aa,Og as Ba,wp as Ca,xn as Da,bp as Ea,Gs as Fa,yp as Ga,Rp as Ha,Pc as Ia,Sp as Ja,Dc as Ka,Fp as La,vp as Ma,xp as Na,Wc as Oa,$n as Pa,Ki as Qa,Vc as Ra,Jc as Sa,Lp as Ta,Up as Ua,Gn as Va,Wp as Wa,Gp as Xa,Vp as Ya,Jp as Za,oi as _a,Zp as $a,Xp as ab,eg as bb,tg as cb,si as db,Sd as eb,Tg as fb,vg as gb,xg as hb,Bg as ib,$g as jb,zg as kb,Dd as lb,Ld as mb,Bd as nb,em as ob,tm as pb,nm as qb,rm as rb,om as sb,sm as tb,im as ub,am as vb,cm as wb,um as xb,pl as yb,fm as zb,mm as Ab,Ai as Bb,Ii as Cb,ym as Db,Om as Eb,lr as Fb,sn as Gb,Mm as Hb,Zm as Ib,Ji as Jb,Qm as Kb,Xm as Lb,eh as Mb};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a,b,c,d,e,f,g,h,i}from"./chunk-
|
|
7
|
+
import{a,b,c,d,e,f,g,h,i}from"./chunk-W622GUAW.mjs";import"./chunk-IG2MTQRP.mjs";import"./chunk-WR4Q363I.mjs";import"./chunk-O2HDYYUV.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-E5AHXLS6.mjs";import"./chunk-PZPJKATS.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as SCENARIO_PACK_FILE_SUFFIX,b as SCENARIO_PACK_SEARCH,i as findScenarioPack,e as findScenarioPackFiles,f as listScenarioPacks,c as nodeScenarioPackFiles,d as readScenarioPackText,h as saveScenarioPack,g as scenarioPackText};
|
|
@@ -4,7 +4,7 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a as E}from"./chunk-5P4PHJRL.mjs";import{W as Y,ha as R,ia as P}from"./chunk-
|
|
7
|
+
import{a as E}from"./chunk-5P4PHJRL.mjs";import{W as Y,ha as R,ia as P}from"./chunk-JPUR2CFX.mjs";import{a as O,z as _}from"./chunk-LPBMBW3O.mjs";import{F as S,c as X,p as A,q as z}from"./chunk-IFETCRWE.mjs";import{g as w,h as y}from"./chunk-JWTSEDIQ.mjs";import{Wb as u}from"./chunk-TTFDUKUS.mjs";import{b as D,e as W,f as Q,l as L}from"./chunk-7EANH5PY.mjs";import{mkdir as se,rm as M}from"node:fs/promises";import{join as I}from"node:path";var ee=200,ne=Y*10,B=2e3,te=["Id","ContentDocumentId","LinkedEntityId","ShareType","Visibility"],ae=["Id","LatestPublishedVersionId","ContentSize"],de="taking",h=D().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),T=D().regex(/^[A-Za-z]{1,40}$/,"Not a sharing value"),V=L({Id:h,ContentDocumentId:h,LinkedEntityId:h,ShareType:T,Visibility:T}),J=L({Id:h,LatestPublishedVersionId:h.nullable(),ContentSize:W().int().nonnegative().nullable(),anchored:Q()});function Re(e,n){return I(e,`${y}.${n}.ndjson`)}var Ce=V.extend({now:L({ShareType:T,Visibility:T})});function Fe(e,n){let t=new Set(n.map(r=>r.toLowerCase())),i=new Map;for(let r of e){let a=r.keyPrefix;t.has(r.name.toLowerCase())&&typeof a=="string"&&a.length===3&&i.set(a,r.name)}return i}function Te(e,n){let t=e.LinkedEntityId;return typeof t=="string"&&t.length>=15?n.get(t.slice(0,3)):void 0}function oe(e){return e.map(n=>{if(!h.safeParse(n).success)throw new Error(`Not a record id: ${n}`);return`'${n}'`}).join(", ")}function ce(e){let n=u(e);return{objectApiName:n,soql:`SELECT ${te.join(", ")} FROM ${y} WHERE LinkedEntityId IN (SELECT Id FROM ${n})`,scanAll:!1}}function be(e){let n=u(e);return{objectApiName:n,soql:`SELECT COUNT() FROM ${y} WHERE LinkedEntityId IN (SELECT Id FROM ${n})`,scanAll:!1}}function le(e,n){return{objectApiName:u(e),soql:`SELECT ${te.join(", ")} FROM ${y} WHERE LinkedEntityId IN (${oe(n)})`,scanAll:!1}}function fe(e){return{objectApiName:w,soql:`SELECT ${ae.join(", ")} FROM ${w} WHERE Id IN (${oe(e)})`,scanAll:!1}}async function*v(e,n){let t=[];for await(let i of e)t.push(i),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}function*C(e,n){let t=[];for(let i of e)t.push(i),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}function G(e,n,t){let i=e.safeParse(n);if(!i.success)throw new Error(`The org answered a ${t} that does not read as one: ${i.error.message}`);return i.data}function F(e){return e.slice(0,15)}async function xe(e){let{reader:n,folder:t,signal:i}=e,r=e.files??O(E(t.dir)),a=I(t.filesDir,de);await se(a,{recursive:!0,mode:X});let m=z(t),b=A(t);await r.writeFile(m,""),await r.writeFile(b,"");try{let x=new Map,q=0,H=async d=>{for await(let c of v(P(d),B)){let s=c.map(o=>G(V,o,"link"));for(let o of s)x.has(F(o.ContentDocumentId))||x.set(F(o.ContentDocumentId),o.ContentDocumentId);q+=s.length,await r.appendFile(m,s.map(o=>`${JSON.stringify(o)}
|
|
8
8
|
`).join(""))}await M(d,{force:!0})},K=e.linked.map(d=>({...ce(d),file:I(a,`${u(d)}.links.ndjson`)})),re=await R(n,K,i),$=[];for(let[d,c]of re.entries()){if(c.read){await H(K[d].file);continue}let s=e.linked[d];$.push(s);let o=await _.read(t,e.snapshotId,s),l=0;for(let g of C(C(pe(o),ee),ne)){let f=g.map(k=>({...le(s,k),file:I(a,`${u(s)}.links.${l++}.ndjson`)})),N=(await R(n,f,i)).find(k=>!k.read);if(N&&!N.read)throw new Error(`The links of the files of ${s} could not be read whole: ${c.reason}; read by the ids of its records, ${N.reason}`);for(let k of f)await H(k.file)}}let j=0,U=0,Z=new Set;for(let d of C(C(x.values(),ee),ne)){let c=d.map((l,g)=>({...fe(l),file:I(a,`documents.${g}.ndjson`)})),o=(await R(n,c,i)).find(l=>!l.read);if(o&&!o.read)throw new Error(`The files the links name could not be read by their ids: ${o.reason}`);for(let l of c){for await(let g of v(P(l.file),B)){let f=g.map(p=>({...G(J.omit({anchored:!0}),p,"file"),anchored:!0}));for(let p of f)Z.add(F(p.Id));j+=f.length,U+=f.length,await r.appendFile(b,f.map(p=>`${JSON.stringify(p)}
|
|
9
9
|
`).join(""))}await M(l.file,{force:!0})}}if(e.documentsInSnapshot){let d=await _.read(t,e.snapshotId,w);for await(let c of v(d.records(),B)){let s=c.filter(o=>typeof o.Id=="string"&&!Z.has(F(o.Id))).map(o=>({...G(J.omit({anchored:!0}),ue(o),"file"),anchored:!1}));j+=s.length,s.length>0&&await r.appendFile(b,s.map(o=>`${JSON.stringify(o)}
|
|
10
10
|
`).join(""))}}return{documents:j,links:q,anchored:U,...$.length>0?{readByIds:$}:{}}}finally{await M(a,{recursive:!0,force:!0})}}function*pe(e){for(let n=0;n<e.size;n++)yield e.idAt(n)}function ue(e){return{Id:e.Id,LatestPublishedVersionId:e.LatestPublishedVersionId??null,ContentSize:e.ContentSize??null}}async function*ie(e,n,t,i){if(!await e.exists(n))throw new S("damaged",`The checkpoint\u2019s ${i} are not there`);for await(let r of e.readLines(n)){if(r==="")continue;let a;try{a=JSON.parse(r)}catch{throw new S("damaged",`The checkpoint\u2019s ${i} hold a line that is not JSON`)}let m=t.safeParse(a);if(!m.success)throw new S("damaged",`The checkpoint\u2019s ${i} hold a line that does not parse`);yield m.data}}function $e(e,n=O(E(e.dir))){return ie(n,z(e),V,"file links")}function je(e,n=O(E(e.dir))){return ie(n,A(e),J,"files")}export{ee as a,te as b,V as c,Re as d,Ce as e,Fe as f,Te as g,ce as h,be as i,le as j,xe as k,$e as l,je as m};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{q as L}from"./chunk-ZUTYVST5.mjs";import{
|
|
7
|
+
import{q as L}from"./chunk-ZUTYVST5.mjs";import{Hb as C,Jb as R,Ob as S,Pb as m,Sb as b}from"./chunk-TTFDUKUS.mjs";var A="PricebookEntryId",F=Object.fromEntries([["OpportunityLineItem","Opportunity"],["QuoteLineItem","Quote"],["OrderItem","Order"],["ContractLineItem","ServiceContract"]].map(([e,o])=>[e,{record:o,field:L[e]}]));function K(e,o,c){if(!e.has(C))return[];let t=new Map;for(let{sourceObject:n,targetObject:a}of c)t.set(n,[...t.get(n)??[],a]);let i=n=>{let a=new Set,l=[C];for(;l.length>0;){let u=l.pop();if(u===n)return!0;a.has(u)||(a.add(u),l.push(...t.get(u)??[]))}return!1};return[...new Set(o.flatMap(n=>F[n]?.record??[]))].filter(n=>e.has(n)&&!i(n)).map(n=>({sourceObject:n,targetObject:C,relationshipName:`${n}Before${C}`,type:"lookup",required:!0}))}function k(e,o){return[e[R],e[S],o?e[m]:""].map(c=>String(c??"")).join("|")}function h(e,o){return`${e}|${o}`}function Y(e){return h([e.book,e.product,e.model].join("|"),e.currency)}function v(e){let o=e[b];return typeof o=="string"&&o!==""?o:void 0}function x(e){let o=e.wanted??new Map,c=e.prices.flatMap(i=>{let d=i.Id,n=v(i);if(typeof d!="string"||n===void 0)return[];let a=e.writtenIn(n),l=new Set(o.get(d)??[]);l.size===0&&!e.active.has(n)&&a!==void 0&&l.add(a);let u=i[R]===e.standardBookId;return[{row:i,id:d,read:n,alone:a,own:l,standard:u}]}),t=new Map;for(let{row:i,read:d,alone:n,own:a,standard:l}of c){if(l)continue;let u=a.size>0?a:n!==void 0?[n]:[],w=h(k({...i,[R]:e.standardBookId},e.sellingModels),d),p=t.get(w)??new Set;for(let y of u)p.add(y);t.set(w,p)}return c.map(({row:i,id:d,read:n,alone:a,own:l,standard:u})=>{let w=k(i,e.sellingModels),p=new Set(o.get(d)??[]);if(u)for(let y of t.get(h(w,n))??[])p.add(y);if(p.size===0)for(let y of l)p.add(y);return{row:i,id:d,key:w,read:n,alone:a,targets:[...p]}})}function _(e,o){let c=new Map;for(let t of e){if(t.alone!==t.read||!o.has(t.read))continue;let i=h(t.key,t.read);c.has(i)||c.set(i,t)}return c}function W(e){let o=x(e),c=_(o,e.active),t=new Map;for(let{row:i,key:d,targets:n}of o)for(let a of n){let l=h(d,a);c.has(l)||t.has(l)||t.set(l,{book:String(i[R]??""),product:String(i[S]??""),model:e.sellingModels?String(i[m]??""):"",currency:a})}return[...t.values()]}function G(e,o){let c=x(e),t=_(c,e.active),i=new Map(c.map(r=>[r.id,r.key])),d=new Map;for(let r of o){let s=r.Id,f=v(r);if(typeof s!="string"||f===void 0||e.writtenIn(f)!==f)continue;let g=k(r,e.sellingModels),P=h(g,f);if(t.has(P))continue;let M=d.get(P);M!==void 0&&!(r.IsActive===!0&&M.IsActive!==!0)||(d.set(P,r),i.set(s,g))}let n=new Map,a=new Set,l=new Set,u=new Map,w=new Set,p=[],y=(r,s,f)=>{s!==r.read&&p.push({from:r.read,to:s,how:f,forLines:s!==r.alone})},E=[];for(let r of c)for(let s of r.targets){let f=h(r.key,s),g=t.get(f);if(g){n.set(f,g.id),a.add(g.id),g!==r&&y(r,s,"replaced");continue}let P=d.get(f);if(P){n.set(f,String(P.Id)),l.add(P),y(r,s,"replaced");continue}E.push({price:r,to:s})}for(let{price:r,to:s}of E){let f=h(r.key,s);n.has(f)?y(r,s,"replaced"):!a.has(r.id)&&!w.has(r.id)?(w.add(r.id),n.set(f,r.id),s!==r.alone&&u.set(r.id,s),y(r,s,"converted")):y(r,s,"none")}let O=new Map,I=[],B=new Map(c.map(r=>[r.row,r]));for(let r of e.prices){let s=B.get(r);if(!s||s.targets.length===0||a.has(s.id)||w.has(s.id)){I.push(r);continue}let f=s.targets.map(g=>n.get(h(s.key,g))).find(g=>g!==void 0&&g!==s.id);if(f===void 0){I.push(r);continue}O.set(s.id,f)}I.push(...o.filter(r=>l.has(r)));for(let r of c){if(r.targets.length>0||r.alone===void 0)continue;let s=h(r.key,r.alone);n.has(s)||n.set(s,r.id)}return{rows:I,standsFor:O,convertedInto:u,written:n,keys:i,said:p}}function N(e){let o=new Map;for(let{from:c,to:t,how:i,forLines:d}of e){let n=[c,t,i,d?"lines":""].join("|"),a=o.get(n)??{from:c,to:t,how:i,forLines:d,prices:0};a.prices++,o.set(n,a)}return[...o.values()]}function $(e){let o=new Map;for(let{from:c,to:t,prices:i}of e){let d=`${c} \u2192 ${t}`;o.set(d,(o.get(d)??0)+i)}return[...o].map(([c,t])=>`${t} ${c}`).join(", ")}function H(e){return T(N(e))}function T(e){let o=(t,i)=>e.filter(d=>d.forLines===t&&d.how===i);return[[o(!1,"replaced"),"price(s) in a currency the target does not hold active replaced by the source's own price in the currency written, for the same product and price book"],[o(!1,"converted"),"no price in the currency written in the source for the same product and price book, written in it at the amount converted at the source's rates"],[o(!0,"replaced"),"price(s) replaced by the source's own price in the currency of the record their lines belong to, for the same product and price book"],[o(!0,"converted"),"no price in the currency of the record their lines belong to in the source for the same product and price book, written in it at its amount converted"],[e.filter(t=>t.how==="none"),"no price in the currency of the record their lines belong to in the source for the same product and price book, and the price goes in another currency for other lines: the target refuses the lines of a record in it"]].filter(([t])=>t.length>0).map(([t,i])=>`${$(t)}: ${i}`)}export{A as a,F as b,K as c,k as d,h as e,Y as f,W as g,G as h,N as i,H as j,T as k};
|