sandforge 1.79.0 → 1.80.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/{chunk-JVL444U5.mjs → chunk-2BA2XKAY.mjs} +1 -1
- package/lib/chunk-2CNCDM56.mjs +7 -0
- package/lib/{chunk-W7KFAY55.mjs → chunk-2GTBABKU.mjs} +1 -1
- package/lib/{chunk-DLDX6RRC.mjs → chunk-2NBYT7GR.mjs} +1 -1
- package/lib/{chunk-HV2MXMGI.mjs → chunk-2UZPIMUC.mjs} +1 -1
- package/lib/chunk-3F6Q5E7I.mjs +14 -0
- package/lib/{chunk-PBI4BYWW.mjs → chunk-3RZQZHEB.mjs} +1 -1
- package/lib/{chunk-P7GSGFJO.mjs → chunk-3TJON4F3.mjs} +1 -1
- package/lib/chunk-4VS2V6WU.mjs +25 -0
- package/lib/{chunk-TQX3PURV.mjs → chunk-5K5VLULK.mjs} +1 -1
- package/lib/{chunk-MYTIL2JD.mjs → chunk-5TC3QB4U.mjs} +1 -1
- package/lib/{chunk-NM4MDLK4.mjs → chunk-6XYKJSGX.mjs} +1 -1
- package/lib/{chunk-RFEO2KAN.mjs → chunk-74Q6DORA.mjs} +1 -1
- package/lib/chunk-7ABODJ4G.mjs +7 -0
- package/lib/{chunk-ZPYJPGDK.mjs → chunk-7EGQP6S4.mjs} +1 -1
- package/lib/chunk-7FFGJWHN.mjs +7 -0
- package/lib/chunk-7YDNUBO5.mjs +7 -0
- package/lib/{chunk-CGWXQX75.mjs → chunk-A527W53V.mjs} +1 -1
- package/lib/chunk-ADOAS63R.mjs +7 -0
- package/lib/chunk-AEKONPF4.mjs +7 -0
- package/lib/{chunk-4HFRHFGQ.mjs → chunk-B5QQJ4SI.mjs} +1 -1
- package/lib/{chunk-2BVTCNWA.mjs → chunk-BGUEWRK2.mjs} +1 -1
- package/lib/{chunk-GNC27UEU.mjs → chunk-BKDV4ENO.mjs} +1 -1
- package/lib/{chunk-QRV2OSIS.mjs → chunk-BTWDMNN3.mjs} +1 -1
- package/lib/{chunk-FOVVHGEP.mjs → chunk-BV6VTP3J.mjs} +1 -1
- package/lib/{chunk-PZTSVQSF.mjs → chunk-BXU6WFMH.mjs} +1 -1
- package/lib/{chunk-ZQOZ4EFW.mjs → chunk-BY2HJFFG.mjs} +1 -1
- package/lib/{chunk-NZ5ZZLKS.mjs → chunk-CEX3NEZL.mjs} +1 -1
- package/lib/{chunk-HTJ5OGP5.mjs → chunk-CHYDMRSV.mjs} +1 -1
- package/lib/chunk-CION3VMZ.mjs +7 -0
- package/lib/chunk-COFG7Q6R.mjs +7 -0
- package/lib/chunk-CSBS5U5I.mjs +7 -0
- package/lib/{chunk-55HEMHEG.mjs → chunk-CU2INBND.mjs} +1 -1
- package/lib/chunk-DB7RBE5D.mjs +7 -0
- package/lib/{chunk-QPF6C5MX.mjs → chunk-DBB3EMIN.mjs} +1 -1
- package/lib/{chunk-F74IHMGL.mjs → chunk-DYFALGRT.mjs} +1 -1
- package/lib/{chunk-TEOLMRDO.mjs → chunk-E5AHXLS6.mjs} +1 -1
- package/lib/{chunk-LRFAIUN7.mjs → chunk-E5ZB3LU5.mjs} +1 -1
- package/lib/chunk-EFR2Y7E4.mjs +7 -0
- package/lib/chunk-EHQ3FX6X.mjs +7 -0
- package/lib/{chunk-RAAANPPG.mjs → chunk-ELFXJHU7.mjs} +1 -1
- package/lib/{chunk-BN7A4GRQ.mjs → chunk-EMNC6YI4.mjs} +1 -1
- package/lib/{chunk-HJC7AIBK.mjs → chunk-EQNW3UC2.mjs} +1 -1
- package/lib/{chunk-Z7X534S4.mjs → chunk-F43REJDZ.mjs} +2 -2
- package/lib/{chunk-QQZZMKU3.mjs → chunk-F6GUDTOB.mjs} +1 -1
- package/lib/{chunk-6EBMEGZB.mjs → chunk-FGRG7ANU.mjs} +1 -1
- package/lib/{chunk-4NAHW2D3.mjs → chunk-FKG7Q3WH.mjs} +1 -1
- package/lib/{chunk-7UQD6V6F.mjs → chunk-FPKYYFM7.mjs} +1 -1
- package/lib/{chunk-ZJKCWBRJ.mjs → chunk-FXXLX4O6.mjs} +1 -1
- package/lib/chunk-G35N4P7D.mjs +7 -0
- package/lib/{chunk-SIOZXPFG.mjs → chunk-GGD7ON3M.mjs} +1 -1
- package/lib/chunk-GSG7WZHM.mjs +7 -0
- package/lib/{chunk-OTWRDD6L.mjs → chunk-GSKCGQIP.mjs} +1 -1
- package/lib/{chunk-3CA767QB.mjs → chunk-HEKAZJRH.mjs} +1 -1
- package/lib/{chunk-4SNDMJP2.mjs → chunk-HLWMJF6Y.mjs} +1 -1
- package/lib/chunk-HOJYWTP7.mjs +20 -0
- package/lib/chunk-HS4YRX4J.mjs +7 -0
- package/lib/chunk-IFETCRWE.mjs +10 -0
- package/lib/{chunk-PUOX4NBJ.mjs → chunk-IG2MTQRP.mjs} +1 -1
- package/lib/{chunk-RACDTRZA.mjs → chunk-IGYH7GMA.mjs} +1 -1
- package/lib/{chunk-X65MT4W3.mjs → chunk-IOIWJ3DJ.mjs} +1 -1
- package/lib/{chunk-4U6NXJNL.mjs → chunk-IQXHJEYB.mjs} +1 -1
- package/lib/{chunk-P2PJYWGQ.mjs → chunk-IWDREM66.mjs} +1 -1
- package/lib/{chunk-ZOVSMN5C.mjs → chunk-IZQZ6ZUF.mjs} +1 -1
- package/lib/{chunk-XBG5SP6Q.mjs → chunk-J525F5KI.mjs} +1 -1
- package/lib/{chunk-5CD257T7.mjs → chunk-JEERQRLW.mjs} +1 -1
- package/lib/{chunk-6QSM2WIH.mjs → chunk-JPUR2CFX.mjs} +1 -1
- package/lib/chunk-JWTSEDIQ.mjs +7 -0
- package/lib/chunk-K327QKMD.mjs +7 -0
- package/lib/{chunk-J7HVXMSW.mjs → chunk-KBJ5VERV.mjs} +1 -1
- package/lib/chunk-KDGMAGQR.mjs +7 -0
- package/lib/chunk-KRCA6IPH.mjs +8 -0
- package/lib/chunk-KYEDBS54.mjs +7 -0
- package/lib/chunk-L5FGY6YA.mjs +7 -0
- package/lib/{chunk-PNCONNFJ.mjs → chunk-L77FJZEP.mjs} +1 -1
- package/lib/{chunk-3OHPD72J.mjs → chunk-LKQ5RKIV.mjs} +1 -1
- package/lib/{chunk-WJY54JO7.mjs → chunk-LPBMBW3O.mjs} +1 -1
- package/lib/{chunk-LV6G4XTK.mjs → chunk-LWW4U276.mjs} +1 -1
- package/lib/{chunk-IAZB4WIL.mjs → chunk-M3ROUWDX.mjs} +1 -1
- package/lib/chunk-MFG4MUIO.mjs +9 -0
- package/lib/{chunk-H45UXY6G.mjs → chunk-MHMH6MTP.mjs} +1 -1
- package/lib/{chunk-HCIDVIOW.mjs → chunk-MILU7WFN.mjs} +1 -1
- package/lib/chunk-MJU2PGZQ.mjs +15 -0
- package/lib/{chunk-HJKM3E56.mjs → chunk-MJVTDA5Q.mjs} +1 -1
- package/lib/{chunk-SBIMVCXT.mjs → chunk-MS4FJDFD.mjs} +9 -9
- package/lib/{chunk-3SRXFZSD.mjs → chunk-MYW5QNGI.mjs} +1 -1
- package/lib/{chunk-VHI54FBK.mjs → chunk-N652NMZ4.mjs} +26 -26
- package/lib/{chunk-3DCUADVK.mjs → chunk-NTFIRZP6.mjs} +1 -1
- package/lib/{chunk-342FN7AO.mjs → chunk-NZC67CGR.mjs} +1 -1
- package/lib/{chunk-RSYICMZG.mjs → chunk-O2HDYYUV.mjs} +1 -1
- package/lib/chunk-OAZRPP4I.mjs +7 -0
- package/lib/{chunk-BILZ3SSR.mjs → chunk-OHWNPXWW.mjs} +1 -1
- package/lib/chunk-OLSGVAIL.mjs +341 -0
- package/lib/chunk-OO6CLPEH.mjs +7 -0
- package/lib/chunk-OPXCV2KL.mjs +7 -0
- package/lib/chunk-P33PSCXK.mjs +7 -0
- package/lib/{chunk-AUTM6H6Z.mjs → chunk-PJ5I73CK.mjs} +1 -1
- package/lib/{chunk-NTDN2JQZ.mjs → chunk-PZPJKATS.mjs} +1 -1
- package/lib/{chunk-5QKTYCWE.mjs → chunk-Q3DM32KF.mjs} +1 -1
- package/lib/{chunk-K22PA4XL.mjs → chunk-QR3WELJQ.mjs} +1 -1
- package/lib/{chunk-42RER7V4.mjs → chunk-R3X3LV64.mjs} +1 -1
- package/lib/chunk-RMBPOTD7.mjs +7 -0
- package/lib/{chunk-IEYG5ATY.mjs → chunk-RPI7LRTW.mjs} +1 -1
- package/lib/{chunk-5MMXFWPD.mjs → chunk-SE4QEZUG.mjs} +1 -1
- package/lib/{chunk-ALJVEUUS.mjs → chunk-SIHORWVK.mjs} +1 -1
- package/lib/{chunk-AAVJ5XVX.mjs → chunk-SOGQW4IG.mjs} +1 -1
- package/lib/chunk-SOU4FRYN.mjs +7 -0
- package/lib/chunk-SU65Z2BA.mjs +7 -0
- package/lib/chunk-T62WNR54.mjs +7 -0
- package/lib/{chunk-5O6JOMHS.mjs → chunk-TSLJUSLW.mjs} +1 -1
- package/lib/chunk-TTFDUKUS.mjs +47 -0
- package/lib/{chunk-57VHUYNG.mjs → chunk-TTKXMDBN.mjs} +1 -1
- package/lib/chunk-UCD54V2M.mjs +7 -0
- package/lib/{chunk-TBZMC2VV.mjs → chunk-UNJA4J37.mjs} +1 -1
- package/lib/{chunk-NGSMZZDA.mjs → chunk-VE6XKGGD.mjs} +1 -1
- package/lib/chunk-VS7ZXUII.mjs +824 -0
- package/lib/{chunk-ALUFROGA.mjs → chunk-VXQLDM4R.mjs} +1 -1
- package/lib/chunk-VYXMVJL5.mjs +7 -0
- package/lib/{chunk-WFEB5X4U.mjs → chunk-W622GUAW.mjs} +1 -1
- package/lib/chunk-W7U5E5ZL.mjs +9 -0
- package/lib/{chunk-AR7BE5O2.mjs → chunk-WA7EYLAQ.mjs} +1 -1
- package/lib/{chunk-EQF2IJS2.mjs → chunk-WR4Q363I.mjs} +1 -1
- package/lib/{chunk-ZXH4MBWP.mjs → chunk-WU3GLFZO.mjs} +1 -1
- package/lib/chunk-WXAQ7FK3.mjs +115 -0
- package/lib/{chunk-YBU4Z4QV.mjs → chunk-X5JYBPXP.mjs} +1 -1
- package/lib/chunk-XAMBCQPU.mjs +7 -0
- package/lib/{chunk-LQ4DRFUH.mjs → chunk-XLXIPIEW.mjs} +1 -1
- package/lib/{chunk-H2PJNIYJ.mjs → chunk-XUWL6ZPC.mjs} +1 -1
- package/lib/{chunk-P42X3B4D.mjs → chunk-YKKRIEH4.mjs} +1 -1
- package/lib/chunk-YRQGKDHM.mjs +7 -0
- package/lib/chunk-ZM6OJGIG.mjs +7 -0
- package/lib/{chunk-SFURUNJM.mjs → chunk-ZVAED4QV.mjs} +1 -1
- package/lib/sandforge-autopilot.mjs +29 -24
- package/lib/sandforge-backup.mjs +25 -21
- package/lib/sandforge-checkpoint.mjs +15 -14
- package/lib/sandforge-cleanup.mjs +14 -10
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +9 -8
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +15 -15
- package/lib/sandforge-env.mjs +88 -88
- package/lib/sandforge-frozen.mjs +43 -34
- package/lib/sandforge-mcp.mjs +12 -12
- package/lib/sandforge-monitor.mjs +7 -7
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge.mjs +4 -4
- package/package.json +1 -1
- package/lib/chunk-2S5OMIIA.mjs +0 -7
- package/lib/chunk-36U7IQ6Y.mjs +0 -25
- package/lib/chunk-3F5YMM2F.mjs +0 -7
- package/lib/chunk-3RYLICRX.mjs +0 -7
- package/lib/chunk-4GL773D5.mjs +0 -7
- package/lib/chunk-4XZ5YT5O.mjs +0 -7
- package/lib/chunk-5AJRHRXA.mjs +0 -20
- package/lib/chunk-5HMAPZBV.mjs +0 -7
- package/lib/chunk-6LAXTAVN.mjs +0 -7
- package/lib/chunk-6MUEPV7M.mjs +0 -9
- package/lib/chunk-75ADZS6B.mjs +0 -7
- package/lib/chunk-B45CNPUX.mjs +0 -47
- package/lib/chunk-BS5T3MOQ.mjs +0 -7
- package/lib/chunk-D3QRXG63.mjs +0 -787
- package/lib/chunk-EEVVGGM6.mjs +0 -7
- package/lib/chunk-ENLBYECD.mjs +0 -7
- package/lib/chunk-EQOQASDQ.mjs +0 -7
- package/lib/chunk-FQBRBBY4.mjs +0 -7
- package/lib/chunk-GAM726CK.mjs +0 -7
- package/lib/chunk-HUMEKZT5.mjs +0 -8
- package/lib/chunk-I3JKJTLO.mjs +0 -110
- package/lib/chunk-KLX67VPL.mjs +0 -7
- package/lib/chunk-L776PUMV.mjs +0 -7
- package/lib/chunk-NEVXIGR6.mjs +0 -10
- package/lib/chunk-NHWE66K5.mjs +0 -7
- package/lib/chunk-OQOZAPCI.mjs +0 -7
- package/lib/chunk-PA3MKJVH.mjs +0 -7
- package/lib/chunk-RH3N2H7P.mjs +0 -7
- package/lib/chunk-SRQDABQ2.mjs +0 -15
- package/lib/chunk-SVS6UMDU.mjs +0 -323
- package/lib/chunk-TNXUU6W7.mjs +0 -14
- package/lib/chunk-VXHDBYMI.mjs +0 -7
- package/lib/chunk-WRU5FJFC.mjs +0 -7
- package/lib/chunk-X2PY6MWZ.mjs +0 -7
- package/lib/chunk-XEFDB2R4.mjs +0 -7
- package/lib/chunk-XETCPL7E.mjs +0 -7
- package/lib/chunk-Y5CGXLUB.mjs +0 -7
- package/lib/chunk-Y6J6QFI2.mjs +0 -7
- package/lib/chunk-YMJVMFPY.mjs +0 -7
- package/lib/chunk-YPSRZRIT.mjs +0 -7
- package/lib/chunk-YW2SBL4Z.mjs +0 -7
- package/lib/chunk-ZE6HKRR4.mjs +0 -9
- package/lib/chunk-ZLZRU6MO.mjs +0 -7
- package/lib/chunk-ZYEE34WO.mjs +0 -7
package/lib/chunk-SRQDABQ2.mjs
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
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 gt,b as rn,c as on}from"./chunk-66NMFCWX.mjs";import{a as dn}from"./chunk-LV6G4XTK.mjs";import{a as wr,b as ln}from"./chunk-XCA5AONB.mjs";import{a as cn,e as hr,i as br}from"./chunk-WR2GIKWE.mjs";import{Aa as ar,Ba as dr,Bc as pn,Ca as cr,Dc as Ar,b as ft,d as Zt,e as Yt,f as en,j as se,k as tn,l as jt,m as Ct,n as xe,o as M,pa as Jn,qa as Zn,ra as Yn,s as de,sa as er,ta as tr,ua as nr,uc as le,va as rr,wa as Mt,xa as or,ya as sr,yc as fr,za as ir}from"./chunk-YMJVMFPY.mjs";import{d as lr}from"./chunk-ALJVEUUS.mjs";import{a as mt,b as Vn}from"./chunk-CE6ZDGBB.mjs";import{a as Rr,b as fn,c as vr,d as mn,e as ht,f as bt,g as Or,h as gn,i as Sr,j as hn,k as bn}from"./chunk-4HFRHFGQ.mjs";import{k as yr}from"./chunk-Z7X534S4.mjs";import{S as mr,U as gr,l as pr}from"./chunk-6QSM2WIH.mjs";import{d as kr}from"./chunk-T63U4OZJ.mjs";import{a as un}from"./chunk-YYZL7UGV.mjs";import{A as Ir,q as Re}from"./chunk-6MUEPV7M.mjs";import{b as sn,c as nt,d as an,h as ur}from"./chunk-OTWRDD6L.mjs";import{a as Be}from"./chunk-5LFSFYFJ.mjs";import{c as Pt,e as oe,f as $t,i as nn,p as Tr}from"./chunk-VXHDBYMI.mjs";import{d as Gn,e as qn,g as Xn,h as Qn}from"./chunk-INIT2UKJ.mjs";import{p as W,q as lt,t as Nt}from"./chunk-CGWXQX75.mjs";import{a as Kn,f as Jt,h as St}from"./chunk-TZE3Y7IQ.mjs";import{b as R}from"./chunk-CA5NAXSU.mjs";import{Fa as Fn,Fd as Hn,Ga as _n,Ha as Wn,Tb as De,Yb as Vt,bc as It,ec as Un,fc as Ot,vb as Qt}from"./chunk-B45CNPUX.mjs";import{b as Q,f as xn,k as Ke,l as Ge,q as Bn,v as Xt}from"./chunk-7EANH5PY.mjs";var co={defaultQueryLimit:500,previewQueryLimit:200,exportQueryLimit:1e3},po={defaultQueryLimit:2e3,previewQueryLimit:2e3,exportQueryLimit:5e3};function kn(s){return s==="production"?{...co}:{...po}}function yn(s){return s?"sandbox":"production"}var rt="IsPersonAccount",uo=new Set(["FirstName","LastName","MiddleName","Suffix","Salutation","Phone","Fax"]);function lo(s){if(uo.has(s))return s;if(s.endsWith("__c"))return`${s.slice(0,-3)}__pc`;if(/^[A-Za-z][A-Za-z0-9]*$/.test(s))return`Person${s}`}function wn(s){let e=(r,o)=>r.fieldPattern.toLowerCase().startsWith(`${o.toLowerCase()}.`)?r.fieldPattern.slice(o.length+1):void 0,t=new Set(s.flatMap(r=>{let o=e(r,W);return o===void 0?[]:[o.toLowerCase()]})),n=[];for(let r of s){let o=e(r,lt),i=o===void 0?void 0:lo(o);i===void 0||t.has(i.toLowerCase())||(t.add(i.toLowerCase()),n.push({...r,fieldPattern:`${W}.${i}`}))}return n}function Nr(s){if(s.objectApiName.toLowerCase()!==W.toLowerCase()||!s.fields.some(p=>p.name===rt))return;let e=new Map(s.fields.map(p=>[p.name.toLowerCase(),p])),t=new Set(s.kept.map(p=>p.fieldApiName.toLowerCase())),n=[],r=new Set,o=[],i=(p,u)=>{t.add(u.name.toLowerCase()),r.add(u.name),n.push({...p,objectApiName:W,fieldApiName:u.name})};for(let p of s.derived){let u=e.get(p.fieldApiName.toLowerCase());if(!u){o.push(p.fieldApiName);continue}t.has(u.name.toLowerCase())||i(p,u)}let a=s.fields.filter(p=>Un(p.name)&&p.updateable===!0&&p.calculated!==!0&&!t.has(p.name.toLowerCase())),d=new Map,c=a.map(p=>{let u=$r(p.name);return d.set(u,p),{...p,name:u,label:p.label??p.name,type:p.type??"string"}});for(let p of hr(s.detector,lt,c)){let u=d.get(p.field.name);!u||t.has(u.name.toLowerCase())||i({objectApiName:W,fieldApiName:u.name,method:br({...p.field,name:u.name}),config:{}},u)}return{rules:n,personOnly:r,unseen:o}}function Pr(s,e){let t=new Set((e??[]).map(n=>n.name.toLowerCase()));return s.filter(n=>!t.has($r(n).toLowerCase()))}function $r(s){return s.endsWith("__pc")?`${s.slice(0,-4)}__c`:s.startsWith("Person")&&!s.includes("__")?s.slice(6):s}function jr(s,e,t,n){if(s.toLowerCase()!==W.toLowerCase())return[...t];let r=Nt(e,!1);return t.filter(o=>!Ot(W,o.fieldApiName,r)&&(r==="person"||!n.has(o.fieldApiName)))}import{randomBytes as Oo}from"node:crypto";var kt=[{id:"tpl-gdpr-standard",name:"GDPR Standard",description:"Standard GDPR compliance: anonymize personal data fields across common Salesforce objects.",complianceFramework:"gdpr",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace with fake first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace with fake last name."},{fieldPattern:"Contact.Email",ruleType:"fake",description:"Replace with fake email address."},{fieldPattern:"Contact.Phone",ruleType:"mask",description:"Mask phone number (keep last 4 digits).",config:{maskKeepLast:4}},{fieldPattern:"Contact.MailingStreet",ruleType:"fake",description:"Replace with fake street address."},{fieldPattern:"Contact.MailingCity",ruleType:"fake",description:"Replace with fake city."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"mask",description:"Mask postal code."},{fieldPattern:"Lead.FirstName",ruleType:"fake",description:"Replace with fake first name."},{fieldPattern:"Lead.LastName",ruleType:"fake",description:"Replace with fake last name."},{fieldPattern:"Lead.Email",ruleType:"fake",description:"Replace with fake email address."},{fieldPattern:"Lead.Phone",ruleType:"mask",description:"Mask phone number."},{fieldPattern:"Lead.Street",ruleType:"fake",description:"Replace with fake street address."},{fieldPattern:"Account.BillingStreet",ruleType:"fake",description:"Replace with fake address."},{fieldPattern:"Account.Phone",ruleType:"mask",description:"Mask phone number."}]},{id:"tpl-ccpa-california",name:"CCPA California",description:"CCPA compliance: anonymize consumer personal information per California privacy regulations.",complianceFramework:"ccpa",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace consumer first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace consumer last name."},{fieldPattern:"Contact.Email",ruleType:"hash",description:"Hash email for pseudonymization."},{fieldPattern:"Contact.Phone",ruleType:"nullify",description:"Nullify phone number."},{fieldPattern:"Contact.MailingStreet",ruleType:"nullify",description:"Nullify street address."},{fieldPattern:"Contact.MailingCity",ruleType:"nullify",description:"Nullify city."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"nullify",description:"Nullify postal code."},{fieldPattern:"Contact.Birthdate",ruleType:"nullify",description:"Remove date of birth."},{fieldPattern:"Lead.Email",ruleType:"hash",description:"Hash email for pseudonymization."},{fieldPattern:"Lead.Phone",ruleType:"nullify",description:"Nullify phone number."}]},{id:"tpl-hipaa-health",name:"HIPAA Health Data",description:"HIPAA compliance: de-identify protected health information (PHI) in healthcare Salesforce orgs.",complianceFramework:"hipaa",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace patient first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace patient last name."},{fieldPattern:"Contact.Email",ruleType:"hash",description:"Hash email address."},{fieldPattern:"Contact.Phone",ruleType:"mask",description:"Mask phone number."},{fieldPattern:"Contact.Birthdate",ruleType:"nullify",description:"Remove date of birth (PHI)."},{fieldPattern:"Contact.MailingStreet",ruleType:"nullify",description:"Remove address (PHI)."},{fieldPattern:"Contact.MailingCity",ruleType:"nullify",description:"Remove city (PHI)."},{fieldPattern:"Contact.MailingState",ruleType:"nullify",description:"Remove state (PHI)."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"truncate",description:"Truncate to first 3 digits.",config:{truncateLength:3,truncateKeep:"first"}},{fieldPattern:"Account.Name",ruleType:"fake",description:"Replace facility name."},{fieldPattern:"Account.Phone",ruleType:"mask",description:"Mask facility phone."}]},{id:"tpl-sandbox-scrub",name:"Sandbox Data Scrub",description:"General-purpose sandbox data scrubbing: mask all PII for safe development use.",complianceFramework:"custom",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Fake first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Fake last name."},{fieldPattern:"Contact.Email",ruleType:"preserve_format",description:"Replace keeping email format."},{fieldPattern:"Contact.Phone",ruleType:"preserve_format",description:"Replace keeping phone format."},{fieldPattern:"Lead.FirstName",ruleType:"fake",description:"Fake first name."},{fieldPattern:"Lead.LastName",ruleType:"fake",description:"Fake last name."},{fieldPattern:"Lead.Email",ruleType:"preserve_format",description:"Replace keeping email format."},{fieldPattern:"Lead.Company",ruleType:"fake",description:"Fake company name."},{fieldPattern:"Account.Name",ruleType:"fake",description:"Fake account name."},{fieldPattern:"Account.Website",ruleType:"constant",description:"Replace with placeholder URL.",config:{constantValue:"https://example.com"}},{fieldPattern:"Opportunity.Name",ruleType:"fake",description:"Fake opportunity name."}]}];var Et=class{operations=new Map;ttlMs;nowFn;constructor(e=36e5,t=Date.now){this.ttlMs=e,this.nowFn=t}isDuplicate(e){return this.pruneExpired(),this.operations.has(e)}register(e,t,n,r){if(this.pruneExpired(),this.operations.has(e))throw new Error(`Duplicate DML operation detected: ${e}`);let o={operationId:e,objectApiName:t,dmlType:n,recordCount:r,registeredAt:new Date(this.nowFn()).toISOString(),status:"pending"};return this.operations.set(e,o),o}markCompleted(e){let t=this.operations.get(e);t&&(t.status="completed")}markFailed(e){let t=this.operations.get(e);t&&(t.status="failed")}get(e){return this.operations.get(e)}get size(){return this.operations.size}clear(){this.operations.clear()}pruneExpired(){let e=this.nowFn()-this.ttlMs;for(let[t,n]of this.operations)new Date(n.registeredAt).getTime()<e&&this.operations.delete(t);if(this.operations.size>1e4){let t=Array.from(this.operations.entries()),n=t.length-1e4;for(let r=0;r<n;r++)this.operations.delete(t[r][0])}}};var fo=3e3;function Se(s){return s.slice(0,15)}function mo(s,e){let t=s??null,n=e??null;return t===n?!0:t===null||n===null?!1:typeof t=="object"||typeof n=="object"?JSON.stringify(t)===JSON.stringify(n):String(t)===String(n)}function go(s){let e=[],t=[],n=0;for(let r of s)t.length>0&&n+r.length+2>fo&&(e.push(t),t=[],n=0),t.push(r),n+=r.length+2;return t.length>0&&e.push(t),e}async function Cr(s,e,t){let n=t.map(a=>a.Id).filter(nt),r=[...new Set(t.flatMap(a=>Object.keys(a)))].filter(a=>a.toLowerCase()!=="id");if(n.length===0||r.length===0)return{write:[...t],unchanged:0};let o=new Map;try{for(let a of go(r))for(let d of await ur(s,e,a,n))typeof d.Id=="string"&&o.set(Se(d.Id),{...o.get(Se(d.Id)),...d})}catch(a){return{write:[...t],unchanged:0,unread:R(a)}}let i=t.filter(a=>{let d=nt(a.Id)?o.get(Se(a.Id)):void 0;return d?Object.keys(a).some(c=>c.toLowerCase()!=="id"&&!mo(a[c],d[c])):!0});return{write:i,unchanged:t.length-i.length}}async function Mr(s,e,t,n){let r=St(e),o=new Set,i=t.filter(nt);for(let a=0;a<i.length;a+=sn){let d=i.slice(a,a+sn),[c]=an(d,d.length),p=new Set,u=await s.query(`SELECT Id, LastModifiedDate FROM ${r} WHERE Id IN (${c})`);for(let h of u.records){if(typeof h.Id!="string")continue;p.add(Se(h.Id)),Date.parse(String(h.LastModifiedDate??""))<=n||o.add(Se(h.Id))}let b=d.filter(h=>!p.has(Se(h)));if(b.length===0)continue;let[l]=an(b,b.length),f=await s.query(`SELECT Id FROM ${r} WHERE Id IN (${l}) AND IsDeleted = true`,{scanAll:!0});for(let h of f.records)typeof h.Id=="string"&&o.add(Se(h.Id))}return o}function Er(s,e){return{async*[Symbol.asyncIterator](){for await(let t of s){let n=t.filter(r=>!(nt(r.Id)&&e.has(Se(r.Id))));n.length>0&&(yield n)}}}}function An(s,e){let t=0;return{batches:{async*[Symbol.asyncIterator](){let n=new Map,r=[],o=0;for await(let a of s)for(let d of a){if(o++,!nt(d.Id)){r.push({...d});continue}let c=n.get(Se(d.Id));if(!c){n.set(Se(d.Id),{...d});continue}for(let[p,u]of Object.entries(d))p in c||(c[p]=u)}t=o;let i=[...n.values(),...r];for(let a=0;a<i.length;a+=e)yield i.slice(a,a+e)}},lines:()=>t}}var Rn="anonymization:template:",zr="anonymizationTemplates",Lr=Ge({id:Q().min(1).max(100),name:Q().trim().min(1).max(Fn),description:Q().max(500),complianceFramework:Xt("custom"),rules:Ke(Bn(Wn,Ge({description:Q().max(500)}))).min(1).max(_n),saved:Xt(!0),createdAt:Q()}),zt=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${Rn}${e.id}`,e,zr)}load(e){let t=Lr.safeParse(this.configStore.get(`${Rn}${e}`));return t.success?t.data:void 0}list(){let e=[];for(let t of Object.values(this.configStore.getByCategory(zr))){let n=Lr.safeParse(t);n.success&&e.push(n.data)}return e.sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}delete(e){return this.configStore.delete(`${Rn}${e}`)}};import{createHash as Dr}from"node:crypto";var bo="anonymization:checkpoint:",ko="anonymizationCheckpoints",qe=2e3,vn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,yo=Q().min(1).max(255),wo=Ge({id:Q().regex(vn),fields:Ke(yo).min(1).max(800),digest:Q().regex(/^[0-9a-f]{64}$/)}),Ao=Ge({objectApiName:Q().min(1).max(255),done:xn(),afterId:Q().regex(vn).optional(),refused:Ke(Q().regex(vn)).max(qe),unconfirmed:Ke(wo).max(qe).optional()}),Ro=Ge({id:Q().min(1).max(200),orgId:Q().min(1).max(200),templateId:Q().min(1).max(200),fingerprint:Q().regex(/^[0-9a-f]{64}$/),savedAt:Q(),objects:Ke(Ao),namesGiven:Q().max(6e4).regex(/^[A-Za-z0-9+/]*={0,2}$/).optional()});function Lt(s,e,t){let n=s.map(o=>[o.fieldPattern,o.ruleType,o.config??null]),r=t?.trim();return Dr("sha256").update(JSON.stringify(r?{rules:n,objects:e,where:r}:{rules:n,objects:e})).digest("hex")}function vo(s){return s==null||s===""?null:typeof s=="string"?s.trim():typeof s=="number"||typeof s=="boolean"?String(s):JSON.stringify(s)}function Tn(s,e){let t=[...e].sort().map(n=>[n,vo(s[n])]);return Dr("sha256").update(JSON.stringify(t)).digest("hex")}function yt(s){return s.reduce((e,t)=>e+t.refused.length,0)}var ot=class{constructor(e){this.configStore=e}configStore;load(e,t,n){let r=Ro.safeParse(this.configStore.get(this.key(e,t)));if(!r.success)return;let o=r.data;if(!(o.orgId!==e||o.templateId!==t||o.fingerprint!==n))return o}save(e){if(yt(e.objects)>qe)throw new Error(`A checkpoint keeps at most ${qe} refused records; this run left ${yt(e.objects)}.`);this.configStore.set(this.key(e.orgId,e.templateId),e,ko)}clear(e,t){this.configStore.delete(this.key(e,t))}key(e,t){return`${bo}${e}:${t}`}};async function To(s){let{open:e,rename:t,rm:n}=await import("node:fs/promises"),{randomBytes:r}=await import("node:crypto"),o=`${s}.${r(4).toString("hex")}.partial`,i=await e(o,"w"),a=!1;return{write:async d=>{let c=Buffer.from(d,"utf8");for(let p=0;p<c.length;){let{bytesWritten:u}=await i.write(c,p,c.length-p,null);p+=u}},close:async()=>{a=!0,await i.close(),await t(o,s)},abort:async()=>{a||await i.close().catch(()=>{}),a=!0,await n(o,{force:!0})}}}function Io(s){let e=[];return{write:async t=>{e.push(t)},close:async()=>{await s(new TextEncoder().encode(e.join("")))},abort:async()=>{e.length=0}}}var Dt=class s{host;constructor(e){this.host=e??null}async defaultHost(){let e=await import("vscode");return{showSaveDialog:t=>e.window.showSaveDialog(t),writeFile:(t,n)=>e.workspace.fs.writeFile(t,n),fileUri:t=>e.Uri.file(t),openFile:async t=>t.scheme==="file"?To(t.fsPath):Io(n=>e.workspace.fs.writeFile(t,n))}}static filtersOf(e,t){let n=e.includes(".")?e.split(".").pop():void 0;return t?.length?{[t.join("/").toUpperCase()]:t}:n?{[n.toUpperCase()]:[n]}:void 0}static ask(e,t,n){let r=s.filtersOf(t,n);return e.showSaveDialog({saveLabel:"Save",defaultUri:e.fileUri(t),...r?{filters:r}:{}})}async save(e,t,n){let r=this.host??await this.defaultHost();try{let o=await s.ask(r,e,n);return o?(await r.writeFile(o,new TextEncoder().encode(t)),{status:"saved",path:o.fsPath}):{status:"cancelled"}}catch(o){return{status:"error",message:o instanceof Error?o.message:String(o)}}}async saveStream(e,t,n){let r=this.host??await this.defaultHost(),o;try{let i=await s.ask(r,e,n);if(!i)return{status:"cancelled"};let a=await r.openFile(i);o=a;let d=await t(c=>a.write(c));return await a.close(),o=void 0,{status:"saved",path:i.fsPath,result:d}}catch(i){return await o?.abort().catch(()=>{}),{status:"error",message:i instanceof Error?i.message:String(i)}}}};function xt(s,e,t,n,r=0){s?.register(e,t,n,r);let o=!1,i=a=>{o||(o=!0,a())};return{progress:(a,d,c,p)=>{o||s?.updateProgress(e,a,d,c,p)},complete:()=>i(()=>s?.complete(e)),partial:()=>i(()=>s?.partial(e)),fail:a=>i(()=>s?.fail(e,a)),cancel:()=>i(()=>s?.cancel(e))}}var ve={orgUnknown:"ORG_NOT_FOUND",production:"PIPELINE_WRITE_REFUSED",needsApproval:"PIPELINE_WRITE_NEEDS_APPROVAL",retries:"PIPELINE_WRITE_NO_RETRIES",filterNeedsObject:"MASKING_FILTER_NEEDS_OBJECT",invalid:"INVALID_PAYLOAD",templateMissing:"TEMPLATE_NOT_FOUND",fieldsUnseen:"MASKING_FIELDS_UNSEEN",masksNothing:"MASKING_MASKS_NOTHING"};function Fe(s,e){return Object.assign(new Error(e),{code:s})}function xr(s,e,t){let n=Hn(s);if(n==="refused")return Fe(ve.production,`${t} is a production org, or one SandForge cannot tell is not: a pipeline never masks one, whatever an Approval step answers. Mask a sandbox, a scratch org or a Developer Edition org. Nothing was masked.`);if(n==="needsApproval"&&!e.approved)return Fe(ve.needsApproval,`${t} is a sandbox marked Staging, which a pipeline masks only once an Approval step before the masking has approved the run, and none did: put an Approval step before it. Nothing was masked.`)}function Br(s,e){if(s.retries!==void 0&&s.retries>0)return{refusal:Fe(ve.retries,"A masking step is never tried again: a second try masks again what the first one masked \u2014 an address it hashed is hashed once more, and no longer gives the same pseudonym on Contact and on Lead. Set its retries to 0. Nothing was masked.")};let t=s.where?.trim();if(t&&s.object===void 0)return{refusal:Fe(ve.filterNeedsObject,"A masking condition filters the rows of one object: name the object it holds, or remove the condition. Nothing was masked.")};let n=Mt.safeParse({orgId:s.orgId,templateId:s.templateId,...s.object!==void 0?{objects:[s.object]}:{},...t?{where:t}:{},snapshot:!0});if(!n.success){let r=n.error.issues[0];return{refusal:Fe(ve.invalid,`The masking step is not one the DataOps page would run (${r.path.join(".")}: ${r.message}). Nothing was masked.`)}}return e(n.data.templateId)?{asked:n.data}:{refusal:Fe(ve.templateMissing,`No masking template is shipped or saved under ${n.data.templateId}: it was deleted on the DataOps page. Choose another. Nothing was masked.`)}}function oo(s){let e=s.fields;return{name:s.name,label:s.label,labelPlural:s.labelPlural??"",keyPrefix:s.keyPrefix??null,custom:s.custom??!1,createable:s.createable,updateable:s.updateable,deletable:s.deletable,queryable:s.queryable,fields:e.map(t=>({name:t.name,label:t.label,type:t.type,length:t.length??0,nillable:t.nillable??!1,createable:t.createable,updateable:t.updateable,externalId:t.externalId??!1,referenceTo:t.referenceTo??[],relationshipName:t.relationshipName??null,picklistValues:t.picklistValues??[],defaultValue:t.defaultValue??null,calculated:t.calculated??!1,autoNumber:t.autoNumber??!1,unique:t.unique??!1,permissionable:t.permissionable??!0})),recordTypeInfos:s.recordTypeInfos??[],childRelationships:s.childRelationships??[]}}var So=new Set(["backup:execute","backup:list","backup:objects","backup:export","backup:delete","dataops:rollback","dataops:anonymize","dataops:anonymization-templates","dataops:quality-scan","dataops:anonymization-template:save","dataops:anonymization-template:delete","dataops:anonymize:coverage","dataops:anonymize:preview","dataops:automation","precheck:pii-scan"]),No=6e4,Po=10,$o=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function jo(s,e){return s.slice(0,15)===e.slice(0,15)}var Fr="ORG_REPLACED_SINCE_BACKUP",Co="Backup was cancelled before it finished. Nothing was saved \u2014 run it again to take a complete snapshot.",it=class extends Error{constructor(){super(Co),this.name="BackupCancelledError"}},wt=class extends Error{constructor(e){super(`The backup could not be written to disk: ${R(e)}`),this.name="BackupWriteError"}},at=class extends Error{constructor(t,n){super(t);this.retryable=n;this.name="BackupNotWholeError"}retryable},jn="IsDeleted = false",Mo="SystemModstamp",_r=5e4,Eo=100,zo=1e6,st=200,Lo=1440*6e4,Do=1440*6e4,Wr="backupRetention:since",xo="BACKUP_BUSY";function Bo(s,e){return e===0?"success":s===0?"failure":"partial"}function In(s){return Vt(s)}function Ur(s,e,t){s.length>=Po||s.push({objectApiName:e,message:t?.[0]?.message??"Unknown DML error"})}function Bt(s,e,t=!1){let n=(e?.rules??[]).map(o=>o.fieldPattern.split(".")[0]).filter((o,i,a)=>a.findIndex(d=>On(d,o))===i);if(s.objects)return s.objects.map(o=>n.find(i=>On(i,o))??(On(o,W)?W:o));if(!e)return[];let r=[...n];return t&&At(s,e,W)&&r.push(W),r}function On(s,e){return s.toLowerCase()===e.toLowerCase()}var Fo=`${rt} = true`;function At(s,e,t){return s.objects===void 0&&t.toLowerCase()===W.toLowerCase()&&Ft(e,W).length===0&&wn(e.rules).length>0}function Sn(s,e,t){return At(s,e,t)?Fo:En(s)}async function Nn(s,e){try{return(await s.describe(W)).fields.some(t=>t.name===rt)}catch(t){return e(`[WARN] dataops: whether the org has person accounts was not read: ${R(t)}`),!1}}function Ft(s,e){let t=`${e.toLowerCase()}.`;return s.rules.filter(n=>n.fieldPattern.toLowerCase().startsWith(t)||n.fieldPattern==="*")}function Cn(s,e){return e.toLowerCase()===W.toLowerCase()?wn(s.rules):[]}function Hr(s){let e=new Map;return{describe:t=>{let n=e.get(t)??s.describe(t);return e.set(t,n),n}}}async function Kr(s,e){return new on(async n=>oo(await s.describe(n))).deniedOf(e.map(({objectApiName:n,rules:r})=>({objectApiName:n,operation:"update",fieldNames:r.map(o=>o.fieldPattern.includes(".")?o.fieldPattern.split(".")[1]:o.fieldPattern).filter(o=>o!=="*")})))}function Gr(s,e){return Ft(s,e).length>0||Cn(s,e).length>0}function Pn(s){return{objectApiName:s.objectApiName,recordCount:s.recordCount,truncated:s.truncated===!0,...s.orgCount!==void 0?{orgCount:s.orgCount}:{},...s.stoppedAt?{stoppedAt:s.stoppedAt}:{},...s.notKept&&s.notKept.length>0?{notKept:[...s.notKept]}:{}}}function $n(s,e){return s.flatMap(t=>{let n=e?.get(t.objectApiName);if(n!==void 0&&n<t.recordCount)return[`${t.objectApiName} ${n} of the ${t.recordCount} it listed (not found on disk)`];if(!t.truncated)return[];if(t.stoppedAt==="not_reached")return[`${t.objectApiName} none (the backup stopped before it)`];let r=t.orgCount!==void 0?` of ${t.orgCount}`:"",o=t.stoppedAt==="cap"?" (stopped at the cap)":t.stoppedAt==="failure"?" (the read failed)":"";return[`${t.objectApiName} ${t.recordCount}${r}${o}`]}).join(", ")}var Xe=200,_o=95,_t=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Wo="NOTHING_TO_RESUME",qr="TEMPLATE_NOT_FOUND";function Xr(s){return new Error(`Template "${s}" not found.`)}function Uo(s){let e=s.Id;if(typeof e!="string"||!_t.test(e))return[];let t=Object.keys(s).filter(n=>n!=="Id");return t.length>0?[{id:e,fields:t,digest:Tn(s,t)}]:[]}var Ho="COUNT_FAILED",Qr="SNAPSHOT_NOT_TAKEN",Ko=/^([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+):/;function Go(s){if(typeof s=="object"&&s!==null){let{errorCode:e,code:t}=s;if(typeof e=="string"&&e!=="")return e;if(typeof t=="string"&&t!=="")return t}return Ko.exec(R(s))?.[1]??"UNKNOWN"}var Vr=5;function Jr(s){return s==null?null:typeof s=="string"||typeof s=="number"||typeof s=="boolean"?s:JSON.stringify(s)}function so(s){return s.done?0:Math.max(0,s.total-s.masked-s.nothingToMask-s.refused-s.unanswered)}function Wt(s){return s.refused+s.unanswered+so(s)}function Rt(s){return s.reduce((e,t)=>({recordsProcessed:e.recordsProcessed+t.masked+t.nothingToMask,recordsFailed:e.recordsFailed+t.refused,recordsNotMasked:e.recordsNotMasked+Wt(t)}),{recordsProcessed:0,recordsFailed:0,recordsNotMasked:0})}function qo(s,e){let{recordsProcessed:t,recordsFailed:n,recordsNotMasked:r}=Rt(s);return r===0?"success":t>0||e&&n===0?"partial":"failure"}function Xo(s,e,t){if(!t||e==="success")return{outcome:e};let{recordsProcessed:n,recordsFailed:r}=Rt(s);return n+r>0?{outcome:"cancelled"}:{outcome:"stopped",code:nn}}function Zr(s){return s.filter(e=>Wt(e)>0).map(e=>`${e.objectApiName} ${Wt(e)}`).join(", ")}function Yr(s){return s.map(e=>({objectApiName:e.objectApiName,total:e.total,processed:e.masked+e.nothingToMask,failed:e.refused,notMasked:Wt(e)}))}function eo(s){return s.filter(e=>e.total>0||e.masked+e.refused>0).map(e=>{let t=so(e);return{...$t(e.objectApiName),updated:e.masked,failed:e.refused+e.unanswered,...e.unanswered>0?{mayHaveBeenWritten:e.unanswered}:{},...t>0?{notSent:t}:{}}})}async function to(s,e,t,n,r,o){return Vn(s,`SELECT ${t} FROM ${e}${Mn(o,r)} ORDER BY Id LIMIT ${n}`,n)}function Mn(s,e){let t=s?.trim(),n=[...t?[`(${Jt(t)})`]:[],...e===void 0?[]:[`Id > '${e}'`]];return n.length===0?"":` WHERE ${n.join(" AND ")}`}function En(s){let e=s.where?.trim();return e||void 0}function Qo(s){let e=s?.trim();return e?`(${Jt(e)}) AND ${jn}`:jn}function Vo(s){let e=new Map;for(let[t,n]of s){if(n.length===0)throw new Error(`No field of ${t} was named for the snapshot to read.`);e.set(t,n.map(r=>St(r)).join(", "))}return e}function no(s,e,t){let n=e===void 0?"more records":`${e} records`;return new at(`${s} holds ${n}, past the ${t} a snapshot reads of one object: no snapshot was kept, as one holding part of the object would be taken for all of it.`,!1)}function io(s,e){return`The org stopped answering the read of ${s} after ${e} record(s), before it said the read was done: no snapshot was kept.`}async function Jo(s,e,t,n){let r={headers:{},maxFetch:1e4,autoFetch:!1,scanAll:t,responseTarget:"QueryResult"},o=await s.query(e,r),i=[...o.records];for(;!o.done;){if(!o.nextRecordsUrl)throw new at(io(n,i.length),!0);o=await s.queryMore(o.nextRecordsUrl,r),i.push(...o.records)}return i}function Zo(s,e,t){let n=s[s.length-1]?.Id;if(typeof n!="string"||!_t.test(n)||n===e)throw new Error(`The org answered a page of ${t} that does not end past the page before it: masking stopped there rather than write the same rows again.`);return n}var ro=class{constructor(e,t){this.deps=e;this.saveDialog=t??new Dt}deps;activeOrgOperations=new Set;writing=new wr;dmlTracker=new Et;backupRecords;syncRuns;expiryListener;sweeping;liveTracker;backupsWriting=new Set;maskingKey=Oo(32).toString("hex");saveDialog;get savedTemplates(){return new zt(this.deps.configStore)}findTemplate(e){return kt.find(t=>t.id===e)??this.savedTemplates.load(e)}ruleConfig(e){let t={...e.config};return e.ruleType==="hash"&&(t.hashSalt=this.maskingKey),t}maskingRules(e,t){return t.map(n=>({objectApiName:e,fieldApiName:n.fieldPattern.includes(".")?n.fieldPattern.split(".")[1]:n.fieldPattern,method:n.ruleType,config:this.ruleConfig(n)}))}refuseUnknownTemplate(e,t,n){M(this.deps,e,"dataops:error",t,Xr(n),{code:qr})}setLiveOperationTracker(e){this.liveTracker=e}setSyncRuns(e){this.syncRuns=e}targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;muteLeases={};setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}setMuteOffered(e){this.muteOffered=e}muteOffered=!0;duplicatesSettleMs=Rr;setDuplicatesSettle(e){this.duplicatesSettleMs=e}duplicatesWatchOf(e,t){return vr({query:async n=>e.query(n),serverTime:async()=>(await e.soap.getServerTimestamp()).timestamp},t,{settleMs:this.duplicatesSettleMs})}ownReader(){return this.reader??=import("./chunk-4XZ5YT5O.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(n=>Re(n,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}orgNameOf(e){return It(this.deps.orgManager.getOrg(e),e)}readAct(e,t,n,r,o,i){let a=this.targetAutomation;return Sr({act:n,target:this.orgNameOf(t),objects:r,org:Or(e,d=>new Tr(No).withTimeout("dataops automation",()=>a.read(t,d)),Vt(this.deps.orgManager.getOrg(t))==="production"),accord:o,mayMute:this.muteOffered,muteLeases:this.muteLeases,...i?{voice:i}:{}})}async releaseMute(e,t){if(!e)return;let n=await e.release();for(let r of Ir(n,this.orgNameOf(t)))this.deps.log(`[INFO] ${r}`);return n}async handleAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(rr,e,"dataops:error",this.deps);if(t)try{let n=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),r=await this.readAct(n,t.orgId,t.act,t.objects,t,bt(t)),o=se(this.deps,e,"dataops:automation:response",{...r.answer});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} refusals=${r.answer.refusals.length}`)}catch(n){M(this.deps,"dataops:automation","dataops:error",e,n)}}setExpiryListener(e){this.expiryListener=e}setBackupRecordStore(e){this.backupRecords=e,this.sweeping=this.sweepBackupFiles()}swept(){return this.sweeping??Promise.resolve()}async sweepBackupFiles(e=Date.now()){await this.expireBackups(e);let t=this.backupRecords;if(t)try{let n=new Set(this.backupsWriting);for(let o of this.deps.configStore.getKeysByPrefix("backup:"))n.add(o.slice(7).split(":")[0]);let r=await t.sweep(n,Lo,e);r.length>0&&this.deps.log(`[INFO] Removed ${r.length} backup file(s) whose backup never saved its metadata: `+r.join(", "))}catch(n){this.deps.log("[WARN] the files of backups that never saved their metadata were not removed: "+R(n))}}isWritingTo(e){return this.writing.has(e)}async handle(e){if(!So.has(e.type))return!1;switch(e.type){case"backup:execute":return await this.handleBackup(e),!0;case"backup:list":return this.handleBackupList(e),!0;case"backup:objects":return await this.handleBackupObjects(e),!0;case"backup:export":return await this.handleBackupExport(e),!0;case"backup:delete":return await this.handleBackupDelete(e),!0;case"dataops:rollback":return await this.writing.during(ln(e,"orgId"),()=>this.handleRollback(e)),!0;case"dataops:anonymize":return await this.writing.during(ln(e,"orgId"),()=>this.handleAnonymize(e)),!0;case"dataops:anonymization-templates":return this.handleAnonymizationTemplates(e),!0;case"dataops:quality-scan":return await this.handleQualityScan(e),!0;case"dataops:anonymization-template:save":return this.handleTemplateSave(e),!0;case"dataops:anonymization-template:delete":return this.handleTemplateDelete(e),!0;case"dataops:anonymize:coverage":return await this.handleAnonymizeCoverage(e),!0;case"dataops:anonymize:preview":return await this.handleAnonymizePreview(e),!0;case"dataops:automation":return await this.handleAutomation(e),!0;case"precheck:pii-scan":return await this.handlePIIScan(e),!0;default:return!1}}async selectAllFields(e,t,n){let r=await e.describe(t),o=r.fields.filter(d=>d.type===mr).map(d=>d.name),i=o.length>0&&n&&!await n()?o:[];return{select:r.fields.filter(d=>!i.includes(d.name)).map(d=>d.name).join(", "),notKept:i}}async maskedFields(e,t,n,r=[]){let o=(await e.describe(t)).fields,i=new Map(o.map(l=>[l.name.toLowerCase(),l.name])),a=[],d=[];for(let l of n){let f=i.get(l.fieldApiName.toLowerCase());f!==void 0?a.push({...l,fieldApiName:f}):l.fieldApiName!=="*"&&!d.includes(l.fieldApiName)&&d.push(l.fieldApiName)}let c=Nr({objectApiName:t,fields:o,kept:a,derived:r,detector:this.deps.infraServices?.piiDetector??new kr});if(c&&c.unseen.length>0){let l=await e.describe(lt).then(f=>f.fields,()=>{});for(let f of Pr(c.unseen,l))d.includes(f)||d.push(f)}let p=c?[...a,...c.rules]:a,u=p.map(l=>l.fieldApiName).filter((l,f,h)=>l!=="Id"&&h.indexOf(l)===f),b=c&&u.length>0&&!u.includes(rt);return{rules:p,select:["Id",...u,...b?[rt]:[]].join(", "),missing:d,rulesOf:c?l=>jr(t,l,p,c.personOnly):()=>p}}async countRows(e,t,n,r){let i=(await e.query(`SELECT COUNT() FROM ${t}${Mn(r,n)}`)).totalSize;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`The org did not say how many records ${t} holds.`);return i}async organizationIdOf(e){try{let n=(await mt(e,"SELECT Id FROM Organization"))[0]?.Id;return typeof n=="string"&&$o.test(n)?n:void 0}catch(t){this.deps.log(`[WARN] dataops: the org did not say which org it is: ${R(t)}`);return}}async handleBackup(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(Jn,e,"dataops:error",this.deps);if(!t)return;let n=e.id,r=await this.takeBackup(n,t,e.type);if("error"in r){M(this.deps,"backup:execute","dataops:error",e,r.error),this.endBackupNotTaken(n,r);return}let o=se(this.deps,e,"dataops:backup:response",{operationId:n,status:"completed",objects:r.objects.map(Pn),totalRecords:r.totalRecords,...r.partial?{partial:!0}:{},timestamp:r.timestamp});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}async backupForPipeline(e,t){let n=e.fields?Vo(e.fields):void 0,r=await this.takeBackup(e.operationId,{orgId:e.orgId,objects:e.objects,...n?{fields:n}:{},...e.scanAll?{scanAll:new Set(e.scanAll)}:{},...e.origin?{origin:e.origin}:{},...e.failWhenTruncated===!0?{failWhenTruncated:!0}:{},...e.onConnection?{onConnection:e.onConnection}:{}},e.origin==="checkpoint"?"checkpoint:take":"pipeline:execute",t);if("error"in r){let o=R(r.error);throw this.endBackupNotTaken(e.operationId,r),r.cancelled?new dn(o):r.error instanceof Error?r.error:new Error(o)}return r}endBackupNotTaken(e,t){if(t.cancelled){xe(this.deps,e,{aborted:!0});return}de(this.deps,e,R(t.error),t.retryable,{context:t.context})}async takeBackup(e,t,n,r){let o={module:"dataops",operation:n},i=`backup:${t.orgId}`;if(this.activeOrgOperations.has(i)){let g=`A backup or rollback operation is already running for org ${t.orgId}. Please wait for it to complete.`;return this.deps.log(`[WARN] ${g}`),{error:new Error(g),retryable:!1,context:o}}this.activeOrgOperations.add(i);let a=()=>{},d,c=new AbortController,p=()=>c.abort();r?.aborted&&c.abort(),r?.addEventListener("abort",p,{once:!0});let u=this.backupCap(),b=this.backupWriter(e);this.backupsWriting.add(e);let l=[],f,h,w,v=(g,$,O,B)=>{Ct(this.deps,e,g,$,O,B),w?.progress(g,$,O,B)};try{if(this.dmlTracker.isDuplicate(e))return this.deps.log(`[WARN] Duplicate backup operation detected: ${e}`),{error:new Error(`Duplicate operation: ${e}`),retryable:!1,context:o};this.dmlTracker.register(e,"backup","insert",t.objects.length);let g=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager);h=g,t.onConnection?.(g);let $=gr(async E=>(await g.query(E)).records),O=this.deps.orgManager.getOrg(t.orgId),B=yn(O?.orgType==="Sandbox"||O?.orgType==="Scratch"),Y=kn(B).defaultQueryLimit,K=`Backup ${t.objects.length} object(s)`;jt(this.deps,e,"dataops",K),this.deps.infraServices?.backgroundRegistry?.register(e,"dataops",K,new Promise((E,S)=>{a=j=>{j===void 0?E():S(j instanceof Error?j:new Error(String(j)))}}),c),w=xt(this.liveTracker,e,"dataops",K,t.objects.length);for(let E of t.objects){if(c.signal.aborted)throw new it;let S=De(E);o.objectName=S;let j={objectApiName:E,recordCount:0,truncated:!1};f=j,await this.readIntoBackup(g,S,j,b,{pageSize:Y,cap:u,select:t.fields?.get(S),where:t.wheres?.get(S),scanAll:t.scanAll?.has(S)===!0,...t.origin==="checkpoint"?{stamp:Mo}:{},whole:t.failWhenTruncated===!0,viewsEncrypted:$},c.signal,()=>{let q=Math.max(1,Math.min(j.orgCount??u,u));v(Math.round((l.length+j.recordCount/q)/t.objects.length*100),l.length,t.objects.length,`Reading ${E} (${j.recordCount} of ${q} records)`)}),f=void 0,l.push(j),j.stoppedAt==="cap"&&this.deps.log(`[WARN] backup of ${S} stopped at the cap of ${u} record(s): the object holds ${j.orgCount??"more"}.`),v(Math.round(l.length/t.objects.length*100),l.length,t.objects.length,`Exported ${E} (${j.recordCount} records)`)}let F=await this.organizationIdOf(g);if(c.signal.aborted)throw new it;let P=this.saveBackupMeta({operationId:e,orgId:t.orgId,organizationId:F,cap:u,...t.origin?{origin:t.origin}:{}},l,b,!1);return this.pruneAfterBackup(t.orgId),xe(this.deps,e,{objects:l.map(E=>({objectApiName:E.objectApiName,recordCount:E.recordCount})),totalRecords:P.totalRecords,...P.partial?{status:"partial"}:{}}),this.dmlTracker.markCompleted(e),P.partial?w?.partial():w?.complete(),{operationId:e,objects:l,totalRecords:P.totalRecords,partial:P.partial,timestamp:P.timestamp}}catch(g){this.dmlTracker.markFailed(e);let $=g instanceof it,O=$||g instanceof wt||t.failWhenTruncated===!0?void 0:await this.keepFailedBackup({operationId:e,orgId:t.orgId,cap:u,...t.origin?{origin:t.origin}:{}},h,{taken:l,reading:f,planned:t.objects},b);O===void 0&&await b.discard().catch(K=>{this.deps.log(`[WARN] backup ${e}: what it wrote before it stopped was not removed: `+R(K))});let B=O===void 0?g:new Error(`${R(g)} \u2014 the backup keeps the ${O.totalRecords} record(s) read before it stopped, listed as partial: ${$n(O.objects)}.`);d=B,$&&this.deps.infraServices?.backgroundRegistry?.abort(e),$?w?.cancel():w?.fail(R(B));let Y=!(g instanceof at)||g.retryable;return{error:B,retryable:Y,context:o,cancelled:$}}finally{r?.removeEventListener("abort",p),a(d),this.activeOrgOperations.delete(i),this.backupsWriting.delete(e)}}backupCap(){let e=this.deps.services?.getSandforgeSetting?.("backup.maxRecordsPerObject",_r);return typeof e!="number"||!Number.isFinite(e)?_r:Math.min(zo,Math.max(Eo,Math.floor(e)))}backupWriter(e){let t=this.backupRecords;if(t){let r=new Set;return{begin:async o=>{r.add(o),await t.begin(e,o).catch(i=>{throw new wt(i)})},append:async(o,i)=>{await t.append(e,o,i).catch(a=>{throw new wt(a)})},keep:()=>{},discard:async()=>{for(let o of r)await t.delete(e,o)}}}let n=new Map;return{begin:async r=>{n.set(r,[])},append:async(r,o)=>{n.get(r)?.push(...o)},keep:()=>{for(let[r,o]of n)this.deps.configStore.set(`backup:${e}:${r}`,o,"backups")},discard:async()=>{n.clear()}}}async readIntoBackup(e,t,n,r,o,i,a){let d=o.scanAll===!0,c={headers:{"Sforce-Query-Options":`batchSize=${o.pageSize}`},maxFetch:1e4,autoFetch:!1,scanAll:d,responseTarget:"QueryResult"},p=o.select;if(p===void 0){let v=await this.selectAllFields(e,t,o.viewsEncrypted);p=v.select,v.notKept.length>0&&(n.notKept=v.notKept)}let u=d?Qo(o.where):o.where,b=`SELECT ${p} FROM ${t}${Mn(u,void 0)}`,l=o.stamp??Gn(b)?.stamp,f=qn(b,l===void 0?void 0:["Id",l]),h=d||o.whole===!0?v=>Jo(e,v,d,t):v=>mt(e,v),w=await e.query(f?.first??b,c);if(Be(e.limitInfo,`dataops:backup query ${t}`),typeof w.totalSize=="number"&&Number.isInteger(w.totalSize)&&(n.orgCount=w.totalSize),o.whole===!0&&n.orgCount!==void 0&&n.orgCount>o.cap)throw no(t,n.orgCount,o.cap);for(await r.begin(n.objectApiName);;){let v=o.cap-n.recordCount,g=w.records.length>v,$=g?w.records.slice(0,v):w.records,O=$;f&&l!==void 0?O=await Qn($,f,h,{stamp:l,...d?{idsWhere:jn}:{}}):f&&await Xn($,f,h);let B=w.done?void 0:w.nextRecordsUrl;if(o.whole===!0&&!w.done&&B===void 0)throw new at(io(t,n.recordCount+O.length),!0);let Y=g||B!==void 0&&n.recordCount+O.length>=o.cap;if(Y&&o.whole===!0)throw no(t,n.orgCount,o.cap);if(await r.append(n.objectApiName,O),n.recordCount+=O.length,Y){n.truncated=!0,n.stoppedAt="cap";return}if(B===void 0)return;if(a(),i.aborted)throw new it;w=await e.queryMore(B,c),Be(e.limitInfo,`dataops:backup query ${t}`)}}saveBackupMeta(e,t,n,r){let o={operationId:e.operationId,orgId:e.orgId,...e.organizationId!==void 0?{organizationId:e.organizationId}:{},...e.origin!==void 0?{origin:e.origin}:{},objects:t.map(Pn),partial:t.some(i=>i.truncated),...r?{status:"failed"}:{},cap:e.cap,timestamp:new Date().toISOString(),totalRecords:t.reduce((i,a)=>i+a.recordCount,0)};return this.deps.configStore.set(`backup:${e.operationId}`,o,"backups"),n.keep(),o}async keepFailedBackup(e,t,n,r){let{taken:o,reading:i}=n,a=i?[...o,{...i,truncated:!0,stoppedAt:"failure"}]:[...o],d=new Set(a.map(u=>u.objectApiName.toLowerCase())),c=n.planned.filter(u=>!d.has(u.toLowerCase())).map(u=>({objectApiName:u,recordCount:0,truncated:!0,stoppedAt:"not_reached"})),p=[...a,...c];if(!p.every(u=>u.recordCount===0))try{let u=t?await this.organizationIdOf(t):void 0,b=this.saveBackupMeta({...e,organizationId:u},p,r,!0);return this.pruneAfterBackup(e.orgId),{...b,objects:p}}catch(u){this.deps.log(`[WARN] backup ${e.operationId}: the rows read before it failed were not kept: `+R(u));try{this.deps.configStore.delete(`backup:${e.operationId}`)}catch{}return}}async expireBackups(e){let t=Ar(this.deps.services);if(t<=0)return;let n=e-t*Do;try{let r=this.retentionSince(e);for(let o of this.backupMetaKeys()){let i=this.deps.configStore.get(o),a=Date.parse(i?.timestamp??"");if(!Number.isFinite(a)||a>=n||a<r||i?.origin==="checkpoint"||i?.orgId!==void 0&&this.backupBusy(i.orgId))continue;await this.removeBackup(o);let d=i?.origin==="sync"?` \u2014 the values the Sync run ${i.runId??"(unknown)"} wrote over, which removing that run no longer puts back`:"";this.deps.log(`[INFO] Removed backup ${o}: taken more than ${t} day(s) ago${d}`),this.expiryListener?.({operationId:o.slice(7),days:t,...i?.timestamp!==void 0?{takenAt:i.timestamp}:{},...i?.origin==="sync"?{syncRunId:i.runId??""}:{}})}}catch(r){this.deps.log(`[WARN] the backups past their age were not removed: ${R(r)}`)}}retentionSince(e){let t=Date.parse(this.deps.configStore.get(Wr)??"");return Number.isFinite(t)?t:(this.deps.configStore.set(Wr,new Date(e).toISOString()),e)}backupMetaKeys(){return this.deps.configStore.getKeysByPrefix("backup:").filter(e=>!e.slice(7).includes(":"))}backupBusy(e){return this.activeOrgOperations.has(`backup:${e}`)}async removeBackup(e){let n=this.deps.configStore.get(e)?.objects??[];for(let o of n)this.deps.configStore.delete(`${e}:${o.objectApiName}`);this.deps.configStore.delete(e);let r=e.slice(7);for(let o of n)await this.backupRecords?.delete(r,o.objectApiName)}async handleBackupDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(tr,e,"dataops:error",this.deps);if(!t)return;if(this.backupBusy(t.orgId)){M(this.deps,"backup:delete","dataops:error",e,new Error(`A backup or rollback operation is already running for org ${t.orgId}. Delete its backups once it has ended.`),{code:xo});return}let n=t.operationIds?new Set(t.operationIds):void 0,r=[];try{for(let i of this.backupMetaKeys()){let a=this.deps.configStore.get(i);if(a?.orgId!==t.orgId)continue;let d=a.operationId??i.slice(7);n&&!n.has(d)||(await this.removeBackup(i),r.push(d))}}catch(i){M(this.deps,"backup:delete","dataops:error",e,i);return}this.deps.log(`[INFO] Deleted ${r.length} backup(s) of org ${t.orgId}`);let o=se(this.deps,e,"backup:delete:result",{orgId:t.orgId,deleted:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} deleted=${r.length}`)}pruneAfterBackup(e){try{this.pruneBackups(e)}catch(t){this.deps.log(`[WARN] backup retention failed after the snapshot was written: ${R(t)}`)}this.sweepBackupFiles()}handleBackupList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(Zn,e,"dataops:error",this.deps);if(!t)return;let n=[];for(let o of this.deps.configStore.getKeysByPrefix("backup:")){if(o.slice(7).includes(":"))continue;let i=this.deps.configStore.get(o);!i||i.orgId!==t.orgId||n.push({operationId:i.operationId??o.slice(7),orgId:i.orgId,timestamp:i.timestamp??"",totalRecords:i.totalRecords??0,totalSize:0,status:i.status==="failed"?"failed":"completed",objectResults:(i.objects??[]).map(Pn),...i.partial?{partial:!0}:{},...i.origin==="sync"?{origin:"sync"}:{}})}n.sort((o,i)=>i.timestamp.localeCompare(o.timestamp));let r=se(this.deps,e,"backup:list:result",{backups:n});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} count=${n.length}`)}async handleBackupExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(er,e,"dataops:error",this.deps);if(!t)return;let n=`backup:${t.operationId}`,r=this.deps.configStore.get(n);if(!r||r.orgId!==t.orgId){M(this.deps,"backup:export","dataops:error",e,new Error(`Backup not found: ${t.operationId}`),{code:"BACKUP_NOT_FOUND"});return}let o=await this.saveDialog.saveStream(`sandforge-backup-${t.operationId}.json`,a=>this.writeBackupDocument(t,r,a),["json"]);if(o.status==="error"){M(this.deps,"backup:export","dataops:error",e,new Error(o.message));return}let i=se(this.deps,e,"backup:export:result",o.status==="saved"?{operationId:t.operationId,status:"saved",path:o.path,objects:o.result}:{operationId:t.operationId,status:"cancelled"});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} ${o.status}`)}async writeBackupDocument(e,t,n){let{operationId:r}=e,i=[["sandforgeBackupVersion",1],["operationId",r],["orgId",e.orgId],["timestamp",t.timestamp??""],["totalRecords",t.totalRecords??0]].map(([d,c])=>` "${d}": ${JSON.stringify(c)},
|
|
8
|
-
`);await n(`{
|
|
9
|
-
${i.join("")} "objects": {`);let a=[];for(let{objectApiName:d}of t.objects??[]){if(a.some(p=>p.objectApiName===d))continue;await n(`${a.length>0?",":""}
|
|
10
|
-
${JSON.stringify(d)}: [`);let c=0;for await(let p of await this.backupBatches(r,d))p.length!==0&&(await n(p.map((u,b)=>`${c+b>0?",":""}
|
|
11
|
-
${JSON.stringify(u)}`).join("")),c+=p.length);await n(c>0?`
|
|
12
|
-
]`:"]"),a.push({objectApiName:d,records:c})}return await n(`${a.length>0?`
|
|
13
|
-
`:""}}
|
|
14
|
-
}
|
|
15
|
-
`),a}async backupBatches(e,t){let n=await this.backupRecords?.batches(e,t,st);if(n)return n;let r=this.deps.configStore.get(`backup:${e}:${t}`),o=Array.isArray(r)?r:[];return{async*[Symbol.asyncIterator](){for(let i=0;i<o.length;i+=st)yield o.slice(i,i+st)}}}async firstBackupRecord(e,t,n){let r=await this.backupBatches(e,t),o=n.origin==="sync"?An(r,st).batches:r;for await(let i of o)if(i[0]!==void 0)return i[0]}pruneBackups(e){let t=this.deps.services?.getSandforgeSetting?.("backup.maxCount",10)??10,n=[];for(let r of this.deps.configStore.getKeysByPrefix("backup:")){if(r.slice(7).includes(":"))continue;let i=this.deps.configStore.get(r);i?.orgId===e&&i.origin!=="sync"&&i.origin!=="checkpoint"&&n.push({key:r,timestamp:i.timestamp??""})}if(!(n.length<=t)){n.sort((r,o)=>r.timestamp.localeCompare(o.timestamp));for(let{key:r}of n.slice(0,n.length-t))this.removeBackup(r),this.deps.log(`[INFO] Pruned backup ${r} (retention: ${t} per org)`)}}async undeleteFromRecycleBin(e,t,n){let r=[];for await(let i of n){let a=i.map(c=>c.Id).filter(c=>typeof c=="string");if(a.length===0)continue;let d=a.map(c=>`'${Kn(c)}'`).join(", ");try{let c=await e.query(`SELECT Id FROM ${t} WHERE Id IN (${d}) AND IsDeleted = true`,{scanAll:!0});r.push(...c.records.map(p=>p.Id))}catch(c){return this.deps.log(`[WARN] Rollback on ${t}: could not look for deleted records \u2014 ${R(c)}`),{undeleted:0}}}let o=0;for(let i=0;i<r.length;i+=200){let a=await e.soap.undelete(r.slice(i,i+200));o+=a.filter(d=>d.success).length}return{undeleted:o}}refuseWithoutGuard(e,t,n,r){oe(this.deps,{...r,outcome:"stopped",source:void 0,code:ft.code}),e(new Error(ft.message),{code:ft.code}),de(this.deps,t,ft.message,!1,{context:n,authored:!0})}async handleRollback(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(nr,e,"dataops:error",this.deps);if(!t)return;let n=t,r=e.id,o={module:"dataops",operation:e.type},i=`backup:${n.orgId}`;if(this.activeOrgOperations.has(i)){let h=`A backup or rollback operation is already running for org ${n.orgId}. Please wait for it to complete.`;this.deps.log(`[WARN] ${h}`),M(this.deps,"dataops:rollback","dataops:error",e,new Error(h)),de(this.deps,r,h,!1,{context:o,authored:!0});return}this.activeOrgOperations.add(i);let a,d=[],c=!1,p=new AbortController,u=()=>{},b,l,f;try{if(this.dmlTracker.isDuplicate(r)){this.deps.log(`[WARN] Duplicate rollback operation detected: ${r}`),M(this.deps,"dataops:rollback","dataops:error",e,new Error(`Duplicate operation: ${r}`)),de(this.deps,r,`Duplicate operation: ${r}`,!1,{context:o,authored:!0});return}this.dmlTracker.register(r,"rollback","upsert",0);let h=await Re(n.orgId,this.deps.orgRegistry,this.deps.orgManager),w=new on(async k=>{let I=await h.describe(k);return oo(I)}),v=`backup:${n.operationId}`,g=this.deps.configStore.get(v);if(!g)throw new Error(`No backup found for operation ${n.operationId}. Cannot rollback.`);if(g.orgId!==n.orgId)throw new Error(`Backup ${n.operationId} was taken from org ${g.orgId} and cannot be restored into org ${n.orgId}.`);a={action:"backup_restore",module:"dataops",operationId:r,orgId:n.orgId,outcome:"failure",source:{origin:"backup",label:g.timestamp?.slice(0,16).replace("T"," ")??n.operationId}};let $=this.deps.infraServices?.productionGuard;if(!$){this.refuseWithoutGuard((k,I)=>M(this.deps,"dataops:rollback","dataops:error",e,k,I),r,o,a);return}let O=[];for(let k of g.objects){let I=await this.firstBackupRecord(n.operationId,k.objectApiName,g);if(I===void 0)continue;let y=De(k.objectApiName);if(!(await w.checkCrudPermission(y,"upsert")).allowed){O.push({objectApiName:y,operation:"upsert",deniedFields:[]});continue}let{denied:he}=await w.partitionWritableFields(y,"upsert",Object.keys(I).filter(me=>me!=="attributes"));he.length>0&&O.push({objectApiName:y,operation:"upsert",deniedFields:he})}if(O.length>0){let k=rn(O);this.deps.log(`[WARN] CRUD/FLS check failed for rollback ${r}: ${k}`),oe(this.deps,{...a,outcome:"stopped",source:void 0,code:gt}),M(this.deps,"dataops:rollback","dataops:error",e,new Error(k),{code:gt}),de(this.deps,r,k,!1,{context:o,authored:!0});return}let B=(k,I,y,Ce=[])=>{oe(this.deps,{...y,outcome:"stopped",source:void 0,code:k}),M(this.deps,"dataops:rollback","dataops:error",e,new Error(I),{code:k,...bn({alsoRefused:Ce})}),de(this.deps,r,I,!1,{context:o,authored:!0})},Y=await this.readAct(h,n.orgId,"restore",g.objects.map(k=>({objectApiName:k.objectApiName,records:k.recordCount})),n,bt(n)),K=hn(Y.answer);if(K){B(K.code,K.message,a,K.alsoRefused);return}f=this.duplicatesWatchOf(h,fn(Y.answer.automation,g.objects.filter(k=>k.recordCount>0).map(k=>k.objectApiName)));let F=this.deps.orgManager.getOrg(n.orgId),P={orgId:n.orgId,orgTier:In(F),operation:"upsert",objectName:g.objects.map(k=>k.objectApiName).join(", ")||"RollbackData",recordCount:g.totalRecords??0,module:"dataops"},{check:E,decision:S}=await pn($,P);if(a.guard=S,(S==="refused"||S==="declined")&&oe(this.deps,{...a,outcome:"stopped",source:void 0}),S==="refused")throw Yt(E.blockedReason??E.impactSummary);if(S==="declined"){let k="Operation cancelled by user (confirmation declined).";M(this.deps,"dataops:rollback","dataops:error",e,new Error(k),{code:Zt.declined}),de(this.deps,r,k,!1,{context:o,authored:!0});return}if(g.organizationId!==void 0){let k=await this.organizationIdOf(h);if(k!==void 0&&!jo(g.organizationId,k)){let I=It(F,n.orgId),y=this.deps.infraServices?.confirmRestoreIntoReplacedOrg;if(!(y?await y({alias:I,backedUpFrom:g.organizationId,now:k}):!1)){oe(this.deps,{...a,outcome:"stopped",source:void 0,code:Fr});let he=`Restore not run: ${I} answers as org ${k}, not as org ${g.organizationId}, which backup ${n.operationId} was taken from, `+(y?"and the restore into the org it is now was not confirmed.":"and nothing here can ask whether to restore into the org it is now.");M(this.deps,"dataops:rollback","dataops:error",e,new Error(he),{code:Fr}),de(this.deps,r,he,!1,{context:o,authored:!0});return}}}let j=await gn(Y,r,n.acceptEmails===!0,bt(n));if("refused"in j){B(j.refused.code,j.refused.message,a);return}l=j.held,jt(this.deps,r,"dataops",`Rollback ${g.objects.length} object(s)`),c=!0,this.deps.infraServices?.backgroundRegistry?.register(r,"dataops",`Rollback ${g.objects.length} object(s)`,new Promise((k,I)=>{u=y=>{y===void 0?k():I(y instanceof Error?y:new Error(String(y)))}}),p),b=xt(this.liveTracker,r,"dataops",`Rollback ${g.objects.length} object(s)`,g.objects.length);let q=!1,L=0,fe=0,Te=0,Qe=[],Ve=new Map,T=g.origin==="sync"&&n.includeChanged!==!0,D=Number.NEGATIVE_INFINITY,ee=!1;if(T){let k=g.runId!==void 0?await this.syncRuns?.get(g.runId).catch(y=>{this.deps.log(`[WARN] Rollback: the Sync run of backup ${n.operationId} could not be read \u2014 ${R(y)}`)}):void 0,I=k?fr(k):void 0;ee=I===void 0,D=await lr({serverTime:async()=>(await h.soap.getServerTimestamp()).timestamp},I)}let X=[];for(let k=0;k<g.objects.length;k++){if(p.signal.aborted){q=!0;break}let I=g.objects[k],y=De(I.objectApiName);o.objectName=y;let Ce=await this.backupBatches(n.operationId,I.objectApiName),he=g.origin==="sync"?An(Ce,st):void 0,me=he?.batches??Ce,Ie;for await(let _ of me)if(Ie=_[0],Ie!==void 0)break;if(T&&Ie!==void 0){let _=[];for await(let ie of me)for(let te of ie)typeof te.Id=="string"&&_.push(te.Id);let ue=await Mr({query:async(ie,te)=>({records:(await h.query(ie,te)).records})},y,_,D);ue.size>0&&(X.push({objectApiName:y,count:ue.size}),me=Er(me,ue))}if(Ie===void 0){Ve.set(I.objectApiName,0),this.deps.log(`[WARN] No backup records for ${I.objectApiName}, skipping.`);continue}let Ut=Object.keys(Ie).filter(_=>_!=="attributes"),{skipped:Ht}=await w.partitionWritableFields(y,"upsert",Ut),Me=new Set(Ht.filter(_=>_.toLowerCase()!=="id").map(_=>_.toLowerCase()));Me.size>0&&this.deps.log(`[INFO] Rollback on ${y}: ${Me.size} non-writable field(s) excluded from the payload \u2014 ${[...Me].sort().join(", ")}`);let vt=await this.undeleteFromRecycleBin(h,y,me);vt.undeleted>0&&this.deps.log(`[INFO] Rollback on ${y}: ${vt.undeleted} record(s) brought back from the recycle bin`),o.batchSize=st;let Ee=0,Ye=0,G=0,We=0;for await(let _ of me){if(p.signal.aborted){q=!0;break}We+=_.length;let ue=_.map(J=>{let we=y===W?Nt(J,!1):void 0,ze={};for(let[tt,Kt]of Object.entries(J))tt!=="attributes"&&(Me.has(tt.toLowerCase())||we!==void 0&&Ot(W,tt,we)||(ze[tt]=Kt));return ze}),ie=ue;if(n.rewriteAll!==!0){let J=await Cr({query:async we=>{let ze=await h.query(we);return{totalSize:ze.totalSize,records:ze.records}}},y,ue);J.unread!==void 0&&this.deps.log(`[WARN] Rollback on ${y}: the org's values could not be read, so ${ue.length} row(s) are written back without comparing \u2014 ${J.unread}`),ie=J.write,G+=J.unchanged}if(ie.length===0)continue;f.beforeWrite(y);let te;try{te=await h.sobject(y).upsert(ie,"Id",{headers:Qt()})}catch(J){throw un(J)==="may-have-written"&&f.wrote(y,ie.map(we=>we.Id)),J}let et=Array.isArray(te)?te:[te];f.wrote(y,et.flatMap((J,we)=>J.success?[ie[we]?.Id]:[]));for(let J of et){if(J.success){Ee++;continue}Ye++,Ur(Qe,y,J.errors)}}if(Be(h.limitInfo,`dataops:rollback upsert ${y}`),Ve.set(I.objectApiName,he&&!q?he.lines():We),L+=Ee,fe+=Ye,Te+=G,d.push({...$t(y),updated:Ee,failed:Ye}),q)break;let ct=`Restored ${y} (${Ee}/${We}${G>0?`, ${G} unchanged`:""})`,Oe=Math.round((k+1)/g.objects.length*100);Ct(this.deps,r,Oe,k+1,g.objects.length,ct),b.progress(Oe,k+1,g.objects.length,ct)}let N=X.reduce((k,I)=>k+I.count,0),ce=Bo(L,fe),V=q&&fe===0||N>0&&ce==="success"?"partial":ce;a&&(c=!1,oe(this.deps,{...a,...q?L+fe>0?{outcome:"cancelled"}:{outcome:"stopped",code:nn}:{outcome:V},objects:d}));let je=await this.releaseMute(l,n.orgId);l=void 0;let ge=await f.read();q?(this.deps.infraServices?.backgroundRegistry?.abort(r),xe(this.deps,r,{aborted:!0,totalRestored:L,totalFailed:fe,totalUnchanged:Te})):xe(this.deps,r,{status:V,totalRestored:L,totalFailed:fe,totalUnchanged:Te}),this.dmlTracker.markCompleted(r),q?b.cancel():V==="failure"?b.fail(`The org refused the ${fe} record(s)`):V==="partial"?b.partial():b.complete();let pe=$n(g.objects,Ve),Je=(q?`Rollback cancelled: ${L} records restored before the cancel; the rest still hold the values they had, and the same restore puts them back`:fe>0?`Rollback ${V}: ${L} restored, ${fe} rejected by the org`:N>0?`Rollback partial: ${L} records restored`:`Rollback completed: ${L} records restored`)+(Te>0?`; ${Te} already held the backup's values and were not written`:"")+(N>0?`; ${N} changed or deleted since the Sync run were left as they are `+(ee?"(the run is no longer kept here, so every record reads as changed since it) ":"")+"unless the restore includes them":""),Ne=ht(ge,this.orgNameOf(n.orgId),"restore"),Ze=pe===""?Je:`${Je}. The backup held only part of the org's records, and the rest were left as they are: ${pe}`,dt=Ne?`${Ze}. ${Ne}`:pe===""?Ze:`${Ze}.`,_e=se(this.deps,e,"dataops:rollback:response",{operationId:n.operationId,status:V,message:dt,totalRestored:L,totalFailed:fe,totalUnchanged:Te,...n.rewriteAll===!0?{rewriteAll:!0}:{},...n.includeChanged===!0?{includeChanged:!0}:{},...N>0?{keptChanged:{total:N,objects:X,...ee?{runNotKept:!0}:{}}}:{},errors:Qe,...pe!==""?{partial:!0}:{},...q?{cancelled:!0}:{},...je?{mutedAutomation:je}:{},...ge?{duplicates:ge}:{}});this.deps.broker.postToWebview(_e),this.deps.log(`[TX] ${_e.type} id=${_e.id} status=${V}`),(fe>0||pe!==""||q||N>0||mn(ge))&&tn(this.deps,V==="failure"?"error":"warning","Restore",`${dt}${Qe[0]?` \u2014 e.g. ${Qe[0].message}`:""}`)}catch(h){this.dmlTracker.markFailed(r),await this.releaseMute(l,n.orgId),l=void 0;let w=await f?.read(),v=ht(w,this.orgNameOf(n.orgId),"restore");M(this.deps,"dataops:rollback","dataops:error",e,v?new Error(`${R(h)} ${v}`):h,{code:en(h),...w?{extraPayload:{duplicates:w}}:{}}),de(this.deps,r,R(h),!0,{context:o}),b?.fail(R(h))}finally{await this.releaseMute(l,n.orgId),this.activeOrgOperations.delete(i),u(),c&&a&&oe(this.deps,{...a,outcome:"failure",objects:d})}}async snapshotBeforeMasking(e,t,n,r,o){let i=new Map,a=new Map;try{for(let p of r){if(p.tally.total===0)continue;p.where!==void 0&&a.set(p.tally.objectApiName,p.where);let{select:u}=await this.maskedFields(e,p.tally.objectApiName,this.maskingRules(p.objectName,p.objectRules),this.maskingRules(p.objectName,p.personRules));u!=="Id"&&i.set(p.tally.objectApiName,u)}}catch(p){return{refused:`No snapshot was taken, so nothing was masked: ${R(p)}`,retryable:!0}}if(i.size===0)return{};let d=`${t}-snapshot`,c=await this.takeBackup(d,{orgId:n,objects:[...i.keys()],...a.size>0?{wheres:a}:{},fields:i},o.origin,o.stop);return"error"in c?(this.endBackupNotTaken(d,c),{refused:`No snapshot was taken, so nothing was masked: ${R(c.error)}`,retryable:c.retryable&&c.cancelled!==!0}):c.partial?{refused:`Snapshot ${d} holds only part of the records the run would mask, so nothing was masked: a restore could not put back the rest (${$n(c.objects)}). Raise sandforge.backup.maxRecordsPerObject, or narrow the run.`,retryable:!1}:{taken:{operationId:d,totalRecords:c.totalRecords}}}async maskingNotCovered(e,t,n,r){if(r.length===0)return{code:ve.masksNothing,message:`The template "${t.name}" has no rule for ${n.join(", ")}: the run would mask nothing. Choose an object its rules name, or another template. Nothing was masked.`,gaps:{fieldsNotFound:[],objectsNotCovered:[...n]}};let o=[],i=[];for(let d of r){if(d.tally.total===0)continue;let{objectApiName:c}=d.tally,{rules:p,missing:u}=await this.maskedFields(e,c,this.maskingRules(d.objectName,d.objectRules),this.maskingRules(d.objectName,d.personRules));o.push(...u.map(b=>({objectApiName:c,fieldApiName:b}))),p.length===0&&i.push(c)}let a={fieldsNotFound:o,objectsNotCovered:i};if(o.length>0){let d=o.map(c=>`${c.objectApiName}.${c.fieldApiName}`).join(", ");return{code:ve.fieldsUnseen,message:`The template "${t.name}" masks ${d}, which the org does not show the user SandForge connects as: it has no such field, or field-level security hides it. `+(i.length>0?`No field of ${i.join(", ")} can be masked. `:"")+"A run masks every field its template names, or nothing: give that user read and edit access to the field, or take the field out of the template. Nothing was masked.",gaps:a}}if(i.length>0)return{code:ve.masksNothing,message:`The template "${t.name}" masks no field of ${i.join(", ")} in this org: the run would write nothing over its records. Choose an object its rules name, or another template. Nothing was masked.`,gaps:a}}async anonymizeForPipeline(e,t){let n=this.deps.orgManager.getOrg(e.orgId);if(!n)throw Fe(ve.orgUnknown,`The org the masking writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was masked.`);let r=xr(In(n),e.answer,It(n,e.orgId));if(r)throw r;let o=Br(e,f=>this.findTemplate(f)!==void 0);if("refusal"in o)throw o.refusal;let i=crypto.randomUUID(),a,d,c,p={origin:"pipeline:execute",pipeline:e.pipeline,accord:e.accord??{},voice:"step",muted:f=>{c=f},refused:(f,h)=>{a??={err:f,...h},this.deps.log(`[ERR] dataops:anonymize ${i} for the pipeline "${e.pipeline.name}": `+R(f))},ended:f=>{d=f}};await this.writing.during(e.orgId,()=>yr(e.answer,()=>this.mask(o.asked,i,p,t)));let u=a,b=c;if(u){let f=R(u.err),h=u.err,w=u.code??(typeof h?.code=="string"?h.code:void 0),v=u.extraPayload?.snapshot,g={...w!==void 0?{code:w}:{},...v!==void 0?{snapshot:v}:{},...b?{mutedAutomation:b}:{}};throw Object.assign(w===Pt?new dn(f):new Error(f),g)}let l=d;if(l===void 0)throw new Error("The masking run ended without a result.");return{operationId:i,result:b?{...l,mutedAutomation:b}:l}}async handleAnonymize(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(Mt,e,"dataops:error",this.deps);if(!t)return;let n=bt(t);await this.mask(t,e.id,{...this.pageMaskingReplies(e),accord:{acceptAutomation:t.acceptAutomation===!0,acceptEmails:t.acceptEmails===!0,muteAutomation:t.muteAutomation===!0},...n?{voice:n}:{}})}pageMaskingReplies(e){return{origin:e.type,refused:(t,n)=>M(this.deps,"dataops:anonymize","dataops:error",e,t,n),ended:t=>{let n=se(this.deps,e,"dataops:anonymize:response",t);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} status=${t.status}`),(t.recordsNotMasked>0||mn(t.duplicates))&&tn(this.deps,t.status==="failure"?"error":"warning","Anonymize",`${t.message}${t.errors[0]?` \u2014 e.g. ${t.errors[0].message}`:""}`)}}}async mask(e,t,n,r){let o,i={},a,d=async()=>(a??={released:await this.releaseMute(o,e.orgId)},a.released),c={...n,refused:(T,D)=>{if(!o){n.refused(T,D);return}i.answer??=ee=>n.refused(T,ee?{...D,extraPayload:{...D.extraPayload,mutedAutomation:ee}}:D)},ended:T=>{if(!o){n.ended(T);return}i.answer??=D=>n.ended(D?{...T,mutedAutomation:D}:T)}},p={module:"dataops",operation:c.origin},u=this.findTemplate(e.templateId),b=Bt(e,u),l={action:"anonymize_execute",module:"dataops",operationId:t,orgId:e.orgId,outcome:"failure",source:{origin:"org",orgId:e.orgId}},f=[],h=[],w=En(e),v=u?Lt(u.rules,b,w):"",g=!1,$=!1,O=!1,B=!1,Y,K,F=new AbortController,P=()=>{},E,S,j,q=async()=>j?.read(),L=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(t);L?.signal.addEventListener("abort",()=>F.abort(),{once:!0});let fe=()=>F.abort();r?.aborted&&F.abort(),r?.addEventListener("abort",fe,{once:!0});let Te=async()=>{oe(this.deps,{...l,outcome:"stopped",source:void 0,code:Pt});let T="The masking run was cancelled before it wrote anything.";c.refused(new Error(T),{code:Pt,...K?{extraPayload:{snapshot:K}}:{}}),await d(),xe(this.deps,t,{aborted:!0})},Qe=(T,D,ee)=>{E=T;let X=R(T),N=Rt(f),ce=g&&N.recordsNotMasked>0,V=ht(ee,this.orgNameOf(e.orgId)),je={...g?{...N,objects:Yr(f)}:{},...K?{snapshot:K}:{},...ee?{duplicates:ee}:{}},ge=ce?`${X} \u2014 ${N.recordsProcessed} masked before it stopped; ${N.recordsNotMasked} still hold their original values (${Zr(f)}).`:X;c.refused(ce||V?new Error(V?`${ge} ${V}`:ge):T,{code:en(T),extraPayload:je}),de(this.deps,t,X,D,{context:p,extraPayload:je}),S?.fail(X)},Ve=()=>{B=!0;let T=new ot(this.deps.configStore),{recordsNotMasked:D}=Rt(f),ee=f.reduce((X,N)=>X+N.masked+N.nothingToMask+N.refused+N.unanswered,0);try{if(D===0)return T.clear(e.orgId,e.templateId),!1;if(ee===0)return T.load(e.orgId,e.templateId,v)!==void 0;let X=h.map(N=>N.progress);return yt(X)>qe?(this.deps.log(`[WARN] dataops:anonymize ${t}: the org refused ${yt(X)} record(s), more than a resume retries (${qe}): only a full run masks them.`),T.clear(e.orgId,e.templateId),!1):(T.save({id:t,orgId:e.orgId,templateId:e.templateId,fingerprint:v,savedAt:new Date().toISOString(),objects:X,...Y?{namesGiven:Y.namesGiven()}:{}}),!0)}catch(X){return this.deps.log(`[WARN] dataops:anonymize ${t}: where the run stopped was not kept: `+R(X)),!1}};try{let T=this.deps.infraServices?.productionGuard;if(!T){this.refuseWithoutGuard((m,C)=>c.refused(m,C),t,p,l);return}if(!u){c.refused(Xr(e.templateId),{code:qr});return}let D=At(e,u,W)?Bt(e,u,!0):void 0,ee=D?[v,Lt(u.rules,D,w)]:[v],X=()=>c.refused(new Error("There is nothing to resume: the run has finished since, another run of this template has stopped since, or its rules have changed. Apply masks every record of its objects."),{code:Wo}),N;if(e.resumeFrom!==void 0){let m=new ot(this.deps.configStore);if(N=ee.map(C=>m.load(e.orgId,e.templateId,C)).find(C=>C?.id===e.resumeFrom),!N){X();return}}let ce=await Re(e.orgId,this.deps.orgRegistry,this.deps.orgManager),V=Hr(ce);if(D&&await Nn(V,this.deps.log)&&(b=D,v=ee[1]),N&&N.fingerprint!==v){X();return}let je,ge=m=>{let C=Be(ce.limitInfo,m);C&&C.usagePercent>=_o&&(je??=C)},pe=()=>je;for(let m of b){let C=Ft(u,m),ae=Cn(u,m);if(C.length===0&&ae.length===0)continue;let be=De(m),U=Sn(e,u,m);p.objectName=be;let A=N?.objects.find(Ue=>Ue.objectApiName===be),x={objectApiName:be,done:A?.done??!1,...A?.afterId!==void 0?{afterId:A.afterId}:{},refused:[...A?.refused??[]],...A?.unconfirmed?.length?{unconfirmed:[...A.unconfirmed]}:{}},Pe=0;if(!x.done){try{Pe=await this.countRows(ce,be,x.afterId,U)}catch(Ue){throw oe(this.deps,{...l,outcome:"failure",source:void 0,objects:[$t(be)],code:Ho,details:{reason:Go(Ue)}}),Ue}ge(`dataops:anonymize count ${be}`),Pe===0&&(x.done=!0)}let Tt=Pe+x.refused.length+(x.unconfirmed?.length??0),pt={objectApiName:be,total:Tt,masked:0,nothingToMask:0,refused:0,unanswered:0,done:Tt===0};f.push(pt),h.push({objectName:m,...U!==void 0?{where:U}:{},objectRules:C,personRules:ae,tally:pt,progress:x})}let Je=f.reduce((m,C)=>m+C.total,0),Ne=await this.maskingNotCovered(V,u,b,h);if(Ne){oe(this.deps,{...l,outcome:"stopped",source:void 0,code:Ne.code}),c.refused(new Error(Ne.message),{code:Ne.code,extraPayload:{...Ne.gaps}}),de(this.deps,t,Ne.message,!1,{context:p,authored:!0});return}let Ze=await Kr(V,h.filter(m=>m.tally.total>0).map(m=>({objectApiName:m.tally.objectApiName,rules:[...m.objectRules,...m.personRules]})));if(Ze.length>0){let m=rn(Ze);this.deps.log(`[WARN] CRUD/FLS check failed for anonymize ${t}: ${m}`),oe(this.deps,{...l,outcome:"stopped",source:void 0,code:gt}),c.refused(new Error(m),{code:gt}),de(this.deps,t,m,!1,{context:p,authored:!0});return}let dt=(m,C,ae=[])=>{oe(this.deps,{...l,outcome:"stopped",source:void 0,code:m}),c.refused(new Error(C),{code:m,...bn({alsoRefused:ae})}),de(this.deps,t,C,!1,{context:p,authored:!0})},_e=await this.readAct(ce,e.orgId,"masking",f.map(m=>({objectApiName:m.objectApiName,records:m.total})),c.accord,c.voice),k=hn(_e.answer);if(k){dt(k.code,k.message,k.alsoRefused);return}let I=this.duplicatesWatchOf(ce,fn(_e.answer.automation,f.filter(m=>m.total>0).map(m=>m.objectApiName)));j=I;let y=this.deps.orgManager.getOrg(e.orgId),Ce={orgId:e.orgId,orgTier:In(y),operation:"update",objectName:b.join(", ")||"AnonymizeData",recordCount:Je,module:"dataops"},{check:he,decision:me}=await pn(T,Ce);if(l.guard=me,(me==="refused"||me==="declined")&&oe(this.deps,{...l,outcome:"stopped",source:void 0}),me==="refused")throw Yt(he.blockedReason??he.impactSummary);if(me==="declined"){let m="Operation cancelled by user (confirmation declined).";c.refused(new Error(m),{code:Zt.declined}),de(this.deps,t,m,!1,{context:p,authored:!0});return}for(let m of he.warnings)this.deps.log(`[WARN] dataops:anonymize ${t}: ${m}`);if(F.signal.aborted){await Te();return}let Ie=await gn(_e,t,c.accord.acceptEmails===!0,c.voice);if("refused"in Ie){dt(Ie.refused.code,Ie.refused.message);return}o=Ie.held,g=!0;let Ut=yn(y?.orgType==="Sandbox"||y?.orgType==="Scratch"),Ht=kn(Ut).defaultQueryLimit;if(e.snapshot===!0){let m=await this.snapshotBeforeMasking(V,t,e.orgId,h,{origin:c.origin,stop:F.signal});if("refused"in m&&F.signal.aborted){await Te();return}if("refused"in m){oe(this.deps,{...l,outcome:"stopped",source:void 0,code:Qr}),c.refused(new Error(m.refused),{code:Qr}),await d(),de(this.deps,t,m.refused,m.retryable,{context:p,authored:!0});return}if(K=m.taken,F.signal.aborted){await Te();return}}let Me=c.pipeline?`Pipeline anonymization with ${u.name}`:`Anonymizing with ${u.name}`;jt(this.deps,t,"dataops",Me),$=!0,O=!0,this.deps.infraServices?.backgroundRegistry?.register(t,"dataops",Me,new Promise((m,C)=>{P=ae=>{ae===void 0?m():C(ae instanceof Error?ae:new Error(String(ae)))}}),F),S=xt(this.liveTracker,t,"dataops",Me,Je);let{AnonymizationEngine:vt}=await import("./chunk-TLH7AD35.mjs"),Ee=new vt(void 0,this.maskingKey);Y=Ee,N&&!(N.namesGiven!==void 0&&Ee.continueFrom(N.namesGiven))&&this.deps.log(`[INFO] dataops:anonymize ${t}: the run it resumes kept no record of the names it made up, so this one may give again a name or an address that run gave.`);let Ye=[],G=!1,We=m=>m.masked+m.nothingToMask+m.refused,ct=(m,C)=>{let ae=f.reduce((x,Pe)=>x+We(Pe),0),be=Math.max(Je,ae),U=Math.round(ae/be*100),A=`Anonymized ${m} (${We(C)}/${Math.max(C.total,We(C))})`;Ct(this.deps,t,U,ae,be,A),S?.progress(U,ae,be,A)};for(let{objectName:m,where:C,objectRules:ae,personRules:be,tally:U,progress:A}of h){if(U.total===0)continue;if(F.signal.aborted){G=!0;break}if(pe())break;let x=U.objectApiName;p.objectName=x;let{select:Pe,rulesOf:Tt}=await this.maskedFields(V,x,this.maskingRules(m,ae),this.maskingRules(m,be));p.batchSize=Xe;let pt=async(Z,ke,$e)=>{let Le=Z.map(Tt),Ae=Z.map((re,H)=>Ee.anonymize([re],Le[H])[0]),ne=[];Z.forEach((re,H)=>{let z={Id:re.Id};for(let ye of Le[H])cn(re[ye.fieldApiName])&&(z[ye.fieldApiName]=Ae[H][ye.fieldApiName]);Object.keys(z).length>1?ne.push(z):U.nothingToMask++});for(let re=0;re<ne.length;re+=Xe){if(F.signal.aborted)return G=!0,!0;if(pe())return!0;let H=ne.slice(re,re+Xe),z;I.beforeWrite(x);try{z=await ce.sobject(m).update(H,{headers:Qt()})}catch(He){throw un(He)==="may-have-written"&&(U.unanswered+=H.length,$e(H,H.flatMap(Uo)),I.wrote(x,H.map(ut=>ut.Id))),He}ge(`dataops:anonymize update ${x}`);let ye=[],Dn=Array.isArray(z)?z:[z];I.wrote(x,Dn.flatMap((He,ut)=>He.success?[H[ut]?.Id]:[])),Dn.forEach((He,ut)=>{if(He.success){U.masked++;return}U.refused++;let qt=H[ut]?.Id;typeof qt=="string"&&_t.test(qt)&&ye.push(qt),Ur(Ye,x,He.errors)}),ke(H,ye),ct(m,U)}return ne.length===0&&ct(m,U),!1},Ue=A.unconfirmed??[];for(let Z=0;Z<Ue.length;Z+=Xe){if(F.signal.aborted){G=!0;break}if(pe())break;let ke=Ue.slice(Z,Z+Xe),$e=ke.map(z=>`'${z.id}'`).join(", "),Le=await mt(ce,`SELECT ${Pe} FROM ${x} WHERE Id IN (${$e})`);ge(`dataops:anonymize query ${x}`);let Ae=new Map(Le.map(z=>[String(z.Id),z])),ne=[];for(let z of ke){let ye=Ae.get(z.id);ye===void 0?U.total-=1:Tn(ye,z.fields)===z.digest?U.nothingToMask++:ne.push(z.id)}let re=new Set(ke.map(z=>z.id)),H=(A.unconfirmed??[]).filter(z=>!re.has(z.id));H.length>0?A.unconfirmed=H:delete A.unconfirmed,A.refused.push(...ne)}if(G||pe())break;let Ln=[...A.refused];for(let Z=0;Z<Ln.length;Z+=Xe){if(F.signal.aborted){G=!0;break}if(pe())break;let ke=Ln.slice(Z,Z+Xe),$e=await mt(ce,`SELECT ${Pe} FROM ${x} WHERE Id IN (${ke.map(re=>`'${re}'`).join(", ")})`);ge(`dataops:anonymize query ${x}`),U.total-=ke.length-$e.length;let Le=[];if(await pt($e,(re,H)=>Le.push(...H),(re,H)=>{let z=new Set(H.map(ye=>ye.id));A.refused=A.refused.filter(ye=>!z.has(ye)),A.unconfirmed=[...A.unconfirmed??[],...H]}))break;let ne=new Set(ke);A.refused=[...A.refused.filter(re=>!ne.has(re)),...Le]}if(G||pe())break;if(A.done){U.done=!0;continue}let Gt=A.afterId;for(;;){if(F.signal.aborted){G=!0;break}if(pe())break;let Z=await to(ce,x,Pe,Ht,Gt,C);if(ge(`dataops:anonymize query ${x}`),Z.records.length===0){U.done=!0,A.done=!0;break}let ke=Z.truncated?Zo(Z.records,Gt,x):void 0;if(F.signal.aborted){G=!0;break}let $e=Ae=>{let ne=Ae[Ae.length-1]?.Id;typeof ne=="string"&&_t.test(ne)&&(A.afterId=ne)};if(await pt(Z.records,(Ae,ne)=>{A.refused.push(...ne),$e(Ae)},(Ae,ne)=>{A.unconfirmed=[...A.unconfirmed??[],...ne],$e(Ae)}))break;if(ke===void 0){U.done=!0,A.done=!0;break}Gt=ke,A.afterId=ke}if(G||pe())break}let Oe=pe(),_=qo(f,G),{recordsProcessed:ue,recordsFailed:ie,recordsNotMasked:te}=Rt(f),et=Zr(f);$=!1,oe(this.deps,{...l,...Xo(f,_,G),objects:eo(f)});let J=Ve();if(te>0){let m=G?"cancelled":Oe?`stopped at ${Oe.usagePercent}% of the org's API requests`:"refused by the org";this.deps.log(`[WARN] dataops:anonymize ${t} ${m}: ${te} record(s) not masked \u2014 ${et}`)}await d();let we=await q();G?(this.deps.infraServices?.backgroundRegistry?.abort(t),xe(this.deps,t,{aborted:!0,totalProcessed:ue,totalFailed:ie,totalNotMasked:te}),S?.cancel()):(xe(this.deps,t,{status:_,totalProcessed:ue,totalFailed:ie,totalNotMasked:te}),_==="failure"?S?.fail(`The org refused the ${ie} record(s)`):_==="partial"?S?.partial():S?.complete());let ze=`${te} still hold their original values (${et})`,tt=G?`Anonymization cancelled: ${ue} masked before the cancel \u2014 ${ze}.`:Oe?`Anonymization stopped at ${Oe.usagePercent}% of the org's daily API requests (${Oe.apiUsage} of ${Oe.apiLimit}): ${ue} masked \u2014 ${ze}. ${J?"Resume it":"Run it again"} once the org has requests to spare.`:ie===0?`Anonymization ${_==="success"?"completed":_}: ${ue} records processed.`:`Anonymization ${_}: ${ue} masked, ${ie} rejected by the org \u2014 those records still hold their original values.`,Kt=J&&te>0?" Resume masks only what this run left.":"",zn=ht(we,this.orgNameOf(e.orgId)),ao=tt+Kt+(zn?` ${zn}`:"");c.ended({templateId:e.templateId,status:_,recordsProcessed:ue,recordsFailed:ie,recordsNotMasked:te,objects:Yr(f),message:ao,errors:Ye,...G?{cancelled:!0}:{},...Oe?{stoppedAtApiLimit:!0}:{},...K?{snapshot:K}:{},...o?{mutedAutomation:o.outcome}:{},...we?{duplicates:we}:{}})}catch(T){await d();let D=await q().catch(()=>{});Qe(T,!0,D)}finally{let T=await d();if(T&&c.muted?.(T),$){let D=f.some(ee=>ee.masked>0);oe(this.deps,{...l,outcome:D?"partial":"failure",objects:g?eo(f):[]})}O&&!B&&Ve(),P(E),L?.release(),r?.removeEventListener("abort",fe),i.answer?.(T)}}handleAnonymizationTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.listedTemplates(),n=se(this.deps,e,"dataops:anonymization-templates:response",{templates:t});this.deps.broker.postToWebview(n),this.deps.log("[TX] dataops:anonymization-templates:response")}listedTemplates(){return[...kt,...this.savedTemplates.list()]}async handleBackupObjects(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(Yn,e,"dataops:error",this.deps);if(!t)return;let n=t.templateId!==void 0?this.findTemplate(t.templateId):void 0;if(t.templateId!==void 0&&!n){this.refuseUnknownTemplate("backup:objects",e,t.templateId);return}try{let r,o=()=>r??=Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager).then(d=>Nn(d,this.deps.log)),i=[];for(let d of n?[n]:this.listedTemplates()){let c=At({},d,W)&&await o();for(let p of Bt({},d,c))p!==""&&p!=="*"&&!i.includes(p)&&i.push(p)}let a=se(this.deps,e,"backup:objects:response",{objects:i});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} objects=${i.length}`)}catch(r){M(this.deps,"backup:objects","dataops:error",e,r)}}async plannedObjectsIn(e,t,n){let r=At(t,n,W)&&await Nn(e,this.deps.log);return Bt(t,n,r)}async handleAnonymizeCoverage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(or,e,"dataops:error",this.deps);if(!t)return;let n=this.findTemplate(t.templateId);if(!n){this.refuseUnknownTemplate("dataops:anonymize:coverage",e,t.templateId);return}try{let r=this.latestBackup(t.orgId),o=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),i=[],a=await this.plannedObjectsIn(o,t,n);for(let p of a){if(!Gr(n,p))continue;let u=De(p),b=null;try{b=await this.countRows(o,u,void 0,Sn(t,n,p))}catch(f){this.deps.log(`[WARN] dataops:anonymize:coverage: ${u} not counted: ${R(f)}`)}let l=r?.objects.find(f=>f.objectApiName.toLowerCase()===u.toLowerCase());i.push({objectApiName:u,count:b,backedUp:l?.recordCount??0,truncated:l?.truncated===!0,...l?.stoppedAt?{stoppedAt:l.stoppedAt}:{}})}let d=new ot(this.deps.configStore).load(t.orgId,t.templateId,Lt(n.rules,a,En(t))),c=se(this.deps,e,"dataops:anonymize:coverage:response",{templateId:t.templateId,...r?{backup:{operationId:r.operationId,timestamp:r.timestamp}}:{},objects:i,...d?{checkpoint:{id:d.id,savedAt:d.savedAt}}:{}});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id} objects=${i.length}`)}catch(r){M(this.deps,"dataops:anonymize:coverage","dataops:error",e,r)}}async handleAnonymizePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(sr,e,"dataops:error",this.deps);if(!t)return;let n=this.findTemplate(t.templateId);if(!n){this.refuseUnknownTemplate("dataops:anonymize:preview",e,t.templateId);return}try{let r=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),{AnonymizationEngine:o}=await import("./chunk-TLH7AD35.mjs"),i=new o(void 0,this.maskingKey),a=[],d=[],c=Hr(r);for(let u of await this.plannedObjectsIn(r,t,n)){if(!Gr(n,u))continue;let b=De(u);try{let l=Ft(n,u),f=Cn(n,u),{rules:h,select:w,missing:v,rulesOf:g}=await this.maskedFields(c,b,this.maskingRules(u,l),this.maskingRules(u,f)),$=await to(r,b,w,Vr,void 0,Sn(t,n,u));Be(r.limitInfo,`dataops:anonymize:preview ${b}`);let O=$.records.length>0;O&&d.push(...v.map(P=>({objectApiName:b,fieldApiName:P})));let[B]=O?await Kr(c,[{objectApiName:b,rules:[...l,...f]}]):[],Y=$.records.map(g),K=$.records.map((P,E)=>i.anonymize([P],Y[E])[0]),F=h.map(P=>P.fieldApiName).filter((P,E,S)=>P!=="Id"&&S.indexOf(P)===E);a.push({objectApiName:b,fields:F,...O&&h.length===0?{notCovered:!0}:{},...B?{writeDenied:{deniedFields:[...B.deniedFields]}}:{},methods:Object.fromEntries(h.map(P=>[P.fieldApiName,P.method])),rows:$.records.slice(0,Vr).map((P,E)=>{let S={},j={},q=new Set(Y[E].map(L=>L.fieldApiName));for(let L of F)S[L]=Jr(P[L]),j[L]=cn(P[L])&&q.has(L)?Jr(K[E][L]):S[L];return{id:String(P.Id??""),before:S,after:j}})})}catch(l){let f=R(l);this.deps.log(`[WARN] dataops:anonymize:preview: ${b} not read: ${f}`),a.push({objectApiName:b,fields:[],rows:[],error:f})}}let p=se(this.deps,e,"dataops:anonymize:preview:response",{templateId:t.templateId,objects:a,fieldsNotFound:d});this.deps.broker.postToWebview(p),this.deps.log(`[TX] ${p.type} id=${p.id} objects=${a.length}`)}catch(r){M(this.deps,"dataops:anonymize:preview","dataops:error",e,r)}}latestBackup(e){let t;for(let n of this.deps.configStore.getKeysByPrefix("backup:")){let r=n.slice(7);if(r.includes(":"))continue;let o=this.deps.configStore.get(n);if(o?.orgId!==e)continue;let i=o.timestamp??"";t&&t.timestamp.localeCompare(i)>=0||(t={operationId:r,timestamp:i,objects:o.objects??[]})}return t}async handleQualityScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(cr,e,"dataops:error",this.deps);if(t)try{let n=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),r=await pr({describe:i=>n.describe(i),query:async i=>{let a=await n.query(i);return Be(n.limitInfo,"dataops:quality-scan"),{totalSize:a.totalSize,records:a.records}}},t),o=se(this.deps,e,"dataops:quality-scan:response",{...r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} objects=${r.objects.length}`)}catch(n){M(this.deps,"dataops:quality-scan","dataops:error",e,n)}}handleTemplateSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(ir,e,"dataops:error",this.deps);if(t)try{let n=t.name.trim();if([...kt,...this.savedTemplates.list()].some(a=>a.name.trim().toLowerCase()===n.toLowerCase())){M(this.deps,"dataops:anonymization-template:save","dataops:error",e,new Error(`A template named "${n}" already exists. Pick another name.`),{code:"DUPLICATE_NAME"});return}let o={id:`tpl-saved-${crypto.randomUUID()}`,name:n,description:"",complianceFramework:"custom",rules:t.rules.map(a=>({...a,description:""})),saved:!0,createdAt:new Date().toISOString()};this.savedTemplates.save(o);let i=se(this.deps,e,"dataops:anonymization-template:save:response",{template:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){M(this.deps,"dataops:anonymization-template:save","dataops:error",e,n)}}handleTemplateDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(ar,e,"dataops:error",this.deps);if(!t)return;let{templateId:n}=t;if(kt.some(r=>r.id===n)){M(this.deps,"dataops:anonymization-template:delete","dataops:error",e,new Error(`Template "${n}" ships with SandForge and cannot be deleted.`),{code:"BUILT_IN"});return}try{let r=this.savedTemplates.delete(n),o=se(this.deps,e,"dataops:anonymization-template:delete:response",{templateId:n,deleted:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(r){M(this.deps,"dataops:anonymization-template:delete","dataops:error",e,r)}}async handlePIIScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(dr,e,"dataops:error",this.deps);if(!t)return;let{orgId:n,objectNames:r}=t;try{if(!this.deps.infraServices?.piiDetector)throw new Error("PII Detector not available.");let o=await Re(n,this.deps.orgRegistry,this.deps.orgManager),i=await Promise.all(r.map(async d=>{let c=De(d),p=await o.describe(c);Be(o.limitInfo,`precheck:pii-scan describe ${c}`);let u=p.fields.map(l=>({apiName:l.name,label:l.label,type:l.type,length:l.length})),b=this.deps.infraServices.piiDetector.detectPII(d,u);return{objectName:d,piiFields:b.piiFields.map(l=>({fieldName:l.fieldApiName,piiType:l.classification,confidence:l.confidence}))}})),a=se(this.deps,e,"precheck:pii-scan:response",{success:!0,results:i});this.deps.broker.postToWebview(a)}catch(o){this.deps.log(`[ERR] precheck:pii-scan: ${R(o)}`);let i=se(this.deps,e,"precheck:pii-scan:response",{success:!1,error:R(o)});this.deps.broker.postToWebview(i)}}};export{kt as a,Et as b,kn as c,yn as d,zt as e,wn as f,Dt as g,xt as h,Br as i,ro as j};
|