sandforge 1.79.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 (256) hide show
  1. package/bin/sandforge-pipeline.mjs +12 -0
  2. package/lib/{chunk-BN7A4GRQ.mjs → chunk-2IB7I3IQ.mjs} +1 -1
  3. package/lib/{chunk-PBI4BYWW.mjs → chunk-2NAIUKVL.mjs} +1 -1
  4. package/lib/chunk-2OIRJEYE.mjs +7 -0
  5. package/lib/{chunk-FOVVHGEP.mjs → chunk-2OZG6GRW.mjs} +1 -1
  6. package/lib/{chunk-5CD257T7.mjs → chunk-2Z54GB6X.mjs} +1 -1
  7. package/lib/chunk-2ZMGVBLW.mjs +7 -0
  8. package/lib/{chunk-4NAHW2D3.mjs → chunk-33ZX3A56.mjs} +1 -1
  9. package/lib/{chunk-4SNDMJP2.mjs → chunk-3AOKLIVE.mjs} +1 -1
  10. package/lib/{chunk-SIOZXPFG.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-GNC27UEU.mjs → chunk-5UT2ZBGF.mjs} +1 -1
  22. package/lib/chunk-5VQNKDFU.mjs +7 -0
  23. package/lib/chunk-5WGA5CZB.mjs +7 -0
  24. package/lib/chunk-5ZKCLBTN.mjs +474 -0
  25. package/lib/chunk-67CC7RAE.mjs +7 -0
  26. package/lib/{chunk-5O6JOMHS.mjs → chunk-6CDIIFNX.mjs} +1 -1
  27. package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
  28. package/lib/{chunk-7UQD6V6F.mjs → chunk-6FMLW7PH.mjs} +1 -1
  29. package/lib/chunk-6IGEASOF.mjs +7 -0
  30. package/lib/{chunk-H2PJNIYJ.mjs → chunk-6NADW3OI.mjs} +1 -1
  31. package/lib/chunk-6SEDOIO3.mjs +10 -0
  32. package/lib/{chunk-AUTM6H6Z.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-HV2MXMGI.mjs → chunk-AJPSGVMD.mjs} +1 -1
  38. package/lib/{chunk-OTWRDD6L.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-XBG5SP6Q.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-BILZ3SSR.mjs → chunk-D7P7DTWL.mjs} +1 -1
  47. package/lib/chunk-DHGPDSXS.mjs +7 -0
  48. package/lib/{chunk-ZXH4MBWP.mjs → chunk-DHIW4IO5.mjs} +1 -1
  49. package/lib/{chunk-NM4MDLK4.mjs → chunk-DMBR24CK.mjs} +1 -1
  50. package/lib/chunk-DPYTG6DM.mjs +48 -0
  51. package/lib/chunk-DQR5NDMI.mjs +7 -0
  52. package/lib/chunk-DXOXLUZA.mjs +7 -0
  53. package/lib/chunk-E2OBAWSH.mjs +7 -0
  54. package/lib/chunk-E2YJVSX6.mjs +10 -0
  55. package/lib/chunk-EAFLDSQ2.mjs +7 -0
  56. package/lib/{chunk-HCIDVIOW.mjs → chunk-EH5YUA5W.mjs} +1 -1
  57. package/lib/{chunk-2BVTCNWA.mjs → chunk-EOSEMFPU.mjs} +1 -1
  58. package/lib/chunk-ETT5GP4P.mjs +13 -0
  59. package/lib/{chunk-3SRXFZSD.mjs → chunk-FDGFUEK3.mjs} +1 -1
  60. package/lib/{chunk-3DCUADVK.mjs → chunk-FLNLG43R.mjs} +1 -1
  61. package/lib/{chunk-HTJ5OGP5.mjs → chunk-FSDO4DJA.mjs} +1 -1
  62. package/lib/{chunk-HJKM3E56.mjs → chunk-FSZTXLNW.mjs} +1 -1
  63. package/lib/chunk-FTA5LOVX.mjs +7 -0
  64. package/lib/chunk-G4VXPS3A.mjs +7 -0
  65. package/lib/chunk-GF247DA7.mjs +7 -0
  66. package/lib/{chunk-QRV2OSIS.mjs → chunk-GK7VEYFM.mjs} +1 -1
  67. package/lib/{chunk-5MMXFWPD.mjs → chunk-GR3NGDVM.mjs} +1 -1
  68. package/lib/{chunk-P7GSGFJO.mjs → chunk-GTIXJCGS.mjs} +1 -1
  69. package/lib/{chunk-342FN7AO.mjs → chunk-GWRKS3AL.mjs} +1 -1
  70. package/lib/{chunk-LQ4DRFUH.mjs → chunk-GYKNCYES.mjs} +1 -1
  71. package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
  72. package/lib/chunk-HVC5CYIB.mjs +7 -0
  73. package/lib/{chunk-EQF2IJS2.mjs → chunk-HYBH5PFM.mjs} +1 -1
  74. package/lib/chunk-HYOOJVR6.mjs +7 -0
  75. package/lib/{chunk-TQX3PURV.mjs → chunk-IBURU7T7.mjs} +1 -1
  76. package/lib/chunk-ICIYL45C.mjs +7 -0
  77. package/lib/{chunk-K22PA4XL.mjs → chunk-IKGHRYCN.mjs} +1 -1
  78. package/lib/chunk-IM2XA6JI.mjs +7 -0
  79. package/lib/{chunk-P2PJYWGQ.mjs → chunk-J6G23RUI.mjs} +1 -1
  80. package/lib/{chunk-JVL444U5.mjs → chunk-JU2XEKEO.mjs} +1 -1
  81. package/lib/{chunk-H45UXY6G.mjs → chunk-K55LH4ZQ.mjs} +1 -1
  82. package/lib/chunk-K5HV4YRO.mjs +7 -0
  83. package/lib/{chunk-IAZB4WIL.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-TEOLMRDO.mjs → chunk-KNIRA333.mjs} +1 -1
  87. package/lib/chunk-KOQV4WXC.mjs +8 -0
  88. package/lib/{chunk-PNCONNFJ.mjs → chunk-KRNFVAGC.mjs} +1 -1
  89. package/lib/chunk-L5FGY6YA.mjs +7 -0
  90. package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
  91. package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
  92. package/lib/{chunk-ZOVSMN5C.mjs → chunk-LO527YLT.mjs} +1 -1
  93. package/lib/chunk-MAHZMPMZ.mjs +7 -0
  94. package/lib/{chunk-QQZZMKU3.mjs → chunk-MHW6DV6T.mjs} +1 -1
  95. package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
  96. package/lib/{chunk-6EBMEGZB.mjs → chunk-MKNAZPOT.mjs} +1 -1
  97. package/lib/{chunk-NTDN2JQZ.mjs → chunk-MNITSYI2.mjs} +8 -8
  98. package/lib/chunk-MO3N5XVV.mjs +341 -0
  99. package/lib/{chunk-SBIMVCXT.mjs → chunk-MS4FJDFD.mjs} +9 -9
  100. package/lib/chunk-MWLFFVQV.mjs +8 -0
  101. package/lib/chunk-N6HHNR6J.mjs +7 -0
  102. package/lib/chunk-N7J6NJQ6.mjs +7 -0
  103. package/lib/chunk-NJ3EOEHS.mjs +9 -0
  104. package/lib/chunk-NWPQF5XR.mjs +7 -0
  105. package/lib/{chunk-PUOX4NBJ.mjs → chunk-NWVVCZUK.mjs} +1 -1
  106. package/lib/{chunk-DLDX6RRC.mjs → chunk-O6ADMP36.mjs} +1 -1
  107. package/lib/chunk-O7DAFE6M.mjs +14 -0
  108. package/lib/chunk-OEHVAJAB.mjs +7 -0
  109. package/lib/chunk-OETEC3P7.mjs +7 -0
  110. package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
  111. package/lib/chunk-OIIL4NVI.mjs +7 -0
  112. package/lib/chunk-OMZJ37JI.mjs +15 -0
  113. package/lib/{chunk-NZ5ZZLKS.mjs → chunk-ONMBSACW.mjs} +1 -1
  114. package/lib/chunk-OQQHNYR7.mjs +272 -0
  115. package/lib/{chunk-AAVJ5XVX.mjs → chunk-OU5W7SCB.mjs} +1 -1
  116. package/lib/{chunk-RSYICMZG.mjs → chunk-OVOLG3AL.mjs} +1 -1
  117. package/lib/{chunk-F74IHMGL.mjs → chunk-OXKZ4Y3B.mjs} +1 -1
  118. package/lib/{chunk-W7KFAY55.mjs → chunk-OZNLOV4U.mjs} +1 -1
  119. package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
  120. package/lib/chunk-PPGDAUEQ.mjs +7 -0
  121. package/lib/{chunk-RACDTRZA.mjs → chunk-PYUEHBA6.mjs} +1 -1
  122. package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
  123. package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
  124. package/lib/{chunk-PZTSVQSF.mjs → chunk-QXLZINZB.mjs} +1 -1
  125. package/lib/chunk-R2BJWO5N.mjs +20 -0
  126. package/lib/chunk-R6TF26V4.mjs +10 -0
  127. package/lib/{chunk-P42X3B4D.mjs → chunk-RKALOKAU.mjs} +1 -1
  128. package/lib/chunk-SQGP46QS.mjs +7 -0
  129. package/lib/chunk-SU65Z2BA.mjs +7 -0
  130. package/lib/chunk-SW2NUKQL.mjs +9 -0
  131. package/lib/chunk-T26C576X.mjs +9 -0
  132. package/lib/{chunk-3OHPD72J.mjs → chunk-T3PLRQ2T.mjs} +1 -1
  133. package/lib/chunk-T5VAULLQ.mjs +7 -0
  134. package/lib/chunk-TEIBWMJM.mjs +7 -0
  135. package/lib/chunk-TKQQVB2D.mjs +9 -0
  136. package/lib/{chunk-RAAANPPG.mjs → chunk-TPHXRHOA.mjs} +1 -1
  137. package/lib/chunk-TQ2TQHTT.mjs +9 -0
  138. package/lib/{chunk-IEYG5ATY.mjs → chunk-TQM2XJ27.mjs} +1 -1
  139. package/lib/{chunk-X65MT4W3.mjs → chunk-UCHAZ4ZU.mjs} +1 -1
  140. package/lib/chunk-UIUPPEFB.mjs +7 -0
  141. package/lib/{chunk-QPF6C5MX.mjs → chunk-UT27HXE7.mjs} +1 -1
  142. package/lib/{chunk-J7HVXMSW.mjs → chunk-UUSLTW5V.mjs} +1 -1
  143. package/lib/chunk-V2QO6KOE.mjs +19 -0
  144. package/lib/chunk-V473C7LY.mjs +7 -0
  145. package/lib/chunk-V4RKM4QZ.mjs +8 -0
  146. package/lib/chunk-VSU74RQ3.mjs +9 -0
  147. package/lib/chunk-VV3B6IC3.mjs +7 -0
  148. package/lib/chunk-W2AAGIZF.mjs +7 -0
  149. package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
  150. package/lib/chunk-WD47PGUS.mjs +10 -0
  151. package/lib/{chunk-3CA767QB.mjs → chunk-WEZLXE34.mjs} +1 -1
  152. package/lib/{chunk-WFEB5X4U.mjs → chunk-WI4HYWV6.mjs} +1 -1
  153. package/lib/{chunk-AR7BE5O2.mjs → chunk-WM5JI4JI.mjs} +1 -1
  154. package/lib/chunk-WWTXRWNZ.mjs +7 -0
  155. package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
  156. package/lib/{chunk-ZJKCWBRJ.mjs → chunk-X2ZVSQ54.mjs} +1 -1
  157. package/lib/{chunk-SFURUNJM.mjs → chunk-XC2QKQT5.mjs} +1 -1
  158. package/lib/chunk-XC54KKKC.mjs +7 -0
  159. package/lib/chunk-XEB6HZ34.mjs +7 -0
  160. package/lib/chunk-XGKSSCW7.mjs +7 -0
  161. package/lib/chunk-XIZ5LMQM.mjs +7 -0
  162. package/lib/{chunk-RFEO2KAN.mjs → chunk-Y5ZCPY36.mjs} +1 -1
  163. package/lib/{chunk-TBZMC2VV.mjs → chunk-YCSFP6ER.mjs} +4 -4
  164. package/lib/{chunk-YBU4Z4QV.mjs → chunk-YHIOS2PU.mjs} +1 -1
  165. package/lib/chunk-YIGFYZQY.mjs +7 -0
  166. package/lib/chunk-YJEXE6HZ.mjs +925 -0
  167. package/lib/{chunk-57VHUYNG.mjs → chunk-YOGMP72T.mjs} +4 -4
  168. package/lib/chunk-ZRUDYB7O.mjs +7 -0
  169. package/lib/{chunk-55HEMHEG.mjs → chunk-ZUA5BNAO.mjs} +1 -1
  170. package/lib/chunk-ZWCRWF7E.mjs +7 -0
  171. package/lib/{chunk-VHI54FBK.mjs → chunk-ZWZXQTAK.mjs} +53 -53
  172. package/lib/sandforge-autopilot.mjs +29 -24
  173. package/lib/sandforge-backup.mjs +67 -32
  174. package/lib/sandforge-checkpoint.mjs +1 -347
  175. package/lib/sandforge-cleanup.mjs +14 -10
  176. package/lib/sandforge-clone.mjs +1 -1
  177. package/lib/sandforge-compare.mjs +9 -8
  178. package/lib/sandforge-dataops.mjs +1 -1
  179. package/lib/sandforge-empty.mjs +15 -15
  180. package/lib/sandforge-env.mjs +101 -101
  181. package/lib/sandforge-frozen.mjs +1 -257
  182. package/lib/sandforge-mcp.mjs +33 -14
  183. package/lib/sandforge-monitor.mjs +7 -7
  184. package/lib/sandforge-pipeline.mjs +88 -0
  185. package/lib/sandforge-seed.mjs +1 -1
  186. package/lib/sandforge-sync.mjs +1 -1
  187. package/lib/sandforge.mjs +6 -6
  188. package/package.json +2 -1
  189. package/lib/chunk-2S5OMIIA.mjs +0 -7
  190. package/lib/chunk-36U7IQ6Y.mjs +0 -25
  191. package/lib/chunk-3F5YMM2F.mjs +0 -7
  192. package/lib/chunk-3RYLICRX.mjs +0 -7
  193. package/lib/chunk-42RER7V4.mjs +0 -14
  194. package/lib/chunk-4GL773D5.mjs +0 -7
  195. package/lib/chunk-4HFRHFGQ.mjs +0 -7
  196. package/lib/chunk-4U6NXJNL.mjs +0 -7
  197. package/lib/chunk-4XZ5YT5O.mjs +0 -7
  198. package/lib/chunk-5AJRHRXA.mjs +0 -20
  199. package/lib/chunk-5HMAPZBV.mjs +0 -7
  200. package/lib/chunk-5P4PHJRL.mjs +0 -9
  201. package/lib/chunk-5QKTYCWE.mjs +0 -11
  202. package/lib/chunk-6LAXTAVN.mjs +0 -7
  203. package/lib/chunk-6MUEPV7M.mjs +0 -9
  204. package/lib/chunk-6QSM2WIH.mjs +0 -10
  205. package/lib/chunk-75ADZS6B.mjs +0 -7
  206. package/lib/chunk-ALJVEUUS.mjs +0 -7
  207. package/lib/chunk-ALUFROGA.mjs +0 -7
  208. package/lib/chunk-B45CNPUX.mjs +0 -47
  209. package/lib/chunk-BS5T3MOQ.mjs +0 -7
  210. package/lib/chunk-CGWXQX75.mjs +0 -7
  211. package/lib/chunk-D3QRXG63.mjs +0 -787
  212. package/lib/chunk-EEVVGGM6.mjs +0 -7
  213. package/lib/chunk-ENLBYECD.mjs +0 -7
  214. package/lib/chunk-EQOQASDQ.mjs +0 -7
  215. package/lib/chunk-FQBRBBY4.mjs +0 -7
  216. package/lib/chunk-GAM726CK.mjs +0 -7
  217. package/lib/chunk-HJC7AIBK.mjs +0 -7
  218. package/lib/chunk-HUMEKZT5.mjs +0 -8
  219. package/lib/chunk-I3JKJTLO.mjs +0 -110
  220. package/lib/chunk-I7O6C2B5.mjs +0 -8
  221. package/lib/chunk-KLX67VPL.mjs +0 -7
  222. package/lib/chunk-L776PUMV.mjs +0 -7
  223. package/lib/chunk-LRFAIUN7.mjs +0 -7
  224. package/lib/chunk-LV6G4XTK.mjs +0 -7
  225. package/lib/chunk-MYTIL2JD.mjs +0 -10
  226. package/lib/chunk-NEVXIGR6.mjs +0 -10
  227. package/lib/chunk-NGSMZZDA.mjs +0 -7
  228. package/lib/chunk-NHWE66K5.mjs +0 -7
  229. package/lib/chunk-OQOZAPCI.mjs +0 -7
  230. package/lib/chunk-PA3MKJVH.mjs +0 -7
  231. package/lib/chunk-QROPNEGY.mjs +0 -14
  232. package/lib/chunk-QWT2C74M.mjs +0 -7
  233. package/lib/chunk-RH3N2H7P.mjs +0 -7
  234. package/lib/chunk-SRQDABQ2.mjs +0 -15
  235. package/lib/chunk-SVS6UMDU.mjs +0 -323
  236. package/lib/chunk-TNXUU6W7.mjs +0 -14
  237. package/lib/chunk-VGW4MXXZ.mjs +0 -7
  238. package/lib/chunk-VXHDBYMI.mjs +0 -7
  239. package/lib/chunk-WJY54JO7.mjs +0 -13
  240. package/lib/chunk-WRU5FJFC.mjs +0 -7
  241. package/lib/chunk-X2PY6MWZ.mjs +0 -7
  242. package/lib/chunk-XEFDB2R4.mjs +0 -7
  243. package/lib/chunk-XETCPL7E.mjs +0 -7
  244. package/lib/chunk-Y5CGXLUB.mjs +0 -7
  245. package/lib/chunk-Y6J6QFI2.mjs +0 -7
  246. package/lib/chunk-YMJVMFPY.mjs +0 -7
  247. package/lib/chunk-YPSRZRIT.mjs +0 -7
  248. package/lib/chunk-YS4G22C2.mjs +0 -7
  249. package/lib/chunk-YW2SBL4Z.mjs +0 -7
  250. package/lib/chunk-Z7X534S4.mjs +0 -10
  251. package/lib/chunk-ZE6HKRR4.mjs +0 -9
  252. package/lib/chunk-ZLZRU6MO.mjs +0 -7
  253. package/lib/chunk-ZPYJPGDK.mjs +0 -7
  254. package/lib/chunk-ZQOZ4EFW.mjs +0 -7
  255. package/lib/chunk-ZUTYVST5.mjs +0 -7
  256. package/lib/chunk-ZYEE34WO.mjs +0 -7
@@ -1,10 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as B,b as J}from"./chunk-TYYOBZMU.mjs";import{a as S}from"./chunk-SIOZXPFG.mjs";import{Aa as C,ra as g,sa as D,ta as U,ua as E}from"./chunk-B45CNPUX.mjs";import{b as l,l as m,s as I,u as M,v as K}from"./chunk-7EANH5PY.mjs";import{randomBytes as R}from"node:crypto";import{mkdirSync as ke,statSync as Y}from"node:fs";import{mkdir as w,open as me,readFile as A,readdir as _,rename as we,rm as f,rmdir as ye,stat as x}from"node:fs/promises";import{homedir as V}from"node:os";import{join as c,resolve as Oe}from"node:path";import{promisify as Q}from"node:util";import{gunzip as Fe,gzip as xe}from"node:zlib";import{createHash as ge}from"node:crypto";var G=16,Z=m({digest:l().regex(/^[0-9a-f]{64}$/),fields:I(l(),l().regex(new RegExp(`^[0-9a-f]{${G}}$`)))});function W(n){return ge("sha256").update(n).digest("hex")}function he(n){return JSON.stringify([n.name.toLowerCase(),n.type,n.createable===!0,n.updateable===!0,n.nillable===!0,[...n.referenceTo??[]].sort(),n.encrypted===!0])}function sn(n){let e=n.map(t=>({name:t.name,key:t.name.toLowerCase(),line:he(t)})).sort((t,r)=>t.key<r.key?-1:t.key>r.key?1:0);return{digest:W(e.map(({line:t})=>t).join(`
8
- `)),fields:Object.fromEntries(e.map(({name:t,line:r})=>[t,W(r).slice(0,G)]))}}function cn(n,e){let t={added:[],removed:[],changed:[]};if(n.digest===e.digest)return t;let r=new Map(Object.entries(n.fields).map(([o,s])=>[o.toLowerCase(),{name:o,print:s}])),i=new Map(Object.entries(e.fields).map(([o,s])=>[o.toLowerCase(),{name:o,print:s}]));for(let[o,{name:s,print:a}]of i){let p=r.get(o);p===void 0?t.added.push(s):p.print!==a&&t.changed.push(s)}for(let[o,{name:s}]of r)i.has(o)||t.removed.push(s);return t.added.sort(),t.removed.sort(),t.changed.sort(),t}var h=448,Ie=384,Ce=30,be=3,Pe=15,ee=1440*6e4,P=1440*6e4,De=Q(xe),Ee=Q(Fe),T="checkpoint.json",Se="fingerprints.json.gz",ve="fingerprints.json",ze="snapshots.json",ne=/^[A-Za-z][A-Za-z0-9_]*$/;function On(n=process.env){let e=n.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?Oe(e):c(V(),".sandforge");return c(t,"checkpoints")}function Le(n=V()){return c(n,".sandforge","locks")}function k(n){let e=E.safeParse(n).success?S(n.slice(0,15)):void 0;if(e===void 0)throw new d("invalid","Not an Organization Id");return e}function Re(n){return n.length===18&&E.safeParse(n).success&&S(n.slice(0,15))===n}function v(n,e,t){return te(c(n,e,t),e,t)}function te(n,e,t){return{organizationId:e,checkpointId:t,dir:n,checkpointFile:c(n,T),fingerprintsFile:c(n,Se),plainFingerprintsFile:c(n,ve),snapshotsFile:c(n,ze),indexDir:c(n,"index"),binDir:c(n,"bin"),filesDir:c(n,"files"),previewsDir:c(n,"previews"),rewindsDir:c(n,"rewinds")}}function re(n){if(!ne.test(n)||n.length>80)throw new d("invalid","Not a Salesforce API name");return n}function Fn(n,e){return c(n.indexDir,`${re(e)}.idx`)}function xn(n){return c(n.indexDir,"recreated.ndjson")}function In(n){return c(n.indexDir,"notInBin.ndjson")}function Cn(n,e){return c(n.binDir,`${re(e)}.ids`)}function bn(n){return c(n.filesDir,"documents.ndjson")}function Pn(n){return c(n.filesDir,"links.ndjson")}var Ae=[/^checkpoint\.json$/,/^fingerprints\.json(?:\.gz)?$/,/^snapshots\.json$/,/^backups\/[A-Za-z0-9_-]{1,200}__[A-Za-z][A-Za-z0-9_]{0,79}\.ndjson(?:\.gz)?$/,/^bin\/[A-Za-z][A-Za-z0-9_]{0,79}\.ids$/,/^files\/(?:links|documents)\.ndjson(?:\.gz)?$/,/^index\/(?:recreated|notInBin)\.ndjson$/],je=["","backups","bin","files","index"],Dn=T;function ie(n){return Ae.some(e=>e.test(n))}async function En(n){let e=[];for(let t of je){let r;try{r=await _(c(n.dir,t),{withFileTypes:!0})}catch(i){if(F(i)==="ENOENT"||F(i)==="ENOTDIR")continue;throw i}for(let i of r){let o=t===""?i.name:`${t}/${i.name}`;if(!i.isFile()||!ie(o))continue;let s=c(n.dir,t,i.name);e.push({path:o,file:s,bytes:(await x(s)).size})}}return e.sort((t,r)=>fe(t.path,r.path))}function Sn(n,e){if(!ie(e))throw new d("invalid","Not a file a checkpoint holds");return c(n,...e.split("/"))}function vn(n,e){return c(n.previewsDir,O(D,e))}function H(n,e){return c(n.rewindsDir,O(U,e))}function O(n,e){let t=n.safeParse(e);if(!t.success)throw new d("invalid","Not an id of this store");return t.data}async function X(n){await w(n,{recursive:!0,mode:h})}var q="abcdefghijklmnopqrstuvwxyz0123456789";function zn(n,e=new Date){let t=e.toISOString(),r=`${t.slice(0,4)}${t.slice(5,7)}${t.slice(8,10)}`,i=`${t.slice(11,13)}${t.slice(14,16)}${t.slice(17,19)}`,o=Array.from(R(4),s=>q[s%q.length]).join("");return`${n}-${r}-${i}-${o}`}function Ne(n,e){if(!Number.isInteger(e)||e<0)throw new RangeError(`Not a number of days: ${e}`);return e===0?null:new Date(n.getTime()+e*P).toISOString()}function oe(n,e){return n.expiresAt!==null&&Date.parse(n.expiresAt)<=e}function $e(n,e){if(n.expiresAt===null)return!1;let t=Date.parse(n.expiresAt);return t>e&&t-e<=be*P}function _e(n,e){let t=e-Pe*P;return Date.parse(n.readFrom)<t?new Date(t).toISOString():void 0}function Te(n,e){let t=n.scratchExpiresAt;if(t===void 0)return!1;let r=Date.parse(t);return Number.isFinite(r)?/^\d{4}-\d{2}-\d{2}$/.test(t)?r+P<=e:r<=e:!1}var d=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointStoreError"}code},se=m({version:K(1),objects:I(l().regex(ne).max(80),Z)});async function He(n,e){let t;try{t=JSON.parse(await Ke(n))}catch{throw new d("damaged","The checkpoint\u2019s field prints cannot be read")}let r=se.safeParse(t);if(!r.success)throw new d("damaged","The checkpoint\u2019s field prints do not parse");let i=new Map(Object.entries(r.data.objects));for(let o of e)if(i.get(o.objectApiName)?.digest!==o.fingerprint)throw new d("damaged",`The field prints of ${o.objectApiName} are not the checkpoint\u2019s`);return i}async function Me(n){let e=se.safeParse({version:1,objects:n});if(!e.success)throw new d("invalid",`Not field prints: ${e.error.message}`);return De(`${JSON.stringify(e.data)}
9
- `)}async function Ke(n){let e;try{e=await A(n.fingerprintsFile)}catch(t){if(t.code!=="ENOENT")throw t;return A(n.plainFingerprintsFile,"utf8")}return(await Ee(e)).toString("utf8")}function Ln(n){let e=n.uid??(()=>process.getuid?.()),t=n.locksDir??Le();for(let r of[n.root,t]){let i=Ue(r,e);if(i!==void 0)return{refusal:i}}return{store:new j({...n,locksDir:t})}}function Ue(n,e){try{let t=Y(n,{throwIfNoEntry:!1});if(t!==void 0&&!t.isDirectory())return{reason:"notAFolder",path:n};ke(n,{recursive:!0,mode:h});let r=e();return r!==void 0&&Y(n).uid!==r?{reason:"otherOwner",path:n}:void 0}catch(t){return{reason:"cannotMake",path:n,detail:rn(t)}}}var j=class{root;locksDir;renameFile;lockOptions;changes=new Map;constructor(e){this.root=e.root,this.locksDir=e.locksDir,this.renameFile=e.rename??((t,r)=>we(t,r)),this.lockOptions={...e.lockSelf?{self:e.lockSelf}:{},...e.lockChecks?{checks:e.lockChecks}:{}}}folderOf(e,t){return v(this.root,k(e),O(g,t))}async create(e,t){let r=this.folderOf(e,t);await X(c(this.root,r.organizationId));try{await w(r.dir,{mode:h})}catch(i){throw F(i)==="EEXIST"?new d("exists",`A checkpoint ${t} is kept already`):i}return await w(r.indexDir,{mode:h}),await w(r.binDir,{mode:h}),r}async write(e){let t=z(e),r=this.folderOf(t.org.organizationId,t.checkpointId);await this.writeWhole(r.checkpointFile,N(t))}async writeFingerprints(e,t){await this.writeWhole(e.fingerprintsFile,await Me(t))}async readFingerprints(e,t){return He(e,t.objects)}async checkpointsOf(e){return this.readsOf(k(e))}async read(e){let t=O(g,e);for(let r of await this.organizationKeys()){let i=v(this.root,r,t);if(await y(i.dir))return L(i)}}async update(e,t){let r=async()=>{let a=await this.read(e);if(a===void 0)throw new d("notFound",`No checkpoint ${e} is kept`);if(a.checkpoint===void 0)throw new d("damaged",`The checkpoint ${e} is damaged`);let p=t(structuredClone(a.checkpoint));if(p.checkpointId!==a.folder.checkpointId||$(p.org.organizationId)!==a.folder.organizationId)throw new d("invalid","A change never moves a checkpoint");return await this.write(p),C.parse(p)},o=(this.changes.get(e)??Promise.resolve()).then(r,r),s=o.catch(()=>{});return this.changes.set(e,s),s.then(()=>{this.changes.get(e)===s&&this.changes.delete(e)}),o}keep(e,t,r=new Date){return this.update(e,i=>({...i,expiresAt:t?null:Ne(r,Ce)}))}async list(e={}){let t=(e.now??new Date).getTime(),r=e.organizationId!==void 0?k(e.organizationId):void 0,i=[];for(let o of await this.organizationKeys(r)){let s=await this.readsOf(o),a=Ze(s);for(let p of s)i.push(await Xe(p,t,a,e.refreshedAt))}return i.sort((o,s)=>fe(s.checkpointId,o.checkpointId))}async delete(e){let t=await this.read(e);if(t===void 0)return{outcome:"notFound"};let r=this.lock(t.folder.organizationId,"delete",t.folder.checkpointId);if("busy"in r)return{outcome:"busy",holder:r.busy};try{await f(t.folder.dir,{recursive:!0,force:!0})}finally{r.lock.release()}return t.checkpoint?{outcome:"deleted",checkpoint:t.checkpoint}:{outcome:"deleted"}}async importInto(e,t,r){let i=this.folderOf(e,t),o=c(this.root,i.organizationId);await X(o);let s=te(c(o,`${Be}${R(6).toString("hex")}`),i.organizationId,i.checkpointId);await w(s.dir,{mode:h});try{let a=z(await r(s));if(a.checkpointId!==i.checkpointId||$(a.org.organizationId)!==i.organizationId)throw new d("invalid","An import keeps the checkpoint it was asked to");let p=z({...a,bytes:await Ge(s.dir,a)});if(await this.writeWhole(s.checkpointFile,N(p)),await y(i.dir))return{outcome:"exists"};try{await this.renameFile(s.dir,i.dir)}catch(u){if(await y(i.dir))return{outcome:"exists"};throw u}return{outcome:"imported",checkpoint:p}}finally{await f(s.dir,{recursive:!0,force:!0}),await ye(o).catch(()=>{})}}async sweep(e=new Date){let t=e.getTime(),r={checkpoints:[],journals:[],previews:0,skipped:[]};for(let i of await this.organizationKeys()){await We(c(this.root,i),t);let o=await qe(await this.readsOf(i),t);if(o.length===0)continue;let s=this.lock(i,"sweep");if("busy"in s){r.skipped.push(i);continue}try{for(let a of o)await Ve(await L(a),t,r)}finally{s.lock.release()}}return r}lock(e,t,r){return nn(this.locksDir,e,{operation:t,...r!==void 0?{checkpointId:r}:{}},this.lockOptions)}heldBy(e){return tn(this.locksDir,e,this.lockOptions)}async organizationKeys(e){return(await b(this.root)).filter(r=>Re(r)&&(e===void 0||r===e))}async readsOf(e){let t=(await b(c(this.root,e))).filter(i=>g.safeParse(i).success),r=[];for(let i of t)r.push(await L(v(this.root,e,i)));return r}async writeWhole(e,t){let r=`${e}.${process.pid}-${R(4).toString("hex")}.tmp`,i=await me(r,"wx",Ie);try{try{await i.writeFile(t,typeof t=="string"?"utf8":void 0),await i.sync()}finally{await i.close()}await this.renameFile(r,e)}catch(o){throw await f(r,{force:!0}),o}}},Be=".importing-",Je=/^\.importing-[0-9a-f]{12}$/;async function We(n,e){for(let t of await b(n)){if(!Je.test(t))continue;let r=c(n,t),i=await x(r).catch(()=>{});i!==void 0&&i.mtimeMs+ee<=e&&await f(r,{recursive:!0,force:!0})}}function z(n){let e=C.safeParse(n);if(!e.success)throw new d("invalid",`Not a checkpoint: ${e.error.message}`);return e.data}function N(n){return`${JSON.stringify(n,null,2)}
10
- `}async function ce(n,e){let t=0;for(let r of await _(n,{withFileTypes:!0})){let i=c(n,r.name);r.isDirectory()?t+=await ce(i,e):r.isFile()&&i!==e&&(t+=(await x(i)).size)}return t}async function Ge(n,e){let t=await ce(n,c(n,T)),r=o=>Buffer.byteLength(N({...e,bytes:o}),"utf8"),i=t+r(t);return i=t+r(i),i}async function L(n){let e;try{e=JSON.parse(await A(n.checkpointFile,"utf8"))}catch{return{folder:n}}let t=C.safeParse(e);return t.success?t.data.checkpointId!==n.checkpointId||$(t.data.org.organizationId)!==n.organizationId?{folder:n}:{folder:n,checkpoint:t.data}:{folder:n}}function Ze(n){let e;for(let{folder:t,checkpoint:r}of n){let i=r?.lastRewind?.rewindId;i!==void 0&&(e===void 0||i>e.rewindId)&&(e={checkpointId:t.checkpointId,rewindId:i})}return e}function Ye(n,e,t,r){if(n.status==="taking")return{why:"taking"};if(n.status==="failed")return{why:"failed"};let i=r?.(e);if(i!==void 0)return{why:"refreshed",refreshedAt:i};if(Te(n.org,t))return{why:"scratchExpired"}}async function Xe({folder:n,checkpoint:e},t,r,i){let o={checkpointId:n.checkpointId,organizationId:n.organizationId};if(e===void 0)return{...o,valid:!1,why:"damaged"};let s=Ye(e,n.organizationId,t,i);if(s!==void 0)return{...o,checkpoint:e,valid:!1,why:s.why,...s.refreshedAt!==void 0?{refreshedAt:s.refreshedAt}:{}};let a={...o,checkpoint:e,valid:!0};$e(e,t)&&(a.expiresSoon=!0);let p=_e(e,t);p!==void 0&&(a.binReachSince=p);let u=e.lastRewind;return u!==void 0&&r?.checkpointId===n.checkpointId&&u.undoUntil!==void 0&&u.undoneAt===void 0&&Date.parse(u.undoUntil)>t&&await y(H(n,u.rewindId))&&(a.undo={rewindId:u.rewindId,until:u.undoUntil}),a}async function qe(n,e){let t=[];for(let{folder:r,checkpoint:i}of n)i!==void 0&&(oe(i,e)||await ae(r,i,e)||(await de(r,e)).length>0)&&t.push(r);return t}async function ae(n,e,t){let r=e.lastRewind?.undoUntil;return e.lastRewind!==void 0&&r!==void 0&&Date.parse(r)<=t&&await y(H(n,e.lastRewind.rewindId))}async function de(n,e){let t=[];for(let r of await b(n.previewsDir)){if(!D.safeParse(r).success)continue;let i=c(n.previewsDir,r),o=await x(i).catch(()=>{});o!==void 0&&o.mtimeMs+ee<=e&&t.push(i)}return t}async function Ve(n,e,t){let{folder:r,checkpoint:i}=n;if(i===void 0)return;if(i.expiresAt!==null&&oe(i,e)){await f(r.dir,{recursive:!0,force:!0});let s=i.lastRewind?.undoUntil,a=s!==void 0&&i.lastRewind?.undoneAt===void 0&&Date.parse(s)>e;t.checkpoints.push({organizationId:r.organizationId,checkpointId:r.checkpointId,name:i.name,...i.org.alias!==void 0?{alias:i.org.alias}:{},takenAt:i.takenAt,expiresAt:i.expiresAt,...a?{undoUntil:s}:{}});return}let o=i.lastRewind;o?.undoUntil!==void 0&&await ae(r,i,e)&&(await f(H(r,o.rewindId),{recursive:!0,force:!0}),t.journals.push({organizationId:r.organizationId,checkpointId:r.checkpointId,name:i.name,rewindId:o.rewindId,undoUntil:o.undoUntil}));for(let s of await de(r,e))await f(s,{recursive:!0,force:!0}),t.previews+=1}var Qe=m({...B,operation:M(["take","rewind","undo","delete","sweep","empty"]),checkpointId:g.optional()}),pe=J(n=>{let e=Qe.safeParse(n);return e.success?e.data:void 0});function en(n,e){return c(n,`${k(e)}.lock`)}function nn(n,e,t,r={}){let i=k(e),o=t.checkpointId!==void 0?O(g,t.checkpointId):void 0,s=pe.acquire(c(n,`${i}.lock`),a=>({...a,operation:t.operation,...o!==void 0?{checkpointId:o}:{}}),r);return"busy"in s?{busy:ue(s.busy)}:{lock:{organizationId:i,release:s.lock.release}}}function tn(n,e,t={}){let r=pe.holder(en(n,e),t);return r!==void 0?ue(r):void 0}function ue({version:n,token:e,...t}){return t}async function b(n){try{return(await _(n,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch(e){if(F(e)==="ENOENT"||F(e)==="ENOTDIR")return[];throw e}}async function y(n){return(await x(n).catch(()=>{}))?.isDirectory()===!0}function $(n){try{return k(n)}catch{return}}function fe(n,e){return n<e?-1:n>e?1:0}function F(n){return n?.code}function rn(n){return n instanceof Error?n.message:String(n)}export{sn as a,cn as b,h as c,Ie as d,Ce as e,be as f,Pe as g,ee as h,On as i,Le as j,k,Fn as l,xn as m,In as n,Cn as o,bn as p,Pn as q,Dn as r,ie as s,En as t,Sn as u,vn as v,H as w,X as x,zn as y,Ne as z,oe as A,$e as B,_e as C,Te as D,d as E,He as F,Me as G,Ln as H,j as I,Ze as J,en as K,nn as L,tn as M};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i,l as j,m as k,n as l,o as m,p as n,q as o,r as p,s as q,t as r,u as s,v as t,w as u,x as v,y as w}from"./chunk-NTDN2JQZ.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{g as IDS_PER_LINE,l as OverwritesRead,h as PIPELINE_NAME_KEPT,e as SCENARIO_COMPANION_SUFFIX,d as SYNC_FILE_OBJECTS,a as SYNC_RUNS_DIR,c as SYNC_RUNS_HARD_MAX_BYTES,b as SYNC_RUNS_MAX_BYTES,w as SyncRunCreations,i as backupIdSchema,t as configTargetOf,n as createdCount,q as deletedCount,u as earlierRunsOf,f as nodeSyncRunCreations,o as overwrittenCount,j as readRemovalState,k as readRunFile,s as settled,m as syncRemovalPlan,p as syncRestorePlan,r as syncUndeletePlan,v as writtenAgainBy};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c}from"./chunk-ALUFROGA.mjs";import"./chunk-TBZMC2VV.mjs";import"./chunk-LQ4DRFUH.mjs";import"./chunk-57VHUYNG.mjs";import"./chunk-5O6JOMHS.mjs";import"./chunk-HUMEKZT5.mjs";import"./chunk-MYTIL2JD.mjs";import"./chunk-JVL444U5.mjs";import"./chunk-KLX67VPL.mjs";import"./chunk-5CD257T7.mjs";import"./chunk-H45UXY6G.mjs";import"./chunk-5P4PHJRL.mjs";import"./chunk-SRQDABQ2.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-LV6G4XTK.mjs";import"./chunk-HJKM3E56.mjs";import"./chunk-XCA5AONB.mjs";import"./chunk-WR2GIKWE.mjs";import"./chunk-YMJVMFPY.mjs";import"./chunk-ALJVEUUS.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-4HFRHFGQ.mjs";import"./chunk-342FN7AO.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-Z7X534S4.mjs";import"./chunk-6QSM2WIH.mjs";import"./chunk-WJY54JO7.mjs";import"./chunk-T63U4OZJ.mjs";import"./chunk-DBFJB2B6.mjs";import"./chunk-NEVXIGR6.mjs";import"./chunk-NTDN2JQZ.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-SAR5622P.mjs";import"./chunk-6MUEPV7M.mjs";import"./chunk-HJC7AIBK.mjs";import"./chunk-OTWRDD6L.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-RH3N2H7P.mjs";import"./chunk-ZUTYVST5.mjs";import"./chunk-55HEMHEG.mjs";import"./chunk-P42X3B4D.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-VXHDBYMI.mjs";import"./chunk-ENLBYECD.mjs";import"./chunk-PA3MKJVH.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-ZLZRU6MO.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-PNCONNFJ.mjs";import"./chunk-CGWXQX75.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-SIOZXPFG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{b as UNDO_AUTOMATION_LIFTED_BY,a as UndoStopped,c as undoCheckpoint};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as fe}from"./chunk-IAZB4WIL.mjs";import{I as me,O as pe,b as le}from"./chunk-XEFDB2R4.mjs";import{$a as ue,bb as ce,h as ie,i as ae,j as de,k as B}from"./chunk-36U7IQ6Y.mjs";import{Ja as se,la as re,ma as ne,na as M,oa as oe,va as v,w as te}from"./chunk-VXHDBYMI.mjs";import{b as z}from"./chunk-WIO4XO4F.mjs";import{h as ee}from"./chunk-PNCONNFJ.mjs";import{p as $}from"./chunk-CGWXQX75.mjs";import{c as J,d as Y,g as Z}from"./chunk-SIOZXPFG.mjs";import{b as F}from"./chunk-CA5NAXSU.mjs";import{$c as Q,Hc as U,Kc as G,Mc as C,Xc as K,_c as H,ad as V,bd as X,fc as W,g as _,h as I,vb as q}from"./chunk-B45CNPUX.mjs";var N=1e4;function we(e,n){if(e.aborted||e.outcomes.length!==n||(e.unmatchedIds?.length??0)>0||e.failures.some(r=>r.recordIndex<0))return;let t=new Array(n);for(let r of e.outcomes){if(r.recordIndex<0||r.recordIndex>=n)return;if(r.success){if(!r.id)return;t[r.recordIndex]={id:r.id}}else{let o=r.error??"Unknown error",i=Y(o);t[r.recordIndex]={error:o,...i?{errorDetails:[i]}:{}}}}return t.every(r=>r!==void 0)?t:void 0}function _e(e){let{conn:n,bulkManager:t,retry:r,signal:o,label:i}=e,p=new ee(e.bulkThreshold),f,b=async(h,d,m)=>{f??=ce(n).then(R=>(R||e.log(`[WARN] ${i}: the org's duplicate rules could not be read: an object of more than the Bulk API threshold goes as a Bulk API job, which a duplicate rule may refuse`),R));let y=await f;if(y===void 0)return ue.has(h)?(e.log(`[INFO] ${i}: ${h} goes through REST: the duplicate rules could not be read, and a standard rule watches it`),!0):!1;let w=y.has(h);return w&&e.log(`[INFO] ${i}: ${h} goes through REST: an active duplicate rule watches it, which a Bulk API job cannot waive`+(d>N?` \u2014 ${d} records in ${Math.ceil(d/Math.max(1,m))} calls, slower than one job`:"")),w};return async(h,d,m,y)=>{let w=(m.length>N||p.shouldUseBulkApi(m.length))&&await b(d,m.length,y),R=w&&await f===void 0?[`The org's duplicate rules could not be read (the user SandForge connects as needs View Setup and Configuration): ${d}, which a standard duplicate rule watches, was sent through REST, whose header lets its matches be saved, rather than as a Bulk API job.`]:[];if(m.length>N&&!w){if(o.aborted)return{successIds:[],errors:[],stopped:!0};let g=new le({signal:o}),s={connection:n,bulkManager:t,onProgress:(a,l)=>{e.onProgress(a,l,`Streaming insert ${d}`)},onOpened:a=>e.calls?.sending(d,m.length,{job:a})};e.calls?.sending(d,m.length);let u=await g.executeChunked(s,d,"insert",g.createChunkGenerator(m),m.length);return e.calls?.answered(d,u.aborted?[]:u.successIds),{successIds:u.successIds,errors:u.errors,...u.aborted?{stopped:!0}:{}}}if(p.shouldUseBulkApi(m.length)&&!w){if(o.aborted)return{successIds:[],errors:[],stopped:!0};let g={connection:n,bulkManager:t,onProgress:(a,l)=>{e.onProgress(a,l,`Bulk insert ${d}`)},signal:o,onOpened:a=>e.calls?.sending(d,m.length,{job:a})};e.calls?.sending(d,m.length);let s=await p.executeBulk(g,d,"insert",m);e.calls?.answered(d,s.aborted?[]:s.successIds);let u=we(s,m.length);return{successIds:s.successIds,errors:s.failures.map(a=>a.error),...u?{rows:u}:{},...s.aborted?{stopped:!0}:{}}}let A=[],S=[],c=[];for(let g=0;g<m.length;g+=y){if(o.aborted)return{successIds:A,errors:S,rows:c,stopped:!0};let s=m.slice(g,g+y);e.calls?.sending(d,s.length);let u=await r.execute(async()=>n.sobject(d).create(s,{headers:q()}));if(u.cancelled)return e.calls?.answered(d,[]),{successIds:A,errors:S,rows:c,stopped:!0};if(u.success&&u.result){let a=[];for(let l of u.result)if(l.success&&l.id)A.push(l.id),a.push(l.id),c.push({id:l.id});else{let E=Z(l.errors);S.push(E),c.push({error:E,errorDetails:(l.errors??[]).map(J)})}e.calls?.answered(d,a)}else{let a=u.error?.message??"Insert failed after retries";for(let l=0;l<s.length;l++)S.push(a),c.push({error:a});e.calls?.answered(d,[])}}return{successIds:A,errors:S,rows:c,...R.length>0?{notes:R}:{}}}}var Re="SELECT Id, DeveloperName FROM RecordType WHERE SobjectType = 'Account' AND IsPersonType = true";async function Ge(e){try{return(await e.query(Re)).records.flatMap(t=>typeof t.Id=="string"&&typeof t.DeveloperName=="string"?[{id:t.Id,developerName:t.DeveloperName}]:[])}catch{return[]}}function Ke(e,n,t){let r=new Set(e===$?t.map(o=>o.id.slice(0,15)):[]);return z(n).filter(o=>!o.master&&o.active&&o.available).map(o=>({recordTypeId:o.recordTypeId,developerName:o.developerName,label:o.name,person:r.has(o.recordTypeId.slice(0,15)),isDefault:o.defaultRecordTypeMapping}))}function Ae(e){let{staticValue:n,picklistValues:t}=e.config;return e.ruleType==="static"&&typeof n=="string"?[n]:e.ruleType==="picklist_random"?[...t??[]]:[]}function He(e,n){if(n.length===0)return{template:e,personObjects:[]};let t=new Map(n.map(i=>[i.id.slice(0,15),i.developerName])),r=[],o=[];for(let i of e.objects){if(i.objectApiName!==$){o.push(i);continue}let p=i.fieldRules.find(d=>d.fieldApiName==="RecordTypeId"),f=p?Ae(p):[],b=f.filter(d=>t.has(d.slice(0,15)));if(b.length>0&&b.length<f.length){let d=b.map(m=>t.get(m.slice(0,15))).join(", ");return{refusal:`${$}: ${d} ${b.length===1?"is a person account record type":"are person account record types"} and the other record types chosen are not: a person account and a business account take different fields. Seed one kind in a run.`}}let h=b.length>0?"person":"business";h==="person"&&r.push(i.objectApiName),o.push({...i,fieldRules:i.fieldRules.filter(d=>!W($,d.fieldApiName,h))})}return{template:{...e,objects:o},personObjects:r}}var ke=/^[a-z]{2,3}(?:_[A-Za-z0-9]{2,4}){0,2}$/;async function Ee(e){try{let t=(await e.query("SELECT DefaultLocaleSidKey FROM Organization LIMIT 1")).records[0]?.DefaultLocaleSidKey;return typeof t=="string"&&ke.test(t)?t:void 0}catch{return}}async function Ve(e,n){return e??await Ee(n)??"en_US"}var tt="SEED_FIT_STORAGE_UNREAD",rt="SEED_CANNOT_FIT";function nt(e,n=!1){return L(e.objects.filter(t=>t.recordCount>0).map(t=>t.objectApiName),n)}function L(e,n=!1){let t=new Set(e);return(r,o)=>t.has(r)&&(o==="insert"||o==="update"&&n&&r===fe)}function ot(e,n,t){if(typeof e.unread=="string")return{room:{perRecord:[],notCounted:[],unread:e.unread},unread:e.unread};let r=X(e,n,t);return{running:r,room:ie(r,t)}}function P(e,n){return I(e.objectApiName,n)?.distribution.mode==="byKey"?"byKey":e.rows!==void 0?"rows":void 0}function ge(e,n){let t=I(e,n.relations);if(!(!t||t.parents.kind!=="generated"||t.distribution.mode==="byKey"||t.parentObject===e||!n.objects.some(r=>r.objectApiName===t.parentObject)))return t}function he(e,n){let t=n?.objects?.[e.objectApiName]??n?.all;return t!==void 0?Math.min(e.recordCount,Math.max(1,Math.floor(t))):e.recordCount}function je(e,n,t){let r=new Map(e.objects.map(f=>[f.objectApiName,f])),o=new Map,i=new Set,p=f=>{let b=o.get(f);if(b!==void 0)return b;let h=r.get(f);if(P(h,e.relations))return o.set(f,h.recordCount),h.recordCount;i.add(f);let d=Math.round(n*he(h,t)),m=ge(f,e),y=m&&!i.has(m.parentObject)?Math.max(1,Math.min(d,_(m.distribution,p(m.parentObject)))):Math.max(1,d);return i.delete(f),o.set(f,y),y};return new Map(e.objects.map(f=>[f.objectApiName,p(f.objectApiName)]))}function $e(e,n){if(n.cannotFit!==void 0)return e;let t=new Map(n.objects.map(r=>[r.objectApiName,r.after]));return{...e,objects:e.objects.map(r=>{let o=t.get(r.objectApiName);return o!==void 0&&o<r.recordCount?{...r,recordCount:o}:r})}}function Te(e,n){let t=e.objects.filter(i=>!P(i,e.relations)),r=t.filter(i=>!ge(i.objectApiName,e)),o;for(let i of r.length>0?r:t){let p=he(i,n);(!o||p>o.records)&&(o={objectApiName:i.objectApiName,records:p})}return o}function Oe(e){return`${e} record${e===1?"":"s"}`}function xe(e){let{template:n,personObjects:t,budget:r,room:o}=e,i=e.ask?.caps,p=e.ask?.share===!0||i===void 0,f=a=>{let l=je(n,a,i),E=$e(n,{objects:n.objects.map(k=>({objectApiName:k.objectApiName,before:k.recordCount,after:l.get(k.objectApiName)??k.recordCount}))}),j=ae(o,k=>l.get(k)??0);return{counts:l,bytes:pe(E,t)+j,roomBytes:j,requests:me(E,e.path),records:[...l.values()].reduce((k,x)=>k+x,0)}},b=a=>a.bytes<=r.bytes,h=a=>r.runRequests===void 0||a.requests<=r.runRequests,d=a=>b(a)&&h(a),m=(a,l,E,j)=>({share:a,budget:{...de(r,l.roomBytes,o),...E==="apiRequests"?{limitedBy:"apiRequests"}:{}},objects:n.objects.map(k=>{let x=P(k,n.relations);return{objectApiName:k.objectApiName,before:k.recordCount,after:l.counts.get(k.objectApiName)??k.recordCount,...x?{keptWhole:x}:{}}}),estimateMB:l.bytes/1048576,...j!==void 0?{cannotFit:j}:{},...o.unread!==void 0?{automationUnread:o.unread}:{}}),y=(a,l,E,j)=>({proposal:m(a,l,E,j),heldBy:E,records:l.records,requests:l.requests}),w=a=>{if(b(a))return`about ${a.requests} API requests, past the ${r.runRequests??0} that leave the org a tenth of its daily requests`;let l=se(a.bytes/1048576,r.bytes/1048576);return`${l.over} MB`+(a.roomBytes>0?", room for what the org's automation creates under them included":"")+`, past the ${l.bound} MB that fit`},R=a=>b(a)?"apiRequests":r.terms.limitedBy,A=n.objects.filter(a=>P(a,n.relations)).reduce((a,l)=>a+l.recordCount,0),S=f(1);if(d(S)){let a=n.objects.some(l=>(S.counts.get(l.objectApiName)??0)<l.recordCount);return y(1,S,a?"caps":"whole")}if(!p)return y(1,S,R(S),`with these caps the seed takes ${w(S)}: lower them, or fit by share`);let c=Te(n,i);if(!c)return y(1,S,R(S),`the ${A} rows the template gives take ${w(S)}, and rows are kept whole`);let g=a=>f(a/c.records),s=B(c.records,a=>d(g(a)));if(s===0){let a=g(1);return y(1/c.records,a,R(a),`the least it can be cut to \u2014 one ${c.objectApiName} and what follows it`+(A>0?`, with the ${A} rows the template gives kept whole`:"")+`, ${Oe(a.records)} \u2014 takes ${w(a)}`)}let u=B(c.records,a=>b(g(a)));return y(s/c.records,g(s),u>s?"apiRequests":r.terms.limitedBy)}function st(e,n,t,r,o){if(!("unread"in e))return xe({template:n,personObjects:t,budget:e,room:r,path:o}).proposal}function it(e,n){if(!(!e||e.before<n))return{module:"seed",share:e.share,...e.withinMB!==void 0?{withinMB:e.withinMB}:{},kept:n,inSource:e.before}}var Se=(e,n)=>n==="insert";function be(e){return typeof e.unread=="string"}function Ce(e){return(U(e).find(t=>t.write==="insert")?.fired??[]).map(t=>{let r=t.flow,o=r?.messages??[];return{kind:t.kind,name:t.name,when:t.when,emails:o.filter(i=>i.kind==="email").length,messages:[...new Set(o.flatMap(i=>i.kind==="email"?[]:[i.kind]))],creates:[...r?.creates??[]],afterCommit:(r?.paths?.length??0)>0,bypasses:(r?.permissions??[]).filter(i=>i.bypass).map(({name:i,held:p})=>p===void 0?{name:i}:{name:i,held:p}),keptQuiet:t.keptQuiet===!0,unread:r!==void 0&&r.condition!=="read"}})}function O(e){return[...new Set(e)].sort((n,t)=>n.localeCompare(t))}function ye(e,n,t,r,o=Se){let i=e.objects.flatMap(c=>{let g=Ce(c);return g.length>0?[{objectApiName:c.objectApiName,entries:g}]:[]}),p=be(t)?void 0:t,f=p!==void 0&&re(p),b=p!==void 0&&ne(p),h=M(C(e),f,b),d=i.flatMap(c=>c.entries.flatMap(g=>g.bypasses)),m=O(d.filter(c=>c.held===!0).map(c=>c.name)),y=O(d.map(c=>c.name)).filter(c=>!m.includes(c)),w=K(e,y),R=y.map(c=>{let g=w.find(s=>s.permission.toLowerCase()===c.toLowerCase())?.permissionSet;return g?{permission:c,permissionSet:g.name}:{permission:c}}),A=H(e,o),S=A.assign.length>0;return{org:n,objectsRead:[...e.objectsRead],objects:i,emailsPerRecord:h,...p&&h.length>0?{limits:{...p}}:{},...be(t)?{limitsUnread:t.unread}:{},alertsAsSingle:f,bypasses:R,bypassesHeld:m,...S?{mute:A,emailsPerRecordMuted:M(C(V(e,Q(A))),f,b)}:{},unread:e.unread.map(({part:c,reason:g})=>({part:c,reason:g})),blinded:G(e.unread),conditionsNotRead:e.conditionsNotRead,...r?{deliverability:r}:{}}}async function pt(e){let n=e.writes??L(e.objects),t;try{t=await e.readAutomation(e.objects)}catch(i){return{error:F(i)}}let r=e.deliverability??(e.readDeliverability?(await te({read:t,writes:Se,readDeliverability:e.readDeliverability,accepted:!1,target:e.org,run:"seed"})).gate.deliverability:void 0);if(C(t).length===0)return{preview:ye(t,e.org,{},r,n)};let o=await e.readLimits().catch(i=>({unread:F(i)}));return{preview:ye(t,e.org,o,r,n)}}function T(e,n="and"){return e.length<=1?e.join(""):e.length===2?`${e[0]} ${n} ${e[1]}`:`${e.slice(0,-1).join(", ")}, ${n} ${e[e.length-1]}`}var ft="SEED_EMAILS_EXCEEDED";function gt(e,n,t){if("error"in e)return{checks:[],unknown:[`what ${t} runs as these records are created could not be read (${e.error}): the emails they make it send are not known`]};let{preview:r}=e,o={objects:n.map(s=>({objectApiName:s.objectApiName,rows:s.recordCount,storageBytes:0}))},i=r.limitsUnread!==void 0?{unread:r.limitsUnread}:r.limits??{},p=oe(o,r.emailsPerRecord,i),f=new Set(n.filter(s=>s.recordCount>0).map(s=>s.objectApiName)),b=r.objects.flatMap(s=>f.has(s.objectApiName)?s.entries.filter(u=>u.unread&&!u.keptQuiet&&u.when!=="before").map(u=>`"${u.name}" on ${s.objectApiName}`):[]),h=[...p.filter(s=>s.verdict==="unread").map(s=>`about ${v(s.emails,s.limit)}, but what ${t} has left today could not be read (${s.unread??"not said"})`),...r.blinded?[`part of what ${t} runs could not be read: emails it sends may not be counted`]:[],...b.length>0?[`the emails of ${T(b)} are not counted: what ${b.length===1?"it does":"they do"} was not read`]:r.conditionsNotRead>0?[`${r.conditionsNotRead} start condition(s) of ${t} not read: the emails of those flows are not counted`]:[]],d=p.find(s=>s.verdict==="exceeds");if(!d)return h.length>0?{checks:p,unknown:h}:{checks:p};let m=p.filter(s=>s.verdict==="exceeds"),y=O(m.flatMap(s=>s.objects.map(u=>u.objectApiName))),w=O(m.flatMap(s=>s.objects.flatMap(u=>u.sentBy))),R=new Map;for(let s of r.objects.flatMap(u=>u.entries))if(!(s.emails===0||!w.includes(s.name)))for(let{name:u}of s.bypasses)R.set(u,(R.get(u)??new Set).add(s.name));let A=r.bypasses.flatMap(s=>{let u=R.get(s.permission);return u?[{...s,quiets:O([...u])}]:[]}),S=m.map(s=>`about ${v(s.emails,s.limit)} (`+s.objects.map(u=>`${u.perRecord} per ${u.objectApiName}`).join(", ")+`), ${s.remaining??0} of ${s.max??0} left today`).join("; "),c=["lower the record counts",`set ${T(y)} to 0`,`turn off ${T(w.map(s=>`"${s}"`))}`,...A.map(s=>"give the user the seed writes as "+(s.permissionSet?`the permission set ${s.permissionSet}, whose ${s.permission}`:`a permission set holding ${s.permission}, which`)+` keeps ${T(s.quiets.map(u=>`"${u}"`))} quiet`)],g=`The seed was refused before it wrote anything: its records would make ${t} send ${S}. Past what is left, a flow that sends in the save refuses its record (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. To seed it, ${T(c,"or")}. Nothing was written.`;return{checks:p,refusal:g,figures:{org:t,limit:d.limit,emails:d.emails,remaining:d.remaining??0,max:d.max??0,objects:y,senders:w,bypasses:A},...h.length>0?{unknown:h}:{}}}var Pe={flow:e=>`flow "${e}"`,trigger:e=>`Apex trigger ${e}`,process:e=>`process "${e}"`,workflowRule:e=>`workflow rule "${e}"`},Ie={before:"before save",after:"after save",beforeAndAfter:"before and after save"},Fe={notification:"custom notifications",outbound:"outbound messages",sms:"text messages"};function Me(e){let n=r=>r.held===!0?" (held)":r.held===!1?" (not held)":"",t=[Ie[e.when],...e.emails>0?[`${e.emails} email(s) a record`]:[],...e.messages.map(r=>`sends ${Fe[r]}`),...e.creates.length>0?[`creates ${e.creates.join(", ")}`]:[],...e.afterCommit?["then after commit"]:[],...e.bypasses.length>0?[`not for a user with ${e.bypasses.map(r=>r.name+n(r)).join(", ")}`]:[],...e.keptQuiet?["quiet for this seed"]:[],...e.unread?["what it does was not read"]:[]];return`${Pe[e.kind](e.name)} (${t.join("; ")})`}function ht(e,n){if("error"in e)return[`target automation: what ${n} runs as these records are created could not be read (${e.error}): the emails they make it send are not known`];let{preview:t}=e,r=[`target automation: what ${n} runs as these records are created`];for(let o of t.objects)r.push(` ${o.objectApiName}: ${o.entries.map(Me).join(", ")}`);t.objects.length===0&&r.push(t.blinded?" nothing found in what could be read":" nothing runs on them: no flow, Apex trigger, process or workflow rule"),t.bypassesHeld.length>0&&r.push(` bypass held: the user the seed writes as holds ${t.bypassesHeld.join(", ")}, and what names it stays quiet`);for(let o of t.bypasses)r.push(o.permissionSet?` bypass: ${o.permission} keeps quiet what names it; permission set ${o.permissionSet} holds it`:` bypass: ${o.permission} keeps quiet what names it; no permission set of ${n} was found to hold it`);t.alertsAsSingle&&t.emailsPerRecord.some(o=>o.alertsAmong)&&r.push(` ${n} counts its email alerts against its single emails too, as a Developer Edition does`);for(let{part:o,reason:i}of t.unread)r.push(` ${o} could not be read: ${i}`);return t.conditionsNotRead>0&&r.push(` ${t.conditionsNotRead} start condition(s) not read`),r}export{_e as a,Ge as b,Ke as c,He as d,Ve as e,tt as f,rt as g,nt as h,L as i,ot as j,$e as k,xe as l,st as m,it as n,pt as o,ft as p,gt as q,ht as r};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{wb as C,xb as O}from"./chunk-B45CNPUX.mjs";import{b as y,f as b,l as R}from"./chunk-7EANH5PY.mjs";var j=["User","Group","Profile","UserRole","RecordType","Organization","Queue","PermissionSet","BusinessProcess","CurrencyType","DandBCompany","DuplicateRecordItem","DuplicateRecordSet","ProcessInstance","LoginHistory","LoginEvent","LoginIp","LoginGeo","AsyncApexJob","ApexLog","ApexTestResult","ApexTestQueueItem","LightningUsageByPageMetrics","LightningExitByPageMetrics","EventBusSubscriber","PlatformEventUsageMetric","CronTrigger","CronJobDetail","AttachedContentDocument","AttachedContentNote","CombinedAttachment","ContentBody","NoteAndAttachment","OwnedContentDocument","EntitySubscription","TopicAssignment","UserRecordAccess","DeclinedEventRelation","UndecidedEventRelation","AcceptedEventRelation","OpenActivity","ActivityHistory","AppUsageAssignment","AuthProvider","Folder","ContentDocument","ContentDocumentLink","OpportunityRelatedDeleteLog","CaseHistory2","Calendar","SlaProcess","AccountCleanInfo","ContactCleanInfo","LeadCleanInfo","ApprovalSubmission","ApprovalSubmissionDetail","ApprovalWorkItem","AIRecordInsight","AIInsightValue","MatchingInformation","Invoice","InvoiceLine","CreditMemo","CreditMemoLine","AppDefinition","BackgroundOperation","ContentTaxonomyTermRelationshipType","Dashboard","DashboardComponent","DeleteEvent","ManagedContentChannel","ManagedContentSpace","ManagedContentVariant","Report","ServiceSetupProvisioning","TabDefinition"],v=new Set(j.map(e=>e.toLowerCase())),P=["History","Feed","Share","ChangeEvent","__hd","__Tag","EventStore"].map(e=>e.toLowerCase()),F=/^vlocity_[a-z0-9]+__/;function W(e,t){return I(e,t,{byNamespace:!0})}function I(e,t,r){let n=e.toLowerCase();return v.has(n)||C(e)||t&&(t.has(e)||B(t).has(n))||r.byNamespace&&F.test(n)?!0:P.some(s=>n.endsWith(s))}var w=new WeakMap;function B(e){let t=w.get(e);if(t&&t.size===e.size)return t.names;let r=new Set([...e].map(n=>n.toLowerCase()));return w.set(e,{size:e.size,names:r}),r}function U(e,t){return O(e)||W(e,t)}function E(e){return O(e)||I(e,void 0,{byNamespace:!1})}function x(e,t=[]){let r=new Set(t);for(let n of e)n.createable===!1&&r.add(n.name);return r}function ce(e,t=r=>U(r)){return new Set(e.filter(r=>{let n=r.referenceTo??[];return n.length>0&&n.every(s=>t(s))}).map(r=>r.name))}var fe=R({name:y(),queryable:b().optional(),createable:b().optional(),updateable:b().optional(),deletable:b().optional(),undeletable:b().optional(),customSetting:b().optional(),layoutable:b().optional(),keyPrefix:y().nullish()}).loose(),D="ContentDocument",z="ContentDocumentLink",G="ContentVersion",L="Attachment",H=[D,L],J=new Set(["feeditem","feedcomment","feedattachment"]),K=new Set(["casehistory2"]),V=new Set(["AccountCleanInfo","ContactCleanInfo","LeadCleanInfo","ApprovalSubmission","ApprovalSubmissionDetail","ApprovalWorkItem","ProcessInstance","ProcessInstanceNode","ProcessInstanceStep","ProcessInstanceWorkitem","AIRecordInsight","AIInsightValue","AIInsightAction","AIInsightFeedback","AIInsightReason","MatchingInformation","Invoice","InvoiceLine","CreditMemo","CreditMemoLine","CreditMemoInvApplication"].map(e=>e.toLowerCase())),X=new Set([G,z].map(e=>e.toLowerCase())),Y=["__b","__x","__dlm","__kav","__ka","__e"],Q=new Set(["AccountContactRole",L,"CaseTeamMember","EmailMessageRelation","EventRelation","OpportunityCompetitor"].map(e=>e.toLowerCase()));function Z(e,t,r,n,s){let o=e.name.toLowerCase();return J.has(o)||o.endsWith("feed")?"chatter":o.endsWith("history")||o.endsWith("__hd")||K.has(o)?"history":o.endsWith("share")?"sharing":o.endsWith("changeevent")?"changeEvent":Y.some(a=>o.endsWith(a))?"unsupportedKind":e.customSetting===!0?n?A(e,s)?void 0:"notWritable":"customSetting":X.has(o)?"heldWithFiles":o===D.toLowerCase()?(s==="delete"?_(e):T(e))?void 0:"notWritable":o===L.toLowerCase()?A(e,s)?void 0:"notWritable":C(e.name)?"files":V.has(o)?"platformCreated":E(e.name)||r==="everything"&&e.layoutable===!1&&!Q.has(o)?"setup":t.out.has(o)?t.tooling.has(o)?"metadata":"notWritable":A(e,s)?void 0:"notWritable"}function A(e,t){return t==="delete"?_(e):$(e)}function $(e){return e.createable===!0&&T(e)}function _(e){return e.queryable===!0&&e.deletable===!0}function T(e){return e.queryable===!0&&e.updateable===!0&&e.deletable===!0}function k(e,t){return e.objectApiName<t.objectApiName?-1:e.objectApiName>t.objectApiName?1:0}var q="all";function ee(e){return e.customSetting===!0}function te(e,t){let r=e.filter(ee);if(t===void 0)return{held:new Set,unknown:[]};if(t===q)return{held:new Set(r.map(a=>a.name.toLowerCase())),unknown:[]};let n=new Set(r.map(a=>a.name.toLowerCase())),s=new Set,o=[];for(let a of t){let p=a.toLowerCase();s.has(p)||o.some(u=>u.toLowerCase()===p)||(n.has(p)?s.add(p):o.push(a))}return{held:s,unknown:o}}function me(e,t,r=[]){let n=t.access??"write",s=n==="delete"?r:x(e,r),o={out:new Set([...s].map(c=>c.toLowerCase())),tooling:new Set(r.map(c=>c.toLowerCase()))},a=new Set((t.excluded??[]).map(c=>c.toLowerCase())),p=new Map(e.map(c=>[c.name.toLowerCase(),c])),u=te(e,t.customSettings),g=u.unknown.map(c=>({objectApiName:c,reason:"notCustomSetting"})),m=[],f=[],i=[];if(t.mode==="picked"){let c=new Set;for(let d of t.objects??[]){let l=d.toLowerCase();if(c.has(l))continue;c.add(l);let h=p.get(l);h?f.push(h):g.push({objectApiName:d,reason:"notFound"})}for(let d of H){let l=d.toLowerCase(),h=p.get(l);if(!(c.has(l)||h===void 0)){if(a.has(l)){g.push({objectApiName:h.name,reason:"excludedByUser"});continue}f.push(h),i.push(h.name)}}for(let d of u.held){let l=p.get(d);c.has(d)||l===void 0||(c.add(d),f.push(l))}}else f.push(...p.values());for(let c of f){let d=c.name.toLowerCase(),l=a.has(d)?"excludedByUser":Z(c,o,t.mode,u.held.has(d),n);l===void 0?m.push(c.name):g.push({objectApiName:c.name,reason:l})}return m.sort(),g.sort(k),{mode:t.mode,candidates:m,leftOut:g,addedToPicked:i}}function ge(e){return e.fields.find(r=>r.name==="Name")?.nillable===!0?"hierarchy":"list"}function he(e){return e==="hierarchy"?"SetupOwnerId":"Name"}function be(e){return e.objects.some(t=>t.customSetting!==void 0)}function ne(e){let t=e.split("__");return t.length>=3&&t[0]!==""?t[0]:void 0}var oe=()=>({first:"child",firmness:0});function re(e,t,r=oe){let n=new Map(e.map((o,a)=>[o.toLowerCase(),a])),s=e.map(()=>new Map);return e.forEach((o,a)=>{for(let p of t.get(o)?.childRelationships??[]){let u=n.get(p.childSObject.toLowerCase());if(u===void 0||u===a)continue;let g=r(p);if(g===void 0)continue;let[m,f]=g.first==="child"?[u,a]:[a,u],i=s[m].get(f);(i===void 0||g.firmness>i)&&s[m].set(f,g.firmness)}}),N(e.map((o,a)=>a),s,Number.NEGATIVE_INFINITY).map(o=>e[o])}function N(e,t,r){let n=new Set(e),s=f=>[...t[f]].filter(([i,c])=>n.has(i)&&c>r).map(([i])=>i),o=ie(e,s,t.length),a=new Map;o.forEach((f,i)=>{for(let c of f)a.set(c,i)});let p=o.map(()=>0),u=o.map(()=>new Set);for(let f of e){let i=a.get(f)??0;for(let c of s(f)){let d=a.get(c)??0;d===i||u[i].has(d)||(u[i].add(d),p[d]++)}}let g=o.map(()=>!1),m=[];for(let f=o.length;f>0;f--){let i=-1;for(let d=0;d<o.length;d++){if(g[d]||p[d]>0)continue;let l=o[d].length===1,h=i>=0&&o[i].length===1;(i<0||l&&!h||l===h&&o[d][0]<o[i][0])&&(i=d)}g[i]=!0;let c=o[i];if(c.length===1)m.push(c[0]);else{let d=Number.POSITIVE_INFINITY;for(let l of c)for(let[h,S]of t[l])S>r&&a.get(h)===i&&S<d&&(d=S);m.push(...N(c,t,d))}for(let d of u[i])p[d]--}return m}function ie(e,t,r){let n=new Array(r).fill(-1),s=new Array(r).fill(0),o=new Array(r).fill(!1),a=[],p=[],u=0;for(let g of e){if(n[g]>=0)continue;let m=[],f=i=>{n[i]=u,s[i]=u,u++,a.push(i),o[i]=!0,m.push({node:i,edges:t(i),at:0})};for(f(g);m.length>0;){let i=m[m.length-1];if(i.at<i.edges.length){let l=i.edges[i.at++];n[l]<0?f(l):o[l]&&(s[i.node]=Math.min(s[i.node],n[l]));continue}m.pop();let c=m[m.length-1];if(c&&(s[c.node]=Math.min(s[c.node],s[i.node])),s[i.node]!==n[i.node])continue;let d=[];for(let l=a.pop();l!==void 0&&(o[l]=!1,d.push(l),l!==i.node);l=a.pop());p.push(d.sort((l,h)=>l-h))}}return p}function M(e){let t=new Map;for(let{objectApiName:r,namespace:n}of e)n!==void 0&&t.set(n,[...t.get(n)??[],r]);return[...t].sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>({namespace:r,objects:n.sort()}))}function se(e,t){return re(e,t).map((r,n)=>{let s=ne(r);return{objectApiName:r,readOrder:n,...s===void 0?{}:{namespace:s}}})}function Ce(e,t,r=new Map){let n=[...e.leftOut],s=[];for(let a of e.candidates){let p=t.get(a);if(p)p.fields.some(u=>u.name==="SystemModstamp")?p.fields.some(u=>u.name==="IsDeleted")?s.push(a):n.push({objectApiName:a,reason:"noRecycleBin"}):n.push({objectApiName:a,reason:"noSystemModstamp"});else{let u=r.get(a);n.push({objectApiName:a,reason:"notDescribed",...u===void 0?{}:{detail:u}})}}let o=se(s,t);return{mode:e.mode,objects:o,leftOut:n.sort(k),packages:M(o)}}function Se(e,t){if(t.size===0)return e;let r=[...e.leftOut],n=[];for(let s of e.objects){let o=t.get(s.objectApiName);o===void 0?n.push({...s,readOrder:n.length}):r.push({objectApiName:s.objectApiName,reason:"unreadable",detail:o})}return{...e,objects:n,leftOut:r.sort(k),packages:M(n)}}export{W as a,U as b,E as c,x as d,ce as e,fe as f,D as g,z as h,G as i,L as j,H as k,q as l,ee as m,me as n,ge as o,he as p,be as q,ne as r,re as s,Ce as t,Se as u};
@@ -1,14 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- var m=()=>({input:process.stdin,output:process.stderr});function p(t,o,r){let{input:e,output:i}=o;return e.isTTY!==!0&&(i.write(`${t}
8
- no terminal to answer: give --yes to go ahead without the question.
9
- `),process.exit(2)),r?.aborted===!0?Promise.resolve(void 0):(i.write(`${t} `),new Promise(c=>{let n=s=>{e.off("data",a),e.off("end",u),r?.removeEventListener("abort",f),e.pause(),c(s)},a=s=>n(String(s).trim()),u=()=>n(void 0),f=()=>{i.write(`
10
- `),n(void 0)};e.on("data",a),e.on("end",u),r?.addEventListener("abort",f,{once:!0}),e.resume()}))}async function T(t,o=m(),r){let e=await p(`${t} [y/N]`,o,r);return e!==void 0&&/^y(es)?$/i.test(e)}async function E(t,o=m()){return await p(t,o)??""}var w=new Set(["\r",`
11
- `]),g=new Set(["\x7F","\b"]),l="",S="";function v(t,o,r=m()){let{input:e,output:i}=r;return e.isTTY!==!0&&(i.write(`${t}
12
- no terminal to type it on: ${o}.
13
- `),process.exit(2)),i.write(`${t} `),e.setRawMode?.(!0),new Promise(c=>{let n="",a=s=>{e.off("data",u),e.off("end",f),e.setRawMode?.(!1),e.pause(),i.write(`
14
- `),c(s)},u=s=>{for(let d of String(s)){if(w.has(d))return a(n);if(d===l||d===S&&n==="")return a(void 0);g.has(d)?n=n.slice(0,-1):d>=" "&&(n+=d)}},f=()=>a(void 0);e.on("data",u),e.on("end",f),e.resume()})}export{T as a,E as b,v as c};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w}from"./chunk-ZUTYVST5.mjs";import"./chunk-NTOVCTRS.mjs";export{a as CURRENCY_FIELD,q as CURRENCY_FOLLOWS,c as CURRENCY_SETTINGS_SOQL,b as CURRENCY_TYPES_SOQL,u as CurrencyReplacementTally,d as DATED_RATES_ON_SOQL,e as DATED_RATES_SOQL,j as DATED_RATE_FIELDS,l as conversionFactor,n as currencyFieldsOf,w as currencyReplacementsNote,k as datedRateOf,g as datedRatesOf,v as describeCurrencyReplaced,t as followParentCurrency,r as followsItsParentsCurrency,f as orgCurrenciesOf,s as parentCurrencyChange,h as readOrgCurrencies,i as readRunCurrencies,p as replaceRowCurrency,o as replacementCurrency,m as roundToScale};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{Vb as a,Xb as d}from"./chunk-B45CNPUX.mjs";async function T(t){let e=(await t.query("SELECT Id, IsSandbox FROM Organization LIMIT 1")).records[0];if(typeof e?.Id!="string")throw new Error("The org gave no Organization record: whether it is a sandbox cannot be told.");if(e.IsSandbox===!0)return{id:e.Id,sandbox:!0};try{let r=(await t.query("SELECT OrganizationType FROM Organization LIMIT 1")).records[0]?.OrganizationType;return typeof r=="string"&&r!==""?{id:e.Id,sandbox:!1,edition:r}:{id:e.Id,sandbox:!1}}catch{return{id:e.Id,sandbox:!1}}}function b(t){let n=a({isSandbox:t.sandbox,edition:t.edition});return d(n,t.edition)==="production"}var c=/\/services\/Soap\//,u=/\/services\/data\/v\d+\.\d+\/jobs\/(?:ingest|query)(?:[/?]|$)/,p=/^\/jobs\/(?:ingest|query)(?:[/?]|$)/;function f(t){let n=typeof t=="string"?t:t?.url??"";return u.test(n)||p.test(n)}function g(t){let n=0;if(typeof t.request!="function")return()=>n;let e=t._transport,o=t.request.bind(t);if(t.request=(...r)=>((e===void 0||!f(r[0]))&&n++,o(...r)),e!==void 0){let r=e.httpRequest.bind(e);e.httpRequest=(...i)=>{let s=i[0].url;return(c.test(s)||u.test(s))&&n++,r(...i)}}return()=>n}export{T as a,b,g as c};
@@ -1,15 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as gt,b as rn,c as on}from"./chunk-66NMFCWX.mjs";import{a as dn}from"./chunk-LV6G4XTK.mjs";import{a as wr,b as ln}from"./chunk-XCA5AONB.mjs";import{a as cn,e as hr,i as br}from"./chunk-WR2GIKWE.mjs";import{Aa as ar,Ba as dr,Bc as pn,Ca as cr,Dc as Ar,b as ft,d as Zt,e as Yt,f as en,j as se,k as tn,l as jt,m as Ct,n as xe,o as M,pa as Jn,qa as Zn,ra as Yn,s as de,sa as er,ta as tr,ua as nr,uc as le,va as rr,wa as Mt,xa as or,ya as sr,yc as fr,za as ir}from"./chunk-YMJVMFPY.mjs";import{d as lr}from"./chunk-ALJVEUUS.mjs";import{a as mt,b as Vn}from"./chunk-CE6ZDGBB.mjs";import{a as Rr,b as fn,c as vr,d as mn,e as ht,f as bt,g as Or,h as gn,i as Sr,j as hn,k as bn}from"./chunk-4HFRHFGQ.mjs";import{k as yr}from"./chunk-Z7X534S4.mjs";import{S as mr,U as gr,l as pr}from"./chunk-6QSM2WIH.mjs";import{d as kr}from"./chunk-T63U4OZJ.mjs";import{a as un}from"./chunk-YYZL7UGV.mjs";import{A as Ir,q as Re}from"./chunk-6MUEPV7M.mjs";import{b as sn,c as nt,d as an,h as ur}from"./chunk-OTWRDD6L.mjs";import{a as Be}from"./chunk-5LFSFYFJ.mjs";import{c as Pt,e as oe,f as $t,i as nn,p as Tr}from"./chunk-VXHDBYMI.mjs";import{d as Gn,e as qn,g as Xn,h as Qn}from"./chunk-INIT2UKJ.mjs";import{p as W,q as lt,t as Nt}from"./chunk-CGWXQX75.mjs";import{a as Kn,f as Jt,h as St}from"./chunk-TZE3Y7IQ.mjs";import{b as R}from"./chunk-CA5NAXSU.mjs";import{Fa as Fn,Fd as Hn,Ga as _n,Ha as Wn,Tb as De,Yb as Vt,bc as It,ec as Un,fc as Ot,vb as Qt}from"./chunk-B45CNPUX.mjs";import{b as Q,f as xn,k as Ke,l as Ge,q as Bn,v as Xt}from"./chunk-7EANH5PY.mjs";var co={defaultQueryLimit:500,previewQueryLimit:200,exportQueryLimit:1e3},po={defaultQueryLimit:2e3,previewQueryLimit:2e3,exportQueryLimit:5e3};function kn(s){return s==="production"?{...co}:{...po}}function yn(s){return s?"sandbox":"production"}var rt="IsPersonAccount",uo=new Set(["FirstName","LastName","MiddleName","Suffix","Salutation","Phone","Fax"]);function lo(s){if(uo.has(s))return s;if(s.endsWith("__c"))return`${s.slice(0,-3)}__pc`;if(/^[A-Za-z][A-Za-z0-9]*$/.test(s))return`Person${s}`}function wn(s){let e=(r,o)=>r.fieldPattern.toLowerCase().startsWith(`${o.toLowerCase()}.`)?r.fieldPattern.slice(o.length+1):void 0,t=new Set(s.flatMap(r=>{let o=e(r,W);return o===void 0?[]:[o.toLowerCase()]})),n=[];for(let r of s){let o=e(r,lt),i=o===void 0?void 0:lo(o);i===void 0||t.has(i.toLowerCase())||(t.add(i.toLowerCase()),n.push({...r,fieldPattern:`${W}.${i}`}))}return n}function Nr(s){if(s.objectApiName.toLowerCase()!==W.toLowerCase()||!s.fields.some(p=>p.name===rt))return;let e=new Map(s.fields.map(p=>[p.name.toLowerCase(),p])),t=new Set(s.kept.map(p=>p.fieldApiName.toLowerCase())),n=[],r=new Set,o=[],i=(p,u)=>{t.add(u.name.toLowerCase()),r.add(u.name),n.push({...p,objectApiName:W,fieldApiName:u.name})};for(let p of s.derived){let u=e.get(p.fieldApiName.toLowerCase());if(!u){o.push(p.fieldApiName);continue}t.has(u.name.toLowerCase())||i(p,u)}let a=s.fields.filter(p=>Un(p.name)&&p.updateable===!0&&p.calculated!==!0&&!t.has(p.name.toLowerCase())),d=new Map,c=a.map(p=>{let u=$r(p.name);return d.set(u,p),{...p,name:u,label:p.label??p.name,type:p.type??"string"}});for(let p of hr(s.detector,lt,c)){let u=d.get(p.field.name);!u||t.has(u.name.toLowerCase())||i({objectApiName:W,fieldApiName:u.name,method:br({...p.field,name:u.name}),config:{}},u)}return{rules:n,personOnly:r,unseen:o}}function Pr(s,e){let t=new Set((e??[]).map(n=>n.name.toLowerCase()));return s.filter(n=>!t.has($r(n).toLowerCase()))}function $r(s){return s.endsWith("__pc")?`${s.slice(0,-4)}__c`:s.startsWith("Person")&&!s.includes("__")?s.slice(6):s}function jr(s,e,t,n){if(s.toLowerCase()!==W.toLowerCase())return[...t];let r=Nt(e,!1);return t.filter(o=>!Ot(W,o.fieldApiName,r)&&(r==="person"||!n.has(o.fieldApiName)))}import{randomBytes as Oo}from"node:crypto";var kt=[{id:"tpl-gdpr-standard",name:"GDPR Standard",description:"Standard GDPR compliance: anonymize personal data fields across common Salesforce objects.",complianceFramework:"gdpr",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace with fake first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace with fake last name."},{fieldPattern:"Contact.Email",ruleType:"fake",description:"Replace with fake email address."},{fieldPattern:"Contact.Phone",ruleType:"mask",description:"Mask phone number (keep last 4 digits).",config:{maskKeepLast:4}},{fieldPattern:"Contact.MailingStreet",ruleType:"fake",description:"Replace with fake street address."},{fieldPattern:"Contact.MailingCity",ruleType:"fake",description:"Replace with fake city."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"mask",description:"Mask postal code."},{fieldPattern:"Lead.FirstName",ruleType:"fake",description:"Replace with fake first name."},{fieldPattern:"Lead.LastName",ruleType:"fake",description:"Replace with fake last name."},{fieldPattern:"Lead.Email",ruleType:"fake",description:"Replace with fake email address."},{fieldPattern:"Lead.Phone",ruleType:"mask",description:"Mask phone number."},{fieldPattern:"Lead.Street",ruleType:"fake",description:"Replace with fake street address."},{fieldPattern:"Account.BillingStreet",ruleType:"fake",description:"Replace with fake address."},{fieldPattern:"Account.Phone",ruleType:"mask",description:"Mask phone number."}]},{id:"tpl-ccpa-california",name:"CCPA California",description:"CCPA compliance: anonymize consumer personal information per California privacy regulations.",complianceFramework:"ccpa",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace consumer first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace consumer last name."},{fieldPattern:"Contact.Email",ruleType:"hash",description:"Hash email for pseudonymization."},{fieldPattern:"Contact.Phone",ruleType:"nullify",description:"Nullify phone number."},{fieldPattern:"Contact.MailingStreet",ruleType:"nullify",description:"Nullify street address."},{fieldPattern:"Contact.MailingCity",ruleType:"nullify",description:"Nullify city."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"nullify",description:"Nullify postal code."},{fieldPattern:"Contact.Birthdate",ruleType:"nullify",description:"Remove date of birth."},{fieldPattern:"Lead.Email",ruleType:"hash",description:"Hash email for pseudonymization."},{fieldPattern:"Lead.Phone",ruleType:"nullify",description:"Nullify phone number."}]},{id:"tpl-hipaa-health",name:"HIPAA Health Data",description:"HIPAA compliance: de-identify protected health information (PHI) in healthcare Salesforce orgs.",complianceFramework:"hipaa",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace patient first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace patient last name."},{fieldPattern:"Contact.Email",ruleType:"hash",description:"Hash email address."},{fieldPattern:"Contact.Phone",ruleType:"mask",description:"Mask phone number."},{fieldPattern:"Contact.Birthdate",ruleType:"nullify",description:"Remove date of birth (PHI)."},{fieldPattern:"Contact.MailingStreet",ruleType:"nullify",description:"Remove address (PHI)."},{fieldPattern:"Contact.MailingCity",ruleType:"nullify",description:"Remove city (PHI)."},{fieldPattern:"Contact.MailingState",ruleType:"nullify",description:"Remove state (PHI)."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"truncate",description:"Truncate to first 3 digits.",config:{truncateLength:3,truncateKeep:"first"}},{fieldPattern:"Account.Name",ruleType:"fake",description:"Replace facility name."},{fieldPattern:"Account.Phone",ruleType:"mask",description:"Mask facility phone."}]},{id:"tpl-sandbox-scrub",name:"Sandbox Data Scrub",description:"General-purpose sandbox data scrubbing: mask all PII for safe development use.",complianceFramework:"custom",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Fake first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Fake last name."},{fieldPattern:"Contact.Email",ruleType:"preserve_format",description:"Replace keeping email format."},{fieldPattern:"Contact.Phone",ruleType:"preserve_format",description:"Replace keeping phone format."},{fieldPattern:"Lead.FirstName",ruleType:"fake",description:"Fake first name."},{fieldPattern:"Lead.LastName",ruleType:"fake",description:"Fake last name."},{fieldPattern:"Lead.Email",ruleType:"preserve_format",description:"Replace keeping email format."},{fieldPattern:"Lead.Company",ruleType:"fake",description:"Fake company name."},{fieldPattern:"Account.Name",ruleType:"fake",description:"Fake account name."},{fieldPattern:"Account.Website",ruleType:"constant",description:"Replace with placeholder URL.",config:{constantValue:"https://example.com"}},{fieldPattern:"Opportunity.Name",ruleType:"fake",description:"Fake opportunity name."}]}];var Et=class{operations=new Map;ttlMs;nowFn;constructor(e=36e5,t=Date.now){this.ttlMs=e,this.nowFn=t}isDuplicate(e){return this.pruneExpired(),this.operations.has(e)}register(e,t,n,r){if(this.pruneExpired(),this.operations.has(e))throw new Error(`Duplicate DML operation detected: ${e}`);let o={operationId:e,objectApiName:t,dmlType:n,recordCount:r,registeredAt:new Date(this.nowFn()).toISOString(),status:"pending"};return this.operations.set(e,o),o}markCompleted(e){let t=this.operations.get(e);t&&(t.status="completed")}markFailed(e){let t=this.operations.get(e);t&&(t.status="failed")}get(e){return this.operations.get(e)}get size(){return this.operations.size}clear(){this.operations.clear()}pruneExpired(){let e=this.nowFn()-this.ttlMs;for(let[t,n]of this.operations)new Date(n.registeredAt).getTime()<e&&this.operations.delete(t);if(this.operations.size>1e4){let t=Array.from(this.operations.entries()),n=t.length-1e4;for(let r=0;r<n;r++)this.operations.delete(t[r][0])}}};var fo=3e3;function Se(s){return s.slice(0,15)}function mo(s,e){let t=s??null,n=e??null;return t===n?!0:t===null||n===null?!1:typeof t=="object"||typeof n=="object"?JSON.stringify(t)===JSON.stringify(n):String(t)===String(n)}function go(s){let e=[],t=[],n=0;for(let r of s)t.length>0&&n+r.length+2>fo&&(e.push(t),t=[],n=0),t.push(r),n+=r.length+2;return t.length>0&&e.push(t),e}async function Cr(s,e,t){let n=t.map(a=>a.Id).filter(nt),r=[...new Set(t.flatMap(a=>Object.keys(a)))].filter(a=>a.toLowerCase()!=="id");if(n.length===0||r.length===0)return{write:[...t],unchanged:0};let o=new Map;try{for(let a of go(r))for(let d of await ur(s,e,a,n))typeof d.Id=="string"&&o.set(Se(d.Id),{...o.get(Se(d.Id)),...d})}catch(a){return{write:[...t],unchanged:0,unread:R(a)}}let i=t.filter(a=>{let d=nt(a.Id)?o.get(Se(a.Id)):void 0;return d?Object.keys(a).some(c=>c.toLowerCase()!=="id"&&!mo(a[c],d[c])):!0});return{write:i,unchanged:t.length-i.length}}async function Mr(s,e,t,n){let r=St(e),o=new Set,i=t.filter(nt);for(let a=0;a<i.length;a+=sn){let d=i.slice(a,a+sn),[c]=an(d,d.length),p=new Set,u=await s.query(`SELECT Id, LastModifiedDate FROM ${r} WHERE Id IN (${c})`);for(let h of u.records){if(typeof h.Id!="string")continue;p.add(Se(h.Id)),Date.parse(String(h.LastModifiedDate??""))<=n||o.add(Se(h.Id))}let b=d.filter(h=>!p.has(Se(h)));if(b.length===0)continue;let[l]=an(b,b.length),f=await s.query(`SELECT Id FROM ${r} WHERE Id IN (${l}) AND IsDeleted = true`,{scanAll:!0});for(let h of f.records)typeof h.Id=="string"&&o.add(Se(h.Id))}return o}function Er(s,e){return{async*[Symbol.asyncIterator](){for await(let t of s){let n=t.filter(r=>!(nt(r.Id)&&e.has(Se(r.Id))));n.length>0&&(yield n)}}}}function An(s,e){let t=0;return{batches:{async*[Symbol.asyncIterator](){let n=new Map,r=[],o=0;for await(let a of s)for(let d of a){if(o++,!nt(d.Id)){r.push({...d});continue}let c=n.get(Se(d.Id));if(!c){n.set(Se(d.Id),{...d});continue}for(let[p,u]of Object.entries(d))p in c||(c[p]=u)}t=o;let i=[...n.values(),...r];for(let a=0;a<i.length;a+=e)yield i.slice(a,a+e)}},lines:()=>t}}var Rn="anonymization:template:",zr="anonymizationTemplates",Lr=Ge({id:Q().min(1).max(100),name:Q().trim().min(1).max(Fn),description:Q().max(500),complianceFramework:Xt("custom"),rules:Ke(Bn(Wn,Ge({description:Q().max(500)}))).min(1).max(_n),saved:Xt(!0),createdAt:Q()}),zt=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${Rn}${e.id}`,e,zr)}load(e){let t=Lr.safeParse(this.configStore.get(`${Rn}${e}`));return t.success?t.data:void 0}list(){let e=[];for(let t of Object.values(this.configStore.getByCategory(zr))){let n=Lr.safeParse(t);n.success&&e.push(n.data)}return e.sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}delete(e){return this.configStore.delete(`${Rn}${e}`)}};import{createHash as Dr}from"node:crypto";var bo="anonymization:checkpoint:",ko="anonymizationCheckpoints",qe=2e3,vn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,yo=Q().min(1).max(255),wo=Ge({id:Q().regex(vn),fields:Ke(yo).min(1).max(800),digest:Q().regex(/^[0-9a-f]{64}$/)}),Ao=Ge({objectApiName:Q().min(1).max(255),done:xn(),afterId:Q().regex(vn).optional(),refused:Ke(Q().regex(vn)).max(qe),unconfirmed:Ke(wo).max(qe).optional()}),Ro=Ge({id:Q().min(1).max(200),orgId:Q().min(1).max(200),templateId:Q().min(1).max(200),fingerprint:Q().regex(/^[0-9a-f]{64}$/),savedAt:Q(),objects:Ke(Ao),namesGiven:Q().max(6e4).regex(/^[A-Za-z0-9+/]*={0,2}$/).optional()});function Lt(s,e,t){let n=s.map(o=>[o.fieldPattern,o.ruleType,o.config??null]),r=t?.trim();return Dr("sha256").update(JSON.stringify(r?{rules:n,objects:e,where:r}:{rules:n,objects:e})).digest("hex")}function vo(s){return s==null||s===""?null:typeof s=="string"?s.trim():typeof s=="number"||typeof s=="boolean"?String(s):JSON.stringify(s)}function Tn(s,e){let t=[...e].sort().map(n=>[n,vo(s[n])]);return Dr("sha256").update(JSON.stringify(t)).digest("hex")}function yt(s){return s.reduce((e,t)=>e+t.refused.length,0)}var ot=class{constructor(e){this.configStore=e}configStore;load(e,t,n){let r=Ro.safeParse(this.configStore.get(this.key(e,t)));if(!r.success)return;let o=r.data;if(!(o.orgId!==e||o.templateId!==t||o.fingerprint!==n))return o}save(e){if(yt(e.objects)>qe)throw new Error(`A checkpoint keeps at most ${qe} refused records; this run left ${yt(e.objects)}.`);this.configStore.set(this.key(e.orgId,e.templateId),e,ko)}clear(e,t){this.configStore.delete(this.key(e,t))}key(e,t){return`${bo}${e}:${t}`}};async function To(s){let{open:e,rename:t,rm:n}=await import("node:fs/promises"),{randomBytes:r}=await import("node:crypto"),o=`${s}.${r(4).toString("hex")}.partial`,i=await e(o,"w"),a=!1;return{write:async d=>{let c=Buffer.from(d,"utf8");for(let p=0;p<c.length;){let{bytesWritten:u}=await i.write(c,p,c.length-p,null);p+=u}},close:async()=>{a=!0,await i.close(),await t(o,s)},abort:async()=>{a||await i.close().catch(()=>{}),a=!0,await n(o,{force:!0})}}}function Io(s){let e=[];return{write:async t=>{e.push(t)},close:async()=>{await s(new TextEncoder().encode(e.join("")))},abort:async()=>{e.length=0}}}var Dt=class s{host;constructor(e){this.host=e??null}async defaultHost(){let e=await import("vscode");return{showSaveDialog:t=>e.window.showSaveDialog(t),writeFile:(t,n)=>e.workspace.fs.writeFile(t,n),fileUri:t=>e.Uri.file(t),openFile:async t=>t.scheme==="file"?To(t.fsPath):Io(n=>e.workspace.fs.writeFile(t,n))}}static filtersOf(e,t){let n=e.includes(".")?e.split(".").pop():void 0;return t?.length?{[t.join("/").toUpperCase()]:t}:n?{[n.toUpperCase()]:[n]}:void 0}static ask(e,t,n){let r=s.filtersOf(t,n);return e.showSaveDialog({saveLabel:"Save",defaultUri:e.fileUri(t),...r?{filters:r}:{}})}async save(e,t,n){let r=this.host??await this.defaultHost();try{let o=await s.ask(r,e,n);return o?(await r.writeFile(o,new TextEncoder().encode(t)),{status:"saved",path:o.fsPath}):{status:"cancelled"}}catch(o){return{status:"error",message:o instanceof Error?o.message:String(o)}}}async saveStream(e,t,n){let r=this.host??await this.defaultHost(),o;try{let i=await s.ask(r,e,n);if(!i)return{status:"cancelled"};let a=await r.openFile(i);o=a;let d=await t(c=>a.write(c));return await a.close(),o=void 0,{status:"saved",path:i.fsPath,result:d}}catch(i){return await o?.abort().catch(()=>{}),{status:"error",message:i instanceof Error?i.message:String(i)}}}};function xt(s,e,t,n,r=0){s?.register(e,t,n,r);let o=!1,i=a=>{o||(o=!0,a())};return{progress:(a,d,c,p)=>{o||s?.updateProgress(e,a,d,c,p)},complete:()=>i(()=>s?.complete(e)),partial:()=>i(()=>s?.partial(e)),fail:a=>i(()=>s?.fail(e,a)),cancel:()=>i(()=>s?.cancel(e))}}var ve={orgUnknown:"ORG_NOT_FOUND",production:"PIPELINE_WRITE_REFUSED",needsApproval:"PIPELINE_WRITE_NEEDS_APPROVAL",retries:"PIPELINE_WRITE_NO_RETRIES",filterNeedsObject:"MASKING_FILTER_NEEDS_OBJECT",invalid:"INVALID_PAYLOAD",templateMissing:"TEMPLATE_NOT_FOUND",fieldsUnseen:"MASKING_FIELDS_UNSEEN",masksNothing:"MASKING_MASKS_NOTHING"};function Fe(s,e){return Object.assign(new Error(e),{code:s})}function xr(s,e,t){let n=Hn(s);if(n==="refused")return Fe(ve.production,`${t} is a production org, or one SandForge cannot tell is not: a pipeline never masks one, whatever an Approval step answers. Mask a sandbox, a scratch org or a Developer Edition org. Nothing was masked.`);if(n==="needsApproval"&&!e.approved)return Fe(ve.needsApproval,`${t} is a sandbox marked Staging, which a pipeline masks only once an Approval step before the masking has approved the run, and none did: put an Approval step before it. Nothing was masked.`)}function Br(s,e){if(s.retries!==void 0&&s.retries>0)return{refusal:Fe(ve.retries,"A masking step is never tried again: a second try masks again what the first one masked \u2014 an address it hashed is hashed once more, and no longer gives the same pseudonym on Contact and on Lead. Set its retries to 0. Nothing was masked.")};let t=s.where?.trim();if(t&&s.object===void 0)return{refusal:Fe(ve.filterNeedsObject,"A masking condition filters the rows of one object: name the object it holds, or remove the condition. Nothing was masked.")};let n=Mt.safeParse({orgId:s.orgId,templateId:s.templateId,...s.object!==void 0?{objects:[s.object]}:{},...t?{where:t}:{},snapshot:!0});if(!n.success){let r=n.error.issues[0];return{refusal:Fe(ve.invalid,`The masking step is not one the DataOps page would run (${r.path.join(".")}: ${r.message}). Nothing was masked.`)}}return e(n.data.templateId)?{asked:n.data}:{refusal:Fe(ve.templateMissing,`No masking template is shipped or saved under ${n.data.templateId}: it was deleted on the DataOps page. Choose another. Nothing was masked.`)}}function oo(s){let e=s.fields;return{name:s.name,label:s.label,labelPlural:s.labelPlural??"",keyPrefix:s.keyPrefix??null,custom:s.custom??!1,createable:s.createable,updateable:s.updateable,deletable:s.deletable,queryable:s.queryable,fields:e.map(t=>({name:t.name,label:t.label,type:t.type,length:t.length??0,nillable:t.nillable??!1,createable:t.createable,updateable:t.updateable,externalId:t.externalId??!1,referenceTo:t.referenceTo??[],relationshipName:t.relationshipName??null,picklistValues:t.picklistValues??[],defaultValue:t.defaultValue??null,calculated:t.calculated??!1,autoNumber:t.autoNumber??!1,unique:t.unique??!1,permissionable:t.permissionable??!0})),recordTypeInfos:s.recordTypeInfos??[],childRelationships:s.childRelationships??[]}}var So=new Set(["backup:execute","backup:list","backup:objects","backup:export","backup:delete","dataops:rollback","dataops:anonymize","dataops:anonymization-templates","dataops:quality-scan","dataops:anonymization-template:save","dataops:anonymization-template:delete","dataops:anonymize:coverage","dataops:anonymize:preview","dataops:automation","precheck:pii-scan"]),No=6e4,Po=10,$o=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function jo(s,e){return s.slice(0,15)===e.slice(0,15)}var Fr="ORG_REPLACED_SINCE_BACKUP",Co="Backup was cancelled before it finished. Nothing was saved \u2014 run it again to take a complete snapshot.",it=class extends Error{constructor(){super(Co),this.name="BackupCancelledError"}},wt=class extends Error{constructor(e){super(`The backup could not be written to disk: ${R(e)}`),this.name="BackupWriteError"}},at=class extends Error{constructor(t,n){super(t);this.retryable=n;this.name="BackupNotWholeError"}retryable},jn="IsDeleted = false",Mo="SystemModstamp",_r=5e4,Eo=100,zo=1e6,st=200,Lo=1440*6e4,Do=1440*6e4,Wr="backupRetention:since",xo="BACKUP_BUSY";function Bo(s,e){return e===0?"success":s===0?"failure":"partial"}function In(s){return Vt(s)}function Ur(s,e,t){s.length>=Po||s.push({objectApiName:e,message:t?.[0]?.message??"Unknown DML error"})}function Bt(s,e,t=!1){let n=(e?.rules??[]).map(o=>o.fieldPattern.split(".")[0]).filter((o,i,a)=>a.findIndex(d=>On(d,o))===i);if(s.objects)return s.objects.map(o=>n.find(i=>On(i,o))??(On(o,W)?W:o));if(!e)return[];let r=[...n];return t&&At(s,e,W)&&r.push(W),r}function On(s,e){return s.toLowerCase()===e.toLowerCase()}var Fo=`${rt} = true`;function At(s,e,t){return s.objects===void 0&&t.toLowerCase()===W.toLowerCase()&&Ft(e,W).length===0&&wn(e.rules).length>0}function Sn(s,e,t){return At(s,e,t)?Fo:En(s)}async function Nn(s,e){try{return(await s.describe(W)).fields.some(t=>t.name===rt)}catch(t){return e(`[WARN] dataops: whether the org has person accounts was not read: ${R(t)}`),!1}}function Ft(s,e){let t=`${e.toLowerCase()}.`;return s.rules.filter(n=>n.fieldPattern.toLowerCase().startsWith(t)||n.fieldPattern==="*")}function Cn(s,e){return e.toLowerCase()===W.toLowerCase()?wn(s.rules):[]}function Hr(s){let e=new Map;return{describe:t=>{let n=e.get(t)??s.describe(t);return e.set(t,n),n}}}async function Kr(s,e){return new on(async n=>oo(await s.describe(n))).deniedOf(e.map(({objectApiName:n,rules:r})=>({objectApiName:n,operation:"update",fieldNames:r.map(o=>o.fieldPattern.includes(".")?o.fieldPattern.split(".")[1]:o.fieldPattern).filter(o=>o!=="*")})))}function Gr(s,e){return Ft(s,e).length>0||Cn(s,e).length>0}function Pn(s){return{objectApiName:s.objectApiName,recordCount:s.recordCount,truncated:s.truncated===!0,...s.orgCount!==void 0?{orgCount:s.orgCount}:{},...s.stoppedAt?{stoppedAt:s.stoppedAt}:{},...s.notKept&&s.notKept.length>0?{notKept:[...s.notKept]}:{}}}function $n(s,e){return s.flatMap(t=>{let n=e?.get(t.objectApiName);if(n!==void 0&&n<t.recordCount)return[`${t.objectApiName} ${n} of the ${t.recordCount} it listed (not found on disk)`];if(!t.truncated)return[];if(t.stoppedAt==="not_reached")return[`${t.objectApiName} none (the backup stopped before it)`];let r=t.orgCount!==void 0?` of ${t.orgCount}`:"",o=t.stoppedAt==="cap"?" (stopped at the cap)":t.stoppedAt==="failure"?" (the read failed)":"";return[`${t.objectApiName} ${t.recordCount}${r}${o}`]}).join(", ")}var Xe=200,_o=95,_t=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Wo="NOTHING_TO_RESUME",qr="TEMPLATE_NOT_FOUND";function Xr(s){return new Error(`Template "${s}" not found.`)}function Uo(s){let e=s.Id;if(typeof e!="string"||!_t.test(e))return[];let t=Object.keys(s).filter(n=>n!=="Id");return t.length>0?[{id:e,fields:t,digest:Tn(s,t)}]:[]}var Ho="COUNT_FAILED",Qr="SNAPSHOT_NOT_TAKEN",Ko=/^([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+):/;function Go(s){if(typeof s=="object"&&s!==null){let{errorCode:e,code:t}=s;if(typeof e=="string"&&e!=="")return e;if(typeof t=="string"&&t!=="")return t}return Ko.exec(R(s))?.[1]??"UNKNOWN"}var Vr=5;function Jr(s){return s==null?null:typeof s=="string"||typeof s=="number"||typeof s=="boolean"?s:JSON.stringify(s)}function so(s){return s.done?0:Math.max(0,s.total-s.masked-s.nothingToMask-s.refused-s.unanswered)}function Wt(s){return s.refused+s.unanswered+so(s)}function Rt(s){return s.reduce((e,t)=>({recordsProcessed:e.recordsProcessed+t.masked+t.nothingToMask,recordsFailed:e.recordsFailed+t.refused,recordsNotMasked:e.recordsNotMasked+Wt(t)}),{recordsProcessed:0,recordsFailed:0,recordsNotMasked:0})}function qo(s,e){let{recordsProcessed:t,recordsFailed:n,recordsNotMasked:r}=Rt(s);return r===0?"success":t>0||e&&n===0?"partial":"failure"}function Xo(s,e,t){if(!t||e==="success")return{outcome:e};let{recordsProcessed:n,recordsFailed:r}=Rt(s);return n+r>0?{outcome:"cancelled"}:{outcome:"stopped",code:nn}}function Zr(s){return s.filter(e=>Wt(e)>0).map(e=>`${e.objectApiName} ${Wt(e)}`).join(", ")}function Yr(s){return s.map(e=>({objectApiName:e.objectApiName,total:e.total,processed:e.masked+e.nothingToMask,failed:e.refused,notMasked:Wt(e)}))}function eo(s){return s.filter(e=>e.total>0||e.masked+e.refused>0).map(e=>{let t=so(e);return{...$t(e.objectApiName),updated:e.masked,failed:e.refused+e.unanswered,...e.unanswered>0?{mayHaveBeenWritten:e.unanswered}:{},...t>0?{notSent:t}:{}}})}async function to(s,e,t,n,r,o){return Vn(s,`SELECT ${t} FROM ${e}${Mn(o,r)} ORDER BY Id LIMIT ${n}`,n)}function Mn(s,e){let t=s?.trim(),n=[...t?[`(${Jt(t)})`]:[],...e===void 0?[]:[`Id > '${e}'`]];return n.length===0?"":` WHERE ${n.join(" AND ")}`}function En(s){let e=s.where?.trim();return e||void 0}function Qo(s){let e=s?.trim();return e?`(${Jt(e)}) AND ${jn}`:jn}function Vo(s){let e=new Map;for(let[t,n]of s){if(n.length===0)throw new Error(`No field of ${t} was named for the snapshot to read.`);e.set(t,n.map(r=>St(r)).join(", "))}return e}function no(s,e,t){let n=e===void 0?"more records":`${e} records`;return new at(`${s} holds ${n}, past the ${t} a snapshot reads of one object: no snapshot was kept, as one holding part of the object would be taken for all of it.`,!1)}function io(s,e){return`The org stopped answering the read of ${s} after ${e} record(s), before it said the read was done: no snapshot was kept.`}async function Jo(s,e,t,n){let r={headers:{},maxFetch:1e4,autoFetch:!1,scanAll:t,responseTarget:"QueryResult"},o=await s.query(e,r),i=[...o.records];for(;!o.done;){if(!o.nextRecordsUrl)throw new at(io(n,i.length),!0);o=await s.queryMore(o.nextRecordsUrl,r),i.push(...o.records)}return i}function Zo(s,e,t){let n=s[s.length-1]?.Id;if(typeof n!="string"||!_t.test(n)||n===e)throw new Error(`The org answered a page of ${t} that does not end past the page before it: masking stopped there rather than write the same rows again.`);return n}var ro=class{constructor(e,t){this.deps=e;this.saveDialog=t??new Dt}deps;activeOrgOperations=new Set;writing=new wr;dmlTracker=new Et;backupRecords;syncRuns;expiryListener;sweeping;liveTracker;backupsWriting=new Set;maskingKey=Oo(32).toString("hex");saveDialog;get savedTemplates(){return new zt(this.deps.configStore)}findTemplate(e){return kt.find(t=>t.id===e)??this.savedTemplates.load(e)}ruleConfig(e){let t={...e.config};return e.ruleType==="hash"&&(t.hashSalt=this.maskingKey),t}maskingRules(e,t){return t.map(n=>({objectApiName:e,fieldApiName:n.fieldPattern.includes(".")?n.fieldPattern.split(".")[1]:n.fieldPattern,method:n.ruleType,config:this.ruleConfig(n)}))}refuseUnknownTemplate(e,t,n){M(this.deps,e,"dataops:error",t,Xr(n),{code:qr})}setLiveOperationTracker(e){this.liveTracker=e}setSyncRuns(e){this.syncRuns=e}targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;muteLeases={};setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}setMuteOffered(e){this.muteOffered=e}muteOffered=!0;duplicatesSettleMs=Rr;setDuplicatesSettle(e){this.duplicatesSettleMs=e}duplicatesWatchOf(e,t){return vr({query:async n=>e.query(n),serverTime:async()=>(await e.soap.getServerTimestamp()).timestamp},t,{settleMs:this.duplicatesSettleMs})}ownReader(){return this.reader??=import("./chunk-4XZ5YT5O.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(n=>Re(n,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}orgNameOf(e){return It(this.deps.orgManager.getOrg(e),e)}readAct(e,t,n,r,o,i){let a=this.targetAutomation;return Sr({act:n,target:this.orgNameOf(t),objects:r,org:Or(e,d=>new Tr(No).withTimeout("dataops automation",()=>a.read(t,d)),Vt(this.deps.orgManager.getOrg(t))==="production"),accord:o,mayMute:this.muteOffered,muteLeases:this.muteLeases,...i?{voice:i}:{}})}async releaseMute(e,t){if(!e)return;let n=await e.release();for(let r of Ir(n,this.orgNameOf(t)))this.deps.log(`[INFO] ${r}`);return n}async handleAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(rr,e,"dataops:error",this.deps);if(t)try{let n=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),r=await this.readAct(n,t.orgId,t.act,t.objects,t,bt(t)),o=se(this.deps,e,"dataops:automation:response",{...r.answer});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} refusals=${r.answer.refusals.length}`)}catch(n){M(this.deps,"dataops:automation","dataops:error",e,n)}}setExpiryListener(e){this.expiryListener=e}setBackupRecordStore(e){this.backupRecords=e,this.sweeping=this.sweepBackupFiles()}swept(){return this.sweeping??Promise.resolve()}async sweepBackupFiles(e=Date.now()){await this.expireBackups(e);let t=this.backupRecords;if(t)try{let n=new Set(this.backupsWriting);for(let o of this.deps.configStore.getKeysByPrefix("backup:"))n.add(o.slice(7).split(":")[0]);let r=await t.sweep(n,Lo,e);r.length>0&&this.deps.log(`[INFO] Removed ${r.length} backup file(s) whose backup never saved its metadata: `+r.join(", "))}catch(n){this.deps.log("[WARN] the files of backups that never saved their metadata were not removed: "+R(n))}}isWritingTo(e){return this.writing.has(e)}async handle(e){if(!So.has(e.type))return!1;switch(e.type){case"backup:execute":return await this.handleBackup(e),!0;case"backup:list":return this.handleBackupList(e),!0;case"backup:objects":return await this.handleBackupObjects(e),!0;case"backup:export":return await this.handleBackupExport(e),!0;case"backup:delete":return await this.handleBackupDelete(e),!0;case"dataops:rollback":return await this.writing.during(ln(e,"orgId"),()=>this.handleRollback(e)),!0;case"dataops:anonymize":return await this.writing.during(ln(e,"orgId"),()=>this.handleAnonymize(e)),!0;case"dataops:anonymization-templates":return this.handleAnonymizationTemplates(e),!0;case"dataops:quality-scan":return await this.handleQualityScan(e),!0;case"dataops:anonymization-template:save":return this.handleTemplateSave(e),!0;case"dataops:anonymization-template:delete":return this.handleTemplateDelete(e),!0;case"dataops:anonymize:coverage":return await this.handleAnonymizeCoverage(e),!0;case"dataops:anonymize:preview":return await this.handleAnonymizePreview(e),!0;case"dataops:automation":return await this.handleAutomation(e),!0;case"precheck:pii-scan":return await this.handlePIIScan(e),!0;default:return!1}}async selectAllFields(e,t,n){let r=await e.describe(t),o=r.fields.filter(d=>d.type===mr).map(d=>d.name),i=o.length>0&&n&&!await n()?o:[];return{select:r.fields.filter(d=>!i.includes(d.name)).map(d=>d.name).join(", "),notKept:i}}async maskedFields(e,t,n,r=[]){let o=(await e.describe(t)).fields,i=new Map(o.map(l=>[l.name.toLowerCase(),l.name])),a=[],d=[];for(let l of n){let f=i.get(l.fieldApiName.toLowerCase());f!==void 0?a.push({...l,fieldApiName:f}):l.fieldApiName!=="*"&&!d.includes(l.fieldApiName)&&d.push(l.fieldApiName)}let c=Nr({objectApiName:t,fields:o,kept:a,derived:r,detector:this.deps.infraServices?.piiDetector??new kr});if(c&&c.unseen.length>0){let l=await e.describe(lt).then(f=>f.fields,()=>{});for(let f of Pr(c.unseen,l))d.includes(f)||d.push(f)}let p=c?[...a,...c.rules]:a,u=p.map(l=>l.fieldApiName).filter((l,f,h)=>l!=="Id"&&h.indexOf(l)===f),b=c&&u.length>0&&!u.includes(rt);return{rules:p,select:["Id",...u,...b?[rt]:[]].join(", "),missing:d,rulesOf:c?l=>jr(t,l,p,c.personOnly):()=>p}}async countRows(e,t,n,r){let i=(await e.query(`SELECT COUNT() FROM ${t}${Mn(r,n)}`)).totalSize;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`The org did not say how many records ${t} holds.`);return i}async organizationIdOf(e){try{let n=(await mt(e,"SELECT Id FROM Organization"))[0]?.Id;return typeof n=="string"&&$o.test(n)?n:void 0}catch(t){this.deps.log(`[WARN] dataops: the org did not say which org it is: ${R(t)}`);return}}async handleBackup(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(Jn,e,"dataops:error",this.deps);if(!t)return;let n=e.id,r=await this.takeBackup(n,t,e.type);if("error"in r){M(this.deps,"backup:execute","dataops:error",e,r.error),this.endBackupNotTaken(n,r);return}let o=se(this.deps,e,"dataops:backup:response",{operationId:n,status:"completed",objects:r.objects.map(Pn),totalRecords:r.totalRecords,...r.partial?{partial:!0}:{},timestamp:r.timestamp});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}async backupForPipeline(e,t){let n=e.fields?Vo(e.fields):void 0,r=await this.takeBackup(e.operationId,{orgId:e.orgId,objects:e.objects,...n?{fields:n}:{},...e.scanAll?{scanAll:new Set(e.scanAll)}:{},...e.origin?{origin:e.origin}:{},...e.failWhenTruncated===!0?{failWhenTruncated:!0}:{},...e.onConnection?{onConnection:e.onConnection}:{}},e.origin==="checkpoint"?"checkpoint:take":"pipeline:execute",t);if("error"in r){let o=R(r.error);throw this.endBackupNotTaken(e.operationId,r),r.cancelled?new dn(o):r.error instanceof Error?r.error:new Error(o)}return r}endBackupNotTaken(e,t){if(t.cancelled){xe(this.deps,e,{aborted:!0});return}de(this.deps,e,R(t.error),t.retryable,{context:t.context})}async takeBackup(e,t,n,r){let o={module:"dataops",operation:n},i=`backup:${t.orgId}`;if(this.activeOrgOperations.has(i)){let g=`A backup or rollback operation is already running for org ${t.orgId}. Please wait for it to complete.`;return this.deps.log(`[WARN] ${g}`),{error:new Error(g),retryable:!1,context:o}}this.activeOrgOperations.add(i);let a=()=>{},d,c=new AbortController,p=()=>c.abort();r?.aborted&&c.abort(),r?.addEventListener("abort",p,{once:!0});let u=this.backupCap(),b=this.backupWriter(e);this.backupsWriting.add(e);let l=[],f,h,w,v=(g,$,O,B)=>{Ct(this.deps,e,g,$,O,B),w?.progress(g,$,O,B)};try{if(this.dmlTracker.isDuplicate(e))return this.deps.log(`[WARN] Duplicate backup operation detected: ${e}`),{error:new Error(`Duplicate operation: ${e}`),retryable:!1,context:o};this.dmlTracker.register(e,"backup","insert",t.objects.length);let g=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager);h=g,t.onConnection?.(g);let $=gr(async E=>(await g.query(E)).records),O=this.deps.orgManager.getOrg(t.orgId),B=yn(O?.orgType==="Sandbox"||O?.orgType==="Scratch"),Y=kn(B).defaultQueryLimit,K=`Backup ${t.objects.length} object(s)`;jt(this.deps,e,"dataops",K),this.deps.infraServices?.backgroundRegistry?.register(e,"dataops",K,new Promise((E,S)=>{a=j=>{j===void 0?E():S(j instanceof Error?j:new Error(String(j)))}}),c),w=xt(this.liveTracker,e,"dataops",K,t.objects.length);for(let E of t.objects){if(c.signal.aborted)throw new it;let S=De(E);o.objectName=S;let j={objectApiName:E,recordCount:0,truncated:!1};f=j,await this.readIntoBackup(g,S,j,b,{pageSize:Y,cap:u,select:t.fields?.get(S),where:t.wheres?.get(S),scanAll:t.scanAll?.has(S)===!0,...t.origin==="checkpoint"?{stamp:Mo}:{},whole:t.failWhenTruncated===!0,viewsEncrypted:$},c.signal,()=>{let q=Math.max(1,Math.min(j.orgCount??u,u));v(Math.round((l.length+j.recordCount/q)/t.objects.length*100),l.length,t.objects.length,`Reading ${E} (${j.recordCount} of ${q} records)`)}),f=void 0,l.push(j),j.stoppedAt==="cap"&&this.deps.log(`[WARN] backup of ${S} stopped at the cap of ${u} record(s): the object holds ${j.orgCount??"more"}.`),v(Math.round(l.length/t.objects.length*100),l.length,t.objects.length,`Exported ${E} (${j.recordCount} records)`)}let F=await this.organizationIdOf(g);if(c.signal.aborted)throw new it;let P=this.saveBackupMeta({operationId:e,orgId:t.orgId,organizationId:F,cap:u,...t.origin?{origin:t.origin}:{}},l,b,!1);return this.pruneAfterBackup(t.orgId),xe(this.deps,e,{objects:l.map(E=>({objectApiName:E.objectApiName,recordCount:E.recordCount})),totalRecords:P.totalRecords,...P.partial?{status:"partial"}:{}}),this.dmlTracker.markCompleted(e),P.partial?w?.partial():w?.complete(),{operationId:e,objects:l,totalRecords:P.totalRecords,partial:P.partial,timestamp:P.timestamp}}catch(g){this.dmlTracker.markFailed(e);let $=g instanceof it,O=$||g instanceof wt||t.failWhenTruncated===!0?void 0:await this.keepFailedBackup({operationId:e,orgId:t.orgId,cap:u,...t.origin?{origin:t.origin}:{}},h,{taken:l,reading:f,planned:t.objects},b);O===void 0&&await b.discard().catch(K=>{this.deps.log(`[WARN] backup ${e}: what it wrote before it stopped was not removed: `+R(K))});let B=O===void 0?g:new Error(`${R(g)} \u2014 the backup keeps the ${O.totalRecords} record(s) read before it stopped, listed as partial: ${$n(O.objects)}.`);d=B,$&&this.deps.infraServices?.backgroundRegistry?.abort(e),$?w?.cancel():w?.fail(R(B));let Y=!(g instanceof at)||g.retryable;return{error:B,retryable:Y,context:o,cancelled:$}}finally{r?.removeEventListener("abort",p),a(d),this.activeOrgOperations.delete(i),this.backupsWriting.delete(e)}}backupCap(){let e=this.deps.services?.getSandforgeSetting?.("backup.maxRecordsPerObject",_r);return typeof e!="number"||!Number.isFinite(e)?_r:Math.min(zo,Math.max(Eo,Math.floor(e)))}backupWriter(e){let t=this.backupRecords;if(t){let r=new Set;return{begin:async o=>{r.add(o),await t.begin(e,o).catch(i=>{throw new wt(i)})},append:async(o,i)=>{await t.append(e,o,i).catch(a=>{throw new wt(a)})},keep:()=>{},discard:async()=>{for(let o of r)await t.delete(e,o)}}}let n=new Map;return{begin:async r=>{n.set(r,[])},append:async(r,o)=>{n.get(r)?.push(...o)},keep:()=>{for(let[r,o]of n)this.deps.configStore.set(`backup:${e}:${r}`,o,"backups")},discard:async()=>{n.clear()}}}async readIntoBackup(e,t,n,r,o,i,a){let d=o.scanAll===!0,c={headers:{"Sforce-Query-Options":`batchSize=${o.pageSize}`},maxFetch:1e4,autoFetch:!1,scanAll:d,responseTarget:"QueryResult"},p=o.select;if(p===void 0){let v=await this.selectAllFields(e,t,o.viewsEncrypted);p=v.select,v.notKept.length>0&&(n.notKept=v.notKept)}let u=d?Qo(o.where):o.where,b=`SELECT ${p} FROM ${t}${Mn(u,void 0)}`,l=o.stamp??Gn(b)?.stamp,f=qn(b,l===void 0?void 0:["Id",l]),h=d||o.whole===!0?v=>Jo(e,v,d,t):v=>mt(e,v),w=await e.query(f?.first??b,c);if(Be(e.limitInfo,`dataops:backup query ${t}`),typeof w.totalSize=="number"&&Number.isInteger(w.totalSize)&&(n.orgCount=w.totalSize),o.whole===!0&&n.orgCount!==void 0&&n.orgCount>o.cap)throw no(t,n.orgCount,o.cap);for(await r.begin(n.objectApiName);;){let v=o.cap-n.recordCount,g=w.records.length>v,$=g?w.records.slice(0,v):w.records,O=$;f&&l!==void 0?O=await Qn($,f,h,{stamp:l,...d?{idsWhere:jn}:{}}):f&&await Xn($,f,h);let B=w.done?void 0:w.nextRecordsUrl;if(o.whole===!0&&!w.done&&B===void 0)throw new at(io(t,n.recordCount+O.length),!0);let Y=g||B!==void 0&&n.recordCount+O.length>=o.cap;if(Y&&o.whole===!0)throw no(t,n.orgCount,o.cap);if(await r.append(n.objectApiName,O),n.recordCount+=O.length,Y){n.truncated=!0,n.stoppedAt="cap";return}if(B===void 0)return;if(a(),i.aborted)throw new it;w=await e.queryMore(B,c),Be(e.limitInfo,`dataops:backup query ${t}`)}}saveBackupMeta(e,t,n,r){let o={operationId:e.operationId,orgId:e.orgId,...e.organizationId!==void 0?{organizationId:e.organizationId}:{},...e.origin!==void 0?{origin:e.origin}:{},objects:t.map(Pn),partial:t.some(i=>i.truncated),...r?{status:"failed"}:{},cap:e.cap,timestamp:new Date().toISOString(),totalRecords:t.reduce((i,a)=>i+a.recordCount,0)};return this.deps.configStore.set(`backup:${e.operationId}`,o,"backups"),n.keep(),o}async keepFailedBackup(e,t,n,r){let{taken:o,reading:i}=n,a=i?[...o,{...i,truncated:!0,stoppedAt:"failure"}]:[...o],d=new Set(a.map(u=>u.objectApiName.toLowerCase())),c=n.planned.filter(u=>!d.has(u.toLowerCase())).map(u=>({objectApiName:u,recordCount:0,truncated:!0,stoppedAt:"not_reached"})),p=[...a,...c];if(!p.every(u=>u.recordCount===0))try{let u=t?await this.organizationIdOf(t):void 0,b=this.saveBackupMeta({...e,organizationId:u},p,r,!0);return this.pruneAfterBackup(e.orgId),{...b,objects:p}}catch(u){this.deps.log(`[WARN] backup ${e.operationId}: the rows read before it failed were not kept: `+R(u));try{this.deps.configStore.delete(`backup:${e.operationId}`)}catch{}return}}async expireBackups(e){let t=Ar(this.deps.services);if(t<=0)return;let n=e-t*Do;try{let r=this.retentionSince(e);for(let o of this.backupMetaKeys()){let i=this.deps.configStore.get(o),a=Date.parse(i?.timestamp??"");if(!Number.isFinite(a)||a>=n||a<r||i?.origin==="checkpoint"||i?.orgId!==void 0&&this.backupBusy(i.orgId))continue;await this.removeBackup(o);let d=i?.origin==="sync"?` \u2014 the values the Sync run ${i.runId??"(unknown)"} wrote over, which removing that run no longer puts back`:"";this.deps.log(`[INFO] Removed backup ${o}: taken more than ${t} day(s) ago${d}`),this.expiryListener?.({operationId:o.slice(7),days:t,...i?.timestamp!==void 0?{takenAt:i.timestamp}:{},...i?.origin==="sync"?{syncRunId:i.runId??""}:{}})}}catch(r){this.deps.log(`[WARN] the backups past their age were not removed: ${R(r)}`)}}retentionSince(e){let t=Date.parse(this.deps.configStore.get(Wr)??"");return Number.isFinite(t)?t:(this.deps.configStore.set(Wr,new Date(e).toISOString()),e)}backupMetaKeys(){return this.deps.configStore.getKeysByPrefix("backup:").filter(e=>!e.slice(7).includes(":"))}backupBusy(e){return this.activeOrgOperations.has(`backup:${e}`)}async removeBackup(e){let n=this.deps.configStore.get(e)?.objects??[];for(let o of n)this.deps.configStore.delete(`${e}:${o.objectApiName}`);this.deps.configStore.delete(e);let r=e.slice(7);for(let o of n)await this.backupRecords?.delete(r,o.objectApiName)}async handleBackupDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(tr,e,"dataops:error",this.deps);if(!t)return;if(this.backupBusy(t.orgId)){M(this.deps,"backup:delete","dataops:error",e,new Error(`A backup or rollback operation is already running for org ${t.orgId}. Delete its backups once it has ended.`),{code:xo});return}let n=t.operationIds?new Set(t.operationIds):void 0,r=[];try{for(let i of this.backupMetaKeys()){let a=this.deps.configStore.get(i);if(a?.orgId!==t.orgId)continue;let d=a.operationId??i.slice(7);n&&!n.has(d)||(await this.removeBackup(i),r.push(d))}}catch(i){M(this.deps,"backup:delete","dataops:error",e,i);return}this.deps.log(`[INFO] Deleted ${r.length} backup(s) of org ${t.orgId}`);let o=se(this.deps,e,"backup:delete:result",{orgId:t.orgId,deleted:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} deleted=${r.length}`)}pruneAfterBackup(e){try{this.pruneBackups(e)}catch(t){this.deps.log(`[WARN] backup retention failed after the snapshot was written: ${R(t)}`)}this.sweepBackupFiles()}handleBackupList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(Zn,e,"dataops:error",this.deps);if(!t)return;let n=[];for(let o of this.deps.configStore.getKeysByPrefix("backup:")){if(o.slice(7).includes(":"))continue;let i=this.deps.configStore.get(o);!i||i.orgId!==t.orgId||n.push({operationId:i.operationId??o.slice(7),orgId:i.orgId,timestamp:i.timestamp??"",totalRecords:i.totalRecords??0,totalSize:0,status:i.status==="failed"?"failed":"completed",objectResults:(i.objects??[]).map(Pn),...i.partial?{partial:!0}:{},...i.origin==="sync"?{origin:"sync"}:{}})}n.sort((o,i)=>i.timestamp.localeCompare(o.timestamp));let r=se(this.deps,e,"backup:list:result",{backups:n});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} count=${n.length}`)}async handleBackupExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(er,e,"dataops:error",this.deps);if(!t)return;let n=`backup:${t.operationId}`,r=this.deps.configStore.get(n);if(!r||r.orgId!==t.orgId){M(this.deps,"backup:export","dataops:error",e,new Error(`Backup not found: ${t.operationId}`),{code:"BACKUP_NOT_FOUND"});return}let o=await this.saveDialog.saveStream(`sandforge-backup-${t.operationId}.json`,a=>this.writeBackupDocument(t,r,a),["json"]);if(o.status==="error"){M(this.deps,"backup:export","dataops:error",e,new Error(o.message));return}let i=se(this.deps,e,"backup:export:result",o.status==="saved"?{operationId:t.operationId,status:"saved",path:o.path,objects:o.result}:{operationId:t.operationId,status:"cancelled"});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} ${o.status}`)}async writeBackupDocument(e,t,n){let{operationId:r}=e,i=[["sandforgeBackupVersion",1],["operationId",r],["orgId",e.orgId],["timestamp",t.timestamp??""],["totalRecords",t.totalRecords??0]].map(([d,c])=>` "${d}": ${JSON.stringify(c)},
8
- `);await n(`{
9
- ${i.join("")} "objects": {`);let a=[];for(let{objectApiName:d}of t.objects??[]){if(a.some(p=>p.objectApiName===d))continue;await n(`${a.length>0?",":""}
10
- ${JSON.stringify(d)}: [`);let c=0;for await(let p of await this.backupBatches(r,d))p.length!==0&&(await n(p.map((u,b)=>`${c+b>0?",":""}
11
- ${JSON.stringify(u)}`).join("")),c+=p.length);await n(c>0?`
12
- ]`:"]"),a.push({objectApiName:d,records:c})}return await n(`${a.length>0?`
13
- `:""}}
14
- }
15
- `),a}async backupBatches(e,t){let n=await this.backupRecords?.batches(e,t,st);if(n)return n;let r=this.deps.configStore.get(`backup:${e}:${t}`),o=Array.isArray(r)?r:[];return{async*[Symbol.asyncIterator](){for(let i=0;i<o.length;i+=st)yield o.slice(i,i+st)}}}async firstBackupRecord(e,t,n){let r=await this.backupBatches(e,t),o=n.origin==="sync"?An(r,st).batches:r;for await(let i of o)if(i[0]!==void 0)return i[0]}pruneBackups(e){let t=this.deps.services?.getSandforgeSetting?.("backup.maxCount",10)??10,n=[];for(let r of this.deps.configStore.getKeysByPrefix("backup:")){if(r.slice(7).includes(":"))continue;let i=this.deps.configStore.get(r);i?.orgId===e&&i.origin!=="sync"&&i.origin!=="checkpoint"&&n.push({key:r,timestamp:i.timestamp??""})}if(!(n.length<=t)){n.sort((r,o)=>r.timestamp.localeCompare(o.timestamp));for(let{key:r}of n.slice(0,n.length-t))this.removeBackup(r),this.deps.log(`[INFO] Pruned backup ${r} (retention: ${t} per org)`)}}async undeleteFromRecycleBin(e,t,n){let r=[];for await(let i of n){let a=i.map(c=>c.Id).filter(c=>typeof c=="string");if(a.length===0)continue;let d=a.map(c=>`'${Kn(c)}'`).join(", ");try{let c=await e.query(`SELECT Id FROM ${t} WHERE Id IN (${d}) AND IsDeleted = true`,{scanAll:!0});r.push(...c.records.map(p=>p.Id))}catch(c){return this.deps.log(`[WARN] Rollback on ${t}: could not look for deleted records \u2014 ${R(c)}`),{undeleted:0}}}let o=0;for(let i=0;i<r.length;i+=200){let a=await e.soap.undelete(r.slice(i,i+200));o+=a.filter(d=>d.success).length}return{undeleted:o}}refuseWithoutGuard(e,t,n,r){oe(this.deps,{...r,outcome:"stopped",source:void 0,code:ft.code}),e(new Error(ft.message),{code:ft.code}),de(this.deps,t,ft.message,!1,{context:n,authored:!0})}async handleRollback(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(nr,e,"dataops:error",this.deps);if(!t)return;let n=t,r=e.id,o={module:"dataops",operation:e.type},i=`backup:${n.orgId}`;if(this.activeOrgOperations.has(i)){let h=`A backup or rollback operation is already running for org ${n.orgId}. Please wait for it to complete.`;this.deps.log(`[WARN] ${h}`),M(this.deps,"dataops:rollback","dataops:error",e,new Error(h)),de(this.deps,r,h,!1,{context:o,authored:!0});return}this.activeOrgOperations.add(i);let a,d=[],c=!1,p=new AbortController,u=()=>{},b,l,f;try{if(this.dmlTracker.isDuplicate(r)){this.deps.log(`[WARN] Duplicate rollback operation detected: ${r}`),M(this.deps,"dataops:rollback","dataops:error",e,new Error(`Duplicate operation: ${r}`)),de(this.deps,r,`Duplicate operation: ${r}`,!1,{context:o,authored:!0});return}this.dmlTracker.register(r,"rollback","upsert",0);let h=await Re(n.orgId,this.deps.orgRegistry,this.deps.orgManager),w=new on(async k=>{let I=await h.describe(k);return oo(I)}),v=`backup:${n.operationId}`,g=this.deps.configStore.get(v);if(!g)throw new Error(`No backup found for operation ${n.operationId}. Cannot rollback.`);if(g.orgId!==n.orgId)throw new Error(`Backup ${n.operationId} was taken from org ${g.orgId} and cannot be restored into org ${n.orgId}.`);a={action:"backup_restore",module:"dataops",operationId:r,orgId:n.orgId,outcome:"failure",source:{origin:"backup",label:g.timestamp?.slice(0,16).replace("T"," ")??n.operationId}};let $=this.deps.infraServices?.productionGuard;if(!$){this.refuseWithoutGuard((k,I)=>M(this.deps,"dataops:rollback","dataops:error",e,k,I),r,o,a);return}let O=[];for(let k of g.objects){let I=await this.firstBackupRecord(n.operationId,k.objectApiName,g);if(I===void 0)continue;let y=De(k.objectApiName);if(!(await w.checkCrudPermission(y,"upsert")).allowed){O.push({objectApiName:y,operation:"upsert",deniedFields:[]});continue}let{denied:he}=await w.partitionWritableFields(y,"upsert",Object.keys(I).filter(me=>me!=="attributes"));he.length>0&&O.push({objectApiName:y,operation:"upsert",deniedFields:he})}if(O.length>0){let k=rn(O);this.deps.log(`[WARN] CRUD/FLS check failed for rollback ${r}: ${k}`),oe(this.deps,{...a,outcome:"stopped",source:void 0,code:gt}),M(this.deps,"dataops:rollback","dataops:error",e,new Error(k),{code:gt}),de(this.deps,r,k,!1,{context:o,authored:!0});return}let B=(k,I,y,Ce=[])=>{oe(this.deps,{...y,outcome:"stopped",source:void 0,code:k}),M(this.deps,"dataops:rollback","dataops:error",e,new Error(I),{code:k,...bn({alsoRefused:Ce})}),de(this.deps,r,I,!1,{context:o,authored:!0})},Y=await this.readAct(h,n.orgId,"restore",g.objects.map(k=>({objectApiName:k.objectApiName,records:k.recordCount})),n,bt(n)),K=hn(Y.answer);if(K){B(K.code,K.message,a,K.alsoRefused);return}f=this.duplicatesWatchOf(h,fn(Y.answer.automation,g.objects.filter(k=>k.recordCount>0).map(k=>k.objectApiName)));let F=this.deps.orgManager.getOrg(n.orgId),P={orgId:n.orgId,orgTier:In(F),operation:"upsert",objectName:g.objects.map(k=>k.objectApiName).join(", ")||"RollbackData",recordCount:g.totalRecords??0,module:"dataops"},{check:E,decision:S}=await pn($,P);if(a.guard=S,(S==="refused"||S==="declined")&&oe(this.deps,{...a,outcome:"stopped",source:void 0}),S==="refused")throw Yt(E.blockedReason??E.impactSummary);if(S==="declined"){let k="Operation cancelled by user (confirmation declined).";M(this.deps,"dataops:rollback","dataops:error",e,new Error(k),{code:Zt.declined}),de(this.deps,r,k,!1,{context:o,authored:!0});return}if(g.organizationId!==void 0){let k=await this.organizationIdOf(h);if(k!==void 0&&!jo(g.organizationId,k)){let I=It(F,n.orgId),y=this.deps.infraServices?.confirmRestoreIntoReplacedOrg;if(!(y?await y({alias:I,backedUpFrom:g.organizationId,now:k}):!1)){oe(this.deps,{...a,outcome:"stopped",source:void 0,code:Fr});let he=`Restore not run: ${I} answers as org ${k}, not as org ${g.organizationId}, which backup ${n.operationId} was taken from, `+(y?"and the restore into the org it is now was not confirmed.":"and nothing here can ask whether to restore into the org it is now.");M(this.deps,"dataops:rollback","dataops:error",e,new Error(he),{code:Fr}),de(this.deps,r,he,!1,{context:o,authored:!0});return}}}let j=await gn(Y,r,n.acceptEmails===!0,bt(n));if("refused"in j){B(j.refused.code,j.refused.message,a);return}l=j.held,jt(this.deps,r,"dataops",`Rollback ${g.objects.length} object(s)`),c=!0,this.deps.infraServices?.backgroundRegistry?.register(r,"dataops",`Rollback ${g.objects.length} object(s)`,new Promise((k,I)=>{u=y=>{y===void 0?k():I(y instanceof Error?y:new Error(String(y)))}}),p),b=xt(this.liveTracker,r,"dataops",`Rollback ${g.objects.length} object(s)`,g.objects.length);let q=!1,L=0,fe=0,Te=0,Qe=[],Ve=new Map,T=g.origin==="sync"&&n.includeChanged!==!0,D=Number.NEGATIVE_INFINITY,ee=!1;if(T){let k=g.runId!==void 0?await this.syncRuns?.get(g.runId).catch(y=>{this.deps.log(`[WARN] Rollback: the Sync run of backup ${n.operationId} could not be read \u2014 ${R(y)}`)}):void 0,I=k?fr(k):void 0;ee=I===void 0,D=await lr({serverTime:async()=>(await h.soap.getServerTimestamp()).timestamp},I)}let X=[];for(let k=0;k<g.objects.length;k++){if(p.signal.aborted){q=!0;break}let I=g.objects[k],y=De(I.objectApiName);o.objectName=y;let Ce=await this.backupBatches(n.operationId,I.objectApiName),he=g.origin==="sync"?An(Ce,st):void 0,me=he?.batches??Ce,Ie;for await(let _ of me)if(Ie=_[0],Ie!==void 0)break;if(T&&Ie!==void 0){let _=[];for await(let ie of me)for(let te of ie)typeof te.Id=="string"&&_.push(te.Id);let ue=await Mr({query:async(ie,te)=>({records:(await h.query(ie,te)).records})},y,_,D);ue.size>0&&(X.push({objectApiName:y,count:ue.size}),me=Er(me,ue))}if(Ie===void 0){Ve.set(I.objectApiName,0),this.deps.log(`[WARN] No backup records for ${I.objectApiName}, skipping.`);continue}let Ut=Object.keys(Ie).filter(_=>_!=="attributes"),{skipped:Ht}=await w.partitionWritableFields(y,"upsert",Ut),Me=new Set(Ht.filter(_=>_.toLowerCase()!=="id").map(_=>_.toLowerCase()));Me.size>0&&this.deps.log(`[INFO] Rollback on ${y}: ${Me.size} non-writable field(s) excluded from the payload \u2014 ${[...Me].sort().join(", ")}`);let vt=await this.undeleteFromRecycleBin(h,y,me);vt.undeleted>0&&this.deps.log(`[INFO] Rollback on ${y}: ${vt.undeleted} record(s) brought back from the recycle bin`),o.batchSize=st;let Ee=0,Ye=0,G=0,We=0;for await(let _ of me){if(p.signal.aborted){q=!0;break}We+=_.length;let ue=_.map(J=>{let we=y===W?Nt(J,!1):void 0,ze={};for(let[tt,Kt]of Object.entries(J))tt!=="attributes"&&(Me.has(tt.toLowerCase())||we!==void 0&&Ot(W,tt,we)||(ze[tt]=Kt));return ze}),ie=ue;if(n.rewriteAll!==!0){let J=await Cr({query:async we=>{let ze=await h.query(we);return{totalSize:ze.totalSize,records:ze.records}}},y,ue);J.unread!==void 0&&this.deps.log(`[WARN] Rollback on ${y}: the org's values could not be read, so ${ue.length} row(s) are written back without comparing \u2014 ${J.unread}`),ie=J.write,G+=J.unchanged}if(ie.length===0)continue;f.beforeWrite(y);let te;try{te=await h.sobject(y).upsert(ie,"Id",{headers:Qt()})}catch(J){throw un(J)==="may-have-written"&&f.wrote(y,ie.map(we=>we.Id)),J}let et=Array.isArray(te)?te:[te];f.wrote(y,et.flatMap((J,we)=>J.success?[ie[we]?.Id]:[]));for(let J of et){if(J.success){Ee++;continue}Ye++,Ur(Qe,y,J.errors)}}if(Be(h.limitInfo,`dataops:rollback upsert ${y}`),Ve.set(I.objectApiName,he&&!q?he.lines():We),L+=Ee,fe+=Ye,Te+=G,d.push({...$t(y),updated:Ee,failed:Ye}),q)break;let ct=`Restored ${y} (${Ee}/${We}${G>0?`, ${G} unchanged`:""})`,Oe=Math.round((k+1)/g.objects.length*100);Ct(this.deps,r,Oe,k+1,g.objects.length,ct),b.progress(Oe,k+1,g.objects.length,ct)}let N=X.reduce((k,I)=>k+I.count,0),ce=Bo(L,fe),V=q&&fe===0||N>0&&ce==="success"?"partial":ce;a&&(c=!1,oe(this.deps,{...a,...q?L+fe>0?{outcome:"cancelled"}:{outcome:"stopped",code:nn}:{outcome:V},objects:d}));let je=await this.releaseMute(l,n.orgId);l=void 0;let ge=await f.read();q?(this.deps.infraServices?.backgroundRegistry?.abort(r),xe(this.deps,r,{aborted:!0,totalRestored:L,totalFailed:fe,totalUnchanged:Te})):xe(this.deps,r,{status:V,totalRestored:L,totalFailed:fe,totalUnchanged:Te}),this.dmlTracker.markCompleted(r),q?b.cancel():V==="failure"?b.fail(`The org refused the ${fe} record(s)`):V==="partial"?b.partial():b.complete();let pe=$n(g.objects,Ve),Je=(q?`Rollback cancelled: ${L} records restored before the cancel; the rest still hold the values they had, and the same restore puts them back`:fe>0?`Rollback ${V}: ${L} restored, ${fe} rejected by the org`:N>0?`Rollback partial: ${L} records restored`:`Rollback completed: ${L} records restored`)+(Te>0?`; ${Te} already held the backup's values and were not written`:"")+(N>0?`; ${N} changed or deleted since the Sync run were left as they are `+(ee?"(the run is no longer kept here, so every record reads as changed since it) ":"")+"unless the restore includes them":""),Ne=ht(ge,this.orgNameOf(n.orgId),"restore"),Ze=pe===""?Je:`${Je}. The backup held only part of the org's records, and the rest were left as they are: ${pe}`,dt=Ne?`${Ze}. ${Ne}`:pe===""?Ze:`${Ze}.`,_e=se(this.deps,e,"dataops:rollback:response",{operationId:n.operationId,status:V,message:dt,totalRestored:L,totalFailed:fe,totalUnchanged:Te,...n.rewriteAll===!0?{rewriteAll:!0}:{},...n.includeChanged===!0?{includeChanged:!0}:{},...N>0?{keptChanged:{total:N,objects:X,...ee?{runNotKept:!0}:{}}}:{},errors:Qe,...pe!==""?{partial:!0}:{},...q?{cancelled:!0}:{},...je?{mutedAutomation:je}:{},...ge?{duplicates:ge}:{}});this.deps.broker.postToWebview(_e),this.deps.log(`[TX] ${_e.type} id=${_e.id} status=${V}`),(fe>0||pe!==""||q||N>0||mn(ge))&&tn(this.deps,V==="failure"?"error":"warning","Restore",`${dt}${Qe[0]?` \u2014 e.g. ${Qe[0].message}`:""}`)}catch(h){this.dmlTracker.markFailed(r),await this.releaseMute(l,n.orgId),l=void 0;let w=await f?.read(),v=ht(w,this.orgNameOf(n.orgId),"restore");M(this.deps,"dataops:rollback","dataops:error",e,v?new Error(`${R(h)} ${v}`):h,{code:en(h),...w?{extraPayload:{duplicates:w}}:{}}),de(this.deps,r,R(h),!0,{context:o}),b?.fail(R(h))}finally{await this.releaseMute(l,n.orgId),this.activeOrgOperations.delete(i),u(),c&&a&&oe(this.deps,{...a,outcome:"failure",objects:d})}}async snapshotBeforeMasking(e,t,n,r,o){let i=new Map,a=new Map;try{for(let p of r){if(p.tally.total===0)continue;p.where!==void 0&&a.set(p.tally.objectApiName,p.where);let{select:u}=await this.maskedFields(e,p.tally.objectApiName,this.maskingRules(p.objectName,p.objectRules),this.maskingRules(p.objectName,p.personRules));u!=="Id"&&i.set(p.tally.objectApiName,u)}}catch(p){return{refused:`No snapshot was taken, so nothing was masked: ${R(p)}`,retryable:!0}}if(i.size===0)return{};let d=`${t}-snapshot`,c=await this.takeBackup(d,{orgId:n,objects:[...i.keys()],...a.size>0?{wheres:a}:{},fields:i},o.origin,o.stop);return"error"in c?(this.endBackupNotTaken(d,c),{refused:`No snapshot was taken, so nothing was masked: ${R(c.error)}`,retryable:c.retryable&&c.cancelled!==!0}):c.partial?{refused:`Snapshot ${d} holds only part of the records the run would mask, so nothing was masked: a restore could not put back the rest (${$n(c.objects)}). Raise sandforge.backup.maxRecordsPerObject, or narrow the run.`,retryable:!1}:{taken:{operationId:d,totalRecords:c.totalRecords}}}async maskingNotCovered(e,t,n,r){if(r.length===0)return{code:ve.masksNothing,message:`The template "${t.name}" has no rule for ${n.join(", ")}: the run would mask nothing. Choose an object its rules name, or another template. Nothing was masked.`,gaps:{fieldsNotFound:[],objectsNotCovered:[...n]}};let o=[],i=[];for(let d of r){if(d.tally.total===0)continue;let{objectApiName:c}=d.tally,{rules:p,missing:u}=await this.maskedFields(e,c,this.maskingRules(d.objectName,d.objectRules),this.maskingRules(d.objectName,d.personRules));o.push(...u.map(b=>({objectApiName:c,fieldApiName:b}))),p.length===0&&i.push(c)}let a={fieldsNotFound:o,objectsNotCovered:i};if(o.length>0){let d=o.map(c=>`${c.objectApiName}.${c.fieldApiName}`).join(", ");return{code:ve.fieldsUnseen,message:`The template "${t.name}" masks ${d}, which the org does not show the user SandForge connects as: it has no such field, or field-level security hides it. `+(i.length>0?`No field of ${i.join(", ")} can be masked. `:"")+"A run masks every field its template names, or nothing: give that user read and edit access to the field, or take the field out of the template. Nothing was masked.",gaps:a}}if(i.length>0)return{code:ve.masksNothing,message:`The template "${t.name}" masks no field of ${i.join(", ")} in this org: the run would write nothing over its records. Choose an object its rules name, or another template. Nothing was masked.`,gaps:a}}async anonymizeForPipeline(e,t){let n=this.deps.orgManager.getOrg(e.orgId);if(!n)throw Fe(ve.orgUnknown,`The org the masking writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was masked.`);let r=xr(In(n),e.answer,It(n,e.orgId));if(r)throw r;let o=Br(e,f=>this.findTemplate(f)!==void 0);if("refusal"in o)throw o.refusal;let i=crypto.randomUUID(),a,d,c,p={origin:"pipeline:execute",pipeline:e.pipeline,accord:e.accord??{},voice:"step",muted:f=>{c=f},refused:(f,h)=>{a??={err:f,...h},this.deps.log(`[ERR] dataops:anonymize ${i} for the pipeline "${e.pipeline.name}": `+R(f))},ended:f=>{d=f}};await this.writing.during(e.orgId,()=>yr(e.answer,()=>this.mask(o.asked,i,p,t)));let u=a,b=c;if(u){let f=R(u.err),h=u.err,w=u.code??(typeof h?.code=="string"?h.code:void 0),v=u.extraPayload?.snapshot,g={...w!==void 0?{code:w}:{},...v!==void 0?{snapshot:v}:{},...b?{mutedAutomation:b}:{}};throw Object.assign(w===Pt?new dn(f):new Error(f),g)}let l=d;if(l===void 0)throw new Error("The masking run ended without a result.");return{operationId:i,result:b?{...l,mutedAutomation:b}:l}}async handleAnonymize(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(Mt,e,"dataops:error",this.deps);if(!t)return;let n=bt(t);await this.mask(t,e.id,{...this.pageMaskingReplies(e),accord:{acceptAutomation:t.acceptAutomation===!0,acceptEmails:t.acceptEmails===!0,muteAutomation:t.muteAutomation===!0},...n?{voice:n}:{}})}pageMaskingReplies(e){return{origin:e.type,refused:(t,n)=>M(this.deps,"dataops:anonymize","dataops:error",e,t,n),ended:t=>{let n=se(this.deps,e,"dataops:anonymize:response",t);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} status=${t.status}`),(t.recordsNotMasked>0||mn(t.duplicates))&&tn(this.deps,t.status==="failure"?"error":"warning","Anonymize",`${t.message}${t.errors[0]?` \u2014 e.g. ${t.errors[0].message}`:""}`)}}}async mask(e,t,n,r){let o,i={},a,d=async()=>(a??={released:await this.releaseMute(o,e.orgId)},a.released),c={...n,refused:(T,D)=>{if(!o){n.refused(T,D);return}i.answer??=ee=>n.refused(T,ee?{...D,extraPayload:{...D.extraPayload,mutedAutomation:ee}}:D)},ended:T=>{if(!o){n.ended(T);return}i.answer??=D=>n.ended(D?{...T,mutedAutomation:D}:T)}},p={module:"dataops",operation:c.origin},u=this.findTemplate(e.templateId),b=Bt(e,u),l={action:"anonymize_execute",module:"dataops",operationId:t,orgId:e.orgId,outcome:"failure",source:{origin:"org",orgId:e.orgId}},f=[],h=[],w=En(e),v=u?Lt(u.rules,b,w):"",g=!1,$=!1,O=!1,B=!1,Y,K,F=new AbortController,P=()=>{},E,S,j,q=async()=>j?.read(),L=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(t);L?.signal.addEventListener("abort",()=>F.abort(),{once:!0});let fe=()=>F.abort();r?.aborted&&F.abort(),r?.addEventListener("abort",fe,{once:!0});let Te=async()=>{oe(this.deps,{...l,outcome:"stopped",source:void 0,code:Pt});let T="The masking run was cancelled before it wrote anything.";c.refused(new Error(T),{code:Pt,...K?{extraPayload:{snapshot:K}}:{}}),await d(),xe(this.deps,t,{aborted:!0})},Qe=(T,D,ee)=>{E=T;let X=R(T),N=Rt(f),ce=g&&N.recordsNotMasked>0,V=ht(ee,this.orgNameOf(e.orgId)),je={...g?{...N,objects:Yr(f)}:{},...K?{snapshot:K}:{},...ee?{duplicates:ee}:{}},ge=ce?`${X} \u2014 ${N.recordsProcessed} masked before it stopped; ${N.recordsNotMasked} still hold their original values (${Zr(f)}).`:X;c.refused(ce||V?new Error(V?`${ge} ${V}`:ge):T,{code:en(T),extraPayload:je}),de(this.deps,t,X,D,{context:p,extraPayload:je}),S?.fail(X)},Ve=()=>{B=!0;let T=new ot(this.deps.configStore),{recordsNotMasked:D}=Rt(f),ee=f.reduce((X,N)=>X+N.masked+N.nothingToMask+N.refused+N.unanswered,0);try{if(D===0)return T.clear(e.orgId,e.templateId),!1;if(ee===0)return T.load(e.orgId,e.templateId,v)!==void 0;let X=h.map(N=>N.progress);return yt(X)>qe?(this.deps.log(`[WARN] dataops:anonymize ${t}: the org refused ${yt(X)} record(s), more than a resume retries (${qe}): only a full run masks them.`),T.clear(e.orgId,e.templateId),!1):(T.save({id:t,orgId:e.orgId,templateId:e.templateId,fingerprint:v,savedAt:new Date().toISOString(),objects:X,...Y?{namesGiven:Y.namesGiven()}:{}}),!0)}catch(X){return this.deps.log(`[WARN] dataops:anonymize ${t}: where the run stopped was not kept: `+R(X)),!1}};try{let T=this.deps.infraServices?.productionGuard;if(!T){this.refuseWithoutGuard((m,C)=>c.refused(m,C),t,p,l);return}if(!u){c.refused(Xr(e.templateId),{code:qr});return}let D=At(e,u,W)?Bt(e,u,!0):void 0,ee=D?[v,Lt(u.rules,D,w)]:[v],X=()=>c.refused(new Error("There is nothing to resume: the run has finished since, another run of this template has stopped since, or its rules have changed. Apply masks every record of its objects."),{code:Wo}),N;if(e.resumeFrom!==void 0){let m=new ot(this.deps.configStore);if(N=ee.map(C=>m.load(e.orgId,e.templateId,C)).find(C=>C?.id===e.resumeFrom),!N){X();return}}let ce=await Re(e.orgId,this.deps.orgRegistry,this.deps.orgManager),V=Hr(ce);if(D&&await Nn(V,this.deps.log)&&(b=D,v=ee[1]),N&&N.fingerprint!==v){X();return}let je,ge=m=>{let C=Be(ce.limitInfo,m);C&&C.usagePercent>=_o&&(je??=C)},pe=()=>je;for(let m of b){let C=Ft(u,m),ae=Cn(u,m);if(C.length===0&&ae.length===0)continue;let be=De(m),U=Sn(e,u,m);p.objectName=be;let A=N?.objects.find(Ue=>Ue.objectApiName===be),x={objectApiName:be,done:A?.done??!1,...A?.afterId!==void 0?{afterId:A.afterId}:{},refused:[...A?.refused??[]],...A?.unconfirmed?.length?{unconfirmed:[...A.unconfirmed]}:{}},Pe=0;if(!x.done){try{Pe=await this.countRows(ce,be,x.afterId,U)}catch(Ue){throw oe(this.deps,{...l,outcome:"failure",source:void 0,objects:[$t(be)],code:Ho,details:{reason:Go(Ue)}}),Ue}ge(`dataops:anonymize count ${be}`),Pe===0&&(x.done=!0)}let Tt=Pe+x.refused.length+(x.unconfirmed?.length??0),pt={objectApiName:be,total:Tt,masked:0,nothingToMask:0,refused:0,unanswered:0,done:Tt===0};f.push(pt),h.push({objectName:m,...U!==void 0?{where:U}:{},objectRules:C,personRules:ae,tally:pt,progress:x})}let Je=f.reduce((m,C)=>m+C.total,0),Ne=await this.maskingNotCovered(V,u,b,h);if(Ne){oe(this.deps,{...l,outcome:"stopped",source:void 0,code:Ne.code}),c.refused(new Error(Ne.message),{code:Ne.code,extraPayload:{...Ne.gaps}}),de(this.deps,t,Ne.message,!1,{context:p,authored:!0});return}let Ze=await Kr(V,h.filter(m=>m.tally.total>0).map(m=>({objectApiName:m.tally.objectApiName,rules:[...m.objectRules,...m.personRules]})));if(Ze.length>0){let m=rn(Ze);this.deps.log(`[WARN] CRUD/FLS check failed for anonymize ${t}: ${m}`),oe(this.deps,{...l,outcome:"stopped",source:void 0,code:gt}),c.refused(new Error(m),{code:gt}),de(this.deps,t,m,!1,{context:p,authored:!0});return}let dt=(m,C,ae=[])=>{oe(this.deps,{...l,outcome:"stopped",source:void 0,code:m}),c.refused(new Error(C),{code:m,...bn({alsoRefused:ae})}),de(this.deps,t,C,!1,{context:p,authored:!0})},_e=await this.readAct(ce,e.orgId,"masking",f.map(m=>({objectApiName:m.objectApiName,records:m.total})),c.accord,c.voice),k=hn(_e.answer);if(k){dt(k.code,k.message,k.alsoRefused);return}let I=this.duplicatesWatchOf(ce,fn(_e.answer.automation,f.filter(m=>m.total>0).map(m=>m.objectApiName)));j=I;let y=this.deps.orgManager.getOrg(e.orgId),Ce={orgId:e.orgId,orgTier:In(y),operation:"update",objectName:b.join(", ")||"AnonymizeData",recordCount:Je,module:"dataops"},{check:he,decision:me}=await pn(T,Ce);if(l.guard=me,(me==="refused"||me==="declined")&&oe(this.deps,{...l,outcome:"stopped",source:void 0}),me==="refused")throw Yt(he.blockedReason??he.impactSummary);if(me==="declined"){let m="Operation cancelled by user (confirmation declined).";c.refused(new Error(m),{code:Zt.declined}),de(this.deps,t,m,!1,{context:p,authored:!0});return}for(let m of he.warnings)this.deps.log(`[WARN] dataops:anonymize ${t}: ${m}`);if(F.signal.aborted){await Te();return}let Ie=await gn(_e,t,c.accord.acceptEmails===!0,c.voice);if("refused"in Ie){dt(Ie.refused.code,Ie.refused.message);return}o=Ie.held,g=!0;let Ut=yn(y?.orgType==="Sandbox"||y?.orgType==="Scratch"),Ht=kn(Ut).defaultQueryLimit;if(e.snapshot===!0){let m=await this.snapshotBeforeMasking(V,t,e.orgId,h,{origin:c.origin,stop:F.signal});if("refused"in m&&F.signal.aborted){await Te();return}if("refused"in m){oe(this.deps,{...l,outcome:"stopped",source:void 0,code:Qr}),c.refused(new Error(m.refused),{code:Qr}),await d(),de(this.deps,t,m.refused,m.retryable,{context:p,authored:!0});return}if(K=m.taken,F.signal.aborted){await Te();return}}let Me=c.pipeline?`Pipeline anonymization with ${u.name}`:`Anonymizing with ${u.name}`;jt(this.deps,t,"dataops",Me),$=!0,O=!0,this.deps.infraServices?.backgroundRegistry?.register(t,"dataops",Me,new Promise((m,C)=>{P=ae=>{ae===void 0?m():C(ae instanceof Error?ae:new Error(String(ae)))}}),F),S=xt(this.liveTracker,t,"dataops",Me,Je);let{AnonymizationEngine:vt}=await import("./chunk-TLH7AD35.mjs"),Ee=new vt(void 0,this.maskingKey);Y=Ee,N&&!(N.namesGiven!==void 0&&Ee.continueFrom(N.namesGiven))&&this.deps.log(`[INFO] dataops:anonymize ${t}: the run it resumes kept no record of the names it made up, so this one may give again a name or an address that run gave.`);let Ye=[],G=!1,We=m=>m.masked+m.nothingToMask+m.refused,ct=(m,C)=>{let ae=f.reduce((x,Pe)=>x+We(Pe),0),be=Math.max(Je,ae),U=Math.round(ae/be*100),A=`Anonymized ${m} (${We(C)}/${Math.max(C.total,We(C))})`;Ct(this.deps,t,U,ae,be,A),S?.progress(U,ae,be,A)};for(let{objectName:m,where:C,objectRules:ae,personRules:be,tally:U,progress:A}of h){if(U.total===0)continue;if(F.signal.aborted){G=!0;break}if(pe())break;let x=U.objectApiName;p.objectName=x;let{select:Pe,rulesOf:Tt}=await this.maskedFields(V,x,this.maskingRules(m,ae),this.maskingRules(m,be));p.batchSize=Xe;let pt=async(Z,ke,$e)=>{let Le=Z.map(Tt),Ae=Z.map((re,H)=>Ee.anonymize([re],Le[H])[0]),ne=[];Z.forEach((re,H)=>{let z={Id:re.Id};for(let ye of Le[H])cn(re[ye.fieldApiName])&&(z[ye.fieldApiName]=Ae[H][ye.fieldApiName]);Object.keys(z).length>1?ne.push(z):U.nothingToMask++});for(let re=0;re<ne.length;re+=Xe){if(F.signal.aborted)return G=!0,!0;if(pe())return!0;let H=ne.slice(re,re+Xe),z;I.beforeWrite(x);try{z=await ce.sobject(m).update(H,{headers:Qt()})}catch(He){throw un(He)==="may-have-written"&&(U.unanswered+=H.length,$e(H,H.flatMap(Uo)),I.wrote(x,H.map(ut=>ut.Id))),He}ge(`dataops:anonymize update ${x}`);let ye=[],Dn=Array.isArray(z)?z:[z];I.wrote(x,Dn.flatMap((He,ut)=>He.success?[H[ut]?.Id]:[])),Dn.forEach((He,ut)=>{if(He.success){U.masked++;return}U.refused++;let qt=H[ut]?.Id;typeof qt=="string"&&_t.test(qt)&&ye.push(qt),Ur(Ye,x,He.errors)}),ke(H,ye),ct(m,U)}return ne.length===0&&ct(m,U),!1},Ue=A.unconfirmed??[];for(let Z=0;Z<Ue.length;Z+=Xe){if(F.signal.aborted){G=!0;break}if(pe())break;let ke=Ue.slice(Z,Z+Xe),$e=ke.map(z=>`'${z.id}'`).join(", "),Le=await mt(ce,`SELECT ${Pe} FROM ${x} WHERE Id IN (${$e})`);ge(`dataops:anonymize query ${x}`);let Ae=new Map(Le.map(z=>[String(z.Id),z])),ne=[];for(let z of ke){let ye=Ae.get(z.id);ye===void 0?U.total-=1:Tn(ye,z.fields)===z.digest?U.nothingToMask++:ne.push(z.id)}let re=new Set(ke.map(z=>z.id)),H=(A.unconfirmed??[]).filter(z=>!re.has(z.id));H.length>0?A.unconfirmed=H:delete A.unconfirmed,A.refused.push(...ne)}if(G||pe())break;let Ln=[...A.refused];for(let Z=0;Z<Ln.length;Z+=Xe){if(F.signal.aborted){G=!0;break}if(pe())break;let ke=Ln.slice(Z,Z+Xe),$e=await mt(ce,`SELECT ${Pe} FROM ${x} WHERE Id IN (${ke.map(re=>`'${re}'`).join(", ")})`);ge(`dataops:anonymize query ${x}`),U.total-=ke.length-$e.length;let Le=[];if(await pt($e,(re,H)=>Le.push(...H),(re,H)=>{let z=new Set(H.map(ye=>ye.id));A.refused=A.refused.filter(ye=>!z.has(ye)),A.unconfirmed=[...A.unconfirmed??[],...H]}))break;let ne=new Set(ke);A.refused=[...A.refused.filter(re=>!ne.has(re)),...Le]}if(G||pe())break;if(A.done){U.done=!0;continue}let Gt=A.afterId;for(;;){if(F.signal.aborted){G=!0;break}if(pe())break;let Z=await to(ce,x,Pe,Ht,Gt,C);if(ge(`dataops:anonymize query ${x}`),Z.records.length===0){U.done=!0,A.done=!0;break}let ke=Z.truncated?Zo(Z.records,Gt,x):void 0;if(F.signal.aborted){G=!0;break}let $e=Ae=>{let ne=Ae[Ae.length-1]?.Id;typeof ne=="string"&&_t.test(ne)&&(A.afterId=ne)};if(await pt(Z.records,(Ae,ne)=>{A.refused.push(...ne),$e(Ae)},(Ae,ne)=>{A.unconfirmed=[...A.unconfirmed??[],...ne],$e(Ae)}))break;if(ke===void 0){U.done=!0,A.done=!0;break}Gt=ke,A.afterId=ke}if(G||pe())break}let Oe=pe(),_=qo(f,G),{recordsProcessed:ue,recordsFailed:ie,recordsNotMasked:te}=Rt(f),et=Zr(f);$=!1,oe(this.deps,{...l,...Xo(f,_,G),objects:eo(f)});let J=Ve();if(te>0){let m=G?"cancelled":Oe?`stopped at ${Oe.usagePercent}% of the org's API requests`:"refused by the org";this.deps.log(`[WARN] dataops:anonymize ${t} ${m}: ${te} record(s) not masked \u2014 ${et}`)}await d();let we=await q();G?(this.deps.infraServices?.backgroundRegistry?.abort(t),xe(this.deps,t,{aborted:!0,totalProcessed:ue,totalFailed:ie,totalNotMasked:te}),S?.cancel()):(xe(this.deps,t,{status:_,totalProcessed:ue,totalFailed:ie,totalNotMasked:te}),_==="failure"?S?.fail(`The org refused the ${ie} record(s)`):_==="partial"?S?.partial():S?.complete());let ze=`${te} still hold their original values (${et})`,tt=G?`Anonymization cancelled: ${ue} masked before the cancel \u2014 ${ze}.`:Oe?`Anonymization stopped at ${Oe.usagePercent}% of the org's daily API requests (${Oe.apiUsage} of ${Oe.apiLimit}): ${ue} masked \u2014 ${ze}. ${J?"Resume it":"Run it again"} once the org has requests to spare.`:ie===0?`Anonymization ${_==="success"?"completed":_}: ${ue} records processed.`:`Anonymization ${_}: ${ue} masked, ${ie} rejected by the org \u2014 those records still hold their original values.`,Kt=J&&te>0?" Resume masks only what this run left.":"",zn=ht(we,this.orgNameOf(e.orgId)),ao=tt+Kt+(zn?` ${zn}`:"");c.ended({templateId:e.templateId,status:_,recordsProcessed:ue,recordsFailed:ie,recordsNotMasked:te,objects:Yr(f),message:ao,errors:Ye,...G?{cancelled:!0}:{},...Oe?{stoppedAtApiLimit:!0}:{},...K?{snapshot:K}:{},...o?{mutedAutomation:o.outcome}:{},...we?{duplicates:we}:{}})}catch(T){await d();let D=await q().catch(()=>{});Qe(T,!0,D)}finally{let T=await d();if(T&&c.muted?.(T),$){let D=f.some(ee=>ee.masked>0);oe(this.deps,{...l,outcome:D?"partial":"failure",objects:g?eo(f):[]})}O&&!B&&Ve(),P(E),L?.release(),r?.removeEventListener("abort",fe),i.answer?.(T)}}handleAnonymizationTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.listedTemplates(),n=se(this.deps,e,"dataops:anonymization-templates:response",{templates:t});this.deps.broker.postToWebview(n),this.deps.log("[TX] dataops:anonymization-templates:response")}listedTemplates(){return[...kt,...this.savedTemplates.list()]}async handleBackupObjects(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(Yn,e,"dataops:error",this.deps);if(!t)return;let n=t.templateId!==void 0?this.findTemplate(t.templateId):void 0;if(t.templateId!==void 0&&!n){this.refuseUnknownTemplate("backup:objects",e,t.templateId);return}try{let r,o=()=>r??=Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager).then(d=>Nn(d,this.deps.log)),i=[];for(let d of n?[n]:this.listedTemplates()){let c=At({},d,W)&&await o();for(let p of Bt({},d,c))p!==""&&p!=="*"&&!i.includes(p)&&i.push(p)}let a=se(this.deps,e,"backup:objects:response",{objects:i});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} objects=${i.length}`)}catch(r){M(this.deps,"backup:objects","dataops:error",e,r)}}async plannedObjectsIn(e,t,n){let r=At(t,n,W)&&await Nn(e,this.deps.log);return Bt(t,n,r)}async handleAnonymizeCoverage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(or,e,"dataops:error",this.deps);if(!t)return;let n=this.findTemplate(t.templateId);if(!n){this.refuseUnknownTemplate("dataops:anonymize:coverage",e,t.templateId);return}try{let r=this.latestBackup(t.orgId),o=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),i=[],a=await this.plannedObjectsIn(o,t,n);for(let p of a){if(!Gr(n,p))continue;let u=De(p),b=null;try{b=await this.countRows(o,u,void 0,Sn(t,n,p))}catch(f){this.deps.log(`[WARN] dataops:anonymize:coverage: ${u} not counted: ${R(f)}`)}let l=r?.objects.find(f=>f.objectApiName.toLowerCase()===u.toLowerCase());i.push({objectApiName:u,count:b,backedUp:l?.recordCount??0,truncated:l?.truncated===!0,...l?.stoppedAt?{stoppedAt:l.stoppedAt}:{}})}let d=new ot(this.deps.configStore).load(t.orgId,t.templateId,Lt(n.rules,a,En(t))),c=se(this.deps,e,"dataops:anonymize:coverage:response",{templateId:t.templateId,...r?{backup:{operationId:r.operationId,timestamp:r.timestamp}}:{},objects:i,...d?{checkpoint:{id:d.id,savedAt:d.savedAt}}:{}});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id} objects=${i.length}`)}catch(r){M(this.deps,"dataops:anonymize:coverage","dataops:error",e,r)}}async handleAnonymizePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(sr,e,"dataops:error",this.deps);if(!t)return;let n=this.findTemplate(t.templateId);if(!n){this.refuseUnknownTemplate("dataops:anonymize:preview",e,t.templateId);return}try{let r=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),{AnonymizationEngine:o}=await import("./chunk-TLH7AD35.mjs"),i=new o(void 0,this.maskingKey),a=[],d=[],c=Hr(r);for(let u of await this.plannedObjectsIn(r,t,n)){if(!Gr(n,u))continue;let b=De(u);try{let l=Ft(n,u),f=Cn(n,u),{rules:h,select:w,missing:v,rulesOf:g}=await this.maskedFields(c,b,this.maskingRules(u,l),this.maskingRules(u,f)),$=await to(r,b,w,Vr,void 0,Sn(t,n,u));Be(r.limitInfo,`dataops:anonymize:preview ${b}`);let O=$.records.length>0;O&&d.push(...v.map(P=>({objectApiName:b,fieldApiName:P})));let[B]=O?await Kr(c,[{objectApiName:b,rules:[...l,...f]}]):[],Y=$.records.map(g),K=$.records.map((P,E)=>i.anonymize([P],Y[E])[0]),F=h.map(P=>P.fieldApiName).filter((P,E,S)=>P!=="Id"&&S.indexOf(P)===E);a.push({objectApiName:b,fields:F,...O&&h.length===0?{notCovered:!0}:{},...B?{writeDenied:{deniedFields:[...B.deniedFields]}}:{},methods:Object.fromEntries(h.map(P=>[P.fieldApiName,P.method])),rows:$.records.slice(0,Vr).map((P,E)=>{let S={},j={},q=new Set(Y[E].map(L=>L.fieldApiName));for(let L of F)S[L]=Jr(P[L]),j[L]=cn(P[L])&&q.has(L)?Jr(K[E][L]):S[L];return{id:String(P.Id??""),before:S,after:j}})})}catch(l){let f=R(l);this.deps.log(`[WARN] dataops:anonymize:preview: ${b} not read: ${f}`),a.push({objectApiName:b,fields:[],rows:[],error:f})}}let p=se(this.deps,e,"dataops:anonymize:preview:response",{templateId:t.templateId,objects:a,fieldsNotFound:d});this.deps.broker.postToWebview(p),this.deps.log(`[TX] ${p.type} id=${p.id} objects=${a.length}`)}catch(r){M(this.deps,"dataops:anonymize:preview","dataops:error",e,r)}}latestBackup(e){let t;for(let n of this.deps.configStore.getKeysByPrefix("backup:")){let r=n.slice(7);if(r.includes(":"))continue;let o=this.deps.configStore.get(n);if(o?.orgId!==e)continue;let i=o.timestamp??"";t&&t.timestamp.localeCompare(i)>=0||(t={operationId:r,timestamp:i,objects:o.objects??[]})}return t}async handleQualityScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(cr,e,"dataops:error",this.deps);if(t)try{let n=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),r=await pr({describe:i=>n.describe(i),query:async i=>{let a=await n.query(i);return Be(n.limitInfo,"dataops:quality-scan"),{totalSize:a.totalSize,records:a.records}}},t),o=se(this.deps,e,"dataops:quality-scan:response",{...r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} objects=${r.objects.length}`)}catch(n){M(this.deps,"dataops:quality-scan","dataops:error",e,n)}}handleTemplateSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(ir,e,"dataops:error",this.deps);if(t)try{let n=t.name.trim();if([...kt,...this.savedTemplates.list()].some(a=>a.name.trim().toLowerCase()===n.toLowerCase())){M(this.deps,"dataops:anonymization-template:save","dataops:error",e,new Error(`A template named "${n}" already exists. Pick another name.`),{code:"DUPLICATE_NAME"});return}let o={id:`tpl-saved-${crypto.randomUUID()}`,name:n,description:"",complianceFramework:"custom",rules:t.rules.map(a=>({...a,description:""})),saved:!0,createdAt:new Date().toISOString()};this.savedTemplates.save(o);let i=se(this.deps,e,"dataops:anonymization-template:save:response",{template:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){M(this.deps,"dataops:anonymization-template:save","dataops:error",e,n)}}handleTemplateDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(ar,e,"dataops:error",this.deps);if(!t)return;let{templateId:n}=t;if(kt.some(r=>r.id===n)){M(this.deps,"dataops:anonymization-template:delete","dataops:error",e,new Error(`Template "${n}" ships with SandForge and cannot be deleted.`),{code:"BUILT_IN"});return}try{let r=this.savedTemplates.delete(n),o=se(this.deps,e,"dataops:anonymization-template:delete:response",{templateId:n,deleted:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(r){M(this.deps,"dataops:anonymization-template:delete","dataops:error",e,r)}}async handlePIIScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(dr,e,"dataops:error",this.deps);if(!t)return;let{orgId:n,objectNames:r}=t;try{if(!this.deps.infraServices?.piiDetector)throw new Error("PII Detector not available.");let o=await Re(n,this.deps.orgRegistry,this.deps.orgManager),i=await Promise.all(r.map(async d=>{let c=De(d),p=await o.describe(c);Be(o.limitInfo,`precheck:pii-scan describe ${c}`);let u=p.fields.map(l=>({apiName:l.name,label:l.label,type:l.type,length:l.length})),b=this.deps.infraServices.piiDetector.detectPII(d,u);return{objectName:d,piiFields:b.piiFields.map(l=>({fieldName:l.fieldApiName,piiType:l.classification,confidence:l.confidence}))}})),a=se(this.deps,e,"precheck:pii-scan:response",{success:!0,results:i});this.deps.broker.postToWebview(a)}catch(o){this.deps.log(`[ERR] precheck:pii-scan: ${R(o)}`);let i=se(this.deps,e,"precheck:pii-scan:response",{success:!1,error:R(o)});this.deps.broker.postToWebview(i)}}};export{kt as a,Et as b,kn as c,yn as d,zt as e,wn as f,Dt as g,xt as h,Br as i,ro as j};