sandforge 0.0.0-stage → 1.79.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/LICENSE +21 -0
- package/README.md +54 -2
- package/THIRD-PARTY-NOTICES.md +1624 -0
- package/bin/sandforge-autopilot.mjs +12 -0
- package/bin/sandforge-backup.mjs +12 -0
- package/bin/sandforge-checkpoint.mjs +12 -0
- package/bin/sandforge-cleanup.mjs +12 -0
- package/bin/sandforge-clone.mjs +12 -0
- package/bin/sandforge-compare.mjs +12 -0
- package/bin/sandforge-dataops.mjs +12 -0
- package/bin/sandforge-empty.mjs +12 -0
- package/bin/sandforge-env.mjs +12 -0
- package/bin/sandforge-frozen.mjs +12 -0
- package/bin/sandforge-mcp.mjs +12 -0
- package/bin/sandforge-monitor.mjs +12 -0
- package/bin/sandforge-seed.mjs +12 -0
- package/bin/sandforge-sync.mjs +12 -0
- package/bin/sandforge.mjs +12 -0
- package/lib/catalogue.en.json +1 -0
- package/lib/chunk-2BVTCNWA.mjs +7 -0
- package/lib/chunk-2S5OMIIA.mjs +7 -0
- package/lib/chunk-2YIV2OB2.mjs +7 -0
- package/lib/chunk-342FN7AO.mjs +9 -0
- package/lib/chunk-36U7IQ6Y.mjs +25 -0
- package/lib/chunk-3CA767QB.mjs +7 -0
- package/lib/chunk-3DCUADVK.mjs +7 -0
- package/lib/chunk-3F5YMM2F.mjs +7 -0
- package/lib/chunk-3OHPD72J.mjs +9 -0
- package/lib/chunk-3RYLICRX.mjs +7 -0
- package/lib/chunk-3SRXFZSD.mjs +7 -0
- package/lib/chunk-42RER7V4.mjs +14 -0
- package/lib/chunk-4GL773D5.mjs +7 -0
- package/lib/chunk-4HFRHFGQ.mjs +7 -0
- package/lib/chunk-4HW535YJ.mjs +7 -0
- package/lib/chunk-4NAHW2D3.mjs +7 -0
- package/lib/chunk-4SNDMJP2.mjs +7 -0
- package/lib/chunk-4TLYUZD5.mjs +7 -0
- package/lib/chunk-4U6NXJNL.mjs +7 -0
- package/lib/chunk-4XZ5YT5O.mjs +7 -0
- package/lib/chunk-55HEMHEG.mjs +7 -0
- package/lib/chunk-57VHUYNG.mjs +10 -0
- package/lib/chunk-5AJRHRXA.mjs +20 -0
- package/lib/chunk-5CD257T7.mjs +7 -0
- package/lib/chunk-5HMAPZBV.mjs +7 -0
- package/lib/chunk-5LFSFYFJ.mjs +7 -0
- package/lib/chunk-5MMXFWPD.mjs +7 -0
- package/lib/chunk-5O6JOMHS.mjs +13 -0
- package/lib/chunk-5P4PHJRL.mjs +9 -0
- package/lib/chunk-5QKTYCWE.mjs +11 -0
- package/lib/chunk-66NMFCWX.mjs +7 -0
- package/lib/chunk-6EBMEGZB.mjs +7 -0
- package/lib/chunk-6LAXTAVN.mjs +7 -0
- package/lib/chunk-6MUEPV7M.mjs +9 -0
- package/lib/chunk-6QSM2WIH.mjs +10 -0
- package/lib/chunk-75ADZS6B.mjs +7 -0
- package/lib/chunk-7EANH5PY.mjs +68 -0
- package/lib/chunk-7F54PZUS.mjs +7 -0
- package/lib/chunk-7UQD6V6F.mjs +7 -0
- package/lib/chunk-AAVJ5XVX.mjs +7 -0
- package/lib/chunk-ALJVEUUS.mjs +7 -0
- package/lib/chunk-ALUFROGA.mjs +7 -0
- package/lib/chunk-AR7BE5O2.mjs +7 -0
- package/lib/chunk-AUTM6H6Z.mjs +7 -0
- package/lib/chunk-AV5SWEHP.mjs +9 -0
- package/lib/chunk-B45CNPUX.mjs +47 -0
- package/lib/chunk-BILZ3SSR.mjs +7 -0
- package/lib/chunk-BN7A4GRQ.mjs +7 -0
- package/lib/chunk-BOGNK4LV.mjs +7 -0
- package/lib/chunk-BS5T3MOQ.mjs +7 -0
- package/lib/chunk-BZ24IAP5.mjs +7 -0
- package/lib/chunk-CA5NAXSU.mjs +7 -0
- package/lib/chunk-CE6ZDGBB.mjs +7 -0
- package/lib/chunk-CGWXQX75.mjs +7 -0
- package/lib/chunk-CHCHAE4B.mjs +7 -0
- package/lib/chunk-D3QRXG63.mjs +787 -0
- package/lib/chunk-DBFJB2B6.mjs +7 -0
- package/lib/chunk-DLDX6RRC.mjs +7 -0
- package/lib/chunk-EADHKH3A.mjs +7 -0
- package/lib/chunk-EEVVGGM6.mjs +7 -0
- package/lib/chunk-ENLBYECD.mjs +7 -0
- package/lib/chunk-EQF2IJS2.mjs +11 -0
- package/lib/chunk-EQOQASDQ.mjs +7 -0
- package/lib/chunk-F2424IKX.mjs +7 -0
- package/lib/chunk-F74IHMGL.mjs +7 -0
- package/lib/chunk-FOVVHGEP.mjs +7 -0
- package/lib/chunk-FQBRBBY4.mjs +7 -0
- package/lib/chunk-FQGHL7GR.mjs +259 -0
- package/lib/chunk-GAM726CK.mjs +7 -0
- package/lib/chunk-GCOB7K5N.mjs +7 -0
- package/lib/chunk-GMY5427L.mjs +7 -0
- package/lib/chunk-GNC27UEU.mjs +7 -0
- package/lib/chunk-H2PJNIYJ.mjs +7 -0
- package/lib/chunk-H45UXY6G.mjs +7 -0
- package/lib/chunk-HCIDVIOW.mjs +7 -0
- package/lib/chunk-HF6LAK3G.mjs +7 -0
- package/lib/chunk-HJC7AIBK.mjs +7 -0
- package/lib/chunk-HJKM3E56.mjs +7 -0
- package/lib/chunk-HTJ5OGP5.mjs +7 -0
- package/lib/chunk-HUMEKZT5.mjs +8 -0
- package/lib/chunk-HV2MXMGI.mjs +7 -0
- package/lib/chunk-HXS7ORUF.mjs +11 -0
- package/lib/chunk-I3JKJTLO.mjs +110 -0
- package/lib/chunk-I7O6C2B5.mjs +8 -0
- package/lib/chunk-IAZB4WIL.mjs +7 -0
- package/lib/chunk-IC2C2GOF.mjs +8 -0
- package/lib/chunk-IEYG5ATY.mjs +7 -0
- package/lib/chunk-INIQ23K6.mjs +7 -0
- package/lib/chunk-INIT2UKJ.mjs +7 -0
- package/lib/chunk-J7HVXMSW.mjs +7 -0
- package/lib/chunk-JVL444U5.mjs +7 -0
- package/lib/chunk-K22PA4XL.mjs +7 -0
- package/lib/chunk-K2FBZIXY.mjs +7 -0
- package/lib/chunk-KLX67VPL.mjs +7 -0
- package/lib/chunk-L776PUMV.mjs +7 -0
- package/lib/chunk-LQ4DRFUH.mjs +9 -0
- package/lib/chunk-LRFAIUN7.mjs +7 -0
- package/lib/chunk-LV6G4XTK.mjs +7 -0
- package/lib/chunk-M6P5ZZLE.mjs +7 -0
- package/lib/chunk-MTMH6H2A.mjs +8 -0
- package/lib/chunk-MYTIL2JD.mjs +10 -0
- package/lib/chunk-NEVXIGR6.mjs +10 -0
- package/lib/chunk-NGSMZZDA.mjs +7 -0
- package/lib/chunk-NHWE66K5.mjs +7 -0
- package/lib/chunk-NM4MDLK4.mjs +7 -0
- package/lib/chunk-NTDN2JQZ.mjs +19 -0
- package/lib/chunk-NTOVCTRS.mjs +7 -0
- package/lib/chunk-NZ5ZZLKS.mjs +7 -0
- package/lib/chunk-OQOZAPCI.mjs +7 -0
- package/lib/chunk-OTWRDD6L.mjs +7 -0
- package/lib/chunk-P2PJYWGQ.mjs +7 -0
- package/lib/chunk-P42X3B4D.mjs +7 -0
- package/lib/chunk-P7GSGFJO.mjs +7 -0
- package/lib/chunk-PA3MKJVH.mjs +7 -0
- package/lib/chunk-PBI4BYWW.mjs +7 -0
- package/lib/chunk-PNCONNFJ.mjs +10 -0
- package/lib/chunk-PTTHSSQO.mjs +7 -0
- package/lib/chunk-PUOX4NBJ.mjs +8 -0
- package/lib/chunk-PZTSVQSF.mjs +7 -0
- package/lib/chunk-QPF6C5MX.mjs +7 -0
- package/lib/chunk-QQZZMKU3.mjs +7 -0
- package/lib/chunk-QROPNEGY.mjs +14 -0
- package/lib/chunk-QRV2OSIS.mjs +7 -0
- package/lib/chunk-QSRAEUGZ.mjs +7 -0
- package/lib/chunk-QWT2C74M.mjs +7 -0
- package/lib/chunk-RAAANPPG.mjs +7 -0
- package/lib/chunk-RACDTRZA.mjs +7 -0
- package/lib/chunk-RFEO2KAN.mjs +7 -0
- package/lib/chunk-RH3N2H7P.mjs +7 -0
- package/lib/chunk-RSWDYIHY.mjs +37 -0
- package/lib/chunk-RSYICMZG.mjs +8 -0
- package/lib/chunk-SAR5622P.mjs +7 -0
- package/lib/chunk-SBIMVCXT.mjs +101 -0
- package/lib/chunk-SCKUIE3R.mjs +7 -0
- package/lib/chunk-SFURUNJM.mjs +7 -0
- package/lib/chunk-SIOZXPFG.mjs +7 -0
- package/lib/chunk-SRPWW4A2.mjs +10 -0
- package/lib/chunk-SRQDABQ2.mjs +15 -0
- package/lib/chunk-SVS6UMDU.mjs +323 -0
- package/lib/chunk-T63U4OZJ.mjs +7 -0
- package/lib/chunk-TBZMC2VV.mjs +11 -0
- package/lib/chunk-TEOLMRDO.mjs +7 -0
- package/lib/chunk-TLH7AD35.mjs +7 -0
- package/lib/chunk-TNXUU6W7.mjs +14 -0
- package/lib/chunk-TQX3PURV.mjs +7 -0
- package/lib/chunk-TUACWKIH.mjs +7 -0
- package/lib/chunk-TW3N6W5Z.mjs +7 -0
- package/lib/chunk-TYYOBZMU.mjs +10 -0
- package/lib/chunk-TZE3Y7IQ.mjs +7 -0
- package/lib/chunk-UNDIBZWG.mjs +7 -0
- package/lib/chunk-VGW4MXXZ.mjs +7 -0
- package/lib/chunk-VHI54FBK.mjs +441 -0
- package/lib/chunk-VXHDBYMI.mjs +7 -0
- package/lib/chunk-W7KFAY55.mjs +7 -0
- package/lib/chunk-WFEB5X4U.mjs +8 -0
- package/lib/chunk-WIO4XO4F.mjs +7 -0
- package/lib/chunk-WJY54JO7.mjs +13 -0
- package/lib/chunk-WR2GIKWE.mjs +7 -0
- package/lib/chunk-WRU5FJFC.mjs +7 -0
- package/lib/chunk-X2PY6MWZ.mjs +7 -0
- package/lib/chunk-X65MT4W3.mjs +7 -0
- package/lib/chunk-XBG5SP6Q.mjs +7 -0
- package/lib/chunk-XCA5AONB.mjs +7 -0
- package/lib/chunk-XEFDB2R4.mjs +7 -0
- package/lib/chunk-XETCPL7E.mjs +7 -0
- package/lib/chunk-Y5CGXLUB.mjs +7 -0
- package/lib/chunk-Y6J6QFI2.mjs +7 -0
- package/lib/chunk-YAZO75G2.mjs +8 -0
- package/lib/chunk-YBU4Z4QV.mjs +7 -0
- package/lib/chunk-YMJVMFPY.mjs +7 -0
- package/lib/chunk-YPSRZRIT.mjs +7 -0
- package/lib/chunk-YS4G22C2.mjs +7 -0
- package/lib/chunk-YW2SBL4Z.mjs +7 -0
- package/lib/chunk-YYZL7UGV.mjs +7 -0
- package/lib/chunk-Z7X534S4.mjs +10 -0
- package/lib/chunk-ZE6HKRR4.mjs +9 -0
- package/lib/chunk-ZHJP7L3K.mjs +7 -0
- package/lib/chunk-ZJKCWBRJ.mjs +7 -0
- package/lib/chunk-ZLZRU6MO.mjs +7 -0
- package/lib/chunk-ZOVSMN5C.mjs +7 -0
- package/lib/chunk-ZPYJPGDK.mjs +7 -0
- package/lib/chunk-ZQOZ4EFW.mjs +7 -0
- package/lib/chunk-ZUTYVST5.mjs +7 -0
- package/lib/chunk-ZXH4MBWP.mjs +7 -0
- package/lib/chunk-ZYEE34WO.mjs +7 -0
- package/lib/sandforge-autopilot.mjs +157 -0
- package/lib/sandforge-backup.mjs +99 -0
- package/lib/sandforge-checkpoint.mjs +353 -0
- package/lib/sandforge-cleanup.mjs +56 -0
- package/lib/sandforge-clone.mjs +7 -0
- package/lib/sandforge-compare.mjs +54 -0
- package/lib/sandforge-dataops.mjs +7 -0
- package/lib/sandforge-empty.mjs +140 -0
- package/lib/sandforge-env.mjs +355 -0
- package/lib/sandforge-frozen.mjs +263 -0
- package/lib/sandforge-mcp.mjs +40 -0
- package/lib/sandforge-monitor.mjs +43 -0
- package/lib/sandforge-seed.mjs +7 -0
- package/lib/sandforge-sync.mjs +7 -0
- package/lib/sandforge.mjs +28 -0
- package/package.json +52 -4
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{c as Xo}from"./chunk-VHI54FBK.mjs";import"./chunk-AAVJ5XVX.mjs";import"./chunk-WFEB5X4U.mjs";import"./chunk-AR7BE5O2.mjs";import"./chunk-3OHPD72J.mjs";import"./chunk-3RYLICRX.mjs";import"./chunk-PUOX4NBJ.mjs";import"./chunk-EQF2IJS2.mjs";import"./chunk-HTJ5OGP5.mjs";import"./chunk-QQZZMKU3.mjs";import"./chunk-PZTSVQSF.mjs";import"./chunk-W7KFAY55.mjs";import"./chunk-5HMAPZBV.mjs";import"./chunk-YPSRZRIT.mjs";import"./chunk-FOVVHGEP.mjs";import{o as $t}from"./chunk-SVS6UMDU.mjs";import"./chunk-AUTM6H6Z.mjs";import"./chunk-INIQ23K6.mjs";import"./chunk-RAAANPPG.mjs";import{a as Jt}from"./chunk-ZE6HKRR4.mjs";import{a as yo,b as wo,c as bo,d as Do,e as $o,f as It,g as xt,h as Nt,i as Xe,j as Lo,k as Ne,l as Fe}from"./chunk-LRFAIUN7.mjs";import"./chunk-OQOZAPCI.mjs";import"./chunk-RSYICMZG.mjs";import"./chunk-IAZB4WIL.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-XEFDB2R4.mjs";import"./chunk-H45UXY6G.mjs";import"./chunk-WRU5FJFC.mjs";import"./chunk-GMY5427L.mjs";import"./chunk-GNC27UEU.mjs";import"./chunk-YBU4Z4QV.mjs";import"./chunk-5P4PHJRL.mjs";import{Ba as Dt,K as Qo,a as Ao,g as Ft,h as _o,i as qo,j as zo,k as Go,l as Uo,m as Wo,n as jt,o as Ho,p as Ko,t as je}from"./chunk-D3QRXG63.mjs";import{h as No,i as Fo,k as jo}from"./chunk-NM4MDLK4.mjs";import{a as Ro}from"./chunk-BS5T3MOQ.mjs";import"./chunk-TEOLMRDO.mjs";import"./chunk-FQBRBBY4.mjs";import"./chunk-YS4G22C2.mjs";import{a as Bo}from"./chunk-SCKUIE3R.mjs";import"./chunk-QROPNEGY.mjs";import{b as lt,e as Zt}from"./chunk-BZ24IAP5.mjs";import{c as tn,d as nn,f as on}from"./chunk-AV5SWEHP.mjs";import"./chunk-I7O6C2B5.mjs";import"./chunk-WR2GIKWE.mjs";import"./chunk-YMJVMFPY.mjs";import"./chunk-ALJVEUUS.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-BOGNK4LV.mjs";import{b as rn,c as sn,d as Ge,e as an,f as ao,g as co,h as lo,i as uo,j as po,k as fo,l as vt,r as mo,s as ho,t as go}from"./chunk-36U7IQ6Y.mjs";import{h as ko,i as Po,j as Co,k as Mo,l as Mt,m as Io,n as xo}from"./chunk-XETCPL7E.mjs";import{a as So,b as Et,c as Pt,d as Oo,e as To,f as vo,g as Eo,h as Ct}from"./chunk-K2FBZIXY.mjs";import"./chunk-Z7X534S4.mjs";import"./chunk-6QSM2WIH.mjs";import"./chunk-WJY54JO7.mjs";import{d as zn}from"./chunk-T63U4OZJ.mjs";import{d as qn}from"./chunk-DBFJB2B6.mjs";import"./chunk-NEVXIGR6.mjs";import"./chunk-NTDN2JQZ.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-F74IHMGL.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-Y5CGXLUB.mjs";import"./chunk-3F5YMM2F.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-SAR5622P.mjs";import{b as dt,c as ze}from"./chunk-L776PUMV.mjs";import{A as Ye,r as Hn,s as At,w as xe,x as Kn,y as Yn}from"./chunk-6MUEPV7M.mjs";import"./chunk-HJC7AIBK.mjs";import"./chunk-OTWRDD6L.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-TYYOBZMU.mjs";import{a as ct,b as Xt}from"./chunk-RH3N2H7P.mjs";import{a as me,i as Ie,k as En,n as Pn,o as Cn,p as Mn,s as In,t as xn,u as Nn,v as Fn}from"./chunk-ZUTYVST5.mjs";import"./chunk-55HEMHEG.mjs";import"./chunk-P42X3B4D.mjs";import"./chunk-TUACWKIH.mjs";import{Ba as ro,D as Rt,Ia as ve,Ja as so,K as Xn,L as Vn,N as Jn,Q as St,S as Qe,T as Zn,W as eo,Wa as io,Xa as Tt,_ as Ot,ka as to,r as Gn,s as Un,w as Wn,wa as no,xa as oo,y as Qn}from"./chunk-VXHDBYMI.mjs";import{q as kt}from"./chunk-ENLBYECD.mjs";import{b as mt,d as ht,e as Tn}from"./chunk-PA3MKJVH.mjs";import{a as le}from"./chunk-4TLYUZD5.mjs";import"./chunk-ZLZRU6MO.mjs";import{a as jn,b as gt,c as yt,f as Dn,h as $n,j as He,l as Ln,m as Bn}from"./chunk-WIO4XO4F.mjs";import{a as We}from"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import{i as vn}from"./chunk-INIT2UKJ.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-PNCONNFJ.mjs";import{X as yn,Y as wn,Z as bn,_ as An,a as cn,b as oe,c as Ue,ca as Me,d as dn,e as ln,ea as kn,f as un,ha as Rn,ia as Sn,ja as On,l as pt,m as pn,n as fn,o as mn,p as ae,q as fe,r as ft,s as Ce,t as hn,y as gn}from"./chunk-CGWXQX75.mjs";import{a as he,h as ge}from"./chunk-TZE3Y7IQ.mjs";import{b as Ke,c as wt,j as bt,k as _n}from"./chunk-SIOZXPFG.mjs";import"./chunk-UNDIBZWG.mjs";import{b as te}from"./chunk-CA5NAXSU.mjs";import{a as Vt,c as en,e as ut,g as Yo}from"./chunk-MTMH6H2A.mjs";import{Ab as Wt,Eb as Te,Fb as Ae,Gb as Be,Hb as Ee,Ib as Ht,Kb as at,Lb as _e,Mb as Pe,Rb as Kt,Tb as Yt,bd as qe,fc as Qt,vb as it,yb as Gt,zb as Ut}from"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-SBIMVCXT.mjs";import"./chunk-NTOVCTRS.mjs";var Bt=ho,_t=mo,ke=200;function wr(l,e){let t=new Set(e?.fields.map(o=>o.name)??[]),n=new Set(l.split(", "));for(let o of[me,Pe])t.has(o)&&n.add(o);return[...n].join(", ")}var br=10,Ar=new Set([ae]),ye="IsPersonAccount",Ve="IsStandard",Je=class{maxConcurrent;constructor(e=10){this.maxConcurrent=e}async listObjects(e,t,n){let[o,r]=await Promise.all([e.describeGlobal(),t.describeGlobal()]),s=new Set(o.sobjects.filter(c=>c.createable).map(c=>c.name)),i=ht(r.sobjects.filter(c=>!s.has(c.name)),await this.toolingObjects(t)),a=new Map(r.sobjects.map(c=>[c.name,c.createable!==!1]));return o.sobjects.filter(c=>c.queryable&&(c.createable||a.get(c.name)===!0)).filter(c=>n||c.custom).filter(c=>!mt(c.name,i)).map(c=>({apiName:c.name,label:c.label,custom:c.custom,...a.has(c.name)?a.get(c.name)===!1?{notCreateableInTarget:!0}:{}:{missingInTarget:!0}}))}async countObjects(e,t){return this.countRecords(e,t)}async scan(e,t,n,o,r={}){let s=Vo(r.maxDepth,Bt),i=Vo(r.maxObjects,_t),a=r.onProgress??(()=>{});if(n.length===0)throw new Error("Choose the objects to copy: a scan starts from them, and with none chosen it would describe and count every object of the org.");let c=await e.describeGlobal(),d=[...n],m=await t.describeGlobal(),u=ht(m.sobjects,await this.toolingObjects(t)),p=R=>mt(R,u);d=d.filter(R=>!p(R)),a(`describing ${d.length} selected object(s)\u2026`);let g=await this.describeAll(e,d),y=new Set(g.keys()),f=new Map(c.sobjects.map(R=>[R.name,R.custom])),A=new Map;for(let R of c.sobjects)R.keyPrefix&&A.set(R.keyPrefix,R.name);let w=await this.walkRecords(e,g,y,{isStandard:R=>f.get(R)===!1||!f.has(R)&&!R.includes("__"),includeStandardObjects:o,leftOut:p,keyPrefixes:A,maxDepth:s,maxObjects:i,say:a}),M=new Set(m.sobjects.map(R=>R.name)),I=[...g.keys()].filter(R=>!M.has(R)),q=await this.currenciesOf(e,t,g),Q=await this.personAccountsOf(e,g,y,w.parentIds,{cutShort:w.cutShort,cutAt:w.cutAt});return{objectDescribes:g,autoDiscoveredObjects:w.added,missingInTarget:I,recordCounts:w.recordCounts,totalObjectsScanned:g.size,parentIds:w.parentIds,personAccounts:Q,scope:{maxDepth:s,maxObjects:i,selected:[...y],parents:w.added.map(R=>({objectApiName:R,records:w.parentIds.get(R)?.length??0})),leftEmpty:w.leftEmpty,standardNeeded:w.standardNeeded,...w.followedByDefault.length>0?{followedByDefault:w.followedByDefault}:{},...q?{currencies:q}:{},...w.cutShort.length>0?{cutShort:w.cutShort}:{}}}}async readFitRows(e,t,n=()=>{}){let o=new Set(t.objectDescribes.keys()),r=new Map;for(let s of t.scope.selected){let i=t.objectDescribes.get(s);if(!i)continue;n(`reading the lookups of ${s} to fit it\u2026`);let a=new Set(i.fields.map(u=>u.name)),c=Ze(s,i).filter(u=>u.targets.some(p=>o.has(p))),d=["Id",...new Set(c.map(u=>u.field)),...(s===ae||s===fe)&&a.has(ye)?[ye]:[],...s===Ae&&a.has(Ve)?[Ve]:[]],m=await vn(`SELECT ${d.map(ge).join(", ")} FROM ${ge(s)} ORDER BY Id`,async u=>(await this.readAll(e,u)).records);r.set(s,m.filter(u=>typeof u.Id=="string"))}return r}async walkFrom(e,t,n,o=()=>{}){let r=new Map(t.objectDescribes),s=new Set(r.keys()),i=new Map;for(let[c,d]of r)d.keyPrefix&&i.set(d.keyPrefix,c);let a=await this.walkRecords(e,r,new Set(t.scope.selected),{isStandard:()=>!1,includeStandardObjects:!0,leftOut:c=>!s.has(c),keyPrefixes:i,maxDepth:t.scope.maxDepth,maxObjects:s.size,say:o},n);return{added:a.added,parentIds:a.parentIds,personAccounts:a.personAccounts,leftEmpty:a.leftEmpty,namingSelected:a.namingSelected}}async personAccountsOf(e,t,n,o,r){let s=new Map;for(let i of[ae,fe]){if(!t.get(i)?.fields.some(d=>d.name===ye))continue;let c=`SELECT COUNT() FROM ${ge(i)} WHERE ${ye} = true`;try{let d=r.cutShort.find(u=>u.objectApiName===i)?.copied;if(n.has(i)&&d!==void 0){let u=r.cutAt.get(i)??await this.lastIdOfTheFirst(e,i,d);s.set(i,u!==void 0?(await e.query(`${c} AND Id <= '${he(u)}'`)).totalSize:Math.min((await e.query(c)).totalSize,d));continue}if(n.has(i)){s.set(i,(await e.query(c)).totalSize);continue}let m=0;for(let u of this.chunk([...o.get(i)??[]],ke)){let p=u.map(g=>`'${he(g)}'`).join(", ");m+=(await e.query(`${c} AND Id IN (${p})`)).totalSize}s.set(i,m)}catch(d){le.warn("Autopilot could not count the person accounts it copies",{objectApiName:i,error:te(d)})}}return s}async lastIdOfTheFirst(e,t,n){let{records:o}=await this.readAll(e,`SELECT Id FROM ${ge(t)} ORDER BY Id`),r=o.length>=n?o[n-1]?.Id:void 0;return typeof r=="string"?r:void 0}async currenciesOf(e,t,n){let o=[...n.values()].filter(a=>a.fields.some(c=>c.name===me)).map(a=>a.name).sort();if(o.length===0)return;let r=await Ie(async a=>(await e.query(a)).records,async a=>(await t.query(a)).records),s=r?.target.corporate;if(!r||s===void 0)return;let i=[...r.source.active].filter(a=>!r.target.active.has(a));return i.length>0?{notInTarget:i.sort(),writtenIn:s,objects:o}:void 0}async walkRecords(e,t,n,o,r){let s=new Set(n),i=new Set,a=o.maxObjects,c=o.maxObjects*go,d=new Map,m=[],u=[],p=[],g=new Map,y=[],f=new Map,A=new Map,w=new Map,M=[],I=T=>{let L=t.get(T);return L?Ze(T,L).map(v=>({...v,targets:v.targets.filter(O=>!o.leftOut(O)&&!i.has(O))})).filter(v=>v.targets.length>0):[]},q=T=>["Id",...new Set(I(T).map(L=>L.field)),...r&&(T===ae||T===fe)&&t.get(T)?.fields.some(L=>L.name===ye)?[ye]:[]].map(ge).join(", "),Q=(T,L,v)=>{let O=`${T.objectApiName}.${T.field}>${L}`;d.has(O)||d.set(O,{objectApiName:T.objectApiName,fieldApiName:T.field,target:L,reason:v,...T.required?{required:!0}:{}})},R=new Map,S=(T,L,v)=>{let O=I(T);for(let x of L)for(let _ of O){let W=x[_.field];if(typeof W!="string"||W==="")continue;let U=kr(W,_.targets,o.keyPrefixes,r!==void 0&&_.polymorphic);if(!U)continue;if(n.has(U)){r&&v>0&&M.push({objectApiName:T,field:_.field,required:_.required,target:U,id:W});continue}let re={objectApiName:T,field:_.field,required:_.required};if(v>=o.maxDepth&&!_.required){s.has(U)||Q(re,U,"depth");continue}if(A.get(U)?.has(W))continue;let z=R.get(U)??{ids:new Set,required:!1,via:[]};z.ids.add(W),z.required||=_.required,z.via.some(V=>V.objectApiName===T&&V.field===_.field)||z.via.push(re),R.set(U,z)}},F=[];for(let T of n){if(r){S(T,r.get(T)??[],0);continue}let L=I(T).filter(v=>v.targets.some(O=>!n.has(O)));if(L.length===0){F.push(T);continue}o.say(`reading the lookups of ${T}\u2026`);try{let v=["Id",...new Set(L.map(_=>_.field))].map(ge).join(", "),{records:O,truncated:x}=await this.readAll(e,`SELECT ${v} FROM ${ge(T)} ORDER BY Id`);if(f.set(T,O.length),x){let _=(await this.countRecords(e,[T])).get(T);p.push({objectApiName:T,copied:O.length,..._!==void 0?{total:_}:{}});let W=O[O.length-1]?.Id;typeof W=="string"&&g.set(T,W)}S(T,O,0)}catch(v){le.warn("Autopilot could not read the lookups of a selected object",{objectApiName:T,error:te(v)}),F.push(T)}}for(let[T,L]of await this.countRecords(e,F))L>5e4?(f.set(T,5e4),p.push({objectApiName:T,copied:5e4,total:L})):f.set(T,L);let C=o.maxDepth+br;for(let T=1;R.size>0&&T<=C;T++){let L=R;R=new Map;let v=[];for(let[O,x]of L){if(s.has(O))continue;let _=o.isStandard(O)&&!o.includeStandardObjects,W=_&&!x.required&&Ar.has(O),U;if(_&&!x.required&&!W?U="standard":s.size>=a&&(x.required&&a<c?a++:U="objects"),U){for(let re of x.via)Q(re,O,U);L.delete(O);continue}if(s.add(O),v.push(O),W)u.push({objectApiName:O,referencedBy:x.via.map(re=>`${re.objectApiName}.${re.field}`)});else if(_){let re=x.via[0];m.push({objectApiName:O,neededBy:`${re.objectApiName}.${re.field}`})}}if(v.length>0){let O=v.filter(_=>!t.has(_));O.length>0&&o.say(`describing ${O.length} parent object(s) at depth ${T}\u2026`);let x=await this.describeAll(e,O);for(let _ of v){let W=t.get(_)??x.get(_);W?(t.set(_,W),y.push(_)):(s.delete(_),i.add(_),L.delete(_))}}for(let[O,x]of L){let _=[...x.ids].filter(V=>!A.get(O)?.has(V));if(_.length===0)continue;o.say(`reading ${_.length} ${O} record(s) by id\u2026`);let W=A.get(O)??new Set;A.set(O,W);let U=O===Te,re=U?wr(q(O),t.get(O)):q(O),z=[];for(let V of this.chunk(_,ke)){let ne=V.map(k=>`'${he(k)}'`).join(", "),be=(await e.query(`SELECT ${re} FROM ${ge(O)} WHERE Id IN (${ne})`)).records.filter(k=>typeof k.Id=="string");for(let k of be)W.add(k.Id);z.push(...be);let b=be.filter(k=>k[ye]===!0).length;r&&b>0&&w.set(O,(w.get(O)??0)+b),S(O,be,T)}if(U){let V=await this.standardPricesOf(e,re,z,W);if(V.length>0){o.say(`reading ${V.length} standard price(s) the prices need\u2026`);for(let ne of V)W.add(ne.Id);S(O,V.map(ne=>({...ne,[Be]:void 0})),T)}}}}let ee=new Map;for(let T of y){let L=[...A.get(T)??[]];ee.set(T,L),f.set(T,L.length)}return{added:y,leftEmpty:[...d.values()].filter(T=>!s.has(T.target)),standardNeeded:m,followedByDefault:u.filter(T=>s.has(T.objectApiName)),cutShort:p,cutAt:g,recordCounts:f,parentIds:ee,personAccounts:w,namingSelected:M}}async standardPricesOf(e,t,n,o){let r=s=>[s[_e],s[me],s[Pe]].map(i=>String(i??"")).join("|");try{let[s]=(await e.query(Ee)).records,i=s?.Id;if(typeof i!="string")return[];let a=n.filter(u=>u[Be]!==i),c=[...new Set(a.flatMap(u=>{let p=u[_e];return typeof p=="string"&&p!==""?[p]:[]}))];if(c.length===0)return[];let d=new Set(a.map(r)),m=[];for(let u of this.chunk(c,ke)){let p=u.map(y=>`'${he(y)}'`).join(", "),g=await e.query(`SELECT ${t} FROM ${Te} WHERE ${Be} = '${he(i)}' AND ${_e} IN (${p})`);for(let y of g.records){let f=y.Id;typeof f!="string"||o.has(f)||!d.has(r(y))||m.push(y)}}return m}catch(s){return le.warn("Autopilot could not read the standard prices its prices need",{error:te(s)}),[]}}async readAll(e,t){let{queryMore:n}=e;if(!n){let r=await e.query(t);return{records:r.records,truncated:r.done===!1}}let o=await We({query:r=>e.query(r),queryMore:r=>n.call(e,r)},t);return o.truncated&&le.warn("Autopilot read the lookups of a selected object to its bound only",{records:o.records.length}),{records:o.records,truncated:o.truncated}}async toolingObjects(e){if(!e.tooling)return[];try{return(await e.tooling.describeGlobal()).sobjects.map(n=>n.name)}catch(t){return le.warn("Autopilot could not ask the Tooling API which objects are metadata",{error:te(t)}),[]}}async describeAll(e,t){let n=new Map,o=this.chunk(t,this.maxConcurrent);for(let r of o){let s=await Promise.allSettled(r.map(i=>e.describe(i)));for(let i of s)i.status==="fulfilled"&&n.set(i.value.name,i.value)}return n}async countRecords(e,t){let n=new Map,o=this.chunk(t,this.maxConcurrent);for(let r of o){let s=await Promise.allSettled(r.map(async i=>{let a=await e.query(`SELECT COUNT() FROM ${ge(i)}`);return{name:i,count:a.totalSize}}));for(let i of s)i.status==="fulfilled"&&n.set(i.value.name,i.value.count)}return n}chunk(e,t){let n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n}};function Vo(l,e){return l!==void 0&&Number.isInteger(l)&&l>0?l:e}function Ze(l,e){return e.fields.filter(t=>t.referenceTo.length>0&&Wt(t)).map(t=>({field:t.name,targets:[...t.referenceTo],required:Ut(l,t.name,t.nillable),polymorphic:t.referenceTo.length>1}))}function kr(l,e,t,n=!1){if(e.length===1&&!n)return e[0];let o=t.get(l.slice(0,3));return o!==void 0&&e.includes(o)?o:void 0}var Jo=3,Rr="the source changed since the plan: plan again";function nr(l,e){return{holds:[...l.links.filter(t=>t.kind==="holds"),...l.requiredOfParents,...l.outward.filter(t=>t.required)],kept:e}}function Zo(l,e){return typeof l!="string"||l===""?!1:e===void 0||e!==null&&l.startsWith(e)}function or(l,e,t){let n=new Map(t.map((s,i)=>[s,i])),o=new Set(e),r={links:[],outward:[],requiredOfParents:[]};for(let[s,i]of l)for(let a of Ze(s,i))for(let c of a.targets.filter(d=>l.has(d))){let d=a.polymorphic?{prefix:l.get(c)?.keyPrefix??null}:{},m={objectApiName:s,field:a.field,parent:c,...d};if(!o.has(s))o.has(c)&&a.required&&r.requiredOfParents.push({...m,kind:"holds"});else if(!o.has(c))r.outward.push({...m,required:a.required});else if(a.required)r.links.push({...m,kind:"holds"});else if(c===s)r.links.push({...m,kind:"selfReference"});else{let u=(n.get(c)??0)<(n.get(s)??0);r.links.push({...m,kind:u?"holds":"owed"})}}return r}function rr(l,e){let t=new Set(l),n=new Set(e.links.filter(o=>o.kind!=="holds").map(o=>o.objectApiName));return(o,r)=>t.has(o)&&(r==="insert"||r==="update"&&(n.has(o)||Me[o]!==void 0))}function sr(l,e,t){return typeof l.unread=="string"?{perRecord:[],notCounted:[],unread:l.unread}:lo(qe(l,e,t),t)}function Sr(l){let e=new Map(l.order.map((t,n)=>[t,n]));return l.order.map(t=>{let n=l.rows.get(t)??[],o=l.lookups.links.filter(i=>i.objectApiName===t),r=l.lookups.outward.filter(i=>i.objectApiName===t),s={name:t,rows:n,at:new Map(n.map((i,a)=>[i.Id,a])),heldBefore:[],heldAfter:[],loose:[],named:[],roots:[],followers:[],persons:new Set(t===ae||t===fe?n.flatMap((i,a)=>i[ye]===!0?[a]:[]):[])};return n.forEach((i,a)=>{let c=[],d=[],m=[];for(let u of o){let p=i[u.field];if(!Zo(p,u.prefix))continue;let g={link:u,id:p};u.kind!=="holds"?m.push(g):(e.get(u.parent)??0)<(e.get(t)??0)?c.push(g):d.push(g)}s.heldBefore.push(c),s.heldAfter.push(d),s.loose.push(m),s.named.push(r.flatMap(u=>{let p=i[u.field];return Zo(p,u.prefix)?[{parent:u.parent,id:p}]:[]})),(c.length>0?s.followers:s.roots).push(a)}),s})}function er(l,e){let t=new Map(l.map(r=>[r.name,r])),n=new Map,o=[...e].flatMap(([r,s])=>[...s].map(i=>({name:r,id:i})));for(let r=o.pop();r;r=o.pop()){let s=t.get(r.name),i=s?.at.get(r.id);if(!s||i===void 0)continue;let a=n.get(r.name)??new Set;if(n.set(r.name,a),!a.has(i)){a.add(i);for(let c of[...s.heldBefore[i],...s.heldAfter[i]])o.push({name:c.link.parent,id:c.id})}}return n}function tr(l){return`${l} record${l===1?"":"s"}`}function Or(l,e){return[...l.parentIds].every(([t,n])=>{let o=new Set(e.get(t)?.ids??[]);return n.every(r=>o.has(r))})}async function ir(l){let{budget:e,room:t,mode:n,parents:o,maxRecords:r}=l,s=Sr(l),i=b=>{let k=n.caps?.[b]??n.all;return k===void 0?void 0:Math.max(1,Math.floor(k))},a=s.some(b=>b.heldAfter.some(k=>k.length>0)),c=new Map;for(let b of s){if(b.name!==Ae)continue;let k=b.rows.filter(D=>D[Ve]===!0);k.length>0&&c.set(b.name,new Set(k.map(D=>D.Id)))}let d=er(s,c),m=b=>{let k={kept:new Map,ids:new Map,cut:new Map},D=new Set;for(let $ of s){let j=d.get($.name)??D,J=i($.name),N=$.roots.filter(Z=>!j.has(Z)),G=N.length===0?0:Math.max(1,Math.round(b*Math.min(N.length,J??1/0))),K=vt(N.length,G).map(Z=>N[Z]),B=new Map;for(let Z of $.followers){if(j.has(Z))continue;let we=$.heldBefore[Z].find(Oe=>!k.ids.get(Oe.link.parent)?.has(Oe.id));we?B.set(Z,we.link):K.push(Z)}K.sort((Z,we)=>Z-we);let ie=$.name===fe?K.filter(Z=>$.persons.has(Z)):[],H=ie.length>0?K.filter(Z=>!$.persons.has(Z)):K,se=J===void 0?H.length:Math.max(0,J-j.size-ie.length),de=H.length>se?vt(H.length,se).map(Z=>H[Z]):H,ue=new Set([...j,...ie,...de]);k.kept.set($.name,ue),k.ids.set($.name,new Set([...ue].map(Z=>$.rows[Z].Id))),k.cut.set($.name,B)}if(!a)return k;for(let $=!0;$;){$=!1;for(let j of s){let J=d.get(j.name)??D,N=k.kept.get(j.name)??new Set;for(let G of[...N]){if(J.has(G))continue;let K=[...j.heldAfter[G],...j.heldBefore[G]].find(B=>!k.ids.get(B.link.parent)?.has(B.id));K&&(N.delete(G),k.ids.get(j.name)?.delete(j.rows[G].Id),k.cut.get(j.name)?.set(G,K.link),$=!0)}}}return k},u=b=>{let k=new Map;for(let D of s){let $=0;for(let j of b.kept.get(D.name)??[])D.loose[j].some(N=>b.ids.get(N.link.parent)?.has(N.id))&&$++;$>0&&k.set(D.name,$)}return k},p=(b,k)=>{let D=new Map,$=0;for(let N of s){let G=b.kept.get(N.name)??new Set,K=0;for(let B of G)N.persons.has(B)&&K++;D.set(N.name,G.size),$+=Rt(N.name,{rows:G.size,personAccounts:K})}for(let[N,{records:G,personAccounts:K}]of k)D.set(N,(D.get(N)??0)+G),$+=Rt(N,{rows:G,...K!==void 0?{personAccounts:K}:{}});let j=u(b),J=uo(t,(N,G)=>{let K=D.get(N)??0;return G==="insert"||Me[N]!==void 0?K:j.get(N)??0});return{records:[...D.values()].reduce((N,G)=>N+G,0),bytes:$,roomBytes:J,requests:Jn([...D.values()].map(N=>({rows:N})))}},g=new Map;for(let b of s)for(let k of b.named)for(let{parent:D,id:$}of k){let j=g.get(D)??new Set;g.set(D,j),j.add($)}let y=[...g.values()].reduce((b,k)=>b+k.size,0),f=b=>{let k=new Map,D=0;for(let J of s)for(let N of b.kept.get(J.name)??[])for(let{parent:G,id:K}of J.named[N]){let B=k.get(G)??new Set;k.set(G,B),B.has(K)||D++,B.add(K)}let $=y>0?D/y:0,j=new Map;for(let[J,{ids:N,personAccounts:G}]of o){let K=Math.max(0,N.length-(g.get(J)?.size??0)),B=Math.min(N.length,(k.get(J)?.size??0)+Math.ceil(K*$));B!==0&&j.set(J,{records:B,...G!==void 0?{personAccounts:Math.ceil(G*B/N.length)}:{}})}return j},A=b=>new Map(b.added.map(k=>{let D=b.personAccounts.get(k);return[k,{records:b.parentIds.get(k)?.length??0,...D!==void 0?{personAccounts:D}:{}}]})),w=b=>b.bytes+b.roomBytes<=e.bytes,M=b=>e.runRequests===void 0||b.requests<=e.runRequests,I=b=>r===void 0||b.records<=r,q=b=>w(b)&&M(b)&&I(b),Q=b=>w(b)?M(b)?"maxTotal":"apiRequests":e.terms.limitedBy,R=b=>w(b)?M(b)?{bound:"maxTotal",records:b.records,allowed:r??0}:{bound:"apiRequests",requests:b.requests,allowed:e.runRequests??0}:{bound:"storage",takesMB:(b.bytes+b.roomBytes)/1048576,fitsMB:e.bytes/1048576},S=b=>{if(!w(b)){let k=so((b.bytes+b.roomBytes)/1048576,e.bytes/1048576);return`${k.over} MB`+(b.roomBytes>0?", room for what the org's automation creates under them included":"")+`, past the ${k.bound} MB that fit`}return M(b)?`${tr(b.records)}, past the ${r??0} the run may write`:`about ${b.requests} API requests, past the ${e.runRequests??0} that leave the org a tenth of its daily requests`},F=b=>new Map(s.map(k=>[k.name,[...b.kept.get(k.name)??[]].sort((D,$)=>D-$).map(D=>k.rows[D])])),C=(b,k,D,$,j,J)=>{let N=s.map(B=>{let ie=k.cut.get(B.name)??new Map,H=new Map;for(let de of ie.values()){let ue=`${de.field}
|
|
8
|
+
${de.parent}`,Z=H.get(ue)??{field:de.field,parent:de.parent,count:0};H.set(ue,{...Z,count:Z.count+1})}let se=k.kept.get(B.name)?.size??0;return{objectApiName:B.name,inSource:B.rows.length,kept:se,cutSpread:B.rows.length-se-ie.size,cutWithParent:[...H.values()].sort((de,ue)=>ue.count-de.count)}}),G=new Map,K=(B,ie,H)=>{let se=`${B}
|
|
9
|
+
${ie}
|
|
10
|
+
${H}`,de=(G.get(se)?.count??0)+1;G.set(se,{objectApiName:B,field:ie,count:de,why:H})};for(let B of s)for(let ie of k.kept.get(B.name)??[])for(let H of B.loose[ie])k.ids.get(H.link.parent)?.has(H.id)||K(B.name,H.link.field,H.link.kind==="owed"?"owed":"selfReference");for(let B of j?.namingSelected??[])B.required||k.ids.get(B.target)?.has(B.id)||K(B.objectApiName,B.field,"onParent");return{heldBy:$,...J?{cannotFit:J.words}:{},kept:F(k),...j?{walk:j}:{},report:{mode:n,heldBy:$,...J?{cannotFit:J.said}:{},budget:{...po(e,D.roomBytes,t),...$==="apiRequests"?{limitedBy:"apiRequests"}:{}},...b!==void 0?{share:b}:{},objects:N,emptied:[...G.values()],parents:j?j.added.map(B=>({objectApiName:B,records:j.parentIds.get(B)?.length??0})):[...o].map(([B,{ids:ie}])=>({objectApiName:B,records:ie.length})),records:D.records,estimateMB:D.bytes/1048576}}},ee={words:Rr,said:{why:"sourceChanged"}},T=b=>({words:`with these caps the plan takes ${S(b)}: lower them, or fit by share`,said:{why:"caps",over:R(b)}}),L=Object.keys(n.caps??{}).find(b=>!s.some(k=>k.name===b)),v=s.reduce((b,k)=>Math.max(b,Math.min(k.roots.length,i(k.name)??1/0)),0),O=m(1),x=p(O,f(O));if(L!==void 0)return C(void 0,O,x,"caps",void 0,{words:`the plan selects no ${L}: a cap holds an object it selects`,said:{why:"capNotSelected",object:L}});if(s.some(b=>b.rows.length>(l.planned.get(b.name)??0)))return C(void 0,O,x,e.terms.limitedBy,void 0,ee);let _=n.all!==void 0||Object.keys(n.caps??{}).length>0,W=n.share===!0||!_,U=b=>{let k=m(b/v);return p(k,f(k))};if(s.every(b=>O.kept.get(b.name)?.size===b.rows.length)&&q(x))return C(W?1:void 0,O,x,"whole",void 0);if(v===0)return C(void 0,O,x,e.terms.limitedBy,void 0,ee);let z=v;if(!q(x)){if(!W)return C(void 0,O,x,Q(x),void 0,T(x));if(z=fo(v,b=>q(U(b))),z===0){let b=m(1/v),k=p(b,f(b));return C(1/v,b,k,Q(k),void 0,{words:`the least it can be cut to \u2014 one record of each object with none to follow, and what follows them, ${tr(k.records)} \u2014 takes ${S(k)}`,said:{why:"least",over:R(k)}})}}let V=z<v?Q(U(z+1)):_?"caps":e.terms.limitedBy,ne=b=>W?b/v:void 0;if(o.size===0){let b=m(z/v);return C(ne(z),b,p(b,new Map),V,void 0)}for(let b=1;b<=Jo;b++){let k=m(z/v),D=await l.walk(F(k));if(!Or(D,o)){let N=p(k,A(D));return C(ne(z),k,N,V,void 0,ee)}let $=D.namingSelected.filter(N=>N.required&&s.find(G=>G.name===N.target)?.at.has(N.id)===!0&&!k.ids.get(N.target)?.has(N.id));if($.length>0){for(let{target:N,id:G}of $){let K=c.get(N)??new Set;c.set(N,K),K.add(G)}d=er(s,c);continue}let j=p(k,A(D));if(q(j))return C(ne(z),k,j,V,D);if(V=Q(j),!W)return C(void 0,k,j,V,D,T(j));if(z===1)return C(ne(z),k,j,V,D,{words:"the least it can be cut to, with the parents its records name, takes "+S(j),said:{why:"least",over:R(j)}});let J=Math.max((j.bytes+j.roomBytes)/Math.max(1,e.bytes),e.runRequests!==void 0?j.requests/Math.max(1,e.runRequests):0,r!==void 0?j.records/Math.max(1,r):0);z=Math.max(1,Math.min(z-1,Math.floor(z/J)))}let Se=m(z/v),be=p(Se,f(Se));return C(ne(z),Se,be,V,void 0,{words:`could not fit in ${Jo} rounds: fit by caps`,said:{why:"rounds"}})}function ar(l,e,t){let{selected:n}=l.scope,o=e.walk?.added??[],r=new Set([...n,...o]),s=new Map(e.walk?.parentIds??[]),i=new Map,a=new Map;for(let f of n){let A=e.kept.get(f)??[];s.set(f,A.map(w=>w.Id)),i.set(f,A.length),l.personAccounts.has(f)&&a.set(f,A.filter(w=>w[ye]===!0).length)}for(let f of o)i.set(f,e.walk?.parentIds.get(f)?.length??0),l.personAccounts.has(f)&&a.set(f,e.walk?.personAccounts.get(f)??0);let c=new Map([...l.scope.leftEmpty,...e.walk?.leftEmpty??[]].filter(f=>r.has(f.objectApiName)&&!r.has(f.target)).map(f=>[`${f.objectApiName}.${f.fieldApiName}>${f.target}`,f])),{maxDepth:d,maxObjects:m,followedByDefault:u,currencies:p}=l.scope,g=u?.filter(f=>r.has(f.objectApiName)),y=p?.objects.filter(f=>r.has(f));return{...l,objectDescribes:new Map([...l.objectDescribes].filter(([f])=>r.has(f))),autoDiscoveredObjects:o,missingInTarget:l.missingInTarget.filter(f=>r.has(f)),recordCounts:i,totalObjectsScanned:r.size,parentIds:s,personAccounts:a,scope:{maxDepth:d,maxObjects:m,selected:n,parents:o.map(f=>({objectApiName:f,records:i.get(f)??0})),leftEmpty:[...c.values()],standardNeeded:l.scope.standardNeeded.filter(f=>r.has(f.objectApiName)),...g!==void 0&&g.length>0?{followedByDefault:g}:{},...p&&y!==void 0&&y.length>0?{currencies:{...p,objects:y}}:{},fitted:t}}}var et=class{deps;eventListeners=[];runningExecutors=[];pendingSkips=new Set;constructor(e){this.deps=e}onEvent(e){return this.eventListeners.push(e),()=>{this.eventListeners=this.eventListeners.filter(t=>t!==e)}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch{}}listObjects(e,t,n){return this.deps.schemaScanner.listObjects(e,t,n)}countObjects(e,t){return this.deps.schemaScanner.countObjects(e,t)}async scanSchemas(e,t,n,o){this.emitEvent({type:"scan-started",timestamp:new Date().toISOString()});let r=await this.deps.schemaScanner.scan(e,t,n.selectedObjects,n.includeStandardObjects,{...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.maxObjects!==void 0?{maxObjects:n.maxObjects}:{},...o?{onProgress:o}:{}});return this.emitEvent({type:"scan-completed",timestamp:new Date().toISOString()}),r}buildGraph(e,t){let n=new Map;for(let[o,r]of e.objectDescribes){let s=r.fields.map(i=>({name:i.name,type:i.type,nillable:i.nillable,referenceTo:i.referenceTo,relationshipName:i.relationshipName}));n.set(o,{name:r.name,fields:s})}return this.deps.graphBuilder.build(n,e.recordCounts,t)}buildCompliance(e,t,n=[]){let o=this.deps.complianceEngine.buildProfile(e,wo(n,t)),r=this.deps.complianceEngine.generateRules(o);return{profile:o,rules:r}}generatePlan(e,t,n,o){let r=bo(t,e.nodes.map(c=>c.objectApiName),n),s={...this.deps.complianceEngine.buildSummary(n),...r.length>0?{notCovered:r}:{}},i=this.deps.planGenerator.generate(e,t,s),a=o?{...i,scope:o}:i;return this.emitEvent({type:"plan-generated",timestamp:new Date().toISOString()}),a}async fitPlan(e,t){let{scan:n,graph:o,plan:r,rules:s,mode:i,budget:a,maxRecords:c,onProgress:d}=t,{schemaScanner:m}=this.deps,u=0,p={describe:v=>e.describe(v),describeGlobal:()=>e.describeGlobal(),query:v=>(u++,e.query(v)),...e.queryMore?{queryMore:v=>(u++,e.queryMore.call(e,v))}:{}},g=r.waves.map(v=>v.objects),y=new Map,f=g.flatMap(v=>Ge(v,o.edges).groups.filter(O=>O.length>1));for(let v of new Set(f.flat()))y.set(v,await t.describeLookups?.(v).catch(()=>null)??null);let A=an(g,o.edges,v=>y.get(v)),{selected:w}=n.scope,M=or(n.objectDescribes,w,A),I=rr(A,M),q=sr(t.automation,t.mutePlan,I),Q=await m.readFitRows(p,n,d),R=await ir({order:A.filter(v=>w.includes(v)),rows:Q,planned:n.recordCounts,lookups:M,parents:new Map(n.scope.parents.map(({objectApiName:v})=>{let O=n.personAccounts.get(v);return[v,{ids:n.parentIds.get(v)??[],...O!==void 0?{personAccounts:O}:{}}]})),budget:a,room:q,mode:i,...c!==void 0?{maxRecords:c}:{},walk:v=>m.walkFrom(p,n,v,d)}),S=q.unread!==void 0?{automationUnread:q.unread}:{},F={...R.report,requestsRead:u,...S,...t.mutePlan?{countedMuted:!0}:{},...c!==void 0?{maxTotal:c}:{}},C=new Map([...R.kept].map(([v,O])=>[v,O.map(x=>x.Id)])),ee={heldBy:R.heldBy,report:F,keptIds:C,...S};if(R.cannotFit!==void 0)return{...ee,cannotFit:R.cannotFit};if(R.heldBy==="whole")return ee;let T=ar(n,R,F),L=this.buildGraph(T,t.batchSize);return{...ee,fitted:{scan:T,graph:L,plan:this.generatePlan(L,r.complianceFramework,s,T.scope),run:nr(M,T.parentIds)}}}async executePlan(e,t,n,o,r,s,i,a){let c=Array.from(o.values()).reduce((A,w)=>A+w,0),d=this.isGrappeActive(c),m=`autopilot-${Date.now()}`;d&&this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:m,totalPartitions:e.waves.length,totalRecords:c}}),this.emitEvent({type:"execution-started",timestamp:new Date().toISOString()});let u=this.deps.createExecutor(),p=()=>{},g=r?u.on("node-completed",r):p,y=r?u.on("node-failed",r):p;for(let A of this.pendingSkips)u.skip(A);this.pendingSkips.clear(),this.runningExecutors.push(u);let f;try{f=await u.execute(e,t.edges,n,o,s,i,a)}finally{this.runningExecutors.splice(this.runningExecutors.indexOf(u),1),g(),y()}return this.emitEvent({type:"execution-completed",timestamp:new Date().toISOString()}),d&&this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:m,totalProcessed:f.totalSuccess+f.totalSkipped,totalFailed:f.totalFailure}}),f}isGrappeActive(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&this.deps.grappeAdapter&&e>=t.autoActivateThreshold)}generateReport(e,t,n,o,r,s){return this.deps.complianceEngine.generateReport(e,t,n,o,r,s)}latestRunningExecutor(){return this.runningExecutors[this.runningExecutors.length-1]}pause(){this.latestRunningExecutor()?.pause()}resume(){this.latestRunningExecutor()?.resume()}skip(e){let t=this.latestRunningExecutor();if(t){t.skip(e);return}this.pendingSkips.add(e)}};var tt=class{build(e,t,n=200){let o=this.extractEdges(e),r=Tr(o,new Set(e.keys())),s=this.tarjanSCC(Array.from(e.keys()),r),i=this.resolveCycles(s,r),{order:a,levels:c}=this.topologicalSort(Array.from(e.keys()),r,s),d=this.buildNodes(e,t,a,c,n),m=this.computeStats(d,o,i);return{nodes:d,edges:o,cycles:i,stats:m}}extractEdges(e){let t=[],n=new Set(e.keys());for(let[o,r]of e)for(let s of r.fields){if(s.type!=="reference"||s.referenceTo.length===0)continue;let i=s.referenceTo.filter(d=>n.has(d));if(i.length===0)continue;if(i.length>1){for(let d of i)t.push({from:d,to:o,fieldApiName:s.name,relationshipType:"polymorphic",required:!s.nillable});continue}let a=i[0],c;a===o?c="hierarchical":s.nillable?c="lookup":c="master_detail",t.push({from:a,to:o,fieldApiName:s.name,relationshipType:c,required:!s.nillable})}return t}tarjanSCC(e,t){let n=new Map;for(let s of e)n.set(s,[]);for(let s of t){let i=n.get(s.to);i&&i.push(s.from)}let o={index:0,stack:[],onStack:new Set,indices:new Map,lowLinks:new Map,sccs:[]},r=[...e].sort();for(let s of r)o.indices.has(s)||this.tarjanStrongConnect(s,n,o);return o.sccs}tarjanStrongConnect(e,t,n){n.indices.set(e,n.index),n.lowLinks.set(e,n.index),n.index++,n.stack.push(e),n.onStack.add(e);let o=t.get(e)??[];for(let r of o)if(n.indices.has(r)){if(n.onStack.has(r)){let s=n.lowLinks.get(e)??0,i=n.indices.get(r)??0;n.lowLinks.set(e,Math.min(s,i))}}else{this.tarjanStrongConnect(r,t,n);let s=n.lowLinks.get(e)??0,i=n.lowLinks.get(r)??0;n.lowLinks.set(e,Math.min(s,i))}if(n.lowLinks.get(e)===n.indices.get(e)){let r=[],s;do s=n.stack.pop(),n.onStack.delete(s),r.push(s);while(s!==e);n.sccs.push(r.sort())}}resolveCycles(e,t){let n=[],o=new Set;for(let r of t)r.from===r.to&&r.relationshipType==="hierarchical"&&o.add(r.from);for(let r of o)n.push({objects:[r],strategy:"two_pass",description:`Insert ${r} without self-lookup, update in 2nd pass`});for(let r of e){if(r.length<=1)continue;let s=new Set(r),i=t.filter(d=>s.has(d.from)&&s.has(d.to)&&d.from!==d.to),a,c;r.length===2&&i.some(m=>!m.required)?(a="nullable_lookup",c=`Insert ${r[0]} without ${r[1]} lookup, insert ${r[1]} with ${r[0]} lookup, update ${r[0]}`):(a="upsert_external_id",c="Decompose cycle into waves with upsert + external ID"),n.push({objects:[...r],strategy:a,description:c})}return n}topologicalSort(e,t,n){let o=new Map;for(let p=0;p<n.length;p++)for(let g of n[p])o.set(g,p);let r=n.length,s=new Map;for(let p=0;p<r;p++)s.set(p,new Set);for(let p of t){let g=o.get(p.from),y=o.get(p.to);g!==void 0&&y!==void 0&&g!==y&&s.get(y).add(g)}let i=new Map;for(let[p,g]of s)i.set(p,new Set(g));let a=[],c=new Map;for(;i.size>0;){let p=[];for(let[g,y]of i)y.size===0&&p.push(g);if(p.length===0){for(let g of i.keys())a.push(g),c.has(g)||c.set(g,0);break}p.sort((g,y)=>g-y);for(let g of p){a.push(g);let y=s.get(g)??new Set,f=-1;for(let A of y)f=Math.max(f,c.get(A)??0);c.set(g,y.size===0?0:f+1),i.delete(g);for(let A of i.values())A.delete(g)}}let d=new Map,m=new Map,u=0;for(let p of a){let g=n[p],y=c.get(p)??0,f=[...g].sort();for(let A of f)d.set(A,u),m.set(A,y),u++}for(let p of e)d.has(p)||(d.set(p,u),m.set(p,0),u++);return{order:d,levels:m}}buildNodes(e,t,n,o,r){let s=[];for(let i of e.keys()){let a=t.get(i)??0;s.push({objectApiName:i,recordCount:a,estimatedApiCalls:a===0?0:Math.ceil(a/r),piiFields:[],anonymizationRules:[],status:"pending",progress:0,insertOrder:n.get(i)??0,level:o.get(i)??0,successCount:0,failureCount:0,errors:[],elapsedMs:0,apiCallsUsed:0})}return s.sort((i,a)=>i.insertOrder-a.insertOrder),s}computeStats(e,t,n){return{totalObjects:e.length,totalRelationships:t.length,cycleCount:n.length,maxDepth:Math.max(0,...e.map(o=>o.level)),totalRecords:e.reduce((o,r)=>o+r.recordCount,0),totalEstimatedApiCalls:e.reduce((o,r)=>o+r.estimatedApiCalls,0)}}};function Tr(l,e){let t=pn(e);return t.length===0?[...l]:[...l.filter(n=>!(n.to===oe&&n.fieldApiName==="ActivityId")),...t.map(n=>({from:n.sourceObject,to:n.targetObject,fieldApiName:n.relationshipName,relationshipType:"lookup",required:!0}))]}import{createHash as vr,randomUUID as Er}from"node:crypto";var Pr=["fake","mask","hash","nullify","redact","shuffle","truncate","preserve_format","age_band","generalize"],nt=class{builtInRules;constructor(){this.builtInRules=new Map,this.builtInRules.set("gdpr",this.buildGDPRRules()),this.builtInRules.set("ccpa",this.buildCCPARules()),this.builtInRules.set("hipaa",this.buildHIPAARules()),this.builtInRules.set("pci_dss",this.buildPCIDSSRules())}buildProfile(e,t,n=[]){let o=this.builtInRules.get(e)??[];return{framework:e,rules:o,autoDetectedPII:t,userOverrides:n,auditRequired:e!=="none"&&e!=="custom"}}generateRules(e){if(e.framework==="none")return[];let t=new Map;for(let o of e.userOverrides){let r=`${o.objectApiName}.${o.fieldApiName}`;t.set(r,o)}let n=[];for(let o of e.autoDetectedPII){let r=`${o.objectApiName}.${o.fieldApiName}`,s=t.get(r);if(s){if(s.method==="skip")continue;n.push({objectApiName:o.objectApiName,fieldApiName:o.fieldApiName,method:s.method,piiCategory:o.piiCategory,aiConfidence:o.confidence,userOverridden:!0,fieldType:o.fieldType});continue}let i=this.findMatchingRule(e.rules,o.piiCategory),a=i&&i.requiredMethod!=="any"?i.requiredMethod:o.suggestedMethod;n.push({objectApiName:o.objectApiName,fieldApiName:o.fieldApiName,method:a,piiCategory:o.piiCategory,aiConfidence:o.confidence,userOverridden:!1,fieldType:o.fieldType})}return n}buildSummary(e){let t={};for(let o of Pr)t[o]=0;for(let o of e)t[o.method]++;let n=[...new Set(e.map(o=>o.objectApiName))];return{totalPiiFields:e.length,totalFieldsToAnonymize:e.length,methodBreakdown:t,objectsWithPii:n}}generateReport(e,t,n,o,r,s){let i=new Set(e.userOverrides.map(y=>`${y.objectApiName}.${y.fieldApiName}`)),a=t.map(y=>{let f=this.findMatchingRule(e.rules,y.piiCategory),A=f?f.id:"custom",w=n.get(y.objectApiName)??0,M=`${y.objectApiName}.${y.fieldApiName}`;return{objectApiName:y.objectApiName,fieldApiName:y.fieldApiName,piiCategory:y.piiCategory,anonymizationMethod:y.method,recordsAnonymized:w,ruleApplied:A,userOverridden:i.has(M)||y.userOverridden}}),c=this.buildObjectSummaries(t,n,e),d=this.computeOverallStatus(c),m=new Date().toISOString(),u=Er(),p=JSON.stringify(a),g=vr("sha256").update(p).digest("hex");return{id:u,framework:e.framework,generatedAt:m,sourceOrgId:o,targetOrgId:r,totalFieldsScanned:s,piiFieldsDetected:e.autoDetectedPII.length,piiFieldsAnonymized:t.length,entries:a,objectSummaries:c,overallStatus:d,checksumSha256:g}}findMatchingRule(e,t){return e.find(n=>n.targetPiiCategories.includes(t))}buildObjectSummaries(e,t,n){let o=new Set;for(let s of e)o.add(s.objectApiName);for(let s of n.autoDetectedPII)o.add(s.objectApiName);let r=[];for(let s of o){let i=e.filter(p=>p.objectApiName===s),a=n.autoDetectedPII.filter(p=>p.objectApiName===s),c=[...new Set(i.map(p=>p.method))],d=t.get(s)??0,m=a.length>0&&a.every(p=>i.some(g=>g.fieldApiName===p.fieldApiName)),u=a.length===0||m?"pass":i.length>0?"partial":"fail";r.push({objectApiName:s,recordCount:d,piiFieldCount:a.length,anonymizationMethods:c,status:u})}return r}computeOverallStatus(e){return e.length===0||e.every(o=>o.status==="pass")?"pass":e.every(o=>o.status==="fail")?"fail":"partial"}buildGDPRRules(){return[{id:"gdpr-01",framework:"gdpr",category:"data_minimization",description:"Anonymize personal identifiers (name, email, phone, address)",targetPiiCategories:["PII"],requiredMethod:"fake",articleReference:"GDPR Art. 25"},{id:"gdpr-02",framework:"gdpr",category:"data_protection",description:"Hash sensitive identifiers for pseudonymization",targetPiiCategories:["SENSITIVE"],requiredMethod:"hash",articleReference:"GDPR Art. 32"},{id:"gdpr-03",framework:"gdpr",category:"health_data",description:"Nullify health-related data",targetPiiCategories:["PHI"],requiredMethod:"nullify",articleReference:"GDPR Art. 9"},{id:"gdpr-04",framework:"gdpr",category:"financial_data",description:"Mask payment card data",targetPiiCategories:["PCI"],requiredMethod:"mask",articleReference:"GDPR Art. 32"}]}buildCCPARules(){return[{id:"ccpa-01",framework:"ccpa",category:"personal_info",description:"Anonymize personal information (name, email, phone)",targetPiiCategories:["PII"],requiredMethod:"fake"},{id:"ccpa-02",framework:"ccpa",category:"commercial_info",description:"Mask commercial and financial data",targetPiiCategories:["PCI","SENSITIVE"],requiredMethod:"mask"},{id:"ccpa-03",framework:"ccpa",category:"biometric",description:"Nullify biometric and health data",targetPiiCategories:["PHI"],requiredMethod:"nullify"}]}buildHIPAARules(){return[{id:"hipaa-01",framework:"hipaa",category:"safe_harbor",description:"Anonymize patient identifiers (name, address, phone)",targetPiiCategories:["PII","PHI"],requiredMethod:"fake",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"},{id:"hipaa-02",framework:"hipaa",category:"safe_harbor_dates",description:"Generalize dates to year only",targetPiiCategories:["SENSITIVE"],requiredMethod:"age_band",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"},{id:"hipaa-03",framework:"hipaa",category:"safe_harbor_ids",description:"Hash medical record numbers and SSNs",targetPiiCategories:["PHI"],requiredMethod:"hash",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"}]}buildPCIDSSRules(){return[{id:"pci-01",framework:"pci_dss",category:"card_data",description:"Mask PAN to show only last 4 digits",targetPiiCategories:["PCI"],requiredMethod:"mask",articleReference:"PCI-DSS Requirement 3.3"},{id:"pci-02",framework:"pci_dss",category:"auth_data",description:"Nullify CVV, expiration, and magnetic strip data",targetPiiCategories:["PCI"],requiredMethod:"nullify",articleReference:"PCI-DSS Requirement 3.2"},{id:"pci-03",framework:"pci_dss",category:"cardholder",description:"Anonymize cardholder personal data",targetPiiCategories:["PII"],requiredMethod:"fake",articleReference:"PCI-DSS Requirement 3.4"}]}};var ot=class{avgSecondsPerApiCall;batchSize;constructor(e){this.avgSecondsPerApiCall=e?.avgSecondsPerApiCall??.5,this.batchSize=e?.batchSize??200}getBatchSize(){return this.batchSize}generate(e,t,n){let o=this.buildWaves(e),r=e.stats.totalRecords,s=e.stats.totalEstimatedApiCalls,i=this.estimateDuration(o,e);return{waves:o,totalRecords:r,estimatedDurationSec:i,estimatedApiCalls:s,complianceFramework:t,anonymizationSummary:n,cycleResolutions:e.cycles}}buildWaves(e){if(e.nodes.length===0)return[];let t=[...e.nodes].sort((i,a)=>i.insertOrder-a.insertOrder),n=new Map;for(let i of t){let a=n.get(i.level);a?a.push(i.objectApiName):n.set(i.level,[i.objectApiName])}let o=[...n.keys()].sort((i,a)=>i-a),r=new Map;for(let i=0;i<o.length;i++){let a=o[i],c=n.get(a);if(c)for(let d of c)r.set(d,i)}let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=n.get(a)??[],d=new Set;for(let u of c)for(let p of e.edges)if(p.to===u){let g=r.get(p.from);g!==void 0&&g<i&&d.add(g)}let m=[...d].sort((u,p)=>u-p);s.push({order:i,objects:c,dependsOn:m})}return s}estimateDuration(e,t){let n=new Map;for(let s of t.nodes)n.set(s.objectApiName,s.estimatedApiCalls);let o=new Map;t.cycles.forEach((s,i)=>{for(let a of s.objects)o.set(a,i)});let r=0;for(let s of e){let i=new Map;for(let a of s.objects){let c=o.get(a),d=c===void 0?`object:${a}`:`cycle:${c}`;i.set(d,(i.get(d)??0)+(n.get(a)??0))}r+=Math.max(0,...i.values())*this.avgSecondsPerApiCall}return r}};var $e=class{idMaps=new Map;registerMappings(e,t){let n=this.idMaps.get(e);n||(n=new Map,this.idMaps.set(e,n));for(let[o,r]of t)n.set(o,r)}remapRecords(e,t,n){let o=t.filter(c=>c.to===n),r=0,s=0,i=0,a=[];for(let[c,d]of e.entries()){let m=new Set,u=new Map;for(let p of o){let g=d[p.fieldApiName];if(g==null||g===""){i++;continue}if(typeof g!="string"){i++;continue}let f=this.idMaps.get(p.from)?.get(g);if(f!==void 0)d[p.fieldApiName]=f,m.add(p.fieldApiName),r++;else{let A=u.get(p.fieldApiName);A?A.parents.push(p.from):u.set(p.fieldApiName,{sourceId:g,parents:[p.from]}),s++}}for(let[p,{sourceId:g,parents:y}]of u)m.has(p)||(d[p]=null,a.push({index:c,fieldApiName:p,sourceId:g,parents:y}))}return{remapped:r,missing:s,skipped:i,unresolved:a}}getTargetId(e,t){return this.idMaps.get(e)?.get(t)}hasObject(e){return this.idMaps.has(e)}getMappingCount(e){return this.idMaps.get(e)?.size??0}get totalMappings(){let e=0;for(let t of this.idMaps.values())e+=t.size;return e}clear(){this.idMaps.clear()}};var Cr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function mr(l,e,t){let n=Yt(l);if(e!==void 0&&!Cr.test(e))throw new Error(`Not a record id to read after: "${e}".`);let o=e===void 0?"":` WHERE Id > '${e}'`;return`SELECT FIELDS(ALL) FROM ${n}${o} ORDER BY Id LIMIT ${Math.trunc(t)}`}var Mr={statusCode:Ke,message:"No result returned for the record",fields:[]},Ir={statusCode:Ke,message:"Refused without a reason",fields:[]},cr="PARENT_REFUSED",dr="PARENT_NOT_WRITTEN",zt="CUT_WITH_PARENT",lr={skipped:l=>`${l} was skipped in this run`,failed:l=>`the run's write of ${l} failed`},xr="PERSON_ACCOUNT_NOT_WRITTEN",Nr="PERSON_CONTACT_NOT_LOOKED_UP",Fr=`SELECT Id FROM RecordType WHERE SobjectType = '${ae}' AND IsPersonType = true`;function ce(l){return l.slice(0,15)}var Re=class{byReason=new Map;add(e){let t=new Set;for(let n of e){let o=`${n.statusCode}\0${n.fields.join(",")}`;if(t.has(o))continue;t.add(o);let r=this.byReason.get(o);this.byReason.set(o,r?{...r,count:r.count+1}:{statusCode:n.statusCode,fields:[...n.fields],count:1,message:n.message})}}addCounted(e){let t=`${e.statusCode}\0${e.fields.join(",")}`,n=this.byReason.get(t);this.byReason.set(t,n?{...n,count:n.count+e.count}:e)}list(){return[...this.byReason.values()].sort((e,t)=>t.count-e.count)}};function ur(){return{written:0,linked:0,failed:0,errors:[],refusals:new Re,apiCallsUsed:0,defaulted:new Map,cutSinceFit:0,heldForRecordType:new Map}}function jr(l){return{statusCode:jn,fields:["RecordTypeId"],count:l.recordCount,message:Ln(l)}}function Dr(l,e){return{objectApiName:l,rows:e.rows,why:{...e.why},...e.predicted?{predicted:e.predicted}:{},...e.readBack?{readBack:e.readBack}:{}}}function pr(l){let e=0;for(let[t,n]of l)Pt(t)&&(e+=n);return e}function $r(l){let e=new Map;for(let t of l.holds)e.set(t.objectApiName,[...e.get(t.objectApiName)??[],t]);return{holds:e,kept:new Map([...l.kept].map(([t,n])=>[t,new Set(n.map(ce))])),stayedOut:new Map}}var Le=class extends Ao{deps;batchSize;paused=!1;pausePromise=null;pauseResolve=null;skippedObjects=new Set;signal;contactPoints;creatableByObject=new Map;currencies;currencyChanges=new Nn;pricesSettled=new Map;currencyChangesByWrittenId=new Map;keyPrefixByObject=new Map;lifecycleByObject=new Map;standardPricebook;deferredStatuses=[];lookupsByObject=new Map;recordTypeMappings;targetRecordTypes=[];planned=new Set;parentIds=new Map;owedLookups=[];unmappedRecordTypes=new Set;leftToThePlatform=new ln;taskOfEmail=new Map;emailsAfterTheirTask=[];taskTurnOver=!1;emailsHeldAndNotSent=0;leftByStop=new Map;lookupsLeftEmpty=new Map;refusedRecords=new Map;notWritten=new Map;reached=new Set;personTypes;personContactsLinked=0;recordTypesGiven=new Map;recordTypesUnderTheLease=new Map;givenRules=new Map;lease;fit;async creatableFieldsOf(e){if(!this.deps.describeCreateableFields)return null;let t=this.creatableByObject.get(e);if(t!==void 0)return t;try{let n=await this.deps.describeCreateableFields(e),o=n.size>0?n:null;return this.creatableByObject.set(e,o),o}catch{return this.creatableByObject.set(e,null),null}}lookupsOf(e){let t=this.deps.describeLookups;if(!t)return Promise.resolve(null);let n=this.lookupsByObject.get(e);return n||(n=t(e).catch(()=>null),this.lookupsByObject.set(e,n)),n}keyPrefixOf(e){let t=this.deps.describeKeyPrefix;if(!t)return Promise.resolve(void 0);let n=this.keyPrefixByObject.get(e);return n||(n=t(e).catch(()=>{}),this.keyPrefixByObject.set(e,n)),n}constructor(e){super(),this.deps=e,this.batchSize=e.batchSize??200}async recordTypesHeldBack(e){let{describeRecordTypes:t,countRecordTypes:n}=this.deps;if(!t||!n)return[];let o=await this.creatableFieldsOf(e);if(o&&!o.has("RecordTypeId"))return[];try{let r=await t(e);if(!r.some(i=>!i.available&&!i.master))return[];let s=this.inTargetRecordTypes(await n(e));return Dn(e,s,yt(r,this.targetRecordTypes))}catch{return[]}}inTargetRecordTypes(e){let t=new Map;for(let[n,o]of e){if(n===null)continue;let r=this.targetRecordTypeOf(n);t.set(r,(t.get(r)??0)+o)}return t}targetRecordTypeOf(e){return this.recordTypeMappings?.find(t=>t.sourceId===e)?.targetId??e}async recordTypesGivenOf(e,t,n=new Map,o=[]){await this.mapRecordTypes(e);let r=new Map;for(let s of new Set(e.waves.flatMap(i=>i.objects))){let i=t.get(s)??0;if(i===0)continue;let a=await this.givenRuleOf(s);if(!a)continue;let c=await this.creatableFieldsOf(s),d,m="masterInSource";if(c&&!c.has("RecordTypeId"))d=i,m="notRead";else{let u=await this.onMasterInSource(s,n.get(s));if(u===void 0)continue;d=o.find(g=>g.objectApiName===s)?Math.min(u,i):u}d!==0&&r.set(s,{objectApiName:s,rows:d,why:{[m]:d},...a.predicted?{predicted:a.predicted}:{}})}return r}async onMasterInSource(e,t){try{if(t===void 0){let r=this.deps.countRecordTypes;return r?pr(await r(e)):void 0}let n=this.deps.querySource;if(!n)return;let o=0;for(let r=0;r<t.length;r+=ke){let s=await n(Mt(e,t.slice(r,r+ke)));o+=pr(He(s))}return o}catch{return}}givenRuleOf(e){let t=this.givenRules.get(e);return t||(t=(async()=>{let n=this.recordTypesUnderTheLease.get(e)??await this.deps.describeRecordTypes?.(e).catch(()=>{});if(!n?.some(s=>!s.master))return;let o=yt(n,this.targetRecordTypes),r=Co(Po(o));return{types:o,...r?{predicted:r}:{}}})(),this.givenRules.set(e,t)),t}async readAgainUnderTheLease(e,t){let n=this.deps.describeRecordTypesAgain;if(!n||!this.lease||this.lease.assigned===0)return;let o=[...new Set(e.waves.flatMap(r=>r.objects))].filter(r=>(t.get(r)??0)>0);await Promise.all(o.map(async r=>{if((await this.deps.describeRecordTypes?.(r).catch(()=>{}))?.some(i=>!i.master))try{this.recordTypesUnderTheLease.set(r,await n(r))}catch{}}))}countCreatedWithoutRecordType(e,t,n,o){let r=this.recordTypesGiven.get(e);r||(r={...t,rows:0,why:{},ids:[]},this.recordTypesGiven.set(e,r)),r.rows++,r.why[n]=(r.why[n]??0)+1,o&&r.ids.length<Mo&&r.ids.push(o)}async afterTheWrites(e){await this.giveTheLeaseBack(),await this.readBackRecordTypes();for(let[t,n]of this.recordTypesGiven){let o=e[t];o&&(e[t]={...o,recordTypeGiven:Dr(t,n)})}}async giveTheLeaseBack(){let e=this.lease;if(e){this.lease=void 0;try{await e.giveBack()}catch(t){le.warn(`[autopilot] the mute's lease was not given back as the writes ended: ${te(t)}`)}}}async readBackRecordTypes(){let e=this.deps.queryTarget;e&&await Promise.all([...this.recordTypesGiven].map(async([t,n])=>{if(n.ids.length!==0)try{let o=await e(Mt(t,n.ids));n.readBack=Io(o,n.types)}catch(o){n.readBack={read:0,types:[],unread:te(o)}}}))}holdOnClosedRecordTypes(e,t,n){let o=n.closedRecordTypes;if(!o)return t;let r=[];for(let s of t){let i=s.RecordTypeId,a=e===fe&&Ce(s),c=typeof i=="string"&&i.length>=15&&!a?o.get(ce(this.targetRecordTypeOf(i))):void 0;if(!c){r.push(s);continue}n.failed++;let d=n.heldForRecordType.get(c.recordTypeId);n.heldForRecordType.set(c.recordTypeId,{...c,recordCount:(d?.recordCount??0)+1});let m=s.Id;typeof m=="string"&&m!==""&&this.refusedRecords.set(ce(m),e)}return r}async mapRecordTypes(e){let{querySource:t,queryTarget:n}=this.deps;if(!t||!n)return;let o=[...new Set(e.waves.flatMap(s=>s.objects))];if(o.length===0)return;let r=`${So} AND SobjectType IN (${o.map(s=>`'${he(s)}'`).join(", ")})`;try{let[s,i]=await Promise.all([t(r),n(r)]),a=Et(s);this.targetRecordTypes=Et(i),this.recordTypeMappings=new Ct().buildMapping(a,this.targetRecordTypes);for(let c of vo(a,this.targetRecordTypes))le.warn(`[autopilot] ${Eo(c)}`)}catch(s){le.warn("Autopilot could not match the record types of the two orgs",{error:te(s)})}}async matchStandardPricebooks(e){let{querySource:t,queryTarget:n}=this.deps;if(!t||!n)return;let o=new Set(e.waves.flatMap(r=>r.objects));if(!(!o.has(Ae)&&!o.has(Te)))try{let[r,s]=await Promise.all([t(Ee),n(Ee)]),i=r[0]?.Id,a=s[0]?.Id;if(typeof i!="string"||typeof a!="string")return;this.standardPricebook={source:i,target:a},this.deps.remapper.registerMappings(Ae,[[i,a]])}catch(r){le.warn("Autopilot could not match the standard price books",{error:te(r)})}}async execute(e,t,n,o,r,s=new Map,i={}){if(!this.deps.queryByIds&&[...s.values()].some(f=>f.length>0))throw new Error("This plan reads the parents its objects reference by id, and the run has no read by id.");this.parentIds=s,this.contactPoints=i.keepContactPoints===!0?void 0:new ko,this.lease=i.lease,this.fit=i.fit?$r(i.fit):void 0;let a=Date.now();this.signal=r;let c=()=>this.pauseResolve?.();r?.addEventListener("abort",c,{once:!0});let d={},m={},u={totalSuccess:0,totalFailure:0,totalSkipped:0,totalLinked:0,elapsedMs:0,completedObjects:[],failedObjects:[],skippedObjects:[],nodeErrors:d,objectOutcomes:m},p=[];this.emit("execution-started",this.makeEvent({type:"execution-started",timestamp:""}));let g=async f=>{await y(f),f===Ue&&await this.writeEmailsAfterTheirTask(t,u)},y=async f=>{if(this.skippedObjects.has(f)){let w=o.get(f)??0;u.skippedObjects.push(f),u.totalSkipped+=w,this.notWritten.set(f,"skipped");return}this.reached.add(f);let A=o.get(f)??0;if(await this.checkPause()){p.push(f),m[f]={written:0,linked:0,failed:0,refusals:[],...A>0?{notSent:A}:{}};return}try{let w=await this.executeObject(f,t,n,A);u.totalSuccess+=w.success,u.totalFailure+=w.failure,u.totalLinked=(u.totalLinked??0)+w.linked,w.cutSinceFit>0&&(u.cutSinceFit=(u.cutSinceFit??0)+w.cutSinceFit);let M=this.leftToThePlatform.counts(f);if(m[f]={written:w.success,linked:w.linked,failed:w.failure,refusals:w.refusals,...w.leftToDefault.length>0?{leftToDefault:w.leftToDefault}:{},...M.length>0?{leftToThePlatform:M}:{},...w.notSent!==void 0&&w.notSent>0?{notSent:w.notSent}:{},...this.currenciesReplacedOf(f),...this.pricesSettledOf(f),...f===fe&&this.personContactsLinked>0?{withTheirPersonAccount:this.personContactsLinked}:{},...w.cutSinceFit>0?{cutSinceFit:w.cutSinceFit}:{},...w.threw!==void 0?{threw:w.threw}:{}},w.notSent!==void 0){p.push(f);return}let{threw:I}=w;if(I!==void 0||w.errors.length>0&&w.success+w.linked===0){u.failedObjects.push(f),I!==void 0&&this.notWritten.set(f,"failed");let q=I!==void 0?[I,...w.errors]:w.errors;d[f]=q[0],this.emit("node-failed",this.makeEvent({type:"node-failed",timestamp:"",objectApiName:f,errors:q,partialSuccessCount:w.success,failureCount:w.failure,linkedCount:w.linked,refusals:w.refusals}))}else u.completedObjects.push(f),this.emit("node-completed",this.makeEvent({type:"node-completed",timestamp:"",objectApiName:f,successCount:w.success,failureCount:w.failure,linkedCount:w.linked,refusals:w.refusals,elapsedMs:w.elapsedMs,apiCallsUsed:w.apiCallsUsed}))}catch(w){u.failedObjects.push(f),this.notWritten.set(f,"failed");let M=te(w);d[f]=M,this.emit("node-failed",this.makeEvent({type:"node-failed",timestamp:"",objectApiName:f,errors:[M],partialSuccessCount:0,failureCount:0,linkedCount:0,refusals:[]}))}};try{await this.matchStandardPricebooks(e),await this.mapRecordTypes(e),await this.readAgainUnderTheLease(e,o),this.planned=new Set(e.waves.flatMap(w=>w.objects));let f={};for(let w of e.waves){if(await this.writeWave(w.objects,t,g),this.stopped())break;await this.fillOwedLookups(f),this.emit("wave-completed",this.makeEvent({type:"wave-completed",timestamp:""}))}if(this.stopped()){let w=new Set([...u.completedObjects,...u.failedObjects,...u.skippedObjects,...p]);for(let M of e.waves.flatMap(I=>I.objects)){if(w.has(M))continue;let I=o.get(M)??0;p.push(M),m[M]={written:0,linked:0,failed:0,refusals:[],...I>0?{notSent:I}:{}}}return u.stopped=!0,u.stoppedObjects=p,this.countEmailsTheStopHeld(u,p,m),this.countWhatTheStopLeft(p,m),await this.sayLookupsLeftOwed(t,f),Object.keys(f).length>0&&(u.lookups=f),await this.afterTheWrites(m),this.reportContactPoints(u),u.elapsedMs=Date.now()-a,u}this.emailsAfterTheirTask.length>0&&(await this.writeEmailsAfterTheirTask(t,u),await this.fillOwedLookups(f)),await this.sayLookupsLeftOwed(t,f);let A=await this.applyDeferredStatuses();return Object.keys(A).length>0&&(u.statuses=A),Object.keys(f).length>0&&(u.lookups=f),await this.afterTheWrites(m),this.stopped()&&(u.stopped=!0,u.stoppedObjects=p,this.countEmailsTheStopHeld(u,p,m),this.countWhatTheStopLeft(p,m)),this.reportContactPoints(u),u.elapsedMs=Date.now()-a,this.emit("execution-completed",this.makeEvent({type:"execution-completed",timestamp:""})),u}catch(f){throw u.elapsedMs=Date.now()-a,u.fatalError=te(f),le.error("Autopilot execution crashed",{error:u.fatalError}),this.emit("execution-failed",this.makeEvent({type:"execution-failed",timestamp:"",error:u.fatalError})),f}finally{r?.removeEventListener("abort",c),await this.giveTheLeaseBack()}}async writeWave(e,t,n){let{within:o,deps:r,groups:s}=Ge(e,t),i=new Map;s.forEach((m,u)=>m.forEach(p=>i.set(p,u)));let a=[];for(let[m,u]of s.entries()){let p=new Set;for(let g of u)for(let y of r.get(g)??[]){let f=i.get(y);f!==void 0&&f!==m&&p.add(a[f])}a.push((async()=>{await Promise.all(p);let g=u.length>1?rn(u,await this.setAtInsert(u,o)):u;for(let y of g)await n(y)})())}let d=(await Promise.allSettled(a)).find(m=>m.status==="rejected");if(d)throw d.reason}async setAtInsert(e,t){let n=new Set(e),o=new Map;for(let r of t)!n.has(r.to)||!n.has(r.from)||o.has(r.to)||o.set(r.to,await this.lookupsOf(r.to));return sn(e,t,r=>o.get(r))}async fillOwedLookups(e){let t=this.owedLookups.splice(0,this.owedLookups.length),{update:n}=this.deps;if(!n||t.length===0)return;let o=new Ro;for(let r of t){let s=r.parents.map(i=>this.deps.remapper.getTargetId(i,r.sourceId)).find(i=>i!==void 0);if(!s){this.owedLookups.push(r);continue}o.add({objectApiName:r.objectApiName,recordId:r.recordId,fieldName:r.fieldApiName,value:s})}for(let[r,s]of o.updates()){let i=e[r],a=i?.filled??0,c=new Re;for(let d of i?.refusals??[])c.addCounted(d);for(let d=0;d<s.length;d+=this.batchSize){if(await this.checkPause()){this.noteLeftByStop(r,"lookups",s.slice(d).map(p=>String(p.Id)));break}let m=s.slice(d,d+this.batchSize),u=await fr(n,r,m);m.forEach((p,g)=>{let y=u[g];if(y?.success){a++;return}let f=Object.keys(p).filter(A=>A!=="Id");c.add(qt(y).map(A=>({...A,fields:f}))),this.noteLookupLeftEmpty(r,String(p.Id))})}e[r]=this.lookupOutcome(r,a,c)}}noteLookupLeftEmpty(e,t){let n=this.lookupsLeftEmpty.get(e);n||(n=new Set,this.lookupsLeftEmpty.set(e,n)),n.add(t)}lookupOutcome(e,t,n){let o=this.lookupsLeftEmpty.get(e)?.size??0;return{filled:t,refusals:n.list(),...o>0?{leftEmpty:o}:{}}}async sayLookupsLeftOwed(e,t){let n=new Map;for(let o of this.owedLookups.splice(0,this.owedLookups.length)){let r=await this.whyLeftOwed(o,e);if(!r)continue;let s=n.get(o.objectApiName);if(!s){s=new Re;for(let i of t[o.objectApiName]?.refusals??[])s.addCounted(i);n.set(o.objectApiName,s)}s.add([{...r,fields:[o.fieldApiName]}]),this.noteLookupLeftEmpty(o.objectApiName,o.recordId)}for(let[o,r]of n){let s=t[o]?.filled??0;t[o]=this.lookupOutcome(o,s,r)}}async whyLeftOwed(e,t){let{fieldApiName:n,sourceId:o}=e,r=this.refusedRecords.get(ce(o)),s=e.parents.find(c=>c===r);if(s)return{statusCode:cr,message:`the ${s} record its ${n} names was refused in this run, and this record, written before it, keeps its ${n} empty.`};let i=this.fit?.stayedOut.get(ce(o)),a=e.parents.find(c=>c===i);if(a)return{statusCode:zt,message:`the ${a} record its ${n} names stayed out with a record the fit cut, and this record, written before it, keeps its ${n} empty.`};for(let c of e.parents){let d=this.notWrittenOf(c);if(d===void 0)continue;let m=t.find(u=>u.from===c&&u.to===e.objectApiName&&u.fieldApiName===n);if(!(m&&!await this.namesARecordOf(e.objectApiName,m,o,e.parents.length)))return{statusCode:dr,message:`the ${c} record its ${n} names was not written: ${lr[d](c)}, and this record, written before it, keeps its ${n} empty.`}}}async executeObject(e,t,n,o){let r=Date.now(),s=ur(),i=()=>{let a=[...s.heldForRecordType.values()];return{success:s.written,linked:s.linked,failure:s.failed,errors:[...a.map(Bn),...s.errors],refusals:[...s.refusals.list(),...a.map(jr)].sort((c,d)=>d.count-c.count),apiCallsUsed:s.apiCallsUsed,elapsedMs:Date.now()-r,leftToDefault:[...s.defaulted].map(([c,d])=>({field:c,count:d})),...s.notSent!==void 0?{notSent:s.notSent}:{},cutSinceFit:s.cutSinceFit}};try{return await this.writeEveryPage(e,t,n,o,s,i)}catch(a){return{...i(),threw:te(a)}}}async writeEveryPage(e,t,n,o,r,s){let i=o>0?await this.recordTypesHeldBack(e):[];i.length>0&&(r.closedRecordTypes=new Map(i.map(u=>[ce(u.recordTypeId),u])));let a=u=>{let p=Math.min(u,o);this.emit("node-progress",this.makeEvent({type:"node-progress",timestamp:"",objectApiName:e,progress:o>0?Math.round(p/o*100):100,recordsProcessed:p,recordsTotal:o,apiCallsUsed:r.apiCallsUsed}))},c=0,d,m=this.standardPricebook;if(Ht(e)&&m){let u=[];for(;c<o;){if(await this.checkPause())return r.notSent=o,s();let{rows:I,advance:q,next:Q,last:R}=await this.readPage(e,c,d);if(r.apiCallsUsed++,q===0)break;c+=q,d=Q;let S=this.leaveToThePlatform(e,I,t);if(this.deps.anonymizer.anonymize(S,n,e),await this.neutralizeContactPoints(e,S),u.push(...S),R)break}let p=await this.pricesInOneCurrencyEach(u,m.source),{standard:g,custom:y}=at(p.rows,m.source),f=at(u.filter(I=>p.standsFor.has(String(I.Id))),m.source);p.said.length>0&&this.pricesSettled.set(e,Fo(p.said));let A=0,w=0,M=async I=>{for(let q=0;q<I.length;q+=this.batchSize){if(await this.checkPause())return r.notSent=u.length-A-w,!1;let Q=I.slice(q,q+this.batchSize);await this.writeBatch(e,Q,t,r),A+=Q.length,a(A+w)}return!0};for(let[I,q]of[[g,f.standard],[y,f.custom]]){if(!await M(I))return s();let Q=this.linkWhatStoodIn(q,p.standsFor,r);if(w+=q.length-Q.length,!await M(Q))return s()}return s()}for(;c<o;){if(await this.checkPause()){r.notSent=o-c;break}let{rows:u,advance:p,next:g,last:y}=await this.readPage(e,c,d);if(r.apiCallsUsed++,p===0)break;d=g;let f=this.leaveToThePlatform(e,u,t);if(this.deps.anonymizer.anonymize(f,n,e),await this.neutralizeContactPoints(e,f),await this.writeBatch(e,f,t,r),c+=p,a(c),y)break}return s()}async neutralizeContactPoints(e,t){let{contactPoints:n}=this,o=this.deps.describeFields;if(!n||!o||t.length===0)return;let r=await o(e).catch(()=>{});if(!r)return;let s=n.forObject(e,r);if(s)for(let i of t)s(i)}reportContactPoints(e){this.contactPoints&&(e.contactPoints=this.contactPoints.report())}async readPage(e,t,n){let o=this.parentIds.get(e);if(o&&this.deps.queryByIds){let i=o.slice(t,t+Math.min(this.batchSize,ke));return i.length===0?{rows:[],advance:0,next:n,last:!0}:{rows:await this.deps.queryByIds(e,i),advance:i.length,next:n,last:!1}}let r=await this.deps.query(e,n,this.batchSize),s=r.at(-1)?.Id;return{rows:r,advance:r.length,next:typeof s=="string"?s:n,last:r.length>0&&typeof s!="string"}}leaveToThePlatform(e,t,n){let o=new Set(n.filter(r=>r.to===e&&(r.required||Gt(r.to,r.fieldApiName))).map(r=>r.fieldApiName));return this.leftToThePlatform.keep(e,t,[...o])}async writeBatch(e,t,n,o){let r=[],s=t,i=this.standardPricebook;if(e===Ae&&i&&(s=t.filter(R=>R.Id!==i.source),o.linked+=t.length-s.length),s=this.holdOnClosedRecordTypes(e,s,o),s=await this.holdBehindRefusedParents(e,s,n,o),s=this.holdBehindCutParents(e,s,o),e===oe&&(s=this.holdEmailsForTheirTask(s)),e===fe&&(s=await this.linkPersonContacts(s,o,r)),s.length===0){this.register(e,r);return}let a=this.deps.remapper.remapRecords(s,n,e);await this.leaveToDefault(e,s,o);let c=await this.creatableFieldsOf(e),d=c?s.map(R=>{let S={};for(let F of Object.keys(R))(F==="Id"||F==="attributes"||c.has(F))&&(S[F]=R[F]);return S}):s;d=this.translateRecordTypes(e,d);let m=new Map;d.forEach((R,S)=>{if(R.RecordTypeId!==void 0)return;let F=s[S]?.RecordTypeId,C=!c||c.has("RecordTypeId");m.set(R,C&&Pt(F)?"masterInSource":"notRead")});for(let R of d)for(let S of Kt(e,R))delete R[S];let u=await this.replaceCurrencies(e,s,d,c);e===ae&&await this.leaveOutForAccountKind(s,d);let p=new Map;d.forEach((R,S)=>{let F=pt(e,R);for(let C of F)delete R[C];F.length>0&&p.set(S,F)});let g=await this.lookupsOwed(e,s,a.unresolved.filter(R=>!p.get(R.index)?.includes(R.fieldApiName)),c),y=this.deps.queryTarget,f=y?R=>(o.apiCallsUsed++,y(R)):void 0;if(e===cn&&f){let R=await kn(f,d);for(let[S,F]of R){let C=d[S].Id;typeof C=="string"&&r.push([C,F])}o.linked+=R.size,d=d.filter((S,F)=>!R.has(F))}if(yn[e]!==void 0&&f){let R=await wn(f,e,d);for(let[S,F]of R){let C=d[S].Id;typeof C=="string"&&r.push([C,F])}o.linked+=R.size,await this.giveFlagsBack(e,[...R].map(([S,F])=>[d[S],F]),o),d=d.filter((S,F)=>!R.has(F))}if(e===Ue&&f){let R=await this.tasksWrittenWithTheirEmail(d,f);for(let[S,F]of R)r.push([S,F]);o.linked+=R.size,d=d.filter(S=>!R.has(String(S.Id)))}if(d.length===0){this.register(e,r);return}let A=await this.startAsDrafts(e,d),w=m.size>0?await this.givenRuleOf(e):void 0,M=await this.deps.insert(e,d);o.apiCallsUsed++;let I=await this.keyPrefixOf(e),q=dn[e],Q=[];if(d.forEach((R,S)=>{let F=typeof R.Id=="string"?R.Id:void 0,C=M[S];if(!C){this.refuse(e,F,o,void 0);return}if(C.success){o.written++;let T=w?m.get(R):void 0;w&&T&&this.countCreatedWithoutRecordType(e,w,T,C.id);let L=u.get(R);this.currencyChanges.add(e,L),L&&C.id&&this.currencyChangesByWrittenId.set(C.id,L),F&&C.id&&r.push([F,C.id]);let v=A.get(S);v&&C.id&&this.deferredStatuses.push({objectApiName:e,id:C.id,status:v});let O=F?g.get(F):void 0;for(let x of C.id?O??[]:[])this.owedLookups.push({objectApiName:e,recordId:C.id,fieldApiName:x.fieldApiName,sourceId:x.sourceId,parents:x.parents});return}let ee=_n(C,I);if(ee.kind==="linked"){o.linked++,F&&r.push([F,ee.id]);return}if(ee.kind==="unidentified"&&q&&f){Q.push({payload:R,sourceId:F,outcome:C});return}this.refuse(e,F,o,C)}),q&&f&&Q.length>0){let R=await Rn(f,e,q,Q.map(S=>S.payload));Q.forEach((S,F)=>{let C=R[F];if(C&&S.sourceId){o.linked++,r.push([S.sourceId,C]);return}this.refuse(e,S.sourceId,o,S.outcome)})}this.register(e,r)}async giveFlagsBack(e,t,n){let o=this.deps.update;if(!o||t.length===0||!bn[e])return;let r=await this.deps.describeFieldsFixedAtInsert?.(e).catch(()=>{}),s=await An(e,t,i=>!r?.has(i),async i=>(n.apiCallsUsed++,o(e,i)),()=>this.stopped());s&&le.warn("Autopilot linked relations without a flag or an answer their rows carried",{objectApiName:e,note:s})}holdEmailsForTheirTask(e){for(let n of e){let o=n.ActivityId;typeof n.Id=="string"&&typeof o=="string"&&o!==""&&this.taskOfEmail.set(n.Id,o)}if(this.taskTurnOver||!this.planned.has(Ue))return e;let t=[];for(let n of e)fn(n)?this.emailsAfterTheirTask.push(n):t.push(n);return t}async tasksWrittenWithTheirEmail(e,t){let n=new Map;for(let[i,a]of this.taskOfEmail){let c=this.deps.remapper.getTargetId(oe,i);c&&n.set(a,c)}let o=e.map(i=>String(i.Id)).filter(i=>n.has(i));if(o.length===0)return new Map;let r;try{r=await mn(t,[...new Set(o.map(i=>n.get(i)??""))])}catch(i){return le.warn("Autopilot could not look up the tasks written with its emails",{error:te(i)}),new Map}let s=new Map;for(let i of o){let a=r.get(n.get(i)??"");a&&s.set(i,a)}return s}async writeEmailsAfterTheirTask(e,t){this.taskTurnOver=!0;let n=this.emailsAfterTheirTask.splice(0,this.emailsAfterTheirTask.length);if(n.length===0)return;let o=ur();for(let d=0;d<n.length;d+=this.batchSize){if(await this.checkPause()){this.emailsHeldAndNotSent+=n.length-d;break}await this.writeBatch(oe,n.slice(d,d+this.batchSize),e,o)}t.totalSuccess+=o.written,t.totalFailure+=o.failed,t.totalLinked=(t.totalLinked??0)+o.linked;let r=t.objectOutcomes??{};t.objectOutcomes=r;let s=r[oe],i=new Re;for(let d of[...s?.refusals??[],...o.refusals.list()])i.addCounted(d);let a=new Map((s?.leftToDefault??[]).map(d=>[d.field,d.count]));for(let[d,m]of o.defaulted)a.set(d,(a.get(d)??0)+m);let c={...s,written:(s?.written??0)+o.written,linked:(s?.linked??0)+o.linked,failed:(s?.failed??0)+o.failed,refusals:i.list(),...a.size>0?{leftToDefault:[...a].map(([d,m])=>({field:d,count:m}))}:{}};r[oe]=c,c.written+c.linked>0&&t.failedObjects.includes(oe)&&(t.failedObjects.splice(t.failedObjects.indexOf(oe),1),delete t.nodeErrors?.[oe],t.completedObjects.push(oe)),this.emit("node-completed",this.makeEvent({type:"node-completed",timestamp:"",objectApiName:oe,successCount:c.written,failureCount:c.failed,linkedCount:c.linked,refusals:c.refusals,elapsedMs:0,apiCallsUsed:o.apiCallsUsed}))}async leaveToDefault(e,t,n){let o=await this.lookupsOf(e);if(!o)return;let r=Tn(o.filter(i=>i.name!=="RecordTypeId"),i=>!this.planned.has(i));if(r.size===0)return;let s=await this.creatableFieldsOf(e);for(let i of t)for(let a of r){let c=i[a];c!=null&&c!==""&&(!s||s.has(a))&&n.defaulted.set(a,(n.defaulted.get(a)??0)+1),delete i[a]}}async replaceCurrencies(e,t,n,o){let r=new Map,{querySource:s,queryTarget:i}=this.deps;if(!s||!i)return r;let a=!o||o.has(me);if(!a&&this.currencyChangesByWrittenId.size===0)return r;let c=p=>typeof p?.[me]=="string"&&p[me]!=="";if(!(a?n.some(c):t.some(c)))return r;this.currencies??=Ie(s,i,{source:this.deps.toolingSource,target:this.deps.toolingTarget});let d=await this.currencies;if(!d)return r;let m=await this.deps.describeCurrencyFields?.(e).catch(()=>{})??new Map,u=a?[]:(await this.lookupsOf(e)??[]).map(p=>p.name);return n.forEach((p,g)=>{let y=t[g],f=y?.[me],A=a?Mn(p,{read:f,currencyFields:m,ratesOn:En(e,y)},d):xn(p,{read:f,parent:y?In(e,y,u,w=>this.currencyChangesByWrittenId.get(w)):void 0,currencyFields:m},d);A&&r.set(p,A)}),r}async pricesInOneCurrencyEach(e,t){let n={rows:e,standsFor:new Map,said:[]},{querySource:o,queryTarget:r}=this.deps;if(!o||!r)return n;let s=d=>typeof d[me]=="string"&&d[me]!=="";if(!e.some(s))return n;this.currencies??=Ie(o,r,{source:this.deps.toolingSource,target:this.deps.toolingTarget});let i=await this.currencies;if(!i)return n;let{target:a}=i,c=No({prices:e,standardBookId:t,sellingModels:e.some(d=>typeof d[Pe]=="string"),writtenIn:d=>a.active.has(d)?d:Cn(void 0,a)?.to,active:a.active},[]);return{rows:c.rows,standsFor:c.standsFor,said:c.said}}linkWhatStoodIn(e,t,n){let o=Te,r=[],s=[];for(let i of e){let a=String(i.Id),c=t.get(a),d=c===void 0?void 0:this.deps.remapper.getTargetId(o,c);if(d===void 0){s.push(i);continue}r.push([a,d]),n.linked++}return this.register(o,r),s}pricesSettledOf(e){let t=this.pricesSettled.get(e)??[];return t.length>0?{pricesSettled:t}:{}}currenciesReplacedOf(e){let t=this.currencyChanges.list().filter(n=>n.objectApiName===e);return t.length>0?{currenciesReplaced:t}:{}}translateRecordTypes(e,t){let n=this.recordTypeMappings;return!n||!t.some(o=>typeof o.RecordTypeId=="string")?t.map(Oo):new Ct().apply(t,n,o=>{this.unmappedRecordTypes.has(o)||(this.unmappedRecordTypes.add(o),To(e,o,"autopilot"))})}async lookupsOwed(e,t,n,o){let r=new Map;if(!this.deps.update||n.length===0)return r;let s=await this.lookupsOf(e);for(let i of n){if(o&&!o.has(i.fieldApiName))continue;let a=s?.find(d=>d.name===i.fieldApiName);if(a&&!a.updateable)continue;let c=t[i.index]?.Id;typeof c=="string"&&r.set(c,[...r.get(c)??[],i])}return r}refuse(e,t,n,o){n.failed++;let r=qt(o);n.errors.push(o?.errors[0]??Lr(r[0])),n.refusals.add(r),t&&this.refusedRecords.set(ce(t),e)}async holdBehindRefusedParents(e,t,n,o){if(this.refusedRecords.size===0&&this.notWritten.size===0&&this.skippedObjects.size===0)return t;let r=n.filter(a=>a.to===e);if(r.length===0)return t;let s=new Map;for(let a of r)s.set(a.fieldApiName,(s.get(a.fieldApiName)??0)+1);let i=[];for(let a of t){let c=pt(e,a),d;for(let y of r){let f=a[y.fieldApiName];if(typeof f!="string"||f===""||c.includes(y.fieldApiName)||this.deps.remapper.getTargetId(y.from,f)!==void 0)continue;let A=this.refusedRecords.get(ce(f))===y.from,w=this.notWrittenOf(y.from);if(!A&&w===void 0)continue;let M=s.get(y.fieldApiName)??0;if(!A&&!await this.namesARecordOf(e,y,f,M))continue;let{from:I,fieldApiName:q}=y;d=A||w===void 0?{edge:y,statusCode:cr,message:`the ${I} record its ${q} names was refused in this run, and written without it this record would stand without its ${I}.`}:{edge:y,statusCode:dr,message:`the ${I} record its ${q} names was not written: ${lr[w](I)}, and written without it this record would stand without its ${I}.`};break}if(!d){i.push(a);continue}let{statusCode:m,message:u,edge:p}=d;o.failed++,o.errors.push(`${m}: ${u}`),o.refusals.add([{statusCode:m,message:u,fields:[p.fieldApiName]}]);let g=a.Id;typeof g=="string"&&g!==""&&this.refusedRecords.set(ce(g),e)}return i}holdBehindCutParents(e,t,n){let o=this.fit,r=o?.holds.get(e);return!o||!r?t:t.filter(s=>{if(!r.some(c=>{let d=s[c.field];if(typeof d!="string"||d==="")return!1;let{prefix:m}=c;if(m!==void 0&&(m===null||!d.startsWith(m))||this.deps.remapper.getTargetId(c.parent,d)!==void 0)return!1;let u=ce(d);return o.stayedOut.has(u)||o.kept.get(c.parent)?.has(u)!==!0}))return!0;n.cutSinceFit++;let a=s.Id;return typeof a=="string"&&a!==""&&o.stayedOut.set(ce(a),e),!1})}notWrittenOf(e){if(!this.planned.has(e))return;let t=this.notWritten.get(e);return t||(this.skippedObjects.has(e)&&!this.reached.has(e)?"skipped":void 0)}async namesARecordOf(e,t,n,o){let r=(await this.lookupsOf(e))?.find(s=>s.name===t.fieldApiName);if(r?.referenceTo.length===1)return r.referenceTo[0]===t.from;if(r&&r.referenceTo.length>1){let s=await this.keyPrefixOf(t.from);return typeof s=="string"&&s!==""&&n.startsWith(s)}return o===1}async linkPersonContacts(e,t,n){let o=e.filter(Ce),r=this.deps.queryTarget;if(o.length===0||!r)return e;let s=await this.lookupsOf(ae);if(s&&!s.some(u=>u.name===ft))return e;let i=new Map;for(let u of o){let p=u.AccountId,g=typeof p=="string"&&p!==""?this.deps.remapper.getTargetId(ae,p):void 0;g&&i.set(u,g)}let a=new Map,c;if(i.size>0)try{t.apiCallsUsed++,a=await gn(r,[...new Set(i.values())])}catch(u){c=te(u)}let d=(u,p,g)=>{t.failed++,t.errors.push(`${p}: ${g}`),t.refusals.add([{statusCode:p,message:g,fields:["AccountId"]}]);let y=u.Id;typeof y=="string"&&y!==""&&this.refusedRecords.set(ce(y),fe)},m=[];for(let u of e){if(!Ce(u)){m.push(u);continue}let p=i.get(u);if(p===void 0){d(u,xr,"the person account this contact belongs to is not in the target: the platform writes the contact with the account, and sent on its own it would stand as a contact of no account.");continue}if(c!==void 0){d(u,Nr,`the contact the platform wrote with its person account could not be looked up (${c}): sent, this one would stand beside it as a second contact.`);continue}let g=a.get(p),y=u.Id;if(g===void 0||typeof y!="string"){m.push(u);continue}n.push([y,g]),t.linked++,this.personContactsLinked++}return m}async leaveOutForAccountKind(e,t){let o=e.some(Ce)?await this.takenAsBusiness(t):()=>!1,r=e.map((s,i)=>hn(s,o(t[i])));t.forEach((s,i)=>{for(let a of Object.keys(s))Qt(ae,a,r[i])&&delete s[a]})}async takenAsBusiness(e){let t=await this.lookupsOf(ae);if(t&&!t.some(a=>a.name===ft))return()=>!0;let n=this.deps.queryTarget;if(!n)return()=>!1;this.personTypes??=n(Fr).then(a=>new Set(a.flatMap(c=>typeof c.Id=="string"?[ce(c.Id)]:[])),()=>{});let o=await this.personTypes;if(!o)return()=>!1;let r=await this.deps.describeRecordTypes?.(ae).catch(()=>{}),s=new Set((r??[]).map(a=>ce(a.recordTypeId))),i=e.some(a=>typeof a.RecordTypeId!="string")?xo(r):void 0;return a=>{let c=a.RecordTypeId,d=typeof c=="string"&&c!==""?c:i;if(d===void 0)return!1;let m=ce(d);return!o.has(m)&&s.has(m)}}register(e,t){t.length>0&&this.deps.remapper.registerMappings(e,t)}async startAsDrafts(e,t){let n=new Map,o=Me[e],{queryTarget:r,update:s}=this.deps;if(!o||!r||!s)return n;let i=this.lifecycleByObject.get(e);i||(i=Sn(r,o),this.lifecycleByObject.set(e,i));let a=await i;return a&&t.forEach((c,d)=>{let m=On(c.Status,a);m&&(n.set(d,String(c.Status)),c.Status=m)}),n}async applyDeferredStatuses(){let e={},{update:t}=this.deps;if(!t||this.deferredStatuses.length===0)return e;let n=new Map;for(let o of this.deferredStatuses)n.set(o.objectApiName,[...n.get(o.objectApiName)??[],o]);for(let[o,r]of n){let s=0,i=0,a=new Re;for(let c=0;c<r.length;c+=this.batchSize){if(await this.checkPause()){this.noteLeftByStop(o,"statuses",r.slice(c).map(u=>u.id));break}let d=r.slice(c,c+this.batchSize),m=await fr(t,o,d.map(u=>({Id:u.id,Status:u.status})));d.forEach((u,p)=>{let g=m[p];if(g?.success){s++;return}i++,a.add(qt(g))})}e[o]={applied:s,refusals:a.list(),...i>0?{leftDraft:i}:{}}}return this.deferredStatuses.length=0,e}noteLeftByStop(e,t,n){if(n.length===0)return;let o=this.leftByStop.get(e);o||(o={lookups:new Set,statuses:new Set},this.leftByStop.set(e,o));for(let r of n)o[t].add(r)}countEmailsTheStopHeld(e,t,n){let o=this.emailsAfterTheirTask.splice(0,this.emailsAfterTheirTask.length),r=this.emailsHeldAndNotSent+o.length;if(this.emailsHeldAndNotSent=0,r===0)return;let s=n[oe]??{written:0,linked:0,failed:0,refusals:[]};n[oe]={...s,notSent:(s.notSent??0)+r,heldForTheirTask:r};for(let d of[e.completedObjects,e.failedObjects]){let m=d.indexOf(oe);m>=0&&d.splice(m,1)}if(t.includes(oe))return;let i=[...this.planned],a=i.indexOf(oe),c=t.findIndex(d=>i.indexOf(d)>a);t.splice(c<0?t.length:c,0,oe)}countWhatTheStopLeft(e,t){let n=new Set(e);for(let r of this.owedLookups.splice(0,this.owedLookups.length))r.parents.some(i=>n.has(i)||this.deps.remapper.getTargetId(i,r.sourceId)!==void 0)?this.noteLeftByStop(r.objectApiName,"lookups",[r.recordId]):this.owedLookups.push(r);let o=this.deferredStatuses.splice(0,this.deferredStatuses.length);for(let r of o)this.noteLeftByStop(r.objectApiName,"statuses",[r.id]);for(let[r,s]of this.leftByStop){let i=t[r]??{written:0,linked:0,failed:0,refusals:[]};t[r]={...i,...s.lookups.size>0?{lookupsLeftEmpty:s.lookups.size}:{},...s.statuses.size>0?{statusesNotGivenBack:s.statuses.size}:{}}}}pause(){this.paused||(this.paused=!0,this.pausePromise=new Promise(e=>{this.pauseResolve=e}),this.emit("paused",this.makeEvent({type:"paused",timestamp:""})))}resume(){this.paused&&(this.paused=!1,this.pauseResolve?.(),this.pausePromise=null,this.pauseResolve=null,this.emit("resumed",this.makeEvent({type:"resumed",timestamp:""})))}skip(e){this.skippedObjects.add(e)}stopped(){return this.signal?.aborted===!0}async checkPause(){return this.stopped()?!0:(this.paused&&this.pausePromise&&await this.pausePromise,this.stopped())}makeEvent(e){return{...e,timestamp:new Date().toISOString()}}};async function fr(l,e,t){try{return await l(e,t)}catch(n){let o=te(n);return t.map(()=>({id:"",success:!1,errors:[o],errorDetails:[wt(o)]}))}}function qt(l){return l?l.errorDetails&&l.errorDetails.length>0?l.errorDetails:l.errors.length>0?l.errors.map(e=>wt(e)):[Ir]:[Mr]}function Lr(l){return l.statusCode===Ke?l.message:`${l.statusCode}: ${l.message}`}var rt=class{threshold;partitionSize;constructor(e=5e3,t=2e3){this.threshold=e,this.partitionSize=t}shouldUseGrappe(e){return e>this.threshold}partition(e,t){if(t<=this.partitionSize)return[{id:`${e}-0`,objectApiName:e,offset:0,limit:t,recordCount:t}];let n=[],o=0,r=0;for(;o<t;){let s=Math.min(this.partitionSize,t-o);n.push({id:`${e}-${r}`,objectApiName:e,offset:o,limit:s,recordCount:s}),o+=s,r++}return n}getThreshold(){return this.threshold}getPartitionSize(){return this.partitionSize}};var Br=`sandforge autopilot \u2014 run an Autopilot copy between two orgs, without the editor.
|
|
11
|
+
|
|
12
|
+
Usage:
|
|
13
|
+
npx sandforge autopilot \\
|
|
14
|
+
--source <alias> --target <alias> --object <ApiName> [options]
|
|
15
|
+
|
|
16
|
+
Required:
|
|
17
|
+
--source <alias> sf CLI alias of the source org
|
|
18
|
+
--target <alias> sf CLI alias of the target org
|
|
19
|
+
--object <ApiName> object to carry; repeat for more. Autopilot works out
|
|
20
|
+
the order from the dependencies between them.
|
|
21
|
+
|
|
22
|
+
Options:
|
|
23
|
+
--standard-objects include standard objects the scan finds (default: off)
|
|
24
|
+
The accounts the selection references are taken
|
|
25
|
+
either way, as is a standard object a record cannot
|
|
26
|
+
be written without, and said.
|
|
27
|
+
--max-depth <n> lookups followed from a selected object (default: 5)
|
|
28
|
+
--max-objects <n> objects the plan holds, the selected ones included;
|
|
29
|
+
each parent a record needs raises it, to twice
|
|
30
|
+
(default: 50)
|
|
31
|
+
--max-total <n> most records the run may write in all (default: 10000)
|
|
32
|
+
--compliance <name> none | gdpr | ccpa | hipaa | pci_dss (default: none)
|
|
33
|
+
--keep-contact-points write emails and phone numbers as read. Without it,
|
|
34
|
+
as in the panel, every address is written under
|
|
35
|
+
.invalid and every phone number as a fictional one,
|
|
36
|
+
whatever the framework (default: off)
|
|
37
|
+
--batch-size <n> records per write call (default: 200)
|
|
38
|
+
--plan-only scan, graph and plan, then stop (default: off)
|
|
39
|
+
Says what a real run would be refused for, each under
|
|
40
|
+
its code: a real run would be refused (CODE): ...;
|
|
41
|
+
with --json, under writeGate.refusals, the codes
|
|
42
|
+
under writeGate.refusalCodes
|
|
43
|
+
--mute-automation mute the target's automation for the run through
|
|
44
|
+
its own bypass: assign the user the run writes as,
|
|
45
|
+
for the run alone, the permission sets holding the
|
|
46
|
+
custom permissions its flows, processes and
|
|
47
|
+
workflow rules test to stay quiet, and take them
|
|
48
|
+
back as it ends; what no bypass keeps quiet still
|
|
49
|
+
runs, and is named. Refused on a production org and
|
|
50
|
+
for a user who cannot assign permission sets, exit
|
|
51
|
+
1; with --plan-only, says what would be muted and
|
|
52
|
+
assigns nothing (default: off)
|
|
53
|
+
--fit share fit the plan to the data storage the target has left:
|
|
54
|
+
keep the largest share of every selected object that
|
|
55
|
+
fits, spread over its ids. A record goes with the
|
|
56
|
+
parent written before it: a contact of a cut account
|
|
57
|
+
is cut, an account kept comes with all its contacts.
|
|
58
|
+
A self-reference and a lookup filled after its wave
|
|
59
|
+
stay empty when their record is cut, and are named.
|
|
60
|
+
It may take 80 % of what the target says it has left,
|
|
61
|
+
half a MB off first for the rounding of what it says,
|
|
62
|
+
less room for what its flows still running create
|
|
63
|
+
under the records (what --mute-automation keeps quiet
|
|
64
|
+
creates nothing); what its Apex triggers create is
|
|
65
|
+
named, not counted. Its writes leave a tenth of the
|
|
66
|
+
day's API requests, and --max-total holds. It reads
|
|
67
|
+
the lookups of each selected object first. The
|
|
68
|
+
records are said object by object, then the gate is
|
|
69
|
+
met again by them; a plan that cannot be cut to fit
|
|
70
|
+
is refused, exit 1. With --plan-only, says them and
|
|
71
|
+
what they meet, and --json names the ids kept
|
|
72
|
+
(default: off)
|
|
73
|
+
--fit-cap <Object>=<n> | <n>
|
|
74
|
+
at most n records of that selected object, or of
|
|
75
|
+
every one another --fit-cap does not name; repeat for
|
|
76
|
+
more. What follows them goes with them. Caps alone
|
|
77
|
+
that leave the plan past what fits refuse it; with
|
|
78
|
+
--fit share, the share is taken of what the caps leave
|
|
79
|
+
--fit-within <MB> with --fit or --fit-cap: take no more than this many
|
|
80
|
+
MB, whatever the target has left
|
|
81
|
+
--accept-emails write although the target delivers the emails its
|
|
82
|
+
flows, processes and workflow rules send as the plan
|
|
83
|
+
writes (Setup > Deliverability: All email), or would
|
|
84
|
+
not say whether it does. Read only when something
|
|
85
|
+
that still runs sends one, with one line of
|
|
86
|
+
anonymous Apex that sends nothing; without the flag
|
|
87
|
+
the run is refused, exit 1 (EMAILS_NOT_ACCEPTED),
|
|
88
|
+
nothing written. On System email only or No access
|
|
89
|
+
it is not needed. --mute-automation keeps quiet what
|
|
90
|
+
tests the org's bypass; what an Apex trigger sends is
|
|
91
|
+
read nowhere (default: off)
|
|
92
|
+
${_o({run:"the run",simulation:"--plan-only",note:["An Autopilot run has no removal: a rewind to this","checkpoint is what takes it back."]})}
|
|
93
|
+
--json emit the run summary as JSON, with the id
|
|
94
|
+
of every record the run created (default: off)
|
|
95
|
+
--fail-on-partial exit 3, not 0, when the run was partial: the target
|
|
96
|
+
refused some of its records, or a record it wrote keeps
|
|
97
|
+
a lookup it could not fill or stays a draft, its
|
|
98
|
+
status refused (default: off)
|
|
99
|
+
--help this text
|
|
100
|
+
|
|
101
|
+
A selected object is copied whole, unless the plan is fitted. Of any other
|
|
102
|
+
object, only the records the selection references are read, by id; a lookup
|
|
103
|
+
past the bounds is left empty, and the plan says which. Before it writes, the
|
|
104
|
+
run is held to --max-total, to the data storage and the daily API requests the
|
|
105
|
+
target has left, and to the daily emails the target's flows would send for its
|
|
106
|
+
records: past any, nothing is written. Where the target delivers those emails,
|
|
107
|
+
or would not say whether it does, it writes only with --accept-emails.
|
|
108
|
+
|
|
109
|
+
Ctrl-C stops the run between two calls, as the panel's Stop does: the summary
|
|
110
|
+
says what it wrote, which objects it did not, and the records it left with a
|
|
111
|
+
lookup empty or as drafts, and --json names every record it created. Ctrl-C
|
|
112
|
+
again ends the process at once.
|
|
113
|
+
|
|
114
|
+
A production target is refused before the scan: Autopilot writes to sandboxes
|
|
115
|
+
and Developer Edition orgs only, and --plan-only, which only reads, runs
|
|
116
|
+
against any org.
|
|
117
|
+
|
|
118
|
+
A run refused before its first write says each reason on a line of its own,
|
|
119
|
+
refused (CODE): ..., and --json prints "refused": {"code", "message"}, the
|
|
120
|
+
other reasons under "alsoRefused": past --max-total (MAX_TOTAL_EXCEEDED), the
|
|
121
|
+
data storage (AUTOPILOT_STORAGE_EXCEEDED), the API requests
|
|
122
|
+
(API_BUDGET_EXCEEDED) or the emails (AUTOPILOT_EMAILS_EXCEEDED) the target has
|
|
123
|
+
left, its emails not accepted (EMAILS_NOT_ACCEPTED), its checkpoint
|
|
124
|
+
(CHECKPOINT_REFUSED), its mute (MUTE_PRODUCTION, MUTE_NO_RIGHT, MUTE_FAILED),
|
|
125
|
+
or its fit (AUTOPILOT_CANNOT_FIT, AUTOPILOT_FIT_STORAGE_UNREAD,
|
|
126
|
+
AUTOPILOT_FIT_READ_REFUSED).
|
|
127
|
+
|
|
128
|
+
Exit codes: 0 the run finished, some of its records refused, left without a
|
|
129
|
+
lookup or left a draft included (read the summary for per-object failures, and
|
|
130
|
+
--json's result.status); 1 the run could not be started or was
|
|
131
|
+
refused, among them emails not accepted (EMAILS_NOT_ACCEPTED) and a checkpoint
|
|
132
|
+
asked first refused or not taken, or it died or produced only failures -- a run
|
|
133
|
+
that died prints no summary, and what it wrote before it died stays; 2 a bad
|
|
134
|
+
command line; 3 the run was partial and --fail-on-partial was given; 130 Ctrl-C
|
|
135
|
+
stopped the run, 143 a SIGTERM (a CI job cancelled or timed out), 129 a SIGHUP.
|
|
136
|
+
`,_r=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,qr="MAX_TOTAL_EXCEEDED",zr="AUTOPILOT_EMAILS_EXCEEDED",Gr="AUTOPILOT_CANNOT_FIT",Ur={switches:["--standard-objects","--keep-contact-points","--plan-only","--json","--fail-on-partial","--mute-automation","--accept-emails",...Ft.switches],values:["--source","--target","--object","--max-depth","--max-objects","--max-total","--compliance","--batch-size","--fit","--fit-cap","--fit-within",...Ft.values]};function Wr(l){let e=l.slice(2);(e.includes("--help")||e.includes("-h"))&&(process.stdout.write(Br),process.exit(0)),Vt(e,Ur);let t=(A,w)=>{let M=e.indexOf(A);return M>=0&&M+1<e.length?e[M+1]:w},n=A=>{let w=[];for(let M=0;M<e.length;M++)e[M]===A&&M+1<e.length&&w.push(e[M+1]);return w},o=t("--source"),r=t("--target"),s=n("--object");(!o||!r||s.length===0)&&(process.stderr.write(`Missing --source, --target or --object. Run with --help.
|
|
137
|
+
`),process.exit(2));for(let A of s)_r.test(A)||(process.stderr.write(`Not an SObject API name: "${A}"
|
|
138
|
+
`),process.exit(2));let i=["none","gdpr","ccpa","hipaa","pci_dss"],a=t("--compliance","none")??"none";i.includes(a)||(process.stderr.write(`--compliance takes ${i.join(", ")} \u2014 not "${a}".
|
|
139
|
+
`),process.exit(2));let c=Number(t("--batch-size","200")??"200");(!Number.isInteger(c)||c<1||c>1e4)&&(process.stderr.write(`--batch-size takes a whole number between 1 and 10000.
|
|
140
|
+
`),process.exit(2));let d=(A,w)=>{let M=Number(t(A,String(w))??w);return(!Number.isInteger(M)||M<1)&&(process.stderr.write(`${A} takes a whole number, 1 or more.
|
|
141
|
+
`),process.exit(2)),M},m=d("--max-depth",Bt),u=d("--max-objects",_t),p=d("--max-total",Qn),g=qo(e),y=A=>{process.stderr.write(`${A}
|
|
142
|
+
`),process.exit(2)},f=Xo(e,y);for(let A of Object.keys(f?.caps?.objects??{}))s.includes(A)||y(`--fit-cap ${A}: give ${A} with --object too.`);return{source:o,target:r,objects:s,includeStandardObjects:e.includes("--standard-objects"),compliance:a,batchSize:c,maxDepth:m,maxObjects:u,maxTotal:p,planOnly:e.includes("--plan-only"),keepContactPoints:e.includes("--keep-contact-points"),json:e.includes("--json"),failOnPartial:e.includes("--fail-on-partial"),muteAutomation:e.includes("--mute-automation"),acceptEmails:e.includes("--accept-emails"),...g!==void 0?{checkpointFirst:g}:{},...f?{fit:f}:{}}}function Hr(l){return{...l.share?{share:!0}:{},...l.caps?.objects?{caps:l.caps.objects}:{},...l.caps?.all!==void 0?{all:l.caps.all}:{},...l.withinMB!==void 0?{withinMB:l.withinMB}:{}}}function Kr(l){return async e=>(await We({query:async t=>l.query(t),queryMore:async t=>l.queryMore(t)},e)).records}async function Yr(l=process.argv){let e=Date.now(),t=Wr(l),n=h=>{process[t.json?"stderr":"stdout"].write(`${h}
|
|
143
|
+
`)};n(`sandforge autopilot ${t.source} -> ${t.target}`),n(`objects: ${t.objects.join(", ")}`);let o=ze(await dt(t.source)),r=await dt(t.target),s=ze(r),i=t.planOnly?void 0:await Jt(s,t.target,{tool:"sandforge autopilot",action:"write",readOnly:"--plan-only"}),a=t.checkpointFirst?Go({module:"autopilot",operationId:`sandforge-autopilot-${e}`,request:t.checkpointFirst,session:r,org:zo(r,i??await ct(s)),connect:ze,journalDir:Qo(),say:n}):void 0,c=!1,d=new Map,m=new Map,u=async h=>{let E=m.get(h);if(E)return E;let P=await s.sobject(h).describe(),Y={creatable:new Set(P.fields.filter(X=>X.createable).map(X=>X.name)),recordTypes:gt(P.recordTypeInfos),keyPrefix:P.keyPrefix??null,lookups:$o(P.fields),currencyFields:Pn(P.fields),fields:P.fields.map(X=>({name:X.name,queryable:!0,createable:X.createable,isReference:X.type==="reference",type:X.type,...X.length>0?{length:X.length}:{},...X.externalId?{externalId:!0}:{}}))};return m.set(h,Y),Y},p=new qn,g=()=>({query:async(h,E,P)=>(await o.query(mr(h,E,P))).records,queryByIds:async(h,E)=>{let P=E.map(X=>`'${he(X)}'`).join(", ");return(await o.query(`SELECT FIELDS(ALL) FROM ${h} WHERE Id IN (${P}) LIMIT ${E.length}`)).records},insert:async(h,E)=>{let P=E.map(pe=>{let st={...pe};return delete st.Id,delete st.attributes,st}),Y=bt(await s.sobject(h).create(P,{headers:it()}),h);Y.some(pe=>pe.success)&&(c=!0);let X=Y.filter(pe=>pe.success&&pe.id).map(pe=>pe.id);return d.set(h,[...d.get(h)??[],...X]),Y},update:async(h,E)=>{let P=bt(await s.sobject(h).update(E,{headers:it()}),h);return P.some(Y=>Y.success)&&(c=!0),P},querySource:async h=>(await o.query(h)).records,queryTarget:Kr(s),toolingSource:async h=>(await o.tooling.query(h)).records,toolingTarget:async h=>(await s.tooling.query(h)).records,describeKeyPrefix:async h=>(await u(h)).keyPrefix,describeLookups:async h=>(await u(h)).lookups,describeFields:async h=>(await u(h)).fields,anonymizer:p,remapper:new $e,describeCreateableFields:async h=>(await u(h)).creatable,describeRecordTypes:async h=>(await u(h)).recordTypes,describeRecordTypesAgain:async h=>gt((await s.sobject(h).describe()).recordTypeInfos),describeCurrencyFields:async h=>(await u(h)).currencyFields,countRecordTypes:async h=>{let E=await o.query($n(h));return He(E.records)}}),y=new et({schemaScanner:new Je,graphBuilder:new tt,complianceEngine:new nt,anonymizer:p,planGenerator:new ot,remapper:new $e,createExecutor:()=>new Le(g()),grappeAdapter:new rt});n(`
|
|
144
|
+
scanning\u2026`);let f=await y.scanSchemas(o,s,{selectedObjects:t.objects,includeStandardObjects:t.includeStandardObjects,maxDepth:t.maxDepth,maxObjects:t.maxObjects},h=>n(` ${h}`)),A=y.buildGraph(f,t.batchSize);n(`graph: ${A.nodes.length} node(s), ${A.edges.length} edge(s)`);let w=t.compliance==="none"?[]:yo(new zn,f.objectDescribes),{rules:M}=y.buildCompliance(t.compliance,[],w),I=y.generatePlan(A,t.compliance,M,f.scope),q=()=>{n(`plan: ${I.waves.length} wave(s), ${I.totalRecords} record(s)`),I.waves.forEach((h,E)=>{n(` wave ${E+1}: ${h.objects.join(", ")}`)});for(let h of Zr(f.scope))n(h);for(let h of es(I))n(h)};q();let Q=h=>new Map(h.map(E=>[E.objectApiName,E.recordCount])),R=Q(A.nodes),S=Nt(I,R,f.personAccounts),F=async()=>{try{return await Xn(s)}catch(h){return{unread:te(h)}}},C=await F(),ee=Ot(S,C),T,L=()=>T??=Vn(s),v,O=()=>v??=Dt(s).read(t.target,Xe(I)).catch(h=>({unread:h instanceof Error?h.message:String(h)})),x,_;if(t.muteAutomation){let h=await O();try{x=await Yn(async()=>Hn(s),h,{writes:(E,P)=>P==="insert"||P==="update"})}catch(E){if(!At(E))throw E;_={code:E.code,message:E.message.replace(/ Nothing was assigned\.$/,"")}}}let W=await Fe(S,C,L,void 0,{readBack:Ne(S),...xe(x?.plan)});n("");for(let h of Tt(S,ee,t.target))n(h);a||n(je(W,t.target));for(let h of yr(f.personAccounts))n(h);if(x)for(let h of Ye(x.muted,t.target))n(` ${h}`);let U,re;if(a&&S.totalRows>0){let h=new Set(S.objects.map(({objectApiName:Y})=>Y)),E=x?.automation??await O(),P={written:Xe(I).filter(Y=>h.has(Y)),running:typeof E.unread=="string"?{firing:[]}:{firing:qe(E,void 0,(Y,X)=>X==="insert"||X==="update").firing}};try{U={ask:P,estimate:await a.scope(P)}}catch(Y){re=kt(Y).replace(/ Nothing was written\.$/,"")}}if(a&&(W=await Fe(S,C,L,U?.estimate,{readBack:Ne(S),...xe(x?.plan)}),n(je(W,t.target)),U))for(let h of Uo(U.estimate))n(h);let z,V;if(t.fit){n(`
|
|
145
|
+
fitting\u2026`);let h=co({storage:C,...t.fit.withinMB!==void 0?{withinMB:t.fit.withinMB}:{},api:"unread"in C?await L().catch(E=>({unread:te(E)})):C.dailyApiRequests??{unread:`${t.target}'s /limits did not list them`},otherRequests:Zn(U?.estimate)});if("unread"in h)V={code:xt.STORAGE_UNREAD,message:`The plan cannot be fitted to ${t.target}, whose data storage left could not be read (${h.unread}).`};else try{z=await y.fitPlan(o,{scan:f,graph:A,plan:I,rules:M,mode:Hr(t.fit),budget:h,automation:await O(),...x?.plan?{mutePlan:x.plan}:{},describeLookups:async P=>(await u(P)).lookups,maxRecords:t.maxTotal,batchSize:t.batchSize,onProgress:P=>n(` ${P}`)});let E=(x?.plan?.assign.length??0)>0;for(let P of Jr(z,t.target,E))n(P);z.cannotFit!==void 0&&(V={code:Gr,message:`The plan cannot be fitted to ${t.target}: ${z.cannotFit}.`})}catch(E){V={code:xt.READ_REFUSED,message:`The plan could not be fitted: the source refused a read of it (${te(E)}).`}}if(z?.fitted){({scan:f,graph:A,plan:I}=z.fitted),R=Q(A.nodes),S=Nt(I,R,f.personAccounts),C=await F(),ee=Ot(S,C),T=void 0;let E=new Set(S.objects.map(({objectApiName:P})=>P));if(a&&U){let{ask:P}=U,Y=P.written.filter(X=>E.has(X));if(Y.length<P.written.length){let X={written:Y,running:{firing:P.running.firing.filter(pe=>E.has(pe.objectApiName))}};try{U={ask:X,estimate:await a.scope(X)}}catch(pe){U=void 0,re=kt(pe).replace(/ Nothing was written\.$/,"")}}}W=await Fe(S,C,L,U?.estimate,{readBack:Ne(S),...xe(x?.plan)}),n(""),q(),n("");for(let P of Tt(S,ee,t.target))n(P);n(je(W,t.target));for(let P of yr(f.personAccounts))n(P)}}let ne=await Lo({plan:S,objects:Xe(I),readAutomation:async h=>{if(x?.automation)return x.automation;let E=v?await v:void 0;return E!==void 0&&typeof E.unread!="string"?E:Dt(s).read(t.target,h)},readLimits:()=>to(s)});for(let h of oo(ne.checks,t.target))n(h);ne.unread!==void 0&&n(` emails: not counted, ${ne.unread} could not be read`);let Se=new Set(S.objects.map(({objectApiName:h})=>h)),be=(h,E)=>Se.has(h)&&(E==="insert"||E==="update"),b=S.totalRows>0?await Wn({read:await O(),...x?.plan?{plan:x.plan}:{},writes:be,readDeliverability:async()=>Xt(i??await ct(s))?Gn:Un(s),accepted:t.acceptEmails,target:t.target,run:"autopilot",keepsAddresses:t.keepContactPoints,mayMute:!t.muteAutomation}):void 0,k=b?.gate;k?.line!==void 0&&n(` ${k.line}`);let D=ro(b?.ofRun);D.deliverability!==void 0&&(W=await Fe(S,C,L,U?.estimate,{readBack:Ne(S),...xe(x?.plan),...D}),n(je(W,t.target)));let $=(h,E)=>E===void 0?void 0:{code:h,message:E},j=[$(Qe,re??(U?.estimate.refusal!==void 0?Wo(U.estimate.refusal):void 0)),$(qr,S.totalRows>t.maxTotal?`The run would write ${S.totalRows} records, more than --max-total ${t.maxTotal}: narrow it (--object, --max-depth, --max-objects), or raise --max-total.`:void 0),$(It.STORAGE_EXCEEDED,io(ee,t.target)),$(It.API_BUDGET_EXCEEDED,St(W,t.target)?.replace(/ Nothing was written\.$/,"")),$(zr,no(ne.checks,t.target)),k?.stop?$(k.stop.code,k.stop.message.replace(/ Nothing was written\./,"")):void 0,_,V].filter(h=>h!==void 0),J=j.map(({message:h})=>h);if(!t.fit&&!("unread"in C)&&(ee.verdict==="exceeds"||S.totalRows>t.maxTotal||St(W,t.target)!==void 0)&&n(" --fit share keeps the largest share of the plan that fits, its records whole"),t.planOnly){let h=await new Le(g()).recordTypesGivenOf(I,R,f.parentIds,f.scope.cutShort);for(let P of A.nodes){let Y=h.get(P.objectApiName);Y&&(P.recordTypeGiven=Y)}let E=(x?.plan?.assign.length??0)>0;for(let P of $t(A.nodes,!0,E))n(P);for(let P of j)n(` ${nn(P)}`);t.json&&process.stdout.write(`${JSON.stringify({tool:"sandforge-autopilot",planOnly:!0,graph:A,plan:I,writeGate:{records:S.totalRows,storage:ee,apiRequests:W,personAccounts:Object.fromEntries(f.personAccounts),emails:ne.checks,...ne.unread!==void 0?{emailsUnread:ne.unread}:{},...k?.deliverability?{deliverability:k.deliverability}:{},refusals:J,refusalCodes:j.map(({code:P})=>P)},...Kn(x),...U?{checkpoint:U.estimate}:{},...z?{fit:gr(z)}:{}},null,2)}
|
|
146
|
+
`);return}let N=(h,E=[])=>{throw t.json&&process.stdout.write(on({tool:"sandforge-autopilot",source:t.source,target:t.target,elapsedMs:Date.now()-e},h,E)),new Error([h,...E].map(tn).join(`
|
|
147
|
+
`))};if(j.length>0){let[h,...E]=j.map(({code:P,message:Y})=>({code:P,message:`${Y} Nothing was written.`}));N(h,E)}n(`
|
|
148
|
+
executing\u2026 (REAL)`);let G=new AbortController,K,ie=Zt(h=>{K=h,process.stderr.write(`
|
|
149
|
+
interrupted: the run stops after the call under way, and says what it wrote (Ctrl-C again ends it at once)
|
|
150
|
+
`),G.abort()}),H,se,de,ue;try{if(a&&U){let P=U,Y=await eo(()=>a.take(P.ask,P.estimate,{signal:G.signal}));if("stop"in Y){Y.stop.code===Qe&&N({code:Qe,message:jt(Y.stop)}),process.stderr.write(`${jt(Y.stop)}
|
|
151
|
+
`),ut(lt(K??"SIGINT"));return}de=Y.checkpoint;for(let X of Ho(Y.checkpoint,t.target,t.muteAutomation))n(X)}let h=x?.prepared?await x.prepared.acquire(`sandforge autopilot ${e}`).catch(P=>{if(!At(P))throw P;return N(P.refusal)}):void 0;se=h?.outcome??x?.muted;let E=h?b?.afterLease(h.outcome,t.acceptEmails):void 0;if(h&&E){se=await h.release();for(let P of Ye(se,t.target))n(P);N({code:E.code,message:E.message})}H=await y.executePlan(I,A,M,R,void 0,G.signal,f.parentIds,{...t.keepContactPoints?{keepContactPoints:!0}:{},...h?{lease:{assigned:h.outcome.assigned.length,giveBack:()=>h.release()}}:{},...z?.fitted?{fit:z.fitted.run}:{}}).finally(async()=>{h&&(se=await h.release())})}finally{if(ie(),a&&de){let h=de;ue=await a.settle(h,c).catch(E=>(n(`warning: the checkpoint '${h.name}' taken before the run, which wrote nothing, could not be deleted (${te(E)}): delete it with ${Bo("checkpoint")} delete --org ${t.target} --checkpoint ${h.checkpointId}`),h));for(let E of Ko(ue))n(E)}}for(let h of se?Ye(se,t.target):[])n(h);let Z=Date.now()-e,we=G.signal.aborted,Oe=Do(H);if(ut(we?lt(K??"SIGINT"):en(Oe,t.failOnPartial)),t.json){let h={status:Oe,...H,...H.stopped===!0?{cancelled:!0}:{}};process.stdout.write(`${JSON.stringify({tool:"sandforge-autopilot",source:t.source,target:t.target,result:h,created:Object.fromEntries(d),...se?{mutedAutomation:se}:{},...ue?{checkpoint:ue}:{},...z?{fit:gr(z)}:{},elapsedMs:Z,...we?{interrupted:!0}:{}},null,2)}
|
|
152
|
+
`),we&&process.stderr.write(`${hr(H)}
|
|
153
|
+
`);return}n(`
|
|
154
|
+
status: ${Oe}`),n(`written: ${H.totalSuccess} linked: ${H.totalLinked??0} refused: ${H.totalFailure} skipped: ${H.totalSkipped}`),H.skippedObjects.length>0&&n(` skipped: ${H.skippedObjects.join(", ")}`),H.cutSinceFit!==void 0&&n(` cut since the fit: ${H.cutSinceFit}, read naming a record the fit cut`),H.fatalError&&n(` the run died with: ${H.fatalError}`);for(let h of Qr(H))n(h);for(let h of ts(H))n(h);if(we){process.stderr.write(`${hr(H)}
|
|
155
|
+
`);return}n(`
|
|
156
|
+
done in ${Z}ms`)}function hr(l){let e=l.stoppedObjects??[];return`interrupted: the run stopped before it was through, ${l.totalSuccess} record(s) written${e.length>0?`, ${e.join(", ")} cut short or not written`:""}; --json names every record it created`}function Qr(l){let e=l.contactPoints;if(!e)return["emails and phone numbers: written as read (--keep-contact-points)"];if(e.values===0)return["emails and phone numbers: none to neutralize"];let t=e.fields.map(n=>`${n.objectApiName}.${n.field} ${n.values}`).join(", ");return[`emails and phone numbers: ${e.values} neutralized (${t}) -- addresses under .invalid, numbers fictional`]}function Xr(l){return`${Math.floor(l*1e3)/10} %`}function Vr(l){switch(l.kind){case"trigger":return`what Apex trigger ${l.name} on ${l.objectApiName} creates`;case"notRead":return`what "${l.name}" on ${l.objectApiName} creates: it was not read`;case"share":return`the ${l.name} rows the flows of ${l.objectApiName} create`}}function Jr(l,e,t){let{heldBy:n,report:o}=l,{budget:r}=o;if(l.cannotFit!==void 0)return[`fit: the plan cannot be fitted: ${l.cannotFit}`];if(n==="whole")return[`fit: the plan fits as it is, ${o.records} record(s), about ${ve(o.estimateMB)} MB: nothing cut`];let s=ve(r.budgetMB+r.automationMB),i={apiRequests:`the largest whose writes leave ${e} a tenth of its daily API requests`,maxTotal:"the largest --max-total lets through",within:`the largest that fits the ${r.withinMB??s} MB asked (--fit-within)`,storage:`the largest that fits ${s} MB: ${r.share*100} % of the ${r.remainingMB} MB ${e} says it has left of ${r.maxMB}, ${r.roundingMB} MB kept first for the rounding of what it says`},a=l.automationUnread!==void 0?`no room kept for what its automation creates: it could not be read (${l.automationUnread})`:r.automationMB>0?`${ve(r.automationMB)} MB of it kept for what its flows still running create under these records`:"nothing kept for its flows: none still running creates records under these"+(t?" (--mute-automation keeps the others quiet)":""),c=n==="caps"?`fit: the caps asked, within the ${s} MB that fit`:`fit: share ${Xr(o.share??1)}, ${i[n]}`,d=Math.max(...o.objects.map(p=>p.objectApiName.length)),m=p=>{let g=p.cutWithParent.reduce((A,w)=>A+w.count,0),y=p.cutSpread+g,f=[...p.cutWithParent.map(A=>`${A.count} with their ${A.parent} (${A.field})`),...p.cutSpread>0?[`${p.cutSpread} spread over the table`]:[]];return` ${p.objectApiName.padEnd(d)} ${p.kept} of ${p.inSource}`+(y>0?` cut ${y}: ${f.join(", ")}`:"")},u=o.emptied.map(p=>`${p.objectApiName}.${p.field} on ${p.count} (`+(p.why==="selfReference"?"the record of its own object it names was cut":"the record it names, written after, was cut")+")");return[`${c}; ${a}`,...o.objects.map(m),...o.parents.map(p=>` ${p.objectApiName}: ${p.records}, those the kept records name`),...u.length>0?[` left empty: ${u.join(", ")}`]:[],...(r.notCounted??[]).map(p=>` not counted: ${Vr(p)}`),` fitted plan: ${o.records} record(s), about ${ve(o.estimateMB)} MB`+(r.automationMB>0?` and ${ve(r.automationMB)} MB for what its flows create under them`:"")+`; ${o.requestsRead} requests read to fit it`,` ${ao(e)}`]}function gr(l){return{applied:l.fitted!==void 0,...l.report,heldBy:l.heldBy,...l.cannotFit!==void 0?{cannotFit:l.cannotFit}:{},...l.automationUnread!==void 0?{automationUnread:l.automationUnread}:{},...l.fitted?{keptIds:Object.fromEntries(l.keptIds)}:{}}}function Zr(l){let e=new Set((l.cutShort??[]).map(s=>s.objectApiName)),t=l.selected.filter(s=>!e.has(s)),n=[`scope: depth ${l.maxDepth}, at most ${l.maxObjects} object(s)`];if(l.fitted){let s=l.fitted.objects.map(i=>`${i.objectApiName} ${i.kept} of ${i.inSource}`);n.push(` fitted to the target's storage, read by id: ${s.join(", ")}`)}else(t.length>0||l.selected.length===0)&&n.push(` copied whole, as selected: ${t.join(", ")||"(none)"}`);for(let s of l.cutShort??[]){let i=s.total!==void 0?` of ${s.total}`:"";n.push(` ${s.objectApiName}: ${s.copied}${i} record(s) copied, the first by Id -- a run copies no more of a selected object`)}if(l.parents.length>0){n.push(" read by id, only the records the selection references:");for(let s of l.parents)n.push(` ${s.objectApiName.padEnd(40)}${String(s.records).padStart(8)}`)}for(let s of l.standardNeeded)n.push(` ${s.objectApiName} taken though standard objects are off: ${s.neededBy} cannot be left empty`);for(let s of l.followedByDefault??[])n.push(` ${s.objectApiName} followed by default though standard objects are off: ${s.referencedBy.join(", ")} reference${s.referencedBy.length===1?"s":""} it`);let o={depth:`further than ${l.maxDepth} lookup(s)`,objects:`past ${l.maxObjects} object(s)`,standard:"a standard object (--standard-objects to take it)"};if(l.leftEmpty.length>0){n.push(` left empty (${l.leftEmpty.length} lookup(s)):`);for(let s of l.leftEmpty)n.push(` ${s.objectApiName}.${s.fieldApiName} -> ${s.target}: ${o[s.reason]}`+(s.required?" \u2014 required: its records will be refused":""))}let r=l.currencies;return r&&n.push(` currencies the target does not hold active: ${r.notInTarget.join(", ")} \u2014 a record in one is written in ${r.writtenIn}, its corporate currency, its amounts converted at the source's rates (${r.objects.join(", ")})`),n}function yr(l){let e=l.get("Account")??0,t=l.get("Contact")??0;return e===0&&t===0?[]:[` sized as Salesforce counts them: ${[...e>0?[`${e} person account(s) at 4 KB each`]:[],...t>0?[`${t} contact(s) of person accounts at none of their own`]:[]].join(", ")}`]}function es(l){if(l.complianceFramework==="none")return[];let e=l.anonymizationSummary,t=[`anonymization (${l.complianceFramework}): ${e.totalFieldsToAnonymize} field(s) on ${e.objectsWithPii.join(", ")||"no object"}`];for(let n of e.notCovered??[])t.push(` ${n.objectApiName}: no rule for its ${n.missing.join(", ")} \u2014 copied as the source holds them`);return t}function ts(l){let e=[],t=n=>{for(let o of n){let r=o.fields.length>0?` [${o.fields.join(", ")}]`:"";e.push(` ${o.statusCode}${r} x${o.count}: ${o.message}`)}};for(let[n,o]of Object.entries(l.objectOutcomes??{})){let r=o.notSent??0;e.push(` ${n.padEnd(28)} written ${o.written} linked ${o.linked} refused ${o.failed}${r>0?` not sent ${r}`:""}`),t(o.refusals),o.threw!==void 0&&e.push(` FAILED part way: ${o.threw}`),o.lookupsLeftEmpty!==void 0&&e.push(` ${o.lookupsLeftEmpty} record(s) keep a lookup empty: the stop came before the second pass filled it`),o.statusesNotGivenBack!==void 0&&e.push(` ${o.statusesNotGivenBack} record(s) stay drafts: the stop came before their status was given back`);for(let s of o.leftToDefault??[])e.push(` left to the target's default: ${s.field} x${s.count}`);for(let s of o.leftToThePlatform??[])e.push(` ${un(s.count,s.why)}`);o.withTheirPersonAccount!==void 0&&o.withTheirPersonAccount>0&&e.push(` ${o.withTheirPersonAccount} contact(s) of person accounts left to the platform, which wrote each with its account: linked to it, not sent`),o.cutSinceFit!==void 0&&e.push(` ${zt} x${o.cutSinceFit}: read naming a record the fit cut, and left out with it: neither written nor refused`);for(let s of o.currenciesReplaced??[])e.push(` ${Fn(s)}`);for(let s of jo(o.pricesSettled??[]))e.push(` ${s}`)}for(let n of l.failedObjects)l.objectOutcomes?.[n]||e.push(` ${n.padEnd(28)} FAILED: ${l.nodeErrors?.[n]??"(no message)"}`);for(let[n,o]of Object.entries(l.lookups??{}))e.push(` ${n.padEnd(28)} lookups filled ${o.filled} refused ${o.leftEmpty??0}`),t(o.refusals);for(let[n,o]of Object.entries(l.statuses??{}))e.push(` ${n.padEnd(28)} statuses applied ${o.applied} refused ${o.leftDraft??0}`),t(o.refusals);return e.push(...$t(Object.values(l.objectOutcomes??{}),!1)),e}process.argv[1]?.includes("sandforge-autopilot")&&(Yo(),Yr().catch(l=>{process.stderr.write(`${l instanceof Error?l.message:String(l)}
|
|
157
|
+
`),process.exit(1)}));export{es as anonymizationLines,gr as autopilotFitJson,Jr as autopilotFitLines,hr as autopilotInterruptedLine,Qr as contactPointLines,Kr as everyPage,Yr as main,ts as outcomeLines,Wr as parseArgs,yr as personAccountLines,Zr as scopeLines};
|
|
@@ -0,0 +1,99 @@
|
|
|
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 W}from"./chunk-PBI4BYWW.mjs";import{a as C,b as R}from"./chunk-5P4PHJRL.mjs";import{a as A,b as U,c as M}from"./chunk-RSWDYIHY.mjs";import{K as T}from"./chunk-D3QRXG63.mjs";import"./chunk-NM4MDLK4.mjs";import"./chunk-BS5T3MOQ.mjs";import"./chunk-TEOLMRDO.mjs";import"./chunk-FQBRBBY4.mjs";import"./chunk-YS4G22C2.mjs";import"./chunk-SCKUIE3R.mjs";import{a as k}from"./chunk-QROPNEGY.mjs";import"./chunk-BZ24IAP5.mjs";import{c as v}from"./chunk-AV5SWEHP.mjs";import{a as E,c as L,d as _,e as P,f as z}from"./chunk-I7O6C2B5.mjs";import{a as B}from"./chunk-4GL773D5.mjs";import{j as O}from"./chunk-SRQDABQ2.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-LV6G4XTK.mjs";import"./chunk-HJKM3E56.mjs";import"./chunk-XCA5AONB.mjs";import"./chunk-WR2GIKWE.mjs";import"./chunk-YMJVMFPY.mjs";import"./chunk-ALJVEUUS.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-4HFRHFGQ.mjs";import"./chunk-342FN7AO.mjs";import"./chunk-BOGNK4LV.mjs";import{x as D}from"./chunk-36U7IQ6Y.mjs";import"./chunk-XETCPL7E.mjs";import"./chunk-K2FBZIXY.mjs";import"./chunk-Z7X534S4.mjs";import"./chunk-6QSM2WIH.mjs";import"./chunk-WJY54JO7.mjs";import"./chunk-T63U4OZJ.mjs";import"./chunk-DBFJB2B6.mjs";import"./chunk-NEVXIGR6.mjs";import{h as S}from"./chunk-NTDN2JQZ.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-F74IHMGL.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-Y5CGXLUB.mjs";import"./chunk-3F5YMM2F.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-SAR5622P.mjs";import{b as I}from"./chunk-L776PUMV.mjs";import"./chunk-6MUEPV7M.mjs";import"./chunk-HJC7AIBK.mjs";import"./chunk-OTWRDD6L.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-RH3N2H7P.mjs";import"./chunk-ZUTYVST5.mjs";import"./chunk-55HEMHEG.mjs";import"./chunk-P42X3B4D.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-VXHDBYMI.mjs";import"./chunk-ENLBYECD.mjs";import"./chunk-PA3MKJVH.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-ZLZRU6MO.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-PNCONNFJ.mjs";import"./chunk-CGWXQX75.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-SIOZXPFG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import{a as x,d as j,e as y,g as N}from"./chunk-MTMH6H2A.mjs";import{Vb as $}from"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-SBIMVCXT.mjs";import"./chunk-NTOVCTRS.mjs";import{join as F}from"node:path";var G=`sandforge backup \u2014 take and restore DataOps snapshots, without the editor.
|
|
8
|
+
|
|
9
|
+
Usage:
|
|
10
|
+
npx sandforge backup --org <alias> [options]
|
|
11
|
+
npx sandforge backup --list [--org <alias>]
|
|
12
|
+
|
|
13
|
+
Required:
|
|
14
|
+
--org <alias> sf CLI alias of the org (--list: every org of the
|
|
15
|
+
store without it)
|
|
16
|
+
|
|
17
|
+
One of:
|
|
18
|
+
--object <ApiName> object to snapshot; repeat for more
|
|
19
|
+
--list name the snapshots kept in the store, each with the
|
|
20
|
+
org it was taken of, then stop: the org's with --org
|
|
21
|
+
(those taken under its alias, and the others of the
|
|
22
|
+
same Organization Id), every org's without it. It
|
|
23
|
+
reads the store alone and contacts no org
|
|
24
|
+
--restore <id> upsert a snapshot back into the org by record Id
|
|
25
|
+
|
|
26
|
+
Options:
|
|
27
|
+
--store <dir> where snapshots live, a folder of your own
|
|
28
|
+
(default: ~/.sandforge/backups, under the folder
|
|
29
|
+
SANDFORGE_JOURNAL_DIR names when it is set)
|
|
30
|
+
--max-records <n> most records of each object a snapshot reads, as
|
|
31
|
+
sandforge.backup.maxRecordsPerObject sets it
|
|
32
|
+
(default: 50000; 100 to 1000000)
|
|
33
|
+
--rewrite-all with --restore: write every row of the snapshot back,
|
|
34
|
+
the ones the org already holds as the snapshot does
|
|
35
|
+
included
|
|
36
|
+
--include-changed with --restore of the snapshot a Sync run kept: put
|
|
37
|
+
back the records changed or deleted since the run too
|
|
38
|
+
${M("written back")} --max-age-days <n> the retention, as sandforge.backup.maxAgeDays sets it:
|
|
39
|
+
snapshots taken more than <n> days ago are removed as
|
|
40
|
+
the command starts, each named on stderr \u2014 the one a
|
|
41
|
+
Sync run kept of what it wrote over too, which removing
|
|
42
|
+
that run then no longer puts back; 0 keeps them all
|
|
43
|
+
(default: 30)
|
|
44
|
+
--yes do not ask before a restore writes. Without it, a
|
|
45
|
+
command with no terminal to answer the question \u2014 a
|
|
46
|
+
CI step \u2014 stops there, exit 2, and writes nothing
|
|
47
|
+
--json emit what the panel would receive, or with --list the
|
|
48
|
+
snapshots, every other line on stderr
|
|
49
|
+
--help this text
|
|
50
|
+
|
|
51
|
+
A restore never deletes: it upserts on Id, so it overwrites the fields of
|
|
52
|
+
records that are there, after bringing back from the recycle bin the ones
|
|
53
|
+
deleted since the snapshot. It reads the org's values first and writes only
|
|
54
|
+
the rows where one of them differs from the snapshot, and says how many it
|
|
55
|
+
found unchanged; --rewrite-all writes them all. Of the snapshot a Sync run
|
|
56
|
+
kept of what it wrote over, the records changed or deleted since the run \u2014
|
|
57
|
+
read against the run's file in SANDFORGE_JOURNAL_DIR \u2014 are left as they are
|
|
58
|
+
and counted, as removing the run with sandforge sync leaves them unless it
|
|
59
|
+
is told to include them; --include-changed includes them here.
|
|
60
|
+
|
|
61
|
+
Before it asks or writes, a restore says what the org runs as the records are
|
|
62
|
+
brought back from the recycle bin and written back \u2014 its record-triggered
|
|
63
|
+
flows, Apex triggers, processes and workflow rules on update and undelete \u2014,
|
|
64
|
+
the emails that sends against what the org has left today, and whether the
|
|
65
|
+
org delivers them.
|
|
66
|
+
|
|
67
|
+
A snapshot says its id, which --restore takes, and what it holds short of the
|
|
68
|
+
org: an object stopped at --max-records, or never reached.
|
|
69
|
+
|
|
70
|
+
Exit codes: 0 the run finished: the snapshot holds every record of its objects,
|
|
71
|
+
or the restore put back every value; 1 it could not start, or the snapshot or
|
|
72
|
+
the restore failed or was refused \u2014 what the org runs as it writes, without
|
|
73
|
+
--accept-automation (AUTOMATION_NOT_ACCEPTED), emails it delivers, without
|
|
74
|
+
--accept-emails (EMAILS_NOT_ACCEPTED), more emails than it has left today
|
|
75
|
+
(EMAILS_EXCEEDED), or a mute refused among the reasons; 2 a bad command line, or a question with no
|
|
76
|
+
terminal to answer it (give --yes); 3 the snapshot holds part of an object's
|
|
77
|
+
records, or the restore left values as they are (rows the org refused, a
|
|
78
|
+
snapshot that holds part of the records, or records of a Sync run's snapshot
|
|
79
|
+
changed since the run, held back without --include-changed).
|
|
80
|
+
`,H=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,q={switches:["--list","--rewrite-all","--include-changed","--yes","--json",...A],values:["--org","--object","--restore","--store","--max-records","--max-age-days"]};function Q(o){let e=o.slice(2);(e.includes("--help")||e.includes("-h"))&&(process.stdout.write(G),process.exit(0)),x(e,q);let t=(h,u)=>{let n=e.indexOf(h);return n>=0&&n+1<e.length?e[n+1]:u},a=h=>{let u=[];for(let n=0;n<e.length;n++)e[n]===h&&n+1<e.length&&u.push(e[n+1]);return u},d=t("--org"),i=e.includes("--list");!d&&!i&&(process.stderr.write(`Missing --org. Run with --help.
|
|
81
|
+
`),process.exit(2));let g=a("--object"),f=t("--restore"),p=[g.length>0,i,f!==void 0].filter(Boolean).length;p===0&&(process.stderr.write(`Nothing to do: give --object, --list or --restore.
|
|
82
|
+
`),process.exit(2)),p>1&&(process.stderr.write(`Give one of --object, --list or --restore.
|
|
83
|
+
`),process.exit(2));for(let h of g)H.test(h)||(process.stderr.write(`Not an SObject API name: "${h}"
|
|
84
|
+
`),process.exit(2));let c=t("--max-records");c!==void 0&&!/^[1-9]\d*$/.test(c)&&(process.stderr.write(`Not a number of records: "${c}"
|
|
85
|
+
`),process.exit(2));let b=e.includes("--rewrite-all");b&&f===void 0&&(process.stderr.write(`--rewrite-all goes with --restore.
|
|
86
|
+
`),process.exit(2));let w=e.includes("--include-changed");w&&f===void 0&&(process.stderr.write(`--include-changed goes with --restore.
|
|
87
|
+
`),process.exit(2));let r=_(t("--max-age-days")),s=U(e),l=A.filter(h=>e.includes(h));l.length>0&&f===void 0&&(process.stderr.write(`${l.join(", ")} go${l.length===1?"es":""} with --restore.
|
|
88
|
+
`),process.exit(2));let m={objects:g,restoreId:f,storeDir:t("--store",E())??"",...c!==void 0?{maxRecords:Number(c)}:{},rewriteAll:b,includeChanged:w,...r!==void 0?{maxAgeDays:r}:{},yes:e.includes("--yes"),json:e.includes("--json"),accord:s};return d?i?{...m,list:!0,org:d}:{...m,list:!1,org:d}:{...m,list:!0}}async function X(o=process.argv){let e=Q(o),t=r=>{process[e.json?"stderr":"stdout"].write(`${r}
|
|
89
|
+
`)},a=L(e.storeDir);if(a!==void 0){process.stderr.write(`${a}
|
|
90
|
+
`),process.exitCode=1;return}t(`store: ${e.storeDir}`);let d=D(F(e.storeDir,"snapshots.json"));if(e.list){let r=d.getKeysByPrefix("backup:").map(l=>d.get(l)),s=e.org!==void 0?K(r,e.org):r;if(e.json){process.stdout.write(`${JSON.stringify(Y(s),null,2)}
|
|
91
|
+
`);return}s.length===0&&t(e.org!==void 0?`No snapshot of ${e.org} in this store.`:"No snapshot in this store.");for(let l of s.map(V))t(l);return}let i=await I(e.org),g=await new B().validateConnection(i.accessToken,i.instanceUrl),f={alias:i.alias,orgType:$({isSandbox:g.isSandbox,edition:g.orgType}),metadata:{apiVersion:"66.0",edition:g.orgType}},p=[],c=new O({log:r=>t(` ${r}`),broker:{postToWebview:r=>{p.push(r);let s=String(r.type??"");(s.endsWith(":error")||s.includes("failed"))&&(t(` ! ${JSON.stringify(r.payload??r)}`),process.exitCode=1)}},orgManager:{getOrg:()=>f},orgRegistry:{getCredentials:async()=>({accessToken:i.accessToken,instanceUrl:i.instanceUrl})},configStore:d,services:{getSandforgeSetting:P(e)},infraServices:{productionGuard:W(t,e.org),confirmRestoreIntoReplacedOrg:({alias:r,backedUpFrom:s,now:l})=>e.yes?Promise.resolve(!1):k(`${r} answered as org ${s} when this snapshot was taken and answers as org ${l} now. Write its saved values into the org it is now?`)},nextId:()=>`cli-${Date.now()}-${Math.random().toString(36).slice(2,8)}`});c.setExpiryListener(r=>process.stderr.write(`${z(r)}
|
|
92
|
+
`)),c.setBackupRecordStore(new R(C(e.storeDir))),await c.swept(),c.setSyncRuns(S(T()));let b=r=>p.find(s=>s.correlationId===r);if(e.restoreId){let r=d.get(`backup:${e.restoreId}`);r||(process.stderr.write(`No snapshot "${e.restoreId}" in ${e.storeDir}.
|
|
93
|
+
`),process.exit(1));let s=`cli-restore-automation-${Date.now()}`;await c.handle({id:s,type:"dataops:automation",payload:{orgId:e.org,act:"restore",objects:(r.objects??[]).map(n=>({objectApiName:n.objectApiName,records:n.recordCount??0})),...e.accord}});let l=b(s);if(l?.type!=="dataops:automation:response"){process.exitCode=1,e.json&&process.stdout.write(`${JSON.stringify({tool:"sandforge-backup",posted:p},null,2)}
|
|
94
|
+
`);return}let m=l.payload;for(let n of m.lines)t(n);if(m.refusals.length>0){for(let n of m.refusals)process.stderr.write(`${v(n)}
|
|
95
|
+
`);process.exitCode=1,e.json&&process.stdout.write(`${JSON.stringify({tool:"sandforge-backup",posted:p},null,2)}
|
|
96
|
+
`);return}if(!e.yes&&!await k(`Upsert snapshot ${e.restoreId} back into ${e.org}? Records with these Ids will have their fields overwritten.`)){t("Nothing written.");return}t(`restoring ${e.restoreId} into ${e.org}${e.rewriteAll?", every row written back":""}\u2026`),await c.handle({id:`cli-restore-${Date.now()}`,type:"dataops:rollback",payload:{orgId:e.org,operationId:e.restoreId,...e.rewriteAll?{rewriteAll:!0}:{},...e.includeChanged?{includeChanged:!0}:{},...e.accord}});let h=p.find(n=>n.type==="dataops:rollback:response"),u=h?.payload??{};typeof u.message=="string"&&t(u.message),h&&y(j(u))}else{t(`snapshot ${e.org}: ${e.objects.join(", ")}`),await c.handle({id:`cli-backup-${Date.now()}`,type:"backup:execute",payload:{orgId:e.org,objects:e.objects}});let r=p.find(s=>s.type==="dataops:backup:response");if(r){let s=ee(r.payload??{});t(s.line),y(s.exitCode)}}if(e.json){process.stdout.write(`${JSON.stringify({tool:"sandforge-backup",posted:p},null,2)}
|
|
97
|
+
`);return}let w=p[p.length-1];w&&t(`
|
|
98
|
+
last message: ${String(w.type)}`)}function Z(o,e){return o!==void 0&&e!==void 0&&o.length>=15&&o.slice(0,15)===e.slice(0,15)}function K(o,e){let t=o.flatMap(a=>a.orgId===e&&a.organizationId!==void 0?[a.organizationId]:[]);return o.filter(a=>a.orgId===e||t.some(d=>Z(d,a.organizationId)))}function V(o){let e=o.objects.map(t=>`${t.objectApiName}:${t.recordCount}`+(t.stoppedAt!==void 0?`/${t.orgCount??"?"}(${t.stoppedAt})`:""));return`${o.operationId} ${o.timestamp} ${o.orgId??"?"} ${o.totalRecords} record(s)${o.status==="failed"?" failed part-way":""} ${e.join(" ")}`}function Y(o){return{tool:"sandforge-backup",snapshots:o.map(e=>({operationId:e.operationId,timestamp:e.timestamp,...e.orgId!==void 0?{orgId:e.orgId}:{},...e.organizationId!==void 0?{organizationId:e.organizationId}:{},totalRecords:e.totalRecords,...e.status!==void 0?{status:e.status}:{},objects:e.objects}))}}function ee(o){let e=String(o.operationId??"?"),t=(o.objects??[]).filter(i=>i.truncated===!0),a=`snapshot ${e}: ${String(o.totalRecords??0)} record(s)`;if(o.partial!==!0&&t.length===0)return{line:`${a} (--restore ${e} puts them back)`,exitCode:0};let d=t.map(i=>`${i.objectApiName} ${i.recordCount} of ${i.orgCount??"?"}`+(i.stoppedAt!==void 0?` (${i.stoppedAt})`:""));return{line:`${a} (partial: ${d.join(", ")||"an object holds fewer records than the org"})`,exitCode:3}}process.argv[1]?.includes("sandforge-backup")&&(N(),X().then(()=>process.exit(process.exitCode??0)).catch(o=>{process.stderr.write(`${o instanceof Error?o.message:String(o)}
|
|
99
|
+
`),process.exit(1)}));export{X as main,Q as parseArgs,Y as snapshotListing,ee as snapshotTaken};
|