sandforge 1.83.0 → 1.84.1

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 (254) hide show
  1. package/README.md +1 -1
  2. package/lib/chunk-23SEDORH.mjs +11 -0
  3. package/lib/{chunk-I5C4O3VA.mjs → chunk-24RFOFYT.mjs} +1 -1
  4. package/lib/chunk-26POJDIT.mjs +7 -0
  5. package/lib/{chunk-WJAZ5LHL.mjs → chunk-2AZQHBEF.mjs} +1 -1
  6. package/lib/{chunk-IHGYJZZ2.mjs → chunk-2HVOZUM4.mjs} +1 -1
  7. package/lib/{chunk-3V4YH5KO.mjs → chunk-2JDAOWUW.mjs} +1 -1
  8. package/lib/{chunk-BNKT3R3F.mjs → chunk-2METQHGG.mjs} +1 -1
  9. package/lib/chunk-2WFIVO4F.mjs +13 -0
  10. package/lib/chunk-2YHZBUZE.mjs +7 -0
  11. package/lib/{chunk-7DPHZWA4.mjs → chunk-326AJTIU.mjs} +14 -14
  12. package/lib/{chunk-UIR77ZJD.mjs → chunk-36JOHEJL.mjs} +1 -1
  13. package/lib/chunk-3PVRGTVK.mjs +7 -0
  14. package/lib/{chunk-2WMKJVD2.mjs → chunk-3Q353S2R.mjs} +1 -1
  15. package/lib/chunk-3TZSBHEY.mjs +7 -0
  16. package/lib/{chunk-T36DZJPH.mjs → chunk-43TOMFV4.mjs} +1 -1
  17. package/lib/{chunk-XAMMIPZ4.mjs → chunk-4CVUUVGJ.mjs} +1 -1
  18. package/lib/{chunk-6YC2ELCU.mjs → chunk-4EOHEDFP.mjs} +1 -1
  19. package/lib/{chunk-ZB5E7NHU.mjs → chunk-4JE4BYXK.mjs} +1 -1
  20. package/lib/{chunk-JREKJO3D.mjs → chunk-54WZUS7J.mjs} +1 -1
  21. package/lib/{chunk-CGZGL6VT.mjs → chunk-5CRLRHOJ.mjs} +1 -1
  22. package/lib/{chunk-UOHZW2L4.mjs → chunk-5IZTFMJM.mjs} +1 -1
  23. package/lib/{chunk-6VOQFISN.mjs → chunk-5M5FQ7RP.mjs} +1 -1
  24. package/lib/{chunk-U4YFYSF3.mjs → chunk-5SMWFNE7.mjs} +1 -1
  25. package/lib/{chunk-HQZUQXDC.mjs → chunk-5XTUSN72.mjs} +1 -1
  26. package/lib/chunk-6I6TWNV5.mjs +7 -0
  27. package/lib/{chunk-QLRWU3MB.mjs → chunk-6JWWSDM6.mjs} +1 -1
  28. package/lib/chunk-6O222PW6.mjs +7 -0
  29. package/lib/{chunk-J3TIHLWG.mjs → chunk-6PD6K7LP.mjs} +1 -1
  30. package/lib/{chunk-ISAUCWYK.mjs → chunk-6QE6R6RL.mjs} +1 -1
  31. package/lib/{chunk-2KTGDYUH.mjs → chunk-6WX5ZU7Q.mjs} +1 -1
  32. package/lib/{chunk-XAUQXYPW.mjs → chunk-6YL7BNYD.mjs} +1 -1
  33. package/lib/chunk-6ZLKIT3H.mjs +7 -0
  34. package/lib/{chunk-XKFHTBAB.mjs → chunk-7QYHEHMA.mjs} +1 -1
  35. package/lib/chunk-7SQSWVAU.mjs +9 -0
  36. package/lib/{chunk-NNV7IGM7.mjs → chunk-7UVKIWKV.mjs} +1 -1
  37. package/lib/{chunk-RZKJQOOC.mjs → chunk-7WATA4SB.mjs} +1 -1
  38. package/lib/{chunk-DMT5SCO3.mjs → chunk-7YNM6KFZ.mjs} +1 -1
  39. package/lib/{chunk-TMIESDE5.mjs → chunk-A3MYSOOC.mjs} +1 -1
  40. package/lib/chunk-AL4C3GFT.mjs +7 -0
  41. package/lib/chunk-B3FBHVNN.mjs +21 -0
  42. package/lib/{chunk-CDWZGQAJ.mjs → chunk-B63POIPQ.mjs} +1 -1
  43. package/lib/{chunk-YEVB7LVK.mjs → chunk-BAWCOKRW.mjs} +1 -1
  44. package/lib/{chunk-FVLFO2S6.mjs → chunk-BBRWFKS5.mjs} +1 -1
  45. package/lib/chunk-BEA27DLS.mjs +7 -0
  46. package/lib/chunk-BRY3PLIZ.mjs +7 -0
  47. package/lib/chunk-CBH3TOWK.mjs +341 -0
  48. package/lib/{chunk-7V2UYZ6S.mjs → chunk-CPQIZGG5.mjs} +1 -1
  49. package/lib/chunk-CVHNXJH3.mjs +7 -0
  50. package/lib/{chunk-ZOSESZ22.mjs → chunk-D4GF4FAB.mjs} +1 -1
  51. package/lib/chunk-DGDRQRCW.mjs +7 -0
  52. package/lib/{chunk-2N73W63D.mjs → chunk-DPMRIMUC.mjs} +1 -1
  53. package/lib/chunk-DUN2EPRC.mjs +7 -0
  54. package/lib/chunk-E3A3LOCY.mjs +7 -0
  55. package/lib/{chunk-KWAVSZ2B.mjs → chunk-EAC5QCE3.mjs} +1 -1
  56. package/lib/{chunk-JUOQUG7U.mjs → chunk-EC72TIEG.mjs} +1 -1
  57. package/lib/chunk-EPFCERGL.mjs +7 -0
  58. package/lib/{chunk-6KOUYHEY.mjs → chunk-ETDCBLGU.mjs} +1 -1
  59. package/lib/{chunk-2R6GFNKF.mjs → chunk-F3AQW6IU.mjs} +1 -1
  60. package/lib/{chunk-AHUGG3WU.mjs → chunk-FITPY3L4.mjs} +1 -1
  61. package/lib/chunk-FNJ4SGWO.mjs +7 -0
  62. package/lib/{chunk-EOQON3E5.mjs → chunk-FP7CYB2F.mjs} +1 -1
  63. package/lib/{chunk-262TP6UU.mjs → chunk-GKY2JMHY.mjs} +1 -1
  64. package/lib/{chunk-JBWJ6UEZ.mjs → chunk-GMIGWR6U.mjs} +1 -1
  65. package/lib/{chunk-OS5GE52G.mjs → chunk-GNRSF65U.mjs} +1 -1
  66. package/lib/chunk-GOOVPVWX.mjs +7 -0
  67. package/lib/{chunk-DB5RVDC5.mjs → chunk-GWZRR3MM.mjs} +1 -1
  68. package/lib/{chunk-SX6QWYCQ.mjs → chunk-H2BHESDA.mjs} +2 -2
  69. package/lib/chunk-H4CGM6YO.mjs +7 -0
  70. package/lib/{chunk-NFEBX75O.mjs → chunk-HCGXK7G7.mjs} +1 -1
  71. package/lib/{chunk-4X5D3MSV.mjs → chunk-HIDW7FNV.mjs} +1 -1
  72. package/lib/chunk-HSBXRQTI.mjs +7 -0
  73. package/lib/chunk-HUZPBE47.mjs +7 -0
  74. package/lib/{chunk-F5SBGJWW.mjs → chunk-HV7VPEXP.mjs} +1 -1
  75. package/lib/chunk-I6E6T6YY.mjs +7 -0
  76. package/lib/chunk-IUM4NFKI.mjs +10 -0
  77. package/lib/chunk-IVFVNNGB.mjs +37 -0
  78. package/lib/{chunk-L4MSL4U7.mjs → chunk-IZGCEOYO.mjs} +1 -1
  79. package/lib/{chunk-E3RQ575Y.mjs → chunk-J3DND3BC.mjs} +1 -1
  80. package/lib/{chunk-MJD6CPZZ.mjs → chunk-JAEDM4SI.mjs} +1 -1
  81. package/lib/chunk-JCFBFF4Y.mjs +7 -0
  82. package/lib/{chunk-U2CTKIPE.mjs → chunk-JE6SCT6R.mjs} +1 -1
  83. package/lib/{chunk-XJICAOAQ.mjs → chunk-JGZPD4IM.mjs} +1 -1
  84. package/lib/{chunk-XCJUNX63.mjs → chunk-JKJ74BX5.mjs} +1 -1
  85. package/lib/{chunk-WAYQLQAD.mjs → chunk-JLSIWO4Z.mjs} +1 -1
  86. package/lib/{chunk-D7XUNWWU.mjs → chunk-JSAJS3MY.mjs} +1 -1
  87. package/lib/chunk-JTJK2D36.mjs +7 -0
  88. package/lib/{chunk-OTJH6AEA.mjs → chunk-KAZS5Z6W.mjs} +1 -1
  89. package/lib/chunk-KB4ZHM4Q.mjs +10 -0
  90. package/lib/{chunk-N2HYG3BL.mjs → chunk-KGU4SVIT.mjs} +1 -1
  91. package/lib/{chunk-FKCIGJOI.mjs → chunk-KJWFYBMU.mjs} +2 -2
  92. package/lib/{chunk-KXUOHACP.mjs → chunk-KZTZDC7H.mjs} +1 -1
  93. package/lib/{chunk-S4PRKKGC.mjs → chunk-L2E5WBGD.mjs} +1 -1
  94. package/lib/{chunk-X2XZQ434.mjs → chunk-L53JWJ3S.mjs} +1 -1
  95. package/lib/{chunk-CQAFVEKP.mjs → chunk-LA4KIATH.mjs} +6 -6
  96. package/lib/chunk-LC3NDW4N.mjs +7 -0
  97. package/lib/{chunk-4V3QO7HF.mjs → chunk-LKTNQEBS.mjs} +1 -1
  98. package/lib/chunk-M2ABR4JM.mjs +7 -0
  99. package/lib/{chunk-3CM7LAPE.mjs → chunk-M4BLK6HJ.mjs} +1 -1
  100. package/lib/{chunk-Z3MGN42K.mjs → chunk-M6K34KGF.mjs} +1 -1
  101. package/lib/{chunk-TUPZY2QJ.mjs → chunk-MDMPJEV3.mjs} +1 -1
  102. package/lib/{chunk-BVZ5H3N4.mjs → chunk-MJZU3U5O.mjs} +68 -63
  103. package/lib/{chunk-OUU47Y7A.mjs → chunk-MSIEU5MR.mjs} +1 -1
  104. package/lib/{chunk-QQDZQCO2.mjs → chunk-N4WPCWJO.mjs} +1 -1
  105. package/lib/{chunk-MTM4KG3T.mjs → chunk-NCZKWSC7.mjs} +1 -1
  106. package/lib/{chunk-Y7YUNRKK.mjs → chunk-NED4MBIM.mjs} +1 -1
  107. package/lib/{chunk-QKJXIY6L.mjs → chunk-NOBQTEQD.mjs} +1 -1
  108. package/lib/{chunk-WBELLGNE.mjs → chunk-NSQWI7ZY.mjs} +1 -1
  109. package/lib/{chunk-BPHTA6KP.mjs → chunk-O677VOGO.mjs} +1 -1
  110. package/lib/chunk-OFTT7J2M.mjs +7 -0
  111. package/lib/{chunk-JH4ZTVQN.mjs → chunk-OLCVHL7I.mjs} +1 -1
  112. package/lib/chunk-OM5NORJG.mjs +7 -0
  113. package/lib/{chunk-QP3JLFIO.mjs → chunk-OMNMLKDT.mjs} +1 -1
  114. package/lib/{chunk-WABXKL4N.mjs → chunk-OPMO6I45.mjs} +1 -1
  115. package/lib/{chunk-7ZBDACVG.mjs → chunk-OUZQPYT3.mjs} +1 -1
  116. package/lib/chunk-OVNMB6Q2.mjs +7 -0
  117. package/lib/{chunk-DKDKCGXV.mjs → chunk-PAXNWTYK.mjs} +1 -1
  118. package/lib/{chunk-GLN4PI5P.mjs → chunk-PBY2O6OF.mjs} +1 -1
  119. package/lib/chunk-PEDQPM2P.mjs +926 -0
  120. package/lib/chunk-PH7SP4YK.mjs +21 -0
  121. package/lib/{chunk-BT43WSOS.mjs → chunk-PMN4PAC3.mjs} +1 -1
  122. package/lib/chunk-PMWAFDUB.mjs +48 -0
  123. package/lib/chunk-PPLVFX6N.mjs +7 -0
  124. package/lib/{chunk-L3I6DAHX.mjs → chunk-PR3XCSPO.mjs} +1 -1
  125. package/lib/{chunk-WZN36ACK.mjs → chunk-PR42EZSR.mjs} +1 -1
  126. package/lib/{chunk-NDFFIJL5.mjs → chunk-PWRJRL5U.mjs} +1 -1
  127. package/lib/{chunk-NS6ONPWL.mjs → chunk-Q7GIJBCD.mjs} +1 -1
  128. package/lib/chunk-Q7TLC3I2.mjs +7 -0
  129. package/lib/{chunk-ALBY5SOH.mjs → chunk-QAFPQ3YB.mjs} +1 -1
  130. package/lib/{chunk-KKS2KFBT.mjs → chunk-QKEKG2LD.mjs} +1 -1
  131. package/lib/{chunk-OOIDCHBQ.mjs → chunk-QO53K5W2.mjs} +2 -2
  132. package/lib/{chunk-HVX2AFYW.mjs → chunk-QTG6LUZT.mjs} +1 -1
  133. package/lib/{chunk-K7G3W7XH.mjs → chunk-RE7RYF3B.mjs} +1 -1
  134. package/lib/{chunk-JIPT5FUD.mjs → chunk-RGBGUCJA.mjs} +1 -1
  135. package/lib/{chunk-GT5ZKU6V.mjs → chunk-RGUQOSBU.mjs} +1 -1
  136. package/lib/{chunk-VXZ5PTOM.mjs → chunk-RHNTHGNU.mjs} +1 -1
  137. package/lib/chunk-RKTFFCNS.mjs +7 -0
  138. package/lib/chunk-RMFU4BAL.mjs +28 -0
  139. package/lib/{chunk-DNQKVCUV.mjs → chunk-ROV3QXEF.mjs} +11 -11
  140. package/lib/chunk-RT47RKLY.mjs +7 -0
  141. package/lib/{chunk-ISOSTAJR.mjs → chunk-S42RBRH2.mjs} +1 -1
  142. package/lib/{chunk-27BBEGUD.mjs → chunk-SI267LYR.mjs} +1 -1
  143. package/lib/chunk-T3G6VZNS.mjs +7 -0
  144. package/lib/chunk-TNT27RBG.mjs +7 -0
  145. package/lib/chunk-UBIKR5VO.mjs +7 -0
  146. package/lib/chunk-UI3JQVRU.mjs +8 -0
  147. package/lib/{chunk-RVCPQVKM.mjs → chunk-UIOMAX56.mjs} +1 -1
  148. package/lib/chunk-UX3BVH2Y.mjs +7 -0
  149. package/lib/{chunk-L4RJX7DG.mjs → chunk-VCUXCK36.mjs} +1 -1
  150. package/lib/chunk-VINGECAJ.mjs +10 -0
  151. package/lib/chunk-VOXJHJIE.mjs +7 -0
  152. package/lib/chunk-W6PN6TJG.mjs +7 -0
  153. package/lib/{chunk-D6JT4PAB.mjs → chunk-WAPSSYMT.mjs} +1 -1
  154. package/lib/{chunk-7BQMBXKX.mjs → chunk-WUUKFE2U.mjs} +1 -1
  155. package/lib/chunk-WWTCWWZI.mjs +7 -0
  156. package/lib/chunk-WXDLQT2O.mjs +10 -0
  157. package/lib/{chunk-TCEXCHXR.mjs → chunk-WY5V5PR3.mjs} +1 -1
  158. package/lib/chunk-X4BXESMQ.mjs +7 -0
  159. package/lib/chunk-XBQGZGWR.mjs +7 -0
  160. package/lib/{chunk-AXFD2OH6.mjs → chunk-XGGOUNPP.mjs} +1 -1
  161. package/lib/chunk-XKWW3GKF.mjs +7 -0
  162. package/lib/{chunk-PDRXM5WN.mjs → chunk-Y2DRK37K.mjs} +1 -1
  163. package/lib/{chunk-ZXOUWHYE.mjs → chunk-YA6ATMTB.mjs} +1 -1
  164. package/lib/{chunk-54HYHHVL.mjs → chunk-YDXMTWAT.mjs} +1 -1
  165. package/lib/chunk-YHR4WQPR.mjs +7 -0
  166. package/lib/{chunk-LWES2KZE.mjs → chunk-YTLUYSMF.mjs} +1 -1
  167. package/lib/{chunk-2K5BYZQM.mjs → chunk-YWEQQL3C.mjs} +1 -1
  168. package/lib/{chunk-C6RKM4BB.mjs → chunk-Z4LKKOFY.mjs} +1 -1
  169. package/lib/chunk-ZBAWJUG2.mjs +7 -0
  170. package/lib/{chunk-446GBKAC.mjs → chunk-ZJW6YOMV.mjs} +1 -1
  171. package/lib/chunk-ZQQXSCVI.mjs +7 -0
  172. package/lib/{chunk-L6CLN664.mjs → chunk-ZQWIVYVM.mjs} +1 -1
  173. package/lib/{chunk-CXKZ6TYV.mjs → chunk-ZV7ZFQQC.mjs} +1 -1
  174. package/lib/sandforge-autopilot.mjs +25 -25
  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 +52 -21
  180. package/lib/sandforge-dataops.mjs +1 -1
  181. package/lib/sandforge-empty.mjs +1 -1
  182. package/lib/sandforge-env.mjs +95 -95
  183. package/lib/sandforge-frozen.mjs +1 -1
  184. package/lib/sandforge-mcp.mjs +12 -12
  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 +1 -1
  190. package/lib/sandforge.mjs +1 -1
  191. package/lib/sf/sandforge/compare.mjs +2 -2
  192. package/lib/sfPlugin.mjs +1 -1
  193. package/oclif.manifest.json +1 -1
  194. package/package.json +1 -1
  195. package/lib/chunk-2ADSD5WK.mjs +0 -7
  196. package/lib/chunk-2GSMHGIV.mjs +0 -7
  197. package/lib/chunk-36Y225OM.mjs +0 -7
  198. package/lib/chunk-3OVTKRS4.mjs +0 -7
  199. package/lib/chunk-4GCYGQXD.mjs +0 -7
  200. package/lib/chunk-4JKR4PTZ.mjs +0 -8
  201. package/lib/chunk-5OGNK3JP.mjs +0 -37
  202. package/lib/chunk-6QSHWIZI.mjs +0 -48
  203. package/lib/chunk-77IVKH7R.mjs +0 -7
  204. package/lib/chunk-77MZRBWX.mjs +0 -7
  205. package/lib/chunk-7WSQ65WG.mjs +0 -9
  206. package/lib/chunk-A32ISQ6M.mjs +0 -28
  207. package/lib/chunk-AG24QMSY.mjs +0 -7
  208. package/lib/chunk-BH76USTQ.mjs +0 -11
  209. package/lib/chunk-BZ24IAP5.mjs +0 -7
  210. package/lib/chunk-CN5HGFG4.mjs +0 -7
  211. package/lib/chunk-CTPLYUXA.mjs +0 -7
  212. package/lib/chunk-DIGUC7S4.mjs +0 -341
  213. package/lib/chunk-DSR2MSBH.mjs +0 -7
  214. package/lib/chunk-ETNQHIDI.mjs +0 -9
  215. package/lib/chunk-FBXH4VRQ.mjs +0 -7
  216. package/lib/chunk-FYWNSMOZ.mjs +0 -10
  217. package/lib/chunk-GEEWPTV5.mjs +0 -7
  218. package/lib/chunk-GTRU5AV5.mjs +0 -7
  219. package/lib/chunk-I3ZO76LL.mjs +0 -21
  220. package/lib/chunk-ISA2NYJV.mjs +0 -7
  221. package/lib/chunk-IXIY6Q4M.mjs +0 -7
  222. package/lib/chunk-JAV6F6OA.mjs +0 -7
  223. package/lib/chunk-JYUMD357.mjs +0 -7
  224. package/lib/chunk-L47JCNP3.mjs +0 -7
  225. package/lib/chunk-LI2XNV7F.mjs +0 -7
  226. package/lib/chunk-LP2D3JJP.mjs +0 -7
  227. package/lib/chunk-LYOGCIYD.mjs +0 -925
  228. package/lib/chunk-N5UIE4IR.mjs +0 -7
  229. package/lib/chunk-O7GCCRPW.mjs +0 -7
  230. package/lib/chunk-OO24ZYYJ.mjs +0 -7
  231. package/lib/chunk-OS6HFJ7L.mjs +0 -7
  232. package/lib/chunk-P6WRYJN3.mjs +0 -7
  233. package/lib/chunk-PGRY365W.mjs +0 -7
  234. package/lib/chunk-PPGDAUEQ.mjs +0 -7
  235. package/lib/chunk-Q4PPI3KG.mjs +0 -7
  236. package/lib/chunk-QFTF2PGS.mjs +0 -21
  237. package/lib/chunk-QO4MPHZD.mjs +0 -7
  238. package/lib/chunk-QXB6U3ZP.mjs +0 -7
  239. package/lib/chunk-R3OM3X4L.mjs +0 -8
  240. package/lib/chunk-R7GKMAT4.mjs +0 -7
  241. package/lib/chunk-SCKUIE3R.mjs +0 -7
  242. package/lib/chunk-SU65Z2BA.mjs +0 -7
  243. package/lib/chunk-T7DDS4UQ.mjs +0 -7
  244. package/lib/chunk-TQJ5NPRC.mjs +0 -7
  245. package/lib/chunk-VZLJZEV2.mjs +0 -7
  246. package/lib/chunk-W3BQGMTR.mjs +0 -7
  247. package/lib/chunk-WXU6ZJIV.mjs +0 -7
  248. package/lib/chunk-X4HZD5U2.mjs +0 -7
  249. package/lib/chunk-X6XNTOGO.mjs +0 -7
  250. package/lib/chunk-XMQ5R6TC.mjs +0 -10
  251. package/lib/chunk-XPXEQKLR.mjs +0 -7
  252. package/lib/chunk-YBZIDW6W.mjs +0 -7
  253. package/lib/chunk-ZCOSME6P.mjs +0 -7
  254. package/lib/chunk-ZTHC42X6.mjs +0 -7
@@ -1,925 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{b as _a,c as Jf,d as Qf}from"./chunk-P6WRYJN3.mjs";import{b as Zp}from"./chunk-77MZRBWX.mjs";import{d as ca,k as Vl,o as Jl,q as ua,r as Ql}from"./chunk-X4HZD5U2.mjs";import{a as Pt,d as Ba,e as Kt,f as An,i as ws,j as St,k as at}from"./chunk-BNKT3R3F.mjs";import{a as Lf}from"./chunk-QROPNEGY.mjs";import{b as vr,e as Jn}from"./chunk-BZ24IAP5.mjs";import{a as qt}from"./chunk-SCKUIE3R.mjs";import{a as yo,b as Ri,c as kt,d as Nn,e as Oi,f as nn,g as bo,h as ki,j as Si}from"./chunk-6FARZYMJ.mjs";import{$ as kp,A as Kf,Aa as Np,B as Vf,C as or,Ca as Cp,D as bs,Da as Mp,E as jn,Ea as Bp,F as Yf,G as Xf,H as Zf,I as qa,Ia as Lp,J as ep,Ja as Wp,K as tp,Ka as Xa,L as np,M as rp,Ma as Dp,N as op,O as Ua,Oa as _p,P as Rs,Pa as qp,Q as sp,Qa as Up,R as ip,Ra as Gp,S as ap,Sa as zp,T as gp,Ta as Za,U as mp,Ua as Hp,V as wp,Va as Kp,W as ir,Wa as ed,X as yp,Xa as Vp,Y as bp,Ya as Jp,Z as Rp,Za as Qp,_ as Op,_a as Yp,aa as Sp,ba as Tp,ca as za,cb as Xp,da as Ha,ea as ks,fa as Ap,ga as Ka,gb as eh,h as ps,ha as Lt,hb as Ss,ia as jp,ib as th,jb as td,ka as $p,kb as nd,lb as rd,m as La,ma as vp,mb as nh,n as Wf,na as Va,nb as rh,o as rr,p as We,pb as od,q as Df,qa as Ep,qb as sd,r as ys,ra as Ja,rb as oh,s as Wa,sa as Ip,sb as sh,t as Da,tb as ih,u as _f,ub as ah,v as qf,va as Qa,w as Uf,wa as xp,x as Gf,xa as Pp,y as zf,ya as Fp,z as Hf,za as Ya}from"./chunk-5OGNK3JP.mjs";import{a as _r,b as ms,c as Mf,d as Bf,e as Pa,f as Fa,g as Na,h as Ca,j as Ma}from"./chunk-QLRWU3MB.mjs";import{a as Hi,b as zu,c as Hu,d as Ku,f as Nr,g as Uo,h as Ki,n as tl}from"./chunk-XMQ5R6TC.mjs";import{B as Gi,G as _o,M as Yn,N as Gu,O as Fr,P as qo,a as ou,l as Ui}from"./chunk-IXIY6Q4M.mjs";import{f as $f,g as Ea,h as vf,i as xf,j as Pf,k as Ff,l as Nf,m as Cf,n as xa,o as nr}from"./chunk-TEIBWMJM.mjs";import{c as Ia,e as hs,f as Ef,g as If,h as gs}from"./chunk-BWWQXU2B.mjs";import{b as Xu,c as Zu,d as el}from"./chunk-T63U4OZJ.mjs";import{a as tf,e as nf,h as rf,j as of}from"./chunk-HQZUQXDC.mjs";import{a as zl}from"./chunk-NS6ONPWL.mjs";import{a as Ll,b as Dr,c as Wl,d as is,f as Dl,g as _l,h as aa,i as ql,j as Ul,k as Gl}from"./chunk-DSR2MSBH.mjs";import{a as nl}from"./chunk-YYZL7UGV.mjs";import{a as Mu,c as _i,g as Bu,h as Lu,i as Wu}from"./chunk-54HYHHVL.mjs";import{b as Hl,c as da,e as Kl}from"./chunk-M6P5ZZLE.mjs";import{h as Bl,i as ia,j as ss}from"./chunk-YBZIDW6W.mjs";import{h as Vi}from"./chunk-BT43WSOS.mjs";import{a as zi}from"./chunk-QSRAEUGZ.mjs";import{a as dp,b as Os,c as cp,d as Ga,e as sr,f as up,g as lp,h as fp,l as pp,m as hp}from"./chunk-SX6QWYCQ.mjs";import{c as Qu,d as Yu,h as al,j as dl}from"./chunk-EOQON3E5.mjs";import{b as zo,m as cl}from"./chunk-4JKR4PTZ.mjs";import{a as Ji,b as Cr,d as il,e as Go,g as Qi,h as Yi,j as Xn}from"./chunk-7WSQ65WG.mjs";import{d as kn}from"./chunk-MJD6CPZZ.mjs";import{a as zc,b as Fn,c as On}from"./chunk-7ZBDACVG.mjs";import{f as wo}from"./chunk-4GCYGQXD.mjs";import{b as rl,c as ol,g as sl}from"./chunk-WXU6ZJIV.mjs";import{$a as uf,$b as Sa,A as bl,Aa as Zl,Ab as mf,Ac as $a,B as Rl,Bc as va,D as ea,E as ta,Ea as ef,Eb as us,F as Ol,Fb as wf,G as kl,Ga as er,Gb as yf,H as Yo,Hb as bf,I as Xo,Ib as ls,J as Br,Jb as wa,K as Lr,L as Sl,M as Tl,Ma as df,N as Al,O as jl,P as Bn,Pb as ya,Rb as ba,Sb as Ra,Ua as as,Va as tr,Wb as Oa,Xb as ka,Yb as Rf,_a as cf,a as $o,bb as Tn,c as iu,cc as Of,d as Ci,da as Yl,dc as kf,e as Mi,eb as lf,f as au,fa as Xl,fb as ff,g as Bi,gc as Ht,h as Li,ha as la,i as ul,j as Ho,k as Zn,kc as Sf,l as ll,m as fl,mc as Tf,n as Ko,nc as fs,o as pl,p as Vo,q as Jo,qb as pf,r as hl,rb as hf,rc as Pe,s as Xi,sb as ha,sc as Ta,t as Zi,tb as ga,u as gl,ub as ds,uc as Aa,vb as ma,vc as ja,w as ml,wb as gf,x as wl,xc as Af,y as yl,yb as cs,z as Qo,zc as jf}from"./chunk-R3OM3X4L.mjs";import{c as Ni,e as su}from"./chunk-77IVKH7R.mjs";import{i as fa,q as pa,r as sf,s as af}from"./chunk-2WMKJVD2.mjs";import{a as Ye}from"./chunk-4TLYUZD5.mjs";import{a as na,b as Sn,c as $l,d as Zo,e as vl,f as Ke,g as El,h as Il,i as es,k as xl,l as Pl,m as Fl,n as ts,o as ra,p as Nl,q as zt,r as ns,s as on,t as oa,u as Cl,v as Wr,w as Ml,x as rs}from"./chunk-VXZ5PTOM.mjs";import{a as Pr,c as du,d as Wi,e as cu,f as uu,g as lu,h as fu,j as pu}from"./chunk-INIT2UKJ.mjs";import{a as Uc}from"./chunk-SU65Z2BA.mjs";import{a as os,b as sa}from"./chunk-HF6LAK3G.mjs";import{l as Uu}from"./chunk-ZOSESZ22.mjs";import{a as gu,b as mu,c as Mn,d as Eu,e as Iu,h as xu,i as Pu,j as Fu,k as Nu,l as Cu,m as Di}from"./chunk-ZXOUWHYE.mjs";import{b as Gc,d as Hc,h as dh}from"./chunk-LCDPCUXS.mjs";import{a as it,b as Mr}from"./chunk-TQ2TQHTT.mjs";import{b as Tu,c as Bo,d as Au,e as ju,f as $u,g as Lo,i as vu,l as Wo,m as Do}from"./chunk-HFSBDM7B.mjs";import{a as Co,b as Mo}from"./chunk-OHEOJISY.mjs";import{a as vo,c as hu}from"./chunk-EADHKH3A.mjs";import{a as Ao,b as jo,c as xr,e as ru}from"./chunk-Z3MGN42K.mjs";import{C as $i,D as So,E as Qn,F as ze,G as Le,H as vi,I as Ir,L as Ei,M as Ii,N as Zc,Q as xi,X as Pi,a as Cn,aa as Fi,b as $e,ba as eu,c as ut,da as tu,f as Kc,g as Vc,h as Jc,i as Qc,ja as nu,ka as To,m as Yc,n as Ti,o as Oo,p as Ai,q as Se,r as ce,s as Er,t as rn,u as ko,w as ji,z as Xc}from"./chunk-2GSMHGIV.mjs";import{a as Ro,h as Be}from"./chunk-TZE3Y7IQ.mjs";import{b as V}from"./chunk-CA5NAXSU.mjs";import{c as Du,f as _u,j as qi,k as qu}from"./chunk-ISOSTAJR.mjs";import{a as He,i as wu,j as yu,l as Eo,o as Io,p as bu,q as xo,r as Ru,s as Po,t as Ou,u as ku,v as Fo,w as Su,x as No}from"./chunk-ICIYL45C.mjs";import{a as Vu,d as Ju}from"./chunk-TUACWKIH.mjs";import{Ac as Tr,Cc as Ar,Da as xc,Ec as et,Fc as Ut,Gc as tn,Gd as $r,H as xn,Hc as mi,Hd as Wc,I as uo,Ic as gt,Jd as Dc,Kc as Fc,Lc as Pn,Mc as Hn,Nc as jr,Oc as Gt,P as Rc,Pc as mt,Pd as yi,Rc as wi,Sc as Nc,T as Oc,Ud as bi,Vc as Cc,W as lo,Wc as Mc,X as fo,Xd as _c,Y as li,Z as kr,_ as bn,ae as qc,ca as kc,da as Sc,ee as Vn,fd as Kn,fe as mo,ha as Tc,ia as Ac,id as ho,ja as jc,ka as $c,na as po,oa as fi,pa as pi,qa as vc,ra as hi,sa as Ec,ua as Rn,uc as Sr,ud as Bc,va as Ic,vd as Lc,wc as Pc,ya as gi,zc as Qe,zd as go}from"./chunk-6QSHWIZI.mjs";import{A as C}from"./chunk-WZQEK4WT.mjs";import{createHash as fy,randomUUID as Us}from"node:crypto";import{existsSync as Yt,readFileSync as pn,readdirSync as py,renameSync as Vg,rmSync as Ws,statSync as Jg,writeFileSync as Qg}from"node:fs";import{basename as rc,dirname as hy,join as Kd,resolve as Wt,sep as gy}from"node:path";import{createReadStream as Nm,existsSync as Cm}from"node:fs";import{createInterface as Mm}from"node:readline";var ch=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function Bm(r){let e=[],t=Mm({input:Nm(r,"utf8"),crlfDelay:1/0}),n=(o,s)=>{typeof s!="string"||!Number.isFinite(Date.parse(s))||(o.endedAt===void 0||Date.parse(s)>Date.parse(o.endedAt))&&(o.endedAt=s)};for await(let o of t){let s=e.at(-1);if(o.startsWith('{"part":')){try{let{part:f}=JSON.parse(o),p=typeof f?.startedAt=="string"?f.startedAt:void 0;e.push({...p?{startedAt:p}:{},wrote:[]})}catch{e.push({wrote:[]})}continue}if(!s)continue;if(o.startsWith('{"end":')){try{n(s,JSON.parse(o).end?.at)}catch{}continue}let i=cl(o);if(i){n(s,i.at),(s.jobEndedAt===void 0||Date.parse(i.orgAt)>Date.parse(s.jobEndedAt))&&(s.jobEndedAt=i.orgAt);continue}if(!o.startsWith('["x"')&&!o.startsWith('["p"')&&!o.startsWith('["g"'))continue;let a;try{a=JSON.parse(o)}catch{continue}if(!Array.isArray(a))continue;let[d,c,u,l]=a;d==="x"?n(s,l):d==="p"&&typeof c=="string"&&ch.test(c)?s.wrote.push(c):d==="g"&&typeof u=="string"&&ch.test(u)&&s.wrote.push(u)}return e}async function uh(r,e){if(!Cm(r))return[];let t;try{t=await Bm(r)}catch{return[]}let n=[];for(let[o,s]of t.entries()){let i=await e.readAt(r,o).catch(()=>{});if(!i)return[];n.push({part:o,created:i.created,linked:i.remap.linked.flatMap(a=>{let d=i.remap.table[a];return d!==void 0?[d]:[]}),wrote:s.wrote,...s.startedAt?{startedAt:s.startedAt}:{},...s.endedAt?{endedAt:s.endedAt}:{},...s.jobEndedAt?{jobEndedAt:s.jobEndedAt}:{}})}return n}function Ln(r){let e=Date.parse(r.endedAt??"");if(!Number.isFinite(e))return;let t=Date.parse(r.startedAt??""),n=Date.parse(r.jobEndedAt??"");return{runRecordedAt:new Date(e),runDurationMs:Number.isFinite(t)&&t<=e?e-t:0,endedByItsWrites:!0,...Number.isFinite(n)?{writtenUntil:new Date(n)}:{}}}function ar(r,e){return r.flatMap(t=>{if(t.part<=e||t.wrote.length===0&&t.linked.length===0)return[];let n=Ln(t);return n?[{span:{runRecordedAt:n.runRecordedAt,runDurationMs:n.runDurationMs},wrote:t.wrote,linked:t.linked}]:[]})}function Wn(r){return r.flatMap(e=>e.ids)}function sn(r,e){if(e===void 0)return r.map(n=>({...n,ids:[...n.ids]}));let t=new Set(e.map(n=>n.slice(0,15)));return r.flatMap(n=>{let o=n.ids.filter(s=>t.has(s.slice(0,15)));return o.length>0?[{objectApiName:n.objectApiName,ids:o}]:[]})}function Fe(r,e=Date.now()){return Math.max(0,e-r)}var id=class{listenerMap=new Map;on(e,t){let n=this.listenerMap.get(e);return n||(n=new Set,this.listenerMap.set(e,n)),n.add(t),()=>{n.delete(t)}}emit(e,t){let n=this.listenerMap.get(e);if(n)for(let o of n)try{o(t)}catch(s){Ye.warn("Event listener threw an error",{eventType:String(e),error:V(s)})}}removeAllListeners(){this.listenerMap.clear()}};var qr=class r{constructor(e){this.store=e}store;map=new Map;existing=new Set;updated=new Set;objectOf=new Map;aliases=new Map;createdKeys=new Set;alias(e,t){e!==t&&this.aliases.set(e,t)}add(e,t,n){if(this.store){this.store.setMapping("created",e,t,n);return}this.forgetCreated(e),this.createdKeys.add(t.slice(0,15)),this.map.set(e,t),this.existing.delete(e),this.updated.delete(e),this.label(e,n)}addUpdated(e,t,n){if(this.store){this.store.setMapping("updated",e,t,n);return}this.forgetCreated(e),this.map.set(e,t),this.existing.delete(e),this.updated.add(e),this.label(e,n)}addExisting(e,t,n){if(this.store){this.store.setMapping("existing",e,t,n);return}this.forgetCreated(e),this.map.set(e,t),this.existing.add(e),this.updated.delete(e),this.label(e,n)}countsByObject(){if(this.store)return this.store.countsByObject();let e=new Map;for(let[t,n]of this.objectOf){let o=e.get(n)??{objectApiName:n,created:0,linked:0,updated:0};this.existing.has(t)?o.linked++:this.updated.has(t)?o.updated++:o.created++,e.set(n,o)}return[...e.values()].map(({updated:t,...n})=>t>0?{...n,updated:t}:n)}createdByObject(){let e=new Map;if(this.store){for(let{kind:t,sourceId:n,objectApiName:o,earlier:s}of this.store.mappings()){if(t!=="created"||s||!o)continue;let i=e.get(o)??[];i.push(n),e.set(o,i)}return[...e].map(([t,n])=>({objectApiName:t,sourceIds:n}))}for(let[t,n]of this.objectOf){if(this.existing.has(t)||this.updated.has(t))continue;let o=e.get(n)??[];o.push(t),e.set(n,o)}return[...e].map(([t,n])=>({objectApiName:t,sourceIds:n}))}forgetCreated(e){let t=this.map.get(e);t!==void 0&&!this.existing.has(e)&&!this.updated.has(e)&&this.createdKeys.delete(t.slice(0,15))}createdTarget(e){return this.store?this.store.createdTarget(e):this.createdKeys.has(e.slice(0,15))}label(e,t){t?this.objectOf.set(e,t):this.objectOf.delete(e)}isExisting(e){if(this.store){let t=this.store.mapping(e);return t!==void 0&&(t.kind==="existing"||t.earlier)}return this.existing.has(e)}isCreated(e){if(this.store){let t=this.store.mapping(e);return t!==void 0&&t.kind==="created"&&!t.earlier}return this.map.has(e)&&!this.existing.has(e)&&!this.updated.has(e)}wasCreated(e){return this.store?this.store.mapping(e)?.kind==="created":this.isCreated(e)}existingSourceIds(){return this.store?[...this.store.mappings()].filter(({kind:e,earlier:t})=>e==="existing"||t).map(({sourceId:e})=>e):[...this.existing]}updatedSourceIds(){return this.store?[...this.store.mappings()].filter(({kind:e,earlier:t})=>e==="updated"&&!t).map(({sourceId:e})=>e):[...this.updated]}get(e){let t=this.aliases.get(e)??e;return this.store?this.store.targetOf(t):this.map.get(t)}remapRecord(e,t){let n={...e};for(let o of t){let s=n[o];if(typeof s=="string"){let i=this.aliases.size>0?this.aliases.get(s)??s:s,a=this.store?this.store.targetOf(i):this.map.get(i);a!==void 0&&(n[o]=a)}}return n}persist(){this.store?.flush()}get count(){return this.store?this.store.mappedSize:this.map.size}clear(){this.aliases.clear(),this.map.clear(),this.existing.clear(),this.updated.clear(),this.objectOf.clear(),this.createdKeys.clear()}toJSON(){let e={};if(this.store){for(let{sourceId:t,targetId:n}of this.store.mappings())e[t]=n;return e}for(let[t,n]of this.map)e[t]=n;return e}static fromJSON(e){let t=new r;for(let[n,o]of Object.entries(e))n==="__proto__"||n==="constructor"||n==="prototype"||typeof o=="string"&&t.add(n,o);return t}};var Wm={BusinessHours:"Name",OperatingHours:"Name",ServiceTerritory:"Name"},Ts=class{constructor(e){this.query=e}query;async resolve(e,t,n,o){if(t.length===0)return{mappings:[],unmatched:[]};let s=o??Wm[e]??"Name",i=Be(e),a=Be(s),d=new Map;for(let b of t){let k=b.Id,O=b[s];typeof k=="string"&&typeof O=="string"&&O&&d.set(k,O)}if(d.size===0)return{mappings:[],unmatched:t.map(b=>({sourceId:typeof b.Id=="string"?b.Id:"",matchValue:typeof b[s]=="string"?b[s]:null})).filter(b=>b.sourceId.length>0)};let c=`SELECT Id, ${a} FROM ${i} WHERE ${a} IN (`,u=Pr(`${c})`),l=Pr(", "),f=new Map,p=[],g=u,h=async()=>{if(p.length===0)return;let b=`${c}${p.join(", ")})`;p=[],g=u;for(let k of await this.query(n,b)){let O=k.Id,w=k[s];typeof O=="string"&&typeof w=="string"&&f.set(w,O)}};for(let b of new Set(d.values())){let k=`'${Ro(b)}'`,O=(p.length>0?l:0)+Pr(k);p.length>=$l||p.length>0&&g+O>14e3?(await h(),g+=Pr(k)):g+=O,p.push(k)}await h();let m=[],R=[];for(let[b,k]of d){let O=f.get(k);O?m.push({sourceId:b,targetId:O,matchedBy:s,matchValue:k}):R.push({sourceId:b,matchValue:k})}return{mappings:m,unmatched:R}}};function ad(r,e){let t=new Set(r.filter(s=>s.createable).map(s=>s.name)),n=new Set(r.filter(s=>s.updateable!==!1).map(s=>s.name)),o=new Map;for(let s of r)s.picklistValues&&s.picklistValues.length>0&&o.set(s.name,new Set(s.picklistValues));return{creatable:t,updateable:n,picklistValuesByField:o.size>0?o:null,picklistFields:ul(r,e),fields:r}}async function an(r,e,t){return ad(await r(e,t),t)}function dd(r,e,t){return e?e.has(t??r.name):r.updateable!==!1}function dr(r,e){let t=new Set;for(let n of r)e.has(n)&&t.add(n);return t}var Dm=new Map;function lh(r){let{objectApiName:e,records:t,fieldInfos:n,remapper:o,referenceFallback:s,failedObjects:i,writtenObjects:a,neverCopied:d,ownerMappings:c,resolvedLookups:u,targetLacks:l,inactiveOwners:f,excludedFields:p,fieldRename:g,creatableFields:h,updatableFields:m,picklistValuesByField:R,picklistFields:b,recordTypeValues:k,businessAccounts:O,contactPoints:w,decide:A,currencies:S,currencyFields:v=Dm,parentCurrencies:j,pricedIn:F,outsideTheSample:B,heldByTheRun:E}=r,_=n.filter(H=>H.isReference).map(H=>H.name),ee=new Set(_),X=w?.forObject(e,n,g),z=H=>h.has(H.name)||g[H.name]!==void 0,J=new Set(n.filter(H=>H.isReference&&(H.referenceTo??[]).some(Q=>i?.has(Q))).map(H=>H.name)),Me=new Set(n.filter(H=>{let Q=H.referenceTo??[];return H.isReference&&Q.length===1&&a?.has(Q[0])===!0}).map(H=>H.name)),ke=ru(n.filter(H=>H.isReference),d),ue=b??new Map;return t.map(H=>{let Q=[],pe=[],we=[],Ee=[],ae=u?.get(H);for(let U of n){if(!U.isReference||p.has(U.name)||ae?.[U.name]!==void 0)continue;let Oe=z(U),ye=dd(U,m,g[U.name]);if(!Oe&&!ye)continue;let le=H[U.name];if(B&&U.name!=="RecordTypeId"&&typeof le=="string"&&le!==""&&!o.get(le)&&B(U,le)){pe.push(U.name),we.push(g[U.name]??U.name);continue}if(E&&U.name!=="RecordTypeId"&&typeof le=="string"&&le!==""&&!o.get(le)&&E(le)){pe.push(U.name),Ee.push(g[U.name]??U.name);continue}if(s!=="nullify"&&!J.has(U.name)&&!Me.has(U.name)||U.name==="RecordTypeId"||ke.has(U.name))continue;let Nt=H[U.name];typeof Nt!="string"||!Nt||Oe&&o.get(Nt)||(pe.push(U.name),Q.push({field:g[U.name]??U.name,sourceRefId:Nt,targetObjects:U.referenceTo??[],...ye?{}:{insertOnly:!0}}))}let D=_.filter(U=>U!=="RecordTypeId"),L=o.remapRecord(H,D);for(let U of pe)L[U]=null;for(let[U,Oe]of Object.entries(ae??{}))L[U]=Oe;let Re=L.OwnerId,Ne=!1;typeof Re=="string"&&c[Re]&&(L.OwnerId=c[Re],Ne=!0);let Ie=ko(L,O?.has(H)===!0),ge={},K=new Set,te=[],M=[],q;for(let U of Object.keys(L)){if(p.has(U))continue;let Oe=g[U];if(Oe){L[U]!==null&&(ge[Oe]=L[U]),K.add(Oe);continue}if(!h.has(U))continue;if(ae?.[U]!==void 0){ge[U]=ae[U];continue}if(U!=="RecordTypeId"&&ke.has(U)&&!(U==="OwnerId"&&Ne)){if(s!=="keep")continue;let le=L[U];if(typeof le=="string"&&l?.has(le)){te.push(U);continue}if(U==="OwnerId"&&typeof le=="string"&&f?.has(le)){q=le;continue}}else if(s==="keep"&&U!=="RecordTypeId"&&ee.has(U)){let le=L[U];if(typeof le=="string"&&l?.has(le)){M.push(U);continue}}if(ho(e,U,Ie))continue;let ye=L[U];ye!==null&&(ge[U]=ye)}let G=ge.RecordTypeId;A?.(ge,typeof G=="string"?G:void 0);for(let U of Nc(e,ge))delete ge[U];let Te;S&&!K.has(He)?Te=xo(ge,{read:H[He],currencyFields:v,recordTypeDefault:Zn(k,G)?.picklists.get(He)?.defaultValue,ratesOn:Eo(e,H),pricedIn:F?.(H)},S):j&&(Te=ku(ge,{read:H[He],parent:Ou(e,H,_,j.changeOf),currencyFields:v},j.currencies));let ie=Ho(ge,R,ue,Zn(k,G),K),ne=Yc(e,ge);for(let U of ne)delete ge[U];return X?.(ge),{source:H,cleaned:ge,nullifiedFks:Q.filter(U=>!ne.includes(U.field)),picklistChanges:ie,...Te?{currencyChange:Te}:{},...te.length>0?{lookupsNotCarried:te}:{},...M.length>0?{lookupsOutsideTheRun:M}:{},...we.length>0?{lookupsOutsideTheSample:we}:{},...Ee.length>0?{lookupsHeldBack:Ee}:{},...q!==void 0?{ownerInactive:q}:{}}})}var _m=/^[a-zA-Z0-9]{15}([a-zA-Z0-9]{3})?$/,fh=Symbol("left to the platform"),As=class{constructor(e){this.deps=e}deps;expansionsUsed=0;failedOrphans=new Set;expansionErrors=[];pastTheCap=new Map;cap=0;async expandForNode(e){if(!e.enabled)return;this.cap=e.maxExpansions;let{fieldInfos:t,records:n,remapper:o,scopeCache:s}=e,i=new Map,a=t.filter(l=>l.isReference&&l.nillable===!1&&l.name!=="RecordTypeId");for(let l of n)for(let f of a){let p=l[f.name];if(typeof p!="string"||!p||o.get(p)||e.leftToThePlatform?.has(p))continue;let g=await this.parentObjectOf(e,f,p);if(!g)continue;let h=`${g}::${p}`;i.has(h)||i.set(h,{object:g,sourceId:p})}let d=4,c=[];for(let[,l]of i){let f=`${l.object}::${l.sourceId}`;if(!this.failedOrphans.has(f)&&!o.get(l.sourceId)){if(this.expansionsUsed+c.length>=e.maxExpansions){this.pastTheCap.set(f,l.object);continue}c.push({...l,cacheKey:f})}}let u=[c.filter(l=>l.object!==ce),c.filter(l=>l.object===ce)];for(let l of u){let f=[];for(let p=0;p<l.length;p+=d){let g=l.slice(p,p+d).filter(h=>!o.get(h.sourceId));await Promise.all(g.map(async h=>{try{let m=await this.expandSingleOrphanParent(e,h.object,h.sourceId);if(m===fh)return;m&&"id"in m?(this.expansionsUsed++,this.pastTheCap.delete(h.cacheKey),m.existing?o.addExisting(h.sourceId,m.id,h.object):(o.add(h.sourceId,m.id,h.object),m.owedStatus&&e.oweStatus?.(h.object,m.id,m.owedStatus),m.callId!==void 0&&e.calls?.answered(m.callId),o.persist()),s&&s.add(h.object,[h.sourceId]),h.object===Se&&rn(m.source)&&f.push(m.source)):(this.failedOrphans.add(h.cacheKey),this.expansionErrors.length<3&&this.expansionErrors.push({recordSummary:`${h.object}/${h.sourceId}`,messages:m&&m.refused.length>0?m.refused:["Orphan parent expansion produced no new id"]}))}catch(m){this.failedOrphans.add(h.cacheKey),this.expansionErrors.length<3&&this.expansionErrors.push({recordSummary:`${h.object}/${h.sourceId}`,messages:[V(m)]})}}))}f.length>0&&await e.linkPersonContacts?.(f)}}async parentObjectOf(e,t,n){let o=t.referenceTo??[],s=o.filter(a=>!Ao(a)),i;return o.length===1?i=s[0]:s.length>0&&(i=await e.objectOf?.(n,s)),i===e.node.objectApiName?void 0:i}capReport(){return this.pastTheCap.size===0?null:{cap:this.cap,notCopied:this.pastTheCap.size,objects:[...new Set(this.pastTheCap.values())]}}buildErrorReport(){return this.failedOrphans.size===0?null:{objectApiName:"__expandOrphanParents__",stage:"insert",failedCount:this.failedOrphans.size,attemptedCount:this.expansionsUsed+this.failedOrphans.size,samples:this.expansionErrors}}async expandSingleOrphanParent(e,t,n){let{sourceOrgId:o,targetOrgId:s,recordTypeMappings:i,recordTypeMapper:a}=e,{anonymize:d,withoutFileContent:c,startAsDraft:u,leftToThePlatform:l}=e;if(!_m.test(n))throw new Error(`Invalid Salesforce record ID for orphan expansion: "${n}"`);let f=Be(t),p=await this.deps.describeFields(o,f),g=c?c(f,p):p,h=zt(g,e.fieldExclusions?.[f]);h.length===0&&h.push("Id");let m=`SELECT ${h.join(", ")} FROM ${f} WHERE Id = '${Ro(n)}'`,R=await this.deps.queryRecords(o,m);if(R.length===0)return null;if(l&&l.keep(f,R).length===0)return fh;let b=R[0],k=rn(b),O=k?await e.personAccountsInTarget?.():void 0;if(f===ce&&k&&O!==!1&&e.contactOnItsOwn?.(n)!==!0)throw new Error("Not copied: a person account's contact is written by the platform with its account, never on its own");let w=null;try{w=ad(await this.deps.describeFields(s,f),f)}catch(D){Ye.warn(`[forge] orphan-parent target describe failed for ${t}: ${D instanceof Error?D.message:String(D)}. Falling back to source createable.`)}let A=new Set(g.filter(D=>D.createable).map(D=>D.name)),S=w?dr(A,w.creatable):A,v=new Set(e.fieldExclusions?.[f]??[]),j=e.fieldMappings?.[f]??{},F=new Set,B=new Set(await e.maskedFieldsOf?.(f).catch(()=>[])??[]),E=[],_=S.has("RecordTypeId")&&!v.has("RecordTypeId")&&j.RecordTypeId===void 0,ee=f===Se&&k&&(e.businessAccountsAmong?(await e.businessAccountsAmong([b],_)).has(b):O===!1),X=ko(b,ee),z={};for(let D of g){let L=D.name;if(v.has(L))continue;let Re=b[L];if(Re==null)continue;if(B.has(L)){(j[L]!==void 0||S.has(L))&&E.push(L);continue}if(D.isReference&&typeof Re=="string"&&L!=="RecordTypeId")continue;let Ne=j[L];if(Ne){z[Ne]=Re,F.add(Ne);continue}S.has(L)&&(ho(f,L,X)||(z[L]=Re))}if(e.contactPoints?.forObject(f,g,j)?.(z),w){let D=new Set([...S].filter(L=>!v.has(L)&&!j[L]));await this.checkPicklists(e,f,b,z,w,D,F)}let J=a&&i?a.apply([z],i,D=>hs(f,D))[0]:z,Me=d?d(f,J,n,g):J,ke=u?await u(f,Me):void 0,ue=await this.insertParent(e,f,n,Me),H=ue.written,Q=ue.callId;if(!H)return null;let pe=H.success?void 0:_l(H,Me,void 0),we=H.errors;if(pe){let D=await this.insertParent(e,f,n,Bl(Me,pe));if(!D.written)return{refused:["No result returned for record",aa(pe,we)]};H=D.written,Q=D.callId}if(H.success)return E.length>0&&e.onMaskedLeftOut?.(f,E),pe&&e.onWrittenWithoutFields?.(f,{rows:1,fields:pe.map(D=>({...D,rows:1}))}),{id:H.id,existing:!1,owedStatus:ke,source:b,...Q!==void 0?{callId:Q}:{}};let Ee=this.deps.describeObject?await this.deps.describeObject(s,f).then(D=>D.keyPrefix,()=>null):null,ae=qu(H,Ee);return ae.kind==="linked"?{id:ae.id,existing:!0,source:b}:{refused:pe?[...H.errors,aa(pe,we)]:H.errors}}async insertParent(e,t,n,o){let s=e.calls?.sending(t,[{sourceId:n,payload:o}]),i;try{i=(await this.deps.insertRecords(e.targetOrgId,t,[o]))[0]}catch(a){throw s!==void 0&&nl(a)!=="may-have-written"&&e.calls?.answered(s),a}return s===void 0?{written:i}:i?.success?{written:i,callId:s}:(e.calls?.answered(s),{written:i})}async checkPicklists(e,t,n,o,s,i,a){let d=e.recordTypePicklists?await e.recordTypePicklists.forRows({objectApiName:t,rows:[n],fields:s.picklistFields,written:p=>i.has(p),recordTypeMappings:e.recordTypeMappings,withoutRecordTypes:!s.fields.some(p=>p.name==="RecordTypeId")}):void 0;for(let p of d?.notes??[])e.onRecordTypeNote?.(t,p);let c=o.RecordTypeId,u=n[He],l=e.currencies&&i.has(He)&&typeof u=="string"&&u!==""?await e.currencies():void 0;if(l){let p=xo(o,{read:u,currencyFields:Io(s.fields),recordTypeDefault:Zn(d?.byRecordType,c)?.picklists.get(He)?.defaultValue,ratesOn:Eo(t,n)},l);e.currencyChanges?.add(t,p);let g=n.Id;p&&typeof g=="string"&&e.currencyChangesById?.set(g,p)}let f=Ho(o,s.picklistValuesByField,s.picklistFields,Zn(d?.byRecordType,c),a);e.picklistChanges?.add(t,f)}};async function*js(r,e){let t=e!==void 0&&Number.isFinite(e)&&e>=1?Math.floor(e):0,n=0,o=[];for await(let s of r){if(t===0){if(s.length===0&&n>0)continue;n++,yield s;continue}for(o=o.length===0?[...s]:[...o,...s];o.length>=t;)n++,yield o.slice(0,t),o=o.slice(t)}(o.length>0||n===0)&&(yield o)}function Vt(r,e,t,n,o,s){let{queryPages:i}=r;if(i)return js(s?.all?i(e,t,s):i(e,t),n);if(s?.all)throw new Error("The deps read no archived row: no cursor to read through queryAll.");return js((async function*(){yield await r.queryRecords(e,t,o)})(),n)}function hh(r){let e=async(...n)=>{let[o,s,...i]=n,a=Wi(s),d=cu(s,a===void 0?void 0:["Id",a.stamp]);if(!d)return r.queryRecords(...n);let c=await r.queryRecords(o,d.first,...i),u=l=>r.queryRecords(o,l);return a===void 0?lu(c,d,u):fu(c,d,u,a)},t=(n,o,s)=>pu(o,i=>(s?.all?r.queryPages?.(n,i,s):r.queryPages?.(n,i))??ph(),s?.all?i=>qm(r.queryPages?.(n,i,s)??ph()):i=>r.queryRecords(n,i),Wi(o));return new Proxy(r,{get(n,o,s){return o==="queryRecords"?e:o==="queryPages"?n.queryPages?t:void 0:Reflect.get(n,o,s)}})}async function qm(r){let e=[];for await(let t of r)for(let n of t)e.push(n);return e}async function*ph(){}var be=class extends Error{constructor(e){super(e),this.name="ForgeAbortedError"}},xd=Dr;function Gm(r){let e=r.from!=="plan"?r.from:r.fromTheJournal?"resumed":r.ofTheRunRetried?"retried":"simulation";return{objectApiName:r.objectApiName,count:r.ids.size,from:e,readAt:r.readAt}}var zm={OpportunityLineItem:{object:"OpportunityLineItemSchedule",lookup:"OpportunityLineItemId"}},Ft=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,mh=2e3;function Hm(){return{pages:0,rows:0,sent:0,succeeded:0,updated:0,linked:0,linkedToCreated:0,failed:0,alreadyExists:0,unidentified:0,writtenBefore:0,withTheirAccount:0,withTheirEmail:0,teamOwners:0,teamOthers:0,teamValues:{notKept:new Map,unread:new Map},rolesOfTheirOpportunity:0,rolesGiven:0,personContactsUnlinked:0,sentOnTheirOwn:0,onTheirOwnWhy:"",withoutParent:0,withoutParentGroups:new Map,rowsLeft:()=>0,held:new Map,heldWholeRows:0,picklists:new Ko,currencies:new Fo,lookupsNotCarried:new Map,lookupsOutsideTheRun:new Map,lookupsHeldBack:new Map,ownersInactive:0}}function wh(r){return r.succeeded+r.updated+r.linked+r.writtenBefore+r.withTheirAccount+r.withTheirEmail+r.teamOwners+r.teamOthers+r.rolesOfTheirOpportunity}function yh(r){return[Fi(r.flagsNotKept),ug(r.teamValues)].flatMap(e=>e?[`, ${e}`]:[]).join("")}function cd(r,e){for(let{count:t,why:n}of e)r.held.set(n,(r.held.get(n)??0)+t)}function ud(r){return[...r.held].map(([e,t])=>({count:t,why:e}))}var Km=5e3,Vm=2e3,bh="afterTask",ld=3,Rh=1e3,Dn=2e3;function Ur(r,e,t){return{objectApiName:r,recordCount:0,fieldCount:e.length,status:"idle",progress:0,included:!0,piiFields:[],anonymizeFields:[],level:t,successCount:0,failureCount:0,errors:[],createableFieldCount:e.filter(n=>n.createable).length,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}}function Jm(r){return r.some(e=>e.isReference&&(e.referenceTo??[]).includes(et))}function sg(r,e){let t=[];for(let n of e){let o=n.referenceTo??[];if(!n.isReference||o.length!==1||!Qe(r,n.name,n.nillable))continue;let[s]=o;s!==r&&!Ke.has(s)&&t.push(s)}return t}function Qm(r,e,t){return sg(r,e).find(n=>t.has(n))}function Ym(r,e,t){let n=t.scopeCache;if(!n)return[];let o=new Set(t.graph.edges.filter(i=>i.targetObject===r).map(i=>i.sourceObject)),s=new Set;for(let i of e)if(i.isReference)for(let a of i.referenceTo??[])a!==r&&o.has(a)&&t.readObjects.has(a)&&!Ke.has(a)&&!t.config.referenceDataObjects.has(a)&&!n.isRead(a)&&s.add(a);return[...s]}var Xm=3,Zm=10,ew=5;function tw(r,e){let t=e.rows.filter(({objectApiName:s,row:i})=>{let a=i.Id;return typeof a!="string"||!r.heldForExclusions.get(s)?.has(a)});if(t.length===e.rows.length)return e;let n=new Set,o=new Set;for(let{objectApiName:s,row:i,field:a}of t)n.add(String(i[a])),o.add(s);return{ids:n,neededBy:o,rows:t}}function Oh(r,e){let t=r.readAsParents.get(e);return!t||t.count===0?"":`, ${t.count} read by id for the ${[...t.neededBy].sort().join(", ")} records that cannot be written without ${t.count===1?"it":"them"}`}function kh(r,e){let t=r.get(e)??new Set;if(!r.isRead(e))return new Set(t);let n=r.scopeOf(e);return new Set([...t].filter(o=>!n?.has(o)))}function Gr(r,e){for(let t of e){let n=t.Id;typeof n=="string"&&n!==""&&r.idsRead.add(n)}}function Sh(r,e){let t=e!==void 0&&e>0?Math.floor(e):0;return t>0?Math.min(r.recordCount,t):r.recordCount}function xs(r){let e=r.maxRecordsPerObject;return e!==void 0&&e>0&&Math.floor(e)>0?Math.floor(e):void 0}var nw={storage:{past:"past the data storage the target has left",more:", or free data storage in the target"},within:{past:"past the MB it may take (--fit-within)",more:", or let it take more (--fit-within)"},maxTotal:{past:"past the records it may write (--max-total)",more:", or raise --max-total"},targetRequests:{past:"past the API requests the target has left today",more:", or run it once the target has more to spare"},bulkBatches:{past:"past the Bulk API batches the target has left today",more:", or run it once the target has more to spare"},sourceRequests:{past:"past the API requests the source has left today",more:", or run it once the source has more to spare"},heavyRoots:{past:"past what the sample may take",more:""},whole:{past:"past what the sample may take",more:""},draw:{past:"past what the sample may take",more:""}};function Th(r,e){let t=r/1048576*100;return(e==="up"?Math.ceil(t):Math.floor(t))/100}var jd=class extends ir{constructor(t,n,o){super("SAMPLE_CANNOT_FIT",t,n);this.sample=o}sample},Ah=3;function rw(r,e){let t=e.slice(0,Ah).map(({sourceId:i,matchValue:a})=>({recordSummary:`Id=${i} matchValue=${a??"null"}`,messages:[a===null?`This ${r} has no name to find it by in the target org: the records that point at it are not linked to one.`:`No ${r} of the target org is named "${a}": the records that point at it are not linked to one. Create a ${r} of that name in the target\u2019s Setup, or rename one of the target\u2019s to it, then run again.`]})),n=e.slice(Ah);if(n.length===0)return t;let o=n.map(({matchValue:i})=>i===null?"no name":`"${i}"`),s=o.length===1?o[0]:`${o.slice(0,-1).join(", ")} or ${o.at(-1)}`;return[...t,{recordSummary:`${n.length} more`,messages:[`No ${r} of the target org is named ${s} either.`]}]}function ow(r){let e=r.orphanExpander.capReport();return e?{orphanParentsCapped:e}:{}}function jh(r){let e=xs(r.config);return e!==void 0&&r.cappedObjects.size>0?{cappedObjects:{perObject:e,objects:[...r.cappedObjects]}}:{}}function sw(r){return r.errors.length===0?"excluded":`excluded: ${r.errors.join("; ").replace(/\s+/g," ").trim()}`}function iw(r,e,t){let n=t.filter(d=>d.isReference),o=d=>n.filter(c=>(c.referenceTo??[]).includes(d)),s=d=>{let c=o(d);return c.length>0&&c.every(u=>(u.referenceTo??[]).length>1)},i=d=>{let c=o(d);return c.length>0&&c.every(u=>u.nillable===!0)},a=new Set(ts(e,new Map([[r,t]])).edges.filter(d=>d.targetObject===r&&(d.required===!0||d.type==="master-detail"&&!i(d.sourceObject))&&Fl(d)&&!s(d.sourceObject)).map(d=>d.sourceObject));for(let d of n){let c=d.referenceTo??[];c.length!==1||!Tr(d)||!Qe(r,d.name,d.nillable)||a.add(c[0])}return a.delete(r),[...a]}function aw(r,e){return $d(Hr(r.values()),e)}function Hr(r,e=new Map){for(let{field:t,parentObject:n,notInTarget:o,reason:s,recordType:i}of r){let a=`${t}|${n}|${o===!0?"outside":""}|${s??""}`,d=e.get(a)??{field:t,parentObject:n,...o?{notInTarget:o}:{},...s!==void 0?{reason:s}:{},...i?{recordType:i}:{},count:0};d.count++,e.set(a,d)}return e}function $d(r,e){return[...r.values()].sort((t,n)=>n.count-t.count).slice(0,3).map(({field:t,parentObject:n,notInTarget:o,reason:s,recordType:i,count:a})=>({recordSummary:i?`RecordType=${i.developerName} (${a} record${a===1?"":"s"})`:`${t} \u2192 ${n} (${a} record${a===1?"":"s"})`,messages:i?[Do({...i,recordCount:a})]:[s!==void 0?`Not written: ${s}`:o?`Not written: ${t} may not be left empty, and the target holds no ${n} record of the id it names, outside the run.`:`Not written: ${t} may not be left empty, and the ${n} it points at `+(e.has(n)?"failed in this run.":"was not written by this run.")]}))}var dw=3,$h=5e4;function cw(r,e){return!e||e.size===0?0:r.reduce((t,{node:n,read:o})=>t+(o>0?(e.get(n.objectApiName)??0)*Math.ceil(o/Dn):0),0)}var vh={field:"",parentObject:"",reason:"the source does not hold it"};function fd(r,e){return`${r} may not be left empty, and names a ${e} record the source does not hold`}function uw(r,e){return`${r} may not be left empty, and names a ${e} record outside the sample: changed since the sample`}function lw(r,e){return`${r} may not be left empty, and names a ${e} record gone from the source since the sample`}function Eh(r,e){return`${r} may not be left empty, and names a ${e} record left aside`}function fw(r,e,t,n=()=>!0){return t.flatMap(o=>{let s=o.referenceTo??[],[i]=s;return o.isReference&&s.length===1&&i!==e&&n(o.name)&&r.writtenObjects.has(i)&&!r.config.referenceDataObjects.has(i)&&r.turnsEnded.has(i)&&Qe(e,o.name,o.nillable)?[{field:o.name,parent:i}]:[]})}var pw="held back for a record type closed to the user the run writes as",hw="held back for a record type the target has none of";function Ih(r){let e=0,t=0,n=0;for(let o of r)o.recordType?.unmapped?t++:o.recordType?e++:n++;return[...e>0?[{count:e,why:pw}]:[],...t>0?[{count:t,why:hw}]:[],...n>0?[{count:n,why:vd}]:[]]}function xh(r,e){return e<=0?{}:r.every(t=>t.unmapped)?{recordTypeNotInTarget:e}:{heldBack:e}}function Ph(r,e){return Di(r.unmapped?"record_type_unmapped":"record_type_unavailable",r.objectApiName,r.developerName,r.recordCount,lg(e))}function gw(r,e,t){let n=r.leftAside.get(e)??new Map;Hr(t,n),r.leftAside.set(e,n)}function mw(r,e){return[...r.leftAside.get(e)?.values()??[]].map(({count:t,reason:n})=>`, ${t} left aside: ${n??""}`).join("")}function ww(r){return[...r.leftAside].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t.values()].sort((n,o)=>o.count-n.count).slice(0,3).map(({field:n,parentObject:o,reason:s,count:i})=>({recordSummary:`${n} \u2192 ${o} (${i} record${i===1?"":"s"})`,messages:[`Left aside, not written: ${s??""}`]}))}))}function Ps(r,e){return r.leftToThePlatform.counts(e).map(({why:t,count:n})=>`, ${Vc(n,t)}`).join("")+mw(r,e)}function yw(r){return[...bw(r),...ww(r)]}function bw(r){let e=new Map;for(let{objectApiName:t,why:n,count:o}of r.leftToThePlatform.counts())e.set(t,[...e.get(t)??[],{recordSummary:Jc(o,n),messages:[Qc(n)]}]);return[...e].map(([t,n])=>({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:n}))}function Kr(r){return r==="not-creatable"?", which the target org takes no insert of":r==="not-in-target"?", which the target org does not have":", excluded from this run"}function Rw(r){let e=new Map([[void 0,new Set],["not-creatable",new Set],["not-in-target",new Set]]);for(let{excluded:t,target:n}of r)e.get(n)?.add(t);return[...e].filter(([,t])=>t.size>0).map(([t,n])=>`${[...n].sort().join(", ")}${Kr(t)}`).join("; ")}function Ow({field:r,excluded:e,through:t,namedBy:n,target:o}){return n!==void 0?`Not written: the only records that name it are ${n} records held back for ${e}${Kr(o)}.`:t!==void 0?`Not written: ${r} may not be left empty, and the ${t} it names is held back for ${e}${Kr(o)}.`:o==="not-creatable"?`Not written: ${r} may not be left empty, and the target org takes no insert of ${e}.`:o==="not-in-target"?`Not written: ${r} may not be left empty, and the target org does not have ${e}.`:e===Gt?`Not written: a price sold under a selling model needs its product's option for that model, and ${e} is excluded from this run.`:`Not written: ${r} may not be left empty, and ${e} is excluded from this run.`}var vd="held back for want of their parent",Fh=" \u2014 the records that cannot be written without one of those not written are held back",Nh={accountNotWritten:"not sent: a person account's contact goes in with its account, which this run did not write",contactNotFound:"not sent: a person account's contact goes in with its account, and the one the platform wrote was not found"};function Fs(r){let e=new Map;for(let{excluded:n,namedBy:o,target:s}of r){let i=o!==void 0,a=`${i?"named":"needing"}|${s??""}`,d=e.get(a)??{namedOnly:i,target:s,objects:[]};d.objects.push(n),e.set(a,d)}let t=({namedOnly:n,target:o})=>(n?3:0)+(o===void 0?0:o==="not-creatable"?1:2);return[...e.values()].sort((n,o)=>t(n)-t(o)).map(({namedOnly:n,target:o,objects:s})=>{let i=`${[...new Set(s)].sort().join(", ")}${Kr(o)}`;return{count:s.length,why:n?`held back, named only by records held back for ${i}`:`held back for want of ${i}`}})}function Qt(r,e){return Fs(r.heldForExclusions.get(e)?.values()??[])}function _n(r){return r.reduce((e,t)=>e+t.count,0)}function cn(r){return r.map(({count:e,why:t})=>`, ${e} of them ${t}`).join("")}function Ns(r,e=!1){let t=_n(r);if(t===0)return"";let n=`, ${t} ${e?"more ":""}failed`;return r.length===1?`${n}, ${r[0].why}`:n+cn(r)}function Ch(r,e){return Ps(r,e)+Ns(Qt(r,e))}function kw(r){return[...r.heldForExclusions].map(([e,t])=>{let n=new Map;for(let o of t.values()){let s=`${o.field}|${o.through??""}|${o.namedBy??""}|${o.excluded}|`+(o.target??""),i=n.get(s)??{...o,count:0};i.count++,n.set(s,i)}return{objectApiName:e,stage:"scope",failedCount:t.size,attemptedCount:0,samples:[...n.values()].sort((o,s)=>s.count-o.count).slice(0,3).map(o=>{let s=`${o.count} record${o.count===1?"":"s"}`;return{recordSummary:o.namedBy!==void 0?`named by ${o.namedBy}.${o.field} (${s})`:`${o.field} \u2192 ${o.through??o.excluded} (${s})`,messages:[Ow(o)]}})}})}function Sw(r,e){for(let[t,n]of r.heldForExclusions){let o=n.get(e);if(o)return{objectApiName:t,why:o}}}function Mh(r,e,t){for(let n of t){let o=e[n.name];if(typeof o!="string"||o===""||r.remapper.get(o))continue;let s=Sw(r,o);if(s){let{excluded:i,target:a}=s.why;return{field:n.name,excluded:i,through:s.objectApiName,...a?{target:a}:{}}}}}function $n(r,e,t=[]){let n=e+_n(t);return`Held back ${r}, nothing written, ${n} failed${cn(t)}`}function Bh(r){return r>0?`, ${r} ${r===1?"person account's contact":"person accounts' contacts"} sent on their own: the target wrote none with their account`:""}function ig(r,e=0){let t=r+e;if(t<=0)return"";let n=e>0?` (${e} of them outside the sample, with an account the run wrote)`:"";return`, ${t} written by the platform with their person account${n}`}function pd(r,e){if(e!==ce)return 0;let t=r.personContactsOutsideTheSample;return r.personContactsOutsideTheSample=0,t}function cr(r,e,t){t<=0||r.writtenByThePlatform.set(e,(r.writtenByThePlatform.get(e)??0)+t)}function Ed(r,e){return r.writtenBefore.from==="resume"?`${e} already in the target, written before the run stopped`:`${e} already in the target from the run retried`}function ag(r,e){let t=Math.min(r,Math.max(0,e)),n=r-t;return(n>0?`, ${n} linked to records already in the target`:"")+(t>0?`, ${t} linked to records the run created (the target refused them as copies of those)`:"")}var Tw=3;function hd(r,e,t,n=0){let o=r.dryRun?"would be inserted":"succeeded",s=e.updated>0?`, ${e.updated} updated through their external id`:"",i=ag(e.linked,e.linkedToCreated),a=ig(e.withTheirAccount,n),d=e.withTheirEmail>0?`, ${e.withTheirEmail} written by the platform with their email`:"",c=dg(e.teamOwners,e.teamOthers)+cg(e.rolesOfTheirOpportunity,e.rolesGiven),u=e.writtenBefore>0?`, ${Ed(r,e.writtenBefore)}`:"",l=e.unidentified>0?` (${e.unidentified} already in the target without Salesforce naming the record \u2014 their children lose the link)`:"";return`${e.succeeded} ${o}${s}${i}${d}${a}${c}${u}, ${e.failed+_n(t)} failed${l}${cn(t)}`}function dg(r,e){return(r>0?`, ${r} written by the platform with their opportunity, for its owner`:"")+(e>0?`, ${e} on the team of their opportunity in the target already`:"")}function cg(r,e){if(r===0)return"";let t=e>0?`, ${e} given the source's fields ${e===1?"it":"they"} lacked`:"";return`, ${r} written by the platform with their opportunity, for its contact${t}`}function Aw(r,e,t){e.forEach(({source:n},o)=>{let s=n.Id,i=t[o]?.[Le];typeof s=="string"&&(typeof i=="string"&&i!==""?r.contactSentWith.set(s,i):r.contactSentWith.delete(s))})}function jw(r,e){for(let t of["notKept","unread"])for(let[n,o]of e[t])r[t].set(n,(r[t].get(n)??0)+o)}function ug(r){return[...[...r.notKept].map(([e,t])=>`${t} linked without the source's ${e}: the target's record keeps its own`),...[...r.unread].map(([e,t])=>`${t} linked whose ${e} was not read: the platform writes the record with the opportunity, which a dry run does not write`)].join(", ")}function zr(r,e,t=!0){let n=[...e.values()].filter(d=>d.namedBy===void 0),o=[...e.values()].filter(d=>d.namedBy!==void 0),s=[...e.values()].every(d=>d.target===void 0),i=d=>s?[...new Set(d.map(c=>c.excluded))].sort().join(", "):Rw(d),a=o.length===0?`every record needs ${i(n)}`:n.length===0?`the only records that name its records are held back for ${i(o)}`:`${n.length} of its records need ${i(n)}, and the only records that name the rest are held back for ${i(o)}`;return`${$n(r,e.size)}: ${a}${s?", excluded from this run":""}.`+(t?" Objects that cannot be written without it will be skipped.":"")}function Lh(r){let e=new Map(r.readAtItsTurn);for(let[s,i]of r.preread)e.set(s,i);let t=new Map,n=[];for(let[s,{records:i,fieldInfos:a}]of e){let d=a.filter(l=>l.isReference),c=Ke.has(s),u=r.scopeCache?.reachedOf(s);for(let l of i){let f=l.Id,p={row:l,lookups:d};c&&typeof f=="string"&&f!==r.config.rootRecordId&&r.roots?.ids.has(f)!==!0&&u?.has(f)!==!0?t.set(f,p):n.push(p)}}let o=new Set;for(let s=n.pop();s;s=n.pop())for(let i of s.lookups){let a=s.row[i.name];if(typeof a!="string"||a===""||o.has(a))continue;o.add(a);let d=t.get(a);d&&n.push(d)}return o}function Wh(r,e,t,n){let o=r.namedByRowsHeldBack.get(t);if(!(!o||n.has(t)||t===r.config.rootRecordId)&&r.roots?.ids.has(t)!==!0&&!(t===r.standardPricebookId||r.config.writtenBefore.has(t))&&r.scopeCache?.reachedOf(e)?.has(t)!==!0)return o}function Dh(r){for(let[e,t]of Object.entries(Ar))if(t.object===r)return{parent:e,lookup:t.lookup}}function $w(r,e){return e.filter(t=>t.isReference&&Qe(r,t.name,t.nillable)).map(t=>t.name)}function vw(r){return r.isScoped===!0||r.files!==void 0||r.beforeWrite!==void 0}function gd(r){return r.size===0?"":`, written without a lookup naming a record the target does not hold, which the platform fills (the owner with the user the run writes as): ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}`}function _h(r,e){for(let{lookupsNotCarried:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function md(r){return r.size===0?"":`, written without ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}: the target holds no record of these ids, outside the run`}function wd(r,e){for(let{lookupsOutsideTheRun:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function Ew(r){return[...r.lookupsOutsideTheRun].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t].sort(([,n],[,o])=>o.rows-n.rows).map(([n,{parent:o,rows:s}])=>({recordSummary:`${n} \u2192 ${o} (${s} record${s===1?"":"s"})`,messages:[`Written without ${n}: the target holds no record of these ids, outside the run.`]}))}))}function yd(r){return r.size===0?"":`, written without ${[...r].map(([t,n])=>`${t} on ${n}`).join(", ")}: the record it names is held back by the run`}function bd(r,e){for(let{lookupsHeldBack:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function Iw(r){return[...r.lookupsHeldBack].map(([e,t])=>({objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[...t].sort(([,n],[,o])=>o.rows-n.rows).map(([n,{parent:o,rows:s}])=>({recordSummary:`${n} \u2192 ${o} (${s} record${s===1?"":"s"})`,messages:[`Written without ${n}: the record it names is one the run holds back or leaves aside, never written.`]}))}))}var qh=10;function Rd(r){return r===0?"":`, written with the user the run writes as for owner on ${r}: the target holds their owner inactive`}function Uh(r){return r.filter(({ownerInactive:e})=>e!==void 0).length}function xw(r,e,t){let n=r.ownersInactive.get(e);for(let{ownerInactive:o}of t)o!==void 0&&(n??={rows:0,owners:new Set},n.rows+=1,n.owners.add(o));n&&r.ownersInactive.set(e,n)}function Pw(r){return[...r.ownersInactive].map(([e,{rows:t,owners:n}])=>{let o=[...n],s=o.slice(0,qh).join(", "),i=o.length-qh;return{objectApiName:e,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`OwnerId \u2192 User (${t} record${t===1?"":"s"})`,messages:[`Written with the user the run writes as for owner: the target holds these owners inactive (${i>0?`${s}, and ${i} more`:s}) and that user may not give a record an inactive owner (Update Records with Inactive Owners). Map them to an active user under Owners (Review \u2192 Controls, or --owner-map on the command line) to give the records to that user.`]}]}})}function $s(r){return`${r} on a case waiting for ${r===1?"its task":"their tasks"}`}function Od(r,e,t){t<=0||r.notSent.set(e,(r.notSent.get(e)??0)+t)}function Fw(r,e,t,n){return{...r,status:t&&r.status!=="error"?"stopped":r.status,message:`${r.message}; ${t?"stopped: ":""}${e} not sent${n}`}}function ur(r,e){r.store?r.store.withTheirRecord(e):r.withTheirRecord.add(e)}function Nw(r,e){return r.store?r.store.markedWithTheirRecord(e):r.withTheirRecord.has(e)}function Gh(r){return r.store?[...r.store.withTheirRecordIds()]:[...r.withTheirRecord]}var Cs=class extends Error{constructor(e,t){super(`Internal error: ${e} holds more rows than a clone of the whole org reads whole${t===void 0?"":` (${t})`}, which its gate should have refused before anything was written. The run stopped rather than write part of it: raise sandforge.forge.maxRecordsPerObject, or leave the object out.`),this.name="WholeReadPastBoundError"}},zh="files",kd=200,Cw=Dn,Sd=[{object:"ContentVersion",counted:"ContentDocument",size:"ContentSize",where:"IsLatest = true AND ContentLocation = 'S'"},{object:"Attachment",counted:"Attachment",size:"BodyLength",where:""}];function Hh(r,e){let t=r.objects.find(n=>n.objectApiName===e);return t||(t={objectApiName:e,planned:0,plannedBytes:0,copied:0,failed:0},r.objects.push(t)),t}function Mw(r,e){let t=[];for(let n of e){let o=n.Id,s=n.ParentId;if(typeof o!="string"||typeof s!="string"||!r.remapper.wasCreated(s))continue;let i=n.Name,a=typeof i=="string"&&i!==""?i:o,d=n.ContentType,c=n.BodyLength;t.push({objectApiName:"Attachment",sourceId:o,body:{objectApiName:"Attachment",id:o},name:a,bytes:typeof c=="number"&&Number.isFinite(c)?c:0,hosts:[{id:s}],fields:{Name:a,...typeof d=="string"&&d!==""?{ContentType:d}:{},IsPrivate:n.IsPrivate===!0}})}return t}function Kh(r){return r?.errorCode==="INVALID_QUERY_LOCATOR"||V(r).includes("INVALID_QUERY_LOCATOR")}function Vh(r){if(Uc(r))return!0;let{errorCode:e,statusCode:t}=r??{};return e==="SERVER_UNAVAILABLE"||t===502||t===503||t===504?!0:V(r).includes("SERVER_UNAVAILABLE")}function Jh(r){return new Promise(e=>setTimeout(e,r))}function Bw(r,e){return e?r?`(${r}) AND ${e.where}`:e.where:r}function vs(r,e){return jo(e)?xr(e)?!0:!r.writtenObjects.has(e):!1}function dn(r,e){let t=e.Id;return typeof t=="string"&&r.writtenBefore.has(t)}function Qh(r,e){if(e!==void 0&&r.recordTypeDecisions.get(e)?.to!==null)return r.recordTypeMappings?.find(t=>t.sourceId===e)?.developerName}function Lw(r){let e=(r?.recordTypes??[]).filter(t=>!t.master);if(!e.some(t=>t.namespacePrefix===void 0))return e.map(Au)}function lg(r){return(r?.recordTypes??[]).filter(e=>e.available&&e.active&&!e.master).map(e=>e.developerName)}var Yh=200,Xh=200,Zh=/[\u0000-\u001f]/;function Td(r,e){if(!gt(e))return"";let t=[...Ma(r.pricesSwappedSaid),...Ww(r)];return t.length===0?"":`, ${t.join("; ")}`}function Ww(r){let e=[...r.pricesKeptAsRead].filter(([s])=>!r.prices.standsFor.has(s)).map(([,s])=>s);if(e.length===0)return[];let t=s=>{let i=new Map;for(let a of s)i.set(a,(i.get(a)??0)+1);return[...i].map(([a,d])=>`${d} ${a}`).join(", ")},n=e.filter(s=>s.to!==void 0&&s.from!==s.to);if(n.length>0)return[`${t(n.map(({from:s,to:i})=>`${s} \u2192 ${i}`))}: no price in the currency written in the source for the same product and price book, written in it at its amount as read, not converted`];let o=e.filter(s=>s.to===void 0).map(({from:s})=>s);return new Set(o).size<2?[]:[`prices written in the target's one currency, which it did not say: ${t(o)}, at their amount as read, not converted`]}var Dw=/^012000000000000(AAA)?$/;function eg(r){return(e,t)=>{for(let n of Object.keys(t))n!=="Id"&&r.patched(String(t.Id),n)}}var _w=["insert","upsert"],qw=["insert","upsert","update"];function tg(r,e){let t="";for(let n of _w){let o=r.splitting.sizes.report({objectApiName:e,op:n});if(!o||o.to>=o.from)continue;let s=`${n}\0${e}`,i=o.rows-(r.smallerCallsSaid.get(s)??0);i<=0||(r.smallerCallsSaid.set(s,o.rows),t+=`, ${i} sent ${o.to} at a time after the target's automation hit a Salesforce limit`)}return t}function Uw(r,e){let{objectApiName:t}=r,n=r.op==="update"?"lookup updates":"records",o=r.alone+r.notSplit+r.keptWhole,s=r.to<r.from&&r.rows>0?`${t}: ${r.rows} ${n} sent ${r.to} at a time`:`${t}: ${o} ${n} refused for a Salesforce limit`;return{objectApiName:t,stage:"scope",failedCount:0,attemptedCount:r.rows,samples:[{recordSummary:s,messages:[Bu(r),...r.notSplit>0?[Lu(r.notSplit,e,"run")]:[]]}]}}function Gw(r){return qw.flatMap(e=>r.splitting.sizes.reports(e).filter(t=>t.rows+t.alone+t.notSplit+t.keptWhole>0).map(t=>Uw(t,Wu(r.splitting.allowance,{objectApiName:t.objectApiName,op:e}))))}function Es(r){return{sending:(e,t,n,o)=>{let s=t.map(({payload:d})=>d),i=Op(s),a=o===!0&&n===void 0?Sp(s):[];return r.sent(e,i,t.flatMap(({sourceId:d,payload:c,owes:u},l)=>d===void 0?[]:[{sourceId:d,fingerprint:kp(c,i),owes:u,...n!==void 0?{externalKey:Tp(c,n)}:{},...a[l]!==void 0?{jobKey:a[l]}:{}}]),new Date,n)},answered:e=>r.answered(e),opened:(e,t)=>r.jobOpened(e,t),unattributed:(e,t)=>r.createdUnattributed(e,t)}}function ng(r){let e=new Map;for(let{objectApiName:t,id:n,status:o}of r){let s=e.get(t)??[];s.push({id:n,status:o}),e.set(t,s)}return e}var zw=[["CreatedDate","LastModifiedDate","SystemModstamp"],["SystemModstamp"]],Hw=new Set(["CreatedDate","LastModifiedDate"]),Kw=new Set(["string","textarea","email","phone","url","picklist","multipicklist","combobox","encryptedstring"]);function Vw(r){return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function Is(r){return typeof r=="string"?Date.parse(r):Number.NaN}var rg="005",Id=class{ids=new Set;issued=0;idFor(e){this.issued++;let n=`${e&&/^[A-Za-z0-9]{3}$/.test(e)?e:"000"}SIM${String(this.issued).padStart(12,"0")}`;return this.ids.add(n),n}has(e){return this.ids.has(e)}};function Jw(r,e,t){return{...r,bulkWriteRecords:void 0,insertRecords:async(n,o,s)=>{let i=await t(n,o);return s.map(()=>({id:e.idFor(i),success:!0,errors:[]}))}}}function Qw(r,e,t){if(!r||!e)return"notRead";let n=r.source.RecordTypeId;return typeof n=="string"&&n!==""&&t.get(n)?.to===null?"decidedDefault":"RecordTypeId"in r.source&&Ia(n)?"masterInSource":"notRead"}function Yw(r,e){return{objectApiName:r,rows:e.rows,why:{...e.why},...e.predicted?{predicted:{...e.predicted}}:{},...e.readBack?{readBack:{...e.readBack,types:e.readBack.types.map(t=>({...t}))}}:{}}}function Ad(r,e){return[r[Pn],e?r[Hn]:"",r[mt]].map(t=>String(t??"")).join("|")}function og(r,e){let t=new Set(e??[]);return r.filter(n=>n.createable&&n.queryable&&!n.isReference&&!t.has(n.name)&&(n.type===void 0||Kw.has(n.type)))}var Xw=200,Zw="the standard price of its product, which it may not go without, changed since the sample";function ey(r){return r?{sample:r}:{}}function ty(r){let e=r.options,t=Object.entries(e.rootWhere??{});return{seed:e.seed??Rn.seed,draw:e.draw??Rn.draw,parents:e.parents??Rn.parents,children:e.children??Rn.children,floor:e.floor??Rn.floor,...e.whole&&e.whole.length>0?{whole:[...e.whole]}:{},...e.window?{window:{...e.window}}:{},...t.length>0?{rootWhere:Object.fromEntries(t)}:{},...e.strata&&e.strata.length>0?{strata:[...e.strata]}:{}}}var lr=class{deps;isPaused=!1;pauseResolve=null;isAborted=!1;bulkCancel=new AbortController;sampling=new AbortController;running=null;constructor(e){this.deps=hh(e)}summarySoFar(){return this.running?this.summaryOf(this.running):void 0}pause(){this.isPaused||(this.isPaused=!0)}resume(){this.isPaused=!1;let e=this.pauseResolve;this.pauseResolve=null,e?.()}abort(){this.isAborted=!0,this.bulkCancel.abort(),this.sampling.abort();let e=this.pauseResolve;this.pauseResolve=null,this.isPaused=!1,e?.()}async bulkTransportOf(e,t){if(e.writeApi!=="auto"||e.dryRun||!this.deps.bulkWriteRecords)return;let n=await this.deps.duplicateRuleObjects?.(t).catch(()=>{}),o=n??sa;return Ye.info(`[forge] writing through the Bulk API: a job per ${Dr} rows of an object from ${2e3}, one at a time on a job limiter of the run's own; by REST: ${[...os,...o].join(", ")}`+(n?"":" (the target did not say which objects its duplicate rules watch)")),this.bulkCancel=new AbortController,this.isAborted&&this.bulkCancel.abort(),{signal:this.bulkCancel.signal,restOnly:new Set([...os,...o]),bulkUnsupported:new Set,manager:new ou(1)}}bulkUpdatesOf(e){let{bulk:t}=e,n=this.deps.bulkWriteRecords;return!t||!n?{}:{bulkUpdate:(o,s)=>n(e.targetOrgId,o,"update",s,{bulkManager:t.manager,signal:t.signal}),restOnly:t.restOnly,bulkUnsupported:t.bulkUnsupported}}async waitIfPaused(){if(this.isAborted)throw new be("Forge execution was aborted by user request. No further batches will be processed.");if(this.isPaused&&(await new Promise(e=>{this.pauseResolve=e}),this.isAborted))throw new be("Forge execution was aborted while paused. No further batches will be processed.")}anonymizeRows(e,t,n,o,s,i){let a=e.config.anonymization;if(!e.anonymize||!a)return n;let d=a.fields[t]??this.detectedPersonalFields(e,a,t,s);if(d.length===0)return n;let c=new Map(s.map(u=>[u.name,u]));return e.anonymize({objectApiName:t,records:n,sourceIds:o,fields:d.map(u=>{let l=c.get(u);return{name:i[u]??u,type:l?.type??"",...l?.length!==void 0?{length:l.length}:{}}}),methods:a.methods})}detectedPersonalFields(e,t,n,o){let s=e.detectedPersonalFields.get(n);if(s)return s;let i=t.personalFieldsOf?.(o.map(a=>({name:a.name,type:a.type??""})))??[];return e.detectedPersonalFields.set(n,i),i}async fieldExclusionsOfTheSource(e,t,n){let o=Object.keys(e);if(o.length===0)return{exclusions:{},unmatched:[]};let s=t.nodes.map(a=>a.objectApiName),i=new Map;for(let a of o){let d=s.find(c=>c.toLowerCase()===a.toLowerCase())??a;if(!i.has(d))try{let c=await this.deps.describeFields(n,d);i.set(d,c.map(u=>u.name))}catch(c){i.set(d,nr(c)?void 0:null)}}return ns(e,s,a=>i.has(a)?i.get(a):null)}fileCopyUnwired(){let{readFileBody:e,insertFile:t,remainingFileStorageMB:n}=this.deps;return e&&t&&n?null:"This session cannot copy files: it reads no file content or file storage. Nothing was read or written."}fileCopyDeps(){let{readFileBody:e,insertFile:t,remainingFileStorageMB:n}=this.deps;return!e||!t||!n?null:{queryRecords:(o,s)=>this.deps.queryRecords(o,s),readFileBody:e,insertFile:t,insertRecords:this.deps.insertRecords,remainingFileStorageMB:n}}anonymizerForRun(){if(this.deps.anonymize)return this.deps.anonymize;let e=new sp;return t=>e.anonymize(t)}async execute(e,t,n,o,s){this.isAborted=!1,this.isPaused=!1,this.pauseResolve=null;let i=this.deps.requestsSent?.(),a=jl(s);if(a.files){let j=uo(a.anonymization!==void 0,a.files.acceptedAsIs);if(j)throw new jn(j,"FILES_NOT_ACCEPTED");let F=this.fileCopyUnwired();if(F)throw new jn(F,"FILES_NOT_COPYABLE")}let d=await this.chooseTheRoots(a,t,a.dryRun?void 0:a.stream?.store),c=await bs(a.ownerMappings,j=>this.deps.queryRecords(n,j),or);if(c)throw c;let u=new Map,l=await this.recordTypeDecisionsOf(s?.decisions?.recordTypeMappings??[],t,n,u),f=await this.fieldExclusionsOfTheSource(a.fieldExclusions,e,t),p={...a,fieldExclusions:f.exclusions,...l.bySource.size===0?{}:{recordTypeMappings:gl(a.recordTypeMappings,l),recordTypeDecisions:l.bySource}},g=p.dryRun?new Id:null,h=p.excludedObjects,m=await this.withWhatStatusesNeed(es(e,h),t,h),R=p.isScoped?await this.withWhatItsRecordsComeWith(m.graph,t,h):m.graph,b=await this.withSellingModelOptions(await this.withTheCatalogItNeeds(R,t,h),t,h),k=this.deps.recordTypePicklists,O=p.dryRun?void 0:p.stream?.store,w=new Date;O?.beginPart(w),d&&O&&!d.fromTheJournal&&O.nameRoots({objectApiName:d.objectApiName,ids:[...d.ids],sha256:d.sha256,readAt:d.readAt,...d.query?{query:d.query}:{}});let A=Mu(),S=await this.bulkTransportOf(p,n),v={...S?{bulk:S}:{},config:p,sourceOrgId:t,targetOrgId:n,graph:b,onProgress:o,remapper:new qr(O),scopeCache:p.isScoped?new Wf:null,scopedBuilder:p.isScoped?new Sn:null,recordTypeMapper:p.recordTypeMappings?new gs:null,referenceDataMapper:new Ts((j,F)=>this.deps.queryRecords(j,F)),orphanExpander:new As(g?Jw(this.deps,g,async(j,F)=>this.deps.describeObject?this.deps.describeObject(j,F).then(B=>B.keyPrefix,()=>null):null):this.deps),batchWriter:new Ul(this.deps,this.deps.batchStrategy,void 0,A),splitting:A,smallerCallsSaid:new Map,failedObjects:new Set,failedInPart:new Set,heldInTheOrg:new Map,leftAside:new Map,turnsEnded:new Set,notCreatable:new Set,notInTarget:new Set,errors:[],truncatedObjects:new Set,cappedObjects:new Set,fieldExclusionsUnmatched:f.unmatched,pendingFkUpdates:[],owedToRowsWrittenBefore:[],deferredNodes:[],turnsAhead:new Set,waitingFor:new Map,readAgainUnder:new Map,askedForRowsThatNeedThem:new Map,targetHolds:new Map,targetReadsRefused:new Set,inactiveUsers:new Set,writesInactiveOwners:Vf(j=>this.deps.queryRecords(n,j)),ownersInactive:new Map,lookupsOutsideTheRun:new Map,lookupsHeldBack:new Map,parentsOutside:new Map,readAsParents:new Map,idsRead:O?{add:j=>O.noteRead(j),has:j=>O.wasRead(j)}:new Set,catalogNodes:[],preread:new Map,readByObject:new Map,notSent:new Map,failedReads:new Set,sourceKeyPrefixes:new Map,cursors:new Map,counted:new Map,tableRecordTypes:new Map,keyPrefixesAsked:new Set,readObjects:new Set(b.nodes.filter(j=>j.included).map(j=>j.objectApiName)),writtenObjects:new Set,sellingModels:b.nodes.some(j=>j.included&&j.objectApiName===jr),standardPricebookId:null,existingRecords:[],lifecycles:new Map,deferredStatuses:[],...O?{store:O}:{},secondPassInStore:!1,statusesGiven:!1,leftDrafts:new Set,statusChildren:m.added,pastDraft:new Map,heldForExclusions:new Map,namedByRowsHeldBack:new Map,readAtItsTurn:new Map,statusChildrenRead:new Map,anonymize:p.anonymization?this.anonymizerForRun():null,contactPoints:p.keepContactPoints?null:new vf(void 0,{upsertKeys:p.upsertMode==="auto"}),detectedPersonalFields:new Map,fileScope:new Map,files:null,fileContentFieldsLeftOut:new Map,maskedSourceFields:Yu(Qu(j=>this.deps.queryRecords(t,j)),async j=>({fields:await this.deps.describeFields(t,j)})),encryptedFieldsLeftOut:new Map,recordTypePicklists:new ll(k&&((j,F)=>k(n,j,F))),picklistChanges:new Ko,currencyChanges:new Fo,currencyChangesById:new Map,recordTypesGiven:new Map,recordTypesUnderTheLease:new Map,pricesSwappedSaid:[],pricesKeptAsRead:new Map,prices:{standsFor:new Map,convertedInto:new Map,written:new Map,keys:new Map},readsEverythingFirst:!1,writtenWithoutFields:new Map,leftEmptyByFilter:new Map,contactsOnTheirOwn:new Set,withTheirRecord:new Set,startedAt:w,writtenByThePlatform:new Map,personContactsOutsideTheSample:0,contactSentWith:new Map,leftToThePlatform:new Kc,emailsAfterTheirTask:[],taskTurnOver:!1,emailsInTwoPasses:!1,emailsLeftForTheirTask:0,emailsFirstPassRan:!1,syncedQuotesLeft:0,requestsBefore:i,...d?{roots:d}:{},readUnder:new Map,simulated:g,gaps:p.dryRun?new Iu:null,decisionsApplied:new Xi,mayHaveBeenWritten:new Map,sourceRecordTypes:new Map,recordTypeRows:u,successCount:0,updatedCount:0,linkedCount:0,linkedToCreatedCount:0,wouldInsertCount:0,failedCount:0,skippedCount:0};for(let[j,F]of p.writtenBefore)v.remapper.addExisting(j,F);for(let{decision:j,reason:F}of l.unresolved)v.errors.push({objectApiName:j.object,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(record type ${j.from} \u2192 ${j.to??"the default"})`,messages:[`The decision was not applied: ${F}.`]}]});this.running=v;try{return await this.runPasses(v)}catch(j){throw this.endBeforeTheEmailsThatWaited(v,v.emailsAfterTheirTask.length+v.emailsLeftForTheirTask,j instanceof be),this.saySyncedQuotesLeft(v),await this.readWrittenBetween(v),this.reportDraftsLeft(v),O?.settleReads(),ip(j,this.summaryOf(v)),j}finally{this.running===v&&(this.running=null),O?.settleReads(),O?.flush()}}async recordTypeDecisionsOf(e,t,n,o){if(e.length===0)return Zi([],[]);let s=this.deps.describeObject,i=async(c,u)=>s?s(c,u).then(l=>this.namedRecordTypes(o,c,l.recordTypes),()=>[]):[],a=[...new Set(e.map(c=>c.object))],d=await Promise.all(a.map(async c=>({objectApiName:c,source:await i(t,c),target:await i(n,c)})));return Zi(e,d)}async namedRecordTypes(e,t,n){if(!n.some(s=>!s.master))return n;let o=e.get(t);return o||(o=this.deps.queryRecords(t,Co).then(s=>Mo(s),()=>[]),e.set(t,o)),Bo(n,await o)}async targetObjectInfoOf(e,t){let n=await this.objectInfoOf(e.targetOrgId,t);return!n||!(e.gaps!==null||n.recordTypes.some(s=>!s.available&&!s.master)||e.config.decisions.namesARecordTypeBare(t))?n:{...n,recordTypes:await this.namedRecordTypes(e.recordTypeRows,e.targetOrgId,n.recordTypes)}}async withMaskedLeftOut(e,t,n,o,s){if(o.length===0)return n;let i=await e.maskedSourceFields(t).catch(()=>[]),a=i.filter(d=>!n.has(d)&&s(d)&&o.some(c=>c[d]!==null&&c[d]!==void 0));return this.noteEncryptedLeftOut(e,t,a),i.length>0?new Set([...n,...i]):n}noteEncryptedLeftOut(e,t,n){if(n.length===0)return;let o=e.encryptedFieldsLeftOut.get(t)??new Set;for(let s of n)o.add(s);e.encryptedFieldsLeftOut.set(t,o)}withoutFileContent(e,t,n,o){let s=n.filter(i=>xn(i)&&i.createable);if(o&&s.length>0){let i=e.fileContentFieldsLeftOut.get(t)??new Set;for(let a of s)i.add(a.name);e.fileContentFieldsLeftOut.set(t,i)}return n.filter(i=>!xn(i))}async readWrittenBetween(e){if(e.config.dryRun||e.writtenBetween)return;if(e.config.stream?.everything===!0&&e.store){await this.readWrittenBetweenByObject(e,e.store);return}let t=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let{objectApiName:o,sourceIds:s}of e.remapper.createdByObject()){let i=s.flatMap(d=>{let c=e.remapper.get(d);return c?[c]:[]});if(i.length===0)continue;let a=await this.auditDatesCopied(e,o);for(let d of kn(i)){let c=await this.writtenDatesOf(e.targetOrgId,o,d);if(!c)return;for(let u of c){let l=Is(u.SystemModstamp),f=h=>{let m=a?Number.NaN:Is(u[h]);return Number.isFinite(m)?m:l},p=f("CreatedDate"),g=f("LastModifiedDate");Number.isFinite(p)&&(t=Math.min(t,p)),Number.isFinite(g)&&(n=Math.max(n,g))}}}Number.isFinite(t)&&Number.isFinite(n)&&(e.writtenBetween={first:new Date(t).toISOString(),last:new Date(Math.max(t,n)).toISOString()})}async readWrittenBetweenByObject(e,t){let n=Vw(e.startedAt.getTime()-Ka),o=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY,i=!1;for(let{objectApiName:a,created:d}of t.countsByObject()){if(d===0)continue;let c=Be(a),l=[...await this.auditDatesCopied(e,a)?[]:[`SELECT MIN(CreatedDate) f, MAX(SystemModstamp) l FROM ${c} WHERE CreatedDate >= ${n}`],`SELECT MIN(SystemModstamp) f, MAX(SystemModstamp) l FROM ${c} WHERE SystemModstamp >= ${n}`],f=!1;for(let p of l)try{let[g]=await this.deps.queryRecords(e.targetOrgId,p),h=Is(g?.f),m=Is(g?.l);Number.isFinite(h)&&(o=Math.min(o,h)),Number.isFinite(m)&&(s=Math.max(s,m)),f=!0;break}catch{}f||(i=!0)}i&&(o=Math.min(o,e.startedAt.getTime()),s=Math.max(s,Date.now()+Ka)),Number.isFinite(o)&&Number.isFinite(s)&&(e.writtenBetween={first:new Date(o).toISOString(),last:new Date(Math.max(o,s)).toISOString()})}async writtenDatesOf(e,t,n){let o=Be(t);for(let s of zw)try{return await this.deps.queryRecords(e,`SELECT Id, ${s.join(", ")} FROM ${o} WHERE Id IN (${n})`)}catch{}}async auditDatesCopied(e,t){let n=o=>o.some(s=>Hw.has(s.name)&&s.createable);try{let[o,s]=await Promise.all([this.deps.describeFields(e.sourceOrgId,t),this.deps.describeFields(e.targetOrgId,t)]);return n(o)&&n(s)}catch{return!0}}async runPasses(e){let{config:t,graph:n,sourceOrgId:o,targetOrgId:s,onProgress:i}=e;e.scopeCache&&e.roots&&t.rootObjectApiName?e.scopeCache.add(t.rootObjectApiName,e.roots.ids):e.scopeCache&&t.rootRecordId&&t.rootObjectApiName&&e.scopeCache.add(t.rootObjectApiName,[t.rootRecordId]);let a=xl(n,t.isScoped?t.rootObjectApiName:void 0),d=this.streamsTheRun(e),c=!d&&vw(t);e.readsEverythingFirst=c,e.emailsInTwoPasses=d&&t.stream?.everything===!0,e.secondPassInStore=e.store!==void 0&&!c,c&&e.store&&e.pendingFkUpdates.push(...e.store.owedLeftByEarlierParts());let u=c?a:await this.singlePassOrder(e);if(c&&e.scopeCache)for(let O of u)O.included&&e.turnsAhead.add(O.objectApiName);if(n.nodes.some(O=>gt(O.objectApiName)))try{let[O,w]=await Promise.all([this.deps.queryRecords(o,mi),this.deps.queryRecords(s,mi)]),A=O[0]?.Id,S=w[0]?.Id;typeof A=="string"&&typeof S=="string"&&(e.standardPricebookId=A,e.remapper.addExisting(A,S),e.scopeCache?.add(Ut,[A]),e.readObjects.add(Ut),n.nodes.some(v=>v.included&&v.objectApiName===Ut)||e.scopeCache?.addRead(Ut,[]))}catch(O){e.errors.push({objectApiName:et,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(standard price book lookup)",messages:[V(O)]}]})}let l=new Map,f=this.deps.isObjectCreatable;if(f){let O=[...new Set(a.filter(w=>w.included&&!t.referenceDataObjects.has(w.objectApiName)).map(w=>w.objectApiName))];for(let w=0;w<O.length&&!this.isAborted;w+=6){let A=O.slice(w,w+6),S=await Promise.allSettled(A.map(async v=>f(s,v)));A.forEach((v,j)=>l.set(v,S[j]))}}for(let[O,w]of l)w.status!=="rejected"||!nr(w.reason)||(e.notInTarget.add(O),e.readObjects.delete(O),e.turnsAhead.delete(O));for(let O of n.nodes){let w=l.get(O.objectApiName);!O.included||w?.status==="fulfilled"&&!w.value||e.notInTarget.has(O.objectApiName)||e.writtenObjects.add(O.objectApiName)}d&&await this.planTheSample(e,u),d&&t.beforeWrite&&await this.countBeforeWrite(e,u);for(let O of u){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");if(!O.included){e.skippedCount++,i({objectName:O.objectApiName,status:"skipped",progress:100,message:`Skipped ${O.objectApiName} (${sw(O)})`});continue}if(e.notInTarget.has(O.objectApiName)){e.scopeCache&&O.objectApiName!==t.rootObjectApiName?(e.notInTargetPutOff??=[]).push(O):this.reportNotInTarget(O,e),await this.endTurn(O.objectApiName,e);continue}if(await this.skipForFailedParent(O,e)){await this.endTurn(O.objectApiName,e);continue}let w=l.get(O.objectApiName);if(w)if(w.status==="fulfilled")w.value||e.notCreatable.add(O.objectApiName);else{let A=w.reason;e.errors.push({objectApiName:O.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed)",messages:[`isObjectCreatable check failed: ${A instanceof Error?A.message:String(A)}`]}]})}c?await this.readInTurn(O,e):d&&this.streamsNode(O,e)?(await this.streamNode(O,e),e.turnsEnded.add(O.objectApiName),O.objectApiName===ut&&await this.writeEmailsAfterTheirTask(e)):(await this.readNode(O,e,!1,!0)&&await this.writeNode(O,e),e.turnsEnded.add(O.objectApiName),O.objectApiName===ut&&await this.writeEmailsAfterTheirTask(e),O.objectApiName===Se&&await this.mapContactsOfPersonAccounts(e),this.releaseRows(e,O.objectApiName))}let p=Pl(e.deferredNodes.splice(0,e.deferredNodes.length),e.catalogNodes,n.edges),g=p.map(O=>Ke.has(O.objectApiName)).lastIndexOf(!0);for(let[O,w]of p.entries()){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");await this.skipForFailedParent(w,e)||(c?(e.scopeCache&&Ke.has(w.objectApiName)&&(this.holdBackWhatHeldRowsCost(e),this.leaveOutWhatOnlyRowsHeldBackName(e,w.objectApiName)),await this.readNode(w,e,!1,!1),await this.readUnderWhatWaited(w.objectApiName,e,g>=0&&O>g?"after the catalog":"before the catalog")):await this.readNode(w,e,!1,!0)&&(await this.writeNode(w,e),e.turnsEnded.add(w.objectApiName),this.releaseRows(e,w.objectApiName)))}await this.readCatalogAgain(e,g<0?[]:p.slice(g+1)),await this.reportNotInTargetOfTheScope(e);for(let O of[...e.preread.keys()])this.releaseRows(e,O,!0);if(c){do this.holdBackWhatHeldRowsCost(e);while(this.holdBackWhatOnlyRowsHeldBackName(e));if(await this.readParentsOutsideTheGraph(e))do this.holdBackWhatHeldRowsCost(e);while(this.holdBackWhatOnlyRowsHeldBackName(e))}let h=this.deps.requestsSent?.();e.roots&&h!==void 0&&e.requestsBefore!==void 0&&(e.readRequests=h-e.requestsBefore);let m=t.stream?.everything===!0,R=t.files&&!m?await this.prepareFiles(e):[];if(c&&t.beforeWrite){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let O=await this.pricesTheGateCounts(e),w=jh(e).cappedObjects,A=await this.withoutWhatTheTargetHoldsByValue(e,await this.withoutWhatThePlatformWrites(e,await Promise.all([...e.preread].map(([j,F])=>this.toWriteAtTheGate(e,j,F,gt(j)?O:0))))),S=t.dryRun?0:await this.readBackRequests(e,A),v=await t.beforeWrite({objects:A,...w?{capped:w}:{},...S>0?{readBack:S}:{},...e.roots?{roots:Gm(e.roots)}:{},dryRun:t.dryRun});await this.afterTheGate(e,v,A)}if(c)for(let O of this.writeOrderOf(e)){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let w=e.preread.get(O.objectApiName);if(w&&!await this.skipForFailedParent(O,e,w.fieldInfos,w.records)&&(await this.writeNode(O,e),O.objectApiName===ut&&await this.writeEmailsAfterTheirTask(e),O.objectApiName===Se&&await this.mapContactsOfPersonAccounts(e),e.pendingFkUpdates.push(...this.owedNowWritten(e)),e.pendingFkUpdates.length>0&&!t.dryRun)){let A=e.pendingFkUpdates.splice(0,e.pendingFkUpdates.length),S=[],v=await _a({pendingFkUpdates:A,remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:s,enabled:!0,onProgress:i,deferUnresolved:!0,stillPending:S,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:this.patchedInTheJournal(e),onAnswered:()=>e.store?.flush(),onRefusedByFilter:(j,F,B)=>this.noteLeftEmptyByFilter(e,j,F,B),...this.secondPassOfTheSample(e)});v&&e.errors.push(v),e.pendingFkUpdates.push(...S)}}await this.writeEmailsAfterTheirTask(e),e.pendingFkUpdates.push(...this.owedNowWritten(e));let b=e.secondPassInStore?await this.secondPassFromTheJournal(e):await _a({pendingFkUpdates:this.sayLookupsOutsideTheClone(e,e.pendingFkUpdates),remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:s,enabled:!t.dryRun,onProgress:i,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:this.patchedInTheJournal(e),onAnswered:()=>e.store?.flush(),onRefusedByFilter:(O,w,A)=>this.noteLeftEmptyByFilter(e,O,w,A),...this.secondPassOfTheSample(e)});if(b&&e.errors.push(b),this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");R.length>0&&!t.dryRun?await this.writeFiles(e,R):m&&t.files&&!t.dryRun&&await this.copyFilesOfTheOrg(e,t.files.maxFileBytes),this.reportDraftsExclusionsLeave(e),await this.restoreStatuses(e),await this.giveTheLeaseBack(e);let k=e.orphanExpander.buildErrorReport();return k&&e.errors.push(k),this.saySyncedQuotesLeft(e),await this.readWrittenBetween(e),await this.readBackRecordTypes(e),this.summaryOf(e)}async afterTheGate(e,t,n){let o=t?t.splitAllowance:void 0;o!==void 0&&e.splitting.allowance.limitTo(o);let s=t?t.lease:void 0;s&&(e.lease=s,s.assigned>0&&await this.readAgainUnderTheLease(e,n))}async readAgainUnderTheLease(e,t){let n=this.deps.describeObjectAgain;if(!n)return;let o=await Promise.all(t.map(async({objectApiName:s,rows:i,counted:a})=>{if(!await this.mayGoWithoutRecordType(e,s,i,a))return[];try{let d=await n(e.targetOrgId,s);return[[s,d.recordTypes]]}catch{return[]}}));for(let[s,i]of o.flat())e.recordTypesUnderTheLease.set(s,i)}async mayGoWithoutRecordType(e,t,n,o){if(n.length===0&&(o?.rows??0)===0||!(await this.objectInfoOf(e.targetOrgId,t))?.recordTypes.some(d=>!d.master))return!1;if(n.length===0)return!0;let{config:i}=e;return!(e.preread.get(t)?.createableSet.has("RecordTypeId")===!0&&!(i.fieldExclusions[t]??[]).includes("RecordTypeId")&&i.fieldMappings[t]?.RecordTypeId===void 0)||n.some(d=>{let c=d.RecordTypeId;return typeof c!="string"||Ia(c)||i.recordTypeDecisions.get(c)?.to===null})}async readBackRequests(e,t){let o=(await Promise.all(t.map(({objectApiName:i,rows:a,counted:d})=>this.mayGoWithoutRecordType(e,i,a,d)))).filter(Boolean).length,s=e.recordTypeRows.has(e.targetOrgId)&&!e.config.dryRun;return o>0&&!s?o+1:o}async giveTheLeaseBack(e){let t=e.lease;if(t){e.lease=void 0;try{await t.giveBack()}catch(n){Ye.warn(`[forge] the mute's lease was not given back as the writes ended: ${V(n)}`)}}}async readBackRecordTypes(e){e.simulated||await Promise.all([...e.recordTypesGiven].map(async([t,n])=>{if(n.ids.length!==0)try{let o=await this.deps.queryRecords(e.targetOrgId,Nf(t,n.ids));n.readBack=Cf(o,n.types)}catch(o){n.readBack={read:0,types:[],unread:V(o)}}}))}async recordTypeCounter(e,t,n,o){let s=e.recordTypesUnderTheLease.get(t)??n?.recordTypes??[];if(!s.some(c=>!c.master))return;let i=await this.namedRecordTypes(e.recordTypeRows,e.targetOrgId,s),a=Pf(xf(i)),d=e.config.recordTypeDecisions;return(c,u)=>{let l=e.recordTypesGiven.get(t);l||(l={rows:0,why:{},...a?{predicted:a}:{},types:i,ids:[]},e.recordTypesGiven.set(t,l));let f=Qw(c,o,d);l.rows++,l.why[f]=(l.why[f]??0)+1,u!==void 0&&l.ids.length<Ff&&l.ids.push(u)}}streamsTheRun(e){let{config:t,graph:n}=e;return t.stream===void 0||t.isScoped?!1:t.stream.everything===!0?!0:t.files===void 0&&!n.nodes.some(o=>o.included&&o.objectApiName===$e)}async keysOfTheTable(e,t,n){let{config:o,sourceOrgId:s}=e;if(o.upsertMode!=="auto"||!this.deps.upsertRecords||e.simulated)return;let i=t.objectApiName,a={unique:new Set,sent:new Set};try{n.described??=await this.deps.describeFields(s,i);let d=new Set(o.fieldExclusions[i]??[]),c=o.fieldMappings[i]??{},u=n.described.filter(R=>R.externalId===!0&&R.createable&&R.queryable&&!d.has(R.name)&&c[R.name]===void 0);if(u.length===0)return a;let l=n.described.find(R=>R.name==="Id"),f=on({node:t,edges:e.graph.edges,fieldInfos:[...l?[l]:[],...u],scopedBuilder:null,scopeCache:null,extraWhere:this.filterOf(e,i),maxRecordsPerObject:this.readBound(e,t),inIdOrder:{}});if(f.kind!=="query"||f.statements.length!==1)return a;let p=f.limit??1/0,g=new Map(u.map(R=>[R.name,new Set])),h=0,m=Vt(this.deps,s,f.statements[0],o.stream?.pageSize,void 0,this.readOptionsOf(e,i));try{for await(let R of m){for(let b of R){if(h>=p)break;h++;for(let[k,O]of g){let w=b[k];typeof w!="string"||w.length===0||O.has(w)?g.delete(k):O.add(w)}}if(h>=p||g.size===0||this.isAborted)break}}finally{await m.return(void 0)}return{unique:new Set(g.keys()),sent:a.sent}}catch(d){return Ye.warn(`[forge] upsert: the external ids of ${i} could not be read \u2014 inserting it: `+V(d)),a}}streamsNode(e,t){let n=e.objectApiName;return!Ke.has(n)&&!gt(n)&&(n!==ut||t.config.stream?.everything===!0)&&!t.config.referenceDataObjects.has(n)}releaseRows(e,t,n=!1){if(e.config.stream?.everything!==!0||!n&&(Ke.has(t)||gt(t)))return;let o=e.preread.get(t);!o||o.records.length===0||e.preread.set(t,{...o,records:[]})}readsArchived(e,t){return e.config.stream?.everything===!0&&tf.has(t)}filterOf(e,t){let n=e.config.objectSoqlFilters?.[t];return this.readsArchived(e,t)?n?`(${n}) AND IsDeleted = false`:"IsDeleted = false":n}readOptionsOf(e,t){return this.readsArchived(e,t)?{all:!0}:void 0}async readWholeOf(e,t,n,o){let s=this.readOptionsOf(e,t);if(!s)return this.deps.queryRecords(e.sourceOrgId,n,o);let i=[],a=Vt(this.deps,e.sourceOrgId,n,void 0,void 0,s);for await(let d of a)for(let c of d)i.push(c);return i}readBound(e,t){if(e.sample?.drawn.has(t.objectApiName))return;let n=e.config.maxRecordsPerObject,o=n!==void 0&&n>0?Math.floor(n):void 0,s=this.streamsNode(t,e)?e.config.stream?.ceiling:void 0;return o===void 0?s:s===void 0?o:Math.min(o,s)}async chooseTheRoots(e,t,n){let o=e.roots,s=n?.resumes===!0,i=s?n?.roots:void 0;if(!o){if(i)throw Pe.of(Lr(i.objectApiName,"otherQuery"));return}let{objectApiName:a,cap:d}=o,c={cap:d,readTotal:o.readTotal,readingBound:ml(o.sourceRequestsLeft),...o.sourceRequestsLeft!==void 0?{sourceRequestsLeft:o.sourceRequestsLeft}:{}};if(s){if(!i)throw Pe.of(Sl(a));if(i.objectApiName.toLowerCase()!==a.toLowerCase())throw Pe.of(Lr(a,"otherQuery"));if(ta(i.ids)!==i.sha256)throw Pe.of(Lr(a,"changed"));return{objectApiName:a,from:"plan",...i.query?{query:i.query}:{},ids:new Set(i.ids),sha256:i.sha256,readAt:i.readAt,fromTheJournal:!0,...c}}let u,l=o.plan;if(l){let m=kl(l,{sourceOrgId:t,objectApiName:a,...o.query?{query:o.query}:{},...o.ids?{ids:o.ids}:{}});if(m)throw Pe.of(Lr(a,m));let R=o.planOfTheRunRetried===!0;if(Ip(l,new Date)<vp||o.query===void 0||R)return{objectApiName:a,from:"plan",...l.query?{query:l.query}:{},ids:new Set(l.ids),sha256:l.sha256,readAt:l.readAt,fromTheJournal:!1,...R?{ofTheRunRetried:!0}:{},...c};u={roots:l.ids.length,readAt:l.readAt}}let f,p,g;if(o.ids!==void 0){let m=o.ids.filter(R=>!Ol(R));if(m.length>0)throw Pe.of({code:"ROOTS_QUERY_REFUSED",message:`${JSON.stringify(m[0]?.slice(0,40))} is not the id of a record: name each ${a} record by its 15- or 18-character id. Nothing was read or written.`,roots:{objectApiName:a}});if(f=ea(o.ids),p="records",f.length>d)throw Pe.of(Br(a,d,p))}else if(o.query!==void 0){let m=yl(o.query);if(m)throw Pe.of(Yo(m,a));let R=o.chosen,b=R?R.ids.map(k=>({Id:k})):await this.deps.queryRecords(t,Qo(a,o.query,e.objectSoqlFilters?.[a],d));if(f=ea(b.flatMap(k=>typeof k.Id=="string"?[k.Id]:[])),p="query",g=R?.readAt,f.length>d)throw Pe.of(Br(a,d,p,o.query))}else throw new Error(`Internal error: the roots of ${a} were asked with neither a query nor ids.`);if(f.length===0)throw Pe.of(Xo(a,o.query,d));let h=g??new Date().toISOString();return o.keepAt!==void 0&&await Ep(o.keepAt,{sourceOrgId:t,fingerprint:o.fingerprint??"",objectApiName:a,...o.query?{query:o.query}:{},from:p==="records"?"records":"query",readAt:h,ids:f}),{objectApiName:a,from:p,...o.query?{query:o.query}:{},ids:new Set(f),sha256:ta(f),readAt:h,fromTheJournal:!1,...u?{readAgain:u}:{},...c}}holdTheRootsReading(e,t,n){let o=e.roots,s=this.deps.requestsSent?.();if(!o||s===void 0||e.requestsBefore===void 0)return;let i=s-e.requestsBefore;if(!(i+n<=o.readingBound))throw Pe.of(Al({roots:o.ids.size,bound:o.readingBound,sent:i,next:n,objectApiName:t,sourceRequestsLeft:o.sourceRequestsLeft}))}holdTheRootsRows(e,t){let n=e.roots;if(!n)return;let o=0;for(let i of e.readByObject.values())o+=i;if(o<=n.readTotal)return;let s=[...e.readByObject].filter(([i])=>i!==t).map(([i,a])=>({objectApiName:i,rows:a}));throw s.push({objectApiName:t,rows:e.readByObject.get(t)??0}),Pe.of(Tl(n.ids.size,n.readTotal,s))}async planTheSample(e,t){let{config:n,store:o}=e,s=n.stream?.everything===!0?n.stream.sample:void 0,i=o?.samplePlan;if(!s){if(i)throw new ir("SAMPLE_PLAN_MISMATCH","The run this one resumes copied a sample of the whole org: resume it as a sample. "+or);return}let a;if(i)try{a=await sr.open(i.dir,{sha256:i.sha256})}catch(d){throw d instanceof Os?new ir("SAMPLE_PLAN_GONE",`The plan of the sample the run resumes is ${d.refusal==="gone"?"no longer on this machine":"no longer as it was drawn"}: it cannot go on with the same records. ${or} Copy a new sample rather than resume this one.`):d}else{if(o?.resumes)throw new ir("SAMPLE_PLAN_MISMATCH",`The run this one resumes copied every record of the whole org, not a sample: resume it as it was set up. ${or}`);a=s.plan??await this.drawThePlan(e,t,s)}o&&!i&&o.nameSamplePlan({dir:a.dir,sha256:a.sha256}),e.sample=await this.runSampleOf(e,a)}async drawThePlan(e,t,n){let{config:o,sourceOrgId:s}=e,i=ty(n),a=t.filter(w=>w.included&&(e.writtenObjects.has(w.objectApiName)||o.referenceDataObjects.has(w.objectApiName))),d=new Map;for(let w of a)d.set(w.objectApiName,await this.deps.describeFields(s,w.objectApiName));let c=(w,A)=>A.nillable===!1&&e.graph.edges.some(S=>S.type==="master-detail"&&S.targetObject===w&&(A.referenceTo??[]).includes(S.sourceObject)),u=[],l=new Map;for(let w of a){let A=w.objectApiName,S=new Set(o.fieldExclusions[A]??[]),v=(d.get(A)??[]).filter(j=>j.isReference&&!S.has(j.name)).map(j=>({name:j.name,referenceTo:j.referenceTo??[],isMasterDetail:c(A,j),...j.nillable!==void 0?{nillable:j.nillable}:{},createable:j.createable,...j.updateable!==void 0?{updateable:j.updateable}:{}}));if(u.push({objectApiName:A,rows:w.recordCount,keyPrefix:(await this.objectInfoOf(s,A))?.keyPrefix??e.sourceKeyPrefixes.get(A)??null,fields:v}),this.streamsNode(w,e)&&!o.referenceDataObjects.has(A)){let j=await this.recordTypesOfTable(e,w);j&&j.closedInSource.length>0&&l.set(A,{closed:new Set(j.closedInSource.map(it)),lacking:new Set(j.lackingInSource.map(it))})}}let f=await n.budget(),p=e.standardPricebookId&&a.some(w=>gt(w.objectApiName))?await this.runCurrencies(e):void 0,g=p&&this.priceCurrencyWrittenIn(e,p.target),h=new Map;if(a.some(w=>w.objectApiName===$e)){let w=await this.averageEmailBytes(e,d.get($e)??[]);w!==void 0&&h.set($e,w)}let m=g?w=>p.target.active.has(w)?void 0:g(w):void 0;this.sampling=new AbortController,this.isAborted&&this.sampling.abort();let R=Date.now(),b;try{b=await yp({source:{pages:(w,A)=>Vt(this.deps,s,w,void 0,void 0,A),count:async(w,A)=>{let S=this.deps.countRecords;if(S)return A?S(s,w,A):S(s,w);let v=0,j=w.replace(/^SELECT COUNT\(\) FROM /,"SELECT Id FROM ");for await(let F of Vt(this.deps,s,j,void 0,void 0,A))v+=F.length;return v}},objects:u,order:a.map(w=>w.objectApiName),excluded:new Map([...o.excludedObjects].map(w=>[w,null])),referenceData:o.referenceDataObjects,fieldsOf:w=>d.get(w)?.filter(A=>A.queryable).map(A=>({name:A.name,...A.type!==void 0?{type:A.type}:{},...A.groupable!==void 0?{groupable:A.groupable}:{},...A.sortable!==void 0?{sortable:A.sortable}:{},...A.aggregatable!==void 0?{aggregatable:A.aggregatable}:{}})),filterOf:w=>o.objectSoqlFilters?.[w],options:i,budget:f,...o.stream?.wholeReadBound!==void 0?{maxRecordsPerObject:o.stream.wholeReadBound}:{},recordTypeVerdict:(w,A)=>{let S=l.get(w),v=it(A);return S?.lacking.has(v)?"recordTypeNotInTarget":S?.closed.has(v)?"heldBack":void 0},...n.sourceRequestsLeft!==void 0?{sourceRequestsLeft:n.sourceRequestsLeft}:{},...n.maxRows!==void 0?{maxRows:n.maxRows}:{},...m?{priceCurrencyWrittenIn:m}:{},...h.size>0?{averageBytes:h}:{},now:R,labelsOf:async(w,A)=>{if(A.toLowerCase()!=="recordtypeid")return;let S=(await this.objectInfoOf(s,w))?.recordTypes??[],v=new Map(S.map(j=>[it(j.recordTypeId),j.developerName]));return j=>typeof j=="string"?v.get(it(j)):void 0},signal:this.sampling.signal,...n.onProgress?{onProgress:n.onProgress}:{}})}catch(w){throw w instanceof gp?new ir("SAMPLE_TOO_LARGE",`${w.message} Or draw among fewer roots: a window of dates (--fit-window) or a filter on the roots of the large objects (--fit-where).`):w instanceof mp||this.isAborted?new be("Forge execution was aborted by user request. Remaining objects were not processed."):w}let{cut:k}=b;if(k.kind==="cannotFit"){let w=k.heaviest.map(B=>`${B.objectApiName} (${B.rows} records${B.whole?", copied whole":""})`).join(", "),A=b.strataFloors,S=k.noRoot?"the objects copied whole and the first root drawn with the records it brings":A?`the objects copied whole and the roots kept of each object and of each value of its strata (${A.roots} roots for the floors of ${A.values} values)`:"the objects copied whole and the roots kept of each object",v=k.noRoot?"Leave objects out (--exclude-object)":A?"Keep no root of each object and value (--fit-floor 0), stratify fewer objects (--fit-strata), leave objects out (--exclude-object)":"Keep no root of each object (--fit-floor 0), leave objects out (--exclude-object)",j=nw[k.limitedBy],F=k.limitedBy==="storage"||k.limitedBy==="within";throw new jd(`No sample of the whole org fits: ${S} take ${k.rows} records, ${(k.storageBytes/1048576).toFixed(1)} MB, ${j.past}; the heaviest are ${w}. ${or} ${v}${j.more}.`,k.heaviest,{limitedBy:k.limitedBy,...F?{needMB:Th(k.storageBytes,"up"),budgetMB:Th(k.limitedBy==="storage"&&f.storageBytes!==void 0?f.storageBytes:f.budget.bytes,"down")}:{},heaviest:k.heaviest.map(B=>B.objectApiName)})}let O=Rp({...b,cut:k},i,f.budget);return up(n.keepAt,{sourceOrgId:s,fingerprint:n.fingerprint,drawnAt:new Date,drawnBy:o.dryRun?"dryRun":"run",sample:O,...b.newestByIds.length>0?{newestByIds:b.newestByIds}:{},...b.oldestByIds.length>0?{oldestByIds:b.oldestByIds}:{},ids:[...k.ids].map(([w,A])=>({objectApiName:w,ids:A})),counts:{personAccounts:Object.fromEntries(k.personAccounts),byThePlatform:k.byThePlatform.map(w=>({...w}))}})}async averageEmailBytes(e,t){let n=og(t,e.config.fieldExclusions[$e]);if(n.length===0)return;let o=this.filterOf(e,$e);try{let s=await this.readWholeOf(e,$e,`SELECT Id, ${n.map(a=>a.name).join(", ")} FROM ${$e}${o?` WHERE ${o}`:""} LIMIT ${Xw}`);if(s.length===0)return;let i=0;for(let a of s)for(let[d,c]of Object.entries(a))d!=="Id"&&typeof c=="string"&&(i+=Buffer.byteLength(c,"utf8"));return Math.ceil(i/s.length)}catch(s){Ye.warn("[forge] the size of the emails could not be read before the sample was drawn: "+V(s));return}}async runSampleOf(e,t){let{manifest:n}=t,o=new Set(n.sample.whole.map(d=>d.objectApiName)),s=new Set([...e.writtenObjects].filter(d=>!o.has(d)&&!e.config.referenceDataObjects.has(d))),i=new Map,a=new Map;for(let d of s){let c=new Set;for await(let f of t.ids(d))for(let p of f)c.add(it(p));i.set(d,c);let l=c.values().next().value?.slice(0,3)??(await this.objectInfoOf(e.sourceOrgId,d))?.keyPrefix??e.sourceKeyPrefixes.get(d);l&&a.set(d,l)}return{plan:t,report:{...n.sample,plan:t.place},drawn:s,ids:i,prefixes:a,counts:n.counts??{personAccounts:{},byThePlatform:[]},gone:new Map,changed:new Map,leftEmpty:new Map,reads:new Map,withoutStandard:new Set}}drawnObjectNamed(e,t,n){let o=t.filter(s=>e.drawn.has(s));if(o.length!==0)return t.length===1?o[0]:o.find(s=>{let i=e.prefixes.get(s);return i!==void 0&&n.startsWith(i)})}inThePlan(e,t,n){return e.ids.get(t)?.has(it(n))===!0}outsideTheSample(e,t,n){let o=e.sample;if(!o)return!1;let s=this.drawnObjectNamed(o,t,n);return s===void 0?!1:!this.inThePlan(o,s,n)||o.gone.get(s)?.has(it(n))===!0}secondPassOfTheSample(e){let t=e.sample;return t?{outsideTheSample:n=>{let o=n.sourceRefId,s=[...t.drawn].find(i=>{let a=t.prefixes.get(i);return a!==void 0&&o.startsWith(a)});return s!==void 0&&this.outsideTheSample(e,[s],o)},onLeftOutsideTheSample:(n,o)=>this.noteLeftOutsideTheSample(e,n,o)}:{}}noteLeftOutsideTheSample(e,t,n){let o=e.sample;if(!o)return;let s=o.leftEmpty.get(t)??new Map;s.set(n,(s.get(n)??0)+1),o.leftEmpty.set(t,s)}async countToWriteOfThePlan(e,t,n){let o=t.objectApiName,s=e.config.stream?.resumeAfter.get(o),i=n.ids.get(o)??new Set,a=s&&Ft.test(s.lastId)?s.lastId:void 0,d=O=>a===void 0||Mr(O,a)>0,c=0;if(!s?.done)for(let O of i)d(O)&&c++;let u=Math.min(c,await this.writtenBeforeOf(e,t,s)),l=e.standardPricebookId,f=o===Ut&&l&&i.has(it(l))&&d(l)&&!e.config.writtenBefore.has(l)?Math.min(1,c-u):0,p=Math.max(0,c-u-f),g=Math.min(p,n.counts.personAccounts[o]??0),h=0;o===ce&&g>0&&await this.personAccountsInTarget(e)===!0&&(h=g);let m=n.counts.byThePlatform.find(O=>O.objectApiName===o);m&&(h+=Math.min(p-h,m.inPlan)),p-=h;let R=O=>n.report.dropped.filter(w=>w.objectApiName===o&&w.reason===O).reduce((w,A)=>w+A.rows,0),b={...u>0?{writtenBefore:u}:{},...f>0?{linkedToTarget:f}:{},...h>0?{byThePlatform:h}:{},...R("noParentInSource")>0?{noParentInSource:R("noParentInSource")}:{},...R("outsideFilter")>0?{outsideFilter:R("outsideFilter")}:{}},k=o===ce&&h>0?0:g;return{read:c,counted:{rows:p,...k>0?{personAccounts:Math.min(k,p)}:{}},...Object.keys(b).length>0?{leftOut:b}:{}}}async personContactsBeyondThePlan(e,t){if(!e.sample?.drawn.has(ce))return;let n=t.find(i=>i.objectApiName===ce),o=t.find(i=>i.objectApiName===Se)?.counted.personAccounts??0;if(!n||o<=0||await this.personAccountsInTarget(e)!==!0)return;let s=n.leftOut?.byThePlatform??0;o<=s||(n.leftOut={...n.leftOut,byThePlatform:o})}async readOfThePlan(e,t,n,o){let s=n.objectApiName,i=t.reads.get(s);if(i)return i;let a=await this.deps.describeFields(e.sourceOrgId,s),d=wp({objectApiName:s,columns:zt(a.filter(c=>!xn(c)),e.config.fieldExclusions[s]),sourceRows:n.recordCount,planRows:o});return t.reads.set(s,d),d}planRowsAfter(e,t,n){let o=e.ids.get(t);if(!o)return 0;if(n===void 0)return o.size;let s=0;for(let i of o)Mr(i,n)>0&&s++;return s}async*pagesOfThePlanByIds(e,t,n,o,s,i=!1){let a=Be(n),d=this.filterOf(e,a),c=Math.max(1,uu(a,du(o),d?`(${d})`:void 0));for await(let u of t.plan.ids(a,{...s!==void 0?{after:s}:{},size:c})){if(this.isAborted)return;let l=u.filter(g=>Ft.test(g));if(l.length===0)continue;let f=`SELECT ${o.join(", ")} FROM ${a} WHERE ${d?`(${d}) AND `:""}Id IN (${l.map(g=>`'${g}'`).join(", ")})`,p=await this.readWholeOf(e,a,f);if(p.sort((g,h)=>Mr(String(g.Id),String(h.Id))),i){let g=new Set(p.map(m=>it(String(m.Id)))),h=t.gone.get(a)??new Set;for(let m of l)g.has(it(m))||h.add(it(m));h.size>0&&t.gone.set(a,h)}yield p}}async rowsOfThePlan(e,t,n,o,s,i=!1){let a=[];for await(let d of this.pagesOfThePlanByIds(e,t,n,o,s,i))for(let c of d)a.push(c);return a}async*pagesOfThePlan(e,t,n,o,s){let i=n.objectApiName,a=o.lastId??o.resumeAfter,d=await this.readOfThePlan(e,t,n,this.planRowsAfter(t,i,a)),c=/^SELECT (.+?) FROM /.exec(s)?.[1]?.split(", ")??["Id"],u=d.by==="ids"?this.pagesOfThePlanByIds(e,t,i,c,a,!0):this.cursorKeptToThePlan(e,t,i,s,a);yield*js(u,e.config.stream?.writeWindow??e.config.stream?.pageSize)}async*cursorKeptToThePlan(e,t,n,o,s){let i=t.ids.get(n)??new Set,a=new Set,d=Vt(this.deps,e.sourceOrgId,o,void 0,()=>e.truncatedObjects.add(n),this.readOptionsOf(e,n));try{for await(let u of d){let l=u.filter(f=>{let p=it(String(f.Id));return i.has(p)?(a.add(p),!0):!1});l.length>0&&(yield l)}}finally{await d.return(void 0)}let c=t.gone.get(n)??new Set;for(let u of i)!a.has(u)&&(s===void 0||Mr(u,s)>0)&&c.add(u);c.size>0&&t.gone.set(n,c)}sampleResultOf(e){let t=e.sample;if(!t||e.simulated)return;let n=new Map(e.remapper.countsByObject().map(i=>[i.objectApiName,i])),o=t.report,s=bp(o.roots);return{seed:o.seed,draw:o.draw,share:o.share,sha256:o.plan.sha256,drawnAt:o.plan.drawnAt,drawnBy:o.plan.drawnBy,...s?{roots:s}:{},objects:o.objects.map(i=>{let a=n.get(i.objectApiName),d=a?a.created+(a.linked??0):0,c=e.store?.earlierRecordsOf(i.objectApiName)??0;return{...i,written:Math.min(i.kept,d+c),goneSinceTheSample:t.gone.get(i.objectApiName)?.size??0,changedSinceTheSample:t.changed.get(i.objectApiName)??0}}),...t.leftEmpty.size>0?{leftEmpty:[...t.leftEmpty].flatMap(([i,a])=>[...a].map(([d,c])=>({objectApiName:i,field:d,rows:c})))}:{}}}async countBeforeWrite(e,t){let{config:n}=e,o=n.beforeWrite;if(!o)return;let s=n.stream?.everything===!0,i=[],a=[],d=new Set,c=[],u=[];for(let A of t){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let S=A.objectApiName;if(!A.included||!e.writtenObjects.has(S))continue;let v=s&&!this.streamsNode(A,e);if(n.referenceDataObjects.has(S)){v&&c.push({objectApiName:S,rows:await this.rowsOf(e,A)});continue}let{read:j,counted:F,leftOut:B,capped:E,partial:_}=e.sample?.drawn.has(S)?await this.countToWriteOfThePlan(e,A,e.sample):await this.countToWrite(e,A);e.counted.set(S,j),E&&a.push(S),_&&d.add(S),v&&!e.sample?.drawn.has(S)&&c.push({objectApiName:S,rows:j}),s&&u.push({node:A,read:j,whole:v}),i.push({objectApiName:S,rows:[],counted:F,...B?{leftOut:B}:{}})}let l=e.sample?.drawn.has(ze)?void 0:i.find(A=>A.objectApiName===ze),f=i.find(A=>A.objectApiName===We),p=l?await this.rolesThePlatformWritesOfTheTables(e,t,i,d):void 0;if(l&&p!==void 0&&p>0){let A=Math.min(p,l.counted.rows);l.counted={...l.counted,rows:l.counted.rows-A},l.leftOut={...l.leftOut,byThePlatform:A}}let g=f?.leftOut?.writtenBefore??0,h=l?this.rolesThePlatformMayWriteOfTheCounts(e,l.counted.rows,(p===void 0?f?.counted.rows??0:0)+g):0;if(l&&h>0&&(l.mayBeByThePlatform=p!==void 0?{rows:h,before:!0}:{rows:h}),await this.personContactsBeyondThePlan(e,i),this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let m=s?await this.heldAtTheGate(e,t,i):void 0;m&&(m.requests+=await this.pricesReplacedAtTheGate(e,i)),m&&(m.requests+=await this.directRelationsAtTheGate(e,i,d));let R=s?await this.measureTheWholeOrg(e,i,c,u,m):void 0,b=R&&e.sample?{...R,sample:{report:e.sample.report,byThePlatform:e.sample.counts.byThePlatform}}:R;if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let k=xs(n),O=n.dryRun&&!s?0:await this.readBackRequests(e,i),w=await o({objects:i,...k!==void 0&&a.length>0?{capped:{perObject:k,objects:a}}:{},...O>0?{readBack:O}:{},...b?{wholeOrg:b}:{},dryRun:n.dryRun});await this.afterTheGate(e,w,i)}async heldAtTheGate(e,t,n){let{config:o}=e,s=t.filter(h=>h.included&&e.writtenObjects.has(h.objectApiName)&&!o.referenceDataObjects.has(h.objectApiName)),i=new Map(s.map((h,m)=>[h.objectApiName,m])),a=new Map,d=new Map,c=new Map,u=$h,l=new Map,f=(h,m,R)=>{let b=a.get(h)??new Map;b.has(m)||u<=0||(b.set(m,R),a.set(h,b),u--)},p={requests:0,lookups:new Map},g=async(h,m)=>{let R=await this.idsUnder(e,h,m);return p.requests+=Math.max(1,Math.ceil((R?.length??0)/Dn)),R};for(let h of s){if(this.isAborted)break;let m=h.objectApiName;if(e.sample?.drawn.has(m))continue;if(u>0&&this.streamsNode(h,e)){let b=await this.recordTypesOfTable(e,h);if(b&&b.closed.length>0&&this.typesHeldRowByRow(e,b)){let k=new Set(b.lackingInSource);for(let[O,w]of[[b.closedInSource.filter(A=>!k.has(A)),d],[b.lackingInSource,c]]){let A=O.map(v=>`'${v}'`).join(", ");if(!A)continue;let S=a.get(m)?.size??0;for(let v of await g(m,`RecordTypeId IN (${A})`)??[])f(m,v,"held");w.set(m,(a.get(m)?.size??0)-S)}}}let R=await this.deps.describeFields(e.sourceOrgId,m).catch(()=>[]);for(let b of R){let[k]=b.referenceTo??[],O=k===void 0?void 0:i.get(k);if(!b.isReference||(b.referenceTo??[]).length!==1||O===void 0||O>=(i.get(m)??0)||!b.createable||(o.fieldExclusions[m]??[]).includes(b.name)||!Qe(m,b.name,b.nillable)||(p.lookups.set(m,(p.lookups.get(m)??0)+1),u<=0))continue;let w=Be(b.name),A=await g(m,`${w} != null AND ${w} NOT IN (SELECT Id FROM ${Be(k)})`);for(let F of A??[])f(m,F,{field:b.name,parentObject:k,reason:fd(b.name,k)});let S=a.get(k);if(!S||S.size===0)continue;let v=[...S].filter(([,F])=>F==="held").map(([F])=>F),j=[...S].filter(([,F])=>F!=="held").map(([F])=>F);for(let[F,B]of[[v,"held"],[j,{field:b.name,parentObject:k,reason:Eh(b.name,k)}]])for(let E of kn(F)){if(u<=0)break;for(let _ of await g(m,`${w} IN (${E})`)??[])f(m,_,B)}}for(let b of R){if(!b.isReference||b.name==="RecordTypeId"||!b.createable||(o.fieldExclusions[m]??[]).includes(b.name)||(b.referenceTo??[]).length===1&&Qe(m,b.name,b.nillable))continue;let k=new Set;for(let w of b.referenceTo??[]){let A=w===m?void 0:a.get(w);if(!(!A||A.size===0))for(let S of kn([...A.keys()])){let v=await g(m,`${Be(b.name)} IN (${S})`);for(let j of v??[])k.add(j)}}for(let w of a.get(m)?.keys()??[])k.delete(w);if(k.size===0)continue;let O=l.get(m)??[];O.push({field:b.name,rows:k.size}),l.set(m,O)}}for(let h of n){let m=l.get(h.objectApiName);m&&(h.leftEmpty=m)}for(let h of n){let m=a.get(h.objectApiName);if(!m||m.size===0)continue;let R=d.get(h.objectApiName)??0,b=c.get(h.objectApiName)??0,k=[...m.values()].filter(S=>S==="held").length,O=m.size-k,w=Math.max(0,h.counted.rows-m.size),A=h.counted.personAccounts;h.counted={rows:w,...A!==void 0&&Math.min(A,w)>0?{personAccounts:Math.min(A,w)}:{}},h.leftOut={...h.leftOut,...R>0?{heldBack:(h.leftOut?.heldBack??0)+R}:{},...b>0?{recordTypeNotInTarget:(h.leftOut?.recordTypeNotInTarget??0)+b}:{},...k-R-b>0?{withoutParent:k-R-b}:{},...O>0?{noParentInSource:O}:{}}}for(let h of a.values())for(let[m,R]of h)e.heldInTheOrg.set(m,R);return p}async pricesReplacedAtTheGate(e,t){let n=t.find(h=>h.objectApiName===et);if(!n||n.counted.rows<=0||!e.standardPricebookId||(e.counted.get(et)??0)>$h)return 0;let o=await this.deps.describeFields(e.sourceOrgId,et).catch(()=>[]);if(!o.some(h=>h.name===mt))return 0;let s=["Id",tn,Pn,mt,...o.some(h=>h.name==="IsActive")?["IsActive"]:[],...e.sellingModels&&o.some(h=>h.name===Hn)?[Hn]:[]],i=this.filterOf(e,et),a=e.sample,d;try{d=a?.drawn.has(et)?await this.rowsOfThePlan(e,a,et,s):await this.readWholeOf(e,et,`SELECT ${s.join(", ")} FROM ${et}`+(i?` WHERE ${i}`:""))}catch(h){return Ye.warn(`[forge] the prices replaced in another currency could not be counted at the gate: ${V(h)}`),1}let c=Math.max(1,Math.ceil(d.length/Dn)),u=e.currencies===void 0,l=d.filter(h=>!e.heldInTheOrg.has(String(h.Id))),f=await this.priceCurrencyInput(e,l,o),p=c+(u&&e.currencies!==void 0?dw:0);if(!f){let h=e.oneCurrency===void 0,m=await this.pricesKeyOf(e);if(!m.oneCurrency)return p;let R=Math.min(n.counted.rows,wi(l,m).standsFor.length);return R>0&&(n.counted={...n.counted,rows:n.counted.rows-R},n.leftOut={...n.leftOut,currencyReplaced:R}),p+(h&&this.deps.orgCurrency?1:0)}let g=Math.min(n.counted.rows,Ca(f,[]).standsFor.size);return g===0||(n.counted={...n.counted,rows:n.counted.rows-g},n.leftOut={...n.leftOut,currencyReplaced:g}),p}async directRelationsAtTheGate(e,t,n){if(e.sample?.drawn.has(Cn))return 0;let o=t.find(p=>p.objectApiName===Cn);if(!o||o.counted.rows<=0||!t.some(p=>p.objectApiName===ce)||n.has(ce)||n.has(Cn))return 0;let s=this.deps.countRecords;if(!s)return 0;let i=e.config.stream?.resumeAfter.get(Cn),a=this.filterOf(e,Cn),d=[...a?[`(${a})`]:[],...i&&Ft.test(i.lastId)?[`Id > '${i.lastId}'`]:[],"IsDirect = true"],c;try{c=await s(e.sourceOrgId,`SELECT COUNT() FROM ${Cn} WHERE ${d.join(" AND ")}`)}catch(p){return Ye.warn(`[forge] the relations the platform writes with the contacts could not be counted at the gate: ${V(p)}`),1}let u=o.leftOut,l=(u?.writtenBefore??0)+(u?.withoutParent??0)+(u?.noParentInSource??0),f=Math.max(0,Math.min(c-l,o.counted.rows));return f===0||(o.counted={...o.counted,rows:o.counted.rows-f},o.leftOut={...u,byThePlatform:(u?.byThePlatform??0)+f}),1}async idsUnder(e,t,n){let o=e.config.stream?.resumeAfter.get(t),s=this.filterOf(e,t),i=[...s?[`(${s})`]:[],...o&&Ft.test(o.lastId)?[`Id > '${o.lastId}'`]:[],n];try{return(await this.readWholeOf(e,t,`SELECT Id FROM ${Be(t)} WHERE ${i.join(" AND ")}`)).map(d=>String(d.Id))}catch(a){Ye.warn(`[forge] the ${t} records held back could not be counted at the gate: ${V(a)}`);return}}async measureTheWholeOrg(e,t,n,o,s){let{config:i}=e,a=i.stream?.wholeReadBound,d=a===void 0?[]:n.filter(({rows:k})=>k>a).map(({objectApiName:k,rows:O})=>({objectApiName:k,rows:O,bound:a})),c=new Set(o.filter(k=>k.whole).map(k=>k.node.objectApiName)),{writes:u,restOnly:l}=await this.writesOfTheWholeOrg(e,t,c),f=o.find(({node:k})=>k.objectApiName===$e&&k.included),p=t.find(k=>k.objectApiName===$e)?.counted?.rows??0,g=f&&p>0?await this.emailBytesOf(e,f.node):void 0,h=i.files?await this.filesOfTheOrg(e,i.files.maxFileBytes):void 0,m=i.keepContactPoints?0:await this.phoneNumbersPastTheFiction(e,o),R=t.find(k=>k.objectApiName===Se)?.counted?.personAccounts??0,b=R>0&&await this.personAccountsInTarget(e)===!1?R:0;return{writes:u,...l?{restOnly:l}:{},...g!==void 0?{emailTextBytes:g}:{},...i.files?{files:h??{unmeasured:!0}}:{},sourceReads:await this.sourceReadsOf(e,o,n,h)+cw(o,s?.lookups),...s&&s.requests>0?{heldReads:s.requests}:{},...d.length>0?{readWholeOver:d}:{},...m>0?{contactPointsBlanked:m}:{},...b>0?{personAccountsAsBusiness:b}:{}}}async writesOfTheWholeOrg(e,t,n){let{config:o}=e,s=o.writeApi==="auto"&&this.deps.bulkWriteRecords!==void 0,i=e.bulk?.restOnly??new Set;if(s&&!e.bulk){let c=await this.deps.duplicateRuleObjects?.(e.targetOrgId).catch(()=>{});i=new Set([...os,...c??sa])}let a=o.stream?.writeWindow??o.stream?.pageSize??Dn,d=t.map(({objectApiName:c,counted:u})=>{let l=Math.max(0,u?.rows??0),f=s&&!i.has(c),p=n.has(c)?[l]:[...Array.from({length:Math.floor(l/a)},()=>a),...l%a>0?[l%a]:[]],g=0,h=0;for(let m of f?p:[])for(let R=0;R<m;R+=Dr){let b=Math.min(Dr,m-R);b<2e3||(g++,h+=b)}return{objectApiName:c,rows:l,jobs:g,jobRows:h,restRows:l-h}});return s?{writes:d,restOnly:i}:{writes:d}}async sourceReadsOf(e,t,n,o){let s=c=>Math.max(1,Math.ceil(Math.max(0,c)/Dn)),i=new Map;for(let{node:c,read:u}of t)i.set(c.objectApiName,u);for(let{objectApiName:c,rows:u}of n)i.set(c,u);let a=0;for(let[c,u]of i){let l=t.find(f=>f.node.objectApiName===c)?.node;a+=e.sample?.drawn.has(c)&&l?(await this.readOfThePlan(e,e.sample,l,u)).requests:s(u)}let d=t.find(({node:c})=>c.objectApiName===$e);if(d&&d.read>0&&t.some(({node:c})=>c.objectApiName===ut)){let c=await this.countOf(e,$e,"ActivityId != null");a+=s(Math.min(c??d.read,d.read))}if(e.config.files){let c=o?.count??0;a+=Sd.length+Math.ceil(c/Dn),a+=Math.ceil(c/kd)+c}return a}async rowsOf(e,t){return await this.countOf(e,t.objectApiName)??t.recordCount}async countOf(e,t,n){let o=this.deps.countRecords;if(!o)return;let s=this.filterOf(e,t),i=[...s?[`(${s})`]:[],...n?[n]:[]],a=i.length>0?` WHERE ${i.join(" AND ")}`:"",d=`SELECT COUNT() FROM ${Be(t)}${a}`,c=this.readOptionsOf(e,t);try{return await(c?o(e.sourceOrgId,d,c):o(e.sourceOrgId,d))}catch{return}}async emailBytesOf(e,t){let n=t.objectApiName;try{let o=await this.deps.describeFields(e.sourceOrgId,n),s=og(o,e.config.fieldExclusions[n]);if(s.length===0)return 0;let i=e.sample;if(i?.drawn.has(n)){let g=0,h=await this.rowsOfThePlan(e,i,n,["Id",...s.map(m=>m.name)],e.config.stream?.resumeAfter.get(n)?.lastId);for(let m of h)for(let[R,b]of Object.entries(m))R!=="Id"&&typeof b=="string"&&(g+=Buffer.byteLength(b,"utf8"));return g}let a=e.config.stream?.resumeAfter.get(n),d=this.filterOf(e,n),c=[...d?[`(${d})`]:[],...a&&Ft.test(a.lastId)?[`Id > '${a.lastId}'`]:[]],u=c.length>0?` WHERE ${c.join(" AND ")}`:"",l=["Id",...s.map(g=>g.name)].join(", "),f=0,p=Vt(this.deps,e.sourceOrgId,`SELECT ${l} FROM ${Be(n)}${u} ORDER BY Id`,e.config.stream?.pageSize,void 0,this.readOptionsOf(e,n));try{for await(let g of p){for(let h of g)for(let[m,R]of Object.entries(h))m!=="Id"&&typeof R=="string"&&(f+=Buffer.byteLength(R,"utf8"));if(this.isAborted)break}}finally{await p.return(void 0)}return f}catch(o){Ye.warn("[forge] the size of the emails could not be read \u2014 measured by their count: "+V(o));return}}async filesOfTheOrg(e,t){let n=0,o=0,s=0;for(let{object:i,size:a,where:d}of Sd){let c=[d,`${a} <= ${t}`].filter(Boolean).join(" AND "),u=[d,`${a} > ${t}`].filter(Boolean).join(" AND "),l=await this.sumOfFiles(e,i,a,c);if(!l)return;n+=l.bytes,o+=l.count;let f=await this.deps.countRecords?.(e.sourceOrgId,`SELECT COUNT() FROM ${i} WHERE ${u}`).catch(()=>{});s+=f??0}return{bytes:n,count:o,overCeiling:s}}async sumOfFiles(e,t,n,o){try{let[s]=await this.deps.queryRecords(e.sourceOrgId,`SELECT SUM(${n}) total, COUNT(Id) n FROM ${t} WHERE ${o}`),i=Number(s?.total??0),a=Number(s?.n??0);if(Number.isFinite(i)&&Number.isFinite(a))return{bytes:i,count:a}}catch{}try{let s=0,i=0,a=Vt(this.deps,e.sourceOrgId,`SELECT Id, ${n} FROM ${t} WHERE ${o} ORDER BY Id`,e.config.stream?.pageSize);try{for await(let d of a){for(let c of d){let u=c[n];s+=typeof u=="number"&&Number.isFinite(u)?u:0,i++}if(this.isAborted)break}}finally{await a.return(void 0)}return{bytes:s,count:i}}catch(s){Ye.warn(`[forge] the files of ${t} could not be measured: ${V(s)}`);return}}async phoneNumbersPastTheFiction(e,t){let n=0;for(let{node:o,read:s}of t){if(s===0||this.isAborted)continue;let i=o.objectApiName,a=new Set(e.config.fieldExclusions[i]??[]),c=(await this.deps.describeFields(e.sourceOrgId,i).catch(()=>[])).filter(u=>u.createable&&!a.has(u.name));for(let u of Ea(c)){if(u.kind!=="phone")continue;let l=await this.countOf(e,i,`${Be(u.name)} != null`);n+=Math.min(l??s,s)}}return Math.max(0,n-$f)}async countToWrite(e,t){let n=t.objectApiName,o=this.streamsNode(t,e),s=o?e.config.stream?.resumeAfter.get(n):void 0,i=this.filterOf(e,n),a=this.readOptionsOf(e,n),d=this.deps.countRecords,c=async z=>{if(!d)return;let J=[...i?[`(${i})`]:[],...z?[z]:[],...s&&Ft.test(s.lastId)?[`Id > '${s.lastId}'`]:[]],Me=J.length>0?` WHERE ${J.join(" AND ")}`:"",ke=`SELECT COUNT() FROM ${Be(n)}${Me}`;try{return await(a?d(e.sourceOrgId,ke,a):d(e.sourceOrgId,ke))}catch{return}},u=this.readBound(e,t),l=u===void 0?void 0:Math.max(0,u-(s?.read??0)),f=await c(),p=f??t.recordCount,g=l===void 0?p:Math.min(p,l),h=xs(e.config),m=h===void 0?void 0:Math.max(0,h-(s?.read??0)),R=m!==void 0&&l===m&&p>m,b=o?await this.recordTypesOfTable(e,t):void 0;if(b&&b.closed.length>0&&!this.typesHeldRowByRow(e,b))return{read:g,counted:{rows:0},...g>0?{leftOut:xh(b.closed,g)}:{}};let k=Math.min(g,await this.writtenBeforeOf(e,t,s)),O=n===Ut?Math.min(g-k,await this.standardBookOfTheTable(e,c)):0,w=g-k-O,A=k>0||O>0?{...k>0?{writtenBefore:k}:{},...O>0?{linkedToTarget:O}:{}}:void 0,S=z=>z===void 0?{rows:w}:{rows:w,personAccounts:z},v=g<p,j=z=>({read:g,counted:S(z),...A?{leftOut:A}:{},...R?{capped:!0}:{},...v?{partial:!0}:{}});if(n!==Se&&n!==ce||!(await this.deps.describeFields(e.sourceOrgId,n).catch(()=>[])).some(z=>z.name==="IsPersonAccount"))return j();let B=await c("IsPersonAccount = true"),E=B===void 0?void 0:Math.min(B,w);if(n!==ce||B===void 0||f===void 0)return j(E);let _=await this.personContactsTakenAsBusinessAtTheGate(e,c);if(_===void 0)return j(E);let ee=Math.max(0,B-_-(f-g)-k);if(ee===0)return j(E);let X=(E??0)-ee;return{read:g,counted:{rows:w-ee,...X>0?{personAccounts:X}:{}},leftOut:{...A,byThePlatform:ee},...R?{capped:!0}:{},...v?{partial:!0}:{}}}async standardBookOfTheTable(e,t){let n=e.standardPricebookId;return!n||!Ft.test(n)||e.config.writtenBefore.has(n)?0:this.filterOf(e,Ut)?Math.min(1,await t(`Id = '${n}'`)??0):1}async personContactsTakenAsBusinessAtTheGate(e,t){if(await this.personAccountsInTarget(e)!==!0)return;let n=await this.personRecordTypesInTarget(e);if(!n)return 0;let{config:o}=e;if(!((await this.deps.describeFields(e.sourceOrgId,Se).catch(()=>[])).some(d=>d.name==="RecordTypeId"&&d.createable)&&!(o.fieldExclusions[Se]??[]).includes("RecordTypeId")&&o.fieldMappings[Se]?.RecordTypeId===void 0)){let d=xa((await this.objectInfoOf(e.targetOrgId,Se))?.recordTypes);return d!==void 0&&!n.has(d.slice(0,15))?void 0:0}let a=(o.recordTypeMappings??[]).filter(d=>!n.has(d.targetId.slice(0,15))).map(d=>d.sourceId);if(a.length===0)return 0;if(a.every(d=>Ft.test(d)))return t(`IsPersonAccount = true AND Account.RecordTypeId IN (${a.map(d=>`'${d}'`).join(", ")})`)}async idsTheTargetLacks(e,t,n,o){return Hf({lookups:t.filter(s=>s.isReference&&o(s.name)),rows:n,ownerMappings:e.config.ownerMappings,outsideTheRun:s=>this.isOutsideTheRun(e,s),mapped:s=>e.remapper.get(s)!==void 0,known:e.targetHolds,refused:e.targetReadsRefused,inactive:e.inactiveUsers,query:s=>this.deps.queryRecords(e.targetOrgId,s),neverCopied:s=>vs(e,s)})}async inactiveOwnersToLeaveOut(e,t,n){if(!n||e.inactiveUsers.size===0)return;let o=Kf(t,e.inactiveUsers,e.config.ownerMappings);if(o.size!==0&&!await e.writesInactiveOwners())return o}isOutsideTheRun(e,t){return!e.writtenObjects.has(t)&&!e.failedObjects.has(t)&&!e.notInTarget.has(t)}noteLookupsOutsideTheRun(e,t,n,o){let s=wd(new Map,o);if(s.size===0)return;let i=e.lookupsOutsideTheRun.get(t)??new Map;for(let[a,d]of s){let c=n.find(l=>l.name===a)?.referenceTo?.[0]??a,u=i.get(a)??{parent:c,rows:0};u.rows+=d,i.set(a,u)}e.lookupsOutsideTheRun.set(t,i)}async noteLookupsHeldBack(e,t,n,o){let s=bd(new Map,o);if(s.size===0)return;let i=e.lookupsHeldBack.get(t)??new Map;for(let[a,d]of s){let c=i.get(a)??{parent:await this.parentNamed(e,n,a,o),rows:0};c.rows+=d,i.set(a,c)}e.lookupsHeldBack.set(t,i)}async parentNamed(e,t,n,o){let s=t.find(d=>d.name===n)?.referenceTo??[];if(s.length===1)return s[0];let i=o.find(d=>d.lookupsHeldBack?.includes(n))?.source[n],a=s.filter(d=>e.writtenObjects.has(d));if(typeof i=="string"&&a.length>0){let c=(await this.sourceKeyPrefixes(e,new Set(a))).get(i.slice(0,3));if(c)return c}return s[0]??n}async rowsWhoseParentTheTargetLacks(e,t,n,o,s){let i=new Map,{config:a}=t;if(a.referenceFallback!=="keep"||a.expandOrphanParents)return i;let d=n.filter(u=>{let l=u.referenceTo??[];return u.isReference&&s(u.name)&&l.length===1&&!vs(t,l[0])&&this.isOutsideTheRun(t,l[0])&&Qe(e.objectApiName,u.name,u.nillable)});if(d.length===0||o.length===0)return i;let c=await this.idsTheTargetLacks(t,d,o,()=>!0);return c.size===0||o.forEach((u,l)=>{for(let f of d){let p=u[f.name];if(!(typeof p!="string"||!c.has(p)||t.remapper.get(p))){i.set(l,{field:f.name,parentObject:(f.referenceTo??[])[0],notInTarget:!0});return}}}),i}rowsOfClosedTypes(e,t,n,o){let{config:s}=e,i=new Map(o.map(c=>[c.recordTypeId,c])),a=n.map(c=>({RecordTypeId:s.recordTypeDecisions.get(String(c.RecordTypeId))?.to===null?void 0:c.RecordTypeId}));e.recordTypeMapper&&s.recordTypeMappings&&(a=e.recordTypeMapper.apply(a,s.recordTypeMappings));let d=new Map;return n.forEach((c,u)=>{let l=a[u]?.RecordTypeId,f=typeof l=="string"?i.get(l):void 0;f&&d.set(c,{field:"RecordTypeId",parentObject:f.developerName,recordType:{...f,objectApiName:t.objectApiName}})}),d}async rowsHeldInTheWholeOrg(e,t,n,o,s){let i=new Map,a=new Map;if(t.config.stream?.everything!==!0||o.length===0)return{held:i,aside:a};let d=fw(t,e.objectApiName,n,s),c=new Set,u=new Map;o.forEach((l,f)=>{let p=t.heldInTheOrg.get(String(l.Id));if(p!==void 0&&p!=="held"){a.set(f,p);return}if(t.sample?.withoutStandard.has(it(String(l.Id)))){i.set(f,{field:Pn,parentObject:et,reason:Zw}),c.add(f);return}for(let{field:g,parent:h}of d){let m=l[g];if(typeof m!="string"||m===""||t.remapper.get(m))continue;let R=t.sample;if(R?.drawn.has(h)){this.inThePlan(R,h,m)?R.gone.get(h)?.has(it(m))?a.set(f,{field:g,parentObject:h,reason:lw(g,h)}):i.set(f,{field:g,parentObject:h}):(i.set(f,{field:g,parentObject:h,reason:uw(g,h)}),c.add(f));return}let b=t.heldInTheOrg.get(m);if(b==="held"){i.set(f,{field:g,parentObject:h});return}if(b){let O=b===vh?fd(g,h):Eh(g,h);a.set(f,{field:g,parentObject:h,reason:O});return}let k=u.get(h)??new Map;k.set(m,[...k.get(m)??[],{index:f,field:g}]),u.set(h,k)}});for(let[l,f]of u){let p=await this.idsInTheSource(t,l,[...f.keys()]);for(let[g,h]of f){let m=p===void 0||p.has(g.slice(0,15));m||t.heldInTheOrg.set(g,vh);for(let{index:R,field:b}of h)i.has(R)||a.has(R)||(m?i.set(R,{field:b,parentObject:l}):a.set(R,{field:b,parentObject:l,reason:fd(b,l)}))}}for(let l of i.keys())a.delete(l);if(c.size>0&&t.sample){let l=e.objectApiName;t.sample.changed.set(l,(t.sample.changed.get(l)??0)+c.size)}return{held:i,aside:a}}async idsInTheSource(e,t,n){let o=new Set;try{for(let s of kn(n)){let i=await this.deps.queryRecords(e.sourceOrgId,`SELECT Id FROM ${Be(t)} WHERE Id IN (${s})`);for(let a of i)o.add(String(a.Id).slice(0,15))}return o}catch(s){Ye.warn(`[forge] whether the source holds the ${t} records named could not be read: ${V(s)}`);return}}async writtenBeforeOf(e,t,n){let{writtenBefore:o}=e.config,s=t.objectApiName,i=e.store?.earlierRecordsOf(s,n!==void 0)??0;if(e.store&&i>0)return i;if(o.size===0||n)return 0;let a=(await this.objectInfoOf(e.sourceOrgId,s))?.keyPrefix??e.sourceKeyPrefixes.get(s);if(!a)return 0;let d=[];for(let p of o.keys())p.startsWith(a)&&d.push(p);let c=e.config.objectSoqlFilters?.[s],u=this.deps.countRecords;if(!c||d.length===0||!u)return d.length;let l=this.readOptionsOf(e,s),f=this.filterOf(e,s)??c;try{let p=0;for(let g of kn(d)){let h=`SELECT COUNT() FROM ${Be(s)} WHERE (${f}) AND Id IN (${g})`;p+=await(l?u(e.sourceOrgId,h,l):u(e.sourceOrgId,h))}return p}catch{return d.length}}async streamNode(e,t,n){let o=e.objectApiName,s=o===$e&&t.emailsInTwoPasses&&!n;s&&(t.emailsFirstPassRan=!0);let i=t.config.stream?.resumeAfter.get(zo(o,n?.name)),a={ended:!1,taken:0,read:i?.read??0,...i?{resumeAfter:i.lastId,lastId:i.lastId}:{},carry:Hm(),...n?{pass:n}:{}},d=n?void 0:this.readBound(t,e);if(i?.done||d!==void 0&&a.read>=d)return;let c=n?void 0:await this.recordTypesOfTable(t,e);if(c&&c.closed.length>0&&!this.typesHeldRowByRow(t,c)){let f=d===void 0?c.rows:Math.min(c.rows,d-a.read);this.holdBackTableForRecordTypes(e,t,c,f);return}let u=n?n.expected:t.counted.get(o)??Sh(e,d);a.carry.rowsLeft=n?()=>Math.max(0,u-a.carry.rows):()=>Math.max(0,u-(a.read-(i?.read??0)));let l=n?.stopped??`Stopped ${e.objectApiName}`;t.cursors.set(o,a);try{let f=n?void 0:await this.keysOfTheTable(t,e,a);for(f&&(a.carry.tableKeys=f);;){if(this.isAborted)throw a.carry.pages>0&&a.carry.rowsLeft()>0?this.stopStreamedNode(e,t,a.carry,0,l):a.carry.pages>0&&!(n&&a.carry.rows===0)&&this.endStreamedNode(e,t,a.carry,this.endOfAStreamedNode(t,o,n)),new be("Forge execution was aborted by user request. Remaining objects were not processed.");if(!await this.readNode(e,t,!1,!0))break;let p=n?t.preread.get(o)?.records??[]:void 0;if(await this.writeNode(e,t,p,a.carry),o===Se&&await this.mapContactsOfPersonAccounts(t),s&&await this.linkTasksOfTheEmailsWritten(t),await this.tellPage(t,e,a),a.ended)break}}finally{t.cursors.delete(o),await a.pages?.return(void 0)}t.store&&a.ended&&!a.failed&&a.lastId!==void 0&&t.store.checkpoint(o,{lastId:a.lastId,read:a.read,done:!0},n?.name),a.carry.pages>0&&!a.failed&&!(n&&a.carry.rows===0)&&this.endStreamedNode(e,t,a.carry,this.endOfAStreamedNode(t,o,n)),this.releaseRows(t,o)}endOfAStreamedNode(e,t,n){if(n)return{...n.end,again:!0};if(t!==$e||!e.emailsInTwoPasses)return{};let o=e.emailsLeftForTheirTask;return{say:this.endOfTheEmails(e,!1),...o>0?{note:`, ${$s(o)}`}:{}}}recordTypesOfTable(e,t){let n=t.objectApiName,o=e.tableRecordTypes.get(n);return o||(o=this.countRecordTypesOfTable(e,t),e.tableRecordTypes.set(n,o)),o}async countRecordTypesOfTable(e,t){let{config:n,sourceOrgId:o,targetOrgId:s}=e,i=t.objectApiName,a=await this.targetObjectInfoOf(e,i),d={closed:[],rows:0,target:a,closedInSource:[],lackingInSource:[]};if(!a||!a.recordTypes.some(c=>!c.available&&!c.master)&&!await this.mayLackRecordTypes(e,i,a)||(n.fieldExclusions[i]??[]).includes("RecordTypeId")||n.fieldMappings[i]?.RecordTypeId)return d;try{let[c,u]=await Promise.all([this.deps.describeFields(o,i),an(this.deps.describeFields,s,i).catch(()=>{})]);if(!c.some(F=>F.name==="RecordTypeId"&&F.createable)||u&&!u.creatable.has("RecordTypeId"))return d;let f=n.stream?.resumeAfter.get(i),p=this.filterOf(e,i),g=[...p?[`(${p})`]:[],...f&&Ft.test(f.lastId)?[`Id > '${f.lastId}'`]:[]],h=g.length>0?` WHERE ${g.join(" AND ")}`:"",m=`FROM ${Be(i)}${h}`,R=await this.readWholeOf(e,i,`SELECT RecordTypeId, COUNT(Id) n ${m} GROUP BY RecordTypeId`),b=R.reduce((F,B)=>F+(typeof B.n=="number"&&B.n>0?B.n:0),0),k=vu(R),O=async F=>[...$u(i,F,a.recordTypes),...await this.typesTheTargetLacks(e,i,F,a)],w=await O(this.recordTypesAsSent(e,k)),A=F=>{let B=new Set(F.map(E=>E.recordTypeId));return[...k.keys()].filter(E=>[...this.recordTypesAsSent(e,[[E,1]]).keys()].some(_=>B.has(_)))},S=(F,B)=>({closed:F,rows:B,target:a,closedInSource:A(F),lackingInSource:A(F.filter(E=>E.unmapped))}),v=this.readBound(e,t),j=v===void 0?void 0:Math.max(0,v-(f?.read??0));if(w.length>0&&j!==void 0&&b>j){let F=await this.recordTypesOfTheRowsRead(e,i,m,j);if(F)return S(await O(this.recordTypesAsSent(e,F.counts)),F.rows)}return S(w,b)}catch{return}}recordTypesAsSent(e,t){let{config:n}=e,o=new Map;for(let[s,i]of t){if(n.recordTypeDecisions.get(s)?.to===null)continue;let a=s;e.recordTypeMapper&&n.recordTypeMappings&&(a=e.recordTypeMapper.apply([{RecordTypeId:s}],n.recordTypeMappings)[0]?.RecordTypeId),typeof a=="string"&&o.set(a,(o.get(a)??0)+i)}return o}async typesTheTargetLacks(e,t,n,o){if(!e.recordTypeMapper||!e.config.recordTypeMappings)return[];if(!o||o.recordTypes.length===0)return[];if(Lo(t,n,o.recordTypes,[]).length===0)return[];let i=await this.sourceRecordTypesOf(e,t);return e.gaps?.knowRecordTypes(t,"source",i),Lo(t,n,o.recordTypes,i)}async mayLackRecordTypes(e,t,n){if(!e.recordTypeMapper||!e.config.recordTypeMappings||n.recordTypes.length===0)return!1;let s=((await this.objectInfoOf(e.sourceOrgId,t))?.recordTypes??[]).filter(a=>!a.master);if(s.length===0)return!1;let i=this.recordTypesAsSent(e,s.map(a=>[a.recordTypeId,1]));return Lo(t,i,n.recordTypes,[]).length>0}async recordTypesOfTheRowsRead(e,t,n,o){let s=!1;try{let i=await this.readWholeOf(e,t,`SELECT RecordTypeId ${n} ORDER BY Id LIMIT ${o}`,()=>{s=!0});if(s)return;let a=new Map;for(let d of i){let c=d.RecordTypeId;typeof c=="string"&&c!==""&&a.set(c,(a.get(c)??0)+1)}return{counts:a,rows:i.length}}catch{return}}typesHeldRowByRow(e,t){if(e.config.stream?.everything!==!0)return!1;let n=t.closed.reduce((o,s)=>o+s.recordCount,0);return t.rows>n}holdBackTableForRecordTypes(e,t,n,o){let s=e.objectApiName;t.gaps?.knowRecordTypes(s,"target",n.target?.recordTypes??[]);for(let i of n.closed)t.gaps?.add(Ph(i,n.target));t.failedObjects.add(s),t.failedCount+=o,t.errors.push({objectApiName:s,stage:"scope",failedCount:o,attemptedCount:0,samples:n.closed.map(i=>({recordSummary:`RecordType=${i.developerName} (${i.recordCount} record${i.recordCount===1?"":"s"})`,messages:[Do(i)]}))}),t.onProgress({objectName:s,status:"error",progress:100,message:`${$n(s,o,Qt(t,s))}: `+n.closed.map(Wo).join(" ")+" Objects that cannot be written without it will be skipped."})}async nextPage(e,t,n,o,s){if(n.ended)return[];let i=e.sample?.drawn.has(t.objectApiName)?e.sample:void 0,a=f=>i?this.pagesOfThePlan(e,i,t,n,f):Vt(this.deps,e.sourceOrgId,f,e.config.stream?.writeWindow??e.config.stream?.pageSize,()=>e.truncatedObjects.add(t.objectApiName),this.readOptionsOf(e,t.objectApiName));n.pages??=a(o);let d=e.config.stream?.everything===!0?ld:0,c;for(let f=0;;f++)try{c=await n.pages.next();break}catch(p){let g=Kh(p);if(!g&&!Vh(p)||f>=d||this.isAborted)throw p;let h=n.lastId===void 0?o:s?.(n.lastId);if(h===void 0)throw p;g||await Jh(Rh*2**f),Ye.warn(`[forge] ${t.objectApiName}: the source ${g?"let its cursor expire":"did not answer"} after ${n.read} row(s) \u2014 reading on from the last one (${f+1}/${d}): `+V(p)),n.pages=a(h)}if(c.done)return n.ended=!0,[];n.taken++;let u=c.value;n.room!==void 0&&(u.length>n.room&&(u=u.slice(0,n.room),n.ended=!0,(n.cutBy==="cap"?e.cappedObjects:e.truncatedObjects).add(t.objectApiName)),n.room-=u.length),n.read+=u.length;let l=u[u.length-1]?.Id;return typeof l=="string"&&(n.lastId=l),u}async readWhole(e,t,n){let o=e.sample;if(o?.drawn.has(t)){let d=/^SELECT (.+?) FROM /.exec(n)?.[1]?.split(", ")??["Id"];return this.rowsOfThePlan(e,o,t,d,void 0,!0)}let s=!1,i=()=>{s=!0,e.truncatedObjects.add(t)},a=await this.readWholeRows(e,n,i);if(s&&e.config.stream?.everything===!0)throw new Cs(t,e.config.stream.wholeReadBound);return a}async readWholeRows(e,t,n){let{stream:o}=e.config,s=o?.pageSize;if(s===void 0||!this.deps.queryPages)return this.deps.queryRecords(e.sourceOrgId,t,n);let i=(o?.everything===!0?o.wholeReadBound:o?.ceiling)??5e4,a=[],d=Vt(this.deps,e.sourceOrgId,t,s);try{for await(let c of d)if(a.push(...c),a.length>i)return n(),a.slice(0,i)}finally{await d.return(void 0)}return a}pagedLimit(e,t){let n=xs(e.config),o=n===void 0?void 0:n-t.read,s=e.config.stream?.ceiling,i=s===void 0?void 0:s-t.read;if(i===void 0&&o===void 0)return;let a=i!==void 0&&(o===void 0||i<o);return t.room=Math.max(0,(a?i:o)??0),t.cutBy=a?"ceiling":"cap",Math.max(1,t.room)}async tellPage(e,t,n){e.store&&n.lastId!==void 0&&e.store.checkpoint(t.objectApiName,{lastId:n.lastId,read:n.read},n.pass?.name);let o=e.config.stream?.onPage;if(!o)return;let s=e.preread.get(t.objectApiName)?.records??[],i=e.simulated?[]:s.flatMap(a=>{let d=a.Id;if(typeof d!="string"||!e.remapper.isCreated(d))return[];let c=e.remapper.get(d);return c?[{sourceId:d,targetId:c}]:[]});await o({objectApiName:t.objectApiName,...n.lastId!==void 0&&!n.pass?{checkpoint:{lastId:n.lastId,read:n.read}}:{},created:i})}endStreamedNode(e,t,n,o={}){let{config:s}=t,i=o.say??t.onProgress,a=e.objectApiName;this.mergePageReports(t,a,n),this.saySentOnTheirOwn(t,n.sentOnTheirOwn,n.onTheirOwnWhy);let d=o.again?[]:Qt(t,a),c=o.again?void 0:t.heldForExclusions.get(a),u=[...ud(n),...d],l=_n(u),f=v=>{t.failedObjects.add(a),i({objectName:a,status:"error",progress:100,message:v})};if(n.heldWhole!==void 0){f(`${$n(a,n.heldWholeRows,d)}: ${n.heldWhole} Objects that cannot be written without it will be skipped.`);return}if(n.rows===0&&c&&c.size>0){f(zr(a,c));return}let p=wh(n);if(n.personContactsUnlinked>0&&n.withTheirAccount===0&&n.sent===0&&n.writtenBefore===0&&n.withoutParent===0){f(`${$n(a,n.personContactsUnlinked,d)}: every record is a person account's contact, which the platform writes with its account, and the run has none of them in the target. Objects that cannot be written without it will be skipped.`);return}if(p===0&&n.failed===0&&n.sent===0&&n.withoutParent>0){f(`${$n(a,n.withoutParent,d)}: every record points at a parent this run did not write. Objects that cannot be written without it will be skipped.`);return}let g=p+n.failed,h=g>0?n.failed/g:0,m=n.failed>0&&n.alreadyExists===n.failed,R=n.failed>0&&!m&&(p===0||h>.5),b=Vo(n.picklists.list())+No(n.currencies.list())+gd(n.lookupsNotCarried)+Rd(n.ownersInactive)+md(n.lookupsOutsideTheRun)+yd(n.lookupsHeldBack)+Td(t,a),k=ss(n.writtenWithoutFields),O=tg(t,a),w=Oh(t,a),A=Bh(n.sentOnTheirOwn);if(R){p>0&&t.failedInPart.add(a),f(p===0?`Failed all ${a} records: ${n.failed+l} failed${cn(u)}${A}${b}${w}`:`${n.failed+l}/${g+l} ${a} records failed (>50%)${cn(u)}${A}${b}${k}${O}${w}`+Fh);return}let S=yh(n);i({objectName:a,status:"done",progress:100,message:`${o.label??`${s.dryRun?"Simulated":"Completed"} ${a}`}: ${hd(s,n,u,pd(t,a))}${o.note??""}${A}${S}${b}${k}${O}${Ps(t,a)}${w}`})}stopStreamedNode(e,t,n,o,s){let i=e.objectApiName,a=o+n.rowsLeft();Od(t,i,a),this.mergePageReports(t,i,n),this.saySentOnTheirOwn(t,n.sentOnTheirOwn,n.onTheirOwnWhy);let d=[...ud(n),...Qt(t,i)],c=wh(n),u=c+n.failed,l=n.failed>0&&n.alreadyExists!==n.failed&&(c===0||n.failed/u>.5);l&&t.failedObjects.add(i),l&&c>0&&t.failedInPart.add(i),t.onProgress({objectName:i,status:l?"error":"stopped",progress:100,message:`${s}: ${hd(t.config,n,d,pd(t,i))}, ${a} not sent${Bh(n.sentOnTheirOwn)}${yh(n)}${Vo(n.picklists.list())}${No(n.currencies.list())}${gd(n.lookupsNotCarried)}${Rd(n.ownersInactive)}${md(n.lookupsOutsideTheRun)}${yd(n.lookupsHeldBack)}${Td(t,i)}${ss(n.writtenWithoutFields)}${Ps(t,i)}`})}mergePageReports(e,t,n){if(n.withoutParent>0&&!n.withoutParentSaid){let i={objectApiName:t,stage:"scope",failedCount:n.withoutParent,attemptedCount:0,samples:$d(n.withoutParentGroups,e.failedObjects)},a=e.errors.findIndex(d=>d.objectApiName===t&&d.stage==="insert");a===-1?e.errors.push(i):e.errors.splice(a,0,i),n.withoutParentSaid=!0}let o=e.errors.filter(i=>i.objectApiName===t&&i.stage==="insert");if(o.length>0){let[i]=o,a={...i,failedCount:o.reduce((u,l)=>u+l.failedCount,0),attemptedCount:n.succeeded+n.updated+n.linked+n.failed,samples:o.flatMap(u=>u.samples).slice(0,Tw)},d=e.errors.indexOf(i),c=e.errors.filter(u=>!o.includes(u));c.splice(d,0,a),e.errors.splice(0,e.errors.length,...c)}let s=e.existingRecords.filter(i=>i.objectApiName===t);if(s.length>1){let i=s.reduce((u,l)=>u+(l.linkedToCreated??0),0),a={objectApiName:t,linked:s.reduce((u,l)=>u+l.linked,0),...i>0?{linkedToCreated:i}:{},unidentified:s.reduce((u,l)=>u+l.unidentified,0)},d=e.existingRecords.indexOf(s[0]),c=e.existingRecords.filter(u=>!s.includes(u));c.splice(d,0,a),e.existingRecords.splice(0,e.existingRecords.length,...c)}}async startAsDrafts(e,t,n){let o=new Map;if(e.config.dryRun)return o;let s=await this.lifecycleOf(e,t);return s&&n.forEach((i,a)=>{let d=To(i.Status,s);d&&(o.set(a,String(i.Status)),i.Status=d)}),o}async oweStatusesFoundAfterStop(e,t,n){let{store:o}=e;if(!o)return;let s=n.filter(a=>{let d=a.Id;return typeof d=="string"&&o.wasFoundAfterStop(d)});if(s.length===0)return;let i=await this.lifecycleOf(e,t);if(i)for(let a of s){if(!To(a.Status,i))continue;let d=e.config.writtenBefore.get(String(a.Id));d&&this.oweStatus(e,t,d,String(a.Status))}}async lifecycleOf(e,t){let n=tu[t];if(!n||!this.deps.updateRecords)return;let o=e.lifecycles.get(t);return o||(o=nu(s=>this.deps.queryRecords(e.targetOrgId,s),n),e.lifecycles.set(t,o)),o}async notePastDraft(e,t,n){if(!([...e.statusChildren.values()].some(({parent:a})=>a===t)||e.config.excludedObjects.size>0&&Ar[t]!==void 0))return;let s=await this.lifecycleOf(e,t);if(!s)return;let i=e.pastDraft.get(t)??new Map;for(let a of n){let d=a.Id;typeof d=="string"&&To(a.Status,s)&&i.set(d,String(a.Status))}e.pastDraft.set(t,i)}async restoreStatuses(e){let t=this.deps.updateRecords;if(t&&e.store){await this.restoreStatusesFromTheJournal(e,t);return}if(!t||e.deferredStatuses.length===0)return;let n=e.deferredStatuses.splice(0,e.deferredStatuses.length);for(let[o,s]of ng(n)){let i=0,a=[];for(let d=0;d<s.length;d+=is.rest){let c=s.slice(d,d+is.rest),u;try{u=await t(e.targetOrgId,o,c.map(({id:l,status:f})=>({Id:l,Status:f})))}catch(l){u=c.map(({id:f})=>({id:f,success:!1,errors:[V(l)]}))}c.forEach(({id:l,status:f},p)=>{let g=u[p];g?.success||(i++,a.length<3&&a.push({recordSummary:`${o} ${l} Status=${f}`,messages:g?.errors??["No result returned for the status update"]}))})}e.onProgress({objectName:o,status:i>0?"error":"done",progress:100,message:`Restored the status of ${s.length-i}/${s.length} ${o} records written as drafts`}),i>0&&e.errors.push({objectApiName:o,stage:"insert",failedCount:i,attemptedCount:s.length,samples:a})}}async restoreStatusesFromTheJournal(e,t){let{store:n}=e;if(!n||e.statusesGiven||n.statusesOwed().size===0)return;e.statusesGiven=!0;let o=new Map,s=new Map,i=async a=>{let d=s.get(a)??[];if(s.set(a,[]),d.length===0)return;let c=o.get(a);if(!c)return;let u;try{u=await t(e.targetOrgId,a,d.map(({id:l,status:f})=>({Id:l,Status:f})))}catch(l){u=d.map(({id:f})=>({id:f,success:!1,errors:[V(l)]}))}d.forEach(({id:l,status:f},p)=>{let g=u[p];if(g?.success){n.gaveStatus(a,l);return}c.failed++,c.samples.length<3&&c.samples.push({recordSummary:`${a} ${l} Status=${f}`,messages:g?.errors??["No result returned for the status update"]})})};for(let{objectApiName:a,id:d,status:c}of n.statusLines()){if(e.leftDrafts.has(d)||n.statusGiven(d))continue;let u=o.get(a)??{entries:0,failed:0,samples:[]};u.entries++,o.set(a,u);let l=s.get(a)??[];l.push({id:d,status:c}),s.set(a,l),l.length>=is.rest&&await i(a)}for(let[a,{entries:d,failed:c,samples:u}]of o)await i(a),e.onProgress({objectName:a,status:c>0?"error":"done",progress:100,message:`Restored the status of ${d-c}/${d} ${a} records written as drafts`}),c>0&&e.errors.push({objectApiName:a,stage:"insert",failedCount:c,attemptedCount:d,samples:u})}reportDraftsExclusionsLeave(e){let t=e.config.excludedObjects;if(t.size===0)return;let n=new Set;for(let[s,i]of Object.entries(Ar)){let a=e.pastDraft.get(s);if(!a||a.size===0)continue;let d=e.statusChildrenRead.get(s),c=[];for(let[u,l]of a){let f=e.remapper.get(u);if(!e.config.dryRun&&!f)continue;let p;if(t.has(i.object))p=`${i.object} is excluded from this run`;else if(d&&!d.kept.has(u)){let h=d.held.get(u);h&&(p=`none of its ${i.object} records can be written without ${h.excluded}`+(h.target?Kr(h.target):", which is excluded from this run"))}if(!p)continue;f&&n.add(f);let g=f!==void 0&&!e.simulated?.has(f)?f:u;c.push({recordSummary:`${s} ${g} Status=${l}`,messages:[`Left a draft: the platform gives ${s} this status only with ${i.object} records under it, and ${p}.`]})}c.length!==0&&e.errors.push({objectApiName:s,stage:"insert",failedCount:c.length,attemptedCount:c.length,samples:c.slice(0,3)})}if(n.size===0)return;for(let s of n)e.leftDrafts.add(s);let o=e.deferredStatuses.splice(0,e.deferredStatuses.length);e.deferredStatuses.push(...o.filter(({id:s})=>!n.has(s)))}reportDraftsLeft(e){if(e.store){if(e.statusesGiven)return;e.statusesGiven=!0;for(let[n,{count:o,samples:s}]of e.store.statusesOwed())e.errors.push({objectApiName:n,stage:"insert",failedCount:o,attemptedCount:o,samples:s.map(({id:i,status:a})=>({recordSummary:`${n} ${i} Status=${a}`,messages:["Written as a draft, and the run stopped before giving it this status back: it stays a draft."]}))});return}let t=e.deferredStatuses.splice(0,e.deferredStatuses.length);for(let[n,o]of ng(t))e.errors.push({objectApiName:n,stage:"insert",failedCount:o.length,attemptedCount:o.length,samples:o.slice(0,3).map(({id:s,status:i})=>({recordSummary:`${n} ${s} Status=${i}`,messages:["Written as a draft, and the run stopped before giving it this status back: it stays a draft."]}))})}async skipForFailedParent(e,t,n,o){let s=u=>iw(e.objectApiName,t.graph,u).filter(l=>t.failedObjects.has(l)&&!t.failedInPart.has(l)),i=s(n??[]);if(i.length===0)return!1;if(!n)try{if(i=s(await this.deps.describeFields(t.sourceOrgId,e.objectApiName)),i.length===0)return!1}catch{}t.skippedCount++,t.failedObjects.add(e.objectApiName);let a=o?.filter(u=>!dn(t.config,u)).length??t.counted.get(e.objectApiName);a!==0&&(t.failedCount+=a??0,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:a??0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:[...i.map(u=>`Not written: its records cannot be written without ${u}, which failed in this run.`),...a===void 0?["Skipped before its records were read: how many there were is not known."]:[]]}]}));let d=Qt(t,e.objectApiName),c=(a??0)+_n(d);return t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (parent failed)`+(c>0?`: ${c} failed${cn(d)}`:"")}),!0}async rowsWithoutTheirParent(e,t,n,o){let s=new Map;o.forEach((u,l)=>{for(let f of n){let[p]=f.referenceTo??[];if(!f.isReference||(f.referenceTo??[]).length!==1||p===e.objectApiName||!t.failedInPart.has(p)||!Qe(e.objectApiName,f.name,f.nillable))continue;let g=u[f.name];if(typeof g=="string"&&g&&!t.remapper.get(g)){s.set(l,{field:f.name,parentObject:p});return}}});let i=n.filter(u=>u.isReference&&(u.referenceTo??[]).length>1&&Qe(e.objectApiName,u.name,u.nillable)),a=[];if(o.forEach((u,l)=>{for(let f of i){let p=u[f.name];typeof p=="string"&&p&&!t.remapper.get(p)&&a.push({index:l,field:f.name,id:p})}}),a.length===0)return s;let d=new Set(t.graph.nodes.filter(u=>u.included).map(u=>u.objectApiName));d.delete(e.objectApiName);let c=await this.sourceKeyPrefixes(t,new Set(i.flatMap(u=>(u.referenceTo??[]).filter(l=>d.has(l)))));for(let{index:u,field:l,id:f}of a){let p=c.get(f.slice(0,3));p&&!s.has(u)&&s.set(u,{field:l,parentObject:p})}return s}async sourceKeyPrefixes(e,t){let n=[];for(let s of t){if(e.sourceKeyPrefixes.has(s))continue;let i=e.preread.get(s)?.records.find(a=>typeof a.Id=="string");i?e.sourceKeyPrefixes.set(s,String(i.Id).slice(0,3)):n.push(s)}for(let s=0;s<n.length;s+=6){let i=n.slice(s,s+6),a=await Promise.all(i.map(d=>this.objectInfoOf(e.sourceOrgId,d)));i.forEach((d,c)=>{let u=a[c]?.keyPrefix;u&&e.sourceKeyPrefixes.set(d,u)})}let o=new Map;for(let s of t){let i=e.sourceKeyPrefixes.get(s);i&&!o.has(i)&&o.set(i,s)}return o}async keyPrefixesNamedBy(e,t){let n=new Set(e.graph.nodes.map(s=>s.objectApiName)),o=new Set;for(let s of t){let i=s.isReference?s.referenceTo??[]:[];if(!(i.length<2))for(let a of i)n.has(a)&&!e.keyPrefixesAsked.has(a)&&o.add(a)}if(o.size>0){for(let s of o)e.keyPrefixesAsked.add(s);await this.sourceKeyPrefixes(e,o)}return e.sourceKeyPrefixes}async excludedByKeyPrefix(e,t,n){let o=e.config.excludedObjects;if(o.size===0)return new Map;let s=new Set;for(let d of n){let c=d.isReference?d.referenceTo??[]:[];if(!(c.length<2||!Qe(t,d.name,d.nillable)))for(let u of c)o.has(u)&&s.add(u)}let i=new Set([...s].filter(d=>!e.keyPrefixesAsked.has(d)));if(i.size>0){for(let d of i)e.keyPrefixesAsked.add(d);await this.sourceKeyPrefixes(e,i)}let a=new Map;for(let d of s){let c=e.sourceKeyPrefixes.get(d);c&&!a.has(c)&&a.set(c,d)}return a}async objectOfSourceId(e,t,n){let o=t.slice(0,3),s=n.find(u=>e.sourceKeyPrefixes.get(u)===o);if(s)return s;let i=new Set(e.graph.nodes.map(u=>u.objectApiName)),a=n.filter(u=>!e.sourceKeyPrefixes.has(u)),d=a.filter(u=>!i.has(u)),c=[a.filter(u=>i.has(u))];for(let u=0;u<d.length;u+=6)c.push(d.slice(u,u+6));for(let u of c){let l=(await this.sourceKeyPrefixes(e,new Set(u))).get(o);if(l)return l}}writeOrderOf(e){return this.orderByFields(e,new Map([...e.preread].map(([t,n])=>[t,n.fieldInfos])))}orderByFields(e,t){let n=e.parentsOutside.size>0?{...e.graph,nodes:[...e.graph.nodes,...e.parentsOutside.values()]}:e.graph,o=new Set(n.nodes.filter(c=>c.included).map(c=>c.objectApiName)),s=[],i=[];for(let[c,u]of t){Jm(u)&&i.push(c);for(let l of u)if(!(!l.isReference||!Tr(l)||!Qe(c,l.name,l.nillable)))for(let f of l.referenceTo??[])f===c||!o.has(f)||s.push({sourceObject:f,targetObject:c,relationshipName:l.name,type:"lookup",required:!0})}let a=Nl(o,i),d=t.get(et)?.some(c=>c.name===mt);return ra(ts(n,t),[...s,...a,...d?Mf(o,i,[...s,...a]):[],...Ti(o),...ji(o,t),..._f(o,t),...xi(o)])}async singlePassOrder(e){let t=e.graph.nodes.filter(o=>o.included);if(!t.some(o=>gt(o.objectApiName))){let o=new Set(t.map(i=>i.objectApiName)),s=new Map;return o.has(Se)&&o.has(ce)&&(await Promise.allSettled([Se,ce].map(a=>this.deps.describeFields(e.sourceOrgId,a)))).forEach((a,d)=>{a.status==="fulfilled"&&s.set([Se,ce][d],a.value)}),ra(ts(e.graph,s),[...Ti(o),...ji(o,s),...xi(o)])}let n=new Map;for(let o=0;o<t.length&&!this.isAborted;o+=6){let s=t.slice(o,o+6);(await Promise.allSettled(s.map(a=>this.deps.describeFields(e.sourceOrgId,a.objectApiName)))).forEach((a,d)=>{a.status==="fulfilled"&&n.set(s[d].objectApiName,a.value)})}return this.orderByFields(e,n)}async withWhatStatusesNeed(e,t,n){let o=new Set(e.nodes.map(d=>d.objectApiName)),s=new Map,i=[],a=[];for(let d of e.nodes){if(this.isAborted)break;let c=Ar[d.objectApiName];if(!d.included||!c||o.has(c.object)||s.has(c.object)||n.has(c.object))continue;let u;try{u=await this.deps.describeFields(t,c.object)}catch{continue}let l=u.find(f=>f.name===c.lookup&&f.isReference&&(f.referenceTo??[]).includes(d.objectApiName));l&&(s.set(c.object,{parent:d.objectApiName,lookup:c.lookup}),i.push(Ur(c.object,u,d.level+1)),a.push({sourceObject:d.objectApiName,targetObject:c.object,relationshipName:l.name,type:"lookup",required:Qe(c.object,l.name,l.nillable)}))}return s.size===0?{graph:e,added:s}:{graph:{...e,nodes:[...e.nodes,...i],edges:[...e.edges,...a]},added:s}}async withWhatItsRecordsComeWith(e,t,n){let o=new Set(e.nodes.map(a=>a.objectApiName)),s=[],i=[];for(let a of e.nodes){if(this.isAborted)break;let d=zm[a.objectApiName];if(!a.included||!d||o.has(d.object)||n.has(d.object))continue;let c;try{c=await this.deps.describeFields(t,d.object)}catch{continue}let u=c.find(l=>l.name===d.lookup&&l.isReference&&(l.referenceTo??[]).includes(a.objectApiName));u&&(o.add(d.object),s.push(Ur(d.object,c,a.level+1)),i.push({sourceObject:a.objectApiName,targetObject:d.object,relationshipName:u.name,type:"lookup",required:Qe(d.object,u.name,u.nillable)}))}return s.length===0?e:{...e,nodes:[...e.nodes,...s],edges:[...e.edges,...i]}}async withTheCatalogItNeeds(e,t,n){let o=Il(e,n);if(o.size===0)return e;let s=new Set(e.edges.map(u=>`${u.sourceObject}|${u.targetObject}`)),i=new Map,a=new Map,d=[],c=e.nodes.filter(u=>u.included);for(;c.length>0&&!this.isAborted;){let u=[];for(let l=0;l<c.length&&!this.isAborted;l+=6){let f=c.slice(l,l+6);(await Promise.allSettled(f.map(({objectApiName:g})=>this.deps.describeFields(t,g)))).forEach((g,h)=>{if(g.status!=="fulfilled")return;let{objectApiName:m,level:R}=f[h];a.set(m,g.value);for(let b of g.value){let k=b.referenceTo??[];if(!b.isReference||k.length!==1)continue;let[O]=k;O===m||!(o.has(O)||i.has(O))||El(m,b)&&(o.delete(O)&&(i.set(O,R+1),u.push({objectApiName:O,level:R+1})),!s.has(`${O}|${m}`)&&(s.add(`${O}|${m}`),d.push({sourceObject:O,targetObject:m,relationshipName:b.name,type:"lookup",required:Qe(m,b.name,b.nillable)})))}})}c=u}return i.size===0?e:{...e,nodes:[...e.nodes,...[...i].map(([u,l])=>Ur(u,a.get(u)??[],l))],edges:[...e.edges,...d]}}async withSellingModelOptions(e,t,n){let o=u=>e.nodes.find(l=>l.included&&l.objectApiName===u),s=o(Zo),i=o(jr);if(!o(et)||!s||!i||n.has(Gt)||e.nodes.some(u=>u.objectApiName===Gt))return e;let a;try{a=await this.deps.describeFields(t,Gt)}catch{return e}let d=Ur(Gt,a,Math.max(s.level,i.level)+1),c=(u,l)=>({sourceObject:u,targetObject:Gt,relationshipName:l,type:"lookup",required:!0});return{...e,nodes:[...e.nodes,d],edges:[...e.edges,c(Zo,"Product2Id"),c(jr,"ProductSellingModelId")]}}summaryOf(e){let t=this.deps.requestsSent?.(),{simulated:n}=e,o=e.config.stream?.summaryBound;if(e.store&&o!==void 0&&e.remapper.count>o)return this.summaryOfTheJournal(e,t);let s=e.remapper.toJSON();if(n)for(let[c,u]of Object.entries(s))n.has(u)&&delete s[c];let i=c=>c in s,a=Gh(e),d=[...e.mayHaveBeenWritten].map(([c,u])=>({objectApiName:c,sourceIds:[...u]}));return{successCount:e.successCount,updatedCount:e.updatedCount,linkedCount:e.linkedCount,...e.linkedToCreatedCount>0&&!n?{linkedToCreatedCount:e.linkedToCreatedCount}:{},wouldInsertCount:e.wouldInsertCount,failedCount:e.failedCount,skippedCount:e.skippedCount,remapCount:Object.keys(s).length,errors:[...e.errors,...kw(e),...yw(e),...Ew(e),...Iw(e),...Pw(e),...Gw(e)],truncatedObjects:[...e.truncatedObjects],...jh(e),...e.fieldExclusionsUnmatched.length>0?{fieldExclusionsUnmatched:[...e.fieldExclusionsUnmatched]}:{},...ow(e),remapTable:s,existingRecords:[...e.existingRecords],existingSourceIds:e.remapper.existingSourceIds().filter(i),updatedSourceIds:e.remapper.updatedSourceIds().filter(i),...a.length>0&&!n?{withTheirRecordSourceIds:a}:{},...e.writtenByThePlatform.size>0?{writtenByThePlatform:[...e.writtenByThePlatform].map(([c,u])=>({objectApiName:c,rows:u}))}:{},...e.leftEmptyByFilter.size>0&&!n?{lookupsLeftEmptyByFilter:[...e.leftEmptyByFilter].flatMap(([c,u])=>[...u].map(([l,{records:f,ids:p}])=>({objectApiName:c,field:l,records:f,recordIds:[...p]})))}:{},remapByObject:n?[]:e.remapper.countsByObject(),...e.notSent.size>0?{notSentByObject:[...e.notSent].map(([c,u])=>({objectApiName:c,notSent:u}))}:{},createdByObject:n?[]:e.remapper.createdByObject(),readByObject:[...e.readByObject].map(([c,u])=>({objectApiName:c,read:u,...this.originOf(e,c,u)})),failedReads:[...e.failedReads],...e.files?{files:structuredClone(e.files)}:{},...e.fileContentFieldsLeftOut.size>0?{fileContentFieldsLeftOut:[...e.fileContentFieldsLeftOut].map(([c,u])=>({objectApiName:c,fields:[...u].sort()}))}:{},...e.encryptedFieldsLeftOut.size>0?{encryptedFieldsLeftOut:[...e.encryptedFieldsLeftOut].map(([c,u])=>({objectApiName:c,fields:[...u].sort()}))}:{},...e.picklistChanges.size>0?{picklistValuesChanged:e.picklistChanges.list()}:{},...e.currencyChanges.size>0?{currenciesReplaced:e.currencyChanges.list()}:{},...e.recordTypesGiven.size>0?{recordTypesGiven:[...e.recordTypesGiven].map(([c,u])=>Yw(c,u))}:{},...e.writtenWithoutFields.size>0?{writtenWithoutFields:[...e.writtenWithoutFields].map(([c,{rows:u,fields:l}])=>({objectApiName:c,rows:u,fields:l.map(f=>({...f}))}))}:{},contactPoints:e.contactPoints?e.contactPoints.report():{neutralized:!1,fields:[],values:0},...e.writtenBetween?{writtenBetween:{...e.writtenBetween}}:{},...e.requestsBefore!==void 0&&t!==void 0?{apiCalls:t-e.requestsBefore}:{},...n?{dryRun:!0}:{},...e.gaps?{gaps:e.gaps.list(e.config.decisions.ignoredGaps)}:{},...e.decisionsApplied.size>0?{decisionsApplied:e.decisionsApplied.list()}:{},...d.length>0?{mayHaveBeenWritten:d}:{},...ey(this.sampleResultOf(e)),...e.roots?{roots:this.rootsResultOf(e,e.roots)}:{},...e.roots&&e.readRequests!==void 0?{reads:{source:e.readRequests}}:{}}}originOf(e,t,n){let o=e.roots;if(!o)return{};let s=t===e.config.rootObjectApiName,i=0;if(s)for(let u of o.ids)e.idsRead.has(u)&&i++;i=Math.min(i,n);let a=0;for(let u of e.scopeCache?.reachedOf(t)??[])s&&o.ids.has(u)||a++;let d=Math.min(a,n-i),c=e.readUnder.get(t);return{origin:{roots:i,under:d,named:n-i-d},...c&&c.size>0?{readUnder:[...c]}:{}}}rootsResultOf(e,t){let n=[],o=[],s=0,i=0,a=0,d=e.errors.find(m=>m.objectApiName===t.objectApiName)?.samples.flatMap(m=>m.messages)[0]??"not written",c=new Set(e.remapper.updatedSourceIds()),u=new Set(Gh(e)),l=new Map((e.preread.get(t.objectApiName)?.records??[]).map(m=>[String(m.Id),m])),f=m=>{let R=l.get(m);return e.simulated!==null&&t.objectApiName===ce&&R!==void 0&&rn(R)&&!e.contactsOnTheirOwn.has(m)&&typeof R.AccountId=="string"&&e.remapper.wasCreated(R.AccountId)},p=0,g=[],h=(m,R)=>{if(g.length>=bn)return;let b=R&&e.simulated===null?e.remapper.get(m):void 0;g.push(b!==void 0?{source:m,target:b}:{source:m})};for(let m of t.ids){if(!e.idsRead.has(m)){n.push(m),h(m,!1);continue}s++,e.remapper.wasCreated(m)||c.has(m)?(i++,h(m,!0)):u.has(m)||f(m)?(i++,p++,h(m,!0)):e.remapper.isExisting(m)?(a++,h(m,!0)):(o.push({id:m,reason:d}),h(m,!1))}return{objectApiName:t.objectApiName,from:t.from,...t.query?{query:{...t.query}}:{},cap:t.cap,asked:t.ids.size,read:s,gone:n,written:i,linked:a,failed:o,sha256:t.sha256,readAt:t.readAt,...t.readAgain?{readAgain:{...t.readAgain}}:{},...p>0?{withTheirAccount:p}:{},ids:g,...t.ids.size>g.length?{idsLeftOut:t.ids.size-g.length}:{},...t.ofTheRunRetried?{ofTheRunRetried:!0}:{}}}summaryOfTheJournal(e,t){let n=this.summaryOf({...e,config:{...e.config,stream:e.config.stream&&{...e.config.stream,summaryBound:void 0}},remapper:new qr,store:void 0,withTheirRecord:new Set,linkedToCreatedCount:0}),o=e.store?.withTheirRecordCount??0,s=e.store?.linkedToCreatedCount()??0;return{...n,remapCount:e.remapper.count,...o>0?{withTheirRecordCount:o}:{},...s>0?{linkedToCreatedCount:s}:{},remapByObject:e.remapper.countsByObject(),...e.requestsBefore!==void 0&&t!==void 0?{apiCalls:t-e.requestsBefore}:{},remapInJournal:!0}}async prepareFiles(e){let{config:t,onProgress:n}=e,o=t.files,s=this.fileCopyDeps();if(!o||!s)return[];let i=await Yf({scope:e.fileScope,sourceOrgId:e.sourceOrgId,maxFileBytes:o.maxFileBytes,queryRecords:s.queryRecords}),a=Xf(i);if(a&&!t.dryRun)throw new jn(`${a} Nothing was written.`,"FILES_UNREAD");e.errors.push(...i.errors);let d=await this.filesCopiedBefore(e,i.files,s),c={...i,files:d.filter(p=>p.into?.unchanged!==!0)},u;if(c.files.length>0)try{u=await np(s,e.targetOrgId)}catch(p){let g=`The file storage the target has left could not be read (${V(p)}), so the files could not be checked against it.`;if(!t.dryRun)throw new jn(`${g} Nothing was written.`,"FILE_STORAGE_UNREAD");e.errors.push(qa(g))}e.files=rp(c,o.maxFileBytes,u),a&&(e.files.lookupFailure=a);let l=ep(c.files),f=u===void 0?null:tp(l,u);if(f&&u!==void 0&&!t.dryRun)throw new jn(`${f} Nothing was written.`,"FILE_STORAGE_EXCEEDED",{neededBytes:l,remainingBytes:u});if(f&&e.errors.push(qa(f)),t.dryRun){e.files.wouldCopy=c.files.map(({objectApiName:p,sourceId:g,name:h,bytes:m})=>({objectApiName:p,sourceId:g,name:h,bytes:m}));for(let p of e.files.objects)n({objectName:p.objectApiName,status:"done",progress:100,message:op(p)});return[]}return d}async filesCopiedBefore(e,t,n){let{store:o}=e;if(!o||e.config.dryRun)return t;let s=await Zf({files:t,targetOrgId:e.targetOrgId,copiedBefore:i=>{let a=o.mapping(i);return a?.earlier&&a.kind==="created"&&a.objectApiName?{objectApiName:a.objectApiName,targetId:a.targetId}:void 0},queryRecords:n.queryRecords});return e.errors.push(...s.errors),s.files}async writeFiles(e,t){let n=this.fileCopyDeps();if(!n||!e.files)return;let{remapper:o}=e;e.failedCount+=await Ua({files:t,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:s=>o.wasCreated(s),get:s=>o.get(s),add:(s,i,a)=>o.add(s,i,a),persist:()=>o.persist()},deps:n,report:e.files,errors:e.errors,waitIfPaused:()=>this.waitIfPaused(),onProgress:e.onProgress,...e.store?{calls:Es(e.store)}:{}})}async copyFilesOfTheOrg(e,t){let n=this.fileCopyDeps();if(!n)return;e.files??={maxFileBytes:t,objects:[],links:0,leftOut:[]};let o=e.files,s=0,i=(d,c)=>e.onProgress({objectName:d,status:"running",progress:50,message:c}),a=e.config.stream?.pageSize??Cw;for(let d of Sd){let{counted:c}=d,u=e.config.stream?.resumeAfter.get(zo(c,zh));if(u?.done)continue;let f=`SELECT ${d.object==="ContentVersion"?"Id, ContentDocumentId, Title, PathOnClient, ContentSize, SharingPrivacy":"Id, ParentId, Name, ContentType, BodyLength, IsPrivate"} FROM ${d.object} WHERE `+[d.where,`${d.size} <= ${t}`].filter(Boolean).join(" AND "),p=u?.read??0,g=u&&Ft.test(u.lastId)?u.lastId:void 0;for(let h=!1;!h;){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let m=await this.filesPageAfter(e,c,f,g,a);if(!m)break;h=m.length<a;let R=!0;for(let k=0;k<m.length;k+=kd){let O=m.slice(k,k+kd),w=d.object==="ContentVersion"?await this.documentsOnTheRunsRecords(e,O):Mw(e,O);if(!w){R=!1;break}if(w.length===0)continue;let A=await this.filesCopiedBefore(e,w,n);for(let v of A){if(v.into?.unchanged)continue;let j=Hh(o,v.objectApiName);j.planned++,j.plannedBytes+=v.bytes}s+=A.filter(v=>v.into?.unchanged).length,e.failedCount+=await Ua({files:A,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:v=>e.remapper.wasCreated(v),get:v=>e.remapper.get(v),add:(v,j,F)=>e.remapper.add(v,j,F),persist:()=>e.remapper.persist()},deps:n,report:o,errors:e.errors,waitIfPaused:()=>this.waitIfPaused(),onProgress:()=>{},...e.store?{calls:Es(e.store)}:{}});let S=Hh(o,c);i(c,`Copying files: ${S.copied} of ${S.planned} copied so far`)}if(!R)break;p+=m.length;let b=m[m.length-1]?.Id;typeof b=="string"&&(g=b),g!==void 0&&e.store?.checkpoint(c,{lastId:g,read:p,...h?{done:!0}:{}},zh)}}for(let d of o.objects){let c=d.objectApiName==="Attachment"?"attachment":"file";e.onProgress({objectName:d.objectApiName,status:d.failed>0&&d.copied===0?"error":"done",progress:100,message:`Copied ${d.copied} ${c}${d.copied===1?"":"s"} of ${d.planned}`+(d.failed>0?`, ${d.failed} failed`:"")})}s>0&&Ye.info(`[forge] ${s} file(s) copied by the run this one takes up: linked to the records they lacked`)}async filesPageAfter(e,t,n,o,s){let i=n+(o?` AND Id > '${o}'`:"")+` ORDER BY Id LIMIT ${s}`;try{return await this.readOnPassingFailure(t,()=>this.deps.queryRecords(e.sourceOrgId,i))}catch(a){e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:o?`(files after ${o})`:"(files)",messages:[`Not read, so not copied \u2014 a run taken up reads them again: ${V(a)}`]}]});return}}async readOnPassingFailure(e,t){for(let n=0;;n++)try{return await t()}catch(o){let s=Kh(o);if(!s&&!Vh(o)||n>=ld||this.isAborted)throw o;s||await Jh(Rh*2**n),Ye.warn(`[forge] ${e}: the source ${s?"let its cursor expire":"did not answer"} \u2014 asking again (${n+1}/${ld}): ${V(o)}`)}}async documentsOnTheRunsRecords(e,t){let n=new Map;for(let d of t){let c=d.ContentDocumentId;typeof c=="string"&&Ft.test(c)&&n.set(c,d)}if(n.size===0)return[];let o=new Map,s=d=>{e.errors.push({objectApiName:"ContentDocument",stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(links of ${n.size} files)`,messages:[d]}]})},i=!1;try{let d=await this.readOnPassingFailure("ContentDocumentLink",()=>this.deps.queryRecords(e.sourceOrgId,`SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility FROM ContentDocumentLink WHERE ContentDocumentId IN (${[...n.keys()].map(c=>`'${c}'`).join(", ")})`,()=>i=!0));for(let c of d){let u=c.ContentDocumentId,l=c.LinkedEntityId;if(typeof u!="string"||typeof l!="string"||!e.remapper.wasCreated(l))continue;let f=o.get(u)??[];if(f.some(h=>h.id===l))continue;let p=c.ShareType,g=c.Visibility;f.push({id:l,...typeof p=="string"?{shareType:p}:{},...typeof g=="string"?{visibility:g}:{}}),o.set(u,f)}}catch(d){s(`Not read, so not copied \u2014 a run taken up reads them again: ${V(d)}`);return}i&&s("More links than the source reads at once: the files were copied onto the records of the run among those read, and may lack a link to the others.");let a=[];for(let[d,c]of o){let u=n.get(d),l=u?.Id;if(!u||typeof l!="string")continue;let f=u.Title,p=typeof f=="string"&&f!==""?f:d,g=u.PathOnClient,h=u.ContentSize;a.push({objectApiName:"ContentDocument",sourceId:d,body:{objectApiName:"ContentVersion",id:l},name:p,bytes:typeof h=="number"&&Number.isFinite(h)?h:0,hosts:c,fields:{Title:p,PathOnClient:typeof g=="string"&&g!==""?g:p,...u.SharingPrivacy==="P"?{SharingPrivacy:"P"}:{}}})}return a}async readInTurn(e,t){t.turnsAhead.delete(e.objectApiName),await this.readNode(e,t,!0,!1),![...t.waitingFor.values()].some(o=>o.includes(e))&&(await this.readUnderWhatWaited(e.objectApiName,t,"at its turn"),await this.endTurn(e.objectApiName,t))}async readUnderWhatWaited(e,t,n){let o=t.scopeCache,s=t.readAgainUnder.get(e);if(!(!o||!s||!o.isRead(e))){t.readAgainUnder.delete(e);for(let{node:i,fieldInfos:a,whileWaiting:d}of s){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");t.failedObjects.has(i.objectApiName)||n==="at its turn"&&!d||n==="after the catalog"&&!d&&!sg(i.objectApiName,a).includes(e)||await this.readAgainUnderRowsOf(t,i,[...a],e)&&await this.readUnderRowsAdded(i.objectApiName,t,1)}}}async readAgainUnderRowsOf(e,t,n,o){let s=on({node:t,edges:e.graph.edges,fieldInfos:n,scopedBuilder:e.scopedBuilder,scopeCache:e.scopeCache,rootObjectApiName:e.config.rootObjectApiName,rootRecordId:e.config.rootRecordId,rootRecordIds:e.roots?.ids,extraWhere:e.config.objectSoqlFilters?.[t.objectApiName],fieldsLeftOut:e.config.fieldExclusions[t.objectApiName],readObjects:e.readObjects,catalog:Ke,under:new Set([o])});return s.kind!=="query"?!1:(await this.readMore(e,t,n,s.statements,`under the ${o} records read after it`)).length>0}async readUnderRowsAdded(e,t,n){let o=t.scopeCache;if(!o||n>=Xm)return;let{config:s}=t,i=new Set(t.graph.edges.filter(a=>a.sourceObject===e&&a.targetObject!==e).map(a=>a.targetObject));for(let a of t.graph.nodes){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let d=a.objectApiName;if(!a.included||!i.has(d)||!o.isRead(d)||d===s.rootObjectApiName||Ke.has(d)||s.referenceDataObjects.has(d)||t.failedObjects.has(d)||t.notCreatable.has(d))continue;let c=await this.fieldsReadAgain(t,a);!c||!await this.readAgainUnderRowsOf(t,a,c.fields,e)||(c.described&&this.withoutFileContent(t,d,c.described,!0),await this.readUnderRowsAdded(d,t,n+1))}}async readWhatTheyCannotBeWrittenWithout(e,t,n,o){let s=e.scopeCache;if(!s||o.length===0)return;let{config:i}=e,a=new Set(i.fieldExclusions[t]??[]),d=new Map;for(let c of n){let u=c.referenceTo??[];if(!c.isReference||u.length!==1||a.has(c.name)||!Tr(c)||!Qe(t,c.name,c.nillable))continue;let[l]=u;if(l===t||l===i.rootObjectApiName||Ke.has(l)||i.referenceDataObjects.has(l)||!e.readObjects.has(l)||e.failedObjects.has(l)||e.notCreatable.has(l)||!s.isRead(l))continue;let f=s.scopeOf(l),p=e.askedForRowsThatNeedThem.get(l),g=e.heldForExclusions.get(l);for(let h of o){let m=h[c.name];typeof m!="string"||m===""||f?.has(m)||p?.has(m)||g?.has(m)||e.remapper.get(m)||e.leftToThePlatform.has(m)||d.set(l,(d.get(l)??new Set).add(m))}}for(let[c,u]of d){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let l=e.graph.nodes.find(m=>m.included&&m.objectApiName===c);if(!l)continue;let f=e.askedForRowsThatNeedThem.get(c)??new Set;for(let m of u)f.add(m);e.askedForRowsThatNeedThem.set(c,f);let p=await this.fieldsReadAgain(e,l);if(!p)continue;let g=zt(p.fields,i.fieldExclusions[c]);(await this.readMore(e,l,p.fields,new Sn().buildById({objectApiName:c,selectFields:g.length>0?g:["Id"],ids:u,extraWhere:i.objectSoqlFilters?.[c]}),`which the ${t} records read after it cannot be written without`)).length!==0&&(p.described&&this.withoutFileContent(e,c,p.described,!0),await this.readUnderRowsAdded(c,e,0))}}async readParentsOutsideTheGraph(e){let{config:t}=e;if(!e.scopeCache||t.referenceFallback!=="nullify")return!1;let n=new Map(e.graph.nodes.map(d=>[d.objectApiName,d])),o=new Map,s=new Map,i=!1,a=[...e.preread].filter(([d])=>!e.failedObjects.has(d)).map(([d,c])=>({objectApiName:d,fieldInfos:c.fieldInfos,records:c.records}));for(let d=0;d<ew&&a.length>0;d++){let c=this.parentsWanted(e,a,d>0,n);c.size>0&&(i=!0);let u=[];for(let[f,p]of c){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let g=await this.refusalOf(e,f,n.get(f),o);g?await this.holdBackForARefusedParent(e,f,g,p,s):u.push([f,p])}let l=[];for(let[f,p]of u){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let g=tw(e,p);if(g.ids.size===0)continue;let h=await this.readParentsById(e,f,n.get(f),g);h&&l.push(h)}a=l}return i}parentsWanted(e,t,n,o){let{config:s}=e,i=new Map,a=new Map,d=c=>{let u=a.get(c);return u||(u=new Set((e.preread.get(c)?.records??[]).flatMap(l=>typeof l.Id=="string"?[l.Id]:[])),a.set(c,u)),u};for(let{objectApiName:c,fieldInfos:u,records:l}of t){let f=new Set(s.fieldExclusions[c]??[]);for(let p of u){let g=p.referenceTo??[];if(!p.isReference||g.length!==1||f.has(p.name)||!Tr(p)||!Qe(c,p.name,p.nillable))continue;let[h]=g;if(h===c||h===s.rootObjectApiName||Ke.has(h)||s.referenceDataObjects.has(h)||s.excludedObjects.has(h)||vs(e,h))continue;let m=o.get(h);if(m&&(!n||!m.included||e.failedObjects.has(h)))continue;let R=e.askedForRowsThatNeedThem.get(h),b=e.heldForExclusions.get(h);for(let k of l){let O=k[p.name];if(typeof O!="string"||O===""||dn(s,k)||e.remapper.get(O)||e.leftToThePlatform.has(O)||R?.has(O)||b?.has(O)||d(h).has(O))continue;let w=i.get(h);w||(w={ids:new Set,neededBy:new Set,rows:[]},i.set(h,w)),w.ids.add(O),w.neededBy.add(c),w.rows.push({objectApiName:c,row:k,field:p.name})}}}return i}async refusalOf(e,t,n,o){if(n)return e.notInTarget.has(t)?"not-in-target":e.notCreatable.has(t)?"not-creatable":void 0;let s=o.get(t);if(s!==void 0)return s??void 0;let i,a=this.deps.isObjectCreatable;if(a)try{await a(e.targetOrgId,t)||(i="not-creatable")}catch(d){nr(d)?i="not-in-target":e.errors.push({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed)",messages:[`isObjectCreatable check failed: ${d instanceof Error?d.message:String(d)}`]}]})}return o.set(t,i??null),i}async holdBackForARefusedParent(e,t,n,o,s){let i=new Map;for(let{objectApiName:a,row:d,field:c}of o.rows){let u=d.Id;if(typeof u!="string"||i.get(a)?.has(u)||!await this.carriesTheLookup(e,a,c,s))continue;let l=i.get(a)??new Map;l.set(u,{row:d,why:{field:c,excluded:t,target:n}}),i.set(a,l)}for(let[a,d]of i){let c=e.preread.get(a);if(!c)continue;let u=c.records.filter(l=>typeof l.Id!="string"||!d.has(l.Id));this.holdBackRowsRead(e,a,c,u,[...d].map(([l,{row:f,why:p}])=>({id:l,row:f,why:p})))}}async carriesTheLookup(e,t,n,o){if(e.config.fieldMappings[t]?.[n])return!0;let s=o.get(t);if(s===void 0){try{s=await an(this.deps.describeFields,e.targetOrgId,t)}catch{s=null}o.set(t,s)}return s===null||s.creatable.has(n)}async readParentsById(e,t,n,o){let{config:s}=e,i=[...o.neededBy].sort().join(", "),a=s.maxRecordsPerObject?Math.floor(s.maxRecordsPerObject):0,d=a>0?a-(e.readByObject.get(t)??0):0;if(a>0&&d<=0){o.ids.size>0&&e.cappedObjects.add(t);return}let c=e.preread.get(t),u,l;if(c)u=[...c.fieldInfos];else{try{l=await this.deps.describeFields(e.sourceOrgId,t)}catch(S){e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(describe, for the ${i} records that cannot be written without its records)`,messages:[V(S)]}]});return}u=l.filter(S=>!xn(S))}let f=e.askedForRowsThatNeedThem.get(t)??new Set;for(let S of o.ids)f.add(S);e.askedForRowsThatNeedThem.set(t,f);let p=zt(u,s.fieldExclusions[t]),g=new Sn().buildById({objectApiName:t,selectFields:p.length>0?p:["Id"],ids:o.ids,extraWhere:s.objectSoqlFilters?.[t]});this.holdTheRootsReading(e,t,g.length);let h;try{h=await Wr(d>0?oa(g,d,{byIdCount:g.length}):{kind:"query",statements:g,byIdCount:g.length},S=>this.deps.queryRecords(e.sourceOrgId,S,()=>e.truncatedObjects.add(t)),void 0,()=>e.cappedObjects.add(t))}catch(S){if(S instanceof be)throw S;e.errors.push({objectApiName:t,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(read by id, for the ${i} records that cannot be written without them)`,messages:[V(S)]}]});return}Gr(e,h);let m=new Set((c?.records??[]).flatMap(S=>typeof S.Id=="string"?[S.Id]:[])),R=h.filter(S=>typeof S.Id!="string"||!m.has(S.Id)),b=S=>(e.graph.nodes.find(v=>v.objectApiName===S)??e.parentsOutside.get(S))?.level??0,k=n??e.parentsOutside.get(t)??Ur(t,u,1+Math.max(0,...[...o.neededBy].map(b))),O=new Set(e.heldForExclusions.get(t)?.keys()??[]);this.holdBackWhatExclusionsCost(e,k,u,R,void 0,await this.excludedByKeyPrefix(e,t,u));let w=[...e.heldForExclusions.get(t)??[]].filter(([S])=>!O.has(S));if(this.leaveToThePlatform(e,t,R,u),R.length===0&&w.length===0)return;let A=c?.createableSet??new Set(u.filter(S=>S.createable).map(S=>S.name));if(R.length>0){e.preread.set(t,c?{...c,records:[...c.records,...R]}:{fieldInfos:u,createableSet:A,records:R,targetSetsPending:null}),l&&this.withoutFileContent(e,t,l,!0),n?c||e.skippedCount--:(e.parentsOutside.set(t,k),e.writtenObjects.add(t));let S=R.find(j=>typeof j.Id=="string")?.Id;typeof S=="string"&&!e.sourceKeyPrefixes.has(t)&&e.sourceKeyPrefixes.set(t,S.slice(0,3));let v=e.readAsParents.get(t)??{count:0,neededBy:new Set};v.count+=R.length;for(let j of o.neededBy)v.neededBy.add(j);e.readAsParents.set(t,v)}else if(!n){let S=e.heldForExclusions.get(t);S&&e.onProgress({objectName:t,status:"error",progress:100,message:zr(t,S,!1)})}if(e.readByObject.set(t,(e.readByObject.get(t)??0)+R.length+w.length),this.holdTheRootsRows(e,t),s.dryRun){let S=R.length>0?await this.writtenWithTheirAccountOnADryRun(e,t,R,A):0,v=c?"more ":"";e.onProgress({objectName:t,status:"running",progress:0,message:`[dry-run] ${t}: ${R.length-S} ${v}record(s) would be inserted`+(S>0?`, ${S} ${v}would be written by the platform with ${Qn(t)}`:"")+`, which the ${i} records cannot be written without: read by id, nothing read under them`+Ns(Fs(w.map(([,j])=>j)),c!==void 0)})}return R.length>0?{objectApiName:t,fieldInfos:u,records:R}:void 0}async endTurn(e,t){t.turnsAhead.delete(e);let n=t.waitingFor.get(e);if(n){t.waitingFor.delete(e);for(let o of n){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");await this.readInTurn(o,t)}}}async readNode(e,t,n,o){let{config:s,sourceOrgId:i,targetOrgId:a,onProgress:d,remapper:c}=t;t.readAtItsTurn.delete(e.objectApiName);let u=t.cursors.get(e.objectApiName);try{(!u||u.taken===0)&&d({objectName:e.objectApiName,status:"scanning",progress:0,message:`Querying ${e.objectApiName} records...`});let l=u?.described??await this.deps.describeFields(i,e.objectApiName);u&&(u.described=l);let f=l.filter(E=>!xn(E)),p=new Set(f.filter(E=>E.createable).map(E=>E.name));if(await this.skipForFailedParent(e,t,f))return!1;if(n&&e.objectApiName!==s.rootObjectApiName){let E=Qm(e.objectApiName,f,t.turnsAhead);if(E)return t.waitingFor.set(E,[...t.waitingFor.get(E)??[],e]),!1}let g={node:e,edges:t.graph.edges,fieldInfos:f,scopedBuilder:t.scopedBuilder,scopeCache:t.scopeCache,rootObjectApiName:s.rootObjectApiName,rootRecordId:s.rootRecordId,rootRecordIds:t.roots?.ids,extraWhere:Bw(this.filterOf(t,e.objectApiName),u?.pass),fieldsLeftOut:s.fieldExclusions[e.objectApiName],maxRecordsPerObject:u?t.sample?.drawn.has(e.objectApiName)?void 0:this.pagedLimit(t,u):s.maxRecordsPerObject,...u?{inIdOrder:u.resumeAfter!==void 0?{afterId:u.resumeAfter}:{}}:{},readObjects:t.readObjects,catalog:Ke,rootReadAgain:!n&&e.objectApiName===s.rootObjectApiName},h=on(g);if(n&&this.waitsForWhatPointsAtIt(e,h,t))return t.catalogNodes.push({node:e,fieldInfos:f}),!1;if(h.kind==="skip"){if(n&&h.reason===na)return t.deferredNodes.push(e),!1;let E=t.heldForExclusions.get(e.objectApiName);return E&&E.size>0?(t.readByObject.set(e.objectApiName,E.size),d({objectName:e.objectApiName,status:"error",progress:100,message:zr(e.objectApiName,E,!1)}),!1):(t.skippedCount++,d({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (out of scope: ${h.reason})`}),!1)}if(t.notCreatable.has(e.objectApiName)){let E=on({...g,maxRecordsPerObject:1}),_=E.kind==="query"?await Wr(E,ee=>this.deps.queryRecords(i,ee)):[];return this.reportNotCreatable(e,t,_.length>0),!1}if(this.holdTheRootsReading(t,e.objectApiName,h.statements.length),t.roots&&h.readUnder){let E=t.readUnder.get(e.objectApiName)??new Set;for(let _ of h.readUnder)E.add(_);t.readUnder.set(e.objectApiName,E)}let R=o&&!s.referenceDataObjects.has(e.objectApiName)?u?.targetSets??an(this.deps.describeFields,a,e.objectApiName).then(E=>({ok:!0,sets:E}),E=>({ok:!1,error:E})):null;u&&(u.targetSets=R);let b=t.scopeCache?new Set:void 0,k=u?E=>{let _=on({...g,maxRecordsPerObject:u.room===void 0?void 0:Math.max(1,u.room),inIdOrder:{afterId:E}});return _.kind==="query"&&_.statements.length===1?_.statements[0]:void 0}:void 0,O=await Wr(h,E=>u?this.nextPage(t,e,u,E,k):this.readWhole(t,e.objectApiName,E),b,()=>t.cappedObjects.add(e.objectApiName));if(u?.ended&&O.length===0&&u.taken>0)return!1;let w=u?.pass?O.filter(u.pass.keep):O;Gr(t,w),this.keepWhatStatusesNeed(t,e,w,b);let A=this.holdBackWhatExclusionsCost(t,e,f,w,b,await this.excludedByKeyPrefix(t,e.objectApiName,f));b&&t.scopeCache?.addReached(e.objectApiName,b);let S=w.find(E=>typeof E.Id=="string")?.Id;if(typeof S=="string"&&!t.sourceKeyPrefixes.has(e.objectApiName)&&t.sourceKeyPrefixes.set(e.objectApiName,S.slice(0,3)),s.referenceDataObjects.has(e.objectApiName)){t.readByObject.set(e.objectApiName,w.length);let E=await t.referenceDataMapper.resolve(e.objectApiName,w,a);for(let _ of E.mappings)c.addExisting(_.sourceId,_.targetId);return E.unmatched.length>0&&t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:E.unmatched.length,attemptedCount:w.length,referenceData:!0,samples:rw(e.objectApiName,E.unmatched)}),t.scopeCache&&Ml(t.scopeCache,e.objectApiName,w),t.linkedCount+=E.mappings.length,d({objectName:e.objectApiName,status:"done",progress:100,message:`Mapped ${e.objectApiName} via reference-data lookup: ${E.mappings.length} resolved, ${E.unmatched.length} unmatched`}),!1}if(this.leaveToThePlatform(t,e.objectApiName,w,f),e.objectApiName===Ut&&t.standardPricebookId){let E=t.standardPricebookId,_=w.filter(ee=>ee.Id!==E);_.length!==w.length&&(w.length=0,w.push(..._))}let v=t.scopeCache;if(n&&v&&Ke.has(e.objectApiName))return rs(v,e.objectApiName,w,f,{settle:!1,keyPrefixes:await this.keyPrefixesNamedBy(t,f)}),t.catalogNodes.push({node:e,fieldInfos:f}),t.readAtItsTurn.set(e.objectApiName,{records:w,fieldInfos:f}),!1;let j=t.heldForExclusions.get(e.objectApiName);if(A>0&&w.length===0&&j&&!u)return t.failedObjects.add(e.objectApiName),t.readByObject.set(e.objectApiName,j.size),d({objectName:e.objectApiName,status:"error",progress:100,message:zr(e.objectApiName,j)}),!1;if(gt(e.objectApiName)&&t.standardPricebookId){await this.addStandardPricebookEntries(e,t,w,f);let E=t.sample;if(E?.drawn.has(e.objectApiName)){let ee=w.filter(J=>this.inThePlan(E,e.objectApiName,String(J.Id)));w.length=0,w.push(...ee);let X=t.standardPricebookId,z=new Set(w.filter(J=>J[tn]===X).map(J=>Ad(J,t.sellingModels)));for(let J of w)J[tn]!==X&&(z.has(Ad(J,t.sellingModels))||E.withoutStandard.add(it(String(J.Id))))}t.readsEverythingFirst||await this.pricesInTheCurrencyWritten(e,t,w,f);let _=await this.keptPrices(t,w);_.length!==w.length&&(w.length=0,w.push(..._))}t.scopeCache&&rs(t.scopeCache,e.objectApiName,w,f,{keyPrefixes:await this.keyPrefixesNamedBy(t,f)}),await this.notePastDraft(t,e.objectApiName,w);let F=e.objectApiName===s.rootObjectApiName||Ke.has(e.objectApiName)?[]:Ym(e.objectApiName,f,t),B=new Set(n?[...t.waitingFor.values()].flat().map(E=>E.objectApiName):[]);for(let E of F){let _=t.readAgainUnder.get(E)??[];t.readAgainUnder.set(E,[..._,{node:e,fieldInfos:f,whileWaiting:B.has(E)}])}if(s.files&&s.stream?.everything!==!0){let E=w.flatMap(_=>typeof _.Id=="string"&&!s.writtenBefore.retried(_.Id)?[_.Id]:[]);t.fileScope.set(e.objectApiName,E)}if(this.withoutFileContent(t,e.objectApiName,l,w.length>0),u&&(u.carry.rows+=w.length),u?.pass||t.readByObject.set(e.objectApiName,(u?u.carry.rows:w.length)+(j?.size??0)),this.holdTheRootsRows(t,e.objectApiName),t.preread.set(e.objectApiName,{fieldInfos:f,createableSet:p,records:w,targetSetsPending:R}),s.dryRun){let E=await this.writtenWithTheirAccountOnADryRun(t,e.objectApiName,w,p),_=w.length-E;d({objectName:e.objectApiName,status:"running",progress:0,message:`[dry-run] ${e.objectApiName}: ${_} record(s) would be inserted`+(E>0?`, ${E} would be written by the platform with ${Qn(e.objectApiName)}`:"")+Ch(t,e.objectApiName)})}return await this.readWhatTheyCannotBeWrittenWithout(t,e.objectApiName,f,w),!0}catch(l){if(l instanceof be||l instanceof Cs||Ta(l))throw l;if(t.notCreatable.has(e.objectApiName))return this.reportNotCreatable(e,t,!0),!1;t.failedObjects.add(e.objectApiName),t.failedReads.add(e.objectApiName),u&&(u.failed=!0);let f=s.isScoped?0:Math.max(0,Sh(e,s.maxRecordsPerObject)-(u?.read??0));return t.failedCount+=f,t.errors.push({objectApiName:e.objectApiName,stage:"query",failedCount:f,attemptedCount:f,samples:[{recordSummary:"(stage failed before insert)",messages:[V(l)]}]}),d({objectName:e.objectApiName,status:"error",progress:100,message:`Error on ${e.objectApiName}: ${V(l)}`}),!1}}holdBackWhatExclusionsCost(e,t,n,o,s,i){let a=e.config.excludedObjects;if(a.size===0)return 0;let d=t.objectApiName,c=n.filter(O=>O.isReference&&Qe(d,O.name,O.nillable)),u=c.filter(O=>{let w=O.referenceTo??[];return w.length===1&&w[0]!==d&&a.has(w[0])}),l=c.filter(O=>{let w=O.referenceTo??[];return w.length>1&&w.some(A=>a.has(A))}),f=d===et&&e.sellingModels&&a.has(Gt),p=Dh(d),g=c.length>0&&e.heldForExclusions.size>0;if(u.length===0&&l.length===0&&!g&&!f&&!p)return 0;let h=O=>{for(let S of u){let v=O[S.name];if(typeof v=="string"&&v!==""&&!e.remapper.get(v))return{field:S.name,excluded:(S.referenceTo??[])[0]}}for(let S of l){let v=O[S.name];if(typeof v!="string"||v===""||e.remapper.get(v))continue;let j=i.get(v.slice(0,3));if(j!==void 0&&(S.referenceTo??[]).includes(j))return{field:S.name,excluded:j}}let w=g?Mh(e,O,c):void 0;if(w)return w;let A=O[Hn];if(f&&typeof A=="string"&&A!=="")return{field:Hn,excluded:Gt}},m=e.heldForExclusions.get(d)??new Map,R=p?e.statusChildrenRead.get(p.parent)??{kept:new Set,held:new Map}:void 0,b=[];for(let O of o){let w=h(O),A=p?O[p.lookup]:void 0;if(!w){b.push(O),R&&typeof A=="string"&&R.kept.add(A);continue}R&&typeof A=="string"&&!R.held.has(A)&&R.held.set(A,w);let S=O.Id;typeof S=="string"&&(s?.delete(S),!m.has(S)&&(m.set(S,w),e.failedCount++))}R&&p&&e.statusChildrenRead.set(p.parent,R),m.size>0&&e.heldForExclusions.set(d,m);let k=o.length-b.length;return k>0&&(o.length=0,o.push(...b)),k}holdBackWhatHeldRowsCost(e){let{config:t}=e;if(e.heldForExclusions.size!==0)for(let n=!0;n&&!this.isAborted;){n=!1;for(let[o,s]of[...e.preread]){let i=s.fieldInfos.filter(c=>c.isReference&&Qe(o,c.name,c.nillable));if(i.length===0)continue;let a=[],d=[];for(let c of s.records){let u=c.Id,l=typeof u=="string"&&!dn(t,c)?Mh(e,c,i):void 0;typeof u=="string"&&l?d.push({id:u,row:c,why:l}):a.push(c)}d.length!==0&&(n=!0,this.holdBackRowsRead(e,o,s,a,d))}}}holdBackWhatOnlyRowsHeldBackName(e){if(!e.scopeCache||e.namedByRowsHeldBack.size===0)return!1;let t=Lh(e),n=!1;for(let[o,s]of[...e.preread]){if(!Ke.has(o))continue;let i=[],a=[];for(let d of s.records){let c=d.Id,u=typeof c=="string"?Wh(e,o,c,t):void 0;typeof c=="string"&&u?a.push({id:c,row:d,why:u}):i.push(d)}a.length!==0&&(n=!0,this.holdBackRowsRead(e,o,s,i,a))}return n}leaveOutWhatOnlyRowsHeldBackName(e,t){let n=e.scopeCache,o=n?.get(t);if(!n||!o||o.size===0||e.namedByRowsHeldBack.size===0)return;let s=Lh(e),i=e.heldForExclusions.get(t)??new Map,a=[];for(let d of o){let c=Wh(e,t,d,s);c&&(a.push(d),!i.has(d)&&(i.set(d,c),e.failedCount++))}a.length!==0&&(e.heldForExclusions.set(t,i),n.forget(t,a))}holdBackRowsRead(e,t,n,o,s){let{config:i,onProgress:a}=e,d=e.heldForExclusions.get(t)??new Map;for(let{id:f,why:p}of s)d.set(f,p);e.heldForExclusions.set(t,d),e.failedCount+=s.length;let c=n.fieldInfos.filter(f=>f.isReference);for(let{row:f,why:p}of s)for(let g of c){let h=f[g.name];typeof h!="string"||h===""||e.namedByRowsHeldBack.has(h)||e.namedByRowsHeldBack.set(h,{field:g.name,excluded:p.excluded,namedBy:t})}let u=new Set(s.map(({id:f})=>f)),l=e.fileScope.get(t)??[];if(l.length>0&&e.fileScope.set(t,l.filter(f=>!u.has(f))),this.noteStatusRowsHeld(e,t,o,s),i.dryRun&&a({objectName:t,status:"running",progress:0,message:`[dry-run] ${t}: ${s.length} fewer would be inserted`+Ns(Fs(s.map(({why:f})=>f)))}),o.length>0){e.preread.set(t,{...n,records:o});return}e.preread.delete(t),e.failedObjects.add(t),a({objectName:t,status:"error",progress:100,message:zr(t,d)})}noteStatusRowsHeld(e,t,n,o){let s=Dh(t);if(!s)return;let i=e.statusChildrenRead.get(s.parent),a=new Map(i?.held??[]);for(let{row:c,why:u}of o){let l=c[s.lookup];typeof l=="string"&&!a.has(l)&&a.set(l,u)}let d=new Set;for(let c of n){let u=c[s.lookup];typeof u=="string"&&d.add(u)}e.statusChildrenRead.set(s.parent,{kept:d,held:a})}keepWhatStatusesNeed(e,t,n,o){let s=e.statusChildren.get(t.objectApiName);if(!s)return;let i=e.pastDraft.get(s.parent),a=[];for(let d of n){let c=d[s.lookup];typeof c=="string"&&i?.has(c)===!0?a.push(d):typeof d.Id=="string"&&o?.delete(d.Id)}a.length!==n.length&&(n.length=0,n.push(...a))}leaveToThePlatform(e,t,n,o){let s=e.leftToThePlatform.keep(t,n,$w(t,o)),i=n.length-s.length;return i>0&&(n.length=0,n.push(...s)),i}leaveWhatHangsFromThePlatform(e,t,n,o){let s=[...o],i=this.leaveToThePlatform(e,t.objectApiName,s,n),a=e.readByObject.get(t.objectApiName);return i>0&&a!==void 0&&e.readByObject.set(t.objectApiName,a-i),s}holdEmailsForTheirTask(e,t){if(e.taskTurnOver||!e.graph.nodes.some(s=>s.included&&s.objectApiName===ut))return t;let n=e.readsEverythingFirst?new Set((e.preread.get(ut)?.records??[]).map(s=>String(s.Id))):void 0,o=[];for(let s of t)Oo(s)&&(n===void 0||n.has(String(s.ActivityId)))?e.emailsInTwoPasses?e.emailsLeftForTheirTask++:e.emailsAfterTheirTask.push(s):o.push(s);return o}async writeEmailsAfterTheirTask(e){if(e.emailsInTwoPasses){await this.streamEmailsAfterTheirTask(e);return}e.taskTurnOver=!0;let t=e.emailsAfterTheirTask.splice(0,e.emailsAfterTheirTask.length),n=e.graph.nodes.find(o=>o.objectApiName===$e);n&&t.length>0&&!this.isAborted&&(e.emailsAllWaiting=void 0,await this.writeNode(n,e,t)),this.endBeforeTheEmailsThatWaited(e,t.length,this.isAborted)}async streamEmailsAfterTheirTask(e){if(e.taskTurnOver)return;e.taskTurnOver=!0;let t=e.emailsLeftForTheirTask;e.emailsLeftForTheirTask=0;let n=e.graph.nodes.find(u=>u.included&&u.objectApiName===$e),o=e.config.stream?.resumeAfter,s=o?.has($e)===!0||o?.has(zo($e,bh))===!0;if(!(n!==void 0&&e.emailsFirstPassRan&&(t>0||s)&&!e.failedObjects.has($e)&&e.graph.nodes.some(u=>u.included&&u.objectApiName===ut))||this.isAborted){this.endBeforeTheEmailsThatWaited(e,t,this.isAborted);return}let a=e.emailsWrittenFirst!==void 0,d=e.config.dryRun?"Simulated":"Completed";try{await this.streamNode(n,e,{name:bh,where:"ActivityId != null",keep:u=>Oo(u),expected:t,stopped:`Stopped ${$e} after their task`,end:{say:this.endOfTheEmails(e,!0),label:a?"after their task":`${d} ${$e} after their task`}})}catch(u){throw e.emailsWrittenFirst=void 0,u}let c=e.emailsWrittenFirst;c&&(e.emailsWrittenFirst=void 0,e.onProgress(c))}endBeforeTheEmailsThatWaited(e,t,n){let o=e.emailsWrittenFirst??e.emailsAllWaiting;e.emailsWrittenFirst=void 0,e.emailsAllWaiting=void 0,o&&(Od(e,$e,t),e.onProgress(Fw(o,t,n,Ch(e,$e))))}endOfTheEmails(e,t){return n=>{if(n.status!=="done"&&n.status!=="error"&&n.status!=="stopped"){e.onProgress(n);return}if(!t){if(e.emailsAfterTheirTask.length===0&&e.emailsLeftForTheirTask===0){e.onProgress(n);return}e.emailsWrittenFirst=n,e.onProgress({...n,status:"running"});return}let o=e.emailsWrittenFirst;e.emailsWrittenFirst=void 0,e.onProgress(o?{...n,status:o.status==="error"?"error":n.status,message:`${o.message}; ${n.message}`}:n)}}async linkTasksWrittenWithEmails(e,t){if(e.emailsInTwoPasses)return this.tasksLinkedBeforeTheirTurn(e,t);let n=new Map;for(let c of e.preread.get($e)?.records??[]){let u=c.ActivityId,l=c.Id;if(typeof u!="string"||u===""||typeof l!="string"||!e.remapper.isCreated(l))continue;let f=e.remapper.get(l);f&&n.set(u,f)}let o=[...new Set(t.flatMap(c=>n.get(String(c.Id))??[]))];if(o.length===0)return{rows:t,linked:0};let s,{simulated:i}=e;try{s=i?new Map(o.map(c=>[c,i.idFor(null)])):await Ai(c=>this.deps.queryRecords(e.targetOrgId,c),o)}catch(c){return e.errors.push({objectApiName:ut,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(tasks the platform wrote with the emails)",messages:[`Not looked up, so written as read: ${V(c)}`]}]}),{rows:t,linked:0}}let a=t.filter(c=>{let u=String(c.Id),l=n.get(u),f=l===void 0?void 0:s.get(l);return f===void 0?!0:(e.remapper.addExisting(u,f,ut),ur(e,u),!1)}),d=t.length-a.length;return d>0&&(e.linkedCount+=d),cr(e,ut,d),{rows:a,linked:d}}tasksLinkedBeforeTheirTurn(e,t){let n=t.filter(s=>{let i=s.Id;return typeof i!="string"||e.remapper.get(i)===void 0}),o=t.length-n.length;return o>0&&(e.linkedCount+=o),cr(e,ut,o),{rows:n,linked:o}}async linkTasksOfTheEmailsWritten(e){let t=new Map;for(let i of e.preread.get($e)?.records??[]){let a=i.ActivityId,d=i.Id;if(typeof a!="string"||a===""||typeof d!="string"||Oo(i)||!e.remapper.isCreated(d))continue;let c=e.remapper.get(d);c&&t.set(c,a)}if(t.size===0)return;let n=[...t.keys()],{simulated:o}=e,s;try{s=o?new Map(n.map(i=>[i,o.idFor(null)])):await Ai(i=>this.deps.queryRecords(e.targetOrgId,i),n)}catch(i){if(e.emailTasksNotLookedUp)return;e.emailTasksNotLookedUp=!0,e.errors.push({objectApiName:ut,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(tasks the platform wrote with the emails)",messages:[`Not looked up, so written as read: ${V(i)}`]}]});return}for(let[i,a]of s){let d=t.get(i);d===void 0||e.remapper.get(d)!==void 0||(e.remapper.addExisting(d,a,ut),ur(e,d))}}async teamOfTheOpportunities(e,t,n,o,s){let i={notKept:new Map,unread:new Map};if(!So(t)||n.length===0)return{rows:n,lookups:new Map,held:new Map,linked:0,owners:0,values:i};let{config:a,remapper:d,simulated:c}=e,u=$i[t],l=a.decisions.defaultOf(t,u),f=c?await this.writesAs(e):void 0,p=await Pi(t,n,{source:R=>this.deps.queryRecords(e.sourceOrgId,R),target:R=>this.deps.queryRecords(e.targetOrgId,R),targetIdOf:R=>d.get(R),mappedUser:R=>a.ownerMappings[R],...l!==void 0?{defaultUser:l}:{},written:s,...c?{simulated:{ownerOf:R=>a.ownerMappings[R]??(f??=c.idFor(rg)),idFor:()=>c.idFor(o)}}:{}});p.defaulted.size>0&&l!==void 0&&e.decisionsApplied.add({kind:"set_default",objectApiName:t,field:u,to:l},p.defaulted.size);for(let[,{field:R,parentObject:b}]of p.held)b==="User"&&e.gaps?.add({kind:"required_field_missing",severity:"blocking",objectApiName:t,field:R,rows:1,detail:{type:"reference"},decisions:[...Eu.required_field_missing??[]]});let g=0,h=0;for(let[R,{id:b,owners:k,notKept:O,unread:w=[]}]of p.linked){let A=String(R.Id);d.addExisting(A,b,t),d.isCreated(String(R.OpportunityId))&&(ur(e,A),h++),k&&g++;for(let S of O)i.notKept.set(S,(i.notKept.get(S)??0)+1);for(let S of w)i.unread.set(S,(i.unread.get(S)??0)+1)}let m=p.linked.size;return m>0&&(e.linkedCount+=m),cr(e,t,h),m>h&&e.existingRecords.push({objectApiName:t,linked:m-h,unidentified:0}),{rows:m>0?n.filter(R=>!p.linked.has(R)):n,lookups:p.lookups,held:p.held,linked:m,owners:g,values:i}}async takeTheSyncCopies(e,t,n,o,s){let i={taken:0,given:0};if(!e.readsEverythingFirst)return i;let{remapper:a,simulated:d,config:c}=e,u=h=>a.wasCreated(h)||c.writtenBefore.has(h),l=[];if(t.forEach(({source:h},m)=>{let R=h[Wa],b=h[Da];if(typeof R!="string"||typeof b!="string"||!u(R)||!u(b))return;let k=a.get(R),O=a.get(b);k&&O&&l.push({index:m,quote:k,product:O})}),l.length===0)return i;let f=h=>s.updatable?s.updatable.has(h):s.fields?.find(m=>m.name===h)?.updateable!==!1,p;if(d)p=this.copiesASimulationFinds(e,t,l,s.keyPrefix);else{let h=k=>s.fields===void 0||s.fields.some(O=>O.name===k&&O.queryable!==!1),m=[...new Set(l.flatMap(({index:k})=>Object.keys(n[k]??{})))].filter(k=>f(k)&&h(k)),R;try{R=await qf(k=>this.deps.queryRecords(e.targetOrgId,k),l,m)}catch(k){return e.errors.push({objectApiName:rr,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(quote lines the platform copied from their opportunity products)",messages:[`Not looked up, so written as read: a quote that syncs with its opportunity may hold a line twice. ${V(k)}`]}]}),i}let b=new Set;for(let k of o){let O=a.get(String(k.Id));O&&b.add(O.slice(0,15))}p=Uf(l,R,b)}if(p.size===0)return i;let g=d?0:await this.giveTheCopiesTheirFields(e,t,n,p,f);for(let[h,m]of p){let R=t[h],b=typeof R.source.Id=="string"?R.source.Id:void 0,k=String(m.Id);b!==void 0&&a.add(b,k,rr),R.nullifiedFks.length>0&&this.oweToTheSecondPass(e,R.nullifiedFks.map(O=>({objectApiName:rr,newId:k,sourceId:b,fieldName:O.field,sourceRefId:O.sourceRefId,...O.insertOnly?{insertOnly:!0}:{}})))}a.persist();for(let h of[...p.keys()].sort((m,R)=>R-m))t.splice(h,1),n.splice(h,1);return{taken:p.size,given:g}}copiesASimulationFinds(e,t,n,o){let s=new Map,{simulated:i}=e;if(!i)return s;let a=l=>typeof l=="string"&&l!==""?l.slice(0,15):void 0,d=new Map;for(let l of e.pendingFkUpdates){let f=a(l.sourceId),p=a(l.sourceRefId);l.objectApiName===We&&l.fieldName===ys&&f&&p&&d.set(f,p)}if(d.size===0)return s;let c=new Map;for(let l of e.preread.get(Df)?.records??[]){let f=a(l.Id),p=a(l.OpportunityId);f&&p&&c.set(f,p)}let u=new Set;for(let{index:l}of n){let{source:f}=t[l],p=a(f[Da]),g=a(f[Wa]),h=p?c.get(p):void 0;!p||!g||!h||d.get(h)!==g||u.has(p)||(u.add(p),s.set(l,{Id:i.idFor(o)}))}return s}async giveTheCopiesTheirFields(e,t,n,o,s,i={objectApiName:rr,recordSummary:"(quote lines the platform copied from their opportunity products)",leftAs:"Taken, and left as the platform copied them, without the fields of the source's lines"}){let a=[];for(let[l,f]of o){let p=new Set(t[l].nullifiedFks.map(h=>h.field)),g=Gf(n[l]??{},f,s,p);Object.keys(g).length>0&&a.push({Id:f.Id,...g})}if(a.length===0)return 0;let d=this.deps.updateRecords,c=[],u=0;for(let l=0;l<a.length;l+=Xh){let f=a.slice(l,l+Xh);if(!d||this.isAborted){c.push(`${f.length} not sent: ${d?"the run was cancelled first":"the run sends no update"}`);continue}try{let p=await d(e.targetOrgId,i.objectApiName,f);f.forEach((g,h)=>{let m=p[h];m?.success?u++:c.push(`${String(g.Id)}: ${m?.errors.join("; ")??"no answer"}`)})}catch(p){c.push(`${f.length} not updated: ${V(p)}`)}}return c.length>0&&e.errors.push({objectApiName:i.objectApiName,stage:"insert",failedCount:0,attemptedCount:a.length,samples:[{recordSummary:i.recordSummary,messages:[`${i.leftAs}: ${c.slice(0,3).join(" | ")}`]}]}),u}async linkTheRolesThePlatformWrote(e,t,n,o){let s={linked:0,given:0};if(t.length===0)return s;let{remapper:i,simulated:a,config:d}=e,c=new Map;if(d.writtenBefore.size>0&&t.forEach(({source:R},b)=>{let k=R.OpportunityId,O=n[b]?.[Le];typeof k!="string"||typeof O!="string"||O===""||vi(R)&&d.writtenBefore.has(k)&&c.set(k,O)}),e.contactSentWith.size===0&&c.size===0)return s;let u=Ir(t.map(({source:R},b)=>({OpportunityId:R.OpportunityId,[Le]:n[b]?.[Le],IsPrimary:R.IsPrimary})),R=>i.isCreated(R)?e.contactSentWith.get(R):c.get(R));if(u.length===0)return s;let l=R=>o.updatable?o.updatable.has(R):o.fields?.find(b=>b.name===R)?.updateable!==!1,f=a?u.filter(R=>i.isCreated(String(t[R].source.OpportunityId))):[],p=u.filter(R=>!f.includes(R)),g=new Map(f.map(R=>[R,{Id:a?.idFor(o.keyPrefix)??""}]));if(p.length>0){let R=S=>o.fields===void 0||o.fields.some(v=>v.name===S&&v.queryable!==!1),b=a?[]:[...new Set(p.flatMap(S=>Object.keys(n[S]??{})))].filter(S=>l(S)&&R(S)),k=new Map(p.map(S=>[S,{opportunity:String(i.get(String(t[S].source.OpportunityId))),contact:String(n[S]?.[Le])}])),O;try{O=await Ei(S=>this.deps.queryRecords(e.targetOrgId,S),[...new Set([...k.values()].map(({opportunity:S})=>S))],b)}catch(S){e.errors.push({objectApiName:ze,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contact roles the platform wrote with their opportunities)",messages:[`Not looked up, so written as read: an opportunity may hold the role of its contact twice. ${V(S)}`]}]}),O=[]}let{found:w,alike:A}=Ii(k,O);for(let[S,v]of w)g.set(S,v);if(A.length>0){for(let S of A)e.contactSentWith.delete(String(t[S].source.OpportunityId));e.errors.push({objectApiName:ze,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contact roles the platform wrote with their opportunities)",messages:[Zc(A.length)]}]})}}if(g.size===0)return s;let h=a?0:await this.giveTheCopiesTheirFields(e,t,n,g,l,{objectApiName:ze,recordSummary:"(contact roles the platform wrote with their opportunities)",leftAs:"Linked, and left as the platform wrote them, without the fields of the source's roles"}),m=0;for(let[R,b]of g){let k=t[R],O=typeof k.source.Id=="string"?k.source.Id:void 0,w=String(b.Id);if(O===void 0)continue;let A=String(k.source.OpportunityId);e.contactSentWith.delete(A),i.addExisting(O,w,ze),i.wasCreated(A)&&(ur(e,O),m++),k.nullifiedFks.length>0&&this.oweToTheSecondPass(e,k.nullifiedFks.map(S=>({objectApiName:ze,newId:w,sourceId:O,fieldName:S.field,sourceRefId:S.sourceRefId,...S.insertOnly?{insertOnly:!0}:{}})))}i.persist();for(let R of[...g.keys()].sort((b,k)=>k-b))t.splice(R,1),n.splice(R,1);return e.linkedCount+=g.size,cr(e,ze,m),g.size>m&&e.existingRecords.push({objectApiName:ze,linked:g.size-m,unidentified:0}),{linked:g.size,given:h}}async mapContactsOfPersonAccounts(e,t=e.preread.get(Se)?.records??[]){let n=new Map;for(let i of t){let a=i[Er],d=i.Id;if(typeof a!="string"||a===""||typeof d!="string"||e.remapper.get(a))continue;let c=e.remapper.get(d);c&&n.set(c,{contact:a,account:d})}if(n.size===0||await this.personAccountsInTarget(e)===!1)return;let{simulated:o}=e;if(o){for(let[,{contact:i,account:a}]of n)e.contactsOnTheirOwn.has(i)||(e.remapper.addExisting(i,o.idFor(null),ce),e.remapper.isCreated(a)&&this.contactWithItsAccount(e,i));return}let s;try{s=await Xc(i=>this.deps.queryRecords(e.targetOrgId,i),[...n.keys()])}catch(i){e.errors.push({objectApiName:Se,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contacts the platform wrote with the person accounts)",messages:[`Not looked up, so what points at them is left empty: ${V(i)}`]}]});return}for(let[i,{contact:a,account:d}]of n){let c=s.get(i);if(!c){e.contactsOnTheirOwn.add(a);continue}e.remapper.addExisting(a,c,ce),e.remapper.isCreated(d)&&this.contactWithItsAccount(e,a)}}contactWithItsAccount(e,t){ur(e,t);let n=e.sample;(n?.drawn.has(ce)?this.inThePlan(n,ce,t):e.writtenObjects.has(ce))||(e.linkedCount++,cr(e,ce,1),n?.drawn.has(ce)&&e.personContactsOutsideTheSample++)}writesAs(e){let{runningUser:t}=this.deps;return e.writesAs??=t?t(e.targetOrgId).then(n=>typeof n=="string"&&n!==""?n:void 0,()=>{}):Promise.resolve(void 0),e.writesAs}personAccountsInTarget(e){return e.personAccountsInTarget??=this.deps.describeFields(e.targetOrgId,Se).then(t=>t.some(n=>n.name===Er),()=>{}),e.personAccountsInTarget}personRecordTypesInTarget(e){return e.personRecordTypes??=this.deps.queryRecords(e.targetOrgId,`SELECT Id, IsPersonType FROM RecordType WHERE SobjectType = '${Se}'`).then(t=>t.length===0?void 0:new Set(t.filter(n=>n.IsPersonType===!0||n.IsPersonType==="true").map(n=>String(n.Id).slice(0,15))),()=>{}),e.personRecordTypes}async takenAsBusinessAccounts(e,t,n){let o=t.filter(rn);if(o.length===0)return new Set;let s=await this.personAccountsInTarget(e);if(s!==!0)return new Set(s===!1?o:[]);let i=await this.personRecordTypesInTarget(e);if(!i)return new Set;let a=new Map((e.config.recordTypeMappings??[]).map(u=>[u.sourceId,u.targetId])),d=u=>{let l=u.RecordTypeId;return n&&typeof l=="string"&&l!==""?l:void 0},c=o.some(u=>d(u)===void 0)?xa((await this.objectInfoOf(e.targetOrgId,Se))?.recordTypes):void 0;return new Set(o.filter(u=>{let l=d(u),f=l===void 0?c:a.get(l);return f!==void 0&&!i.has(f.slice(0,15))}))}async noteContactsOfBusinessAccounts(e,t,n){let o=n.has("RecordTypeId")&&!(e.config.fieldExclusions[Se]??[]).includes("RecordTypeId")&&e.config.fieldMappings[Se]?.RecordTypeId===void 0;for(let s of await this.takenAsBusinessAccounts(e,t,o)){let i=s[Er];typeof i=="string"&&i!==""&&e.contactsOnTheirOwn.add(i)}}async writtenWithTheirAccountOnADryRun(e,t,n,o){if(So(t)){let i=new Set((e.preread.get("Opportunity")?.records??[]).filter(a=>!dn(e.config,a)).map(a=>String(a.Id)));return n.length===0||i.size===0?0:(await this.teamThePlatformWrites(e,t,n,i)).size}if(t===ze)return(await this.rolesThePlatformWritesOfTheRead(e,e.preread.get(We)?.records??[],e.preread.get(ce)?.records??[],n)).size;if(t===Se)return await this.noteContactsOfBusinessAccounts(e,n,o),0;if(t!==ce)return 0;let s=n.filter(i=>rn(i)&&!e.contactsOnTheirOwn.has(String(i.Id))).length;return s>0&&await this.personAccountsInTarget(e)!==!1?s:0}async personContactsOnTheirOwn(e,t){if(t.length===0)return{rows:new Set,why:""};let n=await this.personAccountsInTarget(e);return{rows:new Set(t.filter(i=>n===!1||e.contactsOnTheirOwn.has(String(i.Id)))),why:n===!1?"the target has no person accounts":"their account is no person account in the target"}}saySentOnTheirOwn(e,t,n){t!==0&&e.errors.push({objectApiName:ce,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`IsPersonAccount=true (${t} record${t===1?"":"s"})`,messages:[`Sent as contacts of their own: ${n}, and wrote no contact with it.`]}]})}linkPersonContacts(e,t){let n=0,o=0,s=0,i=0;for(let c of t){let u=String(c.Id),l=e.remapper.get(u);if(l){e.remapper.addExisting(u,l,ce),n++,Nw(e,u)&&o++;continue}let f=c.AccountId;typeof f=="string"&&e.remapper.get(f)?i++:s++}n>0&&(e.linkedCount+=n),cr(e,ce,o),n>o&&e.existingRecords.push({objectApiName:ce,linked:n-o,unidentified:0});let a=[...s>0?[{count:s,why:Nh.accountNotWritten}]:[],...i>0?[{count:i,why:Nh.contactNotFound}]:[]],d=s+i;return d>0&&(e.failedCount+=d,e.errors.push({objectApiName:ce,stage:"scope",failedCount:d,attemptedCount:0,samples:a.map(({count:c,why:u})=>({recordSummary:`IsPersonAccount=true (${c} record${c===1?"":"s"})`,messages:[`Not written: ${u.replace(/^not sent: /,"")}.`]}))})),{linked:n,notSent:a}}reportNotCreatable(e,t,n){t.skippedCount++,n&&t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:["Object is not createable on target org"]}]}),t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:n?`Skipped ${e.objectApiName} (target org rejects inserts on this entity)`:`Skipped ${e.objectApiName} (target org rejects inserts on this entity; the clone holds none of its records)`})}async reportNotInTargetOfTheScope(e){for(let t of e.notInTargetPutOff?.splice(0)??[]){let n=await this.deps.describeFields(e.sourceOrgId,t.objectApiName).catch(()=>{}),o=n&&on({node:t,edges:e.graph.edges,fieldInfos:n,scopedBuilder:e.scopedBuilder,scopeCache:e.scopeCache,rootObjectApiName:e.config.rootObjectApiName,rootRecordId:e.config.rootRecordId,rootRecordIds:e.roots?.ids,readObjects:e.readObjects,catalog:Ke});if(o?.kind!=="skip"||o.reason!==na){this.reportNotInTarget(t,e);continue}e.skippedCount++,e.onProgress({objectName:t.objectApiName,status:"skipped",progress:100,message:`Skipped ${t.objectApiName} (not in the target org; nothing the run read names its records)`})}}reportNotInTarget(e,t){t.skippedCount++,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,skipped:!0,samples:[{recordSummary:"(node-level skip)",messages:["Object is not in the target org, or the user the run writes as cannot see it: none of its records can be written there"]}]}),t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (not in the target org)`})}waitsForWhatPointsAtIt(e,t,n){return!n.scopeCache||!Ke.has(e.objectApiName)?!1:t.kind==="skip"||!Cl(t)}async readCatalogAgain(e,t){let n=e.scopeCache;if(!n)return;let{config:o}=e,s=vl.flatMap(d=>e.catalogNodes.filter(({node:c})=>c.objectApiName===d)).filter(({node:d})=>!e.failedObjects.has(d.objectApiName)&&!e.notCreatable.has(d.objectApiName)&&!o.referenceDataObjects.has(d.objectApiName));if(!s.some(({node:d})=>kh(n,d.objectApiName).size>0))return;let i=new Map([...n.entries()].map(([d,c])=>[d,new Set(c)])),a=new Set;for(let{node:d,fieldInfos:c}of s){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let u=d.objectApiName,l=[...c],f=o.objectSoqlFilters?.[u],p=async m=>u===Ut&&e.standardPricebookId?m.filter(R=>R.Id!==e.standardPricebookId):gt(u)&&e.standardPricebookId?(await this.addStandardPricebookEntries(d,e,m,l),e.readsEverythingFirst||await this.pricesInTheCurrencyWritten(d,e,m,l),this.keptPrices(e,m)):m;if(u===Gt){if(!a.has(Zo)&&!a.has(jr))continue;let m=on({node:d,edges:e.graph.edges,fieldInfos:l,scopedBuilder:e.scopedBuilder,scopeCache:n,rootObjectApiName:o.rootObjectApiName,rootRecordId:o.rootRecordId,rootRecordIds:e.roots?.ids,extraWhere:f,fieldsLeftOut:o.fieldExclusions[u],readObjects:e.readObjects,catalog:Ke});if(m.kind!=="query")continue;(await this.readMore(e,d,l,m.statements,"named by records read after the catalog",p)).length>0&&a.add(u);continue}let g=zt(l,o.fieldExclusions[u]),h=new Set;for(let m=0;m<Zm;m++){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let R=[...kh(n,u)].filter(k=>!h.has(k));if(R.length===0)break;for(let k of R)h.add(k);if((await this.readMore(e,d,l,new Sn().buildById({objectApiName:u,selectFields:g.length>0?g:["Id"],ids:new Set(R),extraWhere:f}),m===0?"named by records read after the catalog":"named by its own records read before them",p)).length===0)break;a.add(u)}}a.size>0&&await this.readAfterTheCatalogAgain(e,t,i)}async readAfterTheCatalogAgain(e,t,n){let o=e.scopeCache;if(!o)return;let{config:s}=e,i=new Set;for(let a of t){if(this.isAborted)throw new be("Forge execution was aborted by user request. Remaining objects were not processed.");let d=a.objectApiName;if(e.failedObjects.has(d)||e.notCreatable.has(d)||s.referenceDataObjects.has(d))continue;let c=n.get(d),u=o.isRead(d)?o.scopeOf(d):void 0,l=new Set([...o.get(d)??[]].filter(b=>!c?.has(b)&&!u?.has(b))),f=new Set(e.graph.edges.filter(b=>b.targetObject===d&&i.has(b.sourceObject)).map(b=>b.sourceObject));if(l.size===0&&f.size===0)continue;let p=await this.fieldsReadAgain(e,a);if(!p)continue;let{fields:g}=p,h=s.objectSoqlFilters?.[d],m=[];if(l.size>0){let b=zt(g,s.fieldExclusions[d]);m.push(...new Sn().buildById({objectApiName:d,selectFields:b.length>0?b:["Id"],ids:l,extraWhere:h}))}if(f.size>0){let b=on({node:a,edges:e.graph.edges,fieldInfos:g,scopedBuilder:e.scopedBuilder,scopeCache:o,rootObjectApiName:s.rootObjectApiName,rootRecordId:s.rootRecordId,rootRecordIds:e.roots?.ids,extraWhere:h,fieldsLeftOut:s.fieldExclusions[d],readObjects:e.readObjects,catalog:Ke,under:f});b.kind==="query"&&m.push(...b.statements)}m.length===0||(await this.readMore(e,a,g,m,"for what the catalog read again brought")).length===0||(i.add(d),p.described&&this.withoutFileContent(e,d,p.described,!0))}}async fieldsReadAgain(e,t){let n=e.preread.get(t.objectApiName);if(n)return{fields:[...n.fieldInfos]};try{let o=await this.deps.describeFields(e.sourceOrgId,t.objectApiName);return{fields:o.filter(s=>!xn(s)),described:o}}catch{return}}async readMore(e,t,n,o,s,i=async a=>a){let a=e.scopeCache;if(!a)return[];let{config:d}=e,c=t.objectApiName,u=d.maxRecordsPerObject?Math.floor(d.maxRecordsPerObject):0,l=u>0?u-(e.readByObject.get(c)??0):0;if(u>0&&l<=0)return o.length>0&&e.cappedObjects.add(c),[];let f=a.isRead(c),p=new Set(f?a.scopeOf(c)??[]:[]),g=m=>typeof m.Id!="string"||!p.has(m.Id);this.holdTheRootsReading(e,c,o.length);let h;try{let m=await Wr(l>0?oa(o,l,{byIdCount:o.length}):{kind:"query",statements:o,byIdCount:o.length},B=>this.deps.queryRecords(e.sourceOrgId,B,()=>e.truncatedObjects.add(c)),void 0,()=>e.cappedObjects.add(c));Gr(e,m);let R=m.filter(g);this.keepWhatStatusesNeed(e,t,R,void 0);let b=e.heldForExclusions.get(c),k=0;for(let B of b?R:[]){let E=B.Id;typeof E!="string"||b?.get(E)?.namedBy===void 0||(b.delete(E),k++)}k>0&&(b?.size===0&&e.heldForExclusions.delete(c),e.failedCount-=k,e.readByObject.set(c,(e.readByObject.get(c)??k)-k));let O=new Set(e.heldForExclusions.get(c)?.keys()??[]);this.holdBackWhatExclusionsCost(e,t,n,R,void 0,await this.excludedByKeyPrefix(e,c,n));let w=[...e.heldForExclusions.get(c)??[]].filter(([B])=>!O.has(B));if(this.leaveToThePlatform(e,c,R,n),h=(await i(R)).filter(g),rs(a,c,h,n,{settle:!1,keyPrefixes:await this.keyPrefixesNamedBy(e,n)}),a.addReadAgain(c,h.flatMap(B=>typeof B.Id=="string"?[B.Id]:[])),await this.notePastDraft(e,c,h),h.length===0&&w.length===0)return[];if(d.files&&d.stream?.everything!==!0){let B=h.flatMap(E=>typeof E.Id=="string"?[E.Id]:[]);e.fileScope.set(c,[...e.fileScope.get(c)??[],...B])}f||e.skippedCount--;let A=e.preread.get(c),S=A?.records??[],v=gt(c)?await this.keptPrices(e,[...S,...h]):[...S,...h],j=v.length-S.length,F=A?.createableSet??new Set(n.filter(B=>B.createable).map(B=>B.name));if(e.preread.set(c,A?{...A,records:v}:{fieldInfos:n,createableSet:F,records:v,targetSetsPending:null}),e.readByObject.set(c,(e.readByObject.get(c)??0)+j+w.length),this.holdTheRootsRows(e,c),d.dryRun){let B=await this.writtenWithTheirAccountOnADryRun(e,c,gt(c)?[]:h,F);e.onProgress({objectName:c,status:"running",progress:0,message:`[dry-run] ${c}: ${j-B} more record(s) would be inserted`+(B>0?`, ${B} more would be written by the platform with ${Qn(c)}`:"")+`, ${s}`+Ns(Fs(w.map(([,E])=>E)),!0)})}}catch(m){if(m instanceof be||Ta(m))throw m;return e.errors.push({objectApiName:c,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(more rows, ${s})`,messages:[V(m)]}]}),[]}return await this.readWhatTheyCannotBeWrittenWithout(e,c,n,h),h}async keptPrices(e,t){let n=await this.pricesKeyOf(e),{kept:o,standsFor:s}=wi(t,n);if(this.pricesStandFor(e,s),n.oneCurrency)for(let i of o){let a=i.Id,d=i[mt];typeof a=="string"&&typeof d=="string"&&d!==""&&e.pricesKeptAsRead.set(a,{from:d,to:n.oneCurrency.code})}return o}async pricesKeyOf(e){e.oneCurrency??=(async()=>{let n=a=>this.deps.describeFields(a,et).catch(()=>[]),[o,s]=await Promise.all([n(e.sourceOrgId),n(e.targetOrgId)]),i=a=>a.some(d=>d.name===mt);if(!(s.length===0||!i(o)||i(s)))try{let a=await this.deps.orgCurrency?.(e.targetOrgId);return typeof a=="string"&&/^[A-Z]{3}$/.test(a)?{code:a}:{}}catch(a){return Ye.warn(`[forge] the target's one currency could not be read: ${V(a)}`),{}}})();let t=await e.oneCurrency;return{sellingModel:e.sellingModels,...t?{oneCurrency:t}:{}}}pricesStandFor(e,t){for(let{left:n,kept:o}of t){let s=n.Id,i=o.Id;if(typeof s!="string"||typeof i!="string"||s===i||e.prices.standsFor.get(s)===i)continue;e.remapper.alias(s,i),e.prices.standsFor.set(s,i);for(let[c,u]of e.prices.standsFor)u===s&&(e.remapper.alias(c,i),e.prices.standsFor.set(c,i));let a=n[mt],d=o[mt];typeof a=="string"&&typeof d=="string"&&a!==d&&e.pricesSwappedSaid.push({from:a,to:d,how:"replaced",forLines:!1})}}async addStandardPricebookEntries(e,t,n,o){let s=t.standardPricebookId;if(!s)return;let i=u=>Ad(u,t.sellingModels),a=new Set,d=new Set,c=new Set;for(let u of n){let l=u.Id;if(typeof l=="string"&&c.add(l),u[tn]===s)continue;let f=u[Pn];typeof f=="string"&&f&&(a.add(f),d.add(i(u)))}if(a.size!==0)try{let u=new Sn().buildJoining({objectApiName:e.objectApiName,selectFields:zt(o,t.config.fieldExclusions[e.objectApiName]),split:{field:Pn,ids:a},whole:{field:tn,ids:new Set([s])}}),l=0;for(let f of u)for(let p of await this.deps.queryRecords(t.sourceOrgId,f)){let g=p.Id;typeof g=="string"&&c.has(g)||d.has(i(p))&&(n.push(p),Gr(t,[p]),l++)}l>0&&t.onProgress({objectName:e.objectApiName,status:"scanning",progress:50,message:`Added ${l} standard price book entr${l===1?"y":"ies"} the custom prices depend on`})}catch(u){t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(standard price book entries)",messages:[V(u)]}]})}}async pricesInTheCurrencyWritten(e,t,n,o,s){let i=await this.priceCurrencyInput(t,n,o);if(!i)return;let a={...i,...s?{wanted:s}:{}},d=s?t.pricesTheGateCounted:void 0,c=Na(a).filter(h=>!d||d.has(Fa(h))),u=[],l=[...new Set(c.map(({currency:h})=>h))].filter(h=>/^[A-Z]{3}$/.test(h));if(l.length>0)try{let h=new Sn().buildJoining({objectApiName:e.objectApiName,selectFields:zt(o,t.config.fieldExclusions[e.objectApiName]),split:{field:Pn,ids:new Set(c.map(({product:m})=>m).filter(m=>m!==""))},whole:{field:tn,ids:new Set(c.map(({book:m})=>m).filter(m=>m!==""))},extraWhere:`${mt} IN (${l.map(m=>`'${m}'`).join(", ")})`});for(let m of h)u.push(...await this.deps.queryRecords(t.sourceOrgId,m))}catch(h){t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(prices in the currency written)",messages:[V(h)]}]});return}let f=t.sample;if(f?.drawn.has(e.objectApiName)){let h=u.filter(m=>this.inThePlan(f,e.objectApiName,String(m.Id)));u.length=0,u.push(...h)}let p=Ca(a,d?u.filter(h=>d.has(Pa(Bf(h,t.sellingModels),String(h[mt])))):u),g=new Set(n);n.length=0,n.push(...p.rows),Gr(t,p.rows.filter(h=>!g.has(h)));for(let[h,m]of p.standsFor)t.remapper.alias(h,m),t.prices.standsFor.set(h,m);for(let[h,m]of t.prices.standsFor){let R=p.standsFor.get(m);R!==void 0&&(t.remapper.alias(h,R),t.prices.standsFor.set(h,R))}for(let[h,m]of p.convertedInto)t.prices.convertedInto.set(h,m);for(let[h,m]of p.written)t.prices.written.set(h,m);for(let[h,m]of p.keys)t.prices.keys.set(h,m);t.pricesSwappedSaid.push(...p.said),!(p.said.length===0||s)&&t.onProgress({objectName:e.objectApiName,status:"scanning",progress:50,message:Ma(p.said).join("; ")})}async priceCurrencyInput(e,t,n){let{standardPricebookId:o}=e;if(!o||!n.some(d=>d.name===mt)||!t.some(d=>typeof d[mt]=="string"))return;let s=await this.runCurrencies(e);if(!s)return;let{target:i}=s,a=this.priceCurrencyWrittenIn(e,i);return{prices:t,standardBookId:o,sellingModels:e.sellingModels,writtenIn:a,active:i.active}}priceCurrencyWrittenIn(e,t){return n=>{let o={[mt]:n};e.config.decisions.applyToRow(et,o,void 0,new Xi);let s=o[mt];return typeof s=="string"&&t.active.has(s)?s:bu(void 0,t)?.to}}async pricesTheGateCounts(e){let t=e.preread.get(et);if(!t||!e.readsEverythingFirst)return 0;let n=await this.priceCurrencyInput(e,t.records,t.fieldInfos);if(!n)return 0;let o=Na({...n,wanted:this.currenciesTheirLinesMayWant(e,t.records,n.active)});return e.pricesTheGateCounted=new Set(o.map(Fa)),o.length}currenciesTheirLinesMayWant(e,t,n){let o=new Set(t.flatMap(d=>typeof d.Id=="string"?[d.Id]:[])),{decisions:s}=e.config,i=d=>{if(s.changesRowsOf(d))return!0;if(!Po(d))return!1;let c=e.preread.get(d)?.fieldInfos.find(u=>u.name===Ru[d])?.referenceTo?.[0];return c===void 0||i(c)},a=new Map;for(let[d,{record:c,field:u}]of Object.entries(ms)){let l=i(c);for(let f of e.preread.get(d)?.records??[]){let p=f[_r];if(typeof p!="string"||typeof f[u]!="string")continue;let g=e.prices.standsFor.get(p)??p;if(!o.has(g))continue;let h=f[He],m=!l&&typeof h=="string"&&n.has(h)?[h]:[...n],R=a.get(g)??new Set;for(let b of m)R.add(b);a.set(g,R)}}return a}currenciesTheirLinesWant(e,t){let n=new Set(t.flatMap(s=>typeof s.Id=="string"?[s.Id]:[])),o=new Map;for(let[s,{field:i}]of Object.entries(ms))for(let a of e.preread.get(s)?.records??[]){let d=a[_r];if(typeof d!="string")continue;let c=e.prices.standsFor.get(d)??d;if(!n.has(c))continue;let u=this.currencyTheirRecordWentIn(e,a,i);if(u===void 0)continue;let l=o.get(c)??new Set;l.add(u),o.set(c,l)}return o}currencyTheirRecordWentIn(e,t,n){let o=t[n];if(typeof o!="string"||e.remapper.get(o)===void 0)return;let s=e.currencyChangesById.get(o)?.to;if(s!==void 0)return s;let i=t[He];return typeof i=="string"&&i!==""?i:void 0}pricedInTheirRecordsCurrency(e,t,n){let o=ms[t]?.field;return o===void 0||e.prices.written.size===0?n:n.map(s=>{let i=s[_r];if(typeof i!="string")return s;let a=e.prices.standsFor.get(i)??i,d=e.prices.keys.get(a),c=d?this.currencyTheirRecordWentIn(e,s,o):void 0;if(d===void 0||c===void 0)return s;let u=e.prices.written.get(Pa(d,c));return u===void 0||u===a||u===i||e.remapper.get(u)===void 0?s:{...s,[_r]:u}})}async objectInfoOf(e,t){if(!this.deps.describeObject)return null;try{return await this.deps.describeObject(e,t)}catch{return null}}async toWriteAtTheGate(e,t,n,o=0){let s=n.records.filter(u=>!dn(e.config,u)),i=n.records.length-s.length,a=s.length>0?await this.heldBackAtTheGate(e,t,n,s):[],d=a.length>0,c={...i>0?{writtenBefore:i}:{},...d?xh(a,s.length):{}};return{objectApiName:t,rows:d?[]:s,...Object.keys(c).length>0?{leftOut:c}:{},...o>0&&!d?{mayAdd:o}:{}}}async withoutWhatThePlatformWrites(e,t){let n=u=>t.find(l=>l.objectApiName===u)?.rows??[],o=new Map,s=new Set(n("Opportunity").map(u=>String(u.Id)));for(let u of t)if(!(!So(u.objectApiName)||u.rows.length===0)){if(s.size===0)break;o.set(u.objectApiName,await this.teamThePlatformWrites(e,u.objectApiName,u.rows,s))}let i=await this.personContactsThePlatformWrites(e,n(Se),n(ce));i.size>0&&o.set(ce,i);let a=await this.rolesThePlatformWritesOfTheRead(e,n(We),n(ce),n(ze)),d=await this.rolesOfOpportunitiesWrittenBefore(e,n(ze).filter(u=>!a.has(u))),c=new Set([...a,...d.linked]);return c.size>0&&o.set(ze,c),t.map(u=>{let l=o.get(u.objectApiName),f=u.objectApiName===ze&&d.mayBe>0?{mayBeByThePlatform:{rows:d.mayBe,before:!0}}:{};return!l||l.size===0?{...u,...f}:{...u,rows:u.rows.filter(p=>!l.has(p)),leftOut:{...u.leftOut,byThePlatform:l.size},...f}})}async withoutWhatTheTargetHoldsByValue(e,t){let{config:n}=e,o=[];for(let s of t){let{objectApiName:i,rows:a}=s,d=e.preread.get(i);if(a.length===0||s.counted||!d){o.push(s);continue}let c=await(d.targetSetsPending??an(this.deps.describeFields,e.targetOrgId,i).then(w=>({ok:!0,sets:w}),w=>({ok:!1,error:w})));if(!c.ok){o.push(s);continue}let u=dr(d.createableSet,c.sets.creatable),l=new Set(n.fieldExclusions[i]??[]),f=n.fieldMappings[i]??{},p=new Set(Object.values(f)),g=new Set(await e.maskedSourceFields(i).catch(()=>[])),h=n.anonymization,m=new Set(e.anonymize&&h?h.fields[i]??this.detectedPersonalFields(e,h,i,d.fieldInfos):[]),R=new Set(e.contactPoints?Ea(d.fieldInfos).map(({name:w})=>w):[]),b=n.decisions.truncatedFieldsOf(i),k=c.sets.fields.filter(({name:w,unique:A,externalId:S})=>A===!0&&u.has(w)&&!(n.upsertMode==="auto"&&S===!0)&&!l.has(w)&&f[w]===void 0&&!p.has(w)&&!g.has(w)&&!m.has(w)&&!R.has(w)&&!b.has(w)&&!(i===Se&&w.endsWith("__pc"))),O=new Map;for(let w of k){let{name:A}=w,S=new Map;for(let F of a){let B=F[A];if(typeof B!="string"||B===""||Zh.test(B))continue;let E=Mn(w,B);S.has(E)||S.set(E,B)}let v=[...S.values()];if(v.length===0)continue;let j=new Set;try{let F=Be(i),B=Be(A);for(let E of kn(v,Yh)){let _=await this.deps.queryRecords(e.targetOrgId,`SELECT ${B} FROM ${F} WHERE ${B} IN (${E})`);for(let ee of _){let X=ee[A];typeof X=="string"&&j.add(Mn(w,X))}}}catch{continue}for(let F of a){let B=F[A];typeof B=="string"&&j.has(Mn(w,B))&&!O.has(F)&&O.set(F,A)}}if(O.size===0){o.push(s);continue}o.push({...s,rows:a.filter(w=>!O.has(w)),leftOut:{...s.leftOut,linkedByValue:{rows:O.size,fields:[...new Set(O.values())]}}})}return o}async rolesOfOpportunitiesWrittenBefore(e,t){let{config:n}=e,o={linked:new Set,mayBe:0};if(n.writtenBefore.size===0)return o;let s=u=>u.slice(0,15),i=new Map;for(let u of t){let l=u.OpportunityId,f=u[Le];typeof l!="string"||typeof f!="string"||f===""||vi(u)&&n.writtenBefore.has(l)&&i.set(s(l),f)}if(i.size===0)return o;let a=Ir(t,u=>i.get(s(u))),d=u=>typeof u=="string"&&u!==""?n.writtenBefore.get(u)??e.remapper.get(u):void 0,c=new Map;for(let u of a){let l=d(t[u].OpportunityId),f=d(t[u][Le]);l!==void 0&&f!==void 0&&c.set(u,{opportunity:l,contact:f})}if(c.size===0)return{...o,mayBe:a.length};try{let u=await Ei(f=>this.deps.queryRecords(e.targetOrgId,f),[...new Set([...c.values()].map(({opportunity:f})=>f))]),{found:l}=Ii(c,u);return{linked:new Set([...l.keys()].map(f=>t[f])),mayBe:a.length-c.size}}catch{return{...o,mayBe:a.length}}}async rolesThePlatformWritesOfTheTables(e,t,n,o){let{config:s}=e,i=new Set(n.map(u=>u.objectApiName));if(!i.has(We)||(s.fieldExclusions[We]??[]).includes(Le)||s.fieldMappings[We]?.[Le]!==void 0)return 0;if([We,ze,ce].some(u=>o.has(u)))return;let d=u=>t.findIndex(l=>l.objectApiName===u),c=i.has(ce)&&d(ce)<d(We);try{if(!(await this.deps.describeFields(e.sourceOrgId,We)).some(w=>w.name===Le&&w.createable)||!(await an(this.deps.describeFields,e.targetOrgId,We)).creatable.has(Le))return 0;let f=w=>s.objectSoqlFilters?.[w],p=s.stream?.resumeAfter.get(ze),g=f(We),h=f(ce),m=[...f(ze)?[`(${f(ze)})`]:[],`Opportunity.${Le} != null`,...p&&Ft.test(p.lastId)?[`Id > '${p.lastId}'`]:[],...g?[`OpportunityId IN (SELECT Id FROM ${We} WHERE (${g}))`]:[],...c&&h?[`${Le} IN (SELECT Id FROM ${ce} WHERE (${h}))`]:[]],R=await this.deps.queryRecords(e.sourceOrgId,`SELECT Id, OpportunityId, ${Le}, IsPrimary, Opportunity.${Le} FROM ${ze} WHERE ${m.join(" AND ")} ORDER BY Id LIMIT ${mh+1}`);if(R.length>mh)return;let b=w=>c||s.writtenBefore.has(w)||e.remapper.get(w)!==void 0,k=w=>{let A=w.Opportunity,S=A!==null&&typeof A=="object"?A[Le]:void 0;return typeof S=="string"&&S!==""?S:void 0},O=new Map;for(let w of R){let A=w.OpportunityId,S=k(w);typeof A!="string"||S===void 0||s.writtenBefore.has(A)||!b(S)||O.set(A.slice(0,15),S)}return Ir(R,w=>O.get(w.slice(0,15))).length}catch{return}}rolesThePlatformMayWriteOfTheCounts(e,t,n){let{config:o}=e;return(o.fieldExclusions[We]??[]).includes(Le)||o.fieldMappings[We]?.[Le]!==void 0?0:Math.min(t,n)}async rolesThePlatformWritesOfTheRead(e,t,n,o){if(o.length===0||t.length===0)return new Set;let{config:s,remapper:i}=e;if((s.fieldExclusions[We]??[]).includes(Le)||s.fieldMappings[We]?.[Le]!==void 0)return new Set;let a=e.preread.get(We);if(!a?.createableSet.has(Le))return new Set;let d=await(a.targetSetsPending??an(this.deps.describeFields,e.targetOrgId,We).then(f=>({ok:!0,sets:f}),f=>({ok:!1,error:f})));if(!d.ok||!d.sets.creatable.has(Le))return new Set;let c=f=>f.slice(0,15),u=new Set(n.map(f=>c(String(f.Id)))),l=new Map;for(let f of t){let p=f.Id,g=f[Le];typeof p!="string"||typeof g!="string"||g===""||dn(s,f)||!u.has(c(g))&&i.get(g)===void 0||l.set(c(p),g)}return l.size===0?new Set:new Set(Ir(o,f=>l.get(c(f))).map(f=>o[f]))}async teamThePlatformWrites(e,t,n,o){let{config:s}=e,i=s.decisions.defaultOf(t,$i[t]),a=await this.writesAs(e);try{let d=await Pi(t,n,{source:c=>this.deps.queryRecords(e.sourceOrgId,c),target:c=>this.deps.queryRecords(e.targetOrgId,c),targetIdOf:c=>o.has(c)?c:void 0,mappedUser:c=>s.ownerMappings[c],...i!==void 0?{defaultUser:i}:{},written:[],simulated:{ownerOf:c=>s.ownerMappings[c]??a??`${rg}gate`,idFor:()=>""}});return new Set(d.linked.keys())}catch{return new Set}}async personContactsThePlatformWrites(e,t,n){let o=n.filter(d=>rn(d)&&!e.contactsOnTheirOwn.has(String(d.Id)));if(o.length===0)return new Set;if(await this.personAccountsInTarget(e)===!1)return new Set;let i=(e.preread.get(Se)?.createableSet??new Set).has("RecordTypeId")&&!(e.config.fieldExclusions[Se]??[]).includes("RecordTypeId")&&e.config.fieldMappings[Se]?.RecordTypeId===void 0,a=new Set([...await this.takenAsBusinessAccounts(e,t,i)].map(d=>String(d[Er])));return new Set(o.filter(d=>!a.has(String(d.Id))))}async heldBackAtTheGate(e,t,n,o){let s=e.graph.nodes.find(u=>u.objectApiName===t);if(!s)return[];let i=await this.objectInfoOf(e.targetOrgId,t);if(!i||i.recordTypes.length===0)return[];if(!(e.recordTypeMapper!==null&&e.config.recordTypeMappings!==void 0)&&!i.recordTypes.some(u=>!u.available&&!u.master))return[];let d=await(n.targetSetsPending??an(this.deps.describeFields,e.targetOrgId,t).then(u=>({ok:!0,sets:u}),u=>({ok:!1,error:u}))),c=d.ok?dr(n.createableSet,d.sets.creatable):n.createableSet;return this.recordTypesHeldBack(s,o,i,c,e)}async recordTypesHeldBack(e,t,n,o,s){let{config:i}=s;if(!n||n.recordTypes.length===0)return[];if(!o.has("RecordTypeId"))return[];if((i.fieldExclusions[e.objectApiName]??[]).includes("RecordTypeId"))return[];if(i.fieldMappings[e.objectApiName]?.RecordTypeId)return[];let a=t.map(c=>({RecordTypeId:i.recordTypeDecisions.get(String(c.RecordTypeId))?.to===null?void 0:c.RecordTypeId}));s.recordTypeMapper&&i.recordTypeMappings&&(a=s.recordTypeMapper.apply(a,i.recordTypeMappings));let d=new Map;for(let c of a){let u=c.RecordTypeId;typeof u=="string"&&d.set(u,(d.get(u)??0)+1)}return[...ju(e.objectApiName,a,n.recordTypes),...await this.typesTheTargetLacks(s,e.objectApiName,d,n)]}oweToTheSecondPass(e,t){let n=this.withoutSyncedQuotes(e,t);if(e.secondPassInStore&&e.store){for(let o of n)e.store.owe(o);return}if(e.store)for(let o of n)e.store.owe(o);e.pendingFkUpdates.push(...n)}withoutSyncedQuotes(e,t){if(e.config.stream?.everything!==!0)return t;let n=t.filter(o=>o.objectApiName!==We||o.fieldName!==ys);return e.syncedQuotesLeft+=t.length-n.length,n.length===t.length?t:n}saySyncedQuotesLeft(e){let t=e.syncedQuotesLeft;t!==0&&(e.syncedQuotesLeft=0,e.errors.push({objectApiName:We,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(${We}.${ys})`,messages:[`Left empty on ${t} opportunit${t===1?"y":"ies"}: filled in, the target syncs the quote at once and writes its lines over the opportunity's products the run copied. Start the sync in the target to fill it in.`]}]}))}patchedInTheJournal(e){let{store:t}=e;if(!(!t||e.secondPassInStore))return eg(t)}oweStatus(e,t,n,o){e.store?e.store.oweStatus(t,n,o):e.deferredStatuses.push({objectApiName:t,id:n,status:o})}countWrites(e,t,n){e.simulated?e.wouldInsertCount+=n.successCount:e.successCount+=n.successCount,e.updatedCount+=n.updatedCount,n.mayHaveBeenWritten&&n.mayHaveBeenWritten.length>0&&e.mayHaveBeenWritten.set(t,[...e.mayHaveBeenWritten.get(t)??[],...n.mayHaveBeenWritten]),e.linkedCount+=n.linkedExistingCount,e.linkedToCreatedCount+=n.linkedToCreatedCount??0,e.failedCount+=n.failureCount,this.oweToTheSecondPass(e,n.pendingFkUpdates),n.writtenWithoutFields&&this.countWrittenWithoutFields(e,t,n.writtenWithoutFields);for(let{field:o,recordId:s}of n.leftEmptyByFilter??[])this.noteLeftEmptyByFilter(e,t,o,s);for(let o of n.withTheirRecord??[])ur(e,o);(n.linkedExistingCount>0||n.unidentifiedExistingCount>0)&&e.existingRecords.push({objectApiName:t,linked:n.linkedExistingCount,...n.linkedToCreatedCount?{linkedToCreated:n.linkedToCreatedCount}:{},unidentified:n.unidentifiedExistingCount}),n.failureCount>0&&e.errors.push({objectApiName:t,stage:"insert",failedCount:n.failureCount,attemptedCount:n.successCount+n.updatedCount+n.linkedExistingCount+n.failureCount,samples:n.errorSamples})}countWrittenWithoutFields(e,t,n){e.writtenWithoutFields.set(t,ia(e.writtenWithoutFields.get(t),n))}noteLeftEmptyByFilter(e,t,n,o){let s=e.leftEmptyByFilter.get(t);s||(s=new Map,e.leftEmptyByFilter.set(t,s));let i=s.get(n)??{records:0,ids:[]};i.records++,i.ids.length<Km&&i.ids.push(o),s.set(n,i)}sayRecordTypeNote(e,t,n){e.errors.push({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:[fl(n)]})}oweLookupsOfRowsWrittenBefore(e,t,n,o,s){let{config:i}=e,a=new Set(e.graph.nodes.filter(l=>l.included).map(l=>l.objectApiName)),d=new Set(i.fieldExclusions[t.objectApiName]??[]),c=i.fieldMappings[t.objectApiName]??{},u=o.filter(l=>l.isReference&&l.name!=="RecordTypeId"&&!d.has(l.name)&&dd(l,s,c[l.name])&&(l.referenceTo??[]).some(f=>a.has(f)));if(u.length!==0)for(let l of n){let f=l.Id;if(typeof f!="string")continue;let p=i.writtenBefore.get(f);if(p)for(let g of u){let h=l[g.name];if(typeof h!="string"||!h||i.writtenBefore.has(h)&&!e.store?.owesUntold(f))continue;let[m]=this.withoutSyncedQuotes(e,[{objectApiName:t.objectApiName,newId:p,sourceId:f,fieldName:c[g.name]??g.name,sourceRefId:h}]);m&&(e.secondPassInStore&&e.store?e.store.owe(m,!0):e.owedToRowsWrittenBefore.push(m))}}}owedNowWritten(e){if(e.owedToRowsWrittenBefore.length===0)return[];let t=[],n=[];for(let o of e.owedToRowsWrittenBefore)e.remapper.get(o.sourceRefId)?t.push(o):n.push(o);return e.owedToRowsWrittenBefore=n,t}sayLookupsOutsideTheClone(e,t){let n=new Map,o=this.keepLookupsInTheClone(e,t,n);return this.sayLeftEmpty(e,n),o}keepLookupsInTheClone(e,t,n){let o=[];for(let s of t){if(e.remapper.get(s.sourceRefId)||e.idsRead.has(s.sourceRefId)){o.push(s);continue}let i=this.objectPointedAt(e,s);if(i!==void 0&&(e.failedObjects.has(i)||e.notCreatable.has(i)||e.notInTarget.has(i))){o.push(s);continue}let a=n.get(s.objectApiName)??new Map,d=`${s.fieldName}|${i??""}`,c=a.get(d)??{field:s.fieldName,parent:i,count:0};c.count++,a.set(d,c),n.set(s.objectApiName,a)}return o}sayLeftEmpty(e,t){for(let[n,o]of t)e.errors.push({objectApiName:n,stage:"scope",failedCount:0,attemptedCount:0,samples:[...o.values()].sort((s,i)=>i.count-s.count).slice(0,3).map(({field:s,parent:i,count:a})=>({recordSummary:`${i===void 0?s:`${s} \u2192 ${i}`} (${a} record${a===1?"":"s"})`,messages:[`Written with the lookup empty: the ${i===void 0?"":`${i} `}record it points at is not in the clone.`]}))})}async secondPassFromTheJournal(e){let{store:t}=e;if(!t)return null;let n=new Qf({remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:e.targetOrgId,enabled:!e.config.dryRun,onProgress:e.onProgress,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:eg(t),onAnswered:()=>t.flush(),onRefusedByFilter:(l,f,p)=>this.noteLeftEmptyByFilter(e,l,f,p),...this.secondPassOfTheSample(e)}),o=new Map,s=e.config.stream?.secondPassPageSize??Vm,i=e.pendingFkUpdates.splice(0,e.pendingFkUpdates.length),a=l=>t.wasPatched(l.newId,l.fieldName),d=new Jf;for(let l of i)d.note(0,l.newId);let c=1;for(let l of t.owedPages(s)){for(let{update:f}of l)a(f)||d.note(c,f.newId);c++}let u=l=>d.spans(l.newId);await n.patch(this.keepLookupsInTheClone(e,i,o),u);for(let l of t.owedPages(s)){let f=l.filter(({update:p,toRowWrittenBefore:g})=>!a(p)&&(!g||e.remapper.get(p.sourceRefId)!==void 0)).map(({update:p})=>p);await n.patch(this.keepLookupsInTheClone(e,f,o),u)}return await n.sendHeld(),this.sayLeftEmpty(e,o),n.finish()}objectPointedAt(e,t){let n=e.config.fieldMappings[t.objectApiName]??{},s=e.preread.get(t.objectApiName)?.fieldInfos.find(a=>a.isReference&&(n[a.name]??a.name)===t.fieldName)?.referenceTo??[];if(s.length===1)return s[0];let i=t.sourceRefId.slice(0,3);return s.find(a=>e.sourceKeyPrefixes.get(a)===i)}applyRecordTypeDecisions(e,t,n,o){let{config:s}=e,i=new Map,a=e.recordTypeMapper&&s.recordTypeMappings?new Set(s.recordTypeMappings.map(d=>d.sourceId)):void 0;return o.forEach((d,c)=>{let u=n[c]?.cleaned.RecordTypeId;if(typeof u!="string"||u===""||!("RecordTypeId"in d))return;let l=s.recordTypeDecisions.get(u);if(l){l.to===null&&delete d.RecordTypeId,e.decisionsApplied.add({kind:"map_record_type",objectApiName:t,from:l.from,...l.to!==null?{to:l.to}:{}});return}!e.simulated||!a||Dw.test(u)||a.has(u)||i.set(u,(i.get(u)??0)+1)}),i}simulateWrite(e,t,n,o,s,i,a,d,c=new Map){let{simulated:u}=e;if(!u)return;let l=t.objectApiName,f=new Set,p=0;i({objectName:l,status:"running",progress:0,recordCount:n.records.length,message:`Simulating the write of ${n.records.length} ${l} records: nothing is sent...`});for(let[g,h]of n.cleaned.entries()){let m=n.records[g]??{},R=d?Pu(l,m,h.source,d):[];if(R.length>0){s.failureCount++,s.errorSamples.length<3&&s.errorSamples.push({recordSummary:Gl(m),messages:[`REQUIRED_FIELD_MISSING: Required fields are missing: [${R.map(w=>w.name).join(", ")}]`]});continue}let b=u.idFor(o),k=typeof h.source.Id=="string"?h.source.Id:void 0,O=c.get(m);if(O!==void 0){s.linkedExistingCount++,p++,f.add(O),k!==void 0&&e.remapper.addExisting(k,b,l);continue}s.successCount++,a&&!Dl(n.records[g]??{})&&a(h),k!==void 0&&e.remapper.add(k,b,l);for(let w of h.nullifiedFks)s.pendingFkUpdates.push({objectApiName:l,newId:b,sourceId:k,fieldName:w.field,sourceRefId:w.sourceRefId,...w.insertOnly?{insertOnly:!0}:{}})}p>0&&i({objectName:l,status:"running",progress:0,message:`[dry-run] ${l}: ${p} fewer would be inserted, linked to the record${p===1?"":"s"} the target holds under the same ${[...f].join(", ")}, which its refusal of the row names`})}holdBackSkippedRows(e,t,n,o,s){let{config:i}=e;if(!i.decisions.skipsRowsOf(t.objectApiName))return n;let a=new Set(i.fieldExclusions[t.objectApiName]??[]),d=new Map(Object.entries(i.fieldMappings[t.objectApiName]??{}).map(([l,f])=>[f,l])),c=n.filter(l=>{let f=l.RecordTypeId;return!i.decisions.holdsBack(t.objectApiName,p=>{let g=d.get(p)??p;return a.has(g)?void 0:l[g]},Qh(i,typeof f=="string"?f:void 0),e.decisionsApplied,s)}),u=n.length-c.length;return u>0&&o({objectName:t.objectApiName,status:"running",progress:0,message:`${t.objectApiName}: ${u} record${u===1?"":"s"} held back, as decided on the gaps`}),c}async findGaps(e,t,n){let{gaps:o}=e;if(!o)return new Map;let s=t.objectApiName,i=new Map([...n.recordTypes?.values()??[]].map(d=>[d.recordType,d]));for(let{picklistChanges:d=[]}of n.cleanedRecords){let c=xu(s,d,u=>{if(u.recordType!==void 0)return i.get(u.recordType)?.picklists.get(u.field)?.values;let l=n.picklistValuesByField?.get(u.field);return l?[...l]:void 0});for(let u of c)o.add(u)}if(n.unmapped.size>0){let d=await this.sourceRecordTypesOf(e,s);o.knowRecordTypes(s,"source",d);for(let[c,u]of n.unmapped){let l=d.find(f=>f.recordTypeId.slice(0,15)===c.slice(0,15))?.developerName??c;o.add(Di("record_type_unmapped",s,l,u,lg(n.targetObject)))}}let a=n.targetFields;return a?(Fu({objectApiName:s,rows:n.recordsToInsert.map((d,c)=>{let u=n.cleanedRecords[c]?.cleaned.RecordTypeId;return{payload:d,source:n.cleanedRecords[c]?.source??{},typed:typeof u=="string"&&n.recordTypes?.has(u)===!0}}),targetFields:a,picklistValuesByField:n.picklistValuesByField,picklistFields:n.picklistFields??new Map},o),await this.currencyGaps(e,s,a,n.cleanedRecords),this.uniqueValueGaps(e,s,a,n.recordsToInsert)):new Map}sourceRecordTypesOf(e,t){let n=e.sourceRecordTypes.get(t);if(!n){let o=this.deps.describeObject;n=o?o(e.sourceOrgId,t).then(s=>this.namedRecordTypes(e.recordTypeRows,e.sourceOrgId,s.recordTypes),()=>[]):Promise.resolve([]),e.sourceRecordTypes.set(t,n)}return n}currenciesFor(e,t,n,o){return t?.some(i=>i.name===He&&i.createable)===!0&&o(He)&&n.some(i=>typeof i[He]=="string"&&i[He]!=="")?this.runCurrencies(e):Promise.resolve(void 0)}async parentCurrenciesFor(e,t,n,o){if(e.currencyChangesById.size===0)return;let s=n?.find(a=>a.name===He);if(!s||s.createable&&!Po(t)||!o.some(a=>typeof a[He]=="string"&&a[He]!==""))return;let i=await e.currencies;return{changeOf:a=>e.currencyChangesById.get(a),...i?{currencies:i}:{}}}runCurrencies(e){let t=this.deps.queryTooling;return e.currencies??=yu(n=>this.deps.queryRecords(e.sourceOrgId,n),n=>this.deps.queryRecords(e.targetOrgId,n),t?{source:n=>t(e.sourceOrgId,n),target:n=>t(e.targetOrgId,n)}:{}),e.currencies}async currencyGaps(e,t,n,o){if(!n.some(d=>d.name===He&&d.createable))return;let s=new Map,i=new Map;for(let{source:d,currencyChange:c}of o){let u=d[He];if(typeof u!="string"||u===""||(s.set(u,(s.get(u)??0)+1),!c||c.chosenBy==="decision"))continue;let l=i.get(u)??{to:new Set,fields:new Set,kept:!1};l.to.add(c.to);for(let f of c.fields)l.fields.add(f);c.notConverted&&(l.kept=!0),i.set(u,l)}if(s.size===0)return;let a=(await e.currencies)?.target.active;if(!(!a||a.size===0))for(let[d,c]of s){if(a.has(d))continue;let u=i.get(d);e.gaps?.add(Nu(t,d,c,u&&{to:[...u.to].sort(),converted:[...u.fields].sort(),asRead:u.kept}))}}async uniqueValueGaps(e,t,n,o){let s=new Map,i=n.filter(a=>a.unique===!0&&a.createable&&!(e.config.upsertMode==="auto"&&a.externalId===!0));for(let a of i){let d=new Map;for(let f of o){let p=f[a.name];if(typeof p!="string"||p===""||Zh.test(p))continue;let g=Mn(a,p),h=d.get(g);h?h.rows++:d.set(g,{value:p,rows:1})}if(d.size===0)continue;let c=new Set;try{let f=Be(t),p=Be(a.name),g=[...d.values()].map(({value:h})=>h);for(let h of kn(g,Yh)){let m=await this.deps.queryRecords(e.targetOrgId,`SELECT ${p} FROM ${f} WHERE ${p} IN (${h})`);for(let R of m){let b=R[a.name];typeof b=="string"&&c.add(Mn(a,b))}}}catch{continue}let u=0,l=0;for(let[f,{rows:p}]of d)c.has(f)&&(u+=p,l++);u>0&&e.gaps?.add(Cu(t,a.name,u,l));for(let f of o){let p=f[a.name];typeof p=="string"&&c.has(Mn(a,p))&&!s.has(f)&&s.set(f,a.name)}}return s}async writeNode(e,t,n,o){let{config:s,sourceOrgId:i,targetOrgId:a,remapper:d}=t;o&&o.pages++;let c=e.objectApiName===$e?this.endOfTheEmails(t,n!==void 0):t.onProgress,u=s.dryRun?"Simulated":"Completed",l=n===void 0?`${u} ${e.objectApiName}`:t.emailsWrittenFirst?"after their task":`${u} ${e.objectApiName} after their task`,f=n===void 0?`Stopped ${e.objectApiName}`:t.emailsWrittenFirst&&!o?"stopped after their task":`Stopped ${e.objectApiName} after their task`,p=t.preread.get(e.objectApiName);if(!p)return;let{fieldInfos:g,createableSet:h,targetSetsPending:m}=p;if(gt(e.objectApiName)&&t.readsEverythingFirst&&n===void 0&&!o){await this.pricesInTheCurrencyWritten(e,t,p.records,g,this.currenciesTheirLinesWant(t,p.records));let j=await this.keptPrices(t,p.records);j.length!==p.records.length&&(p.records.length=0,p.records.push(...j))}let R=n??p.records,b=R.filter(j=>dn(s,j)),k=e.objectApiName===ce?R.filter(j=>rn(j)&&!dn(s,j)):[],O=await this.personContactsOnTheirOwn(t,k),w=new Set(k.filter(j=>!O.rows.has(j))),A=b.length>0||w.size>0?R.filter(j=>!dn(s,j)&&!w.has(j)):R,S=A,v=[];try{let j=null,F,B=null,E,_,ee=await(m??an(this.deps.describeFields,a,e.objectApiName).then($=>({ok:!0,sets:$}),$=>({ok:!1,error:$})));if(ee.ok)j=ee.sets.creatable,F=ee.sets.updateable,B=ee.sets.picklistValuesByField,E=ee.sets.picklistFields,_=ee.sets.fields;else{let $=ee.error;t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed \u2014 falling back to source schema)",messages:[$ instanceof Error?$.message:String($)]}]})}let X=j?dr(h,j):h,z=this.linkPersonContacts(t,[...w]);if(o&&(o.withTheirAccount+=z.linked,cd(o,z.notSent),z.linked===0&&(o.personContactsUnlinked+=w.size)),w.size>0&&z.linked===0&&A.length===0&&b.length===0){if(o)return;t.failedObjects.add(e.objectApiName),c({objectName:e.objectApiName,status:"error",progress:100,message:`${$n(e.objectApiName,w.size,Qt(t,e.objectApiName))}: every record is a person account's contact, which the platform writes with its account, and the run has none of them in the target. Objects that cannot be written without it will be skipped.`});return}if(b.length>0&&(t.linkedCount+=b.length,o&&(o.writtenBefore+=b.length),this.oweLookupsOfRowsWrittenBefore(t,e,b,g,F),await this.oweStatusesFoundAfterStop(t,e.objectApiName,b),A.length===0&&w.size===0)){o||c({objectName:e.objectApiName,status:"done",progress:100,message:`${l}: 0 succeeded, ${Ed(s,b.length)}, 0 failed`});return}let J=await this.targetObjectInfoOf(t,e.objectApiName),Me=Lw(J);t.gaps?.knowRecordTypes(e.objectApiName,"target",J?.recordTypes??[]);let ke=await this.recordTypesHeldBack(e,A,J,X,t),ue=ke.length>0&&s.stream?.everything===!0?this.rowsOfClosedTypes(t,e,A,ke):void 0,H=ue!==void 0&&ue.size>0&&(o!==void 0||ue.size<A.length);if(H){S=A.filter(W=>!ue.has(W)),t.failedCount+=ue.size;for(let W of ue.keys())t.heldInTheOrg.set(String(W.Id),"held");let $=[...ue.values()];if(v.push(...$),o?(o.withoutParent+=$.length,Hr($,o.withoutParentGroups),cd(o,Ih($))):t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:$.length,attemptedCount:0,samples:$d(Hr($),t.failedObjects)}),o&&S.length===0)return}else if(o?.heldWhole!==void 0&&ke.length===0){t.failedCount+=A.length,o.heldWholeRows+=A.length;return}if(ke.length>0&&!H){for(let W of ke)t.gaps?.add(Ph(W,J));if(t.failedObjects.add(e.objectApiName),t.failedCount+=A.length,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:A.length,attemptedCount:0,samples:ke.map(W=>({recordSummary:`RecordType=${W.developerName} (${W.recordCount} record${W.recordCount===1?"":"s"})`,messages:[Do(W)]}))}),o){o.heldWhole??=ke.map(Wo).join(" "),o.heldWholeRows+=A.length;return}let $=Qt(t,e.objectApiName);c({objectName:e.objectApiName,status:"error",progress:100,message:`${$n(e.objectApiName,A.length,$)}: `+ke.map(Wo).join(" ")+" Objects that cannot be written without it will be skipped."});return}S=this.holdBackSkippedRows(t,e,S,c,Me),S=this.leaveWhatHangsFromThePlatform(t,e,g,S);let Q=0;if(e.objectApiName===$e&&n===void 0){let $=this.holdEmailsForTheirTask(t,S);if(Q=S.length-$.length,S=$,Q>0&&S.length===0){let W={objectName:e.objectApiName,status:"running",progress:0,message:`${e.objectApiName}: ${$s(Q)}`};c(W),o||(t.emailsAllWaiting={...W,status:"done",progress:100});return}}let pe=0;if(e.objectApiName===ut){let $=await this.linkTasksWrittenWithEmails(t,S);S=$.rows,pe=$.linked,o&&(o.withTheirEmail+=$.linked)}let we=new Set(s.fieldExclusions[e.objectApiName]??[]),Ee=s.fieldMappings[e.objectApiName]??{},ae=await this.teamOfTheOpportunities(t,e.objectApiName,S,J?.keyPrefix,g.flatMap($=>!$.isReference&&X.has($.name)&&!we.has($.name)&&Ee[$.name]===void 0?[$.name]:[]));S=ae.rows,o&&(o.teamOwners+=ae.owners,o.teamOthers+=ae.linked-ae.owners,jw(o.teamValues,ae.values));let D=await this.rowsWithoutTheirParent(e,t,g,S);for(let[$,W]of await this.rowsWhoseParentTheTargetLacks(e,t,g,S,me=>X.has(me)&&!we.has(me)&&Ee[me]===void 0))D.has($)||D.set($,W);let L=await this.rowsHeldInTheWholeOrg(e,t,g,S,$=>X.has($)&&!we.has($)&&Ee[$]===void 0);for(let[$,W]of L.held)D.has($)||D.set($,W);if(L.aside.size>0){for(let fe of D.keys())L.aside.delete(fe);gw(t,e.objectApiName,L.aside.values()),S.forEach((fe,Ce)=>{let ot=L.aside.get(Ce);ot&&t.heldInTheOrg.set(String(fe.Id),ot)});let $=S.filter((fe,Ce)=>!L.aside.has(Ce)),W=new Map;S.forEach((fe,Ce)=>{L.aside.has(Ce)||W.set(Ce,W.size)});let me=new Map;for(let[fe,Ce]of D){let ot=W.get(fe);ot!==void 0&&me.set(ot,Ce)}D.clear();for(let[fe,Ce]of me)D.set(fe,Ce);S=$}if(S.forEach(($,W)=>{let me=ae.held.get($);me&&!D.has(W)&&D.set(W,{field:me.field,parentObject:me.parentObject,reason:me.why})}),D.size>0&&(s.stream?.everything===!0&&S.forEach(($,W)=>{D.has(W)&&t.heldInTheOrg.set(String($.Id),"held")}),S=S.filter(($,W)=>!D.has(W)),t.failedCount+=D.size,o?(o.withoutParent+=D.size,Hr(D.values(),o.withoutParentGroups),cd(o,[{count:D.size,why:vd}])):t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:D.size,attemptedCount:0,samples:aw(D,t.failedObjects)}),S.length===0&&ae.linked===0)){if(o)return;t.failedObjects.add(e.objectApiName);let $=Q===0?Qt(t,e.objectApiName):[];c({objectName:e.objectApiName,status:"error",progress:100,message:`${$n(e.objectApiName,D.size,$)}: every record points at a parent this run did not write. Objects that cannot be written without it will be skipped.`});return}await t.orphanExpander.expandForNode({node:e,fieldInfos:g,records:S,sourceOrgId:i,targetOrgId:a,remapper:d,scopeCache:t.scopeCache,recordTypeMappings:s.recordTypeMappings,recordTypeMapper:t.recordTypeMapper,enabled:s.expandOrphanParents,maxExpansions:s.maxOrphanParentExpansions,anonymize:t.anonymize?($,W,me,fe)=>this.anonymizeRows(t,$,[W],[me],fe,{})[0]:void 0,contactPoints:t.contactPoints??void 0,withoutFileContent:($,W)=>this.withoutFileContent(t,$,W,!0),startAsDraft:async($,W)=>(await this.startAsDrafts(t,$,[W])).get(0),oweStatus:($,W,me)=>this.oweStatus(t,$,W,me),objectOf:($,W)=>this.objectOfSourceId(t,$,W),leftToThePlatform:t.leftToThePlatform,recordTypePicklists:t.recordTypePicklists,onRecordTypeNote:($,W)=>this.sayRecordTypeNote(t,$,W),picklistChanges:t.picklistChanges,currencies:()=>this.runCurrencies(t),currencyChanges:t.currencyChanges,currencyChangesById:t.currencyChangesById,onWrittenWithoutFields:($,W)=>this.countWrittenWithoutFields(t,$,W),linkPersonContacts:$=>this.mapContactsOfPersonAccounts(t,$),personAccountsInTarget:()=>this.personAccountsInTarget(t),fieldExclusions:s.fieldExclusions,fieldMappings:s.fieldMappings,maskedFieldsOf:$=>t.maskedSourceFields($),onMaskedLeftOut:($,W)=>this.noteEncryptedLeftOut(t,$,W),businessAccountsAmong:($,W)=>this.takenAsBusinessAccounts(t,$,W),contactOnItsOwn:$=>t.contactsOnTheirOwn.has($),...t.store?{calls:Es(t.store)}:{}}),S=this.leaveWhatHangsFromThePlatform(t,e,g,S);let Re=s.fieldMappings[e.objectApiName]??{},Ne=await this.withMaskedLeftOut(t,e.objectApiName,new Set(s.fieldExclusions[e.objectApiName]??[]),S,$=>X.has($)||Re[$]!==void 0),Ie=E?await t.recordTypePicklists.forRows({objectApiName:e.objectApiName,rows:S,fields:E,written:$=>X.has($)&&!Ne.has($)&&Re[$]===void 0,recordTypeMappings:s.recordTypeMappings,withoutRecordTypes:_!==void 0&&!_.some($=>$.name==="RecordTypeId")}):void 0;for(let $ of Ie?.notes??[])this.sayRecordTypeNote(t,e.objectApiName,$);let ge=X.has("RecordTypeId")&&!Ne.has("RecordTypeId")&&Re.RecordTypeId===void 0,K=e.objectApiName===Se?await this.takenAsBusinessAccounts(t,S,ge):void 0,te=Po(e.objectApiName)?void 0:await this.currenciesFor(t,_,S,$=>X.has($)&&!Ne.has($)&&Re[$]===void 0),M=te?void 0:await this.parentCurrenciesFor(t,e.objectApiName,_,S);S=this.pricedInTheirRecordsCurrency(t,e.objectApiName,S);let q=gt(e.objectApiName)?$=>t.prices.convertedInto.get(String($.Id)):void 0,G=s.referenceFallback==="keep"?await this.idsTheTargetLacks(t,g,S,$=>X.has($)&&!Ne.has($)&&Re[$]===void 0):void 0,Te=s.referenceFallback==="keep"?await this.inactiveOwnersToLeaveOut(t,S,X.has("OwnerId")&&!Ne.has("OwnerId")&&Re.OwnerId===void 0):void 0,ie=lh({objectApiName:e.objectApiName,records:S,...q?{pricedIn:q}:{},fieldInfos:g,remapper:d,referenceFallback:s.referenceFallback,failedObjects:t.failedObjects,writtenObjects:t.writtenObjects,neverCopied:$=>vs(t,$),ownerMappings:s.ownerMappings,...ae.lookups.size>0?{resolvedLookups:ae.lookups}:{},...G&&G.size>0?{targetLacks:G}:{},...Te?{inactiveOwners:Te}:{},...t.sample?{outsideTheSample:($,W)=>this.outsideTheSample(t,$.referenceTo??[],W)||t.heldInTheOrg.has(W)}:s.stream?.everything===!0?{heldByTheRun:$=>t.heldInTheOrg.has($)}:{},excludedFields:Ne,fieldRename:Re,creatableFields:X,updatableFields:F,picklistValuesByField:B,picklistFields:E,recordTypeValues:Ie?.byRecordType,businessAccounts:K,contactPoints:t.contactPoints??void 0,decide:($,W)=>s.decisions.applyToRow(e.objectApiName,$,Qh(s,W),t.decisionsApplied,Me),...te||M?{currencyFields:Io(_??[])}:{},...te?{currencies:te}:{},...M?{parentCurrencies:M}:{}}),ne=new Ko,U=new Fo;for(let{picklistChanges:$=[],currencyChange:W,source:me}of ie){ne.add(e.objectApiName,$),t.picklistChanges.add(e.objectApiName,$),o?.picklists.add(e.objectApiName,$),U.add(e.objectApiName,W),t.currencyChanges.add(e.objectApiName,W),o?.currencies.add(e.objectApiName,W);let fe=me.Id;W&&typeof fe=="string"&&t.currencyChangesById.set(fe,W)}let Oe=Vo(ne.list())+No(U.list())+gd(_h(new Map,ie))+Rd(Uh(ie))+md(wd(new Map,ie))+yd(bd(new Map,ie))+(o?"":Td(t,e.objectApiName));o&&(_h(o.lookupsNotCarried,ie),wd(o.lookupsOutsideTheRun,ie),bd(o.lookupsHeldBack,ie),o.ownersInactive+=Uh(ie)),this.noteLookupsOutsideTheRun(t,e.objectApiName,g,ie),await this.noteLookupsHeldBack(t,e.objectApiName,g,ie);for(let $ of ie)for(let W of $.lookupsOutsideTheSample??[])this.noteLeftOutsideTheSample(t,e.objectApiName,W);xw(t,e.objectApiName,ie);let ye=ie.map($=>$.cleaned);t.recordTypeMapper&&s.recordTypeMappings&&(ye=t.recordTypeMapper.apply(ye,s.recordTypeMappings,$=>hs(e.objectApiName,$)));let le=this.applyRecordTypeDecisions(t,e.objectApiName,ie,ye);ye=this.anonymizeRows(t,e.objectApiName,ye,ie.map($=>String($.source.Id??"")),g,s.fieldMappings[e.objectApiName]??{});let Nt=new Map((_??[]).flatMap($=>$.length!==void 0&&$.length>0?[[$.name,$.length]]:[]));if(s.decisions.truncatedFieldsOf(e.objectApiName).size>0)for(let $ of ye)s.decisions.truncate(e.objectApiName,$,Nt,t.decisionsApplied);let ft=new Map;t.gaps&&(ft=await this.findGaps(t,e,{cleanedRecords:ie,recordsToInsert:ye,targetFields:_,targetObject:J,picklistValuesByField:B,picklistFields:E,recordTypes:Ie?.byRecordType,unmapped:le}));let Tt=e.objectApiName===rr?await this.takeTheSyncCopies(t,ie,ye,b,{fields:_,updatable:F,keyPrefix:J?.keyPrefix}):{taken:0,given:0};e.objectApiName===We&&Aw(t,ie,ye);let wt=e.objectApiName===ze?await this.linkTheRolesThePlatformWrote(t,ie,ye,{fields:_,updatable:F,keyPrefix:J?.keyPrefix}):{linked:0,given:0},nt=await this.startAsDrafts(t,e.objectApiName,ye),At=new Map;if(t.store)for(let[$,W]of nt){let me=ie[$];me&&At.set(me,W)}let dt=[];if(gt(e.objectApiName)&&t.standardPricebookId){let $=ie.map((fe,Ce)=>Ce),{standard:W,custom:me}=Fc($.map(fe=>({index:fe,[tn]:ie[fe].source[tn]})),t.standardPricebookId);for(let fe of[W,me])fe.length!==0&&dt.push({records:fe.map(Ce=>ye[Ce.index]),cleaned:fe.map(Ce=>ie[Ce.index])})}dt.length===0&&(ye.length>0||Tt.taken===0&&wt.linked===0)&&dt.push({records:ye,cleaned:ie});let Xt=await this.recordTypeCounter(t,e.objectApiName,J,ge),Ae=ql();Ae.successCount+=Tt.taken;let yt;try{for(let $ of dt){if(t.simulated){this.simulateWrite(t,e,$,J?.keyPrefix,Ae,c,Xt,_,ft);continue}await t.batchWriter.writeNode({node:e,records:$.records,cleanedRecords:$.cleaned,fieldInfos:g,creatableFields:X,upsertMode:s.upsertMode,...o?.tableKeys?{tableKeys:o.tableKeys}:{},targetOrgId:a,targetKeyPrefix:J?.keyPrefix,picklistFields:E,remapper:d,...t.store?{oweLookups:W=>this.oweToTheSecondPass(t,W)}:{},...t.store?{calls:Es(t.store)}:{},...At.size>0?{onWritten:(W,me)=>{let fe=At.get(W);fe!==void 0&&(At.delete(W),this.oweStatus(t,e.objectApiName,me,fe))}}:{},...Xt?{onCreatedWithoutRecordType:Xt}:{},...Object.keys(s.ownerMappings).length>0?{ownersMapped:new Set(Object.values(s.ownerMappings).map(W=>W.slice(0,15)))}:{},...t.bulk?{bulk:t.bulk}:{},waitIfPaused:()=>this.waitIfPaused(),stopped:()=>this.isAborted,onProgress:c},Ae)}}catch($){if(!($ instanceof be))throw $;yt=$}finally{for(let[$,W]of nt){let me=ie[$];if(me&&t.store&&!At.has(me))continue;let fe=me?.source.Id;if(typeof fe!="string")continue;let Ce=d.get(fe);!Ce||d.isExisting(fe)||this.oweStatus(t,e.objectApiName,Ce,W)}this.countWrites(t,e.objectApiName,Ae)}let _e=Ae.successCount,pt=Ae.updatedCount,$t=Ae.linkedExistingCount,x=Ae.failureCount,Y=Ae.unidentifiedExistingCount;if(o){let $=dt.reduce((ot,zn)=>ot+zn.records.length,0),W=dt.flatMap(ot=>ot.cleaned);o.sent+=$,o.succeeded+=_e,o.updated+=pt,o.linked+=$t,o.linkedToCreated+=Ae.linkedToCreatedCount??0,o.failed+=x,o.alreadyExists+=Ae.alreadyExistsCount,o.unidentified+=Y,o.rolesOfTheirOpportunity+=wt.linked,o.rolesGiven+=wt.given,o.writtenWithoutFields=Ae.writtenWithoutFields?ia(o.writtenWithoutFields,Ae.writtenWithoutFields):o.writtenWithoutFields,Ae.flagsNotKept&&(o.flagsNotKept=eu(o.flagsNotKept,Ae.flagsNotKept));let me=yt?$-(_e+pt+$t+x):0,fe=W.slice(0,$-me).filter(ot=>O.rows.has(ot.source)).length;o.sentOnTheirOwn+=fe,fe>0&&(o.onTheirOwnWhy=O.why);let Ce=[...ud(o),...Qt(t,e.objectApiName)];if(yt)throw this.stopStreamedNode(e,t,o,me,f),yt;c({objectName:e.objectApiName,status:"running",progress:0,message:`${e.objectApiName}, page ${o.pages}: ${hd(s,o,Ce)}`});return}let re=_e+pt+$t+b.length+z.linked+ae.linked+wt.linked,ve=re+x,oe=ve>0?x/ve:0,se=x>0&&Ae.alreadyExistsCount===x,rt=x>0&&!se&&(re===0||oe>.5),he=ag($t,Ae.linkedToCreatedCount??0),qe=pt>0?`, ${pt} updated through their external id`:"",Ve=Y>0?` (${Y} already in the target without Salesforce naming the record \u2014 their children lose the link)`:"",bt=$=>[...Ih(v),...D.size>0?[{count:D.size,why:vd}]:[],...z.notSent,...$?Qt(t,e.objectApiName):[]],Zt=bt(Q===0),In=pe>0?`, ${pe} written by the platform with their email`:"",Ct=ig(z.linked,pd(t,e.objectApiName)),Un=dg(ae.owners,ae.linked-ae.owners)+cg(wt.linked,wt.given),vt=dt.flatMap($=>$.cleaned),Je=$=>vt.slice(0,$).filter(W=>O.rows.has(W.source)).length,en=$=>$>0?`, ${$} ${$===1?"person account's contact":"person accounts' contacts"} sent on their own: the target wrote none with their account`:"",Xe=en(Je(vt.length)),Dt=b.length>0?`, ${Ed(s,b.length)}`:"",Mt=Q>0?`, ${$s(Q)}`:"",Rt=[Fi(Ae.flagsNotKept),ug(ae.values)].flatMap($=>$?[`, ${$}`]:[]).join(""),ct=ss(Ae.writtenWithoutFields),De=tg(t,e.objectApiName),Et=Ps(t,e.objectApiName),hn=n===void 0?Oh(t,e.objectApiName):"",eo=s.dryRun?"would be inserted":"succeeded",Gn=Tt.taken>0?` (${zf(Tt.taken,Tt.given,s.dryRun)})`:"",to=$=>`${_e} ${eo}${Gn}${qe}${he}${In}${Ct}${Un}${Dt}, ${x+_n($)} failed${Ve}${cn($)}`,gn=`${Xe}${Mt}${Rt}${Oe}${ct}${De}${Q===0?Et:""}${hn}`;if(yt){let $=dt.reduce((Ce,ot)=>Ce+ot.records.length,0),W=$-(_e+pt+$t+x)+Q;Od(t,e.objectApiName,W);let me=Q>0?` (${$s(Q)})`:"",fe=Je($-W+Q);throw this.saySentOnTheirOwn(t,fe,O.why),(n===void 0?t.onProgress:c)({objectName:e.objectApiName,status:rt?"error":"stopped",progress:100,message:`${f}: ${to(bt(!0))}, ${W} not sent${me}${en(fe)}${Rt}${Oe}${ct}${De}${Et}`}),yt}if(this.saySentOnTheirOwn(t,Je(vt.length),O.why),rt){t.failedObjects.add(e.objectApiName),re>0&&t.failedInPart.add(e.objectApiName);let $=_n(Zt);c({objectName:e.objectApiName,status:"error",progress:100,message:re===0?`Failed all ${e.objectApiName} records: ${x+$} failed${cn(Zt)}${Xe}${Oe}${hn}`:`${x+$}/${ve+$} ${e.objectApiName} records failed (>50%)${cn(Zt)}${Xe}${Oe}${ct}${De}${hn}${Fh}`})}else c({objectName:e.objectApiName,status:"done",progress:100,message:`${l}: ${to(Zt)}${gn}`})}catch(j){if(j instanceof be)throw j;t.failedObjects.add(e.objectApiName),t.failedCount+=S.length,t.errors.push({objectApiName:e.objectApiName,stage:"query",failedCount:S.length,attemptedCount:S.length,samples:[{recordSummary:"(stage failed before insert)",messages:[V(j)]}]}),c({objectName:e.objectApiName,status:"error",progress:100,message:`Error on ${e.objectApiName}: ${V(j)}`})}}};function ny(r,e){if(r.sample===void 0){if(e===void 0)return;throw new Error("A sample was handed to a run whose config copies every record, or walks from a record: run it as its config says, or ask the sample in its config. Nothing was read or written.")}if(r.inputMode!=="org"||e===void 0)throw new Error("The config asks a sample of the whole org, and the run was handed nothing to keep or take up its plan with: it would have copied every record. Nothing was read or written.");return{...e,options:r.sample}}function Pd(r,e,t,n){let o=t?.recordTypeMappings,s=Rs(e.anonymizePII,r,t?.anonymizationRules,n),i=t?.files?{maxFileBytes:t.files.maxFileSizeMB*1048576,acceptedAsIs:t.files.acceptedAsIs}:void 0,a=t?.writtenBefore,d=t?.beforeWrite,c=e.inputMode==="org",u=t?.stream,l=ny(e,u?.sample),f=c?{...u,everything:!0,writeWindow:xd,secondPassPageSize:xd,ceiling:void 0,wholeReadBound:u?.wholeReadBound??u?.ceiling??fo,...l?{sample:l}:{}}:u,p=[...new Set([...r.nodes.filter(Wc).map(O=>O.objectApiName),...e.excludedObjects??[]])],g=p.length>0?p:void 0,h=e.dryRun===!0?!0:void 0,m=Jo(e),R=e.keepContactPoints===!0?!0:void 0,b=ry(r,e,t?.roots);return b||e.inputMode==="record"&&typeof e.recordId=="string"?{...b?{roots:b}:{rootRecordId:e.recordId},rootObjectApiName:b?.objectApiName??r.nodes[0]?.objectApiName,expandOrphanParents:e.expandOrphanParents,maxRecordsPerObject:e.maxRecordsPerObject,fieldExclusions:e.fieldExclusions,excludedObjects:g,ownerMappings:e.ownerMappings,objectSoqlFilters:e.objectSoqlFilters,fieldMappings:e.fieldMappings,recordTypeMappings:o,anonymization:s,keepContactPoints:R,files:i,writtenBefore:a,beforeWrite:d,stream:f,dryRun:h,decisions:m}:e.maxRecordsPerObject!=null||e.fieldExclusions||g||e.ownerMappings||e.objectSoqlFilters||e.fieldMappings||o||s||R||i||a||d||f||h||m?{maxRecordsPerObject:c?void 0:e.maxRecordsPerObject,...c?{writeApi:"auto"}:{},fieldExclusions:e.fieldExclusions,excludedObjects:g,ownerMappings:e.ownerMappings,objectSoqlFilters:e.objectSoqlFilters,fieldMappings:e.fieldMappings,recordTypeMappings:o,anonymization:s,keepContactPoints:R,files:i,writtenBefore:a,beforeWrite:d,stream:f,dryRun:h,decisions:m}:void 0}function ry(r,e,t){let n=e.maxRoots??kr,o=r.nodes.find(a=>a.level===0)??r.nodes[0],s={...t?.plan?{plan:t.plan}:{},...t?.plan&&t.planOfTheRunRetried?{planOfTheRunRetried:!0}:{},...t?.keepAt!==void 0?{keepAt:t.keepAt}:{},...t?.fingerprint!==void 0?{fingerprint:t.fingerprint}:{},...t?.sourceRequestsLeft!==void 0?{sourceRequestsLeft:t.sourceRequestsLeft}:{},...t?.readTotal!==void 0?{readTotal:t.readTotal}:{}};if(e.inputMode==="record"&&t?.ids!==void 0){let a=o?.objectApiName;return a===void 0?void 0:{objectApiName:a,ids:[...t.ids],cap:n,...s}}if(!jc(e)||e.inputMode!=="soql")return;let i=wl(e.soqlQuery??"");if("issue"in i)throw Pe.of(Yo(i.issue,o?.objectApiName));return{objectApiName:o?.objectApiName??i.objectApiName,query:i.query,cap:n,...s}}var Jr="--checkpoint-first",Fd={switches:[Jr],values:["--checkpoint-keep-days","--checkpoint-exclude-object"]},oy=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function pg(r){return[` --checkpoint-first ${r.step??""}take a checkpoint of what ${r.run} writes before its`," first write: each object it writes, and each the"," target's flows that still run create as it writes"," them, held whole, as every checkpoint holds an object."," Its cost is that of the tables, not of the records",` written, and is said first. A rewind to it takes ${r.run}`," back (sandforge checkpoint rewind), and the work of"," anyone else on those objects since with it. Refused",` \u2014 another run writing, a limit, the disk \u2014 ${r.run}`," writes nothing, exit 1; deleted again when it writes",` nothing; with ${r.simulation}, says what it would hold and`," cost, and takes nothing (default: off)",...(r.note??[]).map(t=>` ${t}`)," --checkpoint-keep-days <n>"," the days that checkpoint is kept on this machine,"," 0 to 3650, 0 until it is deleted (default: 7)"," --checkpoint-exclude-object <ApiName>"," leave an object out of that checkpoint, named; a"," rewind leaves its records as they are; repeat for more"].join(`
8
- `)}function Vr(r){process.stderr.write(`${r}
9
- `),process.exit(2)}function hg(r,e=[]){let t=a=>{let d=[];for(let c=0;c<r.length;c++)r[c]===a&&c+1<r.length&&d.push(r[c+1]);return d},n=t("--checkpoint-keep-days"),o=t("--checkpoint-exclude-object");if(!r.includes(Jr)){let a=[...n.length>0?["--checkpoint-keep-days"]:[],...o.length>0?["--checkpoint-exclude-object"]:[]];a.length>0&&Vr(`${a.join(" and ")} ${a.length===1?"goes":"go"} with ${Jr}, which takes the checkpoint they set. Run with --help.`);return}for(let{flag:a,why:d}of e)r.includes(a)&&Vr(`${Jr} does not go with ${a}: ${d}`);n.length>1&&Vr(`--checkpoint-keep-days is given ${n.length} times: give it once.`);let s;if(n.length===1){let a=n[0];s=/^\d{1,4}$/.test(a)?Number(a):Number.NaN;try{fa(s,void 0)}catch{Vr(`--checkpoint-keep-days takes a whole number of days from 0 to 3650, not "${a}".`)}}let i=[];for(let a of o)oy.test(a)||Vr(`--checkpoint-exclude-object takes an object's API name, not "${a}".`),i.some(d=>d.toLowerCase()===a.toLowerCase())||i.push(a);return{...s!==void 0?{keepDays:s}:{},...i.length>0?{excluded:i}:{}}}function fg(r,e){return r!==void 0&&r.length>=15&&r.slice(0,15)===e.slice(0,15)}function sy(r){let e=r.self??Vu,t=r.elsewhere??(s=>Ju(s,e)),n=`A SandForge run is writing to ${r.orgName}: start this run once it has ended. No record was read.`,o=s=>s.writer!==void 0&&s.writer.pid===e.pid&&Date.parse(s.writer.hostStartedAt)===Date.parse(e.startedAt);return async s=>{let i=r.envLock?.(s);if(i!==void 0)return`${i}: start this run once it has ended. No record was read.`;for(let a of r.runs)for(let d of await a.list()){if(d.end!==void 0||!(fg(d.targetOrganizationId,s)||fg(d.targetOrgId,s)||d.targetOrgId===r.alias))continue;let u=r.own?.runId!==void 0&&d.runId===r.own.runId;if(o(d)?!u:t(d))return n}}}function gg(r,e){return{id:e.id,orgType:Mc({isScratch:r.scratch===!0,isSandbox:e.sandbox,edition:e.edition}),...e.edition!==void 0?{edition:e.edition}:{}}}function iy(r){let e=r.reason==="notAFolder"?"it is a file, not a folder":r.reason==="otherOwner"?"another user of this machine owns it, and could read and replace the checkpoints in it":`it could not be made${r.detail!==void 0?` (${r.detail})`:""}`;return`the checkpoints cannot be kept in ${r.path}: ${e}`}function ay(r){let e=-1;return({percentage:t})=>{let n=Math.floor(t/10);n<=e||(e=n,r(` ${af(t)}`))}}function mg(r){let e,t=()=>e??=(async()=>{let{join:o}=await import("node:path"),{takeOrgOf:s}=await import("./chunk-GTRU5AV5.mjs"),{openCheckpointStore:i}=await import("./chunk-XAMMIPZ4.mjs"),{nodeSyncRunCreations:a}=await import("./chunk-2R6GFNKF.mjs"),{nodeSeedRunCreations:d}=await import("./chunk-T7DDS4UQ.mjs"),{envLockHolder:c,envLockLine:u}=await import("./chunk-JUOQUG7U.mjs"),l=i({root:r.storeRoot??o(r.journalDir,"checkpoints"),...r.locksDir!==void 0?{locksDir:r.locksDir}:{}});if("refusal"in l)throw new Error(iy(l.refusal));let{store:f}=l,{session:p}=r,g=r.connect(p),h={id:r.org.id,alias:p.alias,username:p.username,instanceUrl:p.instanceUrl,orgType:r.org.orgType,metadata:{apiVersion:g.version,...r.org.edition!==void 0?{edition:r.org.edition}:{}}},m={log:R=>{R.startsWith("[WARN] ")&&r.say(`warning: ${R.slice(7)}`)},orgManager:{getOrg:R=>R===h.id?h:void 0},orgRegistry:{getCredentials:async R=>R===h.id?{accessToken:p.accessToken,instanceUrl:p.instanceUrl}:void 0}};return{deps:{org:s(g),store:f,handler:m,runWriting:sy({orgName:p.alias,alias:p.alias,runs:[a(r.journalDir),d(r.journalDir)],envLock:R=>{let b=c(f.locksDir,R);return b!==void 0?u(b):void 0},...r.own?{own:r.own}:{}}),...r.freeBytes?{freeBytes:r.freeBytes}:{}},org:{orgId:r.org.id,orgName:p.alias,alias:p.alias,username:p.username,instanceUrl:p.instanceUrl,registered:{orgType:r.org.orgType,...r.org.edition!==void 0?{metadata:{edition:r.org.edition}}:{}}}}})(),n=o=>({module:r.module,written:o.written,running:o.running,request:r.request,operationId:r.operationId,tool:"cli",keepDays:fa(r.request.keepDays,void 0)});return{async scope(o){let s=await import("./chunk-QQDZQCO2.mjs"),{deps:i,org:a}=await t();return s.scopeBeforeRun(i,a,n(o))},async take(o,s,i={}){let a=await import("./chunk-QQDZQCO2.mjs"),{deps:d,org:c}=await t();return a.takeBeforeRun({...d,...i.signal?{signal:i.signal}:{},onProgress:ay(r.say)},c,n(o),s)},async settle(o,s){let i=await import("./chunk-QQDZQCO2.mjs"),{deps:a}=await t(),d=await i.settleBeforeRun(a.store,o,s);return d.notDeleted!==void 0&&r.say(`warning: ${d.notDeleted}`),d.info}}}function Nd(r){return tl(r).map(e=>` ${e}`)}var dy=new Set(["TOO_MANY_RECORDS","API_BUDGET","DISK"]);function Ms(r){let e=r.message.replace(/\s*No record was read\.$/,""),t=dy.has(r.code)?"leave an object out of it (--checkpoint-exclude-object <ApiName>), ":"";return`The checkpoint before the run was refused: ${e} Fix what refuses it, ${t}or run without ${Jr} to write without one.`}function Cd(r){return r.code!==Tn?lf:r.refusal!==void 0?`${Ms(r.refusal)} Nothing was written.`:r.message}function cy(r){return r===null?"kept until it is deleted":`kept until ${r.slice(0,10)}`}function wg(r,e,t){return[`checkpoint before the run: ${r.checkpointId} '${r.name}', ${r.objects.length} object(s), ${r.records} record(s), ${cy(r.expiresAt)}`,` rewind to it: ${qt("checkpoint")} rewind --org ${e} --checkpoint ${r.checkpointId}${t?" --mute-automation":""}`,...r.notHeld.map(({objectApiName:n,reason:o})=>` not in the checkpoint: ${n} \u2014 ${o}`)]}function Md(r){return r.state==="deleted"?[sf]:[]}async function DS(r,e,t,n,o){try{let s=await r.settle(e,t);for(let i of Md(s))o(i);return s}catch(s){return o(`warning: the checkpoint '${e.name}' taken before the run, which wrote nothing, could not be deleted (${s instanceof Error?s.message:String(s)}): delete it with ${qt("checkpoint")} delete --org ${n} --checkpoint ${e.checkpointId}`),e}}var Bs="--leave-undeletable",Bd="UNDELETABLE_NOT_LEFT";function uy(r,e){let t=r.map(o=>`${o.objectApiName} (${o.records} records)`).join(", "),n=St(Bs)?`run again with ${Bs}`:`run ${at(Bs,"removal")}`;return{code:Bd,message:`The user SandForge connects as may not delete the records of ${t} in ${e}. Nothing was removed. Give that user Delete on those objects, or ${n} to remove the rest and leave them.`}}function yg(r,e,t,n=o=>process.stderr.write(`${o}
10
- `)){return async o=>{if(!r)return t(uy(o,e)),!1;let s=o.map(i=>`${i.objectApiName} (${i.records} records)`).join(", ");return n(`The user SandForge connects as may not delete the records of ${s} in ${e}.`),n(`Those stay, with the records they hang from; the rest is removed (${Bs}).`),!0}}function bg(r,e){let t;return async n=>{let o=await r.describeObject?.(e,n);return!o||!o.recordTypes.some(s=>!s.master)?o?.recordTypes:(t??=r.queryRecords(e,Co).then(Mo,()=>[]),Bo(o.recordTypes,await t))}}var oc=`sandforge clone \u2014 Forge a clone of one record, or of whole tables, from a source org
11
- to a target sandbox, or remove what a run of it created.
12
-
13
- Usage:
14
- npx sandforge clone \\
15
- --record <id> --source <alias> --target <alias> [options]
16
- npx sandforge clone \\
17
- --query "<SOQL>" | --record <id> --record <id>... \\
18
- --source <alias> --target <alias> [--max-roots <n>] [--roots-plan <file>]
19
- [--max-read-total <n>] [options]
20
- npx sandforge clone \\
21
- --object <ApiName> [--where <condition>] [--object <ApiName> [--where <condition>]]... \\
22
- --source <alias> --target <alias> [options]
23
- npx sandforge clone \\
24
- --depth all --source <alias> --target <alias> [--fit share] [--dry-run] [--yes]
25
- [options]
26
- npx sandforge clone \\
27
- --remove <summary.json> --target <alias> [--include-changed] [--accept-automation]
28
- [--mute-automation] [--leave-undeletable] [--json]
29
- [--preview] [--sweep | --sweep-list] [--sweep-late] [--sweep-untied] [--sweep-user <id>]
30
- [--audit <file>]
31
- npx sandforge clone \\
32
- --verify <summary.json> --target <alias> [--source <alias>] [--json] [--audit <file>]
33
-
34
- The target must be a sandbox or a Developer Edition org (a Trailhead
35
- playground is one). Its Organization record says which, and any other
36
- org, an org whose edition it does not say included, is refused as a
37
- production org before anything is written or deleted. --dry-run and
38
- --list-objects only read, and run against any org.
39
-
40
- Before it reads a row, the clone says what the target runs on the objects
41
- it writes: its active record-triggered flows, Apex triggers, Process
42
- Builder processes and workflow rules, per object and write, with what of
43
- them sends messages (SENDS MESSAGES) or runs after commit; its assignment
44
- and duplicate rules; and what keeps a flow from starting for the user the
45
- run writes as, and whether that user holds it (with --json, under
46
- targetAutomation). When any of them fires as the clone inserts its
47
- records, or as it updates those it writes a second time \u2014 a lookup
48
- filled in once its record exists, an order or a contract given back its
49
- status \u2014 or the target would not say what it runs, nothing is written
50
- unless --accept-automation is given. A bypass the user does not hold is
51
- given with the permission set of the target that holds it, which
52
- --mute-automation assigns for the run alone, under a lease.
53
-
54
- It then says what the target holds against the rows, read from its
55
- metadata: its active validation rules and what keeps them quiet, its
56
- active duplicate rules and whether each blocks an insert or lets it
57
- through, the fields only the target requires that the clone does not
58
- write, the lookup filters of the lookups it writes, and the daily API
59
- requests the target has left against those the run takes (with --json,
60
- under targetGaps). A gap a decision of --config or --template answers \u2014
61
- a default given to a field only the target requires \u2014 is said answered
62
- by it, as Review shows it decided, and no longer BLOCKING (answeredBy,
63
- with --json). None of it stops the clone. With --dry-run --json,
64
- adminChanges lists, for whoever administers the target, the changes to its
65
- metadata that would let the rows go in as they are \u2014 a picklist value to
66
- add to a record type, a field to lengthen, a rule to turn off \u2014 grouped by
67
- object and record type, each with its step in Setup; the clone makes none.
68
-
69
- Once every row is read and before the first is written, the clone counts
70
- the records it is about to write, per object, and the data storage they
71
- take by the sizes Salesforce documents, and the daily API requests they
72
- take, with those of a checkpoint taken first and of the record types read
73
- back after. It writes nothing past --max-total, nor more than the target's
74
- data storage or its daily API requests have left. It says the emails the
75
- target's flows send as the records go in, against the daily limits it has
76
- left \u2014 a Developer Edition's email alerts counted against its single emails
77
- too \u2014 and writes nothing past them: a record whose flow fails in the save
78
- is refused there, and the org's own emails stop for the day. What sends
79
- and could not be read \u2014 a flow's definition refused or past the read's
80
- bound, a flow a package installed, which the org lets no one read \u2014 is
81
- said not counted (with --dry-run --json, under writePlan.emailsUncounted),
82
- and refuses nothing: --accept-automation already covers it.
83
-
84
- Required:
85
- --record <id> Source record ID (any object type \u2014 prefix detected automatically);
86
- may come from --template instead; --query (below)
87
- clones the records a query chooses, --object whole
88
- tables
89
- --source <alias> sf CLI alias of the source org
90
- --target <alias> sf CLI alias of the target sandbox
91
-
92
- Clone records and what each reaches, in place of one --record:
93
- --query "<SOQL>" the records a query chooses, each cloned with what the
94
- clone of that record copies: a record they share is
95
- read and written once, and a record of the query's
96
- object they name comes as a parent, as a clone of one
97
- record brings it. The query is SELECT Id FROM <Object>
98
- [WHERE \u2026] [ORDER BY \u2026] [LIMIT n]; its WHERE chooses
99
- the records and filters no other read. They are read
100
- by their ids first, ORDER BY Id unless the query
101
- orders them: a LIMIT without an order would choose
102
- other records each time. A GROUP BY, HAVING, OFFSET,
103
- FOR, WITH, USING SCOPE, UPDATE or an aggregate would
104
- have the clone read other records than the query
105
- returns, and is refused (ROOTS_QUERY_REFUSED), exit 2.
106
- Not with --record, --object, --where, --depth all, or
107
- --fit and the flags a sample is drawn by.
108
- --record <id> --record <id>...
109
- records named one by one, of one object, each cloned
110
- with what the clone of that record copies
111
- --max-roots <n> the most records a run takes this way, 1 to 2000
112
- (default: 200)
113
- A query that chooses more, without a LIMIT, is refused
114
- before anything else is read (ROOTS_EXCEEDED), exit 1:
115
- add ORDER BY CreatedDate DESC, Id DESC LIMIT <n> to
116
- take the newest, narrow its WHERE, or raise
117
- --max-roots; past
118
- 2000, copy a sample of the whole org (--depth all
119
- --fit share) with a filter on its roots. A query that
120
- chooses none is refused too (NO_ROOTS), exit 1.
121
- --roots-plan <file> a dry run keeps there the records its query chose, in
122
- place of what a dry run before it kept; a run given it
123
- writes those records and no other: one the query
124
- chooses after the dry run is not written, and one
125
- deleted since is said gone. A plan of another org,
126
- another query or records, or whose ids changed, is
127
- refused (ROOTS_PLAN_MISMATCH), and one that is not
128
- there (ROOTS_PLAN_GONE), exit 2; a plan a day old or
129
- more has the query read again, and the run says so.
130
- Not with --resume: a run taken up writes the records
131
- its journal names.
132
- --max-read-total <n> the most records the run reads in all before it
133
- writes (default: 50000)
134
- It holds every record it reads until it writes. Past
135
- it, refused with nothing written
136
- (READ_BOUND_EXCEEDED), exit 1: fewer records, a
137
- shallower --depth, --exclude-object, or a higher bound.
138
- The read of what the records reach is held besides to
139
- a tenth of the requests the source has left today
140
- (API_BUDGET_EXCEEDED), exit 1.
141
- The run says where its records came from, what its
142
- read came to in records and requests of the source,
143
- per object how its rows came in \u2014 the records, those
144
- read under them, those they name \u2014, and the records
145
- written of those chosen; with --json, under roots,
146
- reads and each object of readByObject (origin,
147
- readUnder). --verify says how many of them the target
148
- holds.
149
-
150
- Clone whole tables, in place of --record:
151
- --object <ApiName> a table to clone; repeat for more. The first is where
152
- discovery starts, and each other must be in its graph
153
- (--depth, --max-nodes): a parent one of them points at,
154
- or a child that hangs from one. Every other object
155
- discovery reaches is left out. A table no clone
156
- writes \u2014 users and their access, setup, a record's
157
- history, feed or sharing rows, a file \u2014 is refused
158
- before a row is read (TABLE_NEVER_CLONED), exit 2.
159
- --where <condition> the rows of the --object before it: a SOQL condition,
160
- written without WHERE (default: every row)
161
- It narrows that table alone: every other --object is
162
- read whole, whatever rows the first keeps. For records
163
- with what each of them reaches \u2014 the accounts of an
164
- industry with their contacts, opportunities and cases
165
- \u2014 give --query "SELECT Id FROM Account WHERE Industry
166
- = 'Energy'" instead.
167
- The run is the panel's run of a query: each table read
168
- with the org's cursor in the order of its ids and
169
- written a page at a time, so the run holds a page of
170
- rows whatever a table holds, and keeps what it wrote in
171
- its journal as it goes; --resume reads each table after
172
- the last row the run wrote. Parents go before the tables
173
- that point at them, their lookups given the records the
174
- run created. With --upsert, every page of a table goes
175
- by one external id, the first whose value each row
176
- the run reads of it holds and no two share. A run that
177
- copies files (--files) reads each table whole. Not
178
- with --record, --expand-orphans or --rehearse. With
179
- --template, the template's choices go with the
180
- tables, its record or query aside.
181
-
182
- Clone the whole org, in place of --record:
183
- --depth all every object of the source the target can take, from
184
- no record and no table, each read a page at a time in
185
- the order of its ids and written ten thousand records
186
- at a time: as a Bulk API job from 2000 of them, by REST
187
- under that and for an object no job writes (an active
188
- duplicate rule watches it, the Bulk API refuses it).
189
- What it leaves out is said with why: setup, metadata,
190
- what only the platform writes, what the target cannot
191
- take, an empty table. Past 1950 objects or 20000 pairs
192
- of related objects, discovery refuses it, never cuts it.
193
- Its dry run stops at the write gate once the source is
194
- counted, and reads no row: per object the records it
195
- would insert and how many go in jobs, the API requests
196
- of both orgs, the Bulk API batches, the data and file
197
- storage, what it leaves out and why, the personal
198
- fields it copies as they are, and each refusal a real
199
- run would meet, exit 1 when there is one (with --json,
200
- under wholeOrg and wouldBeRefused).
201
- A real run asks before its first write, naming the
202
- records and objects, the requests and batches, the
203
- objects of managed packages (the mute reaches none of
204
- what they run), the phone numbers it writes empty and
205
- the personal fields it copies as they are: --yes writes
206
- without the question; with no terminal to answer it,
207
- the run is refused (CONFIRMATION_UNAVAILABLE). It keeps
208
- its journal, which --resume takes it up from and
209
- --remove takes it back from, and exits 3 when the
210
- target refused part of it. --max-total holds it as any
211
- run: give it what the dry run counted. --exclude-object
212
- leaves an object out, --filter narrows one; --files,
213
- off unless given, copies the org's files. Not with
214
- --record, --object, --where, --template, --custom-depth,
215
- --max-nodes, --max, --expand-orphans, --rehearse or
216
- --upsert.
217
- --no-anonymize with --depth all, copy the personal data as the source
218
- holds it, a production org's too
219
- --yes with --depth all, write without the question
220
-
221
- Copy a sample of the whole org that fits the target, with --depth all:
222
- --fit share rather than every record, a sample: roots drawn of
223
- each object, each with its children and the records
224
- it names, none without a record it cannot be written
225
- without; the largest share of the roots that fits
226
- what the target has left \u2014 80 % of the data storage
227
- its /limits say, half a MB off for their rounding,
228
- less what its automation still running creates
229
- under the records \u2014 and --max-total, its default
230
- of 10000 too: raise it to take more. The reference
231
- data go whole. Small parents and the price catalog
232
- go whole while they fit a quarter of the room the
233
- target has, 80 % of what it has left once half a MB
234
- is off, whatever --fit-within and --max-total ask;
235
- a root that would bring in more than a tenth of that
236
- room by itself is set aside and named (heavy roots
237
- set aside:). Drawn before the gate, from ids,
238
- lookups and the few values that decide what it
239
- keeps \u2014 record types, creation dates \u2014, the plan
240
- is kept on disk, the ids of each object and no
241
- value: a dry run's in forge-samples/ under the
242
- journal directory for a day, a run's beside its
243
- journal. The gate counts the plan, and the run
244
- writes its records and no other: a lookup to a
245
- record outside it is written empty and said, a
246
- record gone from the source since is said apart,
247
- one whose parent changed since is held back and
248
- failed. The dry run says the sample
249
- (sample:), per object what it keeps and how, what
250
- goes whole (whole:), the roots set aside (heavy
251
- roots set aside:), what it leaves out and why (not
252
- in the sample:), the lookups left empty (left
253
- empty:) and its plan (sample plan: <folder>); with
254
- --json under wholeOrg.sample, a run's under sample,
255
- and what it wrote of the plan under result.sample.
256
- Not with --files or --list-objects.
257
- --fit-within <MB> take no more than this many MB of the target
258
- --fit-seed <n> the seed the roots are drawn by (default: 1)
259
- The same seed and setup draw the same records.
260
- --fit-draw uniform|recent|oldest
261
- uniform spreads the roots over each object, reading
262
- the id of every root; recent takes the newest and
263
- oldest the oldest by creation date, reading only
264
- those it keeps (default: uniform)
265
- --fit-window created|modified:<from>..<to> | created|modified:<n>d
266
- draw only the roots made (or last modified) in the
267
- window, UTC: a date alone starts at 00:00Z and, as
268
- the end, takes the whole day; either end may be left
269
- out; <n>d is the last n days, fixed when the sample
270
- is drawn. The records under or above a root come
271
- whatever their date.
272
- --fit-where <Object>=<WHERE>
273
- draw the roots of Object only among the records
274
- that match (repeatable, one per object). Unlike
275
- --filter, the records under or above the roots come
276
- whatever it says, and no lookup is written empty for
277
- it.
278
- --fit-strata <Field>|<Object>.<Field>
279
- keep the same share of the roots of each value of a
280
- picklist, checkbox or lookup (RecordTypeId, OwnerId),
281
- at least --fit-floor of each value (repeatable; Field
282
- alone: every object that has it)
283
- A draw told which roots to take names them under
284
- its sample: line \u2014 roots:, per object the roots in
285
- the draw of those of the source; strata:, the roots
286
- and those kept of each value \u2014 and its share is of
287
- the roots in the draw: all of them taken, it is
288
- limited by the draw; widen them to take more.
289
- Refused before any id is read, nothing written,
290
- every problem named with its way out, exit 2: a
291
- field that cannot stratify the roots, a condition
292
- the source refuses, an object with no root of its
293
- own or copied whole, more than two semi-joins with
294
- its --filter (SAMPLE_DRAW_INVALID); exit 1, only
295
- the counts read: no root left in the draw
296
- (SAMPLE_DRAW_EMPTY).
297
- --fit-parents all|required
298
- all copies a record outside the sample that an
299
- optional lookup names, without its children;
300
- required writes such a lookup empty (default: all)
301
- --fit-children <n>|all most children a record brings through each relation,
302
- the newest; a master record brings every detail
303
- (default: 100)
304
- --fit-whole <Object> copy this object whole (repeatable)
305
- --fit-floor <n> roots kept of each object whatever the share
306
- (default: 1)
307
- --fit-plan <folder> write the records of the plan a dry run drew, as its
308
- line sample plan: printed it, within a day: refused
309
- when drawn of another org or with other flags, or
310
- changed since (SAMPLE_PLAN_MISMATCH), or not there
311
- (SAMPLE_PLAN_GONE), exit 2. The run moves it beside
312
- its journal; one that writes nothing puts it back.
313
- Not with --resume, which writes the plan its journal
314
- names: gone, SAMPLE_PLAN_GONE, exit 2.
315
- Refused, exit 1: a target that would not say its
316
- storage, with neither --fit-within nor --max-total
317
- (SAMPLE_STORAGE_UNREAD); the objects copied whole
318
- and the floors alone past what it may take, the
319
- heaviest named (SAMPLE_CANNOT_FIT; with --json,
320
- refused.sample names what held it, limitedBy, and
321
- of a bound in MB the needMB and budgetMB); more
322
- than a million records to hold (SAMPLE_TOO_LARGE); the
323
- roots' ids past a tenth of the source's requests
324
- left today (API_BUDGET_EXCEEDED); a target that has
325
- less room than the plan was fitted to: simulate
326
- again (STORAGE_EXCEEDED).
327
-
328
- Options:
329
- --depth <mode> direct | full | custom | all (default: custom)
330
- --custom-depth <n> traversal depth when --depth is custom (default: 5)
331
- --max <n> max records cloned per object (default: unlimited)
332
- --list-objects print the objects discovery reached, then stop
333
- Answers "why was my object not cloned?" \u2014 an object
334
- absent from this list was never in the graph. With
335
- --json, stdout carries them as JSON: each object's
336
- record count, depth and whether it is included, and
337
- whether the graph was truncated.
338
- --max-nodes <n> objects discovery may reach (default: 50)
339
- Raise it when the summary says TRUNCATED and an
340
- object you expected is missing, e.g. the lines of an
341
- Opportunity's quotes. The prices, products, price
342
- books and selling models the lines use come whatever
343
- the cap, as do the items of an activated order and
344
- the schedules of an opportunity's products. Each
345
- parent a record reached cannot be written without
346
- takes the cap one object further, up to twice it.
347
- An empty table takes no place under it, and nothing
348
- is reached through it; discovery reads four times
349
- the cap in objects at most.
350
- --anonymize anonymize PII fields (default: off)
351
- With --depth all, on unless --no-anonymize when the
352
- source's Organization record says a production org.
353
- --keep-contact-points write emails and phone numbers as read (default: off)
354
- Off, every record is written with its email addresses
355
- under .invalid and its phone numbers in a fictional
356
- range, anonymized or not, so what the target's flows
357
- and email alerts send to them reaches no one. On,
358
- they may reach the real people the records name.
359
- --dry-run skip writes, surface scoped queries (default: off)
360
- It reads the automation and counts the records as a
361
- real run does, and says what would stop that run,
362
- each under the code that run is refused with: a real
363
- run would be refused (CODE): ... With --json, under
364
- wouldBeRefused, and the codes under wouldBeRefusedCodes.
365
- --rehearse have the target judge the rows, keep none (default: off)
366
- Reads and prepares every row as a real run would,
367
- then creates a sample of them in the target \u2014 every
368
- row up to 200, one per object, record type and set of
369
- fields given a value past it, with the records they
370
- name \u2014 in composite calls that each fail on purpose,
371
- so that every write is rolled back. Prints each
372
- refusal (status code, field, rows) and what could not
373
- be judged (with --json, under rehearsal). The target's
374
- automation runs inside each call: emails, @future and
375
- Queueable jobs, platform events published after
376
- commit and the asynchronous paths of Flows never
377
- leave it; platform events published immediately and
378
- callouts do. Refused against a production org, and,
379
- like a real run, without --accept-automation when the
380
- target runs automation on insert. Not with --dry-run,
381
- --upsert, --files, --remap-csv or --list-objects.
382
- --accept-automation write although the target runs flows or Apex
383
- triggers as the clone inserts, or as it updates the
384
- records it inserted, or could not say what it runs
385
- (default: off)
386
- --accept-emails write although the target delivers every email of
387
- what still runs as the clone writes, or would not say
388
- whether it does; --accept-automation never stands for
389
- it. Asked only when what still runs sends one: flows,
390
- processes and workflow rules with an email action,
391
- those whose definition was not read, and the
392
- assignment rules --apply-assignment-rules applies,
393
- whatever --mute-automation leaves. Whether the org
394
- delivers them is read with one line of anonymous Apex
395
- that sends nothing,
396
- Messaging.reserveSingleEmailCapacity(1), as the user
397
- the run writes as, never in a production org; on
398
- System email only or No access, none of them goes
399
- out, the org still counts them against its daily
400
- limits, and nothing is asked. What an Apex trigger
401
- sends is read nowhere (default: off)
402
- --mute-automation mute the target's automation for the run through its
403
- own bypass: assign the user the run writes as, for the
404
- run alone, the permission sets holding the custom
405
- permissions its flows, processes and workflow rules
406
- test to stay quiet, and take them back as it ends.
407
- What no bypass keeps quiet (an Apex trigger, a managed
408
- package's flow) still runs, and still needs
409
- --accept-automation. Refused on a production org and
410
- for a user who cannot assign permission sets, exit 1;
411
- a dry run says what would be muted and assigns nothing
412
- (default: off)
413
- ${pg({run:"the run",simulation:"--dry-run"})}
414
- --max-total <n> most records the run may write in all (default: 10000)
415
- Counted once every row is read: past it, nothing is
416
- written. --max caps each object, this the whole run.
417
- --max-records-per-object <n>
418
- most records one read of an object takes
419
- (default: 50000)
420
- An object with more is read to it and said
421
- TRUNCATED. A clone of a record holds what it reads,
422
- so a higher number takes more memory; 1000000 at most.
423
- --upsert use external Id upsert when available (default: insert)
424
- Skips DUPLICATE_VALUE on re-runs of the same source records.
425
- --expand-orphans single-hop expand orphan parent FKs (default: off)
426
- Clones missing parents (out-of-graph) so child FKs resolve.
427
- --max-orphans <n> with --expand-orphans, most parents from outside the
428
- run it copies, 1 to 1000 (default: 20)
429
- Past it, the rows that cannot be written without one
430
- are refused, and the summary says how many parents
431
- were left and of which objects.
432
- --apply-assignment-rules
433
- apply the target's assignment rules (default: off)
434
- Off, every write says Sforce-Auto-Assign: FALSE and
435
- keeps the owner the run sets. On, the target's active
436
- assignment rules may give the Cases, Leads and
437
- Accounts the run writes another owner, and mail them.
438
- --skip-preflight skip pre-execute target row count (default: off)
439
- The preflight queries each object on target so the user
440
- can see existing volume before pressing through.
441
- --json emit JSON summary on stdout (CI mode) (default: off)
442
- stdout then carries the JSON alone, and every other
443
- line goes to stderr. Saved to a file, the summary is
444
- what --remove takes the run back from. With
445
- --list-objects, the JSON is the objects of the graph.
446
- A run refused before its first write prints
447
- "refused": {"code", "message"} instead, the code its
448
- line names: refused (MAX_TOTAL_EXCEEDED): ..., each
449
- other reason under "alsoRefused", on a line of its own.
450
- How a run ended is under result.status: success,
451
- partial or failure, as its status: line says it.
452
- --fail-on-partial exit 3, not 0, when the run wrote some records and
453
- the target refused others (default: off)
454
- --summary <file> write the summary to <file> as the run goes
455
- The JSON --json prints, written after each object
456
- with what the run has created so far ("running":
457
- true), then whole once it ends. Ctrl-C stops the run
458
- between two calls to the org and writes what it had
459
- created by then ("interrupted": true), as --json then
460
- prints it: --remove takes the run back from either.
461
- A file already there is not overwritten. Not with
462
- --list-objects or --rehearse.
463
- --resume <journal|id> take up where it stopped a run that did not end \u2014 a
464
- Ctrl-C, a failure, a process killed \u2014 from its journal:
465
- its file, or its run id in the journal directory. Each
466
- record that run wrote is linked to and never written
467
- again, the lookups and statuses it still owed are
468
- given, and the rest is written. The same record, orgs,
469
- depth, choices and flags as the run it takes up, or it
470
- is refused; a run that ended is refused too. Every run
471
- that writes keeps its journal there (see
472
- SANDFORGE_JOURNAL_DIR), and says where as it starts.
473
- The calls the run had under way when it stopped are
474
- looked for in the target first: a row found there is
475
- kept as written by the run, never sent again; one the
476
- target may hold already stops the resume before it
477
- writes (see --write-uncertain).
478
- Not with --dry-run, --rehearse or --list-objects.
479
- --write-uncertain with --resume: write all the same the rows of a call
480
- under way when the run stopped that the target may
481
- already hold, records the resume cannot tell from
482
- them being there \u2014 each may then be there twice.
483
- --exclude <obj.field> skip a field on an object during clone (repeatable)
484
- e.g. --exclude Account.Description --exclude Account.NumberOfEmployees
485
- Matched whatever its case. One that names no object
486
- or field of the source refuses the run before a row
487
- is read, exit 2, naming the field nearest it
488
- (FIELD_EXCLUSION_UNMATCHED); a dry run says it, as
489
- the summary's result.fieldExclusionsUnmatched does.
490
- --exclude-object <obj> leave an object out of the clone (repeatable)
491
- e.g. --exclude-object PricebookEntry
492
- Out whether discovery reaches it or the run would
493
- add it past the cap. What it costs is said, not
494
- written: the records that cannot be written without
495
- one of its records, and the orders left drafts.
496
- --owner-map <src=tgt> remap OwnerId from source User Id to target User Id (repeatable)
497
- e.g. --owner-map 005AB...=005XY...
498
- Useful when source records were authored by users
499
- that don't exist on the target sandbox (ex-employees).
500
- A target user the target holds inactive is refused
501
- before anything is read (OWNER_MAP_INACTIVE), and
502
- one it holds no user of (OWNER_MAP_UNKNOWN).
503
- --filter <obj=where> per-object SOQL WHERE filter (repeatable)
504
- e.g. --filter "Case=Status = 'Open' AND CreatedDate > LAST_N_DAYS:30"
505
- Lets BAs narrow a clone to a subset without changing
506
- graph topology. Filter is appended via AND (...) to
507
- the scope-derived clause. Max 512 chars per filter,
508
- max 50 filters total.
509
- --map <obj.src=tgt> per-object source\u2192target field rename (repeatable)
510
- e.g. --map Account.Region__c=Region__pc
511
- Handles schema drift between source and target
512
- (managed-package re-key, namespace change). The
513
- source field is dropped and the value written to
514
- the target field name on insert.
515
- --config <file.json> the run's choices from a JSON file: the decisions
516
- taken in Review's Gaps row (picklistValueMappings,
517
- recordTypeMappings, defaultValues, truncateFields,
518
- skippedRows, ignoredGaps), the fields and objects
519
- left out (fieldExclusions, excludedObjects), the
520
- filters (objectSoqlFilters) and the mappings
521
- (ownerMappings, fieldMappings), as a Forge config
522
- names them. Checked as the panel checks a run's
523
- config; any other key is refused. The flags above
524
- win over the file: their exclusions are added, their
525
- filters and mappings replace the file's for the same
526
- object, user or field.
527
- --template <file.json> a template the Template tab exported: its decisions,
528
- exclusions, filters and mappings, as --config takes
529
- them, and its depth, caps, anonymization, contact
530
- points and orphan parents, each unless its flag is
531
- given. Its record is cloned when --record is not
532
- given; a template of a query needs --record, or
533
- --object. Not with --config.
534
- --remap-csv <file> write the source\u2192target ID remap table to a CSV
535
- file (header: sourceId,targetId). BA reconciliation:
536
- "where did source X go on the target sandbox?"
537
- --files copy the files of the cloned records (default: off)
538
- Salesforce Files (the latest version of each) and
539
- attachments, after the records they hang on. The
540
- total is checked against the target's file storage
541
- before anything is written: past it, refused
542
- (FILE_STORAGE_EXCEEDED), as when that storage could
543
- not be read (FILE_STORAGE_UNREAD) or the files not
544
- all looked up (FILES_UNREAD).
545
- --max-file-size <MB> largest file --files copies, 1 to 35 (default: 10)
546
- A larger file is left out and listed, never cut.
547
- --files-as-is accept that files are copied as they are: their
548
- content cannot be anonymized. Required with --files
549
- when --anonymize is on.
550
- --audit <file> record the run in an audit trail kept in <file>
551
- The entry the panel keeps in Reports -> Audit trail:
552
- per object the records created, updated and lost,
553
- the orgs, the outcome, the user as a hash of the
554
- username, and, for a run refused before it wrote,
555
- the code of what refused it. Counts only, never a
556
- value of a record. Each run adds its entry to the
557
- file; a dry run, --list-objects and --rehearse write
558
- nothing, and add none.
559
- -h, --help show this help and exit
560
-
561
- Remove what a run created:
562
- --remove <file> the summary a run printed with --json, saved to a file,
563
- or the journal of a run: every part of it, the run it
564
- took up and each time it was taken up
565
- Deletes from --target the records that run created,
566
- as the wizard removes a run from Recent runs: children
567
- first, never a record the target already held, and a
568
- record kept while records that stay depend on it. The
569
- target must be the org the run wrote to. A dry run's
570
- summary is refused: it created nothing. So is a run
571
- that still writes its journal, from a terminal or
572
- from VS Code, and the preview of its removal
573
- (RUN_WRITING), the run named: stop it, or let it end.
574
- The removal holds the journal while it deletes: a
575
- --resume of it meanwhile is refused (RUN_WRITING).
576
- What a removal wrote to the records it left is kept
577
- beside the summary, clone-summary.removals.json for
578
- clone-summary.json, and the next --remove of that
579
- summary reads it: what a removal wrote is no change
580
- since the run. Keep that file with the summary.
581
- A summary of a run past 50 000 records keeps their ids
582
- in its journal, which the removal reads them from.
583
- Of a run stopped and taken up with --resume, one
584
- summary per part, it is kept beside the journal too:
585
- the removal of any part, or of the journal, reads what
586
- the others wrote, and once a part's own records are
587
- gone, takes what an earlier removal of another part
588
- left. What the run wrote to a record of another part
589
- is no change since the run. The journal's removal
590
- takes the parts the last first, each read against
591
- its own span: what someone changed, or made, between
592
- two parts stays.
593
- --include-changed remove also the records changed since the run, and
594
- what was added to them since (default: kept)
595
- --accept-automation delete although the target runs flows, Apex triggers,
596
- processes or workflow rules as the records go, those
597
- --sweep deletes included \u2014 before or after a delete,
598
- or as an activated order is set back to Draft for
599
- its delete \u2014 or could not say what it runs
600
- (default: off)
601
- --mute-automation mute the target's automation for the removal through
602
- its own bypass, as for a run: the permission sets
603
- holding the bypasses of what fires as the records go,
604
- those --sweep deletes included, assigned to the user
605
- it deletes as, for the removal alone, and taken back
606
- as it ends; what no bypass keeps quiet still needs
607
- --accept-automation (default: off)
608
- --leave-undeletable remove the rest when the user the removal runs as
609
- may not delete the records of some objects of the
610
- run, leaving those with what they hang from; without
611
- it the removal stops before its first delete and
612
- names them (default: off)
613
- --preview say what the removal would do, and do nothing: per
614
- object the records it would delete, those gone
615
- already, those changed since the run and who changed
616
- them, those it could not see, and what a removal run
617
- now would be refused for, each under the code it is
618
- refused with: a removal would be refused (CODE): ...,
619
- with --json the codes under "refusalCodes", in the
620
- order of "refusals". It reads the records, as
621
- the removal reads them before its first delete, and
622
- writes nothing: not to the org, not beside the
623
- summary. With --sweep, it lists what the sweep would
624
- take, and reads what fires on it with the run's own.
625
- Not with --sweep-list or --audit.
626
- A removal takes no --dry-run: one that did not read
627
- it would delete for real.
628
- --sweep before the run's records go, delete too what the
629
- target's automation made for the run, that the run's
630
- id map does not hold: what the run's user created
631
- under the run's records, what they point at, or what
632
- hangs from those, three links at most, at most a
633
- minute after the record it is tied to \u2014 in the
634
- objects the run wrote and their children, tasks,
635
- events, feed, email messages, notes, case comments,
636
- and the objects the target's flows create. What a
637
- record of the run points at by a lookup the org
638
- refuses the delete for (an asset its case names)
639
- goes once that record is gone. Listed and kept: what
640
- is tied to the run but came later, up to 15 minutes,
641
- or as the org's Automated Process user; and what the
642
- run's user created in the run's window, a second
643
- before its first write to a minute after its last,
644
- tied to nothing of it.
645
- What anyone changed more than 2 s after the run's
646
- last write, and after its own creation, stays \u2014 the
647
- run's user and its automation too \u2014 unless
648
- --include-changed, and the sweep then ends partial,
649
- exit 3; a change made before the run's last write
650
- reads as unchanged. Runs alone when an earlier
651
- --remove took every record of the run. Of a clone of
652
- the whole org, the removal says the sweep is off
653
- unless given: the run's window spans hours, and a
654
- sweep looks at 300 objects at most
655
- (default: off)
656
- --sweep-late with --sweep, take too what it lists as made late;
657
- with --sweep-list, say what it would take
658
- --sweep-untied with --sweep, take too what it lists as tied to
659
- nothing of the run; with --sweep-list, say what it
660
- would take; refused when another run of this
661
- machine wrote to the target in the run's window, or
662
- when that user created records there on objects
663
- neither the run nor the automation reaches (hand
664
- work, likely)
665
- --sweep-user <id> with --sweep or --sweep-list, the user the run wrote as,
666
- for a run whose summary does not keep it: the sweep
667
- reads it otherwise from the run's records, and is
668
- refused when none is left or several users made them
669
- --sweep-list list what --sweep would delete, per object with a few
670
- names and how many it ties to the run, and delete
671
- nothing, the run's records included; exit 3, as a
672
- refused --sweep, when it says the sweep is refused
673
- What a sweep leaves, and why: what another user
674
- created, a colleague's or an integration's; what is
675
- tied to nothing, unless --sweep-untied; what came
676
- more than 15 minutes after its record, or after the
677
- removal began, which cannot be told from work done
678
- by hand; what anyone changed after the run's last
679
- write, the run's own user included, unless
680
- --include-changed; what the
681
- automation changed or deleted rather than created,
682
- which a checkpoint taken before the run takes back;
683
- what left the org (emails, outbound messages); more
684
- than 10 000 records of one object; and what the
685
- panel, another machine or a CI wrote meanwhile, which
686
- a sweep does not see
687
- --json print what became of the records as JSON on stdout,
688
- every other line on stderr; refused before its first
689
- delete, "refused": {"code", "message"}, the code its
690
- line names: refused (CODE): ... \u2014 a production org
691
- (PRODUCTION_TARGET), what fires as it deletes
692
- (AUTOMATION_NOT_ACCEPTED), its mute (MUTE_PRODUCTION,
693
- MUTE_NO_RIGHT, MUTE_FAILED), objects its user may not
694
- delete (UNDELETABLE_NOT_LEFT), an org that is not the
695
- one the run wrote to (OTHER_ORG, its --preview too)
696
- --audit <file> record the removal, and the sweep, in the audit trail
697
- kept in <file>
698
-
699
- Verify what a run created:
700
- --verify <file> the summary a run printed with --json, saved to a file,
701
- or the journal of a run, every part of it
702
- Reads back from --target every record the run created,
703
- after a pause and again until two readings agree (three
704
- at most, two seconds apart): those there, those in the
705
- recycle bin, those neither, out of the user's sight;
706
- checks on twenty records of each object that the
707
- lookups the run set point at the ids their parents got,
708
- reading the source records in --source; and lists the
709
- records changed since the run, which --remove keeps
710
- unless --include-changed. Only reads, from either org.
711
- Exits 0 when VERIFIED, 3 when PARTIAL (a record not
712
- there, a lookup that does not hold, or a part that could
713
- not be checked) and 4 when UNSTABLE (no two readings
714
- agreed: something still writes to the records).
715
- --source <alias> the org the run read from (default: the summary's)
716
- A lookup the clone left out with --exclude reads as
717
- one left empty.
718
- --json print the verification as JSON on stdout, every other
719
- line on stderr; refused for an org that is not the
720
- one the run wrote to, exit 1, "refused": {"code",
721
- "message"}, the code its line names: refused
722
- (OTHER_ORG): ...
723
- --audit <file> record the verification in the audit trail kept in
724
- <file>
725
-
726
- Environment:
727
- SANDFORGE_FORGE_PAGE_SIZE=<n>
728
- a diagnostic: read every statement through the org's
729
- cursor and hand it on in pages of <n> rows, as a run of
730
- whole tables reads, to see a clone's paged read against
731
- a real org. Not a setting: an org answers in pages of
732
- 200 to 2000 rows, and a page of <n> is cut from them.
733
- SANDFORGE_JOURNAL_DIR=<dir>
734
- where every run that writes keeps its journal, in
735
- <dir>/forge-runs/ (default: ~/.sandforge)
736
- What the run wrote, read and still owes, line by line
737
- as it goes, ids only: what --resume takes a run up
738
- from, and what --remove takes it back from however it
739
- ended.
740
-
741
- Exit codes:
742
- 0 the clone ran, a run the target refused some records of too unless
743
- --fail-on-partial; the rehearsal ran, whatever it found refused; the removal
744
- took every record it set out to take; the preview said what a removal
745
- would do, refusals included
746
- 1 the clone or the removal could not run; the clone produced only failures,
747
- or its files were refused; --resume could not take the run up
748
- (RESUME_UNAVAILABLE, RESUME_TARGET_CHANGED, RESUME_CHANGED,
749
- RESUME_UNCERTAIN); the target is a production org; the target
750
- runs automation on insert or on the updates the clone makes after its
751
- inserts, or the removal's deletes fire automation, and
752
- --accept-automation was not given; the target delivers the emails of
753
- what still runs, or would not say whether it does, and --accept-emails
754
- was not given (EMAILS_NOT_ACCEPTED); the checkpoint asked first was
755
- refused or could not be taken (CHECKPOINT_REFUSED); the run would write
756
- more than --max-total records, more than the target's data storage
757
- has left or more emails than it has left today, or would take more API
758
- requests than it has left today (nothing is written or deleted then);
759
- a clone of the whole org nobody answered the question of
760
- (CONFIRMATION_UNAVAILABLE) or that was declined (WRITE_DECLINED), or
761
- whose dry run says a real run would be refused; a sample of it that
762
- could not be drawn (SAMPLE_STORAGE_UNREAD, SAMPLE_CANNOT_FIT,
763
- SAMPLE_TOO_LARGE), or whose draw leaves no root (SAMPLE_DRAW_EMPTY);
764
- a query that chooses no record (NO_ROOTS) or more than --max-roots
765
- (ROOTS_EXCEEDED), records that reach more than --max-read-total
766
- (READ_BOUND_EXCEEDED); a removal of a run that still
767
- writes its journal, or its preview, and a --resume of it, or of a run
768
- whose removal is under way (RUN_WRITING)
769
- 2 a bad command line, an --exclude that names no field of the source
770
- (FIELD_EXCLUSION_UNMATCHED), an --object no clone writes
771
- (TABLE_NEVER_CLONED), or a summary --remove cannot take a run back from, or
772
- a file beside it that is not what a removal kept there; the plan of a
773
- sample --fit-plan gives or --resume takes up gone, or drawn of another
774
- org or setup (SAMPLE_PLAN_GONE, SAMPLE_PLAN_MISMATCH); a draw whose
775
- --fit-window, --fit-where or --fit-strata the source cannot take
776
- (SAMPLE_DRAW_INVALID); a query that cannot choose the records it
777
- clones (ROOTS_QUERY_REFUSED); the plan of roots --roots-plan gives
778
- gone, or of another org, query or records
779
- (ROOTS_PLAN_GONE, ROOTS_PLAN_MISMATCH), and a run taken up whose journal
780
- names none of the roots it read (ROOTS_PLAN_GONE)
781
- 3 the run was partial and --fail-on-partial was given, or was a clone of
782
- the whole org; the removal left
783
- records of the run in the org: kept, or refused, or found neither in the
784
- org nor in its recycle bin, as the user it ran as sees them; or the sweep
785
- was refused, or did not take all it was asked to (a --sweep-untied
786
- refused included)
787
- 130 Ctrl-C stopped the clone: the summary says what it created by then
788
- 143 a SIGTERM stopped it \u2014 a CI job cancelled or timed out \u2014, 129 a SIGHUP:
789
- as Ctrl-C does, the summary and the journal say what it created
790
- `,hr=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,tt=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function my(r,e){return r.verdict==="unread"?` API requests: about ${r.estimate}; what ${e} has left today could not be read (${r.unread})`:` API requests: about ${r.estimate}, of the ${r.remaining} ${e} has left of its ${r.max} a day`+(r.verdict==="exceeds"?": more than it has left":r.verdict==="near"?": it would leave less than a tenth of them":"")}var wy={"validation-rule":"a validation rule refused it","restricted-picklist":"a restricted picklist refused its value","lookup-filter":"a lookup filter refused the record it names","inactive-owner":"the target holds the owner it names inactive"},yy={inputMode:"--record",recordId:"--record",depth:"--depth",customDepth:"--custom-depth",maxRecordsPerObject:"--max",sourceOrgId:"--source",targetOrgId:"--target",fieldExclusions:"--exclude",ownerMappings:"--owner-map",objectSoqlFilters:"--filter",fieldMappings:"--map",soqlQuery:"--object",sample:"--fit"},Yg=["fieldExclusions","excludedObjects","ownerMappings","objectSoqlFilters","fieldMappings","picklistValueMappings","recordTypeMappings","defaultValues","truncateFields","skippedRows","ignoredGaps"],by=C.strictObject(Ic.pick(Object.fromEntries(Yg.map(r=>[r,!0]))).shape);function Ry(r){let e=r;for(let t="";t!==e;)t=e,e=e.replace(/\([^()]*\)/g," ");return/\bFROM\s+([A-Za-z][A-Za-z0-9_]*)/i.exec(e)?.[1]}function Oy(r){let e=[];function t(n){process.stderr.write(`${n}
791
- `),process.exit(2)}for(let n=0;n<r.length;n++){let o=r[n];if(o!=="--object"&&o!=="--where")continue;let s=r[n+1];if((s===void 0||s.startsWith("--"))&&t(o==="--object"?"--object takes the API name of a table to clone.":"--where takes a SOQL condition, written without WHERE."),n++,o==="--object"){tt.test(s)||t(`Invalid --object value "${s}" (must match SObject API name pattern)`),e.some(a=>a.objectApiName===s)&&t(`--object ${s} is named twice.`),e.push({objectApiName:s});continue}let i=e.at(-1);i?i.where!==void 0?t(`--object ${i.objectApiName} is given two --where: join them with AND.`):s.trim()===""?t(`--where for ${i.objectApiName} is empty.`):i.where=s.trim():t("--where filters the --object before it: name the table first.")}return e.length>0?e:void 0}function Xg(r){let[e]=r;return`SELECT Id FROM ${e.objectApiName}${e.where?` WHERE ${e.where}`:""}`}function ky(r,e){let t=new Set(e.map(n=>n.objectApiName));return r.nodes.map(n=>n.objectApiName).filter(n=>!t.has(n))}function Sy(r,e){let t=new Set(r.nodes.map(n=>n.objectApiName));return e.map(n=>n.objectApiName).filter(n=>!t.has(n))}function Ty(r){if(!xr(r))return;let e=Kt(),t=e?`the table ${r}`:`--object ${r}`;return Pc(r)?`${t}: a file goes with the record it hangs on, never as a table of its own. Leave it out${e?"":", and give --files to copy the files of the records cloned"}.`:`${t}: no clone writes it \u2014 users and their access, metadata, a record's history, feed or sharing rows, and the records the platform keeps for itself are not data a copy carries. Leave it out.`}var Ay=10;function jy(r,e){let t=r.filter(i=>Ao(i)&&!xr(i)),n=r.filter(i=>!t.includes(i)),o=i=>e.env?`the table${i.length===1?"":"s"} ${i.join(", ")}`:`--object ${i.join(", ")}`,s=[];if(n.length>0){let i=n.length===1,d=[...e.depth!=="custom"||e.customDepth<Ay?[e.env?"the resource's depth":"--depth"]:[],...e.truncated?[e.env?"the resource's maxNodes":"--max-nodes"]:[]],c=e.depth==="custom"?String(e.customDepth):e.depth;s.push(`${o(n)}: discovery from ${e.root} did not reach ${i?"it":"them"} (${e.objects} object(s), depth ${c}${e.truncated?", cut at its cap":""}): name first a table it hangs from or points at`+(d.length>0?`, or raise ${d.join(" or ")}.`:`; no lookup joins ${i?"it":"them"} to ${e.root} within the deepest walk, so clone ${i?"it":"them"} in a run of ${i?"its":"their"} own.`))}return t.length>0&&s.push(`${o(t)}: discovery does not walk into the objects of a managed package's namespace, whose configuration hangs off standard records: name ${t.length===1?"it":"one of them"} first, the table discovery starts from, or clone it in a run of its own.`),s.join(`
792
- `)}function $y(r,e,t){return r==="record"?"--template: the template clones from a record it does not name: give --record.":`--template: the template clones from a query, which the command runs as whole tables: give ${e!==void 0?`--object ${e}${t!==void 0?` --where "${t}"`:""}`:"--object <ApiName> --where <condition>"} with --template, its root under the query's condition, and an --object for each other table to clone; or --record to clone one record with its choices.`}function vy(r){return`Missing ${[...r.includes("what to clone")?["what to clone: --record <id> for one record, --object <ApiName> for whole tables, or --depth all for the whole org"]:[],...r.filter(t=>t.startsWith("--")).map(t=>`${t} <alias>`)].join("; ")}. Run with --help for usage.`}var kg=1e3;function Ey(r,e){if(!e.given)return;e.expands||(process.stderr.write(`--max-orphans goes with --expand-orphans: it bounds the parents from outside the run that one copies.
793
- `),process.exit(2));let t=Number(r);return(r===void 0||!/^\d{1,4}$/.test(r)||t<1||t>kg)&&(process.stderr.write(`--max-orphans takes a whole number of parents, 1 to ${kg}, not "${r??""}".
794
- `),process.exit(2)),t}function Iy(r,e){let t=r.tables??[],n=[...new Set([...r.excludedObjects,...ky(e,t)])];return{inputMode:"soql",soqlQuery:Xg(t),depth:r.depth,...r.depth==="custom"?{customDepth:r.customDepth}:{},sourceOrgId:r.source,targetOrgId:r.target,anonymizePII:r.anonymize,skipEmpty:!0,batchSize:"auto",...r.maxRecordsPerObject!==void 0?{maxRecordsPerObject:r.maxRecordsPerObject}:{},...Object.keys(r.fieldExclusions).length>0?{fieldExclusions:r.fieldExclusions}:{},...n.length>0?{excludedObjects:n}:{},...Object.keys(r.ownerMappings).length>0?{ownerMappings:r.ownerMappings}:{},...Object.keys(r.objectSoqlFilters).length>0?{objectSoqlFilters:r.objectSoqlFilters}:{},...Object.keys(r.fieldMappings).length>0?{fieldMappings:r.fieldMappings}:{},...r.keepContactPoints?{keepContactPoints:!0}:{},...r.applyAssignmentRules?{applyAssignmentRules:!0}:{},...r.dryRun?{dryRun:!0}:{},...r.decisions}}function xy(r,e,t,n,o){let s=Pd(t,e,{recordTypeMappings:n,anonymizationRules:r.anonymizationRules,...r.files?{files:r.files}:{},stream:{ceiling:r.readCeiling,...r.pageSize!==void 0?{pageSize:r.pageSize}:{}}},o)??{};return r.upsert?{...s,upsertMode:"auto"}:s}function Vd(r){return r.depth==="all"?{inputMode:"org"}:r.roots?.query?{inputMode:"soql",soqlQuery:r.roots.query.soql,queryScope:"records",maxRoots:r.roots.cap}:r.tables?{inputMode:"soql",soqlQuery:Xg(r.tables)}:{inputMode:"record",recordId:r.record}}function Py(r){return r.depth==="all"?"the whole org":r.roots?.query?`query=${r.roots.query.soql}`:r.roots?.ids?`records=${r.roots.ids.join(", ")}`:r.tables?`tables=${r.tables.map(e=>e.where?`${e.objectApiName} (${e.where})`:e.objectApiName).join(", ")}`:`record=${r.record??""}`}var Ld=12;function Fy(r){let{roots:e,result:t,...n}=r;return{...n.record!==void 0?{record:n.record}:{},...n.objects?{objects:n.objects}:{},...n.wholeOrg?{wholeOrg:!0}:{},...e?{roots:{...e,...t.roots!==void 0?{count:t.roots.read}:{}}}:{}}}function Ny(r){if(r.roots){let{objectApiName:n,from:o,count:s}=r.roots;return s!==void 0?`${s} ${n} record${s===1?"":"s"} (${o==="query"?"query":"named"})`:`the ${n} records ${o==="query"?"a query chose":"named"}`}if(r.record)return r.record;let e=(r.objects??[]).map(n=>n.objectApiName),t=e.length<=Ld?e.join(", "):`${e.slice(0,Ld).join(", ")} and ${e.length-Ld} more object(s)`;return r.wholeOrg?e.length>0?`the whole org (${t})`:"the whole org":e.length>0?t:"the run"}function Cy(r){return{inputMode:"org",depth:"all",sourceOrgId:r.source,targetOrgId:r.target,anonymizePII:r.anonymize,skipEmpty:!0,batchSize:"auto",...Object.keys(r.fieldExclusions).length>0?{fieldExclusions:r.fieldExclusions}:{},...r.excludedObjects.length>0?{excludedObjects:r.excludedObjects}:{},...Object.keys(r.ownerMappings).length>0?{ownerMappings:r.ownerMappings}:{},...Object.keys(r.objectSoqlFilters).length>0?{objectSoqlFilters:r.objectSoqlFilters}:{},...Object.keys(r.fieldMappings).length>0?{fieldMappings:r.fieldMappings}:{},...r.keepContactPoints?{keepContactPoints:!0}:{},...r.applyAssignmentRules?{applyAssignmentRules:!0}:{},...r.dryRun?{dryRun:!0}:{},...r.decisions,...r.sample?{sample:Zg(r.sample)}:{}}}function Zg(r){let e={...r.options};return delete e.plan,e}function My(r,e,t,n,o,s){return Pd(t,e,{recordTypeMappings:n,anonymizationRules:r.anonymizationRules,...r.files?{files:r.files}:{},stream:{wholeReadBound:r.readCeiling,...r.pageSize!==void 0?{pageSize:r.pageSize}:{},...s?{sample:s}:{}}},o)??{}}function By(r,e){return e.size===0?r:{...r,nodes:r.nodes.map(t=>e.has(t.objectApiName)?{...t,included:!1,leftOutByUser:!0}:t)}}var Sg=1e6;function Ly(r,e){if(e.length>Sg)return{refusal:[`${r}: the file is larger than ${Sg} bytes`]};let t;try{t=JSON.parse(e.replace(/^\uFEFF/,""))}catch{return{refusal:[`${r}: the file is not JSON`]}}let n=s=>s.issues.map(i=>{let a=i.path.map(String).join(".");return`${r}${a?` (${a})`:""}: ${i.message}`});if(r==="--template"){let s=xc.safeParse(t);return s.success?{file:{kind:"template",template:s.data}}:{refusal:n(s.error)}}let o=by.safeParse(t);return o.success?{file:{kind:"config",config:o.data}}:{refusal:[...n(o.error),`${r} takes ${Yg.join(", ")}; the other choices have flags of their own.`]}}var Qs=["--fit-within","--fit-seed","--fit-draw","--fit-window","--fit-where","--fit-strata","--fit-parents","--fit-children","--fit-whole","--fit-floor","--fit-plan"],Wy={switches:["--list-objects","--anonymize","--keep-contact-points","--dry-run","--rehearse","--accept-automation","--accept-emails","--mute-automation","--upsert","--expand-orphans","--apply-assignment-rules","--skip-preflight","--json","--fail-on-partial","--write-uncertain","--files","--files-as-is","--no-anonymize","--yes",...Fd.switches,"--include-changed"],values:["--record","--source","--target","--object","--where","--depth","--custom-depth","--max","--max-nodes","--max-total","--max-records-per-object","--max-orphans","--summary","--resume","--exclude","--exclude-object","--owner-map","--filter","--map","--config","--template","--remap-csv","--max-file-size","--audit","--fit",...Qs,"--query","--max-roots","--roots-plan","--max-read-total",...Fd.values]},Dy=[["--record","it starts from no record"],["--object","it starts from no table: --exclude-object leaves one out"],["--where","it starts from no table: --filter narrows an object, and --fit-where, with --fit share, draws the roots of a sample among the records that match"],["--template","a template holds the choices of a walk from its record or query: give them with --config"],["--custom-depth","it walks no depth"],["--max-nodes","it takes every object it can, and is refused past 1950 rather than cut"],["--max","it copies every row of what it takes: --filter narrows an object, and --fit share copies a sample of the org that fits the target, none of its records without those they name"],["--expand-orphans","every parent it reaches is in the org it copies"],["--max-orphans","every parent it reaches is in the org it copies"],["--rehearse","a rehearsal holds every row it prepares: --dry-run counts what a real run would write and says what would refuse it, writing nothing"],["--upsert",`its writes go as Bulk API jobs that insert. To copy the org again without its records twice: --resume <journal> takes up a run that stopped, writing nothing it wrote; --remove <summary> takes back a run that ended before the copy is made again; or ${qt("empty")} --target <alias> --objects <A,B> --dry-run says what emptying the target's objects would delete, every record of them`]];function _y(r,e){if(!e){let n=["--yes","--no-anonymize"].filter(o=>r(o));if(n.length===0)return;process.stderr.write(`${n.join(" and ")} ${n.length===1?"goes":"go"} with --depth all: no other clone asks before it writes, and none anonymizes unless --anonymize is given.
795
- `),process.exit(2)}let t=Dy.filter(([n])=>r(n));if(r("--anonymize")&&r("--no-anonymize")&&t.push(["--anonymize","it is given --no-anonymize too: give one of them"]),t.length!==0){for(let[n,o]of t)process.stderr.write(`--depth all clones the whole org, and does not go with ${n}: ${o}.
796
- `);process.exit(2)}}var qy=["--fit-whole","--fit-where","--fit-strata"],Uy=Qs.filter(r=>!qy.includes(r)),Gy={created:"CreatedDate",modified:"LastModifiedDate"},zy=`--fit-window takes created or modified, a colon, then <from>..<to>, each a date, as 2025-06-30, or an instant in UTC, as 2025-06-30T12:00:00Z, either left out but not both; or <n>d, the last n days, 1 to ${po}`;function Hy(r){let e=r.indexOf(":"),t=e>0?Gy[r.slice(0,e)]:void 0,n=r.slice(e+1),o=l=>({refusal:`${zy}, not "${r}"${l}.`});if(t===void 0)return o("");let s=/^(\d{1,6})d$/.exec(n);if(s){let l=Number(s[1]);return l<1||l>po?o(`: ${l} days is out of 1 to ${po}`):{field:t,lastDays:l}}let i=n.indexOf("..");if(i<0)return o("");let a=n.slice(0,i),d=n.slice(i+2);if(a===""&&d==="")return o(": give a start, an end or both");let c=a===""?void 0:hi(a,!1),u=d===""?void 0:hi(d,!0);return a!==""&&c===void 0?o(`: "${a}" is no such date`):d!==""&&u===void 0?o(`: "${d}" is no such date`):c!==void 0&&u!==void 0&&c>=u?o(`: it starts at ${c} and ends before ${u}, so no root is made in it; the end is left out of the window, a date there taking the whole day`):{field:t,...c!==void 0?{from:c}:{},...u!==void 0?{to:u}:{}}}function Ky(r,e){let t={},n=new Set;for(let d of r){let c=d.indexOf("="),u=c>0?d.slice(0,c):"",l=c>0?d.slice(c+1):"";if(!tt.test(u)||l.trim()==="")return{refusal:`Invalid --fit-where value "${d}": it takes <Object>=<WHERE>, the condition the roots of Object are drawn among, as Account=BillingCountry = 'France'.`};if(!Sc.safeParse(l).success)return{refusal:l.length>512?`--fit-where condition for "${u}" exceeds 512 chars`:`--fit-where condition for "${u}" contains forbidden tokens (--, /*, */, trailing ;)`};if(n.has(u.toLowerCase()))return{refusal:`--fit-where names ${u} twice: give one condition of its roots, the two joined with AND or OR.`};n.add(u.toLowerCase()),t[u]=l}let o=Object.keys(t);if(o.length>pi)return{refusal:`--fit-where filters the roots of ${pi} objects at most, not ${o.length}.`};let s=d=>{let c=new Set(d.map(u=>u.toLowerCase()));return o.filter(u=>c.has(u.toLowerCase()))},i=s(e.whole);if(i.length>0)return{refusal:`--fit-where filters the roots of ${i.join(", ")}, which --fit-whole copies whole: every record of it comes, whatever the condition. Leave it out of --fit-whole, or narrow the object itself with --filter, which leaves records out of the copy.`};let a=s(e.excludedObjects);return a.length>0?{refusal:`--fit-where and --exclude-object both name ${a.join(", ")}: the run would leave out an object whose roots it draws. Give each to one of them.`}:{where:t}}function Vy(r){let e=[];for(let n of r){if(!vc.test(n))return{refusal:`Invalid --fit-strata value "${n}": it takes a field, as RecordTypeId, of every object drawn that has it, or an object and its field, as Account.RecordTypeId.`};if(e.some(o=>o.toLowerCase()===n.toLowerCase()))return{refusal:`--fit-strata ${n} is given twice: give it once.`};e.push(n)}if(e.length>fi)return{refusal:`--fit-strata stratifies the roots by ${fi} fields at most, not ${e.length}.`};let t=Ec.safeParse(e);return t.success?{strata:e}:{refusal:`--fit-strata ${t.error.issues.map(n=>n.message).join("; ")}: give each object one field, its own (Object.Field) or the one every object takes (Field).`}}var Tg=1e4,Ag=1e6,jg=1e6,Jy="sample.json";function Qy(r,e){let t=w=>(process.stderr.write(`${w}
797
- `),process.exit(2)),n=w=>r.flatMap((A,S)=>A===w&&S+1<r.length?[r[S+1]]:[]),o=w=>r.includes(w),s=Qs.filter(w=>o(w));if(!o("--fit"))return s.length===0?void 0:t(`${s.join(", ")} ${s.length===1?"goes":"go"} with --depth all --fit share: ${s.length===1?"it sets":"they set"} how a sample of the whole org is drawn, and the line asks for none.`);let i=n("--fit");if(i.length!==1||i[0]!=="share")return t(`--fit takes share, once, not "${i.join(" ")}".`);if(!e.wholeOrg)return t("--fit share goes with --depth all: it copies a sample of the whole org that fits the target. A clone of a record or of tables reads what it reaches: --max caps each object.");if(o("--files"))return t("--fit share copies no files: the sample goes without the files of its records, and --files does not go with it. Leave out --files.");if(o("--list-objects"))return t("--list-objects lists the objects of the graph and draws no sample: leave out --fit share.");if(o("--fit-plan")&&o("--resume"))return t("--fit-plan does not go with --resume: a run taken up writes the plan its journal names, the one it began with.");for(let w of Uy)n(w).length>1&&t(`${w} is given twice: give it once.`);let a=w=>n(w)[0],d={maxTotal:e.maxTotal},c=a("--fit-within");if(c!==void 0){let w=Number(c);(!/^\d+(?:\.\d+)?$/.test(c)||w<=0||w>jg)&&t(`--fit-within takes a number of MB above 0, up to ${jg}, not "${c}".`),d.withinMB=w}let u=a("--fit-seed");u!==void 0&&(/^\d{1,15}$/.test(u)||t(`--fit-seed takes a whole number, 0 or more, not "${u}".`),d.seed=Number(u));let l=a("--fit-draw");l!==void 0&&(l!=="uniform"&&l!=="recent"&&l!=="oldest"&&t(`--fit-draw takes uniform, the roots spread over each object by the seed, recent, the newest by their creation date, or oldest, the oldest by it, not "${l}".`),d.draw=l);let f=a("--fit-window");if(f!==void 0){let w=Hy(f);"refusal"in w?t(w.refusal):d.window=w}let p=a("--fit-parents");p!==void 0&&(p!=="all"&&p!=="required"&&t(`--fit-parents takes all, the records an optional lookup names copied without their children, or required, such a lookup left empty, not "${p}".`),d.parents=p);let g=a("--fit-children");if(g!==void 0){let w=Number(g);g==="all"?d.children="all":/^\d{1,7}$/.test(g)&&w>=1&&w<=Ag?d.children=w:t(`--fit-children takes a whole number of children from 1 to ${Ag}, or all, not "${g}".`)}let h=[];for(let w of n("--fit-whole"))tt.test(w)||t(`Invalid --fit-whole value "${w}" (must match SObject API name pattern)`),h.includes(w)||h.push(w);let m=h.filter(w=>e.excludedObjects.includes(w));m.length>0&&t(`--fit-whole and --exclude-object both name ${m.join(", ")}: the sample would copy whole an object the run leaves out. Give each to one of them.`),h.length>0&&(d.whole=h);let R=Ky(n("--fit-where"),{whole:h,excludedObjects:e.excludedObjects});"refusal"in R?t(R.refusal):Object.keys(R.where).length>0&&(d.rootWhere=R.where);let b=Vy(n("--fit-strata"));"refusal"in b?t(b.refusal):b.strata.length>0&&(d.strata=b.strata);let k=a("--fit-floor");if(k!==void 0){let w=Number(k);(!/^\d{1,5}$/.test(k)||w>Tg)&&t(`--fit-floor takes a whole number of records from 0 to ${Tg}, not "${k}".`),d.floor=w}let O=a("--fit-plan");if(O!==void 0){let w=Wt(O);d.plan=rc(w)===Jy?hy(w):w}return{options:d,maxTotalGiven:e.maxTotalGiven}}var Yy=["--query","--max-roots","--roots-plan","--max-read-total"],Xy=["--record","--object","--where","--fit",...Qs];function Zy(r){let e=b=>r.includes(b),t=b=>r.flatMap((k,O)=>k===b?[r[O+1]]:[]),n=b=>(process.stderr.write(`${b}
798
- `),process.exit(2)),o=t("--query"),s=t("--record");if(o.length===0&&s.length<2){let b=Yy.filter(k=>e(k));b.length>0&&n(`${b.join(", ")} ${b.length===1?"goes":"go"} with --query, or with --record given more than once: a clone of one record, of tables or of the whole org takes no roots of its own.`);return}let i=(b,k,O)=>{let w=Number(k);return k===void 0||k.startsWith("--")||!Number.isInteger(w)||w<1||w>O?n(`${b} takes a whole number, 1 to ${O.toLocaleString("en-US")}.`):w},a=b=>{let k=t(b);return k.length>1&&n(`${b} is given ${k.length} times: give it once.`),k[0]},d=a("--max-roots"),c=d===void 0&&!e("--max-roots")?kr:i("--max-roots",d,bn),u=a("--max-read-total"),l=u===void 0&&!e("--max-read-total")?void 0:i("--max-read-total",u,Number.MAX_SAFE_INTEGER),f=a("--roots-plan");if(e("--roots-plan")){(f===void 0||f.startsWith("--"))&&n("--roots-plan takes the file a dry run keeps the records it chooses in.");let k=[["--resume","a run taken up writes the roots its journal names"],["--list-objects","it reads no record"],["--rehearse","a rehearsal keeps nothing of what it reads"]].filter(([O])=>e(O));k.length>0&&n(`--roots-plan does not go with ${k.map(([O,w])=>`${O}: ${w}`).join("; ")}.`)}let p=f!==void 0?Wt(f):void 0,g={cap:c,...p!==void 0?{plan:p}:{},...l?{readTotal:l}:{}};if(o.length>0){let b=[...Xy.filter(A=>e(A)),...t("--depth").includes("all")?["--depth all"]:[]];b.length>0&&n(`--query clones the records a query chooses, each with what the clone of that record copies: it does not go with ${b.join(", ")} (--record names records one by one, --object reads whole tables, --depth all copies the whole org or a sample of it).`);let k=a("--query");if(k===void 0||k.trim()===""||k.startsWith("--"))return n("--query takes a SOQL query, as SELECT Id FROM Account WHERE \u2026");let O=Tc(k),w=kc(k);return O!==void 0||!w?n(kt({code:"ROOTS_QUERY_REFUSED",message:`${Ac(O??{kind:"noObject"})}. Nothing was read or written.`})):(w.limit!==null&&w.limit>c&&n(`--query: its LIMIT ${w.limit} is past the ${c} records a run clones: give --max-roots ${w.limit} (up to ${bn.toLocaleString("en-US")}), or a lower LIMIT.`),{query:{soql:k.trim(),objectApiName:w.objectApiName,roots:{...w.where!==null?{where:w.where}:{},...w.orderBy!==null?{orderBy:w.orderBy}:{},...w.limit!==null?{limit:w.limit}:{}}},...g})}let h=[],m=new Set;for(let b of s){(b===void 0||!hr.test(b))&&n(`--record takes the 15- or 18-character id of a record: "${b??""}" is none.`);let k=(b??"").slice(0,15);m.has(k)||(m.add(k),h.push(b??""))}let R=[...new Set(h.map(b=>b.slice(0,3)))];return R.length>1&&n(`--record names records of ${R.length} objects (${R.map(b=>`${b}\u2026`).join(", ")}): a clone from records takes the records of one object; clone each object\u2019s apart, or choose them with --query.`),h.length>c&&n(`--record names ${h.length} records, past the ${c} a run clones: give --max-roots ${Math.min(h.length,bn)} (up to ${bn.toLocaleString("en-US")}), or name fewer.`),{ids:h,...g}}function eb(r,e=process.env){let t=r.slice(2);(t.includes("-h")||t.includes("--help"))&&(process.stdout.write(oc),process.exit(0)),Gc(t,Wy);let n=(M,q)=>{let G=t.indexOf(M);return G>=0&&G+1<t.length?t[G+1]:q},o=M=>t.includes(M);o("--config")&&o("--template")&&(process.stderr.write(`--config and --template: give one of them.
799
- `),process.exit(2));let s=o("--template")?"--template":o("--config")?"--config":void 0,i=s?n(s):void 0,a;if(s){(!i||i.startsWith("--"))&&(process.stderr.write(`${s} takes the path of a JSON file.
800
- `),process.exit(2));let M;try{M=pn(i,"utf8")}catch(G){process.stderr.write(`${s}: cannot read ${i}: ${V(G)}
801
- `),process.exit(2)}let q=Ly(s,M);if("refusal"in q){for(let G of q.refusal)process.stderr.write(`${G}
802
- `);process.exit(2)}a=q.file}let d=a?.kind==="template"?a.template:void 0,c=Zy(t),u=n("--depth")==="all";_y(o,u);let l=a?.kind==="template"?{...a.template.config}:a?.config??{},f=d?.config.soqlQuery!==void 0?Ry(d.config.soqlQuery):void 0,p=f!==void 0?l.objectSoqlFilters?.[f]:void 0;if(f!==void 0&&l.objectSoqlFilters?.[f]!==void 0){let M={...l.objectSoqlFilters};delete M[f],l.objectSoqlFilters=M}let g=Oy(t);if(g){let M=["--record","--expand-orphans","--max-orphans","--rehearse"].filter(q=>o(q));if(M.length>0){let q=M.includes("--rehearse")?" --dry-run reads the tables and counts what a real run would write, and says what would refuse it, writing nothing.":"";process.stderr.write(`--object clones whole tables, as the panel runs a query: it does not go with ${M.join(", ")}, which ${M.length===1?"goes":"go"} with a clone of one record (--record).${q}
803
- `),process.exit(2)}d?.config.expandOrphanParents===!0&&(process.stderr.write(`--template: the template brings orphan parents (expandOrphanParents), which go with a clone of one record (--record), not with --object.
804
- `),process.exit(2))}let h=d?.config.inputMode==="record"?d.config.recordId:void 0;d&&!g&&!c?.query&&!o("--record")&&!h&&(process.stderr.write(`${$y(d.config.inputMode,f,p)}
805
- `),process.exit(2));let m=g||u||c?.query?void 0:n("--record")??h,R=n("--source"),b=n("--target"),k=[...!m&&!g&&!u&&!c?["what to clone"]:[],...R?[]:["--source"],...b?[]:["--target"]];(k.length>0||!R||!b)&&(process.stderr.write(`${vy(k)}
806
- `),process.exit(2)),o("--include-changed")&&(process.stderr.write(`--include-changed goes with --remove.
807
- `),process.exit(2));let O=["--dry-run","--upsert","--files","--remap-csv","--list-objects"].filter(M=>o(M));o("--rehearse")&&O.length>0&&(process.stderr.write(`--rehearse does not go with ${O.join(", ")}.
808
- `),process.exit(2));let w=lb(t),A=hg(t,[{flag:"--rehearse",why:"a rehearsal keeps nothing it creates in the target, and there is nothing to take back."},{flag:"--list-objects",why:"it lists the objects of the graph, and writes nothing."},{flag:"--resume",why:"a run taken up is the run its first part began, and a checkpoint taken now would hold what that part wrote: rewind to the one it took, if it took one."}]),S=n("--depth")??d?.config.depth??"custom",v=n("--custom-depth")??(d?.config.customDepth!==void 0?String(d.config.customDepth):"5"),j=n("--max")??(d?.config.maxRecordsPerObject!==void 0?String(d.config.maxRecordsPerObject):void 0),F=n("--max-nodes")??(d?.config.maxNodes!==void 0?String(d.config.maxNodes):void 0),B=n("--max-total"),E=n("--max-records-per-object"),_=M=>{let q=[];for(let G=0;G<t.length;G++)t[G]===M&&G+1<t.length&&q.push(t[G+1]);return q},ee=Object.fromEntries(Object.entries(l.fieldExclusions??{}).map(([M,q])=>[M,[...q]]));for(let M of _("--exclude")){let q=M.indexOf(".");(q<=0||q===M.length-1)&&(process.stderr.write(`Invalid --exclude value "${M}" (expected Object.field)
809
- `),process.exit(2));let G=M.slice(0,q),Te=M.slice(q+1);(!tt.test(G)||!tt.test(Te))&&(process.stderr.write(`Invalid --exclude name in "${M}" (must match SObject API name pattern)
810
- `),process.exit(2));let ie=ee[G]??=[];ie.includes(Te)||ie.push(Te)}let X=[...l.excludedObjects??[]];for(let M of _("--exclude-object"))tt.test(M)||(process.stderr.write(`Invalid --exclude-object value "${M}" (must match SObject API name pattern)
811
- `),process.exit(2)),X.includes(M)||X.push(M);let z={...l.ownerMappings};for(let M of _("--owner-map")){let q=M.indexOf("=");(q<=0||q===M.length-1)&&(process.stderr.write(`Invalid --owner-map value "${M}" (expected sourceId=targetId)
812
- `),process.exit(2));let G=M.slice(0,q),Te=M.slice(q+1);(!hr.test(G)||!hr.test(Te))&&(process.stderr.write(`Invalid --owner-map IDs in "${M}" (must be 15 or 18 char Salesforce IDs)
813
- `),process.exit(2)),z[G]=Te}let J={...l.objectSoqlFilters};for(let M of _("--filter")){let q=M.indexOf("=");(q<=0||q===M.length-1)&&(process.stderr.write(`Invalid --filter value "${M}" (expected Object=where-clause)
814
- `),process.exit(2));let G=M.slice(0,q),Te=M.slice(q+1);Te.length>512&&(process.stderr.write(`--filter where-clause for "${G}" exceeds 512 chars
815
- `),process.exit(2)),/--|\/\*|\*\/|;\s*$/.test(Te)&&(process.stderr.write(`--filter where-clause for "${G}" contains forbidden tokens (--, /*, */, trailing ;)
816
- `),process.exit(2)),J[G]=Te}let Me=new Set(_("--filter").map(M=>M.slice(0,M.indexOf("="))));for(let M of g??[])M.where!==void 0&&(Me.has(M.objectApiName)&&(process.stderr.write(`--where and --filter both filter ${M.objectApiName}: give one of them.
817
- `),process.exit(2)),M.where.length>512&&(process.stderr.write(`--where for "${M.objectApiName}" exceeds 512 chars
818
- `),process.exit(2)),/--|\/\*|\*\/|;\s*$/.test(M.where)&&(process.stderr.write(`--where for "${M.objectApiName}" contains forbidden tokens (--, /*, */, trailing ;)
819
- `),process.exit(2)),J[M.objectApiName]=M.where);let ke=Object.fromEntries(Object.entries(l.fieldMappings??{}).map(([M,q])=>[M,{...q}]));for(let M of _("--map")){let q=M.indexOf("."),G=M.indexOf("=");(q<=0||G<=q+1||G===M.length-1)&&(process.stderr.write(`Invalid --map value "${M}" (expected Object.sourceField=targetField)
820
- `),process.exit(2));let Te=M.slice(0,q),ie=M.slice(q+1,G),ne=M.slice(G+1);(!tt.test(ie)||!tt.test(ne))&&(process.stderr.write(`Invalid --map field name in "${M}" (must match SObject API name pattern)
821
- `),process.exit(2)),(ke[Te]??={})[ie]=ne}let ue=v?Number(v):5,H=j?Number(j):void 0,Q=F?Number(F):void 0;Q!==void 0&&(!Number.isInteger(Q)||Q<1)&&(process.stderr.write(`--max-nodes takes a whole number of objects, 1 or more.
822
- `),process.exit(2));let pe=Ey(n("--max-orphans"),{given:o("--max-orphans"),expands:o("--expand-orphans")||d?.config.expandOrphanParents===!0}),we=B===void 0?er:Number(B);(!Number.isInteger(we)||we<1)&&(process.stderr.write(`--max-total takes a whole number of records, 1 or more.
823
- `),process.exit(2));let Ee=E===void 0?fo:Number(E);(!Number.isInteger(Ee)||Ee<1||Ee>li)&&(process.stderr.write(`--max-records-per-object takes a whole number of records, 1 to ${li}.
824
- `),process.exit(2));let ae=e.SANDFORGE_FORGE_PAGE_SIZE,D=ae===void 0||ae===""?void 0:Number(ae);D!==void 0&&(!Number.isInteger(D)||D<1)&&(process.stderr.write(`SANDFORGE_FORGE_PAGE_SIZE takes a whole number of rows, 1 or more.
825
- `),process.exit(2));let L=o("--anonymize")||d?.config.anonymizePII===!0,Re=o("--keep-contact-points")||d?.config.keepContactPoints===!0,Ne=pb(t,L),Ie=Jo(l),ge=Qy(t,{wholeOrg:u,maxTotal:we,maxTotalGiven:B!==void 0,excludedObjects:X}),te=(u?gi:gi.safeExtend({depth:$c})).safeParse({...Vd({record:m,tables:g,depth:u?"all":void 0,roots:c}),depth:S,customDepth:S==="custom"?ue:void 0,sourceOrgId:R,targetOrgId:b,anonymizePII:L,keepContactPoints:Re,skipEmpty:!0,batchSize:"auto",maxRecordsPerObject:H,fieldExclusions:ee,excludedObjects:X,ownerMappings:z,objectSoqlFilters:J,fieldMappings:ke,...Ie,...ge?{sample:ge.options}:{}});if(!te.success){for(let M of te.error.issues){let[q,...G]=M.path.map(String),Te=yy[q??""]??(s&&q?`${s} ${q}`:q??"arguments"),ie=G.length>0?` (${G.join(".")})`:"";process.stderr.write(`Invalid ${Te}${ie}: ${M.message}
826
- `)}process.exit(2)}return{record:m,...c?{roots:c}:{},tables:g,source:R,target:b,depth:te.data.depth,customDepth:ue,maxNodes:Q,maxRecordsPerObject:H,anonymize:L,anonymizeGiven:o("--anonymize")||o("--no-anonymize"),yes:o("--yes"),keepContactPoints:te.data.keepContactPoints===!0,dryRun:o("--dry-run"),listObjects:o("--list-objects"),upsert:o("--upsert"),expandOrphans:o("--expand-orphans")||d?.config.expandOrphanParents===!0,...pe!==void 0?{maxOrphans:pe}:{},applyAssignmentRules:o("--apply-assignment-rules")||d?.config.applyAssignmentRules===!0,skipPreflight:o("--skip-preflight"),json:o("--json"),failOnPartial:o("--fail-on-partial"),summary:w,fieldExclusions:ee,excludedObjects:X,ownerMappings:z,objectSoqlFilters:J,fieldMappings:ke,remapCsv:fb(t),files:Ne,acceptAutomation:o("--accept-automation"),acceptEmails:o("--accept-emails"),muteAutomation:o("--mute-automation"),...A!==void 0?{checkpointFirst:A}:{},maxTotal:we,readCeiling:Ee,...D!==void 0?{pageSize:D}:{},rehearse:o("--rehearse"),decisions:Ie,anonymizationRules:{...d?.anonymization?.rules},anonymizeFields:d?.anonymization?.fields,choicesFrom:s&&i?{flag:s,path:i}:void 0,audit:sc(t),resume:ob(t),writeUncertain:tb(t),...ge?{sample:ge}:{}}}function tb(r){return r.includes("--write-uncertain")?(r.includes("--resume")||(process.stderr.write(`--write-uncertain goes with --resume: it writes the rows of a call under way when the run stopped that the target may already hold.
827
- `),process.exit(2)),!0):!1}function nb(r,e){let t=ks(r),n=u=>(u??[]).reduce((l,f)=>l+f.rows,0),o=r.uncertain.map(({objectApiName:u,rows:l})=>`${l} ${u}`).join(", "),s=r.underway??[],i=n(r.untold),a=n(r.ofEndedJobs)-i,d=t-n(s)-i-a,c=[`${t} row(s) may already be in ${e} (${o}), sent by insert calls the run had under way when it stopped, their answer never kept.`];for(let u of s){let l=`${u.rows} of them went in Bulk API job ${u.jobId} (${u.objectApiName}), which ${e} holds ${u.state??"not ended"}`+(u.processed!==void 0?`, ${u.processed} row(s) processed`:"");c.push(u.state==="Open"?`${l}: the run stopped before it closed it, and closed, it would still write them.`:`${l}: ${e} writes it to its end whatever became of the run.`)}i>0&&c.push(`${i} of them went in a Bulk API job that wrote records the journal cannot tell apart, several rows under one fingerprint: none of those records is linked to a row, and each is kept as written by the run, for --remove to take back.`),a>0&&c.push(`${a} of them went in a Bulk API job that wrote records whose values are not what the run sent: none is taken for one of them, and each is kept as written by the run.`),d>0&&c.push(`${d} of them went in calls whose records ${e} holds and the resume cannot tell from them, or could not read.`),c.push("Nothing was written.");for(let u of s)c.push(u.state==="Open"?`Run the same --resume again ${u.openUntil!==void 0?`from ${u.openUntil}`+(u.graceLeftMs!==void 0?`, in about ${Math.max(1,Math.ceil(u.graceLeftMs/6e4))} minute(s)`:""):"an hour after the job was opened"}: it aborts job ${u.jobId} if it is open still, then writes its rows.`:`Run the same --resume again once job ${u.jobId} has ended: it reads what the job wrote, row by row.`);return i+a+d>0&&c.push(`Look at the records of those objects the run's user created in ${e} as the run stopped; run the same --resume with --write-uncertain to write those rows all the same (one already there is then there twice), or --remove the run.`),c.join(" ")}function rb(r,e=Date.now()){let t=r.underway??[];if(t.length===0)return;let n=s=>(s??[]).reduce((i,a)=>i+a.rows,0);if(ks(r)>n(t))return;let o=e;for(let s of t){let i;if(s.state==="Open"){let a=s.openUntil!==void 0?Date.parse(s.openUntil):Number.NaN;if(Number.isFinite(a))i=a;else if(s.graceLeftMs!==void 0)i=e+s.graceLeftMs;else return}else{let a=Math.max(0,s.rows-(s.processed??0));i=e+Math.ceil(Uu(a,"save")*1e3)}o=Math.max(o,i)}return new Date(o).toISOString()}function ob(r){let e=r.indexOf("--resume");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--resume takes the journal of the run to take up, or its run id.
828
- `),process.exit(2));let n=["--dry-run","--rehearse","--list-objects"].filter(o=>r.includes(o));return n.length>0&&(process.stderr.write(`--resume takes a run up and writes: it does not go with ${n.join(", ")}.
829
- `),process.exit(2)),t}function $g(r,e){return r.endsWith(".ndjson")||/[\\/]/.test(r)?Wt(r):e.pathOf(r)}function vg(r,e,t={}){return{...r.sample?{sample:xp(r.sample.options,t.planSha256),...t.sourceOrgId?{sourceOrgId:t.sourceOrgId.slice(0,15)}:{}}:{},source:r.source,targetOrgId:e.slice(0,15),record:r.record,...r.tables?{tables:r.tables}:{},...r.roots?.query?{query:{objectApiName:r.roots.query.objectApiName,...r.roots.query.roots}}:{},...r.roots?.ids?{records:[...r.roots.ids].sort()}:{},...r.roots?{maxRoots:r.roots.cap}:{},depth:r.depth,customDepth:r.depth==="custom"?r.customDepth:null,maxNodes:r.maxNodes??null,maxRecordsPerObject:r.maxRecordsPerObject??null,anonymize:r.anonymize,keepContactPoints:r.keepContactPoints,upsert:r.upsert,expandOrphans:r.expandOrphans,...r.maxOrphans!==void 0?{maxOrphans:r.maxOrphans}:{},applyAssignmentRules:r.applyAssignmentRules,fieldExclusions:r.fieldExclusions,excludedObjects:r.excludedObjects,ownerMappings:r.ownerMappings,objectSoqlFilters:r.objectSoqlFilters,fieldMappings:r.fieldMappings,decisions:r.decisions??null,anonymizationRules:r.anonymizationRules,anonymizeFields:r.anonymizeFields??null,files:r.files??null,readCeiling:r.depth==="all"?null:r.readCeiling}}async function sb(r,e,t){let n=await r.headAt(e);if(!n)return{code:"RESUME_UNAVAILABLE",message:`--resume ${e}: there is no journal of a run there. Every run that writes says its journal as it starts (journal: \u2026), under SANDFORGE_JOURNAL_DIR when it is set: give that file, or its run id. Nothing was written.`};if(!n.resume)return{code:"RESUME_UNAVAILABLE",message:`--resume ${e}: the journal does not say how its run was set up, and the run cannot be taken up: --remove ${e} takes back what it wrote, then run the clone again. Nothing was written.`};if((await r.lastEndAt(e))?.status==="success")return{code:"RESUME_UNAVAILABLE",message:`--resume ${e}: the run ended, and there is nothing of it to take up.`};if(n.targetOrgId.slice(0,15)!==t.targetOrgId.slice(0,15))return{code:"RESUME_TARGET_CHANGED",message:`${t.target} is not the org the run to take up wrote to (${n.targetOrgId}): it is taken up there only. Nothing was written.`};let s=t.setup,i=cb(r,e),a=t.sample?.asked===!0;if(i===void 0&&a)return{code:us,message:`--resume ${e}: the run to take up copied every record of the whole org, not a sample: take it up without --fit share and its --fit-* flags. Nothing was written.`};if(i!==void 0&&!a)return{code:us,message:`--resume ${e}: the run to take up copied a sample of the whole org: take it up with --fit share and the --fit-* flags it ran with. Nothing was written.`};if(i!==void 0&&t.sample){let d;try{d=await sr.open(i.dir,{sha256:i.sha256})}catch(c){let u=ls(c,"resume");if(!u)throw c;return{code:u.code,message:u.message.replace(/ Nothing was written\.$/,` It was in ${i.dir}. Nothing was written.`)}}d.manifest.drawnBy==="dryRun"&&(s=t.sample.setupWith(d.sha256))}if(!Pp(n.resume.fingerprint,t.graph,s))return{code:"RESUME_CHANGED",message:`The clone is set up otherwise than the run to take up: ${db(n.resume,t)}. Give the same record or tables, orgs, depth, choices and flags it ran with; or take back what it wrote with --remove ${e}, and run the clone again as it is now. Nothing was written.`}}var ib={sourceOrgId:"--source",depth:"--depth",customDepth:"--custom-depth",soqlQuery:"the first --object and its --where",anonymizePII:"--anonymize",keepContactPoints:"--keep-contact-points",maxRecordsPerObject:"--max",objectSoqlFilters:"--filter or --where",excludedObjects:"--exclude-object",fieldExclusions:"--exclude",fieldMappings:"--map",ownerMappings:"--owner-map",applyAssignmentRules:"--apply-assignment-rules",sample:"--fit and its --fit-* flags",picklistValueMappings:"the decisions of --config or --template",recordTypeMappings:"the decisions of --config or --template",defaultValues:"the decisions of --config or --template",truncateFields:"the decisions of --config or --template",skippedRows:"the decisions of --config or --template",ignoredGaps:"the decisions of --config or --template"},ab=new Set(["inputMode","targetOrgId","skipEmpty","batchSize","dryRun"]);function db(r,e){let t=[];r.recordId!==void 0&&e.record!==void 0&&r.recordId.slice(0,15)!==e.record.slice(0,15)&&t.push(`--record (${r.recordId} then, ${e.record} now)`);let n=r.startedWith;if(n&&e.config){let o={...n.config},s={...e.config},i=[...new Set([...Object.keys(o),...Object.keys(s)])].filter(p=>!ab.has(p)&&p!=="recordId"),a=new Set;for(let p of i)JSON.stringify(o[p]??null)!==JSON.stringify(s[p]??null)&&a.add(ib[p]??p);a.size>0&&t.push(`${[...a].join(", ")} differ`);let d=p=>new Set(p.nodes.filter(g=>g.included||$r(g)).map(g=>g.objectApiName)),c=d(n.graph),u=d(e.graph),l=[...c].filter(p=>!u.has(p)),f=[...u].filter(p=>!c.has(p));l.length>0&&t.push(`it took ${fn(l)}, which this one leaves`),f.length>0&&t.push(`this one takes ${fn(f)}, which it left`)}return t.length>0?t.join("; "):"what differs is among what its journal does not keep: --upsert, --expand-orphans, --max-orphans, --max-nodes, --max-records-per-object, --files, --keep-contact-points, --exclude, --exclude-object, --owner-map, --map and the choices of --config or --template"}function cb(r,e){let t=r.openAt(e);try{return t.samplePlan}finally{t.close()}}function sc(r){let e=r.indexOf("--audit");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--audit takes the file the audit trail is kept in.
830
- `),process.exit(2));try{La(t)}catch(n){process.stderr.write(`--audit ${t} is not an audit trail the command can add to (${V(n)}): give another file, or move it.
831
- `),process.exit(2)}return t}function ub(r,e){return{configStore:La(r),orgManager:{getOrg:t=>e.get(t)},log:t=>process.stderr.write(`${t}
832
- `)}}function Gs(r,e,t){if(r)try{su(ub(r,e),t)}catch(n){process.stderr.write(`The run's entry could not be added to the audit trail in ${r} (${V(n)}).
833
- `)}}function lb(r){let e=r.indexOf("--summary");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--summary takes the file to write the summary to.
834
- `),process.exit(2));let n=["--list-objects","--rehearse"].filter(o=>r.includes(o));return n.length>0&&(process.stderr.write(`--summary does not go with ${n.join(", ")}.
835
- `),process.exit(2)),Yt(t)&&(process.stderr.write(`--summary ${t} exists, and is not overwritten: it may be the summary of an earlier run, which --remove takes that run back from. Give another file, or move it.
836
- `),process.exit(2)),t}function fb(r){let e=r.indexOf("--remap-csv");if(e<0)return;let t=r[e+1];(t===void 0||t.startsWith("--"))&&(process.stderr.write(`--remap-csv takes the .csv file to write the id table to.
837
- `),process.exit(2));let n=Wt(process.cwd(),t),o=Wt(process.cwd());return n===o||n.startsWith(o+gy)||(process.stderr.write(`--remap-csv must stay inside cwd: "${t}" resolves outside ${o}
838
- `),process.exit(2)),n.toLowerCase().endsWith(".csv")||(process.stderr.write(`--remap-csv must use a .csv extension: "${t}"
839
- `),process.exit(2)),Yt(n)&&(process.stderr.write(`--remap-csv refuses to overwrite existing file: "${n}". Give another file, or move it.
840
- `),process.exit(2)),n}function pb(r,e){let t=r.includes("--files"),n=r.includes("--files-as-is"),o=r.indexOf("--max-file-size"),s=o>=0?r[o+1]:void 0;if(!t){(n||o>=0)&&(process.stderr.write(`--files-as-is and --max-file-size go with --files.
841
- `),process.exit(2));return}let i=o>=0?Number(s):10;return(!Number.isInteger(i)||i<1||i>35)&&(process.stderr.write(`--max-file-size takes a whole number of MB from 1 to ${35}, the most one call to Salesforce carries.
842
- `),process.exit(2)),uo(e,n)&&(process.stderr.write(`--anonymize anonymizes the records, and the content of a file cannot be anonymized: add --files-as-is to accept that files are copied as they are, or leave out --files.
843
- `),process.exit(2)),{maxFileSizeMB:i,acceptedAsIs:n}}function hb(r){let e=gu(r.fields);return r.fields.map(t=>({name:t.name,type:t.type,queryable:!0,createable:t.createable??!1,isReference:t.type==="reference",referenceTo:(t.referenceTo??[]).filter(n=>typeof n=="string"),nillable:t.nillable??!0,picklistValues:(t.picklistValues??[]).filter(n=>n?.active!==!1&&typeof n?.value=="string").map(n=>n.value),restrictedPicklist:t.restrictedPicklist===!0,...t.controllerName?{controllerName:t.controllerName}:{},defaultedOnCreate:t.defaultedOnCreate===!0,externalId:t.externalId===!0,updateable:t.updateable!==!1,...t.length>0?{length:t.length}:{},...mu(t,e),...typeof t.groupable=="boolean"?{groupable:t.groupable}:{},...typeof t.sortable=="boolean"?{sortable:t.sortable}:{},...typeof t.aggregatable=="boolean"?{aggregatable:t.aggregatable}:{}}))}function gb(r){return{name:r.name,fields:r.fields.map(e=>({name:e.name,type:String(e.type),referenceTo:(e.referenceTo??[]).filter(t=>typeof t=="string"),relationshipName:e.relationshipName??null,isMasterDetail:e.cascadeDelete===!0,nillable:e.nillable!==!1,createable:e.createable!==!1,updateable:e.updateable!==!1})),childRelationships:r.childRelationships.map(e=>({childSObject:e.childSObject,field:e.field,relationshipName:e.relationshipName??"",isCascadeDelete:!!e.cascadeDelete}))}}async function mb(r,e,t){let n="SELECT Id, Name, DeveloperName, NamespacePrefix, SobjectType FROM RecordType WHERE IsActive = true",o=async u=>(await vo({query:async l=>u.query(l),queryMore:async l=>u.queryMore(l)},n)).records,[s,i]=await Promise.all([o(r),o(e)]),a=u=>({id:u.Id,name:u.Name,developerName:u.DeveloperName,namespacePrefix:u.NamespacePrefix?u.NamespacePrefix:null,sobjectType:u.SobjectType}),[d,c]=[s.map(a),i.map(a)];for(let u of Ef(d,c))t?.(If(u));return new gs().buildMapping(d,c)}function wb(r){let e=new Map;return(t,n)=>{let o=`${t}::${n}`,s=e.get(o);if(s)return s;let i=r(t,n);return e.set(o,i),i.catch(()=>{e.get(o)===i&&e.delete(o)}),i}}async function Wd(r,e,t=!1){let n=t?await r.sobject(e).describe():await r.describe$(e);return{keyPrefix:n.keyPrefix??null,recordTypes:Tu(n.recordTypeInfos)}}function NA(r){return $o(r)==="failure"}var Dd={masterInSource:"on Master in the source",notRead:"whose record type the run does not write",decidedDefault:"sent to the default by your decision",dropped:"whose record type the target lacks or keeps from the user"};function Jd({developerName:r,label:e}){return e!==""&&e!==r?`${r} (${e})`:r}function _d(r,e){let{predicted:t}=r;if(!t)return`${e} on Master, which the target gives a record sent without one for the user the run writes as`;let n=Jd(t);return t.basis==="userDefault"?`${e} as ${n}, the default record type of the user the run writes as`:`${e} as ${n}, the only other ${r.objectApiName} record type open to the user the run writes as, whose describe names Master the default`}function yb(r,e){let t=e.read<r.rows?`${e.read} of ${r.rows}`:`${e.read}`,n=r.predicted?.developerName??"Master",[o,...s]=e.types;if(o&&s.length===0&&o.developerName===n)return`went in as ${Jd(o)}, read back on ${t}`;if(!o)return`none of them found as they were read back (asked of ${t})`;let i=e.types.map(a=>`${a.rows} ${Jd(a)}`).join(", ");return`read back on ${t}: ${i}; the describe said ${n}: an automation of the target sets the record type`}function bb(r,e){if(r.length===0)return[];let t=[`record types the target ${e?"would give":"gave"} the records created without one (${r.length} object(s)):`];for(let n of r){let o=Object.keys(Dd).filter(d=>(n.why[d]??0)>0),s=o.length===1?` ${Dd[o[0]]}`:o.length>1?` (${o.map(d=>`${n.why[d]} ${Dd[d]}`).join(", ")})`:"",{readBack:i}=n,a=e?_d(n,"would go in"):i?i.unread!==void 0?`${_d(n,"went in, its describe says,")}; the record types they hold could not be read back: ${i.unread}`:yb(n,i):_d(n,"went in, its describe says,");t.push(` ${n.objectApiName} ${n.rows} record(s)${s}: ${a}`)}return t}function Rb(r,e){let t=Kn(r.maxFileBytes),n=[`files (up to ${t} each):`];r.lookupFailure&&n.push(` ${r.lookupFailure}`," A real run stops here, before writing anything.");for(let o of r.objects){let s=Kn(o.plannedBytes);n.push(e?` ${o.objectApiName} ${o.planned} would be copied (${s}, dry run, nothing written)`:` ${o.objectApiName} ${o.copied} of ${o.planned} copied (${s})`+(o.failed>0?`, ${o.failed} failed`:""))}if(r.objects.length===0&&!r.lookupFailure&&n.push(" none to copy"),e&&r.wouldCopy&&r.wouldCopy.length>0){n.push(` would copy (${r.wouldCopy.length}):`);for(let o of r.wouldCopy)n.push(` ${o.objectApiName} ${o.name} ${Kn(o.bytes)}`)}if(r.links>0&&n.push(` links to other cloned records: ${r.links}`),r.remainingStorageBytes!==void 0&&n.push(` target file storage left: ${Kn(r.remainingStorageBytes)}`),r.leftOut.length>0){n.push(` left out (${r.leftOut.length}):`);for(let o of r.leftOut){let s=o.reason==="too-large"?`larger than ${t}`:o.reason==="external"?"kept outside Salesforce":"its records were not created by this run";n.push(` ${o.objectApiName} ${o.name} ${Kn(o.bytes)} \u2014 ${s}`)}}return n}function em(r,e){let t=r.truncatedObjects??[];if(t.length!==0)return{...e!==void 0?{perObject:e}:{},objects:[...t]}}function Ob(r){let e=new Map;for(let{objectApiName:i,rows:a}of r.writtenByThePlatform??[]){let d=Qn(i);e.set(d,(e.get(d)??0)+a)}let t=[...e.values()].reduce((i,a)=>i+a,0),n=r.linkedToCreatedCount??0;if(t===0&&n===0)return`linked: ${r.linkedCount} (already in the target, not created)`;let o=r.linkedCount-t-n,s=[...o>0?[`${o} already in the target, not created`]:[],...n>0?[`${n} to records the run created, the target refusing them as copies of those`]:[],...[...e].map(([i,a])=>`${a} written by the platform with ${i}`)];return`linked: ${r.linkedCount} (${s.join("; ")})`}var qd="FIELD_EXCLUSION_UNMATCHED";function tm(r){let e=`${An("--exclude","the exclusion")} ${r.objectApiName}.${r.field}`;return r.missing==="object"?`${e}: the source has no object ${r.objectApiName}`:`${e}: ${r.objectApiName} has no field ${r.field}`+(r.nearest!==void 0?` (${r.nearest}?)`:"")}function kb(r){return[`left nothing out, naming no field of the source (${r.length}):`,...r.map(e=>` ${tm(e)}`)]}function Eg(r,e){let t=Kt()?" of the template the resource names":e?` of --exclude, or of the fieldExclusions of ${e.flag} ${e.path}`:"";return`${r.map(tm).join("; ")}: ${r.length===1?"it leaves":"they leave"} nothing out, and the field the run was asked to keep back would be written with every row. Name the field as the source does \u2014 whatever its case \u2014 or leave the exclusion out${t}. Nothing was read or written.`}async function Sb(r,e,t){let n=Object.keys(r);if(n.length===0)return[];let o=e.nodes.map(i=>i.objectApiName),s=new Map;for(let i of n){let a=o.find(d=>d.toLowerCase()===i.toLowerCase())??i;if(!s.has(a))try{s.set(a,await t(a))}catch(d){s.set(a,nr(d)?void 0:null)}}return ns(r,o,i=>s.has(i)?s.get(i):null).unmatched}function Tb(r){let e=Kt()?"":" (--max-orphans raises it)";return`parents from outside the run not copied: ${r.notCopied} past the ${r.cap} --expand-orphans copies at most${e}, of ${r.objects.join(", ")}; the rows that cannot be written without one were refused`}function Ig(r,e=!1,t,n=!1){let o=[`success: ${r.successCount}`,...r.wouldInsertCount>0?[`would be inserted: ${r.wouldInsertCount} (dry run, nothing written)`]:[],...r.updatedCount>0?[`updated: ${r.updatedCount} (matched by their external id, not created)`]:[],Ob(r),`failed: ${r.failedCount}`+(r.failedReads.length>0?` (read failed: ${r.failedReads.join(", ")})`:""),`skipped: ${r.skippedCount}`,`remaps: ${r.remapCount}`,...r.apiCalls!==void 0?[`calls: ${r.apiCalls} (requests the run sent to both orgs)`]:[]];if(r.existingRecords.length>0){o.push("",`already in the target (${r.existingRecords.length} object(s)):`);for(let g of r.existingRecords){let h=g.linkedToCreated??0,m=[...g.linked-h>0||h===0?[`${g.linked-h} linked`]:[],...h>0?[`${h} linked to records the run created (refused as copies of those)`]:[]];g.unidentified>0&&m.push(`${g.unidentified} not identified \u2014 their children lost the link`),o.push(` ${g.objectApiName} ${m.join(", ")}`)}}if(r.cappedObjects){let{perObject:g,objects:h}=r.cappedObjects;o.push("",`stopped at ${g} records per object (${An("--max","maxRecordsPerObject")}), the source holding more, which were not cloned (${h.length} object(s)):`,...h.map(m=>` ${m}`))}let s=em(r,t);if(s){let g=s.perObject!==void 0?`${s.perObject} `:"",h=Kt()?"":" (--max-records-per-object)";o.push("",`TRUNCATED at ${g}records per object${h}, the source holding more, which were not cloned (${s.objects.length} object(s)):`,...s.objects.map(m=>` ${m}`))}let i=r.fieldExclusionsUnmatched??[];i.length>0&&o.push("",...kb(i)),r.orphanParentsCapped&&o.push("",Tb(r.orphanParentsCapped)),r.files&&o.push("",...Rb(r.files,e));let a=r.fileContentFieldsLeftOut??[];if(a.length>0){o.push("",`left empty, as they hold a file's content (${a.length} object(s)):`);for(let{objectApiName:g,fields:h}of a)o.push(` ${g} ${h.join(", ")}`)}let d=r.encryptedFieldsLeftOut??[];if(d.length>0){o.push("",`left out, encrypted and read masked: the user the source is read as lacks View Encrypted Data, and the masks are not copied (${d.length} object(s)):`);for(let{objectApiName:g,fields:h}of d)o.push(` ${g} ${h.join(", ")}`)}let c=r.picklistValuesChanged??[];if(c.length>0){let g=new Set(c.map(h=>h.objectApiName)).size;o.push("",`picklist values not written as read (${g} object(s)):`);for(let h of c)o.push(` ${h.objectApiName} ${pl(h)}`)}let u=r.currenciesReplaced??[];if(u.length>0){let g=new Set(u.map(h=>h.objectApiName)).size;o.push("",`written in another currency (${g} object(s)):`);for(let h of u)o.push(` ${h.objectApiName} ${Su(h)}`)}let l=bb(r.recordTypesGiven??[],e);l.length>0&&(o.push("",...l),e&&n&&o.push(" the permission sets a real run assigns to mute the automation may open other record types to the user it writes as: it reads them again once assigned, and its summary says what the target gave"));let f=r.writtenWithoutFields??[];if(f.length>0){o.push("",`written again without a field the target refused (${f.length} object(s)):`);for(let{objectApiName:g,fields:h}of f)for(let{field:m,refusedBy:R="validation-rule",reason:b,rows:k}of h)o.push(` ${g}.${m} ${k} record(s) \u2014 ${wy[R]} \u2014 ${b}`)}r.contactPoints&&o.push("",...Fb(r.contactPoints,e));let p=r.mayHaveBeenWritten??[];if(p.length>0){o.push("",`may be in the target, under ids the run never learned (${An("--remove","destroy")} cannot reach them):`);for(let{objectApiName:g,sourceIds:h}of p)o.push(` ${g} ${h.length} record(s)`)}if(r.decisionsApplied&&r.decisionsApplied.length>0&&o.push("",...Pb(r.decisionsApplied)),r.gaps&&o.push("",...Ib(r.gaps)),r.errors.length>0){o.push("",`errors (${r.errors.length} object(s)):`);for(let g of r.errors){o.push(` [${g.stage}] ${g.objectApiName} ${g.failedCount}/${g.attemptedCount}`);for(let h of g.samples){o.push(` ${h.recordSummary}`);for(let m of h.messages)o.push(` \u2514 ${m}`)}}}return o}function Ab(r,e){return{objectApiName:(e.nodes.find(n=>n.level===0)??e.nodes[0])?.objectApiName??r.query?.objectApiName??"",from:r.query?"query":"records",...r.query?{query:r.query.soql}:{ids:[...r.ids??[]]},cap:r.cap,...r.plan!==void 0?{plan:r.plan}:{},...r.readTotal!==void 0?{readTotal:r.readTotal}:{}}}var Yr=10;function jb(r){let e=r.length-Yr;return`${r.slice(0,Yr).join(", ")}${e>0?` and ${e} more`:""}`}function En(r,e){return`${r.toLocaleString("en-US")} ${e}${r===1?"":"s"}`}function $b(r,e){let t=r.roots;if(!t)return[];let n=t.objectApiName,o=t.query?`ORDER BY ${t.query.orderBy??"Id"}${t.query.limit!==void 0?`, LIMIT ${t.query.limit}`:""}; `:"",s=e.resumed?"the journal of the run taken up":`the dry run's plan${e.plan!==void 0?` ${e.plan}`:""}`,i=[t.from==="plan"?`roots: ${En(t.read,`${n} record`)} taken from ${s} (sha256 ${t.sha256.slice(0,12)}\u2026, read ${t.readAt}; at most ${t.cap})`:t.from==="query"?`roots: ${En(t.read,`${n} record`)} the query returns (${o}at most ${t.cap})`:`roots: ${En(t.read,`${n} record`)} named (at most ${t.cap})`];t.from!=="plan"&&e.dryRun&&e.plan!==void 0&&i.push(`roots: kept in ${e.plan} (sha256 ${t.sha256.slice(0,12)}\u2026): the run given --roots-plan with it writes these records, and none the query chooses after`),t.readAgain&&i.push(`roots: the dry run's plan of ${t.readAgain.readAt} (${En(t.readAgain.roots,"record")}) was a day old or more: the query was read again in its place`),t.gone.length>0&&i.push(`roots gone from ${e.source} since they were chosen: ${t.gone.length} (${jb(t.gone)}), none written`);let a=r.readByObject.filter(l=>l.read>0),d=a.reduce((l,f)=>l+f.read,0);i.push(`read: ${En(d,"record")} of ${En(a.length,"object")}`+(r.reads?`, ${En(r.reads.source,"request")} of ${e.source}`:""));for(let l of a)i.push(...vb(l));let c=t.linked>0?`, ${t.linked} linked to records ${e.target} already held`:"",u=(t.withTheirAccount??0)>0?`, ${t.withTheirAccount} of them with their person account`:"";if(i.push(`${e.dryRun?"roots that would be written":"roots written"}: ${t.written} of ${t.read}${u}${c}`),t.failed.length>0){i.push(`roots refused: ${t.failed.length}`);for(let{id:l,reason:f}of t.failed.slice(0,Yr))i.push(` ${l}: ${f}`);t.failed.length>Yr&&i.push(` and ${t.failed.length-Yr} more`)}return i}function vb(r){let e=r.origin;if(!e)return[];let t=[...e.roots>0?[En(e.roots,"root")]:[],...e.under>0?[`${e.under} under the clone's records`]:[],...e.named>0?[`${e.named} named by the clone's records`]:[]],n=r.readUnder&&r.readUnder.length>0?` (read under ${r.readUnder.join(", ")})`:"",o=t.length>1?`${r.read} = ${t.join(" + ")}`:t[0]??`${r.read}`;return[` ${r.objectApiName}: ${o}${n}`]}function Eb(r){let e=r.detail??{},t=[];typeof e.longest=="number"&&typeof e.length=="number"&&t.push(`longest ${e.longest} of ${e.length} characters`),typeof e.precision=="number"&&t.push(`precision ${e.precision}, scale ${String(e.scale??0)}`),typeof e.replacement=="string"&&t.push(`written as "${e.replacement}"`);let n=e.amountsConverted;Array.isArray(n)&&n.length>0&&t.push(`amounts converted into it: ${n.join(", ")}`),e.amountsAsRead===!0&&t.push("amounts written as read, no rate converts them"),typeof e.colliding=="number"&&t.push(`${e.colliding} value(s) already in the target`),e.linkedToTheRecordItNames===!0&&t.push("a real run links each row to the record the target holds");let o=e.mapTo;return Array.isArray(o)&&o.length>0&&t.push(`may map to ${o.join(", ")}`),e.ignored===!0&&t.push("ignored"),t.length>0?` (${t.join("; ")})`:""}function Ib(r){return r.length===0?["gaps: none found (dry run: nothing the target would refuse or change)"]:[`gaps the target holds against the rows (${r.length}, dry run):`,...r.map(e=>{let t=e.field?`${e.objectApiName}.${e.field}`:e.objectApiName,n=e.value!==void 0?` "${e.value}"`:"",o=e.recordType!==void 0?` (record type ${e.recordType})`:"";return` [${e.severity}] ${t} ${e.kind}${n}${o}: ${e.rows} record(s)${Eb(e)}`})]}function xb(r){if(!r.choicesFrom)return[];let e=[Kt()?"choices from the resource in the file:":`choices from ${r.choicesFrom.flag} ${r.choicesFrom.path}, the flags over it:`],t=Object.entries(r.fieldExclusions).flatMap(([a,d])=>d.map(c=>`${a}.${c}`));t.length>0&&e.push(` fields left out: ${t.join(", ")}`),r.excludedObjects.length>0&&e.push(` objects left out: ${r.excludedObjects.join(", ")}`);for(let[a,d]of Object.entries(r.objectSoqlFilters))e.push(` filter ${a}: ${d}`);let n=Object.keys(r.ownerMappings).length;n>0&&e.push(` owners mapped: ${n}`);for(let[a,d]of Object.entries(r.fieldMappings))for(let[c,u]of Object.entries(d))e.push(` renamed: ${a}.${c} \u2192 ${u}`);let o=r.decisions,s=a=>a!==void 0?` (record type ${a})`:"",i=[...(o?.picklistValueMappings??[]).map(a=>` ${a.object}.${a.field} ${a.to===null?"leave_empty":"map_value"} "${a.from}"${a.to!==null?` \u2192 "${a.to}"`:""}${s(a.recordType)}`),...(o?.recordTypeMappings??[]).map(a=>` ${a.object} map_record_type "${a.from}" \u2192 ${a.to===null?"the default":`"${a.to}"`}`),...(o?.defaultValues??[]).map(a=>` ${a.object}.${a.field} set_default "${String(a.value)}"`),...(o?.truncateFields??[]).map(a=>` ${a.object}.${a.field} truncate`),...(o?.skippedRows??[]).map(a=>{let d=Rc(a.gapId),c=hl(a);return` ${a.object}.${d?.field??"?"} skip_rows "${d?.value??""}"${s(d?.recordType)}`+(c!==void 0?`: ignored, ${c}`:"")}),...(o?.ignoredGaps??[]).map(a=>` ignore ${a}`)];return i.length>0&&e.push(` decisions (${i.length}):`,...i),e}function Pb(r){return[`decisions applied (${r.length}):`,...r.map(e=>{let t=e.field?`${e.objectApiName}.${e.field}`:e.objectApiName,n=e.from!==void 0?` "${e.from}"`:"",o=e.to!==void 0?` \u2192 "${e.to}"`:"",s=e.recordType!==void 0?` (record type ${e.recordType})`:"";return` ${t} ${e.kind}${n}${o}${s}: ${e.rows} record(s)`})]}function Fb(r,e){if(!r.neutralized)return[`contact points: written as read (${An("--keep-contact-points","keepContactPoints")}): the target's flows and email alerts may reach the people the records name`];let t=e?"would be neutralized (dry run, nothing written)":"neutralized";return[`contact points: ${r.values} value(s) in ${r.fields.length} field(s) ${t} \u2014 emails under .invalid, phone numbers in a fictional range`,...r.fields.map(({objectApiName:n,field:o,values:s})=>` ${n}.${o} ${s}`),...r.numbersExhausted?[` ${r.numbersExhausted} phone number(s) left out, their field empty: the 10 000 fictional numbers were all given to other numbers of the run`]:[]]}function Nb(r){return r.flatMap(({objectApiName:e,fields:t})=>t.flatMap(n=>{if(n.externalId!==!0||n.createable===!1)return[];let o=Xu(n.name,String(n.type).toLowerCase());return o?[{objectApiName:e,field:n.name,kind:o}]:[]}))}function Cb(r,e){return r.length===0?[]:[`upsert keys: --upsert matches the records of ${e} by these external ids, which the run writes neutralized (emails under .invalid, phone numbers in a fictional range): a record of ${e} holding the real address or number is not matched, and the run creates another beside it; one an earlier run wrote neutralized is. --keep-contact-points matches the real ones`,...r.map(({objectApiName:t,field:n,kind:o})=>` ${t}.${n} (${o})`)]}function Mb(r,e,t,n){if(!r)return{};let o=Dc(Oc(e.gaps,t??[]).filter(s=>!lo(s,n)));return o.length>0?{adminChanges:o}:{}}function Bb(r,e){let t=em(r,e);return{successCount:r.successCount,updatedCount:r.updatedCount,linkedCount:r.linkedCount,...r.linkedToCreatedCount?{linkedToCreatedCount:r.linkedToCreatedCount}:{},...r.writtenByThePlatform?{writtenByThePlatform:r.writtenByThePlatform}:{},wouldInsertCount:r.wouldInsertCount,failedCount:r.failedCount,skippedCount:r.skippedCount,remapCount:r.remapCount,existingRecords:r.existingRecords,errors:r.errors.map(n=>({objectApiName:n.objectApiName,stage:n.stage,failedCount:n.failedCount,attemptedCount:n.attemptedCount,samples:n.samples,...n.referenceData===!0?{referenceData:!0}:{},...n.skipped===!0?{skipped:!0}:{}})),remapTable:r.remapTable,existingSourceIds:r.existingSourceIds,updatedSourceIds:r.updatedSourceIds,createdByObject:r.createdByObject,...r.withTheirRecordSourceIds?{withTheirRecordSourceIds:r.withTheirRecordSourceIds}:{},...r.writtenBetween?{writtenBetween:r.writtenBetween}:{},readByObject:r.readByObject,failedReads:r.failedReads,...r.cappedObjects?{cappedObjects:r.cappedObjects}:{},...t?{truncatedObjects:t}:{},...r.fieldExclusionsUnmatched?{fieldExclusionsUnmatched:r.fieldExclusionsUnmatched}:{},...r.orphanParentsCapped?{orphanParentsCapped:r.orphanParentsCapped}:{},...r.files?{files:r.files}:{},...r.fileContentFieldsLeftOut?{fileContentFieldsLeftOut:r.fileContentFieldsLeftOut}:{},...r.encryptedFieldsLeftOut?{encryptedFieldsLeftOut:r.encryptedFieldsLeftOut}:{},...r.picklistValuesChanged?{picklistValuesChanged:r.picklistValuesChanged}:{},...r.currenciesReplaced?{currenciesReplaced:r.currenciesReplaced}:{},...r.recordTypesGiven?{recordTypesGiven:r.recordTypesGiven}:{},...r.writtenWithoutFields?{writtenWithoutFields:r.writtenWithoutFields}:{},...r.lookupsLeftEmptyByFilter?{lookupsLeftEmptyByFilter:r.lookupsLeftEmptyByFilter}:{},...r.contactPoints?{contactPoints:r.contactPoints}:{},...r.apiCalls!==void 0?{apiCalls:r.apiCalls}:{},...r.gaps?{gaps:r.gaps}:{},...r.decisionsApplied?{decisionsApplied:r.decisionsApplied}:{},...r.mayHaveBeenWritten?{mayHaveBeenWritten:r.mayHaveBeenWritten}:{},...r.remapInJournal?{remapInJournal:!0}:{},...r.remapInJournal?{createdCountByObject:r.remapByObject.filter(({created:n})=>n>0).map(({objectApiName:n,created:o})=>({objectApiName:n,created:o}))}:{},...r.sample?{sample:cR(r.sample)}:{},...r.roots?{roots:r.roots}:{},...r.reads?{reads:r.reads}:{}}}function Lb(r){if(r.status==="running"&&r.message.startsWith("[dry-run] "))return` ${r.message}`;if(r.status==="scanning")return r.progress>0&&r.message?` ${r.message}`:void 0;if(!(r.status!=="done"&&r.status!=="error"&&r.status!=="skipped"&&r.status!=="stopped"))return r.message?` ${r.message}`:void 0}function Wb(r){let e=new Set(r.nodes.filter($r).map(n=>n.objectApiName)),t=!1;return n=>{if(n.status==="skipped"&&e.size>1&&e.has(n.objectName)){if(t)return;t=!0;let o=St("--list-objects")?"; --list-objects names them":"";return` Skipped ${e.size} objects (excluded: empty tables${o})`}return Lb(n)}}function Db(r,e,t){let n=new Set(r.nodes.map(p=>p.objectApiName)),o=r.nodes.filter(p=>p.included).length,s=r.edges.filter(p=>n.has(p.sourceObject)&&n.has(p.targetObject)).length,i=r.nodes.length-r.nodes.filter(rf).length,a=i>0?` (${i} empty, taking no place under it)`:"",d=r.nodes.length-i>t?" (raised for the parents their records cannot be written without)":"",{refused:c,unanswered:u}=cm(r),l=c.length>0?`, ${c.length} not counted (${fn(c)})`:"",f=u.length>0?`, ${u.length} of them kept though their count got no answer (${fn(u)})`:"";return`graph: ${r.nodes.length} objects at a cap of ${t}${a}${d}, ${o} included${f}${l}; ${r.edges.length} lookups, ${s} between these objects; ${e.waves.length} waves, ${e.cycleResolutions.length} cycles`+(r.truncated?" (TRUNCATED)":"")}var nm={missingInTarget:"missing in the target",notQueryable:"not queryable",empty:"empty",unreadable:"unreadable",notWritable:"not writable in the target",createOnly:"creatable but not editable or deletable in the target",setup:"setup",platformCreated:"written by the platform alone",metadata:"metadata",chatter:"Chatter",history:"history",sharing:"sharing",changeEvent:"change events",unsupportedKind:"of a kind no clone writes",customSetting:"custom settings",files:"files, copied with --files",excludedByUser:"left out by --exclude-object",notDescribed:"not described"};function _b(r,e,t){let n=r.nodes.filter(a=>a.included).length,{objects:o,counts:s}=cs(r),i=s.map(({reason:a,count:d})=>`${d} ${nm[a]}`).join(", ");return`graph: the whole of ${t}, ${n} object(s) to copy, ${o.length} left out${i?` (${i})`:""}; ${r.edges.length} lookups; ${e.waves.length} waves, ${e.cycleResolutions.length} cycles`}var qb={listing:()=>"discovery: listing the objects of both orgs\u2026",counting:r=>`discovery: counting the records of ${r??"each"} object(s)\u2026`,describing:r=>`discovery: describing the ${r??""} object(s) that hold records\u2026`};async function Ub(r,e,t){let n;try{return await r.discover(e,{onProgress:o=>{if(o.phase===n)return;n=o.phase;let s=qb[o.phase];s&&t(s(o.total))}})}catch(o){process.stderr.write(`The whole org could not be discovered: ${V(o)}
844
- `),process.exit(1)}}function Ud(r,e,t){let{estimate:n,remaining:o,max:s}=e;return o===void 0||s===void 0?` ${r} of ${t}: about ${n}; what it has left today could not be read`+(e.unread?` (${e.unread})`:""):` ${r} of ${t}: about ${n}, of the ${o} it has left of its ${s} a day`+(e.near?": it would leave less than a tenth of them":"")}var xg=10;function fn(r){let e=r.length-xg;return e>0?`${r.slice(0,xg).join(", ")} and ${e} more`:r.join(", ")}function Gb(r,e,t,n=[]){let{source:o,bulk:s}=r,i=n.filter(({jobs:m})=>m>0),a=i.length>0?` (${fn(i.map(m=>`${m.objectApiName}: ${m.jobs} of ${m.jobRows}`))}; rows of a job carrying the same values go by REST instead)`:"",d=[` writes: ${s?.jobs??0} Bulk API job(s) of ${s?.jobRows??0} record(s) at most${a}, ${s?.restRows??0} record(s) by REST, ${r.restObjects.length} object(s) by REST alone; about ${Math.max(1,Math.round(r.durationSeconds/60))} minute(s) one after another`,Ud("API requests",r.targetApi,t),...s?.batches?[Ud("Bulk API batches",s.batches,t)]:[],Ud("API requests",r.sourceApi,o),...r.discovery?[` of them, sent already by discovery: ${r.discovery.target} of ${t}'s and ${r.discovery.source} of ${o}'s`]:[]],c=r.fileStorage;c&&d.push(` files: ${c.files} file(s), about ${Ht(c.estimateMB)} MB of file storage, of the ${c.remainingMB} MB ${t} has left of ${c.maxMB} MB`+(c.overCeiling>0?`; ${c.overCeiling} past the largest file copied, left out`:""));let u=e.map(({reason:m,count:R})=>`${R} ${nm[m]}`).join(", ");d.push(` left out of ${o}: ${r.leftOut} object(s)${u?`: ${u}`:""}`);let{carried:l}=r,f=l?[["read through a filter",l.filters],["left out by name",l.excluded],["with rows held back by a decision",l.heldBack],["copied without some of their fields",l.fieldsLeftOut]]:[];for(let[m,R]of f)R.length>0&&d.push(` ${m}: ${fn(R)}`);let p=r.personalAsIs??[],g=p.reduce((m,{fields:R})=>m+R.length,0);d.push(g>0?` personal data: ${g} field(s) of ${p.length} object(s) copied as ${o} holds them: `+fn(p.map(({objectApiName:m,fields:R})=>`${m} (${R.join(", ")})`)):" personal data: no personal field copied as it is");let h=r.managedPackages??[];return h.length>0&&d.push(` managed packages: ${h.length} object(s) written, whose triggers and flows no mute reaches: ${fn(h)}`),r.contactPointsBlanked!==void 0&&d.push(` phone numbers: up to ${r.contactPointsBlanked} past the fictional range go in empty`),d}function zb(r,e,t){return`discovery: ${r.source} API request(s) sent to ${e} and ${r.target} to ${t}, before any row is read`}function fr(r,e,t){let n=(o,s)=>{if(!o)return{sent:s};let{parts:i,...a}=o;return{...a,...i?{parts:i}:{},sent:s}};return{target:n(e.target,r.target),source:n(e.source,r.source),...t?{discovery:t}:{}}}function Pg(r){return`Write ${r}?`}function Fg(r,e,t,n){let{source:o,bulk:s}=r,i=e.objects.filter(({rows:h})=>h>0).length,a=r.managedPackages??[],d=r.personalAsIs??[],c=d.reduce((h,{fields:m})=>h+m.length,0),u=r.sample,l=u?.roots?im(u.roots):[],f=u?.roots?.window!==void 0||(u?.roots?.where??[]).length>0?" in the draw":"";return[(u&&n?`a sample of ${o}: ${e.totalRows} record(s) of ${i} object(s) (of ${u.sourceRows} in ${o}) into ${t}, about ${Ht(u.storageMB)} MB`+(ic(n.budget)?` of the ${Ht(u.budgetMB)} MB it may take`:"")+(u.automationMB!==void 0?`, ${Ht(u.automationMB)} MB of it for what the target's automation creates`:"")+`; ${[ac(u),...l].join("; ")}, ${Ys(u.share)} % of the roots${f}; drawn at ${u.drawnAt} by ${u.drawnBy==="dryRun"?"a dry run":"this run"}; ${s?.jobs??0} Bulk API job(s) among them`:void 0)??`${e.totalRows} record(s) of ${i} object(s) of ${o} into ${t}, ${s?.jobs??0} Bulk API job(s) among them`,`about ${r.targetApi.estimate} of ${t}'s API requests`+(s?.batches?` and ${s.batches.estimate} of its Bulk API batches`:"")+` and ${r.sourceApi.estimate} of ${o}'s`,...a.length>0?[`${a.length} object(s) of managed packages, whose triggers and flows no mute reaches (${fn(a)})`]:[],...r.contactPointsBlanked!==void 0?[`up to ${r.contactPointsBlanked} phone number(s) written empty`]:[],c>0?`${c} personal field(s) of ${d.length} object(s) copied as they are`:"no personal field copied as it is"].join("; ")}function Ng(r,e=!1){let t=" \u2014 or leave objects out (--exclude-object), narrow them (--filter)"+(e?".":", or copy a sample of the org that fits the target (--fit share, its dry run first).");return r.replaceAll("turn the copy of files off on Review","leave out --files").replaceAll("leave the object out on Review","leave it out with --exclude-object").replaceAll("the sandforge.forge.maxRecordsPerObject setting lets a run hold at once: raise the setting","--max-records-per-object lets a run hold at once: raise it").replaceAll(" \u2014 or leave objects out.",t).replaceAll(" \u2014 or write fewer records.",t)}var Hb=[[/--fit-where "([A-Za-z0-9_]+)=([^"]*)"/g,'fit.where.$1: "$2"'],[/--fit-where ([A-Za-z0-9_]+)=…/g,"fit.where.$1"],[/--fit-strata ([A-Za-z0-9_]+)\.<Field>/g,"fit.strata: [$1.<Field>]"],[/--fit-draw (uniform|recent|oldest)\b/g,"fit.draw: $1"],[/--fit-within(?![\w-])/g,"fit.withinMB"],[/--fit-(window|where|strata|draw|seed)(?![\w-])/g,"fit.$1"],[/--max-total(?![\w-])/g,"maxTotal"]];function Xr(r){return Kt()?Hb.reduce((e,[t,n])=>e.replace(t,n),r):r}function Kb(r,e,t){let n=r.personAccountsAsBusiness??0;if(!(n<=0))return` person accounts: ${n} of ${e}'s go in as business accounts, ${t} having none, and their contacts as contacts of their own`}function Vb(r,e,t=!1,n=!1){return!St("--max-total")&&ws()?cc(r,e,n).replace(/^The run /,"The clone of the whole org "):`The clone of the whole org would write ${r} records, more than the ${e} --max-total holds it to: give --max-total the count its dry run says, `+(t?"":"copy a sample of the org that fits the target and --max-total (--fit share, its dry run first), ")+"or leave objects out (--exclude-object) or narrow them (--filter)."}function rm(r){let{objectApiName:e,count:t,query:n,fits:o,each:s}=r,i=n?"the query chooses":"named";if(o<1)return;let a=`the ${t} ${e} records ${i} take ${s} each, and about ${o} of them fit`;if(!n)return`${a}: name ${o} of them at most`;let d=n.orderBy===void 0?`the newest ${o}`:`the first ${o} in its order`;return`${a}: ${at("--query")} "${Rl(e,n,o)}" clones ${d}, its dry run first, or narrow its WHERE`}function om(r){return`one of the ${r.count} ${r.objectApiName} records ${r.query?"the query chooses":"named"} takes ${r.each} on average, more than ${r.past} by itself`}function Jb(r,e,t,n=!1){if(ws())return cc(r,e,n);let o=rm(t),s=`leave objects out (${at("--exclude-object")}) or narrow them (${at("--filter")})`;return`The run would write ${r} records, more than the ${e} ${at("--max-total")} holds it to: `+(o!==void 0?`${o}; or ${s}, or raise ${at("--max-total")}.`:`${om(t)}: ${s}, clone less deep (${at("--depth")} direct), or raise ${at("--max-total")}.`)}function Qb(r,e,t){if(r.verdict!=="exceeds")return;let n=rm(t),o=`leave objects out (${at("--exclude-object")})`;return`The records to write take ${ma(r)}, and ${e} has ${r.remainingMB} MB left of ${r.maxMB} MB: `+(n!==void 0?`${n}; or ${o}, or free data storage in ${e}.`:`${om(t)}: ${o}, clone less deep (${at("--depth")} direct), or free data storage in ${e}.`)}function Cg(r,e,t){let n=r.roots;if(!n||n.count<1)return;let o=n.from!=="records";return{objectApiName:n.objectApiName,count:n.count,...o&&e?{query:e}:{},fits:bl(n.count,t.taken,t.room),each:t.each(t.taken/n.count),past:t.past}}function Yb(r,e){if(r.verdict==="exceeds")return`The records to write take ${ma(r)}, and ${e} has ${r.remainingMB} MB left of ${r.maxMB} MB: copy a sample of the org that fits it (--fit share, its dry run first), leave objects out (--exclude-object) or narrow them (--filter), or free data storage in ${e}.`}var Xb=2*1024;function Zb(r){let{storage:e,sample:t,target:n}=r,{withinMB:o}=t.options,s=t.options.maxTotal??er,i=yf({storage:e,bounds:{...o!==void 0?{withinMB:o}:{},...t.maxTotalGiven?{maxTotal:s}:{}},target:n});if(i)throw Pe.of(i);let a=r.automation?{automation:r.automation}:{},d=Xa({storage:e,...o!==void 0?{withinMB:o}:{},...a});if(d)return{...d,budget:{...d.budget,maxTotal:s}};let c=Xa({storage:{maxMB:0,remainingMB:0},...a});return{budget:{bytes:Number.MAX_SAFE_INTEGER,maxTotal:s,limitedBy:"maxTotal"},bytesLimit:"within",roomBytes:s*Xb,...c?.automationBytes?{automationBytes:c.automationBytes}:{}}}function ic(r){return r.remainingMB!==void 0||r.withinMB!==void 0}function Ys(r){return String(Number((r*100).toPrecision(2)))}function ac(r){switch(r.draw){case"recent":return"the newest by creation date";case"oldest":return"the oldest by creation date";case"uniform":return`seed ${r.seed}, spread over the org`}}function sm(r){let e=r.field==="LastModifiedDate"?"last modified":"created";if(r.lastDays!==void 0)return`roots ${e} in the last ${r.lastDays} day(s)`+(r.from!==void 0?`, from ${r.from}`:"");let t=r.from!==void 0?` from ${r.from}`:"",n=r.to!==void 0?` to before ${r.to}`:"";return`roots ${e}${t}${n}`}function im(r){return[...r.window?[sm(r.window)]:[],...(r.where??[]).map(({objectApiName:e,where:t})=>`${e} where ${t}`),...(r.strata??[]).map(({objectApiName:e,field:t,values:n})=>`${e} stratified by ${t} (${n} value(s))`)]}function eR(r){return(r??[]).map(({objectApiName:e,field:t,values:n,more:o})=>({objectApiName:e,field:t,values:n.length+(o??0)}))}function am(r){return r?.window!==void 0||(r?.where??[]).length>0}function tR(r,e,t){let{budget:n}=r;switch(n.limitedBy){case"heavyRoots":return`every root fits but ${r.heavyRoots.length} heavy root(s) set aside below, each past a tenth of the room ${t} has: they alone keep the sample from every root`;case"storage":return`limited by the data storage ${t} has left`;case"within":return`limited by --fit-within ${n.withinMB??""}`.trimEnd();case"maxTotal":return`limited by --max-total ${n.maxTotal??er}`;case"targetRequests":return`limited by the daily API requests ${t} has left`;case"bulkBatches":return`limited by the daily Bulk API batches ${t} has left`;case"sourceRequests":return`limited by the daily API requests ${e} has left`;case"whole":return"every record of the org fits: leave out --fit share to copy the whole org";case"draw":return Xr("limited by the draw: every root --fit-window and --fit-where leave is in the sample; widen them to take more")}}function nR(r){let e=`${r.details} records (${r.details}.${r.field})`;return r.asParents!==void 0?`the ${r.asParents} brought in as parents keep only the ${e} drawn on their own: if they total them (an amount, a roll-up summary), the total counts only those`:`keeps ${r.kept??0} of its ${r.sourceRows??0} ${e} in the sample: if it totals them (an amount, a roll-up summary), the total counts only those`}function rR(r,e){let{budget:t}=r,n=`about ${Ht(r.storageBytes/1048576)} MB`;if(!ic(t))return`${n}, held to ${t.maxTotal??er} records (--max-total): ${e} would not say its data storage`;let o=`${n} of the ${Ht(t.bytes/1048576)} MB the sample may take`;if(t.remainingMB===void 0)return`${o} (--fit-within ${t.withinMB}; ${e} would not say its data storage)`;let s=[`${Ys(t.share??0)} % of the ${t.remainingMB} MB ${e} has left`+(t.maxMB!==void 0?` of ${t.maxMB} MB`:""),...t.roundingMB!==void 0?[`${t.roundingMB} MB off for rounding`]:[],...t.automationMB!==void 0&&t.automationMB>0?[`${Ht(t.automationMB)} MB for what its automation creates`]:[],...t.withinMB!==void 0?[`--fit-within ${t.withinMB}`]:[]];return`${o} (${s.join(", ")})`}var dm={referenceData:"reference data, matched by name",catalog:"the price catalog",smallParent:"a small parent",asked:"--fit-whole"};function oR(r,e,t){switch(r){case"noParentInSource":return`a lookup they may not leave empty names a record ${e} does not hold`;case"outsideFilter":return"a lookup they may not leave empty names a record outside its object's filter";case"excludedObject":return"a lookup they may not leave empty names a record of an object left out";case"withoutParent":return"a record they cannot be written without is left out itself";case"heldBack":return"their record type is closed to the user the run writes as";case"recordTypeNotInTarget":return`their record type is one ${t} has none of`}}function sR(r,e){if(r.whole){let t=e.find(n=>n.objectApiName===r.objectApiName)?.why;return`copied whole${t?` (${dm[t]})`:""}`}return`${r.roots} drawn, ${r.below} under a parent, ${r.asParents} as parents`}function iR(r){return r.label!==void 0?r.label:r.value===null?"(no value)":String(r.value)}function aR(r,e){let t=r.roots;if(!t)return[];let n=[];if(am(t)){let s=new Set(t.notWindowed??[]),i=[...r.objects.flatMap(a=>a.rootsInTheDraw===void 0?[]:[`${a.objectApiName} ${a.rootsInTheDraw} in the draw`+(a.rootsInTheSource!==void 0?` of ${a.rootsInTheSource} root(s) in ${e}`:"")]),...r.noRecordDrawn.filter(({objectApiName:a,noRootInTheDraw:d})=>d&&!s.has(a)).map(({objectApiName:a,sourceRows:d})=>`${a} none in the draw (${d} record(s) in ${e})`),...s.size>0&&t.window?[`not windowed (no ${t.window.field}): ${[...s].join(", ")}`]:[]];i.length>0&&n.push(`roots: ${i.join("; ")}`)}let o=t.strata??[];if(o.length>0){let s=o.map(({objectApiName:i,field:a,values:d,more:c})=>`${i} by ${a}: `+d.map(u=>`${iR(u)} ${u.kept} of ${u.roots} root(s)`).join(", ")+(c!==void 0&&c>0?`, and ${c} more value(s)`:""));n.push(`strata: ${s.join("; ")} (the records under the roots are not stratified)`)}return n}function dR(r,e){let{source:t,target:n}=e,o=r.objects.reduce((c,u)=>c+u.sourceRows,0)+r.noRecordDrawn.reduce((c,u)=>c+u.sourceRows,0),s=r.roots?im({...r.roots,strata:eR(r.roots.strata)}):[],i=[`sample: ${r.rows} of ${o} record(s) of ${t}, of ${r.objects.length} object(s): ${Ys(r.share)} % of the roots ${am(r.roots)?"in the draw ":""}of each object (${[ac(r),...s].join("; ")}), with the records they reach and name; ${rR(r,n)}; ${tR(r,t,n)}`];for(let c of r.objects){let u=(c.childrenCut??[]).map(({field:f,rows:p})=>`${f} ${p}`),l=(r.partialMasters??[]).filter(f=>f.objectApiName===c.objectApiName);i.push(` ${c.objectApiName}: ${c.kept} of ${c.sourceRows} (${sR(c,r.whole)})`+(u.length>0?`; left by the cap of ${r.children} children a record, by the lookup naming their parent: ${u.join(", ")}`:"")+l.map(f=>`; ${nR(f)}`).join(""))}if(i.push(...aR(r,t)),r.whole.length>0&&i.push(`whole: ${r.whole.map(({objectApiName:c,why:u})=>`${c} (${dm[u]})`).join(", ")}`),r.newestByIds&&r.newestByIds.length>0&&i.push(`newest by the order of their ids, the org sorting none of their creation dates \u2014 ids follow it within a load only: ${r.newestByIds.join(", ")}`),r.oldestByIds&&r.oldestByIds.length>0&&i.push(`oldest by the order of their ids, the org sorting none of their creation dates \u2014 ids follow it within a load only: ${r.oldestByIds.join(", ")}`),r.heavyRoots.length>0){i.push(`heavy roots set aside, each bringing in more than a tenth of the room ${n} has:`);for(let{objectApiName:c,id:u,rows:l,relation:f}of r.heavyRoots)i.push(` ${c} ${u}: ${l} record(s) through ${f.objectApiName}.${f.field}`)}if(r.dropped.length>0){i.push("not in the sample, never sent:");for(let{objectApiName:c,rows:u,reason:l}of r.dropped)i.push(` ${c}: ${u}, ${oR(l,t,n)}`)}if(r.leftEmpty.length>0){i.push("left empty, their record outside the sample:");for(let{objectApiName:c,field:u,rows:l}of r.leftEmpty)i.push(` ${c}.${u}: ${l} record(s)`)}if(r.noRecordDrawn.length>0){i.push(`no record drawn, ${t} holding some:`);for(let{objectApiName:c,sourceRows:u,noRootInTheDraw:l}of r.noRecordDrawn)i.push(` ${c}: ${u} in ${t}`+(l?", none of its roots in the draw":""))}let{plan:a}=r,d=a.drawnBy==="run"?"by this run":e.dryRun?e.replayed===!0?"by a dry run, said again by this one (--fit-plan)":"by this dry run":"by a dry run, written by this run (--fit-plan)";return i.push(`sample plan: ${a.path} (sha256 ${a.sha256}, drawn ${a.drawnAt} ${d})`,` drawing it sent ${r.planRequests.source} request(s) to ${t}`+(e.dryRun&&a.drawnBy==="dryRun"?`; --fit-plan ${a.path} writes these records, within a day`:"")),i}function Mg(r){let{budget:e,plan:t}=r;return{seed:r.seed,draw:r.draw,share:r.share,floor:r.floor,parents:r.parents,children:r.children,budget:{bytes:ic(e)?e.bytes:null,...e.remainingMB!==void 0?{remainingMB:e.remainingMB}:{},...e.maxMB!==void 0?{maxMB:e.maxMB}:{},...e.share!==void 0?{share:e.share}:{},...e.roundingMB!==void 0?{roundingMB:e.roundingMB}:{},...e.automationMB!==void 0?{automationMB:e.automationMB}:{},...e.withinMB!==void 0?{withinMB:e.withinMB}:{},...e.maxTotal!==void 0?{maxTotal:e.maxTotal}:{},limitedBy:e.limitedBy},rows:r.rows,storageBytes:r.storageBytes,objects:r.objects.map(n=>({objectApiName:n.objectApiName,sourceRows:n.sourceRows,kept:n.kept,roots:n.roots,below:n.below,asParents:n.asParents,...n.whole?{whole:!0}:{},...n.childrenCut&&n.childrenCut.length>0?{childrenCut:n.childrenCut.map(({field:o,rows:s})=>({field:o,rows:s}))}:{},...n.rootsInTheSource!==void 0?{rootsInTheSource:n.rootsInTheSource}:{},...n.rootsInTheDraw!==void 0?{rootsInTheDraw:n.rootsInTheDraw}:{}})),whole:r.whole.map(({objectApiName:n,why:o})=>({objectApiName:n,why:o})),heavyRoots:r.heavyRoots.map(({objectApiName:n,id:o,rows:s,relation:i})=>({objectApiName:n,id:o,rows:s,relation:{objectApiName:i.objectApiName,field:i.field}})),dropped:r.dropped.map(({objectApiName:n,rows:o,reason:s})=>({objectApiName:n,rows:o,reason:s})),leftEmpty:r.leftEmpty.map(({objectApiName:n,field:o,rows:s})=>({objectApiName:n,field:o,rows:s})),noRecordDrawn:r.noRecordDrawn.map(({objectApiName:n,sourceRows:o,noRootInTheDraw:s})=>({objectApiName:n,sourceRows:o,...s?{noRootInTheDraw:!0}:{}})),...r.roots?{roots:{...r.roots.window?{window:{...r.roots.window}}:{},...r.roots.notWindowed?{notWindowed:[...r.roots.notWindowed]}:{},...r.roots.where?{where:r.roots.where.map(({objectApiName:n,where:o})=>({objectApiName:n,where:o}))}:{},...r.roots.strata?{strata:r.roots.strata.map(({objectApiName:n,field:o,values:s,more:i})=>({objectApiName:n,field:o,values:s.map(a=>({...a})),...i!==void 0?{more:i}:{}}))}:{}}}:{},partialMasters:(r.partialMasters??[]).map(n=>({...n})),...r.newestByIds&&r.newestByIds.length>0?{newestByIds:[...r.newestByIds]}:{},...r.oldestByIds&&r.oldestByIds.length>0?{oldestByIds:[...r.oldestByIds]}:{},planRequests:{source:r.planRequests.source},plan:{path:t.path,sha256:t.sha256,drawnAt:t.drawnAt,drawnBy:t.drawnBy,...t.drawnAgain?{drawnAgain:t.drawnAgain}:{}}}}function cR(r){return{seed:r.seed,draw:r.draw,share:r.share,sha256:r.sha256,drawnAt:r.drawnAt,...r.roots?{roots:structuredClone(r.roots)}:{},objects:r.objects.map(e=>({objectApiName:e.objectApiName,sourceRows:e.sourceRows,kept:e.kept,roots:e.roots,below:e.below,asParents:e.asParents,...e.whole?{whole:!0}:{},written:e.written,goneSinceTheSample:e.goneSinceTheSample,changedSinceTheSample:e.changedSinceTheSample})),...r.leftEmpty&&r.leftEmpty.length>0?{leftEmpty:r.leftEmpty.map(({objectApiName:e,field:t,rows:n})=>({objectApiName:e,field:t,rows:n}))}:{}}}function uR(r,e){let t=r.roots,n=t?[...t.window?[sm(t.window)]:[],...t.whereObjects&&t.whereObjects.length>0?[`the roots of ${t.whereObjects.join(", ")} filtered`]:[],...t.strataFields&&t.strataFields.length>0?[`stratified by ${t.strataFields.join(", ")}`]:[]]:[],o=t?.window!==void 0||(t?.whereObjects??[]).length>0?"in the draw ":"",s=[`sample (${[ac(r),...n].join("; ")}, ${Ys(r.share)} % of the roots ${o}of each object; plan sha256 ${r.sha256}, drawn ${r.drawnAt}):`];for(let i of r.objects){let a=i.whole?"copied whole":`${i.roots} drawn, ${i.below} under a parent, ${i.asParents} as parents`;s.push(` ${i.objectApiName}: ${i.written} written of ${i.kept} in the sample (${a}) of ${i.sourceRows} in ${e}`+(i.goneSinceTheSample>0?`; ${i.goneSinceTheSample} gone from ${e} since the sample, not written`:"")+(i.changedSinceTheSample>0?`; ${i.changedSinceTheSample} changed since the sample: a record they cannot be written without is no longer the one the plan named, held back (failed)`:""))}for(let{objectApiName:i,field:a,rows:d}of r.leftEmpty??[])s.push(` left empty, their record outside the sample: ${i}.${a} ${d}`);return s}function lR(r,e,t){let n=e.draw??Rn.draw,o=e.maxTotal??er,s=new Set(Object.keys(e.rootWhere??{}).map(l=>l.toLowerCase())),i=l=>e.window!==void 0||s.has(l.toLowerCase()),a=0;for(let l of r.nodes){if(!l.included||l.recordCount<=0)continue;let f=n==="uniform"?l.recordCount:Math.min(l.recordCount,o);a+=1+(i(l.objectApiName)?1:0)+Math.ceil(f/fR)}let d=n==="uniform"?"every root's id, spread over the org":`the ${n==="recent"?"newest":"oldest"} by creation date, those it may keep`,c=e.window!==void 0||s.size>0,u=n!=="uniform"&&(e.strata??[]).length>0;return Xr(`sample: drawing it reads at most about ${a} request(s) of ${t} for the roots, by discovery's counts (${d}`+(c?"; of the roots --fit-window and --fit-where leave, fewer than discovery's counts, each object they hold counted again without them":"")+")"+(u?", and a statement per value of each stratum, said once they are counted":"")+"; the records they reach and name are read on top, and said once drawn")}var fR=2e3,pR={counting:"counting the roots of each object",drawing:"reading the ids of the roots",closing:"closing the sample over the records they reach and name",fitting:"cutting it to what the target may take",saving:"keeping its plan"};function hR(r){let e;return t=>{t.step!==e&&(e=t.step,r(`sampling: ${pR[t.step]}\u2026 (${t.requests} request(s) so far)`))}}var gR=new Set([wf,us,"SAMPLE_DRAW_INVALID","ROOTS_QUERY_REFUSED","ROOTS_PLAN_MISMATCH","ROOTS_PLAN_GONE"]);function Bg(r){return gR.has(r)?2:1}function mR(r){let e=0,t=0,n=0,o=0;for(let s of r.nodes)s.included?e++:$r(s)?t++:s.status==="error"||s.errors.length>0?n++:o++;return{included:e,emptyTables:t,notCounted:n,leftOut:o}}function cm(r){let e=[],t=[];for(let n of r.nodes)n.included&&n.recordCountUnknown===!0?t.push(n.objectApiName):!n.included&&!$r(n)&&(n.status==="error"||n.errors.length>0)&&e.push(n.objectApiName);return{refused:e,unanswered:t}}function Ls(r,e){let{refused:t,unanswered:n}=cm(r);return{nodes:r.nodes.length,...mR(r),...t.length>0?{notCountedObjects:t}:{},...n.length>0?{uncountedObjects:n}:{},edges:r.edges.length,waves:e.waves.length,cycles:e.cycleResolutions.length,truncated:r.truncated??!1}}function wR(r){return[...r.nodes].sort((e,t)=>e.objectApiName.localeCompare(t.objectApiName)).map(e=>({objectApiName:e.objectApiName,recordCount:e.recordCount,depth:e.level,included:e.included}))}function Lg(r,e,t,n,o={}){let s=yR(r,e,o);return{...s?{roots:s}:{rootRecordId:r.record},rootObjectApiName:s?.objectApiName??e.nodes[0]?.objectApiName??"",dryRun:r.dryRun,recordTypeMappings:t,maxRecordsPerObject:r.maxRecordsPerObject,referenceFallback:"nullify",upsertMode:r.upsert?"auto":void 0,expandOrphanParents:r.expandOrphans,...r.maxOrphans!==void 0?{maxOrphanParentExpansions:r.maxOrphans}:{},fieldExclusions:Object.keys(r.fieldExclusions).length>0?r.fieldExclusions:void 0,excludedObjects:r.excludedObjects.length>0?r.excludedObjects:void 0,ownerMappings:Object.keys(r.ownerMappings).length>0?r.ownerMappings:void 0,objectSoqlFilters:Object.keys(r.objectSoqlFilters).length>0?r.objectSoqlFilters:void 0,fieldMappings:Object.keys(r.fieldMappings).length>0?r.fieldMappings:void 0,anonymization:Rs(r.anonymize,e,r.anonymizationRules,n),keepContactPoints:r.keepContactPoints,decisions:r.decisions,files:r.files?{maxFileBytes:r.files.maxFileSizeMB*1048576,acceptedAsIs:r.files.acceptedAsIs}:void 0,stream:{ceiling:r.readCeiling,...r.pageSize!==void 0?{pageSize:r.pageSize}:{}}}}function yR(r,e,t={}){let n=r.roots;return n?{objectApiName:(e.nodes.find(s=>s.level===0)??e.nodes[0])?.objectApiName??n.query?.objectApiName??"",...n.query?{query:{...n.query.roots}}:{ids:[...n.ids??[]]},cap:n.cap,...n.readTotal!==void 0?{readTotal:n.readTotal}:{},...t.sourceRequestsLeft!==void 0?{sourceRequestsLeft:t.sourceRequestsLeft}:{},...t.plan?{plan:t.plan}:{},...t.keepAt!==void 0?{keepAt:t.keepAt}:{},...t.chosen&&n.query?{chosen:t.chosen}:{}}:void 0}async function bR(r,e,t){let n=r.roots?.query;if(!n||r.resume!==void 0||t||r.listObjects)return;let{objectApiName:o,roots:s}=n,i=r.roots?.cap??kr,a;try{a=await e(Qo(o,s,r.objectSoqlFilters[o],i))}catch{return}let d=[...new Set(a.flatMap(u=>typeof u.Id=="string"?[u.Id]:[]))],c=d.length>i?Br(o,i,"query",s):d.length===0?Xo(o,s,i):void 0;return c?{refused:{code:c.code,message:c.message}}:{chosen:{ids:d,readAt:new Date().toISOString()}}}function RR(r,e){return e?{...r,stream:{...r.stream,store:e,summaryBound:jp}}:r}function OR(r,e){if(!e)return r;let t=new Map(e.map(n=>[n.objectApiName,n.fieldNames]));return{...r,nodes:r.nodes.map(n=>{let o=t.get(n.objectApiName);if(!o)return n;let s=new Set(n.piiFields);return{...n,anonymizeFields:o.filter(i=>s.has(i))}})}}function Xs(r){return new Zl({query:async(e,t)=>Bn({query:async n=>r.query(n),queryMore:async n=>r.queryMore(n)},t),toolingQuery:async(e,t)=>Bn({query:async n=>r.tooling.query(n),queryMore:async n=>r.tooling.queryMore(n)},t),toolingQueries:async(e,t)=>Xl(await r.request({method:"POST",url:"/tooling/composite",body:JSON.stringify(Yl(`/services/data/v${r.version}`,t)),headers:{"Content-Type":"application/json"}}),t.length),toolingRetrieves:(e,t)=>la(r)(t)})}function kR(r,e,t){let n=o=>{let s=r.get(o);if(!s)throw new Error(`No connection for ${o}`);return s};return new Jl({query:async(o,s)=>Bn({query:async i=>n(o).query(i),queryMore:async i=>n(o).queryMore(i)},s),toolingQuery:async(o,s)=>Bn({query:async i=>n(o).tooling.query(i),queryMore:async i=>n(o).tooling.queryMore(i)},s),describeFields:async(o,s)=>{let i=!t.has(`${o}::${s}`),a=await e(o,s);return{sent:i,createable:a.createable!==!1,fields:a.fields.map(ca)}},readDuplicateRules:async(o,s)=>{let i=await n(o).metadata.read("DuplicateRule",s);return Array.isArray(i)?i:[i]},readLimits:async o=>n(o).request({method:"GET",url:"/limits"}),toolingQueries:async(o,s)=>Vl(n(o))(s),toolingRetrieves:(o,s)=>la(n(o))(s)})}async function un(r){let t=(await r.query("SELECT Id, IsSandbox FROM Organization LIMIT 1")).records[0];if(typeof t?.Id!="string")throw new Error("The org gave no Organization record: whether it is a sandbox cannot be told.");if(t.IsSandbox===!0)return{id:t.Id,sandbox:!0};try{let o=(await r.query("SELECT OrganizationType FROM Organization LIMIT 1")).records[0]?.OrganizationType;return typeof o=="string"&&o!==""?{id:t.Id,sandbox:!1,edition:o}:{id:t.Id,sandbox:!1}}catch{return{id:t.Id,sandbox:!1}}}function Zr(r,e,t){if(e.sandbox||Cc(e.edition))return;let n=t==="clone"?"sandforge clone writes to sandboxes and Developer Edition orgs only. Nothing was written; --dry-run, which only reads, runs against it.":"sandforge clone removes records from sandboxes and Developer Edition orgs only. Nothing was deleted.",o=e.edition?`IsSandbox false, edition ${e.edition}`:"IsSandbox false, and no edition";return`${r} is a production org (its Organization record says ${o}): ${n}`}var SR={parent_refused:"a record it names was refused",beyond_a_call:"the records it needs are more, or deeper, than one call holds",call_budget:"the calls ran out before its turn"};function TR(r,e){let t=r.updates.reduce((n,o)=>n+o.updates,0);return[`rehearsal: ${r.sampled} of the ${r.rows} record(s) the run would create, created in ${e} and rolled back with each call`,...t>0?[` and ${t} update(s) the run makes after its inserts, each in the call that creates its record: ${r.updates.map(n=>`${n.objectApiName} ${n.updates}`).join(", ")}`]:[],` ${r.calls} composite call(s), ${r.maxCalls} at most if a call stops at a refused record`,...r.objects.map(({objectApiName:n,rows:o})=>` ${n.padEnd(40)} ${o}`)]}function AR(r,e,t={}){let n=r.updatesJudged>0?`; ${r.updatesJudged} update(s) judged, ${r.updatesPassed} would save, ${r.updatesJudged-r.updatesPassed} refused`:"",o=r.linked??0,s=o>0?`${o} linked to a record the target holds, `:"",i=[`rehearsed in ${e}: ${r.judged} judged, ${r.passed} would save, ${s}${r.judged-r.passed-o} refused, ${r.notJudged} not judged${n} (${r.calls} call(s), every write rolled back)`];for(let a of r.gaps){let d=typeof a.detail?.statusCode=="string"?a.detail.statusCode:a.value,c=a.field?`.${a.field}`:"",u=a.kind==="picklist_value_refused"&&a.value?` "${a.value}"`:"",l=a.recordType?` (record type ${a.recordType})`:"",f=a.detail?.rowsOfTheRun,p=typeof f=="number"&&f>a.rows?`, ${f} in the run`:"";if(a.kind==="rehearsal_update_refusal"){i.push(` refused on update ${a.objectApiName}${c}: ${d}, ${a.rows} update(s)${p} (the record goes in without what the update gives it)`);continue}let g=lo(a,t.lifted);if(g){i.push(` refused ${a.objectApiName}${c}: ${d}, ${a.rows} row(s)${p}, validation rule "${String(a.detail?.rule)}": the mute lifts it (${g.permission}, in ${g.permissionSet}), which the rehearsal ran without; a real run under it writes the row whole`);continue}i.push(` ${a.severity==="blocking"?"REFUSED":"refused"} ${a.objectApiName}${c}${u}${l}: ${d}, ${a.rows} row(s)${p}`+(a.detail?.writtenWithoutTheField===!0?" (a real run writes it again without the field)":"")+(a.detail?.linkedToTheRecordItNames===!0?" (a real run links it to the record the target holds)":""))}for(let{objectApiName:a,rows:d,reason:c}of r.notJudgedWhy)i.push(` not judged ${a}: ${d} row(s), ${SR[c]}`);return r.updatesNotRehearsed>0&&i.push(` not rehearsed: ${r.updatesNotRehearsed} of the ${r.updates} update(s) the run makes after its inserts`),i}function jR(r,e){return{...r,gaps:r.gaps.map(t=>{let n=lo(t,e);return n?{...t,detail:{...t.detail,liftedByPermission:n.permission,liftedByPermissionSet:n.permissionSet}}:t})}}var $R=new Set(["--remove","--target","--preview","--include-changed","--json","--accept-automation","--leave-undeletable","--sweep","--sweep-list","--sweep-late","--sweep-untied","--audit","--mute-automation","--sweep-user"]),vR=new Set(["--remove","--target","--audit","--sweep-user"]);function ER(r){let e=r.slice(2);(e.includes("-h")||e.includes("--help"))&&(process.stdout.write(oc),process.exit(0));let t=c=>{let u=e.indexOf(c),l=u>=0?e[u+1]:void 0;return l!==void 0&&!l.startsWith("--")?l:void 0},n=c=>e.includes(c);for(let c=0;c<e.length;c++){let u=e[c];if(vR.has(u)){e[c+1]!==void 0&&!e[c+1].startsWith("--")&&c++;continue}u==="--dry-run"&&(process.stderr.write(`--remove does not take --dry-run: a removal that did not read it would delete for real. --preview says what the removal would do, and writes nothing. Run with --help for usage.
845
- `),process.exit(2)),$R.has(u)||(process.stderr.write(`--remove takes --target, --preview, --include-changed, --accept-automation, --mute-automation, --leave-undeletable, --sweep, --sweep-late, --sweep-untied, --sweep-list, --sweep-user, --json and --audit, not "${u}". Run with --help for usage.
846
- `),process.exit(2))}let o=t("--remove"),s=t("--target");(!o||!s)&&(process.stderr.write(`--remove takes the file a run printed its --json summary to, and --target the org the run wrote to. Run with --help for usage.
847
- `),process.exit(2)),n("--sweep")&&n("--sweep-list")&&(process.stderr.write(`--sweep deletes and --sweep-list only lists: give one of them. Run with --help for usage.
848
- `),process.exit(2));let i=["--sweep-list",...n("--sweep")?[]:ym,"--audit"].filter(c=>n(c));n("--preview")&&i.length>0&&(process.stderr.write(`--preview writes nothing: give it without ${i.join(", ")}. Run with --help for usage.
849
- `),process.exit(2));let a=QR(e);"refusal"in a&&(process.stderr.write(`${a.refusal} Run with --help for usage.
850
- `),process.exit(2));let d=IR(t("--sweep-user"),n("--sweep-user"),{sweeps:n("--sweep")||n("--sweep-list")});return{summaryPath:o,target:s,includeChanged:n("--include-changed"),json:n("--json"),acceptAutomation:n("--accept-automation"),muteAutomation:n("--mute-automation"),leaveUndeletable:n("--leave-undeletable"),sweep:n("--sweep"),sweepList:n("--sweep-list"),...a,audit:sc(e),...n("--preview")?{preview:!0}:{},...d!==void 0?{sweepUser:d}:{}}}function IR(r,e,t){if(e)return t.sweeps||(process.stderr.write(`--sweep-user goes with --sweep or --sweep-list: it names the user the run wrote as, whose records the sweep looks for. Run with --help for usage.
851
- `),process.exit(2)),(r===void 0||!hr.test(r)||!r.startsWith("005"))&&(process.stderr.write(`--sweep-user takes the id of a user, 005 and 12 or 15 more letters and digits, not "${r??""}". Run with --help for usage.
852
- `),process.exit(2)),r}function Qd(r,e){if(!(r===void 0||e.kept||e.given)&&/user the run wrote as|different users/.test(r))return` --sweep-user <id> names the user the run wrote as, which its summary does not keep: "sf org display user --target-org ${e.target}" gives the id of the user sf signs in as, the one a run of this machine wrote as`}var lt=C.string().regex(hr,"not a Salesforce id"),Ds=C.iso.datetime(),Wg=C.object({objectApiName:C.string().regex(tt,"not an API name"),kind:C.enum(["flow","trigger","process","workflowRule"]),name:C.string().max(255)}),xR=C.object({silenced:C.array(Wg.extend({permission:C.string().max(255)})),stillRan:C.array(Wg.extend({why:C.enum(["noBypass","managedPackage","notRead","noPermissionSet"])}))});function CA(...r){for(let e of r)if(typeof e=="string"&&hr.test(e))return e}var um=C.object({tool:C.literal("sandforge-clone"),version:C.literal(1),source:C.string(),target:C.string().min(1),targetOrgId:lt.optional(),record:C.string().optional(),objects:C.array(C.object({objectApiName:C.string().regex(tt,"not an API name"),where:C.string().max(512).optional()})).max(2e3).optional(),wholeOrg:C.literal(!0).optional(),roots:C.object({objectApiName:C.string().regex(tt,"not an API name"),from:C.enum(["query","records"])}).optional().catch(void 0),dryRun:C.literal(!1),elapsedMs:C.number().transform(r=>Math.max(0,r)),finishedAt:Ds.optional(),journal:C.string().min(1).max(4096).optional(),part:C.number().int().nonnegative().optional(),result:C.object({remapInJournal:C.literal(!0).optional(),roots:C.object({read:C.number().int().nonnegative()}).optional().catch(void 0),remapTable:C.record(lt,lt),existingSourceIds:C.array(lt),updatedSourceIds:C.array(lt),createdByObject:C.array(C.object({objectApiName:C.string().regex(tt,"not an API name"),sourceIds:C.array(lt)})),withTheirRecordSourceIds:C.array(lt).optional(),unattributed:C.array(C.object({objectApiName:C.string().regex(tt,"not an API name"),ids:C.array(lt)})).optional(),writtenBetween:C.object({first:Ds,last:Ds}).optional(),mayHaveBeenWritten:C.array(C.object({objectApiName:C.string().regex(tt,"not an API name"),sourceIds:C.array(lt)})).optional(),runUserId:lt.optional()}),mutedAutomation:xR.optional().catch(void 0)});async function Yd(r,e,t,n=Lt(Pt())){let o=e.indexOf(`
853
- `),s=o>=0?e.slice(0,o):e;if(/^\{"run":/.test(s))return PR(r,t,n);let i=FR(e);if("refusal"in i)return i;let{journal:a,part:d}=i.summary,c=a!==void 0&&d!==void 0?await n.readAt(a,d):void 0;if(!c){if(!i.summary.result.remapInJournal)return i;let u=(i.summary.objects??[]).map(l=>l.objectApiName);return a===void 0||d===void 0?{refusal:"keeps the ids of its records in a journal it does not name. "+Dg(t,u)}:{refusal:`keeps the ids of its records in ${a}, which cannot be read. `+Dg(t,u)}}return{summary:{...i.summary,result:{...i.summary.result,remapTable:c.remap.table,existingSourceIds:c.remap.linked,updatedSourceIds:[],createdByObject:c.remap.createdByObject,...c.remap.withTheirRecord?{withTheirRecordSourceIds:c.remap.withTheirRecord}:{},...c.unattributed?{unattributed:c.unattributed}:{}}}}}function Dg(r,e=[]){let t=e.length>0?e.join(","):"<its objects>";return`Its records can no longer be removed or verified from here. A checkpoint taken before the run takes ${r} back: ${qt("checkpoint")} list --org ${r} names them, ${qt("checkpoint")} rewind --org ${r} --checkpoint <id> rewinds to one. Without one, ${qt("empty")} --target ${r} --objects ${t} --dry-run says what emptying its objects would delete: every record of them, not only the run's.`}async function PR(r,e,t){let n=await t.readAt(r,"all");if(!n)return{refusal:"is not the journal of a run."};let s=(await t.lastEndAt(r))?.at??Jg(r).mtime.toISOString(),i=Date.parse(s)-Date.parse(n.startedAt),a=n.resume?.startedWith,d=n.resume?.recordId??a?.config.recordId,c=n.roots??(a?.config.queryScope==="records"?{}:void 0),u=n.roots?.objectApiName??a?.graph.nodes.find(h=>h.level===0)?.objectApiName,l=c&&u!==void 0?{objectApiName:u,from:a?.config.inputMode==="soql"||n.roots?.query!==void 0?"query":"records"}:void 0,f=!d&&a?.config.inputMode==="org",p=!d&&!c&&a&&(a.config.inputMode==="soql"||f)?a.graph.nodes.filter(h=>h.included).map(({objectApiName:h})=>{let m=a.config.objectSoqlFilters?.[h];return m!==void 0?{objectApiName:h,where:m}:{objectApiName:h}}):void 0,g=um.safeParse({tool:"sandforge-clone",version:1,source:n.resume?.sourceOrgId??"",target:e,targetOrgId:n.targetOrgId,record:d??(p?void 0:""),...p?{objects:p}:{},...f?{wholeOrg:!0}:{},...l?{roots:l}:{},dryRun:!1,elapsedMs:Number.isFinite(i)&&i>0?i:0,finishedAt:s,journal:r,result:{...n.roots?{roots:{read:n.roots.ids.length}}:{},remapTable:n.remap.table,existingSourceIds:n.remap.linked,updatedSourceIds:[],createdByObject:n.remap.createdByObject,...n.remap.withTheirRecord?{withTheirRecordSourceIds:n.remap.withTheirRecord}:{},...n.runUserId?{runUserId:n.runUserId}:{},...n.unattributed?{unattributed:n.unattributed}:{}}});return g.success?{summary:g.data}:{refusal:`is a journal the command cannot take a run back from: ${g.error.issues.slice(0,5).map(m=>`${m.path.map(String).join(".")||"the journal"}: ${m.message}`).join("; ")}.`}}function FR(r){let e;try{e=JSON.parse(r)}catch(a){return{refusal:`is not JSON (${a instanceof Error?a.message:String(a)}).`}}let n=C.object({tool:C.literal("sandforge-clone"),dryRun:C.boolean()}).safeParse(e);if(!n.success)return{refusal:"is not a summary sandforge clone printed with --json."};if(n.data.dryRun)return{refusal:"is the summary of a dry run, which wrote nothing to the target: there is nothing of it to remove."};let o=ki(e,"sandforge-clone");if(o)return{refusal:Si(o)};if(!C.object({result:C.object({createdByObject:C.array(C.unknown())})}).safeParse(e).success)return{refusal:"does not say which records the run created (createdByObject): it was printed before the summary said so, and the records the run created cannot be told from those the target already held. sandforge cleanup remains for such a run."};let i=um.safeParse(e);return i.success?{summary:i.data}:{refusal:`is not a summary a removal can read: ${i.error.issues.slice(0,5).map(d=>`${d.path.map(String).join(".")||"the summary"}: ${d.message}`).join("; ")}.`}}function dc(r){let{result:e}=r,t=Bc({idRemapTable:e.remapTable,idRemapExisting:[...e.existingSourceIds,...e.updatedSourceIds],idRemapCreated:e.createdByObject});return $p(t,e.unattributed)}function lm(r){return`${Lc({idRemapTable:r.result.remapTable,idRemapExisting:r.result.existingSourceIds,idRemapCreated:r.result.createdByObject,idRemapWithTheirRecord:r.result.withTheirRecordSourceIds}).length+r.result.updatedSourceIds.length} record(s) the target already held, which the run linked to or wrote over, stay`}function NR(r,e,t){let n=e.reduce((s,i)=>s+i.ids.length,0),o=r.result.writtenBetween?.last??r.finishedAt;return[`the clone of ${Ny(Fy(r))} wrote to ${t.target}${o?` until ${o}`:""}; a removal deletes the ${n} record(s) it created, children first:`,...e.map(s=>` ${s.objectApiName}: ${s.ids.length}`),...MR(e),lm(r),t.includeChanged?"records changed since the run go too, and what was added to them since":`records changed since the run stay, as do those records added since depend on (${at("--include-changed","removal")} takes them)`]}function CR(r){return r.flatMap(({part:e,plan:t})=>[`then the ${Wn(t).length} record(s) of the run's part ${e.part} (its summary's "part") an earlier --remove of that part left, once these are gone:`,...t.map(n=>` ${n.objectApiName}: ${n.ids.length}`)])}function MR(r){let e=new Set(r.filter(n=>n.ids.length>0).map(n=>n.objectApiName)),t=e.has("QuoteLineItem")||e.has("OpportunityLineItem");return!e.has("Quote")||!t?[]:[" and the lines the platform copied between a quote the run synced and its opportunity, read as the removal begins and counted apart (--preview counts them)"]}function fm(r){let e=r.platformCopies??0;if(e<=0)return"";let t=r.planned-e;return r.objectApiName===_o?` (${t>0?`${t} the run wrote, and `:""}${e} the target's duplicate rules made of the run's records)`:` (${t} the run wrote, and ${e} the platform copied between the quote the run synced and its opportunity)`}function BR(r,e="run"){let t=r.tookAlong,n=r.cameAlong;return[...t&&t.count>0?[` took along ${t.count} record(s) that were not the ${e}'s, added or changed since it: ${t.objects.join(", ")}`]:[],...n&&n.count>0?[` took along ${n.count} record(s) the ${e} did not write that came with its records, made as it wrote: ${n.objects.join(", ")}`]:[]]}function LR(r){return[r.deleted>0?`${r.deleted} deleted`:"",r.alreadyGone>0?`${r.alreadyGone} already gone`:"",(r.notVisible??0)>0?`${r.notVisible} not visible to this user (neither found nor in the recycle bin)`:"",r.keptChanged>0?`${r.keptChanged} kept, changed since the run`:"",r.keptDependents>0?`${r.keptDependents} kept for records that stay`+(r.heldBy.length>0?` (${r.heldBy.join(", ")})`:""):"",r.refused>0?`${r.refused} refused`:"",(r.notReached??0)>0?`${r.notReached} not reached`:""].filter(Boolean).join(", ")}function WR(r){let e=r.count>r.names.length?", \u2026":"";return`${r.count} file(s) attached to them stay in the org, as the run did not create them: ${r.names.join(", ")}${e}`}function DR(r,e,t=0){let n=[...new Set(e.flatMap(o=>o.unchecked))];return[`removal: ${r.toUpperCase()}`,...e.flatMap(o=>[` ${o.objectApiName}: ${LR(o)||"nothing"} of ${o.planned}${fm(o)}`,...BR(o),...o.reasons.map(s=>` ${s}`),...o.filesLeft&&o.filesLeft.count>0?[` ${WR(o.filesLeft)}`]:[]]),...n.length>0?[`not checked, deleted with their parent: ${n.join(", ")}`]:[],...t>0?[`not reachable: ${t} record(s) a call of the run may have written before its answer was lost may be in the org, under ids the run never learned`]:[]]}function pm(r){let e=r.automationGaps;return e?[...e.error?[` the target's automation could not all be read (${e.error}): what it creates may be missed`]:[],...e.flowsNotRead>0?[` ${e.flowsNotRead} flow(s) on the run's objects not read: what they create is not looked at`]:[],...e.triggers>0?[` ${e.triggers} Apex trigger(s) on the run's objects: what they create no metadata says`]:[]]:[]}function hm(r){return[...r.unread.map(e=>` not looked at: ${e.objectApiName}: ${e.reason}`),...r.handWork.map(e=>` created by the run's user in the window, where neither the run nor its automation writes: ${e.objectApiName}: ${e.count} (left)`)]}var _g=10;function cc(r,e,t=!1){return St("--max-total")?`The run would write ${r} records, more than --max-total ${e}: narrow the clone (--max, --exclude-object, --filter), or raise --max-total.`:ws()?t&&Kt()?`The run would write ${r} records, more than the ${e} the resource's maxTotal holds it to: narrow the resource in the file, or raise its maxTotal.`:`The run would write ${r} records, more than the ${e} its plan counted: the source holds more records than when it was planned. Plan again.`:`The run would write ${r} records, more than the ${e} ${at("--max-total")} holds it to: narrow the clone with this script's own --max, --exclude-object or --filter, or raise its --max-total.`}function ln(r){return St(r)?r:`this script's own removal with ${r==="--sweep-list"||r==="--sweep"?"":"--sweep "}${r}`}function Xd(r){let e=Ba();return e===void 0?`${r} takes them`:`${e} keeps them; ${ln(r)} takes them`}function zs(r){let e=r.length-_g;return`${r.slice(0,_g).join(", ")}${e>0?` and ${e} more`:""}`}function qn(r){return r.map(e=>`${e.objectApiName}: ${e.count}`).join(", ")}function _R(r,e){let t=r.changed??0;return[r.made>0?`${r.made} made for the run`+((r.sameSave??0)>0?` (${r.sameSave} in the same save)`:""):"",r.madeOver>0?`${r.madeOver} under records the run wrote over`:"",r.late>0?`${r.late} late`:"",r.untied>0?`${r.untied} tied to nothing of the run`:"",t>0?`${t} of them changed since the run${e.includeChanged===!0?"":", kept"}`:""].filter(Boolean).join(", ")}function Qr(r,e,t){return r[e]-(t.includeChanged===!0?0:r.changedIn?.[e]??0)}function qR(r,e){let t=e.sweepUntied===!0&&r.untied?.refusal===void 0;return r.found.reduce((n,o)=>{let s=o.classes;return s?n+Qr(s,"made",e)+Qr(s,"madeOver",e)+(e.sweepLate===!0?Qr(s,"late",e):0)+(t?Qr(s,"untied",e):0):n},0)}function qg(r,e,t,n){return t.flatMap(o=>{let s=r.found.find(a=>a.objectApiName===o.objectApiName)?.classes,i=s?Math.min(o.count,Qr(s,e,n)):o.count;return i>0?[{objectApiName:o.objectApiName,count:i}]:[]})}function UR(r,e,t){let n=[],o=r.late??[];if(o.length>0&&e.sweepLate!==!0)n.push(`kept, made late \u2014 tied to the run but created more than a minute after the record it hangs from, or by the org's Automated Process user: ${qn(o)} (${Xd("--sweep-late")})`);else if(t&&e.sweepLate===!0){let i=qg(r,"late",o,e);n.push("of what it would delete, made late, which --sweep-late takes: "+(i.length>0?qn(i):o.length>0?"none":"none found"))}let s=r.untied;if(s&&s.objects.length>0){if(s.refusal!==void 0)n.push(`kept, tied to nothing of the run: ${qn(s.objects)} \u2014 --sweep-untied is refused: ${s.refusal}`);else if(e.sweepUntied!==!0)n.push(`kept, created as the run's user in its window but tied to nothing of it: ${qn(s.objects)} (${Xd("--sweep-untied")})`);else if(t){let i=qg(r,"untied",s.objects,e);n.push("of what it would delete, tied to nothing of the run, which --sweep-untied takes: "+(i.length>0?qn(i):"none"))}}else t&&e.sweepUntied===!0&&n.push(s?.refusal!==void 0?`with --sweep-untied, it would delete nothing tied to nothing of the run: --sweep-untied is refused: ${s.refusal}`:"of what it would delete, tied to nothing of the run, which --sweep-untied takes: none found");if(r.notLooked&&r.notLooked.length>0&&n.push(`not looked at, past the ${Za} objects a sweep counts: `+zs(r.notLooked)),r.muted){let{silenced:i,stillRan:a}=r.muted;n.push(`the run's mute kept ${i.length} automation(s) quiet; `+(a.length>0?`what still ran may have made what is listed: ${zs(a.map(d=>`${d.name} (${d.objectApiName})`))}`:"nothing of what the run fired still ran"))}return t&&n.push(...GR(r,e)),n}function GR(r,e){let t=s=>r.found.some(i=>!i.overBound&&(i.classes?.[s]??0)>0),n=t("made")||t("madeOver"),o=[n?gm:"",e.sweepLate===!0&&t("late")?`under ${n?"them":"the run's records"} within a quarter of an hour with --sweep-late`:"",e.sweepUntied===!0&&r.untied?.refusal===void 0&&t("untied")?"anywhere in the run's window with --sweep-untied":""].filter(Boolean);return o.length===0?[]:[`${mm(`${o.join(", or ")}${o.length>1?",":""}`)}: check the names before a --sweep`]}var gm="under the run's records within a minute of them";function mm(r){return`a record made by hand as the run's user ${r} reads as the automation's, and one changed by hand before the run's last write as unchanged`}function _s(r,e,t,n=t===void 0){let o=qR(r,t??{}),s=r.found.reduce((a,d)=>a+d.count,0),i=r.found.some(a=>a.overBound)?" or more":"";return[r.window?`a sweep looks in ${e} for what the run's user created from ${r.window.from} to ${r.window.to} that the run's id map does not hold, in: ${zs(r.looked)}`:`a sweep of ${e} cannot tell the window the run wrote in`,...r.found.length>0?[`it found ${s}${i} record(s) and would delete `+(o>0?`${o} of them, children first`:"none of them")+"; per object, all it found:",...r.found.map(a=>` ${a.objectApiName}: ${a.count}`+(a.overBound?" or more (over the bound: none would be deleted)":"")+(a.classes?` \u2014 ${_R(a.classes,t??{})}`:"")+(a.names.length>0?` (${a.names.join(", ")}${a.count>a.names.length?", \u2026":""})`:""))]:r.window?["it finds nothing to delete"]:[],...UR(r,t??{},n),...pm(r),...hm(r),...r.refusal?[`sweep refused: ${r.refusal}`]:[]]}function zR(r,e){let t=r?.listing;return e===void 0&&t?.refusal===void 0?t:void 0}function Gd(r,e){let t=r.reduce((h,m)=>h+(m.heldByAutomation??0),0);if(t===0)return[];let n=Math.min(t,r.reduce((h,m)=>h+(m.heldByAutomationAfterRun??0),0)),o=Math.min(t,r.reduce((h,m)=>h+(m.heldByAutomationAlong??0),0)),s=HR(t,o),i=[...new Set(r.flatMap(h=>h.automationHolders??[]))],a=i.length>0?` (${zs(i)})`:"",d=`likely by the target's automation${a}`,c=`delete them by hand, then remove the run again; ${at("--preview","removal")} says what of it their delete leaves changed since, which ${at("--include-changed","removal")} takes`;if(e.part===void 0&&e.sweep!==!0&&e.windowUntold===!0)return[`${t} record(s) of the run kept for records created under them as its user, within a minute of them, ${d}: a sweep cannot take them, as it cannot tell the window the run wrote in now \u2014 ${c}`];let u=e.part!==void 0?"that part's last write":e.inParts===!0?"the last write of the run's part that wrote them":"the run's last write",l=n===0?"during the run, as its user":n===t?`as its user after ${u}, within a minute of them`:`as its user during the run or, under ${n} of them, after ${u}, within a minute of them`,f=e.part===void 0?"of the run":`of the run's part ${e.part} (its summary's "part")`,p=`${t} record(s) ${f} kept for records created under them ${l}, `+(n===0?d:`by the target's automation or by hand${a}`),g=mm(gm);if(e.part!==void 0){let h=m=>`${Ba()===void 0?"--remove":"this script's own removal"} of part ${e.part}'s summary with ${m}`;return[`${p}: `+(e.sweep===!0?"this removal's sweep looked in its own part's window alone, and did not see them; ":"a sweep of this summary looks in its own part's window alone, and leaves them; ")+`${h("--sweep")} ${s} (${h("--sweep-list")} shows them; ${g}: check the names before it), or ${c}`]}return[e.sweep===!0?`${p}: the sweep left them \u2014 ${ln("--sweep-list")} says why; ${ln("--sweep-late")} takes those it lists as late, ${at("--include-changed","removal")} those changed after the run's last write`:`${p}: ${ln("--sweep")} ${s} (${ln("--sweep-list")} shows them); ${g}: check the names before `+(St("--sweep")?"a --sweep":ln("--sweep"))]}function HR(r,e){let t="the removal deletes those, and the org takes them along";return e<=0?"takes them first":e>=r?`takes them with the run's records they hang from: ${t}`:`takes them first, but for those under ${e} of the run's records, which go with them: ${t}`}var wm={late:"made late",untied:"tied to nothing of the run"};function KR(r){return r.map(({class:e,objects:t,option:n,refusal:o})=>{let s=` left, ${wm[e]}: ${qn(t)}`;return o!==void 0?`${s} \u2014 ${n} is refused: ${o}`:`${s} (${Xd(n)})`})}function VR(r){return[`sweep: ${r.status.toUpperCase()}`,...r.objects.flatMap(e=>{let t=e.afterRemoval??0,n=Math.min(e.afterRemovalUnder??0,t),o=e.withRemoval??0,s=[t-n>0?`${t-n} once the records of the run that point at them were gone`:"",n>0?`${n} once the removal was through: the org had not taken them along with the records of the run they hung from`:""].filter(Boolean),i=[e.deleted>0?`${e.deleted} deleted`+(s.length>0?` (${s.join("; ")})`:""):"",e.alreadyGone>0?`${e.alreadyGone} already gone`+(o>0?` (${o} with the records of the run they hung from, as the removal deleted those: the org took them along)`:""):"",e.keptChanged>0?`${e.keptChanged} kept, changed since the run`:"",(e.keptDependents??0)>0?`${e.keptDependents} kept for records that stay`+((e.heldBy??[]).length>0?` (${(e.heldBy??[]).join(", ")})`:""):"",e.refused>0?`${e.refused} refused`:""].filter(Boolean).join(", ");return[` ${e.objectApiName}: ${i||"nothing"} of ${e.found}`,...e.reasons.map(a=>` ${a}`)]}),...KR(r.left??[]),...(r.goneAlong??[]).map(({class:e,objects:t})=>` ${wm[e]}, no longer in the org once the records of the run were gone: ${qn(t)}`),...pm(r),...hm(r),...r.refusal?[` ${r.refusal}`]:[]]}function JR(r){return Zs(r).flatMap(e=>[...Wn(e.created),...e.linked])}function Zs(r){let e=r?.part;return e===void 0?[]:(r?.parts??[]).filter(t=>t.part!==e)}function qs(r,e){let t=new Set(r?.earlier?.partsRemoved??[]);return Zs(r).flatMap(n=>{let o=(e?.otherParts??[]).filter(({part:i})=>i===n.part).flatMap(({objects:i})=>i).reduce((i,a)=>i+a.count,0),s=Wn(sn(n.created,r?.earlier?.removalLeft)).length+o;return s===0?[]:[`a sweep of this summary leaves the ${s} record(s) of the run's part ${n.part} (its summary's "part"), the run's own, never the target's automation's: `+(t.has(n.part)?"an earlier --remove of that part left them, which the removal of this summary takes up once its own records are gone":"--remove of that part's summary takes them")]})}async function Zd(r,e,t,n,o,{signal:s,ofTheRun:i,user:a}={}){let d;try{d=await Xs(r).read(e,n.map(l=>l.objectApiName))}catch(l){d={error:V(l)}}let c=t.result.runUserId??a,u=Zs(i).map(({part:l,created:f})=>({part:l,created:f}));return{writtenBetween:t.result.writtenBetween,created:n,remap:new Set([...Object.values(t.result.remapTable),...JR(i)].map(l=>l.slice(0,15))),...u.length>0?{otherParts:u}:{},automation:Hp(d),...c?{runUserId:c}:{},ties:o,...s?{signal:s}:{}}}var ym=["--sweep-late","--sweep-untied"];function QR(r){let e=ym.filter(t=>r.includes(t));return e.length>0&&!r.includes("--sweep")&&!r.includes("--sweep-list")?{refusal:`${e.join(" and ")} ${e.length===1?"takes":"take"} more of what --sweep lists: give ${e.length===1?"it":"them"} with --sweep, or with --sweep-list to see what ${e.length===1?"it":"they"} would take.`}:{...r.includes("--sweep-late")?{sweepLate:!0}:{},...r.includes("--sweep-untied")?{sweepUntied:!0}:{}}}function YR(r){return{...r.sweepLate?{sweepLate:!0}:{},...r.sweepUntied?{sweepUntied:!0}:{}}}function XR(r){return r?{sweep:e=>r.first(e),automationMade:r.automationMade,afterRemoval:e=>r.afterRemoval(e)}:{}}function ec(r,e,t){let n=Yn(r,e),o=Object.create(n);return o.counts=Kp(dl(al(r),t)),o}function MA(r){let e=Date.parse(r.firstWrittenAt??r.startedAt),t=Date.parse(r.end?.at??r.lastWriteAt??r.lastWrittenAt??"");return Number.isFinite(e)&&Number.isFinite(t)?{from:e,to:Math.max(e,t)}:void 0}function zd(r,e){return r!==void 0&&r.length>=15&&r.slice(0,15)===e.slice(0,15)}async function ZR(r){let e=r.journalDir??Pt(),t=new Set(r.own.ids.map(c=>c.slice(0,15))),n=(c,u)=>!r.span||!Number.isFinite(c)||!Number.isFinite(u)||c<=r.span.to+zp&&u>=r.span.from-Gp,o=[],s=c=>{c.length===0||c.some(u=>t.has(u.slice(0,15)))||o.push({ids:[...c]})},i=Kd(e,"forge-runs"),a=[];try{a=py(i).filter(c=>c.endsWith(".ndjson"))}catch{}let d=Lt(e);for(let c of a){let u=Kd(i,c);if(!(r.own.journal!==void 0&&Wt(r.own.journal)===Wt(u)))try{let l=await d.headAt(u);if(!l||!zd(l.targetOrgId,r.organizationId))continue;let f=await d.lastEndAt(u),p=Date.parse(f?.at??"")||Jg(u).mtimeMs;if(!n(Date.parse(l.startedAt),p))continue;let g=await d.readAt(u,"all");s(g?.created.flatMap(h=>h.ids)??[])}catch{}}for(let c of r.own.otherParts??[])n(c.from,c.to)&&s(c.ids);for(let c of[Vi(e),Vi(e,Zp)]){let u=[];try{u=await c.list()}catch{continue}for(let l of u){if(r.own.runId!==void 0&&l.runId===r.own.runId||!(zd(l.targetOrganizationId,r.organizationId)||l.targetOrganizationId===void 0&&(zd(l.targetOrgId,r.organizationId)||r.alias!==void 0&&l.targetOrgId===r.alias)))continue;let p=Date.parse(l.firstWrittenAt??l.startedAt),g=l.end?Date.parse(l.end.at):Date.parse(l.lastWriteAt??l.lastWrittenAt??"")||Date.now();n(p,g)&&s([...l.created,...l.overwritten??[]].flatMap(h=>h.ids))}}return o}function eO(r){let e=r.removalSpans?.map(t=>t.first).filter(t=>Number.isFinite(Date.parse(t))).sort((t,n)=>Date.parse(t)-Date.parse(n))[0];return{otherRuns:r.otherRuns,...r.muted?{muted:{silenced:r.muted.silenced,stillRan:r.muted.stillRan}}:{},...e!==void 0?{removalBegan:e}:{},...r.made&&r.made.length>0?{madeEarlier:r.made}:{},...r.late&&r.late.length>0?{lateEarlier:r.late}:{}}}async function bm(r,e,t,n,o,s){let i=Date.parse(t.finishedAt??""),a=Zs(s).map(d=>({ids:Wn(d.created),from:Date.parse(d.startedAt??""),to:Date.parse(d.endedAt??"")}));return eO({otherRuns:await ZR({organizationId:r,alias:e,span:Number.isFinite(i)?{from:i-t.elapsedMs,to:i}:void 0,own:{...t.journal!==void 0?{journal:t.journal}:{},ids:n.flatMap(d=>d.ids),...a.length>0?{otherParts:a}:{}}}),...t.mutedAutomation?{muted:t.mutedAutomation}:{},...o?{removalSpans:o.removalSpans}:{},...o?.made?{made:o.made}:{},...o?.late?{late:o.late}:{}})}var Ug=3;function ei(r){return/\.json$/i.test(r)?r.replace(/\.json$/i,".removals.json"):`${r}.removals.json`}function ti(r){let e=r.flatMap(t=>t.ids.map(n=>n.slice(0,15))).sort();return fy("sha256").update(e.join(",")).digest("hex")}var Hd=C.string().refine(r=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:?\d{2})$/.test(r)&&Number.isFinite(Date.parse(r)),"not a date"),tO=C.object({tool:C.literal("sandforge-clone"),version:C.literal(1),run:C.string(),removalStamps:C.record(lt,Hd),removalSpans:C.array(C.object({first:Hd,last:Hd,userId:lt})),removalLeft:C.array(lt).optional(),sweep:C.object({sweptAt:Ds,deleted:C.number().int().nonnegative(),keptChanged:C.number().int().nonnegative(),refused:C.number().int().nonnegative()}).optional(),made:C.array(lt).max(1e4*100).optional(),late:C.array(lt).max(1e4*100).optional(),partsRemoved:C.array(C.number().int().nonnegative()).max(1e4).optional()});function ni(r,e){if(r===void 0)return{};let t;try{t=JSON.parse(r)}catch{}let n=C.object({tool:C.literal("sandforge-clone"),run:C.string()}).safeParse(t);if(!n.success)return{refusal:"is not the record of removals sandforge clone keeps there, and is not overwritten: move it, as the removal keeps there what it leaves on the records of the run."};if(n.data.run!==e)return{otherRun:!0};let o=tO.safeParse(t);if(!o.success)return{refusal:`is not a record of removals a removal can read: ${o.error.issues.slice(0,5).map(p=>`${p.path.map(String).join(".")||"the file"}: ${p.message}`).join("; ")}.`};let{removalStamps:s,removalSpans:i,removalLeft:a,sweep:d,made:c,late:u,partsRemoved:l}=o.data;return{earlier:{removalStamps:s,removalSpans:i,...a?{removalLeft:a}:{},...d?{sweep:d}:{},...c?{made:c}:{},...u?{late:u}:{},...l?{partsRemoved:l}:{}}}}function nO(r,e,t,n=[],o,s=[],i=[],a=[]){let d=new Set(t.gone??[]),c=[...a],u=zi(e?.made,s,c),l=zi(e?.late,i,c),f=u.join()!==(e?.made??[]).join()||l.join()!==(e?.late??[]).join();if(Object.keys(t.stamps).length===0&&!t.span&&d.size===0&&!o&&!f)return;let p=o??e?.sweep,g=d.size>0?n.flatMap(({ids:h})=>h.filter(m=>!d.has(m))):e?.removalLeft;return{tool:"sandforge-clone",version:1,run:r,removalStamps:{...e?.removalStamps,...t.stamps},removalSpans:[...e?.removalSpans??[],...t.span?[t.span]:[]],...g?{removalLeft:g}:{},...p?{sweep:p}:{},...u.length>0?{made:u}:{},...l.length>0?{late:l}:{},...e?.partsRemoved?{partsRemoved:e.partsRemoved}:{}}}async function Rm(r,e=Lt(Pt())){let t=r.journal;if(t===void 0||!Yt(t))return;let n=await uh(t,e),o=n.length>1?await e.readAt(t,"all"):void 0;if(!o)return;let s=ei(t),i;try{i=pn(s,"utf8")}catch(c){if(c?.code!=="ENOENT")return{refusal:`${s} cannot be read: ${c instanceof Error?c.message:String(c)}`}}let a=ti(o.created),d=ni(i,a);return"refusal"in d?{refusal:`${s} ${d.refusal}`}:{parts:n,...r.part!==void 0?{part:r.part}:{},file:s,key:a,created:o.created,...d.earlier?{earlier:d.earlier}:{}}}function Om(r){let e=new Set(r.earlier?.partsRemoved??[]);return r.parts.flatMap(t=>{if(t.part===r.part||!e.has(t.part))return[];let n=sn(t.created,r.earlier?.removalLeft);return n.length>0?[{part:t,plan:n}]:[]})}function km(r,e){if(!(r.parts.length<2))return[...r.parts].sort((t,n)=>n.part-t.part).flatMap(t=>{let n=sn(e,Wn(t.created));return n.length>0?[{part:t,plan:n}]:[]})}function rO(r,e){let t=[...new Set(e.flatMap(s=>s.keptDependents>0?s.heldBy:[]))],n=new Set(r.earlier?.partsRemoved??[]),o=s=>sn(s.created,r.earlier?.removalLeft).map(i=>i.objectApiName);return r.parts.flatMap(s=>{if(s.part===r.part||n.has(s.part))return[];let i=new Set(qo(o(s),r.parts.flatMap(d=>d.part===s.part?[]:o(d)))),a=t.filter(d=>i.has(d));return a.length>0?[{part:s.part,objects:a}]:[]})}function Gg(r){return r.map(({part:e,objects:t})=>`of what this removal kept for records that stay, what the run's part ${e} (its summary's "part") holds \u2014 its ${t.join(", ")} records \u2014 goes with --remove of that part's summary, once that part's own records are gone, without --include-changed`)}function Sm(r,e,t){return r.parts.flatMap(n=>{if(n.part===e)return[];let o=sn(n.created,r.earlier?.removalLeft),s=Ln(n);if(o.length===0||!s)return[];let i=ar(r.parts,n.part);return[{part:n.part,alongside:{plan:o,span:s,...Object.keys(t).length>0?{removalStamps:t}:{},...i.length>0?{laterParts:i}:{}}}]})}function Tm(r){return r?.part===void 0?[]:[...new Set(r.parts.flatMap(e=>e.part===r.part?[]:sn(e.created,r.earlier?.removalLeft).map(t=>t.objectApiName)))]}function oO(r,e){let t=r.earlier,n=[...new Set([...t?.partsRemoved??[],...e.parts])].sort((i,a)=>i-a);if(Object.keys(e.stamps).length===0&&e.spans.length===0&&e.gone.length===0&&n.length===(t?.partsRemoved?.length??0))return;let o=new Set(e.gone.map(i=>i.slice(0,15))),s=(t?.removalLeft??Wn(r.created)).filter(i=>!o.has(i.slice(0,15)));return{tool:"sandforge-clone",version:1,run:r.key,removalStamps:{...t?.removalStamps,...e.stamps},removalSpans:Nr(t?.removalSpans,e.spans),removalLeft:s,...t?.sweep?{sweep:t.sweep}:{},...t?.made?{made:t.made}:{},...t?.late?{late:t.late}:{},partsRemoved:n}}function sO(r){let e={};for(let o of r)for(let s of[...o.otherPartStamps??[],o.stamps])Object.assign(e,s);let n=r.flatMap(o=>o.span?[o.span]:[]).reduce((o,s)=>o?{...o,first:Date.parse(s.first)<Date.parse(o.first)?s.first:o.first,last:Date.parse(s.last)>Date.parse(o.last)?s.last:o.last}:s,void 0);return{stamps:e,...n?{span:n}:{},gone:r.flatMap(o=>o.gone)}}function Am(r,e){return e?{...r,removalStamps:{...r?.removalStamps,...e.removalStamps},removalSpans:Nr(r?.removalSpans,e.removalSpans)}:r}function tc(r,e){let t=`${r}.${process.pid}.tmp`;try{Qg(t,JSON.stringify(e,null,2)+`
854
- `,"utf8"),Vg(t,r);return}catch(n){try{Ws(t,{force:!0})}catch{}return n instanceof Error?n.message:String(n)}}async function iO(r=process.argv){let e={};try{await aO(r,e)}finally{e.lock?.release()}}async function aO(r,e){let t=Date.now(),n=ER(r),o=x=>n.json?console.error(x):console.log(x),s;try{s=pn(n.summaryPath,"utf8")}catch(x){process.stderr.write(`--remove ${n.summaryPath} cannot be read: ${x instanceof Error?x.message:String(x)}
855
- `),process.exit(2)}let i=await Yd(n.summaryPath,s,n.target);"refusal"in i&&(process.stderr.write(`--remove ${n.summaryPath} ${i.refusal}
856
- `),process.exit(2));let a=x=>({code:Ri,message:`${td(x)}. A removal now would delete under it what it goes on writing: ${nd(x)}, then remove it. Nothing was read or deleted.`}),d=i.summary.journal;if(n.preview){let x=d!==void 0?th(d):void 0;return x&&Tt(a(x)),lO(n,i.summary,o,t)}if(d!==void 0){let x=Ss(d,{journalId:rc(d).replace(/\.ndjson$/,""),ranFrom:"commandLine",target:n.target,removes:!0});"busy"in x&&Tt(a(x.busy)),e.lock=x.lock}let c,u=async()=>{if(!c){let x=await Fn(n.target),Y=On(x);c={session:x,conn:Y,org:await un(Y)}}return c},l=i.summary.journal;if(l!==void 0&&Yt(l)&&Lt(Pt()).callsInFlightAt(l)>0){let{conn:x,org:Y}=await u();i.summary.targetOrgId!==void 0&&!Ks(i.summary.targetOrgId,Y.id)&&Tt(wt(i.summary.targetOrgId));let re=await Lt(Pt()).reconcileAt(l,za(x));for(let se of Ha(re,n.target,"removal"))o(se);let ve=(re.underway??[]).reduce((se,{rows:rt})=>se+rt,0),oe=Ap(re)-ve;oe>0&&o(` the journal names none of the ${oe} row(s) that may be in ${n.target}: they stay, and ${ln("--sweep-list")} shows what the run's user created in the run's window`),i=await Yd(n.summaryPath,pn(n.summaryPath,"utf8"),n.target),"refusal"in i&&(process.stderr.write(`--remove ${n.summaryPath} ${i.refusal}
857
- `),process.exit(2))}let{summary:f}=i;f.targetOrgId===void 0&&f.target!==n.target&&(process.stderr.write(`The run wrote to ${f.target}, and its records are removed from that org only: give --target ${f.target}.
858
- `),process.exit(2));let p=(f.result.mayHaveBeenWritten??[]).reduce((x,{sourceIds:Y})=>x+Y.length,0),g=0,h,m,R,b=[],k=!1,O=!1,w,A=x=>{let Y={sweep:n.sweep,windowUntold:k,inParts:O};return w?[...Gd(w.own,Y),...w.others.flatMap(({part:re,objects:ve})=>Gd(ve,{...Y,part:re}))]:Gd(x,Y)},S=(x,Y,re,ve,oe)=>{if(n.json){process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"remove",summary:n.summaryPath,target:n.target,...re?{targetOrgId:re}:{},includeChanged:n.includeChanged,result:{status:x,planned:Y.reduce((se,rt)=>se+rt.planned,0),objects:Y,...p>0?{mayHaveBeenWritten:p}:{},...g>0?{removedEarlier:g}:{},...oe?{sweep:oe}:{},...h?{sweepListing:h}:{},...zg(f,n)!==void 0?{wholeOrgNotSwept:!0}:{},...m?{mutedAutomation:m}:{},...b.length>0?{heldByOtherParts:b}:{}},...ve?{removalsFile:ve}:{},elapsedMs:Fe(t)},null,2)+`
859
- `);for(let se of A(Y))console.error(se);for(let se of Gg(b))console.error(se);return}if(Y.length>0||!oe)for(let se of DR(x,Y,p))console.log(se);if(oe)for(let se of VR(oe))console.log(se);for(let se of A(Y))console.log(se);for(let se of Gg(b))console.log(se);ve&&console.log(`what this removal left on the run's records is kept in ${ve}, which the next --remove of this summary reads`),console.log(`
860
- done in ${Fe(t)}ms`)},v=dc(f);if(v.length===0){o("The run created no record: there is nothing of it to remove."),S("success",[]);return}let j=ti(v),F=ei(n.summaryPath),B;try{B=pn(F,"utf8")}catch(x){x?.code!=="ENOENT"&&(process.stderr.write(`${F} cannot be read: ${x instanceof Error?x.message:String(x)}
861
- `),process.exit(2))}let E=ni(B,j);"refusal"in E&&(process.stderr.write(`${F} ${E.refusal}
862
- `),process.exit(2));let{otherRun:_,earlier:ee}=E,X=await Rm(f);X&&"refusal"in X&&(process.stderr.write(`${X.refusal}
863
- `),process.exit(2)),O=X!==void 0;let z=X&&Wt(F)!==Wt(X.file)?X:void 0,J=Am(ee,z?.earlier);o(`sandforge clone --remove ${n.summaryPath} from ${n.target}`);let Me=zg(f,n);Me!==void 0&&o(Me);let ke=go({objects:v,removalLeft:ee?.removalLeft}),ue=sn(ke,z?.earlier?.removalLeft),H=x=>x.reduce((Y,re)=>Y+re.ids.length,0);g=H(v)-H(ue),H(v)>H(ke)&&o(`${H(v)-H(ke)} record(s) removed by an earlier --remove of this summary`),H(ke)>H(ue)&&o(`${H(ke)-H(ue)} record(s) removed by an earlier --remove of the run's other part or of its journal`);let Q=z?Om(z):[],pe=X&&!("refusal"in X)&&!z?X:void 0,we=pe?km(pe,ue):void 0,Ee=n.includeChanged&&f.result.runUserId!==void 0;if(ue.length===0&&Q.length===0&&!n.sweep&&!n.sweepList&&!Ee){o("nothing left of the run to remove"),S("success",[]);return}let{session:ae,conn:D,org:L}=await u(),Re=new Map([[L.id,{alias:n.target,username:ae.username}]]),Ne=`sandforge-clone-${Us()}`,Ie,ge=x=>Gs(n.audit,Re,{action:"cleanup_delete",module:"forge",operationId:Ne,orgId:L.id,...x,...m?{muted:mo(m)}:{}}),K=n.sweepList?void 0:Zr(n.target,L,"remove");K&&ft({code:"PRODUCTION_TARGET",message:K}),f.targetOrgId!==void 0&&!Ks(f.targetOrgId,L.id)&&Tt(wt(f.targetOrgId));let te=f.result.writtenBetween===void 0?f:void 0;f=await Hs(D,f);let M=()=>bm(L.id,n.target,f,v,J,z);if(n.sweepList){let x=await ed(ec(D,"sandforge clone --sweep-list"),await Zd(D,n.target,f,v,await M(),{ofTheRun:z,...n.sweepUser!==void 0?{user:n.sweepUser}:{}}),J?.removalSpans??[]);for(let re of _s(x,n.target,n,!0))o(re);let Y=Qd(x.refusal,{kept:f.result.runUserId!==void 0,given:n.sweepUser!==void 0,target:n.target});Y!==void 0&&o(Y);for(let re of qs(z,x))o(re);n.json?process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"sweep-list",summary:n.summaryPath,target:n.target,targetOrgId:L.id,listing:x,elapsedMs:Fe(t)},null,2)+`
864
- `):console.log(`
865
- done in ${Fe(t)}ms`),x.refusal!==void 0&&process.exit(Ug);return}let q=f.result.runUserId,G=new AbortController,Te=()=>G.abort(),ie=ue.length>0||Q.length>0||Ee;ue.length>0||Q.length>0?Nt():o(Ee?"nothing left of the run's own records to remove: the duplicate record sets the target's rules made of them are read again, and taken changed since the run":"nothing left of the run to remove");let ne=n.sweep?Vp(ec(D,"sandforge clone --sweep",G.signal),await Zd(D,n.target,f,v,await M(),{signal:G.signal,ofTheRun:z,...n.sweepUser!==void 0?{user:n.sweepUser}:{}}),{includeChanged:n.includeChanged,removalSpans:J?.removalSpans??[],...YR(n),approve:async x=>{h=x,o("");for(let re of _s(x,n.target,n))o(re);let Y=Qd(x.refusal,{kept:f.result.runUserId!==void 0,given:n.sweepUser!==void 0,target:n.target});Y!==void 0&&o(Y);for(let re of qs(z,x))o(re)}}):void 0;if(ne){let x=Jn(Te);try{await ne.ask()}finally{x()}let Y=zR(ne,h);if(Y){h=Y,o("");for(let re of _s(Y,n.target,n))o(re);for(let re of qs(z,Y))o(re)}}let U=ne?.takes??[];(ie||U.length>0)&&!G.signal.aborted&&await nt(U);let Oe,ye=[];if(ie)Oe=await dt(),Oe.stoppedForUndeletable&&(R&&ft(R),process.exit(1));else if(ne){let x=await At(),Y=Jn(Te);try{await ne.first(),await ne.afterRemoval()}finally{if(Y(),x){m=await x.release();for(let re of Xn(m,n.target))o(re)}}}let le=ne?.result();le&&Gs(n.audit,Re,{action:"cleanup_delete",module:"forge",operationId:`${Ne}-sweep`,orgId:L.id,outcome:le.status==="refused"?"stopped":le.status,...le.status==="refused"?{code:"SWEEP_REFUSED"}:{},objects:Qp(le),details:Yp(le,j),...!ie&&m?{muted:mo(m)}:{}});function Nt(){for(let x of NR(f,ue,n))o(x);for(let x of CR(Q))o(x);ee?o(`what earlier removals of this summary left on the run's records, read from ${F}, is not a change since the run`):_&&o(`${F} is of another run: it is not read, and what this removal leaves on the records, if anything, takes its place`),z?.earlier&&o(`what the removals of the run's other part or of its journal left on its records, read from ${z.file}, is no change since the run`)}function ft(x){return ge({outcome:"stopped",code:x.code}),Tt(x)}function Tt(x){return process.stderr.write(`${kt(x)}
866
- `),n.json&&process.stdout.write(bo({tool:"sandforge-clone",summary:n.summaryPath,target:n.target,elapsedMs:Fe(t)},x)),process.exit(1)}function wt(x){return{code:yo,message:`${n.target} is not the org the run wrote to (${x}), and its records are removed from that org only. Nothing was deleted.`}}async function nt(x){let Y=[...new Set([...ue,...Q.flatMap(he=>he.plan)].map(he=>he.objectApiName))],re=[...new Set([...qo(Y,Tm(z),{userKept:q!==void 0}),...Y.length===0&&Ee?[_o]:[],...x])],ve=Gi(Y),oe=await Xs(D).read(n.target,re);o("");for(let he of va(oe,n.target,re.length,ve))o(he);if(n.muteAutomation){let he=new Set(ve);try{Ie=await Yi(async()=>Ji(D),oe,{writes:(qe,Ve)=>Ve==="delete"||Ve==="update"&&he.has(qe)}),m=Ie.muted;for(let qe of Xn(Ie.muted,n.target))o(` ${qe}`)}catch(qe){if(!Cr(qe))throw qe;ft(qe.refusal)}}let se=Ie?.automation??oe,rt=$a(se,n.target,{drafted:ve,assign:fs(se,bi(se,ve)),mayMute:Ie===void 0&&St("--mute-automation")});rt&&!n.acceptAutomation&&ft({code:"AUTOMATION_NOT_ACCEPTED",message:rt})}async function At(){let x=Ie?.prepared&&!G.signal.aborted?await Ie.prepared.acquire(`sandforge clone --remove ${Ne}`).catch(Y=>{if(!Cr(Y))throw Y;return ft(Y.refusal)}):void 0;return x&&(m=x.outcome),x}async function dt(){let x,Y=Jn(Te),re=f.result.writtenBetween,ve=re?{runStartedAt:new Date(re.first),runEndedAt:new Date(re.last)}:{runDurationMs:f.elapsedMs,...f.finishedAt?{runRecordedAt:new Date(f.finishedAt)}:{}},oe=Gu,se=[],rt=yg(n.leaveUndeletable,n.target,Je=>{R=Je}),[he,...qe]=we??[],Ve=z??(he?pe:void 0),bt=z?.part??he?.part.part,Zt=Ve&&bt!==void 0?Sm(Ve,bt,J?.removalStamps??{}):[],In=Ve&&bt!==void 0?ar(Ve.parts,bt):[];try{if(ue.length>0||Ee){let Xe=he?he.plan:ue;oe=await Fr(Yn(D,"sandforge clone --remove"),Xe,{...(he&&Ln(he.part))??ve,...J?{removalStamps:J.removalStamps,removalSpans:J.removalSpans}:{},...XR(ne),...q?{runUserId:q}:{},...In.length>0?{laterParts:In}:{},...Zt.length>0?{otherParts:Zt.map(Dt=>Dt.alongside)}:{},includeChanged:n.includeChanged,onUndeletable:rt,beforeFirstWrite:async()=>{x=await At()},signal:G.signal})}else x=await At();let Je={...J?.removalStamps,...oe.stamps};for(let Xe of oe.otherPartStamps??[])Object.assign(Je,Xe);let en=[...bt!==void 0?[{part:bt,plan:he?he.plan:ue}]:[],...[...qe,...Q].map(Xe=>({part:Xe.part.part,plan:Xe.plan}))];for(let{part:Xe,plan:Dt}of[...qe,...Q]){if(oe.stoppedForUndeletable||oe.cancelled||G.signal.aborted)break;let Mt=Ln(Xe)??(he?ve:void 0);if(!Mt)continue;let Rt=Nr(J?.removalSpans,[oe,...ye].flatMap(Et=>Et.span?[Et.span]:[])),ct=ar(Ve?.parts??[],Xe.part),De=await Fr(Yn(D,"sandforge clone --remove"),Dt,{...Mt,removalStamps:Je,removalSpans:Rt,...q?{runUserId:q}:{},...ct.length>0?{laterParts:ct}:{},otherPartRecords:en.flatMap(Et=>Et.part===Xe.part?[]:Et.plan),includeChanged:n.includeChanged,onUndeletable:rt,signal:G.signal});Object.assign(Je,De.stamps),ye.push(De),z&&se.push({part:Xe.part,objects:De.objects})}}finally{if(Y(),x){m=await x.release();for(let Je of Xn(m,n.target))o(Je)}}if(se.length>0&&(w={own:oe.objects,others:se}),oe.stoppedForUndeletable)return oe;let Ct=J?.removalSpans.at(-1)?.last,Un=Uo(oe.objects,...ye.map(Je=>Je.objects)),vt=oe.cancelled||ye.some(Je=>Je.cancelled);return ge({outcome:Hu({status:Hi(Un,vt)}),objects:Ku(Un),...Ct?{leftBy:Ct}:{}}),oe}let Xt=le&&Jp(le,new Date().toISOString(),J?.sweep),Ae=nO(j,J,Oe&&we?sO([Oe,...ye]):Oe??{stamps:{}},ue,Xt,ne?.made??[],ne?.late??[],ne?.gone??[]);Ae&&X&&!z&&(Ae.partsRemoved=X.parts.map(x=>x.part));let yt=Ae?tc(F,Ae):void 0;if(yt&&process.stderr.write(`What this removal left on the run's records could not be kept in ${F} (${yt}): a later --remove of this summary may keep a record this removal wrote to as changed since the run, which --include-changed then takes.
867
- `),z?.part!==void 0&&Oe&&!Oe.stoppedForUndeletable){let x=[Oe,...ye],Y={};for(let oe of x)for(let se of[oe.stamps,...oe.otherPartStamps??[]])Object.assign(Y,se);let re=oO(z,{stamps:Y,spans:x.flatMap(oe=>oe.span?[oe.span]:[]),gone:x.flatMap(oe=>oe.gone),parts:[z.part,...Q.map(oe=>oe.part.part)]}),ve=re?tc(z.file,re):void 0;ve&&process.stderr.write(`What this removal left on the run's records could not be kept in ${z.file} (${ve}): a later --remove of the run's other part or of its journal may keep a record this removal wrote to as changed since the run, which --include-changed then takes.
868
- `)}let _e=Uo(Oe?.objects??[],...ye.map(x=>x.objects)),pt=Oe?.cancelled===!0||ye.some(x=>x.cancelled),$t=zu(Oe?Hi(_e,pt):"success",le);z?.part!==void 0&&(b=rO(z,_e)),te&&!n.sweep&&_e.some(x=>(x.heldByAutomation??0)>0)&&(k=(await Hs(D,te)).result.writtenBetween===void 0),S($t,_e,L.id,Ae&&!yt?F:void 0,le),$t!=="success"&&process.exit(Ug)}var dO="not read by a preview: what the target's automation does as the records go \u2014 a trigger or a flow that deletes, keeps or creates other records \u2014 and what hangs from them, which a removal reads at each object\u2019s turn: a record kept for records that stay is counted with those to delete";function cO(r){return`${JSON.stringify({tool:"sandforge-clone",version:1,action:"remove-preview",summary:r.summary,target:r.target,...r.targetOrgId!==void 0?{targetOrgId:r.targetOrgId}:{},includeChanged:r.includeChanged,preview:r.preview,...r.sweepListing?{sweepListing:r.sweepListing}:{},refusals:r.refusals.map(({message:e})=>e),refusalCodes:r.refusals.map(({code:e})=>e),notes:r.notes,elapsedMs:r.elapsedMs},null,2)}
869
- `}function uO(r,e,t,n){let o=i=>r.userNames[i]??i,s=["preview: what a removal would do; nothing was written"];for(let i of r.objects){let a=[i.toDelete>0?`${i.toDelete} to delete`:"",n&&i.changedSince>0?`${i.changedSince} of them changed since the run`:"",i.alreadyGone>0?`${i.alreadyGone} gone already`:"",i.notVisible>0?`${i.notVisible} not visible`:"",i.keptChanged>0?`${i.keptChanged} kept, changed since the run`:"",i.undeletable>0?`${i.undeletable} left, the user may not delete them`:"",i.unread>0?`${i.unread} left, not read`:""].filter(Boolean);s.push(` ${i.objectApiName}: ${a.join(", ")||"nothing"} of ${i.planned}${fm(i)}`);let d=Object.entries(i.changedBy).sort((c,u)=>u[1]-c[1]);d.length>0&&s.push(` last changed by: ${d.map(([c,u])=>`${o(c)} ${u}`).join(" \xB7 ")}`);for(let c of i.reasons)s.push(` ${c}`)}for(let i of e)s.push(Nn(i,"a removal"));return[...s,...t]}async function lO(r,e,t,n){let o=e,s=[],i,a=(K,te,M)=>{if(s.push(dO),r.json){process.stdout.write(cO({summary:r.summaryPath,target:r.target,...M!==void 0?{targetOrgId:M}:{},includeChanged:r.includeChanged,preview:K,refusals:te,notes:s,elapsedMs:Fe(n),...i?{sweepListing:i}:{}}));return}t("");for(let q of uO(K,te,s,r.includeChanged))t(q);t(`
870
- done in ${Fe(n)}ms`)};t(`sandforge clone --remove ${r.summaryPath} --preview of ${r.target}`),o.targetOrgId===void 0&&o.target!==r.target&&(process.stderr.write(`The run wrote to ${o.target}, and its records are read in that org only: give --target ${o.target}.
871
- `),process.exit(2));let d=o.journal;d!==void 0&&Yt(d)&&Lt(Pt()).callsInFlightAt(d)>0&&s.push("the run's journal names calls under way when it stopped: a removal looks for their rows in the target first and removes those it finds with the rest; this preview counts only what the summary names");let c=(o.result.mayHaveBeenWritten??[]).reduce((K,{sourceIds:te})=>K+te.length,0);c>0&&s.push(`${c} record(s) a call of the run may have written before its answer was lost may be in the org, under ids the run never learned: no removal reaches them`);let u=dc(o);if(u.length===0){s.push("The run created no record: there is nothing of it to remove."),a({planned:0,objects:[],userNames:{}},[]);return}let l=ei(r.summaryPath),f;try{f=pn(l,"utf8")}catch(K){K?.code!=="ENOENT"&&(process.stderr.write(`${l} cannot be read: ${K instanceof Error?K.message:String(K)}
872
- `),process.exit(2))}let p=ni(f,ti(u));"refusal"in p&&(process.stderr.write(`${l} ${p.refusal}
873
- `),process.exit(2));let g=await Rm(o);g&&"refusal"in g&&(process.stderr.write(`${g.refusal}
874
- `),process.exit(2));let h=g&&Wt(l)!==Wt(g.file)?g:void 0,m=Am(p.earlier,h?.earlier),R=go({objects:u,removalLeft:p.earlier?.removalLeft}),b=sn(R,h?.earlier?.removalLeft),k=h?Om(h):[],O=K=>K.reduce((te,M)=>te+M.ids.length,0);O(u)>O(R)&&s.push(`${O(u)-O(R)} record(s) removed by an earlier --remove of this summary`),O(R)>O(b)&&s.push(`${O(R)-O(b)} record(s) removed by an earlier --remove of the run's other part or of its journal`);for(let{part:K,plan:te}of k)s.push(`with them, ${O(te)} record(s) of the run's part ${K.part} an earlier --remove of that part left, read against that part, once these are gone`);let w=r.includeChanged&&o.result.runUserId!==void 0;if(b.length===0&&k.length===0&&!r.sweep&&!w){s.push("nothing left of the run to remove"),a({planned:0,objects:[],userNames:{}},[]);return}let A=await Fn(r.target),S=On(A),v=await un(S);if(o.targetOrgId!==void 0&&!Ks(o.targetOrgId,v.id)){let K={code:yo,message:`${r.target} is not the org the run wrote to (${o.targetOrgId}): its records are read in that org only. Nothing of the run was read.`};process.stderr.write(`${kt(K)}
875
- `),r.json&&process.stdout.write(bo({tool:"sandforge-clone",action:"remove-preview",summary:r.summaryPath,target:r.target,elapsedMs:Fe(n)},K)),process.exit(1)}let j=[],F=Zr(r.target,v,"remove");if(F&&j.push({code:"PRODUCTION_TARGET",message:F}),o=await Hs(S,o),r.sweep){i=await ed(ec(S,"sandforge clone --remove --preview --sweep"),await Zd(S,r.target,o,u,await bm(v.id,r.target,o,u,m,h),{ofTheRun:h,...r.sweepUser!==void 0?{user:r.sweepUser}:{}}),m?.removalSpans??[]),t("");for(let te of _s(i,r.target,r,!0))t(te);let K=Qd(i.refusal,{kept:o.result.runUserId!==void 0,given:r.sweepUser!==void 0,target:r.target});K!==void 0&&t(K);for(let te of qs(h,i))t(te)}let B=[...new Set([...b,...k.flatMap(K=>K.plan)].map(K=>K.objectApiName))],E=i?_c(i,r):[],_=[...new Set([...qo(B,Tm(h),{userKept:o.result.runUserId!==void 0}),...B.length===0&&w?[_o]:[],...E])],ee=Gi(B),X=await Xs(S).read(r.target,_);t("");for(let K of va(X,r.target,_.length,ee))t(K);let z=$a(X,r.target,{drafted:ee,assign:fs(X,bi(X,ee)),mayMute:!r.muteAutomation&&St("--mute-automation")});if(z&&!r.acceptAutomation&&j.push({code:"AUTOMATION_NOT_ACCEPTED",message:z}),b.length===0&&k.length===0&&!w){s.push("nothing left of the run to remove"),a({planned:0,objects:[],userNames:{}},j,v.id);return}b.length===0&&k.length===0&&s.push("nothing left of the run's own records to remove: the duplicate record sets the target's rules made of them are read again, and taken changed since the run");let J=new AbortController,Me,ke=Jn(K=>{Me=K,J.abort()}),ue=o.result.writtenBetween,H=ue?{runStartedAt:new Date(ue.first),runEndedAt:new Date(ue.last)}:{runDurationMs:o.elapsedMs,...o.finishedAt?{runRecordedAt:new Date(o.finishedAt)}:{}},Q,pe=[],[we,...Ee]=(g&&!h?km(g,b):[])??[],ae=h??(we?g:void 0),D=h?.part??we?.part.part,L=ae&&D!==void 0?ar(ae.parts,D):[],Re=ae&&D!==void 0?Sm(ae,D,m?.removalStamps??{}):[],Ne=[...D!==void 0?[{part:D,plan:we?we.plan:b}]:[],...[...Ee,...k].map(K=>({part:K.part.part,plan:K.plan}))];try{Q=await Fr(Yn(S,"sandforge clone --remove --preview"),we?we.plan:b,{...(we&&Ln(we.part))??H,...m?{removalStamps:m.removalStamps,removalSpans:m.removalSpans}:{},...L.length>0?{laterParts:L}:{},...Re.length>0?{otherParts:Re.map(K=>K.alongside)}:{},...o.result.runUserId?{runUserId:o.result.runUserId}:{},includeChanged:r.includeChanged,previewOnly:!0,signal:J.signal});for(let{part:K,plan:te}of[...Ee,...k]){let M=Ln(K)??(we?H:void 0);if(!M||!Q.preview||J.signal.aborted)continue;let q=ar(ae?.parts??[],K.part);pe.push(await Fr(Yn(S,"sandforge clone --remove --preview"),te,{...M,...m?{removalStamps:m.removalStamps,removalSpans:m.removalSpans}:{},...q.length>0?{laterParts:q}:{},...o.result.runUserId?{runUserId:o.result.runUserId}:{},otherPartRecords:Ne.flatMap(G=>G.part===K.part?[]:G.plan),includeChanged:r.includeChanged,previewOnly:!0,signal:J.signal}))}}finally{ke()}let Ie=Q.preview&&pe.every(K=>K.preview)?{objects:Ki(Q.preview.objects,...pe.map(K=>K.preview?.objects??[])),userNames:Object.assign({},Q.preview.userNames,...pe.map(K=>K.preview?.userNames??{}))}:void 0;Ie||(process.stderr.write(`interrupted: the preview stopped before it was through, and wrote nothing
876
- `),process.exit(vr(Me??"SIGINT")));let ge=[Q,...pe].flatMap(K=>K.undeletable??[]);if(ge.length>0&&!r.leaveUndeletable){let K=ge.map(te=>`${te.objectApiName} (${te.records} records)`).join(", ");j.push({code:Bd,message:`The user SandForge connects as may not delete the records of ${K} in ${r.target}: a removal stops before its first delete, unless given --leave-undeletable, which removes the rest and leaves those.`})}(b.length>0||k.length>0)&&s.push(lm(o)),a({planned:O(b)+k.reduce((K,te)=>K+O(te.plan),0),objects:Ie.objects,...ge.length>0?{undeletable:ge}:{},userNames:Ie.userNames},j,v.id)}async function Hs(r,e,t=Lt(Pt())){if(e.result.writtenBetween||e.journal===void 0||!Yt(e.journal))return e;let n={query:(s=>r.query(s,{scanAll:!0}))},o=await t.writtenBetweenAt(e.journal,r)??await t.writtenBetweenAt(e.journal,n);return o?{...e,result:{...e.result,writtenBetween:o}}:e}function Ks(r,e){return r.slice(0,15)===e.slice(0,15)}var fO=new Set(["--verify","--target","--source","--json","--audit"]),pO=new Set(["--verify","--target","--source","--audit"]);function hO(r){let e=r.slice(2);(e.includes("-h")||e.includes("--help"))&&(process.stdout.write(oc),process.exit(0));let t=s=>{let i=e.indexOf(s),a=i>=0?e[i+1]:void 0;return a!==void 0&&!a.startsWith("--")?a:void 0};for(let s=0;s<e.length;s++){let i=e[s];if(pO.has(i)){e[s+1]!==void 0&&!e[s+1].startsWith("--")&&s++;continue}fO.has(i)||(process.stderr.write(`--verify takes --target, --source, --json and --audit, not "${i}". Run with --help for usage.
877
- `),process.exit(2))}let n=t("--verify"),o=t("--target");return(!n||!o||e.includes("--source")&&!t("--source"))&&(process.stderr.write(`--verify takes the file a run printed its --json summary to, --target the org the run wrote to, and --source, when given, the org it read from. Run with --help for usage.
878
- `),process.exit(2)),{summaryPath:n,target:o,source:t("--source"),json:e.includes("--json"),audit:sc(e)}}var gO=C.object({result:C.object({writtenWithoutFields:C.array(C.object({objectApiName:C.string().regex(tt),fields:C.array(C.object({field:C.string().regex(tt)}))}))})}),mO=C.object({result:C.object({lookupsLeftEmptyByFilter:C.array(C.object({objectApiName:C.string().regex(tt),field:C.string().regex(tt),records:C.number().int().nonnegative(),recordIds:C.array(lt)}))})}),wO={verified:0,partial:3,unstable:4};function yO(r,e){let t=[r.verdict==="unstable"?`verification: UNSTABLE \u2014 no two of ${r.attempts} readings of ${e} agreed: something still writes to the run's records; verify again once it is done`:`verification: ${r.verdict.toUpperCase()} (${r.attempts} readings of ${e})`,...r.roots?[` roots: ${r.roots.inTarget} of ${r.roots.of} in ${e}`]:[]],n=[];for(let s of r.objects){if(s.error!==void 0){t.push(` ${s.objectApiName}: not read (${s.error})`);continue}let i=[s.deleted>0?`${s.deleted} in the recycle bin`:"",s.notVisible>0?`${s.notVisible} neither there nor in the recycle bin, out of sight`:""].filter(Boolean),a=s.linksLeftEmptyByFilter??0,d=s.linksSetByAutomation??0,c=s.linksLeftEmptyByTheRun??0,u=[c>0?`${c} left empty by the run, as it said`:"",a>0?`${a} left empty by the target's lookup filter, as the run said`:"",d>0?`${d} set by the target's automation during the run`:""].filter(Boolean),l=s.linksChecked-s.linksBroken-a-d-c,f=s.withTheirRecord??0,p=s.linksUnchecked!==void 0?`lookups not checked (${s.linksUnchecked})`:s.linksChecked===0?"no lookup the run set to check":s.linksBroken===0&&u.length===0?`lookups: ${s.linksChecked} checked, all hold`:`lookups: ${s.linksChecked} checked, `+[...s.linksBroken>0?[`${s.linksBroken} do not hold`]:[`${l} hold`],...u].join(", ");t.push(s.expected===0&&f>0?` ${s.objectApiName}: none written by the run, and ${f} written by the platform with their record there`:` ${s.objectApiName}: ${s.present} of ${s.expected} there`+(i.length>0?`, ${i.join(", ")}`:"")+(f>0?`, and ${f} written by the platform with their record`:"")+`; ${p}`);for(let g of s.brokenLinks)t.push(g.found===null?` ${g.recordId}: ${g.field} is empty, the run set it to ${g.expected}`:` ${g.recordId}: ${g.field} points at ${g.found}, the run set it to ${g.expected}`);for(let g of s.explainedLinks??[])t.push(g.cause==="automation"?` ${g.recordId}: ${g.field} points at ${g.found??""}, which the target's automation created during the run; the run set it to ${g.expected}`:g.cause==="run"?` ${g.recordId}: ${g.field} is empty: left empty by the run, as it said, rather than set to ${g.expected}`:` ${g.recordId}: ${g.field} is empty: the target's lookup filter refused ${g.expected}, and the run left it empty`);s.recycleBinUnread!==void 0&&t.push(` the recycle bin could not be read (${s.recycleBinUnread})`),(s.moreInTheWindow??0)>0&&t.push(` ${s.moreInTheWindow} more ${s.objectApiName} record(s) were created in ${e} during the run by the run's user than the run wrote`+(f>0?" and the platform wrote with its records":"")+": the target's automation, another session writing as that user, or a call written twice");for(let g of s.changedRecords)n.push(` ${s.objectApiName} ${g.recordId}: modified ${g.modifiedAt}`+(g.modifiedById?` by ${g.modifiedById}`:""))}let o=r.objects.reduce((s,i)=>s+i.changed,0);return o>0&&t.push(`changed since the run: ${o} record(s), which --remove keeps unless --include-changed`,...n),r.linksUnchecked!==void 0&&t.push(`lookups not checked: ${r.linksUnchecked}`),t}async function bO(r=process.argv){let e=Date.now(),t=hO(r),n=E=>t.json?console.error(E):console.log(E),o;try{o=pn(t.summaryPath,"utf8")}catch(E){process.stderr.write(`--verify ${t.summaryPath} cannot be read: ${E instanceof Error?E.message:String(E)}
879
- `),process.exit(2)}let s;try{s=JSON.parse(o)}catch{}C.object({tool:C.literal("sandforge-clone"),dryRun:C.literal(!0)}).safeParse(s).success&&(process.stderr.write(`--verify ${t.summaryPath} is the summary of a dry run, which wrote nothing to the target: there is nothing of it to verify.
880
- `),process.exit(2));let a=ki(s,"sandforge-clone");a&&(process.stderr.write(`--verify ${t.summaryPath} ${Si(a,"verify")}
881
- `),process.exit(2));let d=await Yd(t.summaryPath,o,t.target);"refusal"in d&&(process.stderr.write(`--verify ${t.summaryPath} ${d.refusal}
882
- `),process.exit(2));let{summary:c}=d;c.targetOrgId===void 0&&c.target!==t.target&&(process.stderr.write(`The run wrote to ${c.target}, and its records are verified in that org only: give --target ${c.target}.
883
- `),process.exit(2));let u=dc(c);if(u.length===0){n("The run created no record: there is nothing of it to verify.");return}let l,f=ei(t.summaryPath),p;try{p=pn(f,"utf8")}catch{}let g=ni(p,ti(u)),h=u;if("refusal"in g)n(`${f} ${g.refusal}`);else if(l=g.earlier?.removalStamps,h=go({objects:u,removalLeft:g.earlier?.removalLeft}),h.length===0){n("An earlier --remove of this summary took every record the run created: there is nothing of it to verify.");return}let m=gO.safeParse(s),R=mO.safeParse(s);n(`sandforge clone --verify ${t.summaryPath} in ${t.target}`);let b=await Fn(t.target),k=On(b),O=await un(k);if(c.targetOrgId!==void 0&&!Ks(c.targetOrgId,O.id)){let E={code:yo,message:`${t.target} is not the org the run wrote to (${c.targetOrgId}), and its records are verified in that org only. Nothing of the run was read.`};process.stderr.write(`${kt(E)}
884
- `),t.json&&process.stdout.write(bo({tool:"sandforge-clone",action:"verify",summary:t.summaryPath,target:t.target,elapsedMs:Fe(e)},E)),process.exit(1)}c=await Hs(k,c);let w=c.roots!==void 0&&c.journal!==void 0&&Yt(c.journal)?(await Lt(Pt()).readAt(c.journal,"all"))?.roots:void 0,A=t.source??c.source,S;try{S=sd(On(await Fn(A)),"sandforge clone --verify source")}catch(E){S={unavailable:`the org the run read from, ${A}, could not be reached: ${V(E)}`}}let v=new Map([[O.id,{alias:t.target,username:b.username}]]),j=E=>Gs(t.audit,v,{action:"forge_verify",module:"forge",operationId:`sandforge-clone-${Us()}`,orgId:O.id,...E}),F;try{F=await new oh({target:sd(k,"sandforge clone --verify"),source:S}).verify({records:h,remapTable:c.result.remapTable,...c.result.writtenBetween?{runStartedAt:new Date(c.result.writtenBetween.first),runEndedAt:new Date(c.result.writtenBetween.last)}:c.finishedAt?{runRecordedAt:new Date(c.finishedAt)}:{},...l?{removalStamps:l}:{},...m.success?{writtenWithout:ah(m.data.result.writtenWithoutFields)}:{},...R.success?{leftEmptyByFilter:R.data.result.lookupsLeftEmptyByFilter}:{},leftEmptyByTheRun:ih(c.wholeOrg===!0),...c.result.withTheirRecordSourceIds?{withTheirRecord:c.result.withTheirRecordSourceIds}:{},...w?{roots:{objectApiName:w.objectApiName,sourceIds:w.ids}}:{}})}catch(E){throw j({outcome:"failure"}),E}if(j({outcome:F.verdict==="verified"?"success":"partial",verdict:F.verdict,details:sh(F)}),t.json)process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"verify",summary:t.summaryPath,target:t.target,targetOrgId:O.id,source:A,result:F,elapsedMs:Fe(e)},null,2)+`
885
- `);else{for(let E of yO(F,t.target))console.log(E);console.log(`
886
- done in ${Fe(e)}ms`)}let B=wO[F.verdict];B!==0&&process.exit(B)}var RO=new Set(["done","error","stopped"]);function OO(r){return r?`interrupted: the clone stopped before it was through; ${r} says what it created, and --remove ${r} takes it back`:"interrupted: the clone stopped before it was through; the summary above says what it created, and --remove takes it back from that summary saved to a file (--json)"}function zg(r,e){if(!(r.wholeOrg!==!0||e.sweep||e.sweepList))return`the sweep is off for a clone of the whole org: its window spans the hours the run wrote in, and a sweep looks at ${Za} objects at most; ${ln("--sweep-list")} lists what the target's automation made for it, and ${ln("--sweep")} takes it`}var Hg="ROOT_NEVER_CREATED",kO="TABLE_NEVER_CLONED",nc="No record was read or written.";async function SO(r,e,t){let n=[];for(let i of r)try{await t.createable(i.objectApiName)===!1&&n.push(i)}catch{}if(n.length===0)return;let o=n.find(i=>jo(i.objectApiName));if(o){let i=o.objectApiName;return{code:Hg,message:`${o.named}: SandForge never copies ${i} records, setup or the platform's own, and ${e}'s user may not create them: a clone has nothing to write of what it starts from. ${nc}`}}let s;try{s=await t.whyNot(n.map(i=>i.objectApiName))}catch{return}for(let i of n){let a=s.get(i.objectApiName);if(a===void 0||!Hl(a))continue;let d=i.objectApiName,c=a==="platform"?"the platform writes them itself":"not even one with Modify All Data: they are setup the org keeps as records, or the platform's own";return{code:Hg,message:`${i.named}: no user can create ${d} records in ${e}, ${c}, and a clone has nothing to write of what it starts from. ${nc}`}}}async function TO(r,e){if(r.tables)return r.tables.map(({objectApiName:a})=>({objectApiName:a,named:`--object ${a}`}));if(r.roots?.query){let a=r.roots.query.objectApiName;return[{objectApiName:a,named:`--query (FROM ${a})`}]}let t=r.record??"";if(t==="")return[];let n=t.slice(0,3),o;try{o=await e(r.source)}catch{return[]}let s=o.find(a=>a.keyPrefix===n)?.name;if(!s)return[];let i=r.roots?.ids;return[{objectApiName:s,named:i!==void 0?`--record ${i.length} times (${s} records)`:`--record ${t} (a ${s})`}]}function Kg(r,e,t){let n=o=>{let s=r.get(o);if(!s)throw new Error(`No connection for ${o}`);return s};return{describeFields:async(o,s)=>{let i=!t.has(`${o}::${s}`);return{fields:(await e(o,s)).fields.map(ca),sent:i}},query:async(o,s)=>Bn({query:async i=>n(o).query(i),queryMore:async i=>n(o).queryMore(i)},s)}}function pr(r,e){let t=r.get(e);if(!t)throw new Error(`No connection for ${e}`);return t}var AO=new Set(["Lead","Case"]);function jO(r,e,t,n){return{bulkWriteRecords:async(o,s,i,a,d)=>{if(e.dryRun)throw new Error("A dry run sends no Bulk API job.");if(e.applyAssignmentRules&&AO.has(s))return{answers:[],rows:[],unmatchedIds:[],untouched:{reason:"the run applies the target's assignment rules, which a job cannot",unsupported:!0},requests:0};try{let c=await Wl(Ui(pr(r,o)),d.bulkManager,s,i,a,{...d.externalIdField?{externalIdField:d.externalIdField}:{},...d.signal?{signal:d.signal}:{},...d.onOpened?{onOpened:d.onOpened}:{}});return(c.unmatchedIds.length>0||c.answers.some(u=>u.success))&&n(),c}catch(c){throw c instanceof Ll&&(n(),t?.note({orgId:o,objectApiName:s,...c.jobId?{jobId:c.jobId}:{}})),c}},duplicateRuleObjects:async o=>Lp(pr(r,o))}}async function $O(r,e,t){let n=r?.since(0,e)??[];if(!r||n.length===0)return[];t(`waiting for ${n.length} Bulk API job(s) the run could not read back to end, before the mute is given back\u2026`);let o=await r.stillRunning(n);if(o.length>0){let s=o.map(i=>`${i.objectApiName}${i.jobId?` (${i.jobId})`:""}`).join(", ");t(`warning: ${o.length} Bulk API job(s) were still running as the mute was given back: ${s}; their records may have gone in with the target's automation on`)}return o}async function vO(r,e,t){let n=r.get(e);if(!n)throw new Error(`No connection for ${e}`);return Bn({query:async o=>n.tooling.query(o),queryMore:async o=>n.tooling.queryMore(o)},t)}async function EO(r=process.argv){if(r.slice(2).includes("--verify"))return bO(r);if(r.slice(2).includes("--remove"))return iO(r);let e={};try{await xO(r,e)}finally{e.release?.(),e.journalLock?.release()}}var Vs=class extends Error{constructor(e){super(e),this.name="CheckpointTakeInterrupted"}},Js=class extends Error{constructor(e){super(e),this.name="QuestionInterrupted"}};async function IO(r,e){let t=r.roots?.plan;if(t===void 0)return;let n=s=>(process.stderr.write(`${kt(s)}
887
- `),r.json&&process.stdout.write(nn({tool:"sandforge-clone",source:r.source,target:r.target,dryRun:r.dryRun,elapsedMs:Fe(e)},s)),process.exit(2)),o=`${qt("clone")} \u2026 --dry-run --roots-plan ${t}`;if(r.dryRun){if(!Yt(t))return;try{await Ja(t)}catch(s){if(!(s instanceof Va))throw s;let i=!1;try{let a=JSON.parse(pn(t,"utf8"));i=a?.version===1&&Array.isArray(a.ids)}catch{}i||(process.stderr.write(`--roots-plan ${t} exists, and is no plan of roots: a dry run puts the records it chooses in its place. Give another file, or move it.
888
- `),process.exit(2))}return}try{return await Ja(t)}catch(s){if(!(s instanceof Va))throw s;return n(s.fault==="gone"?{code:"ROOTS_PLAN_GONE",message:`--roots-plan ${t}: no plan of roots is there. The dry run keeps the records its query chooses there, for the run to write those and no other: run ${o} first. Nothing was read or written.`}:{code:"ROOTS_PLAN_MISMATCH",message:`--roots-plan ${t}: ${s.message} Run ${o} again, and give the run the plan it keeps. Nothing was read or written.`})}}async function xO(r,e){let t=Date.now(),n=eb(r),o=n.depth==="all",s=y=>n.json?console.error(y):console.log(y);s(`sandforge clone ${n.source} -> ${n.target} ${Py(n)}`);for(let y of xb(n))s(y);if(n.resume&&n.files===void 0){let y=Lt(Pt()),T=await y.headAt($g(n.resume,y));T?.resume?.files&&(n={...n,files:T.resume.files},s("files: copied as the run taken up was begun, with --files"))}let i=await IO(n,t),a=await Fn(n.source),d=await Fn(n.target),c,u=()=>c??=new eh({...Vd(n),depth:n.depth,sourceOrgId:n.source,targetOrgId:n.target,anonymizePII:n.anonymize,keepContactPoints:n.keepContactPoints,skipEmpty:!0,batchSize:"auto",excludedObjects:n.excludedObjects,...n.decisions},{reviewSkipped:!0}),l=new Map;l.set(n.source,On(a)),l.set(n.target,On(d));let f=new Map([...l].map(([y,T])=>[y,[wo(T)]])),p=y=>(f.get(y)??[]).reduce((T,P)=>T+P(),0),g,h=new Map,m,R=`sandforge-clone-${Us()}`,b,k=y=>{if(g===void 0||n.dryRun||n.listObjects||n.rehearse)return;let T=c?.fit();Gs(n.audit,h,{action:"forge_execute",module:"forge",operationId:R,orgId:g,...y,...b?{muted:mo(b)}:{},...T?{fit:T}:{}})},O;if(!n.dryRun&&!n.listObjects){let y=await un(l.get(n.target));O=y,g=y.id,h.set(y.id,{alias:n.target,username:d.username}),n.audit&&!n.rehearse&&(m=(await un(l.get(n.source))).id,h.set(m,{alias:n.source,username:a.username}));let T=Zr(n.target,y,"clone");T&&(k({outcome:"stopped",code:"PRODUCTION_TARGET",context:u().context()}),process.stderr.write(`${T}
889
- `),process.exit(1))}let w;if(o){let y=await un(l.get(n.source));w=y.id;let T=Zr(n.source,y,"clone")!==void 0;T&&!n.anonymizeGiven&&(n={...n,anonymize:!0},n.files&&!n.files.acceptedAsIs&&(process.stderr.write(`--files: ${n.source} is a production org, whose personal data a clone of the whole org anonymizes unless --no-anonymize is given, and the content of a file cannot be anonymized: add --files-as-is to accept that files are copied as they are, give --no-anonymize, or leave out --files.
890
- `),process.exit(2))),s(n.anonymize?`anonymize: on${T&&!n.anonymizeGiven?`, ${n.source} being a production org (--no-anonymize copies its personal data as it is)`:""}`:`anonymize: off, the personal data copied as ${n.source} holds it`)}let A=await bR(n,async y=>{let T=l.get(n.source);return(await vo({query:async P=>T.query(P),queryMore:async P=>T.queryMore(P)},y,bn+1)).records},i);if(A&&"refused"in A){let{refused:y}=A;k({outcome:"stopped",code:y.code,context:u().context()}),process.stderr.write(`${kt(y)}
891
- `),n.json&&process.stdout.write(nn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:fr({target:p(n.target),source:p(n.source)},{})},y)),process.exit(1)}let S=A?.chosen;if(!n.listObjects){let y=await bs(n.ownerMappings,async T=>(await l.get(n.target).query(T)).records);if(y){k({outcome:"stopped",code:y.code,context:u().context()});let T={code:y.code,message:y.message};process.stderr.write(`${kt(T)}
892
- `),n.json&&process.stdout.write(nn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:fr({target:p(n.target),source:p(n.source)},{})},T)),process.exit(1)}}let v=n.checkpointFirst?mg({module:"forge",operationId:R,request:n.checkpointFirst,session:d,org:gg(d,O??await un(l.get(n.target))),connect:y=>{let T=On(y);return f.get(n.target)?.push(wo(T)),T},journalDir:Pt(),say:s}):void 0,j=[...l.values()].map(wo),F=()=>j.reduce((y,T)=>y+T(),0),B={...Vd(n),depth:n.depth,customDepth:n.depth==="custom"?n.customDepth:void 0,sourceOrgId:n.source,targetOrgId:n.target,anonymizePII:n.anonymize,skipEmpty:!0,batchSize:"auto",...(n.tables||o)&&Object.keys(n.objectSoqlFilters).length>0?{objectSoqlFilters:n.objectSoqlFilters}:{},...o&&n.excludedObjects.length>0?{excludedObjects:n.excludedObjects}:{}},E=new el,_=new Set,ee=wb(async(y,T)=>{_.add(`${y}::${T}`);let P=l.get(y);if(!P)throw new Error(`No connection for ${y}`);return P.sobject(T).describe()}),X=new Map,z={describeObject:async(y,T)=>gb(await ee(y,T)),queryCount:async(y,T,P,N)=>{let I=l.get(y);if(!I)throw new Error(`No connection for ${y}`);return(await I.query(T,N?.all?{scanAll:!0}:void 0)).totalSize},detectPII:y=>Zu(E,y),describeGlobal:y=>{let T=X.get(y);if(!T){let P=l.get(y);if(!P)throw new Error(`No connection for ${y}`);T=P.describeGlobal().then(N=>N.sobjects.map(I=>o?{name:I.name,keyPrefix:I.keyPrefix??null,queryable:I.queryable,createable:I.createable,updateable:I.updateable,deletable:I.deletable,customSetting:I.customSetting,layoutable:I.layoutable}:{name:I.name,keyPrefix:I.keyPrefix??null})),X.set(y,T)}return T},...o?{toolingObjects:async y=>{let T=l.get(y);if(!T)throw new Error(`No connection for ${y}`);return(await T.tooling.describeGlobal()).sobjects.map(P=>P.name)},recordCounts:async y=>{let T=l.get(y);if(!T)throw new Error(`No connection for ${y}`);return T.request(`/services/data/v${T.version}/limits/recordCount`)},createFacts:async y=>(await da(Kg(l,ee,_),y)).facts}:{}},J=await TO(n,z.describeGlobal),Me=await SO(J,n.target,{createable:async y=>(await ee(n.target,y)).createable!==!1,whyNot:y=>Kl((T,P)=>vO(l,T,P),async T=>(await da(Kg(l,ee,_),T)).facts)(n.target,y)});Me&&(k({outcome:"stopped",code:Me.code,context:u().context()}),process.stderr.write(`${kt(Me)}
893
- `),n.json&&process.stdout.write(`${JSON.stringify({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,refused:Me,elapsedMs:Fe(t)},null,2)}
894
- `),process.exit(1));let ke=(n.tables??[]).flatMap(({objectApiName:y})=>{let T=Ty(y);return T!==void 0?[T]:[]});if(ke.length>0){let y={code:kO,message:`${ke.join(" ")} ${nc}`};k({outcome:"stopped",code:y.code,context:u().context()}),process.stderr.write(`${kt(y)}
895
- `),n.json&&process.stdout.write(nn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t)},y)),process.exit(2)}s("discovery\u2026");let ue=new of(z),H={source:p(n.source),target:p(n.target)},Q=o?await Ub(ue,B,s):await ue.discover(B,n.maxNodes===void 0?void 0:{maxNodes:n.maxNodes}),pe={source:p(n.source)-H.source,target:p(n.target)-H.target};o&&s(zb(pe,n.source,n.target));let we=o?void 0:Q.nodes[0]?.objectApiName;we!==void 0&&n.excludedObjects.includes(we)&&(process.stderr.write(`${An(`--exclude-object ${we}`,`the resource's template leaves out ${we}`)}: the ${n.tables?"first table":"record"} to clone is of this object, and nothing would be left to clone.
896
- `),process.exit(2));let Ee=n.tables?Sy(Q,n.tables):[];Ee.length>0&&(process.stderr.write(`${jy(Ee,{root:we??n.tables?.[0]?.objectApiName??"",objects:Q.nodes.length,depth:n.depth,customDepth:n.customDepth,truncated:Q.truncated===!0,env:Kt()})}
897
- `),process.exit(2));let ae=n.tables?Iy(n,Q):o?Cy(n):B,D=ae.excludedObjects??n.excludedObjects,L=o?By(Q,new Set(D)):OR(es(Q,new Set(D)),n.anonymizeFields),Re=new zl().generate(L);if(s(o?_b(L,Re,n.source):Db(L,Re,n.maxNodes??nf)),n.listObjects){let y=wR(L),T=y.map(P=>` ${P.objectApiName.padEnd(42)}${String(P.recordCount).padStart(8)} depth ${P.depth}${P.included?"":" (excluded)"}`);s(`
898
- objects in the graph (${L.nodes.length}):`),s(T.join(`
899
- `)),L.truncated&&s(`
900
- The graph was truncated: discovery stopped before it had walked everything. Raise --max-nodes if an object you need is missing.`),n.json&&process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"list-objects",source:n.source,target:n.target,...n.tables?{tables:n.tables}:o?{wholeOrg:!0}:{record:n.record},graph:Ls(L,Re),objects:y,...o?{leftOut:cs(L)}:{},elapsedMs:Fe(t)},null,2)+`
901
- `);return}let Ne=await Sb(n.fieldExclusions,L,async y=>(await ee(n.source,y)).fields.map(T=>T.name)),Ie=Ne.length>0?{code:qd,message:Eg(Ne,n.choicesFrom).replace(/ Nothing was read or written\.$/,"")}:void 0;if(Ie!==void 0&&!n.dryRun){k({outcome:"stopped",code:qd,context:u().context()});let y={code:qd,message:Eg(Ne,n.choicesFrom)};process.stderr.write(`${kt(y)}
902
- `),n.json&&process.stdout.write(nn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:fr({target:p(n.target),source:p(n.source)},{},o?pe:void 0)},y)),process.exit(2)}Ie!==void 0&&s(` ${Nn(Ie)}`);let ge=o?Np(L):void 0;ge&&(k({outcome:"stopped",code:ge.code,context:u().context()}),process.stderr.write(`${kt(ge)}
903
- `),n.json&&process.stdout.write(nn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:fr({target:p(n.target),source:p(n.source)},{},pe)},ge)),process.exit(1));let K=y=>(k({outcome:"stopped",code:y.code,context:u().context()}),process.stderr.write(`${kt(y)}
904
- `),n.json&&process.stdout.write(nn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:fr({target:p(n.target),source:p(n.source)},{},pe)},y)),process.exit(Bg(y.code))),te=Pt(),M="",q;if(n.sample){let y=g??(await un(l.get(n.target))).id,T={...w?{sourceOrgId:w}:{}};M=Qa(L,vg(n,y,T)),await hp(te,new Date).catch(()=>0);let P=n.sample.options.plan;if(P!==void 0)try{if(q=await sr.open(P,{sourceOrgId:n.source,fingerprint:M}),q.ageMs(new Date)>=dp)throw new Os("gone","The plan of this sample is a day old or more.")}catch(N){let I=ls(N,"replay");if(!I)throw N;K({code:I.code,message:I.message.replace(/ Nothing was written\.$/,` Given: ${P}. Nothing was written.`)})}}let G=!n.dryRun&&!n.rehearse?Lt(te):void 0,Te=(y,T)=>vg(n,y,{...w?{sourceOrgId:w}:{},...T?{planSha256:T}:{}}),ie=g!==void 0?Qa(L,Te(g,q?.sha256)):"",ne,U,Oe=n.muteAutomation;if(G&&g!==void 0&&n.resume){ne=$g(n.resume,G);let y=Ss(ne,{journalId:rc(ne).replace(/\.ndjson$/,""),ranFrom:"commandLine",target:n.target,resumes:!0});if("busy"in y)return K({code:Ri,message:`--resume ${ne}: ${td(y.busy)}. Two runs would write it at once: ${nd(y.busy)}, then take it up. Nothing was written.`});e.journalLock=y.lock;let T=g,P=await sb(G,ne,{target:n.target,targetOrgId:g,graph:L,setup:Te(g),sample:{asked:n.sample!==void 0,setupWith:I=>Te(T,I)},config:ae,...n.record?{record:n.record}:{}});P&&K(P),U=await G.lastEndAt(ne),(await G.headAt(ne))?.resume?.muteAutomation===!0&&(Oe=!0),s(`taking up the run of ${ne}`);let N=await G.reconcileAt(ne,za(l.get(n.target)));for(let I of Ha(N,n.target))s(I);if(ks(N)>0&&!n.writeUncertain){let I=rb(N),Z={code:"RESUME_UNCERTAIN",message:nb(N,n.target),...I!==void 0?{retryAt:I}:{}};K(Z)}}let ye=new Wp,le=new AbortController,Nt={},ft,Tt=y=>{ft=y,process.stderr.write(`
905
- interrupted: the clone stops after the call under way, and says what it created (Ctrl-C again ends it at once)
906
- `),ye.stop(void 0,{discovery:()=>{},run:()=>{le.abort(),Nt.executor?.abort()}})};if(!n.dryRun&&!n.rehearse&&!n.listObjects){ye.beginRun(R,le);let y=Jn(Tt);e.release=()=>{y(),ye.endRun(R)}}let wt=async y=>{le.signal.aborted&&(k({outcome:"stopped",code:Ni,context:u().context()}),await y?.(),s("interrupted: the clone stopped before it wrote anything"),process.exit(vr(ft??"SIGINT")))},nt=await Xs(l.get(n.target)).readForGraph(n.target,L,new Set(D));s("");for(let y of ef(nt,n.target,{applyAssignmentRules:n.applyAssignmentRules,mayMute:St("--mute-automation"),mayApplyAssignmentRules:St("--apply-assignment-rules")}))s(y);let At=qc(nt,new Set(D));for(let y of Af(At,n.target,nt.unread,An("--remove","destroy, or a replace")))s(y);s(n.keepContactPoints?`contact points: written as read (${An("--keep-contact-points","keepContactPoints")})`:"contact points: neutralized before writing (emails under .invalid, phone numbers in a fictional range)");let dt=await kR(l,ee,_).read(n.source,n.target,L,{inputMode:B.inputMode,recordId:B.recordId,maxRecordsPerObject:n.maxRecordsPerObject,fieldExclusions:n.fieldExclusions,fieldMappings:n.fieldMappings,excludedObjects:D}),Xt={...n.decisions,fieldExclusions:n.fieldExclusions,excludedObjects:D},Ae=Sf(L,{leftOut:new Set(D),upsert:n.upsert}),yt=new Set(Ae.map(y=>y.objectApiName)),_e=(y,T)=>T==="insert"||T==="update"&&yt.has(y),pt=Oe?il(nt,_e).plan.alsoLifts:void 0;s("");for(let y of Ql(dt,n.target,{decisions:Xt,...pt?{lifted:pt}:{}}))s(y);let $t=n.upsert&&!n.keepContactPoints?Nb(await Promise.all(L.nodes.filter(y=>y.included).map(async({objectApiName:y})=>({objectApiName:y,fields:await ee(n.source,y).then(T=>T.fields).catch(()=>[])})))):[];for(let y of Cb($t,n.target))s(y);let x,Y,re={},ve=()=>({apiRequests:fr({target:p(n.target),source:p(n.source)},re,o?pe:void 0)}),oe=(y,T=[],P=1)=>{let N={...y,message:Xr(y.message)},I=T.map(Z=>({...Z,message:Xr(Z.message)}));for(let Z of[N,...I])process.stderr.write(`${kt(Z)}
907
- `);return n.json&&process.stdout.write(nn({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),...ve()},N,I)),process.exit(P)};if(Oe){n.muteAutomation||s(" mute: the run taken up was muted, and so is this part of it");try{x=await Yi(async()=>Ji(l.get(n.target)),nt,{writes:_e});for(let y of Xn(x.muted,n.target))s(` ${y}`)}catch(y){if(!Cr(y))throw y;n.dryRun||(k({outcome:"stopped",code:y.code,context:u().context()}),oe(y.refusal)),Y=y.refusal,s(` ${Nn(y.refusal)}`)}}let se=x?.automation??nt,rt=jf(se,n.target,{updated:Ae,assign:fs(se,Tf(se,Ae.map(y=>y.objectApiName))),mayMute:!Oe&&St("--mute-automation")});u().automationRead({automation:se},Ae),rt&&n.acceptAutomation&&u().confirm("automation");let he=n.rehearse?void 0:await sl({read:nt,...x?.plan?{plan:x.plan}:{},writes:_e,applyAssignmentRules:n.applyAssignmentRules,readDeliverability:async()=>{let y=l.get(n.target),T=O??await un(y);return Zr(n.target,T,"clone")!==void 0?rl:ol(y)},accepted:n.acceptEmails,target:n.target,run:"clone",keepsAddresses:n.keepContactPoints,mayMute:!Oe&&St("--mute-automation")});he?.gate.line!==void 0&&s(` ${he.gate.line}`),u().emailsRead(he?.gate.audit),he?.gate.verdict==="asks"&&n.acceptEmails&&u().confirm("emails");let qe=he?.gate.stop,Ve=[...Ie!==void 0?[Ie]:[],...Y!==void 0?[Y]:[]],bt=rt!==void 0&&!n.acceptAutomation;(bt||qe)&&!n.dryRun&&(k({outcome:"stopped",code:bt?"AUTOMATION_NOT_ACCEPTED":Rf,context:u().context()}),bt&&oe({code:"AUTOMATION_NOT_ACCEPTED",message:rt},qe?[qe]:[]),qe&&oe(qe)),bt&&(Ve.push({code:"AUTOMATION_NOT_ACCEPTED",message:rt}),s(" a real run would be refused (AUTOMATION_NOT_ACCEPTED): it writes nothing without --accept-automation: see what fires as it inserts and updates, or could not be read, above")),qe&&(Ve.push(qe),s(` ${Nn(qe)}`)),await wt(),s("record-type mapping\u2026");let Zt=F(),In=[],Ct=await mb(l.get(n.source),l.get(n.target),y=>In.push(y)),Un=F()-Zt;s(`record-types: ${Ct.length} mappings`);for(let y of In)s(` warning: ${y}`);await wt();let vt={statements:0,pages:0},Je=!1,en=y=>(y.some(T=>T.success)&&(Je=!0),y),Xe=o?new Bp(async(y,T)=>(await Ui(pr(l,y)).bulk2.job("ingest",{id:T}).check()).state):void 0,Dt={...o?jO(l,n,Xe,()=>Je=!0):{},queryRecords:async(y,T,P)=>{let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);let{records:I,truncated:Z}=await vo({query:async Ge=>N.query(Ge),queryMore:async Ge=>N.queryMore(Ge)},T,n.readCeiling);return Z&&P?.(),I},queryPages:(y,T,P)=>{let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);return vt.statements++,hu({query:async I=>(vt.pages++,N.query(I)),queryAll:async I=>(vt.pages++,N.query(I,{scanAll:!0})),queryMore:async I=>(vt.pages++,N.queryMore(I))},T,P)},countRecords:async(y,T,P)=>{let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);return(await N.query(T,P?.all?{scanAll:!0}:void 0)).totalSize},queryTooling:async(y,T)=>{let P=l.get(y);if(!P)throw new Error(`No connection for ${y}`);return(await P.tooling.query(T)).records},insertRecords:async(y,T,P)=>{if(n.dryRun)return P.map(()=>({id:"",success:!0,errors:[]}));let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);let I=await N.sobject(T).create(P,{headers:Sr({applyAssignmentRules:n.applyAssignmentRules})});return en(qi(I,T))},updateRecords:async(y,T,P)=>{if(n.dryRun)return[];let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);let I=await N.sobject(T).update(P,{headers:Sr({applyAssignmentRules:n.applyAssignmentRules})}),Z=Array.isArray(I)?I:[I];return en(Z.map((Ge,Ot)=>({id:Ge.id??P[Ot].Id??"",success:Ge.success,errors:(Ge.errors??[]).map(_u),errorDetails:(Ge.errors??[]).map(Du)})))},describeFields:async(y,T)=>hb(await ee(y,T)),isObjectCreatable:async(y,T)=>(await ee(y,T)).createable!==!1,describeObject:async(y,T)=>{let P=l.get(y);if(!P)throw new Error(`No connection for ${y}`);return Wd(P,T)},describeObjectAgain:async(y,T)=>{let P=l.get(y);if(!P)throw new Error(`No connection for ${y}`);return Wd(P,T,!0)},recordTypePicklists:async(y,T,P)=>{let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);return Dp(N,T,P)},upsertRecords:async(y,T,P,N)=>{if(n.dryRun)return N.map(()=>({id:"",success:!0,errors:[]}));let I=l.get(y);if(!I)throw new Error(`No connection for ${y}`);let Z=await I.sobject(T).upsert(N,P,{headers:Sr({applyAssignmentRules:n.applyAssignmentRules})});return en(qi(Z,T))},readFileBody:async(y,T,P)=>{let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);return _p(N,T,P)},insertFile:async(y,T,P)=>{if(n.dryRun)return{id:"",success:!0,errors:[]};let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);let[I]=en([await qp(N,T,P)]);return I},remainingFileStorageMB:async y=>{let T=l.get(y);if(!T)throw new Error(`No connection for ${y}`);return Up(T)},requestsSent:F,runningUser:async y=>{let T=l.get(y);if(!T)throw new Error(`No connection for ${y}`);return(await T.identity()).user_id},orgCurrency:async y=>{let T=l.get(y);if(!T)throw new Error(`No connection for ${y}`);return wu(await T.soap.getUserInfo())}},Mt={};if(n.roots){try{Mt.sourceRequestsLeft=(await tr(l.get(n.source))).remaining}catch{}i&&(Mt.plan=i),S&&(Mt.chosen=S),n.dryRun&&n.roots.plan!==void 0&&(Ws(n.roots.plan,{force:!0}),Mt.keepAt=n.roots.plan)}if(n.rehearse){let y=l.get(n.target),T=Sr({applyAssignmentRules:n.applyAssignmentRules});s(`
908
- rehearsing\u2026 (the rows are read and prepared as the run would; nothing stays in the target)`);let P;try{P=await od({prepare:async I=>{await new lr(rd(Dt,I)).execute(L,n.source,n.target,()=>{},{...Lg(n,L,Ct,Z=>ue.personalFields(Z),Mt),dryRun:!1,files:void 0})},keyPrefixOf:async I=>(await Wd(y,I)).keyPrefix,runningUser:async()=>(await y.identity()).user_id,composite:I=>y.request({method:"POST",url:"/composite",body:JSON.stringify(I),headers:{"Content-Type":"application/json",...T}}),apiPath:`/services/data/v${y.version}`,writeHeaders:T,recordTypeNames:new Map(Ct.map(I=>[I.targetId.slice(0,15),I.developerName])),targetRecordTypes:bg(Dt,n.target),targetFields:I=>Dt.describeFields(n.target,I),validationRules:async()=>nh(dt.gaps),confirm:async I=>{s("");for(let Z of TR(I,n.target))s(Z)},onProgress:I=>{I.phase==="rehearsing"&&s(` call ${I.call} of ${I.calls}\u2026`)}})}catch(I){throw I instanceof rh&&(process.stderr.write(`${I.message}
909
- `),process.exit(1)),I}let N=Fe(t);s("");for(let I of AR(P,n.target,pt?{lifted:pt}:{}))s(I);n.json?process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"rehearse",source:n.source,target:n.target,...g?{targetOrgId:g}:{},record:n.record,graph:Ls(L,Re),targetAutomation:nt,rehearsal:jR(P,pt),elapsedMs:N},null,2)+`
910
- `):console.log(`
911
- done in ${N}ms`);return}if(!n.skipPreflight){s(`
912
- preflight (target row counts)\u2026`);let y=l.get(n.target),T=L.nodes.slice(0,30),P=[];for(let I of T)try{let Z=await y.query(`SELECT COUNT() FROM ${I.objectApiName}`);P.push({name:I.objectApiName,existing:Z.totalSize})}catch{P.push({name:I.objectApiName,existing:-1})}let N=P.filter(I=>I.existing>0);if(N.length===0)s(" target is empty for all sampled objects.");else{let I=N.sort((Z,Ge)=>Ge.existing-Z.existing).slice(0,10);s(` ${N.length}/${P.length} sampled objects have existing rows. Top 10:`);for(let Z of I){let Ge=Z.existing>1e3?" \u26A0":"";s(` ${Z.name.padEnd(40)} ${String(Z.existing).padStart(8)}${Ge}`)}L.nodes.length>T.length&&s(` (sampled first ${T.length}/${L.nodes.length} nodes; --skip-preflight to bypass)`)}}await wt();let Rt=l.get(n.target),ct,De,Et=[],hn={},eo,Gn,to=async(y,T)=>{if(!v||T.totalRows===0)return;let P=new Set(T.objects.map(({objectApiName:I})=>I)),N={written:y.objects.map(({objectApiName:I})=>I).filter(I=>P.has(I)),running:{firing:Vn(se,void 0,_e).firing}};try{De={ask:N,estimate:await v.scope(N)};return}catch(I){return pa(I).replace(/ Nothing was written\.$/,"")}},gn=y=>({unread:V(y)}),$=()=>({target:Math.max(0,p(n.target)-(he?.ofRun.read?.requests??0)),source:p(n.source)}),W=async y=>{let T=y.wholeOrg;if(!T)throw new Error("A clone of the whole org reached its write gate without what it measured of both orgs, which its gate weighs it on. Nothing was written.");let P=pf(T.readWholeOver);if(P&&!y.dryRun)throw Pe.of({...P,message:Ng(P.message,T.sample!==void 0)});let N=gf(y.objects,T),I=ps({firing:Vn(se,void 0,_e).firing},(de,xt)=>_e(de,xt)).perRecord,Z=T.sample?.report;Z&&(Gn=Z,u().sampled(Z));let Ge=await to(y,N),Ot=[...yt],ht,Bt,Ze,st,_t;if(y.dryRun)ht=await mf({objects:y.objects,measures:T,graph:L,anonymizePII:n.anonymize,updatedAfterInsert:Ot,...De?{checkpoint:De.estimate}:{},...y.readBack!==void 0?{readBack:y.readBack}:{},mute:Go(x?.plan),deliverability:he?.ofRun.read?.requests??0,sentBefore:$,...Z?{sample:Z}:{},automation:I,target:{org:n.target,limits:Rt},source:{org:n.source,limits:pr(l,n.source)}}),Bt=Cp(ht),Ze=ht.storage,st=ht.files,_t=ht.wouldBeRefused;else{let de=await as(Rt).catch(gn),xt="unread"in de?await tr(Rt).catch(gn):de.dailyApiRequests;Ze=ga(N,de,ds(N,I));let co=Aa(Ze,n.target),ci=Z?bf({sample:Z,storage:de,target:n.target}):void 0,ui=hf(T.files,de,n.target);st=ui.files;let Fm=await tr(pr(l,n.source)).catch(gn),bc=$(),Or=ha({plan:N,updatedAfterInsert:Ot,...y.readBack!==void 0?{readBack:y.readBack}:{},...De?{checkpoint:De.estimate}:{},mute:Go(x?.plan),...Sa(he?.ofRun),sentBefore:bc.target,budget:xt,target:n.target,wholeOrg:{measures:T,bulkBatches:"unread"in de?de:de.dailyBulkApiBatches,sourceBudget:Fm,source:n.source,sourceSentBefore:bc.source}});Bt={api:Or.api,wholeOrg:Or.wholeOrg},_t=[...ci?[ci]:[],...ci===void 0&&co!==void 0&&Ze.verdict==="exceeds"?[{code:"STORAGE_EXCEEDED",message:`${co} Nothing was written.`,storage:{estimateMB:Number(Ht(Ze.estimateMB)),remainingMB:Ze.remainingMB}}]:[],...ui.stop?[ui.stop]:[],...Or.stop?[Or.stop]:[],...Or.alsoRefused??[]]}let wr=Z?void 0:Yb(Ze,n.target);wr!==void 0&&(_t=_t.map(de=>de.code==="STORAGE_EXCEEDED"?{...de,message:`${wr} Nothing was written.`}:de));let yr={...Mp({run:{source:n.source,graph:L,anonymizePII:n.anonymize,...me()},measures:T,plan:N,budget:Bt,...st?{files:st}:{},...Z?{sample:Z,now:Date.now()}:{}}),discovery:pe};if(re={target:Bt.api,source:Bt.wholeOrg.source},eo={...ht?{dry:ht}:{},question:yr},s(""),Z)for(let de of dR(Z,{source:n.source,target:n.target,dryRun:y.dryRun===!0,replayed:n.sample?.options.plan!==void 0}))s(de);for(let de of ja(N,Ze,n.target))s(de);let br=Kb(T,n.source,n.target);br!==void 0&&s(br);for(let de of Gb(yr,cs(L).counts,n.target,T.writes))s(de);if(De)for(let de of Nd(De.estimate))s(de);let io=yi(se),Rr;if(io.length>0){let de=await wa(Rt).catch(gn),xt=ya(N,io,de);for(let co of ka(xt,n.target))s(co);Rr=Oa(xt,n.target)}let ao=Ra(se,ba(N));ao!==void 0&&s(` emails: not counted, ${ao} could not be read`);let yn=de=>Xr(Ng(de,Z!==void 0)).replace(/ Nothing was written\.$/,""),je=[...N.totalRows>n.maxTotal?[{code:"MAX_TOTAL_EXCEEDED",message:Vb(N.totalRows,n.maxTotal,Z!==void 0,n.dryRun)}]:[],...Ge!==void 0?[{code:Tn,message:Ge}]:[],..._t.map(de=>({code:de.code,message:de.code===Tn&&de.refusal!==void 0?Ms(de.refusal):yn(de.message),stop:de})),...Rr!==void 0?[{code:"EMAILS_EXCEEDED",message:Rr}]:[]];if(ht){for(let{code:de,message:xt}of je)s(` ${Nn({code:de,message:xt})}`);throw Ve.push(...je.map(({code:de,message:xt})=>({code:de,message:xt}))),ct={totalRows:N.totalRows,storageBytes:N.storageBytes,objects:N.objects,...N.leftOut?{leftOut:N.leftOut}:{}},new Ya(ht)}let Ue=de=>`${de} Nothing was written.`,[xe,...di]=je;if(xe)throw Et=di.map(({code:de,message:xt})=>({code:de,message:Ue(xt)})),xe.stop?Pe.of({...xe.stop,message:Ue(xe.message)}):new Pe(xe.code,Ue(xe.message));hn=_i(Bt.api),await fe(yr,N,Z)},me=()=>{let y=Fp(ae);return y?{carried:y}:{}},fe=async(y,T,P)=>{let N=Fg(y,T,n.target,P);if(n.yes){s(` --yes: written without the question: ${N}`),u().confirm("volume");return}if(process.stdin.isTTY!==!0)throw new Pe("CONFIRMATION_UNAVAILABLE",`A clone of the whole org asks before it writes ${N}, and no terminal is there to answer: give --yes to write it. Nothing was written.`);let I=await Lf(Pg(N),void 0,le.signal);if(le.signal.aborted)throw new Js("interrupted at its question: the clone stopped before it wrote anything");if(!I)throw new Pe("WRITE_DECLINED","The clone of the whole org was declined at its question. Nothing was written.");u().confirm("volume")},Ce=async y=>{if(o)return W(y);let T=df(y.objects),P;try{P=await as(Rt)}catch(je){P={unread:V(je)}}let N=ps({firing:Vn(se,void 0,_e).firing},(je,Ue)=>_e(je,Ue)).perRecord,I=ga(T,P,ds(T,N));s("");for(let je of ja(T,I,n.target))s(je);let Z="unread"in P?await tr(Rt).catch(je=>({unread:V(je)})):P.dailyApiRequests,Ge;if(v&&T.totalRows>0){let je=new Set(T.objects.map(({objectApiName:xe})=>xe)),Ue={written:y.objects.map(({objectApiName:xe})=>xe).filter(xe=>je.has(xe)),running:{firing:Vn(se,void 0,_e).firing}};try{De={ask:Ue,estimate:await v.scope(Ue)}}catch(xe){Ge=pa(xe).replace(/ Nothing was written\.$/,"")}}let Ot=ha({plan:T,updatedAfterInsert:[...yt],...y.readBack!==void 0?{readBack:y.readBack}:{},...De?{checkpoint:De.estimate}:{},mute:Go(x?.plan),...Sa(he?.ofRun),sentBefore:$().target,budget:Z,target:n.target});if(hn=_i(Ot.api),re={target:Ot.api},s(my(Ot.api,n.target)),De)for(let je of Nd(De.estimate))s(je);let ht=yi(se),Bt,Ze;if(ht.length>0){let je=await wa(Rt).catch(xe=>({unread:V(xe)})),Ue=ya(T,ht,je);for(let xe of ka(Ue,n.target))s(xe);Bt=Oa(Ue,n.target),Ze=Ue.map(xe=>({limit:xe.limit,emails:xe.emails}))}let st=Ra(se,ba(T));st!==void 0&&s(` emails: not counted, ${st} could not be read`);let _t=n.roots?.query?.roots,wr=Cg(y,_t,{taken:T.totalRows,room:n.maxTotal,each:je=>`about ${Math.ceil(je)} records`,past:`the ${n.maxTotal} --max-total holds the run to`}),yr=T.totalRows>n.maxTotal?wr?Jb(T.totalRows,n.maxTotal,wr,n.dryRun):cc(T.totalRows,n.maxTotal,n.dryRun):void 0,br=I.verdict==="exceeds"?Cg(y,_t,{taken:I.estimateMB,room:I.remainingMB,each:je=>`about ${Ht(je)} MB`,past:`what ${n.target} has left`}):void 0,io=br?Qb(I,n.target,br):Aa(I,n.target),Rr=Ge??(Ot.stop?.refusal!==void 0?Ms(Ot.stop.refusal):void 0),ao=uf(Ot.api,n.target)?.replace(/ Nothing was written\.$/,""),yn=[[Tn,Rr],["MAX_TOTAL_EXCEEDED",yr],["STORAGE_EXCEEDED",io],["EMAILS_EXCEEDED",Bt],[cf,ao]].flatMap(([je,Ue])=>Ue!==void 0?[{code:je,message:Ue}]:[]);if(y.dryRun){for(let di of yn)s(` ${Nn(di)}`);Ve.push(...yn);let je=qe&&he?Of(he.ofRun.senders,T):[],Ue=kf(je);Ue!==void 0&&s(Ue);let xe=ds(T,N);ct={totalRows:T.totalRows,storageBytes:T.storageBytes,...xe>0?{automationBytes:xe}:{},objects:T.objects,...T.leftOut?{leftOut:T.leftOut}:{},...Ze!==void 0?{emails:Ze}:{},...st!==void 0?{emailsUncounted:st}:{},...je.length>0?{emailSendersOfNothingWritten:je}:{}};return}if(yn.length>0){let je=Ue=>`${Ue} Nothing was written.`;throw Et=yn.slice(1).map(({code:Ue,message:xe})=>({code:Ue,message:je(xe)})),new Pe(yn[0].code,je(yn[0].message))}},ot=n.dryRun||n.rehearse?void 0:await Xp(()=>Rt.identity(),"sandforge clone");s(`
913
- executing\u2026 (${n.dryRun?"DRY-RUN":"REAL"}${n.tables?", WHOLE TABLES":""}${o?", WHOLE ORG":""}${n.upsert?", UPSERT":""}${n.expandOrphans?", EXPAND-ORPHANS":""}${n.applyAssignmentRules?", ASSIGNMENT-RULES":""}${n.files?", FILES":""}${n.pageSize!==void 0?`, READ IN PAGES OF ${n.pageSize}`:""})`);let zn=y=>y.apiCalls===void 0?y:{...y,apiCalls:y.apiCalls+Un},no=(y,T,P={},N)=>({tool:"sandforge-clone",version:1,source:n.source,target:n.target,...g?{targetOrgId:g}:{},...n.tables?{objects:n.tables}:o?{wholeOrg:!0}:n.roots?{roots:Ab(n.roots,L)}:{record:n.record},dryRun:n.dryRun,upsert:n.upsert,expandOrphans:n.expandOrphans,applyAssignmentRules:n.applyAssignmentRules,files:n.files!==void 0,...n.choicesFrom?{choices:{from:n.choicesFrom.flag,file:n.choicesFrom.path,...n.decisions?{decisions:n.decisions}:{}}}:{},graph:Ls(L,Re),...Gn?{sample:Mg(Gn)}:{},targetAutomation:he?.ofRun.read?{...nt,deliverability:he.ofRun.read.reading}:nt,...b?{mutedAutomation:b}:n.dryRun?Qi(x):{},...ve(),removalRisks:At,targetGaps:ua(dt,Xt),...Mb(n.dryRun,dt,y.gaps,pt),...$t.length>0?{neutralizedUpsertKeys:$t}:{},result:{...N?{status:N}:{},...Bb(y,n.readCeiling),...ot?{runUserId:ot}:{}},...n.dryRun&&ct!==void 0?{writePlan:ct}:{},...uc(),...n.dryRun?Oi(Ve):{},elapsedMs:Fe(t,T.getTime()),finishedAt:T.toISOString(),...ne&&wn?{journal:ne}:{},...oi()!==void 0?{part:oi()}:{},...ii.length>0?{bulkJobsPastMute:ii}:{},...P}),jm=y=>{let T=eo?.question;return{tool:"sandforge-clone",version:1,source:n.source,target:n.target,dryRun:!0,anonymize:n.anonymize,files:n.files!==void 0,graph:Ls(L,Re),result:{wouldInsertCount:ct?.totalRows??y.totalRows,failedCount:0},...ct!==void 0?{writePlan:ct}:{},targetAutomation:he?.ofRun.read?{...nt,deliverability:he.ofRun.read.reading}:nt,...Qi(x),removalRisks:At,targetGaps:ua(dt,Xt),wholeOrg:{...y.sample?{sample:Mg(y.sample)}:{},wouldInsert:y.wouldInsert,totalRows:y.totalRows,requests:{target:y.targetRequests,source:y.sourceRequests},...y.bulkBatches?{bulkBatches:y.bulkBatches}:{},storage:y.storage,...y.files?{files:y.files}:{},durationSeconds:y.durationSeconds,leftOut:y.leftOut,personalAsIs:y.personalAsIs,...y.personAccountsAsBusiness!==void 0?{personAccountsAsBusiness:y.personAccountsAsBusiness}:{},managedPackages:T?.managedPackages??[],...T?.contactPointsBlanked!==void 0?{contactPointsBlanked:T.contactPointsBlanked}:{},...T?.carried?{carried:T.carried}:{},...T&&ct&&Ve.length===0?{question:Pg(Fg(T,ct,n.target,Gn))}:{}},...uc(),...ve(),...Oi(Ve),elapsedMs:Fe(t)}},mn,gr,uc=()=>{let y=n.dryRun?De?.estimate:gr??mn;return y!==void 0?{checkpoint:y}:{}},ri=async()=>{if(!(!v||!mn||gr)){try{gr=await v.settle(mn,Je)}catch(y){gr=mn,s(`warning: the checkpoint '${mn.name}' taken before the run, which wrote nothing, could not be deleted (${V(y)}): delete it with ${qt("checkpoint")} delete --org ${n.target} --checkpoint ${mn.checkpointId}`)}for(let y of Md(gr))s(y)}},wn,It;if(G&&g!==void 0){if(ne&&n.resume)await G.resumingAt(ne),It=(await G.headAt(ne))?.journalId;else{It=`sandforge-clone-${new Date(t).toISOString().replace(/[:.]/g,"-")}-${Us().slice(0,8)}`,ne=G.pathOf(It);let y=Ss(ne,{journalId:It,ranFrom:"commandLine",target:n.target});"lock"in y&&(e.journalLock=y.lock),await G.begin(It,g,new Date,{sourceOrgId:n.source,fingerprint:ie,targetSalesforceOrgId:g,...n.record?{recordId:n.record}:{},...n.muteAutomation?{muteAutomation:!0}:{},...n.files?{files:n.files}:{},startedWith:{graph:L,config:ae}},ot)}wn=G.openAt(ne),s(Kt()?`journal: ${ne}`:`journal: ${ne} (--resume ${ne} takes the run up if it stops)`)}let oi=()=>wn&&wn.partCount>0?wn.partCount-1:void 0,$m=async()=>{if(!n.sample||n.dryRun||n.resume||It===void 0)return;let y=Ga(te,It);if(q&&Yt(y)&&!Yt(q.dir))try{Vg(y,q.dir);return}catch{}await pp(y)},mr=async(y,T)=>{if(!G||!ne||!wn)return;wn.close();let P=ne;try{!T&&U?await G.stopAt(P,U.status,U.forgeId):!T&&!n.resume?(Ws(P,{force:!0}),Ws(P.replace(/\.ndjson$/,".end.json"),{force:!0}),await $m()):await G.stopAt(P,y,`${It??"run"}#${oi()??0}`)}catch(N){process.stderr.write(`The journal ${P} could not be ended (${V(N)}).
914
- `)}finally{e.journalLock?.release()}},lc;if(n.sample){let y=n.sample,T=q;if(q&&!n.dryRun&&It!==void 0)try{T=await fp(q,te,It)}catch(I){await mr("failure",!1),process.stderr.write(`The plan of --fit-plan ${q.dir} could not be moved beside the run's journal (${V(I)}): keep it in ${Kd(te,"forge-samples")}, where its dry run put it. Nothing was written.
915
- `),process.exit(1)}if(T)s(`sample: takes up the plan ${T.dir}, drawn ${T.manifest.drawnAt}: no root is drawn again`);else if(n.resume)s("sample: the run taken up goes on with the plan its journal names");else{s(lR(L,y.options,n.source));let I=n.dryRun?void 0:await lp(te,M,new Date).catch(()=>{});I instanceof sr&&s(` a dry run drew a plan of this setup at ${I.manifest.drawnAt}: this run draws its own; --fit-plan ${I.dir} writes that one's records instead`)}let P=ps({firing:Vn(se,void 0,_e).firing},(I,Z)=>_e(I,Z)).perRecord,N=T||n.resume?void 0:await tr(pr(l,n.source)).catch(gn);lc={options:Zg(y),budget:async()=>Zb({storage:await as(Rt).catch(gn),sample:y,target:n.target,automation:P}),keepAt:n.dryRun||It===void 0?cp(te,M):Ga(te,It),fingerprint:M,...T?{plan:T}:{},...N&&"remaining"in N?{sourceRequestsLeft:N.remaining}:{},onProgress:hR(s)}}let jt,vm=Wb(L),si=new lr(Dt),fc=!1,ro=y=>{if(!n.summary)return;let T=tc(n.summary,y);T&&!fc&&(fc=!0,process.stderr.write(`The summary could not be written to ${n.summary} (${T}).
916
- `))},pc=-1,Em=()=>{let y=si.summarySoFar();if(!y)return;let T=y.successCount+y.linkedCount+y.updatedCount+y.failedCount;T!==pc&&(pc=T,ro(no(zn(y),new Date,{running:!0})))};Nt.executor=si,await wt(()=>mr("cancelled",!1));let oo,ii=[],Im,hc=()=>Im??=$O(Xe,n.target,s).then(y=>{ii=y.map(({objectApiName:T,jobId:P})=>({objectApiName:T,...P?{jobId:P}:{}}))}),xm=async y=>{if(await Ce(y),y.dryRun||n.dryRun)return;if(v&&De&&!mn){let N=De,I=await ff(()=>v.take(N.ask,N.estimate,{signal:le.signal}));if("stop"in I)throw I.stop.code!==Tn?new Vs(Cd(I.stop)):new Pe(Tn,Cd(I.stop));mn=I.checkpoint;for(let Z of wg(I.checkpoint,n.target,Oe))s(Z)}if(!x?.prepared||oo)return hn;let T=await x.prepared.acquire(`sandforge clone ${t}`).catch(async N=>{if(!Cr(N))throw N;return k({outcome:"stopped",code:N.code,context:u().context()}),await ri(),oe(N.refusal)});oo=T,b=T.outcome;let P=he?.afterLease(T.outcome,n.acceptEmails);if(P)throw new Pe(P.code,P.message);return{...hn,lease:{assigned:T.outcome.assigned.length,giveBack:async()=>(await hc(),T.release())}}};try{let y=await si.execute(L,n.source,n.target,T=>{let P=vm(T);P&&s(P),n.summary&&RO.has(T.status)&&Em()},RR({...o?My(n,ae,L,Ct,T=>ue.personalFields(T),lc):n.tables?xy(n,ae,L,Ct,T=>ue.personalFields(T)):Lg(n,L,Ct,T=>ue.personalFields(T),Mt),beforeWrite:xm},wn)).finally(async()=>{if(oo){await hc(),b=await oo.release();for(let T of Xn(b,n.target))s(T)}});jt=zn(y),await ri(),n.pageSize!==void 0&&s(`read in pages of ${n.pageSize}: ${vt.statements} statement(s) through the org's cursor, ${vt.pages} page(s) answered`)}catch(y){if(y instanceof Ya){let st=jm(y.dryRun);n.json?process.stdout.write(`${JSON.stringify(st,null,2)}
917
- `):console.log(`
918
- done in ${st.elapsedMs}ms`),Ve.length>0&&process.exit(1);return}(y instanceof Vs||y instanceof Js)&&(k({outcome:"stopped",code:Ni,context:u().context()}),await mr("cancelled",!1),s(y.message),process.exit(vr(ft??"SIGINT"))),await ri();let T=y instanceof Pe?y:n.sample?ls(y,n.resume?"resume":"draw"):void 0,P=y instanceof jn?y:void 0,N=T??P,I=N?void 0:ap(y),Z=I?Ci(I):void 0,Ge=Z?Mi(Z):[],Ot=ft!==void 0||y instanceof be,ht=N?"stopped":Ot?au(I,Ge):"failure";k({outcome:ht,...N?{code:N.code}:ht==="stopped"?{code:iu}:{},...Z?{objects:Ge,...m?{source:{origin:"org",orgId:m}}:{},carried:Li(Z)}:{},...Bi(I?.contactPoints),context:u().context(I?.decisionsApplied)});let Bt=I!==void 0&&I.successCount+I.updatedCount+I.linkedCount>0;if(await mr(Ot?"cancelled":"failure",Bt),N){let st={code:N.code,message:N.message,...T?.sample?{sample:T.sample}:{}};oe(st,T?Et:[],Bg(N.code))}let Ze=I;if(Ze&&(ft!==void 0||y instanceof be)){let st=no(zn(Ze),new Date,{interrupted:!0});if(ro(st),n.json)process.stdout.write(JSON.stringify(st,null,2)+`
919
- `);else{console.log("");for(let _t of Ig(Ze,n.dryRun,n.readCeiling))console.log(_t)}s(OO(n.summary)),process.exit(vr(ft??"SIGINT"))}throw Ze&&ro(no(zn(Ze),new Date,{error:V(y)})),y}finally{e.release?.()}await mr("success",!0);let gc=Ci(jt),so=$o(jt);k({outcome:so,objects:Mi(gc),...m?{source:{origin:"org",orgId:m}}:{},carried:Li(gc),...Bi(jt.contactPoints),context:u().context(jt.decisionsApplied)});let mc=new Date,Pm=Fe(t,mc.getTime()),wc=no(jt,mc,{},so);ro(wc);let ai;if(n.remapCsv){let y=["sourceId,targetId"];for(let[T,P]of Object.entries(jt.remapTable))y.push(`"${T.replace(/"/g,'""')}","${P.replace(/"/g,'""')}"`);try{Qg(n.remapCsv,y.join(`
920
- `)+`
921
- `,{encoding:"utf8",flag:"wx"}),s(`remap-csv: wrote ${Object.keys(jt.remapTable).length} mappings to ${n.remapCsv}`)}catch(T){ai=T?.code==="EEXIST"?`--remap-csv refuses to overwrite existing file: "${n.remapCsv}"`:`--remap-csv ${n.remapCsv} could not be written: ${V(T)}`}}if(n.json)process.stdout.write(JSON.stringify(wc,null,2)+`
922
- `);else{console.log(""),console.log(`status: ${so}`);let y=(x?.plan?.assign.length??0)>0;for(let T of Ig(jt,n.dryRun,n.readCeiling,y))console.log(T);if(jt.roots){console.log("");let T={source:n.source,target:n.target,dryRun:n.dryRun,...n.roots?.plan!==void 0?{plan:n.roots.plan}:{},...n.resume!==void 0?{resumed:!0}:{}};for(let P of $b(jt,T))console.log(P)}if(jt.sample){console.log("");for(let T of uR(jt.sample,n.source))console.log(T)}console.log(`
923
- done in ${Pm}ms`)}ai!==void 0&&(process.stderr.write(`${ai}: the summary names what the run created.
924
- `),process.exit(1));let yc=Hc(so,n.failOnPartial||o);yc!==0&&process.exit(yc)}function PO(r){return r instanceof zc?{line:r.message,exitCode:1}:r instanceof Error&&r.message.startsWith("Invalid SF org alias:")?{line:r.message,exitCode:2}:{line:`FATAL: ${r instanceof Error?r.stack??r.message:String(r)}`,exitCode:1}}/sandforge-clone\.[cm]?[jt]s$/.test(process.argv[1]??"")&&(dh(),EO().catch(r=>{let e=PO(r);process.stderr.write(`${e.line}
925
- `),process.exit(e.exitCode)}));export{id as a,Fe as b,Jr as c,Fd as d,pg as e,hg as f,gg as g,mg as h,Nd as i,Ms as j,Cd as k,wg as l,Md as m,DS as n,Bd as o,yg as p,my as q,Ry as r,Xg as s,ky as t,Sy as u,Ty as v,jy as w,$y as x,vy as y,Iy as z,xy as A,Vd as B,Py as C,Ny as D,Cy as E,My as F,By as G,Ly as H,Qy as I,Zy as J,eb as K,nb as L,rb as M,$g as N,vg as O,sb as P,db as Q,ub as R,hb as S,gb as T,mb as U,wb as V,Wd as W,NA as X,bb as Y,Rb as Z,qd as _,tm as $,kb as aa,Eg as ba,Sb as ca,Tb as da,Ig as ea,Ab as fa,$b as ga,Ib as ha,xb as ia,Pb as ja,Fb as ka,Nb as la,Cb as ma,Mb as na,Bb as oa,Lb as pa,Wb as qa,Db as ra,_b as sa,Gb as ta,zb as ua,fr as va,Pg as wa,Fg as xa,Ng as ya,Xr as za,Kb as Aa,Vb as Ba,rm as Ca,Jb as Da,Qb as Ea,Cg as Fa,Zb as Ga,dR as Ha,Mg as Ia,cR as Ja,uR as Ka,lR as La,hR as Ma,Bg as Na,mR as Oa,cm as Pa,wR as Qa,Lg as Ra,yR as Sa,bR as Ta,RR as Ua,OR as Va,Xs as Wa,kR as Xa,un as Ya,Zr as Za,TR as _a,AR as $a,ER as ab,Qd as bb,xR as cb,CA as db,Yd as eb,Dg as fb,FR as gb,dc as hb,NR as ib,CR as jb,MR as kb,fm as lb,BR as mb,DR as nb,cc as ob,ln as pb,_s as qb,zR as rb,Gd as sb,VR as tb,JR as ub,qs as vb,Zd as wb,ym as xb,QR as yb,YR as zb,XR as Ab,ec as Bb,MA as Cb,ZR as Db,eO as Eb,ei as Fb,ti as Gb,ni as Hb,nO as Ib,Rm as Jb,Om as Kb,km as Lb,Sm as Mb,oO as Nb,sO as Ob,Am as Pb,tc as Qb,iO as Rb,dO as Sb,cO as Tb,uO as Ub,Hs as Vb,hO as Wb,yO as Xb,bO as Yb,OO as Zb,zg as _b,Hg as $b,kO as ac,SO as bc,jO as cc,$O as dc,EO as ec,PO as fc};