sandforge 1.79.0 → 1.80.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/{chunk-JVL444U5.mjs → chunk-2BA2XKAY.mjs} +1 -1
- package/lib/chunk-2CNCDM56.mjs +7 -0
- package/lib/{chunk-W7KFAY55.mjs → chunk-2GTBABKU.mjs} +1 -1
- package/lib/{chunk-DLDX6RRC.mjs → chunk-2NBYT7GR.mjs} +1 -1
- package/lib/{chunk-HV2MXMGI.mjs → chunk-2UZPIMUC.mjs} +1 -1
- package/lib/chunk-3F6Q5E7I.mjs +14 -0
- package/lib/{chunk-PBI4BYWW.mjs → chunk-3RZQZHEB.mjs} +1 -1
- package/lib/{chunk-P7GSGFJO.mjs → chunk-3TJON4F3.mjs} +1 -1
- package/lib/chunk-4VS2V6WU.mjs +25 -0
- package/lib/{chunk-TQX3PURV.mjs → chunk-5K5VLULK.mjs} +1 -1
- package/lib/{chunk-MYTIL2JD.mjs → chunk-5TC3QB4U.mjs} +1 -1
- package/lib/{chunk-NM4MDLK4.mjs → chunk-6XYKJSGX.mjs} +1 -1
- package/lib/{chunk-RFEO2KAN.mjs → chunk-74Q6DORA.mjs} +1 -1
- package/lib/chunk-7ABODJ4G.mjs +7 -0
- package/lib/{chunk-ZPYJPGDK.mjs → chunk-7EGQP6S4.mjs} +1 -1
- package/lib/chunk-7FFGJWHN.mjs +7 -0
- package/lib/chunk-7YDNUBO5.mjs +7 -0
- package/lib/{chunk-CGWXQX75.mjs → chunk-A527W53V.mjs} +1 -1
- package/lib/chunk-ADOAS63R.mjs +7 -0
- package/lib/chunk-AEKONPF4.mjs +7 -0
- package/lib/{chunk-4HFRHFGQ.mjs → chunk-B5QQJ4SI.mjs} +1 -1
- package/lib/{chunk-2BVTCNWA.mjs → chunk-BGUEWRK2.mjs} +1 -1
- package/lib/{chunk-GNC27UEU.mjs → chunk-BKDV4ENO.mjs} +1 -1
- package/lib/{chunk-QRV2OSIS.mjs → chunk-BTWDMNN3.mjs} +1 -1
- package/lib/{chunk-FOVVHGEP.mjs → chunk-BV6VTP3J.mjs} +1 -1
- package/lib/{chunk-PZTSVQSF.mjs → chunk-BXU6WFMH.mjs} +1 -1
- package/lib/{chunk-ZQOZ4EFW.mjs → chunk-BY2HJFFG.mjs} +1 -1
- package/lib/{chunk-NZ5ZZLKS.mjs → chunk-CEX3NEZL.mjs} +1 -1
- package/lib/{chunk-HTJ5OGP5.mjs → chunk-CHYDMRSV.mjs} +1 -1
- package/lib/chunk-CION3VMZ.mjs +7 -0
- package/lib/chunk-COFG7Q6R.mjs +7 -0
- package/lib/chunk-CSBS5U5I.mjs +7 -0
- package/lib/{chunk-55HEMHEG.mjs → chunk-CU2INBND.mjs} +1 -1
- package/lib/chunk-DB7RBE5D.mjs +7 -0
- package/lib/{chunk-QPF6C5MX.mjs → chunk-DBB3EMIN.mjs} +1 -1
- package/lib/{chunk-F74IHMGL.mjs → chunk-DYFALGRT.mjs} +1 -1
- package/lib/{chunk-TEOLMRDO.mjs → chunk-E5AHXLS6.mjs} +1 -1
- package/lib/{chunk-LRFAIUN7.mjs → chunk-E5ZB3LU5.mjs} +1 -1
- package/lib/chunk-EFR2Y7E4.mjs +7 -0
- package/lib/chunk-EHQ3FX6X.mjs +7 -0
- package/lib/{chunk-RAAANPPG.mjs → chunk-ELFXJHU7.mjs} +1 -1
- package/lib/{chunk-BN7A4GRQ.mjs → chunk-EMNC6YI4.mjs} +1 -1
- package/lib/{chunk-HJC7AIBK.mjs → chunk-EQNW3UC2.mjs} +1 -1
- package/lib/{chunk-Z7X534S4.mjs → chunk-F43REJDZ.mjs} +2 -2
- package/lib/{chunk-QQZZMKU3.mjs → chunk-F6GUDTOB.mjs} +1 -1
- package/lib/{chunk-6EBMEGZB.mjs → chunk-FGRG7ANU.mjs} +1 -1
- package/lib/{chunk-4NAHW2D3.mjs → chunk-FKG7Q3WH.mjs} +1 -1
- package/lib/{chunk-7UQD6V6F.mjs → chunk-FPKYYFM7.mjs} +1 -1
- package/lib/{chunk-ZJKCWBRJ.mjs → chunk-FXXLX4O6.mjs} +1 -1
- package/lib/chunk-G35N4P7D.mjs +7 -0
- package/lib/{chunk-SIOZXPFG.mjs → chunk-GGD7ON3M.mjs} +1 -1
- package/lib/chunk-GSG7WZHM.mjs +7 -0
- package/lib/{chunk-OTWRDD6L.mjs → chunk-GSKCGQIP.mjs} +1 -1
- package/lib/{chunk-3CA767QB.mjs → chunk-HEKAZJRH.mjs} +1 -1
- package/lib/{chunk-4SNDMJP2.mjs → chunk-HLWMJF6Y.mjs} +1 -1
- package/lib/chunk-HOJYWTP7.mjs +20 -0
- package/lib/chunk-HS4YRX4J.mjs +7 -0
- package/lib/chunk-IFETCRWE.mjs +10 -0
- package/lib/{chunk-PUOX4NBJ.mjs → chunk-IG2MTQRP.mjs} +1 -1
- package/lib/{chunk-RACDTRZA.mjs → chunk-IGYH7GMA.mjs} +1 -1
- package/lib/{chunk-X65MT4W3.mjs → chunk-IOIWJ3DJ.mjs} +1 -1
- package/lib/{chunk-4U6NXJNL.mjs → chunk-IQXHJEYB.mjs} +1 -1
- package/lib/{chunk-P2PJYWGQ.mjs → chunk-IWDREM66.mjs} +1 -1
- package/lib/{chunk-ZOVSMN5C.mjs → chunk-IZQZ6ZUF.mjs} +1 -1
- package/lib/{chunk-XBG5SP6Q.mjs → chunk-J525F5KI.mjs} +1 -1
- package/lib/{chunk-5CD257T7.mjs → chunk-JEERQRLW.mjs} +1 -1
- package/lib/{chunk-6QSM2WIH.mjs → chunk-JPUR2CFX.mjs} +1 -1
- package/lib/chunk-JWTSEDIQ.mjs +7 -0
- package/lib/chunk-K327QKMD.mjs +7 -0
- package/lib/{chunk-J7HVXMSW.mjs → chunk-KBJ5VERV.mjs} +1 -1
- package/lib/chunk-KDGMAGQR.mjs +7 -0
- package/lib/chunk-KRCA6IPH.mjs +8 -0
- package/lib/chunk-KYEDBS54.mjs +7 -0
- package/lib/chunk-L5FGY6YA.mjs +7 -0
- package/lib/{chunk-PNCONNFJ.mjs → chunk-L77FJZEP.mjs} +1 -1
- package/lib/{chunk-3OHPD72J.mjs → chunk-LKQ5RKIV.mjs} +1 -1
- package/lib/{chunk-WJY54JO7.mjs → chunk-LPBMBW3O.mjs} +1 -1
- package/lib/{chunk-LV6G4XTK.mjs → chunk-LWW4U276.mjs} +1 -1
- package/lib/{chunk-IAZB4WIL.mjs → chunk-M3ROUWDX.mjs} +1 -1
- package/lib/chunk-MFG4MUIO.mjs +9 -0
- package/lib/{chunk-H45UXY6G.mjs → chunk-MHMH6MTP.mjs} +1 -1
- package/lib/{chunk-HCIDVIOW.mjs → chunk-MILU7WFN.mjs} +1 -1
- package/lib/chunk-MJU2PGZQ.mjs +15 -0
- package/lib/{chunk-HJKM3E56.mjs → chunk-MJVTDA5Q.mjs} +1 -1
- package/lib/{chunk-SBIMVCXT.mjs → chunk-MS4FJDFD.mjs} +9 -9
- package/lib/{chunk-3SRXFZSD.mjs → chunk-MYW5QNGI.mjs} +1 -1
- package/lib/{chunk-VHI54FBK.mjs → chunk-N652NMZ4.mjs} +26 -26
- package/lib/{chunk-3DCUADVK.mjs → chunk-NTFIRZP6.mjs} +1 -1
- package/lib/{chunk-342FN7AO.mjs → chunk-NZC67CGR.mjs} +1 -1
- package/lib/{chunk-RSYICMZG.mjs → chunk-O2HDYYUV.mjs} +1 -1
- package/lib/chunk-OAZRPP4I.mjs +7 -0
- package/lib/{chunk-BILZ3SSR.mjs → chunk-OHWNPXWW.mjs} +1 -1
- package/lib/chunk-OLSGVAIL.mjs +341 -0
- package/lib/chunk-OO6CLPEH.mjs +7 -0
- package/lib/chunk-OPXCV2KL.mjs +7 -0
- package/lib/chunk-P33PSCXK.mjs +7 -0
- package/lib/{chunk-AUTM6H6Z.mjs → chunk-PJ5I73CK.mjs} +1 -1
- package/lib/{chunk-NTDN2JQZ.mjs → chunk-PZPJKATS.mjs} +1 -1
- package/lib/{chunk-5QKTYCWE.mjs → chunk-Q3DM32KF.mjs} +1 -1
- package/lib/{chunk-K22PA4XL.mjs → chunk-QR3WELJQ.mjs} +1 -1
- package/lib/{chunk-42RER7V4.mjs → chunk-R3X3LV64.mjs} +1 -1
- package/lib/chunk-RMBPOTD7.mjs +7 -0
- package/lib/{chunk-IEYG5ATY.mjs → chunk-RPI7LRTW.mjs} +1 -1
- package/lib/{chunk-5MMXFWPD.mjs → chunk-SE4QEZUG.mjs} +1 -1
- package/lib/{chunk-ALJVEUUS.mjs → chunk-SIHORWVK.mjs} +1 -1
- package/lib/{chunk-AAVJ5XVX.mjs → chunk-SOGQW4IG.mjs} +1 -1
- package/lib/chunk-SOU4FRYN.mjs +7 -0
- package/lib/chunk-SU65Z2BA.mjs +7 -0
- package/lib/chunk-T62WNR54.mjs +7 -0
- package/lib/{chunk-5O6JOMHS.mjs → chunk-TSLJUSLW.mjs} +1 -1
- package/lib/chunk-TTFDUKUS.mjs +47 -0
- package/lib/{chunk-57VHUYNG.mjs → chunk-TTKXMDBN.mjs} +1 -1
- package/lib/chunk-UCD54V2M.mjs +7 -0
- package/lib/{chunk-TBZMC2VV.mjs → chunk-UNJA4J37.mjs} +1 -1
- package/lib/{chunk-NGSMZZDA.mjs → chunk-VE6XKGGD.mjs} +1 -1
- package/lib/chunk-VS7ZXUII.mjs +824 -0
- package/lib/{chunk-ALUFROGA.mjs → chunk-VXQLDM4R.mjs} +1 -1
- package/lib/chunk-VYXMVJL5.mjs +7 -0
- package/lib/{chunk-WFEB5X4U.mjs → chunk-W622GUAW.mjs} +1 -1
- package/lib/chunk-W7U5E5ZL.mjs +9 -0
- package/lib/{chunk-AR7BE5O2.mjs → chunk-WA7EYLAQ.mjs} +1 -1
- package/lib/{chunk-EQF2IJS2.mjs → chunk-WR4Q363I.mjs} +1 -1
- package/lib/{chunk-ZXH4MBWP.mjs → chunk-WU3GLFZO.mjs} +1 -1
- package/lib/chunk-WXAQ7FK3.mjs +115 -0
- package/lib/{chunk-YBU4Z4QV.mjs → chunk-X5JYBPXP.mjs} +1 -1
- package/lib/chunk-XAMBCQPU.mjs +7 -0
- package/lib/{chunk-LQ4DRFUH.mjs → chunk-XLXIPIEW.mjs} +1 -1
- package/lib/{chunk-H2PJNIYJ.mjs → chunk-XUWL6ZPC.mjs} +1 -1
- package/lib/{chunk-P42X3B4D.mjs → chunk-YKKRIEH4.mjs} +1 -1
- package/lib/chunk-YRQGKDHM.mjs +7 -0
- package/lib/chunk-ZM6OJGIG.mjs +7 -0
- package/lib/{chunk-SFURUNJM.mjs → chunk-ZVAED4QV.mjs} +1 -1
- package/lib/sandforge-autopilot.mjs +29 -24
- package/lib/sandforge-backup.mjs +25 -21
- package/lib/sandforge-checkpoint.mjs +15 -14
- package/lib/sandforge-cleanup.mjs +14 -10
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +9 -8
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +15 -15
- package/lib/sandforge-env.mjs +88 -88
- package/lib/sandforge-frozen.mjs +43 -34
- package/lib/sandforge-mcp.mjs +12 -12
- package/lib/sandforge-monitor.mjs +7 -7
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge.mjs +4 -4
- package/package.json +1 -1
- package/lib/chunk-2S5OMIIA.mjs +0 -7
- package/lib/chunk-36U7IQ6Y.mjs +0 -25
- package/lib/chunk-3F5YMM2F.mjs +0 -7
- package/lib/chunk-3RYLICRX.mjs +0 -7
- package/lib/chunk-4GL773D5.mjs +0 -7
- package/lib/chunk-4XZ5YT5O.mjs +0 -7
- package/lib/chunk-5AJRHRXA.mjs +0 -20
- package/lib/chunk-5HMAPZBV.mjs +0 -7
- package/lib/chunk-6LAXTAVN.mjs +0 -7
- package/lib/chunk-6MUEPV7M.mjs +0 -9
- package/lib/chunk-75ADZS6B.mjs +0 -7
- package/lib/chunk-B45CNPUX.mjs +0 -47
- package/lib/chunk-BS5T3MOQ.mjs +0 -7
- package/lib/chunk-D3QRXG63.mjs +0 -787
- package/lib/chunk-EEVVGGM6.mjs +0 -7
- package/lib/chunk-ENLBYECD.mjs +0 -7
- package/lib/chunk-EQOQASDQ.mjs +0 -7
- package/lib/chunk-FQBRBBY4.mjs +0 -7
- package/lib/chunk-GAM726CK.mjs +0 -7
- package/lib/chunk-HUMEKZT5.mjs +0 -8
- package/lib/chunk-I3JKJTLO.mjs +0 -110
- package/lib/chunk-KLX67VPL.mjs +0 -7
- package/lib/chunk-L776PUMV.mjs +0 -7
- package/lib/chunk-NEVXIGR6.mjs +0 -10
- package/lib/chunk-NHWE66K5.mjs +0 -7
- package/lib/chunk-OQOZAPCI.mjs +0 -7
- package/lib/chunk-PA3MKJVH.mjs +0 -7
- package/lib/chunk-RH3N2H7P.mjs +0 -7
- package/lib/chunk-SRQDABQ2.mjs +0 -15
- package/lib/chunk-SVS6UMDU.mjs +0 -323
- package/lib/chunk-TNXUU6W7.mjs +0 -14
- package/lib/chunk-VXHDBYMI.mjs +0 -7
- package/lib/chunk-WRU5FJFC.mjs +0 -7
- package/lib/chunk-X2PY6MWZ.mjs +0 -7
- package/lib/chunk-XEFDB2R4.mjs +0 -7
- package/lib/chunk-XETCPL7E.mjs +0 -7
- package/lib/chunk-Y5CGXLUB.mjs +0 -7
- package/lib/chunk-Y6J6QFI2.mjs +0 -7
- package/lib/chunk-YMJVMFPY.mjs +0 -7
- package/lib/chunk-YPSRZRIT.mjs +0 -7
- package/lib/chunk-YW2SBL4Z.mjs +0 -7
- package/lib/chunk-ZE6HKRR4.mjs +0 -9
- package/lib/chunk-ZLZRU6MO.mjs +0 -7
- package/lib/chunk-ZYEE34WO.mjs +0 -7
|
@@ -0,0 +1,341 @@
|
|
|
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 qr}from"./chunk-INIQ23K6.mjs";import{a as Gr}from"./chunk-ELFXJHU7.mjs";import{b as Kt}from"./chunk-W7U5E5ZL.mjs";import{$ as yt,C as _r,F as Wr,G as Ur,H as Br,U as zr,V as mt,W as wt,X as Jr,Y as Hr,_ as Kr,aa as Yr,c as Or,e as jr,f as Cr,h as xr,j as Ir,k as Er,u as Tr,x as Mr}from"./chunk-ZM6OJGIG.mjs";import{b as Fr,g as Pr}from"./chunk-MHMH6MTP.mjs";import{e as gt,m as Nr}from"./chunk-COFG7Q6R.mjs";import{a as Lr,f as Dr}from"./chunk-PJ5I73CK.mjs";import{a as ot,b as st}from"./chunk-5P4PHJRL.mjs";import{Na as We,O as De,Va as pr,Wa as ct,_ as hr,c as Xn,cb as gr,d as Zn,db as mr,g as at,gb as ut,h as rr,hb as Ue,i as or,ib as wr,j as sr,jb as lt,k as ir,kb as yr,l as dt,m as ar,n as dr,o as cr,ob as br,pb as Rr,q as ur,qb as kr,rb as Sr,s as lr,sb as ft,tb as vr,ub as $r,vb as Ar}from"./chunk-VS7ZXUII.mjs";import{k as Mn,n as _n}from"./chunk-OO6CLPEH.mjs";import{b as Ie,e as Ve}from"./chunk-BZ24IAP5.mjs";import{a as _t}from"./chunk-SCKUIE3R.mjs";import{a as Yt,b as Vt,c as Fe,d as Xt,e as Zt,g as Qt,h as en,j as tn}from"./chunk-AV5SWEHP.mjs";import{a as ht,c as pt}from"./chunk-I7O6C2B5.mjs";import{B as hn,Ec as En,wc as Cn,x as ln,y as fn}from"./chunk-2CNCDM56.mjs";import{qb as Qn,rb as er,xb as tr,y as Le,zb as nr}from"./chunk-4VS2V6WU.mjs";import{k as Vn}from"./chunk-6XYKJSGX.mjs";import{b as yn,l as In}from"./chunk-F43REJDZ.mjs";import{C as mn,N as Pe,Q as wn,U as rt,V as xn,a as nn}from"./chunk-JPUR2CFX.mjs";import{a as Ze,b as bn,c as kn,f as Sn,h as Qe,k as vn,l as $n,m as An,n as On,o as et,r as tt,t as nt,w as jn}from"./chunk-PZPJKATS.mjs";import{n as Nn}from"./chunk-G35N4P7D.mjs";import{b as xe,c as Se}from"./chunk-KDGMAGQR.mjs";import{B as le,s as Ne,t as Me,y as Pn,z as _e}from"./chunk-MFG4MUIO.mjs";import{B as ue,D as un,p as an}from"./chunk-EQNW3UC2.mjs";import{b as ke,c as Jt,g as Ye}from"./chunk-HS4YRX4J.mjs";import{i as on,v as sn}from"./chunk-ZUTYVST5.mjs";import{a as cn}from"./chunk-CU2INBND.mjs";import{a as dn}from"./chunk-YKKRIEH4.mjs";import{d as Rn}from"./chunk-TUACWKIH.mjs";import{Ca as zn,Ia as Jn,K as Wn,L as Un,P as Bn,Pa as Hn,S as fe,bb as Kn,cb as Yn,i as Xe,ka as qn,r as Tn,s as Fn,va as Gn,x as Dn,ya as it}from"./chunk-VYXMVJL5.mjs";import{ea as Ln}from"./chunk-CION3VMZ.mjs";import{a as te}from"./chunk-EADHKH3A.mjs";import{i as rn}from"./chunk-INIT2UKJ.mjs";import{h as gn}from"./chunk-L77FJZEP.mjs";import{j as pn}from"./chunk-GGD7ON3M.mjs";import{a as Ht,c as Ee,e as Te,g as fr}from"./chunk-MTMH6H2A.mjs";import{$b as Wt,Wc as qt,Xb as Dt,Yb as Ke,Yc as Gt,Zc as zt,lc as Ut,mc as Bt,yb as Lt}from"./chunk-TTFDUKUS.mjs";import{A as R}from"./chunk-7EANH5PY.mjs";import{b as ao}from"./chunk-MS4FJDFD.mjs";import{d as io}from"./chunk-NTOVCTRS.mjs";var Ro=io(ao());import{randomUUID as po}from"node:crypto";import{existsSync as ve,mkdirSync as go,readFileSync as $e,renameSync as mo,writeFileSync as wo}from"node:fs";import{dirname as yo,join as he,resolve as bo}from"node:path";var ko=`sandforge sync \u2014 run a Sync between two orgs, without the editor.
|
|
8
|
+
|
|
9
|
+
Usage:
|
|
10
|
+
npx sandforge sync \\
|
|
11
|
+
--source <alias> --target <alias> --object <ApiName> [options]
|
|
12
|
+
|
|
13
|
+
Required:
|
|
14
|
+
--source <alias> sf CLI alias of the source org
|
|
15
|
+
--target <alias> sf CLI alias of the target org
|
|
16
|
+
--object <ApiName> object to sync; repeat for more. The run writes the
|
|
17
|
+
parents their lookups name first, and keeps the
|
|
18
|
+
order given otherwise.
|
|
19
|
+
Append ":<Field>" to match on an external Id, which
|
|
20
|
+
turns that object's operation into an upsert.
|
|
21
|
+
|
|
22
|
+
Options:
|
|
23
|
+
--operation <op> insert | upsert | update (default: insert)
|
|
24
|
+
Per-object ":<Field>" wins over this.
|
|
25
|
+
--where <obj=clause> SOQL WHERE for one object (repeatable)
|
|
26
|
+
e.g. --where "Account=BillingCountry = 'France'"
|
|
27
|
+
--batch-size <n> records per write call (default: 200)
|
|
28
|
+
--dry-run simulate: read both orgs and say what the run
|
|
29
|
+
would insert, update, skip or refuse, writing
|
|
30
|
+
nothing (default: off)
|
|
31
|
+
--max-records-per-object <n>
|
|
32
|
+
the most records of one object the run reads, from
|
|
33
|
+
1 to 50000; an object with more is read up to it, and
|
|
34
|
+
the run says so on stderr and under readCut with
|
|
35
|
+
--json, and ends partial (default: 50000)
|
|
36
|
+
--files copy the files of the records each object writes:
|
|
37
|
+
Salesforce Files and legacy attachments, 10 MB each
|
|
38
|
+
and 100 MB a run at most unless --max-file-mb and
|
|
39
|
+
--max-run-mb say otherwise, as a configuration that
|
|
40
|
+
copies files does. The command keeps no record of
|
|
41
|
+
the files it copied: run again, it copies them
|
|
42
|
+
again (default: off)
|
|
43
|
+
--max-file-mb <n> with --files, the largest file copied, from 1 to 35;
|
|
44
|
+
a larger one is left out and counted (default: 10)
|
|
45
|
+
--max-run-mb <n> with --files, the most a run copies, from 1 to 2000;
|
|
46
|
+
the files past it are left out and counted
|
|
47
|
+
(default: 100)
|
|
48
|
+
--keep-contact-points write emails and phone numbers as read. Without
|
|
49
|
+
it, as in the panel, every address is written
|
|
50
|
+
under .invalid and every phone number as a
|
|
51
|
+
fictional one (default: off)
|
|
52
|
+
--json emit the run summary as JSON (default: off)
|
|
53
|
+
Saved to a file, it is what --remove takes the
|
|
54
|
+
run back from: it names what the run created.
|
|
55
|
+
The run's file does too, whatever becomes of the
|
|
56
|
+
run (see SANDFORGE_JOURNAL_DIR). A dry run's names
|
|
57
|
+
under wouldBeRefused what a real run would be
|
|
58
|
+
refused for, the code of each under
|
|
59
|
+
wouldBeRefusedCodes, as its line names it. A real
|
|
60
|
+
run refused before its first write prints
|
|
61
|
+
"refused": {"code", "message"} instead, the code its
|
|
62
|
+
line names: refused (CODE): ..., each other reason
|
|
63
|
+
of its gate under "alsoRefused", on a line of its own.
|
|
64
|
+
--fail-on-partial exit 3, not 0, when the run wrote some records and
|
|
65
|
+
the target refused others, or read an object up to
|
|
66
|
+
--max-records-per-object, a dry run's read
|
|
67
|
+
included (default: off)
|
|
68
|
+
--mute-automation mute the target's automation for the run through
|
|
69
|
+
its own bypass: assign the user the run writes as,
|
|
70
|
+
for the run alone, the permission sets holding the
|
|
71
|
+
custom permissions its flows, processes and
|
|
72
|
+
workflow rules test to stay quiet, and take them
|
|
73
|
+
back as it ends; what no bypass keeps quiet still
|
|
74
|
+
runs, and is named. Refused on a production org and
|
|
75
|
+
for a user who cannot assign permission sets, exit
|
|
76
|
+
1; with --dry-run, says what would be muted and
|
|
77
|
+
assigns nothing (default: off)
|
|
78
|
+
--accept-emails write although the target delivers the emails its
|
|
79
|
+
flows, processes and workflow rules send as the run
|
|
80
|
+
writes (Setup > Deliverability: All email), or would
|
|
81
|
+
not say whether it does. Read only when something
|
|
82
|
+
that still runs sends one, with one line of
|
|
83
|
+
anonymous Apex that sends nothing; without the flag
|
|
84
|
+
the run is refused, exit 1 (EMAILS_NOT_ACCEPTED),
|
|
85
|
+
nothing written. On System email only or No access
|
|
86
|
+
it is not needed. --mute-automation keeps quiet what
|
|
87
|
+
tests the org's bypass; what an Apex trigger sends is
|
|
88
|
+
read nowhere (default: off)
|
|
89
|
+
${rr({run:"the run",simulation:"--dry-run"})}
|
|
90
|
+
--help this text
|
|
91
|
+
|
|
92
|
+
Run a saved configuration:
|
|
93
|
+
npx sandforge sync \\
|
|
94
|
+
--config-file <config.json> --store <dir> --source <alias> --target <alias> \\
|
|
95
|
+
[--dry-run] [--json]
|
|
96
|
+
|
|
97
|
+
--config-file <file> a Sync configuration as the panel saves one, checked
|
|
98
|
+
as the panel checks it: its objects, filters,
|
|
99
|
+
mappings, add-ons, mode, and whether it copies files.
|
|
100
|
+
It runs between the two orgs given, whatever orgs it
|
|
101
|
+
names. In delta mode, each object reads only what the
|
|
102
|
+
source changed since its last good run. A transform
|
|
103
|
+
rule that names no field is refused before any org is
|
|
104
|
+
reached, exit 1: it would change every field of every
|
|
105
|
+
record.
|
|
106
|
+
--store <dir> where the configuration is kept between runs, with
|
|
107
|
+
its watermarks, the files it copied and which record
|
|
108
|
+
of the target each source record it wrote became, as
|
|
109
|
+
the panel keeps them beside it: give every run of it
|
|
110
|
+
the same directory, and --remove too. A later run
|
|
111
|
+
points a lookup at the copy an earlier run wrote.
|
|
112
|
+
--object, --where, --operation, --batch-size, --files, --max-file-mb,
|
|
113
|
+
--max-run-mb and --keep-contact-points come from the file (files,
|
|
114
|
+
keepContactPoints), and are refused with it. A legacy attachment the source changed since it was copied is
|
|
115
|
+
replaced, its earlier copy deleted, on a sandbox or a Developer Edition org,
|
|
116
|
+
as in the panel; a production org keeps the copy.
|
|
117
|
+
|
|
118
|
+
Remove what a run created:
|
|
119
|
+
npx sandforge sync \\
|
|
120
|
+
--remove <summary.json | run file | run id> --target <alias>
|
|
121
|
+
[--include-changed] [--accept-automation] [--store <dir>]
|
|
122
|
+
[--sweep | --sweep-list] [--sweep-late] [--sweep-untied] [--json]
|
|
123
|
+
|
|
124
|
+
--remove <file | id> the summary a run printed with --json, saved to a
|
|
125
|
+
file; or the run's file, which it names as it
|
|
126
|
+
begins, or its run id. Deletes from the target what
|
|
127
|
+
the run created: the records it inserted, or
|
|
128
|
+
upserted where the target held none, the last object
|
|
129
|
+
written first, into the target's recycle bin. Before
|
|
130
|
+
that, gives the records it wrote over \u2014 an update,
|
|
131
|
+
an upsert that found the record \u2014 the values they
|
|
132
|
+
held before the run, of the fields it wrote, which
|
|
133
|
+
the run kept first in <dir>/backups (below); one
|
|
134
|
+
changed since the run stays as it is unless
|
|
135
|
+
--include-changed. First of all, what a delta run
|
|
136
|
+
deleted as the source had is brought back from the
|
|
137
|
+
target's recycle bin, while it is there. A run
|
|
138
|
+
another process still writes is refused, exit 1.
|
|
139
|
+
From its file, a run killed,
|
|
140
|
+
stopped or ended by an error is taken back too: a
|
|
141
|
+
Bulk API job it had under way, which ran on in the
|
|
142
|
+
target, is read back by its id first, and its
|
|
143
|
+
records go with the rest.
|
|
144
|
+
--target <alias> the org the run wrote to, and no other. It must be a
|
|
145
|
+
sandbox or a Developer Edition org.
|
|
146
|
+
--include-changed remove also the records changed since the run, which
|
|
147
|
+
are kept otherwise, and give back their values from
|
|
148
|
+
before the run to the records it wrote over that
|
|
149
|
+
were changed since
|
|
150
|
+
--accept-automation remove although the target runs flows, Apex
|
|
151
|
+
triggers, processes or workflow rules as the removal
|
|
152
|
+
brings records back from the recycle bin, gives them
|
|
153
|
+
their values back, sets them back to Draft or
|
|
154
|
+
deletes them, those --sweep deletes included, or
|
|
155
|
+
could not say what it runs. Each is named before
|
|
156
|
+
anything is written; without the flag the removal
|
|
157
|
+
then writes nothing, exit 1 (default: off)
|
|
158
|
+
--mute-automation mute the target's automation for the removal through
|
|
159
|
+
its own bypass, as for a run; what no bypass keeps
|
|
160
|
+
quiet still needs --accept-automation (default: off)
|
|
161
|
+
--store <dir> for a run of a saved configuration: its store, which
|
|
162
|
+
the removal tells what it took, so that the next
|
|
163
|
+
delta run reads those objects whole and copies the
|
|
164
|
+
files it deleted again
|
|
165
|
+
--sweep before the run's records go, delete too what the
|
|
166
|
+
target's automation made for the run, that the run did
|
|
167
|
+
not write: what the run's user created under the
|
|
168
|
+
records it created or wrote over, what they point
|
|
169
|
+
at, or what hangs from those, three links at most, at
|
|
170
|
+
most a minute after the record it is tied to \u2014 in the
|
|
171
|
+
objects whose records it created and their children,
|
|
172
|
+
tasks, events, feed, email messages, notes, case
|
|
173
|
+
comments, and the objects the target's flows create.
|
|
174
|
+
What a record of the run points at by a lookup the
|
|
175
|
+
org refuses the delete for goes once that record is
|
|
176
|
+
gone. The window runs from a second
|
|
177
|
+
before the run's first write \u2014 its first call, an
|
|
178
|
+
update before anything was created included, which
|
|
179
|
+
the summary dates by this machine's clock, read on
|
|
180
|
+
the org's \u2014 to a minute after its last write: the
|
|
181
|
+
last record it created, read back from the org, or
|
|
182
|
+
a later call, an update included, as the summary
|
|
183
|
+
dates it. Listed and kept: what is tied to the run
|
|
184
|
+
but came later, up to 15 minutes, or as the org's
|
|
185
|
+
Automated Process user; and what the run's user
|
|
186
|
+
created in the window tied to nothing of the run.
|
|
187
|
+
What anyone changed more than 2 s after the run's
|
|
188
|
+
last write, and after its own creation, stays \u2014 the
|
|
189
|
+
run's user and its automation too \u2014 unless
|
|
190
|
+
--include-changed, and the sweep then ends partial,
|
|
191
|
+
exit 3; a change made before the run's last write
|
|
192
|
+
reads as unchanged
|
|
193
|
+
(default: off)
|
|
194
|
+
--sweep-late with --sweep, take too what it lists as made late;
|
|
195
|
+
with --sweep-list, say what it would take
|
|
196
|
+
--sweep-untied with --sweep, take too what it lists as tied to
|
|
197
|
+
nothing of the run; with --sweep-list, say what it
|
|
198
|
+
would take; refused when another run of this
|
|
199
|
+
machine wrote to the target in the window, or when
|
|
200
|
+
that user created records in the window on objects
|
|
201
|
+
neither the run nor the automation reaches (hand
|
|
202
|
+
work, likely)
|
|
203
|
+
--sweep-list list what --sweep would delete, per object with a few
|
|
204
|
+
names and how many it ties to the run, and delete
|
|
205
|
+
nothing, the run's records included; exit 3, as a
|
|
206
|
+
refused --sweep, when it says the sweep is refused.
|
|
207
|
+
What a sweep leaves: what another user created; what
|
|
208
|
+
is tied to nothing, unless --sweep-untied; what came
|
|
209
|
+
more than 15 minutes after its record, or after the
|
|
210
|
+
removal began; what anyone changed after the run's
|
|
211
|
+
last write, the run's own user included, unless
|
|
212
|
+
--include-changed; what the automation changed
|
|
213
|
+
rather than created; what left the org; and what the
|
|
214
|
+
panel or another machine wrote
|
|
215
|
+
--leave-undeletable remove the rest when the user the removal runs as
|
|
216
|
+
may not delete the records of some objects of the
|
|
217
|
+
run, leaving those with what they hang from; without
|
|
218
|
+
it the removal stops before its first delete and
|
|
219
|
+
names them (default: off)
|
|
220
|
+
--json print the removal as JSON; refused before its first
|
|
221
|
+
write, "refused": {"code", "message"}, the code its
|
|
222
|
+
line names: refused (CODE): ... \u2014 a production org
|
|
223
|
+
(PRODUCTION_TARGET), what fires as it writes
|
|
224
|
+
(AUTOMATION_NOT_ACCEPTED), its mute (MUTE_PRODUCTION,
|
|
225
|
+
MUTE_NO_RIGHT, MUTE_FAILED), objects its user may not
|
|
226
|
+
delete (UNDELETABLE_NOT_LEFT), an org that is not the
|
|
227
|
+
one the run wrote to (OTHER_ORG), a run still writing
|
|
228
|
+
(RUN_WRITING)
|
|
229
|
+
|
|
230
|
+
What the removal left on the run's records is kept beside the summary, in
|
|
231
|
+
<summary>.removals.json, or beside the run's file, in <run id>.removal.json,
|
|
232
|
+
and the next --remove of the same summary or file reads it.
|
|
233
|
+
|
|
234
|
+
Environment:
|
|
235
|
+
SANDFORGE_JOURNAL_DIR=<dir>
|
|
236
|
+
where every run that writes keeps its file, in
|
|
237
|
+
<dir>/sync-runs/<run id>.ndjson (default: ~/.sandforge),
|
|
238
|
+
said as it begins: what it created, its calls as
|
|
239
|
+
they went and answered, a Bulk API job's id once the
|
|
240
|
+
org opened it, and how it ended. Ids and dates only.
|
|
241
|
+
What a run writes over \u2014 an update, an upsert that
|
|
242
|
+
finds the record \u2014 is read from the target first and
|
|
243
|
+
kept in <dir>/backups, readable by you alone, as
|
|
244
|
+
sandforge backup keeps a snapshot: the values the
|
|
245
|
+
records held, of the fields the run writes, which
|
|
246
|
+
--remove gives back. A call whose values cannot be
|
|
247
|
+
kept is not sent, its rows refused with why.
|
|
248
|
+
|
|
249
|
+
Before its first write, a run counts the records it writes under each filter,
|
|
250
|
+
and is refused, with nothing written, when they would take more data storage
|
|
251
|
+
than the target has left, or make the target's automation send more emails
|
|
252
|
+
than it has left today; --dry-run says what it would meet. A run of a saved
|
|
253
|
+
configuration leaves as they are the records an earlier run of it copied that
|
|
254
|
+
are still in the target, and inserts the others.
|
|
255
|
+
|
|
256
|
+
Exit codes: 0 the run finished, some of its records refused included (read
|
|
257
|
+
the summary for per-object failures), or the removal took every record it set
|
|
258
|
+
out to; 1 the run or the removal could not be started, either was refused
|
|
259
|
+
before it wrote anything \u2014 a production target among the reasons; for the
|
|
260
|
+
run, more data storage than the target has left, more emails or API requests
|
|
261
|
+
than it has left today, emails it delivers without --accept-emails
|
|
262
|
+
(EMAILS_NOT_ACCEPTED), a checkpoint asked first refused or not taken
|
|
263
|
+
(CHECKPOINT_REFUSED); for the removal, what the target runs as it writes,
|
|
264
|
+
without --accept-automation \u2014 or the run produced only failures, or it
|
|
265
|
+
stopped on an error (its file keeps what it created); 2 a bad command line,
|
|
266
|
+
or a summary or a file --remove cannot take a run back from; 3 the removal
|
|
267
|
+
left records of the run in the target, or its sweep was refused or did not
|
|
268
|
+
take all it was asked to (a --sweep-untied refused included), or the run was
|
|
269
|
+
partial \u2014 records refused, or an object read up to --max-records-per-object,
|
|
270
|
+
a dry run's read among them \u2014 and --fail-on-partial was given; 130 a Ctrl-C
|
|
271
|
+
stopped the run, 143 a SIGTERM (a CI job cancelled or timed out), 129 a
|
|
272
|
+
SIGHUP: its file keeps what it created.
|
|
273
|
+
`,So=["--object","--where","--operation","--batch-size","--files","--max-file-mb","--max-run-mb","--keep-contact-points"],_=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,vo=new Set(["SYNC_TARGET_UNWRITABLE",fe,it]),$o={switches:["--dry-run","--files","--keep-contact-points","--json","--fail-on-partial","--mute-automation","--accept-emails",...at.switches],values:["--source","--target","--object","--operation","--where","--batch-size","--max-records-per-object","--max-file-mb","--max-run-mb","--config-file","--store",...at.values]};function bt(t,r,e,n){if(t===void 0)return n;let s=Number(t);return(!/^\d+$/.test(t)||s<e.min||s>e.max)&&(process.stderr.write(`${r} takes a whole number from ${e.min} to ${e.max}, not "${t}".
|
|
274
|
+
`),process.exit(2)),s}function Ao(t){let r=t.slice(2);(r.includes("--help")||r.includes("-h"))&&(process.stdout.write(ko),process.exit(0)),Ht(r,$o);let e=(S,$)=>{let b=r.indexOf(S);return b>=0&&b+1<r.length?r[b+1]:$},n=S=>{let $=[];for(let b=0;b<r.length;b++)r[b]===S&&b+1<r.length&&$.push(r[b+1]);return $},s=S=>r.includes(S),i=or(r),d=i!==void 0?{checkpointFirst:i}:{},u=bt(e("--max-records-per-object"),"--max-records-per-object",{min:1,max:5e4},5e4),l=e("--source"),a=e("--target");if(s("--config-file")){let S=e("--config-file"),$=e("--store");(!S||!$||!l||!a)&&(process.stderr.write(`--config-file wants the file, --store <dir> where it is kept between runs, --source and --target. Run with --help.
|
|
275
|
+
`),process.exit(2));let b=So.filter(s);return b.length>0&&(process.stderr.write(`--config-file takes its objects, filters and files from the file: ${b.join(", ")} cannot be given with it.
|
|
276
|
+
`),process.exit(2)),{source:l,target:a,objects:[],operation:"insert",where:{},batchSize:200,dryRun:s("--dry-run"),files:!1,maxRecordsPerObject:u,keepContactPoints:!1,json:s("--json"),failOnPartial:s("--fail-on-partial"),muteAutomation:s("--mute-automation"),acceptEmails:s("--accept-emails"),...d,configFile:S,store:$}}s("--store")&&(process.stderr.write(`--store keeps a saved configuration between runs: give it with --config-file.
|
|
277
|
+
`),process.exit(2));let f=n("--object");(!l||!a||f.length===0)&&(process.stderr.write(`Missing --source, --target or --object. Run with --help.
|
|
278
|
+
`),process.exit(2));let g=f.map(S=>{let[$,b]=S.split(":");return _.test($)||(process.stderr.write(`Not an SObject API name: "${$}"
|
|
279
|
+
`),process.exit(2)),ln($)&&(process.stderr.write(`${fn($,"give --files")}
|
|
280
|
+
`),process.exit(2)),b!==void 0&&!_.test(b)&&(process.stderr.write(`Not a field API name: "${b}"
|
|
281
|
+
`),process.exit(2)),{objectApiName:$,externalIdField:b}}),v=e("--operation","insert")??"insert";v!=="insert"&&v!=="upsert"&&v!=="update"&&(process.stderr.write(`--operation takes insert, upsert or update, not "${v}".
|
|
282
|
+
`),process.exit(2));let k={};for(let S of n("--where")){let $=S.indexOf("="),b=$>0?S.slice(0,$):"";_.test(b)||(process.stderr.write(`--where wants "Object=clause", not "${S}".
|
|
283
|
+
`),process.exit(2)),k[b]=S.slice($+1)}let y=e("--batch-size","200")??"200",j=Number(y);(!Number.isInteger(j)||j<1||j>1e4)&&(process.stderr.write(`--batch-size takes a whole number between 1 and 10000.
|
|
284
|
+
`),process.exit(2)),!s("--files")&&(s("--max-file-mb")||s("--max-run-mb"))&&(process.stderr.write(`--max-file-mb and --max-run-mb go with --files.
|
|
285
|
+
`),process.exit(2));let I=bt(e("--max-file-mb"),"--max-file-mb",{min:1,max:35}),U=bt(e("--max-run-mb"),"--max-run-mb",{min:1,max:2e3});return{source:l,target:a,objects:g,operation:v,where:k,batchSize:j,dryRun:s("--dry-run"),files:s("--files"),...I!==void 0?{maxFileMB:I}:{},...U!==void 0?{maxRunMB:U}:{},maxRecordsPerObject:u,keepContactPoints:s("--keep-contact-points"),json:s("--json"),failOnPartial:s("--fail-on-partial"),muteAutomation:s("--mute-automation"),acceptEmails:s("--accept-emails"),...d}}function Oo(t){let r=new Date().toISOString(),e=t.objects.map((n,s)=>({objectApiName:n.objectApiName,externalIdField:n.externalIdField,operation:n.externalIdField?"upsert":t.operation,fieldMappings:[],transformRules:[],excludedFields:[],addOnFields:[],batchSize:t.batchSize,where:t.where[n.objectApiName],insertOrder:s}));return{id:`cli-${Date.now()}`,name:"sandforge-sync",description:"Headless run",sourceOrgId:t.source,targetOrgId:t.target,direction:"source_to_target",mode:"full",objects:e,conflictStrategy:"source_wins",enableRollback:!1,createdAt:r,updatedAt:r,...t.files?{files:{maxFileSizeMB:t.maxFileMB??10,maxRunMB:t.maxRunMB??100}}:{},...t.keepContactPoints?{keepContactPoints:!0}:{}}}function jo(t,r){let e;try{e=JSON.parse(t)}catch{return{refusal:"is not JSON: give a Sync configuration as the panel saves one."}}if(typeof e!="object"||e===null||Array.isArray(e))return{refusal:"is not a Sync configuration: it holds no object."};let n=hn.safeParse({config:{...e,sourceOrgId:r.source,targetOrgId:r.target}});if(!n.success){let d=n.error.issues[0];return{refusal:`is not a configuration a run takes (${d.path.slice(1).join(".")||"configuration"}: ${d.message})`}}let s=n.data.config;if(s.id===void 0)return{refusal:"names no id: a saved configuration keeps its watermarks and the files it copied under its id."};let i=new Date().toISOString();return{config:{...s,id:s.id,createdAt:s.createdAt??i,updatedAt:s.updatedAt??i,objects:s.objects.map(d=>({...d,batchSize:d.batchSize??200}))}}}function Qr(t){return go(t,{recursive:!0}),new xr(Le(he(t,"configStore.json")))}function Co(t,r,e,n,s=!1,i=5e4){let d=a=>({query:async f=>a.query(f),queryMore:async f=>a.queryMore(f)}),u=a=>({pages:d(a),transport:a,create:async(f,g)=>a.sobject(f).create(g,{headers:Lt()})}),l=new Map;return{copy:Cr({[t.sourceOrgId]:u(r),[t.targetOrgId]:u(e)}),sourceIds:async(a,f)=>{let g=a.objectApiName;if(!_.test(g))throw new Error(`Not an SObject API name: ${g}`);let v=ue(a.where,f),{records:k}=await te(d(r),`SELECT Id FROM ${g}${v?` WHERE ${v}`:""}`,i);return k.flatMap(y=>typeof y.Id=="string"?[y.Id]:[])},store:n??{load:()=>l.size===0?{kind:"none"}:{kind:"stored",map:{version:1,entries:[...l.values()]}},record:(a,f)=>{l.set(`${f.sourceOrgId}|${f.targetOrgId}|${f.sourceId}`,f)}},...s?{deleteFromTarget:async(a,f)=>pn(await e.sobject(a).destroy(f),a).map(g=>({id:g.id,success:g.success,errors:g.errors}))}:{}}}function xo(t){let r=Ke({isSandbox:t.sandbox,edition:t.edition});return jr(new In,t.id,{orgType:r})}function Vr(t,r=5e4,e){return async(n,s,i)=>{let d=s.objectApiName;if(!_.test(d))throw new Error(`Not an SObject API name: ${d}`);let u=ue(s.where,i?.changedSince),l=u?` WHERE ${u}`:"",a={query:async y=>t.query(y),queryMore:async y=>t.queryMore(y)},g=(await t.sobject(d).describe()).fields.filter(y=>y.type!=="address"&&y.type!=="location").map(y=>y.name),v=!1,k=await rn(`SELECT ${(g.length>0?g:["Id"]).join(", ")} FROM ${d}${l}`,async y=>{let j=await te(a,y,r);return v||=j.truncated,j.records});return v&&(i?.onBoundReached?.(),e?.(d,k.length)),k}}function Io(t,r){let e=`${_t("clone")} --depth all --source ${r.source} --target ${r.target} --fit share --dry-run`;return t.map(n=>`${n.objectApiName}: the read of the source stopped at ${n.read} records (--max-records-per-object ${n.bound}): this run copied part of the object. `+_r("source",n.bound,{raise:"--max-records-per-object",sample:e}))}function Rt(t,r){return t==="success"&&r.length>0?"partial":t}function Eo(t,r){return async(e,n,s)=>{let i=n.objectApiName;if(!_.test(i))throw new Error(`Not an SObject API name: ${i}`);let d=ue(n.where,s?.changedSince),{totalSize:u}=await t.query(`SELECT COUNT() FROM ${i}${d?` WHERE ${d}`:""}`);return r===void 0?u:Math.min(u,r)}}function To(t){return async(r,e)=>{let n=r.objectApiName;if(!_.test(n))return 0;let s=ue(r.where,e?.changedSince);try{return(await t.query(`SELECT COUNT() FROM ${n} WHERE IsPersonAccount = true`+(s?` AND (${s})`:""))).totalSize}catch{return 0}}}function Fo(t){return async r=>{let e=r.objectApiName;if(!_.test(e))throw new Error(`Not an SObject API name: ${e}`);let n=ue(r.where,void 0),{records:s}=await te({query:async i=>t.query(i),queryMore:async i=>t.queryMore(i)},`SELECT Id FROM ${e}${n?` WHERE ${n}`:""}`);return s.flatMap(i=>typeof i.Id=="string"?[i.Id]:[])}}function Xr(t){if(t.go||t.code!==fe&&t.code!==Xe)return t;let{code:r,message:e,refusal:n}=t;return{...t,message:dr({code:r,message:e,...n?{refusal:n}:{}})}}var Po={notInTarget:"it has no such object, or the user the run writes as cannot see it",notCreateable:"the user the run writes as may not create its records",notUpdateable:"the user the run writes as may not edit its records",unread:"it did not describe the object",notAKey:"its upsert matches on a field that is neither an External ID nor an idLookup field"};function kt(t,r){return{...t??{},sent:r}}function eo(t,r){let e=t.notWritten??0,n=t.total>0?t.total:e,s=[`write gate: ${n-e} record(s) to write to ${r}, about ${Jn(t.storage.estimateMB)} MB of data storage`];for(let a of t.objects)s.push(` ${a.objectApiName.padEnd(42)}${String(a.rows).padStart(8)}`);e>0&&s.push(` of the ${n} a run counts from the source, ${e} would not be written: held back or refused, as each object says; what follows is measured on all of them`),t.alreadyCopied>0&&s.push(` not counted: ${t.alreadyCopied} record(s) an earlier run of this configuration copied, still in the target, left as they are`),(t.alreadyLinked??0)>0&&s.push(` not counted: ${t.alreadyLinked} record(s) an earlier run of this configuration linked to records the target held, left as they are`),(t.overwrites??0)>0&&s.push(` of them, up to ${t.overwrites} written by an update or an upsert over records ${r} holds: their values are kept first, and --remove puts them back`),(t.rolesLinked??0)>0&&s.push(` not counted: ${t.rolesLinked} OpportunityContactRole record(s) the platform writes itself with the opportunities the run creates, for their contact: the run links each and does not send it`),(t.rolesByThePlatform??0)>0&&s.push(` of them, up to ${t.rolesByThePlatform} OpportunityContactRole record(s) the platform writes itself with the opportunities the run creates, for their contact: the run links each and does not send it`);let{storage:i}=t;i.verdict==="unread"?s.push(` the data storage ${r} has left could not be read (${i.unread??""}): whether the records fit is not known`):i.remainingMB!==void 0&&i.maxMB!==void 0&&s.push(` data storage of ${r}: ${i.remainingMB} MB left of ${i.maxMB} MB`+(i.verdict==="exceeds"?": the records do not fit":i.verdict==="near"?": the records take more than 80 % of it":""));for(let a of t.emails){let f=a.objects.map(v=>`${v.perRecord} per ${v.objectApiName}`).join("; "),g=` emails: these records make ${r} send about ${Gn(a.emails,a.limit)} (${f})`+(a.alertsCounted?", its email alerts among them, as a Developer Edition counts them":"");s.push(a.verdict==="unread"?`${g}; what it has left today could not be read (${a.unread??""})`:a.verdict==="fits"?`${g}; it has ${a.remaining??"?"} of ${a.max??"?"} left today`:`${g}, more than the ${a.remaining??"?"} of ${a.max??"?"} it has left today`)}t.emailsUnread!==void 0&&s.push(` emails: not counted, ${t.emailsUnread} could not be read`),t.deliverability&&s.push(` ${zn(t.deliverability.reading)}`);let d=t.apiRequests;d&&(s.push(d.verdict==="unread"?` API requests: about ${d.estimate}; what ${r} has left today could not be read (${d.unread??""})`:` API requests: about ${d.estimate}, of the ${d.remaining??"?"} ${r} has left of its ${d.max??"?"} a day`+(d.verdict==="exceeds"?": more than it has left":d.verdict==="near"?": it would leave less than a tenth of them":"")),s.push(` ${Nn}`));for(let a of t.unwritable??[])s.push(` ${a.objectApiName}: ${a.rows} record(s) ${r} takes none of \u2014 ${Po[a.why]}${a.key!==void 0?` (${a.key})`:""}`);let u=new Set((t.unwritable??[]).map(({objectApiName:a})=>a)),l=({parent:a,field:f})=>`${f} names ${a} records ${u.has(a)?"left out":"held back"}`;for(let a of t.heldBack??[]){let f=a.parents??[a];s.push(` ${a.objectApiName}: ${a.rows} record(s) held back, not written \u2014 `+(f.length===1?`their ${l(f[0])}`:f.map(g=>`${g.rows} whose ${l(g)}`).join("; ")))}return t.aboveRecords!==void 0&&s.push(` more than ${t.aboveRecords} records: the panel asks before it writes (sandforge.safety.confirmAboveRecords)`),s}function to(t,r,e=!1){let n=t.flatMap(i=>i.recordTypeGiven?[i.recordTypeGiven]:[]),s=hr(n,r);return s.length>0&&r&&e&&s.push(" the permission sets a real run assigns to mute the automation may open other record types to the user it writes as: it reads them again once assigned, and its summary says what the target gave"),s}function no(t){return`${t} already linked by an earlier run of this configuration to records the target held, left as they are`}function No(t,r="the target",e=!1,n,s){let i=[`
|
|
286
|
+
simulation: ${t.objects.length} object(s), nothing written`];if(t.writeOrder){i.push(` write order: ${t.writeOrder.objects.join(", ")}`);for(let d of t.writeOrder.moved)i.push(` ${d.objectApiName} after ${d.after}: its ${d.field} names one`);for(let d of t.writeOrder.cycles)i.push(` ${d.join(", ")} name each other: in this order, the lookup at the one written later is left empty`)}if(t.writeCheck){for(let u of eo(t.writeCheck,r))i.push(` ${u}`);for(let u of t.checkpoint?dt(t.checkpoint):[])i.push(` ${u}`);if(t.writeCheck.verdict==="refused"){let u=t.writeCheck,[l,a]=(u.unwritable??[]).length>0?["SYNC_TARGET_UNWRITABLE","the target takes none of the records of an object it writes"]:n!==void 0?[fe,n]:u.storage.verdict==="exceeds"?["SYNC_STORAGE_EXCEEDED","the records do not fit"]:u.apiRequests?.verdict==="exceeds"?[Bn,"it takes more API requests than the target has left today"]:[fe,u.checkpointUnread??"the checkpoint asked first is refused"];i.push(` a run would be refused before it writes (${l}): ${a}`)}else(t.writeCheck.unwritable??[]).length>0&&i.push(" a run of the command would be refused before it writes (SYNC_TARGET_UNWRITABLE): the target takes none of the records of an object it writes; leave it out of the configuration");let d=t.writeCheck.emails.some(u=>u.verdict==="exceeds");t.writeCheck.verdict!=="refused"&&d?i.push(" a run of the command would be refused before it writes (SYNC_EMAILS_EXCEEDED): past a daily email limit"):t.writeCheck.verdict!=="refused"&&s!==void 0&&i.push(` a run of the command would be refused before it writes (${it}): `+s)}t.writeCheckUnread!==void 0&&i.push(` the records to write could not be counted: ${t.writeCheckUnread}`);for(let d of t.objects){i.push(` ${d.objectApiName} (${d.operation}): ${d.read} read, would insert ${d.insert}, update ${d.update}, delete ${d.delete}, skip ${d.skipped}, refuse ${d.refused}`+(t.direction==="bidirectional"?`, ${d.conflicts} in conflict`:"")),d.alreadyCopied!==void 0&&i.push(` ${d.alreadyCopied} already copied by an earlier run of this configuration, left as they are`),d.alreadyLinked!==void 0&&i.push(` ${no(d.alreadyLinked)}`),(d.encryptedLeftOut??[]).length>0&&i.push(` ${ro(d.encryptedLeftOut??[])}`),d.conflictFields.length>0&&i.push(` differ on: ${d.conflictFields.join(", ")}`),d.files&&i.push(` files: would copy ${d.files.copied}, add ${d.files.versions} version(s), ${d.files.unchanged} unchanged, ${d.files.tooLarge+d.files.pastRunCap} skipped past the caps`);for(let u of d.notes)i.push(` ${u}`);if(d.validationRules&&d.validationRules.length>0){i.push(` ${d.validationRules.length} active validation rule(s) of the target, which a simulation cannot evaluate \u2014 a record one of them refuses is counted as written:`);for(let u of d.validationRules)i.push(` ${u.name}${u.field?` (${u.field})`:""}: ${u.message||"(no message)"}`)}}t.validationRulesUnread&&i.push(` the target's validation rules could not be listed (${t.validationRulesUnread}): any of them may refuse a record counted as written`);for(let d of to(t.objects,!0,e))i.push(` ${d}`);return t.cancelled&&i.push(" stopped by a cancel before its last object"),t.error&&i.push(` stopped at ${t.failedObject??"an object"}: ${t.error}`),i}var Mo=/^(PARENT_REFUSED|RECORD_TYPE_UNAVAILABLE|RECORD_TYPE_UNMAPPED):/;function _o(t){let r=t.slice(0,3);for(let e of t.slice(3))Mo.test(e)&&r.push(e);return r}var Lo={notInTarget:": the lookup held an id from the source org that the target does not have.",ownerRefusedEarlier:", left out from the start: the target refused the same owner earlier in this run, an id from the source org that the target does not have.",parentRefused:": the record it names, written after them, was refused in this run.",notSet:": the target refused setting it once the record it names was written",notReached:": the run was stopped before it was set, once the record it names was written."},Do={"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 Wo(t){let r=Uo(t),e=Math.max(0,(t.skipped??0)-r);return`${t.objectApiName}: ${t.processed??0} processed, ${t.success??0} succeeded, ${t.failed??0} failed, ${e} skipped`+(r>0?`, ${r} linked`:"")}function Uo(t){return(t.writtenByThePlatform?.records??0)+(t.linkedToExisting?.records??0)}function Bo(t){let r=[];(t.encryptedLeftOut??[]).length>0&&r.push(ro(t.encryptedLeftOut??[]));let e=t.linkedToExisting;e&&r.push(`${e.records} record(s) linked to a record the target holds, not written: the target refused them as a duplicate of it${e.refusal?` (${e.refusal})`:""}; what the run writes under them points at that record.`);let n=t.writtenByThePlatform;n&&r.push(`${n.records} record(s) linked to the contact role the platform wrote with their opportunity, for its contact, not written; ${n.given} given the source's fields ${n.given===1?"it":"they"} lacked`+(n.refusal?`, the others left as the platform wrote them (${n.refusal}).`:"."));for(let{records:d,fields:u,reason:l,refusal:a}of t.lookupsLeftOut??[]){let f=l==="notSet"?`${a?` (${a})`:""}.`:"";r.push(`${d} record(s) written without ${u.join(", ")}${Lo[l]}${f}`)}let s=t.lookupsSetAfter;s&&r.push(`${s.records} record(s) given ${s.fields.join(", ")} by a second write once ${s.after.join(", ")} ${s.after.length===1?"was":"were"} written: the objects name each other, and no order writes both first.`);let i=t.writtenWithoutFields;return i&&r.push(`${i.rows} record(s) written again without the fields the target refused them on:`,...i.fields.map(({field:d,rows:u,refusedBy:l="validation-rule",reason:a})=>` ${u} without ${d}: ${Do[l]}, ${a}`)),r}function ro(t){return`${t.join(", ")}: encrypted, and read masked by the user the source is read as (it lacks View Encrypted Data): left out of every record written, never copied as masks`}function qo(t){return t?t.neutralized?[`emails and phone numbers: ${t.values} value(s) in ${t.fields.length} field(s) neutralized, addresses under .invalid and numbers fictional, so what the target's automation sends to them reaches no one`,...t.fields.map(({objectApiName:r,field:e,values:n})=>` ${r}.${e} ${n}`),...t.numbersExhausted?[` ${t.numbersExhausted} phone number(s) left out, their field empty: the 10 000 fictional numbers were all given to other numbers of the run`]:[]]:["emails and phone numbers: written as read (--keep-contact-points): the target's automation may have emailed or texted the people the records name"]:[]}function Go(t){return(t??[]).map(r=>`${sn(r)}.`)}function zo(t,r=!1){return[...r?[Dr]:[],...Vn(t??[]).map(e=>`${e}.`)]}function Jo(t){let r=t.read==="delta"?`delta: ${t.changed} record(s) changed since ${t.since??"the last run"}`:`delta: read whole (${t.reason??"no watermark"}), ${t.changed} record(s)`,e=t.deletionsChecked?`, ${t.deleted} deleted as the source deleted them`+(t.deleteFailed>0?`, ${t.deleteFailed} refused`:""):"",n=t.recorded!==void 0?"; watermark recorded":"; watermark kept as it was: the next run reads from the same point",s=(t.lookupsOwed??0)>0?`, ${t.lookupsOwed} record(s) left without a lookup this run was to set among them`:"";return`${r}${e}${n}${s}`}function Ho(t){let r=new Map,e=new On,n=new Map,s=new Set,i,d,u,l=a=>{if(a<=0)return;let f=new Date().toISOString();d??=f,u=f};return{runId:t,sending:(a,f)=>l(f),writing:(a,f)=>l(f),answered:()=>{u=new Date().toISOString()},note:(a,f)=>{if(f.length===0)return;let g=f.filter(v=>{let k=v.slice(0,15);return s.has(k)?!1:(s.add(k),!0)});g.length>0&&r.set(a,[...r.get(a)??[],...g]),i=new Date().toISOString(),d??=i,u=i},touched:(a,f)=>{f<=0||(i=new Date().toISOString(),u=i)},overwriting:(a,f,g)=>{g.length!==0&&(e.candidates(a,f,g),l(g.length))},overwrote:(a,f)=>{e.answer(a,f),u=new Date().toISOString()},deleted:(a,f)=>{if(f.length===0)return;let g=n.get(a)??new Map;for(let v of f)g.has(v.slice(0,15))||g.set(v.slice(0,15),v);n.set(a,g),l(f.length)},overwrittenCount:()=>e.count,flush:async()=>{},created:()=>[...r].map(([a,f])=>({objectApiName:a,ids:[...f]})),lastWrittenAt:()=>i,firstWrittenAt:()=>d,lastWriteAt:()=>u,overwritten:()=>e.read(),deletions:()=>[...n].map(([a,f])=>({objectApiName:a,ids:[...f.values()]}))}}function Ko(t,r){return r?{runId:t.runId,note:(e,n,s)=>{t.note(e,n,s),r.note(e,n,s)},noteUnanswered:(e,n)=>{t.note(e,n),r.noteUnanswered?r.noteUnanswered(e,n):r.note(e,n)},sending:(e,n,s)=>{t.sending?.(e,n,s),r.sending?.(e,n,s)},answered:(e,n)=>{t.answered?.(e,n),r.answered?.(e,n)},writing:(e,n)=>{t.writing?.(e,n),r.writing?.(e,n)},touched:(e,n)=>{t.touched?.(e,n),r.touched?.(e,n)},overwriting:(e,n,s,i)=>{t.overwriting?.(e,n,s),r.overwriting?.(e,n,s,i)},overwrote:(e,n)=>{t.overwrote?.(e,n),r.overwrote?.(e,n)},deleted:(e,n)=>{t.deleted?.(e,n),r.deleted?.(e,n)},checkpoint:e=>{t.checkpoint?.(e),r.checkpoint?.(e)},overwrittenCount:()=>t.overwrittenCount?.()??r.overwrittenCount?.()??0,flush:async()=>await t.flush()??await r.flush()}:t}var St="sandforge-sync";function Yo(t,r){let e=new Set(r);return{...t,objectsRead:t.objectsRead.filter(n=>e.has(n)),objects:t.objects.filter(n=>e.has(n.objectApiName))}}async function Vo(t){try{let e=(await t.query("SELECT Id FROM Organization LIMIT 1")).records[0]?.Id;return typeof e=="string"?e:void 0}catch{return}}async function Xo(t=process.argv){if(t.slice(2).includes("--remove"))return gs(t);let r=Date.now(),e=Ao(t),n=o=>{e.json||process.stdout.write(`${o}
|
|
287
|
+
`)},s=o=>{process[e.json?"stderr":"stdout"].write(`${o}
|
|
288
|
+
`)},i,d;if(e.configFile!==void 0&&e.store!==void 0){let o;try{o=$e(e.configFile,"utf8")}catch(w){process.stderr.write(`--config-file ${e.configFile} cannot be read: ${w instanceof Error?w.message:String(w)}
|
|
289
|
+
`),process.exit(2)}let c=jo(o,e);"refusal"in c&&(process.stderr.write(`--config-file ${e.configFile} ${c.refusal}
|
|
290
|
+
`),process.exit(2));let p=Ut(c.config.objects);p.length>0&&(process.stderr.write(`--config-file ${e.configFile}: ${Bt(p)} Nothing was read or written.
|
|
291
|
+
`),process.exit(1)),i=c.config,d=Qr(e.store),d.save(i)}else i=Oo(e);n(`sandforge sync ${e.source} -> ${e.target}`),n(`objects: ${i.objects.map(o=>o.objectApiName).join(", ")}`+(d?` (configuration ${i.id}, ${i.mode})`:""));let u=Se(await xe(e.source)),l=await xe(e.target),a=Se(l),f=[Ye(a)],g=()=>f.reduce((o,c)=>o+c(),0),v=new Map,k=new AbortController,y=e.dryRun?await ke(a).catch(()=>{}):await Kt(a,e.target,{tool:"sandforge sync",action:"write",readOnly:"--dry-run"}),j=`sandforge-sync-${po()}`,I=Ho(j),U=e.dryRun?void 0:Qe(De()),S=U?.recorder({runId:j,configId:d?i.id:St,configName:d?i.name:St,sourceOrgId:e.source,targetOrgId:y?.id??e.target,targetAlias:e.target,...y?{targetOrganizationId:y.id}:{}});nr(S,()=>a.identity(),"sandforge sync");let $=!1,b=()=>{let o=U?.pathOf(j);$||o===void 0||($=!0,s(`run file: ${o} (--remove ${o} takes back what the run creates)`))},J=Ko(I,S),N=S?{...J,note:(o,c,p)=>{b(),J.note(o,c,p)},sending:(o,c,p)=>{b(),J.sending?.(o,c,p)}}:J,H=e.checkpointFirst?ir({module:"sync",operationId:j,request:e.checkpointFirst,session:l,org:sr(l,y??await ke(a)),connect:o=>{let c=Se(o);return f.push(Ye(c)),c},journalDir:De(),say:s,own:{runId:j}}):void 0,X=async o=>{let c=v.get(o);if(c)return c;let p=await a.sobject(o).describe(),w=gt(p);return v.set(o,w),w},L=i.objects.some(o=>o.operation==="update"||o.operation==="upsert"),K=ht(),D;if(!e.dryRun&&L){let o=pt(K);o!==void 0&&(process.stderr.write(`${o} What the run would write over could not be kept, so nothing was written.
|
|
292
|
+
`),process.exit(1)),D=Fr({runId:j,orgId:e.target,...y?{organizationId:y.id}:{},files:new st(ot(K)),meta:Le(he(K,"snapshots.json"))})}let B=async o=>(await te({query:async c=>a.query(c),queryMore:async c=>a.queryMore(c)},o)).records,Ae=D?Pr({query:B,backup:D,recorder:N,describe:o=>X(o),viewsEncrypted:rt(B)}):void 0,W=new Ur({connection:a,bulkExecutor:new gn,bulkManager:new nn,retryConfig:{},signal:k.signal,onProgress:(o,c,p)=>n(` ${p}: ${o}/${c}`),log:n,calls:Wr(N,Ae)}),ne=!1,F=async(o,c,p,w,P)=>{if(e.dryRun)throw new Error(`A dry run writes nothing: ${o} ${c} refused.`);return b(),p.length>0&&(ne=!0),o==="delete"?W.delete(c,p,w):o==="upsert"?W.upsert(c,P??"Id",p,w):o==="update"?W.update(c,p,w):W.insert(c,p,w)},C=new Date().toISOString(),q,E,pe,G,Oe=zr(i,async o=>(await a.query(o)).totalSize),M={readStorage:()=>Wn(a),readApiBudget:()=>Un(a),readAutomation:o=>We(a).read(e.target,o),readLimits:()=>qn(a),readDeliverability:async()=>Jt(y??await ke(a))?Tn:Fn(a),emails:{target:e.target,accepted:e.acceptEmails,keepsAddresses:i.keepContactPoints===!0,mayMute:!e.muteAutomation},confirmAboveRecords:Dn,sentBefore:()=>g()+(e.dryRun?tr:0),...Oe?{countTarget:Oe}:{},...H?{checkpointFirst:{scope:async(o,c)=>(q={written:o,running:c},E=await H.scope(q),E),take:async o=>{if(!q)throw new Error("its scope was not read");let c=await H.take(q,o,{signal:k.signal});if(c.taken){pe=c.checkpoint,N.checkpoint?.(c.checkpoint);for(let p of cr(c.checkpoint,e.target,e.muteAutomation))s(p)}return c}}}:{}},re=y?Wt({orgType:Ke({isSandbox:y.sandbox,edition:y.edition}),metadata:{edition:y.edition}}):"production",Z,ge,oe,me=[],se=[],h=o=>{let c=Xr({go:!1,...o});return c.go?o:{code:c.code,message:c.message}},m=(o,c)=>({measure:async p=>{let w=await mt(p,{...M,readAutomation:o,...c?{mutePlan:c}:{}});ge=w.checkpointFailed,oe=w.runEmails?.gate.stop;let P=wt(w,{policy:"refuse",org:e.target});return me=P.filter(V=>!vo.has(V.code)).map(({code:V,message:Re})=>({code:V,message:Re})),e.dryRun||(se=P.map(h)),w.check},hold:async p=>{let w=await mt(p,{...M,readAutomation:o,...c?{mutePlan:c}:{}});Z=w.check,n("");for(let ce of eo(w.check,e.target))n(ce);for(let ce of w.checkpoint?dt(w.checkpoint):[])s(ce);let P=await Jr(w,{policy:"refuse",org:e.target,orgTier:re}),[V,...Re]=wt(w,{policy:"refuse",org:e.target});return se=!P.go&&V?.code===P.code?Re.map(h):[],{check:w.check,answer:Xr(await Kr(w,P,M.checkpointFirst))}}}),O=e.muteAutomation&&!e.dryRun?Yr(m,M.readAutomation,async o=>{let c=await _e(async()=>Ne(a),o,{writes:yt});for(let p of le(c.muted,e.target))n(` ${p}`);return c},`sandforge sync ${j}`,{target:e.target}):void 0,A,x,Q=()=>A??=(async()=>{let o=i.objects.map(p=>p.objectApiName),c=await M.readAutomation(o).catch(p=>({unread:p instanceof Error?p.message:String(p)}));try{let p=await _e(async()=>Ne(a),c,{writes:yt});for(let w of le(p.muted,e.target))n(w);return x=p,{planned:p}}catch(p){if(!Me(p))throw p;return n(Xt(p.refusal)),{refused:p.refusal}}})(),ie=async o=>{let c=(await Q()).planned?.automation;return c&&o.every(p=>c.objectsRead.includes(p))?Yo(c,o):M.readAutomation(o)},we=O?.gate??(e.dryRun&&e.muteAutomation?m(ie,()=>x?.plan):m(M.readAutomation)),T={measure:o=>we.measure(o),hold:async o=>{let c=await we.hold(o);return c.answer.go&&b(),c}},ye,ae;if(i.files!==void 0){let o=y?xo(y):!1;ae=Co(i,u,a,d?.fileStore(),o,e.maxRecordsPerObject),e.dryRun&&ae.deleteFromTarget&&(ae={...ae,deleteFromTarget:async c=>{throw new Error(`A dry run writes nothing: delete ${c} refused.`)}})}let ee=new Map,$t=()=>{let o=Io([...ee.values()],e);o.length>0&&process.stderr.write(`${o.join(`
|
|
293
|
+
`)}
|
|
294
|
+
`)},At=()=>ee.size>0?{readCut:[...ee.values()]}:{},Ot=new Br({...e.dryRun?{}:{creations:N},signal:k.signal,...ae?{files:ae}:{},...d&&e.store!==void 0?{idMap:bn(Ze(e.store),o=>d.isSaved(o))}:{},...d?{deltaStore:d.deltaStore(),deltaReads:un({query:async(o,c)=>u.query(o,c),queryMore:async o=>u.queryMore(o)},{query:async o=>a.query(o),queryMore:async o=>a.queryMore(o)},k.signal)}:{},dataSync:new Nr({insert:(o,c,p)=>F("insert",o,c,p),update:(o,c,p)=>F("update",o,c,p),upsert:(o,c,p,w)=>F("upsert",o,p,w,c),delete:(o,c,p)=>F("delete",o,c,p),describeTargetFields:X}),conflictResolver:new qr,fieldMapping:new cn,transformPipeline:new dn,querySource:Vr(u,e.maxRecordsPerObject,(o,c)=>{ee.set(o,{objectApiName:o,read:c,bound:e.maxRecordsPerObject})}),queryTarget:Vr(a,e.maxRecordsPerObject),maskedSourceFields:xn(rt(async o=>(await te({query:async c=>u.query(c),queryMore:async c=>u.queryMore(c)},o)).records),o=>u.sobject(o).describe()),findInTarget:an({query:async o=>a.query(o),queryMore:async o=>a.queryMore(o)}),describeTargetFields:X,describeTargetFieldsAgain:async o=>gt(await a.sobject(o).describe()),leaseOfTheGate:()=>O?.lease(),queryTargetRows:B,countSource:Eo(u,e.maxRecordsPerObject),countPersonAccounts:To(u),readSourceIds:Fo(u),writeGate:T,readValidationRules:_n(async o=>(await te({query:async c=>a.tooling.query(c),queryMore:async c=>a.tooling.queryMore(c)},o)).records,Mn(a),Ln(a)),currencies:()=>on(async o=>(await u.query(o)).records,async o=>(await a.query(o)).records,{source:async o=>(await u.tooling.query(o)).records,target:async o=>(await a.tooling.query(o)).records}),standardPricebooks:()=>Lr(async o=>(await u.query(o)).records,async o=>(await a.query(o)).records),recordTypes:()=>Gr({query:async o=>u.query(o),queryMore:async o=>u.queryMore(o)},{query:async o=>a.query(o),queryMore:async o=>a.queryMore(o)})});if(e.dryRun){n(`
|
|
295
|
+
simulating\u2026 (DRY-RUN: nothing is written)`);let c={...await Ot.simulate(i),...E?{checkpoint:E}:{}},{planned:p,refused:w}=e.muteAutomation?await Q():{},P=ge??(E?.refusal?ar(E.refusal):void 0),V=c.writeCheck?.unwritable??[],Re=[w,V.length>0?{code:"SYNC_TARGET_UNWRITABLE",message:Hr(V,e.target,c.writeCheck?.heldBack)}:void 0,P!==void 0?{code:fe,message:P}:void 0,...me,oe].filter(He=>He!==void 0),ce=Date.now()-r;if($t(),Te(Ee(Rt("success",[...ee.values()]),e.failOnPartial)),e.json){process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",source:e.source,target:e.target,dryRun:!0,simulation:c,...At(),...Pn(p),...E?{checkpoint:E}:{},apiRequests:kt(c.writeCheck?.apiRequests,g()),...Zt(Re),elapsedMs:ce},null,2)}
|
|
296
|
+
`);return}let so=(p?.plan?.assign.length??0)>0;for(let He of No(c,e.target,so,P,oe?.message))n(He);n(`
|
|
297
|
+
done in ${ce}ms`);return}n(`
|
|
298
|
+
executing\u2026 (REAL)`);let Y=U?.pathOf(j),de,oo=Ve(o=>{de=o,process.stderr.write(`
|
|
299
|
+
interrupted: the run stops before its next call, and its file keeps what it created (Ctrl-C again ends it at once)
|
|
300
|
+
`),k.abort()}),jt=async()=>{!H||!pe||G||(G=await ur(H,pe,ne,e.target,s))},z,Ge={status:"failure"};try{z=await Ot.execute(i).finally(async()=>{ye=await O?.release()}),ye&&(z={...z,mutedAutomation:ye}),Ge={status:Rt(z.status,[...ee.values()]),...z.cancelled?{cancelled:!0}:{}},await jt()}catch(o){if(D?.close(),await jt(),!(o instanceof Mr))throw await S?.end(Ge),Y!==void 0&&ve(Y)&&process.stderr.write(`the run stopped on an error; what it created is kept in ${Y}, and --remove ${Y} takes it back
|
|
301
|
+
`),o;let c=o.code===Xe,p=c?[]:se;e.json?(c||process.stderr.write(`${[o,...p].map(Fe).join(`
|
|
302
|
+
`)}
|
|
303
|
+
`),process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",source:e.source,target:e.target,dryRun:!1,refused:{code:o.code,message:o.message},...p.length>0?{alsoRefused:p}:{},...Z?{writeCheck:Z}:{},...G?{checkpoint:G}:{},apiRequests:kt(Z?.apiRequests,g()),elapsedMs:Date.now()-r},null,2)}
|
|
304
|
+
`)):n(c?`
|
|
305
|
+
${o.message}`:`
|
|
306
|
+
${[o,...p].map(Fe).join(`
|
|
307
|
+
`)}`),process.exit(c?Ie(de??"SIGINT"):1)}finally{oo()}await S?.end(Ge),D?.close();let Ct=await S?.flush();Ct!==void 0&&process.stderr.write(`what the run created could not all be written to ${Y??"its file"} (${Ct}): --remove takes it back from the --json summary
|
|
308
|
+
`);let xt=Date.now()-r,ze=I.created(),It=I.lastWrittenAt(),Et=I.firstWrittenAt(),Tt=I.lastWriteAt(),je=I.overwritten(),Je=I.deletions(),Ft=ze.length>0||je.length>0||Je.length>0?y?.id??await Vo(a):void 0,be=Y!==void 0&&ve(Y)?Y:void 0;$t();let Ce=Rt(z.status,[...ee.values()]);if(e.json){process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",source:e.source,target:e.target,...Ft?{targetOrgId:Ft}:{},...d?{configId:i.id}:{},dryRun:e.dryRun,startedAt:C,finishedAt:new Date().toISOString(),result:{...z,status:Ce},...At(),...G?{checkpoint:G}:{},apiRequests:kt(Z?.apiRequests,g()),created:{runId:I.runId,...It?{lastWrittenAt:It}:{},...Et?{firstWrittenAt:Et}:{},...Tt?{lastWriteAt:Tt}:{},...be?{runFile:be}:{},objects:ze,...je.length>0?{overwritten:je}:{},...Je.length>0?{deleted:Je}:{}},elapsedMs:xt},null,2)}
|
|
309
|
+
`),de&&process.exit(Ie(de)),Te(Ee(Ce,e.failOnPartial));return}let Pt=z.objectResults??[];n(`
|
|
310
|
+
status: ${Ce}`);for(let o of ye?le(ye,e.target):[])n(o);for(let o of Pt){n(` ${Wo(o)}`),typeof o.alreadyCopied=="number"&&n(` ${o.alreadyCopied} already copied by an earlier run of this configuration, left as they are`),typeof o.alreadyLinked=="number"&&n(` ${no(o.alreadyLinked)}`);for(let w of _o(o.errors??[]))n(` ${w}`);for(let w of Bo(o))n(` ${w}`);for(let w of Go(o.currenciesReplaced))n(` ${w}`);for(let w of zo(o.pricesSettled,o.standardPricebookMatched===!0))n(` ${w}`);let c=o.files;c&&n(` files: ${c.copied??0} copied, ${c.versions??0} version(s) added, ${c.failed??0} failed`);let p=o.delta;p&&n(` ${Jo(p)}`)}for(let o of to(Pt,!1))n(` ${o}`);for(let o of qo(z.contactPoints))n(` ${o}`);let Nt=ze.reduce((o,c)=>o+c.ids.length,0),Mt=je.reduce((o,c)=>o+c.ids.length,0);Mt>0&&n(`
|
|
311
|
+
wrote over ${Mt} record(s) of ${e.target}, their values from before kept in ${he(K,"backups")}: --remove ${be??"with the --json summary"} gives them back`),Nt>0&&n(`
|
|
312
|
+
created ${Nt} record(s) and file(s) in ${e.target}: `+(be!==void 0?`--remove ${be} takes them back`:"run with --json and save the summary to a file, and --remove takes them back from it")),n(`
|
|
313
|
+
done in ${xt}ms`),de&&process.exit(Ie(de)),Te(Ee(Ce,e.failOnPartial))}var Be=new Set(["--remove","--target","--include-changed","--accept-automation","--mute-automation","--store","--sweep","--sweep-list",...br,"--leave-undeletable","--json"]),Zo=new Set(["--remove","--target","--store"]);function Qo(t){let r=t.slice(2);for(let u=0;u<r.length;u++){let l=r[u];if(Zo.has(l)){u++;continue}Be.has(l)||(process.stderr.write(`--remove takes --target, --include-changed, --accept-automation, --mute-automation, --store, --sweep, --sweep-late, --sweep-untied, --sweep-list, --leave-undeletable and --json, not "${l}". Run with --help.
|
|
314
|
+
`),process.exit(2))}let e=u=>{let l=r.indexOf(u);return l>=0&&l+1<r.length?r[l+1]:void 0},n=e("--remove"),s=e("--target"),i=e("--store");r.includes("--store")&&(!i||Be.has(i))&&(process.stderr.write(`--store wants the directory the configuration of the run is kept in.
|
|
315
|
+
`),process.exit(2)),(!n||!s||Be.has(n)||Be.has(s))&&(process.stderr.write(`--remove takes the file a run printed its --json summary to, or the run file it named as it began, or its run id, and --target the org the run wrote to. Run with --help.
|
|
316
|
+
`),process.exit(2)),r.includes("--sweep")&&r.includes("--sweep-list")&&(process.stderr.write(`--sweep deletes and --sweep-list only lists: give one of them. Run with --help.
|
|
317
|
+
`),process.exit(2));let d=Rr(r);return"refusal"in d&&(process.stderr.write(`${d.refusal} Run with --help.
|
|
318
|
+
`),process.exit(2)),{summaryPath:n,target:s,includeChanged:r.includes("--include-changed"),acceptAutomation:r.includes("--accept-automation"),muteAutomation:r.includes("--mute-automation"),json:r.includes("--json"),...i!==void 0?{store:i}:{},sweep:r.includes("--sweep"),sweepList:r.includes("--sweep-list"),...d,leaveUndeletable:r.includes("--leave-undeletable")}}var qe=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,es=R.object({tool:R.literal("sandforge-sync"),source:R.string().min(1),target:R.string().min(1),targetOrgId:R.string().regex(qe).optional(),configId:R.string().min(1).max(200).optional(),dryRun:R.boolean().optional(),startedAt:R.string().min(1).max(40).optional(),finishedAt:R.string().min(1).max(40).optional(),result:R.object({status:R.enum(["success","partial","failure"])}).loose(),created:R.object({runId:R.string().min(1).max(200),lastWrittenAt:R.string().min(1).max(40).optional(),firstWrittenAt:R.string().min(1).max(40).optional(),lastWriteAt:R.string().min(1).max(40).optional(),objects:R.array(R.object({objectApiName:R.string().regex(_),ids:R.array(R.string().regex(qe))})),overwritten:R.array(R.object({objectApiName:R.string().regex(_),backup:vn,ids:R.array(R.string().regex(qe))})).optional(),deleted:R.array(R.object({objectApiName:R.string().regex(_),ids:R.array(R.string().regex(qe))})).optional()}).optional()}).loose();function ts(t){let r;try{r=JSON.parse(t)}catch{return{refusal:"is not JSON: save the output of a run printed with --json."}}let e=en(r,"sandforge-sync");if(e)return{refusal:tn(e)};let n=es.safeParse(r);if(!n.success){let s=n.error.issues[0];return{refusal:`is not the summary of a sandforge sync run (${s.path.join(".")||"summary"}: ${s.message}).`}}return n.data.dryRun===!0?{refusal:"is the summary of a dry run, which wrote nothing: there is nothing to remove."}:n.data.created?{summary:n.data}:{refusal:"names nothing the run created: it was printed before runs named what they created, so its records cannot be told from the ones it updated."}}function ns(t){return/\.json$/i.test(t)?t.replace(/\.json$/i,".removals.json"):`${t}.removals.json`}function rs(t,r){let e=t.created,n=t.finishedAt??e?.lastWrittenAt??new Date().toISOString();return{runId:e?.runId??"sandforge-sync",configId:t.configId??"sandforge-sync",configName:t.configId??"sandforge-sync",sourceOrgId:t.source,targetOrgId:t.target,startedAt:t.startedAt??n,end:{at:n,status:t.result.status},...e?.lastWrittenAt?{lastWrittenAt:e.lastWrittenAt}:{},...e?.firstWrittenAt?{firstWrittenAt:e.firstWrittenAt}:{},...e?.lastWriteAt?{lastWriteAt:e.lastWriteAt}:{},created:(e?.objects??[]).filter(s=>s.ids.length>0),...(e?.overwritten??[]).some(s=>s.ids.length>0)?{overwritten:(e?.overwritten??[]).filter(s=>s.ids.length>0)}:{},...(e?.deleted??[]).some(s=>s.ids.length>0)?{deleted:(e?.deleted??[]).filter(s=>s.ids.length>0)}:{},...r?{removal:r}:{}}}function os(t,r,e="sandforge sync"){if(r.sandbox||Dt(r.edition))return;let n=r.edition?`IsSandbox false, edition ${r.edition}`:"IsSandbox false, and no edition";return`${t} is a production org (its Organization record says ${n}): ${e} removes records from sandboxes and Developer Edition orgs only. Nothing was deleted.`}function ss(t,r){let e=n=>[n.deleted>0?`${n.deleted} deleted`:"",n.alreadyGone>0?`${n.alreadyGone} already gone`:"",(n.notVisible??0)>0?`${n.notVisible} not visible`:"",n.keptChanged>0?`${n.keptChanged} kept, changed since the run`:"",n.keptDependents>0?`${n.keptDependents} kept, records that stay depend on them`:"",n.refused>0?`${n.refused} refused`:"",(n.notReached??0)>0?`${n.notReached} not reached`:""].filter(Boolean).join(", ");return[`removal: ${t.toUpperCase()}`,...r.flatMap(n=>[` ${n.objectApiName}: ${e(n)||"nothing"} of ${n.planned}${gr(n)}`,...mr(n),...n.reasons.map(s=>` ${s}`)])]}function is(t){return t.flatMap(r=>{let e=[r.keptChanged>0?`${r.keptChanged} left as they are, changed since the run`:"",r.alreadyGone>0?`${r.alreadyGone} no longer in the org`:"",r.refused>0?`${r.refused} refused`:"",r.notKept>0?`${r.notKept} whose values from before are no longer kept (their backup was deleted, or past its retention)`:"",(r.notReached??0)>0?`${r.notReached} not reached`:"",(r.restoredWithout??0)>0?`${r.restoredWithout} given back but for fields the org no longer takes, which keep the run's values`:""].filter(Boolean);return[` ${r.objectApiName}: ${r.restored} of ${r.planned} given back their values from before the run${e.length>0?`; ${e.join(", ")}`:""}`,...r.reasons.map(n=>` ${n}`)]})}function as(t){return t.flatMap(r=>{let e=[r.alreadyBack>0?`${r.alreadyBack} back in the org already`:"",r.goneForGood>0?`${r.goneForGood} no longer in the recycle bin, gone for good`:"",r.refused>0?`${r.refused} refused`:"",(r.notReached??0)>0?`${r.notReached} not reached`:""].filter(Boolean);return[` ${r.objectApiName}: ${r.undeleted} of ${r.planned} the run deleted brought back from the recycle bin${e.length>0?`; ${e.join(", ")}`:""}`,...r.reasons.map(n=>` ${n}`)]})}function ds(t,r){return t===void 0?[]:[...r.readWhole&&r.readWhole.length>0?[`configuration ${t}: its next run reads ${r.readWhole.join(", ")} whole`]:[],...(r.filesForgotten??0)>0?[`configuration ${t}: ${r.filesForgotten} copied file(s) forgotten, copied again by its next run`]:[],...(r.linksForgotten??0)>0?[`configuration ${t}: ${r.linksForgotten} record(s) forgotten, which no later run points a lookup at`]:[]]}var Zr=3,cs=/^[A-Za-z0-9][A-Za-z0-9_-]{0,199}$/;function us(t,r=De(),e=kn){if(ve(t)){let s;try{s=$e(t,"utf8").split(`
|
|
319
|
+
`).find(d=>d.trim()!=="")}catch{return}let i;try{i=JSON.parse(s??"")}catch{return}return typeof i=="object"&&i!==null&&"run"in i?bo(t):void 0}if(!cs.test(t))return;let n=he(r,e,`${t}.ndjson`);return ve(n)?n:void 0}function ls(t){let r=ct(t.runUserId),e=pr.safeParse(t.mutedAutomation);return{...r?{runUserId:r}:{},...e.success?{muted:e.data}:{}}}function fs(t,r){let e;try{e=$e(t.summaryPath,"utf8")}catch(f){process.stderr.write(`--remove ${t.summaryPath} cannot be read: ${f instanceof Error?f.message:String(f)}
|
|
320
|
+
`),process.exit(2)}let n=ts(e);"refusal"in n&&(process.stderr.write(`--remove ${t.summaryPath} ${n.refusal}
|
|
321
|
+
`),process.exit(2));let{summary:s}=n;s.targetOrgId===void 0&&s.target!==t.target&&(process.stderr.write(`The run wrote to ${s.target}, and what it created is removed from that org only: give --target ${s.target}.
|
|
322
|
+
`),process.exit(2));let i=ns(t.summaryPath),d,u;try{u=$e(i,"utf8")}catch(f){f?.code!=="ENOENT"&&(process.stderr.write(`${i} cannot be read: ${f instanceof Error?f.message:String(f)}
|
|
323
|
+
`),process.exit(2))}if(u!==void 0){let f;try{f=JSON.parse(u)}catch{f=void 0}let g=f?.runId;d=g===s.created?.runId?$n(f):void 0,g!==s.created?.runId?r(`${i} is of another run: it is not read, and this removal's takes its place`):d||(process.stderr.write(`${i} does not read as what earlier removals did.
|
|
324
|
+
`),process.exit(2))}let l=rs(s,d),a=d??{};return{run:l,...s.configId!==void 0?{configId:s.configId}:{},...s.targetOrgId!==void 0?{targetOrgId:s.targetOrgId}:{},...d?{earlier:d}:{},...ls(s.result),updateRemoval:async f=>{a=f(a);let g=`${i}.${process.pid}.tmp`;wo(g,`${JSON.stringify({version:1,runId:l.runId,...a},null,2)}
|
|
325
|
+
`),mo(g,i)}}}async function hs(t,r){let e=Qe(yo(t),""),n;try{n=An($e(t,"utf8"))}catch(d){process.stderr.write(`--remove ${t} cannot be read: ${d instanceof Error?d.message:String(d)}
|
|
326
|
+
`),process.exit(2)}n||(process.stderr.write(`--remove ${t} names no run of sandforge sync.
|
|
327
|
+
`),process.exit(2)),e.pathOf(n.runId)!==t&&(process.stderr.write(`--remove ${t} is the file of the run ${n.runId} under another name: give it as ${e.pathOf(n.runId)}, where what its removals did is kept beside it.
|
|
328
|
+
`),process.exit(2));let s=await e.get(n.runId)??n;s.targetOrganizationId===void 0&&s.targetOrgId!==r.target&&(process.stderr.write(`The run wrote to ${s.targetOrgId}, and what it created is removed from that org only: give --target ${s.targetOrgId}.
|
|
329
|
+
`),process.exit(2));let i=ct(s.runUserId);return{run:s,...s.configId!==St?{configId:s.configId}:{},...s.targetOrganizationId!==void 0?{targetOrgId:s.targetOrganizationId}:{},...s.removal?{earlier:s.removal}:{},updateRemoval:d=>e.updateRemoval(s.runId,d),runs:e,...i?{runUserId:i}:{}}}function ps(t,r){return t.map(({job:e,objectApiName:n,read:s})=>{let i=` Bulk API job ${e} (${n})`;switch(s.state){case"ended":return`${i}: the run's file holds no answer of it; it ended in ${r}, and the ${s.created.length} record(s) it created are removed with the rest`;case"never-closed":return`${i}: never closed, it wrote nothing`;case"running":return`${i}: still running in ${r}: what it creates stays, and the next --remove of the run reads it again`;default:return`${i}: could not be read back (${s.reason}): what it created stays`}})}async function gs(t=process.argv){let r=Date.now(),e=Qo(t),n=h=>{process[e.json?"stderr":"stdout"].write(`${h}
|
|
330
|
+
`)},s=us(e.summaryPath),i=s!==void 0?await hs(s,e):fs(e,n),{earlier:d}=i,u;e.store!==void 0&&(i.configId===void 0&&(process.stderr.write(`--store tells the configuration a run was of what its removal took, and ${e.summaryPath} names none: the run was not of a saved configuration (--config-file).
|
|
331
|
+
`),process.exit(2)),u=ve(he(e.store,"configStore.json"))?Qr(e.store):void 0,u?.isSaved(i.configId)||(process.stderr.write(`${e.store} holds no configuration ${i.configId}: give the --store the run was made with.
|
|
332
|
+
`),process.exit(2)));let l=i.run;Rn(l)&&W({code:Vt,message:`The run is still writing, in process ${l.writer?.pid??"?"}: remove it once it has ended. Nothing was deleted.`});let a,f=(h,m,O,A={},x,Q,ie,we)=>{if(e.json){process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",action:"remove",summary:e.summaryPath,target:e.target,includeChanged:e.includeChanged,result:{status:h,planned:O,objects:m,...A,...x?{sweep:x}:{},...a?{sweepListing:a}:{},...Q?{restored:Q}:{},...ie?{undeleted:ie}:{},...we?{mutedAutomation:we}:{}},elapsedMs:Date.now()-r},null,2)}
|
|
333
|
+
`);for(let T of lt(m,e))n(T);return}for(let T of x?yr(x):[])n(T);for(let T of ss(h,m))n(T);for(let T of lt(m,e))n(T);for(let T of ie?as(ie):[])n(T);for(let T of Q?is(Q):[])n(T);for(let T of ds(i.configId,A))n(T);n(`
|
|
334
|
+
done in ${Date.now()-r}ms`)},g=i.runs!==void 0&&(l.jobs??[]).length>0;if(et(l).length===0&&tt(l).length===0&&nt(l).length===0&&!g&&!e.sweep&&!e.sweepList){let h=d?.undo?.removedAt??d?.restoredAt??d?.undeletedAt;n(h!==void 0?`what the run created was removed already, on ${h}`:"The run created nothing: there is nothing of it to remove."),f("success",[],0);return}let v=await xe(e.target),k=Se(v),y=await ke(k),j=e.sweepList?void 0:os(e.target,y);if(j&&W({code:"PRODUCTION_TARGET",message:j}),i.targetOrgId!==void 0&&i.targetOrgId.slice(0,15)!==y.id.slice(0,15)&&W({code:Yt,message:`${e.target} is not the org the run wrote to (${i.targetOrgId}), and what it created is removed from that org only. Nothing was deleted.`}),g&&i.runs){let h=i.runs,m=await Or(h,l,k,()=>Pe(k,"sandforge sync --remove").serverTime());for(let O of ps(m,e.target))n(O);m.some(O=>O.answered)&&(l=await h.get(l.runId)??l)}!l.end&&l.inFlight&&l.inFlight.job===void 0&&n(` the run stopped during a call of ${l.inFlight.rows} ${l.inFlight.objectApiName} row(s): those ${e.target} took are not in its file, and stay; ${ut("--sweep-list")} shows what the run's user created in the run's window`);let I=et(l),U=async h=>{let m;try{m=await We(k).read(e.target,[...new Set([...l.created,...l.overwritten??[]].map(x=>x.objectApiName).filter(x=>!Sn.includes(x)))])}catch(x){m={error:x instanceof Error?x.message:String(x)}}let O=Pe(k,"sandforge sync --sweep"),A=Ar({otherRuns:await $r({organizationId:y.id,alias:e.target,span:vr(l),own:{runId:l.runId,ids:l.created.flatMap(x=>x.ids)}}),...i.muted?{muted:i.muted}:{},...d?.removalSpans?{removalSpans:d.removalSpans}:{},...d?.madeEarlier?{made:d.madeEarlier}:{},...d?.lateEarlier?{late:d.lateEarlier}:{}});return Er(O,l.created,m,h,l.firstWrittenAt!==void 0?{at:l.firstWrittenAt,...l.lastWriteAt!==void 0?{lastAt:l.lastWriteAt}:{},serverTime:()=>O.serverTime()}:void 0,l.overwritten??[],{...i.runUserId?{runUserId:i.runUserId}:{},ties:A})};if(e.sweepList){let h=await Qn(ft(k,"sandforge sync --sweep-list"),await U(),d?.removalSpans??[]);for(let m of Ue(h,e.target,e,!0))n(m);e.json?process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",action:"sweep-list",summary:e.summaryPath,target:e.target,listing:h,elapsedMs:Date.now()-r},null,2)}
|
|
335
|
+
`):n(`
|
|
336
|
+
done in ${Date.now()-r}ms`),h.refusal!==void 0&&process.exit(Zr);return}let S=tt(l),$,b={kept:[...S],notKept:0};if(S.length>0){let h=ht(),m=pt(h);if(m!==void 0)n(m);else{$=new st(ot(h));let O=Le(he(h,"snapshots.json"));b=En(S,A=>O.get(`backup:${A}`),30)}}n(`sandforge sync --remove ${e.summaryPath} from ${e.target}`);for(let{objectApiName:h,ids:m}of b.kept)n(` ${h}: ${m.length} to give back their values from before the run`);b.notKept>0&&n(` values from before no longer kept (past sandforge.backup.maxAgeDays, or deleted): ${b.notKept} record(s) the run wrote over keep its values`),b.keptUntil!==void 0&&b.kept.length>0&&n(` values from before kept until ${b.keptUntil}, at the default retention`);let J=nt(l);for(let{objectApiName:h,ids:m}of J)n(` ${h}: ${m.length} the run deleted, as the source had, to bring back from the recycle bin`);for(let{objectApiName:h,ids:m}of I)n(` ${h}: ${m.length} to remove`);I.length===0&&S.length===0&&J.length===0&&n("nothing left of the run to remove"),e.sweep&&n(`before them, a sweep deletes what the target's automation made for the run, as the run's user, tied to its records \u2014 run ${ut("--sweep-list")} to see what`);let N=new AbortController,H=Ve(()=>N.abort()),X=d??{},L=e.sweep?er(ft(k,"sandforge sync --sweep",N.signal),await U(N.signal),{includeChanged:e.includeChanged,removalSpans:X.removalSpans??[],...kr(e),approve:async h=>{a=h,n("");for(let m of Ue(h,e.target,e))n(m)}}):void 0;await L?.ask();let K=wr(L,a);if(K){a=K,n("");for(let h of Ue(K,e.target,e))n(h)}let D=h=>[...new Set(h.map(({objectApiName:m})=>m))],B=qt({bringBack:D(J),giveBack:D(b.kept),setToDraft:mn(D(I)),delete:wn(D(I))},L?.takes??[]),Ae=[...new Set(Object.values(B).flat())];function W(h){return process.stderr.write(`${Fe(h)}
|
|
337
|
+
`),e.json&&process.stdout.write(Qt({tool:"sandforge-sync",summary:e.summaryPath,target:e.target,elapsedMs:Date.now()-r},h)),process.exit(1)}let ne=h=>(H(),W(h)),F;if(Ae.length>0&&!N.signal.aborted){let h=await We(k).read(e.target,Ae,{undeletes:!0});n("");for(let A of Kn(h,e.target,B))n(A);if(e.muteAutomation)try{F=await _e(async()=>Ne(k),h,{writes:Gt(B)});for(let A of le(F.muted,e.target))n(` ${A}`)}catch(A){if(!Me(A))throw A;ne(A.refusal)}let m=F?.automation??h,O=Yn(m,e.target,{steps:B,assign:Hn(m,zt(m,B)),mayMute:F===void 0&&Xn("--mute-automation")});O&&!e.acceptAutomation&&ne({code:"AUTOMATION_NOT_ACCEPTED",message:O})}let C,q,E=F?.muted,pe=async()=>{!F?.prepared||N.signal.aborted||(q=await F.prepared.acquire(`sandforge sync --remove ${l.runId}`).catch(h=>{if(!Me(h))throw h;return ne(h.refusal)}),E=q.outcome)},G=Pe(k,"sandforge sync --remove"),Oe=await Ir(G,l.created),M;try{C=await Cn({run:l,org:G,includeChanged:e.includeChanged,...Sr(L),...i.runUserId?{runUserId:i.runUserId}:{},onUndeletable:lr(e.leaveUndeletable,e.target,h=>{M=h}),beforeFirstWrite:pe,signal:N.signal,...u&&e.store!==void 0?{configs:u,links:Ze(e.store)}:{},...$?{backups:$}:{},undelete:h=>k.soap.undelete(h),...i.runs?{earlierRuns:jn(l,await i.runs.list())}:{},store:{updateRemoval:(h,m)=>h!==l.runId&&i.runs?i.runs.updateRemoval(h,m):i.updateRemoval(O=>(X=m(O),X))}})}finally{H();let h=L?.made??new Set,m=L?.late??new Set,O=L?.gone??new Set;if((h.size>0||m.size>0||O.size>0)&&await i.updateRemoval(A=>Tr(A,h,m,O)).catch(A=>{process.stderr.write(`What the sweep found made for the run could not be kept (${A instanceof Error?A.message:String(A)}): a later --sweep may list it as tied to nothing.
|
|
338
|
+
`)}),q){E=await q.release();for(let A of le(E,e.target))n(A)}}E&&(C={...C,result:{...C.result,mutedAutomation:E}}),C.stoppedForUndeletable&&(M&&W(M),process.exit(1));let re=C.result.status==="cancelled"?{}:await Oe.take();for(let h of[...C.notes,...re.note?[re.note]:[]])process.stderr.write(`${h}
|
|
339
|
+
`);let Z=C.result.objects.some(h=>h.deleted+h.alreadyGone>0);i.configId!==void 0&&!u&&Z&&process.stderr.write(`The run was of the saved configuration ${i.configId}, and its store was not given: its next delta run is not told what this removal took, and a later run may point a lookup at a record it deleted. Give ${Zn("--store")} with the next removal, or run the configuration full next time.
|
|
340
|
+
`);let{readWhole:ge,filesForgotten:oe}=C.result,me=L?.result(),se=yn(C.result.status,me);f(se,re.object?[...C.result.objects,re.object]:C.result.objects,C.planned,{...ge?{readWhole:ge}:{},...oe!==void 0?{filesForgotten:oe}:{},...C.linksForgotten!==void 0?{linksForgotten:C.linksForgotten}:{}},me,C.result.restored,C.result.undeleted,E),se!=="success"&&process.exit(Zr)}process.argv[1]?.includes("sandforge-sync")&&(fr(),Xo().then(()=>process.exit(process.exitCode??0)).catch(t=>{process.stderr.write(`${t instanceof Error?t.message:String(t)}
|
|
341
|
+
`),process.exit(1)}));export{Ro as a,Ao as b,Oo as c,jo as d,Qr as e,Co as f,xo as g,Vr as h,Io as i,Rt as j,Eo as k,To as l,Fo as m,Xr as n,kt as o,eo as p,to as q,no as r,No as s,_o as t,Wo as u,Bo as v,ro as w,qo as x,Go as y,zo as z,Jo as A,Ho as B,Ko as C,St as D,Xo as E,Qo as F,ts as G,ns as H,rs as I,os as J,ss as K,is as L,as as M,ds as N,us as O,ps as P,gs as Q};
|
|
@@ -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 Ge}from"./chunk-DYFALGRT.mjs";import{a as xe,b as je,c as Te,d as Oe,f as Pe}from"./chunk-M6P5ZZLE.mjs";import{Q as Me,_ as Le,aa as De,ca as qe,ga as B,na as Ie,oa as Ve,sa as Be,ua as U,va as Ue,xa as Qe}from"./chunk-CION3VMZ.mjs";import{b as E}from"./chunk-CA5NAXSU.mjs";import{$c as Se,L as Fe,N as ve,O as Ne,P as _e,Q as Ae,R as Ce,S as $e,T as Ee}from"./chunk-TTFDUKUS.mjs";import{e as X,l as ee}from"./chunk-7EANH5PY.mjs";var v=class extends Error{};function lt(e){let r=[],n=0;for(;n<e.length;){let t=e.slice(n),i=/^\s+/.exec(t);if(i){n+=i[0].length;continue}if(t.startsWith("/*")){let d=e.indexOf("*/",n+2);if(d<0)throw new v("an unclosed comment");n=d+2;continue}let l=t[0];if(l==="'"||l==='"'){let d=1;for(;d<t.length&&t[d]!==l;)d+=t[d]==="\\"?2:1;if(d>=t.length)throw new v("an unclosed text");r.push(t.slice(0,d+1)),n+=d+1;continue}let f=/^(?:\d+(?:\.\d+)?|[A-Za-z_$][A-Za-z0-9_$.]*)/.exec(t);if(f){r.push(f[0]),n+=f[0].length;continue}let p=/^(?:&&|\|\||==|!=|<>|<=|>=|[=<>+\-*/^&!(),])/.exec(t);if(!p)throw new v(`an unexpected character: ${t[0]}`);r.push(p[0]),n+=p[0].length}return r}var We=[new Set(["||"]),new Set(["&&"]),new Set(["=","==","<>","!=","<",">","<=",">="]),new Set(["+","-","&"]),new Set(["*","/"]),new Set(["^"])];function ut(e){let r=lt(e),n=0,t=()=>r[n],i=u=>{if(r[n]!==u)throw new v(`${u} expected`);n++},l=u=>{if(u>=We.length)return f();let o=l(u+1);for(let a=t();a!==void 0&&We[u].has(a);a=t())n++,o={kind:"binary",op:a,left:o,right:l(u+1)};return o},f=()=>{if(t()==="!")return n++,{kind:"not",arg:f()};if(t()==="-"||t()==="+"){let u=r[n++],o=f();return u==="-"?{kind:"negative",arg:o}:o}return p()},p=()=>{let u=r[n++];if(u===void 0)throw new v("the formula ends early");if(u==="("){let a=l(0);return i(")"),a}if(u.startsWith("'")||u.startsWith('"'))return{kind:"literal",value:`text:${u.slice(1,-1)}`};if(/^\d/.test(u))return{kind:"literal",value:`number:${Number(u)}`};if(!/^[A-Za-z_$]/.test(u))throw new v(`${u} out of place`);if(t()==="("){n++;let a=[];if(t()!==")")for(a.push(l(0));t()===",";)n++,a.push(l(0));return i(")"),{kind:"call",name:u.toUpperCase(),args:a}}let o=u.toUpperCase();return o==="TRUE"||o==="FALSE"||o==="NULL"?{kind:"literal",value:o.toLowerCase()}:{kind:"reference",name:u.toLowerCase()}},d=l(0);if(n!==r.length)throw new v(`${r[n]} out of place`);return d}function S(e){switch(e.kind){case"call":return e.name==="PRIORVALUE"&&e.args.length===1?S(e.args[0]):{...e,args:e.args.map(S)};case"binary":return{...e,left:S(e.left),right:S(e.right)};case"not":case"negative":return{...e,arg:S(e.arg)};default:return e}}function N(e){switch(e.kind){case"call":return`${e.name}(${e.args.map(N).join(",")})`;case"binary":{let r=e.op==="=="?"=":e.op==="!="?"<>":e.op,n=[N(e.left),N(e.right)];return(r==="="||r==="<>")&&n.sort(),`(${n[0]} ${r} ${n[1]})`}case"not":return`NOT(${N(e.arg)})`;case"negative":return`-(${N(e.arg)})`;case"literal":return e.value;case"reference":return e.name}}var Ke=e=>e==="true"?"false":e==="false"?"true":"unknown";function P(e){return e.kind==="call"&&e.name==="AND"?e.args.flatMap(P):e.kind==="binary"&&e.op==="&&"?[...P(e.left),...P(e.right)]:[e]}function M(e){return e.kind==="call"&&e.name==="OR"?e.args.flatMap(M):e.kind==="binary"&&e.op==="||"?[...M(e.left),...M(e.right)]:[e]}function te(e){if(e.kind==="not"){let r=te(e.arg);return{condition:r.condition,holds:!r.holds}}if(e.kind==="call"&&e.name==="NOT"&&e.args.length===1){let r=te(e.args[0]);return{condition:r.condition,holds:!r.holds}}return e.kind==="binary"&&(e.op==="<>"||e.op==="!=")?{condition:N({...e,op:"="}),holds:!1}:{condition:N(e),holds:!0}}function ne(e){if(e.kind==="literal"){if(e.value==="true")return"true";if(e.value==="false")return"false"}}function k(e){let r=ne(e);if(r)return r;if(e.kind==="not")return Ke(k(e.arg));if(e.kind==="call")switch(e.name){case"ISCHANGED":return"false";case"ISNEW":return"true";case"NOT":return e.args.length===1?Ke(k(e.args[0])):"unknown";case"AND":return ze(P(e));case"OR":return He(M(e));case"IF":{if(e.args.length!==3)return"unknown";let[n,t,i]=e.args,l=k(n);if(l==="true")return k(t);if(l==="false")return k(i);let f=k(t);return f===k(i)?f:"unknown"}default:return"unknown"}return e.kind==="binary"?e.op==="&&"?ze(P(e)):e.op==="||"?He(M(e)):ct(e):"unknown"}function ze(e){let r=e.map(k);if(r.includes("false"))return"false";let n=new Map;for(let t of e){let{condition:i,holds:l}=te(t),f=n.get(i);if(f!==void 0&&f!==l)return"false";n.set(i,l)}return r.every(t=>t==="true")?"true":"unknown"}function He(e){let r=e.map(k);return r.includes("true")?"true":r.every(n=>n==="false")?"false":"unknown"}function ct(e){let r=e.op==="="||e.op==="==",n=e.op==="<>"||e.op==="!=";if(N(e.left)===N(e.right))return n||e.op==="<"||e.op===">"?"false":"unknown";if(!r&&!n)return"unknown";let t=ne(e.left)??k(e.left),i=ne(e.right)??k(e.right);return t==="unknown"||i==="unknown"?"unknown":t===i===r?"true":"false"}function Ze(e){try{return k(S(ut(e)))==="false"}catch(r){if(r instanceof v)return!1;throw r}}var et=25,W=20,ie=W*Me,G=4,Ye=10,dt=2e3,ft=.8;function pt(e){return typeof e!="object"||e===null?null:{optional:e.optionalFilter===!0}}function It(e){return{name:e.name,type:String(e.type),createable:e.createable===!0,nillable:e.nillable!==!1,defaultedOnCreate:e.defaultedOnCreate===!0,referenceTo:(e.referenceTo??[]).filter(r=>typeof r=="string"),picklistValues:(e.picklistValues??[]).filter(r=>r?.active!==!1&&typeof r?.value=="string").map(r=>r?.value),lookupFilter:pt(e.filteredLookupInfo)}}function oe(e){return`SELECT Id, ValidationName, NamespacePrefix, ErrorDisplayField, ErrorMessage, EntityDefinition.QualifiedApiName FROM ValidationRule WHERE Active = true AND EntityDefinition.QualifiedApiName IN (${e.map(n=>`'${n}'`).join(", ")})`}function gt(e){return`SELECT QualifiedApiName, Label FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName = '${x.test(e)?e:""}'`}function q(e){return`SELECT Metadata FROM ValidationRule WHERE Id = '${e}'`}var mt="SELECT DeveloperName, MasterLabel, NamespacePrefix, SobjectType FROM DuplicateRule WHERE IsActive = true",ae=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,x=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,ht=ee({DailyApiRequests:ee({Max:X(),Remaining:X()}).loose()}).loose(),y=e=>typeof e=="string"?e:"";function le(e){if(typeof e!="object"||e===null)return;let r=e.QualifiedApiName;return typeof r=="string"&&r!==""?r:void 0}function Q(e,r){return e?`${e}__${r}`:r}function D(e){return typeof e=="string"?[e]:Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}function yt(e){return{...e,nodes:e.nodes.map(r=>r.leftOutByUser===!0?{...r,included:!0}:r)}}function se(e,r){let n=y(e).trim(),t=n.slice(n.lastIndexOf(".")+1);if(x.test(t))return r?r.find(i=>i.name.toLowerCase()===t.toLowerCase())?.name:t}function tt(e){let r=Ie({filterFormula:e}).filter(t=>t.bypass).map(t=>t.name),n=Ve(e).map(t=>t.value===void 0?t.reference:`${t.reference} = '${t.value}'`);return{bypasses:[...r.map(t=>`$Permission.${t}`),...n],permissions:r}}function wt(e,r={}){let n=r.maxRecordsPerObject,t=e.nodes.filter(d=>d.included),i=r.inputMode==="record"&&typeof r.recordId=="string"?"atMost":"exact",l=t.map(d=>d.recordCountUnknown===!0?(n===void 0?i="unknown":i==="exact"&&(i="atMost"),{...d,recordCount:n??0}):{...d,recordCount:n===void 0?d.recordCount:Math.min(d.recordCount,n)}),f=new Ge().generate({...e,nodes:l}).totalApiCalls,p=l.reduce((d,u)=>d+Math.max(1,Math.ceil(u.recordCount/dt)),0);return{writes:f,reads:p,bound:i}}function j(e){let{idValue:r,...n}=e;return{id:Fe(e.kind,e.objectApiName,e.field,e.recordType,r??e.value),source:"metadata",rows:0,...n}}function ue(e){return e?{field:e}:{}}function Vt(e){return async r=>qe(await e.request({method:"POST",url:"/tooling/composite",body:JSON.stringify(De(`/services/data/v${e.version}`,r)),headers:{"Content-Type":"application/json"}}),r.length)}async function bt(e,r,n){let t=e.filter(({id:i})=>ae.test(i));t.length!==0&&await B(r,[{queries:t.map(({id:i,rule:l})=>({soql:q(i),retrieve:{sobject:"ValidationRule",id:i},take:f=>{let p=f[0]?.Metadata,d=typeof p=="object"&&p!==null?p.errorConditionFormula:void 0;typeof d=="string"&&Ze(d)&&(l.onChangeOnly=!0)},refused:()=>{}})),requests:W}],G,n)}async function kt(e,r,n,t,i){let l=[...new Set(r)].filter(g=>x.test(g));if(l.length===0)return[];let f=new Map(l.map(g=>[g.toLowerCase(),g])),p=new Map(l.map((g,b)=>[g,b])),d=await e(oe(l)),u=new Map,o=async(g,b)=>{let R=se(b,void 0);if(!n)return R;let F=u.get(g);F||(F=n(g).catch(()=>[]),u.set(g,F));let C=y(b).trim().toLowerCase();if(!C)return;let _=R?.toLowerCase(),$=await F;return $.length===0?R:$.find(A=>A.name.toLowerCase()===_)?.name??$.find(A=>A.label?.trim().toLowerCase()===C)?.name},h=(await Promise.all(d.map(async g=>{let b=le(g.EntityDefinition),R=b===void 0?void 0:f.get(b.toLowerCase()),F=y(g.ValidationName);return!R||!F?[]:[{id:y(g.Id),rule:{objectApiName:R,name:Q(y(g.NamespacePrefix),F),message:y(g.ErrorMessage),...ue(await o(R,g.ErrorDisplayField))}}]}))).flat().sort((g,b)=>(p.get(g.rule.objectApiName)??0)-(p.get(b.rule.objectApiName)??0)||g.rule.name.localeCompare(b.rule.name));return t&&await bt(h,t,i),h.map(({rule:g})=>g)}async function Bt(e,r,n,t){let i=[...new Set(r)].filter(a=>x.test(a));if(i.length===0)return{rules:[],notRead:0,requests:0};let l=new Map(i.map(a=>[a.toLowerCase(),a])),f=await e(oe(i)),p=f.requests,d=f.records.flatMap(a=>{let h=le(a.EntityDefinition),g=h===void 0?void 0:l.get(h.toLowerCase()),b=y(a.ValidationName);return!g||!b?[]:[{id:y(a.Id),objectApiName:g,name:Q(y(a.NamespacePrefix),b),read:!1,permissions:[]}]}),u=d.filter(a=>ae.test(a.id)),o=(a,h)=>{let g=typeof h=="object"&&h!==null?h.errorConditionFormula:void 0;typeof g=="string"&&(a.read=!0,a.permissions=tt(g).permissions)};return n?p+=await B(n,[{queries:u.slice(0,ie).map(a=>({soql:q(a.id),retrieve:{sobject:"ValidationRule",id:a.id},take:h=>o(a,h[0]?.Metadata),refused:()=>{}})),requests:W}],G,t):await U(u.slice(0,et).map(a=>async()=>{try{let h=await e(q(a.id));p+=h.requests,o(a,h.records[0]?.Metadata)}catch{p++}}),G),{rules:d.filter(a=>a.permissions.length>0).map(({objectApiName:a,name:h,permissions:g})=>({objectApiName:a,name:h,permissions:g})),notRead:d.filter(a=>!a.read).length,requests:p}}function Ut(e,r,n){let t=async i=>(await e(gt(i))).flatMap(l=>typeof l.QualifiedApiName=="string"?[{name:l.QualifiedApiName,...typeof l.Label=="string"?{label:l.Label}:{}}]:[]);return i=>kt(e,i,t,r,n)}var Je=class{deps;constructor(r){this.deps=r}async read(r,n,t,i={}){let l=new Set(i.excludedObjects??[]),f=Ue(yt(t),l),p=[];if(f.length===0)return{gaps:[],unread:p,requests:0};let d=0,u=(s,c)=>{p.push({part:s,reason:c})},o=new Map(f.map(s=>[s.toLowerCase(),s])),a=s=>s===void 0?void 0:o.get(s.toLowerCase()),h=new Map(f.map((s,c)=>[s,c])),g=f.filter(s=>x.test(s)),b=[],R=[],F,C,_=new Map,$=new Map,A=new Set,I=(s,c,m)=>async()=>{try{let w=await c();d+=w.requests,m(w.records)}catch(w){d++,u(s,E(w))}},ce=(s,c,m,w)=>async()=>{try{let{fields:J,sent:ot,createable:at}=await this.deps.describeFields(s,c);ot&&d++,w.set(c,J),w===_&&at===!1&&A.add(c)}catch(J){d++,u(m,`${c}: ${E(J)}`)}};await U([...g.length>0?[I("validationRules",()=>this.deps.toolingQuery(n,oe(g)),s=>{b=s})]:[],I("duplicateRules",()=>this.deps.query(n,mt),s=>{R=s}),async()=>{try{d++,F=await this.deps.readLimits(n)}catch(s){C=E(s)}},...f.flatMap(s=>[ce(n,s,"targetFields",_),ce(r,s,"sourceFields",$)])],G);let T=b.flatMap(s=>{let c=a(le(s.EntityDefinition)),m=y(s.ValidationName);if(!c||!m)return[];let w=y(s.Id);return[{id:ae.test(w)?w:null,name:Q(y(s.NamespacePrefix),m),objectApiName:c,...ue(se(s.ErrorDisplayField,_.get(c))),message:y(s.ErrorMessage),formula:"notRead",bypasses:[],permissions:[]}]}).sort((s,c)=>(h.get(s.objectApiName)??0)-(h.get(c.objectApiName)??0)||s.name.localeCompare(c.name)),{toolingQueries:O,toolingRetrieves:de}=this.deps,K=T.filter(s=>s.id!==null).slice(0,O?ie:et);for(let s of T)s.id===null&&(s.formula="unreadable");let z=R.flatMap(s=>{let c=a(y(s.SobjectType)),m=Q(y(s.NamespacePrefix),y(s.DeveloperName));return!c||!y(s.DeveloperName)?[]:[{objectApiName:c,developerName:m,label:y(s.MasterLabel)||m,fullName:`${y(s.SobjectType)}.${m}`}]}),fe=new Map,pe=[];for(let s=0;s<z.length;s+=Ye)pe.push(z.slice(s,s+Ye).map(c=>c.fullName));let V,H,ge=(s,c)=>{let m=typeof c=="object"&&c!==null?c.errorConditionFormula:void 0;if(typeof m!="string"){s.formula="unreadable";return}s.formula="read",Object.assign(s,tt(m));let w=se(c.errorDisplayField,_.get(s.objectApiName));w&&(s.field=w)},rt=async()=>{if(!O||K.length===0)return;let s=await B(c=>O(n,c),[{queries:K.map(c=>({soql:q(c.id),retrieve:{sobject:"ValidationRule",id:c.id},take:m=>ge(c,m[0]?.Metadata),refused:m=>{c.formula="unreadable",V??=m}})),requests:W}],G,de&&(c=>de(n,c)));d+=s},me=new Map,Z={},he=[...A].filter(s=>x.test(s)),st=async()=>{let[s,c]=await Promise.all([Oe((m,w)=>this.deps.toolingQuery(m,w),n,he),this.deps.createFacts?this.deps.createFacts(n).then(m=>({facts:m,requests:0})).catch(()=>({facts:{},requests:0})):Te(this.deps,n)]);d+=s.requests+c.requests;for(let[m,w]of s.answered)me.set(m,w);Z=c.facts};await U([...he.length>0?[st]:[],...O?[rt]:[],...(O?[]:K).map(s=>async()=>{try{let c=await this.deps.toolingQuery(n,q(s.id));d+=c.requests,ge(s,c.records[0]?.Metadata)}catch(c){d++,s.formula="unreadable",V??=E(c)}}),...pe.map(s=>async()=>{try{d++;for(let c of await this.deps.readDuplicateRules(n,s)){if(typeof c!="object"||c===null)continue;let m=c,w=y(m.fullName);w&&fe.set(w.toLowerCase(),m)}}catch(c){H??=E(c)}})],G),V!==void 0&&u("validationRuleFormulas",V),H!==void 0&&u("duplicateRuleActions",H);let Y=new Set,ye=!1;T.some(s=>s.permissions.length>0)&&await I("userPermissions",()=>this.deps.query(n,Le),s=>{ye=!0;for(let c of s)Y.add(Be(y(c.NamespacePrefix),y(c.DeveloperName)))})();let we=[...new Set(T.flatMap(s=>s.permissions.filter(c=>!Y.has(c.toLowerCase()))))],it=we.length>0?await Qe(we,async s=>{let c=[];return await I("permissionSets",()=>this.deps.query(n,s),m=>{c=m})(),c},()=>p.some(s=>s.part==="permissionSets")):void 0,be=[...T.map(s=>vt(s,ye?Y:void 0,it)),...z.map(s=>Nt(s,fe.get(s.fullName.toLowerCase()))),...f.flatMap(s=>{if(A.has(s))return[Ft(s,xe(s,Z,me.get(s.toLowerCase())),_.get(s)??[],Z)];let c=_.get(s),m=$.get(s);return c&&m?_t(s,c,m,i):[]})],ke=ht.safeParse(F),Re=C===void 0&&ke.success?ke.data.DailyApiRequests:void 0;return Re||u("apiBudget",C??"the limits the org answered hold no DailyApiRequests"),be.push(At(t,i,f[0],Re)),{gaps:Ae(be),unread:p,requests:d}}},Rt={platform:"object_platform_only",setup:"object_setup_only",feature:"object_feature_off",parent:"object_through_parent",user:"object_not_createable"};function Ft(e,r,n,t){let i=r==="parent"?Pe(n,t):[];return j({kind:Rt[r],severity:je(r)?"info":"blocking",objectApiName:e,...i.length>0?{detail:{editOn:i}}:{},decisions:["exclude_object"]})}function vt(e,r,n){let t=r?e.permissions.filter(f=>r.has(f.toLowerCase())):[],i=t.length>0?[]:e.permissions.flatMap(f=>{let p=n?.find(d=>d.permission.toLowerCase()===f.toLowerCase());return p?[Ce(p)]:[]}),l=e.field?["leave_empty","ignore"]:["ignore"];return j({kind:"validation_rule",severity:t.length>0?"info":"warning",objectApiName:e.objectApiName,...ue(e.field),idValue:e.name,detail:{rule:e.name,message:e.message,formula:e.formula,...e.bypasses.length>0?{bypasses:e.bypasses}:{},...t.length>0?{heldBypasses:t}:{},...i.length>0?{assign:i}:{}},decisions:l,...e.field?{defaultDecision:"leave_empty"}:{}})}function Nt(e,r){let n=y(r?.actionOnInsert).toLowerCase(),t=n==="block"||n==="allow"?n:"unknown",i=D(r?.operationsOnInsert).map(f=>f.toLowerCase());return j({kind:"duplicate_rule",severity:t==="allow"?"info":"warning",objectApiName:e.objectApiName,idValue:e.developerName,detail:{rule:e.label,developerName:e.developerName,action:t,...t==="allow"?{alert:i.includes("alert")}:{},...t==="allow"?{report:i.includes("report")}:{}},decisions:t==="allow"?["ignore"]:["ignore","exclude_object"],...t==="allow"?{defaultDecision:"ignore"}:{}})}function _t(e,r,n,t){let i=o=>o.toLowerCase(),l=new Set((t.fieldExclusions?.[e]??[]).map(i)),f=new Map(Object.entries(t.fieldMappings?.[e]??{}).map(([o,a])=>[i(o),i(a)])),p=new Set([...f].filter(([o])=>!l.has(o)).map(([,o])=>o)),d=new Map(n.map(o=>[i(o.name),o])),u=o=>{let a=i(o);if(p.has(a))return;let h=d.get(a);return h?l.has(a)||f.has(a)?"excluded":h.createable?void 0:"notCreateableInSource":"notInSource"};return r.flatMap(o=>{let a=u(o.name);if(o.createable&&!o.nillable&&!o.defaultedOnCreate&&a)return[j({kind:"required_field_missing",severity:"blocking",objectApiName:e,field:o.name,detail:{type:o.type,reason:a,...o.referenceTo.length>0?{referenceTo:o.referenceTo}:{},...o.picklistValues.length>0?{values:o.picklistValues}:{}},decisions:["set_default","exclude_object"]})];if(o.type==="reference"&&o.lookupFilter&&!a){let h=o.nillable;return[j({kind:"lookup_filter",severity:"warning",objectApiName:e,field:o.name,detail:{referenceTo:o.referenceTo,optional:h,filterOptional:o.lookupFilter.optional},decisions:h?["leave_empty","ignore"]:["ignore","exclude_object"],...h?{defaultDecision:"leave_empty"}:{}})]}return[]})}function At(e,r,n,t){let i=e.nodes[0]?.objectApiName??n,l=wt(e,r),f=l.writes+l.reads,p="warning";if(t&&l.bound!=="unknown"){let d=f>t.Remaining,u=t.Max-t.Remaining+f>ft*t.Max;p=d&&l.bound==="exact"?"blocking":d||u?"warning":"info"}return j({kind:"api_budget",severity:p,objectApiName:i,detail:{calls:f,writes:l.writes,reads:l.reads,estimate:l.bound,...t?{max:t.Max,remaining:t.Remaining}:{budgetRead:!1}},decisions:["ignore"]})}var Ct={blocking:"BLOCKING",warning:"warning",info:"info"},$t=new Set(["picklist_value_refused","dependent_value_invalid","picklist_value_absent","currency_inactive"]),Et=new Set(["record_type_unmapped","record_type_unavailable"]);function nt(e,r,n=[e.id]){if(ve(r.ignoredGaps,e.id,n)!==void 0)return"left as it is";let t=e.objectApiName;if(r.excludedObjects?.includes(t))return`${t} left out of the run`;let i=new Set(e.decisions),{field:l,value:f}=e;if(i.has("skip_rows")&&Ne((r.skippedRows??[]).filter(o=>o.object===t),e.id,n))return"these rows held back";if($t.has(e.kind)&&l!==void 0&&f!==void 0&&(i.has("map_value")||i.has("leave_empty"))){let o=(r.picklistValueMappings??[]).filter(h=>h.object===t&&h.field===l&&h.from===f),a=_e(o,e,n);if(a?.to===null&&i.has("leave_empty"))return"the field left empty in these rows";if(a&&a.to!==null&&i.has("map_value"))return`written as "${a.to}"`}let p=Et.has(e.kind)?e.value??e.recordType:void 0;if(p!==void 0&&i.has("map_record_type")){let o=r.recordTypeMappings?.find(a=>a.object===t&&a.from===p);if(o)return o.to===null?"written with the object's default record type":`written as record type ${o.to}`}if(l===void 0)return;let d=o=>o.object===t&&o.field===l,u=i.has("set_default")?r.defaultValues?.find(d):void 0;if(u)return`default "${String(u.value)}"`;if(i.has("truncate")&&r.truncateFields?.some(d))return"cut to the field's length";if(i.has("leave_empty")&&r.fieldExclusions?.[t]?.includes(l))return"the field left out of the rows"}function Qt(e,r){let n=e.gaps.map(t=>t.id);return{...e,gaps:e.gaps.map(t=>{let i=nt(t,r,n);return i===void 0?t:{...t,answeredBy:i}})}}function Xe(e,r,n,t){if(t)return`the mute lifts it (${t.permission}, in ${t.permissionSet}): ${re(e,!0)}`;let i=r?nt(e,r,n):void 0;return i===void 0?`${Ct[e.severity]}: ${re(e)}`:`answered by the run's decision: ${i} \u2014 ${re(e)}`}var St={validationRules:"the validation rules",validationRuleFormulas:"the formulas of some validation rules",duplicateRules:"the duplicate rules",duplicateRuleActions:"what the duplicate rules do on insert",userPermissions:"the custom permissions of the user the run writes as",permissionSets:"the permission sets that hold a bypass of a validation rule the user the run writes as does not",targetFields:"the fields of an object in the target",sourceFields:"the fields of an object in the source",apiBudget:"the daily API requests left"},Gt={notInSource:"the source has no such field",notCreateableInSource:"the source cannot give it",excluded:"the run leaves it out"},L=e=>typeof e=="number"?String(e):"?";function re(e,r=!1){let n=e.detail??{};switch(e.kind){case"required_field_missing":return`required field ${e.field??""} (${y(n.type)}): only the target requires it, and the run does not write it (${Gt[y(n.reason)]??y(n.reason)}): every row is refused unless it is given a value`;case"validation_rule":{let t=e.field?` on ${e.field}`:"",i=[...D(n.bypasses).map(f=>`not when ${f}`),...D(n.heldBypasses).length>0?[`kept quiet for this run: the user it writes as holds ${D(n.heldBypasses).join(", ")}`]:[],...n.formula==="notRead"?["formula not read"]:[],...n.formula==="unreadable"?["formula unreadable"]:[],...e.field&&!r?[`a row it refuses goes again without ${e.field}`]:[]],l=y(n.message)?`: "${y(n.message)}"`:"";return`validation rule "${y(n.rule)}"${t}${l}${i.length>0?` (${i.join("; ")})`:""}`}case"duplicate_rule":{let t=`duplicate rule "${y(n.rule)}"`;if(n.action==="block")return`${t}: blocks an insert it matches: a row it matches is refused, whatever allowSave says`;if(n.action==="allow"){let i=[n.alert===!0?"an alert":"",n.report===!0?"a report":""].filter(Boolean).join(" and ");return`${t}: allows an insert it matches${i?`, with ${i}`:""}: the run saves it (allowSave=true)`}return`${t}: what it does on insert was not read: a rule that blocks refuses a row it matches`}case"lookup_filter":return`lookup filter on ${e.field??""}: not checked before the run; `+(n.optional===!0?"a lookup it refuses is left empty":"the lookup is required, and a row it refuses is refused");case"object_not_createable":return"the user the run writes as may not create its records in the target: every row is skipped, after the objects written before it, unless the object is left out";case"object_platform_only":return"no user can create its records in the target, the platform writes them itself: the run skips every row of it";case"object_setup_only":return"no user can create its records in the target, not even one with Modify All Data, and no permission set gives Create on it: setup the org keeps as records, or the platform's own; the run skips every row of it";case"object_feature_off":return"even a user with Modify All Data may not create its records in the target, though a permission set can give Create on it: a feature or licence the target has not turned on for that user keeps it closed; turn it on, or every row is skipped, after the objects written before it, unless the object is left out";case"object_through_parent":{let t=D(n.editOn);return`no permission set gives Create on it: ${t.length>0?`the user the run writes as creates its records with Edit on ${t.join(" and ")}, which they hang from, or no user can`:"the records they hang from may open it to the user the run writes as, or no user can: read as a user with Modify All Data, the target would tell"}; every row is skipped, after the objects written before it, unless the object is left out`}case"api_budget":{let t=`about ${L(n.calls)} call(s) (${L(n.writes)} write(s) of 200 rows, ${L(n.reads)} read(s))`,i=n.estimate==="atMost"?`at most ${t}, counted on whole tables`:n.estimate==="unknown"?"an unknown number of calls: an object was never counted":t,l=n.budgetRead===!1?"the daily requests left could not be read":`${L(n.remaining)} of ${L(n.max)} daily requests left`;return`API budget: the run takes ${i}; ${l}`}default:return e.kind}}function xt(e,r,n){return $e(e).map(({permission:t,permissionSet:i,others:l})=>{if(!i)return` ${t}: no permission set of ${r} holds it: an admin creates one that includes it`;let f=l.length>0?`; also held by ${l.map(d=>d.name).join(", ")}`:"",p=n?`: ${Se(i.name,r,n)}`:"";return` ${t}: held by permission set ${i.name}, the smallest${f}${p}`})}function Wt(e,r,n={}){let t=[`target gaps: what ${r} holds against the rows, read from its metadata`],i=e.gaps.map(u=>u.id),l=e.gaps.filter(u=>u.kind==="api_budget"),f=e.gaps.filter(u=>u.kind!=="api_budget"),p=[...new Set(f.map(u=>u.objectApiName))].sort((u,o)=>u.localeCompare(o));for(let u of p){t.push(` ${u}`);for(let o of f.filter(a=>a.objectApiName===u)){let a=Ee(o,n.lifted);t.push(` ${Xe(o,n.decisions,i,a)}`),a||t.push(...xt(o,r,n.username))}}f.length===0&&t.push(e.unread.length>0?" nothing found in what could be read":" no validation rule, duplicate rule, field only the target requires or lookup filter");for(let u of l)t.push(` ${Xe(u,n.decisions,i)}`);let d=f.filter(u=>u.detail?.formula==="notRead").length;d>0&&t.push(` ${d} validation rule formula(s) not read: the read takes ${n.formulasBound??ie} at most`);for(let{part:u,reason:o}of e.unread)t.push(` ${St[u]??u} could not be read: ${o}`);return t.push(` read in ${e.requests} request(s) to ${r}`),t}export{et as a,W as b,ie as c,It as d,oe as e,gt as f,q as g,mt as h,tt as i,wt as j,Vt as k,kt as l,Bt as m,Ut as n,Je as o,nt as p,Qt as q,Wt as r};
|
|
@@ -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,b,c,d,e,f,g,h,i,j,k,l,m}from"./chunk-XLXIPIEW.mjs";import"./chunk-TTKXMDBN.mjs";import"./chunk-5TC3QB4U.mjs";import"./chunk-2BA2XKAY.mjs";import"./chunk-JEERQRLW.mjs";import"./chunk-5P4PHJRL.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-SIHORWVK.mjs";import"./chunk-NZC67CGR.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-JPUR2CFX.mjs";import"./chunk-LPBMBW3O.mjs";import"./chunk-IFETCRWE.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-SAR5622P.mjs";import"./chunk-EQNW3UC2.mjs";import"./chunk-GSKCGQIP.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-ZUTYVST5.mjs";import"./chunk-CU2INBND.mjs";import"./chunk-YKKRIEH4.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-VYXMVJL5.mjs";import"./chunk-AEKONPF4.mjs";import"./chunk-JWTSEDIQ.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-CION3VMZ.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-L77FJZEP.mjs";import"./chunk-A527W53V.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-GGD7ON3M.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{h as REWIND_MUTING_STEP_WORDS,g as REWIND_STEP_WORDS,i as acceptanceRefusal,j as boundsRefusal,k as boundsRefusals,e as firedCount,m as notConfirmedRefusal,a as objectsWrittenBy,b as previewTotals,f as remakeUnasked,d as rewindStepsOf,c as selectionDiff,l as undeletableUnattendedRefusal};
|
|
@@ -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{ib as o,ic as c}from"./chunk-TTFDUKUS.mjs";var u=new Set(["picklist","multipicklist"]);function d(s){return(s.picklistValues??[]).filter(n=>n.active!==!1&&typeof n.value=="string"&&n.value!=="").map(n=>n.value)}function b(s){let n=new Map,r=t=>{let i=n.get(t);return i||(i=s(t),n.set(t,i)),i};return{async createable(t){let{fields:i}=await r(t);return new Set(i.filter(e=>e.createable===!0).map(e=>e.name))},async visible(t){let{fields:i}=await r(t);return new Set(i.map(e=>e.name))},async computed(t){let{fields:i}=await r(t);return new Set(i.filter(e=>e.calculated===!0||e.autoNumber===!0).map(e=>e.name))},async picklistValues(t){let{fields:i}=await r(t),e=new Map;for(let a of i){if(!u.has(a.type??""))continue;let l=d(a);l.length>0&&e.set(a.name,l)}return e},async keyPrefix(t){let{keyPrefix:i}=await r(t);return typeof i=="string"&&i.length===3?i:void 0},async lengths(t){let{fields:i}=await r(t);return new Map(i.flatMap(e=>typeof e.length=="number"&&e.length>0?[[e.name,e.length]]:[]))},async required(t){let{fields:i}=await r(t);return i.filter(e=>e.createable===!0&&e.nillable===!1&&e.defaultedOnCreate!==!0&&(e.referenceTo??[]).length===0).map(e=>({fieldApiName:e.name,type:e.type??"string",picklistValues:d(e),referenceTo:[],length:e.length??0,integerDigits:o({...e,type:e.type??"string"}),objectApiName:t,required:!0}))}}}function m(s,n){return async r=>(await s.required(r)).filter(t=>!c(r,t.fieldApiName,n.includes(r)?"person":"business"))}export{b as a,m 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{h as M,i as T}from"./chunk-
|
|
7
|
+
import{h as M,i as T}from"./chunk-6XYKJSGX.mjs";import{o as b}from"./chunk-ZUTYVST5.mjs";import{Hb as _,Ib as h,Jb as p,Kb as R,Ob as C,Pb as S,Sb as k}from"./chunk-TTFDUKUS.mjs";async function Y(r,e){try{let[c,i]=await Promise.all([r(R),e(R)]),d=c[0]?.Id,a=i[0]?.Id;return typeof d=="string"&&typeof a=="string"?{source:d,target:a}:void 0}catch{return}}function v(r,e){return r===h||e.some(c=>typeof c[p]=="string")}var K=[p,C,S];function A(r,e,c,i,d=()=>!1){let a={...e,standsFor:new Map,standardFirst:0,standardMatched:!1,prices:[],leftIn:new Map};if(!c)return a;let o=e.records.map((t,s)=>s),m=t=>({records:t.map(s=>e.records[s]),sources:t.map(s=>e.sources[s]),sourceIds:t.map(s=>e.sourceIds[s])});if(r===h){let t=o.filter(s=>e.sourceIds[s]!==c.source);return t.length===o.length?a:{...m(t),standsFor:new Map,standardFirst:0,standardMatched:!0,prices:[],leftIn:new Map}}if(r!==_)return a;let l=o,I=new Map,P=new Map,O=[];if(i){let{target:t}=i,s=e.sources.filter(n=>!K.some(f=>{let u=n[f];return typeof u=="string"&&u!==""&&d(u)})),E=n=>t.active.has(n)?n:b(void 0,t)?.to,g=M({prices:s,standardBookId:c.source,sellingModels:s.some(n=>typeof n[S]=="string"),writtenIn:E,active:t.active},[]),B=new Set(g.standsFor.keys());l=o.filter(n=>{let f=e.sourceIds[n];return f===void 0||!B.has(f)});let D=new Map(s.map(n=>[n.Id,n[k]]));for(let[n,f]of g.standsFor){I.set(n,f);let u=D.get(n),w=typeof u=="string"?E(u):void 0;typeof u=="string"&&w!==void 0&&P.set(n,{from:u,to:w})}O=T(g.said)}let y=t=>e.sources[t][p]===c.source,F=[...l.filter(y),...l.filter(t=>!y(t))];return{...m(F),standsFor:I,standardFirst:l.filter(y).length,standardMatched:!1,prices:O,leftIn:P}}function Q(r,e){let c=r.prices.map(i=>({...i}));for(let i of e){let d=r.leftIn.get(i),a=d&&(c.find(o=>o.from===d.from&&o.to===d.to&&o.how==="replaced"&&!o.forLines)??c.find(o=>o.from===d.from&&o.to===d.to&&o.how==="replaced"));a&&a.prices--}return c.filter(i=>i.prices>0)}function q(r,e){return e===1?`1 ${r} record held back, not sent: read in a currency the target org does not hold active, it stands for the source's own price of its product and price book in the currency written, which this run did not write.`:`${e} ${r} records held back, not sent: read in a currency the target org does not hold active, they stand for the source's own prices of their product and price book in the currency written, which this run did not write.`}var H="The standard price book is matched to the target org's, never written.";function $(r,e){return e.prices.length===0&&!e.standardMatched?r:{...r,...e.prices.length>0?{pricesSettled:[...e.prices]}:{},...e.standardMatched?{standardPricebookMatched:!0}:{}}}export{Y as a,v as b,A as c,Q as d,q as e,H as f,$ as g};
|
|
@@ -4,7 +4,7 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a as le}from"./chunk-TUACWKIH.mjs";import{
|
|
7
|
+
import{a as le}from"./chunk-TUACWKIH.mjs";import{Aa as de,ta as ce,zc as ue}from"./chunk-TTFDUKUS.mjs";import{b as k,e as I,k as b,l as p,r as ae,s as oe,u as G,v as E}from"./chunk-7EANH5PY.mjs";import{appendFile as Be,mkdir as Te,readFile as Je,readdir as $e,rename as Ue,rm as We,stat as He,writeFile as Ze}from"node:fs/promises";import*as M from"node:path";import{appendFile as ke,mkdir as Re,readFile as je,readdir as xe,rename as Oe,rm as Ie,stat as Ae,writeFile as Fe}from"node:fs/promises";import*as $ from"node:path";var Ne="sync-links",Me=2e5,_e=16*1024*1024,J=k().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),Y=k().min(1).max(200),Ee=p({s:Y,t:Y,o:k().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),p:b(ae([J,J])).max(5e4),l:E(!0).optional()}),De=p({s:Y,t:Y,f:b(J).max(1e6)});function T(s){return s.slice(0,15)}function Ke(s){return s.replace(/[^A-Za-z0-9_-]/g,"_")}function Ce(s){try{return JSON.parse(s)}catch{return}}function Le(s){let e=new Map;for(let t of s.split(`
|
|
8
8
|
`)){if(t.trim()==="")continue;let n=Ce(t),r=Ee.safeParse(n);if(r.success){let{s:y,t:R,o:C,p:P,l:D}=r.data;for(let[_,K]of P){let c=`${y}|${R}|${T(_)}`;e.delete(c),e.set(c,{s:y,t:R,o:C,source:_,target:K,...D===!0?{linked:!0}:{}})}continue}let i=De.safeParse(n);if(!i.success)continue;let{s:o,t:f,f:a}=i.data,g=new Set(a.map(T));for(let[y,R]of e)R.s===o&&R.t===f&&g.has(T(R.target))&&e.delete(y)}return e}function ht(s){return new H({storagePath:s,readFile:e=>je(e,"utf8"),writeFile:(e,t)=>Fe(e,t,"utf8"),appendFile:(e,t)=>ke(e,t,"utf8"),rename:(e,t)=>Oe(e,t),mkdir:async e=>{await Re(e,{recursive:!0})},rm:e=>Ie(e,{force:!0}),listFiles:async e=>{let t;try{t=await xe(e)}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of t){let i=await Ae($.join(e,r)).catch(()=>{});i?.isFile()&&n.push({name:r,size:i.size})}return n}})}var H=class{constructor(e){this.deps=e;this.dir=$.join(e.storagePath,Ne),this.maxPairs=e.maxPairs??Me,this.compactBytes=e.compactBytes??_e}deps;dir;maxPairs;compactBytes;queue=Promise.resolve();fileOf(e){return $.join(this.dir,`${Ke(e)}.ndjson`)}inTurn(e){let t=this.queue.then(e);return this.queue=t.catch(()=>{}),t}async read(e){let t;try{t=await this.deps.readFile(this.fileOf(e))}catch(n){if(n?.code==="ENOENT")return new Map;throw n}return Le(t)}async load(e,t){await this.queue;let n=new Map;for(let r of(await this.read(e)).values())r.s===t.sourceOrgId&&r.t===t.targetOrgId&&n.set(T(r.source),r.target);return n}async linked(e,t){await this.queue;let n=new Set;for(let r of(await this.read(e)).values())r.linked&&r.s===t.sourceOrgId&&r.t===t.targetOrgId&&n.add(T(r.source));return n}record(e,t,n,r,i=!1){let o=r.filter(([f,a])=>J.safeParse(f).success&&J.safeParse(a).success);return o.length===0?Promise.resolve():this.inTurn(async()=>{await this.deps.mkdir(this.dir);let f=this.fileOf(e);for(let a=0;a<o.length;a+=5e4){let g={s:t.sourceOrgId,t:t.targetOrgId,o:n,p:o.slice(a,a+5e4),...i?{l:!0}:{}};await this.deps.appendFile(f,`${JSON.stringify(g)}
|
|
9
9
|
`)}await this.keepWithinBounds(e)})}forget(e,t,n){let r=new Set(n.filter(i=>J.safeParse(i).success).map(T));return r.size===0?Promise.resolve(0):this.inTurn(async()=>{let i=0,o=[];for(let a of(await this.read(e)).values())a.s!==t.sourceOrgId||a.t!==t.targetOrgId||r.has(T(a.target))&&(i++,o.push(a.target));if(i===0)return 0;let f={s:t.sourceOrgId,t:t.targetOrgId,f:[...new Set(o)]};return await this.deps.appendFile(this.fileOf(e),`${JSON.stringify(f)}
|
|
10
10
|
`),await this.keepWithinBounds(e),i})}delete(e){return this.inTurn(()=>this.deps.rm(this.fileOf(e)))}async keepWithinBounds(e){let t=this.fileOf(e),n=$.basename(t);if(((await this.deps.listFiles(this.dir)).find(a=>a.name===n)?.size??0)<=this.compactBytes)return;let i=[...(await this.read(e)).values()].slice(-this.maxPairs),o=[];for(let a of i){let g=o[o.length-1];if(g?.s===a.s&&g.t===a.t&&g.o===a.o&&g.l===a.linked&&g.p.length<5e4){g.p.push([a.source,a.target]);continue}o.push({s:a.s,t:a.t,o:a.o,p:[[a.source,a.target]],...a.linked?{l:!0}:{}})}let f=`${t}.${process.pid}.tmp`;await this.deps.writeFile(f,o.map(a=>`${JSON.stringify(a)}
|