sandforge 1.79.0 → 1.81.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/bin/sandforge-pipeline.mjs +12 -0
- package/lib/{chunk-BN7A4GRQ.mjs → chunk-2IB7I3IQ.mjs} +1 -1
- package/lib/{chunk-PBI4BYWW.mjs → chunk-2NAIUKVL.mjs} +1 -1
- package/lib/chunk-2OIRJEYE.mjs +7 -0
- package/lib/{chunk-FOVVHGEP.mjs → chunk-2OZG6GRW.mjs} +1 -1
- package/lib/{chunk-5CD257T7.mjs → chunk-2Z54GB6X.mjs} +1 -1
- package/lib/chunk-2ZMGVBLW.mjs +7 -0
- package/lib/{chunk-4NAHW2D3.mjs → chunk-33ZX3A56.mjs} +1 -1
- package/lib/{chunk-4SNDMJP2.mjs → chunk-3AOKLIVE.mjs} +1 -1
- package/lib/{chunk-SIOZXPFG.mjs → chunk-3B5H24ZG.mjs} +1 -1
- package/lib/chunk-43K2C6H2.mjs +7 -0
- package/lib/chunk-4JKR4PTZ.mjs +8 -0
- package/lib/chunk-4L7FBOJS.mjs +8 -0
- package/lib/chunk-5344TZBT.mjs +11 -0
- package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
- package/lib/chunk-55LQD3Y3.mjs +7 -0
- package/lib/chunk-56MPPWLA.mjs +7 -0
- package/lib/chunk-5C5XEVZN.mjs +11 -0
- package/lib/chunk-5CKWGZX4.mjs +9 -0
- package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
- package/lib/{chunk-GNC27UEU.mjs → chunk-5UT2ZBGF.mjs} +1 -1
- package/lib/chunk-5VQNKDFU.mjs +7 -0
- package/lib/chunk-5WGA5CZB.mjs +7 -0
- package/lib/chunk-5ZKCLBTN.mjs +474 -0
- package/lib/chunk-67CC7RAE.mjs +7 -0
- package/lib/{chunk-5O6JOMHS.mjs → chunk-6CDIIFNX.mjs} +1 -1
- package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
- package/lib/{chunk-7UQD6V6F.mjs → chunk-6FMLW7PH.mjs} +1 -1
- package/lib/chunk-6IGEASOF.mjs +7 -0
- package/lib/{chunk-H2PJNIYJ.mjs → chunk-6NADW3OI.mjs} +1 -1
- package/lib/chunk-6SEDOIO3.mjs +10 -0
- package/lib/{chunk-AUTM6H6Z.mjs → chunk-742SSN7I.mjs} +1 -1
- package/lib/chunk-7DALDJMO.mjs +7 -0
- package/lib/chunk-7PK5QDQI.mjs +7 -0
- package/lib/chunk-AELFEK3G.mjs +7 -0
- package/lib/chunk-AITNZWLB.mjs +9 -0
- package/lib/{chunk-HV2MXMGI.mjs → chunk-AJPSGVMD.mjs} +1 -1
- package/lib/{chunk-OTWRDD6L.mjs → chunk-BNO5GIJ6.mjs} +1 -1
- package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
- package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
- package/lib/chunk-BZFIOZS3.mjs +156 -0
- package/lib/{chunk-XBG5SP6Q.mjs → chunk-C4YGSK6W.mjs} +1 -1
- package/lib/chunk-CAFUNR6D.mjs +7 -0
- package/lib/chunk-CULAOP3U.mjs +7 -0
- package/lib/chunk-D62KWDDT.mjs +7 -0
- package/lib/{chunk-BILZ3SSR.mjs → chunk-D7P7DTWL.mjs} +1 -1
- package/lib/chunk-DHGPDSXS.mjs +7 -0
- package/lib/{chunk-ZXH4MBWP.mjs → chunk-DHIW4IO5.mjs} +1 -1
- package/lib/{chunk-NM4MDLK4.mjs → chunk-DMBR24CK.mjs} +1 -1
- package/lib/chunk-DPYTG6DM.mjs +48 -0
- package/lib/chunk-DQR5NDMI.mjs +7 -0
- package/lib/chunk-DXOXLUZA.mjs +7 -0
- package/lib/chunk-E2OBAWSH.mjs +7 -0
- package/lib/chunk-E2YJVSX6.mjs +10 -0
- package/lib/chunk-EAFLDSQ2.mjs +7 -0
- package/lib/{chunk-HCIDVIOW.mjs → chunk-EH5YUA5W.mjs} +1 -1
- package/lib/{chunk-2BVTCNWA.mjs → chunk-EOSEMFPU.mjs} +1 -1
- package/lib/chunk-ETT5GP4P.mjs +13 -0
- package/lib/{chunk-3SRXFZSD.mjs → chunk-FDGFUEK3.mjs} +1 -1
- package/lib/{chunk-3DCUADVK.mjs → chunk-FLNLG43R.mjs} +1 -1
- package/lib/{chunk-HTJ5OGP5.mjs → chunk-FSDO4DJA.mjs} +1 -1
- package/lib/{chunk-HJKM3E56.mjs → chunk-FSZTXLNW.mjs} +1 -1
- package/lib/chunk-FTA5LOVX.mjs +7 -0
- package/lib/chunk-G4VXPS3A.mjs +7 -0
- package/lib/chunk-GF247DA7.mjs +7 -0
- package/lib/{chunk-QRV2OSIS.mjs → chunk-GK7VEYFM.mjs} +1 -1
- package/lib/{chunk-5MMXFWPD.mjs → chunk-GR3NGDVM.mjs} +1 -1
- package/lib/{chunk-P7GSGFJO.mjs → chunk-GTIXJCGS.mjs} +1 -1
- package/lib/{chunk-342FN7AO.mjs → chunk-GWRKS3AL.mjs} +1 -1
- package/lib/{chunk-LQ4DRFUH.mjs → chunk-GYKNCYES.mjs} +1 -1
- package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
- package/lib/chunk-HVC5CYIB.mjs +7 -0
- package/lib/{chunk-EQF2IJS2.mjs → chunk-HYBH5PFM.mjs} +1 -1
- package/lib/chunk-HYOOJVR6.mjs +7 -0
- package/lib/{chunk-TQX3PURV.mjs → chunk-IBURU7T7.mjs} +1 -1
- package/lib/chunk-ICIYL45C.mjs +7 -0
- package/lib/{chunk-K22PA4XL.mjs → chunk-IKGHRYCN.mjs} +1 -1
- package/lib/chunk-IM2XA6JI.mjs +7 -0
- package/lib/{chunk-P2PJYWGQ.mjs → chunk-J6G23RUI.mjs} +1 -1
- package/lib/{chunk-JVL444U5.mjs → chunk-JU2XEKEO.mjs} +1 -1
- package/lib/{chunk-H45UXY6G.mjs → chunk-K55LH4ZQ.mjs} +1 -1
- package/lib/chunk-K5HV4YRO.mjs +7 -0
- package/lib/{chunk-IAZB4WIL.mjs → chunk-K77NR3UK.mjs} +1 -1
- package/lib/chunk-KE2PGD6C.mjs +7 -0
- package/lib/chunk-KGYXLSQ5.mjs +37 -0
- package/lib/{chunk-TEOLMRDO.mjs → chunk-KNIRA333.mjs} +1 -1
- package/lib/chunk-KOQV4WXC.mjs +8 -0
- package/lib/{chunk-PNCONNFJ.mjs → chunk-KRNFVAGC.mjs} +1 -1
- package/lib/chunk-L5FGY6YA.mjs +7 -0
- package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
- package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
- package/lib/{chunk-ZOVSMN5C.mjs → chunk-LO527YLT.mjs} +1 -1
- package/lib/chunk-MAHZMPMZ.mjs +7 -0
- package/lib/{chunk-QQZZMKU3.mjs → chunk-MHW6DV6T.mjs} +1 -1
- package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
- package/lib/{chunk-6EBMEGZB.mjs → chunk-MKNAZPOT.mjs} +1 -1
- package/lib/{chunk-NTDN2JQZ.mjs → chunk-MNITSYI2.mjs} +8 -8
- package/lib/chunk-MO3N5XVV.mjs +341 -0
- package/lib/{chunk-SBIMVCXT.mjs → chunk-MS4FJDFD.mjs} +9 -9
- package/lib/chunk-MWLFFVQV.mjs +8 -0
- package/lib/chunk-N6HHNR6J.mjs +7 -0
- package/lib/chunk-N7J6NJQ6.mjs +7 -0
- package/lib/chunk-NJ3EOEHS.mjs +9 -0
- package/lib/chunk-NWPQF5XR.mjs +7 -0
- package/lib/{chunk-PUOX4NBJ.mjs → chunk-NWVVCZUK.mjs} +1 -1
- package/lib/{chunk-DLDX6RRC.mjs → chunk-O6ADMP36.mjs} +1 -1
- package/lib/chunk-O7DAFE6M.mjs +14 -0
- package/lib/chunk-OEHVAJAB.mjs +7 -0
- package/lib/chunk-OETEC3P7.mjs +7 -0
- package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
- package/lib/chunk-OIIL4NVI.mjs +7 -0
- package/lib/chunk-OMZJ37JI.mjs +15 -0
- package/lib/{chunk-NZ5ZZLKS.mjs → chunk-ONMBSACW.mjs} +1 -1
- package/lib/chunk-OQQHNYR7.mjs +272 -0
- package/lib/{chunk-AAVJ5XVX.mjs → chunk-OU5W7SCB.mjs} +1 -1
- package/lib/{chunk-RSYICMZG.mjs → chunk-OVOLG3AL.mjs} +1 -1
- package/lib/{chunk-F74IHMGL.mjs → chunk-OXKZ4Y3B.mjs} +1 -1
- package/lib/{chunk-W7KFAY55.mjs → chunk-OZNLOV4U.mjs} +1 -1
- package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
- package/lib/chunk-PPGDAUEQ.mjs +7 -0
- package/lib/{chunk-RACDTRZA.mjs → chunk-PYUEHBA6.mjs} +1 -1
- package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
- package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
- package/lib/{chunk-PZTSVQSF.mjs → chunk-QXLZINZB.mjs} +1 -1
- package/lib/chunk-R2BJWO5N.mjs +20 -0
- package/lib/chunk-R6TF26V4.mjs +10 -0
- package/lib/{chunk-P42X3B4D.mjs → chunk-RKALOKAU.mjs} +1 -1
- package/lib/chunk-SQGP46QS.mjs +7 -0
- package/lib/chunk-SU65Z2BA.mjs +7 -0
- package/lib/chunk-SW2NUKQL.mjs +9 -0
- package/lib/chunk-T26C576X.mjs +9 -0
- package/lib/{chunk-3OHPD72J.mjs → chunk-T3PLRQ2T.mjs} +1 -1
- package/lib/chunk-T5VAULLQ.mjs +7 -0
- package/lib/chunk-TEIBWMJM.mjs +7 -0
- package/lib/chunk-TKQQVB2D.mjs +9 -0
- package/lib/{chunk-RAAANPPG.mjs → chunk-TPHXRHOA.mjs} +1 -1
- package/lib/chunk-TQ2TQHTT.mjs +9 -0
- package/lib/{chunk-IEYG5ATY.mjs → chunk-TQM2XJ27.mjs} +1 -1
- package/lib/{chunk-X65MT4W3.mjs → chunk-UCHAZ4ZU.mjs} +1 -1
- package/lib/chunk-UIUPPEFB.mjs +7 -0
- package/lib/{chunk-QPF6C5MX.mjs → chunk-UT27HXE7.mjs} +1 -1
- package/lib/{chunk-J7HVXMSW.mjs → chunk-UUSLTW5V.mjs} +1 -1
- package/lib/chunk-V2QO6KOE.mjs +19 -0
- package/lib/chunk-V473C7LY.mjs +7 -0
- package/lib/chunk-V4RKM4QZ.mjs +8 -0
- package/lib/chunk-VSU74RQ3.mjs +9 -0
- package/lib/chunk-VV3B6IC3.mjs +7 -0
- package/lib/chunk-W2AAGIZF.mjs +7 -0
- package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
- package/lib/chunk-WD47PGUS.mjs +10 -0
- package/lib/{chunk-3CA767QB.mjs → chunk-WEZLXE34.mjs} +1 -1
- package/lib/{chunk-WFEB5X4U.mjs → chunk-WI4HYWV6.mjs} +1 -1
- package/lib/{chunk-AR7BE5O2.mjs → chunk-WM5JI4JI.mjs} +1 -1
- package/lib/chunk-WWTXRWNZ.mjs +7 -0
- package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
- package/lib/{chunk-ZJKCWBRJ.mjs → chunk-X2ZVSQ54.mjs} +1 -1
- package/lib/{chunk-SFURUNJM.mjs → chunk-XC2QKQT5.mjs} +1 -1
- package/lib/chunk-XC54KKKC.mjs +7 -0
- package/lib/chunk-XEB6HZ34.mjs +7 -0
- package/lib/chunk-XGKSSCW7.mjs +7 -0
- package/lib/chunk-XIZ5LMQM.mjs +7 -0
- package/lib/{chunk-RFEO2KAN.mjs → chunk-Y5ZCPY36.mjs} +1 -1
- package/lib/{chunk-TBZMC2VV.mjs → chunk-YCSFP6ER.mjs} +4 -4
- package/lib/{chunk-YBU4Z4QV.mjs → chunk-YHIOS2PU.mjs} +1 -1
- package/lib/chunk-YIGFYZQY.mjs +7 -0
- package/lib/chunk-YJEXE6HZ.mjs +925 -0
- package/lib/{chunk-57VHUYNG.mjs → chunk-YOGMP72T.mjs} +4 -4
- package/lib/chunk-ZRUDYB7O.mjs +7 -0
- package/lib/{chunk-55HEMHEG.mjs → chunk-ZUA5BNAO.mjs} +1 -1
- package/lib/chunk-ZWCRWF7E.mjs +7 -0
- package/lib/{chunk-VHI54FBK.mjs → chunk-ZWZXQTAK.mjs} +53 -53
- package/lib/sandforge-autopilot.mjs +29 -24
- package/lib/sandforge-backup.mjs +67 -32
- package/lib/sandforge-checkpoint.mjs +1 -347
- 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 +101 -101
- package/lib/sandforge-frozen.mjs +1 -257
- package/lib/sandforge-mcp.mjs +33 -14
- package/lib/sandforge-monitor.mjs +7 -7
- package/lib/sandforge-pipeline.mjs +88 -0
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge.mjs +6 -6
- package/package.json +2 -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-42RER7V4.mjs +0 -14
- package/lib/chunk-4GL773D5.mjs +0 -7
- package/lib/chunk-4HFRHFGQ.mjs +0 -7
- package/lib/chunk-4U6NXJNL.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-5P4PHJRL.mjs +0 -9
- package/lib/chunk-5QKTYCWE.mjs +0 -11
- package/lib/chunk-6LAXTAVN.mjs +0 -7
- package/lib/chunk-6MUEPV7M.mjs +0 -9
- package/lib/chunk-6QSM2WIH.mjs +0 -10
- package/lib/chunk-75ADZS6B.mjs +0 -7
- package/lib/chunk-ALJVEUUS.mjs +0 -7
- package/lib/chunk-ALUFROGA.mjs +0 -7
- package/lib/chunk-B45CNPUX.mjs +0 -47
- package/lib/chunk-BS5T3MOQ.mjs +0 -7
- package/lib/chunk-CGWXQX75.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-HJC7AIBK.mjs +0 -7
- package/lib/chunk-HUMEKZT5.mjs +0 -8
- package/lib/chunk-I3JKJTLO.mjs +0 -110
- package/lib/chunk-I7O6C2B5.mjs +0 -8
- package/lib/chunk-KLX67VPL.mjs +0 -7
- package/lib/chunk-L776PUMV.mjs +0 -7
- package/lib/chunk-LRFAIUN7.mjs +0 -7
- package/lib/chunk-LV6G4XTK.mjs +0 -7
- package/lib/chunk-MYTIL2JD.mjs +0 -10
- package/lib/chunk-NEVXIGR6.mjs +0 -10
- package/lib/chunk-NGSMZZDA.mjs +0 -7
- package/lib/chunk-NHWE66K5.mjs +0 -7
- package/lib/chunk-OQOZAPCI.mjs +0 -7
- package/lib/chunk-PA3MKJVH.mjs +0 -7
- package/lib/chunk-QROPNEGY.mjs +0 -14
- package/lib/chunk-QWT2C74M.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-VGW4MXXZ.mjs +0 -7
- package/lib/chunk-VXHDBYMI.mjs +0 -7
- package/lib/chunk-WJY54JO7.mjs +0 -13
- 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-YS4G22C2.mjs +0 -7
- package/lib/chunk-YW2SBL4Z.mjs +0 -7
- package/lib/chunk-Z7X534S4.mjs +0 -10
- package/lib/chunk-ZE6HKRR4.mjs +0 -9
- package/lib/chunk-ZLZRU6MO.mjs +0 -7
- package/lib/chunk-ZPYJPGDK.mjs +0 -7
- package/lib/chunk-ZQOZ4EFW.mjs +0 -7
- package/lib/chunk-ZUTYVST5.mjs +0 -7
- package/lib/chunk-ZYEE34WO.mjs +0 -7
|
@@ -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 Je,c as Rn,d as Re,e as Rt,f as Ot,g as At,h as St,j as Ct,l as
|
|
8
|
-
`),this.count++,this.lines.length>=po&&await this.flush()}async flush(){if(this.lines.length===0)return;let n=this.lines.join("");this.lines=[],await ho(this.file,n,{encoding:"utf8",mode:nn,flag:"a"})}};function Bt(e,n,t){let o=pe(n);return wo(e,`${o}.links${t===void 0?"":`.${t}`}.ndjson`)}function*Wt(e,n){let t=[];for(let o of e)t.push(o),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}var bo=wn({sobjects:hn(Yn)}).loose(),Wn=class{files=new Z;held=new Map;sharings=[];prefixes;now;constructor(n,t){this.prefixes=n,this.now=t}anchoredNow(n){return(this.files.flagsOf(n)&_t)!==0}anchoredThen(n){return(this.files.flagsOf(n)&Tt)!==0}sharingAt(n){let t=this.sharings.indexOf(n);return t>=0?t:(this.sharings.push(n),this.sharings.length-1)}};function Ro(e,n){let t=n.fields.find(s=>s.name.toLowerCase()==="linkedentityid"),o=new Set((t?.referenceTo??[]).map(s=>s.toLowerCase()));if(o.size===0)throw new Error(`The describe of ${me} names no record a link ties a file to.`);return e.objects.map(({objectApiName:s})=>s).filter(s=>{if(s.toLowerCase()===le.toLowerCase()||!o.has(s.toLowerCase()))return!1;let i=e.changes.get(s);return i!==void 0&&!("unread"in i)&&(i.count??0)>0})}async function*Oo(e,n){let t=await We.read(e.folder,e.snapshotId,n);for(let s=0;s<t.size;s++)yield t.idAt(s);let o=e.changes.get(n);if(!(o===void 0||"unread"in o||!o.live))for await(let s of se(o.live.file))typeof s.Id=="string"&&!t.has(s.Id)&&(yield s.Id)}async function Ao(e,n){let{reader:t,previewDir:o,signal:s}=e,i=n.map(l=>({...St(l),file:Bt(o,l)})),r=await Ln(t,i,s),a=[];for(let[l,w]of r.entries()){let p=n[l];if(w.read){a.push({objectApiName:p,file:i[l].file});continue}let c=0,g=Oo(e,p);for await(let d of So(g,Je*In)){let h=[...Wt(d,Je)].map(j=>({...Ct(p,j),file:Bt(o,p,c++)})),R=(await Ln(t,h,s)).find(j=>!j.read);if(R&&!R.read)throw new Error(`The links of the files of ${p} could not be read whole: ${w.reason}; read by the ids of its records, ${R.reason}`);for(let j of h)a.push({objectApiName:p,file:j.file})}}return a}async function*So(e,n){let t=[];for await(let o of e)t.push(o),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}async function xt(e){let n=bo.safeParse(await e.describeGlobal());if(!n.success)throw new Error("The org\u2019s global describe does not read as one.");let t=Ot(n.data.sobjects,e.objects.map(({objectApiName:a})=>a)),o=Ro(e,await e.linkDescribe),s=await Ao(e,o),i=new Wn(t,s);for await(let a of Fn(e.folder))i.files.add(a.Id,Mt|(a.anchored?Tt:0));let r=await vn.read(e.folder);for await(let a of Bn(e.folder))i.held.set($n(Gt(a,r)),i.sharingAt($t(a)));for(let{file:a}of s)for await(let l of se(a))typeof l.ContentDocumentId=="string"&&i.files.add(l.ContentDocumentId,_t);return i}function Gt(e,n){let t=Be(e.LinkedEntityId),o=t===void 0?void 0:n.currentOf(t);return o===void 0?e:{...e,LinkedEntityId:o}}async function Pn(e,n,t,o,s){for(let i of o)for await(let r of dn(n(t,i)))typeof r.Id=="string"&&e.add(r.Id,s)}async function Ft(e){let n=0;for await(let t of dn(e))typeof t.Id=="string"&&n++;return n}async function Et(e,n,t){let o=new Map;if(n.length===0)return o;let s=Le([...n],Je).map(a=>({objectApiName:le,soql:`SELECT ${ko.join(", ")} FROM ${le} WHERE Id IN (${a})`,scanAll:!0})),r=(await ve(e,s,(a,l)=>{for(let w of l){let p=Be(w.Id);p!==void 0&&o.set(p,w)}},t)).find(a=>!a.read);if(r&&!r.read)throw new Error(`The files the checkpoint names could not be read by their ids: ${r.reason}`);return o}function Co(e,n){return n===void 0||n.version===null||e.LatestPublishedVersionId===null?!1:Be(n.version)!==Be(e.LatestPublishedVersionId)}async function Ut(e){let{anchors:n,reader:t,classFileOf:o,signal:s}=e,i=n.files,r=le;await Pn(i,o,r,Cn.toDelete,_n),await Pn(i,o,r,Cn.comesBack,An),await Pn(i,o,r,Cn.lost,Sn);let a=new Map,l=e.fileChanges;if(!("unread"in l)){for(let D of[l.live,l.deleted])if(D!==void 0)for await(let L of se(D.file)){let N=Be(L.Id);N!==void 0&&(i.add(String(L.Id),Dt),a.set(N,{version:vt(L.LatestPublishedVersionId),size:Tn(L.ContentSize)}))}}let w=await We.read(e.folder,e.snapshotId,r),p=D=>(i.flagsOf(D)&Dt)===0&&!w.has(D),c=new Ge(o(r,"createdSince")),g=new Ge(o(r,"deletedWhileTaken")),d=new Ge(o(r,"goneForGood")),f=new Ge(o(r,"newFileVersion")),h=0,b=0,R=async D=>{let L=await Et(t,D.filter(N=>N.anchored&&p(N.Id)).map(N=>N.Id),s);for(let N of D){if(!N.anchored)continue;let V=Be(N.Id)??"",J=a.get(V);if(p(N.Id)){let x=L.get(V);if(x===void 0){i.add(N.Id,Sn),await d.add({Id:N.Id});continue}J={version:vt(x.LatestPublishedVersionId),size:Tn(x.ContentSize)},x.IsDeleted===!0&&(i.add(N.Id,An),await g.add({Id:N.Id}))}let Y=i.flagsOf(N.Id);(Y&Sn)===0&&((Y&An)!==0&&(h+=J?.size??N.ContentSize??0),Co(N,J)&&await f.add({Id:N.Id}))}},j=[];for await(let D of Fn(e.folder))j.push(D),j.length>=Je*In&&(await R(j),j=[]);await R(j);let C=new Z,v=[],O=async D=>{let L=await Et(t,D,s);for(let N of D){let V=L.get(Be(N)??"");V===void 0||V.IsDeleted===!0||yo(V.CreatedDate)>=e.t0s&&(i.add(N,_n),await c.add({Id:N}),v.push(V))}},B=[];for(let{file:D}of n.now)for await(let L of se(D)){let N=L.ContentDocumentId;typeof N!="string"||(i.flagsOf(N)&Mt)!==0||!p(N)||C.add(N)&&(B.push(N),B.length>=Je*In&&(await O(B),B=[]))}await O(B);for await(let D of dn(o(r,"createdSince"))){let L=Be(D.Id);L!==void 0&&(b+=a.get(L)?.size??0)}for await(let D of dn(o(r,"broughtBackSince")))b+=a.get(Be(D.Id)??"")?.size??0;for(let D of v)b+=Tn(D.ContentSize)??0;for(let D of[c,g,d,f])await D.flush();return{files:{...await Po(e),outsideAdded:await Ft(o(r,"outsideAdded")),outsideDeleted:await Ft(o(r,"outsideDeleted")),storage:{bringBack:h,undo:b},...e.queryAllFiles?{}:{blindSpot:!0}},createdSince:c.count,deletedWhileTaken:g.count,goneForGood:d.count,newFileVersion:f.count,changedBy:v}}async function Po(e){let{anchors:n,classFileOf:t}=e,o=new Z,s=new Set;for(let{objectApiName:c}of e.objects){if(c.toLowerCase()===le.toLowerCase())continue;if(!e.told.has(c)){for(let[d,f]of n.prefixes)f.toLowerCase()===c.toLowerCase()&&s.add(d);continue}let g=(d,f)=>Pn(o,t,c,d,f);await g(Mn.toDelete,Nt),await g(Mn.comesBack,jt),await g(Mn.lost,Lt)}let i=c=>s.has(c.LinkedEntityId.slice(0,3)),r=c=>new Ge(Re(e.previewDir,c)),a=r("linkAdded"),l=r("linkRemoved"),w=r("linkChanged");for(let{file:c}of n.now)for await(let g of se(c)){let d=Rn.safeParse(g);if(!d.success)throw new Error(`The org answered a link that does not read as one: ${d.error.message}`);let f=d.data,h=$n(f),b=n.held.get(h);if(b!==void 0){if(n.held.set(h,b|On),i(f)||n.sharings[b&~On]===$t(f))continue;let[R,j]=(n.sharings[b&~On]??"").split("/"),C={...f,ShareType:R,Visibility:j,now:{ShareType:f.ShareType,Visibility:f.Visibility}};await w.add(C);continue}i(f)||(n.files.flagsOf(f.ContentDocumentId)&_n)===0&&(o.flagsOf(f.LinkedEntityId)&Nt)===0&&await a.add(f)}let p=await vn.read(e.folder);for await(let c of Bn(e.folder)){let g=Gt(c,p);((n.held.get($n(g))??0)&On)!==0||i(g)||(n.files.flagsOf(g.ContentDocumentId)&(An|Sn))===0&&(o.flagsOf(g.LinkedEntityId)&(jt|Lt))===0&&await l.add(g)}for(let c of[a,l,w])await c.flush();return{unlink:a.count,relink:l.count,updateLinks:w.count}}async function zt(e){let{anchors:n,reader:t,classFileOf:o,signal:s}=e,i=[];for(let l of Cn.toDelete)for await(let w of dn(o(le,l)))typeof w.Id=="string"&&i.push(w.Id);if(i.length===0)return{links:0,files:0};let r=new Map,a=0;for(let l of Wt(Le(i,Je),In)){let w=l.map(g=>({objectApiName:me,soql:`SELECT Id, ContentDocumentId, LinkedEntityId FROM ${me} WHERE ContentDocumentId IN (${g})`,scanAll:!1})),c=(await ve(t,w,(g,d)=>{for(let f of d){let h=f.LinkedEntityId,b=f.ContentDocumentId;typeof h!="string"||typeof b!="string"||h.startsWith(mo)||At({LinkedEntityId:h},n.prefixes)===void 0&&(a++,r.set(b.slice(0,15),b))}},s)).find(g=>!g.read);if(c&&!c.read)throw new Error(`The links of the files to delete to what the checkpoint does not hold could not be read: ${c.reason}`)}if(r.size>0){let l=new Ge(o(le,"outsideParents"));for(let w of r.values())await l.add({Id:w});await l.flush()}return{links:a,files:r.size}}var Gn=Object.freeze({kind:"org",notHeld:new Map,heldAs:()=>"org",unseenOf:()=>Promise.resolve([]),requests:()=>0,diffAccess:()=>({kind:"org"})});function xn(e){return e.slice(0,15)}function Io(e,n,t,o){let s=n.detail!==void 0?` (${n.detail})`:"";switch(n.reason){case"noViewAll":case"noModifyAll":return`${t} ${o} View All and Modify All on ${e}`;case"parentNotSeen":return`${t} ${o} View All and Modify All on every record ${e} hangs from`+s;case"activities":return`${t} doesn't have View All Data and Modify All Data, which tasks and events need: Salesforce has no View All for activities`;case"catalog":return`${t} doesn't have View All Data and Modify All Data, which products and price books need: Salesforce has no View All or Modify All for them`;case"filesNotProven":return`${t} doesn't have View All Data and Modify All Data, which files need: nothing else proves who sees every file`;case"settingNotProven":return`${t} doesn't have View All Data and Modify All Data, which custom settings need: no permission on an object proves who sees and writes every row`}}async function ss(e){let{grants:n,reader:t}=e;if(n.kind==="org"||e.userId===void 0)return Gn;let o=e.checkpoint.objects,s=o.filter(f=>f.customSetting!==void 0).map(f=>f.objectApiName),i=new Map,r=n.requests,a=async f=>{let h=[...new Set(f)].filter(j=>!i.has(j.toLowerCase()));if(h.length===0)return;let b=t.calls(),R=await Promise.allSettled(h.map(j=>t.describe(j)));r+=t.calls()-b,R.forEach((j,C)=>{if(j.status==="rejected"&&j.reason instanceof te)throw j.reason;let v=j.status==="fulfilled"&&"body"in j.value?j.value.body:void 0,O=tn.safeParse(v);i.set(h[C].toLowerCase(),O.success?O.data:void 0)})},l=()=>[...i.values()].filter(f=>f!==void 0),w=async f=>{let h=f.filter(R=>!n.objects.has(R.toLowerCase()));await a(h);let b={grants:n.objects,describes:l(),customSettings:s};return await a(Pt(f,b)),It(f,{...b,describes:l()})},p=await w(o.map(f=>f.objectApiName)),c=xn(e.userId)===xn(e.checkpoint.takenBy.userId)?"no longer has":"doesn't have",g=new Map,d=new Map;for(let[f,h]of p)"access"in h?g.set(f,h.access):d.set(f,Io(f,h,e.username,c));return{kind:"perObject",userKey:xn(e.userId),notHeld:d,heldAs:f=>g.get(f),unseenOf:async f=>{let h=await w(f);return f.filter(b=>{let R=h.get(b);return R===void 0||!("access"in R)})},requests:()=>r,diffAccess:()=>({kind:"perObject",requests:r})}}var Lo=["giveBack","touched","createdSince","broughtBackSince","comesBackWithParent","unexplained","inBin","withParent","deletedWhileTaken","toRecreate","goneForGood","convertedLead","activatedContract","carrier","deletedWithCreatedParent","deletedWithParentOutside","deletedByOther","outOfReach","undoCannot","outsideParents","outsideAdded","outsideDeleted","newFileVersion"],vo="Lead",Bo="IsConverted",Fo="Contract",Eo="Status",qt="StatusCode",Mo="Activated",To=["createdSince","broughtBackSince"];function X(e,n,t){return jo(e,`${pe(n)}.${t}.ndjson`)}var Dn=1e3,_o=1440*6e4,$o=60*6e4,Wo=100,xo=2e3,Jt=["LastModifiedById","LastModifiedDate"];function ee(e){return typeof e=="string"&&e.length>=15?e.slice(0,15):void 0}function ke(e){let n=en(e);return n===null?Number.NaN:Date.parse(n)}function Hn(e){return e.toLowerCase()===le.toLowerCase()}function Go(e){return e==null||e===""}function Ie(e,n){let t=n.toLowerCase();return e.find(o=>o.toLowerCase()===t)}function Uo(e){return!e.leftOutFields.some(n=>n.reason==="base64")}var fn=class{constructor(n){this.file=n}file;lines=[];written=!1;count=0;async add(n){this.lines.push(`${JSON.stringify(n)}
|
|
9
|
-
`),this.count++,this.lines.length>=xo&&await this.flush()}async flush(){if(this.lines.length===0)return;let n=this.lines.join("");this.lines=[],await No(this.file,n,{encoding:"utf8",mode:nn,flag:this.written?"a":"w"}),this.written=!0}async discard(){this.lines=[],this.written&&await qn(this.file,{force:!0})}};async function Kn(e,n){await Promise.all(Lo.map(t=>qn(X(e,n,t),{force:!0})))}var Un=class{constructor(n){this.activeFrom=n}activeFrom;counts=new Map;active=new Set;add(n){let t=n.LastModifiedById;typeof t!="string"||t===""||(this.counts.set(t,(this.counts.get(t)??0)+1),ke(n.LastModifiedDate)>=this.activeFrom&&this.active.add(t))}byUser(){return Object.fromEntries([...this.counts].sort(([n],[t])=>n<t?-1:n>t?1:0))}};function Qt(e,n){let t,o=async()=>{let s=new Set;try{for await(let i of se(rt(e,n))){let r=ee(i.Id);r!==void 0&&s.add(r)}}catch(i){throw i.code!=="ENOENT"?i:new Error(`The checkpoint\u2019s list of what ${n} held in the recycle bin is not on this machine.`)}return s};return async s=>(await(t??=o())).has(s)}async function zo(e,n,t,o){let s=pe(n.objectApiName),i=n.readMode==="scanAllLive",r=i?" AND IsDeleted = false":"",a=async p=>{let c=e.lane(),g=[];try{let d=await pt(c,{objectApiName:s,soql:p,scanAll:i},f=>{g.push(...f)});if(!d.read)throw new Error(d.reason);return g}finally{c.close()}},l=t.length>Wo?rn/4:rn,w=new Map;for(let p of Le(o,l)){let c=await nt(`SELECT ${t.join(", ")} FROM ${s} WHERE Id IN (${p})${r}`,a,{stamp:"SystemModstamp",...i?{idsWhere:"IsDeleted = false"}:{}});for(let g of c){let d=ee(g.Id);d!==void 0&&w.set(d,g)}}return w}var qo=/__(?:c|pc|s)$/i,Ho=/^(.+)__[A-Za-z]+__s$/i,Ko=/^(.+)__pc$/i,Vo=/^[A-Za-z][A-Za-z0-9_]*$/,Jo=200;function Qo(e,n){if(!qo.test(n)||!Vo.test(n))return;let t=Ko.exec(n);if(t)return{entity:je,name:`${t[1]}__c`};let o=Ho.exec(n);return o?{entity:e,name:`${o[1]}__c`}:{entity:e,name:n}}var Zo=hn(wn({QualifiedApiName:Xn()}).loose());function Xo(e,n){let t=`SELECT QualifiedApiName FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName = '${pe(e)}' AND QualifiedApiName IN (`,o=r=>`${t}${r.map(a=>`'${a}'`).join(", ")})`,s=[],i=[];for(let r of n){let a=[...i,r],l=a.length>Jo||encodeURIComponent(o(a)).length>14e3;i.length>0&&l?(s.push({soql:o(i),names:i}),i=[r]):i=a}return i.length>0&&s.push({soql:o(i),names:i}),s}async function Yo(e,n){let t=new Map,o=new Map;for(let[r,a]of n){let l={removed:[],hidden:[]};t.set(r,l);for(let w of a){let p=Qo(r,w);if(p===void 0){l.hidden.push(w);continue}let c=o.get(p.entity)??new Map;o.set(p.entity,c);let g=p.name.toLowerCase(),d=c.get(g)??{name:p.name,fields:[]};c.set(g,d),d.fields.push({objectApiName:r,field:w})}}let s=0,i=new Map;for(let[r,a]of o){let l=new Set,w=new Map,p=Xo(r,[...a.values()].map(({name:c})=>c));for(let c of p){s++;try{let g=await e.tooling(c.soql);if(!g.done)throw new Error("FieldDefinition answered more than one page");let d=Zo.safeParse(g.records);if(!d.success)throw new Error("FieldDefinition answered rows with no field name");for(let f of d.data)l.add(f.QualifiedApiName.toLowerCase())}catch(g){if(g instanceof te)throw g;let d=Pe(g);for(let f of c.names)w.set(f.toLowerCase(),d)}}for(let[c,{fields:g}]of a){let d=w.get(c);for(let{objectApiName:f,field:h}of g){let b=t.get(f);if(b!==void 0)if(d!==void 0){let R=i.get(f)??{fields:[],reasons:[]};i.set(f,R),R.fields.push(h),R.reasons.includes(d)||R.reasons.push(d)}else l.has(c)?b.hidden.push(h):b.removed.push(h)}}}for(let[r,a]of t){a.removed.sort(),a.hidden.sort();let l=i.get(r);l!==void 0&&(a.uncertain={fields:l.fields.sort(),...l.reasons.length>0?{reason:l.reasons.join("; ")}:{}})}return{gone:t,requests:s}}async function Ht(e,n,t){let{checkpoint:o,folder:s,reader:i}=e,r=new Date(Date.parse(o.readFrom)-_o).toISOString(),a=await Promise.allSettled(n.map(({objectApiName:h})=>i.describe(h,r))),l,w=new Map,p=new Map;for(let[h,b]of a.entries()){let R=n[h].objectApiName;if(b.status==="rejected"){if(b.reason instanceof te)throw b.reason;w.set(R,{unread:`The org did not answer the describe of ${R}: ${Pe(b.reason)}`});continue}if("notModified"in b.value){w.set(R,{gone:new Set});continue}let j=tn.safeParse(b.value.body);if(!j.success){w.set(R,{unread:`The describe of ${R} does not read as one.`});continue}t.set(R,j.data);try{let C=(await(l??=ct(s,o.objects))).get(R);if(C===void 0)throw new Error(`The checkpoint holds no field prints of ${R}.`);p.set(R,st(C,it(j.data.fields)))}catch(C){w.set(R,{unread:Pe(C)})}}let c=new Map(n.map(h=>[h.objectApiName,new Set(bn(h.objectApiName,h.fields,o.ignoredFields).map(b=>b.toLowerCase()))])),g=(h,b)=>b.filter(R=>c.get(h)?.has(R.toLowerCase())===!0),d=new Map([...p].map(([h,b])=>[h,g(h,b.removed)]).filter(([,h])=>h.length>0)),f=d.size>0?await Yo(i,d):{gone:new Map,requests:0};for(let[h,{removed:b,added:R,changed:j}]of p){let C=f.gone.get(h);w.set(h,{...g(h,b).length+R.length+j.length>0?{drift:{removed:C?.removed??[],added:R,changed:j,...C!==void 0&&C.hidden.length>0?{hidden:C.hidden}:{},...C?.uncertain!==void 0?{uncertain:C.uncertain}:{}}}:{},gone:new Set(b.map(v=>v.toLowerCase()))})}return{now:w,requests:f.requests}}function ei(e,n){let t=i=>{let r=n.get(i);return r!==void 0&&!("unread"in r)&&r.moved},o=e.find(({objectApiName:i})=>i===je),s=o!==void 0&&Ie(o.fields,an)!==void 0&&t(je);return e.filter(({objectApiName:i})=>t(i)||s&&i===mn)}function ni(e,n){let t=[...e.cascadeParents,...e.restrictParents??[]].filter(s=>!n.has(s.toLowerCase()));if(e.customSetting!==void 0){let s=Ie(e.fields,kn(e.customSetting));s!==void 0&&!n.has(s.toLowerCase())&&!t.includes(s)&&t.push(s)}if(Hn(e.objectApiName))for(let s of dt){let i=Ie(e.fields,s);i!==void 0&&!n.has(i.toLowerCase())&&t.push(i)}let o=Ie(e.fields,an);if(e.objectApiName===je&&o!==void 0){let s=Ie(e.fields,"AccountId");for(let i of[o,s])i!==void 0&&!n.has(i.toLowerCase())&&t.push(i)}return[...t,...Jt]}async function ti(e,n,t){let{folder:o,checkpoint:s}=e.input,i=new Map,r=new Map;for(let{objectApiName:a,cascadeParents:l,restrictParents:w=[]}of n){let p=t.get(a);if(!p||"unread"in p||!p.deleted||p.deleted.rows===0)continue;let c=new Map,g=new Map;try{let d=await We.read(o,s.snapshotId,a),f=Qt(o,a);for await(let h of se(p.deleted.file)){let b=ee(h.Id);if(b===void 0)continue;let R=v=>v.map(O=>ee(h[O])).filter(O=>O!==void 0&&O!==b),j=ee(h.LastModifiedById),C=()=>({objectApiName:a,id:String(h.Id),stamp:ke(h.SystemModstamp),parents:R(l),restricts:R(w),...j!==void 0?{by:j}:{}});if(!d.retired(h.Id)){if(!d.has(h.Id)){if(await f(b)){g.set(b,C());continue}if(ke(h.CreatedDate)>=e.t0s&&g.set(b,C()),!(ke(h.CreatedDate)<e.t0s))continue}c.set(b,C())}}}catch(d){if(d instanceof te)throw d;continue}for(let[d,f]of c)i.set(d,f);for(let[d,f]of g)r.set(d,f)}return{back:i,gone:r}}function oi(e,n){let t=s=>e.get(s)?.stamp??n.get(s)?.stamp,o=new Set;for(let s of[e,n])for(let[i,r]of s)[...r.parents,...r.restricts].some(l=>(t(l)??0)>r.stamp)&&o.add(i);return zn(o,e,n),o}function zn(e,n,t){let o=s=>n.get(s)?.stamp??t.get(s)?.stamp;for(let s=e.size>0;s;){s=!1;for(let i of[n,t])for(let[r,a]of i){if(e.has(r))continue;a.parents.some(w=>e.has(w)&&o(w)===a.stamp)&&(e.add(r),s=!0)}}for(let s of e)n.delete(s)}function ii(e,n){if(n===void 0)return new Set;let t=[...e].filter(([,o])=>o.by!==n).map(([o])=>o);return Zt(t,e)}function Zt(e,n){let t=new Set(e);for(let o=t.size>0;o;){o=!1;for(let[s,i]of n){if(t.has(s))continue;i.parents.some(a=>t.has(a)&&n.get(a)?.stamp===i.stamp)&&(t.add(s),o=!0)}}return t}function si(e,n,t){let o=new Map(e.map(l=>[l.objectApiName,l.undeletable])),s=new Set,i=new Set,r=(l,w)=>l.parents.find(p=>!w.has(p)&&t.get(p)?.stamp===l.stamp),a=l=>l.parents.some(w=>n.get(w)?.stamp===l.stamp);for(let l of[...n.values()]){if(a(l))continue;let w=new Set,p=[],c=r(l,w),g=!1;for(;c!==void 0;){w.add(c),p.push(c);let h=t.get(c);if(!h)break;if(a(h)){g=!0;break}c=r(h,w)}let d=p[p.length-1];if(d===void 0||g)continue;let f=t.get(d);if(!(!f||o.get(f.objectApiName)!==!0)){s.add(d);for(let h of p.slice(0,-1))i.add(h)}}for(let l of[...s,...i]){let w=t.get(l);w&&n.set(l,w)}return s}function ri(e,n,t){let o=new Map;for(let[s,i]of e){if(t.has(s)){o.set(s,"deletedWithParentOutside");continue}if(n.has(s))continue;i.parents.some(a=>!e.has(a)&&n.get(a)?.stamp===i.stamp)&&o.set(s,"deletedWithCreatedParent")}for(let s=o.size>0;s;){s=!1;for(let[i,r]of e){if(o.has(i))continue;let a=r.parents.find(w=>o.has(w)&&e.get(w)?.stamp===r.stamp),l=a===void 0?void 0:o.get(a);l!==void 0&&(o.set(i,l),s=!0)}}for(let s of o.keys())e.delete(s);return o}async function ai(e,n,t,o,s,i){let r=new Set,a=new Set,l=new Set(n.map(({objectApiName:d})=>d.toLowerCase())),w=new Map(n.map(d=>[d.objectApiName,d])),p=new Map;for(let[d,f]of t)o.has(d)||s.has(d)||f.parents.some(b=>(t.get(b)??o.get(b))?.stamp===f.stamp)||p.set(f.objectApiName,[...p.get(f.objectApiName)??[],f]);if(p.size===0)return{outside:r,stuck:a,requests:0};let c=e.reader.calls(),g=async d=>{try{return await i(d)}catch(f){if(f instanceof te)throw f;return}};for(let[d,f]of p){let h=w.get(d),b=await g(d);if(!h||!b)continue;let R=new Set([...h.cascadeParents,...h.restrictParents??[]].map(P=>P.toLowerCase())),j=b.fields.filter(P=>P.type==="reference"&&!R.has(P.name.toLowerCase())&&(P.referenceTo??[]).some(H=>!l.has(H.toLowerCase())));if(j.length===0)continue;let C=[...new Set(j.flatMap(P=>(P.referenceTo??[]).filter(H=>!l.has(H.toLowerCase()))))],v=await Promise.all(C.map(g)),O=new Map;if(v.forEach((P,H)=>{if(!P)return;let Q=P.keyPrefix;for(let z of P.childRelationships??[]){if(z.cascadeDelete!==!0||z.childSObject.toLowerCase()!==d.toLowerCase())continue;let fe=j.find(oe=>oe.name.toLowerCase()===z.field.toLowerCase());fe&&O.set(fe.name,[...O.get(fe.name)??[],{object:C[H],...typeof Q=="string"?{prefix:Q}:{}}])}}),O.size===0)continue;let B=[...O.keys()].map(pn),W=pe(d),D=f.map(P=>P.id),L=new Map,N=Le(D).map(P=>({objectApiName:W,soql:`SELECT Id, ${B.join(", ")} FROM ${W} WHERE Id IN (${P}) AND IsDeleted = true`,scanAll:!0}));if((await ve(e.reader,N,(P,H)=>{for(let Q of H){let z=ee(Q.Id);if(z!==void 0)for(let[fe,oe]of O){let ue=Q[fe];if(typeof ue!="string"||ee(ue)===void 0)continue;let Ae=oe.length===1?oe[0]:oe.find(he=>he.prefix!==void 0&&ue.startsWith(he.prefix));Ae&&L.set(z,[...L.get(z)??[],{object:Ae.object,id:ue}])}}},e.signal)).some(P=>!P.read))continue;let J=new Map;for(let P of L.values())for(let{object:H,id:Q}of P)J.set(H,[...J.get(H)??[],Q]);let Y=[];for(let[P,H]of J){let Q=pe(P);for(let z of Le([...new Set(H)]))Y.push({object:P,read:{objectApiName:Q,soql:`SELECT Id, IsDeleted, SystemModstamp FROM ${Q} WHERE Id IN (${z})`,scanAll:!0}})}let x=new Map;await ve(e.reader,Y.map(({read:P})=>P),(P,H)=>{for(let Q of H){let z=ee(Q.Id);z!==void 0&&Q.IsDeleted===!0&&x.set(z,ke(Q.SystemModstamp))}},e.signal);for(let P of f){let H=ee(P.id);if(H!==void 0)for(let{id:Q}of L.get(H)??[]){let z=x.get(ee(Q)??"");z!==void 0&&(z===P.stamp?r.add(H):z>P.stamp&&a.add(H))}}}return{outside:r,stuck:a,requests:e.reader.calls()-c}}async function ci(e,n,t,o){let s=[...new Set([...e.values()].map(({objectApiName:l})=>l))],i=await Promise.allSettled(s.map(t)),r=new Map([...n.keys()].map(l=>[l.toLowerCase(),l])),a=new Map;for(let[l,w]of i.entries()){if(w.status==="rejected"){if(w.reason instanceof te)throw w.reason;let p=s[l];o.set(p,Pe(w.reason));for(let[c,g]of e)g.objectApiName===p&&e.delete(c);continue}for(let p of w.value.childRelationships??[]){let c=r.get(p.childSObject.toLowerCase());if(c===void 0)continue;let g=Ie(n.get(c)??[],p.field);if(g===void 0)continue;let d=a.get(c);d||(d=new Set,a.set(c,d)),d.add(g)}}return new Map([...a].map(([l,w])=>[l,[...w]]))}async function di(e,n){let t=new Set,o=e.find(({objectApiName:i})=>i===je);if(!o||Ie(o.fields,an)===void 0)return t;let s=n.get(je);if(!s||"unread"in s||!s.live)return t;try{for await(let i of se(s.live.file)){let r=ee(i.AccountId);r!==void 0&&jn(je,i)&&t.add(r)}}catch{return new Set}return t}async function fi(e,n,t,o){if("unread"in t)return{unread:t.unread};let{input:s,previewDir:i,t0s:r,back:a,carriers:l,stranded:w,stuck:p,others:c,personAccounts:g}=e,{folder:d,reader:f,checkpoint:h,signal:b}=s,R=n.objectApiName,j=Hn(R)?e.files:void 0,C=L=>j===void 0||j.anchoredThen(L),v=new Map,O=L=>{let N=v.get(L);return N||(N=new fn(X(i,R,L)),v.set(L,N)),N},B=L=>v.get(L)?.count??0,W=new Un(e.activeFrom),D=[];try{let L=await We.read(d,h.snapshotId,R),N=Qt(d,R),{gone:V}=o,J=ut(R,h.ignoredFields),Y=bn(R,n.fields,[]),x=m=>J.has(m.toLowerCase())||V.has(m.toLowerCase()),P=Y.filter(m=>!x(m)).map(pn),H=Y.filter(x),Q=R===vo?Ie(n.fields,Bo):void 0,z=Q!==void 0&&!V.has(Q.toLowerCase())?Q:void 0,fe=R===Fo?Ie(n.fields,Eo):void 0,oe=fe!==void 0&&P.includes(fe)?fe:void 0,ue=["Id","SystemModstamp",...Jt,...P,...z!==void 0&&!P.includes(z)?[z]:[],...oe!==void 0?[qt]:[]],Ae=n.cascadeParents.filter(m=>!V.has(m.toLowerCase())),he=(n.restrictParents??[]).filter(m=>!V.has(m.toLowerCase())),Se=R===je&&Ie(n.fields,an)!==void 0,De=m=>Se&&jn(R,m),ye=Uo(n)?"toRecreate":"goneForGood",ze=e.access.heldAs(R)==="parent"?"outOfReach":ye,be=r-Dn,ne={fields:0,cleared:0,liveNotHeld:0,deletedHeld:0},Fe=m=>{let A=ee(m.Id);if(A===void 0)throw new Error(`${R} answered a record without its Id.`);return{id:String(m.Id),key:A}},ge=(m,A,I)=>m.map($=>ee(A[$])).filter($=>$!==void 0&&$!==I),we=(m,A)=>ge(Ae,m,A),Ee=(m,A)=>{let I=ke(m.SystemModstamp);return we(m,A).some($=>a.get($)?.stamp===I)},sn=Date.parse(h.takenAt),Ze=Date.parse(s.readAt)-Dn,Me=(m,A,I,$)=>{W.add(m);let S=we(m,I),F=ge(he,m,I),U=$&&ke(m.CreatedDate)>=sn&&ke(m.LastModifiedDate)<=Ze;n.undeletable&&S.length+F.length===0||D.push({id:A,parents:S,restricts:F,goesAlong:U,undeletable:n.undeletable})},ae=new Map,qe=e.lookups.get(R)??[];if(qe.length>0&&L.size>0)for await(let m of L.records()){if(De(m))continue;let A=ee(m.Id);if(A===void 0)continue;let I=qe.filter($=>{let S=ee(m[$]);return S!==void 0&&a.has(S)});I.length>0&&ae.set(A,{id:String(m.Id),fields:I})}let Te=async m=>{if(m.length===0)return;if(P.length===0){for(let F of m)F.stamp!==F.held&&await O("touched").add({Id:F.id});return}let A=m.map(F=>F.id),I=new Map,$=await L.chunk(A).batches(h.snapshotId,R,rn);for await(let F of $??[])for(let U of F){let G=ee(U.Id);G!==void 0&&I.set(G,U)}if(b?.aborted)throw new te;let S=await zo(f,n,ue,A);for(let F of m){let U=S.get(F.key);if(!U)continue;let G=I.get(F.key);if(!G)throw new Error(`The checkpoint\u2019s snapshot of ${R} does not hold record ${F.id}, which its index names.`);if(z!==void 0&&G[z]!==!0&&U[z]===!0){await O("convertedLead").add({Id:F.id});continue}if(oe!==void 0&&U[qt]===Mo&&!Nn(G[oe],U[oe])){await O("activatedContract").add({Id:F.id});continue}let ie=P.filter(ce=>!Nn(G[ce],U[ce]));if(ie.length>0){ne.fields+=ie.length;let ce=(F.cleared??[]).filter(un=>ie.includes(un)&&Go(U[un]));ce.length>0&&ne.cleared++,await O("giveBack").add({Id:F.id,fields:ie,...ce.length>0?{cleared:ce}:{}}),W.add(U)}else ke(U.SystemModstamp)!==F.held&&await O("touched").add({Id:F.id})}},Ce=[],Ne=async m=>{Ce.push(m),Ce.length>=Ve&&(await Te(Ce),Ce=[])};if(t.live)for await(let m of se(t.live.file)){let{id:A,key:I}=Fe(m),$=De(m),S=L.stampOf(A);if(S!==void 0){if($||!C(A))continue;let U=ae.get(I)?.fields;U&&ae.delete(I);let G=R===mn&&g.delete(I),ie=ke(m.SystemModstamp);(U||G||ie!==S||S>=be)&&await Ne({id:A,key:I,held:S,stamp:ie,...U?{cleared:U}:{}});continue}if(ne.liveNotHeld++,$)continue;let F=await N(I)?"broughtBackSince":ke(m.CreatedDate)>=r?"createdSince":void 0;F===void 0?await O("unexplained").add({Id:A}):j!==void 0&&!j.anchoredNow(A)?await O("outsideAdded").add({Id:A}):(await O(F).add({Id:A}),Me(m,A,I,!0))}for(let[m,A]of ae){let I=L.stampOf(A.id);I!==void 0&&await Ne({id:A.id,key:m,held:I,stamp:I,cleared:A.fields})}if(R===mn)for(let m of g){let A=L.rowOf(m);if(A<0||(g.delete(m),ae.has(m)))continue;let I=L.idAt(A),$=L.stampOf(I);$!==void 0&&await Ne({id:I,key:m,held:$,stamp:$})}if(await Te(Ce),t.deleted)for await(let m of se(t.deleted.file)){let{id:A,key:I}=Fe(m);if(L.retired(A))continue;let $=De(m);if(L.has(A)){if(ne.deletedHeld++,$)continue;if(!C(A)){await O("outsideDeleted").add({Id:A});continue}let S=w.get(I);c.has(I)?await O("deletedByOther").add({Id:A}):p.has(I)?await O(e.answeredGone.has(I)?ze:ye).add({Id:A}):S!==void 0?await O(S).add({Id:A}):Ee(m,I)?await O("withParent").add({Id:A}):n.undeletable?await O("inBin").add({Id:A}):await O(ye).add({Id:A});continue}if(l.has(I)&&!$){await O("carrier").add({Id:A});continue}if(!($||await N(I)))if(ke(m.CreatedDate)<r){let S=w.get(I),F=C(A)?c.has(I)?"deletedByOther":p.has(I)?"goneForGood":S??"deletedWhileTaken":"outsideDeleted";await O(F).add({Id:A})}else Ee(m,I)&&(await O("comesBackWithParent").add({Id:A}),Me(m,A,I,!1))}let He=t.count;if(L.size>0&&He===void 0)throw new Error(`The org gave no count of the ${R} records it holds.`);if(L.size-((He??0)-ne.liveNotHeld)-ne.deletedHeld>0){let m=new bt(L);if(t.deleted)for await(let S of se(t.deleted.file))m.mark(S.Id);let[A]=await ve(f,[wt(R,n.readMode)],(S,F)=>{for(let U of F)m.mark(U.Id)},b);if(!A.read)throw new Error(A.reason);let I=[],$=async()=>{let S=new Set;if(Se){let F=await L.chunk(I).batches(h.snapshotId,R,rn);for await(let U of F??[])for(let G of U){let ie=ee(G.Id);ie!==void 0&&De(G)&&S.add(ie)}}for(let F of I)S.has(F.slice(0,15))||await O(C(F)?ze:"outsideDeleted").add({Id:F});I=[]};for(let S of m.ids())I.push(S),I.length>=Ve&&await $();await $()}for(let m of v.values())await m.flush();let Ye=B("toRecreate"),_e=B("goneForGood"),k=B("convertedLead"),E=B("activatedContract"),K=B("deletedWithCreatedParent"),u=B("deletedWithParentOutside"),y=B("deletedByOther"),T=B("outOfReach"),M=B("carrier");return{told:{diff:{objectApiName:R,toDelete:{createdSince:B("createdSince"),broughtBackSince:B("broughtBackSince"),comesBackWithParent:B("comesBackWithParent")},toGiveBack:{records:B("giveBack"),fields:ne.fields,clearedLookups:ne.cleared},toBringBack:{inBin:B("inBin"),withParent:B("withParent"),deletedWhileTaken:B("deletedWhileTaken"),...M>0?{carriers:M}:{}},...Ye>0?{toRecreate:Ye}:{},cannotUndo:[..._e>0?[{reason:"goneForGood",count:_e}]:[],...k>0?[{reason:"convertedLead",count:k}]:[],...E>0?[{reason:"activatedContract",count:E}]:[],...K>0?[{reason:"deletedWithCreatedParent",count:K}]:[],...u>0?[{reason:"deletedWithParentOutside",count:u}]:[],...y>0?[{reason:"deletedByOther",count:y}]:[],...T>0?[{reason:"outOfReach",count:T}]:[]],outside:[],touched:B("touched"),unexplained:B("unexplained"),lastChangedBy:W.byUser(),...o.drift?{schemaDrift:o.drift}:{},notCompared:H},people:W,pending:D}}}catch(L){for(let N of v.values())await N.discard();if(L instanceof te)throw L;return{unread:Pe(L)}}}async function*Xt(e,n){let t=[];for(let o of To)if(n.diff.toDelete[o]!==0)for await(let s of se(X(e,n.diff.objectApiName,o)))typeof s.Id=="string"&&(t.push(s.Id),t.length>=Ve&&(yield t,t=[]));t.length>0&&(yield t)}async function li(e,n,t,o,s){let{input:i,previewDir:r}=e,a=n.diff.objectApiName,w=((await t(a)).childRelationships??[]).filter(C=>C.cascadeDelete===!0&&!s.has(C.childSObject.toLowerCase()));if(w.length===0)return[];let p=await o(),c=w.filter(C=>p.has(C.childSObject));if(c.length===0)return[];let g=new Set(await e.access.unseenOf([...new Set(c.map(({childSObject:C})=>C))])),d=c.filter(({childSObject:C})=>!g.has(C));if(d.length===0)return[];let f=Date.parse(i.checkpoint.takenAt);if(!Number.isFinite(f))throw new Error(`Not a date: ${i.checkpoint.takenAt}`);let h=ht(Math.ceil(f/Dn)*Dn),b=new Map,R=new Map,j=new Map;for await(let C of Xt(r,n)){let v=d;for(;v.length>0;){let O=[];for(let D of v){let L=pe(D.childSObject),N=pn(D.field),V=ft(L)==="scanAllLive",J=j.get(L)??"CreatedDate";for(let Y of Le(C))O.push({child:L,field:N,read:{objectApiName:L,soql:`SELECT Id, ${N} FROM ${L} WHERE ${N} IN (${Y}) AND ${J} >= ${h}${V?" AND IsDeleted = false":""}`,scanAll:V}})}let B=await ve(i.reader,O.map(({read:D})=>D),(D,L)=>{let{child:N,field:V}=O[D],J=b.get(N);J||(J={records:new Set,parents:new Set},b.set(N,J));for(let Y of L){let x=ee(Y.Id),P=ee(Y[V]);x!==void 0&&J.records.add(x),P!==void 0&&(J.parents.add(P),R.set(P,String(Y[V])))}},i.signal),W=new Set;B.forEach((D,L)=>{if(D.read)return;let{child:N}=O[L];if(!j.has(N)&&/No such column 'CreatedDate'/.test(D.reason)){W.add(N);return}throw new Error(`The ${D.objectApiName} records its deletion would take along could not be read: `+D.reason)});for(let D of W)j.set(D,"SystemModstamp");v=v.filter(D=>W.has(pe(D.childSObject)))}}if(R.size>0){let C=new fn(X(r,a,"outsideParents"));for(let v of R.values())await C.add({Id:v});await C.flush()}return[...b].filter(([,{records:C}])=>C.size>0).sort(([C],[v])=>C<v?-1:C>v?1:0).map(([C,{records:v,parents:O}])=>({objectApiName:C,count:v.size,parents:O.size}))}async function ui(e,n,t,o){if(e.kind==="org")return;let{objectApiName:s,toDelete:i}=n.diff,r=i.createdSince+i.broughtBackSince;if(r===0)return;let l=((await t(s)).childRelationships??[]).filter(d=>d.cascadeDelete===!0).map(d=>d.childSObject);if(l.length===0)return;let w=await o(),p=[...new Set(l.filter(d=>w.has(d)))].sort(),g=[...p.length>0?await e.unseenOf(p):[]].sort((d,f)=>+!Kt.has(d)-+!Kt.has(f));return g.length>0?{objectApiName:s,children:g,records:r}:void 0}var Kt=new Set(["Event","Task"]);async function gi(e,n){let t=new Set(n.flatMap(({pending:c})=>c.flatMap(({parents:g,restricts:d})=>[...g,...d]))),o=new Set;if(t.size>0)for(let c of n)for await(let g of Xt(e,c))for(let d of g){let f=d.slice(0,15);t.has(f)&&o.add(f)}let s=new Map(n.flatMap(({pending:c})=>c.map(g=>[g.id.slice(0,15),g]))),i=c=>c.goesAlong?c.parents.find(g=>o.has(g)):void 0,r=(c,g=new Set)=>{let d=s.get(c),f=d&&!g.has(c)?i(d):void 0;return f===void 0?c:r(f,new Set([...g,c]))},a=new Map,l=(c,g)=>{let d=a.get(c);if(d!==void 0)return d;a.set(c,!1);let f=r(c),h=g.restricts.some(b=>o.has(b)&&r(b)!==f)||g.parents.some(b=>{let R=s.get(b);return R!==void 0&&i(R)!==void 0&&l(b,R)});return a.set(c,h),h},w=[],p=[];for(let{diff:c,pending:g}of n){let d=c.objectApiName,f=O=>i(O)!==void 0&&!l(O.id.slice(0,15),O),h=g.filter(f).length;h>0&&p.push({objectApiName:d,count:h});let b=g.filter(O=>!f(O)),R=b.filter(O=>[...O.parents,...O.restricts].some(B=>o.has(B))),j=new Set(R.map(({id:O})=>O)),C=b.filter(O=>!O.undeletable&&!j.has(O.id));if(C.length+R.length===0)continue;let v=new fn(X(e,d,"undoCannot"));for(let{id:O}of C)await v.add({Id:O});for(let{id:O}of R)await v.add({Id:O,reason:"deletedBeforeParent"});await v.flush(),C.length>0&&w.push({objectApiName:d,count:C.length}),R.length>0&&w.push({objectApiName:d,count:R.length,reason:"deletedBeforeParent"})}return{undoCannot:w,withParentDeleted:p}}async function hi(e,n,t){let o={};if(n.length===0)return o;let s=Le([...n].sort()).map(i=>({objectApiName:"User",soql:`SELECT Id, Name FROM User WHERE Id IN (${i})`,scanAll:!1}));return await ve(e,s,(i,r)=>{for(let a of r)typeof a.Id=="string"&&typeof a.Name=="string"&&(o[a.Id]=a.Name)},t),o}function Vt(e){let{toDelete:n,toGiveBack:t,toBringBack:o}=e;return n.createdSince+n.broughtBackSince+n.comesBackWithParent+t.records+o.inBin+o.withParent+o.deletedWhileTaken+(o.carriers??0)+(e.toRecreate??0)+e.touched+e.unexplained+e.cannotUndo.reduce((s,i)=>s+i.count,0)>0||e.schemaDrift!==void 0}async function wi(e){let n=await e.describe(me),t=tn.safeParse("body"in n?n.body:null);if(!t.success)throw new Error(`The org gave no describe of ${me}.`);return t.data}function Yt(e){return(n,t)=>X(e,n,t)}async function pi(e,n){let t=n.fileObject.objectApiName,o=n.changes.get(t);if(!(n.unread.has(t)||o===void 0||"unread"in o))try{return{anchors:await xt({reader:e.reader,folder:e.folder,previewDir:n.previewDir,snapshotId:e.checkpoint.snapshotId,objects:n.ordered,changes:n.changes,linkDescribe:n.linkDescribe,describeGlobal:e.describeGlobal,...e.signal?{signal:e.signal}:{}})}}catch(s){if(s instanceof te)throw s;return{unread:"The links of its files to the records of the checkpoint could not be read: "+Pe(s)}}}async function eo(e){await Promise.all(["linkAdded","linkRemoved","linkChanged"].map(n=>qn(Re(e,n),{force:!0})))}async function mi(e,n){let t=n.fileObject.objectApiName,o=n.outcomes.get(t),s=n.changes.get(t);if(o===void 0||!("told"in o)||s===void 0)return;let i=new Set([...n.outcomes].filter(([,r])=>"told"in r).map(([r])=>r));try{let r=await Ut({anchors:n.anchors,reader:e.reader,folder:e.folder,snapshotId:e.checkpoint.snapshotId,t0s:n.t0s,objects:n.ordered,fileChanges:s,told:i,classFileOf:Yt(n.previewDir),previewDir:n.previewDir,queryAllFiles:e.checkpoint.takenBy?.queryAllFiles===!0&&e.queryAllFiles!==!1,...e.signal?{signal:e.signal}:{}}),{diff:a,people:l}=o.told;a.toDelete.createdSince+=r.createdSince,a.toBringBack.deletedWhileTaken+=r.deletedWhileTaken;for(let g of r.changedBy)l.add(g);a.lastChangedBy=l.byUser();let w=r.goneForGood,p=r.newFileVersion,c=a.cannotUndo.find(g=>g.reason==="goneForGood");return c!==void 0?c.count+=w:w>0&&a.cannotUndo.unshift({reason:"goneForGood",count:w}),a.cannotUndo.push(...p>0?[{reason:"newFileVersion",count:p}]:[]),r.files}catch(r){if(r instanceof te)throw r;await Kn(n.previewDir,t),await eo(n.previewDir),n.outcomes.set(t,{unread:Pe(r)});return}}async function ki(e,n){let t=n.fileObject.objectApiName,o=n.outcomes.get(t);if(o===void 0||!("told"in o))return;let{diff:s}=o.told;if(s.toDelete.createdSince+s.toDelete.broughtBackSince!==0)try{let{links:i,files:r}=await zt({anchors:n.anchors,reader:e.reader,classFileOf:Yt(n.previewDir),...e.signal?{signal:e.signal}:{}});if(i===0)return;s.outside=[...s.outside.filter(({objectApiName:a})=>a!==me),{objectApiName:me,count:i,parents:r}].sort((a,l)=>a.objectApiName<l.objectApiName?-1:a.objectApiName>l.objectApiName?1:0)}catch(i){if(i instanceof te)throw i;await Kn(n.previewDir,t),await eo(n.previewDir),n.outcomes.set(t,{unread:Pe(i)})}}async function Is(e){let{checkpoint:n,folder:t,reader:o,previewId:s,readAt:i,signal:r}=e,a=Date.parse(n.readFrom);if(!Number.isFinite(a))throw new Error(`Not a date: ${n.readFrom}`);let l=Date.parse(i);if(!Number.isFinite(l))throw new Error(`Not a date: ${i}`);if(r?.aborted)throw new te;let w=a-(a%1e3+1e3)%1e3,p=at(t,s);await yn(p);let c=[...n.objects].sort((k,E)=>k.readOrder-E.readOrder),g=e.access??Gn,d=c.filter(({objectApiName:k})=>!g.notHeld.has(k)),f=new Map,h=n.files!==void 0?d.find(({objectApiName:k})=>Hn(k)):void 0,b=await mt(o,d.map(({objectApiName:k})=>k),n.readFrom,r),R=new Map(d.map(({objectApiName:k},E)=>[k,b[E]])),j=ei(d,R),C=h!==void 0?wi(o):void 0;C?.catch(()=>{});let v=await Ht(e,j,f),O=v.requests,B=new Map,W=new Set,D=[];for(let k of c){let E=k.objectApiName,K=g.notHeld.get(E);if(K!==void 0){B.set(E,K);continue}let u=R.get(E);if(u===void 0||"unread"in u){B.set(E,u?.unread??"Its newest record was not read.");continue}let y=v.now.get(E);y===void 0?(W.add(E),D.push({object:k,fields:{gone:new Set},check:u})):"unread"in y?B.set(E,y.unread):D.push({object:k,fields:y,check:u})}let L=await kt(o,D.map(({object:k,fields:E})=>({objectApiName:k.objectApiName,readMode:k.readMode,held:k.records>0,fields:ni(k,E.gone)})),n.readFrom,p,r,D.map(({check:k})=>k)),N=new Map(D.map(({object:k},E)=>[k.objectApiName,L[E]])),V=D.filter(({object:k})=>{if(!W.has(k.objectApiName))return!1;let E=N.get(k.objectApiName);return E!==void 0&&!("unread"in E)&&E.count!==void 0&&E.count<k.records});if(V.length>0){let k=await Ht(e,V.map(({object:E})=>E),f);O+=k.requests;for(let E of V){let K=E.object.objectApiName;W.delete(K);let u=k.now.get(K);u===void 0||"unread"in u?B.set(K,u?.unread??"Its describe was not read."):E.fields=u}}let J=new Map,Y=k=>{let E=f.get(k);if(E)return Promise.resolve(E);let K=J.get(k);return K||(K=(async()=>{let u=await o.describe(k),y=tn.safeParse("body"in u?u.body:null);if(!y.success)throw new Error(`The org gave no describe of ${k}.`);return y.data})(),J.set(k,K)),K},{back:x,gone:P}=await ti({input:e,t0s:w},c,N),H=ii(x,g.userKey),Q=new Map([...P,...x]),z=oi(x,P),fe=await yt.read(t);for(let k of fe.keys())(x.has(k)||P.has(k))&&z.add(k);let oe=Zt([...fe.keys()].filter(k=>Q.has(k)),Q);zn(z,x,P);for(let k of H)x.delete(k),z.delete(k);let ue=si(c,x,P),Ae=new Map(D.map(({object:k,fields:E})=>[k.objectApiName,bn(k.objectApiName,k.fields,n.ignoredFields).filter(K=>!E.gone.has(K.toLowerCase()))])),he=await ci(x,Ae,Y,B),Se=await ai(e,D.map(({object:k})=>k),x,P,ue,Y);for(let k of Se.stuck)z.add(k);zn(z,x,P);for(let k of[...ue])x.has(k)||ue.delete(k);let De=ri(x,P,Se.outside),ye=0,ze=o.calls(),be=h!==void 0&&C!==void 0?await pi(e,{previewDir:p,ordered:c,changes:N,linkDescribe:C,fileObject:h,unread:B}):void 0;ye+=o.calls()-ze;let ne=be!==void 0&&"anchors"in be?be.anchors:void 0,Fe={input:e,previewDir:p,t0s:w,activeFrom:l-$o,back:x,carriers:ue,stranded:De,stuck:z,answeredGone:oe,others:H,access:g,lookups:he,personAccounts:await di(c,N),...ne!==void 0?{files:ne}:{}},ge=new Map;for(let{object:k,fields:E}of D){if(r?.aborted)throw new te;let K=B.get(k.objectApiName)??(be!==void 0&&"unread"in be&&k===h?be.unread:void 0),u=N.get(k.objectApiName);ge.set(k.objectApiName,K!==void 0||u===void 0?{unread:K??"Its changes were not read."}:await fi(Fe,k,u,E))}let we;if(ne!==void 0&&h!==void 0){let k=o.calls();we=await mi(e,{anchors:ne,fileObject:h,changes:N,outcomes:ge,ordered:c,previewDir:p,t0s:w}),ye+=o.calls()-k}let Ee=new Set(c.map(({objectApiName:k})=>k.toLowerCase()));if(n.files!==void 0&&h!==void 0)for(let k of[me,et])Ee.add(k.toLowerCase());let sn,Ze=()=>sn??=tt({describeGlobal:e.describeGlobal}),Me=[];for(let[k,E]of ge){if(!("told"in E))continue;let{toDelete:K}=E.told.diff;if(K.createdSince+K.broughtBackSince!==0)try{E.told.diff.outside=await li(Fe,E.told,Y,Ze,Ee);let u=await ui(g,E.told,Y,Ze);u!==void 0&&Me.push(u)}catch(u){if(u instanceof te)throw u;await Kn(p,k),ge.set(k,{unread:Pe(u)})}}if(ne!==void 0&&h!==void 0){let k=o.calls();await ki(e,{anchors:ne,fileObject:h,outcomes:ge,previewDir:p}),ye+=o.calls()-k,"told"in(ge.get(h.objectApiName)??{unread:""})||(we=void 0)}let ae=c.flatMap(({objectApiName:k})=>{let E=ge.get(k);return E&&"told"in E?[E.told]:[]}),{undoCannot:qe,withParentDeleted:Te}=await gi(p,ae),Ce=new Set(ae.map(({diff:k})=>k.objectApiName)),Ne=Me.filter(({objectApiName:k})=>Ce.has(k)),He=[...new Set(ae.flatMap(({diff:k})=>Object.keys(k.lastChangedBy)))],Xe=await hi(o,He,r),Ye=new Set(ae.flatMap(({people:k})=>[...k.active])),_e=ae.filter(({diff:k})=>W.has(k.objectApiName)&&!Vt(k)).length;return{checkpointId:n.checkpointId,previewId:s,readAt:i,objects:ae.map(({diff:k})=>k).filter(Vt),undoCannot:qe,...Te.length>0?{withParentDeleted:Te}:{},...Se.requests>0?{parentsOutsideRequests:Se.requests}:{},...O>0?{fieldsRequests:O}:{},described:{first:j.length,later:V.length},..._e>0?{fieldsNotChecked:_e}:{},...we!==void 0?{files:we}:{},...h!==void 0?{filesRequests:ye}:{},access:g.diffAccess(),...Ne.length>0?{unseen:Ne}:{},unread:c.flatMap(({objectApiName:k})=>{let E=ge.get(k),K=E&&"unread"in E?E.unread:E?void 0:B.get(k);return K===void 0?[]:[{objectApiName:k,reason:K}]}),userNames:Xe,activeLastHour:[...Ye].sort()}}var Ai=1e3,Si=25,Ci=2e3,Oe=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,no=["createdSince","broughtBackSince","comesBackWithParent","giveBack","inBin","withParent","deletedWhileTaken","toRecreate","carrier"],de={createdSince:1,broughtBackSince:2,comesBackWithParent:4,giveBack:8,inBin:16,withParent:32,deletedWhileTaken:64,toRecreate:128,carrier:256},to=32768,Pi={createdSince:de.createdSince|de.comesBackWithParent|de.carrier,broughtBackSince:de.broughtBackSince|de.carrier,comesBackWithParent:de.comesBackWithParent,giveBack:de.giveBack|de.inBin|de.withParent,inBin:de.inBin,withParent:de.withParent,deletedWhileTaken:de.deletedWhileTaken,toRecreate:de.toRecreate,carrier:de.carrier},ln=new Set(["createdSince","broughtBackSince"]),Ue={changedSincePreview:1,changedDuringRewind:2,outsideNotAccepted:4,holdsLeft:8,noUndoNotAccepted:16,beforeParentNotAccepted:32,recreateNotAccepted:64,keyTaken:128,needsUnpickedParent:256,heldByUnpicked:512},Ii=[{cls:"linkAdded",as:"unlink"},{cls:"linkRemoved",as:"relink"},{cls:"linkChanged",as:"share"}];function zs(e,n){return[n,e.automatedProcessUserId].filter(t=>typeof t=="string"&&t!=="")}function qs(e,n){let t=n.length>0?n.join(", "):"child";return`${e}: given back once the ${t} records hanging from it that the rewind deletes were gone, as those records held some of its values in place`}function Qe(e){let n=en(e);return n===null?Number.NaN:Date.parse(n)}function re(e,n){let t=e.Id;if(typeof t!="string"||!Oe.test(t))throw new Error(`A line of ${n} names no record: the diff it was read from is not whole.`);return t}async function*q(e){try{for await(let n of se(e))yield n}catch(n){if(n.code!=="ENOENT")throw n}}function Di(e,n){return Jn(e,`${pe(n)}.beforeParent.ndjson`)}var on=class{constructor(n){this.file=n}file;lines=[];written=!1;async add(n){this.lines.push(`${JSON.stringify(n)}
|
|
10
|
-
`),this.lines.length>=Ci&&await this.flush()}async flush(){if(this.lines.length===0)return;let n=this.lines.join("");this.lines=[],await bi(this.file,n,{encoding:"utf8",mode:nn,flag:this.written?"a":"w"}),this.written=!0}},Vn=class{entries=new Map;add(n,t,o,s,i){let r=`${n}\0${t}\0${s??""}\0${i??""}`,a=this.entries.get(r);a||(a={objectApiName:n,reason:t,...s!==void 0?{by:s}:{},...i!==void 0?{needs:i}:{},count:0,ids:[]},this.entries.set(r,a)),a.count++,a.ids.length<Si&&a.ids.push(o)}all(n){let t=(o,s)=>(o??"")<(s??"")?-1:(o??"")>(s??"")?1:0;return[...this.entries.values()].sort((o,s)=>(n.get(o.objectApiName)??0)-(n.get(s.objectApiName)??0)||t(o.reason,s.reason)||t(o.by,s.by)||t(o.needs,s.needs))}};function oo(e,n){if(!(typeof n!="string"||n===""))return e==="SetupOwnerId"&&Oe.test(n)?n.slice(0,15):n}async function Ni(e,n,t,o){let s=new Z;if(e.customSetting===void 0)return s;let i=kn(e.customSetting).toLowerCase(),r=e.fields.find(w=>w.toLowerCase()===i);if(r===void 0)return s;let a=new Z;for(let w of o){let p=X(t,e.objectApiName,w);for await(let c of q(p))a.add(re(c,p))}if(a.size===0)return s;let l=new Set;for await(let w of q($e(n,e.objectApiName))){let p=oo(r,w[r]);p!==void 0&&l.add(p)}if(l.size===0)return s;for await(let w of q(cn(n,e.objectApiName))){if(typeof w.Id!="string"||!a.has(w.Id))continue;let p=oo(r,w[r]);p!==void 0&&l.has(p)&&s.add(w.Id)}return s}function io(e){return{objectApiName:e,deleted:0,withParentDeleted:0,undoCannot:0,nextPassDeleted:0,broughtBack:0,backWithParent:0,recreated:0,givenBackFirst:0,givenBackAfter:0,givenBackNextPass:0,skipped:0}}function ji(e){return Object.entries(e).some(([n,t])=>n!=="objectApiName"&&t!==0)}function so(e){return`${e.ContentDocumentId.slice(0,15)}:${e.LinkedEntityId.slice(0,15)}`}function ro(e,n,t){let s=(n==="linkChanged"?Rt:Rn).safeParse(e);if(!s.success)throw new Error(`A line of ${t} names no link: the diff it was read from is not whole.`);return s.data}function co(e){return{unlink:{file:Re(e,"linkAdded"),count:0},relink:{file:Re(e,"linkRemoved"),count:0},share:{file:Re(e,"linkChanged"),count:0}}}async function Li(e){let n={};for(let{cls:o,as:s}of Ii){let i=new Set,r=Re(e.confirmedDir,o);for await(let p of q(r))i.add(so(ro(p,o,r)));let a=Re(e.freshDir,o),l=new on(Re(e.dir,o)),w=0;for await(let p of q(a)){let c=ro(p,o,a);if(e.deleted(c.ContentDocumentId)||e.deleted(c.LinkedEntityId))continue;let g=e.pass===2&&o==="linkRemoved"&&(e.earlier(c.ContentDocumentId)||e.earlier(c.LinkedEntityId));if(!i.has(so(c))&&!g){e.left.add(me,"changedSincePreview",c.Id);continue}await l.add(p),w++}await l.flush(),n[s]={file:l.file,count:w}}let t=co(e.dir);return{unlink:n.unlink??t.unlink,relink:n.relink??t.relink,share:n.share??t.share}}var vi=["inBin","withParent","deletedWhileTaken","carrier"],Bi=new Set(["id","createdbyid","lastmodifiedbyid","systemmodstamp","createddate","lastmodifieddate"]);function Fi(e,n){return e.flatMap(t=>{let o=n[t];return typeof o=="string"&&Oe.test(o)?[o.slice(0,15)]:[]})}function ao(e,n,t){let o=t===void 0?void 0:new Set(t.map(s=>s.toLowerCase()));return Object.entries(e).flatMap(([s,i])=>{let r=s.toLowerCase();if(Bi.has(r)||o!==void 0&&!o.has(r))return[];if(typeof i!="string"||!Oe.test(i))return[];let a=i.slice(0,15);return n.has(a)?[{field:s,needs:n.get(a)}]:[]})}async function Ei(e,n,t){let{freshDir:o,heldRows:s}=e,i=new Map,r=new Map;for(let d of n)for(let f of[...vi,"toRecreate","comesBackWithParent"]){let h=X(o,d.objectApiName,f);for await(let b of q(h)){let R=re(b,h).slice(0,15);i.set(R,d.objectApiName),r.set(R,f)}}let a=new Map;for(let d of n)if(d.cascadeParents.length!==0)for await(let f of q(cn(o,d.objectApiName))){if(typeof f.Id!="string"||!Oe.test(f.Id))continue;let h=f.Id.slice(0,15),b=r.get(h);(b==="withParent"||b==="comesBackWithParent")&&a.set(h,Fi(d.cascadeParents,f))}let l=new Set;for(let[d,f]of r)(f==="inBin"||f==="deletedWhileTaken"||f==="carrier")&&t(i.get(d)??"")&&l.add(d);for(let d=l.size>0;d;){d=!1;for(let[f,h]of a)l.has(f)||!h.some(b=>l.has(b))||(l.add(f),d=!0)}let w=(d,f=new Set)=>{let h=i.get(d);if(!(h===void 0||f.has(d))){if(!t(h))return h;f.add(d);for(let b of a.get(d)??[]){if(l.has(b))continue;let R=w(b,f);if(R!==void 0)return R}}},p=new Map,c=new Map;for(let[d,f]of r){if(l.has(d)||f==="comesBackWithParent")continue;let h=i.get(d)??"";if(!t(h))p.set(d,h);else if(f==="withParent"){let b=w(d);c.set(d,b),p.set(d,b)}}let g=new Map;if(s===void 0)return{comes:l,left:c,fields:g};for(let d of[...n].reverse()){let f=d.objectApiName;if(!t(f))continue;let h=new Set(d.cascadeParents.map(v=>v.toLowerCase())),b=[],R=X(o,f,"toRecreate");for await(let v of q(R))b.push(re(v,R));if(b.length>0)for await(let v of s(f,b)){if(typeof v.Id!="string"||!Oe.test(v.Id))continue;let O=v.Id.slice(0,15),B=ao(v,p,void 0);if(B.length===0)continue;let W=B.find(({field:D})=>h.has(D.toLowerCase()));W!==void 0?(c.set(O,W.needs),p.set(O,W.needs)):g.set(O,{fields:B.map(({field:D})=>D),needs:B[0].needs})}let j=new Map,C=X(o,f,"giveBack");for await(let v of q(C)){let O=re(v,C),B=Array.isArray(v.fields)?v.fields.filter(W=>typeof W=="string"):void 0;j.set(O.slice(0,15),{id:O,differ:B})}for(let v of["inBin","withParent"]){let O=X(o,f,v);for await(let B of q(O)){let W=re(B,O);l.has(W.slice(0,15))&&j.set(W.slice(0,15),{id:W,differ:void 0})}}if(j.size!==0)for await(let v of s(f,[...j.values()].map(({id:O})=>O))){if(typeof v.Id!="string"||!Oe.test(v.Id))continue;let O=v.Id.slice(0,15),B=j.get(O);if(B===void 0)continue;let W=ao(v,p,B.differ);W.length>0&&g.set(O,{fields:W.map(({field:D})=>D),needs:W[0].needs})}}return{comes:l,left:c,fields:g}}function Mi(e,n){let t=n!==void 0?` Rewind ${n} with it to put it back.`:"",o=n??"an object this rewind was not limited to";switch(e){case"needsUnpickedParent":return`Left: it comes back only with a parent this rewind leaves deleted, or a lookup of it names a record this rewind leaves deleted (${o}), which the org refuses to point at.${t}`;case"heldByUnpicked":return`Given back but for the values records of ${o} created since hold in place: this rewind leaves them, so the org refuses to change those values.${t}`;case"outsideNotAccepted":return`Kept: records of ${o} created since hang from it, which its deletion would take along, and deleting them was not accepted.${t}`;default:return`Kept: records of ${o} this rewind leaves as they are hang from it, and its deletion would take them along.${t}`}}async function Ti(e){let{checkpoint:n,pass:t,confirmedDir:o,freshDir:s,dir:i,signal:r}=e,a=Date.parse(n.takenAt);if(!Number.isFinite(a))throw new Error(`Not a date: ${n.takenAt}`);let l=Date.parse(e.readAt);if(!Number.isFinite(l))throw new Error(`Not a date: ${e.readAt}`);let w=l-Ai;if(await yn(i),(await Ri(i)).length>0)throw new Error(`A rewind's plan is written to a folder of its own: ${i} is not empty.`);let p=()=>{if(r?.aborted)throw new te},c=[...n.objects].map(lt).sort((u,y)=>u.readOrder-y.readOrder),g=new Map(c.map(({objectApiName:u},y)=>[u,y])),d=new Map(c.map(({objectApiName:u})=>[u,io(u)])),f=u=>d.get(u)??io(u),h=new Set(e.ownWriters.map(u=>u.slice(0,15))),b=new Map(Object.entries(e.removalStamps??{}).map(([u,y])=>[u.slice(0,15),Qe(y)])),R=u=>fo(u,w,h,b),j=(u,y)=>u.flatMap(T=>{let M=y[T];return typeof M=="string"&&Oe.test(M)?[M]:[]}),C=(u,y)=>j(u.cascadeParents,y),v=(u,y)=>j(u.restrictParents??[],y),O=new Vn,B=u=>e.objects===void 0||e.objects.has(u),W=e.objects!==void 0?await Ei(e,c,B):void 0,D=new Map,L=new Map,N=new on(Jn(i,"leftFields.ndjson")),V=0,J=(u,y,T,M)=>{if(O.add(u,y,T,void 0,M),D.set(T.slice(0,15),Mi(y,M)),M===void 0)return;let _=L.get(M);_||(_=new Z,L.set(M,_)),_.add(T)},Y=new Z,x=new Z,P=new Z,H=new Z,Q=new Z,z=new Z,fe=[];for(let u of c){p();let y=u.objectApiName,T=B(y),M=(g.get(y)??0)+1,_=f(y),m=new Z;for(let S of no){let F=X(o,y,S);for await(let U of q(F))m.add(re(U,F),de[S])}let A=t===2?await Gi(s,y,w,h,b,fe):void 0,I=new Map,$=S=>{let F=I.get(S);return F||(F=new on(X(i,y,S)),I.set(S,F)),F};for(let S of no){if(!T&&S!=="comesBackWithParent"&&S!=="createdSince")continue;let F=X(s,y,S);for await(let U of q(F)){let G=re(U,F),ie=(m.flagsOf(G)&Pi[S])!==0;if(!T&&!(t===2?ie:S==="comesBackWithParent"&&ie&&W?.comes.has(G.slice(0,15))))continue;ie&&m.add(G,to),ie&&ln.has(S)&&(m.flagsOf(G)&de.carrier)!==0&&z.add(G);let ce=A?.other.flagsOf(G)??0,un=T&&A?.own.has(G)===!0;if(ce>0||!(ie||un)){let Ke=ce>0?"changedDuringRewind":"changedSincePreview";O.add(y,Ke,G,ce>0?fe[ce-1]:void 0),ln.has(S)&&P.add(G,Ue[Ke]);continue}if(W!==void 0&&T){let Ke=G.slice(0,15);if(S==="comesBackWithParent"&&!W.comes.has(Ke))continue;if((S==="withParent"||S==="toRecreate")&&W.left.has(Ke)){J(y,"needsUnpickedParent",G,W.left.get(Ke));continue}let gn=W.fields.get(Ke);if(gn!==void 0&&(S==="giveBack"||S==="toRecreate"||S==="inBin"||S==="withParent")){J(y,"needsUnpickedParent",G,gn.needs),await N.add({Id:G,fields:gn.fields}),V++;let Qn=Array.isArray(U.fields)?U.fields:[],lo=Qn.filter(Zn=>typeof Zn=="string"&&!gn.fields.some(uo=>uo.toLowerCase()===Zn.toLowerCase()));if(S==="giveBack"&&Qn.length>0&&lo.length===0)continue}}if(S==="toRecreate"&&!e.acceptRecreate){O.add(y,"recreateNotAccepted",G);continue}await $(S).add(S==="giveBack"?U:{Id:G}),S==="giveBack"&&W!==void 0&&Y.add(G,M),ln.has(S)?x.add(G,M):S==="comesBackWithParent"?(H.add(G),_.nextPassDeleted++):S==="carrier"?(H.add(G),Q.add(G),_.carriers=(_.carriers??0)+1,_.nextPassDeleted++):S==="inBin"||S==="deletedWhileTaken"?_.broughtBack++:S==="withParent"?_.backWithParent++:S==="toRecreate"&&_.recreated++,(S==="inBin"||S==="withParent")&&await $("giveBack").add({Id:G})}}for(let S of I.values())await S.flush();_.skipped=T?m.count(S=>(S&to)===0):0}await N.flush();let oe=new Map;if(W!==void 0){let u=new Z;for(let y of c){let T=y.objectApiName;if(B(T)||y.cascadeParents.length===0)continue;let M=new Z;for(let _ of ln){let m=X(s,T,_);for await(let A of q(m))M.add(re(A,m))}for await(let _ of q($e(s,T))){if(typeof _.Id!="string"||!Oe.test(_.Id)||x.has(_.Id))continue;let m=M.has(_.Id),A=m&&Qe(_.CreatedDate)>=a&&Qe(_.LastModifiedDate)<=w;for(let I of C(y,_)){let $=x.flagsOf(I);if($>0){if(P.has(I)||A&&e.acceptOutside)continue;let F=c[$-1].objectApiName;oe.set(I.slice(0,15),T),A?(P.add(I,Ue.outsideNotAccepted),J(F,"outsideNotAccepted",I,T)):P.add(I,Ue.holdsLeft);continue}let S=Y.flagsOf(I);m&&S>0&&u.add(I)&&J(c[S-1].objectApiName,"heldByUnpicked",I,T)}}}}if(n.scope.mode==="picked"&&!e.acceptOutside)for(let u of c){let y=X(s,u.objectApiName,"outsideParents");for await(let T of q(y)){let M=re(T,y);!x.has(M)||P.has(M)||z.has(M)||(P.add(M,Ue.outsideNotAccepted),O.add(u.objectApiName,"outsideNotAccepted",M))}}let ue=c.map(u=>({object:u,file:$e(s,u.objectApiName)}));for(let u=P.size>0;u;){p(),u=!1;for(let{object:y,file:T}of ue)for await(let M of q(T)){if(!P.has(M.Id))continue;let _=oe.get(String(M.Id).slice(0,15));for(let m of C(y,M))!x.has(m)||P.has(m)||(P.add(m,Ue.holdsLeft),_!==void 0&&oe.set(m.slice(0,15),_),u=!0)}}for(let{object:u,file:y}of ue)for await(let T of q(y))if(x.has(T.Id)&&P.flagsOf(T.Id)===Ue.holdsLeft){let M=re(T,y),_=oe.get(M.slice(0,15));_!==void 0?J(u.objectApiName,"holdsLeft",M,_):O.add(u.objectApiName,"holdsLeft",M)}let Ae=new Z,he=u=>x.has(u)&&!P.has(u),Se=new Map,De=u=>{let y=u.slice(0,15);return Se.get(y)??y},ye=new Z,ze=[...c].reverse(),be=[];for(let u of ze){p();let y=u.objectApiName,T=$e(s,y),M=new on(Di(i,y)),_=0;for await(let m of q(T)){let A=typeof m.Id=="string"?m.Id:"";if(!he(A))continue;let I=Qe(m.LastModifiedDate),$=C(u,m).filter(he);if($.length>0&&Qe(m.CreatedDate)>=a&&(I<=w||I<=(b.get(A.slice(0,15))??Number.NaN))){let G=De($[0]);if(!($.some(ce=>ye.has(ce))||v(u,m).some(ce=>he(ce)&&De(ce)!==G))){Ae.add(A),Se.set(A.slice(0,15),G),f(y).withParentDeleted++;continue}ye.add(A)}let F=[...C(u,m),...v(u,m)].filter(he);if(u.undeletable&&F.length===0)continue;let U=F.length>0?"beforeParentNotAccepted":"noUndoNotAccepted";e.acceptNoUndo?(f(y).undoCannot++,F.length>0&&(await M.add({Id:A,parents:F}),_++)):(P.add(A,Ue[U]),O.add(y,U,A))}await M.flush(),_>0&&be.push({objectApiName:y,count:_,file:M.file})}let ne=new xe(`${i}/deletes`),Fe=new xe(`${i}/along-to-draft`),ge={},we=new Z,Ee=0;for(let u of c){p();let y=u.objectApiName,T=$e(s,y),M=0;for await(let _ of q(T)){let m=typeof _.Id=="string"?_.Id:"";if(x.has(m)&&(Ee++,!P.has(m))){for(let A of C(u,_))we.has(A)||we.add(A,(g.get(y)??0)+1);if(Ae.has(m)){ot([y]).length>0&&await Fe.add(y,m);continue}await ne.add(y,m),M++,t===2&&R(_)&&typeof _.LastModifiedDate=="string"&&(ge[m]=_.LastModifiedDate)}}f(y).deleted=M}if(Ee!==x.size)throw new Error("The fresh diff's reads do not hold every record its classes name to delete.");let sn=await En.of(ne),Ze=await En.of(Fe),Me=new Z;if(t===1&&H.size>0){for(let u of c)for await(let y of q(cn(s,u.objectApiName)))if(H.has(y.Id))for(let T of C(u,y))Me.add(T)}let ae=new Map;for(let u of c){let y=await Ni(u,s,i,["inBin","deletedWhileTaken"]);if(y.size===0)continue;ae.set(u.objectApiName,y);let T=f(u.objectApiName);T.broughtBack-=y.size,T.keyTaken=y.size;for(let M of["inBin","deletedWhileTaken"]){let _=X(i,u.objectApiName,M);for await(let m of q(_)){let A=re(m,_);y.has(A)&&O.add(u.objectApiName,"keyTaken",A)}}}let qe=new xe(`${i}/giveBackFirst`),Te=new xe(`${i}/giveBackAfter`),Ce=[];for(let u of c){p();let y=u.objectApiName,T=X(i,y,"giveBack"),M=!1;for await(let $ of q(T))if(we.has($.Id)){M=!0;break}let _=new Z;if(M)for await(let $ of q($e(s,y)))we.has($.Id)&&C(u,$).some(he)&&_.add(String($.Id));let m=f(y),A=new Set,I=ae.get(y);for await(let $ of q(T)){let S=re($,T);if(I?.has(S)===!0)continue;let F=we.flagsOf(S),U=_.has(S);if(F>0){if(await Te.add(y,S),m.givenBackAfter++,A.add(c[F-1].objectApiName),!U)continue}else if(!U&&Me.has(S)){m.givenBackNextPass++;continue}await qe.add(y,S),m.givenBackFirst++}A.size>0&&Ce.push({objectApiName:y,by:[...A]})}let Ne=new xe(`${i}/bringBack`),He=new xe(`${i}/recreate`);for(let u of ze){let y=ae.get(u.objectApiName);for(let M of["carrier","inBin","deletedWhileTaken"]){let _=X(i,u.objectApiName,M);for await(let m of q(_)){let A=re(m,_);y?.has(A)!==!0&&await Ne.add(u.objectApiName,A)}}let T=X(i,u.objectApiName,"toRecreate");for await(let M of q(T))await He.add(u.objectApiName,re(M,T))}let Xe=new Z;if(t===2)for(let u of c)for(let y of["inBin","withParent","deletedWhileTaken","carrier","toRecreate"]){let T=X(o,u.objectApiName,y);for await(let M of q(T))Xe.add(re(M,T))}let Ye=n.files===void 0||!B(le)?co(i):await Li({confirmedDir:o,freshDir:s,dir:i,pass:t,deleted:u=>Oe.test(u)&&he(u),earlier:u=>Oe.test(u)&&(Xe.has(u)||Xe.has(e.recreated?.originalOf(u.slice(0,15))??u)),left:O}),_e=new xe(`${i}/unlinkFrom`);for(let u of ln){let y=X(i,le,u);for await(let T of q(y)){let M=re(T,y);(P.flagsOf(M)&Ue.outsideNotAccepted)!==0&&await _e.add(le,M)}}let k={...e.removalStamps,...ge},E=Object.keys(k).length>0,K=c.map(({objectApiName:u})=>f(u)).filter(ji);return{pass:t,dir:i,deletes:sn,removal:{runStartedAt:new Date(a),runEndedAt:new Date(w),includeChanged:!1,...E?{removalStamps:k}:{},...e.removalSpans&&e.removalSpans.length>0?{removalSpans:[...e.removalSpans]}:{}},bringBack:await Ne.finish(),carriers:Q,goesAlong:Ae,alongToDraft:Ze,recreate:await He.finish(),giveBack:{beforeDeletes:await qe.finish(),afterDeletes:await Te.finish(),heldBy:Ce},restore:{changedAfter:e.readAt,ownWriters:[...e.ownWriters],includeChanged:!1,...E?{stamps:k}:{}},objects:K,undoCannot:K.filter(u=>u.undoCannot>0).map(({objectApiName:u,undoCannot:y})=>({objectApiName:u,count:y})),beforeParent:be.reverse(),left:O.all(g),links:{...Ye,unlinkFrom:await _e.finish()},...W!==void 0?{limited:{objects:c.map(({objectApiName:u})=>u).filter(B),needs:[...L].sort(([u],[y])=>(g.get(u)??0)-(g.get(y)??0)).map(([u,y])=>({objectApiName:u,records:y.size})),why:D,leftFields:{file:N.file,count:V}}}:{}}}function Hs(e,n){if(n===void 0)return e;let t=i=>i.filter(r=>n.has(r.objectApiName)),{files:o,...s}=e;return{...s,objects:t(e.objects),undoCannot:t(e.undoCannot),unread:t(e.unread),...e.withParentDeleted?{withParentDeleted:t(e.withParentDeleted)}:{},...e.unseen?{unseen:t(e.unseen)}:{},...o!==void 0&&n.has(le)?{files:o}:{}}}var _i=200;function Ks(e,n){return async function*(t,o){if(o.length===0)return;let s=await We.read(n,e.snapshotId,t);for(let i=0;i<o.length;i+=Ve){let r=await s.chunk(o.slice(i,i+Ve)).batches(e.snapshotId,t,_i);for await(let a of r??[])yield*a}}}var $i=new Set(["needsUnpickedParent","heldByUnpicked","outsideNotAccepted","holdsLeft","keyTaken"]);async function Wi(e,n){let t=0;for await(let o of q(X(e,n,"giveBack")))Array.isArray(o.fields)&&t++;return t}async function xi(e){let n=new Set(e.limited?.objects??e.objects.map(i=>i.objectApiName)),t=[];for(let i of e.objects){let r={objectApiName:i.objectApiName,picked:n.has(i.objectApiName),toDelete:i.deleted+i.withParentDeleted+i.nextPassDeleted-(i.carriers??0),toGiveBack:await Wi(e.dir,i.objectApiName),toBringBack:i.broughtBack+i.backWithParent,toRecreate:i.recreated};r.toDelete+r.toGiveBack+r.toBringBack+r.toRecreate>0&&t.push(r)}let o=new Map;for(let i of e.left){if(!n.has(i.objectApiName)||!$i.has(i.reason))continue;let r=`${i.objectApiName}\0${i.reason}`,a=o.get(r);a?a.count+=i.count:o.set(r,{objectApiName:i.objectApiName,reason:i.reason,count:i.count})}let s=e.undoCannot.flatMap(({objectApiName:i,count:r})=>{let a=e.beforeParent.find(w=>w.objectApiName===i),l=r-(a?.count??0);return[...l>0?[{objectApiName:i,count:l}]:[],...a!==void 0&&a.count>0?[{objectApiName:i,count:a.count,reason:"deletedBeforeParent"}]:[]]});return{objects:[...n],acts:t,left:[...o.values()],needs:e.limited?.needs??[],undoCannot:s}}async function Vs(e){let n=Jn(e.previewDir,`selection-${yi(4).toString("hex")}`);try{let t=await Ti({checkpoint:e.checkpoint,pass:1,confirmedDir:e.previewDir,freshDir:e.previewDir,readAt:e.readAt,ownWriters:[],acceptOutside:e.acceptOutside,acceptNoUndo:!0,acceptRecreate:!0,...e.objects?{objects:e.objects}:{},...e.heldRows?{heldRows:e.heldRows}:{},dir:n,...e.signal?{signal:e.signal}:{}});return await xi(t)}finally{await Oi(n,{recursive:!0,force:!0})}}function fo(e,n,t,o){let s=Qe(e.LastModifiedDate);if(!(s>n))return!1;let i=typeof e.Id=="string"?e.Id:"",r=typeof e.LastModifiedById=="string"?e.LastModifiedById:"";return s<=(o.get(i.slice(0,15))??Number.NaN)||t.has(r.slice(0,15))}async function Gi(e,n,t,o,s,i){let r={own:new Z,other:new Z};for(let a of[$e(e,n),cn(e,n)])for await(let l of q(a)){if(!(Qe(l.LastModifiedDate)>t))continue;let p=re(l,a);if(fo(l,t,o,s)){r.own.add(p);continue}let c=typeof l.LastModifiedById=="string"?l.LastModifiedById:"",g=i.indexOf(c);g<0&&(i.push(c),g=i.length-1),r.other.add(p,g+1)}return r}export{Gn as a,ss as b,X as c,Uo as d,Is as e,zs as f,qs as g,Ti as h,Hs as i,Ks as j,xi as k,Vs as l};
|
|
7
|
+
import{c as Pt,d as It}from"./chunk-2Z54GB6X.mjs";import{a as Je,c as Rn,d as Re,e as Rt,f as Ot,g as At,h as St,j as Ct,l as Fn,m as En}from"./chunk-R6TF26V4.mjs";import{d as tn,f as an,g as ut,h as gt,i as ht,k as wt,l as bn,m as vn}from"./chunk-JU2XEKEO.mjs";import{a as Nn}from"./chunk-AITNZWLB.mjs";import{C as ot}from"./chunk-ZWCRWF7E.mjs";import{A as Bn,B as se,C as yt,E as xe,F as cn,G as bt,e as it,i as te,l as Ve,p as jn,q as ft,r as $e,s as lt,t as pt,x as mt,y as kt,z as ve}from"./chunk-ETT5GP4P.mjs";import{b as Z,e as We,g as Ln}from"./chunk-SW2NUKQL.mjs";import{J as dt,a as st,b as rt,d as nn,o as at,x as ct,z as yn}from"./chunk-E2YJVSX6.mjs";import{b as rn,d as Le,e as tt}from"./chunk-BNO5GIJ6.mjs";import{i as nt}from"./chunk-INIT2UKJ.mjs";import{E as en}from"./chunk-XEB6HZ34.mjs";import{q as mn,r as je}from"./chunk-55LQD3Y3.mjs";import{h as pn}from"./chunk-TZE3Y7IQ.mjs";import{f as Yn,g as le,h as me,i as et,p as kn}from"./chunk-EAFLDSQ2.mjs";import{b as Pe}from"./chunk-CA5NAXSU.mjs";import{vc as pe}from"./chunk-DPYTG6DM.mjs";import{b as Xn,k as hn,l as wn}from"./chunk-WZQEK4WT.mjs";import{randomBytes as yi}from"node:crypto";import{appendFile as bi,readdir as Ri,rm as Oi}from"node:fs/promises";import{join as Jn}from"node:path";import{appendFile as No,rm as qn}from"node:fs/promises";import{join as jo}from"node:path";import{appendFile as ho}from"node:fs/promises";import{join as wo}from"node:path";var In=it*10,po=2e3,mo="005",ko=["Id","IsDeleted","CreatedDate","LastModifiedById","LastModifiedDate","LatestPublishedVersionId","ContentSize"],Mt=1,Tt=2,_t=4,Dt=8,_n=16,An=32,Sn=64,Nt=1,jt=2,Lt=4,On=32768,Cn={toDelete:["createdSince","broughtBackSince"],comesBack:["inBin","withParent","deletedWhileTaken"],lost:["goneForGood","toRecreate"]},Mn={toDelete:["createdSince","broughtBackSince","comesBackWithParent"],comesBack:["inBin","withParent","deletedWhileTaken"],lost:["goneForGood","deletedWithCreatedParent","deletedWithParentOutside"]};function Be(e){return typeof e=="string"&&e.length>=15?e.slice(0,15):void 0}function $n(e){return`${e.ContentDocumentId.slice(0,15)}${e.LinkedEntityId.slice(0,15)}`}function $t(e){return`${e.ShareType}/${e.Visibility}`}async function*dn(e){try{for await(let n of se(e))yield n}catch(n){if(n.code==="ENOENT")return;throw n}}function vt(e){return typeof e=="string"&&/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/.test(e)?e:null}function Tn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function yo(e){let n=en(e);return n===null?Number.NaN:Date.parse(n)}var Ge=class{constructor(n){this.file=n}file;lines=[];count=0;async add(n){this.lines.push(`${JSON.stringify(n)}
|
|
8
|
+
`),this.count++,this.lines.length>=po&&await this.flush()}async flush(){if(this.lines.length===0)return;let n=this.lines.join("");this.lines=[],await ho(this.file,n,{encoding:"utf8",mode:nn,flag:"a"})}};function Bt(e,n,t){let o=pe(n);return wo(e,`${o}.links${t===void 0?"":`.${t}`}.ndjson`)}function*Wt(e,n){let t=[];for(let o of e)t.push(o),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}var bo=wn({sobjects:hn(Yn)}).loose(),Wn=class{files=new Z;held=new Map;sharings=[];prefixes;now;constructor(n,t){this.prefixes=n,this.now=t}anchoredNow(n){return(this.files.flagsOf(n)&_t)!==0}anchoredThen(n){return(this.files.flagsOf(n)&Tt)!==0}sharingAt(n){let t=this.sharings.indexOf(n);return t>=0?t:(this.sharings.push(n),this.sharings.length-1)}};function Ro(e,n){let t=n.fields.find(s=>s.name.toLowerCase()==="linkedentityid"),o=new Set((t?.referenceTo??[]).map(s=>s.toLowerCase()));if(o.size===0)throw new Error(`The describe of ${me} names no record a link ties a file to.`);return e.objects.map(({objectApiName:s})=>s).filter(s=>{if(s.toLowerCase()===le.toLowerCase()||!o.has(s.toLowerCase()))return!1;let i=e.changes.get(s);return i!==void 0&&!("unread"in i)&&(i.count??0)>0})}async function*Oo(e,n){let t=await $e.read(e.folder,e.snapshotId,n);for(let s=0;s<t.size;s++)yield t.idAt(s);let o=e.changes.get(n);if(!(o===void 0||"unread"in o||!o.live))for await(let s of se(o.live.file))typeof s.Id=="string"&&!t.has(s.Id)&&(yield s.Id)}async function Ao(e,n){let{reader:t,previewDir:o,signal:s}=e,i=n.map(l=>({...St(l),file:Bt(o,l)})),r=await Bn(t,i,s),a=[];for(let[l,w]of r.entries()){let p=n[l];if(w.read){a.push({objectApiName:p,file:i[l].file});continue}let c=0,g=Oo(e,p);for await(let d of So(g,Je*In)){let h=[...Wt(d,Je)].map(j=>({...Ct(p,j),file:Bt(o,p,c++)})),R=(await Bn(t,h,s)).find(j=>!j.read);if(R&&!R.read)throw new Error(`The links of the files of ${p} could not be read whole: ${w.reason}; read by the ids of its records, ${R.reason}`);for(let j of h)a.push({objectApiName:p,file:j.file})}}return a}async function*So(e,n){let t=[];for await(let o of e)t.push(o),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}async function xt(e){let n=bo.safeParse(await e.describeGlobal());if(!n.success)throw new Error("The org\u2019s global describe does not read as one.");let t=Ot(n.data.sobjects,e.objects.map(({objectApiName:a})=>a)),o=Ro(e,await e.linkDescribe),s=await Ao(e,o),i=new Wn(t,s);for await(let a of En(e.folder))i.files.add(a.Id,Mt|(a.anchored?Tt:0));let r=await jn.read(e.folder);for await(let a of Fn(e.folder))i.held.set($n(Gt(a,r)),i.sharingAt($t(a)));for(let{file:a}of s)for await(let l of se(a))typeof l.ContentDocumentId=="string"&&i.files.add(l.ContentDocumentId,_t);return i}function Gt(e,n){let t=Be(e.LinkedEntityId),o=t===void 0?void 0:n.currentOf(t);return o===void 0?e:{...e,LinkedEntityId:o}}async function Pn(e,n,t,o,s){for(let i of o)for await(let r of dn(n(t,i)))typeof r.Id=="string"&&e.add(r.Id,s)}async function Ft(e){let n=0;for await(let t of dn(e))typeof t.Id=="string"&&n++;return n}async function Et(e,n,t){let o=new Map;if(n.length===0)return o;let s=Le([...n],Je).map(a=>({objectApiName:le,soql:`SELECT ${ko.join(", ")} FROM ${le} WHERE Id IN (${a})`,scanAll:!0})),r=(await ve(e,s,(a,l)=>{for(let w of l){let p=Be(w.Id);p!==void 0&&o.set(p,w)}},t)).find(a=>!a.read);if(r&&!r.read)throw new Error(`The files the checkpoint names could not be read by their ids: ${r.reason}`);return o}function Co(e,n){return n===void 0||n.version===null||e.LatestPublishedVersionId===null?!1:Be(n.version)!==Be(e.LatestPublishedVersionId)}async function Ut(e){let{anchors:n,reader:t,classFileOf:o,signal:s}=e,i=n.files,r=le;await Pn(i,o,r,Cn.toDelete,_n),await Pn(i,o,r,Cn.comesBack,An),await Pn(i,o,r,Cn.lost,Sn);let a=new Map,l=e.fileChanges;if(!("unread"in l)){for(let D of[l.live,l.deleted])if(D!==void 0)for await(let L of se(D.file)){let N=Be(L.Id);N!==void 0&&(i.add(String(L.Id),Dt),a.set(N,{version:vt(L.LatestPublishedVersionId),size:Tn(L.ContentSize)}))}}let w=await $e.read(e.folder,e.snapshotId,r),p=D=>(i.flagsOf(D)&Dt)===0&&!w.has(D),c=new Ge(o(r,"createdSince")),g=new Ge(o(r,"deletedWhileTaken")),d=new Ge(o(r,"goneForGood")),f=new Ge(o(r,"newFileVersion")),h=0,b=0,R=async D=>{let L=await Et(t,D.filter(N=>N.anchored&&p(N.Id)).map(N=>N.Id),s);for(let N of D){if(!N.anchored)continue;let V=Be(N.Id)??"",J=a.get(V);if(p(N.Id)){let x=L.get(V);if(x===void 0){i.add(N.Id,Sn),await d.add({Id:N.Id});continue}J={version:vt(x.LatestPublishedVersionId),size:Tn(x.ContentSize)},x.IsDeleted===!0&&(i.add(N.Id,An),await g.add({Id:N.Id}))}let Y=i.flagsOf(N.Id);(Y&Sn)===0&&((Y&An)!==0&&(h+=J?.size??N.ContentSize??0),Co(N,J)&&await f.add({Id:N.Id}))}},j=[];for await(let D of En(e.folder))j.push(D),j.length>=Je*In&&(await R(j),j=[]);await R(j);let C=new Z,v=[],O=async D=>{let L=await Et(t,D,s);for(let N of D){let V=L.get(Be(N)??"");V===void 0||V.IsDeleted===!0||yo(V.CreatedDate)>=e.t0s&&(i.add(N,_n),await c.add({Id:N}),v.push(V))}},B=[];for(let{file:D}of n.now)for await(let L of se(D)){let N=L.ContentDocumentId;typeof N!="string"||(i.flagsOf(N)&Mt)!==0||!p(N)||C.add(N)&&(B.push(N),B.length>=Je*In&&(await O(B),B=[]))}await O(B);for await(let D of dn(o(r,"createdSince"))){let L=Be(D.Id);L!==void 0&&(b+=a.get(L)?.size??0)}for await(let D of dn(o(r,"broughtBackSince")))b+=a.get(Be(D.Id)??"")?.size??0;for(let D of v)b+=Tn(D.ContentSize)??0;for(let D of[c,g,d,f])await D.flush();return{files:{...await Po(e),outsideAdded:await Ft(o(r,"outsideAdded")),outsideDeleted:await Ft(o(r,"outsideDeleted")),storage:{bringBack:h,undo:b},...e.queryAllFiles?{}:{blindSpot:!0}},createdSince:c.count,deletedWhileTaken:g.count,goneForGood:d.count,newFileVersion:f.count,changedBy:v}}async function Po(e){let{anchors:n,classFileOf:t}=e,o=new Z,s=new Set;for(let{objectApiName:c}of e.objects){if(c.toLowerCase()===le.toLowerCase())continue;if(!e.told.has(c)){for(let[d,f]of n.prefixes)f.toLowerCase()===c.toLowerCase()&&s.add(d);continue}let g=(d,f)=>Pn(o,t,c,d,f);await g(Mn.toDelete,Nt),await g(Mn.comesBack,jt),await g(Mn.lost,Lt)}let i=c=>s.has(c.LinkedEntityId.slice(0,3)),r=c=>new Ge(Re(e.previewDir,c)),a=r("linkAdded"),l=r("linkRemoved"),w=r("linkChanged");for(let{file:c}of n.now)for await(let g of se(c)){let d=Rn.safeParse(g);if(!d.success)throw new Error(`The org answered a link that does not read as one: ${d.error.message}`);let f=d.data,h=$n(f),b=n.held.get(h);if(b!==void 0){if(n.held.set(h,b|On),i(f)||n.sharings[b&~On]===$t(f))continue;let[R,j]=(n.sharings[b&~On]??"").split("/"),C={...f,ShareType:R,Visibility:j,now:{ShareType:f.ShareType,Visibility:f.Visibility}};await w.add(C);continue}i(f)||(n.files.flagsOf(f.ContentDocumentId)&_n)===0&&(o.flagsOf(f.LinkedEntityId)&Nt)===0&&await a.add(f)}let p=await jn.read(e.folder);for await(let c of Fn(e.folder)){let g=Gt(c,p);((n.held.get($n(g))??0)&On)!==0||i(g)||(n.files.flagsOf(g.ContentDocumentId)&(An|Sn))===0&&(o.flagsOf(g.LinkedEntityId)&(jt|Lt))===0&&await l.add(g)}for(let c of[a,l,w])await c.flush();return{unlink:a.count,relink:l.count,updateLinks:w.count}}async function zt(e){let{anchors:n,reader:t,classFileOf:o,signal:s}=e,i=[];for(let l of Cn.toDelete)for await(let w of dn(o(le,l)))typeof w.Id=="string"&&i.push(w.Id);if(i.length===0)return{links:0,files:0};let r=new Map,a=0;for(let l of Wt(Le(i,Je),In)){let w=l.map(g=>({objectApiName:me,soql:`SELECT Id, ContentDocumentId, LinkedEntityId FROM ${me} WHERE ContentDocumentId IN (${g})`,scanAll:!1})),c=(await ve(t,w,(g,d)=>{for(let f of d){let h=f.LinkedEntityId,b=f.ContentDocumentId;typeof h!="string"||typeof b!="string"||h.startsWith(mo)||At({LinkedEntityId:h},n.prefixes)===void 0&&(a++,r.set(b.slice(0,15),b))}},s)).find(g=>!g.read);if(c&&!c.read)throw new Error(`The links of the files to delete to what the checkpoint does not hold could not be read: ${c.reason}`)}if(r.size>0){let l=new Ge(o(le,"outsideParents"));for(let w of r.values())await l.add({Id:w});await l.flush()}return{links:a,files:r.size}}var Gn=Object.freeze({kind:"org",notHeld:new Map,heldAs:()=>"org",unseenOf:()=>Promise.resolve([]),requests:()=>0,diffAccess:()=>({kind:"org"})});function xn(e){return e.slice(0,15)}function Io(e,n,t,o){let s=n.detail!==void 0?` (${n.detail})`:"";switch(n.reason){case"noViewAll":case"noModifyAll":return`${t} ${o} View All and Modify All on ${e}`;case"parentNotSeen":return`${t} ${o} View All and Modify All on every record ${e} hangs from`+s;case"activities":return`${t} doesn't have View All Data and Modify All Data, which tasks and events need: Salesforce has no View All for activities`;case"catalog":return`${t} doesn't have View All Data and Modify All Data, which products and price books need: Salesforce has no View All or Modify All for them`;case"filesNotProven":return`${t} doesn't have View All Data and Modify All Data, which files need: nothing else proves who sees every file`;case"settingNotProven":return`${t} doesn't have View All Data and Modify All Data, which custom settings need: no permission on an object proves who sees and writes every row`}}async function ss(e){let{grants:n,reader:t}=e;if(n.kind==="org"||e.userId===void 0)return Gn;let o=e.checkpoint.objects,s=o.filter(f=>f.customSetting!==void 0).map(f=>f.objectApiName),i=new Map,r=n.requests,a=async f=>{let h=[...new Set(f)].filter(j=>!i.has(j.toLowerCase()));if(h.length===0)return;let b=t.calls(),R=await Promise.allSettled(h.map(j=>t.describe(j)));r+=t.calls()-b,R.forEach((j,C)=>{if(j.status==="rejected"&&j.reason instanceof te)throw j.reason;let v=j.status==="fulfilled"&&"body"in j.value?j.value.body:void 0,O=tn.safeParse(v);i.set(h[C].toLowerCase(),O.success?O.data:void 0)})},l=()=>[...i.values()].filter(f=>f!==void 0),w=async f=>{let h=f.filter(R=>!n.objects.has(R.toLowerCase()));await a(h);let b={grants:n.objects,describes:l(),customSettings:s};return await a(Pt(f,b)),It(f,{...b,describes:l()})},p=await w(o.map(f=>f.objectApiName)),c=xn(e.userId)===xn(e.checkpoint.takenBy.userId)?"no longer has":"doesn't have",g=new Map,d=new Map;for(let[f,h]of p)"access"in h?g.set(f,h.access):d.set(f,Io(f,h,e.username,c));return{kind:"perObject",userKey:xn(e.userId),notHeld:d,heldAs:f=>g.get(f),unseenOf:async f=>{let h=await w(f);return f.filter(b=>{let R=h.get(b);return R===void 0||!("access"in R)})},requests:()=>r,diffAccess:()=>({kind:"perObject",requests:r})}}var Lo=["giveBack","touched","createdSince","broughtBackSince","comesBackWithParent","unexplained","inBin","withParent","deletedWhileTaken","toRecreate","goneForGood","convertedLead","activatedContract","carrier","deletedWithCreatedParent","deletedWithParentOutside","deletedByOther","outOfReach","undoCannot","outsideParents","outsideAdded","outsideDeleted","newFileVersion"],vo="Lead",Bo="IsConverted",Fo="Contract",Eo="Status",qt="StatusCode",Mo="Activated",To=["createdSince","broughtBackSince"];function X(e,n,t){return jo(e,`${pe(n)}.${t}.ndjson`)}var Dn=1e3,_o=1440*6e4,$o=60*6e4,Wo=100,xo=2e3,Jt=["LastModifiedById","LastModifiedDate"];function ee(e){return typeof e=="string"&&e.length>=15?e.slice(0,15):void 0}function ke(e){let n=en(e);return n===null?Number.NaN:Date.parse(n)}function Hn(e){return e.toLowerCase()===le.toLowerCase()}function Go(e){return e==null||e===""}function Ie(e,n){let t=n.toLowerCase();return e.find(o=>o.toLowerCase()===t)}function Uo(e){return!e.leftOutFields.some(n=>n.reason==="base64")}var fn=class{constructor(n){this.file=n}file;lines=[];written=!1;count=0;async add(n){this.lines.push(`${JSON.stringify(n)}
|
|
9
|
+
`),this.count++,this.lines.length>=xo&&await this.flush()}async flush(){if(this.lines.length===0)return;let n=this.lines.join("");this.lines=[],await No(this.file,n,{encoding:"utf8",mode:nn,flag:this.written?"a":"w"}),this.written=!0}async discard(){this.lines=[],this.written&&await qn(this.file,{force:!0})}};async function Kn(e,n){await Promise.all(Lo.map(t=>qn(X(e,n,t),{force:!0})))}var Un=class{constructor(n){this.activeFrom=n}activeFrom;counts=new Map;active=new Set;add(n){let t=n.LastModifiedById;typeof t!="string"||t===""||(this.counts.set(t,(this.counts.get(t)??0)+1),ke(n.LastModifiedDate)>=this.activeFrom&&this.active.add(t))}byUser(){return Object.fromEntries([...this.counts].sort(([n],[t])=>n<t?-1:n>t?1:0))}};function Qt(e,n){let t,o=async()=>{let s=new Set;try{for await(let i of se(at(e,n))){let r=ee(i.Id);r!==void 0&&s.add(r)}}catch(i){throw i.code!=="ENOENT"?i:new Error(`The checkpoint\u2019s list of what ${n} held in the recycle bin is not on this machine.`)}return s};return async s=>(await(t??=o())).has(s)}async function zo(e,n,t,o){let s=pe(n.objectApiName),i=n.readMode==="scanAllLive",r=i?" AND IsDeleted = false":"",a=async p=>{let c=e.lane(),g=[];try{let d=await kt(c,{objectApiName:s,soql:p,scanAll:i},f=>{g.push(...f)});if(!d.read)throw new Error(d.reason);return g}finally{c.close()}},l=t.length>Wo?rn/4:rn,w=new Map;for(let p of Le(o,l)){let c=await nt(`SELECT ${t.join(", ")} FROM ${s} WHERE Id IN (${p})${r}`,a,{stamp:"SystemModstamp",...i?{idsWhere:"IsDeleted = false"}:{}});for(let g of c){let d=ee(g.Id);d!==void 0&&w.set(d,g)}}return w}var qo=/__(?:c|pc|s)$/i,Ho=/^(.+)__[A-Za-z]+__s$/i,Ko=/^(.+)__pc$/i,Vo=/^[A-Za-z][A-Za-z0-9_]*$/,Jo=200;function Qo(e,n){if(!qo.test(n)||!Vo.test(n))return;let t=Ko.exec(n);if(t)return{entity:je,name:`${t[1]}__c`};let o=Ho.exec(n);return o?{entity:e,name:`${o[1]}__c`}:{entity:e,name:n}}var Zo=hn(wn({QualifiedApiName:Xn()}).loose());function Xo(e,n){let t=`SELECT QualifiedApiName FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName = '${pe(e)}' AND QualifiedApiName IN (`,o=r=>`${t}${r.map(a=>`'${a}'`).join(", ")})`,s=[],i=[];for(let r of n){let a=[...i,r],l=a.length>Jo||encodeURIComponent(o(a)).length>14e3;i.length>0&&l?(s.push({soql:o(i),names:i}),i=[r]):i=a}return i.length>0&&s.push({soql:o(i),names:i}),s}async function Yo(e,n){let t=new Map,o=new Map;for(let[r,a]of n){let l={removed:[],hidden:[]};t.set(r,l);for(let w of a){let p=Qo(r,w);if(p===void 0){l.hidden.push(w);continue}let c=o.get(p.entity)??new Map;o.set(p.entity,c);let g=p.name.toLowerCase(),d=c.get(g)??{name:p.name,fields:[]};c.set(g,d),d.fields.push({objectApiName:r,field:w})}}let s=0,i=new Map;for(let[r,a]of o){let l=new Set,w=new Map,p=Xo(r,[...a.values()].map(({name:c})=>c));for(let c of p){s++;try{let g=await e.tooling(c.soql);if(!g.done)throw new Error("FieldDefinition answered more than one page");let d=Zo.safeParse(g.records);if(!d.success)throw new Error("FieldDefinition answered rows with no field name");for(let f of d.data)l.add(f.QualifiedApiName.toLowerCase())}catch(g){if(g instanceof te)throw g;let d=Pe(g);for(let f of c.names)w.set(f.toLowerCase(),d)}}for(let[c,{fields:g}]of a){let d=w.get(c);for(let{objectApiName:f,field:h}of g){let b=t.get(f);if(b!==void 0)if(d!==void 0){let R=i.get(f)??{fields:[],reasons:[]};i.set(f,R),R.fields.push(h),R.reasons.includes(d)||R.reasons.push(d)}else l.has(c)?b.hidden.push(h):b.removed.push(h)}}}for(let[r,a]of t){a.removed.sort(),a.hidden.sort();let l=i.get(r);l!==void 0&&(a.uncertain={fields:l.fields.sort(),...l.reasons.length>0?{reason:l.reasons.join("; ")}:{}})}return{gone:t,requests:s}}async function Ht(e,n,t){let{checkpoint:o,folder:s,reader:i}=e,r=new Date(Date.parse(o.readFrom)-_o).toISOString(),a=await Promise.allSettled(n.map(({objectApiName:h})=>i.describe(h,r))),l,w=new Map,p=new Map;for(let[h,b]of a.entries()){let R=n[h].objectApiName;if(b.status==="rejected"){if(b.reason instanceof te)throw b.reason;w.set(R,{unread:`The org did not answer the describe of ${R}: ${Pe(b.reason)}`});continue}if("notModified"in b.value){w.set(R,{gone:new Set});continue}let j=tn.safeParse(b.value.body);if(!j.success){w.set(R,{unread:`The describe of ${R} does not read as one.`});continue}t.set(R,j.data);try{let C=(await(l??=dt(s,o.objects))).get(R);if(C===void 0)throw new Error(`The checkpoint holds no field prints of ${R}.`);p.set(R,rt(C,st(j.data.fields)))}catch(C){w.set(R,{unread:Pe(C)})}}let c=new Map(n.map(h=>[h.objectApiName,new Set(bn(h.objectApiName,h.fields,o.ignoredFields).map(b=>b.toLowerCase()))])),g=(h,b)=>b.filter(R=>c.get(h)?.has(R.toLowerCase())===!0),d=new Map([...p].map(([h,b])=>[h,g(h,b.removed)]).filter(([,h])=>h.length>0)),f=d.size>0?await Yo(i,d):{gone:new Map,requests:0};for(let[h,{removed:b,added:R,changed:j}]of p){let C=f.gone.get(h);w.set(h,{...g(h,b).length+R.length+j.length>0?{drift:{removed:C?.removed??[],added:R,changed:j,...C!==void 0&&C.hidden.length>0?{hidden:C.hidden}:{},...C?.uncertain!==void 0?{uncertain:C.uncertain}:{}}}:{},gone:new Set(b.map(v=>v.toLowerCase()))})}return{now:w,requests:f.requests}}function ei(e,n){let t=i=>{let r=n.get(i);return r!==void 0&&!("unread"in r)&&r.moved},o=e.find(({objectApiName:i})=>i===je),s=o!==void 0&&Ie(o.fields,an)!==void 0&&t(je);return e.filter(({objectApiName:i})=>t(i)||s&&i===mn)}function ni(e,n){let t=[...e.cascadeParents,...e.restrictParents??[]].filter(s=>!n.has(s.toLowerCase()));if(e.customSetting!==void 0){let s=Ie(e.fields,kn(e.customSetting));s!==void 0&&!n.has(s.toLowerCase())&&!t.includes(s)&&t.push(s)}if(Hn(e.objectApiName))for(let s of ut){let i=Ie(e.fields,s);i!==void 0&&!n.has(i.toLowerCase())&&t.push(i)}let o=Ie(e.fields,an);if(e.objectApiName===je&&o!==void 0){let s=Ie(e.fields,"AccountId");for(let i of[o,s])i!==void 0&&!n.has(i.toLowerCase())&&t.push(i)}return[...t,...Jt]}async function ti(e,n,t){let{folder:o,checkpoint:s}=e.input,i=new Map,r=new Map;for(let{objectApiName:a,cascadeParents:l,restrictParents:w=[]}of n){let p=t.get(a);if(!p||"unread"in p||!p.deleted||p.deleted.rows===0)continue;let c=new Map,g=new Map;try{let d=await $e.read(o,s.snapshotId,a),f=Qt(o,a);for await(let h of se(p.deleted.file)){let b=ee(h.Id);if(b===void 0)continue;let R=v=>v.map(O=>ee(h[O])).filter(O=>O!==void 0&&O!==b),j=ee(h.LastModifiedById),C=()=>({objectApiName:a,id:String(h.Id),stamp:ke(h.SystemModstamp),parents:R(l),restricts:R(w),...j!==void 0?{by:j}:{}});if(!d.retired(h.Id)){if(!d.has(h.Id)){if(await f(b)){g.set(b,C());continue}if(ke(h.CreatedDate)>=e.t0s&&g.set(b,C()),!(ke(h.CreatedDate)<e.t0s))continue}c.set(b,C())}}}catch(d){if(d instanceof te)throw d;continue}for(let[d,f]of c)i.set(d,f);for(let[d,f]of g)r.set(d,f)}return{back:i,gone:r}}function oi(e,n){let t=s=>e.get(s)?.stamp??n.get(s)?.stamp,o=new Set;for(let s of[e,n])for(let[i,r]of s)[...r.parents,...r.restricts].some(l=>(t(l)??0)>r.stamp)&&o.add(i);return zn(o,e,n),o}function zn(e,n,t){let o=s=>n.get(s)?.stamp??t.get(s)?.stamp;for(let s=e.size>0;s;){s=!1;for(let i of[n,t])for(let[r,a]of i){if(e.has(r))continue;a.parents.some(w=>e.has(w)&&o(w)===a.stamp)&&(e.add(r),s=!0)}}for(let s of e)n.delete(s)}function ii(e,n){if(n===void 0)return new Set;let t=[...e].filter(([,o])=>o.by!==n).map(([o])=>o);return Zt(t,e)}function Zt(e,n){let t=new Set(e);for(let o=t.size>0;o;){o=!1;for(let[s,i]of n){if(t.has(s))continue;i.parents.some(a=>t.has(a)&&n.get(a)?.stamp===i.stamp)&&(t.add(s),o=!0)}}return t}function si(e,n,t){let o=new Map(e.map(l=>[l.objectApiName,l.undeletable])),s=new Set,i=new Set,r=(l,w)=>l.parents.find(p=>!w.has(p)&&t.get(p)?.stamp===l.stamp),a=l=>l.parents.some(w=>n.get(w)?.stamp===l.stamp);for(let l of[...n.values()]){if(a(l))continue;let w=new Set,p=[],c=r(l,w),g=!1;for(;c!==void 0;){w.add(c),p.push(c);let h=t.get(c);if(!h)break;if(a(h)){g=!0;break}c=r(h,w)}let d=p[p.length-1];if(d===void 0||g)continue;let f=t.get(d);if(!(!f||o.get(f.objectApiName)!==!0)){s.add(d);for(let h of p.slice(0,-1))i.add(h)}}for(let l of[...s,...i]){let w=t.get(l);w&&n.set(l,w)}return s}function ri(e,n,t){let o=new Map;for(let[s,i]of e){if(t.has(s)){o.set(s,"deletedWithParentOutside");continue}if(n.has(s))continue;i.parents.some(a=>!e.has(a)&&n.get(a)?.stamp===i.stamp)&&o.set(s,"deletedWithCreatedParent")}for(let s=o.size>0;s;){s=!1;for(let[i,r]of e){if(o.has(i))continue;let a=r.parents.find(w=>o.has(w)&&e.get(w)?.stamp===r.stamp),l=a===void 0?void 0:o.get(a);l!==void 0&&(o.set(i,l),s=!0)}}for(let s of o.keys())e.delete(s);return o}async function ai(e,n,t,o,s,i){let r=new Set,a=new Set,l=new Set(n.map(({objectApiName:d})=>d.toLowerCase())),w=new Map(n.map(d=>[d.objectApiName,d])),p=new Map;for(let[d,f]of t)o.has(d)||s.has(d)||f.parents.some(b=>(t.get(b)??o.get(b))?.stamp===f.stamp)||p.set(f.objectApiName,[...p.get(f.objectApiName)??[],f]);if(p.size===0)return{outside:r,stuck:a,requests:0};let c=e.reader.calls(),g=async d=>{try{return await i(d)}catch(f){if(f instanceof te)throw f;return}};for(let[d,f]of p){let h=w.get(d),b=await g(d);if(!h||!b)continue;let R=new Set([...h.cascadeParents,...h.restrictParents??[]].map(P=>P.toLowerCase())),j=b.fields.filter(P=>P.type==="reference"&&!R.has(P.name.toLowerCase())&&(P.referenceTo??[]).some(H=>!l.has(H.toLowerCase())));if(j.length===0)continue;let C=[...new Set(j.flatMap(P=>(P.referenceTo??[]).filter(H=>!l.has(H.toLowerCase()))))],v=await Promise.all(C.map(g)),O=new Map;if(v.forEach((P,H)=>{if(!P)return;let Q=P.keyPrefix;for(let z of P.childRelationships??[]){if(z.cascadeDelete!==!0||z.childSObject.toLowerCase()!==d.toLowerCase())continue;let fe=j.find(oe=>oe.name.toLowerCase()===z.field.toLowerCase());fe&&O.set(fe.name,[...O.get(fe.name)??[],{object:C[H],...typeof Q=="string"?{prefix:Q}:{}}])}}),O.size===0)continue;let B=[...O.keys()].map(pn),W=pe(d),D=f.map(P=>P.id),L=new Map,N=Le(D).map(P=>({objectApiName:W,soql:`SELECT Id, ${B.join(", ")} FROM ${W} WHERE Id IN (${P}) AND IsDeleted = true`,scanAll:!0}));if((await ve(e.reader,N,(P,H)=>{for(let Q of H){let z=ee(Q.Id);if(z!==void 0)for(let[fe,oe]of O){let ue=Q[fe];if(typeof ue!="string"||ee(ue)===void 0)continue;let Ae=oe.length===1?oe[0]:oe.find(he=>he.prefix!==void 0&&ue.startsWith(he.prefix));Ae&&L.set(z,[...L.get(z)??[],{object:Ae.object,id:ue}])}}},e.signal)).some(P=>!P.read))continue;let J=new Map;for(let P of L.values())for(let{object:H,id:Q}of P)J.set(H,[...J.get(H)??[],Q]);let Y=[];for(let[P,H]of J){let Q=pe(P);for(let z of Le([...new Set(H)]))Y.push({object:P,read:{objectApiName:Q,soql:`SELECT Id, IsDeleted, SystemModstamp FROM ${Q} WHERE Id IN (${z})`,scanAll:!0}})}let x=new Map;await ve(e.reader,Y.map(({read:P})=>P),(P,H)=>{for(let Q of H){let z=ee(Q.Id);z!==void 0&&Q.IsDeleted===!0&&x.set(z,ke(Q.SystemModstamp))}},e.signal);for(let P of f){let H=ee(P.id);if(H!==void 0)for(let{id:Q}of L.get(H)??[]){let z=x.get(ee(Q)??"");z!==void 0&&(z===P.stamp?r.add(H):z>P.stamp&&a.add(H))}}}return{outside:r,stuck:a,requests:e.reader.calls()-c}}async function ci(e,n,t,o){let s=[...new Set([...e.values()].map(({objectApiName:l})=>l))],i=await Promise.allSettled(s.map(t)),r=new Map([...n.keys()].map(l=>[l.toLowerCase(),l])),a=new Map;for(let[l,w]of i.entries()){if(w.status==="rejected"){if(w.reason instanceof te)throw w.reason;let p=s[l];o.set(p,Pe(w.reason));for(let[c,g]of e)g.objectApiName===p&&e.delete(c);continue}for(let p of w.value.childRelationships??[]){let c=r.get(p.childSObject.toLowerCase());if(c===void 0)continue;let g=Ie(n.get(c)??[],p.field);if(g===void 0)continue;let d=a.get(c);d||(d=new Set,a.set(c,d)),d.add(g)}}return new Map([...a].map(([l,w])=>[l,[...w]]))}async function di(e,n){let t=new Set,o=e.find(({objectApiName:i})=>i===je);if(!o||Ie(o.fields,an)===void 0)return t;let s=n.get(je);if(!s||"unread"in s||!s.live)return t;try{for await(let i of se(s.live.file)){let r=ee(i.AccountId);r!==void 0&&vn(je,i)&&t.add(r)}}catch{return new Set}return t}async function fi(e,n,t,o){if("unread"in t)return{unread:t.unread};let{input:s,previewDir:i,t0s:r,back:a,carriers:l,stranded:w,stuck:p,others:c,personAccounts:g}=e,{folder:d,reader:f,checkpoint:h,signal:b}=s,R=n.objectApiName,j=Hn(R)?e.files:void 0,C=L=>j===void 0||j.anchoredThen(L),v=new Map,O=L=>{let N=v.get(L);return N||(N=new fn(X(i,R,L)),v.set(L,N)),N},B=L=>v.get(L)?.count??0,W=new Un(e.activeFrom),D=[];try{let L=await $e.read(d,h.snapshotId,R),N=Qt(d,R),{gone:V}=o,J=wt(R,h.ignoredFields),Y=bn(R,n.fields,[]),x=m=>J.has(m.toLowerCase())||V.has(m.toLowerCase()),P=Y.filter(m=>!x(m)).map(pn),H=Y.filter(x),Q=R===vo?Ie(n.fields,Bo):void 0,z=Q!==void 0&&!V.has(Q.toLowerCase())?Q:void 0,fe=R===Fo?Ie(n.fields,Eo):void 0,oe=fe!==void 0&&P.includes(fe)?fe:void 0,ue=["Id","SystemModstamp",...Jt,...P,...z!==void 0&&!P.includes(z)?[z]:[],...oe!==void 0?[qt]:[]],Ae=n.cascadeParents.filter(m=>!V.has(m.toLowerCase())),he=(n.restrictParents??[]).filter(m=>!V.has(m.toLowerCase())),Se=R===je&&Ie(n.fields,an)!==void 0,De=m=>Se&&vn(R,m),ye=Uo(n)?"toRecreate":"goneForGood",ze=e.access.heldAs(R)==="parent"?"outOfReach":ye,be=r-Dn,ne={fields:0,cleared:0,liveNotHeld:0,deletedHeld:0},Fe=m=>{let A=ee(m.Id);if(A===void 0)throw new Error(`${R} answered a record without its Id.`);return{id:String(m.Id),key:A}},ge=(m,A,I)=>m.map($=>ee(A[$])).filter($=>$!==void 0&&$!==I),we=(m,A)=>ge(Ae,m,A),Ee=(m,A)=>{let I=ke(m.SystemModstamp);return we(m,A).some($=>a.get($)?.stamp===I)},sn=Date.parse(h.takenAt),Ze=Date.parse(s.readAt)-Dn,Me=(m,A,I,$)=>{W.add(m);let S=we(m,I),F=ge(he,m,I),U=$&&ke(m.CreatedDate)>=sn&&ke(m.LastModifiedDate)<=Ze;n.undeletable&&S.length+F.length===0||D.push({id:A,parents:S,restricts:F,goesAlong:U,undeletable:n.undeletable})},ae=new Map,qe=e.lookups.get(R)??[];if(qe.length>0&&L.size>0)for await(let m of L.records()){if(De(m))continue;let A=ee(m.Id);if(A===void 0)continue;let I=qe.filter($=>{let S=ee(m[$]);return S!==void 0&&a.has(S)});I.length>0&&ae.set(A,{id:String(m.Id),fields:I})}let Te=async m=>{if(m.length===0)return;if(P.length===0){for(let F of m)F.stamp!==F.held&&await O("touched").add({Id:F.id});return}let A=m.map(F=>F.id),I=new Map,$=await L.chunk(A).batches(h.snapshotId,R,rn);for await(let F of $??[])for(let U of F){let G=ee(U.Id);G!==void 0&&I.set(G,U)}if(b?.aborted)throw new te;let S=await zo(f,n,ue,A);for(let F of m){let U=S.get(F.key);if(!U)continue;let G=I.get(F.key);if(!G)throw new Error(`The checkpoint\u2019s snapshot of ${R} does not hold record ${F.id}, which its index names.`);if(z!==void 0&&G[z]!==!0&&U[z]===!0){await O("convertedLead").add({Id:F.id});continue}if(oe!==void 0&&U[qt]===Mo&&!Nn(G[oe],U[oe])){await O("activatedContract").add({Id:F.id});continue}let ie=P.filter(ce=>!Nn(G[ce],U[ce]));if(ie.length>0){ne.fields+=ie.length;let ce=(F.cleared??[]).filter(un=>ie.includes(un)&&Go(U[un]));ce.length>0&&ne.cleared++,await O("giveBack").add({Id:F.id,fields:ie,...ce.length>0?{cleared:ce}:{}}),W.add(U)}else ke(U.SystemModstamp)!==F.held&&await O("touched").add({Id:F.id})}},Ce=[],Ne=async m=>{Ce.push(m),Ce.length>=Ve&&(await Te(Ce),Ce=[])};if(t.live)for await(let m of se(t.live.file)){let{id:A,key:I}=Fe(m),$=De(m),S=L.stampOf(A);if(S!==void 0){if($||!C(A))continue;let U=ae.get(I)?.fields;U&&ae.delete(I);let G=R===mn&&g.delete(I),ie=ke(m.SystemModstamp);(U||G||ie!==S||S>=be)&&await Ne({id:A,key:I,held:S,stamp:ie,...U?{cleared:U}:{}});continue}if(ne.liveNotHeld++,$)continue;let F=await N(I)?"broughtBackSince":ke(m.CreatedDate)>=r?"createdSince":void 0;F===void 0?await O("unexplained").add({Id:A}):j!==void 0&&!j.anchoredNow(A)?await O("outsideAdded").add({Id:A}):(await O(F).add({Id:A}),Me(m,A,I,!0))}for(let[m,A]of ae){let I=L.stampOf(A.id);I!==void 0&&await Ne({id:A.id,key:m,held:I,stamp:I,cleared:A.fields})}if(R===mn)for(let m of g){let A=L.rowOf(m);if(A<0||(g.delete(m),ae.has(m)))continue;let I=L.idAt(A),$=L.stampOf(I);$!==void 0&&await Ne({id:I,key:m,held:$,stamp:$})}if(await Te(Ce),t.deleted)for await(let m of se(t.deleted.file)){let{id:A,key:I}=Fe(m);if(L.retired(A))continue;let $=De(m);if(L.has(A)){if(ne.deletedHeld++,$)continue;if(!C(A)){await O("outsideDeleted").add({Id:A});continue}let S=w.get(I);c.has(I)?await O("deletedByOther").add({Id:A}):p.has(I)?await O(e.answeredGone.has(I)?ze:ye).add({Id:A}):S!==void 0?await O(S).add({Id:A}):Ee(m,I)?await O("withParent").add({Id:A}):n.undeletable?await O("inBin").add({Id:A}):await O(ye).add({Id:A});continue}if(l.has(I)&&!$){await O("carrier").add({Id:A});continue}if(!($||await N(I)))if(ke(m.CreatedDate)<r){let S=w.get(I),F=C(A)?c.has(I)?"deletedByOther":p.has(I)?"goneForGood":S??"deletedWhileTaken":"outsideDeleted";await O(F).add({Id:A})}else Ee(m,I)&&(await O("comesBackWithParent").add({Id:A}),Me(m,A,I,!1))}let He=t.count;if(L.size>0&&He===void 0)throw new Error(`The org gave no count of the ${R} records it holds.`);if(L.size-((He??0)-ne.liveNotHeld)-ne.deletedHeld>0){let m=new lt(L);if(t.deleted)for await(let S of se(t.deleted.file))m.mark(S.Id);let[A]=await ve(f,[mt(R,n.readMode)],(S,F)=>{for(let U of F)m.mark(U.Id)},b);if(!A.read)throw new Error(A.reason);let I=[],$=async()=>{let S=new Set;if(Se){let F=await L.chunk(I).batches(h.snapshotId,R,rn);for await(let U of F??[])for(let G of U){let ie=ee(G.Id);ie!==void 0&&De(G)&&S.add(ie)}}for(let F of I)S.has(F.slice(0,15))||await O(C(F)?ze:"outsideDeleted").add({Id:F});I=[]};for(let S of m.ids())I.push(S),I.length>=Ve&&await $();await $()}for(let m of v.values())await m.flush();let Ye=B("toRecreate"),_e=B("goneForGood"),k=B("convertedLead"),E=B("activatedContract"),K=B("deletedWithCreatedParent"),u=B("deletedWithParentOutside"),y=B("deletedByOther"),T=B("outOfReach"),M=B("carrier");return{told:{diff:{objectApiName:R,toDelete:{createdSince:B("createdSince"),broughtBackSince:B("broughtBackSince"),comesBackWithParent:B("comesBackWithParent")},toGiveBack:{records:B("giveBack"),fields:ne.fields,clearedLookups:ne.cleared},toBringBack:{inBin:B("inBin"),withParent:B("withParent"),deletedWhileTaken:B("deletedWhileTaken"),...M>0?{carriers:M}:{}},...Ye>0?{toRecreate:Ye}:{},cannotUndo:[..._e>0?[{reason:"goneForGood",count:_e}]:[],...k>0?[{reason:"convertedLead",count:k}]:[],...E>0?[{reason:"activatedContract",count:E}]:[],...K>0?[{reason:"deletedWithCreatedParent",count:K}]:[],...u>0?[{reason:"deletedWithParentOutside",count:u}]:[],...y>0?[{reason:"deletedByOther",count:y}]:[],...T>0?[{reason:"outOfReach",count:T}]:[]],outside:[],touched:B("touched"),unexplained:B("unexplained"),lastChangedBy:W.byUser(),...o.drift?{schemaDrift:o.drift}:{},notCompared:H},people:W,pending:D}}}catch(L){for(let N of v.values())await N.discard();if(L instanceof te)throw L;return{unread:Pe(L)}}}async function*Xt(e,n){let t=[];for(let o of To)if(n.diff.toDelete[o]!==0)for await(let s of se(X(e,n.diff.objectApiName,o)))typeof s.Id=="string"&&(t.push(s.Id),t.length>=Ve&&(yield t,t=[]));t.length>0&&(yield t)}async function li(e,n,t,o,s){let{input:i,previewDir:r}=e,a=n.diff.objectApiName,w=((await t(a)).childRelationships??[]).filter(C=>C.cascadeDelete===!0&&!s.has(C.childSObject.toLowerCase()));if(w.length===0)return[];let p=await o(),c=w.filter(C=>p.has(C.childSObject));if(c.length===0)return[];let g=new Set(await e.access.unseenOf([...new Set(c.map(({childSObject:C})=>C))])),d=c.filter(({childSObject:C})=>!g.has(C));if(d.length===0)return[];let f=Date.parse(i.checkpoint.takenAt);if(!Number.isFinite(f))throw new Error(`Not a date: ${i.checkpoint.takenAt}`);let h=pt(Math.ceil(f/Dn)*Dn),b=new Map,R=new Map,j=new Map;for await(let C of Xt(r,n)){let v=d;for(;v.length>0;){let O=[];for(let D of v){let L=pe(D.childSObject),N=pn(D.field),V=gt(L)==="scanAllLive",J=j.get(L)??"CreatedDate";for(let Y of Le(C))O.push({child:L,field:N,read:{objectApiName:L,soql:`SELECT Id, ${N} FROM ${L} WHERE ${N} IN (${Y}) AND ${J} >= ${h}${V?" AND IsDeleted = false":""}`,scanAll:V}})}let B=await ve(i.reader,O.map(({read:D})=>D),(D,L)=>{let{child:N,field:V}=O[D],J=b.get(N);J||(J={records:new Set,parents:new Set},b.set(N,J));for(let Y of L){let x=ee(Y.Id),P=ee(Y[V]);x!==void 0&&J.records.add(x),P!==void 0&&(J.parents.add(P),R.set(P,String(Y[V])))}},i.signal),W=new Set;B.forEach((D,L)=>{if(D.read)return;let{child:N}=O[L];if(!j.has(N)&&/No such column 'CreatedDate'/.test(D.reason)){W.add(N);return}throw new Error(`The ${D.objectApiName} records its deletion would take along could not be read: `+D.reason)});for(let D of W)j.set(D,"SystemModstamp");v=v.filter(D=>W.has(pe(D.childSObject)))}}if(R.size>0){let C=new fn(X(r,a,"outsideParents"));for(let v of R.values())await C.add({Id:v});await C.flush()}return[...b].filter(([,{records:C}])=>C.size>0).sort(([C],[v])=>C<v?-1:C>v?1:0).map(([C,{records:v,parents:O}])=>({objectApiName:C,count:v.size,parents:O.size}))}async function ui(e,n,t,o){if(e.kind==="org")return;let{objectApiName:s,toDelete:i}=n.diff,r=i.createdSince+i.broughtBackSince;if(r===0)return;let l=((await t(s)).childRelationships??[]).filter(d=>d.cascadeDelete===!0).map(d=>d.childSObject);if(l.length===0)return;let w=await o(),p=[...new Set(l.filter(d=>w.has(d)))].sort(),g=[...p.length>0?await e.unseenOf(p):[]].sort((d,f)=>+!Kt.has(d)-+!Kt.has(f));return g.length>0?{objectApiName:s,children:g,records:r}:void 0}var Kt=new Set(["Event","Task"]);async function gi(e,n){let t=new Set(n.flatMap(({pending:c})=>c.flatMap(({parents:g,restricts:d})=>[...g,...d]))),o=new Set;if(t.size>0)for(let c of n)for await(let g of Xt(e,c))for(let d of g){let f=d.slice(0,15);t.has(f)&&o.add(f)}let s=new Map(n.flatMap(({pending:c})=>c.map(g=>[g.id.slice(0,15),g]))),i=c=>c.goesAlong?c.parents.find(g=>o.has(g)):void 0,r=(c,g=new Set)=>{let d=s.get(c),f=d&&!g.has(c)?i(d):void 0;return f===void 0?c:r(f,new Set([...g,c]))},a=new Map,l=(c,g)=>{let d=a.get(c);if(d!==void 0)return d;a.set(c,!1);let f=r(c),h=g.restricts.some(b=>o.has(b)&&r(b)!==f)||g.parents.some(b=>{let R=s.get(b);return R!==void 0&&i(R)!==void 0&&l(b,R)});return a.set(c,h),h},w=[],p=[];for(let{diff:c,pending:g}of n){let d=c.objectApiName,f=O=>i(O)!==void 0&&!l(O.id.slice(0,15),O),h=g.filter(f).length;h>0&&p.push({objectApiName:d,count:h});let b=g.filter(O=>!f(O)),R=b.filter(O=>[...O.parents,...O.restricts].some(B=>o.has(B))),j=new Set(R.map(({id:O})=>O)),C=b.filter(O=>!O.undeletable&&!j.has(O.id));if(C.length+R.length===0)continue;let v=new fn(X(e,d,"undoCannot"));for(let{id:O}of C)await v.add({Id:O});for(let{id:O}of R)await v.add({Id:O,reason:"deletedBeforeParent"});await v.flush(),C.length>0&&w.push({objectApiName:d,count:C.length}),R.length>0&&w.push({objectApiName:d,count:R.length,reason:"deletedBeforeParent"})}return{undoCannot:w,withParentDeleted:p}}async function hi(e,n,t){let o={};if(n.length===0)return o;let s=Le([...n].sort()).map(i=>({objectApiName:"User",soql:`SELECT Id, Name FROM User WHERE Id IN (${i})`,scanAll:!1}));return await ve(e,s,(i,r)=>{for(let a of r)typeof a.Id=="string"&&typeof a.Name=="string"&&(o[a.Id]=a.Name)},t),o}function Vt(e){let{toDelete:n,toGiveBack:t,toBringBack:o}=e;return n.createdSince+n.broughtBackSince+n.comesBackWithParent+t.records+o.inBin+o.withParent+o.deletedWhileTaken+(o.carriers??0)+(e.toRecreate??0)+e.touched+e.unexplained+e.cannotUndo.reduce((s,i)=>s+i.count,0)>0||e.schemaDrift!==void 0}async function wi(e){let n=await e.describe(me),t=tn.safeParse("body"in n?n.body:null);if(!t.success)throw new Error(`The org gave no describe of ${me}.`);return t.data}function Yt(e){return(n,t)=>X(e,n,t)}async function pi(e,n){let t=n.fileObject.objectApiName,o=n.changes.get(t);if(!(n.unread.has(t)||o===void 0||"unread"in o))try{return{anchors:await xt({reader:e.reader,folder:e.folder,previewDir:n.previewDir,snapshotId:e.checkpoint.snapshotId,objects:n.ordered,changes:n.changes,linkDescribe:n.linkDescribe,describeGlobal:e.describeGlobal,...e.signal?{signal:e.signal}:{}})}}catch(s){if(s instanceof te)throw s;return{unread:"The links of its files to the records of the checkpoint could not be read: "+Pe(s)}}}async function eo(e){await Promise.all(["linkAdded","linkRemoved","linkChanged"].map(n=>qn(Re(e,n),{force:!0})))}async function mi(e,n){let t=n.fileObject.objectApiName,o=n.outcomes.get(t),s=n.changes.get(t);if(o===void 0||!("told"in o)||s===void 0)return;let i=new Set([...n.outcomes].filter(([,r])=>"told"in r).map(([r])=>r));try{let r=await Ut({anchors:n.anchors,reader:e.reader,folder:e.folder,snapshotId:e.checkpoint.snapshotId,t0s:n.t0s,objects:n.ordered,fileChanges:s,told:i,classFileOf:Yt(n.previewDir),previewDir:n.previewDir,queryAllFiles:e.checkpoint.takenBy?.queryAllFiles===!0&&e.queryAllFiles!==!1,...e.signal?{signal:e.signal}:{}}),{diff:a,people:l}=o.told;a.toDelete.createdSince+=r.createdSince,a.toBringBack.deletedWhileTaken+=r.deletedWhileTaken;for(let g of r.changedBy)l.add(g);a.lastChangedBy=l.byUser();let w=r.goneForGood,p=r.newFileVersion,c=a.cannotUndo.find(g=>g.reason==="goneForGood");return c!==void 0?c.count+=w:w>0&&a.cannotUndo.unshift({reason:"goneForGood",count:w}),a.cannotUndo.push(...p>0?[{reason:"newFileVersion",count:p}]:[]),r.files}catch(r){if(r instanceof te)throw r;await Kn(n.previewDir,t),await eo(n.previewDir),n.outcomes.set(t,{unread:Pe(r)});return}}async function ki(e,n){let t=n.fileObject.objectApiName,o=n.outcomes.get(t);if(o===void 0||!("told"in o))return;let{diff:s}=o.told;if(s.toDelete.createdSince+s.toDelete.broughtBackSince!==0)try{let{links:i,files:r}=await zt({anchors:n.anchors,reader:e.reader,classFileOf:Yt(n.previewDir),...e.signal?{signal:e.signal}:{}});if(i===0)return;s.outside=[...s.outside.filter(({objectApiName:a})=>a!==me),{objectApiName:me,count:i,parents:r}].sort((a,l)=>a.objectApiName<l.objectApiName?-1:a.objectApiName>l.objectApiName?1:0)}catch(i){if(i instanceof te)throw i;await Kn(n.previewDir,t),await eo(n.previewDir),n.outcomes.set(t,{unread:Pe(i)})}}async function Is(e){let{checkpoint:n,folder:t,reader:o,previewId:s,readAt:i,signal:r}=e,a=Date.parse(n.readFrom);if(!Number.isFinite(a))throw new Error(`Not a date: ${n.readFrom}`);let l=Date.parse(i);if(!Number.isFinite(l))throw new Error(`Not a date: ${i}`);if(r?.aborted)throw new te;let w=a-(a%1e3+1e3)%1e3,p=ct(t,s);await yn(p);let c=[...n.objects].sort((k,E)=>k.readOrder-E.readOrder),g=e.access??Gn,d=c.filter(({objectApiName:k})=>!g.notHeld.has(k)),f=new Map,h=n.files!==void 0?d.find(({objectApiName:k})=>Hn(k)):void 0,b=await yt(o,d.map(({objectApiName:k})=>k),n.readFrom,r),R=new Map(d.map(({objectApiName:k},E)=>[k,b[E]])),j=ei(d,R),C=h!==void 0?wi(o):void 0;C?.catch(()=>{});let v=await Ht(e,j,f),O=v.requests,B=new Map,W=new Set,D=[];for(let k of c){let E=k.objectApiName,K=g.notHeld.get(E);if(K!==void 0){B.set(E,K);continue}let u=R.get(E);if(u===void 0||"unread"in u){B.set(E,u?.unread??"Its newest record was not read.");continue}let y=v.now.get(E);y===void 0?(W.add(E),D.push({object:k,fields:{gone:new Set},check:u})):"unread"in y?B.set(E,y.unread):D.push({object:k,fields:y,check:u})}let L=await bt(o,D.map(({object:k,fields:E})=>({objectApiName:k.objectApiName,readMode:k.readMode,held:k.records>0,fields:ni(k,E.gone)})),n.readFrom,p,r,D.map(({check:k})=>k)),N=new Map(D.map(({object:k},E)=>[k.objectApiName,L[E]])),V=D.filter(({object:k})=>{if(!W.has(k.objectApiName))return!1;let E=N.get(k.objectApiName);return E!==void 0&&!("unread"in E)&&E.count!==void 0&&E.count<k.records});if(V.length>0){let k=await Ht(e,V.map(({object:E})=>E),f);O+=k.requests;for(let E of V){let K=E.object.objectApiName;W.delete(K);let u=k.now.get(K);u===void 0||"unread"in u?B.set(K,u?.unread??"Its describe was not read."):E.fields=u}}let J=new Map,Y=k=>{let E=f.get(k);if(E)return Promise.resolve(E);let K=J.get(k);return K||(K=(async()=>{let u=await o.describe(k),y=tn.safeParse("body"in u?u.body:null);if(!y.success)throw new Error(`The org gave no describe of ${k}.`);return y.data})(),J.set(k,K)),K},{back:x,gone:P}=await ti({input:e,t0s:w},c,N),H=ii(x,g.userKey),Q=new Map([...P,...x]),z=oi(x,P),fe=await ft.read(t);for(let k of fe.keys())(x.has(k)||P.has(k))&&z.add(k);let oe=Zt([...fe.keys()].filter(k=>Q.has(k)),Q);zn(z,x,P);for(let k of H)x.delete(k),z.delete(k);let ue=si(c,x,P),Ae=new Map(D.map(({object:k,fields:E})=>[k.objectApiName,bn(k.objectApiName,k.fields,n.ignoredFields).filter(K=>!E.gone.has(K.toLowerCase()))])),he=await ci(x,Ae,Y,B),Se=await ai(e,D.map(({object:k})=>k),x,P,ue,Y);for(let k of Se.stuck)z.add(k);zn(z,x,P);for(let k of[...ue])x.has(k)||ue.delete(k);let De=ri(x,P,Se.outside),ye=0,ze=o.calls(),be=h!==void 0&&C!==void 0?await pi(e,{previewDir:p,ordered:c,changes:N,linkDescribe:C,fileObject:h,unread:B}):void 0;ye+=o.calls()-ze;let ne=be!==void 0&&"anchors"in be?be.anchors:void 0,Fe={input:e,previewDir:p,t0s:w,activeFrom:l-$o,back:x,carriers:ue,stranded:De,stuck:z,answeredGone:oe,others:H,access:g,lookups:he,personAccounts:await di(c,N),...ne!==void 0?{files:ne}:{}},ge=new Map;for(let{object:k,fields:E}of D){if(r?.aborted)throw new te;let K=B.get(k.objectApiName)??(be!==void 0&&"unread"in be&&k===h?be.unread:void 0),u=N.get(k.objectApiName);ge.set(k.objectApiName,K!==void 0||u===void 0?{unread:K??"Its changes were not read."}:await fi(Fe,k,u,E))}let we;if(ne!==void 0&&h!==void 0){let k=o.calls();we=await mi(e,{anchors:ne,fileObject:h,changes:N,outcomes:ge,ordered:c,previewDir:p,t0s:w}),ye+=o.calls()-k}let Ee=new Set(c.map(({objectApiName:k})=>k.toLowerCase()));if(n.files!==void 0&&h!==void 0)for(let k of[me,et])Ee.add(k.toLowerCase());let sn,Ze=()=>sn??=tt({describeGlobal:e.describeGlobal}),Me=[];for(let[k,E]of ge){if(!("told"in E))continue;let{toDelete:K}=E.told.diff;if(K.createdSince+K.broughtBackSince!==0)try{E.told.diff.outside=await li(Fe,E.told,Y,Ze,Ee);let u=await ui(g,E.told,Y,Ze);u!==void 0&&Me.push(u)}catch(u){if(u instanceof te)throw u;await Kn(p,k),ge.set(k,{unread:Pe(u)})}}if(ne!==void 0&&h!==void 0){let k=o.calls();await ki(e,{anchors:ne,fileObject:h,outcomes:ge,previewDir:p}),ye+=o.calls()-k,"told"in(ge.get(h.objectApiName)??{unread:""})||(we=void 0)}let ae=c.flatMap(({objectApiName:k})=>{let E=ge.get(k);return E&&"told"in E?[E.told]:[]}),{undoCannot:qe,withParentDeleted:Te}=await gi(p,ae),Ce=new Set(ae.map(({diff:k})=>k.objectApiName)),Ne=Me.filter(({objectApiName:k})=>Ce.has(k)),He=[...new Set(ae.flatMap(({diff:k})=>Object.keys(k.lastChangedBy)))],Xe=await hi(o,He,r),Ye=new Set(ae.flatMap(({people:k})=>[...k.active])),_e=ae.filter(({diff:k})=>W.has(k.objectApiName)&&!Vt(k)).length;return{checkpointId:n.checkpointId,previewId:s,readAt:i,objects:ae.map(({diff:k})=>k).filter(Vt),undoCannot:qe,...Te.length>0?{withParentDeleted:Te}:{},...Se.requests>0?{parentsOutsideRequests:Se.requests}:{},...O>0?{fieldsRequests:O}:{},described:{first:j.length,later:V.length},..._e>0?{fieldsNotChecked:_e}:{},...we!==void 0?{files:we}:{},...h!==void 0?{filesRequests:ye}:{},access:g.diffAccess(),...Ne.length>0?{unseen:Ne}:{},unread:c.flatMap(({objectApiName:k})=>{let E=ge.get(k),K=E&&"unread"in E?E.unread:E?void 0:B.get(k);return K===void 0?[]:[{objectApiName:k,reason:K}]}),userNames:Xe,activeLastHour:[...Ye].sort()}}var Ai=1e3,Si=25,Ci=2e3,Oe=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,no=["createdSince","broughtBackSince","comesBackWithParent","giveBack","inBin","withParent","deletedWhileTaken","toRecreate","carrier"],de={createdSince:1,broughtBackSince:2,comesBackWithParent:4,giveBack:8,inBin:16,withParent:32,deletedWhileTaken:64,toRecreate:128,carrier:256},to=32768,Pi={createdSince:de.createdSince|de.comesBackWithParent|de.carrier,broughtBackSince:de.broughtBackSince|de.carrier,comesBackWithParent:de.comesBackWithParent,giveBack:de.giveBack|de.inBin|de.withParent,inBin:de.inBin,withParent:de.withParent,deletedWhileTaken:de.deletedWhileTaken,toRecreate:de.toRecreate,carrier:de.carrier},ln=new Set(["createdSince","broughtBackSince"]),Ue={changedSincePreview:1,changedDuringRewind:2,outsideNotAccepted:4,holdsLeft:8,noUndoNotAccepted:16,beforeParentNotAccepted:32,recreateNotAccepted:64,keyTaken:128,needsUnpickedParent:256,heldByUnpicked:512},Ii=[{cls:"linkAdded",as:"unlink"},{cls:"linkRemoved",as:"relink"},{cls:"linkChanged",as:"share"}];function zs(e,n){return[n,e.automatedProcessUserId].filter(t=>typeof t=="string"&&t!=="")}function qs(e,n){let t=n.length>0?n.join(", "):"child";return`${e}: given back once the ${t} records hanging from it that the rewind deletes were gone, as those records held some of its values in place`}function Qe(e){let n=en(e);return n===null?Number.NaN:Date.parse(n)}function re(e,n){let t=e.Id;if(typeof t!="string"||!Oe.test(t))throw new Error(`A line of ${n} names no record: the diff it was read from is not whole.`);return t}async function*q(e){try{for await(let n of se(e))yield n}catch(n){if(n.code!=="ENOENT")throw n}}function Di(e,n){return Jn(e,`${pe(n)}.beforeParent.ndjson`)}var on=class{constructor(n){this.file=n}file;lines=[];written=!1;async add(n){this.lines.push(`${JSON.stringify(n)}
|
|
10
|
+
`),this.lines.length>=Ci&&await this.flush()}async flush(){if(this.lines.length===0)return;let n=this.lines.join("");this.lines=[],await bi(this.file,n,{encoding:"utf8",mode:nn,flag:this.written?"a":"w"}),this.written=!0}},Vn=class{entries=new Map;add(n,t,o,s,i){let r=`${n}\0${t}\0${s??""}\0${i??""}`,a=this.entries.get(r);a||(a={objectApiName:n,reason:t,...s!==void 0?{by:s}:{},...i!==void 0?{needs:i}:{},count:0,ids:[]},this.entries.set(r,a)),a.count++,a.ids.length<Si&&a.ids.push(o)}all(n){let t=(o,s)=>(o??"")<(s??"")?-1:(o??"")>(s??"")?1:0;return[...this.entries.values()].sort((o,s)=>(n.get(o.objectApiName)??0)-(n.get(s.objectApiName)??0)||t(o.reason,s.reason)||t(o.by,s.by)||t(o.needs,s.needs))}};function oo(e,n){if(!(typeof n!="string"||n===""))return e==="SetupOwnerId"&&Oe.test(n)?n.slice(0,15):n}async function Ni(e,n,t,o){let s=new Z;if(e.customSetting===void 0)return s;let i=kn(e.customSetting).toLowerCase(),r=e.fields.find(w=>w.toLowerCase()===i);if(r===void 0)return s;let a=new Z;for(let w of o){let p=X(t,e.objectApiName,w);for await(let c of q(p))a.add(re(c,p))}if(a.size===0)return s;let l=new Set;for await(let w of q(xe(n,e.objectApiName))){let p=oo(r,w[r]);p!==void 0&&l.add(p)}if(l.size===0)return s;for await(let w of q(cn(n,e.objectApiName))){if(typeof w.Id!="string"||!a.has(w.Id))continue;let p=oo(r,w[r]);p!==void 0&&l.has(p)&&s.add(w.Id)}return s}function io(e){return{objectApiName:e,deleted:0,withParentDeleted:0,undoCannot:0,nextPassDeleted:0,broughtBack:0,backWithParent:0,recreated:0,givenBackFirst:0,givenBackAfter:0,givenBackNextPass:0,skipped:0}}function ji(e){return Object.entries(e).some(([n,t])=>n!=="objectApiName"&&t!==0)}function so(e){return`${e.ContentDocumentId.slice(0,15)}:${e.LinkedEntityId.slice(0,15)}`}function ro(e,n,t){let s=(n==="linkChanged"?Rt:Rn).safeParse(e);if(!s.success)throw new Error(`A line of ${t} names no link: the diff it was read from is not whole.`);return s.data}function co(e){return{unlink:{file:Re(e,"linkAdded"),count:0},relink:{file:Re(e,"linkRemoved"),count:0},share:{file:Re(e,"linkChanged"),count:0}}}async function Li(e){let n={};for(let{cls:o,as:s}of Ii){let i=new Set,r=Re(e.confirmedDir,o);for await(let p of q(r))i.add(so(ro(p,o,r)));let a=Re(e.freshDir,o),l=new on(Re(e.dir,o)),w=0;for await(let p of q(a)){let c=ro(p,o,a);if(e.deleted(c.ContentDocumentId)||e.deleted(c.LinkedEntityId))continue;let g=e.pass===2&&o==="linkRemoved"&&(e.earlier(c.ContentDocumentId)||e.earlier(c.LinkedEntityId));if(!i.has(so(c))&&!g){e.left.add(me,"changedSincePreview",c.Id);continue}await l.add(p),w++}await l.flush(),n[s]={file:l.file,count:w}}let t=co(e.dir);return{unlink:n.unlink??t.unlink,relink:n.relink??t.relink,share:n.share??t.share}}var vi=["inBin","withParent","deletedWhileTaken","carrier"],Bi=new Set(["id","createdbyid","lastmodifiedbyid","systemmodstamp","createddate","lastmodifieddate"]);function Fi(e,n){return e.flatMap(t=>{let o=n[t];return typeof o=="string"&&Oe.test(o)?[o.slice(0,15)]:[]})}function ao(e,n,t){let o=t===void 0?void 0:new Set(t.map(s=>s.toLowerCase()));return Object.entries(e).flatMap(([s,i])=>{let r=s.toLowerCase();if(Bi.has(r)||o!==void 0&&!o.has(r))return[];if(typeof i!="string"||!Oe.test(i))return[];let a=i.slice(0,15);return n.has(a)?[{field:s,needs:n.get(a)}]:[]})}async function Ei(e,n,t){let{freshDir:o,heldRows:s}=e,i=new Map,r=new Map;for(let d of n)for(let f of[...vi,"toRecreate","comesBackWithParent"]){let h=X(o,d.objectApiName,f);for await(let b of q(h)){let R=re(b,h).slice(0,15);i.set(R,d.objectApiName),r.set(R,f)}}let a=new Map;for(let d of n)if(d.cascadeParents.length!==0)for await(let f of q(cn(o,d.objectApiName))){if(typeof f.Id!="string"||!Oe.test(f.Id))continue;let h=f.Id.slice(0,15),b=r.get(h);(b==="withParent"||b==="comesBackWithParent")&&a.set(h,Fi(d.cascadeParents,f))}let l=new Set;for(let[d,f]of r)(f==="inBin"||f==="deletedWhileTaken"||f==="carrier")&&t(i.get(d)??"")&&l.add(d);for(let d=l.size>0;d;){d=!1;for(let[f,h]of a)l.has(f)||!h.some(b=>l.has(b))||(l.add(f),d=!0)}let w=(d,f=new Set)=>{let h=i.get(d);if(!(h===void 0||f.has(d))){if(!t(h))return h;f.add(d);for(let b of a.get(d)??[]){if(l.has(b))continue;let R=w(b,f);if(R!==void 0)return R}}},p=new Map,c=new Map;for(let[d,f]of r){if(l.has(d)||f==="comesBackWithParent")continue;let h=i.get(d)??"";if(!t(h))p.set(d,h);else if(f==="withParent"){let b=w(d);c.set(d,b),p.set(d,b)}}let g=new Map;if(s===void 0)return{comes:l,left:c,fields:g};for(let d of[...n].reverse()){let f=d.objectApiName;if(!t(f))continue;let h=new Set(d.cascadeParents.map(v=>v.toLowerCase())),b=[],R=X(o,f,"toRecreate");for await(let v of q(R))b.push(re(v,R));if(b.length>0)for await(let v of s(f,b)){if(typeof v.Id!="string"||!Oe.test(v.Id))continue;let O=v.Id.slice(0,15),B=ao(v,p,void 0);if(B.length===0)continue;let W=B.find(({field:D})=>h.has(D.toLowerCase()));W!==void 0?(c.set(O,W.needs),p.set(O,W.needs)):g.set(O,{fields:B.map(({field:D})=>D),needs:B[0].needs})}let j=new Map,C=X(o,f,"giveBack");for await(let v of q(C)){let O=re(v,C),B=Array.isArray(v.fields)?v.fields.filter(W=>typeof W=="string"):void 0;j.set(O.slice(0,15),{id:O,differ:B})}for(let v of["inBin","withParent"]){let O=X(o,f,v);for await(let B of q(O)){let W=re(B,O);l.has(W.slice(0,15))&&j.set(W.slice(0,15),{id:W,differ:void 0})}}if(j.size!==0)for await(let v of s(f,[...j.values()].map(({id:O})=>O))){if(typeof v.Id!="string"||!Oe.test(v.Id))continue;let O=v.Id.slice(0,15),B=j.get(O);if(B===void 0)continue;let W=ao(v,p,B.differ);W.length>0&&g.set(O,{fields:W.map(({field:D})=>D),needs:W[0].needs})}}return{comes:l,left:c,fields:g}}function Mi(e,n){let t=n!==void 0?` Rewind ${n} with it to put it back.`:"",o=n??"an object this rewind was not limited to";switch(e){case"needsUnpickedParent":return`Left: it comes back only with a parent this rewind leaves deleted, or a lookup of it names a record this rewind leaves deleted (${o}), which the org refuses to point at.${t}`;case"heldByUnpicked":return`Given back but for the values records of ${o} created since hold in place: this rewind leaves them, so the org refuses to change those values.${t}`;case"outsideNotAccepted":return`Kept: records of ${o} created since hang from it, which its deletion would take along, and deleting them was not accepted.${t}`;default:return`Kept: records of ${o} this rewind leaves as they are hang from it, and its deletion would take them along.${t}`}}async function Ti(e){let{checkpoint:n,pass:t,confirmedDir:o,freshDir:s,dir:i,signal:r}=e,a=Date.parse(n.takenAt);if(!Number.isFinite(a))throw new Error(`Not a date: ${n.takenAt}`);let l=Date.parse(e.readAt);if(!Number.isFinite(l))throw new Error(`Not a date: ${e.readAt}`);let w=l-Ai;if(await yn(i),(await Ri(i)).length>0)throw new Error(`A rewind's plan is written to a folder of its own: ${i} is not empty.`);let p=()=>{if(r?.aborted)throw new te},c=[...n.objects].map(ht).sort((u,y)=>u.readOrder-y.readOrder),g=new Map(c.map(({objectApiName:u},y)=>[u,y])),d=new Map(c.map(({objectApiName:u})=>[u,io(u)])),f=u=>d.get(u)??io(u),h=new Set(e.ownWriters.map(u=>u.slice(0,15))),b=new Map(Object.entries(e.removalStamps??{}).map(([u,y])=>[u.slice(0,15),Qe(y)])),R=u=>fo(u,w,h,b),j=(u,y)=>u.flatMap(T=>{let M=y[T];return typeof M=="string"&&Oe.test(M)?[M]:[]}),C=(u,y)=>j(u.cascadeParents,y),v=(u,y)=>j(u.restrictParents??[],y),O=new Vn,B=u=>e.objects===void 0||e.objects.has(u),W=e.objects!==void 0?await Ei(e,c,B):void 0,D=new Map,L=new Map,N=new on(Jn(i,"leftFields.ndjson")),V=0,J=(u,y,T,M)=>{if(O.add(u,y,T,void 0,M),D.set(T.slice(0,15),Mi(y,M)),M===void 0)return;let _=L.get(M);_||(_=new Z,L.set(M,_)),_.add(T)},Y=new Z,x=new Z,P=new Z,H=new Z,Q=new Z,z=new Z,fe=[];for(let u of c){p();let y=u.objectApiName,T=B(y),M=(g.get(y)??0)+1,_=f(y),m=new Z;for(let S of no){let F=X(o,y,S);for await(let U of q(F))m.add(re(U,F),de[S])}let A=t===2?await Gi(s,y,w,h,b,fe):void 0,I=new Map,$=S=>{let F=I.get(S);return F||(F=new on(X(i,y,S)),I.set(S,F)),F};for(let S of no){if(!T&&S!=="comesBackWithParent"&&S!=="createdSince")continue;let F=X(s,y,S);for await(let U of q(F)){let G=re(U,F),ie=(m.flagsOf(G)&Pi[S])!==0;if(!T&&!(t===2?ie:S==="comesBackWithParent"&&ie&&W?.comes.has(G.slice(0,15))))continue;ie&&m.add(G,to),ie&&ln.has(S)&&(m.flagsOf(G)&de.carrier)!==0&&z.add(G);let ce=A?.other.flagsOf(G)??0,un=T&&A?.own.has(G)===!0;if(ce>0||!(ie||un)){let Ke=ce>0?"changedDuringRewind":"changedSincePreview";O.add(y,Ke,G,ce>0?fe[ce-1]:void 0),ln.has(S)&&P.add(G,Ue[Ke]);continue}if(W!==void 0&&T){let Ke=G.slice(0,15);if(S==="comesBackWithParent"&&!W.comes.has(Ke))continue;if((S==="withParent"||S==="toRecreate")&&W.left.has(Ke)){J(y,"needsUnpickedParent",G,W.left.get(Ke));continue}let gn=W.fields.get(Ke);if(gn!==void 0&&(S==="giveBack"||S==="toRecreate"||S==="inBin"||S==="withParent")){J(y,"needsUnpickedParent",G,gn.needs),await N.add({Id:G,fields:gn.fields}),V++;let Qn=Array.isArray(U.fields)?U.fields:[],lo=Qn.filter(Zn=>typeof Zn=="string"&&!gn.fields.some(uo=>uo.toLowerCase()===Zn.toLowerCase()));if(S==="giveBack"&&Qn.length>0&&lo.length===0)continue}}if(S==="toRecreate"&&!e.acceptRecreate){O.add(y,"recreateNotAccepted",G);continue}await $(S).add(S==="giveBack"?U:{Id:G}),S==="giveBack"&&W!==void 0&&Y.add(G,M),ln.has(S)?x.add(G,M):S==="comesBackWithParent"?(H.add(G),_.nextPassDeleted++):S==="carrier"?(H.add(G),Q.add(G),_.carriers=(_.carriers??0)+1,_.nextPassDeleted++):S==="inBin"||S==="deletedWhileTaken"?_.broughtBack++:S==="withParent"?_.backWithParent++:S==="toRecreate"&&_.recreated++,(S==="inBin"||S==="withParent")&&await $("giveBack").add({Id:G})}}for(let S of I.values())await S.flush();_.skipped=T?m.count(S=>(S&to)===0):0}await N.flush();let oe=new Map;if(W!==void 0){let u=new Z;for(let y of c){let T=y.objectApiName;if(B(T)||y.cascadeParents.length===0)continue;let M=new Z;for(let _ of ln){let m=X(s,T,_);for await(let A of q(m))M.add(re(A,m))}for await(let _ of q(xe(s,T))){if(typeof _.Id!="string"||!Oe.test(_.Id)||x.has(_.Id))continue;let m=M.has(_.Id),A=m&&Qe(_.CreatedDate)>=a&&Qe(_.LastModifiedDate)<=w;for(let I of C(y,_)){let $=x.flagsOf(I);if($>0){if(P.has(I)||A&&e.acceptOutside)continue;let F=c[$-1].objectApiName;oe.set(I.slice(0,15),T),A?(P.add(I,Ue.outsideNotAccepted),J(F,"outsideNotAccepted",I,T)):P.add(I,Ue.holdsLeft);continue}let S=Y.flagsOf(I);m&&S>0&&u.add(I)&&J(c[S-1].objectApiName,"heldByUnpicked",I,T)}}}}if(n.scope.mode==="picked"&&!e.acceptOutside)for(let u of c){let y=X(s,u.objectApiName,"outsideParents");for await(let T of q(y)){let M=re(T,y);!x.has(M)||P.has(M)||z.has(M)||(P.add(M,Ue.outsideNotAccepted),O.add(u.objectApiName,"outsideNotAccepted",M))}}let ue=c.map(u=>({object:u,file:xe(s,u.objectApiName)}));for(let u=P.size>0;u;){p(),u=!1;for(let{object:y,file:T}of ue)for await(let M of q(T)){if(!P.has(M.Id))continue;let _=oe.get(String(M.Id).slice(0,15));for(let m of C(y,M))!x.has(m)||P.has(m)||(P.add(m,Ue.holdsLeft),_!==void 0&&oe.set(m.slice(0,15),_),u=!0)}}for(let{object:u,file:y}of ue)for await(let T of q(y))if(x.has(T.Id)&&P.flagsOf(T.Id)===Ue.holdsLeft){let M=re(T,y),_=oe.get(M.slice(0,15));_!==void 0?J(u.objectApiName,"holdsLeft",M,_):O.add(u.objectApiName,"holdsLeft",M)}let Ae=new Z,he=u=>x.has(u)&&!P.has(u),Se=new Map,De=u=>{let y=u.slice(0,15);return Se.get(y)??y},ye=new Z,ze=[...c].reverse(),be=[];for(let u of ze){p();let y=u.objectApiName,T=xe(s,y),M=new on(Di(i,y)),_=0;for await(let m of q(T)){let A=typeof m.Id=="string"?m.Id:"";if(!he(A))continue;let I=Qe(m.LastModifiedDate),$=C(u,m).filter(he);if($.length>0&&Qe(m.CreatedDate)>=a&&(I<=w||I<=(b.get(A.slice(0,15))??Number.NaN))){let G=De($[0]);if(!($.some(ce=>ye.has(ce))||v(u,m).some(ce=>he(ce)&&De(ce)!==G))){Ae.add(A),Se.set(A.slice(0,15),G),f(y).withParentDeleted++;continue}ye.add(A)}let F=[...C(u,m),...v(u,m)].filter(he);if(u.undeletable&&F.length===0)continue;let U=F.length>0?"beforeParentNotAccepted":"noUndoNotAccepted";e.acceptNoUndo?(f(y).undoCannot++,F.length>0&&(await M.add({Id:A,parents:F}),_++)):(P.add(A,Ue[U]),O.add(y,U,A))}await M.flush(),_>0&&be.push({objectApiName:y,count:_,file:M.file})}let ne=new We(`${i}/deletes`),Fe=new We(`${i}/along-to-draft`),ge={},we=new Z,Ee=0;for(let u of c){p();let y=u.objectApiName,T=xe(s,y),M=0;for await(let _ of q(T)){let m=typeof _.Id=="string"?_.Id:"";if(x.has(m)&&(Ee++,!P.has(m))){for(let A of C(u,_))we.has(A)||we.add(A,(g.get(y)??0)+1);if(Ae.has(m)){ot([y]).length>0&&await Fe.add(y,m);continue}await ne.add(y,m),M++,t===2&&R(_)&&typeof _.LastModifiedDate=="string"&&(ge[m]=_.LastModifiedDate)}}f(y).deleted=M}if(Ee!==x.size)throw new Error("The fresh diff's reads do not hold every record its classes name to delete.");let sn=await Ln.of(ne),Ze=await Ln.of(Fe),Me=new Z;if(t===1&&H.size>0){for(let u of c)for await(let y of q(cn(s,u.objectApiName)))if(H.has(y.Id))for(let T of C(u,y))Me.add(T)}let ae=new Map;for(let u of c){let y=await Ni(u,s,i,["inBin","deletedWhileTaken"]);if(y.size===0)continue;ae.set(u.objectApiName,y);let T=f(u.objectApiName);T.broughtBack-=y.size,T.keyTaken=y.size;for(let M of["inBin","deletedWhileTaken"]){let _=X(i,u.objectApiName,M);for await(let m of q(_)){let A=re(m,_);y.has(A)&&O.add(u.objectApiName,"keyTaken",A)}}}let qe=new We(`${i}/giveBackFirst`),Te=new We(`${i}/giveBackAfter`),Ce=[];for(let u of c){p();let y=u.objectApiName,T=X(i,y,"giveBack"),M=!1;for await(let $ of q(T))if(we.has($.Id)){M=!0;break}let _=new Z;if(M)for await(let $ of q(xe(s,y)))we.has($.Id)&&C(u,$).some(he)&&_.add(String($.Id));let m=f(y),A=new Set,I=ae.get(y);for await(let $ of q(T)){let S=re($,T);if(I?.has(S)===!0)continue;let F=we.flagsOf(S),U=_.has(S);if(F>0){if(await Te.add(y,S),m.givenBackAfter++,A.add(c[F-1].objectApiName),!U)continue}else if(!U&&Me.has(S)){m.givenBackNextPass++;continue}await qe.add(y,S),m.givenBackFirst++}A.size>0&&Ce.push({objectApiName:y,by:[...A]})}let Ne=new We(`${i}/bringBack`),He=new We(`${i}/recreate`);for(let u of ze){let y=ae.get(u.objectApiName);for(let M of["carrier","inBin","deletedWhileTaken"]){let _=X(i,u.objectApiName,M);for await(let m of q(_)){let A=re(m,_);y?.has(A)!==!0&&await Ne.add(u.objectApiName,A)}}let T=X(i,u.objectApiName,"toRecreate");for await(let M of q(T))await He.add(u.objectApiName,re(M,T))}let Xe=new Z;if(t===2)for(let u of c)for(let y of["inBin","withParent","deletedWhileTaken","carrier","toRecreate"]){let T=X(o,u.objectApiName,y);for await(let M of q(T))Xe.add(re(M,T))}let Ye=n.files===void 0||!B(le)?co(i):await Li({confirmedDir:o,freshDir:s,dir:i,pass:t,deleted:u=>Oe.test(u)&&he(u),earlier:u=>Oe.test(u)&&(Xe.has(u)||Xe.has(e.recreated?.originalOf(u.slice(0,15))??u)),left:O}),_e=new We(`${i}/unlinkFrom`);for(let u of ln){let y=X(i,le,u);for await(let T of q(y)){let M=re(T,y);(P.flagsOf(M)&Ue.outsideNotAccepted)!==0&&await _e.add(le,M)}}let k={...e.removalStamps,...ge},E=Object.keys(k).length>0,K=c.map(({objectApiName:u})=>f(u)).filter(ji);return{pass:t,dir:i,deletes:sn,removal:{runStartedAt:new Date(a),runEndedAt:new Date(w),includeChanged:!1,...E?{removalStamps:k}:{},...e.removalSpans&&e.removalSpans.length>0?{removalSpans:[...e.removalSpans]}:{}},bringBack:await Ne.finish(),carriers:Q,goesAlong:Ae,alongToDraft:Ze,recreate:await He.finish(),giveBack:{beforeDeletes:await qe.finish(),afterDeletes:await Te.finish(),heldBy:Ce},restore:{changedAfter:e.readAt,ownWriters:[...e.ownWriters],includeChanged:!1,...E?{stamps:k}:{}},objects:K,undoCannot:K.filter(u=>u.undoCannot>0).map(({objectApiName:u,undoCannot:y})=>({objectApiName:u,count:y})),beforeParent:be.reverse(),left:O.all(g),links:{...Ye,unlinkFrom:await _e.finish()},...W!==void 0?{limited:{objects:c.map(({objectApiName:u})=>u).filter(B),needs:[...L].sort(([u],[y])=>(g.get(u)??0)-(g.get(y)??0)).map(([u,y])=>({objectApiName:u,records:y.size})),why:D,leftFields:{file:N.file,count:V}}}:{}}}function Hs(e,n){if(n===void 0)return e;let t=i=>i.filter(r=>n.has(r.objectApiName)),{files:o,...s}=e;return{...s,objects:t(e.objects),undoCannot:t(e.undoCannot),unread:t(e.unread),...e.withParentDeleted?{withParentDeleted:t(e.withParentDeleted)}:{},...e.unseen?{unseen:t(e.unseen)}:{},...o!==void 0&&n.has(le)?{files:o}:{}}}var _i=200;function Ks(e,n){return async function*(t,o){if(o.length===0)return;let s=await $e.read(n,e.snapshotId,t);for(let i=0;i<o.length;i+=Ve){let r=await s.chunk(o.slice(i,i+Ve)).batches(e.snapshotId,t,_i);for await(let a of r??[])yield*a}}}var $i=new Set(["needsUnpickedParent","heldByUnpicked","outsideNotAccepted","holdsLeft","keyTaken"]);async function Wi(e,n){let t=0;for await(let o of q(X(e,n,"giveBack")))Array.isArray(o.fields)&&t++;return t}async function xi(e){let n=new Set(e.limited?.objects??e.objects.map(i=>i.objectApiName)),t=[];for(let i of e.objects){let r={objectApiName:i.objectApiName,picked:n.has(i.objectApiName),toDelete:i.deleted+i.withParentDeleted+i.nextPassDeleted-(i.carriers??0),toGiveBack:await Wi(e.dir,i.objectApiName),toBringBack:i.broughtBack+i.backWithParent,toRecreate:i.recreated};r.toDelete+r.toGiveBack+r.toBringBack+r.toRecreate>0&&t.push(r)}let o=new Map;for(let i of e.left){if(!n.has(i.objectApiName)||!$i.has(i.reason))continue;let r=`${i.objectApiName}\0${i.reason}`,a=o.get(r);a?a.count+=i.count:o.set(r,{objectApiName:i.objectApiName,reason:i.reason,count:i.count})}let s=e.undoCannot.flatMap(({objectApiName:i,count:r})=>{let a=e.beforeParent.find(w=>w.objectApiName===i),l=r-(a?.count??0);return[...l>0?[{objectApiName:i,count:l}]:[],...a!==void 0&&a.count>0?[{objectApiName:i,count:a.count,reason:"deletedBeforeParent"}]:[]]});return{objects:[...n],acts:t,left:[...o.values()],needs:e.limited?.needs??[],undoCannot:s}}async function Vs(e){let n=Jn(e.previewDir,`selection-${yi(4).toString("hex")}`);try{let t=await Ti({checkpoint:e.checkpoint,pass:1,confirmedDir:e.previewDir,freshDir:e.previewDir,readAt:e.readAt,ownWriters:[],acceptOutside:e.acceptOutside,acceptNoUndo:!0,acceptRecreate:!0,...e.objects?{objects:e.objects}:{},...e.heldRows?{heldRows:e.heldRows}:{},dir:n,...e.signal?{signal:e.signal}:{}});return await xi(t)}finally{await Oi(n,{recursive:!0,force:!0})}}function fo(e,n,t,o){let s=Qe(e.LastModifiedDate);if(!(s>n))return!1;let i=typeof e.Id=="string"?e.Id:"",r=typeof e.LastModifiedById=="string"?e.LastModifiedById:"";return s<=(o.get(i.slice(0,15))??Number.NaN)||t.has(r.slice(0,15))}async function Gi(e,n,t,o,s,i){let r={own:new Z,other:new Z};for(let a of[xe(e,n),cn(e,n)])for await(let l of q(a)){if(!(Qe(l.LastModifiedDate)>t))continue;let p=re(l,a);if(fo(l,t,o,s)){r.own.add(p);continue}let c=typeof l.LastModifiedById=="string"?l.LastModifiedById:"",g=i.indexOf(c);g<0&&(i.push(c),g=i.length-1),r.other.add(p,g+1)}return r}export{Gn as a,ss as b,X as c,Uo as d,Is as e,zs as f,qs as g,Ti as h,Hs as i,Ks as j,xi as k,Vs as l};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{a as c,b as f,c as p}from"./chunk-QIRO4HTE.mjs";import{createHmac as g,randomBytes as d}from"node:crypto";function k(o){let t=o.truncateLength;return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):0}function R(o,t){let e=o.maskKeepLast;if(typeof e!="number"||!Number.isFinite(e)||e<=0)return 0;let n=Math.floor(e);return t>n?n:0}var m=/^[^\s@]+@[^\s@]+$/,h="example.invalid";function A(o){let t=o.lastIndexOf("@");return`${t===-1?o:o.slice(0,t)}@${h}`}var u=class extends Error{constructor(t){super(`Hash rule for ${t} has no hashSalt. The values being hashed are low-entropy PII (emails, phone numbers, names), so an unkeyed digest is recovered by enumeration in seconds. Set config.hashSalt to a secret value.`),this.name="MissingHashSaltError"}},y=class{personaRegistry;fallbackKey;constructor(t,e){this.fallbackKey=e??d(32).toString("hex"),this.personaRegistry=t??new p(this.fallbackKey)}saltedRegistries=new Map;registryFor(t){let e=t.config.hashSalt;if(!e)return this.personaRegistry;let n=this.saltedRegistries.get(e);return n||(n=new p(e),this.saltedRegistries.set(e,n)),n}namesGiven(){return this.personaRegistry.namesGiven()}continueFrom(t){return this.personaRegistry.continueFrom(t)}forgetRecords(){this.personaRegistry.forgetRecords();for(let t of this.saltedRegistries.values())t.forgetRecords()}peopleHeld(){let t=this.personaRegistry.size;for(let e of this.saltedRegistries.values())t+=e.size;return t}anonymize(t,e){return t.map(n=>{let i={...n},r=String(n.Id??n.id??"");for(let s of e)s.fieldApiName in i&&(i[s.fieldApiName]=this.applyRule(i[s.fieldApiName],s,r));return i})}applyRule(t,e,n=""){let r={mask:(s,a)=>this.applyMask(s,a),hash:(s,a)=>this.applyHash(s,a),fake:(s,a)=>this.applyFake(s,a,n),nullify:()=>null,shuffle:(s,a)=>this.applyShuffle(s,a),truncate:(s,a)=>this.applyTruncate(s,a),constant:(s,a)=>a.config.constantValue??"",preserve_format:s=>this.applyPreserveFormat(s)}[e.method];return r?r(t,e):t}preview(t,e,n){let i=t.slice(0,Math.max(0,n));return this.anonymize(i,e)}validateRules(t){let e=[];for(let n of t)n.fieldApiName||e.push("Rule must specify a fieldApiName"),n.objectApiName||e.push("Rule must specify an objectApiName"),n.method==="mask"&&!n.config.maskChar&&e.push(`Mask rule for ${n.fieldApiName} must specify a maskChar`),n.method==="hash"&&n.config.hashAlgorithm!=="sha256"&&n.config.hashAlgorithm!=="md5"&&e.push(`Hash rule for ${n.fieldApiName} must specify hashAlgorithm as sha256 or md5`),n.method==="hash"&&!n.config.hashSalt&&e.push(`Hash rule for ${n.fieldApiName} must specify a hashSalt \u2014 an unkeyed digest of low-entropy PII is trivially reversible`),n.method==="constant"&&n.config.constantValue===void 0&&e.push(`Constant rule for ${n.fieldApiName} must specify a constantValue`);return e}applyMask(t,e){let n=String(t??""),i=e.config.maskChar??"*",r=e.config.maskStart??0,s=e.config.maskEnd??n.length-R(e.config,n.length),a=n.split("");for(let l=r;l<Math.min(s,a.length);l++)a[l]=i;return a.join("")}applyHash(t,e){let n=e.config.hashSalt;if(!n)throw new u(e.fieldApiName);let i=e.config.hashAlgorithm??"sha256",r=String(t??""),s=g(i,n).update(r).digest("hex").slice(0,32);return m.test(r)?`${i}-${s}@${h}`:`${i}:${s}`}applyFake(t,e,n){let i=n!==""?n:this.keyedDigest(String(t??""),e),r=this.registryFor(e).getPersona(i),s=c[e.fieldApiName];if(s==="email")return A(r.email);if(s)return r[s];let a=this.keyedDigest(`${e.fieldApiName}:${i}`,e).slice(0,8);return m.test(String(t??""))?`fake-${a}@${h}`:`fake_${a}`}applyShuffle(t,e){return f(String(t??""),e.config.hashSalt??this.fallbackKey)}applyTruncate(t,e){let n=k(e.config);if(n===0)return"";let i=String(t??"");return e.config.truncateKeep==="first"?i.slice(0,n):i.slice(-n)}keyedDigest(t,e){return g("sha256",e.config.hashSalt??this.fallbackKey).update(t).digest("hex")}applyPreserveFormat(t){return String(t??"").replace(/[a-zA-Z]/g,"x").replace(/[0-9]/g,"0")}};export{u as a,y as b};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a as c}from"./chunk-
|
|
7
|
+
import{a as c}from"./chunk-RKALOKAU.mjs";var p=class{apply(n,r,t=[]){return m(n,r,t)}applyAddOns(n,r){let t={...n};for(let o of r)(!(o.fieldApiName in t)||o.overwriteExisting)&&(t[o.fieldApiName]=o.value);return t}},g=new Set(["direct","rename","transform","add_on"]),i=e=>e.toLowerCase();function S(e){return new Set(e.filter(n=>n.type!=="exclude").map(n=>i(n.targetField)))}function w(e,n=[]){let r=new Set(n.map(i));for(let t of e)(g.has(t.type)||t.type==="exclude")&&r.add(i(t.sourceField)),r.add(i(t.targetField));return r}var y=new c;function m(e,n,r=[]){if(n.length===0&&r.length===0)return{...e};let t=new Set(r.map(i)),o=Object.fromEntries(Object.entries(e).filter(([s])=>!t.has(i(s)))),d=w(n,r),l=Object.fromEntries(Object.entries(o).filter(([s])=>!d.has(i(s))));for(let s of n){let u=R(o,s);u!==void 0&&(l[s.targetField]=u)}return l}function a(e,n){if(n in e)return e[n];let r=i(n),t=Object.keys(e).find(o=>i(o)===r);return t===void 0?void 0:e[t]}var f=Symbol("exclude");function R(e,n){let r=F[n.type],t=r(e,n);if(!(t===f||t===void 0))return n.transformRules&&n.transformRules.length>0?y.transform(t,n.transformRules):t}var F={direct:(e,n)=>a(e,n.sourceField),rename:(e,n)=>a(e,n.sourceField),transform:(e,n)=>a(e,n.sourceField),constant:(e,n)=>n.targetField?n.sourceField:void 0,formula:(e,n)=>k(e,n.sourceField),exclude:()=>f,add_on:(e,n)=>a(e,n.sourceField)};function k(e,n){return/\{(\w+)\}/g.test(n)?n.replace(/\{(\w+)\}/g,(t,o)=>{let d=e[o];return d!=null?String(d):""}):e[n]}export{p as a,g as b,S as c,w as d,m as e};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{a as vt,d as Tt,e as _t,g as Bt,h as xt,i as Ft,j as Ut,k as Xe}from"./chunk-54HYHHVL.mjs";import{a as Ce,b as q,d as H,e as jt,f as Ze,h as j}from"./chunk-BNO5GIJ6.mjs";import{e as $t,h as Ht,i as Jt}from"./chunk-KRNFVAGC.mjs";import{da as me,e as te,ea as Ye,ga as pe,ja as Pe}from"./chunk-55LQD3Y3.mjs";import{h as N}from"./chunk-TZE3Y7IQ.mjs";import{b as P}from"./chunk-CA5NAXSU.mjs";import{$b as Ct,Tc as Lt,ec as Nt,fc as ee,jc as Ee,mc as ge,nc as Ke,pc as Ge,qc as Mt}from"./chunk-DPYTG6DM.mjs";import{b as x,e as Ve,f as L,i as Et,k as ae,l as X,o as Ie,s as Pt}from"./chunk-WZQEK4WT.mjs";var Ne=class{activeJobs=new Map;maxConcurrentJobs;maxCompletedJobs=50;constructor(e=5){this.maxConcurrentJobs=e}registerJob(e){this.activeJobs.set(e.id,e)}updateJobState(e,t){let n=this.activeJobs.get(e);return n?(n.state=t,(t==="JobComplete"||t==="Failed"||t==="Aborted")&&this.purgeCompletedJobs(),!0):!1}updateJobCounts(e,t,n){let o=this.activeJobs.get(e);return o?(o.numberRecordsProcessed=t,o.numberRecordsFailed=n,!0):!1}updateTotalRecords(e,t){let n=this.activeJobs.get(e);return n?(n.totalRecords=t,!0):!1}getJob(e){return this.activeJobs.get(e)}getActiveJobs(){return Array.from(this.activeJobs.values()).filter(e=>e.state==="UploadComplete"||e.state==="InProgress")}getCompletedJobs(){return Array.from(this.activeJobs.values()).filter(e=>e.state==="JobComplete"||e.state==="Failed"||e.state==="Aborted")}canStartNewJob(){return this.getActiveJobs().length<this.maxConcurrentJobs}removeJob(e){return this.activeJobs.delete(e)}get totalJobs(){return this.activeJobs.size}purgeCompletedJobs(){let e=Array.from(this.activeJobs.entries()).filter(([,t])=>["JobComplete","Failed","Aborted"].includes(t.state));if(e.length>this.maxCompletedJobs){let t=e.slice(0,e.length-this.maxCompletedJobs);for(let[n]of t)this.activeJobs.delete(n)}}clear(){this.activeJobs.clear()}};function Un(r,e){let t=Xe(r,e);if(t.state==="Open")throw new Error(`Bulk API job ${r||"(no id)"} is still open after its close was sent`);return{state:t.state,...t.numberRecordsProcessed!==void 0?{numberRecordsProcessed:t.numberRecordsProcessed}:{},...t.errorMessage?{errorMessage:t.errorMessage}:{}}}function Me(r){return{bulk2:{createJob:e=>{let t=r.bulk2.createJob(e);return{get id(){return t.id},open:async()=>{await t.open()},uploadData:n=>t.uploadData(n),close:()=>t.close(),abort:()=>t.abort(),check:async()=>Un($t(t)??"",await t.check()),getAllResults:()=>t.getAllResults()}},job:(e,{id:t})=>{let n=r.bulk2.job(e,{id:t});return{check:async()=>Xe(t,await n.check()),getSuccessfulResults:()=>n.getSuccessfulResults(),getAllResults:()=>n.getAllResults(),abort:()=>n.abort()}}}}}var zt=100,et=2e3,qt=20,Wt=20,Hn=X({name:x(),label:x(),type:x(),createable:L().optional(),updateable:L().optional(),nillable:L().optional(),defaultedOnCreate:L().optional(),aggregatable:L().optional(),groupable:L().optional(),filterable:L().optional(),nameField:L().optional(),autoNumber:L().optional(),calculated:L().optional(),referenceTo:ae(x()).optional()}).loose(),G=X({name:x(),label:x(),queryable:L().optional(),updateable:L().optional(),deletable:L().optional(),fields:ae(Hn),childRelationships:ae(X({childSObject:x(),field:x(),cascadeDelete:L().optional(),restrictedDelete:L().optional()}).loose()).optional()}).loose(),Jn=Pt(x(),Et()),zn=X({k:Ie([x(),Ve(),L()]).nullable(),n:Ve().int().nonnegative()}).loose();function Qt(r){return(r.createable===!0||r.updateable===!0)&&r.type!=="boolean"}function qn(r){return r.groupable===!0&&(Qt(r)||r.nameField===!0)}function Wn(r,e){return e.createable===!0&&e.nillable===!1&&e.defaultedOnCreate!==!0||Ct(r,e.name)}function Le(r,e,t){let n=P(t);r.some(o=>o.check===e&&o.message===n)||r.push({check:e,message:n})}async function Qn(r,e,t,n){let o=new Map,s=[],a=[],i=(f,u)=>{s.push({fieldApiName:f.name,label:f.label,reason:u})},d=t.filter(f=>f.aggregatable===!0),l=t.filter(f=>f.aggregatable!==!0&&f.filterable===!0);for(let f of t)f.aggregatable!==!0&&f.filterable!==!0&&i(f,"not-countable");if(n===0)for(let f of[...d,...l])o.set(f.name,0);else{for(let f=0;f<d.length;f+=zt){let u=d.slice(f,f+zt);try{let g=u.map(R=>`COUNT(${N(R.name)})`).join(", "),m=await r.query(`SELECT ${g} FROM ${e}`),h=Jn.parse(m.records[0]??{});u.forEach((R,b)=>{let w=h[`expr${b}`];if(typeof w!="number")throw new Error(`The org answered no count for ${e}.${R.name}.`);o.set(R.name,w)})}catch(g){Le(a,"fill",g);for(let m of u)o.delete(m.name),i(m,"refused")}}for(let[f,u]of l.entries()){if(f>=Wt){i(u,"query-budget");continue}try{let g=await r.query(`SELECT COUNT() FROM ${e} WHERE ${N(u.name)} != null`);o.set(u.name,g.totalSize)}catch(g){Le(a,"fill",g),i(u,"refused")}}}return{fields:t.filter(f=>o.has(f.name)).map(f=>({fieldApiName:f.name,label:f.label,filled:o.get(f.name)??0,required:Wn(e,f)})).sort((f,u)=>f.filled-u.filled||f.fieldApiName.localeCompare(u.fieldApiName)),unmeasured:s,errors:a}}async function Vn(r,e,t,n,o){let s=[],a=n?t.find(d=>d.name.toLowerCase()===n.toLowerCase()):t.find(d=>d.name==="Email")??t.find(d=>d.nameField===!0);if(!a)return n&&s.push({check:"duplicates",message:`${e} has no field ${n} the org can group records by.`}),{duplicates:null,errors:s};let i={keyField:a.name,keyLabel:a.label,groups:[],groupCount:0,recordCount:0,truncated:!1};if(o===0)return{duplicates:i,errors:s};try{let d=await Kn(r,e,a.name),l=d.rows.map(c=>({value:String(c.value),count:c.count}));return{duplicates:{...i,groups:l.slice(0,qt),groupCount:l.length,recordCount:l.reduce((c,f)=>c+f.count,0),truncated:d.truncated},errors:s}}catch(d){return Le(s,"duplicates",d),{duplicates:null,errors:s}}}async function Kn(r,e,t){let n=N(t),o=await r.query(`SELECT ${n} k, COUNT(Id) n FROM ${e} WHERE ${n} != null GROUP BY ${n} HAVING COUNT(Id) > 1 ORDER BY COUNT(Id) DESC LIMIT ${et}`),s=[];for(let a of o.records){let i=zn.safeParse(a);!i.success||i.data.k===null||s.push({value:i.data.k,count:i.data.n})}return{rows:s,truncated:o.records.length>=et}}async function Gn(r,e,t,n,o){let s=[];if(!t.some(a=>a.name==="LastModifiedDate"&&a.filterable===!0))return{stale:null,errors:s};if(o===0)return{stale:{days:n,records:0},errors:s};try{let a=await r.query(`SELECT COUNT() FROM ${e} WHERE LastModifiedDate < LAST_N_DAYS:${n}`);return{stale:{days:n,records:a.totalSize},errors:s}}catch(a){return Le(s,"stale",a),{stale:null,errors:s}}}async function Yn(r,e,t){let n,o,s;try{if(n=G.parse(await r.describe(N(e.objectApiName))),o=N(n.name),n.queryable===!1)throw new Error(`${o} cannot be queried.`);s=(await r.query(`SELECT COUNT() FROM ${o}`)).totalSize}catch(c){return{status:"failed",objectApiName:e.objectApiName,message:P(c)}}let a=n.fields.filter(qn).sort((c,f)=>c.label.localeCompare(f.label)),[i,d,l]=await Promise.all([Qn(r,o,n.fields.filter(Qt),s),Vn(r,o,a,e.duplicateKey,s),Gn(r,o,n.fields,t,s)]);return{status:"scanned",objectApiName:e.objectApiName,label:n.label,totalRecords:s,fields:i.fields,unmeasured:i.unmeasured,duplicates:d.duplicates,stale:l.stale,keyFields:a.map(c=>({fieldApiName:c.name,label:c.label})),errors:[...i.errors,...d.errors,...l.errors]}}async function ro(r,e,t=()=>new Date){if(!Number.isInteger(e.staleDays)||e.staleDays<1)throw new Error(`A staleness threshold is a whole number of days, not ${e.staleDays}.`);let n=t().toISOString(),o=[];for(let s of e.objects)o.push(await Yn(r,s,e.staleDays));return{orgId:e.orgId,staleDays:e.staleDays,scannedAt:n,bounds:{duplicateGroupLimit:et,duplicateSample:qt,singleFieldQueries:Wt},objects:o}}var tt=1e4,ve=5e4,Vt="DELETE_FAILED",nt="UNABLE_TO_LOCK_ROW",Kt=3,Zn=2e3,Gt="FEATURENOTENABLED",rt="ContentVersion",Yt="ContentDocument",ot=new Set([rt,Yt]);async function he(r,e,t,n,o="delete"){let s=!1,a={},i=0,d=0,l=(g,m)=>(d+=g,m()),c={bulk2:{createJob:g=>{let m=r.bulk2.createJob(g);return{get id(){return m.id},open:()=>l(1,()=>m.open()),uploadData:h=>l(1,()=>m.uploadData(h)),close:async()=>{await l(1,()=>m.close()),s=!0},abort:()=>l(1,()=>m.abort()),check:async()=>{let h=await l(1,()=>m.check());return a={state:h.state,message:h.errorMessage},h},getAllResults:async()=>{let h=await l(Jt,()=>m.getAllResults());return i=Array.isArray(h)?h.length:(h.successfulResults?.length??0)+(h.failedResults?.length??0),h}}}}},f;try{f=await new Ht().executeBulk({connection:c,bulkManager:new Ne(1),...n?{signal:n}:{}},e,o,t.map(g=>({Id:g})))}catch(g){if(!s){let m=g?.errorCode;return{kind:"untouched",reason:P(g),...typeof m=="string"&&m!==""?{code:m}:{},requests:d}}throw g}if(f.aborted)return{kind:"aborted",requests:d};if(a.state!=="JobComplete"&&i===0)return{kind:"untouched",reason:a.message||`job ${a.state??"not complete"}`,requests:d};let u=new Map(f.outcomes.map(g=>[g.recordIndex,g]));return{kind:"answered",requests:d,rows:t.map((g,m)=>{let h=u.get(m);return h?.success?{success:!0}:{success:!1,error:h?.error??"The job gave no result for it."}})}}function ho(r,e){let t=Me(r);return{...Ce(r,e),queryDeleted:async n=>({records:(await r.query(n,{scanAll:!0})).records}),bulkDestroy:(n,o,s)=>he(t,n,o,s),bulkHardDestroy:(n,o,s)=>he(t,n,o,s,"hardDelete")}}var st=X({success:L(),errors:ae(Ie([X({statusCode:x().optional(),errorCode:x().optional(),message:x().optional()}).loose(),x()])).optional()}).loose();function ne(r){return r.slice(0,15)}function je(r){return typeof r=="string"?void 0:r.statusCode??r.errorCode}function it(r){if(typeof r=="string")return r;let e=je(r),t=r.message??"";return e&&t?`${e}: ${t}`:e||t||"The org gave no reason."}function de(r){return async e=>(await r.query(e)).records.filter(n=>typeof n=="object"&&n!==null)}function Xn(r){return new Promise(e=>setTimeout(e,r))}function er(r){let e=Zn*2**r;return Math.floor(e/2+Math.random()*(e/2))}async function Zt(r,e,t,n){let o=[...t];for(let s=0;s<Kt;s++){let a=o.flatMap((d,l)=>d.kind==="refused"&&d.locked===!0?[l]:[]);if(a.length===0||n.stopped?.()===!0||(await(n.wait??Xn)(er(s)),n.stopped?.()===!0))break;let i=await e(a.map(d=>r[d]));if(i===void 0)break;a.forEach((d,l)=>{let c=i[l];c&&(o[d]={...c,lockResends:s+1})})}return o}async function at(r,e,t,n={}){if(e===rt)return ar(r,t,n);let o=s=>tr(r,e,s);return Zt(t,o,await o(t),n)}async function tr(r,e,t){let n;try{n=await r.destroy(e,[...t])}catch(s){let a=P(s);return t.map(()=>({kind:"refused",reason:a,dependency:!1}))}let o=Array.isArray(n)?n:[n];return t.map((s,a)=>{let i=st.safeParse(o[a]);if(i.success&&i.data.success)return{kind:"deleted"};let d=i.success?i.data.errors??[]:[];if(d.some(c=>je(c)==="ENTITY_IS_DELETED"))return{kind:"gone"};let l=d.length>0&&d.every(c=>je(c)===nt);return{kind:"refused",reason:d.length>0?it(d[0]):"The org gave no reason.",dependency:d.some(c=>je(c)===Vt),...l?{locked:!0}:{}}})}async function nr(r,e,t,n="recycle",o={}){let s=n==="hard"?r.bulkHardDestroy?.bind(r):r.bulkDestroy?.bind(r);if(s===void 0)return n==="hard"?{hardRefused:rr}:"untouched";let a=async d=>{let l;try{l=await s(e,d,o.signal)}catch(f){let u=P(f);return d.map(()=>({kind:"refused",reason:u,dependency:!1}))}if(l.kind==="aborted")return"aborted";if(l.kind==="untouched"){if(n!=="hard")return"untouched";if(l.code===Gt)return{hardRefused:or(l.reason)};let f=`Not deleted for good: the job was not handed over \u2014 ${l.reason}`;return d.map(()=>({kind:"refused",reason:f,dependency:!1}))}let{rows:c}=l;return d.map((f,u)=>{let g=c[u];if(g?.success===!0)return{kind:"deleted"};let{code:m,message:h}=ir(g?.error??"");return m==="ENTITY_IS_DELETED"?{kind:"gone"}:{kind:"refused",reason:m&&h?`${m}: ${h}`:g?.error||m||h||"The org gave no reason.",dependency:m===Vt,...m===nt?{locked:!0}:{}}})},i=await a(t);return Array.isArray(i)?Zt(t,async d=>{let l=await a(d);return Array.isArray(l)?l:void 0},i,o):i}var rr="Records cannot be deleted for good through this connection: nothing was sent.";function or(r){return`The user SandForge connects as may not delete records for good in this org: Salesforce refused the job before it held a record (${Gt}: ${r}). Nothing was deleted for good, and nothing was sent to the recycle bin instead.`}var sr="A file is never deleted for good: that takes a Bulk API job, which no file was ever sent by. Not sent.";function ir(r){let e=/^([A-Z][A-Z0-9_]*):([\s\S]*?)(?::(?:--|[\w.,]+))?$/.exec(r.trim());return e?{code:e[1],message:e[2].trim()}:{message:r.trim()}}async function ar(r,e,t){let n;try{n=await j(r,rt,["ContentDocumentId"],e)}catch(d){let l=P(d);return e.map(()=>({kind:"refused",reason:l,dependency:!1}))}let o=new Map;for(let d of n)typeof d.Id=="string"&&typeof d.ContentDocumentId=="string"&&o.set(ne(d.Id),d.ContentDocumentId);let s=[...new Set(o.values())],a=s.length>0?await at(r,Yt,s,t):[],i=new Map(s.map((d,l)=>[d,a[l]]));return e.map(d=>{let l=o.get(ne(d));return l===void 0?{kind:"gone"}:i.get(l)??{kind:"refused",reason:"The org gave no answer for its document.",dependency:!1}})}function Xt(r){let e=[];for(let t=0;t<r.length;t+=q)e.push({ids:r.slice(t,t+q),byJob:!1});return e}function en(r,e,t,n="recycle"){return ot.has(e)?!1:n==="hard"||r.bulkDestroy!==void 0&&t>=tt}async function dr(r,e,t,n="recycle"){let o=[],s=!ot.has(e)&&(n==="hard"||r.bulkDestroy!==void 0),a=d=>{if(d.length===0)return;if(!s||n!=="hard"&&d.length<tt){o.push(...Xt(d));return}let l=Math.ceil(d.length/Math.ceil(d.length/ve));for(let c=0;c<d.length;c+=l)o.push({ids:d.slice(c,c+l),byJob:!0})};if(!Ee(e)||t.length===0)return a(t),o;let i=new Set;try{i=new Set([...await pe(de(r),t)].map(ne))}catch{}return a(t.filter(d=>!i.has(ne(d)))),a(t.filter(d=>i.has(ne(d)))),o}function tn(r){return{objectApiName:r,op:"delete"}}async function nn(r,e,t,n,o){let s={stopped:o.stopped,...o.wait?{wait:o.wait}:{}},{stopped:a}=await Ut(t,{key:tn(e),sizes:n.sizes,allowance:n.allowance,beforeEachSend:()=>o.stopped()?"stop":void 0,send:async i=>({answers:await at(r,e,i,s)}),limited:i=>i?.kind==="refused"?Lt([i.reason]):void 0,settle:(i,d,l,c)=>{let f=[],u=[];i.forEach((g,m)=>{if(l.has(m))return;let h=d[m]??{kind:"refused",reason:"The org gave no answer for it.",dependency:!1},R=c.get(m);f.push(g),u.push(R!==void 0&&h.kind==="refused"?{...h,dependency:!1,limit:R}:h)}),f.length>0&&o.settle(f,u)}});return a!==void 0}function dt(r,e){let t=tn(r),n=e.sizes.report(t);if(!n)return[];let o=[];return n.rows+n.alone+n.notSplit+n.keptWhole>0&&o.push(Bt(n)),n.notSplit>0&&o.push(xt(n.notSplit,Ft(e.allowance,t),"removal")),n.keptWhole>0?o.push(_t):n.alone>0&&o.push(Tt),o}function rn(r){let e=0,t=0,n=0,o=0;for(let a of r)e++,a==="deleted"?t++:a==="gone"?n++:o++;if(e===0)return[];let s=[t>0?`${t} deleted`:"",n>0?`${n} already gone`:"",o>0?`${o} still refused`:""].filter(Boolean);return[`The org could not lock ${e} record(s) (${nt}), each sent again up to ${Kt} times, a wait before each: ${s.join(", ")}.`]}async function on(r,e,t,n){let o=n.mode??"recycle";if(o==="hard"&&ot.has(e))return t.length>0&&n.settle(t,t.map(()=>({kind:"refused",reason:sr,dependency:!1}))),{stopped:!1};let s=n.wait?{wait:n.wait}:{},a=await dr(r,e,t,o);for(let i=a.shift();i!==void 0;i=a.shift()){let{ids:d,byJob:l}=i;if(n.stopped())return{stopped:!0};if(await n.prepare?.(d),!l){if(await nn(r,e,d,n.splitting,{stopped:n.stopped,settle:n.settle,...s}))return{stopped:!0};continue}let c=await nr(r,e,d,o,{stopped:n.stopped,...s,...n.signal?{signal:n.signal}:{}});if(c==="aborted")return{stopped:!0};if(c==="untouched"){a.unshift(...Xt(d));continue}if(!Array.isArray(c))return{stopped:!0,hardRefused:c.hardRefused};n.settle(d,c)}return{stopped:!1}}async function sn(r,e){for(let t=0,n=!0;n;t++){n=!1;for(let o of r){let s=e.idsOf(o,t);if(s.length===0)continue;if(e.stopped())return!0;let a=e.deleted(o);if(await e.send(o,s,t))return!0;e.deleted(o)>a&&(n=!0)}}return!1}async function Te(r,e){let t=new Set(e.map(a=>a.objectApiName)),n=new Map;for(let{objectApiName:a}of e){let i;try{i=(G.parse(await r.describe(a)).childRelationships??[]).map(l=>l.childSObject)}catch{continue}for(let d of i){if(d===a||!t.has(d))continue;let l=n.get(d)??new Set;l.add(a),n.set(d,l)}}let o=[...e],s=[];for(;o.length>0;){let a=o.findIndex(i=>!o.some(d=>d!==i&&n.get(d.objectApiName)?.has(i.objectApiName)));s.push(...o.splice(a>=0?a:0,1))}return s}async function ct(r,e,t){if(r.length===0)return{gone:[],unchecked:[]};let n;try{n=await e(r)}catch(a){return{gone:[],unchecked:[...r],failure:P(a)}}let o=new Set(n.map(a=>ne(String(a.Id)))),s=r.filter(a=>!o.has(ne(a)));return{gone:s.filter(t),unchecked:s.filter(a=>!t(a))}}function cr(r){return r.filter(e=>me[e]!==void 0&&!Ye.has(e))}async function lt(r,e,t,n,o,s){let a=de(r),i=[];for(let{objectApiName:d}of e){let l=me[d];if(!l||Ye.has(d))continue;let c;for await(let f of t.pages(d)){let u=f.filter(w=>n(d,w));if(u.length===0)continue;if(o())return{drafted:i,cancelled:!0};c??=await Pe(a,l);let g=c,m=g?.draft;if(!g||!m)break;let h=await s(d,u),R;try{R=await j(r,d,["Status"],u)}catch{continue}let b=R.filter(w=>typeof w.Id=="string"&&!h.has(w.Id.slice(0,15))).filter(w=>{let k=g.categoryOf.get(String(w.Status));return k!==void 0&&k!=="Draft"}).map(w=>({objectApiName:d,id:String(w.Id),draft:m,status:String(w.Status)}));for(let w=0;w<b.length;w+=q){if(o())return{drafted:i,cancelled:!0};let k=b.slice(w,w+q);i.push(...k);try{await r.update(d,k.map(({id:I})=>({Id:I,Status:m})))}catch{}}}}return{drafted:i,cancelled:!1}}function ko(r,e,t,n){if(t)return`${r} ${t.id}: ${e}`;let o=n.filter(s=>s.objectApiName===r).map(s=>`${s.id} (${s.status})`);return o.length>0?`${r}: ${e} Set to Draft, with the status each had: ${o.join(", ")}.`:`${r}: ${e}`}async function an(r,e,t){let n=[...new Set(e.map(o=>o.objectApiName))];for(let o of n){let s=e.filter(c=>c.objectApiName===o),a=new Map(s.map(c=>[c.id.slice(0,15),c])),i=s.map(c=>c.id),d;try{d=await j(r,o,["Status"],i)}catch(c){t.note(o,`Status set to ${s[0].draft} for the delete, and not read back to be restored: ${P(c)}`,!0);continue}let l=d.flatMap(c=>{let f=typeof c.Id=="string"?a.get(c.Id.slice(0,15)):void 0;return f&&c.Status===f.draft?[f]:[]});for(let c=0;c<l.length;c+=q){let f=l.slice(c,c+q),u;try{u=await r.update(o,f.map(({id:m,status:h})=>({Id:m,Status:h})))}catch(m){u=f.map(()=>({success:!1,errors:[P(m)]}))}let g=Array.isArray(u)?u:[u];f.forEach(({draft:m,status:h},R)=>{let b=st.safeParse(g[R]);if(b.success&&b.data.success){t.note(o,`Status set to ${m} for the delete, then back to ${h}.`,!1,f[R]);return}let w=b.success?b.data.errors??[]:[],k=w.length>0?it(w[0]):"The org gave no reason.";t.note(o,`Status set to ${m} for the delete, and left there: the org refused ${h} back \u2014 ${k}`,!0,f[R])})}}}var le="DuplicateRecordSet",lr="DuplicateRecordItem",_e=2e3,ur=999,fr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function T(r){return r.slice(0,15)}function dn(r){return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function ut(r){return typeof r=="string"?Date.parse(r):Number.NaN}async function cn(r,e){return(await gr(r,e)).map(t=>({id:t.id,modified:mr(t,e)}))}async function gr(r,e){if(!Number.isFinite(e.start)||!Number.isFinite(e.end)||!fr.test(e.user))return[];let t;try{let l=await r.query(`SELECT Id, CreatedDate, LastModifiedDate, LastModifiedById FROM ${le} WHERE CreatedDate >= ${dn(e.start-2e3)} AND CreatedDate <= ${dn(e.end+6e4)} LIMIT ${_e}`);if(l.records.length>=_e)return[];t=l.records.filter(c=>typeof c=="object"&&c!==null)}catch{return[]}let n=t.flatMap(l=>typeof l.Id=="string"?[l.Id]:[]);if(n.length===0)return[];let o=new Map,s=new Map,a=new Map;try{for(let l of H(n)){let c=await r.query(`SELECT Id, RecordId, DuplicateRecordSetId, CreatedDate FROM ${lr} WHERE DuplicateRecordSetId IN (${l}) LIMIT ${_e}`);if(c.records.length>=_e)return[];for(let f of c.records){let u=f??{},g=u.DuplicateRecordSetId,m=u.RecordId;if(typeof g!="string")continue;let h=ut(u.CreatedDate);if(Number.isFinite(h)&&!(h<=(a.get(T(g))??Number.NaN))&&a.set(T(g),h),typeof m!="string"||!e.has(T(m))){let R=o.get(T(g))??new Set;R.add(typeof m=="string"?T(m):`item ${String(u.Id)}`),o.set(T(g),R)}else s.set(T(g),[...s.get(T(g))??[],T(m)])}}}catch{return[]}let i=T(e.user),d=(l,c)=>{let f=o.get(l)?.size??0;return s.has(l)?f<=1:f===0&&typeof c=="string"&&T(c)===i};return t.flatMap(l=>typeof l.Id=="string"&&d(T(l.Id),l.LastModifiedById)?[{id:l.Id,created:ut(l.CreatedDate),modified:ut(l.LastModifiedDate),...typeof l.LastModifiedById=="string"?{modifiedBy:l.LastModifiedById}:{},names:s.get(T(l.Id))??[],...a.has(T(l.Id))?{itemsMade:a.get(T(l.Id))}:{}}]:[])}function mr(r,e){if((r.modifiedBy!==void 0?T(r.modifiedBy):"")===T(e.user)&&r.modified<=e.end+6e4)return Math.min(r.modified,e.end);let n=e.end+6e4;return r.names.length>0&&r.created<=n&&r.modified<=n&&(r.modified===r.created||r.modified<=(r.itemsMade??Number.NaN)+ur)?Math.min(r.modified,e.end):r.modified}async function ln(r,e,t,n="recycle"){let o=N(e),s=new Set;try{for(let a of H(t)){let i=await r.queryDeleted(`SELECT Id FROM ${o} WHERE Id IN (${a}) AND IsDeleted = true`);for(let d of i.records){let l=d?.Id;typeof l=="string"&&s.add(l.slice(0,15))}}}catch(a){return{error:P(a)}}return{deleted:s,inBin:n!=="hard"}}var pr=/__kav$/i;function ye(r){return pr.test(r)}function fn(r){return r.replace(/v$/i,"")}var ft="Kept: its article holds a version the run did not write \u2014 a draft begun on it, or a version published since \u2014 which deleting the article would take with it. A removal that takes what changed since the run takes it too.",hr={statusCode:"ENTITY_IS_DELETED",message:"The version is no longer in the org: it went with its article."},un=" AND IsLatestVersion = false AND PublishStatus = 'Archived'",yr="An article version is deleted through its article, over REST.",br={success:!1,errors:[{message:"The org gave no reason."}]};function J(r){return r.slice(0,15)}function gn(r,e){let t=r.bulkDestroy?.bind(r);return{query:n=>r.query(n),queryDeleted:n=>r.queryDeleted(n),update:(n,o)=>r.update(n,o),serverTime:()=>r.serverTime(),userId:()=>r.userId(),describeGlobal:()=>r.describeGlobal(),describe:n=>ye(n)?Rr(r,n):r.describe(n),destroy:(n,o)=>ye(n)?wr(r,n,o,e):r.destroy(n,o),...t?{bulkDestroy:(n,o,s)=>ye(n)?Promise.resolve({kind:"untouched",reason:yr,requests:0}):t(n,o,s)}:{}}}async function Rr(r,e){let t=await r.describe(e);if(typeof t!="object"||t===null)return t;let n;try{n=(await r.describe(fn(e)))?.deletable}catch{n=void 0}let o={...t};return delete o.deletable,typeof n=="boolean"?{...o,deletable:n}:o}async function mn(r,e,t){let n=N(e),o=new Map,s=new Map,a=(d,l)=>{for(let c of d){let f=c;if(typeof f?.Id!="string"||typeof f.KnowledgeArticleId!="string")continue;l?.set(J(f.Id),f.KnowledgeArticleId);let u=J(f.KnowledgeArticleId),g=s.get(u)??new Set;g.add(J(f.Id)),s.set(u,g)}};for(let d of["",un])for(let l of H(t)){let c=await r.query(`SELECT Id, KnowledgeArticleId FROM ${n} WHERE Id IN (${l})${d}`);a(c.records,o)}let i=[...new Set(o.values())];for(let d of["",un])for(let l of H(i)){let c=await r.query(`SELECT Id, KnowledgeArticleId FROM ${n} WHERE KnowledgeArticleId IN (${l})${d}`);a(c.records)}return{articleOf:o,versions:s}}function pn({articleOf:r,versions:e},t,n){if(n.includeChanged)return new Set;let o=new Set(t.map(J)),s=a=>[...e.get(a)??[]].some(i=>!o.has(i));return new Set([...r.values()].map(J).filter(s))}async function hn(r,e,t,n){let o=await mn(r,e,t),s=pn(o,t,n);return new Set(t.map(J).filter(a=>{let i=o.articleOf.get(a);return i!==void 0&&s.has(J(i))}))}async function wr(r,e,t,n){let o=await mn(r,e,t),{articleOf:s}=o,a=[...new Set(s.values())],i=pn(o,t,n),d=a.filter(c=>!i.has(J(c))),l=new Map;if(d.length>0){let c;try{c=await r.destroy(fn(e),d)}catch(u){let g=P(u);c=d.map(()=>({success:!1,errors:[{message:g}]}))}let f=Array.isArray(c)?c:[c];d.forEach((u,g)=>l.set(J(u),f[g]))}return t.map(c=>{let f=s.get(J(c));return f===void 0?{success:!1,errors:[hr]}:i.has(J(f))?{success:!1,errors:[{message:ft}]}:l.get(J(f))??br})}var xe="Quote",Re="QuoteLineItem",be="Opportunity",we="OpportunityLineItem",yn=2e3;function Sr(r){return r.slice(0,15)}function bn(r){return typeof r=="string"?Date.parse(r):Number.NaN}function F(r,e){let t=r[e];return typeof t=="string"&&t!==""?Sr(t):void 0}function mt(r,e){return r.has(e)||r.otherParts?.has(e)===!0}function kr(r,e){let t=new Set,n=new Set;for(let g of r.syncing){let m=F(g,"Id"),h=F(g,"SyncedQuoteId");!m||!h||!mt(e,m)||!e.has(h)||(t.add(h),n.add(m))}if(t.size===0)return[];let o=r.quoteLines.filter(g=>{let m=F(g,"QuoteId");return m!==void 0&&t.has(m)&&F(g,"Id")!==void 0}),s=r.opportunityLines.filter(g=>{let m=F(g,"OpportunityId");return m!==void 0&&n.has(m)&&F(g,"Id")!==void 0}),a=g=>F(g,"CreatedById"),i=(g,m)=>{let h=F(g,"Id");if(!h||mt(e,h)||!m)return!1;let R=e.user??a(m),b=bn(g.CreatedDate);return R!==void 0&&a(g)===R&&b>=e.start&&b<=e.end},d=g=>({id:String(g.Id),modified:bn(g.LastModifiedDate)}),l=new Map(s.flatMap(g=>{let m=F(g,"Id");return m&&e.has(m)?[[m,g]]:[]})),c=new Map;for(let g of o){let m=F(g,"Id"),h=F(g,"OpportunityLineItemId");m&&h&&e.has(m)&&!c.has(h)&&c.set(h,g)}let f=o.filter(g=>{let m=F(g,"OpportunityLineItemId");return i(g,m?l.get(m):void 0)}).map(d),u=s.filter(g=>{let m=F(g,"Id");return i(g,m?c.get(m):void 0)}).map(d);return[...f.length>0?[{objectApiName:Re,copies:f}]:[],...u.length>0?[{objectApiName:we,copies:u}]:[]]}function Rn(r,e=[]){let t=new Set(r),n=t.has(be)||new Set(e).has(be);if(!t.has(xe)||!n)return[];let o=t.has(Re),s=t.has(we);return o===s?[]:[o?we:Re]}async function gt(r,e,t,n,o){let s=t.map(N).join(", "),a=[];for(let i of H(o)){let d=await r.query(`SELECT ${s} FROM ${N(e)} WHERE ${N(n)} IN (${i}) LIMIT ${yn}`);if(d.records.length>=yn)throw new Error(`More ${e} records than one read takes.`);for(let l of d.records)typeof l=="object"&&l!==null&&a.push(l)}return a}async function wn(r,e,t,n){let o=n.has(Re)||n.has(we),s=n.has(be)||e.otherParts?.objects.has(be)===!0;if(t.length===0||!s||!o)return[];try{let i=(await gt(r,be,["Id","SyncedQuoteId"],"SyncedQuoteId",t)).filter(c=>{let f=F(c,"Id");return f!==void 0&&mt(e,f)});if(i.length===0)return[];let d=await gt(r,Re,["Id","QuoteId","OpportunityLineItemId","CreatedById","CreatedDate","LastModifiedDate"],"QuoteId",[...new Set(i.map(c=>String(c.SyncedQuoteId)))]),l=await gt(r,we,["Id","OpportunityId","CreatedById","CreatedDate","LastModifiedDate"],"OpportunityId",i.map(c=>String(c.Id)));return kr({syncing:i,quoteLines:d,opportunityLines:l},e)}catch{return[]}}var Or=5,Se=4,Fe=2e3,Ar=4,He=[["CreatedDate","LastModifiedDate","CreatedById","LastModifiedById"],["CreatedDate","LastModifiedDate","CreatedById"],["SystemModstamp"],[]],ht=1e4,Dr="005",Sn="ContentDocumentLink",Ir="ContentDocument",Er="ContentVersion",Pr=5;function Je(r){let e=new Set(r.flatMap(n=>n.ids.map(y))),t=new Map;for(let{objectApiName:n,ids:o}of r)t.set(n,[...t.get(n)??[],...o]);return{objects:[...t].map(([n,o])=>({objectApiName:n,count:o.length})),pages:async function*(n){let o=t.get(n);o&&o.length>0&&(yield o)},has:n=>e.has(n)}}function re(r){return!Array.isArray(r)}function Xo(r){return re(r)?r.objects.reduce((e,t)=>e+t.count,0):r.reduce((e,t)=>e+t.ids.length,0)}function es(r){return(re(r)?r.objects:r).map(e=>e.objectApiName)}var ze=class{bits=new Uint8Array(0);add(e){let t=e>>3;if(t>=this.bits.length){let n=new Uint8Array(Math.max(t+1,this.bits.length*2,64));n.set(this.bits),this.bits=n}this.bits[t]|=1<<(e&7)}has(e){let t=e>>3;return t<this.bits.length&&(this.bits[t]&1<<(e&7))!==0}},yt=class{dates=new Float64Array(0);set(e,t){if(e>=this.dates.length){let n=new Float64Array(Math.max(e+1,this.dates.length*2,64)).fill(Number.NaN);n.set(this.dates),this.dates=n}this.dates[e]=t}at(e){return e<this.dates.length?this.dates[e]:Number.NaN}latestWithin(e,t){let n=Number.NaN;for(let o of this.dates)o>=e&&o<=t&&!(o<=n)&&(n=o);return n}};function ue(r,e){return typeof r=="string"&&e.has(y(r))}var kn=[{created:"CreatedDate",modified:"LastModifiedDate"},{modified:"SystemModstamp"}],pt={ContentDocumentLink:{ends:["ContentDocumentId","LinkedEntityId"],cameWithRun:(r,e)=>{let t=r.LinkedEntityId;return ue(r.ContentDocumentId,e)&&(ue(t,e)||typeof t=="string"&&t.startsWith(Dr))}},DuplicateRecordItem:{ends:["RecordId"],cameWithRun:(r,e)=>ue(r.RecordId,e)},ContentVersion:{ends:["ContentDocumentId"],cameWithRun:(r,e)=>ue(r.ContentDocumentId,e)},[te.objectApiName]:{ends:[te.parent,te.field],cameWithRun:(r,e)=>r[te.field]===te.value&&ue(r[te.parent],e)}};function ts(r,e){return{...Ce(r,e),serverTime:async()=>(await r.soap.getServerTimestamp()).timestamp,userId:async()=>(await r.soap.getUserInfo()).userId,queryDeleted:async t=>({records:(await r.query(t,{scanAll:!0})).records}),bulkDestroy:(t,n,o)=>he(Me(r),t,n,o)}}function bt(r,e,t){let n=new Map;for(let o of r??[]){let s=St(o.span,[],t);if(Number.isFinite(s.end))for(let a of o[e]??[]){let i=y(a);s.end<=(n.get(i)?.end??Number.NEGATIVE_INFINITY)||n.set(i,s)}}return n}function Cr(r=[],e=[]){if(r.length===0&&e.length===0)return;let t=[...r.map(({plan:n})=>re(n)?n:Je(n)),Je(e)];return{has:n=>t.some(o=>o.has(n))}}function Nr(r=[],e=[]){return new Set([...r.map(({plan:t})=>re(t)?t.objects:t),e].flat().map(t=>t.objectApiName))}function En(r,e){return new Map([...bt(r,"wrote",e)].map(([t,{end:n}])=>[t,n]))}function Pn(r,e){return`The user SandForge connects as may not delete ${r} records in this org: the ${e} record(s) of the run stay, and were not sent.`}function Rt(r,e){return`Not visible: ${r} record(s) found neither in the org nor in its recycle bin, as the user the removal runs as sees them \u2014 out of that user's sight, or deleted for good \u2014 are not counted as removed`+(e?` (the recycle bin could not be read: ${e})`:".")}function On(r,e,t){for(let o of r){let s=o.deleted+o.alreadyGone+o.keptChanged+o.keptDependents+o.refused+(o.notVisible??0);o.planned>s&&(o.notReached=o.planned-s)}let n=new Set(r.map(o=>o.objectApiName));for(let{objectApiName:o,count:s}of e)s===0||n.has(o)||(n.add(o),r.push({...new ke(o,s,t(o)).result,notReached:s}));return r}var ns={objects:[],cancelled:!1,gone:[],stamps:{},left:async function*(){}};function y(r){return r.slice(0,15)}function Mr(r){return r?.errorCode==="INVALID_FIELD"||/no such column/i.test(P(r))}function Lr(r,e){let t=/no such column '(\w+)'/i.exec(P(r))?.[1],n=He.findIndex((o,s)=>s>e&&(t===void 0||!o.includes(t)));return n===-1?He.length:n}function M(r){return typeof r=="string"?Date.parse(r):Number.NaN}function Cn(){return{modified:new yt,missing:new Set,firstCreated:Number.NaN,lastCreated:Number.NaN,binned:new Set}}var ke=class{result;notes=[];refused=new Map;unread;held=[];goneAt=new ze;goneLater=new Set;deletedLater=new Set;notVisible=0;notVisibleNote;secondTry=new Set;filesLeft=new Map;automationHeld=new Map;automationHeldAfter=new Set;automationHeldAlong=new Set;tookAlong=new Map;cameAlong=new Map;limitNotes=[];lockResent=new Map;constructor(e,t,n=0){this.result={objectApiName:e,planned:t,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],...n>0?{platformCopies:n}:{},unchecked:[],reasons:[]}}note(e){this.notes.includes(e)||this.notes.push(e)}isGone(e,t){return this.goneAt.has(t)||this.goneLater.has(y(e))}waiting(){return[...[...this.refused].filter(([,e])=>e.dependency).map(([e])=>e),...this.held]}refusedSent(){return[...this.refused].filter(([,e])=>e.sent).map(([e])=>e)}refusedToSendAgain(){return[...this.refused].filter(([,e])=>e.sent&&e.limit!==!0).map(([e])=>e)}secondTryNote(){if(this.secondTry.size===0)return[];let e=0,t=0,n=0,o=0;for(let a of this.secondTry){let i=y(a);this.deletedLater.has(i)?e++:this.goneLater.has(i)?t++:this.refused.has(a)?o++:n++}return[`Refused at first, sent again once the rest had gone: ${[e>0?`${e} deleted`:"",t>0?`${t} already gone`:"",n>0?`${n} kept for records that stay`:"",o>0?`${o} refused again`:""].filter(Boolean).join(", ")}.`]}settle(){this.result.keptDependents=this.held.length,this.result.refused=this.refused.size+(this.unread?.count??0),this.notVisible>0&&(this.result.notVisible=this.notVisible),this.held.length===0&&(this.result.heldBy=[]);let e=this.held.flatMap(s=>{let a=this.automationHeld.get(y(s));return a?[a]:[]}),t=this.held.filter(s=>{let a=y(s);return this.automationHeld.has(a)&&this.automationHeldAfter.has(a)}).length,n=this.held.filter(s=>{let a=y(s);return this.automationHeld.has(a)&&this.automationHeldAlong.has(a)}).length;e.length>0?(this.result.heldByAutomation=e.length,t>0?this.result.heldByAutomationAfterRun=t:delete this.result.heldByAutomationAfterRun,n>0?this.result.heldByAutomationAlong=n:delete this.result.heldByAutomationAlong,this.result.automationHolders=[...new Set(e.flatMap(s=>[...s]))]):(delete this.result.heldByAutomation,delete this.result.heldByAutomationAfterRun,delete this.result.heldByAutomationAlong,delete this.result.automationHolders);let o=[...this.notVisibleNote?[this.notVisibleNote]:[],...this.notes,...this.limitNotes,...rn(this.lockResent.values()),...this.secondTryNote(),...this.unread?[this.unread.reason]:[],...[...this.refused.values()].map(s=>s.reason)];return this.result.reasons=[...new Set(o)].slice(0,Or),this.filesLeft.size>0&&(this.result.filesLeft={count:this.filesLeft.size,names:[...this.filesLeft.values()].slice(0,Pr)}),this.tookAlong.size>0&&(this.result.tookAlong={count:this.tookAlong.size,objects:[...new Set(this.tookAlong.values())]}),this.cameAlong.size>0&&(this.result.cameAlong={count:this.cameAlong.size,objects:[...new Set(this.cameAlong.values())]}),this.result}};async function rs(r,e,t){let n=re(e)?e:Je(e),o=n,s=o.objects.reduce((p,S)=>p+S.count,0),a=new Map,i=p=>a.get(p)??0,d=()=>t.signal?.aborted===!0,l=t.splitting??vt(),c=()=>({objects:On([],o.objects,i),cancelled:!0,gone:[],stamps:{},left:()=>In(n)}),f=new Map,u=new Map;for(let{objectApiName:p}of o.objects){let S=Cn();f.set(p,S);let O=0;for await(let A of o.pages(p)){if(d())return c();let v=A[0];v!==void 0&&!u.has(v.slice(0,3))&&u.set(v.slice(0,3),p);let E=O;if(O+=A.length,S.error!==void 0)continue;let D=await Fr(r,p,A,E,S);if(S.error!==void 0||D.length===0)continue;if(d())return c();let B=await ln(r,p,D);if("error"in B)S.binError=B.error;else for(let z of B.deleted)S.binned.add(z)}}let g=new Map,m=!1,h=r.bulkDestroy?.bind(r),R={query:p=>r.query(p),destroy:(p,S)=>(m=!0,r.destroy(p,S)),...h?{bulkDestroy:(p,S)=>(m=!0,h(p,S,t.signal))}:{},update:(p,S)=>(m=!0,r.update(p,S)),serverTime:()=>r.serverTime(),userId:()=>r.userId(),queryDeleted:p=>r.queryDeleted(p),describeGlobal:()=>r.describeGlobal(),describe:p=>{let S=g.get(p);return S||(S=r.describe(p),g.set(p,S)),S}},b=gn(R,{includeChanged:t.includeChanged}),w=await Te(b,o.objects),k=await Br(b,w,(p,S)=>S-(f.get(p)?.missing.size??0)),I=new Set(k.map(p=>p.objectApiName));if(k.length>0&&t.onUndeletable&&t.previewOnly!==!0){if(d())return c();if(!await t.onUndeletable(k))return{...c(),objects:[],undeletable:k,stoppedForUndeletable:!0}}let[C,_]=await Promise.all([Hr(b),t.previewOnly===!0?void 0:Jr(b)]),{start:Y,end:V}=St(t,f.values(),C.aheadMs);if(d())return c();let oe=Cr(t.otherParts,t.otherPartRecords),qe=Nr(t.otherParts,t.otherPartRecords),Ae=await Ur(b,o,{start:Y,end:V,...t.runUserId?{user:y(t.runUserId)}:{},...oe?{otherParts:{has:p=>oe.has(p),objects:qe}}:{},undeletable:I,snapshots:f});if(t.runUserId&&t.alongAccepted!==!0){let p=await cn(b,{has:S=>o.has(S),start:Y,end:V,user:t.runUserId});p.length>0&&!o.objects.some(S=>S.objectApiName===le)&&await Nn(b,le)&&Ae.push({objectApiName:le,copies:p})}if(Ae.length>0){o=await $r(o,Ae,f,u);for(let{objectApiName:p,copies:S}of Ae)a.set(p,S.length);s=o.objects.reduce((p,S)=>p+S.count,0),w=await Te(b,o.objects)}let vn=new Map(Object.entries(t.removalStamps??{}).map(([p,S])=>[y(p),M(S)])),Tn=En(t.laterParts,C.aheadMs),se=new Set;for(let{objectApiName:p}of o.objects){let S=f.get(p);if(!S||S.error!==void 0)continue;let O=0;for await(let A of o.pages(p))for(let v of A){let E=S.modified.at(O++),D=y(v);if(S.missing.has(D))continue;E<=V||E<=(vn.get(D)??Number.NaN)||E<=(Tn.get(D)??Number.NaN)||se.add(D)}}if(t.previewOnly===!0){if(d())return c();let p=new Set,S=await vr(b,o,w,{snapshots:f,changed:se,undeletable:I,includeChanged:t.includeChanged,stopped:d,copiesOf:i,...t.previewHeld===!0?{held:{notSent:p,check:new Oe(b,{runRecords:o,reached:{has:()=>!1},stays:O=>p.has(O),runStart:Y,runEnd:V,removalStart:C.start,removalUser:void 0,earlierRemovals:(t.removalSpans??[]).map(O=>({start:M(O.first),end:M(O.last),user:y(O.userId)})),includeChanged:t.includeChanged,previewing:!0,...t.goesWithParent?{goesWithParent:t.goesWithParent}:{},...t.goesWithParentReadBelow?{goesWithParentReadBelow:!0}:{},...t.alongAccepted?{alongAccepted:t.alongAccepted}:{},...t.runUserId?{runUser:y(t.runUserId)}:{},...t.laterParts?{linkedLater:bt(t.laterParts,"linked",C.aheadMs)}:{},...oe?{otherPartRecords:oe,otherPartObjects:qe}:{}})}}:{}});return S?{...k.length>0?{undeletable:k}:{},objects:[],cancelled:!1,gone:[],stamps:{},left:()=>In(n),preview:S}:c()}let kt=await xr(b,t.otherParts??[],C.aheadMs,d);if(!kt)return c();let Ot=new Set,_n={has:p=>o.has(p)&&Ot.has(u.get(p.slice(0,3))??"")},We=new Oe(b,{runRecords:o,reached:_n,stays:p=>se.has(p)&&!t.includeChanged,runStart:Y,runEnd:V,removalStart:C.start,removalUser:_,earlierRemovals:(t.removalSpans??[]).map(p=>({start:M(p.first),end:M(p.last),user:y(p.userId)})),includeChanged:t.includeChanged,...t.goesWithParent?{goesWithParent:t.goesWithParent}:{},...t.goesWithParentReadBelow?{goesWithParentReadBelow:!0}:{},...t.alongAccepted?{alongAccepted:t.alongAccepted}:{},...t.alongToDraft?{alongToDraft:t.alongToDraft}:{},...t.runUserId?{runUser:y(t.runUserId)}:{},...t.automationMade?{automationMade:jn(t.automationMade)}:{},...t.laterParts?{linkedLater:bt(t.laterParts,"linked",C.aheadMs)}:{},...oe?{otherPartRecords:oe,otherPartObjects:qe}:{}});if(d())return c();await t.beforeFirstWrite?.(),t.sweep&&await t.sweep(l)&&(m=!0);let Z=[],At=p=>Z.find(S=>S.result.objectApiName===p);async function*Qe(p,S,O){for(let{objectApiName:A}of S){let v=At(A),E=0;for await(let D of p.pages(A)){let B=D.filter(z=>O(A,z,v?.isGone(z,E++)===!0));B.length>0&&(yield{objectApiName:A,ids:B})}}}let Bn=()=>Qe(o,w,(p,S,O)=>{let A=f.get(p),v=y(S);return A?.modifiedColumn==="LastModifiedDate"&&!A.missing.has(v)&&!se.has(v)&&!O}),De=[],$=async p=>{await an(b,De,{note:(D,B,z)=>{let U=At(D);if(!U){if(!z)return;let W=o.objects.find(Q=>Q.objectApiName===D);U=new ke(D,W?.count??0,i(D)),Z.push(U)}U.note(B)}});let S=m?await An(b,Bn(),{start:C.start,user:_}):{},O=[];if(m)for(let D of kt)O.push(await An(b,D.unchanged(),{start:C.start,user:_}));let A=m?zr(C,_):void 0,v=[];if(!re(e))for await(let{ids:D}of Qe(n,w,(B,z,U)=>U))for(let B of D)v.push(B);for(let D of Z)D.limitNotes=dt(D.result.objectApiName,l);let E=Z.map(D=>D.settle());return{...k.length>0?{undeletable:k}:{},objects:p?On(E,w,i):E,cancelled:p,gone:v,left:()=>Qe(n,n.objects,(D,B,z)=>!z),stamps:S,...A?{span:A}:{},...O.length>0?{otherPartStamps:O}:{}}};if(d())return m?$(!0):c();let Dt=async(p,S)=>(await We.heldAmong(p,S)).held,It=await lt(b,w,o,(p,S)=>{let O=y(S),A=f.get(p);return A!==void 0&&A.error===void 0&&!I.has(p)&&!A.missing.has(O)&&!(se.has(O)&&!t.includeChanged)},d,Dt);if(De=It.drafted,It.cancelled)return $(!0);if(t.alongToDraft){let p=await lt(b,t.alongToDraft.objects,t.alongToDraft,()=>!0,d,Dt);if(De=[...De,...p.drafted],p.cancelled)return $(!0)}let K=0;for(let{objectApiName:p,count:S}of w){if(d())return $(!0);let O=new ke(p,S,i(p));Z.push(O),Ot.add(p);let A=f.get(p);if(!A||A.error!==void 0){O.unread={reason:A?.error??"The org gave no reason.",count:S},K+=S,t.onProgress?.(K,s,p);continue}if(I.has(p)){let U=0,W=0;for await(let Q of o.pages(p))for(let ie of Q){let fe=y(ie),Fn=U++;A.missing.has(fe)?A.binned.has(fe)?(O.result.alreadyGone++,O.goneAt.add(Fn)):O.notVisible++:W++}O.notVisible>0&&(O.notVisibleNote=Rt(O.notVisible,A.binError)),W>0&&(O.unread={reason:Pn(p,W),count:W}),K+=S,t.onProgress?.(K,s,p);continue}let v=en(b,p,S),E=[],D=new Map,B=async()=>{let U=E,W=D;return E=[],D=new Map,Dn(b,We,O,U,{stopped:d,splitting:l,placeOf:W,onDeleted:Q=>{K+=Q,t.onProgress?.(K,s,p)},onHeld:Q=>{K+=Q,t.onProgress?.(K,s,p)}})},z=0;for await(let U of o.pages(p)){if(d())return $(!0);let W=E.length;for(let Q of U){let ie=y(Q),fe=z++;A.missing.has(ie)?A.binned.has(ie)?(O.result.alreadyGone++,O.goneAt.add(fe)):O.notVisible++:se.has(ie)&&!t.includeChanged?O.result.keptChanged++:(E.push(Q),D.set(ie,fe))}if(O.notVisible>0&&(O.notVisibleNote=Rt(O.notVisible,A.binError)),K+=U.length-(E.length-W),!(v&&E.length<ve)&&await B())return $(!0)}if(v&&E.length>0&&(d()||await B()))return $(!0)}let xn=Z.some(p=>p.result.deleted>0);if(await sn(Z,{stopped:d,idsOf:(p,S)=>{if(S>0)return p.waiting();let O=p.refusedToSendAgain();return O.length>0||xn?[...O,...p.held]:[]},send:async(p,S,O)=>{let A=new Set(O===0?p.refusedToSendAgain():[]),v=await Dn(b,We,p,S,{stopped:d,splitting:l,onSent:E=>{for(let D of E)A.has(D)&&p.secondTry.add(D)}});for(let E of p.held)A.has(E)&&p.secondTry.add(E);return v},deleted:p=>p.result.deleted}))return $(!0);if(t.afterRemoval){if(d())return $(!0);await t.afterRemoval(l)&&(m=!0)}for(let p of Z){if(d())return $(!0);await _r(b,p,f.get(p.result.objectApiName))}return $(!1)}async function jr(r,e,t,n,o){let{changed:s,includeChanged:a}=o,i=[];for await(let d of e.pages(t))for(let l of d){let c=y(l);!n.has(c)&&(a||!s.has(c))&&i.push(l)}try{return{kept:await hn(r,t,i,{includeChanged:a})}}catch(d){return{kept:new Set,unread:P(d)}}}async function vr(r,e,t,n){let o=[],s=new Set,a=new Set;for(let{objectApiName:i,count:d}of t){let l=n.copiesOf(i),c={objectApiName:i,planned:d,toDelete:0,alreadyGone:0,changedSince:0,keptChanged:0,changedBy:{},undeletable:0,notVisible:0,unread:0,...l>0?{platformCopies:l}:{},reasons:[]};o.push(c);let f=n.snapshots.get(i);if(!f||f.error!==void 0){if(c.unread=d,c.reasons.push(f?.error??"The org gave no reason."),n.held)for await(let R of e.pages(i))for(let b of R)n.held.notSent.add(y(b));continue}let u=ye(i)&&!n.undeletable.has(i)?await jr(r,e,i,f.missing,n):void 0,g=[],m=[],h=R=>{n.held?.notSent.add(R)};for await(let R of e.pages(i))for(let b of R){let w=y(b);f.missing.has(w)?f.binned.has(w)?c.alreadyGone++:c.notVisible++:n.undeletable.has(i)?(c.undeletable++,h(w)):u?.unread!==void 0?(c.unread++,h(w)):n.changed.has(w)?(c.changedSince++,g.push(b),n.includeChanged?(c.toDelete++,m.push(b)):(c.keptChanged++,h(w))):u?.kept.has(w)?(c.changedSince++,c.keptChanged++,h(w)):(c.toDelete++,m.push(b))}if(n.held&&m.length>0){if(n.stopped())return;let R=await n.held.check.heldAmong(i,m),b=m.filter(k=>R.held.has(y(k)));if(b.length>0){c.toDelete-=b.length,c.keptDependents=b.length,c.heldBy=[...R.holders];for(let I of b)n.held.notSent.add(y(I));let k=b.filter(I=>R.byAutomation.has(y(I)));k.length>0&&(c.heldByAutomation=k.length)}let w=new Map;for(let k of m)if(!R.held.has(y(k)))for(let[I,C]of R.cameAlong.get(y(k))??[])a.has(I)||(a.add(I),w.set(I,C));w.size>0&&(c.cameAlong={count:w.size,objects:[...new Set(w.values())]}),R.reason!==void 0&&c.reasons.push(R.reason),R.unchecked.size>0&&c.reasons.push(`Not checked: what hangs from them through ${[...R.unchecked].join(", ")}, which the org deletes along but does not let be read by the record it hangs from.`)}if(u?.unread!==void 0?c.reasons.push(`Its articles could not be read: ${u.unread}`):u!==void 0&&u.kept.size>0&&c.reasons.push(ft),c.notVisible>0&&c.reasons.push(Rt(c.notVisible,f.binError)),c.undeletable>0&&c.reasons.push(Pn(i,c.undeletable)),!(g.length===0||f.modifiedColumn!=="LastModifiedDate")){if(n.stopped())return;try{let R=await j(r,i,["LastModifiedById"],g,Se);for(let b of R){let w=b.LastModifiedById;typeof w!="string"||w===""||(c.changedBy[w]=(c.changedBy[w]??0)+1,s.add(w))}}catch(R){c.reasons.push(`Who changed them since the run could not be read: ${P(R)}`)}}}if(!n.stopped())return{objects:o,userNames:await Tr(r,[...s])}}async function Tr(r,e){let t={};if(e.length===0)return t;try{for(let n of await j(r,"User",["Name"],[...e].sort()))typeof n.Id=="string"&&typeof n.Name=="string"&&(t[n.Id]=n.Name)}catch{}return t}async function _r(r,e,t){let{gone:n,unchecked:o,failure:s}=await ct(e.refusedSent(),a=>j(r,e.result.objectApiName,[],a),a=>t!==void 0&&t.error===void 0&&!t.missing.has(y(a)));for(let a of n)e.refused.delete(a),e.goneLater.add(y(a)),e.result.alreadyGone++;o.length>0&&e.note(`Not checked: ${o.length} refused record(s) could not be read back once the rest had gone, to tell whether a parent deleted after them took them along`+(s?` \u2014 ${s}`:"."))}function os(r,e=[],t={}){return[...new Set([...r,...Rn(r,e),...t.userKept===!0&&r.length>0?[le]:[]])]}async function Br(r,e,t){let n=[];for(let{objectApiName:o,count:s}of e){if(o===Er||s===0)continue;let a=t(o,s);if(a!==0)try{let i=G.safeParse(await r.describe(o));i.success&&i.data.deletable===!1&&n.push({objectApiName:o,records:a})}catch{}}return n}async function An(r,e,t){let n={},{start:o,user:s}=t;if(s===void 0||!Number.isFinite(o))return n;for await(let{objectApiName:a,ids:i}of e){let d;try{d=await j(r,a,["LastModifiedDate","LastModifiedById"],i)}catch{continue}for(let l of d)typeof l.Id=="string"&&typeof l.LastModifiedDate=="string"&&typeof l.LastModifiedById=="string"&&y(l.LastModifiedById)===s&&M(l.LastModifiedDate)>=o&&(n[l.Id]=l.LastModifiedDate)}return n}async function xr(r,e,t,n){let o=[];for(let s of e){let a=re(s.plan)?s.plan:Je(s.plan),{end:i}=St(s.span,[],t),d=new Map(Object.entries(s.removalStamps??{}).map(([f,u])=>[y(f),M(u)])),l=En(s.laterParts,t),c=new Map;if(Number.isFinite(i))for(let{objectApiName:f}of a.objects){let u=new ze,g=0,m=!1;for await(let h of a.pages(f)){if(n())return;let R=g;if(g+=h.length,m)continue;let b;try{b=await j(r,f,["LastModifiedDate"],h,Se)}catch{m=!0;continue}let w=new Map;for(let k of b)typeof k.Id=="string"&&w.set(y(k.Id),M(k.LastModifiedDate));h.forEach((k,I)=>{let C=y(k),_=w.get(C);_!==void 0&&(_<=i||_<=(d.get(C)??Number.NaN)||_<=(l.get(C)??Number.NaN))&&u.add(R+I)})}m||c.set(f,u)}o.push({unchanged:async function*(){for(let{objectApiName:f}of a.objects){let u=c.get(f);if(!u)continue;let g=0;for await(let m of a.pages(f)){let h=m.filter(()=>u.has(g++));h.length>0&&(yield{objectApiName:f,ids:h})}}}})}return o}async function Dn(r,e,t,n,o){let{objectApiName:s}=t.result,a=await e.heldAmong(s,n);a.reason!==void 0&&t.note(a.reason);for(let u of a.unchecked)t.result.unchecked.includes(u)||t.result.unchecked.push(u);let i=n.filter(u=>a.held.has(y(u)));if(o.placeOf){for(let u of i)t.held.push(u);t.result.heldBy=[...new Set([...t.result.heldBy,...a.holders])]}else t.held=i,t.result.heldBy=[...a.holders];for(let u of i)t.refused.delete(u);for(let u of n){let g=y(u),m=a.byAutomation.get(g);m?t.automationHeld.set(g,m):t.automationHeld.delete(g),m&&a.automationAfter.has(g)?t.automationHeldAfter.add(g):t.automationHeldAfter.delete(g),m&&a.automationAlong.has(g)?t.automationHeldAlong.add(g):t.automationHeldAlong.delete(g)}o.onHeld?.(i.length);let d=n.filter(u=>!a.held.has(y(u))),l=new Map,c=(u,g)=>{u.forEach((m,h)=>{let R=g[h],b=y(m);if((R.lockResends!==void 0||t.lockResent.has(b))&&t.lockResent.set(b,R.kind),R.kind==="refused"){t.refused.set(m,{reason:R.reason,dependency:R.dependency,sent:!0,...R.limit?{limit:!0}:{}});return}t.refused.delete(m);let w=o.placeOf?.get(b);if(w!==void 0?t.goneAt.add(w):t.goneLater.add(b),R.kind==="deleted"){t.result.deleted++,w===void 0&&t.deletedLater.add(b);for(let k of l.get(b)??[])t.filesLeft.set(k.key,k.name);for(let[k,I]of a.along.get(b)??[])t.tookAlong.set(k,I);for(let[k,I]of a.cameAlong.get(b)??[])t.cameAlong.set(k,I)}else t.result.alreadyGone++}),o.onSent?.(u),o.onDeleted?.(u.length)},{stopped:f}=await on(r,s,d,{stopped:o.stopped,splitting:o.splitting,prepare:async u=>{l=await e.filesOn(u)},settle:c});return f}async function Fr(r,e,t,n,o){let s,a=o.modifiedColumn?kn.filter(({modified:i})=>i===o.modifiedColumn):kn;for(let{created:i,modified:d}of a)try{let c=await j(r,e,i?[i,d]:[d],t,Se),f=new Map;for(let g of c)typeof g.Id=="string"&&f.set(y(g.Id),M(g[d])),i&&(o.firstCreated=Mn(o.firstCreated,M(g[i])),o.lastCreated=wt(o.lastCreated,M(g[i])));o.modifiedColumn=d;let u=[];return t.forEach((g,m)=>{let h=y(g),R=f.get(h);R===void 0&&(o.missing.add(h),u.push(g)),o.modified.set(n+m,R??Number.NaN)}),u}catch(l){s??=P(l)}return o.error=s,o.modifiedColumn=void 0,[]}async function*In(r){for(let{objectApiName:e}of r.objects)for await(let t of r.pages(e))t.length>0&&(yield{objectApiName:e,ids:[...t]})}async function Ur(r,e,t){let n=new Set(e.objects.filter(i=>i.count>0).map(i=>i.objectApiName));if(!n.has(xe))return[];let o=[];for await(let i of e.pages(xe))o.push(...i);let s=await wn(r,{has:i=>e.has(i),start:t.start,end:t.end,...t.user!==void 0?{user:t.user}:{},...t.otherParts?{otherParts:t.otherParts}:{}},o,n),a=[];for(let i of s){let{objectApiName:d}=i;if(t.undeletable.has(d))continue;let l=t.snapshots.get(d);if(l){if(l.error!==void 0||l.modifiedColumn!=="LastModifiedDate")continue}else if(!await Nn(r,d))continue;a.push(i)}return a}async function Nn(r,e){try{let t=G.safeParse(await r.describe(e));return t.success&&t.data.deletable!==!1}catch{return!1}}async function $r(r,e,t,n){let o=new Map(e.map(({objectApiName:i,copies:d})=>[i,d])),s=new Set(e.flatMap(({copies:i})=>i.map(d=>y(d.id)))),a=r.objects.map(i=>{let d=o.get(i.objectApiName);return d?{objectApiName:i.objectApiName,count:i.count+d.length}:i});for(let[i,d]of o){r.objects.some(u=>u.objectApiName===i)||a.push({objectApiName:i,count:d.length});let l=t.get(i);l||(l={...Cn(),modifiedColumn:"LastModifiedDate"},t.set(i,l));let c=0;for await(let u of r.pages(i))c+=u.length;for(let u of d)l.modified.set(c++,u.modified);let f=d[0]?.id.slice(0,3);f!==void 0&&!n.has(f)&&n.set(f,i)}return{objects:a,pages:async function*(i){yield*r.pages(i);let d=o.get(i);d&&d.length>0&&(yield d.map(l=>l.id))},has:i=>r.has(i)||s.has(i)}}async function Hr(r){let e=Date.now(),t=Number.NaN;try{t=M(await r.serverTime())}catch{}return Number.isFinite(t)?{start:Math.floor(t/1e3)*1e3,aheadMs:t-(e+Date.now())/2}:{start:Number.POSITIVE_INFINITY,aheadMs:Number.NaN}}async function Jr(r){try{let e=await r.userId();return typeof e=="string"&&e!==""?y(e):void 0}catch{return}}function zr(r,e){if(!(e===void 0||!Number.isFinite(r.start)))return{first:new Date(r.start).toISOString(),last:new Date(Date.now()+r.aheadMs+ht).toISOString(),userId:e}}function Mn(r,e){return Number.isNaN(r)||e<r?e:r}function wt(r,e){return Number.isNaN(r)||e>r?e:r}var Ln=999;function qr(r,e,t){let n=Number.NaN;for(let o of r)o.lastCreated>=e&&o.lastCreated<=t&&(n=wt(n,o.lastCreated)),n=wt(n,o.modified.latestWithin(e,t));return n}function St(r,e,t){let n=Wr(r,e,t),o=(r.writtenUntil?.getTime()??Number.NaN)+Ln;return Number.isFinite(n.end)&&o>n.end?{...n,end:o}:n}function Wr(r,e,t){let n=[...e],o=Number.NaN;for(let l of n)o=Mn(o,l.firstCreated);let s=r.runDurationMs??0,a=(r.runRecordedAt?.getTime()??Number.NaN)+t;if(r.runEndedAt===void 0&&Number.isFinite(a)){let l=a-s-ht,c=a+ht,f=r.endedByItsWrites===!0?qr(n,l,c):Number.NaN;return{start:r.runStartedAt?.getTime()??(o>l?o:l),end:Number.isFinite(f)?Math.min(f+Ln,c):c}}let i=r.runStartedAt?.getTime()??o,d=r.runEndedAt?.getTime()??i+s;return{start:i,end:d}}function jn(r){let e=new Set,t=-1;return{has:n=>(r.size!==t&&(e=new Set([...r].map(y)),t=r.size),e.has(n))}}function ss(r,e){let t=new Oe(r,{runRecords:e.runRecords,reached:{has:()=>!1},stays:()=>!1,runStart:e.runStart,runEnd:e.runEnd,removalStart:Number.POSITIVE_INFINITY,removalUser:void 0,earlierRemovals:(e.removalSpans??[]).map(n=>({start:M(n.first),end:M(n.last),user:y(n.userId)})),includeChanged:e.includeChanged,automationMade:jn(e.taken),...e.runUserId?{runUser:y(e.runUserId)}:{}});return async(n,o)=>{let s=await t.heldAmong(n,o,1);return{held:s.held,holders:[...s.holders],...s.reason!==void 0?{reason:s.reason}:{}}}}var Ue="IsPersonAccount";function Qr(r,e){return{holding:new Set([...r.holding,...e.holding]),automation:[...r.automation,...e.automation],along:[...r.along,...e.along],goes:[...r.goes,...e.goes],unchecked:r.unchecked||e.unchecked}}var Vr=50;function $e(r,e){return JSON.stringify(e.map(t=>r[t]??null))}var Oe=class{constructor(e,t){this.org=e;this.context=t}org;context;worked;statuses=new Map;lockedUnder=new Map;files=new Map;datesKept=new Map;cascadeEnds=new Map;async heldAmong(e,t,n=0){let o={held:new Set,holders:new Set,otherwise:new Set,mayBeAutomation:[],byAutomation:new Map,automationAfter:new Set,automationAlong:new Set,along:new Map,cameAlong:new Map,unchecked:new Set};if(t.length===0)return o;let s;try{let u=G.parse(await this.org.describe(e)),g=await this.workedObjects(),m=e==="Account"&&u.fields.some(h=>h.name===Ue);s=(u.childRelationships??[]).filter(h=>(h.cascadeDelete===!0||h.restrictedDelete===!0)&&g.has(h.childSObject)).map(h=>({childSObject:h.childSObject,field:h.field,restricted:h.cascadeDelete!==!0,...m&&h.childSObject==="Contact"&&h.field==="AccountId"?{personContacts:!0}:{}}))}catch(u){return o.reason=P(u),t.forEach(g=>this.hold(o,y(g))),o}let a=[];for(let u=0;u<t.length;u+=q)a.push(t.slice(u,u+q));let i=a.length>1?await Ze(s.map(u=>()=>this.anyPointing(u)),Se):s.map(()=>!0),d=s.filter((u,g)=>i[g]).flatMap(u=>a.map(g=>async()=>({relationship:u,...await this.holdingIn(u,g)}))),l=o.mayBeAutomation,c=new Map;for(let{relationship:u,holding:g,unchecked:m,automation:h,along:R,goes:b}of await Ze(d,Se)){m&&o.unchecked.add(u.childSObject),(g.size>0||h.length>0)&&o.holders.add(u.childSObject),g.forEach(w=>this.hold(o,w));for(let w of h)o.held.add(y(w.parent));l.push(...h);for(let{parent:w,key:k}of R){let I=o.along.get(w)??new Map;I.set(k,u.childSObject),o.along.set(w,I)}b.length>0&&c.set(u.childSObject,[...c.get(u.childSObject)??[],...b])}if(await this.heldBelow(c,o,n),n>0)return o;this.context.previewing!==!0&&await this.lockedPastDraft(e,t,o),Ee(e)&&await this.standardPricesHeld(t,o),e===Ge&&await this.sellingModelOptionsHeld(t,o),this.context.alongAccepted!==!0&&await this.automationHeldBelow(l,o);let f=await this.byAutomationOnly(e,l,o.otherwise);return o.byAutomation=f.objects,o.automationAfter=f.after,o.automationAlong=f.along,o}hold(e,t){e.held.add(t),e.otherwise.add(t)}async heldBelow(e,t,n){let o=(s,a,i,d)=>{let l=s.get(a)??new Map;l.set(i,d),s.set(a,l)};for(let[s,a]of e){let i=[...new Set(a.map(l=>l.id))],d=n+1<Ar?await this.heldAmong(s,i,n+1):void 0;for(let{parent:l,id:c,came:f}of a){let u=y(c);if(!d||d.held.has(u)){this.hold(t,l),t.holders.add(s),d?.holders.forEach(g=>t.holders.add(g));continue}f&&o(t.cameAlong,l,u,s);for(let[g,m]of d.along.get(u)??[])o(t.along,l,g,m);for(let[g,m]of d.cameAlong.get(u)??[])o(t.cameAlong,l,g,m)}d?.unchecked.forEach(l=>t.unchecked.add(l))}}async automationHeldBelow(e,t){let n=new Map;for(let o of e)t.otherwise.has(y(o.parent))||n.set(o.object,[...n.get(o.object)??[],o]);for(let[o,s]of n){let a=await this.heldAmong(o,[...new Set(s.map(i=>i.id))],1);for(let i of s){let d=y(i.id),l=a.mayBeAutomation.some(c=>y(c.parent)===d&&c.creator!==i.creator);!a.otherwise.has(d)&&!l||(this.hold(t,y(i.parent)),a.holders.forEach(c=>t.holders.add(c)))}a.unchecked.forEach(i=>t.unchecked.add(i))}}async byAutomationOnly(e,t,n){let o=new Map,s=new Set,a=t.filter(f=>!n.has(y(f.parent)));if(a.length===0)return{objects:o,after:s,along:new Set};let i;try{let f=await j(this.org,e,["CreatedDate","CreatedById"],[...new Set(a.map(u=>u.parent))]);i=new Map(f.flatMap(u=>typeof u.Id=="string"?[[y(u.Id),u]]:[]))}catch{return{objects:o,after:s,along:new Set}}let d=new Set,l=new Set;for(let f of a){let u=y(f.parent),g=i.get(u),m=M(g?.CreatedDate),h=g?.CreatedById,R=this.context.runUser??(typeof h=="string"?y(h):void 0),b=f.created-m;if(!(R!==void 0&&f.creator===R&&b>=-2e3&&b<=6e4)){d.add(u);continue}let k=o.get(u)??new Set;k.add(f.object),o.set(u,k),f.created>this.context.runEnd&&s.add(u),f.along||l.add(u)}for(let f of d)o.delete(f),s.delete(f);let c=new Set([...o.keys()].filter(f=>!l.has(f)));return{objects:o,after:s,along:c}}async holdingIn(e,t){let n=N(e.childSObject),o=N(e.field),[s]=H(t,t.length),a=new Set(["Id",o,...pt[n]?.ends??[],...e.personContacts?[Ue]:[]]),i=this.datesKept.get(n)??0;for(;i<He.length;){let d=He[i],l;try{l=await this.org.query(`SELECT ${[...a,...d].join(", ")} FROM ${n} WHERE ${o} IN (${s}) LIMIT ${Fe}`)}catch(R){Mr(R)?(i=Lr(R,i),this.datesKept.set(n,i)):i++;continue}if(l.records.length>=Fe){if(t.length>1){let R=Math.ceil(t.length/2);return Qr(await this.holdingIn(e,t.slice(0,R)),await this.holdingIn(e,t.slice(R)))}return{holding:new Set(t.map(y)),automation:[],along:[],goes:[],unchecked:!1}}let c=new Set,f=[],u=[],g=[],m=new Map;for(let R of l.records){if(typeof R!="object"||R===null)continue;let b=R,w=b[e.field];if(typeof w!="string"||typeof b.Id!="string"||(n===Sn&&o==="LinkedEntityId"&&this.noteFile(b),this.lockedUnder.get(y(b.Id))===y(w)))continue;let k={onlyIncluded:!1};if(!this.stays(b,n,e.restricted,e.personContacts,k)){if(k.onlyIncluded&&u.push({parent:y(w),key:y(b.Id)}),n!==Sn&&this.goesAlongUnread(b)){let _=!(pt[n]?.cameWithRun(b,this.context.runRecords)===!0||e.personContacts===!0&&b[Ue]===!0)&&!k.onlyIncluded&&k.byRemoval!==!0&&this.context.goesWithParent?.(b,this.context.runEnd)!==!0;g.push({parent:y(w),id:b.Id,came:_})}continue}let I=this.mayBeAutomation(b);if(I){let C={parent:w,id:b.Id,object:n,along:!e.restricted,...I};f.push(C),e.restricted&&m.set(b.Id,C)}else c.add(y(w))}let h=await this.ofOtherParts(n,[...m.keys()]);for(let[R,b]of m)h.has(y(R))&&(f.splice(f.indexOf(b),1),c.add(y(b.parent)));return{holding:c,automation:f,along:u,goes:g,unchecked:!1}}return{holding:new Set,automation:[],along:[],goes:[],unchecked:!e.restricted}}goesAlongUnread(e){let t=y(e.Id),{runRecords:n,otherPartRecords:o,automationMade:s,goesWithParent:a,runEnd:i}=this.context;return this.context.alongAccepted!==!0&&!n.has(t)&&o?.has(t)!==!0&&s?.has(t)!==!0&&(this.context.goesWithParentReadBelow===!0||a?.(e,i)!==!0)}async ofOtherParts(e,t){let n=new Set,{otherPartRecords:o,otherPartObjects:s,runRecords:a}=this.context;if(t.length===0||!o||!s)return n;let i=this.cascadeEnds.get(e);i||(i=(async()=>{let c=new Set;for(let f of s)try{let u=G.parse(await this.org.describe(f));for(let g of u.childRelationships??[])g.childSObject===e&&g.cascadeDelete===!0&&c.add(g.field)}catch{}return[...c]})(),this.cascadeEnds.set(e,i));let d=await i;if(d.length===0)return n;let l;try{l=await j(this.org,e,d,t)}catch{return n}for(let c of l){if(typeof c.Id!="string")continue;let f=d.flatMap(u=>{let g=c[u];return typeof g=="string"?[y(g)]:[]});f.some(u=>a.has(u))||f.some(u=>o.has(u))&&n.add(y(c.Id))}return n}mayBeAutomation(e){let{runRecords:t,runStart:n,runEnd:o,runUser:s,otherPartRecords:a}=this.context;if(typeof e.Id!="string"||t.has(y(e.Id))||a?.has(y(e.Id))===!0||typeof e.CreatedById!="string")return;let i=y(e.CreatedById);if(s!==void 0&&i!==s)return;let d=M(e.CreatedDate);if(!(d>=n-2e3&&d<=o+6e4))return;let l=M(e.LastModifiedDate),c=typeof e.LastModifiedById=="string"?y(e.LastModifiedById):void 0;if(!(l>o&&c!==void 0&&c!==i))return{created:d,creator:i}}async anyPointing(e){try{let t=N(e.childSObject),n=N(e.field);return(await this.org.query(`SELECT Id FROM ${t} WHERE ${n} != null LIMIT 1`)).records.length>0}catch{return!0}}noteFile(e){let t=e.LinkedEntityId,n=e.ContentDocumentId;if(typeof t!="string"||typeof n!="string"||ue(n,this.context.runRecords))return;let o=this.files.get(y(t))??new Set;o.add(n),this.files.set(y(t),o)}async filesOn(e){let t=new Map;for(let s of e){let a=this.files.get(y(s));a&&a.size>0&&t.set(y(s),[...a])}let n=[...new Set([...t.values()].flat())];if(n.length===0)return new Map;let o=new Map;try{for(let s of await j(this.org,Ir,["Title"],n))typeof s.Id=="string"&&typeof s.Title=="string"&&s.Title!==""&&o.set(y(s.Id),s.Title)}catch{}return new Map([...t].map(([s,a])=>[s,a.map(i=>({key:y(i),name:o.get(y(i))??i}))]))}async lockedPastDraft(e,t,n){for(let[o,s]of Object.entries(Nt)){let a=s.find(u=>u.object===e)?.lookup,i=me[o];if(!a||!i)continue;let d=await this.statusCategoriesOf(i);if(!d)continue;let l,c;try{l=await j(this.org,e,[a],t);let u=[...new Set(l.map(g=>g[a]).filter(g=>typeof g=="string"))];c=u.length>0?await j(this.org,o,["Status"],u):[]}catch{continue}let f=new Set(c.filter(u=>{let g=d.categoryOf.get(String(u.Status));return g!==void 0&&g!=="Draft"}).map(u=>y(String(u.Id))));for(let u of l){let g=u[a];typeof u.Id!="string"||typeof g!="string"||f.has(y(g))&&(this.hold(n,y(u.Id)),n.holders.add(o),this.lockedUnder.set(y(u.Id),y(g)))}}}statusCategoriesOf(e){let t=this.statuses.get(e);return t||(t=Pe(de(this.org),e),this.statuses.set(e,t)),t}async standardPricesHeld(e,t){try{let n=de(this.org),o=[...await pe(n,e)];if(o.length===0)return;let s=await this.priceKeyFields(),a=await j(this.org,ee,s,o),i=await this.pricesOfProducts(a,s),d=i.flatMap(u=>typeof u.Id=="string"?[u.Id]:[]),l=new Set([...await pe(n,d)].map(y)),c=new Set(e.map(y)),f=new Set;for(let u of i){if(typeof u.Id!="string")continue;let g=y(u.Id);if(l.has(g))continue;(c.has(g)?t.held.has(g):this.stays(u,ee,!0))&&f.add($e(u,s))}for(let u of a)typeof u.Id!="string"||!f.has($e(u,s))||(this.hold(t,y(u.Id)),t.holders.add(ee))}catch{}}async sellingModelOptionsHeld(e,t){let n=[ge,Ke];try{let o=await j(this.org,Ge,n,e),s=await this.pricesOfProducts(o,[...n,"IsActive"]),a=new Set(s.filter(i=>typeof i.Id=="string"&&i.IsActive===!0&&this.stays(i,ee,!0)).map(i=>$e(i,n)));for(let i of o)typeof i.Id!="string"||!a.has($e(i,n))||(this.hold(t,y(i.Id)),t.holders.add(ee))}catch{}}async priceKeyFields(){let e=G.parse(await this.org.describe(ee)),t=new Set(e.fields.map(n=>n.name));return[ge,...[Ke,Mt].filter(n=>t.has(n))]}async pricesOfProducts(e,t){let n=[...new Set(e.map(a=>a[ge]).filter(a=>typeof a=="string"))],o=[...new Set(["Id",...t])].map(N).join(", "),s=[];for(let a of H(n,Vr)){let i=await this.org.query(`SELECT ${o} FROM ${ee} WHERE ${ge} IN (${a}) LIMIT ${Fe}`);if(i.records.length>=Fe)throw new Error("More prices than one read takes.");for(let d of i.records)typeof d=="object"&&d!==null&&s.push(d)}return s}stays(e,t,n=!1,o=!1,s){let a=y(e.Id),{runRecords:i,reached:d,runStart:l,runEnd:c,removalStart:f,removalUser:u,earlierRemovals:g,includeChanged:m}=this.context;if(i.has(a))return d.has(a)||this.context.stays(a);if(n)return!0;if(this.context.automationMade?.has(a)===!0||this.context.goesWithParent?.(e,c)===!0||this.context.alongToDraft?.has(a)===!0||pt[t]?.cameWithRun(e,i))return!1;if(o&&e[Ue]===!0)return!(M(e.LastModifiedDate??e.SystemModstamp)<=c)&&!m;let h="CreatedDate"in e?"CreatedDate":"SystemModstamp"in e?"SystemModstamp":void 0;if(!h)return!0;let R=M(e[h]),b=M(h==="CreatedDate"?e.LastModifiedDate:e.SystemModstamp);if(!(R>=l))return!0;let w=this.context.linkedLater?.get(a);if(w&&(R<=c||R>=w.start)&&b<=w.end)return!1;let k=typeof e.CreatedById=="string"?y(e.CreatedById):void 0,I=(_,Y)=>_!==void 0&&(_===u&&Y>=f||g.some(V=>_===V.user&&Y>=V.start&&Y<=V.end));if(I(k,R))return s&&(s.byRemoval=!0),!1;if(b<=c)return!1;let C=typeof e.LastModifiedById=="string"?y(e.LastModifiedById):void 0;return R<=c&&I(C,b)?!1:(m&&s&&(s.onlyIncluded=!0),!m)}workedObjects(){return this.worked??=jt(this.org),this.worked}};export{Ne as a,et as b,qt as c,Wt as d,G as e,Qt as f,qn as g,Qn as h,Vn as i,Kn as j,Gn as k,ro as l,Me as m,tt as n,ve as o,he as p,ho as q,at as r,rr as s,sr as t,en as u,nn as v,dt as w,rn as x,on as y,sn as z,Te as A,ct as B,cr as C,lt as D,ko as E,an as F,wn as G,le as H,gr as I,ht as J,re as K,Xo as L,es as M,ts as N,ns as O,rs as P,os as Q,ss as R};
|