sandforge 0.0.0-stage → 1.79.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +54 -2
  3. package/THIRD-PARTY-NOTICES.md +1624 -0
  4. package/bin/sandforge-autopilot.mjs +12 -0
  5. package/bin/sandforge-backup.mjs +12 -0
  6. package/bin/sandforge-checkpoint.mjs +12 -0
  7. package/bin/sandforge-cleanup.mjs +12 -0
  8. package/bin/sandforge-clone.mjs +12 -0
  9. package/bin/sandforge-compare.mjs +12 -0
  10. package/bin/sandforge-dataops.mjs +12 -0
  11. package/bin/sandforge-empty.mjs +12 -0
  12. package/bin/sandforge-env.mjs +12 -0
  13. package/bin/sandforge-frozen.mjs +12 -0
  14. package/bin/sandforge-mcp.mjs +12 -0
  15. package/bin/sandforge-monitor.mjs +12 -0
  16. package/bin/sandforge-seed.mjs +12 -0
  17. package/bin/sandforge-sync.mjs +12 -0
  18. package/bin/sandforge.mjs +12 -0
  19. package/lib/catalogue.en.json +1 -0
  20. package/lib/chunk-2BVTCNWA.mjs +7 -0
  21. package/lib/chunk-2S5OMIIA.mjs +7 -0
  22. package/lib/chunk-2YIV2OB2.mjs +7 -0
  23. package/lib/chunk-342FN7AO.mjs +9 -0
  24. package/lib/chunk-36U7IQ6Y.mjs +25 -0
  25. package/lib/chunk-3CA767QB.mjs +7 -0
  26. package/lib/chunk-3DCUADVK.mjs +7 -0
  27. package/lib/chunk-3F5YMM2F.mjs +7 -0
  28. package/lib/chunk-3OHPD72J.mjs +9 -0
  29. package/lib/chunk-3RYLICRX.mjs +7 -0
  30. package/lib/chunk-3SRXFZSD.mjs +7 -0
  31. package/lib/chunk-42RER7V4.mjs +14 -0
  32. package/lib/chunk-4GL773D5.mjs +7 -0
  33. package/lib/chunk-4HFRHFGQ.mjs +7 -0
  34. package/lib/chunk-4HW535YJ.mjs +7 -0
  35. package/lib/chunk-4NAHW2D3.mjs +7 -0
  36. package/lib/chunk-4SNDMJP2.mjs +7 -0
  37. package/lib/chunk-4TLYUZD5.mjs +7 -0
  38. package/lib/chunk-4U6NXJNL.mjs +7 -0
  39. package/lib/chunk-4XZ5YT5O.mjs +7 -0
  40. package/lib/chunk-55HEMHEG.mjs +7 -0
  41. package/lib/chunk-57VHUYNG.mjs +10 -0
  42. package/lib/chunk-5AJRHRXA.mjs +20 -0
  43. package/lib/chunk-5CD257T7.mjs +7 -0
  44. package/lib/chunk-5HMAPZBV.mjs +7 -0
  45. package/lib/chunk-5LFSFYFJ.mjs +7 -0
  46. package/lib/chunk-5MMXFWPD.mjs +7 -0
  47. package/lib/chunk-5O6JOMHS.mjs +13 -0
  48. package/lib/chunk-5P4PHJRL.mjs +9 -0
  49. package/lib/chunk-5QKTYCWE.mjs +11 -0
  50. package/lib/chunk-66NMFCWX.mjs +7 -0
  51. package/lib/chunk-6EBMEGZB.mjs +7 -0
  52. package/lib/chunk-6LAXTAVN.mjs +7 -0
  53. package/lib/chunk-6MUEPV7M.mjs +9 -0
  54. package/lib/chunk-6QSM2WIH.mjs +10 -0
  55. package/lib/chunk-75ADZS6B.mjs +7 -0
  56. package/lib/chunk-7EANH5PY.mjs +68 -0
  57. package/lib/chunk-7F54PZUS.mjs +7 -0
  58. package/lib/chunk-7UQD6V6F.mjs +7 -0
  59. package/lib/chunk-AAVJ5XVX.mjs +7 -0
  60. package/lib/chunk-ALJVEUUS.mjs +7 -0
  61. package/lib/chunk-ALUFROGA.mjs +7 -0
  62. package/lib/chunk-AR7BE5O2.mjs +7 -0
  63. package/lib/chunk-AUTM6H6Z.mjs +7 -0
  64. package/lib/chunk-AV5SWEHP.mjs +9 -0
  65. package/lib/chunk-B45CNPUX.mjs +47 -0
  66. package/lib/chunk-BILZ3SSR.mjs +7 -0
  67. package/lib/chunk-BN7A4GRQ.mjs +7 -0
  68. package/lib/chunk-BOGNK4LV.mjs +7 -0
  69. package/lib/chunk-BS5T3MOQ.mjs +7 -0
  70. package/lib/chunk-BZ24IAP5.mjs +7 -0
  71. package/lib/chunk-CA5NAXSU.mjs +7 -0
  72. package/lib/chunk-CE6ZDGBB.mjs +7 -0
  73. package/lib/chunk-CGWXQX75.mjs +7 -0
  74. package/lib/chunk-CHCHAE4B.mjs +7 -0
  75. package/lib/chunk-D3QRXG63.mjs +787 -0
  76. package/lib/chunk-DBFJB2B6.mjs +7 -0
  77. package/lib/chunk-DLDX6RRC.mjs +7 -0
  78. package/lib/chunk-EADHKH3A.mjs +7 -0
  79. package/lib/chunk-EEVVGGM6.mjs +7 -0
  80. package/lib/chunk-ENLBYECD.mjs +7 -0
  81. package/lib/chunk-EQF2IJS2.mjs +11 -0
  82. package/lib/chunk-EQOQASDQ.mjs +7 -0
  83. package/lib/chunk-F2424IKX.mjs +7 -0
  84. package/lib/chunk-F74IHMGL.mjs +7 -0
  85. package/lib/chunk-FOVVHGEP.mjs +7 -0
  86. package/lib/chunk-FQBRBBY4.mjs +7 -0
  87. package/lib/chunk-FQGHL7GR.mjs +259 -0
  88. package/lib/chunk-GAM726CK.mjs +7 -0
  89. package/lib/chunk-GCOB7K5N.mjs +7 -0
  90. package/lib/chunk-GMY5427L.mjs +7 -0
  91. package/lib/chunk-GNC27UEU.mjs +7 -0
  92. package/lib/chunk-H2PJNIYJ.mjs +7 -0
  93. package/lib/chunk-H45UXY6G.mjs +7 -0
  94. package/lib/chunk-HCIDVIOW.mjs +7 -0
  95. package/lib/chunk-HF6LAK3G.mjs +7 -0
  96. package/lib/chunk-HJC7AIBK.mjs +7 -0
  97. package/lib/chunk-HJKM3E56.mjs +7 -0
  98. package/lib/chunk-HTJ5OGP5.mjs +7 -0
  99. package/lib/chunk-HUMEKZT5.mjs +8 -0
  100. package/lib/chunk-HV2MXMGI.mjs +7 -0
  101. package/lib/chunk-HXS7ORUF.mjs +11 -0
  102. package/lib/chunk-I3JKJTLO.mjs +110 -0
  103. package/lib/chunk-I7O6C2B5.mjs +8 -0
  104. package/lib/chunk-IAZB4WIL.mjs +7 -0
  105. package/lib/chunk-IC2C2GOF.mjs +8 -0
  106. package/lib/chunk-IEYG5ATY.mjs +7 -0
  107. package/lib/chunk-INIQ23K6.mjs +7 -0
  108. package/lib/chunk-INIT2UKJ.mjs +7 -0
  109. package/lib/chunk-J7HVXMSW.mjs +7 -0
  110. package/lib/chunk-JVL444U5.mjs +7 -0
  111. package/lib/chunk-K22PA4XL.mjs +7 -0
  112. package/lib/chunk-K2FBZIXY.mjs +7 -0
  113. package/lib/chunk-KLX67VPL.mjs +7 -0
  114. package/lib/chunk-L776PUMV.mjs +7 -0
  115. package/lib/chunk-LQ4DRFUH.mjs +9 -0
  116. package/lib/chunk-LRFAIUN7.mjs +7 -0
  117. package/lib/chunk-LV6G4XTK.mjs +7 -0
  118. package/lib/chunk-M6P5ZZLE.mjs +7 -0
  119. package/lib/chunk-MTMH6H2A.mjs +8 -0
  120. package/lib/chunk-MYTIL2JD.mjs +10 -0
  121. package/lib/chunk-NEVXIGR6.mjs +10 -0
  122. package/lib/chunk-NGSMZZDA.mjs +7 -0
  123. package/lib/chunk-NHWE66K5.mjs +7 -0
  124. package/lib/chunk-NM4MDLK4.mjs +7 -0
  125. package/lib/chunk-NTDN2JQZ.mjs +19 -0
  126. package/lib/chunk-NTOVCTRS.mjs +7 -0
  127. package/lib/chunk-NZ5ZZLKS.mjs +7 -0
  128. package/lib/chunk-OQOZAPCI.mjs +7 -0
  129. package/lib/chunk-OTWRDD6L.mjs +7 -0
  130. package/lib/chunk-P2PJYWGQ.mjs +7 -0
  131. package/lib/chunk-P42X3B4D.mjs +7 -0
  132. package/lib/chunk-P7GSGFJO.mjs +7 -0
  133. package/lib/chunk-PA3MKJVH.mjs +7 -0
  134. package/lib/chunk-PBI4BYWW.mjs +7 -0
  135. package/lib/chunk-PNCONNFJ.mjs +10 -0
  136. package/lib/chunk-PTTHSSQO.mjs +7 -0
  137. package/lib/chunk-PUOX4NBJ.mjs +8 -0
  138. package/lib/chunk-PZTSVQSF.mjs +7 -0
  139. package/lib/chunk-QPF6C5MX.mjs +7 -0
  140. package/lib/chunk-QQZZMKU3.mjs +7 -0
  141. package/lib/chunk-QROPNEGY.mjs +14 -0
  142. package/lib/chunk-QRV2OSIS.mjs +7 -0
  143. package/lib/chunk-QSRAEUGZ.mjs +7 -0
  144. package/lib/chunk-QWT2C74M.mjs +7 -0
  145. package/lib/chunk-RAAANPPG.mjs +7 -0
  146. package/lib/chunk-RACDTRZA.mjs +7 -0
  147. package/lib/chunk-RFEO2KAN.mjs +7 -0
  148. package/lib/chunk-RH3N2H7P.mjs +7 -0
  149. package/lib/chunk-RSWDYIHY.mjs +37 -0
  150. package/lib/chunk-RSYICMZG.mjs +8 -0
  151. package/lib/chunk-SAR5622P.mjs +7 -0
  152. package/lib/chunk-SBIMVCXT.mjs +101 -0
  153. package/lib/chunk-SCKUIE3R.mjs +7 -0
  154. package/lib/chunk-SFURUNJM.mjs +7 -0
  155. package/lib/chunk-SIOZXPFG.mjs +7 -0
  156. package/lib/chunk-SRPWW4A2.mjs +10 -0
  157. package/lib/chunk-SRQDABQ2.mjs +15 -0
  158. package/lib/chunk-SVS6UMDU.mjs +323 -0
  159. package/lib/chunk-T63U4OZJ.mjs +7 -0
  160. package/lib/chunk-TBZMC2VV.mjs +11 -0
  161. package/lib/chunk-TEOLMRDO.mjs +7 -0
  162. package/lib/chunk-TLH7AD35.mjs +7 -0
  163. package/lib/chunk-TNXUU6W7.mjs +14 -0
  164. package/lib/chunk-TQX3PURV.mjs +7 -0
  165. package/lib/chunk-TUACWKIH.mjs +7 -0
  166. package/lib/chunk-TW3N6W5Z.mjs +7 -0
  167. package/lib/chunk-TYYOBZMU.mjs +10 -0
  168. package/lib/chunk-TZE3Y7IQ.mjs +7 -0
  169. package/lib/chunk-UNDIBZWG.mjs +7 -0
  170. package/lib/chunk-VGW4MXXZ.mjs +7 -0
  171. package/lib/chunk-VHI54FBK.mjs +441 -0
  172. package/lib/chunk-VXHDBYMI.mjs +7 -0
  173. package/lib/chunk-W7KFAY55.mjs +7 -0
  174. package/lib/chunk-WFEB5X4U.mjs +8 -0
  175. package/lib/chunk-WIO4XO4F.mjs +7 -0
  176. package/lib/chunk-WJY54JO7.mjs +13 -0
  177. package/lib/chunk-WR2GIKWE.mjs +7 -0
  178. package/lib/chunk-WRU5FJFC.mjs +7 -0
  179. package/lib/chunk-X2PY6MWZ.mjs +7 -0
  180. package/lib/chunk-X65MT4W3.mjs +7 -0
  181. package/lib/chunk-XBG5SP6Q.mjs +7 -0
  182. package/lib/chunk-XCA5AONB.mjs +7 -0
  183. package/lib/chunk-XEFDB2R4.mjs +7 -0
  184. package/lib/chunk-XETCPL7E.mjs +7 -0
  185. package/lib/chunk-Y5CGXLUB.mjs +7 -0
  186. package/lib/chunk-Y6J6QFI2.mjs +7 -0
  187. package/lib/chunk-YAZO75G2.mjs +8 -0
  188. package/lib/chunk-YBU4Z4QV.mjs +7 -0
  189. package/lib/chunk-YMJVMFPY.mjs +7 -0
  190. package/lib/chunk-YPSRZRIT.mjs +7 -0
  191. package/lib/chunk-YS4G22C2.mjs +7 -0
  192. package/lib/chunk-YW2SBL4Z.mjs +7 -0
  193. package/lib/chunk-YYZL7UGV.mjs +7 -0
  194. package/lib/chunk-Z7X534S4.mjs +10 -0
  195. package/lib/chunk-ZE6HKRR4.mjs +9 -0
  196. package/lib/chunk-ZHJP7L3K.mjs +7 -0
  197. package/lib/chunk-ZJKCWBRJ.mjs +7 -0
  198. package/lib/chunk-ZLZRU6MO.mjs +7 -0
  199. package/lib/chunk-ZOVSMN5C.mjs +7 -0
  200. package/lib/chunk-ZPYJPGDK.mjs +7 -0
  201. package/lib/chunk-ZQOZ4EFW.mjs +7 -0
  202. package/lib/chunk-ZUTYVST5.mjs +7 -0
  203. package/lib/chunk-ZXH4MBWP.mjs +7 -0
  204. package/lib/chunk-ZYEE34WO.mjs +7 -0
  205. package/lib/sandforge-autopilot.mjs +157 -0
  206. package/lib/sandforge-backup.mjs +99 -0
  207. package/lib/sandforge-checkpoint.mjs +353 -0
  208. package/lib/sandforge-cleanup.mjs +56 -0
  209. package/lib/sandforge-clone.mjs +7 -0
  210. package/lib/sandforge-compare.mjs +54 -0
  211. package/lib/sandforge-dataops.mjs +7 -0
  212. package/lib/sandforge-empty.mjs +140 -0
  213. package/lib/sandforge-env.mjs +355 -0
  214. package/lib/sandforge-frozen.mjs +263 -0
  215. package/lib/sandforge-mcp.mjs +40 -0
  216. package/lib/sandforge-monitor.mjs +43 -0
  217. package/lib/sandforge-seed.mjs +7 -0
  218. package/lib/sandforge-sync.mjs +7 -0
  219. package/lib/sandforge.mjs +28 -0
  220. package/package.json +52 -4
@@ -0,0 +1,14 @@
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 Kb,b as pa,c as Yb,d as Qb}from"./chunk-IC2C2GOF.mjs";import{b as Cy}from"./chunk-VGW4MXXZ.mjs";import{a as yl,b as Ny,c as $y,d as _i,e as gs}from"./chunk-JVL444U5.mjs";import{a as _y}from"./chunk-KLX67VPL.mjs";import{c as Ly,d as Fy}from"./chunk-5CD257T7.mjs";import{c as Zb,l as eR}from"./chunk-5AJRHRXA.mjs";import{a as ww,d as Iw,e as Aw,f as ms,g as go,h as Tl,i as Vi,j as Tw,k as Ew,l as Pw,m as Cw}from"./chunk-LRFAIUN7.mjs";import{a as lb,b as $l,c as Ub,d as Hb,e as Bb,h as qb,i as Wb,j as zb,m as Gb,n as Jb,o as la,p as Ll,q as ua,r as Vb}from"./chunk-OQOZAPCI.mjs";import{b as Fb,e as _b}from"./chunk-RSYICMZG.mjs";import{A as kb,B as Ob,C as Ib,D as da,E as ca,F as an,G as Ab,J as Tb,K as Eb,L as Pb,M as Cb,N as Db,P as Nl,Q as xb,R as Mb,S as jb,X as Nb,Z as $b,_ as Lb,a as Qi,c as Zi,d as ea,e as ub,i as pb,j as gb,k as Pt,m as ta,n as ra,o as jr,p as wo,q as bo,r as Ro,s as fb,t as hb,u as mb,v as na,w as oa,x as sa,y as yb,z as Sb}from"./chunk-XEFDB2R4.mjs";import{b as ia,g as aa}from"./chunk-H45UXY6G.mjs";import{e as ur,g as wb,i as bb,k as Rb,l as vo,m as vb}from"./chunk-WRU5FJFC.mjs";import{a as Xb}from"./chunk-4GL773D5.mjs";import{a as Jg,b as hi,c as dl,d as cl,e as ny,g as Qr,h as Jt,i as Py,j as Dy}from"./chunk-SRQDABQ2.mjs";import{a as xt}from"./chunk-LV6G4XTK.mjs";import{a as my,b as yy}from"./chunk-XCA5AONB.mjs";import{a as Di,b as oy,c as sy,d as iy,e as ls,f as ay,g as dy,h as cy,j as ly}from"./chunk-WR2GIKWE.mjs";import{$ as $f,$b as om,A as ff,Ab as xh,B as kn,Bb as Mh,Bc as Ke,C as el,Ca as Xf,Cb as jh,Cc as us,D as hf,Da as Kf,Db as Nh,Dc as wy,E as mf,Ea as Yf,Eb as $h,Ec as by,F as yi,Fa as Qf,Fb as Lh,G as yf,Ga as Zf,Gb as bi,H as wf,Ha as eh,Hb as Fh,I as bf,Ia as th,Ib as _h,J as Rf,Ja as rh,Jb as Uh,K as vf,Ka as nh,Kb as Hh,L as Sf,La as oh,Lb as Bh,M as tl,Ma as sh,Mb as qh,N as kf,Na as ih,Nb as Wh,O as Of,Oa as ah,Ob as zh,P as If,Pa as Pr,Pb as Gh,Q as Af,Qa as dh,Qb as Jh,R as Tf,Ra as il,Rb as Vh,S as Ef,Sa as wi,Sb as Xh,T as Pf,Ta as ns,Tb as Kh,U as Cf,Ua as ch,Ub as Yh,V as Df,Va as lh,Vb as Qh,W as xf,Wb as Zh,X as Mf,Xb as em,Y as jf,Yb as tm,Z as Nf,Zb as rm,_ as ro,_b as nm,a as Tr,aa as Lf,ac as sm,b as ve,ba as Ff,bc as im,c as gi,ca as _f,cc as am,d as St,da as rl,dc as dm,e as Jr,ea as Uf,ec as cm,f as to,fa as Hf,fb as uh,fc as lm,g as st,ga as Bf,gb as ph,gc as um,h as nr,ha as qf,hb as gh,hc as pm,i as Sn,ia as Wf,ib as fh,ic as gm,j as A,ja as zf,jb as hh,jc as fm,k as Oe,ka as Gf,kb as mh,kc as al,l as We,la as Jf,lb as yh,lc as hm,m as $e,ma as Vf,mb as wh,mc as mm,n as pe,na as nl,nb as bh,nc as ym,o as P,oa as ol,ob as Rh,oc as wm,p as fi,pa as sl,pb as vh,pc as bm,q as Qo,qb as Sh,qc as Rm,r as Er,rb as kh,rc as vm,s as Le,sb as Oh,sc as Sm,t as cf,tb as Ih,tc as km,u as lf,ub as Ah,uc as D,v as uf,vb as Th,w as pf,wb as Eh,wc as Ci,x as mi,xb as Ph,yb as Ch,z as gf,zb as Dh}from"./chunk-YMJVMFPY.mjs";import{g as Pi}from"./chunk-ALJVEUUS.mjs";import{a as At,b as ts,c as Yg,d as Qg}from"./chunk-CE6ZDGBB.mjs";import{a as Ry,b as vy,c as Sy,d as ky,e as Oy,f as ji,g as ao,h as Pn,i as Dr,j as Zr,k as Ni}from"./chunk-4HFRHFGQ.mjs";import{b as En,c as Ey}from"./chunk-BOGNK4LV.mjs";import{$ as jw,Ab as rb,Bb as nb,Eb as ob,Fa as Pl,Fb as sb,Ga as Cl,Hb as jl,Ia as Dl,Ib as ib,Jb as ab,K as xw,Kb as db,Lb as cb,Ma as Ki,O as Mw,Oa as Bw,Pa as ys,Qa as qw,Sa as Ww,Ta as zw,Ua as Gw,Va as Jw,Wa as Vw,Ya as Xw,Za as Kw,_a as xl,a as di,ab as fo,b as Tg,cb as Yw,db as Yi,eb as Qw,g as gw,h as Al,ia as Nw,ja as $w,ka as Xi,la as El,m as fw,n as Ji,na as Lw,nb as Zw,o as hw,oa as Fw,p as mw,pa as _w,pb as ho,q as yw,qa as Uw,rb as eb,sa as Hw,sb as mo,tb as yo,x as Dw,xb as tb,yb as lr,zb as Ml}from"./chunk-36U7IQ6Y.mjs";import{h as bw}from"./chunk-XETCPL7E.mjs";import{a as Rw,b as vw,f as Sw,g as kw,h as Ow}from"./chunk-K2FBZIXY.mjs";import{a as Ym,b as no,c as oo,d as Yr,e as Qm,f as fl,i as uy,j as py,k as Mi,l as gy,m as fy,q as wl,r as fs,s as Cn,t as Bi}from"./chunk-Z7X534S4.mjs";import{B as Jm,C as zt,D as Ai,E as Ti,F as Ei,K as Vm,L as pl,M as gl,N as Gt,O as Xm,P as Km,Q as Kr,U as sr,V as Tn,a as Wg,b as Om,c as Im,d as Am,e as Wt,f as Tm,g as ll,h as Em,i as Pm,j as Cm,k as Dm,m as In,o as is,p as _m,pa as Ui,q as Um,s as Hm,t as Bm,ta as Hi,u as as,w as qm,x as Wm,y as zm,z as Gm}from"./chunk-6QSM2WIH.mjs";import{d as xi}from"./chunk-T63U4OZJ.mjs";import{H as jy,d as $i,h as Li,i as xy,k as My,x as Fi}from"./chunk-NEVXIGR6.mjs";import{b as Zm,f as ey,o as Tt,p as ds,q as hl,r as io,s as ml,t as cs,w as ty,x as ry}from"./chunk-NTDN2JQZ.mjs";import{a as hy}from"./chunk-YYZL7UGV.mjs";import{a as Oi,c as Ii}from"./chunk-SAR5622P.mjs";import{b as Ag}from"./chunk-L776PUMV.mjs";import{A as _t,b as Gc,d as wg,e as Jc,f as bg,g as Xo,h as Vc,i as Rg,j as vg,k as ai,l as Sg,m as Xc,n as kg,o as Og,p as Ig,q as B,r as Et,s as kt,u as Ay,v as Cr,w as Ty,y as mt,z as ps}from"./chunk-6MUEPV7M.mjs";import{B as rs,D as df,p as nf}from"./chunk-HJC7AIBK.mjs";import{a as Ri,b as Dt,c as On,d as os,e as vi,f as ss,g as Si,h as Vr,i as xm,j as ki,k as ul}from"./chunk-OTWRDD6L.mjs";import{a as De}from"./chunk-5LFSFYFJ.mjs";import{a as Qn,b as yg,c as ii}from"./chunk-RH3N2H7P.mjs";import{a as sf,d as af}from"./chunk-55HEMHEG.mjs";import{a as of}from"./chunk-P42X3B4D.mjs";import{a as so,d as An}from"./chunk-TUACWKIH.mjs";import{$ as Xy,A as Uy,Aa as nn,Ba as on,D as qi,E as Rl,F as Hy,G as By,H as qy,Ha as sn,I as Wy,Ia as hs,J as zy,K as dr,Ka as Sl,L as Xt,La as kl,Ma as Ol,Na as aw,O as en,Oa as dw,P as lo,Pa as cw,Q as Wi,Qa as Il,R as uo,S as tn,T as po,Ta as ct,U as zi,Ua as lw,Va as uw,W as Gi,Wa as pw,X as Gy,Y as Jy,Z as Vy,_ as rn,a as zg,b as eo,ba as vl,c as gt,d as Gg,e as X,ea as Ky,f as at,h as Vg,ha as Yy,i as Ze,ia as Qy,j as Xg,ja as Zy,k as Qc,ka as cr,l as Kg,m as Zo,n as Zc,o as ir,p as ge,pa as ew,q as Iy,r as Mt,ra as tw,s as jt,sa as rw,ta as nw,ua as ow,va as sw,w as Vt,x as Mr,ya as iw,z as bl}from"./chunk-VXHDBYMI.mjs";import{q as ar,r as xr,s as co}from"./chunk-ENLBYECD.mjs";import{c as Fg,f as pi,g as _g,j as Ug,l as Hg,r as Bg,s as qg}from"./chunk-PA3MKJVH.mjs";import{a as se}from"./chunk-4TLYUZD5.mjs";import{a as Ko}from"./chunk-ZLZRU6MO.mjs";import{b as Zg,e as ef,k as tf,m as rf}from"./chunk-WIO4XO4F.mjs";import{a as or}from"./chunk-EADHKH3A.mjs";import{i as es}from"./chunk-INIT2UKJ.mjs";import{e as Nm,h as Xr,k as $m,l as Lm,m as Fm}from"./chunk-PNCONNFJ.mjs";import{E as rr,F as Yo,M as Mg,O as jg,X as Ng,Y as $g,_ as Lg,a as ci,b as qt,c as li,e as Pg,i as Cg,l as ui,m as Yc,n as Dg,o as xg,p as Zn,q as tr}from"./chunk-CGWXQX75.mjs";import{a as Bt,d as Kc,f as Eg,h as He}from"./chunk-TZE3Y7IQ.mjs";import{f as Mm,j as jm}from"./chunk-SIOZXPFG.mjs";import{a as mg,b as T}from"./chunk-CA5NAXSU.mjs";import{$a as Bp,$b as kr,Ac as Qp,Ad as Vo,Bc as Wc,Bd as Ft,Cc as Zp,Cd as pg,D as Cp,Dc as eg,Dd as zc,Ec as ri,Ed as ni,Fc as tg,Fd as oi,Gd as gg,Hd as fg,Id as hg,Jd as si,Mc as rg,T as Dp,Tb as pt,Tc as Go,Ua as Fp,Vb as vn,Vc as Gr,Wb as Vp,X as xp,Xa as _p,Y as $c,Ya as Up,Yb as Ee,Z as Mp,Za as Hp,Zb as Yn,Zc as ng,_a as Ys,_b as Hc,a as bp,aa as Sr,ab as qp,b as Rp,ba as Ks,bb as Qs,bc as Re,bd as Ar,c as Ip,ca as jp,cd as ot,da as Lc,db as Wp,ea as Fc,eb as zp,fa as Np,fb as Gp,ga as _c,hc as Bc,ic as qo,id as og,j as Xn,jc as Wo,k as Kn,lb as Jp,lc as Xp,ma as $p,mb as Uc,mc as Kp,n as Wr,na as Lp,nd as sg,o as Ho,od as ig,p as Ap,pd as Jo,q as Tp,r as Ep,rc as Or,td as ag,uc as zo,ud as dg,vb as Zs,vc as ti,vd as cg,w as Pp,wc as qc,wd as lg,xb as ei,xc as zr,xd as ug,yc as Yp,zb as Bo,zc as Ir}from"./chunk-B45CNPUX.mjs";import{a as vp,b as L,e as Me,f as ze,i as Vn,k as ke,l as G,o as Sp,p as Vs,s as Xs,u as Xe,v as vt,x as kp,y as Op,z as Uo}from"./chunk-7EANH5PY.mjs";import{randomBytes as lI}from"node:crypto";import{createReadStream as uI}from"node:fs";import{open as pI,readdir as gI,rm as fI,stat as hI}from"node:fs/promises";import{homedir as mI}from"node:os";import{join as Kt,resolve as yI}from"node:path";import{createInterface as wI}from"node:readline";var Fl="journal.ndjson",ga=2e3,sR=/^em-\d{8}-\d{6}-[a-z0-9]{4}$/,tR="abcdefghijklmnopqrstuvwxyz0123456789";function Ul(s=new Date){let e=s.toISOString(),t=`${e.slice(0,4)}${e.slice(5,7)}${e.slice(8,10)}`,r=`${e.slice(11,13)}${e.slice(14,16)}${e.slice(17,19)}`,n=Array.from(lI(4),o=>tR[o%tR.length]).join("");return`em-${t}-${r}-${n}`}function _l(s){return sR.test(s)}function Hl(s=process.env){let e=s.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?yI(e):Kt(mI(),".sandforge");return Kt(t,"empty")}var bI=L().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),Nr=L().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Not an API name").max(80),ws=Uo.datetime({offset:!0}),rR=ke(bI).max(ga),iR=Xe(["success","partial","failure","cancelled"]),aR=G({v:vt(1),kind:vt("head"),runId:L().regex(sR),organizationId:L().min(15).max(18),orgName:L(),startedAt:ws,readAt:ws,previewId:L(),mode:Xe(["objects","org"]),deleteMode:Xe(["recycle","hard"]),request:G({mode:Xe(["objects","org"]),objects:ke(L()).optional(),excluded:ke(L()).optional(),customSettings:ze().optional(),files:ze().optional(),managedPackages:ze().optional(),unrestorable:ze().optional()}).strict(),passes:ke(G({objectApiName:Nr,records:Me().int().nonnegative().optional(),sent:Me().int().nonnegative().optional(),rows:L().max(200).optional()})),toDraftAlong:ke(G({objectApiName:Nr,condition:L().optional()})),beforeParent:ke(G({objectApiName:Nr,field:L(),parent:Nr,reason:Xe(["restricted","customPrices"])})),undoLost:ke(G({objectApiName:Nr,field:L().optional(),parent:Nr.optional(),reason:Xe(["restricted","unordered","notRestorable"]),records:Me().int().nonnegative().optional(),atLeast:vt(!0).optional()})).optional()}),RI=G({kind:vt("attempt"),at:ws,resumed:ze()}),dR=G({kind:vt("spooled"),objectApiName:Nr,place:Me().int().nonnegative(),count:Me().int().nonnegative(),sinceRead:ze()}),vI=G({kind:vt("settled"),objectApiName:Nr,deleted:rR,gone:rR}),SI=G({objectApiName:Nr,planned:Me().int().nonnegative(),deleted:Me().int().nonnegative(),gone:Me().int().nonnegative(),refused:Me().int().nonnegative(),notReached:Me().int().nonnegative().optional(),madeSince:Me().int().nonnegative().optional(),reasons:ke(L())}),cR=G({kind:vt("end"),at:ws,status:iR,hardRefused:L().optional(),passes:ke(SI)}),kI=G({kind:vt("undo"),at:ws,status:iR}),nR=Vs("kind",[aR,RI,dR,vI,cR,kI]),pr=class extends Error{constructor(e){super(e),this.name="EmptyJournalDamaged"}};function OI(s){return s==="success"||s==="partial"}var fa=class s{constructor(e,t){this.dir=e;this.head=t}dir;head;static async begin(e,t){let r=aR.parse({v:1,kind:"head",...t});await Fi(e);let n=new s(e,r);return await n.write(r,"wx"),n}static async open(e){let t;for await(let r of oR(Kt(e,Fl))){r.kind==="head"&&(t=r);break}if(t===void 0)throw new pr("The journal of this emptying names nothing it was to do.");return new s(e,t)}idsDirOf(e,t){return Kt(this.dir,"ids",`${e}-${pt(t)}`)}async write(e,t="a"){let r=Kt(this.dir,Fl),n=await pI(r,t,$i);try{await n.appendFile(`${JSON.stringify(e)}
8
+ `,"utf8"),await n.sync()}finally{await n.close()}}attempt(e,t){return this.write({kind:"attempt",at:t.toISOString(),resumed:e})}spooled(e){return this.write(dR.parse({kind:"spooled",...e}))}async settled(e,t,r){for(let n=0;n<Math.max(t.length,r.length);n+=ga)await this.write({kind:"settled",objectApiName:e,deleted:t.slice(n,n+ga),gone:r.slice(n,n+ga)})}ended(e,t,r,n){return this.write(cR.parse({kind:"end",at:r.toISOString(),status:e,...n!==void 0?{hardRefused:n}:{},passes:t}))}undone(e,t){return this.write({kind:"undo",at:t.toISOString(),status:e})}lines(){return oR(Kt(this.dir,Fl))}async state(){let e=0,t,r,n=!1,o=!1,i=new Map;for await(let a of this.lines())switch(a.kind){case"attempt":e++,r=void 0;break;case"spooled":i.set(a.objectApiName,a);break;case"settled":a.deleted.length>0&&(o=!0);break;case"end":t=a,r=a;break;case"undo":OI(a.status)&&(n=!0);break;default:break}return{head:this.head,attempts:e,...t?{lastEnd:t}:{},open:e>0&&!n&&(r===void 0||r.status==="cancelled"||r.status==="failure"&&o),undone:n,spooled:i,deletedAny:o}}async*settledOf(e){for await(let t of this.lines())t.kind==="settled"&&t.objectApiName===e&&(yield t)}};async function*oR(s){let e=uI(s,{encoding:"utf8"}),t=wI({input:e,crlfDelay:1/0}),r,n=0,o=(i,a)=>{try{return nR.parse(JSON.parse(i))}catch{throw new pr(`Line ${a} of the journal of this emptying does not read: the journal is not used.`)}};try{for await(let i of t)n++,i.trim()!==""&&(r&&(yield o(r.raw,r.number)),r={raw:i,number:n})}catch(i){throw i.code==="ENOENT"?new pr("The journal of this emptying is not on this machine."):i}finally{t.close(),e.destroy()}if(r)try{yield nR.parse(JSON.parse(r.raw))}catch{return}}var ha=class{constructor(e){this.root=e}root;orgDir(e){return Kt(this.root,My(e))}begin(e,t){return fa.begin(Kt(this.orgDir(e),t.runId),{...t,organizationId:e})}async runsOf(e){let t=this.orgDir(e),r;try{r=await gI(t)}catch(n){if(n.code==="ENOENT")return[];throw n}return r.filter(_l).sort().map(n=>({runId:n,dir:Kt(t,n)}))}async lastOf(e){return(await this.runsOf(e)).at(-1)}async open(e,t){if(!_l(t))throw new pr(`Not an emptying's id: ${t}`);let r=Kt(this.orgDir(e),t);try{await hI(r)}catch{throw new pr(`No journal of the emptying ${t} is on this machine.`)}return fa.open(r)}async remove(e,t){_l(t)&&await fI(Kt(this.orgDir(e),t),{recursive:!0,force:!0})}};import{randomUUID as YM}from"node:crypto";import{join as QM}from"node:path";var So=new Map,lR=(s,e)=>`${s}::${e}`;async function Ut(s,e,t,r=Date.now){let n=lR(s,e),o=So.get(n);if(o&&r()-o.at<3e5)return o.value;let i=t();So.set(n,{at:r(),value:i});try{return await i}catch(a){throw So.get(n)?.value===i&&So.delete(n),a}}function uR(s){let e=lR(s,"");for(let t of So.keys())t.startsWith(e)&&So.delete(t)}var II=G({orgId:L(),detectedAt:L(),evidence:Xe(["connection","monitor","production"]),previousOrganizationId:L().optional(),organizationId:L().optional(),previousInstanceName:L().optional(),instanceName:L().optional(),sandboxName:L().optional(),reportedBy:L().optional()}),AI=G({organizationId:L(),instanceName:L().optional(),formerOrganizationIds:ke(L()),refreshes:ke(II)}),pR="sandbox-refresh:",TI="sandbox-refresh",gR=10,EI=20,PI=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function Bl(s){return s!==void 0&&PI.test(s)?s.slice(0,15):void 0}function fR(s){try{return new URL(s).hostname.toLowerCase()}catch{return}}function CI(s){let e=fR(s.instanceUrl),t=".my.salesforce.com";return e?.endsWith(t)?e.slice(0,-t.length):void 0}function DI(s,e,t){let r=t.toLowerCase(),n=CI(s);return n&&fR(e.instanceUrl)?.startsWith(`${n}--${r}.`)?!0:e.username.toLowerCase()===`${s.username.toLowerCase()}.${r}`}var ma=class{constructor(e){this.deps=e;this.now=e.now??(()=>new Date)}deps;listeners=new Set;now;onRefreshDetected(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}observe(e,t,r){let n=this.deps.orgManager.getOrg(e);if(n?.orgType!=="Sandbox")return;let o=Bl(t.organizationId);if(!o)return;let i=this.read(e),a=i??this.baselineOf(n);if(!a){this.write(e,{organizationId:o,instanceName:t.instanceName,formerOrganizationIds:[],refreshes:[]});return}if(o===a.organizationId){let p=t.instanceName!==void 0&&t.instanceName!==a.instanceName;(!i||p)&&this.write(e,{...a,instanceName:t.instanceName??a.instanceName});return}if(a.formerOrganizationIds.includes(o))return;let[d,...c]=a.refreshes,l=d?.evidence==="production"&&d.organizationId===void 0?d:void 0,u={...l??{orgId:e,detectedAt:this.now().toISOString(),evidence:r},previousOrganizationId:a.organizationId,organizationId:o,previousInstanceName:a.instanceName,instanceName:t.instanceName};return this.write(e,{organizationId:o,instanceName:t.instanceName,formerOrganizationIds:[a.organizationId,...a.formerOrganizationIds].slice(0,EI),refreshes:(l?[u,...c]:[u,...a.refreshes]).slice(0,gR)}),this.deps.log?.(`[sandbox-refresh] ${n.alias}: org ${a.organizationId} is now ${o} (${r})`),l||this.emit(u),u}noteCompletedRefresh(e){let t=this.deps.orgManager.getOrg(e.orgId);if(!t)return[];let r=[];for(let n of this.deps.orgManager.getAllOrgs()){if(n.orgType!=="Sandbox"||n.id===t.id||!DI(t,n,e.sandboxName))continue;let o=this.read(n.id)??this.baselineOf(n);if(!o)continue;let i=Date.parse(e.refreshDate);if(o.refreshes.some(c=>c.evidence!=="production"&&Date.parse(c.detectedAt)>=i))continue;let d={orgId:n.id,detectedAt:this.now().toISOString(),evidence:"production",sandboxName:e.sandboxName,reportedBy:t.id};this.write(n.id,{...o,refreshes:[d,...o.refreshes].slice(0,gR)}),this.deps.log?.(`[sandbox-refresh] ${n.alias}: ${t.alias} reports the refresh of "${e.sandboxName}"`),r.push(d),this.emit(d)}return r}refreshesOf(e){return this.read(e)?.refreshes??[]}organizationIdOf(e){return this.read(e)?.organizationId}wasRefreshedTo(e,t){let r=Bl(t);return r!==void 0&&this.refreshesOf(e).some(n=>n.organizationId===r)}baselineOf(e){let t=Bl(e.orgId);return t===void 0?void 0:{organizationId:t,formerOrganizationIds:[],refreshes:[]}}read(e){let t=this.deps.configStore.get(`${pR}${e}`);if(t===void 0)return;let r=AI.safeParse(t);if(!r.success){this.deps.log?.(`[sandbox-refresh] ignoring an unreadable record for ${e}`);return}return r.data}write(e,t){this.deps.configStore.set(`${pR}${e}`,t,TI)}emit(e){for(let t of this.listeners)try{t(e)}catch(r){this.deps.log?.(`[sandbox-refresh] a listener failed: ${String(r)}`)}}};function dn(s){let e;try{e=new URL(s)}catch{return{ok:!1,reason:"invalid"}}return e.protocol!=="https:"?{ok:!1,reason:"not-https",protocol:e.protocol}:{ok:!0,url:e}}var xI=5,MI=5e3,jI=3e4,NI=G({device_code:L().min(1).max(4096),user_code:L().regex(/^[A-Za-z0-9-]{4,32}$/),verification_uri:L().min(1).max(2048),interval:Me().int().positive().max(300).optional(),expires_in:Me().int().positive().optional()}),$I=G({access_token:L().min(1),refresh_token:L().min(1).optional(),instance_url:L().min(1).max(2048)}),hR=G({error:L().min(1),error_description:L().optional()}),Dn=class extends Error{constructor(){super("Sign-in cancelled."),this.name="DeviceLoginCancelledError"}},ya=class extends Error{constructor(e){super(e),this.name="RefusedByHostError"}};function LI(s,e){return new Promise((t,r)=>{if(e?.aborted){r(new Dn);return}let n=()=>{clearTimeout(o),r(new Dn)},o=setTimeout(()=>{e?.removeEventListener("abort",n),t()},s);e?.addEventListener("abort",n,{once:!0})})}function yR(s){let e=dn(s);if(!(!e.ok||e.url.username!==""||e.url.password!=="")&&!(e.url.port!==""||!hg(e.url.hostname)))return e.url}function mR(s){return`Salesforce refused the device sign-in: ${s.error_description?`${s.error_description} (${s.error})`:s.error}`}var wa=class{fetchFn;now;sleep;constructor(e={}){this.fetchFn=e.fetch??((t,r)=>fetch(t,r)),this.now=e.now??Date.now,this.sleep=e.sleep??LI}async authorize(e,t,r){let n=await this.post(e,{response_type:"device_code",client_id:t},r),o=hR.safeParse(n);if(o.success)throw new Error(mR(o.data));let i=NI.safeParse(n);if(!i.success)throw new Error("Salesforce answered the device sign-in without a usable code.");let a=yR(i.data.verification_uri);if(!a)throw new Error("Salesforce sent a verification page that is not on a Salesforce host.");let d=Math.min((i.data.expires_in??Number.POSITIVE_INFINITY)*1e3,Tp);return{deviceCode:i.data.device_code,userCode:i.data.user_code,verificationUri:a.href,intervalMs:(i.data.interval??xI)*1e3,expiresAt:this.now()+d}}async awaitApproval(e,t,r,n){let o=r.intervalMs;for(;;){let i=r.expiresAt-this.now();if(i<=0||(await this.sleep(Math.min(o,i),n),this.now()>=r.expiresAt))break;let a;try{a=await this.post(e,{grant_type:"device",client_id:t,code:r.deviceCode},n)}catch(c){if(n?.aborted)throw new Dn;if(c instanceof ya)throw c;continue}let d=hR.safeParse(a);if(d.success){if(d.data.error==="authorization_pending")continue;if(d.data.error==="slow_down"){o+=MI;continue}throw new Error(mR(d.data))}return FI(a)}throw new Error("The code expired before it was approved. Start the sign-in again for a new one.")}async post(e,t,r){if(r?.aborted)throw new Dn;let n=AbortSignal.timeout(jI),o;try{o=await this.fetchFn(`${e}/services/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams(t).toString(),signal:r?AbortSignal.any([r,n]):n})}catch(a){throw r?.aborted?new Dn:a}let i=await o.text();try{return JSON.parse(i)}catch{throw new ya(`Salesforce answered HTTP ${o.status} with a page instead of JSON. Check the login URL.`)}}};function FI(s){let e=$I.safeParse(s);if(!e.success)throw new Error("Salesforce approved the sign-in without an access token and an instance URL.");if(!e.data.refresh_token)throw new Error('Salesforce signed you in without a refresh token, so the Salesforce CLI could not keep the session. Give the external client app the "Perform requests at any time (refresh_token, offline_access)" scope, then sign in again.');let t=yR(e.data.instance_url);if(!t||t.pathname!=="/"||t.search!==""||t.hash!=="")throw new Error("Salesforce approved the sign-in for an instance that is not a Salesforce host.");return{refreshToken:e.data.refresh_token,instanceUrl:t.origin}}var gr=class{host;constructor(e){this.host=e??null}async defaultHost(){let e=await import("vscode");return{openExternal:t=>e.env.openExternal(t),parseUri:t=>e.Uri.parse(t,!0)}}async open(e){let t=this.host??await this.defaultHost();try{return await t.openExternal(t.parseUri(e))?{status:"opened"}:{status:"error",message:"VS Code did not open the page."}}catch(r){return{status:"error",message:r instanceof Error?r.message:String(r)}}}};import{readFile as _I,readdir as UI}from"node:fs/promises";import{join as wR}from"node:path";var HI=/^[^.][^@/\\]*@[^/\\]+\.json$/;async function bR(s,e=Date.now()){let t=wR(s,".sfdx"),r;try{r=await UI(t)}catch{return 0}let n=new Set;return await Promise.all(r.filter(o=>HI.test(o)&&!o.endsWith(".partial.json")).map(async o=>{let i=await BI(wR(t,o),e);i&&n.add(i)})),n.size}async function BI(s,e){try{let t=JSON.parse(await _I(s,"utf8"));if(typeof t!="object"||t===null)return;let{orgId:r,username:n,expirationDate:o}=t;if(typeof r!="string"||r===""||typeof n!="string")return;if(typeof o=="string"){let i=Date.parse(o);if(Number.isFinite(i)&&i+1440*60*1e3<=e)return}return r}catch{return}}import{homedir as qI}from"node:os";var WI=new Set(["org:list","org:connect","org:connect:cancel","org:disconnect","org:select","org:update","org:open-in-browser","org:cli-status"]),RR=15e3,vR="The Salesforce CLI holds no connected org yet. Use Log in with your browser on the Organizations page: it opens the Salesforce login page.",ba=class{constructor(e,t={}){this.deps=e;this.browser=t.browser??new gr,this.deviceLogin=t.deviceLogin??new wa,this.countCliOrgs=t.countCliOrgs??(()=>bR(qI())),this.connectTo=t.connectTo??(r=>Ig(r))}deps;browser;deviceLogin;countCliOrgs;connectTo;pendingSignIns=new Map;async handle(e){if(!WI.has(e.type))return!1;switch(e.type){case"org:list":return this.handleOrgList(e),!0;case"org:connect":return await this.handleOrgConnect(e),!0;case"org:connect:cancel":return this.handleConnectCancel(e),!0;case"org:disconnect":return await this.handleOrgDisconnect(e),!0;case"org:select":return this.handleOrgSelect(e),!0;case"org:update":return this.handleOrgUpdate(e),!0;case"org:open-in-browser":return await this.handleOpenInBrowser(e),!0;case"org:cli-status":return await this.handleCliStatus(e),!0;default:return!1}}async handleCliStatus(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let[t,r]=await Promise.all([this.deps.sfdxBridge.isCliAvailable().catch(()=>!1),this.countCliOrgs().catch(()=>0)]),n=A(this.deps,e,"org:cli-status:response",{available:t,orgCount:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleOrgList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.deps.orgManager.getAllOrgs(),r=A(this.deps,e,"org:list:response",{orgs:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}async handleOrgConnect(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(rm,e,"org:error",this.deps);if(!t)return;let r=t;switch(r.authMethod){case"sfdx_import":await this.handleSfdxImport(e);break;case"usernamePassword":await this.handleUsernamePassword(e,r);break;case"oauth_web":await this.handleOAuthWeb(e,r);break;case"jwt":await this.handleJwt(e);break;case"oauth_device":await this.handleOAuthDevice(e);break;default:Oe(this.deps,"warning","Auth Method",`${r.authMethod} is not yet supported.`),this.failConnect(e,`${r.authMethod} is not yet supported.`,"UNSUPPORTED_AUTH");break}this.syncOrgState()}failConnect(e,t,r){P(this.deps,"org:connect","org:error",e,new Error(t),{code:r,retryable:!1})}notifyCliMissing(e){Oe(this.deps,"error","Salesforce CLI",`${Ho} ${e}`,{actions:[{label:"Install the CLI",command:"sf-cli-install",url:Ap}]})}ackConnect(e,t){let r=A(this.deps,e,"org:statusChanged",{orgId:t,status:"connected"});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}async handleSfdxImport(e){try{if(!await this.deps.sfdxBridge.isCliAvailable()){this.notifyCliMissing("Importing orgs from the CLI needs it."),this.failConnect(e,Ho,"SF_CLI_NOT_FOUND");return}let r=[],n=await this.deps.sfdxBridge.listOrgs(d=>{r.push(d)});if(n.length===0&&r.length>0){let d=this.reportUnreadable(r);Oe(this.deps,"error","Import Failed",d),this.failConnect(e,d,"SFDX_IMPORT_FAILED");return}if(n.length===0){Oe(this.deps,"info","Import",vR,{autoDismissMs:null,code:"NO_CLI_ORGS"}),this.failConnect(e,vR,"NO_CLI_ORGS");return}let o=await this.saveImported(n),i=this.deps.orgManager.getAllOrgs(),a=A(this.deps,e,"org:list:response",{orgs:i});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id}`),Oe(this.deps,"success","Import",`Imported ${n.length} org(s) from SF CLI.`),r.length>0&&Oe(this.deps,"warning","Import",this.reportUnreadable(r),{autoDismissMs:null}),this.ackConnect(e,o[0])}catch(t){let r=T(t);this.deps.log(`[ERR] org:sfdx-import: ${r}`),Oe(this.deps,"error","Import Failed",r),this.failConnect(e,r,"SFDX_IMPORT_FAILED")}}reportUnreadable(e){for(let o of e)this.deps.log(`[WARN] org:import: ${o.why==="notConnected"?"not connected":"no access token for"} ${o.alias??o.username}: ${o.reason}`);let t=o=>o.map(i=>`${Re(i)} (${i.reason})`).join("; "),r=e.filter(o=>o.why!=="notConnected"),n=e.filter(o=>o.why==="notConnected");return[...n.length>0?[`The Salesforce CLI cannot reach these orgs, so they were not imported: ${t(n)}. Log in to each again with the CLI, or use Log in with your browser; a scratch org past its date is gone, create a new one.`]:[],...r.length>0?[`No access token from the Salesforce CLI, so not imported: ${t(r)}`]:[]].join(" ")}async saveImported(e){let t=await Promise.all(e.map(n=>this.typedImport(n))),r=[];for(let{org:n,credentials:o}of t){let i=this.refreshedEntryFor(n);i&&this.deps.log(`[INFO] org:import: ${i.alias} was refreshed into org ${n.orgId}; its entry is updated`);let a=i?{...n,id:i.id}:n;await this.deps.orgRegistry.saveOrg(a,o),r.push(a.id)}return r}async typedImport(e){let{org:t,credentials:r}=e;if(t.orgType!=="Production"||(t.metadata.edition??"")!=="")return e;let{accessToken:n,instanceUrl:o}=r;if(!n||!o)return e;try{let i=await vg(this.connectTo({instanceUrl:o,accessToken:n,version:t.metadata.apiVersion}).then(l=>Qn(l)),RR,`the org did not answer within ${RR/1e3} s`),a=vn({isSandbox:i.sandbox,edition:i.edition}),{safetyTier:d,color:c}=kr(a);return a!==t.orgType&&this.deps.log(`[INFO] org:import: ${t.alias} says it is ${i.edition??(i.sandbox?"a sandbox":"no edition")}; typed ${a}`),{credentials:r,org:{...t,orgType:a,safetyTier:d,appearance:{...t.appearance,color:c},metadata:{...t.metadata,edition:i.edition??""}}}}catch(i){return this.deps.log(`[WARN] org:import: ${t.alias} gave no edition and could not be asked what it is (${T(i)}): typed Production until it is reconnected`),e}}refreshedEntryFor(e){let t=this.deps.sandboxRefreshes;if(!t||this.deps.orgManager.getOrg(e.id))return;let r=e.username.toLowerCase();return this.deps.orgManager.getAllOrgs().find(n=>n.username.toLowerCase()===r&&t.wasRefreshedTo(n.id,e.orgId))}async handleUsernamePassword(e,t){if(!t.username||!t.password){Oe(this.deps,"error","Auth","Username and password are required."),this.failConnect(e,"Username and password are required.","MISSING_CREDENTIALS");return}let r=this.resolveLoginUrl(e,t);if(!r)return;let n=await this.deps.authProvider.authenticate({method:"usernamePassword",loginUrl:r,username:t.username,password:t.password,securityToken:t.securityToken});if(!n.success||!n.accessToken||!n.instanceUrl){Oe(this.deps,"error","Auth Failed",n.error??"Authentication failed"),this.failConnect(e,n.error??"Authentication failed","AUTH_FAILED");return}try{let o=await this.deps.authProvider.validateConnection(n.accessToken,n.instanceUrl),i=vn({isSandbox:o.isSandbox,edition:o.orgType}),{safetyTier:a,color:d}=kr(i),c={id:o.orgId,alias:t.alias??t.username??o.username,username:o.username,...o.orgName?{organizationName:o.orgName}:{},instanceUrl:n.instanceUrl,orgId:o.orgId,orgType:i,authMethod:"usernamePassword",safetyTier:a,appearance:{color:d,icon:"cloud",position:0},metadata:{apiVersion:Xn.DEFAULT_API_VERSION,edition:o.orgType,features:[]},status:"connected",lastConnected:new Date().toISOString(),tags:[]},l=this.deps.authProvider.buildConnectionConfig({method:"usernamePassword",loginUrl:r,username:t.username,password:t.password,securityToken:t.securityToken},n);await this.deps.orgRegistry.saveOrg(c,l);let u=A(this.deps,e,"org:statusChanged",{orgId:c.id,status:"connected"});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`),Oe(this.deps,"success","Connected",`${Re(c)} connected.`)}catch(o){let i=T(o);this.deps.log(`[ERR] org:username-password: ${i}`),Oe(this.deps,"error","Validation Failed",`Auth succeeded but org validation failed: ${i}`),this.failConnect(e,`Auth succeeded but org validation failed: ${i}`,"ORG_VALIDATION_FAILED")}}resolveLoginUrl(e,t){let r=t.loginUrl??"https://login.salesforce.com",n=si(r);if(n.ok)return n.origin;let o=n.reason==="not-https"?"Login URL must use HTTPS.":n.reason==="not-salesforce"?`Login URL must be a Salesforce login host (login.salesforce.com, test.salesforce.com or a My Domain): "${r}". For an org on another Salesforce cloud, log in with "sf org login web --instance-url <url>", then add it with Import from Salesforce CLI.`:n.reason==="not-origin"?`Login URL must name a host only, with no path, query or credentials: "${r}".`:`Invalid login URL: "${r}".`;Oe(this.deps,"error","Auth",o),this.failConnect(e,o,"INVALID_LOGIN_URL")}async handleOAuthWeb(e,t){let r=this.resolveLoginUrl(e,t);if(r)try{if(!await this.deps.sfdxBridge.isCliAvailable()){this.notifyCliMissing("OAuth web login runs through it."),this.failConnect(e,Ho,"SF_CLI_NOT_FOUND");return}let o=t.alias??"",i=await this.deps.sfdxBridge.loginWeb(o,r);await this.importSignedInOrg(e,i,"OAuth")}catch(n){let o=T(n);this.deps.log(`[ERR] org:oauth-web: ${o}`),Oe(this.deps,"error","OAuth Failed",o),this.failConnect(e,o,"OAUTH_WEB_FAILED")}}async handleJwt(e){let t=D(nm,e,"org:error",this.deps);if(!t)return;let r=this.resolveLoginUrl(e,t);if(r)try{if(!await this.requireCli(e,"JWT sign-in runs through it."))return;let n=await this.deps.sfdxBridge.loginJwt({username:t.username,clientId:t.clientId,keyFile:t.jwtKeyFile,loginUrl:r,alias:t.alias||void 0});await this.importSignedInOrg(e,n,"JWT")}catch(n){let o=T(n);this.deps.log(`[ERR] org:jwt: ${o}`),Oe(this.deps,"error","JWT Sign-in Failed",o),this.failConnect(e,o,"JWT_LOGIN_FAILED")}}async handleOAuthDevice(e){let t=D(om,e,"org:error",this.deps);if(!t)return;let r=this.resolveLoginUrl(e,t);if(!r)return;let n=new AbortController;this.pendingSignIns.set(e.id,n);try{if(!await this.requireCli(e,"The device sign-in hands its session to it."))return;let o=await this.deviceLogin.authorize(r,t.clientId,n.signal),i=A(this.deps,e,"org:device-code",{userCode:o.userCode,verificationUri:o.verificationUri,expiresAt:o.expiresAt});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`);let a=await this.browser.open(o.verificationUri);a.status==="error"&&this.deps.log(`[WARN] org:oauth-device: verification page not opened: ${a.message}`);let d=await this.deviceLogin.awaitApproval(r,t.clientId,o,n.signal);if(n.signal.aborted)throw new Error("Sign-in cancelled.");let c=await this.deps.sfdxBridge.loginWithRefreshToken({clientId:t.clientId,refreshToken:d.refreshToken,instanceUrl:d.instanceUrl,alias:t.alias||void 0});await this.importSignedInOrg(e,c,"Device Sign-in")}catch(o){if(n.signal.aborted){this.deps.log(`[INFO] org:oauth-device cancelled id=${e.id}`),this.failConnect(e,"Sign-in cancelled.","CANCELLED");return}let i=T(o);this.deps.log(`[ERR] org:oauth-device: ${i}`),Oe(this.deps,"error","Device Sign-in Failed",i),this.failConnect(e,i,"OAUTH_DEVICE_FAILED")}finally{this.pendingSignIns.delete(e.id)}}handleConnectCancel(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(sm,e,"org:error",this.deps);t&&this.pendingSignIns.get(t.requestId)?.abort()}async requireCli(e,t){return await this.deps.sfdxBridge.isCliAvailable()?!0:(this.notifyCliMissing(t),this.failConnect(e,Ho,"SF_CLI_NOT_FOUND"),!1)}async importSignedInOrg(e,t,r){let n=await this.deps.sfdxBridge.findOrg(t.username);if(!n)throw new Error(`Signed in as ${t.username}, but "sf org display" does not show that org as connected.`);let[o]=await this.saveImported([n]);Oe(this.deps,"success",r,`${Re(n.org)} connected.`),this.ackConnect(e,o??n.org.id)}async handleOrgDisconnect(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(im,e,"org:error",this.deps);if(!t)return;let r=t;ai().remove(r.orgId),await this.deps.orgRegistry.removeOrg(r.orgId);let n=A(this.deps,e,"org:statusChanged",{orgId:r.orgId,status:"disconnected"});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`),this.syncOrgState()}handleOrgSelect(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(am,e,"org:error",this.deps);if(!t)return;let{orgId:r}=t;if(!this.deps.orgManager.getOrg(r)){Oe(this.deps,"warning","Orgs",`Unknown org: ${r}`);return}this.deps.onOrgSelected?.(r);let n=A(this.deps,e,"org:selected",{orgId:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleOrgUpdate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(cm,e,"org:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){P(this.deps,"org:update","org:error",e,new Error(`Unknown org: ${t.orgId}`),{code:"ORG_NOT_FOUND",retryable:!1});return}try{this.deps.orgRegistry.updateOrgMetadata({...r,alias:t.alias,appearance:{...r.appearance,color:t.color},tags:t.tags,...t.staging!==void 0?{staging:t.staging}:{}})}catch(o){P(this.deps,"org:update","org:error",e,o,{code:"ORG_UPDATE_FAILED",retryable:!0});return}let n=A(this.deps,e,"org:list:response",{orgs:this.deps.orgManager.getAllOrgs()});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`),this.syncOrgState()}async handleOpenInBrowser(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(dm,e,"org:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){P(this.deps,"org:open-in-browser","org:error",e,new Error(`No registered org has the id "${t.orgId}".`),{code:"ORG_NOT_FOUND",retryable:!1});return}let n=dn(r.instanceUrl);if(!n.ok){let a=n.reason==="not-https"?`its instance URL must use HTTPS, got "${n.protocol}"`:"its instance URL is not a valid URL";P(this.deps,"org:open-in-browser","org:error",e,new Error(`Cannot open "${Re(r)}": ${a}.`),{code:"INVALID_INSTANCE_URL",retryable:!1});return}let o=await this.browser.open(n.url.toString());o.status==="error"&&this.deps.log(`[WARN] org:open-in-browser: not opened: ${o.message}`);let i=A(this.deps,e,"org:open-in-browser:response",o);this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} status=${o.status}`)}syncOrgState(){let e=this.deps.orgManager.getAllOrgs();this.deps.stateSync.updateState({orgs:e})}};function zI(s){let e=Dp.safeParse(s.services?.getSandforgeSetting?.("forge.graphView","auto"));return e.success?e.data:"auto"}function GI(s){return s.services?.getSandforgeSetting?.("grappe.enabled",!1)===!0}var JI=new Set(["settings:get","settings:update","telemetry:status","telemetry:toggle"]),Ra=class{constructor(e){this.deps=e}deps;async handle(e){if(!JI.has(e.type))return!1;switch(e.type){case"settings:get":return this.handleSettingsGet(e),!0;case"settings:update":return this.handleSettingsUpdate(e),!0;case"telemetry:status":return this.handleTelemetryStatus(e),!0;case"telemetry:toggle":return await this.handleTelemetryToggle(e),!0;default:return!1}}postSettings(){this.deps.broker.postToWebview({id:this.deps.nextId(),type:"settings:response",timestamp:Date.now(),payload:this.settingsPayload()})}settingsPayload(){return{settings:this.deps.configStore.getByCategory("settings"),forgeGraphView:zI(this.deps),grappeEnabled:GI(this.deps)}}handleSettingsGet(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=A(this.deps,e,"settings:response",this.settingsPayload());this.deps.broker.postToWebview(t),this.deps.log(`[TX] ${t.type} id=${t.id}`)}handleSettingsUpdate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(lm,e,"settings:error",this.deps);if(!t)return;let r=t;this.deps.configStore.set(r.key,r.value,"settings");let n=A(this.deps,e,"settings:response",this.settingsPayload());this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleTelemetryStatus(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.deps.services?.getSandforgeSetting?.("telemetry",!1)??!1,r=this.deps.services?.telemetry.getTelemetryEventCount()??0,n=A(this.deps,e,"telemetry:status:response",{enabled:t,eventCount:r});this.deps.broker.postToWebview(n)}async handleTelemetryToggle(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(um,e,"settings:error",this.deps);if(!t)return;let{enabled:r}=t;if(!this.deps.services?.setSandforgeSetting){let n=A(this.deps,e,"telemetry:toggle:response",{success:!1,enabled:this.deps.services?.getSandforgeSetting?.("telemetry",!1)??!1,error:"Settings backend not available \u2014 telemetry preference was not persisted."});this.deps.broker.postToWebview(n);return}try{await this.deps.services.setSandforgeSetting("telemetry",r);let n=this.deps.services.getSandforgeSetting?.("telemetry",r)??r,o=A(this.deps,e,"telemetry:toggle:response",{success:!0,enabled:n});this.deps.broker.postToWebview(o)}catch(n){this.deps.log(`[ERR] telemetry:toggle: ${T(n)}`);let o=A(this.deps,e,"telemetry:toggle:response",{success:!1,enabled:this.deps.services.getSandforgeSetting?.("telemetry",!1)??!1,error:T(n)});this.deps.broker.postToWebview(o)}}};var VI="/lightning/setup/AsyncApexJobs/home";function SR(s){let e=dn(s);return e.ok?{ok:!0,url:new URL(VI,e.url.origin).toString()}:e}var ql={DailyApiRequests:{weight:.2,category:"limits"},DataStorageMB:{weight:.2,category:"storage"},DailyBulkApiBatches:{weight:.15,category:"limits"},DailyBulkV2QueryJobs:{weight:.15,category:"limits"},DailyAsyncApexExecutions:{weight:.15,category:"jobs"}},Wl=1,kR=.15,XI=.55;function OR(s){let e=Math.max(0,Math.min(100,s)),t;return e<=50?t=100-e*.6:t=70-(e-50)*1.4,Math.max(0,Math.min(100,Math.round(t)))}function KI(s){let e=Math.max(0,Math.min(100,s)),t;return e<=75?t=e/75*70:t=70+(e-75)/25*30,Math.max(0,Math.min(100,Math.round(t)))}function zl(s,e,t){if(s<=e)return 100;if(s>=t)return 20;let r=(s-e)/(t-e);return Math.round(100-r*80)}function IR(s){switch(s){case"up":return"degrading";case"down":return"improving";case"stable":return"stable"}}function AR(s){return s.direction!=="up"?0:Math.min(15,Math.max(0,Math.abs(s.changePercent)*.5))}function bs(s){return s>=70?"healthy":s>=40?"warning":"critical"}function TR(s,e){if(e<75)return"No action needed.";let t=e>=90?"Urgent: ":"";switch(s){case"DailyApiRequests":return`${t}Review scheduled batch jobs and integrations consuming API calls.`;case"DataStorageMB":return`${t}Consider archiving old records or cleaning up attachments.`;case"DailyBulkApiBatches":return`${t}Group small Bulk API loads into fewer, larger jobs, or spread them over several days.`;case"DailyBulkV2QueryJobs":return`${t}Review the integrations that run Bulk API 2.0 queries, and how often they run.`;case"DailyAsyncApexExecutions":return`${t}Review queued and scheduled Apex jobs for efficiency.`;default:return`${t}Monitor this limit and optimize usage if it continues to grow.`}}function ER(s){let e=s.max-s.remaining;return`${s.usedPercent}% used (${e.toLocaleString()} / ${s.max.toLocaleString()})`}var va=class{calculate(e){let t=[],r=this.countOptionalDimensions(e),n=this.computeLimitsWeightMultiplier(r);this.addCoreLimitFactors(e,t,n),this.addRemainingLimitFactors(e,t,n);let o=this.computeOptionalDimensionWeight(r);this.addMetadataDimension(e,t,o),this.addCoverageDimension(e,t,o),this.addSecurityDimension(e,t,o);let{weightedSum:i,totalWeight:a}=t.reduce((g,h)=>({weightedSum:g.weightedSum+h.score*h.weight,totalWeight:g.totalWeight+h.weight}),{weightedSum:0,totalWeight:0}),d=a>0?Math.round(i/a):100,c=this.scoreToOverallStatus(d),u=[...t].sort((g,h)=>g.score-h.score).filter(g=>g.status!=="healthy").slice(0,3),p=this.buildSummary(c,u);return{overallScore:d,overallStatus:c,factors:t,summary:p,topRisks:u}}countOptionalDimensions(e){let t=0;return(e.metadataCounts!==void 0||e.orgInfo!==void 0)&&t++,e.codeCoverage!==void 0&&t++,e.securitySettings!==void 0&&t++,t}computeLimitsWeightMultiplier(e){if(e===0)return Wl;let t=e*kR;return Math.max(XI,Wl-t)}computeOptionalDimensionWeight(e){return e===0?0:kR}addCoreLimitFactors(e,t,r){for(let[n,o]of Object.entries(ql)){let i=e.limits.find(p=>p.name===n);if(!i)continue;let a=OR(i.usedPercent),d=this.fetchTrendData(e,n),c=d?IR(d.direction):"stable",l=d?AR(d):0,u=Math.max(0,Math.round(a-l));t.push({name:i.name,category:o.category,score:u,weight:o.weight*r,status:bs(u),detail:ER(i),recommendation:TR(i.name,i.usedPercent),trend:c})}}addRemainingLimitFactors(e,t,r){let n=new Set(Object.keys(ql)),o=e.limits.filter(c=>!n.has(c.name)&&c.usedPercent>0);if(o.length===0)return;let i=Object.values(ql).reduce((c,l)=>c+l.weight,0),d=Math.max(0,(Wl-i)*r)/o.length;for(let c of o){let l=OR(c.usedPercent),u=this.fetchTrendData(e,c.name),p=u?IR(u.direction):"stable",g=u?AR(u):0,h=Math.max(0,Math.round(l-g));t.push({name:c.name,category:"limits",score:h,weight:d,status:bs(h),detail:ER(c),recommendation:TR(c.name,c.usedPercent),trend:p})}}addMetadataDimension(e,t,r){if(e.metadataCounts===void 0&&e.orgInfo===void 0)return;let n=e.metadataCounts?.customObjectCount??e.orgInfo?.customObjectCount??0,o=e.metadataCounts?.customFieldCount??0,i=e.metadataCounts?.apexClassCount??e.orgInfo?.apexClassCount??0,a=Math.round(zl(n,50,500)*.4+zl(o,200,2e3)*.3+zl(i,100,1e3)*.3),d=`${n} custom objects, ${o} custom fields, ${i} Apex classes`,c=a<60?"High metadata complexity detected - consider consolidating custom objects and reviewing unused Apex classes":"Metadata complexity is manageable";t.push({name:"Metadata Complexity",category:"metadata",score:a,weight:r,status:bs(a),detail:d,recommendation:c,trend:"stable"})}addCoverageDimension(e,t,r){if(e.codeCoverage===void 0)return;let n=KI(e.codeCoverage),o=`${Math.round(e.codeCoverage)}% org-wide Apex code coverage`,i=e.codeCoverage<75?`Code coverage is at ${Math.round(e.codeCoverage)}% - Salesforce requires minimum 75% for deployment`:"Code coverage meets Salesforce requirements";t.push({name:"Code Coverage",category:"coverage",score:n,weight:r,status:bs(n),detail:o,recommendation:i,trend:"stable"})}addSecurityDimension(e,t,r){if(e.securitySettings===void 0)return;let{score:n,detail:o,recommendation:i}=this.scoreSecuritySettings(e.securitySettings);t.push({name:"Security Settings",category:"security",score:n,weight:r,status:bs(n),detail:o,recommendation:i,trend:"stable"})}scoreSecuritySettings(e){let t=0,r=[];e.passwordMinLength>=12?t+=25:e.passwordMinLength>=8?t+=15:(t+=5,r.push("password minimum length is below 8 characters")),e.passwordComplexity?t+=20:r.push("password complexity requirements are disabled"),e.sessionTimeout<=120?t+=20:e.sessionTimeout<=480?t+=10:r.push("session timeout exceeds 8 hours"),e.mfaEnabled?t+=20:r.push("MFA is not enabled"),e.ipRestrictions?t+=15:r.push("login IP restrictions are not configured");let n=r.length===0?"All security settings are properly configured":`${r.length} security issue(s) found`,o=r.length===0?"Security configuration is strong":`Improve security: ${r.join(", ")}`;return{score:t,detail:n,recommendation:o}}fetchTrendData(e,t){if(e.trends)return e.trends[t];if(e.trendStorage)return e.trendStorage.getTrendData(e.orgId,t)}scoreToOverallStatus(e){return e>=70?"healthy":e>=40?"warning":"critical"}buildSummary(e,t){return e==="healthy"&&t.length===0?"Your org is healthy. All limits are within safe thresholds.":e==="healthy"?`Your org is healthy but ${t[0].name} is trending up.`:e==="warning"?`Warning: ${t.map(o=>o.name).join(", ")} approaching limits. Review recommendations.`:`Critical: ${t.map(n=>n.name).join(", ")} at dangerous levels. Immediate action required.`}};var YI=ke(G({version:L()}));function PR(s){let e=YI.parse(s).map(({version:t})=>t).filter(t=>Number.isFinite(Number(t)));if(e.length===0)throw new Error("The org listed no API version under /services/data.");return e.reduce((t,r)=>Number(r)>Number(t)?r:t)}function QI(s){if(!s)return;let e=new Date(s);return Number.isNaN(e.getTime())?void 0:e.toISOString()}var Sa=class{cache=new Map;cacheTtlMs;constructor(e=300*1e3){this.cacheTtlMs=e}async fetch(e,t){let r=this.cache.get(e);if(r&&Date.now()-r.fetchedAt<this.cacheTtlMs)return r.data;let[n,o,i,a,d,c]=await Promise.all([t.latestApiVersion(),t.queryOrg(),t.queryCount("SELECT COUNT() FROM User WHERE IsActive = true"),t.queryCount("SELECT COUNT() FROM EntityDefinition WHERE DeploymentStatus != null AND QualifiedApiName LIKE '%__c'"),t.queryCount("SELECT COUNT() FROM ApexClass"),t.queryCount("SELECT COUNT() FROM FlowDefinitionView WHERE IsActive = true")]),l=o.namespacePrefix||void 0,u=QI(o.createdDate),p={name:o.name,orgId:o.orgId,type:o.type,edition:o.edition,instanceName:o.instanceName,apiVersion:n,userCount:i,customObjectCount:a,apexClassCount:d,flowCount:c,...l!==void 0?{namespacePrefix:l}:{},...u!==void 0?{createdDate:u}:{}};return this.cache.set(e,{data:p,fetchedAt:Date.now()}),p}clearCache(e){e?this.cache.delete(e):this.cache.clear()}};function CR(s){return Object.entries(s).map(([e,{Max:t,Remaining:r}])=>({name:e,max:t,remaining:r,usedPercent:t>0?Math.round((t-r)/t*100):0}))}var Gl=1440*60*1e3,DR=7*Gl,ZI=500*1024,eA=900*1e3,tA=2,rA="trends",nA=new Set(Ys),oA=Gl,Oa=class{configStore;lastSaveTimestamps=new Map;constructor(e){this.configStore=e}trendKey(e){return`trend:${e}`}record(e,t){let r=Date.now();this.isRateLimited(e,r)||this.append(e,this.read(e),t,r)}recordAndGetTrends(e,t,r){let n=Date.now(),o=this.read(e),a=(this.isRateLimited(e,n)?o:this.append(e,o,t,n)).filter(l=>l.timestamp>=ka(n-DR)),d=a.filter(l=>l.timestamp>=ka(n-oA)),c={};for(let l of r)c[l]=this.computeTrend(l,a,d);return c}getHistory(e,t=Gl){let r=ka(Date.now()-t);return this.read(e).filter(n=>n.timestamp>=r)}getTrendData(e,t){let r=this.getHistory(e);return this.computeTrend(t,r,r)}purge(e){let t=this.trendKey(e);this.configStore.delete(t),this.lastSaveTimestamps.delete(e)}read(e){return this.configStore.get(this.trendKey(e))??[]}isRateLimited(e,t){return t-(this.lastSaveTimestamps.get(e)??0)<eA}append(e,t,r,n){let o=ka(n-DR),i=[...t,r].filter(d=>d.timestamp>=o).map(d=>({...d,limits:d.limits.filter(c=>nA.has(c.name))})),a=this.trimToSizeLimit(i);return this.configStore.set(this.trendKey(e),a,rA),this.lastSaveTimestamps.set(e,n),a}computeTrend(e,t,r){let{values:n,timestamps:o}=xR(e,t),{values:i}=xR(e,r);if(i.length<2)return{limitName:e,direction:"stable",changePercent:0,sparklineData:n,timestamps:o};let a=i[0],d=i[i.length-1],c=d-a,l;Math.abs(c)<=tA?l="stable":c>0?l="up":l="down";let u;if(l==="up"&&d<100){let p=this.getTimeSpanMs(r);if(p>0){let g=c/p;if(g>0){let f=(100-d)/g;u=Math.round(f/(3600*1e3)*10)/10}}}return{limitName:e,direction:l,changePercent:Math.round(c*10)/10,predictedTimeToLimit:u,sparklineData:n,timestamps:o}}getTimeSpanMs(e){if(e.length<2)return 0;let t=new Date(e[0].timestamp).getTime();return new Date(e[e.length-1].timestamp).getTime()-t}trimToSizeLimit(e){let t=[...e];for(;t.length>0&&!(new TextEncoder().encode(JSON.stringify(t)).length<=ZI);)t.shift();return t}};function ka(s){return new Date(s).toISOString()}function xR(s,e){let t=[],r=[];for(let n of e){let o=n.limits.find(i=>i.name===s);o&&(t.push(o.usedPercent),r.push(n.timestamp))}return{values:t,timestamps:r}}var Ia=class{onNotify;definitions=new Map;activeAlerts=new Map;lastTriggered=new Map;constructor(e){this.onNotify=e}addDefinition(e){this.definitions.set(e.id,e)}removeDefinition(e){this.definitions.delete(e)}getDefinitions(){return[...this.definitions.values()]}evaluate(e,t,r){for(let n of this.definitions.values()){if(!n.enabled||n.metric!==e||!sA(n.condition,t))continue;let o=`${n.id}:${r}`;if(this.isInCooldown(n,o))continue;let i=this.createAlert(n,t,r);return this.activeAlerts.set(i.id,i),this.lastTriggered.set(o,Date.now()),this.onNotify(i),i}return null}getActiveAlerts(){return[...this.activeAlerts.values()].filter(e=>e.status==="active"||e.status==="acknowledged")}acknowledgeAlert(e){let t=this.activeAlerts.get(e);t&&(t.status="acknowledged",t.acknowledgedAt=new Date().toISOString())}resolveAlert(e){let t=this.activeAlerts.get(e);t&&(t.status="resolved",t.resolvedAt=new Date().toISOString())}restoreAlerts(e){for(let t of e)if(t.status==="active"||t.status==="acknowledged"){this.activeAlerts.set(t.id,t);let r=`${t.definitionId}:${t.orgId}`,n=Date.parse(t.triggeredAt);!Number.isNaN(n)&&n>(this.lastTriggered.get(r)??0)&&this.lastTriggered.set(r,n)}}dismissAlert(e){let t=this.activeAlerts.get(e);t&&(t.status="dismissed")}isInCooldown(e,t){let r=this.lastTriggered.get(t);if(r===void 0)return!1;let n=e.cooldownMinutes*60*1e3;return Date.now()-r<n}createAlert(e,t,r){return{id:`alert-${globalThis.crypto.randomUUID()}`,definitionId:e.id,severity:e.severity,status:"active",message:`${e.name}: ${e.metric} is ${t} (threshold: ${e.condition.threshold})`,currentValue:t,threshold:e.condition.threshold,orgId:r,triggeredAt:new Date().toISOString()}}};function sA(s,e){switch(s.operator){case"gt":return e>s.threshold;case"gte":return e>=s.threshold;case"lt":return e<s.threshold;case"lte":return e<=s.threshold;case"eq":return e===s.threshold;case"neq":return e!==s.threshold}}var ko="alert:state:",Jl="alerts";var Aa=class{constructor(e){this.configStore=e}configStore;saveAlerts(e){this.configStore.set(`${ko}active`,e,Jl)}loadAlerts(){let e=this.configStore.get(`${ko}active`);return Array.isArray(e)?e:[]}saveDefinitions(e){this.configStore.set(`${ko}definitions`,e,Jl)}loadDefinitions(){let e=this.configStore.get(`${ko}definitions`);return Array.isArray(e)?e:[]}saveHistory(e){let t=this.loadHistory(),r=new Set(t.map(a=>a.id)),n=e.filter(a=>!r.has(a.id));if(n.length===0)return;let o=[...t,...n],i=o.length>500?o.slice(o.length-500):o;this.configStore.set(`${ko}history`,i,Jl)}loadHistory(){let e=this.configStore.get(`${ko}history`);return Array.isArray(e)?e:[]}};var Vl=[{id:"alert-api-critical",name:"API Requests Critical",description:"Fires when daily API request usage reaches 90% of the org limit",enabled:!0,metric:"DailyApiRequests",condition:{operator:"gte",threshold:90},severity:"critical",cooldownMinutes:15,notificationChannels:["vscode_notification"]},{id:"alert-storage-critical",name:"Data Storage Critical",description:"Fires when data storage usage reaches 85% of the org limit",enabled:!0,metric:"DataStorageMB",condition:{operator:"gte",threshold:85},severity:"critical",cooldownMinutes:30,notificationChannels:["vscode_notification"]},{id:"alert-async-critical",name:"Async Apex Critical",description:"Fires when daily async Apex execution usage reaches 90% of the org limit",enabled:!0,metric:"DailyAsyncApexExecutions",condition:{operator:"gte",threshold:90},severity:"critical",cooldownMinutes:15,notificationChannels:["vscode_notification"]},{id:"alert-email-warning",name:"Workflow Emails Warning",description:"Fires when daily workflow email usage reaches 80% of the org limit",enabled:!0,metric:"DailyWorkflowEmails",condition:{operator:"gte",threshold:80},severity:"warning",cooldownMinutes:30,notificationChannels:["vscode_notification"]},{id:"alert-filestorage-critical",name:"File Storage Critical",description:"Fires when file storage usage reaches 85% of the org limit",enabled:!0,metric:"FileStorageMB",condition:{operator:"gte",threshold:85},severity:"critical",cooldownMinutes:30,notificationChannels:["vscode_notification"]}];var Ta=class{queryErrors;errorCache=new Map;truncatedCache=new Map;constructor(e){this.queryErrors=e}async fetch(e){let t=new Date(Date.now()-864e5).toISOString(),{records:r,truncated:n}=await this.queryErrors(e,t);return this.errorCache.set(e,r),this.truncatedCache.set(e,n),r}getRecentErrors(e){return this.errorCache.get(e)??[]}isTruncated(e){return this.truncatedCache.get(e)??!1}getErrorsByType(e){let t=this.getRecentErrors(e),r=new Map;for(let n of t){let o=r.get(n.errorType)??0;r.set(n.errorType,o+1)}return r}};var Ea=class{querySessions;sessionCache=new Map;truncatedCache=new Map;constructor(e){this.querySessions=e}async fetch(e){let{records:t,truncated:r}=await this.querySessions(e);return this.sessionCache.set(e,t),this.truncatedCache.set(e,r),t}getActiveSessions(e){return this.sessionCache.get(e)??[]}isTruncated(e){return this.truncatedCache.get(e)??!1}getActiveUserCount(e){let t=this.getActiveSessions(e);return new Set(t.map(n=>n.userId)).size}};var Pa=class{fetchLogs;analyses=new Map;truncatedCache=new Map;constructor(e){this.fetchLogs=e}analyze(e){let t=iA(e),r=aA(e),n=dA(e),o=e.durationMs,i=cA(t,r,n,o);return{logId:e.id,totalDuration:e.durationMs,soqlQueries:t,dmlStatements:r,heapUsed:n,cpuTime:o,issues:i}}async fetchAndAnalyze(e,t=10){let{records:r,truncated:n}=await this.fetchLogs(e,t),o=r.map(i=>this.analyze(i));return this.analyses.set(e,o),this.truncatedCache.set(e,n),o}isTruncated(e){return this.truncatedCache.get(e)??!1}getRecentAnalyses(e){return this.analyses.get(e)??[]}getTopIssues(e){let t=this.analyses.get(e)??[],r=new Map;for(let n of t)for(let o of n.issues){let i=`${o.type}:${o.message}`,a=r.get(i);a?a.count++:r.set(i,{issue:o,count:1})}return[...r.values()].sort((n,o)=>o.count-n.count).map(n=>n.issue)}};function iA(s){return Math.min(Math.floor(s.logSize/500),100)}function aA(s){return Math.min(Math.floor(s.logSize/1e3),150)}function dA(s){return Math.min(s.logSize*10,6e6)}function cA(s,e,t,r){let n=[];return s>=100?n.push({type:"soql_in_loop",severity:"critical",message:`SOQL query limit reached: ${s}/100`}):s>=100*.8&&n.push({type:"governor_warning",severity:"warning",message:`Approaching SOQL query limit: ${s}/100`}),e>=150?n.push({type:"excessive_dml",severity:"critical",message:`DML statement limit reached: ${e}/150`}):e>=150*.6&&n.push({type:"governor_warning",severity:"warning",message:`Approaching DML statement limit: ${e}/150`}),t>=6e6?n.push({type:"large_heap",severity:"critical",message:`Heap size limit reached: ${t}/6000000`}):t>=6e6*.7&&n.push({type:"large_heap",severity:"warning",message:`Approaching heap size limit: ${t}/6000000`}),r>5e3&&n.push({type:"slow_query",severity:"warning",message:`Slow execution: ${r}ms exceeds 5000ms threshold`}),n}var lA=new Set(Bp);function jR(s){return typeof s=="string"&&lA.has(s)?s:"Unknown"}function uA(){let s=new Map;return{load:e=>s.get(e),save:(e,t)=>{s.set(e,t)}}}function MR(s){return`${s.sandboxName}:${s.refreshDate}`}var Ca=class{querySandboxes;onRefreshDetected;seen;refreshCache=new Map;supportedCache=new Map;truncatedCache=new Map;constructor(e,t,r=uA()){this.querySandboxes=e,this.onRefreshDetected=t,this.seen=r}async fetch(e){let{supported:t,events:r,truncated:n}=await this.querySandboxes(e);if(this.refreshCache.set(e,r),this.supportedCache.set(e,t),this.truncatedCache.set(e,n),!t)return r;let o=r.filter(d=>d.status==="Completed"),i=this.seen.load(e);if(i!==void 0){let d=new Set(i);for(let c of o)d.has(MR(c))||this.onRefreshDetected?.(c)}let a=o.map(MR);return(i===void 0||a.some(d=>!i.includes(d)))&&this.seen.save(e,a),r}isSupported(e){return this.supportedCache.get(e)??!0}isTruncated(e){return this.truncatedCache.get(e)??!1}getRecentRefreshes(e){return this.refreshCache.get(e)??[]}isRefreshInProgress(e){return(this.refreshCache.get(e)??[]).some(r=>qp(r.status))}};var Da=class s{providers;constructor(e){this.providers=e}async computeHealth(e){let t=await Promise.all(this.providers.map(c=>c(e))),r=s.computeScore(t),n=r===null?"unknown":s.statusFromScore(r),o=t.find(c=>c.name==="apiLimits"),i=t.find(c=>c.name==="storage"),a=t.find(c=>c.name==="activeJobs"),d=t.find(c=>c.name==="recentErrors");return{orgId:e,overall:n,apiLimitsStatus:o?.status??"unknown",storageStatus:i?.status??"unknown",failedJobs:a?.status==="unknown"?null:a?.count??null,failedJobsOutOf:a?.status==="unknown"?null:a?.outOf??null,recentErrorLogs:d?.status==="unknown"?null:d?.count??null,lastChecked:new Date().toISOString()}}static computeScore(e){let t=e.filter(n=>n.status!=="unknown");if(t.length===0)return null;let r=t.reduce((n,o)=>n+o.score,0);return Math.round(r/t.length)}static statusFromScore(e){return e>=80?"healthy":e>=50?"degraded":"critical"}};var NR=new Set(["Queued","Processing"]),xa=class{queryJobs;jobCache=new Map;constructor(e){this.queryJobs=e}async fetch(e){let t=await this.queryJobs(e);return this.jobCache.set(e,t),t}getActiveJobs(e){return(this.jobCache.get(e)??[]).filter(r=>NR.has(r.status))}getFailedJobs(e){return(this.jobCache.get(e)??[]).filter(r=>r.status==="Failed")}getJobStats(e){let t=this.jobCache.get(e)??[];return{total:t.length,active:t.filter(r=>NR.has(r.status)).length,completed:t.filter(r=>r.status==="Completed").length,failed:t.filter(r=>r.status==="Failed").length}}};var pA=3e4,gA=1440*60*1e3,$R=100,LR=50,FR=20,_R="sandbox-process-seen:";function fA(s){return{load:e=>{let t=s.get(`${_R}${e}`);return Array.isArray(t)?t.filter(r=>typeof r=="string"):void 0},save:(e,t)=>{s.set(`${_R}${e}`,t,"sandbox-refresh")}}}function UR(s){let e=new Oa(s.configStore),t=new Aa(s.configStore),r=new Ia(b=>{s.log(`[ALERT] ${b.severity}: ${b.message}`);let O=b.severity==="critical"?"error":"warning";s.notify(O,b.message),t.saveAlerts(r.getActiveAlerts())}),n=t.loadDefinitions(),o=n.length>0?n:Vl;for(let b of o)r.addDefinition(b);n.length===0&&t.saveDefinitions(Vl);let i=t.loadAlerts();r.restoreAlerts(i);let a=new Ta(async(b,O)=>{let k=await s.getConnection(b),{records:S,truncated:E}=await ts(k,`SELECT Id, Operation, Status, DurationMilliseconds, LogLength, StartTime, LogUser.Username FROM ApexLog WHERE Status != 'Success' AND StartTime > ${O} ORDER BY StartTime DESC LIMIT ${LR}`,LR);return De(k.limitInfo,"monitor:error-logs apexLog"),{records:S.map(I=>({id:I.Id,errorType:I.Status,message:`${I.Operation} - ${I.Status}`,timestamp:I.StartTime,user:I.LogUser?.Username??void 0,context:I.Operation})),truncated:E}}),d=async(b,O)=>{let k=await s.getConnection(b),S=await k.query(`SELECT COUNT() FROM ApexLog WHERE Status != 'Success' AND StartTime > ${O}`);return De(k.limitInfo,"monitor:refresh apexLogCount"),S.totalSize},c=new Ea(async b=>{let O=await s.getConnection(b),{records:k,truncated:S}=await ts(O,`SELECT Id, UsersId, Users.Username, LoginType, SessionType, CreatedDate, SourceIp FROM AuthSession ORDER BY CreatedDate DESC LIMIT ${$R}`,$R);return De(O.limitInfo,"monitor:sessions authSession"),{records:k.map(E=>({sessionId:E.Id,userId:E.UsersId,username:E.Users?.Username??E.UsersId,sessionType:E.SessionType??E.LoginType??"Unknown",loginTime:E.CreatedDate,sourceIp:E.SourceIp??""})),truncated:S}}),l=new Pa(async(b,O)=>{let k=await s.getConnection(b),{records:S,truncated:E}=await ts(k,`SELECT Id, Operation, Status, DurationMilliseconds, LogLength, StartTime, LogUser.Username FROM ApexLog ORDER BY StartTime DESC LIMIT ${O}`,O);return De(k.limitInfo,"monitor:apex-insights apexLog"),{records:S.map(I=>({id:I.Id,operation:I.Operation??"Unknown",status:I.Status,durationMs:I.DurationMilliseconds??0,logSize:I.LogLength??0,startTime:I.StartTime,user:I.LogUser?.Username??"Unknown"})),truncated:E}}),u=new Set,p=new Ca(async b=>{if(u.has(b))return{supported:!1,events:[],truncated:!1};let O=await s.getConnection(b),k;try{k=await ts(O,`SELECT Id, SandboxName, Status, CreatedDate, Description FROM SandboxProcess ORDER BY CreatedDate DESC LIMIT ${FR}`,FR)}catch(S){let E=S instanceof Error?S.message:String(S);if(E.includes("SandboxProcess")&&E.includes("not supported"))return u.add(b),{supported:!1,events:[],truncated:!1};throw S}return De(O.limitInfo,"monitor:sandbox-refresh sandboxProcess"),{supported:!0,events:k.records.map(S=>({orgId:b,sandboxName:S.SandboxName??"Unknown",refreshDate:S.CreatedDate,status:jR(S.Status),sourceOrg:S.Description??void 0})),truncated:k.truncated}},b=>s.onSandboxRefreshCompleted?.(b),fA(s.configStore)),g=new Map,h=async(b,O)=>{let k=g.get(b);if(k&&Date.now()-k.fetchedAt<pA)return k.data;let S=await O.request(`/services/data/${Kn}/limits`);return g.set(b,{data:S,fetchedAt:Date.now()}),S},f=async b=>{try{let O=await s.getConnection(b),S=(await h(b,O)).DailyApiRequests;if(!S||!S.Max)return{name:"apiLimits",status:"unknown",score:0,message:"No API limit reported"};let E=Math.round((S.Max-S.Remaining)/S.Max*100);return{name:"apiLimits",status:E>80?"critical":E>60?"warning":"ok",score:100-E,message:`API usage at ${E}%`,percent:E}}catch{return{name:"apiLimits",status:"unknown",score:0,message:"Unable to fetch limits"}}},m=async b=>{try{let O=await s.getConnection(b),S=(await h(b,O)).DataStorageMB;if(!S||!S.Max)return{name:"storage",status:"unknown",score:0,message:"No storage limit reported"};let E=Math.round((S.Max-S.Remaining)/S.Max*100);return{name:"storage",status:E>85?"critical":E>70?"warning":"ok",score:100-E,message:`Storage usage at ${E}%`,percent:E}}catch{return{name:"storage",status:"unknown",score:0,message:"Unable to fetch storage"}}},y=async b=>{let O;try{let E=new Date(Date.now()-gA).toISOString();O=await d(b,E)}catch{return{name:"recentErrors",status:"unknown",score:0,message:"Unable to fetch error logs"}}let k=Math.max(0,100-O*5);return{name:"recentErrors",status:O>10?"critical":O>3?"warning":"ok",score:k,count:O,message:`${O} recent errors`}},w=new xa(async b=>{let O=await s.getConnection(b),k=await At(O,`SELECT Id, JobType, Status, NumberOfErrors, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${Wr.monitorJobs}`);return De(O.limitInfo,"monitor:refresh asyncJobs"),k.map(S=>({id:S.Id,jobType:S.JobType??"Batch",status:S.Status,createdBy:S.CreatedById,createdDate:S.CreatedDate,failedRecords:S.NumberOfErrors}))}),v=async b=>{try{await w.fetch(b);let O=w.getJobStats(b),k=Math.max(0,100-O.failed*10);return{name:"activeJobs",status:O.failed>5?"critical":O.failed>0?"warning":"ok",score:k,count:O.failed,outOf:O.total,message:`${O.active} active, ${O.failed} failed of ${O.total} recent jobs`}}catch{return{name:"activeJobs",status:"unknown",score:0,message:"Unable to fetch jobs"}}},R=new Da([f,m,y,v]);return{trendStorage:e,alertStateStore:t,alertEngine:r,errorLogMonitor:a,userSessionMonitor:c,apexLogAnalyzer:l,sandboxRefreshTracker:p,healthCheck:R,healthSignals:{apiLimits:f,storage:m,recentErrors:y,activeJobs:v},getOrFetchLimits:h,forgetOrg:b=>{g.delete(b)}}}var HR=25e3,BR=20,hA=20,mA=20,yA=500,zR=`SELECT Id, JobType, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${Wr.monitorJobs}`,wA=`SELECT Id, JobType, Status, NumberOfErrors, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${Wr.monitorJobs}`,bA=new Set([zR,wA]),RA=new Set(["Queued","Preparing","Processing"]),vA=new Set(["BatchApex","Queueable","Future"]),Rs=3600*1e3,qR=Rs,WR=3;function Xl(s){let e=Math.floor(s/60),t=s%60;return e>0?`${e}h${String(t).padStart(2,"0")}m`:`${t}m`}function SA(s,e){return s.status===e.status&&s.batchesProcessed===e.batchesProcessed&&s.totalBatches===e.totalBatches}function kA(s,e,t){let r=new Map;for(let n of e){let o=s?.get(n.id);if(o!==void 0&&SA(o,n)){r.set(n.id,o);continue}r.set(n.id,{status:n.status,batchesProcessed:n.batchesProcessed,totalBatches:n.totalBatches,unchangedSinceMs:t,movedWhileWatched:o!==void 0})}return r}function OA(s,e,t){let r=[],n=[],o=[];for(let a of s){if(!RA.has(a.status)||!vA.has(a.jobType))continue;let d=e.get(a.id),c=d===void 0?null:t-d.unchangedSinceMs,l=a.batchesProcessed,u=a.totalBatches;if(a.status==="Processing"&&l!==null&&u!==null&&l<u&&c!==null&&c>=Rs){n.push({job:a,stillMs:c,done:l,total:u});continue}if(d?.movedWhileWatched===!0&&c!==null&&c<Rs)continue;let p=t-Date.parse(a.createdDate);p>=qR&&o.push({job:a,ageMs:p,stillMs:c})}n.sort((a,d)=>d.stillMs-a.stillMs);for(let{job:a,stillMs:d,done:c,total:l}of n){let u=Xl(Math.floor(d/6e4));r.push({type:"stuck",severity:"critical",title:`${a.jobType} ${a.id}: no batch completed in ${u}`,detail:`${c} of ${l} batches processed, unchanged across ${u} of observation by this dashboard while ${a.status} (stall bound ${Rs/6e4}m).`,affectedJobs:[a.id],recommendation:"Check the job in Setup > Apex Jobs first. If it is still at the same batch, abort it and re-run it once the cause is known."})}let i=new Map;for(let a of s){if(a.status==="Aborted"||a.status!=="Failed"&&a.failedRecords<=0)continue;let d=i.get(a.jobType)??[];d.push(a),i.set(a.jobType,d)}for(let[a,d]of i){if(d.length<WR)continue;let c=d.reduce((l,u)=>l+(u.failedRecords||0),0);r.push({type:"frequent_failures",severity:"critical",title:`${d.length} ${a} jobs failed`,detail:`${d.length} of the last ${s.length} jobs are ${a} failures (${c} failed batch execution(s) reported) \u2014 at or above the ${WR}-failure pattern threshold.`,affectedJobs:d.map(l=>l.id),recommendation:`Open the most recent ${a} failure and read its extended status: a repeat at this rate is a defect or a data problem, not contention.`})}if(o.length>0){o.sort((p,g)=>g.ageMs-p.ageMs);let a=o[0],d=Xl(Math.floor(a.ageMs/6e4)),{batchesProcessed:c,totalBatches:l}=a.job,u=c===null||l===null||l<=0?"it reports no batch counter, so its progress cannot be observed":a.stillMs===null||a.stillMs<6e4?`${c} of ${l} batches processed, first seen at these values on this refresh`:`${c} of ${l} batches processed, unchanged over the ${Xl(Math.floor(a.stillMs/6e4))} watched so far`;r.push({type:"long_running",severity:"warning",title:o.length===1?`1 job unfinished ${d} after submission`:`${o.length} jobs unfinished ${qR/6e4}m or more after submission`,detail:`${a.job.jobType} ${a.job.id} is ${a.job.status}, submitted ${d} ago; ${u}. Time since submission includes time spent queued: it is not evidence of a stall.`,affectedJobs:o.map(({job:p})=>p.id),recommendation:`Keep this dashboard refreshing to measure progress, or check the job in Setup > Apex Jobs. A batch is called stuck only once its batch counter stays unchanged for ${Rs/6e4}m of watching; a job without batch counters never is.`})}return r}var IA=new Set(["monitor:refresh","monitor:open-apex-jobs","monitor:live-operations","monitor:storage","monitor:deployments","monitor:api-usage","monitor:error-logs","monitor:sessions","monitor:apex-insights","monitor:sandbox-refresh","monitor:alerts","monitor:alert:acknowledge","monitor:alert:dismiss"]),Ma=class{constructor(e,t){this.deps=e;this.externalBrowser=t??new gr;let r=UR({configStore:e.configStore,log:n=>e.log(n),notify:(n,o)=>Oe(e,n,"Alert",o),getConnection:async n=>this.withSharedJobQuery(n,await B(n,e.orgRegistry,e.orgManager)),onSandboxRefreshCompleted:n=>{e.sandboxRefreshes?.noteCompletedRefresh(n)}});this.trendStorage=r.trendStorage,this.forgetServicesOrg=r.forgetOrg,this.alertStateStore=r.alertStateStore,this.alertEngine=r.alertEngine,this.errorLogMonitor=r.errorLogMonitor,this.userSessionMonitor=r.userSessionMonitor,this.apexLogAnalyzer=r.apexLogAnalyzer,this.sandboxRefreshTracker=r.sandboxRefreshTracker,this.healthCheck=r.healthCheck,this.healthSignals=r.healthSignals,this.getOrFetchLimits=r.getOrFetchLimits}deps;trendStorage;orgInfoFetcher=new Sa;healthCalculator=new va;liveOperationTracker;getOrFetchLimits;forgetServicesOrg;errorLogMonitor;userSessionMonitor;apexLogAnalyzer;sandboxRefreshTracker;healthCheck;healthSignals;alertEngine;alertStateStore;inFlightJobRecords=new Map;jobProgress=new Map;externalBrowser;setLiveOperationTracker(e){this.liveOperationTracker=e,e.onChange(this.onLiveOperationsChange)}onLiveOperationsChange=()=>this.pushLiveOperationsSoon();livePush;dispose(){this.livePush!==void 0&&(clearTimeout(this.livePush),this.livePush=void 0),this.liveOperationTracker?.offChange(this.onLiveOperationsChange)}pushLiveOperationsSoon(){this.livePush===void 0&&(this.livePush=setTimeout(()=>{this.livePush=void 0;let e={id:this.deps.nextId(),type:"monitor:live-operations:changed",timestamp:Date.now(),payload:{operations:(this.liveOperationTracker?.getAll()??[]).map(t=>({...t}))}};this.deps.broker.postToWebview(e)},yA),this.livePush.unref?.())}async readOrgHealth(e,t){let r=[];for(let n of t)r.push(await this.healthSignals[n](e));return r}getAlertEngine(){return this.alertEngine}forgetOrg(e){this.forgetServicesOrg(e),this.orgInfoFetcher.clearCache(e),this.jobProgress.delete(e),this.trendStorage.purge(e)}async handle(e){if(!IA.has(e.type))return!1;switch(e.type){case"monitor:refresh":return await this.handleRefresh(e),!0;case"monitor:open-apex-jobs":return await this.handleOpenApexJobs(e),!0;case"monitor:live-operations":return this.handleLiveOperations(e),!0;case"monitor:storage":return await this.handleStorage(e),!0;case"monitor:deployments":return await this.handleDeployments(e),!0;case"monitor:api-usage":return await this.handleApiUsage(e),!0;case"monitor:error-logs":return await this.handleErrorLogs(e),!0;case"monitor:sessions":return await this.handleSessions(e),!0;case"monitor:apex-insights":return await this.handleApexInsights(e),!0;case"monitor:sandbox-refresh":return await this.handleSandboxRefresh(e),!0;case"monitor:alerts":return this.handleAlerts(e),!0;case"monitor:alert:acknowledge":return this.handleAlertAcknowledge(e),!0;case"monitor:alert:dismiss":return this.handleAlertDismiss(e),!0;default:return!1}}withSharedJobQuery(e,t){return new Proxy(t,{get:(r,n)=>{if(n==="query")return i=>{let a=this.inFlightJobRecords.get(e);return a!==void 0&&bA.has(i)?Promise.resolve({done:!0,totalSize:a.length,records:a}):r.query(i)};let o=Reflect.get(r,n,r);return typeof o=="function"?o.bind(r):o}})}pastDeadline(e,t){return e.aborted?(this.deps.log(`[WARN] monitor:refresh outlived its ${HR}ms bound; skipping ${t}`),!0):!1}async handleRefresh(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Pr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{await new ge(HR).withTimeout("monitor:refresh",n=>this.executeRefresh(e,r,n))}catch(n){P(this.deps,"monitor:refresh","monitor:error",e,n)}}async executeRefresh(e,t,r){try{let n=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),[o,i]=await Promise.allSettled([this.getOrFetchLimits(t.orgId,n),At(n,zR)]);if(o.status==="rejected")throw o.reason;let a=CR(o.value);De(n.limitInfo,"monitor:refresh limits");let d=[];for(let k of a){let S=this.alertEngine.evaluate(k.name,k.usedPercent,t.orgId);S&&d.push(S)}if(this.alertStateStore.saveAlerts(this.alertEngine.getActiveAlerts()),d.length>0&&this.alertStateStore.saveHistory(d),i.status==="rejected")throw i.reason;let c=i.value;if(De(n.limitInfo,"monitor:refresh asyncJobs"),this.inFlightJobRecords.set(t.orgId,c),this.pastDeadline(r,"org info and health check"))return;let l=Date.now(),u=c.map(k=>({id:k.Id,jobType:k.JobType??"Unknown",status:k.Status,createdBy:k.CreatedById,createdDate:k.CreatedDate,failedRecords:k.NumberOfErrors,batchesProcessed:k.JobItemsProcessed??null,totalBatches:k.TotalJobItems??null})),p=c.length>=Wr.monitorJobs,g=u.map(({id:k,jobType:S,status:E,createdBy:I,createdDate:C,failedRecords:F})=>({id:k,jobType:S,status:E,createdBy:I,createdDate:C,failedRecords:F})),h=kA(this.jobProgress.get(t.orgId),u,l);this.jobProgress.set(t.orgId,h);let f=OA(u,h,l),m={orgId:t.orgId,limits:a,timestamp:new Date().toISOString()},y=this.trendStorage.recordAndGetTrends(t.orgId,m,Ys),[w,v]=await Promise.all([this.fetchOrgInfo(t.orgId,n),this.computeOrgHealth(t.orgId)]);w&&this.deps.sandboxRefreshes?.observe(t.orgId,{organizationId:w.orgId,instanceName:w.instanceName||void 0},"monitor");let R=this.healthCalculator.calculate({limits:a,orgId:t.orgId,trends:y,orgInfo:w}),b=R.overallScore;if(this.pastDeadline(r,"the monitor:data reply"))return;let O=A(this.deps,e,"monitor:data",{limits:a,jobs:g,jobsTruncated:p,healthScore:b,healthReport:R,trends:y,jobInsights:f,orgInfo:w,orgHealthStatus:v,lastUpdated:new Date().toISOString()});this.deps.broker.postToWebview(O),this.deps.log(`[TX] ${O.type} id=${O.id}`)}catch(n){if(this.pastDeadline(r,`the failure "${T(n)}"`))return;P(this.deps,"monitor:refresh","monitor:error",e,n)}finally{this.inFlightJobRecords.delete(t.orgId)}}async computeOrgHealth(e){try{return await this.healthCheck.computeHealth(e)}catch(t){this.deps.log(`[WARN] HealthCheck failed: ${String(t)}`);return}}async fetchOrgInfo(e,t){try{let r={latestApiVersion:async()=>PR(await t.request("/services/data")),queryOrg:async()=>{let n=this.deps.orgManager.getOrg(e),o=await At(t,"SELECT Name, Id, OrganizationType, InstanceName, NamespacePrefix, CreatedDate FROM Organization LIMIT 1");De(t.limitInfo,"monitor:refresh orgInfo");let i=o[0];return{name:i?.Name??n?.alias??"",orgId:i?.Id??e,type:n?.orgType??"Production",edition:i?.OrganizationType??n?.metadata.edition??"",instanceName:i?.InstanceName??"",namespacePrefix:i?.NamespacePrefix,createdDate:i?.CreatedDate}},queryCount:async n=>(await t.query(n)).totalSize};return await this.orgInfoFetcher.fetch(e,r)}catch(r){this.deps.log(`[WARN] OrgInfo fetch failed: ${String(r)}`);return}}handleLiveOperations(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.liveOperationTracker?.getAll()??[],r=A(this.deps,e,"monitor:live-operations:response",{operations:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}async handleStorage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Pr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.orgId,this.deps.orgRegistry,this.deps.orgManager),o=await n.request(`/services/data/${Kn}/limits/recordCount`);De(n.limitInfo,"monitor:storage recordCount");let i=(o.sObjects??[]).filter(g=>g.count>0).sort((g,h)=>h.count-g.count),a=i.slice(0,mA),d=a.map(g=>g.name).filter(g=>/^[A-Za-z][A-Za-z0-9_]*$/.test(g)),c=new Map;if(d.length>0){let g=await At(n,`SELECT QualifiedApiName, Label FROM EntityDefinition WHERE QualifiedApiName IN (${d.map(h=>`'${h}'`).join(", ")})`);De(n.limitInfo,"monitor:storage entityDefinition");for(let h of g)h.Label&&c.set(h.QualifiedApiName,h.Label)}let l=a.map(g=>({objectName:g.name,label:c.get(g.name)??g.name,recordCount:g.count})),u=i.reduce((g,h)=>g+h.count,0),p=A(this.deps,e,"monitor:storage:response",{success:!0,objects:l,totalRecords:u,objectCount:i.length});this.deps.broker.postToWebview(p),this.deps.log(`[TX] ${p.type} id=${p.id}`)}catch(n){P(this.deps,"monitor:storage","monitor:error",e,n)}}async handleDeployments(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Pr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.orgId,this.deps.orgRegistry,this.deps.orgManager),i=(await n.tooling.query(`SELECT Id, Status, StartDate, CompletedDate, CreatedBy.Name, NumberComponentsTotal, NumberComponentErrors FROM DeployRequest ORDER BY StartDate DESC LIMIT ${BR}`)).records;De(n.limitInfo,"monitor:deployments deployRequest");let a=i.map(c=>({id:c.Id,status:c.Status,startDate:c.StartDate,completedDate:c.CompletedDate??void 0,createdBy:c.CreatedBy?.Name??"Unknown",componentCount:c.NumberComponentsTotal??0,errorCount:c.NumberComponentErrors??0})),d=A(this.deps,e,"monitor:deployments:response",{success:!0,deployments:a,truncated:i.length>=BR});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){P(this.deps,"monitor:deployments","monitor:error",e,n)}}async handleApiUsage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Pr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.orgId,this.deps.orgRegistry,this.deps.orgManager),o=await this.getOrFetchLimits(r.orgId,n);De(n.limitInfo,"monitor:api-usage limits");let i=["DailyApiRequests","DailyBulkApiBatches","DailyBulkV2QueryJobs","DailyBulkV2QueryFileStorageMB","DailyStreamingApiEvents","DailyGenericStreamingApiEvents","DailyDurableStreamingApiEvents","DailyAsyncApexExecutions","HourlyAsyncReportRuns","HourlyTimeBasedWorkflow","DailyWorkflowEmails","MassEmail","SingleEmail","HourlyPublishedPlatformEvents","DailyStandardVolumePlatformEvents"],a=[];for(let c of i){let l=o[c];if(l&&typeof l.Max=="number"){let u=l.Max-l.Remaining,p=l.Max>0?Math.round(u/l.Max*100):0;a.push({category:c,used:u,max:l.Max,usedPercent:p})}}a.sort((c,l)=>l.usedPercent-c.usedPercent);let d=A(this.deps,e,"monitor:api-usage:response",{success:!0,categories:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){P(this.deps,"monitor:api-usage","monitor:error",e,n)}}async handleOpenApexJobs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(dh,e,"monitor:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){P(this.deps,"monitor:open-apex-jobs","monitor:error",e,new Error(`No registered org has the id "${t.orgId}".`),{code:"ORG_NOT_FOUND"});return}let n=SR(r.instanceUrl);if(!n.ok){let o=n.reason==="not-https"?`its instance URL must use HTTPS, got "${n.protocol}"`:"its instance URL is not a valid URL";P(this.deps,"monitor:open-apex-jobs","monitor:error",e,new Error(`Cannot open Apex Jobs for "${Re(r)}": ${o}.`),{code:"INVALID_INSTANCE_URL"});return}try{let o=await this.externalBrowser.open(n.url),i=A(this.deps,e,"monitor:open-apex-jobs:response",o);this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} status=${o.status}`)}catch(o){P(this.deps,"monitor:open-apex-jobs","monitor:error",e,o)}}async handleErrorLogs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Pr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.errorLogMonitor.fetch(r.orgId),i=[...this.errorLogMonitor.getErrorsByType(r.orgId).entries()].map(([d,c])=>({type:d,count:c})),a=A(this.deps,e,"monitor:error-logs:response",{success:!0,errors:n,errorsByType:i,totalCount:n.length,truncated:this.errorLogMonitor.isTruncated(r.orgId)});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id}`)}catch(n){P(this.deps,"monitor:error-logs","monitor:error",e,n)}}async handleSessions(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Pr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.userSessionMonitor.fetch(r.orgId),o=this.userSessionMonitor.getActiveUserCount(r.orgId),i=A(this.deps,e,"monitor:sessions:response",{success:!0,sessions:n,activeUserCount:o,truncated:this.userSessionMonitor.isTruncated(r.orgId)});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){P(this.deps,"monitor:sessions","monitor:error",e,n)}}async handleApexInsights(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Pr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.apexLogAnalyzer.fetchAndAnalyze(r.orgId,hA),o=this.apexLogAnalyzer.getTopIssues(r.orgId),i=A(this.deps,e,"monitor:apex-insights:response",{success:!0,analyses:n,topIssues:o,truncated:this.apexLogAnalyzer.isTruncated(r.orgId)});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){P(this.deps,"monitor:apex-insights","monitor:error",e,n)}}async checkSandboxIdentity(e){let t=this.deps.sandboxRefreshes;if(!(!t||this.deps.orgManager.getOrg(e)?.orgType!=="Sandbox"))try{let r=await B(e,this.deps.orgRegistry,this.deps.orgManager),[n]=await At(r,"SELECT Id, InstanceName FROM Organization");De(r.limitInfo,"monitor:sandbox-refresh organization"),n&&t.observe(e,{organizationId:n.Id,instanceName:n.InstanceName??void 0},"monitor")}catch(r){this.deps.log(`[WARN] monitor:sandbox-refresh identity check: ${T(r)}`)}}async handleSandboxRefresh(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Pr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{await this.checkSandboxIdentity(r.orgId);let n=await this.sandboxRefreshTracker.fetch(r.orgId),o=this.sandboxRefreshTracker.isRefreshInProgress(r.orgId),i=A(this.deps,e,"monitor:sandbox-refresh:response",{success:!0,supported:this.sandboxRefreshTracker.isSupported(r.orgId),refreshes:n,inProgress:o,truncated:this.sandboxRefreshTracker.isTruncated(r.orgId),detected:this.deps.sandboxRefreshes?.refreshesOf(r.orgId)??[]});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){P(this.deps,"monitor:sandbox-refresh","monitor:error",e,n)}}handleAlerts(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.alertEngine.getActiveAlerts(),r=this.alertStateStore.loadHistory(),n=A(this.deps,e,"monitor:alerts:result",{alerts:t,history:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleAlertAcknowledge(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(il,e,"monitor:error",this.deps);if(!t)return;let r=t;this.alertEngine.acknowledgeAlert(r.alertId),this.alertStateStore.saveAlerts(this.alertEngine.getActiveAlerts());let n=A(this.deps,e,"monitor:alert:acknowledge:response",{success:!0});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleAlertDismiss(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(il,e,"monitor:error",this.deps);if(!t)return;let r=t;this.alertEngine.dismissAlert(r.alertId),this.alertStateStore.saveAlerts(this.alertEngine.getActiveAlerts());let n=A(this.deps,e,"monitor:alert:dismiss:response",{success:!0});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}};var yt={orgUnknown:"ORG_NOT_FOUND",production:"PIPELINE_WRITE_REFUSED",needsApproval:"PIPELINE_WRITE_NEEDS_APPROVAL",templateMissing:"SEED_TEMPLATE_MISSING",templateInvalid:"SEED_TEMPLATE_INVALID",templateUsesAi:"SEED_TEMPLATE_USES_AI",unanswered:"SEED_CONFIRMATION_UNAVAILABLE"};function cn(s,e){return Object.assign(new Error(e),{code:s})}function GR(s,e,t){let r=oi(s);if(r==="refused")return cn(yt.production,`${t} is a production org, or one SandForge cannot tell is not: a pipeline never seeds one, whatever an Approval step answers. Seed a sandbox, a scratch org or a Developer Edition org. Nothing was written.`);if(r==="needsApproval"&&!e.approved)return cn(yt.needsApproval,`${t} is a sandbox marked Staging, which a pipeline seeds only once an Approval step before the seed has approved the run, and none did: put an Approval step before it. Nothing was written.`)}function Kl(s){return s.objects.flatMap(e=>e.fieldRules.filter(t=>t.ruleType==="ai_generate").map(t=>`${e.objectApiName}.${t.fieldApiName}`))}function ja(s,e,t){let r=t(e)??Qs.find(d=>d.id===e);if(r==null)return{refusal:cn(yt.templateMissing,`No Seed template is saved under ${e}, and SandForge ships none: it was deleted on the Seed page. Choose another. Nothing was written.`)};let n=r.name,o=typeof n=="string"&&n!==""?n:e,i=ro.safeParse(r);if(!i.success){let d=i.error.issues[0];return{refusal:cn(yt.templateInvalid,`The Seed template "${o}" no longer validates (${d.path.join(".")}: ${d.message}): open it on the Seed page and save it again. Nothing was written.`)}}let a=Kl(i.data);return a.length>0?{refusal:cn(yt.templateUsesAi,`The Seed template "${o}" fills ${a.join(", ")} with AI rules: a pipeline runs where nobody watches, and an AI rule sends field names to Anthropic on each run. Give ${a.length===1?"it a Faker rule":"them Faker rules"} on the Seed page. Nothing was written.`)}:{asked:{orgId:s,template:i.data}}}var Yl="seed:template:",JR="seedTemplates",xn=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${Yl}${e.id}`,e,JR)}load(e){return this.configStore.get(`${Yl}${e}`)}list(){let e=this.configStore.getByCategory(JR);return Object.values(e).sort((r,n)=>n.updatedAt.localeCompare(r.updatedAt))}delete(e){return this.configStore.delete(`${Yl}${e}`)}};var Na=class{templates=new Map;generateId;now;store;constructor(e,t,r){this.generateId=e,this.now=t,this.store=r}create(e){let t=this.now(),r={...e,id:this.generateId(),createdAt:t,updatedAt:t};return this.templates.set(r.id,r),this.store?.save(r),r}get(e){let t=this.templates.get(e);if(t)return t;if(this.store){let r=this.store.load(e);return r&&this.templates.set(e,r),r}}list(){return Array.from(this.templates.values()).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}update(e,t){let r=this.templates.get(e);if(!r)throw new Error(`Template not found: ${e}`);let n={...r,...t,id:r.id,createdAt:r.createdAt,updatedAt:this.now()};return this.templates.set(e,n),this.store?.save(n),n}delete(e){let t=this.templates.delete(e);return this.store&&this.store.delete(e)||t}duplicate(e,t){let r=this.templates.get(e);if(!r)throw new Error(`Template not found: ${e}`);let n=this.now(),o={...r,id:this.generateId(),name:t,version:1,createdAt:n,updatedAt:n};return this.templates.set(o.id,o),this.store?.save(o),o}};var VR=[{id:"assureur-fr",name:"Assureur fran\xE7ais",description:"Compagnie d'assurance fran\xE7aise avec contrats, sinistres et assur\xE9s.",industry:"Insurance",locale:"fr-FR",dataPatterns:{Name:{fieldType:"string",generator:"faker",params:{method:"company.name",locale:"fr"},examples:["AXA Pr\xE9voyance","Mutuelle du Soleil","Groupe Assurancia"]},FirstName:{fieldType:"string",generator:"faker",params:{method:"person.firstName",locale:"fr"},examples:["Jean","Marie","Philippe"]},LastName:{fieldType:"string",generator:"faker",params:{method:"person.lastName",locale:"fr"},examples:["Dupont","Martin","Lefebvre"]},SIRET__c:{fieldType:"string",generator:"pattern",params:{pattern:"###########00##"},examples:["12345678900012","98765432100034","55566677800015"]},Contract_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Auto","Habitation","Sant\xE9","Vie","Responsabilit\xE9 Civile"]},examples:["Auto","Habitation","Sant\xE9"]},Premium__c:{fieldType:"currency",generator:"range",params:{min:200,max:5e3,currency:"EUR"},examples:["450.00","1200.50","3200.00"]}}},{id:"hospital-us",name:"H\xF4pital am\xE9ricain",description:"Hospital system with patients, procedures, and medical codes.",industry:"Healthcare",locale:"en-US",dataPatterns:{FirstName:{fieldType:"string",generator:"faker",params:{method:"person.firstName",locale:"en_US"},examples:["James","Sarah","Michael"]},LastName:{fieldType:"string",generator:"faker",params:{method:"person.lastName",locale:"en_US"},examples:["Johnson","Williams","Smith"]},MRN__c:{fieldType:"string",generator:"sequence",params:{prefix:"MRN-",padLength:8},examples:["MRN-00000001","MRN-00000002","MRN-00000003"]},ICD10_Code__c:{fieldType:"string",generator:"random_pick",params:{values:["J06.9","I10","E11.9","M54.5","J18.9","K21.0","N39.0"]},examples:["J06.9","I10","E11.9"]},CPT_Code__c:{fieldType:"string",generator:"random_pick",params:{values:["99213","99214","99215","99203","99204","36415","71046"]},examples:["99213","99214","36415"]},Insurance_Provider__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Blue Cross","Aetna","UnitedHealth","Cigna","Medicare","Medicaid"]},examples:["Blue Cross","Aetna","Medicare"]}}},{id:"ecommerce-b2c",name:"E-commerce B2C",description:"Online retail with products, orders, customers, and reviews.",industry:"Retail",locale:"en-US",dataPatterns:{Product_Name__c:{fieldType:"string",generator:"faker",params:{method:"commerce.productName"},examples:["Ergonomic Steel Chair","Wireless Bluetooth Headphones","Organic Cotton T-Shirt"]},SKU__c:{fieldType:"string",generator:"sequence",params:{prefix:"SKU-",padLength:6},examples:["SKU-000001","SKU-000002","SKU-000003"]},Price__c:{fieldType:"currency",generator:"range",params:{min:9.99,max:999.99,currency:"USD"},examples:["29.99","149.50","499.00"]},Order_Status__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Pending","Processing","Shipped","Delivered","Returned","Cancelled"]},examples:["Pending","Shipped","Delivered"]},Rating__c:{fieldType:"number",generator:"range",params:{min:1,max:5},examples:["4","5","3"]},Review_Text__c:{fieldType:"textarea",generator:"ai_generate",params:{prompt:"Product review, 1-3 sentences, realistic tone"},examples:["Great product, fast shipping!","Good quality but runs small.","Exactly as described."]}}},{id:"banque-eu",name:"Banque europ\xE9enne",description:"European bank with accounts, transactions, IBAN/BIC codes.",industry:"Banking",locale:"fr-FR",dataPatterns:{IBAN__c:{fieldType:"string",generator:"faker",params:{method:"finance.iban",locale:"fr"},examples:["FR7630006000011234567890189","DE89370400440532013000","ES9121000418450200051332"]},BIC__c:{fieldType:"string",generator:"faker",params:{method:"finance.bic"},examples:["BNPAFRPPXXX","DEUTDEFFXXX","BBVAESMMXXX"]},Transaction_Amount__c:{fieldType:"currency",generator:"range",params:{min:-1e4,max:5e4,currency:"EUR"},examples:["1250.00","-450.75","15000.00"]},Transaction_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Virement","Pr\xE9l\xE8vement","Carte","Ch\xE8que","Esp\xE8ces"]},examples:["Virement","Carte","Pr\xE9l\xE8vement"]},Account_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Courant","\xC9pargne","PEL","Titre","Professionnel"]},examples:["Courant","\xC9pargne","PEL"]},Risk_Score__c:{fieldType:"number",generator:"range",params:{min:0,max:100},examples:["15","42","78"]}}},{id:"startup-saas",name:"Startup SaaS",description:"SaaS company with subscriptions, MRR metrics, churn tracking.",industry:"Technology",locale:"en-US",dataPatterns:{Company_Name__c:{fieldType:"string",generator:"faker",params:{method:"company.name"},examples:["Acme Cloud","DataSync Pro","NeuralFlow AI"]},Plan__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{Free:.4,Starter:.25,Pro:.2,Enterprise:.15}},examples:["Free","Pro","Enterprise"]},MRR__c:{fieldType:"currency",generator:"range",params:{min:0,max:25e3,currency:"USD"},examples:["0.00","499.00","12500.00"]},Churn_Risk__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Low","Medium","High","Critical"]},examples:["Low","Medium","High"]},Active_Users__c:{fieldType:"number",generator:"range",params:{min:1,max:500},examples:["12","85","250"]},NPS_Score__c:{fieldType:"number",generator:"range",params:{min:-100,max:100},examples:["72","-15","45"]}}},{id:"immobilier",name:"Immobilier",description:"Agence immobili\xE8re avec biens, mandats et visites.",industry:"Real Estate",locale:"fr-FR",dataPatterns:{Property_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Appartement","Maison","Studio","Loft","Terrain","Local commercial"]},examples:["Appartement","Maison","Studio"]},Surface__c:{fieldType:"number",generator:"range",params:{min:15,max:300,unit:"m\xB2"},examples:["45","120","85"]},Price__c:{fieldType:"currency",generator:"range",params:{min:5e4,max:2e6,currency:"EUR"},examples:["185000","450000","1200000"]},City__c:{fieldType:"string",generator:"random_pick",params:{values:["Paris","Lyon","Marseille","Bordeaux","Toulouse","Nantes","Lille"]},examples:["Paris","Lyon","Bordeaux"]},Mandate_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Exclusif","Simple","Semi-exclusif"]},examples:["Exclusif","Simple","Semi-exclusif"]},DPE__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{A:.05,B:.1,C:.2,D:.3,E:.2,F:.1,G:.05}},examples:["C","D","B"]}}},{id:"education",name:"\xC9ducation",description:"Educational institution with students, courses, and grades.",industry:"Education",locale:"fr-FR",dataPatterns:{Student_ID__c:{fieldType:"string",generator:"sequence",params:{prefix:"STU-",padLength:6},examples:["STU-000001","STU-000002","STU-000003"]},FirstName:{fieldType:"string",generator:"faker",params:{method:"person.firstName",locale:"fr"},examples:["L\xE9a","Hugo","Emma"]},LastName:{fieldType:"string",generator:"faker",params:{method:"person.lastName",locale:"fr"},examples:["Bernard","Petit","Robert"]},Course_Name__c:{fieldType:"string",generator:"random_pick",params:{values:["Math\xE9matiques","Physique","Histoire","Anglais","Informatique","Philosophie"]},examples:["Math\xE9matiques","Physique","Informatique"]},Grade__c:{fieldType:"number",generator:"range",params:{min:0,max:20,precision:1},examples:["14.5","8.0","17.5"]},Semester__c:{fieldType:"picklist",generator:"random_pick",params:{values:["S1","S2","S3","S4","S5","S6"]},examples:["S1","S2","S3"]}}},{id:"logistique",name:"Logistique",description:"Logistics company with parcels, warehouses, and shipment tracking.",industry:"Logistics",locale:"fr-FR",dataPatterns:{Tracking_Number__c:{fieldType:"string",generator:"sequence",params:{prefix:"TRK-",padLength:10},examples:["TRK-0000000001","TRK-0000000002","TRK-0000000003"]},Status__c:{fieldType:"picklist",generator:"random_pick",params:{values:["En pr\xE9paration","Exp\xE9di\xE9","En transit","En livraison","Livr\xE9","Retourn\xE9"]},examples:["Exp\xE9di\xE9","En transit","Livr\xE9"]},Weight__c:{fieldType:"number",generator:"range",params:{min:.1,max:500,unit:"kg"},examples:["2.5","15.0","125.0"]},Warehouse__c:{fieldType:"string",generator:"random_pick",params:{values:["Paris-Nord","Lyon-Est","Marseille-Port","Bordeaux-Sud","Lille-Centre"]},examples:["Paris-Nord","Lyon-Est","Marseille-Port"]},Carrier__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Colissimo","Chronopost","DHL","FedEx","UPS","GLS"]},examples:["Colissimo","Chronopost","DHL"]},Delivery_Date__c:{fieldType:"date",generator:"relative_date",params:{minDaysFromNow:1,maxDaysFromNow:14},examples:["2026-03-01","2026-03-05","2026-03-12"]}}},{id:"rh",name:"Ressources humaines",description:"HR department with employees, leaves, payroll, and performance.",industry:"Human Resources",locale:"fr-FR",dataPatterns:{Employee_ID__c:{fieldType:"string",generator:"sequence",params:{prefix:"EMP-",padLength:5},examples:["EMP-00001","EMP-00002","EMP-00003"]},Department__c:{fieldType:"picklist",generator:"random_pick",params:{values:["R&D","Marketing","Ventes","RH","Finance","Support","Direction"]},examples:["R&D","Marketing","Finance"]},Contract_Type__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{CDI:.6,CDD:.2,Stage:.1,Alternance:.1}},examples:["CDI","CDD","Stage"]},Salary__c:{fieldType:"currency",generator:"range",params:{min:25e3,max:12e4,currency:"EUR"},examples:["35000","55000","85000"]},Leave_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Cong\xE9s pay\xE9s","RTT","Maladie","Sans solde","Maternit\xE9","Formation"]},examples:["Cong\xE9s pay\xE9s","RTT","Maladie"]},Leave_Days__c:{fieldType:"number",generator:"range",params:{min:.5,max:25},examples:["1","5","12"]}}},{id:"ong",name:"ONG/Association",description:"Non-profit organization with donors, campaigns, and volunteers.",industry:"Non-Profit",locale:"fr-FR",dataPatterns:{Donor_Type__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{Particulier:.7,Entreprise:.2,Fondation:.1}},examples:["Particulier","Entreprise","Fondation"]},Donation_Amount__c:{fieldType:"currency",generator:"range",params:{min:5,max:5e4,currency:"EUR"},examples:["25.00","150.00","5000.00"]},Campaign_Name__c:{fieldType:"string",generator:"ai_generate",params:{prompt:"Charity campaign name, inspiring and concise"},examples:["Solidarit\xE9 Hiver 2026","Course pour la Vie","Un Toit Pour Tous"]},Volunteer_Status__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Actif","Inactif","En formation","Suspendu"]},examples:["Actif","En formation","Inactif"]},Hours_Volunteered__c:{fieldType:"number",generator:"range",params:{min:1,max:200},examples:["8","40","120"]},Tax_Receipt__c:{fieldType:"boolean",generator:"weighted_pick",params:{values:{true:.8,false:.2}},examples:["true","false","true"]}}}],$a=class{customPersonas=new Map;customCounter=0;getBuiltInPersonas(){return[...VR]}getPersona(e){let t=VR.find(r=>r.id===e);return t||this.customPersonas.get(e)}async createCustomPersona(e,t){let r=TA(e),n=await t(r),o=PA(n);this.customCounter+=1;let i=`custom-${Date.now()}-${this.customCounter}`,a={id:i,name:o.name,description:o.description,industry:o.industry,locale:o.locale,dataPatterns:o.dataPatterns};return this.customPersonas.set(i,a),a}getCustomPersonas(){return Array.from(this.customPersonas.values())}},XR=kp(s=>typeof s=="string"&&s.trim().length>0?Number(s):s,Me().finite()),Mn=XR.optional().catch(void 0),Ql=L().min(1).optional().catch(void 0),Zl={faker:G({method:L().transform((s,e)=>{let t=zp(s);return t||(e.addIssue({code:Op.custom,message:`unknown faker method ${s}`}),vp)}),locale:Ql}),random_pick:G({values:ke(Sp([L(),Me(),ze()]).transform(String)).min(1)}),weighted_pick:G({values:Xs(L(),XR).refine(s=>Object.keys(s).length>0)}),range:G({min:Mn,max:Mn,currency:Ql}),sequence:G({prefix:Ql,start:Mn,step:Mn,padLength:Mn}),pattern:G({pattern:L().min(1)}),ai_generate:G({prompt:L().min(1)}),relative_date:G({minDaysFromNow:Mn,maxDaysFromNow:Mn})},AA={faker:'{ "method": one of the faker methods below, "locale" (optional): e.g. "fr_FR" }',random_pick:'{ "values": ["value1", "value2"] }',weighted_pick:'{ "values": { "value1": 0.7, "value2": 0.3 } }',range:'{ "min": number, "max": number, "currency" (optional): e.g. "EUR" }',sequence:'{ "prefix": "INV-", "start" (optional): integer, "step" (optional): integer }',pattern:'{ "pattern": a mask where # stands for a digit, e.g. "FR-#####" }',ai_generate:'{ "prompt": what to write in the field }, only on string and textarea fields',relative_date:'{ "minDaysFromNow": integer, "maxDaysFromNow": integer, negative for the past }'};function TA(s){let e=Object.keys(Zl);return["You are a data generation expert. Based on the following description, create a data generation persona for Salesforce.","",`Description: ${s}`,"","Respond with ONLY a JSON object in this exact format (no markdown, no extra text):","{",' "name": "Persona name",',' "description": "Brief description",',' "industry": "Industry name",',' "locale": "locale code (e.g. en-US, fr-FR)",',' "dataPatterns": {',' "FieldApiName": {',' "fieldType": "string|number|picklist|currency|date|boolean|textarea",',` "generator": "${e.join("|")}",`,' "params": the params of that generator, listed below,',' "examples": ["example1", "example2", "example3"]'," }"," }","}","","Params of each generator:",...e.map(r=>`- ${r}: ${AA[r]}`),"",`Faker methods: ${Wp.join(", ")}.`,"A pattern that uses another generator, another faker method or other params is discarded.","","Include at least 5 relevant field patterns for the described industry."].join(`
9
+ `)}function EA(s){let e=s.generator;if(typeof e!="string"||!Object.hasOwn(Zl,e))return null;let r=Zl[e].safeParse(s.params??{});if(!r.success)return null;let n=typeof s.fieldType=="string"?s.fieldType:"string";return e==="ai_generate"&&!Fp(n)?null:{fieldType:n,generator:e,params:r.data,examples:Array.isArray(s.examples)?s.examples.filter(o=>typeof o=="string"):[]}}function PA(s){let e;try{e=$p(Lp,s)}catch{throw new Error("AI response is not a valid JSON object. The AI model returned an unexpected format \u2014 try again or check the AI provider configuration.")}let t={};for(let[a,d]of Object.entries(e.dataPatterns))if(typeof d=="object"&&d!==null){let c=EA(d);c&&(t[a]=c)}let{name:r,description:n,industry:o,locale:i}=e;return{name:r,description:n,industry:o,locale:i,dataPatterns:t}}var Oo="SEED_WRITE_DECLINED",KR=6e4;function $r(s){let e=s?.read.gate.audit;return e===void 0?{}:{details:{deliverability:e,...s?.accepted===!0?{confirmed:"emails"}:{}}}}var ZR="the checkpoints of this window are not open to the Seed page",Nt=class extends Error{constructor(t,r,n){super(r);this.code=t;this.refusal=n;this.name="SeedCheckpointStopped"}code;refusal};async function vs(s,e){try{if(!s)throw new Error(ZR);return{ask:e,planned:await s.scope(e,{})}}catch(t){throw new Nt(tn,ar(t))}}async function Ss(s,e,t,r,n){let o=await Gi(async()=>{if(!s)throw new Error(ZR);return s.take(e.ask,{runId:t},{planned:e.planned,signal:r,onProgress:({percentage:i,processedObjects:a,totalObjects:d})=>n(Math.round(i),a,d,co(i))})});if("stop"in o)throw new Nt(o.stop.code,o.stop.message,o.stop.refusal);return o.checkpoint}async function ln(s,e,t,r,n){if(!(!e||!s))try{return await s.settle(e,t)}catch(o){return r(`[WARN] ${n}: the checkpoint '${e.name}' taken before the run is kept: `+T(o)),e}}function ks(s,e){let t=new Set(s);return(r,n)=>t.has(r)&&(n==="insert"||e&&n==="update")}function _a(s,e){return typeof s.unread=="string"?{firing:[]}:Ar(s,void 0,e)}function CA(s,e,t){return t==="refuse"?{code:yt.unanswered,message:`The seed needed an answer before it wrote \u2014 ${e} delivers the emails what still runs sends, or would not say whether it does \u2014 and no Approval step before it approved the run: put one before it. Nothing was written.`}:{code:iw,message:s.gate.stop?.message??"The seed was refused for its emails. Nothing was written."}}var DA={ask:(s,e)=>s.confirmRun(e),unanswered:"goOn"};function xA(s,e){let t=[];return s.check.verdict==="unread"&&t.push(`the data storage ${e} has left could not be read (${s.check.unread})`),s.api.verdict==="near"&&t.push(`it would leave ${e} ${s.api.remaining-s.api.estimate} of its ${s.api.max} daily API requests`),t.join(", and ")}function YR(s,e,t){if(Ko(s))return t(`[OFFLINE] seed NOT queued for replay (inserts are not idempotent): ${e}`),{offlineReplayAvailable:!1,retryHint:"Seed operations are not queued for offline replay (inserts are not idempotent \u2014 replaying could duplicate records). Re-run the template manually once the org is reachable again."}}var La=1e3;function MA(s){return Array.isArray(s.objectResults)?{...s,objectResults:s.objectResults.map(e=>{let t=e.createdIds.length>La||e.errors.length>La;return t?{...e,createdIds:e.createdIds.slice(0,La),errors:e.errors.slice(0,La),truncated:t}:e})}:s}function QR(s){return{query:async e=>s.tooling.query(e),queryMore:async e=>s.tooling.queryMore(e)}}function jA(s){return s.objectResults.flatMap(t=>t.errors)[0]??"The seed wrote no records."}var NA=new Set(["seed:execute","seed:automation","seed:describe-global","seed:describe-object","seed:template:save","seed:template:load","seed:template:list","seed:template:delete","seed:list-personas","seed:create-persona","seed:scenario:packs","seed:scenario:prepare","seed:scenario:execute","seed:scenario:agents","seed:scenario:save","seed:scenario:test-file"]),Fa=class{constructor(e){this.deps=e;this.seedTemplateStore=new xn(e.configStore),this.templateManager=new Na(()=>crypto.randomUUID(),()=>new Date().toISOString(),this.seedTemplateStore),this.personaManager=new $a}deps;seedTemplateStore;templateManager;personaManager;registry;liveTracker;runCreations;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}setRunCreations(e){this.runCreations=e}runningRuns=new Set;isRunning(e){return this.runningRuns.has(e)}setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-4XZ5YT5O.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}readAutomation(e,t,r,n,o,i,a){let d=this.targetAutomation;return la({org:n,objects:r,writes:o,readAutomation:c=>i===void 0?new ge(KR).withTimeout("seed automation",()=>d.read(e,c)):typeof i.unread=="string"?Promise.reject(new Error(i.unread)):Promise.resolve(i),readLimits:()=>cr(t),...a?{deliverability:a}:{},...i===void 0?{readDeliverability:()=>Ee(this.deps.orgManager.getOrg(e))==="production"?Promise.resolve(Mt):jt(t)}:{}})}setMuteLeases(e){this.muteLeases=e}muteLeases={};setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;checkpointProgress(e){return(t,r,n,o)=>{$e(this.deps,e,t,r,n,o),this.liveTracker?.updateProgress(e,t,r,n,o)}}async handleAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Ff,e,"seed:automation:error",this.deps);if(t)try{let r=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),n=this.deps.orgManager.getOrg(t.orgId),o=await this.readAutomation(t.orgId,r,t.objects,Re(n,t.orgId),Wb(t.objects,t.publishes===!0));if("error"in o)throw new Error(o.error);let i=A(this.deps,e,"seed:automation:response",{orgId:t.orgId,objects:t.objects,preview:o.preview});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(r){P(this.deps,"seed:automation","seed:automation:error",e,r,{retryable:!0})}}async handle(e){if(!NA.has(e.type))return!1;switch(e.type){case"seed:describe-global":return await this.handleDescribeGlobal(e),!0;case"seed:describe-object":return await this.handleDescribeObject(e),!0;case"seed:execute":return await this.handleExecute(e),!0;case"seed:automation":return await this.handleAutomation(e),!0;case"seed:template:save":return await this.handleTemplateSave(e),!0;case"seed:template:load":return await this.handleTemplateLoad(e),!0;case"seed:template:list":return await this.handleTemplateList(e),!0;case"seed:template:delete":return await this.handleTemplateDelete(e),!0;case"seed:list-personas":return await this.handleListPersonas(e),!0;case"seed:create-persona":return await this.handleCreatePersona(e),!0;case"seed:scenario:packs":return await this.handleScenarioPacks(e),!0;case"seed:scenario:prepare":return await this.handleScenarioPrepare(e),!0;case"seed:scenario:execute":return await this.handleScenarioExecute(e),!0;case"seed:scenario:agents":return await this.handleScenarioAgents(e),!0;case"seed:scenario:save":return await this.handleScenarioSave(e),!0;case"seed:scenario:test-file":return await this.handleScenarioTestFile(e),!0;default:return!1}}workspaceFolders(){return this.deps.services?.getWorkspaceFolders?.()??[]}answerScenario(e,t,r){let n=A(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}async handleScenarioPacks(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!!D(Bf,e,"seed:error",this.deps))try{let{listScenarioPacks:t,nodeScenarioPackFiles:r}=await import("./chunk-TQX3PURV.mjs"),n=this.workspaceFolders(),o=await t(r(),n);this.answerScenario(e,"seed:scenario:packs:response",{packs:o,workspace:n.length>0})}catch(t){P(this.deps,"seed:scenario:packs","seed:error",e,t)}}async handleScenarioPrepare(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(qf,e,"seed:error",this.deps);if(t)try{let r=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),{prepareScenario:n,readScenarioCaseStatus:o,scenarioKnowledge:i}=await import("./chunk-5MMXFWPD.mjs"),{seedObjectAccess:a}=await import("./chunk-4NAHW2D3.mjs"),d=await o(async u=>(await r.query(u)).records),c=await i(a(r),u=>r.describe(u)),l=n(t.pack,{caseStatus:d,knowledge:c,...t.seed!==void 0?{seed:t.seed}:{},...t.articleBodyField!==void 0?{articleBodyField:t.articleBodyField}:{}});this.answerScenario(e,"seed:scenario:prepare:response",{...l})}catch(r){P(this.deps,"seed:scenario:prepare","seed:error",e,r,{retryable:!0})}}async handleScenarioExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Wf,e,"seed:error",this.deps);if(!t)return;let{compileScenario:r,ScenarioCompileError:n}=await import("./chunk-3CA767QB.mjs"),o;try{o=r(t.pack,t.options)}catch(a){if(!(a instanceof n))throw a;P(this.deps,"seed:scenario:execute","seed:error",e,a,{code:"SCENARIO_INVALID",retryable:!1});return}let i=ro.safeParse(o.template);if(!i.success){P(this.deps,"seed:scenario:execute","seed:error",e,new Error(`The scenario compiled to a template the seed refuses: ${i.error.issues[0]?.message??"invalid"}`),{code:"SCENARIO_INVALID",retryable:!1});return}await this.runAsked(e,{orgId:t.orgId,template:i.data,...t.locale!==void 0?{locale:t.locale}:{},...t.muteAutomation!==void 0?{muteAutomation:t.muteAutomation}:{},...t.checkpointFirst?{checkpointFirst:t.checkpointFirst}:{}},{pack:t.pack,options:t.options,compiled:o})}async keepScenario(e,t,r){let{compiled:n,pack:o}=t,i=n.tests.filter(u=>u.openCase!==void 0),a=new Set(i.map(u=>u.openCase?.caseKey)),d=Object.keys(r).filter(u=>a.has(u)).length,c={packId:o.id,packName:o.name,tests:n.tests.length,openCasesWritten:d,openCases:a.size};if(d===0)return{...c,companion:{kind:"none"}};let l=this.runCreations;if(!l)return{...c,companion:{kind:"failed",message:"The runs are not kept in this window."}};try{let{nodeScenarioSidecarFiles:u,scenarioRunSidecar:p,writeScenarioRunSidecar:g}=await import("./chunk-H2PJNIYJ.mjs");return await g(u(),l.storagePath,p({runId:e.operationId,pack:o,compiled:n,options:t.options,caseIds:r})),{...c,companion:{kind:"kept"}}}catch(u){let p=T(u);return this.deps.log(`[WARN] seed:scenario:execute ${e.operationId}: the companion file could not be written, so its test file cannot be: ${p}`),{...c,companion:{kind:"failed",message:p}}}}async handleScenarioAgents(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(zf,e,"seed:error",this.deps);if(t)try{let r=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),{readAgentCatalog:n}=await import("./chunk-7UQD6V6F.mjs"),{scenarioCasePicklists:o,toolingQueryAll:i}=await import("./chunk-5MMXFWPD.mjs"),{scenarioProjectOf:a}=await import("./chunk-K22PA4XL.mjs"),d=await n(i(QR(r))),c=await o(l=>r.describe(l));this.answerScenario(e,"seed:scenario:agents:response",{orgId:t.orgId,agents:d.kind==="agents"?{kind:"agents",agents:d.catalog.agents}:d,project:await a(this.workspaceFolders()),...c?{casePicklists:c}:{}})}catch(r){P(this.deps,"seed:scenario:agents","seed:error",e,r,{retryable:!0})}}async handleScenarioSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Gf,e,"seed:error",this.deps);if(t)try{let{nodeScenarioPackFiles:r,saveScenarioPack:n}=await import("./chunk-TQX3PURV.mjs"),o=await n(r(),this.workspaceFolders(),t.pack,t.overwrite===!0);this.answerScenario(e,"seed:scenario:save:response",{outcome:o})}catch(r){P(this.deps,"seed:scenario:save","seed:error",e,r)}}async handleScenarioTestFile(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Jf,e,"seed:error",this.deps);if(!t)return;let r=n=>this.answerScenario(e,"seed:scenario:test-file:response",{runId:t.runId,outcome:n});try{let n=this.runCreations,o=n?await n.get(t.runId):void 0,i=o?this.deps.orgManager.getOrg(o.targetOrgId):void 0;if(!n||!o||!i){r({kind:"unavailable",reason:"run-unknown",message:o?"The org this run wrote to is no longer connected to SandForge.":"Nothing of this run is kept any more."});return}let a=await B(o.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),{readAgentCatalog:d}=await import("./chunk-7UQD6V6F.mjs"),{nodeAgentTestSpecFiles:c}=await import("./chunk-3DCUADVK.mjs"),{toolingQueryAll:l}=await import("./chunk-5MMXFWPD.mjs"),{findScenarioPack:u,nodeScenarioPackFiles:p}=await import("./chunk-TQX3PURV.mjs"),{nodeScenarioSidecarFiles:g}=await import("./chunk-H2PJNIYJ.mjs"),{scenarioProjectOf:h,writeRunTestFile:f}=await import("./chunk-K22PA4XL.mjs"),m=this.workspaceFolders(),y=await f({sidecar:g(),spec:c()},{runId:t.runId,storagePath:n.storagePath,project:await h(m),alias:Re(i,o.targetOrgId),choice:t.choice,...t.overwrite!==void 0?{overwrite:t.overwrite}:{},readCatalog:()=>d(l(QR(a))),findPack:(w,v)=>u(p(),m,w,v)});r(y)}catch(n){P(this.deps,"seed:scenario:test-file","seed:error",e,n,{retryable:!0})}}async handleTemplateSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Uf,e,"seed:error",this.deps);if(t)try{let r=t.template;if(r.id&&this.templateManager.get(r.id)){let n=this.templateManager.update(r.id,r),o=A(this.deps,e,"seed:template:save:response",{success:!0,id:n.id});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}else{let n=this.templateManager.create(r),o=A(this.deps,e,"seed:template:save:response",{success:!0,id:n.id});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}}catch(r){P(this.deps,"seed:template:save","seed:error",e,r)}}async handleTemplateLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(rl,e,"seed:error",this.deps);if(t)try{let r=this.seedTemplateStore.load(t.id),n=A(this.deps,e,"seed:template:load:response",{template:r??null});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){P(this.deps,"seed:template:load","seed:error",e,r)}}async handleTemplateList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let r=this.seedTemplateStore.list().map(o=>({id:o.id,name:o.name,description:o.description,tags:o.tags,updatedAt:o.updatedAt,objectCount:o.objects.length,totalRecords:o.objects.reduce((i,a)=>i+a.recordCount,0)})),n=A(this.deps,e,"seed:template:list:response",{templates:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(t){P(this.deps,"seed:template:list","seed:error",e,t)}}async handleTemplateDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(rl,e,"seed:error",this.deps);if(t)try{let r=this.seedTemplateStore.delete(t.id),n=A(this.deps,e,"seed:template:delete:response",{success:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){P(this.deps,"seed:template:delete","seed:error",e,r)}}async handleListPersonas(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.personaManager.getBuiltInPersonas(),r=this.personaManager.getCustomPersonas(),n=[...t,...r].map(i=>({id:i.id,name:i.name,description:i.description,industry:i.industry,locale:i.locale,dataPatterns:i.dataPatterns})),o=A(this.deps,e,"seed:list-personas:response",{personas:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(t){P(this.deps,"seed:list-personas","seed:error",e,t)}}async handleCreatePersona(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Hf,e,"seed:error",this.deps);if(t)try{let r=t;if(!r.description||r.description.trim().length===0){let c=A(this.deps,e,"seed:create-persona:response",{persona:{id:"",name:"",description:"",industry:"",locale:"",dataPatterns:{}},success:!1,error:"Description is required to create a custom persona"});this.deps.broker.postToWebview(c);return}let n=this.deps.services;if(!n?.isAIEnabled())throw new Error("AI is disabled. Enable sandforge.ai.enabled and add your Anthropic API key in SandForge Settings > AI > API key to create custom personas.");let o=async c=>(await n.aiClient().chat({messages:[{role:"user",content:c}]})).text,i=await this.personaManager.createCustomPersona(r.description,o),a={id:i.id,name:i.name,description:i.description,industry:i.industry,locale:i.locale,dataPatterns:i.dataPatterns},d=A(this.deps,e,"seed:create-persona:response",{persona:a,success:!0});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(r){P(this.deps,"seed:create-persona","seed:error",e,r)}}buildSeedCallAI(){let e=this.deps.services;return e?.isAIEnabled()?async t=>{try{return(await e.aiClient().chat({messages:[{role:"user",content:t}]})).text}catch(r){return this.deps.log(`[AI] seed data generation failed, falling back to faker: ${T(r)}`),"[]"}}:async()=>"[]"}async handleDescribeGlobal(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Lf,e,"seed:error",this.deps);if(!t)return;let r=t,n=st(this.deps);try{let o=await B(r.orgId,this.deps.orgRegistry,this.deps.orgManager),d=(await new ge(n.timeouts.describeGlobal).withTimeout("describe-global",()=>o.describeGlobal())).sobjects.filter(l=>l.createable).filter(l=>!ei(l.name)).map(l=>({apiName:l.name,label:l.label,recordCount:0,dependencies:[]})),c=A(this.deps,e,"seed:describe-global:response",{objects:d});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(o){P(this.deps,"seed:describe-global","seed:error",e,o)}}async handleDescribeObject(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(_f,e,"seed:error",this.deps);if(!t)return;let r=t,n=st(this.deps);try{let o=await B(r.orgId,this.deps.orgRegistry,this.deps.orgManager),i=pt(r.objectApiName),d=await new ge(n.timeouts.describe).withTimeout("describe-object",()=>o.describe(i)),c=d.fields.filter(p=>p.createable).map(p=>({fieldApiName:p.name,label:p.label,type:p.type,required:!p.nillable&&!p.defaultedOnCreate,picklistValues:p.picklistValues?.map(g=>g.value)??[],referenceTo:p.referenceTo??[],length:p.length,integerDigits:Gp(p),objectApiName:r.objectApiName})),l=Ub(i,d.recordTypeInfos,i===Zn?await $l(o):[]),u=A(this.deps,e,"seed:describe-object:response",{objectApiName:r.objectApiName,objectLabel:d.label,fields:c,recordTypes:l});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(o){P(this.deps,"seed:describe-object","seed:error",e,o)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D($f,e,"seed:error",this.deps);if(!t)return;let r=t;if(r.dryRun===!0){P(this.deps,"seed:execute","seed:error",e,new Error('Seed has no dry run: remove "dryRun" from this request to run the seed.'),{code:"DRY_RUN_UNSUPPORTED",retryable:!1});return}await this.runAsked(e,r)}async runAsked(e,t,r){let n=e.id,o={module:"seed",operation:e.type};try{let i=await this.clearSeed(t,n,o,DA,r!==void 0);if("refusal"in i){let{refusal:l}=i;P(this.deps,"seed:execute","seed:error",e,new Error(l.message),{code:l.code,retryable:!1,...l.extraPayload?{extraPayload:l.extraPayload}:{}}),l.failed&&Le(this.deps,n,l.message,!1,{context:o,...l.failed.authored?{authored:!0}:{}});return}let a=r?`Seed of the scenario ${r.pack.name}`:"Seed data generation",{abortController:d,execution:c}=this.beginSeed(e,i,n,o,a,void 0,r);this.registry?this.registry.register(n,"seed",a,c,d):await c}catch(i){this.deps.infraServices?.performanceTracker?.complete(n),this.liveTracker?.fail(n,T(i));let a=YR(i,n,this.deps.log);P(this.deps,"seed:execute","seed:error",e,i,{code:to(i),retryable:!0,extraPayload:a}),Le(this.deps,n,T(i),!0,{extraPayload:a,context:o})}}async clearSeed(e,t,r,n,o=!1){let i=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200,a=e.template.objects.map(ne=>({...ne,batchSize:ne.batchSize??i}));Object.assign(r,Er(a));let d=await B(e.orgId,this.deps.orgRegistry,this.deps.orgManager),c={...e.template,objects:a},l=c.objects.some(ne=>ne.objectApiName===Zn)?Hb(c,await $l(d)):{template:c,personObjects:[]};if("refusal"in l)return{refusal:{code:"RECORD_TYPES_MIXED",message:l.refusal}};let u={orgId:e.orgId,template:l.template,personObjects:l.personObjects,locale:await Bb(e.locale,d)},p=e.template.objects.reduce((ne,ce)=>ne+ce.recordCount,0),g=[],h=ne=>{g.push(ne),this.deps.log(`[WARN] seed:execute ${t}: ${ne}`)},f=this.deps.orgManager.getOrg(u.orgId),m=Re(f,u.orgId),y=l.template.objects.map(ne=>({objectApiName:ne.objectApiName,recordCount:ne.recordCount})),w=this.targetAutomation,v=await new ge(KR).withTimeout("seed automation",()=>w.read(u.orgId,y.map(ne=>ne.objectApiName))).catch(ne=>({unread:T(ne)})),R=qb(l.template,o),b;if("muteAutomation"in e&&e.muteAutomation===!0)try{b=await mt(async()=>Et(d),v,{...this.muteLeases,writes:R})}catch(ne){if(!kt(ne))throw ne;return X(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",code:ne.code}),{refusal:{code:ne.code,message:ne.message,extraPayload:{},failed:{authored:!0}}}}b&&(u.mute=b);let O=Jb(e.fit,p);O&&(u.fit=O);let k=zb(v,b?.plan,R),S=await Vt({read:v,...b?.plan?{plan:b.plan}:{},writes:R,readDeliverability:()=>Ee(f)==="production"?Promise.resolve(Mt):jt(d),accepted:!1,target:m,run:"seed",keepsAddresses:!0}),E={read:S,accepted:!1};u.emails=E;let I=S.gate.verdict==="asks",C;if(e.checkpointFirst!==void 0){let ne={module:"seed",orgId:u.orgId,operationId:t,written:y.filter(ce=>ce.recordCount>0).map(ce=>ce.objectApiName),running:k.running??{firing:[]},request:e.checkpointFirst};try{C=await vs(this.beforeRunCheckpoints,ne)}catch(ce){if(!(ce instanceof Nt))throw ce;return X(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",code:ce.code}),{refusal:{code:ce.code,message:ce.message,extraPayload:{},failed:{authored:!0}}}}}let{seedObjectAccess:F,templateTheOrgTakes:Y}=await import("./chunk-4NAHW2D3.mjs"),z=await Y(l.template,F(d)),te=Eb(Qo(this.deps.services),l.template),{describedFieldsOf:H,requiredForAccountKinds:x}=await import("./chunk-XBG5SP6Q.mjs"),j=0,K=H(async ne=>(j++,d.describe(ne))),Q=await Tb(z,{describeCreateableFields:K.createable,describeRequiredFields:x(K,l.personObjects)},te),_={duplicateRules:fo(v),partition:te,slices:Q,slicesRead:j,bulkThreshold:st(this.deps).bulk.threshold,automationRead:nn(v)},V=await xb(d,z,l.personObjects,Re(f,u.orgId),C?.planned,{...on(S.ofRun),...Ty(b?.plan)},_);if(V.check.verdict==="unread"&&h(`the data storage the org has left could not be read (${V.check.unread}): whether the records fit is not known`),V.refusal){let ne=V.refusedFor==="checkpoint",ce=ne?tn:V.refusedFor==="apiRequests"?lo:Nl,we=ne?V.checkpointRefusal?.code:void 0;X(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",code:ce,...we!==void 0?{details:{checkpointRefusal:we}}:{}});let le=V.check,Se=ne?void 0:Gb(Mb(V),z,l.personObjects,k.room,_);return{refusal:{code:ce,message:V.refusal,extraPayload:{...le.verdict==="unread"||ce!==Nl?{}:{estimateMB:Number(hs(le.estimateMB)),remainingMB:le.remainingMB,maxMB:le.maxMB,org:Re(f,u.orgId)},...we!==void 0?{checkpointRefusal:we}:{},...Se?{fit:Se}:{}},failed:{authored:!0}}}}let ue=await this.readAutomation(u.orgId,d,y.map(ne=>ne.objectApiName),m,R,b?.automation??v,S.gate.deliverability),me=ua(ue,y,m);for(let ne of me.unknown??[])h(ne);if(me.refusal)return X(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",code:Ll}),{refusal:{code:Ll,message:me.refusal,extraPayload:me.figures?{...me.figures}:{},failed:{authored:!0}}};let re=this.deps.infraServices?.productionGuard;if(!re)return X(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",code:ve.code}),{refusal:{code:ve.code,message:ve.message,failed:{authored:!1}}};let ie={orgId:u.orgId,orgTier:Ee(f),operation:"insert",objectName:"SeedData",recordCount:p,module:"seed"},{check:Be,decision:fe}=await Ke(re,ie);if((fe==="refused"||fe==="declined")&&X(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",guard:fe}),fe==="refused")throw Jr(Be.blockedReason??Be.impactSummary);if(fe==="declined")return{refusal:{code:St.declined,message:"Operation cancelled by user (confirmation declined).",failed:{authored:!1}}};if(V.check.verdict==="unread"||V.api.verdict==="near"||C!==void 0||I){let ne=await n.ask(re,{stage:"write",module:"seed",org:m,orgTier:Ee(f),objects:l.template.objects.map(ce=>({objectApiName:ce.objectApiName,rows:ce.recordCount})).sort((ce,we)=>we.rows-ce.rows),total:p,storage:sn(V.check),counted:!0,...uo(V.api),...C?{checkpoint:C.planned}:{},...S.gate.confirmation});if(ne==="confirmed"&&I&&(E.accepted=!0),ne==="declined")return X(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",guard:fe,code:Oo,...$r(E)}),{refusal:{code:Oo,message:"The seed was cancelled before it wrote anything. Nothing was written.",failed:{authored:!0}}};if(ne==="unavailable"&&I){let ce=CA(S,m,n.unanswered);return X(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",guard:fe,code:ce.code,...$r(E)}),{refusal:{...ce,failed:{authored:!0}}}}if(ne==="unavailable"&&C!==void 0)return X(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",guard:fe,code:yt.unanswered}),{refusal:{code:yt.unanswered,message:`The seed needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${m} \u2014 and there was no one to ask. Nothing was written.`,failed:{authored:!0}}};if(ne==="unavailable"&&n.unanswered==="refuse")return X(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",guard:fe,code:yt.unanswered}),{refusal:{code:yt.unanswered,message:`The seed needed an answer before it wrote \u2014 ${xA(V,m)} \u2014 and no Approval step before it approved the run: put one before it. Nothing was written.`,failed:{authored:!0}}};ne==="unavailable"&&this.deps.log(`[WARN] seed:execute ${t}: nobody could be asked about the storage or the API requests the org has left; the seed goes on`)}return{conn:d,run:u,plannedRecords:p,guardDecision:fe,automation:ue,orgName:m,warnings:g,...C?{checkpoint:C}:{}}}beginSeed(e,t,r,n,o,i,a){this.deps.infraServices?.performanceTracker?.start(r,"seed"),We(this.deps,r,"seed",o),this.liveTracker?.register(r,"seed",o,t.plannedRecords);let d=new AbortController,c=this.executeSeed(e,t.conn,t.run,r,d,n,t.guardDecision,i,a,t.checkpoint);return{abortController:d,execution:c}}async seedForPipeline(e,t){let r=this.deps.orgManager.getOrg(e.orgId);if(!r)throw cn(yt.orgUnknown,`The org the seed writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was written.`);let n=GR(Ee(r),e.answer,Re(r,e.orgId));if(n)throw n;let o=ja(e.orgId,e.templateId,l=>this.seedTemplateStore.load(l));if("refusal"in o)throw o.refusal;let i=Sn("seed:pipeline",crypto.randomUUID(),"seed:execute"),a=i.id,d={module:"seed",operation:i.type},c={ask:()=>Promise.resolve(e.answer.approved?"confirmed":"unavailable"),unanswered:"refuse"};return Mi(e.answer,async()=>{let l=await this.clearSeed(o.asked,a,d,c);if("refusal"in l)throw cn(l.refusal.code,l.refusal.message);if(t?.aborted)throw X(this.deps,{action:"seed_execute",module:"seed",operationId:a,orgId:e.orgId,outcome:"stopped",guard:l.guardDecision,code:gt}),new xt("The seed was cancelled before it wrote anything. Nothing was written.");let u=Vb(l.automation,l.orgName);for(let w of u)this.deps.log(`[INFO] seed:execute ${a}: ${w}`);let p,g=`Pipeline seed of ${o.asked.template.name}`,{abortController:h,execution:f}=this.beginSeed(i,l,a,d,g,{pipeline:e.pipeline,ended:w=>{p=w}});this.registry?.register(a,"seed",g,f,h);let m=()=>{this.registry?this.registry.abort(a):h.abort()};t?.addEventListener("abort",m,{once:!0});try{await f}finally{t?.removeEventListener("abort",m)}let y=p;if(y===void 0)throw new Error("The seed ended without a result.");if("error"in y)throw y.error instanceof Error?y.error:new Error(T(y.error));return{operationId:a,runId:y.result.operationId,result:y.result,automation:u,warnings:l.warnings}})}async executeSeed(e,t,r,n,o,i,a,d,c,l){let u=st(this.deps),p=new Date().toISOString(),g,h=!1,f={},m=r.template.name,y={origin:"generator",...typeof m=="string"?{label:m}:{}};try{let w=nr(this.deps),v=new Qi({retryConfig:u.retry,signal:o.signal,onRetry:(de,be,Ce)=>{this.deps.log(`[RETRY] seed insert attempt=${de} code=${be.originalError.statusCode} delay=${Ce}ms`)}}),R=this.deps,b=crypto.randomUUID(),O=this.runCreations?.recorder({runId:b,targetOrgId:r.orgId,startedAt:p,...d?{pipeline:d.pipeline}:{}});lr(O,()=>t.identity(),`seed:execute ${n}`);let k={base:0,total:0},S=(de,be,Ce)=>{let tt=k.base+de,_e=Math.max(k.total,tt,be,1),Ue=Math.round(tt/_e*100);$e(R,n,Ue,tt,_e,Ce),this.liveTracker?.updateProgress(n,Ue,tt,_e,Ce)},E=lb({conn:t,bulkThreshold:u.bulk.threshold,bulkManager:w,retry:v,signal:o.signal,label:`seed:execute ${n}`,log:de=>this.deps.log(de),onProgress:S,...O?{calls:{sending:(de,be,Ce)=>O.sending(de,be,Ce),answered:(de,be)=>O.answered(de,be)}}:{}}),I=async(de,be,Ce,tt)=>{Ce.length>0&&(h=!0);let _e=await E(de,be,Ce,tt);return O?.note(be,_e.successIds),_e},C=de=>this.deps.log(`[WARN] seed:execute ${n}: what the run created could not all be kept, so removing it may leave some of it in the org: ${T(de)}`),{SeedValidator:F}=await import("./chunk-BN7A4GRQ.mjs"),{DataPlanBuilder:Y}=await import("./chunk-J7HVXMSW.mjs"),{FieldMapper:z}=await import("./chunk-DLDX6RRC.mjs"),{ReferenceLinker:te}=await import("./chunk-NZ5ZZLKS.mjs"),{AIDataGenerator:H}=await import("./chunk-HCIDVIOW.mjs"),{FakerFallback:x}=await import("./chunk-3SRXFZSD.mjs"),{readExistingParentIds:j,readPresentParentIds:K}=await import("./chunk-P2PJYWGQ.mjs"),{seedObjectAccess:Q}=await import("./chunk-4NAHW2D3.mjs"),{describedFieldsOf:_,requiredForAccountKinds:V}=await import("./chunk-XBG5SP6Q.mjs"),{seedTargetOf:ue}=await import("./chunk-QPF6C5MX.mjs"),me=c?(await import("./chunk-BILZ3SSR.mjs")).seedKnowledge:void 0,re=new H(this.buildSeedCallAI()),ie=new x(r.locale),Be=new z({aiGenerator:re,fakerFallback:ie}),fe=new te,ne=new F,ce=new Y,{SeedGrappeAdapter:we}=await import("./chunk-PTTHSSQO.mjs"),le=Qo(this.deps.services),Se=_(de=>t.describe(de)),je={validator:ne,describeCreateableFields:Se.createable,describeVisibleFields:Se.visible,describePicklistValues:Se.picklistValues,describeFieldLengths:Se.lengths,describeRequiredFields:V(Se,r.personObjects),objectAccess:Q(t),readExistingParentIds:(de,be,Ce)=>j(t,de,be,Ce),readPresentParentIds:(de,be)=>K(t,de,be),describeKeyPrefix:Se.keyPrefix,...ue(t),planBuilder:ce,fieldMapper:Be,referenceLinker:fe,insert:I,generateId:()=>crypto.randomUUID(),now:()=>new Date().toISOString(),services:this.deps.services,grappeAdapter:new we(()=>crypto.randomUUID(),le?.grappeSize),grappeConfig:le,onGrappeEvent:de=>fi(this.deps,de),onProgress:de=>{k.base=de.processedRecords,k.total=de.totalRecords,S(0,de.totalRecords,`Insert ${de.objectApiName}`)},signal:o.signal,...c&&me?{onRowIds:(de,be)=>{de==="Case"&&Object.assign(f,be)},knowledge:me({org:t,plan:{publish:!0,links:c.compiled.closedCaseArticles},...O?{journal:O}:{},signal:o.signal})}:{}};if(!this.deps.services)throw new Error("SeedOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let M=this.deps.services.seedOrchestrator(je),N=r.template;$e(this.deps,n,0,0,1,"Validating template and building plan");let U;this.runningRuns.add(b);let W=r.mute,ae=W?.muted;try{l&&(g=await Ss(this.beforeRunCheckpoints,l,b,o.signal,this.checkpointProgress(n)),O?.checkpoint?.(g));let de=W?.prepared?await W.prepared.acquire(b):void 0;de&&(ae=de.outcome);let be=de&&r.emails?r.emails.read.afterLease(de.outcome,r.emails.accepted):void 0;if(de&&be)throw ae=await de.release(),new Nt(be.code,be.message);U=await M.execute(N,r.orgId,b).finally(async()=>{de&&(ae=await de.release())}),ae&&(U={...U,mutedAutomation:ae});let Ce=await ln(this.beforeRunCheckpoints,g,h,this.deps.log,`seed:execute ${n}`);g=void 0,Ce&&(U={...U,checkpoint:Ce})}catch(de){throw await O?.end({status:"failure",finishedAt:new Date().toISOString(),objectResults:[]}).catch(C),this.runningRuns.delete(b),de}await O?.end({finishedAt:new Date().toISOString(),status:U.status,...U.cancelled?{cancelled:!0}:{},objectResults:U.objectResults}).catch(C),c&&(U={...U,scenario:await this.keepScenario(U,c,f)}),this.runningRuns.delete(b),U.cancelled||$e(this.deps,n,100,1,1,"Seed complete");let q=U.totalRecordsCreated;this.deps.infraServices?.performanceTracker?.update(n,q,1),this.deps.infraServices?.performanceTracker?.complete(n),U.cancelled?(this.registry?.abort(n),pe(this.deps,n,{aborted:!0,totalRecords:q}),this.liveTracker?.cancel(n)):(pe(this.deps,n,{status:U.status,totalRecords:q}),U.status==="failure"?this.liveTracker?.fail(n,jA(U)):U.status==="partial"?this.liveTracker?.partial(n):this.liveTracker?.complete(n));let he=U.objectResults.some(de=>de.recordsCreated+de.recordsFailed>0),Fe=U.cancelled===!0?he?"cancelled":"stopped":U.status;X(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:Fe,...Fe==="stopped"?{code:Ze}:{},guard:a,objects:U.objectResults.map(de=>({...at(de.objectApiName),created:de.recordsCreated,failed:de.recordsFailed})),source:y,...U.mutedAutomation?{muted:ot(U.mutedAutomation)}:{},...U.checkpoint?.state==="taken"?{checkpointId:U.checkpoint.checkpointId}:{},...r.fit?{fit:r.fit}:{},...$r(r.emails)});let Te=A(this.deps,e,"seed:execute:response",MA(U));if(this.deps.broker.postToWebview(Te),this.deps.log(`[TX] ${Te.type} id=${Te.id}`),d?.ended({result:U}),U.status==="failure"&&!U.cancelled)return{status:"failure"}}catch(w){this.deps.infraServices?.performanceTracker?.complete(n);let v=await ln(this.beforeRunCheckpoints,g,h,this.deps.log,`seed:execute ${n}`),R=v?.state==="deleted"?`${T(w)} ${xr}`:void 0,b=R!==void 0?new Error(R):w;if(w instanceof Nt){if(w.code===Ze)this.registry?.abort(n),pe(this.deps,n,{aborted:!0,totalRecords:0}),this.liveTracker?.cancel(n);else{let E=T(b);this.liveTracker?.fail(n,E),Le(this.deps,n,E,!1,{context:i,authored:!0})}let S=w.refusal?.code;return X(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:"stopped",guard:a,code:w.code,...S!==void 0||r.emails?.read.gate.audit!==void 0?{details:{...$r(r.emails).details,...S!==void 0?{checkpointRefusal:S}:{}}}:{}}),P(this.deps,"seed:execute","seed:error",e,b,{code:w.code,retryable:!1,...S!==void 0?{extraPayload:{checkpointRefusal:S}}:{}}),d?.ended({error:w}),w.code===Ze?void 0:{status:"failure"}}this.liveTracker?.fail(n,T(b));let O=kt(w)?w:void 0;X(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:O?"stopped":"failure",guard:a,source:y,...O?{code:O.code}:{},...v?.state==="taken"?{checkpointId:v.checkpointId}:{},...r.fit?{fit:r.fit}:{},...$r(r.emails)});let k=YR(w,n,this.deps.log);return P(this.deps,"seed:execute","seed:error",e,w,{...O?{code:O.code}:{},retryable:!0,extraPayload:{...k,...v?{checkpoint:v}:{}}}),Le(this.deps,n,T(b),!0,{extraPayload:k,context:i}),d?.ended({error:b}),{status:"failure"}}}};function $A(s){if(s.length>512)throw new Error(`SOQL WHERE clause too long (${s.length} > 512 chars)`);return Eg(s)}var Os=class{log;described=new WeakMap;constructor(e){this.log=e.log}describe(e,t){let r=this.described.get(e);r||(r=new Map,this.described.set(e,r));let n=r.get(t);return n||(n=e.describe(t),r.set(t,n)),n}async fetchRecords(e,t,r){let n=await this.getQueryFields(e,t),o=this.buildSoql(n,t,r),i=this.cleanRecords(await es(o,async a=>{let d=[],c=await e.query(a);for(d.push(...c.records);!c.done&&c.nextRecordsUrl;)c=await e.queryMore(c.nextRecordsUrl),d.push(...c.records);return d}));return this.log(`[CloneRecordFetcher] Fetched ${i.length} records from ${t}`),i}async countRecords(e,t,r,n=[]){let o=`SELECT COUNT() FROM ${He(t)}${this.whereOf(r,n)}`;return(await e.query(o)).totalSize}async fetchSample(e,t,r,n,o=[]){let i=await this.getQueryFields(e,t),a=this.buildSoql(i,t,n,o);return a+=` LIMIT ${r}`,this.cleanRecords(await es(a,async d=>(await e.query(d)).records))}async getQueryFields(e,t){let r=await this.describe(e,t),n=new Set;n.add("Id");for(let o of r.fields)(o.createable||o.type==="reference")&&n.add(o.name);return Array.from(n)}buildSoql(e,t,r,n=[]){return`SELECT ${e.join(", ")} FROM ${He(t)}${this.whereOf(r,n)}`}whereOf(e,t){let r=e?$A(e):void 0;return t.length===0?r?` WHERE ${r}`:"":` WHERE ${[...r?[`(${r})`]:[],...t].join(" AND ")}`}cleanRecords(e){return e.map(t=>{let r={...t};return delete r.attributes,r})}};var Is=class{resolveInsertOrder(e,t){if(e.length===0)return[];let r=new Set(e),n=t.filter(u=>u.from!==u.to&&r.has(u.from)&&r.has(u.to)),o=new Map(e.map(u=>[u,new Set])),i=new Map(e.map(u=>[u,new Set])),a=new Map(e.map(u=>[u,new Set]));for(let u of n)o.get(u.to)?.add(u.from),u.required&&(eu(u)?a:i).get(u.to)?.add(u.from);let d=di(i).filter(u=>u.length>1);if(d.length>0)throw new Error(FA(d,n.filter(u=>!eu(u))));let c=new Map(e.map(u=>[u,new Set([...i.get(u)??[],...a.get(u)??[]])])),l=di(c).some(u=>u.length>1)?i:c;return LA(di(o),o,e).flatMap(u=>u.length>1?Tg(u,l):u)}lookupsOf(e,t){return t.filter(r=>r.to===e&&!eu(r)).map(r=>({field:r.fieldApiName,referenceTo:r.from}))}lookupsFilledAfter(e,t){let r=new Map(e.map((n,o)=>[n,o]));return t.filter(n=>{let o=r.get(n.to),i=r.get(n.from);return!n.required&&o!==void 0&&i!==void 0&&i>=o})}detectSelfReferentialEdges(e){return e.filter(t=>t.from===t.to)}buildEdgesFromDescribe(e,t){let r=new Set(e),n=[];for(let o of e){let i=t.get(o);if(i){for(let a of i.fields)if(a.createable!==!1&&!(o===qt&&a.name==="ActivityId")&&a.type==="reference"&&a.referenceTo){let d=Bo(o,a.name,a.nillable)||a.updateable===!1;for(let c of a.referenceTo)r.has(c)&&n.push({from:c,to:o,fieldApiName:a.name,relationshipType:"lookup",required:d})}}}for(let o of Yc(r))n.push({from:o.sourceObject,to:o.targetObject,fieldApiName:o.relationshipName,relationshipType:"lookup",required:!0});return n}};function LA(s,e,t){let r=new Map;t.forEach((c,l)=>{r.has(c)||r.set(c,l)});let n=new Map;s.forEach((c,l)=>c.forEach(u=>n.set(u,l)));let o=s.map(c=>Math.min(...c.map(l=>r.get(l)??1/0))),i=s.map((c,l)=>{let u=new Set;for(let p of c)for(let g of e.get(p)??[]){let h=n.get(g);h!==void 0&&h!==l&&u.add(h)}return u}),a=new Set,d=[];for(;d.length<s.length;){let c=-1;for(let l=0;l<s.length;l++)a.has(l)||[...i[l]].some(u=>!a.has(u))||(c===-1||o[l]<o[c])&&(c=l);if(c===-1)break;a.add(c),d.push(s[c])}return d}function eu(s){return Yc(new Set([s.from,s.to])).some(e=>e.sourceObject===s.from&&e.targetObject===s.to&&e.relationshipName===s.fieldApiName)}function FA(s,e){let t=s.flatMap(r=>{let n=new Set(r);return e.filter(o=>o.required&&n.has(o.from)&&n.has(o.to)).map(o=>`${o.to}.${o.fieldApiName}`)});return`Cycle detected among objects: ${s.flat().join(", ")}. ${_A(t)} must be set when the record is created, so no object of the cycle can be written first.`}function _A(s){return s.length<=1?s.join(""):`${s.slice(0,-1).join(", ")} and ${s[s.length-1]}`}function tu(s){return s==="insert"||s==="upsert"}function Ua(s,e){return{sending:(t,r,n)=>{tu(r)&&s.sending(t,n,r==="upsert"?{upsert:!0}:void 0)},opened:(t,r,n,o)=>{tu(r)&&s.sending(t,n,{job:o,...r==="upsert"?{upsert:!0}:{}})},answered:(t,r,n)=>{if(!tu(r))return;let o=da(r,n);s.answered(t,o),e?.(o.length)}}}var UA=new Set(["seed:clone:describe-source","seed:clone:preview","seed:clone:execute"]),HA=5,BA=10,qA=-1,ev="Operation blocked by Production Guard: ",jn={confirmationDeclined:"PRODUCTION_CONFIRMATION_DECLINED",guardBlocked:"PRODUCTION_GUARD_BLOCKED",failed:"CLONE_FAILED",emailsExceeded:"CLONE_EMAILS_EXCEEDED",apiBudgetExceeded:"API_BUDGET_EXCEEDED"},WA=6e4,zA={neutralized:!1,fields:[],values:0},GA="PREVIEWED_FOR_OTHER_ORGS",JA="NOT_PREVIEWED",VA="PREVIEW_NOT_HELD",XA=50,Ba=class{constructor(e){this.deps=e}deps;registry;liveTracker;previewedOrgs=new Map;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-4XZ5YT5O.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async emailGate(e,t,r,n,o,i){let a=r.filter(c=>c.recordCount>0);if(a.length===0)return;let d=await la({org:n,objects:a.map(c=>c.objectApiName),readAutomation:c=>o===void 0?this.readTargetAutomation(e,c):typeof o.unread=="string"?Promise.reject(new Error(o.unread)):Promise.resolve(o),readLimits:()=>cr(t),...i?{deliverability:i}:{}});return ua(d,a,n)}readTargetAutomation(e,t){let r=this.targetAutomation;return new ge(WA).withTimeout("clone automation",()=>r.read(e,t))}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}runCreations;runningRuns=new Set;setRunCreations(e){this.runCreations=e}isRunning(e){return this.runningRuns.has(e)}async endKept(e,t,r){if(!e)return!1;try{return await e.end({finishedAt:new Date().toISOString(),status:r.status,...r.cancelled?{cancelled:!0}:{},objectResults:[]}),!0}catch(n){return this.deps.log(`[WARN] seed:clone:execute ${t}: what the clone created could not all be kept, so removing it may leave some of it in the org: ${T(n)}`),!1}finally{this.runningRuns.delete(t)}}stoppedForCheckpoint(e,t,r,n,o){let{operationId:i}=t;if(r.code===Ze){X(this.deps,{...t,outcome:"stopped",source:void 0,code:Ze}),this.registry?.abort(i),pe(this.deps,i,{aborted:!0,totalInserted:0,totalFailed:0}),this.liveTracker?.cancel(i);let c={status:"partial",objectResults:[],totalSourceRecords:0,totalInserted:0,totalFailed:0,durationMs:o,cancelled:!0};this.deps.broker.postToWebview(A(this.deps,e,"seed:clone:execute:response",c));return}let a=r.refusal?.code,d=a!==void 0?{checkpointRefusal:a}:{};X(this.deps,{...t,outcome:"stopped",source:void 0,code:r.code,...a!==void 0?{details:d}:{}}),Le(this.deps,i,r.message,!1,{context:n,authored:!0,extraPayload:{code:r.code,...d}}),this.liveTracker?.fail(i,r.message)}async handle(e){if(!UA.has(e.type))return!1;switch(e.type){case"seed:clone:describe-source":return await this.handleDescribeSource(e),!0;case"seed:clone:preview":return await this.handlePreview(e),!0;case"seed:clone:execute":return await this.handleExecute(e),!0;default:return!1}}async handleDescribeSource(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Vf,e,"seed:clone:error",this.deps);if(t)try{let r=await B(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await r.describeGlobal();De(r.limitInfo,"seed:clone:describe-source");let o=n.sobjects.filter(a=>a.createable&&a.queryable).filter(a=>!ei(a.name)).map(a=>({apiName:a.name,label:a.label,recordCount:qA})),i=A(this.deps,e,"seed:clone:describe-source:response",{objects:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} count=${o.length}`)}catch(r){P(this.deps,"seed:clone:describe-source","seed:clone:error",e,r)}}async handlePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(nl,e,"seed:clone:error",this.deps);if(t)try{let r=await B(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),o=new Os({log:this.deps.log}),i=new Is,a=t.objects.map(R=>R.objectApiName),d=new Map(t.objects.map(R=>[R.objectApiName,R.whereClause])),c=new Map,l=new Map,u=[];for(let R of t.objects){let[b,O]=await Promise.all([Ha("target",R.objectApiName,()=>n.describe(R.objectApiName)),Ha("source",R.objectApiName,()=>o.describe(r,R.objectApiName))]);De(n.limitInfo,`seed:clone:preview describe ${R.objectApiName} in the target`),De(r.limitInfo,`seed:clone:preview describe ${R.objectApiName}`),c.set(R.objectApiName,b),l.set(R.objectApiName,O);let k=Cg(R.objectApiName,rv(R.objectApiName,c.get(R.objectApiName),l.get(R.objectApiName)),d),[S,E,I]=await Promise.all([o.countRecords(r,R.objectApiName,R.whereClause,k),o.fetchSample(r,R.objectApiName,HA,R.whereClause,k),k.length>0?o.countRecords(r,R.objectApiName,R.whereClause):void 0]),C=I===void 0?0:I-S;u.push({objectApiName:R.objectApiName,recordCount:S,...C>0?{leftToThePlatform:C}:{},sampleRecords:E.map(F=>nT(F,BA))})}let p=i.buildEdgesFromDescribe(a,nv(c,l)),g=i.resolveInsertOrder(a,p),h=u.map(R=>({...R,relationships:i.lookupsOf(R.objectApiName,p)})),f=YA(i.lookupsFilledAfter(g,p),g),m=QA(g,l,c),y=ZA(g,c,l),w={objects:h,insertOrder:g,...f.length>0?{filledAfterInsert:f}:{},...m.length>0?{sourceOnlyLookups:m}:{},...y.length>0?{targetOnlyRequiredLookups:y}:{}},v=A(this.deps,e,"seed:clone:preview:response",w);this.deps.broker.postToWebview(v),this.deps.log(`[TX] ${v.type} id=${v.id}`),this.rememberPreview(e.id,t,new Map(u.map(R=>[R.objectApiName,R.recordCount])),new Set(i.lookupsFilledAfter(g,p).map(R=>R.to)))}catch(r){P(this.deps,"seed:clone:preview","seed:clone:error",e,r)}}rememberPreview(e,t,r,n){this.previewedOrgs.set(e,{sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,recordCounts:r,secondPass:n});for(let o of this.previewedOrgs.keys()){if(this.previewedOrgs.size<=XA)break;this.previewedOrgs.delete(o)}}refusedAgainstItsPreview(e){if(e.previewId===void 0)return{code:JA,reason:"Clone refused: it names no preview. Preview it, then run the preview shown."};let t=this.previewedOrgs.get(e.previewId);if(!t)return{code:VA,reason:"Clone refused: the preview it names is not one SandForge answered, or no longer holds. Preview it again."};if(t.sourceOrgId!==e.sourceOrgId||t.targetOrgId!==e.targetOrgId)return{code:GA,reason:"Clone refused: its preview was made for another source or target org. Preview it again."}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(nl,e,"seed:clone:error",this.deps);if(!t)return;let r=this.refusedAgainstItsPreview(t);if(r!==void 0){P(this.deps,e.type,"seed:clone:error",e,new Error(r.reason),{code:r.code});return}let n=e.id,o=Date.now(),i={module:"seed",operation:e.type,...Er(t.objects.map(R=>({objectApiName:R.objectApiName})))},a=new AbortController,d=()=>{},c=new Promise((R,b)=>{d=O=>O===void 0?R():b(O)});c.catch(()=>{}),this.registry?.register(n,"clone",`Clone ${t.objects.length} object(s)`,c,a);let l={action:"seed_clone",module:"seed",operationId:n,orgId:t.targetOrgId,outcome:"failure",source:{origin:"org",orgId:t.sourceOrgId}},u=!1,p,g=0,h,f=!1,m=[],y=!!(t.upsert&&t.externalIdField),w=bb(t.keepContactPoints===!0?{keepContactPoints:!0}:{}),v=()=>w?.report()??zA;try{let R=this.deps.infraServices?.productionGuard;if(!R){X(this.deps,{...l,outcome:"stopped",source:void 0,code:ve.code}),Le(this.deps,n,ve.message,!1,{context:i,extraPayload:{code:ve.code}}),d(new Error(ve.message));return}let b=this.deps.orgManager.getOrg(t.targetOrgId),O={orgId:t.targetOrgId,orgTier:Ee(b),operation:t.upsert?"upsert":"insert",objectName:t.objects.map($=>$.objectApiName).join(", ")||"CloneData",recordCount:"unknown",module:"clone"},{check:k,decision:S}=await Ke(R,O);if(l.guard=S,(S==="refused"||S==="declined")&&X(this.deps,{...l,outcome:"stopped",source:void 0}),S==="refused")throw new Error(`${ev}${k.blockedReason??k.impactSummary}`);if(S==="declined"){let $="Operation cancelled by user (confirmation declined).";Le(this.deps,n,$,!1,{context:i,extraPayload:{code:jn.confirmationDeclined}}),d(new Error($));return}let E=await B(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),I=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),C=Re(b,t.targetOrgId),F=this.previewedOrgs.get(t.previewId??""),Y=F?.recordCounts,z=t.objects.map($=>({objectApiName:$.objectApiName,recordCount:Y?.get($.objectApiName)??0})),te=z.filter($=>$.recordCount>0).map($=>$.objectApiName),H=($,J,oe)=>{let Ie=oe!==void 0?{checkpointRefusal:oe}:{};X(this.deps,{...l,outcome:"stopped",source:void 0,code:$,...oe!==void 0?{details:Ie}:{}}),Le(this.deps,n,J,!1,{context:i,authored:!0,extraPayload:{code:$,...Ie}}),d(new Error(J))},x,j=te.length>0?await this.readTargetAutomation(t.targetOrgId,te).catch($=>({unread:T($)})):{unread:"the clone sends no record"},K=te.length>0?await Vt({read:j,writes:ks(te,!0),readDeliverability:()=>Ee(b)==="production"?Promise.resolve(Mt):jt(I),accepted:!1,target:C,run:"clone",keepsAddresses:t.keepContactPoints===!0}):void 0,Q=K?.gate.verdict==="asks";if(t.checkpointFirst!==void 0){try{x=await vs(this.beforeRunCheckpoints,{module:"seed",orgId:t.targetOrgId,operationId:n,written:te,running:_a(j,ks(te,!0)),request:t.checkpointFirst})}catch(J){if(!(J instanceof Nt))throw J;H(J.code,J.message);return}let $=zi(x.planned);if($){H($.code,$.message,$.refusal.code);return}}let _=await this.emailGate(t.targetOrgId,I,z,C,j,K?.gate.deliverability);for(let $ of _?.unknown??[])this.deps.log(`[WARN] seed:clone:execute ${n}: ${$}`);if(_?.refusal&&_.figures){let $=KA(_.figures);X(this.deps,{...l,outcome:"stopped",source:void 0,code:jn.emailsExceeded}),Le(this.deps,n,$,!1,{context:i,authored:!0,extraPayload:{code:jn.emailsExceeded,..._.figures}}),d(new Error($));return}let V=x||Q?await dr(I).catch($=>({unread:T($)})):void 0,ue=V!==void 0&&!("unread"in V)?V.dailyApiRequests:await Xt(I).catch($=>({unread:T($)})),me=en({run:Db(z.map($=>({objectApiName:$.objectApiName,rows:$.recordCount})),{threshold:st(this.deps).bulk.threshold,perCall:this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200),duplicateRules:fo(j),...F?{secondPass:F.secondPass}:{},automationRead:te.length>0?nn(j):0}),...po(x?.planned),...on(K?.ofRun)},ue);me.verdict==="unread"&&this.deps.log(`[WARN] seed:clone:execute ${n}: the daily API requests the target has left could not be read (${me.unread})`);let re=Wi(me,C);if(re){X(this.deps,{...l,outcome:"stopped",source:void 0,code:jn.apiBudgetExceeded}),Le(this.deps,n,re,!1,{context:i,authored:!0,extraPayload:{code:jn.apiBudgetExceeded}}),d(new Error(re));return}let ie=!1;if(x||Q){let $=z.filter(oe=>oe.recordCount>0).map(oe=>({objectApiName:oe.objectApiName,rows:oe.recordCount})).sort((oe,Ie)=>Ie.rows-oe.rows),J=await R.confirmRun({stage:"write",module:"seed",org:C,orgTier:Ee(b),objects:$,total:$.reduce((oe,Ie)=>oe+Ie.rows,0),storage:sn(rn({storageBytes:$.reduce((oe,Ie)=>oe+qi(Ie.objectApiName,{rows:Ie.rows}),0)},V??{unread:"not read"})),counted:!0,...uo(me),...x?{checkpoint:x.planned}:{},...K?.gate.confirmation});if(J!=="confirmed"){let oe=K?.gate.stop;J!=="declined"&&!x&&oe?H(oe.code,oe.message):H(J==="declined"?Oo:yt.unanswered,J==="declined"?"The clone was cancelled before it wrote anything. Nothing was written.":`The clone needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${C} \u2014 and there was no one to ask. Nothing was written.`);return}ie=Q}if(l.details=$r(K?{read:K,accepted:ie}:void 0).details,We(this.deps,n,"clone",`Clone ${t.objects.length} object(s)`),this.liveTracker?.register(n,"clone",`Clone ${t.objects.length} object(s)`),x)try{h=await Ss(this.beforeRunCheckpoints,x,n,a.signal,($,J,oe,Ie)=>{$e(this.deps,n,$,J,oe,Ie),this.liveTracker?.updateProgress(n,$,J,oe,Ie)})}catch($){if(!($ instanceof Nt))throw $;this.stoppedForCheckpoint(e,l,$,i,Date.now()-o),d($.code===Ze?void 0:$);return}u=!0;let Be=st(this.deps),fe=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200;i.batchSize=fe;let ne=new Map,ce={objects:0,records:0,of:1};p=this.runCreations?.recorder({runId:n,targetOrgId:t.targetOrgId,sourceOrgId:t.sourceOrgId,startedAt:new Date(o).toISOString(),origin:"clone"}),h&&p?.checkpoint?.(h),lr(p,()=>I.identity(),`seed:clone:execute ${n}`),p&&this.runningRuns.add(n);let we=new an({...p?{calls:Ua(p,$=>{g+=$})}:{},keyPrefixOf:$=>ne.get($)?.keyPrefix,connection:I,bulkExecutor:new Xr(Be.bulk.threshold),bulkManager:nr(this.deps),retryConfig:Be.retry,signal:a.signal,onProgress:($,J,oe)=>{$e(this.deps,n,J>0?Math.round($/J*100):0,$,J,oe),this.liveTracker?.updateProgress(n,Math.round((ce.objects+$/Math.max(J,1))/ce.of*100),ce.records+$,0,oe)},log:$=>this.deps.log($)}),le=new Os({log:this.deps.log}),Se=new Is,je=t.objects.map($=>$.objectApiName),M=new Set(je),N=new Map,U=new Map,W=new Map;for(let $ of je){let[J,oe]=await Promise.all([Ha("target",$,()=>I.describe($)),Ha("source",$,()=>le.describe(E,$))]);De(I.limitInfo,`seed:clone:execute describe ${$}`),De(E.limitInfo,`seed:clone:execute describe ${$} in the source`),N.set($,J),U.set($,oe),W.set($,ur(J).fields??[]),ne.set($,{keyPrefix:J.keyPrefix??null,recordTypes:Zg(J.recordTypeInfos)})}let ae=Se.buildEdgesFromDescribe(je,nv(N,U)),q=Se.resolveInsertOrder(je,ae),he=Se.lookupsFilledAfter(q,ae);ce.of=Math.max(q.length,1);let Fe=new Map(t.objects.map($=>[$.objectApiName,$])),Te=new Map,de=new Map,be=new Map,Ce=[],tt=new Pg,_e=0,Ue=!1,lt=new Map,Wn=[],br=M.has(li),yn=$=>At(I,$),Ws=new Map,Ur=new Map,wn=Tn(sr($=>At(E,$)),async $=>U.get($)??await le.describe(E,$)),zn=new Map,Rr=async($,J)=>{if(J.length===0)return;let oe=await wn($);for(let Ie of oe){let ye=!1;for(let Z of J)Ie in Z&&(ye||=Z[Ie]!==null&&Z[Ie]!==void 0,delete Z[Ie]);ye&&zn.set($,(zn.get($)??new Set).add(Ie))}},zs=async($,J)=>{let oe=(N.get($)?.fields??[]).filter(Z=>Z.type==="reference"),Ie=await xw({lookups:oe,rows:J,known:Ws,query:yn});if(Ie.size===0)return;let ye=Ur.get($)??new Map;for(let Z of J)for(let{name:ee}of oe){let Ae=Z[ee];typeof Ae!="string"||!Ie.has(Ae)||(delete Z[ee],ye.set(ee,(ye.get(ee)??0)+1))}ye.size!==0&&(Ur.set($,ye),this.deps.log(`[INFO] seed:clone ${$}: written without a user or a queue the target does not hold, which the platform fills (the owner with the user the clone writes as): `+[...ye].map(([Z,ee])=>`${Z} on ${ee}`).join(", ")))},Zt=async($,J)=>{await Rr($,J),await zs($,J),w&&Rb(w,$,W.get($)??[],J,y?t.externalIdField:void 0),J.length>0&&(f=!0);try{return{outcomes:t.upsert&&t.externalIdField?await we.upsert($,t.externalIdField,J,fe):await we.insert($,J,fe),stopped:!1}}catch(oe){if(!(oe instanceof vo))throw oe;return{outcomes:oe.written,stopped:!0}}},Fo=($,J,oe,Ie)=>{$.forEach((ye,Z)=>{let ee=typeof J[Z]?.Id=="string"?J[Z].Id:"";if(ye.success){oe.insertedCount++,ee&&ye.id&&(Te.set(ee,ye.id),oe.idMappings.push({sourceId:ee,targetId:ye.id}));let Ae=ye.id;if(Ae)for(let{fieldName:xe,sourceRefId:ut}of Ie[Z]??[])Ce.push({objectApiName:oe.objectApiName,newId:Ae,sourceId:ee||void 0,fieldName:xe,sourceRefId:ut})}else ye.existingId?(oe.linkedCount=(oe.linkedCount??0)+1,ee&&(Te.set(ee,ye.existingId),oe.idMappings.push({sourceId:ee,targetId:ye.existingId}))):(oe.failedCount++,oe.errors.push({sourceId:ee,message:ye.errors[0]??"Unknown insert error"}))})},It=async $=>{let J=new Map((m.find(ee=>ee.objectApiName===qt)?.idMappings??[]).map(ee=>[ee.sourceId,ee.targetId])),oe=new Map;for(let[ee,Ae]of lt){let xe=J.get(ee);xe&&oe.set(Ae,xe)}let Ie=$.map(ee=>String(ee.Id)).filter(ee=>oe.has(ee));if(Ie.length===0)return new Map;let ye;try{ye=await xg(yn,[...new Set(Ie.map(ee=>oe.get(ee)??""))])}catch(ee){return this.deps.log(`[seed:clone] tasks written with the clone's emails not looked up, written as read: ${T(ee)}`),new Map}let Z=new Map;for(let ee of Ie){let Ae=ye.get(oe.get(ee)??"");Ae&&Z.set(ee,Ae)}return Z},bn=async($,J,oe)=>{if(Ng[$]===void 0)return new Map;let Ie;try{Ie=await $g(yn,$,oe)}catch(Z){return this.deps.log(`[seed:clone] ${$}: the relations the target holds not looked up, written as read: ${T(Z)}`),new Map}let ye=new Map;for(let[Z,ee]of Ie){let Ae=J[Z]?.Id;typeof Ae=="string"&&ye.set(Ae,ee)}return ye},_o=async($,J)=>{if(de.size===0)return new Map;let oe=N.get(rr),Ie=[...new Set(J.flatMap(xe=>Object.keys(xe)))].filter(xe=>sv(oe,xe)),ye;try{ye=await jg(yn,J.map((xe,ut)=>({OpportunityId:xe.OpportunityId,[Yo]:xe[Yo],IsPrimary:$[ut]?.IsPrimary})),xe=>de.get(xe),Ie)}catch(xe){return this.deps.log(`[seed:clone] ${rr}: the roles the platform wrote with the clone's opportunities not looked up, written as read \u2014 an opportunity may hold the role of its contact twice: ${T(xe)}`),new Map}let{found:Z,alike:ee}=ye;if(ee.length>0){this.deps.log(`[seed:clone] ${rr}: ${Mg(ee.length)}`);for(let xe of ee)de.delete(String(J[xe]?.OpportunityId))}let Ae=new Map;for(let[xe,ut]of Z){let Ve=$[xe]?.Id;typeof Ve=="string"&&(Ae.set(Ve,String(ut.Id)),be.set(Ve,ut),de.delete(String(J[xe]?.OpportunityId)))}return Ae},Gn=async($,J)=>{let oe=N.get(rr),Ie=[];if($.forEach(([ee,Ae],xe)=>{let ut=be.get(String(ee.Id))??{},Ve=Object.entries(J[xe]??{}).filter(([qr,Jn])=>sv(oe,qr)&&Jn!==null&&Jn!==void 0&&String(ut[qr]??"")!==String(Jn));Ve.length>0&&Ie.push({Id:Ae,...Object.fromEntries(Ve)})}),Ie.length===0||Ue||a.signal.aborted)return;let ye;try{ye=await we.update(rr,Ie,fe)}catch(ee){if(!(ee instanceof vo))throw ee;Ue=!0,ye=ee.written}let Z=Ie.flatMap((ee,Ae)=>ye[Ae]?.success?[]:[`${ee.Id}: ${ye[Ae]?.errors[0]??"not updated"}`]);Z.length>0&&this.deps.log(`[seed:clone] ${rr}: linked, and left as the platform wrote them, without the fields of the source's roles: ${Z.slice(0,3).join(" | ")}`)},Gs=async()=>{br=!1;let $=Wn.splice(0,Wn.length),J=m.find(ee=>ee.objectApiName===qt);if($.length===0||!J||Ue)return;if(a.signal.aborted){Ue=!0;return}let oe=$.map(ee=>iv(qt,ee,N.get(qt),M,Te)),Ie=ov(qt,$,oe,he,Te),{outcomes:ye,stopped:Z}=await Zt(qt,oe);Fo(ye,$,J,Ie),ce.records+=$.length,Z&&(Ue=!0)};for(let $=0;$<q.length;$++){if(a.signal.aborted){Ue=!0;break}let J=q[$],oe=Fe.get(J);$e(this.deps,n,Math.round($/q.length*100),$,q.length,`Cloning ${J}`),ce.objects=$,this.liveTracker?.updateProgress(n,Math.round($/q.length*100),ce.records,0,`Cloning ${J}`);let Ie;try{Ie=await le.fetchRecords(E,J,oe.whereClause)}catch(qe){_e++,m.push({objectApiName:J,sourceCount:0,insertedCount:0,failedCount:0,idMappings:[],errors:[{sourceId:"",message:T(qe)}]});continue}let ye=tt.keep(J,Ie,rv(J,N.get(J),U.get(J)).map(({name:qe})=>qe)),Z=Ie.length-ye.length;if(J===qt)for(let qe of ye){let Je=qe.ActivityId;typeof qe.Id=="string"&&typeof Je=="string"&&Je!==""&&lt.set(qe.Id,Je)}let ee=ye.map(qe=>iv(J,qe,N.get(J),M,Te)),Ae=rT(ye,N.get(J));Ae.length>0&&this.deps.log(`[INFO] seed:clone ${J}: ${Ae.length} field(s) the target does not have left out \u2014 ${Ae.join(", ")}`);let xe=ov(J,ye,ee,he,Te),ut=ef(J,ee,ne.get(J)?.recordTypes??[]);if(ut.length>0){_e++,m.push({objectApiName:J,sourceCount:Ie.length,insertedCount:0,failedCount:ye.length,...Z>0?{leftToThePlatform:Z}:{},idMappings:[],errors:ut.map(qe=>{let Je=ye.find((Qe,Rn)=>tf(ee[Rn],[qe]));return{sourceId:typeof Je?.Id=="string"?Je.Id:qe.recordTypeId,message:rf(qe)}})});continue}if(J===qt&&br){let qe=ye.map(Je=>Dg(Je));Wn.push(...ye.filter((Je,Qe)=>qe[Qe])),ye=ye.filter((Je,Qe)=>!qe[Qe]),ee=ee.filter((Je,Qe)=>!qe[Qe]),xe=xe.filter((Je,Qe)=>!qe[Qe])}let Ve=J===li?await It(ye):J===rr?await _o(ye,ee):await bn(J,ye,ee),qr=[],Jn=[];if(Ve.size>0){let qe=ye.map(Je=>!Ve.has(String(Je.Id)));ye.forEach((Je,Qe)=>{qe[Qe]||(qr.push([Je,Ve.get(String(Je.Id))??""]),Jn.push(ee[Qe]))}),ye=ye.filter((Je,Qe)=>qe[Qe]),ee=ee.filter((Je,Qe)=>qe[Qe]),xe=xe.filter((Je,Qe)=>qe[Qe])}if(a.signal.aborted){Ue=!0;break}let{outcomes:jc,stopped:cI}=await Zt(J,ee);if(cI&&(Ue=!0,jc.length===0))break;if(J===oT&&jc.forEach((qe,Je)=>{let Qe=ee[Je]?.[Yo];qe.success&&qe.id&&qe.created!==!1&&typeof Qe=="string"&&Qe!==""&&de.set(qe.id,Qe)}),J===rr&&qr.length>0&&await Gn(qr,Jn),qr.length>0){let qe=N.get(J),Je=await Lg(J,qr,Qe=>qe?.fields.find(Rn=>Rn.name===Qe)?.updateable!==!1,async Qe=>{try{return await we.update(J,Qe,fe)}catch(Rn){if(!(Rn instanceof vo))throw Rn;return Ue=!0,Rn.written}},()=>Ue||a.signal.aborted);Je&&this.deps.log(`[seed:clone] ${J}: ${Je}`)}let Nc={objectApiName:J,sourceCount:Ie.length,insertedCount:0,failedCount:0,linkedCount:Ve.size,...J===rr&&Ve.size>0?{writtenByThePlatform:Ve.size}:{},...Z>0?{leftToThePlatform:Z}:{},...Ae.length>0?{fieldsNotInTarget:Ae}:{},idMappings:[],errors:[]};for(let[qe,Je]of Ve)Te.set(qe,Je),Nc.idMappings.push({sourceId:qe,targetId:Je});if(Fo(jc,ye,Nc,xe),m.push(Nc),ce.records+=ye.length,Ue)break;J===li&&await Gs()}await Gs();let vr;if(Ce.length>0&&(a.signal.aborted&&(Ue=!0),vr=Ue?tT(Ce):await eT({owed:Ce,idMap:Te,targetConn:I,targetOrgId:t.targetOrgId,stopped:()=>a.signal.aborted,report:$=>{$e(this.deps,n,100,ce.records,ce.records,$),this.liveTracker?.updateProgress(n,100,ce.records,0,$)}}),a.signal.aborted&&(Ue=!0),p&&vr.filled>0)){let $=new Map;for(let{objectApiName:J,newId:oe}of Ce)$.set(J,[...$.get(J)??[],oe]);for(let[J,oe]of $)p.wroteAgain(J,oe)}for(let $ of m){let J=Ur.get($.objectApiName);J&&($.lookupsNotCarried=[...J].map(([Ie,ye])=>({field:Ie,records:ye})));let oe=zn.get($.objectApiName);oe&&($.encryptedLeftOut=[...oe].sort())}let Mc=m.reduce(($,J)=>$+J.sourceCount,0),Ne=m.reduce(($,J)=>$+J.insertedCount,0),Ge=m.reduce(($,J)=>$+(J.linkedCount??0),0),rt=m.reduce(($,J)=>$+(J.leftToThePlatform??0),0),Ye=m.reduce(($,J)=>$+J.failedCount,0),ht=Ye===0&&_e===0?"success":Ne+Ge>0?"partial":"failure",et=vr!==void 0&&vr.filled<vr.owed,bt=v(),er=(Ue||et)&&ht==="success"?"partial":ht,Hr=await this.endKept(p,n,{status:er,cancelled:Ue});p=void 0;let Lt=await ln(this.beforeRunCheckpoints,h,f,this.deps.log,`seed:clone:execute ${n}`);h=void 0;let Rt={status:er,objectResults:m,totalSourceRecords:Mc,totalInserted:Ne,totalLinked:Ge,...rt>0?{totalLeftToThePlatform:rt}:{},totalFailed:Ye,...vr?{secondPass:vr}:{},durationMs:Date.now()-o,...Ue?{cancelled:!0}:{},contactPoints:bt,...Hr&&g>0?{runId:n}:{}};u=!1;let dt=Ue?Ne+Ye>0?"cancelled":"stopped":Rt.status;X(this.deps,{...tv(l,dt,m,y,bt),...dt==="stopped"?{code:Ze}:{},...Lt?.state==="taken"?{checkpointId:Lt.checkpointId}:{}});let Ht=!Ue&&Rt.status==="failure"?"No record could be cloned.":void 0;Ue?(this.registry?.abort(n),pe(this.deps,n,{aborted:!0,totalInserted:Ne,totalFailed:Ye}),this.liveTracker?.cancel(n)):(pe(this.deps,n,{status:Rt.status,totalInserted:Ne,totalFailed:Ye}),Ht!==void 0?this.liveTracker?.fail(n,Ht):Rt.status==="partial"?this.liveTracker?.partial(n):this.liveTracker?.complete(n));let Js={...Rt,...Lt?{checkpoint:Lt}:{}},Br=A(this.deps,e,"seed:clone:execute:response",Js);this.deps.broker.postToWebview(Br),this.deps.log(`[TX] ${Br.type} id=${Br.id} status=${Rt.status}`),d(Ht===void 0?void 0:new Error(Ht))}catch(R){let b=await ln(this.beforeRunCheckpoints,h,f,this.deps.log,`seed:clone:execute ${n}`);u&&X(this.deps,{...tv(l,"failure",m,y,v()),...b?.state==="taken"?{checkpointId:b.checkpointId}:{}}),await this.endKept(p,n,{status:"failure",cancelled:!1});let O=b?.state==="deleted"?`${T(R)} ${xr}`:T(R);this.deps.log(`[ERR] seed:clone:execute: ${O}`),Le(this.deps,n,T(R),!0,{context:i,extraPayload:{code:O.startsWith(ev)?jn.guardBlocked:jn.failed,...b?{checkpoint:b}:{}}}),this.liveTracker?.fail(n,O),d(R)}}};function KA(s){let e=[`narrow the filters of ${s.objects.join(", ")} or leave them out`,`turn off ${s.senders.map(t=>`"${t}"`).join(", ")}`,...s.bypasses.map(t=>"give the user the clone writes as "+(t.permissionSet?`the permission set ${t.permissionSet}, whose ${t.permission}`:`a permission set holding ${t.permission}, which`)+" keeps them quiet")];return`The clone was refused before it wrote anything: its records would make ${s.org} send about ${sw(s.emails,s.limit)}, ${s.remaining} of ${s.max} left today. 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 clone them, ${e.join("; or ")}. Nothing was written.`}function tv(s,e,t,r,n){return{...s,details:{...s.details,...Zo(n).details},outcome:e,objects:t.map(o=>({...at(o.objectApiName),...r?{upserted:o.insertedCount}:{created:o.insertedCount},failed:o.failedCount})),carried:Object.fromEntries(t.map(o=>[o.objectApiName,o.idMappings.length]))}}function rv(s,e,t){let r=new Set((t?.fields??[]).map(n=>n.name));return(e?.fields??[]).filter(n=>n.type==="reference"&&r.has(n.name)&&Bo(s,n.name,n.nillable)).map(n=>({name:n.name,referenceTo:n.referenceTo??[]}))}async function Ha(s,e,t){try{return await t()}catch(r){throw new Error(`${e} could not be described in the ${s} org: ${T(r)}`)}}function nv(s,e){return new Map([...s].map(([t,r])=>{let n=new Map((e.get(t)?.fields??[]).map(i=>[i.name,i.referenceTo??[]])),o=r.fields.flatMap(i=>{if(i.type!=="reference")return[i];let a=n.get(i.name)??[],d=(i.referenceTo??[]).filter(c=>a.includes(c));return d.length>0?[{...i,referenceTo:d}]:[]});return[t,{fields:o}]}))}function YA(s,e){let t=new Map(e.map((r,n)=>[r,n]));return s.map(r=>({objectApiName:r.to,field:r.fieldApiName,referenceTo:r.from})).sort((r,n)=>(t.get(r.objectApiName)??0)-(t.get(n.objectApiName)??0))}function QA(s,e,t){let r=new Set(s);return s.flatMap(n=>{let o=qa(t.get(n));return o?(e.get(n)?.fields??[]).filter(i=>i.type==="reference"&&i.createable!==!1&&!o.has(i.name)).flatMap(i=>(i.referenceTo??[]).filter(a=>r.has(a)).map(a=>({objectApiName:n,field:i.name,referenceTo:a}))):[]})}function ZA(s,e,t){return s.flatMap(r=>{let n=qa(t.get(r));return n?(e.get(r)?.fields??[]).filter(o=>o.type==="reference"&&!n.has(o.name)&&o.createable!==!1&&o.defaultedOnCreate!==!0&&Bo(r,o.name,o.nillable)).flatMap(o=>(o.referenceTo??[]).map(i=>({objectApiName:r,field:o.name,referenceTo:i}))):[]})}function ov(s,e,t,r,n){let o=r.filter(c=>c.to===s),i=new Set(o.filter(c=>c.from!==s).map(c=>c.fieldApiName)),a=new Set(o.map(c=>c.fieldApiName)),d=new Set(e.map(c=>c.Id).filter(c=>typeof c=="string"));return t.map((c,l)=>{let u=[];for(let p of a){let g=e[l]?.[p];typeof g!="string"||g===""||n.has(g)||p in c&&(!i.has(p)&&!d.has(g)||(delete c[p],u.push({fieldName:p,sourceRefId:g})))}return u})}async function eT(s){let{owed:e,targetConn:t}=s,{patchCycleFkUpdates:r}=await import("./chunk-ZPYJPGDK.mjs"),n=await r({pendingFkUpdates:e,remapper:s.idMap,updateRecords:async(o,i,a)=>{let d=await t.sobject(i).update(a,{allowRecursive:!0,headers:Zs()});return(Array.isArray(d)?d:[d]).map((c,l)=>{let u=a[l]?.Id;return{id:c.id??(typeof u=="string"?u:""),success:c.success,errors:(c.success?[]:c.errors).map(Mm)}})},targetOrgId:s.targetOrgId,enabled:!0,stopped:s.stopped,onProgress:o=>s.report(o.message)});return{owed:e.length,filled:e.length-(n?.failedCount??0),samples:(n?.samples??[]).map(({recordSummary:o,messages:i})=>({record:o,messages:i}))}}function tT(s){let e=[...new Set(s.map(t=>t.objectApiName))];return{owed:s.length,filled:0,samples:[{record:`${e.join(", ")}: ${s.length} lookup${s.length===1?"":"s"} not sent`,messages:["The run was cancelled before they were filled in: they stay empty."]}],cancelledBefore:!0}}function qa(s){let e=new Set((s?.fields??[]).map(t=>t.name));return e.size>0?e:null}function rT(s,e){let t=qa(e);if(!t)return[];let r=new Set;for(let n of s)for(let o of Object.keys(n))o!=="Id"&&!t.has(o)&&r.add(o);return[...r].sort()}function nT(s,e){let t={};for(let[r,n]of Object.entries(s)){if(Object.keys(t).length>=e)break;n==null||n===""||(t[r]=n)}return t}var oT="Opportunity";function sv(s,e){if(e==="OpportunityId"||e===Yo)return!1;let t=s?.fields.find(r=>r.name===e);return t!==void 0&&t.updateable!==!1}function iv(s,e,t,r,n){let o=new Set((t?.fields??[]).filter(d=>d.createable===!1).map(d=>d.name)),i=qa(t),a={};for(let[d,c]of Object.entries(e))d==="Id"||o.has(d)||i&&!i.has(d)||(a[d]=c);if(t)for(let d of t.fields){if(d.type!=="reference"||!(d.referenceTo??[]).some(l=>r.has(l)))continue;let c=a[d.name];typeof c=="string"&&n.has(c)&&(a[d.name]=n.get(c))}for(let d of ui(s,a))delete a[d];return a}var sT=new Set(["double","currency","percent","int","integer"]),Wa=class{validate(e,t,r,n){let o=[],i=new Map(r.map(a=>[a.name,a]));for(let a=0;a<e.length&&o.length<100;a++){let d=e[a];for(let c of t){if(o.length>=100)break;if(!c.sfFieldApiName)continue;let l=i.get(c.sfFieldApiName);if(!l)continue;let u=d[c.csvHeader]??"";if(u===""&&!l.nillable&&l.defaultValue===null){o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"missing_required",message:`Required field "${c.sfFieldApiName}" is empty`,value:u});continue}if(u!==""){if(sT.has(l.type.toLowerCase())){let p=parseFloat(u);isNaN(p)&&o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"type_mismatch",message:`Expected numeric value for field "${c.sfFieldApiName}", got "${u}"`,value:u})}l.length&&l.length>0&&u.length>l.length&&o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"length_exceeded",message:`Value exceeds max length ${l.length} for field "${c.sfFieldApiName}" (got ${u.length})`,value:u}),l.type.toLowerCase()==="picklist"&&l.picklistValues&&l.picklistValues.length>0&&(l.picklistValues.map(g=>g.value).includes(u)||o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"invalid_picklist",message:`Invalid picklist value "${u}" for field "${c.sfFieldApiName}"`,value:u}))}}}if(n&&o.length<100){let a=t.find(d=>d.sfFieldApiName===n);if(a){let d=new Map;for(let c=0;c<e.length&&o.length<100;c++){let l=e[c][a.csvHeader]??"";if(l==="")continue;let u=d.get(l);u!==void 0?o.push({row:c+1,column:a.csvHeader,field:n,errorType:"duplicate_external_id",message:`Duplicate external ID "${l}" (also in row ${u})`,value:l}):d.set(l,c+1)}}}return{valid:o.length===0,errors:o,warningCount:0}}};var iT=new Set(["seed:csv:validate","seed:csv:execute"]),aT=100,av="IMPORT_CANCELLED",dT=6e4,za=class{constructor(e){this.deps=e}deps;registry;liveTracker;setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}runCreations;runningRuns=new Set;setRunCreations(e){this.runCreations=e}isRunning(e){return this.runningRuns.has(e)}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-4XZ5YT5O.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handle(e){if(!iT.has(e.type))return!1;switch(e.type){case"seed:csv:validate":return await this.handleValidate(e),!0;case"seed:csv:execute":return await this.handleExecute(e),!0;default:return!1}}async endKept(e,t,r){if(!e)return!1;try{return await e.end({finishedAt:new Date().toISOString(),status:r.status,...r.cancelled?{cancelled:!0}:{},objectResults:[]}),!0}catch(n){return this.deps.log(`[WARN] seed:csv:execute ${t}: what the import created could not all be kept, so removing it may leave some of it in the org: ${T(n)}`),!1}finally{this.runningRuns.delete(t)}}stoppedForCheckpoint(e,t,r,n){let{operationId:o}=t;if(r.code===Ze){X(this.deps,{...t,outcome:"stopped",source:void 0,code:av}),this.registry?.abort(o),pe(this.deps,o,{aborted:!0,insertedCount:0,failedCount:0}),this.liveTracker?.cancel(o);let d={insertedCount:0,failedCount:0,errors:[],cancelled:!0};this.deps.broker.postToWebview(A(this.deps,e,"seed:csv:execute:response",d));return}let i=r.refusal?.code,a=i!==void 0?{checkpointRefusal:i}:{};X(this.deps,{...t,outcome:"stopped",source:void 0,code:r.code,...i!==void 0?{details:a}:{}}),P(this.deps,"seed:csv:execute","seed:csv:error",e,r,{code:r.code,retryable:!1,...i!==void 0?{extraPayload:a}:{}}),Le(this.deps,o,r.message,!1,{context:n,authored:!0,extraPayload:{code:r.code,...a}}),this.liveTracker?.fail(o,r.message)}async handleValidate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(ol,e,"seed:csv:error",this.deps);if(t)try{let r=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),n=await r.describe(t.objectApiName);De(r.limitInfo,`seed:csv:validate describe ${t.objectApiName}`);let i=new Wa().validate(t.records,t.columnMappings,n.fields,t.externalIdField),a=A(this.deps,e,"seed:csv:validate:response",i);this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} valid=${i.valid}`)}catch(r){P(this.deps,"seed:csv:validate","seed:csv:error",e,r)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(ol,e,"seed:csv:error",this.deps);if(!t)return;let r=e.id,n={module:"seed",operation:e.type,objectName:t.objectApiName},o=new AbortController,i=()=>{},a=new Promise((h,f)=>{i=m=>m===void 0?h():f(m)});a.catch(()=>{}),this.registry?.register(r,"csv","CSV import",a,o);let d={action:"seed_csv_import",module:"seed",operationId:r,orgId:t.orgId,outcome:"failure",source:{origin:"csv"}},c=!1,l,u=0,p,g=!1;try{let h=this.deps.infraServices?.productionGuard;if(!h){X(this.deps,{...d,outcome:"stopped",source:void 0,code:ve.code}),P(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(ve.message),{code:ve.code,retryable:!1}),Le(this.deps,r,ve.message,!1,{context:n,extraPayload:{code:ve.code}}),i(new Error(ve.message));return}let f=this.deps.orgManager.getOrg(t.orgId),m={orgId:t.orgId,orgTier:Ee(f),operation:t.externalIdField?"upsert":"insert",objectName:t.objectApiName,recordCount:t.records.length,module:"seed"},{check:y,decision:w}=await Ke(h,m);if(d.guard=w,(w==="refused"||w==="declined")&&X(this.deps,{...d,outcome:"stopped",source:void 0}),w==="refused")throw Jr(y.blockedReason??y.impactSummary);if(w==="declined"){let le="Operation cancelled by user (confirmation declined).";P(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(le),{code:St.declined}),Le(this.deps,r,le,!1,{context:n}),i(new Error(le));return}let v=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),R=Re(f,t.orgId),b=(le,Se,je)=>{let M=je!==void 0?{checkpointRefusal:je}:{};X(this.deps,{...d,outcome:"stopped",source:void 0,code:le,...je!==void 0?{details:M}:{}}),P(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(Se),{code:le,retryable:!1,...je!==void 0?{extraPayload:M}:{}}),Le(this.deps,r,Se,!1,{context:n,authored:!0,extraPayload:{code:le,...M}}),i(new Error(Se))},O=this.targetAutomation,k=ks([t.objectApiName],!!t.externalIdField),S=await new ge(dT).withTimeout("csv automation",()=>O.read(t.orgId,[t.objectApiName])).catch(le=>({unread:T(le)}));typeof S.unread=="string"&&this.deps.log(`[WARN] seed:csv:execute ${r}: what the org runs on ${t.objectApiName} could not be read (${S.unread}): it is asked about its emails, and a checkpoint holds the object alone`);let E=await Vt({read:S,writes:k,readDeliverability:()=>Ee(f)==="production"?Promise.resolve(Mt):jt(v),accepted:!1,target:R,run:"seed",keepsAddresses:!0}),I=E.gate.verdict==="asks",C;if(t.checkpointFirst!==void 0){try{C=await vs(this.beforeRunCheckpoints,{module:"seed",orgId:t.orgId,operationId:r,written:[t.objectApiName],running:_a(S,k),request:t.checkpointFirst})}catch(Se){if(!(Se instanceof Nt))throw Se;b(Se.code,Se.message);return}let le=zi(C.planned);if(le){b(le.code,le.message,le.refusal.code);return}}let F=C||I?await dr(v).catch(le=>({unread:T(le)})):void 0,Y=F!==void 0&&!("unread"in F)?F.dailyApiRequests:await Xt(v).catch(le=>({unread:T(le)})),z=en({run:Pb([{objectApiName:t.objectApiName,rows:t.records.length}],{threshold:st(this.deps).bulk.threshold,perCall:this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200),duplicateRules:fo(S)})+Cb(0,nn(S)),...po(C?.planned),...on(E.ofRun)},Y);z.verdict==="unread"&&this.deps.log(`[WARN] seed:csv:execute ${r}: the daily API requests the org has left could not be read (${z.unread})`);let te=Wi(z,Re(f,t.orgId));if(te){X(this.deps,{...d,outcome:"stopped",source:void 0,code:lo}),P(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(te),{code:lo,retryable:!1}),Le(this.deps,r,te,!1,{context:n,authored:!0,extraPayload:{code:lo}}),i(new Error(te));return}let H=!1;if(C||I){let le=t.records.length,Se=await h.confirmRun({stage:"write",module:"seed",org:R,orgTier:Ee(f),objects:[{objectApiName:t.objectApiName,rows:le}],total:le,storage:sn(rn({storageBytes:qi(t.objectApiName,{rows:le})},F??{unread:"not read"})),...uo(z),...C?{checkpoint:C.planned}:{},...E.gate.confirmation});if(Se!=="confirmed"){let je=E.gate.stop;Se!=="declined"&&!C&&je?b(je.code,je.message):b(Se==="declined"?Oo:yt.unanswered,Se==="declined"?"The import was cancelled before it wrote anything. Nothing was written.":`The import needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${R} \u2014 and there was no one to ask. Nothing was written.`);return}H=I}if(d.details=$r({read:E,accepted:H}).details,We(this.deps,r,"seed",`CSV import ${t.records.length} record(s) into ${t.objectApiName}`),this.liveTracker?.register(r,"csv",`CSV import ${t.records.length} record(s) into ${t.objectApiName}`,t.records.length),C)try{p=await Ss(this.beforeRunCheckpoints,C,r,o.signal,(le,Se,je,M)=>{$e(this.deps,r,le,Se,je,M),this.liveTracker?.updateProgress(r,le,Se,je,M)})}catch(le){if(!(le instanceof Nt))throw le;this.stoppedForCheckpoint(e,d,le,n),i(le.code===Ze?void 0:le);return}c=!0;let x=st(this.deps),j=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200;n.batchSize=j,l=this.runCreations?.recorder({runId:r,targetOrgId:t.orgId,startedAt:new Date().toISOString(),origin:"csv"}),p&&l?.checkpoint?.(p),lr(l,()=>v.identity(),`seed:csv:execute ${r}`),l&&this.runningRuns.add(r);let K=new an({connection:v,bulkExecutor:new Xr(x.bulk.threshold),bulkManager:nr(this.deps),retryConfig:x.retry,signal:o.signal,onProgress:(le,Se,je)=>{let M=Se>0?Math.round(le/Se*100):0;$e(this.deps,r,M,le,Se,je),this.liveTracker?.updateProgress(r,M,le,Se,je)},log:le=>this.deps.log(le),...l?{calls:Ua(l,le=>{u+=le})}:{}}),Q=t.records.map(le=>cT(le,t.columnMappings)),_=o.signal.aborted,V=[];if(!_){Q.length>0&&(g=!0);try{V=t.externalIdField?await K.upsert(t.objectApiName,t.externalIdField,Q,j):await K.insert(t.objectApiName,Q,j)}catch(le){if(!(le instanceof vo))throw le;_=!0,V=le.written}}let ue=[],me=0;for(let le of V)le.success?me++:ue.length<aT&&ue.push(le.errors[0]??"Unknown insert error");let re=V.length-me,ie=re===0?"success":me>0?"partial":"failure",Be=!_&&ie==="failure"?ue[0]??"No row could be imported.":void 0;c=!1;let fe=await ln(this.beforeRunCheckpoints,p,g,this.deps.log,`seed:csv:execute ${r}`);p=void 0,_&&V.length===0?X(this.deps,{...d,outcome:"stopped",source:void 0,code:av}):X(this.deps,{...d,outcome:_?"cancelled":ie,objects:[{...at(t.objectApiName),...t.externalIdField?{upserted:me}:{created:me},failed:re}],...fe?.state==="taken"?{checkpointId:fe.checkpointId}:{}});let ne=await this.endKept(l,r,{status:_&&ie==="success"?"partial":ie,cancelled:_});l=void 0;let ce={insertedCount:me,failedCount:re,errors:ue,..._?{cancelled:!0}:{},...ne&&u>0?{runId:r}:{},...fe?{checkpoint:fe}:{}};_?(this.registry?.abort(r),pe(this.deps,r,{aborted:!0,insertedCount:me,failedCount:re}),this.liveTracker?.cancel(r)):(pe(this.deps,r,{status:ie,insertedCount:me,failedCount:re}),Be!==void 0?this.liveTracker?.fail(r,Be):ie==="partial"?this.liveTracker?.partial(r):this.liveTracker?.complete(r));let we=A(this.deps,e,"seed:csv:execute:response",ce);this.deps.broker.postToWebview(we),this.deps.log(`[TX] ${we.type} id=${we.id} inserted=${me} failed=${re}`),i(Be===void 0?void 0:new Error(Be))}catch(h){let f=await ln(this.beforeRunCheckpoints,p,g,this.deps.log,`seed:csv:execute ${r}`);c&&X(this.deps,{...d,...f?.state==="taken"?{checkpointId:f.checkpointId}:{}}),await this.endKept(l,r,{status:"failure",cancelled:!1});let m=f?.state==="deleted"?`${T(h)} ${xr}`:T(h);P(this.deps,"seed:csv:execute","seed:csv:error",e,h,{code:to(h),retryable:!0,...f?{extraPayload:{checkpoint:f}}:{}}),Le(this.deps,r,m,!0,{context:n}),this.liveTracker?.fail(r,m),i(h)}}};function cT(s,e){let t={};for(let r of e){if(!r.sfFieldApiName)continue;let n=s[r.csvHeader];n===void 0||n===""||(t[r.sfFieldApiName]=lT(n))}return t}function lT(s){if(s==="true")return!0;if(s==="false")return!1;if(s==="null")return null;let e=Number(s);return!Number.isNaN(e)&&s.trim()!==""?e:s}var uT={string:new Set(["string","textarea","richtext","phone","email","url","picklist","multipicklist","encryptedstring"]),int:new Set(["int","double","currency","percent","string"]),double:new Set(["double","currency","percent","string"]),currency:new Set(["currency","double","string"]),percent:new Set(["percent","double","string"]),boolean:new Set(["boolean","string"]),date:new Set(["date","datetime","string"]),datetime:new Set(["datetime","date","string"]),id:new Set(["id","reference","string"]),reference:new Set(["reference","id","string"]),picklist:new Set(["picklist","string","multipicklist"]),multipicklist:new Set(["multipicklist","string"]),phone:new Set(["phone","string"]),email:new Set(["email","string"]),url:new Set(["url","string"]),textarea:new Set(["textarea","richtext","string"]),richtext:new Set(["richtext","textarea","string"]),time:new Set(["time","string"]),base64:new Set(["base64","string"]),address:new Set(["address"]),location:new Set(["location"])},pT=[{source:"double",target:"int",reason:"Decimal portion will be truncated"},{source:"datetime",target:"date",reason:"Time portion will be lost"},{source:"richtext",target:"textarea",reason:"HTML formatting will be lost"},{source:"multipicklist",target:"picklist",reason:"Multiple selections may be lost"}];function ru(s,e){let t=s.toLowerCase(),r=e.toLowerCase();if(t===r)return!0;let n=uT[t];return n?n.has(r):r==="string"}var Ga=class{validateMapping(e,t,r){let n=[],o=[],i=new Map(e.map(d=>[d.apiName,d])),a=new Map(t.map(d=>[d.apiName,d]));for(let[d,c]of Object.entries(r)){let l=i.get(d),u=a.get(c);if(!l||!u)continue;let p=this.checkTypeCompatibility(d,l.type,c,u.type);p.compatible?p.reason&&o.push(p):n.push(p)}return{valid:n.length===0,errors:n,warnings:o}}validateRecords(e,t){let r=[];for(let n=0;n<e.length;n++){let o=e[n];for(let i of t){let a=o[i.apiName];if(i.required&&dv(a)){r.push({recordIndex:n,field:i.apiName,message:`Required field '${i.apiName}' is missing or empty`});continue}if(dv(a))continue;let d=this.validateValueType(a,i);if(d){r.push({recordIndex:n,field:i.apiName,message:d});continue}if(i.maxLength!==void 0&&typeof a=="string"&&a.length>i.maxLength&&r.push({recordIndex:n,field:i.apiName,message:`Value exceeds max length of ${i.maxLength} (got ${a.length})`}),i.picklistValues&&i.picklistValues.length>0){let c=String(a);i.picklistValues.includes(c)||r.push({recordIndex:n,field:i.apiName,message:`Value '${c}' is not a valid picklist value. Allowed: ${i.picklistValues.join(", ")}`})}}}return{valid:r.length===0,errors:r}}checkTypeCompatibility(e,t,r,n){let o=t.toLowerCase(),i=n.toLowerCase();if(o===i)return{sourceField:e,sourceType:t,targetField:r,targetType:n,compatible:!0};let a=ru(o,i),d=pT.find(c=>c.source===o&&c.target===i);return{sourceField:e,sourceType:t,targetField:r,targetType:n,compatible:a,reason:a?d?.reason:`Type '${t}' is not compatible with '${n}'`}}validateValueType(e,t){let r=t.type.toLowerCase();switch(r){case"boolean":if(typeof e!="boolean")return`Expected boolean but got ${typeof e}`;break;case"int":if(typeof e!="number"||!Number.isInteger(e))return`Expected integer but got ${typeof e=="number"?"float":typeof e}`;break;case"double":case"currency":case"percent":if(typeof e!="number")return`Expected number but got ${typeof e}`;break;case"date":case"datetime":if(typeof e!="string"||!gT(e))return`Expected valid ${r} string`;break}}};function dv(s){return s==null||s===""}function gT(s){let e=Date.parse(s);return!isNaN(e)}var Ja=class{paused=!1;waiting=new Set;get isPaused(){return this.paused}pause(){this.paused=!0}resume(){this.paused=!1;let e=[...this.waiting];this.waiting.clear();for(let t of e)t()}async whilePaused(e){!this.paused||e?.aborted||await new Promise(t=>{let r=()=>{this.waiting.delete(r),e?.removeEventListener("abort",r),t()};this.waiting.add(r),e?.addEventListener("abort",r,{once:!0})})}};var nu=3e4,lv=6e4,ou="Nothing was read or written.",hT="Nothing was read.",uv="the checkpoints of this window are not open to the Sync page",mT=new Set(["sync:execute","sync:simulate","sync:write-order","sync:pause","sync:resume","sync:describe-global","sync:describe-fields","sync:config:save","sync:config:load","sync:config:list","sync:config:delete","sync:config:reset-delta"]),pv={insert:0,update:1,upsert:2,delete:3};function iu(s,e){let t=s.objects??[],r="insert";for(let o of t)pv[o.operation]>pv[r]&&(r=o.operation);s.mode==="delta"&&s.propagateDeletes===!0&&(r="delete");let n=t.map(o=>o.objectApiName);return{orgId:s.targetOrgId,orgTier:Ee(e),operation:r,objectName:n.length>0?n.join(", "):"SyncData",recordCount:"unknown",module:"sync"}}function yT(s){return s.map(e=>{let t={...at(e.objectApiName),failed:e.failed+(e.delta?.deleteFailed??0),deleted:e.delta?.deleted??0};switch(e.operation){case"insert":return{...t,created:e.success};case"update":return{...t,updated:e.success};case"delete":return{...t,deleted:e.success};case"upsert":{let r=e.upsertSplit??{created:0,updated:0},n=e.success-r.created-r.updated;return{...t,created:r.created,updated:r.updated,...n>0?{upserted:n}:{}}}}})}var wT=new Set(["direct","rename"]),su=20,bT=G({fields:ke(G({name:L(),type:L(),createable:ze(),updateable:ze()}).loose())});function gv(s,e,t){let r=bT.safeParse(s);if(r.success)return r.data.fields;let n=r.error.issues[0];throw new Error(`The ${t} org described ${e} in a shape field types cannot be compared on (${n.path.join(".")}: ${n.message}), so the sync was not started and nothing was written.`)}function fv(s){if(s==="ask")return{emailsLiftedBy:"Untick Mute automation to be asked about them and sync all the same"};let e=py();return e?{emailsAccepted:e.approved,emailsLiftedBy:"Approve an Approval step put before this Sync step to sync all the same"}:{emailsLiftedBy:"Run it from the Sync page, which asks before it writes, to sync all the same"}}var Va=class{constructor(e){this.deps=e;this.syncConfigStore=new Pt(e.configStore)}deps;activeOperationIds=new Set;dmlTracker=new hi;syncConfigStore;registry;historyLogger;liveTracker;pauseGates=new Map;runCreations;backupRecords;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-4XZ5YT5O.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",Mr);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):Mr}writeGateFor(e,t,r,n,o,i){let a=this.deps.orgManager.getOrg(e.targetOrgId),d=this.targetAutomation,c=this.deps.infraServices?.productionGuard,l=fv(r),u=cl(a?.orgType==="Sandbox"||a?.orgType==="Scratch"),p=jb(e,async g=>{let{totalSize:h}=await t.query(g);return u==="production"?Math.min(h,dl(u).defaultQueryLimit):h});return Nb({readStorage:()=>new ge(nu).withTimeout("sync:limits",()=>dr(t)),readApiBudget:()=>new ge(nu).withTimeout("sync:limits",()=>Xt(t)),readAutomation:n??(g=>new ge(lv).withTimeout("sync:automation",()=>d.read(e.targetOrgId,g))),readLimits:()=>new ge(nu).withTimeout("sync:limits",()=>cr(t)),readDeliverability:()=>Ee(a)==="production"?Promise.resolve(Mt):jt(t),emails:{target:Re(a,e.targetOrgId),accepted:l.emailsAccepted===!0,keepsAddresses:e.keepContactPoints===!0},confirmAboveRecords:this.confirmAboveRecords(),bulkThreshold:st(this.deps).bulk.threshold,...o?{checkpointFirst:o}:{},...i?{mutePlan:i}:{},...p?{countTarget:p}:{}},{policy:r,org:Re(a,e.targetOrgId),orgTier:Ee(a),...c?{confirm:g=>c.confirmRun(g)}:{},emailsLiftedBy:l.emailsLiftedBy})}setRegistry(e){this.registry=e}setMuteLeases(e){this.muteLeases=e}muteLeases={};setHistoryLogger(e){this.historyLogger=e}setLiveOperationTracker(e){this.liveTracker=e}setRunCreations(e){this.runCreations=e}setBackupRecordStore(e){this.backupRecords=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;runCheckpointOf(e,t,r,n){let o=this.beforeRunCheckpoints,i={runId:t},a,d,c,l;return{gate:{scope:async(u,p)=>{if(!o)throw new Error(uv);return a={module:"sync",orgId:e.targetOrgId,operationId:t,written:[...u],running:p,request:r},d=await o.scope(a,i),l=d.refusal,d},take:async u=>{if(!o||!a)throw new Error(uv);let p=await o.take(a,i,{planned:u,...n?{signal:n.signal,onProgress:g=>{let h=co(g.percentage),f=Math.round(g.percentage),{processedObjects:m,totalObjects:y}=g;$e(this.deps,t,f,m,y,h),this.liveTracker?.updateProgress(t,f,m,y,h)}}:{}});return p.taken?(c=p.checkpoint,n?.recorder?.checkpoint?.(p.checkpoint)):"refusal"in p&&(l=p.refusal),p}},planned:()=>d,taken:()=>c,refusal:()=>l}}async settleRunCheckpoint(e,t,r){let n=e?.taken();if(!(!n||!this.beforeRunCheckpoints))try{return await this.beforeRunCheckpoints.settle(n,t)}catch(o){return this.deps.log(`[WARN] sync ${r}: the checkpoint '${n.name}' taken before the run is kept: ${T(o)}`),n}}isRunning(e){return this.activeOperationIds.has(e)}async handle(e){if(!mT.has(e.type))return!1;switch(e.type){case"sync:describe-global":return await this.handleDescribeGlobal(e),!0;case"sync:describe-fields":return await this.handleDescribeFields(e),!0;case"sync:execute":return await this.handleExecute(e),!0;case"sync:simulate":return await this.handleSimulate(e),!0;case"sync:write-order":return await this.handleWriteOrder(e),!0;case"sync:pause":return await this.handleRunControl(e,"pause"),!0;case"sync:resume":return await this.handleRunControl(e,"resume"),!0;case"sync:config:save":return await this.handleConfigSave(e),!0;case"sync:config:load":return await this.handleConfigLoad(e),!0;case"sync:config:list":return await this.handleConfigList(e),!0;case"sync:config:delete":return await this.handleConfigDelete(e),!0;case"sync:config:reset-delta":return await this.handleConfigResetDelta(e),!0;default:return!1}}refusedFieldless(e,t,r,n,o){let i=qo(t.objects);return i.length===0?!1:(P(this.deps,r,n,e,new Error(`${Wo(i)} ${o}`),{code:Bc,extraPayload:{rules:i}}),!0)}async handleConfigSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(mf,e,"sync:error",this.deps);if(t&&!this.refusedFieldless(e,t.config,"sync:config:save","sync:error","Nothing was saved."))try{let r=t.config;if(fg(this.syncConfigStore.list(),r.id,r.name)){let o=A(this.deps,e,"sync:config:save:response",{success:!1,id:r.id,code:"DUPLICATE_NAME"});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} DUPLICATE_NAME`);return}this.syncConfigStore.save(r);let n=A(this.deps,e,"sync:config:save:response",{success:!0,id:r.id});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){P(this.deps,"sync:config:save","sync:error",e,r)}}async handleConfigLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(yi,e,"sync:error",this.deps);if(t)try{let r=this.syncConfigStore.load(t.id),n=A(this.deps,e,"sync:config:load:response",{config:r??null});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){P(this.deps,"sync:config:load","sync:error",e,r)}}async handleConfigList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let r=this.syncConfigStore.list().map(o=>{let i=this.syncConfigStore.loadDelta(o.id);return{id:o.id,name:o.name,description:o.description,updatedAt:o.updatedAt,mode:o.mode,propagateDeletes:o.propagateDeletes===!0,watermarks:i.kind==="stored"?i.state.entries.length:0}}),n=A(this.deps,e,"sync:config:list:response",{configs:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(t){P(this.deps,"sync:config:list","sync:error",e,t)}}async handleConfigDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(yi,e,"sync:error",this.deps);if(t)try{let r=this.syncConfigStore.delete(t.id);await this.runCreations?.idMap().delete(t.id).catch(o=>this.deps.log(`[WARN] sync:config:delete ${t.id}: ${T(o)}`));let n=A(this.deps,e,"sync:config:delete:response",{success:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){P(this.deps,"sync:config:delete","sync:error",e,r)}}async handleConfigResetDelta(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(yi,e,"sync:error",this.deps);if(t)try{if(!this.syncConfigStore.load(t.id))throw new Error("This configuration is no longer saved: there is nothing to reset.");let r=this.syncConfigStore.clearDelta(t.id),n=A(this.deps,e,"sync:config:reset-delta:response",{success:!0,id:t.id,cleared:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} cleared=${r}`)}catch(r){P(this.deps,"sync:config:reset-delta","sync:error",e,r)}}deltaStoreFor(){return this.syncConfigStore.deltaStore()}fileStoreFor(){return this.syncConfigStore.fileStore()}idMapFor(){let e=this.runCreations;if(e)return Zm(e.idMap(),t=>this.syncConfigStore.isSaved(t))}recordRun(e,t,r,n,o,i){let a=yT(r.objectResults??[]),d=a.some(l=>l.created+l.updated+l.deleted+l.failed+(l.upserted??0)>0),c=r.cancelled===!0?d?"cancelled":"stopped":r.status;X(this.deps,{action:"sync_execute",module:"sync",operationId:t,orgId:e.targetOrgId,outcome:c,...c==="stopped"?{code:Ze}:{},guard:n,objects:a,source:{origin:"org",orgId:e.sourceOrgId},details:{triggeredBy:o,...En(i)},...r.mutedAutomation?{muted:ot(r.mutedAutomation)}:{},...r.checkpoint?.state==="taken"?{checkpointId:r.checkpoint.checkpointId}:{}})}recordRefused(e,t,r){X(this.deps,{action:"sync_execute",module:"sync",operationId:e,orgId:t,outcome:"stopped",code:r})}recordStopped(e,t,r){X(this.deps,{action:"sync_execute",module:"sync",operationId:e,orgId:t,outcome:"stopped",guard:r})}buildGuardRequest(e){return iu(e,this.deps.orgManager.getOrg(e.targetOrgId))}async assertFieldTypesMatch(e,t,r,n){let o=new Ga,i=[],a=l=>({apiName:l.name,type:l.type});for(let l of e.objects){if(l.operation==="delete")continue;let u=l.objectApiName,p=new ge(n),[g,h]=await Promise.all([p.withTimeout(`describe-source-${u}`,()=>Ut(e.sourceOrgId,u,()=>t.describe(u))),p.withTimeout(`describe-target-${u}`,()=>Ut(e.targetOrgId,u,()=>r.describe(u)))]),f=gv(g,u,"source").map(a),m=gv(h,u,"target").filter(R=>R.createable||R.updateable).map(a),y=wb(l,{creatable:new Set(m.map(R=>R.apiName))}),w=af(y.fieldMappings,y.excludedFields),v=[Object.fromEntries(f.filter(R=>!w.has(R.apiName.toLowerCase())).map(R=>[R.apiName,R.apiName])),...l.fieldMappings.filter(R=>wT.has(R.type)).map(R=>({[R.sourceField]:R.targetField}))];for(let R of v)for(let b of o.validateMapping(f,m,R).errors)i.push(`${u}.${b.sourceField} (${b.sourceType}) -> ${u}.${b.targetField} (${b.targetType})`)}if(i.length===0)return;let d=i.slice(0,su).join("; "),c=i.length>su?` and ${i.length-su} more`:"";throw new Error(`Field types do not match between the orgs, so the sync was not started and nothing was written: ${d}${c}. Map each field onto a field of a compatible type, or convert the value with a transform.`)}async handleDescribeGlobal(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(yf,e,"sync:error",this.deps);if(!t)return;let r=st(this.deps);try{let n=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),o=new ge(r.timeouts.describeGlobal),i=await o.withTimeout("describe-global",()=>n.describeGlobal());De(n.limitInfo,"sync:describe-global");let a=i.sobjects.filter(u=>u.queryable&&!mi(u.name)),d,c=[];if(t.targetOrgId===void 0)d=a.filter(u=>u.createable).map(u=>u.name);else{let u=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),p=await o.withTimeout("describe-global",()=>u.describeGlobal());De(u.limitInfo,"sync:describe-global target");let g=new Map(p.sobjects.map(h=>[h.name,{createable:h.createable,updateable:h.updateable}]));d=[];for(let h of a){let f=g.get(h.name);if(f&&(f.createable||f.updateable)){d.push(h.name);continue}h.createable&&c.push({objectApiName:h.name,why:f?"notCreateable":"notInTarget"})}}let l=A(this.deps,e,"sync:describe-global:response",{objects:d,...c.length>0?{unwritable:c}:{}});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(n){P(this.deps,"sync:describe-global","sync:error",e,n)}}async handleDescribeFields(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(wf,e,"sync:error",this.deps);if(!t)return;let r=t,n=st(this.deps);try{let o=await B(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await B(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=new ge(n.timeouts.describe),[d,c]=await Promise.all([a.withTimeout("describe-source",()=>o.describe(r.objectApiName)),a.withTimeout("describe-target",()=>i.describe(r.objectApiName))]);De(o.limitInfo,`sync:describe-fields source ${r.objectApiName}`),De(i.limitInfo,`sync:describe-fields target ${r.objectApiName}`);let l=p=>p.filter(g=>g.createable).map(g=>({apiName:g.name,label:g.label,type:g.type})),u=A(this.deps,e,"sync:describe-fields:response",{objectApiName:r.objectApiName,sourceFields:l(d.fields),targetFields:l(c.fields)});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(o){P(this.deps,"sync:describe-fields","sync:error",e,o)}}async handleWriteOrder(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(el,e,"sync:error",this.deps);if(!t)return;let r=t.config;try{let n=await B(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),o=st(this.deps).timeouts.describe,i=new Map;for(let l of r.objects){if(l.operation==="delete")continue;let u=l.objectApiName;try{let p=await new ge(o).withTimeout(`describe-target-${u}`,()=>Ut(r.targetOrgId,u,()=>n.describe(u)));i.set(u,Ob(l,ur(p)))}catch{}}let{order:a}=Ib(r.objects,i),d=await this.encryptedMaskedOf(r,o).catch(()=>[]),c=A(this.deps,e,"sync:write-order:response",{order:a,...d.length>0?{encrypted:d}:{}});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(n){P(this.deps,"sync:write-order","sync:error",e,n)}}async encryptedMaskedOf(e,t){let r=e.objects.filter(a=>a.operation!=="delete");if(r.length===0)return[];let n=await B(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=Tn(sr(async a=>(await n.query(a)).records),a=>new ge(t).withTimeout(`describe-source-${a}`,()=>Ut(e.sourceOrgId,a,()=>n.describe(a)))),i=[];for(let a of r){let d=await o(a.objectApiName);d.length>0&&i.push({objectApiName:a.objectApiName,fields:d})}return i}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(kn,e,"sync:error",this.deps);t&&(this.refusedFieldless(e,t.config,"sync:execute","sync:error",ou)||await this.startExecution(e,t.config,"manual",t.muteAutomation===!0,t.checkpointFirst))}async handleSimulate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(el,e,"sync:error",this.deps);if(!t||this.refusedFieldless(e,t.config,"sync:simulate","sync:error",hT))return;let r=e.id,n=t.config,o=`Simulation of a sync of ${n.objects.length} object(s), writing nothing`,i=new AbortController;We(this.deps,r,"sync",o),this.liveTracker?.register(r,"sync",o);let a=this.simulateSync(e,n,r,i,t.checkpointFirst);if(this.registry){let d=a.then(c=>({status:c===null||c.error?"failure":"success"}));this.registry.register(r,"sync",o,d,i)}else await a}async simulateSync(e,t,r,n,o){let i=st(this.deps),a={module:"sync",operation:e.type,...Er(t.objects)};try{let d=await this.readersFor(t,n.signal),{DataSync:c}=await import("./chunk-SFURUNJM.mjs"),{ConflictResolver:l}=await import("./chunk-CHCHAE4B.mjs"),{FieldMappingService:u}=await import("./chunk-P7GSGFJO.mjs"),{TransformPipeline:p}=await import("./chunk-2BVTCNWA.mjs"),{toolingQueriesOver:g,toolingValidationRules:h}=await import("./chunk-X2PY6MWZ.mjs"),{toolingRetrievesOver:f}=await import("./chunk-4XZ5YT5O.mjs"),m=d.targetConn.tooling,y=async()=>{throw new Error("A simulation writes nothing: the write it reached was refused.")},w=new c({insert:y,update:y,upsert:y,delete:y,describeTargetFields:d.describeTargetFields});if(!this.deps.services)throw new Error("SyncOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let v=o?this.runCheckpointOf(t,r,o):void 0,R=this.deps.services.syncOrchestrator({dataSync:w,conflictResolver:new l,fieldMapping:new u,transformPipeline:new p,querySource:d.querySource,maskedSourceFields:d.maskedSourceFields,queryTarget:d.queryTarget,services:this.deps.services,signal:n.signal,findInTarget:d.findInTarget,describeTargetFields:d.describeTargetFields,readSourceIds:d.readSourceIds,countSource:d.countSource,countPersonAccounts:d.countPersonAccounts,writeGate:this.writeGateFor(t,d.targetConn,"ask",void 0,v?.gate),queryTargetRows:d.queryTargetRows,recordTypes:d.recordTypes,currencies:d.currencies,standardPricebooks:d.standardPricebooks,deltaStore:this.deltaStoreFor(),deltaReads:d.deltaReads,idMap:this.idMapFor(),files:d.files,readValidationRules:h(async E=>(await or({query:async I=>m.query(I),queryMore:async I=>m.queryMore(I)},E)).records,g(d.targetConn),f(d.targetConn)),onSimulationProgress:(E,I,C)=>{let F=Math.round(E/I*100),Y=`Simulating ${C}`;$e(this.deps,r,F,E,I,Y),this.liveTracker?.updateProgress(r,F,E,I,Y)}});await this.assertFieldTypesMatch(t,d.sourceConn,d.targetConn,i.timeouts.describe);let b=await R.simulate(t),O=v?.planned(),k={...b,...O?{checkpoint:O}:{},operationId:r};k.cancelled?this.endCancelled(r):k.error?(this.liveTracker?.fail(r,k.error),Le(this.deps,r,k.error,!0,{context:a})):($e(this.deps,r,100,1,1,"Simulation complete"),pe(this.deps,r,{status:"success",simulated:!0}),this.liveTracker?.complete(r)),this.deps.log(`[sync] simulation ${r} ${k.cancelled?"stopped":"finished"}: `+k.objects.map(E=>`${E.objectApiName} insert=${E.insert} update=${E.update} delete=${E.delete} skipped=${E.skipped} refused=${E.refused} conflicts=${E.conflicts}`).join("; "));let S=A(this.deps,e,"sync:simulate:response",k);return this.deps.broker.postToWebview(S),this.deps.log(`[TX] ${S.type} id=${S.id}`),k}catch(d){return this.liveTracker?.fail(r,T(d)),P(this.deps,"sync:simulate","sync:error",e,d),Le(this.deps,r,T(d),!0,{context:a}),null}}async handleRunControl(e,t){this.deps.log(`[RX] ${e.type} id=${e.id}`);let r=D(hf,e,"sync:error",this.deps);if(!r)return;let{operationId:n}=r,o=t==="pause"?"sync:pause:response":"sync:resume:response",i=this.pauseGates.get(n),a;i?(t==="pause"?(i.pause(),this.liveTracker?.pause(n)):(i.resume(),this.liveTracker?.resume(n)),a={success:!0,operationId:n,paused:i.isPaused}):a={success:!1,operationId:n,paused:!1,error:"No sync with this id is running: it has finished, or it was not started here."};let d=A(this.deps,e,o,a);this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id} paused=${a.paused}`)}async readersFor(e,t){let r=st(this.deps),n=await B(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=E=>{let I=this.deps.orgManager.getOrg(E),C=cl(I?.orgType==="Sandbox"||I?.orgType==="Scratch");return{tier:C,limits:dl(C)}},a=new Qi({retryConfig:r.retry}),d=(E,I)=>async(C,F,Y)=>{let z=pt(F.objectApiName),te="",H=rs(F.where,Y?.changedSince);H&&(te+=` WHERE ${H}`),F.orderBy&&(te+=` ORDER BY ${Kc(F.orderBy)}`);let{tier:x,limits:j}=i(I);x==="production"&&(te+=` LIMIT ${j.defaultQueryLimit}`);let K=!1,Q=await a.execute(async()=>{K=!1;let ue=(await E.describe(z)).fields.map(ie=>ie.name),me=ue.length>0?ue:["Id"],re={query:async ie=>E.query(ie),queryMore:async ie=>E.queryMore(ie)};return es(`SELECT ${me.join(", ")} FROM ${z}${te}`,async ie=>{let Be=await or(re,ie);return K||=Be.truncated,Be.records})});if(!Q.success)throw Q.error??new Error("Query failed after retries");De(E.limitInfo,`sync:execute query ${z}`);let _=Q.result??[],V=x==="production"&&_.length>=j.defaultQueryLimit;if(K||V){Y?.onBoundReached?.();let ue=V?`${j.defaultQueryLimit} records (production-tier query cap)`:`${5e4} records / ${500} pages`,me=I===e.sourceOrgId?"source":"target",re=me==="source"?"this sync copies a subset, not the whole object":"conflict detection ran against a subset of the destination";this.deps.log(`[WARN] sync:execute ${z} (${me}): read stopped at ${_.length} record(s) \u2014 bound: ${ue}. ${re}.`),Oe(this.deps,"warning","Sync",`${z}: only ${_.length} record(s) were read from the ${me} (bound: ${ue}) \u2014 ${re}. Narrow it with a WHERE filter, or split the run.`)}return _},c=async(E,I,C)=>{let Y=`SELECT COUNT() FROM ${pt(I.objectApiName)}`,z=rs(I.where,C?.changedSince);z&&(Y+=` WHERE ${z}`);let{totalSize:te}=await n.query(Y),{tier:H,limits:x}=i(E);return Math.min(te,H==="production"?x.defaultQueryLimit:5e4)},l=async(E,I)=>{let C=pt(E.objectApiName),F=rs(E.where,I?.changedSince),Y=`SELECT COUNT() FROM ${C} WHERE IsPersonAccount = true`+(F?` AND (${F})`:"");try{return(await n.query(Y)).totalSize}catch{return 0}},u=new Map,p=async E=>{let I=u.get(E);if(I)return I;let C=await o.describe(E),F=ur(C);return u.set(E,F),F},g=async E=>ur(await o.describe(E)),h=async E=>(await or({query:async I=>o.query(I),queryMore:async I=>o.queryMore(I)},E)).records,f=nf({query:async E=>o.query(E),queryMore:async E=>o.queryMore(E)},t),m=async(E,I,C,F)=>{let Y=await f(E,I,C,F);return De(o.limitInfo,`sync:simulate lookup ${I.objectApiName}`),Y},y=df({query:async(E,I)=>n.query(E,I),queryMore:async E=>n.queryMore(E)},{query:async E=>o.query(E),queryMore:async E=>o.queryMore(E)},t),w=E=>({pages:{query:async I=>E.query(I),queryMore:async I=>E.queryMore(I)},transport:E,create:async(I,C)=>E.sobject(I).create(C,{headers:Zs()})}),v=async(E,I)=>{let F=`SELECT Id FROM ${pt(E.objectApiName)}`,Y=rs(E.where,I);Y&&(F+=` WHERE ${Y}`),E.orderBy&&(F+=` ORDER BY ${Kc(E.orderBy)}`);let{tier:z,limits:te}=i(e.sourceOrgId);z==="production"&&(F+=` LIMIT ${te.defaultQueryLimit}`);let{records:H}=await or(w(n).pages,F);return H.flatMap(x=>typeof x.Id=="string"?[x.Id]:[])},R={copy:pb({[e.sourceOrgId]:w(n),[e.targetOrgId]:w(o)}),sourceIds:v,store:this.fileStoreFor(),...e.files!==void 0&&ub(this.deps.infraServices?.productionGuard,e.targetOrgId,this.deps.orgManager.getOrg(e.targetOrgId))?{deleteFromTarget:async(E,I)=>jm(await o.sobject(E).destroy(I),E).map(C=>({id:C.id,success:C.success,errors:C.errors}))}:{}},b=async()=>{let{readSyncRecordTypes:E}=await import("./chunk-QRV2OSIS.mjs");return E(w(n).pages,w(o).pages)},O=async()=>{let{readRunCurrencies:E}=await import("./chunk-QWT2C74M.mjs");return E(async I=>(await n.query(I)).records,async I=>(await o.query(I)).records,{source:async I=>(await n.tooling.query(I)).records,target:async I=>(await o.tooling.query(I)).records})},k=async()=>{let{readStandardPricebooks:E}=await import("./chunk-6EBMEGZB.mjs");return E(async I=>(await n.query(I)).records,async I=>(await o.query(I)).records)},S=Tn(sr(async E=>(await n.query(E)).records),E=>Ut(e.sourceOrgId,E,()=>n.describe(E)));return{sourceConn:n,targetConn:o,querySource:d(n,e.sourceOrgId),queryTarget:d(o,e.targetOrgId),maskedSourceFields:S,countSource:c,describeTargetFields:p,describeTargetFieldsAgain:g,queryTargetRows:h,recordTypes:b,currencies:O,standardPricebooks:k,findInTarget:m,readSourceIds:E=>v(E),countPersonAccounts:l,deltaReads:y,files:R}}async rerunFromSnapshot(e,t){this.deps.log(`[RX] sync:history:rerun id=${e.id}`);let r=D(kn,{...e,payload:{config:t}},"sync:history:error",this.deps);r&&(this.refusedFieldless(e,r.config,"sync:history:rerun","sync:history:error",ou)||await this.startExecution(e,r.config,"rerun"))}async executeScheduled(e,t="schedule"){let r=kn.safeParse({config:e});if(!r.success)throw new Error(`Scheduled sync config failed validation: ${r.error.issues.map(m=>m.message).join("; ")}`);let n=qo(r.data.config.objects);if(n.length>0)throw Object.assign(new Error(`${Wo(n)} ${ou}`),{code:Bc});let o=t==="pipeline"?Sn("sync:pipeline",crypto.randomUUID(),"sync:execute"):Sn("sync:schedule",crypto.randomUUID(),"sync:execute"),i=o.id,a=this.deps.services?.getSandforgeSetting?.("sync.defaultBatchSize",200)??200,d={...r.data.config,objects:r.data.config.objects.map(m=>({...m,batchSize:m.batchSize??a}))},c=this.deps.infraServices?.productionGuard;if(!c)throw this.recordRefused(i,d.targetOrgId,ve.code),gi();let{check:l,decision:u}=await Ke(c,this.buildGuardRequest(d)),p=u;if((u==="refused"||u==="declined")&&this.recordStopped(i,d.targetOrgId,u),u==="refused")throw new Error(`Operation blocked by Production Guard: ${l.blockedReason??l.impactSummary}`);if(u==="declined")throw new Error(`${t==="pipeline"?"Pipeline":"Scheduled"} sync cancelled (confirmation declined).`);this.dmlTracker.register(i,"sync","upsert",d.objects?.length??0),this.activeOperationIds.add(i),this.deps.infraServices?.performanceTracker?.start(i,"sync");let g=`${t==="pipeline"?"Pipeline":"Scheduled"} sync of ${d.objects?.length??0} object(s)`;We(this.deps,i,"sync",g),this.liveTracker?.register(i,"sync",g,0,{pausable:!0});let h=new AbortController,f=this.executeSync(o,d,i,h,t,p);return this.registry?.register(i,"sync",g,f,h),f}async startExecution(e,t,r,n=!1,o){let i=e.id,a={module:"sync",operation:e.type},d=this.registry?.holdUntilStart(i);try{let c=this.deps.services?.getSandforgeSetting?.("sync.defaultBatchSize",200)??200,l=t,u={...l,objects:l.objects.map(v=>({...v,batchSize:v.batchSize??c}))};Object.assign(a,Er(u.objects));let p=this.deps.infraServices?.productionGuard;if(!p){this.recordRefused(i,u.targetOrgId,ve.code),P(this.deps,"sync:execute","sync:error",e,new Error(ve.message),{code:ve.code}),Le(this.deps,i,ve.message,!1,{context:a});return}let{check:g,decision:h}=await Ke(p,this.buildGuardRequest(u)),f=h;if((h==="refused"||h==="declined")&&this.recordStopped(i,u.targetOrgId,h),h==="refused")throw Jr(g.blockedReason??g.impactSummary);if(h==="declined"){let v="Operation cancelled by user (confirmation declined).";P(this.deps,"sync:execute","sync:error",e,new Error(v),{code:St.declined}),Le(this.deps,i,v,!1,{context:a});return}if(d?.signal.aborted){this.answerCancelledBeforeStart(e,u,h);return}if(this.dmlTracker.isDuplicate(i)){this.deps.log(`[WARN] Duplicate sync operation detected: ${i}`),P(this.deps,"sync:execute","sync:error",e,new Error(`Duplicate operation: ${i}`)),Le(this.deps,i,`Duplicate operation: ${i}`,!1,{context:a});return}this.dmlTracker.register(i,"sync","upsert",u.objects?.length??0),this.activeOperationIds.add(i),this.deps.infraServices?.performanceTracker?.start(i,"sync");let m=`Sync ${u.objects?.length??0} object(s)`;We(this.deps,i,"sync",m),this.liveTracker?.register(i,"sync",m,0,{pausable:!0});let y=new AbortController,w=this.executeSync(e,u,i,y,r,f,n,o);this.registry?this.registry.register(i,"sync",m,w,y):await w}catch(c){this.dmlTracker.markFailed(i),P(this.deps,"sync:execute","sync:error",e,c,{code:to(c)}),Le(this.deps,i,T(c),!0,{context:a})}finally{d?.release()}}answerCancelledBeforeStart(e,t,r){X(this.deps,{action:"sync_execute",module:"sync",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:r,code:gt});let n={configId:t.id,operationId:e.id,status:"partial",objectResults:[],totalProcessed:0,totalSuccess:0,totalFailed:0,totalSkipped:0,duration:0,timestamp:new Date().toISOString(),cancelled:!0,error:"Cancelled before it started: nothing was written."},o=A(this.deps,e,"sync:execute:response",n);this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} (cancelled before it started)`)}endCancelled(e){this.registry?.abort(e),pe(this.deps,e,{aborted:!0}),this.liveTracker?.cancel(e)}async executeSync(e,t,r,n,o,i,a=!1,d){let c=st(this.deps),l,u,p=!1,g,h=b=>({measure:O=>b.measure(O),hold:async O=>{let k=await b.hold(O);return g=k.answer.emails,k}}),f=new Ja;this.pauseGates.set(r,f);let m=this.runCreations?.recorder({runId:r,configId:t.id,configName:t.name??"",sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId}),y=this.backupRecords,w=m&&y?ia({runId:r,orgId:t.targetOrgId,files:y,meta:this.deps.configStore}):void 0,v=d?this.runCheckpointOf(t,r,d,{signal:n.signal,...m?{recorder:m}:{}}):void 0,R=()=>{try{w?.close()}catch(b){this.deps.log(`[WARN] sync ${r}: the backup of what it wrote over could not be listed whole: `+T(b))}};try{let b=await this.readersFor(t,n.signal),{sourceConn:O,targetConn:k}=b;lr(m,()=>k.identity(),`sync ${r}`);let S=b.queryTargetRows,E=m&&w?aa({query:S,backup:w,recorder:m,describe:b.describeTargetFields,viewsEncrypted:sr(S)}):void 0,I=new Xr(c.bulk.threshold),C=nr(this.deps),F=new an({connection:k,bulkExecutor:I,bulkManager:C,retryConfig:c.retry,signal:n.signal,pauseGate:f,onProgress:(fe,ne,ce)=>{let we=Math.round(fe/ne*100);$e(this.deps,r,we,fe,ne,ce),this.liveTracker?.updateProgress(r,we,fe,ne,ce)},log:fe=>this.deps.log(fe),...m?{calls:ca(m,E)}:{}}),{DataSync:Y}=await import("./chunk-SFURUNJM.mjs"),{ConflictResolver:z}=await import("./chunk-CHCHAE4B.mjs"),{FieldMappingService:te}=await import("./chunk-P7GSGFJO.mjs"),{TransformPipeline:H}=await import("./chunk-2BVTCNWA.mjs"),x=fe=>{fe.length>0&&(p=!0)},j=new Y({upsert:(fe,ne,ce,we)=>(x(ce),F.upsert(fe,ne,ce,we)),insert:(fe,ne,ce)=>(x(ne),F.insert(fe,ne,ce)),update:(fe,ne,ce)=>(x(ne),F.update(fe,ne,ce)),delete:(fe,ne,ce)=>(x(ne),F.delete(fe,ne,ce)),describeTargetFields:b.describeTargetFields}),K=new z,Q=new te,_=new H,V={dataSync:j,conflictResolver:K,fieldMapping:Q,transformPipeline:_,querySource:b.querySource,maskedSourceFields:b.maskedSourceFields,queryTarget:b.queryTarget,services:this.deps.services,grappeConfig:Qo(this.deps.services),onGrappeEvent:fe=>fi(this.deps,fe),countSource:b.countSource,countPersonAccounts:b.countPersonAccounts,describeTargetFields:b.describeTargetFields,describeTargetFieldsAgain:b.describeTargetFieldsAgain,leaseOfTheGate:()=>u?.lease(),queryTargetRows:S,readSourceIds:b.readSourceIds,findInTarget:b.findInTarget,writeGate:(()=>{let fe=o==="schedule"||o==="pipeline"?"unattended":"ask";if(!a)return h(this.writeGateFor(t,k,fe,void 0,v?.gate));let ne=this.targetAutomation;return u=Lb((we,le)=>this.writeGateFor(t,k,fe,we,v?.gate,le),we=>new ge(lv).withTimeout("sync:automation",()=>ne.read(t.targetOrgId,we)),we=>mt(async()=>Et(k),we,{...this.muteLeases,writes:$b}),r,{target:Re(this.deps.orgManager.getOrg(t.targetOrgId),t.targetOrgId),liftedBy:fv(fe).emailsLiftedBy}),h(u.gate)})(),recordTypes:b.recordTypes,currencies:b.currencies,standardPricebooks:b.standardPricebooks,signal:n.signal,pauseGate:f,deltaStore:this.deltaStoreFor(),deltaReads:b.deltaReads,files:{...b.files,onProgress:(fe,ne)=>{$e(this.deps,r,fe,0,0,ne),this.liveTracker?.updateProgress(r,fe,0,0,ne)}},...m?{creations:m}:{},idMap:this.idMapFor()};if(!this.deps.services)throw new Error("SyncOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let ue=this.deps.services.syncOrchestrator(V);await this.assertFieldTypesMatch(t,O,k,c.timeouts.describe),$e(this.deps,r,10,0,1,"Initializing sync");let me=await ue.execute(t).finally(async()=>{l=await u?.release()}),re=await this.settleRunCheckpoint(v,p,r),ie={...me,...l?{mutedAutomation:l}:{},...re?{checkpoint:re}:{}};if(await m?.end({status:ie.status,cancelled:ie.cancelled===!0}),R(),ie.cancelled?this.endCancelled(r):($e(this.deps,r,100,1,1,"Sync complete"),pe(this.deps,r,{status:ie.status??"completed"}),ie.status==="failure"?this.liveTracker?.fail(r,ie.error??"No record could be synced."):ie.status==="partial"?this.liveTracker?.partial(r):this.liveTracker?.complete(r)),this.dmlTracker.markCompleted(r),t.files){let fe=ie.objectResults.flatMap(ne=>ne.files?[ne.files]:[]);this.deps.log(`[sync] ${r} files: ${gb(fe)}`)}De(O.limitInfo,"sync:execute completion (source)"),De(k.limitInfo,"sync:execute completion (target)");try{this.historyLogger?.logExecution(t,ie,o)}catch(fe){this.deps.log(`[WARN] sync history logging failed: ${T(fe)}`)}this.recordRun(t,r,ie,i,o,g);let Be=A(this.deps,e,"sync:execute:response",ie);return this.deps.broker.postToWebview(Be),this.deps.log(`[TX] ${Be.type} id=${Be.id}`),ie}catch(b){await m?.end({status:"failure"}),R(),this.dmlTracker.markFailed(r);let O=await this.settleRunCheckpoint(v,p,r),k=O?.state==="deleted";if(this.liveTracker?.fail(r,T(b)),b instanceof kb){let C=v?.refusal(),F=k?`${b.message} ${xr}`:b.message,Y={...C?{checkpointRefusal:C.code}:{},...O?{checkpoint:O}:{}};return X(this.deps,{action:"sync_execute",module:"sync",operationId:r,orgId:t.targetOrgId,outcome:"stopped",guard:i,code:b.code,details:{triggeredBy:o,...C?{checkpointRefusal:C.code}:{},...En(g)}}),P(this.deps,"sync:execute","sync:error",e,b,{code:b.code,extraPayload:Y}),Le(this.deps,r,F,!1,{context:{module:"sync",operation:e.type,...Er(t.objects)}}),{...b.result,configId:t.id,operationId:r,status:"failure",timestamp:new Date().toISOString(),error:F,...O?{checkpoint:O}:{}}}Ko(b)&&o!=="rerun"&&d===void 0&&this.deps.infraServices?.offlineManager?this.deps.infraServices.offlineManager.enqueue({id:r,type:"sync",orgId:t.targetOrgId,payload:{config:t}})&&this.deps.log(`[OFFLINE] sync queued for replay on reconnect: ${r}`):Ko(b)&&o==="rerun"&&this.deps.log(`[OFFLINE] sync replay failed again \u2014 not re-queued (replay outcomes surface via operation:failed): ${r}`);let S=k?new Error(`${T(b)} ${xr}`):b;P(this.deps,"sync:execute","sync:error",e,b,{...O?{extraPayload:{checkpoint:O}}:{}}),Le(this.deps,r,T(S),!0,{context:{module:"sync",operation:e.type,...Er(t.objects)}});let I={...(b instanceof Sb?b.result:void 0)??{objectResults:[],totalProcessed:0,totalSuccess:0,totalFailed:0,totalSkipped:0,duration:0},configId:t.id,operationId:r,status:"failure",timestamp:new Date().toISOString(),error:T(S),...O?{checkpoint:O}:{}};try{this.historyLogger?.logExecution(t,I,o)}catch(C){this.deps.log(`[WARN] sync history logging failed: ${T(C)}`)}return this.recordRun(t,r,I,i,o,g),I}finally{this.pauseGates.delete(r),this.activeOperationIds.has(r)&&(this.deps.infraServices?.performanceTracker?.complete(r),this.activeOperationIds.delete(r))}}};var RT=new Set(["sync:history:list","sync:history:detail","sync:history:rerun","sync:history:export"]),Xa=class{constructor(e,t,r){this.deps=e;this.historyStore=t;this.syncOps=r}deps;historyStore;syncOps;async handle(e){if(!RT.has(e.type))return!1;switch(e.type){case"sync:history:list":return this.handleList(e),!0;case"sync:history:detail":return this.handleDetail(e),!0;case"sync:history:export":return this.handleExport(e),!0;case"sync:history:rerun":return await this.handleRerun(e),!0;default:return!1}}handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.historyStore.list(),r=A(this.deps,e,"sync:history:list:response",{entries:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} count=${t.length}`)}catch(t){P(this.deps,"sync:history:list","sync:history:error",e,t)}}handleDetail(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(tl,e,"sync:history:error",this.deps);if(t)try{let r=this.historyStore.load(t.entryId)??null,n=A(this.deps,e,"sync:history:detail:response",{entry:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){P(this.deps,"sync:history:detail","sync:history:error",e,r)}}handleExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(xf,e,"sync:history:error",this.deps);if(t)try{let r=t.format==="csv"?this.historyStore.exportAsCsv(t.entryIds):this.historyStore.exportAsJson(t.entryIds),n=A(this.deps,e,"sync:history:export:response",{data:r,format:t.format});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} format=${t.format}`)}catch(r){P(this.deps,"sync:history:export","sync:history:error",e,r)}}async handleRerun(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(tl,e,"sync:history:error",this.deps);if(!t)return;let r=this.historyStore.load(t.entryId);if(!r){P(this.deps,"sync:history:rerun","sync:history:error",e,new Error(`History entry not found: ${t.entryId}`),{code:"NOT_FOUND"});return}await this.syncOps.rerunFromSnapshot(e,r.configSnapshot)}};var vT=1e4;async function hv(s,e){if(s.configId!==void 0&&e.isSaved(s.configId))return{leftAsIs:!0,objects:[]};let t=new Set(s.objects);if(t.size===0)return{leftAsIs:!1,objects:[]};let r=c=>Tt(c).filter(l=>t.has(l.objectApiName)),n=(await e.runs()).find(c=>c.sourceOrgId===s.sourceOrgId&&c.targetOrgId===s.targetOrgId&&r(c).length>0);if(!n)return{leftAsIs:!1,objects:[]};let o=n.created.map(c=>c.objectApiName),i=r(n).sort((c,l)=>o.indexOf(c.objectApiName)-o.indexOf(l.objectApiName)),a,d=[];for(let{objectApiName:c,ids:l}of i){let u=l.slice(0,vT),p;try{p=await e.countInTarget(c,u)+(l.length-u.length)}catch(g){a??=g instanceof Error?g.message:String(g),p=l.length}p>0&&d.push({objectApiName:c,count:p})}return{leftAsIs:!1,run:{runId:n.runId,configName:n.configName,startedAt:n.startedAt,...n.realtime?{realtime:!0}:{}},objects:d,...a!==void 0?{unread:a}:{}}}var ST=new Set(["sync:removal:info","sync:removal:list","sync:remove","sync:remove:sweep","sync:remove:automation","sync:earlier-copies"]),kT=6e4,OT=12e4,mv=6e4,IT=6e4,yv="The run is still writing in another window: remove it once it has ended there.",Ka=class{constructor(e,t,r,n=so){this.deps=e;this.history=t;this.isRunning=r;this.self=n;this.configs=new Pt(e.configStore)}deps;history;isRunning;self;creations;otherModuleRuns=()=>Promise.resolve([]);backups;registry;liveTracker;removing=new Set;configs;targetAutomation={read:async(e,t,r)=>(await this.ownReader()).read(e,t,r)};reader;elsewhere(e){return!this.isRunning(e.runId)&&An(e,this.self)}stillWriting(e){return this.isRunning(e.runId)||An(e,this.self)}setRunCreations(e){this.creations=e}setBackupRecordStore(e){this.backups=e}setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-4XZ5YT5O.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handle(e){if(!ST.has(e.type))return!1;switch(e.type){case"sync:removal:info":return await this.handleInfo(e),!0;case"sync:removal:list":return await this.handleList(e),!0;case"sync:remove":return await this.handleRemove(e),!0;case"sync:remove:sweep":return await this.handleSweepList(e),!0;case"sync:remove:automation":return await this.handleRemovalAutomation(e),!0;case"sync:earlier-copies":return await this.handleEarlierCopies(e),!0;default:return!1}}tierOf(e){let t=this.deps.orgManager.getOrg(e);return Ee(t)}infoOf(e,t=[]){let r=Tt(e),n=ry(e,t),o=r.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length})),i=io(e),a=this.keptBack(i),d=hl(e),c=ml(e),l=cs(e),u={runId:e.runId,configId:e.configId,configName:e.configName,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,startedAt:e.startedAt,...e.end?{endedAt:e.end.at}:{},...!e.end&&e.inFlight?{inFlight:{objectApiName:e.inFlight.objectApiName,rows:e.inFlight.rows}}:{},...this.elsewhere(e)?{runningElsewhere:!0}:{},...e.realtime?{realtime:!0}:{},created:ds(e),left:o,...d>0?{overwritten:d}:{},...a.kept.length>0?{putBack:a.kept.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length})),...a.keptUntil!==void 0?{putBackKeptUntil:a.keptUntil}:{}}:{},...a.notKept>0?{putBackNotKept:a.notKept}:{},...c>0?{deleted:c}:{},...e.unkept?{notKeptEncrypted:e.unkept.flatMap(({objectApiName:m,fields:y})=>y.map(w=>`${m}.${w}`))}:{},...l.length>0?{bringBack:l.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length}))}:{},...e.removal?.undo?{removed:e.removal.undo}:{},...n.length>0?{writtenAgain:n}:{}},p=e.removal?.undo?Tt(e,!0):[],g=p.length>0?{...u,createdByObject:p.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length}))}:u,h=r.length>0||i.length>0||l.length>0?r:p;if(h.length===0&&i.length===0&&l.length===0)return g;let f=this.refusalOf(e,h,[...i,...l]);return f?{...g,refusal:f}:g}keptBack(e){return by(e,t=>this.deps.configStore.get(`backup:${t}`),wy(this.deps.services))}removalStepsOf(e,t=!1){let r=o=>[...new Set(o.map(({objectApiName:i})=>i))],n=r(Tt(e,t));return{bringBack:r(cs(e)),giveBack:r(this.keptBack(io(e)).kept),setToDraft:zt(n),delete:Kr(n)}}guardRequestOf(e,t,r){let n=o=>o.reduce((i,a)=>i+a.ids.length,0);return{orgId:e.targetOrgId,orgTier:this.tierOf(e.targetOrgId),operation:t.length>0?"delete":"update",objectName:[...new Set([...t,...r].map(o=>o.objectApiName))].join(", "),recordCount:n(t)+n(r),module:"sync"}}refusalOf(e,t,r){if(this.isRunning(e.runId))return{code:"RUNNING",message:"The run is still writing: remove it once it has ended."};if(this.elsewhere(e))return{code:"RUNNING",message:yv};if(!this.deps.orgManager.getOrg(e.targetOrgId))return{code:"ORG_GONE",message:"The org the run wrote to is no longer connected: connect it again to remove the run."};let n=this.deps.infraServices?.productionGuard;if(!n)return{code:"NO_GUARD",message:ve.message};let o=n.check(this.guardRequestOf(e,t,r));return o.allowed?void 0:{code:"GUARD_BLOCKED",message:o.blockedReason??o.impactSummary}}async withJobAnswered(e){let t=this.creations;if(!t||(e.jobs??[]).length===0||this.stillWriting(e)||!this.deps.orgManager.getOrg(e.targetOrgId))return e;let r=`sync:removal of ${e.runId}`;try{let n=await new ge(IT).withTimeout(r,async()=>{let o=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=Gt(o,r);return Zi(t,e,In(o),()=>i.serverTime())});for(let o of ea(r,n))this.deps.log(o);return n.some(o=>o.answered)?await t.get(e.runId)??e:e}catch(n){return this.deps.log(`[WARN] ${r}: the job could not be read back: ${T(n)}`),e}}async runOf(e){let t=await this.creations?.get(e);return t?this.withJobAnswered(t):void 0}async handleInfo(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(kf,e,"sync:remove:error",this.deps);if(t)try{let r=await this.runOf(t.runId),o=r!==void 0&&(Tt(r).length>0||io(r).length>0)?await this.creations?.list()??[]:[],i=A(this.deps,e,"sync:removal:info:response",{info:r?this.infoOf(r,o):null});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(r){P(this.deps,"sync:removal:info","sync:remove:error",e,r)}}async handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Of,e,"sync:remove:error",this.deps);if(t===null)return;let r=t?.realtime===!0;try{let n=new Set(this.history.list().flatMap(d=>d.result.created?.runId?[d.result.created.runId]:[])),o=[];for(let d of await this.creations?.list()??[]){let c=n.has(d.runId)||d.realtime===!0!==r;o.push(c?d:await this.withJobAnswered(d))}let i=o.filter(d=>d.realtime===!0===r&&!n.has(d.runId)&&!this.isRunning(d.runId)&&(ds(d)>0||hl(d)>0||ml(d)>0||!d.end&&d.inFlight!==void 0)),a=A(this.deps,e,"sync:removal:list:response",{runs:i.map(d=>this.infoOf(d,o))});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} count=${i.length}`)}catch(n){P(this.deps,"sync:removal:list","sync:remove:error",e,n)}}async handleEarlierCopies(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(If,e,"sync:remove:error",this.deps);if(t)try{let r=this.creations,n=await hv(t,{runs:async()=>await r?.list()??[],isSaved:i=>this.configs.isSaved(i),countInTarget:async(i,a)=>{let d=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),c=pt(i),l=0;for(let u of os(a.filter(On)))l+=(await d.query(`SELECT COUNT() FROM ${c} WHERE Id IN (${u})`)).totalSize;return l}}),o=A(this.deps,e,"sync:earlier-copies:response",{copies:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(r){P(this.deps,"sync:earlier-copies","sync:remove:error",e,r)}}async sweepInputOf(e,t,r,n){let o=this.targetAutomation,i=[...new Set([...t.created,...t.overwritten??[]].map(l=>l.objectApiName).filter(l=>!ey.includes(l)))],a;try{a=await new ge(kT).withTimeout(`${r} automation`,()=>o.read(t.targetOrgId,i))}catch(l){a={error:T(l)}}let d=Gt(e,r),c=await ra(d,t.created,a,n,t.firstWrittenAt!==void 0?{at:t.firstWrittenAt,...t.lastWriteAt!==void 0?{lastAt:t.lastWriteAt}:{},serverTime:()=>d.serverTime()}:void 0,t.overwritten??[],{...t.runUserId?{runUserId:t.runUserId}:{},ties:{}});return wo({...c,ties:{...c.ties,...await oa(t,c.writtenBetween,await this.creations?.list().catch(()=>[])??[],this.otherModuleRuns)}},d)}async localRunsOn(e){return na(await this.creations?.list().catch(()=>[])??[],e)}setOtherModuleRuns(e){this.otherModuleRuns=e}async handleSweepList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Tf,e,"sync:remove:sweep:error",this.deps);if(!t)return;let r=(n,o)=>P(this.deps,"sync:remove:sweep","sync:remove:sweep:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to sweep after.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=await new ge(OT).withTimeout("sync:remove:sweep",async()=>{let i=await B(n.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await this.sweepInputOf(i,n,"sync:remove:sweep");return ho(jr(i,"sync:remove:sweep"),a,n.removal?.removalSpans??[])});this.deps.broker.postToWebview(A(this.deps,e,"sync:remove:sweep:response",{runId:n.runId,listing:o}))}catch(n){P(this.deps,"sync:remove:sweep","sync:remove:sweep:error",e,n,{code:"SWEEP_ERROR",retryable:!0})}}async handleRemovalAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Ef,e,"sync:remove:automation:error",this.deps);if(!t)return;let r=(n,o)=>P(this.deps,"sync:remove:automation","sync:remove:automation:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to remove.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=Go(this.removalStepsOf(n,t.again===!0),t.sweptObjects??[]),i=[...new Set(Object.values(o).flat())],a=this.targetAutomation,d=await new ge(mv).withTimeout("sync:remove:automation",()=>a.read(n.targetOrgId,i,{undeletes:!0})),c=A(this.deps,e,"sync:remove:automation:response",{runId:n.runId,automation:d,steps:o});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(n){let o=n instanceof ir;P(this.deps,"sync:remove:automation","sync:remove:automation:error",e,n,{code:o?"TIMEOUT":"AUTOMATION_ERROR",retryable:!0})}}sweepOfRemoval(e){let{conn:t,run:r,input:n}=e;return bo({input:async()=>{if(n instanceof Error)throw n;return n},org:jr(t,"sync:remove sweep",e.signal),options:{includeChanged:e.includeChanged,removalSpans:r.removal?.removalSpans??[],sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},guard:e.guard,guardOf:{orgId:r.targetOrgId,orgTier:this.tierOf(r.targetOrgId),operation:"delete",module:"sync"},onGuardDecision:(o,i)=>{let a=yo(o,"");delete a.forgeId,X(this.deps,{action:"cleanup_delete",module:"sync",operationId:`${e.operationId}-sweep`,orgId:r.targetOrgId,outcome:o.status==="refused"?"stopped":o.status,...i?{guard:i}:{},...o.status==="refused"?{code:Ro(i)}:{},objects:mo(o),details:{...a,runId:r.runId}})},keepMade:async(o,i,a)=>{await this.creations?.updateRemoval(r.runId,d=>sa(d,o,i,a)).catch(d=>{this.deps.log(`[WARN] sync:remove ${e.operationId}: what the sweep found made for the run could not be kept: ${T(d)}`)})}})}refuse(e,t,r,n=!1){P(this.deps,"sync:remove","sync:remove:error",e,new Error(t),{code:r,...n?{retryable:n}:{}})}recordNotRemoved(e,t,r,n={}){X(this.deps,{action:"cleanup_delete",module:"sync",operationId:e.id,orgId:t.targetOrgId,outcome:r,...n,details:{runId:t.runId}})}setMuteLeases(e){this.muteLeases=e}muteLeases={};async handleRemove(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Af,e,"sync:remove:error",this.deps);if(!t)return;let r=this.creations;if(!r){this.refuse(e,"What Sync runs created is not kept in this window yet.","NOT_INITIALIZED",!0);return}let n;try{n=await this.runOf(t.runId)}catch(a){P(this.deps,"sync:remove","sync:remove:error",e,a,{code:"REMOVE_ERROR",retryable:!0});return}if(!n){this.refuse(e,"Nothing this run created is kept: it created nothing, or ran before runs kept what they created, or the record of it was dropped to make room.","NOT_KEPT");return}if(this.isRunning(n.runId)){this.refuse(e,"The run is still writing: remove it once it has ended.","RUNNING");return}if(this.elsewhere(n)){this.refuse(e,yv,"RUNNING");return}let o=t.again===!0;if(Tt(n,o).length===0&&io(n).length===0&&cs(n).length===0){let a=n.removal?.undo?.removedAt??n.removal?.restoredAt??n.removal?.undeletedAt;a!==void 0?this.refuse(e,`What this run created was removed already, on ${a}.`,"ALREADY_REMOVED"):this.refuse(e,"This run created nothing to remove.","NOTHING_TO_REMOVE");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){this.refuse(e,"The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}if(this.removing.has(n.runId)){this.refuse(e,"What this run created is being removed already.","DUPLICATE");return}this.removing.add(n.runId);let i=this.registry?.holdUntilStart(e.id);try{await this.removeRun(e,r,n,{includeChanged:t.includeChanged===!0,sweep:t.sweep===!0,sweepLate:t.sweep===!0&&t.sweepLate===!0,sweepUntied:t.sweep===!0&&t.sweepUntied===!0,again:o,muteAutomation:t.muteAutomation===!0},i)}finally{this.removing.delete(n.runId),i?.release()}}async removeRun(e,t,r,n,o){let{includeChanged:i,again:a}=n,d=Tt(r,a),c=[...io(r),...cs(r)],l=d.reduce((k,S)=>k+S.ids.length,0),u=c.reduce((k,S)=>k+S.ids.length,0),p=r.targetOrgId,g=this.deps.infraServices?.productionGuard;if(!g){this.recordNotRemoved(e,r,"stopped",{code:ve.code}),this.refuse(e,ve.message,ve.code);return}let{check:h,decision:f}=await Ke(g,this.guardRequestOf(r,d,c));if(f==="refused"||f==="declined"){this.recordNotRemoved(e,r,"stopped",{guard:f}),f==="refused"?this.refuse(e,`Operation blocked by Production Guard: ${h.blockedReason??h.impactSummary}`,St.blocked):this.refuse(e,"Operation cancelled by user (confirmation declined).",St.declined,!0);return}if(o?.signal.aborted){this.recordNotRemoved(e,r,"stopped",{guard:f,code:gt});let k={runId:r.runId,status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(A(this.deps,e,"sync:remove:response",{result:k,operationId:e.id}));return}let m=e.id,y=u>0?`Removing ${l} record(s) and file(s) a Sync run created, and giving ${u} record(s) it wrote over or deleted their values back`:`Removing ${l} record(s) and file(s) a Sync run created`,w=new AbortController,v=()=>{},R=new Promise((k,S)=>{v=E=>E===void 0?k():S(E)});R.catch(()=>{}),We(this.deps,m,"sync",y),this.registry?.register(m,"sync",y,R,w),this.liveTracker?.register(m,"sync",y,l+u);let b,O;try{let k=await B(p,this.deps.orgRegistry,this.deps.orgManager),S=n.sweep?await this.sweepInputOf(k,r,"sync:remove sweep",w.signal).catch(ue=>new Error(T(ue))):void 0;O=S?await this.sweepOfRemoval({conn:k,run:r,input:S,includeChanged:i,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,signal:w.signal,guard:g,operationId:m}):void 0;let E=O;await E?.ask();let I;if(n.muteAutomation===!0){let ue=Go(this.removalStepsOf(r,a),E?.takes??[]),me=[...new Set(Object.values(ue).flat())],re=this.targetAutomation,ie=await new ge(mv).withTimeout("sync:remove:automation",()=>re.read(r.targetOrgId,me,{undeletes:!0})).catch(Be=>({unread:T(Be)}));I=await mt(async()=>Et(k),ie,{...this.muteLeases,writes:Gr(ue)})}let C,F=I?.muted,Y=async()=>{let ue=I?.prepared;!ue||w.signal.aborted||(C=await ue.acquire(m),F=C.outcome)},z=Gt(k,"sync:remove"),te=await ta(z,r.created),{result:H,notes:x,earlierStamped:j}=await Ci({run:r,org:z,includeChanged:i,...a?{again:a}:{},store:t,configs:this.configs,links:t.idMap(),...this.backups?{backups:this.backups}:{},earlierRuns:ty(r,await t.list().catch(()=>[])),undelete:ue=>k.soap.undelete(ue),...E?{sweep:ue=>E.first(ue),afterRemoval:ue=>E.afterRemoval(ue),automationMade:E.automationMade}:{},...r.runUserId?{runUserId:r.runUserId}:{},onUndeletable:Tr(this.deps,p,"sync:remove"),beforeFirstWrite:Y,signal:w.signal,onProgress:(ue,me,re)=>{let ie=Math.min(100,Math.round(ue/Math.max(me,1)*100));$e(this.deps,m,ie,ue,me,re),w.signal.aborted||this.registry?.updateProgress(m,ie),this.liveTracker?.updateProgress(m,ie,ue,me,re)}}).finally(async()=>{C&&(F=await C.release())}),K=await O?.settle(),Q=H.status==="cancelled"?{}:await te.take();for(let ue of[...x,...Q.note?[Q.note]:[]])this.deps.log(`[WARN] sync:remove ${m}: ${ue}`);for(let{runId:ue,records:me}of j??[])this.deps.log(`[INFO] sync:remove ${m}: ${me} record(s) given back hold the values of the earlier run ${ue} again, stamped on it`);let _={...H,objects:Q.object?[...H.objects,Q.object]:H.objects,status:no(H.status,K),...K?{sweep:K}:{},...F?{mutedAutomation:F}:{}};X(this.deps,{action:"cleanup_delete",module:"sync",operationId:m,orgId:p,outcome:oo(H),guard:f,objects:Pi(Yr(_.objects),_.restored??[],_.undeleted??[]),..._.leftBy?{leftBy:_.leftBy}:{},...F?{muted:ot(F)}:{},details:{runId:r.runId}});let V=A(this.deps,e,"sync:remove:response",{result:_,operationId:m});this.deps.broker.postToWebview(V),this.deps.log(`[TX] ${V.type} id=${V.id} status=${_.status}`),_.status==="cancelled"||_.sweep?.status==="cancelled"?(pe(this.deps,m,{aborted:!0}),this.liveTracker?.cancel(m)):(pe(this.deps,m,{status:_.status}),_.status==="failure"?(b=new Error("Nothing this run created could be removed."),this.liveTracker?.fail(m,"Nothing this run created could be removed.")):_.status==="partial"?this.liveTracker?.partial(m):this.liveTracker?.complete(m))}catch(k){b=k,await O?.settle().catch(()=>{});let S=kt(k)?k:void 0;this.recordNotRemoved(e,r,S?"stopped":"failure",{guard:f,...S?{code:S.code}:{}}),P(this.deps,"sync:remove","sync:remove:error",e,k,{code:S?.code??"REMOVE_ERROR",retryable:!0}),pe(this.deps,m,{status:"failure"}),this.liveTracker?.fail(m,T(k))}finally{v(b)}}};var AT=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,TT=/^[A-Za-z][A-Za-z0-9_]*$/;function Ya(s,e,t){if(!AT.test(t)||!TT.test(e))return{ok:!1,reason:"not-a-record"};let r=dn(s);return r.ok?{ok:!0,url:new URL(`/lightning/r/${e}/${t}/view`,r.url.origin).toString()}:r}var ET=new Set(["seed:removal:info","seed:removal:list","seed:remove","seed:remove:sweep","seed:open-record"]),wv=6e4,PT=12e4,CT=6e4,bv="The seed is still writing: remove it once it has ended.",Rv="The seed is still writing in another window: remove it once it has ended there.",Qa=class{constructor(e,t,r=()=>!1,n=so){this.deps=e;this.isRunning=r;this.self=n;this.externalBrowser=t??new gr}deps;isRunning;self;creations;otherModuleRuns=()=>Promise.resolve([]);registry;liveTracker;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;removing=new Set;externalBrowser;elsewhere(e){return!this.isRunning(e.runId)&&An(e,this.self)}setRunCreations(e){this.creations=e}setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-4XZ5YT5O.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}async handle(e){return ET.has(e.type)?(e.type==="seed:removal:info"?await this.handleInfo(e):e.type==="seed:removal:list"?await this.handleList(e):e.type==="seed:remove:sweep"?await this.handleSweepList(e):e.type==="seed:open-record"?await this.handleOpenRecord(e):await this.handleRemove(e),!0):!1}tierOf(e){let t=this.deps.orgManager.getOrg(e);return Ee(t)}infoOf(e){let t=Tt(e),r={runId:e.runId,targetOrgId:e.targetOrgId,startedAt:e.startedAt,endedAt:e.end?.at??e.lastWrittenAt??e.startedAt,...e.origin?{origin:e.origin}:{},...e.origin==="clone"?{sourceOrgId:e.sourceOrgId}:{},...e.pipeline?{pipeline:e.pipeline}:{},...e.end?{}:this.isRunning(e.runId)?{running:!0}:this.elsewhere(e)?{runningElsewhere:!0}:{unfinished:!0,...e.inFlight?{inFlight:{objectApiName:e.inFlight.objectApiName,rows:e.inFlight.rows}}:{}},created:ds(e),objects:[...new Set([...e.created.map(({objectApiName:d})=>d),...(e.overwritten??[]).map(({objectApiName:d})=>d)])],left:t.map(({objectApiName:d,ids:c})=>({objectApiName:d,count:c.length})),...e.removal?.undo?{removed:e.removal.undo}:{},...e.checkpoint?{checkpoint:e.checkpoint}:{}},n=e.removal?.undo?Tt(e,!0):[],o=n.length>0?{...r,createdByObject:n.map(({objectApiName:d,ids:c})=>({objectApiName:d,count:c.length}))}:r,i=t.length>0?t:n;if(i.length===0)return o;let a=this.refusalOf(e,i);return a?{...o,refusal:a}:o}async withScenario(e){let t=this.creations;if(!t||e.origin)return e;try{let{nodeScenarioSidecarFiles:r,readScenarioRunSidecar:n}=await import("./chunk-H2PJNIYJ.mjs"),o=await n(r(),t.storagePath,e.runId);if(o.kind!=="read")return e;let{packId:i,agent:a}=o.sidecar;return{...e,scenario:{packId:i,...a?{agent:a.agent}:{}}}}catch{return e}}refusalOf(e,t){if(this.isRunning(e.runId))return{code:"RUNNING",message:bv};if(this.elsewhere(e))return{code:"RUNNING",message:Rv};if(!this.deps.orgManager.getOrg(e.targetOrgId))return{code:"ORG_GONE",message:"The org the run wrote to is no longer connected: connect it again to remove the run."};let r=this.deps.infraServices?.productionGuard;if(!r)return{code:"NO_GUARD",message:ve.message};let n=r.check({orgId:e.targetOrgId,orgTier:this.tierOf(e.targetOrgId),operation:"delete",objectName:t.map(o=>o.objectApiName).join(", "),recordCount:t.reduce((o,i)=>o+i.ids.length,0),module:"seed"});return n.allowed?void 0:{code:"GUARD_BLOCKED",message:n.blockedReason??n.impactSummary}}async withJobAnswered(e){let t=this.creations;if(!t||(e.jobs??[]).length===0||this.isRunning(e.runId)||this.elsewhere(e)||!this.deps.orgManager.getOrg(e.targetOrgId))return e;let r=`seed:removal of ${e.runId}`;try{let n=await new ge(CT).withTimeout(r,async()=>{let o=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=Gt(o,r);return Zi(t,e,In(o),()=>i.serverTime())});for(let o of ea(r,n))this.deps.log(o);return n.some(o=>o.answered)?await t.get(e.runId)??e:e}catch(n){return this.deps.log(`[WARN] ${r}: the job could not be read back: ${T(n)}`),e}}async runOf(e){let t=await this.creations?.get(e);return t?this.withJobAnswered(t):void 0}async handleInfo(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Pf,e,"seed:remove:error",this.deps);if(t)try{let r=await this.runOf(t.runId),n=A(this.deps,e,"seed:removal:info:response",{info:r?await this.withScenario(this.infoOf(r)):null});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){P(this.deps,"seed:removal:info","seed:remove:error",e,r)}}async handleOpenRecord(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Zf,e,"seed:open-record:error",this.deps);if(!t)return;let r=(n,o)=>{P(this.deps,"seed:open-record","seed:open-record:error",e,new Error(n),{code:o})};try{let n=await this.creations?.get(t.runId);if(!n){r("Nothing of this run is kept any more.","NOT_KEPT");return}let o=t.recordId.slice(0,15),i;for(let{objectApiName:u,ids:p}of n.created){let g=p.find(h=>h.slice(0,15)===o);if(g){i={objectApiName:u,id:g};break}}if(!i){r("This record is not one this run created.","NOT_CREATED");return}let a=this.deps.orgManager.getOrg(n.targetOrgId);if(!a){r("The org this run wrote to is no longer connected.","ORG_NOT_FOUND");return}let d=Ya(a.instanceUrl,i.objectApiName,i.id);if(!d.ok){let u=d.reason==="not-https"?`its instance URL must use HTTPS, got "${d.protocol}"`:d.reason==="invalid"?"its instance URL is not a valid URL":"the record is not one an address can be built for";r(`Cannot open the record in "${Re(a)}": ${u}.`,d.reason==="not-a-record"?"NOT_CREATED":"INVALID_INSTANCE_URL");return}let c=await this.externalBrowser.open(d.url),l=A(this.deps,e,"seed:open-record:response",c);this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} status=${c.status}`)}catch(n){P(this.deps,"seed:open-record","seed:open-record:error",e,n)}}async handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=[];for(let o of await this.creations?.list()??[])t.push(await this.withJobAnswered(o));let r=[];for(let o of t)r.push(await this.withScenario(this.infoOf(o)));let n=A(this.deps,e,"seed:removal:list:response",{runs:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} runs=${t.length}`)}catch(t){P(this.deps,"seed:removal:list","seed:remove:error",e,t)}}async sweepInputOf(e,t,r,n){let o=this.targetAutomation,i;try{i=await new ge(wv).withTimeout(`${r} automation`,()=>o.read(t.targetOrgId,t.created.map(c=>c.objectApiName)))}catch(c){i={error:T(c)}}let a=Gt(e,r),d=await ra(a,t.created,i,n,void 0,[],{...t.runUserId?{runUserId:t.runUserId}:{},ties:{}});return wo({...d,ties:{...d.ties,...await oa(t,d.writtenBetween,await this.creations?.list().catch(()=>[])??[],this.otherModuleRuns)}},a)}async localRunsOn(e){return na(await this.creations?.list().catch(()=>[])??[],e)}setOtherModuleRuns(e){this.otherModuleRuns=e}async handleSweepList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Df,e,"seed:remove:sweep:error",this.deps);if(!t)return;let r=(n,o)=>P(this.deps,"seed:remove:sweep","seed:remove:sweep:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to sweep after.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=await new ge(PT).withTimeout("seed:remove:sweep",async()=>{let i=await B(n.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await this.sweepInputOf(i,n,"seed:remove:sweep");return ho(jr(i,"seed:remove:sweep"),a,n.removal?.removalSpans??[])});this.deps.broker.postToWebview(A(this.deps,e,"seed:remove:sweep:response",{runId:n.runId,listing:o}))}catch(n){P(this.deps,"seed:remove:sweep","seed:remove:sweep:error",e,n,{code:"SWEEP_ERROR",retryable:!0})}}sweepOfRemoval(e){let{conn:t,run:r}=e;return bo({input:()=>this.sweepInputOf(t,r,"seed:remove sweep",e.signal),org:jr(t,"seed:remove sweep",e.signal),options:{includeChanged:e.includeChanged,removalSpans:r.removal?.removalSpans??[],sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},guard:e.guard,guardOf:{orgId:r.targetOrgId,orgTier:this.tierOf(r.targetOrgId),operation:"delete",module:"seed"},onGuardDecision:(n,o)=>{let i=yo(n,"");delete i.forgeId,X(this.deps,{action:"cleanup_delete",module:"seed",operationId:`${e.operationId}-sweep`,orgId:r.targetOrgId,outcome:n.status==="refused"?"stopped":n.status,...o?{guard:o}:{},...n.status==="refused"?{code:Ro(o)}:{},objects:mo(n),details:{...i,runId:r.runId}})},keepMade:async(n,o,i)=>{await this.creations?.updateRemoval(r.runId,a=>sa(a,n,o,i)).catch(a=>{this.deps.log(`[WARN] seed:remove ${e.operationId}: what the sweep found made for the run could not be kept: ${T(a)}`)})}})}refuse(e,t,r,n=!1){P(this.deps,"seed:remove","seed:remove:error",e,new Error(t),{code:r,...n?{retryable:n}:{}})}recordNotRemoved(e,t,r,n={}){X(this.deps,{action:"cleanup_delete",module:"seed",operationId:e.id,orgId:t.targetOrgId,outcome:r,...n,details:{runId:t.runId}})}setMuteLeases(e){this.muteLeases=e}muteLeases={};async handleRemove(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Cf,e,"seed:remove:error",this.deps);if(!t)return;let r=this.creations,n=await this.runOf(t.runId);if(!r||!n){this.refuse(e,"Nothing this run created is kept: it created nothing, or was dropped to make room for newer seeds.","NOT_KEPT");return}let o=t.again===!0;if(Tt(n,o).length===0){n.removal?.undo?this.refuse(e,`What this run created was removed already, on ${n.removal.undo.removedAt}.`,"ALREADY_REMOVED"):this.refuse(e,"This run created nothing to remove.","NOTHING_TO_REMOVE");return}if(this.isRunning(n.runId)){this.refuse(e,bv,"RUNNING");return}if(this.elsewhere(n)){this.refuse(e,Rv,"RUNNING");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){this.refuse(e,"The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}if(this.removing.has(n.runId)){this.refuse(e,"What this run created is being removed already.","DUPLICATE");return}this.removing.add(n.runId);let i=this.registry?.holdUntilStart(e.id);try{await this.removeRun(e,r,n,{includeChanged:t.includeChanged===!0,sweep:t.sweep===!0,sweepLate:t.sweep===!0&&t.sweepLate===!0,sweepUntied:t.sweep===!0&&t.sweepUntied===!0,again:o,muteAutomation:t.muteAutomation===!0},i)}finally{this.removing.delete(n.runId),i?.release()}}async removeRun(e,t,r,n,o){let{includeChanged:i,again:a}=n,d=Tt(r,a),c=d.reduce((b,O)=>b+O.ids.length,0),l=r.targetOrgId,u=this.deps.infraServices?.productionGuard;if(!u){this.recordNotRemoved(e,r,"stopped",{code:ve.code}),this.refuse(e,ve.message,ve.code);return}let{check:p,decision:g}=await Ke(u,{orgId:l,orgTier:this.tierOf(l),operation:"delete",objectName:d.map(b=>b.objectApiName).join(", "),recordCount:c,module:"seed"});if(g==="refused"||g==="declined"){this.recordNotRemoved(e,r,"stopped",{guard:g}),g==="refused"?this.refuse(e,`Operation blocked by Production Guard: ${p.blockedReason??p.impactSummary}`,St.blocked):this.refuse(e,"Operation cancelled by user (confirmation declined).",St.declined,!0);return}if(o?.signal.aborted){this.recordNotRemoved(e,r,"stopped",{guard:g,code:gt});let b={runId:r.runId,status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(A(this.deps,e,"seed:remove:response",{result:b,operationId:e.id}));return}let h=e.id,f=`Removing ${c} record(s) a Seed run created`,m=new AbortController,y=()=>{},w=new Promise((b,O)=>{y=k=>k===void 0?b():O(k)});w.catch(()=>{}),We(this.deps,h,"seed",f),this.registry?.register(h,"seed",f,w,m),this.liveTracker?.register(h,"seed",f,c);let v,R;try{let b=await B(l,this.deps.orgRegistry,this.deps.orgManager);R=n.sweep?await this.sweepOfRemoval({conn:b,run:r,includeChanged:i,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,signal:m.signal,guard:u,operationId:h}):void 0;let O=R;await O?.ask();let k;if(n.muteAutomation===!0){let K=[...new Set(d.map(me=>me.objectApiName))],Q=Go({setToDraft:zt(K),delete:Kr(K)},O?.takes??[]),_=Q.delete??[],V=this.targetAutomation,ue=await new ge(wv).withTimeout("seed:remove automation",()=>V.read(r.targetOrgId,_)).catch(me=>({unread:T(me)}));k=await mt(async()=>Et(b),ue,{...this.muteLeases,writes:Gr(Q)})}let S,E=k?.muted,I=async()=>{let K=k?.prepared;!K||m.signal.aborted||(S=await K.acquire(h),E=S.outcome)},C=Gt(b,"seed:remove"),F=await ta(C,r.created),{result:Y,notes:z}=await Ci({run:r,org:C,includeChanged:i,...a?{again:a}:{},store:t,...O?{sweep:K=>O.first(K),afterRemoval:K=>O.afterRemoval(K),automationMade:O.automationMade}:{},...r.runUserId?{runUserId:r.runUserId}:{},onUndeletable:Tr(this.deps,l,"seed:remove"),beforeFirstWrite:I,signal:m.signal,onProgress:(K,Q,_)=>{let V=Math.min(100,Math.round(K/Math.max(Q,1)*100));$e(this.deps,h,V,K,Q,_),m.signal.aborted||this.registry?.updateProgress(h,V),this.liveTracker?.updateProgress(h,V,K,Q,_)}}).finally(async()=>{S&&(E=await S.release())}),te=await R?.settle(),H=Y.status==="cancelled"?{}:await F.take();for(let K of[...z,...H.note?[H.note]:[]])this.deps.log(`[WARN] seed:remove ${h}: ${K}`);let x={runId:Y.runId,status:no(Y.status,te),includeChanged:Y.includeChanged,objects:H.object?[...Y.objects,H.object]:Y.objects,finishedAt:Y.finishedAt,...Y.leftBy?{leftBy:Y.leftBy}:{},...te?{sweep:te}:{},...E?{mutedAutomation:E}:{}};X(this.deps,{action:"cleanup_delete",module:"seed",operationId:h,orgId:l,outcome:oo(Y),guard:g,objects:Yr(x.objects),...x.leftBy?{leftBy:x.leftBy}:{},...E?{muted:ot(E)}:{},details:{runId:r.runId}});let j=A(this.deps,e,"seed:remove:response",{result:x,operationId:h});this.deps.broker.postToWebview(j),this.deps.log(`[TX] ${j.type} id=${j.id} status=${x.status}`),x.status==="cancelled"||x.sweep?.status==="cancelled"?(pe(this.deps,h,{aborted:!0}),this.liveTracker?.cancel(h)):(pe(this.deps,h,{status:x.status}),x.status==="failure"?(v=new Error("Nothing this run created could be removed."),this.liveTracker?.fail(h,"Nothing this run created could be removed.")):x.status==="partial"?this.liveTracker?.partial(h):this.liveTracker?.complete(h))}catch(b){v=b,await R?.settle().catch(()=>{});let O=kt(b)?b:void 0;this.recordNotRemoved(e,r,O?"stopped":"failure",{guard:g,...O?{code:O.code}:{}}),P(this.deps,"seed:remove","seed:remove:error",e,b,{code:O?.code??"REMOVE_ERROR",retryable:!0}),pe(this.deps,h,{status:"failure"}),this.liveTracker?.fail(h,T(b))}finally{y(v)}}};var Za="sync:history:all",vv="syncHistory";var ed=class{constructor(e){this.configStore=e}configStore;save(e){let t=this.loadAll(),r=t.findIndex(o=>o.id===e.id);r>=0?t[r]=e:t.push(e);let n=t.length>500?t.sort((o,i)=>o.startTime.localeCompare(i.startTime)).slice(t.length-500):t;this.configStore.set(Za,n,vv)}load(e){return this.loadAll().find(t=>t.id===e)}list(){return this.loadAll().sort((e,t)=>t.startTime.localeCompare(e.startTime))}delete(e){let t=this.loadAll(),r=t.filter(n=>n.id!==e);return r.length===t.length?!1:(this.configStore.set(Za,r,vv),!0)}exportAsJson(e){let t=this.getFilteredEntries(e);return JSON.stringify(t,null,2)}exportAsCsv(e){let t=this.getFilteredEntries(e),r="id,configName,status,totalProcessed,totalSuccess,totalFailed,totalSkipped,startTime,endTime,duration,triggeredBy",n=t.map(o=>{let i=this.csvEscape(o.configSnapshot.name);return[o.id,i,o.result.status,o.result.totalProcessed,o.result.totalSuccess,o.result.totalFailed,o.result.totalSkipped,o.startTime,o.endTime,o.result.duration,o.triggeredBy].join(",")});return[r,...n].join(`
10
+ `)}clear(){this.configStore.delete(Za)}loadAll(){let e=this.configStore.get(Za);return Array.isArray(e)?e:[]}getFilteredEntries(e){let t=this.list();if(!e||e.length===0)return t;let r=new Set(e);return t.filter(n=>r.has(n.id))}csvEscape(e){return e.includes(",")?`"${e}"`:e}};var DT=/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+:/;function xT(s){if(s.errors.length<=50)return s;let e=s.errors.slice(0,50),t=0;for(let r of s.errors.slice(50))DT.test(r)||e.includes(r)?t++:e.push(r);return t===0?{...s,errors:e}:{...s,errors:e,refusalsDropped:(s.refusalsDropped??0)+t}}var td=class{constructor(e,t=()=>crypto.randomUUID()){this.historyStore=e;this.generateId=t}historyStore;generateId;logExecution(e,t,r,n){let i=new Date(t.timestamp).getTime()-t.duration,a={id:this.generateId(),configSnapshot:structuredClone(e),result:{...t,objectResults:t.objectResults.map(xT)},startTime:new Date(i).toISOString(),endTime:t.timestamp,triggeredBy:r,...n?{scheduleId:n}:{}};return this.historyStore.save(a),a}getHistory(){return this.historyStore.list()}getEntry(e){return this.historyStore.load(e)}exportHistory(e,t){return e==="csv"?this.historyStore.exportAsCsv(t):this.historyStore.exportAsJson(t)}};var MT={Report:"ReportFolder",Dashboard:"DashboardFolder",EmailTemplate:"EmailTemplateFolder"},jT=new Set(["compare:execute","compare:permissions","compare:snapshots","compare:drift","compare:validate-deployment","compare:deploy"]),NT=5;function $T(s){let e=new Map;for(let t of s.components){let r=e.get(t.componentType)??{objectApiName:t.componentType,created:0,updated:0,deleted:0,failed:0};if(t.outcome==="created")r.created+=1;else if(t.outcome==="changed")r.updated+=1;else if(t.outcome==="failed")r.failed+=1;else continue;e.set(t.componentType,r)}return[...e.values()]}var rd=class{constructor(e,t={}){this.deps=e;this.options=t}deps;options;validations=new Map;async handle(e){if(!jT.has(e.type))return!1;switch(e.type){case"compare:execute":return await this.handleCompareStart(e),!0;case"compare:permissions":return await this.handlePermissions(e),!0;case"compare:snapshots":return await this.handleSnapshots(e),!0;case"compare:drift":return await this.handleDrift(e),!0;case"compare:validate-deployment":return await this.handleValidateDeployment(e),!0;case"compare:deploy":return await this.handleDeploy(e),!0;default:return!1}}async handleValidateDeployment(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(ch,e,"compare:error",this.deps);if(!t)return;let r=t.testLevel==="RunSpecifiedTests"?t.runTests??[]:[];try{if(!await this.passGuard(e,t.targetOrgId,t.components,!0))return;let n=await B(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await import("./chunk-ZOVSMN5C.mjs"),a=this.options.waiting??i.DEFAULT_WAITING,d=this.progressTo(e),c=await i.retrieveComponents(i.metadataApiOf(n),n.version,t.components,{waiting:a,onProgress:d});if(c.managed.length>0){P(this.deps,"compare:validate-deployment","compare:error",e,new Error("A managed package installed "+c.managed.map(p=>`${p.componentType} ${p.fullName}`).join(", ")+" in the source, and it owns them: untick them and validate again. Nothing was sent to the target."),{code:"MANAGED"});return}let l=c.retrieved.length>0?await i.deployPackage(i.metadataApiOf(o),c.zipFile,i.deployOptions(!0,t.testLevel,r),{waiting:a,onProgress:d}):void 0,u=i.deploymentReport(l,c,{sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,checkOnly:!0,testLevel:t.testLevel,runTests:r});u.success&&u.deployId&&this.keepValidation(u.deployId,{sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,zipFile:c.zipFile,components:c.retrieved,testLevel:t.testLevel,runTests:r}),this.post(A(this.deps,e,"compare:validate-deployment:response",{report:u}),u)}catch(n){P(this.deps,"compare:validate-deployment","compare:error",e,n,{code:await this.deployErrorCode(n)})}}async handleDeploy(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(lh,e,"compare:error",this.deps);if(!t)return;let r=this.validations.get(t.validationId);if(!r){P(this.deps,"compare:deploy","compare:error",e,new Error(`No successful validation ${t.validationId} is waiting in this window: validate the deployment, then deploy it. Nothing was deployed.`),{code:"NOT_VALIDATED"});return}if(r.targetOrgId!==t.targetOrgId){P(this.deps,"compare:deploy","compare:error",e,new Error(`Validation ${t.validationId} was run in another org than the one named. Nothing was deployed.`),{code:"TARGET_MISMATCH"});return}let n;try{if(n=await this.passGuard(e,r.targetOrgId,r.components,!1),!n)return;this.validations.delete(t.validationId);let o=await B(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await import("./chunk-ZOVSMN5C.mjs"),a=await i.deployPackage(i.metadataApiOf(o),r.zipFile,i.deployOptions(!1,r.testLevel,r.runTests),{waiting:this.options.waiting??i.DEFAULT_WAITING,onProgress:this.progressTo(e)}),d=i.deploymentReport(a,{missing:[],problems:[]},{sourceOrgId:r.sourceOrgId,targetOrgId:r.targetOrgId,checkOnly:!1,testLevel:r.testLevel,runTests:r.runTests});X(this.deps,{action:"metadata_deploy",module:"compare",operationId:e.id,orgId:r.targetOrgId,outcome:d.success?"success":"failure",guard:n,objects:$T(d),source:{origin:"org",orgId:r.sourceOrgId}}),this.post(A(this.deps,e,"compare:deploy:response",{report:d}),d)}catch(o){n&&X(this.deps,{action:"metadata_deploy",module:"compare",operationId:e.id,orgId:r.targetOrgId,outcome:"failure",guard:n}),P(this.deps,"compare:deploy","compare:error",e,o,{code:await this.deployErrorCode(o)})}}async passGuard(e,t,r,n){let o=this.deps.infraServices?.productionGuard??new gy,i=this.deps.orgManager.getOrg(t),a={orgId:t,orgTier:Ee(i),operation:"deploy",objectName:[...new Set(r.map(l=>l.componentType))].join(", "),recordCount:r.length,module:"compare"};if(n){let l=o.check(a);if(l.allowed)return"allowed";this.refuse(e,l.blockedReason??l.impactSummary);return}let{check:d,decision:c}=await Ke(o,a);if((c==="refused"||c==="declined")&&X(this.deps,{action:"metadata_deploy",module:"compare",operationId:e.id,orgId:t,outcome:"stopped",guard:c}),c==="refused"){this.refuse(e,d.blockedReason??d.impactSummary);return}if(c==="declined"){P(this.deps,e.type,"compare:error",e,new Error("Operation cancelled by user (deployment confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}return c}refuse(e,t){P(this.deps,e.type,"compare:error",e,new Error(`Operation blocked by Production Guard: ${t}`),{code:"GUARD_BLOCKED"})}keepValidation(e,t){for(this.validations.set(e,t);this.validations.size>NT;){let r=this.validations.keys().next().value;if(r===void 0)break;this.validations.delete(r)}}progressTo(e){return t=>$e(this.deps,e.id,t.total>0?Math.round(t.done/t.total*100):0,t.done,t.total,t.step)}post(e,t){this.deps.broker.postToWebview(e),this.deps.log(`[TX] ${e.type} id=${e.id} deploy=${t.deployId??"-"} status=${t.status}`)}async deployErrorCode(e){let{DeploymentStillRunning:t}=await import("./chunk-ZOVSMN5C.mjs");return e instanceof t?"STILL_RUNNING":"DEPLOY_ERROR"}async handleCompareStart(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(ns,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await this.compareOrgs(r),o=A(this.deps,e,"compare:execute:response",n);this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(n){P(this.deps,"compare:execute","compare:error",e,n)}}async compareOrgs(e,t){t?.throwIfAborted();let r=await B(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager);t?.throwIfAborted();let n=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),{DiffEngine:o}=await import("./chunk-7F54PZUS.mjs"),{MetadataCompare:i}=await import("./chunk-F2424IKX.mjs"),{createContentReader:a}=await import("./chunk-HXS7ORUF.mjs"),d=new o,c=async(h,f)=>{let m=h===e.sourceOrgId?r:n,y=new Map,w=async b=>{t?.throwIfAborted();let O=await m.metadata.list(b);return De(m.limitInfo,`compare:metadata list ${String(f)}`),Array.isArray(O)?O:[]},v=MT[f],R=v?(await w([{type:v}])).map(b=>({type:f,folder:b.fullName})):[{type:f}];for(let b=0;b<R.length;b+=3)for(let O of await w(R.slice(b,b+3)))y.set(O.fullName,JSON.stringify(O));return y},l=a(h=>h===e.sourceOrgId?r:n,t),u=new i(c,d,l);if(!this.deps.services)throw new Error("CompareHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let p=this.deps.services.compareOrchestrator({metadataCompare:u,diffEngine:d,services:this.deps.services}),g={id:crypto.randomUUID(),name:"compare-from-ui",sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,mode:"metadata",componentTypes:e.types,includeManaged:e.includeManaged??!0,createdAt:new Date().toISOString()};return p.execute(g,t)}async handlePermissions(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(wi,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await B(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=async(f,m)=>{let y=await At(f,"SELECT Id, Name, Label, IsOwnedByProfile FROM PermissionSet WHERE IsOwnedByProfile = false");De(f.limitInfo,`compare:permissions ${m}`);let w=await At(f,"SELECT Id, Name FROM Profile");return De(f.limitInfo,`compare:permissions profiles ${m}`),{permSets:y,profiles:w}},[a,d]=await Promise.all([i(n,"source"),i(o,"target")]),c=new Set(a.permSets.map(f=>f.Name)),l=new Set(d.permSets.map(f=>f.Name)),u=new Set(a.profiles.map(f=>f.Name)),p=new Set(d.profiles.map(f=>f.Name)),g={permissionSets:{sourceOnly:a.permSets.filter(f=>!l.has(f.Name)).map(f=>({name:f.Name,label:f.Label})),targetOnly:d.permSets.filter(f=>!c.has(f.Name)).map(f=>({name:f.Name,label:f.Label})),shared:a.permSets.filter(f=>l.has(f.Name)).map(f=>({name:f.Name,label:f.Label}))},profiles:{sourceOnly:a.profiles.filter(f=>!p.has(f.Name)).map(f=>({name:f.Name})),targetOnly:d.profiles.filter(f=>!u.has(f.Name)).map(f=>({name:f.Name})),shared:a.profiles.filter(f=>p.has(f.Name)).map(f=>({name:f.Name}))}},h=A(this.deps,e,"compare:permissions:response",{permissions:g});this.deps.broker.postToWebview(h),this.deps.log(`[TX] ${h.type} id=${h.id}`)}catch(n){P(this.deps,"compare:permissions","compare:error",e,n)}}async handleSnapshots(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(wi,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await B(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=async(g,h)=>{let f=await g.describeGlobal();De(g.limitInfo,`compare:snapshots describeGlobal ${h}`);let m=f.sobjects.map(y=>({name:y.name,custom:y.custom,label:y.label,queryable:y.queryable}));return{totalObjects:m.length,customObjects:m.filter(y=>y.custom).length,standardObjects:m.filter(y=>!y.custom).length,queryableObjects:m.filter(y=>y.queryable).length,objects:m}},[a,d]=await Promise.all([i(n,"source"),i(o,"target")]),c=new Set(a.objects.map(g=>g.name)),l=new Set(d.objects.map(g=>g.name)),u={source:{orgId:r.sourceOrgId,totalObjects:a.totalObjects,customObjects:a.customObjects,standardObjects:a.standardObjects,queryableObjects:a.queryableObjects},target:{orgId:r.targetOrgId,totalObjects:d.totalObjects,customObjects:d.customObjects,standardObjects:d.standardObjects,queryableObjects:d.queryableObjects},diff:{sourceOnly:a.objects.filter(g=>!l.has(g.name)).map(g=>g.name),targetOnly:d.objects.filter(g=>!c.has(g.name)).map(g=>g.name),sharedCount:a.objects.filter(g=>l.has(g.name)).length},capturedAt:new Date().toISOString()},p=A(this.deps,e,"compare:snapshots:response",{snapshot:u});this.deps.broker.postToWebview(p),this.deps.log(`[TX] ${p.type} id=${p.id}`)}catch(n){P(this.deps,"compare:snapshots","compare:error",e,n)}}async handleDrift(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(wi,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await B(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=async(g,h)=>{let f={},m=await At(g,"SELECT Name, LanguageLocaleKey, DefaultLocaleSidKey, TimeZoneSidKey, FiscalYearStartMonth FROM Organization LIMIT 1");if(De(g.limitInfo,`compare:drift companyInfo ${h}`),m[0])for(let[y,w]of Object.entries(m[0]))y!=="attributes"&&y!=="Id"&&(f[`Organization.${y}`]=String(w));return f},[a,d]=await Promise.all([i(n,"source"),i(o,"target")]),c=new Set([...Object.keys(a),...Object.keys(d)]),l=[];for(let g of c){let h=a[g],f=d[g];h===void 0?l.push({setting:g,sourceValue:"",targetValue:f??"",status:"missing_source"}):f===void 0?l.push({setting:g,sourceValue:h,targetValue:"",status:"missing_target"}):h!==f?l.push({setting:g,sourceValue:h,targetValue:f,status:"drift"}):l.push({setting:g,sourceValue:h,targetValue:f,status:"match"})}let u={items:l,totalChecked:l.length,driftCount:l.filter(g=>g.status==="drift").length,matchCount:l.filter(g=>g.status==="match").length,missingCount:l.filter(g=>g.status==="missing_source"||g.status==="missing_target").length,detectedAt:new Date().toISOString()},p=A(this.deps,e,"compare:drift:response",{drift:u});this.deps.broker.postToWebview(p),this.deps.log(`[TX] ${p.type} id=${p.id}`)}catch(n){P(this.deps,"compare:drift","compare:error",e,n)}}};import{randomBytes as QT}from"node:crypto";function Sv(s,e,t){return s==="delete"?{...at(e),deleted:t.done,failed:t.failed}:{...at(e),updated:t.done,failed:t.failed}}async function nd(s,e,t){let r=crypto.randomUUID(),n=s.infraServices?.productionGuard;if(!n)return X(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"stopped",code:ve.code}),{ran:!1,operationId:r,code:ve.code,message:ve.message};let o=s.orgManager.getOrg(e.orgId),{check:i,decision:a}=await Ke(n,{orgId:e.orgId,orgTier:Ee(o),operation:e.operation,objectName:e.objectNames.join(", "),recordCount:e.recordCount,module:"dataops"}),d=a;if(a==="refused"||a==="declined")return X(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"stopped",guard:a}),{ran:!1,operationId:r,guard:a,message:a==="refused"?`Operation blocked by Production Guard: ${i.blockedReason??i.impactSummary}`:"Operation cancelled by user (confirmation declined)."};We(s,r,"dataops",e.description);let c=new AbortController,l=()=>{},u=new Promise((f,m)=>{l=y=>y===void 0?f():m(y)});u.catch(()=>{}),s.infraServices?.backgroundRegistry?.register(r,"dataops",e.description,u,c);let p=Jt(t,r,"dataops",e.description,e.recordCount),g=[],h=0;try{let f=await e.run((w,v)=>{g.push({objectApiName:w,counts:v}),h+=v.done+v.failed;let R=Math.min(100,Math.round(h/Math.max(e.recordCount,1)*100)),b=`${w}: ${v.done} done, ${v.failed} refused`;$e(s,r,R,h,e.recordCount,b),p.progress(R,h,e.recordCount,b)},c.signal);await e.beforeEnd?.();let m=ul(f),y=c.signal.aborted;if(X(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,...y?m.done+m.failed>0?{outcome:"cancelled"}:{outcome:"stopped",code:Ze}:{outcome:m.status},...d?{guard:d}:{},objects:f.map(w=>Sv(e.operation,w.objectApiName,w.counts))}),y)return s.infraServices?.backgroundRegistry?.abort(r),pe(s,r,{aborted:!0,done:m.done,failed:m.failed}),p.cancel(),l(),{ran:!0,operationId:r,outcome:m,...d?{guard:d}:{},cancelled:!0,error:`Cancelled: ${m.done} record(s) ${e.operation==="delete"?"deleted":"overwritten"} before the cancel; the rest were left as they are.`};if(pe(s,r,{status:m.status,done:m.done,failed:m.failed}),m.status==="failure"){let w=`The org refused the ${m.failed} record(s)`;p.fail(w),l(new Error(w))}else m.status==="partial"?p.partial():p.complete(),l();return{ran:!0,operationId:r,outcome:m,...d?{guard:d}:{}}}catch(f){await e.beforeEnd?.();let m=T(f);return X(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"failure",...d?{guard:d}:{},objects:g.map(y=>Sv(e.operation,y.objectApiName,y.counts))}),Le(s,r,m,!0,{context:{module:"dataops",operation:e.origin,objectName:e.objectNames.join(", ")}}),p.fail(m),l(f),{ran:!0,operationId:r,outcome:{...ul(g),status:"failure"},...d?{guard:d}:{},error:m}}}var kv=100;async function FT(s,e,t){let r=new Map,n=[],o=t.map(a=>He(a.name)).filter(a=>a!=="Id"),i=[];for(let a=0;a<o.length;a+=kv)i.push(o.slice(a,a+kv));i.length===0&&i.push([]);for(let a of i){let d=await s.query(`SELECT ${["Id",...a].join(", ")} FROM ${e} ORDER BY Id DESC LIMIT ${200}`);for(let c of d.records){if(typeof c!="object"||c===null)continue;let l={...c};delete l.attributes;let u=typeof l.Id=="string"?l.Id:void 0;if(!u)continue;let p=r.get(u);p?Object.assign(p,l):(r.set(u,l),n.push(u))}}return n.map(a=>r.get(a))}async function _T(s,e,t){let r,n;try{if(r=Wt.parse(await s.describe(He(t))),n=He(r.name),r.queryable===!1)throw new Error(`${n} cannot be queried.`)}catch(h){return{status:"failed",objectApiName:t,message:T(h)}}let o=ls(e,n,r.fields),i=new Set(o.map(h=>h.field.name)),a=r.fields.filter(h=>sy(h)&&iy(h)||i.has(h.name)),d=[],c;try{d=await FT(s,n,a)}catch(h){c=T(h)}let l=c?o:ls(e,n,r.fields,d),u=e.getPatterns(),p=l.map(h=>{let f=ay(h.field),m=d.map(w=>w[h.field.name]),y=h.detectedBy==="content"?u[h.pattern]:void 0;return{fieldApiName:h.field.name,label:h.field.label,classification:h.classification,detectedBy:h.detectedBy,pattern:h.pattern,filled:m.filter(Di).length,...y?{matched:m.filter(w=>typeof w=="string"&&y.test(w)).length}:{},...f?{searchedFor:f}:{}}}).sort((h,f)=>f.filled-h.filled||h.label.localeCompare(f.label)),g=dy(r);return{status:"scanned",objectApiName:t,label:r.label,sampled:d.length,fields:p,nameField:g?{fieldApiName:g.name,label:g.label}:null,...c!==void 0?{sampleError:c}:{}}}async function Ov(s,e,t,r=()=>new Date){let n=r().toISOString(),o=[];for(let i of t.objects)o.push(await _T(s,e,i));return{orgId:t.orgId,scannedAt:n,sampleSize:200,objects:o}}async function UT(s,e,t,r){let n=t.fields.filter(oy).map(d=>d.name),o=await Vr(s,t.name,n,r),i=ls(e,t.name,t.fields,o),a=ly(t,i);return{objectApiName:t.name,records:o,erased:a.fields,plan:{objectApiName:t.name,label:t.label,records:o.length,fields:a.fields.map(d=>({fieldApiName:d.field.name,label:d.field.label,method:d.method})),kept:a.kept.map(d=>({fieldApiName:d.name,label:d.label}))}}}async function Iv(s,e,t,r){let n=[],o;for(let i of r){let a=Wt.parse(await s.describe(He(i.objectApiName))),d=l=>({objectApiName:a.name,plan:{objectApiName:a.name,label:a.label,records:0,refused:l}});if(t==="anonymize"){if(a.updateable!==!0){n.push(d(`The connected user may not edit ${a.label} records.`));continue}n.push(await UT(s,e,a,i.ids));continue}if(a.deletable!==!0){n.push(d(`The connected user may not delete ${a.label} records.`));continue}o??=await vi(s);let c=await Si(s,a,i.ids,o);n.push({objectApiName:a.name,ids:[...i.ids],plan:{objectApiName:a.name,label:a.label,records:i.ids.length,related:c.related,uncounted:c.uncounted}})}return n}function od(s){let e=new Map;for(let t of s)t.refused||t.records===0||e.set(t.objectApiName,(e.get(t.objectApiName)??0)+t.records);return[...e].map(([t,r])=>({objectApiName:t,records:r}))}function HT(s,e){return e.map(t=>({objectApiName:s,fieldApiName:t.field.name,method:t.method,config:{}}))}async function Av(s,e,t,r,n){let o=[];for(let i of t){if(n?.aborted)break;if(i.plan.refused)continue;let a;if(i.ids)a=await ki(s,i.objectApiName,i.ids,n);else{let d=i.erased??[],c=i.records??[];if(d.length===0||c.length===0)continue;let l=e.anonymize(c,HT(i.objectApiName,d)),u=[],p=0;c.forEach((g,h)=>{let f={Id:g.Id};for(let m of d)Di(g[m.field.name])&&(f[m.field.name]=l[h][m.field.name]??null);Object.keys(f).length>1?u.push(f):p++}),a=await xm(s,i.objectApiName,u,n),a.done+=p}o.push({objectApiName:i.objectApiName,counts:a}),r?.(i.objectApiName,a)}return o}var Tv="dataops:subject-requests",BT="audit",qT=G({objectApiName:L(),done:Me().int().nonnegative(),failed:Me().int().nonnegative()}),WT=Vs("kind",[G({kind:vt("searched"),at:L(),searchedBy:ke(Xe(["email","phone","name"])),objects:ke(G({objectApiName:L(),found:Me().int().nonnegative(),truncated:ze()}))}),G({kind:vt("exported"),at:L(),records:Me().int().nonnegative()}),G({kind:vt("erased"),at:L(),mode:Xe(["anonymize","delete"]),outcome:Xe(["success","partial","failure","stopped"]),operationId:L(),objects:ke(qT)})]),zT=G({requestId:L().min(1),orgId:L().min(1),openedAt:L(),events:ke(WT)}),sd=class{constructor(e,t=500){this.configStore=e;this.limit=t}configStore;limit;has(e,t){return this.read().some(r=>r.requestId===e&&r.orgId===t)}record(e,t,r){let n=this.read(),o=n.find(i=>i.requestId===e&&i.orgId===t);o||(o={requestId:e,orgId:t,openedAt:r.at,events:[]},n.push(o)),o.events.push(r),this.write(n)}list(){return this.read().reverse()}read(){let e=this.configStore.get(Tv);return Array.isArray(e)?e.flatMap(t=>{let r=zT.safeParse(t);return r.success?[r.data]:[]}):[]}write(e){this.configStore.set(Tv,e.slice(-this.limit),BT)}};function JT(s){return Uc(s).slice(-8)}function VT(s){return`%${s.split("").join("%")}%`}function Ev(s,e){return typeof s=="string"&&s.trim().toLowerCase()===e.trim().toLowerCase()}function XT(s,e,t){let r=He(s.name);if(e==="email"&&t.email){let n=t.email.trim();return{field:s,kind:e,soql:`${r} = '${Bt(n)}'`,matches:o=>Ev(o,n)}}if(e==="phone"&&t.phone){let n=JT(t.phone);return{field:s,kind:e,soql:`${r} LIKE '${VT(n)}'`,matches:o=>typeof o=="string"&&Uc(o).includes(n)}}if(e==="name"&&t.name){let n=t.name.trim();return{field:s,kind:e,soql:`${r} = '${Bt(n)}'`,matches:o=>Ev(o,n)}}}async function KT(s,e,t){try{let r=Wt.parse(await s.describe(He(e))),n=He(r.name);if(r.queryable===!1)throw new Error(`${n} cannot be queried.`);let o=cy(r).flatMap(({field:g,kind:h})=>{let f=XT(g,h,t.identifiers);return f?[f]:[]});if(o.length===0)return{status:"skipped",objectApiName:e,label:r.label};let i=o.map(g=>({fieldApiName:g.field.name,label:g.field.label,kind:g.kind})),a=o.map(g=>g.soql).join(" OR "),d=(await s.query(`SELECT COUNT() FROM ${n} WHERE ${a}`)).totalSize;if(d===0)return{status:"searched",objectApiName:e,label:r.label,counted:d,records:[],truncated:!1,searched:i};let c=r.fields.find(g=>g.nameField===!0),l=[...new Set(["Id",...c?[c.name]:[],...o.map(g=>g.field.name)])].map(He),u=await s.query(`SELECT ${l.join(", ")} FROM ${n} WHERE ${a} ORDER BY Id LIMIT ${t.limit}`),p=[];for(let g of u.records){if(typeof g!="object"||g===null)continue;let h=g;if(!On(h.Id))continue;let f=[...new Set(o.filter(y=>y.matches(h[y.field.name])).map(y=>y.field.name))];if(f.length===0)continue;let m=c?h[c.name]:null;p.push({id:h.Id,name:typeof m=="string"?m:null,matchedBy:f})}return{status:"searched",objectApiName:e,label:r.label,counted:d,records:p,truncated:d>t.limit,searched:i}}catch(r){return{status:"failed",objectApiName:e,message:YT(T(r),t.identifiers)}}}function YT(s,e){let t=s;for(let r of[e.email,e.name,e.phone]){let n=r?.trim();n&&(t=t.replace(new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),"\u2026"))}return t}async function Pv(s,e){let t=[];for(let r of e.objects)t.push(await KT(s,r,e));return t}var ZT=6e4,eE=new Set(["dataops:pii-inventory","dataops:dsr:search","dataops:dsr:export","dataops:dsr:erase","dataops:dsr:log"]),tE=20;function rE(s){let e="payload"in s?s.payload:void 0;return typeof e=="object"&&e!==null&&"dryRun"in e?e.dryRun===!0:!1}function nE(s){return typeof s=="object"&&s!==null&&"success"in s&&s.success===!0}function oE(s,e){return{...s,update:async(t,r)=>{e.beforeWrite(t);try{let n=await s.update(t,r),o=Array.isArray(n)?n:[n];return e.wrote(t,o.flatMap((i,a)=>nE(i)?[r[a]?.Id]:[])),n}catch(n){throw hy(n)==="may-have-written"&&e.wrote(t,r.map(o=>o.Id)),n}}}}function sE(s){return["email","name","phone"].filter(e=>s[e]!==void 0)}var id=class{constructor(e,t){this.deps=e;this.saveDialog=t??new Qr}deps;found=new Map;maskingKey=QT(32).toString("hex");saveDialog;writing=new my;liveTracker;setLiveOperationTracker(e){this.liveTracker=e}targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;muteLeases={};setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}duplicatesSettleMs=Ry;setDuplicatesSettle(e){this.duplicatesSettleMs=e}ownReader(){return this.reader??=import("./chunk-4XZ5YT5O.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}isWritingTo(e){return this.writing.has(e)}get requestLog(){return new sd(this.deps.configStore)}get detector(){return this.deps.infraServices?.piiDetector??new xi}async session(e,t){let r=await B(e,this.deps.orgRegistry,this.deps.orgManager);return Ri(r,t)}async handle(e){if(!eE.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"dataops:pii-inventory":return await this.handleInventory(e),!0;case"dataops:dsr:search":return await this.handleSearch(e),!0;case"dataops:dsr:export":return await this.handleExport(e),!0;case"dataops:dsr:erase":return await this.writing.during(rE(e)?void 0:yy(e,"orgId"),()=>this.handleErase(e)),!0;default:return this.handleLog(e),!0}}async handleInventory(e){let t=D(Kf,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:pii-inventory"),n=await Ov(r,this.detector,t),o=A(this.deps,e,"dataops:pii-inventory:response",{...n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} objects=${n.objects.length}`)}catch(r){P(this.deps,"dataops:pii-inventory","dataops:error",e,r)}}async handleSearch(e){let t=D(Yf,e,"dataops:error",this.deps);if(!t)return;let{orgId:r,objects:n}=t,o={...t.email!==void 0?{email:t.email}:{},...t.name!==void 0?{name:t.name}:{},...t.phone!==void 0?{phone:t.phone}:{}};try{let i=await this.session(r,"dataops:dsr:search"),a=await Pv(i,{objects:n,identifiers:o,limit:200}),d=this.requestLog,c=t.requestId!==void 0&&d.has(t.requestId,r)?t.requestId:crypto.randomUUID(),l=new Date().toISOString(),u={orgId:r,objects:new Map};for(let f of a)f.status==="searched"&&u.objects.set(f.objectApiName,new Set(f.records.map(m=>m.id)));this.hold(c,u),d.record(c,r,{kind:"searched",at:l,searchedBy:sE(o),objects:a.flatMap(f=>f.status==="searched"?[{objectApiName:f.objectApiName,found:f.records.length,truncated:f.truncated}]:[])});let p={requestId:c,orgId:r,searchedAt:l,limit:200,objects:a},g=A(this.deps,e,"dataops:dsr:search:response",{...p});this.deps.broker.postToWebview(g);let h=[...u.objects.values()].reduce((f,m)=>f+m.size,0);this.deps.log(`[TX] ${g.type} id=${g.id} records=${h}`)}catch(i){P(this.deps,"dataops:dsr:search","dataops:error",e,i)}}hold(e,t){for(this.found.delete(e),this.found.set(e,t);this.found.size>tE;){let r=this.found.keys().next().value;if(r===void 0)break;this.found.delete(r)}}heldFor(e,t){let r=this.found.get(e);if(!r||r.orgId!==t)throw new Error("This request has found nothing in this window. Search again: an export or an erasure only acts on the records a search found.");return r}async handleExport(e){let t=D(Qf,e,"dataops:error",this.deps);if(t)try{let r=this.heldFor(t.requestId,t.orgId),n=await this.session(t.orgId,"dataops:dsr:export"),o={},i=0;for(let[u,p]of r.objects){if(p.size===0)continue;let g=Wt.parse(await n.describe(u)),h=await Vr(n,g.name,g.fields.map(f=>f.name),[...p]);o[u]=h,i+=h.length}let a=new Date().toISOString(),d={sandforgeSubjectRequestVersion:1,requestId:t.requestId,orgId:t.orgId,exportedAt:a,objects:o},c=await this.saveDialog.save(`sandforge-subject-request-${t.requestId.slice(0,8)}.json`,JSON.stringify(d,null,2),["json"]);c.status==="saved"&&this.requestLog.record(t.requestId,t.orgId,{kind:"exported",at:a,records:i});let l=A(this.deps,e,"dataops:dsr:export:response",{requestId:t.requestId,records:i,saved:c});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} ${c.status} records=${i}`)}catch(r){P(this.deps,"dataops:dsr:export","dataops:error",e,r)}}async handleErase(e){let t=D(eh,e,"dataops:error",this.deps);if(!t)return;let{orgId:r,requestId:n,mode:o,dryRun:i}=t;try{let a=this.heldFor(n,r),d=t.records.reduce((j,K)=>{let Q=a.objects.get(K.objectApiName);return j+K.ids.filter(_=>!Q?.has(_)).length},0);if(d>0)throw new Error(`${d} of the records to erase were not found by this request. Search again, and erase from what the search lists.`);let c=await this.session(r,"dataops:dsr:erase"),l=await Iv(c,this.detector,o,t.records),u=l.map(j=>j.plan),p=od(u);if(i){let j=A(this.deps,e,"dataops:dsr:erase:response",{requestId:n,mode:o,dryRun:i,plan:u,written:p});this.deps.broker.postToWebview(j),this.deps.log(`[TX] ${j.type} id=${j.id} plan objects=${u.length}`);return}let g=u.filter(j=>!j.refused&&j.records>0),h=g.reduce((j,K)=>j+K.records,0);if(h===0){let j=u.flatMap(K=>K.refused?[K.refused]:[]);throw new Error(j.length>0?`Nothing can be erased. ${j.join(" ")}`:"Nothing is left to erase: the records found are no longer in the org.")}let f=Re(this.deps.orgManager.getOrg(r),r),m=await B(r,this.deps.orgRegistry,this.deps.orgManager),y=this.targetAutomation,w=await Dr({act:o==="delete"?"cleanup":"masking",target:f,objects:p,org:ao(m,j=>new ge(ZT).withTimeout("dataops automation",()=>y.read(r,j)),Ee(this.deps.orgManager.getOrg(r))==="production"),accord:t,mayMute:!0,muteLeases:this.muteLeases,voice:"erasure"}),v=Zr(w.answer),R=v?{refused:v}:await Pn(w,e.id,t.acceptEmails===!0,"erasure");if("refused"in R){let j=crypto.randomUUID();X(this.deps,{action:"subject_erase",module:"dataops",operationId:j,orgId:r,outcome:"stopped",code:R.refused.code}),this.requestLog.record(n,r,{kind:"erased",at:new Date().toISOString(),mode:o,outcome:"stopped",operationId:j,objects:[]}),P(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(R.refused.message),{code:R.refused.code,...v?Ni(v):{}});return}let b=R.held,O={},k=async()=>{if(!(!b||O.back)){O.back=await b.release();for(let j of _t(O.back,f))this.deps.log(`[INFO] ${j}`)}},S=o==="anonymize"?Sy({query:async j=>m.query(j),serverTime:async()=>(await m.soap.getServerTimestamp()).timestamp},vy(w.answer.automation,p.map(j=>j.objectApiName)),{settleMs:this.duplicatesSettleMs}):void 0,E={},I=async()=>{await k(),!E.read&&(E.read=!0,E.duplicates=await S?.read())},C=()=>Oy(E.duplicates,f,"erasure"),F=()=>b?{mutedAutomation:O.back??b.outcome}:{},Y=new Cy(void 0,this.maskingKey),z=await nd(this.deps,{orgId:r,operation:o==="delete"?"delete":"update",objectNames:g.map(j=>j.objectApiName),recordCount:h,action:"subject_erase",description:`Erase ${h} record(s) of a subject request`,origin:"dataops:dsr:erase",run:(j,K)=>Av(S?oE(c,S):c,Y,l,j,K),beforeEnd:I},this.liveTracker).finally(k),te=new Date().toISOString();if(!z.ran){this.requestLog.record(n,r,{kind:"erased",at:te,mode:o,outcome:"stopped",operationId:z.operationId,objects:[]}),P(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(z.message),{...z.code?{code:z.code}:{},extraPayload:F()});return}this.requestLog.record(n,r,{kind:"erased",at:te,mode:o,outcome:z.outcome.status,operationId:z.operationId,objects:z.outcome.objects});let{duplicates:H}=E;if(z.error!==void 0){let j=C();P(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(j?`${z.error} ${j}`:z.error),{...z.cancelled?{code:Ze}:{},extraPayload:{...F(),...H?{duplicates:H}:{}}});return}let x=A(this.deps,e,"dataops:dsr:erase:response",{requestId:n,mode:o,dryRun:i,plan:u,outcome:z.outcome,...F(),...H?{duplicates:H}:{}});this.deps.broker.postToWebview(x),this.deps.log(`[TX] ${x.type} id=${x.id} ${z.outcome.status} done=${z.outcome.done} failed=${z.outcome.failed}`),ky(H)&&Oe(this.deps,"warning","Erase",C())}catch(a){P(this.deps,"dataops:dsr:erase","dataops:error",e,a)}}handleLog(e){try{let t=this.requestLog.list(),r=A(this.deps,e,"dataops:dsr:log:response",{entries:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} entries=${t.length}`)}catch(t){P(this.deps,"dataops:dsr:log","dataops:error",e,t)}}};var iE=new Set(["User","Group","RecordType","BusinessHours","Profile","UserRole"]);function jv(s){return s.type==="reference"&&Tm(s)&&s.nillable===!0&&s.filterable===!0&&s.referenceTo?.length===1&&!iE.has(s.referenceTo[0])}function Nv(s,e){return e>0&&s/e>=.9}async function aE(s,e,t){let r,n,o;try{if(r=Wt.parse(await s.describe(He(e.objectApiName))),n=He(r.name),r.queryable===!1)throw new Error(`${n} cannot be queried.`);o=(await s.query(`SELECT COUNT() FROM ${n}`)).totalSize}catch(p){return{status:"failed",objectApiName:e.objectApiName,message:T(p)}}let i=r.fields.filter(ll).sort((p,g)=>p.label.localeCompare(g.label)),a=r.fields.filter(jv),[d,c,l]=await Promise.all([Em(s,n,a,o),Pm(s,n,i,e.duplicateKey,o),Dm(s,n,r.fields,t,o)]),u=d.fields.filter(p=>Nv(p.filled,o)&&p.filled<o).map(p=>{let g=a.find(h=>h.name===p.fieldApiName);return{fieldApiName:p.fieldApiName,label:p.label,referenceTo:g?.referenceTo?.[0]??"",filled:p.filled,empty:o-p.filled}}).sort((p,g)=>g.empty-p.empty||p.label.localeCompare(g.label));return{status:"scanned",objectApiName:e.objectApiName,label:r.label,totalRecords:o,stale:l.stale,orphans:u,duplicates:c.duplicates,keyFields:i.map(p=>({fieldApiName:p.name,label:p.label})),errors:[...d.errors,...c.errors,...l.errors]}}async function $v(s,e,t=()=>new Date){if(!Number.isInteger(e.staleDays)||e.staleDays<1)throw new Error(`A staleness threshold is a whole number of days, not ${e.staleDays}.`);let r=t().toISOString(),n=[];for(let o of e.objects)n.push(await aE(s,o,e.staleDays));return{orgId:e.orgId,staleDays:e.staleDays,scannedAt:r,orphanThreshold:.9,bounds:{duplicateGroupLimit:Om,duplicateSample:Im,singleFieldQueries:Am},objects:n}}function Dv(s){return s.flatMap(e=>{let t=typeof e=="object"&&e!==null?e.Id:void 0;return On(t)?[t]:[]})}function dE(s,e){switch(s){case"int":case"long":case"double":case"currency":case"percent":return typeof e=="number"&&Number.isFinite(e)?String(e):void 0;case"boolean":return typeof e=="boolean"?String(e):void 0;case"date":return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(e)?e:void 0;case"datetime":case"time":return;default:return typeof e=="string"?`'${Bt(e)}'`:void 0}}function cE(s,e){let t=String(e??"");return typeof e=="string"&&s!=="date"?t.toLowerCase():t}var xv=100,lE=2e3;async function uE(s,e,t,r){let n=He(e.name),o=He(t.name),i=await Cm(s,n,t.name),a=i.rows.reduce((u,p)=>u+p.count-1,0),d=i.rows.map(u=>dE(t.type,u.value));if(d.some(u=>u===void 0))throw new Error(`Copies of ${e.label} records cannot be picked out by ${t.label}: its values are dates and times, which this cleanup does not compare.`);let c=e.fields.some(u=>u.name==="LastModifiedDate"),l=[];for(let u=0;u<d.length&&l.length<r;u+=xv){let p=d.slice(u,u+xv).join(", "),g=await s.query(`SELECT Id, ${o}${c?", LastModifiedDate":""} FROM ${n} WHERE ${o} IN (${p}) ORDER BY Id LIMIT ${lE}`),h=new Map;for(let f of g.records){if(typeof f!="object"||f===null)continue;let m=f;if(!On(m.Id))continue;let y=cE(t.type,m[t.name]),w=h.get(y)??[];w.push({id:m.Id,modified:typeof m.LastModifiedDate=="string"?m.LastModifiedDate:""}),h.set(y,w)}for(let f of h.values()){f.sort((m,y)=>y.modified.localeCompare(m.modified)||y.id.localeCompare(m.id));for(let m of f.slice(1)){if(l.length>=r)break;l.push(m.id)}}}return{total:a,ids:l}}async function au(s,e,t,r){let n=Wt.parse(await s.describe(He(e))),o=He(n.name),i=c=>n.fields.find(l=>l.name.toLowerCase()===c.toLowerCase());if(t.kind==="stale"){if(!Number.isInteger(t.days)||t.days<1)throw new Error(`A staleness threshold is a whole number of days, not ${t.days}.`);if(!i("LastModifiedDate"))throw new Error(`${n.label} records carry no date of last modification.`);let c=`LastModifiedDate < LAST_N_DAYS:${t.days}`,l=(await s.query(`SELECT COUNT() FROM ${o} WHERE ${c}`)).totalSize,u=await s.query(`SELECT Id FROM ${o} WHERE ${c} ORDER BY LastModifiedDate, Id LIMIT ${r}`),p=Dv(u.records);return{object:n,total:l,ids:p,truncated:l>p.length}}if(t.kind==="orphans"){let c=i(t.fieldApiName);if(!c||!jv(c))throw new Error(`${t.fieldApiName} is not a lookup of ${n.label} that can leave a record without its parent.`);let l=He(c.name),u=(await s.query(`SELECT COUNT() FROM ${o}`)).totalSize,p=(await s.query(`SELECT COUNT() FROM ${o} WHERE ${l} = null`)).totalSize;if(!Nv(u-p,u))throw new Error(`${c.label} is filled on fewer than ${Math.round(.9*100)}% of ${n.label} records: the business does not rely on it, and a record without it is no orphan.`);let g=await s.query(`SELECT Id FROM ${o} WHERE ${l} = null ORDER BY Id LIMIT ${r}`),h=Dv(g.records);return{object:n,total:p,ids:h,truncated:p>h.length}}let a=i(t.keyField);if(!a||!ll(a))throw new Error(`${t.keyField} is not a field ${n.label} records can be grouped by.`);let d=await uE(s,n,a,r);return{object:n,total:d.total,ids:d.ids,truncated:d.total>d.ids.length}}var pE=6e4,gE=new Set(["dataops:cleanup:scan","dataops:cleanup:export","dataops:cleanup:delete"]);function Fv(s){switch(s.kind){case"stale":return`stale-${s.days}d`;case"orphans":return`orphans-${s.fieldApiName}`;default:return`duplicates-${s.keyField}`}}var ad=class{constructor(e,t){this.deps=e;this.saveDialog=t??new Qr}deps;saveDialog;liveTracker;setLiveOperationTracker(e){this.liveTracker=e}targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;muteLeases={};setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}ownReader(){return this.reader??=import("./chunk-4XZ5YT5O.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async session(e,t){let r=await B(e,this.deps.orgRegistry,this.deps.orgManager);return Ri(r,t)}async handle(e){if(!gE.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"dataops:cleanup:scan":return await this.handleScan(e),!0;case"dataops:cleanup:export":return await this.handleExport(e),!0;default:return await this.handleDelete(e),!0}}async handleScan(e){let t=D(Xf,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:cleanup:scan"),n=await $v(r,t),o=A(this.deps,e,"dataops:cleanup:scan:response",{...n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} objects=${n.objects.length}`)}catch(r){P(this.deps,"dataops:cleanup:scan","dataops:error",e,r)}}async handleExport(e){let t=D(th,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:cleanup:export"),n=await au(r,t.objectApiName,t.recommendation,1e3),o=await Vr(r,n.object.name,n.object.fields.map(l=>l.name),n.ids),i=new Date().toISOString(),a={sandforgeCleanupVersion:1,orgId:t.orgId,objectApiName:n.object.name,recommendation:t.recommendation,exportedAt:i,recommended:n.total,records:o},d=await this.saveDialog.save(`sandforge-cleanup-${n.object.name}-${Fv(t.recommendation)}.json`,JSON.stringify(a,null,2),["json"]),c=A(this.deps,e,"dataops:cleanup:export:response",{objectApiName:t.objectApiName,records:o.length,truncated:n.truncated,saved:d});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id} ${d.status} records=${o.length}`)}catch(r){P(this.deps,"dataops:cleanup:export","dataops:error",e,r)}}async handleDelete(e){let t=D(rh,e,"dataops:error",this.deps);if(!t)return;let{orgId:r,recommendation:n,dryRun:o}=t;try{let i=await this.session(r,"dataops:cleanup:delete"),a=await au(i,t.objectApiName,n,1e3),{object:d,ids:c}=a;if(d.deletable!==!0)throw new Error(`The connected user may not delete ${d.label} records.`);if(o){let k=await Si(i,d,c,await vi(i)),S={objectApiName:d.name,label:d.label,records:c.length,related:k.related,uncounted:k.uncounted},E=A(this.deps,e,"dataops:cleanup:delete:response",{objectApiName:t.objectApiName,dryRun:o,plan:S,truncated:a.truncated,written:od([S])});this.deps.broker.postToWebview(E),this.deps.log(`[TX] ${E.type} id=${E.id} plan records=${c.length}`);return}if(c.length===0)throw new Error(`No ${d.label} record is left to delete for this recommendation.`);let l=await B(r,this.deps.orgRegistry,this.deps.orgManager),u=Re(this.deps.orgManager.getOrg(r),r),p=this.targetAutomation,g=ji(t),h=await Dr({act:"cleanup",target:u,objects:[{objectApiName:d.name,records:c.length}],org:ao(l,k=>new ge(pE).withTimeout("dataops automation",()=>p.read(r,k)),Ee(this.deps.orgManager.getOrg(r))==="production"),accord:t,mayMute:!0,muteLeases:this.muteLeases,...g?{voice:g}:{}}),f=Zr(h.answer);if(f){P(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(f.message),{code:f.code,...Ni(f)});return}let m=await Pn(h,e.id,t.acceptEmails===!0,g);if("refused"in m){P(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(m.refused.message),{code:m.refused.code});return}let y=m.held,w={},v=async()=>{if(!(!y||w.back)){w.back=await y.release();for(let k of _t(w.back,u))this.deps.log(`[INFO] ${k}`)}},R={objectApiName:d.name,label:d.label,records:c.length},b=await nd(this.deps,{orgId:r,operation:"delete",objectNames:[d.name],recordCount:c.length,action:"cleanup_delete",description:`Delete ${c.length} ${d.name} record(s): ${Fv(n)}`,origin:"dataops:cleanup:delete",run:async(k,S)=>{let E=await ki(i,d.name,c,S);return k(d.name,E),[{objectApiName:d.name,counts:E}]},beforeEnd:v},this.liveTracker).finally(v);if(!b.ran){P(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(b.message),b.code?{code:b.code}:void 0);return}if(b.error!==void 0){P(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(b.error),b.cancelled?{code:Ze}:void 0);return}let O=A(this.deps,e,"dataops:cleanup:delete:response",{objectApiName:t.objectApiName,dryRun:o,plan:R,truncated:a.truncated,outcome:b.outcome,...y?{mutedAutomation:w.back??y.outcome}:{}});this.deps.broker.postToWebview(O),this.deps.log(`[TX] ${O.type} id=${O.id} ${b.outcome.status} deleted=${b.outcome.done} failed=${b.outcome.failed}`)}catch(i){P(this.deps,"dataops:cleanup:delete","dataops:error",e,i)}}};import{join as bP}from"node:path";async function _v(s){let{permissions:e,objects:t}=s;if(e.viewAllData&&e.modifyAllData)return{kind:"org"};let r={kind:"perObject",viewAllData:e.viewAllData,modifyAllData:e.modifyAllData},n=await s.grants();if("unread"in n)return{...r,unseen:t.map(u=>({objectApiName:u,reason:"permissionsUnread",detail:n.unread}))};let o=await s.describe(t),i={grants:n.grants,describes:o,...s.customSettings?{customSettings:s.customSettings}:{}},a=Ly(t,i),d=a.length>0?[...o,...await s.describe(a)]:o,c=Fy(t,{...i,describes:d}),l=[];for(let[u,p]of c)"access"in p||l.push({objectApiName:u,reason:p.reason,...p.detail!==void 0?{detail:p.detail}:{}});return{...r,unseen:l}}function Uv(s,e){if(e.kind==="org")return[];let t=new Set(s.kind==="org"?[]:s.unseen.map(r=>r.objectApiName));return e.unseen.map(r=>r.objectApiName).filter(r=>!t.has(r))}var dd="No record was read or deleted.",fE="Nothing was deleted.";function As(s,e){return{allowed:!1,refusal:{code:"PRODUCTION",message:`${s} is a production org, or cannot be told from one: ${e}. Emptying is for sandboxes, scratch orgs and Developer Edition orgs: SandForge never empties objects of a production org, and nothing lifts this. ${dd}`}}}async function Nn(s,e){let{orgName:t,registered:r}=e;if(r===void 0)return As(t,"SandForge has no record of what kind of org it is");if(!Yn(r))return As(t,"SandForge has it registered as a production org");let n;try{n=await Qn(s)}catch(i){return As(t,`it did not say what org it is (${T(i)})`)}if(yg(n))return As(t,n.edition?`its Organization record says IsSandbox false, edition ${n.edition}`:"its Organization record says IsSandbox false, and no edition");let o=Ee(r);return o==="production"?As(t,"SandForge has it registered as a production org"):o==="staging"&&e.mode==="org"?{allowed:!1,refusal:{code:"STAGING_ORG",message:`${t} is a sandbox marked Staging: it holds real data, and SandForge never empties the whole of it. Pick the objects to empty instead, which Production Guard asks about, or unmark it in Org Manager if it holds nobody's work. ${dd}`}}:{allowed:!0,org:n,tier:o}}var Hv=["PermissionsViewAllData","PermissionsModifyAllData","PermissionsBulkApiHardDelete"];async function Ts(s){let e=async n=>(await s.query(`SELECT ${n.join(", ")} FROM UserPermissionAccess`)).records[0]??{},t,r;try{t=await e(Hv)}catch(n){try{t=await e(Hv.slice(0,2)),r=`whether the user has Bulk API Hard Delete could not be read: ${T(n)}`}catch(o){return{viewAllData:!1,modifyAllData:!1,hardDelete:!1,unread:T(o)}}}return{viewAllData:t.PermissionsViewAllData===!0,modifyAllData:t.PermissionsModifyAllData===!0,hardDelete:t.PermissionsBulkApiHardDelete===!0,...r!==void 0?{unread:r}:{}}}function du(s){return{code:"HARD_DELETE_NOT_PERMITTED",message:"Deleting for good needs Bulk API Hard Delete, and the user SandForge deletes as "+(s.unread!==void 0?`could not be read to have it (${s.unread}). `:"doesn't have it: Salesforce refuses the job as it is opened. ")+"Give the user a permission set with Bulk API Hard Delete, or empty to the recycle bin, which Undo brings back. Nothing was deleted."}}var cu=60*6e4,Bv=2e3,qv=/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/;async function lu(s,e,t,r){let n=t.filter(l=>qv.test(l)).map(l=>l.slice(0,15)),o=n.length>0?` AND LastModifiedById NOT IN (${n.map(l=>`'${l}'`).join(", ")})`:"",i=new Map,a=[],d=!1;for(let l of e){let u=He(l);try{let p=await s.query(`SELECT LastModifiedById, LastModifiedDate FROM ${u} WHERE LastModifiedDate >= ${r}${o} LIMIT ${Bv}`);p.records.length>=Bv&&(d=!0);for(let g of p.records){let{LastModifiedById:h,LastModifiedDate:f}=g;if(typeof h!="string"||!qv.test(h))continue;let m=h.slice(0,15),y=typeof f=="string"&&!Number.isNaN(Date.parse(f))?f:"",w=i.get(m);if(!w){i.set(m,{userId:h,records:1,lastChangedAt:y});continue}w.records+=1,y!==""&&(w.lastChangedAt===""||Date.parse(y)>Date.parse(w.lastChangedAt))&&(w.lastChangedAt=y)}}catch(p){a.push(`${l}: ${T(p)}`)}}let c=[...i.keys()].sort();return{people:c.map(l=>i.get(l).userId),...d?{atLeast:!0}:{},who:c.map(l=>i.get(l)),unread:a}}var hE=200;async function Wv(s,e){let t=e.who.map(o=>o.userId).slice(0,hE);if(t.length===0)return e;let r;try{r=(await s.query(`SELECT Id, Name FROM User WHERE Id IN (${t.map(o=>`'${o}'`).join(", ")})`)).records}catch{return e}let n=new Map;for(let o of r){let{Id:i,Name:a}=o;typeof i=="string"&&typeof a=="string"&&a.trim()!==""&&n.set(i.slice(0,15),a.trim())}return{...e,who:e.who.map(o=>{let i=n.get(o.userId.slice(0,15));return i!==void 0?{...o,name:i}:o})}}function mE(s){let e;for(let t of s)t.lastChangedAt!==""&&(e===void 0||Date.parse(t.lastChangedAt)>Date.parse(e))&&(e=t.lastChangedAt);return e}function uu(s,e,t={}){if(t.accepted===!0)return;let r=new Set((t.accepted??[]).map(l=>l.slice(0,15))),n=e.people.filter(l=>!r.has(l.slice(0,15)));if(n.length===0)return;let o=n.length,i=`${e.atLeast?"At least ":""}${o} ${o===1?"person":"people"}`,a=mE(e.who.filter(l=>n.includes(l.userId))),d=r.size>0?" the preview did not name":"",c=t.voice==="page"?"or tick the box that lets their work go, to empty all the same":"or add --accept-people-active to empty all the same";return{code:"PEOPLE_ACTIVE",message:`${i}${d} other than the user SandForge deletes as changed records of these objects in ${s} in the last hour${a!==void 0?`, the last at ${a}`:""}: emptying them would take their work. Empty once they have stopped, ${c}. `+fE}}var yE=1e4,Gv={bulkDestroy:()=>Promise.reject(new Error("an estimate sends no job"))};function pu(s){return as(Gv,s,1,"hard")}var Jv=9,wE=25;function Vv(s,e,t){let r=e>0&&as(Gv,s,e,t);if(!r&&t==="hard"&&e>0)return{objectApiName:s,records:e,restCalls:0,jobs:[],toTheBin:!1,notSent:!0};if(!r)return{objectApiName:s,records:e,restCalls:Math.ceil(e/Dt),jobs:[],toTheBin:!0};let n=Math.ceil(e/is),o=Math.ceil(e/n),i=[];for(let a=e;a>0;a-=o)i.push(Math.min(a,o));return{objectApiName:s,records:e,restCalls:0,jobs:i,toTheBin:t==="recycle"}}function fr(s,e){return{apiRequests:s,seconds:s*e}}function Es(s){return s.reduce((e,t)=>({apiRequests:e.apiRequests+t.apiRequests,seconds:e.seconds+t.seconds}),{apiRequests:0,seconds:0})}function Xv(s){return Math.max(1,Math.ceil(s/wl))}function Kv(s){return s.notSent?{apiRequests:0,seconds:0}:Es([fr(Xv(s.records),Cn),fr(1,fs),fr(s.restCalls,Bi),...s.jobs.map(e=>({apiRequests:$m({stateReads:Fm(e)}),seconds:Lm(e)}))])}function bE(s){return s<=0?{apiRequests:0,seconds:0}:Es([fr(1,fs),fr(Math.ceil(s/wl),Cn),fr(Math.ceil(s/Dt),Bi),fr(Math.ceil(s/Dt),Cn)])}function RE(s){if(s<=0)return{apiRequests:0,seconds:0};let e=Math.ceil(s/Dt);return Es([fr(e,Bi),fr(e,Cn)])}var vE=.05,zv={check:2,connect:3};function cd(s,e,t,r=0){let n=t*zv.check+zv.connect,o=t*e+n+s.apiRequests+r,i=Math.ceil(o*vE);return{apiRequests:o+i,seconds:e*fs+s.seconds,requests:{reads:e,readings:t,passes:s.apiRequests,margin:i,connecting:n,...r>0?{mute:r}:{}}}}function Yv(s){let e=s.passes.map(({objectApiName:d,records:c})=>Vv(d,Math.max(0,c),s.mode)),t=Es([bE(s.toDraft),fr(s.draftReads??0,Cn),...e.map(Kv),...(s.refused??[]).map(RE)]),r=cd(t,Math.max(0,s.reads),s.readings??2),n=e.reduce((d,c)=>d+c.jobs.reduce((l,u)=>l+Math.ceil(u/yE),0),0),o=s.mode==="recycle"?Math.max(0,s.deleted):e.filter(d=>d.toTheBin).reduce((d,c)=>d+c.records,0),i=s.dataStorageMB===void 0?void 0:s.dataStorageMB*wE,a=e.some(d=>d.jobs.length>0);return{...r,bulkBatches:n,passes:e,binRecords:o,...i===void 0?{}:{bin:{documentedCapacity:i,past:o>i}},api:en(r.apiRequests,s.apiBudget),...a?{batches:s.bulkBatches?en(n,s.bulkBatches):{verdict:"unread",estimate:n,unread:"the limits the org answered list no DailyBulkApiBatches"}}:{}}}function Qv(s,e,t,r=0){let n=Es(e.map(o=>{let i=Vv(o.objectApiName,Math.max(0,o.records),s),a=Kv(i);if(!o.idsRead||i.notSent)return a;let d=Xv(i.records);return{apiRequests:a.apiRequests-d,seconds:a.seconds-d*Cn}}));return cd(n,Math.max(0,t),1,Math.max(0,r)).apiRequests}var gu=3;function Zv(s,e,t=0){return cd({apiRequests:Math.max(0,s),seconds:0},Math.max(0,e),1,Math.max(0,t)).apiRequests}function eS(s,e,t,r=0){let n={apiRequests:s.requests.passes,seconds:s.seconds-s.requests.reads*fs},o=cd(n,Math.max(0,e),t,Math.max(0,r)),i=s.api.verdict==="unread"?{unread:s.api.unread}:{max:s.api.max,remaining:s.api.remaining};return{...s,...o,api:en(o.apiRequests,i)}}var SE=$y.extend({relationshipName:L().nullish(),polymorphicForeignKey:ze().optional()}),tS=_i.extend({deletable:ze().optional(),fields:ke(SE)});function fu(s){return fw.has(s)}var rS={pricebook2:{field:"IsStandard",value:!0}};function nS(s){let e=rS[s.toLowerCase()];return e?`${e.field} = ${String(e.value)}`:void 0}function $n(s){let e=rS[s.toLowerCase()];return e?`${e.field} = ${String(!e.value)}`:void 0}var kE=new Set(["pricebook2","product2"]);function oS(s,e){return e!==void 0&&s.childSObject!==void 0&&s.field!==void 0&&Ny(s.childSObject,s.field,e)?"restricted":s.cascadeDelete===!0?"cascade":s.restrictedDelete===!0?"restricted":"lookup"}function hu(s,e=t=>t){let t=[];for(let[r,n]of s)for(let o of n.childRelationships??[]){let i=e(o.childSObject),a=s.get(i)?ld(s,i,o.field):void 0;sS(a,r)||t.push({parent:r,child:e(o.childSObject),field:o.field,kind:oS(o,r)})}return t}var Ps=5,OE=8;function sS(s,e){if(s?.polymorphicForeignKey===!0)return!1;let t=s?.referenceTo??[];return t.length>0&&!t.some(r=>r.toLowerCase()===e.toLowerCase())}function IE(s,e,t){let r=ld(s,e,t);return(r?.referenceTo?.length??0)>1||r?.polymorphicForeignKey===!0}function mu(s,e,t){let r=new Map;for(let h of[...e,...s,...t.keys()])r.set(h.toLowerCase(),h);let n=h=>r.get(h.toLowerCase())??h,o=h=>t.get(h)??t.get(n(h)),i=new Set(s.map(h=>h.toLowerCase())),a=new Set([...e,...s].map(h=>h.toLowerCase())),d=new Map,c=new Map,l=new Set,u=(h,f)=>{let m=c.get(h)??new Set;m.add(f),c.set(h,m)},p=s.map(h=>({top:h,from:h,above:[]}));for(;p.length>0;){let h=[];for(let{top:f,from:m,above:y}of p){let w=o(m);if(!w){l.add(m);continue}for(let v of w.childRelationships??[]){if(oS(v,m)!=="cascade")continue;let R=n(v.childSObject),O=o(R)?.fields.find(I=>I.name.toLowerCase()===v.field.toLowerCase());if(sS(O,m))continue;let k=R.toLowerCase();if(!a.has(k)||k===m.toLowerCase()||y.some(I=>I.object.toLowerCase()===k))continue;let S=[{object:R,field:v.field,parent:m},...y],E=d.get(R)??[];if(S.length>1&&E.length>=OE){u(R,m);continue}d.set(R,[...E,{object:R,steps:S,emptied:f}]),!(i.has(k)||S.length>=Ps)&&h.push({top:f,from:R,above:S})}}p=h}for(let h=!0;h;){h=!1;for(let[f,m]of d)for(let y of m)for(let[w,v]of y.steps.entries())w===0||!c.has(v.object)||y.steps.slice(0,w).some(b=>IE(t,b.object,b.field))||c.get(f)?.has(v.object)||(u(f,v.object),h=!0)}let g=[...d.keys()].filter(h=>!i.has(h.toLowerCase())).sort();return{emptied:new Set(s),routes:d,along:g,routesCut:new Map([...c].map(([h,f])=>[h,[...f].sort()])),undescribed:[...l].filter(h=>!i.has(h.toLowerCase())).sort()}}function Io(s,e){let t=new Set,r=new Set,n=o=>{if(!r.has(o)){r.add(o),e.emptied.has(o)&&t.add(o);for(let i of e.routes.get(o)??[])n(i.emptied)}};return n(s),t}function AE(s,e,t){if(t===void 0)return s;if(t==="unnamed")return{...s,exact:!1};if(t.length===0)return s;let r=t.map(n=>`'${n}'`).join(", ");return{soql:`${s.soql} AND ${e} NOT IN (${r})`,exact:s.exact}}function ld(s,e,t){let r=t.toLowerCase();return s.get(e)?.fields.find(n=>n.name.toLowerCase()===r)}function ud(s,e,t=$n,r=()=>{}){let n=[],o=(i,a,d,c)=>AE({soql:i,exact:a},d,r(c));for(let[i,a]of s.entries()){if(!e.has(a.object)){let h=[...n,a.field].join(".");return o(`${h} != null`,!1,h,a.parent)}let d=ld(e,a.object,a.field);if(!d){if(i===0)return;let h=s[i-1],f=[...n.slice(0,-1),h.field].join(".");return o(`${f} != null`,!1,f,h.parent)}let c=(d.referenceTo?.length??0)>1||d.polymorphicForeignKey===!0,l=d.relationshipName??void 0,u=i===s.length-1,p=l?[...n,l].join("."):void 0,g=[...n,d.name].join(".");if(c)return p?o(`${p}.Type = '${a.parent}'`,u,g,a.parent):o(`${g} != null`,!1,g,a.parent);if(u){let h=t(a.parent);if(h===void 0&&!kE.has(a.parent.toLowerCase()))return o(`${g} != null`,!0,g,a.parent);if(!p)return o(`${g} != null`,!1,g,a.parent);let f=h!==void 0?` AND ${p}.${h}`:"";return o(`${p}.Id != null${f}`,!0,g,a.parent)}if(!l||i+1>=Ps)return o(`${g} != null`,!1,g,a.parent);n.push(l)}}function iS(s,e,t){let r=[];for(let[n,o]of s.entries()){let i=e.has(o.object)?ld(e,o.object,o.field):void 0;if(!i)return;let a=[...r,i.name].join(".");if(n===s.length-1)return`${a} IN (${t.map(c=>`'${c}'`).join(", ")})`;if((i.referenceTo?.length??0)>1||i.polymorphicForeignKey===!0||!i.relationshipName||n+1>=Ps)return;r.push(i.relationshipName)}}function Cs(s,e,t=$n,r){let n=s.map(a=>ud(a.steps,e,t,r)).filter(a=>a!==void 0);if(n.length===0)return;if(n.length===1)return n[0];let o=n.every(a=>a.exact)&&n.length===s.length,i=[...new Set(n.map(a=>a.soql))];return i.length===1?{soql:i[0],exact:o}:{soql:i.map(a=>`(${a})`).join(" OR "),exact:o}}function aS(s,e,t,r,n,o=$n,i){let a={object:s,field:e,parent:t};if(r.emptied.has(t))return ud([a],n,o,i);let d=(r.routes.get(t)??[]).map(c=>({object:s,steps:[a,...c.steps],emptied:c.emptied}));return Cs(d,n,o,i)}var lS=4,dS=100,TE=/^[A-Za-z0-9]+$/;function cS(s,e){let t=$n(s);if(t!==void 0)return t;if(e&&s.toLowerCase()===tr.toLowerCase())return`${gs} = false`}var Un="stopped before the org was asked";function uS(s,e,t="COUNT()"){let r=fu(s),n=[...e,...r?["IsDeleted = false"]:[]],o=n.length===0?"":` WHERE ${n.map(i=>n.length>1?`(${i})`:i).join(" AND ")}`;return{soql:`SELECT ${t} FROM ${He(s)}${o}`,all:r}}var _n=class{statements=new Map;answers=new Map;ask(e,t){let r=uS(e,t.map(i=>typeof i=="string"?i:i.soql)),n=t.some(i=>typeof i!="string"&&!i.exact),o=this.statements.get(r.soql);return this.statements.set(r.soql,{...r,atMost:n||o?.atMost===!0}),r.soql}get size(){return this.statements.size}async run(e,t){let r=!1;return await ss([...this.statements].map(([n,{soql:o,all:i,atMost:a}])=>async()=>{if(t()){r=!0,this.answers.set(n,{unread:Un});return}try{let d=await(i?e.countAll(o):e.count(o));this.answers.set(n,{records:d,...a?{atMost:!0}:{}})}catch(d){this.answers.set(n,{unread:T(d)})}}),lS),r}answer(e){return this.answers.get(e)??{unread:Un}}},fd=class{statements=new Map;answers=new Map;ask(e,t){let r=uS(e,t,"Id");return this.statements.set(r.soql,r.all),r.soql}get size(){return this.statements.size}async run(e,t){let r=!1;return await ss([...this.statements].map(([n,o])=>async()=>{if(t()){r=!0,this.answers.set(n,{counted:{unread:Un}});return}try{let i=await e.readIds(n,o),a=i.ids.filter(d=>TE.test(d));this.answers.set(n,{counted:{records:i.totalSize},...a.length===i.totalSize?{ids:a}:{}})}catch(i){this.answers.set(n,{counted:{unread:T(i)}})}}),lS),r}answer(e){return this.answers.get(e)??{counted:{unread:Un}}}};function bu(s,e){return s.records===void 0?s:e.records===void 0?{unread:e.unread??Un}:{records:Math.max(0,s.records-e.records),...e.atMost?{atLeast:!0}:{}}}function yu(s,e){return s.records===void 0?s:e.records===void 0?{...s,atMost:!0}:{...s,records:Math.max(0,s.records-e.records),...e.atMost?{atLeast:!0}:{},...e.atLeast?{atMost:!0}:{}}}function un(s){return s.records===0&&s.atLeast!==!0}function Ln(s){return s===void 0||s.records===void 0||s.records>0}function gd(s){return{unread:`${s}: the lookup its records go by is hidden from the user`}}function Ru(s){return s.records===void 0?s:{...s,atLeast:!0}}function Ds(s){return s.records===void 0?s:{...s,atMost:!0}}function wu(s,e){let t=e.key?s.answer(e.key):gd(e.objectApiName),r=e.going?bu(t,s.answer(e.going)):t,n=(r.records??0)>0;return e.more&&n&&(r={...r,atLeast:!0}),e.under&&n&&(r=Ru(r)),e.over&&n&&(r=Ds(r)),r}function vu(s,e){return s.every(t=>e.get(t.emptied)!=="unnamed"&&t.steps.every(r=>e.get(r.parent)!=="unnamed"))}function EE(s){let e=r=>typeof r=="string"?r:r.soql,t=[...new Set(s.map(r=>r.length===1?e(r[0]):r.map(n=>`(${e(n)})`).join(" AND ")))];return{soql:t.length===1?t[0]:t.map(r=>`(${r})`).join(" OR "),exact:s.every(r=>r.every(n=>typeof n=="string"||n.exact))}}function Fn(s){let e=s.filter(n=>n.records!==void 0);if(e.length===0)return s.length===0?{records:0}:{unread:s[0].unread??Un};let t=s.some(n=>n.records===void 0||n.atLeast),r=s.some(n=>n.atMost);return{records:e.reduce((n,o)=>n+(o.records??0),0),...r?{atMost:!0}:{},...t?{atLeast:!0}:{}}}var pd="Pricebook2";function PE(s){let e=new Map,t=r=>r.records.records??Number.POSITIVE_INFINITY;for(let r of s){let n=[r.objectApiName,r.field??"",r.parent??""].join("\0"),o=e.get(n);(!o||t(r)>t(o))&&e.set(n,r)}return[...e.values()]}async function pS(s,e,t=()=>!1,r={undo:!0}){let{affected:n,order:o,relations:i,describes:a}=s,d=o.passes.map(M=>M.objectApiName),c=a.get(tr)?.fields.some(M=>M.name===gs)===!0,l=M=>{let N=cS(M,c);if(!(M.toLowerCase()===tr.toLowerCase()&&n.emptied.has(Zn)))return N},u=M=>{let N=l(M);return N===void 0?[]:[N]},p=new Map,g=M=>p.get(M),h=M=>g(M),f=M=>ud(M,a,l,h),m=M=>Cs(M,a,l,h),y=(M,N,U)=>aS(M,N,U,n,a,l,h),w=new _n,v=new Map;for(let M of d)v.set(M,w.ask(M,u(M)));let R=await w.run(e,t),b=new Map(d.map(M=>[M,w.answer(v.get(M)??"")])),O=M=>[...Io(M,n)].some(N=>Ln(b.get(N))),k=M=>M.filter(N=>Ln(b.get(N.emptied))),S=M=>!n.emptied.has(M)&&n.routesCut.has(M),E=new _n,I=[];for(let{parent:M,child:N,field:U,kind:W}of i){if(W!=="restricted"||N===M||n.emptied.has(N)||!O(M))continue;let ae=y(N,U,M),q=n.routes.has(N)?m(k(n.routes.get(N)??[])):void 0;I.push({objectApiName:N,field:U,parent:M,...ae?{key:E.ask(N,[ae])}:{},...ae&&q?{going:E.ask(N,[q,ae])}:{},...q&&S(N)?{over:!0}:{},...n.emptied.has(M)&&!n.routes.has(N)?{naming:""}:{}})}for(let{child:M,field:N,parent:U,rows:W}of yl){if(W===void 0||!O(U)||n.emptied.has(M)||!n.routes.has(M))continue;let q=a.get(M)?.fields.some(Fe=>Fe.name===W.field)===!0?y(M,N,U):void 0;if(!q)continue;let he=`${W.field} = ${String(W.value)}`;I.push({objectApiName:M,field:N,parent:U,key:E.ask(M,[he,q]),along:!0,...n.emptied.has(U)?{naming:he}:{}})}R=await E.run(e,t)||R;let C=new fd,F=new Map,Y=new Map;I.forEach((M,N)=>{if(M.naming===void 0||M.key===void 0||(wu(E,M).records??0)===0)return;let U=`Id IN (SELECT ${He(M.field)} FROM ${He(M.objectApiName)}${M.naming!==""?` WHERE ${M.naming}`:""})`;F.set(N,C.ask(M.parent,[...u(M.parent),U])),Y.set(M.parent,[...Y.get(M.parent)??[],U])}),R=await C.run(e,t)||R;for(let M of Y.keys()){let N=[...F].filter(([W])=>I[W].parent===M).map(([,W])=>C.answer(W));if(N.every(W=>W.counted.records===0))continue;let U=new Set(N.flatMap(W=>W.ids??[]));p.set(M,N.every(W=>W.ids!==void 0)&&U.size<=dS?[...U]:"unnamed")}let z=M=>{let N={archived:new Map,kept:new Map,goneBefore:new Map,along:new Map,refusals:[],undoLost:[]};for(let q of o.passes){let he=q.objectApiName;if(!Ln(b.get(he)))continue;let Fe=u(he);fu(he)&&N.archived.set(he,M.ask(he,[...Fe,"IsArchived = true"]));let Te=nS(he);Te!==void 0&&N.kept.set(he,M.ask(he,[Te]));let de=k(q.goneBefore);if(de.length>0){let Ce=m(de);N.goneBefore.set(he,Ce?{key:M.ask(he,[...Fe,Ce]),unreadable:!1}:{unreadable:!0})}let be=r.undo?k(q.sentBeforeTheirParent):[];for(let Ce of be){let tt=f(Ce.steps),_e=Ce.steps[0],Ue=tt?[...Fe,tt]:void 0;N.undoLost.push({objectApiName:he,field:_e.field,parent:_e.parent,reason:"unordered",...Ue?{key:M.ask(he,Ue),conditions:Ue}:{}})}}for(let q of n.along){let he=k(n.routes.get(q)??[]);if(he.length===0)continue;let Fe=he.map(de=>{let be=f(de.steps);return{route:de,...be?{key:M.ask(q,[be])}:{}}}),Te=he.length>1?m(he):void 0;N.along.set(q,{...Te?{total:M.ask(q,[Te])}:Fe[0].key?{total:Fe[0].key}:{},via:Fe})}let U=q=>o.passes.findIndex(he=>he.objectApiName===q);for(let q of r.undo?o.beforeParent:[]){if(q.reason==="customPrices"){if(!O(pd)||!O(q.parent)||U(pd)>U(q.parent))continue;let de=y(q.objectApiName,"Pricebook2Id",pd),be=y(q.objectApiName,q.field,q.parent),Ce=de&&be?[de,be]:void 0;N.undoLost.push({objectApiName:q.objectApiName,field:q.field,parent:q.parent,reason:"restricted",...Ce?{key:M.ask(q.objectApiName,Ce),conditions:Ce}:{},...S(pd)||S(q.parent)?{under:!0}:{}});continue}if(!O(q.objectApiName)||!O(q.parent))continue;let he=y(q.objectApiName,q.field,q.parent),Fe=[];if(!n.emptied.has(q.objectApiName)){let de=m(k(n.routes.get(q.objectApiName)??[]));de&&Fe.push(de)}let Te=S(q.objectApiName)||S(q.parent);N.undoLost.push({objectApiName:q.objectApiName,field:q.field,parent:q.parent,reason:"restricted",...he?{key:M.ask(q.objectApiName,[...Fe,he]),conditions:[...Fe,he]}:{},...Te?{under:!0}:{}})}for(let{child:q,field:he,parent:Fe,rows:Te}of yl){if(Te===void 0||!O(Fe)||!n.emptied.has(q))continue;let be=a.get(q)?.fields.some(tt=>tt.name===Te.field)===!0?y(q,he,Fe):void 0;if(!be||!r.undo||!Ln(b.get(q)))continue;let Ce=`${Te.field} = ${String(Te.value)}`;N.undoLost.push({objectApiName:q,field:he,parent:Fe,reason:"restricted",key:M.ask(q,[Ce,be]),conditions:[Ce,be],more:!0})}let W=(q,he,Fe,Te=!1)=>{N.refusals.push({code:q,objectApiName:he,key:M.ask(he,Fe),...Te?{under:!0}:{}})};for(let q of o.toDraft){if(!O(q))continue;let he="StatusCode != 'Draft'";if(n.emptied.has(q)){W("activatedOrder",q,[he]);continue}let Fe=k(n.routes.get(q)??[]),Te=m(Fe);W(vu(Fe,p)?"activatedOrder":"activatedOrderLeft",q,Te?[Te,he]:[{soql:he,exact:!1}],Te!==void 0&&S(q))}for(let[q,he]of N.kept)N.refusals.push({code:"standardPriceBook",objectApiName:q,key:he});n.emptied.has(ci)&&Ln(b.get(ci))&&(n.emptied.has(tr)||W("directContactRelation",ci,[{soql:"IsDirect = true",exact:!n.routes.has(tr)}]));let ae=a.get(tr);return n.emptied.has(tr)&&!n.emptied.has(Zn)&&Ln(b.get(tr))&&ae?.fields.some(q=>q.name===gs)===!0&&W("personAccountContact",tr,[`${gs} = true`]),N},te=new fd,H=new Map;if(p.size>0){let M=new Set;g=N=>(n.emptied.has(N)||M.add(N),p.get(N)),z(new _n),g=N=>p.get(N);for(let N of[...M].sort()){let U=k(n.routes.get(N)??[]),W=U.filter(he=>p.has(he.emptied));if(W.length===0)continue;let ae=p.get(W[0].emptied),q=U.length===1&&Array.isArray(ae)?iS(U[0].steps,a,ae):void 0;q===void 0?p.set(N,"unnamed"):H.set(N,te.ask(N,[q]))}R=await te.run(e,t)||R;for(let[N,U]of H){let W=te.answer(U);p.set(N,W.ids!==void 0&&W.ids.length<=dS?W.ids:"unnamed")}}let x=new _n,j=z(x);R=await x.run(e,t)||R;let K=M=>wu(x,M),Q=new _n,_=new Map;for(let[M,N]of Y)N.length===2&&p.get(M)==="unnamed"&&_.set(M,Q.ask(M,[...u(M),...N]));let V=new Map,ue=new Map;for(let M of j.undoLost)ue.set(M.objectApiName,[...ue.get(M.objectApiName)??[],M]);for(let[M,N]of ue){let U=N.filter(ae=>!un(K(ae)));if(U.length<2)continue;let W=U.map(ae=>ae.conditions);W.some(ae=>ae===void 0)||V.set(M,Q.ask(M,[EE(W)]))}R=await Q.run(e,t)||R;let me=I.map((M,N)=>{let U=F.get(N);return{objectApiName:M.objectApiName,field:M.field,parent:M.parent,records:wu(E,M),...U!==void 0?{keeps:C.answer(U).counted}:{}}}).filter(M=>!un(M.records)),re=M=>{let N=me.flatMap(q=>q.parent===M&&q.keeps!==void 0?[q.keeps]:[]);if(N.length===0)return;let U=p.get(M);if(Array.isArray(U))return{records:U.length};let W=Fn(N),ae=_.get(M);return ae!==void 0?yu(W,Q.answer(ae)):N.length>1&&(W.records??0)>0?Ds(W):W},ie=me.filter(M=>!Array.isArray(p.get(M.parent))&&I.some(N=>N.along===!0&&N.objectApiName===M.objectApiName&&N.field===M.field&&N.parent===M.parent)),Be=me.filter(M=>I.some(N=>N.along===!0&&N.objectApiName===M.objectApiName&&N.field===M.field&&N.parent===M.parent)),fe=o.passes.map(M=>{let N=M.objectApiName,U=cS(N,c),W=b.get(N)??{unread:Un};if(!Ln(W))return{objectApiName:N,...U!==void 0?{rows:U}:{},records:W,sent:W};let ae=j.goneBefore.get(N),q=ae===void 0?W:ae.unreadable||ae.key===void 0?gd(N):n.routesCut.has(N)?Ds(bu(W,x.answer(ae.key))):bu(W,x.answer(ae.key)),he=j.archived.get(N),Fe=j.kept.get(N),Te=re(N);return{objectApiName:N,...U!==void 0?{rows:U}:{},records:W,sent:q,...he?{archived:x.answer(he)}:{},...Fe?{kept:x.answer(Fe)}:{},...Te&&!un(Te)?{blocked:Te}:{}}}),ne=r.undo?fe.filter(M=>a.get(M.objectApiName)?.undeletable===!1&&!un(M.sent)).map(M=>({objectApiName:M.objectApiName,reason:"notRestorable",records:M.sent})):[],ce=[...j.along].map(([M,{total:N,via:U}])=>{let W=N?x.answer(N):gd(M),ae=n.routesCut.get(M),q=ie.filter(be=>be.objectApiName===M),he=Be.filter(be=>be.objectApiName===M),Fe=q.length>0?Fn(q.map(be=>be.records)):void 0,Te=he.length>0?Fn(he.map(be=>be.records)):void 0,de=Fe?yu(W,Fe):W;return{objectApiName:M,records:ae?Ru(de):de,via:U.map(({route:be,key:Ce})=>{let tt=Ce?x.answer(Ce):gd(M),_e=be.steps[0],Ue=q.filter(lt=>lt.field===_e.field&&lt.parent===_e.parent);return{field:_e.field,parent:_e.parent,emptied:be.emptied,records:Ue.length>0?yu(tt,Fn(Ue.map(lt=>lt.records))):tt}}).filter(be=>!un(be.records)),...Te&&!un(Te)?{blocking:Te}:{},...ae?{routesNotRead:[...ae]}:{}}}).filter(M=>!un(M.records)),we=(M,N)=>M.map(U=>({...N(U),records:K(U)})).filter(U=>!un(U.records)),le=PE([...we(j.undoLost,M=>({objectApiName:M.objectApiName,...M.field!==void 0?{field:M.field}:{},...M.parent!==void 0?{parent:M.parent}:{},reason:M.reason})),...ne]),Se=new Map;for(let M of le)Se.set(M.objectApiName,[...Se.get(M.objectApiName)??[],M]);let je=Fn([...Se].map(([M,N])=>{let U=V.get(M),W=N.filter(q=>q.reason==="notRestorable");if(U===void 0){let q=Fn(N.map(he=>he.records));return N.length>1&&(q.records??0)>0?Ds(q):q}let ae=Q.answer(U);return N.some(q=>q.reason!=="notRestorable"&&q.records.atLeast)&&(ae.records??0)>0&&(ae=Ru(ae)),W.length>0?Ds(Fn([ae,...W.map(q=>q.records)])):ae}));return{objects:fe,along:ce,refusals:we(j.refusals,M=>({code:M.code,objectApiName:M.objectApiName})),blockers:me,undoLost:le,undoLostRecords:je,kept:p,statements:w.size+E.size+C.size+te.size+x.size+Q.size,...R?{stopped:!0}:{}}}var hS={lookup:0,cascade:1,restricted:2,customPrices:2},gS="Pricebook2",Su="Product2",fS="PricebookEntry";function CE(s,e){let t=[],r=[],n=o=>s.emptied.has(o)||s.routes.has(o);for(let o of s.emptied)for(let i of Io(o,s))i!==o&&t.push({first:i,then:o,reason:"cascade"});for(let{parent:o,child:i,field:a,kind:d}of e){if(i===o||!n(i)||!n(o))continue;if(d==="lookup"){s.emptied.has(i)&&s.emptied.has(o)&&t.push({first:i,then:o,reason:"lookup"});continue}if(d!=="restricted")continue;let c=Io(i,s),l=s.emptied.has(i)?[i]:[...c],u=!1;for(let p of Io(o,s))if(!c.has(p))for(let g of l)g!==p&&(t.push({first:g,then:p,reason:"restricted"}),u=!0);u&&r.push({objectApiName:i,field:a,parent:o,reason:"restricted"})}return s.emptied.has(gS)&&s.emptied.has(Su)&&(t.push({first:gS,then:Su,reason:"customPrices"}),n(fS)&&r.push({objectApiName:fS,field:"Product2Id",parent:Su,reason:"customPrices"})),{constraints:t,beforeParent:r}}function DE(s){return Object.hasOwn(hS,s)}function mS(s,e){let{constraints:t,beforeParent:r}=CE(s,e),n=[...s.emptied].sort(),o=new Map(n.map(u=>[u,[]]));for(let{first:u,then:p,reason:g}of t)g==="cascade"?o.get(u)?.push({childSObject:p,field:g,cascadeDelete:!0}):o.get(p)?.push({childSObject:u,field:g});let i=new Map(n.map(u=>[u,{name:u,fields:[],childRelationships:o.get(u)??[]}])),a=qg(n,i,({field:u})=>{let p=DE(u)?u:"lookup";return{first:p==="cascade"?"parent":"child",firmness:hS[p]}}),d=new Map(a.map((u,p)=>[u,p])),c=(u,p)=>(d.get(u)??0)<(d.get(p)??0);return{passes:a.map(u=>{let p=s.routes.get(u)??[];return{objectApiName:u,goneBefore:p.filter(g=>c(g.emptied,u)),sentBeforeTheirParent:p.filter(g=>!c(g.emptied,u))}}),beforeParent:r,unordered:xE(t.filter(({first:u,then:p})=>!c(u,p))),toDraft:zt([...n,...s.along])}}function xE(s){let e=new Set;return s.filter(({first:t,then:r,reason:n})=>{let o=`${t}\0${r}\0${n}`;return e.has(o)?!1:(e.add(o),!0)})}function ME(s){switch(s){case"configuration":case"excludedByUser":case"notFound":case"chatter":case"history":case"sharing":case"changeEvent":case"unsupportedKind":case"customSetting":case"heldWithFiles":case"setup":case"platformCreated":case"metadata":return s;case"notCustomSetting":return"notFound";case"files":return"documents";case"notWritable":return"notDeletable"}}var jE=(s,e,t)=>{let r=mw(s,e,"empty",t.customSettings?{customSettings:Hg}:{});return{candidates:r.candidates,leftOut:r.leftOut.map(({objectApiName:n,reason:o,detail:i})=>({objectApiName:n,reason:ME(o),...i===void 0?{}:{detail:i}}))}},NE=new Set([_g,Ug].map(s=>s.toLowerCase()));function yS(s,e){return s.objectApiName<e.objectApiName?-1:s.objectApiName>e.objectApiName?1:0}function $E(s,e){if(s.customSetting===!0&&e.customSettings!==!0)return"customSetting";if(NE.has(s.name.toLowerCase())&&e.files!==!0)return"files";if(Bg(s.name)!==void 0&&e.managedPackages!==!0)return"managedPackage";if(s.undeletable===!1&&e.unrestorable!==!0)return"notRestorable"}function hd(s,e,t,r=jE){let n=r(s,e,{customSettings:!0}),o=new Map(s.map(u=>[u.name.toLowerCase(),u])),i=new Set(n.candidates.map(u=>u.toLowerCase())),a=new Map(n.leftOut.map(u=>[u.objectApiName.toLowerCase(),u])),d=[],c=[],l=u=>{let p=a.get(u.name.toLowerCase());return p?{...p,objectApiName:u.name}:{objectApiName:u.name,reason:"notDeletable"}};if(t.mode==="objects"){let u=new Set;for(let p of t.objects??[]){let g=p.toLowerCase();if(u.has(g))continue;u.add(g);let h=o.get(g);h?i.has(g)?d.push(h.name):c.push(l(h)):c.push({objectApiName:p,reason:"notFound"})}}else{let u=new Set((t.excluded??[]).map(p=>p.toLowerCase()));for(let p of t.excluded??[])o.has(p.toLowerCase())||c.push({objectApiName:p,reason:"notFound"});for(let p of o.values()){let g=p.name.toLowerCase();if(u.has(g)){c.push({objectApiName:p.name,reason:"excludedByUser"});continue}if(!i.has(g)){c.push(l(p));continue}let h=$E(p,t);h===void 0?d.push(p.name):c.push({objectApiName:p.name,reason:h})}}return d.sort(),c.sort(yS),{mode:t.mode,objects:d,leftOut:c,worked:[...n.candidates].sort()}}function wS(s,e,t=new Map){let r=[],n=[...s.leftOut];for(let o of s.objects){let i=e.get(o);if(i)i.deletable===!1?n.push({objectApiName:o,reason:"notDeletable"}):i.fields.some(a=>a.name==="IsDeleted")?r.push(o):n.push({objectApiName:o,reason:"noRecycleBin"});else{let a=t.get(o);n.push({objectApiName:o,reason:"notDescribed",...a===void 0?{}:{detail:a}})}}return{...s,objects:r,leftOut:n.sort(yS)}}async function ku(s,e,t,r){await ss(e.map(n=>async()=>{try{t.set(n,tS.parse(await s.describe(n)))}catch(o){r.set(n,T(o))}}),6)}function FE(s,e){if(e!=="hard")return s;let t=s.objects.filter(r=>!pu(r));return t.length===0?s:{...s,objects:s.objects.filter(pu),leftOut:[...s.leftOut,...t.map(r=>({objectApiName:r,reason:"notForGood"}))].sort((r,n)=>r.objectApiName<n.objectApiName?-1:r.objectApiName>n.objectApiName?1:0)}}function Hn(s){return s.records}async function bS(s,e){let t=hd(s.global,s.tooling,s.request,s.rule),r=new Map,n=new Map;await ku(e,t.objects,r,n);let o=FE(wS(t,r,n),s.deleteMode),i=new Map([...t.worked,...s.global.map(S=>S.name)].map(S=>[S.toLowerCase(),S])),a=S=>i.get(S.toLowerCase())??S,d=mu(o.objects,t.worked,r);for(let S=0;S<Ps;S++){let E=d.undescribed.filter(I=>!r.has(I)&&!n.has(I));if(E.length===0)break;await ku(e,E,r,n),d=mu(o.objects,t.worked,r)}let c=S=>d.emptied.has(S)||d.routes.has(S),l=[...new Set(hu(r,a).filter(({kind:S,parent:E,child:I})=>S==="restricted"&&c(E)&&!c(I)).map(({child:S})=>S))].filter(S=>!r.has(S)&&!n.has(S));await ku(e,l,r,n);let u=hu(r,a),p=mS(d,u),g=await pS({affected:d,order:p,relations:u,describes:r},e,s.stopped,{undo:s.deleteMode==="recycle"}),h=[...g.objects.filter(S=>Hn(S.records)===void 0),...g.along.filter(S=>Hn(S.records)===void 0)].map(S=>S.objectApiName),f=[...g.objects.map(S=>Math.max(0,(Hn(S.records)??0)-(S.blocked?.records??0))),...g.along.map(S=>Hn(S.records)??0)].filter(S=>S>0),m=f.reduce((S,E)=>S+E,0),y=g.along.some(S=>S.records.atLeast===!0)||g.objects.some(S=>S.blocked?.atMost===!0),w=g.refusals.filter(S=>S.code==="activatedOrder").reduce((S,E)=>S+(Hn(E.records)??0),0),v=p.toDraft.filter(S=>!d.emptied.has(S)).map(S=>{let E=d.routes.get(S)??[];if(!vu(E,g.kept))return{objectApiName:S};let I=Cs(E,r,void 0,C=>g.kept.get(C));return{objectApiName:S,...I?{condition:I.soql}:{}}}),R=S=>S.records===void 0||S.records>0,b=g.objects.filter(S=>R(S.records)).length+g.along.filter(S=>R(S.records)).length,O=Jv+r.size+n.size+g.statements+2*b,k=Yv({mode:s.deleteMode,passes:g.objects.map(S=>({objectApiName:S.objectApiName,records:Hn(zt([S.objectApiName]).length>0?S.records:S.sent)??0})),toDraft:w,deleted:m,reads:O,draftReads:v.filter(S=>S.condition!==void 0).length,refused:g.blockers.map(S=>Hn(S.records)??0),...s.apiBudget?{apiBudget:s.apiBudget}:{},...s.bulkBatches?{bulkBatches:s.bulkBatches}:{},...s.dataStorageMB===void 0?{}:{dataStorageMB:s.dataStorageMB}});return{mode:t.mode,deleteMode:s.deleteMode,passes:g.objects,along:g.along,leftOut:o.leftOut,refusals:g.refusals,blockers:g.blockers,beforeParent:p.beforeParent,unordered:p.unordered,undoLost:g.undoLost,undoLostRecords:g.undoLostRecords,undo:s.deleteMode==="recycle",affected:[...d.emptied,...d.along].sort(),toDraftAlong:v,cost:k,total:{records:m,objects:f.length,uncounted:h,...y?{atLeast:!0}:{}},statements:g.statements,...g.stopped?{stopped:!0}:{}}}var _E=5,UE=is,md=class{constructor(e,t){this.objectApiName=e;this.planned=t}objectApiName;planned;deleted=0;gone=0;refused=new Map;refusedUnkept=0;lockResent=new Map;notes=[];settle(e,t){e.forEach((r,n)=>{let o=t[n],i=r.slice(0,15);if((o.lockResends!==void 0||this.lockResent.has(i))&&this.lockResent.set(i,o.kind),o.kind!=="refused"){this.refused.delete(r),o.kind==="deleted"?this.deleted++:this.gone++;return}let a={reason:o.reason,dependency:o.dependency,again:o.limit===void 0&&o.reason!==Bm};this.refused.has(r)||this.refused.size<UE?this.refused.set(r,a):(this.refusedUnkept++,this.note(o.reason))})}note(e){this.notes.includes(e)||this.notes.push(e)}toSendAgain(){return[...this.refused].filter(([,e])=>e.again).map(([e])=>e)}heldByDependents(){return[...this.refused].filter(([,e])=>e.again&&e.dependency).map(([e])=>e)}result(e,t){let r=this.refused.size+this.refusedUnkept,n=this.refusedUnkept>0?[`${this.refusedUnkept} more refused record(s) were counted, not kept for a second try: the reasons given are those of the records kept.`]:[],o=[...qm(this.objectApiName,e),...Wm(this.lockResent.values()),...this.notes,...n,...[...this.refused.values()].map(a=>a.reason)],i=this.deleted+this.gone+r;return{objectApiName:this.objectApiName,planned:this.planned,deleted:this.deleted,gone:this.gone,refused:r,...t&&this.planned>i?{notReached:this.planned-i}:{},reasons:[...new Set(o)].slice(0,_E)}}};async function RS(s,e,t){let{mode:r}=t,n=()=>t.signal?.aborted===!0,o=t.splitting??Oi(),i=e.objects.reduce((f,m)=>f+m.count,0),a=[],d=0,c=[],l=f=>{let m=a.find(y=>y.objectApiName===f);if(!m){let y=e.objects.find(w=>w.objectApiName===f);m=new md(f,y?.count??0),a.push(m)}return m},u=async(f,m)=>{await Ei(s,c,{note:(w,v,R,b)=>l(w).note(R?Ti(w,v,b,c):v)});let y=a.map(w=>w.result(o,f));if(f)for(let{objectApiName:w,count:v}of e.objects)y.some(R=>R.objectApiName===w)||y.push({...new md(w,v).result(o,!1),...v>0?{notReached:v}:{}});return{hard:r==="hard",objects:y,cancelled:f,...m!==void 0?{hardRefused:m}:{}}},p=(f,m)=>zm(s,f.objectApiName,m,{mode:r,stopped:n,splitting:o,...t.signal?{signal:t.signal}:{},...t.wait?{wait:t.wait}:{},settle:(y,w)=>{let v=f.deleted+f.gone+f.refused.size+f.refusedUnkept;f.settle(y,w),t.onSettled?.(f.objectApiName,y,w),d+=f.deleted+f.gone+f.refused.size+f.refusedUnkept-v,t.onProgress?.(d,i,f.objectApiName)}});if(r==="hard"&&s.bulkHardDestroy===void 0)return u(!0,Hm);if(t.toDraft!==!1){let f=await Ai(s,e.objects,e,()=>!0,n,async()=>new Set);if(c=f.drafted,f.cancelled)return u(!0)}for(let{objectApiName:f,count:m}of e.objects){if(n())return u(!0);let y=l(f),w=as(s,f,m,r),v=[],R=async()=>{let b=v;return v=[],p(y,b)};for await(let b of e.pages(f)){if(n())return u(!0);if(v.push(...b),w&&v.length<is)continue;let O=await R();if(O.stopped)return u(!0,O.hardRefused)}if(v.length>0){if(n())return u(!0);let b=await R();if(b.stopped)return u(!0,b.hardRefused)}}let g;if(await Gm(a,{stopped:n,idsOf:(f,m)=>m===0?f.toSendAgain():f.heldByDependents(),send:async(f,m)=>{let y=await p(f,[...m]);return g=y.hardRefused,y.stopped},deleted:f=>f.deleted}))return u(!0,g);for(let f of a){if(n())return u(!0);let{gone:m,unchecked:y,failure:w}=await Jm([...f.refused.keys()],v=>Vr(s,f.objectApiName,[],v),()=>!0);for(let v of m)f.refused.delete(v),f.gone++;y.length>0&&f.note(`Not checked: ${y.length} refused record(s) could not be read back once the rest had gone, to tell whether a parent deleted after them took them along`+(w?` \u2014 ${w}`:"."))}return u(!1)}function HE(s){let e=Math.floor(Date.parse(s)/1e3)*1e3;if(!Number.isFinite(e))throw new RangeError(`Not a date-time: ${s}`);return`CreatedDate < ${new Date(e).toISOString().replace(".000Z","Z")}`}function BE(s){return/CreatedDate/.test(T(s))}function Ou(s){let e=s.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?e[0]:e.map(t=>`(${t})`).join(" AND ")}function qE(s,e,t,r){let n=e?.count??t??s.planned,o=s.deleted+s.gone+s.refused,i=r&&n>o?n-o:0;return{objectApiName:s.objectApiName,planned:n,deleted:s.deleted,gone:s.gone,refused:s.refused,...i>0?{notReached:i}:{},reasons:s.reasons}}function WE(s,e,t,r=!1){if(e&&t===void 0)return"cancelled";let n=s.reduce((i,a)=>i+a.deleted,0),o=s.reduce((i,a)=>i+a.refused+(a.notReached??0),0);return t!==void 0?n>0?"partial":"failure":o===0?"success":n>0||r||s.some(i=>i.gone>0)?"partial":"failure"}async function vS(s){let{journal:e,org:t}=s,r=e.head,n=s.now??(()=>new Date),o=await e.state();await e.attempt(s.resumed,n());let i=[],a=new Ui,d=new Map;if(s.resumed){for await(let x of e.lines())if(x.kind==="settled"){for(let j of[...x.deleted,...x.gone])a.add(j);d.set(x.objectApiName,(d.get(x.objectApiName)??0)+x.deleted.length+x.gone.length)}}let c=new AbortController,l=s.signal?AbortSignal.any([s.signal,c.signal]):c.signal,u=()=>l.aborted,p,g=!1,h=HE(r.readAt),f=new Map(r.passes.map(x=>[x.objectApiName,x])),m=x=>f.get(x)?.rows??$n(x),y=new Map,w=new Map,v=()=>r.passes.reduce((x,j)=>x+Math.max(0,(w.get(j.objectApiName)??j.sent??j.records??0)-(d.get(j.objectApiName)??0)),0),R=async(x,j)=>{let K=async Q=>{let _=await hw(t.ids,x,[{objectApiName:j.objectApiName,...Q!==void 0?{filter:Q}:{}}],{signal:l});return _.stopped?void 0:_.spool};try{let Q=await K(Ou([j.filter,j.own,h]));return Q?{spool:Q,sinceRead:!0}:void 0}catch(Q){if(!BE(Q))throw Q;i.push(`${j.objectApiName} has no CreatedDate: its records were read whole, those made after the preview among them.`);let _=await K(Ou([j.filter,j.own]));return _?{spool:_,sinceRead:!1}:void 0}},b=x=>{let j=y.get(x);if(j)return j;let K=(async()=>{let Q=r.passes.findIndex(Be=>Be.objectApiName===x),_=e.idsDirOf(Q,x),V=o.spooled.get(x);if(s.resumed&&V)return w.set(x,V.count),{spool:await Hi.open(_,Ji),count:V.count,sinceRead:V.sinceRead};if(u())return;let ue=m(x),me=await R(_,{objectApiName:x,...ue!==void 0?{own:ue}:{}});if(!me)return;let re=me.spool.count,ie=f.get(x)?.records;if(ie!==void 0&&re>ie){p={code:"ORG_CHANGED",message:`${x} now holds ${re.toLocaleString("en-US")} records to delete, where the preview counted ${ie.toLocaleString("en-US")}: the org changed beyond what was confirmed, and the emptying stopped before deleting any of them. Preview it again, then resume or undo it.`},c.abort();return}return await e.spooled({objectApiName:x,place:Q,count:re,sinceRead:me.sinceRead}),w.set(x,re),{spool:me.spool,count:re,sinceRead:me.sinceRead}})();return y.set(x,K),K},O={objects:r.passes.map(x=>({objectApiName:x.objectApiName,count:x.sent??x.records??0})),pages:x=>({async*[Symbol.asyncIterator](){let j=await b(x);if(j)for await(let K of j.spool.pages(x)){let Q=a.size>0?K.filter(_=>!a.has(_)):K;Q.length>0&&(yield Q)}}})},k=Promise.resolve(),S,E=(x,j,K)=>{let Q=[],_=[];j.forEach((V,ue)=>{let me=K[ue]?.kind;me==="deleted"?Q.push(V):me==="gone"&&_.push(V)}),Q.length>0&&(g=!0),Q.length+_.length!==0&&(k=k.then(async()=>{if(S===void 0)try{await e.settled(x,Q,_)}catch(V){S=T(V),c.abort()}}))},I=[];for(let[x,j]of r.toDraftAlong.entries()){if(j.condition===void 0||u())continue;let K=e.idsDirOf(r.passes.length+x,j.objectApiName),Q=await R(K,{objectApiName:j.objectApiName,filter:j.condition});if(!Q)break;let{drafted:_}=await Ai(t.deletion,[{objectApiName:j.objectApiName}],Q.spool,()=>!0,u,async()=>new Set);I.push(..._)}let C=await RS(t.deletion,O,{mode:r.deleteMode,signal:l,...s.splitting?{splitting:s.splitting}:{},...s.wait?{wait:s.wait}:{},onSettled:E,onProgress:(x,j,K)=>{let Q=Math.max(x,v());s.onProgress?.({percentage:Q>0?Math.min(99,Math.round(x/Q*100)):99,step:`${K}: ${x.toLocaleString("en-US")} of about ${Q.toLocaleString("en-US")} settled`})}}).finally(async()=>{await k,await Ei(t.deletion,I,{note:(x,j,K,Q)=>i.push(Ti(x,j,Q,I))})});S!==void 0&&i.push(`The journal of this emptying could not be written (${S}): it stopped there, so that its Undo misses nothing it deleted.`);let F=new Map;for(let[x,j]of y)F.set(x,await j.catch(()=>{}));let Y=C.objects.map(x=>qE(x,F.get(x.objectApiName),f.get(x.objectApiName)?.records,C.cancelled));if(!C.cancelled)for(let x of Y){if(!F.get(x.objectApiName)?.sinceRead)continue;let K=m(x.objectApiName),Q=h.replace("CreatedDate <","CreatedDate >=");try{let _=await t.deletion.query(`SELECT COUNT() FROM ${He(x.objectApiName)} WHERE ${Ou([K,Q])}`);_.totalSize>0&&(x.madeSince=_.totalSize)}catch(_){i.push(`Whether ${x.objectApiName} records were made after the preview could not be read: `+T(_))}}let z=C.cancelled&&p===void 0&&S===void 0,te=p!==void 0||S!==void 0?g?"partial":"failure":WE(Y,z,C.hardRefused,s.resumed&&o.deletedAny),H=Y.reduce((x,j)=>x+j.refused,0);return s.resumed&&te==="partial"&&!g&&H>0&&i.push(`The org refused again the ${H.toLocaleString("en-US")} record(s) this emptying had left, each said with its words above: they stay, and the emptying is closed. Undo brings back what it deleted.`),{status:te,hard:C.hard,passes:Y,...C.hardRefused!==void 0?{hardRefused:C.hardRefused}:{},...p!==void 0?{changed:p}:{},deletedAny:g,notes:i}}var zE=/Entity is not in the recycle bin/,GE=/INSUFFICIENT_ACCESS/,JE=5,SS=5e4;function yd(s){return s.slice(0,15)}function Iu(s){let e=new Set;for(let t of s){let r=t?.Id;typeof r=="string"&&e.add(yd(r))}return e}function VE(s){let e=s?.errors?.[0];if(e===void 0)return"The org gave no reason.";if(typeof e=="string")return e;let t=e.statusCode??"",r=e.message??"";return t&&r?`${t}: ${r}`:t||r||"The org gave no reason."}function XE(s){return{objectApiName:s,planned:0,undeleted:0,alreadyBack:0,notInBin:0,othersDeletion:0,refused:0,reasons:[]}}function xs(s,e){s.reasons.length<JE&&!s.reasons.includes(e)&&s.reasons.push(e)}async function*KE(s,e,t){let r=t?new Ui:void 0;for await(let o of s.settledOf(e)){if(r)for(let i of[...o.deleted,...o.gone])r.add(i);o.deleted.length>0&&(yield[...o.deleted])}if(!t||!r)return;let n=await Hi.open(s.idsDirOf(t.place,e),Ji);for await(let o of n.pages(e)){let i=o.filter(a=>!r.has(a));i.length>0&&(yield i)}}async function kS(s){let e=0,t=0,r,n=new Map;for await(let o of s.lines())o.kind==="attempt"?(e++,r=void 0):o.kind==="end"?(t++,r=o.status):o.kind==="spooled"&&n.set(o.objectApiName,{place:o.place,count:o.count,attempt:e});return{spooledIn:n,...e>t?{unendedAttempt:e}:{},wentThrough:r==="success"||r==="partial"}}function OS(s,e){let t=s.spooledIn.get(e);return t!==void 0&&s.unendedAttempt!==void 0&&t.attempt===s.unendedAttempt?t:void 0}function YE(s){return(s.head.undoLost??[]).filter(e=>e.records===void 0||e.records>0).map(e=>({objectApiName:e.objectApiName,...e.field!==void 0?{field:e.field}:{},...e.parent!==void 0?{parent:e.parent}:{},reason:e.reason,records:{...e.records!==void 0?{records:e.records}:{unread:"not counted"},...e.atLeast===!0?{atLeast:!0}:{}}}))}async function IS(s){let e=await kS(s),t=0;for(let{objectApiName:r}of s.head.passes){let n=0;for await(let a of s.settledOf(r))a.deleted.length!==0&&(n+=a.deleted.length,t+=Math.ceil(a.deleted.length/Dt)*gu);let o=OS(e,r);o&&(n+=o.count,t+=Math.ceil(o.count/Dt)*gu);let i=(s.head.undoLost??[]).filter(a=>a.objectApiName===r).reduce((a,d)=>a+(d.records??0),0);t+=Math.ceil(Math.min(i,n)/Dt)}return t}async function AS(s){let{journal:e,org:t}=s,r=e.head,n=[],o=()=>s.signal?.aborted===!0,i=await kS(e),a=[],d=new Map,c=!1,l=[...r.passes].reverse();for(let[f,{objectApiName:m}]of l.entries()){let y=XE(m);a.push(y);let w=He(m),v=OS(i,m);for await(let R of KE(e,m,v)){y.planned+=R.length;for(let b=0;b<R.length;b+=Dt){let O=R.slice(b,b+Dt);if(c||o()){c=!0,y.notReached=(y.notReached??0)+O.length;continue}let[k]=os(O,Dt),S,E;try{S=Iu((await t.queryDeleted(`SELECT Id FROM ${w} WHERE Id IN (${k}) AND IsDeleted = true`)).records),E=Iu((await t.query(`SELECT Id FROM ${w} WHERE Id IN (${k})`)).records)}catch(F){y.refused+=O.length,xs(y,`The recycle bin could not be read: ${T(F)}`);continue}let I=O.filter(F=>S.has(yd(F)));for(let F of O)S.has(yd(F))||(E.has(yd(F))?y.alreadyBack++:(y.notInBin++,xs(y,"No longer in the recycle bin, nor in the org: emptied from the bin, or pushed out of it.")));if(I.length===0)continue;let C;try{let F=await s.undelete(I),Y=Array.isArray(F)?F:[F];C=I.map((z,te)=>Y[te]??{success:!1})}catch(F){let Y=T(F);C=I.map(()=>({success:!1,errors:[Y]}))}C.forEach((F,Y)=>{if(F.success===!0){y.undeleted++;return}let z=VE(F);if(zE.test(z)){y.notInBin++;let te=d.get(m)??[];te.length<SS&&te.push(I[Y]),d.set(m,te),xs(y,"Salesforce still lists it as deleted but will not bring it back: emptied from the recycle bin, or kept there for good \u2014 deleted on its own before a record it hangs from was deleted after it (the org answers 'Entity is not in the recycle bin')")}else GE.test(z)?(y.othersDeletion++,xs(y,`Deleted by another user than the one bringing it back: only Modify All Data brings back another's deletions (${z})`)):(y.refused++,xs(y,z))})}s.onProgress?.({percentage:Math.round((f+1)/Math.max(1,l.length)*100),step:`${m}: ${y.undeleted.toLocaleString("en-US")} brought back`})}}if(!c)for(let f of a){let m=d.get(f.objectApiName)??[];if(m.length===0)continue;f.notInBin>m.length&&n.push(`${f.objectApiName}: past ${SS.toLocaleString("en-US")} records answered not in the recycle bin, whether a parent brought back later took them back was not read: they are counted as not back.`);let y=He(f.objectApiName);try{let w=0;for(let R of os(m,Dt)){let b=await t.query(`SELECT Id FROM ${y} WHERE Id IN (${R})`);w+=Iu(b.records).size}let v=Math.min(w,f.notInBin);f.notInBin-=v,f.alreadyBack+=v}catch(w){n.push(`Whether the ${f.objectApiName} records the org answered were not in the recycle bin came back with their parent could not be read (${T(w)}): they are counted as not back.`)}}let u=i.wentThrough?YE(e):[],p=a.reduce((f,m)=>f+m.undeleted+m.alreadyBack,0),g=a.reduce((f,m)=>f+m.notInBin+m.othersDeletion+m.refused+(m.notReached??0),0)+u.length;return{status:c?"cancelled":g===0?"success":p>0?"partial":"failure",objects:a.filter(f=>f.planned>0),notes:n,...u.length>0?{previewedLost:u}:{}}}var Yt="Nothing was deleted.";function bd(s){return{query:e=>s.query(e),queryMore:e=>s.queryMore(e)}}var Au=G({Max:Me(),Remaining:Me()}).loose(),QE=G({DailyApiRequests:Au.optional(),DailyBulkApiBatches:Au.optional(),DataStorageMB:Au.optional()}).loose();async function ZE(s){try{let e=QE.parse(await s.limits()),t=o=>o?{max:o.Max,remaining:o.Remaining}:void 0,r=t(e.DailyApiRequests),n=t(e.DailyBulkApiBatches);return{apiBudget:r??{unread:"the limits the org answered list no DailyApiRequests"},...n?{bulkBatches:n}:{},...e.DataStorageMB?{dataStorageMB:e.DataStorageMB.Max}:{}}}catch(e){return{apiBudget:{unread:T(e)}}}}async function ES(s){try{return(await s.query("SELECT Id FROM User WHERE UserType = 'AutomatedProcess'")).records.map(t=>t.Id).filter(t=>typeof t=="string")}catch{return[]}}function Pu(s){let e=t=>t.records===void 0||t.records>0;return[...s.passes.filter(t=>e(t.records)).map(t=>t.objectApiName),...s.along.filter(t=>e(t.records)).map(t=>t.objectApiName)]}function eP(s){let e=s.passes.map(n=>({objectApiName:n.objectApiName,records:n.sent.records??0})).filter(n=>n.records>0),t=s.refusals.filter(n=>n.code==="activatedOrder"&&(n.records.records??0)>0).map(n=>({objectApiName:n.objectApiName,records:n.records.records??0})),r=[...e];for(let n of t)r.some(o=>o.objectApiName===n.objectApiName)||r.push(n);return{objects:r,steps:{delete:e.map(n=>n.objectApiName),...t.length>0?{setToDraft:t.map(n=>n.objectApiName)}:{}},written:[...e.map(n=>({...n,write:"delete"})),...t.map(n=>({...n,write:"update"}))]}}async function tP(s,e){let t=[];for(let r of e)try{let n=_i.safeParse(await s.describe(r));n.success&&t.push(n.data)}catch{}return t}function PS(s,e){return{code:"RUN_WRITING",message:`${e.operation==="take"?`A checkpoint of ${s} is being taken`:e.operation==="rewind"?`A rewind is writing to ${s}`:e.operation==="undo"?`An undo is writing to ${s}`:e.operation==="empty"?`An emptying of its objects, or its undo, is writing to ${s}`:`SandForge is deleting checkpoints of ${s}`} (process ${e.pid} on ${e.host}): empty once it has ended. ${Yt}`}}function Ao(s,e={}){let[t,...r]=s;return{ran:!1,refusal:t,...r.length>0?{alsoRefused:r}:{},...e}}async function Tu(s,e){let t=await s.lastOf(e);if(!t)return;let r;try{r=await s.open(e,t.runId)}catch(o){if(o instanceof pr)return;throw o}let n=await r.state();return n.open?{runId:t.runId,startedAt:n.head.startedAt,journal:r}:void 0}function CS(s,e){return{code:"OPEN_RUN",message:`The last emptying of ${s} (${e}) stopped part way: resume it, or undo it, before another one starts, so that its Undo still reaches the org as it was. ${Yt}`}}function rP(s){return s.reason==="notRestorable"?`${s.objectApiName}, which Salesforce does not bring back`:`${s.objectApiName} before ${s.parent??"their parent"}`}function DS(s){let e=s.undoLostRecords;return e?.records!==void 0?{records:e.records,atLeast:e.atLeast===!0}:{records:s.undoLost.reduce((t,r)=>t+(r.records.records??0),0),atLeast:s.undoLost.some(t=>t.records.records===void 0||t.records.atLeast===!0)}}function nP(s){if(s.deleteMode!=="recycle")return;let e=s.undoLost.filter(i=>i.records.records===void 0||i.records.records>0);if(e.length===0)return;let t=DS(s),r=`${t.atLeast?"at least ":""}${t.records.toLocaleString("en-US")}`,n=[...new Set(e.map(rP))],o=e.some(i=>i.reason==="restricted"||i.reason==="unordered");return{code:"NO_UNDO",message:`${r} record(s) would stay gone after Undo (${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""})`+(o?": some go before a record they name, as Salesforce requires, and once both have gone, Undo cannot bring them back":"")+". Accept it to empty all the same, or leave those objects out. "+Yt}}function oP(s,e){let t=[],{api:r,batches:n}=s.cost;return r.verdict==="exceeds"&&t.push({code:"API_BUDGET",message:`The emptying takes about ${r.estimate.toLocaleString("en-US")} API requests, and ${e} has ${r.remaining.toLocaleString("en-US")} left today. Empty fewer objects, or tomorrow. ${Yt}`}),n?.verdict==="exceeds"&&t.push({code:"BULK_BATCHES",message:`The emptying's Bulk API jobs take about ${n.estimate.toLocaleString("en-US")} batches, and ${e} has ${n.remaining.toLocaleString("en-US")} left today. Empty fewer records, or tomorrow. ${Yt}`}),t}function wd(s){return s.records}function sP(s,e){let t=[],r=new Map(s.passes.map(o=>[o.objectApiName,o]));for(let o of e.passes){let i=r.get(o.objectApiName),a=wd(o.records);if(!i){(a===void 0||a>0)&&t.push(`${o.objectApiName} is now emptied too`);continue}a===void 0&&wd(i.records)!==void 0&&t.push(`${o.objectApiName} could not be counted again (${o.records.unread??""})`)}let n=new Map(s.along.map(o=>[o.objectApiName,o]));for(let o of e.along){let i=n.get(o.objectApiName),a=wd(o.records),d=i?wd(i.records):0;if(a===void 0){d!==void 0&&t.push(`what goes along of ${o.objectApiName} could not be counted again`);continue}d!==void 0&&a>d&&t.push(`${a.toLocaleString("en-US")} ${o.objectApiName} record(s) now go along, where the preview counted ${d.toLocaleString("en-US")}`)}if(e.deleteMode==="recycle"){let o=c=>DS(c).records,i=c=>new Set(c.undoLost.map(l=>`${l.objectApiName}.${l.field??""}.${l.reason}`)),a=i(s);([...i(e)].filter(c=>!a.has(c)).length>0||o(e)>o(s))&&t.push("more records would go beyond what Undo brings back")}return t}function TS(s,e){return{code:"ORG_CHANGED",message:`${s} changed since the preview, beyond what was confirmed: ${e.slice(0,5).join("; ")}${e.length>5?"; \u2026":""}. Preview the emptying again. ${Yt}`}}function Eu(s,e,t){let r=t.automation?Ar(t.automation,t.mutePlan,Gr(t.steps)):{firing:[]};return{module:"empty",written:Pu(e),running:{firing:r.firing},request:{},orgId:s.orgId,operationId:s.operationId}}async function xS(s,e){let{org:t,orgName:r}=s,n=s.requestsSent?.()??0,o=bd(t),i=await Nn(o,{orgName:r,registered:s.registered,mode:e.request.mode});if(!i.allowed)return{previewed:!1,refusal:i.refusal};let a=await NS(s,e.request,e.deleteMode),d=await Dr({act:"empty",target:r,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},...jS(a.preview)}),c=await Tu(s.store,i.org.id),l=e.checkpointFirst===!0&&s.checkpoints?await s.checkpoints.scope(Eu(s,a.preview,d.answer),{operationId:s.operationId}):void 0,u=s.requestsSent!==void 0?s.requestsSent()-n:void 0,p=MS(a,u,2,Cr(d.mute?.plan)),g={previewId:iP(s.now?.()??new Date),readAt:p.readAt,orgName:r,tier:i.tier,preview:p.preview,request:e.request,organizationId:i.org.id,access:p.access,hardDelete:{permitted:p.permissions.hardDelete,...p.permissions.unread!==void 0?{unread:p.permissions.unread}:{}},peopleActive:aP(p.people),...l?{checkpoint:l}:{},...c?{openRun:{runId:c.runId,startedAt:c.startedAt}}:{}},h=await LS(s,i.org.id,p,{deleteMode:e.deleteMode,acceptNoUndo:e.acceptNoUndo===!0,...e.acceptPeopleActive===!0?{peopleAccepted:!0}:{},automation:d.answer,...l?{checkpoint:l}:{},...c?{open:c.runId}:{}});return{previewed:!0,kept:g,automation:d.answer,refusals:h,...u!==void 0?{requestsSent:u}:{}}}function MS(s,e,t,r){let n=e??s.preview.cost.requests.reads;return{...s,preview:{...s.preview,cost:eS(s.preview.cost,n,t,r)}}}function iP(s){return Ul(s).replace(/^em-/,"ep-")}function jS(s){let e=eP(s);return{objects:e.objects,writes:{steps:e.steps,written:e.written}}}async function NS(s,e,t){let{org:r}=s,n=bd(r),o=await r.serverTime(),i=G({sobjects:ke(pi)}).loose().parse(await r.describeGlobal()).sobjects,a=await r.toolingObjects(),d=await ZE(r),c=await bS({global:i,tooling:a,request:e,deleteMode:t,apiBudget:d.apiBudget,...d.bulkBatches?{bulkBatches:d.bulkBatches}:{},...d.dataStorageMB!==void 0?{dataStorageMB:d.dataStorageMB}:{},stopped:()=>s.signal?.aborted===!0},r),l=await Ts(n),u=Pu(c),p=new Set(i.filter(w=>w.customSetting===!0).map(w=>w.name)),g=await _v({permissions:l,objects:u,customSettings:u.filter(w=>p.has(w)),grants:async()=>_y(n,()=>r.userId()),describe:w=>tP(r,w)}),h=await r.userId(),f=new Date(Date.parse(o)-cu).toISOString(),m=await lu(r,u,[h,...await ES(r)],f),y=s.voice==="page"?await Wv(r,m):m;return{readAt:o,preview:c,permissions:l,access:g,people:y}}function aP(s){return{people:s.people.length,...s.atLeast?{atLeast:!0}:{},...s.who.length>0?{who:s.who.map(e=>({...e}))}:{},...s.unread.length>0?{unread:s.unread}:{}}}function $S(s){return s.voice==="page"?"page":"flags"}async function LS(s,e,t,r){let n=[],o=await s.runWriting?.(e);o!==void 0&&n.push({code:"RUN_WRITING",message:o}),r.open!==void 0&&n.push(CS(s.orgName,r.open)),t.preview.stopped&&n.push({code:"PREVIEW_STOPPED",message:`The preview was stopped before every count was in: preview again. ${dd}`}),r.deleteMode==="hard"&&!t.permissions.hardDelete&&n.push(du(t.permissions));let i=uu(s.orgName,t.people,{...r.peopleAccepted!==void 0?{accepted:r.peopleAccepted}:{},voice:$S(s)});i&&n.push(i);let a=r.acceptNoUndo?void 0:nP(t.preview);a&&n.push(a),n.push(...oP(t.preview,s.orgName)),r.checkpoint?.refusal&&n.push({...r.checkpoint.refusal});let d=Zr(r.automation);return d&&n.push({code:d.code,message:d.message},...d.alsoRefused),n}function dP(s){let e=s.toISOString();return{runId:"",status:"success",hard:!1,passes:[],totals:{deleted:0,gone:0,refused:0,notReached:0},undo:{offered:!1,why:"nothingDeleted"},notes:["The org holds nothing the preview would delete any more: nothing was sent."],startedAt:e,finishedAt:e}}function cP(s){return{mode:s.mode,...s.objects?{objects:[...s.objects]}:{},...s.excluded?{excluded:[...s.excluded]}:{},...s.customSettings!==void 0?{customSettings:s.customSettings}:{},...s.files!==void 0?{files:s.files}:{},...s.managedPackages!==void 0?{managedPackages:s.managedPackages}:{},...s.unrestorable!==void 0?{unrestorable:s.unrestorable}:{}}}function lP(s){return s.undoLost.filter(e=>e.records.records===void 0||e.records.records>0).map(e=>({objectApiName:e.objectApiName,...e.field!==void 0?{field:e.field}:{},...e.parent!==void 0?{parent:e.parent}:{},reason:e.reason,...e.records.records!==void 0?{records:e.records.records}:{},...e.records.atLeast===!0?{atLeast:!0}:{}}))}async function uP(s){let e=new Map,t=new Map;for await(let r of s.lines())if(r.kind==="spooled")e.set(r.objectApiName,r.count);else if(r.kind==="settled"){let n=t.get(r.objectApiName)??0;t.set(r.objectApiName,n+r.deleted.length+r.gone.length)}return s.head.passes.map(r=>{let n=e.get(r.objectApiName);return n===void 0?{objectApiName:r.objectApiName,records:r.sent??r.records??0,idsRead:!1}:{objectApiName:r.objectApiName,records:Math.max(0,n-(t.get(r.objectApiName)??0)),idsRead:!0}})}function pP(s){return s.reduce((e,t)=>({deleted:e.deleted+t.deleted,gone:e.gone+t.gone,refused:e.refused+t.refused,notReached:e.notReached+(t.notReached??0)}),{deleted:0,gone:0,refused:0,notReached:0})}async function FS(s,e){let{org:t,orgName:r}=s,n=s.now??(()=>new Date);if(!e.confirmed&&e.resumeRunId===void 0)throw new Error("An emptying acts on a preview it was confirmed on, or takes up a run.");let o=s.requestsSent?.()??0,i=bd(t),a=await Nn(i,{orgName:r,registered:s.registered,mode:e.confirmed?.request.mode??"objects"});if(!a.allowed)return{ran:!1,refusal:a.refusal};let d=a.org.id,c,l=await Tu(s.store,d);if(e.resumeRunId!==void 0){if(!l||l.runId!==e.resumeRunId)return{ran:!1,refusal:{code:"RUN_GONE",message:`${e.resumeRunId} is not the last emptying of ${r} stopped part way: there is nothing of it to take up. ${Yt}`}};if(c=l.journal,c.head.mode==="org"&&a.tier==="staging"){let I=await Nn(i,{orgName:r,registered:s.registered,mode:"org"});if(!I.allowed)return{ran:!1,refusal:I.refusal}}}else if(e.confirmed&&e.confirmed.organizationId.slice(0,15)!==d.slice(0,15))return{ran:!1,refusal:TS(r,["it is another org than the one the preview read \u2014 a refreshed sandbox is a new org"])};let u=e.confirmed,p=c?c.head.deleteMode:u?.preview.deleteMode??"recycle",g=[],h,f,m,y;if(u){h=await NS(s,u.request,p);let I=[...sP(u.preview,h.preview),...Uv(u.access,h.access).map(C=>`the user is no longer proven to see every record of ${C}`)];if(I.length>0&&g.push(TS(r,I)),h.preview.total.records===0&&h.preview.total.uncounted.length===0&&I.length===0)return{ran:!0,result:dP(n())};f=await Dr({act:"empty",target:r,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},...jS(h.preview)}),e.checkpointFirst===!0&&(m=s.checkpoints?await s.checkpoints.scope(Eu(s,h.preview,f.answer),{operationId:s.operationId}):void 0,m||g.push({code:"CHECKPOINT_REFUSED",message:`Checkpoints cannot be taken from here: run without Checkpoint first. ${Yt}`})),h=MS(h,s.requestsSent!==void 0?s.requestsSent()-o:void 0,1,Cr(f.mute?.plan)),g.push(...await LS(s,d,h,{deleteMode:p,acceptNoUndo:e.acceptNoUndo===!0,...e.acceptPeopleActive===!0?{peopleAccepted:(u.peopleActive.who??[]).map(C=>C.userId)}:{},automation:f.answer,...m?{checkpoint:m}:{},...l?{open:l.runId}:{}}))}else{let I=c.head,C=await Ts(i);p==="hard"&&!C.hardDelete&&g.push(du(C));let F=await s.runWriting?.(d);F!==void 0&&g.push({code:"RUN_WRITING",message:F});let Y=I.passes.map(Q=>Q.objectApiName),z=await t.userId(),te=await t.serverTime(),H=await lu(t,Y,[z,...await ES(t)],new Date(Date.parse(te)-cu).toISOString()),x=uu(r,H,{...e.acceptPeopleActive===!0?{accepted:!0}:{},voice:$S(s)});x&&g.push(x);let j=I.passes.map(Q=>({objectApiName:Q.objectApiName,records:Q.sent??Q.records??0})).filter(Q=>Q.records>0);f=await Dr({act:"empty",target:r,objects:j,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{}});let K=Zr(f.answer);K&&g.push({code:K.code,message:K.message},...K.alsoRefused),y=Qv(p,await uP(c),s.requestsSent!==void 0?s.requestsSent()-o:0,Cr(f.mute?.plan))}if(g.length>0)return Ao(g);let w=u&&h?h.preview:void 0,v=w?w.total.records:c.head.passes.reduce((I,C)=>I+(C.records??0),0),R=w?Pu(w):c.head.passes.map(I=>I.objectApiName),b=await s.askGuard({operation:p==="hard"?"hardDelete":"delete",objectNames:R,recordCount:v});if(b.decision==="refused"||b.decision==="declined")return Ao([{code:"GUARD",message:b.decision==="refused"?`Production Guard refused the emptying: ${b.reason??"no reason given"}. ${Yt}`:`The emptying was declined at Production Guard's confirmation. ${Yt}`}],{guard:b.decision});let O=b.decision,k;if(m&&s.checkpoints&&w){let I=await s.checkpoints.take(Eu(s,w,f.answer),{operationId:s.operationId},{planned:m,...s.signal?{signal:s.signal}:{},onProgress:({percentage:C})=>s.onProgress?.(Math.round(C/10),`Taking the checkpoint first (${Math.round(C)}%)`)});if(!I.taken)return Ao(["stopped"in I?{code:"CANCELLED",message:`The emptying was stopped while its checkpoint was taken. ${Yt}`}:{code:I.refusal.code,message:I.refusal.message}],{guard:O});k=I.checkpoint}let S=async I=>{if(!k||k.state!=="taken"||!s.checkpoints)return k;try{return await s.checkpoints.settle(k,I)}catch{return k}},E=s.lock(d);if("busy"in E)return await S(!1),Ao([PS(r,E.busy)],{guard:O});try{let I=await Tu(s.store,d);if(!c&&I)return await S(!1),Ao([CS(r,I.runId)],{guard:O});let C=await Pn(f,s.operationId,e.accord.acceptEmails===!0,s.voice);if("refused"in C)return await S(!1),Ao([{code:C.refused.code,message:C.refused.message}],{guard:O});let F=C.held,Y=n(),z=c??await s.store.begin(d,{runId:Ul(Y),orgName:r,startedAt:Y.toISOString(),readAt:u.readAt,previewId:u.previewId,mode:w.mode,deleteMode:p,request:cP(u.request),passes:w.passes.map(re=>({objectApiName:re.objectApiName,...re.records.records!==void 0?{records:re.records.records}:{},...re.sent.records!==void 0?{sent:re.sent.records}:{},...re.rows!==void 0?{rows:re.rows}:{}})),toDraftAlong:w.toDraftAlong,beforeParent:w.beforeParent,...p==="recycle"?{undoLost:lP(w)}:{}}),te=w&&w.cost.api.verdict!=="unread"?Ii(w.cost.api).splitAllowance:void 0,H,x,j=[];try{H=await vS({org:{deletion:t,ids:t},journal:z,resumed:c!==void 0,...s.signal?{signal:s.signal}:{},splitting:Oi(te),now:n,onProgress:({percentage:re,step:ie})=>s.onProgress?.(re,ie)})}catch(re){throw await z.ended("failure",[],n()).catch(()=>{}),re}finally{let re=t.lostJobs?.()??[];if(re.length>0&&t.stillRunning){let ie=await t.stillRunning(re);ie.length>0&&j.push(`${ie.length} Bulk API job(s) the org was still running after ten minutes: the mute was given back all the same, and what they delete from now on runs the org's automation.`)}F&&(x=await F.release(),j.push(..._t(x,r).map(ie=>ie.trim())))}let K=H.passes,Q=n();await z.ended(H.status,K,Q,H.hardRefused);let _=await S(H.deletedAny),V=[];if(H.status==="success"||H.status==="partial")for(let re of await s.store.runsOf(d))re.runId>=z.head.runId||(await s.store.remove(d,re.runId),V.push(re.runId));let ue=await z.state();return{ran:!0,result:{runId:z.head.runId,status:H.status,hard:H.hard,passes:K,totals:pP(K),...H.hardRefused!==void 0?{hardRefused:H.hardRefused}:{},undo:H.hard?{offered:!1,why:"hard"}:ue.deletedAny?{offered:!0}:{offered:!1,why:"nothingDeleted"},...c?{resumed:!0}:{},notes:[...H.notes,...H.changed?[H.changed.message]:[],...j],...x?{mutedAutomation:x}:{},..._?{checkpoint:_}:{},...V.length>0?{removedRuns:V}:{},...s.requestsSent!==void 0?{requestsSent:s.requestsSent()-o}:{},...y!==void 0?{requestsEstimate:y}:{},startedAt:Y.toISOString(),finishedAt:Q.toISOString()},guard:O}}finally{E.lock.release()}}async function _S(s,e){let{org:t,orgName:r}=s,n=s.now??(()=>new Date),o=s.requestsSent?.()??0,i=bd(t),a=await Nn(i,{orgName:r,registered:s.registered,mode:"objects"});if(!a.allowed)return{ran:!1,refusal:a.refusal};let d=a.org.id,c=(R,b)=>({ran:!1,refusal:{code:R,message:`${b} Nothing was brought back.`}}),l;try{l=await s.store.open(d,e.runId)}catch(R){if(R instanceof pr)return c("RUN_GONE",R.message);throw R}if((await s.store.lastOf(d))?.runId!==e.runId)return c("NOT_LAST_RUN",`${e.runId} is not the last emptying of ${r}: Undo reaches the last one alone, as what a later emptying deleted may hang from what this one did.`);let p=await l.state();if(l.head.deleteMode==="hard")return c("UNDO_UNAVAILABLE",`${e.runId} deleted for good: Salesforce brings back nothing a hard delete took, what went along included.`);if(p.undone)return c("UNDO_UNAVAILABLE",`${e.runId} was undone already.`);let g=await s.runWriting?.(d),h=[];g!==void 0&&h.push({code:"RUN_WRITING",message:g});let f=l.head.passes.map(R=>({objectApiName:R.objectApiName,records:R.records??0})),m=await Dr({act:"emptyUndo",target:r,objects:f,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},writes:{steps:{bringBack:f.map(R=>R.objectApiName)},written:[]}}),y=Zr(m.answer);if(y&&h.push({code:y.code,message:y.message},...y.alsoRefused),h.length>0){let[R,...b]=h;return{ran:!1,refusal:R,...b.length>0?{alsoRefused:b}:{}}}let w=Zv(await IS(l),s.requestsSent!==void 0?s.requestsSent()-o:0,Cr(m.mute?.plan)),v=s.lock(d);if("busy"in v)return{ran:!1,refusal:PS(r,v.busy)};try{let R=await Pn(m,s.operationId,e.accord.acceptEmails===!0,s.voice);if("refused"in R)return{ran:!1,refusal:{code:R.refused.code,message:R.refused.message}};let b,O;try{O=await AS({org:t,undelete:S=>t.undelete(S),journal:l,...s.signal?{signal:s.signal}:{},onProgress:({percentage:S,step:E})=>s.onProgress?.(S,E)})}finally{R.held&&(b=await R.held.release())}let k=n();return O.status!=="cancelled"&&await l.undone(O.status,k),{ran:!0,result:{runId:e.runId,status:O.status,objects:O.objects,notes:[...O.notes,...b?_t(b,r).map(S=>S.trim()):[]],...b?{mutedAutomation:b}:{},...s.requestsSent!==void 0?{requestsSent:s.requestsSent()-o}:{},requestsEstimate:w,...O.previewedLost?{previewedLost:O.previewedLost}:{},finishedAt:k.toISOString()}}}finally{v.lock.release()}}function gP(s){let e=In(s),t={closed:!1};return{bulk:{bulk2:{createJob:r=>{let n=e.bulk2.createJob(r);return t={closed:!1},{get id(){return n.id},open:async()=>{await n.open();let o=Nm(n);t={...o!==void 0?{jobId:o}:{},closed:!1}},uploadData:o=>n.uploadData(o),close:async()=>{await n.close(),t={...t,closed:!0}},abort:()=>n.abort(),check:()=>n.check(),getAllResults:()=>n.getAllResults()}}}},last:()=>t}}function US(s,e,t){let r=ii(s),n=Um(s,t),o=gP(s),i=[],a=new Kw(async(l,u)=>(await In(s).bulk2.job("ingest",{id:u}).check()).state),d=l=>async(u,p,g)=>{try{return await _m(o.bulk,u,p,g,l)}catch(h){let f=o.last();throw f.closed&&i.push({orgId:e,objectApiName:u,...f.jobId?{jobId:f.jobId}:{}}),h}},c=l=>({totalSize:l.totalSize,done:l.done,records:l.records,...l.nextRecordsUrl?{nextRecordsUrl:l.nextRecordsUrl}:{}});return{describe:l=>s.describe(l),count:async l=>(await s.query(l)).totalSize,countAll:async l=>(await s.query(l,{scanAll:!0})).totalSize,readIds:async(l,u)=>{let p=await s.query(l,{scanAll:u});return{totalSize:p.totalSize,ids:p.records.flatMap(g=>typeof g.Id=="string"?[g.Id]:[])}},query:async(l,u)=>c(await s.query(l,{scanAll:u?.scanAll===!0})),queryMore:async l=>c(await s.queryMore(l)),queryDeleted:l=>n.queryDeleted(l),describeGlobal:()=>s.describeGlobal(),toolingObjects:async()=>{try{return(await s.tooling.describeGlobal()).sobjects.map(l=>l.name)}catch{return[]}},serverTime:async()=>(await s.soap.getServerTimestamp()).timestamp,userId:async()=>(await s.soap.getUserInfo()).userId,limits:()=>s.request({method:"GET",url:"/limits"}),update:(l,u)=>n.update(l,u),destroy:(l,u)=>n.destroy(l,u),bulkDestroy:d("delete"),bulkHardDestroy:d("hardDelete"),undelete:l=>s.soap.undelete(l),lostJobs:()=>[...i],stillRunning:l=>a.stillRunning(l),requestsSent:r}}import{readdir as fP,readFile as hP,rm as HS,stat as BS,writeFile as mP}from"node:fs/promises";import{join as Rd}from"node:path";var WS=/^ep-\d{8}-\d{6}-[a-z0-9]{4}$/,yP=50;function vd(s){return WS.test(s)}var qS=G({records:Me().optional(),unread:L().optional()}).loose(),wP=G({v:vt(1),orgId:L().min(1),kept:G({previewId:L().regex(WS),readAt:L(),orgName:L(),organizationId:L().min(15).max(18),request:G({mode:Xe(["objects","org"])}).loose(),preview:G({mode:Xe(["objects","org"]),deleteMode:Xe(["recycle","hard"]),passes:ke(G({objectApiName:L(),records:qS}).loose()),along:ke(G({objectApiName:L(),records:qS}).loose()),undoLost:ke(G({objectApiName:L()}).loose()),total:G({records:Me()}).loose()}).loose(),access:G({kind:Xe(["org","perObject"])}).loose(),peopleActive:G({people:Me(),who:ke(G({userId:L()}).loose()).optional()}).loose()}).loose()}),Sd=class{constructor(e,t=Li){this.root=e;this.keepMs=t}root;keepMs;async keep(e,t,r=Date.now()){if(!vd(t.previewId))throw new Error(`Not a preview's id: ${t.previewId}`);await Fi(this.root),await mP(Rd(this.root,`${t.previewId}.json`),JSON.stringify({v:1,orgId:e,kept:t}),{mode:$i}),await this.sweep(r)}async read(e,t=Date.now()){if(!vd(e))return;let r=Rd(this.root,`${e}.json`);try{if((await BS(r)).mtimeMs+this.keepMs<=t)return;let n=wP.safeParse(JSON.parse(await hP(r,"utf8")));return!n.success||n.data.kept.previewId!==e?void 0:{orgId:n.data.orgId,kept:n.data.kept}}catch{return}}async remove(e){vd(e)&&await HS(Rd(this.root,`${e}.json`),{force:!0})}async sweep(e){let t;try{t=await fP(this.root)}catch{return}let r=t.filter(o=>o.endsWith(".json")&&vd(o.slice(0,-5))).sort(),n=Math.max(0,r.length-yP);for(let[o,i]of r.entries()){let a=Rd(this.root,i);try{(o<n||(await BS(a)).mtimeMs+this.keepMs<=e)&&await HS(a,{force:!0})}catch{}}}};var RP=6e4,vP=20,To="dataops",SP=new Set(["dataops:empty:scope","dataops:empty:preview","dataops:empty:run","dataops:empty:cancel","dataops:empty:undo"]),Lr=class extends Error{constructor(t,r=[],n){super(t.message);this.refusal=t;this.alsoRefused=r;this.mutedAutomation=n;this.name="EmptyRefused"}refusal;alsoRefused;mutedAutomation};function kP(s){return s.passes.filter(e=>e.deleted+e.refused+(e.notReached??0)>0).map(e=>({...at(e.objectApiName),deleted:e.deleted,failed:e.refused,...(e.notReached??0)>0?{notSent:e.notReached}:{}}))}function OP(s){return s.objects.filter(e=>e.undeleted+e.notInBin+e.othersDeletion+e.refused>0).map(e=>({...at(e.objectApiName),created:e.undeleted,failed:e.notInBin+e.othersDeletion+e.refused,...(e.notReached??0)>0?{notSent:e.notReached}:{}}))}function IP(s){return{previewId:s.previewId,readAt:s.readAt,orgName:s.orgName,tier:s.tier,preview:s.preview,access:s.access,hardDelete:s.hardDelete,peopleActive:s.peopleActive,...s.checkpoint?{checkpoint:s.checkpoint}:{},...s.openRun?{openRun:s.openRun}:{}}}var kd=class{constructor(e){this.deps=e}deps;liveTracker;previews=new Map;running=new Map;writing=new Map;targetAutomation;muteLeases={};checkpoints;runWriting;stores;orgOf=(e,t)=>US(e,t,"dataops:empty");setLiveOperationTracker(e){this.liveTracker=e}setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}setBeforeRunCheckpoints(e){this.checkpoints=e}setRunWriting(e){this.runWriting=e}setStores(e){this.stores=e}setOrgOf(e){this.orgOf=e}isWritingTo(e,t){for(let[r,n]of this.writing)if(n===e&&r!==t)return!0;return!1}async handle(e){if(!SP.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"dataops:empty:scope":return await this.handleScope(e),!0;case"dataops:empty:preview":return await this.handlePreview(e),!0;case"dataops:empty:run":return await this.handleRun(e),!0;case"dataops:empty:cancel":return this.handleCancel(e),!0;default:return await this.handleUndo(e),!0}}async countingReader(e){let{TargetAutomationReader:t,targetAutomationQueries:r}=await import("./chunk-4XZ5YT5O.mjs");return new t(r(async n=>{let o=await B(n,this.deps.orgRegistry,this.deps.orgManager);return e(o),o}))}ownStores(){if(this.stores)return this.stores;let e=jy({root:xy()});if("refusal"in e)throw new Lr({code:"RUN_WRITING",message:`The lock of the org cannot be kept in ${e.refusal.path}. Nothing was read or deleted.`});let t=e.store;return this.stores={journals:new ha(Hl()),previews:new Sd(bP(Hl(),"previews")),lock:r=>t.lock(r,"empty")},this.stores}async contextOf(e,t,r,n,o){let i=this.deps.orgManager.getOrg(e),a=await B(e,this.deps.orgRegistry,this.deps.orgManager),d=Re(i,e),c=this.ownStores(),l=this.orgOf(a,e),u=[],p,g=()=>this.targetAutomation?Promise.resolve(this.targetAutomation):(p??=this.countingReader(m=>u.push(ii(m))),p),h=ji(r),f=this.runWriting?.(e,d,t);return{org:l,...l.requestsSent?{requestsSent:()=>(l.requestsSent?.()??0)+u.reduce((m,y)=>m+y(),0)}:{},orgId:e,orgName:d,username:i?.username??d,registered:i,store:c.journals,lock:c.lock,...f?{runWriting:f}:{},automation:ao(a,async m=>{let y=await g();return new ge(RP).withTimeout("dataops automation",()=>y.read(e,m,{undeletes:!0}))},!1),muteLeases:this.muteLeases,...h?{voice:h}:{},...this.checkpoints?{checkpoints:this.checkpoints}:{},askGuard:async m=>{let y=this.deps.infraServices?.productionGuard;if(!y)return{decision:"refused",reason:ve.message};let{check:w,decision:v}=await Ke(y,{orgId:e,orgTier:Ee(i),operation:m.operation,objectName:m.objectNames.join(", "),recordCount:m.recordCount,module:To});return{decision:v,...v==="refused"?{reason:w.blockedReason??w.impactSummary}:{}}},operationId:t,tool:"panel",...n?{signal:n}:{},...o?{onProgress:o}:{}}}fail(e,t,r){if(t instanceof Lr){P(this.deps,e.type,"dataops:error",e,t,{code:t.refusal.code,retryable:!1,...t.alsoRefused.length>0||t.mutedAutomation?{extraPayload:{...t.alsoRefused.length>0?{alsoRefused:[...t.alsoRefused]}:{},...t.mutedAutomation?{mutedAutomation:t.mutedAutomation}:{}}}:{}});return}P(this.deps,e.type,"dataops:error",e,t,{code:r})}respond(e,t,r){let n=A(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}async handleScope(e){let t=D(nh,e,"dataops:error",this.deps);if(t)try{let{orgId:r,...n}=t,o=await this.contextOf(r,e.id,{}),i={query:u=>o.org.query(u)},a=await Nn(i,{orgName:o.orgName,registered:o.registered,mode:n.mode});if(!a.allowed)throw new Lr(a.refusal);let d=G({sobjects:ke(pi)}).loose().parse(await o.org.describeGlobal()).sobjects,c=hd(d,await o.org.toolingObjects(),n),l=await Ts(i);this.respond(e,"dataops:empty:scope:response",{mode:c.mode,objects:c.objects,leftOut:c.leftOut,candidates:c.worked,tier:a.tier,hardDelete:{permitted:l.hardDelete,...l.unread!==void 0?{unread:l.unread}:{}}})}catch(r){this.fail(e,r,"EMPTY_SCOPE_ERROR")}}previewStore(){return this.ownStores().previews}async keep(e,t){for(this.previews.set(t.previewId,{orgId:e,kept:t,at:Date.now()});this.previews.size>vP;){let r=this.previews.keys().next().value;if(r===void 0)break;this.previews.delete(r)}try{await this.previewStore()?.keep(e,t)}catch(r){this.deps.log(`[WARN] dataops:empty:preview: ${t.previewId} kept in this window alone (${r instanceof Error?r.message:String(r)})`)}}async keptPreview(e,t){let r=this.previews.get(t),n=r&&Date.now()-r.at<=Li?r:await this.previewStore()?.read(t);return n?.orgId===e?n.kept:void 0}async letGo(e){this.previews.delete(e),await this.previewStore()?.remove(e).catch(()=>{})}async handlePreview(e){let t=D(oh,e,"dataops:error",this.deps);if(!t)return;let r=new AbortController;this.running.set(e.id,r);try{let n=await this.contextOf(t.orgId,e.id,t,r.signal),o=await xS(n,{request:t.request,deleteMode:t.deleteMode,accord:t,...t.acceptNoUndo!==void 0?{acceptNoUndo:t.acceptNoUndo}:{},...t.acceptPeopleActive!==void 0?{acceptPeopleActive:t.acceptPeopleActive}:{},...t.checkpointFirst!==void 0?{checkpointFirst:t.checkpointFirst}:{}});if(!o.previewed)throw new Lr(o.refusal);await this.keep(t.orgId,o.kept),this.respond(e,"dataops:empty:preview:response",{...IP(o.kept),automation:o.automation,refusals:o.refusals,...o.requestsSent!==void 0?{requestsSent:o.requestsSent}:{}})}catch(n){this.fail(e,n,"EMPTY_PREVIEW_ERROR")}finally{this.running.delete(e.id)}}handleCancel(e){let t=D(ih,e,"dataops:error",this.deps);if(!t)return;let r=this.running.get(t.operationId);r&&(this.deps.infraServices?.backgroundRegistry?.abort(t.operationId),r.abort()),this.respond(e,"dataops:empty:cancel:response",{operationId:t.operationId,cancelled:r!==void 0})}async writeAct(e,t,r,n,o,i,a){let d=e.id,c=this.deps.infraServices?.backgroundRegistry,l=new AbortController;this.running.set(d,l),this.writing.set(d,t);let u=()=>{},p=new Promise((f,m)=>{u=y=>y===void 0?f():m(y)});p.catch(()=>{}),We(this.deps,d,To,r),c?.register(d,To,r,p,l);let g=Jt(this.liveTracker,d,To,r),h=(f,m)=>{$e(this.deps,d,f,0,0,m),l.signal.aborted||c?.updateProgress(d,f),g.progress(f,0,0,m)};try{let f=await this.contextOf(t,d,a,l.signal,h),m=await n(f);if(!m.ran)throw o("stopped",{code:m.refusal.code,...m.guard?{guard:m.guard}:{}}),pe(this.deps,d,{status:"refused",code:m.refusal.code}),g.fail(m.refusal.message),u(new Error(m.refusal.message)),new Lr(m.refusal,m.alsoRefused??[],m.mutedAutomation);let{result:y}=m;if(o(y.status,{result:y,...m.guard?{guard:m.guard}:{}}),await i(y),y.status==="cancelled")c?.abort(d),pe(this.deps,d,{aborted:!0}),g.cancel(),u();else if(y.status==="failure"){let w="Nothing the emptying set out to do went through: its result says why.";pe(this.deps,d,{status:y.status}),g.fail(w),u(new Error(w))}else pe(this.deps,d,{status:y.status}),y.status==="success"?g.complete():g.partial(),u()}catch(f){throw f instanceof Lr||(o("failure",{}),pe(this.deps,d,{status:"failure"}),g.fail(f instanceof Error?f.message:String(f)),u(f)),f}finally{this.running.delete(d),this.writing.delete(d)}}async handleRun(e){let t=D(sh,e,"dataops:error",this.deps);if(t)try{let r;if(t.previewId!==void 0&&(r=await this.keptPreview(t.orgId,t.previewId),!r))throw new Lr({code:"PREVIEW_GONE",message:"The preview this emptying was confirmed on is no longer kept on this machine \u2014 a preview is kept a day: preview it again, then empty. Nothing was read or deleted."});let n=o=>({empty:"run",...r?{mode:r.preview.mode,deleteMode:r.preview.deleteMode}:{},...t.resumeRunId!==void 0?{resumes:t.resumeRunId}:{},...o?{runId:o.runId,hard:o.hard,gone:o.totals.gone,...o.status==="cancelled"?{cancelled:!0}:{}}:{}});await this.writeAct(e,t.orgId,t.resumeRunId!==void 0?`Taking up the emptying ${t.resumeRunId}`:`Emptying ${r?.preview.total.objects??0} object(s) of ${r?.orgName??t.orgId}`,o=>FS(o,{...r?{confirmed:r}:{},...t.resumeRunId!==void 0?{resumeRunId:t.resumeRunId}:{},accord:t,...t.acceptNoUndo!==void 0?{acceptNoUndo:t.acceptNoUndo}:{},...t.acceptPeopleActive!==void 0?{acceptPeopleActive:t.acceptPeopleActive}:{},...t.checkpointFirst!==void 0?{checkpointFirst:t.checkpointFirst}:{}}),(o,i)=>X(this.deps,{action:"cleanup_delete",module:To,operationId:e.id,orgId:t.orgId,outcome:o,...i.guard?{guard:i.guard}:{},...i.code!==void 0?{code:i.code}:{},...i.result?{objects:kP(i.result)}:{},...i.result?.mutedAutomation?{muted:ot(i.result.mutedAutomation)}:{},...i.result?.checkpoint?.state==="taken"?{checkpointId:i.result.checkpoint.checkpointId}:{},details:n(i.result)}),async o=>{t.previewId!==void 0&&await this.letGo(t.previewId),this.respond(e,"dataops:empty:run:response",{operationId:e.id,result:o})},t)}catch(r){this.fail(e,r,"EMPTY_RUN_ERROR")}}async handleUndo(e){let t=D(ah,e,"dataops:error",this.deps);if(t)try{await this.writeAct(e,t.orgId,`Undoing the emptying ${t.runId}`,r=>_S(r,{runId:t.runId,accord:t}),(r,n)=>X(this.deps,{action:"empty_undo",module:To,operationId:e.id,orgId:t.orgId,outcome:r,...n.code!==void 0?{code:n.code}:{},...n.result?{objects:OP(n.result)}:{},...n.result?.mutedAutomation?{muted:ot(n.result.mutedAutomation)}:{},details:{empty:"undo",runId:t.runId}}),r=>this.respond(e,"dataops:empty:undo:response",{operationId:e.id,result:r}),t)}catch(r){this.fail(e,r,"EMPTY_UNDO_ERROR")}}};import{userInfo as SC}from"node:os";var zS=6e4,AP=2*6e4,TP=50,EP=2880*6e4,PP=60*6e4,CP=250,GS="pipeline-triggers",DP=G({cron:L().optional(),timezone:L().optional(),nextRunAt:Me().optional(),lastFiredAt:Me().optional(),lastOutcome:Xe(["started","missed"]).optional()});function Ms(s,e){return`pipeline-trigger:${s}:${e}`}var Od=class{constructor(e){this.deps=e;this.now=e.now??(()=>Date.now()),this.newId=e.newId??(()=>globalThis.crypto.randomUUID())}deps;engine=new Qb;now;newId;timer;started=!1;firstLook=!0;looking;lookAgain=!1;lastPrune=0;soonest;busyMisses=new Map;refusedMisses=new Map;unscheduled=new Map;start(){this.started||(this.started=!0,this.firstLook=!0,this.deps.log("[pipeline-triggers] started"),this.look())}stop(){this.started&&(this.started=!1,clearTimeout(this.timer),this.timer=void 0,this.deps.log("[pipeline-triggers] stopped"))}reload(){return this.started?this.look():Promise.resolve()}async onSandboxRefresh(e){if(!this.started)return;let t=this.deps.org(e.orgId);for(let r of this.deps.pipelines())for(let n of this.triggersOf(r)){if(!this.engine.firesOnRefreshOf(n,e.orgId)||this.engine.idleReason(n,t)||!this.deps.claims.claim(`refresh:${r.id}:${n.id}:${e.key}`))continue;let o=this.now(),i=await this.problemsOf(r);if(i.length>0){this.refuseStart(r,n,"sandbox_refresh",o,i,{sandboxName:t?.name});continue}this.fire(r,n,"sandbox_refresh",o,t?.name)}}async statuses(){let e=[],t=this.now();for(let r of this.deps.pipelines()){let n=this.triggersOf(r),o;for(let i of n){let a=this.read(r.id,i.id),d=i.type,c={pipelineId:r.id,triggerId:i.id,type:d,armed:!1,...a.lastFiredAt!==void 0?{lastFiredAt:new Date(a.lastFiredAt).toISOString(),...a.lastOutcome?{lastOutcome:a.lastOutcome}:{}}:{},...d==="schedule"?{timezone:this.engine.timezoneOf(i)}:{}},l=this.engine.idleReason(i,this.orgOf(i),t);l||(o??=await this.problemsOf(r),o.length>0&&(l={idle:"cannotRun",detail:o.join(" ")})),!l&&!this.started&&(l={idle:"stopped"});let u;if(!l&&d==="schedule"){let p=this.planOf(i,a)??this.engine.nextRun(i,t);typeof p=="number"?u=p:l=p}e.push(l?{...c,idle:l.idle,...l.detail?{detail:l.detail}:{}}:{...c,armed:!0,...u!==void 0?{nextRunAt:new Date(u).toISOString()}:{}})}}return e}look(){return this.looking?(this.lookAgain=!0,this.looking):(this.looking=this.lookNow().catch(e=>{this.deps.log(`[pipeline-triggers] a look failed: ${T(e)}`)}).finally(()=>{this.looking=void 0,this.lookAgain?(this.lookAgain=!1,this.look()):this.arm()}),this.looking)}async lookNow(){if(!this.started)return;let e=this.now(),t=this.firstLook;this.firstLook=!1,e-this.lastPrune>=PP&&(this.lastPrune=e,this.deps.claims.prune(EP));let r=new Set,n=new Set,o;for(let i of this.deps.pipelines()){n.add(i.id);let a;for(let d of this.triggersOf(i)){r.add(Ms(i.id,d.id));let c=this.engine.idleReason(d,this.orgOf(d),e);if(c||(a??=await this.problemsOf(i)),d.type!=="schedule")continue;let l=c?this.unplan(i,d):this.lookAt(i,d,e,t,a??[]);l!==void 0&&(o===void 0||l<o)&&(o=l)}this.sayWhyUnscheduled(i,a)}for(let i of[...this.unscheduled.keys()])n.has(i)||this.unscheduled.delete(i);this.soonest=o,this.forgetAllBut(r)}sayWhyUnscheduled(e,t){if(t===void 0)return;let r=this.unscheduled.get(e.id);if(t.length===0){if(r===void 0)return;this.unscheduled.delete(e.id),this.deps.log(`[pipeline-triggers] "${e.name}" can run again: its triggers start it`);return}let n=t.join(" ");r!==n&&(this.unscheduled.set(e.id,n),this.deps.log(`[pipeline-triggers] "${e.name}" is not scheduled: its triggers start nothing while a step cannot run. ${n}`))}lookAt(e,t,r,n,o){let i=this.read(e.id,t.id),a=this.planOf(t,i);if(a===void 0)return this.plan(e,t,i,r);if(a>r)return a;let d=this.engine.dueBetween(t,a,r,TP),c=[a,...d.times],l=c[c.length-1],u=!n&&r-l<=AP?l:void 0,p=u===void 0?c:c.slice(0,-1),g=this.plan(e,t,i,r),h=p.filter(f=>this.deps.claims.claim(this.dueKey(e,t,f)));if(h.length>0){let f={reason:n?"closed":"asleep",count:h.length,...h.length>1?{lastDueAt:new Date(h[h.length-1]).toISOString()}:{},...d.more?{atLeast:!0}:{}};this.recordMissed(e,"schedule",h[0],f),this.remember(e,t,{lastFiredAt:h[h.length-1],lastOutcome:"missed"}),this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:"schedule",dueAt:new Date(h[0]).toISOString(),missed:f,...g!==void 0?{nextRunAt:new Date(g).toISOString()}:{}})}return u!==void 0&&this.deps.claims.claim(this.dueKey(e,t,u))&&(o.length>0?this.refuseStart(e,t,"schedule",u,o,{...g!==void 0?{nextRunAt:new Date(g).toISOString()}:{}}):this.fire(e,t,"schedule",u)),g}refuseStart(e,t,r,n,o,i){let a=o.join(" "),d=Ms(e.id,t.id),c=r==="schedule"?this.refusedMisses.get(d):void 0,l=c&&c.detail===a?{...c,count:c.count+1}:{runId:`missed-${this.newId()}`,detail:a,firstDueAt:n,count:1};r==="schedule"&&this.refusedMisses.set(d,l);let u={reason:"cannotRun",count:l.count,...l.count>1?{lastDueAt:new Date(n).toISOString()}:{},detail:a};this.recordMissed(e,r,l.firstDueAt,u,l.runId),this.remember(e,t,{lastFiredAt:n,lastOutcome:"missed"}),!(l.count>1)&&this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:r,dueAt:new Date(n).toISOString(),missed:u,...i})}dueKey(e,t,r){return`due:${e.id}:${t.id}:${r}`}fire(e,t,r,n,o){let i=Ms(e.id,t.id);this.refusedMisses.delete(i);let a=this.deps.start(e,r);if(a.started){this.busyMisses.delete(i),this.remember(e,t,{lastFiredAt:n,lastOutcome:"started"}),this.deps.log(`[pipeline-triggers] started "${e.name}" (${r})`),a.run.then(u=>{u?.status==="failed"&&this.deps.report({kind:"failed",pipelineName:e.name,triggeredBy:r,error:u.error??"the run failed",...o?{sandboxName:o}:{}})},u=>{this.deps.report({kind:"failed",pipelineName:e.name,triggeredBy:r,error:T(u),...o?{sandboxName:o}:{}})});return}let d=this.busyMisses.get(i),c=d&&d.busySince===a.busy.startedAt?{...d,count:d.count+1,lastDueAt:n}:{runId:`missed-${this.newId()}`,busySince:a.busy.startedAt,firstDueAt:n,count:1,lastDueAt:n};this.busyMisses.set(i,c);let l={reason:"busy",count:c.count,busySince:c.busySince,...c.count>1?{lastDueAt:new Date(c.lastDueAt).toISOString()}:{}};this.recordMissed(e,r,c.firstDueAt,l,c.runId),this.remember(e,t,{lastFiredAt:n,lastOutcome:"missed"}),this.deps.log(`[pipeline-triggers] "${e.name}" not started (${r}): a run started at ${a.busy.startedAt} is going`),c.count===1&&this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:r,dueAt:new Date(n).toISOString(),missed:l,...o?{sandboxName:o}:{}})}recordMissed(e,t,r,n,o=`missed-${this.newId()}`){this.deps.record({runId:o,pipelineId:e.id,pipelineName:e.name,status:"missed",triggeredBy:t,startTime:new Date(r).toISOString(),duration:0,stepCount:0,errorCount:0,missed:n})}planOf(e,t){return t.cron===(e.config.cron??"").trim()&&t.timezone===this.engine.timezoneOf(e)?t.nextRunAt:void 0}plan(e,t,r,n){let o=this.engine.nextRun(t,n),i=typeof o=="number"?o:void 0;return this.write(e.id,t.id,{...r,cron:(t.config.cron??"").trim(),timezone:this.engine.timezoneOf(t),nextRunAt:i}),i}unplan(e,t){let r=this.read(e.id,t.id);(r.nextRunAt!==void 0||r.cron!==void 0)&&this.write(e.id,t.id,{...r.lastFiredAt!==void 0?{lastFiredAt:r.lastFiredAt}:{},...r.lastOutcome?{lastOutcome:r.lastOutcome}:{}})}remember(e,t,r){this.write(e.id,t.id,{...this.read(e.id,t.id),...r})}forgetAllBut(e){for(let t of Object.keys(this.deps.store.getByCategory(GS)))e.has(t)||this.deps.store.delete(t)}arm(){if(clearTimeout(this.timer),this.timer=void 0,!this.started)return;let e=this.soonest===void 0?zS:this.soonest-this.now(),t=Math.min(Math.max(e,CP),zS);this.timer=setTimeout(()=>{this.look()},t),this.timer.unref?.()}triggersOf(e){return(Array.isArray(e.triggers)?e.triggers:[]).flatMap(r=>{let n=Yb.safeParse(r);if(!n.success)return[];let o=n.data;return o.type==="schedule"||o.type==="sandbox_refresh"?[o]:[]})}orgOf(e){let t=e.config.orgId;return e.type==="sandbox_refresh"&&t?this.deps.org(t):void 0}async problemsOf(e){try{return await this.deps.problems(e)}catch(t){return[`The saved pipeline cannot be read: ${T(t)}.`]}}read(e,t){let r=DP.safeParse(this.deps.store.get(Ms(e,t)));return r.success?r.data:{}}write(e,t,r){this.deps.store.set(Ms(e,t),r,GS)}};function Eo(){let s=new Map,e=new Map;return{claim(t){return s.has(t)?!1:(s.set(t,Date.now()),!0)},hold(t,r){let n=e.get(t);return n?{busy:n}:(e.set(t,r),{release:()=>{e.delete(t)}})},prune(t){let r=Date.now()-t;for(let[n,o]of s)o<r&&s.delete(n)}}}var tB=65*6e4;var JS=[{id:"tpl-sandbox-refresh",name:"Sandbox Refresh",description:"Full sandbox refresh: backup data, seed test data, verify deployment.",category:"environment",steps:[{name:"Backup Target Data",type:"dataops:backup",description:"Export current target data before refresh."},{name:"Seed Test Data",type:"seed:execute",description:"Generate and insert test data from templates."},{name:"Verify Deployment",type:"compare:execute",description:"Compare metadata between source and target."}]},{id:"tpl-data-migration-dry",name:"Migration Pre-flight Check",description:"Describe source objects, deltas, field mappings and conflicts for a migration (steps do not run yet).",category:"migration",steps:[{name:"Describe Source Objects",type:"sync:describe-global",description:"List all queryable objects in source."},{name:"Detect Deltas",type:"sync:delta",description:"Identify new, modified, and deleted records."},{name:"Validate Field Mappings",type:"sync:describe-fields",description:"Verify field compatibility between orgs."},{name:"List Conflicts",type:"sync:preview",description:"List conflicts between source and target records."}]},{id:"tpl-nightly-cleanup",name:"Nightly Cleanup",description:"Scheduled cleanup: anonymize stale data, archive old records, refresh monitoring.",category:"maintenance",steps:[{name:"Anonymize PII",type:"dataops:anonymize",description:"Apply GDPR anonymization rules to sensitive data."},{name:"Archive Old Records",type:"dataops:backup",description:"Backup and archive records older than 90 days."},{name:"Refresh Monitor",type:"monitor:refresh",description:"Refresh org health and limit data."}]}];var VS="pipeline-rewind-grants",KS="pipeline:rewind-grant:",XS="pipeline:saved:",Cu=G({pipelineId:L().min(1).max(200),stepId:L().min(1).max(200),organizationId:L().min(1).max(18),checkpointId:L().min(1).max(200),digest:L().regex(/^sha256:[0-9a-f]{64}$/),grantedAt:Uo.datetime(),grantedBy:L().max(80).optional(),takenBackAt:Uo.datetime().optional()}).strict();function xu(s,e){return`Rewind step "${s}" has `+(e==="changed"?"not been confirmed since it was changed":"never been confirmed")+": open it and type the org's alias, or, for an org that has none, its name or Organization Id. No record was written."}function Du(s,e){return`${KS}${s}:${e}`}var js=class{constructor(e){this.store=e}store;all(){return Object.values(this.store.getByCategory(VS)).flatMap(e=>{let t=Cu.safeParse(e);return t.success?[t.data]:[]})}get(e,t){let r=Cu.safeParse(this.store.get(Du(e,t)));return r.success?r.data:void 0}write(e){this.store.set(Du(e.pipelineId,e.stepId),Cu.parse(e),VS)}revoke(e,t){return this.store.delete(Du(e,t))}revokePipeline(e){let t=`${KS}${e}:`,r=[];for(let n of this.store.getKeysByPrefix(t))this.store.delete(n)&&r.push(n.slice(t.length));return r}revokeChanged(e,t,r=()=>new Date){let n=[];for(let o of this.all().filter(i=>i.pipelineId===e)){let i=t.find(d=>d.id===o.stepId),a=i?.type==="rewind";a&&o.takenBackAt!==void 0||a&&Ns(i.config)===o.digest||(a?(this.write({...o,takenBackAt:r().toISOString()}),n.push(o.stepId)):this.revoke(o.pipelineId,o.stepId)&&o.takenBackAt===void 0&&n.push(o.stepId))}return n}async revokeVoid(e){let t=[],r=new Map;for(let n of this.all()){let i=!this.store.has(`${XS}${n.pipelineId}`);if(!i&&e){let a=r.get(n.checkpointId);a||(a=e(n.checkpointId),r.set(n.checkpointId,a)),i=!await a}i&&this.revoke(n.pipelineId,n.stepId)&&t.push(n)}return t}verify(e,t){let r=this.get(e,t.id);return!r||!this.store.has(`${XS}${e}`)?{refusal:"never"}:r.takenBackAt!==void 0||Ns(t.config)!==r.digest?{refusal:"changed"}:{grant:{organizationId:r.organizationId,checkpointId:r.checkpointId,digest:r.digest,grantedAt:r.grantedAt}}}};function Ns(s){let e=Ft.safeParse(s??{});return e.success?ni(e.data):void 0}function YS(s,e){return new js(s).revokePipeline(e)}import{randomBytes as xP,randomUUID as Po}from"node:crypto";import{lstat as MP,rename as jP,rm as NP,stat as $P}from"node:fs/promises";import{hostname as LP}from"node:os";import{basename as $s,dirname as rk,join as FP,sep as _P}from"node:path";var UP=new Set(["checkpoint:list","checkpoint:scope","checkpoint:take","checkpoint:preview","checkpoint:plan-selection","checkpoint:rewind","checkpoint:undo","checkpoint:delete","checkpoint:keep","checkpoint:rename","checkpoint:ignore-fields","checkpoint:rewinds","checkpoint:export","checkpoint:import-read","checkpoint:import"]),hr="checkpoint",HP=8,BP=6e4,Fr="CANCELLED",qP={success:"success",partial:"partial",unstable:"partial",failure:"failure",cancelled:"cancelled"},WP={preview:"previewed",rewind:"rewound to",undo:"used",export:"exported"};function Mu(s){let{result:e,notes:t,deliverability:r}=s;return{done:!0,result:e,notes:t,...r!==void 0?{deliverability:r}:{}}}var zP=/\s*\b(?:No record was (?:read or )?written|Nothing was written)\./g;function ju(s,e,t,r){let n=t(s),o=(e??[]).map(t);return o.length===0?{done:!1,refusal:n}:r?{done:!1,refusal:{code:n.code,message:nk([n,...o])},alsoRefused:o}:{done:!1,refusal:n,alsoRefused:o}}function nk(s){let e=!1;return s.map(({message:t})=>{let r=t.replace(zP,"").trim();return e?r:(e=r!==t.trim(),t)}).join(" ")}var GP=new Set(["RUN_WRITING","API_BUDGET","EMAILS"]),Bn=class extends Error{constructor(t,r,n,o=[]){super(r);this.code=t;this.result=n;this.alsoRefused=o;this.name="CheckpointStepRefused"}code;result;alsoRefused};function QS(s){return s.deleted.some(e=>e.deleted>0)||s.restored.some(e=>e.restored+(e.restoredWithout??0)>0)||s.undeleted.some(e=>e.undeleted>0)||(s.recreated??[]).some(e=>e.created>0)}async function JP(){let[s,e,t,r,n,o,i,a,d,c,l]=await Promise.all([import("./chunk-2S5OMIIA.mjs"),import("./chunk-EQOQASDQ.mjs"),import("./chunk-Y6J6QFI2.mjs"),import("./chunk-YW2SBL4Z.mjs"),import("./chunk-NHWE66K5.mjs"),import("./chunk-ZYEE34WO.mjs"),import("./chunk-4U6NXJNL.mjs"),import("./chunk-75ADZS6B.mjs"),import("./chunk-6LAXTAVN.mjs"),import("./chunk-X65MT4W3.mjs"),import("./chunk-EEVVGGM6.mjs")]);return{pageEmailsRefusal:l.pageEmailsRefusal,planSelection:a.planSelection,snapshotRowsOf:a.snapshotRowsOf,rewindWriters:a.rewindWriters,boundsRefusals:d.boundsRefusals,selectionDiff:d.selectionDiff,rewindStepsOf:d.rewindStepsOf,notConfirmedRefusal:d.notConfirmedRefusal,undeletableUnattendedRefusal:d.undeletableUnattendedRefusal,REWIND_STEP_WORDS:d.REWIND_STEP_WORDS,REWIND_MUTING_STEP_WORDS:d.REWIND_MUTING_STEP_WORDS,guardCheckpoint:o.guardCheckpoint,newArchiveKey:i.newArchiveKey,archiveKeyText:i.archiveKeyText,parseArchiveKey:i.parseArchiveKey,ARCHIVE_EXTENSION:i.ARCHIVE_EXTENSION,exportCheckpointArchive:i.exportCheckpointArchive,CheckpointExportError:i.CheckpointExportError,readArchiveHeader:i.readArchiveHeader,importCheckpointArchive:i.importCheckpointArchive,DEFAULT_KEEP_DAYS:s.DEFAULT_KEEP_DAYS,openCheckpointStore:s.openCheckpointStore,defaultCheckpointStoreRoot:s.defaultCheckpointStoreRoot,scratchOrgExpired:s.scratchOrgExpired,previewDirOf:s.previewDirOf,CheckpointStoreError:s.CheckpointStoreError,takeCheckpoint:e.takeCheckpoint,scopeCheckpoint:e.scopeCheckpoint,takeOrgOf:e.takeOrgOf,CheckpointTakeStopped:e.CheckpointTakeStopped,previewCheckpoint:t.previewCheckpoint,rewindOrg:r.rewindOrg,rewindOrgOf:r.rewindOrgOf,RewindStopped:r.RewindStopped,undoCheckpoint:n.undoCheckpoint,UndoStopped:n.UndoStopped,beforeRunScopeOf:c.beforeRunScopeOf,beforeRunAskedOf:c.beforeRunAskedOf,beforeRunKeepDaysOf:c.beforeRunKeepDaysOf,beforeRunDiskRefusal:c.beforeRunDiskRefusal,beforeRunOutcomeOf:c.beforeRunOutcomeOf,freeBytesOf:c.freeBytesOf,scopeBeforeRun:c.scopeBeforeRun,settleBeforeRun:c.settleBeforeRun}}var Pe=class extends Error{constructor(t,r,n=!1,o,i,a=[]){super(r);this.code=t;this.retryable=n;this.result=o;this.refusal=i;this.alsoRefused=a;this.name="Refused"}code;retryable;result;refusal;alsoRefused};function ZS(s){return s instanceof xt?s:s instanceof Pe?s.code===Fr?new xt(s.message):new Bn(s.code,s.alsoRefused.length>0?nk([s,...s.alsoRefused]):s.message,s.result,s.alsoRefused):s}async function ek(s){try{return(await $P(s)).isDirectory()}catch{return!1}}function Qt(s,e){return s!==void 0&&e!==void 0&&s.length>=15&&s.slice(0,15)===e.slice(0,15)}var tk=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function Id(s,e){if(e===void 0)return;let t=new Map(s.objects.map(({objectApiName:n})=>[n.toLowerCase(),n])),r=e.filter(n=>!t.has(n.toLowerCase()));if(r.length>0)throw new Pe("NOT_HELD",`The checkpoint '${s.name}' holds no ${r.join(", ")}: a rewind is limited to objects it holds. No record was read or written.`);return[...new Set(e.flatMap(n=>t.get(n.toLowerCase())??[]))]}function ft(s){return Re(s)}function VP(s,e){let t=[...e].sort((n,o)=>o.length-n.length),r=s;for(let n of t)r=r.replaceAll(n,$s(n));for(let n of t){let o=rk(n);o===n||o.length<=1||(r=r.replaceAll(`${o}${_P}`,"").replaceAll(o,$s(o)))}return r}function XP(s){return{formatVersion:s.formatVersion,checkpointFormat:s.checkpointFormat,sandforgeVersion:s.sandforgeVersion,organizationId:s.organizationId,orgTier:s.orgTier,checkpointId:s.checkpointId,takenAt:s.takenAt,records:s.records,objects:s.objects,files:s.files,bytes:s.bytes}}function KP(s){let e=s.reason==="notAFolder"?"it is a file, not a folder":s.reason==="otherOwner"?"another user of this machine owns it, and could read and replace the checkpoints in it":`it could not be made${s.detail!==void 0?` (${s.detail})`:""}`;return`The checkpoints cannot be kept in ${s.path}: ${e}.`}function Nu(s){return`${s.operation==="take"?"a checkpoint is being taken":s.operation==="rewind"?"a rewind is writing":s.operation==="undo"?"an undo is writing":s.operation==="empty"?"an emptying of its objects is writing":"SandForge is deleting checkpoints"} (process ${s.pid} on ${s.host})`}var Ad=class{constructor(e,t={},r=so){this.deps=e;this.writers=t;this.self=r}deps;writers;self;loaded;store;liveTracker;syncRuns;seedRuns;targetAutomation={read:async(e,t,r)=>(await this.ownReader()).read(e,t,r)};reader;previewsAnswered;previewReads=new Map;changeListeners=new Set;importFiles=new Map;muteLeases={};freeBytes;setLiveOperationTracker(e){this.liveTracker=e}setRunFiles(e,t){e==="sync"?this.syncRuns=t:this.seedRuns=t}setStore(e){this.store=Promise.resolve(e)}setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}setFreeBytes(e){this.freeBytes=e}rewindFromPreviewsAnswered(){this.previewsAnswered??=new Map}async handle(e){if(!UP.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"checkpoint:list":return await this.handleList(e),!0;case"checkpoint:scope":return await this.handleScope(e),!0;case"checkpoint:take":return await this.handleTake(e),!0;case"checkpoint:preview":return await this.handlePreview(e),!0;case"checkpoint:plan-selection":return await this.handlePlanSelection(e),!0;case"checkpoint:rewind":return await this.handleRewind(e),!0;case"checkpoint:undo":return await this.handleUndo(e),!0;case"checkpoint:delete":return await this.handleDelete(e),!0;case"checkpoint:keep":return await this.handleKeep(e),!0;case"checkpoint:rename":return await this.handleRename(e),!0;case"checkpoint:ignore-fields":return await this.handleIgnoreFields(e),!0;case"checkpoint:rewinds":return await this.handleRewinds(e),!0;case"checkpoint:export":return await this.handleExport(e),!0;case"checkpoint:import-read":return await this.handleImportRead(e),!0;case"checkpoint:import":return await this.handleImport(e),!0;default:return!1}}async sweep(){try{let t=await(await this.openedStore()).sweep();for(let r of t.checkpoints)this.deps.log(`[INFO] Removed checkpoint '${r.name}' of ${r.alias??r.organizationId}, taken ${r.takenAt}: kept until ${r.expiresAt}`+(r.undoUntil!==void 0?`; the undo of its last rewind, open until ${r.undoUntil}, went with it`:""));for(let r of t.journals)this.deps.log(`[INFO] Removed the journal of rewind ${r.rewindId} of checkpoint '${r.name}': it could be undone until ${r.undoUntil}`);for(let r of t.skipped)this.deps.log(`[INFO] Checkpoints of ${r} not swept: a take, a rewind or an undo runs`);t.checkpoints.length>0&&this.checkpointsChanged()}catch(e){this.deps.log(`[WARN] Expired checkpoints were not removed: ${T(e)}`)}}async keptBefore(e){let t=e.previousOrganizationId??this.deps.sandboxRefreshes?.organizationIdOf(e.orgId);return t===void 0||!tk.test(t)?0:(await(await this.openedStore()).list({organizationId:t})).length}async latestUsableOf(e){let t=this.deps.orgManager.getOrg(e);if(!t||!Yn(t))return;let r=await this.openedStore(),n=(await this.listOfOrg(r,e)).find(o=>o.valid&&o.checkpoint!==void 0)?.checkpoint;return n?{checkpointId:n.checkpointId,name:n.name,takenAt:n.takenAt}:void 0}onCheckpointsChanged(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}async scopeBeforeRun(e,t={}){let r=this.registeredOrg(e.orgId),n=await this.modules(),o=await this.openedStore(),i=await this.connect(r);return n.scopeBeforeRun({org:n.takeOrgOf(i),store:o,handler:this.deps,runWriting:this.beforeRunWriting(r,t),...this.freeBytes?{freeBytes:this.freeBytes}:{}},this.takeRequestOf(r,{mode:"picked"}),this.beforeRunRequestOf(n,e))}async takeBeforeRun(e,t={},r={}){let n=`checkpoint:before-run:${Po()}`,o=this.registeredOrg(e.orgId),i=await this.modules(),a=await this.openedStore(),d=this.beforeRunRequestOf(i,e),c=i.beforeRunScopeOf(d),l=(h,f={})=>{let{taken:m}=f;X(this.deps,{action:"checkpoint_take",module:hr,operationId:n,orgId:o.id,outcome:h,beforeRun:{module:e.module,operationId:e.operationId},...f.code!==void 0?{code:f.code}:{},details:m?{checkpointId:m.checkpointId,records:m.records,objects:m.objects.length,bytes:m.bytes}:{}})};if(r.planned!==void 0){let h=i.beforeRunDiskRefusal(r.planned.estimate.bytes,await(this.freeBytes??i.freeBytesOf)(a.root));if(h!==void 0)return l("stopped",{code:h.code}),{taken:!1,refusal:h}}let u=await this.connect(o);if(r.signal?.aborted)return l("cancelled"),{taken:!1,stopped:!0};let p;try{p=await this.take(n,i,a,u,o,i.beforeRunAskedOf(c,d),{description:`Checkpoint first: taking a checkpoint of ${ft(o)} before the run`,runWriting:this.beforeRunWriting(o,t),...r.signal?{signal:r.signal}:{},...r.onProgress?{onProgress:r.onProgress}:{}})}catch(h){if(h instanceof Pe&&h.code===Fr)return l("cancelled"),{taken:!1,stopped:!0};if(h instanceof Pe&&h.refusal!==void 0)return l("stopped",{code:h.refusal.code}),{taken:!1,refusal:h.refusal};throw l("failure"),h}let g=await i.beforeRunOutcomeOf(a,c,p);return g.taken?l("success",{taken:g.checkpoint}):(this.checkpointsChanged(),l("stopped",{..."refusal"in g?{code:g.refusal.code}:{}})),g}async settleBeforeRun(e,t){let r=await this.modules(),n=await this.openedStore(),o=await r.settleBeforeRun(n,e,t);return o.notDeleted!==void 0&&this.deps.log(`[WARN] ${o.notDeleted}`),o.info.state==="deleted"&&(this.deps.log(`[INFO] Deleted checkpoint '${e.name}', taken before a run that wrote nothing`),this.checkpointsChanged()),o.info}beforeRunRequestOf(e,t){let r=this.deps.services?.getSandforgeSetting?.("checkpoint.beforeRunKeepDays",Pp.default);return{module:t.module,written:t.written,running:t.running,request:t.request,operationId:t.operationId,tool:"panel",keepDays:e.beforeRunKeepDaysOf(t.request.keepDays,r)}}beforeRunWriting(e,t){return this.runWriting(e.id,ft(e),"start this run","No record was read.",t)}async takeForPipeline(e,t){let r=`checkpoint:pipeline:${Po()}`;try{let n=Vo.safeParse(e.config);if(!n.success)throw new Pe("CONFIG_INVALID",`The Checkpoint step "${e.origin.step}" does not read: ${n.error.issues[0]?.message??"its configuration is not one"}. Nothing was read.`);let o=n.data,i=this.registeredOrg(o.orgId),a=await this.modules(),d=await this.openedStore(),c=await this.connect(i);if(t?.aborted)throw new Pe(Fr,new a.CheckpointTakeStopped().message);let{checkpoint:l}=await this.take(r,a,d,c,i,{...o.name!==void 0?{nameWithDate:o.name}:{},mode:o.mode,...o.objects!==void 0?{objects:o.objects}:{},...o.excluded!==void 0?{excluded:o.excluded}:{},...o.maxTotal!==void 0?{maxTotal:o.maxTotal}:{},keepDays:o.keepDays,...o.ignoredFields!==void 0?{ignoredFields:o.ignoredFields}:{}},{description:`Pipeline '${e.origin.pipeline}': taking a checkpoint of ${ft(i)}`,...t?{signal:t}:{}});return{operationId:r,checkpointId:l.checkpointId,name:l.name,records:l.objects.reduce((u,p)=>u+p.records,0),objects:l.objects.length,bytes:l.bytes,movedWhileTaken:l.movedWhileTaken}}catch(n){throw ZS(n)}}async rewindForPipeline(e,t){let r=`checkpoint:pipeline:${Po()}`,{grant:n,origin:o}=e;try{let i=await this.modules(),a=Ft.safeParse(e.config);if(!a.success)throw new Pe("CONFIG_INVALID",`The Rewind step "${o.step}" does not read: ${a.error.issues[0]?.message??"its configuration is not one"}. No record was read or written.`);let d=a.data;if(n.digest!==ni(d)||n.checkpointId!==d.checkpointId)throw this.refusalOf(i.notConfirmedRefusal(o.step,!0));let c=await this.openedStore(),{folder:l,checkpoint:u}=await this.checkpointOf(c,d.checkpointId);if(!Qt(n.organizationId,u.org.organizationId))throw this.refusalOf(i.notConfirmedRefusal(o.step,!0));this.usable(i,u,"rewind");let p=this.registeredOrg(d.orgId);if(!Qt(p.orgId,u.org.organizationId)&&!Qt(this.deps.sandboxRefreshes?.organizationIdOf(p.id),u.org.organizationId))throw new Pe("OTHER_ORG",`The checkpoint '${u.name}' is not of ${ft(p)}, the org the Rewind step "${o.step}" names. No record was read or written.`);let g=Id(u,d.objects),h=await this.connect(p),f=ft(p),m={operationId:r,pipeline:{origin:o,grantedAt:n.grantedAt}},y=()=>(this.audit(m,"rewind",p,u,"stopped",{code:gt}),new xt(new i.RewindStopped().message)),w=(F,Y=[])=>(this.audit(m,"rewind",p,u,"stopped",{code:F.code}),this.refusalOf(F,Y));if(t?.aborted)throw y();let v;try{v=await i.previewCheckpoint({org:i.takeOrgOf(h),store:c,readAutomation:F=>this.readAutomation(p.id,F),runWriting:this.runWriting(p.id,f,"rewind","No record would be read or written."),...t?{signal:t}:{}},{checkpoint:u,folder:l,orgName:f,registered:p,username:p.username,...g!==void 0?{objects:g}:{},reusesPreview:!0,...d.muteAutomation?{muteAutomation:!0}:{},acceptOutside:d.acceptOutside})}catch(F){throw t?.aborted?y():F}if(!v.previewed)throw w(v.refusal);let R=g!==void 0?i.selectionDiff(v.diff,await i.planSelection({checkpoint:u,previewDir:i.previewDirOf(l,v.diff.previewId),readAt:v.diff.readAt,objects:new Set(g),acceptOutside:d.acceptOutside,heldRows:i.snapshotRowsOf(u,l),...t?{signal:t}:{}})):v.diff,b=d.muteAutomation&&v.automation?Ay(v.automation,Gr(i.rewindStepsOf(R))).automation:v.automation,O=await i.boundsRefusals({orgName:f,preview:{diff:R,...b?{automation:b}:{},...v.emails?{emails:v.emails}:{},...v.emailsUncounted!==void 0?{emailsUncounted:v.emailsUncounted}:{},...v.deliverability?{deliverability:v.deliverability}:{}},bounds:{maxRecords:d.maxRecords,refuseWhenActive:d.refuseWhenActive},accepted:d,writers:async()=>i.rewindWriters(u.takenBy,await i.takeOrgOf(h).userId()),words:d.muteAutomation?i.REWIND_MUTING_STEP_WORDS:i.REWIND_STEP_WORDS,user:p.username}),[k,...S]=[...v.refusal!==void 0?[v.refusal]:[],...O.filter(F=>F.code!==v.refusal?.code)];if(k!==void 0)throw w(k,S);if(t?.aborted)throw y();let E=[],I=[],C=await this.writeAct(m,"rewind",p,u,`Pipeline '${o.pipeline}': rewinding ${f} to '${u.name}'`,async(F,Y)=>{let z=await i.rewindOrg({org:i.rewindOrgOf(h),undelete:te=>h.soap.undelete(te),store:c,readAutomation:te=>this.readAutomation(p.id,te),runWriting:this.runWriting(p.id,f,"rewind","No record was read or written."),onUndeletable:te=>(E.push(...te),this.deps.log(`[WARN] checkpoint:rewind ${r}: the user may not delete ${te.map(H=>`${H.objectApiName} (${H.records})`).join(", ")} in the target, and nobody runs the pipeline to be asked: the deletion is left untouched`),Promise.resolve(!1)),onProgress:({percentage:te,step:H})=>Y(te,H),signal:F,...d.muteAutomation?{mute:this.muteOf(h)}:{}},{checkpoint:u,folder:l,orgName:f,registered:p,username:p.username,previewId:v.diff.previewId,reusesPreview:v.diff,...g!==void 0?{objects:g}:{},acceptAutomation:d.acceptAutomation,acceptEmails:d.acceptEmails,acceptNoUndo:d.acceptNoUndo,acceptRecreate:d.acceptRecreate,acceptOutside:d.acceptOutside,acceptUnseen:d.acceptUnseen});return z.rewound?(I=z.notes,Mu(z)):ju(z.refusal,z.alsoRefused,te=>te,!1)},F=>F instanceof i.RewindStopped,{...t?{signal:t}:{},acceptEmails:d.acceptEmails,refusalOf:F=>E.length>0?i.undeletableUnattendedRefusal(f,E,QS(F)):void 0});return{operationId:r,checkpointId:u.checkpointId,result:C,notes:I,estimate:v.estimate}}catch(i){throw ZS(i)}}async exportCheckpoint(e){try{let t=await this.modules(),r=await this.openedStore(),{folder:n,checkpoint:o}=await this.checkpointOf(r,e.checkpointId);this.usable(t,o,"export");let i=e.key??t.newArchiveKey(),a=await t.exportCheckpointArchive({folder:n,checkpoint:o,out:e.out,key:i,sandforgeVersion:e.sandforgeVersion}),{header:d}=a;return X(this.deps,{action:"checkpoint_export",module:hr,operationId:Po(),orgId:this.orgOfCheckpoint(o)?.id??o.org.organizationId,outcome:"success",details:{checkpointId:o.checkpointId,records:d.records,objects:d.objects,files:d.files,bytes:a.bytes}}),{exported:!0,checkpoint:o,header:d,bytes:a.bytes,sha256:a.sha256,...e.key===void 0?{key:t.archiveKeyText(i)}:{}}}catch(t){return{exported:!1,refusal:await this.transferRefusalOf(t,"EXPORT_ERROR")}}}async readImport(e){let t=await this.importChecked(e);return"refusal"in t?{allowed:!1,...t}:{allowed:!0,header:t.read.header}}async importCheckpoint(e){let t=await this.importChecked(e),r=(d,c,l,u={})=>{X(this.deps,{action:"checkpoint_import",module:hr,operationId:Po(),orgId:d,outcome:c,...u.code!==void 0?{code:u.code}:{},details:{...l?{checkpointId:l.checkpointId,records:l.records,objects:l.objects}:{},...u.alreadyKept?{alreadyKept:!0}:{}}})};if("refusal"in t)return t.orgId!==void 0&&r(t.orgId,"stopped",t.header,{code:t.refusal.code}),{imported:!1,refusal:t.refusal,...t.header?{header:t.header}:{}};let{m:n,store:o,org:i,read:a}=t;try{let d=await n.importCheckpointArchive({store:o,file:e.file,read:a,key:e.key,...i.alias?{alias:i.alias}:{},keepDays:e.keepDays??n.DEFAULT_KEEP_DAYS,takenOn:{host:LP(),pid:process.pid}});if(!d.imported)return r(i.id,"stopped",a.header,{code:d.refusal.code}),{imported:!1,header:a.header,refusal:d.refusal};r(i.id,"success",a.header,d.outcome==="alreadyKept"?{alreadyKept:!0}:{}),d.outcome==="imported"&&this.checkpointsChanged();let c=ft(i);return{imported:!0,outcome:d.outcome,checkpoint:d.checkpoint,warnings:[`Rewinds of ${c} from two machines at once fight each other: the lock is per machine. Agree on who rewinds.`,"A field your user cannot see is neither compared nor written back by a rewind from this machine, and its preview names it.","The rewinds made from the machine it came from, and their Undo, stayed there."]}}catch(d){return r(i.id,"failure",a.header),{imported:!1,header:a.header,refusal:await this.transferRefusalOf(d,"IMPORT_ERROR")}}}async importChecked(e){let t,r;try{let n=await this.modules(),o=await this.openedStore(),i=this.registeredOrg(e.orgId);r=i.id;let a=await n.readArchiveHeader(e.file);if("refusal"in a)return{refusal:a.refusal,orgId:r};t=a.read.header;let d=await this.connect(i),c=await n.guardCheckpoint(d,{act:"import",orgName:ft(i),registered:i,username:i.username,organizationId:t.organizationId});if(!c.allowed){let l=c.refusal.code==="OTHER_ORG"?this.refreshedAt(t.organizationId):void 0;return{refusal:l!==void 0?{code:"OTHER_ORG",message:`The sandbox this file's checkpoint was taken of was refreshed on ${l.slice(0,10)}: ${ft(i)} is another org now, and the checkpoint can no longer be rewound to. Nothing was imported.`}:c.refusal,header:t,orgId:r}}return{m:n,store:o,org:i,read:a.read}}catch(n){return{refusal:await this.transferRefusalOf(n,"IMPORT_ERROR"),...t?{header:t}:{},...r!==void 0?{orgId:r}:{}}}}async transferRefusalOf(e,t){if(e instanceof Pe)return{code:e.code,message:e.message};let r=await this.modules().catch(()=>{});return r!==void 0&&e instanceof r.CheckpointExportError?{code:e.code,message:e.message}:{code:t,message:T(e)}}async handleExport(e){let t=D(yh,e,"checkpoint:error",this.deps);if(!t)return;let r=[];try{let n=this.fileDialogs("export"),o=await this.modules(),i=await this.openedStore();r.push(i.root);let{checkpoint:a}=await this.checkpointOf(i,t.checkpointId);this.usable(o,a,"export");let{checkpointId:d}=a,c=await n.pickExportFile(`${d}${o.ARCHIVE_EXTENSION}`);if(c===void 0){this.respond(e,"checkpoint:export:response",{status:"cancelled",checkpointId:d});return}r.push(c);let l=await MP(c).then(()=>!0,()=>!1),u=l?FP(rk(c),`.${$s(c)}.${xP(4).toString("hex")}.export`):c;r.push(u);let p=await this.exportCheckpoint({checkpointId:d,out:u,sandforgeVersion:n.sandforgeVersion});if(!p.exported)throw new Pe(p.refusal.code,p.refusal.message);if(l)try{await jP(u,c)}catch(g){throw await NP(u,{force:!0}),g}this.respond(e,"checkpoint:export:response",{status:"saved",checkpointId:d,fileName:$s(c),key:p.key,records:p.header.records,objects:p.header.objects,bytes:p.bytes})}catch(n){this.fail(e,this.pathless(n,r,"EXPORT_ERROR"),"EXPORT_ERROR")}}async handleImportRead(e){let t=[];try{let r=this.fileDialogs("import"),n=await this.modules(),o=await this.openedStore();t.push(o.root);let i=await r.pickImportFile();if(i===void 0){this.respond(e,"checkpoint:import-read:response",{status:"cancelled"});return}t.push(i);let a=await n.readArchiveHeader(i);if("refusal"in a)throw this.refusalOf(a.refusal);let{header:d}=a.read,c=[],l;for(let p of this.deps.orgManager.getAllOrgs()){if(!this.organizationIdsOf(p.id).some(f=>Qt(f,d.organizationId)))continue;let h=await this.readImport({orgId:p.id,file:i});h.allowed?c.push(p.id):l??=h.refusal}if(c.length===0&&l!==void 0)throw new Pe(l.code,l.message);let u=await o.read(d.checkpointId)!==void 0;this.respond(e,"checkpoint:import-read:response",{status:"read",token:this.keepImportFile(i),fileName:$s(i),summary:XP(d),orgIds:c,...u?{keptHere:!0}:{}})}catch(r){this.fail(e,this.pathless(r,t,"IMPORT_ERROR"),"IMPORT_ERROR")}}async handleImport(e){let t=D(wh,e,"checkpoint:error",this.deps);if(!t)return;let r=this.importFiles.get(t.token),n=r!==void 0?[r]:[];try{if(r===void 0)throw new Pe("IMPORT_FILE_GONE","This window no longer knows the file to import: choose it again with Import\u2026. Nothing was imported.");let o=await this.modules();n.push((await this.openedStore()).root);let i=o.parseArchiveKey(t.key);if(i===void 0){let d=await this.readImport({orgId:t.orgId,file:r});throw d.allowed?new Pe("IMPORT_KEY","That is not a key SandForge draws: 52 letters and digits, in groups of four as the export showed it. Nothing was imported."):new Pe(d.refusal.code,d.refusal.message)}let a=await this.importCheckpoint({orgId:t.orgId,file:r,key:i,keepDays:t.keepDays});if(!a.imported)throw new Pe(a.refusal.code,a.refusal.message);this.importFiles.delete(t.token),this.respond(e,"checkpoint:import:response",{checkpoint:a.checkpoint,outcome:a.outcome})}catch(o){this.fail(e,this.pathless(o,n,"IMPORT_ERROR"),"IMPORT_ERROR")}}fileDialogs(e){let t=this.deps.infraServices?.checkpointFiles;if(!t)throw new Pe("NO_FILE_DIALOG",e==="export"?"This window has no dialog to ask where the file goes: export the checkpoint with npx sandforge checkpoint export. Nothing was written.":"This window has no dialog to ask which file to read: import it with npx sandforge checkpoint import. Nothing was imported.");return t}keepImportFile(e){let t=Po();this.importFiles.set(t,e);for(let r of this.importFiles.keys()){if(this.importFiles.size<=HP)break;this.importFiles.delete(r)}return t}pathless(e,t,r){let n=e instanceof Pe?e:new Pe(r,T(e));return new Pe(n.code,VP(n.message,t),n.retryable)}checkpointsChanged(){for(let e of this.changeListeners)try{e()}catch(t){this.deps.log(`[WARN] A listener of the checkpoints failed: ${T(t)}`)}}modules(){return this.loaded??=JP(),this.loaded}async openedStore(){this.store??=this.modules().then(t=>{let r=t.openCheckpointStore({root:t.defaultCheckpointStoreRoot()});return"store"in r?r.store:r.refusal});let e=await this.store;if("reason"in e)throw this.store=void 0,new Pe("STORE_REFUSED",KP(e));return e}respond(e,t,r){let n=A(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}fail(e,t,r,n=!0){if(t instanceof Pe){P(this.deps,e.type,"checkpoint:error",e,t,{code:t.code,retryable:t.retryable,...t.alsoRefused.length>0?{extraPayload:{alsoRefused:[...t.alsoRefused]}}:{}});return}P(this.deps,e.type,"checkpoint:error",e,t,{code:r,retryable:n})}refusalOf(e,t=[]){return new Pe(e.code,e.message,GP.has(e.code),void 0,e,t)}registeredOrg(e){let t=this.deps.orgManager.getOrg(e);if(!t)throw new Pe("ORG_NOT_FOUND","SandForge has no connected org of this id: connect it first.");return t}async connect(e){try{return await B(e.id,this.deps.orgRegistry,this.deps.orgManager)}catch(t){throw t instanceof wg&&t.code==="SCRATCH_ORG_EXPIRED"?new Pe("SCRATCH_EXPIRED",`${ft(e)} is a scratch org that has expired: its checkpoints can only be deleted.`):t}}takeRequestOf(e,t){let r=e.metadata?.expirationDate,{mode:n,objects:o,excluded:i,customSettings:a,maxTotal:d}=t;return{orgId:e.id,orgName:ft(e),...e.alias?{alias:e.alias}:{},username:e.username,instanceUrl:e.instanceUrl,registered:e,...e.orgType==="Scratch"&&r!==void 0&&/^\d{4}-\d{2}-\d{2}$/.test(r)?{scratchExpiresAt:r}:{},mode:n,...o!==void 0?{objects:o}:{},...i!==void 0?{excluded:i}:{},...a!==void 0?{customSettings:a}:{},...d!==void 0?{maxTotal:d}:{}}}writingTo(e,t,r,n,o={}){return this.runWriting(e,t,r,n,o)}runWriting(e,t,r,n,o={}){let i=`A SandForge run is writing to ${t}: ${r} once it has ended. ${n}`;return async a=>{if(this.writers.writingTo?.(e,o.operationId)===!0)return i;for(let d of[this.syncRuns,this.seedRuns])if(d){for(let c of await d.list())if(!(c.end!==void 0||!this.writesTo(c,e,a))&&!(o.runId!==void 0&&c.runId===o.runId&&this.writtenHere(c))&&(this.writers.isRunning?.(c.runId)===!0||An(c,this.self)))return i}}}writtenHere(e){let t=e.writer;return t!==void 0&&t.pid===this.self.pid&&Date.parse(t.hostStartedAt)===Date.parse(this.self.startedAt)}writesTo(e,t,r){return e.targetOrgId===t||Qt(e.targetOrganizationId,r)||Qt(this.deps.orgManager.getOrg(e.targetOrgId)?.orgId,r)}refreshedAt(e){let t=this.deps.sandboxRefreshes;if(t)for(let r of this.deps.orgManager.getAllOrgs())for(let n of t.refreshesOf(r.id)){let o=n.previousOrganizationId??(n.organizationId===void 0?t.organizationIdOf(r.id):void 0);if(Qt(o,e))return n.detectedAt}}organizationIdsOf(e){let t=this.deps.sandboxRefreshes,r=[this.deps.orgManager.getOrg(e)?.orgId,t?.organizationIdOf(e),...t?.refreshesOf(e).map(o=>o.previousOrganizationId)??[]],n=[];for(let o of r)o===void 0||!tk.test(o)||n.some(i=>Qt(i,o))||n.push(o);return n}async listOfOrg(e,t){let r=o=>this.refreshedAt(o);return(await Promise.all(this.organizationIdsOf(t).map(o=>e.list({organizationId:o,refreshedAt:r})))).flat().sort((o,i)=>o.checkpointId<i.checkpointId?1:o.checkpointId>i.checkpointId?-1:0)}orgOfCheckpoint(e){let t=e.org.organizationId,r=this.deps.orgManager.getAllOrgs(),n=r.filter(a=>Qt(a.orgId,t)),o=n.find(a=>a.alias===e.org.alias)??n[0];if(o)return o;let i=this.deps.sandboxRefreshes;return r.find(a=>Qt(i?.organizationIdOf(a.id),t))}async checkpointOf(e,t){let r=await e.read(t);if(r===void 0)throw new Pe("NOT_FOUND",`No checkpoint ${t} is kept on this machine.`,!1);if(r.checkpoint===void 0)throw new Pe("DAMAGED",`The file of checkpoint ${t} cannot be read: it can only be deleted.`);return{folder:r.folder,checkpoint:r.checkpoint}}usable(e,t,r){let n=Re(t.org);if(t.status!=="ready")throw new Pe(t.status==="taking"?"TAKING":"FAILED",t.status==="taking"?`The checkpoint '${t.name}' is being taken, or its take never ended: it can be ${WP[r]} once taken, or deleted.`:`The take of checkpoint '${t.name}' failed: it can only be deleted.`);let o=this.refreshedAt(t.org.organizationId);if(o!==void 0)throw new Pe("OTHER_ORG",`This sandbox was refreshed on ${o.slice(0,10)}: ${n} is another org now, and this checkpoint is of the org before it. It can only be deleted.`);if(e.scratchOrgExpired(t.org,Date.now()))throw new Pe("SCRATCH_EXPIRED",`${n} is a scratch org that has expired: its checkpoints can only be deleted.`)}connectedOrgOf(e,t){let r=this.orgOfCheckpoint(e);if(!r){let n=Re(e.org);throw new Pe("ORG_NOT_FOUND",`${n} is not connected in SandForge: connect it to ${t}.`)}return r}async undoOffered(e,t,r,n){if((await e.list({organizationId:t.organizationId,refreshedAt:d=>this.refreshedAt(d)})).find(d=>d.checkpointId===r.checkpointId)?.undo?.rewindId===n)return;let i=r.lastRewind,a=i?.rewindId!==n?`the rewind ${n} is not the last rewind to '${r.name}'`:i.undoneAt!==void 0?`it was undone on ${i.undoneAt.slice(0,10)}, and there is nothing left to undo`:i.undoUntil!==void 0&&Date.parse(i.undoUntil)<=Date.now()?`its 15 days ended on ${i.undoUntil.slice(0,10)}, and what it deleted may have left the recycle bin`:"Undo is offered for the last rewind of an org only, while its journal is kept on this machine";throw new Pe("UNDO_CLOSED",`This rewind can no longer be undone: ${a}. No record was read or written.`)}audit(e,t,r,n,o,i={}){let{result:a,code:d,deliverability:c}=i,l=a?.mutedAutomation??i.muted,u=a?.rewindId??i.rewindId,p=e.pipeline;X(this.deps,{action:t==="rewind"?"checkpoint_rewind":"checkpoint_undo",module:hr,operationId:e.operationId,orgId:r.id,outcome:o,...a?{objects:Pi(Yr(a.deleted),a.restored,a.undeleted)}:{},...d!==void 0?{code:d}:{},...l?{muted:ot(l)}:{},details:{checkpointId:n.checkpointId,...u!==void 0?{rewindId:u}:{},...a?{status:a.status,passes:a.passes}:{},...a?.scope?{limitedTo:a.scope.objects.join(", ")}:{},...c!==void 0?{deliverability:c}:{},...c!==void 0&&c!=="withheld"&&i.acceptEmails===!0?{confirmed:"emails"}:{},...p?{pipeline:p.origin.pipeline,step:p.origin.step,trigger:p.origin.trigger,grantedAt:p.grantedAt}:{}}})}async handleList(e){let t=D(uh,e,"checkpoint:error",this.deps);if(t!==null)try{let r=await this.openedStore(),n=t?.orgId===void 0?await r.list({refreshedAt:o=>this.refreshedAt(o)}):await this.listOfOrg(r,t.orgId);this.respond(e,"checkpoint:list:response",{checkpoints:n})}catch(r){this.fail(e,r,"LIST_ERROR")}}async handleScope(e){let t=D(ph,e,"checkpoint:error",this.deps);if(t)try{let r=this.registeredOrg(t.orgId),n=await this.modules(),o=await this.openedStore(),i=await this.connect(r),a=await n.scopeCheckpoint({org:n.takeOrgOf(i),store:o,handler:this.deps,runWriting:this.runWriting(r.id,ft(r),"take the checkpoint","No record was read.")},this.takeRequestOf(r,t));this.respond(e,"checkpoint:scope:response",{orgId:t.orgId,mode:a.mode,objects:a.objects,leftOut:a.leftOut,estimate:a.estimate,...a.refusal?{refusal:a.refusal}:{},...a.files?{files:a.files}:{},...a.customSettings?{customSettings:a.customSettings}:{}})}catch(r){this.fail(e,r,"SCOPE_ERROR")}}async handleTake(e){let t=D(gh,e,"checkpoint:error",this.deps);if(!t)return;let r=e.id,o=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(r);try{let i=this.registeredOrg(t.orgId),a=await this.modules(),d=await this.openedStore(),c=await this.connect(i);if(o?.signal.aborted)throw new Pe(Fr,new a.CheckpointTakeStopped().message,!0);await this.take(e.id,a,d,c,i,t,{kept:({checkpoint:l,requests:u,estimate:p})=>this.respond(e,"checkpoint:take:response",{checkpoint:l,operationId:e.id,...u?{requests:u}:{},estimate:p})})}catch(i){this.fail(e,i,"TAKE_ERROR")}finally{o?.release()}}async take(e,t,r,n,o,i,a={}){let d=ft(o),c=a.description??`Taking a checkpoint of ${d}`,l=this.deps.infraServices?.backgroundRegistry,u=new AbortController,p=()=>{},g=new Promise((y,w)=>{p=v=>v===void 0?y():w(v)});g.catch(()=>{}),We(this.deps,e,hr,c),l?.register(e,hr,c,g,u);let h=Jt(this.liveTracker,e,hr,c),f=y=>{let{percentage:w,processedObjects:v,totalObjects:R,step:b}=y;$e(this.deps,e,w,v,R,b),u.signal.aborted||l?.updateProgress(e,w),h.progress(w,v,R,b),a.onProgress?.(y)},m=()=>{l?l.abort(e):u.abort()};a.signal?.addEventListener("abort",m,{once:!0}),a.signal?.aborted&&m();try{let y=await t.takeCheckpoint({org:t.takeOrgOf(n),store:r,handler:this.deps,signal:u.signal,onProgress:f,runWriting:a.runWriting??this.runWriting(o.id,d,"take the checkpoint","No record was read.")},{...this.takeRequestOf(o,i),...i.name!==void 0?{name:i.name}:{},...i.nameWithDate!==void 0?{nameWithDate:i.nameWithDate}:{},keepDays:i.keepDays,...i.ignoredFields?{ignoredFields:i.ignoredFields}:{},...i.unprovenLeftOut===!0?{unprovenLeftOut:!0}:{},...i.beforeRun!==void 0?{beforeRun:i.beforeRun}:{}});if(!y.taken)throw pe(this.deps,e,{status:"refused",code:y.refusal.code}),h.fail(y.refusal.message),p(new Error(y.refusal.message)),this.refusalOf(y.refusal);for(let{objectApiName:R,reason:b}of y.notChecked)this.deps.log(`[WARN] checkpoint:take ${e}: what moved in ${R} while it was read was not checked: ${b}`);let{checkpoint:w}=y,v={checkpoint:w,...y.requests?{requests:y.requests}:{},estimate:y.estimate};return a.kept?.(v),this.checkpointsChanged(),pe(this.deps,e,{status:"success",objects:w.objects.length,records:w.objects.reduce((R,b)=>R+b.records,0)}),h.complete(),p(),v}catch(y){throw y instanceof Pe?y:y instanceof t.CheckpointTakeStopped?(l?.abort(e),pe(this.deps,e,{aborted:!0}),h.cancel(),p(),new Pe(Fr,y.message,!0)):(pe(this.deps,e,{status:"failure"}),h.fail(T(y)),p(y),y)}finally{a.signal?.removeEventListener("abort",m)}}async handlePreview(e){let t=D(fh,e,"checkpoint:error",this.deps);if(t)try{let r=await this.modules(),n=await this.openedStore(),{folder:o,checkpoint:i}=await this.checkpointOf(n,t.checkpointId);this.usable(r,i,"preview");let a=Id(i,t.objects),d=this.connectedOrgOf(i,`preview the checkpoint '${i.name}'`),c=await this.connect(d),l=await r.previewCheckpoint({org:r.takeOrgOf(c),store:n,readAutomation:u=>this.readAutomation(d.id,u),runWriting:this.runWriting(d.id,ft(d),"rewind","No record would be read or written."),...t.muteAutomation===!0?{mute:this.muteOf(c)}:{}},{checkpoint:i,folder:o,orgName:ft(d),registered:d,username:d.username,...a!==void 0?{objects:a}:{},...this.previewsAnswered!==void 0?{reusesPreview:!0}:{},...t.muteAutomation===!0?{muteAutomation:!0}:{},...t.acceptOutside!==void 0?{acceptOutside:t.acceptOutside}:{}});if(!l.previewed)throw this.refusalOf(l.refusal);this.previewsAnswered?.set(l.diff.previewId,l.diff),this.previewReads.set(l.diff.previewId,{checkpointId:i.checkpointId,readAt:l.diff.readAt}),this.respond(e,"checkpoint:preview:response",{diff:l.diff,...l.automation?{automation:l.automation}:{},...l.emails?{emails:l.emails}:{},...l.emailsKeepingOutside?{emailsKeepingOutside:l.emailsKeepingOutside}:{},...l.emailsUncounted!==void 0?{emailsUncounted:l.emailsUncounted}:{},...l.deliverability?{deliverability:l.deliverability}:{},estimate:l.estimate,...l.refusal?{refusal:l.refusal}:{}})}catch(r){this.fail(e,r,"PREVIEW_ERROR")}}async handlePlanSelection(e){let t=D(mh,e,"checkpoint:error",this.deps);if(t)try{let r=await this.modules(),n=await this.openedStore(),{folder:o,checkpoint:i}=await this.checkpointOf(n,t.checkpointId);this.usable(r,i,"preview");let a=Id(i,t.objects)??[],d=r.previewDirOf(o,t.previewId),c=this.previewReads.get(t.previewId);if(c?.checkpointId!==i.checkpointId||!await ek(d))throw new Pe("PREVIEW_GONE",`The preview to plan this selection from is no longer kept on this machine: preview the rewind to '${i.name}' again. No record was read or written.`);let l=await r.planSelection({checkpoint:i,previewDir:d,readAt:c.readAt,objects:new Set(a),acceptOutside:t.acceptOutside,heldRows:r.snapshotRowsOf(i,o)});this.respond(e,"checkpoint:plan-selection:response",{checkpointId:i.checkpointId,previewId:t.previewId,plan:l})}catch(r){this.fail(e,r,"PLAN_SELECTION_ERROR")}}async handleRewind(e){let t=D(hh,e,"checkpoint:error",this.deps);if(!t)return;let n=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(e.id);try{let o=await this.modules(),i=await this.openedStore(),{folder:a,checkpoint:d}=await this.checkpointOf(i,t.checkpointId);this.usable(o,d,"rewind");let c=Id(d,t.objects);if(!await ek(o.previewDirOf(a,t.previewId)))throw new Pe("PREVIEW_GONE",`The preview this rewind was confirmed on is no longer kept on this machine: preview the rewind to '${d.name}' again, then rewind. No record was read or written.`);let l=this.connectedOrgOf(d,`rewind it to the checkpoint '${d.name}'`),u=await this.connect(l),p=this.pageAt(e);if(n?.signal.aborted)throw this.audit(p,"rewind",l,d,"stopped",{code:gt}),new Pe(Fr,new o.RewindStopped().message,!0);let g=this.previewsAnswered?.get(t.previewId);this.previewsAnswered?.delete(t.previewId);let h=g?.checkpointId===d.checkpointId?g:void 0,f=ft(l);await this.writeAct(p,"rewind",l,d,`Rewinding ${f} to '${d.name}'`,async(m,y)=>{let w=await o.rewindOrg({org:o.rewindOrgOf(u),undelete:R=>u.soap.undelete(R),store:i,readAutomation:R=>this.readAutomation(l.id,R),runWriting:this.runWriting(l.id,f,"rewind","No record was read or written."),onUndeletable:Tr(this.deps,l.id,"checkpoint:rewind"),onProgress:({percentage:R,step:b})=>y(R,b),signal:m,...t.muteAutomation===!0?{mute:this.muteOf(u)}:{}},{checkpoint:d,folder:a,orgName:f,registered:l,username:l.username,previewId:t.previewId,...h?{reusesPreview:h}:{},...c!==void 0?{objects:c}:{},acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails===!0,canMute:!0,acceptNoUndo:t.acceptNoUndo,acceptRecreate:t.acceptRecreate,acceptOutside:t.acceptOutside,acceptUnseen:t.acceptUnseen});if(w.rewound)return Mu(w);let v=t.fromPage===!0;return ju(w.refusal,w.alsoRefused,R=>v?o.pageEmailsRefusal(R,"rewind",f):R,v)},m=>m instanceof o.RewindStopped,{acceptEmails:t.acceptEmails===!0})}catch(o){this.fail(e,o,"REWIND_ERROR")}finally{n?.release()}}async handleUndo(e){let t=D(bh,e,"checkpoint:error",this.deps);if(!t)return;let n=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(e.id);try{let o=await this.modules(),i=await this.openedStore(),{folder:a,checkpoint:d}=await this.checkpointOf(i,t.checkpointId);this.usable(o,d,"undo"),await this.undoOffered(i,a,d,t.rewindId);let c=this.connectedOrgOf(d,`undo its rewind to '${d.name}'`),l=await this.connect(c),u=this.pageAt(e);if(n?.signal.aborted)throw this.audit(u,"undo",c,d,"stopped",{code:gt,rewindId:t.rewindId}),new Pe(Fr,new o.UndoStopped().message,!0);let p=ft(c);await this.writeAct(u,"undo",c,d,`Undoing the rewind of ${p} to '${d.name}'`,async(g,h)=>{let f=await o.undoCheckpoint({org:o.rewindOrgOf(l),undelete:y=>l.soap.undelete(y),store:i,readAutomation:y=>this.readAutomation(c.id,y),runWriting:this.runWriting(c.id,p,"undo the rewind","No record was read or written."),onUndeletable:Tr(this.deps,c.id,"checkpoint:undo"),onProgress:({percentage:y,step:w})=>h(y,w),signal:g,...t.muteAutomation===!0?{mute:this.muteOf(l)}:{}},{checkpoint:d,folder:a,orgName:p,registered:c,username:c.username,rewindId:t.rewindId,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails===!0,canMute:!0});if(f.undone)return Mu(f);let m=t.fromPage===!0;return ju(f.refusal,f.alsoRefused,y=>m?o.pageEmailsRefusal(y,"undo",p):y,m)},g=>g instanceof o.UndoStopped,{rewindId:t.rewindId,acceptEmails:t.acceptEmails===!0})}catch(o){this.fail(e,o,"UNDO_ERROR")}finally{n?.release()}}muteOf(e){return(t,r)=>mt(async()=>Et(e),t,{...this.muteLeases,writes:r})}pageAt(e){return{operationId:e.id,respond:(t,r)=>this.respond(e,t,r)}}async writeAct(e,t,r,n,o,i,a,d={}){let{operationId:c}=e,{rewindId:l}=d,u=this.deps.infraServices?.backgroundRegistry,p=new AbortController,g=()=>{},h=new Promise((v,R)=>{g=b=>b===void 0?v():R(b)});h.catch(()=>{}),We(this.deps,c,hr,o),u?.register(c,hr,o,h,p);let f=Jt(this.liveTracker,c,hr,o),m=l!==void 0?{rewindId:l}:{},y=(v,R)=>{$e(this.deps,c,v,0,0,R),p.signal.aborted||u?.updateProgress(c,v),f.progress(v,0,0,R)},w=()=>{u?u.abort(c):p.abort()};d.signal?.addEventListener("abort",w,{once:!0}),d.signal?.aborted&&w();try{let v=await i(p.signal,y);if(!v.done)throw this.audit(e,t,r,n,"stopped",{code:v.refusal.code,...m}),pe(this.deps,c,{status:"refused",code:v.refusal.code}),f.fail(v.refusal.message),g(new Error(v.refusal.message)),this.refusalOf(v.refusal,v.alsoRefused);let{result:R,notes:b,deliverability:O}=v,k={...O!==void 0?{deliverability:O}:{},...d.acceptEmails===!0?{acceptEmails:!0}:{}};for(let E of b)this.deps.log(`[WARN] checkpoint:${t} ${c}: ${E}`);for(let E of R.removedJournals??[])this.deps.log(`[INFO] Removed the journal of rewind ${E.rewindId} of checkpoint '${E.name}': Undo reaches the last rewind of the org alone`);let S=d.refusalOf?.(R);if(S!==void 0)throw this.audit(e,t,r,n,QS(R)?"partial":"stopped",{result:R,code:S.code,...k}),pe(this.deps,c,{status:"refused",code:S.code}),f.fail(S.message),g(new Error(S.message)),new Pe(S.code,S.message,!1,R);if(this.audit(e,t,r,n,qP[R.status],{result:R,...k}),e.respond?.(`checkpoint:${t}:response`,{result:R,operationId:c}),R.status==="cancelled")u?.abort(c),pe(this.deps,c,{aborted:!0}),f.cancel(),g();else if(R.status==="failure"){let E=`Nothing the ${t} set out to write went through: its result says why.`;pe(this.deps,c,{status:R.status}),f.fail(E),g(new Error(E))}else pe(this.deps,c,{status:R.status}),R.status==="success"?f.complete():f.partial(),g();return R}catch(v){if(v instanceof Pe)throw v;if(a(v))throw u?.abort(c),pe(this.deps,c,{aborted:!0}),f.cancel(),g(),this.audit(e,t,r,n,"stopped",{code:Fr,...m}),new Pe(Fr,T(v),!0);let R=ps(v);throw this.audit(e,t,r,n,"failure",{...m,...R?{muted:R}:{}}),this.unreleased(e,t,r,R),pe(this.deps,c,{status:"failure"}),f.fail(T(v)),g(v),v}finally{d.signal?.removeEventListener("abort",w)}}unreleased(e,t,r,n){n?.released===!1&&this.deps.log(`[WARN] checkpoint:${t} ${e.operationId}: `+_t(n,ft(r)).map(o=>o.trim()).join("; "))}readAutomation(e,t){let r=this.targetAutomation;return new ge(BP).withTimeout("checkpoint:preview automation",()=>r.read(e,t,{undeletes:!0}))}ownReader(){return this.reader??=import("./chunk-4XZ5YT5O.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handleDelete(e){let t=D(Rh,e,"checkpoint:error",this.deps);if(t)try{let r=await this.openedStore(),n=[],o=[];for(let i of t.checkpointIds){let a=await r.delete(i);a.outcome==="deleted"?n.push(i):a.outcome==="busy"&&o.push(a.holder)}for(let i of o)this.deps.log(`[WARN] checkpoint:delete: kept while ${Nu(i)}`);if(n.length===0&&o.length>0)throw new Pe("RUN_WRITING",`The checkpoint was not deleted: ${Nu(o[0])}. Delete it once that has ended.`,!0);this.respond(e,"checkpoint:delete:response",{deleted:n}),n.length>0&&this.checkpointsChanged()}catch(r){this.fail(e,r,"DELETE_ERROR")}}async handleKeep(e){let t=D(vh,e,"checkpoint:error",this.deps);t&&await this.change(e,t.checkpointId,"keep",r=>r.keep(t.checkpointId,t.keep))}async handleRename(e){let t=D(Sh,e,"checkpoint:error",this.deps);t&&await this.change(e,t.checkpointId,"rename",r=>r.update(t.checkpointId,n=>({...n,name:t.name})))}async handleIgnoreFields(e){let t=D(kh,e,"checkpoint:error",this.deps);t&&await this.change(e,t.checkpointId,"ignore-fields",r=>r.update(t.checkpointId,n=>({...n,ignoredFields:t.fields})))}async handleRewinds(e){let t=D(Oh,e,"checkpoint:error",this.deps);if(t!==null)try{let r=await this.openedStore(),{readRewindLedgers:n}=await import("./chunk-RACDTRZA.mjs"),i=(t?.orgIds??this.deps.orgManager.getAllOrgs().map(c=>c.id)).map(c=>({orgId:c,ids:this.organizationIdsOf(c)})),a=await n(r.root,i.flatMap(({ids:c})=>c)),d=[];for(let[c,l]of a){for(let u of l.unreadable)this.deps.log(`[WARN] Line ${u} of the rewind ledger of ${c} does not parse: left out`);for(let u of l.records){let p=i.filter(({ids:g})=>g.some(h=>Qt(h,u.organizationId)));d.push({...u,orgIds:p.map(({orgId:g})=>g)})}}this.respond(e,"checkpoint:rewinds:response",{rewinds:d})}catch(r){this.fail(e,r,"REWINDS_ERROR")}}async change(e,t,r,n){try{let o=await this.modules(),i=await this.openedStore(),{folder:a}=await this.checkpointOf(i,t),d=i.heldBy(a.organizationId);if(d!==void 0&&(d.checkpointId===void 0||d.checkpointId===t))throw new Pe("RUN_WRITING",`The checkpoint was not changed: ${Nu(d)}. Change it once that has ended.`,!0);let c;try{c=await n(i)}catch(l){throw l instanceof o.CheckpointStoreError?new Pe(l.code==="notFound"?"NOT_FOUND":l.code==="damaged"?"DAMAGED":"INVALID",l.message):l}this.respond(e,`checkpoint:${r}:response`,{checkpoint:c}),this.checkpointsChanged()}catch(o){this.fail(e,o,"CHANGE_ERROR")}}};var dk={apiLimits:"apiLimits",storage:"storage",recentErrors:"recentErrors",failedJobs:"activeJobs"},$u=Object.keys(dk),ok={apiLimits:{variable:Jo.apiLimits,read:s=>s.percent},storage:{variable:Jo.storage,read:s=>s.percent},recentErrors:{variable:Jo.recentErrors,read:s=>s.count},failedJobs:{variable:Jo.failedJobs,read:s=>s.count}},ck=500,lk=G({orgId:cf,checks:ke(Xe(["apiLimits","storage","recentErrors","failedJobs"])).min(1).refine(s=>new Set(s).size===s.length)}),uk=G({message:L().trim().min(1).max(ck)});function Ot(s,e){return`${s} ${e}${s===1?"":"s"}`}function yr(s,e,t,r){let n=new Date().toISOString();return{stepId:s.id,stepName:s.name,stepType:s.type,status:"completed",output:t,summary:r,startTime:e,endTime:n,duration:new Date(n).getTime()-new Date(e).getTime()}}function wt(s,e,t,r){let n=new Date().toISOString();return{stepId:s.id,stepName:s.name,stepType:s.type,status:"failed",output:t,error:r,startTime:e,endTime:n,duration:new Date(n).getTime()-new Date(e).getTime()}}function mr(s,e,t,r){if(typeof t!="string"||t.trim()==="")return`${e} names no org: choose ${r}.`;if(s.orgName(t)===void 0)return`${e} names an org SandForge does not know (${t}): connect it, or choose ${r} again.`}function Uu(s){return Array.isArray(s)&&s.length>0?s:void 0}function YP(s){return e=>{let t=`Backup step "${e.name}"`,r=e.config??{},n=mr(s,t,r.orgId,"the org it backs up");if(n)return n;let o=Uu(r.objects);if(!o)return`${t} names no object: list the API names of the objects it backs up.`;let i=o.filter(a=>!lf.safeParse(a).success);if(i.length>0)return`${t} names what is not an object API name: ${i.map(String).join(", ")}.`;if(!sl.safeParse({orgId:r.orgId,objects:o}).success)return`${t} backs up more objects than one backup takes: at most 100.`}}function QP(s){return e=>{let t=`Compare step "${e.name}"`,r=e.config??{},n=mr(s,t,r.sourceOrgId,"the org it compares from")??mr(s,t,r.targetOrgId,"the org it compares with");if(n)return n;if(r.sourceOrgId===r.targetOrgId)return`${t} compares an org with itself: choose two different orgs.`;let o=Uu(r.types);if(!o)return`${t} names no component type: choose what it compares.`;if(!ns.safeParse({sourceOrgId:r.sourceOrgId,targetOrgId:r.targetOrgId,types:o}).success)return`${t} names component types the Compare page would not send: at most 50, each a type name.`}}function ZP(s){return e=>{let t=`Pre-check step "${e.name}"`,r=e.config??{},n=mr(s,t,r.orgId,"the org it checks");if(n)return n;let o=Uu(r.checks);if(!o)return`${t} names no check: choose what it checks (${$u.join(", ")}).`;let i=o.filter(a=>typeof a!="string"||!$u.includes(a));if(i.length>0)return`${t} names checks SandForge does not have: ${i.map(String).join(", ")}. It can check ${$u.join(", ")}.`;if(!lk.safeParse({orgId:r.orgId,checks:o}).success)return`${t} names the same check twice.`}}function eC(s){return e=>{let t=`Notification step "${e.name}"`;if(!s.notify)return`${t} cannot show a notification: there is no VS Code window to show it in.`;let r=(e.config??{}).message;if(typeof r!="string"||r.trim()==="")return`${t} has no message: write what the notification says.`;if(!uk.safeParse({message:r}).success)return`${t} has a message longer than ${ck} characters.`}}function tC(s){return async(e,t)=>{let r=new Date().toISOString(),{orgId:n,objects:o}=sl.parse({orgId:e.config.orgId,objects:e.config.objects}),i=await s.backup({operationId:s.newId(),orgId:n,objects:o},t.signal),a=s.orgName(n)??n,d=i.objects.filter(l=>l.truncated).map(l=>l.objectApiName),c=`Backed up ${Ot(i.totalRecords,"record")} of ${Ot(i.objects.length,"object")} from ${a}`+(d.length>0?`; only part of ${d.join(", ")}: the org holds more rows than one backup reads.`:".");return yr(e,r,{operationId:i.operationId,orgId:n,objects:i.objects,totalRecords:i.totalRecords,partial:i.partial},c)}}function rC(s){return async(e,t)=>{let r=new Date().toISOString(),{sourceOrgId:n,targetOrgId:o,types:i}=ns.parse({sourceOrgId:e.config.sourceOrgId,targetOrgId:e.config.targetOrgId,types:e.config.types}),a=await s.compare({sourceOrgId:n,targetOrgId:o,types:i},t.signal),{added:d,removed:c,modified:l,unchanged:u,notCompared:p}=a.summary,g=s.orgName(n)??n,h=s.orgName(o)??o;return yr(e,r,{sourceOrgId:n,targetOrgId:o,types:i,summary:a.summary,content:a.content,variables:{[ig]:String(d+c+l)}},`Compared ${Ot(i.length,"component type")} of ${g} with ${h}: ${c} only in ${g}, ${d} only in ${h}, ${l} modified, ${u} unchanged, ${p} not compared.`)}}function sk(s){switch(s.status){case"critical":return`${s.message} (critical)`;case"unknown":return`${s.message} (could not be read)`;case"warning":return`${s.message} (warning)`;default:return s.message}}function nC(s){return async e=>{let t=new Date().toISOString(),{orgId:r,checks:n}=lk.parse({orgId:e.config.orgId,checks:e.config.checks}),o=s.orgName(r)??r,i=await s.readOrgHealth(r,n.map(u=>dk[u])),a=n.map((u,p)=>({check:u,signal:i[p]})),d={};for(let{check:u,signal:p}of a){let g=p?ok[u].read(p):void 0;g!==void 0&&p.status!=="unknown"&&(d[ok[u].variable]=String(g))}let c={orgId:r,checks:a.map(({check:u,signal:p})=>({check:u,status:p?.status??"unknown",message:p?.message??"Not read"})),variables:d},l=a.filter(({signal:u})=>!u||u.status==="critical"||u.status==="unknown");return l.length>0?wt(e,t,c,`Pre-check "${e.name}" failed on ${o}: ${l.map(({check:u,signal:p})=>p?sk(p):`${u} was not read`).join("; ")}.`):yr(e,t,c,`${a.length===1?"The check":`${a.length} checks`} passed on ${o}: ${a.map(({signal:u})=>sk(u)).join("; ")}.`)}}function oC(s){return async(e,t)=>{let r=new Date().toISOString(),{message:n}=uk.parse({message:e.config.message});return s.notify?(s.notify(t.pipelineName?`${t.pipelineName}: ${n}`:n),yr(e,r,{message:n},"Showed a notification in VS Code.")):wt(e,r,{},`Notification step "${e.name}" cannot show a notification: there is no VS Code window to show it in.`)}}function sC(s){return e=>{let t=`Approval step "${e.name}"`;if(!s.askApproval)return`${t} cannot ask anyone: there is no VS Code window to ask in.`;switch(ug(e.config)){case"timeout":return`${t} waits for a time it cannot keep: set a whole number of minutes from 1 to ${dg} (a day).`;case"message":return`${t} has a message that is not text, or is longer than ${cg} characters.`;default:return}}}function ik(s){return s.via==="page"?" on the Automation page":s.via==="notification"?" in the VS Code notification":""}function iC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Approval step "${e.name}"`;if(!s.askApproval)return wt(e,r,{},`${n} cannot ask anyone: there is no VS Code window to ask in.`);let o=lg(e.config)??ag,i=e.config?.message,a=typeof i=="string"&&i.trim()!==""?i.trim():void 0,d=await s.askApproval({stepId:e.id,stepName:e.name,...t.pipelineName?{pipelineName:t.pipelineName}:{},...a?{message:a}:{},timeoutMs:o*6e4},t.signal),c={approval:d};switch(d.decision){case"approved":return{...yr(e,r,c,`Approved${ik(d)} at ${d.at}.`),approval:d};case"rejected":return{...wt(e,r,c,`${n} was rejected${ik(d)} at ${d.at}.`),approval:d};case"timedOut":return{...wt(e,r,c,`${n} was not approved in time: nobody answered within ${Ot(o,"minute")}.`),approval:d};case"cancelled":return{...wt(e,r,c,`${n} was stopped before anyone answered.`),approval:d}}}}function pk(s,e){let t=`Sync step "${e.name}"`,r=(e.config??{}).configId;if(typeof r!="string"||r.trim()==="")return{problem:`${t} names no saved Sync configuration: choose the one it runs.`};let n=s.savedSyncConfig?.(r);if(n==null)return{problem:`${t} names a Sync configuration that is no longer saved (${r}): choose another.`};let o=kn.safeParse({config:n});if(!o.success){let d=o.error.issues[0];return{problem:`${t} names a Sync configuration that no longer validates (${d.path.slice(1).join(".")}: ${d.message}): open it on the Sync page and save it again.`}}let i=n,a=typeof i.name=="string"&&i.name!==""?i.name:r;return{config:i,name:a}}function gk(s){return(s.listSyncConfigs?.()??[]).flatMap(t=>{if(typeof t!="object"||t===null)return[];let{id:r,name:n}=t;if(typeof r!="string"||r==="")return[];let o=typeof n=="string"&&n!==""?n:r;if(!kn.safeParse({config:t}).success)return[{id:r,name:o,valid:!1}];let i=t;return[{id:r,name:o,valid:!0,sourceOrgId:i.sourceOrgId,targetOrgId:i.targetOrgId,...s.syncGuard?{guard:s.syncGuard(i).decision}:{}}]})}function fk(s){return s===void 0||s.steps.slice(0,s.index).some(e=>e.type==="approval")}function aC(s){return(e,t)=>{let r=`Sync step "${e.name}"`;if(!s.runSync||!s.savedSyncConfig||!s.syncGuard)return`${r} cannot run here: Sync is not available in this window.`;let n=pk(s,e);if("problem"in n)return n.problem;let{config:o}=n,i=mr(s,r,o.sourceOrgId,"the source org of its configuration")??mr(s,r,o.targetOrgId,"the target org of its configuration");if(i)return i;let a=s.syncGuard(o);if(a.decision==="refused")return`${r} writes where Production Guard refuses it, whatever anyone answers: ${a.reason}.`;if(a.decision==="asks"&&!fk(t)){let d=s.orgName(o.targetOrgId)??o.targetOrgId;return`${r} writes to ${d}, which Production Guard asks about before a write, and nobody may be there to answer when the pipeline runs: put an Approval step before it.`}}}function Hu(s){let e=s.previousResults.filter(r=>r.stepType==="approval"),t=e[e.length-1];return{approved:t?.status==="completed"&&t.approval?.decision==="approved"}}function dC(s){return async(e,t)=>{let r=new Date().toISOString(),n=pk(s,e);if("problem"in n)throw new Error(n.problem);if(!s.runSync)throw new Error(`Sync step "${e.name}" cannot run here: Sync is not available in this window.`);let{config:o,name:i}=n,a=await s.runSync(o,Hu(t),t.signal);if(a.cancelled)throw new xt(`Sync step "${e.name}" was cancelled: ${a.error??"the run stopped before it synced every object."}`);let d=s.orgName(o.targetOrgId)??o.targetOrgId,c=a.summary,l={configId:o.id,configName:i,operationId:a.operationId,status:a.status,totalProcessed:a.totalProcessed,totalSuccess:a.totalSuccess,totalFailed:a.totalFailed,totalSkipped:a.totalSkipped,objects:a.objectResults.map(p=>({objectApiName:p.objectApiName,operation:p.operation,processed:p.processed,success:p.success,failed:p.failed,skipped:p.skipped})),...typeof c=="object"&&c!==null?{summary:c}:{}},u=`${Ot(a.totalSuccess,"record")} written, ${a.totalFailed} failed and ${a.totalSkipped} skipped of ${a.totalProcessed} read`;return a.status!=="success"?wt(e,r,l,`Sync step "${e.name}" ran "${i}" into ${d} and did not complete: ${u}`+(a.error?`; ${a.error}`:".")):yr(e,r,l,`Synced "${i}" into ${d}: ${u}.`)}}function pn(s){return typeof s=="string"&&s.trim()!==""?s.trim():void 0}function Bu(s){let e=s.issues[0];return e?e.path.length>0?`${e.path.join(".")}: ${e.message}`:e.message:"its configuration is not one"}function cC(s,e){return s!==void 0&&e!==void 0&&s.length>=15&&s.slice(0,15)===e.slice(0,15)}function Td(s){return s.pipelineName??s.pipelineId}function hk(s,e,t,r,n){let o=s.orgName(t)??t,i=oi(s.orgTier?.(t)??"production");if(i==="refused")return`${e} writes to ${o}, a production org or one SandForge cannot tell is not: a pipeline never ${r} one, whatever an Approval step answers. Choose a sandbox, a scratch org or a Developer Edition org.`;if(i==="needsApproval"&&!fk(n))return`${e} writes to ${o}, a sandbox marked Staging, which a pipeline ${r} only once an Approval step before it has approved the run: put an Approval step before it.`}function mk(s,e,t){return s.retries!==void 0&&s.retries>0?`${e} is given retries, and is never tried again: ${t}. Set its retries to 0.`:void 0}function yk(s){if(s instanceof xt)return;let e=s?.code;return typeof e=="string"?e:void 0}function lC(s){return(e,t)=>{let r=`Seed step "${e.name}"`;if(!s.seed||!s.savedSeedTemplate)return`${r} cannot run here: Seed is not available in this window.`;let n=e.config??{},o=mr(s,r,n.orgId,"the org it seeds");if(o)return o;let i=pn(n.templateId);if(i===void 0)return`${r} names no Seed template: choose the one it seeds with.`;let a=String(n.orgId),d=ja(a,i,c=>s.savedSeedTemplate?.(c));return"refusal"in d?`${r}: ${d.refusal.message}`:mk(e,r,"a second try would write a second set of records")??hk(s,r,a,"seeds",t)}}function uC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Seed step "${e.name}"`;if(!s.seed)throw new Error(`${n} cannot run here: Seed is not available in this window.`);let{orgId:o,templateId:i}=pg.parse({orgId:e.config.orgId,templateId:pn(e.config.templateId)}),a=s.orgName(o)??o,d;try{d=await s.seed({orgId:o,templateId:i,pipeline:{name:Td(t)},answer:Hu(t)},t.signal)}catch(g){let h=yk(g);if(h===void 0)throw g;return wt(e,r,{orgId:o,templateId:i,code:h},`${n}: ${g.message}`)}let{result:c}=d,l={orgId:o,templateId:i,operationId:d.operationId,runId:d.runId,status:c.status,totalRecordsCreated:c.totalRecordsCreated,totalRecordsFailed:c.totalRecordsFailed,objects:c.objectResults.map(g=>({objectApiName:g.objectApiName,recordsCreated:g.recordsCreated,recordsFailed:g.recordsFailed})),...d.automation.length>0?{automation:d.automation}:{}},u=Ot(c.totalRecordsCreated,"record"),p="take them back from Seed's Recent runs";if(c.cancelled)throw new xt(`${n} was cancelled: it had created ${u} in ${a}, which stay there; ${p}.`);return c.status!=="success"?wt(e,r,l,`${n} seeded ${a} and did not complete: ${u} created, ${c.totalRecordsFailed} refused; ${p}.`):yr(e,r,l,`Seeded ${u} into ${a}: ${p}.`)}}function wk(s){let e=(s.listSeedTemplates?.()??[]).map(n=>({raw:n,builtIn:!1})),t=Qs.map(n=>({raw:n,builtIn:!0})),r=new Set;return[...e,...t].flatMap(({raw:n,builtIn:o})=>{if(typeof n!="object"||n===null)return[];let{id:i,name:a}=n;if(typeof i!="string"||i===""||r.has(i))return[];r.add(i);let d=typeof a=="string"&&a!==""?a:i,c=ro.safeParse(n);return[{id:i,name:d,builtIn:o,valid:c.success,usesAi:c.success&&Kl(c.data).length>0}]})}function pC(s){let e=[];for(let t of s.rules){let r=t.fieldPattern.split(".")[0];r&&!e.includes(r)&&e.push(r)}return e}function bk(s){return(s.maskingTemplates?.()??[]).map(e=>({id:e.id,name:e.name,builtIn:e.builtIn,objects:pC(e)}))}function gC(s){return(e,t)=>{let r=`Anonymize step "${e.name}"`;if(!s.anonymize||!s.maskingTemplates)return`${r} cannot run here: DataOps is not available in this window.`;let n=e.config??{},o=mr(s,r,n.orgId,"the org it masks");if(o)return o;let i=pn(n.templateId);if(i===void 0)return`${r} names no masking template: choose the one it masks with.`;let a=String(n.orgId),d=s.maskingTemplates(),c=pn(n.object),l=pn(n.where),u=Py({orgId:a,templateId:i,...c!==void 0?{object:c}:{},...l!==void 0?{where:l}:{},...e.retries!==void 0?{retries:e.retries}:{}},g=>d.some(h=>h.id===g));if("refusal"in u)return`${r}: ${u.refusal.message}`;let p=zc.safeParse({orgId:a,templateId:i,...Rk(n)});return p.success?hk(s,r,a,"masks",t):`${r} does not read (${Bu(p.error)}).`}}function Rk(s){return Object.fromEntries(["acceptAutomation","acceptEmails","muteAutomation"].flatMap(e=>s[e]===void 0?[]:[[e,s[e]]]))}var ak=3;function fC(s){let e=[...new Set(s.errors.map(r=>`${r.objectApiName}: ${r.message}`))];if(e.length===0)return s.message?` (${s.message})`:"";let t=e.length-ak;return`, refused by the org: ${e.slice(0,ak).join("; ")}`+(t>0?`; and ${Ot(t,"other reason")}`:"")}function hC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Anonymize step "${e.name}"`;if(!s.anonymize)throw new Error(`${n} cannot run here: DataOps is not available in this window.`);let o=pn(e.config.object),i=pn(e.config.where),{orgId:a,templateId:d,acceptAutomation:c,acceptEmails:l,muteAutomation:u}=zc.parse({orgId:e.config.orgId,templateId:pn(e.config.templateId),...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...Rk(e.config)}),p=s.orgName(a)??a,g=b=>b?` ${_t(b,p).map(O=>O.trim()).join("; ")}.`:"",h;try{h=await s.anonymize({orgId:a,templateId:d,...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...e.retries!==void 0?{retries:e.retries}:{},accord:{acceptAutomation:c,acceptEmails:l,muteAutomation:u},pipeline:{name:Td(t)},answer:Hu(t)},t.signal)}catch(b){let O=yk(b);if(O===void 0)throw b;let k=b.snapshot,S=ps(b);return wt(e,r,{orgId:a,templateId:d,code:O,...k!==void 0?{snapshot:k}:{},...S?{mutedAutomation:S}:{}},`${n}: ${b.message}`+(typeof k?.operationId=="string"?` The snapshot ${k.operationId} it took keeps the values it wrote over, in clear, until it is deleted on the DataOps page.`:"")+g(S))}let{result:f}=h,m=f.snapshot?`the snapshot ${f.snapshot.operationId} keeps the values it wrote over, in clear, until it is deleted on the DataOps page, where a restore writes them back`:"no snapshot was kept",y={orgId:a,templateId:d,...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},operationId:h.operationId,status:f.status,recordsProcessed:f.recordsProcessed,recordsFailed:f.recordsFailed,recordsNotMasked:f.recordsNotMasked,objects:f.objects,message:f.message,errors:f.errors,...f.snapshot?{snapshot:f.snapshot}:{},...f.mutedAutomation?{mutedAutomation:f.mutedAutomation}:{}},w=g(f.mutedAutomation);if(f.cancelled)throw new xt(`${n} was cancelled: it masked ${Ot(f.recordsProcessed,"record")} in ${p} before the stop, and ${f.recordsNotMasked} still hold their values; ${m}.`+w);let v=f.objects.filter(b=>b.notMasked>0);if(f.recordsNotMasked>0){let b=`${v.map(O=>`${O.notMasked} of ${O.objectApiName}`).join(", ")} still hold their values${fC(f)}`;return wt(e,r,y,`${n} masked ${p} and did not complete: ${b}; ${m}.${w}`)}let R=o!==void 0?i!==void 0?`the ${o} rows where ${i}`:`every ${o} row`:`every row of ${f.objects.map(b=>b.objectApiName).join(", ")}`;return yr(e,r,y,`Masked ${Ot(f.recordsProcessed,"record")} in ${p}, ${R}; ${m}.${w}`)}}function mC(s){return e=>{let t=`Checkpoint step "${e.name}"`;if(!s.takeCheckpoint)return`${t} cannot run here: Checkpoints are not available in this window.`;let r=e.config??{},n=mr(s,t,r.orgId,"the org it takes");if(n)return n;let o=String(r.orgId);if((s.orgTier?.(o)??"production")==="production")return`${t} names ${s.orgName(o)??o}, a production org or one SandForge cannot tell is not: SandForge takes no checkpoint of one.`;let i=Vo.safeParse(r);if(!i.success)return`${t} does not read (${Bu(i.error)}).`}}function yC(s){return s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:s<1024*1024*1024?`${(s/1024/1024).toFixed(1)} MB`:`${(s/1024/1024/1024).toFixed(2)} GB`}function wC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Checkpoint step "${e.name}"`;if(!s.takeCheckpoint)throw new Error(`${n} cannot run here: Checkpoints are not available in this window.`);let o=Vo.parse(e.config),i=s.orgName(o.orgId)??o.orgId,a;try{a=await s.takeCheckpoint({config:o,origin:{pipeline:Td(t),step:e.name,trigger:s.trigger??"manual"}},t.signal)}catch(l){if(!(l instanceof Bn))throw l;return wt(e,r,{orgId:o.orgId,code:l.code},l.message)}let d=a.movedWhileTaken,c=d.changed+d.deleted+d.created;return yr(e,r,{orgId:o.orgId,operationId:a.operationId,checkpointId:a.checkpointId,name:a.name,records:a.records,objects:a.objects,bytes:a.bytes,movedWhileTaken:d},`Took the checkpoint '${a.name}' of ${i}: ${Ot(a.records,"record")} of ${Ot(a.objects,"object")}, ${yC(a.bytes)} on this machine, `+(o.keepDays===0?"kept until it is deleted":`kept ${Ot(o.keepDays,"day")}`)+(c>0?`; ${Ot(c,"record")} changed while it was taken.`:"."))}}var bC={damaged:"whose file cannot be read: it can only be deleted",taking:"whose take is under way or never ended",failed:"whose take failed: it can only be deleted",refreshed:"of the org a sandbox was before its refresh: the sandbox is another org now, and the checkpoint can only be deleted. Take a checkpoint of it again, and choose it",scratchExpired:"of a scratch org that has expired: it can only be deleted"};function vk(s,e,t,r){let n=s.checkpointKept?.(r);if(n===void 0)return;if(!n.kept)return{why:"missing",problem:`${e} rewinds to the checkpoint ${r}, which is not kept on this machine: it was deleted or expired, or the pipeline came from another machine. Take a checkpoint here, choose it, and confirm the step again.`};let o=n.name!==void 0?`'${n.name}'`:r;if(!n.valid){let a=n.why??"damaged";return{why:a,problem:`${e} rewinds to the checkpoint ${o}, ${bC[a]}.`}}let i=s.organizationIdsOf?.(t)??[];if(n.organizationId!==void 0&&!i.some(a=>cC(a,n.organizationId)))return{why:"otherOrg",problem:`${e} rewinds ${s.orgName(t)??t} to the checkpoint ${o}, which was taken of another org.`}}function RC(s){return e=>{let t=`Rewind step "${e.name}"`;if(!s.rewind||!s.rewindGrant)return`${t} cannot run here: Checkpoints are not available in this window.`;let r=e.config??{},n=mr(s,t,r.orgId,"the org it rewinds");if(n)return n;let o=String(r.orgId);if((s.orgTier?.(o)??"production")==="production")return`${t} writes to ${s.orgName(o)??o}, a production org or one SandForge cannot tell is not: SandForge rewinds none.`;let i=Ft.safeParse(r);if(!i.success)return`${t} does not read (${Bu(i.error)}).`;let a=mk(e,t,"a second try would read the org after the first one wrote, with nobody to read its preview");if(a)return a;let d=s.rewindGrant(s.pipelineId??"",e);return"refusal"in d?xu(e.name,d.refusal):vk(s,t,o,i.data.checkpointId)?.problem}}function _u(s){return{deleted:s.deleted.reduce((e,t)=>e+t.deleted,0),gaveBack:s.restored.reduce((e,t)=>e+t.restored+(t.restoredWithout??0),0),broughtBack:s.undeleted.reduce((e,t)=>e+t.undeleted,0),madeAgain:(s.recreated??[]).reduce((e,t)=>e+t.created,0)}}function Lu(s){let e=_u(s);return`${e.deleted} deleted, ${e.gaveBack} given their values back, ${e.broughtBack} brought back from the recycle bin`+(e.madeAgain>0?`, ${e.madeAgain} made again with new Ids`:"")}function Fu(s){return s.undo?`Undo on the Checkpoints page takes it back until ${s.undo.until}`:"it wrote nothing Undo would take back"}function vC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Rewind step "${e.name}"`;if(!s.rewind||!s.rewindGrant)throw new Error(`${n} cannot run here: Checkpoints are not available in this window.`);let o=Ft.parse(e.config),i=s.rewindGrant(t.pipelineId,e);if("refusal"in i)return wt(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:"NOT_CONFIRMED"},xu(e.name,i.refusal));let a=s.orgName(o.orgId)??o.orgId,d=h=>h?` ${_t(h,a).map(f=>f.trim()).join("; ")}.`:"",c;try{c=await s.rewind({config:o,grant:i.grant,origin:{pipeline:Td(t),step:e.name,trigger:s.trigger??"manual"}},t.signal)}catch(h){let f=(h instanceof Bn?h.result?.mutedAutomation:void 0)??ps(h);if(!(h instanceof Bn)){if(!f||h instanceof xt)throw h;return wt(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,mutedAutomation:f},`${T(h)}${d(f)}`)}return wt(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:h.code,...h.alsoRefused.length>0?{alsoRefused:[...h.alsoRefused]}:{},...h.result?{status:h.result.status,..._u(h.result)}:{},...f?{mutedAutomation:f}:{}},`${h.message}${d(f)}`)}let{result:l}=c,u=l.residual.reduce((h,f)=>h+f.count,0),p={orgId:o.orgId,checkpointId:c.checkpointId,operationId:c.operationId,rewindId:l.rewindId,status:l.status,..._u(l),residual:u,...l.undo?{undoUntil:l.undo.until}:{},apiRequests:l.apiRequests.used,...l.mutedAutomation?{mutedAutomation:l.mutedAutomation}:{}},g=d(l.mutedAutomation);if(l.status==="cancelled")throw new xt(`${n} was stopped part way in ${a}: ${Lu(l)}; ${Fu(l)}.${g}`);return l.status!=="success"?wt(e,r,p,`${n} rewound ${a} and did not complete (${l.status}): ${Lu(l)}; ${Ot(u,"record")} still ${u===1?"differs":"differ"} from the checkpoint`+(l.unread&&l.unread.length>0?`, and ${l.unread.map(h=>h.objectApiName).join(", ")} could not be read`:"")+`; ${Fu(l)}.${g}`):yr(e,r,p,`Rewound ${a} to the checkpoint ${c.checkpointId}: ${Lu(l)}, with ${Ot(l.apiRequests.used,"API request")}; ${Fu(l)}.${g}`)}}function Sk(s,e,t,r){let n=r?{granted:{at:r.grantedAt,digestMatches:r.matches}}:{},o=Ft.safeParse(e.config??{});if(!o.success)return{stepId:e.id,valid:!1,why:"config",...n};let{orgId:i,checkpointId:a}=o.data,d=vk({...s,checkpointKept:()=>t},"The step",i,a);return{stepId:e.id,checkpointId:a,valid:d===void 0,...d?{why:d.why}:{},...n}}function kk(s,e){s.registerHandler("backup",tC(e),YP(e)),s.registerHandler("compare",rC(e),QP(e)),s.registerHandler("precheck",nC(e),ZP(e)),s.registerHandler("notification",oC(e),eC(e)),s.registerHandler("approval",iC(e),sC(e)),s.registerHandler("sync",dC(e),aC(e)),s.registerHandler("seed",uC(e),lC(e)),s.registerHandler("anonymize",hC(e),gC(e)),s.registerHandler("checkpoint",wC(e),mC(e)),s.registerHandler("rewind",vC(e),RC(e))}function qu(s,e){return`${s}\0${e}`}var Ed=class{constructor(e){this.deps=e}deps;waiting=new Map;get canAsk(){return this.deps.ask!==void 0}ask(e,t){let r=this.deps.now??(()=>new Date),n=qu(e.operationId,e.stepId),o={...e,expiresAt:new Date(r().getTime()+e.timeoutMs).toISOString()};return new Promise(i=>{let a=l=>{this.waiting.get(n)?.settle===a&&(this.waiting.delete(n),clearTimeout(c),t?.removeEventListener("abort",d),i(l))},d=()=>a({decision:"cancelled",at:r().toISOString()}),c=setTimeout(()=>a({decision:"timedOut",at:r().toISOString()}),e.timeoutMs);if(this.waiting.set(n,{question:o,settle:a}),t?.aborted){d();return}t?.addEventListener("abort",d,{once:!0}),this.deps.announce?.(o),this.deps.ask?.(o).then(l=>{if(l===void 0)return;let u=l==="approve"?"approved":"rejected";this.answer(e.operationId,e.stepId,u,"notification")||this.deps.tooLate?.(o)},()=>{})})}answer(e,t,r,n){let o=this.waiting.get(qu(e,t));if(!o)return!1;let i=this.deps.now??(()=>new Date),a=this.deps.who?.();return o.settle({decision:r,via:n,at:i().toISOString(),...a?{by:a}:{}}),!0}isWaiting(e,t){return this.waiting.has(qu(e,t))}};var Ok=50,Ak={manual:"by hand",schedule:"by its schedule",sandbox_refresh:"by a sandbox refresh",event:"by an event",webhook:"by a webhook",deployment_complete:"by a deployment"};function kC(s,e){return`Pipeline "${s}" is already running: the run started ${Ak[e.triggeredBy]} at ${e.startedAt} has not ended. A pipeline runs once at a time.`}function OC(s){return{stepName:s.stepName,stepType:s.stepType,status:s.status,...s.duration!==void 0?{duration:s.duration}:{},...s.summary!==void 0?{summary:s.summary}:{},...s.error!==void 0?{error:s.error}:{},...s.approval!==void 0?{approval:s.approval}:{}}}var IC={approved:"success",rejected:"stopped",timedOut:"stopped",cancelled:"cancelled"};function Ik(){try{return Gg(SC().username)}catch{return}}function AC(s,e){let t=s,r=0,n=!1,o=!1,i,a=()=>{o||(o=!0,e())},d=()=>{r=Date.now(),i=setTimeout(a,t)};return{start(){n||(n=!0,d())},hold(){i!==void 0&&(clearTimeout(i),i=void 0,t=Math.max(0,t-(Date.now()-r)))},resume(){!n||o||i!==void 0||d()},end(){o=!0,clearTimeout(i),i=void 0}}}function Wu(s){return s.flatMap(e=>e.type==="rewind"&&typeof e.id=="string"&&e.id!==""?[{id:e.id,config:typeof e.config=="object"&&e.config!==null?e.config:{}}]:[])}var TC=new Set(["pipeline:execute","pipeline:templates","pipeline:list","pipeline:history","pipeline:save","pipeline:delete","pipeline:approval","pipeline:sync-configs","pipeline:seed-templates","pipeline:masking-templates","pipeline:rewind-steps","pipeline:rewind-grant","pipeline:rewind-revoke","marketplace:list","marketplace:install"]),Pd=class{constructor(e){this.deps=e}deps;pipelineMarketplace;stepRunners;claims=Eo();scheduler;reportTrigger=()=>{};approvalGate;unreadableSaid=new Map;liveTracker;setLiveOperationTracker(e){this.liveTracker=e}approvals(){let e=this.deps.services;return this.approvalGate??=new Ed({...e?.askApproval?{ask:e.askApproval}:{},announce:t=>this.postStepUpdate({operationId:t.operationId,stepId:t.stepId,status:"running",approval:{...t.message?{message:t.message}:{},expiresAt:t.expiresAt}}),tooLate:t=>e?.approvalTooLate?.(t),who:Ik}),this.approvalGate}async askApproval(e,t,r){r.holdBudget(!0);try{let n=await this.approvals().ask({...e,operationId:r.operationId},t);return this.recordApproval(e,n,r.operationId),n}finally{r.holdBudget(!1)}}async untimed(e,t){t.holdBudget(!0);try{return await e()}finally{t.holdBudget(!1)}}rewindGrants(){return new js(this.deps.configStore)}async runSyncUntimed(e,t,r,n,o){o.holdBudget(!0);try{return await e(t,r,n)}finally{o.holdBudget(!1)}}recordApproval(e,t,r){try{if(!(this.deps.services?.getSandforgeSetting?.("safety.auditLogging",!0)!==!1))return;new eo(this.deps.configStore).append({id:crypto.randomUUID(),action:"pipeline_approval",module:"automation",operationId:r,outcome:IC[t.decision],objects:[],details:{pipeline:e.pipelineName??"",step:e.stepName,decision:t.decision,...t.via?{via:t.via}:{},...t.by?{answeredBy:t.by}:{}},timestamp:t.at})}catch(n){this.deps.log(`[WARN] audit trail: approval of run ${r} was not recorded \u2014 ${T(n)}`)}}setPipelineMarketplace(e){this.pipelineMarketplace=e}setStepRunners(e){this.stepRunners=e}startTriggers(e){e.claims&&(this.claims=e.claims),this.reportTrigger=e.report,this.triggerScheduler().start()}stopTriggers(){this.scheduler?.stop()}noticeSandboxRefresh(e){return this.scheduler?.onSandboxRefresh(e)??Promise.resolve()}triggerScheduler(){return this.scheduler??=new Od({pipelines:()=>this.savedPipelines(),problems:e=>this.pipelineProblems(e),org:e=>{let t=this.deps.orgManager.getOrg(e);return t?{name:Re(t,t.id),sandbox:t.orgType==="Sandbox"}:void 0},start:(e,t)=>this.startTriggeredRun(e,t),record:e=>this.recordEntry(e),store:this.deps.configStore,claims:{claim:e=>this.claims.claim(e),hold:(e,t)=>this.claims.hold(e,t),prune:e=>this.claims.prune(e)},report:e=>this.reportTrigger(e),log:this.deps.log}),this.scheduler}savedPipelines(){let e=this.deps.configStore.getByCategory("pipelines"),t=new Map,r=Object.entries(e).flatMap(([n,o])=>{let i=al.safeParse(o);return i.success?[i.data]:(t.set(n,km(i.error)),[])});for(let[n,o]of t){if(this.unreadableSaid.get(n)===o)continue;let i=e[n]?.name;this.deps.log(`[pipeline-triggers] saved pipeline ${typeof i=="string"?`"${i}"`:n} is not scheduled: it does not read as a pipeline (${o}).`)}this.unreadableSaid.clear();for(let[n,o]of t)this.unreadableSaid.set(n,o);return r}async pipelineProblems(e){return(await this.buildOrchestrator(void 0,e)).check(e)}startTriggeredRun(e,t){let r=this.claims.hold(e.id,{startedAt:new Date().toISOString(),triggeredBy:t});if("busy"in r)return{started:!1,busy:r.busy};let n=`${Jp}${crypto.randomUUID()}`;return{started:!0,run:this.runPipeline(e,{},t,n).catch(i=>{throw this.deps.log(`[ERR] ${t} run of "${e.name}": ${T(i)}`),Le(this.deps,n,T(i),!1,{context:{module:"automation",operation:"pipeline:execute"}}),i}).finally(()=>r.release())}}async handle(e){if(!TC.has(e.type))return!1;switch(e.type){case"pipeline:execute":return await this.handlePipelineRun(e),!0;case"pipeline:templates":return this.handlePipelineTemplates(e),!0;case"pipeline:list":return await this.handlePipelineList(e),!0;case"pipeline:history":return this.handlePipelineHistory(e),!0;case"pipeline:save":return this.handlePipelineSave(e),!0;case"pipeline:delete":return this.handlePipelineDelete(e),!0;case"pipeline:approval":return this.handlePipelineApproval(e),!0;case"pipeline:sync-configs":return this.handleSyncConfigs(e),!0;case"pipeline:seed-templates":return this.handleSeedTemplates(e),!0;case"pipeline:masking-templates":return this.handleMaskingTemplates(e),!0;case"pipeline:rewind-steps":return await this.handleRewindSteps(e),!0;case"pipeline:rewind-grant":return await this.handleRewindGrant(e),!0;case"pipeline:rewind-revoke":return this.handleRewindRevoke(e),!0;case"marketplace:list":return this.handleMarketplaceList(e),!0;case"marketplace:install":return this.handleMarketplaceInstall(e),!0;default:return!1}}async handlePipelineRun(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(fm,e,"pipeline:error",this.deps);if(!t)return;let r=t,n=e.id,o={module:"automation",operation:e.type},i=r.pipeline,a=typeof i.id=="string"&&i.id!==""?this.claims.hold(i.id,{startedAt:new Date().toISOString(),triggeredBy:"manual"}):{release:()=>{}};if("busy"in a){P(this.deps,"pipeline:execute","pipeline:error",e,new Error(kC(i.name,a.busy)),{code:"PIPELINE_RUNNING",retryable:!0});return}try{let d=await this.runPipeline(i,r.variables??{},"manual",n),c=A(this.deps,e,"pipeline:run:response",d);this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(d){P(this.deps,"pipeline:execute","pipeline:error",e,d),Le(this.deps,n,T(d),!1,{context:o})}finally{a.release()}}handlePipelineApproval(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(ym,e,"pipeline:error",this.deps);if(!t)return;this.approvals().answer(t.operationId,t.stepId,t.decision,"page")||this.deps.log(`[WARN] pipeline:approval for a step that no longer waits: ${t.stepId}`)}async checkpointsOf(e){let t=new Map,r=this.stepRunners?.readCheckpoint;if(!e||!r)return t;for(let n of Wu(e.steps)){let o=Ft.safeParse(n.config);if(!(!o.success||t.has(o.data.checkpointId)))try{t.set(o.data.checkpointId,await r(o.data.checkpointId))}catch(i){this.deps.log(`[WARN] checkpoint ${o.data.checkpointId} not read for a check: ${T(i)}`)}}return t}async revokeVoidGrants(){try{let e=this.stepRunners?.readCheckpoint,t=await this.rewindGrants().revokeVoid(e?async r=>(await e(r)).kept:void 0);for(let r of t)this.deps.log(`[INFO] the confirmation of Rewind step ${r.stepId} of pipeline ${r.pipelineId} was taken back: its pipeline is no longer saved, or its checkpoint ${r.checkpointId} is no longer kept`)}catch(e){this.deps.log(`[WARN] confirmations of Rewind steps not checked: ${T(e)}`)}}savedPipeline(e){let t=al.safeParse(this.deps.configStore.get(`pipeline:saved:${e}`));return t.success?t.data:void 0}async describeRewindStep(e,t){let r=this.stepRunners,n=Ft.safeParse(t.config),o=n.success&&r?.readCheckpoint?await r.readCheckpoint(n.data.checkpointId):void 0,i=this.rewindGrants().get(e,t.id),a=i?{grantedAt:i.grantedAt,matches:i.takenBackAt===void 0&&Ns(t.config)===i.digest}:void 0;return r?{info:Sk(r,t,o,a),...o?{checkpoint:o}:{}}:{info:{stepId:t.id,valid:!1,why:"missing",...a?{granted:{at:a.grantedAt,digestMatches:a.matches}}:{}}}}async handleRewindSteps(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(wm,e,"pipeline:error",this.deps);if(t)try{let r=this.savedPipeline(t.pipelineId),n=[];for(let i of Wu(r?.steps??[]))n.push((await this.describeRewindStep(t.pipelineId,i)).info);let o=A(this.deps,e,"pipeline:rewind-steps:response",{pipelineId:t.pipelineId,steps:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} (${n.length} Rewind steps)`)}catch(r){P(this.deps,"pipeline:rewind-steps","pipeline:error",e,r)}}async handleRewindGrant(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(bm,e,"pipeline:error",this.deps);if(!t)return;let{pipelineId:r,stepId:n,typed:o}=t,i=d=>{let c=A(this.deps,e,"pipeline:rewind-grant:response",d);this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} ${d.granted?"granted":`refused ${d.code}`}`)},a=(d,c={})=>i({granted:!1,pipelineId:r,stepId:n,code:d,...c.why!==void 0?{why:c.why}:{},...c.reason!==void 0?{reason:c.reason}:{}});try{let d=this.savedPipeline(r),c=Wu(d?.steps??[]).find(f=>f.id===n);if(!c)return a("NOT_SAVED");let l=Ft.safeParse(c.config);if(!l.success)return a("CONFIG_INVALID",{reason:l.error.issues[0]?.message??""});let u=this.deps.orgManager.getOrg(l.data.orgId);if(!u)return a("ORG_UNKNOWN");if(o!==Re(u))return a("TYPED_MISMATCH");let{info:p,checkpoint:g}=await this.describeRewindStep(r,c);if(!p.valid)return a("CHECKPOINT_INVALID",{why:p.why??"missing"});if(!g?.kept||g.organizationId===void 0)return a("CHECKPOINT_INVALID",{why:"missing"});let h=Ik();this.rewindGrants().write({pipelineId:r,stepId:n,organizationId:g.organizationId,checkpointId:l.data.checkpointId,digest:Ns(c.config)??"",grantedAt:new Date().toISOString(),...h!==void 0?{grantedBy:h}:{}}),this.deps.log(`[INFO] pipeline:rewind-grant: Rewind step ${n} of pipeline ${r} confirmed for ${Re(u)}, to checkpoint ${l.data.checkpointId}`),i({granted:!0,pipelineId:r,stepId:n,step:(await this.describeRewindStep(r,c)).info})}catch(d){P(this.deps,"pipeline:rewind-grant","pipeline:error",e,d)}}handleRewindRevoke(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Rm,e,"pipeline:error",this.deps);if(t)try{let r=this.rewindGrants().revoke(t.pipelineId,t.stepId),n=A(this.deps,e,"pipeline:rewind-revoke:response",{pipelineId:t.pipelineId,stepId:t.stepId,revoked:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} revoked=${r}`)}catch(r){P(this.deps,"pipeline:rewind-revoke","pipeline:error",e,r)}}handleSeedTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.stepRunners?wk(this.stepRunners):[],r=A(this.deps,e,"pipeline:seed-templates:response",{templates:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} (${t.length} templates)`)}catch(t){P(this.deps,"pipeline:seed-templates","pipeline:error",e,t)}}handleMaskingTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.stepRunners?bk(this.stepRunners):[],r=A(this.deps,e,"pipeline:masking-templates:response",{templates:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} (${t.length} templates)`)}catch(t){P(this.deps,"pipeline:masking-templates","pipeline:error",e,t)}}handleSyncConfigs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.stepRunners?gk(this.stepRunners):[],r=A(this.deps,e,"pipeline:sync-configs:response",{configs:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} (${t.length} configurations)`)}catch(t){P(this.deps,"pipeline:sync-configs","pipeline:error",e,t)}}async buildOrchestrator(e,t){let{PipelineBuilder:r}=await import("./chunk-4HW535YJ.mjs"),{TriggerEngine:n}=await import("./chunk-2YIV2OB2.mjs"),{StepLibrary:o}=await import("./chunk-IEYG5ATY.mjs"),{StepExecutor:i}=await import("./chunk-ZQOZ4EFW.mjs"),{ConditionalRouter:a}=await import("./chunk-ZJKCWBRJ.mjs"),{PipelineHistory:d}=await import("./chunk-ZHJP7L3K.mjs"),c=new i;if(this.stepRunners){let l=e??{operationId:"",holdBudget:()=>{}},{runSync:u,seed:p,anonymize:g,takeCheckpoint:h,rewind:f}=this.stepRunners,m=await this.checkpointsOf(t),y=this.rewindGrants();kk(c,{...this.stepRunners,...t?.id?{pipelineId:t.id}:{},...l.triggeredBy?{trigger:l.triggeredBy}:{},rewindGrant:(w,v)=>y.verify(w,v),checkpointKept:w=>m.get(w),...u?{runSync:(w,v,R)=>this.runSyncUntimed(u,w,v,R,l)}:{},...p?{seed:(w,v)=>this.untimed(()=>p(w,v),l)}:{},...g?{anonymize:(w,v)=>this.untimed(()=>g(w,v),l)}:{},...h?{takeCheckpoint:(w,v)=>this.untimed(()=>h(w,v),l)}:{},...f?{rewind:(w,v)=>this.untimed(()=>f(w,v),l)}:{},...this.approvals().canAsk?{askApproval:(w,v)=>this.askApproval(w,v,l)}:{}})}if(!this.deps.services)throw new Error("AutomationHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");return this.deps.services.automationOrchestrator({builder:new r,triggerEngine:new n,stepLibrary:new o,stepExecutor:c,conditionalRouter:new a,history:new d,services:this.deps.services})}async runPipeline(e,t,r,n){let o={module:"automation",operation:"pipeline:execute"},i=this.deps.services?.getSandforgeSetting?.("pipeline.timeout",3e5)??3e5,a=new AbortController,d=!1,c=AC(i,()=>{d=!0,a.abort()}),l=await this.buildOrchestrator({operationId:n,holdBudget:b=>b?c.hold():c.resume(),triggeredBy:r},e);this.deps.infraServices?.performanceTracker?.start(n,"automation");let u=`Pipeline: ${e.name}`;We(this.deps,n,"automation",u);let p=Jt(this.liveTracker,n,"automation",u,e.steps.length),g=b=>d&&b.status==="stopped"?{...b,status:"failed"}:b,h=(b,O)=>{let k=O,S=l.getActiveRuns(),E=e.steps.length,I=S[0]?.stepResults.length??0,C=Math.round(I/E*100),F=`Step: ${k.stepResult.stepName} (${k.stepResult.status})`;$e(this.deps,n,C,I,E,F),p.progress(C,I,E,F)},f=(b,O)=>{let{stepId:k}=O;this.postStepUpdate({operationId:n,stepId:k,status:"running"})},m=(b,O)=>{let k=g(O.stepResult);this.postStepUpdate({operationId:n,stepId:k.stepId,status:k.status==="failed"||k.status==="skipped"||k.status==="stopped"?k.status:"completed",...k.duration!==void 0?{duration:k.duration}:{},...k.summary!==void 0?{summary:k.summary}:{},...k.error!==void 0?{error:k.error}:{}})};l.on("stepCompleted",h),l.on("stepStarted",f),l.on("stepCompleted",m),l.on("stepSkipped",m),c.start();let y=()=>{};this.deps.infraServices?.backgroundRegistry?.register(n,"automation",u,new Promise((b,O)=>{y=k=>k?O(k):b()}),a);let w;try{w=await l.execute(e,t,r,a.signal)}catch(b){throw y(new Error(T(b))),p.fail(T(b)),b}finally{c.end(),l.off?.("stepCompleted",h),l.off?.("stepStarted",f),l.off?.("stepCompleted",m),l.off?.("stepSkipped",m)}let v=d&&w.status==="cancelled",R=v?{...w,status:"failed",error:`Pipeline ran out of time: sandforge.pipeline.timeout stopped it after ${i} ms.`,stepResults:w.stepResults.map(g)}:w;return y(R.status==="failed"?new Error(R.error??"Pipeline failed"):void 0),R.status==="failed"?p.fail(R.error??"Pipeline failed"):R.status==="cancelled"?p.cancel():R.status==="completed_with_warnings"?p.partial():p.complete(),this.deps.infraServices?.performanceTracker?.complete(n),this.recordRun(R,e),R.status==="failed"?Le(this.deps,n,R.error??"Pipeline failed",v,{context:o}):pe(this.deps,n,{status:R.status,stepResults:R.stepResults.length}),R}postStepUpdate(e){let t={id:this.deps.nextId(),type:"pipeline:step",timestamp:Date.now(),payload:e};this.deps.broker.postToWebview(t)}recordRun(e,t){this.writeHistory({runId:e.id,pipelineId:e.pipelineId,pipelineName:e.pipelineName,status:e.status,triggeredBy:e.triggeredBy,startTime:e.startTime,duration:e.duration??0,stepCount:e.stepResults.filter(r=>r.status!=="skipped").length,errorCount:e.stepResults.filter(r=>r.status==="failed").length,steps:e.stepResults.map(OC)},{pipeline:t})}recordEntry(e){this.writeHistory(e)}writeHistory(e,t={}){try{let r=new Date(e.startTime).getTime();this.deps.configStore.set(`pipeline:history:${e.runId}`,{...e,timestamp:Number.isNaN(r)?Date.now():r,...t},"pipeline-history"),this.trimHistory()}catch(r){this.deps.log(`[ERR] pipeline history write: ${T(r)}`)}}trimHistory(){let e=Object.entries(this.deps.configStore.getByCategory("pipeline-history"));if(e.length<=Ok)return;let t=e.map(([r,n])=>{let o=n.timestamp;return{key:r,timestamp:typeof o=="number"?o:0}}).sort((r,n)=>r.timestamp-n.timestamp);for(let{key:r}of t.slice(0,e.length-Ok))this.deps.configStore.delete(r)}handlePipelineTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=A(this.deps,e,"pipeline:templates:response",{templates:JS});this.deps.broker.postToWebview(t),this.deps.log("[TX] pipeline:templates:response")}async handlePipelineList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.deps.configStore.getByCategory("pipelines"),r=Object.entries(t).map(([i,a])=>({key:i,...a})),n=await this.triggerScheduler().statuses();await this.revokeVoidGrants();let o=A(this.deps,e,"pipeline:list:response",{pipelines:r,triggers:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] pipeline:list:response (${r.length} pipelines)`)}catch(t){P(this.deps,"pipeline:list","pipeline:error",e,t)}}handlePipelineHistory(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.deps.configStore.getByCategory("pipeline-history"),n=Object.values(t).map(i=>{let a={...i};return delete a.pipeline,a}).sort((i,a)=>{let d=typeof i.timestamp=="number"?i.timestamp:0;return(typeof a.timestamp=="number"?a.timestamp:0)-d}),o=A(this.deps,e,"pipeline:history:response",{history:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] pipeline:history:response (${n.length} entries)`)}catch(t){P(this.deps,"pipeline:history","pipeline:error",e,t)}}handlePipelineSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=D(hm,e,"pipeline:error",this.deps);if(!t)return;let r=t,n=r.id||crypto.randomUUID(),o=`pipeline:saved:${n}`;this.deps.configStore.set(o,{...r.config,id:n,savedAt:new Date().toISOString()},"pipelines");let i=Array.isArray(r.config.steps)?r.config.steps:[],a=this.rewindGrants().revokeChanged(n,i.map(c=>({...typeof c.id=="string"?{id:c.id}:{},...c.type==="rewind"?{type:"rewind"}:{},config:typeof c.config=="object"&&c.config!==null?c.config:{}})));for(let c of a)this.deps.log(`[INFO] pipeline:save ${n}: the confirmation of Rewind step ${c} was taken back, since the save changed what it does`);this.scheduler?.reload();let d=A(this.deps,e,"pipeline:save:response",{success:!0,id:n});this.deps.broker.postToWebview(d),this.deps.log(`[TX] pipeline:save:response id=${n}`)}catch(t){P(this.deps,"pipeline:save","pipeline:error",e,t)}}handlePipelineDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=D(mm,e,"pipeline:error",this.deps);if(!t)return;let{id:r}=t,n=this.claims.hold(r,{startedAt:new Date().toISOString(),triggeredBy:"manual"});if("busy"in n){let a=this.deps.configStore.get(`pipeline:saved:${r}`),d=typeof a?.name=="string"?a.name:r;P(this.deps,"pipeline:delete","pipeline:error",e,new Error(`Pipeline "${d}" is running: the run started ${Ak[n.busy.triggeredBy]} at ${n.busy.startedAt} has not ended. Delete it once that run has ended.`),{code:"PIPELINE_RUNNING",retryable:!0});return}let o;try{o=this.deps.configStore.delete(`pipeline:saved:${r}`);let a=this.rewindGrants().revokePipeline(r);a.length>0&&this.deps.log(`[INFO] pipeline:delete ${r}: the confirmations of Rewind steps ${a.join(", ")} were taken back`)}finally{n.release()}this.scheduler?.reload();let i=A(this.deps,e,"pipeline:delete:response",{id:r,deleted:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] pipeline:delete:response id=${r} deleted=${o}`)}catch(t){P(this.deps,"pipeline:delete","pipeline:error",e,t)}}handleMarketplaceList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{if(!this.pipelineMarketplace)throw new Error("Pipeline Marketplace not available.");let t=D(vm,e,"pipeline:error",this.deps);if(t===null)return;let r;t?.query?r=this.pipelineMarketplace.search(t.query):t?.category?r=this.pipelineMarketplace.getByCategory(t.category):r=this.pipelineMarketplace.getTemplates();let n=A(this.deps,e,"marketplace:list:response",{success:!0,templates:r.map(o=>({id:o.id,name:o.name,description:o.description,category:o.category,author:"SandForge",stepTypes:o.steps.map(i=>i.type)}))});this.deps.broker.postToWebview(n)}catch(t){this.deps.log(`[ERR] marketplace:list: ${T(t)}`);let r=A(this.deps,e,"marketplace:list:response",{success:!1,error:T(t)});this.deps.broker.postToWebview(r)}}handleMarketplaceInstall(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Sm,e,"pipeline:error",this.deps);if(!t)return;let{templateId:r}=t;try{if(!this.pipelineMarketplace)throw new Error("Pipeline Marketplace not available.");if(!this.pipelineMarketplace.getById(r))throw new Error(`Template "${r}" not found.`);let o=this.pipelineMarketplace.exportTemplate(r),i;try{i=JSON.parse(o)}catch{throw new Error(`Template "${r}" contains invalid JSON.`)}let a=i.id;typeof a=="string"&&a!==""&&this.rewindGrants().revokePipeline(a);let d=A(this.deps,e,"marketplace:install:response",{success:!0,pipeline:i});this.deps.broker.postToWebview(d)}catch(n){this.deps.log(`[ERR] marketplace:install: ${T(n)}`);let o=A(this.deps,e,"marketplace:install:response",{success:!1,error:T(n)});this.deps.broker.postToWebview(o)}}};var Co=class{calls=new Map;begin(e){let t=new AbortController;return this.calls.has(e)||this.calls.set(e,t),{signal:t.signal,end:()=>{this.calls.get(e)===t&&this.calls.delete(e)}}}abort(e){let t=this.calls.get(e);return t?.abort(),t!==void 0}};function qn(s,e){return e.aborted?(s.catch(()=>{}),Promise.reject(Tk())):new Promise((t,r)=>{let n=()=>r(Tk());e.addEventListener("abort",n,{once:!0}),s.then(o=>{e.removeEventListener("abort",n),t(o)},o=>{e.removeEventListener("abort",n),r(o)})})}function Tk(){return Object.assign(new Error("Stopped before its answer came."),{code:"CANCELLED"})}var Ek=200,zu=50,Gu="ai.enabled",Ju="ai.errorResolution",Pk="ai:conversations:index",Ck="ai",Cd="ai.anthropic.key",EC=new Set(["ai:chat","ai:chat:cancel","ai:conversation:create","ai:conversation:load","ai:conversation:delete","ai:conversation:delete-all","ai:conversation:list","ai:status","ai:save-key","ai:settings","ai:remove-key"]),Dd=class{constructor(e){this.deps=e}deps;aiAssistant;asking=new Co;setAIAssistant(e){this.aiAssistant=e}async handle(e){if(!EC.has(e.type))return!1;switch(e.type){case"ai:chat":return await this.handleChat(e),!0;case"ai:chat:cancel":return this.handleChatCancel(e),!0;case"ai:conversation:create":return this.handleConversationCreate(e),!0;case"ai:conversation:load":return this.handleConversationLoad(e),!0;case"ai:conversation:list":return this.handleConversationList(e),!0;case"ai:conversation:delete":return this.handleConversationDelete(e),!0;case"ai:conversation:delete-all":return this.handleConversationDeleteAll(e),!0;case"ai:status":return await this.handleStatus(e),!0;case"ai:save-key":return await this.handleSaveKey(e),!0;case"ai:settings":return await this.handleSettings(e),!0;case"ai:remove-key":return await this.handleRemoveKey(e),!0;default:return!1}}conversationKey(e){return`ai:conversation:${e}`}loadIndex(){return this.deps.configStore.get(Pk)??[]}saveIndex(e){this.deps.configStore.set(Pk,e,Ck)}loadConversation(e){return this.deps.configStore.get(this.conversationKey(e))}saveConversation(e){this.deps.configStore.set(this.conversationKey(e.id),e,Ck),this.updateIndexEntry(e)}updateIndexEntry(e){let t=this.loadIndex(),r=t.findIndex(o=>o.id===e.id),n={id:e.id,title:e.title,createdAt:e.createdAt,messageCount:e.messages.length,updatedAt:e.updatedAt};r>=0?t[r]=n:t.push(n),this.saveIndex(this.withinTheBound(t,e.id))}withinTheBound(e,t){if(e.length<=zu)return e;let r=o=>o.updatedAt??o.createdAt,n=new Set([...e].filter(o=>o.id!==t).sort((o,i)=>r(o).localeCompare(r(i))).slice(0,e.length-zu).map(o=>o.id));for(let o of n)this.forgetConversation(o);return this.deps.log(`[INFO] ai: ${n.size} conversation(s) written to least recently deleted (${zu} are kept).`),e.filter(o=>!n.has(o.id))}forgetConversation(e){this.asking.abort(e),this.aiAssistant?.deleteConversation(e),this.deps.configStore.delete(this.conversationKey(e))}deleteAllConversations(){let e=this.conversationKey(""),t=new Set(this.loadIndex().map(r=>r.id));for(let r of this.deps.configStore.getKeysByPrefix(e))t.add(r.slice(e.length));for(let r of t)this.forgetConversation(r);return this.saveIndex([]),t.size}pruneMessages(e){if(e.length<=Ek)return e;let t=e.filter(o=>o.role==="system"),r=e.filter(o=>o.role!=="system"),n=Ek-t.length;return[...t,...r.slice(-n)]}isChatRole(e){return e==="user"||e==="assistant"||e==="system"}toConversation(e){let t=e.messages.filter(r=>this.isChatRole(r.role)).map(r=>({id:r.id,role:r.role,content:r.content,timestamp:r.timestamp,tokenCount:r.tokenCount}));return{id:e.id,title:e.title,messages:t,createdAt:e.createdAt,updatedAt:e.updatedAt,totalTokens:t.reduce((r,n)=>r+(n.tokenCount??0),0)}}restoreConversationIfNeeded(e){let t=this.aiAssistant;if(!t||t.getConversation(e))return;let r=this.loadConversation(e);r&&(t.restoreConversation(this.toConversation(r)),this.deps.log(`Restored conversation ${e} from store.`))}async handleChat(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D($h,e,"ai:error",this.deps);if(!t)return;let r=t,n=this.aiAssistant;if(!n){let i=A(this.deps,e,"ai:error",{message:"AI is not configured. Set your API key in Settings > AI."});this.deps.broker.postToWebview(i);return}this.restoreConversationIfNeeded(r.conversationId);let o=this.asking.begin(r.conversationId);try{let i=await n.chat(r.conversationId,r.message,{signal:o.signal}),a=n.getConversation(r.conversationId);a&&this.persistConversationFromMemory(a);let d=A(this.deps,e,"ai:chat:response",{conversationId:r.conversationId,message:{id:i.id,role:i.role,content:i.content,timestamp:i.timestamp,tokenCount:i.tokenCount},...a?{title:a.title}:{}});this.deps.broker.postToWebview(d),this.deps.log("[TX] ai:chat:response")}catch(i){if(o.signal.aborted){let c=A(this.deps,e,"ai:chat:response",{conversationId:r.conversationId,code:"CANCELLED"});this.deps.broker.postToWebview(c),this.deps.log("[TX] ai:chat:response cancelled");return}let a=T(i),d=A(this.deps,e,"ai:error",{message:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ai:error: ${a}`)}finally{o.end()}}handleChatCancel(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(bi,e,"ai:error",this.deps);t&&this.asking.abort(t.conversationId)}handleConversationCreate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Lh,e,"ai:error",this.deps);if(!t)return;let r=t;if(!this.aiAssistant){let i=A(this.deps,e,"ai:error",{message:"AI is not configured. Set your API key in Settings > AI."});this.deps.broker.postToWebview(i);return}let n=this.aiAssistant.createConversation(r.title);this.persistConversationFromMemory(n);let o=A(this.deps,e,"ai:conversation:created",{conversation:{id:n.id,title:n.title,createdAt:n.createdAt}});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ai:conversation:created id=${n.id}`)}handleConversationLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(bi,e,"ai:error",this.deps);if(!t)return;let r=t;if(this.aiAssistant){let i=this.aiAssistant.getConversation(r.conversationId);if(i){let a=A(this.deps,e,"ai:conversation:loaded",{conversation:{id:i.id,title:i.title,messages:i.messages.map(d=>({id:d.id,role:d.role,content:d.content,timestamp:d.timestamp}))}});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ai:conversation:loaded id=${i.id} (memory)`);return}}let n=this.loadConversation(r.conversationId);if(!n){let i=A(this.deps,e,"ai:error",{message:`Conversation ${r.conversationId} not found.`});this.deps.broker.postToWebview(i);return}let o=A(this.deps,e,"ai:conversation:loaded",{conversation:{id:n.id,title:n.title,messages:n.messages.map(i=>({id:i.id,role:i.role,content:i.content,timestamp:i.timestamp}))}});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ai:conversation:loaded id=${n.id} (store)`)}handleConversationList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.loadIndex(),r=A(this.deps,e,"ai:conversation:list:response",{conversations:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ai:conversation:list:response count=${t.length}`)}handleConversationDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(bi,e,"ai:error",this.deps);if(!t)return;let r=t;this.aiAssistant&&this.aiAssistant.deleteConversation(r.conversationId),this.deps.configStore.delete(this.conversationKey(r.conversationId));let n=this.loadIndex().filter(i=>i.id!==r.conversationId);this.saveIndex(n);let o=A(this.deps,e,"ai:conversation:deleted",{conversationId:r.conversationId});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ai:conversation:deleted id=${r.conversationId}`)}handleConversationDeleteAll(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.deleteAllConversations(),r=A(this.deps,e,"ai:conversation:deleted-all",{count:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ai:conversation:deleted-all count=${t}`)}async handleStatus(e){this.deps.log(`[RX] ${e.type} id=${e.id}`),await this.postStatus(e)}async postStatus(e){let t=await this.deps.secretVault.hasSecret(Cd),r=A(this.deps,e,"ai:status:response",{enabled:!!this.aiAssistant&&t,provider:this.aiAssistant?_p:"none",model:this.aiAssistant?Hp(this.deps.services?.getSandforgeSetting?.("ai.model",Up.MODEL)):"",budget:this.aiAssistant?this.deps.services?.sessionBudget?.getState():void 0,hasKey:t,errorResolution:this.deps.services?.getSandforgeSetting?.(Ju,!0)??!0});this.deps.broker.postToWebview(r),this.deps.log("[TX] ai:status:response")}async enableAIFeature(){await this.writeSetting("ai:save-key",Gu,!0)}async writeSetting(e,t,r){if(!this.deps.services?.setSandforgeSetting)return this.deps.log(`[WARN] ${e}: no settings backend \u2014 sandforge.${t} left as-is.`),!1;try{return await this.deps.services.setSandforgeSetting(t,r),!0}catch(n){return this.deps.log(`[ERR] ${e}: writing sandforge.${t} failed: ${T(n)}`),!1}}async rebuildAIStack(e="ai:save-key"){let t=this.deps.services?.reinitAI;if(!t){this.deps.log(`[WARN] ${e}: no AI rebuild wired \u2014 the change applies after a reload.`);return}try{await t()}catch(r){this.deps.log(`[ERR] ${e}: rebuilding the AI stack failed: ${T(r)}`)}}async handleSaveKey(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Fh,e,"ai:error",this.deps);if(!t)return;let{apiKey:r,errorResolution:n}=t;try{let o=await this.deps.secretVault.hasSecret(Cd);await this.deps.secretVault.storeSecret(Cd,r),(!o||n!==void 0)&&await this.writeSetting("ai:save-key",Ju,n===!0),await this.enableAIFeature(),await this.rebuildAIStack();let i=A(this.deps,e,"ai:save-key:response",{success:!0});this.deps.broker.postToWebview(i),this.deps.log("[TX] ai:save-key:response success"),await this.postStatus(e)}catch(o){let i=T(o);this.deps.log(`[ERR] ai:save-key: ${i}`);let a=A(this.deps,e,"ai:save-key:response",{success:!1,error:i});this.deps.broker.postToWebview(a)}}async handleSettings(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(_h,e,"ai:error",this.deps);if(!t)return;let r=[];t.errorResolution!==void 0&&r.push([Ju,t.errorResolution]),t.enabled!==void 0&&r.push([Gu,t.enabled]);let n=!0;for(let[i,a]of r)await this.writeSetting("ai:settings",i,a)||(n=!1);await this.rebuildAIStack("ai:settings");let o=A(this.deps,e,"ai:settings:response",{success:n,...n?{}:{error:"The setting could not be written: the SandForge log says why."}});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ai:settings:response success=${n}`),await this.postStatus(e)}async handleRemoveKey(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{await this.deps.secretVault.deleteSecret(Cd);let t=this.deleteAllConversations();await this.writeSetting("ai:remove-key",Gu,!1),await this.rebuildAIStack("ai:remove-key");let r=A(this.deps,e,"ai:remove-key:response",{success:!0,conversationsDeleted:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ai:remove-key:response conversations=${t}`),await this.postStatus(e)}catch(t){let r=T(t);this.deps.log(`[ERR] ai:remove-key: ${r}`);let n=A(this.deps,e,"ai:remove-key:response",{success:!1,error:r});this.deps.broker.postToWebview(n)}}persistConversationFromMemory(e){let t=e.messages.map(n=>({id:n.id,role:n.role,content:n.content,timestamp:n.timestamp,tokenCount:n.tokenCount})),r={id:e.id,title:e.title,messages:this.pruneMessages(t),createdAt:e.createdAt,updatedAt:e.updatedAt};this.saveConversation(r)}};var PC=new Set(["ai:anomaly-scan"]),xd=class{constructor(e){this.deps=e}deps;ruleModules;setRuleModules(e){this.ruleModules=e}async handle(e){return PC.has(e.type)&&e.type==="ai:anomaly-scan"?(await this.handleAnomalyScan(e),!0):!1}async handleAnomalyScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Uh,e,"ai:error",this.deps);if(!t)return;let{orgId:r,objectName:n,sampleSize:o}=t;try{if(!this.ruleModules?.anomalyDetector)throw new Error("Anomaly scan is still starting up. Try again in a moment.");let i=await B(r,this.deps.orgRegistry,this.deps.orgManager),a=pt(n),d=o??Wr.anomalyScan,c=`SELECT FIELDS(ALL) FROM ${a} LIMIT ${d}`,l=await Qg(i,a,c),u=l.records,p={records:u,fields:Object.keys(u[0]??{})},g=this.ruleModules.anomalyDetector.detectAnomalies(p,n),h=A(this.deps,e,"ai:anomaly-scan:response",{success:!0,anomalies:g.anomalies.map(f=>({field:f.field,type:f.type,description:f.description,severity:f.severity})),sample:{read:u.length,limit:l.limit??d}});this.deps.broker.postToWebview(h)}catch(i){this.deps.log(`[ERR] ai:anomaly-scan: ${T(i)}`);let a=A(this.deps,e,"ai:anomaly-scan:response",{success:!1,error:T(i)});this.deps.broker.postToWebview(a)}}};function Dk(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"")}function CC(s){let e=[s];return s.endsWith("ies")&&s.length>3&&e.push(`${s.slice(0,-3)}y`),(s.endsWith("ses")||s.endsWith("xes")||s.endsWith("ches"))&&e.push(s.slice(0,-2)),s.endsWith("s")&&!s.endsWith("ss")&&e.push(s.slice(0,-1)),e}function DC(s){let e=new Map;for(let t of s)if(t.queryable!==!1)for(let r of[t.name,t.label,t.labelPlural]){if(!r)continue;let n=Dk(r);n&&!e.has(n)&&e.set(n,t.name)}return e}function xk(s,e,t=5){if(t<=0)return[];let r=DC(e),n=s.split(/[^A-Za-z0-9_]+/).filter(Boolean),o=[],i=new Set;for(let a=0;a<n.length;a++){let d=Math.min(4,n.length-a);for(let c=d;c>=1;c--){let l=n.slice(a,a+c).join(""),u=CC(Dk(l)).map(p=>r.get(p)).find(p=>p!==void 0);if(u){if(!i.has(u)&&(i.add(u),o.push(u),o.length>=t))return o;a+=c-1;break}}}return o}var xC={sync:"Sync",seed:"Seed",dataops:"DataOps"};function Mk(s){if(s.code==="STEP_NOT_RUNNABLE")return`A pipeline cannot run a ${s.stepType} step, so the draft leaves it out.`;let e=xC[s.page];return`The draft leaves out the ${e} work, which writes to an org: run it from the ${e} page, where Production Guard can stop or ask first.`}var MC=new Set(["WHERE","USING","WITH","GROUP","ORDER","LIMIT","OFFSET","FOR","UPDATE"]),jC=new Set(["WITH","GROUP","ORDER","LIMIT","OFFSET","FOR","UPDATE"]),NC=new Set(["AND","OR","NOT","WHERE"]),$C=/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/,LC=/^([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)(?:\s+[A-Za-z_]\w*)?$/,FC=/^[A-Za-z_]\w*\s*\(([^()]*)\)(?:\s+[A-Za-z_]\w*)?$/,_C=/([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*(?:!=|<>|<=|>=|=|<|>|\bNOT\s+IN\b|\bIN\b|\bLIKE\b|\bINCLUDES\b|\bEXCLUDES\b)/gi;function UC(s){let e="",t=0;for(;t<s.length;){if(s[t]!=="'"){e+=s[t],t++;continue}for(t++;t<s.length&&s[t]!=="'";)t+=s[t]==="\\"?2:1;t++,e+="''"}return e}var jk=/\(\s*SELECT\b/iy;function HC(s){let e="",t=0;for(;t<s.length;){if(jk.lastIndex=t,s[t]!=="("||!jk.test(s)){e+=s[t],t++;continue}let r=0,n=t;for(;n<s.length;n++)if(s[n]==="(")r++;else if(s[n]===")"&&--r===0)break;e+="()",t=n+1}return e}function BC(s){let e=[],t=0,r=0;for(;r<s.length;){let n=s[r];if(n==="(")t++,r++;else if(n===")")t=Math.max(0,t-1),r++;else if(/\w/.test(n)){let o=r;for(;r<s.length&&/\w/.test(s[r]);)r++;t===0&&e.push({word:s.slice(o,r),start:o,end:r})}else r++}return e}function qC(s){let e=[],t=0,r=0;for(let n=0;n<s.length;n++)s[n]==="("?t++:s[n]===")"?t=Math.max(0,t-1):s[n]===","&&t===0&&(e.push(s.slice(r,n)),r=n+1);return e.push(s.slice(r)),e}function WC(s){let e=LC.exec(s);if(e)return e[1];let t=FC.exec(s);if(t){let r=t[1].trim();return $C.test(r)?r:null}return null}function zC(s){let e=HC(UC(s)).replace(/\bTYPEOF\b[\s\S]*?\bEND\b/gi,"()"),t=BC(e),r=f=>t[f]?.word.toUpperCase();if(r(0)!=="SELECT")return null;let n=t.findIndex(f=>f.word.toUpperCase()==="FROM");if(n<1||n+1>=t.length)return null;let o=t[n+1].word,i=new Set([o.toUpperCase()]),a=r(n+2)==="AS"?n+3:n+2,d=r(a),c=e.slice(t[n+1].end,t[a]?.start);d&&!MC.has(d)&&!c.includes(",")&&i.add(d);let l=[],u=e.slice(t[0].end,t[n].start);for(let f of qC(u)){let m=WC(f.trim());m&&l.push(m)}let p=t.findIndex((f,m)=>m>n+1&&f.word.toUpperCase()==="WHERE");if(p>=0){let f=t.findIndex((y,w)=>w>p&&jC.has(r(w)??"")),m=e.slice(t[p].end,f<0?e.length:t[f].start);for(let y of m.matchAll(_C))NC.has(y[1].toUpperCase())||l.push(y[1])}let g=new Set,h=[];for(let f of l){let[m,...y]=f.split("."),w=y.length>0&&i.has(m.toUpperCase())?y.join("."):f,v=w.toUpperCase();g.has(v)||(g.add(v),h.push(w))}return{objectApiName:o,fieldRefs:h}}async function Nk(s,e){let t=zC(s);if(!t)return{fieldsChecked:0,problems:[{kind:"no-from"}]};let r=t.objectApiName.toLowerCase(),n=e.catalog.find(l=>l.name.toLowerCase()===r);if(!n)return{rootObject:t.objectApiName,fieldsChecked:0,problems:[{kind:"object-missing",object:t.objectApiName}]};let o;try{o=await e.describe(n.name)}catch(l){return{rootObject:n.name,rootLabel:n.label,fieldsChecked:0,problems:[{kind:"describe-failed",object:n.name,detail:T(l)}]}}let i=new Set(o.fields.map(l=>l.name.toLowerCase())),a=new Set(o.fields.flatMap(l=>l.relationshipName?[l.relationshipName.toLowerCase()]:[])),d=[],c=new Set;for(let l of t.fieldRefs){let[u,...p]=l.split(".");p.length===0?i.has(u.toLowerCase())||d.push({kind:"field-missing",object:n.name,field:u}):!a.has(u.toLowerCase())&&!c.has(u.toLowerCase())&&(c.add(u.toLowerCase()),d.push({kind:"relationship-missing",object:n.name,relationship:u}))}if(d.length===0)try{await e.explain(s)}catch(l){d.push({kind:"org-refused",detail:T(l)})}return{rootObject:n.name,rootLabel:o.label||n.label,fieldsChecked:t.fieldRefs.length,problems:d}}function Vu(s){return VC().text(s)}var JC=new Set;function VC(){let s=Fb(),e=new Map,t=o=>{let i=e.get(o);if(i!==void 0)return i;let a=s(o);return e.set(o,a),a},r=o=>{let i=_b({text:o},JC,t).text;return typeof i=="string"?i:o},n=o=>typeof o=="string"?r(o):Array.isArray(o)?o.map(n):o!==null&&typeof o=="object"?Object.fromEntries(Object.entries(o).map(([i,a])=>[i,n(a)])):o;return{text:r,deep:o=>n(o)}}var Ct=_c,$t=_c.text,$k="{firstName}, {lastName}, {company}, {email} and {caseSubject}";var Cq=[`- "id" and each topic's "key": lower-case letters and digits in words joined by single hyphens, starting with a letter, ${Ct.maxKeyLength} characters at most.`,`- "name": at most ${$t.name} characters. "businessContext": what the company does and who its customers are, in two or three sentences, at most ${$t.businessContext} characters.`,`- "customers": "count" is 10 unless the scenario asks for another number, at least the number of topics and at most ${Ct.maxCustomers}; "industry" is the customers' industry as an Account Industry value of Salesforce (Retail, Telecommunications, Technology...), at most ${$t.industry} characters.`,`- "topics": ${Ct.topics.min} to ${Ct.topics.max}, five unless the scenario calls for more or fewer: the subjects customers write to support about. "label": at most ${$t.label} characters.`,`- "utterances": ${Ct.utterances.min} to ${Ct.utterances.max} a topic, two unless it needs more: what a customer whose case on the topic is still open says to the agent ("text"), and what the agent should do, in plain words ("expectedOutcome"), each at most ${$t.utterance} characters. They may name the customer and the case with ${$k}, filled in when the pack is seeded.`,`- "decoy": an article close to the topic it "resembles", by its key, that does not answer it, so that a test tells the right article from the nearest. "title" at most ${$t.articleTitle} characters, "summary" at most ${$t.articleSummary}, "body" plain-text paragraphs of 600 to 1,500 characters. No placeholder.`,`- "outOfScope": ${Ct.outOfScope.min} to ${Ct.outOfScope.max}, three unless more are useful: what a customer may say that no topic covers, and that the agent should decline ("expectedOutcome"), each at most ${$t.utterance} characters. No placeholder.`,"- No word in braces but the placeholders named here, where they are allowed."];var Dq=[`- "article": what the agent answers the topic from. "title" at most ${$t.articleTitle} characters and none of the titles above; "summary" at most ${$t.articleSummary}; "body" plain-text paragraphs of 1,200 to 3,000 characters, at most ${$t.articleBody}: the policy or the procedure, with the figures, delays and conditions customers ask about. No placeholder in the article.`,`- "facts": ${Ct.facts.min} to ${Ct.facts.max}, each a sentence of the body copied word for word, at most ${$t.fact} characters: what an answer drawn from the article has to say.`,`- "caseTemplates": ${Ct.caseTemplates.min} to ${Ct.caseTemplates.max}, two unless the topic needs more: cases customers open on the topic. "subject" at most ${$t.caseSubject} characters, and may name {firstName}, {lastName}, {company} and {email}; "description" what the customer writes, under 600 characters; "priority" is High, Medium or Low; "origin" is Phone, Email or Web; "followUp" what the customer writes again while the case is open, under 300 characters; "resolution" ${Ct.resolutionSteps.min} to ${Ct.resolutionSteps.max} steps, each a comment of the agent who resolved the case, under 400 characters. "description", "followUp" and "resolution" may name ${$k}.`,"- No word in braces but the placeholders named here, where they are allowed."];var XC=new Set(["ai:forge-plan","ai:generate-pipeline","ai:scenario-draft","ai:tool:cancel"]),Xu={success:!1,code:"CANCELLED"},Lk="AI not configured. Set your API key in Settings > AI.";function KC(s){switch(s){case"Production":return"production";case"Sandbox":return"sandbox";case"Developer":return"developer";case"Scratch":return"scratch";default:return"production"}}var Md=class{constructor(e){this.deps=e}deps;aiModules;drafting=new Co;describeGlobalCache=new ys({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});describeCache=new ys({defaultTtl:5*6e4,maxSize:50,maxSizeBytes:20*1024*1024});setAIModules(e){this.aiModules=e}forgetOrg(e){this.describeGlobalCache.invalidate(e),this.describeCache.invalidateByPrefix(`${e}::`)}async handle(e){if(!XC.has(e.type))return!1;switch(e.type){case"ai:forge-plan":return await this.handleForgePlan(e),!0;case"ai:generate-pipeline":return await this.handleGeneratePipeline(e),!0;case"ai:scenario-draft":return await this.handleScenarioDraft(e),!0;case"ai:tool:cancel":return this.handleCancel(e),!0;default:return!1}}handleCancel(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(qh,e,"ai:error",this.deps);t&&this.drafting.abort(t.requestId)}async handleForgePlan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Hh,e,"ai:error",this.deps);if(!t)return;let{orgId:r,prompt:n}=t,o=this.drafting.begin(e.id);try{let i=this.aiModules?.nl2soql;if(n!==void 0&&!i){this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{success:!1,code:"AI_NOT_CONFIGURED",error:Lk}));return}let a=await qn(this.connect(r),o.signal),d=await qn(this.loadCatalog(r,a),o.signal),c=t.soql??"",l;if(n!==void 0&&i){let{result:p}=await this.draft(i,n,r,a,d,o.signal);c=p.soql,l=p.explanation}let u=await qn(Nk(c,{catalog:d,describe:async p=>{let g=await this.describeObject(r,a,p);return{name:g.apiName,label:g.label,fields:g.fields.map(h=>({name:h.apiName,relationshipName:h.relationshipName}))}},explain:p=>a.request(`/query/?explain=${encodeURIComponent(p)}`)}),o.signal);this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{success:u.problems.length===0,soql:c,...l?{explanation:l}:{},...u.rootObject?{rootObject:u.rootObject}:{},...u.rootLabel?{rootLabel:u.rootLabel}:{},fieldsChecked:u.fieldsChecked,problems:u.problems}))}catch(i){if(o.signal.aborted){this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{...Xu})),this.deps.log("[TX] ai:forge-plan:response cancelled");return}this.deps.log(`[ERR] ai:forge-plan: ${T(i)}`),this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{success:!1,error:T(i)}))}finally{o.end()}}async connect(e){return await B(e,this.deps.orgRegistry,this.deps.orgManager)}async draft(e,t,r,n,o,i){let a=xk(t,o),d=await qn(this.describeObjects(r,n,a),i),c={objects:d.length>0?d:o.map(u=>({apiName:u.name,label:u.label,fields:[]}))};return{result:await qn(e.generateSOQL(t,c,{signal:i}),i),described:d}}async loadCatalog(e,t){let r=this.describeGlobalCache.get(e);if(r)return r;let o=(await t.describeGlobal()).sobjects.filter(i=>i.queryable!==!1).map(i=>({name:i.name,label:i.label,labelPlural:i.labelPlural,queryable:i.queryable}));return this.describeGlobalCache.set(e,o),o}async describeObjects(e,t,r){let n=[];for(let o of r)try{n.push(await this.describeObject(e,t,o))}catch(i){this.deps.log(`[WARN] ai:nl2soql describe ${o}: ${T(i)}`)}return n}async describeObject(e,t,r){let n=`${e}::${r}`,o=this.describeCache.get(n);if(o)return o;let i=await t.describe(r),a={apiName:i.name,label:i.label??i.name,fields:i.fields.map(d=>({apiName:d.name,label:d.label??d.name,type:d.type,...d.relationshipName?{relationshipName:d.relationshipName}:{}}))};return this.describeCache.set(n,a),a}async handleGeneratePipeline(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Bh,e,"ai:error",this.deps);if(!t)return;let{description:r,orgIds:n}=t,o=this.drafting.begin(e.id);try{if(!this.aiModules?.pipelineGenerator)throw new Error("AI not configured. Set your API key in Settings > AI to enable this feature.");let i=(n??[]).map(l=>{let u=this.deps.orgManager.getOrg(l);return{orgId:l,alias:u?.alias??l,type:KC(u?.orgType)}}),{suggestions:a=[],...d}=await qn(this.aiModules.pipelineGenerator.generatePipeline(r,i,{signal:o.signal}),o.signal);if(d.steps.length===0&&a.length>0){let l=a.map(Mk).join(" ");this.deps.log(`[ERR] ai:generate-pipeline: ${l}`),this.deps.broker.postToWebview(A(this.deps,e,"ai:generate-pipeline:response",{success:!1,error:l,suggestions:a}));return}if(d.steps.length===0)throw new Error("The AI returned a pipeline with no steps, so there is nothing to load. Name the operations it should run, for example: back up Account daily, then compare dev with uat.");let c=A(this.deps,e,"ai:generate-pipeline:response",{success:!0,pipeline:d,...a.length>0?{suggestions:a}:{}});this.deps.broker.postToWebview(c)}catch(i){if(o.signal.aborted){this.deps.broker.postToWebview(A(this.deps,e,"ai:generate-pipeline:response",{...Xu})),this.deps.log("[TX] ai:generate-pipeline:response cancelled");return}this.deps.log(`[ERR] ai:generate-pipeline: ${T(i)}`);let a=A(this.deps,e,"ai:generate-pipeline:response",{success:!1,error:T(i)});this.deps.broker.postToWebview(a)}finally{o.end()}}async handleScenarioDraft(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Wh,e,"ai:error",this.deps);if(!t)return;let r=i=>this.deps.broker.postToWebview(A(this.deps,e,"ai:scenario-draft:response",i));if(t.maskOnly){r({success:!0,sentText:Vu(t.text)});return}let n=this.aiModules?.scenarioDrafter;if(!n){r({success:!1,code:"AI_NOT_CONFIGURED",error:Lk,sentText:Vu(t.text)});return}let o=this.drafting.begin(e.id);try{let i=await n.draft({text:t.text,language:t.language,...t.casePicklists?{casePicklists:t.casePicklists}:{},...t.agent?{agent:t.agent}:{},...t.draft?{from:t.draft}:{}},{signal:o.signal});i.kind==="failed"?this.deps.log(`[ERR] ai:scenario-draft (${i.failedAt.call}): ${i.error}`):i.kind==="stopped"&&this.deps.log("[TX] ai:scenario-draft:response cancelled"),r(YC(i))}catch(i){this.deps.log(`[ERR] ai:scenario-draft: ${T(i)}`),r({success:!1,error:T(i)})}finally{o.end()}}};function YC(s){switch(s.kind){case"complete":return{success:!0,sentText:s.sentText,pack:s.pack};case"stopped":return{...Xu,sentText:s.sentText,...s.draft?{draft:s.draft}:{}};case"failed":return{success:!1,error:s.error,failedAt:s.failedAt,sentText:s.sentText,...s.issues?{issues:s.issues}:{},...s.draft?{draft:s.draft}:{}}}}var QC=new Set(["ai:chat","ai:chat:cancel","ai:conversation:create","ai:conversation:load","ai:conversation:list","ai:conversation:delete","ai:conversation:delete-all","ai:status","ai:save-key","ai:settings","ai:remove-key","ai:tool:cancel","ai:forge-plan","ai:anomaly-scan","ai:generate-pipeline","ai:scenario-draft"]),jd=class{chatHandler;analysisHandler;toolsHandler;subHandlers;constructor(e){this.chatHandler=new Dd(e),this.analysisHandler=new xd(e),this.toolsHandler=new Md(e),this.subHandlers=[this.chatHandler,this.analysisHandler,this.toolsHandler]}setAIAssistant(e){this.chatHandler.setAIAssistant(e)}setAIModules(e){this.toolsHandler.setAIModules(e)}setRuleModules(e){this.analysisHandler.setRuleModules(e)}forgetOrg(e){this.toolsHandler.forgetOrg(e)}async handle(e){if(!QC.has(e.type))return!1;for(let t of this.subHandlers)if(await t.handle(e))return!0;return!1}};function Fk(s,e,t){return{records:s.totalRows,estimateMB:e.estimateMB,verdict:e.verdict,...e.verdict==="unread"?{unread:e.unread}:{remainingMB:e.remainingMB,maxMB:e.maxMB},...t.verdict==="unread"?{}:{apiRequests:{estimate:t.estimate,remaining:t.remaining,max:t.max,verdict:t.verdict}}}}function _k(s,e,t){let{mode:r,share:n}=s,o=r.all!==void 0||Object.keys(r.caps??{}).length>0;return{module:"autopilot",...n!==void 0?{share:n}:{},...o?{capped:!0}:{},...r.withinMB!==void 0?{withinMB:r.withinMB}:{},kept:e,inSource:t}}var ZC=new Set(["autopilot:list-objects","autopilot:count-objects","autopilot:scan-schema","autopilot:generate-plan","autopilot:fit-plan","autopilot:fit-undo","autopilot:execute","autopilot:pause","autopilot:resume","autopilot:skip-node","autopilot:compliance-report"]),eD=10,Ku=3e4,Uk=6e4;function Hk(s){return`autopilot:${s}`}var Yu=(s,e)=>e==="insert"||e==="update",Nd={code:"AUTOPILOT_NOT_READY",message:"Autopilot module is not initialized."},Do={code:"AUTOPILOT_RUNNING",message:"An Autopilot run is still writing to this target org: Monitor's Live Operations shows where it is. Start another once it has ended."},tD=new Set(["autopilot:pause","autopilot:resume","autopilot:skip-node"]),$d=class{constructor(e){this.deps=e}deps;operations=new Map;currentOperationId;executingOperations=new Set;runningRequests=new Set;writingTargets=new Map;beforeRunCheckpoints;orchestrator;registry;liveTracker;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-4XZ5YT5O.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}setOrchestrator(e){this.orchestrator=e}setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}isWritingTo(e,t){let r=this.writingTargets.get(e);return r!==void 0&&(t===void 0||t!==Hk(r))}async handle(e){if(!ZC.has(e.type))return!1;switch(e.type){case"autopilot:list-objects":return await this.handleListObjects(e),!0;case"autopilot:count-objects":return await this.handleCountObjects(e),!0;case"autopilot:scan-schema":return await this.handleScanSchema(e),!0;case"autopilot:generate-plan":return await this.handleGeneratePlan(e),!0;case"autopilot:fit-plan":return await this.handleFitPlan(e),!0;case"autopilot:fit-undo":return await this.handleFitUndo(e),!0;case"autopilot:execute":return await this.handleExecute(e),!0;case"autopilot:pause":return this.handlePause(e),!0;case"autopilot:resume":return this.handleResume(e),!0;case"autopilot:skip-node":return this.handleSkipNode(e),!0;case"autopilot:compliance-report":return this.handleComplianceReport(e),!0;default:return!1}}refuseNotReady(e){P(this.deps,e.type,"autopilot:error",e,new Error(Nd.message),{code:Nd.code}),tD.has(e.type)&&Oe(this.deps,"error","Autopilot",Nd.message,{code:Nd.code})}resolveCurrentOperation(){return this.currentOperationId!==void 0?this.operations.get(this.currentOperationId):void 0}evictOldOperations(){for(;this.operations.size>eD;){let e=this.operations.keys().next();if(e.done||this.executingOperations.has(e.value))return;this.operations.delete(e.value),this.currentOperationId===e.value&&(this.currentOperationId=[...this.operations.keys()].pop())}}async handleListObjects(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=D(Ih,e,"autopilot:error",this.deps);if(t)try{let r=await B(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await this.orchestrator.listObjects(r,n,t.includeStandardObjects),i=A(this.deps,e,"autopilot:objects-listed",{objects:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} count=${o.length}`)}catch(r){P(this.deps,"autopilot:list-objects","autopilot:error",e,r)}}async handleCountObjects(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=D(Ah,e,"autopilot:error",this.deps);if(t)try{let r=await B(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await this.orchestrator.countObjects(r,t.objectApiNames),o=A(this.deps,e,"autopilot:objects-counted",{counts:Object.fromEntries(n)});this.deps.broker.postToWebview(o)}catch(r){P(this.deps,"autopilot:count-objects","autopilot:error",e,r)}}async handleScanSchema(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=D(Th,e,"autopilot:error",this.deps);if(!t)return;let r=t,n=this.currentOperationId,o={id:e.id,targetOrgId:r.targetOrgId,sourceOrgId:r.sourceOrgId};this.operations.set(e.id,o),this.currentOperationId=e.id,this.evictOldOperations();try{let i=await B(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await B(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),d=await this.orchestrator.scanSchemas(i,a,{selectedObjects:r.selectedObjects,includeStandardObjects:r.includeStandardObjects,...r.maxDepth!==void 0?{maxDepth:r.maxDepth}:{},...r.maxObjects!==void 0?{maxObjects:r.maxObjects}:{}});o.scanResult=d;let c=this.orchestrator.buildGraph(d);o.graph=c;let l=A(this.deps,e,"autopilot:schema-result",{graph:c});this.deps.broker.postToWebview(l)}catch(i){this.operations.delete(e.id),this.currentOperationId===e.id&&(this.currentOperationId=n),P(this.deps,"autopilot:scan-schema","autopilot:error",e,i),Oe(this.deps,"error","Autopilot",`Schema scan failed: ${T(i)}`)}}async handleGeneratePlan(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.graph){Oe(this.deps,"error","Autopilot","No schema scan result available. Run scan-schema first.");return}let r=D(Eh,e,"autopilot:error",this.deps);if(!r)return;let n=r;try{let o=n.complianceFramework!=="none"&&t.scanResult?ww(this.deps.infraServices?.piiDetector??new xi,t.scanResult.objectDescribes):[],{profile:i,rules:a}=this.orchestrator.buildCompliance(n.complianceFramework,[],o);t.profile=i,t.rules=a;let d=this.orchestrator.generatePlan(t.graph,n.complianceFramework,a,t.scanResult?.scope);t.plan=d,t.fit&&(t.fit={...t.fit,plan:this.orchestrator.generatePlan(t.fit.graph,n.complianceFramework,a,t.fit.scan.scope)}),await this.sendPlanReady(e,t)}catch(o){P(this.deps,"autopilot:generate-plan","autopilot:error",e,o),Oe(this.deps,"error","Autopilot",`Plan generation failed: ${T(o)}`)}}async sendPlanReady(e,t,r,n){let{plan:o,graph:i}=t.fit??t,a=t.fit?.scan??t.scanResult;if(!o||!i)return;let d;try{d=a?await this.planWriteGate(t.targetOrgId,Tl(o,a.recordCounts,a.personAccounts),r??await this.readTargetDataStorage(t.targetOrgId)):void 0}catch(l){this.deps.log(`[WARN] ${e.type}: what the plan comes to against the target could not be told (${T(l)})`)}if((t.fit??t).plan!==o)return;let c=A(this.deps,e,"autopilot:plan-ready",{plan:o,graph:i,...d?{writeGate:d}:{},...n?{fitNotApplied:n}:{}});this.deps.broker.postToWebview(c)}async planWriteGate(e,t,r,n){let o=await Pw(t,r,()=>this.readTargetApiBudget(e),n);return Fk(t,rn(t,r),o)}refuseFit(e,t,r,n){P(this.deps,e.type,"autopilot:error",e,new Error(r),{code:t,...n?{extraPayload:n}:{}})}async handleFitPlan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let{orchestrator:t}=this;if(!t){this.refuseNotReady(e);return}let r=D(Ch,e,"autopilot:error",this.deps);if(!r)return;let n=this.resolveCurrentOperation(),{plan:o,graph:i,rules:a,scanResult:d}=n??{};if(!n||!o||!i||!a||!d){this.refuseFit(e,go.NO_PLAN,"No execution plan available. Run generate-plan first.");return}let{targetOrgId:c}=n;if(this.writingTargets.has(c)){this.refuseFit(e,Do.code,Do.message);return}try{let l=await this.readTargetAutomation(c,o),u=r.muteAutomation===!0?await this.planMute(c,l).catch(w=>{if(!kt(w))throw w}):void 0,p=await this.readTargetDataStorage(c),g=r.checkpointFirst!==void 0?await this.checkpointFirstOf(e,c,o,r.checkpointFirst,{read:l,...u?{mute:u}:{}},new AbortController().signal):void 0,h=gw({storage:p,...r.mode.withinMB!==void 0?{withinMB:r.mode.withinMB}:{},..."unread"in p?{}:{api:p.dailyApiRequests??{unread:"the target's /limits did not list them"}},otherRequests:po(g&&"estimate"in g?g.estimate:void 0)});if("unread"in h){this.refuseFit(e,go.STORAGE_UNREAD,`The plan cannot be fitted: the target's data storage left could not be read (${h.unread}).`,{reason:h.unread});return}let f=await B(n.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),m=await B(c,this.deps.orgRegistry,this.deps.orgManager),y;try{y=await t.fitPlan(f,{scan:d,graph:i,plan:o,rules:a,mode:r.mode,budget:h,automation:l,...u?.plan?{mutePlan:u.plan}:{},describeLookups:async w=>Aw((await m.describe(w)).fields)})}catch(w){let v=T(w);this.refuseFit(e,go.READ_REFUSED,`The plan could not be fitted: the source refused a read of it (${v}).`,{reason:v});return}if(n.plan!==o||this.currentOperationId!==n.id||this.writingTargets.has(c)){this.refuseFit(e,go.STALE,"The plan changed while it was fitted: fit it again.");return}if(y.fitted){n.fit={...y.fitted,report:y.report},await this.sendPlanReady(e,n,p);return}y.report.cannotFit===void 0&&(n.fit=void 0),await this.sendPlanReady(e,n,p,y.report)}catch(l){P(this.deps,"autopilot:fit-plan","autopilot:error",e,l)}}async handleFitUndo(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.plan){this.refuseFit(e,go.NO_PLAN,"No execution plan available. Run generate-plan first.");return}if(this.writingTargets.has(t.targetOrgId)){this.refuseFit(e,Do.code,Do.message);return}t.fit=void 0;try{await this.sendPlanReady(e,t)}catch(r){P(this.deps,"autopilot:fit-undo","autopilot:error",e,r)}}async handleExecute(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.plan||!t.graph||!t.rules||!t.scanResult){Oe(this.deps,"error","Autopilot","No execution plan available. Run generate-plan first.");return}let r=D(Ph,e,"autopilot:error",this.deps);if(!r)return;let n=r,{rules:o,fit:i}=t,a=i?.plan??t.plan,d=i?.graph??t.graph,c=i?.scan??t.scanResult,l=this.deps.infraServices?.productionGuard;if(!l){X(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:ve.code}),P(this.deps,"autopilot:execute","autopilot:error",e,new Error(ve.message),{code:ve.code});return}if(this.writingTargets.has(t.targetOrgId)){P(this.deps,"autopilot:execute","autopilot:error",e,new Error(Do.message),{code:Do.code});return}this.writingTargets.set(t.targetOrgId,e.id),this.runningRequests.add(e.id);try{await this.executeRun(e,t,{plan:a,graph:d,rules:o,scanResult:c,...i?{fit:i}:{}},n,l)}finally{this.writingTargets.delete(t.targetOrgId),this.runningRequests.delete(e.id)}}async executeRun(e,t,{plan:r,graph:n,rules:o,scanResult:i,fit:a},d,c){if(!this.orchestrator)return;let l=Array.from(i.recordCounts.values()).reduce((_,V)=>_+V,0),u=a?_k(a.report,l,[...t.scanResult?.recordCounts.values()??[]].reduce((_,V)=>_+V,0)):void 0,p=new AbortController,g=()=>{},h=new Promise((_,V)=>{g=ue=>ue===void 0?_():V(ue)});h.catch(()=>{}),this.registry?.register(e.id,"autopilot","Autopilot run",h,p);let f=this.deps.orgManager.getOrg(t.targetOrgId),m={orgId:t.targetOrgId,orgTier:Ee(f),operation:"insert",objectName:r.waves[0]?.objects[0]??"AutopilotData",recordCount:l,module:"autopilot"},{check:y,decision:w}=await Ke(c,m),v=w;if((w==="refused"||w==="declined")&&X(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:w,...u?{fit:u}:{}}),w==="refused"){let _=Jr(y.blockedReason??y.impactSummary);P(this.deps,"autopilot:execute","autopilot:error",e,_,{code:St.blocked}),g(_);return}if(w==="declined"){let _="Operation cancelled by user (confirmation declined).";P(this.deps,"autopilot:execute","autopilot:error",e,new Error(_),{code:St.declined}),g(new Error(_));return}let R=Tl(r,i.recordCounts,i.personAccounts),b,O;if(d.muteAutomation===!0)try{({mute:b,read:O}=await this.runMute(t.targetOrgId,r))}catch(_){if(!kt(_))throw _;X(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:v,...u?{fit:u}:{},code:_.code}),P(this.deps,"autopilot:execute","autopilot:error",e,_,{code:_.code}),g(_);return}let k;if(d.checkpointFirst!==void 0&&R.totalRows>0){O??=await this.readTargetAutomation(t.targetOrgId,r);let _=await this.checkpointFirstOf(e,t.targetOrgId,r,d.checkpointFirst,{read:O,mute:b},p.signal);if("refused"in _){X(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:v,...u?{fit:u}:{},code:ms.CHECKPOINT_REFUSED});let V=new Error(_.refused);P(this.deps,"autopilot:execute","autopilot:error",e,V,{code:ms.CHECKPOINT_REFUSED}),g(V);return}k=_}R.totalRows>0&&(O??=await this.readTargetAutomation(t.targetOrgId,r));let S=await this.targetEmails(t.targetOrgId,r,R,b?b.automation:O),E=new Set(R.objects.map(({objectApiName:_})=>_)),I=(_,V)=>E.has(_)&&Yu(_,V),C=Re(f,t.targetOrgId),F=O?await Vt({read:O,...b?.plan?{plan:b.plan}:{},writes:I,readDeliverability:async()=>m.orgTier==="production"?Mt:jt(await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager)),accepted:!1,target:C,run:"autopilot",keepsAddresses:d.keepContactPoints===!0}):void 0,Y=await Cw({plan:R,storage:await this.readTargetDataStorage(t.targetOrgId),readApiBudget:()=>this.readTargetApiBudget(t.targetOrgId),confirmAboveRecords:this.confirmAboveRecords(),emails:S.checks,...S.unread!==void 0?{emailsUncounted:S.unread}:{},org:C,orgTier:m.orgTier,confirm:_=>c.confirmRun(_),...k?{checkpointFirst:k}:{},readBack:Ew(R),mute:Cr(b?.plan),...F?{runEmails:F}:{}});if(!Y.go){X(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:v,...u?{fit:u}:{},code:Y.code,details:En(Y.emails)});let _=new Error(Y.message);P(this.deps,"autopilot:execute","autopilot:error",e,_,{code:ms[Y.code],...await this.fitOffer(t,Y,R,k)}),g(_);return}this.liveTracker?.register(e.id,"autopilot","Autopilot run",l),this.executingOperations.add(t.id);let z=new Map,te=!1,H=b?.muted,x=Y.checkpoint,j,K=!1,Q=_=>{te||(te=!0,X(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:_,guard:v,objects:[...z.values()],source:{origin:"org",orgId:t.sourceOrgId},..._==="stopped"?{code:Ze}:{},...H?{muted:ot(H)}:{},...j?.state==="taken"?{checkpointId:j.checkpointId}:{},...u?{fit:u}:{},details:En(Y.emails)}))};try{d.grappeThreshold&&this.deps.log(`[GRAPPE] autopilot threshold set to ${d.grappeThreshold}`);for(let N of r.waves)for(let U of N.objects)this.sendNodeProgress(e,String(U),"processing",N.order);let _=new Map;for(let N of r.waves)for(let U of N.objects)_.set(String(U),N.order);let V=b?.prepared?await b.prepared.acquire(e.id).catch(N=>{if(!kt(N))throw N;return N}):void 0;if(kt(V)){x&&(j=await this.settleCheckpoint(x,!1)),te=!0,X(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:v,...u?{fit:u}:{},code:V.code}),this.liveTracker?.fail(e.id,V.message),P(this.deps,"autopilot:execute","autopilot:error",e,V,{code:V.code,...j?{extraPayload:{checkpoint:j}}:{}}),g(V);return}V&&(H=V.outcome);let ue=V?F?.afterLease(V.outcome,Y.emails?.accepted===!0):void 0;if(V&&ue){H=await V.release(),x&&(j=await this.settleCheckpoint(x,!1)),te=!0,X(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:v,code:ue.code,muted:ot(H),details:En(Y.emails)});let N=Ey(ue.message,"autopilot","Untick Mute automation to be asked about them and run it all the same"),U=new Error(N);this.liveTracker?.fail(e.id,N),P(this.deps,"autopilot:execute","autopilot:error",e,U,{code:ms.EMAILS_NOT_ACCEPTED,...j?{extraPayload:{checkpoint:j}}:{}}),g(U);return}K=!0;let re=await this.orchestrator.executePlan(r,n,o,i.recordCounts,N=>{let U=String(N.objectApiName);z.set(U,{...at(U),...N.type==="node-completed"?{created:N.successCount,failed:N.failureCount}:{created:N.partialSuccessCount,failed:N.failureCount??0}});let W=[...z.values()].reduce((ae,q)=>ae+q.created+q.failed,0);this.liveTracker?.updateProgress(e.id,l>0?Math.round(W/l*100):0,W,l,U),N.type==="node-completed"?this.sendNodeProgress(e,U,"completed",_.get(U)??0,{recordCount:N.successCount,failureCount:N.failureCount,linkedCount:N.linkedCount,refusals:N.refusals,apiCallsUsed:N.apiCallsUsed}):this.sendNodeProgress(e,U,"failed",_.get(U)??0,{recordCount:N.partialSuccessCount,failureCount:N.failureCount,linkedCount:N.linkedCount,refusals:N.refusals,error:N.errors[0]??`Execution failed for ${U}`})},p.signal,i.parentIds,{...d.keepContactPoints===!0?{keepContactPoints:!0}:{},...V?{lease:{assigned:V.outcome.assigned.length,giveBack:()=>V.release()}}:{},...a?{fit:a.run}:{}}).finally(async()=>{V&&(H=await V.release())});x&&(j=await this.settleCheckpoint(x,re.totalSuccess>0));let ie=new Set(re.completedObjects),Be=new Set(re.failedObjects),fe=new Set(re.skippedObjects),ne=new Set(re.stoppedObjects??[]),ce=[],we=0,le=[],Se=[];for(let N of r.waves)for(let U of N.objects){let W=String(U),ae=re.objectOutcomes?.[W],q=re.statuses?.[W],he=re.lookups?.[W],Fe=(ae?.leftToThePlatform??[]).reduce((_e,Ue)=>_e+Ue.count,0),Te={...ae?{recordCount:ae.written,failureCount:ae.failed,linkedCount:ae.linked,refusals:ae.refusals,...Fe>0?{leftToThePlatform:Fe}:{},...ae.currenciesReplaced?{currenciesReplaced:ae.currenciesReplaced}:{},...ae.pricesSettled?{pricesSettled:ae.pricesSettled}:{},...ae.recordTypeGiven?{recordTypeGiven:ae.recordTypeGiven}:{},...ae.cutSinceFit!==void 0?{cutSinceFit:ae.cutSinceFit}:{}}:{},...q?{statusesApplied:q.applied,statusRefusals:q.refusals}:{},...he?{lookupsFilled:he.filled,lookupRefusals:he.refusals}:{}};if(ie.has(W))this.sendNodeProgress(e,W,"completed",N.order,{recordCount:i.recordCounts.get(W)??0,failureCount:0,...Te});else if(Be.has(W))this.sendNodeProgress(e,W,"failed",N.order,{...Te,error:re.nodeErrors?.[W]??`Execution failed for ${W}`});else if(fe.has(W)){let _e=i.recordCounts.get(W)??0;z.set(W,{...at(W),skipped:"counted",..._e>0?{notSent:_e}:{}}),this.sendNodeProgress(e,W,"skipped",N.order,{recordCount:0,failureCount:0,..._e>0?{notSent:_e}:{}})}else if(ne.has(W)){let _e=ae?.notSent??0;we+=ae?.heldForTheirTask??0,z.set(W,{...at(W),created:ae?.written??0,failed:ae?.failed??0,..._e>0?{notSent:_e}:{}}),this.sendNodeProgress(e,W,"stopped",N.order,{...Te,recordCount:ae?.written??0,failureCount:ae?.failed??0,..._e>0?{notSent:_e}:{}})}let de=()=>z.get(W)??{...at(W),created:ae?.written??0,failed:ae?.failed??0},be=ae?.lookupsLeftEmpty??0,Ce=ae?.statusesNotGivenBack??0;if(be+Ce>0){let _e={...be>0?{lookupsLeftEmpty:be}:{},...Ce>0?{statusesNotGivenBack:Ce}:{}};ce.push({objectApiName:W,..._e}),z.set(W,{...de(),..._e})}he?.leftEmpty!==void 0&&(le.push({objectApiName:W,records:he.leftEmpty,refusals:he.refusals}),z.set(W,{...de(),lookupsNotFilled:he.leftEmpty}));let tt=q?.leftDraft??0;q&&tt>0&&(Se.push({objectApiName:W,records:tt,refusals:q.refusals}),z.set(W,{...de(),statusesNotApplied:tt}))}let je=Iw(re);Q(re.stopped?re.totalSuccess+re.totalFailure>0?"cancelled":"stopped":je);let M=A(this.deps,e,"autopilot:completed",{status:je,totalRecords:re.totalSuccess+re.totalFailure+re.totalSkipped,totalSuccessCount:re.totalSuccess,totalFailureCount:re.totalFailure,totalElapsedMs:re.elapsedMs,totalApiCalls:0,...H?{mutedAutomation:H}:{},...j?{checkpoint:j}:{},...re.cutSinceFit!==void 0?{cutSinceFit:re.cutSinceFit}:{},...le.length>0?{lookupsNotFilled:le}:{},...Se.length>0?{statusesNotApplied:Se}:{},...re.stopped?{stopped:!0,notWritten:re.stoppedObjects??[],...ce.length>0?{leftByStop:ce}:{},...we>0?{emailsHeldForTheirTask:we}:{}}:{}});this.deps.broker.postToWebview(M),re.stopped?this.liveTracker?.cancel(e.id):je==="failure"?this.liveTracker?.fail(e.id,re.fatalError??"No record could be written."):je==="partial"?this.liveTracker?.partial(e.id):this.liveTracker?.complete(e.id),g()}catch(_){this.liveTracker?.fail(e.id,T(_)),g(_),x&&j===void 0&&(j=await this.settleCheckpoint(x,K)),Q("failure"),P(this.deps,"autopilot:execute","autopilot:error",e,_,j?{extraPayload:{checkpoint:j}}:void 0),Oe(this.deps,"error","Autopilot",`Execution failed: ${T(_)}`)}finally{this.executingOperations.delete(t.id)}}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",Mr);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):Mr}async readTargetDataStorage(e){try{let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return await new ge(Ku).withTimeout("autopilot:limits",()=>dr(t))}catch(t){return{unread:T(t)}}}setMuteLeases(e){this.muteLeases=e}muteLeases={};async runMute(e,t){let r=await this.readTargetAutomation(e,t);return{mute:await this.planMute(e,r),read:r}}planMute(e,t){return mt(async()=>Et(await B(e,this.deps.orgRegistry,this.deps.orgManager)),t,{...this.muteLeases,writes:Yu})}async readTargetAutomation(e,t){let r=this.targetAutomation;return new ge(Uk).withTimeout("autopilot:automation",()=>r.read(e,Vi(t))).catch(n=>({unread:T(n)}))}async checkpointFirstOf(e,t,r,n,o,i){let a=this.beforeRunCheckpoints;if(!a)return{refused:ar(new Error("SandForge's checkpoints are not set up in this window"))};let{read:d,mute:c}=o,l="objects"in d?Ar(d,c?.plan,Yu):{firing:[]},u={module:"autopilot",orgId:t,operationId:e.id,written:Vi(r),running:l,request:n},p={operationId:Hk(e.id)};try{return{estimate:await a.scope(u,p),take:h=>a.take(u,p,{planned:h,signal:i})}}catch(g){return{refused:ar(g)}}}async settleCheckpoint(e,t){let r=this.beforeRunCheckpoints;if(!r)return e;try{return await r.settle(e,t)}catch(n){return this.deps.log(`[WARN] autopilot:execute: the checkpoint '${e.name}' taken before the run is kept, as it could not be settled (${T(n)})`),e}}async fitOffer(e,t,r,n){if(t.code!=="STORAGE_EXCEEDED"&&t.code!=="API_BUDGET_EXCEEDED")return{};let{targetOrgId:o}=e,{check:i}=t,a=this.deps.orgManager.getOrg(o),d={org:Re(a,o),estimateMB:i.estimateMB,...i.verdict==="unread"?{}:{remainingMB:i.remainingMB,maxMB:i.maxMB}};try{let c=await this.planWriteGate(o,r,await this.readTargetDataStorage(o),n?.estimate);return{extraPayload:{...d,writeGate:c}}}catch(c){return this.deps.log(`[WARN] autopilot:execute: what the plan comes to could not be read again (${T(c)})`),{extraPayload:d}}}async readTargetApiBudget(e){let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return new ge(Ku).withTimeout("autopilot:limits",()=>Xt(t))}async targetEmails(e,t,r,n){let o=this.targetAutomation,i=await Tw({plan:r,objects:Vi(t),readAutomation:a=>n?"objects"in n?Promise.resolve(n):Promise.reject(new Error(n.unread)):new ge(Uk).withTimeout("autopilot:automation",()=>o.read(e,a)),readLimits:async()=>{let a=await B(e,this.deps.orgRegistry,this.deps.orgManager);return new ge(Ku).withTimeout("autopilot:limits",()=>cr(a))}});i.unread!==void 0&&this.deps.log(`[WARN] autopilot:execute: the emails the target's flows send were not counted: ${i.unread} could not be read`);for(let a of i.checks.filter(d=>d.verdict==="unread"))this.deps.log(`[WARN] autopilot:execute: about ${a.emails} ${a.limit} from the target's flows, against a limit that could not be read: ${a.unread??""}`);return i}sendNodeProgress(e,t,r,n,o){let i=A(this.deps,e,"autopilot:node-progress",{nodeId:t,objectName:t,status:r,wave:n,...o??{}});this.deps.broker.postToWebview(i)}hasExecutingOperation(){return this.executingOperations.size>0}handlePause(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}if(!this.hasExecutingOperation()){Oe(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.pause();for(let t of this.runningRequests)this.liveTracker?.pause(t);Oe(this.deps,"info","Autopilot","Execution paused.")}catch(t){P(this.deps,"autopilot:pause","autopilot:error",e,t),Oe(this.deps,"error","Autopilot",`Pause failed: ${T(t)}`)}}handleResume(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}if(!this.hasExecutingOperation()){Oe(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.resume();for(let t of this.runningRequests)this.liveTracker?.resume(t);Oe(this.deps,"info","Autopilot","Execution resumed.")}catch(t){P(this.deps,"autopilot:resume","autopilot:error",e,t),Oe(this.deps,"error","Autopilot",`Resume failed: ${T(t)}`)}}handleSkipNode(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=D(Dh,e,"autopilot:error",this.deps);if(!t)return;let r=t;if(!this.hasExecutingOperation()){Oe(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.skip(r.objectApiName),Oe(this.deps,"info","Autopilot",`Skipped node: ${r.objectApiName}`)}catch(n){P(this.deps,"autopilot:skip-node","autopilot:error",e,n),Oe(this.deps,"error","Autopilot",`Skip failed: ${T(n)}`)}}handleComplianceReport(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.profile||!t.rules||!t.scanResult){Oe(this.deps,"error","Autopilot","No compliance data available. Run generate-plan first.");return}try{let r=t.fit?.scan??t.scanResult,n=this.orchestrator.generateReport(t.profile,t.rules,r.recordCounts,"","",r.totalObjectsScanned),o=A(this.deps,e,"autopilot:compliance-report",{report:n});this.deps.broker.postToWebview(o)}catch(r){P(this.deps,"autopilot:compliance-report","autopilot:error",e,r),Oe(this.deps,"error","Autopilot",`Report generation failed: ${T(r)}`)}}};import{AsyncLocalStorage as rD}from"node:async_hooks";var nD=new rD;async function Bk(s){let e=new Map;return{result:await nD.run(e,s),sent:e}}function qk(s,e){let t=s.get(e.sourceOrgId)??0,r=e.targetOrgId===e.sourceOrgId?0:s.get(e.targetOrgId)??0;return t+r>0?{source:t,target:r}:void 0}import*as Qu from"node:path";var Ld="forge:imported-templates",oD=10,Wk="forge",sD=G({folder:L().min(1),templates:ke(Vn()),replacing:ke(L())});function _r(s){if(typeof s!="object"||s===null||Array.isArray(s))return!1;let{id:e}=s;return typeof e=="string"&&e.length>0}function Ls(s,e,t){let r=new Map;for(let i of e)r.has(i.id)||r.set(i.id,i);let n=s.map(i=>t.has(i.id)?r.get(i.id)??i:i),o=new Set(s.map(i=>i.id));for(let[i,a]of r)o.has(i)||n.push(a);return n}function Zu(s,e){return Qu.resolve(s)===Qu.resolve(e)}function ep(s){let e=s.get(Ld);if(!Array.isArray(e))return[];let t=[];for(let r of e){let n=sD.safeParse(r);if(!n.success)continue;let{folder:o,templates:i,replacing:a}=n.data;t.push({folder:o,templates:i.filter(_r),replacing:a})}return t}function Fd(s,e){return ep(s).find(t=>Zu(t.folder,e))}function zk(s,e,t,r){if(t.length===0)return;let n=ep(s),o=n.findIndex(d=>Zu(d.folder,e)),i=o>=0?n.splice(o,1)[0]:void 0,a=new Map((i?.templates??[]).map(d=>[d.id,d]));for(let d of t)a.set(d.id,d);n.push({folder:i?.folder??e,templates:[...a.values()],replacing:[...new Set([...i?.replacing??[],...r])]}),s.set(Ld,n.slice(-oD),Wk)}function Gk(s,e){let t=ep(s).filter(r=>!Zu(r.folder,e));t.length>0?s.set(Ld,t,Wk):s.delete(Ld)}function iD(s){return{seed:s.seed,draw:s.draw,share:s.share,sha256:s.sha256,drawnAt:s.drawnAt,...s.drawnBy?{drawnBy:s.drawnBy}:{},...s.drawnAgain?{drawnAgain:s.drawnAgain}:{},...s.ofTheRunRetried?{ofTheRunRetried:!0}:{},objects:s.objects.map(e=>({objectApiName:e.objectApiName,sourceRows:e.sourceRows,kept:e.kept,roots:e.roots,below:e.below,asParents:e.asParents,...e.whole?{whole:e.whole}:{},...e.childrenCut?{childrenCut:e.childrenCut.map(({field:t,rows:r})=>({field:t,rows:r}))}:{},written:e.written,goneSinceTheSample:e.goneSinceTheSample,changedSinceTheSample:e.changedSinceTheSample})),...s.leftEmpty?{leftEmpty:s.leftEmpty.map(({objectApiName:e,field:t,rows:r})=>({objectApiName:e,field:t,rows:r}))}:{}}}function Jk(s){let{leftOut:e,...t}=s.graph,r=new Map;for(let u of e??[])r.set(u.reason,(r.get(u.reason)??0)+1);let n=[...r].map(([u,p])=>({reason:u,count:p})).sort((u,p)=>p.count-u.count||u.reason.localeCompare(p.reason)),{idRemapWithTheirRecord:o,sample:i,config:a,...d}=s,c=s.remapInJournal?void 0:o,l=a?.sample?{...a.sample}:void 0;return l&&delete l.plan,{...d,graph:{...t,edges:[],withoutEdges:!0},...a?{config:l?{...a,sample:l}:a}:{},...i?{sample:iD(i)}:{},...n.length>0?{leftOutCounts:n}:{},...c?{idRemapWithTheirRecord:c}:{}}}var Vk="SELECT Id, Name, Username FROM User WHERE IsActive = true AND UserType = 'Standard' ORDER BY Name LIMIT 2001";function Xk(s,e){let t=s.flatMap(r=>{let{Id:n,Name:o,Username:i}=r;return typeof n!="string"||typeof o!="string"?[]:[{id:n,name:o,username:typeof i=="string"?i:""}]});return{users:t.slice(0,2e3),truncated:e||t.length>2e3}}var np=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,jo=L().min(1).max(128),dD=G({recordId:L().regex(np,"Invalid Salesforce record ID"),orgId:jo}),hn=xp.superRefine((s,e)=>{if(s.inputMode!=="org"&&s.depth!=="all"&&s.sample===void 0)return;let t=$c(s);t!==void 0&&e.addIssue({code:"custom",message:t,path:["inputMode"]});let r=cD(s.sample);r!==void 0&&e.addIssue({code:"custom",message:r.message,path:r.path})});function cD(s){if(s?.plan!==void 0)return{message:"The panel names no plan of a sample: a run takes up the plan of its last simulation of itself. plan must be left out",path:["sample","plan"]};if(s?.maxTotal!==void 0)return{message:"The panel bounds a sample by the data storage it may take, not by its records (the command line\u2019s --max-total). maxTotal must be left out",path:["sample","maxTotal"]}}var lD=G({config:hn}),uD=G({graph:Sr,config:hn,anonymizationRules:Ks.optional(),files:jp.optional(),retryOf:L().min(1).max(200).optional(),reviewSkipped:ze().optional(),muteAutomation:ze().optional(),checkpointFirst:pf.optional()}).superRefine((s,e)=>{let t=Mp(s.config,s.files);t!==void 0&&e.addIssue({code:"custom",message:t,path:["files"]})});function pD(s,e){let t=s.check(e);return{check:t,decision:t.allowed?"allowed":"refused"}}var Kk="FILES_NOT_ACCEPTED",Yk="RETRY_UNAVAILABLE",gD="GRAPH_WITHOUT_EDGES",fD="This graph is the one the history keeps of a clone of the whole org, without the relations between its objects, and cannot be run as it is. Discover the org again from the Forge panel. Nothing was read or written.",hD="WHOLE_ORG_DIRECT",mD="A clone of the whole org is not started by Clone directly: Review lists what it leaves out and the personal fields it copies as they are. Open Review and execute it from there. Nothing was read or written.",yD="WHOLE_ORG_REHEARSAL",wD="A clone of the whole org is not rehearsed: a rehearsal holds every row it prepares. Simulate it, which stops at its gate, and its confirmation lists what it writes. Nothing was read or sent.",bD="A clone of the whole org keeps its journal on disk, which could not be opened. Nothing was written.",xo="JOURNAL_GONE",gn="The ids of this run's records were kept in its journal, which is gone: they can no longer be removed, verified, retried against or exported from here.",RD="RESUME_UNAVAILABLE",Qk="RESUME_TARGET_CHANGED",tp="RESUME_CHANGED",vD=G({forgeId:L().min(1).max(200),graph:Sr.optional(),config:hn.optional(),muteAutomation:ze().optional()}).strict(),Zk=new Set(["cancelled","failure","interrupted"]),fn="Forge execution was aborted before it started. Nothing was written.",rp="FORGE_RUNNING",SD="FORGE_STOP_AMBIGUOUS",kD={stopped:{code:"DISCOVERY_STOPPED",message:"The discovery was stopped before it finished. Discover again to see the graph."},superseded:{code:"DISCOVERY_SUPERSEDED",message:`The discovery was stopped to make way for a newer one: ${3} discoveries at most are walked at once in this window. Discover again to see the graph.`}},OD=G({requestId:L().min(1).max(200).optional()}).optional(),ID=G({template:Lc}),AD=G({forgeId:L().min(1).max(200),includeChanged:ze().optional(),sweep:ze().optional(),again:ze().optional(),muteAutomation:ze().optional(),sweepLate:ze().optional(),sweepUntied:ze().optional()}),TD=G({forgeId:L().min(1).max(200),again:ze().optional(),sweptObjects:uf.optional()}),ED=G({forgeId:L().min(1).max(200)}),PD=G({forgeId:L().min(1).max(200),recordId:L().regex(np,"Invalid Salesforce record ID")}).strict(),CD=G({forgeId:L().min(1).max(200)}).strict(),DD=G({forgeId:L().min(1).max(200)}).strict(),xD=5e3,MD=G({templateId:L().min(1).max(200)}),jD=G({graph:Sr,config:hn}),ND=G({framework:L().min(1).max(50),graph:Sr,config:hn,anonymizationRules:Ks.optional()}),$D=G({sourceOrgId:jo,targetOrgId:jo,objectApiNames:ke(L().regex(/^[A-Za-z][A-Za-z0-9_]*$/).max(80)).max(100)}),LD=G({graph:Sr,config:hn,anonymizationRules:Ks.optional()}),FD=G({targetOrgId:jo,graph:Sr}),_D=G({graph:Sr,config:hn}),UD=G({orgId:jo}),HD=G({targetOrgId:jo,objectApiNames:ke(L().min(1).max(255)).max(5e3)}),BD=G({graph:Sr,config:hn,muteAutomation:ze().optional()}).refine(s=>s.config.inputMode==="org",{message:"A sample is drawn from a clone of the whole org alone (inputMode org, depth all)",path:["config","inputMode"]}),qD="A sample of the whole org keeps its plan on disk, in the extension\u2019s storage, which this window has none of. Nothing was read or written.",WD=16;function eO(s){let e=s.fit();return e?{fit:e}:{}}function _d(s,e){let t=0,r=null,n=null,o=a=>{s(...a),t=Date.now(),r=null},i=((...a)=>{r=a;let d=e-(Date.now()-t);d<=0?(n&&(clearTimeout(n),n=null),o(a)):n||(n=setTimeout(()=>{n=null,r&&o(r)},d))});return i.flush=()=>{n&&(clearTimeout(n),n=null),r&&o(r)},i}function zD(){let s=new Map;return e=>{let t=s.get(e.objectName)??{},r={...t,...typeof e.recordCount=="number"?{recordCount:(t.recordCount??0)+e.recordCount}:{},...typeof e.fieldCount=="number"?{fieldCount:e.fieldCount}:{},...typeof e.createableFieldCount=="number"?{createableFieldCount:e.createableFieldCount}:{}};return s.set(e.objectName,r),{...e,...r}}}function nt(s,e,t,r){return D(s,e,t,r)}function GD(s,e){let t=new Set,r=e.find(n=>n.forgeId===s);for(;r&&!t.has(r.forgeId);){if(t.add(r.forgeId),r.checkpoint?.state==="taken")return r.checkpoint;let n=r.retryOf;r=n===void 0?void 0:e.find(o=>o.forgeId===n)}}function tO(s){return s.successCount+s.updatedCount>0}function rO(s,e){let t=new Set,r=s;for(;r&&!t.has(r.forgeId);){if(t.add(r.forgeId),r.undo)return r;let n=r.retryOf;r=n===void 0?void 0:e.find(o=>o.forgeId===n)}}function JD(s){let e=new Set([...s.created,...s.unattributed??[]].flatMap(({ids:r})=>r.map(n=>n.slice(0,15)))),t=new Set(s.remap.withTheirRecord??[]);return s.remap.linked.filter(r=>{let n=s.remap.table[r];return!t.has(r)&&n!==void 0&&e.has(n.slice(0,15))}).length}function VD(s,e){let t=s.remap.createdByObject.reduce((d,c)=>d+c.sourceIds.length,0),r=Object.keys(s.remap.table).length,n=JD(s),o=new Set(s.remap.withTheirRecord??[]),i=s.remap.linked.filter(d=>o.has(d)),a=r>Ki?{idRemapTable:{},idRemapExisting:[],idRemapCreated:[],idRemapByObject:s.remap.createdByObject.map(({objectApiName:d,sourceIds:c})=>({objectApiName:d,created:c.length,linked:0})),remapInJournal:!0,...i.length>0?{withTheirRecordCount:i.length}:{}}:{idRemapTable:s.remap.table,idRemapExisting:s.remap.linked,idRemapCreated:s.remap.createdByObject,...i.length>0?{idRemapWithTheirRecord:i}:{}};return{forgeId:s.parts>1?`${s.journalId}-${s.parts-1}`:s.journalId,status:"partial",interrupted:!0,graph:e,duration:0,timestamp:s.partStartedAt,idRemapCount:r,...a,createdCount:t,linkedExistingCount:s.remap.linked.length,...n>0?{linkedToCreatedCount:n}:{},journalId:s.journalId,journalPart:Math.max(0,s.parts-1),...s.endBefore?{retryOf:s.endBefore.forgeId,resumed:!0}:{},...s.runUserId?{runUserId:s.runUserId}:{},...s.checkpoint?{checkpoint:s.checkpoint}:{}}}var XD=new Set(["forge:preview","forge:discover","forge:execute","forge:pause","forge:resume","forge:abort","forge:templates:list","forge:templates:save","forge:templates:delete","forge:history:list","forge:undo","forge:resume-run","forge:open-record","forge:verify:request","forge:export-ids:request","forge:plan:request","forge:compliance:request","forge:metadata-diff:request","forge:rehearse:request","forge:automation:request","forge:undo-automation:request","forge:undo-sweep:request","forge:gaps:request","forge:users:request","forge:target-records:request","forge:sample-budget:request"]),nO=3e4,KD=3e4,YD=6e4,Fs=6e4,QD=12e4;function oO(s){let e=Date.parse(s.writtenBetween?.first??""),t=Date.parse(s.writtenBetween?.last??"");if(Number.isFinite(e)&&Number.isFinite(t))return{from:e,to:t};let r=Date.parse(s.timestamp);return{from:r-Math.max(0,s.duration),to:r}}var sO="The history no longer holds this run: what its id map holds cannot be told from what the target\u2019s automation created, and nothing is swept. Remove its records without the sweep.",ZD=6e4,ex=10*6e4,tx=8,rx=8,Mo=3e4,nx=3e4,iO="forge:templates",aO="forge:history";function ox(s,e,t){let r=new Set([s]),n=new Set;for(let o=!0;o;){o=!1;let i=a=>{r.has(a)||(r.add(a),o=!0)};for(let a of e)a.journalId!==void 0&&r.has(a.forgeId)&&!n.has(a.journalId)&&(n.add(a.journalId),o=!0);for(let a of n)for(let d of t.get(a)??[])i(d);for(let a of e){a.journalId!==void 0&&n.has(a.journalId)&&i(a.forgeId);let d=a.retryOf;d!==void 0&&(r.has(a.forgeId)?i(d):r.has(d)&&i(a.forgeId))}}return{inLine:r,journals:n}}function sx(s,e,t,r){let n=new Map;for(let i of[...e,...t])i.retryOf!==void 0&&!n.has(i.forgeId)&&n.set(i.forgeId,i.retryOf);let o=i=>{let a=new Set;for(let d=n.get(i);d!==void 0;d=n.get(d)){if(d===s)return!0;if(a.has(d))return!1;a.add(d)}return!1};return e.flatMap(i=>{if(!i.resumed||i.remapInJournal||i.targetOrgId!==r)return[];if(!o(i.forgeId))return[];let a=i.idRemapTable??{},d=(i.idRemapExisting??[]).flatMap(l=>{let u=a[l];return u!==void 0?[u]:[]}),c=i.wroteToEarlierParts??[];return c.length===0&&d.length===0?[]:[{span:gO(i.writtenBetween,i),...c.length>0?{wrote:c}:{},...d.length>0?{linked:d}:{}}]})}function gO(s,e){return s?{runStartedAt:new Date(s.first),runEndedAt:new Date(s.last)}:{runDurationMs:e.duration,runRecordedAt:new Date(e.timestamp)}}function ix(s,e){let t=[...new Set(s.flatMap(r=>r.keptDependents>0?r.heldBy:[]))];return e.flatMap(r=>{if(r.undo)return[];let n=[...s.map(a=>a.objectApiName),...e.flatMap(a=>a===r?[]:a.objects)],o=Kr(r.objects,n),i=t.filter(a=>o.includes(a));return i.length>0?[{forgeId:r.forgeId,objects:i}]:[]})}function ax(s){return s.map(e=>({objectApiName:e.objectApiName,jobId:e.jobId,rows:e.rows,...e.state!==void 0?{state:e.state}:{},...e.processed!==void 0?{processed:e.processed}:{},...e.graceLeftMs!==void 0?{minutesLeft:Math.max(1,Math.ceil(e.graceLeftMs/6e4))}:{}}))}function dx(s){return(s.mayHaveBeenWritten??[]).reduce((e,{sourceIds:t})=>e+t.length,0)}function cx(s,e){if(!e||e.calls===0)return dx({mayHaveBeenWritten:s});let t=e.lookedFor??new Set,r=(s??[]).reduce((n,{sourceIds:o})=>n+o.filter(i=>!t.has(i)).length,0);return Dl(e)+r}function lx(s,e){if(!e.journalRead)return;let t=e.callsNotLookedFor??0,r=e.reconciled?.lookedFor??new Set,n=t>0?0:(s??[]).reduce((o,{sourceIds:i})=>o+i.filter(a=>!r.has(a)).length,0);if(!(t===0&&n===0))return{...t>0?{callsAfterRemoval:t}:{},...n>0?{notJournaled:n}:{}}}function ux(s,e){if(!s)return;let t=s.map(r=>({...r}));for(let{objectApiName:r,rows:n}of e){let o=t.find(i=>i.objectApiName===r);o?o.created+=n:t.push({objectApiName:r,created:n,linked:0})}return t}var dO="forge";function px(s){let e={...s};return delete e.sourceOrgId,delete e.targetOrgId,e}function gx(s){let e=(s.errors??[]).filter(r=>!r.objectApiName.startsWith("__")),t=[...new Set(e.filter(r=>r.failedCount>0||r.skipped).map(r=>r.objectApiName))];return{status:s.status,created:s.createdCount??s.idRemapCount-(s.linkedExistingCount??0),linked:s.linkedExistingCount??0,updated:s.updatedCount??0,failed:e.reduce((r,n)=>r+n.failedCount,0),durationMs:s.duration,...t.length>0?{objectsWithFailures:t.slice(0,20),why:fx(e)}:{},...s.failedReads?.length?{failedReads:s.failedReads}:{}}}function fx(s){let e=new Map;for(let t of s){if(t.failedCount===0&&!t.skipped)continue;let r=e.get(t.objectApiName)??new Set;e.set(t.objectApiName,r);let n=t.samples.flatMap(o=>o.messages).map(o=>/^([A-Z][A-Z0-9_]+):/.exec(o)?.[1]).filter(o=>o!==void 0);n.length===0&&r.add(t.stage);for(let o of n)r.add(o)}return Object.fromEntries([...e].slice(0,20).map(([t,r])=>[t,[...r].slice(0,5)]))}function hx(s,e){let t=s.nodes.filter(d=>d.included),r=t.map(d=>d.objectApiName).join(", ")||"ForgeData",n=fy,o=e.inputMode==="org"?void 0:e.maxRecordsPerObject,i=e.inputMode==="record"&&typeof e.recordId=="string",a=0;for(let d of t)if(d.recordCountUnknown===!0){if(o===void 0)return{objectName:r,recordCount:"unknown",alsoWrites:n};a+=o,i=!0}else a+=o===void 0?d.recordCount:Math.min(d.recordCount,o);return{objectName:r,recordCount:i?{atMost:a}:a,alsoWrites:n}}function mx(s,e,t){return{forgeId:`forge-${Date.now()}`,status:t.wouldBeRefused.length>0?"failure":"success",graph:s,duration:Date.now()-e,timestamp:new Date().toISOString(),idRemapCount:0,createdCount:0,dryRun:!0,wouldInsertCount:t.totalRows}}function cO(s,e){let t=e.nodes.map(n=>`${n.objectApiName}:${n.included||n.leftOutByUser===!0?1:0}`).sort(),r=e.edges.map(n=>`${n.sourceObject}>${n.targetObject}:${n.required===!0?1:0}`).sort();return JSON.stringify([s,t,r])}function lO(s,e){let t=(e.nodes??[]).map(r=>r.objectApiName).sort();return JSON.stringify([s.sourceOrgId,s.targetOrgId,t])}function yx(s,e){return e.size===0?s:{...s,objectsRead:s.objectsRead.filter(t=>!e.has(t)),objects:s.objects.filter(t=>!e.has(t.objectApiName))}}function uO(s,e){return s.apiCalls===void 0?s:{...s,apiCalls:s.apiCalls+e}}function pO(s,e){return!s.sample||!e||!e.drawnAgain&&!e.ofTheRunRetried?s:{...s,sample:{...s.sample,...e.drawnAgain?{drawnAgain:e.drawnAgain}:{},...e.ofTheRunRetried?{ofTheRunRetried:!0}:{}}}}function wx(s){return s instanceof Error&&s.name==="ForgeAbortedError"}var Ud=class extends Error{constructor(t,r){super(r);this.code=t;this.name="RehearsalStoppedError"}code};function bx(s){return{sampled:s.sampled,judged:s.judged,passed:s.passed,linked:s.linked??0,refused:s.judged-s.passed-(s.linked??0),notJudged:s.notJudged,updatesJudged:s.updatesJudged,updatesRefused:s.updatesJudged-s.updatesPassed,updatesNotRehearsed:s.updatesNotRehearsed,calls:s.calls}}var Hd=class s{constructor(e,t,r){this.deps=e;this.externalBrowser=t??new gr,this.saveDialog=r??new Qr}deps;abortController=null;stops=new Yw;executeOperationId=null;writingTo=null;orchestrator;planGenerator;complianceService;metadataDiff;targetAutomation;targetGaps;requestsSent;muteOrgOf;muteLeases;lostBulkJobs;beforeRunCheckpoints;rehearser;rehearseOperationId=null;templateStore;removalPlans;runJournal;otherModuleRuns=()=>Promise.resolve([]);journalsRunning=new Set;describeGlobalCache=new ys({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});dmlTracker=new hi;removing=new Set;trials=new rb;simulations=new By;sampleSimulations=new Map;verifying=new Set;automationReads=new Map;automationReadAgain=new Set;discoverySent=new Map;liveTracker;lastWriteAt=new Map;static DUPLICATE_COOLDOWN_MS=6e4;static MAX_HISTORY=20;externalBrowser;saveDialog;forgetOrg(e){this.describeGlobalCache.invalidate(e),this.orchestrator?.clearDiscoveryCache([e]);for(let[t,r]of this.automationReads)r.orgId===e&&this.automationReads.delete(t)}setForgeOrchestrator(e,t){this.orchestrator=e,t&&(this.planGenerator=t.planGenerator,this.complianceService=t.complianceService,this.metadataDiff=t.metadataDiff,this.targetAutomation=t.targetAutomation,this.targetGaps=t.targetGaps,this.templateStore=t.templateStore,this.removalPlans=t.removalPlans,this.runJournal=t.runJournal,this.requestsSent=t.requestsSent,this.muteOrgOf=t.muteOrg,this.muteLeases=t.muteLeases,this.lostBulkJobs=t.lostBulkJobs,this.rehearser=t.rehearser)}setLiveOperationTracker(e){this.liveTracker=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}trackRun(e,t,r,n=!1){let o=this.deps.infraServices?.backgroundRegistry;if(!o)return()=>{};let i=()=>{},a=new Promise((c,l)=>{i=u=>{u===void 0?c():l(u instanceof Error?u:new Error(String(u)))}}),d=new AbortController;return d.signal.addEventListener("abort",()=>{r.abort(),n&&this.orchestrator?.abort()},{once:!0}),o.register(e,"forge",t,a,d),i}isWritingTo(e,t){return this.writingTo===e&&(t===void 0||t!==this.executeOperationId)}async handle(e){if(!XD.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"forge:preview":return await this.handleForgePreview(e),!0;case"forge:discover":return await this.handleDiscover(e),!0;case"forge:execute":return await this.handleExecute(e),!0;case"forge:pause":return this.handlePause(e),!0;case"forge:resume":return this.handleResume(e),!0;case"forge:abort":return this.handleAbort(e),!0;case"forge:templates:list":return await this.handleTemplatesList(e),!0;case"forge:templates:save":return await this.handleSaveTemplate(e),!0;case"forge:templates:delete":return await this.handleDeleteTemplate(e),!0;case"forge:history:list":return await this.handleHistoryList(e),!0;case"forge:undo":return await this.handleUndo(e),!0;case"forge:resume-run":return await this.handleResumeRun(e),!0;case"forge:open-record":return await this.handleOpenRecord(e),!0;case"forge:verify:request":return await this.handleVerify(e),!0;case"forge:export-ids:request":return await this.handleExportIds(e),!0;case"forge:plan:request":return await this.handlePlanRequest(e),!0;case"forge:compliance:request":return await this.handleComplianceRequest(e),!0;case"forge:metadata-diff:request":return await this.handleMetadataDiffRequest(e),!0;case"forge:rehearse:request":return await this.handleRehearseRequest(e),!0;case"forge:automation:request":return await this.handleAutomationRequest(e),!0;case"forge:undo-automation:request":return await this.handleUndoAutomation(e),!0;case"forge:undo-sweep:request":return await this.handleUndoSweep(e),!0;case"forge:gaps:request":return await this.handleGapsRequest(e),!0;case"forge:users:request":return await this.handleUsersRequest(e),!0;case"forge:target-records:request":return await this.handleTargetRecordsRequest(e),!0;case"forge:sample-budget:request":return await this.handleSampleBudgetRequest(e),!0;default:return!1}}async loadTemplates(){if(!this.templateStore){let e=this.deps.configStore.get(iO);return{templates:Array.isArray(e)?e.filter(_r):[]}}return this.withImportedTemplates(this.templateStore)}async withImportedTemplates(e){let t=Fd(this.deps.configStore,e.workspacePath);if(!t)return{templates:await e.list()};let r;try{r=await e.merge(t.templates,new Set(t.replacing))}catch(n){let o=T(n);return se.warn(`Imported forge templates not written into .sandforge/: ${o}`),{templates:await e.list(),importNotMerged:o}}return Gk(this.deps.configStore,e.workspacePath),se.info("Merged an imported set of forge templates into .sandforge/"),{templates:r}}async saveTemplates(e){if(!this.templateStore){this.deps.configStore.set(iO,e,dO);return}let t=await this.templateStore.list();for(let r of t.filter(n=>!e.some(o=>o.id===n.id)))await this.templateStore.delete(r.id);for(let r of e)await this.templateStore.save(r)}loadHistory(){return this.deps.configStore.get(aO)??[]}saveHistory(e){this.deps.configStore.set(aO,e,dO)}noteForgeWrite(e){let t=Date.now();for(let[r,n]of this.lastWriteAt)t-n>=s.DUPLICATE_COOLDOWN_MS&&this.lastWriteAt.delete(r);this.lastWriteAt.set(e,t)}async handleForgePreview(e){let t=nt(dD,e,"forge:preview:error",this.deps);if(!t)return;let{recordId:r,orgId:n}=t;try{let o=await B(n,this.deps.orgRegistry,this.deps.orgManager),i=r.substring(0,3),a=this.describeGlobalCache.get(n);if(!a){let w=await o.describeGlobal();De(o.limitInfo,"forge:preview describeGlobal"),a=w.sobjects.map(v=>({name:v.name,label:v.label,keyPrefix:v.keyPrefix??null})),this.describeGlobalCache.set(n,a)}let d=a.find(w=>w.keyPrefix===i);if(!d){let w=A(this.deps,e,"forge:preview:error",{message:`Unknown object for key prefix "${i}"`});this.deps.broker.postToWebview(w);return}let c=await Yg(o,d.name,`SELECT FIELDS(STANDARD) FROM ${d.name} WHERE Id = '${Bt(r)}' LIMIT 1`);if(De(o.limitInfo,`forge:preview query ${d.name}`),!c||c.length===0){let w=A(this.deps,e,"forge:preview:error",{message:`Record not found: ${r}`});this.deps.broker.postToWebview(w);return}let l=c[0],u=new Set(["attributes","Id"]),p=Object.entries(l).filter(([w])=>!u.has(w)).filter(([,w])=>w!=null&&String(w)!=="").slice(0,8).map(([w,v])=>({name:w,value:String(v)})),g=await o.describe(d.name);De(o.limitInfo,`forge:preview describe ${d.name}`);let h=g.fields.length,f=0;try{f=(await o.query(`SELECT COUNT() FROM ${d.name}`)).totalSize}catch{}let m=f*.001,y=A(this.deps,e,"forge:preview:response",{objectApiName:d.name,objectLabel:d.label,recordId:r,fields:p,estimatedRecordCount:f,totalFieldCount:h,estimatedSize:m});this.deps.broker.postToWebview(y)}catch(o){P(this.deps,"forge:preview","forge:preview:error",e,o,{code:"PREVIEW_ERROR"})}}async handleDiscover(e){if(!this.orchestrator){P(this.deps,"forge:discover","forge:discover:error",e,new Error("Forge module is not initialized"),{code:"NOT_INITIALIZED"});return}let t=nt(lD,e,"forge:discover:error",this.deps);if(!t)return;let{config:r}=t,n=new AbortController,o=`forge-discover-${this.deps.nextId()}`,{discovery:i,superseded:a}=this.stops.beginDiscovery(e.id,n,o);for(let u of a)this.stopDiscovery(u);We(this.deps,o,"forge","Discovering object graph");let d=this.trackRun(o,"Discovering object graph",n),c,l=_d(u=>{let p=A(this.deps,e,"forge:discover:progress",u);this.deps.broker.postToWebview(p)},100);try{se.info("Forge discover started");let u=this.orchestrator,{result:p,sent:g}=await Bk(()=>u.discover(r,{...r.inputMode==="org"?{}:{maxNodes:r.maxNodes},signal:n.signal,onProgress:y=>{l(y)}}));if(l.flush(),n.signal.aborted){pe(this.deps,o,{aborted:!0}),this.answerStoppedDiscovery(e,i);return}let h=qk(g,r),f=lO(r,p);this.discoverySent.delete(f),h&&this.discoverySent.set(f,h);for(let y of this.discoverySent.keys()){if(this.discoverySent.size<=rx)break;this.discoverySent.delete(y)}let m=A(this.deps,e,"forge:discover:response",{graph:h?{...p,discoveryRequests:h}:p});this.deps.broker.replyToRequester(m),pe(this.deps,o,{nodeCount:p.nodes?.length??0}),se.info("Forge discover finished",{objects:p.nodes?.length??0,records:p.totalRecords})}catch(u){if(l.flush(),n.signal.aborted){pe(this.deps,o,{aborted:!0}),this.answerStoppedDiscovery(e,i);return}c=u,P(this.deps,"forge:discover","forge:discover:error",e,u,{code:"DISCOVER_ERROR",retryable:!0}),Le(this.deps,o,T(u),!0)}finally{d(c),this.stops.endDiscovery(i)}}stopDiscovery(e){this.deps.infraServices?.backgroundRegistry?.abort(e.operationId),e.controller.abort()}answerStoppedDiscovery(e,t){let{code:r,message:n}=kD[t.stop??"stopped"];P(this.deps,"forge:discover","forge:discover:error",e,new Error(n),{code:r,retryable:!0})}async handleExecute(e,t){if(!this.orchestrator){P(this.deps,"forge:execute","forge:execute:error",e,new Error("Forge module is not initialized"),{code:"NOT_INITIALIZED"});return}let r=t?t.startedWith:nt(uD,e,"forge:execute:error",this.deps);if(!r)return;let{graph:n,config:o,anonymizationRules:i,files:a,reviewSkipped:d,muteAutomation:c}=r,l=t?t.forgeId:r.retryOf,u=l!==void 0?GD(l,this.loadHistory()):void 0,p=l===void 0?r.checkpointFirst:void 0;l!==void 0&&r.checkpointFirst!==void 0&&se.info("Forge run: no checkpoint taken for a retry or a resume, which takes up a run that wrote",{checkpoint:u?.checkpointId??"none"});let g=o.dryRun===!0,h=Ml(n,o),f=Hy(o),m=new nb(o,{reviewSkipped:d===!0,...this.trials.before(h)}),y=o.inputMode==="org",w=y&&o.sample!==void 0,v=(Ne,Ge)=>{g||X(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",code:Ne,context:m.context()}),P(this.deps,"forge:execute","forge:execute:error",e,new Error(Ge),{code:Ne})};if(n.withoutEdges===!0){v(gD,fD);return}if(y&&d===!0){v(hD,mD);return}let R=y?Jw(n):void 0;if(R){v(R.code,R.message);return}let b=a?Cp(o.anonymizePII,a.acceptedAsIs):null;if(b){X(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",code:Kk,context:m.context()}),P(this.deps,"forge:execute","forge:execute:error",e,new Error(b),{code:Kk});return}let O,k;if(l!==void 0&&!t){let Ne=await this.runToRetry(l,o.targetOrgId);if("refused"in Ne){X(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",code:Yk,context:m.context()}),P(this.deps,"forge:execute","forge:execute:error",e,new Error(Ne.refused),{code:Yk});return}O=Ne.written,k=Ne.journalId!==void 0?{journalId:Ne.journalId}:{}}let S=this.deps.infraServices?.productionGuard;if(!S){X(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",code:ve.code,context:m.context()}),P(this.deps,"forge:execute","forge:execute:error",e,new Error(ve.message),{code:ve.code});return}let E=this.deps.orgManager.getOrg(o.targetOrgId),I=Ee(E),C=Re(E,o.targetOrgId);if(I==="production"){this.refuseAtGate(e,o.targetOrgId,new ct("PRODUCTION_TARGET",`${C} is a production org, or an org SandForge cannot tell is a sandbox, a scratch org or a Developer Edition org: Forge writes to those only. Nothing was read or written.`),void 0,m.context());return}let F=await this.ownerMapRefusal(o);if(F){g||X(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",code:F.code,context:m.context()}),P(this.deps,"forge:execute","forge:execute:error",e,F,{code:F.code,retryable:!0});return}let Y={orgId:o.targetOrgId,orgTier:I,operation:"insert",...hx(n,o),module:"forge"},z=new AbortController,te=this.stops.awaitGuard(e.id,z),{check:H,decision:x}=g?pD(S,Y):await Ke(S,Y).finally(te);g&&te();let j=x;if(H.warnings.length>0&&se.warn("Forge run: Production Guard warnings",{warnings:H.warnings}),(x==="refused"||x==="declined")&&X(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",guard:x,context:m.context()}),x==="refused"){P(this.deps,"forge:execute","forge:execute:error",e,new Error(`Operation blocked by Production Guard: ${H.blockedReason??H.impactSummary}`),{code:"GUARD_BLOCKED"});return}if(x==="declined"){P(this.deps,"forge:execute","forge:execute:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}if(z.signal.aborted){X(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",guard:x,code:gt,context:m.context()}),P(this.deps,"forge:execute","forge:execute:error",e,new Error(fn),{code:gt,retryable:!0});return}let K=`${o.sourceOrgId}:${o.targetOrgId}:${o.recordId??""}`,Q=n.nodes?.map(Ne=>Ne.objectApiName).join(",")??"",_=`forge:${K}:${Q}:${n.totalRecords??0}`+(l!==void 0?`:${t?"resume":"retry"}:${l}`:""),V=this.dmlTracker.isDuplicate(_)?this.dmlTracker.get(_):void 0,ue=this.lastWriteAt.get(_),me=ue!==void 0&&Date.now()-ue<s.DUPLICATE_COOLDOWN_MS;if(V?.status==="pending"||me){se.warn("Duplicate forge execution detected",{operationId:_}),P(this.deps,"forge:execute","forge:execute:error",e,new Error(`Duplicate forge operation: ${_}`),{code:"DUPLICATE"});return}if(this.executeOperationId!==null){X(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",guard:x,code:rp,context:m.context()}),P(this.deps,"forge:execute","forge:execute:error",e,new Error("Another Forge run is still under way in this window: start this one once it has ended. A run asked to stop ends once the step under way is done."),{code:rp,retryable:!0});return}let re=n.totalRecords??0;V?(V.status="pending",V.recordCount=re,V.registeredAt=new Date().toISOString()):this.dmlTracker.register(_,"forge","upsert",re),this.abortController=z;let ie=`forge-execute-${this.deps.nextId()}`,Be=g?"Simulating forge operation":"Executing forge operation";We(this.deps,ie,"forge",Be);let fe=this.trackRun(ie,Be,z,!0);this.liveTracker?.register(ie,"forge",Be),this.executeOperationId=ie,this.writingTo=g?null:o.targetOrgId,this.stops.beginRun(e.id,z);let ne=Date.now(),ce,we,le,Se,je,M=!1,N=()=>{M||!we||(M=!0,we.close())},U={keep:!1},W=!1,ae=async()=>{if(!ce||W)return;W=!0;let Ne=ce,Ge=U;N(),await(Ge.keep?this.runJournal?.stop(Ne,Ge.status,Ge.forgeId):this.runJournal?.end(Ne))?.catch(rt=>{se.warn(`Forge run journal not ${Ge.keep?"kept":"dropped"}: ${T(rt)}`)}),this.journalsRunning.delete(Ne)},q={requests:0},he,Fe=()=>{let Ne=this.requestsSent?.();return Ne===void 0||he===void 0?void 0:q.requests+Ne-he},Te,de=!1,be=[],Ce,tt=0,_e,Ue,lt,Wn,br=[],yn,Ws=()=>(yn??=this.jobsStillRunning(o.targetOrgId,Wn,q).then(Ne=>{br=Ne}),yn),Ur,wn={firing:[]},zn,Rr,zs,Zt,Fo=!1,It,bn,_o=_d(Ne=>{let Ge=A(this.deps,e,"forge:progress",Ne);this.deps.broker.postToWebview(Ge)},100),Gn=_d(Ne=>{this.deps.broker.postToWebview(A(this.deps,e,"forge:sampling:progress",{...Ne}))},100),Gs=this.liveProgressOf(ie,n),vr=zD(),Mc=this.orchestrator.on("forge:progress",Ne=>{let Ge=vr(Ne),rt=Fe(),Ye=rt===void 0?Ge:{...Ge,apiCalls:rt};Gs(Ye);let ht=Ye.status;if(ht==="done"||ht==="error"||ht==="skipped"||ht==="stopped"){_o.flush();let et=A(this.deps,e,"forge:progress",Ye);this.deps.broker.postToWebview(et);return}_o(Ye)});try{se.info("Forge execute started",{source:Re(this.deps.orgManager.getOrg(o.sourceOrgId),"unknown org"),target:Re(this.deps.orgManager.getOrg(o.targetOrgId),"unknown org")});let Ne=this.maxRecordsPerObject(),Ge=Ol(n,{leftOut:new Set(n.nodes.filter(ri).map(Z=>Z.objectApiName)),retry:l!==void 0}),rt=new Set(Ge.map(Z=>Z.objectApiName)),Ye=(Z,ee)=>ee==="insert"||ee==="update"&&rt.has(Z);if(g){if(p!==void 0||y||w){let Z=await this.automationBeforeTheRun(o.targetOrgId,n);if("automation"in Z){let ee=c===!0?await mt(()=>this.muteOrg(o.targetOrgId),Z.automation,{...this.muteLeases,writes:Ye}).then(Ae=>Ae.plan,Ae=>{se.warn(`Forge simulation: the mute could not be planned (${T(Ae)})`)}):void 0;wn=Ar(Z.automation,ee,Ye),zn=ee}}}else{let Z=await this.automationBeforeTheRun(o.targetOrgId,n);tt=nn("automation"in Z?Z.automation:Z);let ee=Z,Ae;if(c===!0){let Ve=await mt(()=>this.muteOrg(o.targetOrgId),"automation"in Z?Z.automation:Z,{...this.muteLeases,writes:Ye});Ue=Ve.prepared,lt=Ve.muted,Ae=Ve.plan,"automation"in Z&&Ve.automation&&(ee={...Z,automation:Ve.automation})}if((p!==void 0||w||y)&&"automation"in Z&&(wn=Ar(Z.automation,Ae,Ye)),Ce=ee,"automation"in ee&&(be=rg(ee.automation)),z.signal.aborted)throw de=!0,new Error(fn);if(m.automationRead(ee,Ge),Zt=await Vt({read:"automation"in Z?Z.automation:Z,...Ae?{plan:Ae}:{},writes:Ye,applyAssignmentRules:o.applyAssignmentRules===!0,readDeliverability:()=>this.readDeliverability(o.targetOrgId,z.signal),accepted:!1,target:C,run:"clone",keepsAddresses:o.keepContactPoints===!0}),q.requests+=Zt.ofRun.read?.requests??0,z.signal.aborted)throw de=!0,new Error(fn);m.emailsRead(Zt.gate.audit);let xe=await this.confirmAutomation(S,{orgId:o.targetOrgId,org:C,orgTier:I,username:E?.username},ee,Ge,d===!0,Zt.gate.confirmation);xe==="confirmed"&&(m.confirm("automation"),Zt.gate.verdict==="asks"&&(Fo=!0,m.confirm("emails"))),j=us(j,xe);let ut=y?[]:Uy(n,o.maxRecordsPerObject,Ne);if(ut.length>0){if(z.signal.aborted)throw de=!0,new Error(fn);let Ve=await this.confirmReadCeiling(S,{org:C,orgTier:I,source:Re(this.deps.orgManager.getOrg(o.sourceOrgId),o.sourceOrgId)},ut,Ne);Ve==="confirmed"&&m.confirm("volume"),j=us(j,Ve)}}if(z.signal.aborted)throw de=!0,new Error(fn);let ht=g?void 0:this.runUserOf(o.targetOrgId),et=await this.loadRecordTypeMappings(o,z.signal,q);if(z.signal.aborted)throw de=!0,new Error(fn);le=await ht,ne=Date.now(),he=this.requestsSent?.(),Wn=this.lostBulkJobs?.count;let bt=g?void 0:this.runJournal;if(bt){let Z=t?.journalId??`forge-run-${ne}`;if(ce=Z,this.journalsRunning.add(Z),we=await(t?bt.resuming(Z).then(async()=>{let Ae=await B(o.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),xe=await bt.reconcile(Z,Pl(Ae));for(let Ve of Cl(xe,C))se.info(`Forge resume: ${Ve.trim()}`);Se=xe.uncertain,je=xe.underway;let ut=this.loadHistory().find(Ve=>Ve.forgeId===t.forgeId);ut&&xe.found.length>0&&await this.withRowsFoundAfterStop(ut,xe.found)}):bt.begin(Z,o.targetOrgId,new Date(ne),{...this.resumeHeadOf(n,o,i,Ne),...c===!0?{muteAutomation:!0}:{},...a?{files:a}:{}},le)).then(()=>bt.open(Z),Ae=>{se.warn(`Forge run journal not started: ${T(Ae)}`)}),t&&!we)throw new Error("The journal of the run to resume could not be opened, or the target could not be read for the calls the run had under way. Nothing was written.")}if(y&&!g&&!we)throw new Error(bD);if(w&&(It=await this.sampleOf({graph:n,config:o,anonymizationRules:i,readCeiling:Ne,dryRun:g,...ce!==void 0?{journalId:ce}:{},resumes:t!==void 0,...k?{retried:k}:{},volumeCase:f,target:C,lookup:q,room:()=>Al(wn,Ye).perRecord,onProgress:Gn})),z.signal.aborted)throw de=!0,new Error(fn);let er,Hr=y?zw(o):void 0,Lt=this.writeGate({guard:S,targetOrgId:o.targetOrgId,org:C,orgTier:I,lookup:q,emailsPerInsert:be,...Ce!==void 0?{automation:Ce}:{},...on(Zt?.ofRun),sentBefore:tt+(this.discoverySent.get(lO(o,n))?.target??0),mute:Cr(Ue?.plan??zn),mayBeInTarget:Se,...je&&je.length>0?{jobsUnderway:je}:{},...g?{}:{simulated:this.simulations.of(f)},updatedAfterInsert:[...rt],...y?{automationRoom:()=>Al(wn,Ye).perRecord}:{},...y?{wholeOrg:{source:Re(this.deps.orgManager.getOrg(o.sourceOrgId),o.sourceOrgId),sourceOrgId:o.sourceOrgId,graph:n,anonymizePII:o.anonymizePII,...Hr?{carried:Hr}:{}}}:{},...p!==void 0?{checkpoint:{ask:{module:"forge",orgId:o.targetOrgId,operationId:ie,running:wn,request:p},own:{operationId:ie},signal:z.signal,onEstimate:Z=>{zs=Z},onTaken:Z=>{Rr=Z,bt&&ce&&we&&bt.keepCheckpoint(ce,Z).catch(ee=>{se.warn(`Forge run journal: the checkpoint taken first not named (${T(ee)})`)})},onProgress:Z=>{let ee=co(Z);$e(this.deps,ie,Z,0,0,ee),this.liveTracker?.updateProgress(ie,Z,0,0,ee)}}}:{},onSimulated:Z=>{_e=Z},...w?{sampled:Z=>{Gn.flush();let ee=It?.drawnAgain,Ae=ee||It?.ofTheRunRetried?{...Z,plan:{...Z.plan,...ee?{drawnAgain:ee}:{},...It?.ofTheRunRetried?{ofTheRunRetried:!0}:{}}}:Z;return m.sampled(Ae),Ae}}:y?{onSampleOffer:Z=>{bn=Z}}:{},onConfirmed:()=>{j=us(j,"confirmed"),m.confirm("volume")}}),Rt=await this.orchestrator.execute(n,o,{recordTypeMappings:et,anonymizationRules:i,files:a,writtenBefore:O,stream:{ceiling:Ne,...we?{store:we,summaryBound:Ki}:{},...It?{sample:It.stream}:{}},...le?{runUserId:le}:{},beforeWrite:async Z=>{let ee=await Lt(Z);if(!Ue||Z.dryRun||er)return ee;let Ae=await Ue.acquire(ie);er=Ae,lt=Ae.outcome;let xe=Zt?.afterLease(Ae.outcome,Fo);if(xe)throw new ct(xe.code,xe.message);return{...ee,lease:{assigned:Ae.outcome.assigned.length,giveBack:async()=>(await Ws(),Ae.release())}}}}).catch(Z=>{if(!Vw(Z))throw Z;return Ur=Z.dryRun,mx(n,ne,Z.dryRun)}).finally(N).finally(async()=>{er&&(await Ws(),lt=await er.release())}),dt=pO(uO(Rt,q.requests),It),Ht=dt.remapInJournal&&we&&ce?{journalId:ce,journalPart:Math.max(0,we.partCount-1)}:{},Js=lt?{mutedAutomation:lt,...br.length>0?{bulkJobsPastMute:br,errors:[...dt.errors??[],...xl(br)]}:{}}:{},Br=g?zs:Rr?await this.settleCheckpoint(Rr,(dt.createdCount??dt.idRemapCount-(dt.linkedExistingCount??0))+(dt.updatedCount??0)>0):u,$=Br?{checkpoint:Br}:{},J=t&&!g&&we&&ce?await this.wroteToEarlierPartsOf(dt,ce,we.partCount-1):{},oe=l!==void 0?{...dt,...Ht,...Js,...$,retryOf:l,...t?{resumed:!0}:{},...J}:{...dt,...Ht,...Js,...$};"journalId"in Ht&&!g&&(U={keep:!0,status:"success",forgeId:oe.forgeId});let Ie=oe.createdCount??oe.idRemapCount-(oe.linkedExistingCount??0);oe.status!=="failure"&&Ie>0&&this.noteForgeWrite(_),oe.status==="failure"&&(Te=new Error("Forge execution finished with a failure status.")),g?(this.trials.note("simulation",h),_e&&this.simulations.note(f,_e),It&&Ur?.sample&&this.noteSampleSimulation(f,It.fingerprint)):(X(this.deps,{action:"forge_execute",module:"forge",operationId:ie,orgId:o.targetOrgId,outcome:oe.status,guard:j,objects:Qc(oe),source:{origin:"org",orgId:o.sourceOrgId},carried:Zc(oe),...Zo(oe.contactPoints),...eO(m),context:m.context(oe.decisionsApplied),...lt?{muted:ot(lt)}:{},...Br?.state==="taken"?{checkpointId:Br.checkpointId}:{}}),this.addToHistory(oe,o)),se.info("Forge execute finished",gx(oe)),await ae(),Gn.flush();let ye=A(this.deps,e,"forge:execute:response",{result:oe,operationId:ie,...Ur?{wholeOrgDryRun:Ur}:{},...bn?{sampleOffer:bn}:{}});this.deps.broker.postToWebview(ye),this.dmlTracker.markCompleted(_),pe(this.deps,ie,{status:oe.status}),oe.status==="failure"?this.liveTracker?.fail(ie,"Forge execution finished with a failure status."):oe.status==="partial"?this.liveTracker?.partial(ie):this.liveTracker?.complete(ie)}catch(Ne){Gn.flush();let Ge=Zy(Ne,t?"resume":"draw")??Ne,rt=lw(Ge)?Ge:uw(Ge),Ye=kt(Ge)?Ge:void 0;(rt?.code==="AUTOMATION_DECLINED"||rt?.code==="READ_DECLINED"||rt?.code==="WRITE_DECLINED")&&(j=us(j,"declined"));let ht=de||wx(Ge)||rt!==void 0||Ye!==void 0;ht||(Te=Ge);let et=rt||Ye?void 0:jw(Ge),bt=et?Xg(et):void 0,er=bt?Qc(bt):[],Hr=de||rt||Ye?"stopped":ht?Kg(et,er):"failure",Lt=rt?rt.code:Ye?Ye.code:de?gt:Hr==="stopped"?Ze:void 0,Rt=Rr?await this.settleCheckpoint(Rr,et?tO(et):!(de||rt||Ye)):u;se.info("Forge execute stopped",{outcome:Hr,...Lt?{code:Lt}:{},...et?{created:et.successCount,linked:et.linkedCount,failed:et.failedCount}:{}});let dt=et&&!g?this.keepStoppedRun(pO(et,It),n,o,{startedAt:ne,cancelled:ht,retryOf:l,resumed:t!==void 0,callsBefore:q.requests,...we&&ce?{journalId:ce,journalPart:Math.max(0,we.partCount-1)}:{},...Rt?{checkpoint:Rt}:{},...le?{runUserId:le}:{},...br.length>0?{bulkJobsPastMute:br}:{},...t&&we&&ce?await this.wroteToEarlierPartsOf({idRemapTable:et.remapTable,idRemapCreated:et.createdByObject,...et.remapInJournal?{remapInJournal:!0}:{}},ce,we.partCount-1):{}}):void 0;we&&ce&&dt?U={keep:!0,status:ht?"cancelled":"failure",forgeId:dt.forgeId}:t&&(U={keep:!0,...t.end}),g||X(this.deps,{action:"forge_execute",module:"forge",operationId:ie,orgId:o.targetOrgId,outcome:Hr,...Lt?{code:Lt}:{},guard:j,...bt?{objects:er,source:{origin:"org",orgId:o.sourceOrgId},carried:Zc(bt)}:{},...Zo(et?.contactPoints),...eO(m),context:m.context(et?.decisionsApplied),...lt?{muted:ot(lt)}:{},...Rt?.state==="taken"?{checkpointId:Rt.checkpointId}:{}}),this.dmlTracker.markFailed(_),this.lastWriteAt.delete(_),It?.adoptedFrom!==void 0&&ce!==void 0&&!U.keep&&!(et&&tO(et))&&await this.giveThePlanBack(ce,It.adoptedFrom),await ae();let Ht=Rr&&Rt?{checkpoint:Rt}:{};P(this.deps,"forge:execute","forge:execute:error",e,Ge,{code:Lt??(ht?Ze:"EXECUTE_ERROR"),retryable:!0,...dt?{extraPayload:{result:U.keep?{...dt,resumable:!0}:dt}}:rt?.stop?{extraPayload:{gate:rt.stop,...Ht,...bn?{sampleOffer:bn}:{}}}:Rr?{extraPayload:Ht}:{}}),ht?(this.deps.infraServices?.backgroundRegistry?.abort(ie),pe(this.deps,ie,{aborted:!0}),this.liveTracker?.cancel(ie)):(Le(this.deps,ie,T(Ge),!0),this.liveTracker?.fail(ie,T(Ge))),U.keep&&this.liveTracker?.offerResume(ie,U.forgeId)}finally{await ae(),fe(Te),this.executeOperationId===ie&&(this.executeOperationId=null,this.writingTo=null),this.stops.endRun(e.id),Mc(),_o.flush(),this.abortController=null}}addToHistory(e,t){let r={...t.inputMode==="org"?Jk(e):e,config:px(t),targetOrgId:t.targetOrgId,sourceOrgId:t.sourceOrgId},n=[r,...this.loadHistory()];this.saveHistory(n.slice(0,s.MAX_HISTORY)),this.keepRemovalPlans(r,n.slice(s.MAX_HISTORY))}keepStoppedRun(e,t,r,n){if(!(e.remapInJournal?e.successCount>0:e.createdByObject.some(d=>d.sourceIds.length>0)))return;let i=uO(Vg(e,t,{startedAt:n.startedAt,status:n.cancelled?"partial":"failure"}),n.callsBefore),a={...i,...n.cancelled?{cancelled:!0}:{},...n.retryOf!==void 0?{retryOf:n.retryOf}:{},...n.retryOf!==void 0&&n.resumed?{resumed:!0}:{},...n.journalId?{journalId:n.journalId}:{},...n.journalId&&n.journalPart!==void 0?{journalPart:n.journalPart}:{},...n.checkpoint?{checkpoint:n.checkpoint}:{},...n.runUserId?{runUserId:n.runUserId}:{},...n.wroteToEarlierParts?{wroteToEarlierParts:n.wroteToEarlierParts}:{},...n.bulkJobsPastMute?{bulkJobsPastMute:n.bulkJobsPastMute,errors:[...i.errors??[],...xl(n.bulkJobsPastMute)]}:{}};return this.addToHistory(a,r),a}async wroteToEarlierPartsOf(e,t,r){let n=this.runJournal;if(!n||e.remapInJournal||r<1)return{};let o=new Set(Or(e).flatMap(({ids:i})=>i.map(a=>a.slice(0,15))));try{let i=(await n.wroteIn(t,r)).filter(a=>!o.has(a.slice(0,15)));return i.length>0&&i.length<=Ki?{wroteToEarlierParts:i}:{}}catch(i){return se.warn(`Forge run journal not read for what the part wrote: ${T(i)}`),{}}}async ownerMapRefusal(e){let t=e.ownerMappings??{};if(Object.keys(t).length!==0)try{let r=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager);return await Mw(t,async n=>(await r.query(n)).records)}catch(r){se.warn(`Forge run: the users its owners are mapped to could not be read first (${T(r)})`);return}}runUserOf(e){return tb(async()=>(await B(e,this.deps.orgRegistry,this.deps.orgManager)).identity(),"forge:execute")}async settleCheckpoint(e,t){let r=this.beforeRunCheckpoints;if(!r)return e;try{return await r.settle(e,t)}catch(n){return se.warn(`Forge run: the checkpoint '${e.name}' taken before it is kept, as it could not be settled (${T(n)})`),e}}async runToRetry(e,t){let r=this.loadHistory(),n=r.find(d=>d.forgeId===e);if(!n)return{refused:"The run to retry is no longer in the history, so what it wrote is not known. Run the clone again from Review."};if(n.targetOrgId!==t)return{refused:"The run to retry wrote to another org than this one."};if(!n.idRemapTable)return{refused:"The run to retry kept no record of what it wrote. Run the clone again from Review."};let o=new Set,i=n;for(;i&&!o.has(i.forgeId);){if(o.add(i.forgeId),i.undo)return{refused:`The records ${i===n?"the run to retry created":"a run it was built on created"} were removed on ${i.undo.removedAt}: there is nothing to retry against. Run the clone again from Review.`};let d=i.retryOf;i=d===void 0?void 0:r.find(c=>c.forgeId===d)}let a=await this.withIdsOf(n);return"gone"in a?{refused:a.gone}:{written:a.entry.idRemapTable??{},...n.journalId!==void 0?{journalId:n.journalId}:{}}}liveProgressOf(e,t){let r=t.nodes.filter(i=>i.included).length,n=new Set,o=0;return i=>{(i.status==="done"||i.status==="error"||i.status==="skipped")&&!n.has(i.objectName)&&(n.add(i.objectName),o+=i.recordCount??0);let d=r>0?Math.min(100,Math.round(n.size/r*100)):0;this.liveTracker?.updateProgress(e,d,o,0,i.message)}}handlePause(e){this.orchestrator?.pause(),this.executeOperationId&&this.liveTracker?.pause(this.executeOperationId),se.info("Forge paused")}handleResume(e){this.orchestrator?.resume(),this.executeOperationId&&this.liveTracker?.resume(this.executeOperationId),se.info("Forge resumed")}handleAbort(e){let t=nt(OD,e,"forge:abort:error",this.deps);if(t===null)return;let r=this.stops.stop(t?.requestId,{discovery:n=>this.stopDiscovery(n),run:()=>{this.executeOperationId&&this.deps.infraServices?.backgroundRegistry?.abort(this.executeOperationId),this.abortController?.abort(),this.abortController=null,this.orchestrator?.abort()}});if("refused"in r){if(r.refused==="none"){se.info("Forge stop: no operation under way answers it");return}P(this.deps,"forge:abort","forge:abort:error",e,new Error(`${r.live} Forge operations are under way in this window, and the stop did not say which one it was for: nothing was stopped. Stop it from its own screen, or from Live Operations.`),{code:SD});return}se.info("Forge stopped",{what:r.stops.kind})}refuseAtGate(e,t,r,n,o){X(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:t,outcome:"stopped",...n?{guard:n}:{},code:r.code,...o?{context:o}:{}}),P(this.deps,"forge:execute","forge:execute:error",e,r,{code:r.code,retryable:!0,...r.stop?{extraPayload:{gate:r.stop}}:{}})}keepAutomationRead(e,t,r){let n=cO(e,t);this.automationReads.delete(n),this.automationReads.set(n,{orgId:e,at:Date.now(),read:r});for(let o of this.automationReads.keys()){if(this.automationReads.size<=tx)break;this.automationReads.delete(o)}r.catch(()=>{this.automationReads.get(n)?.read===r&&this.automationReads.delete(n)})}readAutomationAgain(e){for(let[t,r]of this.automationReads)r.orgId===e&&this.automationReads.delete(t);this.automationReadAgain.add(e)}async removalMute(e,t,r,n=[],o=!1){let i=this.targetAutomation,a=[...new Set([...Kr(t,n,{userKept:o}),...r])],d=i?await new ge(Fs).withTimeout("forge:undo-automation",()=>i.read(e,a)).catch(l=>({unread:T(l)})):{unread:"no reader of the target org's automation is set up"},c=new Set(zt(t));return mt(()=>this.muteOrg(e),d,{...this.muteLeases,writes:(l,u)=>u==="delete"||u==="update"&&c.has(l)})}async muteOrg(e){return this.muteOrgOf?this.muteOrgOf(e):Et(await B(e,this.deps.orgRegistry,this.deps.orgManager))}async automationBeforeTheRun(e,t){let r=new Set(t.nodes.filter(d=>!d.included).map(d=>d.objectApiName)),o=this.automationReadAgain.delete(e)?void 0:this.automationReads.get(cO(e,t));if(o&&Date.now()-o.at<ex)try{return{automation:yx(await o.read,r),reused:!0}}catch{}let i=this.targetAutomation;if(!i)return{unread:"no reader of the target org's automation is set up"};let a=new Set(t.nodes.filter(ri).map(d=>d.objectApiName));try{return{automation:await new ge(Fs).withTimeout("forge:automation",()=>i.readForGraph(e,t,a)),reused:!1}}catch(d){return{unread:T(d)}}}async confirmAutomation(e,t,r,n,o,i={}){let a="automation"in r?r.automation:void 0,d=n.map(y=>y.objectApiName),c=a?Sl(a):[],l=a?kl(a,d):[],u=a?Il(a):[{part:"automation",reason:"unread"in r?r.unread:""}];se.info("Forge target automation before the run",{..."reused"in r?{reused:r.reused}:{},firedOnInsert:c.length,firedOnUpdate:l.length,unread:u.map(y=>y.part)});let p=c.length===0&&l.length===0&&u.length===0,g=a?ng(a):[],h=i.deliverability!==void 0;if(p&&!h&&!(o&&g.length>0))return"allowed";let f=a&&!p?dw(a,d):[],m=await e.confirmRun({stage:"automation",org:t.org,orgTier:t.orgTier,fired:c,firedOnUpdate:l,updateSteps:aw(n.filter(y=>l.some(w=>w.objectApiName===y.objectApiName))),unread:u,bypass:f,assign:a&&!p?cw(a,f,t.username?{alias:t.org,username:t.username}:void 0):[],...g.length>0?{removal:g}:{},...i});if(m==="confirmed")return"confirmed";throw this.readAutomationAgain(t.orgId),m==="declined"?new ct("AUTOMATION_DECLINED",p&&!h?"Forge execution was cancelled at the confirmation of what may refuse a removal of the records it creates. Nothing was read or written.":"Forge execution was cancelled at the confirmation of what the target org runs as it inserts and updates the records. Nothing was read or written."):new ct("CONFIRMATION_UNAVAILABLE","Forge execution needed a confirmation of what the target org runs as it inserts and updates the records, and there was no one to ask. Nothing was read or written.")}async confirmReadCeiling(e,t,r,n){se.info("Forge read past the ceiling",{ceiling:n,objects:Object.fromEntries(r.slice(0,20).map(i=>[i.objectApiName,i.rows]))});let o=await e.confirmRun({stage:"read",org:t.org,orgTier:t.orgTier,source:t.source,objects:r,ceiling:n});if(o==="confirmed")return"confirmed";throw o==="declined"?new ct("READ_DECLINED","Forge execution was cancelled at the confirmation of the tables it reads with no cap per object. Nothing was read or written.",void 0,n):new ct("CONFIRMATION_UNAVAILABLE","Forge execution needed a confirmation of the tables it reads with no cap per object, and there was no one to ask. Nothing was read or written.")}maxRecordsPerObject(){let e=this.deps.services?.getSandforgeSetting?.("forge.maxRecordsPerObject",bl);return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.floor(e),og):bl}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",Mr);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):Mr}async readTargetEmailLimits(e){try{let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return await new ge(Mo).withTimeout("forge:limits",()=>cr(t))}catch(t){return{unread:T(t)}}}async readTargetDataStorage(e){try{let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return await new ge(Mo).withTimeout("forge:limits",()=>dr(t))}catch(t){return{unread:T(t)}}}async readTargetApiBudget(e){try{let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return await new ge(Mo).withTimeout("forge:limits",()=>Xt(t))}catch(t){return{unread:T(t)}}}async readSourceApiBudget(e,t){t.requests++;try{let r=await B(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager);return await new ge(Mo).withTimeout("forge:limits",()=>Xt(r))}catch(r){return{unread:T(r)}}}limitsTransportOf(e,t){return{request:async r=>{t.requests++;let n=await B(e,this.deps.orgRegistry,this.deps.orgManager);return new ge(Mo).withTimeout("forge:limits",()=>n.request(r))}}}async jobsStillRunning(e,t,r){let n=this.lostBulkJobs;if(!n||t===void 0)return[];let o=n.since(t,e);if(o.length===0)return[];se.info("Forge execute: waiting for the Bulk API jobs the run lost before the mute is given back",{jobs:o.map(a=>`${a.objectApiName} ${a.jobId??"(no id)"}`)});let i=await n.stillRunning(o,()=>{r.requests++});return i.length>0&&se.warn("Forge execute: Bulk API jobs still running as the mute is given back; what they write now goes in with the target\u2019s automation",{jobs:i.map(a=>`${a.objectApiName} ${a.jobId??"(no id)"}`)}),i.map(({objectApiName:a,jobId:d})=>({objectApiName:a,...d?{jobId:d}:{}}))}async sampleOf(e){let{config:t}=e,r=this.runJournal?.storagePath;if(r===void 0)throw new Error(qD);let n=this.setupFingerprintOf(e.graph,t,e.anonymizationRules,e.readCeiling),o=new Date,i,a,d,c=!1,l,u=f=>{if(!(f instanceof Nw))throw f};if(e.dryRun||e.journalId===void 0)i=$w(r,n);else if(e.retried&&!e.resumes){i=Xi(r,e.journalId);let f=e.retried.journalId,m=f!==void 0?await El.open(Xi(r,f),{fingerprint:n}).catch(u):void 0;m?(a=await Uw(m,r,e.journalId),c=!0):d="planGone"}else if(i=Xi(r,e.journalId),!e.resumes){let f=await Lw(r,n,o);if(f instanceof El)a=await Fw(f,r,e.journalId).catch(u),a?l=f.dir:d="planTaken";else if(f==="tooOld")d="tooOld";else{let m=this.sampleSimulations.get(e.volumeCase);m!==void 0&&(d=m===n?"planTaken":"setUpOtherwise")}}await Hw(r,o).catch(f=>{se.warn(`Forge sample: the plans of past simulations were not swept (${T(f)})`)});let p;if(!a&&!e.resumes){let f=await this.readSourceApiBudget(t,e.lookup);"unread"in f||(p=f.remaining)}let g=t.sample?.withinMB;return{stream:{options:t.sample??{},budget:async()=>{e.lookup.requests++;let f=await this.readTargetDataStorage(t.targetOrgId),m=Yy({storage:f,bounds:g!==void 0?{withinMB:g}:{},target:e.target});if(m)throw ct.of(m);let y=Yi({storage:f,...g!==void 0?{withinMB:g}:{},automation:e.room()});if(!y)throw new Error("No budget of the sample could be read. Nothing was written.");return y},keepAt:i,fingerprint:n,...a?{plan:a}:{},...p!==void 0?{sourceRequestsLeft:p}:{},onProgress:e.onProgress},fingerprint:n,...d?{drawnAgain:d}:{},...c?{ofTheRunRetried:!0}:{},...l!==void 0?{adoptedFrom:l}:{}}}async giveThePlanBack(e,t){let r=this.runJournal?.storagePath;r!==void 0&&await _w(r,e,t).catch(n=>{se.warn(`Forge sample: the plan of the simulation was not put back (${T(n)})`)})}noteSampleSimulation(e,t){this.sampleSimulations.delete(e),this.sampleSimulations.set(e,t);for(let r of this.sampleSimulations.keys()){if(this.sampleSimulations.size<=WD)break;this.sampleSimulations.delete(r)}}writeGate(e){let t=e.checkpoint,r=n=>t&&{...t.ask,written:n.objects.filter(({rows:o})=>o>0).map(o=>o.objectApiName)};return async n=>{let o=e.wholeOrg,i=n.wholeOrg;if(o&&!i)throw new Error("A clone of the whole org reached its write gate without what it measured of both orgs, which its gate weighs it on. Nothing was written.");let a=i?.sample?e.sampled?.(i.sample.report)??i.sample.report:void 0;if(n.dryRun&&o&&i){let H=vl(n.objects,i);e.onSimulated?.(H);let x=r(H),j;t&&x&&this.beforeRunCheckpoints&&H.totalRows>0&&(j=await this.beforeRunCheckpoints.scope(x,t.own).then(Q=>(t.onEstimate(Q),Q),Q=>{se.warn(`Forge simulation: ${ar(Q)}`)}));let K=await Ky({objects:n.objects,measures:i,graph:o.graph,anonymizePII:o.anonymizePII,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...j?{checkpoint:j}:{},...n.readBack!==void 0?{readBack:n.readBack}:{},...e.mute!==void 0?{mute:e.mute}:{},...e.deliverability!==void 0?{deliverability:e.deliverability}:{},...e.sentBefore!==void 0?{sentBefore:()=>({target:e.sentBefore??0})}:{},target:{org:e.org,limits:this.limitsTransportOf(e.targetOrgId,e.lookup)},source:{org:o.source,limits:this.limitsTransportOf(o.sourceOrgId,e.lookup)},...a?{sample:a}:{},...e.automationRoom?{automation:e.automationRoom()}:{}});if(!a&&K.storage.verdict==="exceeds"){let Q=Yi({storage:K.storage});Q&&e.onSampleOffer?.(Q.budget)}throw se.info("Forge write gate: the dry run of a clone of the whole org",{records:K.totalRows,objects:K.wouldInsert.length,targetRequests:K.targetRequests.estimate,sourceRequests:K.sourceRequests.estimate,...K.bulkBatches?{bulkBatches:K.bulkBatches.estimate}:{},wouldBeRefused:K.wouldBeRefused.map(Q=>Q.code)}),new Gw(K)}if(n.dryRun){let H=Rl(n.objects);e.onSimulated?.(H);let x=r(H);return t&&x&&this.beforeRunCheckpoints&&H.totalRows>0&&await this.beforeRunCheckpoints.scope(x,t.own).then(t.onEstimate,j=>{se.warn(`Forge simulation: ${ar(j)}`)}),{}}let d=i?Gy(i.readWholeOver):void 0;if(d)throw ct.of(d);let c=i?vl(n.objects,i):Rl(n.objects);if(c.totalRows===0)return{};e.lookup.requests++;let l=await this.readTargetDataStorage(e.targetOrgId),u=rn(c,l,o&&e.automationRoom?Xy(c,e.automationRoom()):0);if(a){let H=Qy({sample:a,storage:l,target:e.org});if(H)throw ct.of(H)}let p=this.confirmAboveRecords(),g=p>0&&c.totalRows>p?p:void 0,h=uy(e.orgTier),f=h!==void 0&&c.totalRows>h?h:void 0;se.info("Forge write gate",{records:c.totalRows,objects:Object.fromEntries(c.objects.slice(0,20).map(H=>[H.objectApiName,H.rows])),storageEstimateMB:hs(u.estimateMB),...u.verdict==="unread"?{storageUnread:u.unread}:{storageRemainingMB:u.remainingMB,storageMaxMB:u.maxMB},storage:u.verdict});let m=pw(u,e.org);if(m&&u.verdict==="exceeds"){if(o&&!a&&!("unread"in l)){let H=Yi({storage:l});H&&e.onSampleOffer?.(H.budget)}throw new ct("STORAGE_EXCEEDED",`${m} Nothing was written.`,{estimateMB:Number(hs(u.estimateMB)),remainingMB:u.remainingMB})}u.verdict==="near"?se.warn("Forge write gate: the records take more than 80 % of the data storage the target has left"):u.verdict==="unread"&&se.warn("Forge write gate: the data storage the target has left could not be read"),f!==void 0&&se.warn(`Forge write gate: more than ${f} records, a large volume`);let y=i?Jy(i.files,l,e.org):void 0;if(y?.stop)throw ct.of(y.stop);let w;"unread"in l?(e.lookup.requests++,w=await this.readTargetApiBudget(e.targetOrgId)):w=l.dailyApiRequests;let v=r(c),R;if(t&&v){let H=this.beforeRunCheckpoints;if(!H)throw new ct(tn,ar(new Error("SandForge's checkpoints are not set up in this window")));R=await H.scope(v,t.own).catch(x=>{throw new ct(tn,ar(x))})}let b=o?await this.readSourceApiBudget(o,e.lookup):void 0,O=Vy({plan:c,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...n.readBack!==void 0?{readBack:n.readBack}:{},...R?{checkpoint:R}:{},...e.mute!==void 0?{mute:e.mute}:{},...e.deliverability!==void 0?{deliverability:e.deliverability}:{},...e.sentBefore!==void 0?{sentBefore:e.sentBefore}:{},budget:w,target:e.org,...o&&i?{wholeOrg:{measures:i,bulkBatches:"unread"in l?l:l.dailyBulkApiBatches,sourceBudget:b,source:o.source}}:{}});if(se.info("Forge write gate: API requests",{estimate:O.api.estimate,verdict:O.api.verdict,...O.api.verdict==="unread"?{unread:O.api.unread}:{remaining:O.api.remaining,max:O.api.max},...O.api.parts?{parts:O.api.parts}:{}}),O.stop)throw ct.of(O.stop);let k=Ii(O.api),S=o&&i&&O.wholeOrg?Xw({run:o,measures:i,plan:c,budget:{api:O.api,wholeOrg:O.wholeOrg},...y?.files?{files:y.files}:{},...a?{sample:a,now:Date.now()}:{}}):void 0;S&&se.info("Forge write gate: a clone of the whole org",{sourceRequests:O.wholeOrg?.source.estimate,sourceApi:O.wholeOrg?.source.verdict,jobs:S.bulk?.jobs??0,...O.wholeOrg?.bulkBatches?{bulkBatches:O.wholeOrg.bulkBatches.estimate}:{},durationSeconds:Math.round(S.durationSeconds),managedPackages:S.managedPackages?.length??0,personalAsIs:S.personalAsIs?.length??0});let E=async()=>{let H=this.beforeRunCheckpoints;if(!t||!v||!R||!H)return;let x=R,j=await Gi(()=>H.take(v,t.own,{planned:x,signal:t.signal,onProgress:({percentage:K})=>t.onProgress?.(K)}));if("stop"in j)throw j.stop.code===tn?ct.of({...j.stop,code:tn}):Object.assign(new Error(j.stop.message),{name:"ForgeAbortedError"});t.onTaken(j.checkpoint)},I=[],C=[];if(e.emailsPerInsert.length>0){e.lookup.requests++;for(let H of ew(c,e.emailsPerInsert,await this.readTargetEmailLimits(e.targetOrgId)))H.verdict==="exceeds"?I.push(nw(H)):H.verdict==="unread"&&C.push(ow(H));C.length>0&&se.warn("Forge write gate: a daily email limit of the target could not be read",{limits:C.map(({limit:H,emails:x})=>({limit:H,emails:x}))}),I.length>0&&se.warn("Forge write gate: the records take the target past a daily email limit",{limits:I.map(({limit:H,emails:x,remaining:j})=>({limit:H,emails:x,remaining:j}))})}let F=e.automation===void 0?void 0:"automation"in e.automation?rw(e.automation.automation,tw(c)):`the target's automation: ${e.automation.unread}`;F!==void 0&&se.warn("Forge write gate: what of the target sends emails could not all be read, and its emails were not counted");let Y=(e.mayBeInTarget??[]).filter(({rows:H})=>H>0),z=e.simulated?qy(e.simulated,c.totalRows):void 0;if(z?.farAbove&&se.warn("Forge write gate: far more records than the last simulation of the case",{records:c.totalRows,simulated:z.total}),g===void 0&&u.verdict==="fits"&&I.length===0&&C.length===0&&F===void 0&&Y.length===0&&z?.farAbove!==!0&&!O.asks)return await E(),k;let te=await e.guard.confirmRun({stage:"write",org:e.org,orgTier:e.orgTier,objects:c.objects.map(({objectApiName:H,rows:x})=>({objectApiName:H,rows:x})),total:c.totalRows,...g!==void 0?{aboveRecords:g}:{},...f!==void 0?{largeVolume:f}:{},storage:sn(u),...c.leftOut?{leftOut:c.leftOut}:{},...n.objects.some(H=>H.counted)?{counted:!0}:{},...I.length>0?{emails:I}:{},...C.length>0?{emailsUnread:C}:{},...F!==void 0?{emailsUncounted:F}:{},...Wy(c),...zy(c),...Y.length>0?{mayBeInTarget:Y.map(({objectApiName:H,rows:x})=>({objectApiName:H,rows:x}))}:{},...Y.length>0&&e.jobsUnderway&&e.jobsUnderway.length>0?{jobsUnderway:ax(e.jobsUnderway)}:{},...n.capped?{capped:n.capped}:{},...z?{simulated:z}:{},...S?{wholeOrg:S,...O.confirmation.checkpoint?{checkpoint:O.confirmation.checkpoint}:{}}:O.confirmation});if(te==="confirmed")return e.onConfirmed(),await E(),k;throw te==="declined"?new ct("WRITE_DECLINED","Forge execution was cancelled before it wrote the records it had read. Nothing was written."):new ct("CONFIRMATION_UNAVAILABLE","Forge execution needed a confirmation before it wrote the records it had read, and there was no one to ask. Nothing was written.")}}async loadRecordTypeMappings(e,t,r){let n=()=>{},o=new Promise(i=>{n=()=>i(void 0),t.addEventListener("abort",n,{once:!0})});try{let i=new ge(nx).withTimeout("forge:record-types",()=>this.readRecordTypeMappings(e,r));return await Promise.race([i,o])}catch(i){se.warn(`[forge] Record types could not be read from both orgs (${T(i)}); cloned records keep their source RecordTypeId.`);return}finally{t.removeEventListener("abort",n)}}async readRecordTypeMappings(e,t){let[r,n]=await Promise.all([e.sourceOrgId,e.targetOrgId].map(async o=>{let i=await B(o,this.deps.orgRegistry,this.deps.orgManager),{records:a}=await or({query:async d=>(t.requests++,i.query(d)),queryMore:async d=>(t.requests++,i.queryMore(d))},Rw);return vw(a)}));for(let o of Sw(r,n))se.warn(`[forge] ${kw(o)}`);return new Ow().buildMapping(r,n)}async handleTemplatesList(e){let{templates:t,importNotMerged:r}=await this.loadTemplates(),n=A(this.deps,e,"forge:templates:list:response",{templates:t.filter(o=>Lc.safeParse(o).success),...r===void 0?{}:{importNotMerged:r}});this.deps.broker.postToWebview(n)}async handleSaveTemplate(e){let t=nt(ID,e,"forge:templates:save:error",this.deps);if(!t)return;let{template:r}=t;try{let o=[r,...(await this.loadTemplates()).templates.filter(i=>i.id!==r.id)];await this.saveTemplates(o)}catch(o){P(this.deps,"forge:templates:save","forge:templates:save:error",e,o);return}let n=A(this.deps,e,"forge:templates:save:response",{success:!0});this.deps.broker.postToWebview(n)}async handleDeleteTemplate(e){let t=nt(MD,e,"forge:templates:delete:error",this.deps);if(!t)return;let{templateId:r}=t;try{let o=(await this.loadTemplates()).templates.filter(i=>i.id!==r);await this.saveTemplates(o)}catch(o){P(this.deps,"forge:templates:delete","forge:templates:delete:error",e,o);return}let n=A(this.deps,e,"forge:templates:delete:response",{success:!0});this.deps.broker.postToWebview(n)}async handleHistoryList(e){await this.keepRunsLeftOver();let t=this.loadHistory(),r=await this.resumableRuns(t),n=[];try{n=await this.removalPlans?.list()??[]}catch(l){se.warn(`Forge removal plans could not be read: ${T(l)}`)}let o=await this.journalsPresent([...t.flatMap(l=>l.remapInJournal&&l.journalId?[l.journalId]:[]),...n.flatMap(l=>l.inJournal?[l.inJournal.journalId]:[])]),i=t.map(l=>({...l,...r.has(l.forgeId)?{resumable:!0}:{},...l.remapInJournal&&!(l.journalId&&o.has(l.journalId))?{journalGone:!0}:{}})),a=new Set(i.map(l=>l.forgeId)),d=n.filter(l=>!a.has(l.forgeId)&&Ir(l).length>0).map(l=>l.inJournal&&!o.has(l.inJournal.journalId)?{...l,journalGone:!0}:l);await this.dropJournalsNoLongerNamed(t,n);let c=A(this.deps,e,"forge:history:list:response",{history:i,...d.length>0?{olderRuns:d}:{}});this.deps.broker.postToWebview(c)}async handleUndo(e){let t=nt(AD,e,"forge:undo:error",this.deps);if(!t)return;let{forgeId:r}=t,n=t.includeChanged===!0,o=t.sweep===!0,i=t.again===!0,a=t.muteAutomation===!0,d=o&&t.sweepLate===!0,c=o&&t.sweepUntied===!0,l=(R,b)=>this.refuseUndo(e,R,b),u=this.loadHistory().find(R=>R.forgeId===r),p=u?void 0:await this.keptRemovalPlan(r),g,h={},f=u?.targetOrgId??p?.targetOrgId,m=u?u.journalId:p?.inJournal?.journalId;if(f&&m&&(!u||u.idRemapCreated)){if(this.removing.has(r)){l("The records of this run are being removed already.","DUPLICATE");return}this.removing.add(r);try{let R=await this.callsLookedForBeforeRemoval({forgeId:r,targetOrgId:f,journalId:m,removedBefore:(u??p)?.undo!==void 0});if("unread"in R){l(R.unread,"IN_FLIGHT_UNREAD");return}g=R.reconciled,h=R,g&&g.found.length>0&&(u?u=await this.withRowsFoundAfterStop(u,g.found):p&&(p=await this.planWithRowsFoundAfterStop(p,g.found)))}finally{this.removing.delete(r)}}let y,w,v=()=>{};if(u){let R=Date.parse(u.timestamp);if(!u.idRemapCreated||!u.targetOrgId||Number.isNaN(R)){l("This run was recorded before Forge kept what a run created: its records cannot be removed from the history.","NOT_RECORDED");return}let b=u.remapInJournal&&u.journalId&&u.journalPart!==void 0?{journalId:u.journalId,part:u.journalPart}:void 0,O=lx(u.mayHaveBeenWritten,{...h,reconciled:g});if(y={...u,targetOrgId:u.targetOrgId,unreachable:cx(u.mayHaveBeenWritten,g),...O?{notLookedFor:O}:{},...b?{inJournal:b}:{}},u.remapInJournal){if(w=[],i||zr(u).length>0){let k=await this.journalRecordsOf(b,u.undo,i);if("gone"in k){l(k.gone,xo);return}w=k.records,v=k.close}}else w=i?Or(u):zo(u)}else if(p){if(o){l(sO,"SWEEP_UNAVAILABLE");return}y={...p,unreachable:g&&g.calls>0?Dl(g):p.mayHaveBeenWritten??0,...h.callsNotLookedFor?{notLookedFor:{callsAfterRemoval:h.callsNotLookedFor}}:{}};let{inJournal:R}=p;if(R&&(i||Ir(p).length>0)){let b=await this.journalRecordsOf(R,p.undo,i);if("gone"in b){l(b.gone,xo);return}w=b.records,v=b.close}else w=i?p.objects.map(({objectApiName:b,ids:O})=>({objectApiName:b,ids:[...O]})):qc(p)}else{l("This run is no longer in the Forge history.","NOT_FOUND");return}try{let R=pl(w),b=o&&y.undo!==void 0;if(R===0&&!b){y.undo?l(`The records this run created were already removed, on ${y.undo.removedAt}.`,"ALREADY_REMOVED"):l("This run created no record to remove.","NOTHING_TO_REMOVE");return}if(this.removing.has(r)){l("The records of this run are being removed already.","DUPLICATE");return}this.removing.add(r);let O=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(e.id);try{await this.removeRun(e,y,w,{includeChanged:n,again:i,muteAutomation:a,sweepLate:d,sweepUntied:c,...!o&&u?.config?.inputMode==="org"?{wholeOrgNotSwept:!0}:{}},o?u:void 0,O)}finally{this.removing.delete(r),O?.release()}}finally{v()}}async journalRecordsOf(e,t,r=!1){let n=this.runJournal;if(!n||!e)return{gone:gn};try{let o=await n.recordsOf(e.journalId,e.part,r);if(o)return o;let i=await this.planRecordsOf({inJournal:e,...t?{undo:t}:{}},r);return"gone"in i?i:{records:i.records,close:()=>{}}}catch(o){return se.warn(`Forge run journal could not be read: ${T(o)}`),{gone:gn}}}async journalsPresent(e){let t=this.runJournal;if(e.length===0)return new Set;if(!t)return new Set;try{return await t.present(e)}catch(r){return se.warn(`Forge run journals could not be listed: ${T(r)}`),new Set(e)}}async dropJournalsNoLongerNamed(e,t){let r=this.runJournal;if(r)try{let n=new Set([...e.map(o=>o.journalId),...t.map(o=>o.inJournal?.journalId),...this.journalsRunning].filter(o=>o!==void 0).map(o=>r.fileNameOf(o)));for(let o of await r.endedFiles())n.has(o)||await r.forgetFile(o)}catch(n){se.warn(`Forge run journals could not be dropped: ${T(n)}`)}}async withIdsOf(e,t=!1){if(!e.remapInJournal)return{entry:e};let r=this.runJournal;if(!r||!e.journalId||e.journalPart===void 0)return{gone:gn};try{let n=await r.idsOf(e.journalId,e.journalPart);if(!n)return{gone:gn};let o=await r.leftOf(e.journalId,e.journalPart),i={...e.removalStamps,...await r.stampsOf(e.journalId,e.journalPart)};return{entry:{...e,idRemapTable:n.table,idRemapExisting:n.existing,idRemapCreated:n.createdByObject,...o?{removalLeft:o}:{},...Object.keys(i).length>0?{removalStamps:i}:{},...t&&n.withTheirRecord?{idRemapWithTheirRecord:n.withTheirRecord}:{}}}}catch(n){return se.warn(`Forge run journal could not be read: ${T(n)}`),{gone:gn}}}async planRecordsOf(e,t=!1){let r=this.runJournal;if(!r)return{gone:gn};try{let{journalId:n,part:o}=e.inJournal,i=await r.idsOf(n,o);if(!i)return{gone:gn};let a={idRemapTable:i.table,idRemapExisting:i.existing,idRemapCreated:i.createdByObject};if(t)return{records:Or(a)};let d=await r.leftOf(n,o);return{records:zo({...a,...e.undo?{undo:e.undo}:{},...d?{removalLeft:d}:{}})}}catch(n){return se.warn(`Forge run journal could not be read: ${T(n)}`),{gone:gn}}}async keptRemovalPlan(e){try{return await this.removalPlans?.get(e)}catch(t){se.warn(`Forge removal plans could not be read: ${T(t)}`);return}}async callsLookedForBeforeRemoval(e){let t=this.runJournal,{forgeId:r,journalId:n}=e;if(!t||this.journalsRunning.has(n))return{};try{if((await t.lastEnd(n))?.forgeId!==r)return{};let a=t.callsInFlight(n);if(e.removedBefore)return a>0?{journalRead:!0,callsNotLookedFor:a}:{};if(a===0)return{journalRead:!0}}catch{return{}}let o=Re(this.deps.orgManager.getOrg(e.targetOrgId),e.targetOrgId);try{let i=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await t.reconcile(n,Pl(i));for(let d of Cl(a,o,"removal"))se.info(`Forge removal: ${d.trim()}`);return{reconciled:a,journalRead:!0}}catch(i){return{unread:`${o} could not be read for the insert calls this run had under way when it stopped (${T(i)}): removed without them, the records those calls wrote would stay behind. Nothing was deleted.`}}}async datedByItsJournal(e,t){let r=this.runJournal,{journalId:n,part:o,scope:i}=e;if(!(!r||!n))try{return(await r.present([n])).has(n)?await r.writtenBetween(n,t,o,i):void 0}catch(a){se.warn(`Forge run not dated from its journal: ${T(a)}`);return}}async withRowsFoundAfterStop(e,t){let r=this.runJournal,{journalId:n,journalPart:o}=e;if(!r||!n||o===void 0)return e;let i=t.reduce((l,{rows:u})=>l+u,0),a=ux(e.idRemapByObject,t),d;if(e.remapInJournal)d={...e,idRemapCount:e.idRemapCount+i,createdCount:(e.createdCount??0)+i,...a?{idRemapByObject:a}:{}};else{let l=await r.idsOf(n,o).catch(()=>{});if(!l)return e;d={...e,idRemapTable:l.table,idRemapExisting:l.existing,idRemapCreated:l.createdByObject,idRemapCount:Object.keys(l.table).length,createdCount:l.createdByObject.reduce((u,{sourceIds:p})=>u+p.length,0),...a?{idRemapByObject:a}:{}}}this.saveHistory(this.loadHistory().map(l=>l.forgeId===d.forgeId?d:l));let c=ti(d);return c&&await this.removalPlans?.put(c).catch(l=>{se.warn(`Forge removal plan not kept: ${T(l)}`)}),d}async planWithRowsFoundAfterStop(e,t){let{inJournal:r}=e;if(!r)return e;let n=r.left.map(i=>({...i}));for(let{objectApiName:i,rows:a}of t){let d=n.find(c=>c.objectApiName===i);d?d.count+=a:n.unshift({objectApiName:i,count:a})}let o={...e,inJournal:{...r,left:n}};return await this.removalPlans?.put(o).catch(i=>{se.warn(`Forge removal plan not kept: ${T(i)}`)}),o}async keepRunsLeftOver(){let e=this.runJournal;if(e)try{let t=new Set(this.journalsRunning);for(let r of await e.leftOver(t)){let n=r.resume?.startedWith;if(!n){let o=Bw.planOf(r),i=this.removalPlans;o&&i&&await i.putIfAbsent(o),(!o||i)&&await e.forget(r.journalId);continue}if(r.created.length>0||e.callsInFlight(r.journalId)>0){let o=VD(r,n.graph);this.addToHistory(o,n.config),await e.stop(r.journalId,"interrupted",o.forgeId)}else r.endBefore?await e.stop(r.journalId,r.endBefore.status,r.endBefore.forgeId):await e.forget(r.journalId)}}catch(t){se.warn(`Forge run journals could not be read: ${T(t)}`)}}async resumableRuns(e){let t=new Set,r=this.runJournal;if(!r)return t;for(let n of e)if(!(!n.journalId||this.journalsRunning.has(n.journalId))){try{let o=await r.lastEnd(n.journalId);if(o?.forgeId!==n.forgeId||!Zk.has(o.status))continue}catch{continue}rO(n,e)===void 0&&t.add(n.forgeId)}return t}async runToResume(e){let t=this.loadHistory(),r=t.find(l=>l.forgeId===e);if(!r)return{refused:"The run to resume is no longer in the history: what it wrote and where it stopped are not known."};let n=r.targetOrgId,o=this.runJournal;if(!r.journalId||!o)return{refused:"This run kept no journal to take it up from. Retry it from its results instead.",targetOrgId:n};if(this.journalsRunning.has(r.journalId))return{refused:"This run is being taken up already.",targetOrgId:n};let i=await o.lastEnd(r.journalId);if(!i||i.forgeId!==r.forgeId||!Zk.has(i.status))return{refused:"This run was taken up already, or its run ended: only the last part of a run that stopped can be resumed.",targetOrgId:n};let a=rO(r,t);if(a!==void 0)return{refused:`The records ${a===r?"this run created":"a part of this run created"} were removed on ${a.undo?.removedAt}: there is nothing to resume against.`,targetOrgId:n};let d=await o.head(r.journalId),c=d?.resume?.startedWith;return!d?.resume||!c||d.targetOrgId!==n?{refused:"The journal of this run does not say how it was set up. Retry it from its results instead.",targetOrgId:n}:{entry:r,journalId:r.journalId,head:{...d.resume,startedWith:c},targetOrgId:d.targetOrgId,end:i}}async handleResumeRun(e){let t=nt(vD,e,"forge:execute:error",this.deps);if(!t)return;let r=(y,w,v)=>{v&&X(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:v,outcome:"stopped",code:y}),P(this.deps,"forge:execute","forge:execute:error",e,new Error(w),{code:y})},n=await this.runToResume(t.forgeId);if("refused"in n){r(RD,n.refused,n.targetOrgId);return}let{entry:o,journalId:i,head:a,targetOrgId:d,end:c}=n,l=this.deps.orgManager.getOrg(d);if(!l){r(Qk,"The org this run wrote to is no longer registered in SandForge: the run cannot be taken up there.",d);return}if(a.targetSalesforceOrgId!==void 0&&l.orgId&&l.orgId.slice(0,15)!==a.targetSalesforceOrgId.slice(0,15)){r(Qk,`${Re(l,d)} is no longer the org this run wrote to \u2014 refreshed or replaced since: what the run wrote is not there.`,d);return}let{graph:u,config:p,anonymizationRules:g}=a.startedWith,h=$c(p);if(h!==void 0){r(tp,`${h}. Nothing was read or written.`,d);return}let f=this.maxRecordsPerObject(),m=y=>Ww(a.fingerprint,y.graph,this.runSetupOf(y.config,g,f,a.targetSalesforceOrgId));if(!m({graph:u,config:p})){r(tp,"This run would now be set up otherwise than the part it resumes (sandforge.forge.maxRecordsPerObject changed since): put the setting back to take it up, or retry it.",d);return}if(t.graph&&t.config&&!m({graph:t.graph,config:t.config})){r(tp,"The clone on this page is set up otherwise than the run to resume: its objects, filters or decisions changed since.",d);return}await this.handleExecute(e,{forgeId:o.forgeId,journalId:i,head:a,end:c,startedWith:{graph:u,config:p,...g?{anonymizationRules:g}:{},...t.muteAutomation===!0||a.muteAutomation===!0?{muteAutomation:!0}:{},...a.files?{files:a.files}:{}}})}resumeHeadOf(e,t,r,n){let o=this.targetSalesforceOrgIdOf(t);return{sourceOrgId:t.sourceOrgId,fingerprint:this.setupFingerprintOf(e,t,r,n),...o?{targetSalesforceOrgId:o}:{},startedWith:{graph:e,config:t,...r?{anonymizationRules:r}:{}}}}targetSalesforceOrgIdOf(e){let t=this.deps.orgManager.getOrg(e.targetOrgId)?.orgId;return t&&np.test(t)?t:void 0}setupFingerprintOf(e,t,r,n){return this.fingerprintOf(e,t,r,n,this.targetSalesforceOrgIdOf(t))}fingerprintOf(e,t,r,n,o){return qw(e,this.runSetupOf(t,r,n,o))}runSetupOf(e,t,r,n){return{config:{...e,dryRun:void 0},anonymizationRules:t??{},ceiling:e.inputMode==="org"?null:r,targetSalesforceOrgId:n?.slice(0,15)??null}}keepRemovalPlans(e,t){let r=this.removalPlans;if(!r)return;let n=ti(e),o=[...n?[r.put(n)]:[],...t.flatMap(i=>{let a=ti(i);return a&&Ir(a).length>0?[r.putIfAbsent(a)]:[]})];Promise.all(o).catch(i=>{se.warn(`Forge removal plan not kept: ${T(i)}`)})}refuseUndo(e,t,r){P(this.deps,"forge:undo","forge:undo:error",e,new Error(t),{code:r})}async handleOpenRecord(e){let t=nt(PD,e,"forge:open-record:error",this.deps);if(!t)return;let r=(l,u)=>{P(this.deps,"forge:open-record","forge:open-record:error",e,new Error(l),{code:u})},n=this.loadHistory().find(l=>l.forgeId===t.forgeId);if(!n){r("This run is no longer in the Forge history.","NOT_FOUND");return}if(!n.targetOrgId){r("This run was recorded before Forge kept the org it wrote to.","NOT_RECORDED");return}let o=await this.withIdsOf(n);if("gone"in o){r(o.gone,xo);return}let i=t.recordId.slice(0,15),a;for(let{objectApiName:l,ids:u}of Or(o.entry)){let p=u.find(g=>g.slice(0,15)===i);if(p){a={objectApiName:l,id:p};break}}if(!a){r("This record is not one this run created.","NOT_CREATED");return}let d=this.deps.orgManager.getOrg(n.targetOrgId);if(!d){r("The org this run wrote to is no longer registered.","ORG_NOT_FOUND");return}let c=Ya(d.instanceUrl,a.objectApiName,a.id);if(!c.ok){let l=c.reason==="not-https"?`its instance URL must use HTTPS, got "${c.protocol}"`:c.reason==="invalid"?"its instance URL is not a valid URL":"the record is not one an address can be built for";r(`Cannot open the record in "${Re(d)}": ${l}.`,c.reason==="not-a-record"?"NOT_CREATED":"INVALID_INSTANCE_URL");return}try{let l=await this.externalBrowser.open(c.url),u=A(this.deps,e,"forge:open-record:response",l);this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id} status=${l.status}`)}catch(l){P(this.deps,"forge:open-record","forge:open-record:error",e,l)}}async handleVerify(e){let t=nt(CD,e,"forge:verify:error",this.deps);if(!t)return;let{forgeId:r}=t,n=(l,u)=>{P(this.deps,"forge:verify:request","forge:verify:error",e,new Error(l),{code:u})},o=this.loadHistory().find(l=>l.forgeId===r);if(!o){n("This run is no longer in the Forge history.","NOT_FOUND");return}if(o.dryRun===!0){n("A simulation wrote nothing: there is nothing of it to verify.","SIMULATION");return}let i=o.targetOrgId;if(!o.idRemapCreated||!o.idRemapTable||!i){n("This run was recorded before Forge kept what a run created: its records cannot be verified.","NOT_RECORDED");return}let a=o;if(o.remapInJournal&&zr(o).length>0){let l=await this.withIdsOf(o,!0);if("gone"in l){n(l.gone,xo);return}a=l.entry}let d=o.remapInJournal&&a===o?[]:zo(a);if(d.length===0){o.undo?n(`The records this run created were removed, on ${o.undo.removedAt}: there is nothing of it to verify.`,"ALREADY_REMOVED"):n("This run created no record to verify.","NOTHING_TO_VERIFY");return}if(!this.deps.orgManager.getOrg(i)){n("The org this run wrote to is no longer registered.","ORG_NOT_FOUND");return}if(this.verifying.has(r)){n("The records of this run are being verified already.","DUPLICATE");return}this.verifying.add(r);let c=`forge-verify-${this.deps.nextId()}`;try{let l=await B(i,this.deps.orgRegistry,this.deps.orgManager),u=new ib({target:jl(l,"forge:verify"),source:await this.verificationSource(o.sourceOrgId)}),p=o.writtenBetween??await this.datedByItsJournal({journalId:o.journalId,part:o.journalPart,scope:"part"},l),g=await u.verify({records:d,remapTable:a.idRemapTable??{},...p?{runStartedAt:new Date(p.first),runEndedAt:new Date(p.last)}:{runRecordedAt:new Date(o.timestamp)},...a.removalStamps?{removalStamps:a.removalStamps}:{},...o.config?.fieldExclusions?{fieldExclusions:o.config.fieldExclusions}:{},...o.config?.fieldMappings?{fieldMappings:o.config.fieldMappings}:{},writtenWithout:cb(o.writtenWithoutFields??[]),...o.lookupsLeftEmptyByFilter?{leftEmptyByFilter:o.lookupsLeftEmptyByFilter}:{},leftEmptyByTheRun:db(o.config?.inputMode==="org"),...a.idRemapWithTheirRecord?{withTheirRecord:a.idRemapWithTheirRecord}:{}});this.saveHistory(this.loadHistory().map(f=>f.forgeId===r?{...f,verification:g}:f)),X(this.deps,{action:"forge_verify",module:"forge",operationId:c,orgId:i,outcome:g.verdict==="verified"?"success":"partial",verdict:g.verdict,details:{forgeId:r,...ab(g)}});let h=A(this.deps,e,"forge:verify:response",{verification:g});this.deps.broker.postToWebview(h),this.deps.log(`[TX] ${h.type} id=${h.id} verdict=${g.verdict}`)}catch(l){X(this.deps,{action:"forge_verify",module:"forge",operationId:c,orgId:i,outcome:"failure",details:{forgeId:r}}),P(this.deps,"forge:verify:request","forge:verify:error",e,l,{code:"VERIFY_ERROR",retryable:!0})}finally{this.verifying.delete(r)}}async handleExportIds(e){let t=nt(DD,e,"forge:export-ids:error",this.deps);if(!t)return;let r=(c,l)=>{P(this.deps,"forge:export-ids:request","forge:export-ids:error",e,new Error(c),{code:l})},n=this.loadHistory().find(c=>c.forgeId===t.forgeId);if(!n){r("This run is no longer in the Forge history.","NOT_FOUND");return}if(!n.remapInJournal){r("This run keeps its ids in its results: save its Id map from there.","NOT_IN_JOURNAL");return}let o=await this.idMapRowsInJournal(n),i,a=()=>{};if(o)i=o.rows,a=o.close;else{let c=await this.withIdsOf(n);if("gone"in c){r(c.gone,xo);return}i=Qp(c.entry)}let d=new Date().toISOString().slice(0,10);try{let c=await this.saveDialog.saveStream(`sandforge-forge-id-map-${d}.csv`,async p=>{await p(Zp([]));let g=0,h=[];for(let f of i)h.push(f),!(h.length<xD)&&(await p(`
11
+ ${Wc(h)}`),g+=h.length,h=[]);return h.length>0&&await p(`
12
+ ${Wc(h)}`),g+h.length},["csv"]),l=c.status==="saved"?{status:"saved",path:c.path,rows:c.result}:c,u=A(this.deps,e,"forge:export-ids:response",l);this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id} status=${c.status}`)}finally{a()}}async idMapRowsInJournal(e){let t=this.runJournal;if(!(!t||!e.journalId||e.journalPart===void 0))try{return await t.idMapRowsOf(e.journalId,e.journalPart)}catch(r){se.warn(`Forge run journal could not be read: ${T(r)}`);return}}async verificationSource(e){if(!e)return{unavailable:"This run was recorded before Forge kept the org it read from."};if(!this.deps.orgManager.getOrg(e))return{unavailable:"The org this run read from is no longer registered."};try{let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return jl(t,"forge:verify source")}catch(t){return{unavailable:`The org this run read from could not be reached: ${T(t)}`}}}async removeRun(e,t,r,n,o,i){let{includeChanged:a,again:d}=n,{forgeId:c,targetOrgId:l}=t,u=pl(r),p=(I,C)=>this.refuseUndo(e,I,C),g=this.deps.infraServices?.productionGuard;if(!g){X(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:l,outcome:"stopped",code:ve.code}),p(ve.message,ve.code);return}let h=this.deps.orgManager.getOrg(l),f=Ee(h),{check:m,decision:y}=u>0?await Ke(g,{orgId:l,orgTier:f,operation:"delete",objectName:gl(r).join(", "),recordCount:u,module:"forge"}):{check:void 0,decision:"allowed"};if(m&&(y==="refused"||y==="declined")){X(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:l,outcome:"stopped",guard:y}),y==="refused"?p(`Operation blocked by Production Guard: ${m.blockedReason??m.impactSummary}`,"GUARD_BLOCKED"):P(this.deps,"forge:undo","forge:undo:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}if(i?.signal.aborted){X(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:l,outcome:"stopped",guard:y,code:gt});let I={forgeId:c,status:"cancelled",includeChanged:a,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(A(this.deps,e,"forge:undo:response",{result:I,operationId:e.id}));return}let w=e.id,v=u>0?`Removing ${u} record(s) a Forge run created`:"Sweeping what the target\u2019s automation created during a Forge run",R=new AbortController;We(this.deps,w,"forge",v);let b=this.trackRun(w,v,R);this.liveTracker?.register(w,"forge",v,u);let O,k,S,E;try{let I=await B(l,this.deps.orgRegistry,this.deps.orgManager),{inJournal:C}=t,F=t.writtenBetween??await this.datedByItsJournal({journalId:t.journalId??C?.journalId,part:t.journalPart??C?.part},I),Y={...t.removalStamps,...C?await this.runJournal?.stampsOf(C.journalId,C.part).catch(U=>(se.warn(`Forge removal stamps not read: ${T(U)}`),{})):{}};u>0&&(k=await this.otherPartsOf(c,l,I));let z=fl(t.removalSpans,k?.spans);o&&(S=await this.sweepOfRemoval({conn:I,entry:o,includeChanged:a,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,removalSpans:z,signal:R.signal,guard:g,orgTier:f,operationId:w,muted:()=>u===0?E:void 0}));let te=S;await te?.ask();let H=te?.takes??[],x=n.muteAutomation===!0&&(u>0||H.length>0)?await this.removalMute(l,gl(r),H,k?.parts.flatMap(U=>U.objects)??[],t.runUserId!==void 0&&u>0):void 0,j;E=x?.muted;let K=async()=>{let U=x?.prepared;!U||R.signal.aborted||(j=await U.acquire(w),E=j.outcome)},_=await(u===0?(async()=>(await K(),await te?.first(),await te?.afterRemoval(),Xm))():Km(Gt(I,"forge:undo"),r,{...F?{runStartedAt:new Date(F.first),runEndedAt:new Date(F.last)}:{runDurationMs:t.duration,runRecordedAt:new Date(t.timestamp)},...Object.keys(Y).length>0?{removalStamps:Y}:{},...z.length>0?{removalSpans:z}:{},...k&&k.laterParts.length>0?{laterParts:k.laterParts}:{},...te?{sweep:U=>te.first(U),afterRemoval:U=>te.afterRemoval(U),automationMade:te.automationMade}:{},...t.runUserId?{runUserId:t.runUserId}:{},...k&&k.parts.length>0?{otherParts:k.parts.map(U=>U.alongside)}:{},includeChanged:a,onUndeletable:Tr(this.deps,l,"forge:undo"),beforeFirstWrite:K,signal:R.signal,onProgress:(U,W,ae)=>{let q=Math.min(100,Math.round(U/Math.max(W,1)*100));$e(this.deps,w,q,U,W,ae),R.signal.aborted||this.deps.infraServices?.backgroundRegistry?.updateProgress(w,q),this.liveTracker?.updateProgress(w,q,U,W,ae)}})).finally(async()=>{j&&(E=await j.release())});k&&await this.keepOtherPartStamps(k.parts,_.otherPartStamps??[]);let V=await S?.settle(),ue=d?void 0:t.undo?.removedAt,me=t.unreachable,re=k?ix(_.objects,k.parts):[],ie=(k?.parts??[]).flatMap(U=>U.undo&&U.records>0?[{forgeId:U.forgeId,records:U.records}]:[]),Be={forgeId:c,status:Ym(_.objects,_.cancelled),includeChanged:a,objects:_.objects,finishedAt:new Date().toISOString(),...ue?{leftBy:ue}:{},...me>0?{mayHaveBeenWritten:me}:{},...t.notLookedFor?{notLookedFor:t.notLookedFor}:{},...E?{mutedAutomation:E}:{},...re.length>0?{heldByOtherParts:re}:{},...ie.length>0?{otherPartsLeft:ie}:{}};u>0&&X(this.deps,{action:"cleanup_delete",module:"forge",operationId:w,orgId:l,outcome:oo(Be),guard:y,objects:Yr(Be.objects),...ue?{leftBy:ue}:{},...E?{muted:ot(E)}:{}});let fe={...Be,status:no(Be.status,V),...V?{sweep:V}:{},...n.wholeOrgNotSwept?{wholeOrgNotSwept:!0}:{}};n.wholeOrgNotSwept&&se.info("Forge removal: a clone of the whole org removed without its sweep; what the target\u2019s automation created during the run stays");let ne=Qm(fe,u,t.undo,d),ce=V&&eb(V,new Date().toISOString(),o?.sweep),we=Object.keys(_.stamps).length>0,le=_.span,Se,je;if(C)(_.objects.some(W=>W.deleted+W.alreadyGone>0)||d&&ne!==void 0)&&(je=await this.runJournal?.keepLeftPages(C.journalId,C.part,_.left()).catch(W=>{se.warn(`Forge removal left not kept: ${T(W)}`)})),we&&await this.runJournal?.keepStamps(C.journalId,C.part,_.stamps).catch(W=>{se.warn(`Forge removal stamps not kept: ${T(W)}`)});else if((_.gone.length>0||d&&ne)&&!Vm(r)){let U=new Set(_.gone);Se=r.flatMap(({ids:W})=>W.filter(ae=>!U.has(ae)))}if(ne||we||le||Se||je||ce){let U=W=>({...W,...ne?{undo:ne}:{},...ce?{sweep:ce}:{},...we&&!C?{removalStamps:{...W.removalStamps,..._.stamps}}:{},...le?{removalSpans:[...W.removalSpans??[],le]}:{},...Se?{removalLeft:Se}:{}});this.saveHistory(this.loadHistory().map(W=>W.forgeId===c?{...U(W),...je?{removalLeftByObject:je}:{}}:W)),await this.removalPlans?.update(c,W=>{let ae={...U(W),...W.inJournal&&je?{inJournal:{...W.inJournal,left:je}}:{}};return Ir(ae).length>0?ae:void 0}).catch(W=>{se.warn(`Forge removal plan not updated: ${T(W)}`)})}let M=A(this.deps,e,"forge:undo:response",{result:fe,operationId:w});this.deps.broker.postToWebview(M);let N=fe.status==="failure"?"No record this run created could be removed.":u===0&&V&&V.status!=="success"?V.refusal??"The sweep left records in the org.":void 0;fe.status==="cancelled"||V?.status==="cancelled"?(pe(this.deps,w,{aborted:!0}),this.liveTracker?.cancel(w)):(pe(this.deps,w,{status:N&&u===0?"failure":fe.status}),N?(O=new Error(N),this.liveTracker?.fail(w,N)):fe.status==="partial"?this.liveTracker?.partial(w):this.liveTracker?.complete(w))}catch(I){O=I,await S?.settle().catch(F=>{se.warn(`Forge sweep not recorded: ${T(F)}`)});let C=kt(I)?I:void 0;X(this.deps,{action:"cleanup_delete",module:"forge",operationId:w,orgId:l,outcome:C?"stopped":"failure",guard:y,...C?{code:C.code}:{}}),P(this.deps,"forge:undo","forge:undo:error",e,I,{code:C?.code??"UNDO_ERROR",retryable:!0}),pe(this.deps,w,{status:"failure"}),this.liveTracker?.fail(w,T(I))}finally{k?.close(),b(O)}}async otherPartsOf(e,t,r){let n=[],o=[],i=this.loadHistory(),a=new Set(i.map(u=>u.forgeId)),d=(await this.keptRemovalPlans()).filter(u=>!a.has(u.forgeId)),c=u=>sx(u,i,d,t),l=[];for(let u of await this.runLineOf(e,i,d)){let p=i.find(f=>f.forgeId===u),g=p?void 0:d.find(f=>f.forgeId===u);(p??g)?.targetOrgId===t&&l.push((p??g)?.removalSpans??[]);let h=p?await this.otherPartFromEntry(p,t,r,c(u)):await this.otherPartFromPlan(g,t,r,c(u));h&&(h.close&&n.push(h.close),o.push(h.part))}return{parts:o,spans:fl(...l),laterParts:c(e),close:()=>n.forEach(u=>u())}}async otherPartObjectsOf(e,t){let r=this.loadHistory(),n=new Set(r.map(a=>a.forgeId)),o=(await this.keptRemovalPlans()).filter(a=>!n.has(a.forgeId)),i=new Set;for(let a of await this.runLineOf(e,r,o)){let d=r.find(u=>u.forgeId===a),c=d?void 0:o.find(u=>u.forgeId===a);if((d??c)?.targetOrgId!==t)continue;let l=d?zr(d):c?Ir(c):[];for(let{objectApiName:u}of l)i.add(u)}return[...i]}async runLineOf(e,t,r){let n=[...t.map(a=>({forgeId:a.forgeId,...a.retryOf!==void 0?{retryOf:a.retryOf}:{},...a.journalId!==void 0?{journalId:a.journalId}:{}})),...r.map(a=>({forgeId:a.forgeId,...a.retryOf!==void 0?{retryOf:a.retryOf}:{},...a.inJournal?{journalId:a.inJournal.journalId}:{}}))],o=this.runJournal,i=new Map;for(;;){let{inLine:a,journals:d}=ox(e,n,i),c=o?[...d].filter(l=>!i.has(l)):[];if(!o||c.length===0)return[...a].filter(l=>l!==e);for(let l of c)i.set(l,await o.partsOf(l).catch(u=>(se.warn(`Forge run journal parts not read: ${T(u)}`),[])))}}async keptRemovalPlans(){try{return await this.removalPlans?.list()??[]}catch(e){return se.warn(`Forge removal plans could not be read: ${T(e)}`),[]}}async otherPartFromEntry(e,t,r,n){if(e.targetOrgId!==t||!e.idRemapCreated||this.removing.has(e.forgeId)||zr(e).length===0)return;let o=e.remapInJournal&&e.journalId&&e.journalPart!==void 0?{journalId:e.journalId,part:e.journalPart}:void 0,i,a;if(o){let c=await this.journalRecordsOf(o,e.undo);if("gone"in c)return;i=c.records,a=c.close}else i=zo(e);let d=e.writtenBetween??await this.datedByItsJournal({journalId:e.journalId,part:e.journalPart},r);return{part:{forgeId:e.forgeId,...o?{inJournal:o}:{},alongside:await this.alongside(i,d,e,e.removalStamps,o,n),...e.undo?{undo:e.undo}:{},objects:zr(e).map(c=>c.objectApiName),records:zr(e).reduce((c,l)=>c+l.count,0)},...a?{close:a}:{}}}async otherPartFromPlan(e,t,r,n){if(!e||e.targetOrgId!==t||this.removing.has(e.forgeId)||Ir(e).length===0)return;let o=e.inJournal?{journalId:e.inJournal.journalId,part:e.inJournal.part}:void 0,i,a;if(o){let c=await this.journalRecordsOf(o,e.undo);if("gone"in c)return;i=c.records,a=c.close}else i=qc(e);let d=e.writtenBetween??await this.datedByItsJournal({journalId:o?.journalId,part:o?.part},r);return{part:{forgeId:e.forgeId,...o?{inJournal:o}:{},alongside:await this.alongside(i,d,e,e.removalStamps,o,n),...e.undo?{undo:e.undo}:{},objects:Ir(e).map(c=>c.objectApiName),records:Ir(e).reduce((c,l)=>c+l.count,0)},...a?{close:a}:{}}}async alongside(e,t,r,n,o,i){let a={...n,...o?await this.runJournal?.stampsOf(o.journalId,o.part).catch(()=>({})):{}};return{plan:e,span:gO(t,r),...Object.keys(a).length>0?{removalStamps:a}:{},...i.length>0?{laterParts:i}:{}}}async keepOtherPartStamps(e,t){for(let[r,n]of e.entries()){let o=t[r]??{};if(Object.keys(o).length===0)continue;if(n.inJournal){await this.runJournal?.keepStamps(n.inJournal.journalId,n.inJournal.part,o).catch(a=>{se.warn(`Forge removal stamps of another part not kept: ${T(a)}`)});continue}let i=a=>({...a,removalStamps:{...a.removalStamps,...o}});this.saveHistory(this.loadHistory().map(a=>a.forgeId===n.forgeId?i(a):a)),await this.removalPlans?.update(n.forgeId,a=>i(a)).catch(a=>{se.warn(`Forge removal plan not updated: ${T(a)}`)})}}sweepOfRemoval(e){let{conn:t,entry:r}=e,n=r.targetOrgId??"";return bo({input:async()=>{let o=await this.sweepInputOf(r,t,e.signal);return"gone"in o?{refused:o.gone}:o},org:jr(t,"forge:undo sweep",e.signal),options:{includeChanged:e.includeChanged,removalSpans:e.removalSpans,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},guard:e.guard,guardOf:{orgId:n,orgTier:e.orgTier,operation:"delete",module:"forge"},onGuardDecision:(o,i)=>{let a=e.muted();X(this.deps,{action:"cleanup_delete",module:"forge",operationId:`${e.operationId}-sweep`,orgId:n,outcome:o.status==="refused"?"stopped":o.status,...i?{guard:i}:{},...o.status==="refused"?{code:Ro(i)}:{},objects:mo(o),details:yo(o,r.forgeId),...a?{muted:ot(a)}:{}})},keepMade:async(o,i,a)=>{await this.removalPlans?.keepMade(r.forgeId,o,i,a).catch(d=>{se.warn(`Forge sweep finds not kept: ${T(d)}`)})}})}async sweepInputOf(e,t,r){let n=await this.withIdsOf(e);if("gone"in n)return n;let o=n.entry,i=Or(o),a=await this.sweepPartsBeside(e),d=new Set(Object.values(o.idRemapTable??{}).map(p=>p.slice(0,15))),c=this.targetAutomation,l=e.targetOrgId??"",u;if(!c)u={error:"Target automation reader not configured"};else try{u=await new ge(Fs).withTimeout("forge:undo-sweep automation",()=>c.read(l,i.map(p=>p.objectApiName)))}catch(p){u={error:T(p)}}return wo({writtenBetween:e.writtenBetween,created:i,remap:d,automation:Zw(u),...e.runUserId?{runUserId:e.runUserId}:{},ties:await this.tiesOf(e),...a.length>0?{otherParts:a}:{},...r?{signal:r}:{}},Gt(t,"forge:undo-sweep copies"))}async sweepPartsBeside(e){let t=this.loadHistory(),r=new Set(t.map(a=>a.forgeId)),n=(await this.keptRemovalPlans()).filter(a=>!r.has(a.forgeId)),o=[],i=0;for(let a of await this.runLineOf(e.forgeId,t,n)){i++;let d=t.find(u=>u.forgeId===a),c=d?void 0:n.find(u=>u.forgeId===a);if((d??c)?.targetOrgId!==e.targetOrgId)continue;let l;if(d){let u=await this.withIdsOf(d);"gone"in u||(l=Or(u.entry))}else if(c?.inJournal){let u=await this.planRecordsOf({...c,inJournal:c.inJournal},!0);"gone"in u||(l=u.records)}else c&&(l=c.objects);l&&o.push({part:d?.journalPart??c?.inJournal?.part??i,created:l})}return o}async tiesOf(e){let t=e.writtenBetween,r=await this.localRunsOn(e.targetOrgId,t,e.forgeId);e.targetOrgId!==void 0&&r.push(...await this.otherModuleRuns(e.targetOrgId,t).catch(()=>[]));let n=e.mutedAutomation,o=yb(e.removalSpans),i=await this.removalPlans?.madeOf(e.forgeId).catch(()=>[]),a=await this.removalPlans?.lateOf(e.forgeId).catch(()=>[]);return{otherRuns:fb(t,r),...n?.state==="muted"?{muted:{silenced:n.silenced,stillRan:n.stillRan}}:{},...o?{removalBegan:o}:{},...i&&i.length>0?{madeEarlier:i}:{},...a&&a.length>0?{lateEarlier:a}:{}}}async localRunsOn(e,t,r){let n=await this.removalPlans?.list().catch(()=>[]),o=new Set,i=[],a=async(d,c)=>{if(!hb(t,d))return{ids:[],...d};let l=await c();return l?{ids:l.flatMap(({ids:u})=>u),...d}:{ids:[],idsUntold:!0,...d}};for(let d of this.loadHistory()){if(o.add(d.forgeId),d.forgeId===r||d.targetOrgId!==e)continue;let c=oO(d);i.push(d.remapInJournal?await a(c,async()=>{let l=await this.withIdsOf(d);return"gone"in l?void 0:Or(l.entry)}):{ids:Or(d).flatMap(({ids:l})=>l),...c})}for(let d of n??[]){if(o.has(d.forgeId)||d.forgeId===r||d.targetOrgId!==e)continue;let c=oO(d),l=d.inJournal;i.push(l?await a(c,async()=>{let u=await this.planRecordsOf({...d,inJournal:l},!0);return"gone"in u?void 0:u.records}):{ids:d.objects.flatMap(({ids:u})=>u),...c})}return i}setOtherModuleRuns(e){this.otherModuleRuns=e}async handleUndoSweep(e){let t=nt(ED,e,"forge:undo-sweep:error",this.deps);if(!t)return;let r=(i,a)=>P(this.deps,"forge:undo-sweep","forge:undo-sweep:error",e,new Error(i),{code:a}),n=this.loadHistory().find(i=>i.forgeId===t.forgeId);if(!n){r(sO,"NOT_FOUND");return}let o=n.targetOrgId;if(!n.idRemapCreated||!o){r("This run was recorded before Forge kept what a run created: nothing of it can be swept.","NOT_RECORDED");return}try{let i=await new ge(QD).withTimeout("forge:undo-sweep",async()=>{let a=await B(o,this.deps.orgRegistry,this.deps.orgManager),d=await this.sweepInputOf(n,a);return"gone"in d?d:ho(jr(a,"forge:undo-sweep"),d,n.removalSpans??[])});if("gone"in i){r(i.gone,xo);return}this.deps.broker.postToWebview(A(this.deps,e,"forge:undo-sweep:response",{forgeId:t.forgeId,listing:i}))}catch(i){let a=i instanceof ir;P(this.deps,"forge:undo-sweep","forge:undo-sweep:error",e,i,{code:a?"TIMEOUT":"SWEEP_ERROR",retryable:!0})}}async handlePlanRequest(e){if(!this.planGenerator){P(this.deps,"forge:plan","forge:plan:error",e,new Error("Plan generator not configured"),{code:"NOT_INITIALIZED"});return}let t=nt(jD,e,"forge:plan:error",this.deps);if(!t)return;let{graph:r,config:n}=t,o=`forge-plan-${this.deps.nextId()}`;We(this.deps,o,"forge","Generating execution plan");try{se.info("Forge plan generation started");let i=await this.readPersonalFields(r,n),a=await new ge(nO).withTimeout("forge:plan",()=>Promise.resolve(this.planGenerator.generate(i))),d=A(this.deps,e,"forge:plan:response",i===r?{plan:a}:{plan:a,graph:i});this.deps.broker.postToWebview(d),pe(this.deps,o,{waveCount:a.waves?.length??0})}catch(i){let a=i instanceof ir;P(this.deps,"forge:plan","forge:plan:error",e,i,{code:a?"TIMEOUT":"PLAN_ERROR",retryable:a}),pe(this.deps,o,{status:"failure"})}}async readPersonalFields(e,t){let r=this.orchestrator;if(!r)return e;try{return await new ge(nO).withTimeout("forge:plan:personal-fields",n=>r.readPersonalFields(e,t,n))}catch(n){return se.warn(`Forge personal fields not read: ${T(n)}`),e}}async handleComplianceRequest(e){if(!this.complianceService){P(this.deps,"forge:compliance","forge:compliance:error",e,new Error("Compliance service not configured"),{code:"NOT_INITIALIZED"});return}let t=nt(ND,e,"forge:compliance:error",this.deps);if(!t)return;let{framework:r,graph:n,config:o,anonymizationRules:i}=t,a=`forge-compliance-${this.deps.nextId()}`;We(this.deps,a,"forge","Generating compliance report");try{se.info("Forge compliance report generation started");let d=await new ge(KD).withTimeout("forge:compliance",()=>Promise.resolve(this.complianceService.generate(r,n,o,i))),c=A(this.deps,e,"forge:compliance:response",{report:d});this.deps.broker.postToWebview(c),pe(this.deps,a,{framework:r})}catch(d){let c=d instanceof ir;P(this.deps,"forge:compliance","forge:compliance:error",e,d,{code:c?"TIMEOUT":"COMPLIANCE_ERROR",retryable:c}),pe(this.deps,a,{status:"failure"})}}async handleMetadataDiffRequest(e){if(!this.metadataDiff){P(this.deps,"forge:metadata-diff","forge:metadata-diff:error",e,new Error("Metadata diff service not configured"),{code:"NOT_INITIALIZED"});return}let t=nt($D,e,"forge:metadata-diff:error",this.deps);if(!t)return;let{sourceOrgId:r,targetOrgId:n,objectApiNames:o}=t,i=`forge-metadata-diff-${this.deps.nextId()}`;We(this.deps,i,"forge","Comparing metadata schemas");try{se.info("Forge metadata diff started");let a=await new ge(YD).withTimeout("forge:metadata-diff",()=>this.metadataDiff.compare(r,n,o)),d=A(this.deps,e,"forge:metadata-diff:response",{diffs:a});this.deps.broker.postToWebview(d),se.info("Forge metadata diff finished",{objects:o.length,differences:a.length,objectsMissing:a.filter(c=>c.issue==="object_missing").length}),pe(this.deps,i,{objectCount:o.length})}catch(a){let d=a instanceof ir;P(this.deps,"forge:metadata-diff","forge:metadata-diff:error",e,a,{code:d?"TIMEOUT":"METADATA_DIFF_ERROR",retryable:d}),pe(this.deps,i,{status:"failure"})}}async handleRehearseRequest(e){let t=this.rehearser,r=(k,S,E=!1)=>P(this.deps,"forge:rehearse","forge:rehearse:error",e,k,{code:S,retryable:E});if(!t){r(new Error("Forge rehearsal is not initialized"),"NOT_INITIALIZED");return}let n=nt(LD,e,"forge:rehearse:error",this.deps);if(!n)return;let{graph:o,config:i,anonymizationRules:a}=n;if(i.inputMode==="org"){r(new Error(wD),yD);return}let d=(k,S,E={})=>X(this.deps,{action:"forge_rehearse",module:"forge",operationId:k,orgId:i.targetOrgId,outcome:S,...E}),c=(k,S,E=!1)=>{d(e.id,"stopped",{code:S}),r(k,S,E)},l=this.deps.infraServices?.productionGuard;if(!l){c(new Error(ve.message),ve.code);return}let u=this.deps.orgManager.getOrg(i.targetOrgId),p=Ee(u),g=Re(u,i.targetOrgId);if(p==="production"){c(new Error(`${g} is a production org, or an org SandForge cannot tell is a sandbox, a scratch org or a Developer Edition org: a rehearsal creates records in those only. Nothing was read or sent.`),"PRODUCTION_TARGET");return}if(this.rehearseOperationId!==null){c(new Error("A rehearsal is already under way in this window: rehearse once it has ended."),"REHEARSAL_RUNNING",!0);return}if(this.executeOperationId!==null){c(new Error("A Forge run is under way in this window: rehearse once it has ended."),rp,!0);return}let h=`forge-rehearse-${this.deps.nextId()}`,f="Rehearsing a forge run";this.rehearseOperationId=h,We(this.deps,h,"forge",f);let m=new AbortController,y=this.trackRun(h,f,m);this.liveTracker?.register(h,"forge",f);let w,v=!1,R=k=>this.deps.broker.postToWebview(A(this.deps,e,"forge:rehearse:progress",{...k})),b=k=>{if(k.phase!=="rehearsing"||!k.call||!k.calls)return;let S=Math.min(100,Math.round((k.call-1)/k.calls*100));m.signal.aborted||this.deps.infraServices?.backgroundRegistry?.updateProgress(h,S),this.liveTracker?.updateProgress(h,S,k.call-1,k.calls,`call ${k.call} of ${k.calls}`)},O=_d(R,100);try{let k=await this.automationBeforeTheRun(i.targetOrgId,o),S="automation"in k?k.automation:void 0,E=await this.loadRecordTypeMappings(i,new AbortController().signal,{requests:0}),I=await t.rehearse(o,i,{recordTypeMappings:E,anonymizationRules:a,signal:m.signal,onProgress:C=>{if(C.phase==="reading"){O(C);return}O.flush(),R(C),b(C)},confirm:async C=>{let F=await l.confirmRun({stage:"rehearsal",org:g,orgTier:p,rows:C.rows,sampled:C.sampled,updates:C.updates.reduce((Y,z)=>Y+z.updates,0),calls:C.calls,maxCalls:C.maxCalls,fired:S?Sl(S):[],firedOnUpdate:S?kl(S,C.updates.map(Y=>Y.objectApiName)):[],unread:S?Il(S):[{part:"automation",reason:"unread"in k?k.unread:""}]});if(F==="confirmed"){v=!0;return}throw new Ud(F==="declined"?"REHEARSAL_DECLINED":"CONFIRMATION_UNAVAILABLE",F==="declined"?"The rehearsal was cancelled at its confirmation. Nothing was sent to the target.":"The rehearsal needed a confirmation, and there was no one to ask. Nothing was sent to the target.")}});this.deps.broker.postToWebview(A(this.deps,e,"forge:rehearse:response",{rehearsal:I})),this.trials.note("rehearsal",Ml(o,i)),se.info("Forge rehearsal",{rows:I.rows,sampled:I.sampled,judged:I.judged,passed:I.passed,notJudged:I.notJudged,calls:I.calls,plannedCalls:I.plannedCalls,codes:[...new Set(I.gaps.flatMap(C=>typeof C.detail?.statusCode=="string"?[C.detail.statusCode]:[]))]}),d(h,"success",{guard:v?"confirmed":"allowed",details:bx(I)}),pe(this.deps,h,{status:"success"}),this.liveTracker?.complete(h)}catch(k){let S=k instanceof Ud?k:void 0,E=k instanceof sb?k:void 0,I=k instanceof ob?k:void 0,C=T(k);if(r(k instanceof Error?k:new Error(C),S?.code??(E?"REHEARSAL_CANCELLED":"REHEARSAL_ERROR"),!0),S||E){let F=S?.code==="REHEARSAL_DECLINED"?"declined":v?"confirmed":void 0;d(h,"stopped",{code:S?.code??"REHEARSAL_CANCELLED",...F?{guard:F}:{},...E?{details:{calls:E.calls}}:{}}),pe(this.deps,h,{aborted:!0}),this.liveTracker?.cancel(h)}else w=k,d(h,"failure",{...v?{guard:"confirmed"}:{},...I?{code:"REHEARSAL_NOT_ROLLED_BACK",details:{recordsLeft:I.ids.length},objects:I.objects.map(({objectApiName:F,created:Y})=>({objectApiName:F,created:Y,updated:0,deleted:0,failed:0}))}:{}}),Le(this.deps,h,C,!0),this.liveTracker?.fail(h,C)}finally{O.flush(),y(w),this.rehearseOperationId===h&&(this.rehearseOperationId=null)}}async handleAutomationRequest(e){if(!this.targetAutomation){P(this.deps,"forge:automation","forge:automation:error",e,new Error("Target automation reader not configured"),{code:"NOT_INITIALIZED"});return}let t=nt(FD,e,"forge:automation:error",this.deps);if(!t)return;let{targetOrgId:r,graph:n}=t,o=`forge-automation-${this.deps.nextId()}`;We(this.deps,o,"forge","Reading the target org's automation");try{let i=new ge(Fs).withTimeout("forge:automation",()=>this.targetAutomation.readForGraph(r,n));this.keepAutomationRead(r,n,i);let a=await this.withDeliverability(r,n,await i);this.deps.broker.postToWebview(A(this.deps,e,"forge:automation:response",{automation:a})),se.info("Forge target automation read",{objects:a.objectsRead.length,objectsWithAutomation:a.objects.length,flows:a.objects.reduce((d,c)=>d+c.flows.length,0),triggers:a.objects.reduce((d,c)=>d+c.triggers.length,0),conditionsNotRead:a.conditionsNotRead,unread:a.unread.map(d=>d.part),requests:a.requests}),pe(this.deps,o,{objectCount:a.objectsRead.length})}catch(i){let a=i instanceof ir;P(this.deps,"forge:automation","forge:automation:error",e,i,{code:a?"TIMEOUT":"AUTOMATION_ERROR",retryable:a}),pe(this.deps,o,{status:"failure"})}}async readDeliverability(e,t){let r=()=>{},n=new Promise((o,i)=>{r=()=>i(new Error(fn)),t?.addEventListener("abort",r,{once:!0})});try{return await Promise.race([new ge(Iy).withTimeout("forge:deliverability",async()=>jt(await B(e,this.deps.orgRegistry,this.deps.orgManager))),n])}finally{t?.removeEventListener("abort",r)}}async withDeliverability(e,t,r){let n=this.deps.orgManager.getOrg(e),o=Ol(t,{leftOut:new Set(t.nodes.filter(ri).map(d=>d.objectApiName))}),i=new Set(o.map(d=>d.objectApiName)),{ofRun:a}=await Vt({read:r,writes:(d,c)=>c==="insert"||c==="update"&&i.has(d),readDeliverability:()=>Ee(n)==="production"?Promise.resolve(Mt):this.readDeliverability(e),accepted:!1,target:Re(n,e),run:"clone"});return a.read?{...r,deliverability:a.read.reading,requests:r.requests+a.read.requests}:r}async handleUndoAutomation(e){let t=nt(TD,e,"forge:undo-automation:error",this.deps);if(!t)return;let r=(d,c)=>P(this.deps,"forge:undo-automation","forge:undo-automation:error",e,d,{code:c}),n=this.targetAutomation;if(!n){r(new Error("Target automation reader not configured"),"NOT_INITIALIZED");return}let o=this.loadHistory().find(d=>d.forgeId===t.forgeId);if(!o?.targetOrgId){r(new Error("This run is no longer in the Forge history."),"NOT_FOUND");return}let i=(t.again===!0?Yp(o):zr(o)).map(d=>d.objectApiName),a=o.targetOrgId;try{let d=await this.otherPartObjectsOf(t.forgeId,a),c=[...new Set([...Kr(i,d,{userKept:o.runUserId!==void 0}),...t.sweptObjects??[]])],l=await new ge(Fs).withTimeout("forge:undo-automation",()=>n.read(a,c));this.deps.broker.postToWebview(A(this.deps,e,"forge:undo-automation:response",{forgeId:t.forgeId,automation:l,drafted:zt(i)}))}catch(d){let c=d instanceof ir;P(this.deps,"forge:undo-automation","forge:undo-automation:error",e,d,{code:c?"TIMEOUT":"AUTOMATION_ERROR",retryable:c})}}async handleGapsRequest(e){if(!this.targetGaps){P(this.deps,"forge:gaps","forge:gaps:error",e,new Error("Target gap reader not configured"),{code:"NOT_INITIALIZED"});return}let t=nt(_D,e,"forge:gaps:error",this.deps);if(!t)return;let{graph:r,config:n}=t,o=this.targetGaps,i=`forge-gaps-${this.deps.nextId()}`;We(this.deps,i,"forge","Reading what the target org holds against the rows");try{let a=await new ge(ZD).withTimeout("forge:gaps",()=>o.read(n.sourceOrgId,n.targetOrgId,r,n));this.deps.broker.postToWebview(A(this.deps,e,"forge:gaps:response",{gaps:a})),se.info("Forge target gaps read",{gaps:a.gaps.length,blocking:a.gaps.filter(d=>d.severity==="blocking").length,kinds:[...new Set(a.gaps.map(d=>d.kind))],unread:a.unread.map(d=>d.part),requests:a.requests}),pe(this.deps,i,{objectCount:r.nodes.length})}catch(a){let d=a instanceof ir;P(this.deps,"forge:gaps","forge:gaps:error",e,a,{code:d?"TIMEOUT":"GAPS_ERROR",retryable:d}),pe(this.deps,i,{status:"failure"})}}async handleUsersRequest(e){let t=nt(UD,e,"forge:users:error",this.deps);if(t)try{let r=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),n=await r.query(Vk);De(r.limitInfo,"forge:users query");let{users:o,truncated:i}=Xk(n.records,n.done===!1);this.deps.broker.postToWebview(A(this.deps,e,"forge:users:response",{orgId:t.orgId,users:o,truncated:i}))}catch(r){P(this.deps,"forge:users","forge:users:error",e,r,{code:"USERS_ERROR"})}}async handleTargetRecordsRequest(e){let t=nt(HD,e,"forge:target-records:error",this.deps);if(t)try{let r=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await new ge(Mo).withTimeout("forge:target-records",()=>r.request(`/services/data/v${r.version}/limits/recordCount`)),o=yw(n);if(!o)throw new Error("The target org answered its record counts in no form known.");let i=[...new Set(t.objectApiNames)].map(a=>({objectApiName:a,records:o.get(a)??0})).filter(({records:a})=>a>0).sort((a,d)=>d.records-a.records||a.objectApiName.localeCompare(d.objectApiName));this.deps.broker.postToWebview(A(this.deps,e,"forge:target-records:response",{targetOrgId:t.targetOrgId,objects:i}))}catch(r){P(this.deps,"forge:target-records","forge:target-records:error",e,r,{code:"TARGET_RECORDS_ERROR"})}}async handleSampleBudgetRequest(e){let t=nt(BD,e,"forge:sample-budget:error",this.deps);if(!t)return;let{graph:r,config:n}=t;try{let[o,i]=await Promise.all([this.readTargetDataStorage(n.targetOrgId),this.readSourceApiBudget(n,{requests:0})]),a=Qw({graph:r,options:n.sample,...n.excludedObjects?{excludedObjects:n.excludedObjects}:{},storage:o,source:i,maxRecordsPerObject:this.maxRecordsPerObject()});this.deps.broker.postToWebview(A(this.deps,e,"forge:sample-budget:response",{targetOrgId:n.targetOrgId,budget:a}))}catch(o){P(this.deps,"forge:sample-budget","forge:sample-budget:error",e,o,{code:"SAMPLE_BUDGET_ERROR"})}}};import{randomUUID as Rx}from"node:crypto";import*as mO from"node:os";import*as wr from"node:path";var fO=50*1024*1024,vx=new Set(["migration:pick-file","migration:import-sfdmu","migration:save-sync-config"]),Sx="Saved from the SandForge Migration page",kx=new Set([".json"]);function Ox(s,e,t){if(typeof s!="string"||s.trim().length===0)throw new Error("Invalid import path: path is empty.");if(!wr.isAbsolute(s))throw new Error(`Invalid import path: "${s}" is not absolute. Pick a file inside the workspace or your home directory.`);let r=wr.resolve(s),n=wr.extname(r).toLowerCase();if(!e.has(n))throw new Error(`Invalid import path: "${n||"(none)"}" is not a supported extension (expected ${[...e].join(", ")}).`);if(!t.some(i=>{let a=wr.resolve(i);if(process.platform==="win32"){let d=r.toLowerCase(),c=a.toLowerCase();return d===c||d.startsWith(c+wr.sep)}return r===a||r.startsWith(a+wr.sep)}))throw new Error("Invalid import path: the file must be inside an open workspace folder or your home directory.");return r}async function hO(s,e){let t=await s.statSize(e);if(t>fO){let r=(t/1048576).toFixed(1),n=fO/(1024*1024);throw new Error(`Import file is too large: ${r} MB exceeds the ${n} MB limit. Split the file into smaller chunks and retry.`)}}var Bd=class{constructor(e){this.deps=e}deps;fileReader;setFileReader(e){this.fileReader=e}async handle(e){if(!vx.has(e.type))return!1;switch(e.type){case"migration:pick-file":return await this.handlePickFile(e),!0;case"migration:import-sfdmu":return await this.handleImportSfdmu(e),!0;case"migration:save-sync-config":return this.handleSaveSyncConfig(e),!0;default:return!1}}handleSaveSyncConfig(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Gh,e,"migration:error",this.deps);if(!t)return;let r=n=>{this.deps.broker.postToWebview(A(this.deps,e,"migration:save-sync-config:response",n))};try{let n=t.name.trim();if(n===""){r({success:!1,code:"NAME_REQUIRED"});return}let o=new Pt(this.deps.configStore);if(gg(o.list(),n)){r({success:!1,code:"DUPLICATE_NAME"});return}let a=(Array.isArray(t.config.objects)?t.config.objects:[]).map(u=>typeof u=="object"&&u!==null?u.objectApiName:void 0).filter(u=>typeof u=="string").filter(u=>mi(u));if(a.length>0){r({success:!1,code:"SYNC_CANNOT_COPY",objects:a});return}let d=new Date().toISOString(),c=gf.safeParse({...t.config,id:Rx(),name:n,description:Sx,createdAt:d,updatedAt:d});if(!c.success){let[u]=c.error.issues;r({success:!1,code:"INVALID_CONFIG",reason:u?`${u.path.join(".")}: ${u.message}`:c.error.message});return}let l=c.data;o.save(l),this.deps.log(`[TX] migration:save-sync-config:response saved ${l.id}`),r({success:!0,id:l.id,name:l.name})}catch(n){P(this.deps,"migration:save-sync-config","migration:error",e,n)}}getAllowedBaseDirs(){return[...this.deps.services?.getWorkspaceFolders?.()??[],mO.homedir()]}async handlePickFile(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.fileReader;if(!t?.pickExportFile)throw new Error("Migration services not available.");let r=await t.pickExportFile();this.deps.broker.postToWebview(A(this.deps,e,"migration:pick-file:response",r===void 0?{}:{filePath:r}))}catch(t){P(this.deps,"migration:pick-file","migration:error",e,t)}}async handleImportSfdmu(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(zh,e,"migration:error",this.deps);if(!t)return;let{filePath:r}=t;try{let n=this.fileReader;if(!n)throw new Error("Migration services not available.");let o=Ox(r,kx,this.getAllowedBaseDirs());await hO(n,o);let{SfdmuImporter:i,SfdmuRefusal:a}=await import("./chunk-YAZO75G2.mjs"),d=new i({readFile:async c=>(c!==o&&await hO(n,c),n.readFile(c))});try{let{config:c,notes:l}=await d.import(o),u=A(this.deps,e,"migration:import-sfdmu:response",{success:!0,config:c,notes:l});this.deps.broker.postToWebview(u)}catch(c){if(!(c instanceof a))throw c;this.deps.log(`[ERR] migration:import-sfdmu: ${c.message}`),this.deps.broker.postToWebview(A(this.deps,e,"migration:import-sfdmu:response",{success:!1,error:c.message,code:c.code,objects:[...c.objects]}))}}catch(n){this.deps.log(`[ERR] migration:import-sfdmu: ${T(n)}`);let o=A(this.deps,e,"migration:import-sfdmu:response",{success:!1,error:T(n)});this.deps.broker.postToWebview(o)}}};import*as No from"node:fs/promises";var RO="settings",yO=G({version:L(),exportedAt:L(),exportedBy:L().optional(),categories:ke(Xe(["syncMappings","forgePlans","pipelines","anonymizationTemplates",RO])),data:Xs(L(),Vn())});function wO(s){return s!==RO}var op={syncMappings:"sync:config:",forgePlans:"forge:templates",pipelines:"pipeline:saved:",anonymizationTemplates:"anonymization:"},bO={syncMappings:"syncConfigs",forgePlans:"forge",pipelines:"pipelines",anonymizationTemplates:"anonymizationTemplates"},_s="forge:templates";function Ix(s){return typeof s.name=="string"&&s.name.length>0?s.name:s.id}var qd=class{constructor(e,t){this.configStore=e;this.workspace=t}configStore;workspace;async exportProfile(e,t){try{let r={},n=0;for(let i of e){if(i==="forgePlans"){let l=await this.heldTemplates();r[i]=l.length>0?{[_s]:l}:{},n+=l.length;continue}let a=op[i],d=this.configStore.getKeysByPrefix(a),c={};for(let l of d){let u=this.configStore.get(l);u!==void 0&&(c[l]=u,n++)}r[i]=c}let o={version:"1.0.0",exportedAt:new Date().toISOString(),exportedBy:t,categories:e,data:r};return{success:!0,json:JSON.stringify(o,null,2),categoriesExported:e.length,entriesExported:n}}catch(r){return{success:!1,categoriesExported:0,entriesExported:0,error:r instanceof Error?r.message:String(r)}}}async importProfile(e,t=!0){let r=[];try{let n=JSON.parse(e),o=yO.safeParse(n);if(!o.success)return{success:!1,categoriesImported:0,entriesImported:0,warnings:[],error:`Invalid profile format: ${o.error.issues.map(c=>c.message).join(", ")}`};let i=o.data,a=i.categories.filter(wO),d=0;for(let c of a){let l=i.data[c];if(!l||typeof l!="object"){r.push(`Category "${c}" has no data, skipped.`);continue}if(c==="forgePlans"){d+=await this.importTemplates(l,t,r);continue}let u=op[c];for(let[p,g]of Object.entries(l)){if(!p.startsWith(u)){r.push(`Key "${p}" does not match expected prefix "${u}" for category "${c}", skipped.`);continue}if(!t&&this.configStore.has(p)){r.push(`Key "${p}" already exists, skipped.`);continue}if(this.configStore.set(p,g,bO[c]),d++,c==="pipelines"){let h=YS(this.configStore,p.slice(u.length));h.length>0&&r.push(`Pipeline "${p}" was written over: confirm its Rewind ${h.length===1?"step":"steps"} again.`)}}}return{success:!0,categoriesImported:a.length,entriesImported:d,warnings:r}}catch(n){return{success:!1,categoriesImported:0,entriesImported:0,warnings:r,error:n instanceof Error?n.message:String(n)}}}validateProfile(e){try{let t=JSON.parse(e),r=yO.safeParse(t);return r.success?{valid:!0,categories:r.data.categories.filter(wO)}:{valid:!1,error:r.error.issues.map(n=>n.message).join(", ")}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async listCategories(){let e=[];for(let[t,r]of Object.entries(op)){let n=t==="forgePlans"?(await this.heldTemplates()).length:this.configStore.getKeysByPrefix(r).length;e.push({category:t,entryCount:n})}return e}async heldTemplates(){if(!this.workspace){let r=this.configStore.get(_s);return Array.isArray(r)?r.filter(_r):[]}let e=await this.workspace.readTemplates(),t=Fd(this.configStore,this.workspace.folder);return t?Ls(e,t.templates,new Set(t.replacing)):[...e]}async importTemplates(e,t,r){let n=await this.heldTemplates(),o=new Set(n.map(c=>c.id)),i=new Set,a=[],d=[];for(let[c,l]of Object.entries(e)){if(c!==_s){r.push(`Key "${c}" does not match expected prefix "${_s}" for category "forgePlans", skipped.`);continue}if(!Array.isArray(l)){r.push(`Key "${c}" holds no list of templates, skipped.`);continue}for(let u of l){if(!_r(u)){r.push(`An entry of "${c}" has no id, skipped.`);continue}if(!i.has(u.id)){if(i.add(u.id),o.has(u.id)){if(!t){r.push(`Forge template "${Ix(u)}" already exists, skipped.`);continue}d.push(u.id)}a.push(u)}}}return this.workspace?zk(this.configStore,this.workspace.folder,a,d):a.length>0&&this.configStore.set(_s,Ls(n,a,new Set(d)),bO.forgePlans),a.length}};import*as sp from"node:path";var Wd=class{deps;filePath;constructor(e){this.deps=e,this.filePath=sp.join(e.workspacePath,".sandforge","forge-templates.json")}async list(){let e;try{e=JSON.parse(await this.deps.readFile(this.filePath))}catch{return[]}return Array.isArray(e)?e.filter(_r):[]}async save(e){let t=await this.list(),r=t.findIndex(n=>n.id===e.id);r>=0?t[r]=e:t.push(e),await this.write(t)}get workspacePath(){return this.deps.workspacePath}async merge(e,t=new Set){let r=await this.list(),n=Ls(r,e.filter(_r),t);return JSON.stringify(n)===JSON.stringify(r)?r:(await this.write(n),n)}async delete(e){let r=(await this.list()).filter(n=>n.id!==e);await this.write(r)}async write(e){let t=sp.join(this.deps.workspacePath,".sandforge");await this.deps.mkdir(t).catch(()=>{}),await this.deps.writeFile(this.filePath,JSON.stringify(e,null,2))}};var Ax=new Set(["config:export","config:import","config:categories","config:validate"]);function Tx(s){let e=s.services?.getWorkspaceFolders?.()[0];if(!e)return;let t=new Wd({workspacePath:e,readFile:r=>No.readFile(r,"utf-8"),writeFile:(r,n)=>No.writeFile(r,n,"utf-8"),mkdir:r=>No.mkdir(r,{recursive:!0}).then(()=>{})});return{folder:e,readTemplates:()=>t.list()}}var zd=class{constructor(e){this.deps=e;this.profileManager=new qd(e.configStore,Tx(e))}deps;profileManager;async handle(e){if(!Ax.has(e.type))return!1;switch(e.type){case"config:export":return await this.handleExport(e),!0;case"config:import":return await this.handleImport(e),!0;case"config:categories":return await this.handleCategories(e),!0;case"config:validate":return this.handleValidate(e),!0;default:return!1}}async handleExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Zh,e,"config:error",this.deps);if(!t)return;let r=t;try{let n=await this.profileManager.exportProfile(r.categories),o=A(this.deps,e,"config:export:response",{success:n.success,json:n.json,categoriesExported:n.categoriesExported,entriesExported:n.entriesExported,error:n.error});this.deps.broker.postToWebview(o),this.deps.log(`[TX] config:export:response (${n.entriesExported} entries)`)}catch(n){P(this.deps,"config:export","config:error",e,n)}}async handleImport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(em,e,"config:error",this.deps);if(!t)return;let r=t;try{let n=await this.profileManager.importProfile(r.json,r.overwrite),o=A(this.deps,e,"config:import:response",{success:n.success,categoriesImported:n.categoriesImported,entriesImported:n.entriesImported,warnings:n.warnings,error:n.error});this.deps.broker.postToWebview(o),this.deps.log(`[TX] config:import:response (${n.entriesImported} entries)`)}catch(n){P(this.deps,"config:import","config:error",e,n)}}async handleCategories(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=await this.profileManager.listCategories(),r=A(this.deps,e,"config:categories:response",{categories:t});this.deps.broker.postToWebview(r),this.deps.log("[TX] config:categories:response")}catch(t){P(this.deps,"config:categories","config:error",e,t)}}handleValidate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(tm,e,"config:error",this.deps);if(!t)return;let r=t;try{let n=this.profileManager.validateProfile(r.json),o=A(this.deps,e,"config:validate:response",{valid:n.valid,categories:n.categories,error:n.error});this.deps.broker.postToWebview(o),this.deps.log("[TX] config:validate:response")}catch(n){P(this.deps,"config:validate","config:error",e,n)}}};var Ex=G({metric:L(),operator:Xe(["gt","gte","lt","lte","eq","neq"]),threshold:Me(),warningThreshold:Me().optional()}),Px=G({id:L(),name:L(),description:L(),category:Xe(["security","performance","compliance","custom"]),condition:Ex,remediation:L(),enabled:ze()}),Us=G({id:L(),name:L(),description:L(),rules:ke(Px),createdAt:L(),updatedAt:L()});function vO(s,e,t){switch(e){case"gt":return s>t;case"gte":return s>=t;case"lt":return s<t;case"lte":return s<=t;case"eq":return s===t;case"neq":return s!==t}}var Gd=class s{evaluateRule(e,t){let{metric:r,operator:n,threshold:o,warningThreshold:i}=e.condition;if(!Object.prototype.hasOwnProperty.call(t,r))return{ruleId:e.id,ruleName:e.name,category:e.category,status:"unknown",actualValue:null,threshold:o,message:`${e.name}: not measured \u2014 SandForge reads no ${r} value for this org`,remediation:""};let a=t[r],d="pass";vO(a,n,o)?d="fail":i!==void 0&&vO(a,n,i)&&(d="warning");let c=d==="pass"?`${e.name}: compliant (${a})`:`${e.name}: ${d} \u2014 actual ${a} ${n} ${d==="fail"?o:i??o}`;return{ruleId:e.id,ruleName:e.name,category:e.category,status:d,actualValue:a,threshold:o,message:c,remediation:d==="pass"?"":e.remediation}}evaluatePolicy(e,t){let n=e.rules.filter(a=>a.enabled).map(a=>this.evaluateRule(a,t)),o=s.computeComplianceScore(n),i=n.filter(a=>(a.status==="fail"||a.status==="warning")&&a.remediation).map(a=>a.remediation);return{policyId:e.id,policyName:e.name,evaluatedAt:new Date().toISOString(),complianceScore:o,ruleResults:n,remediations:i}}static computeComplianceScore(e){let t=e.filter(o=>o.status!=="unknown");if(t.length===0)return null;let r={pass:100,warning:50,fail:0},n=t.reduce((o,i)=>o+r[i.status],0);return Math.round(n/t.length)}};var Jd="governance:policy:",Cx="governance",Hs=class{constructor(e){this.configStore=e}configStore;getAll(){let e=this.configStore.getKeysByPrefix(Jd),t=[];for(let r of e){let n=this.configStore.get(r);if(n){let o=Us.safeParse(n);o.success&&t.push(o.data)}}return t}getById(e){let t=this.configStore.get(`${Jd}${e}`);if(!t)return;let r=Us.safeParse(t);return r.success?r.data:void 0}save(e){this.configStore.set(`${Jd}${e.id}`,e,Cx)}delete(e){return this.configStore.delete(`${Jd}${e}`)}static getDefaultTemplates(){let e=new Date().toISOString();return[{id:"template-security",name:"Security Policy",description:"Default security governance rules",rules:[{id:"sec-mfa",name:"MFA Enabled",description:"Multi-factor authentication should be enabled for all users",category:"security",condition:{metric:"mfaEnabledPercent",operator:"lt",threshold:100,warningThreshold:90},remediation:"Enable MFA for all user profiles in Setup > Identity Verification",enabled:!0},{id:"sec-password",name:"Password Policy Strength",description:"Password policy should enforce minimum complexity",category:"security",condition:{metric:"passwordPolicyScore",operator:"lt",threshold:60,warningThreshold:80},remediation:"Strengthen password policy in Setup > Password Policies",enabled:!0}],createdAt:e,updatedAt:e},{id:"template-performance",name:"Performance Policy",description:"Default performance governance rules",rules:[{id:"perf-api",name:"API Usage Limit",description:"API usage should stay below critical thresholds",category:"performance",condition:{metric:"apiUsagePercent",operator:"gt",threshold:90,warningThreshold:75},remediation:"Optimize API-heavy integrations or request a limit increase",enabled:!0},{id:"perf-storage",name:"Storage Usage",description:"Data storage should not exceed safe limits",category:"performance",condition:{metric:"storageUsagePercent",operator:"gt",threshold:90,warningThreshold:75},remediation:"Archive old records or increase storage allocation",enabled:!0}],createdAt:e,updatedAt:e},{id:"template-compliance",name:"Compliance Policy",description:"Default compliance governance rules",rules:[{id:"comp-coverage",name:"Code Coverage",description:"Apex code coverage must meet minimum threshold",category:"compliance",condition:{metric:"codeCoveragePercent",operator:"lt",threshold:75,warningThreshold:85},remediation:"Write additional unit tests to increase code coverage",enabled:!0}],createdAt:e,updatedAt:e}]}};var Dx={apiUsagePercent:"DailyApiRequests",storageUsagePercent:"DataStorageMB"},xx=new Set(["governance:policies:list","governance:policy:save","governance:policy:delete","governance:evaluate","governance:templates"]),Vd=class{constructor(e,t){this.deps=e;this.store=new Hs(e.configStore),this.engine=new Gd,this.alertEngine=t}deps;store;engine;alertEngine;async handle(e){if(!xx.has(e.type))return!1;switch(e.type){case"governance:policies:list":return this.handlePoliciesList(e),!0;case"governance:policy:save":return this.handlePolicySave(e),!0;case"governance:policy:delete":return this.handlePolicyDelete(e),!0;case"governance:evaluate":return await this.handleEvaluate(e),!0;case"governance:templates":return this.handleTemplates(e),!0;default:return!1}}handlePoliciesList(e){try{let r=this.store.getAll().map(o=>({id:o.id,name:o.name,description:o.description,ruleCount:o.rules.length,createdAt:o.createdAt,updatedAt:o.updatedAt})),n=A(this.deps,e,"governance:policies:result",{policies:r});this.deps.broker.postToWebview(n),this.deps.log("[TX] governance:policies:result")}catch(t){P(this.deps,"governance:policies:list","governance:error",e,t)}}handlePolicySave(e){let t=D(Xh,e,"governance:error",this.deps);if(t)try{let r=Us.safeParse(t.policy);if(!r.success){P(this.deps,"governance:policy:save","governance:error",e,new Error(`Validation failed: ${r.error.message}`),{code:"VALIDATION_ERROR"});return}this.store.save(r.data);let n=A(this.deps,e,"governance:policy:save:response",{success:!0});this.deps.broker.postToWebview(n),this.deps.log("[TX] governance:policy:save:response")}catch(r){P(this.deps,"governance:policy:save","governance:error",e,r)}}handlePolicyDelete(e){let t=D(Vh,e,"governance:error",this.deps);if(t)try{let r=this.store.delete(t.policyId),n=A(this.deps,e,"governance:policy:delete:response",{success:r});this.deps.broker.postToWebview(n),this.deps.log("[TX] governance:policy:delete:response")}catch(r){P(this.deps,"governance:policy:delete","governance:error",e,r)}}async handleEvaluate(e){let t=D(Kh,e,"governance:error",this.deps);if(!t)return;let r=t;try{let n=this.store.getById(r.policyId);if(!n){P(this.deps,"governance:evaluate","governance:error",e,new Error(`Policy not found: ${r.policyId}`),{code:"NOT_FOUND"});return}let i=await(await B(r.orgId,this.deps.orgRegistry,this.deps.orgManager)).request(`/services/data/${Kn}/limits`),a={};for(let[l,{Max:u,Remaining:p}]of Object.entries(i))a[l]=u>0?Math.round((u-p)/u*100):0;for(let[l,u]of Object.entries(Dx))u in a&&(a[l]=a[u]);let d=this.engine.evaluatePolicy(n,a);if(this.alertEngine)for(let l of d.ruleResults)l.status==="fail"&&l.actualValue!==null&&this.alertEngine.evaluate(`governance:${l.ruleId}`,l.actualValue,r.orgId);let c=A(this.deps,e,"governance:evaluate:response",{success:!0,result:d});this.deps.broker.postToWebview(c),this.deps.log("[TX] governance:evaluate:response")}catch(n){P(this.deps,"governance:evaluate","governance:error",e,n)}}handleTemplates(e){try{let t=Hs.getDefaultTemplates(),r=A(this.deps,e,"governance:templates:response",{templates:t});this.deps.broker.postToWebview(r),this.deps.log("[TX] governance:templates:response")}catch(t){P(this.deps,"governance:templates","governance:error",e,t)}}};var Xd=class s{static COMMON_OBJECTS=[{apiName:"Account",label:"Account"},{apiName:"Contact",label:"Contact"},{apiName:"Opportunity",label:"Opportunity"},{apiName:"Case",label:"Case"},{apiName:"Lead",label:"Lead"}];suggest(e,t){let r=new Set(e),n=new Set(t);return s.COMMON_OBJECTS.map(o=>({objectApiName:o.apiName,label:o.label,isAvailable:r.has(o.apiName),isAlreadySelected:n.has(o.apiName)}))}};var Mx=new Set(["OpportunityId","CaseId","ContractId","OrderId"]),Kd=class{detect(e,t,r,n){let o=new Set(r),i=new Set(n),a=[];for(let d of t)if(d.type==="reference"&&d.referenceTo.length!==0)for(let c of d.referenceTo){if(c===e||o.has(c)||!i.has(c)||Fg(c))continue;let l=this.inferRelationshipType(d.name);a.push({childObject:e,parentObject:c,lookupField:d.name,relationshipType:l,suggestedInsertOrder:0})}return a}inferRelationshipType(e){return Mx.has(e)?"masterDetail":"lookup"}};var Yd=class{estimate(e,t=new Set,r=200){let n=r>0?r:200,o=e.map(c=>({objectApiName:c.objectApiName,recordCount:c.count,estimatedApiCalls:c.count>0?Math.ceil(c.count/n):0,isParentDependency:t.has(c.objectApiName)})),i=o.reduce((c,l)=>c+l.recordCount,0),a=o.reduce((c,l)=>c+l.estimatedApiCalls,0),d=a*2;return{objects:o,totalRecords:i,totalApiCalls:a,estimatedDurationSec:d}}};var Qd=class{minConfidence;constructor(e=.4){this.minConfidence=e}suggest(e,t){let r=[],n=new Set,o=[...e];for(let i of o){let a;for(let d of t){if(n.has(d.apiName))continue;let c=this.computeScore(i,d);c.confidence>(a?.confidence??0)&&(a=c)}a&&a.confidence>=this.minConfidence&&(r.push(a),n.add(a.targetField))}return r.sort((i,a)=>a.confidence-i.confidence)}toMappings(e){return e.map(t=>({sourceField:t.sourceField,targetField:t.targetField,type:t.type}))}computeScore(e,t){if(e.apiName===t.apiName)return{sourceField:e.apiName,targetField:t.apiName,type:this.inferType(e,t),confidence:1,reason:"exact_name"};let r=this.normalize(e.apiName),n=this.normalize(t.apiName);if(r===n&&r.length>0)return{sourceField:e.apiName,targetField:t.apiName,type:this.inferType(e,t),confidence:.9,reason:"normalized_name"};let o=this.stringSimilarity(e.label.toLowerCase(),t.label.toLowerCase());if(o>=.8&&this.isTypeCompatible(e.type,t.type))return{sourceField:e.apiName,targetField:t.apiName,type:this.inferType(e,t),confidence:Math.min(.85,o),reason:"label_match"};let i=this.stringSimilarity(r,n),a=this.isTypeCompatible(e.type,t.type);return i>=.6&&a?{sourceField:e.apiName,targetField:t.apiName,type:this.inferType(e,t),confidence:i*.7,reason:"partial_match"}:{sourceField:e.apiName,targetField:t.apiName,type:"direct",confidence:0,reason:"no_match"}}normalize(e){return e.replace(/__c$/i,"").replace(/__r$/i,"").replace(/_/g,"").toLowerCase()}stringSimilarity(e,t){if(e===t)return 1;if(e.length<2||t.length<2)return 0;let r=this.bigrams(e),n=this.bigrams(t),o=0,i=[...n];for(let a of r){let d=i.indexOf(a);d>=0&&(o++,i.splice(d,1))}return 2*o/(r.length+n.length)}bigrams(e){let t=[];for(let r=0;r<e.length-1;r++)t.push(e.slice(r,r+2));return t}isTypeCompatible(e,t){return ru(e,t)}inferType(e,t){return e.apiName===t.apiName&&e.type===t.type?"direct":e.apiName!==t.apiName?"rename":"direct"}};var jx=new Set(["quicksync:suggest-objects","quicksync:detect-relationships","quicksync:preview","quicksync:execute"]),Bs={direction:"source_to_target",mode:"full",conflictStrategy:"source_wins",operation:"insert",batchSize:200},Zd=class{constructor(e){this.deps=e}deps;suggester=new Xd;relationshipDetector=new Kd;previewEstimator=new Yd;autoFieldMapper=new Qd;async handle(e){if(!jx.has(e.type))return!1;switch(e.type){case"quicksync:suggest-objects":return await this.handleSuggestObjects(e),!0;case"quicksync:detect-relationships":return await this.handleDetectRelationships(e),!0;case"quicksync:preview":return await this.handlePreview(e),!0;case"quicksync:execute":return await this.handleExecute(e),!0;default:return!1}}async handleSuggestObjects(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(xh,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let i=(await(await B(r.orgId??"",this.deps.orgRegistry,this.deps.orgManager)).describeGlobal()).sobjects.filter(c=>c.createable&&c.queryable).map(c=>c.name),a=this.suggester.suggest(i,r.alreadySelected??[]),d=A(this.deps,e,"quicksync:suggest-objects:response",{suggestions:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){P(this.deps,"quicksync:suggest-objects","quicksync:error",e,n)}}async handleDetectRelationships(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Mh,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.orgId??"",this.deps.orgRegistry,this.deps.orgManager),i=(await n.describe(r.objectApiName??"")).fields.map(l=>({name:l.name,type:l.type,referenceTo:l.referenceTo??[],relationshipName:l.relationshipName??null})),a=r.availableObjects??(await n.describeGlobal()).sobjects.filter(l=>l.createable&&l.queryable).map(l=>l.name),d=this.relationshipDetector.detect(r.objectApiName??"",i,r.alreadySelected??[],a),c=A(this.deps,e,"quicksync:detect-relationships:response",{suggestions:d});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(n){P(this.deps,"quicksync:detect-relationships","quicksync:error",e,n)}}async handlePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(jh,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=[...new Set([...r.selectedObjects,...r.parentObjects??[]])],i=[];for(let l of o){let u=await n.query(`SELECT COUNT() FROM ${l}`);i.push({objectApiName:l,count:u.totalSize??0})}let a=new Set(r.parentObjects??[]),d=this.previewEstimator.estimate(i,a),c=A(this.deps,e,"quicksync:preview:response",{preview:d});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(n){P(this.deps,"quicksync:preview","quicksync:error",e,n)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Nh,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let n=Np.parse(r.config),o=await B(n.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await B(n.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=[...new Set([...n.selectedObjects,...n.parentObjects])],d=[];for(let u=0;u<a.length;u++){let p=a[u],g=n.parentObjects.includes(p),[h,f]=await Promise.all([Ut(n.sourceOrgId,p,()=>o.describe(p)),Ut(n.targetOrgId,p,()=>i.describe(p))]),m=h.fields.filter(R=>R.createable).map(R=>({apiName:R.name,label:R.label,type:R.type})),y=f.fields.filter(R=>R.createable).map(R=>({apiName:R.name,label:R.label,type:R.type})),w=this.autoFieldMapper.suggest(m,y),v=this.autoFieldMapper.toMappings(w);d.push({objectApiName:p,operation:Bs.operation,fieldMappings:v,transformRules:[],excludedFields:[],batchSize:Bs.batchSize,insertOrder:g?0:u+1})}let c={id:e.id,name:`Quick Sync ${new Date().toISOString()}`,description:"Auto-generated by Quick Sync",sourceOrgId:n.sourceOrgId,targetOrgId:n.targetOrgId,direction:Bs.direction,mode:Bs.mode,objects:d,conflictStrategy:Bs.conflictStrategy,enableRollback:!1};Oe(this.deps,"info","Quick Sync",`Starting sync of ${a.length} object(s)`);let l=A(this.deps,e,"quicksync:execute:response",{syncConfig:c,objectCount:a.length});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(n){P(this.deps,"quicksync:execute","quicksync:error",e,n)}}};var SO=6e4,Nx=2880*6e4,$x=60*6e4,ec=class{deps;schedules=new Map;checkInterval;lastTickTime=0;claims;lastPrune=0;running=new Set;constructor(e){this.deps=e,this.claims=e.claims??Eo()}start(){if(this.checkInterval)return;let e=this.deps.scheduleStore.loadAll(),t=this.now();for(let r of e)this.schedules.set(r.id,this.withPlausibleNextRun(r,t));this.lastTickTime=this.now(),this.checkInterval=setInterval(()=>{this.tick()},SO),this.deps.log("[SyncScheduleExecutor] started")}withPlausibleNextRun(e,t){if(!e.nextRunAt)return e;let r=new Date(e.nextRunAt).getTime(),n=Number.isNaN(r);if(!n&&r<=t+Kb)return e;let o={...e,nextRunAt:this.computeNextRunAt(e.cron,e.timezone)};return this.deps.scheduleStore.save(o),this.deps.log(`[SyncScheduleExecutor] ${e.id}: next run ${n?`"${e.nextRunAt}" cannot be read,`:e.nextRunAt} replaced by ${o.nextRunAt||"none"}`),o}stop(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=void 0,this.deps.log("[SyncScheduleExecutor] stopped"))}async tick(){let e=this.now(),t=e-this.lastTickTime;t>2*SO&&this.deps.log(`[SyncScheduleExecutor] sleep-wake detected (elapsed ${Math.round(t/1e3)}s)`),this.lastTickTime=e,e-this.lastPrune>=$x&&(this.lastPrune=e,this.claims.prune(Nx));for(let r of this.schedules.values()){if(!r.enabled||!r.nextRunAt)continue;let n=new Date(r.nextRunAt).getTime();if(Number.isNaN(n)){let i=r.nextRunAt;r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),this.deps.scheduleStore.save(r),this.deps.log(`[SyncScheduleExecutor] ${r.id}: next run "${i}" cannot be read, replaced by ${r.nextRunAt||"none"}`);continue}if(n>e||this.running.has(r.id))continue;if(!this.claims.claim(`sync-schedule:${r.id}:${n}`)){this.deps.log(`[SyncScheduleExecutor] ${r.id} due at ${r.nextRunAt} is run by another window`),r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone);continue}let o=this.deps.configStore.load(r.configId);if(!o){this.deps.log(`[SyncScheduleExecutor] config not found for schedule ${r.id} (configId=${r.configId})`),r.lastRunAt=new Date(e).toISOString(),r.lastResult="failure",r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),r.updatedAt=new Date(e).toISOString(),this.deps.scheduleStore.save(r),r.notifyOnFailure&&this.deps.notificationCenter.notify("error","Sync schedule failed",`${r.name}: sync configuration "${r.configId}" no longer exists. Save the configuration again, or delete the schedule.`);continue}r.notifyOnComplete&&this.deps.notificationCenter.notify("info","Sync schedule started",r.name),this.running.add(r.id);try{let i=await this.deps.onExecute(o);if(r.lastRunAt=new Date(e).toISOString(),r.lastResult=i.cancelled?"cancelled":i.status,r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),r.updatedAt=new Date(e).toISOString(),this.deps.scheduleStore.save(r),i.cancelled)r.notifyOnComplete&&this.deps.notificationCenter.notify("info","Sync schedule cancelled",`${r.name}: ${i.error??"the run was cancelled."} Its entry in the sync history has what it wrote.`);else if(i.status==="failure"){if(r.notifyOnFailure){let a=i.objectResults.flatMap(d=>d.errors)[0];this.deps.notificationCenter.notify("error","Sync schedule failed",`${r.name}: ${a??"the run failed; its entry in the sync history has the details."}`)}}else if(i.status==="partial"&&r.notifyOnComplete){let a=i.objectResults.flatMap(d=>d.errors)[0];this.deps.notificationCenter.notify("warning","Sync schedule completed with errors",`${r.name}: ${a??"some records failed; its entry in the sync history has the details."}`)}else r.notifyOnComplete&&this.deps.notificationCenter.notify("success","Sync schedule completed",r.name)}catch(i){if(r.lastRunAt=new Date(e).toISOString(),r.lastResult="failure",r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),r.updatedAt=new Date(e).toISOString(),this.deps.scheduleStore.save(r),r.notifyOnFailure){let a=i instanceof Error?i.message:String(i);this.deps.notificationCenter.notify("error","Sync schedule failed",`${r.name}: ${a}`)}}finally{this.running.delete(r.id)}}}upsert(e){let t=this.schedules.get(e.id),r={...e,nextRunAt:this.computeNextRunAt(e.cron,e.timezone),lastRunAt:t?.lastRunAt,lastResult:t?.lastResult};return this.schedules.set(r.id,r),this.deps.scheduleStore.save(r),this.deps.log(`[SyncScheduleExecutor] upserted schedule ${r.id}`),r}delete(e){let t=this.schedules.delete(e);return t&&(this.deps.scheduleStore.delete(e),this.deps.log(`[SyncScheduleExecutor] deleted schedule ${e}`)),t}toggle(e,t){let r=this.schedules.get(e);if(r)return r.enabled=t,t&&(r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone)),r.updatedAt=new Date(this.now()).toISOString(),this.deps.scheduleStore.save(r),this.deps.log(`[SyncScheduleExecutor] toggled ${e} -> ${t?"enabled":"disabled"}`),r}getSchedules(){return Array.from(this.schedules.values())}getSchedule(e){return this.schedules.get(e)}computeNextRunAt(e,t){let r=pa(e,t,this.now());return typeof r=="number"?new Date(r).toISOString():(this.deps.log(`[SyncScheduleExecutor] no next run for cron "${e}": ${r.reason}`),"")}now(){return this.deps.now?this.deps.now():Date.now()}};var ip="schedule:sync:",kO="syncSchedules",tc=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${ip}${e.id}`,e,kO)}load(e){return this.configStore.get(`${ip}${e}`)}list(){let e=this.configStore.getByCategory(kO);return Object.values(e).sort((r,n)=>n.createdAt.localeCompare(r.createdAt))}delete(e){return this.configStore.delete(`${ip}${e}`)}loadAll(){return this.list()}};var Lx=new Set(["sync:schedule:list","sync:schedule:upsert","sync:schedule:toggle","sync:schedule:delete"]),rc=class{constructor(e){this.deps=e}deps;executor;executeBridge;inFlight=0;claims=Eo();async handle(e){if(!Lx.has(e.type))return!1;switch(e.type){case"sync:schedule:list":return this.handleList(e),!0;case"sync:schedule:upsert":return this.handleUpsert(e),!0;case"sync:schedule:toggle":return this.handleToggle(e),!0;case"sync:schedule:delete":return this.handleDelete(e),!0;default:return!1}}getExecutor(){if(!this.executor){let e=new ec({scheduleStore:new tc(this.deps.configStore),configStore:new Pt(this.deps.configStore),onExecute:t=>this.executeDue(t),notificationCenter:{notify:(t,r,n)=>{this.deps.log(`[SyncSchedule] ${t}: ${r} \u2014 ${n}`),Oe(this.deps,t,r,n)}},log:this.deps.log,claims:{claim:t=>this.claims.claim(t),prune:t=>this.claims.prune(t)}});e.start(),e.stop(),this.executor=e}return this.executor}async executeDue(e){if(!this.executeBridge)throw new Error("Scheduled sync execution is not wired to the sync engine yet");let t=this.deps.services?.getSandforgeSetting?.("sync.maxConcurrentOps",3)??3;if(this.inFlight>=t)throw new Error(`Scheduled sync skipped: ${this.inFlight} execution(s) already in flight (max ${t})`);this.inFlight++;try{return await this.executeBridge(e)}finally{this.inFlight--}}startScheduler(e,t){this.executeBridge=e,t&&(this.claims=t),this.getExecutor().start(),this.deps.log("[SyncScheduleHandler] scheduler started (tick loop running)")}stopScheduler(){this.executor?.stop()}handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.getExecutor().getSchedules(),r=A(this.deps,e,"sync:schedule:list:response",{schedules:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}catch(t){P(this.deps,"sync:schedule:list","sync:schedule:error",e,t)}}handleUpsert(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Mf,e,"sync:schedule:error",this.deps);if(!t)return;let r=t.schedule.configId;if(!new Pt(this.deps.configStore).load(r)){P(this.deps,"sync:schedule:upsert","sync:schedule:error",e,new Error(`Sync configuration not found: ${r}. Save it from the Sync tab first.`),{code:"NOT_FOUND"});return}let{cron:n,timezone:o}=t.schedule,i=pa(n,o,Date.now());if(typeof i!="number"){P(this.deps,"sync:schedule:upsert","sync:schedule:error",e,new Error(i.refused==="unreadable"?`The schedule was not saved: SandForge cannot read the cron expression "${n}" (${i.reason}).`:`The schedule was not saved. ${i.reason}`),{code:"INVALID_SCHEDULE"});return}try{let a=this.getExecutor().upsert(t.schedule),d=A(this.deps,e,"sync:schedule:upsert:response",{success:!0,schedule:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(a){P(this.deps,"sync:schedule:upsert","sync:schedule:error",e,a)}}handleToggle(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(jf,e,"sync:schedule:error",this.deps);if(t)try{let r=this.getExecutor().toggle(t.scheduleId,t.enabled);if(!r){P(this.deps,"sync:schedule:toggle","sync:schedule:error",e,new Error(`Schedule not found: ${t.scheduleId}`),{code:"NOT_FOUND"});return}let n=A(this.deps,e,"sync:schedule:toggle:response",{success:!0,schedule:r,scheduleId:t.scheduleId,enabled:t.enabled});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){P(this.deps,"sync:schedule:toggle","sync:schedule:error",e,r)}}handleDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Nf,e,"sync:schedule:error",this.deps);if(t)try{let r=this.getExecutor().delete(t.scheduleId),n=A(this.deps,e,"sync:schedule:delete:response",{success:r,scheduleId:t.scheduleId});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){P(this.deps,"sync:schedule:delete","sync:schedule:error",e,r)}}};var Fx=new Set(["direct","rename"]);function OO(s,e,t,r={}){let n={objectApiName:s.objectApiName,fieldMappings:[],addOnFields:[],transformRules:[],applyDeletes:s.applyDeletes},o=r.keepContactPoints===!0?{keepContactPoints:!0}:{};switch(s.match.kind){case"id":return{...n,keyField:"Id",keySource:"Id",...o};case"externalId":return{...n,keyField:s.match.field,keySource:s.match.field,...o};case"syncConfig":{let i=e(s.match.configId);if(!i)throw new Error(`${s.objectApiName}: the saved Sync configuration picked no longer exists.`);if(i.sourceOrgId!==t.sourceOrgId||i.targetOrgId!==t.targetOrgId)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" runs between two other orgs.`);let a=i.objects.find(p=>p.objectApiName===s.objectApiName);if(!a)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" does not carry it.`);let d=qo([a]);if(d.length>0)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" cannot be applied. ${Wo(d)}`);let c=Xp([a]);if(c.length>0)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" cannot be applied. ${Kp(c)}`);let l=a.externalIdField?.trim()||"Id",u=a.fieldMappings.find(p=>p.targetField===l&&Fx.has(p.type));return{...n,keyField:l,keySource:l==="Id"?"Id":u?.sourceField??l,fieldMappings:a.fieldMappings,...a.excludedFields?.length?{excludedFields:a.excludedFields}:{},addOnFields:a.addOnFields,transformRules:a.transformRules,...i.keepContactPoints===!0?{keepContactPoints:!0}:{}}}}}var _x=G({entityName:L().min(1),changeType:L().min(1),recordIds:ke(L()),commitTimestamp:Me(),commitUser:L().optional(),transactionKey:L().optional(),changeOrigin:L().optional(),changedFields:ke(L()).optional(),nulledFields:ke(L()).optional()}).loose(),Ux=G({event:G({replayId:Me()}).loose(),payload:G({ChangeEventHeader:_x}).loose()}).loose(),nc="ChangeEvent";function AO(s){return`/data/${s.endsWith("__c")?s.slice(0,-1):s}${nc}`}function TO(s){if(!s.endsWith(nc)||s===nc)return null;let e=s.slice(0,-nc.length);return e.endsWith("__")?`${e}c`:e}function EO(s,e){return s.endsWith("__c")?`${s.slice(0,-3)}__${e}__s`:s.endsWith("Address")?`${s.slice(0,-7)}${e}`:e}function IO(s){let e=s.indexOf(".");return e<0?s:EO(s.slice(0,e),s.slice(e+1))}function Hx(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function PO(s,e){let t=Ux.safeParse(e);if(!t.success){let i=t.error.issues[0];throw new Error(`A message on ${s} is not a change event (${i.path.join(".")||"message"}: ${i.message}).`)}let{ChangeEventHeader:r,...n}=t.data.payload,o={};for(let[i,a]of Object.entries(n))if(Hx(a))for(let[d,c]of Object.entries(a))o[EO(i,d)]=c;else o[i]=a;for(let i of r.nulledFields??[])o[IO(i)]=null;return{channel:s,replayId:t.data.event.replayId,objectApiName:r.entityName,changeType:r.changeType,recordIds:r.recordIds,commitTimestamp:r.commitTimestamp,commitUser:r.commitUser??"",transactionKey:r.transactionKey??"",changeOrigin:r.changeOrigin??"",changedFieldNames:(r.changedFields??[]).map(IO),values:o}}var ap="SandForgeRealtime";function CO(s){return s.changeOrigin.split(";").some(e=>e.trim()===`client=${ap}`)}var $o=class extends Error{constructor(t,r){super(`${t}: ${r}`);this.channel=t;this.answer=r;this.name="SubscriptionRefused"}channel;answer;get replayIdRefused(){return/replay ?id/i.test(this.answer)}};function Bx(s){return s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s)}function DO(s){let e=new Map,t=new Map,r=[],n=!1,o={added(a){a.disable("websocket")},outgoing(a,d){if(a.channel==="/meta/subscribe"&&a.subscription){let c=e.get(a.subscription);c!==void 0&&(a.ext={...a.ext??{},replay:{[a.subscription]:c}})}d(a)},incoming(a,d){if(a.channel==="/meta/subscribe"&&a.successful===!1)t.set(a.subscription??"",a.error??"refused without a reason");else if((a.channel==="/meta/handshake"||a.channel==="/meta/connect")&&a.successful===!1&&a.advice?.reconnect==="none"){if(!n){n=!0;let c=a.error??`${a.channel} refused`;for(let l of r)l(c)}}else if(!a.channel.startsWith("/meta/")){let c=a.data?.event?.replayId;typeof c=="number"&&e.has(a.channel)&&e.set(a.channel,c)}d(a)}},i=s.createClient([o]);return{subscribe(a,d,c){return e.set(a,d),t.delete(a),new Promise((l,u)=>{i.subscribe(a,c).then(()=>l(),p=>{e.delete(a),u(new $o(a,t.get(a)??Bx(p)))})})},onDown(a){r.push(a)},disconnect(){n=!0,i.disconnect()}}}var xO="SELECT EventChannel, SelectedEntity FROM PlatformEventChannelMember";function MO(s){let e=new Map;for(let t of s){let r=typeof t.SelectedEntity=="string"?t.SelectedEntity:"",n=TO(r);if(!n||e.has(n))continue;let o=typeof t.EventChannel=="string"?t.EventChannel:"";e.set(n,{objectApiName:n,channel:o})}return[...e.values()].sort((t,r)=>t.objectApiName.localeCompare(r.objectApiName))}async function jO(s,e,t,r,n=()=>{}){let o=t.filter(i=>i.sourceOrgId===r.sourceOrgId&&i.targetOrgId===r.targetOrgId);return Promise.all(s.map(async({objectApiName:i,channel:a})=>{let d=!0,c=[];try{c=(await e(i)).fields.filter(u=>u.externalId===!0).map(u=>u.name).sort()}catch(l){d=!1,n(`[realtime] ${i} could not be described in the target: ${T(l)}`)}return{objectApiName:i,channel:a,inTarget:d,externalIdFields:c,syncConfigs:o.filter(l=>l.objects.some(u=>u.objectApiName===i)).map(l=>({id:l.id,name:l.name}))}}))}var sc=class{constructor(e=1e4){this.capacity=e}capacity;stamps=new Map;record(e,t){if(this.stamps.delete(e),this.stamps.set(e,t),this.stamps.size>this.capacity){let r=this.stamps.keys().next().value;r!==void 0&&this.stamps.delete(r)}}wrote(e,t){return this.stamps.get(e)===t}},mn=200,NO=new Set(["int","double","currency","percent","long"]),qx="The org sent an overflow notice instead of this change: one transaction changed more records than change events carry. A Sync run brings the target up to date.";function Wx(s){return s==="DELETE"||s==="GAP_DELETE"}function $O(s){return s==="CREATE"||s==="UNDELETE"}function oc(s){if(typeof s!="string"||s==="")return null;let e=s.replace(/([+-]\d{2})(\d{2})$/,"$1:$2"),t=Date.parse(e);return Number.isNaN(t)?null:t}function LO(s){return Object.fromEntries(Object.entries(s).filter(([e])=>e!=="attributes"))}function FO(s){return s==null||s===""}function dp(s){return String(s).toLowerCase()}var ic=class{constructor(e,t){this.plan=e;this.deps=t;this.objectConfig={objectApiName:e.objectApiName,operation:e.keyField==="Id"?"update":"upsert",externalIdField:e.keyField,fieldMappings:[],transformRules:e.transformRules,excludedFields:[],addOnFields:[],batchSize:mn,insertOrder:0}}plan;deps;mapping=new sf;transforms=new of;objectConfig;masked=new Set;get contactPoints(){return this.plan.keepContactPoints===!0?void 0:this.deps.contactPoints}async apply(e){let t=e.map(()=>[]),r=[],n=this.deps.maskedSourceFields;n&&(this.masked=new Set(await n(this.plan.objectApiName).catch(()=>[])));let o=[];e.forEach((i,a)=>{if(i.changeType==="GAP_OVERFLOW"){t[a].push({outcome:"failed",error:qx});return}if(i.recordIds.length===0){t[a].push({outcome:"failed",error:"The change named no record."});return}let d=Wx(i.changeType)?"delete":"upsert";if(d==="delete"&&!this.plan.applyDeletes){t[a].push({outcome:"deletes-off"});return}let c=o[o.length-1];(!c||c.kind!==d)&&(c={kind:d,changes:new Map},o.push(c));for(let l of i.recordIds){let u=c.changes.get(l);u?(u.eventIndexes.push(a),u.values={...u.values,...i.values},u.full=u.full||$O(i.changeType),u.needsRead=u.needsRead||i.changeType.startsWith("GAP_"),u.commitTimestamp=Math.min(u.commitTimestamp,i.commitTimestamp),u.replayId=Math.max(u.replayId,i.replayId)):c.changes.set(l,{recordId:l,eventIndexes:[a],changeType:i.changeType,full:$O(i.changeType),needsRead:i.changeType.startsWith("GAP_")&&d==="upsert",values:{...i.values},commitTimestamp:i.commitTimestamp,replayId:i.replayId})}});for(let i of o){let a=[...i.changes.values()],d=(c,l)=>{for(let u of c.eventIndexes)t[u].push(l)};try{i.kind==="upsert"?await this.applyUpserts(a,d,r):await this.applyDeletes(a,d,r)}catch(c){let l=T(c);for(let u of a)d(u,{outcome:"failed",error:l})}}return{results:t.map(zx),held:r}}async resolve(e,t,r){let n=e.record[this.plan.keyField],o;if(e.kind==="delete"?o=t==="source_wins"?{}:null:o=this.resolvedValues(e,t,r),o===null)return{success:!0,resolvedValues:{}};try{if(e.kind==="delete"){let d=await this.writeOne("delete",{Id:e.targetId});return d.success?{success:!0,resolvedValues:{Id:e.targetId}}:{success:!1,resolvedValues:{},error:d.errors[0]??"Delete refused."}}let i=await this.coerced({...o,[this.plan.keyField]:n}),a=await this.writeOne(this.objectConfig.operation,i);return a.success?(await this.rememberWrites([a.id??e.targetId]),{success:!0,resolvedValues:i}):{success:!1,resolvedValues:{},error:a.errors[0]??"Write refused."}}catch(i){return{success:!1,resolvedValues:{},error:T(i)}}}resolvedValues(e,t,r){let n=Object.fromEntries(Object.entries(e.record).filter(([o])=>o!==this.plan.keyField));switch(t){case"source_wins":return n;case"merge":{let o=Object.fromEntries(Object.entries(n).filter(([,i])=>i!==null));return Object.keys(o).length>0?o:null}case"manual":{let o=Object.fromEntries(Object.entries(r??{}).filter(([i])=>i in n).map(([i,a])=>[i,a.value]));return Object.keys(o).length>0?o:null}case"target_wins":case"newest_wins":return null}}async coerced(e){let t=await this.deps.target.describe(this.plan.objectApiName),r=new Map(t.fields.map(o=>[o.name,o.type??""])),n={};for(let[o,i]of Object.entries(e)){let a=r.get(o)??"";if(typeof i=="string"&&a==="boolean")n[o]=i.trim().toLowerCase()==="true";else if(typeof i=="string"&&NO.has(a)&&i.trim()!==""){let d=Number(i);n[o]=Number.isNaN(d)?i:d}else n[o]=i}return n}async writeOne(e,t){let{outcomes:r}=await this.deps.write({...this.objectConfig,operation:e,batchSize:1},[t],this.contactPoints);return r[0]??{success:!1,errors:["The target answered nothing."]}}async applyUpserts(e,t,r){let n=this.plan.objectApiName,o=new Map((await this.deps.target.describe(n)).fields.map(g=>[g.name,g]));if(this.plan.keyField!=="Id"&&!o.has(this.plan.keyField))throw new Error(`${n} has no field ${this.plan.keyField} in the target org.`);await this.readWhole(e.filter(g=>g.needsRead),t);let i=e.filter(g=>!g.needsRead||g.full),a=await this.keysOf(i,t,!1);i=i.filter(g=>a.has(g.recordId));let d=await this.readTarget([...new Set([...a.values()])],o,this.writtenFieldsOf(i,a)),c=[],l=[];for(let g of i){let h=a.get(g.recordId),f=d.get(dp(h))??[];if(f.length>1){t(g,{outcome:"failed",error:`${f.length} records of ${n} in the target have ${this.plan.keyField} = ${String(h)}.`});continue}let m=f[0];if(!m){this.plan.keyField==="Id"?t(g,{outcome:"failed",error:"No record in the target has this Id: it was made after the two orgs were copied. Match on an external id to copy records made since."}):g.full?c.push({change:g,record:this.recordFor(g,h,o,!1)}):l.push(g);continue}let y=String(m.Id),w=this.recordFor(g,h,o,!0),v=oc(m.LastModifiedDate);if(!(v!==null&&v>g.commitTimestamp&&!this.deps.ownWrites.wrote(y,v))){c.push({change:g,record:w,targetId:y});continue}switch(this.deps.conflictStrategy){case"source_wins":c.push({change:g,record:w,targetId:y});break;case"merge":{let b=Object.fromEntries(Object.entries(w).filter(([O,k])=>k!==null||O===this.plan.keyField));Object.keys(b).length>1?c.push({change:g,record:b,targetId:y}):t(g,{outcome:"kept-target"});break}case"manual":r.push(this.held(g,"upsert",w,m)),t(g,{outcome:"held"});break;case"target_wins":case"newest_wins":t(g,{outcome:"kept-target"});break}}if(l.length>0){for(let g of l)g.needsRead=!0;await this.readWhole(l,t);for(let g of l.filter(h=>h.full))c.push({change:g,record:this.recordFor(g,a.get(g.recordId),o,!1)})}if(c.length===0)return;let{outcomes:u}=await this.deps.write(this.objectConfig,c.map(g=>g.record),this.contactPoints),p=[];c.forEach((g,h)=>{let f=u[h];if(f?.success){t(g.change,{outcome:"applied"});let m=f.id??g.targetId;m&&p.push(m)}else t(g.change,{outcome:"failed",error:f?.errors[0]??"The target answered nothing for this record."})}),await this.rememberWrites(p)}async applyDeletes(e,t,r){let n=this.plan.objectApiName,o=new Map((await this.deps.target.describe(n)).fields.map(u=>[u.name,u])),i=await this.keysOf(e,t,!0),a=e.filter(u=>i.has(u.recordId)),d=await this.readTarget([...new Set([...i.values()])],o,[]),c=[];for(let u of a){let p=i.get(u.recordId),g=d.get(dp(p))??[];if(g.length>1){t(u,{outcome:"failed",error:`${g.length} records of ${n} in the target have ${this.plan.keyField} = ${String(p)}.`});continue}let h=g[0];if(!h){t(u,{outcome:"applied"});continue}let f=String(h.Id),m=oc(h.LastModifiedDate);!(m!==null&&m>u.commitTimestamp&&!this.deps.ownWrites.wrote(f,m))||this.deps.conflictStrategy==="source_wins"?c.push({change:u,targetId:f}):this.deps.conflictStrategy==="manual"?(r.push(this.held(u,"delete",{[this.plan.keyField]:p},h)),t(u,{outcome:"held"})):t(u,{outcome:"kept-target"})}if(c.length===0)return;let{outcomes:l}=await this.deps.write({...this.objectConfig,operation:"delete"},c.map(u=>({Id:u.targetId})));c.forEach((u,p)=>{let g=l[p];t(u.change,g?.success?{outcome:"applied"}:{outcome:"failed",error:g?.errors[0]??"The target answered nothing for this record."})})}held(e,t,r,n){let o=Object.keys(r).filter(i=>i!==this.plan.keyField);return{conflictId:`${this.plan.objectApiName}:${e.recordId}:${e.replayId}`,objectApiName:this.plan.objectApiName,recordId:e.recordId,replayId:e.replayId,changeType:e.changeType,kind:t,record:r,targetId:String(n.Id),targetValues:Object.fromEntries(o.map(i=>[i,n[i]??null])),targetLastModified:new Date(oc(n.LastModifiedDate)??0).toISOString()}}async keysOf(e,t,r){let{keySource:n}=this.plan,o=e.filter(a=>n!=="Id"&&FO(a.values[n])&&!(n in a.values&&a.full));if(o.length>0){let a=await this.readSource(o.map(d=>d.recordId),`Id, ${He(n)}`,r);for(let d of o){let c=a.get(d.recordId);c&&(d.values={...d.values,[n]:c[n]??null})}}let i=new Map;for(let a of e){if(n!=="Id"&&!(n in a.values)){t(a,{outcome:"failed",error:r?"The deleted record can no longer be read in the source (it left the recycle bin), so the record to delete in the target cannot be found.":"The source record could not be read back, so its record in the target cannot be found."});continue}let d=this.plan.keyField==="Id"?a.recordId:this.mapped(a)[this.plan.keyField];if(FO(d)){t(a,{outcome:"failed",error:`The source record has no ${n}, so its record in the target cannot be found.`});continue}i.set(a.recordId,d)}return i}mapped(e){let r={...this.masked.size>0?Object.fromEntries(Object.entries(e.values).filter(([o])=>!this.masked.has(o))):e.values,Id:e.recordId},n=this.mapping.apply(r,this.plan.fieldMappings,this.plan.excludedFields);return this.plan.keySource!=="Id"&&n[this.plan.keyField]===void 0&&(n[this.plan.keyField]=r[this.plan.keySource]),n=this.transforms.transformRecord(n,this.objectConfig),this.mapping.applyAddOns(n,this.plan.addOnFields)}recordFor(e,t,r,n){let o=this.mapped(e),i=n?[]:ui(this.plan.objectApiName,o),a={};for(let[d,c]of Object.entries(o)){if(c===void 0||d==="Id"||d===this.plan.keyField||i.includes(d))continue;let l=r.get(d);l&&((n?l.updateable!==!0:l.createable!==!0)||(a[d]=c))}return a[this.plan.keyField]=t,a}writtenFieldsOf(e,t){let r=new Set;for(let n of e)if(t.has(n.recordId))for(let[o,i]of Object.entries(this.mapped(n)))i!==void 0&&r.add(o);return[...r]}async readWhole(e,t){if(e.length===0)return;let r=await this.readSource(e.map(n=>n.recordId),"FIELDS(ALL)",!1);for(let n of e){let o=r.get(n.recordId);if(!o){t(n,{outcome:"failed",error:"The source record could not be read back: it was deleted since."});continue}n.values={...LO(o),...n.values},n.full=!0}}async readSource(e,t,r){let n=pt(this.plan.objectApiName),o=new Map;for(let i=0;i<e.length;i+=mn){let d=e.slice(i,i+mn).map(u=>`'${Bt(u)}'`).join(", "),c=t==="FIELDS(ALL)"?` LIMIT ${mn}`:"",l=await this.deps.source.query(`SELECT ${t} FROM ${n} WHERE Id IN (${d})${c}`,{includeDeleted:r});for(let u of l)o.set(String(u.Id),u)}return o}async readTarget(e,t,r){let n=pt(this.plan.objectApiName),o=He(this.plan.keyField),i=NO.has(t.get(this.plan.keyField)?.type??""),a=r.filter(l=>l!=="Id"&&l!==this.plan.keyField&&l!=="LastModifiedDate"&&t.has(l)),d=["Id",...o==="Id"?[]:[o],"LastModifiedDate",...a],c=new Map;for(let l=0;l<e.length;l+=mn){let p=e.slice(l,l+mn).map(f=>i?String(Number(f)):`'${Bt(String(f))}'`).join(", "),g=`WHERE ${o} IN (${p})`,h;try{h=await this.deps.target.query(`SELECT ${d.map(He).join(", ")} FROM ${n} ${g}`)}catch{h=await this.deps.target.query(`SELECT Id${o==="Id"?"":`, ${o}`}, LastModifiedDate FROM ${n} ${g}`)}for(let f of h){let m=dp(f[this.plan.keyField]);c.set(m,[...c.get(m)??[],LO(f)])}}return c}async rememberWrites(e){if(e.length===0)return;let t=pt(this.plan.objectApiName);try{for(let r=0;r<e.length;r+=mn){let n=e.slice(r,r+mn).map(i=>`'${Bt(i)}'`).join(", "),o=await this.deps.target.query(`SELECT Id, LastModifiedDate FROM ${t} WHERE Id IN (${n})`);for(let i of o){let a=oc(i.LastModifiedDate);a!==null&&this.deps.ownWrites.record(String(i.Id),a)}}}catch{}}};function zx(s){let e=s.find(t=>t.outcome==="failed");return e||(s.some(t=>t.outcome==="held")?{outcome:"held"}:s.length>0&&s.every(t=>t.outcome==="kept-target")?{outcome:"kept-target"}:s.length>0&&s.every(t=>t.outcome==="deletes-off")?{outcome:"deletes-off"}:{outcome:"applied"})}var ac=class{constructor(e){this.deps=e}deps;async open(e){let t={subscribed:[],refused:[],notes:[]};for(let r of e){let n=AO(r),o=a=>{let d;try{d=PO(n,a)}catch(c){this.deps.onUnreadable(n,T(c));return}this.deps.onEvent(d)},i=this.deps.replayStore.get(n);try{await this.deps.transport.subscribe(n,i??-1,o),t.subscribed.push(r)}catch(a){if(i!==void 0&&a instanceof $o&&a.replayIdRefused)try{await this.deps.transport.subscribe(n,-2,o),t.subscribed.push(r),t.notes.push(`${r}: the org no longer holds the point the last session stopped at (replay id ${i}), so every change it still holds \u2014 up to three days \u2014 is replayed instead. Changes older than that were not received; a Sync run brings the target up to date.`)}catch(d){t.refused.push({objectApiName:r,reason:_O(d)})}else t.refused.push({objectApiName:r,reason:_O(a)})}}return t}close(){this.deps.transport.disconnect()}};function _O(s){return s instanceof $o?s.answer:T(s)}var Vx=[2e3,1e4,3e4],Xx=6e4,dc=class{constructor(e,t){this.config=e;this.deps=t}config;deps;state="disconnected";subscription;watched=[];refused=[];notes=[];error;stopped=!1;buffer=[];flushTimer;flushing=Promise.resolve();held=new Map;startedAt=0;lastEventAt;received=0;applied=0;failed=0;lagTotal=0;lagCount=0;currentLag=0;recentReceipts=[];now(){return(this.deps.now??Date.now)()}get sessionId(){return this.config.sessionId}get running(){return this.state==="syncing"||this.state==="connecting"}async start(){this.state="connecting",this.startedAt=this.now();let e;try{e=await this.open(this.config.watchedObjects)}catch(t){throw this.state="error",this.error=T(t),t}return this.watched=e.subscribed,this.refused=e.refused,this.notes=e.notes,e.subscribed.length===0?(this.state="error",this.error="The source org refused a subscription to every watched object.",this.closeSubscription()):this.state="syncing",e}async stop(){this.stopped=!0,this.state="disconnected",this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0,this.closeSubscription(),this.buffer=[],await this.flushing;let e=this.held.size;return this.held.clear(),e}snapshot(){return{status:this.state,sessionId:this.config.sessionId,watchedObjects:this.watched,refused:this.refused,notes:this.notes,...this.error?{error:this.error}:{}}}metrics(){let e=this.now();this.recentReceipts=this.recentReceipts.filter(r=>e-r<Xx);let t=this.applied+this.failed;return{eventsReceived:this.received,eventsApplied:this.applied,eventsFailed:this.failed,eventsPerMinute:this.recentReceipts.length,averageLagMs:this.lagCount>0?this.lagTotal/this.lagCount:0,currentLagMs:this.currentLag,errorRate:t>0?this.failed/t*100:0,startedAt:new Date(this.startedAt).toISOString(),...this.lastEventAt!==void 0?{lastEventAt:new Date(this.lastEventAt).toISOString()}:{}}}async resolveConflict(e,t,r){let n=this.held.get(e);if(!n)return{success:!1,resolvedValues:{},error:"This change is no longer held: the session that held it has stopped, or it was already decided."};let o=await n.applier.resolve(n.change,t,r);return o.success&&this.held.delete(e),o}closeSubscription(){this.subscription?.close(),this.subscription=void 0}async open(e){let t=await this.deps.openTransport();return t.onDown(r=>{this.reconnect(r)}),this.subscription=new ac({transport:t,replayStore:this.deps.replayStore,onEvent:r=>this.receive(r),onUnreadable:(r,n)=>this.deps.log(`[WARN] realtime ${r}: ${n}`)}),this.subscription.open(e)}async reconnect(e){if(!(this.stopped||this.state!=="syncing")){this.state="connecting",this.error=`The connection to the source org was closed (${e}); reconnecting.`,this.deps.sink.status(this.snapshot()),this.closeSubscription(),this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0,await this.flushing,this.buffer=[];for(let t of Vx){if(await new Promise(r=>setTimeout(r,t)),this.stopped)return;try{let r=await this.open(this.watched);if(r.subscribed.length>0){this.watched=r.subscribed,this.notes=[...this.notes,...r.notes],this.state="syncing",this.error=void 0,this.deps.sink.status(this.snapshot());return}this.closeSubscription()}catch(r){this.deps.log(`[WARN] realtime reconnect failed: ${T(r)}`)}}this.stopped||(this.state="error",this.error=`The connection to the source org was closed (${e}) and could not be reopened.`,this.deps.sink.status(this.snapshot()))}}receive(e){if(this.stopped)return;let t=this.now();this.received++,this.lastEventAt=t,this.recentReceipts.push(t),this.buffer.push(e),this.scheduleFlush(this.buffer.length>=this.config.maxBatchSize?0:this.config.flushIntervalMs)}scheduleFlush(e){if(this.flushTimer!==void 0){if(e>0)return;clearTimeout(this.flushTimer)}this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushing=this.flushing.then(()=>this.flush())},e)}async flush(){for(;this.buffer.length>0&&!this.stopped;){let e=this.buffer.splice(0,this.config.maxBatchSize);try{await this.process(e)}catch(t){this.deps.log(`[ERR] realtime batch: ${T(t)}`)}}}async process(e){let t=e.map(()=>({outcome:"watched"})),r=new Map;e.forEach((i,a)=>{CO(i)?t[a]={outcome:"own-write"}:this.config.appliers.has(i.objectApiName)&&r.set(i.objectApiName,[...r.get(i.objectApiName)??[],a])});for(let[i,a]of r){let d=this.config.appliers.get(i);if(d)try{let{results:c,held:l}=await d.apply(a.map(u=>e[u]));c.forEach((u,p)=>{t[a[p]]=u});for(let u of l)this.held.set(u.conflictId,{change:u,applier:d}),this.deps.sink.conflict(u)}catch(c){let l=T(c);for(let u of a)t[u]={outcome:"failed",error:l}}}let n=this.now(),o=new Map;e.forEach((i,a)=>{let d=t[a];d.outcome==="applied"&&this.applied++,d.outcome==="failed"&&this.failed++;let c=Math.max(0,n-i.commitTimestamp);this.lagTotal+=c,this.lagCount++,this.currentLag=c,o.set(i.channel,Math.max(o.get(i.channel)??0,i.replayId))}),this.deps.sink.events(e.map((i,a)=>Kx(i,t[a]))),this.deps.replayStore.save(o)}};function Kx(s,e){let t={};for(let r of s.changedFieldNames)r in s.values&&(t[r]=s.values[r]);return{replayId:s.replayId,objectApiName:s.objectApiName,changeType:s.changeType,recordIds:s.recordIds,commitTimestamp:new Date(s.commitTimestamp).toISOString(),changedFields:s.changedFieldNames.length>0?t:{...s.values},commitUser:s.commitUser,transactionKey:s.transactionKey,applied:e.outcome==="applied",outcome:e.outcome,...e.error?{error:e.error}:{}}}var Yx="realtime:replay:",Qx="realtime",qs=class{constructor(e,t){this.configStore=e;this.sourceOrgId=t}configStore;sourceOrgId;get key(){return`${Yx}${this.sourceOrgId}`}read(){let e=this.configStore.get(this.key),t={};if(!e||typeof e!="object")return t;for(let[r,n]of Object.entries(e))typeof n=="number"&&Number.isFinite(n)&&(t[r]=n);return t}get(e){return this.read()[e]}save(e){e.size!==0&&this.configStore.set(this.key,{...this.read(),...Object.fromEntries(e)},Qx)}forget(){this.configStore.delete(this.key)}};function cp(s){return s.eventsFailed===0?"success":s.eventsApplied>0?"partial":"failure"}function UO(s){return s.slice(0,15)}function HO(s){let e=s.store.recorder({runId:s.sessionId,configId:`realtime:${s.sessionId}`,configName:"",sourceOrgId:s.sourceOrgId,targetOrgId:s.targetOrgId,realtime:!0});s.identity&&lr(e,s.identity,`realtime ${s.sessionId}`);let t=s.backups?ia({runId:s.sessionId,orgId:s.targetOrgId,files:s.backups,meta:s.meta}):void 0,r=d=>s.target.query(d),n=t?aa({query:r,backup:t,recorder:e,describe:async d=>ur(await s.target.describe(d)),viewsEncrypted:sr(r)}):void 0,o=new Set,i=(d,c,l,u)=>{if(c==="insert"||c==="upsert"){for(let g of da(c,u))o.add(UO(g));return}if(c!=="delete")return;let p=l.flatMap((g,h)=>{let f=g.Id;return u[h]?.success===!0&&typeof f=="string"&&!o.has(UO(f))?[f]:[]});p.length>0&&e.deleted?.(d,p)},a;return{runId:s.sessionId,calls:ca(e,n),write:d=>{let c=Promise.resolve();return(l,u,p)=>{let g=c.then(async()=>{let h=await d(l,u,p);return i(l.objectApiName,l.operation,u,h.outcomes),h});return c=g.catch(()=>{}),g}},get ended(){return a!==void 0},end:d=>(a??=(async()=>{await e.end({status:d.status,...d.cancelled?{cancelled:!0}:{}});try{t?.close()}catch(c){s.log(`[WARN] realtime ${s.sessionId}: the backup of what it wrote over could not be listed whole: ${c instanceof Error?c.message:String(c)}`)}return e.flush()})(),a)}}var Zx=new Set(["realtime:start","realtime:stop","realtime:status","realtime:metrics","realtime:objects","realtime:resolve-conflict"]);function eM(s){let e=r=>B(r,s.orgRegistry,s.orgManager),t=st(s);return{async openTransport(r){let{streaming:n}=await e(r);return DO({createClient(o){let i=n.createClient(o);return{subscribe:(a,d)=>i.subscribe(a,d),disconnect:()=>i.disconnect?.()}}})},async identity(r){return(await e(r)).identity()},reader(r){return{async query(n,o){let i=await e(r),a=o?.includeDeleted===!0,{records:d}=await or({query:async c=>i.query(c,{scanAll:a}),queryMore:async c=>i.queryMore(c)},n);return d},async describe(n){let o=await e(r);return{fields:(await Ut(r,n,()=>o.describe(n))).fields}}}},writer(r,n){return async(o,i,a)=>{let d=await e(r),c=await Og(d,ap),l=new an({connection:c,bulkExecutor:new Xr(t.bulk.threshold),bulkManager:nr(s),retryConfig:t.retry,onProgress:()=>{},log:p=>s.log(p),...n?{calls:n}:{}});return new vb({upsert:(p,g,h,f)=>l.upsert(p,g,h,f),insert:(p,g,h)=>l.insert(p,g,h),update:(p,g,h)=>l.update(p,g,h),delete:(p,g,h)=>l.delete(p,g,h),describeTargetFields:async p=>ur(await Ut(r,p,()=>d.describe(p))),...a?{contactPoints:a}:{}}).write(o,i)}},async tooling(r,n){let o=await e(r),{records:i}=await or({query:async a=>o.tooling.query(a),queryMore:async a=>o.tooling.queryMore(a)},n);return i}}}var cc=class{constructor(e,t){this.deps=e;this.syncConfigs=new Pt(e.configStore),this.access=t??eM(e)}deps;current;lastMetrics=null;registry;liveTracker;syncConfigs;access;runCreations;backupRecords;openRuns=new Set;isWritingTo(e){let t=this.current;return t!==void 0&&t.guard!==void 0&&t.session.running&&t.targetOrgId===e}isRunning(e){return this.openRuns.has(e)}setRunCreations(e){this.runCreations=e}setBackupRecordStore(e){this.backupRecords=e}async handle(e){if(!Zx.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"realtime:objects":return await this.handleObjects(e),!0;case"realtime:start":return await this.handleStart(e),!0;case"realtime:stop":return await this.handleStop(e),!0;case"realtime:status":return this.post(A(this.deps,e,"realtime:status:response",this.statusPayload())),!0;case"realtime:metrics":return this.post(A(this.deps,e,"realtime:metrics:response",{metrics:this.current?.session.metrics()??this.lastMetrics})),!0;case"realtime:resolve-conflict":return await this.handleResolve(e),!0;default:return!1}}setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}async dispose(){await this.stopCurrent()}forgetOrg(e){new qs(this.deps.configStore,e).forget()}post(e){this.deps.broker.postToWebview(e),this.deps.log(`[TX] ${e.type} id=${e.id}`)}pushEvents(e){let t={id:this.deps.nextId(),type:"realtime:events-batch",timestamp:Date.now(),payload:{events:e}};this.deps.broker.postToWebview(t)}pushConflict(e){let t={id:this.deps.nextId(),type:"realtime:conflict",timestamp:Date.now(),payload:{replayId:e.replayId,objectApiName:e.objectApiName,recordIds:[e.recordId],changeType:e.changeType,sourceValues:Object.fromEntries(Object.entries(e.record).filter(([r])=>r in e.targetValues)),targetValues:e.targetValues,targetLastModified:e.targetLastModified}};this.deps.broker.postToWebview(t)}pushStatus(e){let t={id:this.deps.nextId(),type:"realtime:status:response",timestamp:Date.now(),payload:e};this.deps.broker.postToWebview(t)}pushStopped(e,t){let r={id:this.deps.nextId(),type:"realtime:stopped",timestamp:Date.now(),payload:{sessionId:e,reason:t,success:!0}};this.deps.broker.postToWebview(r)}statusPayload(){if(!this.current)return{status:"disconnected",watchedObjects:[]};let e=this.current.encryptedLeftOut??[];return{...this.current.session.snapshot(),...e.length>0?{encryptedLeftOut:e}:{}}}async stopCurrent(){let e=this.current;if(!e)return;this.current=void 0,e.detach();let t=await e.session.stop();return this.lastMetrics=e.session.metrics(),e.finish(),await e.endRun(),e.guard&&X(this.deps,{action:"realtime_sync",module:"sync",operationId:e.operationId,orgId:e.targetOrgId,outcome:cp(this.lastMetrics),guard:e.guard,source:{origin:"org",orgId:e.sourceOrgId}}),t>0&&Oe(this.deps,"warning","Real-time sync",`${t} change(s) held for a decision were not applied: the session that held them has stopped.`),e.session.sessionId}async handleObjects(e){let t=D(vf,e,"realtime:error",this.deps);if(t)try{let r=await this.access.tooling(t.sourceOrgId,xO),n=this.access.reader(t.targetOrgId),o=await jO(MO(r),i=>n.describe(i),this.syncConfigs.list(),t,i=>this.deps.log(i));this.post(A(this.deps,e,"realtime:objects:response",{objects:o}))}catch(r){let n=mg(T(r));P(this.deps,"realtime:objects","realtime:error",e,r,n?{code:n}:void 0)}}async handleStart(e){let t=D(bf,e,"realtime:error",this.deps);if(!t)return;let r=n=>{this.post(A(this.deps,e,"realtime:started",{success:!1,watchedObjects:[],refused:[],notes:[],error:n}))};if(this.current?.session.running){r(`A real-time session is already running (${this.current.session.sessionId}). Stop it before starting another.`);return}try{let n=t.apply.map(I=>OO(I,C=>this.syncConfigs.load(C),t,{keepContactPoints:t.keepContactPoints===!0})),o=n.length>0?await this.passesProductionGuard(e,t.targetOrgId,n):void 0;if(n.length>0&&!o){r("The target org is protected by the Production Guard, which did not allow the writes.");return}let i=new AbortController,a=new sc,d=this.access.reader(t.sourceOrgId),c=this.access.reader(t.targetOrgId),l=crypto.randomUUID(),u=o&&this.runCreations?HO({sessionId:l,sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,store:this.runCreations,...this.backupRecords?{backups:this.backupRecords}:{},meta:this.deps.configStore,target:c,identity:async()=>await this.access.identity?.(t.targetOrgId)??{},log:I=>this.deps.log(I)}):void 0,p=u?u.write(this.access.writer(t.targetOrgId,u.calls)):this.access.writer(t.targetOrgId),g=new bw,h=Tn(sr(I=>d.query(I)),I=>d.describe(I)),f=new Map(n.map(I=>[I.objectApiName,new ic(I,{source:d,target:c,write:p,conflictStrategy:t.conflictStrategy,ownWrites:a,contactPoints:g,maskedSourceFields:h})])),m,y=()=>{},w=new Promise((I,C)=>{y=F=>{F?m?.fail(F):i.signal.aborted?m?.cancel():m?.complete(),F?C(new Error(F)):I()}});w.catch(()=>{});let v=async()=>{if(!u)return;let I=await u.end({status:cp(R.metrics()),cancelled:i.signal.aborted}).catch(C=>T(C));this.openRuns.delete(u.runId),I!==void 0&&Oe(this.deps,"warning","Real-time sync",`What the session wrote could not all be kept (${I}): removing it may leave some of it in the target.`)},R=new dc({sessionId:l,watchedObjects:t.watchedObjects,appliers:f,flushIntervalMs:t.flushIntervalMs,maxBatchSize:t.maxBatchSize},{openTransport:()=>this.access.openTransport(t.sourceOrgId),replayStore:new qs(this.deps.configStore,t.sourceOrgId),sink:{events:I=>this.pushEvents(I),conflict:I=>this.pushConflict(I),status:I=>{if(I.status!=="error"){this.pushStatus(I);return}y(I.error),v().then(()=>this.pushStatus(I))}},log:I=>this.deps.log(I)}),b={session:R,abort:i,operationId:e.id,sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,guard:o,finish:I=>y(I),detach:()=>{},endRun:v};this.current=b,this.lastMetrics=null,u&&this.openRuns.add(u.runId);let O;try{O=await R.start()}catch(I){throw await v(),I}let k=R.snapshot();if(O.subscribed.length>0){let I=`Real-time sync of ${O.subscribed.length} object(s)`;this.registry?.register(R.sessionId,"sync",I,w,i),m=Jt(this.liveTracker,R.sessionId,"realtime",I);let C=()=>{this.current?.session===R&&this.stopCurrent().then(F=>{F&&this.pushStopped(F,"cancelled")})};i.signal.addEventListener("abort",C,{once:!0}),b.detach=()=>i.signal.removeEventListener("abort",C)}else y(),await v();let S=new Set(O.subscribed),E=(await Promise.all(n.filter(I=>S.has(I.objectApiName)).map(async I=>({objectApiName:I.objectApiName,fields:[...await h(I.objectApiName)].sort()})))).filter(I=>I.fields.length>0);E.length>0&&(b.encryptedLeftOut=E),this.post(A(this.deps,e,"realtime:started",{success:O.subscribed.length>0,sessionId:R.sessionId,watchedObjects:O.subscribed,refused:O.refused,notes:O.notes,...E.length>0?{encryptedLeftOut:E}:{},...k.error?{error:k.error}:{}}))}catch(n){r(T(n))}}async passesProductionGuard(e,t,r){let n=this.deps.infraServices?.productionGuard;if(!n)throw X(this.deps,{action:"realtime_sync",module:"sync",operationId:e.id,orgId:t,outcome:"stopped",code:ve.code}),gi();let o={orgId:t,orgTier:Ee(this.deps.orgManager.getOrg(t)),operation:r.some(a=>a.applyDeletes)?"delete":"upsert",objectName:r.map(a=>a.objectApiName).join(", "),recordCount:"unknown",module:"sync"},{decision:i}=await Ke(n,o);if(i==="refused"||i==="declined"){X(this.deps,{action:"realtime_sync",module:"sync",operationId:e.id,orgId:t,outcome:"stopped",guard:i});return}return i}async handleStop(e){let t=D(Rf,e,"realtime:error",this.deps);if(!t)return;let r=this.current;if(!r||t.sessionId!==""&&t.sessionId!==r.session.sessionId){this.post(A(this.deps,e,"realtime:status:response",this.statusPayload()));return}let n=await this.stopCurrent();this.post(A(this.deps,e,"realtime:stopped",{sessionId:n??r.session.sessionId,reason:"stopped",success:!0}))}async handleResolve(e){let t=D(Sf,e,"realtime:error",this.deps);if(!t)return;let r=this.current?await this.current.session.resolveConflict(t.conflictId,t.resolution,t.fieldResolutions&&Object.fromEntries(Object.entries(t.fieldResolutions).map(([n,o])=>[n,{value:o.value,source:o.source}]))):{success:!1,resolvedValues:{},error:"No real-time session is running: the change it held was dropped when it stopped."};r.success||Oe(this.deps,"warning","Real-time sync",`The decision on ${t.conflictId} was not applied: ${r.error??"refused"}`),this.post(A(this.deps,e,"realtime:conflict-resolved",{conflictId:t.conflictId,resolution:t.resolution,success:r.success,resolvedValues:r.resolvedValues,...r.error?{error:r.error}:{}}))}};var tM=new Set(["file:save"]),lc=class{constructor(e,t){this.deps=e;this.saveDialog=t??new Qr}deps;saveDialog;async handle(e){return tM.has(e.type)?(await this.handleSave(e),!0):!1}async handleSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=ff.safeParse(e.payload);if(!t.success){let i={status:"error",message:`Invalid payload \u2014 ${t.error.issues.slice(0,3).map(a=>`${a.path.join(".")||"(root)"}: ${a.message}`).join("; ")}`};this.deps.log(`[FileHandler] save ${i.status}: ${i.message}`),this.deps.broker.postToWebview(A(this.deps,e,"file:save:response",i));return}let r=t.data,n=await this.saveDialog.save(r.suggestedName,r.content,r.extensions);this.deps.log(`[FileHandler] save ${n.status}`),this.deps.broker.postToWebview(A(this.deps,e,"file:save:response",n))}};var rM=new Set(["reports:list","reports:audit","reports:lineage"]),nM="forge:history",oM="sync:history:all",BO=50;function sM(s){return s.readByObject?s.readByObject.reduce((t,r)=>t+r.read,0):(s.graph?.nodes??[]).reduce((t,r)=>t+(r.recordCount??0),0)}function iM(s){let e=s.graph?.nodes??[];return e.filter(t=>!eg(t)).length+tg(s,e).length}var uc=class{constructor(e){this.deps=e}deps;async handle(e){if(!rM.has(e.type))return!1;switch(e.type){case"reports:list":return this.handleList(e),!0;case"reports:audit":return this.handleAudit(e),!0;case"reports:lineage":return this.handleLineage(e),!0;default:return!1}}handleAudit(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Yh,e,"reports:error",this.deps);if(t===null)return;let r=new eo(this.deps.configStore).list(t??{});this.deps.log(`[ReportsHandler] audit trail: ${r.entries.length} of ${r.total} entries`),this.deps.broker.postToWebview(A(this.deps,e,"reports:audit:response",{...r}))}handleLineage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Qh,e,"reports:error",this.deps);if(t===null)return;let r=new zg(this.deps.configStore);this.deps.broker.postToWebview(A(this.deps,e,"reports:lineage:response",{lineage:r.get(t?.operationId),runs:r.runs()}))}handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.readLimit(e),r=this.build(t);this.deps.log(`[ReportsHandler] ${r.reports.length} report(s) from stored history (${r.summary.successRate}% success)`),this.deps.broker.postToWebview(A(this.deps,e,"reports:list:response",{...r}))}readLimit(e){let t=e.payload?.limit;return typeof t!="number"||!Number.isFinite(t)||t<=0?BO:Math.min(Math.floor(t),500)}build(e=BO){let t=this.deps.configStore.get(nM)??[],r=this.deps.configStore.get(oM)??[],n=[...t.map(o=>this.forgeReport(o)),...r.map(o=>this.syncReport(o))].sort((o,i)=>i.generatedAt.localeCompare(o.generatedAt)).slice(0,e);return{reports:n,summary:dM(n)}}forgeReport(e){let t=iM(e),r=sM(e);return{id:`forge-${e.forgeId}`,definitionId:`forge-${e.forgeId}`,type:"forge_execution",title:`Forge clone \u2014 ${t} object(s)`,summary:`${e.status} \xB7 ${r} record(s) across ${t} object(s) \xB7 ${e.idRemapCount} id(s) remapped`,sections:[{title:"Outcome",type:"summary",order:0,content:{status:e.status,objects:t,records:r,idRemapCount:e.idRemapCount,durationMs:e.duration}}],metadata:{module:"forge",operationId:e.forgeId,duration:e.duration,recordCount:r},generatedAt:e.timestamp}}syncReport(e){let t=e.result,r=t?.totalProcessed??0,n=t?.totalFailed??0;return{id:`sync-${e.id}`,definitionId:`sync-${e.id}`,type:"sync_execution",title:`Sync \u2014 ${e.configSnapshot?.name??"unnamed configuration"}`,summary:`${t?.status??"unknown"} \xB7 ${r} processed, ${t?.totalSuccess??0} succeeded, ${n} failed \xB7 triggered ${e.triggeredBy}`,sections:[{title:"Outcome",type:"summary",order:0,content:{status:t?.status??"unknown",processed:r,succeeded:t?.totalSuccess??0,failed:n,skipped:t?.totalSkipped??0,triggeredBy:e.triggeredBy}}],metadata:{module:"sync",operationId:e.id,duration:t?.duration,recordCount:r},generatedAt:e.endTime??e.startTime}}};function aM(s){let e=s.sections[0]?.content?.status;return e==="failure"||e==="failed"||e==="partial"}function dM(s){let e=s.length;if(e===0)return{totalOperations:0,successRate:0,avgDuration:0,errorRate:0};let t=s.filter(aM).length,r=s.map(o=>o.metadata.duration??0),n=o=>Math.round(o*10)/10;return{totalOperations:e,successRate:n((e-t)/e*100),avgDuration:Math.round(r.reduce((o,i)=>o+i,0)/e),errorRate:n(t/e*100)}}function qO(s){return Object.values(s).every(e=>e<50)}var pc=class{deps;constructor(e){this.deps=e}async analyzeOrg(e,t){let r=await this.deps.getConnection(e),n=await this.queryRecordCounts(r),o;if(t){let i=await this.deps.getConnection(t);o=await this.queryRecordCounts(i)}return this.decide(e,n,t,o)}async queryRecordCounts(e){let t=await Promise.all(bp.map(async n=>{try{let o=await e.query(`SELECT COUNT() FROM ${n}`);return{objectName:n,count:o.totalSize}}catch{return{objectName:n,count:0}}})),r={};for(let{objectName:n,count:o}of t)r[n]=o;return r}decide(e,t,r,n){let o=Object.values(t).reduce((l,u)=>l+u,0),i=qO(t),a=n!==void 0&&!qO(n),d="none",c="";return i&&a&&r?(d="clone",c="home.smartAction.reasonClone"):i&&o===0?(d="quick-seed",c="home.smartAction.reasonEmpty"):i?(d="quick-seed",c="home.smartAction.reasonSampleOnly"):a&&r&&(d="sync",c="home.smartAction.reasonSync"),{action:d,reasonKey:c,details:{targetOrgId:e,sourceOrgId:r,recordCounts:t,...n?{sourceRecordCounts:n}:{}}}}};function lM(s,e){return`smart-action:${s}:${e??""}`}var uM=300*1e3,pM=new Set(["smart-action:analyze"]),gc=class{constructor(e){this.deps=e;this.analyzer=new pc({getConnection:t=>B(t,e.orgRegistry,e.orgManager)})}deps;analyzer;cache=new Map;async handle(e){return pM.has(e.type)&&e.type==="smart-action:analyze"?(await this.handleAnalyze(e),!0):!1}forgetOrg(e){for(let[t,r]of this.cache)r.orgIds.includes(e)&&this.cache.delete(t)}async handleAnalyze(e){let t=D(gm,e,"smart-action:error",this.deps);if(t)try{let r=t.targetOrgId,n=t.sourceOrgId,o=lM(r,n),i=this.cache.get(o);if(i&&Date.now()-i.fetchedAt<uM){this.deps.log(`[SmartAction] Cache hit for ${r}`);let c=A(this.deps,e,"smart-action:analyze:response",{recommendation:i.recommendation});this.deps.broker.postToWebview(c),this.deps.log("[TX] smart-action:analyze:response (cached)");return}this.deps.log(`[SmartAction] Analyzing org ${r}`);let a=await this.analyzer.analyzeOrg(r,n);this.cache.set(o,{recommendation:a,fetchedAt:Date.now(),orgIds:n?[r,n]:[r]});let d=A(this.deps,e,"smart-action:analyze:response",{recommendation:a});this.deps.broker.postToWebview(d),this.deps.log("[TX] smart-action:analyze:response")}catch(r){P(this.deps,"smart-action:analyze","smart-action:error",e,r)}}};var gM=new Set(["execution:abort"]),fc=class{constructor(e,t){this.deps=e;this.registry=t}deps;registry;async handle(e){return gM.has(e.type)&&e.type==="execution:abort"?(await this.handleAbort(e),!0):!1}async handleAbort(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=D(Jh,e,"execution:error",this.deps);if(!t)return;let r=t.operationId??t.executionId??"",n=this.registry.get(r);if(!n&&this.registry.cancelBeforeStart(r)){let i=A(this.deps,e,"execution:abort:response",{success:!0,operationId:r});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} (before it started)`);return}if(!n){let i=A(this.deps,e,"execution:abort:response",{success:!1,error:`Operation not found: ${r}`});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} (not found)`);return}if(n.status!=="running"){let i=A(this.deps,e,"execution:abort:response",{success:!1,error:"Operation already finished",status:n.status});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} (already ${n.status})`);return}this.registry.abort(r);let o=A(this.deps,e,"execution:abort:response",{success:!0,operationId:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(t){P(this.deps,"execution:abort","execution:error",e,t)}}};import{readFile as fM}from"node:fs/promises";import{join as hM}from"node:path";var lp=new Map;function WO(s,e){let t=hM(s,`${e}.json`),r=lp.get(t);if(r)return r;let n=fM(t,"utf-8").then(o=>JSON.parse(o));return lp.set(t,n),n.catch(()=>lp.delete(t)),n}var mM=new Set(["i18n:locale"]),hc=class{constructor(e,t){this.deps=e;this.localesDir=t}deps;localesDir;async handle(e){return mM.has(e.type)?(await this.handleLocaleRequest(e),!0):!1}async handleLocaleRequest(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(pm,e,"i18n:locale:response",this.deps);if(!t)return;let{lng:r}=t;if(!this.localesDir){let n=A(this.deps,e,"i18n:locale:response",{lng:r,error:"Locale files are not available in this extension host."});this.deps.broker.replyToRequester(n);return}try{let n=await WO(this.localesDir,r),o=A(this.deps,e,"i18n:locale:response",{lng:r,bundle:n});this.deps.broker.replyToRequester(o),this.deps.log(`[TX] i18n:locale:response (${r})`)}catch(n){this.deps.log(`[ERR] i18n:locale (${r}): ${T(n)}`);let o=A(this.deps,e,"i18n:locale:response",{lng:r,error:T(n)});this.deps.broker.replyToRequester(o)}}};import{AsyncLocalStorage as yM}from"node:async_hooks";function GO(s,e){if(!s)return{decision:"refused",reason:"no Production Guard runs in this window"};let t=s.check(e);return t.allowed?t.requiresConfirmation?{decision:"asks"}:{decision:"allowed"}:{decision:"refused",reason:t.blockedReason??t.impactSummary}}var zO=new yM;async function JO(s,e,t,r){let n=Symbol("pipeline sync"),o,i=s.registry?.onEvent((d,c,l)=>{c!=="started"||l.module!=="sync"||zO.getStore()!==n||(o=d,r?.aborted&&s.registry?.abort(d))}),a=()=>{o!==void 0&&s.registry?.abort(o)};r?.addEventListener("abort",a,{once:!0});try{return await zO.run(n,()=>Mi(t,()=>s.execute(e)))}finally{i?.(),r?.removeEventListener("abort",a)}}var wM=G({setting:L().regex(/^sandforge(?:\.[A-Za-z][A-Za-z0-9]*)+$/)}),mc=class{handlerDeps;executeCommand;panelRouteListener;panelReloadListener;idCounter=0;orgHandler;settingsHandler;monitorHandler;seedHandler;seedCloneHandler;seedCsvHandler;syncHandler;syncHistoryHandler;syncRemovalHandler;seedRemovalHandler;compareHandler;dataOpsHandler;complianceHandler;cleanupHandler;emptyHandler;automationHandler;aiHandler;autopilotHandler;forgeHandler;frozenHandler;checkpointHandler;migrationHandler;configHandler;governanceHandler;quickSyncHandler;syncScheduleHandler;realtimeHandler;fileHandler;reportsHandler;smartActionHandler;i18nHandler;syncHistoryStore;executionHandler;backgroundRegistry;refreshDetector;checkpointStore;beforeRunCheckpoints;constructor(e){this.executeCommand=e.executeCommand??(()=>Promise.resolve()),this.refreshDetector=new ma({configStore:e.configStore,orgManager:e.orgManager,log:e.log}),this.handlerDeps={log:e.log,broker:e.broker,stateSync:e.stateSync,orgManager:e.orgManager,orgRegistry:e.orgRegistry,configStore:e.configStore,secretVault:e.secretVault,authProvider:e.authProvider,sfdxBridge:e.sfdxBridge,services:e.services,robustness:Fc,bulkManager:new Wg(Fc.bulk.maxConcurrentJobs),nextId:()=>this.nextId(),sandboxRefreshes:this.refreshDetector},this.orgHandler=new ba(this.handlerDeps),this.settingsHandler=new Ra(this.handlerDeps),this.monitorHandler=new Ma(this.handlerDeps),this.seedHandler=new Fa(this.handlerDeps),this.seedCloneHandler=new Ba(this.handlerDeps),this.seedCsvHandler=new za(this.handlerDeps),this.seedRemovalHandler=new Qa(this.handlerDeps,void 0,r=>this.seedHandler.isRunning(r)||this.seedCsvHandler.isRunning(r)||this.seedCloneHandler.isRunning(r)),this.syncHandler=new Va(this.handlerDeps),this.syncHistoryStore=new ed(e.configStore),this.syncHandler.setHistoryLogger(new td(this.syncHistoryStore)),this.syncHistoryHandler=new Xa(this.handlerDeps,this.syncHistoryStore,this.syncHandler),this.syncRemovalHandler=new Ka(this.handlerDeps,this.syncHistoryStore,r=>this.syncHandler.isRunning(r)||this.realtimeHandler.isRunning(r)),this.compareHandler=new rd(this.handlerDeps),this.dataOpsHandler=new Dy(this.handlerDeps),this.complianceHandler=new id(this.handlerDeps),this.cleanupHandler=new ad(this.handlerDeps),this.emptyHandler=new kd(this.handlerDeps),this.automationHandler=new Pd(this.handlerDeps),this.aiHandler=new jd(this.handlerDeps),this.autopilotHandler=new $d(this.handlerDeps),this.forgeHandler=new Hd(this.handlerDeps),this.frozenHandler=new eR(this.handlerDeps),this.frozenHandler.setSaltKeeper(Zb(e.secretVault));let t=()=>[this.forgeHandler,this.frozenHandler,this.dataOpsHandler,this.complianceHandler,this.emptyHandler,this.autopilotHandler,this.realtimeHandler];this.checkpointHandler=new Ad(this.handlerDeps,{isRunning:r=>this.syncHandler.isRunning(r)||this.seedHandler.isRunning(r)||this.seedCsvHandler.isRunning(r)||this.seedCloneHandler.isRunning(r),writingTo:(r,n)=>t().some(o=>o.isWritingTo(r,n))}),this.beforeRunCheckpoints={scope:(r,n)=>this.checkpointHandler.scopeBeforeRun(r,n),take:(r,n,o)=>this.checkpointHandler.takeBeforeRun(r,n,o),settle:(r,n)=>this.checkpointHandler.settleBeforeRun(r,n)},this.forgeHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.autopilotHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.frozenHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.syncHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.seedHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.seedCsvHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.seedCloneHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.emptyHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.emptyHandler.setRunWriting((r,n,o)=>this.checkpointHandler.writingTo(r,n,"empty it","Nothing was deleted.",{operationId:o})),this.forgeHandler.setOtherModuleRuns(this.otherModuleRuns("forge",t)),this.syncRemovalHandler.setOtherModuleRuns(this.otherModuleRuns("sync",t)),this.seedRemovalHandler.setOtherModuleRuns(this.otherModuleRuns("seed",t)),this.frozenHandler.setOtherModuleRuns(this.otherModuleRuns("frozen",t)),this.migrationHandler=new Bd(this.handlerDeps),this.configHandler=new zd(this.handlerDeps),this.governanceHandler=new Vd(this.handlerDeps,this.monitorHandler.getAlertEngine()),this.quickSyncHandler=new Zd(this.handlerDeps),this.syncScheduleHandler=new rc(this.handlerDeps),this.realtimeHandler=new cc(this.handlerDeps),this.fileHandler=new lc(this.handlerDeps),this.reportsHandler=new uc(this.handlerDeps),this.smartActionHandler=new gc(this.handlerDeps),this.i18nHandler=new hc(this.handlerDeps,e.localesDir),this.automationHandler.setStepRunners({orgName:r=>{let n=e.orgManager.getOrg(r);return n?Re(n,n.id):void 0},newId:()=>crypto.randomUUID(),backup:(r,n)=>this.dataOpsHandler.backupForPipeline(r,n),compare:(r,n)=>this.compareHandler.compareOrgs(r,n),readOrgHealth:(r,n)=>this.monitorHandler.readOrgHealth(r,n),notify:e.services?.showNotification,savedSyncConfig:r=>new Pt(e.configStore).load(r),listSyncConfigs:()=>new Pt(e.configStore).list(),syncGuard:r=>GO(this.handlerDeps.infraServices?.productionGuard,iu(r,e.orgManager.getOrg(r.targetOrgId))),runSync:(r,n,o)=>JO({execute:i=>this.syncHandler.executeScheduled(i,"pipeline"),registry:this.backgroundRegistry},r,n,o),orgTier:r=>{let n=e.orgManager.getOrg(r);return n?Ee(n):void 0},organizationIdsOf:r=>[e.orgManager.getOrg(r)?.orgId,this.refreshDetector.organizationIdOf(r)].filter(n=>typeof n=="string"&&n!==""),savedSeedTemplate:r=>new xn(e.configStore).load(r),listSeedTemplates:()=>new xn(e.configStore).list(),seed:(r,n)=>this.seedHandler.seedForPipeline(r,n),maskingTemplates:()=>[...Jg.map(r=>({...r,builtIn:!0})),...new ny(e.configStore).list().map(r=>({...r,builtIn:!1}))],anonymize:(r,n)=>this.dataOpsHandler.anonymizeForPipeline(r,n),takeCheckpoint:(r,n)=>this.checkpointHandler.takeForPipeline(r,n),rewind:(r,n)=>this.checkpointHandler.rewindForPipeline(r,n),readCheckpoint:r=>this.readCheckpointForRewind(r)}),this.checkpointHandler.onCheckpointsChanged(()=>{this.automationHandler.revokeVoidGrants()}),this.refreshDetector.onRefreshDetected(r=>this.forgetOrg(r.orgId)),this.refreshDetector.onRefreshDetected(r=>{let n=r.previousOrganizationId??this.refreshDetector.organizationIdOf(r.orgId)??r.detectedAt;Promise.resolve().then(()=>this.automationHandler.noticeSandboxRefresh({orgId:r.orgId,key:n}))})}get sandboxRefreshes(){return this.refreshDetector}postSettings(){this.settingsHandler.postSettings()}forgetOrg(e){ai().remove(e),uR(e),this.monitorHandler.forgetOrg(e),this.forgeHandler.forgetOrg(e),this.frozenHandler.forgetOrg(e),this.aiHandler.forgetOrg(e),this.smartActionHandler.forgetOrg(e),this.realtimeHandler.forgetOrg(e),this.handlerDeps.log(`[sandbox-refresh] dropped what was cached about ${e}`)}setLiveOperationTracker(e){this.monitorHandler.setLiveOperationTracker(e),this.seedHandler.setLiveOperationTracker(e),this.syncHandler.setLiveOperationTracker(e),this.syncRemovalHandler.setLiveOperationTracker(e),this.seedRemovalHandler.setLiveOperationTracker(e),this.forgeHandler.setLiveOperationTracker(e),this.seedCloneHandler.setLiveOperationTracker(e),this.seedCsvHandler.setLiveOperationTracker(e),this.frozenHandler.setLiveOperationTracker(e),this.autopilotHandler.setLiveOperationTracker(e),this.checkpointHandler.setLiveOperationTracker(e),this.dataOpsHandler.setLiveOperationTracker(e),this.cleanupHandler.setLiveOperationTracker(e),this.emptyHandler.setLiveOperationTracker(e),this.complianceHandler.setLiveOperationTracker(e),this.automationHandler.setLiveOperationTracker(e),this.realtimeHandler.setLiveOperationTracker(e)}setBackupRecordStore(e){this.dataOpsHandler.setBackupRecordStore(e),this.syncHandler.setBackupRecordStore(e),this.syncRemovalHandler.setBackupRecordStore(e),this.realtimeHandler.setBackupRecordStore(e)}otherModuleRuns(e,t){return async(r,n)=>{let o=e==="forge"?this.forgeHandler:e==="frozen"?this.frozenHandler:void 0,i=new eo(this.handlerDeps.configStore).list({orgId:r,limit:Ep}).entries,a=[...e==="forge"?[]:await this.forgeHandler.localRunsOn(r,n),...e==="sync"?[]:await this.syncRemovalHandler.localRunsOn(r),...e==="seed"?[]:await this.seedRemovalHandler.localRunsOn(r),...mb(i,e==="frozen"?"frozen_load":void 0)];if(t().some(d=>d!==o&&d.isWritingTo(r))){let d=Date.now();a.push({ids:[],idsUntold:!0,from:d,to:d})}return a}}setSyncRunCreations(e){this.syncHandler.setRunCreations(e),this.syncRemovalHandler.setRunCreations(e),this.realtimeHandler.setRunCreations(e),this.dataOpsHandler.setSyncRuns(e),this.checkpointHandler.setRunFiles("sync",e)}setSeedRunCreations(e){this.seedHandler.setRunCreations(e),this.seedCsvHandler.setRunCreations(e),this.seedCloneHandler.setRunCreations(e),this.seedRemovalHandler.setRunCreations(e),this.checkpointHandler.setRunFiles("seed",e)}sweepCheckpoints(){return this.checkpointHandler.sweep()}setCheckpointStore(e){this.checkpointStore=e,this.checkpointHandler.setStore(e)}async readCheckpointForRewind(e){let{openCheckpointStore:t,defaultCheckpointStoreRoot:r}=await import("./chunk-2S5OMIIA.mjs"),n=this.checkpointStore;if(!n){let d=t({root:r()});if(!("store"in d))throw new Error(`The checkpoints of this machine cannot be read: ${d.refusal.reason}`);n=d.store}let o=await n.read(e);if(o===void 0)return{kept:!1};if(o.checkpoint===void 0)return{kept:!0,valid:!1,why:"damaged"};let{organizationId:i}=o.checkpoint.org,a=(await n.list({organizationId:i,refreshedAt:d=>this.refreshedAtOf(d)})).find(d=>d.checkpointId===e);return{kept:!0,organizationId:i,name:o.checkpoint.name,valid:a?.valid??!1,...a?.why!==void 0?{why:a.why}:{}}}refreshedAtOf(e){let t=r=>r!==void 0&&r.length>=15&&r.slice(0,15)===e.slice(0,15);for(let r of this.handlerDeps.orgManager.getAllOrgs())for(let n of this.refreshDetector.refreshesOf(r.id)){let o=n.previousOrganizationId??(n.organizationId===void 0?this.refreshDetector.organizationIdOf(r.id):void 0);if(t(o))return n.detectedAt}}setEmptyStores(e){this.emptyHandler.setStores(e)}rewindCheckpointsFromPreviewsAnswered(){this.checkpointHandler.rewindFromPreviewsAnswered()}exportCheckpoint(e){return this.checkpointHandler.exportCheckpoint(e)}readCheckpointImport(e){return this.checkpointHandler.readImport(e)}importCheckpoint(e){return this.checkpointHandler.importCheckpoint(e)}checkpointsKeptBefore(e){return this.checkpointHandler.keptBefore(e)}latestCheckpointOf(e){return this.checkpointHandler.latestUsableOf(e)}onCheckpointsChanged(e){return this.checkpointHandler.onCheckpointsChanged(e)}setPanelRouteListener(e){this.panelRouteListener=e}setPanelReloadListener(e){this.panelReloadListener=e}setAIAssistant(e){this.aiHandler.setAIAssistant(e)}setInfraServices(e){this.handlerDeps.infraServices=e}setOrgSelectionCallback(e){this.handlerDeps.onOrgSelected=e}setBackgroundRegistry(e){this.backgroundRegistry=e,this.syncHandler.setRegistry(e),this.syncRemovalHandler.setRegistry(e),this.seedRemovalHandler.setRegistry(e),this.seedHandler.setRegistry(e),this.seedCloneHandler.setRegistry(e),this.seedCsvHandler.setRegistry(e),this.frozenHandler.setRegistry(e),this.realtimeHandler.setRegistry(e),this.autopilotHandler.setRegistry(e),this.executionHandler=new fc(this.handlerDeps,e)}async replayQueuedOperation(e){let t=Sn("offline-replay",e.id,`${e.type}:execute`);switch(e.type){case"sync":await this.syncHandler.rerunFromSnapshot(t,e.payload.config);return;case"seed":{let r={...t,payload:e.payload};await this.seedHandler.handle(r);return}default:throw new Error(`Unsupported queued operation type: ${e.type}`)}}startSyncScheduler(e){this.syncScheduleHandler.startScheduler(t=>this.syncHandler.executeScheduled(t),e)}stopSyncScheduler(){this.syncScheduleHandler.stopScheduler()}stopLiveOperationsPush(){this.monitorHandler.dispose()}async stopRealtime(){await this.realtimeHandler.dispose()}startPipelineTriggers(e){this.automationHandler.startTriggers(e)}stopPipelineTriggers(){this.automationHandler.stopTriggers()}setAIModules(e){this.aiHandler.setAIModules(e),this.handlerDeps.errorResolver=e?.errorResolver}setRuleModules(e){this.aiHandler.setRuleModules(e)}setMigrationServices(e){this.migrationHandler.setFileReader(e)}setPipelineMarketplace(e){this.automationHandler.setPipelineMarketplace(e)}setAutopilotOrchestrator(e){this.autopilotHandler.setOrchestrator(e)}setForgeOrchestrator(e,t){this.forgeHandler.setForgeOrchestrator(e,t)}registerAll(e){let t=(r,n)=>{for(let o of r)e.route(o,async i=>{await n.handle(i)})};t(["org:list","org:connect","org:connect:cancel","org:disconnect","org:select","org:update","org:open-in-browser","org:cli-status"],this.orgHandler),t(["settings:get","settings:update","telemetry:status","telemetry:toggle"],this.settingsHandler),t(["i18n:locale"],this.i18nHandler),t(["seed:execute","seed:automation","seed:describe-global","seed:describe-object","seed:template:save","seed:template:load","seed:template:list","seed:template:delete","seed:list-personas","seed:create-persona","seed:scenario:packs","seed:scenario:prepare","seed:scenario:execute","seed:scenario:agents","seed:scenario:save","seed:scenario:test-file"],this.seedHandler),t(["seed:clone:describe-source","seed:clone:preview","seed:clone:execute"],this.seedCloneHandler),t(["seed:csv:validate","seed:csv:execute"],this.seedCsvHandler),t(["sync:execute","sync:simulate","sync:write-order","sync:pause","sync:resume","sync:describe-global","sync:describe-fields","sync:config:save","sync:config:load","sync:config:list","sync:config:delete","sync:config:reset-delta"],this.syncHandler),t(["sync:history:list","sync:history:detail","sync:history:rerun","sync:history:export"],this.syncHistoryHandler),t(["sync:removal:info","sync:removal:list","sync:remove","sync:remove:sweep","sync:remove:automation","sync:earlier-copies"],this.syncRemovalHandler),t(["seed:removal:info","seed:removal:list","seed:remove","seed:remove:sweep","seed:open-record"],this.seedRemovalHandler),t(["sync:schedule:list","sync:schedule:upsert","sync:schedule:toggle","sync:schedule:delete"],this.syncScheduleHandler),t(["quicksync:suggest-objects","quicksync:detect-relationships","quicksync:preview","quicksync:execute"],this.quickSyncHandler),t(["monitor:refresh","monitor:open-apex-jobs","monitor:live-operations","monitor:storage","monitor:deployments","monitor:api-usage","monitor:error-logs","monitor:sessions","monitor:apex-insights","monitor:sandbox-refresh","monitor:alerts","monitor:alert:acknowledge","monitor:alert:dismiss"],this.monitorHandler),t(["governance:policies:list","governance:policy:save","governance:policy:delete","governance:evaluate","governance:templates"],this.governanceHandler),t(["compare:execute","compare:permissions","compare:snapshots","compare:drift","compare:validate-deployment","compare:deploy"],this.compareHandler),t(["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"],this.dataOpsHandler),t(["dataops:pii-inventory","dataops:dsr:search","dataops:dsr:export","dataops:dsr:erase","dataops:dsr:log"],this.complianceHandler),t(["dataops:cleanup:scan","dataops:cleanup:export","dataops:cleanup:delete"],this.cleanupHandler),t(["dataops:empty:scope","dataops:empty:preview","dataops:empty:run","dataops:empty:cancel","dataops:empty:undo"],this.emptyHandler),t(["pipeline:execute","pipeline:templates","pipeline:list","pipeline:history","pipeline:save","pipeline:delete","pipeline:approval","pipeline:sync-configs","pipeline:seed-templates","pipeline:masking-templates","pipeline:rewind-steps","pipeline:rewind-grant","pipeline:rewind-revoke","marketplace:list","marketplace:install"],this.automationHandler),t(["ai:chat","ai:chat:cancel","ai:conversation:create","ai:conversation:load","ai:conversation:list","ai:conversation:delete","ai:conversation:delete-all","ai:status","ai:save-key","ai:settings","ai:remove-key","ai:tool:cancel","ai:forge-plan","ai:anomaly-scan","ai:generate-pipeline","ai:scenario-draft"],this.aiHandler),t(["autopilot:list-objects","autopilot:count-objects","autopilot:scan-schema","autopilot:generate-plan","autopilot:fit-plan","autopilot:fit-undo","autopilot:execute","autopilot:pause","autopilot:resume","autopilot:skip-node","autopilot:compliance-report"],this.autopilotHandler),t(["forge:preview","forge:discover","forge:execute","forge:pause","forge:resume","forge:abort","forge:templates:list","forge:templates:save","forge:templates:delete","forge:history:list","forge:undo","forge:resume-run","forge:open-record","forge:verify:request","forge:export-ids:request","forge:plan:request","forge:compliance:request","forge:metadata-diff:request","forge:rehearse:request","forge:automation:request","forge:undo-automation:request","forge:undo-sweep:request","forge:gaps:request","forge:users:request","forge:target-records:request","forge:sample-budget:request"],this.forgeHandler),t(["frozen:config:get","frozen:config:save","frozen:select","frozen:extract","frozen:manifest:get","frozen:load","frozen:load:preview","frozen:verify","frozen:remove","frozen:remove:sweep","frozen:remove:automation","frozen:remove:preview","frozen:status","frozen:rules:clear","frozen:rules:create"],this.frozenHandler),t(["checkpoint:list","checkpoint:scope","checkpoint:take","checkpoint:preview","checkpoint:plan-selection","checkpoint:rewind","checkpoint:undo","checkpoint:delete","checkpoint:keep","checkpoint:rename","checkpoint:ignore-fields","checkpoint:rewinds","checkpoint:export","checkpoint:import-read","checkpoint:import"],this.checkpointHandler),t(["migration:pick-file","migration:import-sfdmu","migration:save-sync-config"],this.migrationHandler),t(["config:export","config:import","config:categories","config:validate"],this.configHandler),t(["smart-action:analyze"],this.smartActionHandler),t(["file:save"],this.fileHandler),t(["reports:list","reports:audit","reports:lineage"],this.reportsHandler),this.executionHandler&&t(["execution:abort"],this.executionHandler),t(["realtime:objects","realtime:start","realtime:stop","realtime:status","realtime:metrics","realtime:resolve-conflict"],this.realtimeHandler),e.route("panel:route",r=>{this.panelRouteListener?.(r)}),e.route("panel:reload",r=>{this.panelReloadListener?.(r)}),e.route("workbench:reload",()=>{this.executeCommand("workbench.action.reloadWindow")}),e.route("workbench:open-setting",r=>{let n=wM.safeParse(r.payload);if(!n.success){this.handlerDeps.log("[WARN] workbench:open-setting: not a SandForge setting id");return}this.executeCommand("workbench.action.openSettings",n.data.setting)}),e.route("error:boundary",r=>{let{payload:n}=r;this.handlerDeps.log(`[ERR] Webview crash (error:boundary): ${n?.message??"unknown error"}`+(n?.stack?`
13
+ ${n.stack}`:""))})}nextId(){return`ext-${++this.idCounter}`}};var yc=class{maxActions;windowMs;nowFn;timestamps=[];constructor(e,t,r=Date.now){this.maxActions=Math.max(1,e),this.windowMs=Math.max(100,t),this.nowFn=r}tryAcquire(){let e=this.nowFn();return this.pruneExpired(e),this.timestamps.length>=this.maxActions?!1:(this.timestamps.push(e),!0)}get remaining(){return this.pruneExpired(this.nowFn()),Math.max(0,this.maxActions-this.timestamps.length)}reset(){this.timestamps=[]}pruneExpired(e){let t=e-this.windowMs,r=0;for(;r<this.timestamps.length&&this.timestamps[r]<=t;)r++;r>0&&(this.timestamps=this.timestamps.slice(r))}};var bM=100,RM=1e3,vM=3,SM=1e3;function kM(s){return typeof s=="object"&&s!==null&&"protocolVersion"in s&&"payload"in s&&typeof s.payload=="object"}var VO=500;function OM(s){let e=s.map(t=>`${t.path.map(String).join(".")}: ${t.message}`).join("; ");return e.length<=VO?e:`${e.slice(0,VO)}\u2026(+${s.length} issues)`}var bc=class{handlers=new Map;panels=new Set;rateLimiter;telemetry;fixSuggestionNotifier;mismatchCount=0;webviewSeen=!1;firstWebviewCallbacks=[];senders=new Map;constructor(e){this.rateLimiter=new yc(e?.rateLimitMax??bM,e?.rateLimitWindowMs??RM),this.telemetry=e?.telemetry,this.fixSuggestionNotifier=e?.showFixSuggestion}registerPanel(e,{inbound:t=!0}={}){this.panels.add(e);let r=t?e.webview.onDidReceiveMessage(n=>{this.dispatch(n,e)}):void 0;if(!this.webviewSeen){this.webviewSeen=!0;for(let n of this.firstWebviewCallbacks.splice(0))this.runFirstWebview(n)}return{dispose:()=>{this.panels.delete(e),r?.dispose();for(let[n,o]of this.senders)o===e&&this.senders.delete(n)}}}onFirstWebview(e){if(this.webviewSeen){this.runFirstWebview(e);return}this.firstWebviewCallbacks.push(e)}runFirstWebview(e){try{e()}catch(t){this.logError("first webview",t)}}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>{this.handlers.get(e)?.delete(t)}}postToWebview(e){for(let t of this.panels)t.webview.postMessage(e)}replyToRequester(e){let t=typeof e.correlationId=="string"?this.senders.get(e.correlationId):void 0;if(t&&this.panels.has(t)){t.webview.postMessage(e);return}this.postToWebview(e)}get panelCount(){return this.panels.size}showFixSuggestion(e){this.fixSuggestionNotifier?.(e)}dispose(){this.handlers.clear(),this.panels.clear(),this.firstWebviewCallbacks=[],this.senders.clear()}logFn;setLogFunction(e){this.logFn=e}logError(e,t){let r=T(t);this.logFn?.(`[MessageBroker] Handler error for "${e}": ${r}`)}warn(e,t){try{this.telemetry?.addBreadcrumb(e,"bridge","warning"),this.telemetry?.getLogger?.()?.warn?.(t??{},e)}catch{}}dispatch(e,t){if(!kM(e)){this.logFn?.("[MessageBroker] Received malformed message: not an envelope");return}let r=Ip.safeParse(e);if(!r.success){let o=OM(r.error.issues);this.logFn?.(`[MessageBroker] Invalid enveloped payload: ${o}`),this.warn("bridge invalid payload",{issues:o});let i=e.payload,a=typeof i?.id=="string"?i.id:void 0;this.postBridgeError("invalid-payload",o,a);return}let n=r.data;Rp(n.protocolVersion)?this.mismatchCount=0:(this.mismatchCount++,this.warn("bridge protocol mismatch",{serverVersion:1,clientVersion:n.protocolVersion,count:this.mismatchCount}),this.postBridgeMismatch(n.protocolVersion),this.mismatchCount>=vM&&this.postBridgeReloadBanner()),t&&this.rememberSender(n.payload.id,t),this.continueDispatch(n.payload)}rememberSender(e,t){if(this.senders.delete(e),this.senders.set(e,t),this.senders.size>SM){let r=this.senders.keys().next().value;r!==void 0&&this.senders.delete(r)}}continueDispatch(e){if(!this.rateLimiter.tryAcquire()){this.logFn?.(`[MessageBroker] Rate limited: dropping message of type "${e.type}"`),this.postBridgeError("rate-limited",`"${e.type}" was dropped`,e.id);return}let t=this.handlers.get(e.type);if(!t){this.logFn?.(`[MessageBroker] Unhandled message type: "${e.type}"`),this.postBridgeError("unhandled-type",`no handler for "${e.type}"`,e.id);return}for(let r of t)try{let n=r(e);n&&typeof n.catch=="function"&&n.catch(o=>{this.logError(e.type,o)})}catch(n){this.logError(e.type,n)}}nextControlId(){return`bridge-${globalThis.crypto.randomUUID()}`}postBridgeError(e,t,r){this.postToWebview({id:this.nextControlId(),type:"bridge:error",timestamp:Date.now(),...r?{correlationId:r}:{},payload:{reason:e,details:t}})}postBridgeMismatch(e){this.postToWebview({id:this.nextControlId(),type:"bridge:protocol-mismatch",timestamp:Date.now(),payload:{serverVersion:1,clientVersion:e}})}postBridgeReloadBanner(){this.postToWebview({id:this.nextControlId(),type:"bridge:reload-banner",timestamp:Date.now(),payload:{reason:"protocol-mismatch"}})}};var Rc=class{constructor(e){this.broker=e}broker;disposers=[];route(e,t){let r=this.broker.on(e,n=>t(Object.freeze(n)));this.disposers.push(r)}routePrefix(e,t,r){for(let n of t)n.startsWith(e)&&this.route(n,r)}routeAll(e){for(let[t,r]of Object.entries(e))this.route(t,r)}get routeCount(){return this.disposers.length}dispose(){for(let e of this.disposers)e();this.disposers=[]}};var vc=class{constructor(e){this.broker=e}broker;state={orgs:[],settings:{},activeOperations:[],extensionReady:!1,selectedOrgId:null};idCounter=0;pushTimer;disposed=!1;updateState(e){this.state={...this.state,...e},!this.pushTimer&&!this.disposed&&(this.pushTimer=setTimeout(()=>{this.pushTimer=void 0,this.pushState()},16))}setActiveOperations(e){this.updateState({activeOperations:e})}getState(){return this.state}pushState(){let e={id:`state-sync-${++this.idCounter}`,type:"state:sync",timestamp:Date.now(),payload:{...this.state}};this.broker.postToWebview(e)}dispose(){this.disposed=!0,this.pushTimer&&(clearTimeout(this.pushTimer),this.pushTimer=void 0)}reset(){this.pushTimer&&(clearTimeout(this.pushTimer),this.pushTimer=void 0),this.state={orgs:[],settings:{},activeOperations:[],extensionReady:!1,selectedOrgId:null}}};var Sc=class{storage;prefix;logWarning;constructor(e,t="sandforge",r){this.storage=e,this.prefix=t,this.logWarning=r}async storeSecret(e,t){await this.storage.store(this.prefixKey(e),t)}async getSecret(e){return this.storage.get(this.prefixKey(e))}async deleteSecret(e){await this.storage.delete(this.prefixKey(e))}async storeObject(e,t){await this.storeSecret(e,JSON.stringify(t))}async getObject(e){let t=await this.getSecret(e);if(t)try{return JSON.parse(t)}catch(r){let n=T(r);this.logWarning?.(`[SecretVault] Failed to parse JSON for key "${e}": ${n}`);return}}async hasSecret(e){return await this.storage.get(this.prefixKey(e))!==void 0}prefixKey(e){return`${this.prefix}.${e}`}};var kc=class{orgs=new Map;listeners=new Set;onOrgChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}offOrgChange(e){this.listeners.delete(e)}emit(e){for(let t of this.listeners)try{t(e)}catch(r){se.warn("OrgManager listener threw",{error:T(r)})}}addOrg(e){let t=this.orgs.has(e.id);this.orgs.set(e.id,e),this.emit({type:t?"updated":"added",orgId:e.id,org:e})}removeOrg(e){let t=this.orgs.delete(e);return t&&this.emit({type:"removed",orgId:e}),t}getOrg(e){return this.orgs.get(e)}getAllOrgs(){return Array.from(this.orgs.values())}updateStatus(e,t){let r=this.orgs.get(e);if(!r)return!1;let n={...r,status:t};return this.orgs.set(e,n),this.emit({type:"statusChanged",orgId:e,org:n}),!0}findByTag(e){return this.getAllOrgs().filter(t=>t.tags.includes(e))}get connectedCount(){return this.getAllOrgs().filter(e=>e.status==="connected").length}clear(){let e=Array.from(this.orgs.keys());this.orgs.clear();for(let t of e)this.emit({type:"removed",orgId:t})}dispose(){this.listeners.clear(),this.orgs.clear()}};var Lo="org.",Oc="org-cred.",up="orgs",XO=1e4;function IM(s){let e={...s,tags:Array.isArray(s.tags)?s.tags:[],appearance:{color:s.appearance?.color??"#4a9eff",icon:s.appearance?.icon??"cloud",position:s.appearance?.position??0}};return AM(e)}function AM(s){if(s.orgType===Vp(s.orgType,s.metadata?.edition))return s;let{safetyTier:e,color:t}=kr("Developer");return{...s,orgType:"Developer",safetyTier:e,appearance:{...s.appearance,color:s.appearance.color===Hc?t:s.appearance.color}}}var Ic=class{constructor(e,t,r){this.configStore=e;this.secretVault=t;this.orgManager=r}configStore;secretVault;orgManager;loadAll(){let e=this.configStore.getByCategory(up),t=new Map,r=[];for(let[n,o]of Object.entries(e)){if(!n.startsWith(Lo))continue;let i=IM(o),a=i.orgId??i.id,d=n.slice(Lo.length),c=t.get(a);if(!c){t.set(a,{key:n,org:i});continue}d===a?(r.push(c.key),t.set(a,{key:n,org:i})):r.push(n)}for(let n of r){this.configStore.delete(n);let o=n.slice(Lo.length);this.secretVault.deleteSecret(`${Oc}${o}`).catch(()=>{}),this.orgManager.removeOrg(o),se.warn("Pruned duplicate org entry (same orgId as a canonical entry)",{key:n})}for(let{org:n}of t.values())this.orgManager.addOrg(n)}async saveOrg(e,t){let r=`${Lo}${e.id}`,n=this.configStore.get(r),i=n!==void 0&&Ee(n)==="production"&&Yn(e)&&n.appearance?.color===Hc?void 0:n?.appearance?.color,a=n?{...e,alias:n.alias??e.alias,appearance:{...e.appearance,color:i??e.appearance.color,icon:n.appearance?.icon??e.appearance.icon},tags:n.tags??e.tags,...n.staging!==void 0?{staging:n.staging}:{},...e.organizationName===void 0&&n.organizationName!==void 0?{organizationName:n.organizationName}:{}}:e;this.configStore.set(r,a,up),this.orgManager.addOrg(a),t&&await this.secretVault.storeObject(`${Oc}${e.id}`,t)}async removeOrg(e){this.configStore.delete(`${Lo}${e}`),await this.secretVault.deleteSecret(`${Oc}${e}`),this.orgManager.removeOrg(e)}async getCredentials(e){let t=this.secretVault.getObject(`${Oc}${e}`);t.catch(()=>{});let r;try{return await Promise.race([t,new Promise((n,o)=>{r=setTimeout(()=>{o(new Error(`Secret storage did not answer within ${XO} ms for org "${e}" \u2014 the OS keyring may be locked or unavailable.`))},XO)})])}finally{r!==void 0&&clearTimeout(r)}}updateOrgMetadata(e){this.configStore.set(`${Lo}${e.id}`,e,up),this.orgManager.addOrg(e)}};import{mkdtemp as TM,readFile as EM,rm as PM}from"node:fs/promises";import{tmpdir as CM}from"node:os";import{join as pp}from"node:path";async function KO(s){let e=await TM(pp(CM(),"sandforge-sf-"));try{let t={stdout:pp(e,"stdout.json"),stderr:pp(e,"stderr.txt")},r;try{await s(t)}catch(o){r=o}let n=o=>EM(o,"utf8").catch(()=>"");return{stdout:await n(t.stdout),stderr:await n(t.stderr),...r!==void 0?{failure:r}:{}}}finally{await PM(e,{recursive:!0,force:!0}).catch(()=>{})}}var eI=10*1024*1024,DM=3e4,Ac=3e4,mp=6e4,YO=12e4,QO=3e4,xM=4,MM=2e3,jM=/["%!\u0000-\u001f\u007f]/,ZO=/^[A-Za-z0-9._-]+={0,2}$/;async function yp(s,e){let{exec:t}=await import("child_process"),{promisify:r}=await import("util"),n=await r(t)(s,{maxBuffer:eI,windowsHide:!0,env:Jc(),...e});return{stdout:String(n.stdout),stderr:String(n.stderr)}}function tI(s,e){if(jM.test(s))throw new Error(`The ${e} cannot contain ", %, ! or control characters on Windows: the command prompt that runs sf would act on them.`);return`"${s}"`}async function Tc(s,e){let{exec:t,execFile:r}=await import("child_process");return new Promise(n=>{let o={encoding:"utf8",maxBuffer:eI,windowsHide:!0,timeout:e.timeoutMs,env:Jc()},i={},a=!1,d=u=>{a||(a=!0,clearTimeout(i.timer),n(u))},c=(u,p,g)=>{d({stdout:String(p),stderr:String(g),...u?{failure:{message:u.message,killed:u.killed}}:{}})},l=process.platform==="win32"?t(["sf",...s.map(u=>tI(u.value,u.role))].join(" "),o,c):r("sf",s.map(u=>u.value),o,c);i.timer=setTimeout(()=>{d({stdout:"",stderr:"",failure:{message:`sf did not finish within ${Math.round(e.timeoutMs/1e3)} s`,killed:!0}}),process.platform==="win32"&&l.pid!==void 0&&r("taskkill",["/pid",String(l.pid),"/T","/F"],{windowsHide:!0},()=>{})},e.timeoutMs+MM),l.stdin?.once("error",()=>{}),l.stdin?.end(e.input??"")})}var NM=G({status:Me().optional(),result:Vn().optional(),message:L().optional(),name:L().optional()}).loose();function rI(s){try{let e=NM.safeParse(JSON.parse(oI(s.stdout)));return e.success?e.data:void 0}catch{return}}function nI(s,e,t,r){let n=e?.message?.trim();if(n)return new Error(n);if(s.failure?.killed)return new Error(`${t} did not finish within ${r/1e3} s.`);let o=s.stderr.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0);return new Error(o??s.failure?.message??`${t} failed without saying why.`)}var $M=G({id:L().min(1),username:L().min(1),instanceUrl:L().min(1),accessToken:L().nullish(),alias:L().nullish(),connectedStatus:L().nullish(),apiVersion:L().nullish(),devHubId:L().nullish(),status:L().nullish(),expirationDate:L().nullish(),edition:L().nullish()}).loose(),LM=G({username:L().min(1),orgId:L().min(1),instanceUrl:L().min(1)}).loose();function gp(s,e,t=mp){let r=rI(s);if(s.failure||r?.status!==0)throw nI(s,r,e,t);let n=LM.safeParse(r.result);if(!n.success)throw new Error(`${e} succeeded but did not say which org it signed in to.`);return{username:n.data.username,orgId:n.data.orgId,instanceUrl:n.data.instanceUrl}}function fp(s){let e=si(s);if(!e.ok)throw new Error(`Invalid instanceUrl: "${s}" \u2014 expected an https:// Salesforce login host with no path (${e.reason})`);return e.origin}function oI(s){let e=s.replace(/\u001b\[[0-9;]*m/g,""),t=e.search(/[{[]/);if(t===-1)throw new Error(`No JSON found in output (${s.length} chars): ${s.slice(0,200)}`);return e.slice(t)}function FM(s){if(/['\u0000-\u001f\u007f]/.test(s))throw new Error("The temporary folder path cannot contain a quote or control characters: the shell that runs sf would act on them.");return`'${s}'`}function _M(s,e){let t=s;return t.killed===!0?`its ${e/1e3} s limit`:typeof t.code=="number"?`exit code ${t.code}`:Vc(T(s))??"an error that says nothing"}async function UM(s,e){let t=Date.now(),r=o=>process.platform==="win32"?tI(o,"temporary folder path"):FM(o),n=!1;try{let o=await KO(async a=>{let d=`${s} > ${r(a.stdout)} 2> ${r(a.stderr)}`;n=!0,await yp(d,{timeout:e})}),i=o.failure===void 0?void 0:n?_M(o.failure,e):T(o.failure);return{ran:n,stdout:o.stdout,stderr:o.stderr,ms:Date.now()-t,...i?{failure:Xo(i)}:{}}}catch(o){return{ran:n,stdout:"",stderr:"",ms:Date.now()-t,failure:Xo(T(o))}}}function sI(s){if(!s.ran)return`could not be made (${(s.failure??"").slice(0,200)})`;let e=Pc(s.stderr);return`ended with ${s.failure??"exit code 0"} after ${wp(s.ms)} s, with ${s.stdout.length} chars in its stdout file and ${s.stderr.length} in its stderr file${e?` ("${e}")`:""}`}function Pc(s){let e=Vc(s);return e===void 0?void 0:Xo(e).slice(0,200)}function wp(s){return(s/1e3).toFixed(1)}function iI(s,e){return s.ms>=e-500}function HM(s,e,t,r,n){let o=Pc(s.stderr),i=a=>a.length>0?a.join(" | "):"none";return[`first run: ${wp(s.ms)} s of the ${n/1e3} s allowed`+(iI(s,n)?" (it reached the limit)":"")+`, exit code 0, stdout ${s.stdout.length} chars, stderr ${s.stderr.length} chars`+(o?` ("${o}")`:""),`run with its output sent to files: ${sI(e)}`,t.failure?`the search for sf could not run: ${t.failure}`:`sf found: ${i(t.sf)}; node found: ${i(t.node)}`,`sf --version: ${r===void 0?"not run":r===""?"printed nothing":`"${r}"`}`,`sf runs from: ${Xo(process.cwd())}`,`variables ${bg()}`].join("; ")}function BM(s,e,t,r,n){let o=Pc(s.stderr),i=process.platform==="win32"?"where.exe sf":"which -a sf",a=new Set(t.sf.map(l=>l.replace(/[\\/][^\\/]*$/,""))).size,d=t.runs?`This window runs ${t.runs}${a>1?` (sf is found in ${a} folders of its PATH)`:""}`:t.failure?`${i} could not run in this window (${t.failure.slice(0,200)})`:`${i} finds no sf this window can run`,c=r===void 0?"":r===""?", and its sf --version printed nothing either":`, and its sf --version says ${r}`;return`sf org list --json ended without an error and printed nothing${o?` (it said: ${o})`:""}, so there are no orgs to read. It ran ${wp(s.ms)} s${iI(s,n)?`, its ${n/1e3} s limit,`:""} and exited with code 0. Run again with its output sent to a file, it ${sI(e)}. ${d}${c}. In a terminal of this window, run sf org list --json and ${i}: another first line there means VS Code runs another sf than the terminal. Details in View > Output > SandForge.`}function hp(s){return s.connectedStatus!==void 0?s.connectedStatus==="Connected":s.isScratch===!0&&s.status==="Active"&&s.isExpired!==!0}function qM(s){return s.connectedStatus!==void 0?`the CLI reports ${s.connectedStatus}`:s.isScratch===!0&&(s.isExpired===!0||s.status==="Expired")?s.expirationDate?`a scratch org that expired on ${s.expirationDate}`:"a scratch org that expired":s.isScratch===!0?`a scratch org its Dev Hub reports ${s.status??"without a status"}`:"the CLI did not say it is connected"}async function WM(s){let{jsforce:e}=await import("./chunk-GAM726CK.mjs"),t=new e.Connection({instanceUrl:s.instanceUrl,accessToken:s.accessToken,...s.apiVersion?{version:s.apiVersion}:{}});return Qn(t)}async function zM(s,e){let t=new Array(s.length),r=0,n=async()=>{for(;r<s.length;){let o=r++;t[o]=await s[o]()}};return await Promise.all(Array.from({length:Math.min(e,s.length)},n)),t}var Ec=class{constructor(e=kg,t=WM){this.readToken=e;this.readKind=t}readToken;readKind;versionAnswer;async isCliAvailable(){try{let{stdout:e}=await yp("sf --version",{timeout:DM});return this.versionAnswer=Pc(e)??"",!0}catch{return!1}}async listOrgs(e){let t=await this.readOrgEntries(),r=this.dedupeByOrgId(t.filter(a=>hp(a))),n=new Set(r.map(a=>a.orgId));for(let a of this.dedupeByOrgId(t.filter(d=>!hp(d))))n.has(a.orgId)||e?.({username:a.username,...a.alias?{alias:a.alias}:{},orgId:a.orgId,reason:qM(a),why:"notConnected"});let o=await zM(r.map(a=>async()=>{try{return{entry:await this.withUsableToken(a)}}catch(d){return{entry:a,reason:T(d)}}}),xM),i=[];for(let{entry:a,reason:d}of o)d===void 0?i.push(this.mapToSalesforceOrg(a)):e?.({username:a.username,alias:a.alias,orgId:a.orgId,reason:d});return i}async findOrg(e){let t=await this.displayOrg(e);if(!t||!hp(t))return;let r;try{r=await this.withUsableToken(t)}catch(n){throw new Error(`The Salesforce CLI gave no access token for ${t.username}: ${T(n)}`)}return this.mapToSalesforceOrg(await this.typedByTheOrg(r))}async displayOrg(e){if(!/^[\w.@+-]+$/.test(e)||e.startsWith("-"))throw new Error(`Invalid username format: "${e}"`);let t=await Tc([{value:"org",role:"command"},{value:"display",role:"command"},{value:"--target-org",role:"flag"},{value:e,role:"username"},{value:"--json",role:"flag"}],{timeoutMs:QO}),r=rI(t);if(r?.name==="NamedOrgNotFoundError")return;if(t.failure||r?.status!==0)throw nI(t,r,"sf org display",QO);let n=$M.safeParse(r.result);if(!n.success)throw new Error("sf org display succeeded but did not say which org it shows.");let o=n.data,i=typeof o.devHubId=="string"&&o.devHubId!=="";return{orgId:o.id,username:o.username,instanceUrl:o.instanceUrl,...o.alias?{alias:o.alias}:{},...o.accessToken?{accessToken:o.accessToken}:{},...o.connectedStatus?{connectedStatus:o.connectedStatus}:{},...o.apiVersion?{instanceApiVersion:o.apiVersion}:{},...i?{isScratch:!0}:{},...i&&o.status?{status:o.status}:{},...i&&o.expirationDate?{expirationDate:o.expirationDate}:{},...i&&o.edition?{orgEdition:o.edition}:{}}}async typedByTheOrg(e){if(e.isScratch===!0||e.accessToken===void 0)return e;try{let t=await this.readKind({instanceUrl:e.instanceUrl,accessToken:e.accessToken,...e.instanceApiVersion?{apiVersion:e.instanceApiVersion}:{}});return{...e,isSandbox:t.sandbox,...t.edition?{orgEdition:t.edition}:{}}}catch{return e}}async loginJwt(e){let t=[{value:"org",role:"command"},{value:"login",role:"command"},{value:"jwt",role:"command"},{value:"--username",role:"flag"},{value:e.username,role:"username"},{value:"--jwt-key-file",role:"flag"},{value:e.keyFile,role:"private key file path"},{value:"--client-id",role:"flag"},{value:e.clientId,role:"consumer key"},{value:"--instance-url",role:"flag"},{value:fp(e.loginUrl),role:"login URL"}];return e.alias&&t.push({value:"--alias",role:"flag"},{value:e.alias,role:"alias"}),t.push({value:"--json",role:"flag"}),gp(await Tc(t,{timeoutMs:mp}),"sf org login jwt")}async loginWithRefreshToken(e){if(!ZO.test(e.clientId))throw new Error("The consumer key holds characters the Salesforce CLI does not accept.");if(!ZO.test(e.refreshToken))throw new Error("Salesforce issued a refresh token the Salesforce CLI cannot store (unexpected characters).");let t=new URL(fp(e.instanceUrl)).host,r=[{value:"org",role:"command"},{value:"login",role:"command"},{value:"sfdx-url",role:"command"}];e.alias&&r.push({value:"--alias",role:"flag"},{value:e.alias,role:"alias"}),r.push({value:"--json",role:"flag"},{value:"--sfdx-url-stdin",role:"flag"});let n=`force://${e.clientId}::${e.refreshToken}@${t}
14
+ `;return gp(await Tc(r,{timeoutMs:mp,input:n}),"sf org login sfdx-url")}async readOrgEntries(){let e="sf org list --json",t=Date.now(),r,n="";try{let a=await yp(e,{timeout:Ac});r=a.stdout,n=a.stderr}catch(a){let d=a;if(r=String(d.stdout??""),!r)throw new Error(`SF CLI failed with no output: ${d.message}`)}r.trim()===""&&(r=await this.rereadBlankOrgList(e,{ms:Date.now()-t,stdout:r,stderr:n}));let o=oI(r),i;try{i=JSON.parse(o)}catch(a){throw new Error(`Failed to parse SF CLI JSON: ${a instanceof Error?a.message:a}. Output starts with: ${r.slice(0,300)}`)}return[...i.result?.nonScratchOrgs??[],...i.result?.scratchOrgs??[],...i.result?.sandboxes??[],...i.result?.other??[],...i.result?.devHubs??[]]}async rereadBlankOrgList(e,t){let r=await UM(e,Ac),n=await Rg(),o=HM(t,r,n,this.versionAnswer,Ac);if(r.stdout.trim()!=="")return se.warn(`${e} printed nothing on its pipe; what it wrote to a file was read instead. ${o}`),r.stdout;throw se.warn(`${e} printed nothing, on its pipe or to a file. ${o}`),new Error(BM(t,r,n,this.versionAnswer,Ac))}async loginWeb(e,t){if(e&&!/^[\w.-]+$/.test(e))throw new Error(`Invalid alias format: "${e}"`);let r=[{value:"org",role:"command"},{value:"login",role:"command"},{value:"web",role:"command"},{value:"--instance-url",role:"flag"},{value:fp(t),role:"login URL"}];return e&&r.push({value:"--alias",role:"flag"},{value:e,role:"alias"}),r.push({value:"--json",role:"flag"}),gp(await Tc(r,{timeoutMs:YO}),"sf org login web",YO)}dedupeByOrgId(e){let t=new Map;for(let r of e)r.orgId&&!t.has(r.orgId)&&t.set(r.orgId,r);return Array.from(t.values())}async withUsableToken(e){if(Xc(e.accessToken))return e;let t=await this.readToken(e.username);if(!Xc(t.accessToken))throw new Error("the Salesforce CLI showed no usable access token");return{...e,accessToken:t.accessToken,instanceUrl:t.instanceUrl??e.instanceUrl}}mapToSalesforceOrg(e){let t=vn({isScratch:e.isScratch,isSandbox:e.isSandbox,edition:e.orgEdition}),{safetyTier:r,color:n}=kr(t),o={id:e.orgId,alias:e.alias||e.username,username:e.username,...typeof e.name=="string"&&e.name.trim()!==""?{organizationName:e.name.trim()}:{},instanceUrl:e.instanceUrl,orgId:e.orgId,orgType:t,authMethod:"sfdx_import",safetyTier:r,appearance:{color:n,icon:"cloud",position:0},metadata:{apiVersion:e.instanceApiVersion??Xn.DEFAULT_API_VERSION,edition:e.orgEdition??"",features:[],...t==="Scratch"&&e.expirationDate?{expirationDate:e.expirationDate}:{}},status:"connected",lastConnected:new Date().toISOString(),tags:[]},i={loginUrl:e.instanceUrl,accessToken:e.accessToken,instanceUrl:e.instanceUrl,username:e.username};return{org:o,credentials:i}}};function GM(s,e){return e?new Promise((t,r)=>{let n=()=>r(e.reason);e.aborted?n():e.addEventListener("abort",n,{once:!0}),s.then(o=>{e.removeEventListener("abort",n),t(o)},o=>{e.removeEventListener("abort",n),r(o)})}):s}var Cc=class{deps;results=new Map;constructor(e){this.deps=e}async execute(e,t){let r=Date.now(),{items:n,managedLeftOut:o}=await GM(this.deps.metadataCompare.compare(e.sourceOrgId,e.targetOrgId,e.componentTypes,{includeManaged:e.includeManaged},t),t),i=this.deps.diffEngine.computeSummary(n),a=this.deps.diffEngine.computeCoverage(n,this.deps.metadataCompare.budget,o),d=Date.now()-r,c={configId:e.id,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,mode:e.mode,summary:i,content:a,diffs:n,timestamp:new Date().toISOString(),duration:d};return this.results.set(e.id,c),c}getLastResult(e){return this.results.get(e)}};function JM(){return globalThis.crypto.randomUUID()}function aI(s){return{stepId:s.id,stepName:s.name,stepType:s.type,status:"skipped"}}function VM(s,e){let t={};for(let r of s.variables)r.defaultValue!==void 0&&(t[r.name]=r.defaultValue);return{...t,...e}}function XM(s){if(s.status!=="completed")return{};let e=s.output?.variables;return typeof e!="object"||e===null||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(t=>typeof t[1]=="string"))}function dI(s){return`Validation failed: ${s.join(", ")}`}function KM(s,e,t){let r=[["success",s.onSuccess],["failure",s.onFailure]];for(let[n,o]of r){if(!o)continue;let i=t.findIndex(d=>d.id===o);if(i>e)continue;let a=i===-1?`"${o}", which is not a step of this pipeline`:`"${t[i].name}", which does not come after it`;return`Step "${s.name}" routes on ${n} to ${a}: a route can only skip ahead.`}}var Dc=class{deps;activeRuns=new Map;handlers=new Map;cancelledRuns=new Set;aborters=new Map;constructor(e){this.deps=e}async execute(e,t,r,n){let o=this.deps.builder.validate(e);if(o.length>0){let f=this.createRun(e,t,r);return f.status="failed",f.error=dI(o),f.endTime=new Date().toISOString(),this.emit("failed",{runId:f.id,error:f.error}),f}let i=this.refuseUnrunnable(e,t,r);if(i)return i;let a=this.createRun(e,t,r);a.status="running",this.activeRuns.set(a.id,a);let d=new AbortController,c=()=>d.abort();n?.aborted&&d.abort(),n?.addEventListener("abort",c,{once:!0}),this.aborters.set(a.id,d),this.emit("started",{runId:a.id,pipelineId:e.id});let l=VM(e,t),{steps:u}=e,p=this.deps.conditionalRouter,g=!1,h=0;for(;h<u.length;){if(this.cancelledRuns.has(a.id)||d.signal.aborted){a.status="cancelled";break}let f=u[h],m=await this.runStep(f,a,l,d.signal);if(a.stepResults.push(m),m.status==="skipped"){this.emit("stepSkipped",{runId:a.id,stepResult:m}),h+=1;continue}if(this.emit("stepCompleted",{runId:a.id,stepResult:m}),Object.assign(l,XM(m)),l[sg]=m.status==="completed"?"succeeded":"failed",d.signal.aborted||m.status==="stopped"){a.status="cancelled";break}if(m.status==="failed"&&(g=!0,!f.continueOnError)){a.status="failed",a.error=m.error;break}let y=h+1;if(p.endsRun(f,m))y=u.length;else{let w=p.getNextStep(f,m),v=w?u.findIndex((R,b)=>b>h&&R.id===w):-1;v!==-1&&(y=v)}for(let w of u.slice(h+1,y)){let v=aI(w);a.stepResults.push(v),this.emit("stepSkipped",{runId:a.id,stepResult:v})}h=y}return a.status==="running"&&(a.status=g?"completed_with_warnings":"completed"),a.endTime=new Date().toISOString(),a.duration=new Date(a.endTime).getTime()-new Date(a.startTime).getTime(),n?.removeEventListener("abort",c),this.aborters.delete(a.id),this.activeRuns.delete(a.id),this.cancelledRuns.delete(a.id),this.deps.history.record(a),a.status==="failed"?this.emit("failed",{runId:a.id,error:a.error}):this.emit("completed",{runId:a.id,status:a.status}),a}cancel(e){if(this.activeRuns.has(e)){this.cancelledRuns.add(e),this.aborters.get(e)?.abort();let t=this.activeRuns.get(e);t&&(t.status="cancelled")}}getRun(e){return this.activeRuns.get(e)??this.deps.history.getRun(e)}getActiveRuns(){return[...this.activeRuns.values()]}on(e,t){let r=this.handlers.get(e);r||(r=new Set,this.handlers.set(e,r)),r.add(t)}off(e,t){let r=this.handlers.get(e);r&&r.delete(t)}async runStep(e,t,r,n){if(e.condition&&e.type!=="condition"){let o;try{o=this.deps.conditionalRouter.evaluate(e.condition,r)}catch(i){return{stepId:e.id,stepName:e.name,stepType:e.type,status:"failed",error:`Step "${e.name}" did not run: its condition could not be evaluated, as ${T(i)}.`}}if(!o)return aI(e)}return this.emit("stepStarted",{runId:t.id,stepId:e.id}),this.deps.stepExecutor.execute(e,{variables:r,previousResults:t.stepResults,pipelineId:t.pipelineId,pipelineName:t.pipelineName,runId:t.id,signal:n})}refuseUnrunnable(e,t,r){let n=this.refusals(e);if(n.length===0)return;let o=this.createRun(e,t,r);return o.status="failed",o.stepResults=n.map(({step:i,reason:a})=>({stepId:i.id,stepName:i.name,stepType:i.type,status:"failed",error:a})),o.error=`Pipeline did not start: ${n.map(({reason:i})=>i).join(" ")}`,o.endTime=new Date().toISOString(),o.duration=new Date(o.endTime).getTime()-new Date(o.startTime).getTime(),this.deps.history.record(o),this.emit("failed",{runId:o.id,error:o.error}),o}check(e){let t=this.deps.builder.validate(e);return t.length>0?[dI(t)]:this.refusals(e).map(({reason:r})=>r)}refusals(e){let t=new Set(e.variables.map(r=>r.name));return e.steps.flatMap((r,n)=>{let o=this.deps.stepExecutor.check(r,{steps:e.steps,index:n,declared:t})??this.conditionProblem(r)??KM(r,n,e.steps);return o===void 0?[]:[{step:r,reason:o}]})}conditionProblem(e){if(!e.condition||e.type==="condition")return;let t=this.deps.conditionalRouter.check(e.condition);return t===void 0?void 0:`Step "${e.name}" runs only when its condition holds, and the condition ${t}.`}emit(e,t){let r=this.handlers.get(e);if(r)for(let n of r)n(e,t)}createRun(e,t,r){return{id:JM(),pipelineId:e.id,pipelineName:e.name,status:"queued",triggeredBy:r,stepResults:[],variables:t,startTime:new Date().toISOString()}}};var xc=class{operations=new Map;changeHandlers=new Set;cleanupTimers=new Map;register(e,t,r,n=0,o={}){let i={operationId:e,module:t,description:r,status:"running",percentage:0,processedRecords:0,totalRecords:n,currentStep:r,startedAt:new Date().toISOString(),elapsedMs:0,recordsPerSecond:0,...o.pausable?{pausable:!0}:{}};this.operations.set(e,i),this.notifyChange()}updateProgress(e,t,r,n,o){let i=this.operations.get(e);if(!i)return;let a=Date.now()-new Date(i.startedAt).getTime(),d=a/1e3,c=d>0?Math.round(r/d):0;i.percentage=Math.min(100,Math.max(0,t)),i.processedRecords=r,i.totalRecords=n,i.currentStep=o,i.elapsedMs=a,i.recordsPerSecond=c,this.notifyChange()}complete(e){let t=this.operations.get(e);t&&(t.status="completed",t.percentage=100,t.elapsedMs=Date.now()-new Date(t.startedAt).getTime(),this.notifyChange(),this.scheduleRemoval(e,3e4))}partial(e){let t=this.operations.get(e);t&&(t.status="partial",t.elapsedMs=Date.now()-new Date(t.startedAt).getTime(),this.notifyChange(),this.scheduleRemoval(e,6e4))}fail(e,t){let r=this.operations.get(e);r&&(r.status="failed",r.error=t,r.elapsedMs=Date.now()-new Date(r.startedAt).getTime(),this.notifyChange(),this.scheduleRemoval(e,6e4))}pause(e){let t=this.operations.get(e);t?.status==="running"&&(t.status="paused",this.notifyChange())}resume(e){let t=this.operations.get(e);t?.status==="paused"&&(t.status="running",this.notifyChange())}cancel(e){let t=this.operations.get(e);t&&(t.status="cancelled",t.elapsedMs=Date.now()-new Date(t.startedAt).getTime(),this.notifyChange(),this.scheduleRemoval(e,3e4))}offerResume(e,t){let r=this.operations.get(e);!r||r.status!=="cancelled"&&r.status!=="failed"||(r.resumeRun=t,this.notifyChange())}getAll(){return Array.from(this.operations.values())}getActive(){return this.getAll().filter(e=>e.status==="running"||e.status==="paused")}get(e){return this.operations.get(e)}onChange(e){this.changeHandlers.add(e)}offChange(e){this.changeHandlers.delete(e)}get activeCount(){return this.getActive().length}dispose(){for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear(),this.operations.clear(),this.changeHandlers.clear()}scheduleRemoval(e,t){let r=this.cleanupTimers.get(e);r&&clearTimeout(r);let n=setTimeout(()=>{this.operations.delete(e),this.cleanupTimers.delete(e),this.notifyChange()},t);this.cleanupTimers.set(e,n)}notifyChange(){let e=this.getAll();for(let t of this.changeHandlers)t(e)}};var ZM=3e4;function ej(s,e){let t=vn({isSandbox:e.isSandbox,edition:e.orgType}),{safetyTier:r,color:n}=kr(t);return{id:e.orgId,alias:s.alias,username:e.username||s.username,instanceUrl:s.instanceUrl,orgId:e.orgId,orgType:t,authMethod:"sfdx_import",safetyTier:r,appearance:{color:n,icon:"cloud",position:0},metadata:{apiVersion:Xn.DEFAULT_API_VERSION,edition:e.orgType,features:[]},status:"connected",lastConnected:new Date().toISOString(),tags:[]}}function tj(s,e,t){if(s.correlationId===e){if(s.type===t)return"answered";if(s.type==="bridge:error")return"refused";if(s.type.endsWith(":error"))return"failed"}}function rj(s){let e=s.payload??{};if(s.type.endsWith(":error")||s.type==="operation:failed"){let t=e.message??e.error??e.details??JSON.stringify(e);return`! ${s.type}: ${String(t)}`}if(s.type==="notification")return`! notification (${String(e.level)}): ${String(e.title)} \u2014 ${String(e.message)}`}function nj(s,e){return{compareOrchestrator:r=>new Cc(r),automationOrchestrator:r=>new Dc(r),seedOrchestrator:r=>new Ab(r),getSandforgeSetting:(r,n)=>n,isAIEnabled:()=>!1,configStore:s,showNotification:r=>e(` notification: ${r}`)}}function JV(s){let{log:e}=s,t=s.waitMs??5*6e4,r=Gc();Sg("command line");let n=Dw(QM(s.storeDir,"configStore.json")),o=new Map,i=new Sc({get:v=>Promise.resolve(o.get(v)),store:(v,R)=>(o.set(v,R),Promise.resolve()),delete:v=>(o.delete(v),Promise.resolve())}),a=new kc,d=new Ic(n,i,a),c=new Ec,l=new Xb;l.setSfdxBridge(c);let u=new bc;u.setLogFunction(e);let p=new Rc(u),g=nj(n,e),h=new mc({log:e,broker:u,stateSync:new vc(u),orgManager:a,orgRegistry:d,configStore:n,secretVault:i,authProvider:l,sfdxBridge:c,services:g});h.setLiveOperationTracker(new xc),s.compose?.({handlers:h,configStore:n,orgRegistry:d,orgManager:a,services:g,log:e}),h.registerAll(p);let f=[],m=new Set,y,w={webview:{postMessage:v=>{f.push(v);let R=rj(v);R&&e(` ${R}`),s.onPost?.(v);for(let b of[...m])b(v);return Promise.resolve(!0)},onDidReceiveMessage:v=>(y=v,{dispose:()=>{y=void 0}})}};return u.registerPanel(w),{posted:f,async connect(v){let R=await Ag(v),b=await l.validateConnection(R.accessToken,R.instanceUrl),O=ej(R,b);return await d.saveOrg(O,{loginUrl:R.instanceUrl,instanceUrl:R.instanceUrl,accessToken:R.accessToken,username:R.username}),O},connectingRequests:()=>Gc()-r,request(v){let R=y;if(!R)return Promise.reject(new Error("No panel is registered with the broker."));let b=v.responseType??`${v.type}:response`,O=v.timeoutMs??ZM,k={id:`wv-${YM()}`,type:v.type,timestamp:Date.now(),...v.payload!==void 0?{payload:v.payload}:{}},S=Date.now();return new Promise(E=>{let I=Y=>{m.delete(C),clearTimeout(F),E(Y)},C=Y=>{let z=tj(Y,k.id,b);if(!z)return;let te=Date.now()-S;I({outcome:z,message:Y,elapsedMs:te,late:te>O})},F=setTimeout(()=>I({outcome:"unanswered",elapsedMs:Date.now()-S,late:!0}),Math.max(t,O));m.add(C),R({protocolVersion:1,payload:k})})}}}export{dd as a,_l as b,Hl as c,ha as d,JV as e};