sandforge 1.79.0 → 1.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. package/bin/sandforge-pipeline.mjs +12 -0
  2. package/lib/{chunk-BN7A4GRQ.mjs → chunk-2IB7I3IQ.mjs} +1 -1
  3. package/lib/{chunk-PBI4BYWW.mjs → chunk-2NAIUKVL.mjs} +1 -1
  4. package/lib/chunk-2OIRJEYE.mjs +7 -0
  5. package/lib/{chunk-FOVVHGEP.mjs → chunk-2OZG6GRW.mjs} +1 -1
  6. package/lib/{chunk-5CD257T7.mjs → chunk-2Z54GB6X.mjs} +1 -1
  7. package/lib/chunk-2ZMGVBLW.mjs +7 -0
  8. package/lib/{chunk-4NAHW2D3.mjs → chunk-33ZX3A56.mjs} +1 -1
  9. package/lib/{chunk-4SNDMJP2.mjs → chunk-3AOKLIVE.mjs} +1 -1
  10. package/lib/{chunk-SIOZXPFG.mjs → chunk-3B5H24ZG.mjs} +1 -1
  11. package/lib/chunk-43K2C6H2.mjs +7 -0
  12. package/lib/chunk-4JKR4PTZ.mjs +8 -0
  13. package/lib/chunk-4L7FBOJS.mjs +8 -0
  14. package/lib/chunk-5344TZBT.mjs +11 -0
  15. package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
  16. package/lib/chunk-55LQD3Y3.mjs +7 -0
  17. package/lib/chunk-56MPPWLA.mjs +7 -0
  18. package/lib/chunk-5C5XEVZN.mjs +11 -0
  19. package/lib/chunk-5CKWGZX4.mjs +9 -0
  20. package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
  21. package/lib/{chunk-GNC27UEU.mjs → chunk-5UT2ZBGF.mjs} +1 -1
  22. package/lib/chunk-5VQNKDFU.mjs +7 -0
  23. package/lib/chunk-5WGA5CZB.mjs +7 -0
  24. package/lib/chunk-5ZKCLBTN.mjs +474 -0
  25. package/lib/chunk-67CC7RAE.mjs +7 -0
  26. package/lib/{chunk-5O6JOMHS.mjs → chunk-6CDIIFNX.mjs} +1 -1
  27. package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
  28. package/lib/{chunk-7UQD6V6F.mjs → chunk-6FMLW7PH.mjs} +1 -1
  29. package/lib/chunk-6IGEASOF.mjs +7 -0
  30. package/lib/{chunk-H2PJNIYJ.mjs → chunk-6NADW3OI.mjs} +1 -1
  31. package/lib/chunk-6SEDOIO3.mjs +10 -0
  32. package/lib/{chunk-AUTM6H6Z.mjs → chunk-742SSN7I.mjs} +1 -1
  33. package/lib/chunk-7DALDJMO.mjs +7 -0
  34. package/lib/chunk-7PK5QDQI.mjs +7 -0
  35. package/lib/chunk-AELFEK3G.mjs +7 -0
  36. package/lib/chunk-AITNZWLB.mjs +9 -0
  37. package/lib/{chunk-HV2MXMGI.mjs → chunk-AJPSGVMD.mjs} +1 -1
  38. package/lib/{chunk-OTWRDD6L.mjs → chunk-BNO5GIJ6.mjs} +1 -1
  39. package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
  40. package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
  41. package/lib/chunk-BZFIOZS3.mjs +156 -0
  42. package/lib/{chunk-XBG5SP6Q.mjs → chunk-C4YGSK6W.mjs} +1 -1
  43. package/lib/chunk-CAFUNR6D.mjs +7 -0
  44. package/lib/chunk-CULAOP3U.mjs +7 -0
  45. package/lib/chunk-D62KWDDT.mjs +7 -0
  46. package/lib/{chunk-BILZ3SSR.mjs → chunk-D7P7DTWL.mjs} +1 -1
  47. package/lib/chunk-DHGPDSXS.mjs +7 -0
  48. package/lib/{chunk-ZXH4MBWP.mjs → chunk-DHIW4IO5.mjs} +1 -1
  49. package/lib/{chunk-NM4MDLK4.mjs → chunk-DMBR24CK.mjs} +1 -1
  50. package/lib/chunk-DPYTG6DM.mjs +48 -0
  51. package/lib/chunk-DQR5NDMI.mjs +7 -0
  52. package/lib/chunk-DXOXLUZA.mjs +7 -0
  53. package/lib/chunk-E2OBAWSH.mjs +7 -0
  54. package/lib/chunk-E2YJVSX6.mjs +10 -0
  55. package/lib/chunk-EAFLDSQ2.mjs +7 -0
  56. package/lib/{chunk-HCIDVIOW.mjs → chunk-EH5YUA5W.mjs} +1 -1
  57. package/lib/{chunk-2BVTCNWA.mjs → chunk-EOSEMFPU.mjs} +1 -1
  58. package/lib/chunk-ETT5GP4P.mjs +13 -0
  59. package/lib/{chunk-3SRXFZSD.mjs → chunk-FDGFUEK3.mjs} +1 -1
  60. package/lib/{chunk-3DCUADVK.mjs → chunk-FLNLG43R.mjs} +1 -1
  61. package/lib/{chunk-HTJ5OGP5.mjs → chunk-FSDO4DJA.mjs} +1 -1
  62. package/lib/{chunk-HJKM3E56.mjs → chunk-FSZTXLNW.mjs} +1 -1
  63. package/lib/chunk-FTA5LOVX.mjs +7 -0
  64. package/lib/chunk-G4VXPS3A.mjs +7 -0
  65. package/lib/chunk-GF247DA7.mjs +7 -0
  66. package/lib/{chunk-QRV2OSIS.mjs → chunk-GK7VEYFM.mjs} +1 -1
  67. package/lib/{chunk-5MMXFWPD.mjs → chunk-GR3NGDVM.mjs} +1 -1
  68. package/lib/{chunk-P7GSGFJO.mjs → chunk-GTIXJCGS.mjs} +1 -1
  69. package/lib/{chunk-342FN7AO.mjs → chunk-GWRKS3AL.mjs} +1 -1
  70. package/lib/{chunk-LQ4DRFUH.mjs → chunk-GYKNCYES.mjs} +1 -1
  71. package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
  72. package/lib/chunk-HVC5CYIB.mjs +7 -0
  73. package/lib/{chunk-EQF2IJS2.mjs → chunk-HYBH5PFM.mjs} +1 -1
  74. package/lib/chunk-HYOOJVR6.mjs +7 -0
  75. package/lib/{chunk-TQX3PURV.mjs → chunk-IBURU7T7.mjs} +1 -1
  76. package/lib/chunk-ICIYL45C.mjs +7 -0
  77. package/lib/{chunk-K22PA4XL.mjs → chunk-IKGHRYCN.mjs} +1 -1
  78. package/lib/chunk-IM2XA6JI.mjs +7 -0
  79. package/lib/{chunk-P2PJYWGQ.mjs → chunk-J6G23RUI.mjs} +1 -1
  80. package/lib/{chunk-JVL444U5.mjs → chunk-JU2XEKEO.mjs} +1 -1
  81. package/lib/{chunk-H45UXY6G.mjs → chunk-K55LH4ZQ.mjs} +1 -1
  82. package/lib/chunk-K5HV4YRO.mjs +7 -0
  83. package/lib/{chunk-IAZB4WIL.mjs → chunk-K77NR3UK.mjs} +1 -1
  84. package/lib/chunk-KE2PGD6C.mjs +7 -0
  85. package/lib/chunk-KGYXLSQ5.mjs +37 -0
  86. package/lib/{chunk-TEOLMRDO.mjs → chunk-KNIRA333.mjs} +1 -1
  87. package/lib/chunk-KOQV4WXC.mjs +8 -0
  88. package/lib/{chunk-PNCONNFJ.mjs → chunk-KRNFVAGC.mjs} +1 -1
  89. package/lib/chunk-L5FGY6YA.mjs +7 -0
  90. package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
  91. package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
  92. package/lib/{chunk-ZOVSMN5C.mjs → chunk-LO527YLT.mjs} +1 -1
  93. package/lib/chunk-MAHZMPMZ.mjs +7 -0
  94. package/lib/{chunk-QQZZMKU3.mjs → chunk-MHW6DV6T.mjs} +1 -1
  95. package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
  96. package/lib/{chunk-6EBMEGZB.mjs → chunk-MKNAZPOT.mjs} +1 -1
  97. package/lib/{chunk-NTDN2JQZ.mjs → chunk-MNITSYI2.mjs} +8 -8
  98. package/lib/chunk-MO3N5XVV.mjs +341 -0
  99. package/lib/{chunk-SBIMVCXT.mjs → chunk-MS4FJDFD.mjs} +9 -9
  100. package/lib/chunk-MWLFFVQV.mjs +8 -0
  101. package/lib/chunk-N6HHNR6J.mjs +7 -0
  102. package/lib/chunk-N7J6NJQ6.mjs +7 -0
  103. package/lib/chunk-NJ3EOEHS.mjs +9 -0
  104. package/lib/chunk-NWPQF5XR.mjs +7 -0
  105. package/lib/{chunk-PUOX4NBJ.mjs → chunk-NWVVCZUK.mjs} +1 -1
  106. package/lib/{chunk-DLDX6RRC.mjs → chunk-O6ADMP36.mjs} +1 -1
  107. package/lib/chunk-O7DAFE6M.mjs +14 -0
  108. package/lib/chunk-OEHVAJAB.mjs +7 -0
  109. package/lib/chunk-OETEC3P7.mjs +7 -0
  110. package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
  111. package/lib/chunk-OIIL4NVI.mjs +7 -0
  112. package/lib/chunk-OMZJ37JI.mjs +15 -0
  113. package/lib/{chunk-NZ5ZZLKS.mjs → chunk-ONMBSACW.mjs} +1 -1
  114. package/lib/chunk-OQQHNYR7.mjs +272 -0
  115. package/lib/{chunk-AAVJ5XVX.mjs → chunk-OU5W7SCB.mjs} +1 -1
  116. package/lib/{chunk-RSYICMZG.mjs → chunk-OVOLG3AL.mjs} +1 -1
  117. package/lib/{chunk-F74IHMGL.mjs → chunk-OXKZ4Y3B.mjs} +1 -1
  118. package/lib/{chunk-W7KFAY55.mjs → chunk-OZNLOV4U.mjs} +1 -1
  119. package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
  120. package/lib/chunk-PPGDAUEQ.mjs +7 -0
  121. package/lib/{chunk-RACDTRZA.mjs → chunk-PYUEHBA6.mjs} +1 -1
  122. package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
  123. package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
  124. package/lib/{chunk-PZTSVQSF.mjs → chunk-QXLZINZB.mjs} +1 -1
  125. package/lib/chunk-R2BJWO5N.mjs +20 -0
  126. package/lib/chunk-R6TF26V4.mjs +10 -0
  127. package/lib/{chunk-P42X3B4D.mjs → chunk-RKALOKAU.mjs} +1 -1
  128. package/lib/chunk-SQGP46QS.mjs +7 -0
  129. package/lib/chunk-SU65Z2BA.mjs +7 -0
  130. package/lib/chunk-SW2NUKQL.mjs +9 -0
  131. package/lib/chunk-T26C576X.mjs +9 -0
  132. package/lib/{chunk-3OHPD72J.mjs → chunk-T3PLRQ2T.mjs} +1 -1
  133. package/lib/chunk-T5VAULLQ.mjs +7 -0
  134. package/lib/chunk-TEIBWMJM.mjs +7 -0
  135. package/lib/chunk-TKQQVB2D.mjs +9 -0
  136. package/lib/{chunk-RAAANPPG.mjs → chunk-TPHXRHOA.mjs} +1 -1
  137. package/lib/chunk-TQ2TQHTT.mjs +9 -0
  138. package/lib/{chunk-IEYG5ATY.mjs → chunk-TQM2XJ27.mjs} +1 -1
  139. package/lib/{chunk-X65MT4W3.mjs → chunk-UCHAZ4ZU.mjs} +1 -1
  140. package/lib/chunk-UIUPPEFB.mjs +7 -0
  141. package/lib/{chunk-QPF6C5MX.mjs → chunk-UT27HXE7.mjs} +1 -1
  142. package/lib/{chunk-J7HVXMSW.mjs → chunk-UUSLTW5V.mjs} +1 -1
  143. package/lib/chunk-V2QO6KOE.mjs +19 -0
  144. package/lib/chunk-V473C7LY.mjs +7 -0
  145. package/lib/chunk-V4RKM4QZ.mjs +8 -0
  146. package/lib/chunk-VSU74RQ3.mjs +9 -0
  147. package/lib/chunk-VV3B6IC3.mjs +7 -0
  148. package/lib/chunk-W2AAGIZF.mjs +7 -0
  149. package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
  150. package/lib/chunk-WD47PGUS.mjs +10 -0
  151. package/lib/{chunk-3CA767QB.mjs → chunk-WEZLXE34.mjs} +1 -1
  152. package/lib/{chunk-WFEB5X4U.mjs → chunk-WI4HYWV6.mjs} +1 -1
  153. package/lib/{chunk-AR7BE5O2.mjs → chunk-WM5JI4JI.mjs} +1 -1
  154. package/lib/chunk-WWTXRWNZ.mjs +7 -0
  155. package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
  156. package/lib/{chunk-ZJKCWBRJ.mjs → chunk-X2ZVSQ54.mjs} +1 -1
  157. package/lib/{chunk-SFURUNJM.mjs → chunk-XC2QKQT5.mjs} +1 -1
  158. package/lib/chunk-XC54KKKC.mjs +7 -0
  159. package/lib/chunk-XEB6HZ34.mjs +7 -0
  160. package/lib/chunk-XGKSSCW7.mjs +7 -0
  161. package/lib/chunk-XIZ5LMQM.mjs +7 -0
  162. package/lib/{chunk-RFEO2KAN.mjs → chunk-Y5ZCPY36.mjs} +1 -1
  163. package/lib/{chunk-TBZMC2VV.mjs → chunk-YCSFP6ER.mjs} +4 -4
  164. package/lib/{chunk-YBU4Z4QV.mjs → chunk-YHIOS2PU.mjs} +1 -1
  165. package/lib/chunk-YIGFYZQY.mjs +7 -0
  166. package/lib/chunk-YJEXE6HZ.mjs +925 -0
  167. package/lib/{chunk-57VHUYNG.mjs → chunk-YOGMP72T.mjs} +4 -4
  168. package/lib/chunk-ZRUDYB7O.mjs +7 -0
  169. package/lib/{chunk-55HEMHEG.mjs → chunk-ZUA5BNAO.mjs} +1 -1
  170. package/lib/chunk-ZWCRWF7E.mjs +7 -0
  171. package/lib/{chunk-VHI54FBK.mjs → chunk-ZWZXQTAK.mjs} +53 -53
  172. package/lib/sandforge-autopilot.mjs +29 -24
  173. package/lib/sandforge-backup.mjs +67 -32
  174. package/lib/sandforge-checkpoint.mjs +1 -347
  175. package/lib/sandforge-cleanup.mjs +14 -10
  176. package/lib/sandforge-clone.mjs +1 -1
  177. package/lib/sandforge-compare.mjs +9 -8
  178. package/lib/sandforge-dataops.mjs +1 -1
  179. package/lib/sandforge-empty.mjs +15 -15
  180. package/lib/sandforge-env.mjs +101 -101
  181. package/lib/sandforge-frozen.mjs +1 -257
  182. package/lib/sandforge-mcp.mjs +33 -14
  183. package/lib/sandforge-monitor.mjs +7 -7
  184. package/lib/sandforge-pipeline.mjs +88 -0
  185. package/lib/sandforge-seed.mjs +1 -1
  186. package/lib/sandforge-sync.mjs +1 -1
  187. package/lib/sandforge.mjs +6 -6
  188. package/package.json +2 -1
  189. package/lib/chunk-2S5OMIIA.mjs +0 -7
  190. package/lib/chunk-36U7IQ6Y.mjs +0 -25
  191. package/lib/chunk-3F5YMM2F.mjs +0 -7
  192. package/lib/chunk-3RYLICRX.mjs +0 -7
  193. package/lib/chunk-42RER7V4.mjs +0 -14
  194. package/lib/chunk-4GL773D5.mjs +0 -7
  195. package/lib/chunk-4HFRHFGQ.mjs +0 -7
  196. package/lib/chunk-4U6NXJNL.mjs +0 -7
  197. package/lib/chunk-4XZ5YT5O.mjs +0 -7
  198. package/lib/chunk-5AJRHRXA.mjs +0 -20
  199. package/lib/chunk-5HMAPZBV.mjs +0 -7
  200. package/lib/chunk-5P4PHJRL.mjs +0 -9
  201. package/lib/chunk-5QKTYCWE.mjs +0 -11
  202. package/lib/chunk-6LAXTAVN.mjs +0 -7
  203. package/lib/chunk-6MUEPV7M.mjs +0 -9
  204. package/lib/chunk-6QSM2WIH.mjs +0 -10
  205. package/lib/chunk-75ADZS6B.mjs +0 -7
  206. package/lib/chunk-ALJVEUUS.mjs +0 -7
  207. package/lib/chunk-ALUFROGA.mjs +0 -7
  208. package/lib/chunk-B45CNPUX.mjs +0 -47
  209. package/lib/chunk-BS5T3MOQ.mjs +0 -7
  210. package/lib/chunk-CGWXQX75.mjs +0 -7
  211. package/lib/chunk-D3QRXG63.mjs +0 -787
  212. package/lib/chunk-EEVVGGM6.mjs +0 -7
  213. package/lib/chunk-ENLBYECD.mjs +0 -7
  214. package/lib/chunk-EQOQASDQ.mjs +0 -7
  215. package/lib/chunk-FQBRBBY4.mjs +0 -7
  216. package/lib/chunk-GAM726CK.mjs +0 -7
  217. package/lib/chunk-HJC7AIBK.mjs +0 -7
  218. package/lib/chunk-HUMEKZT5.mjs +0 -8
  219. package/lib/chunk-I3JKJTLO.mjs +0 -110
  220. package/lib/chunk-I7O6C2B5.mjs +0 -8
  221. package/lib/chunk-KLX67VPL.mjs +0 -7
  222. package/lib/chunk-L776PUMV.mjs +0 -7
  223. package/lib/chunk-LRFAIUN7.mjs +0 -7
  224. package/lib/chunk-LV6G4XTK.mjs +0 -7
  225. package/lib/chunk-MYTIL2JD.mjs +0 -10
  226. package/lib/chunk-NEVXIGR6.mjs +0 -10
  227. package/lib/chunk-NGSMZZDA.mjs +0 -7
  228. package/lib/chunk-NHWE66K5.mjs +0 -7
  229. package/lib/chunk-OQOZAPCI.mjs +0 -7
  230. package/lib/chunk-PA3MKJVH.mjs +0 -7
  231. package/lib/chunk-QROPNEGY.mjs +0 -14
  232. package/lib/chunk-QWT2C74M.mjs +0 -7
  233. package/lib/chunk-RH3N2H7P.mjs +0 -7
  234. package/lib/chunk-SRQDABQ2.mjs +0 -15
  235. package/lib/chunk-SVS6UMDU.mjs +0 -323
  236. package/lib/chunk-TNXUU6W7.mjs +0 -14
  237. package/lib/chunk-VGW4MXXZ.mjs +0 -7
  238. package/lib/chunk-VXHDBYMI.mjs +0 -7
  239. package/lib/chunk-WJY54JO7.mjs +0 -13
  240. package/lib/chunk-WRU5FJFC.mjs +0 -7
  241. package/lib/chunk-X2PY6MWZ.mjs +0 -7
  242. package/lib/chunk-XEFDB2R4.mjs +0 -7
  243. package/lib/chunk-XETCPL7E.mjs +0 -7
  244. package/lib/chunk-Y5CGXLUB.mjs +0 -7
  245. package/lib/chunk-Y6J6QFI2.mjs +0 -7
  246. package/lib/chunk-YMJVMFPY.mjs +0 -7
  247. package/lib/chunk-YPSRZRIT.mjs +0 -7
  248. package/lib/chunk-YS4G22C2.mjs +0 -7
  249. package/lib/chunk-YW2SBL4Z.mjs +0 -7
  250. package/lib/chunk-Z7X534S4.mjs +0 -10
  251. package/lib/chunk-ZE6HKRR4.mjs +0 -9
  252. package/lib/chunk-ZLZRU6MO.mjs +0 -7
  253. package/lib/chunk-ZPYJPGDK.mjs +0 -7
  254. package/lib/chunk-ZQOZ4EFW.mjs +0 -7
  255. package/lib/chunk-ZUTYVST5.mjs +0 -7
  256. package/lib/chunk-ZYEE34WO.mjs +0 -7
@@ -1,11 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{u as Q,w as q}from"./chunk-WJY54JO7.mjs";import{E as W,F as Z,d as K,k as I,r as b,s as L,t as F,u as J,x as D,z as U}from"./chunk-NEVXIGR6.mjs";import{Aa as Y,Ba as G,Ca as N}from"./chunk-B45CNPUX.mjs";import{b as H,e as _,m as $,v as X}from"./chunk-7EANH5PY.mjs";import{createCipheriv as be,createDecipheriv as Be,createHash as y,hkdfSync as Ae,randomBytes as S,timingSafeEqual as Ee}from"node:crypto";import{createReadStream as Oe}from"node:fs";import{lstat as ee,open as T,rename as xe,rm as Ie,statfs as Se}from"node:fs/promises";import{basename as ie,dirname as oe,join as ve}from"node:path";import{Readable as ae}from"node:stream";import{pipeline as se}from"node:stream/promises";import{createGunzip as Re,createGzip as Ce}from"node:zlib";var ct=".sfcheckpoint",Te=1024*1024,Pe=new Set([1]),He=new Set([1]),P=32,A=16,_e=4096,$e=1024,Ne=64*1024*1024,ce=2**32,he="sandforge-checkpoint/1 block key",fe="sandforge-checkpoint/1 key check",M="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",Ke=Math.ceil(P*8/5),w="Nothing was imported.";function ht(){return S(P)}function ft(n){if(n.length!==P)throw new RangeError("Not a key of a checkpoint file");let e="",t=0,r=0;for(let i of n)for(t=(t<<8|i)&65535,r+=8;r>=5;)e+=M[t>>>r-5&31],r-=5;return r>0&&(e+=M[t<<5-r&31]),(e.match(/.{1,4}/g)??[]).join("-")}function dt(n){let e=n.replace(/[\s-]/g,"").toUpperCase();if(e.length!==Ke||!/^[A-Z2-7]+$/.test(e))return;let t=Buffer.alloc(P),r=0,i=0,o=0;for(let a of e)r=(r<<5|M.indexOf(a))&65535,i+=5,i>=8&&(t[o++]=r>>>i-8&255,i-=8);if((r&(1<<i)-1)===0)return t}function v(n,e,t,r){return Buffer.from(Ae("sha256",n,e,t,r))}function de(n,e){let t=Buffer.alloc(12);return n.copy(t,0),t.writeUInt32BE(e,8),t}function le(n,e,t){let r=Buffer.alloc(37);return n.copy(r,0),r.writeUInt32BE(e,32),r[36]=t?1:0,r}function Fe(n,e,t,r){let i=be("aes-256-gcm",n.blockKey,de(n.prefix,e),{authTagLength:A});return i.setAAD(le(n.headerHash,e,t)),Buffer.concat([i.update(r),i.final(),i.getAuthTag()])}function De(n,e,t,r){let i=Be("aes-256-gcm",n.blockKey,de(n.prefix,e),{authTagLength:A});i.setAAD(le(n.headerHash,e,t)),i.setAuthTag(r.subarray(r.length-A));try{let o=i.update(r.subarray(0,r.length-A));return Buffer.concat([o,i.final()])}catch{return}}var R=class extends Error{constructor(t){super(t.message);this.refusal=t;this.name="ImportRefused"}refusal};function f(n){return new R({code:"IMPORT_DAMAGED",message:`This checkpoint file ${n}: it was changed or damaged after it was exported. ${w}`})}var E=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointExportError"}code};function Me(n){return{...C(n,ue),org:C(n.org,pe)}}var ue=["lastRewind","takenOn","expiresAt","bytes","importedFrom"],pe=["alias"];function C(n,e){return Object.fromEntries(Object.entries(n).filter(([t])=>!e.includes(t)))}async function*ye(n,e){if(e===0)return;let t=0;for await(let r of Oe(n,{start:0,end:e-1})){let i=r;t+=i.length,yield i}if(t!==e)throw new E("EXPORT_CHANGED",`${ie(n)} of the checkpoint shrank while it was exported: export it again.`)}async function me(n,e){let t=y("sha256");for await(let r of ye(n,e))t.update(r);return t.digest("hex")}async function lt(n){let{folder:e,checkpoint:t,out:r,key:i}=n,o=n.chunkBytes??Te;if(await ee(r).catch(()=>{}))throw new E("EXPORT_EXISTS",`${r} is there already: name another file, or move that one away first.`);let a=Buffer.from(`${JSON.stringify(Me(t))}
8
- `,"utf8"),s=[{path:b,bytes:a.length,sha256:y("sha256").update(a).digest("hex"),content:a}];for(let l of await F(e))l.path!==b&&s.push({...l,sha256:await me(l.file,l.bytes)});let h=S(32),c=S(8),d={format:"sandforge-checkpoint",formatVersion:1,checkpointFormat:1,sandforgeVersion:n.sandforgeVersion,organizationId:I(t.org.organizationId),orgTier:t.org.tier,checkpointId:t.checkpointId,takenAt:t.takenAt,records:we(t),objects:t.objects.length,files:s.length,bytes:s.reduce((l,p)=>l+p.bytes,0),cipher:"aes-256-gcm",kdf:"hkdf-sha256",salt:h.toString("hex"),noncePrefix:c.toString("hex"),keyCheck:v(i,h,fe,16).toString("hex"),chunkBytes:o},u=Buffer.from(`${JSON.stringify(N.parse(d))}
9
- `),m={blockKey:v(i,h,he,32),prefix:c,headerHash:y("sha256").update(u).digest()},k=ve(oe(r),`.${ie(r)}.${process.pid}-${S(4).toString("hex")}.tmp`),O=y("sha256"),g=0,x=await T(k,"wx",K);try{try{let l=async p=>{O.update(p),g+=p.length,await ge(x,p)};await l(u),await se(ae.from(ze(s)),Ce({level:6}),async p=>{await je(p,o,m,l)}),await x.sync()}finally{await x.close()}if(await ee(r).catch(()=>{}))throw new E("EXPORT_EXISTS",`${r} appeared while the checkpoint was exported: name another file.`);await xe(k,r)}catch(l){throw await Ie(k,{force:!0}),l}return{header:d,bytes:g,sha256:O.digest("hex")}}async function ge(n,e){for(let t=0;t<e.length;){let{bytesWritten:r}=await n.write(e,t,e.length-t);t+=r}}function we(n){return n.objects.reduce((e,t)=>e+t.records,0)}async function*ze(n){for(let e of n){let{path:t,bytes:r,sha256:i}=e;if(yield Buffer.from(`${JSON.stringify({path:t,bytes:r,sha256:i})}
10
- `,"utf8"),e.content!==void 0){yield e.content;continue}let o=y("sha256");for await(let a of ye(e.file??"",r))o.update(a),yield a;if(o.digest("hex")!==i)throw new E("EXPORT_CHANGED",`${t} of the checkpoint changed while it was exported: export it again.`)}yield Buffer.from(`${JSON.stringify({end:!0,files:n.length})}
11
- `,"utf8")}async function je(n,e,t,r){let i=0,o,a=[],s=0,h=async c=>{if(o!==void 0){if(i>=ce)throw new RangeError("The checkpoint is too large for one file");await r(Fe(t,i,c,o)),i++,o=void 0}};for await(let c of n)for(a.push(c),s+=c.length;s>=e;){let d=Buffer.concat(a);await h(!1),o=d.subarray(0,e),a=[d.subarray(e)],s=d.length-e}s>0&&(await h(!1),o=Buffer.concat(a)),await h(!0)}async function z(n,e,t){let r=Buffer.alloc(t),i=0;for(;i<t;){let{bytesRead:o}=await n.read(r,i,t-i,e+i);if(o===0)break;i+=o}return i===t?r:r.subarray(0,i)}function B(n){return{refusal:{code:"IMPORT_NOT_ARCHIVE",message:`This is not a checkpoint file SandForge exported: ${n}. ${w}`}}}async function Ve(n){let e;try{e=await T(n,"r")}catch(t){let r=t.code;return B(r==="ENOENT"?"there is no such file":"it cannot be read")}try{let t=await e.stat();if(!t.isFile())return B("it is not a file");let r=await z(e,0,Math.min(t.size,_e)),i=r.indexOf(10);if(i<0)return B("it does not start with a checkpoint file\u2019s header");let o=r.subarray(0,i+1),a;try{a=JSON.parse(o.toString("utf8"))}catch{return B("it does not start with a checkpoint file\u2019s header")}let s=G.safeParse(a);if(!s.success)return B("it does not start with a checkpoint file\u2019s header");let{formatVersion:h,checkpointFormat:c,sandforgeVersion:d}=s.data;if(!He.has(h)||!Pe.has(c))return{refusal:{code:"IMPORT_VERSION",message:`This file was made by SandForge ${d}, with checkpoint format ${c} in file format ${h}, which this SandForge does not read: update SandForge, then import it. ${w}`}};let u=N.safeParse(a);return u.success?{read:{header:u.data,headerBytes:o.length,headerHash:y("sha256").update(o).digest(),size:t.size}}:B("its header does not read")}finally{await e.close()}}async function Xe(n){try{let e=await Se(n);return Number(e.bavail)*Number(e.bsize)}catch{return}}async function ut(n){try{return await Ye(n)}catch(e){if(e instanceof R)return{imported:!1,refusal:e.refusal};if(e instanceof W&&e.code==="damaged")return{imported:!1,refusal:{code:"IMPORT_DAMAGED",message:`${e.message} ${w}`}};throw e}}async function Ye(n){let{store:e,file:t,key:r}=n,i=n.now??new Date,o=await Ve(t);if("refusal"in o)return{imported:!1,refusal:o.refusal};if(!o.read.headerHash.equals(n.read.headerHash))throw f("changed since its header was read");let a=o.read,{header:s}=a,h=Buffer.from(s.salt,"hex");if(!Ee(v(r,h,fe,16),Buffer.from(s.keyCheck,"hex")))return{imported:!1,refusal:{code:"IMPORT_KEY",message:`This key is not the one the file was exported with. ${w}`}};let c={blockKey:v(r,h,he,32),prefix:Buffer.from(s.noncePrefix,"hex"),headerHash:a.headerHash},d=await e.read(s.checkpointId);if(d!==void 0)return ne(d,t,a,c);let u=await(n.freeBytes??Xe)(e.root),m=s.bytes+Q(s.records,2)+s.objects*8;if(u!==void 0&&u<m)return{imported:!1,refusal:{code:"IMPORT_DISK",message:`The checkpoint takes about ${te(m)} on this machine, and its disk has ${te(u)} free: make room, then import it. ${w}`}};let k=await e.importInto(s.organizationId,s.checkpointId,async g=>{let x=await ke(t,a,c,g.dir),l=We(x,a,{...n.alias!==void 0?{alias:n.alias}:{},keepDays:n.keepDays,takenOn:n.takenOn,now:i});await D(g.indexDir);for(let p of l.objects){let V=await q(g,l.snapshotId,p.objectApiName);if(V.rows!==p.records)throw f(`holds ${V.rows} records of ${p.objectApiName} where its checkpoint counts ${p.records}`)}return await Z(g,l.objects),l});if(k.outcome==="imported")return{imported:!0,outcome:"imported",checkpoint:k.checkpoint};let O=await e.read(s.checkpointId);if(O===void 0)throw f("could not be kept");return ne(O,t,a,c)}function te(n){return`${(n/(1024*1024)).toFixed(1)} MB`}async function ne(n,e,t,r){let i=c=>({imported:!1,refusal:{code:"IMPORT_KEPT_OTHER",message:`A checkpoint ${t.header.checkpointId} is kept on this machine already, ${c}: delete it first to import this file. ${w}`}});if(n.folder.organizationId!==I(t.header.organizationId))return i("of another org");if(n.checkpoint===void 0)return i("damaged");let o=i("and differs from this one"),a=await ke(e,t,r),s=new Map(a.hashes.filter(([c])=>c!==b).map(([c,d])=>[c,d])),h=(await F(n.folder)).filter(c=>c.path!==b);if(h.length!==s.size)return o;for(let c of h)if(s.get(c.path)!==await me(c.file,c.bytes))return o;return{imported:!0,outcome:"alreadyKept",checkpoint:n.checkpoint}}var Ge=$({path:H().min(1).max(300),bytes:_().int().nonnegative(),sha256:H().regex(/^[0-9a-f]{64}$/)}),Le=$({end:X(!0),files:_().int().positive()});async function ke(n,e,t,r){let i=await T(n,"r"),o=y("sha256");try{let a=new j(e.header,r);try{await se(ae.from(Je(i,e,t,o)),Re(),async h=>{for await(let c of h)await a.take(c)})}catch(h){throw String(h.code??"").startsWith("Z_")?f("does not inflate"):h}finally{await a.close()}return{...a.ended(),sha256:o.digest("hex")}}finally{await i.close()}}async function*Je(n,e,t,r){r.update(await z(n,0,e.headerBytes));let i=e.header.chunkBytes+A,o=e.size-e.headerBytes;if(o<=0)throw f("holds nothing after its header");let a=Math.ceil(o/i),s=o-(a-1)*i;if(s<=A)throw f("ends inside a block");if(a>ce)throw f("holds more blocks than a file can");for(let h=0;h<a;h++){let c=h===a-1,d=c?s:i,u=await z(n,e.headerBytes+h*i,d);if(u.length<d)throw f("is cut short");r.update(u);let m=De(t,h,c,u);if(m===void 0)throw f(`holds a block, the ${Ue(h+1)} of ${a}, that does not decrypt`);yield m}}function Ue(n){let e=n%100,t=e>=11&&e<=13?"th":["th","st","nd","rd"][n%10]??"th";return`${n}${t}`}var j=class{constructor(e,t){this.header=e;this.into=t}header;into;line=[];lineBytes=0;current;seen=new Set;hashes=[];portable;bytes=0;end=!1;async take(e){let t=0;for(;t<e.length;){if(this.end)throw f("holds bytes after its last entry");let r=this.current;if(r!==void 0){let s=e.subarray(t,t+Math.min(r.left,e.length-t));t+=s.length,r.left-=s.length,r.hash.update(s),r.handle!==void 0&&await ge(r.handle,s),r.held?.push(Buffer.from(s)),r.left===0&&await this.endEntry();continue}let i=e.indexOf(10,t),o=i<0?e.length:i;if(this.lineBytes+=o-t,this.lineBytes>$e)throw f("holds a line too long for an entry");if(this.line.push(e.subarray(t,o)),t=o,i<0)continue;t++;let a=Buffer.concat(this.line).toString("utf8");this.line=[],this.lineBytes=0,await this.startEntry(a)}}async startEntry(e){let t;try{t=JSON.parse(e)}catch{throw f("holds an entry that does not read")}let r=Le.safeParse(t);if(r.success){if(r.data.files!==this.hashes.length||r.data.files!==this.header.files)throw f("counts other files than it holds");this.end=!0;return}let i=Ge.safeParse(t);if(!i.success)throw f("holds an entry that does not read");let{path:o,bytes:a,sha256:s}=i.data;if(!L(o))throw f(`names a file no checkpoint holds, ${JSON.stringify(o)}`);if(this.seen.has(o))throw f(`holds ${o} twice`);if(this.seen.add(o),this.bytes+=a,this.bytes>this.header.bytes||this.seen.size>this.header.files)throw f("holds more than its header says");let h=o===b;if(h&&a>Ne)throw f("holds a checkpoint.json larger than any checkpoint\u2019s");let c;if(!h&&this.into!==void 0){let d=J(this.into,o);await D(oe(d)),c=await T(d,"wx",K)}this.current={path:o,left:a,sha256:s,hash:y("sha256"),...c!==void 0?{handle:c}:{},...h?{held:[]}:{}},a===0&&await this.endEntry()}async endEntry(){let e=this.current;if(e!==void 0){if(this.current=void 0,e.handle!==void 0)try{await e.handle.sync()}finally{await e.handle.close()}if(e.hash.digest("hex")!==e.sha256)throw f(`holds ${e.path} with other bytes than its sha256 says`);e.held!==void 0&&(this.portable=Buffer.concat(e.held)),this.hashes.push([e.path,e.sha256])}}async close(){await this.current?.handle?.close().catch(()=>{})}ended(){if(!this.end||this.current!==void 0)throw f("is cut short");if(this.bytes!==this.header.bytes)throw f("holds other bytes than its header says");if(this.portable===void 0)throw f("holds no checkpoint.json");return{portable:this.portable,hashes:this.hashes}}};function We(n,e,t){let r;try{r=JSON.parse(n.portable.toString("utf8"))}catch{throw f("holds a checkpoint.json that does not read")}if(!re(r)||!re(r.org))throw f("holds a checkpoint.json that does not read");let i=Y.safeParse({...C(r,ue),org:{...C(r.org,pe),...t.alias!==void 0?{alias:t.alias}:{}},takenOn:t.takenOn,expiresAt:U(t.now,t.keepDays),bytes:0,importedFrom:{at:t.now.toISOString(),sandforgeVersion:e.header.sandforgeVersion,sha256:n.sha256}});if(!i.success)throw f("holds a checkpoint.json that does not parse");let o=i.data,{header:a}=e;if(o.checkpointId!==a.checkpointId||I(o.org.organizationId)!==I(a.organizationId)||o.takenAt!==a.takenAt||o.status!=="ready"||we(o)!==a.records||o.objects.length!==a.objects)throw f("holds another checkpoint than its header says");return o}function re(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}export{ct as a,Te as b,ht as c,ft as d,dt as e,E as f,Me as g,lt as h,Ve as i,ut as j};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i,j,k,l,m}from"./chunk-LQ4DRFUH.mjs";import"./chunk-57VHUYNG.mjs";import"./chunk-MYTIL2JD.mjs";import"./chunk-JVL444U5.mjs";import"./chunk-5CD257T7.mjs";import"./chunk-5P4PHJRL.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-ALJVEUUS.mjs";import"./chunk-342FN7AO.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-6QSM2WIH.mjs";import"./chunk-WJY54JO7.mjs";import"./chunk-NEVXIGR6.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-SAR5622P.mjs";import"./chunk-HJC7AIBK.mjs";import"./chunk-OTWRDD6L.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-ZUTYVST5.mjs";import"./chunk-55HEMHEG.mjs";import"./chunk-P42X3B4D.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-VXHDBYMI.mjs";import"./chunk-ENLBYECD.mjs";import"./chunk-PA3MKJVH.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-ZLZRU6MO.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-PNCONNFJ.mjs";import"./chunk-CGWXQX75.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-SIOZXPFG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{h as REWIND_MUTING_STEP_WORDS,g as REWIND_STEP_WORDS,i as acceptanceRefusal,j as boundsRefusal,k as boundsRefusals,e as firedCount,m as notConfirmedRefusal,a as objectsWrittenBy,b as previewTotals,f as remakeUnasked,d as rewindStepsOf,c as selectionDiff,l as undeletableUnattendedRefusal};
@@ -1,9 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as Ne,b as Fe}from"./chunk-TYYOBZMU.mjs";import{a as xe,b as be,c as $e}from"./chunk-RH3N2H7P.mjs";import{a as ue,b as Le,c as De}from"./chunk-TUACWKIH.mjs";import{a as Ue}from"./chunk-4TLYUZD5.mjs";import{b as S}from"./chunk-CA5NAXSU.mjs";import{$c as ae,_c as Pe,ac as ie,ad as Ce,dd as ce,ed as Me,fd as ve,gd as _e,j as Re,vb as Ie}from"./chunk-B45CNPUX.mjs";import{b as q,e as Ae,k as B,l as J,v as Oe,z as X}from"./chunk-7EANH5PY.mjs";var Y=class e{static DEFAULT_MAX_PER_ORG=5;static DEFAULT_RECYCLE_INTERVAL=900*1e3;connections=new Map;config;cleanupTimer;recycleTimer;maxPerOrg;recycleIntervalMs;latencySamples=new Map;constructor(t,n){this.config={maxConnections:t?.maxConnections??10,keepAliveInterval:t?.keepAliveInterval??6e4,connectionTimeout:t?.connectionTimeout??3e4,idleTimeout:t?.idleTimeout??3e5},this.maxPerOrg=n?.maxPerOrg??e.DEFAULT_MAX_PER_ORG,this.recycleIntervalMs=n?.recycleIntervalMs??e.DEFAULT_RECYCLE_INTERVAL}acquire(t,n,s){let r=this.connections.get(t);if(r&&r.active)return r.lastUsedAt=Date.now(),r.accessToken=s,r;this.connections.size>=this.config.maxConnections&&this.evictOldest();let o={orgId:t,instanceUrl:n,accessToken:s,createdAt:Date.now(),lastUsedAt:Date.now(),active:!0};return this.connections.set(t,o),o}release(t){let n=this.connections.get(t);n&&(n.lastUsedAt=Date.now())}remove(t){return this.latencySamples.delete(t),this.connections.delete(t)}get(t){return this.connections.get(t)}get size(){return this.connections.size}getConfig(){return{...this.config}}getMaxPerOrg(){return this.maxPerOrg}recordLatency(t,n){if(!Number.isFinite(n)||n<0)return;let s=this.latencySamples.get(t);s||(s=[],this.latencySamples.set(t,s)),s.push(n),s.length>1e3&&s.splice(0,s.length-1e3)}getLatencyMetrics(t){let n=this.latencySamples.get(t);if(!n||n.length===0)return;let s=[...n].sort((f,c)=>f-c),r=s.reduce((f,c)=>f+c,0),o=Math.floor(s.length*.95),i=Math.floor(s.length*.99);return{min:s[0],max:s[s.length-1],avg:Math.round(r/s.length),p95:s[Math.min(o,s.length-1)],p99:s[Math.min(i,s.length-1)],sampleCount:s.length}}getAllLatencyMetrics(){let t=new Map;for(let n of this.latencySamples.keys()){let s=this.getLatencyMetrics(n);s&&t.set(n,s)}return t}cleanupIdle(){let t=Date.now(),n=0;for(let[s,r]of this.connections)t-r.lastUsedAt>this.config.idleTimeout&&(this.connections.delete(s),n++);return n}recycleStale(){let t=Date.now(),n=0;for(let[s,r]of this.connections)t-r.createdAt>this.recycleIntervalMs&&(r.active=!1,this.connections.delete(s),n++);return n}startCleanup(){this.stopCleanup(),this.cleanupTimer=setInterval(()=>this.cleanupIdle(),this.config.keepAliveInterval)}stopCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0)}startRecycling(){this.stopRecycling(),this.recycleTimer=setInterval(()=>this.recycleStale(),this.recycleIntervalMs)}stopRecycling(){this.recycleTimer&&(clearInterval(this.recycleTimer),this.recycleTimer=void 0)}evictOldest(){let t,n=1/0;for(let[s,r]of this.connections)r.lastUsedAt<n&&(n=r.lastUsedAt,t=s);t&&this.connections.delete(t)}dispose(){this.stopCleanup(),this.stopRecycling(),this.connections.clear(),this.latencySamples.clear()}};var Z=class{state="closed";failureCount=0;lastFailureTime=0;halfOpenSuccesses=0;halfOpenInFlight=0;config;constructor(t){this.config={failureThreshold:t?.failureThreshold??5,resetTimeout:t?.resetTimeout??6e4,halfOpenRequests:t?.halfOpenRequests??1}}getState(){return this.state==="open"&&this.shouldTransitionToHalfOpen()&&(this.state="half_open",this.halfOpenSuccesses=0),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t==="half_open"?this.halfOpenInFlight<this.config.halfOpenRequests:!1}recordSuccess(){this.state==="half_open"?(this.halfOpenSuccesses++,this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1),this.halfOpenSuccesses>=this.config.halfOpenRequests&&this.reset()):this.failureCount=0}recordFailure(){this.failureCount++,this.lastFailureTime=Date.now(),this.state==="half_open"?this.trip():this.failureCount>=this.config.failureThreshold&&this.trip()}trip(){this.state="open",this.lastFailureTime=Date.now()}reset(){this.state="closed",this.failureCount=0,this.halfOpenSuccesses=0,this.halfOpenInFlight=0}getFailureCount(){return this.failureCount}acquirePermit(){return this.canExecute()?(this.getState()==="half_open"&&this.halfOpenInFlight++,!0):!1}releasePermit(){this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1)}getConfig(){return{...this.config}}shouldTransitionToHalfOpen(){return Date.now()-this.lastFailureTime>=this.config.resetTimeout}};var je=["INVALID_SESSION_ID","INVALID_AUTH_HEADER","SESSION_EXPIRED"];function He(e){if(typeof e=="object"&&e!==null){let{errorCode:n,statusCode:s}=e;if(typeof n=="string"&&je.includes(n)||s===401)return!0}let t=S(e);return je.some(n=>t.includes(n))||t.includes("Session expired")?!0:/\b401\b/.test(t)&&/unauthorized/i.test(t)}var ze=0;function Sn(){return ze}async function de(e,t){let n=$e(e);try{return await t()}finally{ze+=n()}}var L=class extends Error{constructor(n,s,r){super(`${n}: ${r}`);this.code=n;this.orgId=s;this.name="OrgConnectionError"}code;orgId};import{homedir as yt,userInfo as Et}from"node:os";var kt=[/^ELECTRON_.+$/,/^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,/^SNAP(|_.*)$/,/^GDK_PIXBUF_.+$/],qe=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED"];function We(e){return kt.some(t=>t.test(e))}function le(e=process.env){let t={};for(let[n,s]of Object.entries(e))We(n)||(t[n]=s);return t.NO_COLOR="1",t}function Rn(e=process.env){let t=Object.keys(e).filter(c=>(e[c]??"")!==""),n=qe.filter(c=>t.some(d=>d.toUpperCase()===c)),s=t.filter(c=>/^(SF|SFDX)_/i.test(c)).sort(),r=t.filter(c=>We(c)),o=r.filter(c=>c.startsWith("ELECTRON_")).sort(),i=r.length-o.length,f=r.length===0?"none":[...o,...i>0?[`${i} VSCODE_ or other VS Code variables`]:[]].join(", ");return`set: ${n.length>0?n.join(", "):"none of "+qe.join(", ")}; SF_/SFDX_: ${s.length>0?s.join(", "):"none"}; not passed to sf, as a terminal does not get them: ${f}`}function St(){try{return Et().username}catch{return process.env.USERNAME??process.env.USER??""}}function Be(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(e,t=yt(),n=St()){let s=e;return t.length>3&&(s=s.replace(new RegExp(Be(t),"gi"),"~")),n.length>=2&&(s=s.replace(new RegExp(`(?<=[\\\\/])${Be(n)}(?=[\\\\/]|$)`,"gim"),"<user>")),s.replace(/00D\w{12,15}![\w.]+/g,"<token>").replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g,"<username>")}function In(e){return e.split(/\r?\n/).map(t=>t.trim()).find(t=>t.length>0)}function Tt(e,t){if(process.platform!=="win32")return e[0];let s=(Object.entries(t).find(([r])=>r.toUpperCase()==="PATHEXT")?.[1]??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);return e.find(r=>{let o=r.lastIndexOf(".");return o>Math.max(r.lastIndexOf("\\"),r.lastIndexOf("/"))&&s.includes(r.slice(o).toLowerCase())})}async function Pn(e=1e4){let{exec:t}=await import("child_process"),{promisify:n}=await import("util"),s=process.platform==="win32"?"where sf node":"which -a sf node",r=le(),o,i;try{let g=await n(t)(s,{timeout:e,windowsHide:!0,env:r});o=String(g.stdout)}catch(g){let a=g;o=String(a.stdout??""),o.trim()===""&&(i=Je(a.message??String(g)))}let f=o.split(/\r?\n/).map(g=>g.trim()).filter(g=>g.length>0).map(g=>Je(g)),c=g=>f.filter(a=>new RegExp(`(^|[\\\\/])${g}(\\.[A-Za-z0-9]+)?$`,"i").test(a)),d=c("sf"),u=Tt(d,r);return{sf:d,node:c("node"),...u!==void 0?{runs:u}:{},...i?{failure:i}:{}}}var At=10*1024*1024,he=3e4,Ve=he+2e3,ge=`sf did not answer within ${he/1e3} s \u2014 check the Salesforce CLI`;function Ge(e){return e instanceof Error&&e.message===ge}var fe=2e4;function Q(e,t,n){let s,r=new Promise((o,i)=>{s=setTimeout(()=>i(new Error(n)),t)});return Promise.race([e,r]).finally(()=>clearTimeout(s))}var D=new Y,Ot=300*1e3,K=new Map,Rt={failureThreshold:3,resetTimeout:3e4},Xe=new Map;function Fn(){return D}function It(e){let t=Xe.get(e);return t||(t=new Z({...Rt}),Xe.set(e,t)),t}var Ye;var pe="panel";function jn(e){pe=e}function Pt(e,t=pe){return t==="panel"?"Reconnect it on the Organizations page (Try Reconnect on its card).":`Sign in to it again with "sf org login web --alias ${e}" (in a CI job, "sf org login jwt" or "sf org login sfdxurl"), then run the command again, with its --resume if it stopped a run part way.`}function Ze(e=pe){return e==="panel"?"Create a new one and import it.":'Create a new one ("sf org create scratch") and give its alias.'}function Ke(e,t){let n=t?.organization_id;if(!(!Ye||typeof n!="string"))try{Ye(e,{organizationId:n})}catch(s){Ue.warn("Identity observer threw",{orgId:e,error:S(s)})}}var Ct="[REDACTED]";function Qe(e){return typeof e=="string"&&e.length>0&&!e.startsWith(Ct)&&!/\s/.test(e)}async function Mt(e){if(!/^[\w.@+-]+$/.test(e))throw new Error(`Invalid username format: "${e}"`);let{execFile:t,exec:n}=await import("child_process"),{promisify:s}=await import("util"),r={maxBuffer:At,timeout:he,windowsHide:!0,env:le()},o=a=>Q(s(t)("sf",a,r),Ve,ge),i=a=>{let h=!1,m,E=new Promise((T,M)=>{m=n(a,r,(k,R)=>{h=!0,k?M(k):T({stdout:R})})});return Q(E,Ve,ge).catch(T=>{throw!h&&m?.pid!==void 0&&t("taskkill",["/pid",String(m.pid),"/T","/F"],{windowsHide:!0},()=>{}),T})},f=(a,h)=>process.platform==="win32"?i(a):o(h),c=(a,h)=>{let m=a.replace(/\[[0-9;]*m/g,""),E=m.search(/[{[]/);if(E===-1)throw new Error(`Failed to parse "${h}" output: no JSON found. Ensure Salesforce CLI (sf) is installed and the org is authenticated.`);return JSON.parse(m.slice(E)).result??{}},d;try{let{stdout:a}=await f(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),h=c(a,"sf org display");d=typeof h.instanceUrl=="string"?h.instanceUrl:void 0}catch(a){if(Ge(a))throw a;d=void 0}try{let{stdout:a}=await f(`sf org auth show-access-token -o "${e}" --json`,["org","auth","show-access-token","-o",e,"--json"]),h=c(a,"sf org auth show-access-token");if(Qe(h.accessToken))return{accessToken:h.accessToken,instanceUrl:d}}catch(a){if(Ge(a))throw a}let{stdout:u}=await f(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),g=c(u,"sf org display");if(!Qe(g.accessToken))throw new Error('Neither "sf org auth show-access-token" nor "sf org display" returned an access token. The org session may have expired \u2014 try re-authenticating with "sf org login".');return!d&&typeof g.instanceUrl=="string"&&(d=g.instanceUrl),{accessToken:g.accessToken,instanceUrl:d}}async function Hn(e,t){let{jsforce:n}=await import("./chunk-GAM726CK.mjs");return new n.Connection({instanceUrl:e.instanceUrl,accessToken:e.accessToken??void 0,version:e.version,callOptions:{client:t}})}async function zn(e){let{jsforce:t}=await import("./chunk-GAM726CK.mjs");return new t.Connection({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:e.version})}async function qn(e,t,n){let{jsforce:s}=await import("./chunk-GAM726CK.mjs"),r=e,o=n.getOrg(e);if(!o)throw new Error(`Org not found: ${e}`);let i=await t.getCredentials(e);if(!i?.accessToken||!i.instanceUrl)throw new Error(`No credentials for org "${o.alias}" (${e}). Reconnect the org.`);let f=o.metadata.apiVersion||Re.DEFAULT_API_VERSION,c=D.get(r),d=Date.now()-(K.get(e)??0)<Ot;if(c&&c.active&&c.accessToken===i.accessToken&&d)return c.lastUsedAt=Date.now(),new s.Connection({instanceUrl:c.instanceUrl,accessToken:c.accessToken,version:f});let u=new s.Connection({instanceUrl:i.instanceUrl,accessToken:i.accessToken,version:f}),g=It(e);if(!g.acquirePermit())throw new L("ORG_TEMPORARILY_UNREACHABLE",e,`"${o.alias}" failed several times in a row, so SandForge waits a moment before calling it again. Try again in a minute.`);let a=Date.now(),h=`identity check did not answer within ${fe/1e3} s`;try{let m=await de(u,()=>Q(u.identity(),fe,h)),E=Date.now()-a;return g.recordSuccess(),D.acquire(r,i.instanceUrl,i.accessToken),D.recordLatency(r,E),K.set(e,Date.now()),Ke(e,m),u}catch(m){let E=Date.now()-a;if(D.remove(r),K.delete(e),He(m))try{let k=await Mt(o.username),R=k.instanceUrl??i.instanceUrl;if(k.accessToken===i.accessToken&&R===i.instanceUrl)throw new Error("sf CLI token store is stale too (same expired token) \u2014 re-authenticate the org");let x=new s.Connection({instanceUrl:R,accessToken:k.accessToken,version:f}),re=await de(x,()=>Q(x.identity(),fe,h));return await t.saveOrg(o,{...i,accessToken:k.accessToken,instanceUrl:R}),g.recordSuccess(),D.acquire(r,R,k.accessToken),D.recordLatency(r,E),K.set(e,Date.now()),Ke(e,re),x}catch(k){g.recordFailure();let R=S(k);n.updateStatus(e,"expired");let x=ie(o,new Date().toISOString().slice(0,10));throw x!==void 0?new L("SCRATCH_ORG_EXPIRED",e,`The scratch org "${o.alias}" expired on ${x}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${Ze()} (cause: ${R})`):new L("ORG_AUTH_EXPIRED",e,`The session with "${o.alias}" has expired and could not be renewed. ${Pt(o.alias)} (cause: ${R})`)}g.recordFailure();let T=S(m),M=ie(o,new Date().toISOString().slice(0,10));throw M!==void 0?(n.updateStatus(e,"expired"),new L("SCRATCH_ORG_EXPIRED",e,`The scratch org "${o.alias}" expired on ${M}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${Ze()} (cause: ${T})`)):new Error(`Connection failed for "${o.alias}": ${T}`)}finally{g.releasePermit()}}import{randomUUID as vt}from"node:crypto";import{hostname as _t,homedir as xt,uptime as bt}from"node:os";import{mkdir as $t,readFile as at,readdir as Ut,rename as ct,writeFile as Lt}from"node:fs/promises";import{dirname as me,join as ye}from"node:path";function et(e){let t=e,n=typeof t?.errorCode=="string"?t.errorCode:typeof t?.name=="string"?t.name:void 0;return{success:!1,errors:[{...n?{statusCode:n}:{},message:S(e)}]}}function tt(e){return(Array.isArray(e)?e[0]:e)??{success:!1,errors:[{message:"the org answered nothing"}]}}function ts(e){return{typeOrg:()=>xe(e),query:async t=>({records:(await e.query(t)).records}),identity:async()=>{let t=await e.identity();return{user_id:t.user_id,organization_id:t.organization_id}},createAssignment:async t=>e.sobject("PermissionSetAssignment").create(t,{headers:Ie()}).then(tt,et),deleteAssignment:async t=>e.sobject("PermissionSetAssignment").destroy(t).then(tt,et)}}var j=class extends Error{constructor(n){super(n.message);this.refusal=n;this.name="MuteRefusedError"}refusal;get code(){return this.refusal.code}};function Dt(e){return e instanceof j||e instanceof Error&&e.name==="MuteRefusedError"&&"refusal"in e}var Nt=60,Ft=5*6e4,jt=3e4,Ht=6e4,zt=200,qt=448,Bt=384,se=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,H=q().regex(se),Jt=J({id:H,permissionSetId:H,permissionSet:q().min(1).max(255)}),Wt=J({runId:q().min(1).max(255),host:q().min(1).max(255),pid:Ae().int().nonnegative(),hostStartedAt:X.datetime({offset:!0}),acquiredAt:X.datetime({offset:!0}),endsAt:X.datetime({offset:!0}),needs:B(H),assigning:B(H),created:B(Jt)}),ut=J({version:Oe(1),organizationId:H,userId:H,leases:B(Wt)}),Vt=J(Ne),Gt=Fe(e=>{let t=Vt.safeParse(e);return t.success?t.data:void 0});function dt(e=process.env,t=xt()){let n=e.SANDFORGE_MUTE_LEASES_DIR;return n!==void 0&&n.trim()!==""?n:ye(t,".sandforge","mute-leases")}function Xt(e,t,n){if(!se.test(t)||!se.test(n))throw new Error("A mute lease is journaled under an org id and a user id.");return ye(e,`${t.slice(0,15)}-${n.slice(0,15)}.json`)}var lt={host:_t(),pid:ue.pid,startedAt:ue.startedAt},Yt=6e4,N=new Set;function ft(e,t,n){return`${e}
8
- ${t}
9
- ${n}`}function Zt(e,t,n,s={}){let r=s.now?.()??Date.now();if(!(Date.parse(e.endsAt)>r)||e.assigning.length>0)return!1;if(e.host!==n.host)return!0;if(e.pid===n.pid&&e.hostStartedAt===n.startedAt)return N.has(ft(t,e.runId,e.acquiredAt));let o=s.bootedAt?.()??Date.now()-bt()*1e3,i=Date.parse(e.hostStartedAt);return Number.isFinite(i)&&i<o-Yt?!1:(s.isAlive??De)(e.pid)}var Kt=e=>new Promise(t=>setTimeout(t,e));function ee(e,t,n){let s=n?.code;return new Error(`The journal of the mute leases in ${me(e)} could not be ${t}${typeof s=="string"?` (${s})`:""}: the user SandForge runs as must read and write that folder, or SANDFORGE_MUTE_LEASES_DIR name another, the same for every run that mutes the org.`)}function Qt(e,t){let n=Date.parse(e.acquiredAt);return{pid:e.pid,host:e.host,here:e.host===t.host,until:new Date((Number.isFinite(n)?n:Date.now())+Le).toISOString()}}function gt(e){return"A run locks it only while it takes, renews or ends a lease of the same org and user, but "+(e.here?`a lock its process could not remove holds until that process has ended, ${e.until} at the latest.`:`a lock a process of another machine could not remove holds until ${e.until}.`)}function en(e){return`nothing was assigned. ${gt(e)} Run again in a moment, or end process ${e.pid} and run again should none of its runs be muting this org.`}async function te(e,t,n,s,r=en,o=Ht){let i=n.self??lt,f={self:i,...n.checks?{checks:n.checks}:{}},c=Date.now()+o;for(await $t(me(e),{recursive:!0,mode:qt}).catch(d=>{throw ee(e,"made",d)});;){let d;try{d=Gt.acquire(`${e}.lock`,u=>u,f)}catch(u){throw ee(e,"locked",u)}if("lock"in d)try{let u=await tn(e,t).catch(a=>{throw ee(e,"read",a)});return await s(u,async a=>{let h=`${e}.${process.pid}-${vt()}.tmp`;try{await Lt(h,JSON.stringify(a,null,2),{encoding:"utf8",mode:Bt}),await ct(h,e)}catch(m){throw ee(e,"written",m)}})}finally{d.lock.release()}if(Date.now()>c){let u=Qt(d.busy,i);throw new j({code:"MUTE_FAILED",message:`The journal of the mute leases in ${me(e)} stayed locked for a minute by process ${u.pid} on ${u.host}: ${r(u)}`})}await Kt(zt)}}async function tn(e,t){let n={version:1,...t,leases:[]},s;try{s=await at(e,"utf8")}catch(r){if(r.code==="ENOENT")return n;throw r}try{let r=ut.safeParse(JSON.parse(s));if(r.success)return r.data}catch{}return await ct(e,`${e}.${Date.now()}.unreadable`).catch(()=>{}),n}var nn=new Set(["ENTITY_IS_DELETED","INVALID_CROSS_REFERENCE_KEY","NOT_FOUND"]);async function ne(e,t,n,s){let r=t.leases.filter(u=>u!==n&&s(u)),o=[...n.created],i=new Set,f=n.assigning[0];if(f!==void 0){let u=new Set(t.leases.flatMap(a=>a===n?[]:a.created.map(h=>h.id))),g=await e.query(`SELECT Id, PermissionSetId, PermissionSet.Name FROM PermissionSetAssignment WHERE AssigneeId = '${t.userId}' AND PermissionSetId IN ('${f}')`).then(a=>a.records).catch(()=>[]);for(let a of g){let h=typeof a.Id=="string"?a.Id:void 0,m=typeof a.PermissionSetId=="string"?a.PermissionSetId:void 0;if(!h||!m||u.has(h)||o.some(T=>T.id===h))continue;let E=a.PermissionSet;o.push({id:h,permissionSetId:m,permissionSet:typeof E?.Name=="string"?E.Name:m}),i.add(h)}}let c={removed:[],passed:[],left:[],found:[]};for(let u of o){let g=r.find(m=>m.needs.includes(u.permissionSetId));if(g){g.created.some(m=>m.id===u.id)||g.created.push(u),c.passed.push(u);continue}let a=await e.deleteAssignment(u.id),h=a.errors?.[0]?.statusCode??a.errors?.[0]?.errorCode;a.success||h!==void 0&&nn.has(h)?(c.removed.push(u),i.has(u.id)&&c.found.push(u)):c.left.push({...u,why:a.errors?.[0]?.message??h??"the org refused the delete"})}let d=t.leases.indexOf(n);return c.left.length===0?t.leases.splice(d,1):t.leases[d]={...n,endsAt:new Date(0).toISOString(),needs:[],assigning:[],created:c.left.map(({id:u,permissionSetId:g,permissionSet:a})=>({id:u,permissionSetId:g,permissionSet:a}))},c}function F(e){return e.map(t=>t.permissionSet)}function nt(e,t){let n=r=>F(r).join(", "),s=[];return e.removed.length>0&&s.push(`What this run had assigned was taken back: ${n(e.removed)}.`),e.passed.length>0&&s.push(`${n(e.passed)} stays assigned for another run that mutes this org as the same user${t?", which takes it back as it ends":""}.`),e.left.length>0&&s.push(`${e.left.map(r=>`${r.permissionSet} (${r.why})`).join(", ")} could not be taken back${t?": the next run that mutes this org takes it back":""}.`),s}function st(e,t){return`The journal still names this run's lease: this process tries again while it runs, and releases the lease once the journal can be written; the next run that mutes this org from another process releases it at the latest once process ${e} has ended.`+(t?` Until it is released, and before ${t.until}, a run of another process that ends may leave what it holds of ${t.sets.join(", ")} assigned for that lease, which the release takes back.`:"")}function ht(e){let t=e.length===1?"it":"them";return`found assigned to the user the run writes as for a run whose process ended as it assigned ${t}; found by user and set, not by id: had an admin assigned ${t} to that user since, theirs went with ${t}`}async function sn(e,t,n){let s=[];for(let r of[...t.leases])n(r)||s.push(...(await ne(e,t,r,n)).found);return s}async function rn(e){let t;try{t=(await e.query("SELECT PermissionsAssignPermissionSets, PermissionsManageUsers FROM UserPermissionAccess")).records[0]}catch(n){return`the org would not say whether the user the run writes as may assign permission sets (${S(n)})`}if(!(t?.PermissionsAssignPermissionSets===!0||t?.PermissionsManageUsers===!0))return"the user the run writes as cannot assign permission sets (neither Assign Permission Sets nor Manage Users)"}function rt(e){let t=e.indexOf("__");return t>0&&!e.slice(t+2).includes("__")?{namespace:e.slice(0,t),developerName:e.slice(t+2)}:{namespace:"",developerName:e}}var ot=/^[A-Za-z][A-Za-z0-9_]*$/;async function on(e,t){let s=t.map(rt).filter(i=>ot.test(i.developerName)&&(!i.namespace||ot.test(i.namespace)));if(s.length===0)return new Map;let r=await e.query("SELECT Id, Name, NamespacePrefix FROM PermissionSet WHERE Name IN ("+[...new Set(s.map(i=>`'${i.developerName}'`))].join(", ")+")"),o=new Map;for(let i of t){let{namespace:f,developerName:c}=rt(i),d=r.records.find(u=>String(u.Name??"").toLowerCase()===c.toLowerCase()&&String(u.NamespacePrefix??"").toLowerCase()===f.toLowerCase());typeof d?.Id=="string"&&o.set(i,d.Id)}return o}async function it(e,t,n){if(n.length===0)return new Map;let s=await e.query(`SELECT Id, PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId = '${t}' AND PermissionSetId IN (${n.map(o=>`'${o}'`).join(", ")})`),r=new Map;for(let o of s.records){let i=o.PermissionSetId,f=o.Id;typeof i=="string"&&typeof f=="string"&&r.set(i,f)}return r}function we(e,t,n){return{state:t,assigned:[],held:[],permissions:ae(e),silenced:e.silenced.map(s=>({...s})),stillRan:e.stillRuns.map(s=>({...s})),...e.assign.length>0?{alsoLifted:(e.alsoLifts??[]).map(s=>({...s}))}:{},...e.liftsUnread?{liftsUnread:e.liftsUnread.map(s=>({...s}))}:{},...n?{reason:n}:{}}}var pt="nothing found can be muted: no flow, process or workflow rule the run fires has a bypass a permission set of the target holds; the run goes on as without the option";async function an(e,t,n={}){let s,r;try{let d=await e.typeOrg();s=be(d),r=d.id}catch(d){return{refused:{code:"MUTE_PRODUCTION",message:`The target did not say what org it is (${S(d)}), and its automation is muted on no org that cannot be told from a production one. Nothing was assigned.`}}}if(s)return{refused:{code:"MUTE_PRODUCTION",message:"The target is a production org: its automation is never muted there, whatever the setting says. Nothing was assigned; run without the option."}};let{plan:o,automation:i,planned:f}=dn(t,n.writes);if(o.assign.length===0)return{plan:o,automation:t,planned:f,acquire:async()=>({outcome:f,release:async()=>f})};let c=await rn(e);return c!==void 0?{refused:{code:"MUTE_NO_RIGHT",message:`The target's automation cannot be muted: ${c}. Nothing was assigned.`}}:(mt.set(o,await un(n.dir??dt(),r)),{plan:o,automation:i,planned:f,acquire:d=>ln(e,o,d,n)})}var mt=new WeakMap,cn=/^[A-Za-z0-9]{15}-[A-Za-z0-9]{15}\.json$/;async function un(e,t){if(!se.test(t))return 0;let n=`${t.slice(0,15)}-`,s;try{s=await Ut(e)}catch{return 0}let r=0;for(let o of s)if(!(!o.startsWith(n)||!cn.test(o)))try{let i=ut.safeParse(JSON.parse(await at(ye(e,o),"utf8")));if(!i.success)continue;for(let f of i.data.leases)r+=(f.assigning.length>0?1:0)+f.created.length}catch{}return r}function dn(e,t){let n=Pe(e,t);return n.assign.length===0?{plan:n,automation:e,planned:we(n,"nothing",pt)}:{plan:n,automation:Ce(e,ae(n)),planned:we(n,"planned")}}async function ln(e,t,n,s={}){let r=s.self??lt,o=()=>s.checks?.now?.()??Date.now(),i=s.minutes??Nt,f=l=>{throw new j({code:"MUTE_FAILED",message:l})},c=await e.identity().catch(l=>f(`The target would not say who the run writes as (${S(l)}).`)),d={organizationId:c.organization_id,userId:c.user_id},u=Xt(s.dir??dt(),d.organizationId,d.userId),g=t.assign.map(l=>l.permissionSet),a=await on(e,g).catch(l=>f(`The permission sets to assign could not be read (${S(l)}).`)),h=g.filter(l=>!a.has(l));h.length>0&&f(`The target holds no permission set ${h.join(", ")}: nothing was assigned.`);let m=g.map(l=>a.get(l)),E=new Map(g.map(l=>[a.get(l),l])),T=l=>Zt(l,u,r,s.checks),M=new Date(o()).toISOString(),k=ft(u,n,M),R=!1,x=m.map(l=>E.get(l)),re=s.retryEveryMs??jt,W,Ee=(l,A)=>{if(W!==void 0)return;let p=new Set(l.map(y=>y.id)),O=!1,I=()=>clearInterval(W);W=setInterval(()=>{O||(O=!0,te(u,d,s,async(y,V)=>{let v=y.leases.find(b=>b.runId===n&&b.acquiredAt===M);if(v){v.assigning=[],v.created=[...v.created,...A.filter(U=>!v.created.some(G=>G.id===U.id))].filter(U=>!p.has(U.id));let b=await ne(e,y,v,T);for(let U of b.removed)p.add(U.id);await V(y)}I()},void 0,0).catch(()=>{}).finally(()=>{O=!1}))},re),W.unref?.()},z=await te(u,d,s,async(l,A)=>{let p=F(await sn(e,l,T)),O=await it(e,d.userId,m),I=m.filter(w=>!O.has(w)),y={runId:n,host:r.host,pid:r.pid,hostStartedAt:r.startedAt,acquiredAt:M,endsAt:new Date(o()+i*6e4).toISOString(),needs:m,assigning:[...I],created:[]};l.leases.push(y),N.add(k),await A(l),R=!0;let V=[...y.assigning],v=()=>A(l).then(()=>{V=[...y.assigning]},w=>S(w)),b=async w=>{y.assigning=[];let C=await ne(e,l,y,T);N.delete(k);let P=await v();P!==void 0&&Ee(C.removed,[...C.passed,...C.left]);let _=P!==void 0&&V.length===0?{sets:x,until:y.endsAt}:void 0,Te=nt(C,P===void 0);return f([w,...P!==void 0&&P!==w?[P]:[],...Te.length>0?Te:["Nothing was assigned."],...P!==void 0&&(C.passed.length>0||C.left.length>0||_)?[st(r.pid,_)]:[],...p.length>0?[`Taking its lease, the run took back ${p.join(", ")}, ${ht(p)}.`]:[]].join(" "))};for(let w of I){let C=await e.createAssignment({AssigneeId:d.userId,PermissionSetId:w});if(y.assigning=y.assigning.filter(_=>_!==w),C.success&&C.id){y.created.push({id:C.id,permissionSetId:w,permissionSet:E.get(w)});let _=await v();if(_!==void 0)return b(_);continue}let P=C.errors?.[0];if((P?.statusCode??P?.errorCode)==="DUPLICATE_VALUE"){let _=await v();if(_!==void 0)return b(_);continue}return b(`${E.get(w)} could not be assigned to the user the run writes as: ${P?.message??P?.statusCode??"the org refused it"}.`)}let U=await it(e,d.userId,m).catch(()=>new Map),G=m.filter(w=>!U.has(w));if(G.length>0)return b(`Read back, the user the run writes as does not hold ${G.map(w=>E.get(w)).join(", ")}.`);let wt=new Set(y.created.map(w=>w.permissionSetId));return{endsAt:y.endsAt,assigned:y.created.map(w=>w.permissionSet),held:m.filter(w=>!wt.has(w)).map(w=>E.get(w)),found:p}}).catch(l=>{if(N.delete(k),Dt(l))throw l;return f(`${S(l)}${R?"":" Nothing was assigned."}`)}),$={...we(t,"muted"),assigned:z.assigned,held:z.held,leaseEndsAt:z.endsAt,...z.found.length>0?{tookBackOfEnded:z.found}:{}},ke=s.renewEveryMs??Ft,oe=ke>0?setInterval(()=>{te(u,d,s,async(l,A)=>{let p=l.leases.find(I=>I.runId===n&&I.acquiredAt===M);if(!p||!N.has(k))return;let O=new Date(o()+i*6e4).toISOString();p.endsAt=O,await A(l),$.leaseEndsAt=O}).catch(()=>{})},ke):void 0;oe?.unref?.();let Se;return{outcome:$,release:()=>(Se??=(async()=>{oe&&clearInterval(oe);let l={};try{await te(u,d,s,async(p,O)=>{let I=p.leases.find(y=>y.runId===n&&y.acquiredAt===M);N.delete(k),I&&(l.done=await ne(e,p,I,T),await O(p))},p=>`nothing was taken back. ${gt(p)} Should none of its runs be muting this org, end process ${p.pid}`);let A=l.done?.left??[];return{...$,released:A.length===0,takenBack:F(l.done?.removed??[]),...l.done&&l.done.passed.length>0?{passed:F(l.done.passed)}:{},...A.length>0?{notTakenBack:F(A),reason:`${A.map(p=>`${p.permissionSet} (${p.why})`).join(", ")} could not be taken back: the lease ends at ${$.leaseEndsAt}, and the next run that mutes this org releases it`}:{}}}catch(A){N.delete(k);let p=l.done;if(Ee(p?.removed??[],p?[...p.passed,...p.left]:[]),p!==void 0){let O=$.leaseEndsAt,I=O!==void 0&&Date.parse(O)>o()?{sets:x,until:O}:void 0;return{...$,released:!1,takenBack:F(p.removed),notTakenBack:F([...p.passed,...p.left]),reason:[S(A),...nt({...p,removed:[]},!1),st(r.pid,I)].join(" ")}}return{...$,released:!1,takenBack:[],reason:`the assignments could not be taken back (${S(A)}): this process tries again while it runs, and takes them back once it can use the journal; past ${$.leaseEndsAt}, or once process ${r.pid} has ended, the next run that mutes this org releases the lease`}}})(),Se)}}var fn=2,gn=3;function hn(e){return!e||e.assign.length===0?0:fn+gn+2*e.assign.length+(mt.get(e)??0)}function ns(e){let t=hn(e);return t>0?{mute:t}:{}}function pn(e){return{state:"nothing",assigned:[],held:[],permissions:[],silenced:[],stillRan:[],reason:`nothing can be muted: ${e}; the run goes on as without the option`}}function ss(e){return e?{mutedAutomation:e.muted,...e.plan?{mutePlan:e.plan}:{}}:{}}async function rs(e,t,n={}){if(typeof t.unread=="string")return{automation:void 0,muted:pn(`the target's automation could not be read (${t.unread})`)};let s=await an(await e(),t,n);if("refused"in s)throw new j(s.refused);return{automation:s.automation,...s.plan.assign.length>0?{prepared:s}:{},muted:s.planned,plan:s.plan}}function os(e){let t=e?.mutedAutomation;return t!==null&&typeof t=="object"?t:void 0}function is(e,t){let n=[];e.state==="nothing"?n.push(`mute: ${e.reason??pt}`):e.state==="planned"?n.push(`mute: planned, ${e.permissions.length>0?`the permission set(s) holding ${e.permissions.join(", ")}`:"nothing"} for the user it writes as in ${t}, for the run alone; nothing is assigned yet`):n.push(`mute: ${e.assigned.length>0?`assigned ${e.assigned.join(", ")}`:"assigned nothing"}${e.held.length>0?`; ${e.held.join(", ")} held already`:""} to the user the run writes as in ${t}, for the run alone`),e.tookBackOfEnded&&e.tookBackOfEnded.length>0&&n.push(` taken back before the run: ${e.tookBackOfEnded.join(", ")}, `+ht(e.tookBackOfEnded));for(let r of e.silenced)n.push(` silenced: ${ce(r)} (bypass ${r.permission})`);for(let r of e.stillRan)n.push(` still runs: ${ce(r)} (${Me(r.why)})`);for(let r of e.alsoLifted??[])n.push(` also lifts: ${ve(r)}`);for(let r of e.liftsUnread??[])n.push(` ${_e(r)}`);let s=e.takenBack??(e.released===!0?e.assigned:[]);if(s.length>0&&n.push(` taken back: ${s.join(", ")}, as the run ended`),e.passed&&e.passed.length>0&&n.push(` stays assigned: ${e.passed.join(", ")}, for another run that mutes ${t} as the same user, which takes ${e.passed.length===1?"it":"them"} back as it ends`),e.released===!1){let r=e.notTakenBack!==void 0&&e.notTakenBack.length===0;n.push(` ${r?"lease not released":"not taken back"}: ${e.reason??"the assignments stay until the lease ends"}`)}return n}export{He as a,Sn as b,de as c,L as d,le as e,Rn as f,Je as g,In as h,Pn as i,Q as j,Fn as k,jn as l,Qe as m,Mt as n,Hn as o,zn as p,qn as q,ts as r,Dt as s,an as t,dn as u,hn as v,ns as w,ss as x,rs as y,os as z,is as A};
@@ -1,10 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{o as ht}from"./chunk-WJY54JO7.mjs";import{E as ze,d as pt,x as mt}from"./chunk-NEVXIGR6.mjs";import{a as dn,d as cn,e as ln,g as un,h as fn,i as gn,j as pn,k as gt}from"./chunk-SAR5622P.mjs";import{C as sn,v as on}from"./chunk-HJC7AIBK.mjs";import{a as Ue,b as re,d as ee,e as an,f as ft,h as z}from"./chunk-OTWRDD6L.mjs";import{c as rn}from"./chunk-EADHKH3A.mjs";import{e as mn,h as hn,i as yn}from"./chunk-PNCONNFJ.mjs";import{ca as Oe,da as ut,fa as Ee,ia as qe}from"./chunk-CGWXQX75.mjs";import{h as F}from"./chunk-TZE3Y7IQ.mjs";import{b as N}from"./chunk-CA5NAXSU.mjs";import{Db as en,Eb as fe,Ib as $e,Lb as ke,Mb as ct,Ob as lt,Pb as tn,Tb as K,nc as nn,yb as Xt}from"./chunk-B45CNPUX.mjs";import{b as x,e as ue,f as $,i as Ae,k as X,l as W,o as Be,s as Fe,v as Zt}from"./chunk-7EANH5PY.mjs";var He=class{activeJobs=new Map;maxConcurrentJobs;maxCompletedJobs=50;constructor(e=5){this.maxConcurrentJobs=e}registerJob(e){this.activeJobs.set(e.id,e)}updateJobState(e,t){let n=this.activeJobs.get(e);return n?(n.state=t,(t==="JobComplete"||t==="Failed"||t==="Aborted")&&this.purgeCompletedJobs(),!0):!1}updateJobCounts(e,t,n){let o=this.activeJobs.get(e);return o?(o.numberRecordsProcessed=t,o.numberRecordsFailed=n,!0):!1}updateTotalRecords(e,t){let n=this.activeJobs.get(e);return n?(n.totalRecords=t,!0):!1}getJob(e){return this.activeJobs.get(e)}getActiveJobs(){return Array.from(this.activeJobs.values()).filter(e=>e.state==="UploadComplete"||e.state==="InProgress")}getCompletedJobs(){return Array.from(this.activeJobs.values()).filter(e=>e.state==="JobComplete"||e.state==="Failed"||e.state==="Aborted")}canStartNewJob(){return this.getActiveJobs().length<this.maxConcurrentJobs}removeJob(e){return this.activeJobs.delete(e)}get totalJobs(){return this.activeJobs.size}purgeCompletedJobs(){let e=Array.from(this.activeJobs.entries()).filter(([,t])=>["JobComplete","Failed","Aborted"].includes(t.state));if(e.length>this.maxCompletedJobs){let t=e.slice(0,e.length-this.maxCompletedJobs);for(let[n]of t)this.activeJobs.delete(n)}}clear(){this.activeJobs.clear()}};function Rr(r,e){let t=gt(r,e);if(t.state==="Open")throw new Error(`Bulk API job ${r||"(no id)"} is still open after its close was sent`);return{state:t.state,...t.numberRecordsProcessed!==void 0?{numberRecordsProcessed:t.numberRecordsProcessed}:{},...t.errorMessage?{errorMessage:t.errorMessage}:{}}}function Je(r){return{bulk2:{createJob:e=>{let t=r.bulk2.createJob(e);return{get id(){return t.id},open:async()=>{await t.open()},uploadData:n=>t.uploadData(n),close:()=>t.close(),abort:()=>t.abort(),check:async()=>Rr(mn(t)??"",await t.check()),getAllResults:()=>t.getAllResults()}},job:(e,{id:t})=>{let n=r.bulk2.job(e,{id:t});return{check:async()=>gt(t,await n.check()),getSuccessfulResults:()=>n.getSuccessfulResults(),getAllResults:()=>n.getAllResults(),abort:()=>n.abort()}}}}}var bn=100,yt=2e3,wn=20,Rn=20,Sr=W({name:x(),label:x(),type:x(),createable:$().optional(),updateable:$().optional(),nillable:$().optional(),defaultedOnCreate:$().optional(),aggregatable:$().optional(),groupable:$().optional(),filterable:$().optional(),nameField:$().optional(),autoNumber:$().optional(),calculated:$().optional(),referenceTo:X(x()).optional()}).loose(),de=W({name:x(),label:x(),queryable:$().optional(),updateable:$().optional(),deletable:$().optional(),fields:X(Sr),childRelationships:X(W({childSObject:x(),field:x(),cascadeDelete:$().optional(),restrictedDelete:$().optional()}).loose()).optional()}).loose(),Ar=Fe(x(),Ae()),kr=W({k:Be([x(),ue(),$()]).nullable(),n:ue().int().nonnegative()}).loose();function Sn(r){return(r.createable===!0||r.updateable===!0)&&r.type!=="boolean"}function Or(r){return r.groupable===!0&&(Sn(r)||r.nameField===!0)}function Er(r,e){return e.createable===!0&&e.nillable===!1&&e.defaultedOnCreate!==!0||Xt(r,e.name)}function Qe(r,e,t){let n=N(t);r.some(o=>o.check===e&&o.message===n)||r.push({check:e,message:n})}async function Dr(r,e,t,n){let o=new Map,s=[],i=[],a=(f,l)=>{s.push({fieldApiName:f.name,label:f.label,reason:l})},d=t.filter(f=>f.aggregatable===!0),c=t.filter(f=>f.aggregatable!==!0&&f.filterable===!0);for(let f of t)f.aggregatable!==!0&&f.filterable!==!0&&a(f,"not-countable");if(n===0)for(let f of[...d,...c])o.set(f.name,0);else{for(let f=0;f<d.length;f+=bn){let l=d.slice(f,f+bn);try{let g=l.map(b=>`COUNT(${F(b.name)})`).join(", "),p=await r.query(`SELECT ${g} FROM ${e}`),m=Ar.parse(p.records[0]??{});l.forEach((b,h)=>{let R=m[`expr${h}`];if(typeof R!="number")throw new Error(`The org answered no count for ${e}.${b.name}.`);o.set(b.name,R)})}catch(g){Qe(i,"fill",g);for(let p of l)o.delete(p.name),a(p,"refused")}}for(let[f,l]of c.entries()){if(f>=Rn){a(l,"query-budget");continue}try{let g=await r.query(`SELECT COUNT() FROM ${e} WHERE ${F(l.name)} != null`);o.set(l.name,g.totalSize)}catch(g){Qe(i,"fill",g),a(l,"refused")}}}return{fields:t.filter(f=>o.has(f.name)).map(f=>({fieldApiName:f.name,label:f.label,filled:o.get(f.name)??0,required:Er(e,f)})).sort((f,l)=>f.filled-l.filled||f.fieldApiName.localeCompare(l.fieldApiName)),unmeasured:s,errors:i}}async function Ir(r,e,t,n,o){let s=[],i=n?t.find(d=>d.name.toLowerCase()===n.toLowerCase()):t.find(d=>d.name==="Email")??t.find(d=>d.nameField===!0);if(!i)return n&&s.push({check:"duplicates",message:`${e} has no field ${n} the org can group records by.`}),{duplicates:null,errors:s};let a={keyField:i.name,keyLabel:i.label,groups:[],groupCount:0,recordCount:0,truncated:!1};if(o===0)return{duplicates:a,errors:s};try{let d=await Pr(r,e,i.name),c=d.rows.map(u=>({value:String(u.value),count:u.count}));return{duplicates:{...a,groups:c.slice(0,wn),groupCount:c.length,recordCount:c.reduce((u,f)=>u+f.count,0),truncated:d.truncated},errors:s}}catch(d){return Qe(s,"duplicates",d),{duplicates:null,errors:s}}}async function Pr(r,e,t){let n=F(t),o=await r.query(`SELECT ${n} k, COUNT(Id) n FROM ${e} WHERE ${n} != null GROUP BY ${n} HAVING COUNT(Id) > 1 ORDER BY COUNT(Id) DESC LIMIT ${yt}`),s=[];for(let i of o.records){let a=kr.safeParse(i);!a.success||a.data.k===null||s.push({value:a.data.k,count:a.data.n})}return{rows:s,truncated:o.records.length>=yt}}async function Cr(r,e,t,n,o){let s=[];if(!t.some(i=>i.name==="LastModifiedDate"&&i.filterable===!0))return{stale:null,errors:s};if(o===0)return{stale:{days:n,records:0},errors:s};try{let i=await r.query(`SELECT COUNT() FROM ${e} WHERE LastModifiedDate < LAST_N_DAYS:${n}`);return{stale:{days:n,records:i.totalSize},errors:s}}catch(i){return Qe(s,"stale",i),{stale:null,errors:s}}}async function Nr(r,e,t){let n,o,s;try{if(n=de.parse(await r.describe(F(e.objectApiName))),o=F(n.name),n.queryable===!1)throw new Error(`${o} cannot be queried.`);s=(await r.query(`SELECT COUNT() FROM ${o}`)).totalSize}catch(u){return{status:"failed",objectApiName:e.objectApiName,message:N(u)}}let i=n.fields.filter(Or).sort((u,f)=>u.label.localeCompare(f.label)),[a,d,c]=await Promise.all([Dr(r,o,n.fields.filter(Sn),s),Ir(r,o,i,e.duplicateKey,s),Cr(r,o,n.fields,t,s)]);return{status:"scanned",objectApiName:e.objectApiName,label:n.label,totalRecords:s,fields:a.fields,unmeasured:a.unmeasured,duplicates:d.duplicates,stale:c.stale,keyFields:i.map(u=>({fieldApiName:u.name,label:u.label})),errors:[...a.errors,...d.errors,...c.errors]}}async function Ps(r,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 n=t().toISOString(),o=[];for(let s of e.objects)o.push(await Nr(r,s,e.staleDays));return{orgId:e.orgId,staleDays:e.staleDays,scannedAt:n,bounds:{duplicateGroupLimit:yt,duplicateSample:wn,singleFieldQueries:Rn},objects:o}}var wt=1e4,Ve=5e4,An="DELETE_FAILED",Rt="UNABLE_TO_LOCK_ROW",kn=3,jr=2e3,On="FEATURENOTENABLED",St="ContentVersion",En="ContentDocument",At=new Set([St,En]);async function De(r,e,t,n,o="delete"){let s=!1,i={},a=0,d=0,c=(g,p)=>(d+=g,p()),u={bulk2:{createJob:g=>{let p=r.bulk2.createJob(g);return{get id(){return p.id},open:()=>c(1,()=>p.open()),uploadData:m=>c(1,()=>p.uploadData(m)),close:async()=>{await c(1,()=>p.close()),s=!0},abort:()=>c(1,()=>p.abort()),check:async()=>{let m=await c(1,()=>p.check());return i={state:m.state,message:m.errorMessage},m},getAllResults:async()=>{let m=await c(yn,()=>p.getAllResults());return a=Array.isArray(m)?m.length:(m.successfulResults?.length??0)+(m.failedResults?.length??0),m}}}}},f;try{f=await new hn().executeBulk({connection:u,bulkManager:new He(1),...n?{signal:n}:{}},e,o,t.map(g=>({Id:g})))}catch(g){if(!s){let p=g?.errorCode;return{kind:"untouched",reason:N(g),...typeof p=="string"&&p!==""?{code:p}:{},requests:d}}throw g}if(f.aborted)return{kind:"aborted",requests:d};if(i.state!=="JobComplete"&&a===0)return{kind:"untouched",reason:i.message||`job ${i.state??"not complete"}`,requests:d};let l=new Map(f.outcomes.map(g=>[g.recordIndex,g]));return{kind:"answered",requests:d,rows:t.map((g,p)=>{let m=l.get(p);return m?.success?{success:!0}:{success:!1,error:m?.error??"The job gave no result for it."}})}}function $s(r,e){let t=Je(r);return{...Ue(r,e),queryDeleted:async n=>({records:(await r.query(n,{scanAll:!0})).records}),bulkDestroy:(n,o,s)=>De(t,n,o,s),bulkHardDestroy:(n,o,s)=>De(t,n,o,s,"hardDelete")}}var kt=W({success:$(),errors:X(Be([W({statusCode:x().optional(),errorCode:x().optional(),message:x().optional()}).loose(),x()])).optional()}).loose();function ge(r){return r.slice(0,15)}function We(r){return typeof r=="string"?void 0:r.statusCode??r.errorCode}function Ot(r){if(typeof r=="string")return r;let e=We(r),t=r.message??"";return e&&t?`${e}: ${t}`:e||t||"The org gave no reason."}function be(r){return async e=>(await r.query(e)).records.filter(n=>typeof n=="object"&&n!==null)}function vr(r){return new Promise(e=>setTimeout(e,r))}function Mr(r){let e=jr*2**r;return Math.floor(e/2+Math.random()*(e/2))}async function Dn(r,e,t,n){let o=[...t];for(let s=0;s<kn;s++){let i=o.flatMap((d,c)=>d.kind==="refused"&&d.locked===!0?[c]:[]);if(i.length===0||n.stopped?.()===!0||(await(n.wait??vr)(Mr(s)),n.stopped?.()===!0))break;let a=await e(i.map(d=>r[d]));if(a===void 0)break;i.forEach((d,c)=>{let u=a[c];u&&(o[d]={...u,lockResends:s+1})})}return o}async function Et(r,e,t,n={}){if(e===St)return $r(r,t,n);let o=s=>Lr(r,e,s);return Dn(t,o,await o(t),n)}async function Lr(r,e,t){let n;try{n=await r.destroy(e,[...t])}catch(s){let i=N(s);return t.map(()=>({kind:"refused",reason:i,dependency:!1}))}let o=Array.isArray(n)?n:[n];return t.map((s,i)=>{let a=kt.safeParse(o[i]);if(a.success&&a.data.success)return{kind:"deleted"};let d=a.success?a.data.errors??[]:[];if(d.some(u=>We(u)==="ENTITY_IS_DELETED"))return{kind:"gone"};let c=d.length>0&&d.every(u=>We(u)===Rt);return{kind:"refused",reason:d.length>0?Ot(d[0]):"The org gave no reason.",dependency:d.some(u=>We(u)===An),...c?{locked:!0}:{}}})}async function Tr(r,e,t,n="recycle",o={}){let s=n==="hard"?r.bulkHardDestroy?.bind(r):r.bulkDestroy?.bind(r);if(s===void 0)return n==="hard"?{hardRefused:xr}:"untouched";let i=async d=>{let c;try{c=await s(e,d,o.signal)}catch(f){let l=N(f);return d.map(()=>({kind:"refused",reason:l,dependency:!1}))}if(c.kind==="aborted")return"aborted";if(c.kind==="untouched"){if(n!=="hard")return"untouched";if(c.code===On)return{hardRefused:_r(c.reason)};let f=`Not deleted for good: the job was not handed over \u2014 ${c.reason}`;return d.map(()=>({kind:"refused",reason:f,dependency:!1}))}let{rows:u}=c;return d.map((f,l)=>{let g=u[l];if(g?.success===!0)return{kind:"deleted"};let{code:p,message:m}=Fr(g?.error??"");return p==="ENTITY_IS_DELETED"?{kind:"gone"}:{kind:"refused",reason:p&&m?`${p}: ${m}`:g?.error||p||m||"The org gave no reason.",dependency:p===An,...p===Rt?{locked:!0}:{}}})},a=await i(t);return Array.isArray(a)?Dn(t,async d=>{let c=await i(d);return Array.isArray(c)?c:void 0},a,o):a}var xr="Records cannot be deleted for good through this connection: nothing was sent.";function _r(r){return`The user SandForge connects as may not delete records for good in this org: Salesforce refused the job before it held a record (${On}: ${r}). Nothing was deleted for good, and nothing was sent to the recycle bin instead.`}var Br="A file is never deleted for good: that takes a Bulk API job, which no file was ever sent by. Not sent.";function Fr(r){let e=/^([A-Z][A-Z0-9_]*):([\s\S]*?)(?::(?:--|[\w.,]+))?$/.exec(r.trim());return e?{code:e[1],message:e[2].trim()}:{message:r.trim()}}async function $r(r,e,t){let n;try{n=await z(r,St,["ContentDocumentId"],e)}catch(d){let c=N(d);return e.map(()=>({kind:"refused",reason:c,dependency:!1}))}let o=new Map;for(let d of n)typeof d.Id=="string"&&typeof d.ContentDocumentId=="string"&&o.set(ge(d.Id),d.ContentDocumentId);let s=[...new Set(o.values())],i=s.length>0?await Et(r,En,s,t):[],a=new Map(s.map((d,c)=>[d,i[c]]));return e.map(d=>{let c=o.get(ge(d));return c===void 0?{kind:"gone"}:a.get(c)??{kind:"refused",reason:"The org gave no answer for its document.",dependency:!1}})}function In(r){let e=[];for(let t=0;t<r.length;t+=re)e.push({ids:r.slice(t,t+re),byJob:!1});return e}function Pn(r,e,t,n="recycle"){return At.has(e)?!1:n==="hard"||r.bulkDestroy!==void 0&&t>=wt}async function qr(r,e,t,n="recycle"){let o=[],s=!At.has(e)&&(n==="hard"||r.bulkDestroy!==void 0),i=d=>{if(d.length===0)return;if(!s||n!=="hard"&&d.length<wt){o.push(...In(d));return}let c=Math.ceil(d.length/Math.ceil(d.length/Ve));for(let u=0;u<d.length;u+=c)o.push({ids:d.slice(u,u+c),byJob:!0})};if(!$e(e)||t.length===0)return i(t),o;let a=new Set;try{a=new Set([...await Ee(be(r),t)].map(ge))}catch{}return i(t.filter(d=>!a.has(ge(d)))),i(t.filter(d=>a.has(ge(d)))),o}function Cn(r){return{objectApiName:r,op:"delete"}}async function Nn(r,e,t,n,o){let s={stopped:o.stopped,...o.wait?{wait:o.wait}:{}},{stopped:i}=await pn(t,{key:Cn(e),sizes:n.sizes,allowance:n.allowance,beforeEachSend:()=>o.stopped()?"stop":void 0,send:async a=>({answers:await Et(r,e,a,s)}),limited:a=>a?.kind==="refused"?nn([a.reason]):void 0,settle:(a,d,c,u)=>{let f=[],l=[];a.forEach((g,p)=>{if(c.has(p))return;let m=d[p]??{kind:"refused",reason:"The org gave no answer for it.",dependency:!1},b=u.get(p);f.push(g),l.push(b!==void 0&&m.kind==="refused"?{...m,dependency:!1,limit:b}:m)}),f.length>0&&o.settle(f,l)}});return i!==void 0}function Dt(r,e){let t=Cn(r),n=e.sizes.report(t);if(!n)return[];let o=[];return n.rows+n.alone+n.notSplit+n.keptWhole>0&&o.push(un(n)),n.notSplit>0&&o.push(fn(n.notSplit,gn(e.allowance,t),"removal")),n.keptWhole>0?o.push(ln):n.alone>0&&o.push(cn),o}function jn(r){let e=0,t=0,n=0,o=0;for(let i of r)e++,i==="deleted"?t++:i==="gone"?n++:o++;if(e===0)return[];let s=[t>0?`${t} deleted`:"",n>0?`${n} already gone`:"",o>0?`${o} still refused`:""].filter(Boolean);return[`The org could not lock ${e} record(s) (${Rt}), each sent again up to ${kn} times, a wait before each: ${s.join(", ")}.`]}async function vn(r,e,t,n){let o=n.mode??"recycle";if(o==="hard"&&At.has(e))return t.length>0&&n.settle(t,t.map(()=>({kind:"refused",reason:Br,dependency:!1}))),{stopped:!1};let s=n.wait?{wait:n.wait}:{},i=await qr(r,e,t,o);for(let a=i.shift();a!==void 0;a=i.shift()){let{ids:d,byJob:c}=a;if(n.stopped())return{stopped:!0};if(await n.prepare?.(d),!c){if(await Nn(r,e,d,n.splitting,{stopped:n.stopped,settle:n.settle,...s}))return{stopped:!0};continue}let u=await Tr(r,e,d,o,{stopped:n.stopped,...s,...n.signal?{signal:n.signal}:{}});if(u==="aborted")return{stopped:!0};if(u==="untouched"){i.unshift(...In(d));continue}if(!Array.isArray(u))return{stopped:!0,hardRefused:u.hardRefused};n.settle(d,u)}return{stopped:!1}}async function Mn(r,e){for(let t=0,n=!0;n;t++){n=!1;for(let o of r){let s=e.idsOf(o,t);if(s.length===0)continue;if(e.stopped())return!0;let i=e.deleted(o);if(await e.send(o,s,t))return!0;e.deleted(o)>i&&(n=!0)}}return!1}async function Ke(r,e){let t=new Set(e.map(i=>i.objectApiName)),n=new Map;for(let{objectApiName:i}of e){let a;try{a=(de.parse(await r.describe(i)).childRelationships??[]).map(c=>c.childSObject)}catch{continue}for(let d of a){if(d===i||!t.has(d))continue;let c=n.get(d)??new Set;c.add(i),n.set(d,c)}}let o=[...e],s=[];for(;o.length>0;){let i=o.findIndex(a=>!o.some(d=>d!==a&&n.get(d.objectApiName)?.has(a.objectApiName)));s.push(...o.splice(i>=0?i:0,1))}return s}async function It(r,e,t){if(r.length===0)return{gone:[],unchecked:[]};let n;try{n=await e(r)}catch(i){return{gone:[],unchecked:[...r],failure:N(i)}}let o=new Set(n.map(i=>ge(String(i.Id)))),s=r.filter(i=>!o.has(ge(i)));return{gone:s.filter(t),unchecked:s.filter(i=>!t(i))}}function Ur(r){return r.filter(e=>Oe[e]!==void 0&&!ut.has(e))}async function Pt(r,e,t,n,o,s){let i=be(r),a=[];for(let{objectApiName:d}of e){let c=Oe[d];if(!c||ut.has(d))continue;let u;for await(let f of t.pages(d)){let l=f.filter(R=>n(d,R));if(l.length===0)continue;if(o())return{drafted:a,cancelled:!0};u??=await qe(i,c);let g=u,p=g?.draft;if(!g||!p)break;let m=await s(d,l),b;try{b=await z(r,d,["Status"],l)}catch{continue}let h=b.filter(R=>typeof R.Id=="string"&&!m.has(R.Id.slice(0,15))).filter(R=>{let S=g.categoryOf.get(String(R.Status));return S!==void 0&&S!=="Draft"}).map(R=>({objectApiName:d,id:String(R.Id),draft:p,status:String(R.Status)}));for(let R=0;R<h.length;R+=re){if(o())return{drafted:a,cancelled:!0};let S=h.slice(R,R+re);a.push(...S);try{await r.update(d,S.map(({id:j})=>({Id:j,Status:p})))}catch{}}}}return{drafted:a,cancelled:!1}}function Qs(r,e,t,n){if(t)return`${r} ${t.id}: ${e}`;let o=n.filter(s=>s.objectApiName===r).map(s=>`${s.id} (${s.status})`);return o.length>0?`${r}: ${e} Set to Draft, with the status each had: ${o.join(", ")}.`:`${r}: ${e}`}async function Ln(r,e,t){let n=[...new Set(e.map(o=>o.objectApiName))];for(let o of n){let s=e.filter(u=>u.objectApiName===o),i=new Map(s.map(u=>[u.id.slice(0,15),u])),a=s.map(u=>u.id),d;try{d=await z(r,o,["Status"],a)}catch(u){t.note(o,`Status set to ${s[0].draft} for the delete, and not read back to be restored: ${N(u)}`,!0);continue}let c=d.flatMap(u=>{let f=typeof u.Id=="string"?i.get(u.Id.slice(0,15)):void 0;return f&&u.Status===f.draft?[f]:[]});for(let u=0;u<c.length;u+=re){let f=c.slice(u,u+re),l;try{l=await r.update(o,f.map(({id:p,status:m})=>({Id:p,Status:m})))}catch(p){l=f.map(()=>({success:!1,errors:[N(p)]}))}let g=Array.isArray(l)?l:[l];f.forEach(({draft:p,status:m},b)=>{let h=kt.safeParse(g[b]);if(h.success&&h.data.success){t.note(o,`Status set to ${p} for the delete, then back to ${m}.`,!1,f[b]);return}let R=h.success?h.data.errors??[]:[],S=R.length>0?Ot(R[0]):"The org gave no reason.";t.note(o,`Status set to ${p} for the delete, and left there: the org refused ${m} back \u2014 ${S}`,!0,f[b])})}}}var Re="DuplicateRecordSet",zr="DuplicateRecordItem",Ge=2e3,Hr=999,Jr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function V(r){return r.slice(0,15)}function Tn(r){return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function Ct(r){return typeof r=="string"?Date.parse(r):Number.NaN}async function xn(r,e){return(await Qr(r,e)).map(t=>({id:t.id,modified:Wr(t,e)}))}async function Qr(r,e){if(!Number.isFinite(e.start)||!Number.isFinite(e.end)||!Jr.test(e.user))return[];let t;try{let d=await r.query(`SELECT Id, CreatedDate, LastModifiedDate, LastModifiedById FROM ${Re} WHERE CreatedDate >= ${Tn(e.start-2e3)} AND CreatedDate <= ${Tn(e.end+6e4)} LIMIT ${Ge}`);if(d.records.length>=Ge)return[];t=d.records.filter(c=>typeof c=="object"&&c!==null)}catch{return[]}let n=t.flatMap(d=>typeof d.Id=="string"?[d.Id]:[]);if(n.length===0)return[];let o=new Set,s=new Map,i=new Map;try{for(let d of ee(n)){let c=await r.query(`SELECT Id, RecordId, DuplicateRecordSetId, CreatedDate FROM ${zr} WHERE DuplicateRecordSetId IN (${d}) LIMIT ${Ge}`);if(c.records.length>=Ge)return[];for(let u of c.records){let f=u??{},l=f.DuplicateRecordSetId,g=f.RecordId;if(typeof l!="string")continue;let p=Ct(f.CreatedDate);Number.isFinite(p)&&!(p<=(i.get(V(l))??Number.NaN))&&i.set(V(l),p),typeof g!="string"||!e.has(V(g))?o.add(V(l)):s.set(V(l),[...s.get(V(l))??[],V(g)])}}}catch{return[]}let a=V(e.user);return t.flatMap(d=>typeof d.Id=="string"&&!o.has(V(d.Id))&&(s.has(V(d.Id))||typeof d.LastModifiedById=="string"&&V(d.LastModifiedById)===a)?[{id:d.Id,created:Ct(d.CreatedDate),modified:Ct(d.LastModifiedDate),...typeof d.LastModifiedById=="string"?{modifiedBy:d.LastModifiedById}:{},names:s.get(V(d.Id))??[],...i.has(V(d.Id))?{itemsMade:i.get(V(d.Id))}:{}}]:[])}function Wr(r,e){if((r.modifiedBy!==void 0?V(r.modifiedBy):"")===V(e.user)&&r.modified<=e.end+6e4)return Math.min(r.modified,e.end);let n=e.end+6e4;return r.names.length>0&&r.created<=n&&r.modified<=n&&(r.modified===r.created||r.modified<=(r.itemsMade??Number.NaN)+Hr)?Math.min(r.modified,e.end):r.modified}async function _n(r,e,t,n="recycle"){let o=F(e),s=new Set;try{for(let i of ee(t)){let a=await r.queryDeleted(`SELECT Id FROM ${o} WHERE Id IN (${i}) AND IsDeleted = true`);for(let d of a.records){let c=d?.Id;typeof c=="string"&&s.add(c.slice(0,15))}}}catch(i){return{error:N(i)}}return{deleted:s,inBin:n!=="hard"}}var Vr=/__kav$/i;function Ie(r){return Vr.test(r)}function Fn(r){return r.replace(/v$/i,"")}var Nt="Kept: its article holds a version the run did not write \u2014 a draft begun on it, or a version published since \u2014 which deleting the article would take with it. A removal that takes what changed since the run takes it too.",Kr={statusCode:"ENTITY_IS_DELETED",message:"The version is no longer in the org: it went with its article."},Bn=" AND IsLatestVersion = false AND PublishStatus = 'Archived'",Gr="An article version is deleted through its article, over REST.",Yr={success:!1,errors:[{message:"The org gave no reason."}]};function te(r){return r.slice(0,15)}function $n(r,e){let t=r.bulkDestroy?.bind(r);return{query:n=>r.query(n),queryDeleted:n=>r.queryDeleted(n),update:(n,o)=>r.update(n,o),serverTime:()=>r.serverTime(),userId:()=>r.userId(),describeGlobal:()=>r.describeGlobal(),describe:n=>Ie(n)?Zr(r,n):r.describe(n),destroy:(n,o)=>Ie(n)?Xr(r,n,o,e):r.destroy(n,o),...t?{bulkDestroy:(n,o,s)=>Ie(n)?Promise.resolve({kind:"untouched",reason:Gr,requests:0}):t(n,o,s)}:{}}}async function Zr(r,e){let t=await r.describe(e);if(typeof t!="object"||t===null)return t;let n;try{n=(await r.describe(Fn(e)))?.deletable}catch{n=void 0}let o={...t};return delete o.deletable,typeof n=="boolean"?{...o,deletable:n}:o}async function qn(r,e,t){let n=F(e),o=new Map,s=new Map,i=(d,c)=>{for(let u of d){let f=u;if(typeof f?.Id!="string"||typeof f.KnowledgeArticleId!="string")continue;c?.set(te(f.Id),f.KnowledgeArticleId);let l=te(f.KnowledgeArticleId),g=s.get(l)??new Set;g.add(te(f.Id)),s.set(l,g)}};for(let d of["",Bn])for(let c of ee(t)){let u=await r.query(`SELECT Id, KnowledgeArticleId FROM ${n} WHERE Id IN (${c})${d}`);i(u.records,o)}let a=[...new Set(o.values())];for(let d of["",Bn])for(let c of ee(a)){let u=await r.query(`SELECT Id, KnowledgeArticleId FROM ${n} WHERE KnowledgeArticleId IN (${c})${d}`);i(u.records)}return{articleOf:o,versions:s}}function Un({articleOf:r,versions:e},t,n){if(n.includeChanged)return new Set;let o=new Set(t.map(te)),s=i=>[...e.get(i)??[]].some(a=>!o.has(a));return new Set([...r.values()].map(te).filter(s))}async function zn(r,e,t,n){let o=await qn(r,e,t),s=Un(o,t,n);return new Set(t.map(te).filter(i=>{let a=o.articleOf.get(i);return a!==void 0&&s.has(te(a))}))}async function Xr(r,e,t,n){let o=await qn(r,e,t),{articleOf:s}=o,i=[...new Set(s.values())],a=Un(o,t,n),d=i.filter(u=>!a.has(te(u))),c=new Map;if(d.length>0){let u;try{u=await r.destroy(Fn(e),d)}catch(l){let g=N(l);u=d.map(()=>({success:!1,errors:[{message:g}]}))}let f=Array.isArray(u)?u:[u];d.forEach((l,g)=>c.set(te(l),f[g]))}return t.map(u=>{let f=s.get(te(u));return f===void 0?{success:!1,errors:[Kr]}:a.has(te(f))?{success:!1,errors:[{message:Nt}]}:c.get(te(f))??Yr})}var Ze="Quote",Ce="QuoteLineItem",Pe="Opportunity",Ne="OpportunityLineItem",Hn=2e3;function eo(r){return r.slice(0,15)}function Jn(r){return typeof r=="string"?Date.parse(r):Number.NaN}function G(r,e){let t=r[e];return typeof t=="string"&&t!==""?eo(t):void 0}function vt(r,e){return r.has(e)||r.otherParts?.has(e)===!0}function to(r,e){let t=new Set,n=new Set;for(let g of r.syncing){let p=G(g,"Id"),m=G(g,"SyncedQuoteId");!p||!m||!vt(e,p)||!e.has(m)||(t.add(m),n.add(p))}if(t.size===0)return[];let o=r.quoteLines.filter(g=>{let p=G(g,"QuoteId");return p!==void 0&&t.has(p)&&G(g,"Id")!==void 0}),s=r.opportunityLines.filter(g=>{let p=G(g,"OpportunityId");return p!==void 0&&n.has(p)&&G(g,"Id")!==void 0}),i=g=>G(g,"CreatedById"),a=(g,p)=>{let m=G(g,"Id");if(!m||vt(e,m)||!p)return!1;let b=e.user??i(p),h=Jn(g.CreatedDate);return b!==void 0&&i(g)===b&&h>=e.start&&h<=e.end},d=g=>({id:String(g.Id),modified:Jn(g.LastModifiedDate)}),c=new Map(s.flatMap(g=>{let p=G(g,"Id");return p&&e.has(p)?[[p,g]]:[]})),u=new Map;for(let g of o){let p=G(g,"Id"),m=G(g,"OpportunityLineItemId");p&&m&&e.has(p)&&!u.has(m)&&u.set(m,g)}let f=o.filter(g=>{let p=G(g,"OpportunityLineItemId");return a(g,p?c.get(p):void 0)}).map(d),l=s.filter(g=>{let p=G(g,"Id");return a(g,p?u.get(p):void 0)}).map(d);return[...f.length>0?[{objectApiName:Ce,copies:f}]:[],...l.length>0?[{objectApiName:Ne,copies:l}]:[]]}function Qn(r,e=[]){let t=new Set(r),n=t.has(Pe)||new Set(e).has(Pe);if(!t.has(Ze)||!n)return[];let o=t.has(Ce),s=t.has(Ne);return o===s?[]:[o?Ne:Ce]}async function jt(r,e,t,n,o){let s=t.map(F).join(", "),i=[];for(let a of ee(o)){let d=await r.query(`SELECT ${s} FROM ${F(e)} WHERE ${F(n)} IN (${a}) LIMIT ${Hn}`);if(d.records.length>=Hn)throw new Error(`More ${e} records than one read takes.`);for(let c of d.records)typeof c=="object"&&c!==null&&i.push(c)}return i}async function Wn(r,e,t,n){let o=n.has(Ce)||n.has(Ne),s=n.has(Pe)||e.otherParts?.objects.has(Pe)===!0;if(t.length===0||!s||!o)return[];try{let a=(await jt(r,Pe,["Id","SyncedQuoteId"],"SyncedQuoteId",t)).filter(u=>{let f=G(u,"Id");return f!==void 0&&vt(e,f)});if(a.length===0)return[];let d=await jt(r,Ce,["Id","QuoteId","OpportunityLineItemId","CreatedById","CreatedDate","LastModifiedDate"],"QuoteId",[...new Set(a.map(u=>String(u.SyncedQuoteId)))]),c=await jt(r,Ne,["Id","OpportunityId","CreatedById","CreatedDate","LastModifiedDate"],"OpportunityId",a.map(u=>String(u.Id)));return to({syncing:a,quoteLines:d,opportunityLines:c},e)}catch{return[]}}var no=5,ve=4,Xe=2e3,ro=4,nt=[["CreatedDate","LastModifiedDate","CreatedById","LastModifiedById"],["CreatedDate","LastModifiedDate","CreatedById"],["SystemModstamp"],[]],Lt=1e4,oo="005",Vn="ContentDocumentLink",so="ContentDocument",io="ContentVersion",ao=5;function rt(r){let e=new Set(r.flatMap(n=>n.ids.map(w))),t=new Map;for(let{objectApiName:n,ids:o}of r)t.set(n,[...t.get(n)??[],...o]);return{objects:[...t].map(([n,o])=>({objectApiName:n,count:o.length})),pages:async function*(n){let o=t.get(n);o&&o.length>0&&(yield o)},has:n=>e.has(n)}}function pe(r){return!Array.isArray(r)}function ki(r){return pe(r)?r.objects.reduce((e,t)=>e+t.count,0):r.reduce((e,t)=>e+t.ids.length,0)}function Oi(r){return(pe(r)?r.objects:r).map(e=>e.objectApiName)}var ot=class{bits=new Uint8Array(0);add(e){let t=e>>3;if(t>=this.bits.length){let n=new Uint8Array(Math.max(t+1,this.bits.length*2,64));n.set(this.bits),this.bits=n}this.bits[t]|=1<<(e&7)}has(e){let t=e>>3;return t<this.bits.length&&(this.bits[t]&1<<(e&7))!==0}},Tt=class{dates=new Float64Array(0);set(e,t){if(e>=this.dates.length){let n=new Float64Array(Math.max(e+1,this.dates.length*2,64)).fill(Number.NaN);n.set(this.dates),this.dates=n}this.dates[e]=t}at(e){return e<this.dates.length?this.dates[e]:Number.NaN}latestWithin(e,t){let n=Number.NaN;for(let o of this.dates)o>=e&&o<=t&&!(o<=n)&&(n=o);return n}};function je(r,e){return typeof r=="string"&&e.has(w(r))}var Kn=[{created:"CreatedDate",modified:"LastModifiedDate"},{modified:"SystemModstamp"}],Mt={ContentDocumentLink:{ends:["ContentDocumentId","LinkedEntityId"],cameWithRun:(r,e)=>{let t=r.LinkedEntityId;return je(r.ContentDocumentId,e)&&(je(t,e)||typeof t=="string"&&t.startsWith(oo))}},DuplicateRecordItem:{ends:["RecordId"],cameWithRun:(r,e)=>je(r.RecordId,e)},ContentVersion:{ends:["ContentDocumentId"],cameWithRun:(r,e)=>je(r.ContentDocumentId,e)}};function Ei(r,e){return{...Ue(r,e),serverTime:async()=>(await r.soap.getServerTimestamp()).timestamp,userId:async()=>(await r.soap.getUserInfo()).userId,queryDeleted:async t=>({records:(await r.query(t,{scanAll:!0})).records}),bulkDestroy:(t,n,o)=>De(Je(r),t,n,o)}}function xt(r,e,t){let n=new Map;for(let o of r??[]){let s=Ft(o.span,[],t);if(Number.isFinite(s.end))for(let i of o[e]??[]){let a=w(i);s.end<=(n.get(a)?.end??Number.NEGATIVE_INFINITY)||n.set(a,s)}}return n}function co(r=[],e=[]){if(r.length===0&&e.length===0)return;let t=[...r.map(({plan:n})=>pe(n)?n:rt(n)),rt(e)];return{has:n=>t.some(o=>o.has(n))}}function lo(r=[],e=[]){return new Set([...r.map(({plan:t})=>pe(t)?t.objects:t),e].flat().map(t=>t.objectApiName))}function er(r,e){return new Map([...xt(r,"wrote",e)].map(([t,{end:n}])=>[t,n]))}function tr(r,e){return`The user SandForge connects as may not delete ${r} records in this org: the ${e} record(s) of the run stay, and were not sent.`}function _t(r,e){return`Not visible: ${r} record(s) found neither in the org nor in its recycle bin, as the user the removal runs as sees them \u2014 out of that user's sight, or deleted for good \u2014 are not counted as removed`+(e?` (the recycle bin could not be read: ${e})`:".")}function Gn(r,e,t){for(let o of r){let s=o.deleted+o.alreadyGone+o.keptChanged+o.keptDependents+o.refused+(o.notVisible??0);o.planned>s&&(o.notReached=o.planned-s)}let n=new Set(r.map(o=>o.objectApiName));for(let{objectApiName:o,count:s}of e)s===0||n.has(o)||(n.add(o),r.push({...new Me(o,s,t(o)).result,notReached:s}));return r}var Di={objects:[],cancelled:!1,gone:[],stamps:{},left:async function*(){}};function w(r){return r.slice(0,15)}function uo(r){return r?.errorCode==="INVALID_FIELD"||/no such column/i.test(N(r))}function fo(r,e){let t=/no such column '(\w+)'/i.exec(N(r))?.[1],n=nt.findIndex((o,s)=>s>e&&(t===void 0||!o.includes(t)));return n===-1?nt.length:n}function q(r){return typeof r=="string"?Date.parse(r):Number.NaN}function nr(){return{modified:new Tt,missing:new Set,firstCreated:Number.NaN,lastCreated:Number.NaN,binned:new Set}}var Me=class{result;notes=[];refused=new Map;unread;held=[];goneAt=new ot;goneLater=new Set;deletedLater=new Set;notVisible=0;notVisibleNote;secondTry=new Set;filesLeft=new Map;automationHeld=new Map;automationHeldAfter=new Set;automationHeldAlong=new Set;tookAlong=new Map;cameAlong=new Map;limitNotes=[];lockResent=new Map;constructor(e,t,n=0){this.result={objectApiName:e,planned:t,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],...n>0?{platformCopies:n}:{},unchecked:[],reasons:[]}}note(e){this.notes.includes(e)||this.notes.push(e)}isGone(e,t){return this.goneAt.has(t)||this.goneLater.has(w(e))}waiting(){return[...[...this.refused].filter(([,e])=>e.dependency).map(([e])=>e),...this.held]}refusedSent(){return[...this.refused].filter(([,e])=>e.sent).map(([e])=>e)}refusedToSendAgain(){return[...this.refused].filter(([,e])=>e.sent&&e.limit!==!0).map(([e])=>e)}secondTryNote(){if(this.secondTry.size===0)return[];let e=0,t=0,n=0,o=0;for(let i of this.secondTry){let a=w(i);this.deletedLater.has(a)?e++:this.goneLater.has(a)?t++:this.refused.has(i)?o++:n++}return[`Refused at first, sent again once the rest had gone: ${[e>0?`${e} deleted`:"",t>0?`${t} already gone`:"",n>0?`${n} kept for records that stay`:"",o>0?`${o} refused again`:""].filter(Boolean).join(", ")}.`]}settle(){this.result.keptDependents=this.held.length,this.result.refused=this.refused.size+(this.unread?.count??0),this.notVisible>0&&(this.result.notVisible=this.notVisible),this.held.length===0&&(this.result.heldBy=[]);let e=this.held.flatMap(s=>{let i=this.automationHeld.get(w(s));return i?[i]:[]}),t=this.held.filter(s=>{let i=w(s);return this.automationHeld.has(i)&&this.automationHeldAfter.has(i)}).length,n=this.held.filter(s=>{let i=w(s);return this.automationHeld.has(i)&&this.automationHeldAlong.has(i)}).length;e.length>0?(this.result.heldByAutomation=e.length,t>0?this.result.heldByAutomationAfterRun=t:delete this.result.heldByAutomationAfterRun,n>0?this.result.heldByAutomationAlong=n:delete this.result.heldByAutomationAlong,this.result.automationHolders=[...new Set(e.flatMap(s=>[...s]))]):(delete this.result.heldByAutomation,delete this.result.heldByAutomationAfterRun,delete this.result.heldByAutomationAlong,delete this.result.automationHolders);let o=[...this.notVisibleNote?[this.notVisibleNote]:[],...this.notes,...this.limitNotes,...jn(this.lockResent.values()),...this.secondTryNote(),...this.unread?[this.unread.reason]:[],...[...this.refused.values()].map(s=>s.reason)];return this.result.reasons=[...new Set(o)].slice(0,no),this.filesLeft.size>0&&(this.result.filesLeft={count:this.filesLeft.size,names:[...this.filesLeft.values()].slice(0,ao)}),this.tookAlong.size>0&&(this.result.tookAlong={count:this.tookAlong.size,objects:[...new Set(this.tookAlong.values())]}),this.cameAlong.size>0&&(this.result.cameAlong={count:this.cameAlong.size,objects:[...new Set(this.cameAlong.values())]}),this.result}};async function Ii(r,e,t){let n=pe(e)?e:rt(e),o=n,s=o.objects.reduce((y,A)=>y+A.count,0),i=new Map,a=y=>i.get(y)??0,d=()=>t.signal?.aborted===!0,c=t.splitting??dn(),u=()=>({objects:Gn([],o.objects,a),cancelled:!0,gone:[],stamps:{},left:()=>Xn(n)}),f=new Map,l=new Map;for(let{objectApiName:y}of o.objects){let A=nr();f.set(y,A);let E=0;for await(let P of o.pages(y)){if(d())return u();let J=P[0];J!==void 0&&!l.has(J.slice(0,3))&&l.set(J.slice(0,3),y);let B=E;if(E+=P.length,A.error!==void 0)continue;let C=await wo(r,y,P,B,A);if(A.error!==void 0||C.length===0)continue;if(d())return u();let Q=await _n(r,y,C);if("error"in Q)A.binError=Q.error;else for(let ne of Q.deleted)A.binned.add(ne)}}let g=new Map,p=!1,m=r.bulkDestroy?.bind(r),b={query:y=>r.query(y),destroy:(y,A)=>(p=!0,r.destroy(y,A)),...m?{bulkDestroy:(y,A)=>(p=!0,m(y,A,t.signal))}:{},update:(y,A)=>(p=!0,r.update(y,A)),serverTime:()=>r.serverTime(),userId:()=>r.userId(),queryDeleted:y=>r.queryDeleted(y),describeGlobal:()=>r.describeGlobal(),describe:y=>{let A=g.get(y);return A||(A=r.describe(y),g.set(y,A)),A}},h=$n(b,{includeChanged:t.includeChanged}),R=await Ke(h,o.objects),S=await yo(h,R,(y,A)=>A-(f.get(y)?.missing.size??0)),j=new Set(S.map(y=>y.objectApiName));if(S.length>0&&t.onUndeletable&&t.previewOnly!==!0){if(d())return u();if(!await t.onUndeletable(S))return{...u(),objects:[],undeletable:S,stoppedForUndeletable:!0}}let[_,U]=await Promise.all([Ao(h),t.previewOnly===!0?void 0:ko(h)]),{start:k,end:O}=Ft(t,f.values(),_.aheadMs);if(d())return u();let I=co(t.otherParts,t.otherPartRecords),D=lo(t.otherParts,t.otherPartRecords),M=await Ro(h,o,{start:k,end:O,...t.runUserId?{user:w(t.runUserId)}:{},...I?{otherParts:{has:y=>I.has(y),objects:D}}:{},undeletable:j,snapshots:f});if(t.runUserId&&t.alongAccepted!==!0){let y=await xn(h,{has:A=>o.has(A),start:k,end:O,user:t.runUserId});y.length>0&&!o.objects.some(A=>A.objectApiName===Re)&&await rr(h,Re)&&M.push({objectApiName:Re,copies:y})}if(M.length>0){o=await So(o,M,f,l);for(let{objectApiName:y,copies:A}of M)i.set(y,A.length);s=o.objects.reduce((y,A)=>y+A.count,0),R=await Ke(h,o.objects)}let H=new Map(Object.entries(t.removalStamps??{}).map(([y,A])=>[w(y),q(A)])),v=er(t.laterParts,_.aheadMs),T=new Set;for(let{objectApiName:y}of o.objects){let A=f.get(y);if(!A||A.error!==void 0)continue;let E=0;for await(let P of o.pages(y))for(let J of P){let B=A.modified.at(E++),C=w(J);if(A.missing.has(C))continue;B<=O||B<=(H.get(C)??Number.NaN)||B<=(v.get(C)??Number.NaN)||T.add(C)}}if(t.previewOnly===!0){if(d())return u();let y=new Set,A=await po(h,o,R,{snapshots:f,changed:T,undeletable:j,includeChanged:t.includeChanged,stopped:d,copiesOf:a,...t.previewHeld===!0?{held:{notSent:y,check:new Le(h,{runRecords:o,reached:{has:()=>!1},stays:E=>y.has(E),runStart:k,runEnd:O,removalStart:_.start,removalUser:void 0,earlierRemovals:(t.removalSpans??[]).map(E=>({start:q(E.first),end:q(E.last),user:w(E.userId)})),includeChanged:t.includeChanged,previewing:!0,...t.goesWithParent?{goesWithParent:t.goesWithParent}:{},...t.goesWithParentReadBelow?{goesWithParentReadBelow:!0}:{},...t.alongAccepted?{alongAccepted:t.alongAccepted}:{},...t.runUserId?{runUser:w(t.runUserId)}:{},...t.laterParts?{linkedLater:xt(t.laterParts,"linked",_.aheadMs)}:{},...I?{otherPartRecords:I,otherPartObjects:D}:{}})}}:{}});return A?{...S.length>0?{undeletable:S}:{},objects:[],cancelled:!1,gone:[],stamps:{},left:()=>Xn(n),preview:A}:u()}let L=await bo(h,t.otherParts??[],_.aheadMs,d);if(!L)return u();let xe=new Set,hr={has:y=>o.has(y)&&xe.has(l.get(y.slice(0,3))??"")},at=new Le(h,{runRecords:o,reached:hr,stays:y=>T.has(y)&&!t.includeChanged,runStart:k,runEnd:O,removalStart:_.start,removalUser:U,earlierRemovals:(t.removalSpans??[]).map(y=>({start:q(y.first),end:q(y.last),user:w(y.userId)})),includeChanged:t.includeChanged,...t.goesWithParent?{goesWithParent:t.goesWithParent}:{},...t.goesWithParentReadBelow?{goesWithParentReadBelow:!0}:{},...t.alongAccepted?{alongAccepted:t.alongAccepted}:{},...t.alongToDraft?{alongToDraft:t.alongToDraft}:{},...t.runUserId?{runUser:w(t.runUserId)}:{},...t.automationMade?{automationMade:ir(t.automationMade)}:{},...t.laterParts?{linkedLater:xt(t.laterParts,"linked",_.aheadMs)}:{},...I?{otherPartRecords:I,otherPartObjects:D}:{}});if(d())return u();await t.beforeFirstWrite?.(),t.sweep&&await t.sweep(c)&&(p=!0);let le=[],Kt=y=>le.find(A=>A.result.objectApiName===y);async function*dt(y,A,E){for(let{objectApiName:P}of A){let J=Kt(P),B=0;for await(let C of y.pages(P)){let Q=C.filter(ne=>E(P,ne,J?.isGone(ne,B++)===!0));Q.length>0&&(yield{objectApiName:P,ids:Q})}}}let yr=()=>dt(o,R,(y,A,E)=>{let P=f.get(y),J=w(A);return P?.modifiedColumn==="LastModifiedDate"&&!P.missing.has(J)&&!T.has(J)&&!E}),_e=[],Z=async y=>{await Ln(h,_e,{note:(C,Q,ne)=>{let Y=Kt(C);if(!Y){if(!ne)return;let se=o.objects.find(ie=>ie.objectApiName===C);Y=new Me(C,se?.count??0,a(C)),le.push(Y)}Y.note(Q)}});let A=p?await Yn(h,yr(),{start:_.start,user:U}):{},E=[];if(p)for(let C of L)E.push(await Yn(h,C.unchanged(),{start:_.start,user:U}));let P=p?Oo(_,U):void 0,J=[];if(!pe(e))for await(let{ids:C}of dt(n,R,(Q,ne,Y)=>Y))for(let Q of C)J.push(Q);for(let C of le)C.limitNotes=Dt(C.result.objectApiName,c);let B=le.map(C=>C.settle());return{...S.length>0?{undeletable:S}:{},objects:y?Gn(B,R,a):B,cancelled:y,gone:J,left:()=>dt(n,n.objects,(C,Q,ne)=>!ne),stamps:A,...P?{span:P}:{},...E.length>0?{otherPartStamps:E}:{}}};if(d())return p?Z(!0):u();let Gt=async(y,A)=>(await at.heldAmong(y,A)).held,Yt=await Pt(h,R,o,(y,A)=>{let E=w(A),P=f.get(y);return P!==void 0&&P.error===void 0&&!j.has(y)&&!P.missing.has(E)&&!(T.has(E)&&!t.includeChanged)},d,Gt);if(_e=Yt.drafted,Yt.cancelled)return Z(!0);if(t.alongToDraft){let y=await Pt(h,t.alongToDraft.objects,t.alongToDraft,()=>!0,d,Gt);if(_e=[..._e,...y.drafted],y.cancelled)return Z(!0)}let ae=0;for(let{objectApiName:y,count:A}of R){if(d())return Z(!0);let E=new Me(y,A,a(y));le.push(E),xe.add(y);let P=f.get(y);if(!P||P.error!==void 0){E.unread={reason:P?.error??"The org gave no reason.",count:A},ae+=A,t.onProgress?.(ae,s,y);continue}if(j.has(y)){let Y=0,se=0;for await(let ie of o.pages(y))for(let ye of ie){let Se=w(ye),wr=Y++;P.missing.has(Se)?P.binned.has(Se)?(E.result.alreadyGone++,E.goneAt.add(wr)):E.notVisible++:se++}E.notVisible>0&&(E.notVisibleNote=_t(E.notVisible,P.binError)),se>0&&(E.unread={reason:tr(y,se),count:se}),ae+=A,t.onProgress?.(ae,s,y);continue}let J=Pn(h,y,A),B=[],C=new Map,Q=async()=>{let Y=B,se=C;return B=[],C=new Map,Zn(h,at,E,Y,{stopped:d,splitting:c,placeOf:se,onDeleted:ie=>{ae+=ie,t.onProgress?.(ae,s,y)},onHeld:ie=>{ae+=ie,t.onProgress?.(ae,s,y)}})},ne=0;for await(let Y of o.pages(y)){if(d())return Z(!0);let se=B.length;for(let ie of Y){let ye=w(ie),Se=ne++;P.missing.has(ye)?P.binned.has(ye)?(E.result.alreadyGone++,E.goneAt.add(Se)):E.notVisible++:T.has(ye)&&!t.includeChanged?E.result.keptChanged++:(B.push(ie),C.set(ye,Se))}if(E.notVisible>0&&(E.notVisibleNote=_t(E.notVisible,P.binError)),ae+=Y.length-(B.length-se),!(J&&B.length<Ve)&&await Q())return Z(!0)}if(J&&B.length>0&&(d()||await Q()))return Z(!0)}let br=le.some(y=>y.result.deleted>0);if(await Mn(le,{stopped:d,idsOf:(y,A)=>{if(A>0)return y.waiting();let E=y.refusedToSendAgain();return E.length>0||br?[...E,...y.held]:[]},send:async(y,A,E)=>{let P=new Set(E===0?y.refusedToSendAgain():[]),J=await Zn(h,at,y,A,{stopped:d,splitting:c,onSent:B=>{for(let C of B)P.has(C)&&y.secondTry.add(C)}});for(let B of y.held)P.has(B)&&y.secondTry.add(B);return J},deleted:y=>y.result.deleted}))return Z(!0);if(t.afterRemoval){if(d())return Z(!0);await t.afterRemoval(c)&&(p=!0)}for(let y of le){if(d())return Z(!0);await ho(h,y,f.get(y.result.objectApiName))}return Z(!1)}async function go(r,e,t,n,o){let{changed:s,includeChanged:i}=o,a=[];for await(let d of e.pages(t))for(let c of d){let u=w(c);!n.has(u)&&(i||!s.has(u))&&a.push(c)}try{return{kept:await zn(r,t,a,{includeChanged:i})}}catch(d){return{kept:new Set,unread:N(d)}}}async function po(r,e,t,n){let o=[],s=new Set;for(let{objectApiName:i,count:a}of t){let d=n.copiesOf(i),c={objectApiName:i,planned:a,toDelete:0,alreadyGone:0,changedSince:0,keptChanged:0,changedBy:{},undeletable:0,notVisible:0,unread:0,...d>0?{platformCopies:d}:{},reasons:[]};o.push(c);let u=n.snapshots.get(i);if(!u||u.error!==void 0){if(c.unread=a,c.reasons.push(u?.error??"The org gave no reason."),n.held)for await(let m of e.pages(i))for(let b of m)n.held.notSent.add(w(b));continue}let f=Ie(i)&&!n.undeletable.has(i)?await go(r,e,i,u.missing,n):void 0,l=[],g=[],p=m=>{n.held?.notSent.add(m)};for await(let m of e.pages(i))for(let b of m){let h=w(b);u.missing.has(h)?u.binned.has(h)?c.alreadyGone++:c.notVisible++:n.undeletable.has(i)?(c.undeletable++,p(h)):f?.unread!==void 0?(c.unread++,p(h)):n.changed.has(h)?(c.changedSince++,l.push(b),n.includeChanged?(c.toDelete++,g.push(b)):(c.keptChanged++,p(h))):f?.kept.has(h)?(c.changedSince++,c.keptChanged++,p(h)):(c.toDelete++,g.push(b))}if(n.held&&g.length>0){if(n.stopped())return;let m=await n.held.check.heldAmong(i,g),b=g.filter(R=>m.held.has(w(R)));if(b.length>0){c.toDelete-=b.length,c.keptDependents=b.length,c.heldBy=[...m.holders];for(let S of b)n.held.notSent.add(w(S));let R=b.filter(S=>m.byAutomation.has(w(S)));R.length>0&&(c.heldByAutomation=R.length)}let h=new Map;for(let R of g)if(!m.held.has(w(R)))for(let[S,j]of m.cameAlong.get(w(R))??[])h.set(S,j);h.size>0&&(c.cameAlong={count:h.size,objects:[...new Set(h.values())]}),m.reason!==void 0&&c.reasons.push(m.reason),m.unchecked.size>0&&c.reasons.push(`Not checked: what hangs from them through ${[...m.unchecked].join(", ")}, which the org deletes along but does not let be read by the record it hangs from.`)}if(f?.unread!==void 0?c.reasons.push(`Its articles could not be read: ${f.unread}`):f!==void 0&&f.kept.size>0&&c.reasons.push(Nt),c.notVisible>0&&c.reasons.push(_t(c.notVisible,u.binError)),c.undeletable>0&&c.reasons.push(tr(i,c.undeletable)),!(l.length===0||u.modifiedColumn!=="LastModifiedDate")){if(n.stopped())return;try{let m=await z(r,i,["LastModifiedById"],l,ve);for(let b of m){let h=b.LastModifiedById;typeof h!="string"||h===""||(c.changedBy[h]=(c.changedBy[h]??0)+1,s.add(h))}}catch(m){c.reasons.push(`Who changed them since the run could not be read: ${N(m)}`)}}}if(!n.stopped())return{objects:o,userNames:await mo(r,[...s])}}async function mo(r,e){let t={};if(e.length===0)return t;try{for(let n of await z(r,"User",["Name"],[...e].sort()))typeof n.Id=="string"&&typeof n.Name=="string"&&(t[n.Id]=n.Name)}catch{}return t}async function ho(r,e,t){let{gone:n,unchecked:o,failure:s}=await It(e.refusedSent(),i=>z(r,e.result.objectApiName,[],i),i=>t!==void 0&&t.error===void 0&&!t.missing.has(w(i)));for(let i of n)e.refused.delete(i),e.goneLater.add(w(i)),e.result.alreadyGone++;o.length>0&&e.note(`Not checked: ${o.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`+(s?` \u2014 ${s}`:"."))}function Pi(r,e=[],t={}){return[...new Set([...r,...Qn(r,e),...t.userKept===!0&&r.length>0?[Re]:[]])]}async function yo(r,e,t){let n=[];for(let{objectApiName:o,count:s}of e){if(o===io||s===0)continue;let i=t(o,s);if(i!==0)try{let a=de.safeParse(await r.describe(o));a.success&&a.data.deletable===!1&&n.push({objectApiName:o,records:i})}catch{}}return n}async function Yn(r,e,t){let n={},{start:o,user:s}=t;if(s===void 0||!Number.isFinite(o))return n;for await(let{objectApiName:i,ids:a}of e){let d;try{d=await z(r,i,["LastModifiedDate","LastModifiedById"],a)}catch{continue}for(let c of d)typeof c.Id=="string"&&typeof c.LastModifiedDate=="string"&&typeof c.LastModifiedById=="string"&&w(c.LastModifiedById)===s&&q(c.LastModifiedDate)>=o&&(n[c.Id]=c.LastModifiedDate)}return n}async function bo(r,e,t,n){let o=[];for(let s of e){let i=pe(s.plan)?s.plan:rt(s.plan),{end:a}=Ft(s.span,[],t),d=new Map(Object.entries(s.removalStamps??{}).map(([f,l])=>[w(f),q(l)])),c=er(s.laterParts,t),u=new Map;if(Number.isFinite(a))for(let{objectApiName:f}of i.objects){let l=new ot,g=0,p=!1;for await(let m of i.pages(f)){if(n())return;let b=g;if(g+=m.length,p)continue;let h;try{h=await z(r,f,["LastModifiedDate"],m,ve)}catch{p=!0;continue}let R=new Map;for(let S of h)typeof S.Id=="string"&&R.set(w(S.Id),q(S.LastModifiedDate));m.forEach((S,j)=>{let _=w(S),U=R.get(_);U!==void 0&&(U<=a||U<=(d.get(_)??Number.NaN)||U<=(c.get(_)??Number.NaN))&&l.add(b+j)})}p||u.set(f,l)}o.push({unchanged:async function*(){for(let{objectApiName:f}of i.objects){let l=u.get(f);if(!l)continue;let g=0;for await(let p of i.pages(f)){let m=p.filter(()=>l.has(g++));m.length>0&&(yield{objectApiName:f,ids:m})}}}})}return o}async function Zn(r,e,t,n,o){let{objectApiName:s}=t.result,i=await e.heldAmong(s,n);i.reason!==void 0&&t.note(i.reason);for(let l of i.unchecked)t.result.unchecked.includes(l)||t.result.unchecked.push(l);let a=n.filter(l=>i.held.has(w(l)));if(o.placeOf){for(let l of a)t.held.push(l);t.result.heldBy=[...new Set([...t.result.heldBy,...i.holders])]}else t.held=a,t.result.heldBy=[...i.holders];for(let l of a)t.refused.delete(l);for(let l of n){let g=w(l),p=i.byAutomation.get(g);p?t.automationHeld.set(g,p):t.automationHeld.delete(g),p&&i.automationAfter.has(g)?t.automationHeldAfter.add(g):t.automationHeldAfter.delete(g),p&&i.automationAlong.has(g)?t.automationHeldAlong.add(g):t.automationHeldAlong.delete(g)}o.onHeld?.(a.length);let d=n.filter(l=>!i.held.has(w(l))),c=new Map,u=(l,g)=>{l.forEach((p,m)=>{let b=g[m],h=w(p);if((b.lockResends!==void 0||t.lockResent.has(h))&&t.lockResent.set(h,b.kind),b.kind==="refused"){t.refused.set(p,{reason:b.reason,dependency:b.dependency,sent:!0,...b.limit?{limit:!0}:{}});return}t.refused.delete(p);let R=o.placeOf?.get(h);if(R!==void 0?t.goneAt.add(R):t.goneLater.add(h),b.kind==="deleted"){t.result.deleted++,R===void 0&&t.deletedLater.add(h);for(let S of c.get(h)??[])t.filesLeft.set(S.key,S.name);for(let[S,j]of i.along.get(h)??[])t.tookAlong.set(S,j);for(let[S,j]of i.cameAlong.get(h)??[])t.cameAlong.set(S,j)}else t.result.alreadyGone++}),o.onSent?.(l),o.onDeleted?.(l.length)},{stopped:f}=await vn(r,s,d,{stopped:o.stopped,splitting:o.splitting,prepare:async l=>{c=await e.filesOn(l)},settle:u});return f}async function wo(r,e,t,n,o){let s,i=o.modifiedColumn?Kn.filter(({modified:a})=>a===o.modifiedColumn):Kn;for(let{created:a,modified:d}of i)try{let u=await z(r,e,a?[a,d]:[d],t,ve),f=new Map;for(let g of u)typeof g.Id=="string"&&f.set(w(g.Id),q(g[d])),a&&(o.firstCreated=or(o.firstCreated,q(g[a])),o.lastCreated=Bt(o.lastCreated,q(g[a])));o.modifiedColumn=d;let l=[];return t.forEach((g,p)=>{let m=w(g),b=f.get(m);b===void 0&&(o.missing.add(m),l.push(g)),o.modified.set(n+p,b??Number.NaN)}),l}catch(c){s??=N(c)}return o.error=s,o.modifiedColumn=void 0,[]}async function*Xn(r){for(let{objectApiName:e}of r.objects)for await(let t of r.pages(e))t.length>0&&(yield{objectApiName:e,ids:[...t]})}async function Ro(r,e,t){let n=new Set(e.objects.filter(a=>a.count>0).map(a=>a.objectApiName));if(!n.has(Ze))return[];let o=[];for await(let a of e.pages(Ze))o.push(...a);let s=await Wn(r,{has:a=>e.has(a),start:t.start,end:t.end,...t.user!==void 0?{user:t.user}:{},...t.otherParts?{otherParts:t.otherParts}:{}},o,n),i=[];for(let a of s){let{objectApiName:d}=a;if(t.undeletable.has(d))continue;let c=t.snapshots.get(d);if(c){if(c.error!==void 0||c.modifiedColumn!=="LastModifiedDate")continue}else if(!await rr(r,d))continue;i.push(a)}return i}async function rr(r,e){try{let t=de.safeParse(await r.describe(e));return t.success&&t.data.deletable!==!1}catch{return!1}}async function So(r,e,t,n){let o=new Map(e.map(({objectApiName:a,copies:d})=>[a,d])),s=new Set(e.flatMap(({copies:a})=>a.map(d=>w(d.id)))),i=r.objects.map(a=>{let d=o.get(a.objectApiName);return d?{objectApiName:a.objectApiName,count:a.count+d.length}:a});for(let[a,d]of o){r.objects.some(l=>l.objectApiName===a)||i.push({objectApiName:a,count:d.length});let c=t.get(a);c||(c={...nr(),modifiedColumn:"LastModifiedDate"},t.set(a,c));let u=0;for await(let l of r.pages(a))u+=l.length;for(let l of d)c.modified.set(u++,l.modified);let f=d[0]?.id.slice(0,3);f!==void 0&&!n.has(f)&&n.set(f,a)}return{objects:i,pages:async function*(a){yield*r.pages(a);let d=o.get(a);d&&d.length>0&&(yield d.map(c=>c.id))},has:a=>r.has(a)||s.has(a)}}async function Ao(r){let e=Date.now(),t=Number.NaN;try{t=q(await r.serverTime())}catch{}return Number.isFinite(t)?{start:Math.floor(t/1e3)*1e3,aheadMs:t-(e+Date.now())/2}:{start:Number.POSITIVE_INFINITY,aheadMs:Number.NaN}}async function ko(r){try{let e=await r.userId();return typeof e=="string"&&e!==""?w(e):void 0}catch{return}}function Oo(r,e){if(!(e===void 0||!Number.isFinite(r.start)))return{first:new Date(r.start).toISOString(),last:new Date(Date.now()+r.aheadMs+Lt).toISOString(),userId:e}}function or(r,e){return Number.isNaN(r)||e<r?e:r}function Bt(r,e){return Number.isNaN(r)||e>r?e:r}var sr=999;function Eo(r,e,t){let n=Number.NaN;for(let o of r)o.lastCreated>=e&&o.lastCreated<=t&&(n=Bt(n,o.lastCreated)),n=Bt(n,o.modified.latestWithin(e,t));return n}function Ft(r,e,t){let n=Do(r,e,t),o=(r.writtenUntil?.getTime()??Number.NaN)+sr;return Number.isFinite(n.end)&&o>n.end?{...n,end:o}:n}function Do(r,e,t){let n=[...e],o=Number.NaN;for(let c of n)o=or(o,c.firstCreated);let s=r.runDurationMs??0,i=(r.runRecordedAt?.getTime()??Number.NaN)+t;if(r.runEndedAt===void 0&&Number.isFinite(i)){let c=i-s-Lt,u=i+Lt,f=r.endedByItsWrites===!0?Eo(n,c,u):Number.NaN;return{start:r.runStartedAt?.getTime()??(o>c?o:c),end:Number.isFinite(f)?Math.min(f+sr,u):u}}let a=r.runStartedAt?.getTime()??o,d=r.runEndedAt?.getTime()??a+s;return{start:a,end:d}}function ir(r){let e=new Set,t=-1;return{has:n=>(r.size!==t&&(e=new Set([...r].map(w)),t=r.size),e.has(n))}}function Ci(r,e){let t=new Le(r,{runRecords:e.runRecords,reached:{has:()=>!1},stays:()=>!1,runStart:e.runStart,runEnd:e.runEnd,removalStart:Number.POSITIVE_INFINITY,removalUser:void 0,earlierRemovals:(e.removalSpans??[]).map(n=>({start:q(n.first),end:q(n.last),user:w(n.userId)})),includeChanged:e.includeChanged,automationMade:ir(e.taken),...e.runUserId?{runUser:w(e.runUserId)}:{}});return async(n,o)=>{let s=await t.heldAmong(n,o,1);return{held:s.held,holders:[...s.holders],...s.reason!==void 0?{reason:s.reason}:{}}}}var et="IsPersonAccount",Io=50;function tt(r,e){return JSON.stringify(e.map(t=>r[t]??null))}var Le=class{constructor(e,t){this.org=e;this.context=t}org;context;worked;statuses=new Map;lockedUnder=new Map;files=new Map;datesKept=new Map;cascadeEnds=new Map;async heldAmong(e,t,n=0){let o={held:new Set,holders:new Set,otherwise:new Set,mayBeAutomation:[],byAutomation:new Map,automationAfter:new Set,automationAlong:new Set,along:new Map,cameAlong:new Map,unchecked:new Set};if(t.length===0)return o;let s;try{let l=de.parse(await this.org.describe(e)),g=await this.workedObjects(),p=e==="Account"&&l.fields.some(m=>m.name===et);s=(l.childRelationships??[]).filter(m=>(m.cascadeDelete===!0||m.restrictedDelete===!0)&&g.has(m.childSObject)).map(m=>({childSObject:m.childSObject,field:m.field,restricted:m.cascadeDelete!==!0,...p&&m.childSObject==="Contact"&&m.field==="AccountId"?{personContacts:!0}:{}}))}catch(l){return o.reason=N(l),t.forEach(g=>this.hold(o,w(g))),o}let i=[];for(let l=0;l<t.length;l+=re)i.push(t.slice(l,l+re));let a=i.length>1?await ft(s.map(l=>()=>this.anyPointing(l)),ve):s.map(()=>!0),d=s.filter((l,g)=>a[g]).flatMap(l=>i.map(g=>async()=>({relationship:l,...await this.holdingIn(l,g)}))),c=o.mayBeAutomation,u=new Map;for(let{relationship:l,holding:g,unchecked:p,automation:m,along:b,goes:h}of await ft(d,ve)){p&&o.unchecked.add(l.childSObject),(g.size>0||m.length>0)&&o.holders.add(l.childSObject),g.forEach(R=>this.hold(o,R));for(let R of m)o.held.add(w(R.parent));c.push(...m);for(let{parent:R,key:S}of b){let j=o.along.get(R)??new Map;j.set(S,l.childSObject),o.along.set(R,j)}h.length>0&&u.set(l.childSObject,[...u.get(l.childSObject)??[],...h])}if(await this.heldBelow(u,o,n),n>0)return o;this.context.previewing!==!0&&await this.lockedPastDraft(e,t,o),$e(e)&&await this.standardPricesHeld(t,o),e===lt&&await this.sellingModelOptionsHeld(t,o),this.context.alongAccepted!==!0&&await this.automationHeldBelow(c,o);let f=await this.byAutomationOnly(e,c,o.otherwise);return o.byAutomation=f.objects,o.automationAfter=f.after,o.automationAlong=f.along,o}hold(e,t){e.held.add(t),e.otherwise.add(t)}async heldBelow(e,t,n){let o=(s,i,a,d)=>{let c=s.get(i)??new Map;c.set(a,d),s.set(i,c)};for(let[s,i]of e){let a=[...new Set(i.map(c=>c.id))],d=n+1<ro?await this.heldAmong(s,a,n+1):void 0;for(let{parent:c,id:u,came:f}of i){let l=w(u);if(!d||d.held.has(l)){this.hold(t,c),t.holders.add(s),d?.holders.forEach(g=>t.holders.add(g));continue}f&&o(t.cameAlong,c,l,s);for(let[g,p]of d.along.get(l)??[])o(t.along,c,g,p);for(let[g,p]of d.cameAlong.get(l)??[])o(t.cameAlong,c,g,p)}d?.unchecked.forEach(c=>t.unchecked.add(c))}}async automationHeldBelow(e,t){let n=new Map;for(let o of e)t.otherwise.has(w(o.parent))||n.set(o.object,[...n.get(o.object)??[],o]);for(let[o,s]of n){let i=await this.heldAmong(o,[...new Set(s.map(a=>a.id))],1);for(let a of s){let d=w(a.id),c=i.mayBeAutomation.some(u=>w(u.parent)===d&&u.creator!==a.creator);!i.otherwise.has(d)&&!c||(this.hold(t,w(a.parent)),i.holders.forEach(u=>t.holders.add(u)))}i.unchecked.forEach(a=>t.unchecked.add(a))}}async byAutomationOnly(e,t,n){let o=new Map,s=new Set,i=t.filter(f=>!n.has(w(f.parent)));if(i.length===0)return{objects:o,after:s,along:new Set};let a;try{let f=await z(this.org,e,["CreatedDate","CreatedById"],[...new Set(i.map(l=>l.parent))]);a=new Map(f.flatMap(l=>typeof l.Id=="string"?[[w(l.Id),l]]:[]))}catch{return{objects:o,after:s,along:new Set}}let d=new Set,c=new Set;for(let f of i){let l=w(f.parent),g=a.get(l),p=q(g?.CreatedDate),m=g?.CreatedById,b=this.context.runUser??(typeof m=="string"?w(m):void 0),h=f.created-p;if(!(b!==void 0&&f.creator===b&&h>=-2e3&&h<=6e4)){d.add(l);continue}let S=o.get(l)??new Set;S.add(f.object),o.set(l,S),f.created>this.context.runEnd&&s.add(l),f.along||c.add(l)}for(let f of d)o.delete(f),s.delete(f);let u=new Set([...o.keys()].filter(f=>!c.has(f)));return{objects:o,after:s,along:u}}async holdingIn(e,t){let n=F(e.childSObject),o=F(e.field),[s]=ee(t,t.length),i=new Set(["Id",o,...Mt[n]?.ends??[],...e.personContacts?[et]:[]]),a=this.datesKept.get(n)??0;for(;a<nt.length;){let d=nt[a],c;try{c=await this.org.query(`SELECT ${[...i,...d].join(", ")} FROM ${n} WHERE ${o} IN (${s}) LIMIT ${Xe}`)}catch(b){uo(b)?(a=fo(b,a),this.datesKept.set(n,a)):a++;continue}if(c.records.length>=Xe)return{holding:new Set(t.map(w)),automation:[],along:[],goes:[],unchecked:!1};let u=new Set,f=[],l=[],g=[],p=new Map;for(let b of c.records){if(typeof b!="object"||b===null)continue;let h=b,R=h[e.field];if(typeof R!="string"||typeof h.Id!="string"||(n===Vn&&o==="LinkedEntityId"&&this.noteFile(h),this.lockedUnder.get(w(h.Id))===w(R)))continue;let S={onlyIncluded:!1};if(!this.stays(h,n,e.restricted,e.personContacts,S)){if(S.onlyIncluded&&l.push({parent:w(R),key:w(h.Id)}),n!==Vn&&this.goesAlongUnread(h)){let U=!(Mt[n]?.cameWithRun(h,this.context.runRecords)===!0||e.personContacts===!0&&h[et]===!0)&&!S.onlyIncluded&&S.byRemoval!==!0&&this.context.goesWithParent?.(h,this.context.runEnd)!==!0;g.push({parent:w(R),id:h.Id,came:U})}continue}let j=this.mayBeAutomation(h);if(j){let _={parent:R,id:h.Id,object:n,along:!e.restricted,...j};f.push(_),e.restricted&&p.set(h.Id,_)}else u.add(w(R))}let m=await this.ofOtherParts(n,[...p.keys()]);for(let[b,h]of p)m.has(w(b))&&(f.splice(f.indexOf(h),1),u.add(w(h.parent)));return{holding:u,automation:f,along:l,goes:g,unchecked:!1}}return{holding:new Set,automation:[],along:[],goes:[],unchecked:!e.restricted}}goesAlongUnread(e){let t=w(e.Id),{runRecords:n,otherPartRecords:o,automationMade:s,goesWithParent:i,runEnd:a}=this.context;return this.context.alongAccepted!==!0&&!n.has(t)&&o?.has(t)!==!0&&s?.has(t)!==!0&&(this.context.goesWithParentReadBelow===!0||i?.(e,a)!==!0)}async ofOtherParts(e,t){let n=new Set,{otherPartRecords:o,otherPartObjects:s,runRecords:i}=this.context;if(t.length===0||!o||!s)return n;let a=this.cascadeEnds.get(e);a||(a=(async()=>{let u=new Set;for(let f of s)try{let l=de.parse(await this.org.describe(f));for(let g of l.childRelationships??[])g.childSObject===e&&g.cascadeDelete===!0&&u.add(g.field)}catch{}return[...u]})(),this.cascadeEnds.set(e,a));let d=await a;if(d.length===0)return n;let c;try{c=await z(this.org,e,d,t)}catch{return n}for(let u of c){if(typeof u.Id!="string")continue;let f=d.flatMap(l=>{let g=u[l];return typeof g=="string"?[w(g)]:[]});f.some(l=>i.has(l))||f.some(l=>o.has(l))&&n.add(w(u.Id))}return n}mayBeAutomation(e){let{runRecords:t,runStart:n,runEnd:o,runUser:s,otherPartRecords:i}=this.context;if(typeof e.Id!="string"||t.has(w(e.Id))||i?.has(w(e.Id))===!0||typeof e.CreatedById!="string")return;let a=w(e.CreatedById);if(s!==void 0&&a!==s)return;let d=q(e.CreatedDate);if(!(d>=n-2e3&&d<=o+6e4))return;let c=q(e.LastModifiedDate),u=typeof e.LastModifiedById=="string"?w(e.LastModifiedById):void 0;if(!(c>o&&u!==void 0&&u!==a))return{created:d,creator:a}}async anyPointing(e){try{let t=F(e.childSObject),n=F(e.field);return(await this.org.query(`SELECT Id FROM ${t} WHERE ${n} != null LIMIT 1`)).records.length>0}catch{return!0}}noteFile(e){let t=e.LinkedEntityId,n=e.ContentDocumentId;if(typeof t!="string"||typeof n!="string"||je(n,this.context.runRecords))return;let o=this.files.get(w(t))??new Set;o.add(n),this.files.set(w(t),o)}async filesOn(e){let t=new Map;for(let s of e){let i=this.files.get(w(s));i&&i.size>0&&t.set(w(s),[...i])}let n=[...new Set([...t.values()].flat())];if(n.length===0)return new Map;let o=new Map;try{for(let s of await z(this.org,so,["Title"],n))typeof s.Id=="string"&&typeof s.Title=="string"&&s.Title!==""&&o.set(w(s.Id),s.Title)}catch{}return new Map([...t].map(([s,i])=>[s,i.map(a=>({key:w(a),name:o.get(w(a))??a}))]))}async lockedPastDraft(e,t,n){for(let[o,s]of Object.entries(en)){let i=s.find(l=>l.object===e)?.lookup,a=Oe[o];if(!i||!a)continue;let d=await this.statusCategoriesOf(a);if(!d)continue;let c,u;try{c=await z(this.org,e,[i],t);let l=[...new Set(c.map(g=>g[i]).filter(g=>typeof g=="string"))];u=l.length>0?await z(this.org,o,["Status"],l):[]}catch{continue}let f=new Set(u.filter(l=>{let g=d.categoryOf.get(String(l.Status));return g!==void 0&&g!=="Draft"}).map(l=>w(String(l.Id))));for(let l of c){let g=l[i];typeof l.Id!="string"||typeof g!="string"||f.has(w(g))&&(this.hold(n,w(l.Id)),n.holders.add(o),this.lockedUnder.set(w(l.Id),w(g)))}}}statusCategoriesOf(e){let t=this.statuses.get(e);return t||(t=qe(be(this.org),e),this.statuses.set(e,t)),t}async standardPricesHeld(e,t){try{let n=be(this.org),o=[...await Ee(n,e)];if(o.length===0)return;let s=await this.priceKeyFields(),i=await z(this.org,fe,s,o),a=await this.pricesOfProducts(i,s),d=a.flatMap(l=>typeof l.Id=="string"?[l.Id]:[]),c=new Set([...await Ee(n,d)].map(w)),u=new Set(e.map(w)),f=new Set;for(let l of a){if(typeof l.Id!="string")continue;let g=w(l.Id);if(c.has(g))continue;(u.has(g)?t.held.has(g):this.stays(l,fe,!0))&&f.add(tt(l,s))}for(let l of i)typeof l.Id!="string"||!f.has(tt(l,s))||(this.hold(t,w(l.Id)),t.holders.add(fe))}catch{}}async sellingModelOptionsHeld(e,t){let n=[ke,ct];try{let o=await z(this.org,lt,n,e),s=await this.pricesOfProducts(o,[...n,"IsActive"]),i=new Set(s.filter(a=>typeof a.Id=="string"&&a.IsActive===!0&&this.stays(a,fe,!0)).map(a=>tt(a,n)));for(let a of o)typeof a.Id!="string"||!i.has(tt(a,n))||(this.hold(t,w(a.Id)),t.holders.add(fe))}catch{}}async priceKeyFields(){let e=de.parse(await this.org.describe(fe)),t=new Set(e.fields.map(n=>n.name));return[ke,...[ct,tn].filter(n=>t.has(n))]}async pricesOfProducts(e,t){let n=[...new Set(e.map(i=>i[ke]).filter(i=>typeof i=="string"))],o=[...new Set(["Id",...t])].map(F).join(", "),s=[];for(let i of ee(n,Io)){let a=await this.org.query(`SELECT ${o} FROM ${fe} WHERE ${ke} IN (${i}) LIMIT ${Xe}`);if(a.records.length>=Xe)throw new Error("More prices than one read takes.");for(let d of a.records)typeof d=="object"&&d!==null&&s.push(d)}return s}stays(e,t,n=!1,o=!1,s){let i=w(e.Id),{runRecords:a,reached:d,runStart:c,runEnd:u,removalStart:f,removalUser:l,earlierRemovals:g,includeChanged:p}=this.context;if(a.has(i))return d.has(i)||this.context.stays(i);if(n)return!0;if(this.context.automationMade?.has(i)===!0||this.context.goesWithParent?.(e,u)===!0||this.context.alongToDraft?.has(i)===!0||Mt[t]?.cameWithRun(e,a))return!1;if(o&&e[et]===!0)return!(q(e.LastModifiedDate??e.SystemModstamp)<=u)&&!p;let m="CreatedDate"in e?"CreatedDate":"SystemModstamp"in e?"SystemModstamp":void 0;if(!m)return!0;let b=q(e[m]),h=q(m==="CreatedDate"?e.LastModifiedDate:e.SystemModstamp);if(!(b>=c))return!0;let R=this.context.linkedLater?.get(i);if(R&&(b<=u||b>=R.start)&&h<=R.end)return!1;let S=typeof e.CreatedById=="string"?w(e.CreatedById):void 0,j=(U,k)=>U!==void 0&&(U===l&&k>=f||g.some(O=>U===O.user&&k>=O.start&&k<=O.end));if(j(S,b))return s&&(s.byRemoval=!0),!1;if(h<=u)return!1;let _=typeof e.LastModifiedById=="string"?w(e.LastModifiedById):void 0;return b<=u&&j(_,h)?!1:(p&&s&&(s.onlyIncluded=!0),!p)}workedObjects(){return this.worked??=an(this.org),this.worked}};var Po="encryptedstring";async function Co(r){try{let[e]=await r("SELECT PermissionsViewEncryptedData FROM UserPermissionAccess");return e?.PermissionsViewEncryptedData===!0}catch{return!1}}function Mi(r){let e;return()=>(e??=Co(r),e)}function Li(r,e){let t=new Map;return n=>{let o=t.get(n);return o||(o=(async()=>{let s;try{s=(await e(n)).fields.filter(a=>a.type===Po).map(a=>a.name)}catch{return[]}return s.length>0&&!await r()?s:[]})(),t.set(n,o)),o}}var me=5,qt=25,Ut=3;function Bi(r){return{get version(){return r.version},request:async e=>await r.request(e),query:async(e,t)=>await r.query(e,{scanAll:t?.scanAll===!0}),queryMore:async e=>await r.queryMore(e)}}var oe=class extends Error{constructor(){super("The read was stopped."),this.name="OrgReadStopped"}},No="PROCESSING_HALTED",ar="If-Modified-Since",jo=/^\d{1,3}\.\d$/,vo=/^\/services\/data\/v\d{1,3}\.\d\/query(?:All)?\/[A-Za-z0-9-]+$/,Mo=W({records:X(Fe(x(),Ae())),done:$(),totalSize:ue().optional(),nextRecordsUrl:x().optional()}).loose(),Lo=W({compositeResponse:X(W({body:Ae(),httpStatusCode:ue(),referenceId:x()}).loose())}),To=X(W({errorCode:x().optional(),message:x().optional()}).loose());function xo(r,e,t){if(!jo.test(r))throw new Error(`Not an API version: ${r}`);if(e.length>me)throw new Error(`A composite runs ${me} queries, not ${e.length}`);if(e.length+t.length>qt)throw new Error(`A composite holds ${qt} subrequests, not ${e.length+t.length}`);let n=`/services/data/v${r}`;return{allOrNone:!1,compositeRequest:[...e.map((o,s)=>({method:"GET",url:o.kind==="first"?`${n}/${o.scanAll?"queryAll":"query"}?q=${encodeURIComponent(o.soql)}`:o.path,referenceId:`q${s}`})),...t.map(({path:o,headers:s},i)=>({method:"GET",url:`${n}/${o}`,referenceId:`d${i}`,...s?{httpHeaders:s}:{}}))]}}function _o(r){let e=Lo.safeParse(r);if(!e.success)return;let t=new Map;for(let n of e.data.compositeResponse){if(n.httpStatusCode<400){t.set(n.referenceId,{ok:!0,status:n.httpStatusCode,body:n.body});continue}let o=To.safeParse(n.body),s=o.success?o.data[0]:void 0;t.set(n.referenceId,{ok:!1,refused:s?[s.errorCode,s.message].filter(Boolean).join(": "):`status ${n.httpStatusCode}`,halted:s?.errorCode===No})}return t}function $t(r){let e=Mo.safeParse(r);return e.success?e.data:void 0}function Bo(r){return typeof r=="object"&&r!==null&&typeof r.errorCode=="string"}function Fo(r){let e=/^https:\/\//i.test(r)?new URL(r).pathname:r;if(!vo.test(e))throw new Error(`Not the next page of a query: ${r}`);return e}function Fi(r,e){let t=new Set,n=[],o=me,s="composite",i=0,a=!1,d=!1,c=0,u=0,f=!1,l=()=>{for(let k of t)k.state==="pending"&&(k.state="idle",k.settle?.reject(new oe));for(let k of n.splice(0))k.settle.reject(new oe)},g=()=>{d||(d=!0,queueMicrotask(()=>{d=!1,R()}))},p=(k,O)=>{k.state="idle";let I=k.settle;k.ask=void 0,k.settle=void 0,O instanceof Error?I?.reject(O):I?.resolve(O)},m=async(k,O)=>{let I=xo(r.version,k.map(v=>v.ask),O),D;u++;try{D=await r.request({method:"POST",url:"/composite",body:JSON.stringify(I),headers:{"Content-Type":"application/json"}})}catch(v){if(Bo(v)){s="single";for(let L of k)L.state="pending";n.unshift(...O);return}let T=new Error(N(v));for(let L of k)p(L,T);for(let L of O)L.settle.reject(T);return}let M=_o(D);if(!M){s="single";for(let v of k)v.state="pending";n.unshift(...O);return}let H=0;if(k.forEach((v,T)=>{let L=M.get(`q${T}`);if(L&&!L.ok&&L.halted){H++,v.state="pending";return}if(!L){p(v,new Error("The org gave no answer to this query of the composite"));return}if(!L.ok){p(v,new Error(L.refused));return}let xe=$t(L.body);p(v,xe??new Error(`The org answered a query with status ${L.status} and no page`))}),H>0){let v=k.length-H;v===0?s="single":o=Math.min(o,v)}O.forEach((v,T)=>{let L=M.get(`d${T}`);L?L.ok?v.settle.resolve(L.status===304?{notModified:!0}:{body:L.body}):v.settle.reject(new Error(L.refused)):v.settle.reject(new Error("The org gave no answer to this describe of the composite"))})},b=async(k,O)=>{for(let I of k){let D=I.ask;u++;try{let M=D.kind==="first"?await r.query(D.soql,{scanAll:D.scanAll}):await r.queryMore(D.path);p(I,$t(M)??new Error("The org answered a query with no page"))}catch(M){p(I,new Error(N(M)))}}for(let I of O){u++;try{let D=await r.request({method:"GET",url:`/services/data/v${r.version}/${I.path}`,...I.headers?{headers:I.headers}:{}}),M=I.headers?.[ar]!==void 0&&(D==null||D==="");I.settle.resolve(M?{notModified:!0}:{body:D})}catch(D){I.settle.reject(new Error(N(D)))}}},h=async(k,O,I)=>{try{s==="composite"?await m(k,O):await b(k,O)}catch(D){let M=new Error(N(D));for(let H of k)H.state==="sent"&&p(H,M);for(let H of O)H.settle.reject(M)}finally{i--,I||(a=!1),g(),_()}},R=()=>{if(e?.aborted){l();return}for(;;){if(a)return;let k=[...t],O=k.filter(T=>T.state==="pending").sort((T,L)=>T.order-L.order);if(!(O.length>0&&!k.some(T=>T.state==="idle"))&&n.length===0)return;let D=O.slice(0,o),M=qt-D.length,H=s==="composite"&&n.length===0&&D.length>0&&D.every(T=>T.oneRow&&T.ask?.kind==="first");if(i>=(H?Ut:1))return;let v=n.splice(0,M);if(D.length===0&&v.length===0)return;for(let T of D)T.state="sent";i++,H||(a=!0),h(D,v,H)}},S=()=>{f=!1,g()},j=()=>{f||e===void 0||e.aborted||(e.addEventListener("abort",S,{once:!0}),f=!0)},_=()=>{!f||i>0||t.size>0||n.length>0||(e?.removeEventListener("abort",S),f=!1)},U=(k,O)=>t.has(k)?k.state!=="idle"?Promise.reject(new Error("A read asks one page at a time.")):e?.aborted?Promise.reject(new oe):new Promise((I,D)=>{k.ask=O,k.settle={resolve:I,reject:D},k.state="pending",k.order=++c,g()}):Promise.reject(new Error("This read is closed."));return{lane(k){let O={state:"idle",order:0,oneRow:k?.oneRow===!0};return t.add(O),j(),{query:(I,D)=>U(O,{kind:"first",soql:I,scanAll:D?.scanAll===!0}),queryMore:I=>{let D;try{D=Fo(I)}catch(M){return Promise.reject(M instanceof Error?M:new Error(String(M)))}return U(O,{kind:"next",path:D})},close(){t.delete(O)&&(O.state==="pending"&&p(O,new Error("This read is closed.")),g(),_())}}},describe(k,O){return e?.aborted?Promise.reject(new oe):new Promise((I,D)=>{let M=K(k),H;if(O!==void 0){let v=Date.parse(O);if(!Number.isFinite(v))throw new Error(`Not a date: ${O}`);H={[ar]:new Date(v).toUTCString()}}j(),n.push({path:`sobjects/${M}/describe`,...H?{headers:H}:{},settle:{resolve:I,reject:D}}),g()})},async tooling(k){if(e?.aborted)throw new oe;u++;let O;try{O=await r.request({method:"GET",url:`/services/data/v${r.version}/tooling/query?q=${encodeURIComponent(k)}`})}catch(D){throw new Error(N(D))}let I=$t(O);if(!I)throw new Error("The org answered a Tooling API query with no page");return I},calls:()=>u}}import{createReadStream as $o}from"node:fs";import{appendFile as qo,mkdir as Uo,rm as zo,writeFile as Ho}from"node:fs/promises";import*as he from"node:path";import{createInterface as Jo}from"node:readline";var Qo="The org stopped answering before it said the read was done: some of its records were not read.",dr=384,Wo=448;function cr(r){let e=typeof r=="number"?r:Date.parse(r);if(!Number.isFinite(e))throw new Error(`Not a date: ${String(r)}`);let t=e-(e%1e3+1e3)%1e3;return new Date(t).toISOString().replace(/\.\d{3}Z$/,"Z")}function zt(r){let e=Date.parse(r);if(!Number.isFinite(e))throw new Error(`Not a date: ${r}`);return cr(e-on)}function lr(r,e){return[...new Set([...r,...e.map(F)])].join(", ")}function Ht(r,e,t,n){let o=K(r),s=[n,e==="scanAllLive"?"IsDeleted = false":void 0].filter(i=>i!==void 0);return{objectApiName:o,soql:`SELECT ${t} FROM ${o}${s.length>0?` WHERE ${s.join(" AND ")}`:""}`,scanAll:e==="scanAllLive"}}function Vo(r){let e=K(r);return{objectApiName:e,soql:`SELECT SystemModstamp FROM ${e} ORDER BY SystemModstamp DESC LIMIT 1`,scanAll:!0}}var Ko=["Id","SystemModstamp","CreatedDate","LastModifiedDate","LastModifiedById"],Go=["Id","SystemModstamp","CreatedDate"];function Yo(r,e,t,n=[]){return Ht(r,e,lr(Ko,n),`SystemModstamp >= ${zt(t)}`)}function Zo(r,e,t=[]){let n=K(r);return{objectApiName:n,soql:`SELECT ${lr(Go,t)} FROM ${n} WHERE IsDeleted = true AND SystemModstamp >= ${zt(e)}`,scanAll:!0}}function Xo(r,e){return Ht(r,e,"COUNT()")}function Gi(r,e){let t=K(r);return{objectApiName:t,soql:`SELECT Id FROM ${t} WHERE IsDeleted = true AND SystemModstamp < ${cr(e)}`,scanAll:!0}}function Yi(r,e){return Ht(r,e,"Id")}async function es(r,e,t){let n,o,s={query:async a=>{let d=await r.query(a,{scanAll:e.scanAll});return n=d,o=d.totalSize,d},queryMore:async a=>(n=await r.queryMore(a),n)},i=0;try{for await(let a of rn(s,e.soql))await t(a),i+=a.length}catch(a){if(a instanceof oe)throw a;return{objectApiName:e.objectApiName,read:!1,rows:i,reason:N(a)}}return n?.done!==!0?{objectApiName:e.objectApiName,read:!1,rows:i,reason:Qo}:{objectApiName:e.objectApiName,read:!0,rows:i,...o!==void 0?{totalSize:o}:{}}}async function Jt(r,e,t,n,o={}){let s=o.oneRow===!0,i=new Array(e.length),a=async l=>{let g=e.slice(l,l+me),p=g.map(()=>r.lane({oneRow:s})),m=await Promise.allSettled(g.map(async(b,h)=>{let R=p[h];try{return await es(R,b,S=>t(l+h,S))}finally{R.close()}}));for(let[b,h]of m.entries()){if(h.status==="rejected")throw h.reason instanceof Error?h.reason:new Error(String(h.reason));i[l+b]=h.value}},d=0,c=async()=>{for(;d<e.length;){if(n?.aborted)throw new oe;let l=d;d+=me,await a(l)}},u=Math.ceil(e.length/me),f=await Promise.allSettled(Array.from({length:Math.min(s?Ut:1,u)},c));for(let l of f)if(l.status==="rejected")throw l.reason instanceof Error?l.reason:new Error(String(l.reason));if(n?.aborted)throw new oe;return i}function ts(r){return`${JSON.stringify(Object.fromEntries(Object.entries(r).filter(([e])=>e!=="attributes")))}
8
- `}async function ns(r,e,t){for(let o of e)await Uo(he.dirname(o.file),{recursive:!0,mode:Wo}),await Ho(o.file,"",{encoding:"utf8",mode:dr});let n=await Jt(r,e,async(o,s)=>{s.length!==0&&await qo(e[o].file,s.map(ts).join(""),{encoding:"utf8",mode:dr})},t);return await Promise.all(n.map((o,s)=>o.read?void 0:zo(e[s].file,{force:!0}))),n}async function*Zi(r){let e=$o(r,{encoding:"utf8"}),t=Jo({input:e,crlfDelay:1/0});try{for await(let n of t){if(n==="")continue;let o=JSON.parse(n);if(typeof o!="object"||o===null||Array.isArray(o))throw new Error(`${he.basename(r)} holds a line that is no record.`);yield o}}finally{t.close(),e.destroy()}}async function rs(r,e,t,n){let o=Date.parse(zt(t)),s=[];return(await Jt(r,e.map(Vo),(a,d)=>{d.length>0&&(s[a]=d[0].SystemModstamp)},n,{oneRow:!0})).map((a,d)=>{if(!a.read)return{objectApiName:a.objectApiName,unread:a.reason};if(s[d]===void 0)return{objectApiName:a.objectApiName,latest:null,moved:!1};let c=sn(s[d]);return c===null?{objectApiName:a.objectApiName,unread:`${a.objectApiName} answered a SystemModstamp that is not a date.`}:{objectApiName:a.objectApiName,latest:c,moved:Date.parse(c)>=o}})}async function os(r,e,t){return(await Jt(r,e.map(({objectApiName:o,readMode:s})=>Xo(o,s)),()=>{},t,{oneRow:!0})).map(o=>o.read?o.totalSize===void 0?{objectApiName:o.objectApiName,unread:"The org gave no count of its records."}:{objectApiName:o.objectApiName,count:o.totalSize}:{objectApiName:o.objectApiName,unread:o.reason})}function ss(r,e){return he.join(r,`${K(e)}.live.ndjson`)}function is(r,e){return he.join(r,`${K(e)}.deleted.ndjson`)}async function Xi(r,e,t,n,o,s){if(s!==void 0&&s.length!==e.length)throw new Error(`${s.length} pre-checks for ${e.length} objects`);let i=s??await rs(r,e.map(({objectApiName:m})=>m),t,o),a=new Map,d=[];i.forEach((m,b)=>{"unread"in m?a.set(b,m.unread):m.moved&&d.push(b)});let c=d.flatMap(m=>{let{objectApiName:b,readMode:h,fields:R=[]}=e[m],S=K(b);return[{...Yo(S,h,t,R),file:ss(n,S)},{...Zo(S,t,R),file:is(n,S)}]}),u=await ns(r,c,o),f=new Map;d.forEach((m,b)=>{let h=u[b*2],R=u[b*2+1],S=[h,R].find(j=>!j.read);if(S&&!S.read){a.set(m,S.reason);return}f.set(m,{live:{file:c[b*2].file,rows:h.rows},deleted:{file:c[b*2+1].file,rows:R.rows}})});let l=e.map((m,b)=>({object:m,index:b})).filter(({object:m,index:b})=>!a.has(b)&&(f.has(b)||m.held)).map(({index:m})=>m),g=await os(r,l.map(m=>e[m]),o),p=new Map;return l.forEach((m,b)=>{let h=g[b];"unread"in h?a.set(m,h.unread):p.set(m,h.count)}),i.map((m,b)=>{if("unread"in m)return m;let h=a.get(b);if(h!==void 0)return{objectApiName:m.objectApiName,unread:h};let R=f.get(b),S=p.get(b);return{objectApiName:m.objectApiName,latest:m.latest,moved:m.moved,...R?.live?{live:R.live}:{},...R?.deleted?{deleted:R.deleted}:{},...S!==void 0?{count:S}:{}}})}import{randomBytes as as}from"node:crypto";import{createReadStream as ds}from"node:fs";import{appendFile as cs,open as gr,readFile as ls,rename as us,rm as fs}from"node:fs/promises";import{join as Wt}from"node:path";import{createInterface as gs}from"node:readline";var ps=2e3,ce=15,pr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ms=2e3,mr="spool.json",Te="a rewind";function Qt(r){return typeof r=="string"&&pr.test(r)?r.slice(0,ce):void 0}var st=class{bytes=Buffer.alloc(ce*1024);flags=new Uint16Array(1024);slots=new Uint32Array(2048);used=0;get size(){return this.used}find(e){let t=this.slots.length-1;for(let n=ht(e)&t;;n=n+1&t){let o=this.slots[n];if(o===0)return-1;if(this.holds(o-1,e))return o-1}}holds(e,t){let n=e*ce;for(let o=0;o<ce;o++)if(this.bytes[n+o]!==t.charCodeAt(o))return!1;return!0}keyAt(e){let t=e*ce;return this.bytes.toString("latin1",t,t+ce)}place(e,t){let n=this.slots.length-1,o=ht(t)&n;for(;this.slots[o]!==0;)o=o+1&n;this.slots[o]=e+1}add(e,t=0){let n=Qt(e);if(n===void 0)throw new RangeError(`Not a Salesforce id: ${String(e)}`);let o=this.find(n);if(o>=0)return this.flags[o]|=t,!1;if((this.used+1)*2>this.slots.length){let s=this.slots;this.slots=new Uint32Array(s.length*2);for(let i of s)i!==0&&this.place(i-1,this.keyAt(i-1))}if((this.used+1)*ce>this.bytes.length){let s=Buffer.alloc(this.bytes.length*2);this.bytes.copy(s),this.bytes=s;let i=new Uint16Array(this.flags.length*2);i.set(this.flags),this.flags=i}return this.bytes.write(n,this.used*ce,ce,"latin1"),this.flags[this.used]=t,this.place(this.used,n),this.used++,!0}has(e){let t=Qt(e);return t!==void 0&&this.find(t)>=0}count(e){let t=0;for(let n=0;n<this.used;n++)e(this.flags[n])&&t++;return t}flagsOf(e){let t=Qt(e);if(t===void 0)return 0;let n=this.find(t);return n<0?0:this.flags[n]}},hs=W({version:Zt(1),objects:X(W({objectApiName:x().min(1),count:ue().int().nonnegative()}))});function Vt(r,e){return Wt(r,`${K(e)}.ids`)}async function ys(r,e){let t=`${r}.${process.pid}-${as(4).toString("hex")}.tmp`,n=await gr(t,"wx",pt);try{try{await n.writeFile(e,"utf8"),await n.sync()}finally{await n.close()}await us(t,r)}catch(o){throw await fs(t,{force:!0}),o}}async function bs(r){let e=await gr(r,"r+");try{await e.sync()}finally{await e.close()}}async function ws(r,e,t=Te){for(let{objectApiName:n,count:o}of e)o>0&&await bs(Vt(r,n));return await ys(Wt(r,mr),`${JSON.stringify({version:1,objects:e})}
9
- `),new it(r,e,t)}var ur=class{constructor(e,t=Te){this.dir=e;this.act=t}dir;act;order=[];counts=new Map;lines=new Map;written=new Set;keys=new st;made=!1;async add(e,t){if(!this.keys.add(t))return!1;let n=this.lines.get(e);return n||(K(e),n=[],this.lines.set(e,n),this.order.push(e)),n.push(t),this.counts.set(e,(this.counts.get(e)??0)+1),n.length>=ms&&await this.flush(e),!0}async flush(e){let t=this.lines.get(e)??[];this.made||(await mt(this.dir),this.made=!0);let n=!this.written.has(e);t.length===0&&!n||(await cs(Vt(this.dir,e),t.map(o=>`${o}
10
- `).join(""),{encoding:"utf8",mode:pt,flag:n?"w":"a"}),this.written.add(e),this.lines.set(e,[]))}get objects(){return this.order.map(e=>({objectApiName:e,count:this.counts.get(e)??0}))}async finish(e){this.made||(await mt(this.dir),this.made=!0);for(let t of this.order)await this.flush(t);return ws(this.dir,e?e(this.objects):this.objects,this.act)}},it=class r{constructor(e,t,n=Te){this.dir=e;this.objects=t;this.act=n}dir;objects;act;get count(){return this.objects.reduce((e,t)=>e+t.count,0)}static async open(e,t=Te){let n;try{n=JSON.parse(await ls(Wt(e,mr),"utf8"))}catch{throw new ze("damaged",`The list of what ${t} sets out to do is not on this machine.`)}let o=hs.safeParse(n);if(!o.success)throw new ze("damaged",`The list of what ${t} sets out to do does not read as one.`);for(let{objectApiName:s}of o.data.objects)K(s);return new r(e,o.data.objects,t)}async*pages(e,t=ps){let n=this.objects.find(u=>u.objectApiName===e);if(!n||n.count===0)return;let o=()=>new ze("damaged",`The ${e} records ${this.act} sets out to act on are not as they were written.`),s=Math.max(1,Math.floor(t)),i=ds(Vt(this.dir,e),{encoding:"utf8"}),a=gs({input:i,crlfDelay:1/0}),d=0,c=[];try{for await(let u of a)if(u!==""){if(!pr.test(u))throw o();d++,c.push(u),c.length>=s&&(yield c,c=[])}}catch(u){throw u.code==="ENOENT"?o():u}finally{a.close(),i.destroy()}if(d!==n.count)throw o();c.length>0&&(yield c)}},fr=class r{constructor(e,t){this.spool=e;this.keys=t}spool;keys;static async of(e,t){return new r(await e.finish(t),e.keys)}static async open(e,t=Te){let n=await it.open(e,t),o=new st;for(let{objectApiName:s}of n.objects)for await(let i of n.pages(s))for(let a of i)o.add(a);return new r(n,o)}get objects(){return this.spool.objects}pages(e){return this.spool.pages(e)}has(e){return this.keys.has(e)}};export{He as a,yt as b,wn as c,Rn as d,de as e,Sn as f,Or as g,Dr as h,Ir as i,Pr as j,Cr as k,Ps as l,Je as m,wt as n,Ve as o,De as p,$s as q,Et as r,xr as s,Br as t,Pn as u,Nn as v,Dt as w,jn as x,vn as y,Mn as z,Ke as A,It as B,Ur as C,Pt as D,Qs as E,Ln as F,Wn as G,Re as H,Qr as I,Lt as J,pe as K,ki as L,Oi as M,Ei as N,Di as O,Ii as P,Pi as Q,Ci as R,Po as S,Co as T,Mi as U,Li as V,me as W,qt as X,Ut as Y,Bi as Z,oe as _,Fi as $,cr as aa,zt as ba,Xo as ca,Gi as da,Yi as ea,es as fa,Jt as ga,ns as ha,Zi as ia,rs as ja,os as ka,ss as la,is as ma,Xi as na,ps as oa,st as pa,Vt as qa,ws as ra,ur as sa,it as ta,fr as ua};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{f as a,g as b,h as c,i as d,j as e,k as f,l as g}from"./chunk-57VHUYNG.mjs";import"./chunk-MYTIL2JD.mjs";import"./chunk-JVL444U5.mjs";import"./chunk-5CD257T7.mjs";import"./chunk-5P4PHJRL.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-ALJVEUUS.mjs";import"./chunk-6QSM2WIH.mjs";import"./chunk-WJY54JO7.mjs";import"./chunk-NEVXIGR6.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-SAR5622P.mjs";import"./chunk-HJC7AIBK.mjs";import"./chunk-OTWRDD6L.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-ZUTYVST5.mjs";import"./chunk-55HEMHEG.mjs";import"./chunk-P42X3B4D.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-PA3MKJVH.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-PNCONNFJ.mjs";import"./chunk-CGWXQX75.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-SIOZXPFG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{d as diffOfPicked,b as heldInPlaceReason,g as planSelection,c as rewindPlan,a as rewindWriters,f as selectionPlanOf,e as snapshotRowsOf};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{J as H}from"./chunk-6QSM2WIH.mjs";import{b as k,c as ie,d as $}from"./chunk-OTWRDD6L.mjs";import{i as oe}from"./chunk-INIT2UKJ.mjs";import{h as Y}from"./chunk-TZE3Y7IQ.mjs";import{b as S}from"./chunk-CA5NAXSU.mjs";var ye=5,pe=100;function y(t){return t.slice(0,15)}function L(t){return t==null||t===""}var ae=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;function he(t,n){if(L(t)||L(n))return L(t)&&L(n);if(typeof t=="number"||typeof n=="number")return Number(t)===Number(n);if(typeof t=="string"&&typeof n=="string"){if(t===n)return!0;if(ae.test(t)&&ae.test(n)){let a=Date.parse(t);return Number.isFinite(a)&&a===Date.parse(n)}return!1}return JSON.stringify(t)===JSON.stringify(n)}function me(t){let n;return()=>(n??=(async()=>{try{let a=await t.userId?.();return typeof a=="string"&&a!==""?y(a):void 0}catch{return}})(),n)}async function de(t){let n=Date.now();try{let a=Date.parse(await t.serverTime());return Number.isFinite(a)?a-(n+Date.now())/2:0}catch{return 0}}async function Ie(t,n){let a=Date.parse(n??"");return Number.isFinite(a)?a+await de(t)+H:Number.NEGATIVE_INFINITY}var be=1e3;function Re(t){let n=Date.parse(t);return Number.isFinite(n)?n-be:Number.NEGATIVE_INFINITY}function ke(t,n){let a=Object.hasOwn(t,n)?t[n]:[];return new Map(a.filter(c=>c.toLowerCase()!=="id").map(c=>[c.toLowerCase(),c]))}var Ae={INACTIVE_OWNER_OR_USER:"OwnerId"};function Oe(t,n){let a=new Set;for(let s of t.errors??[]){if(typeof s=="string")continue;if(Array.isArray(s.fields))for(let p of s.fields)typeof p=="string"&&a.add(p);let f=s.statusCode!==void 0?Ae[s.statusCode]:void 0;f!==void 0&&(!Array.isArray(s.fields)||s.fields.length===0)&&a.add(f)}let c=new Map(Object.keys(n).map(s=>[s.toLowerCase(),s]));return[...a].flatMap(s=>{let f=c.get(s.toLowerCase());return f!==void 0&&f!=="Id"?[f]:[]})}function ve(t,n){let a=Array.isArray(t)?t:[t];return Array.from({length:n},(c,s)=>a[s]??{success:!1})}function J(t){let n=t.errors?.[0];if(n===void 0)return{words:"The org gave no reason."};if(typeof n=="string")return{words:n};let a=n.statusCode,c=n.message??"";return{...a?{code:a}:{},words:a&&c?`${a}: ${c}`:a||c}}function P(t,{fields:n,why:a}){return`${n.map(c=>`${t}.${c}`).join(", ")}: the value from before is no longer taken (${a}) \u2014 left as the run wrote it`}async function je(t,n,a){let c=new Set;try{for(let s of $(a)){let f=await t.query(`SELECT Id FROM ${n} WHERE Id IN (${s})`);for(let p of f.records)typeof p.Id=="string"&&c.add(y(p.Id))}}catch(s){return{unread:S(s)}}return{live:c}}var Q=class{result;said=new Set;constructor(n,a){this.result={objectApiName:n,planned:a,restored:0,keptChanged:0,alreadyGone:0,refused:0,notKept:0,reasons:[]}}without(){this.result.restoredWithout=(this.result.restoredWithout??0)+1}reason(n){this.said.has(n)||this.said.size>=ye||(this.said.add(n),this.result.reasons.push(n))}};async function De(t){let{org:n,plan:a}=t,c=[],s=[],f={},p=!1,I=!1;if(a.length===0)return{objects:c,left:s,wrote:p,cancelled:I,stamps:f};let M=t.changedAfter!==void 0?Re(t.changedAfter):await Ie(n,t.lastWriteAt),R=new Map(Object.entries(t.stamps??{}).map(([h,_])=>[y(h),Date.parse(_)])),F=t.ownWriters&&t.ownWriters.length>0?new Set(t.ownWriters.map(y)):void 0,W=t.stampsFor,ce=me(n);for(let{objectApiName:h,backup:_,ids:C}of a){let u=new Q(h,C.length);c.push(u.result);let B=t.unkept?.find(e=>e.objectApiName===h);if(B&&B.fields.length>0&&u.reason(`${B.fields.map(e=>`${h}.${e}`).join(", ")}: not kept, encrypted \u2014 the run's user cannot view encrypted data, and read their values from before masked; left as the run wrote them`),I||t.signal?.aborted){I=!0,u.result.notReached=C.length,s.push(...C);continue}let x=Y(h),m=new Map(C.map(e=>[y(e),e])),U=t.fields?ke(t.fields,h):void 0,O=new Map,G=new Set;try{let e=await t.backups.batches(_,h,k);for await(let r of e??[])for(let o of r){if(typeof o.Id!="string"||!m.has(y(o.Id)))continue;let i=O.get(y(o.Id))??{};for(let[l,d]of Object.entries(o)){if(l==="Id")continue;let g=U?U.get(l.toLowerCase()):l;g!==void 0&&!(g in i)&&(i[g]=d)}if(U&&Object.keys(i).length===0){G.add(y(o.Id));continue}O.set(y(o.Id),i)}}catch(e){u.reason(`The values from before the run could not be read: ${S(e)}`),O.clear(),G.clear()}let X=[...G].filter(e=>!O.has(e)).length;X>0&&u.reason(`${X} ${h} record(s) hold no value of a field that may be written back now: left as they are`);for(let e of[...m.keys()])O.has(e)||(u.result.notKept++,m.delete(e));if(m.size===0)continue;let Z=new Set;for(let e of O.values())for(let r of Object.keys(e))Z.add(Y(r));let ee=["Id","LastModifiedDate",...F?["LastModifiedById"]:[],...Z],ue=ee.length>pe?k/4:k,q=new Map,fe=async e=>{if(t.signal?.aborted)throw new T;return(await n.query(e)).records};try{for(let e of $([...m.values()],ue)){let r=await oe(`SELECT ${ee.join(", ")} FROM ${x} WHERE Id IN (${e})`,fe,{stamp:"LastModifiedDate"});for(let o of r)typeof o.Id=="string"&&q.set(y(o.Id),o)}}catch(e){if(e instanceof T){I=!0,u.result.notReached=m.size,s.push(...m.values());continue}u.result.refused+=m.size,u.reason(S(e)),s.push(...m.values());continue}let D=[],te=new Set,le=W?Date.now()+await de(n)-H:0;for(let[e,r]of m){let o=q.get(e);if(!o){u.result.alreadyGone++,t.counted?.(r,"alreadyGone");continue}let i=Date.parse(String(o.LastModifiedDate??"")),l=o.LastModifiedById,d=i<=M||i<=(R.get(e)??Number.NaN)||F!==void 0&&typeof l=="string"&&F.has(y(l));if(!d&&!t.includeChanged){u.result.keptChanged++,s.push(r);continue}let g=O.get(e)??{},w={Id:o.Id};for(let[b,A]of Object.entries(g))he(A,o[b])||(w[b]=L(A)?null:A);if(Object.keys(w).length===1){u.result.restored++,t.counted?.(r,"restored"),d&&W?.(r)&&typeof o.LastModifiedDate=="string"&&(f[o.Id]=o.LastModifiedDate);continue}D.push(w),d&&W?.(r)&&te.add(r)}let j=[],v=[],E=(e,r)=>{u.result.refused++,u.reason(r),s.push(m.get(y(e.Id))??e.Id)},z=e=>{u.result.restored++,t.counted?.(m.get(y(e.Id))??e.Id,"restored")},ge=e=>{u.result.alreadyGone++,t.counted?.(m.get(y(e.Id))??e.Id,"alreadyGone")},ne=e=>{I=!0,u.result.notReached=(u.result.notReached??0)+e.length,s.push(...e.map(r=>m.get(y(r.Id))??r.Id))},re=(e,r,o,i)=>{let l=Object.keys(e).filter(w=>w!=="Id"&&!r.includes(w));if(l.length>0){let w={Id:e.Id};for(let b of l)w[b]=e[b];j.push({record:w,leftOut:o});return}if(o.length===0){z(e);return}let[d,...g]=o;i?(u.without(),u.reason(P(h,d))):E(e,P(h,d));for(let w of g)u.reason(P(h,w))},K=async e=>{try{return p=!0,ve(await n.update(h,[...e]),e.length)}catch(r){let o=S(r);return e.map(()=>({success:!1,errors:[o]}))}},we=async e=>{let r=t.keep;if(!r)return!0;let o=e.map(i=>{let l=q.get(y(i.Id))??{},d={Id:i.Id};for(let g of Object.keys(i))g!=="Id"&&(d[g]=l[g]??null);return d});try{return await r(h,o),!0}catch(i){let l=`What these ${e.length} ${h} record(s) hold now could not be kept before they were written (${S(i)}), so none of them was written: nothing is written over that cannot be put back.`;for(let d of e)E(d,l);return!1}};for(let e=0;e<D.length;e+=k){let r=D.slice(e,e+k);if(t.signal?.aborted){I=!0;let i=D.slice(e);u.result.notReached=(u.result.notReached??0)+i.length,s.push(...i.map(l=>m.get(y(l.Id))??l.Id));break}if(!await we(r))continue;(await K(r)).forEach((i,l)=>{let d=r[l];if(i.success===!0){z(d);return}let g=J(i),w=Oe(i,d);if(g.code==="ENTITY_IS_DELETED"&&w.length===0){v.push({record:d,why:g.words});return}let b=Object.keys(d).filter(A=>A!=="Id"&&!w.includes(A));if(w.length>0&&b.length>0){let A={Id:d.Id};for(let se of b)A[se]=d[se];j.push({record:A,leftOut:[{fields:w,why:g.words}]});return}E(d,g.words)})}let N=[];if(v.length>0&&t.signal?.aborted)ne(v.map(({record:e})=>e));else if(v.length>0){let e=await je(n,x,v.map(({record:r})=>r.Id));e.unread!==void 0&&u.reason(`Whether ${v.length} ${h} record(s) refused as deleted are still in the org could not be read (${e.unread}): left to be given back again`);for(let{record:r,why:o}of v){if(e.unread!==void 0){E(r,o);continue}if(!e.live.has(y(r.Id))){ge(r);continue}let i=Object.keys(r).filter(l=>l!=="Id"&&ie(r[l]));i.length===0?E(r,o):i.length===1?re(r,i,[{fields:i,why:o}],!1):N.push({record:r,lookups:i,given:[],refusedAlone:[]})}}let V=N.length>0;for(let e=0;V&&N.some(({lookups:r})=>r.length>e);e++){let r=N.filter(({lookups:o})=>o.length>e);for(let o=0;o<r.length;o+=k){if(t.signal?.aborted){ne(N.map(({record:d})=>d)),V=!1;break}let i=r.slice(o,o+k);(await K(i.map(({record:d,lookups:g})=>({Id:d.Id,[g[e]]:d[g[e]]})))).forEach((d,g)=>{let w=i[g],b=w.lookups[e];d.success===!0?w.given.push(b):w.refusedAlone.push({field:b,why:J(d).words})})}}for(let e of V?N:[]){let r=new Map;for(let{field:o,why:i}of e.refusedAlone)r.set(i,[...r.get(i)??[],o]);re(e.record,e.lookups,[...r].map(([o,i])=>({fields:i,why:o})),e.given.length>0)}for(let e=0;e<j.length;e+=k){let r=j.slice(e,e+k);if(t.signal?.aborted){I=!0,u.result.notReached=(u.result.notReached??0)+j.length-e,s.push(...j.slice(e).map(({record:i})=>m.get(y(i.Id))??i.Id));break}(await K(r.map(({record:i})=>i))).forEach((i,l)=>{let{record:d,leftOut:g}=r[l];if(i.success===!0){if(g.length===0){z(d);return}u.without();for(let w of g)u.reason(P(h,w));return}E(d,J(i).words)})}Object.assign(f,await Ee(n,x,[...te],le,ce))}return{objects:c,left:s,wrote:p,cancelled:I,stamps:f}}async function Ee(t,n,a,c,s){let f={};if(a.length===0)return f;let p=await s();if(p===void 0)return f;for(let I of $(a)){let M;try{M=(await t.query(`SELECT Id, LastModifiedDate, LastModifiedById FROM ${n} WHERE Id IN (${I})`)).records}catch{continue}for(let R of M)typeof R.Id=="string"&&typeof R.LastModifiedDate=="string"&&typeof R.LastModifiedById=="string"&&y(R.LastModifiedById)===p&&Date.parse(R.LastModifiedDate)>=c&&(f[R.Id]=R.LastModifiedDate)}return f}var T=class extends Error{};function $e(t,n,a=[]){let c=t.map(s=>({...s}));for(let s of a){if(s.undeleted+s.refused===0)continue;let f=c.find(p=>p.objectApiName===s.objectApiName);f?(f.created+=s.undeleted,f.failed+=s.refused):c.push({objectApiName:s.objectApiName,created:s.undeleted,updated:0,deleted:0,failed:s.refused})}for(let s of n){let f=s.restored+(s.restoredWithout??0);if(f+s.refused===0)continue;let p=c.find(I=>I.objectApiName===s.objectApiName);p?(p.updated+=f,p.failed+=s.refused):c.push({objectApiName:s.objectApiName,created:0,updated:f,deleted:0,failed:s.refused})}return c}export{he as a,me as b,de as c,Ie as d,De as e,Ee as f,$e as g};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as je,b as Ne,c as Pe,d as Fe,k as We,l as xe,o as Le,q as _e}from"./chunk-TBZMC2VV.mjs";import{e as Me}from"./chunk-LQ4DRFUH.mjs";import{b as De,f as Te}from"./chunk-57VHUYNG.mjs";import{m as Be}from"./chunk-5O6JOMHS.mjs";import{b as Se}from"./chunk-KLX67VPL.mjs";import{i as he,j as we,k as ke,l as ye,m as be,p as Re,q as Ae}from"./chunk-342FN7AO.mjs";import{A as Ie,B as $e,C as ve,z as Ue}from"./chunk-Z7X534S4.mjs";import{$ as Ce,C as ge,_ as Oe}from"./chunk-6QSM2WIH.mjs";import{a as le,b as fe}from"./chunk-SAR5622P.mjs";import{s as pe}from"./chunk-6MUEPV7M.mjs";import{b as ue,d as ce}from"./chunk-OTWRDD6L.mjs";import{Ba as Ee,s as me}from"./chunk-VXHDBYMI.mjs";import{g as L,h as _,q as de}from"./chunk-PA3MKJVH.mjs";import{b as x}from"./chunk-CA5NAXSU.mjs";import{Kc as se,Sc as W}from"./chunk-B45CNPUX.mjs";var C=class extends Error{constructor(){super("The undo was stopped before it wrote anything to the org."),this.name="UndoStopped"}},z="No record was written.",Je="accept that it runs to undo the rewind all the same";function ze(e){return e.slice(0,15)}function Ke(e){return{query:n=>e.query(n),queryMore:n=>e.queryMore(n)}}function Ye(e,n,t){if(e.kind==="org")return;let a=e.userKey;if(n.users.some(i=>i.slice(0,15)!==a))return{code:"PERMISSIONS",message:`This rewind was made as another user than ${t}: what it deleted is that user's deletion in the recycle bin, which Salesforce brings back only for a user with View All Data and Modify All Data. Undo it as the user it was made as, or as a user with View All Data and Modify All Data. ${z}`};let r=n.objects.flatMap(i=>{let l=e.notHeld.get(i);return l===void 0?[]:[`${i}: ${l}`]});if(r.length!==0)return{code:"PERMISSIONS",message:`Undo takes back what the rewind did to objects ${t} no longer holds whole (${r.join("; ")}), and does not stop part way: an undo left part way could not be offered again. Undo it once the user has View All and Modify All on them again, or as a user with View All Data and Modify All Data. ${z}`}}function Qe(e,n){return{undone:!1,refusal:{code:e,message:n}}}function Xe(e,n){return{code:"RUN_WRITING",message:`${n.operation==="take"?`A checkpoint of ${e} is being taken`:n.operation==="rewind"?`A rewind is writing to ${e}`:n.operation==="undo"?`An undo is writing to ${e}`:`SandForge is deleting checkpoints of ${e}`} (process ${n.pid} on ${n.host}): undo the rewind once it has ended. No record was read or written.`}}function Ze(e,n,t,a){let r=W(n,t),i=[...new Set(r.map(b=>b.objectApiName))],l=(t.setToDraft??[]).length>0?", sets an order back to Draft":"",h=r.length>0?`${Me(r)} flow(s), trigger(s) or rule(s) of ${i.join(", ")} run as the undo brings records back, gives them their values back${l} or sends them back to the recycle bin`:"what runs as the undo writes could not all be read, so automation may run";return{code:"AUTOMATION",message:`${e}: ${h}. ${ke("undo",a)}Undo refused; ${Je}. ${z}`}}async function et(e,n){let t=0,a=0;for await(let r of n.bringBack.pages(L)){t+=r.length;for(let i of ce(r,ue)){let l=await e.queryDeleted(`SELECT Id, ContentSize FROM ${L} WHERE Id IN (${i}) AND IsDeleted = true`);for(let h of l.records)typeof h.ContentSize=="number"&&(a+=h.ContentSize)}}return{files:t,bytes:a}}function tt(e,n){return e.status==="cancelled"||e.status==="failure"?e.status:n.some(t=>t.reason==="changedDuringRewind")?"unstable":e.status}function nt(e,n){return e.map(t=>{let a=Object.keys(t.by).filter(i=>!n.has(ze(i)));if(a.length===0)return{objectApiName:t.objectApiName,reason:"automation",count:t.count,ids:[...t.ids]};let r=a.length===1&&a[0]!=="unknown"?a[0]:void 0;return{objectApiName:t.objectApiName,reason:"changedDuringRewind",...r!==void 0?{by:r}:{},count:t.count,ids:[...t.ids]}})}async function Ot(e,n){let{checkpoint:t,folder:a,orgName:r,rewindId:i}=n,l=e.signal,h=()=>l?.aborted===!0,b=(U,k)=>e.onProgress?.({percentage:U,step:k}),c=_e(e.org,e.undelete),T,S=await Se(Ke(c.org),{act:"undo",orgName:r,registered:n.registered,username:n.username,organizationId:t.org.organizationId,customSettings:de(t)},{userId:async()=>T=await c.org.userId()});if(!S.allowed)return{undone:!1,refusal:S.refusal};let R=e.store.lock(t.org.organizationId,"undo",t.checkpointId);if("busy"in R)return{undone:!1,refusal:Xe(r,R.busy)};try{let U=await e.runWriting?.(S.org.id);if(U!==void 0)return Qe("RUN_WRITING",U);let k=await Ie(c.org,r);if(h())throw new C;b(5,"Reading what the rewind did");let g=await Ne(a,i,t.objects),G=Pe(g),M=g.goesWithParent.objects,Ge=g.remade.keys.size>0?"Sending back to the recycle bin what the rewind brought back, and deleting again what it made again":"Sending back to the recycle bin what the rewind brought back",A=o=>o.filter(u=>u.count>0).map(u=>u.objectApiName),j=g.links,q=o=>o>0?[_]:[],N=g.remade.objects.filter(({objectApiName:o,count:u})=>u>0&&ge([o]).length>0),m={bringBack:A(g.bringBack.objects),giveBack:[...A(g.giveBack.objects),...q(j?.share.count??0)],...N.length>0?{setToDraft:A(N)}:{},delete:[...new Set([...A(M),...A(g.remove.objects),...q(j?.remove.count??0)])],...(j?.reinsert.count??0)>0?{recreate:[_]}:{}},H;try{H=await et(c.org,g)}finally{await g.dispose()}let V=ve("undo",H,k.fileStorage?.remaining,r);if(V)return{undone:!1,refusal:V};let w=[...new Set([...m.bringBack??[],...m.giveBack??[],...m.setToDraft??[],...m.delete??[],...m.recreate??[]])],P;try{P=await De({grants:S.grants,...T!==void 0?{userId:T}:{},username:n.username,checkpoint:t,reader:Ce(c.org,l)})}catch(o){throw o instanceof Oe||h()?new C:o}if(P.kind==="perObject"){let o=await je(a,i),u=Ye(P,{users:o.passes.map(f=>f.userId),objects:w},n.username);if(u)return{undone:!1,refusal:u}}let d;if(w.length>0&&e.readAutomation){try{d=await e.readAutomation(w)}catch(o){d=Le(w,x(o))}c.add(d.requests)}let I=d,y=w.length>0?await We(e.mute,d,m):{},$="refusal"in y?y:void 0,J="refusal"in y?void 0:y.mute;y.automation&&(d=y.automation);let v=$?$.plan:J?.plan,K=n.acceptEmails===!0,p=w.length>0&&I?await Re({act:"undo",orgName:r,automation:I,steps:m,...v?{plan:v}:{},accepted:K,mayMute:e.mute===void 0&&n.canMute===!0,read:()=>me(c.org)}):void 0,Y=he(G,M,N),Q=d?we(Y,d):void 0,O=$?[$.refusal]:[];d&&!n.acceptAutomation&&(W(d,m).length>0||se(d.unread)||Q!==void 0)&&O.push(Ze(r,d,m,Q));let X=Ue({objects:t.objects,rewound:G,along:M,automationRequests:0}),Z=Ee(p?.ofRun),ee=$e("undo",{run:c.used()-(Z.deliverability??0)+X.apiRequests,...Z},k,r);w.length>0&&ee&&O.push(ee);let te=d?be("undo",ye(Y,d,k.emails),r):void 0;w.length>0&&te&&O.push(te),p?.refusal&&O.push(p.refusal);let[ne,...oe]=O;if(ne)return{undone:!1,refusal:ne,...oe.length>0?{alsoRefused:oe}:{}};if(h())throw new C;let qe=await c.org.userId(),He=new Set(Te(t.takenBy,qe).map(ze));b(20,"Bringing back what the rewind deleted and giving back what it wrote over");let B,E;try{E=await xe(J,`undo ${t.checkpointId} ${i}`,o=>{let u=o&&v&&I&&p?Ae({act:"undo",orgName:r,automation:I,steps:m,plan:v,held:o.outcome,planned:p.ofRun.senders,...p.ofRun.read?{reading:p.ofRun.read.reading}:{},accepted:K}):void 0;return u?Promise.resolve({relit:u}):Fe({folder:a,rewindId:i,lock:R.lock,objects:t.objects,org:c.org,undelete:c.undelete,splitting:le(fe(k.remaining,c.used()+X.apiRequests)),...l?{signal:l}:{},...e.onUndeletable?{onUndeletable:e.onUndeletable}:{},onProgress:(f,ae,Ve)=>b(20+Math.round(70*f/Math.max(ae,1)),`${Ge}: ${Ve} ${f} / ${ae}`)})},o=>{B=o})}catch(o){if(!pe(o))throw o;return{undone:!1,refusal:{code:"MUTE",message:`${o.message} No record was written.`}}}if("relit"in E)return{undone:!1,refusal:E.relit};let s=E,re=nt(s.residual,He),D=tt(s,re),F=[...s.notes];if(D!=="cancelled"&&D!=="failure"){let o=(e.now??(()=>new Date))().toISOString();try{await e.store.update(t.checkpointId,f=>f.lastRewind?.rewindId===i?{...f,lastRewind:{...f.lastRewind,undoneAt:o}}:f)}catch(f){F.push(`The checkpoint could not be told the rewind was undone (${x(f)}): its list may still offer to undo it.`)}let u=await Be({folder:a,lock:R.lock,checkpoint:t,rewindId:i,status:D,undoneAt:o});u!==void 0&&F.push(u)}let ie=c.used();return{undone:!0,result:{checkpointId:t.checkpointId,rewindId:i,status:D,deleted:s.deleted,...s.remade?{remade:s.remade}:{},...s.carriedAlone?{carriedAlone:s.carriedAlone}:{},...s.wentAlong?{wentAlong:s.wentAlong}:{},restored:s.restored,undeleted:s.undeleted,...s.files?{files:s.files}:{},residual:re,passes:1,apiRequests:{used:ie,leftToday:Math.max(0,k.remaining-ie)},finishedAt:s.finishedAt,...B?{mutedAutomation:B}:{}},notes:F,...p?.gate.audit!==void 0?{deliverability:p.gate.audit}:{}}}finally{R.lock.release()}}export{C as a,Je as b,Ot as c};