sandforge 1.81.0 → 1.83.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 (240) hide show
  1. package/README.md +48 -0
  2. package/bin/sandforge-users.mjs +12 -0
  3. package/lib/{chunk-J6G23RUI.mjs → chunk-262TP6UU.mjs} +1 -1
  4. package/lib/{chunk-NWVVCZUK.mjs → chunk-27BBEGUD.mjs} +1 -1
  5. package/lib/{chunk-Y5ZCPY36.mjs → chunk-2ADSD5WK.mjs} +1 -1
  6. package/lib/{chunk-55LQD3Y3.mjs → chunk-2GSMHGIV.mjs} +1 -1
  7. package/lib/chunk-2K5BYZQM.mjs +8 -0
  8. package/lib/{chunk-GK7VEYFM.mjs → chunk-2KTGDYUH.mjs} +1 -1
  9. package/lib/{chunk-T3PLRQ2T.mjs → chunk-2N73W63D.mjs} +1 -1
  10. package/lib/{chunk-7PK5QDQI.mjs → chunk-2R6GFNKF.mjs} +1 -1
  11. package/lib/{chunk-2OIRJEYE.mjs → chunk-2WMKJVD2.mjs} +1 -1
  12. package/lib/{chunk-D62KWDDT.mjs → chunk-36Y225OM.mjs} +1 -1
  13. package/lib/{chunk-HYOOJVR6.mjs → chunk-3CM7LAPE.mjs} +1 -1
  14. package/lib/{chunk-OIIL4NVI.mjs → chunk-3OVTKRS4.mjs} +1 -1
  15. package/lib/{chunk-UT27HXE7.mjs → chunk-3V4YH5KO.mjs} +1 -1
  16. package/lib/{chunk-OZNLOV4U.mjs → chunk-446GBKAC.mjs} +1 -1
  17. package/lib/{chunk-SQGP46QS.mjs → chunk-4GCYGQXD.mjs} +1 -1
  18. package/lib/{chunk-2NAIUKVL.mjs → chunk-4V3QO7HF.mjs} +1 -1
  19. package/lib/{chunk-GWRKS3AL.mjs → chunk-4X5D3MSV.mjs} +1 -1
  20. package/lib/{chunk-KGYXLSQ5.mjs → chunk-5OGNK3JP.mjs} +1 -1
  21. package/lib/{chunk-D7P7DTWL.mjs → chunk-6KOUYHEY.mjs} +1 -1
  22. package/lib/chunk-6QSHWIZI.mjs +48 -0
  23. package/lib/chunk-6VOQFISN.mjs +7 -0
  24. package/lib/{chunk-742SSN7I.mjs → chunk-6YC2ELCU.mjs} +1 -1
  25. package/lib/chunk-77IVKH7R.mjs +7 -0
  26. package/lib/{chunk-KNIRA333.mjs → chunk-77MZRBWX.mjs} +1 -1
  27. package/lib/{chunk-ZUA5BNAO.mjs → chunk-7BQMBXKX.mjs} +1 -1
  28. package/lib/{chunk-OQQHNYR7.mjs → chunk-7DPHZWA4.mjs} +2 -2
  29. package/lib/chunk-7V2UYZ6S.mjs +7 -0
  30. package/lib/chunk-7WSQ65WG.mjs +9 -0
  31. package/lib/{chunk-HVC5CYIB.mjs → chunk-7ZBDACVG.mjs} +1 -1
  32. package/lib/chunk-A32ISQ6M.mjs +28 -0
  33. package/lib/{chunk-XC2QKQT5.mjs → chunk-AG24QMSY.mjs} +1 -1
  34. package/lib/{chunk-K77NR3UK.mjs → chunk-AHUGG3WU.mjs} +1 -1
  35. package/lib/{chunk-K55LH4ZQ.mjs → chunk-ALBY5SOH.mjs} +1 -1
  36. package/lib/chunk-AXFD2OH6.mjs +7 -0
  37. package/lib/{chunk-YCSFP6ER.mjs → chunk-BH76USTQ.mjs} +1 -1
  38. package/lib/chunk-BNKT3R3F.mjs +7 -0
  39. package/lib/{chunk-YIGFYZQY.mjs → chunk-BPHTA6KP.mjs} +1 -1
  40. package/lib/{chunk-MNITSYI2.mjs → chunk-BT43WSOS.mjs} +1 -1
  41. package/lib/{chunk-ZWZXQTAK.mjs → chunk-BVZ5H3N4.mjs} +14 -14
  42. package/lib/{chunk-43K2C6H2.mjs → chunk-C6RKM4BB.mjs} +1 -1
  43. package/lib/{chunk-C4YGSK6W.mjs → chunk-CDWZGQAJ.mjs} +1 -1
  44. package/lib/chunk-CGZGL6VT.mjs +7 -0
  45. package/lib/{chunk-KE2PGD6C.mjs → chunk-CN5HGFG4.mjs} +1 -1
  46. package/lib/chunk-CQAFVEKP.mjs +13 -0
  47. package/lib/{chunk-XIZ5LMQM.mjs → chunk-CTPLYUXA.mjs} +1 -1
  48. package/lib/chunk-CXKZ6TYV.mjs +9 -0
  49. package/lib/{chunk-DHIW4IO5.mjs → chunk-D6JT4PAB.mjs} +1 -1
  50. package/lib/{chunk-AELFEK3G.mjs → chunk-D7XUNWWU.mjs} +1 -1
  51. package/lib/{chunk-GR3NGDVM.mjs → chunk-DB5RVDC5.mjs} +1 -1
  52. package/lib/{chunk-MO3N5XVV.mjs → chunk-DIGUC7S4.mjs} +2 -2
  53. package/lib/{chunk-2OZG6GRW.mjs → chunk-DKDKCGXV.mjs} +1 -1
  54. package/lib/chunk-DMT5SCO3.mjs +7 -0
  55. package/lib/chunk-DNQKVCUV.mjs +475 -0
  56. package/lib/{chunk-MAHZMPMZ.mjs → chunk-DSR2MSBH.mjs} +1 -1
  57. package/lib/{chunk-O6ADMP36.mjs → chunk-E3RQ575Y.mjs} +1 -1
  58. package/lib/{chunk-ETT5GP4P.mjs → chunk-EOQON3E5.mjs} +1 -1
  59. package/lib/{chunk-TKQQVB2D.mjs → chunk-ETNQHIDI.mjs} +1 -1
  60. package/lib/chunk-F5SBGJWW.mjs +7 -0
  61. package/lib/chunk-FBXH4VRQ.mjs +7 -0
  62. package/lib/chunk-FKCIGJOI.mjs +15 -0
  63. package/lib/{chunk-OVOLG3AL.mjs → chunk-FVLFO2S6.mjs} +1 -1
  64. package/lib/{chunk-YOGMP72T.mjs → chunk-FYWNSMOZ.mjs} +1 -1
  65. package/lib/{chunk-DHGPDSXS.mjs → chunk-GEEWPTV5.mjs} +1 -1
  66. package/lib/{chunk-FSDO4DJA.mjs → chunk-GLN4PI5P.mjs} +1 -1
  67. package/lib/{chunk-PYUEHBA6.mjs → chunk-GT5ZKU6V.mjs} +1 -1
  68. package/lib/chunk-GTRU5AV5.mjs +7 -0
  69. package/lib/chunk-H33DVU3D.mjs +7 -0
  70. package/lib/{chunk-5WGA5CZB.mjs → chunk-H4OBZIX3.mjs} +1 -1
  71. package/lib/{chunk-4L7FBOJS.mjs → chunk-HQZUQXDC.mjs} +1 -1
  72. package/lib/{chunk-VSU74RQ3.mjs → chunk-HVX2AFYW.mjs} +1 -1
  73. package/lib/chunk-I3ZO76LL.mjs +21 -0
  74. package/lib/{chunk-V4RKM4QZ.mjs → chunk-I5C4O3VA.mjs} +1 -1
  75. package/lib/{chunk-FSZTXLNW.mjs → chunk-IHGYJZZ2.mjs} +1 -1
  76. package/lib/chunk-ISA2NYJV.mjs +7 -0
  77. package/lib/{chunk-2IB7I3IQ.mjs → chunk-ISAUCWYK.mjs} +1 -1
  78. package/lib/{chunk-3B5H24ZG.mjs → chunk-ISOSTAJR.mjs} +1 -1
  79. package/lib/chunk-IXIY6Q4M.mjs +7 -0
  80. package/lib/{chunk-TPHXRHOA.mjs → chunk-J3TIHLWG.mjs} +1 -1
  81. package/lib/{chunk-TQM2XJ27.mjs → chunk-JAV6F6OA.mjs} +1 -1
  82. package/lib/chunk-JBWJ6UEZ.mjs +7 -0
  83. package/lib/{chunk-WM5JI4JI.mjs → chunk-JH4ZTVQN.mjs} +1 -1
  84. package/lib/{chunk-BZFIOZS3.mjs → chunk-JIPT5FUD.mjs} +1 -1
  85. package/lib/{chunk-6FMLW7PH.mjs → chunk-JPEVIXNH.mjs} +1 -1
  86. package/lib/{chunk-67CC7RAE.mjs → chunk-JREKJO3D.mjs} +1 -1
  87. package/lib/{chunk-3AOKLIVE.mjs → chunk-JUOQUG7U.mjs} +1 -1
  88. package/lib/chunk-JYUMD357.mjs +7 -0
  89. package/lib/{chunk-56MPPWLA.mjs → chunk-K7G3W7XH.mjs} +1 -1
  90. package/lib/{chunk-OU5W7SCB.mjs → chunk-KKS2KFBT.mjs} +1 -1
  91. package/lib/{chunk-RKALOKAU.mjs → chunk-KWAVSZ2B.mjs} +1 -1
  92. package/lib/{chunk-WI4HYWV6.mjs → chunk-KXUOHACP.mjs} +1 -1
  93. package/lib/{chunk-GTIXJCGS.mjs → chunk-L3I6DAHX.mjs} +1 -1
  94. package/lib/{chunk-FLNLG43R.mjs → chunk-L47JCNP3.mjs} +1 -1
  95. package/lib/{chunk-5344TZBT.mjs → chunk-L4MSL4U7.mjs} +1 -1
  96. package/lib/chunk-L4RJX7DG.mjs +7 -0
  97. package/lib/chunk-L6CLN664.mjs +7 -0
  98. package/lib/chunk-LI2XNV7F.mjs +7 -0
  99. package/lib/chunk-LP2D3JJP.mjs +7 -0
  100. package/lib/{chunk-EH5YUA5W.mjs → chunk-LWES2KZE.mjs} +1 -1
  101. package/lib/{chunk-YJEXE6HZ.mjs → chunk-LYOGCIYD.mjs} +2 -2
  102. package/lib/{chunk-BNO5GIJ6.mjs → chunk-MJD6CPZZ.mjs} +1 -1
  103. package/lib/{chunk-33ZX3A56.mjs → chunk-MTM4KG3T.mjs} +1 -1
  104. package/lib/{chunk-E2YJVSX6.mjs → chunk-N2HYG3BL.mjs} +1 -1
  105. package/lib/chunk-N5UIE4IR.mjs +7 -0
  106. package/lib/{chunk-R6TF26V4.mjs → chunk-NDFFIJL5.mjs} +1 -1
  107. package/lib/{chunk-FDGFUEK3.mjs → chunk-NFEBX75O.mjs} +1 -1
  108. package/lib/{chunk-QXLZINZB.mjs → chunk-NNV7IGM7.mjs} +1 -1
  109. package/lib/{chunk-OXKZ4Y3B.mjs → chunk-NS6ONPWL.mjs} +1 -1
  110. package/lib/{chunk-OEHVAJAB.mjs → chunk-O7GCCRPW.mjs} +1 -1
  111. package/lib/chunk-OO24ZYYJ.mjs +7 -0
  112. package/lib/chunk-OOIDCHBQ.mjs +9 -0
  113. package/lib/{chunk-MWLFFVQV.mjs → chunk-OS5GE52G.mjs} +1 -1
  114. package/lib/chunk-OS6HFJ7L.mjs +7 -0
  115. package/lib/{chunk-HYBH5PFM.mjs → chunk-OTJH6AEA.mjs} +1 -1
  116. package/lib/chunk-OUU47Y7A.mjs +7 -0
  117. package/lib/{chunk-FTA5LOVX.mjs → chunk-P6WRYJN3.mjs} +1 -1
  118. package/lib/{chunk-DXOXLUZA.mjs → chunk-PDRXM5WN.mjs} +1 -1
  119. package/lib/chunk-PGRY365W.mjs +7 -0
  120. package/lib/chunk-Q4PPI3KG.mjs +7 -0
  121. package/lib/chunk-QFTF2PGS.mjs +21 -0
  122. package/lib/chunk-QKJXIY6L.mjs +7 -0
  123. package/lib/{chunk-DMBR24CK.mjs → chunk-QLRWU3MB.mjs} +1 -1
  124. package/lib/chunk-QO4MPHZD.mjs +7 -0
  125. package/lib/chunk-QP3JLFIO.mjs +7 -0
  126. package/lib/{chunk-UCHAZ4ZU.mjs → chunk-QQDZQCO2.mjs} +1 -1
  127. package/lib/chunk-QROPNEGY.mjs +14 -0
  128. package/lib/{chunk-6NADW3OI.mjs → chunk-QXB6U3ZP.mjs} +1 -1
  129. package/lib/chunk-R3OM3X4L.mjs +8 -0
  130. package/lib/chunk-R7GKMAT4.mjs +7 -0
  131. package/lib/{chunk-JU2XEKEO.mjs → chunk-RVCPQVKM.mjs} +1 -1
  132. package/lib/{chunk-WEZLXE34.mjs → chunk-RZKJQOOC.mjs} +1 -1
  133. package/lib/chunk-S4PRKKGC.mjs +8 -0
  134. package/lib/{chunk-NJ3EOEHS.mjs → chunk-SX6QWYCQ.mjs} +1 -1
  135. package/lib/{chunk-ONMBSACW.mjs → chunk-T36DZJPH.mjs} +1 -1
  136. package/lib/{chunk-AJPSGVMD.mjs → chunk-T7DDS4UQ.mjs} +1 -1
  137. package/lib/chunk-TCEXCHXR.mjs +7 -0
  138. package/lib/chunk-TMIESDE5.mjs +7 -0
  139. package/lib/chunk-TQJ5NPRC.mjs +7 -0
  140. package/lib/chunk-TUPZY2QJ.mjs +7 -0
  141. package/lib/{chunk-2Z54GB6X.mjs → chunk-U2CTKIPE.mjs} +1 -1
  142. package/lib/{chunk-DQR5NDMI.mjs → chunk-U4YFYSF3.mjs} +1 -1
  143. package/lib/{chunk-EOSEMFPU.mjs → chunk-UIR77ZJD.mjs} +1 -1
  144. package/lib/{chunk-UUSLTW5V.mjs → chunk-UOHZW2L4.mjs} +1 -1
  145. package/lib/chunk-UV74P4H2.mjs +7 -0
  146. package/lib/{chunk-CULAOP3U.mjs → chunk-VXZ5PTOM.mjs} +1 -1
  147. package/lib/{chunk-IBURU7T7.mjs → chunk-VZLJZEV2.mjs} +1 -1
  148. package/lib/chunk-W3BQGMTR.mjs +7 -0
  149. package/lib/{chunk-WWTXRWNZ.mjs → chunk-WABXKL4N.mjs} +1 -1
  150. package/lib/{chunk-E2OBAWSH.mjs → chunk-WAYQLQAD.mjs} +1 -1
  151. package/lib/{chunk-6CDIIFNX.mjs → chunk-WBELLGNE.mjs} +1 -1
  152. package/lib/{chunk-LO527YLT.mjs → chunk-WJAZ5LHL.mjs} +1 -1
  153. package/lib/{chunk-6IGEASOF.mjs → chunk-WXU6ZJIV.mjs} +1 -1
  154. package/lib/{chunk-YHIOS2PU.mjs → chunk-WZN36ACK.mjs} +1 -1
  155. package/lib/{chunk-AITNZWLB.mjs → chunk-X2XZQ434.mjs} +1 -1
  156. package/lib/chunk-X4HZD5U2.mjs +7 -0
  157. package/lib/chunk-X6XNTOGO.mjs +7 -0
  158. package/lib/{chunk-5VQNKDFU.mjs → chunk-XAMMIPZ4.mjs} +1 -1
  159. package/lib/{chunk-MHW6DV6T.mjs → chunk-XAUQXYPW.mjs} +1 -1
  160. package/lib/{chunk-5UT2ZBGF.mjs → chunk-XCJUNX63.mjs} +1 -1
  161. package/lib/chunk-XJICAOAQ.mjs +7 -0
  162. package/lib/{chunk-GYKNCYES.mjs → chunk-XKFHTBAB.mjs} +1 -1
  163. package/lib/{chunk-6SEDOIO3.mjs → chunk-XMQ5R6TC.mjs} +1 -1
  164. package/lib/chunk-XPXEQKLR.mjs +7 -0
  165. package/lib/{chunk-SW2NUKQL.mjs → chunk-Y7YUNRKK.mjs} +1 -1
  166. package/lib/{chunk-UIUPPEFB.mjs → chunk-YBZIDW6W.mjs} +1 -1
  167. package/lib/{chunk-X2ZVSQ54.mjs → chunk-YEVB7LVK.mjs} +1 -1
  168. package/lib/{chunk-EAFLDSQ2.mjs → chunk-Z3MGN42K.mjs} +1 -1
  169. package/lib/{chunk-MKNAZPOT.mjs → chunk-ZB5E7NHU.mjs} +1 -1
  170. package/lib/chunk-ZCOSME6P.mjs +7 -0
  171. package/lib/{chunk-KRNFVAGC.mjs → chunk-ZOSESZ22.mjs} +1 -1
  172. package/lib/chunk-ZTHC42X6.mjs +7 -0
  173. package/lib/{chunk-XEB6HZ34.mjs → chunk-ZXOUWHYE.mjs} +1 -1
  174. package/lib/sandforge-autopilot.mjs +1 -1
  175. package/lib/sandforge-backup.mjs +1 -1
  176. package/lib/sandforge-checkpoint.mjs +1 -1
  177. package/lib/sandforge-cleanup.mjs +1 -1
  178. package/lib/sandforge-clone.mjs +1 -1
  179. package/lib/sandforge-compare.mjs +1 -1
  180. package/lib/sandforge-dataops.mjs +1 -1
  181. package/lib/sandforge-empty.mjs +4 -4
  182. package/lib/sandforge-env.mjs +184 -139
  183. package/lib/sandforge-frozen.mjs +1 -1
  184. package/lib/sandforge-mcp.mjs +14 -14
  185. package/lib/sandforge-monitor.mjs +1 -1
  186. package/lib/sandforge-pipeline.mjs +1 -1
  187. package/lib/sandforge-seed.mjs +1 -1
  188. package/lib/sandforge-sync.mjs +1 -1
  189. package/lib/sandforge-users.mjs +155 -0
  190. package/lib/sandforge.mjs +1 -22
  191. package/lib/sf/sandforge/autopilot.mjs +20 -0
  192. package/lib/sf/sandforge/backup.mjs +20 -0
  193. package/lib/sf/sandforge/checkpoint.mjs +20 -0
  194. package/lib/sf/sandforge/cleanup.mjs +20 -0
  195. package/lib/sf/sandforge/clone.mjs +20 -0
  196. package/lib/sf/sandforge/compare.mjs +20 -0
  197. package/lib/sf/sandforge/dataops.mjs +20 -0
  198. package/lib/sf/sandforge/empty.mjs +20 -0
  199. package/lib/sf/sandforge/env.mjs +20 -0
  200. package/lib/sf/sandforge/frozen.mjs +20 -0
  201. package/lib/sf/sandforge/hardis-commands.mjs +20 -0
  202. package/lib/sf/sandforge/index.mjs +20 -0
  203. package/lib/sf/sandforge/mcp.mjs +20 -0
  204. package/lib/sf/sandforge/monitor.mjs +20 -0
  205. package/lib/sf/sandforge/pipeline.mjs +20 -0
  206. package/lib/sf/sandforge/seed.mjs +20 -0
  207. package/lib/sf/sandforge/sync.mjs +20 -0
  208. package/lib/sf/sandforge/users.mjs +20 -0
  209. package/lib/sfHelpHook.mjs +7 -0
  210. package/lib/sfPlugin.mjs +11 -0
  211. package/oclif.manifest.json +1 -0
  212. package/package.json +17 -3
  213. package/lib/chunk-2ZMGVBLW.mjs +0 -7
  214. package/lib/chunk-5C5XEVZN.mjs +0 -11
  215. package/lib/chunk-5CKWGZX4.mjs +0 -9
  216. package/lib/chunk-5ZKCLBTN.mjs +0 -474
  217. package/lib/chunk-7DALDJMO.mjs +0 -7
  218. package/lib/chunk-CAFUNR6D.mjs +0 -7
  219. package/lib/chunk-DPYTG6DM.mjs +0 -48
  220. package/lib/chunk-G4VXPS3A.mjs +0 -7
  221. package/lib/chunk-GF247DA7.mjs +0 -7
  222. package/lib/chunk-IKGHRYCN.mjs +0 -7
  223. package/lib/chunk-IM2XA6JI.mjs +0 -7
  224. package/lib/chunk-K5HV4YRO.mjs +0 -7
  225. package/lib/chunk-KOQV4WXC.mjs +0 -8
  226. package/lib/chunk-N6HHNR6J.mjs +0 -7
  227. package/lib/chunk-N7J6NJQ6.mjs +0 -7
  228. package/lib/chunk-NWPQF5XR.mjs +0 -7
  229. package/lib/chunk-O7DAFE6M.mjs +0 -14
  230. package/lib/chunk-OMZJ37JI.mjs +0 -15
  231. package/lib/chunk-R2BJWO5N.mjs +0 -20
  232. package/lib/chunk-T26C576X.mjs +0 -9
  233. package/lib/chunk-T5VAULLQ.mjs +0 -7
  234. package/lib/chunk-V2QO6KOE.mjs +0 -19
  235. package/lib/chunk-V473C7LY.mjs +0 -7
  236. package/lib/chunk-W2AAGIZF.mjs +0 -7
  237. package/lib/chunk-WD47PGUS.mjs +0 -10
  238. package/lib/chunk-XC54KKKC.mjs +0 -7
  239. package/lib/chunk-XGKSSCW7.mjs +0 -7
  240. package/lib/chunk-ZWCRWF7E.mjs +0 -7
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-QP3JLFIO.mjs";import"./chunk-CXKZ6TYV.mjs";import"./chunk-UV74P4H2.mjs";import"./chunk-N2HYG3BL.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-ISOSTAJR.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-6QSHWIZI.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{p as ObservedUsersRunStore,c as RECOVERY_CATEGORY,h as USERS_RUN_NOT_FOUND,i as USERS_RUN_REPLACED,a as awaitingAddressesOf,m as changingUsersOf,k as choicesKeyOf,l as planSignatureOf,f as readSavedTesters,d as recoveryTestersKey,b as recoveryUsersOf,j as replacedRunOf,g as saveTesters,e as savedTestersSchema,o as usersAuditObjectsOf,n as usersDoneOf};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{h as M,i as T}from"./chunk-DMBR24CK.mjs";import{p as b}from"./chunk-ICIYL45C.mjs";import{fc as _,gc as h,hc as p,ic as R,mc as C,nc as S,qc as k}from"./chunk-DPYTG6DM.mjs";async function Y(r,e){try{let[c,i]=await Promise.all([r(R),e(R)]),d=c[0]?.Id,a=i[0]?.Id;return typeof d=="string"&&typeof a=="string"?{source:d,target:a}:void 0}catch{return}}function v(r,e){return r===h||e.some(c=>typeof c[p]=="string")}var K=[p,C,S];function A(r,e,c,i,d=()=>!1){let a={...e,standsFor:new Map,standardFirst:0,standardMatched:!1,prices:[],leftIn:new Map};if(!c)return a;let o=e.records.map((t,s)=>s),m=t=>({records:t.map(s=>e.records[s]),sources:t.map(s=>e.sources[s]),sourceIds:t.map(s=>e.sourceIds[s])});if(r===h){let t=o.filter(s=>e.sourceIds[s]!==c.source);return t.length===o.length?a:{...m(t),standsFor:new Map,standardFirst:0,standardMatched:!0,prices:[],leftIn:new Map}}if(r!==_)return a;let l=o,I=new Map,P=new Map,O=[];if(i){let{target:t}=i,s=e.sources.filter(n=>!K.some(f=>{let u=n[f];return typeof u=="string"&&u!==""&&d(u)})),E=n=>t.active.has(n)?n:b(void 0,t)?.to,g=M({prices:s,standardBookId:c.source,sellingModels:s.some(n=>typeof n[S]=="string"),writtenIn:E,active:t.active},[]),B=new Set(g.standsFor.keys());l=o.filter(n=>{let f=e.sourceIds[n];return f===void 0||!B.has(f)});let D=new Map(s.map(n=>[n.Id,n[k]]));for(let[n,f]of g.standsFor){I.set(n,f);let u=D.get(n),w=typeof u=="string"?E(u):void 0;typeof u=="string"&&w!==void 0&&P.set(n,{from:u,to:w})}O=T(g.said)}let y=t=>e.sources[t][p]===c.source,F=[...l.filter(y),...l.filter(t=>!y(t))];return{...m(F),standsFor:I,standardFirst:l.filter(y).length,standardMatched:!1,prices:O,leftIn:P}}function Q(r,e){let c=r.prices.map(i=>({...i}));for(let i of e){let d=r.leftIn.get(i),a=d&&(c.find(o=>o.from===d.from&&o.to===d.to&&o.how==="replaced"&&!o.forLines)??c.find(o=>o.from===d.from&&o.to===d.to&&o.how==="replaced"));a&&a.prices--}return c.filter(i=>i.prices>0)}function q(r,e){return e===1?`1 ${r} record held back, not sent: read in a currency the target org does not hold active, it stands for the source's own price of its product and price book in the currency written, which this run did not write.`:`${e} ${r} records held back, not sent: read in a currency the target org does not hold active, they stand for the source's own prices of their product and price book in the currency written, which this run did not write.`}var H="The standard price book is matched to the target org's, never written.";function $(r,e){return e.prices.length===0&&!e.standardMatched?r:{...r,...e.prices.length>0?{pricesSettled:[...e.prices]}:{},...e.standardMatched?{standardPricebookMatched:!0}:{}}}export{Y as a,v as b,A as c,Q as d,q as e,H as f,$ as g};
7
+ import{h as M,i as T}from"./chunk-QLRWU3MB.mjs";import{p as b}from"./chunk-ICIYL45C.mjs";import{Ec as _,Fc as h,Gc as p,Hc as R,Lc as C,Mc as S,Pc as k}from"./chunk-6QSHWIZI.mjs";async function Y(r,e){try{let[c,i]=await Promise.all([r(R),e(R)]),d=c[0]?.Id,a=i[0]?.Id;return typeof d=="string"&&typeof a=="string"?{source:d,target:a}:void 0}catch{return}}function v(r,e){return r===h||e.some(c=>typeof c[p]=="string")}var K=[p,C,S];function A(r,e,c,i,d=()=>!1){let a={...e,standsFor:new Map,standardFirst:0,standardMatched:!1,prices:[],leftIn:new Map};if(!c)return a;let o=e.records.map((t,s)=>s),m=t=>({records:t.map(s=>e.records[s]),sources:t.map(s=>e.sources[s]),sourceIds:t.map(s=>e.sourceIds[s])});if(r===h){let t=o.filter(s=>e.sourceIds[s]!==c.source);return t.length===o.length?a:{...m(t),standsFor:new Map,standardFirst:0,standardMatched:!0,prices:[],leftIn:new Map}}if(r!==_)return a;let l=o,I=new Map,P=new Map,O=[];if(i){let{target:t}=i,s=e.sources.filter(n=>!K.some(f=>{let u=n[f];return typeof u=="string"&&u!==""&&d(u)})),E=n=>t.active.has(n)?n:b(void 0,t)?.to,g=M({prices:s,standardBookId:c.source,sellingModels:s.some(n=>typeof n[S]=="string"),writtenIn:E,active:t.active},[]),B=new Set(g.standsFor.keys());l=o.filter(n=>{let f=e.sourceIds[n];return f===void 0||!B.has(f)});let D=new Map(s.map(n=>[n.Id,n[k]]));for(let[n,f]of g.standsFor){I.set(n,f);let u=D.get(n),w=typeof u=="string"?E(u):void 0;typeof u=="string"&&w!==void 0&&P.set(n,{from:u,to:w})}O=T(g.said)}let y=t=>e.sources[t][p]===c.source,F=[...l.filter(y),...l.filter(t=>!y(t))];return{...m(F),standsFor:I,standardFirst:l.filter(y).length,standardMatched:!1,prices:O,leftIn:P}}function Q(r,e){let c=r.prices.map(i=>({...i}));for(let i of e){let d=r.leftIn.get(i),a=d&&(c.find(o=>o.from===d.from&&o.to===d.to&&o.how==="replaced"&&!o.forLines)??c.find(o=>o.from===d.from&&o.to===d.to&&o.how==="replaced"));a&&a.prices--}return c.filter(i=>i.prices>0)}function q(r,e){return e===1?`1 ${r} record held back, not sent: read in a currency the target org does not hold active, it stands for the source's own price of its product and price book in the currency written, which this run did not write.`:`${e} ${r} records held back, not sent: read in a currency the target org does not hold active, they stand for the source's own prices of their product and price book in the currency written, which this run did not write.`}var H="The standard price book is matched to the target org's, never written.";function $(r,e){return e.prices.length===0&&!e.standardMatched?r:{...r,...e.prices.length>0?{pricesSettled:[...e.prices]}:{},...e.standardMatched?{standardPricebookMatched:!0}:{}}}export{Y as a,v as b,A as c,Q as d,q as e,H as f,$ as g};
@@ -0,0 +1,7 @@
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{b as I}from"./chunk-CA5NAXSU.mjs";import{dd as u,s as A}from"./chunk-6QSHWIZI.mjs";import{createHash as E}from"node:crypto";var b="lineage:runs",h="lineage";function y(t){let e=t.objects.filter(i=>i.records>0);if(e.length===0)return null;let o="source",r="target",n=[{id:o,type:"source",label:t.source.label,origin:t.source.origin,...t.source.orgId?{orgId:t.source.orgId}:{}}],a=[];for(let i of e){let d=`object:${i.objectApiName}`;n.push({id:d,type:"object",label:i.objectApiName,objectApiName:i.objectApiName,recordCount:i.records}),a.push({sourceId:o,targetId:d}),a.push({sourceId:d,targetId:r,recordCount:i.records})}return n.push({id:r,type:"destination",label:t.target.label,orgId:t.target.orgId,origin:"org"}),{nodes:n,edges:a,operationId:t.operationId,generatedAt:t.generatedAt,module:t.module,action:t.action}}var c=class{constructor(e,o=100){this.configStore=e;this.limit=o}configStore;limit;save(e){let o=this.read().filter(r=>r.operationId!==e.operationId);o.push(e),this.configStore.set(b,o.slice(-this.limit),h)}get(e){let o=this.read();return e===void 0?o[o.length-1]??null:o.find(r=>r.operationId===e)??null}runs(){return this.read().reverse().map(e=>({operationId:e.operationId,generatedAt:e.generatedAt,...e.module?{module:e.module}:{},...e.action?{action:e.action}:{},...R(e)}))}read(){let e=this.configStore.get(b);return Array.isArray(e)?e.filter(S):[]}};function R(t){let e=t.nodes.find(o=>o.type==="destination");return e?{targetLabel:e.label}:{}}function S(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.operationId=="string"&&typeof e.generatedAt=="string"&&Array.isArray(e.nodes)&&Array.isArray(e.edges)}var j=100,L="audit:trail",O="audit",l=class{constructor(e,o=A){this.configStore=e;this.limit=o}configStore;limit;append(e){let o=this.read();o.push(e),this.configStore.set(L,o.slice(-this.limit),O)}list(e={}){let o=this.read().reverse(),r=o.filter(i=>(e.module===void 0||i.module===e.module)&&(e.orgId===void 0||i.orgId===e.orgId)),n=e.offset??0,a=e.limit??j;return{entries:r.slice(n,n+a),total:r.length,offset:n,facets:x(o)}}read(){let e=this.configStore.get(L);return Array.isArray(e)?e.filter(D):[]}};function x(t){let e=new Set,o=new Map;for(let r of t)e.add(r.module),r.orgId!==void 0&&!o.has(r.orgId)&&o.set(r.orgId,r.orgAlias);return{modules:[...e].sort(),orgs:[...o].map(([r,n])=>n?{orgId:r,orgAlias:n}:{orgId:r})}}function D(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.action=="string"&&typeof e.module=="string"&&typeof e.timestamp=="string"}var w="ABORTED_BEFORE_START";function v(t){let e=t?.trim().toLowerCase();if(e)return`sha256:${E("sha256").update(e).digest("hex").slice(0,12)}`}function P(t,e,o=new Date){try{let r=t.services?.getSandforgeSetting?.("safety.auditLogging",!0)!==!1;if(!r&&e.outcome==="stopped"&&e.code===void 0)return;let n=o.toISOString(),a=t.orgManager.getOrg(e.orgId),i=a?u(a):void 0,d=v(a?.username),s=e.source?.origin==="org"?e.source.orgId:void 0,f=s!==void 0?t.orgManager.getOrg(s):void 0,g=f?u(f):void 0,p=e.objects??[];if(new l(t.configStore).append({id:crypto.randomUUID(),action:e.action,module:e.module,orgId:e.orgId,...i?{orgAlias:i}:{},...s!==void 0?{sourceOrgId:s}:{},...g?{sourceOrgAlias:g}:{},operationId:e.operationId,outcome:e.outcome,...r&&e.guard?{guard:e.guard}:{},objects:[...p],...e.leftBy?{leftBy:e.leftBy}:{},...d?{userId:d}:{},...e.context?{context:e.context}:{},...e.verdict?{verdict:e.verdict}:{},...e.muted?{muted:e.muted}:{},...e.checkpointId?{checkpointId:e.checkpointId}:{},...e.beforeRun?{beforeRun:{...e.beforeRun}}:{},...e.fit?{fit:{...e.fit}}:{},details:{...e.details,...e.code?{code:e.code}:{}},timestamp:n}),!e.source)return;let m=y({operationId:e.operationId,module:e.module,action:e.action,source:e.source.origin==="org"?{origin:"org",orgId:e.source.orgId,label:g??e.source.orgId}:{origin:e.source.origin,label:e.source.label??""},target:{label:i??e.orgId,orgId:e.orgId},objects:C(p,e.carried),generatedAt:n});m&&new c(t.configStore).save(m)}catch(r){t.log(`[WARN] audit trail: run ${e.operationId} was not recorded \u2014 ${I(r)}`)}}function C(t,e){return e?Object.entries(e).map(([o,r])=>({objectApiName:o,records:r})):t.map(o=>({objectApiName:o.objectApiName,records:o.created+o.updated+(o.upserted??0)}))}function F(t){return{objectApiName:t,created:0,updated:0,deleted:0,failed:0}}export{c as a,l as b,w as c,v as d,P as e,F as f};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{h as S,i as g,j as m,v as R}from"./chunk-MNITSYI2.mjs";var y=20,v="seed-runs",l="sandforge-seed",h=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function O(s,e){let t=s.finishedAt??new Date().toISOString();return{runId:s.runId,configId:l,configName:l,sourceOrgId:s.targetOrgId,targetOrgId:s.targetOrgId,startedAt:s.startedAt??t,end:{at:t,status:s.status},lastWrittenAt:t,created:s.objectResults.filter(d=>d.createdIds.length>0).map(d=>({objectApiName:d.objectApiName,ids:[...d.createdIds]})),...s.runUserId!==void 0&&h.test(s.runUserId)?{runUserId:s.runUserId}:{},...e?{removal:e}:{}}}function N(s,e){return new I(S(s,v,e))}var I=class{constructor(e,t=y){this.runs=e;this.max=t}runs;max;recorder(e){let t=this.runs.recorder({runId:e.runId,configId:l,configName:l,sourceOrgId:e.sourceOrgId??e.targetOrgId,targetOrgId:e.targetOrgId,...e.startedAt!==void 0?{startedAt:e.startedAt}:{},...e.origin!==void 0?{origin:e.origin}:{},...e.pipeline!==void 0?{pipeline:{name:e.pipeline.name.slice(0,m)}}:{},...e.targetOrganizationId!==void 0?{targetOrganizationId:e.targetOrganizationId}:{},...e.targetAlias!==void 0?{targetAlias:e.targetAlias}:{},...e.runUserId!==void 0&&h.test(e.runUserId)?{runUserId:e.runUserId}:{}}),d=new Set,u=n=>{let i=n.filter(r=>!d.has(r.slice(0,15)));for(let r of i)d.add(r.slice(0,15));return i},a=(n,i)=>{for(let r=0;r<n.length;r+=g)i(n.slice(r,r+g))},f=(n,i,r)=>a(u(i),o=>t.note(n,o,r)),c=new Map,p=!1;return{runId:e.runId,note:(n,i)=>f(n,i),sending:(n,i,r)=>{r?.job!==void 0?c.set(n,r.job):c.delete(n),t.sending?.(n,i,r)},answered:(n,i)=>{c.delete(n);let r=u(i);t.answered?.(n,r.slice(0,g)),a(r.slice(g),o=>t.note(n,o))},wroteAgain:(n,i)=>a(i.filter(r=>d.has(r.slice(0,15))),r=>t.note(n,r)),checkpoint:n=>t.checkpoint?.(n),runUser:n=>{p||t.runUser?.(n)},end:async n=>{let i=n.finishedAt??new Date().toISOString();for(let{objectApiName:o,createdIds:A}of n.objectResults)f(o,A,i);if(d.size===0&&c.size===0){p=!0,await t.flush(),await this.runs.forget(e.runId);return}await t.end({status:n.status,...n.cancelled?{cancelled:!0}:{},at:i});let r=await t.flush();if(r!==void 0)throw new Error(r);await this.keepTheLatest()}}}record(e){let t=e.startedAt??e.finishedAt;return this.recorder({runId:e.runId,targetOrgId:e.targetOrgId,...t!==void 0?{startedAt:t}:{},...e.runUserId!==void 0?{runUserId:e.runUserId}:{}}).end(e)}async keepTheLatest(){let e=(await this.runs.list()).filter(R),t=e.length-this.max;for(let d of[...e].reverse()){if(t<=0)return;await this.runs.forget(d.runId),t--}}pathOf(e){return this.runs.pathOf(e)}get storagePath(){return this.runs.storagePath}get(e){return this.runs.get(e)}list(){return this.runs.list()}answerInFlight(e,t,d,u,a){return this.runs.answerInFlight(e,t,d,u,a)}async updateRemoval(e,t){await this.runs.get(e)&&await this.runs.updateRemoval(e,t)}};export{y as a,v as b,O as c,N as d,I as e};
7
+ import{h as S,i as g,j as m,v as R}from"./chunk-BT43WSOS.mjs";var y=20,v="seed-runs",l="sandforge-seed",h=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function O(s,e){let t=s.finishedAt??new Date().toISOString();return{runId:s.runId,configId:l,configName:l,sourceOrgId:s.targetOrgId,targetOrgId:s.targetOrgId,startedAt:s.startedAt??t,end:{at:t,status:s.status},lastWrittenAt:t,created:s.objectResults.filter(d=>d.createdIds.length>0).map(d=>({objectApiName:d.objectApiName,ids:[...d.createdIds]})),...s.runUserId!==void 0&&h.test(s.runUserId)?{runUserId:s.runUserId}:{},...e?{removal:e}:{}}}function N(s,e){return new I(S(s,v,e))}var I=class{constructor(e,t=y){this.runs=e;this.max=t}runs;max;recorder(e){let t=this.runs.recorder({runId:e.runId,configId:l,configName:l,sourceOrgId:e.sourceOrgId??e.targetOrgId,targetOrgId:e.targetOrgId,...e.startedAt!==void 0?{startedAt:e.startedAt}:{},...e.origin!==void 0?{origin:e.origin}:{},...e.pipeline!==void 0?{pipeline:{name:e.pipeline.name.slice(0,m)}}:{},...e.targetOrganizationId!==void 0?{targetOrganizationId:e.targetOrganizationId}:{},...e.targetAlias!==void 0?{targetAlias:e.targetAlias}:{},...e.runUserId!==void 0&&h.test(e.runUserId)?{runUserId:e.runUserId}:{}}),d=new Set,u=n=>{let i=n.filter(r=>!d.has(r.slice(0,15)));for(let r of i)d.add(r.slice(0,15));return i},a=(n,i)=>{for(let r=0;r<n.length;r+=g)i(n.slice(r,r+g))},f=(n,i,r)=>a(u(i),o=>t.note(n,o,r)),c=new Map,p=!1;return{runId:e.runId,note:(n,i)=>f(n,i),sending:(n,i,r)=>{r?.job!==void 0?c.set(n,r.job):c.delete(n),t.sending?.(n,i,r)},answered:(n,i)=>{c.delete(n);let r=u(i);t.answered?.(n,r.slice(0,g)),a(r.slice(g),o=>t.note(n,o))},wroteAgain:(n,i)=>a(i.filter(r=>d.has(r.slice(0,15))),r=>t.note(n,r)),checkpoint:n=>t.checkpoint?.(n),runUser:n=>{p||t.runUser?.(n)},end:async n=>{let i=n.finishedAt??new Date().toISOString();for(let{objectApiName:o,createdIds:A}of n.objectResults)f(o,A,i);if(d.size===0&&c.size===0){p=!0,await t.flush(),await this.runs.forget(e.runId);return}await t.end({status:n.status,...n.cancelled?{cancelled:!0}:{},at:i});let r=await t.flush();if(r!==void 0)throw new Error(r);await this.keepTheLatest()}}}record(e){let t=e.startedAt??e.finishedAt;return this.recorder({runId:e.runId,targetOrgId:e.targetOrgId,...t!==void 0?{startedAt:t}:{},...e.runUserId!==void 0?{runUserId:e.runUserId}:{}}).end(e)}async keepTheLatest(){let e=(await this.runs.list()).filter(R),t=e.length-this.max;for(let d of[...e].reverse()){if(t<=0)return;await this.runs.forget(d.runId),t--}}pathOf(e){return this.runs.pathOf(e)}get storagePath(){return this.runs.storagePath}get(e){return this.runs.get(e)}list(){return this.runs.list()}answerInFlight(e,t,d,u,a){return this.runs.answerInFlight(e,t,d,u,a)}async updateRemoval(e,t){await this.runs.get(e)&&await this.runs.updateRemoval(e,t)}};export{y as a,v as b,O as c,N as d,I as e};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as c}from"./chunk-RKALOKAU.mjs";var p=class{apply(n,r,t=[]){return m(n,r,t)}applyAddOns(n,r){let t={...n};for(let o of r)(!(o.fieldApiName in t)||o.overwriteExisting)&&(t[o.fieldApiName]=o.value);return t}},g=new Set(["direct","rename","transform","add_on"]),i=e=>e.toLowerCase();function S(e){return new Set(e.filter(n=>n.type!=="exclude").map(n=>i(n.targetField)))}function w(e,n=[]){let r=new Set(n.map(i));for(let t of e)(g.has(t.type)||t.type==="exclude")&&r.add(i(t.sourceField)),r.add(i(t.targetField));return r}var y=new c;function m(e,n,r=[]){if(n.length===0&&r.length===0)return{...e};let t=new Set(r.map(i)),o=Object.fromEntries(Object.entries(e).filter(([s])=>!t.has(i(s)))),d=w(n,r),l=Object.fromEntries(Object.entries(o).filter(([s])=>!d.has(i(s))));for(let s of n){let u=R(o,s);u!==void 0&&(l[s.targetField]=u)}return l}function a(e,n){if(n in e)return e[n];let r=i(n),t=Object.keys(e).find(o=>i(o)===r);return t===void 0?void 0:e[t]}var f=Symbol("exclude");function R(e,n){let r=F[n.type],t=r(e,n);if(!(t===f||t===void 0))return n.transformRules&&n.transformRules.length>0?y.transform(t,n.transformRules):t}var F={direct:(e,n)=>a(e,n.sourceField),rename:(e,n)=>a(e,n.sourceField),transform:(e,n)=>a(e,n.sourceField),constant:(e,n)=>n.targetField?n.sourceField:void 0,formula:(e,n)=>k(e,n.sourceField),exclude:()=>f,add_on:(e,n)=>a(e,n.sourceField)};function k(e,n){return/\{(\w+)\}/g.test(n)?n.replace(/\{(\w+)\}/g,(t,o)=>{let d=e[o];return d!=null?String(d):""}):e[n]}export{p as a,g as b,S as c,w as d,m as e};
7
+ import{a as c}from"./chunk-KWAVSZ2B.mjs";var p=class{apply(n,r,t=[]){return m(n,r,t)}applyAddOns(n,r){let t={...n};for(let o of r)(!(o.fieldApiName in t)||o.overwriteExisting)&&(t[o.fieldApiName]=o.value);return t}},g=new Set(["direct","rename","transform","add_on"]),i=e=>e.toLowerCase();function S(e){return new Set(e.filter(n=>n.type!=="exclude").map(n=>i(n.targetField)))}function w(e,n=[]){let r=new Set(n.map(i));for(let t of e)(g.has(t.type)||t.type==="exclude")&&r.add(i(t.sourceField)),r.add(i(t.targetField));return r}var y=new c;function m(e,n,r=[]){if(n.length===0&&r.length===0)return{...e};let t=new Set(r.map(i)),o=Object.fromEntries(Object.entries(e).filter(([s])=>!t.has(i(s)))),d=w(n,r),l=Object.fromEntries(Object.entries(o).filter(([s])=>!d.has(i(s))));for(let s of n){let u=R(o,s);u!==void 0&&(l[s.targetField]=u)}return l}function a(e,n){if(n in e)return e[n];let r=i(n),t=Object.keys(e).find(o=>i(o)===r);return t===void 0?void 0:e[t]}var f=Symbol("exclude");function R(e,n){let r=F[n.type],t=r(e,n);if(!(t===f||t===void 0))return n.transformRules&&n.transformRules.length>0?y.transform(t,n.transformRules):t}var F={direct:(e,n)=>a(e,n.sourceField),rename:(e,n)=>a(e,n.sourceField),transform:(e,n)=>a(e,n.sourceField),constant:(e,n)=>n.targetField?n.sourceField:void 0,formula:(e,n)=>k(e,n.sourceField),exclude:()=>f,add_on:(e,n)=>a(e,n.sourceField)};function k(e,n){return/\{(\w+)\}/g.test(n)?n.replace(/\{(\w+)\}/g,(t,o)=>{let d=e[o];return d!=null?String(d):""}):e[n]}export{p as a,g as b,S as c,w as d,m as e};
@@ -4,7 +4,7 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{q as Nt}from"./chunk-MO3N5XVV.mjs";import{a as It}from"./chunk-2NAIUKVL.mjs";import{i as pe,j as Bt,l as Ut,m as Pe,n as Wt,o as Gt,p as qt,q as Vt,r as he,s as me,w as Kt}from"./chunk-V2QO6KOE.mjs";import{g as _t}from"./chunk-WD47PGUS.mjs";import{e as xt,g as Mt}from"./chunk-5C5XEVZN.mjs";import{f as Dt,h as Pt}from"./chunk-DXOXLUZA.mjs";import{a as Ht}from"./chunk-TW3N6W5Z.mjs";import{Db as Lt,Wa as oe,c as je,d as Le,e as bt,f as At,h as $t,i as Ne,j as kt,k as Rt,l as St,lb as Ie,m as Ot,mb as Tt,pb as De,q as Ft,qb as fe,sb as zt,tb as ne,xb as Ct,yb as jt}from"./chunk-YJEXE6HZ.mjs";import{a as te,d as gt,j as Ce,l as yt,m as vt}from"./chunk-O7DAFE6M.mjs";import{b as de,e as at}from"./chunk-BZ24IAP5.mjs";import{a as ke}from"./chunk-SCKUIE3R.mjs";import{c as ee,d as ue}from"./chunk-6FARZYMJ.mjs";import{b as le}from"./chunk-CAFUNR6D.mjs";import{m as wt}from"./chunk-KGYXLSQ5.mjs";import{d as ut}from"./chunk-T63U4OZJ.mjs";import{b as st,c as Se}from"./chunk-HVC5CYIB.mjs";import{B as Z,s as Ee,u as Fe,v as Te}from"./chunk-T26C576X.mjs";import{Ic as ht,Jc as mt,eb as ze,hb as ce,kb as ct,lb as ft,mc as J,tc as pt}from"./chunk-KOQV4WXC.mjs";import{q as lt}from"./chunk-2OIRJEYE.mjs";import{b as rt,f as it,g as dt,h as Et}from"./chunk-LCDPCUXS.mjs";import{E as Oe}from"./chunk-55LQD3Y3.mjs";import{Ad as ot,Hd as nt,xc as et,xd as tt,yd as Re,zd as ie}from"./chunk-DPYTG6DM.mjs";import{existsSync as _e,mkdirSync as mo,readdirSync as go,readFileSync as ve}from"node:fs";import{dirname as wo,join as G}from"node:path";import{homedir as yo}from"node:os";var vo=`sandforge frozen \u2014 build and replay a Frozen Dataset, without the editor.
7
+ import{q as Nt}from"./chunk-DIGUC7S4.mjs";import{a as It}from"./chunk-4V3QO7HF.mjs";import{a as _t,b as pe,c as Bt,e as Ut,f as Pe,g as Wt,h as Gt,i as qt,j as Vt,k as he,l as me,m as Kt}from"./chunk-I3ZO76LL.mjs";import{e as xt,g as Mt}from"./chunk-CQAFVEKP.mjs";import{f as Dt,h as Pt}from"./chunk-PDRXM5WN.mjs";import{a as Ht}from"./chunk-TW3N6W5Z.mjs";import{Db as Lt,Wa as oe,c as je,d as Le,e as bt,f as At,h as $t,i as Ne,j as kt,k as Rt,l as St,lb as Ie,m as Ot,mb as Tt,pb as De,q as Ft,qb as fe,sb as zt,tb as ne,xb as Ct,yb as jt}from"./chunk-LYOGCIYD.mjs";import{a as te,d as gt,j as Ce}from"./chunk-BNKT3R3F.mjs";import{a as yt,b as vt}from"./chunk-QROPNEGY.mjs";import{b as de,e as at}from"./chunk-BZ24IAP5.mjs";import{a as ke}from"./chunk-SCKUIE3R.mjs";import{c as ee,d as ue}from"./chunk-6FARZYMJ.mjs";import{b as le}from"./chunk-AXFD2OH6.mjs";import{m as wt}from"./chunk-5OGNK3JP.mjs";import{d as ut}from"./chunk-T63U4OZJ.mjs";import{a as Ee,c as Fe,d as Te,j as Z}from"./chunk-7WSQ65WG.mjs";import{b as st,c as Se}from"./chunk-7ZBDACVG.mjs";import{Cc as ht,Dc as mt,_a as ze,bb as ce,eb as ct,fb as ft,gc as J,nc as pt}from"./chunk-R3OM3X4L.mjs";import{q as lt}from"./chunk-2WMKJVD2.mjs";import{b as rt,f as it,g as dt,h as Et}from"./chunk-LCDPCUXS.mjs";import{E as Oe}from"./chunk-2GSMHGIV.mjs";import{Wc as et,Wd as tt,Xd as Re,Yd as ie,Zd as ot,ee as nt}from"./chunk-6QSHWIZI.mjs";import{existsSync as _e,mkdirSync as mo,readdirSync as go,readFileSync as ve}from"node:fs";import{dirname as wo,join as G}from"node:path";import{homedir as yo}from"node:os";var vo=`sandforge frozen \u2014 build and replay a Frozen Dataset, without the editor.
8
8
 
9
9
  Usage:
10
10
  npx sandforge frozen <step> --config <file> [options]
@@ -263,7 +263,7 @@ FAILED or PARTIAL; one UNSTABLE is said, and the verify step gives it a code.
263
263
  `),process.exit(2));let a=jt(t);"refusal"in a&&(process.stderr.write(`${a.refusal} Run with --help.
264
264
  `),process.exit(2));let l;if(t.includes("--max-total")){let p=o("--max-total");l=Number(p),n!=="load"&&(process.stderr.write(`--max-total goes with load. Run with --help.
265
265
  `),process.exit(2)),(p===void 0||!/^\d+$/.test(p)||l<1||l>Zt)&&(process.stderr.write(`--max-total takes a whole number from 1 to ${Zt}, not "${p??""}".
266
- `),process.exit(2))}return{step:n,configPath:s,source:i,target:m,author:o("--author"),storePath:o("--store"),saltFile:o("--salt-file"),pilot:t.includes("--pilot"),reload:t.includes("--reload"),dryRun:t.includes("--dry-run"),writeEncrypted:t.includes("--write-encrypted"),muteAutomation:t.includes("--mute-automation"),acceptAutomation:t.includes("--accept-automation"),...d!==void 0?{checkpointFirst:d}:{},includeChanged:t.includes("--include-changed"),acceptEmails:t.includes("--accept-emails"),sweep:t.includes("--sweep"),sweepList:t.includes("--sweep-list"),...a,preview:t.includes("--preview"),...l!==void 0?{maxTotal:l}:{},...r!==void 0?{goneFirst:r}:{},yes:t.includes("--yes"),json:t.includes("--json")}}async function ko(e){let o=(await e.query("SELECT Id, IsSandbox FROM Organization LIMIT 1")).records[0];if(!o)throw new Error("The org gave no Organization record.");if(o.IsSandbox)return{id:o.Id,orgType:"Sandbox"};try{let s=(await e.query("SELECT OrganizationType FROM Organization LIMIT 1")).records[0]?.OrganizationType;return typeof s=="string"&&s!==""?{id:o.Id,orgType:et({isSandbox:!1,edition:s}),edition:s}:{id:o.Id,orgType:"Production"}}catch{return{id:o.Id,orgType:"Production"}}}async function Jt(e,t,o,n){let s=await st(e),i=Se(s),m;try{m=await ko(i)}catch(r){let d=r instanceof Error?r.message:String(r);throw new Error(`Could not read the Organization record of '${e}': ${d}`)}return t.set(m.id,{org:{id:m.id,alias:e,orgType:m.orgType,metadata:{apiVersion:"66.0",...m.edition?{edition:m.edition}:{}},username:s.username,instanceUrl:s.instanceUrl},credentials:{accessToken:s.accessToken,instanceUrl:s.instanceUrl}}),o?.set(m.id,i),n?.set(m.id,{session:s,typed:m}),m.id}var x={run:"load",done:"loaded",source:"the frozen dataset",recordedIn:"in this sas",remove:"`remove`",module:"frozen",again:"reload",againSubject:{purge:"reload",sweep:"reloadSweep"},maybeMasks:"the dataset's manifest does not say its extraction left out what it read masked, so they may hold masks such as ****1234; --write-encrypted writes them as the dataset holds them"};function We(e){return!e||e.length===0?[]:[`kept: the platform does not delete them \u2014 ${e.map(({objectApiName:o,count:n})=>`${o} (${n})`).join(", ")}`]}function Qt(e,t,o=x){let n=(e??[]).filter(i=>i.reason==="may-hold-masks");if(n.length===0)return[];let s=n.map(({objectApiName:i,field:m,affectedRecords:r})=>`${i}.${m} (${r})`).join(", ");return[`${t} out, encrypted in the target: ${s} \u2014 ${o.maybeMasks}`]}function Ro(e,t){let o=e==="token"?"each record its own, from the token the value carries":`each record its own, its rank appended: the field is ${e==="unique"?"unique in the target":"the record name"}`;return t===void 0?o:`${o} (first: "${t}")`}function Ge(e){return e.created.reduce((t,o)=>t+o.count,0)}function So(e){return{...e.includeChanged?{includeChanged:!0}:{},...e.sweep?{sweep:!0}:{},...e.sweepLate?{sweepLate:!0}:{},...e.sweepUntied?{sweepUntied:!0}:{},...e.muteAutomation?{muteAutomation:!0}:{}}}var Oo={removal:{heading:"removal",writer:"this removal",verb:"remove"},reload:{heading:"reload",writer:"this reload's purge",verb:"reload"},reloadSweep:{heading:"reload",writer:"this reload's sweep",verb:"reload"},replayAgain:{heading:"replay",writer:"this replay's purge",verb:"replay again"},replayAgainSweep:{heading:"replay",writer:"this replay's sweep",verb:"replay again"}};function xe({read:e,steps:t,mute:o},n,s="removal",i){let m=o?Z(o.muted,n).map(l=>` ${l}`):[];if(!("objects"in e)){let l=Oo[s],p=s==="reload"||s==="replayAgain",g=`${l.writer}${p&&i?" and its sweep":""}`;return{lines:[`${l.heading} automation: what ${n} runs could not be read: ${e.unread}`,...m],refusal:`What ${n} runs as ${g} writes could not be read (${e.unread}), so what fires as the records go is not known. Nothing was written or deleted. Add --accept-automation to ${l.verb} all the same, or turn that automation off in ${n} first.`}}let r=o?.automation??e,d=i?tt(t,i.delete??[]):t,a=mt(r,n,{steps:t,...i?{sweep:i}:{},assign:pt(r,ot(r,d)),mayMute:o===void 0&&Ce("--mute-automation"),subject:s});return{lines:[...ht(e,n,t,s,i),...m],...a!==void 0?{refusal:a}:{}}}function Eo(e,t,o=x){let n=Ge(e),s=e.earlier?`a ${o.run} before the last one, whose records the ${o.run}s after it left in place,`:`the last ${o.run}`,i=`a removal deletes the ${n} record(s) it created, children first:`;return e.removed&&n===0?i=`its records were removed on ${e.removed.removedAt}, and none is left to remove`:n===0&&(e.keptByThePlatform?.length??0)>0?i="it created no record a removal takes":e.removed&&(i=`the removal of ${e.removed.removedAt} left ${n} of the records it created, and a removal deletes those, children first:`),[`${s} wrote to ${t} at ${e.loadedAt}; ${i}`,...e.created.map(m=>` ${m.objectApiName}: ${m.count}`),`${e.linked} record(s) it linked to or reused stay`,...We(e.keptByThePlatform)]}function Fo(e,t){return e.recorded&&(Ge(e)>0||(t?.delete??[]).length>0)}function To(e){return[e.deleted>0?`${e.deleted} deleted`:"",e.alreadyGone>0?`${e.alreadyGone} already gone`:"",e.keptChanged>0?`${e.keptChanged} kept, changed since the load`:"",e.keptDependents>0?`${e.keptDependents} kept for records that stay`+(e.heldBy.length>0?` (${e.heldBy.join(", ")})`:""):"",e.refused>0?`${e.refused} refused`:"",(e.notReached??0)>0?`${e.notReached} not reached`:""].filter(Boolean).join(", ")}function zo(e,t=x){let o=e.count>e.names.length?", \u2026":"";return`${e.count} file(s) attached to them stay in the org, as the ${t.run} did not create them: ${e.names.join(", ")}${o}`}function Yt(e){return`graph: ${e.objects} object(s) at a cap of ${e.maxNodes}`+(e.objects>e.maxNodes?" (raised for the parents their records cannot be written without)":"")+(e.truncated?" \u2014 TRUNCATED: objects further out were not read":"")}function eo(e){return"reusedFrom"in e?`graph reused from ${e.reusedFrom} (discovered ${e.discoveredAt}): the source's schema has not changed since`:`rediscovered: ${e.rediscovered}`}function Co(e){switch(e.phase){case"discovery":return` discovery: ${e.objects??0} object(s) reached`;case"axis":return` listing the values of axis ${e.axis??"?"}\u2026`;case"combination":return` combination ${e.index??"?"}/${e.of??"?"}: ${e.combinationKey??"?"}`;case"candidate":return` candidate ${e.candidate??"?"}/${e.candidates??"?"} of ${e.combinationKey??"?"}: measuring its own records\u2026`;case"measure":return` measuring the ${e.roots??0} root(s) kept, together\u2026`}}function jo(e){let t=e.reason==="timeout"?"its time ran out":"it was cancelled",o=e.during==="axes"?"while it listed the axis values":e.during==="measure"?"while it measured the roots it kept":`while it probed ${e.combinationKey??"?"}`+(e.candidate!==void 0?`, candidate ${e.candidate} of ${e.candidates??"?"}`:"");return[`STOPPED: ${t} ${o}; the combinations decided before are kept`,...e.notProbed.length>0?[` never probed: ${e.notProbed.join(", ")}`]:[]]}var Lo=new Set(["NO_LOAD","ALREADY_REMOVED","NOTHING_TO_REMOVE"]),uo="REMOVAL_DECLINED",to=["MUTE_PRODUCTION","MUTE_NO_RIGHT","MUTE_FAILED"],No=new Map([["frozen:load:error",new Set(["EMAILS_NOT_ACCEPTED","FROZEN_EMAILS_EXCEEDED",ze,"FROZEN_STORAGE_EXCEEDED","AUTOMATION_NOT_ACCEPTED",le.code,...to])],["frozen:remove:error",new Set(["AUTOMATION_NOT_ACCEPTED","GUARD_BLOCKED","GUARD_DECLINED",le.code,...to])]]);function Be(e){let t=e.payload?.code,o=No.get(String(e.type??""));if(!(typeof t!="string"||o?.has(t)!==!0))return{code:t,message:String(e.payload?.message??"")}}function Ue(e){let t=String(e.type??"");if(!t.endsWith(":error")||t==="frozen:remove:automation:error")return!1;let o=String(e.payload?.code);return t==="frozen:remove:error"&&o===uo?!1:!((t==="frozen:remove:error"||t==="frozen:remove:preview:error")&&Lo.has(o))}var oo={passed:0,partial:3,unstable:4,failed:1};function Io(e,t,o){return async(n,s)=>{let i=Date.parse(s?.first??""),m=Math.max(i,Date.parse(s?.last??""));return!Number.isFinite(i)||!Number.isFinite(m)?[]:[...(await Lt({organizationId:n,alias:e,span:{from:i,to:m},own:{ids:[]},...t!==void 0?{journalDir:t}:{}})).map(({ids:d})=>({ids:d,from:i,to:m})),...Gt(Vt(t??te(),n),{sasMark:o,own:[]})]}}function Do(e,t){return dt(t.map(o=>{let n=o.payload??{};if(e==="verify"&&o.type==="frozen:verify:result"){let s=String(n.verdict?.status??"");return Object.prototype.hasOwnProperty.call(oo,s)?oo[s]:1}if(e==="load"&&o.type==="frozen:load:response"){let s=n.report;return s?.status==="completed"&&(s.sweeps??[]).every(i=>i.result.status==="success")?0:3}return e==="remove"&&o.type==="frozen:remove:response"?n.result?.status==="success"?0:3:0}))}function Po(e,t){return` data storage: about ${J(e.estimateMB)} MB`+(e.automationMB!==void 0&&e.automationMB>0?`, about ${J(e.automationMB)} MB of it for what the target's automation creates under them,`:"")+` of the ${J(e.remainingMB)} MB ${t} has left of ${J(e.maxMB)} MB`+(e.freedMB!==void 0?`, and the reload's purge frees about ${J(e.freedMB)} MB first`:"")}function no(e,t){return Ft(e.verdict==="unread"?{verdict:"unread",estimate:e.estimate,unread:e.unread??"not said"}:{verdict:e.verdict,estimate:e.estimate,remaining:e.remaining??0,max:e.max??0},t)}function xo(e){return(e.filter(o=>o.type==="frozen:remove:response").at(-1)?.payload?.result?.objects??[]).some(o=>o.deleted+o.alreadyGone>0)}function ge(e,t){if(gt()!==void 0)return De(e);let o=t.remove.replace(/`/g,"");return e==="--sweep"||e==="--sweep-list"?`${o} ${e}`:`${o} --sweep ${e}`}function Mo(e,t=x){if(!e||e.found.length===0)return[];let o=e.found.reduce((l,p)=>l+p.count,0),n=e.found.some(l=>l.overBound)?" or more":"",s=l=>e.found.reduce((p,g)=>p+(g.classes?l(g.classes):0),0),i=s(l=>l.made+l.madeOver),m=s(l=>l.late),r=s(l=>l.untied),d=e.found.filter(l=>l.overBound).map(l=>l.objectApiName),a=[...i>0?[`${ge("--sweep",t)} takes the ${i} tied to the ${t.run}`]:[],...m>0?[`${ge("--sweep-late",t)} takes the ${m} made late`]:[],...r>0?[e.untied?.refusal!==void 0?`the ${r} tied to nothing of the ${t.run} now stay: --sweep-untied is refused (${e.untied.refusal})`:`${ge("--sweep-untied",t)} takes the ${r} tied to nothing of the ${t.run} now`]:[],...d.length>0?[`no sweep takes those of ${d.join(", ")}, past its bound`]:[]];return[`not swept: ${o}${n} record(s) the ${t.run}'s user created in its window stay, what the target's automation made for the ${t.run} likely: `+e.found.map(l=>`${l.objectApiName}: ${l.count}`).join(", "),...a.map(l=>` ${l}`),` ${ge("--sweep-list",t)} names them first: a record made by hand as that user in the ${t.run}'s window reads as the automation's, so check the names before a sweep`]}function _o(e,t={},o=x){let n=String(e.type??""),s=e.payload??{},i=n.replace(/^frozen:/,`${o.module}:`),m=o===x?"load":"run";if((n==="frozen:remove:error"||n==="frozen:remove:preview:error")&&!Ue(e))return[`nothing to remove: ${String(s.message??"")}`];if(n==="frozen:remove:error"&&!Ue(e))return[String(s.message??"")];if(n==="frozen:remove:automation:error")return[];if(n.endsWith(":error")){let r=n==="frozen:load:error"?s.sweeps??[]:[],d=n==="frozen:load:error"?s.emails:void 0,a=n==="frozen:load:error"?s.automation:void 0,l=n==="frozen:load:error"?s.mutedAutomation:void 0,p=Be(e);return[...p?[]:[`! ${i}: ${String(s.message??"")}${s.code?` [${String(s.code)}]`:""}`],...a?me(a,"the target"):[],...d?he(d,"the target"):[],...l?Z(l,"the target"):[],...r.length>0?[`before the ${o.run} ended, its sweep had already done this:`]:[],...r.flatMap(({loadedAt:g,result:y})=>[`sweep of the ${o.run} of ${g}:`,...ne(y)]),...p?[ee(p)]:[]]}switch(n){case"frozen:select:progress":return[Co(s)];case"frozen:select:response":{let r=s.selection;return[`selected ${r.combinations.length} root(s): ${r.combinations.map(d=>d.combinationKey).join(", ")}`,...r.uncovered.map(d=>` uncovered ${d.combinationKey}: ${d.reason}`),...r.stopped?jo(r.stopped):[],...r.discovery?[eo(r.discovery)]:[],...r.graph?[Yt(r.graph)]:[],`volumetry ${r.volumetry.total} / ${r.volumetry.budgetMax} record(s)`+(r.volumetry.summed?" \u2014 each kept root's own records added up: they were not measured together":""),...Object.entries(r.volumetry.measured).filter(([,d])=>d>0).map(([d,a])=>` ${d}: ${a}`)]}case"frozen:control:result":{let r=s.report;return[`non-reidentification control: ${r.passed?"PASSED":"FAILED"}`,...r.checks.map(d=>` ${d.passed?"ok ":"FAIL"} ${d.name}`+(d.violations.length>0?` (${d.violations.length} violation(s))`:""))]}case"frozen:extract:response":{let r=s.manifest,d=s.discovery;return[`frozen ${String(s.recordCount)} record(s) as version ${r.version} in ${String(s.datasetDir)}`,...d?[eo(d)]:[],...r.coverage?[Yt(r.coverage)]:[],...r.coverage&&r.coverage.unboundedObjects.length>0?[`read without the time bound: ${r.coverage.unboundedObjects.join(", ")}`]:[],...(r.coverage?.leftToThePlatform??[]).map(a=>`${a.objectApiName}: ${a.note}`),...(r.coverage?.exclusionCosts??[]).map(a=>`${a.objectApiName}: ${a.note}`),...(r.coverage?.requiredLeftEmpty??[]).length>0?[`required in the source and left empty by the rules \u2014 a load will ask a value for each: ${(r.coverage?.requiredLeftEmpty??[]).join(", ")}`]:[],...(r.coverage?.keptWithoutARule??[]).length>0?["kept without a rule, the platform's own words: "+(r.coverage?.keptWithoutARule??[]).join(", ")]:[],...(r.coverage?.encryptedNotKept??[]).length>0?["not kept, encrypted and read masked: the user the source is read as lacks View Encrypted Data, and the masks are not copied: "+(r.coverage?.encryptedNotKept??[]).join(", ")]:[],...Object.entries(r.volumetry.measured).filter(([,a])=>a>0).map(([a,l])=>` ${a}: ${l}`)]}case"frozen:load:response":{let r=s.report,d=[`${o.run}: ${r.status} in ${r.durationMs}ms \u2014 ${r.alignment.excludedObjects.length} object(s) excluded, ${r.alignment.removals.length} field removal(s), ${r.alignment.recordTypeIssues.length} record type issue(s), ${r.placeholders.length} placeholder(s)`];for(let f of r.alignment.excludedObjects)d.push(` ${f.objectApiName}: not ${o.done} \u2014 ${f.reason}`);d.push(...Qt(r.alignment.removals,"left",o));for(let f of r.perObject){let S=f.writtenByThePlatform??0;d.push(` ${f.objectApiName}: ${f.inserted} inserted, ${f.reused} reused`+(S>0?` (${S} written by the platform with ${Oe(f.objectApiName)})`:"")+`, ${f.skippedDuplicates.length} duplicate(s), ${f.failed.length} failed of ${f.fromFiles}`);let P=f.failed[0];P&&d.push(` first refusal: ${P.errors?.[0]??P.error??"?"}`)}for(let f of[...r.leftToThePlatform??[],...r.untypedFeedItems??[],...r.heldForExcludedParents??[],...r.quotesLeftUnsynced??[],...r.keysLeftEmpty??[]])d.push(` ${f.objectApiName}: ${f.note}`);let a=r.perObject.filter(f=>(f.writtenWithoutFields?.fields.length??0)>0);if(a.length>0){d.push(`written again without a field a validation rule or a restricted picklist refused (${a.length} object(s)):`);for(let{objectApiName:f,writtenWithoutFields:S}of a)for(let{field:P,refusedBy:q,reason:V,rows:Ve,replacedWith:se}of S?.fields??[]){let Q=q==="restricted-picklist"?"a restricted picklist refused its value":"a validation rule refused it",j=se===void 0?"":` \u2014 written with "${se}", as its picklist rule declares`;d.push(` ${f}.${P} ${Ve} record(s) \u2014 ${Q}${j} \u2014 ${V}`)}}d.push(`pass 2: ${r.pass2.resolved} resolved, ${r.pass2.unresolved.length} unresolved`);for(let f of r.pass2.unresolved.slice(0,5))d.push(` ${f.objectApiName}.${f.field}: ${f.detail}`);let l=r.personContact,p=l?.sent??[];if(l&&l.restored+p.length+l.unresolved.length>0){d.push(`person contacts: ${l.restored} linked, ${p.length} sent as contacts of their own, ${l.unresolved.length} not linked`);for(let f of p.slice(0,5))d.push(` ${f.contactReferenceId} sent: ${f.detail}`);for(let f of l.unresolved.slice(0,5))d.push(` ${f.contactReferenceId}: ${f.detail}`)}if(r.statuses&&r.statuses.restored+r.statuses.refused.length>0){d.push(`statuses applied after insert: ${r.statuses.restored}, refused ${r.statuses.refused.length}`);for(let f of r.statuses.refused.slice(0,5))d.push(` ${f.objectApiName} \u2192 ${f.status}: ${f.detail}`)}let g=f=>Object.values(f).reduce((S,P)=>S+P,0),y=g(r.purge.deleted),z=g(r.purge.deactivated??{});if(y+z+r.purge.failures.length>0){d.push(`purge of earlier ${o.run}s: ${y} deleted, ${z} deactivated, ${r.purge.failures.length} failed`);for(let f of r.purge.failures.slice(0,5))d.push(` ${f.objectApiName}: ${f.errors[0]??"?"}`)}for(let[f,S]of Object.entries(r.purge.cameAlong??{}))d.push(` ${f}: took along ${S.count} record(s) the ${o.run}s did not write that came with their records, made as they wrote: ${S.objects.join(", ")}`);let M=Object.entries(r.purge.leftUnrecorded??{});if(M.length>0){d.push("left in place, of a load recorded before loads kept what they created \u2014 it may have linked them:");for(let[f,S]of M)d.push(` ${f}: ${S}`)}let C=Object.entries(r.purge.keptByThePlatform??{});if(C.length>0){d.push("kept by the purge, the platform does not delete them:");for(let[f,S]of C)d.push(` ${f}: ${S}`)}for(let f of s.report.sweeps??[]){d.push(`sweep of the ${o.run} of ${f.loadedAt}:`,...ne(f.result));let S=f.result.objects.reduce((P,q)=>P+q.keptChanged,0);S>0&&d.push(` ${S} record(s) kept, changed since that ${o.run}: `+(o===x?"load --reload --sweep --include-changed, or remove --sweep --include-changed, ":`${o.remove} --sweep --include-changed `)+"takes them")}let F=s.report.mutedAutomation;F&&d.push(...Z(F,"the target"));let D=s.report.automation;D&&d.push(...me(D,"the target"));let u=s.report.emails;u&&d.push(...he(u,"the target"));let $=s.report.apiRequests;return $&&d.push(no($,"the target")),d.push(...lo(s.report.recordTypesGiven,!1)),d}case"frozen:load:preview:response":{let r=s.plan,d=u=>r.perObject.reduce(($,f)=>$+u(f),0),a=[`dry run${r.mode.pilot?" (pilot)":""}${r.mode.reload?` (${o.again})`:""}: ${d(u=>u.toInsert)} record(s) to insert, ${d(u=>u.reusedByKeys+u.reusedFromCatalog+(u.writtenByThePlatform??0))} to link, ${d(u=>u.notSent)} not sent`+(r.mode.reload?`, ${d(u=>u.toPurge)} to purge and ${d(u=>u.toDeactivate)} to deactivate of ${r.earlierLoads} earlier ${o.run}(s)`:"")+" \u2014 nothing written"];for(let u of r.perObject){let $=[`${u.toInsert} to insert`,u.reusedByKeys>0?`${u.reusedByKeys} found by identity keys`:"",u.reusedFromCatalog>0?`${u.reusedFromCatalog} found in the catalog`:"",(u.writtenByThePlatform??0)>0?`${u.writtenByThePlatform} to link (written by the platform with ${Oe(u.objectApiName)})`:"",u.fieldsDropped>0?`${u.fieldsDropped} field(s) dropped`:"",u.picklistsRewritten>0?`${u.picklistsRewritten} picklist value(s) rewritten`:"",u.notSent>0?`${u.notSent} not sent`:"",u.toPurge>0?`${u.toPurge} to purge`:"",u.toDeactivate>0?`${u.toDeactivate} to deactivate`:""].filter(Boolean);a.push(` ${u.objectApiName}: ${$.join(", ")} of ${u.fromFiles}`)}for(let u of r.excludedObjects)a.push(` ${u.objectApiName}: not ${o.done} \u2014 ${u.reason}`);a.push(...Qt(r.removals,"would leave",o));for(let u of[...r.heldForExcludedParents??[],...r.quotesLeftUnsynced??[],...r.keysLeftEmpty??[]])a.push(` ${u.objectApiName}: ${u.note}`);for(let u of r.placeholders)a.push(`placeholder for ${u.objectApiName}.${u.field}: ${u.affectedRecords} record(s)`);for(let u of r.requiredDefaults)a.push(`default for ${u.objectApiName}.${u.field}: ${u.affectedRecords} record(s)`+(u.perRecord?`, ${Ro(u.perRecord,u.example)}`:""));r.personContacts>0&&a.push(`${r.personContacts} person account contact(s) go in with their account, not counted above`);let l=Object.entries(r.leftUnrecorded??{});if(l.length>0){a.push("left in place, of a load recorded before loads kept what they created \u2014 it may have linked them:");for(let[u,$]of l)a.push(` ${u}: ${$}`)}let p=Object.entries(r.keptByThePlatform??{});if(p.length>0){a.push("left in place by the purge, the platform does not delete them:");for(let[u,$]of p)a.push(` ${u}: ${$}`)}let g=u=>` ${u.name}${u.field?` (${u.field})`:""}${u.message?` \u2014 ${u.message}`:""}`,y=r.perObject.filter(u=>(u.validationRules?.length??0)>0);for(let u of y){a.push(`${u.objectApiName}: ${u.validationRules?.length??0} active validation rule(s) of the target, which a preview cannot evaluate \u2014 a record one of them refuses is counted to insert:`);for(let $ of u.validationRules??[])a.push(g($))}for(let u of r.perObject){let $=u.lookupFilters??[];$.length!==0&&a.push(`${u.objectApiName}: ${$.length} lookup filter(s) of the target, which a preview cannot check \u2014 a record whose lookup it refuses is refused, and what hangs from it: `+$.map(f=>`${f.field} (${f.referenceTo.join(" or ")}, ${f.records} record(s))`).join(", "))}for(let u of r.perObject){let $=u.validationRulesOnChange??[];$.length!==0&&a.push(`${u.objectApiName}: ${$.length} rule(s) left out \u2014 their formula holds only on a change of a record (ISCHANGED, PRIORVALUE, NOT(ISNEW())), which an insert never is: `+$.join(", "))}let z=new Map(r.placeholders.filter(u=>(u.validationRules?.length??0)>0).map(u=>[u.placeholderObjectApiName,u.validationRules??[]]));for(let[u,$]of z){a.push(`placeholder of ${u}: ${$.length} active validation rule(s) of the target, which a preview cannot evaluate \u2014 a placeholder one of them refuses stops the load:`);for(let f of $)a.push(g(f))}r.validationRulesUnread&&a.push(`the target's validation rules could not be listed (${r.validationRulesUnread}): any of them may refuse a record counted to insert`);let M=s.plan.automation;M&&a.push(...me(M,"the target"));let C=s.plan.emails;C&&a.push(...he(C,"the target"));let F=s.plan.apiRequests;F&&a.push(no(F,"the target"));let D=s.plan.storage;return D&&a.push(Po(D,"the target")),a}case"frozen:verify:result":{let r=s.verdict;return[`verification: ${r.status.toUpperCase()}`,...r.checks.map(d=>{let a=Vo(d,o);return` ${d.passed?"ok ":"FAIL"} ${a.name}: ${a.detail}`})]}case"frozen:remove:response":{let r=s.result,d=[...new Set(r.objects.flatMap(l=>l.unchecked))],a=r.sweep!==void 0&&r.objects.length===0;return[...r.sweep?ne(r.sweep):[],...(r.otherLoadSweeps??[]).flatMap(({loadedAt:l,result:p})=>[`sweep of the ${o.run} of ${l}:`,...ne(p)]),...a?[]:[`removal: ${r.status.toUpperCase()}`+(r.leftBy?` \u2014 of what the removal of ${r.leftBy} left`:"")],...r.objects.flatMap(l=>[` ${l.objectApiName}: ${To(l)||"nothing"} of ${l.planned}${Ie(l)}`,...Tt(l,m),...l.reasons.map(p=>` ${p}`),...l.filesLeft&&l.filesLeft.count>0?[` ${zo(l.filesLeft,o)}`]:[]]),...d.length>0?[`not checked, deleted with their parent: ${d.join(", ")}`]:[],...We(r.keptByThePlatform),...zt(r.objects,{sweep:r.sweep!==void 0}),...r.mutedAutomation?Z(r.mutedAutomation,"the target"):[]]}case"frozen:remove:sweep:response":{let r=s.loads;if(r)return r.flatMap(({loadedAt:a,listing:l})=>[`sweep of the ${o.run} of ${a}:`,...fe(l,"the target org",t,!0)]);let d=s.otherLoads??[];return d.length>0?[{loadedAt:String(s.loadedAt),listing:s.listing},...d].flatMap(({loadedAt:a,listing:l})=>[`sweep of the ${o.run} of ${a}:`,...fe(l,"the target org",t,!0)]):fe(s.listing,"the target org",t,!0)}case"frozen:remove:preview:response":return Uo(s.preview,o);case"frozen:status:response":return[JSON.stringify(s.status,null,2)];default:return[]}}var Bo="not read by a preview: what hangs from the records, which a removal reads at each object's turn \u2014 a record kept for records that stay is counted with those to delete \u2014 nor what the target's automation does as they go";function Uo(e,t=x){let o=i=>e.userNames[i]??i,n=["preview: what a removal would do; nothing was deleted"+(e.leftBy?` \u2014 of what the removal of ${e.leftBy} left`:"")];for(let i of e.objects){let m=[i.toDelete>0?`${i.toDelete} to delete`:"",e.includeChanged&&i.changedSince>0?`${i.changedSince} of them changed since the ${t.run}`:"",i.alreadyGone>0?`${i.alreadyGone} gone already`:"",i.notVisible>0?`${i.notVisible} not visible`:"",i.keptChanged>0?`${i.keptChanged} kept, changed since the ${t.run}`:"",i.undeletable>0?`${i.undeletable} left, the user may not delete them`:"",i.unread>0?`${i.unread} left, not read`:""].filter(Boolean);n.push(` ${i.objectApiName}: ${m.join(", ")||"nothing"} of ${i.planned}${Ie(i)}`);let r=Object.entries(i.changedBy).sort((d,a)=>a[1]-d[1]);r.length>0&&n.push(` last changed by: ${r.map(([d,a])=>`${o(d)} ${a}`).join(" \xB7 ")}`);for(let d of i.reasons)n.push(` ${d}`)}n.push(...We(e.keptByThePlatform));let s=e.refusalCodes;return e.refusals.forEach((i,m)=>{n.push(s?.length===e.refusals.length?ue({code:s[m],message:i},"a removal"):`a removal would be refused: ${i}`)}),n.push(Bo),n}async function Wo(e){let t=G(e,"manifest.json");if(_e(t))try{let o=await _t(e),{version:n}=JSON.parse(ve(t,"utf8"));return{dir:e,digest:o,...typeof n=="string"?{version:n}:{}}}catch{return}}function Go(e,t){let o=G(e,xt(t)),n=G(e,"referenceid-mapping.json");return!_e(o)&&_e(n)?n:o}function ro(e){return{status:e.status.toUpperCase(),objects:(e.objects??[]).map(({status:t,...o})=>({...o,verdict:t==="passed"?"PASSED":"FAILED"}))}}async function qo(e,t,o){let n=a=>t.filter(l=>l.type===a).at(-1)?.payload,s=o.targetOrgId?Go(o.sasDir,o.targetOrgId):void 0,i={tool:"sandforge-frozen",step:e,posted:t},m=[],r=[],d=async a=>{if(a===void 0)return;let l=await Wo(a);l&&(i.dataset=l)};switch(e){case"extract":{let a=n("frozen:extract:response");if(!a)break;await d(typeof a.datasetDir=="string"?a.datasetDir:o.datasetDir);let l=a.manifest?.volumetry?.measured??{};i.objects=Object.entries(l).filter(([,p])=>p>0).map(([p,g])=>({objectApiName:p,records:g}));break}case"load":{await d(o.datasetDir);let a=n("frozen:load:response")?.report,l=n("frozen:load:preview:response")?.plan,p=a?a.recordTypesGiven:l?.recordTypesGiven;p&&(i.recordTypesGiven=p),a?(i.mapping=a.mappingPath,i.objects=a.perObject.map(y=>({objectApiName:y.objectApiName,fromFiles:y.fromFiles,inserted:y.inserted,reused:y.reused,duplicates:y.skippedDuplicates.length,failed:y.failed.length}))):l&&(s&&(i.mapping=s),i.objects=l.perObject.map(y=>({objectApiName:y.objectApiName,fromFiles:y.fromFiles,toInsert:y.toInsert,toLink:y.reusedByKeys+y.reusedFromCatalog+(y.writtenByThePlatform??0),notSent:y.notSent,toPurge:y.toPurge,toDeactivate:y.toDeactivate}))),a&&(i.status=a.status),!a&&n("frozen:load:error")?.code==="LOAD_CANCELLED"&&(i.status="cancelled",s&&(i.mapping=s));let g=n("frozen:verify:result")?.verdict;g&&(i.verdict=ro(g));break}case"verify":{let a=n("frozen:verify:result")?.verdict;await d(a?.manifestPath?wo(a.manifestPath):o.datasetDir),s&&(i.mapping=s),a&&(i.verdict=ro(a));break}case"remove":{s&&(i.mapping=s);let a=n("frozen:remove:response")?.result,l=n("frozen:remove:preview:response")?.preview;a?(i.status=a.status,a.mutedAutomation&&(i.mutedAutomation=a.mutedAutomation),i.objects=a.objects.map(p=>({objectApiName:p.objectApiName,planned:p.planned,deleted:p.deleted,alreadyGone:p.alreadyGone,keptChanged:p.keptChanged,keptDependents:p.keptDependents,refused:p.refused,notReached:p.notReached??0,notVisible:p.notVisible??0,...p.tookAlong?{tookAlong:p.tookAlong}:{},...p.cameAlong?{cameAlong:p.cameAlong}:{}})),i.includeChanged=a.includeChanged):l&&(i.preview=!0,i.includeChanged=l.includeChanged,i.objects=l.objects.map(p=>({objectApiName:p.objectApiName,planned:p.planned,toDelete:p.toDelete,alreadyGone:p.alreadyGone,changedSince:p.changedSince,keptChanged:p.keptChanged,undeletable:p.undeletable,notVisible:p.notVisible,unread:p.unread})),m.push(...l.refusals),l.refusalCodes?.length===l.refusals.length&&r.push(...l.refusalCodes));break}}return m.push(...o.refusals??[]),o.refusalCodes?.length===(o.refusals??[]).length&&r.push(...o.refusalCodes??[]),m.length>0&&(i.refusals=m),m.length>0&&r.length===m.length&&(i.refusalCodes=r),o.mute&&Object.assign(i,o.mute),o.checkpoint&&(i.checkpoint=o.checkpoint),i}function Vo(e,t){return t===x?e:{name:e.name==="load"?t.run:e.name,detail:e.detail.replace(/\bThe load\b/g,`The ${t.run}`).replace(/\bthe load\b/g,`the ${t.run}`).replace(/\bnot loaded\b/g,`not ${t.done}`).replace(/\bnot loadable\b/g,`not ${t.run}able`)}}async function Ko(e=process.argv){await Ho($o(e))}async function Ho(e,t){let o=Date.now(),n=c=>{process[e.json?"stderr":"stdout"].write(`${c}
266
+ `),process.exit(2))}return{step:n,configPath:s,source:i,target:m,author:o("--author"),storePath:o("--store"),saltFile:o("--salt-file"),pilot:t.includes("--pilot"),reload:t.includes("--reload"),dryRun:t.includes("--dry-run"),writeEncrypted:t.includes("--write-encrypted"),muteAutomation:t.includes("--mute-automation"),acceptAutomation:t.includes("--accept-automation"),...d!==void 0?{checkpointFirst:d}:{},includeChanged:t.includes("--include-changed"),acceptEmails:t.includes("--accept-emails"),sweep:t.includes("--sweep"),sweepList:t.includes("--sweep-list"),...a,preview:t.includes("--preview"),...l!==void 0?{maxTotal:l}:{},...r!==void 0?{goneFirst:r}:{},yes:t.includes("--yes"),json:t.includes("--json")}}async function ko(e){let o=(await e.query("SELECT Id, IsSandbox FROM Organization LIMIT 1")).records[0];if(!o)throw new Error("The org gave no Organization record.");if(o.IsSandbox)return{id:o.Id,orgType:"Sandbox"};try{let s=(await e.query("SELECT OrganizationType FROM Organization LIMIT 1")).records[0]?.OrganizationType;return typeof s=="string"&&s!==""?{id:o.Id,orgType:et({isSandbox:!1,edition:s}),edition:s}:{id:o.Id,orgType:"Production"}}catch{return{id:o.Id,orgType:"Production"}}}async function Jt(e,t,o,n){let s=await st(e),i=Se(s),m;try{m=await ko(i)}catch(r){let d=r instanceof Error?r.message:String(r);throw new Error(`Could not read the Organization record of '${e}': ${d}`)}return t.set(m.id,{org:{id:m.id,alias:e,orgType:m.orgType,metadata:{apiVersion:"66.0",...m.edition?{edition:m.edition}:{}},username:s.username,instanceUrl:s.instanceUrl},credentials:{accessToken:s.accessToken,instanceUrl:s.instanceUrl}}),o?.set(m.id,i),n?.set(m.id,{session:s,typed:m}),m.id}var x={run:"load",done:"loaded",source:"the frozen dataset",recordedIn:"in this sas",remove:"`remove`",module:"frozen",again:"reload",againSubject:{purge:"reload",sweep:"reloadSweep"},maybeMasks:"the dataset's manifest does not say its extraction left out what it read masked, so they may hold masks such as ****1234; --write-encrypted writes them as the dataset holds them"};function We(e){return!e||e.length===0?[]:[`kept: the platform does not delete them \u2014 ${e.map(({objectApiName:o,count:n})=>`${o} (${n})`).join(", ")}`]}function Qt(e,t,o=x){let n=(e??[]).filter(i=>i.reason==="may-hold-masks");if(n.length===0)return[];let s=n.map(({objectApiName:i,field:m,affectedRecords:r})=>`${i}.${m} (${r})`).join(", ");return[`${t} out, encrypted in the target: ${s} \u2014 ${o.maybeMasks}`]}function Ro(e,t){let o=e==="token"?"each record its own, from the token the value carries":`each record its own, its rank appended: the field is ${e==="unique"?"unique in the target":"the record name"}`;return t===void 0?o:`${o} (first: "${t}")`}function Ge(e){return e.created.reduce((t,o)=>t+o.count,0)}function So(e){return{...e.includeChanged?{includeChanged:!0}:{},...e.sweep?{sweep:!0}:{},...e.sweepLate?{sweepLate:!0}:{},...e.sweepUntied?{sweepUntied:!0}:{},...e.muteAutomation?{muteAutomation:!0}:{}}}var Oo={removal:{heading:"removal",writer:"this removal",verb:"remove"},reload:{heading:"reload",writer:"this reload's purge",verb:"reload"},reloadSweep:{heading:"reload",writer:"this reload's sweep",verb:"reload"},replayAgain:{heading:"replay",writer:"this replay's purge",verb:"replay again"},replayAgainSweep:{heading:"replay",writer:"this replay's sweep",verb:"replay again"}};function xe({read:e,steps:t,mute:o},n,s="removal",i){let m=o?Z(o.muted,n).map(l=>` ${l}`):[];if(!("objects"in e)){let l=Oo[s],p=s==="reload"||s==="replayAgain",g=`${l.writer}${p&&i?" and its sweep":""}`;return{lines:[`${l.heading} automation: what ${n} runs could not be read: ${e.unread}`,...m],refusal:`What ${n} runs as ${g} writes could not be read (${e.unread}), so what fires as the records go is not known. Nothing was written or deleted. Add --accept-automation to ${l.verb} all the same, or turn that automation off in ${n} first.`}}let r=o?.automation??e,d=i?tt(t,i.delete??[]):t,a=mt(r,n,{steps:t,...i?{sweep:i}:{},assign:pt(r,ot(r,d)),mayMute:o===void 0&&Ce("--mute-automation"),subject:s});return{lines:[...ht(e,n,t,s,i),...m],...a!==void 0?{refusal:a}:{}}}function Eo(e,t,o=x){let n=Ge(e),s=e.earlier?`a ${o.run} before the last one, whose records the ${o.run}s after it left in place,`:`the last ${o.run}`,i=`a removal deletes the ${n} record(s) it created, children first:`;return e.removed&&n===0?i=`its records were removed on ${e.removed.removedAt}, and none is left to remove`:n===0&&(e.keptByThePlatform?.length??0)>0?i="it created no record a removal takes":e.removed&&(i=`the removal of ${e.removed.removedAt} left ${n} of the records it created, and a removal deletes those, children first:`),[`${s} wrote to ${t} at ${e.loadedAt}; ${i}`,...e.created.map(m=>` ${m.objectApiName}: ${m.count}`),`${e.linked} record(s) it linked to or reused stay`,...We(e.keptByThePlatform)]}function Fo(e,t){return e.recorded&&(Ge(e)>0||(t?.delete??[]).length>0)}function To(e){return[e.deleted>0?`${e.deleted} deleted`:"",e.alreadyGone>0?`${e.alreadyGone} already gone`:"",e.keptChanged>0?`${e.keptChanged} kept, changed since the load`:"",e.keptDependents>0?`${e.keptDependents} kept for records that stay`+(e.heldBy.length>0?` (${e.heldBy.join(", ")})`:""):"",e.refused>0?`${e.refused} refused`:"",(e.notReached??0)>0?`${e.notReached} not reached`:""].filter(Boolean).join(", ")}function zo(e,t=x){let o=e.count>e.names.length?", \u2026":"";return`${e.count} file(s) attached to them stay in the org, as the ${t.run} did not create them: ${e.names.join(", ")}${o}`}function Yt(e){return`graph: ${e.objects} object(s) at a cap of ${e.maxNodes}`+(e.objects>e.maxNodes?" (raised for the parents their records cannot be written without)":"")+(e.truncated?" \u2014 TRUNCATED: objects further out were not read":"")}function eo(e){return"reusedFrom"in e?`graph reused from ${e.reusedFrom} (discovered ${e.discoveredAt}): the source's schema has not changed since`:`rediscovered: ${e.rediscovered}`}function Co(e){switch(e.phase){case"discovery":return` discovery: ${e.objects??0} object(s) reached`;case"axis":return` listing the values of axis ${e.axis??"?"}\u2026`;case"combination":return` combination ${e.index??"?"}/${e.of??"?"}: ${e.combinationKey??"?"}`;case"candidate":return` candidate ${e.candidate??"?"}/${e.candidates??"?"} of ${e.combinationKey??"?"}: measuring its own records\u2026`;case"measure":return` measuring the ${e.roots??0} root(s) kept, together\u2026`}}function jo(e){let t=e.reason==="timeout"?"its time ran out":"it was cancelled",o=e.during==="axes"?"while it listed the axis values":e.during==="measure"?"while it measured the roots it kept":`while it probed ${e.combinationKey??"?"}`+(e.candidate!==void 0?`, candidate ${e.candidate} of ${e.candidates??"?"}`:"");return[`STOPPED: ${t} ${o}; the combinations decided before are kept`,...e.notProbed.length>0?[` never probed: ${e.notProbed.join(", ")}`]:[]]}var Lo=new Set(["NO_LOAD","ALREADY_REMOVED","NOTHING_TO_REMOVE"]),uo="REMOVAL_DECLINED",to=["MUTE_PRODUCTION","MUTE_NO_RIGHT","MUTE_FAILED"],No=new Map([["frozen:load:error",new Set(["EMAILS_NOT_ACCEPTED","FROZEN_EMAILS_EXCEEDED",ze,"FROZEN_STORAGE_EXCEEDED","AUTOMATION_NOT_ACCEPTED",le.code,...to])],["frozen:remove:error",new Set(["AUTOMATION_NOT_ACCEPTED","GUARD_BLOCKED","GUARD_DECLINED",le.code,...to])]]);function Be(e){let t=e.payload?.code,o=No.get(String(e.type??""));if(!(typeof t!="string"||o?.has(t)!==!0))return{code:t,message:String(e.payload?.message??"")}}function Ue(e){let t=String(e.type??"");if(!t.endsWith(":error")||t==="frozen:remove:automation:error")return!1;let o=String(e.payload?.code);return t==="frozen:remove:error"&&o===uo?!1:!((t==="frozen:remove:error"||t==="frozen:remove:preview:error")&&Lo.has(o))}var oo={passed:0,partial:3,unstable:4,failed:1};function Io(e,t,o){return async(n,s)=>{let i=Date.parse(s?.first??""),m=Math.max(i,Date.parse(s?.last??""));return!Number.isFinite(i)||!Number.isFinite(m)?[]:[...(await Lt({organizationId:n,alias:e,span:{from:i,to:m},own:{ids:[]},...t!==void 0?{journalDir:t}:{}})).map(({ids:d})=>({ids:d,from:i,to:m})),...Gt(Vt(t??te(),n),{sasMark:o,own:[]})]}}function Do(e,t){return dt(t.map(o=>{let n=o.payload??{};if(e==="verify"&&o.type==="frozen:verify:result"){let s=String(n.verdict?.status??"");return Object.prototype.hasOwnProperty.call(oo,s)?oo[s]:1}if(e==="load"&&o.type==="frozen:load:response"){let s=n.report,i=n.replay?.summary.records.refusedBeforeWrite;return s?.status==="completed"&&(s.sweeps??[]).every(m=>m.result.status==="success")&&(i??0)===0?0:3}return e==="remove"&&o.type==="frozen:remove:response"?n.result?.status==="success"?0:3:0}))}function Po(e,t){return` data storage: about ${J(e.estimateMB)} MB`+(e.automationMB!==void 0&&e.automationMB>0?`, about ${J(e.automationMB)} MB of it for what the target's automation creates under them,`:"")+` of the ${J(e.remainingMB)} MB ${t} has left of ${J(e.maxMB)} MB`+(e.freedMB!==void 0?`, and the reload's purge frees about ${J(e.freedMB)} MB first`:"")}function no(e,t){return Ft(e.verdict==="unread"?{verdict:"unread",estimate:e.estimate,unread:e.unread??"not said"}:{verdict:e.verdict,estimate:e.estimate,remaining:e.remaining??0,max:e.max??0},t)}function xo(e){return(e.filter(o=>o.type==="frozen:remove:response").at(-1)?.payload?.result?.objects??[]).some(o=>o.deleted+o.alreadyGone>0)}function ge(e,t){if(gt()!==void 0)return De(e);let o=t.remove.replace(/`/g,"");return e==="--sweep"||e==="--sweep-list"?`${o} ${e}`:`${o} --sweep ${e}`}function Mo(e,t=x){if(!e||e.found.length===0)return[];let o=e.found.reduce((l,p)=>l+p.count,0),n=e.found.some(l=>l.overBound)?" or more":"",s=l=>e.found.reduce((p,g)=>p+(g.classes?l(g.classes):0),0),i=s(l=>l.made+l.madeOver),m=s(l=>l.late),r=s(l=>l.untied),d=e.found.filter(l=>l.overBound).map(l=>l.objectApiName),a=[...i>0?[`${ge("--sweep",t)} takes the ${i} tied to the ${t.run}`]:[],...m>0?[`${ge("--sweep-late",t)} takes the ${m} made late`]:[],...r>0?[e.untied?.refusal!==void 0?`the ${r} tied to nothing of the ${t.run} now stay: --sweep-untied is refused (${e.untied.refusal})`:`${ge("--sweep-untied",t)} takes the ${r} tied to nothing of the ${t.run} now`]:[],...d.length>0?[`no sweep takes those of ${d.join(", ")}, past its bound`]:[]];return[`not swept: ${o}${n} record(s) the ${t.run}'s user created in its window stay, what the target's automation made for the ${t.run} likely: `+e.found.map(l=>`${l.objectApiName}: ${l.count}`).join(", "),...a.map(l=>` ${l}`),` ${ge("--sweep-list",t)} names them first: a record made by hand as that user in the ${t.run}'s window reads as the automation's, so check the names before a sweep`]}function _o(e,t={},o=x){let n=String(e.type??""),s=e.payload??{},i=n.replace(/^frozen:/,`${o.module}:`),m=o===x?"load":"run";if((n==="frozen:remove:error"||n==="frozen:remove:preview:error")&&!Ue(e))return[`nothing to remove: ${String(s.message??"")}`];if(n==="frozen:remove:error"&&!Ue(e))return[String(s.message??"")];if(n==="frozen:remove:automation:error")return[];if(n.endsWith(":error")){let r=n==="frozen:load:error"?s.sweeps??[]:[],d=n==="frozen:load:error"?s.emails:void 0,a=n==="frozen:load:error"?s.automation:void 0,l=n==="frozen:load:error"?s.mutedAutomation:void 0,p=Be(e);return[...p?[]:[`! ${i}: ${String(s.message??"")}${s.code?` [${String(s.code)}]`:""}`],...a?me(a,"the target"):[],...d?he(d,"the target"):[],...l?Z(l,"the target"):[],...r.length>0?[`before the ${o.run} ended, its sweep had already done this:`]:[],...r.flatMap(({loadedAt:g,result:y})=>[`sweep of the ${o.run} of ${g}:`,...ne(y)]),...p?[ee(p)]:[]]}switch(n){case"frozen:select:progress":return[Co(s)];case"frozen:select:response":{let r=s.selection;return[`selected ${r.combinations.length} root(s): ${r.combinations.map(d=>d.combinationKey).join(", ")}`,...r.uncovered.map(d=>` uncovered ${d.combinationKey}: ${d.reason}`),...r.stopped?jo(r.stopped):[],...r.discovery?[eo(r.discovery)]:[],...r.graph?[Yt(r.graph)]:[],`volumetry ${r.volumetry.total} / ${r.volumetry.budgetMax} record(s)`+(r.volumetry.summed?" \u2014 each kept root's own records added up: they were not measured together":""),...Object.entries(r.volumetry.measured).filter(([,d])=>d>0).map(([d,a])=>` ${d}: ${a}`)]}case"frozen:control:result":{let r=s.report;return[`non-reidentification control: ${r.passed?"PASSED":"FAILED"}`,...r.checks.map(d=>` ${d.passed?"ok ":"FAIL"} ${d.name}`+(d.violations.length>0?` (${d.violations.length} violation(s))`:""))]}case"frozen:extract:response":{let r=s.manifest,d=s.discovery;return[`frozen ${String(s.recordCount)} record(s) as version ${r.version} in ${String(s.datasetDir)}`,...d?[eo(d)]:[],...r.coverage?[Yt(r.coverage)]:[],...r.coverage&&r.coverage.unboundedObjects.length>0?[`read without the time bound: ${r.coverage.unboundedObjects.join(", ")}`]:[],...(r.coverage?.leftToThePlatform??[]).map(a=>`${a.objectApiName}: ${a.note}`),...(r.coverage?.exclusionCosts??[]).map(a=>`${a.objectApiName}: ${a.note}`),...(r.coverage?.requiredLeftEmpty??[]).length>0?[`required in the source and left empty by the rules \u2014 a load will ask a value for each: ${(r.coverage?.requiredLeftEmpty??[]).join(", ")}`]:[],...(r.coverage?.keptWithoutARule??[]).length>0?["kept without a rule, the platform's own words: "+(r.coverage?.keptWithoutARule??[]).join(", ")]:[],...(r.coverage?.encryptedNotKept??[]).length>0?["not kept, encrypted and read masked: the user the source is read as lacks View Encrypted Data, and the masks are not copied: "+(r.coverage?.encryptedNotKept??[]).join(", ")]:[],...Object.entries(r.volumetry.measured).filter(([,a])=>a>0).map(([a,l])=>` ${a}: ${l}`)]}case"frozen:load:response":{let r=s.report,d=[`${o.run}: ${r.status} in ${r.durationMs}ms \u2014 ${r.alignment.excludedObjects.length} object(s) excluded, ${r.alignment.removals.length} field removal(s), ${r.alignment.recordTypeIssues.length} record type issue(s), ${r.placeholders.length} placeholder(s)`];for(let f of r.alignment.excludedObjects)d.push(` ${f.objectApiName}: not ${o.done} \u2014 ${f.reason}`);d.push(...Qt(r.alignment.removals,"left",o));for(let f of r.perObject){let S=f.writtenByThePlatform??0;d.push(` ${f.objectApiName}: ${f.inserted} inserted, ${f.reused} reused`+(S>0?` (${S} written by the platform with ${Oe(f.objectApiName)})`:"")+`, ${f.skippedDuplicates.length} duplicate(s), ${f.failed.length} failed of ${f.fromFiles}`);let P=f.failed[0];P&&d.push(` first refusal: ${P.errors?.[0]??P.error??"?"}`)}for(let f of[...r.leftToThePlatform??[],...r.untypedFeedItems??[],...r.heldForExcludedParents??[],...r.quotesLeftUnsynced??[],...r.keysLeftEmpty??[]])d.push(` ${f.objectApiName}: ${f.note}`);let a=r.perObject.filter(f=>(f.writtenWithoutFields?.fields.length??0)>0);if(a.length>0){d.push(`written again without a field a validation rule or a restricted picklist refused (${a.length} object(s)):`);for(let{objectApiName:f,writtenWithoutFields:S}of a)for(let{field:P,refusedBy:q,reason:V,rows:Ve,replacedWith:se}of S?.fields??[]){let Q=q==="restricted-picklist"?"a restricted picklist refused its value":"a validation rule refused it",j=se===void 0?"":` \u2014 written with "${se}", as its picklist rule declares`;d.push(` ${f}.${P} ${Ve} record(s) \u2014 ${Q}${j} \u2014 ${V}`)}}d.push(`pass 2: ${r.pass2.resolved} resolved, ${r.pass2.unresolved.length} unresolved`);for(let f of r.pass2.unresolved.slice(0,5))d.push(` ${f.objectApiName}.${f.field}: ${f.detail}`);let l=r.personContact,p=l?.sent??[];if(l&&l.restored+p.length+l.unresolved.length>0){d.push(`person contacts: ${l.restored} linked, ${p.length} sent as contacts of their own, ${l.unresolved.length} not linked`);for(let f of p.slice(0,5))d.push(` ${f.contactReferenceId} sent: ${f.detail}`);for(let f of l.unresolved.slice(0,5))d.push(` ${f.contactReferenceId}: ${f.detail}`)}if(r.statuses&&r.statuses.restored+r.statuses.refused.length>0){d.push(`statuses applied after insert: ${r.statuses.restored}, refused ${r.statuses.refused.length}`);for(let f of r.statuses.refused.slice(0,5))d.push(` ${f.objectApiName} \u2192 ${f.status}: ${f.detail}`)}let g=f=>Object.values(f).reduce((S,P)=>S+P,0),y=g(r.purge.deleted),z=g(r.purge.deactivated??{});if(y+z+r.purge.failures.length>0){d.push(`purge of earlier ${o.run}s: ${y} deleted, ${z} deactivated, ${r.purge.failures.length} failed`);for(let f of r.purge.failures.slice(0,5))d.push(` ${f.objectApiName}: ${f.errors[0]??"?"}`)}for(let[f,S]of Object.entries(r.purge.cameAlong??{}))d.push(` ${f}: took along ${S.count} record(s) the ${o.run}s did not write that came with their records, made as they wrote: ${S.objects.join(", ")}`);let M=Object.entries(r.purge.leftUnrecorded??{});if(M.length>0){d.push("left in place, of a load recorded before loads kept what they created \u2014 it may have linked them:");for(let[f,S]of M)d.push(` ${f}: ${S}`)}let C=Object.entries(r.purge.keptByThePlatform??{});if(C.length>0){d.push("kept by the purge, the platform does not delete them:");for(let[f,S]of C)d.push(` ${f}: ${S}`)}for(let f of s.report.sweeps??[]){d.push(`sweep of the ${o.run} of ${f.loadedAt}:`,...ne(f.result));let S=f.result.objects.reduce((P,q)=>P+q.keptChanged,0);S>0&&d.push(` ${S} record(s) kept, changed since that ${o.run}: `+(o===x?"load --reload --sweep --include-changed, or remove --sweep --include-changed, ":`${o.remove} --sweep --include-changed `)+"takes them")}let F=s.report.mutedAutomation;F&&d.push(...Z(F,"the target"));let D=s.report.automation;D&&d.push(...me(D,"the target"));let u=s.report.emails;u&&d.push(...he(u,"the target"));let $=s.report.apiRequests;return $&&d.push(no($,"the target")),d.push(...lo(s.report.recordTypesGiven,!1)),d}case"frozen:load:preview:response":{let r=s.plan,d=u=>r.perObject.reduce(($,f)=>$+u(f),0),a=[`dry run${r.mode.pilot?" (pilot)":""}${r.mode.reload?` (${o.again})`:""}: ${d(u=>u.toInsert)} record(s) to insert, ${d(u=>u.reusedByKeys+u.reusedFromCatalog+(u.writtenByThePlatform??0))} to link, ${d(u=>u.notSent)} not sent`+(r.mode.reload?`, ${d(u=>u.toPurge)} to purge and ${d(u=>u.toDeactivate)} to deactivate of ${r.earlierLoads} earlier ${o.run}(s)`:"")+" \u2014 nothing written"];for(let u of r.perObject){let $=[`${u.toInsert} to insert`,u.reusedByKeys>0?`${u.reusedByKeys} found by identity keys`:"",u.reusedFromCatalog>0?`${u.reusedFromCatalog} found in the catalog`:"",(u.writtenByThePlatform??0)>0?`${u.writtenByThePlatform} to link (written by the platform with ${Oe(u.objectApiName)})`:"",u.fieldsDropped>0?`${u.fieldsDropped} field(s) dropped`:"",u.picklistsRewritten>0?`${u.picklistsRewritten} picklist value(s) rewritten`:"",u.notSent>0?`${u.notSent} not sent`:"",u.toPurge>0?`${u.toPurge} to purge`:"",u.toDeactivate>0?`${u.toDeactivate} to deactivate`:""].filter(Boolean);a.push(` ${u.objectApiName}: ${$.join(", ")} of ${u.fromFiles}`)}for(let u of r.excludedObjects)a.push(` ${u.objectApiName}: not ${o.done} \u2014 ${u.reason}`);a.push(...Qt(r.removals,"would leave",o));for(let u of[...r.heldForExcludedParents??[],...r.quotesLeftUnsynced??[],...r.keysLeftEmpty??[]])a.push(` ${u.objectApiName}: ${u.note}`);for(let u of r.placeholders)a.push(`placeholder for ${u.objectApiName}.${u.field}: ${u.affectedRecords} record(s)`);for(let u of r.requiredDefaults)a.push(`default for ${u.objectApiName}.${u.field}: ${u.affectedRecords} record(s)`+(u.perRecord?`, ${Ro(u.perRecord,u.example)}`:""));r.personContacts>0&&a.push(`${r.personContacts} person account contact(s) go in with their account, not counted above`);let l=Object.entries(r.leftUnrecorded??{});if(l.length>0){a.push("left in place, of a load recorded before loads kept what they created \u2014 it may have linked them:");for(let[u,$]of l)a.push(` ${u}: ${$}`)}let p=Object.entries(r.keptByThePlatform??{});if(p.length>0){a.push("left in place by the purge, the platform does not delete them:");for(let[u,$]of p)a.push(` ${u}: ${$}`)}let g=u=>` ${u.name}${u.field?` (${u.field})`:""}${u.message?` \u2014 ${u.message}`:""}`,y=r.perObject.filter(u=>(u.validationRules?.length??0)>0);for(let u of y){a.push(`${u.objectApiName}: ${u.validationRules?.length??0} active validation rule(s) of the target, which a preview cannot evaluate \u2014 a record one of them refuses is counted to insert:`);for(let $ of u.validationRules??[])a.push(g($))}for(let u of r.perObject){let $=u.lookupFilters??[];$.length!==0&&a.push(`${u.objectApiName}: ${$.length} lookup filter(s) of the target, which a preview cannot check \u2014 a record whose lookup it refuses is refused, and what hangs from it: `+$.map(f=>`${f.field} (${f.referenceTo.join(" or ")}, ${f.records} record(s))`).join(", "))}for(let u of r.perObject){let $=u.validationRulesOnChange??[];$.length!==0&&a.push(`${u.objectApiName}: ${$.length} rule(s) left out \u2014 their formula holds only on a change of a record (ISCHANGED, PRIORVALUE, NOT(ISNEW())), which an insert never is: `+$.join(", "))}let z=new Map(r.placeholders.filter(u=>(u.validationRules?.length??0)>0).map(u=>[u.placeholderObjectApiName,u.validationRules??[]]));for(let[u,$]of z){a.push(`placeholder of ${u}: ${$.length} active validation rule(s) of the target, which a preview cannot evaluate \u2014 a placeholder one of them refuses stops the load:`);for(let f of $)a.push(g(f))}r.validationRulesUnread&&a.push(`the target's validation rules could not be listed (${r.validationRulesUnread}): any of them may refuse a record counted to insert`);let M=s.plan.automation;M&&a.push(...me(M,"the target"));let C=s.plan.emails;C&&a.push(...he(C,"the target"));let F=s.plan.apiRequests;F&&a.push(no(F,"the target"));let D=s.plan.storage;return D&&a.push(Po(D,"the target")),a}case"frozen:verify:result":{let r=s.verdict;return[`verification: ${r.status.toUpperCase()}`,...r.checks.map(d=>{let a=Vo(d,o);return` ${d.passed?"ok ":"FAIL"} ${a.name}: ${a.detail}`})]}case"frozen:remove:response":{let r=s.result,d=[...new Set(r.objects.flatMap(l=>l.unchecked))],a=r.sweep!==void 0&&r.objects.length===0;return[...r.sweep?ne(r.sweep):[],...(r.otherLoadSweeps??[]).flatMap(({loadedAt:l,result:p})=>[`sweep of the ${o.run} of ${l}:`,...ne(p)]),...a?[]:[`removal: ${r.status.toUpperCase()}`+(r.leftBy?` \u2014 of what the removal of ${r.leftBy} left`:"")],...r.objects.flatMap(l=>[` ${l.objectApiName}: ${To(l)||"nothing"} of ${l.planned}${Ie(l)}`,...Tt(l,m),...l.reasons.map(p=>` ${p}`),...l.filesLeft&&l.filesLeft.count>0?[` ${zo(l.filesLeft,o)}`]:[]]),...d.length>0?[`not checked, deleted with their parent: ${d.join(", ")}`]:[],...We(r.keptByThePlatform),...zt(r.objects,{sweep:r.sweep!==void 0}),...r.mutedAutomation?Z(r.mutedAutomation,"the target"):[]]}case"frozen:remove:sweep:response":{let r=s.loads;if(r)return r.flatMap(({loadedAt:a,listing:l})=>[`sweep of the ${o.run} of ${a}:`,...fe(l,"the target org",t,!0)]);let d=s.otherLoads??[];return d.length>0?[{loadedAt:String(s.loadedAt),listing:s.listing},...d].flatMap(({loadedAt:a,listing:l})=>[`sweep of the ${o.run} of ${a}:`,...fe(l,"the target org",t,!0)]):fe(s.listing,"the target org",t,!0)}case"frozen:remove:preview:response":return Uo(s.preview,o);case"frozen:status:response":return[JSON.stringify(s.status,null,2)];default:return[]}}var Bo="not read by a preview: what hangs from the records, which a removal reads at each object's turn \u2014 a record kept for records that stay is counted with those to delete \u2014 nor what the target's automation does as they go";function Uo(e,t=x){let o=i=>e.userNames[i]??i,n=["preview: what a removal would do; nothing was deleted"+(e.leftBy?` \u2014 of what the removal of ${e.leftBy} left`:"")];for(let i of e.objects){let m=[i.toDelete>0?`${i.toDelete} to delete`:"",e.includeChanged&&i.changedSince>0?`${i.changedSince} of them changed since the ${t.run}`:"",i.alreadyGone>0?`${i.alreadyGone} gone already`:"",i.notVisible>0?`${i.notVisible} not visible`:"",i.keptChanged>0?`${i.keptChanged} kept, changed since the ${t.run}`:"",i.undeletable>0?`${i.undeletable} left, the user may not delete them`:"",i.unread>0?`${i.unread} left, not read`:""].filter(Boolean);n.push(` ${i.objectApiName}: ${m.join(", ")||"nothing"} of ${i.planned}${Ie(i)}`);let r=Object.entries(i.changedBy).sort((d,a)=>a[1]-d[1]);r.length>0&&n.push(` last changed by: ${r.map(([d,a])=>`${o(d)} ${a}`).join(" \xB7 ")}`);for(let d of i.reasons)n.push(` ${d}`)}n.push(...We(e.keptByThePlatform));let s=e.refusalCodes;return e.refusals.forEach((i,m)=>{n.push(s?.length===e.refusals.length?ue({code:s[m],message:i},"a removal"):`a removal would be refused: ${i}`)}),n.push(Bo),n}async function Wo(e){let t=G(e,"manifest.json");if(_e(t))try{let o=await _t(e),{version:n}=JSON.parse(ve(t,"utf8"));return{dir:e,digest:o,...typeof n=="string"?{version:n}:{}}}catch{return}}function Go(e,t){let o=G(e,xt(t)),n=G(e,"referenceid-mapping.json");return!_e(o)&&_e(n)?n:o}function ro(e){return{status:e.status.toUpperCase(),objects:(e.objects??[]).map(({status:t,...o})=>({...o,verdict:t==="passed"?"PASSED":"FAILED"}))}}async function qo(e,t,o){let n=a=>t.filter(l=>l.type===a).at(-1)?.payload,s=o.targetOrgId?Go(o.sasDir,o.targetOrgId):void 0,i={tool:"sandforge-frozen",step:e,posted:t},m=[],r=[],d=async a=>{if(a===void 0)return;let l=await Wo(a);l&&(i.dataset=l)};switch(e){case"extract":{let a=n("frozen:extract:response");if(!a)break;await d(typeof a.datasetDir=="string"?a.datasetDir:o.datasetDir);let l=a.manifest?.volumetry?.measured??{};i.objects=Object.entries(l).filter(([,p])=>p>0).map(([p,g])=>({objectApiName:p,records:g}));break}case"load":{await d(o.datasetDir);let a=n("frozen:load:response")?.report,l=n("frozen:load:preview:response")?.plan,p=a?a.recordTypesGiven:l?.recordTypesGiven;p&&(i.recordTypesGiven=p),a?(i.mapping=a.mappingPath,i.objects=a.perObject.map(y=>({objectApiName:y.objectApiName,fromFiles:y.fromFiles,inserted:y.inserted,reused:y.reused,duplicates:y.skippedDuplicates.length,failed:y.failed.length}))):l&&(s&&(i.mapping=s),i.objects=l.perObject.map(y=>({objectApiName:y.objectApiName,fromFiles:y.fromFiles,toInsert:y.toInsert,toLink:y.reusedByKeys+y.reusedFromCatalog+(y.writtenByThePlatform??0),notSent:y.notSent,toPurge:y.toPurge,toDeactivate:y.toDeactivate}))),a&&(i.status=a.status),!a&&n("frozen:load:error")?.code==="LOAD_CANCELLED"&&(i.status="cancelled",s&&(i.mapping=s));let g=n("frozen:verify:result")?.verdict;g&&(i.verdict=ro(g));break}case"verify":{let a=n("frozen:verify:result")?.verdict;await d(a?.manifestPath?wo(a.manifestPath):o.datasetDir),s&&(i.mapping=s),a&&(i.verdict=ro(a));break}case"remove":{s&&(i.mapping=s);let a=n("frozen:remove:response")?.result,l=n("frozen:remove:preview:response")?.preview;a?(i.status=a.status,a.mutedAutomation&&(i.mutedAutomation=a.mutedAutomation),i.objects=a.objects.map(p=>({objectApiName:p.objectApiName,planned:p.planned,deleted:p.deleted,alreadyGone:p.alreadyGone,keptChanged:p.keptChanged,keptDependents:p.keptDependents,refused:p.refused,notReached:p.notReached??0,notVisible:p.notVisible??0,...p.tookAlong?{tookAlong:p.tookAlong}:{},...p.cameAlong?{cameAlong:p.cameAlong}:{}})),i.includeChanged=a.includeChanged):l&&(i.preview=!0,i.includeChanged=l.includeChanged,i.objects=l.objects.map(p=>({objectApiName:p.objectApiName,planned:p.planned,toDelete:p.toDelete,alreadyGone:p.alreadyGone,changedSince:p.changedSince,keptChanged:p.keptChanged,undeletable:p.undeletable,notVisible:p.notVisible,unread:p.unread})),m.push(...l.refusals),l.refusalCodes?.length===l.refusals.length&&r.push(...l.refusalCodes));break}}return m.push(...o.refusals??[]),o.refusalCodes?.length===(o.refusals??[]).length&&r.push(...o.refusalCodes??[]),m.length>0&&(i.refusals=m),m.length>0&&r.length===m.length&&(i.refusalCodes=r),o.mute&&Object.assign(i,o.mute),o.checkpoint&&(i.checkpoint=o.checkpoint),i}function Vo(e,t){return t===x?e:{name:e.name==="load"?t.run:e.name,detail:e.detail.replace(/\bThe load\b/g,`The ${t.run}`).replace(/\bthe load\b/g,`the ${t.run}`).replace(/\bnot loaded\b/g,`not ${t.done}`).replace(/\bnot loadable\b/g,`not ${t.run}able`)}}async function Ko(e=process.argv){await Ho($o(e))}async function Ho(e,t){let o=Date.now(),n=c=>{process[e.json?"stderr":"stdout"].write(`${c}
267
267
  `)},s=t?.words??x,i=t?{}:JSON.parse(ve(e.configPath??"","utf8")),m=t?t.folder.dir:typeof i.sasDir=="string"?i.sasDir:G(yo(),".sandforge-sas");t||mo(m,{recursive:!0});let r=wt(t?t.auditStore:e.storePath??G(m,"cli-store.json")),d=new Map,a=new Map,l=new Map,p=e.source?await Jt(e.source,d):void 0,g=e.target?await Jt(e.target,d,a,l):void 0,y=[],z=!1,M=!1,C=new Kt({log:()=>{},broker:{postToWebview:c=>{if(c.type==="frozen:load:progress")return;if(t&&String(c.type).endsWith(":error")&&c.payload){let w=c.payload.code;c.payload.message=t.reword(typeof w=="string"?w:void 0,String(c.payload.message??""),c.payload)}y.push(c),Ue(c)&&(z=!0);let h=t?.refusalOf(c);if(h&&(E??=h,j.push(h)),M)return;let v=h?[ee(h)]:_o(c,e,s);for(let w of t?t.lines(c,v):v)n(w)}},orgManager:{getOrg:c=>d.get(c)?.org},orgRegistry:{getCredentials:async c=>d.get(c)?.credentials},configStore:r,infraServices:{productionGuard:It(n,e.target??e.source??"the org"),piiDetector:new ut},nextId:()=>`cli-${Date.now()}-${Math.random().toString(36).slice(2,8)}`});t&&C.setReplayStores(t.stores);let F=g?a.get(g):void 0,D=g?l.get(g):void 0,u=e.checkpointFirst&&D?$t({module:t?"replay":"frozen",operationId:`sandforge-frozen-load-${o}`,request:e.checkpointFirst,session:D.session,org:{id:D.typed.id,orgType:D.typed.orgType,...D.typed.edition!==void 0?{edition:D.typed.edition}:{}},connect:Se,journalDir:te(),say:n}):void 0;F&&C.setTargetAutomation(oe(F)),C.setMuteOffered(Ce("--mute-automation")),C.setSaltKeeper(Ut(process.env,e.saltFile)),e.target&&C.setOtherModuleRuns(Io(e.target,void 0,Pe(m)));let $=new Ht;C.setRegistry($);let f,S,P=!1,q=!1,V,se=at(c=>{if(V=c,process.stderr.write(`
268
268
  interrupted: the ${e.step==="load"?s.run:e.step} stops after the call under way, and says what it wrote (Ctrl-C again ends it at once)
269
269
  `),S){S.abort();return}for(let h of $.getRunning())$.abort(h.operationId);f&&$.cancelBeforeStart(f),(!f||q)&&process.exit(de(c))}),Q=t?void 0:typeof i.datasetDir=="string"?i.datasetDir:G(m,"dataset"),j=[],U=c=>{let h=t?{code:c.code,message:t.reword(c.code,c.message)}:c;j.push(h),n(ue(h,`a ${s.run}`))},B=c=>{if(!t)return{};let{organizationId:h,checkpointId:v,config:w}=t.request;return c==="load"?{replay:t.request}:c==="verify"?{replay:{organizationId:h,checkpointId:v,...w?{config:w}:{}}}:{replay:{organizationId:h,checkpointId:v}}},be=[],E,Ke=!1,K,H,X,Ae=async(c,h=Number(process.exitCode??0))=>{if(!e.json)return;let v=[...j,...be],w=await qo(e.step,y,{...Q!==void 0?{datasetDir:Q}:{},sasDir:m,...g?{targetOrgId:g}:{},...v.length>0?{refusals:v.map(({message:A})=>A),refusalCodes:v.map(({code:A})=>A)}:{},...K?{mute:K}:{},...H?{checkpoint:H}:{}}),b=t?{...t.answer(w,{exit:h,...c?{ended:c}:{},...E?{refused:E}:{},...g?{targetOrgId:g}:{}}),...X?{notSwept:X}:{}}:{...w,...X?{notSwept:X}:{},...E?{refused:E}:{},...c?{ended:c}:{}};process.stdout.write(`${JSON.stringify(b,null,2)}
@@ -0,0 +1,7 @@
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{Hb as h,Kb as D,Lb as R,dd as O}from"./chunk-6QSHWIZI.mjs";function P(t,f){return t.previousOrganizationId??(t.organizationId===void 0?f?.(t.orgId):void 0)??t.detectedAt}function x(t){let f=(i,s)=>{let o=R.safeParse(t.configStore.get(D(i,P(s,t.organizationIdOf))));return o.success&&o.data.finishedAt!==void 0};return{progressOf(i){let s=t.orgOf(i);if(s?.orgType!=="Sandbox")return;let[o]=t.refreshesOf(i);if(!(o===void 0||f(i,o)))return{orgId:i,alias:O(s,s.username),detectedAt:o.detectedAt,done:0,total:h}}}}var b=3e4;function A(t){let f=x(t),i=t.ttlMs??b,s=t.now??(()=>Date.now()),o=new Map,g=new Map,a=new Map,u=new Set,l=new Set,p=()=>{for(let e of[...l])try{e()}catch(r){t.log?.(`[recovery] a listener of the progress failed: ${String(r)}`)}},v=(e,r)=>{if(u.has(e))return;let n=g.get(e);if(n!==void 0&&s()-n<i)return;let c=a.get(e)??0;u.add(e),t.statusOf(e).then(d=>{if(u.delete(e),g.delete(e),(a.get(e)??0)!==c){v(e,r);return}let S=o.get(e),m=S!==void 0&&S.detectedAt===r.detectedAt?S:r;if(d===void 0){o.delete(e);return}o.set(e,{...d,detectedAt:r.detectedAt,at:s()}),(m.done!==d.done||m.total!==d.total)&&p()},d=>{u.delete(e),g.set(e,s()),t.log?.(`[recovery] the steps of ${e} could not be deduced: ${d instanceof Error?d.message:String(d)}`)})};return{progressOf(e){let r=f.progressOf(e);if(r===void 0)return;let n=o.get(e),c=n!==void 0&&n.detectedAt===r.detectedAt;return(!c||s()-n.at>=i)&&v(e,r),c?{...r,done:n.done,total:n.total}:r},onDidChange(e){return l.add(e),{dispose:()=>l.delete(e)}},invalidate(e){let r=e!==void 0?[e]:[...o.keys()];for(let n of r){a.set(n,(a.get(n)??0)+1),g.delete(n);let c=o.get(n);c!==void 0&&o.set(n,{...c,at:Number.NEGATIVE_INFINITY})}p()}}}export{P as a,A as b};
@@ -0,0 +1,9 @@
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 we,b as ye}from"./chunk-4GCYGQXD.mjs";import{a as Me,b as Se}from"./chunk-PC247GKX.mjs";import{b as I}from"./chunk-CA5NAXSU.mjs";import{a as X,b as ke,c as Ae}from"./chunk-TUACWKIH.mjs";import{be as fe,ce as K,de as ge,ge as Q,he as me,ie as he,je as pe,vc as le}from"./chunk-6QSHWIZI.mjs";import{b as F,e as ue,k as z,l as j,v as ce,z as W}from"./chunk-WZQEK4WT.mjs";import{randomUUID as qe}from"node:crypto";import{hostname as He,homedir as Je,uptime as We}from"node:os";import{mkdir as Be,readFile as be,readdir as Ye,rename as _e,writeFile as Ge}from"node:fs/promises";import{dirname as ee,join as ne}from"node:path";function Ee(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:I(e)}]}}function Pe(e){return(Array.isArray(e)?e[0]:e)??{success:!1,errors:[{message:"the org answered nothing"}]}}function Dt(e){return{typeOrg:()=>we(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:le()}).then(Pe,Ee),deleteAssignment:async t=>e.sobject("PermissionSetAssignment").destroy(t).then(Pe,Ee)}}var x=class extends Error{constructor(n){super(n.message);this.refusal=n;this.name="MuteRefusedError"}refusal;get code(){return this.refusal.code}};function Ze(e){return e instanceof x||e instanceof Error&&e.name==="MuteRefusedError"&&"refusal"in e}var Ve=60,Ke=5*6e4,Qe=3e4,Xe=6e4,et=200,tt=448,nt=384,Z=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,C=F().regex(Z),st=j({id:C,permissionSetId:C,permissionSet:F().min(1).max(255)}),rt=j({runId:F().min(1).max(255),host:F().min(1).max(255),pid:ue().int().nonnegative(),hostStartedAt:W.datetime({offset:!0}),acquiredAt:W.datetime({offset:!0}),endsAt:W.datetime({offset:!0}),needs:z(C),assigning:z(C),created:z(st)}),Le=j({version:ce(1),organizationId:C,userId:C,leases:z(rt)}),ot=j(Me),at=Se(e=>{let t=ot.safeParse(e);return t.success?t.data:void 0});function ve(e=process.env,t=Je()){let n=e.SANDFORGE_MUTE_LEASES_DIR;return n!==void 0&&n.trim()!==""?n:ne(t,".sandforge","mute-leases")}function it(e,t,n){if(!Z.test(t)||!Z.test(n))throw new Error("A mute lease is journaled under an org id and a user id.");return ne(e,`${t.slice(0,15)}-${n.slice(0,15)}.json`)}var Ne={host:He(),pid:X.pid,startedAt:X.startedAt},dt=6e4,_=new Set;function xe(e,t,n){return`${e}
8
+ ${t}
9
+ ${n}`}function ut(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 _.has(xe(t,e.runId,e.acquiredAt));let i=s.bootedAt?.()??Date.now()-We()*1e3,c=Date.parse(e.hostStartedAt);return Number.isFinite(c)&&c<i-dt?!1:(s.isAlive??Ae)(e.pid)}var ct=e=>new Promise(t=>setTimeout(t,e));function B(e,t,n){let s=n?.code;return new Error(`The journal of the mute leases in ${ee(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 lt(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())+ke).toISOString()}}function Ce(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 ft(e){return`nothing was assigned. ${Ce(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 Y(e,t,n,s,r=ft,i=Xe){let c=n.self??Ne,g={self:c,...n.checks?{checks:n.checks}:{}},h=Date.now()+i;for(await Be(ee(e),{recursive:!0,mode:tt}).catch(u=>{throw B(e,"made",u)});;){let u;try{u=at.acquire(`${e}.lock`,a=>a,g)}catch(a){throw B(e,"locked",a)}if("lock"in u)try{let a=await gt(e,t).catch(l=>{throw B(e,"read",l)});return await s(a,async l=>{let p=`${e}.${process.pid}-${qe()}.tmp`;try{await Ge(p,JSON.stringify(l,null,2),{encoding:"utf8",mode:nt}),await _e(p,e)}catch(w){throw B(e,"written",w)}})}finally{u.lock.release()}if(Date.now()>h){let a=lt(u.busy,c);throw new x({code:"MUTE_FAILED",message:`The journal of the mute leases in ${ee(e)} stayed locked for a minute by process ${a.pid} on ${a.host}: ${r(a)}`})}await ct(et)}}async function gt(e,t){let n={version:1,...t,leases:[]},s;try{s=await be(e,"utf8")}catch(r){if(r.code==="ENOENT")return n;throw r}try{let r=Le.safeParse(JSON.parse(s));if(r.success)return r.data}catch{}return await _e(e,`${e}.${Date.now()}.unreadable`).catch(()=>{}),n}var mt=new Set(["ENTITY_IS_DELETED","INVALID_CROSS_REFERENCE_KEY","NOT_FOUND"]);async function G(e,t,n,s){let r=t.leases.filter(a=>a!==n&&s(a)),i=[...n.created],c=new Set,g=n.assigning[0];if(g!==void 0){let a=new Set(t.leases.flatMap(l=>l===n?[]:l.created.map(p=>p.id))),A=await e.query(`SELECT Id, PermissionSetId, PermissionSet.Name FROM PermissionSetAssignment WHERE AssigneeId = '${t.userId}' AND PermissionSetId IN ('${g}')`).then(l=>l.records).catch(()=>[]);for(let l of A){let p=typeof l.Id=="string"?l.Id:void 0,w=typeof l.PermissionSetId=="string"?l.PermissionSetId:void 0;if(!p||!w||a.has(p)||i.some(v=>v.id===p))continue;let O=l.PermissionSet;i.push({id:p,permissionSetId:w,permissionSet:typeof O?.Name=="string"?O.Name:w}),c.add(p)}}let h={removed:[],passed:[],left:[],found:[]};for(let a of i){let A=r.find(w=>w.needs.includes(a.permissionSetId));if(A){A.created.some(w=>w.id===a.id)||A.created.push(a),h.passed.push(a);continue}let l=await e.deleteAssignment(a.id),p=l.errors?.[0]?.statusCode??l.errors?.[0]?.errorCode;l.success||p!==void 0&&mt.has(p)?(h.removed.push(a),c.has(a.id)&&h.found.push(a)):h.left.push({...a,why:l.errors?.[0]?.message??p??"the org refused the delete"})}let u=t.leases.indexOf(n);return h.left.length===0?t.leases.splice(u,1):t.leases[u]={...n,endsAt:new Date(0).toISOString(),needs:[],assigning:[],created:h.left.map(({id:a,permissionSetId:A,permissionSet:l})=>({id:a,permissionSetId:A,permissionSet:l}))},h}function L(e){return e.map(t=>t.permissionSet)}function $e(e,t){let n=r=>L(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 Ie(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 De(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 ht(e,t,n){let s=[];for(let r of[...t.leases])n(r)||s.push(...(await G(e,t,r,n)).found);return s}async function pt(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 (${I(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 Re(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 Oe=/^[A-Za-z][A-Za-z0-9_]*$/;async function wt(e,t){let s=t.map(Re).filter(c=>Oe.test(c.developerName)&&(!c.namespace||Oe.test(c.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(c=>`'${c.developerName}'`))].join(", ")+")"),i=new Map;for(let c of t){let{namespace:g,developerName:h}=Re(c),u=r.records.find(a=>String(a.Name??"").toLowerCase()===h.toLowerCase()&&String(a.NamespacePrefix??"").toLowerCase()===g.toLowerCase());typeof u?.Id=="string"&&i.set(c,u.Id)}return i}async function Te(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(i=>`'${i}'`).join(", ")})`),r=new Map;for(let i of s.records){let c=i.PermissionSetId,g=i.Id;typeof c=="string"&&typeof g=="string"&&r.set(c,g)}return r}function te(e,t,n){return{state:t,assigned:[],held:[],permissions:K(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 Ue="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 yt(e,t,n={}){let s,r;try{let u=await e.typeOrg();s=ye(u),r=u.id}catch(u){return{refused:{code:"MUTE_PRODUCTION",message:`The target did not say what org it is (${I(u)}), 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:i,automation:c,planned:g}=Mt(t,n.writes);if(i.assign.length===0)return{plan:i,automation:t,planned:g,acquire:async()=>({outcome:g,release:async()=>g})};let h=await pt(e);return h!==void 0?{refused:{code:"MUTE_NO_RIGHT",message:`The target's automation cannot be muted: ${h}. Nothing was assigned: run it without muting the target's automation, or have that user given Assign Permission Sets.`}}:(Fe.set(i,await At(n.dir??ve(),r)),{plan:i,automation:c,planned:g,acquire:u=>St(e,i,u,n)})}var Fe=new WeakMap,kt=/^[A-Za-z0-9]{15}-[A-Za-z0-9]{15}\.json$/;async function At(e,t){if(!Z.test(t))return 0;let n=`${t.slice(0,15)}-`,s;try{s=await Ye(e)}catch{return 0}let r=0;for(let i of s)if(!(!i.startsWith(n)||!kt.test(i)))try{let c=Le.safeParse(JSON.parse(await be(ne(e,i),"utf8")));if(!c.success)continue;for(let g of c.data.leases)r+=(g.assigning.length>0?1:0)+g.created.length}catch{}return r}function Mt(e,t){let n=fe(e,t);return n.assign.length===0?{plan:n,automation:e,planned:te(n,"nothing",Ue)}:{plan:n,automation:ge(e,K(n)),planned:te(n,"planned")}}async function St(e,t,n,s={}){let r=s.self??Ne,i=()=>s.checks?.now?.()??Date.now(),c=s.minutes??Ve,g=o=>{throw new x({code:"MUTE_FAILED",message:o})},h=await e.identity().catch(o=>g(`The target would not say who the run writes as (${I(o)}).`)),u={organizationId:h.organization_id,userId:h.user_id},a=it(s.dir??ve(),u.organizationId,u.userId),A=t.assign.map(o=>o.permissionSet),l=await wt(e,A).catch(o=>g(`The permission sets to assign could not be read (${I(o)}).`)),p=A.filter(o=>!l.has(o));p.length>0&&g(`The target holds no permission set ${p.join(", ")}: nothing was assigned.`);let w=A.map(o=>l.get(o)),O=new Map(A.map(o=>[l.get(o),o])),v=o=>ut(o,a,r,s.checks),D=new Date(i()).toISOString(),N=xe(a,n,D),se=!1,re=w.map(o=>O.get(o)),ze=s.retryEveryMs??Qe,q,oe=(o,y)=>{if(q!==void 0)return;let d=new Set(o.map(m=>m.id)),k=!1,M=()=>clearInterval(q);q=setInterval(()=>{k||(k=!0,Y(a,u,s,async(m,H)=>{let P=m.leases.find(R=>R.runId===n&&R.acquiredAt===D);if(P){P.assigning=[],P.created=[...P.created,...y.filter(b=>!P.created.some(J=>J.id===b.id))].filter(b=>!d.has(b.id));let R=await G(e,m,P,v);for(let b of R.removed)d.add(b.id);await H(m)}M()},void 0,0).catch(()=>{}).finally(()=>{k=!1}))},ze),q.unref?.()},U=await Y(a,u,s,async(o,y)=>{let d=L(await ht(e,o,v)),k=await Te(e,u.userId,w),M=w.filter(f=>!k.has(f)),m={runId:n,host:r.host,pid:r.pid,hostStartedAt:r.startedAt,acquiredAt:D,endsAt:new Date(i()+c*6e4).toISOString(),needs:w,assigning:[...M],created:[]};o.leases.push(m),_.add(N),await y(o),se=!0;let H=[...m.assigning],P=()=>y(o).then(()=>{H=[...m.assigning]},f=>I(f)),R=async f=>{m.assigning=[];let E=await G(e,o,m,v);_.delete(N);let S=await P();S!==void 0&&oe(E.removed,[...E.passed,...E.left]);let $=S!==void 0&&H.length===0?{sets:re,until:m.endsAt}:void 0,de=$e(E,S===void 0);return g([f,...S!==void 0&&S!==f?[S]:[],...de.length>0?de:["Nothing was assigned."],...S!==void 0&&(E.passed.length>0||E.left.length>0||$)?[Ie(r.pid,$)]:[],...d.length>0?[`Taking its lease, the run took back ${d.join(", ")}, ${De(d)}.`]:[]].join(" "))};for(let f of M){let E=await e.createAssignment({AssigneeId:u.userId,PermissionSetId:f});if(m.assigning=m.assigning.filter($=>$!==f),E.success&&E.id){m.created.push({id:E.id,permissionSetId:f,permissionSet:O.get(f)});let $=await P();if($!==void 0)return R($);continue}let S=E.errors?.[0];if((S?.statusCode??S?.errorCode)==="DUPLICATE_VALUE"){let $=await P();if($!==void 0)return R($);continue}return R(`${O.get(f)} could not be assigned to the user the run writes as: ${S?.message??S?.statusCode??"the org refused it"}.`)}let b=await Te(e,u.userId,w).catch(()=>new Map),J=w.filter(f=>!b.has(f));if(J.length>0)return R(`Read back, the user the run writes as does not hold ${J.map(f=>O.get(f)).join(", ")}.`);let je=new Set(m.created.map(f=>f.permissionSetId));return{endsAt:m.endsAt,assigned:m.created.map(f=>f.permissionSet),held:w.filter(f=>!je.has(f)).map(f=>O.get(f)),found:d}}).catch(o=>{if(_.delete(N),Ze(o))throw o;return g(`${I(o)}${se?"":" Nothing was assigned."}`)}),T={...te(t,"muted"),assigned:U.assigned,held:U.held,leaseEndsAt:U.endsAt,...U.found.length>0?{tookBackOfEnded:U.found}:{}},ae=s.renewEveryMs??Ke,V=ae>0?setInterval(()=>{Y(a,u,s,async(o,y)=>{let d=o.leases.find(M=>M.runId===n&&M.acquiredAt===D);if(!d||!_.has(N))return;let k=new Date(i()+c*6e4).toISOString();d.endsAt=k,await y(o),T.leaseEndsAt=k}).catch(()=>{})},ae):void 0;V?.unref?.();let ie;return{outcome:T,release:()=>(ie??=(async()=>{V&&clearInterval(V);let o={};try{await Y(a,u,s,async(d,k)=>{let M=d.leases.find(m=>m.runId===n&&m.acquiredAt===D);_.delete(N),M&&(o.done=await G(e,d,M,v),await k(d))},d=>`nothing was taken back. ${Ce(d)} Should none of its runs be muting this org, end process ${d.pid}`);let y=o.done?.left??[];return{...T,released:y.length===0,takenBack:L(o.done?.removed??[]),...o.done&&o.done.passed.length>0?{passed:L(o.done.passed)}:{},...y.length>0?{notTakenBack:L(y),reason:`${y.map(d=>`${d.permissionSet} (${d.why})`).join(", ")} could not be taken back: the lease ends at ${T.leaseEndsAt}, and the next run that mutes this org releases it`}:{}}}catch(y){_.delete(N);let d=o.done;if(oe(d?.removed??[],d?[...d.passed,...d.left]:[]),d!==void 0){let k=T.leaseEndsAt,M=k!==void 0&&Date.parse(k)>i()?{sets:re,until:k}:void 0;return{...T,released:!1,takenBack:L(d.removed),notTakenBack:L([...d.passed,...d.left]),reason:[I(y),...$e({...d,removed:[]},!1),Ie(r.pid,M)].join(" ")}}return{...T,released:!1,takenBack:[],reason:`the assignments could not be taken back (${I(y)}): this process tries again while it runs, and takes them back once it can use the journal; past ${T.leaseEndsAt}, or once process ${r.pid} has ended, the next run that mutes this org releases the lease`}}})(),ie)}}var Et=2,Pt=3;function $t(e){return!e||e.assign.length===0?0:Et+Pt+2*e.assign.length+(Fe.get(e)??0)}function Ut(e){let t=$t(e);return t>0?{mute:t}:{}}function It(e){return{state:"nothing",assigned:[],held:[],permissions:[],silenced:[],stillRan:[],reason:`nothing can be muted: ${e}; the run goes on as without the option`}}function Ft(e){return e?{mutedAutomation:e.muted,...e.plan?{mutePlan:e.plan}:{}}:{}}async function zt(e,t,n={}){if(typeof t.unread=="string")return{automation:void 0,muted:It(`the target's automation could not be read (${t.unread})`)};let s=await yt(await e(),t,n);if("refused"in s)throw new x(s.refused);return{automation:s.automation,...s.plan.assign.length>0?{prepared:s}:{},muted:s.planned,plan:s.plan}}function jt(e){let t=e?.mutedAutomation;return t!==null&&typeof t=="object"?t:void 0}function qt(e,t){let n=[];e.state==="nothing"?n.push(`mute: ${e.reason??Ue}`):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(", ")}, `+De(e.tookBackOfEnded));for(let r of e.silenced)n.push(` silenced: ${Q(r)} (bypass ${r.permission})`);for(let r of e.stillRan)n.push(` still runs: ${Q(r)} (${me(r.why)})`);for(let r of e.alsoLifted??[])n.push(` also lifts: ${he(r)}`);for(let r of e.liftsUnread??[])n.push(` ${pe(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{Dt as a,Ze as b,yt as c,Mt as d,$t as e,Ut as f,Ft as g,zt as h,jt as i,qt as j};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{i as g,n as p,o as m}from"./chunk-T26C576X.mjs";import{a as b,b as I}from"./chunk-MS4FJDFD.mjs";import{c as w}from"./chunk-LCDPCUXS.mjs";import{Ec as l,p as d,q as u}from"./chunk-DPYTG6DM.mjs";import{A as c}from"./chunk-WZQEK4WT.mjs";import{d as f}from"./chunk-NTOVCTRS.mjs";var a=class extends Error{constructor(t,r){super(`${r} Nothing was read from ${t}.`);this.alias=t;this.reason=r;this.name="SfSessionError",this.stack=this.message}alias;reason},$=c.object({name:c.string().optional(),message:c.string().optional()}).loose();function h(e){if(typeof e!="string")return;let n=e.replace(/\u001b\[[0-9;]*m/g,""),t=n.indexOf("{");if(t!==-1)try{let r=$.safeParse(JSON.parse(n.slice(t)));return r.success?r.data:void 0}catch{return}}function C(e,n=process.platform){let t=typeof e=="object"&&e!==null?e:{};return t.code==="ENOENT"?!0:n==="win32"&&(t.status===9009||/is not recognized as an internal or external command/i.test(String(t.stderr??"")))}function S(e,n,t=process.platform){if(C(n,t))return new a(e,`${d} SandForge reads each org through the Salesforce CLI: install it with "npm install -g @salesforce/cli" (${u}), sign in to the org with "sf org login web --alias ${e}", and run again.`);let r=typeof n=="object"&&n!==null?n:{},o=h(r.stdout)??h(r.stderr);if(o?.name==="NamedOrgNotFoundError"||/^No authorization information found for /.test(o?.message??""))return new a(e,`sf does not know ${e}: "sf org list" names the orgs it knows; "sf org login web --alias ${e}" adds it (in a CI job, "sf org login jwt" or "sf org login sfdx-url").`);let s=typeof r.stderr=="string"?r.stderr.split(/\r?\n/).find(y=>y.trim()!==""):void 0,i=o?.message?.trim()||s?.trim()||(n instanceof Error?n.message:String(n));return new a(e,`sf could not show ${e}: ${i}`)}var k=f(I()),x=f(b());import{execFileSync as E}from"node:child_process";function T(e){try{return E("sf",["org","display","--target-org",e,"--json"],{encoding:"utf8",maxBuffer:50*1024*1024,shell:process.platform==="win32"})}catch(n){throw S(e,n)}}async function A(e,n=m){if(!w.test(e))throw new Error(`Invalid SF org alias: "${e}" (an alias or a username: letters, digits, _ . @ + and -, not starting with . @ + or -)`);let t=T(e),r=JSON.parse(t),o=r.result;if(typeof o?.devHubId=="string"&&o.devHubId!==""){let i=typeof o.expirationDate=="string"?l({orgType:"Scratch",metadata:{expirationDate:o.expirationDate}},new Date().toISOString().slice(0,10)):void 0;if(i!==void 0||o.status==="Deleted")throw new Error(`The scratch org '${e}' ${i!==void 0?`expired on ${i}`:"is deleted"}: Salesforce deletes a scratch org when it expires, and no sign-in brings it back. Create a new one ("sf org create scratch") and give its alias.`)}if(!r.result?.instanceUrl)throw new Error(`sf org display did not return a usable session for alias '${e}'.`);let s=await n(e);if(!p(s.accessToken))throw new Error(`The Salesforce CLI showed no usable access token for alias '${e}'. Sign in again with "sf org login web --alias ${e}" where a browser opens; in a CI job, with "sf org login jwt --alias ${e}" (a client id, a key file and a username) or "sf org login sfdx-url --alias ${e} --sfdx-url-file <file>" (see ci-examples/README.md).`);return{alias:e,username:r.result.username??"",instanceUrl:s.instanceUrl??r.result.instanceUrl,accessToken:s.accessToken,...typeof r.result.devHubId=="string"&&r.result.devHubId!==""?{scratch:!0}:{}}}function H(e,n=process.env){let t=g(e.instanceUrl,n),r=new k.default.Connection({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:"66.0",...t!==void 0?{httpProxy:t}:{}});return t===void 0&&(r._transport=new x.HttpProxyTransport("")),r}export{a,A as b,H as c};
7
+ import{i as g,n as p,o as m}from"./chunk-OUU47Y7A.mjs";import{a as b,b as I}from"./chunk-MS4FJDFD.mjs";import{c as w}from"./chunk-LCDPCUXS.mjs";import{bd as l,p as d,q as u}from"./chunk-6QSHWIZI.mjs";import{A as c}from"./chunk-WZQEK4WT.mjs";import{d as f}from"./chunk-NTOVCTRS.mjs";var a=class extends Error{constructor(t,r){super(`${r} Nothing was read from ${t}.`);this.alias=t;this.reason=r;this.name="SfSessionError",this.stack=this.message}alias;reason},$=c.object({name:c.string().optional(),message:c.string().optional()}).loose();function h(e){if(typeof e!="string")return;let n=e.replace(/\u001b\[[0-9;]*m/g,""),t=n.indexOf("{");if(t!==-1)try{let r=$.safeParse(JSON.parse(n.slice(t)));return r.success?r.data:void 0}catch{return}}function C(e,n=process.platform){let t=typeof e=="object"&&e!==null?e:{};return t.code==="ENOENT"?!0:n==="win32"&&(t.status===9009||/is not recognized as an internal or external command/i.test(String(t.stderr??"")))}function S(e,n,t=process.platform){if(C(n,t))return new a(e,`${d} SandForge reads each org through the Salesforce CLI: install it with "npm install -g @salesforce/cli" (${u}), sign in to the org with "sf org login web --alias ${e}", and run again.`);let r=typeof n=="object"&&n!==null?n:{},o=h(r.stdout)??h(r.stderr);if(o?.name==="NamedOrgNotFoundError"||/^No authorization information found for /.test(o?.message??""))return new a(e,`sf does not know ${e}: "sf org list" names the orgs it knows; "sf org login web --alias ${e}" adds it (in a CI job, "sf org login jwt" or "sf org login sfdx-url").`);let s=typeof r.stderr=="string"?r.stderr.split(/\r?\n/).find(y=>y.trim()!==""):void 0,i=o?.message?.trim()||s?.trim()||(n instanceof Error?n.message:String(n));return new a(e,`sf could not show ${e}: ${i}`)}var k=f(I()),x=f(b());import{execFileSync as E}from"node:child_process";function T(e){try{return E("sf",["org","display","--target-org",e,"--json"],{encoding:"utf8",maxBuffer:50*1024*1024,shell:process.platform==="win32"})}catch(n){throw S(e,n)}}async function A(e,n=m){if(!w.test(e))throw new Error(`Invalid SF org alias: "${e}" (an alias or a username: letters, digits, _ . @ + and -, not starting with . @ + or -)`);let t=T(e),r=JSON.parse(t),o=r.result;if(typeof o?.devHubId=="string"&&o.devHubId!==""){let i=typeof o.expirationDate=="string"?l({orgType:"Scratch",metadata:{expirationDate:o.expirationDate}},new Date().toISOString().slice(0,10)):void 0;if(i!==void 0||o.status==="Deleted")throw new Error(`The scratch org '${e}' ${i!==void 0?`expired on ${i}`:"is deleted"}: Salesforce deletes a scratch org when it expires, and no sign-in brings it back. Create a new one ("sf org create scratch") and give its alias.`)}if(!r.result?.instanceUrl)throw new Error(`sf org display did not return a usable session for alias '${e}'.`);let s=await n(e);if(!p(s.accessToken))throw new Error(`The Salesforce CLI showed no usable access token for alias '${e}'. Sign in again with "sf org login web --alias ${e}" where a browser opens; in a CI job, with "sf org login jwt --alias ${e}" (a client id, a key file and a username) or "sf org login sfdx-url --alias ${e} --sfdx-url-file <file>" (see ci-examples/README.md).`);return{alias:e,username:r.result.username??"",instanceUrl:s.instanceUrl??r.result.instanceUrl,accessToken:s.accessToken,...typeof r.result.devHubId=="string"&&r.result.devHubId!==""?{scratch:!0}:{}}}function H(e,n=process.env){let t=g(e.instanceUrl,n),r=new k.default.Connection({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:"66.0",...t!==void 0?{httpProxy:t}:{}});return t===void 0&&(r._transport=new x.HttpProxyTransport("")),r}export{a,A as b,H as c};
@@ -0,0 +1,28 @@
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 s}from"./chunk-SCKUIE3R.mjs";import{readFileSync as d}from"node:fs";import{extname as p,join as i}from"node:path";import{pathToFileURL as c}from"node:url";var r={autopilot:"run an Autopilot copy between two orgs",backup:"take and restore DataOps snapshots",checkpoint:"take a checkpoint of an org's data, and rewind the org to it",cleanup:"Bulk delete records you created on a sandbox in a time window",clone:"clone a record, or whole tables, from one org to a sandbox, or remove a run",compare:"compare two orgs the way the Compare page does",dataops:"mask an org's records, and put them back",empty:"empty objects of a sandbox, or the whole of it",env:"apply a sandforge.yaml to an org, and take it back",frozen:"build and replay a Frozen Dataset",mcp:"the MCP server: these scripts as tools for an AI agent, on stdio",monitor:"read an org the way the Monitor page does",pipeline:"plan and run an Automation pipeline exported from VS Code",seed:"fill an org from a seed template",sync:"run a Sync between two orgs",users:"set up the users of a sandbox after its refresh, and take them back"},a=o=>Object.prototype.hasOwnProperty.call(r,o);function m(o){let[e,...n]=o;if(e===void 0)return{kind:"refused",reason:"Name the command to run."};if(e==="--help"||e==="-h"||e==="help")return{kind:"help"};if(e==="--version"||e==="-v")return{kind:"version"};if(a(e))return{kind:"run",tool:e,args:n};let t=e.replace(/^sandforge-/,"");return t!==e&&a(t)?{kind:"refused",reason:`"${e}" is named ${t} here: ${s(t)} \u2026.`}:{kind:"refused",reason:e.startsWith("-")?`"${e}" is not a flag sandforge reads: name a command first.`:`"${e}" is not a command of sandforge.`}}function l(){let o=Math.max(...Object.keys(r).map(n=>n.length));return`sandforge \u2014 SandForge's command lines, without the editor: Seed, Forge's clone, Sync,
8
+ Checkpoints, DataOps, Frozen Dataset, the emptying of a sandbox, the users of a sandbox,
9
+ sandforge.yaml environments, Automation pipelines, and the MCP server.
10
+
11
+ Usage:
12
+ sandforge <command> [options]
13
+ sandforge <command> --help what the command does, its options and its exit codes
14
+
15
+ Commands:
16
+ ${Object.entries(r).map(([n,t])=>` ${n.padEnd(o)} ${t}`).join(`
17
+ `)}
18
+
19
+ Each org is named by its sf CLI alias: the Salesforce CLI (sf) must be installed and logged in
20
+ to it. In Claude Code:
21
+ claude mcp add sandforge -- npx -y sandforge mcp
22
+
23
+ --version the version of SandForge these scripts belong to
24
+ --help this text
25
+ `}function f(o,e=__dirname,n=__filename){return i(e,`sandforge-${o}${p(n)}`)}function u(o=__dirname){let e=JSON.parse(d(i(o,"..","package.json"),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}var g=o=>import(c(o).href);async function h(o=process.argv,e=g){let n=m(o.slice(2));switch(n.kind){case"help":process.stdout.write(l());return;case"version":process.stdout.write(`${u()}
26
+ `);return;case"refused":process.stderr.write(`${n.reason} Nothing was run. The commands: ${Object.keys(r).join(", ")}. Run with --help.
27
+ `),process.exitCode=2;return;case"run":{let t=f(n.tool);process.argv=[o[0]??process.execPath,t,...n.args],await e(t);return}}}/(?:^|[\\/])sandforge\.[cm]?[jt]s$/.test(process.argv[1]??"")&&h().catch(o=>{process.stderr.write(`${o instanceof Error?o.message:String(o)}
28
+ `),process.exit(1)});export{r as a,m as b,l as c,f as d,u as e,h as f};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{m as a,n as b,o as c,p as d,q as e,r as f,s as g}from"./chunk-DHGPDSXS.mjs";import"./chunk-GMY5427L.mjs";import"./chunk-TEIBWMJM.mjs";import"./chunk-BWWQXU2B.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-UIUPPEFB.mjs";import"./chunk-T63U4OZJ.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-ICIYL45C.mjs";import"./chunk-ZUA5BNAO.mjs";import"./chunk-RKALOKAU.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-55LQD3Y3.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-3B5H24ZG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-DPYTG6DM.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as DataSync,f as MAX_RESULT_REFUSALS_PER_OBJECT,g as buildObjectResult,d as linkedRecordOf,c as notReachedOf,b as unsetOf,e as withCurrencies};
7
+ import{m as a,n as b,o as c,p as d,q as e,r as f,s as g}from"./chunk-GEEWPTV5.mjs";import"./chunk-GMY5427L.mjs";import"./chunk-TEIBWMJM.mjs";import"./chunk-BWWQXU2B.mjs";import"./chunk-T63U4OZJ.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-YBZIDW6W.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-2GSMHGIV.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-ISOSTAJR.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-ICIYL45C.mjs";import"./chunk-7BQMBXKX.mjs";import"./chunk-KWAVSZ2B.mjs";import"./chunk-6QSHWIZI.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as DataSync,f as MAX_RESULT_REFUSALS_PER_OBJECT,g as buildObjectResult,d as linkedRecordOf,c as notReachedOf,b as unsetOf,e as withCurrencies};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{b as S,d as z}from"./chunk-BNO5GIJ6.mjs";import{h as I}from"./chunk-TZE3Y7IQ.mjs";import{b as h}from"./chunk-CA5NAXSU.mjs";import{Yb as R}from"./chunk-DPYTG6DM.mjs";import{b as f,e as b,f as y,i as A,k,l as m,o as K}from"./chunk-WZQEK4WT.mjs";var w="Knowledge__kav",j="CaseArticle",T="Case",P="Summary",B=255,D=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,L=m({name:f(),type:f(),length:b().optional(),extraTypeInfo:f().nullish(),htmlFormatted:y().optional(),createable:y().optional()}).loose(),F=m({fields:k(A())}).loose();function M(e){if(!(e.type!=="textarea"||e.createable!==!0))return e.name===P?"summary":e.extraTypeInfo==="richtextarea"||e.htmlFormatted===!0?"richText":(e.length??0)>B?"longText":void 0}var O={richText:0,longText:1,summary:2};function G(e){let r=F.safeParse(e);if(!r.success)return[];let o=[];for(let t of r.data.fields){let n=L.safeParse(t);if(!n.success)continue;let d=M(n.data);d===void 0||typeof n.data.length!="number"||o.push({name:n.data.name,length:n.data.length,kind:d})}return o.sort((t,n)=>O[t.kind]-O[n.kind]||n.length-t.length||t.name.localeCompare(n.name))}function U(e){return{articleBodyField:e.name,articleBodyLength:e.length,...e.kind==="richText"?{articleBodyHtml:!0}:{}}}var x=m({success:y(),errors:k(K([m({statusCode:f().optional(),message:f().optional()}).loose(),f()])).optional()}).loose();function $(e){let r=x.safeParse(e),o=r.success?r.data.errors?.[0]:void 0;return o===void 0?"The org gave no reason.":typeof o=="string"?o:[o.statusCode,o.message].filter(Boolean).join(": ")||"The org gave no reason."}function N(e){let r=x.safeParse(e);return r.success&&r.data.success}function C(e){return e.slice(0,15)}function X(e){return async({ids:r,results:o})=>{let t=r.get(w)??new Map;if(t.size===0)return{skipped:o.find(u=>u.objectApiName===w)?.errors[0]??`The run wrote no ${w} article, so none was published or linked.`};let n={};return e.plan.publish&&(n.publish=await _(e,t)),e.plan.links.length>0&&(n.links=await v(e,t,r.get(T)??new Map)),n}}async function _(e,r){let o={asked:r.size,done:0,notDone:[]};for(let[t,n]of r){if(e.signal?.aborted){o.notDone.push({key:t,reason:"Left a draft: the run was stopped before it was published."});continue}if(!D.test(n)){o.notDone.push({key:t,reason:`Left a draft: ${n} is not a record id.`});continue}try{await e.org.request({method:"PATCH",url:`/knowledgeManagement/articleVersions/masterVersions/${n}`,body:JSON.stringify({publishStatus:"Online"}),headers:{"Content-Type":"application/json"}}),o.done++}catch(d){o.notDone.push({key:t,reason:`Left a draft: ${h(d)}`})}finally{e.journal?.wroteAgain(w,[n])}}return o}async function v(e,r,o){let t={asked:e.plan.links.length,done:0,notDone:[]},n,d;try{n=await q(e.org,[...r.values()])}catch(s){n=new Map,d=h(s)}let u=[],c=(s,a)=>{t.notDone.push({key:s,reason:`Not linked: ${a}.`})};for(let{caseKey:s,articleKey:a}of e.plan.links){let l=o.get(s),g=r.get(a);if(l===void 0){c(s,"its case was not written");continue}if(g===void 0){c(s,`its article ${a} was not written`);continue}let i=n.get(C(g));if(i===void 0){c(s,`the article of ${a} could not be read back`+(d?` (${d})`:": the org no longer holds its version"));continue}u.push({caseKey:s,caseId:l,articleId:i,versionId:g})}for(let s=0;s<u.length;s+=S){let a=u.slice(s,s+S);if(e.signal?.aborted){for(let{caseKey:i}of a)t.notDone.push({key:i,reason:"Not linked: the run was stopped before it."});continue}let l;try{l=await e.org.sobject(j).create(a.map(({caseId:i,articleId:p})=>({CaseId:i,KnowledgeArticleId:p})),{headers:R()})}catch(i){let p=`Not linked: ${h(i)}`;for(let{caseKey:E}of a)t.notDone.push({key:E,reason:p});l=[]}finally{e.journal?.wroteAgain(T,a.map(({caseId:i})=>i)),e.journal?.wroteAgain(w,[...new Set(a.map(({versionId:i})=>i))])}let g=Array.isArray(l)?l:[l];g.length!==0&&a.forEach(({caseKey:i},p)=>{N(g[p])?t.done++:t.notDone.push({key:i,reason:`Not linked: ${$(g[p])}`})})}return t}async function q(e,r){let o=I(w),t=new Map;for(let n of z(r)){let d=await e.query(`SELECT Id, KnowledgeArticleId FROM ${o} WHERE Id IN (${n})`);for(let u of d.records){let c=u;typeof c?.Id=="string"&&typeof c.KnowledgeArticleId=="string"&&t.set(C(c.Id),c.KnowledgeArticleId)}}return t}export{w as a,G as b,U as c,X as d};
7
+ import{b as S,d as z}from"./chunk-MJD6CPZZ.mjs";import{h as I}from"./chunk-TZE3Y7IQ.mjs";import{b as h}from"./chunk-CA5NAXSU.mjs";import{vc as R}from"./chunk-6QSHWIZI.mjs";import{b as f,e as b,f as y,i as A,k,l as m,o as K}from"./chunk-WZQEK4WT.mjs";var w="Knowledge__kav",j="CaseArticle",T="Case",P="Summary",B=255,D=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,L=m({name:f(),type:f(),length:b().optional(),extraTypeInfo:f().nullish(),htmlFormatted:y().optional(),createable:y().optional()}).loose(),F=m({fields:k(A())}).loose();function M(e){if(!(e.type!=="textarea"||e.createable!==!0))return e.name===P?"summary":e.extraTypeInfo==="richtextarea"||e.htmlFormatted===!0?"richText":(e.length??0)>B?"longText":void 0}var O={richText:0,longText:1,summary:2};function G(e){let r=F.safeParse(e);if(!r.success)return[];let o=[];for(let t of r.data.fields){let n=L.safeParse(t);if(!n.success)continue;let d=M(n.data);d===void 0||typeof n.data.length!="number"||o.push({name:n.data.name,length:n.data.length,kind:d})}return o.sort((t,n)=>O[t.kind]-O[n.kind]||n.length-t.length||t.name.localeCompare(n.name))}function U(e){return{articleBodyField:e.name,articleBodyLength:e.length,...e.kind==="richText"?{articleBodyHtml:!0}:{}}}var x=m({success:y(),errors:k(K([m({statusCode:f().optional(),message:f().optional()}).loose(),f()])).optional()}).loose();function $(e){let r=x.safeParse(e),o=r.success?r.data.errors?.[0]:void 0;return o===void 0?"The org gave no reason.":typeof o=="string"?o:[o.statusCode,o.message].filter(Boolean).join(": ")||"The org gave no reason."}function N(e){let r=x.safeParse(e);return r.success&&r.data.success}function C(e){return e.slice(0,15)}function X(e){return async({ids:r,results:o})=>{let t=r.get(w)??new Map;if(t.size===0)return{skipped:o.find(u=>u.objectApiName===w)?.errors[0]??`The run wrote no ${w} article, so none was published or linked.`};let n={};return e.plan.publish&&(n.publish=await _(e,t)),e.plan.links.length>0&&(n.links=await v(e,t,r.get(T)??new Map)),n}}async function _(e,r){let o={asked:r.size,done:0,notDone:[]};for(let[t,n]of r){if(e.signal?.aborted){o.notDone.push({key:t,reason:"Left a draft: the run was stopped before it was published."});continue}if(!D.test(n)){o.notDone.push({key:t,reason:`Left a draft: ${n} is not a record id.`});continue}try{await e.org.request({method:"PATCH",url:`/knowledgeManagement/articleVersions/masterVersions/${n}`,body:JSON.stringify({publishStatus:"Online"}),headers:{"Content-Type":"application/json"}}),o.done++}catch(d){o.notDone.push({key:t,reason:`Left a draft: ${h(d)}`})}finally{e.journal?.wroteAgain(w,[n])}}return o}async function v(e,r,o){let t={asked:e.plan.links.length,done:0,notDone:[]},n,d;try{n=await q(e.org,[...r.values()])}catch(s){n=new Map,d=h(s)}let u=[],c=(s,a)=>{t.notDone.push({key:s,reason:`Not linked: ${a}.`})};for(let{caseKey:s,articleKey:a}of e.plan.links){let l=o.get(s),g=r.get(a);if(l===void 0){c(s,"its case was not written");continue}if(g===void 0){c(s,`its article ${a} was not written`);continue}let i=n.get(C(g));if(i===void 0){c(s,`the article of ${a} could not be read back`+(d?` (${d})`:": the org no longer holds its version"));continue}u.push({caseKey:s,caseId:l,articleId:i,versionId:g})}for(let s=0;s<u.length;s+=S){let a=u.slice(s,s+S);if(e.signal?.aborted){for(let{caseKey:i}of a)t.notDone.push({key:i,reason:"Not linked: the run was stopped before it."});continue}let l;try{l=await e.org.sobject(j).create(a.map(({caseId:i,articleId:p})=>({CaseId:i,KnowledgeArticleId:p})),{headers:R()})}catch(i){let p=`Not linked: ${h(i)}`;for(let{caseKey:E}of a)t.notDone.push({key:E,reason:p});l=[]}finally{e.journal?.wroteAgain(T,a.map(({caseId:i})=>i)),e.journal?.wroteAgain(w,[...new Set(a.map(({versionId:i})=>i))])}let g=Array.isArray(l)?l:[l];g.length!==0&&a.forEach(({caseKey:i},p)=>{N(g[p])?t.done++:t.notDone.push({key:i,reason:`Not linked: ${$(g[p])}`})})}return t}async function q(e,r){let o=I(w),t=new Map;for(let n of z(r)){let d=await e.query(`SELECT Id, KnowledgeArticleId FROM ${o} WHERE Id IN (${n})`);for(let u of d.records){let c=u;typeof c?.Id=="string"&&typeof c.KnowledgeArticleId=="string"&&t.set(C(c.Id),c.KnowledgeArticleId)}}return t}export{w as a,G as b,U as c,X as d};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as N}from"./chunk-ETT5GP4P.mjs";import{a as j,h as D}from"./chunk-TZE3Y7IQ.mjs";import{b as J}from"./chunk-CA5NAXSU.mjs";function se(e){return`sync-before-${e.replace(/[^A-Za-z0-9-]+/g,"-")}`.slice(0,200)}var oe=1e3;function he(e){let o=se(e.runId),d=new Map,a=e.everyMs??oe,g=()=>(e.now?.()??new Date).getTime(),S,I=Number.NEGATIVE_INFINITY,k,E=!1,R=h=>{if(S===void 0)return;let t=[...d].map(([l,c])=>({objectApiName:l,recordCount:c,truncated:!1}));e.meta.set(`backup:${o}`,{operationId:o,orgId:e.orgId,...e.organizationId!==void 0?{organizationId:e.organizationId}:{},objects:t,partial:h,timestamp:S,totalRecords:t.reduce((l,c)=>l+c.recordCount,0),origin:"sync",runId:e.runId},"backups")},z=()=>{if(E)return;let h=I+a-g();if(h<=0){k!==void 0&&clearTimeout(k),k=void 0,I=g(),R(!0);return}k??=setTimeout(()=>{if(k=void 0,!E){I=g();try{R(!0)}catch{}}},h),k.unref?.()};return{id:o,keep:async(h,t)=>{t.length!==0&&(d.has(h)||(S??=(e.now?.()??new Date).toISOString(),d.set(h,0),R(!0),await e.files.begin(o,h)),await e.files.append(o,h,t),d.set(h,(d.get(h)??0)+t.length),z())},close:()=>{E=!0,k!==void 0&&clearTimeout(k),k=void 0,R(!1)}}}var F=200,de=["LastModifiedDate","LastModifiedById"],ee=100,te=4e3,ae=20,ne=255;function ce(e=ne){return 2*Math.max(0,e)+2}function ke(e,o){let d=o===void 0||o.creatable.size+4>ee;if(e.toLowerCase()==="id")return{characters:ae,wide:d};let a=o?.fields?.find(g=>g.name.toLowerCase()===e.toLowerCase());return a&&["double","int","long","currency","percent"].includes(a.type??"")?{characters:(a.precision??a.digits??18)+2,wide:d}:{characters:ce(a?.length??ne),wide:d}}function fe(e){let o=e.wide?F/4:F,d=Math.floor((te+2)/(Math.max(1,e.characters)+2));return Math.max(1,Math.min(o,d))}function me(e,o){let d=fe(o),a=e.reduce((g,S)=>g+Math.ceil(Math.max(0,S)/d),0);return a>0?a+1:0}function u(e){return e.slice(0,15)}function U(e,o){if(typeof e=="number"&&Number.isFinite(e))return`#${e}`;if(!(typeof e!="string"||e===""))return o?u(e):e.toLowerCase()}function ue(e){return typeof e=="number"?String(e):`'${j(String(e))}'`}function ge(e,o){let d=[],a=[],g=0;for(let S of e){let I=ue(S);a.length>0&&(a.length>=o||g+I.length>te)&&(d.push(a),a=[],g=0),a.push(I),g+=I.length+2}return a.length>0&&d.push(a),d}function le(e,o,d){return`What these ${o} ${e} record(s) would write over in the target could not be read and kept first (${J(d)}), so none of them was written: a run writes over nothing it cannot put back.`}function Se(e){let o=new Map,d=new Map,a=new Set,g=new Map,S=new Map,I=new Map,k=new Map,E=new Map,R=new Map,z=t=>{let l=e.describe,c=e.viewsEncrypted;if(!l||!c)return Promise.resolve(new Set);let y=I.get(t);return y||(y=l(t).then(async f=>{let m=(f.fields??[]).filter(M=>M.type===N).map(M=>M.name);return m.length>0&&!await c()?new Set(m):new Set},()=>new Set),I.set(t,y)),y},h=t=>{let l=e.describe;if(!l)return Promise.resolve(new Set);let c=S.get(t);return c||(c=l(t).then(y=>new Set((y.fields??[]).filter(f=>f.type==="base64"||f.queryable===!1).map(f=>f.name)),()=>new Set),S.set(t,c)),c};return{before:async(t,l,c,y)=>{if(g.delete(t),l!=="update"&&l!=="upsert"||c.length===0)return;let f=l==="update"?"Id":y??"Id",m=f==="Id";try{D(t),D(f);let M=await h(t),p=await z(t),v=new Set,O=new Set,T=new Map;for(let n of c){let i=U(n[f],m);i!==void 0&&!T.has(i)&&T.set(i,n[f]);for(let[r,s]of Object.entries(n))if(!(r==="Id"||r===f||r==="attributes")&&!M.has(r)&&!(typeof s=="object"&&s!==null)){if(p.has(r)){O.add(r);continue}v.add(D(r))}}if(T.size===0||v.size===0&&O.size===0)return;let x=["Id",...m?[]:[f],...v],V=[...x,...de.filter(n=>!x.includes(n))],re=V.length>ee?F/4:F,$=new Map,P=R.get(t)===!1?x:V;for(let n of ge([...T.values()],re)){let i=s=>`SELECT ${s.join(", ")} FROM ${t} WHERE ${f} IN (${n.join(", ")})`,r;try{r=await e.query(i(P))}catch(s){if(P===x)throw s;P=x,R.set(t,!1),r=await e.query(i(P))}for(let s of r){let w=U(m?s.Id:s[f],m);w===void 0||typeof s.Id!="string"||$.set(w,[...$.get(w)??[],s])}}let K=o.get(t)??new Map,_=[],B=new Map,C=new Map,G=new Map;for(let n of c){let i=U(n[f],m),r=i===void 0?void 0:$.get(i),s=r?.length===1?r[0]:void 0,w=s?.Id;if(_.push(w),!s||w===void 0||a.has(u(w)))continue;typeof s.LastModifiedDate=="string"&&G.set(u(w),{id:w,at:s.LastModifiedDate,...typeof s.LastModifiedById=="string"?{by:s.LastModifiedById}:{}});let ie=K.get(u(w)),q=B.get(u(w))??{Id:w},Q=C.get(u(w))??new Set;for(let b of Object.keys(n))!v.has(b)||ie?.has(b)||b in q||(q[b]=s[b]??null,Q.add(b));Q.size!==0&&(B.set(u(w),q),C.set(u(w),Q))}if(O.size>0&&_.some(n=>n!==void 0&&!a.has(u(n)))){let n=k.get(t)??new Set,i=[...O].filter(r=>!n.has(r));if(i.length>0){for(let r of i)n.add(r);k.set(t,n),e.recorder.unkept?.(t,i)}}if(B.size===0){g.set(t,{reaches:_,named:[],added:new Map});return}let X=[...B.values()],L=d.get(t)??new Map,Y=X.flatMap(n=>{let i=L.get(u(n.Id)),r=Object.entries(n).filter(([s])=>s==="Id"||!i?.has(s));return r.length>1?[Object.fromEntries(r)]:[]});Y.length>0&&await e.backup.keep(t,Y);for(let n of Y){let i=L.get(u(n.Id))??new Set;for(let r of Object.keys(n))r!=="Id"&&i.add(r);L.set(u(n.Id),i)}d.set(t,L);let A=X.map(n=>n.Id),W=E.get(t)??new Set,H=[];for(let n of A){let i=u(n);if(W.has(i))continue;W.add(i);let r=G.get(i);r&&H.push(r)}E.set(t,W),H.length>0?e.recorder.overwriting?.(t,e.backup.id,A,H):e.recorder.overwriting?.(t,e.backup.id,A);let Z=await e.recorder.flush();if(Z!==void 0)throw new Error(`the run's file could not be written: ${Z}`);for(let[n,i]of C){let r=K.get(n)??new Set;for(let s of i)r.add(s);K.set(n,r)}o.set(t,K),g.set(t,{reaches:_,named:A,added:C});return}catch(M){return le(t,c.length,M)}},answered:(t,l,c)=>{if(l==="insert"||l==="upsert")for(let p of c)p.success&&typeof p.id=="string"&&p.id!==""&&(l==="insert"||p.created===!0)&&a.add(u(p.id));let y=g.get(t);if(g.delete(t),!y||y.named.length===0)return;let f=new Set;c.forEach((p,v)=>{let O=y.reaches[v];O!==void 0&&p.success&&p.created!==!0&&f.add(u(O))});let m=y.named.filter(p=>!f.has(u(p))),M=o.get(t);for(let p of m){let v=M?.get(u(p));for(let O of y.added.get(u(p))??[])v?.delete(O)}e.recorder.overwrote?.(t,m)}}}export{se as a,he as b,ae as c,ce as d,ke as e,me as f,Se as g};
7
+ import{a as N}from"./chunk-EOQON3E5.mjs";import{a as j,h as D}from"./chunk-TZE3Y7IQ.mjs";import{b as J}from"./chunk-CA5NAXSU.mjs";function se(e){return`sync-before-${e.replace(/[^A-Za-z0-9-]+/g,"-")}`.slice(0,200)}var oe=1e3;function he(e){let o=se(e.runId),d=new Map,a=e.everyMs??oe,g=()=>(e.now?.()??new Date).getTime(),S,I=Number.NEGATIVE_INFINITY,k,E=!1,R=h=>{if(S===void 0)return;let t=[...d].map(([l,c])=>({objectApiName:l,recordCount:c,truncated:!1}));e.meta.set(`backup:${o}`,{operationId:o,orgId:e.orgId,...e.organizationId!==void 0?{organizationId:e.organizationId}:{},objects:t,partial:h,timestamp:S,totalRecords:t.reduce((l,c)=>l+c.recordCount,0),origin:"sync",runId:e.runId},"backups")},z=()=>{if(E)return;let h=I+a-g();if(h<=0){k!==void 0&&clearTimeout(k),k=void 0,I=g(),R(!0);return}k??=setTimeout(()=>{if(k=void 0,!E){I=g();try{R(!0)}catch{}}},h),k.unref?.()};return{id:o,keep:async(h,t)=>{t.length!==0&&(d.has(h)||(S??=(e.now?.()??new Date).toISOString(),d.set(h,0),R(!0),await e.files.begin(o,h)),await e.files.append(o,h,t),d.set(h,(d.get(h)??0)+t.length),z())},close:()=>{E=!0,k!==void 0&&clearTimeout(k),k=void 0,R(!1)}}}var F=200,de=["LastModifiedDate","LastModifiedById"],ee=100,te=4e3,ae=20,ne=255;function ce(e=ne){return 2*Math.max(0,e)+2}function ke(e,o){let d=o===void 0||o.creatable.size+4>ee;if(e.toLowerCase()==="id")return{characters:ae,wide:d};let a=o?.fields?.find(g=>g.name.toLowerCase()===e.toLowerCase());return a&&["double","int","long","currency","percent"].includes(a.type??"")?{characters:(a.precision??a.digits??18)+2,wide:d}:{characters:ce(a?.length??ne),wide:d}}function fe(e){let o=e.wide?F/4:F,d=Math.floor((te+2)/(Math.max(1,e.characters)+2));return Math.max(1,Math.min(o,d))}function me(e,o){let d=fe(o),a=e.reduce((g,S)=>g+Math.ceil(Math.max(0,S)/d),0);return a>0?a+1:0}function u(e){return e.slice(0,15)}function U(e,o){if(typeof e=="number"&&Number.isFinite(e))return`#${e}`;if(!(typeof e!="string"||e===""))return o?u(e):e.toLowerCase()}function ue(e){return typeof e=="number"?String(e):`'${j(String(e))}'`}function ge(e,o){let d=[],a=[],g=0;for(let S of e){let I=ue(S);a.length>0&&(a.length>=o||g+I.length>te)&&(d.push(a),a=[],g=0),a.push(I),g+=I.length+2}return a.length>0&&d.push(a),d}function le(e,o,d){return`What these ${o} ${e} record(s) would write over in the target could not be read and kept first (${J(d)}), so none of them was written: a run writes over nothing it cannot put back.`}function Se(e){let o=new Map,d=new Map,a=new Set,g=new Map,S=new Map,I=new Map,k=new Map,E=new Map,R=new Map,z=t=>{let l=e.describe,c=e.viewsEncrypted;if(!l||!c)return Promise.resolve(new Set);let y=I.get(t);return y||(y=l(t).then(async f=>{let m=(f.fields??[]).filter(M=>M.type===N).map(M=>M.name);return m.length>0&&!await c()?new Set(m):new Set},()=>new Set),I.set(t,y)),y},h=t=>{let l=e.describe;if(!l)return Promise.resolve(new Set);let c=S.get(t);return c||(c=l(t).then(y=>new Set((y.fields??[]).filter(f=>f.type==="base64"||f.queryable===!1).map(f=>f.name)),()=>new Set),S.set(t,c)),c};return{before:async(t,l,c,y)=>{if(g.delete(t),l!=="update"&&l!=="upsert"||c.length===0)return;let f=l==="update"?"Id":y??"Id",m=f==="Id";try{D(t),D(f);let M=await h(t),p=await z(t),v=new Set,O=new Set,T=new Map;for(let n of c){let i=U(n[f],m);i!==void 0&&!T.has(i)&&T.set(i,n[f]);for(let[r,s]of Object.entries(n))if(!(r==="Id"||r===f||r==="attributes")&&!M.has(r)&&!(typeof s=="object"&&s!==null)){if(p.has(r)){O.add(r);continue}v.add(D(r))}}if(T.size===0||v.size===0&&O.size===0)return;let x=["Id",...m?[]:[f],...v],V=[...x,...de.filter(n=>!x.includes(n))],re=V.length>ee?F/4:F,$=new Map,P=R.get(t)===!1?x:V;for(let n of ge([...T.values()],re)){let i=s=>`SELECT ${s.join(", ")} FROM ${t} WHERE ${f} IN (${n.join(", ")})`,r;try{r=await e.query(i(P))}catch(s){if(P===x)throw s;P=x,R.set(t,!1),r=await e.query(i(P))}for(let s of r){let w=U(m?s.Id:s[f],m);w===void 0||typeof s.Id!="string"||$.set(w,[...$.get(w)??[],s])}}let K=o.get(t)??new Map,_=[],B=new Map,C=new Map,G=new Map;for(let n of c){let i=U(n[f],m),r=i===void 0?void 0:$.get(i),s=r?.length===1?r[0]:void 0,w=s?.Id;if(_.push(w),!s||w===void 0||a.has(u(w)))continue;typeof s.LastModifiedDate=="string"&&G.set(u(w),{id:w,at:s.LastModifiedDate,...typeof s.LastModifiedById=="string"?{by:s.LastModifiedById}:{}});let ie=K.get(u(w)),q=B.get(u(w))??{Id:w},Q=C.get(u(w))??new Set;for(let b of Object.keys(n))!v.has(b)||ie?.has(b)||b in q||(q[b]=s[b]??null,Q.add(b));Q.size!==0&&(B.set(u(w),q),C.set(u(w),Q))}if(O.size>0&&_.some(n=>n!==void 0&&!a.has(u(n)))){let n=k.get(t)??new Set,i=[...O].filter(r=>!n.has(r));if(i.length>0){for(let r of i)n.add(r);k.set(t,n),e.recorder.unkept?.(t,i)}}if(B.size===0){g.set(t,{reaches:_,named:[],added:new Map});return}let X=[...B.values()],L=d.get(t)??new Map,Y=X.flatMap(n=>{let i=L.get(u(n.Id)),r=Object.entries(n).filter(([s])=>s==="Id"||!i?.has(s));return r.length>1?[Object.fromEntries(r)]:[]});Y.length>0&&await e.backup.keep(t,Y);for(let n of Y){let i=L.get(u(n.Id))??new Set;for(let r of Object.keys(n))r!=="Id"&&i.add(r);L.set(u(n.Id),i)}d.set(t,L);let A=X.map(n=>n.Id),W=E.get(t)??new Set,H=[];for(let n of A){let i=u(n);if(W.has(i))continue;W.add(i);let r=G.get(i);r&&H.push(r)}E.set(t,W),H.length>0?e.recorder.overwriting?.(t,e.backup.id,A,H):e.recorder.overwriting?.(t,e.backup.id,A);let Z=await e.recorder.flush();if(Z!==void 0)throw new Error(`the run's file could not be written: ${Z}`);for(let[n,i]of C){let r=K.get(n)??new Set;for(let s of i)r.add(s);K.set(n,r)}o.set(t,K),g.set(t,{reaches:_,named:A,added:C});return}catch(M){return le(t,c.length,M)}},answered:(t,l,c)=>{if(l==="insert"||l==="upsert")for(let p of c)p.success&&typeof p.id=="string"&&p.id!==""&&(l==="insert"||p.created===!0)&&a.add(u(p.id));let y=g.get(t);if(g.delete(t),!y||y.named.length===0)return;let f=new Set;c.forEach((p,v)=>{let O=y.reaches[v];O!==void 0&&p.success&&p.created!==!0&&f.add(u(O))});let m=y.named.filter(p=>!f.has(u(p))),M=o.get(t);for(let p of m){let v=M?.get(u(p));for(let O of y.added.get(u(p))??[])v?.delete(O)}e.recorder.overwrote?.(t,m)}}}export{se as a,he as b,ae as c,ce as d,ke as e,me as f,Se as g};