sandforge 1.80.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-EMNC6YI4.mjs → chunk-2IB7I3IQ.mjs} +1 -1
- package/lib/{chunk-3RZQZHEB.mjs → chunk-2NAIUKVL.mjs} +1 -1
- package/lib/{chunk-AEKONPF4.mjs → chunk-2OIRJEYE.mjs} +1 -1
- package/lib/{chunk-BV6VTP3J.mjs → chunk-2OZG6GRW.mjs} +1 -1
- package/lib/{chunk-JEERQRLW.mjs → chunk-2Z54GB6X.mjs} +1 -1
- package/lib/chunk-2ZMGVBLW.mjs +7 -0
- package/lib/{chunk-FKG7Q3WH.mjs → chunk-33ZX3A56.mjs} +1 -1
- package/lib/{chunk-HLWMJF6Y.mjs → chunk-3AOKLIVE.mjs} +1 -1
- package/lib/{chunk-GGD7ON3M.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-BKDV4ENO.mjs → chunk-5UT2ZBGF.mjs} +1 -1
- package/lib/chunk-5VQNKDFU.mjs +7 -0
- package/lib/{chunk-XAMBCQPU.mjs → chunk-5WGA5CZB.mjs} +1 -1
- package/lib/chunk-5ZKCLBTN.mjs +474 -0
- package/lib/{chunk-UCD54V2M.mjs → chunk-67CC7RAE.mjs} +1 -1
- package/lib/{chunk-TSLJUSLW.mjs → chunk-6CDIIFNX.mjs} +1 -1
- package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
- package/lib/{chunk-FPKYYFM7.mjs → chunk-6FMLW7PH.mjs} +1 -1
- package/lib/chunk-6IGEASOF.mjs +7 -0
- package/lib/{chunk-XUWL6ZPC.mjs → chunk-6NADW3OI.mjs} +1 -1
- package/lib/chunk-6SEDOIO3.mjs +10 -0
- package/lib/{chunk-PJ5I73CK.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-2UZPIMUC.mjs → chunk-AJPSGVMD.mjs} +1 -1
- package/lib/{chunk-GSKCGQIP.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-J525F5KI.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-OHWNPXWW.mjs → chunk-D7P7DTWL.mjs} +1 -1
- package/lib/{chunk-COFG7Q6R.mjs → chunk-DHGPDSXS.mjs} +1 -1
- package/lib/{chunk-WU3GLFZO.mjs → chunk-DHIW4IO5.mjs} +1 -1
- package/lib/{chunk-6XYKJSGX.mjs → chunk-DMBR24CK.mjs} +1 -1
- package/lib/chunk-DPYTG6DM.mjs +48 -0
- package/lib/{chunk-BY2HJFFG.mjs → chunk-DQR5NDMI.mjs} +1 -1
- package/lib/chunk-DXOXLUZA.mjs +7 -0
- package/lib/{chunk-YRQGKDHM.mjs → chunk-E2OBAWSH.mjs} +1 -1
- package/lib/chunk-E2YJVSX6.mjs +10 -0
- package/lib/{chunk-JWTSEDIQ.mjs → chunk-EAFLDSQ2.mjs} +1 -1
- package/lib/{chunk-MILU7WFN.mjs → chunk-EH5YUA5W.mjs} +1 -1
- package/lib/{chunk-BGUEWRK2.mjs → chunk-EOSEMFPU.mjs} +1 -1
- package/lib/chunk-ETT5GP4P.mjs +13 -0
- package/lib/{chunk-MYW5QNGI.mjs → chunk-FDGFUEK3.mjs} +1 -1
- package/lib/{chunk-NTFIRZP6.mjs → chunk-FLNLG43R.mjs} +1 -1
- package/lib/{chunk-CHYDMRSV.mjs → chunk-FSDO4DJA.mjs} +1 -1
- package/lib/{chunk-MJVTDA5Q.mjs → chunk-FSZTXLNW.mjs} +1 -1
- package/lib/{chunk-SOU4FRYN.mjs → chunk-FTA5LOVX.mjs} +1 -1
- package/lib/chunk-G4VXPS3A.mjs +7 -0
- package/lib/chunk-GF247DA7.mjs +7 -0
- package/lib/{chunk-BTWDMNN3.mjs → chunk-GK7VEYFM.mjs} +1 -1
- package/lib/{chunk-SE4QEZUG.mjs → chunk-GR3NGDVM.mjs} +1 -1
- package/lib/{chunk-3TJON4F3.mjs → chunk-GTIXJCGS.mjs} +1 -1
- package/lib/{chunk-NZC67CGR.mjs → chunk-GWRKS3AL.mjs} +1 -1
- package/lib/{chunk-XLXIPIEW.mjs → chunk-GYKNCYES.mjs} +1 -1
- package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
- package/lib/{chunk-KDGMAGQR.mjs → chunk-HVC5CYIB.mjs} +1 -1
- package/lib/{chunk-WR4Q363I.mjs → chunk-HYBH5PFM.mjs} +1 -1
- package/lib/chunk-HYOOJVR6.mjs +7 -0
- package/lib/{chunk-5K5VLULK.mjs → chunk-IBURU7T7.mjs} +1 -1
- package/lib/chunk-ICIYL45C.mjs +7 -0
- package/lib/{chunk-QR3WELJQ.mjs → chunk-IKGHRYCN.mjs} +1 -1
- package/lib/chunk-IM2XA6JI.mjs +7 -0
- package/lib/{chunk-IWDREM66.mjs → chunk-J6G23RUI.mjs} +1 -1
- package/lib/{chunk-2BA2XKAY.mjs → chunk-JU2XEKEO.mjs} +1 -1
- package/lib/{chunk-MHMH6MTP.mjs → chunk-K55LH4ZQ.mjs} +1 -1
- package/lib/chunk-K5HV4YRO.mjs +7 -0
- package/lib/{chunk-M3ROUWDX.mjs → chunk-K77NR3UK.mjs} +1 -1
- package/lib/chunk-KE2PGD6C.mjs +7 -0
- package/lib/chunk-KGYXLSQ5.mjs +37 -0
- package/lib/{chunk-E5AHXLS6.mjs → chunk-KNIRA333.mjs} +1 -1
- package/lib/chunk-KOQV4WXC.mjs +8 -0
- package/lib/{chunk-L77FJZEP.mjs → chunk-KRNFVAGC.mjs} +1 -1
- package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
- package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
- package/lib/{chunk-IZQZ6ZUF.mjs → chunk-LO527YLT.mjs} +1 -1
- package/lib/chunk-MAHZMPMZ.mjs +7 -0
- package/lib/{chunk-F6GUDTOB.mjs → chunk-MHW6DV6T.mjs} +1 -1
- package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
- package/lib/{chunk-FGRG7ANU.mjs → chunk-MKNAZPOT.mjs} +1 -1
- package/lib/{chunk-PZPJKATS.mjs → chunk-MNITSYI2.mjs} +8 -8
- package/lib/{chunk-OLSGVAIL.mjs → chunk-MO3N5XVV.mjs} +53 -53
- 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-IG2MTQRP.mjs → chunk-NWVVCZUK.mjs} +1 -1
- package/lib/{chunk-2NBYT7GR.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-CEX3NEZL.mjs → chunk-ONMBSACW.mjs} +1 -1
- package/lib/chunk-OQQHNYR7.mjs +272 -0
- package/lib/{chunk-SOGQW4IG.mjs → chunk-OU5W7SCB.mjs} +1 -1
- package/lib/{chunk-O2HDYYUV.mjs → chunk-OVOLG3AL.mjs} +1 -1
- package/lib/{chunk-DYFALGRT.mjs → chunk-OXKZ4Y3B.mjs} +1 -1
- package/lib/{chunk-2GTBABKU.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-IGYH7GMA.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-BXU6WFMH.mjs → chunk-QXLZINZB.mjs} +1 -1
- package/lib/chunk-R2BJWO5N.mjs +20 -0
- package/lib/chunk-R6TF26V4.mjs +10 -0
- package/lib/{chunk-YKKRIEH4.mjs → chunk-RKALOKAU.mjs} +1 -1
- package/lib/chunk-SQGP46QS.mjs +7 -0
- package/lib/chunk-SW2NUKQL.mjs +9 -0
- package/lib/{chunk-MFG4MUIO.mjs → chunk-T26C576X.mjs} +1 -1
- package/lib/{chunk-LKQ5RKIV.mjs → chunk-T3PLRQ2T.mjs} +1 -1
- package/lib/chunk-T5VAULLQ.mjs +7 -0
- package/lib/{chunk-KYEDBS54.mjs → chunk-TEIBWMJM.mjs} +1 -1
- package/lib/chunk-TKQQVB2D.mjs +9 -0
- package/lib/{chunk-ELFXJHU7.mjs → chunk-TPHXRHOA.mjs} +1 -1
- package/lib/chunk-TQ2TQHTT.mjs +9 -0
- package/lib/{chunk-RPI7LRTW.mjs → chunk-TQM2XJ27.mjs} +1 -1
- package/lib/{chunk-IOIWJ3DJ.mjs → chunk-UCHAZ4ZU.mjs} +1 -1
- package/lib/{chunk-G35N4P7D.mjs → chunk-UIUPPEFB.mjs} +1 -1
- package/lib/{chunk-DBB3EMIN.mjs → chunk-UT27HXE7.mjs} +1 -1
- package/lib/{chunk-KBJ5VERV.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-HEKAZJRH.mjs → chunk-WEZLXE34.mjs} +1 -1
- package/lib/{chunk-W622GUAW.mjs → chunk-WI4HYWV6.mjs} +1 -1
- package/lib/{chunk-WA7EYLAQ.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-FXXLX4O6.mjs → chunk-X2ZVSQ54.mjs} +1 -1
- package/lib/{chunk-ZVAED4QV.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-74Q6DORA.mjs → chunk-Y5ZCPY36.mjs} +1 -1
- package/lib/{chunk-UNJA4J37.mjs → chunk-YCSFP6ER.mjs} +4 -4
- package/lib/{chunk-X5JYBPXP.mjs → chunk-YHIOS2PU.mjs} +1 -1
- package/lib/chunk-YIGFYZQY.mjs +7 -0
- package/lib/chunk-YJEXE6HZ.mjs +925 -0
- package/lib/{chunk-TTKXMDBN.mjs → chunk-YOGMP72T.mjs} +4 -4
- package/lib/chunk-ZRUDYB7O.mjs +7 -0
- package/lib/{chunk-CU2INBND.mjs → chunk-ZUA5BNAO.mjs} +1 -1
- package/lib/chunk-ZWCRWF7E.mjs +7 -0
- package/lib/{chunk-N652NMZ4.mjs → chunk-ZWZXQTAK.mjs} +52 -52
- package/lib/sandforge-autopilot.mjs +11 -11
- package/lib/sandforge-backup.mjs +63 -32
- package/lib/sandforge-checkpoint.mjs +1 -348
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +1 -1
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +11 -11
- package/lib/sandforge-env.mjs +104 -104
- package/lib/sandforge-frozen.mjs +1 -266
- package/lib/sandforge-mcp.mjs +33 -14
- package/lib/sandforge-monitor.mjs +1 -1
- 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-2CNCDM56.mjs +0 -7
- package/lib/chunk-3F6Q5E7I.mjs +0 -14
- package/lib/chunk-4VS2V6WU.mjs +0 -25
- package/lib/chunk-5P4PHJRL.mjs +0 -9
- package/lib/chunk-5TC3QB4U.mjs +0 -10
- package/lib/chunk-7ABODJ4G.mjs +0 -7
- package/lib/chunk-7EGQP6S4.mjs +0 -7
- package/lib/chunk-7FFGJWHN.mjs +0 -7
- package/lib/chunk-7YDNUBO5.mjs +0 -7
- package/lib/chunk-A527W53V.mjs +0 -7
- package/lib/chunk-ADOAS63R.mjs +0 -7
- package/lib/chunk-B5QQJ4SI.mjs +0 -7
- package/lib/chunk-CION3VMZ.mjs +0 -7
- package/lib/chunk-CSBS5U5I.mjs +0 -7
- package/lib/chunk-DB7RBE5D.mjs +0 -7
- package/lib/chunk-E5ZB3LU5.mjs +0 -7
- package/lib/chunk-EFR2Y7E4.mjs +0 -7
- package/lib/chunk-EHQ3FX6X.mjs +0 -7
- package/lib/chunk-EQNW3UC2.mjs +0 -7
- package/lib/chunk-F43REJDZ.mjs +0 -10
- package/lib/chunk-GSG7WZHM.mjs +0 -7
- package/lib/chunk-HOJYWTP7.mjs +0 -20
- package/lib/chunk-HS4YRX4J.mjs +0 -7
- package/lib/chunk-I7O6C2B5.mjs +0 -8
- package/lib/chunk-IFETCRWE.mjs +0 -10
- package/lib/chunk-IQXHJEYB.mjs +0 -7
- package/lib/chunk-JPUR2CFX.mjs +0 -10
- package/lib/chunk-K327QKMD.mjs +0 -7
- package/lib/chunk-KRCA6IPH.mjs +0 -8
- package/lib/chunk-LPBMBW3O.mjs +0 -13
- package/lib/chunk-LWW4U276.mjs +0 -7
- package/lib/chunk-MJU2PGZQ.mjs +0 -15
- package/lib/chunk-OAZRPP4I.mjs +0 -7
- package/lib/chunk-OO6CLPEH.mjs +0 -7
- package/lib/chunk-OPXCV2KL.mjs +0 -7
- package/lib/chunk-P33PSCXK.mjs +0 -7
- package/lib/chunk-Q3DM32KF.mjs +0 -11
- package/lib/chunk-QROPNEGY.mjs +0 -14
- package/lib/chunk-QWT2C74M.mjs +0 -7
- package/lib/chunk-R3X3LV64.mjs +0 -14
- package/lib/chunk-RMBPOTD7.mjs +0 -7
- package/lib/chunk-SIHORWVK.mjs +0 -7
- package/lib/chunk-T62WNR54.mjs +0 -7
- package/lib/chunk-TTFDUKUS.mjs +0 -47
- package/lib/chunk-VE6XKGGD.mjs +0 -7
- package/lib/chunk-VGW4MXXZ.mjs +0 -7
- package/lib/chunk-VS7ZXUII.mjs +0 -824
- package/lib/chunk-VXQLDM4R.mjs +0 -7
- package/lib/chunk-VYXMVJL5.mjs +0 -7
- package/lib/chunk-W7U5E5ZL.mjs +0 -9
- package/lib/chunk-WXAQ7FK3.mjs +0 -115
- package/lib/chunk-YS4G22C2.mjs +0 -7
- package/lib/chunk-ZM6OJGIG.mjs +0 -7
- package/lib/chunk-ZUTYVST5.mjs +0 -7
|
@@ -0,0 +1,10 @@
|
|
|
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{h as O}from"./chunk-AITNZWLB.mjs";import{A as R,B as _,e as X,k as S,r as P}from"./chunk-ETT5GP4P.mjs";import{H as E,c as Y,p as A,q as z}from"./chunk-E2YJVSX6.mjs";import{g as w,h as y}from"./chunk-EAFLDSQ2.mjs";import{vc as u}from"./chunk-DPYTG6DM.mjs";import{b as D,e as W,f as Q,l as L}from"./chunk-WZQEK4WT.mjs";import{mkdir as se,rm as M}from"node:fs/promises";import{join as I}from"node:path";var ee=200,ne=X*10,B=2e3,te=["Id","ContentDocumentId","LinkedEntityId","ShareType","Visibility"],ae=["Id","LatestPublishedVersionId","ContentSize"],de="taking",h=D().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),T=D().regex(/^[A-Za-z]{1,40}$/,"Not a sharing value"),V=L({Id:h,ContentDocumentId:h,LinkedEntityId:h,ShareType:T,Visibility:T}),J=L({Id:h,LatestPublishedVersionId:h.nullable(),ContentSize:W().int().nonnegative().nullable(),anchored:Q()});function Re(e,n){return I(e,`${y}.${n}.ndjson`)}var Ce=V.extend({now:L({ShareType:T,Visibility:T})});function Fe(e,n){let t=new Set(n.map(r=>r.toLowerCase())),i=new Map;for(let r of e){let a=r.keyPrefix;t.has(r.name.toLowerCase())&&typeof a=="string"&&a.length===3&&i.set(a,r.name)}return i}function Te(e,n){let t=e.LinkedEntityId;return typeof t=="string"&&t.length>=15?n.get(t.slice(0,3)):void 0}function oe(e){return e.map(n=>{if(!h.safeParse(n).success)throw new Error(`Not a record id: ${n}`);return`'${n}'`}).join(", ")}function ce(e){let n=u(e);return{objectApiName:n,soql:`SELECT ${te.join(", ")} FROM ${y} WHERE LinkedEntityId IN (SELECT Id FROM ${n})`,scanAll:!1}}function be(e){let n=u(e);return{objectApiName:n,soql:`SELECT COUNT() FROM ${y} WHERE LinkedEntityId IN (SELECT Id FROM ${n})`,scanAll:!1}}function le(e,n){return{objectApiName:u(e),soql:`SELECT ${te.join(", ")} FROM ${y} WHERE LinkedEntityId IN (${oe(n)})`,scanAll:!1}}function fe(e){return{objectApiName:w,soql:`SELECT ${ae.join(", ")} FROM ${w} WHERE Id IN (${oe(e)})`,scanAll:!1}}async function*v(e,n){let t=[];for await(let i of e)t.push(i),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}function*C(e,n){let t=[];for(let i of e)t.push(i),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}function G(e,n,t){let i=e.safeParse(n);if(!i.success)throw new Error(`The org answered a ${t} that does not read as one: ${i.error.message}`);return i.data}function F(e){return e.slice(0,15)}async function xe(e){let{reader:n,folder:t,signal:i}=e,r=e.files??S(O(t.dir)),a=I(t.filesDir,de);await se(a,{recursive:!0,mode:Y});let m=z(t),b=A(t);await r.writeFile(m,""),await r.writeFile(b,"");try{let x=new Map,q=0,H=async d=>{for await(let c of v(_(d),B)){let s=c.map(o=>G(V,o,"link"));for(let o of s)x.has(F(o.ContentDocumentId))||x.set(F(o.ContentDocumentId),o.ContentDocumentId);q+=s.length,await r.appendFile(m,s.map(o=>`${JSON.stringify(o)}
|
|
8
|
+
`).join(""))}await M(d,{force:!0})},K=e.linked.map(d=>({...ce(d),file:I(a,`${u(d)}.links.ndjson`)})),re=await R(n,K,i),$=[];for(let[d,c]of re.entries()){if(c.read){await H(K[d].file);continue}let s=e.linked[d];$.push(s);let o=await P.read(t,e.snapshotId,s),l=0;for(let g of C(C(pe(o),ee),ne)){let f=g.map(k=>({...le(s,k),file:I(a,`${u(s)}.links.${l++}.ndjson`)})),N=(await R(n,f,i)).find(k=>!k.read);if(N&&!N.read)throw new Error(`The links of the files of ${s} could not be read whole: ${c.reason}; read by the ids of its records, ${N.reason}`);for(let k of f)await H(k.file)}}let j=0,U=0,Z=new Set;for(let d of C(C(x.values(),ee),ne)){let c=d.map((l,g)=>({...fe(l),file:I(a,`documents.${g}.ndjson`)})),o=(await R(n,c,i)).find(l=>!l.read);if(o&&!o.read)throw new Error(`The files the links name could not be read by their ids: ${o.reason}`);for(let l of c){for await(let g of v(_(l.file),B)){let f=g.map(p=>({...G(J.omit({anchored:!0}),p,"file"),anchored:!0}));for(let p of f)Z.add(F(p.Id));j+=f.length,U+=f.length,await r.appendFile(b,f.map(p=>`${JSON.stringify(p)}
|
|
9
|
+
`).join(""))}await M(l.file,{force:!0})}}if(e.documentsInSnapshot){let d=await P.read(t,e.snapshotId,w);for await(let c of v(d.records(),B)){let s=c.filter(o=>typeof o.Id=="string"&&!Z.has(F(o.Id))).map(o=>({...G(J.omit({anchored:!0}),ue(o),"file"),anchored:!1}));j+=s.length,s.length>0&&await r.appendFile(b,s.map(o=>`${JSON.stringify(o)}
|
|
10
|
+
`).join(""))}}return{documents:j,links:q,anchored:U,...$.length>0?{readByIds:$}:{}}}finally{await M(a,{recursive:!0,force:!0})}}function*pe(e){for(let n=0;n<e.size;n++)yield e.idAt(n)}function ue(e){return{Id:e.Id,LatestPublishedVersionId:e.LatestPublishedVersionId??null,ContentSize:e.ContentSize??null}}async function*ie(e,n,t,i){if(!await e.exists(n))throw new E("damaged",`The checkpoint\u2019s ${i} are not there`);for await(let r of e.readLines(n)){if(r==="")continue;let a;try{a=JSON.parse(r)}catch{throw new E("damaged",`The checkpoint\u2019s ${i} hold a line that is not JSON`)}let m=t.safeParse(a);if(!m.success)throw new E("damaged",`The checkpoint\u2019s ${i} hold a line that does not parse`);yield m.data}}function $e(e,n=S(O(e.dir))){return ie(n,z(e),V,"file links")}function je(e,n=S(O(e.dir))){return ie(n,A(e),J,"files")}export{ee as a,te as b,V as c,Re as d,Ce as e,Fe as f,Te as g,ce as h,be as i,le as j,xe as k,$e as l,je as m};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{
|
|
7
|
+
import{Oc as c,Pc as l,Rc as d,Sc as m}from"./chunk-DPYTG6DM.mjs";var g=class{transform(n,r){let t=n;for(let o of r)t=p(t,o.type,o.config);return t}transformRecord(n,r){let t=d([{objectApiName:r.objectApiName,transformRules:r.transformRules}]);if(t.length>0)throw new Error(m(t));let o={...n},s=(r.externalIdField??"Id").toLowerCase(),R=a=>{let i=a.toLowerCase();return i!==s&&i!=="id"};for(let a of r.transformRules){let i=a.field?.trim();if(!i)throw new Error(l(c([r])));for(let f of h(o,i))R(f)&&(o[f]=p(o[f],a.type,a.config))}return o}};function h(e,n){let r=n.toLowerCase();return Object.keys(e).filter(t=>t.toLowerCase()===r)}function u(e){return(n,r)=>typeof n=="string"?e(n,r):n}function w(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.trim()==="")return;let n=Number(e);return Number.isNaN(n)?void 0:n}var b={uppercase:u(e=>e.toUpperCase()),lowercase:u(e=>e.toLowerCase()),trim:u(e=>e.trim()),truncate:u((e,n)=>e.slice(0,n.length??e.length)),prefix:u((e,n)=>`${n.prefix??""}${e}`),suffix:u((e,n)=>`${e}${n.suffix??""}`),replace:u((e,n)=>n.search?e.split(n.search).join(n.replace??""):e),regex_replace:u((e,n)=>n.regex?e.replace(y(n.regex),n.replace??""):e),map_value:(e,n)=>{let r=String(e??""),t=n.valueMap??{};return r in t?t[r]:e},default_value:(e,n)=>e==null||e===""?n.defaultValue??"":e,format_date:u((e,n)=>T(e,n.dateFormat??"YYYY-MM-DD")),format_number:(e,n)=>{let r=w(e);if(r===void 0)return e;let t=n.numberFormat??"0";return k(r,t)},custom_formula:(e,n)=>{let r=n.formula??"";return x(e,r)}};function y(e){try{return new RegExp(e,"g")}catch(n){throw new Error(`The pattern "${e}" of a Regex replace rule is no regular expression: `+(n instanceof Error?n.message:String(n)))}}function p(e,n,r){let t=b[n];return t(e,r)}function T(e,n){let r=new Date(e);if(isNaN(r.getTime()))return e;let t=r.getUTCFullYear().toString(),o=(r.getUTCMonth()+1).toString().padStart(2,"0"),s=r.getUTCDate().toString().padStart(2,"0");return n.replace("YYYY",t).replace("MM",o).replace("DD",s)}function k(e,n){let r=n.indexOf(".");if(r===-1)return Math.round(e).toString();let t=n.length-r-1;return e.toFixed(t)}function x(e,n){if(n.includes("VALUE")){let r=w(e);if(r!==void 0){let t=n.replace(/VALUE/g,r.toString());return N(t)??e}}return e}function N(e){let n=e.replace(/\s/g,""),r=/^(-?\d+(?:\.\d+)?)([-+*/])(-?\d+(?:\.\d+)?)$/.exec(n);if(!r)return;let t=Number(r[1]),o=r[2],s=Number(r[3]);switch(o){case"+":return t+s;case"-":return t-s;case"*":return t*s;case"/":return s===0?void 0:t/s;default:return}}export{g as a};
|
|
@@ -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 d}from"./chunk-PPGDAUEQ.mjs";import{a as c}from"./chunk-SU65Z2BA.mjs";import{xc as a,zc as u}from"./chunk-DPYTG6DM.mjs";async function I(t){let e=(await t.query("SELECT Id, IsSandbox FROM Organization LIMIT 1")).records[0];if(typeof e?.Id!="string")throw new Error("The org gave no Organization record: whether it is a sandbox cannot be told.");if(e.IsSandbox===!0)return{id:e.Id,sandbox:!0};try{let r=(await t.query("SELECT OrganizationType FROM Organization LIMIT 1")).records[0]?.OrganizationType;return typeof r=="string"&&r!==""?{id:e.Id,sandbox:!1,edition:r}:{id:e.Id,sandbox:!1}}catch{return{id:e.Id,sandbox:!1}}}function h(t){let n=a({isSandbox:t.sandbox,edition:t.edition});return u(n,t.edition)==="production"}function p(t){let{errorCode:n,statusCode:e}=typeof t=="object"&&t!==null?t:{},o=t instanceof Error?t.message:String(t);return e===403||typeof n=="string"&&/^INSUFFICIENT_ACCESS/.test(n)||/\bINSUFFICIENT_ACCESS/.test(o)||(n==="INVALID_TYPE"||/\bINVALID_TYPE\b/.test(o))&&/\bOrganization\b/.test(o)}function l(t){if(d(t))return"auth";if(c(t))return"network";if(p(t))return"organizationRefused"}function O(t,n,e){let o=n instanceof Error?n.message:String(n);switch(e){case"auth":return`${t} refused the session SandForge holds for it (${o}): reconnect it \u2014 Reconnect on the Organizations page, or "sf org login web --alias ${t}" for a command line \u2014 then try again.`;case"network":return`${t} did not answer (${o}): try again once it answers.`;case"organizationRefused":return`${t} would not show its Organization record (${o}): reading it takes the View Setup and Configuration permission, which the user SandForge connects as lacks: give it to them, or connect as a user who has it.`}}var g=/\/services\/Soap\//,f=/\/services\/data\/v\d+\.\d+\/jobs\/(?:ingest|query)(?:[/?]|$)/,y=/^\/jobs\/(?:ingest|query)(?:[/?]|$)/;function b(t){let n=typeof t=="string"?t:t?.url??"";return f.test(n)||y.test(n)}function S(t){let n=0;if(typeof t.request!="function")return()=>n;let e=t._transport,o=t.request.bind(t);if(t.request=(...r)=>((e===void 0||!b(r[0]))&&n++,o(...r)),e!==void 0){let r=e.httpRequest.bind(e);e.httpRequest=(...i)=>{let s=i[0].url;return(g.test(s)||f.test(s))&&n++,r(...i)}}return()=>n}export{I as a,h as b,p as c,l as d,O as e,S as f};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{o as m}from"./chunk-4JKR4PTZ.mjs";import{H as d,d as w,z as b}from"./chunk-E2YJVSX6.mjs";import{vc as u}from"./chunk-DPYTG6DM.mjs";import{b as R,e as A,k as j,l as p,v as P}from"./chunk-WZQEK4WT.mjs";import{randomBytes as O}from"node:crypto";import{createReadStream as T}from"node:fs";import{appendFile as C,open as $,readFile as D,rename as F,rm as _}from"node:fs/promises";import{join as k}from"node:path";import{createInterface as M}from"node:readline";var U=2e3,a=15,x=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,W=2e3,z="spool.json",h="a rewind";function v(r){return typeof r=="string"&&x.test(r)?r.slice(0,a):void 0}var g=class{bytes=Buffer.alloc(a*1024);flags=new Uint16Array(1024);slots=new Uint32Array(2048);used=0;get size(){return this.used}find(t){let e=this.slots.length-1;for(let s=m(t)&e;;s=s+1&e){let n=this.slots[s];if(n===0)return-1;if(this.holds(n-1,t))return n-1}}holds(t,e){let s=t*a;for(let n=0;n<a;n++)if(this.bytes[s+n]!==e.charCodeAt(n))return!1;return!0}keyAt(t){let e=t*a;return this.bytes.toString("latin1",e,e+a)}place(t,e){let s=this.slots.length-1,n=m(e)&s;for(;this.slots[n]!==0;)n=n+1&s;this.slots[n]=t+1}add(t,e=0){let s=v(t);if(s===void 0)throw new RangeError(`Not a Salesforce id: ${String(t)}`);let n=this.find(s);if(n>=0)return this.flags[n]|=e,!1;if((this.used+1)*2>this.slots.length){let o=this.slots;this.slots=new Uint32Array(o.length*2);for(let i of o)i!==0&&this.place(i-1,this.keyAt(i-1))}if((this.used+1)*a>this.bytes.length){let o=Buffer.alloc(this.bytes.length*2);this.bytes.copy(o),this.bytes=o;let i=new Uint16Array(this.flags.length*2);i.set(this.flags),this.flags=i}return this.bytes.write(s,this.used*a,a,"latin1"),this.flags[this.used]=e,this.place(this.used,s),this.used++,!0}has(t){let e=v(t);return e!==void 0&&this.find(e)>=0}count(t){let e=0;for(let s=0;s<this.used;s++)t(this.flags[s])&&e++;return e}flagsOf(t){let e=v(t);if(e===void 0)return 0;let s=this.find(e);return s<0?0:this.flags[s]}},B=p({version:P(1),objects:j(p({objectApiName:R().min(1),count:A().int().nonnegative()}))});function S(r,t){return k(r,`${u(t)}.ids`)}async function G(r,t){let e=`${r}.${process.pid}-${O(4).toString("hex")}.tmp`,s=await $(e,"wx",w);try{try{await s.writeFile(t,"utf8"),await s.sync()}finally{await s.close()}await F(e,r)}catch(n){throw await _(e,{force:!0}),n}}async function J(r){let t=await $(r,"r+");try{await t.sync()}finally{await t.close()}}async function L(r,t,e=h){for(let{objectApiName:s,count:n}of t)n>0&&await J(S(r,s));return await G(k(r,z),`${JSON.stringify({version:1,objects:t})}
|
|
8
|
+
`),new y(r,t,e)}var I=class{constructor(t,e=h){this.dir=t;this.act=e}dir;act;order=[];counts=new Map;lines=new Map;written=new Set;keys=new g;made=!1;async add(t,e){if(!this.keys.add(e))return!1;let s=this.lines.get(t);return s||(u(t),s=[],this.lines.set(t,s),this.order.push(t)),s.push(e),this.counts.set(t,(this.counts.get(t)??0)+1),s.length>=W&&await this.flush(t),!0}async flush(t){let e=this.lines.get(t)??[];this.made||(await b(this.dir),this.made=!0);let s=!this.written.has(t);e.length===0&&!s||(await C(S(this.dir,t),e.map(n=>`${n}
|
|
9
|
+
`).join(""),{encoding:"utf8",mode:w,flag:s?"w":"a"}),this.written.add(t),this.lines.set(t,[]))}get objects(){return this.order.map(t=>({objectApiName:t,count:this.counts.get(t)??0}))}async finish(t){this.made||(await b(this.dir),this.made=!0);for(let e of this.order)await this.flush(e);return L(this.dir,t?t(this.objects):this.objects,this.act)}},y=class r{constructor(t,e,s=h){this.dir=t;this.objects=e;this.act=s}dir;objects;act;get count(){return this.objects.reduce((t,e)=>t+e.count,0)}static async open(t,e=h){let s;try{s=JSON.parse(await D(k(t,z),"utf8"))}catch{throw new d("damaged",`The list of what ${e} sets out to do is not on this machine.`)}let n=B.safeParse(s);if(!n.success)throw new d("damaged",`The list of what ${e} sets out to do does not read as one.`);for(let{objectApiName:o}of n.data.objects)u(o);return new r(t,n.data.objects,e)}async*pages(t,e=U){let s=this.objects.find(c=>c.objectApiName===t);if(!s||s.count===0)return;let n=()=>new d("damaged",`The ${t} records ${this.act} sets out to act on are not as they were written.`),o=Math.max(1,Math.floor(e)),i=T(S(this.dir,t),{encoding:"utf8"}),f=M({input:i,crlfDelay:1/0}),E=0,l=[];try{for await(let c of f)if(c!==""){if(!x.test(c))throw n();E++,l.push(c),l.length>=o&&(yield l,l=[])}}catch(c){throw c.code==="ENOENT"?n():c}finally{f.close(),i.destroy()}if(E!==s.count)throw n();l.length>0&&(yield l)}},N=class r{constructor(t,e){this.spool=t;this.keys=e}spool;keys;static async of(t,e){return new r(await t.finish(e),t.keys)}static async open(t,e=h){let s=await y.open(t,e),n=new g;for(let{objectApiName:o}of s.objects)for await(let i of s.pages(o))for(let f of i)n.add(f);return new r(s,n)}get objects(){return this.spool.objects}pages(t){return this.spool.pages(t)}has(t){return this.keys.has(t)}};export{U as a,g as b,S as c,L as d,I as e,y as f,N as g};
|
|
@@ -4,6 +4,6 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a as je,b as He}from"./chunk-TYYOBZMU.mjs";import{a as $e,b as be,c as Le,g as Ue}from"./chunk-HS4YRX4J.mjs";import{a as de,b as Ne,c as Fe}from"./chunk-TUACWKIH.mjs";import{a as De}from"./chunk-4TLYUZD5.mjs";import{b as R}from"./chunk-CA5NAXSU.mjs";import{bd as Ce,cd as ce,dc as ae,dd as Ie,gd as ue,hd as Me,id as _e,j as Pe,jd as xe,yb as ve}from"./chunk-TTFDUKUS.mjs";import{b as q,e as Oe,k as B,l as J,v as Re,z as Y}from"./chunk-7EANH5PY.mjs";var Z=class e{static DEFAULT_MAX_PER_ORG=5;static DEFAULT_RECYCLE_INTERVAL=900*1e3;connections=new Map;config;cleanupTimer;recycleTimer;maxPerOrg;recycleIntervalMs;latencySamples=new Map;constructor(t,n){this.config={maxConnections:t?.maxConnections??10,keepAliveInterval:t?.keepAliveInterval??6e4,connectionTimeout:t?.connectionTimeout??3e4,idleTimeout:t?.idleTimeout??3e5},this.maxPerOrg=n?.maxPerOrg??e.DEFAULT_MAX_PER_ORG,this.recycleIntervalMs=n?.recycleIntervalMs??e.DEFAULT_RECYCLE_INTERVAL}acquire(t,n,s){let r=this.connections.get(t);if(r&&r.active)return r.lastUsedAt=Date.now(),r.accessToken=s,r;this.connections.size>=this.config.maxConnections&&this.evictOldest();let o={orgId:t,instanceUrl:n,accessToken:s,createdAt:Date.now(),lastUsedAt:Date.now(),active:!0};return this.connections.set(t,o),o}release(t){let n=this.connections.get(t);n&&(n.lastUsedAt=Date.now())}remove(t){return this.latencySamples.delete(t),this.connections.delete(t)}get(t){return this.connections.get(t)}get size(){return this.connections.size}getConfig(){return{...this.config}}getMaxPerOrg(){return this.maxPerOrg}recordLatency(t,n){if(!Number.isFinite(n)||n<0)return;let s=this.latencySamples.get(t);s||(s=[],this.latencySamples.set(t,s)),s.push(n),s.length>1e3&&s.splice(0,s.length-1e3)}getLatencyMetrics(t){let n=this.latencySamples.get(t);if(!n||n.length===0)return;let s=[...n].sort((u,f)=>u-f),r=s.reduce((u,f)=>u+f,0),o=Math.floor(s.length*.95),a=Math.floor(s.length*.99);return{min:s[0],max:s[s.length-1],avg:Math.round(r/s.length),p95:s[Math.min(o,s.length-1)],p99:s[Math.min(a,s.length-1)],sampleCount:s.length}}getAllLatencyMetrics(){let t=new Map;for(let n of this.latencySamples.keys()){let s=this.getLatencyMetrics(n);s&&t.set(n,s)}return t}cleanupIdle(){let t=Date.now(),n=0;for(let[s,r]of this.connections)t-r.lastUsedAt>this.config.idleTimeout&&(this.connections.delete(s),n++);return n}recycleStale(){let t=Date.now(),n=0;for(let[s,r]of this.connections)t-r.createdAt>this.recycleIntervalMs&&(r.active=!1,this.connections.delete(s),n++);return n}startCleanup(){this.stopCleanup(),this.cleanupTimer=setInterval(()=>this.cleanupIdle(),this.config.keepAliveInterval)}stopCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0)}startRecycling(){this.stopRecycling(),this.recycleTimer=setInterval(()=>this.recycleStale(),this.recycleIntervalMs)}stopRecycling(){this.recycleTimer&&(clearInterval(this.recycleTimer),this.recycleTimer=void 0)}evictOldest(){let t,n=1/0;for(let[s,r]of this.connections)r.lastUsedAt<n&&(n=r.lastUsedAt,t=s);t&&this.connections.delete(t)}dispose(){this.stopCleanup(),this.stopRecycling(),this.connections.clear(),this.latencySamples.clear()}};var K=class{state="closed";failureCount=0;lastFailureTime=0;halfOpenSuccesses=0;halfOpenInFlight=0;config;constructor(t){this.config={failureThreshold:t?.failureThreshold??5,resetTimeout:t?.resetTimeout??6e4,halfOpenRequests:t?.halfOpenRequests??1}}getState(){return this.state==="open"&&this.shouldTransitionToHalfOpen()&&(this.state="half_open",this.halfOpenSuccesses=0),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t==="half_open"?this.halfOpenInFlight<this.config.halfOpenRequests:!1}recordSuccess(){this.state==="half_open"?(this.halfOpenSuccesses++,this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1),this.halfOpenSuccesses>=this.config.halfOpenRequests&&this.reset()):this.failureCount=0}recordFailure(){this.failureCount++,this.lastFailureTime=Date.now(),this.state==="half_open"?this.trip():this.failureCount>=this.config.failureThreshold&&this.trip()}trip(){this.state="open",this.lastFailureTime=Date.now()}reset(){this.state="closed",this.failureCount=0,this.halfOpenSuccesses=0,this.halfOpenInFlight=0}getFailureCount(){return this.failureCount}acquirePermit(){return this.canExecute()?(this.getState()==="half_open"&&this.halfOpenInFlight++,!0):!1}releasePermit(){this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1)}getConfig(){return{...this.config}}shouldTransitionToHalfOpen(){return Date.now()-this.lastFailureTime>=this.config.resetTimeout}};var ze=0;function An(){return ze}async function le(e,t){let n=Ue(e);try{return await t()}finally{ze+=n()}}var L=class extends Error{constructor(n,s,r){super(`${n}: ${r}`);this.code=n;this.orgId=s;this.name="OrgConnectionError"}code;orgId};import{homedir as kt,userInfo as St}from"node:os";var Tt=[/^ELECTRON_.+$/,/^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,/^SNAP(|_.*)$/,/^GDK_PIXBUF_.+$/],qe=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED"];function We(e){return Tt.some(t=>t.test(e))}function fe(e=process.env){let t={};for(let[n,s]of Object.entries(e))We(n)||(t[n]=s);return t.NO_COLOR="1",t}function vn(e=process.env){let t=Object.keys(e).filter(f=>(e[f]??"")!==""),n=qe.filter(f=>t.some(d=>d.toUpperCase()===f)),s=t.filter(f=>/^(SF|SFDX)_/i.test(f)).sort(),r=t.filter(f=>We(f)),o=r.filter(f=>f.startsWith("ELECTRON_")).sort(),a=r.length-o.length,u=r.length===0?"none":[...o,...a>0?[`${a} VSCODE_ or other VS Code variables`]:[]].join(", ");return`set: ${n.length>0?n.join(", "):"none of "+qe.join(", ")}; SF_/SFDX_: ${s.length>0?s.join(", "):"none"}; not passed to sf, as a terminal does not get them: ${u}`}function At(){try{return St().username}catch{return process.env.USERNAME??process.env.USER??""}}function Be(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(e,t=kt(),n=At()){let s=e;return t.length>3&&(s=s.replace(new RegExp(Be(t),"gi"),"~")),n.length>=2&&(s=s.replace(new RegExp(`(?<=[\\\\/])${Be(n)}(?=[\\\\/]|$)`,"gim"),"<user>")),s.replace(/00D\w{12,15}![\w.]+/g,"<token>").replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g,"<username>")}function Cn(e){return e.split(/\r?\n/).map(t=>t.trim()).find(t=>t.length>0)}function Ot(e,t){if(process.platform!=="win32")return e[0];let s=(Object.entries(t).find(([r])=>r.toUpperCase()==="PATHEXT")?.[1]??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);return e.find(r=>{let o=r.lastIndexOf(".");return o>Math.max(r.lastIndexOf("\\"),r.lastIndexOf("/"))&&s.includes(r.slice(o).toLowerCase())})}async function In(e=1e4){let{exec:t}=await import("child_process"),{promisify:n}=await import("util"),s=process.platform==="win32"?"where sf node":"which -a sf node",r=fe(),o,a;try{let h=await n(t)(s,{timeout:e,windowsHide:!0,env:r});o=String(h.stdout)}catch(h){let i=h;o=String(i.stdout??""),o.trim()===""&&(a=Je(i.message??String(h)))}let u=o.split(/\r?\n/).map(h=>h.trim()).filter(h=>h.length>0).map(h=>Je(h)),f=h=>u.filter(i=>new RegExp(`(^|[\\\\/])${h}(\\.[A-Za-z0-9]+)?$`,"i").test(i)),d=f("sf"),c=Ot(d,r);return{sf:d,node:f("node"),...c!==void 0?{runs:c}:{},...a?{failure:a}:{}}}function Q(e,t){let n=(e[t.toLowerCase()]??e[t.toUpperCase()]??"").trim();return n===""?void 0:n}function Rt(e,t){if(t===void 0)return!1;let n=e.hostname.toLowerCase(),s=e.port||(e.protocol==="https:"?"443":"80");return t.split(/[\s,]+/).filter(r=>r!=="").some(r=>{if(r==="*")return!0;let[,o="",a]=/^(.*?)(?::(\d+))?$/.exec(r.toLowerCase())??[];if(a!==void 0&&a!==s)return!1;let u=o.replace(/^\*?\.?/,"");return u!==""&&(n===u||n.endsWith(`.${u}`))})}function Ve(e,t=process.env){let n;try{n=new URL(e)}catch{return}let s=n.protocol==="https:"?Q(t,"https_proxy")??Q(t,"http_proxy"):Q(t,"http_proxy");if(s!==void 0)return Rt(n,Q(t,"no_proxy"))?void 0:s}var Pt="https://login.salesforce.com";async function F(e,t=process.env){let{jsforce:n,HttpProxyTransport:s}=await import("./chunk-L5FGY6YA.mjs"),r=Ve(e.instanceUrl??e.loginUrl??Pt,t),o=new n.Connection({...e,...r!==void 0?{httpProxy:r}:{}});return r===void 0&&(o._transport=new s("")),o}var vt=10*1024*1024,pe=3e4,Ge=pe+2e3,he=`sf did not answer within ${pe/1e3} s \u2014 check the Salesforce CLI`;function Xe(e){return e instanceof Error&&e.message===he}var ge=2e4;function te(e,t,n){let s,r=new Promise((o,a)=>{s=setTimeout(()=>a(new Error(n)),t)});return Promise.race([e,r]).finally(()=>clearTimeout(s))}var U=new Z,Ct=300*1e3,ee=new Map,It={failureThreshold:3,resetTimeout:3e4},Ye=new Map;function Jn(){return U}function Mt(e){let t=Ye.get(e);return t||(t=new K({...It}),Ye.set(e,t)),t}var Ze;var me="panel";function Wn(e){me=e}function _t(e,t=me){return t==="panel"?"Reconnect it on the Organizations page (Try Reconnect on its card).":`Sign in to it again with "sf org login web --alias ${e}" (in a CI job, "sf org login jwt" or "sf org login sfdx-url"), then run the command again, with its --resume if it stopped a run part way.`}function Ke(e=me){return e==="panel"?"Create a new one and import it.":'Create a new one ("sf org create scratch") and give its alias.'}function Qe(e,t){let n=t?.organization_id;if(!(!Ze||typeof n!="string"))try{Ze(e,{organizationId:n})}catch(s){De.warn("Identity observer threw",{orgId:e,error:R(s)})}}var xt="[REDACTED]";function et(e){return typeof e=="string"&&e.length>0&&!e.startsWith(xt)&&!/\s/.test(e)}async function $t(e){if(!/^[\w.@+-]+$/.test(e))throw new Error(`Invalid username format: "${e}"`);let{execFile:t,exec:n}=await import("child_process"),{promisify:s}=await import("util"),r={maxBuffer:vt,timeout:pe,windowsHide:!0,env:fe()},o=i=>te(s(t)("sf",i,r),Ge,he),a=i=>{let g=!1,m,k=new Promise((T,S)=>{m=n(i,r,(E,C)=>{g=!0,E?S(E):T({stdout:C})})});return te(k,Ge,he).catch(T=>{throw!g&&m?.pid!==void 0&&t("taskkill",["/pid",String(m.pid),"/T","/F"],{windowsHide:!0},()=>{}),T})},u=(i,g)=>process.platform==="win32"?a(i):o(g),f=(i,g)=>{let m=i.replace(/\[[0-9;]*m/g,""),k=m.search(/[{[]/);if(k===-1)throw new Error(`Failed to parse "${g}" output: no JSON found. Ensure Salesforce CLI (sf) is installed and the org is authenticated.`);return JSON.parse(m.slice(k)).result??{}},d;try{let{stdout:i}=await u(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),g=f(i,"sf org display");d=typeof g.instanceUrl=="string"?g.instanceUrl:void 0}catch(i){if(Xe(i))throw i;d=void 0}try{let{stdout:i}=await u(`sf org auth show-access-token -o "${e}" --json`,["org","auth","show-access-token","-o",e,"--json"]),g=f(i,"sf org auth show-access-token");if(et(g.accessToken))return{accessToken:g.accessToken,instanceUrl:d}}catch(i){if(Xe(i))throw i}let{stdout:c}=await u(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),h=f(c,"sf org display");if(!et(h.accessToken))throw new Error('Neither "sf org auth show-access-token" nor "sf org display" returned an access token. The org session may have expired \u2014 try re-authenticating with "sf org login".');return!d&&typeof h.instanceUrl=="string"&&(d=h.instanceUrl),{accessToken:h.accessToken,instanceUrl:d}}async function Vn(e,t){return F({instanceUrl:e.instanceUrl,accessToken:e.accessToken??void 0,version:e.version,callOptions:{client:t}})}async function Gn(e){return F({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:e.version})}async function Xn(e,t,n){let s=e,r=n.getOrg(e);if(!r)throw new Error(`Org not found: ${e}`);let o=await t.getCredentials(e);if(!o?.accessToken||!o.instanceUrl)throw new Error(`No credentials for org "${r.alias}" (${e}). Reconnect the org.`);let a=r.metadata.apiVersion||Pe.DEFAULT_API_VERSION,u=U.get(s),f=Date.now()-(ee.get(e)??0)<Ct;if(u&&u.active&&u.accessToken===o.accessToken&&f)return u.lastUsedAt=Date.now(),F({instanceUrl:u.instanceUrl,accessToken:u.accessToken,version:a});let d=await F({instanceUrl:o.instanceUrl,accessToken:o.accessToken,version:a}),c=Mt(e);if(!c.acquirePermit())throw new L("ORG_TEMPORARILY_UNREACHABLE",e,`"${r.alias}" failed several times in a row, so SandForge waits a moment before calling it again. Try again in a minute.`);let h=Date.now(),i=`identity check did not answer within ${ge/1e3} s`;try{let g=await le(d,()=>te(d.identity(),ge,i)),m=Date.now()-h;return c.recordSuccess(),U.acquire(s,o.instanceUrl,o.accessToken),U.recordLatency(s,m),ee.set(e,Date.now()),Qe(e,g),d}catch(g){let m=Date.now()-h;if(U.remove(s),ee.delete(e),$e(g))try{let S=await $t(r.username),E=S.instanceUrl??o.instanceUrl;if(S.accessToken===o.accessToken&&E===o.instanceUrl)throw new Error("sf CLI token store is stale too (same expired token) \u2014 re-authenticate the org");let C=await F({instanceUrl:E,accessToken:S.accessToken,version:a}),W=await le(C,()=>te(C.identity(),ge,i));return await t.saveOrg(r,{...o,accessToken:S.accessToken,instanceUrl:E}),c.recordSuccess(),U.acquire(s,E,S.accessToken),U.recordLatency(s,m),ee.set(e,Date.now()),Qe(e,W),C}catch(S){c.recordFailure();let E=R(S);n.updateStatus(e,"expired");let C=ae(r,new Date().toISOString().slice(0,10));throw C!==void 0?new L("SCRATCH_ORG_EXPIRED",e,`The scratch org "${r.alias}" expired on ${C}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${Ke()} (cause: ${E})`):new L("ORG_AUTH_EXPIRED",e,`The session with "${r.alias}" has expired and could not be renewed. ${_t(r.alias)} (cause: ${E})`)}c.recordFailure();let k=R(g),T=ae(r,new Date().toISOString().slice(0,10));throw T!==void 0?(n.updateStatus(e,"expired"),new L("SCRATCH_ORG_EXPIRED",e,`The scratch org "${r.alias}" expired on ${T}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${Ke()} (cause: ${k})`)):new Error(`Connection failed for "${r.alias}": ${k}`)}finally{c.releasePermit()}}import{randomUUID as bt}from"node:crypto";import{hostname as Lt,homedir as Ut,uptime as Dt}from"node:os";import{mkdir as Nt,readFile as ct,readdir as Ft,rename as ut,writeFile as jt}from"node:fs/promises";import{dirname as we,join as Ee}from"node:path";function tt(e){let t=e,n=typeof t?.errorCode=="string"?t.errorCode:typeof t?.name=="string"?t.name:void 0;return{success:!1,errors:[{...n?{statusCode:n}:{},message:R(e)}]}}function nt(e){return(Array.isArray(e)?e[0]:e)??{success:!1,errors:[{message:"the org answered nothing"}]}}function as(e){return{typeOrg:()=>be(e),query:async t=>({records:(await e.query(t)).records}),identity:async()=>{let t=await e.identity();return{user_id:t.user_id,organization_id:t.organization_id}},createAssignment:async t=>e.sobject("PermissionSetAssignment").create(t,{headers:ve()}).then(nt,tt),deleteAssignment:async t=>e.sobject("PermissionSetAssignment").destroy(t).then(nt,tt)}}var j=class extends Error{constructor(n){super(n.message);this.refusal=n;this.name="MuteRefusedError"}refusal;get code(){return this.refusal.code}};function Ht(e){return e instanceof j||e instanceof Error&&e.name==="MuteRefusedError"&&"refusal"in e}var zt=60,qt=5*6e4,Bt=3e4,Jt=6e4,Wt=200,Vt=448,Gt=384,oe=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,H=q().regex(oe),Xt=J({id:H,permissionSetId:H,permissionSet:q().min(1).max(255)}),Yt=J({runId:q().min(1).max(255),host:q().min(1).max(255),pid:Oe().int().nonnegative(),hostStartedAt:Y.datetime({offset:!0}),acquiredAt:Y.datetime({offset:!0}),endsAt:Y.datetime({offset:!0}),needs:B(H),assigning:B(H),created:B(Xt)}),dt=J({version:Re(1),organizationId:H,userId:H,leases:B(Yt)}),Zt=J(je),Kt=He(e=>{let t=Zt.safeParse(e);return t.success?t.data:void 0});function lt(e=process.env,t=Ut()){let n=e.SANDFORGE_MUTE_LEASES_DIR;return n!==void 0&&n.trim()!==""?n:Ee(t,".sandforge","mute-leases")}function Qt(e,t,n){if(!oe.test(t)||!oe.test(n))throw new Error("A mute lease is journaled under an org id and a user id.");return Ee(e,`${t.slice(0,15)}-${n.slice(0,15)}.json`)}var ft={host:Lt(),pid:de.pid,startedAt:de.startedAt},en=6e4,D=new Set;function gt(e,t,n){return`${e}
|
|
7
|
+
import{a as De}from"./chunk-4TLYUZD5.mjs";import{a as be,b as Le,f as Ue}from"./chunk-SQGP46QS.mjs";import{a as $e}from"./chunk-PPGDAUEQ.mjs";import{a as je,b as He}from"./chunk-PC247GKX.mjs";import{a as de,b as Ne,c as Fe}from"./chunk-TUACWKIH.mjs";import{b as R}from"./chunk-CA5NAXSU.mjs";import{Ec as ae,Ed as Ce,Fd as ce,Gd as Ie,Jd as ue,Kd as Me,Ld as _e,Md as xe,Yb as ve,k as Pe}from"./chunk-DPYTG6DM.mjs";import{b as q,e as Oe,k as B,l as J,v as Re,z as Y}from"./chunk-WZQEK4WT.mjs";var Z=class e{static DEFAULT_MAX_PER_ORG=5;static DEFAULT_RECYCLE_INTERVAL=900*1e3;connections=new Map;config;cleanupTimer;recycleTimer;maxPerOrg;recycleIntervalMs;latencySamples=new Map;constructor(t,n){this.config={maxConnections:t?.maxConnections??10,keepAliveInterval:t?.keepAliveInterval??6e4,connectionTimeout:t?.connectionTimeout??3e4,idleTimeout:t?.idleTimeout??3e5},this.maxPerOrg=n?.maxPerOrg??e.DEFAULT_MAX_PER_ORG,this.recycleIntervalMs=n?.recycleIntervalMs??e.DEFAULT_RECYCLE_INTERVAL}acquire(t,n,s){let r=this.connections.get(t);if(r&&r.active)return r.lastUsedAt=Date.now(),r.accessToken=s,r;this.connections.size>=this.config.maxConnections&&this.evictOldest();let o={orgId:t,instanceUrl:n,accessToken:s,createdAt:Date.now(),lastUsedAt:Date.now(),active:!0};return this.connections.set(t,o),o}release(t){let n=this.connections.get(t);n&&(n.lastUsedAt=Date.now())}remove(t){return this.latencySamples.delete(t),this.connections.delete(t)}get(t){return this.connections.get(t)}get size(){return this.connections.size}getConfig(){return{...this.config}}getMaxPerOrg(){return this.maxPerOrg}recordLatency(t,n){if(!Number.isFinite(n)||n<0)return;let s=this.latencySamples.get(t);s||(s=[],this.latencySamples.set(t,s)),s.push(n),s.length>1e3&&s.splice(0,s.length-1e3)}getLatencyMetrics(t){let n=this.latencySamples.get(t);if(!n||n.length===0)return;let s=[...n].sort((u,f)=>u-f),r=s.reduce((u,f)=>u+f,0),o=Math.floor(s.length*.95),a=Math.floor(s.length*.99);return{min:s[0],max:s[s.length-1],avg:Math.round(r/s.length),p95:s[Math.min(o,s.length-1)],p99:s[Math.min(a,s.length-1)],sampleCount:s.length}}getAllLatencyMetrics(){let t=new Map;for(let n of this.latencySamples.keys()){let s=this.getLatencyMetrics(n);s&&t.set(n,s)}return t}cleanupIdle(){let t=Date.now(),n=0;for(let[s,r]of this.connections)t-r.lastUsedAt>this.config.idleTimeout&&(this.connections.delete(s),n++);return n}recycleStale(){let t=Date.now(),n=0;for(let[s,r]of this.connections)t-r.createdAt>this.recycleIntervalMs&&(r.active=!1,this.connections.delete(s),n++);return n}startCleanup(){this.stopCleanup(),this.cleanupTimer=setInterval(()=>this.cleanupIdle(),this.config.keepAliveInterval)}stopCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0)}startRecycling(){this.stopRecycling(),this.recycleTimer=setInterval(()=>this.recycleStale(),this.recycleIntervalMs)}stopRecycling(){this.recycleTimer&&(clearInterval(this.recycleTimer),this.recycleTimer=void 0)}evictOldest(){let t,n=1/0;for(let[s,r]of this.connections)r.lastUsedAt<n&&(n=r.lastUsedAt,t=s);t&&this.connections.delete(t)}dispose(){this.stopCleanup(),this.stopRecycling(),this.connections.clear(),this.latencySamples.clear()}};var K=class{state="closed";failureCount=0;lastFailureTime=0;halfOpenSuccesses=0;halfOpenInFlight=0;config;constructor(t){this.config={failureThreshold:t?.failureThreshold??5,resetTimeout:t?.resetTimeout??6e4,halfOpenRequests:t?.halfOpenRequests??1}}getState(){return this.state==="open"&&this.shouldTransitionToHalfOpen()&&(this.state="half_open",this.halfOpenSuccesses=0),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t==="half_open"?this.halfOpenInFlight<this.config.halfOpenRequests:!1}recordSuccess(){this.state==="half_open"?(this.halfOpenSuccesses++,this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1),this.halfOpenSuccesses>=this.config.halfOpenRequests&&this.reset()):this.failureCount=0}recordFailure(){this.failureCount++,this.lastFailureTime=Date.now(),this.state==="half_open"?this.trip():this.failureCount>=this.config.failureThreshold&&this.trip()}trip(){this.state="open",this.lastFailureTime=Date.now()}reset(){this.state="closed",this.failureCount=0,this.halfOpenSuccesses=0,this.halfOpenInFlight=0}getFailureCount(){return this.failureCount}acquirePermit(){return this.canExecute()?(this.getState()==="half_open"&&this.halfOpenInFlight++,!0):!1}releasePermit(){this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1)}getConfig(){return{...this.config}}shouldTransitionToHalfOpen(){return Date.now()-this.lastFailureTime>=this.config.resetTimeout}};var ze=0;function An(){return ze}async function le(e,t){let n=Ue(e);try{return await t()}finally{ze+=n()}}var L=class extends Error{constructor(n,s,r){super(`${n}: ${r}`);this.code=n;this.orgId=s;this.name="OrgConnectionError"}code;orgId};import{homedir as kt,userInfo as St}from"node:os";var Tt=[/^ELECTRON_.+$/,/^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,/^SNAP(|_.*)$/,/^GDK_PIXBUF_.+$/],qe=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED"];function We(e){return Tt.some(t=>t.test(e))}function fe(e=process.env){let t={};for(let[n,s]of Object.entries(e))We(n)||(t[n]=s);return t.NO_COLOR="1",t}function vn(e=process.env){let t=Object.keys(e).filter(f=>(e[f]??"")!==""),n=qe.filter(f=>t.some(d=>d.toUpperCase()===f)),s=t.filter(f=>/^(SF|SFDX)_/i.test(f)).sort(),r=t.filter(f=>We(f)),o=r.filter(f=>f.startsWith("ELECTRON_")).sort(),a=r.length-o.length,u=r.length===0?"none":[...o,...a>0?[`${a} VSCODE_ or other VS Code variables`]:[]].join(", ");return`set: ${n.length>0?n.join(", "):"none of "+qe.join(", ")}; SF_/SFDX_: ${s.length>0?s.join(", "):"none"}; not passed to sf, as a terminal does not get them: ${u}`}function At(){try{return St().username}catch{return process.env.USERNAME??process.env.USER??""}}function Be(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(e,t=kt(),n=At()){let s=e;return t.length>3&&(s=s.replace(new RegExp(Be(t),"gi"),"~")),n.length>=2&&(s=s.replace(new RegExp(`(?<=[\\\\/])${Be(n)}(?=[\\\\/]|$)`,"gim"),"<user>")),s.replace(/00D\w{12,15}![\w.]+/g,"<token>").replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g,"<username>")}function Cn(e){return e.split(/\r?\n/).map(t=>t.trim()).find(t=>t.length>0)}function Ot(e,t){if(process.platform!=="win32")return e[0];let s=(Object.entries(t).find(([r])=>r.toUpperCase()==="PATHEXT")?.[1]??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);return e.find(r=>{let o=r.lastIndexOf(".");return o>Math.max(r.lastIndexOf("\\"),r.lastIndexOf("/"))&&s.includes(r.slice(o).toLowerCase())})}async function In(e=1e4){let{exec:t}=await import("child_process"),{promisify:n}=await import("util"),s=process.platform==="win32"?"where sf node":"which -a sf node",r=fe(),o,a;try{let h=await n(t)(s,{timeout:e,windowsHide:!0,env:r});o=String(h.stdout)}catch(h){let i=h;o=String(i.stdout??""),o.trim()===""&&(a=Je(i.message??String(h)))}let u=o.split(/\r?\n/).map(h=>h.trim()).filter(h=>h.length>0).map(h=>Je(h)),f=h=>u.filter(i=>new RegExp(`(^|[\\\\/])${h}(\\.[A-Za-z0-9]+)?$`,"i").test(i)),d=f("sf"),c=Ot(d,r);return{sf:d,node:f("node"),...c!==void 0?{runs:c}:{},...a?{failure:a}:{}}}function Q(e,t){let n=(e[t.toLowerCase()]??e[t.toUpperCase()]??"").trim();return n===""?void 0:n}function Rt(e,t){if(t===void 0)return!1;let n=e.hostname.toLowerCase(),s=e.port||(e.protocol==="https:"?"443":"80");return t.split(/[\s,]+/).filter(r=>r!=="").some(r=>{if(r==="*")return!0;let[,o="",a]=/^(.*?)(?::(\d+))?$/.exec(r.toLowerCase())??[];if(a!==void 0&&a!==s)return!1;let u=o.replace(/^\*?\.?/,"");return u!==""&&(n===u||n.endsWith(`.${u}`))})}function Ve(e,t=process.env){let n;try{n=new URL(e)}catch{return}let s=n.protocol==="https:"?Q(t,"https_proxy")??Q(t,"http_proxy"):Q(t,"http_proxy");if(s!==void 0)return Rt(n,Q(t,"no_proxy"))?void 0:s}var Pt="https://login.salesforce.com";async function F(e,t=process.env){let{jsforce:n,HttpProxyTransport:s}=await import("./chunk-L5FGY6YA.mjs"),r=Ve(e.instanceUrl??e.loginUrl??Pt,t),o=new n.Connection({...e,...r!==void 0?{httpProxy:r}:{}});return r===void 0&&(o._transport=new s("")),o}var vt=10*1024*1024,pe=3e4,Ge=pe+2e3,he=`sf did not answer within ${pe/1e3} s \u2014 check the Salesforce CLI`;function Xe(e){return e instanceof Error&&e.message===he}var ge=2e4;function te(e,t,n){let s,r=new Promise((o,a)=>{s=setTimeout(()=>a(new Error(n)),t)});return Promise.race([e,r]).finally(()=>clearTimeout(s))}var U=new Z,Ct=300*1e3,ee=new Map,It={failureThreshold:3,resetTimeout:3e4},Ye=new Map;function Jn(){return U}function Mt(e){let t=Ye.get(e);return t||(t=new K({...It}),Ye.set(e,t)),t}var Ze;var me="panel";function Wn(e){me=e}function _t(e,t=me){return t==="panel"?"Reconnect it on the Organizations page (Try Reconnect on its card).":`Sign in to it again with "sf org login web --alias ${e}" (in a CI job, "sf org login jwt" or "sf org login sfdx-url"), then run the command again, with its --resume if it stopped a run part way.`}function Ke(e=me){return e==="panel"?"Create a new one and import it.":'Create a new one ("sf org create scratch") and give its alias.'}function Qe(e,t){let n=t?.organization_id;if(!(!Ze||typeof n!="string"))try{Ze(e,{organizationId:n})}catch(s){De.warn("Identity observer threw",{orgId:e,error:R(s)})}}var xt="[REDACTED]";function et(e){return typeof e=="string"&&e.length>0&&!e.startsWith(xt)&&!/\s/.test(e)}async function $t(e){if(!/^[\w.@+-]+$/.test(e))throw new Error(`Invalid username format: "${e}"`);let{execFile:t,exec:n}=await import("child_process"),{promisify:s}=await import("util"),r={maxBuffer:vt,timeout:pe,windowsHide:!0,env:fe()},o=i=>te(s(t)("sf",i,r),Ge,he),a=i=>{let g=!1,m,k=new Promise((T,S)=>{m=n(i,r,(E,C)=>{g=!0,E?S(E):T({stdout:C})})});return te(k,Ge,he).catch(T=>{throw!g&&m?.pid!==void 0&&t("taskkill",["/pid",String(m.pid),"/T","/F"],{windowsHide:!0},()=>{}),T})},u=(i,g)=>process.platform==="win32"?a(i):o(g),f=(i,g)=>{let m=i.replace(/\[[0-9;]*m/g,""),k=m.search(/[{[]/);if(k===-1)throw new Error(`Failed to parse "${g}" output: no JSON found. Ensure Salesforce CLI (sf) is installed and the org is authenticated.`);return JSON.parse(m.slice(k)).result??{}},d;try{let{stdout:i}=await u(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),g=f(i,"sf org display");d=typeof g.instanceUrl=="string"?g.instanceUrl:void 0}catch(i){if(Xe(i))throw i;d=void 0}try{let{stdout:i}=await u(`sf org auth show-access-token -o "${e}" --json`,["org","auth","show-access-token","-o",e,"--json"]),g=f(i,"sf org auth show-access-token");if(et(g.accessToken))return{accessToken:g.accessToken,instanceUrl:d}}catch(i){if(Xe(i))throw i}let{stdout:c}=await u(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),h=f(c,"sf org display");if(!et(h.accessToken))throw new Error('Neither "sf org auth show-access-token" nor "sf org display" returned an access token. The org session may have expired \u2014 try re-authenticating with "sf org login".');return!d&&typeof h.instanceUrl=="string"&&(d=h.instanceUrl),{accessToken:h.accessToken,instanceUrl:d}}async function Vn(e,t){return F({instanceUrl:e.instanceUrl,accessToken:e.accessToken??void 0,version:e.version,callOptions:{client:t}})}async function Gn(e){return F({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:e.version})}async function Xn(e,t,n){let s=e,r=n.getOrg(e);if(!r)throw new Error(`Org not found: ${e}`);let o=await t.getCredentials(e);if(!o?.accessToken||!o.instanceUrl)throw new Error(`No credentials for org "${r.alias}" (${e}). Reconnect the org.`);let a=r.metadata.apiVersion||Pe.DEFAULT_API_VERSION,u=U.get(s),f=Date.now()-(ee.get(e)??0)<Ct;if(u&&u.active&&u.accessToken===o.accessToken&&f)return u.lastUsedAt=Date.now(),F({instanceUrl:u.instanceUrl,accessToken:u.accessToken,version:a});let d=await F({instanceUrl:o.instanceUrl,accessToken:o.accessToken,version:a}),c=Mt(e);if(!c.acquirePermit())throw new L("ORG_TEMPORARILY_UNREACHABLE",e,`"${r.alias}" failed several times in a row, so SandForge waits a moment before calling it again. Try again in a minute.`);let h=Date.now(),i=`identity check did not answer within ${ge/1e3} s`;try{let g=await le(d,()=>te(d.identity(),ge,i)),m=Date.now()-h;return c.recordSuccess(),U.acquire(s,o.instanceUrl,o.accessToken),U.recordLatency(s,m),ee.set(e,Date.now()),Qe(e,g),d}catch(g){let m=Date.now()-h;if(U.remove(s),ee.delete(e),$e(g))try{let S=await $t(r.username),E=S.instanceUrl??o.instanceUrl;if(S.accessToken===o.accessToken&&E===o.instanceUrl)throw new Error("sf CLI token store is stale too (same expired token) \u2014 re-authenticate the org");let C=await F({instanceUrl:E,accessToken:S.accessToken,version:a}),W=await le(C,()=>te(C.identity(),ge,i));return await t.saveOrg(r,{...o,accessToken:S.accessToken,instanceUrl:E}),c.recordSuccess(),U.acquire(s,E,S.accessToken),U.recordLatency(s,m),ee.set(e,Date.now()),Qe(e,W),C}catch(S){c.recordFailure();let E=R(S);n.updateStatus(e,"expired");let C=ae(r,new Date().toISOString().slice(0,10));throw C!==void 0?new L("SCRATCH_ORG_EXPIRED",e,`The scratch org "${r.alias}" expired on ${C}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${Ke()} (cause: ${E})`):new L("ORG_AUTH_EXPIRED",e,`The session with "${r.alias}" has expired and could not be renewed. ${_t(r.alias)} (cause: ${E})`)}c.recordFailure();let k=R(g),T=ae(r,new Date().toISOString().slice(0,10));throw T!==void 0?(n.updateStatus(e,"expired"),new L("SCRATCH_ORG_EXPIRED",e,`The scratch org "${r.alias}" expired on ${T}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${Ke()} (cause: ${k})`)):new Error(`Connection failed for "${r.alias}": ${k}`)}finally{c.releasePermit()}}import{randomUUID as bt}from"node:crypto";import{hostname as Lt,homedir as Ut,uptime as Dt}from"node:os";import{mkdir as Nt,readFile as ct,readdir as Ft,rename as ut,writeFile as jt}from"node:fs/promises";import{dirname as we,join as Ee}from"node:path";function tt(e){let t=e,n=typeof t?.errorCode=="string"?t.errorCode:typeof t?.name=="string"?t.name:void 0;return{success:!1,errors:[{...n?{statusCode:n}:{},message:R(e)}]}}function nt(e){return(Array.isArray(e)?e[0]:e)??{success:!1,errors:[{message:"the org answered nothing"}]}}function as(e){return{typeOrg:()=>be(e),query:async t=>({records:(await e.query(t)).records}),identity:async()=>{let t=await e.identity();return{user_id:t.user_id,organization_id:t.organization_id}},createAssignment:async t=>e.sobject("PermissionSetAssignment").create(t,{headers:ve()}).then(nt,tt),deleteAssignment:async t=>e.sobject("PermissionSetAssignment").destroy(t).then(nt,tt)}}var j=class extends Error{constructor(n){super(n.message);this.refusal=n;this.name="MuteRefusedError"}refusal;get code(){return this.refusal.code}};function Ht(e){return e instanceof j||e instanceof Error&&e.name==="MuteRefusedError"&&"refusal"in e}var zt=60,qt=5*6e4,Bt=3e4,Jt=6e4,Wt=200,Vt=448,Gt=384,oe=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,H=q().regex(oe),Xt=J({id:H,permissionSetId:H,permissionSet:q().min(1).max(255)}),Yt=J({runId:q().min(1).max(255),host:q().min(1).max(255),pid:Oe().int().nonnegative(),hostStartedAt:Y.datetime({offset:!0}),acquiredAt:Y.datetime({offset:!0}),endsAt:Y.datetime({offset:!0}),needs:B(H),assigning:B(H),created:B(Xt)}),dt=J({version:Re(1),organizationId:H,userId:H,leases:B(Yt)}),Zt=J(je),Kt=He(e=>{let t=Zt.safeParse(e);return t.success?t.data:void 0});function lt(e=process.env,t=Ut()){let n=e.SANDFORGE_MUTE_LEASES_DIR;return n!==void 0&&n.trim()!==""?n:Ee(t,".sandforge","mute-leases")}function Qt(e,t,n){if(!oe.test(t)||!oe.test(n))throw new Error("A mute lease is journaled under an org id and a user id.");return Ee(e,`${t.slice(0,15)}-${n.slice(0,15)}.json`)}var ft={host:Lt(),pid:de.pid,startedAt:de.startedAt},en=6e4,D=new Set;function gt(e,t,n){return`${e}
|
|
8
8
|
${t}
|
|
9
9
|
${n}`}function tn(e,t,n,s={}){let r=s.now?.()??Date.now();if(!(Date.parse(e.endsAt)>r)||e.assigning.length>0)return!1;if(e.host!==n.host)return!0;if(e.pid===n.pid&&e.hostStartedAt===n.startedAt)return D.has(gt(t,e.runId,e.acquiredAt));let o=s.bootedAt?.()??Date.now()-Dt()*1e3,a=Date.parse(e.hostStartedAt);return Number.isFinite(a)&&a<o-en?!1:(s.isAlive??Fe)(e.pid)}var nn=e=>new Promise(t=>setTimeout(t,e));function ne(e,t,n){let s=n?.code;return new Error(`The journal of the mute leases in ${we(e)} could not be ${t}${typeof s=="string"?` (${s})`:""}: the user SandForge runs as must read and write that folder, or SANDFORGE_MUTE_LEASES_DIR name another, the same for every run that mutes the org.`)}function sn(e,t){let n=Date.parse(e.acquiredAt);return{pid:e.pid,host:e.host,here:e.host===t.host,until:new Date((Number.isFinite(n)?n:Date.now())+Ne).toISOString()}}function ht(e){return"A run locks it only while it takes, renews or ends a lease of the same org and user, but "+(e.here?`a lock its process could not remove holds until that process has ended, ${e.until} at the latest.`:`a lock a process of another machine could not remove holds until ${e.until}.`)}function rn(e){return`nothing was assigned. ${ht(e)} Run again in a moment, or end process ${e.pid} and run again should none of its runs be muting this org.`}async function se(e,t,n,s,r=rn,o=Jt){let a=n.self??ft,u={self:a,...n.checks?{checks:n.checks}:{}},f=Date.now()+o;for(await Nt(we(e),{recursive:!0,mode:Vt}).catch(d=>{throw ne(e,"made",d)});;){let d;try{d=Kt.acquire(`${e}.lock`,c=>c,u)}catch(c){throw ne(e,"locked",c)}if("lock"in d)try{let c=await on(e,t).catch(i=>{throw ne(e,"read",i)});return await s(c,async i=>{let g=`${e}.${process.pid}-${bt()}.tmp`;try{await jt(g,JSON.stringify(i,null,2),{encoding:"utf8",mode:Gt}),await ut(g,e)}catch(m){throw ne(e,"written",m)}})}finally{d.lock.release()}if(Date.now()>f){let c=sn(d.busy,a);throw new j({code:"MUTE_FAILED",message:`The journal of the mute leases in ${we(e)} stayed locked for a minute by process ${c.pid} on ${c.host}: ${r(c)}`})}await nn(Wt)}}async function on(e,t){let n={version:1,...t,leases:[]},s;try{s=await ct(e,"utf8")}catch(r){if(r.code==="ENOENT")return n;throw r}try{let r=dt.safeParse(JSON.parse(s));if(r.success)return r.data}catch{}return await ut(e,`${e}.${Date.now()}.unreadable`).catch(()=>{}),n}var an=new Set(["ENTITY_IS_DELETED","INVALID_CROSS_REFERENCE_KEY","NOT_FOUND"]);async function re(e,t,n,s){let r=t.leases.filter(c=>c!==n&&s(c)),o=[...n.created],a=new Set,u=n.assigning[0];if(u!==void 0){let c=new Set(t.leases.flatMap(i=>i===n?[]:i.created.map(g=>g.id))),h=await e.query(`SELECT Id, PermissionSetId, PermissionSet.Name FROM PermissionSetAssignment WHERE AssigneeId = '${t.userId}' AND PermissionSetId IN ('${u}')`).then(i=>i.records).catch(()=>[]);for(let i of h){let g=typeof i.Id=="string"?i.Id:void 0,m=typeof i.PermissionSetId=="string"?i.PermissionSetId:void 0;if(!g||!m||c.has(g)||o.some(T=>T.id===g))continue;let k=i.PermissionSet;o.push({id:g,permissionSetId:m,permissionSet:typeof k?.Name=="string"?k.Name:m}),a.add(g)}}let f={removed:[],passed:[],left:[],found:[]};for(let c of o){let h=r.find(m=>m.needs.includes(c.permissionSetId));if(h){h.created.some(m=>m.id===c.id)||h.created.push(c),f.passed.push(c);continue}let i=await e.deleteAssignment(c.id),g=i.errors?.[0]?.statusCode??i.errors?.[0]?.errorCode;i.success||g!==void 0&&an.has(g)?(f.removed.push(c),a.has(c.id)&&f.found.push(c)):f.left.push({...c,why:i.errors?.[0]?.message??g??"the org refused the delete"})}let d=t.leases.indexOf(n);return f.left.length===0?t.leases.splice(d,1):t.leases[d]={...n,endsAt:new Date(0).toISOString(),needs:[],assigning:[],created:f.left.map(({id:c,permissionSetId:h,permissionSet:i})=>({id:c,permissionSetId:h,permissionSet:i}))},f}function N(e){return e.map(t=>t.permissionSet)}function st(e,t){let n=r=>N(r).join(", "),s=[];return e.removed.length>0&&s.push(`What this run had assigned was taken back: ${n(e.removed)}.`),e.passed.length>0&&s.push(`${n(e.passed)} stays assigned for another run that mutes this org as the same user${t?", which takes it back as it ends":""}.`),e.left.length>0&&s.push(`${e.left.map(r=>`${r.permissionSet} (${r.why})`).join(", ")} could not be taken back${t?": the next run that mutes this org takes it back":""}.`),s}function rt(e,t){return`The journal still names this run's lease: this process tries again while it runs, and releases the lease once the journal can be written; the next run that mutes this org from another process releases it at the latest once process ${e} has ended.`+(t?` Until it is released, and before ${t.until}, a run of another process that ends may leave what it holds of ${t.sets.join(", ")} assigned for that lease, which the release takes back.`:"")}function pt(e){let t=e.length===1?"it":"them";return`found assigned to the user the run writes as for a run whose process ended as it assigned ${t}; found by user and set, not by id: had an admin assigned ${t} to that user since, theirs went with ${t}`}async function cn(e,t,n){let s=[];for(let r of[...t.leases])n(r)||s.push(...(await re(e,t,r,n)).found);return s}async function un(e){let t;try{t=(await e.query("SELECT PermissionsAssignPermissionSets, PermissionsManageUsers FROM UserPermissionAccess")).records[0]}catch(n){return`the org would not say whether the user the run writes as may assign permission sets (${R(n)})`}if(!(t?.PermissionsAssignPermissionSets===!0||t?.PermissionsManageUsers===!0))return"the user the run writes as cannot assign permission sets (neither Assign Permission Sets nor Manage Users)"}function ot(e){let t=e.indexOf("__");return t>0&&!e.slice(t+2).includes("__")?{namespace:e.slice(0,t),developerName:e.slice(t+2)}:{namespace:"",developerName:e}}var it=/^[A-Za-z][A-Za-z0-9_]*$/;async function dn(e,t){let s=t.map(ot).filter(a=>it.test(a.developerName)&&(!a.namespace||it.test(a.namespace)));if(s.length===0)return new Map;let r=await e.query("SELECT Id, Name, NamespacePrefix FROM PermissionSet WHERE Name IN ("+[...new Set(s.map(a=>`'${a.developerName}'`))].join(", ")+")"),o=new Map;for(let a of t){let{namespace:u,developerName:f}=ot(a),d=r.records.find(c=>String(c.Name??"").toLowerCase()===f.toLowerCase()&&String(c.NamespacePrefix??"").toLowerCase()===u.toLowerCase());typeof d?.Id=="string"&&o.set(a,d.Id)}return o}async function at(e,t,n){if(n.length===0)return new Map;let s=await e.query(`SELECT Id, PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId = '${t}' AND PermissionSetId IN (${n.map(o=>`'${o}'`).join(", ")})`),r=new Map;for(let o of s.records){let a=o.PermissionSetId,u=o.Id;typeof a=="string"&&typeof u=="string"&&r.set(a,u)}return r}function ye(e,t,n){return{state:t,assigned:[],held:[],permissions:ce(e),silenced:e.silenced.map(s=>({...s})),stillRan:e.stillRuns.map(s=>({...s})),...e.assign.length>0?{alsoLifted:(e.alsoLifts??[]).map(s=>({...s}))}:{},...e.liftsUnread?{liftsUnread:e.liftsUnread.map(s=>({...s}))}:{},...n?{reason:n}:{}}}var mt="nothing found can be muted: no flow, process or workflow rule the run fires has a bypass a permission set of the target holds; the run goes on as without the option";async function ln(e,t,n={}){let s,r;try{let d=await e.typeOrg();s=Le(d),r=d.id}catch(d){return{refused:{code:"MUTE_PRODUCTION",message:`The target did not say what org it is (${R(d)}), and its automation is muted on no org that cannot be told from a production one. Nothing was assigned.`}}}if(s)return{refused:{code:"MUTE_PRODUCTION",message:"The target is a production org: its automation is never muted there, whatever the setting says. Nothing was assigned; run without the option."}};let{plan:o,automation:a,planned:u}=hn(t,n.writes);if(o.assign.length===0)return{plan:o,automation:t,planned:u,acquire:async()=>({outcome:u,release:async()=>u})};let f=await un(e);return f!==void 0?{refused:{code:"MUTE_NO_RIGHT",message:`The target's automation cannot be muted: ${f}. Nothing was assigned: run it without muting the target's automation, or have that user given Assign Permission Sets.`}}:(wt.set(o,await gn(n.dir??lt(),r)),{plan:o,automation:a,planned:u,acquire:d=>pn(e,o,d,n)})}var wt=new WeakMap,fn=/^[A-Za-z0-9]{15}-[A-Za-z0-9]{15}\.json$/;async function gn(e,t){if(!oe.test(t))return 0;let n=`${t.slice(0,15)}-`,s;try{s=await Ft(e)}catch{return 0}let r=0;for(let o of s)if(!(!o.startsWith(n)||!fn.test(o)))try{let a=dt.safeParse(JSON.parse(await ct(Ee(e,o),"utf8")));if(!a.success)continue;for(let u of a.data.leases)r+=(u.assigning.length>0?1:0)+u.created.length}catch{}return r}function hn(e,t){let n=Ce(e,t);return n.assign.length===0?{plan:n,automation:e,planned:ye(n,"nothing",mt)}:{plan:n,automation:Ie(e,ce(n)),planned:ye(n,"planned")}}async function pn(e,t,n,s={}){let r=s.self??ft,o=()=>s.checks?.now?.()??Date.now(),a=s.minutes??zt,u=l=>{throw new j({code:"MUTE_FAILED",message:l})},f=await e.identity().catch(l=>u(`The target would not say who the run writes as (${R(l)}).`)),d={organizationId:f.organization_id,userId:f.user_id},c=Qt(s.dir??lt(),d.organizationId,d.userId),h=t.assign.map(l=>l.permissionSet),i=await dn(e,h).catch(l=>u(`The permission sets to assign could not be read (${R(l)}).`)),g=h.filter(l=>!i.has(l));g.length>0&&u(`The target holds no permission set ${g.join(", ")}: nothing was assigned.`);let m=h.map(l=>i.get(l)),k=new Map(h.map(l=>[i.get(l),l])),T=l=>tn(l,c,r,s.checks),S=new Date(o()).toISOString(),E=gt(c,n,S),C=!1,W=m.map(l=>k.get(l)),yt=s.retryEveryMs??Bt,V,ke=(l,A)=>{if(V!==void 0)return;let p=new Set(l.map(y=>y.id)),O=!1,P=()=>clearInterval(V);V=setInterval(()=>{O||(O=!0,se(c,d,s,async(y,G)=>{let M=y.leases.find(x=>x.runId===n&&x.acquiredAt===S);if(M){M.assigning=[],M.created=[...M.created,...A.filter(b=>!M.created.some(X=>X.id===b.id))].filter(b=>!p.has(b.id));let x=await re(e,y,M,T);for(let b of x.removed)p.add(b.id);await G(y)}P()},void 0,0).catch(()=>{}).finally(()=>{O=!1}))},yt),V.unref?.()},z=await se(c,d,s,async(l,A)=>{let p=N(await cn(e,l,T)),O=await at(e,d.userId,m),P=m.filter(w=>!O.has(w)),y={runId:n,host:r.host,pid:r.pid,hostStartedAt:r.startedAt,acquiredAt:S,endsAt:new Date(o()+a*6e4).toISOString(),needs:m,assigning:[...P],created:[]};l.leases.push(y),D.add(E),await A(l),C=!0;let G=[...y.assigning],M=()=>A(l).then(()=>{G=[...y.assigning]},w=>R(w)),x=async w=>{y.assigning=[];let I=await re(e,l,y,T);D.delete(E);let v=await M();v!==void 0&&ke(I.removed,[...I.passed,...I.left]);let _=v!==void 0&&G.length===0?{sets:W,until:y.endsAt}:void 0,Ae=st(I,v===void 0);return u([w,...v!==void 0&&v!==w?[v]:[],...Ae.length>0?Ae:["Nothing was assigned."],...v!==void 0&&(I.passed.length>0||I.left.length>0||_)?[rt(r.pid,_)]:[],...p.length>0?[`Taking its lease, the run took back ${p.join(", ")}, ${pt(p)}.`]:[]].join(" "))};for(let w of P){let I=await e.createAssignment({AssigneeId:d.userId,PermissionSetId:w});if(y.assigning=y.assigning.filter(_=>_!==w),I.success&&I.id){y.created.push({id:I.id,permissionSetId:w,permissionSet:k.get(w)});let _=await M();if(_!==void 0)return x(_);continue}let v=I.errors?.[0];if((v?.statusCode??v?.errorCode)==="DUPLICATE_VALUE"){let _=await M();if(_!==void 0)return x(_);continue}return x(`${k.get(w)} could not be assigned to the user the run writes as: ${v?.message??v?.statusCode??"the org refused it"}.`)}let b=await at(e,d.userId,m).catch(()=>new Map),X=m.filter(w=>!b.has(w));if(X.length>0)return x(`Read back, the user the run writes as does not hold ${X.map(w=>k.get(w)).join(", ")}.`);let Et=new Set(y.created.map(w=>w.permissionSetId));return{endsAt:y.endsAt,assigned:y.created.map(w=>w.permissionSet),held:m.filter(w=>!Et.has(w)).map(w=>k.get(w)),found:p}}).catch(l=>{if(D.delete(E),Ht(l))throw l;return u(`${R(l)}${C?"":" Nothing was assigned."}`)}),$={...ye(t,"muted"),assigned:z.assigned,held:z.held,leaseEndsAt:z.endsAt,...z.found.length>0?{tookBackOfEnded:z.found}:{}},Se=s.renewEveryMs??qt,ie=Se>0?setInterval(()=>{se(c,d,s,async(l,A)=>{let p=l.leases.find(P=>P.runId===n&&P.acquiredAt===S);if(!p||!D.has(E))return;let O=new Date(o()+a*6e4).toISOString();p.endsAt=O,await A(l),$.leaseEndsAt=O}).catch(()=>{})},Se):void 0;ie?.unref?.();let Te;return{outcome:$,release:()=>(Te??=(async()=>{ie&&clearInterval(ie);let l={};try{await se(c,d,s,async(p,O)=>{let P=p.leases.find(y=>y.runId===n&&y.acquiredAt===S);D.delete(E),P&&(l.done=await re(e,p,P,T),await O(p))},p=>`nothing was taken back. ${ht(p)} Should none of its runs be muting this org, end process ${p.pid}`);let A=l.done?.left??[];return{...$,released:A.length===0,takenBack:N(l.done?.removed??[]),...l.done&&l.done.passed.length>0?{passed:N(l.done.passed)}:{},...A.length>0?{notTakenBack:N(A),reason:`${A.map(p=>`${p.permissionSet} (${p.why})`).join(", ")} could not be taken back: the lease ends at ${$.leaseEndsAt}, and the next run that mutes this org releases it`}:{}}}catch(A){D.delete(E);let p=l.done;if(ke(p?.removed??[],p?[...p.passed,...p.left]:[]),p!==void 0){let O=$.leaseEndsAt,P=O!==void 0&&Date.parse(O)>o()?{sets:W,until:O}:void 0;return{...$,released:!1,takenBack:N(p.removed),notTakenBack:N([...p.passed,...p.left]),reason:[R(A),...st({...p,removed:[]},!1),rt(r.pid,P)].join(" ")}}return{...$,released:!1,takenBack:[],reason:`the assignments could not be taken back (${R(A)}): this process tries again while it runs, and takes them back once it can use the journal; past ${$.leaseEndsAt}, or once process ${r.pid} has ended, the next run that mutes this org releases the lease`}}})(),Te)}}var mn=2,wn=3;function yn(e){return!e||e.assign.length===0?0:mn+wn+2*e.assign.length+(wt.get(e)??0)}function cs(e){let t=yn(e);return t>0?{mute:t}:{}}function En(e){return{state:"nothing",assigned:[],held:[],permissions:[],silenced:[],stillRan:[],reason:`nothing can be muted: ${e}; the run goes on as without the option`}}function us(e){return e?{mutedAutomation:e.muted,...e.plan?{mutePlan:e.plan}:{}}:{}}async function ds(e,t,n={}){if(typeof t.unread=="string")return{automation:void 0,muted:En(`the target's automation could not be read (${t.unread})`)};let s=await ln(await e(),t,n);if("refused"in s)throw new j(s.refused);return{automation:s.automation,...s.plan.assign.length>0?{prepared:s}:{},muted:s.planned,plan:s.plan}}function ls(e){let t=e?.mutedAutomation;return t!==null&&typeof t=="object"?t:void 0}function fs(e,t){let n=[];e.state==="nothing"?n.push(`mute: ${e.reason??mt}`):e.state==="planned"?n.push(`mute: planned, ${e.permissions.length>0?`the permission set(s) holding ${e.permissions.join(", ")}`:"nothing"} for the user it writes as in ${t}, for the run alone; nothing is assigned yet`):n.push(`mute: ${e.assigned.length>0?`assigned ${e.assigned.join(", ")}`:"assigned nothing"}${e.held.length>0?`; ${e.held.join(", ")} held already`:""} to the user the run writes as in ${t}, for the run alone`),e.tookBackOfEnded&&e.tookBackOfEnded.length>0&&n.push(` taken back before the run: ${e.tookBackOfEnded.join(", ")}, `+pt(e.tookBackOfEnded));for(let r of e.silenced)n.push(` silenced: ${ue(r)} (bypass ${r.permission})`);for(let r of e.stillRan)n.push(` still runs: ${ue(r)} (${Me(r.why)})`);for(let r of e.alsoLifted??[])n.push(` also lifts: ${_e(r)}`);for(let r of e.liftsUnread??[])n.push(` ${xe(r)}`);let s=e.takenBack??(e.released===!0?e.assigned:[]);if(s.length>0&&n.push(` taken back: ${s.join(", ")}, as the run ended`),e.passed&&e.passed.length>0&&n.push(` stays assigned: ${e.passed.join(", ")}, for another run that mutes ${t} as the same user, which takes ${e.passed.length===1?"it":"them"} back as it ends`),e.released===!1){let r=e.notTakenBack!==void 0&&e.notTakenBack.length===0;n.push(` ${r?"lease not released":"not taken back"}: ${e.reason??"the assignments stay until the lease ends"}`)}return n}export{An as a,le as b,L as c,fe as d,vn as e,Je as f,Cn as g,In as h,Ve as i,F as j,te as k,Jn as l,Wn as m,et as n,$t as o,Vn as p,Gn as q,Xn as r,as as s,Ht as t,ln as u,hn as v,yn as w,cs as x,us as y,ds as z,ls as A,fs as B};
|
|
@@ -4,6 +4,6 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{g as A,k as S}from"./chunk-
|
|
7
|
+
import{g as A,k as S}from"./chunk-5WGA5CZB.mjs";import{e as k,f as w}from"./chunk-NWVVCZUK.mjs";import{tb as T,ub as h}from"./chunk-DPYTG6DM.mjs";import{mkdir as v,rename as D,writeFile as x}from"node:fs/promises";import*as f from"node:path";var y="CaseId",O=80;function $(e){let t=T.safeParse(e.choice);if(!t.success)return{ok:!1,refusals:t.error.issues.map(a=>({code:"choice-invalid",name:a.path.join("."),message:a.message}))};let n=t.data,s=A(e.catalog,n.agent);if(!s)return{ok:!1,refusals:[{code:"agent-absent",name:n.agent,message:`"${n.agent}" is not one of this org's agents`}]};let r=P(n,s,E(e.compiled.tests));if(r.length>0)return{ok:!1,refusals:r};let i=new Map(n.topics.map(a=>[a.packTopic,a])),c=S(s,y)?y:void 0,g=[],o=[];for(let a of e.compiled.tests){if(a.topicKey===null){if(n.guardTopic===null){o.push({test:a.key,reason:"no-guard-topic",message:`"${a.utterance}" is on no topic of the scenario, and no topic of the agent is chosen to decline it: the test is left out`});continue}g.push({key:a.key,utterance:a.utterance,expectedTopic:n.guardTopic,expectedActions:[],expectedOutcome:a.expectedOutcome,contextVariables:[]});continue}let u=i.get(a.topicKey),p=[];if(a.openCase){let m=e.openCaseIds[a.openCase.caseKey];if(m===void 0){o.push({test:a.key,reason:"case-not-written",message:`The case ${a.openCase.caseKey} the test is about was not written by the run: the test is left out`});continue}c!==void 0&&p.push({name:c,value:m})}g.push({key:a.key,utterance:a.utterance,expectedTopic:u.agentTopic,expectedActions:[...u.actions],expectedOutcome:j(a),contextVariables:p})}return g.length===0?{ok:!1,refusals:[{code:"no-test-left",name:e.compiled.packId,message:"No test of the scenario is left to write: "+o.map(a=>a.message).join("; ")}]}:{ok:!0,spec:{name:M(e.compiled.template.name),description:F(e.compiled.packId,e.compiled.seed,e.runId),subjectName:s.name,testCases:g},choice:n,leftOut:o,...c!==void 0?{contextVariable:c}:{}}}function E(e){return[...new Set(e.flatMap(t=>t.topicKey===null?[]:[t.topicKey]))]}function P(e,t,n){let s=[],r=new Map(t.topics.map(o=>[o.name,o])),i=new Set(t.topics.flatMap(o=>o.actions.map(a=>a.name))),c=o=>({code:"topic-absent",name:o,message:`"${o}" is not a topic of the agent ${t.name}`});for(let o of e.topics){n.includes(o.packTopic)||s.push({code:"pack-topic-unknown",name:o.packTopic,message:`"${o.packTopic}" is not a topic of the scenario`});let a=r.get(o.agentTopic);if(!a){s.push(c(o.agentTopic));continue}let u=new Set(a.actions.map(p=>p.name));for(let p of o.actions)u.has(p)||s.push(i.has(p)?{code:"action-not-of-topic",name:p,message:`"${p}" is not an action of the topic ${a.name}, which the agent answers "${o.packTopic}" from`}:{code:"action-absent",name:p,message:`"${p}" is not an action of the agent ${t.name}`})}let g=new Set(e.topics.map(o=>o.packTopic));for(let o of n)g.has(o)||s.push({code:"pack-topic-unmatched",name:o,message:`The topic "${o}" of the scenario is matched to no topic of the agent`});return e.guardTopic!==null&&!r.has(e.guardTopic)&&s.push(c(e.guardTopic)),s}function j(e){if(!e.article)return e.expectedOutcome;let t=e.article.facts.length>0?`, which states: ${e.article.facts.join("; ")}`:"";return`${e.expectedOutcome} The answer draws on the article "${e.article.title}"${t}.`}function M(e){let t=" (SandForge)",n=O-t.length;return`${e.length>n?e.slice(0,n).trimEnd():e}${t}`}function F(e,t,n){let s=n!==void 0?`, written by the seed run ${n}`:"";return`SandForge scenario ${e}, seed ${t}${s}. Its cases are about the records that run wrote: once it is removed, they are about none.`}var C="specs",L=80,V=10;function K(e,t){return G(h(e,t))}function W(e,t,n){let s=n==="agentforce-studio"?"ngtTestSpec":"testSpec";return`${b(e)}-${b(t)}-sandforge-${s}.yaml`}function z(e,t){let n=c=>c.replace(/[^A-Za-z0-9]+/g,"_").replace(/^_+|_+$/g,""),s=`${n(t)}_SandForge`,r=n(e);/^[A-Za-z]/.test(r)||(r=`Agent_${r}`.replace(/_+$/,""));let i=L-s.length-1;return r=r.slice(0,i).replace(/_+$/,""),`${r}_${s}`}function Z(e){let t=e.runner==="agentforce-studio"?["--test-runner","agentforce-studio"]:[],n=["sf","agent","test","create","--spec",e.specPath,"--api-name",e.apiName,...t,"-o",e.alias],s=["sf","agent","test","run","--api-name",e.apiName,"--wait",String(V),...t,"-o",e.alias];return{create:{argv:n,line:R(n)},run:{argv:s,line:R(s)}}}function te(){return{mkdir:async e=>{await v(e,{recursive:!0})},writeNew:async(e,t)=>{try{return await x(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}},replace:async(e,t)=>{let n=`${e}.${process.pid}.tmp`;await x(n,t,"utf8"),await D(n,e)}}}async function X(e,t){let n=W(t.model.subjectName,t.packId,t.runner),s=`${C}/${n}`,r=f.join(t.projectDir,C,n),i=K(t.model,t.runner);if(await e.mkdir(f.dirname(r)),t.overwrite===!0)await e.replace(r,i);else if(!await e.writeNew(r,i))return{kind:"exists",path:r,specPath:s};let c=z(t.model.subjectName,t.packId);return{kind:"written",path:r,specPath:s,apiName:c,commands:Z({specPath:s,apiName:c,alias:t.alias,runner:t.runner})}}async function ne(e,t){let n=w(t.sidecar,t.pack);if(!n.ok)return{kind:"refused",refusals:[{code:"pack-changed",name:t.pack.id,message:n.message}]};let s=$({compiled:n.compiled,catalog:t.catalog,choice:t.choice,openCaseIds:t.sidecar.openCases,runId:t.sidecar.runId});if(!s.ok)return{kind:"refused",refusals:s.refusals};let{choice:r}=s,i=await X(e,{projectDir:t.projectDir,model:s.spec,runner:r.runner,packId:t.pack.id,alias:t.alias,...t.overwrite!==void 0?{overwrite:t.overwrite}:{}});return i.kind==="exists"?i:{...i,leftOut:s.leftOut,sidecar:k(t.sidecar,r)}}function G(e){return`${l(e,0).join(`
|
|
8
8
|
`)}
|
|
9
9
|
`}function l(e,t){let n=" ".repeat(t),s=[];for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let c=`${n}${J(r)}:`;Array.isArray(i)?i.length===0?s.push(`${c} []`):s.push(c,...I(i,t+2)):d(i)?Object.values(i).every(g=>g===void 0)?s.push(`${c} {}`):s.push(c,...l(i,t+2)):s.push(`${c} ${_(i)}`)}return s}function I(e,t){let n=" ".repeat(t),s=[];for(let r of e){let i=Array.isArray(r)?r.length===0?void 0:I(r,t+2):d(r)&&Object.values(r).some(c=>c!==void 0)?l(r,t+2):void 0;if(i===void 0){s.push(`${n}- ${Array.isArray(r)?"[]":d(r)?"{}":_(r)}`);continue}s.push(`${n}- ${i[0].slice(t+2)}`,...i.slice(1))}return s}function d(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function J(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)?e:N(e)}function _(e){if(typeof e=="string")return N(e);if(typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return String(e);if(e===null)return"null";throw new TypeError(`No YAML scalar for ${typeof e}`)}function N(e){return JSON.stringify(e).replace(/[\u007f-\u009f\u2028\u2029\ufeff\ufffe\uffff]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function b(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}function R(e){return e.map(t=>/^[A-Za-z0-9_./:@=+,-]+$/.test(t)?t:`"${t.replace(/(["\\])/g,"\\$1")}"`).join(" ")}export{C as a,V as b,K as c,W as d,z as e,Z as f,te as g,X as h,ne as i,G as j};
|
|
@@ -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{$ as g,Aa as H,Ba as I,Ca as J,Da as K,Ea as L,Fa as M,Ga as N,Ha as O,Ia as P,Ja as Q,Ka as R,V as a,W as b,X as c,Y as d,Z as e,_ as f,aa as h,ba as i,ca as j,da as k,ea as l,fa as m,ga as n,ha as o,ia as p,ja as q,ka as r,la as s,ma as t,na as u,oa as v,pa as w,qa as x,ra as y,sa as z,ta as A,ua as B,va as C,wa as D,xa as E,ya as F,za as G}from"./chunk-KOQV4WXC.mjs";import"./chunk-CULAOP3U.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-KRNFVAGC.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-2OIRJEYE.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-55LQD3Y3.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-3B5H24ZG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-EAFLDSQ2.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-DPYTG6DM.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{m as ASSIGNMENT_RULES_SOQL,h as AUTOMATION_READ_MOST,b as CONDITIONS_BOUND,f as CONDITION_REQUESTS_BOUND,c as DEFINITIONS_BOUND,g as DEFINITION_REQUESTS_BOUND,n as DUPLICATE_RULES_SOQL,i as FLOWS_SOQL,k as PROCESSES_SOQL,d as TOOLING_QUERIES_PER_REQUEST,e as TOOLING_RETRIEVES_PER_REQUEST,j as TRIGGERS_SOQL,N as TargetAutomationReader,o as USER_PERMISSIONS_SOQL,l as WORKFLOW_RULES_SOQL,a as answerOf,R as automationLines,p as conditionSoql,z as customObjectIdsSoql,Q as customPermissionsByIdSoql,A as customPermissionsSoql,G as decisionChecks,F as fieldsRequiredFilled,L as inFlight,H as messagesOf,M as objectsTheRunWrites,I as pathsOf,J as permissionKey,C as permissionSetSizesSoql,B as permissionSetsHoldingSoql,D as permissionsNamed,y as processObjectsSoql,O as readBypassGrants,w as readInComposites,x as ruleDefinitionSoql,P as setCustomPermissionsSoql,E as switchesNamed,v as targetAutomationQueries,s as toolingAnswersOf,q as toolingCompositeBody,t as toolingRecordsOf,r as toolingRetrieveBody,u as toolingRetrievesOver,K as unreadPartOf};
|
|
@@ -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{c as E}from"./chunk-K2FBZIXY.mjs";import{b as S}from"./chunk-T63U4OZJ.mjs";import{h as N}from"./chunk-TZE3Y7IQ.mjs";import{b as h,e as m,k as y,l as b}from"./chunk-7EANH5PY.mjs";var z={kind:"master"};function w(i){return i.available&&i.active&&!i.master}function B(i){let t=i.find(n=>n.defaultRecordTypeMapping);if(t&&w(t))return{kind:"given",info:t,basis:"userDefault"};let e=i.filter(w);return e.length===1?{kind:"given",info:e[0],basis:"onlyOneOpen"}:z}function ie(i){if(i.kind!=="master")return{developerName:i.info.developerName,label:i.info.name,basis:i.basis}}var L=200,j=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/;function se(i,t){let e=t.filter(n=>j.test(n)).slice(0,L).map(n=>`'${n}'`);return`SELECT RecordTypeId, COUNT(Id) n FROM ${N(i)} WHERE Id IN (${e.join(", ")}) GROUP BY RecordTypeId`}var U=b({RecordTypeId:h().nullish(),n:m().int().nonnegative()});function oe(i,t){let e=y(U).safeParse(i);if(!e.success)return{read:0,types:[],unread:"the org answered rows that name no record type count"};let n=new Map;for(let{RecordTypeId:s,n:o}of e.data){let a=K(s??null,t),d=n.get(a.developerName);d?d.rows+=o:n.set(a.developerName,{...a,rows:o})}let r=[...n.values()].sort((s,o)=>o.rows-s.rows);return{read:r.reduce((s,o)=>s+o.rows,0),types:r}}function K(i,t){if(i===null||E(i)){let n=t.find(r=>r.master);return{developerName:n?.developerName??"Master",label:n?.name??"Master"}}let e=t.find(n=>n.recordTypeId.slice(0,15)===i.slice(0,15));return e?{developerName:e.developerName,label:e.name}:{developerName:i,label:i}}function ae(i){if(!i)return;let t=B(i);return t.kind==="given"?t.info.recordTypeId:i.find(e=>e.master)?.recordTypeId}function fe(i){if(typeof i!="object"||i===null)return!1;let{errorCode:t,name:e}=i;return t==="NOT_FOUND"||e==="NOT_FOUND"}import{createHash as R,createHmac as T}from"node:crypto";var p="SANDFORGE_FROZEN_SALT",me=["keep","clear","firstName","lastName","companyName","phoneE164","email","registrationSIV","contractNumber","postalCodeGeneralize","dateMonthStart","dateShift","geoRound1","kmRound10"],f=class extends Error{constructor(){super(`No pseudonymization salt. In VS Code, the first extraction makes one and keeps it in the editor's secret storage, which could not keep it here. On the command line, give it with --salt-file <file>, or set ${p} (bash or zsh: export ${p}="<salt>"; PowerShell: $env:${p} = "<salt>") and start VS Code from that shell. Use the salt the dataset was built with: another one gives the same records other pseudonyms.`),this.name="MissingSaltError"}},V=["Alix","Camille","Dominique","\xC9loi","Faustine","Gabin","H\xE9lo\xEFse","Ibrahim","Jasmine","Kylian","L\xE9a","Mathis","Nour","Oc\xE9ane","Paul","Quitterie","Rayan","Salom\xE9","Th\xE9o","Ursule","Victor","Wendy","Xavier","Yasmine","Zacharie","Ambre","Bastien","Chlo\xE9","Dorian","Emma","Fabien","Gabrielle","Hugo","In\xE8s","Jules","Klara","Louis","Manon","No\xE9","Oph\xE9lie"],H=["Arnaud","Berthelot","Chevallier","Deschamps","Etcheverry","Fontaine","Guibert","Hamonic","Imbert","Jacquin","Kermarrec","Lefebvre","Mignard","Noirot","Ollivier","Perrin","Quentin","Rochefort","Seguin","Thibault","Uberti","Vasseur","Wagner","Xuereb","Yverneau","Zimmermann","Aubry","Barbier","Charpentier","Delattre","Esnault","Fournier","Gosselin","Hervieux","Leloup","Marchand","Navarro","Pasquier","Renard","Sauvage"],v=["Aster","Boreal","C\xE9drat","Delta","Ellipse","Fulmen","Granit","Halcyon","Isatis","Jaspe","Kelvin","Lumen","M\xE9ridien","Noroit","Obsidienne","Pulsar"],k=["Conseil","Services","Industries","Solutions","Groupe","SAS","Partenaires","Logistique"],$="ABCDEFGHJKLMNPRSTUVWXYZ",x=/^(\d{4})-(\d{2})-(\d{2})$/,A=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{1,3})?(Z|[+-]\d{2}:?\d{2})$/;function Z(i){return Date.parse(i.replace(/([+-]\d{2})(\d{2})$/,"$1:$2"))}var D=864e5,u=class{salt;constructor(t){if(!t)throw new f;this.salt=t}get saltFingerprint(){return R("sha256").update(this.salt).digest("hex").slice(0,12)}get dateShiftDays(){return 200+R("sha256").update(`${this.salt}|dateShift-offset`).digest().readUInt32BE(0)%201}pseudonymize(t,e){if(e==null)return e;switch(t){case"keep":return e;case"clear":return"";case"firstName":return this.pick(t,String(e),V);case"lastName":return this.pick(t,String(e),H);case"companyName":return this.companyName(String(e));case"phoneE164":return this.phoneE164(String(e));case"email":return this.email(String(e));case"registrationSIV":return this.registrationSIV(String(e));case"contractNumber":return this.contractNumber(String(e));case"postalCodeGeneralize":return this.postalCodeGeneralize(String(e));case"dateMonthStart":return this.dateMonthStart(String(e));case"dateShift":return this.dateShift(e);case"geoRound1":return this.roundNumber(e,1);case"kmRound10":return this.roundTo(e,10)}}digest(t,e){return T("sha256",this.salt).update(`${t}|${e}`).digest()}*bytes(t,e){let n=this.digest(t,e),r=0;for(;;){for(let s of n)yield s;r+=1,n=T("sha256",this.salt).update(`${t}|${e}|#${r}`).digest()}}pick(t,e,n){let r=this.digest(t,e);return n[r.readUInt32BE(0)%n.length]}companyName(t){let e=this.digest("companyName",t),n=v[e.readUInt32BE(0)%v.length],r=k[e.readUInt32BE(4)%k.length];return`${n} ${r}`}phoneE164(t){let e=this.bytes("phoneE164",t),n="";for(let r=0;r<4;r++)n+=String(e.next().value%10);return`+3363998${n}`}email(t){return`user-${this.digest("email",t).subarray(0,4).toString("hex")}@example.invalid`}registrationSIV(t){let e=this.bytes("registrationSIV",t),n=()=>$[e.next().value%$.length],r=()=>String(e.next().value%10);return`${n()}${n()}-${r()}${r()}${r()}-${n()}${n()}`}contractNumber(t){let e=this.bytes("contractNumber",t),n="";for(let r of t)r>="0"&&r<="9"?n+=String(e.next().value%10):r>="A"&&r<="Z"?n+=String.fromCharCode(65+e.next().value%26):r>="a"&&r<="z"?n+=String.fromCharCode(97+e.next().value%26):n+=r;return n}postalCodeGeneralize(t){let e=t.trim();if(e.length<=2)return e;if(/^\d+$/.test(e))return e.slice(0,2)+"0".repeat(e.length-2);let n=e.slice(0,2);for(let r of e.slice(2))r>="0"&&r<="9"?n+="0":r>="A"&&r<="Z"||r>="a"&&r<="z"?n+="X":n+=r;return n}dateMonthStart(t){let e=x.exec(t)??A.exec(t);return e?`${e[1]}-${e[2]}-01`:""}dateShift(t){if(typeof t=="string"&&x.test(t))return new Date(Date.parse(`${t}T00:00:00Z`)-this.dateShiftDays*D).toISOString().slice(0,10);if(typeof t=="string"&&A.test(t)){let e=Z(t);if(Number.isFinite(e))return new Date(e-this.dateShiftDays*D).toISOString()}return""}roundNumber(t,e){let n=typeof t=="number"?t:Number(String(t).trim());if(!Number.isFinite(n))return"";let r=10**e,s=Math.round(n*r)/r;return typeof t=="number"?s:String(s)}roundTo(t,e){let n=typeof t=="number"?t:Number(String(t).trim());if(!Number.isFinite(n))return"";let r=Math.round(n/e)*e;return typeof t=="number"?r:String(r)}};import{createHash as Y,randomBytes as X}from"node:crypto";var G=80,W=40,F=1e4,q=64,I=".invalid",g=/\.invalid$/i,C=/[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+/g,J=/\+?(?<!\d)\d(?:[\s.()/-]{0,2}\d){6,}/g;function M(i){return/^(?:(?:00)?330?|0)63998\d{4}$/.test(i.replace(/\D/g,""))}function O(i){return`+3363998${i.replace(/\D/g,"").slice(-4)}`}var Q=/^[\d\s.()/+-]+$/;function _(i,t){if(!Q.test(i))return null;let e=t.slice(3),n=/^[\s(]*\+/.test(i)?[`33${e}`,`330${e}`]:[`0${e}`,`33${e}`,`330${e}`,`0033${e}`,`00330${e}`],r=i.replace(/\D/g,"").length,s=n.find(a=>a.length===r);if(s===void 0)return null;let o=0;return i.replace(/\d/g,()=>s[o++])}function ee(i,t={}){let e=[];for(let n of i){let r=(n.type??"").toLowerCase(),s=S(n.name,r);if(!s)continue;let o=r==="email"||r==="phone",a=r==="email"?G:r==="phone"?W:0,d=n.length!==void 0&&n.length>0?n.length:a;e.push({name:t[n.name]??n.name,kind:s,typed:o,...d>0?{maxLength:d}:{},...n.externalId===!0?{key:!0}:{}})}return e}var P=class{pseudonymizer;upsertKeys;drawnFor=new Map;taken=new Set;exhausted=0;counted=new Map;constructor(t=X(32).toString("hex"),e={}){this.pseudonymizer=new u(t),this.upsertKeys=e.upsertKeys===!0}forObject(t,e,n={}){let r=ee(e,n);if(r.length!==0)return s=>{for(let o of r){let a=s[o.name];if(typeof a!="string")continue;let d=this.neutralize(o,a);d!==a&&(d===null?delete s[o.name]:s[o.name]=d,this.count(t,o))}}}email(t,e=G,n=!1){let r=t.trim();if(r===""||g.test(r))return t;let s=`${r}${I}`;if(s.length<=e)return s;let o=this.shortAddress(r,n);return o.length<=e?o:null}phone(t,e){return/\d/.test(t)?M(t)?(this.taken.add(O(t)),t):this.fictional(t,e):t}report(){let t=[],e=0;for(let[n,r]of this.counted)for(let[s,{kind:o,values:a}]of r)t.push({objectApiName:n,field:s,kind:o,values:a}),e+=a;return{neutralized:!0,fields:t,values:e,...this.exhausted>0?{numbersExhausted:this.exhausted}:{}}}neutralize(t,e){let n=this.upsertKeys&&t.key===!0;return t.typed?t.kind==="email"?this.email(e,t.maxLength,n):this.phone(e,t.maxLength):t.kind==="email"?this.addressesIn(e,t.maxLength,n):this.numbersIn(e,t.maxLength)}addressesIn(t,e,n=!1){let r=a=>e===void 0||a.length<=e,s=t.replace(C,a=>g.test(a)?a:`${a}${I}`);if(s===t||r(s))return s;let o=t.replace(C,a=>g.test(a)?a:this.shortAddress(a,n));return r(o)?o:null}numbersIn(t,e){let n=d=>e===void 0||d.length<=e,r=!1,s=d=>t.replace(J,c=>{if(M(c))return this.taken.add(O(c)),c;let l=this.drawnNumber(c);return l===null?(r=!0,c):_(c,l)??(d?`0${l.slice(3)}`:l)}),o=s(!1);if(r)return null;if(o===t||n(o))return o;let a=s(!0);return n(a)?a:null}fictional(t,e){let n=this.drawnNumber(t);if(n===null)return null;let r=_(t,n);if(r!==null&&(e===void 0||r.length<=e))return r;if(e===void 0||n.length<=e)return n;let s=`0${n.slice(3)}`;return s.length<=e?s:null}drawnNumber(t){let e=t.replace(/[^\d+]/g,""),n=this.drawnFor.get(e);if(n!==void 0)return n;if(this.taken.size>=F)return this.exhausted+=1,null;let r=o=>String(this.pseudonymizer.pseudonymize("phoneE164",o)),s=r(e);for(let o=1;this.taken.has(s)&&o<=q;o+=1)s=r(`${e}#${o}`);for(let o=Number(s.slice(-4));this.taken.has(s);)o=(o+1)%F,s=`+3363998${String(o).padStart(4,"0")}`;return this.drawnFor.set(e,s),this.taken.add(s),s}shortAddress(t,e=!1){let n=t.toLowerCase();return e?`user-${Y("sha256").update(n).digest("hex").slice(0,16)}@example.invalid`:String(this.pseudonymizer.pseudonymize("email",n))}count(t,e){let n=this.counted.get(t)??new Map,r=n.get(e.name)??{kind:e.kind,values:0};r.values+=1,n.set(e.name,r),this.counted.set(t,n)}};export{p as a,me as b,f as c,u as d,G as e,F as f,ee as g,P as h,B as i,ie as j,L as k,se as l,oe as m,ae as n,fe as o};
|
|
7
|
+
import{c as E}from"./chunk-BWWQXU2B.mjs";import{b as S}from"./chunk-T63U4OZJ.mjs";import{h as N}from"./chunk-TZE3Y7IQ.mjs";import{b as h,e as m,k as y,l as b}from"./chunk-WZQEK4WT.mjs";var z={kind:"master"};function w(i){return i.available&&i.active&&!i.master}function B(i){let t=i.find(n=>n.defaultRecordTypeMapping);if(t&&w(t))return{kind:"given",info:t,basis:"userDefault"};let e=i.filter(w);return e.length===1?{kind:"given",info:e[0],basis:"onlyOneOpen"}:z}function ie(i){if(i.kind!=="master")return{developerName:i.info.developerName,label:i.info.name,basis:i.basis}}var L=200,j=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/;function se(i,t){let e=t.filter(n=>j.test(n)).slice(0,L).map(n=>`'${n}'`);return`SELECT RecordTypeId, COUNT(Id) n FROM ${N(i)} WHERE Id IN (${e.join(", ")}) GROUP BY RecordTypeId`}var U=b({RecordTypeId:h().nullish(),n:m().int().nonnegative()});function oe(i,t){let e=y(U).safeParse(i);if(!e.success)return{read:0,types:[],unread:"the org answered rows that name no record type count"};let n=new Map;for(let{RecordTypeId:s,n:o}of e.data){let a=K(s??null,t),d=n.get(a.developerName);d?d.rows+=o:n.set(a.developerName,{...a,rows:o})}let r=[...n.values()].sort((s,o)=>o.rows-s.rows);return{read:r.reduce((s,o)=>s+o.rows,0),types:r}}function K(i,t){if(i===null||E(i)){let n=t.find(r=>r.master);return{developerName:n?.developerName??"Master",label:n?.name??"Master"}}let e=t.find(n=>n.recordTypeId.slice(0,15)===i.slice(0,15));return e?{developerName:e.developerName,label:e.name}:{developerName:i,label:i}}function ae(i){if(!i)return;let t=B(i);return t.kind==="given"?t.info.recordTypeId:i.find(e=>e.master)?.recordTypeId}function fe(i){if(typeof i!="object"||i===null)return!1;let{errorCode:t,name:e}=i;return t==="NOT_FOUND"||e==="NOT_FOUND"}import{createHash as R,createHmac as T}from"node:crypto";var p="SANDFORGE_FROZEN_SALT",me=["keep","clear","firstName","lastName","companyName","phoneE164","email","registrationSIV","contractNumber","postalCodeGeneralize","dateMonthStart","dateShift","geoRound1","kmRound10"],f=class extends Error{constructor(){super(`No pseudonymization salt. In VS Code, the first extraction makes one and keeps it in the editor's secret storage, which could not keep it here. On the command line, give it with --salt-file <file>, or set ${p} (bash or zsh: export ${p}="<salt>"; PowerShell: $env:${p} = "<salt>") and start VS Code from that shell. Use the salt the dataset was built with: another one gives the same records other pseudonyms.`),this.name="MissingSaltError"}},V=["Alix","Camille","Dominique","\xC9loi","Faustine","Gabin","H\xE9lo\xEFse","Ibrahim","Jasmine","Kylian","L\xE9a","Mathis","Nour","Oc\xE9ane","Paul","Quitterie","Rayan","Salom\xE9","Th\xE9o","Ursule","Victor","Wendy","Xavier","Yasmine","Zacharie","Ambre","Bastien","Chlo\xE9","Dorian","Emma","Fabien","Gabrielle","Hugo","In\xE8s","Jules","Klara","Louis","Manon","No\xE9","Oph\xE9lie"],H=["Arnaud","Berthelot","Chevallier","Deschamps","Etcheverry","Fontaine","Guibert","Hamonic","Imbert","Jacquin","Kermarrec","Lefebvre","Mignard","Noirot","Ollivier","Perrin","Quentin","Rochefort","Seguin","Thibault","Uberti","Vasseur","Wagner","Xuereb","Yverneau","Zimmermann","Aubry","Barbier","Charpentier","Delattre","Esnault","Fournier","Gosselin","Hervieux","Leloup","Marchand","Navarro","Pasquier","Renard","Sauvage"],v=["Aster","Boreal","C\xE9drat","Delta","Ellipse","Fulmen","Granit","Halcyon","Isatis","Jaspe","Kelvin","Lumen","M\xE9ridien","Noroit","Obsidienne","Pulsar"],k=["Conseil","Services","Industries","Solutions","Groupe","SAS","Partenaires","Logistique"],$="ABCDEFGHJKLMNPRSTUVWXYZ",x=/^(\d{4})-(\d{2})-(\d{2})$/,A=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{1,3})?(Z|[+-]\d{2}:?\d{2})$/;function Z(i){return Date.parse(i.replace(/([+-]\d{2})(\d{2})$/,"$1:$2"))}var D=864e5,u=class{salt;constructor(t){if(!t)throw new f;this.salt=t}get saltFingerprint(){return R("sha256").update(this.salt).digest("hex").slice(0,12)}get dateShiftDays(){return 200+R("sha256").update(`${this.salt}|dateShift-offset`).digest().readUInt32BE(0)%201}pseudonymize(t,e){if(e==null)return e;switch(t){case"keep":return e;case"clear":return"";case"firstName":return this.pick(t,String(e),V);case"lastName":return this.pick(t,String(e),H);case"companyName":return this.companyName(String(e));case"phoneE164":return this.phoneE164(String(e));case"email":return this.email(String(e));case"registrationSIV":return this.registrationSIV(String(e));case"contractNumber":return this.contractNumber(String(e));case"postalCodeGeneralize":return this.postalCodeGeneralize(String(e));case"dateMonthStart":return this.dateMonthStart(String(e));case"dateShift":return this.dateShift(e);case"geoRound1":return this.roundNumber(e,1);case"kmRound10":return this.roundTo(e,10)}}digest(t,e){return T("sha256",this.salt).update(`${t}|${e}`).digest()}*bytes(t,e){let n=this.digest(t,e),r=0;for(;;){for(let s of n)yield s;r+=1,n=T("sha256",this.salt).update(`${t}|${e}|#${r}`).digest()}}pick(t,e,n){let r=this.digest(t,e);return n[r.readUInt32BE(0)%n.length]}companyName(t){let e=this.digest("companyName",t),n=v[e.readUInt32BE(0)%v.length],r=k[e.readUInt32BE(4)%k.length];return`${n} ${r}`}phoneE164(t){let e=this.bytes("phoneE164",t),n="";for(let r=0;r<4;r++)n+=String(e.next().value%10);return`+3363998${n}`}email(t){return`user-${this.digest("email",t).subarray(0,4).toString("hex")}@example.invalid`}registrationSIV(t){let e=this.bytes("registrationSIV",t),n=()=>$[e.next().value%$.length],r=()=>String(e.next().value%10);return`${n()}${n()}-${r()}${r()}${r()}-${n()}${n()}`}contractNumber(t){let e=this.bytes("contractNumber",t),n="";for(let r of t)r>="0"&&r<="9"?n+=String(e.next().value%10):r>="A"&&r<="Z"?n+=String.fromCharCode(65+e.next().value%26):r>="a"&&r<="z"?n+=String.fromCharCode(97+e.next().value%26):n+=r;return n}postalCodeGeneralize(t){let e=t.trim();if(e.length<=2)return e;if(/^\d+$/.test(e))return e.slice(0,2)+"0".repeat(e.length-2);let n=e.slice(0,2);for(let r of e.slice(2))r>="0"&&r<="9"?n+="0":r>="A"&&r<="Z"||r>="a"&&r<="z"?n+="X":n+=r;return n}dateMonthStart(t){let e=x.exec(t)??A.exec(t);return e?`${e[1]}-${e[2]}-01`:""}dateShift(t){if(typeof t=="string"&&x.test(t))return new Date(Date.parse(`${t}T00:00:00Z`)-this.dateShiftDays*D).toISOString().slice(0,10);if(typeof t=="string"&&A.test(t)){let e=Z(t);if(Number.isFinite(e))return new Date(e-this.dateShiftDays*D).toISOString()}return""}roundNumber(t,e){let n=typeof t=="number"?t:Number(String(t).trim());if(!Number.isFinite(n))return"";let r=10**e,s=Math.round(n*r)/r;return typeof t=="number"?s:String(s)}roundTo(t,e){let n=typeof t=="number"?t:Number(String(t).trim());if(!Number.isFinite(n))return"";let r=Math.round(n/e)*e;return typeof t=="number"?r:String(r)}};import{createHash as Y,randomBytes as X}from"node:crypto";var G=80,W=40,F=1e4,q=64,I=".invalid",g=/\.invalid$/i,C=/[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+/g,J=/\+?(?<!\d)\d(?:[\s.()/-]{0,2}\d){6,}/g;function M(i){return/^(?:(?:00)?330?|0)63998\d{4}$/.test(i.replace(/\D/g,""))}function O(i){return`+3363998${i.replace(/\D/g,"").slice(-4)}`}var Q=/^[\d\s.()/+-]+$/;function _(i,t){if(!Q.test(i))return null;let e=t.slice(3),n=/^[\s(]*\+/.test(i)?[`33${e}`,`330${e}`]:[`0${e}`,`33${e}`,`330${e}`,`0033${e}`,`00330${e}`],r=i.replace(/\D/g,"").length,s=n.find(a=>a.length===r);if(s===void 0)return null;let o=0;return i.replace(/\d/g,()=>s[o++])}function ee(i,t={}){let e=[];for(let n of i){let r=(n.type??"").toLowerCase(),s=S(n.name,r);if(!s)continue;let o=r==="email"||r==="phone",a=r==="email"?G:r==="phone"?W:0,d=n.length!==void 0&&n.length>0?n.length:a;e.push({name:t[n.name]??n.name,kind:s,typed:o,...d>0?{maxLength:d}:{},...n.externalId===!0?{key:!0}:{}})}return e}var P=class{pseudonymizer;upsertKeys;drawnFor=new Map;taken=new Set;exhausted=0;counted=new Map;constructor(t=X(32).toString("hex"),e={}){this.pseudonymizer=new u(t),this.upsertKeys=e.upsertKeys===!0}forObject(t,e,n={}){let r=ee(e,n);if(r.length!==0)return s=>{for(let o of r){let a=s[o.name];if(typeof a!="string")continue;let d=this.neutralize(o,a);d!==a&&(d===null?delete s[o.name]:s[o.name]=d,this.count(t,o))}}}email(t,e=G,n=!1){let r=t.trim();if(r===""||g.test(r))return t;let s=`${r}${I}`;if(s.length<=e)return s;let o=this.shortAddress(r,n);return o.length<=e?o:null}phone(t,e){return/\d/.test(t)?M(t)?(this.taken.add(O(t)),t):this.fictional(t,e):t}report(){let t=[],e=0;for(let[n,r]of this.counted)for(let[s,{kind:o,values:a}]of r)t.push({objectApiName:n,field:s,kind:o,values:a}),e+=a;return{neutralized:!0,fields:t,values:e,...this.exhausted>0?{numbersExhausted:this.exhausted}:{}}}neutralize(t,e){let n=this.upsertKeys&&t.key===!0;return t.typed?t.kind==="email"?this.email(e,t.maxLength,n):this.phone(e,t.maxLength):t.kind==="email"?this.addressesIn(e,t.maxLength,n):this.numbersIn(e,t.maxLength)}addressesIn(t,e,n=!1){let r=a=>e===void 0||a.length<=e,s=t.replace(C,a=>g.test(a)?a:`${a}${I}`);if(s===t||r(s))return s;let o=t.replace(C,a=>g.test(a)?a:this.shortAddress(a,n));return r(o)?o:null}numbersIn(t,e){let n=d=>e===void 0||d.length<=e,r=!1,s=d=>t.replace(J,c=>{if(M(c))return this.taken.add(O(c)),c;let l=this.drawnNumber(c);return l===null?(r=!0,c):_(c,l)??(d?`0${l.slice(3)}`:l)}),o=s(!1);if(r)return null;if(o===t||n(o))return o;let a=s(!0);return n(a)?a:null}fictional(t,e){let n=this.drawnNumber(t);if(n===null)return null;let r=_(t,n);if(r!==null&&(e===void 0||r.length<=e))return r;if(e===void 0||n.length<=e)return n;let s=`0${n.slice(3)}`;return s.length<=e?s:null}drawnNumber(t){let e=t.replace(/[^\d+]/g,""),n=this.drawnFor.get(e);if(n!==void 0)return n;if(this.taken.size>=F)return this.exhausted+=1,null;let r=o=>String(this.pseudonymizer.pseudonymize("phoneE164",o)),s=r(e);for(let o=1;this.taken.has(s)&&o<=q;o+=1)s=r(`${e}#${o}`);for(let o=Number(s.slice(-4));this.taken.has(s);)o=(o+1)%F,s=`+3363998${String(o).padStart(4,"0")}`;return this.drawnFor.set(e,s),this.taken.add(s),s}shortAddress(t,e=!1){let n=t.toLowerCase();return e?`user-${Y("sha256").update(n).digest("hex").slice(0,16)}@example.invalid`:String(this.pseudonymizer.pseudonymize("email",n))}count(t,e){let n=this.counted.get(t)??new Map,r=n.get(e.name)??{kind:e.kind,values:0};r.values+=1,n.set(e.name,r),this.counted.set(t,n)}};export{p as a,me as b,f as c,u as d,G as e,F as f,ee as g,P as h,B as i,ie as j,L as k,se as l,oe as m,ae as n,fe as o};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{a as d,b as g,c as f}from"./chunk-SQGP46QS.mjs";import{a as s}from"./chunk-PPGDAUEQ.mjs";import{a}from"./chunk-SU65Z2BA.mjs";function c(n,t,e){if(!g(t))return;let o=t.edition?`IsSandbox false, edition ${t.edition}`:"IsSandbox false, and no edition",r=e.action==="write"?`${e.tool} writes to sandboxes and Developer Edition orgs only. Nothing was written`:`${e.tool} deletes from sandboxes and Developer Edition orgs only. Nothing was deleted`;return`${n} is a production org (its Organization record says ${o}): ${r}; ${e.readOnly}, which only reads, runs against it.`}function p(n,t,e){let o=t instanceof Error?t.message:String(t),r=`Nothing was ${e.action==="write"?"written":"deleted"}.`,i=`${e.tool} ${e.action==="write"?"writes to":"deletes from"} no org it cannot tell from a production one`;return s(t)?`${n} refused the session sf gave for it (${o}), and ${i}. "sf org display --target-org ${n}" says what sf holds for it; "sf org login web --alias ${n}" signs in again (in a CI job, "sf org login jwt" or "sf org login sfdx-url"); then run the command again. ${r}`:a(t)?`${n} did not answer (${o}), and ${i}. Run the command again once it answers. ${r}`:f(t)?`${n} would not show its Organization record (${o}), and ${i}. Reading it takes the View Setup and Configuration permission: give it to the user the alias signs in as, or name an alias of a user who has it. ${r}`:`${n} did not say what org it is (${o}), and ${i}. ${r}`}var u=1;async function y(n,t,e){let o;try{o=await d(n)}catch(i){process.stderr.write(`${p(t,i,e)}
|
|
8
|
+
`),process.exit(u)}let r=c(t,o,e);return r!==void 0&&(process.stderr.write(`${r}
|
|
9
|
+
`),process.exit(u)),o}export{p 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 n,b as p,h as a}from"./chunk-
|
|
7
|
+
import{a as n,b as p,h as a}from"./chunk-BWWQXU2B.mjs";import{a as o}from"./chunk-EADHKH3A.mjs";import{q as d}from"./chunk-55LQD3Y3.mjs";var R=`SELECT Id FROM RecordType WHERE SobjectType = '${d}' AND IsPersonType = true`;async function S(i,t){let[y,c]=await Promise.all([o(i,n).then(({records:e})=>p(e)),o(t,n).then(({records:e})=>p(e))]),r;try{let{records:e}=await o(t,R);r=new Set(e.flatMap(s=>typeof s.Id=="string"?[s.Id.slice(0,15)]:[]))}catch{r=void 0}return{mappings:new a().buildMapping(y,c),source:y,target:c,...r?{personTypes:r}:{}}}export{S as a};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{createHash as g}from"node:crypto";function h(n){return n.slice(0,15)}function b(n,t){let e=h(n),r=h(t);return e<r?-1:e>r?1:0}var k=2**21,w=2**53;function v(n,t){let e=g("sha256").update(`${n}:${h(t)}`).digest(),r=e.readUInt32BE(0),s=e.readUInt32BE(4)>>>11;return(r*k+s)/w}function x(n,t){return n/Math.max(t,n+1)}var y=1024;function D(n,t){let e=Math.floor(Math.max(0,n)/y);return Math.max(1,Math.min(e,t??1/0))}function l(n,t){return n.rank!==t.rank?n.rank<t.rank?-1:1:n.objectApiName!==t.objectApiName?n.objectApiName<t.objectApiName?-1:1:b(n.id,t.id)}var p=class{items=[];get size(){return this.items.length}peek(){return this.items[0]}push(t){let e=this.items;e.push(t);let r=e.length-1;for(;r>0;){let s=r-1>>1;if(l(e[r],e[s])<=0)break;[e[r],e[s]]=[e[s],e[r]],r=s}}pop(){let t=this.items,e=t[0],r=t.pop();if(t.length===0||r===void 0)return e;t[0]=r;let s=0;for(;;){let i=2*s+1,u=i+1,o=s;if(i<t.length&&l(t[i],t[o])>0&&(o=i),u<t.length&&l(t[u],t[o])>0&&(o=u),o===s)break;[t[s],t[o]]=[t[o],t[s]],s=o}return e}values(){return this.items}};function f(n){return`${n.objectApiName}
|
|
8
|
+
${h(n.id)}`}function d(n,t){return t===void 0?n:`${n}
|
|
9
|
+
${t}`}var m=class{constructor(t,e){this.most=t;this.floor=e}most;floor;kept=new p;floors=new Map;inKept=new Set;inFloor=new Set;letGo=1/0;offer(t,e,r,s){let i={objectApiName:t,id:e,rank:r},u=[];if(this.floor>0){let o=d(t,s),a=this.floors.get(o);if(a||(a=new p,this.floors.set(o,a)),a.push(i),this.inFloor.add(f(i)),a.size>this.floor){let c=a.pop();c&&(this.inFloor.delete(f(c)),u.push(c))}}if(this.most>0){if(this.kept.push(i),this.inKept.add(f(i)),this.kept.size>this.most){let o=this.kept.pop();o&&(this.inKept.delete(f(o)),u.push(o))}}else u.push(i);for(let o of u){let a=f(o);!this.inKept.has(a)&&!this.inFloor.has(a)&&(this.letGo=Math.min(this.letGo,o.rank))}}keeps(t,e,r){let s=this.floors.get(d(t,r));if(this.floor>0&&(s?.size??0)<this.floor||this.kept.size<this.most)return!0;let i=this.kept.peek();return i!==void 0&&e<i.rank}leftUnread(t){this.letGo=Math.min(this.letGo,t)}get beyond(){return this.letGo}drawn(){let t=new Map;for(let e of this.kept.values())t.set(f(e),e);for(let e of this.floors.values())for(let r of e.values())t.set(f(r),{...r,rank:0});return[...t.values()].sort(l)}};export{h as a,b,v as c,x as d,y as e,D as f,l as g,p as h,m as i};
|
|
@@ -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{
|
|
7
|
+
import{_d as c}from"./chunk-DPYTG6DM.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";var y=[{type:"seed",label:"Seed Data",description:"Seed an org with a template saved on the Seed page or shipped with SandForge, never a production org; its records are taken back from Seed\u2019s Recent runs",category:"data",icon:"database",configSchema:{orgId:{type:"string"},templateId:{type:"string"}}},{type:"sync",label:"Sync Data",description:"Run a Sync configuration saved on the Sync page; a target Production Guard asks about, a production org or a sandbox marked Staging, needs an Approval step before it",category:"data",icon:"sync",configSchema:{configId:{type:"string"}}},{type:"backup",label:"Backup",description:"Take a DataOps snapshot of the listed objects into local storage",category:"data",icon:"archive",configSchema:{orgId:{type:"string"},objects:{type:"array"}}},{type:"restore",label:"Restore",description:"Restore data from a previous backup snapshot",category:"data",icon:"history",configSchema:{backupId:{type:"string"}}},{type:"anonymize",label:"Anonymize",description:"Mask an org with a DataOps template, after a snapshot of the values it writes over, never a production org",category:"data",icon:"shield",configSchema:{orgId:{type:"string"},templateId:{type:"string"},object:{type:"string",optional:!0},where:{type:"string",optional:!0},acceptAutomation:{type:"boolean",default:!1},acceptEmails:{type:"boolean",default:!1},muteAutomation:{type:"boolean",default:!1}}},{type:"delete",label:"Delete",description:"Delete records matching specified criteria",category:"data",icon:"trash",configSchema:{objectName:{type:"string"},where:{type:"string"}}},{type:"checkpoint",label:"Checkpoint",description:"Take a checkpoint of a sandbox, a scratch org or a Developer Edition org, kept on this machine",category:"data",icon:"bookmark",configSchema:{orgId:{type:"string"},mode:{type:"string",default:"everything"},objects:{type:"array",optional:!0},excluded:{type:"array",optional:!0},name:{type:"string",optional:!0},keepDays:{type:"number",default:c},maxTotal:{type:"number",optional:!0},ignoredFields:{type:"array",optional:!0}}},{type:"rewind",label:"Rewind",description:"Put an org back to a checkpoint kept on this machine, once confirmed by typing the org\u2019s alias, at most maxRecords records",category:"data",icon:"history",configSchema:{orgId:{type:"string"},checkpointId:{type:"string"},objects:{type:"array",optional:!0},acceptAutomation:{type:"boolean",default:!1},acceptEmails:{type:"boolean",default:!1},muteAutomation:{type:"boolean",default:!1},acceptNoUndo:{type:"boolean",default:!1},acceptRecreate:{type:"boolean",default:!1},acceptOutside:{type:"boolean",default:!1},acceptUnseen:{type:"boolean",default:!1},maxRecords:{type:"number",required:!0},refuseWhenActive:{type:"boolean",default:!0}}},{type:"compare",label:"Compare Orgs",description:"Compare the metadata of two orgs, as the Compare page does",category:"quality",icon:"git-compare",configSchema:{sourceOrgId:{type:"string"},targetOrgId:{type:"string"},types:{type:"array"}}},{type:"precheck",label:"Pre-check",description:"Read an org\u2019s API usage, storage, error logs or failed jobs as the Monitor does; the run stops on a critical reading",category:"quality",icon:"check-circle",configSchema:{orgId:{type:"string"},checks:{type:"array"}}},{type:"condition",label:"Condition",description:"Branch pipeline execution based on conditions",category:"control",icon:"git-branch",configSchema:{field:{type:"string"},operator:{type:"string"},value:{type:"string"}}},{type:"delay",label:"Delay",description:"Wait for a specified duration before continuing",category:"control",icon:"clock",configSchema:{durationMs:{type:"number"}}},{type:"approval",label:"Approval",description:"Pauses the run until someone approves it in VS Code; a rejection, or no answer in time, stops it",category:"control",icon:"user-check",configSchema:{message:{type:"string"},timeoutMinutes:{type:"number"}}},{type:"notification",label:"Notification",description:"Shows its message as a VS Code notification",category:"notification",icon:"bell",configSchema:{message:{type:"string"}}}],p=class{registry;constructor(){this.registry=new Map(y.map(e=>[e.type,e]))}getStepTypes(){return[...this.registry.values()]}getStepType(e){return this.registry.get(e)}getDefaultConfig(e){let r=this.registry.get(e);if(!r)return{};let o={};for(let[t,a]of Object.entries(r.configSchema)){let n=a;if(!(n.optional===!0||n.required===!0)){if("default"in n){o[t]=n.default;continue}switch(n.type){case"string":o[t]="";break;case"number":o[t]=0;break;case"array":o[t]=[];break;case"boolean":o[t]=!1;break;default:o[t]=null}}}return o}validateStepConfig(e,r){let o=this.registry.get(e);if(!o)return[`Unknown step type: ${e}`];let t=[];for(let[a,n]of Object.entries(o.configSchema)){let l=n,i=r[a],s=l.type;i!=null&&(s==="array"&&!Array.isArray(i)?t.push(`Field "${a}" must be an array`):s==="string"&&typeof i!="string"?t.push(`Field "${a}" must be a string`):s==="number"&&typeof i!="number"?t.push(`Field "${a}" must be a number`):s==="boolean"&&typeof i!="boolean"&&t.push(`Field "${a}" must be a boolean`))}return t}getStepCategories(){let e=new Set;for(let r of this.registry.values())e.add(r.category);return[...e]}};export{p as StepLibrary};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s}from"./chunk-
|
|
7
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s}from"./chunk-2OIRJEYE.mjs";import"./chunk-EAFLDSQ2.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-DPYTG6DM.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{r as BEFORE_RUN_DELETED_WORDS,e as BEFORE_RUN_DISK_ROOM,a as WRITE_PATH_STEPS,j as beforeRunAskedOf,f as beforeRunDiskRefusal,d as beforeRunEstimateOf,q as beforeRunFailedWords,i as beforeRunKeepDaysOf,h as beforeRunNameOf,l as beforeRunOutcomeOf,s as beforeRunProgressWords,p as beforeRunRefusedWords,c as beforeRunScopeOf,k as beforeRunTakenOf,g as freeBytesOf,m as scopeBeforeRun,o as settleBeforeRun,n as takeBeforeRun,b as writePathOrderDefects};
|
|
@@ -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{e as R}from"./chunk-
|
|
7
|
+
import{e as R}from"./chunk-3B5H24ZG.mjs";var h="FIELD_CUSTOM_VALIDATION_EXCEPTION",y="INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST",_="FIELD_FILTER_VALIDATION_EXCEPTION",w="INACTIVE_OWNER_OR_USER",E=/\[(005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?)\]/,F="005",b=["CreatedById","LastModifiedById"];function A(t,e){if(t.statusCode!==w)return;let r=c(e,"OwnerId"),n=r===void 0?void 0:e[r],o=E.exec(t.message)?.[1];if(!(typeof n!="string"||o===void 0))return n.slice(0,15)===o.slice(0,15)?o.slice(0,15):void 0}function D(t,e,r){let n=c(e,"OwnerId");if(n===void 0||n.toLowerCase()===r?.toLowerCase())return;let o=e[n];if(!(typeof o!="string"||!o.startsWith(F)||t.fields.some(s=>s.toLowerCase()!=="ownerid")||!(E.test(t.message)?A(t,e)!==void 0:b.every(s=>c(e,s)===void 0))))return{field:n,refusedBy:"inactive-owner",reason:R(t)}}var S=new Map([[h,"validation-rule"],[y,"restricted-picklist"],[_,"lookup-filter"]]);function T(t){return t!=null&&t!==""}function c(t,e){let r=e.toLowerCase();return Object.keys(t).find(n=>n.toLowerCase()===r&&T(t[n]))}function P(t,e,r,n,o){if(!t||t.length===0)return;let i=new Map;for(let a of t){let s=S.get(a.statusCode);if(!s){let d=o?.inactiveOwner===!0&&a.statusCode===w?D(a,e,r):void 0;if(!d)return;i.has(d.field)||i.set(d.field,d);continue}let u=a.fields.map(d=>c(e,d)).filter(d=>d!==void 0&&d.toLowerCase()!==r?.toLowerCase());if(u.length===0||s==="lookup-filter"&&!u.every(d=>n?.(d)===!0))return;for(let d of u)i.has(d)||i.set(d,{field:d,refusedBy:s,reason:R(a)})}return[...i.values()]}function K(t){return(t??[]).some(e=>e.statusCode===h&&e.fields.length===0)}function B(t,e){let r=new Set(e.map(n=>n.field));return Object.fromEntries(Object.entries(t).filter(([n])=>!r.has(n)))}function j(t,e){let r=t??{rows:0,fields:[]};r.rows+=e.rows;for(let n of e.fields){let o=r.fields.find(i=>i.field===n.field&&i.reason===n.reason);o?o.rows+=n.rows:r.fields.push({...n})}return r}var k={"validation-rule":"a validation rule of the target refused it","restricted-picklist":"a restricted picklist of the target refused its value","lookup-filter":"a lookup filter of the target refused the record it names","inactive-owner":"the target holds the owner it names inactive"};function x(t){return(t?.fields??[]).map(({field:e,refusedBy:r="validation-rule",reason:n,rows:o,replacedWith:i})=>{let a=i===void 0?`written without ${e}`:`written with ${e} set to "${i}"`;return`, ${o} ${a}: ${k[r]}, ${n}`}).join("")}function V(t){let e=`${t.rows} record(s) written again without the fields the target refused them on${x(t)}`;return e.endsWith(".")?e:`${e}.`}var f=class{config;constructor(e){this.config={maxRetries:e?.maxRetries??3,initialDelay:e?.initialDelay??1e3,maxDelay:e?.maxDelay??3e4,backoffMultiplier:e?.backoffMultiplier??2,jitter:e?.jitter??!0}}calculateDelay(e){let r=this.config.initialDelay*Math.pow(this.config.backoffMultiplier,e),n=Math.min(r,this.config.maxDelay);if(!this.config.jitter)return n;let o=n/2;return Math.floor(o+Math.random()*o)}async execute(e){let r,n=0;for(let o=0;o<=this.config.maxRetries;o++)try{return{success:!0,result:await e(),attempts:o+1,totalDelay:n}}catch(i){if(r=i instanceof Error?i:new Error(String(i)),o<this.config.maxRetries){let a=this.calculateDelay(o);n+=a,await new Promise(s=>setTimeout(s,a))}}return{success:!1,error:r,attempts:this.config.maxRetries+1,totalDelay:n}}shouldRetry(e){return e<this.config.maxRetries}getConfig(){return{...this.config}}};var O="UNABLE_TO_LOCK_ROW",l=3,C=2e3,L=200,Z=`Rows the target refuses for a record lock go again on their own, up to ${l} times each: up to ${l} more requests for every ${L} of them, which no estimate made before the write can count.`,X=`rows the target refuses for a record lock go again, up to ${l} times each: up to ${l} more requests for every ${L} of them, not counted above`,I="CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY",v=/\bfirst error: UNABLE_TO_LOCK_ROW\b/,N=/^([A-Z][A-Z0-9_]*):\s*([\s\S]*)$/;function p(t,e){return t===O||t===I&&v.test(e)}function q(t,e){return e&&e.length>0?e.every(r=>p(r.statusCode,r.message)):t.length>0&&t.every(r=>{let n=N.exec(r.trim());return n!==null&&p(n[1],n[2])})}var $=new f({initialDelay:C});function U(t){return $.calculateDelay(t)}function H(t,e){return new Promise(r=>{if(e?.aborted){r();return}let n=()=>{clearTimeout(o),e?.removeEventListener("abort",n),r()},o=setTimeout(n,t);e?.addEventListener("abort",n,{once:!0})})}function W(t){return`sent again ${t===1?"once":`${t} times`}, waiting longer each time: the target still could not lock a record the write needed`}function J(t,e){return`${t} \u2014 ${W(e)}`}async function Q(t){let e=[...t.outcomes],r=new Map,n=e.flatMap((s,u)=>t.locked(s)?[u]:[]),o=n.length;for(let s=0;n.length>0&&s<l&&(await t.wait(U(s)),!t.stopped());s++){let u=n,d=await t.send(u);if(d.slice(0,u.length).forEach((m,g)=>{e[u[g]]=m,r.set(u[g],(r.get(u[g])??0)+1)}),d.length<u.length)break;n=u.filter(m=>t.locked(e[m]))}let i=0,a=0;for(let[s,u]of r)t.written(e[s])?i++:t.locked(e[s])&&(a++,e[s]=t.note(e[s],u));return{outcomes:e,refused:o,sentAgain:r.size,written:i,stillLocked:a,notSentAgain:o-r.size}}function ee(t,e){if(e.refused===0)return;let r=e.sentAgain-e.written-e.stillLocked,n=[`${e.written} written`,...e.stillLocked>0?[`${e.stillLocked} still refused for the lock`]:[],...r>0?[`${r} refused for another reason`]:[],...e.notSentAgain>0?[`${e.notSentAgain} not sent again: the run was stopped`]:[]];return`${e.refused} ${t} refused because the target could not lock a record their write needed (${O}), sent again up to ${l} times, waiting longer each time: ${n.join(", ")}`}export{y as a,_ as b,w as c,A as d,c as e,P as f,K as g,B as h,j as i,x as j,V as k,f as l,Z as m,X as n,q as o,H as p,J as q,Q as r,ee as s};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a,b,c,d,e,f}from"./chunk-
|
|
7
|
+
import{a,b,c,d,e,f}from"./chunk-YHIOS2PU.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-55LQD3Y3.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-3B5H24ZG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-DPYTG6DM.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as OPPORTUNITY,c as SeedPlatformRoles,b as rolesNotLookedUpNote,d as rolesOfADryRun,f as seedTargetOf,e as writtenByThePlatformLine};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a,b}from"./chunk-
|
|
7
|
+
import{a,b}from"./chunk-FSDO4DJA.mjs";import"./chunk-DPYTG6DM.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as DataPlanBuilder,b as resolveInsertOrder};
|