sandforge 1.80.0 → 1.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/bin/sandforge-pipeline.mjs +12 -0
  2. package/lib/{chunk-EMNC6YI4.mjs → chunk-2IB7I3IQ.mjs} +1 -1
  3. package/lib/{chunk-3RZQZHEB.mjs → chunk-2NAIUKVL.mjs} +1 -1
  4. package/lib/{chunk-AEKONPF4.mjs → chunk-2OIRJEYE.mjs} +1 -1
  5. package/lib/{chunk-BV6VTP3J.mjs → chunk-2OZG6GRW.mjs} +1 -1
  6. package/lib/{chunk-JEERQRLW.mjs → chunk-2Z54GB6X.mjs} +1 -1
  7. package/lib/chunk-2ZMGVBLW.mjs +7 -0
  8. package/lib/{chunk-FKG7Q3WH.mjs → chunk-33ZX3A56.mjs} +1 -1
  9. package/lib/{chunk-HLWMJF6Y.mjs → chunk-3AOKLIVE.mjs} +1 -1
  10. package/lib/{chunk-GGD7ON3M.mjs → chunk-3B5H24ZG.mjs} +1 -1
  11. package/lib/chunk-43K2C6H2.mjs +7 -0
  12. package/lib/chunk-4JKR4PTZ.mjs +8 -0
  13. package/lib/chunk-4L7FBOJS.mjs +8 -0
  14. package/lib/chunk-5344TZBT.mjs +11 -0
  15. package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
  16. package/lib/chunk-55LQD3Y3.mjs +7 -0
  17. package/lib/chunk-56MPPWLA.mjs +7 -0
  18. package/lib/chunk-5C5XEVZN.mjs +11 -0
  19. package/lib/chunk-5CKWGZX4.mjs +9 -0
  20. package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
  21. package/lib/{chunk-BKDV4ENO.mjs → chunk-5UT2ZBGF.mjs} +1 -1
  22. package/lib/chunk-5VQNKDFU.mjs +7 -0
  23. package/lib/{chunk-XAMBCQPU.mjs → chunk-5WGA5CZB.mjs} +1 -1
  24. package/lib/chunk-5ZKCLBTN.mjs +474 -0
  25. package/lib/{chunk-UCD54V2M.mjs → chunk-67CC7RAE.mjs} +1 -1
  26. package/lib/{chunk-TSLJUSLW.mjs → chunk-6CDIIFNX.mjs} +1 -1
  27. package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
  28. package/lib/{chunk-FPKYYFM7.mjs → chunk-6FMLW7PH.mjs} +1 -1
  29. package/lib/chunk-6IGEASOF.mjs +7 -0
  30. package/lib/{chunk-XUWL6ZPC.mjs → chunk-6NADW3OI.mjs} +1 -1
  31. package/lib/chunk-6SEDOIO3.mjs +10 -0
  32. package/lib/{chunk-PJ5I73CK.mjs → chunk-742SSN7I.mjs} +1 -1
  33. package/lib/chunk-7DALDJMO.mjs +7 -0
  34. package/lib/chunk-7PK5QDQI.mjs +7 -0
  35. package/lib/chunk-AELFEK3G.mjs +7 -0
  36. package/lib/chunk-AITNZWLB.mjs +9 -0
  37. package/lib/{chunk-2UZPIMUC.mjs → chunk-AJPSGVMD.mjs} +1 -1
  38. package/lib/{chunk-GSKCGQIP.mjs → chunk-BNO5GIJ6.mjs} +1 -1
  39. package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
  40. package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
  41. package/lib/chunk-BZFIOZS3.mjs +156 -0
  42. package/lib/{chunk-J525F5KI.mjs → chunk-C4YGSK6W.mjs} +1 -1
  43. package/lib/chunk-CAFUNR6D.mjs +7 -0
  44. package/lib/chunk-CULAOP3U.mjs +7 -0
  45. package/lib/chunk-D62KWDDT.mjs +7 -0
  46. package/lib/{chunk-OHWNPXWW.mjs → chunk-D7P7DTWL.mjs} +1 -1
  47. package/lib/{chunk-COFG7Q6R.mjs → chunk-DHGPDSXS.mjs} +1 -1
  48. package/lib/{chunk-WU3GLFZO.mjs → chunk-DHIW4IO5.mjs} +1 -1
  49. package/lib/{chunk-6XYKJSGX.mjs → chunk-DMBR24CK.mjs} +1 -1
  50. package/lib/chunk-DPYTG6DM.mjs +48 -0
  51. package/lib/{chunk-BY2HJFFG.mjs → chunk-DQR5NDMI.mjs} +1 -1
  52. package/lib/chunk-DXOXLUZA.mjs +7 -0
  53. package/lib/{chunk-YRQGKDHM.mjs → chunk-E2OBAWSH.mjs} +1 -1
  54. package/lib/chunk-E2YJVSX6.mjs +10 -0
  55. package/lib/{chunk-JWTSEDIQ.mjs → chunk-EAFLDSQ2.mjs} +1 -1
  56. package/lib/{chunk-MILU7WFN.mjs → chunk-EH5YUA5W.mjs} +1 -1
  57. package/lib/{chunk-BGUEWRK2.mjs → chunk-EOSEMFPU.mjs} +1 -1
  58. package/lib/chunk-ETT5GP4P.mjs +13 -0
  59. package/lib/{chunk-MYW5QNGI.mjs → chunk-FDGFUEK3.mjs} +1 -1
  60. package/lib/{chunk-NTFIRZP6.mjs → chunk-FLNLG43R.mjs} +1 -1
  61. package/lib/{chunk-CHYDMRSV.mjs → chunk-FSDO4DJA.mjs} +1 -1
  62. package/lib/{chunk-MJVTDA5Q.mjs → chunk-FSZTXLNW.mjs} +1 -1
  63. package/lib/{chunk-SOU4FRYN.mjs → chunk-FTA5LOVX.mjs} +1 -1
  64. package/lib/chunk-G4VXPS3A.mjs +7 -0
  65. package/lib/chunk-GF247DA7.mjs +7 -0
  66. package/lib/{chunk-BTWDMNN3.mjs → chunk-GK7VEYFM.mjs} +1 -1
  67. package/lib/{chunk-SE4QEZUG.mjs → chunk-GR3NGDVM.mjs} +1 -1
  68. package/lib/{chunk-3TJON4F3.mjs → chunk-GTIXJCGS.mjs} +1 -1
  69. package/lib/{chunk-NZC67CGR.mjs → chunk-GWRKS3AL.mjs} +1 -1
  70. package/lib/{chunk-XLXIPIEW.mjs → chunk-GYKNCYES.mjs} +1 -1
  71. package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
  72. package/lib/{chunk-KDGMAGQR.mjs → chunk-HVC5CYIB.mjs} +1 -1
  73. package/lib/{chunk-WR4Q363I.mjs → chunk-HYBH5PFM.mjs} +1 -1
  74. package/lib/chunk-HYOOJVR6.mjs +7 -0
  75. package/lib/{chunk-5K5VLULK.mjs → chunk-IBURU7T7.mjs} +1 -1
  76. package/lib/chunk-ICIYL45C.mjs +7 -0
  77. package/lib/{chunk-QR3WELJQ.mjs → chunk-IKGHRYCN.mjs} +1 -1
  78. package/lib/chunk-IM2XA6JI.mjs +7 -0
  79. package/lib/{chunk-IWDREM66.mjs → chunk-J6G23RUI.mjs} +1 -1
  80. package/lib/{chunk-2BA2XKAY.mjs → chunk-JU2XEKEO.mjs} +1 -1
  81. package/lib/{chunk-MHMH6MTP.mjs → chunk-K55LH4ZQ.mjs} +1 -1
  82. package/lib/chunk-K5HV4YRO.mjs +7 -0
  83. package/lib/{chunk-M3ROUWDX.mjs → chunk-K77NR3UK.mjs} +1 -1
  84. package/lib/chunk-KE2PGD6C.mjs +7 -0
  85. package/lib/chunk-KGYXLSQ5.mjs +37 -0
  86. package/lib/{chunk-E5AHXLS6.mjs → chunk-KNIRA333.mjs} +1 -1
  87. package/lib/chunk-KOQV4WXC.mjs +8 -0
  88. package/lib/{chunk-L77FJZEP.mjs → chunk-KRNFVAGC.mjs} +1 -1
  89. package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
  90. package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
  91. package/lib/{chunk-IZQZ6ZUF.mjs → chunk-LO527YLT.mjs} +1 -1
  92. package/lib/chunk-MAHZMPMZ.mjs +7 -0
  93. package/lib/{chunk-F6GUDTOB.mjs → chunk-MHW6DV6T.mjs} +1 -1
  94. package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
  95. package/lib/{chunk-FGRG7ANU.mjs → chunk-MKNAZPOT.mjs} +1 -1
  96. package/lib/{chunk-PZPJKATS.mjs → chunk-MNITSYI2.mjs} +8 -8
  97. package/lib/{chunk-OLSGVAIL.mjs → chunk-MO3N5XVV.mjs} +53 -53
  98. package/lib/chunk-MWLFFVQV.mjs +8 -0
  99. package/lib/chunk-N6HHNR6J.mjs +7 -0
  100. package/lib/chunk-N7J6NJQ6.mjs +7 -0
  101. package/lib/chunk-NJ3EOEHS.mjs +9 -0
  102. package/lib/chunk-NWPQF5XR.mjs +7 -0
  103. package/lib/{chunk-IG2MTQRP.mjs → chunk-NWVVCZUK.mjs} +1 -1
  104. package/lib/{chunk-2NBYT7GR.mjs → chunk-O6ADMP36.mjs} +1 -1
  105. package/lib/chunk-O7DAFE6M.mjs +14 -0
  106. package/lib/chunk-OEHVAJAB.mjs +7 -0
  107. package/lib/chunk-OETEC3P7.mjs +7 -0
  108. package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
  109. package/lib/chunk-OIIL4NVI.mjs +7 -0
  110. package/lib/chunk-OMZJ37JI.mjs +15 -0
  111. package/lib/{chunk-CEX3NEZL.mjs → chunk-ONMBSACW.mjs} +1 -1
  112. package/lib/chunk-OQQHNYR7.mjs +272 -0
  113. package/lib/{chunk-SOGQW4IG.mjs → chunk-OU5W7SCB.mjs} +1 -1
  114. package/lib/{chunk-O2HDYYUV.mjs → chunk-OVOLG3AL.mjs} +1 -1
  115. package/lib/{chunk-DYFALGRT.mjs → chunk-OXKZ4Y3B.mjs} +1 -1
  116. package/lib/{chunk-2GTBABKU.mjs → chunk-OZNLOV4U.mjs} +1 -1
  117. package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
  118. package/lib/chunk-PPGDAUEQ.mjs +7 -0
  119. package/lib/{chunk-IGYH7GMA.mjs → chunk-PYUEHBA6.mjs} +1 -1
  120. package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
  121. package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
  122. package/lib/{chunk-BXU6WFMH.mjs → chunk-QXLZINZB.mjs} +1 -1
  123. package/lib/chunk-R2BJWO5N.mjs +20 -0
  124. package/lib/chunk-R6TF26V4.mjs +10 -0
  125. package/lib/{chunk-YKKRIEH4.mjs → chunk-RKALOKAU.mjs} +1 -1
  126. package/lib/chunk-SQGP46QS.mjs +7 -0
  127. package/lib/chunk-SW2NUKQL.mjs +9 -0
  128. package/lib/{chunk-MFG4MUIO.mjs → chunk-T26C576X.mjs} +1 -1
  129. package/lib/{chunk-LKQ5RKIV.mjs → chunk-T3PLRQ2T.mjs} +1 -1
  130. package/lib/chunk-T5VAULLQ.mjs +7 -0
  131. package/lib/{chunk-KYEDBS54.mjs → chunk-TEIBWMJM.mjs} +1 -1
  132. package/lib/chunk-TKQQVB2D.mjs +9 -0
  133. package/lib/{chunk-ELFXJHU7.mjs → chunk-TPHXRHOA.mjs} +1 -1
  134. package/lib/chunk-TQ2TQHTT.mjs +9 -0
  135. package/lib/{chunk-RPI7LRTW.mjs → chunk-TQM2XJ27.mjs} +1 -1
  136. package/lib/{chunk-IOIWJ3DJ.mjs → chunk-UCHAZ4ZU.mjs} +1 -1
  137. package/lib/{chunk-G35N4P7D.mjs → chunk-UIUPPEFB.mjs} +1 -1
  138. package/lib/{chunk-DBB3EMIN.mjs → chunk-UT27HXE7.mjs} +1 -1
  139. package/lib/{chunk-KBJ5VERV.mjs → chunk-UUSLTW5V.mjs} +1 -1
  140. package/lib/chunk-V2QO6KOE.mjs +19 -0
  141. package/lib/chunk-V473C7LY.mjs +7 -0
  142. package/lib/chunk-V4RKM4QZ.mjs +8 -0
  143. package/lib/chunk-VSU74RQ3.mjs +9 -0
  144. package/lib/chunk-VV3B6IC3.mjs +7 -0
  145. package/lib/chunk-W2AAGIZF.mjs +7 -0
  146. package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
  147. package/lib/chunk-WD47PGUS.mjs +10 -0
  148. package/lib/{chunk-HEKAZJRH.mjs → chunk-WEZLXE34.mjs} +1 -1
  149. package/lib/{chunk-W622GUAW.mjs → chunk-WI4HYWV6.mjs} +1 -1
  150. package/lib/{chunk-WA7EYLAQ.mjs → chunk-WM5JI4JI.mjs} +1 -1
  151. package/lib/chunk-WWTXRWNZ.mjs +7 -0
  152. package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
  153. package/lib/{chunk-FXXLX4O6.mjs → chunk-X2ZVSQ54.mjs} +1 -1
  154. package/lib/{chunk-ZVAED4QV.mjs → chunk-XC2QKQT5.mjs} +1 -1
  155. package/lib/chunk-XC54KKKC.mjs +7 -0
  156. package/lib/chunk-XEB6HZ34.mjs +7 -0
  157. package/lib/chunk-XGKSSCW7.mjs +7 -0
  158. package/lib/chunk-XIZ5LMQM.mjs +7 -0
  159. package/lib/{chunk-74Q6DORA.mjs → chunk-Y5ZCPY36.mjs} +1 -1
  160. package/lib/{chunk-UNJA4J37.mjs → chunk-YCSFP6ER.mjs} +4 -4
  161. package/lib/{chunk-X5JYBPXP.mjs → chunk-YHIOS2PU.mjs} +1 -1
  162. package/lib/chunk-YIGFYZQY.mjs +7 -0
  163. package/lib/chunk-YJEXE6HZ.mjs +925 -0
  164. package/lib/{chunk-TTKXMDBN.mjs → chunk-YOGMP72T.mjs} +4 -4
  165. package/lib/chunk-ZRUDYB7O.mjs +7 -0
  166. package/lib/{chunk-CU2INBND.mjs → chunk-ZUA5BNAO.mjs} +1 -1
  167. package/lib/chunk-ZWCRWF7E.mjs +7 -0
  168. package/lib/{chunk-N652NMZ4.mjs → chunk-ZWZXQTAK.mjs} +52 -52
  169. package/lib/sandforge-autopilot.mjs +11 -11
  170. package/lib/sandforge-backup.mjs +63 -32
  171. package/lib/sandforge-checkpoint.mjs +1 -348
  172. package/lib/sandforge-cleanup.mjs +1 -1
  173. package/lib/sandforge-clone.mjs +1 -1
  174. package/lib/sandforge-compare.mjs +1 -1
  175. package/lib/sandforge-dataops.mjs +1 -1
  176. package/lib/sandforge-empty.mjs +11 -11
  177. package/lib/sandforge-env.mjs +104 -104
  178. package/lib/sandforge-frozen.mjs +1 -266
  179. package/lib/sandforge-mcp.mjs +33 -14
  180. package/lib/sandforge-monitor.mjs +1 -1
  181. package/lib/sandforge-pipeline.mjs +88 -0
  182. package/lib/sandforge-seed.mjs +1 -1
  183. package/lib/sandforge-sync.mjs +1 -1
  184. package/lib/sandforge.mjs +6 -6
  185. package/package.json +2 -1
  186. package/lib/chunk-2CNCDM56.mjs +0 -7
  187. package/lib/chunk-3F6Q5E7I.mjs +0 -14
  188. package/lib/chunk-4VS2V6WU.mjs +0 -25
  189. package/lib/chunk-5P4PHJRL.mjs +0 -9
  190. package/lib/chunk-5TC3QB4U.mjs +0 -10
  191. package/lib/chunk-7ABODJ4G.mjs +0 -7
  192. package/lib/chunk-7EGQP6S4.mjs +0 -7
  193. package/lib/chunk-7FFGJWHN.mjs +0 -7
  194. package/lib/chunk-7YDNUBO5.mjs +0 -7
  195. package/lib/chunk-A527W53V.mjs +0 -7
  196. package/lib/chunk-ADOAS63R.mjs +0 -7
  197. package/lib/chunk-B5QQJ4SI.mjs +0 -7
  198. package/lib/chunk-CION3VMZ.mjs +0 -7
  199. package/lib/chunk-CSBS5U5I.mjs +0 -7
  200. package/lib/chunk-DB7RBE5D.mjs +0 -7
  201. package/lib/chunk-E5ZB3LU5.mjs +0 -7
  202. package/lib/chunk-EFR2Y7E4.mjs +0 -7
  203. package/lib/chunk-EHQ3FX6X.mjs +0 -7
  204. package/lib/chunk-EQNW3UC2.mjs +0 -7
  205. package/lib/chunk-F43REJDZ.mjs +0 -10
  206. package/lib/chunk-GSG7WZHM.mjs +0 -7
  207. package/lib/chunk-HOJYWTP7.mjs +0 -20
  208. package/lib/chunk-HS4YRX4J.mjs +0 -7
  209. package/lib/chunk-I7O6C2B5.mjs +0 -8
  210. package/lib/chunk-IFETCRWE.mjs +0 -10
  211. package/lib/chunk-IQXHJEYB.mjs +0 -7
  212. package/lib/chunk-JPUR2CFX.mjs +0 -10
  213. package/lib/chunk-K327QKMD.mjs +0 -7
  214. package/lib/chunk-KRCA6IPH.mjs +0 -8
  215. package/lib/chunk-LPBMBW3O.mjs +0 -13
  216. package/lib/chunk-LWW4U276.mjs +0 -7
  217. package/lib/chunk-MJU2PGZQ.mjs +0 -15
  218. package/lib/chunk-OAZRPP4I.mjs +0 -7
  219. package/lib/chunk-OO6CLPEH.mjs +0 -7
  220. package/lib/chunk-OPXCV2KL.mjs +0 -7
  221. package/lib/chunk-P33PSCXK.mjs +0 -7
  222. package/lib/chunk-Q3DM32KF.mjs +0 -11
  223. package/lib/chunk-QROPNEGY.mjs +0 -14
  224. package/lib/chunk-QWT2C74M.mjs +0 -7
  225. package/lib/chunk-R3X3LV64.mjs +0 -14
  226. package/lib/chunk-RMBPOTD7.mjs +0 -7
  227. package/lib/chunk-SIHORWVK.mjs +0 -7
  228. package/lib/chunk-T62WNR54.mjs +0 -7
  229. package/lib/chunk-TTFDUKUS.mjs +0 -47
  230. package/lib/chunk-VE6XKGGD.mjs +0 -7
  231. package/lib/chunk-VGW4MXXZ.mjs +0 -7
  232. package/lib/chunk-VS7ZXUII.mjs +0 -824
  233. package/lib/chunk-VXQLDM4R.mjs +0 -7
  234. package/lib/chunk-VYXMVJL5.mjs +0 -7
  235. package/lib/chunk-W7U5E5ZL.mjs +0 -9
  236. package/lib/chunk-WXAQ7FK3.mjs +0 -115
  237. package/lib/chunk-YS4G22C2.mjs +0 -7
  238. package/lib/chunk-ZM6OJGIG.mjs +0 -7
  239. package/lib/chunk-ZUTYVST5.mjs +0 -7
@@ -0,0 +1,15 @@
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 wn}from"./chunk-43K2C6H2.mjs";import{a as Rr,b as es}from"./chunk-XCA5AONB.mjs";import{a as xt,b as bn,c as Xn}from"./chunk-66NMFCWX.mjs";import{a as Yn,e as wr,i as yr}from"./chunk-WB2RIVO3.mjs";import{Aa as lr,Ac as hr,Ba as ur,Ca as pr,Dc as Zn,Fc as Sr,Hc as is,Ic as $t,Jc as as,Kc as Bt,Lc as ds,Mc as en,Oc as Cr,Pc as Pr,Qc as Mr,b as Vt,d as Kn,e as qn,f as Hn,j as ke,k as hn,l as Yt,m as Mt,n as Ve,o as H,pa as er,qa as tr,ra as nr,s as pe,sa as sr,ta as rr,ua as or,va as ir,wa as kn,wc as Se,xa as ar,ya as dr,za as cr}from"./chunk-CAFUNR6D.mjs";import{d as gr}from"./chunk-AITNZWLB.mjs";import{a as Et,b as Zs}from"./chunk-CE6ZDGBB.mjs";import{a as vr,b as ts,c as $r,d as ns,e as ss,f as Zt,g as Jt,h as Tr,i as rs,j as jr,k as yn,l as os}from"./chunk-OEHVAJAB.mjs";import{k as Ir,r as Er,s as xr}from"./chunk-6SEDOIO3.mjs";import{l as fr}from"./chunk-ZWCRWF7E.mjs";import{d as Ar}from"./chunk-T63U4OZJ.mjs";import{a as Jn}from"./chunk-YYZL7UGV.mjs";import{a as br,c as kr}from"./chunk-ETT5GP4P.mjs";import{B as Or,r as ze}from"./chunk-T26C576X.mjs";import{b as Qn,c as zt,d as Vn,h as mr}from"./chunk-BNO5GIJ6.mjs";import{a as Ye}from"./chunk-5LFSFYFJ.mjs";import{c as Qt,e as be,f as gn,i as Gn}from"./chunk-KOQV4WXC.mjs";import{b as Nr}from"./chunk-VV3B6IC3.mjs";import{d as Xs,e as Qs,g as Vs,h as Ys}from"./chunk-INIT2UKJ.mjs";import{B as Js}from"./chunk-XEB6HZ34.mjs";import{q as se,r as Xt,u as mn}from"./chunk-55LQD3Y3.mjs";import{a as Gs,f as Gt,h as bt}from"./chunk-TZE3Y7IQ.mjs";import{b as P}from"./chunk-CA5NAXSU.mjs";import{Ac as Un,Gc as Pt,Kc as qs,Lc as fn,Yb as Wn,a as Re,fb as Ws,fe as Hs,gb as Us,hb as Ks,vc as xe,x as _s,y as ht}from"./chunk-DPYTG6DM.mjs";import{b as ie,e as Ls,f as Ds,k as vt,l as gt,q as Fs,v as _n}from"./chunk-WZQEK4WT.mjs";var vo={defaultQueryLimit:500,previewQueryLimit:200,exportQueryLimit:1e3},$o={defaultQueryLimit:2e3,previewQueryLimit:2e3,exportQueryLimit:5e3};function An(i){return i==="production"?{...vo}:{...$o}}function In(i){return i?"sandbox":"production"}var Lt="IsPersonAccount",No=new Set(["FirstName","LastName","MiddleName","Suffix","Salutation","Phone","Fax"]);function Oo(i){if(No.has(i))return i;if(i.endsWith("__c"))return`${i.slice(0,-3)}__pc`;if(/^[A-Za-z][A-Za-z0-9]*$/.test(i))return`Person${i}`}function cs(i){let e=(s,r)=>s.fieldPattern.toLowerCase().startsWith(`${r.toLowerCase()}.`)?s.fieldPattern.slice(r.length+1):void 0,t=new Set(i.flatMap(s=>{let r=e(s,se);return r===void 0?[]:[r.toLowerCase()]})),n=[];for(let s of i){let r=e(s,Xt),o=r===void 0?void 0:Oo(r);o===void 0||t.has(o.toLowerCase())||(t.add(o.toLowerCase()),n.push({...s,fieldPattern:`${se}.${o}`}))}return n}function zr(i){if(i.objectApiName.toLowerCase()!==se.toLowerCase()||!i.fields.some(l=>l.name===Lt))return;let e=new Map(i.fields.map(l=>[l.name.toLowerCase(),l])),t=new Set(i.kept.map(l=>l.fieldApiName.toLowerCase())),n=[],s=new Set,r=[],o=(l,p)=>{t.add(p.name.toLowerCase()),s.add(p.name),n.push({...l,objectApiName:se,fieldApiName:p.name})};for(let l of i.derived){let p=e.get(l.fieldApiName.toLowerCase());if(!p){r.push(l.fieldApiName);continue}t.has(p.name.toLowerCase())||o(l,p)}let a=i.fields.filter(l=>qs(l.name)&&l.updateable===!0&&l.calculated!==!0&&!t.has(l.name.toLowerCase())),d=new Map,c=a.map(l=>{let p=Lr(l.name);return d.set(p,l),{...l,name:p,label:l.label??l.name,type:l.type??"string"}});for(let l of wr(i.detector,Xt,c)){let p=d.get(l.field.name);!p||t.has(p.name.toLowerCase())||o({objectApiName:se,fieldApiName:p.name,method:yr({...l.field,name:p.name}),config:{}},p)}return{rules:n,personOnly:s,unseen:r}}function Br(i,e){let t=new Set((e??[]).map(n=>n.name.toLowerCase()));return i.filter(n=>!t.has(Lr(n).toLowerCase()))}function Lr(i){return i.endsWith("__pc")?`${i.slice(0,-4)}__c`:i.startsWith("Person")&&!i.includes("__")?i.slice(6):i}function Dr(i,e,t,n){if(i.toLowerCase()!==se.toLowerCase())return[...t];let s=mn(e,!1);return t.filter(r=>!fn(se,r.fieldApiName,s)&&(s==="person"||!n.has(r.fieldApiName)))}var Fr=200,To=48,jo=64;function Rn(i,e){return Math.max(1,Math.ceil(i/e))}function _r(i,e,t){let n=Math.max(1,Math.ceil(i/e)),s=t.masking?Math.ceil(i/Fr):0;return n+1+s+(t.duplicateRule?2:0)}function ls(i,e,t,n){let s=0,r=0,o=0,a=0,d=[],c=[];for(let l of i){let p=Rn(l.rows,e);p>ht&&c.push(l.objectApiName);let g=Math.floor(l.rows/e),u=l.rows-g*e;s+=g*Math.ceil(e/t)+Math.ceil(u/t)+1,n==="masking"&&(r+=Math.ceil(l.rows/Fr)),o+=p+(l.duplicateRule&&n==="masking"?2*p:0)+2,a+=l.rows*(To+jo*l.fields),d.push({objectApiName:l.objectApiName,size:e,slices:p,...l.approximate?{approximate:!0}:{}})}return{objects:d,requests:s+r+o,parts:{snapshots:s,updates:r,reads:o},diskBytes:a,seconds:Math.round(s*Er+r*xr),tooMany:c}}function Sn(i){return Math.ceil(i*1.1)}function us(i){let e=["bytes","KB","MB","GB","TB"],t=i,n=0;for(;t>=1024&&n<e.length-1;)t/=1024,n++;return n===0?`${i} bytes`:`${t.toFixed(t<10?1:0)} ${e[n]}`}import{createHash as Co}from"node:crypto";import{mkdir as Po,readFile as Mo,rm as Eo,writeFile as xo}from"node:fs/promises";import*as ps from"node:path";function vn(i){if(!/^[A-Za-z0-9_-]{1,200}$/.test(i))throw new Error(`Not a set id: "${i}".`);return i}var Wr=/^[0-9a-f]{64}$/;function Ei(i){return{save:async(e,t)=>{await i.storeSecret(`dataops.runKey.${vn(e)}`,t)},load:async e=>{let t=await i.getSecret(`dataops.runKey.${vn(e)}`);return t!==void 0&&Wr.test(t)?t:void 0},delete:async e=>{await i.deleteSecret(`dataops.runKey.${vn(e)}`)}}}var zo=384,Bo=448;function xi(i){let e=ps.join(i,"keys"),t=n=>ps.join(e,`${vn(n)}.key`);return{save:async(n,s)=>{await Po(e,{recursive:!0,mode:Bo}),await xo(t(n),s,{encoding:"utf8",mode:zo})},load:async n=>{try{let s=(await Mo(t(n),"utf8")).trim();return Wr.test(s)?s:void 0}catch{return}},delete:async n=>{await Eo(t(n),{force:!0})}}}function fs(i){return Co("sha256").update(`sandforge-slice-key:${i}`).digest("hex").slice(0,16)}import{randomBytes as Zo}from"node:crypto";import{statfs as Jo}from"node:fs/promises";import*as ho from"node:path";var tn=[{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 $n=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,s){if(this.pruneExpired(),this.operations.has(e))throw new Error(`Duplicate DML operation detected: ${e}`);let r={operationId:e,objectApiName:t,dmlType:n,recordCount:s,registeredAt:new Date(this.nowFn()).toISOString(),status:"pending"};return this.operations.set(e,r),r}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 s=0;s<n;s++)this.operations.delete(t[s][0])}}};var Lo=3e3;function Ze(i){return i.slice(0,15)}function Do(i,e){let t=i??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 Fo(i){let e=[],t=[],n=0;for(let s of i)t.length>0&&n+s.length+2>Lo&&(e.push(t),t=[],n=0),t.push(s),n+=s.length+2;return t.length>0&&e.push(t),e}async function Ur(i,e,t){let n=t.map(a=>a.Id).filter(zt),s=[...new Set(t.flatMap(a=>Object.keys(a)))].filter(a=>a.toLowerCase()!=="id");if(n.length===0||s.length===0)return{write:[...t],unchanged:0};let r=new Map;try{for(let a of Fo(s))for(let d of await mr(i,e,a,n))typeof d.Id=="string"&&r.set(Ze(d.Id),{...r.get(Ze(d.Id)),...d})}catch(a){return{write:[...t],unchanged:0,unread:P(a)}}let o=t.filter(a=>{let d=zt(a.Id)?r.get(Ze(a.Id)):void 0;return d?Object.keys(a).some(c=>c.toLowerCase()!=="id"&&!Do(a[c],d[c])):!0});return{write:o,unchanged:t.length-o.length}}async function Kr(i,e,t,n){let s=bt(e),r=new Set,o=t.filter(zt);for(let a=0;a<o.length;a+=Qn){let d=o.slice(a,a+Qn),[c]=Vn(d,d.length),l=new Set,p=await i.query(`SELECT Id, LastModifiedDate FROM ${s} WHERE Id IN (${c})`);for(let S of p.records){if(typeof S.Id!="string")continue;l.add(Ze(S.Id)),Date.parse(String(S.LastModifiedDate??""))<=n||r.add(Ze(S.Id))}let g=d.filter(S=>!l.has(Ze(S)));if(g.length===0)continue;let[u]=Vn(g,g.length),f=await i.query(`SELECT Id FROM ${s} WHERE Id IN (${u}) AND IsDeleted = true`,{scanAll:!0});for(let S of f.records)typeof S.Id=="string"&&r.add(Ze(S.Id))}return r}function qr(i,e){return{async*[Symbol.asyncIterator](){for await(let t of i){let n=t.filter(s=>!(zt(s.Id)&&e.has(Ze(s.Id))));n.length>0&&(yield n)}}}}function ms(i,e){let t=0;return{batches:{async*[Symbol.asyncIterator](){let n=new Map,s=[],r=0;for await(let a of i)for(let d of a){if(r++,!zt(d.Id)){s.push({...d});continue}let c=n.get(Ze(d.Id));if(!c){n.set(Ze(d.Id),{...d});continue}for(let[l,p]of Object.entries(d))l in c||(c[l]=p)}t=r;let o=[...n.values(),...s];for(let a=0;a<o.length;a+=e)yield o.slice(a,a+e)}},lines:()=>t}}var gs="anonymization:template:",Hr="anonymizationTemplates",Gr=gt({id:ie().min(1).max(100),name:ie().trim().min(1).max(Ws),description:ie().max(500),complianceFramework:_n("custom"),rules:vt(Fs(Ks,gt({description:ie().max(500)}))).min(1).max(Us),saved:_n(!0),createdAt:ie()}),Nn=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${gs}${e.id}`,e,Hr)}load(e){let t=Gr.safeParse(this.configStore.get(`${gs}${e}`));return t.success?t.data:void 0}list(){let e=[];for(let t of Object.values(this.configStore.getByCategory(Hr))){let n=Gr.safeParse(t);n.success&&e.push(n.data)}return e.sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}delete(e){return this.configStore.delete(`${gs}${e}`)}};import{createHash as Xr}from"node:crypto";var Wo="anonymization:checkpoint:",Uo="anonymizationCheckpoints",Nt=2e3,hs=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Ko=ie().min(1).max(255),qo=gt({id:ie().regex(hs),fields:vt(Ko).min(1).max(800),digest:ie().regex(/^[0-9a-f]{64}$/)}),Ho=gt({objectApiName:ie().min(1).max(255),done:Ds(),afterId:ie().regex(hs).optional(),refused:vt(ie().regex(hs)).max(Nt),unconfirmed:vt(qo).max(Nt).optional(),slice:gt({setId:ie().min(1).max(200),index:Ls().int().positive()}).optional()}),Go=gt({id:ie().min(1).max(200),orgId:ie().min(1).max(200),templateId:ie().min(1).max(200),fingerprint:ie().regex(/^[0-9a-f]{64}$/),savedAt:ie(),objects:vt(Ho),namesGiven:ie().max(6e4).regex(/^[A-Za-z0-9+/]*={0,2}$/).optional(),setId:ie().min(1).max(200).optional()});function sn(i,e,t,n){let s=i.map(o=>[o.fieldPattern,o.ruleType,o.config??null]),r=t?.trim();return Xr("sha256").update(JSON.stringify({rules:s,objects:e,...r?{where:r}:{},...n!==void 0?{slices:n}:{}})).digest("hex")}function Xo(i){return i==null||i===""?null:typeof i=="string"?i.trim():typeof i=="number"||typeof i=="boolean"?String(i):JSON.stringify(i)}function bs(i,e){let t=[...e].sort().map(n=>[n,Xo(i[n])]);return Xr("sha256").update(JSON.stringify(t)).digest("hex")}function nn(i){return i.reduce((e,t)=>e+t.refused.length,0)}var nt=class{constructor(e){this.configStore=e}configStore;load(e,t,n){let s=Go.safeParse(this.configStore.get(this.key(e,t)));if(!s.success)return;let r=s.data;if(!(r.orgId!==e||r.templateId!==t||r.fingerprint!==n))return r}save(e){if(nn(e.objects)>Nt)throw new Error(`A checkpoint keeps at most ${Nt} refused records; this run left ${nn(e.objects)}.`);this.configStore.set(this.key(e.orgId,e.templateId),e,Uo)}clear(e,t){this.configStore.delete(this.key(e,t))}key(e,t){return`${Wo}${e}:${t}`}};async function Qo(i){let{open:e,rename:t,rm:n}=await import("node:fs/promises"),{randomBytes:s}=await import("node:crypto"),r=`${i}.${s(4).toString("hex")}.partial`,o=await e(r,"w"),a=!1;return{write:async d=>{let c=Buffer.from(d,"utf8");for(let l=0;l<c.length;){let{bytesWritten:p}=await o.write(c,l,c.length-l,null);l+=p}},close:async()=>{a=!0,await o.close(),await t(r,i)},abort:async()=>{a||await o.close().catch(()=>{}),a=!0,await n(r,{force:!0})}}}function Vo(i){let e=[];return{write:async t=>{e.push(t)},close:async()=>{await i(new TextEncoder().encode(e.join("")))},abort:async()=>{e.length=0}}}var On=class i{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"?Qo(t.fsPath):Vo(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 s=i.filtersOf(t,n);return e.showSaveDialog({saveLabel:"Save",defaultUri:e.fileUri(t),...s?{filters:s}:{}})}async save(e,t,n){let s=this.host??await this.defaultHost();try{let r=await i.ask(s,e,n);return r?(await s.writeFile(r,new TextEncoder().encode(t)),{status:"saved",path:r.fsPath}):{status:"cancelled"}}catch(r){return{status:"error",message:r instanceof Error?r.message:String(r)}}}async saveStream(e,t,n){let s=this.host??await this.defaultHost(),r;try{let o=await i.ask(s,e,n);if(!o)return{status:"cancelled"};let a=await s.openFile(o);r=a;let d=await t(c=>a.write(c));return await a.close(),r=void 0,{status:"saved",path:o.fsPath,result:d}}catch(o){return await r?.abort().catch(()=>{}),{status:"error",message:o instanceof Error?o.message:String(o)}}}};function rn(i,e,t,n,s=0){i?.register(e,t,n,s);let r=!1,o=a=>{r||(r=!0,a())};return{progress:(a,d,c,l)=>{r||i?.updateProgress(e,a,d,c,l)},complete:()=>o(()=>i?.complete(e)),partial:()=>o(()=>i?.partial(e)),fail:a=>o(()=>i?.fail(e,a)),cancel:()=>o(()=>i?.cancel(e))}}var Ue={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 st(i,e){return Object.assign(new Error(e),{code:i})}function Qr(i,e,t){let n=Hs(i);if(n==="refused")return st(Ue.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 st(Ue.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 ks(i,e){if(i.retries!==void 0&&i.retries>0)return{refusal:st(Ue.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=i.where?.trim();if(t&&i.object===void 0)return{refusal:st(Ue.filterNeedsObject,"A masking condition filters the rows of one object: name the object it holds, or remove the condition. Nothing was masked.")};let n=kn.safeParse({orgId:i.orgId,templateId:i.templateId,...i.object!==void 0?{objects:[i.object]}:{},...t?{where:t}:{},snapshot:!0});if(!n.success){let s=n.error.issues[0];return{refusal:st(Ue.invalid,`The masking step is not one the DataOps page would run (${s.path.join(".")}: ${s.message}). Nothing was masked.`)}}return e(n.data.templateId)?{asked:n.data}:{refusal:st(Ue.templateMissing,`No masking template is shipped or saved under ${n.data.templateId}: it was deleted on the DataOps page. Choose another. Nothing was masked.`)}}var Yo=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function Vr(i){if(!Yo.test(i))throw new Error(`Not a record id: "${i}".`);return i}function ws(i,e){let t=i?.trim();return[...t?[`(${Gt(t)})`]:[],...e.createdSince!==void 0?[`CreatedDate >= ${Js(e.createdSince)}`]:[],...e.afterId!==void 0?[`Id > '${Vr(e.afterId)}'`]:[],...e.untilId!==void 0?[`Id <= '${Vr(e.untilId)}'`]:[]]}function ys(i){return i.length===0?"":` WHERE ${i.join(" AND ")}`}function Yr(i,e,t,n,s){if(!Number.isInteger(s)||s<=0)throw new Error(`Not a slice size: ${s}.`);return`SELECT ${e} FROM ${bt(i)}${ys(ws(t,n))} ORDER BY Id LIMIT ${s}`}function As(i,e,t,n){return`SELECT COUNT() FROM ${bt(i)}`+ys(ws(e,{...n,createdSince:t}))}function Zr(i,e,t){return`SELECT COUNT() FROM ${bt(i)}`+ys(ws(e,{afterId:t}))}function bo(i){let e=i.fields;return{name:i.name,label:i.label,labelPlural:i.labelPlural??"",keyPrefix:i.keyPrefix??null,custom:i.custom??!1,createable:i.createable,updateable:i.updateable,deletable:i.deletable,queryable:i.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:i.recordTypeInfos??[],childRelationships:i.childRelationships??[]}}var ei=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"]),ti=6e4,ni=10,si=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function ri(i,e){return i.slice(0,15)===e.slice(0,15)}var Jr="ORG_REPLACED_SINCE_BACKUP",oi="Backup was cancelled before it finished. Nothing was saved \u2014 run it again to take a complete snapshot.",Ot=class extends Error{constructor(){super(oi),this.name="BackupCancelledError"}},cn=class extends Error{constructor(e){super(`The backup could not be written to disk: ${P(e)}`),this.name="BackupWriteError"}},Wt=class extends Error{constructor(t,n){super(t);this.retryable=n;this.name="BackupNotWholeError"}retryable},Cs="IsDeleted = false",ii="SystemModstamp",ko=5e4,ai=100,an=_s;function di(i){return typeof i!="number"||!Number.isFinite(i)?ko:Math.min(an,Math.max(ai,Math.floor(i)))}var Dt=200,ci=1440*6e4,li=1440*6e4,eo="backupRetention:since",Is="BACKUP_BUSY";function ui(i,e){return e===0?"success":i===0?"failure":"partial"}function Rs(i){return Un(i)}function to(i,e,t){i.length>=ni||i.push({objectApiName:e,message:t?.[0]?.message??"Unknown DML error"})}function Tn(i,e,t=!1){let n=(e?.rules??[]).map(r=>r.fieldPattern.split(".")[0]).filter((r,o,a)=>a.findIndex(d=>En(d,r))===o);if(i.objects)return i.objects.map(r=>n.find(o=>En(o,r))??(En(r,se)?se:r));if(!e)return[];let s=[...n];return t&&ln(i,e,se)&&s.push(se),s}function En(i,e){return i.toLowerCase()===e.toLowerCase()}var pi=`${Lt} = true`;function ln(i,e,t){return i.objects===void 0&&t.toLowerCase()===se.toLowerCase()&&Ft(e,se).length===0&&cs(e.rules).length>0}function jn(i,e,t){return ln(i,e,t)?pi:zn(i)}async function Ss(i,e){try{return(await i.describe(se)).fields.some(t=>t.name===Lt)}catch(t){return e(`[WARN] dataops: whether the org has person accounts was not read: ${P(t)}`),!1}}function Ft(i,e){let t=`${e.toLowerCase()}.`;return i.rules.filter(n=>n.fieldPattern.toLowerCase().startsWith(t)||n.fieldPattern==="*")}function dn(i,e){return e.toLowerCase()===se.toLowerCase()?cs(i.rules):[]}function Cn(i){let e=new Map;return{describe:t=>{let n=e.get(t)??i.describe(t);return e.set(t,n),n}}}async function vs(i,e){return new Xn(async n=>bo(await i.describe(n))).deniedOf(e.map(({objectApiName:n,rules:s})=>({objectApiName:n,operation:"update",fieldNames:s.map(r=>r.fieldPattern.includes(".")?r.fieldPattern.split(".")[1]:r.fieldPattern).filter(r=>r!=="*")})))}function no(i,e){return Ft(i,e).length>0||dn(i,e).length>0}function $s(i){return{objectApiName:i.objectApiName,recordCount:i.recordCount,truncated:i.truncated===!0,...i.orgCount!==void 0?{orgCount:i.orgCount}:{},...i.stoppedAt?{stoppedAt:i.stoppedAt}:{},...i.notKept&&i.notKept.length>0?{notKept:[...i.notKept]}:{},...i.where?{where:i.where}:{}}}function Ns(i,e){return i.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 s=t.orgCount!==void 0?` of ${t.orgCount}`:"",r=t.stoppedAt==="cap"?" (stopped at the cap)":t.stoppedAt==="failure"?" (the read failed)":"";return[`${t.objectApiName} ${t.recordCount}${s}${r}`]}).join(", ")}var rt=200,Os=95,un=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,fi="NOTHING_TO_RESUME",so="TEMPLATE_NOT_FOUND";function Ts(i){return new Error(`Template "${i}" not found.`)}function mi(i){let e=i.Id;if(typeof e!="string"||!un.test(e))return[];let t=Object.keys(i).filter(n=>n!=="Id");return t.length>0?[{id:e,fields:t,digest:bs(i,t)}]:[]}var gi="COUNT_FAILED",on="SNAPSHOT_NOT_TAKEN",js=new Set(["QUERY_TIMEOUT","OPERATION_TOO_LARGE"]),hi=/^([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+):/;function Pn(i){if(typeof i=="object"&&i!==null){let{errorCode:e,code:t}=i;if(typeof e=="string"&&e!=="")return e;if(typeof t=="string"&&t!=="")return t}return hi.exec(P(i))?.[1]??"UNKNOWN"}var ro=5;function oo(i){return i==null?null:typeof i=="string"||typeof i=="number"||typeof i=="boolean"?i:JSON.stringify(i)}function wo(i){return i.done?0:Math.max(0,i.total-i.masked-i.nothingToMask-i.refused-i.unanswered-(i.deletedSince??0))}function Bn(i){return i.refused+i.unanswered+wo(i)+(i.late??0)}function _t(i){return i.reduce((e,t)=>({recordsProcessed:e.recordsProcessed+t.masked+t.nothingToMask,recordsFailed:e.recordsFailed+t.refused,recordsNotMasked:e.recordsNotMasked+Bn(t)}),{recordsProcessed:0,recordsFailed:0,recordsNotMasked:0})}function bi(i,e){let{recordsProcessed:t,recordsFailed:n,recordsNotMasked:s}=_t(i);return s===0?"success":t>0||e&&n===0?"partial":"failure"}function ki(i,e,t){if(!t||e==="success")return{outcome:e};let{recordsProcessed:n,recordsFailed:s}=_t(i);return n+s>0?{outcome:"cancelled"}:{outcome:"stopped",code:Gn}}function io(i){return i.filter(e=>Bn(e)>0).map(e=>`${e.objectApiName} ${Bn(e)}`).join(", ")}function ao(i){return i.map(e=>({objectApiName:e.objectApiName,total:e.total,processed:e.masked+e.nothingToMask,failed:e.refused,notMasked:Bn(e)}))}function co(i){return i.filter(e=>e.total>0||e.masked+e.refused>0).map(e=>{let t=wo(e);return{...gn(e.objectApiName),updated:e.masked,failed:e.refused+e.unanswered,...e.unanswered>0?{mayHaveBeenWritten:e.unanswered}:{},...t>0?{notSent:t}:{}}})}async function lo(i,e,t,n,s,r){return Zs(i,`SELECT ${t} FROM ${e}${xn(r,s)} ORDER BY Id LIMIT ${n}`,n)}function xn(i,e){let t=i?.trim(),n=[...t?[`(${Gt(t)})`]:[],...e===void 0?[]:[`Id > '${e}'`]];return n.length===0?"":` WHERE ${n.join(" AND ")}`}function zn(i){let e=i.where?.trim();return e||void 0}function wi(i){let e=i?.trim();return e?`(${Gt(e)}) AND ${Cs}`:Cs}function yi(i){let e=new Map;for(let[t,n]of i){if(n.length===0)throw new Error(`No field of ${t} was named for the snapshot to read.`);e.set(t,n.map(s=>bt(s)).join(", "))}return e}function uo(i,e,t){let n=e===void 0?"more records":`${e} records`;return new Wt(`${i} 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 yo(i,e){return`The org stopped answering the read of ${i} after ${e} record(s), before it said the read was done: no snapshot was kept.`}async function Ai(i,e,t,n){let s={headers:{},maxFetch:1e4,autoFetch:!1,scanAll:t,responseTarget:"QueryResult"},r=await i.query(e,s),o=[...r.records];for(;!r.done;){if(!r.nextRecordsUrl)throw new Wt(yo(n,o.length),!0);r=await i.queryMore(r.nextRecordsUrl,s),o.push(...r.records)}return o}function Ii(i,e,t){let n=i[i.length-1]?.Id;if(typeof n!="string"||!un.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}function Ri(i){let e=i?.[0];return e?.statusCode==="ENTITY_IS_DELETED"||e?.errorCode==="ENTITY_IS_DELETED"}function Mn(i){return i.slices.filter(e=>!e.late&&e.state!=="pending"&&e.lastId!==void 0).at(-1)?.lastId}function Si(i){return i.slices.reduce((e,t)=>{let n=t.state==="masking"?Math.max(0,t.rows-t.masked-t.nothingToMask-t.refused-t.deletedSince-(t.unanswered??0)):0;return e+n+t.refused+(t.lateLeft??0)},0)}var po=100,fo=3;function mo(i){return`_refused_${i}`}var go=class{constructor(e,t){this.deps=e;this.saveDialog=t??new On}deps;activeOrgOperations=new Set;writing=new Rr;dmlTracker=new $n;backupRecords;syncRuns;expiryListener;sweeping;liveTracker;backupsWriting=new Set;maskingKey=Zo(32).toString("hex");runKeys;freeBytes=async()=>{let e=this.backupRecords?.directory;if(e!==void 0)for(let t of[e,ho.dirname(e)])try{let n=await Jo(t);return Number(n.bavail)*Number(n.bsize)}catch{}};sliceRunsOn=new Map;saveDialog;get savedTemplates(){return new Nn(this.deps.configStore)}findTemplate(e){return tn.find(t=>t.id===e)??this.savedTemplates.load(e)}ruleConfig(e,t=this.maskingKey){let n={...e.config};return e.ruleType==="hash"&&(n.hashSalt=t),n}maskingRules(e,t,n=this.maskingKey){return t.map(s=>({objectApiName:e,fieldApiName:s.fieldPattern.includes(".")?s.fieldPattern.split(".")[1]:s.fieldPattern,method:s.ruleType,config:this.ruleConfig(s,n)}))}refuseUnknownTemplate(e,t,n){H(this.deps,e,"dataops:error",t,Ts(n),{code:so})}setLiveOperationTracker(e){this.liveTracker=e}setSyncRuns(e){this.syncRuns=e}setRunKeyStore(e){this.runKeys=e}setFreeBytes(e){this.freeBytes=e}get sliceSets(){return new Mr(this.deps.configStore)}busyMessage(e,t){let n=this.sliceRunsOn.get(e);if(n===void 0)return t;let s=this.onCommandLine?"the same line with --resume masks the rest, and --abandon gives the set up":"Resume masks the rest, and Abandon gives the set up";return`A masking run in slices (set ${n}) writes to org ${e} now, and holds its backups and restores until it ends: wait for it, or stop it; once stopped, ${s}.`}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;setOnCommandLine(e){this.onCommandLine=e}onCommandLine=!1;countGaveUp(e,t){if(!js.has(Pn(e)))return e;let n=this.onCommandLine?"give --slices, which reads the object a slice at a time by Id and plans on the org's own figure when no count comes, or narrow --where to an indexed field, such as a range of CreatedDate":`mask in slices, which reads the object a slice at a time by Id and plans on the org's own figure when no count comes, or narrow the run from the command line with sandforge dataops anonymize --object ${t} --where on an indexed field, such as a range of CreatedDate`;return new Error(`${P(e)} The org gave up counting the ${t} records the run would mask: ${n}. Nothing was masked.`)}duplicatesSettleMs=vr;setDuplicatesSettle(e){this.duplicatesSettleMs=e}duplicatesWatchOf(e,t){return $r({query:async n=>e.query(n),serverTime:async()=>(await e.soap.getServerTimestamp()).timestamp},t,{settleMs:this.duplicatesSettleMs})}ownReader(){return this.reader??=import("./chunk-T5VAULLQ.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(n=>ze(n,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}orgNameOf(e){return Pt(this.deps.orgManager.getOrg(e),e)}readAct(e,t,n,s,r,o){let a=this.targetAutomation;return jr({act:n,target:this.orgNameOf(t),objects:s,org:Tr(e,d=>new Nr(ti).withTimeout("dataops automation",()=>a.read(t,d)),Un(this.deps.orgManager.getOrg(t))==="production"),accord:r,mayMute:this.muteOffered,muteLeases:this.muteLeases,...o?{voice:o}:{}})}async releaseMute(e,t){if(!e)return;let n=await e.release();for(let s of Or(n,this.orgNameOf(t)))this.deps.log(`[INFO] ${s}`);return n}async handleAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(ir,e,"dataops:error",this.deps);if(t)try{let n=await ze(t.orgId,this.deps.orgRegistry,this.deps.orgManager),s=await this.readAct(n,t.orgId,t.act,t.objects,t,Jt(t)),r=ke(this.deps,e,"dataops:automation:response",{...s.answer});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} refusals=${s.answer.refusals.length}`)}catch(n){H(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 r of this.deps.configStore.getKeysByPrefix("backup:"))n.add(r.slice(7).split(":")[0]);let s=await t.sweep(n,ci,e);s.length>0&&this.deps.log(`[INFO] Removed ${s.length} backup file(s) whose backup never saved its metadata: `+s.join(", "))}catch(n){this.deps.log("[WARN] the files of backups that never saved their metadata were not removed: "+P(n))}}isWritingTo(e){return this.writing.has(e)}async handle(e){if(!ei.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(es(e,"orgId"),()=>this.handleRollback(e)),!0;case"dataops:anonymize":return await this.writing.during(es(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 s=await e.describe(t),r=s.fields.filter(d=>d.type===br).map(d=>d.name),o=r.length>0&&n&&!await n()?r:[];return{select:s.fields.filter(d=>!o.includes(d.name)).map(d=>d.name).join(", "),notKept:o}}async maskedFields(e,t,n,s=[]){let r=(await e.describe(t)).fields,o=new Map(r.map(u=>[u.name.toLowerCase(),u.name])),a=[],d=[];for(let u of n){let f=o.get(u.fieldApiName.toLowerCase());f!==void 0?a.push({...u,fieldApiName:f}):u.fieldApiName!=="*"&&!d.includes(u.fieldApiName)&&d.push(u.fieldApiName)}let c=zr({objectApiName:t,fields:r,kept:a,derived:s,detector:this.deps.infraServices?.piiDetector??new Ar});if(c&&c.unseen.length>0){let u=await e.describe(Xt).then(f=>f.fields,()=>{});for(let f of Br(c.unseen,u))d.includes(f)||d.push(f)}let l=c?[...a,...c.rules]:a,p=l.map(u=>u.fieldApiName).filter((u,f,S)=>u!=="Id"&&S.indexOf(u)===f),g=c&&p.length>0&&!p.includes(Lt);return{rules:l,select:["Id",...p,...g?[Lt]:[]].join(", "),missing:d,rulesOf:c?u=>Dr(t,u,l,c.personOnly):()=>l}}async countRows(e,t,n,s){let o=(await e.query(`SELECT COUNT() FROM ${t}${xn(s,n)}`)).totalSize;if(typeof o!="number"||!Number.isInteger(o)||o<0)throw new Error(`The org did not say how many records ${t} holds.`);return o}async organizationIdOf(e){try{let n=(await Et(e,"SELECT Id FROM Organization"))[0]?.Id;return typeof n=="string"&&si.test(n)?n:void 0}catch(t){this.deps.log(`[WARN] dataops: the org did not say which org it is: ${P(t)}`);return}}async handleBackup(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(er,e,"dataops:error",this.deps);if(!t)return;let n=e.id,s=new Map;for(let[a,d]of Object.entries(t.wheres??{})){let c=t.objects.find(l=>En(l,a));c!==void 0&&d.trim()!==""&&s.set(xe(c),d.trim())}if(t.slices===!0){await this.backupInSlices(e,{orgId:t.orgId,objects:t.objects,wheres:s});return}let r=await this.takeBackup(n,{orgId:t.orgId,objects:t.objects,...s.size>0?{wheres:s}:{}},e.type);if("error"in r){H(this.deps,"backup:execute","dataops:error",e,r.error),this.endBackupNotTaken(n,r);return}let o=ke(this.deps,e,"dataops:backup:response",{operationId:n,status:"completed",objects:r.objects.map($s),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 backupInSlices(e,t){let n=e.id,s={module:"dataops",operation:e.type},r=(g,u)=>{H(this.deps,"backup:execute","dataops:error",e,new Error(u),{...g?{code:g}:{}}),pe(this.deps,n,u,!1,{context:s,authored:!0})};if(!this.backupRecords){r(Re.needsStore,"A backup in slices writes each slice to the backup files, and this host keeps none.");return}let o=`backup:${t.orgId}`;if(this.activeOrgOperations.has(o)){r(void 0,this.busyMessage(t.orgId,`A backup or rollback operation is already running for org ${t.orgId}. Please wait for it to complete.`));return}this.activeOrgOperations.add(o);let a=new AbortController,d=()=>{},c,l,p=`Backup ${t.objects.length} object(s) in slices`;try{let g=await ze(t.orgId,this.deps.orgRegistry,this.deps.orgManager);Yt(this.deps,n,"dataops",p),this.deps.infraServices?.backgroundRegistry?.register(n,"dataops",p,new Promise((A,B)=>{d=C=>{C===void 0?A():B(C instanceof Error?C:new Error(String(C)))}}),a),c=rn(this.liveTracker,n,"dataops",p,t.objects.length);let u=0,f=new Date().toISOString(),S=await this.organizationIdOf(g),k={setId:n,kind:"backup",orgId:t.orgId,...S!==void 0?{organizationId:S}:{},size:this.backupCap(),state:"open",startedAt:f,lastActivityAt:f,requestsSpent:0,objects:t.objects.map(A=>{let B=xe(A),C=t.wheres.get(B);return{objectApiName:B,...C?{where:C}:{},done:!1,slices:[]}})},E=this.sliceSets,j=()=>{k.lastActivityAt=new Date().toISOString(),k.requestsSpent=u,E.save(k)};j();let y,b=!1;e:for(let A of k.objects)for(s.objectName=A.objectApiName;;){if(a.signal.aborted){b=!0;break e}let B=A.slices.filter(ve=>!ve.late);if(B.length>=ht){y=`${A.objectApiName} holds more rows than ${ht} slices of ${k.size} do: the backup stopped there.`;break e}let C=as(k),ee=Mn(A),G={index:C,...ee!==void 0?{afterId:ee}:{},rows:0,snapshotId:is(k.setId,C),state:"pending",masked:0,refused:0,deletedSince:0,nothingToMask:0,sizeUsed:B.at(-1)?.sizeUsed??k.size};A.slices.push(G),j();let W=await this.snapshotSlice(g,t.orgId,k,A,G,{bounds:ee!==void 0?{afterId:ee}:{},stop:a.signal,onRequest:()=>{u++},origin:e.type,clock:!1});if("failed"in W){A.slices=A.slices.filter(ve=>ve!==G),j(),W.cancelled?b=!0:y=this.sliceNotTakenMessage(A.objectApiName,W);break e}if(W.lastId===void 0){await this.removeBackup(`backup:${G.snapshotId}`),A.slices=A.slices.filter(ve=>ve!==G),A.done=!0,j();break}G.rows=W.rows,G.lastId=W.lastId,G.sizeUsed=W.sizeUsed,G.takenAt=new Date().toISOString(),G.state="snapshotted",j();let X=`Backed up ${A.objectApiName} slice ${C} (${W.rows} records)`;Mt(this.deps,n,0,C,C,X),c.progress(0,C,C,X)}k.objects.every(A=>A.done)&&(k.state="done"),j();let I=k.objects.map(A=>({objectApiName:A.objectApiName,recordCount:A.slices.reduce((B,C)=>B+C.rows,0),truncated:!A.done,...A.done?{}:{stoppedAt:"failure"},...A.where?{where:A.where}:{}})),N=I.reduce((A,B)=>A+B.recordCount,0),D=k.state!=="done";b?(this.deps.infraServices?.backgroundRegistry?.abort(n),Ve(this.deps,n,{aborted:!0,totalRecords:N}),c.cancel()):(Ve(this.deps,n,{objects:I.map(A=>({objectApiName:A.objectApiName,recordCount:A.recordCount})),totalRecords:N,...D?{status:"partial"}:{}}),D?c.partial():c.complete()),y&&this.deps.log(`[WARN] backup ${n}: ${y}`);let R=ke(this.deps,e,"dataops:backup:response",{operationId:n,status:D?"partial":"completed",objects:I,totalRecords:N,...D?{partial:!0}:{},timestamp:k.lastActivityAt,slices:en(k,{requestsSpent:u})});this.deps.broker.postToWebview(R),this.deps.log(`[TX] ${R.type} id=${R.id} slices=${$t(k).length}`),(y||b)&&hn(this.deps,"warning","Backup",`${b?"The backup in slices was cancelled":y}: set ${k.setId} holds ${N} record(s) in ${$t(k).length} slice(s), listed as partial.`)}catch(g){l=g,H(this.deps,"backup:execute","dataops:error",e,g),pe(this.deps,n,P(g),!0,{context:s}),c?.fail(P(g))}finally{this.activeOrgOperations.delete(o),d(l)}}restoreOfSet(e,t){let n=t===void 0?e.operationId:t.origin==="slice"?t.setId:void 0;if(n===void 0)return e.slices?{refused:{code:"NOT_A_SLICE_SET",message:`Backup ${e.operationId} holds no slices: restore it whole, without naming a slice.`}}:{};let s=this.sliceSets.get(n);if(!s||s.orgId!==e.orgId)return{};if(s.kind==="masking"&&s.state==="open"){let u=this.sliceWays(this.onCommandLine?void 0:"page");return{refused:{code:Re.runOpen,message:`Set ${s.setId} is still open: its masking run stopped part way, and resumed it would mask again over what a restore puts back. Give it up first (${u.abandon}), then restore it; or resume it to its end (${u.resume}). Nothing was written.`}}}let r=e.slices??(t?.slice?[t.slice.index]:void 0),o=s.objects.flatMap(u=>u.slices.filter(f=>f.state!=="pending").map(f=>({objectApiName:u.objectApiName,slice:f})));o.sort((u,f)=>u.slice.index-f.slice.index);let a=(r??[]).filter(u=>!o.some(f=>f.slice.index===u));if(a.length>0)return{refused:{code:"SLICE_NOT_FOUND",message:`Set ${s.setId} holds no slice ${a.join(", ")}: its slices are ${o.map(u=>u.slice.index).join(", ")||"none"}. Nothing was written.`}};let d=r?o.filter(u=>r.includes(u.slice.index)):o,c=u=>r!==void 0||e.rewriteAll===!0||u.slice.restoredAt===void 0,l=d.filter(c).map(u=>({snapshotId:u.slice.snapshotId,objectApiName:u.objectApiName,recordCount:u.slice.rows,slice:u.slice})),p=d.filter(u=>!c(u)).map(u=>({index:u.slice.index,objectApiName:u.objectApiName,restored:0,failed:0,unchanged:0,skipped:!0}));if(l.length===0&&p.length>0){let u=p.map(S=>o.find(k=>k.slice.index===S.index)?.slice.restoredAt??"").sort().at(-1),f=this.onCommandLine?"--rewrite-all":"Write every row back";return{refused:{code:"NOTHING_TO_RESTORE",message:`Every slice of set ${s.setId} was restored already (the last on ${u}): nothing was written. ${f} restores them again.`}}}let g=s.objects.map(u=>({objectApiName:u.objectApiName,recordCount:l.filter(f=>f.objectApiName===u.objectApiName).reduce((f,S)=>f+S.recordCount,0)})).filter(u=>l.some(f=>f.objectApiName===u.objectApiName));return{set:s,meta:{orgId:s.orgId,...s.organizationId!==void 0?{organizationId:s.organizationId}:{},timestamp:s.startedAt,totalRecords:g.reduce((u,f)=>u+f.recordCount,0),objects:g},parts:l,skipped:p}}async backupForPipeline(e,t){let n=e.fields?yi(e.fields):void 0,s=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 s){let r=P(s.error);throw this.endBackupNotTaken(e.operationId,s),s.cancelled?new wn(r):s.error instanceof Error?s.error:new Error(r)}return s}endBackupNotTaken(e,t){if(t.cancelled){Ve(this.deps,e,{aborted:!0});return}pe(this.deps,e,P(t.error),t.retryable,{context:t.context})}async takeBackup(e,t,n,s){let r={module:"dataops",operation:n},o=t.slice,a=`backup:${t.orgId}`;if(!o&&this.activeOrgOperations.has(a)){let y=`A backup or rollback operation is already running for org ${t.orgId}. Please wait for it to complete.`;return this.deps.log(`[WARN] ${y}`),{error:new Error(this.busyMessage(t.orgId,y)),retryable:!1,context:r}}o||this.activeOrgOperations.add(a);let d=()=>{},c,l=new AbortController,p=()=>l.abort();s?.aborted&&l.abort(),s?.addEventListener("abort",p,{once:!0});let g=this.backupCap(),u=this.backupWriter(e);this.backupsWriting.add(e);let f=[],S,k,E,j=(y,b,I,N)=>{o||(Mt(this.deps,e,y,b,I,N),E?.progress(y,b,I,N))};try{if(!o&&this.dmlTracker.isDuplicate(e))return this.deps.log(`[WARN] Duplicate backup operation detected: ${e}`),{error:new Error(`Duplicate operation: ${e}`),retryable:!1,context:r};o||this.dmlTracker.register(e,"backup","insert",t.objects.length);let y=await ze(t.orgId,this.deps.orgRegistry,this.deps.orgManager);k=y,t.onConnection?.(y);let b=kr(async C=>(await y.query(C)).records),I=this.deps.orgManager.getOrg(t.orgId),N=In(I?.orgType==="Sandbox"||I?.orgType==="Scratch"),D=An(N).defaultQueryLimit,R=`Backup ${t.objects.length} object(s)`;o||(Yt(this.deps,e,"dataops",R),this.deps.infraServices?.backgroundRegistry?.register(e,"dataops",R,new Promise((C,ee)=>{d=G=>{G===void 0?C():ee(G instanceof Error?G:new Error(String(G)))}}),l),E=rn(this.liveTracker,e,"dataops",R,t.objects.length));for(let C of t.objects){if(l.signal.aborted)throw new Ot;let ee=xe(C);r.objectName=ee;let G=t.wheres?.get(ee),W={objectApiName:C,recordCount:0,truncated:!1,...G!==void 0?{where:G}:{}};S=W,await this.readIntoBackup(y,ee,W,u,{pageSize:D,cap:o?.size??g,select:t.fields?.get(ee),where:G,scanAll:t.scanAll?.has(ee)===!0,...t.origin==="checkpoint"?{stamp:ii}:{},whole:t.failWhenTruncated===!0||o!==void 0,viewsEncrypted:b,...o?{slice:{bounds:o.bounds,size:o.size,...o.skip?{skip:o.skip}:{}},onRequest:o.onRequest}:{}},l.signal,()=>{let X=Math.max(1,Math.min(W.orgCount??g,g));j(Math.round((f.length+W.recordCount/X)/t.objects.length*100),f.length,t.objects.length,`Reading ${C} (${W.recordCount} of ${X} records)`)}),S=void 0,f.push(W),W.stoppedAt==="cap"&&this.deps.log(`[WARN] backup of ${ee} stopped at the cap of ${g} record(s): the object holds ${W.orgCount??"more"}.`),j(Math.round(f.length/t.objects.length*100),f.length,t.objects.length,`Exported ${C} (${W.recordCount} records)`)}let A=o?void 0:await this.organizationIdOf(y);if(l.signal.aborted)throw new Ot;let B=this.saveBackupMeta({operationId:e,orgId:t.orgId,organizationId:A,cap:o?.size??g,...t.origin?{origin:t.origin}:{},...o?{origin:"slice",setId:o.setId,slice:{index:o.index,...o.bounds.afterId!==void 0?{afterId:o.bounds.afterId}:{},...f[0]?.lastId!==void 0?{lastId:f[0].lastId}:{},size:o.size}}:{}},f,u,!1);return o?{operationId:e,objects:f,totalRecords:B.totalRecords,partial:!1,timestamp:B.timestamp}:(this.pruneAfterBackup(t.orgId),Ve(this.deps,e,{objects:f.map(C=>({objectApiName:C.objectApiName,recordCount:C.recordCount})),totalRecords:B.totalRecords,...B.partial?{status:"partial"}:{}}),this.dmlTracker.markCompleted(e),B.partial?E?.partial():E?.complete(),{operationId:e,objects:f,totalRecords:B.totalRecords,partial:B.partial,timestamp:B.timestamp})}catch(y){o||this.dmlTracker.markFailed(e);let b=y instanceof Ot,I=b||y instanceof cn||t.failWhenTruncated===!0||o!==void 0?void 0:await this.keepFailedBackup({operationId:e,orgId:t.orgId,cap:g,...t.origin?{origin:t.origin}:{}},k,{taken:f,reading:S,planned:t.objects},u);I===void 0&&await u.discard().catch(R=>{this.deps.log(`[WARN] backup ${e}: what it wrote before it stopped was not removed: `+P(R))});let N=I===void 0?y:new Error(`${P(y)} \u2014 the backup keeps the ${I.totalRecords} record(s) read before it stopped, listed as partial: ${Ns(I.objects)}.`);c=N,b&&!o&&this.deps.infraServices?.backgroundRegistry?.abort(e),b?E?.cancel():E?.fail(P(N));let D=!(y instanceof Wt)||y.retryable;return{error:N,retryable:D,context:r,cancelled:b}}finally{s?.removeEventListener("abort",p),d(c),o||this.activeOrgOperations.delete(a),this.backupsWriting.delete(e)}}backupCap(){return di(this.deps.services?.getSandforgeSetting?.("backup.maxRecordsPerObject",ko))}snapshotCapWay(e,t){let n=this.backupCap(),s=e.filter(d=>d.tally.total>n),r=s.length>0?s.map(d=>d.tally.objectApiName).join(", "):"the object",o=s.reduce((d,c)=>Math.max(d,Rn(c.tally.total,n)),1),a=n<an&&s.every(d=>d.tally.total<=an);return t==="step"?`A pipeline's step masks no slices: mask ${r} from the DataOps panel, in slices each backed up just before it is masked, or with sandforge dataops anonymize --slices.`:t===void 0&&this.onCommandLine?`Give --slices to mask ${r} in ${o} slices, each with its own snapshot (the same line with --dry-run shows the plan)`+(a?`, --max-records up to ${an} (this run held ${n})`:"")+", or narrow the run with --where.":`Tick "Mask in slices" in the confirmation: ${r} is then masked in ${o} slices, each backed up just before it is masked`+(a?`; or raise sandforge.backup.maxRecordsPerObject in Settings (this run held ${n}, 1,000,000 at most)`:"")+"."}backupWriter(e){let t=this.backupRecords;if(t){let s=new Set;return{begin:async r=>{s.add(r),await t.begin(e,r).catch(o=>{throw new cn(o)})},append:async(r,o)=>{await t.append(e,r,o).catch(a=>{throw new cn(a)})},keep:()=>{},discard:async()=>{for(let r of s)await t.delete(e,r)}}}let n=new Map;return{begin:async s=>{n.set(s,[])},append:async(s,r)=>{n.get(s)?.push(...r)},keep:()=>{for(let[s,r]of n)this.deps.configStore.set(`backup:${e}:${s}`,r,"backups")},discard:async()=>{n.clear()}}}async readIntoBackup(e,t,n,s,r,o,a){let d=r.scanAll===!0,c=()=>r.onRequest?.(),l={headers:{"Sforce-Query-Options":`batchSize=${r.pageSize}`},maxFetch:1e4,autoFetch:!1,scanAll:d,responseTarget:"QueryResult"},p=r.select;if(p===void 0){let y=await this.selectAllFields(e,t,r.viewsEncrypted);p=y.select,y.notKept.length>0&&(n.notKept=y.notKept)}let g=d?wi(r.where):r.where,u=r.slice,f=u?Yr(t,p,g,u.bounds,u.size):`SELECT ${p} FROM ${t}${xn(g,void 0)}`,S=r.stamp??Xs(f)?.stamp,k=Qs(f,S===void 0?void 0:["Id",S]),E=d||r.whole===!0?y=>(c(),Ai(e,y,d,t)):y=>(c(),Et(e,y)),j=await e.query(k?.first??f,l);if(c(),Ye(e.limitInfo,`dataops:backup query ${t}`),!u&&typeof j.totalSize=="number"&&Number.isInteger(j.totalSize)&&(n.orgCount=j.totalSize),!u&&r.whole===!0&&n.orgCount!==void 0&&n.orgCount>r.cap)throw uo(t,n.orgCount,r.cap);for(await s.begin(n.objectApiName);;){let y=r.cap-n.recordCount,b=j.records.length>y,I=b?j.records.slice(0,y):j.records,N=I;k&&S!==void 0?N=await Ys(I,k,E,{stamp:S,...d?{idsWhere:Cs}:{}}):k&&await Vs(I,k,E);let D=j.done?void 0:j.nextRecordsUrl;if(r.whole===!0&&!j.done&&D===void 0)throw new Wt(yo(t,n.recordCount+N.length),!0);let R=b||D!==void 0&&n.recordCount+N.length>=r.cap;if(u){let A=N.at(-1)?.Id;typeof A=="string"&&(n.lastId=A);let B=u.skip?N.filter(C=>!u.skip?.(C)):N;if(await s.append(n.objectApiName,B),n.recordCount+=B.length,n.readCount=(n.readCount??0)+N.length,R||D===void 0)return;if(a(),o.aborted)throw new Ot;j=await e.queryMore(D,l),c(),Ye(e.limitInfo,`dataops:backup query ${t}`);continue}if(R&&r.whole===!0)throw uo(t,n.orgCount,r.cap);if(await s.append(n.objectApiName,N),n.recordCount+=N.length,R){n.truncated=!0,n.stoppedAt="cap";return}if(D===void 0)return;if(a(),o.aborted)throw new Ot;j=await e.queryMore(D,l),c(),Ye(e.limitInfo,`dataops:backup query ${t}`)}}saveBackupMeta(e,t,n,s){let r={operationId:e.operationId,orgId:e.orgId,...e.organizationId!==void 0?{organizationId:e.organizationId}:{},...e.origin!==void 0?{origin:e.origin}:{},...e.setId!==void 0?{setId:e.setId}:{},...e.slice!==void 0?{slice:e.slice}:{},objects:t.map($s),partial:t.some(o=>o.truncated),...s?{status:"failed"}:{},cap:e.cap,timestamp:new Date().toISOString(),totalRecords:t.reduce((o,a)=>o+a.recordCount,0)};return this.deps.configStore.set(`backup:${e.operationId}`,r,"backups"),n.keep(),r}async keepFailedBackup(e,t,n,s){let{taken:r,reading:o}=n,a=o?[...r,{...o,truncated:!0,stoppedAt:"failure"}]:[...r],d=new Set(a.map(p=>p.objectApiName.toLowerCase())),c=n.planned.filter(p=>!d.has(p.toLowerCase())).map(p=>({objectApiName:p,recordCount:0,truncated:!0,stoppedAt:"not_reached"})),l=[...a,...c];if(!l.every(p=>p.recordCount===0))try{let p=t?await this.organizationIdOf(t):void 0,g=this.saveBackupMeta({...e,organizationId:p},l,s,!0);return this.pruneAfterBackup(e.orgId),{...g,objects:l}}catch(p){this.deps.log(`[WARN] backup ${e.operationId}: the rows read before it failed were not kept: `+P(p));try{this.deps.configStore.delete(`backup:${e.operationId}`)}catch{}return}}async expireBackups(e){let t=Sr(this.deps.services);if(t<=0)return;let n=e-t*li;try{let s=this.retentionSince(e);for(let r of this.backupMetaKeys()){let o=this.deps.configStore.get(r),a=Date.parse(o?.timestamp??"");if(!Number.isFinite(a)||a>=n||a<s||o?.origin==="checkpoint"||o?.origin==="slice"||o?.orgId!==void 0&&this.backupBusy(o.orgId))continue;await this.removeBackup(r);let d=o?.origin==="sync"?` \u2014 the values the Sync run ${o.runId??"(unknown)"} wrote over, which removing that run no longer puts back`:"";this.deps.log(`[INFO] Removed backup ${r}: taken more than ${t} day(s) ago${d}`),this.expiryListener?.({operationId:r.slice(7),days:t,...o?.timestamp!==void 0?{takenAt:o.timestamp}:{},...o?.origin==="sync"?{syncRunId:o.runId??""}:{}})}for(let r of this.sliceSets.list()){let o=Date.parse(r.lastActivityAt);!Number.isFinite(o)||o>=n||o<s||this.backupBusy(r.orgId)||(await this.removeSliceSet(r),this.deps.log(`[INFO] Removed set of slices ${r.setId}: last moved more than ${t} day(s) ago`+(r.state==="open"?", its run left open and now over":"")),this.expiryListener?.({operationId:r.setId,days:t,takenAt:r.startedAt}))}}catch(s){this.deps.log(`[WARN] the backups past their age were not removed: ${P(s)}`)}}async removeSliceSet(e){for(let t of e.objects)for(let n of t.slices)await this.removeBackup(`backup:${n.snapshotId}`),await this.backupRecords?.delete(n.snapshotId,mo(t.objectApiName));this.sliceSets.delete(e.setId),e.kind==="masking"&&e.state==="open"&&e.templateId!==void 0&&new nt(this.deps.configStore).clear(e.orgId,e.templateId),await this.runKeys?.delete(e.setId).catch(t=>{this.deps.log(`[WARN] the key of set ${e.setId} was not removed: ${P(t)}`)})}retentionSince(e){let t=Date.parse(this.deps.configStore.get(eo)??"");return Number.isFinite(t)?t:(this.deps.configStore.set(eo,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 r of n)this.deps.configStore.delete(`${e}:${r.objectApiName}`);this.deps.configStore.delete(e);let s=e.slice(7);for(let r of n)await this.backupRecords?.delete(s,r.objectApiName)}async handleBackupDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(rr,e,"dataops:error",this.deps);if(!t)return;if(this.backupBusy(t.orgId)){H(this.deps,"backup:delete","dataops:error",e,new Error(this.busyMessage(t.orgId,`A backup or rollback operation is already running for org ${t.orgId}. Delete its backups once it has ended.`)),{code:Is});return}let n=t.operationIds?new Set(t.operationIds):void 0;for(let o of n??[]){let a=this.deps.configStore.get(`backup:${o}`);if(!(a?.origin!=="slice"||a.orgId!==t.orgId)){H(this.deps,"backup:delete","dataops:error",e,new Error(`Backup ${o} is slice ${a.slice?.index??"?"} of set ${a.setId??"?"}: a slice is deleted with its set, which holds the way back of every slice. Delete set ${a.setId??"?"} to delete it. Nothing was deleted.`),{code:Re.deleteAlone});return}}let s=[];try{for(let o of this.backupMetaKeys()){let a=this.deps.configStore.get(o);if(a?.orgId!==t.orgId||a.origin==="slice")continue;let d=a.operationId??o.slice(7);n&&!n.has(d)||(await this.removeBackup(o),s.push(d))}for(let o of this.sliceSets.list(t.orgId))n&&!n.has(o.setId)||(await this.removeSliceSet(o),s.push(o.setId))}catch(o){H(this.deps,"backup:delete","dataops:error",e,o);return}this.deps.log(`[INFO] Deleted ${s.length} backup(s) of org ${t.orgId}`);let r=ke(this.deps,e,"backup:delete:result",{orgId:t.orgId,deleted:s});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} deleted=${s.length}`)}pruneAfterBackup(e){try{this.pruneBackups(e)}catch(t){this.deps.log(`[WARN] backup retention failed after the snapshot was written: ${P(t)}`)}this.sweepBackupFiles()}handleBackupList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(tr,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 a=this.deps.configStore.get(o);!a||a.orgId!==t.orgId||a.origin!=="slice"&&n.push({operationId:a.operationId??o.slice(7),orgId:a.orgId,timestamp:a.timestamp??"",totalRecords:a.totalRecords??0,totalSize:0,status:a.status==="failed"?"failed":"completed",objectResults:(a.objects??[]).map($s),...a.partial?{partial:!0}:{},...a.origin==="sync"?{origin:"sync"}:{}})}n.sort((o,a)=>a.timestamp.localeCompare(o.timestamp));let s=this.sliceSets.list(t.orgId).map(Cr).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt)),r=ke(this.deps,e,"backup:list:result",{backups:n,...s.length>0?{sets:s}:{}});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=Se(sr,e,"dataops:error",this.deps);if(!t)return;let n=`backup:${t.operationId}`,s=this.deps.configStore.get(n);if(!s||s.orgId!==t.orgId){H(this.deps,"backup:export","dataops:error",e,new Error(`Backup not found: ${t.operationId}`),{code:"BACKUP_NOT_FOUND"});return}let r=await this.saveDialog.saveStream(`sandforge-backup-${t.operationId}.json`,a=>this.writeBackupDocument(t,s,a),["json"]);if(r.status==="error"){H(this.deps,"backup:export","dataops:error",e,new Error(r.message));return}let o=ke(this.deps,e,"backup:export:result",r.status==="saved"?{operationId:t.operationId,status:"saved",path:r.path,objects:r.result}:{operationId:t.operationId,status:"cancelled"});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} ${r.status}`)}async writeBackupDocument(e,t,n){let{operationId:s}=e,o=[["sandforgeBackupVersion",1],["operationId",s],["orgId",e.orgId],["timestamp",t.timestamp??""],["totalRecords",t.totalRecords??0]].map(([d,c])=>` "${d}": ${JSON.stringify(c)},
8
+ `);await n(`{
9
+ ${o.join("")} "objects": {`);let a=[];for(let{objectApiName:d}of t.objects??[]){if(a.some(l=>l.objectApiName===d))continue;await n(`${a.length>0?",":""}
10
+ ${JSON.stringify(d)}: [`);let c=0;for await(let l of await this.backupBatches(s,d))l.length!==0&&(await n(l.map((p,g)=>`${c+g>0?",":""}
11
+ ${JSON.stringify(p)}`).join("")),c+=l.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,Dt);if(n)return n;let s=this.deps.configStore.get(`backup:${e}:${t}`),r=Array.isArray(s)?s:[];return{async*[Symbol.asyncIterator](){for(let o=0;o<r.length;o+=Dt)yield r.slice(o,o+Dt)}}}async firstBackupRecord(e,t,n){let s=await this.backupBatches(e,t),r=n.origin==="sync"?ms(s,Dt).batches:s;for await(let o of r)if(o[0]!==void 0)return o[0]}pruneBackups(e){let t=this.deps.services?.getSandforgeSetting?.("backup.maxCount",10)??10,n=[];for(let s of this.deps.configStore.getKeysByPrefix("backup:")){if(s.slice(7).includes(":"))continue;let o=this.deps.configStore.get(s);o?.orgId===e&&o.origin!=="sync"&&o.origin!=="checkpoint"&&o.origin!=="slice"&&n.push({key:s,timestamp:o.timestamp??""})}if(!(n.length<=t)){n.sort((s,r)=>s.timestamp.localeCompare(r.timestamp));for(let{key:s}of n.slice(0,n.length-t))this.removeBackup(s),this.deps.log(`[INFO] Pruned backup ${s} (retention: ${t} per org)`)}}async undeleteFromRecycleBin(e,t,n){let s=[];for await(let o of n){let a=o.map(c=>c.Id).filter(c=>typeof c=="string");if(a.length===0)continue;let d=a.map(c=>`'${Gs(c)}'`).join(", ");try{let c=await e.query(`SELECT Id FROM ${t} WHERE Id IN (${d}) AND IsDeleted = true`,{scanAll:!0});s.push(...c.records.map(l=>l.Id))}catch(c){return this.deps.log(`[WARN] Rollback on ${t}: could not look for deleted records \u2014 ${P(c)}`),{undeleted:0}}}let r=0;for(let o=0;o<s.length;o+=200){let a=await e.soap.undelete(s.slice(o,o+200));r+=a.filter(d=>d.success).length}return{undeleted:r}}refuseWithoutGuard(e,t,n,s){be(this.deps,{...s,outcome:"stopped",source:void 0,code:Vt.code}),e(new Error(Vt.message),{code:Vt.code}),pe(this.deps,t,Vt.message,!1,{context:n,authored:!0})}async handleRollback(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(or,e,"dataops:error",this.deps);if(!t)return;let n=t,s=e.id,r={module:"dataops",operation:e.type},o=`backup:${n.orgId}`;if(this.activeOrgOperations.has(o)){let k=this.busyMessage(n.orgId,`A backup or rollback operation is already running for org ${n.orgId}. Please wait for it to complete.`);this.deps.log(`[WARN] ${k}`),H(this.deps,"dataops:rollback","dataops:error",e,new Error(k)),pe(this.deps,s,k,!1,{context:r,authored:!0});return}this.activeOrgOperations.add(o);let a,d,c=[],l=!1,p=new AbortController,g=()=>{},u,f,S;try{if(this.dmlTracker.isDuplicate(s)){this.deps.log(`[WARN] Duplicate rollback operation detected: ${s}`),H(this.deps,"dataops:rollback","dataops:error",e,new Error(`Duplicate operation: ${s}`)),pe(this.deps,s,`Duplicate operation: ${s}`,!1,{context:r,authored:!0});return}this.dmlTracker.register(s,"rollback","upsert",0);let k=await ze(n.orgId,this.deps.orgRegistry,this.deps.orgManager),E=new Xn(async $=>{let z=await k.describe($);return bo(z)}),j=`backup:${n.operationId}`,y=this.deps.configStore.get(j),b=this.restoreOfSet(n,y);if("refused"in b){H(this.deps,"dataops:rollback","dataops:error",e,new Error(b.refused.message),{code:b.refused.code}),pe(this.deps,s,b.refused.message,!1,{context:r,authored:!0});return}d=b.set;let I=b.meta??y;if(!I)throw new Error(`No backup found for operation ${n.operationId}. Cannot rollback.`);let N=b.parts??I.objects.map($=>({snapshotId:n.operationId,objectApiName:$.objectApiName,recordCount:$.recordCount}));if(I.orgId!==n.orgId){let $=Pt(this.deps.orgManager.getOrg(I.orgId),I.orgId),z=Pt(this.deps.orgManager.getOrg(n.orgId),n.orgId);throw new Error(`Backup ${n.operationId} was taken from org ${I.orgId} and cannot be restored into org ${n.orgId}. A restore writes back by record Id, and an Id belongs to the org that holds it: to bring these records from ${$} into ${z}, copy them with Forge or Sync.`)}a={action:"backup_restore",module:"dataops",operationId:s,orgId:n.orgId,outcome:"failure",source:{origin:"backup",label:I.timestamp?.slice(0,16).replace("T"," ")??n.operationId}};let D=this.deps.infraServices?.productionGuard;if(!D){this.refuseWithoutGuard(($,z)=>H(this.deps,"dataops:rollback","dataops:error",e,$,z),s,r,a);return}let R=[],A=new Set;for(let $ of N){if(A.has($.objectApiName.toLowerCase()))continue;let z=await this.firstBackupRecord($.snapshotId,$.objectApiName,I);if(z===void 0)continue;A.add($.objectApiName.toLowerCase());let M=xe($.objectApiName);if(!(await E.checkCrudPermission(M,"upsert")).allowed){R.push({objectApiName:M,operation:"upsert",deniedFields:[]});continue}let{denied:Ke}=await E.partitionWritableFields(M,"upsert",Object.keys(z).filter(Oe=>Oe!=="attributes"));Ke.length>0&&R.push({objectApiName:M,operation:"upsert",deniedFields:Ke})}if(R.length>0){let $=bn(R);this.deps.log(`[WARN] CRUD/FLS check failed for rollback ${s}: ${$}`),be(this.deps,{...a,outcome:"stopped",source:void 0,code:xt}),H(this.deps,"dataops:rollback","dataops:error",e,new Error($),{code:xt}),pe(this.deps,s,$,!1,{context:r,authored:!0});return}let B=($,z,M,de=[])=>{be(this.deps,{...M,outcome:"stopped",source:void 0,code:$}),H(this.deps,"dataops:rollback","dataops:error",e,new Error(z),{code:$,...os({alsoRefused:de})}),pe(this.deps,s,z,!1,{context:r,authored:!0})},C=await this.readAct(k,n.orgId,"restore",I.objects.map($=>({objectApiName:$.objectApiName,records:$.recordCount})),n,Jt(n)),ee=yn(C.answer);if(ee){B(ee.code,ee.message,a,ee.alsoRefused);return}S=this.duplicatesWatchOf(k,ts(C.answer.automation,I.objects.filter($=>$.recordCount>0).map($=>$.objectApiName)));let G=this.deps.orgManager.getOrg(n.orgId),W={orgId:n.orgId,orgTier:Rs(G),operation:"upsert",objectName:I.objects.map($=>$.objectApiName).join(", ")||"RollbackData",recordCount:I.totalRecords??0,module:"dataops"},{check:X,decision:ve}=await Zn(D,W);if(a.guard=ve,(ve==="refused"||ve==="declined")&&be(this.deps,{...a,outcome:"stopped",source:void 0}),ve==="refused")throw qn(X.blockedReason??X.impactSummary);if(ve==="declined"){let $="Operation cancelled by user (confirmation declined).";H(this.deps,"dataops:rollback","dataops:error",e,new Error($),{code:Kn.declined}),pe(this.deps,s,$,!1,{context:r,authored:!0});return}if(I.organizationId!==void 0){let $=await this.organizationIdOf(k);if($!==void 0&&!ri(I.organizationId,$)){let z=Pt(G,n.orgId),M=this.deps.infraServices?.confirmRestoreIntoReplacedOrg;if(!(M?await M({alias:z,backedUpFrom:I.organizationId,now:$}):!1)){be(this.deps,{...a,outcome:"stopped",source:void 0,code:Jr});let Ke=`Restore not run: ${z} answers as org ${$}, not as org ${I.organizationId}, which backup ${n.operationId} was taken from, `+(M?"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.");H(this.deps,"dataops:rollback","dataops:error",e,new Error(Ke),{code:Jr}),pe(this.deps,s,Ke,!1,{context:r,authored:!0});return}}}let kt=await rs(C,s,n.acceptEmails===!0,Jt(n));if("refused"in kt){B(kt.refused.code,kt.refused.message,a);return}f=kt.held,Yt(this.deps,s,"dataops",`Rollback ${I.objects.length} object(s)`);let Ge=b.skipped??[];l=!0,this.deps.infraServices?.backgroundRegistry?.register(s,"dataops",`Rollback ${I.objects.length} object(s)`,new Promise(($,z)=>{g=M=>{M===void 0?$():z(M instanceof Error?M:new Error(String(M)))}}),p),u=rn(this.liveTracker,s,"dataops",`Rollback ${I.objects.length} object(s)`,I.objects.length);let we=!1,Ce=0,$e=0,Je=0,ot=[],wt=new Map,Ut=I.origin==="sync"&&n.includeChanged!==!0,Be=Number.NEGATIVE_INFINITY,F=!1;if(Ut){let $=I.runId!==void 0?await this.syncRuns?.get(I.runId).catch(M=>{this.deps.log(`[WARN] Rollback: the Sync run of backup ${n.operationId} could not be read \u2014 ${P(M)}`)}):void 0,z=$?hr($):void 0;F=z===void 0,Be=await gr({serverTime:async()=>(await k.soap.getServerTimestamp()).timestamp},z)}let Q=[];for(let $=0;$<N.length;$++){if(p.signal.aborted){we=!0;break}let z=N[$],M=xe(z.objectApiName);r.objectName=M;let de=await this.backupBatches(z.snapshotId,z.objectApiName),Ke=I.origin==="sync"?ms(de,Dt):void 0,Oe=Ke?.batches??de,De;for await(let ce of Oe)if(De=ce[0],De!==void 0)break;if(Ut&&De!==void 0){let ce=[];for await(let Fe of Oe)for(let Pe of Fe)typeof Pe.Id=="string"&&ce.push(Pe.Id);let tt=await Kr({query:async(Fe,Pe)=>({records:(await k.query(Fe,Pe)).records})},M,ce,Be);tt.size>0&&(Q.push({objectApiName:M,count:tt.size}),Oe=qr(Oe,tt))}if(De===void 0){wt.set(z.objectApiName,wt.get(z.objectApiName)??0),this.deps.log(`[WARN] No backup records for ${z.objectApiName}, skipping.`);continue}let pn=Object.keys(De).filter(ce=>ce!=="attributes"),{skipped:it}=await E.partitionWritableFields(M,"upsert",pn),at=new Set(it.filter(ce=>ce.toLowerCase()!=="id").map(ce=>ce.toLowerCase()));at.size>0&&this.deps.log(`[INFO] Rollback on ${M}: ${at.size} non-writable field(s) excluded from the payload \u2014 ${[...at].sort().join(", ")}`);let yt=await this.undeleteFromRecycleBin(k,M,Oe);yt.undeleted>0&&this.deps.log(`[INFO] Rollback on ${M}: ${yt.undeleted} record(s) brought back from the recycle bin`),r.batchSize=Dt;let dt=0,ct=0,Te=0,At=0;for await(let ce of Oe){if(p.signal.aborted){we=!0;break}At+=ce.length;let tt=ce.map(le=>{let qe=M===se?mn(le,!1):void 0,Z={};for(let[He,ut]of Object.entries(le))He!=="attributes"&&(at.has(He.toLowerCase())||qe!==void 0&&fn(se,He,qe)||(Z[He]=ut));return Z}),Fe=tt;if(n.rewriteAll!==!0){let le=await Ur({query:async qe=>{let Z=await k.query(qe);return{totalSize:Z.totalSize,records:Z.records}}},M,tt);le.unread!==void 0&&this.deps.log(`[WARN] Rollback on ${M}: the org's values could not be read, so ${tt.length} row(s) are written back without comparing \u2014 ${le.unread}`),Fe=le.write,Te+=le.unchanged}if(Fe.length===0)continue;S.beforeWrite(M);let Pe;try{Pe=await k.sobject(M).upsert(Fe,"Id",{headers:Wn()})}catch(le){throw Jn(le)==="may-have-written"&&S.wrote(M,Fe.map(qe=>qe.Id)),le}let qt=Array.isArray(Pe)?Pe:[Pe];S.wrote(M,qt.flatMap((le,qe)=>le.success?[Fe[qe]?.Id]:[]));for(let le of qt){if(le.success){dt++;continue}ct++,to(ot,M,le.errors)}}Ye(k.limitInfo,`dataops:rollback upsert ${M}`),wt.set(z.objectApiName,(wt.get(z.objectApiName)??0)+(Ke&&!we?Ke.lines():At)),Ce+=dt,$e+=ct,Je+=Te;let Kt=c.find(ce=>ce.objectApiName===M);if(Kt?(Kt.updated+=dt,Kt.failed+=ct):c.push({...gn(M),updated:dt,failed:ct}),z.slice&&(Ge.push({index:z.slice.index,objectApiName:M,restored:dt,failed:ct,unchanged:Te}),!we&&d&&(z.slice.restoredAt=new Date().toISOString(),z.slice.state="restored",d.lastActivityAt=z.slice.restoredAt,this.sliceSets.save(d))),we)break;let jt=`Restored ${M}${z.slice?` slice ${z.slice.index}`:""} (${dt}/${At}${Te>0?`, ${Te} unchanged`:""})`,lt=Math.round(($+1)/N.length*100);Mt(this.deps,s,lt,$+1,N.length,jt),u.progress(lt,$+1,N.length,jt)}let re=Q.reduce(($,z)=>$+z.count,0),U=ui(Ce,$e),te=we&&$e===0||re>0&&U==="success"?"partial":U;a&&(l=!1,be(this.deps,{...a,...we?Ce+$e>0?{outcome:"cancelled"}:{outcome:"stopped",code:Gn}:{outcome:te},objects:c}));let Tt=await this.releaseMute(f,n.orgId);f=void 0;let Xe=await S.read();we?(this.deps.infraServices?.backgroundRegistry?.abort(s),Ve(this.deps,s,{aborted:!0,totalRestored:Ce,totalFailed:$e,totalUnchanged:Je})):Ve(this.deps,s,{status:te,totalRestored:Ce,totalFailed:$e,totalUnchanged:Je}),this.dmlTracker.markCompleted(s),we?u.cancel():te==="failure"?u.fail(`The org refused the ${$e} record(s)`):te==="partial"?u.partial():u.complete();let Le=Ns(I.objects,wt),et=(we?`Rollback cancelled: ${Ce} records restored before the cancel; the rest still hold the values they had, and the same restore puts them back`:$e>0?`Rollback ${te}: ${Ce} restored, ${$e} rejected by the org`:re>0?`Rollback partial: ${Ce} records restored`:`Rollback completed: ${Ce} records restored`)+(Je>0?`; ${Je} already held the backup's values and were not written`:"")+(re>0?`; ${re} changed or deleted since the Sync run were left as they are `+(F?"(the run is no longer kept here, so every record reads as changed since it) ":"")+"unless the restore includes them":""),me=Zt(Xe,this.orgNameOf(n.orgId),"restore"),Ne=Le===""?et:`${et}. The backup held only part of the org's records, and the rest were left as they are: ${Le}`,Qe=me?`${Ne}. ${me}`:Le===""?Ne:`${Ne}.`,ae=ke(this.deps,e,"dataops:rollback:response",{operationId:n.operationId,status:te,message:Qe,totalRestored:Ce,totalFailed:$e,totalUnchanged:Je,...n.rewriteAll===!0?{rewriteAll:!0}:{},...n.includeChanged===!0?{includeChanged:!0}:{},...re>0?{keptChanged:{total:re,objects:Q,...F?{runNotKept:!0}:{}}}:{},errors:ot,...Le!==""?{partial:!0}:{},...we?{cancelled:!0}:{},...Tt?{mutedAutomation:Tt}:{},...Xe?{duplicates:Xe}:{},...d?{slices:Ge}:{}});this.deps.broker.postToWebview(ae),this.deps.log(`[TX] ${ae.type} id=${ae.id} status=${te}`),($e>0||Le!==""||we||re>0||ss(Xe))&&hn(this.deps,te==="failure"?"error":"warning","Restore",`${Qe}${ot[0]?` \u2014 e.g. ${ot[0].message}`:""}`)}catch(k){this.dmlTracker.markFailed(s),await this.releaseMute(f,n.orgId),f=void 0;let E=await S?.read(),j=Zt(E,this.orgNameOf(n.orgId),"restore");H(this.deps,"dataops:rollback","dataops:error",e,j?new Error(`${P(k)} ${j}`):k,{code:Hn(k),...E?{extraPayload:{duplicates:E}}:{}}),pe(this.deps,s,P(k),!0,{context:r}),u?.fail(P(k))}finally{await this.releaseMute(f,n.orgId),this.activeOrgOperations.delete(o),g(),l&&a&&be(this.deps,{...a,outcome:"failure",objects:c})}}async snapshotBeforeMasking(e,t,n,s,r){let o=new Map,a=new Map;try{for(let l of s){if(l.tally.total===0)continue;l.where!==void 0&&a.set(l.tally.objectApiName,l.where);let{select:p}=await this.maskedFields(e,l.tally.objectApiName,this.maskingRules(l.objectName,l.objectRules),this.maskingRules(l.objectName,l.personRules));p!=="Id"&&o.set(l.tally.objectApiName,p)}}catch(l){return{refused:`No snapshot was taken, so nothing was masked: ${P(l)}`,retryable:!0}}if(o.size===0)return{};let d=`${t}-snapshot`,c=await this.takeBackup(d,{orgId:n,objects:[...o.keys()],...a.size>0?{wheres:a}:{},fields:o},r.origin,r.stop);return"error"in c?(this.endBackupNotTaken(d,c),{refused:`No snapshot was taken, so nothing was masked: ${P(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 (${Ns(c.objects)}). `+this.snapshotCapWay(s),retryable:!1}:{taken:{operationId:d,totalRecords:c.totalRecords}}}async maskingNotCovered(e,t,n,s){if(s.length===0)return{code:Ue.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 r=[],o=[];for(let d of s){if(d.tally.total===0)continue;let{objectApiName:c}=d.tally,{rules:l,missing:p}=await this.maskedFields(e,c,this.maskingRules(d.objectName,d.objectRules),this.maskingRules(d.objectName,d.personRules));r.push(...p.map(g=>({objectApiName:c,fieldApiName:g}))),l.length===0&&o.push(c)}let a={fieldsNotFound:r,objectsNotCovered:o};if(r.length>0){let d=r.map(c=>`${c.objectApiName}.${c.fieldApiName}`).join(", ");return{code:Ue.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. `+(o.length>0?`No field of ${o.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(o.length>0)return{code:Ue.masksNothing,message:`The template "${t.name}" masks no field of ${o.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 st(Ue.orgUnknown,`The org the masking writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was masked.`);let s=Qr(Rs(n),e.answer,Pt(n,e.orgId));if(s)throw s;let r=ks(e,f=>this.findTemplate(f)!==void 0);if("refusal"in r)throw r.refusal;let o=crypto.randomUUID(),a,d,c,l={origin:"pipeline:execute",pipeline:e.pipeline,accord:e.accord??{},voice:"step",muted:f=>{c=f},refused:(f,S)=>{a??={err:f,...S},this.deps.log(`[ERR] dataops:anonymize ${o} for the pipeline "${e.pipeline.name}": `+P(f))},ended:f=>{d=f}};await this.writing.during(e.orgId,()=>Ir(e.answer,()=>this.mask(r.asked,o,l,t)));let p=a,g=c;if(p){let f=P(p.err),S=p.err,k=p.code??(typeof S?.code=="string"?S.code:void 0),E=p.extraPayload?.snapshot,j={...k!==void 0?{code:k}:{},...E!==void 0?{snapshot:E}:{},...g?{mutedAutomation:g}:{}};throw Object.assign(k===Qt?new wn(f):new Error(f),j)}let u=d;if(u===void 0)throw new Error("The masking run ended without a result.");return{operationId:o,result:g?{...u,mutedAutomation:g}:u}}async previewMaskingForPipeline(e,t){let n=(b,I)=>st(b,I),s=()=>new wn("The dry run of the masking was stopped: nothing was masked.");if(!this.deps.orgManager.getOrg(e.orgId))throw n(Ue.orgUnknown,`The org the masking writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was masked.`);let r=ks(e,b=>this.findTemplate(b)!==void 0);if("refusal"in r)throw r.refusal;let o=r.asked,a=this.findTemplate(o.templateId);if(!a)throw Ts(o.templateId);let d=this.sliceSets.openFor(o.orgId,o.templateId);if(d)throw n(Re.runOpen,this.sliceRunOpenMessage(d,"step"));let c=await ze(o.orgId,this.deps.orgRegistry,this.deps.orgManager),l=Cn(c),p=await this.plannedObjectsIn(l,o,a),g=[];for(let b of p){if(t?.aborted)throw s();let I=Ft(a,b),N=dn(a,b);if(I.length===0&&N.length===0)continue;let D=xe(b),R=jn(o,a,b),A;try{A=await this.countRows(c,D,void 0,R)}catch(B){throw this.countGaveUp(B,D)}g.push({objectName:b,...R!==void 0?{where:R}:{},objectRules:I,personRules:N,tally:{objectApiName:D,total:A,masked:0,nothingToMask:0,refused:0,unanswered:0,done:A===0},progress:{objectApiName:D,done:A===0,refused:[]}})}let u=await this.maskingNotCovered(l,a,p,g);if(u)throw n(u.code,u.message);let f=g.filter(b=>b.tally.total>0),S=await vs(l,f.map(b=>({objectApiName:b.tally.objectApiName,rules:[...b.objectRules,...b.personRules]})));if(S.length>0)throw n(xt,bn(S));let k=this.backupCap();if(g.some(b=>b.tally.total>k))throw n(on,`Nothing was masked: ${g.filter(b=>b.tally.total>k).map(b=>`${b.tally.objectApiName} holds ${b.tally.total} record(s)`).join(", ")}, more than the ${k} a snapshot holds of one object. `+this.snapshotCapWay(g,"step"));if(t?.aborted)throw s();let E=await this.readAct(c,o.orgId,"masking",g.map(b=>({objectApiName:b.tally.objectApiName,records:b.tally.total})),e.accord??{},"step"),j=yn(E.answer);if(j)throw n(j.code,j.message);let y=[];for(let b of g){let{rules:I}=await this.maskedFields(l,b.tally.objectApiName,this.maskingRules(b.objectName,b.objectRules),this.maskingRules(b.objectName,b.personRules));y.push({objectApiName:b.tally.objectApiName,records:b.tally.total,fields:[...new Set(I.map(N=>N.fieldApiName))].filter(N=>N!=="Id")})}return{objects:y,records:y.reduce((b,I)=>b+I.records,0)}}async handleAnonymize(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(kn,e,"dataops:error",this.deps);if(!t)return;let n=Jt(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)=>H(this.deps,"dataops:anonymize","dataops:error",e,t,n),ended:t=>{let n=ke(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||ss(t.duplicates))&&hn(this.deps,t.status==="failure"?"error":"warning","Anonymize",`${t.message}${t.errors[0]?` \u2014 e.g. ${t.errors[0].message}`:""}`)}}}pageSizeFor(e){let t=this.deps.orgManager.getOrg(e);return An(In(t?.orgType==="Sandbox"||t?.orgType==="Scratch")).defaultQueryLimit}sliceWays(e){return e==="page"?{resume:"Resume",abandon:"Abandon",restore:()=>"Restore lists the set and puts its values back"}:e===void 0&&this.onCommandLine?{resume:"the same line with --resume",abandon:"--abandon",restore:t=>`the same command with --restore ${t} puts its values back`}:{resume:"Resume on the DataOps panel, or sandforge dataops anonymize --resume",abandon:"Abandon on the DataOps panel, or sandforge dataops anonymize --abandon",restore:()=>"the Restore tab of the DataOps panel lists the set and puts its values back"}}async approximateCount(e,t,n){if(js.has(Pn(n)))try{let s=await e.request(`/services/data/v${e.version}/limits/recordCount?sObjects=${t}`),{recordCountsOf:r}=await import("./chunk-XC54KKKC.mjs"),o=r(s)?.get(t);return o!==void 0&&this.deps.log(`[INFO] dataops:anonymize: the org gave up counting ${t}; its own figure, ${o}, plans the slices, approximate.`),o}catch(s){this.deps.log(`[WARN] dataops:anonymize: the org's figure of ${t} was not read: `+P(s));return}}async apiBudgetFor(e,t){let{apiBudgetCheckOf:n,readApiBudget:s}=await import("./chunk-W2AAGIZF.mjs"),r=await s(e).catch(a=>({unread:P(a)})),o=n(t,r);return o.verdict==="unread"?{verdict:"unread",unread:o.unread}:{verdict:o.verdict,remaining:o.remaining,max:o.max}}async sliceRunPlan(e,t,n,s){let r=[];for(let o of t){if(o.tally.total===0)continue;let{select:a}=await this.maskedFields(e,o.tally.objectApiName,this.maskingRules(o.objectName,o.objectRules),this.maskingRules(o.objectName,o.personRules));r.push({objectApiName:o.tally.objectApiName,rows:o.tally.total,fields:a.split(",").length})}return ls(r,n,s,"masking")}tooManySlicesMessage(e,t){let n=e.objects.filter(r=>e.tooMany.includes(r.objectApiName)).map(r=>`${r.objectApiName} (${r.slices} slices)`).join(", "),s=this.onCommandLine?`Give --max-records up to ${an}, so that a slice holds more, or narrow the run with --where.`:"Raise sandforge.backup.maxRecordsPerObject in Settings, up to 1,000,000, so that a slice holds more.";return`Nothing was masked: ${n} would take more than the ${ht} slices a set holds, at ${t} records a slice. ${s}`}diskShortMessage(e,t,n=!1){let s=this.backupRecords?.directory??"the backups folder",r=this.onCommandLine?"give --store a folder on another disk, delete the backups no longer needed (sandforge backup --list, then delete them), or keep backups fewer days (--max-age-days)":"delete the backups no longer needed in the Restore tab, or keep backups fewer days (sandforge.backup.maxAgeDays)";return`${n?"Nothing was masked":"The run stopped between two slices"}: the slices' snapshots take about ${us(e)}, and ${s} has ${us(t)} free. To make room, ${r}.`}sliceBudgetStop(e,t,n,s,r){if(t!==void 0&&n+s>t)return`Stopped between slices: the run sent ${n} request(s), and the next slice takes about ${s} more, past the ${t} of ${r==="page"?"the requests it was given":"--max-requests"}.`;let o=Ye(e.limitInfo,"dataops:anonymize slices");if(o&&o.apiLimit>0&&(o.apiUsage+s)/o.apiLimit*100>=Os)return`Stopped between slices: the org used ${o.apiUsage} of its ${o.apiLimit} daily API requests, and the next slice takes about ${s} more, past the ${Os}% the run leaves the org's integrations below.`}sliceNotTakenMessage(e,t){if(t.code===Re.readTooHeavy){let n=this.onCommandLine?"narrow --where to an indexed field, such as a range of CreatedDate, or give a lower --max-records":"mask it from the command line with --where on an indexed field, such as a range of CreatedDate, or lower sandforge.backup.maxRecordsPerObject";return`The org would not read a slice of ${e} in time, even halved ${fo} times (${P(t.failed)}): the run stopped there, and nothing of that slice was masked. To go on, ${n}.`}return`The snapshot of the next slice of ${e} was not taken (${P(t.failed)}): the run stopped there, and nothing of that slice was masked.`}sliceRunOpenMessage(e,t){let n=$t(e),s=this.sliceWays(t);return`A masking run of this template in slices is still open on ${this.orgNameOf(e.orgId)} (set ${e.setId}, ${n.filter(Bt).length} of ${n.length} slice(s) masked, last moved ${e.lastActivityAt}): a new run would mask its rows again and write over where it stopped. Resume it (${s.resume}), or give it up (${s.abandon}), which masks nothing more and keeps its slices to restore. Nothing was masked.`}sliceKeyLostMessage(e,t){let n=this.sliceWays(t);return`The key set ${e.setId} was masked with is not kept where this run reads it: masked with another, the same address would get another digest and the same record another person. Give the set up (${n.abandon}); ${n.restore(e.setId)} if its values are wanted back, and a new run masks again. Nothing was masked.`}slicesSentence(e,t,n,s,r=[]){let o=this.sliceWays(n),a=$t(e),d=ds(e);return[...t?[t.message]:[],`Set ${e.setId}: ${a.filter(Bt).length} of ${a.length} slice(s) of up to ${e.size} records masked, each backed up just before it was masked; ${o.restore(e.setId)}.`,...d>0?[`${d} record(s) were created during the run in a range a slice had masked, or past its last slice: no snapshot holds them, and they were not masked.`]:[],...r.length>0?[`Whether records were created during the run in a range a slice had masked could not be read for ${r.join(", ")}: any such record was not masked.`]:[],...e.state==="open"&&s?[`${o.resume[0].toUpperCase()}${o.resume.slice(1)} masks the rest, each slice backed up first.`]:[]].join(" ")}async snapshotSlice(e,t,n,s,r,o){let a;try{o.clock!==!1&&(a=new Date((await e.soap.getServerTimestamp()).timestamp).toISOString(),o.onRequest())}catch(c){this.deps.log(`[WARN] dataops: the org's clock before slice ${r.index} was not read: `+P(c))}let d=r.sizeUsed;for(let c=0;;c++){let l=await this.takeBackup(r.snapshotId,{orgId:t,objects:[s.objectApiName],...s.where!==void 0?{wheres:new Map([[s.objectApiName,s.where]])}:{},...o.select!==void 0?{fields:new Map([[s.objectApiName,o.select]])}:{},slice:{setId:n.setId,index:r.index,bounds:o.bounds,size:d,...o.skip?{skip:o.skip}:{},onRequest:o.onRequest}},o.origin,o.stop);if(!("error"in l)){let g=l.objects[0];return{rows:g?.recordCount??0,read:g?.readCount??g?.recordCount??0,...g?.lastId!==void 0?{lastId:g.lastId}:{},sizeUsed:d,...a!==void 0?{readSince:a}:{}}}if(l.cancelled)return{failed:l.error,code:Qt,cancelled:!0};if(!js.has(Pn(l.error)))return{failed:l.error,code:on};if(c>=fo||d<=po)return{failed:l.error,code:Re.readTooHeavy};d=Math.max(po,Math.floor(d/2)),this.deps.log(`[INFO] dataops: the org would not read slice ${r.index} of ${s.objectApiName} in time; read again in ${d} records.`)}}async countLateRows(e,t,n){let s=[],r=async o=>{let a=await e.query(o);return n(),typeof a.totalSize=="number"?a.totalSize:0};for(let o of t.objects)try{let a=o.slices.filter(g=>!g.late&&g.lastId!==void 0),d=a.at(-1)?.lastId,c=await r(d!==void 0?Zr(o.objectApiName,o.where,d):`SELECT COUNT() FROM ${o.objectApiName}${xn(o.where,void 0)}`);c>0?(o.tailLeft=c,o.done=!1):delete o.tailLeft;let l=t.serverStartedAt;if(d===void 0||l===void 0||await r(As(o.objectApiName,o.where,l,{untilId:d}))===0)continue;for(let g of a){if(g.lastId===void 0)continue;let u=await r(As(o.objectApiName,o.where,g.readSince??l,{...g.afterId!==void 0?{afterId:g.afterId}:{},untilId:g.lastId}));u>0?g.lateLeft=u:delete g.lateLeft}}catch(a){this.deps.log(`[WARN] dataops: the ${o.objectApiName} records created during set ${t.setId} were not counted: ${P(a)}`),s.push(`${o.objectApiName} (${P(a)})`)}return s}async abandonSliceSet(e,t,n){if(!e){n.refused(new Error(`No masking run of this template in slices is open on ${this.orgNameOf(t.orgId)}: there is nothing to give up.`),{code:Re.nothingToAbandon});return}if(this.sliceRunsOn.get(t.orgId)===e.setId){n.refused(new Error(this.busyMessage(t.orgId,"")),{code:Is});return}e.state="abandoned",e.lastActivityAt=new Date().toISOString(),this.sliceSets.save(e),new nt(this.deps.configStore).clear(t.orgId,t.templateId),await this.runKeys?.delete(e.setId).catch(a=>{this.deps.log(`[WARN] dataops: the key of set ${e.setId} was not removed: ${P(a)}`)});let r=$t(e).filter(Bt).length,o=this.sliceWays(n.voice);this.deps.log(`[INFO] dataops: set ${e.setId} given up, ${r} slice(s) masked`),n.ended({templateId:t.templateId,status:"success",recordsProcessed:0,recordsFailed:0,recordsNotMasked:0,objects:[],message:`Set ${e.setId} given up: nothing more is masked. Its ${r} masked slice(s) stay masked, each with its snapshot; ${o.restore(e.setId)} until the retention removes them. The records no slice reached keep their values.`,errors:[],abandoned:!0,slices:en(e,{requestsSpent:0})})}async mask(e,t,n,s){let r,o={},a,d=async()=>(a??={released:await this.releaseMute(r,e.orgId)},a.released),c={...n,refused:(F,Q)=>{if(!r){n.refused(F,Q);return}o.answer??=re=>n.refused(F,re?{...Q,extraPayload:{...Q.extraPayload,mutedAutomation:re}}:Q)},ended:F=>{if(!r){n.ended(F);return}o.answer??=Q=>n.ended(Q?{...F,mutedAutomation:Q}:F)}},l={module:"dataops",operation:c.origin},p=this.findTemplate(e.templateId),g=Tn(e,p),u={action:"anonymize_execute",module:"dataops",operationId:t,orgId:e.orgId,outcome:"failure",source:{origin:"org",orgId:e.orgId}},f=[],S=[],k=zn(e),E=p?sn(p.rules,g,k):"",j=!1,y=!1,b=!1,I=!1,N,D,R,A=0,B=0,C,ee,G=!1,W=[],X=new AbortController,ve=()=>{},kt,Ge,we,Ce=async()=>ns(ee,await we?.read()),$e=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(t);$e?.signal.addEventListener("abort",()=>X.abort(),{once:!0});let Je=()=>X.abort();s?.aborted&&X.abort(),s?.addEventListener("abort",Je,{once:!0});let ot=async()=>{be(this.deps,{...u,outcome:"stopped",source:void 0,code:Qt});let F="The masking run was cancelled before it wrote anything.";c.refused(new Error(F),{code:Qt,...D?{extraPayload:{snapshot:D}}:{}}),await d(),Ve(this.deps,t,{aborted:!0})},wt=(F,Q,re)=>{kt=F;let U=P(F),te=_t(f),Tt=j&&te.recordsNotMasked>0,Xe=Zt(re,this.orgNameOf(e.orgId)),Le={...j?{...te,objects:ao(f)}:{},...D?{snapshot:D}:{},...re?{duplicates:re}:{},...R?{slices:en(R,{requestsSpent:A})}:{}},et=Tt?`${U} \u2014 ${te.recordsProcessed} masked before it stopped; ${te.recordsNotMasked} still hold their original values (${io(f)}).`:U;c.refused(Tt||Xe?new Error(Xe?`${et} ${Xe}`:et):F,{code:Hn(F),extraPayload:Le}),pe(this.deps,t,U,Q,{context:l,extraPayload:Le}),Ge?.fail(U)},Ut=()=>{I=!0;let F=new nt(this.deps.configStore),{recordsNotMasked:Q}=_t(f),re=f.reduce((U,te)=>U+te.masked+te.nothingToMask+te.refused+te.unanswered,0);try{if(Q===0&&R?.state!=="open"||R!==void 0&&R.state!=="open")return F.clear(e.orgId,e.templateId),!1;if(re===0&&R===void 0)return F.load(e.orgId,e.templateId,E)!==void 0;let U=S.map(te=>te.progress);return nn(U)>Nt?(this.deps.log(`[WARN] dataops:anonymize ${t}: the org refused ${nn(U)} record(s), more than a resume retries (${Nt}): only a full run masks them.`),F.clear(e.orgId,e.templateId),!1):(F.save({id:t,orgId:e.orgId,templateId:e.templateId,fingerprint:E,savedAt:new Date().toISOString(),objects:U,...N?{namesGiven:N.namesGiven()}:{},...R?{setId:R.setId}:{}}),!0)}catch(U){return this.deps.log(`[WARN] dataops:anonymize ${t}: where the run stopped was not kept: `+P(U)),!1}},Be=()=>{if(R){R.lastActivityAt=new Date().toISOString(),R.requestsSpent=B+A,this.sliceSets.save(R);try{new nt(this.deps.configStore).save({id:t,orgId:e.orgId,templateId:e.templateId,fingerprint:E,savedAt:new Date().toISOString(),objects:S.map(F=>F.progress),...N?{namesGiven:N.namesGiven()}:{},setId:R.setId})}catch(F){this.deps.log(`[WARN] dataops:anonymize ${t}: where the run is in set ${R.setId} was not kept: ${P(F)}`)}}};try{let F=this.deps.infraServices?.productionGuard;if(!F){this.refuseWithoutGuard((m,v)=>c.refused(m,v),t,l,u);return}if(!p){c.refused(Ts(e.templateId),{code:so});return}let Q=ln(e,p,se)?Tn(e,p,!0):void 0,re=this.sliceSets,U=re.openFor(e.orgId,e.templateId);if(e.abandon===!0){await this.abandonSliceSet(U,e,c);return}let te=(m,v)=>sn(p.rules,m,k,v),Xe=(Q?[g,Q]:[g]).flatMap(m=>[te(m),...U?[te(m,U.size)]:[]]),Le=m=>c.refused(new Error(m??"There is nothing to resume: the run has finished since, another run of this template has stopped since, its rules have changed, or the slices it masked expired. Apply masks every record of its objects."),{code:fi}),et=(m,v)=>{be(this.deps,{...u,outcome:"stopped",source:void 0,code:m}),c.refused(new Error(v),{code:m}),pe(this.deps,t,v,!1,{context:l,authored:!0})},me;if(e.resumeFrom!==void 0){let m=new nt(this.deps.configStore);if(me=Xe.map(v=>m.load(e.orgId,e.templateId,v)).find(v=>v?.id===e.resumeFrom),!me){Le();return}if(me.setId!==void 0&&me.setId!==U?.setId||me.setId===void 0&&e.slices===!0){Le(me.setId===void 0?"The run this one resumes was not in slices: it resumes as it ran, without slices, or Apply masks every record of its objects in slices. Nothing was masked.":void 0);return}}if(U&&me?.setId!==U.setId){et(Re.runOpen,this.sliceRunOpenMessage(U,c.voice));return}let Ne=me?.setId!==void 0?U?.size:e.slices===!0?this.backupCap():void 0;if(E=te(g,Ne),Ne!==void 0&&!this.backupRecords){et(Re.needsStore,"A run in slices writes each slice to the backup files, and this host keeps none. Nothing was masked.");return}let Qe=this.maskingKey;if(me?.setId!==void 0&&U){if(Qe=await this.runKeys?.load(U.setId).catch(v=>{this.deps.log(`[WARN] dataops:anonymize: the key of set ${U.setId} was not read: `+P(v))})??this.maskingKey,U.keyCheck!==void 0&&fs(Qe)!==U.keyCheck){et(Re.keyLost,this.sliceKeyLostMessage(U,c.voice));return}R=U,B=U.requestsSpent}let ae=await ze(e.orgId,this.deps.orgRegistry,this.deps.orgManager),$=Cn(ae);if(Q&&await Ss($,this.deps.log)&&(g=Q,E=te(Q,Ne)),me&&me.fingerprint!==E){Le();return}let z,M=m=>{A++;let v=Ye(ae.limitInfo,m);v&&v.usagePercent>=Os&&(z??=v)},de=()=>z,Ke=new Set;for(let m of g){let v=Ft(p,m),V=dn(p,m);if(v.length===0&&V.length===0)continue;let _=xe(m),L=jn(e,p,m);l.objectName=_;let T=me?.objects.find(Me=>Me.objectApiName===_),x={objectApiName:_,done:T?.done??!1,...T?.afterId!==void 0?{afterId:T.afterId}:{},refused:[...T?.refused??[]],...T?.unconfirmed?.length?{unconfirmed:[...T.unconfirmed]}:{},...T?.slice?{slice:{...T.slice}}:{}},ye=0,J=async Me=>{try{let Y=await this.countRows(ae,_,Me,L);return M(`dataops:anonymize count ${_}`),Y}catch(Y){let ge=Ne!==void 0&&Me===void 0&&L===void 0?await this.approximateCount(ae,_,Y):void 0;if(ge!==void 0)return Ke.add(_),ge;throw be(this.deps,{...u,outcome:"failure",source:void 0,objects:[gn(_)],code:gi,details:{reason:Pn(Y)}}),this.countGaveUp(Y,_)}},je=R?.objects.find(Me=>Me.objectApiName===_);je?(ye=Si(je),je.done||(ye+=await J(Mn(je))),x.done=ye===0):x.done||(ye=await J(x.afterId),ye===0&&(x.done=!0));let St=ye+x.refused.length+(x.unconfirmed?.length??0),mt={objectApiName:_,total:St,masked:0,nothingToMask:0,refused:0,unanswered:0,done:St===0};f.push(mt),S.push({objectName:m,...L!==void 0?{where:L}:{},objectRules:v,personRules:V,tally:mt,progress:x})}let Oe=f.reduce((m,v)=>m+v.total,0),De=await this.maskingNotCovered($,p,g,S);if(De){be(this.deps,{...u,outcome:"stopped",source:void 0,code:De.code}),c.refused(new Error(De.message),{code:De.code,extraPayload:{...De.gaps}}),pe(this.deps,t,De.message,!1,{context:l,authored:!0});return}let pn=await vs($,S.filter(m=>m.tally.total>0).map(m=>({objectApiName:m.tally.objectApiName,rules:[...m.objectRules,...m.personRules]})));if(pn.length>0){let m=bn(pn);this.deps.log(`[WARN] CRUD/FLS check failed for anonymize ${t}: ${m}`),be(this.deps,{...u,outcome:"stopped",source:void 0,code:xt}),c.refused(new Error(m),{code:xt}),pe(this.deps,t,m,!1,{context:l,authored:!0});return}let it=(m,v,V=[])=>{be(this.deps,{...u,outcome:"stopped",source:void 0,code:m}),c.refused(new Error(v),{code:m,...os({alsoRefused:V})}),pe(this.deps,t,v,!1,{context:l,authored:!0})};if(e.snapshot===!0&&Ne===void 0){let m=this.backupCap();if(S.some(v=>v.tally.total>m)){it(on,`Nothing was masked: ${S.filter(v=>v.tally.total>m).map(v=>`${v.tally.objectApiName} holds ${v.tally.total} record(s)`).join(", ")}, more than the ${m} a snapshot holds of one object. `+this.snapshotCapWay(S,c.voice));return}}if(Ne!==void 0){let m=await this.sliceRunPlan($,S,Ne,this.pageSizeFor(e.orgId));if(m.tooMany.length>0){it(Re.tooMany,this.tooManySlicesMessage(m,Ne));return}let v=await this.freeBytes();if(v!==void 0&&Sn(m.diskBytes)>v){it(Re.diskShort,this.diskShortMessage(Sn(m.diskBytes),v,!0));return}}let at=await this.readAct(ae,e.orgId,"masking",f.map(m=>({objectApiName:m.objectApiName,records:m.total})),c.accord,c.voice),yt=yn(at.answer);if(yt){it(yt.code,yt.message,yt.alsoRefused);return}let dt=ts(at.answer.automation,f.filter(m=>m.total>0).map(m=>m.objectApiName)),ct=()=>this.duplicatesWatchOf(ae,dt),Te=ct();we=Te;let At=this.deps.orgManager.getOrg(e.orgId),Kt={orgId:e.orgId,orgTier:Rs(At),operation:"update",objectName:g.join(", ")||"AnonymizeData",recordCount:Oe,module:"dataops"},{check:jt,decision:lt}=await Zn(F,Kt);if(u.guard=lt,(lt==="refused"||lt==="declined")&&be(this.deps,{...u,outcome:"stopped",source:void 0}),lt==="refused")throw qn(jt.blockedReason??jt.impactSummary);if(lt==="declined"){let m="Operation cancelled by user (confirmation declined).";c.refused(new Error(m),{code:Kn.declined}),pe(this.deps,t,m,!1,{context:l,authored:!0});return}for(let m of jt.warnings)this.deps.log(`[WARN] dataops:anonymize ${t}: ${m}`);if(X.signal.aborted){await ot();return}let ce=await rs(at,t,c.accord.acceptEmails===!0,c.voice);if("refused"in ce){it(ce.refused.code,ce.refused.message);return}if(r=ce.held,j=!0,Ne!==void 0){let m=`backup:${e.orgId}`;if(this.activeOrgOperations.has(m)){it(Is,this.busyMessage(e.orgId,`A backup or rollback operation is already running for org ${e.orgId}. Mask once it has ended.`));return}if(this.activeOrgOperations.add(m),G=!0,!R){let v=new Date().toISOString(),V=await ae.soap.getServerTimestamp().then(L=>new Date(L.timestamp).toISOString()).catch(()=>v);A++;let _=await this.organizationIdOf(ae);A++,R={setId:t,kind:"masking",orgId:e.orgId,..._!==void 0?{organizationId:_}:{},templateId:e.templateId,fingerprint:E,size:Ne,state:"open",startedAt:v,serverStartedAt:V,lastActivityAt:v,requestsSpent:0,keyCheck:fs(Qe),objects:S.map(L=>({objectApiName:L.tally.objectApiName,...L.where!==void 0?{where:L.where}:{},done:L.tally.total===0,slices:[]}))},re.save(R),await this.runKeys?.save(R.setId,Qe).catch(L=>{this.deps.log(`[WARN] dataops:anonymize ${t}: the key of set ${t} was not kept, so only this window resumes it: ${P(L)}`)})}this.sliceRunsOn.set(e.orgId,R.setId)}let tt=In(At?.orgType==="Sandbox"||At?.orgType==="Scratch"),Fe=An(tt).defaultQueryLimit;if(e.snapshot===!0&&R===void 0){let m=await this.snapshotBeforeMasking($,t,e.orgId,S,{origin:c.origin,stop:X.signal});if("refused"in m&&X.signal.aborted){await ot();return}if("refused"in m){be(this.deps,{...u,outcome:"stopped",source:void 0,code:on}),c.refused(new Error(m.refused),{code:on}),await d(),pe(this.deps,t,m.refused,m.retryable,{context:l,authored:!0});return}if(D=m.taken,X.signal.aborted){await ot();return}}let Pe=c.pipeline?`Pipeline anonymization with ${p.name}`:`Anonymizing with ${p.name}`;Yt(this.deps,t,"dataops",Pe),y=!0,b=!0,this.deps.infraServices?.backgroundRegistry?.register(t,"dataops",Pe,new Promise((m,v)=>{ve=V=>{V===void 0?m():v(V instanceof Error?V:new Error(String(V)))}}),X),Ge=rn(this.liveTracker,t,"dataops",Pe,Oe);let{AnonymizationEngine:qt}=await import("./chunk-PZBZ7MNC.mjs"),le=new qt(void 0,Qe);N=le,me&&!(me.namesGiven!==void 0&&le.continueFrom(me.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 qe=[],Z=!1,He=m=>m.masked+m.nothingToMask+m.refused+(m.deletedSince??0),ut,Ps=(m,v)=>{let V=f.reduce((x,ye)=>x+He(ye),0),_=Math.max(Oe,V),L=Math.round(V/_*100),T=`Anonymized ${m}${ut?` ${ut}`:""} (${He(v)}/${Math.max(v.total,He(v))})`;Mt(this.deps,t,L,V,_,T),Ge?.progress(L,V,_,T)},Ln=[],Ao=async m=>{let v=R,V=this.backupRecords,{safeObj:_,fields:L,tally:T,progress:x,writeBack:ye}=m,J=v?.objects.find(h=>h.objectApiName===_);if(!v||!V||!J)throw new Error(`The set of slices holds no ${_}: nothing more was masked.`);let je=mo(_),St=L.split(",").length,mt=()=>({masked:T.masked,nothing:T.nothingToMask,refused:T.refused,gone:T.deletedSince??0}),Me=(h,w)=>{h.masked+=T.masked-w.masked,h.nothingToMask+=T.nothingToMask-w.nothing,h.deletedSince+=(T.deletedSince??0)-w.gone;let O=x.unconfirmed?.length??0;O>0?h.unanswered=O:delete h.unanswered},Y=async h=>{let w=[];for await(let O of await this.backupBatches(h.snapshotId,je))for(let K of O)typeof K.Id=="string"&&w.push(K.Id);return w},ge=async(h,w)=>{w.length===0?await V.delete(h.snapshotId,je):(await V.begin(h.snapshotId,je),await V.append(h.snapshotId,je,w.map(O=>({Id:O})))),h.refused=w.length},_e=async(h,w)=>{w.length!==0&&(await V.append(h.snapshotId,je,w.map(O=>({Id:O}))),h.refused+=w.length)},Ae=J.slices.find(h=>h.state==="masking")??J.slices.at(-1);if(Ae){Ae.masked+=T.masked,Ae.nothingToMask+=T.nothingToMask,Ae.deletedSince+=T.deletedSince??0,await _e(Ae,x.refused),x.refused=[];let h=x.unconfirmed?.length??0;h>0?Ae.unanswered=h:delete Ae.unanswered}for(let h of J.slices){if(h.refused===0)continue;let w=await Y(h),O=[...w],K=[];for(let oe=0;oe<w.length;oe+=rt){if(X.signal.aborted)return Z=!0,"stopped";if(de())return"stopped";let ue=w.slice(oe,oe+rt),Ie=await Et(ae,`SELECT ${L} FROM ${_} WHERE Id IN (${ue.map(Ht=>`'${Ht}'`).join(", ")})`);M(`dataops:anonymize query ${_}`);let he=ue.length-Ie.length;h.deletedSince+=he,T.deletedSince=(T.deletedSince??0)+he;let We=mt(),q=[],ne=!1;try{ne=await ye(Ie,(Ht,Fn)=>q.push(...Fn),(Ht,Fn)=>{x.unconfirmed=[...x.unconfirmed??[],...Fn]})}finally{Me(h,We),O=O.slice(ue.length),K.push(...q),await ge(h,[...K,...ne?ue:[],...O]),Be()}if(ne)return"stopped"}}let Ee=async h=>{let w=new Set;for(let O of J.slices)if(!(O!==h&&O.lateOf!==h.index)&&O.state!=="pending")for await(let K of await this.backupBatches(O.snapshotId,_))for(let oe of K)typeof oe.Id=="string"&&w.add(oe.Id);return w},fe=async h=>{let w=x.slice?.index===h.index?x.afterId:void 0,O=w===void 0;for await(let K of await this.backupBatches(h.snapshotId,_)){let oe=K;if(!O){let q=oe.findIndex(ne=>ne.Id===w);if(q<0)continue;O=!0,oe=oe.slice(q+1)}if(oe.length===0)continue;if(X.signal.aborted)return Z=!0,!0;if(de())return!0;let ue=mt(),Ie=[],he=q=>{let ne=q[q.length-1]?.Id;typeof ne=="string"&&un.test(ne)&&(x.afterId=ne)},We=!0;try{We=await ye(oe,(q,ne)=>{Ie.push(...ne),he(q)},(q,ne)=>{x.unconfirmed=[...x.unconfirmed??[],...ne],he(q)}),We||he(oe)}finally{Me(h,ue),await _e(h,Ie)}if(We)return!0}if(!O)throw new Error(`The snapshot of slice ${h.index} of ${_} no longer holds the row the run stopped at: it is not the file the slice was masked from, and nothing more of it was masked.`);return!1};for(;;){if(X.signal.aborted)return Z=!0,"stopped";if(de())return"stopped";let h=J.slices.find(w=>!Bt(w));if(!h){let w=J.slices.find(We=>!We.late&&(We.lateLeft??0)>0);if(!w&&J.done)break;let O=J.slices.filter(We=>!We.late),K=O.at(-1)?.sizeUsed??v.size,oe=Math.max(1,Math.min(K,T.total-He(T))),ue=_r(oe,Fe,{masking:!0,duplicateRule:Te.covers(_)}),Ie=this.sliceBudgetStop(ae,e.maxRequests,A,ue,c.voice);if(Ie)return C={budget:!0,message:Ie},"stopped";if(!w&&O.length>=ht)return C={code:Re.tooMany,message:`${_} holds more rows than ${ht} slices of ${K} do, as it grew during the run: the run stopped between two slices.`},"stopped";let he=as(v);h={index:he,...w?{late:!0,lateOf:w.index,...(w.lateAfterId??w.afterId)!==void 0?{afterId:w.lateAfterId??w.afterId}:{}}:Mn(J)!==void 0?{afterId:Mn(J)}:{},rows:0,snapshotId:is(v.setId,he),state:"pending",masked:0,refused:0,deletedSince:0,nothingToMask:0,sizeUsed:K},J.slices.push(h),Be()}if(h.state==="pending"){let w=h.late===!0?J.slices.find(ne=>ne.index===h?.lateOf):void 0,O=await this.freeBytes(),K=Sn(h.sizeUsed*(48+64*St));if(O!==void 0&&K>O)return J.slices=J.slices.filter(ne=>ne!==h),Be(),C={code:Re.diskShort,message:this.diskShortMessage(K,O)},"stopped";let oe=w?{...h.afterId!==void 0?{afterId:h.afterId}:{},...w.lastId!==void 0?{untilId:w.lastId}:{},createdSince:w.readSince??v.serverStartedAt??v.startedAt}:h.afterId!==void 0?{afterId:h.afterId}:{},ue=w?await Ee(w):void 0,Ie=Rn(Math.max(T.total,He(T)),h.sizeUsed);ut=`slice ${h.index} of about ${Math.max(Ie,h.index)}`;let he=f.reduce((ne,Ht)=>ne+He(Ht),0),We=`Backing up ${_} ${ut}`;Mt(this.deps,t,Math.round(he/Math.max(Oe,he,1)*100),he,Math.max(Oe,he),We);let q=await this.snapshotSlice(ae,e.orgId,v,J,h,{select:L,bounds:oe,...ue?{skip:ne=>ue.has(String(ne.Id))}:{},stop:X.signal,onRequest:()=>{A++},origin:c.origin});if("failed"in q)return J.slices=J.slices.filter(ne=>ne!==h),Be(),q.cancelled?(Z=!0,"stopped"):(C={code:q.code,message:this.sliceNotTakenMessage(_,q)},"stopped");if(q.lastId===void 0){await this.removeBackup(`backup:${h.snapshotId}`),J.slices=J.slices.filter(ne=>ne!==h),w?(delete w.lateLeft,delete w.lateAfterId,q.readSince&&(w.readSince=q.readSince)):J.done=!0,Be();continue}h.rows=q.rows,h.lastId=q.lastId,h.sizeUsed=q.sizeUsed,h.takenAt=new Date().toISOString(),q.readSince&&(h.readSince=q.readSince),w&&(q.read<q.sizeUsed?(delete w.lateLeft,delete w.lateAfterId,q.readSince&&(w.readSince=q.readSince)):w.lateAfterId=q.lastId),h.state="masking",x.slice={setId:v.setId,index:h.index},delete x.afterId,Be()}if(ut??=`slice ${h.index}`,await fe(h))return"stopped";Ln.push(h.index),ut=void 0,h.state="masked",delete h.unanswered,ee=ns(ee,await Te.read()),Te=ct(),we=Te,le.forgetRecords(),delete x.slice,delete x.afterId,Be()}return T.done=!0,x.done=!0,"done"};for(let{objectName:m,where:v,objectRules:V,personRules:_,tally:L,progress:T}of S){if(L.total===0)continue;if(X.signal.aborted){Z=!0;break}if(de())break;let x=L.objectApiName;l.objectName=x;let{select:ye,rulesOf:J}=await this.maskedFields($,x,this.maskingRules(m,V,Qe),this.maskingRules(m,_,Qe));l.batchSize=rt;let je=async(Y,ge,_e)=>{let Ae=Y.map(J),Ee=Y.map((h,w)=>le.anonymize([h],Ae[w])[0]),fe=[];Y.forEach((h,w)=>{let O={Id:h.Id};for(let K of Ae[w])Yn(h[K.fieldApiName])&&(O[K.fieldApiName]=Ee[w][K.fieldApiName]);Object.keys(O).length>1?fe.push(O):L.nothingToMask++});for(let h=0;h<fe.length;h+=rt){if(X.signal.aborted)return Z=!0,!0;if(de())return!0;let w=fe.slice(h,h+rt),O;Te.beforeWrite(x);try{O=await ae.sobject(m).update(w,{headers:Wn()})}catch(ue){throw Jn(ue)==="may-have-written"&&(L.unanswered+=w.length,_e(w,w.flatMap(mi)),Te.wrote(x,w.map(Ie=>Ie.Id))),ue}M(`dataops:anonymize update ${x}`);let K=[],oe=Array.isArray(O)?O:[O];Te.wrote(x,oe.flatMap((ue,Ie)=>ue.success?[w[Ie]?.Id]:[])),oe.forEach((ue,Ie)=>{if(ue.success){L.masked++;return}if(R&&Ri(ue.errors)){L.deletedSince=(L.deletedSince??0)+1;return}L.refused++;let he=w[Ie]?.Id;typeof he=="string"&&un.test(he)&&K.push(he),to(qe,x,ue.errors)}),ge(w,K),Ps(m,L)}return fe.length===0&&Ps(m,L),!1},St=T.unconfirmed??[];for(let Y=0;Y<St.length;Y+=rt){if(X.signal.aborted){Z=!0;break}if(de())break;let ge=St.slice(Y,Y+rt),_e=ge.map(O=>`'${O.id}'`).join(", "),Ae=await Et(ae,`SELECT ${ye} FROM ${x} WHERE Id IN (${_e})`);M(`dataops:anonymize query ${x}`);let Ee=new Map(Ae.map(O=>[String(O.Id),O])),fe=[];for(let O of ge){let K=Ee.get(O.id);K===void 0?L.total-=1:bs(K,O.fields)===O.digest?L.nothingToMask++:fe.push(O.id)}let h=new Set(ge.map(O=>O.id)),w=(T.unconfirmed??[]).filter(O=>!h.has(O.id));w.length>0?T.unconfirmed=w:delete T.unconfirmed,T.refused.push(...fe)}if(Z||de())break;let mt=[...T.refused];for(let Y=0;Y<mt.length;Y+=rt){if(X.signal.aborted){Z=!0;break}if(de())break;let ge=mt.slice(Y,Y+rt),_e=await Et(ae,`SELECT ${ye} FROM ${x} WHERE Id IN (${ge.map(h=>`'${h}'`).join(", ")})`);M(`dataops:anonymize query ${x}`),L.total-=ge.length-_e.length;let Ae=[];if(await je(_e,(h,w)=>Ae.push(...w),(h,w)=>{let O=new Set(w.map(K=>K.id));T.refused=T.refused.filter(K=>!O.has(K)),T.unconfirmed=[...T.unconfirmed??[],...w]}))break;let fe=new Set(ge);T.refused=[...T.refused.filter(h=>!fe.has(h)),...Ae]}if(Z||de())break;if(R){if(await Ao({objectName:m,safeObj:x,fields:ye,tally:L,progress:T,writeBack:je})!=="done")break;continue}if(T.done){L.done=!0;continue}let Me=T.afterId;for(;;){if(X.signal.aborted){Z=!0;break}if(de())break;let Y=await lo(ae,x,ye,Fe,Me,v);if(M(`dataops:anonymize query ${x}`),Y.records.length===0){L.done=!0,T.done=!0;break}let ge=Y.truncated?Ii(Y.records,Me,x):void 0;if(X.signal.aborted){Z=!0;break}let _e=Ee=>{let fe=Ee[Ee.length-1]?.Id;typeof fe=="string"&&un.test(fe)&&(T.afterId=fe)};if(await je(Y.records,(Ee,fe)=>{T.refused.push(...fe),_e(Ee)},(Ee,fe)=>{T.unconfirmed=[...T.unconfirmed??[],...fe],_e(Ee)}))break;if(ge===void 0){L.done=!0,T.done=!0;break}Me=ge,T.afterId=ge}if(Z||de())break}if(R){!Z&&!de()&&!C&&(W=await this.countLateRows(ae,R,()=>{A++}));for(let m of f){let v=R.objects.find(_=>_.objectApiName===m.objectApiName),V=m.done&&v?ds({objects:[v]}):0;V>0&&(m.late=V)}if(_t(f).recordsNotMasked===0&&R.objects.every(m=>m.done&&(m.tailLeft??0)===0&&m.slices.every(v=>Bt(v)&&v.refused===0&&(v.lateLeft??0)===0))&&(R.state="done"),$t(R).length===0&&R.state==="open"?(R.state="abandoned",this.sliceSets.delete(R.setId)):Be(),R.state!=="open"){let m=R.setId;await this.runKeys?.delete(m).catch(v=>{this.deps.log(`[WARN] dataops:anonymize ${t}: the key of set ${m} was not removed: ${P(v)}`)})}}let It=de(),pt=bi(f,Z),{recordsProcessed:Rt,recordsFailed:Ct,recordsNotMasked:ft}=_t(f),Ms=io(f);y=!1,be(this.deps,{...u,...ki(f,pt,Z),objects:co(f),...R?{details:{setId:R.setId,sliceSize:R.size,...Ln.length>0?{slices:Ln.join(",")}:{}}}:{}});let Es=Ut();if(ft>0){let m=Z?"cancelled":It?`stopped at ${It.usagePercent}% of the org's API requests`:"refused by the org";this.deps.log(`[WARN] dataops:anonymize ${t} ${m}: ${ft} record(s) not masked \u2014 ${Ms}`)}await d();let Dn=await Ce();Z?(this.deps.infraServices?.backgroundRegistry?.abort(t),Ve(this.deps,t,{aborted:!0,totalProcessed:Rt,totalFailed:Ct,totalNotMasked:ft}),Ge?.cancel()):(Ve(this.deps,t,{status:pt,totalProcessed:Rt,totalFailed:Ct,totalNotMasked:ft}),pt==="failure"?Ge?.fail(`The org refused the ${Ct} record(s)`):pt==="partial"?Ge?.partial():Ge?.complete());let xs=`${ft} still hold their original values (${Ms})`,Io=Z?`Anonymization cancelled: ${Rt} masked before the cancel \u2014 ${xs}.`:It?`Anonymization stopped at ${It.usagePercent}% of the org's daily API requests (${It.apiUsage} of ${It.apiLimit}): ${Rt} masked \u2014 ${xs}. ${Es?"Resume it":"Run it again"} once the org has requests to spare.`:Ct===0?`Anonymization ${pt==="success"?"completed":pt}: ${Rt} records processed.`:`Anonymization ${pt}: ${Rt} masked, ${Ct} rejected by the org \u2014 those records still hold their original values.`,Ro=Es&&ft>0?" Resume masks only what this run left.":"",zs=Zt(Dn,this.orgNameOf(e.orgId)),Bs=R?this.slicesSentence(R,C,c.voice,ft>0,W):"",So=Io+(Bs?` ${Bs}`:Ro)+(zs?` ${zs}`:"");c.ended({templateId:e.templateId,status:pt,recordsProcessed:Rt,recordsFailed:Ct,recordsNotMasked:ft,objects:ao(f),message:So,errors:qe,...Z?{cancelled:!0}:{},...It?{stoppedAtApiLimit:!0}:{},...D?{snapshot:D}:{},...r?{mutedAutomation:r.outcome}:{},...Dn?{duplicates:Dn}:{},...R?{slices:en(R,{requestsSpent:A,stoppedOnBudget:C?.budget===!0})}:{}})}catch(F){await d();let Q=await Ce().catch(()=>{});wt(F,!0,Q)}finally{let F=await d();if(F&&c.muted?.(F),y){let Q=f.some(re=>re.masked>0);be(this.deps,{...u,outcome:Q?"partial":"failure",objects:j?co(f):[]})}if(b&&!I){try{Be()}catch(Q){this.deps.log(`[WARN] dataops:anonymize ${t}: its set of slices was not kept: `+P(Q))}Ut()}G&&(this.activeOrgOperations.delete(`backup:${e.orgId}`),this.sliceRunsOn.delete(e.orgId)),ve(kt),$e?.release(),s?.removeEventListener("abort",Je),o.answer?.(F)}}handleAnonymizationTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.listedTemplates(),n=ke(this.deps,e,"dataops:anonymization-templates:response",{templates:t});this.deps.broker.postToWebview(n),this.deps.log("[TX] dataops:anonymization-templates:response")}listedTemplates(){return[...tn,...this.savedTemplates.list()]}async handleBackupObjects(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(nr,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 s,r=()=>s??=ze(t.orgId,this.deps.orgRegistry,this.deps.orgManager).then(d=>Ss(d,this.deps.log)),o=[];for(let d of n?[n]:this.listedTemplates()){let c=ln({},d,se)&&await r();for(let l of Tn({},d,c))l!==""&&l!=="*"&&!o.includes(l)&&o.push(l)}let a=ke(this.deps,e,"backup:objects:response",{objects:o});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} objects=${o.length}`)}catch(s){H(this.deps,"backup:objects","dataops:error",e,s)}}async plannedObjectsIn(e,t,n){let s=ln(t,n,se)&&await Ss(e,this.deps.log);return Tn(t,n,s)}async handleAnonymizeCoverage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(ar,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 s=this.latestBackup(t.orgId),r=await ze(t.orgId,this.deps.orgRegistry,this.deps.orgManager),o=[],a=await this.plannedObjectsIn(r,t,n),d=[];for(let S of a){if(!no(n,S))continue;let k=xe(S),E=jn(t,n,S),j=null,y;try{j=await this.countRows(r,k,void 0,E)}catch(N){this.deps.log(`[WARN] dataops:anonymize:coverage: ${k} not counted: ${P(N)}`),y=await this.approximateCount(r,k,N)}d.push({objectName:S,...j!==null?{rows:j}:y!==void 0?{rows:y}:{},...j===null&&y!==void 0?{approximate:!0}:{}});let b=s?.objects.find(N=>N.objectApiName.toLowerCase()===k.toLowerCase()),I=b?.where!==void 0&&b.where!==E;o.push({objectApiName:k,count:j,backedUp:I?0:b?.recordCount??0,truncated:!I&&b?.truncated===!0,...b?.stoppedAt&&!I?{stoppedAt:b.stoppedAt}:{},...I?{filtered:!0}:{}})}let c=this.sliceSets.openFor(t.orgId,t.templateId),l=c?.size??this.backupCap(),p;if(t.slices===!0||c!==void 0||d.some(S=>(S.rows??0)>this.backupCap())){let S=Cn(r),k=[];for(let y of d){if(y.rows===void 0)continue;let b=Ft(n,y.objectName),I=dn(n,y.objectName),N=await this.maskedFields(S,xe(y.objectName),this.maskingRules(y.objectName,b),this.maskingRules(y.objectName,I)).then(({select:D})=>D.split(",").length,()=>b.length+I.length+1);k.push({objectApiName:xe(y.objectName),rows:y.rows,fields:N,...y.approximate?{approximate:!0}:{}})}let E=ls(k,l,this.pageSizeFor(t.orgId),"masking");for(let y of o){let b=E.objects.find(I=>I.objectApiName===y.objectApiName);b&&(y.slicePlan=b)}let j=await this.freeBytes();p={requests:E.requests,parts:E.parts,bulkBatches:0,diskBytes:E.diskBytes,...j!==void 0?{diskFree:j}:{},seconds:E.seconds,apiBudget:await this.apiBudgetFor(r,E.requests)}}let g=new nt(this.deps.configStore),u=(c?g.load(t.orgId,t.templateId,sn(n.rules,a,zn(t),c.size)):void 0)??g.load(t.orgId,t.templateId,sn(n.rules,a,zn(t))),f=ke(this.deps,e,"dataops:anonymize:coverage:response",{templateId:t.templateId,...s?{backup:{operationId:s.operationId,timestamp:s.timestamp}}:{},objects:o,...u?{checkpoint:{id:u.id,savedAt:u.savedAt}}:{},...p?{plan:p}:{},...c?{sliceSet:Pr(c)}:{}});this.deps.broker.postToWebview(f),this.deps.log(`[TX] ${f.type} id=${f.id} objects=${o.length}`)}catch(s){H(this.deps,"dataops:anonymize:coverage","dataops:error",e,s)}}async handleAnonymizePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(dr,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 s=await ze(t.orgId,this.deps.orgRegistry,this.deps.orgManager),{AnonymizationEngine:r}=await import("./chunk-PZBZ7MNC.mjs"),o=new r(void 0,this.maskingKey),a=[],d=[],c=Cn(s);for(let p of await this.plannedObjectsIn(s,t,n)){if(!no(n,p))continue;let g=xe(p);try{let u=Ft(n,p),f=dn(n,p),{rules:S,select:k,missing:E,rulesOf:j}=await this.maskedFields(c,g,this.maskingRules(p,u),this.maskingRules(p,f)),y=await lo(s,g,k,ro,void 0,jn(t,n,p));Ye(s.limitInfo,`dataops:anonymize:preview ${g}`);let b=y.records.length>0;b&&d.push(...E.map(A=>({objectApiName:g,fieldApiName:A})));let[I]=b?await vs(c,[{objectApiName:g,rules:[...u,...f]}]):[],N=y.records.map(j),D=y.records.map((A,B)=>o.anonymize([A],N[B])[0]),R=S.map(A=>A.fieldApiName).filter((A,B,C)=>A!=="Id"&&C.indexOf(A)===B);a.push({objectApiName:g,fields:R,...b&&S.length===0?{notCovered:!0}:{},...I?{writeDenied:{deniedFields:[...I.deniedFields]}}:{},methods:Object.fromEntries(S.map(A=>[A.fieldApiName,A.method])),rows:y.records.slice(0,ro).map((A,B)=>{let C={},ee={},G=new Set(N[B].map(W=>W.fieldApiName));for(let W of R)C[W]=oo(A[W]),ee[W]=Yn(A[W])&&G.has(W)?oo(D[B][W]):C[W];return{id:String(A.Id??""),before:C,after:ee}})})}catch(u){let f=P(u);this.deps.log(`[WARN] dataops:anonymize:preview: ${g} not read: ${f}`),a.push({objectApiName:g,fields:[],rows:[],error:f})}}let l=ke(this.deps,e,"dataops:anonymize:preview:response",{templateId:t.templateId,objects:a,fieldsNotFound:d});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} objects=${a.length}`)}catch(s){H(this.deps,"dataops:anonymize:preview","dataops:error",e,s)}}latestBackup(e){let t;for(let n of this.deps.configStore.getKeysByPrefix("backup:")){let s=n.slice(7);if(s.includes(":"))continue;let r=this.deps.configStore.get(n);if(r?.orgId!==e||r.origin==="slice")continue;let o=r.timestamp??"";t&&t.timestamp.localeCompare(o)>=0||(t={operationId:s,timestamp:o,objects:r.objects??[]})}return t}async handleQualityScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(pr,e,"dataops:error",this.deps);if(t)try{let n=await ze(t.orgId,this.deps.orgRegistry,this.deps.orgManager),s=await fr({describe:o=>n.describe(o),query:async o=>{let a=await n.query(o);return Ye(n.limitInfo,"dataops:quality-scan"),{totalSize:a.totalSize,records:a.records}}},t),r=ke(this.deps,e,"dataops:quality-scan:response",{...s});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} objects=${s.objects.length}`)}catch(n){H(this.deps,"dataops:quality-scan","dataops:error",e,n)}}handleTemplateSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(cr,e,"dataops:error",this.deps);if(t)try{let n=t.name.trim();if([...tn,...this.savedTemplates.list()].some(a=>a.name.trim().toLowerCase()===n.toLowerCase())){H(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 r={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(r);let o=ke(this.deps,e,"dataops:anonymization-template:save:response",{template:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(n){H(this.deps,"dataops:anonymization-template:save","dataops:error",e,n)}}handleTemplateDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(lr,e,"dataops:error",this.deps);if(!t)return;let{templateId:n}=t;if(tn.some(s=>s.id===n)){H(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 s=this.savedTemplates.delete(n),r=ke(this.deps,e,"dataops:anonymization-template:delete:response",{templateId:n,deleted:s});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}catch(s){H(this.deps,"dataops:anonymization-template:delete","dataops:error",e,s)}}async handlePIIScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Se(ur,e,"dataops:error",this.deps);if(!t)return;let{orgId:n,objectNames:s}=t;try{if(!this.deps.infraServices?.piiDetector)throw new Error("PII Detector not available.");let r=await ze(n,this.deps.orgRegistry,this.deps.orgManager),o=await Promise.all(s.map(async d=>{let c=xe(d),l=await r.describe(c);Ye(r.limitInfo,`precheck:pii-scan describe ${c}`);let p=l.fields.map(u=>({apiName:u.name,label:u.label,type:u.type,length:u.length})),g=this.deps.infraServices.piiDetector.detectPII(d,p);return{objectName:d,piiFields:g.piiFields.map(u=>({fieldName:u.fieldApiName,piiType:u.classification,confidence:u.confidence}))}})),a=ke(this.deps,e,"precheck:pii-scan:response",{success:!0,results:o});this.deps.broker.postToWebview(a)}catch(r){this.deps.log(`[ERR] precheck:pii-scan: ${P(r)}`);let o=ke(this.deps,e,"precheck:pii-scan:response",{success:!1,error:P(r)});this.deps.broker.postToWebview(o)}}};export{tn as a,$n as b,An as c,In as d,Nn as e,cs as f,On as g,rn as h,ks as i,Sn as j,us as k,Ei as l,xi as m,ai as n,an as o,go as p};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a}from"./chunk-BXU6WFMH.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as ReferenceLinker};
7
+ import{a}from"./chunk-QXLZINZB.mjs";import"./chunk-DPYTG6DM.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as ReferenceLinker};