sandforge 1.85.0 → 1.86.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (274) hide show
  1. package/README.md +1 -1
  2. package/lib/{chunk-THYQOG24.mjs → chunk-22L43JMK.mjs} +1 -1
  3. package/lib/{chunk-U4S27YRP.mjs → chunk-2LSGWTWX.mjs} +1 -1
  4. package/lib/{chunk-MRN72UEO.mjs → chunk-2YJJTQNC.mjs} +1 -1
  5. package/lib/chunk-34SMB5PA.mjs +10 -0
  6. package/lib/chunk-35B73566.mjs +7 -0
  7. package/lib/{chunk-YZKE6D3K.mjs → chunk-35IJ4WEU.mjs} +1 -1
  8. package/lib/chunk-3EHPAFKV.mjs +7 -0
  9. package/lib/{chunk-3OKDWZ32.mjs → chunk-3HAVVEXF.mjs} +1 -1
  10. package/lib/{chunk-32ZB5ICW.mjs → chunk-3I6FXFCN.mjs} +1 -1
  11. package/lib/{chunk-JFVY66BS.mjs → chunk-3KJCSYXY.mjs} +1 -1
  12. package/lib/{chunk-ULEYGOZU.mjs → chunk-3L6DVNCR.mjs} +1 -1
  13. package/lib/chunk-3LRFPGYZ.mjs +7 -0
  14. package/lib/{chunk-GHUA6OQQ.mjs → chunk-3MVWGL5A.mjs} +1 -1
  15. package/lib/{chunk-SF52ZSIV.mjs → chunk-4CSBZZAL.mjs} +1 -1
  16. package/lib/{chunk-FBYFCKPG.mjs → chunk-4NSXPONF.mjs} +1 -1
  17. package/lib/{chunk-A3QNSALB.mjs → chunk-4VLP6RHC.mjs} +1 -1
  18. package/lib/{chunk-TWYNQ2OO.mjs → chunk-4XROG5CT.mjs} +1 -1
  19. package/lib/chunk-54V4FVEY.mjs +7 -0
  20. package/lib/chunk-55OJJT2Q.mjs +7 -0
  21. package/lib/{chunk-JRI6A24G.mjs → chunk-5EHHQ5UX.mjs} +1 -1
  22. package/lib/{chunk-VPGX5Z5D.mjs → chunk-5JMQXHJ2.mjs} +1 -1
  23. package/lib/{chunk-CI2O7WBH.mjs → chunk-65AMXOQU.mjs} +1 -1
  24. package/lib/{chunk-5T3LFDJ5.mjs → chunk-6HHSAPIM.mjs} +1 -1
  25. package/lib/chunk-6KVBCFVS.mjs +7 -0
  26. package/lib/chunk-6NG7C2U3.mjs +476 -0
  27. package/lib/{chunk-F2424IKX.mjs → chunk-6ROL3KBM.mjs} +1 -1
  28. package/lib/{chunk-7ZYCRIHE.mjs → chunk-72AWCN7U.mjs} +1 -1
  29. package/lib/{chunk-MQLTEXB7.mjs → chunk-7KHA5UIQ.mjs} +1 -1
  30. package/lib/chunk-7O6EFNQS.mjs +10 -0
  31. package/lib/{chunk-73SLYGWD.mjs → chunk-A2CH2QGX.mjs} +1 -1
  32. package/lib/chunk-A2TXLAC3.mjs +276 -0
  33. package/lib/chunk-ALWVNR34.mjs +7 -0
  34. package/lib/{chunk-JBOGAUGH.mjs → chunk-ATBQIE2V.mjs} +1 -1
  35. package/lib/{chunk-C2MHMI7U.mjs → chunk-ATQML7ZK.mjs} +1 -1
  36. package/lib/chunk-AVY742BJ.mjs +7 -0
  37. package/lib/{chunk-VLAU5QQT.mjs → chunk-AXTB2HJS.mjs} +1 -1
  38. package/lib/chunk-BBZUGKBZ.mjs +10 -0
  39. package/lib/chunk-BIDXK7KA.mjs +7 -0
  40. package/lib/{chunk-KYLHS74X.mjs → chunk-BLMJ4WVI.mjs} +1 -1
  41. package/lib/{chunk-A7YP27GQ.mjs → chunk-BNHJCJJM.mjs} +1 -1
  42. package/lib/{chunk-ZDMSTL2L.mjs → chunk-BNPQEQXC.mjs} +1 -1
  43. package/lib/chunk-C5AUNG6T.mjs +37 -0
  44. package/lib/{chunk-LY6EPMIP.mjs → chunk-C5EQ7GFC.mjs} +1 -1
  45. package/lib/{chunk-LOO42EW5.mjs → chunk-C7CKDZMC.mjs} +62 -62
  46. package/lib/{chunk-ZP3WJGS3.mjs → chunk-CB4U22NR.mjs} +1 -1
  47. package/lib/chunk-CJAWKLAL.mjs +7 -0
  48. package/lib/chunk-CL75DEMQ.mjs +9 -0
  49. package/lib/{chunk-7L6FE5PP.mjs → chunk-CLUNF4FK.mjs} +1 -1
  50. package/lib/chunk-CSMGP53U.mjs +7 -0
  51. package/lib/{chunk-S6BMJSLD.mjs → chunk-CT324C7I.mjs} +1 -1
  52. package/lib/{chunk-YXOPKGDX.mjs → chunk-CZXDJXQP.mjs} +1 -1
  53. package/lib/{chunk-PGG4ULEW.mjs → chunk-D2X6U3MS.mjs} +1 -1
  54. package/lib/{chunk-FG4Y4ZVL.mjs → chunk-DAUX63UB.mjs} +1 -1
  55. package/lib/chunk-DB7JNALQ.mjs +10 -0
  56. package/lib/chunk-DDNCJVZ2.mjs +17 -0
  57. package/lib/{chunk-YGE4AUXG.mjs → chunk-DLSU66MY.mjs} +1 -1
  58. package/lib/{chunk-DCJBP3LE.mjs → chunk-DO6PSHQZ.mjs} +1 -1
  59. package/lib/{chunk-ROTDZKOE.mjs → chunk-DUBECLZV.mjs} +1 -1
  60. package/lib/{chunk-SES5HPBZ.mjs → chunk-DYHF6DNT.mjs} +1 -1
  61. package/lib/chunk-E5FSPXYH.mjs +930 -0
  62. package/lib/{chunk-QAXKUEJT.mjs → chunk-EGL3I3IX.mjs} +1 -1
  63. package/lib/chunk-EIYMQPMG.mjs +7 -0
  64. package/lib/{chunk-AX3YF7SC.mjs → chunk-EUIALBMX.mjs} +1 -1
  65. package/lib/{chunk-57QRXYAZ.mjs → chunk-FI3R5ZOQ.mjs} +1 -1
  66. package/lib/{chunk-FCZDWGQI.mjs → chunk-FM4QCTO7.mjs} +1 -1
  67. package/lib/{chunk-74HZ274R.mjs → chunk-FRSIEASH.mjs} +1 -1
  68. package/lib/{chunk-G6IYOZEH.mjs → chunk-FV6MOSHD.mjs} +1 -1
  69. package/lib/chunk-FYG47CNA.mjs +7 -0
  70. package/lib/chunk-GB6W4Q56.mjs +7 -0
  71. package/lib/chunk-GEV2DCMK.mjs +7 -0
  72. package/lib/{chunk-NZJXEULY.mjs → chunk-GFB2DNCB.mjs} +1 -1
  73. package/lib/chunk-GFGMGFSH.mjs +7 -0
  74. package/lib/{chunk-EFHDE7W4.mjs → chunk-GIFQXB2Q.mjs} +1 -1
  75. package/lib/{chunk-P6A22FMQ.mjs → chunk-GP5J3DGS.mjs} +1 -1
  76. package/lib/chunk-GQZEX7LH.mjs +231 -0
  77. package/lib/{chunk-BRN42U26.mjs → chunk-GYDTM62J.mjs} +1 -1
  78. package/lib/{chunk-GNCEHAJY.mjs → chunk-GYFIXUJG.mjs} +1 -1
  79. package/lib/chunk-GZW2GNFK.mjs +7 -0
  80. package/lib/chunk-H6BHWAX7.mjs +8 -0
  81. package/lib/{chunk-GUYEXPJ4.mjs → chunk-HDDJ3CVN.mjs} +1 -1
  82. package/lib/{chunk-3GATEVHC.mjs → chunk-HDWB4ZOG.mjs} +1 -1
  83. package/lib/chunk-HGVPBJR6.mjs +7 -0
  84. package/lib/{chunk-55VBV2WK.mjs → chunk-HLROVOR6.mjs} +1 -1
  85. package/lib/{chunk-HV3TDLFR.mjs → chunk-HUOR4M2L.mjs} +1 -1
  86. package/lib/chunk-HZCS6EED.mjs +8 -0
  87. package/lib/{chunk-WZX6VCIT.mjs → chunk-HZUI56KZ.mjs} +1 -1
  88. package/lib/chunk-IAB5H7WN.mjs +7 -0
  89. package/lib/{chunk-RY7WUJXH.mjs → chunk-IQ5UKRHU.mjs} +1 -1
  90. package/lib/{chunk-OUWR5M5G.mjs → chunk-IRQ4WANV.mjs} +1 -1
  91. package/lib/{chunk-F44EHXLI.mjs → chunk-IT3DGX37.mjs} +1 -1
  92. package/lib/chunk-J347SPU6.mjs +49 -0
  93. package/lib/{chunk-IZ2M2RGO.mjs → chunk-JANBNTR5.mjs} +1 -1
  94. package/lib/chunk-JFXQZPRY.mjs +9 -0
  95. package/lib/{chunk-VKA5OZBJ.mjs → chunk-JRLYWVF4.mjs} +1 -1
  96. package/lib/{chunk-FM5ESRH6.mjs → chunk-JSNMUTY6.mjs} +1 -1
  97. package/lib/chunk-JTNJKSAA.mjs +7 -0
  98. package/lib/{chunk-4D6OHSX3.mjs → chunk-JV2LAKWQ.mjs} +1 -1
  99. package/lib/{chunk-BY42YL4D.mjs → chunk-JV7K2ZHK.mjs} +1 -1
  100. package/lib/{chunk-A6IJUOLB.mjs → chunk-K4TQ7YHX.mjs} +1 -1
  101. package/lib/chunk-K5PUMHZU.mjs +7 -0
  102. package/lib/chunk-KH4KLCYG.mjs +7 -0
  103. package/lib/{chunk-FZF6FB65.mjs → chunk-KQVLZVOP.mjs} +1 -1
  104. package/lib/chunk-KWUS7UAV.mjs +19 -0
  105. package/lib/{chunk-2UUSF32M.mjs → chunk-L6G73FXM.mjs} +1 -1
  106. package/lib/{chunk-LUNGNCM3.mjs → chunk-LG466Q5H.mjs} +1 -1
  107. package/lib/{chunk-YTBM3TSW.mjs → chunk-LHNAR6FC.mjs} +1 -1
  108. package/lib/chunk-LT4GHEI2.mjs +7 -0
  109. package/lib/{chunk-P3OYE2FS.mjs → chunk-MR262Y3B.mjs} +1 -1
  110. package/lib/{chunk-TSTCHIBU.mjs → chunk-NCCHOV2N.mjs} +1 -1
  111. package/lib/chunk-NICRSGLS.mjs +7 -0
  112. package/lib/chunk-NV5QA2HY.mjs +7 -0
  113. package/lib/{chunk-6HAKOS6W.mjs → chunk-O3GIN5TU.mjs} +1 -1
  114. package/lib/chunk-O6FHK6NQ.mjs +13 -0
  115. package/lib/{chunk-OXIIKAUZ.mjs → chunk-O7YIEFG7.mjs} +1 -1
  116. package/lib/chunk-OCUVAA5E.mjs +7 -0
  117. package/lib/chunk-OLCS7JCT.mjs +14 -0
  118. package/lib/chunk-ON7Y63FK.mjs +9 -0
  119. package/lib/{chunk-K2WOT75I.mjs → chunk-OO2WY3UB.mjs} +1 -1
  120. package/lib/{chunk-3EOIAC2M.mjs → chunk-OT2NHL2V.mjs} +1 -1
  121. package/lib/{chunk-BK5SRDAD.mjs → chunk-P2M5ZXWU.mjs} +1 -1
  122. package/lib/{chunk-DCZYWMSA.mjs → chunk-P4YOHLZ4.mjs} +1 -1
  123. package/lib/chunk-PBHDPTT6.mjs +343 -0
  124. package/lib/chunk-PE7CHD2W.mjs +7 -0
  125. package/lib/{chunk-LU7M5URW.mjs → chunk-PIQ2I67B.mjs} +1 -1
  126. package/lib/chunk-PKYDNZJK.mjs +7 -0
  127. package/lib/chunk-PVZ72OOQ.mjs +7 -0
  128. package/lib/chunk-QACFTHJM.mjs +8 -0
  129. package/lib/{chunk-LNAZHI3J.mjs → chunk-QGVL5EW3.mjs} +1 -1
  130. package/lib/chunk-QHE2RUWX.mjs +7 -0
  131. package/lib/{chunk-4RNP65FV.mjs → chunk-RCW5BZNW.mjs} +1 -1
  132. package/lib/{chunk-OTKXTBTX.mjs → chunk-RJ6HHG7J.mjs} +1 -1
  133. package/lib/{chunk-IVDBVWKK.mjs → chunk-RPTEEI4R.mjs} +1 -1
  134. package/lib/chunk-RQW5S67A.mjs +7 -0
  135. package/lib/chunk-RTCMYMED.mjs +7 -0
  136. package/lib/chunk-RWVX7XSD.mjs +7 -0
  137. package/lib/{chunk-2UUS4IGB.mjs → chunk-RZOINFNL.mjs} +1 -1
  138. package/lib/chunk-SOOTWGMQ.mjs +7 -0
  139. package/lib/chunk-STQ2JMIZ.mjs +7 -0
  140. package/lib/{chunk-RC25QQVF.mjs → chunk-SUIPDW5O.mjs} +1 -1
  141. package/lib/{chunk-Z354SAEF.mjs → chunk-SZOJ7BEJ.mjs} +1 -1
  142. package/lib/{chunk-45375WT5.mjs → chunk-T542Z54E.mjs} +1 -1
  143. package/lib/chunk-TAN2CIRI.mjs +21 -0
  144. package/lib/{chunk-BGJBYDRW.mjs → chunk-TCNBINOG.mjs} +1 -1
  145. package/lib/chunk-TFDF3DBN.mjs +7 -0
  146. package/lib/{chunk-B5A4JHNN.mjs → chunk-TICZXC53.mjs} +1 -1
  147. package/lib/chunk-TLX45X5U.mjs +7 -0
  148. package/lib/{chunk-W6SLQZKQ.mjs → chunk-TMIV3IWH.mjs} +1 -1
  149. package/lib/chunk-TQ6HEJ73.mjs +11 -0
  150. package/lib/chunk-TTU5EQZ6.mjs +7 -0
  151. package/lib/chunk-TYUYPFDJ.mjs +7 -0
  152. package/lib/chunk-TZXYVMZC.mjs +7 -0
  153. package/lib/{chunk-4N425UJC.mjs → chunk-UCUFLFNK.mjs} +1 -1
  154. package/lib/chunk-UK3QLBHW.mjs +7 -0
  155. package/lib/{chunk-SKGAERV4.mjs → chunk-UM2B4GR7.mjs} +1 -1
  156. package/lib/chunk-UZFTTNOP.mjs +7 -0
  157. package/lib/chunk-V3AXSKSU.mjs +7 -0
  158. package/lib/chunk-VA6EEI6X.mjs +21 -0
  159. package/lib/{chunk-LSEM2BZH.mjs → chunk-VFKG2G37.mjs} +1 -1
  160. package/lib/chunk-VJNEW5MQ.mjs +7 -0
  161. package/lib/{chunk-EYFP3NA6.mjs → chunk-VKREON6Q.mjs} +1 -1
  162. package/lib/{chunk-TIVI2KGB.mjs → chunk-VNNDYPBL.mjs} +1 -1
  163. package/lib/{chunk-J3FJ3BWE.mjs → chunk-VRBETPHY.mjs} +1 -1
  164. package/lib/{chunk-UX4AOSMU.mjs → chunk-VT6P3X6R.mjs} +1 -1
  165. package/lib/{chunk-CUOWQMGW.mjs → chunk-VUTQY76O.mjs} +1 -1
  166. package/lib/chunk-WF5S4FW5.mjs +7 -0
  167. package/lib/{chunk-JHJDDQDE.mjs → chunk-WJGK6VGU.mjs} +1 -1
  168. package/lib/{chunk-IZREPWYQ.mjs → chunk-WJHMB3SL.mjs} +1 -1
  169. package/lib/{chunk-XZRON54U.mjs → chunk-WQCXOZEJ.mjs} +1 -1
  170. package/lib/{chunk-N2MXYD67.mjs → chunk-WVVFR4E3.mjs} +1 -1
  171. package/lib/{chunk-GG5I52UT.mjs → chunk-XBYXT74L.mjs} +1 -1
  172. package/lib/chunk-XJE3LJHP.mjs +7 -0
  173. package/lib/{chunk-3QCUSZIZ.mjs → chunk-XV4CVZYD.mjs} +1 -1
  174. package/lib/chunk-Y37ED7AS.mjs +7 -0
  175. package/lib/{chunk-MN3XBJPE.mjs → chunk-YGBNZYT4.mjs} +1 -1
  176. package/lib/{chunk-SBDF4AE5.mjs → chunk-YGTOX7IL.mjs} +1 -1
  177. package/lib/{chunk-SQM32AOQ.mjs → chunk-YJ27WHKR.mjs} +1 -1
  178. package/lib/chunk-YRULC27A.mjs +7 -0
  179. package/lib/{chunk-RMFU4BAL.mjs → chunk-YSVAHT4Q.mjs} +4 -4
  180. package/lib/chunk-YTOTMJTY.mjs +15 -0
  181. package/lib/{chunk-SU24AE3H.mjs → chunk-YZKZC62O.mjs} +1 -1
  182. package/lib/{chunk-LJNRN7MY.mjs → chunk-YZQN7BRB.mjs} +1 -1
  183. package/lib/{chunk-NMF55UBQ.mjs → chunk-Z5IUK2QO.mjs} +1 -1
  184. package/lib/{chunk-6ZWY36LK.mjs → chunk-ZEGSMW5A.mjs} +1 -1
  185. package/lib/{chunk-YV7JYHJP.mjs → chunk-ZIKLQZBG.mjs} +1 -1
  186. package/lib/chunk-ZVU7MD2S.mjs +7 -0
  187. package/lib/sandforge-autopilot.mjs +33 -27
  188. package/lib/sandforge-backup.mjs +19 -19
  189. package/lib/sandforge-checkpoint.mjs +1 -1
  190. package/lib/sandforge-cleanup.mjs +1 -1
  191. package/lib/sandforge-clone.mjs +1 -1
  192. package/lib/sandforge-compare.mjs +29 -16
  193. package/lib/sandforge-dataops.mjs +1 -1
  194. package/lib/sandforge-empty.mjs +11 -13
  195. package/lib/sandforge-env.mjs +105 -105
  196. package/lib/sandforge-frozen.mjs +1 -1
  197. package/lib/sandforge-mcp.mjs +2 -2
  198. package/lib/sandforge-monitor.mjs +1 -1
  199. package/lib/sandforge-pipeline.mjs +13 -13
  200. package/lib/sandforge-seed.mjs +1 -1
  201. package/lib/sandforge-sync.mjs +1 -1
  202. package/lib/sandforge-users.mjs +13 -15
  203. package/lib/sandforge.mjs +1 -1
  204. package/lib/sf/sandforge/dataops.mjs +2 -2
  205. package/lib/sfPlugin.mjs +1 -1
  206. package/oclif.manifest.json +1 -1
  207. package/package.json +1 -1
  208. package/lib/chunk-26EGXYZ4.mjs +0 -21
  209. package/lib/chunk-2JRVBXJL.mjs +0 -7
  210. package/lib/chunk-2METQHGG.mjs +0 -7
  211. package/lib/chunk-3XU7CEJQ.mjs +0 -7
  212. package/lib/chunk-4BQPAVMP.mjs +0 -14
  213. package/lib/chunk-4KMKOE77.mjs +0 -156
  214. package/lib/chunk-4RPA7Z52.mjs +0 -7
  215. package/lib/chunk-5C7LQXYS.mjs +0 -7
  216. package/lib/chunk-5EESNYE3.mjs +0 -8
  217. package/lib/chunk-6ZW6BLV5.mjs +0 -7
  218. package/lib/chunk-AAOMUI7S.mjs +0 -15
  219. package/lib/chunk-AIUAEBHR.mjs +0 -7
  220. package/lib/chunk-BD724WOH.mjs +0 -7
  221. package/lib/chunk-CRPLDXJU.mjs +0 -48
  222. package/lib/chunk-CSSOLHE3.mjs +0 -7
  223. package/lib/chunk-D63HEQ3B.mjs +0 -7
  224. package/lib/chunk-DN7YBILC.mjs +0 -21
  225. package/lib/chunk-DNE7JI3A.mjs +0 -11
  226. package/lib/chunk-EFHM2U4D.mjs +0 -7
  227. package/lib/chunk-EINEGS6E.mjs +0 -7
  228. package/lib/chunk-EM5EFMHA.mjs +0 -272
  229. package/lib/chunk-FH5UR35W.mjs +0 -7
  230. package/lib/chunk-FN7TOBJR.mjs +0 -7
  231. package/lib/chunk-HGJFATSI.mjs +0 -10
  232. package/lib/chunk-HOEE3PE5.mjs +0 -7
  233. package/lib/chunk-HV63UGL5.mjs +0 -7
  234. package/lib/chunk-JKFCGYJE.mjs +0 -7
  235. package/lib/chunk-KATBU46O.mjs +0 -7
  236. package/lib/chunk-LD34JNCC.mjs +0 -7
  237. package/lib/chunk-LPN4WYTP.mjs +0 -478
  238. package/lib/chunk-MAOUFJ47.mjs +0 -7
  239. package/lib/chunk-MB2DG66I.mjs +0 -13
  240. package/lib/chunk-NCASRA7L.mjs +0 -9
  241. package/lib/chunk-NEKNAILD.mjs +0 -7
  242. package/lib/chunk-NN2IO4WE.mjs +0 -7
  243. package/lib/chunk-O3ZQSWDN.mjs +0 -10
  244. package/lib/chunk-OFQOKSEW.mjs +0 -7
  245. package/lib/chunk-PP7PJXRJ.mjs +0 -341
  246. package/lib/chunk-PT2E2HFD.mjs +0 -7
  247. package/lib/chunk-PZBZ7MNC.mjs +0 -7
  248. package/lib/chunk-QBYK5XIT.mjs +0 -8
  249. package/lib/chunk-RFD6NPWJ.mjs +0 -8
  250. package/lib/chunk-RIIJJRGF.mjs +0 -7
  251. package/lib/chunk-RKTFFCNS.mjs +0 -7
  252. package/lib/chunk-RM5G4IP6.mjs +0 -19
  253. package/lib/chunk-RTPNK7OB.mjs +0 -7
  254. package/lib/chunk-RZXEO5IE.mjs +0 -7
  255. package/lib/chunk-SAHGDSZQ.mjs +0 -37
  256. package/lib/chunk-SRPWW4A2.mjs +0 -10
  257. package/lib/chunk-SVNSAHG3.mjs +0 -7
  258. package/lib/chunk-T63U4OZJ.mjs +0 -7
  259. package/lib/chunk-TE2W76II.mjs +0 -10
  260. package/lib/chunk-TEIBWMJM.mjs +0 -7
  261. package/lib/chunk-TFGJDZFE.mjs +0 -7
  262. package/lib/chunk-TG52WNGV.mjs +0 -10
  263. package/lib/chunk-TQONVFI3.mjs +0 -7
  264. package/lib/chunk-TW3N6W5Z.mjs +0 -7
  265. package/lib/chunk-UZMLPKW6.mjs +0 -7
  266. package/lib/chunk-WB2RIVO3.mjs +0 -7
  267. package/lib/chunk-WQO7RXEB.mjs +0 -926
  268. package/lib/chunk-X3MBY2RX.mjs +0 -7
  269. package/lib/chunk-XMJRXXUN.mjs +0 -7
  270. package/lib/chunk-YNMU5I7P.mjs +0 -7
  271. package/lib/chunk-YSQJKIO6.mjs +0 -7
  272. package/lib/chunk-YVVPJRZC.mjs +0 -7
  273. package/lib/chunk-ZLQHBI6V.mjs +0 -9
  274. package/lib/chunk-ZRUDYB7O.mjs +0 -7
@@ -0,0 +1,930 @@
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 ed,c as Ep,d as Ip}from"./chunk-IQ5UKRHU.mjs";import{b as Ch}from"./chunk-VT6P3X6R.mjs";import{d as Oa,k as Af,o as jf,q as ka,r as $f}from"./chunk-ALWVNR34.mjs";import{a as At,d as Qa,e as Kt,f as In,i as ks,j as jt,k as it}from"./chunk-QHE2RUWX.mjs";import{a as ko,b as xi,c as Tt,d as Ln,e as Pi,f as on,g as So,h as Fi,j as Ci}from"./chunk-6FARZYMJ.mjs";import{b as uu,f as Fr,h as lu,k as tr}from"./chunk-DDNCJVZ2.mjs";import{$ as th,$a as Ih,A as jp,Aa as dd,B as $p,Ba as fh,C as vp,Ca as ph,D as ar,Da as hh,E as Ts,Ea as cd,F as xn,Fa as gh,G as xp,H as Pp,Ha as mh,I as Fp,Ia as wh,J as td,Ja as yh,K as Cp,L as Np,M as Mp,N as Bp,Na as bh,O as Lp,Oa as Rh,P as nd,Pa as Oh,Q as As,R as Wp,Ra as kh,S as Dp,Sa as Sh,T as _p,Ta as Th,U as Jp,Ua as Ah,V as Qp,Va as jh,W as Yp,Wa as ud,X as cr,Xa as $h,Y as Xp,Ya as vh,Z as Zp,Za as ld,_ as eh,_a as Eh,aa as od,ab as xh,bb as Ph,ca as nh,da as rh,ea as oh,fa as sh,fb as Fh,ga as $s,ha as vs,i as ys,ia as Es,ja as ih,jb as Nh,ka as sd,kb as Mh,la as Nt,lb as Is,ma as ah,mb as Bh,n as Ya,nb as fd,o as bp,oa as dh,ob as pd,p as ir,pb as hd,q as We,qa as ch,qb as Lh,r as Rp,ra as id,rb as Wh,s as Ss,t as Xa,tb as gd,u as Za,ub as md,v as Op,va as uh,vb as Dh,w as kp,wa as ad,wb as _h,x as Sp,xa as lh,xb as qh,y as Tp,yb as Uh,z as Ap}from"./chunk-C5AUNG6T.mjs";import{a as Hr,b as Os,c as wp,d as yp,e as za,f as Ha,g as Ka,h as Va,j as Ja}from"./chunk-3I6FXFCN.mjs";import{c as Nu,d as Mu,e as oa,f as Rl,g as Ol,h as kl,k as Wr,l as Ko,m as sa,s as $l}from"./chunk-7O6EFNQS.mjs";import{B as na,G as zo,M as nr,N as bl,O as Lr,P as Ho,a as Tu,l as ta}from"./chunk-3LRFPGYZ.mjs";import{a as fp,b as pp,c as hp,d as gp,e as mp,f as Ga,g as sr}from"./chunk-GB6W4Q56.mjs";import{f as ap,g as qa,h as dp,i as cp}from"./chunk-AVY742BJ.mjs";import{c as Ua,e as bs,f as up,g as lp,h as Rs}from"./chunk-BWWQXU2B.mjs";import{h as ia}from"./chunk-KWUS7UAV.mjs";import{a as ra}from"./chunk-QSRAEUGZ.mjs";import{a as Pf,e as Ff,g as Cf,j as Nf,l as Mf}from"./chunk-HZCS6EED.mjs";import{a as kf}from"./chunk-EGL3I3IX.mjs";import{a as hf,b as zr,c as gf,d as us,f as wf,g as yf,h as ba,i as bf,j as Rf,k as Of}from"./chunk-CSMGP53U.mjs";import{a as vl}from"./chunk-YYZL7UGV.mjs";import{a as ul,c as Zi,g as ll,h as fl,i as pl}from"./chunk-YDXMTWAT.mjs";import{b as Sf,c as Ra,e as Tf}from"./chunk-M6P5ZZLE.mjs";import{h as pf,i as ya,j as cs,q as mf}from"./chunk-35B73566.mjs";import{e as Bu,f as Lu,g as Wu}from"./chunk-TYUYPFDJ.mjs";import{a as qp,b as js,d as Up,e as rd,f as dr,g as Gp,h as zp,i as Hp,m as Kp,n as Vp}from"./chunk-TICZXC53.mjs";import{c as Al,d as jl,h as Ml,j as Bl}from"./chunk-DLSU66MY.mjs";import{c as Jo,o as Ll}from"./chunk-H6BHWAX7.mjs";import{a as Gt,c as Ar}from"./chunk-AL4C3GFT.mjs";import{d as jn}from"./chunk-GP5J3DGS.mjs";import{a as cu,b as Bn,c as An}from"./chunk-WQCXOZEJ.mjs";import{b as El,c as Il,g as xl}from"./chunk-ZVU7MD2S.mjs";import{$ as Xl,$a as Wf,$b as Yf,A as or,B as Dl,C as _l,Cc as qt,D as Yo,E as ql,F as Xo,G as Zo,Gc as rp,H as Ul,I as ua,Ic as op,J as la,Jc as ws,K as Gl,Kb as Kf,Lb as Vf,M as zl,Mb as ja,N as Hl,Nb as $a,Nc as Pe,O as Kl,Ob as fs,Oc as Ba,P as es,Pb as va,Q as Vl,Qa as If,Qb as ps,Qc as La,R as Jl,Rb as Ea,Rc as Wa,Sb as Jf,T as fa,Tc as sp,U as pa,Ua as xf,Ub as hs,V as Ql,Vc as ip,W as Yl,Wa as qn,Wb as Qf,Wc as Da,X as ts,Xc as _a,Y as ns,Z as qr,_ as Ur,_b as gs,a as xo,aa as Zl,ac as Xf,ba as ef,bc as Zf,ca as tf,cb as Df,cc as ms,d as Du,da as _n,db as _f,dc as Ia,e as Vi,f as Ji,g as _u,h as Qi,i as Yi,j as aa,jc as xa,k as Dr,kb as qf,lc as Pa,mb as ls,mc as Fa,nb as Un,o as Pl,p as Vo,qc as Ca,r as da,rc as Na,s as ca,sb as Uf,sc as ep,t as Fl,ta as vf,tb as Gf,u as Cl,v as Nl,va as Ef,vb as En,vc as Ma,x as rr,xa as Sa,y as Wl,yb as zf,yc as tp,z as Qo,zb as Hf,zc as np}from"./chunk-OLCS7JCT.mjs";import{g as Hi,i as ju,j as $u,k as vu}from"./chunk-TQ6HEJ73.mjs";import{f as Oo}from"./chunk-65AMXOQU.mjs";import{i as Ta,q as Aa,r as Bf,s as Lf}from"./chunk-6HHSAPIM.mjs";import{b as zi,f as Au}from"./chunk-K5PUMHZU.mjs";import{a as Ve}from"./chunk-4TLYUZD5.mjs";import{a as ha,b as vn,c as nf,d as rs,e as rf,f as Je,g as of,h as sf,i as os,k as af,l as df,m as cf,n as ss,o as ga,p as uf,q as _t,r as is,s as an,t as ma,u as lf,v as Gr,w as ff,x as as}from"./chunk-EUIALBMX.mjs";import{a as Br,c as Eu,d as Ki,e as Iu,f as xu,g as Pu,h as Fu,j as Cu}from"./chunk-INIT2UKJ.mjs";import{b as au}from"./chunk-Q7TLC3I2.mjs";import{a as ds,b as wa}from"./chunk-HF6LAK3G.mjs";import{l as wl}from"./chunk-ATBQIE2V.mjs";import{b as yl}from"./chunk-UCUFLFNK.mjs";import{a as Uu,b as Gu,c as $n,d as rl,e as ol,h as sl,i as il,j as al,k as dl,l as cl,m as Xi}from"./chunk-4XROG5CT.mjs";import{b as du,d as fu,h as Gh}from"./chunk-LCDPCUXS.mjs";import{a as st,b as _r}from"./chunk-TQ2TQHTT.mjs";import{b as Xu,c as _o,d as Zu,e as el,f as tl,g as qo,i as nl,l as Uo,m as Go}from"./chunk-HFSBDM7B.mjs";import{a as Wo,b as Do}from"./chunk-OHEOJISY.mjs";import{a as Po,c as qu}from"./chunk-EADHKH3A.mjs";import{a as Eo,b as Io,c as Mr,e as Su}from"./chunk-DAUX63UB.mjs";import{C as Li,D as $o,E as Dn,F as ze,G as Le,H as Wi,I as Nr,L as Di,M as _i,N as bu,Q as qi,X as Ui,a as Wn,aa as Gi,b as Ee,ba as Ru,c as lt,da as Ou,f as pu,g as hu,h as gu,i as mu,ja as ku,ka as vo,m as wu,n as Ni,o as Ao,p as Mi,q as Te,r as ae,s as Cr,t as sn,u as jo,w as Bi,z as yu}from"./chunk-SZOJ7BEJ.mjs";import{a as To,h as Be}from"./chunk-TZE3Y7IQ.mjs";import{b as Q}from"./chunk-CA5NAXSU.mjs";import{c as hl,f as gl,j as ea,k as ml}from"./chunk-22L43JMK.mjs";import{a as Sl,d as Tl}from"./chunk-TUACWKIH.mjs";import{a as He,i as zu,j as Hu,l as Fo,o as Co,p as Ku,q as No,r as Vu,s as Mo,t as Ju,u as Qu,v as Bo,w as Yu,x as Lo}from"./chunk-ICIYL45C.mjs";import{$ as Oi,Ba as Ai,Bc as vr,Dc as Vc,Ed as Zc,Fd as eu,Ga as Kc,Gc as Qe,H as kn,Hc as Er,I as ho,Jc as Ir,Jd as bo,Lc as tt,Mc as zt,Nc as rn,Oc as ji,P as Nc,Pc as wt,Qd as tu,Rc as Jc,Rd as Pr,Sc as Mn,T as Mc,Tc as Zn,Uc as xr,Vc as Ht,Vd as nu,W as go,Wc as yt,X as jr,Xd as ru,Y as Bc,Yc as $i,Yd as ou,Zc as Qc,_ as mo,aa as $r,ad as Yc,ba as Sn,bd as Xc,ce as vi,fa as Lc,he as Ei,ia as Wc,ja as Dc,ka as _c,ke as su,la as qc,na as Uc,nd as er,pe as iu,qa as wo,qd as yo,ra as ki,sa as Si,ta as Gc,te as Ii,ua as Ti,ue as Ro,va as zc,xa as Tn,ya as Hc}from"./chunk-J347SPU6.mjs";import{A as M}from"./chunk-WZQEK4WT.mjs";import{createHash as nb,randomUUID as Qs}from"node:crypto";import{existsSync as Yt,readFileSync as gn,readdirSync as rb,renameSync as Pm,rmSync as Hs,statSync as Fm,writeFileSync as Cm}from"node:fs";import{basename as yc,dirname as ob,join as Ys,resolve as Ut,sep as sb}from"node:path";import{createReadStream as Sw,existsSync as Tw}from"node:fs";import{createInterface as Aw}from"node:readline";var zh=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function jw(r){let e=[],t=Aw({input:Sw(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=Ll(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"&&zh.test(c)?s.wrote.push(c):d==="g"&&typeof u=="string"&&zh.test(u)&&s.wrote.push(u)}return e}async function Hh(r,e){if(!Tw(r))return[];let t;try{t=await jw(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 Gn(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 ur(r,e){return r.flatMap(t=>{if(t.part<=e||t.wrote.length===0&&t.linked.length===0)return[];let n=Gn(t);return n?[{span:{runRecordedAt:n.runRecordedAt,runDurationMs:n.runDurationMs},wrote:t.wrote,linked:t.linked}]:[]})}function zn(r){return r.flatMap(e=>e.ids)}function dn(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 wd=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){Ve.warn("Event listener threw an error",{eventType:String(e),error:Q(s)})}}removeAllListeners(){this.listenerMap.clear()}};var Kr=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 vw={BusinessHours:"Name",OperatingHours:"Name",ServiceTerritory:"Name"},xs=class{constructor(e){this.query=e}query;async resolve(e,t,n,o){if(t.length===0)return{mappings:[],unmatched:[]};let s=o??vw[e]??"Name",i=Be(e),a=Be(s),d=new Map;for(let O of t){let S=O.Id,R=O[s];typeof S=="string"&&typeof R=="string"&&R&&d.set(S,R)}if(d.size===0)return{mappings:[],unmatched:t.map(O=>({sourceId:typeof O.Id=="string"?O.Id:"",matchValue:typeof O[s]=="string"?O[s]:null})).filter(O=>O.sourceId.length>0)};let c=`SELECT Id, ${a} FROM ${i} WHERE ${a} IN (`,u=Br(`${c})`),l=Br(", "),f=new Map,p=[],h=u,g=async()=>{if(p.length===0)return;let O=`${c}${p.join(", ")})`;p=[],h=u;for(let S of await this.query(n,O)){let R=S.Id,b=S[s];typeof R=="string"&&typeof b=="string"&&f.set(b,R)}};for(let O of new Set(d.values())){let S=`'${To(O)}'`,R=(p.length>0?l:0)+Br(S);p.length>=nf||p.length>0&&h+R>14e3?(await g(),h+=Br(S)):h+=R,p.push(S)}await g();let m=[],w=[];for(let[O,S]of d){let R=f.get(S);R?m.push({sourceId:O,targetId:R,matchedBy:s,matchValue:S}):w.push({sourceId:O,matchValue:S})}return{mappings:m,unmatched:w}}};function yd(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:Wl(r,e),fields:r}}async function cn(r,e,t){return yd(await r(e,t),t)}function bd(r,e,t){return e?e.has(t??r.name):r.updateable!==!1}function lr(r,e){let t=new Set;for(let n of r)e.has(n)&&t.add(n);return t}var Ew=new Map;function Kh(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:h,creatableFields:g,updatableFields:m,picklistValuesByField:w,picklistFields:O,recordTypeValues:S,businessAccounts:R,contactPoints:b,decide:T,currencies:k,currencyFields:v=Ew,parentCurrencies:$,pricedIn:E,outsideTheSample:B,heldByTheRun:I}=r,G=n.filter(K=>K.isReference).map(K=>K.name),re=new Set(G),z=b?.forObject(e,n,h),_=K=>g.has(K.name)||h[K.name]!==void 0,ee=new Set(n.filter(K=>K.isReference&&(K.referenceTo??[]).some(ne=>i?.has(ne))).map(K=>K.name)),ve=new Set(n.filter(K=>{let ne=K.referenceTo??[];return K.isReference&&ne.length===1&&a?.has(ne[0])===!0}).map(K=>K.name)),he=Su(n.filter(K=>K.isReference),d),de=O??new Map;return t.map(K=>{let ne=[],fe=[],Ae=[],me=[],ce=u?.get(K);for(let U of n){if(!U.isReference||p.has(U.name)||ce?.[U.name]!==void 0)continue;let oe=_(U),ge=bd(U,m,h[U.name]);if(!oe&&!ge)continue;let ue=K[U.name];if(B&&U.name!=="RecordTypeId"&&typeof ue=="string"&&ue!==""&&!o.get(ue)&&B(U,ue)){fe.push(U.name),Ae.push(h[U.name]??U.name);continue}if(I&&U.name!=="RecordTypeId"&&typeof ue=="string"&&ue!==""&&!o.get(ue)&&I(ue)){fe.push(U.name),me.push(h[U.name]??U.name);continue}if(s!=="nullify"&&!ee.has(U.name)&&!ve.has(U.name)||U.name==="RecordTypeId"||he.has(U.name))continue;let It=K[U.name];typeof It!="string"||!It||oe&&o.get(It)||(fe.push(U.name),ne.push({field:h[U.name]??U.name,sourceRefId:It,targetObjects:U.referenceTo??[],...ge?{}:{insertOnly:!0}}))}let W=G.filter(U=>U!=="RecordTypeId"),J=o.remapRecord(K,W);for(let U of fe)J[U]=null;for(let[U,oe]of Object.entries(ce??{}))J[U]=oe;let we=J.OwnerId,Y=!1;typeof we=="string"&&c[we]&&(J.OwnerId=c[we],Y=!0);let Ce=jo(J,R?.has(K)===!0),Oe={},Ne=new Set,Ke=[],q=[],P;for(let U of Object.keys(J)){if(p.has(U))continue;let oe=h[U];if(oe){J[U]!==null&&(Oe[oe]=J[U]),Ne.add(oe);continue}if(!g.has(U))continue;if(ce?.[U]!==void 0){Oe[U]=ce[U];continue}if(U!=="RecordTypeId"&&he.has(U)&&!(U==="OwnerId"&&Y)){if(s!=="keep")continue;let ue=J[U];if(typeof ue=="string"&&l?.has(ue)){Ke.push(U);continue}if(U==="OwnerId"&&typeof ue=="string"&&f?.has(ue)){P=ue;continue}}else if(s==="keep"&&U!=="RecordTypeId"&&re.has(U)){let ue=J[U];if(typeof ue=="string"&&l?.has(ue)){q.push(U);continue}}if(yo(e,U,Ce))continue;let ge=J[U];ge!==null&&(Oe[U]=ge)}let D=Oe.RecordTypeId;T?.(Oe,typeof D=="string"?D:void 0);for(let U of Qc(e,Oe))delete Oe[U];let X;k&&!Ne.has(He)?X=No(Oe,{read:K[He],currencyFields:v,recordTypeDefault:or(S,D)?.picklists.get(He)?.defaultValue,ratesOn:Fo(e,K),pricedIn:E?.(K)},k):$&&(X=Qu(Oe,{read:K[He],parent:Ju(e,K,G,$.changeOf),currencyFields:v},$.currencies));let H=Qo(Oe,w,de,or(S,D),Ne),je=wu(e,Oe);for(let U of je)delete Oe[U];return z?.(Oe),{source:K,cleaned:Oe,nullifiedFks:ne.filter(U=>!je.includes(U.field)),picklistChanges:H,...X?{currencyChange:X}:{},...Ke.length>0?{lookupsNotCarried:Ke}:{},...q.length>0?{lookupsOutsideTheRun:q}:{},...Ae.length>0?{lookupsOutsideTheSample:Ae}:{},...me.length>0?{lookupsHeldBack:me}:{},...P!==void 0?{ownerInactive:P}:{}}})}var Iw=/^[a-zA-Z0-9]{15}([a-zA-Z0-9]{3})?$/,Vh=Symbol("left to the platform"),Ps=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 h=await this.parentObjectOf(e,f,p);if(!h)continue;let g=`${h}::${p}`;i.has(g)||i.set(g,{object:h,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!==ae),c.filter(l=>l.object===ae)];for(let l of u){let f=[];for(let p=0;p<l.length;p+=d){let h=l.slice(p,p+d).filter(g=>!o.get(g.sourceId));await Promise.all(h.map(async g=>{try{let m=await this.expandSingleOrphanParent(e,g.object,g.sourceId);if(m===Vh)return;m&&"id"in m?(this.expansionsUsed++,this.pastTheCap.delete(g.cacheKey),m.existing?o.addExisting(g.sourceId,m.id,g.object):(o.add(g.sourceId,m.id,g.object),m.owedStatus&&e.oweStatus?.(g.object,m.id,m.owedStatus),m.callId!==void 0&&e.calls?.answered(m.callId),o.persist()),s&&s.add(g.object,[g.sourceId]),g.object===Te&&sn(m.source)&&f.push(m.source)):(this.failedOrphans.add(g.cacheKey),this.expansionErrors.length<3&&this.expansionErrors.push({recordSummary:`${g.object}/${g.sourceId}`,messages:m&&m.refused.length>0?m.refused:["Orphan parent expansion produced no new id"]}))}catch(m){this.failedOrphans.add(g.cacheKey),this.expansionErrors.length<3&&this.expansionErrors.push({recordSummary:`${g.object}/${g.sourceId}`,messages:[Q(m)]})}}))}f.length>0&&await e.linkPersonContacts?.(f)}}async parentObjectOf(e,t,n){let o=t.referenceTo??[],s=o.filter(a=>!Eo(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(!Iw.test(n))throw new Error(`Invalid Salesforce record ID for orphan expansion: "${n}"`);let f=Be(t),p=await this.deps.describeFields(o,f),h=c?c(f,p):p,g=_t(h,e.fieldExclusions?.[f]);g.length===0&&g.push("Id");let m=`SELECT ${g.join(", ")} FROM ${f} WHERE Id = '${To(n)}'`,w=await this.deps.queryRecords(o,m);if(w.length===0)return null;if(l&&l.keep(f,w).length===0)return Vh;let O=w[0],S=sn(O),R=S?await e.personAccountsInTarget?.():void 0;if(f===ae&&S&&R!==!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 b=null;try{b=yd(await this.deps.describeFields(s,f),f)}catch(W){Ve.warn(`[forge] orphan-parent target describe failed for ${t}: ${W instanceof Error?W.message:String(W)}. Falling back to source createable.`)}let T=new Set(h.filter(W=>W.createable).map(W=>W.name)),k=b?lr(T,b.creatable):T,v=new Set(e.fieldExclusions?.[f]??[]),$=e.fieldMappings?.[f]??{},E=new Set,B=new Set(await e.maskedFieldsOf?.(f).catch(()=>[])??[]),I=[],G=k.has("RecordTypeId")&&!v.has("RecordTypeId")&&$.RecordTypeId===void 0,re=f===Te&&S&&(e.businessAccountsAmong?(await e.businessAccountsAmong([O],G)).has(O):R===!1),z=jo(O,re),_={};for(let W of h){let J=W.name;if(v.has(J))continue;let we=O[J];if(we==null)continue;if(B.has(J)){($[J]!==void 0||k.has(J))&&I.push(J);continue}if(W.isReference&&typeof we=="string"&&J!=="RecordTypeId")continue;let Y=$[J];if(Y){_[Y]=we,E.add(Y);continue}k.has(J)&&(yo(f,J,z)||(_[J]=we))}if(e.contactPoints?.forObject(f,h,$)?.(_),b){let W=new Set([...k].filter(J=>!v.has(J)&&!$[J]));await this.checkPicklists(e,f,O,_,b,W,E)}let ee=a&&i?a.apply([_],i,W=>bs(f,W))[0]:_,ve=d?d(f,ee,n,h):ee,he=u?await u(f,ve):void 0,de=await this.insertParent(e,f,n,ve),K=de.written,ne=de.callId;if(!K)return null;let fe=K.success?void 0:yf(K,ve,void 0),Ae=K.errors;if(fe){let W=await this.insertParent(e,f,n,pf(ve,fe));if(!W.written)return{refused:["No result returned for record",ba(fe,Ae)]};K=W.written,ne=W.callId}if(K.success)return I.length>0&&e.onMaskedLeftOut?.(f,I),fe&&e.onWrittenWithoutFields?.(f,{rows:1,fields:fe.map(W=>({...W,rows:1}))}),{id:K.id,existing:!1,owedStatus:he,source:O,...ne!==void 0?{callId:ne}:{}};let me=this.deps.describeObject?await this.deps.describeObject(s,f).then(W=>W.keyPrefix,()=>null):null,ce=ml(K,me);return ce.kind==="linked"?{id:ce.id,existing:!0,source:O}:{refused:fe?[...K.errors,ba(fe,Ae)]:K.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&&vl(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=No(o,{read:u,currencyFields:Co(s.fields),recordTypeDefault:or(d?.byRecordType,c)?.picklists.get(He)?.defaultValue,ratesOn:Fo(t,n)},l);e.currencyChanges?.add(t,p);let h=n.Id;p&&typeof h=="string"&&e.currencyChangesById?.set(h,p)}let f=Qo(o,s.picklistValuesByField,s.picklistFields,or(d?.byRecordType,c),a);e.picklistChanges?.add(t,f)}};async function*Fs(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 Fs(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 Fs((async function*(){yield await r.queryRecords(e,t,o)})(),n)}function Qh(r){let e=async(...n)=>{let[o,s,...i]=n,a=Ki(s),d=Iu(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?Pu(c,d,u):Fu(c,d,u,a)},t=(n,o,s)=>Cu(o,i=>(s?.all?r.queryPages?.(n,i,s):r.queryPages?.(n,i))??Jh(),s?.all?i=>xw(r.queryPages?.(n,i,s)??Jh()):i=>r.queryRecords(n,i),Ki(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 xw(r){let e=[];for await(let t of r)for(let n of t)e.push(n);return e}async function*Jh(){}var Re=class extends Error{constructor(e){super(e),this.name="ForgeAbortedError"}},Hd=zr;function Fw(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 Cw={OpportunityLineItem:{object:"OpportunityLineItemSchedule",lookup:"OpportunityLineItemId"}},Mt=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Xh=2e3;function Nw(){return{pages:0,rows:0,sent:0,succeeded:0,updated:0,linked:0,linkedToCreated:0,linkedByThePlatform: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 Yo,currencies:new Bo,lookupsNotCarried:new Map,lookupsOutsideTheRun:new Map,lookupsHeldBack:new Map,ownersInactive:0}}function Zh(r){return r.succeeded+r.updated+r.linked+r.writtenBefore+r.withTheirAccount+r.withTheirEmail+r.teamOwners+r.teamOthers+r.rolesOfTheirOpportunity}function eg(r){return[Gi(r.flagsNotKept),Hg(r.teamValues)].flatMap(e=>e?[`, ${e}`]:[]).join("")}function Rd(r,e){for(let{count:t,why:n}of e)r.held.set(n,(r.held.get(n)??0)+t)}function Od(r){return[...r.held].map(([e,t])=>({count:t,why:e}))}var Mw=5e3,Bw=2e3,tg="afterTask",kd=3,ng=1e3,Kn=2e3;function Vr(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 Lw(r){return r.some(e=>e.isReference&&(e.referenceTo??[]).includes(tt))}function _g(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&&!Je.has(s)&&t.push(s)}return t}function Ww(r,e,t){return _g(r,e).find(n=>t.has(n))}function Dw(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)&&!Je.has(a)&&!t.config.referenceDataObjects.has(a)&&!n.isRead(a)&&s.add(a);return[...s]}var _w=3,qw=10,Uw=5;function Gw(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 rg(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 og(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 Jr(r,e){for(let t of e){let n=t.Id;typeof n=="string"&&n!==""&&r.idsRead.add(n)}}function sg(r,e){let t=e!==void 0&&e>0?Math.floor(e):0;return t>0?Math.min(r.recordCount,t):r.recordCount}function Ls(r){let e=r.maxRecordsPerObject;return e!==void 0&&e>0&&Math.floor(e)>0?Math.floor(e):void 0}var zw={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 ig(r,e){let t=r/1048576*100;return(e==="up"?Math.ceil(t):Math.floor(t))/100}var Wd=class extends cr{constructor(t,n,o){super("SAMPLE_CANNOT_FIT",t,n);this.sample=o}sample},Dd=class extends cr{constructor(t,n){super("SAMPLE_TOO_LARGE",t);this.sample=n}sample},ag=3;function Hw(r,e){let t=e.slice(0,ag).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(ag);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 Kw(r){let e=r.orphanExpander.capReport();return e?{orphanParentsCapped:e}:{}}function dg(r){let e=Ls(r.config);return e!==void 0&&r.cappedObjects.size>0?{cappedObjects:{perObject:e,objects:[...r.cappedObjects]}}:{}}function Vw(r){return r.errors.length===0?"excluded":`excluded: ${r.errors.join("; ").replace(/\s+/g," ").trim()}`}function Jw(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(ss(e,new Map([[r,t]])).edges.filter(d=>d.targetObject===r&&(d.required===!0||d.type==="master-detail"&&!i(d.sourceObject))&&cf(d)&&!s(d.sourceObject)).map(d=>d.sourceObject));for(let d of n){let c=d.referenceTo??[];c.length!==1||!Er(d)||!Qe(r,d.name,d.nillable)||a.add(c[0])}return a.delete(r),[...a]}function Qw(r,e){return _d(Yr(r.values()),e)}function Yr(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?[Go({...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 Yw=3,cg=5e4;function Xw(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/Kn):0),0)}var Sd={field:"",parentObject:"",reason:"the source does not hold it"};function Td(r,e){return`${r} may not be left empty, and names a ${e} record the source does not hold`}var ug={field:"",parentObject:"",reason:"the source holds it outside its object's filter"};function Ad(r,e){return`${r} may not be left empty, and names a ${e} record outside the ${e} filter`}function Zw(r,e){return`${r} may not be left empty, and names a ${e} record outside the sample: changed since the sample`}function ey(r,e){return`${r} may not be left empty, and names a ${e} record gone from the source since the sample`}function lg(r,e){return`${r} may not be left empty, and names a ${e} record left aside`}function ty(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 ny="held back for a record type closed to the user the run writes as",ry="held back for a record type the target has none of";function fg(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:ny}]:[],...t>0?[{count:t,why:ry}]:[],...n>0?[{count:n,why:qd}]:[]]}function pg(r,e){return e<=0?{}:r.every(t=>t.unmapped)?{recordTypeNotInTarget:e}:{heldBack:e}}function hg(r,e){return Xi(r.unmapped?"record_type_unmapped":"record_type_unavailable",r.objectApiName,r.developerName,r.recordCount,Kg(e))}function oy(r,e,t){let n=r.leftAside.get(e)??new Map;Yr(t,n),r.leftAside.set(e,n)}function sy(r,e){return[...r.leftAside.get(e)?.values()??[]].map(({count:t,reason:n})=>`, ${t} left aside: ${n??""}`).join("")}function iy(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 Ws(r,e){return r.leftToThePlatform.counts(e).map(({why:t,count:n})=>`, ${hu(n,t)}`).join("")+sy(r,e)}function ay(r){return[...dy(r),...iy(r)]}function dy(r){let e=new Map;for(let{objectApiName:t,why:n,count:o}of r.leftToThePlatform.counts())e.set(t,[...e.get(t)??[],{recordSummary:gu(o,n),messages:[mu(n)]}]);return[...e].map(([t,n])=>({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:n}))}function Xr(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 cy(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(", ")}${Xr(t)}`).join("; ")}function uy({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}${Xr(o)}.`:t!==void 0?`Not written: ${r} may not be left empty, and the ${t} it names is held back for ${e}${Xr(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===Ht?`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 qd="held back for want of their parent",gg=" \u2014 the records that cannot be written without one of those not written are held back",mg={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 Ds(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(", ")}${Xr(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 Ds(r.heldForExclusions.get(e)?.values()??[])}function Vn(r){return r.reduce((e,t)=>e+t.count,0)}function ln(r){return r.map(({count:e,why:t})=>`, ${e} of them ${t}`).join("")}function _s(r,e=!1){let t=Vn(r);if(t===0)return"";let n=`, ${t} ${e?"more ":""}failed`;return r.length===1?`${n}, ${r[0].why}`:n+ln(r)}function wg(r,e){return Ws(r,e)+_s(Qt(r,e))}function ly(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:[uy(o)]}})}})}function fy(r,e){for(let[t,n]of r.heldForExclusions){let o=n.get(e);if(o)return{objectApiName:t,why:o}}}function yg(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=fy(r,o);if(s){let{excluded:i,target:a}=s.why;return{field:n.name,excluded:i,through:s.objectApiName,...a?{target:a}:{}}}}}function Pn(r,e,t=[]){let n=e+Vn(t);return`Held back ${r}, nothing written, ${n} failed${ln(t)}`}function bg(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 qg(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 jd(r,e){if(e!==ae)return 0;let t=r.personContactsOutsideTheSample;return r.personContactsOutsideTheSample=0,t}function Hn(r,e,t){t<=0||(r.writtenByThePlatform.set(e,(r.writtenByThePlatform.get(e)??0)+t),r.store?.writtenByThePlatform(e,t))}function Ud(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 Ug(r,e,t,n){let o=Math.min(e,Math.max(0,t)),s=Math.min(e-o,Math.max(0,n?.rows??0)),i=e-o-s,a=r.dryRun?"the run would create (the target would refuse them as copies of those)":"the run created (the target refused them as copies of those)";return(i>0?`, ${i} linked to records already in the target`:"")+(o>0?`, ${o} linked to records ${a}`:"")+(n&&s>0?`, ${s} written by the platform with ${Dn(n.objectApiName)}`:"")}var py=3;function $d(r,e,t,n,o=0){let s=r.dryRun?"would be inserted":"succeeded",i=t.updated>0?`, ${t.updated} updated through their external id`:"",a=Ug(r,t.linked,t.linkedToCreated,{objectApiName:e,rows:t.linkedByThePlatform}),d=qg(t.withTheirAccount,o),c=t.withTheirEmail>0?`, ${t.withTheirEmail} written by the platform with their email`:"",u=Gg(t.teamOwners,t.teamOthers)+zg(t.rolesOfTheirOpportunity,t.rolesGiven),l=t.writtenBefore>0?`, ${Ud(r,t.writtenBefore)}`:"",f=t.unidentified>0?` (${t.unidentified} already in the target without Salesforce naming the record \u2014 their children lose the link)`:"";return`${t.succeeded} ${s}${i}${a}${c}${d}${u}${l}, ${t.failed+Vn(n)} failed${f}${ln(n)}`}function Gg(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 zg(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 hy(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 gy(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 Hg(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 Qr(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(", "):cy(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`${Pn(r,e.size)}: ${a}${s?", excluded from this run":""}.`+(t?" Objects that cannot be written without it will be skipped.":"")}function Rg(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=Je.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 Og(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 kg(r){for(let[e,t]of Object.entries(Ir))if(t.object===r)return{parent:e,lookup:t.lookup}}function my(r,e){return e.filter(t=>t.isReference&&Qe(r,t.name,t.nillable)).map(t=>t.name)}function wy(r){return r.isScoped===!0||r.files!==void 0||r.beforeWrite!==void 0}function vd(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 Sg(r,e){for(let{lookupsNotCarried:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function Ed(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 Id(r,e){for(let{lookupsOutsideTheRun:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function yy(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 xd(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 Pd(r,e){for(let{lookupsHeldBack:t=[]}of e)for(let n of t)r.set(n,(r.get(n)??0)+1);return r}function by(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 Tg=10;function Fd(r){return r===0?"":`, written with the user the run writes as for owner on ${r}: the target holds their owner inactive`}function Ag(r){return r.filter(({ownerInactive:e})=>e!==void 0).length}function Ry(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 Oy(r){return[...r.ownersInactive].map(([e,{rows:t,owners:n}])=>{let o=[...n],s=o.slice(0,Tg).join(", "),i=o.length-Tg;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 Cs(r){return`${r} on a case waiting for ${r===1?"its task":"their tasks"}`}function Cd(r,e,t){t<=0||r.notSent.set(e,(r.notSent.get(e)??0)+t)}function ky(r,e,t,n){return{...r,status:t&&r.status!=="error"?"stopped":r.status,message:`${r.message}; ${t?"stopped: ":""}${e} not sent${n}`}}function fr(r,e){r.store?r.store.withTheirRecord(e):r.withTheirRecord.add(e)}function Sy(r,e){return r.store?r.store.markedWithTheirRecord(e):r.withTheirRecord.has(e)}function jg(r){return r.store?[...r.store.withTheirRecordIds()]:[...r.withTheirRecord]}var qs=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"}},$g="files",Nd=200,Ty=Kn,Md=[{object:"ContentVersion",counted:"ContentDocument",size:"ContentSize",where:"IsLatest = true AND ContentLocation = 'S'"},{object:"Attachment",counted:"Attachment",size:"BodyLength",where:""}];function vg(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 Ay(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 Eg(r){return r?.errorCode==="INVALID_QUERY_LOCATOR"||Q(r).includes("INVALID_QUERY_LOCATOR")}function Ig(r){if(au(r))return!0;let{errorCode:e,statusCode:t}=r??{};return e==="SERVER_UNAVAILABLE"||t===502||t===503||t===504?!0:Q(r).includes("SERVER_UNAVAILABLE")}function xg(r){return new Promise(e=>setTimeout(e,r))}function jy(r,e){return e?r?`(${r}) AND ${e.where}`:e.where:r}function Ns(r,e){return Io(e)?Mr(e)?!0:!r.writtenObjects.has(e):!1}function un(r,e){let t=e.Id;return typeof t=="string"&&r.writtenBefore.has(t)}function Pg(r,e){if(e!==void 0&&r.recordTypeDecisions.get(e)?.to!==null)return r.recordTypeMappings?.find(t=>t.sourceId===e)?.developerName}function $y(r){let e=(r?.recordTypes??[]).filter(t=>!t.master);if(!e.some(t=>t.namespacePrefix===void 0))return e.map(Zu)}function Kg(r){return(r?.recordTypes??[]).filter(e=>e.available&&e.active&&!e.master).map(e=>e.developerName)}var Fg=200,Cg=200,Gd=/[\u0000-\u001f]/;function Bd(r,e){if(!wt(e))return"";let t=[...Ja(r.pricesSwappedSaid),...vy(r)];return t.length===0?"":`, ${t.join("; ")}`}function vy(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 Ey=/^012000000000000(AAA)?$/;function Ng(r){return(e,t)=>{for(let n of Object.keys(t))n!=="Id"&&r.patched(String(t.Id),n)}}var Iy=["insert","upsert"],xy=["insert","upsert","update"];function Mg(r,e){let t="";for(let n of Iy){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 Py(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:[ll(r),...r.notSplit>0?[fl(r.notSplit,e,"run")]:[]]}]}}function Fy(r){return xy.flatMap(e=>r.splitting.sizes.reports(e).filter(t=>t.rows+t.alone+t.notSplit+t.keptWhole>0).map(t=>Py(t,pl(r.splitting.allowance,{objectApiName:t.objectApiName,op:e}))))}function Ms(r){return{sending:(e,t,n,o)=>{let s=t.map(({payload:d})=>d),i=nh(s),a=o===!0&&n===void 0?oh(s):[];return r.sent(e,i,t.flatMap(({sourceId:d,payload:c,owes:u},l)=>d===void 0?[]:[{sourceId:d,fingerprint:rh(c,i),owes:u,...n!==void 0?{externalKey:sh(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 Bg(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 Cy=[["CreatedDate","LastModifiedDate","SystemModstamp"],["SystemModstamp"]],Ny=new Set(["CreatedDate","LastModifiedDate"]),My=new Set(["string","textarea","email","phone","url","picklist","multipicklist","combobox","encryptedstring"]);function By(r){return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function Bs(r){return typeof r=="string"?Date.parse(r):Number.NaN}var Lg="005",zd=class{ids=new Set;issued=0;uniqueValues=new Map;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)}holderOf(e,t,n){return this.uniqueValues.get(`${e}.${t}`)?.get(n)}hold(e,t,n,o){let s=`${e}.${t}`,i=this.uniqueValues.get(s)??new Map;i.has(n)||i.set(n,o),this.uniqueValues.set(s,i)}};function Wg(r,e){return e.filter(t=>t.unique===!0&&t.createable&&!(r.upsertMode==="auto"&&t.externalId===!0))}function Ly(r,e){let t=r[e];return typeof t=="string"&&t!==""&&!Gd.test(t)?t:void 0}function Wy(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 Dy(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&&Ua(n)?"masterInSource":"notRead"}function _y(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 Ld(r,e){return[r[Mn],e?r[Zn]:"",r[yt]].map(t=>String(t??"")).join("|")}function Dg(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||My.has(n.type)))}var qy=200,Uy="the standard price of its product, which it may not go without, changed since the sample";function Gy(r){return r?{sample:r}:{}}function zy(r){let e=r.options,t=Object.entries(e.rootWhere??{});return{seed:e.seed??Tn.seed,draw:e.draw??Tn.draw,parents:e.parents??Tn.parents,children:e.children??Tn.children,floor:e.floor??Tn.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 pr=class{deps;isPaused=!1;pauseResolve=null;isAborted=!1;bulkCancel=new AbortController;sampling=new AbortController;running=null;constructor(e){this.deps=Qh(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??wa;return Ve.info(`[forge] writing through the Bulk API: a job per ${zr} rows of an object from ${2e3}, one at a time on a job limiter of the run's own; by REST: ${[...ds,...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([...ds,...o]),bulkUnsupported:new Set,manager:new Tu(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 Re("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 Re("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(l=>[l.name,l])),u=a.classes?.[t];return e.anonymize({objectApiName:t,records:n,sourceIds:o,fields:d.map(l=>{let f=c.get(l),p=u?.[l];return{name:i[l]??l,type:f?.type??"",...f?.length!==void 0?{length:f.length}:{},...p!==void 0?{classification:p}:{}}}),methods:a.methods,...a.everything?{everything:!0}:{}})}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??""})),n)??[];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,sr(c)?void 0:null)}}return is(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 Wp;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=tf(s);if(a.files){let $=ho(a.anonymization!==void 0,a.files.acceptedAsIs);if($)throw new xn($,"FILES_NOT_ACCEPTED");let E=this.fileCopyUnwired();if(E)throw new xn(E,"FILES_NOT_COPYABLE")}let d=await this.chooseTheRoots(a,t,a.dryRun?void 0:a.stream?.store),c=await Ts(a.ownerMappings,$=>this.deps.queryRecords(n,$),ar);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}},h=p.dryRun?new zd:null,g=p.excludedObjects,m=await this.withWhatStatusesNeed(os(e,g),t,g),w=p.isScoped?await this.withWhatItsRecordsComeWith(m.graph,t,g):m.graph,O=await this.withSellingModelOptions(await this.withTheCatalogItNeeds(w,t,g),t,g),S=this.deps.recordTypePicklists,R=p.dryRun?void 0:p.stream?.store,b=new Date;R?.beginPart(b),d&&R&&!d.fromTheJournal&&R.nameRoots({objectApiName:d.objectApiName,ids:[...d.ids],sha256:d.sha256,readAt:d.readAt,...d.query?{query:d.query}:{}});let T=ul(),k=await this.bulkTransportOf(p,n),v={...k?{bulk:k}:{},config:p,sourceOrgId:t,targetOrgId:n,graph:O,onProgress:o,remapper:new Kr(R),scopeCache:p.isScoped?new bp:null,scopedBuilder:p.isScoped?new vn:null,recordTypeMapper:p.recordTypeMappings?new Rs:null,referenceDataMapper:new xs(($,E)=>this.deps.queryRecords($,E)),orphanExpander:new Ps(h?Wy(this.deps,h,async($,E)=>this.deps.describeObject?this.deps.describeObject($,E).then(B=>B.keyPrefix,()=>null):null):this.deps),batchWriter:new Rf(this.deps,this.deps.batchStrategy,void 0,T),splitting:T,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:vp($=>this.deps.queryRecords(n,$)),ownersInactive:new Map,lookupsOutsideTheRun:new Map,lookupsHeldBack:new Map,parentsOutside:new Map,readAsParents:new Map,idsRead:R?{add:$=>R.noteRead($),has:$=>R.wasRead($)}: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(O.nodes.filter($=>$.included).map($=>$.objectApiName)),writtenObjects:new Set,sellingModels:O.nodes.some($=>$.included&&$.objectApiName===xr),standardPricebookId:null,existingRecords:[],lifecycles:new Map,deferredStatuses:[],...R?{store:R}:{},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 cp(void 0,{upsertKeys:p.upsertMode==="auto"}),detectedPersonalFields:new Map,fileScope:new Map,files:null,fileContentFieldsLeftOut:new Map,maskedSourceFields:jl(Al($=>this.deps.queryRecords(t,$)),async $=>({fields:await this.deps.describeFields(t,$)})),encryptedFieldsLeftOut:new Map,recordTypePicklists:new Dl(S&&(($,E)=>S(n,$,E))),picklistChanges:new Yo,currencyChanges:new Bo,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:b,writtenByThePlatform:new Map,personContactsOutsideTheSample:0,contactSentWith:new Map,leftToThePlatform:new pu,emailsAfterTheirTask:[],taskTurnOver:!1,emailsInTwoPasses:!1,emailsLeftForTheirTask:0,emailsFirstPassRan:!1,syncedQuotesLeft:0,requestsBefore:i,...d?{roots:d}:{},readUnder:new Map,simulated:h,gaps:p.dryRun?new ol:null,decisionsApplied:new ua,mayHaveBeenWritten:new Map,sourceRecordTypes:new Map,recordTypeRows:u,successCount:0,updatedCount:0,linkedCount:0,linkedToCreatedCount:0,wouldInsertCount:0,failedCount:0,skippedCount:0};for(let[$,E]of p.writtenBefore)v.remapper.addExisting($,E);for(let{decision:$,reason:E}of l.unresolved)v.errors.push({objectApiName:$.object,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(record type ${$.from} \u2192 ${$.to??"the default"})`,messages:[`The decision was not applied: ${E}.`]}]});this.running=v;try{return await this.runPasses(v)}catch($){throw this.endBeforeTheEmailsThatWaited(v,v.emailsAfterTheirTask.length+v.emailsLeftForTheirTask,$ instanceof Re),this.saySyncedQuotesLeft(v),await this.readWrittenBetween(v),this.reportDraftsLeft(v),R?.settleReads(),Dp($,this.summaryOf(v)),$}finally{this.running===v&&(this.running=null),R?.settleReads(),R?.flush()}}async recordTypeDecisionsOf(e,t,n,o){if(e.length===0)return la([],[]);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 la(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,Wo).then(s=>Do(s),()=>[]),e.set(t,o)),_o(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=>kn(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=>!kn(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 jn(i)){let c=await this.writtenDatesOf(e.targetOrgId,o,d);if(!c)return;for(let u of c){let l=Bs(u.SystemModstamp),f=g=>{let m=a?Number.NaN:Bs(u[g]);return Number.isFinite(m)?m:l},p=f("CreatedDate"),h=f("LastModifiedDate");Number.isFinite(p)&&(t=Math.min(t,p)),Number.isFinite(h)&&(n=Math.max(n,h))}}}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=By(e.startedAt.getTime()-sd),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[h]=await this.deps.queryRecords(e.targetOrgId,p),g=Bs(h?.f),m=Bs(h?.l);Number.isFinite(g)&&(o=Math.min(o,g)),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()+sd)),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 Cy)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=>Ny.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=af(n,t.isScoped?t.rootObjectApiName:void 0),d=this.streamsTheRun(e),c=!d&&wy(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 R of u)R.included&&e.turnsAhead.add(R.objectApiName);if(n.nodes.some(R=>wt(R.objectApiName)))try{let[R,b]=await Promise.all([this.deps.queryRecords(o,ji),this.deps.queryRecords(s,ji)]),T=R[0]?.Id,k=b[0]?.Id;typeof T=="string"&&typeof k=="string"&&(e.standardPricebookId=T,e.remapper.addExisting(T,k),e.scopeCache?.add(zt,[T]),e.readObjects.add(zt),n.nodes.some(v=>v.included&&v.objectApiName===zt)||e.scopeCache?.addRead(zt,[]))}catch(R){e.errors.push({objectApiName:tt,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(standard price book lookup)",messages:[Q(R)]}]})}let l=new Map,f=this.deps.isObjectCreatable;if(f){let R=[...new Set(a.filter(b=>b.included&&!t.referenceDataObjects.has(b.objectApiName)).map(b=>b.objectApiName))];for(let b=0;b<R.length&&!this.isAborted;b+=6){let T=R.slice(b,b+6),k=await Promise.allSettled(T.map(async v=>f(s,v)));T.forEach((v,$)=>l.set(v,k[$]))}}for(let[R,b]of l)b.status!=="rejected"||!sr(b.reason)||(e.notInTarget.add(R),e.readObjects.delete(R),e.turnsAhead.delete(R));for(let R of n.nodes){let b=l.get(R.objectApiName);!R.included||b?.status==="fulfilled"&&!b.value||e.notInTarget.has(R.objectApiName)||e.writtenObjects.add(R.objectApiName)}d&&await this.planTheSample(e,u),d&&t.beforeWrite&&await this.countBeforeWrite(e,u);for(let R of u){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");if(!R.included){e.skippedCount++,i({objectName:R.objectApiName,status:"skipped",progress:100,message:`Skipped ${R.objectApiName} (${Vw(R)})`});continue}if(e.notInTarget.has(R.objectApiName)){e.scopeCache&&R.objectApiName!==t.rootObjectApiName?(e.notInTargetPutOff??=[]).push(R):this.reportNotInTarget(R,e),await this.endTurn(R.objectApiName,e);continue}if(await this.skipForFailedParent(R,e)){await this.endTurn(R.objectApiName,e);continue}let b=l.get(R.objectApiName);if(b)if(b.status==="fulfilled")b.value||e.notCreatable.add(R.objectApiName);else{let T=b.reason;e.errors.push({objectApiName:R.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(target describe failed)",messages:[`isObjectCreatable check failed: ${T instanceof Error?T.message:String(T)}`]}]})}c?await this.readInTurn(R,e):d&&this.streamsNode(R,e)?(await this.streamNode(R,e),e.turnsEnded.add(R.objectApiName),R.objectApiName===lt&&await this.writeEmailsAfterTheirTask(e)):(await this.readNode(R,e,!1,!0)&&await this.writeNode(R,e),e.turnsEnded.add(R.objectApiName),R.objectApiName===lt&&await this.writeEmailsAfterTheirTask(e),R.objectApiName===Te&&await this.mapContactsOfPersonAccounts(e),this.releaseRows(e,R.objectApiName))}let p=df(e.deferredNodes.splice(0,e.deferredNodes.length),e.catalogNodes,n.edges),h=p.map(R=>Je.has(R.objectApiName)).lastIndexOf(!0);for(let[R,b]of p.entries()){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");await this.skipForFailedParent(b,e)||(c?(e.scopeCache&&Je.has(b.objectApiName)&&(this.holdBackWhatHeldRowsCost(e),this.leaveOutWhatOnlyRowsHeldBackName(e,b.objectApiName)),await this.readNode(b,e,!1,!1),await this.readUnderWhatWaited(b.objectApiName,e,h>=0&&R>h?"after the catalog":"before the catalog")):await this.readNode(b,e,!1,!0)&&(await this.writeNode(b,e),e.turnsEnded.add(b.objectApiName),this.releaseRows(e,b.objectApiName)))}await this.readCatalogAgain(e,h<0?[]:p.slice(h+1)),await this.reportNotInTargetOfTheScope(e);for(let R of[...e.preread.keys()])this.releaseRows(e,R,!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 g=this.deps.requestsSent?.();e.roots&&g!==void 0&&e.requestsBefore!==void 0&&(e.readRequests=g-e.requestsBefore);let m=t.stream?.everything===!0,w=t.files&&!m?await this.prepareFiles(e):[];if(c&&t.beforeWrite){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let R=await this.pricesTheGateCounts(e),b=dg(e).cappedObjects,T=await this.withoutWhatTheTargetHoldsByValue(e,await this.withoutWhatThePlatformWrites(e,await Promise.all([...e.preread].map(([$,E])=>this.toWriteAtTheGate(e,$,E,wt($)?R:0))))),k=t.dryRun?0:await this.readBackRequests(e,T),v=await t.beforeWrite({objects:T,...b?{capped:b}:{},...k>0?{readBack:k}:{},...e.roots?{roots:Fw(e.roots)}:{},dryRun:t.dryRun});await this.afterTheGate(e,v,T)}if(c)for(let R of this.writeOrderOf(e)){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let b=e.preread.get(R.objectApiName);if(b&&!await this.skipForFailedParent(R,e,b.fieldInfos,b.records)&&(await this.writeNode(R,e),R.objectApiName===lt&&await this.writeEmailsAfterTheirTask(e),R.objectApiName===Te&&await this.mapContactsOfPersonAccounts(e),e.pendingFkUpdates.push(...this.owedNowWritten(e)),e.pendingFkUpdates.length>0&&!t.dryRun)){let T=e.pendingFkUpdates.splice(0,e.pendingFkUpdates.length),k=[],v=await ed({pendingFkUpdates:T,remapper:e.remapper,updateRecords:this.deps.updateRecords,targetOrgId:s,enabled:!0,onProgress:i,deferUnresolved:!0,stillPending:k,stopped:()=>this.isAborted,splitting:e.splitting,...this.bulkUpdatesOf(e),onPatched:this.patchedInTheJournal(e),onAnswered:()=>e.store?.flush(),onRefusedByFilter:($,E,B)=>this.noteLeftEmptyByFilter(e,$,E,B),...this.secondPassOfTheSample(e)});v&&e.errors.push(v),e.pendingFkUpdates.push(...k)}}await this.writeEmailsAfterTheirTask(e),e.pendingFkUpdates.push(...this.owedNowWritten(e));let O=e.secondPassInStore?await this.secondPassFromTheJournal(e):await ed({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:(R,b,T)=>this.noteLeftEmptyByFilter(e,R,b,T),...this.secondPassOfTheSample(e)});if(O&&e.errors.push(O),this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");w.length>0&&!t.dryRun?await this.writeFiles(e,w):m&&t.files&&!t.dryRun&&await this.copyFilesOfTheOrg(e,t.files.maxFileBytes),this.reportDraftsExclusionsLeave(e),await this.restoreStatuses(e),await this.giveTheLeaseBack(e);let S=e.orphanExpander.buildErrorReport();return S&&e.errors.push(S),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"||Ua(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){Ve.warn(`[forge] the mute's lease was not given back as the writes ended: ${Q(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,gp(t,n.ids));n.readBack=mp(o,n.types)}catch(o){n.readBack={read:0,types:[],unread:Q(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=pp(fp(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=Dy(c,o,d);l.rows++,l.why[f]=(l.why[f]??0)+1,u!==void 0&&l.ids.length<hp&&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===Ee)}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(w=>w.externalId===!0&&w.createable&&w.queryable&&!d.has(w.name)&&c[w.name]===void 0);if(u.length===0)return a;let l=n.described.find(w=>w.name==="Id"),f=an({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,h=new Map(u.map(w=>[w.name,new Set])),g=0,m=Vt(this.deps,s,f.statements[0],o.stream?.pageSize,void 0,this.readOptionsOf(e,i));try{for await(let w of m){for(let O of w){if(g>=p)break;g++;for(let[S,R]of h){let b=O[S];typeof b!="string"||b.length===0||R.has(b)?h.delete(S):R.add(b)}}if(g>=p||h.size===0||this.isAborted)break}}finally{await m.return(void 0)}return{unique:new Set(h.keys()),sent:a.sent}}catch(d){return Ve.warn(`[forge] upsert: the external ids of ${i} could not be read \u2014 inserting it: `+Q(d)),a}}streamsNode(e,t){let n=e.objectApiName;return!Je.has(n)&&!wt(n)&&(n!==lt||t.config.stream?.everything===!0)&&!t.config.referenceDataObjects.has(n)}releaseRows(e,t,n=!1){if(e.config.stream?.everything!==!0||!n&&(Je.has(t)||wt(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&&Pf.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(Ur(i.objectApiName,"otherQuery"));return}let{objectApiName:a,cap:d}=o,c={cap:d,readTotal:o.readTotal,readingBound:zl(o.sourceRequestsLeft),...o.sourceRequestsLeft!==void 0?{sourceRequestsLeft:o.sourceRequestsLeft}:{}};if(s){if(!i)throw Pe.of(Xl(a));if(i.objectApiName.toLowerCase()!==a.toLowerCase())throw Pe.of(Ur(a,"otherQuery"));if(pa(i.ids)!==i.sha256)throw Pe.of(Ur(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=Yl(l,{sourceOrgId:t,objectApiName:a,...o.query?{query:o.query}:{},...o.ids?{ids:o.ids}:{}});if(m)throw Pe.of(Ur(a,m));let w=o.planOfTheRunRetried===!0;if(lh(l,new Date)<ch||o.query===void 0||w)return{objectApiName:a,from:"plan",...l.query?{query:l.query}:{},ids:new Set(l.ids),sha256:l.sha256,readAt:l.readAt,fromTheJournal:!1,...w?{ofTheRunRetried:!0}:{},...c};u={roots:l.ids.length,readAt:l.readAt}}else o.planPastItsDay!==void 0&&o.query!==void 0&&(u={...o.planPastItsDay});let f,p,h;if(o.ids!==void 0){let m=o.ids.filter(w=>!Ql(w));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=fa(o.ids),p="records",f.length>d)throw Pe.of(qr(a,d,p))}else if(o.query!==void 0){let m=Kl(o.query);if(m)throw Pe.of(ts(m,a));let w=o.chosen,O=w?w.ids.map(S=>({Id:S})):await this.deps.queryRecords(t,es(a,o.query,e.objectSoqlFilters?.[a],d));if(f=fa(O.flatMap(S=>typeof S.Id=="string"?[S.Id]:[])),p="query",h=w?.readAt,f.length>d)throw Pe.of(qr(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(ns(a,o.query,d));let g=h??new Date().toISOString();return o.keepAt!==void 0&&await uh(o.keepAt,{sourceOrgId:t,fingerprint:o.fingerprint??"",objectApiName:a,...o.query?{query:o.query}:{},from:p==="records"?"records":"query",readAt:g,ids:f}),{objectApiName:a,from:p,...o.query?{query:o.query}:{},ids:new Set(f),sha256:pa(f),readAt:g,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(ef({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(Zl(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 cr("SAMPLE_PLAN_MISMATCH","The run this one resumes copied a sample of the whole org: resume it as a sample. "+ar);return}let a;if(i)try{a=await dr.open(i.dir,{sha256:i.sha256})}catch(d){throw d instanceof js?new cr("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. ${ar} Copy a new sample rather than resume this one.`):d}else{if(o?.resumes)throw new cr("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. ${ar}`);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=zy(n),a=t.filter(T=>T.included&&(e.writtenObjects.has(T.objectApiName)||o.referenceDataObjects.has(T.objectApiName))),d=new Map;for(let T of a)d.set(T.objectApiName,await this.deps.describeFields(s,T.objectApiName));let c=(T,k)=>k.nillable===!1&&e.graph.edges.some(v=>v.type==="master-detail"&&v.targetObject===T&&(k.referenceTo??[]).includes(v.sourceObject)),u=[],l=new Map;for(let T of a){let k=T.objectApiName,v=new Set(o.fieldExclusions[k]??[]),$=(d.get(k)??[]).filter(E=>E.isReference&&!v.has(E.name)).map(E=>({name:E.name,referenceTo:E.referenceTo??[],isMasterDetail:c(k,E),...E.nillable!==void 0?{nillable:E.nillable}:{},createable:E.createable,...E.updateable!==void 0?{updateable:E.updateable}:{}}));if(u.push({objectApiName:k,rows:T.recordCount,keyPrefix:(await this.objectInfoOf(s,k))?.keyPrefix??e.sourceKeyPrefixes.get(k)??null,fields:$}),this.streamsNode(T,e)&&!o.referenceDataObjects.has(k)){let E=await this.recordTypesOfTable(e,T);E&&E.closedInSource.length>0&&l.set(k,{closed:new Set(E.closedInSource.map(st)),lacking:new Set(E.lackingInSource.map(st))})}}let f=await this.restOnlyOfTheWholeOrg(e),p=th(await n.budget(),{...f?{restOnly:f}:{},...n.sourceRequestsLeft!==void 0?{source:{left:n.sourceRequestsLeft,objects:a.map(T=>({objectApiName:T.objectApiName,columns:_t((d.get(T.objectApiName)??[]).filter(k=>!kn(k)),o.fieldExclusions[T.objectApiName]),sourceRows:T.recordCount}))}}:{}}),h=e.standardPricebookId&&a.some(T=>wt(T.objectApiName))?await this.runCurrencies(e):void 0,g=h&&this.priceCurrencyWrittenIn(e,h.target),m=new Map;if(a.some(T=>T.objectApiName===Ee)){let T=await this.averageEmailBytes(e,d.get(Ee)??[]);T!==void 0&&m.set(Ee,T)}let w=g?T=>h.target.active.has(T)?void 0:g(T):void 0;this.sampling=new AbortController,this.isAborted&&this.sampling.abort();let O=Date.now(),S;try{S=await Xp({source:{pages:(T,k)=>Vt(this.deps,s,T,void 0,void 0,k),count:async(T,k)=>{let v=this.deps.countRecords;if(v)return k?v(s,T,k):v(s,T);let $=0,E=T.replace(/^SELECT COUNT\(\) FROM /,"SELECT Id FROM ");for await(let B of Vt(this.deps,s,E,void 0,void 0,k))$+=B.length;return $}},objects:u,order:a.map(T=>T.objectApiName),excluded:new Map([...o.excludedObjects].map(T=>[T,null])),referenceData:o.referenceDataObjects,fieldsOf:T=>d.get(T)?.filter(k=>k.queryable).map(k=>({name:k.name,...k.type!==void 0?{type:k.type}:{},...k.groupable!==void 0?{groupable:k.groupable}:{},...k.sortable!==void 0?{sortable:k.sortable}:{},...k.aggregatable!==void 0?{aggregatable:k.aggregatable}:{}})),filterOf:T=>o.objectSoqlFilters?.[T],options:i,budget:p,...o.stream?.wholeReadBound!==void 0?{maxRecordsPerObject:o.stream.wholeReadBound}:{},recordTypeVerdict:(T,k)=>{let v=l.get(T),$=st(k);return v?.lacking.has($)?"recordTypeNotInTarget":v?.closed.has($)?"heldBack":void 0},...n.sourceRequestsLeft!==void 0?{sourceRequestsLeft:n.sourceRequestsLeft}:{},...n.maxRows!==void 0?{maxRows:n.maxRows}:{},...w?{priceCurrencyWrittenIn:w}:{},...m.size>0?{averageBytes:m}:{},now:O,labelsOf:async(T,k)=>{if(k.toLowerCase()!=="recordtypeid")return;let v=(await this.objectInfoOf(s,T))?.recordTypes??[],$=new Map(v.map(E=>[st(E.recordTypeId),E.developerName]));return E=>typeof E=="string"?$.get(st(E)):void 0},signal:this.sampling.signal,...n.onProgress?{onProgress:n.onProgress}:{}})}catch(T){throw T instanceof Jp?new Dd(`${T.message} Or draw among fewer roots: a window of dates (--fit-window) or a filter on the roots of the large objects (--fit-where).`,{rows:T.rows,most:T.most}):T instanceof Qp||this.isAborted?new Re("Forge execution was aborted by user request. Remaining objects were not processed."):T}let{cut:R}=S;if(R.kind==="cannotFit"){let T=R.heaviest.map(I=>`${I.objectApiName} (${I.rows} records${I.whole?", copied whole":""})`).join(", "),k=S.strataFloors,v=R.noRoot?"the objects copied whole and the first root drawn with the records it brings":k?`the objects copied whole and the roots kept of each object and of each value of its strata (${k.roots} roots for the floors of ${k.values} values)`:"the objects copied whole and the roots kept of each object",$=R.noRoot?"Leave objects out (--exclude-object)":k?"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)",E=zw[R.limitedBy],B=R.limitedBy==="storage"||R.limitedBy==="within";throw new Wd(`No sample of the whole org fits: ${v} take ${R.rows} records, ${(R.storageBytes/1048576).toFixed(1)} MB, ${E.past}; the heaviest are ${T}. ${ar} ${$}${E.more}.`,R.heaviest,{limitedBy:R.limitedBy,...B?{needMB:ig(R.storageBytes,"up"),budgetMB:ig(R.limitedBy==="storage"&&p.storageBytes!==void 0?p.storageBytes:p.budget.bytes,"down")}:{},heaviest:R.heaviest.map(I=>I.objectApiName)})}let b=eh({...S,cut:R},i,p.budget);return Gp(n.keepAt,{sourceOrgId:s,fingerprint:n.fingerprint,drawnAt:new Date,drawnBy:o.dryRun?"dryRun":"run",sample:b,...S.newestByIds.length>0?{newestByIds:S.newestByIds}:{},...S.oldestByIds.length>0?{oldestByIds:S.oldestByIds}:{},ids:[...R.ids].map(([T,k])=>({objectApiName:T,ids:k})),counts:{personAccounts:Object.fromEntries(R.personAccounts),byThePlatform:R.byThePlatform.map(T=>({...T}))}})}async averageEmailBytes(e,t){let n=Dg(t,e.config.fieldExclusions[Ee]);if(n.length===0)return;let o=this.filterOf(e,Ee);try{let s=await this.readWholeOf(e,Ee,`SELECT Id, ${n.map(a=>a.name).join(", ")} FROM ${Ee}${o?` WHERE ${o}`:""} LIMIT ${qy}`);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){Ve.warn("[forge] the size of the emails could not be read before the sample was drawn: "+Q(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(st(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(st(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(st(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&&Mt.test(s.lastId)?s.lastId:void 0,d=R=>a===void 0||_r(R,a)>0,c=0;if(!s?.done)for(let R of i)d(R)&&c++;let u=Math.min(c,await this.writtenBeforeOf(e,t,s)),l=e.standardPricebookId,f=o===zt&&l&&i.has(st(l))&&d(l)&&!e.config.writtenBefore.has(l)?Math.min(1,c-u):0,p=Math.max(0,c-u-f),h=Math.min(p,n.counts.personAccounts[o]??0),g=0;o===ae&&h>0&&await this.personAccountsInTarget(e)===!0&&(g=h);let m=n.counts.byThePlatform.find(R=>R.objectApiName===o);m&&(g+=Math.min(p-g,m.inPlan)),p-=g;let w=R=>n.report.dropped.filter(b=>b.objectApiName===o&&b.reason===R).reduce((b,T)=>b+T.rows,0),O={...u>0?{writtenBefore:u}:{},...f>0?{linkedToTarget:f}:{},...g>0?{byThePlatform:g}:{},...w("noParentInSource")>0?{noParentInSource:w("noParentInSource")}:{},...w("outsideFilter")>0?{outsideFilter:w("outsideFilter")}:{}},S=o===ae&&g>0?0:h;return{read:c,counted:{rows:p,...S>0?{personAccounts:Math.min(S,p)}:{}},...Object.keys(O).length>0?{leftOut:O}:{}}}async personContactsBeyondThePlan(e,t){if(!e.sample?.drawn.has(ae))return;let n=t.find(i=>i.objectApiName===ae),o=t.find(i=>i.objectApiName===Te)?.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=Yp({objectApiName:s,columns:_t(a.filter(c=>!kn(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)_r(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,xu(a,Eu(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(h=>Mt.test(h));if(l.length===0)continue;let f=`SELECT ${o.join(", ")} FROM ${a} WHERE ${d?`(${d}) AND `:""}Id IN (${l.map(h=>`'${h}'`).join(", ")})`,p=await this.readWholeOf(e,a,f);if(p.sort((h,g)=>_r(String(h.Id),String(g.Id))),i){let h=new Set(p.map(m=>st(String(m.Id)))),g=t.gone.get(a)??new Set;for(let m of l)h.has(st(m))||g.add(st(m));g.size>0&&t.gone.set(a,g)}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*Fs(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=st(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||_r(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=Zp(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 T of t){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let k=T.objectApiName;if(!T.included||!e.writtenObjects.has(k))continue;let v=s&&!this.streamsNode(T,e);if(n.referenceDataObjects.has(k)){v&&c.push({objectApiName:k,rows:await this.rowsOf(e,T)});continue}let{read:$,counted:E,leftOut:B,capped:I,partial:G}=e.sample?.drawn.has(k)?await this.countToWriteOfThePlan(e,T,e.sample):await this.countToWrite(e,T);e.counted.set(k,$),I&&a.push(k),G&&d.add(k),v&&!e.sample?.drawn.has(k)&&c.push({objectApiName:k,rows:$}),s&&u.push({node:T,read:$,whole:v}),i.push({objectApiName:k,rows:[],counted:E,...B?{leftOut:B}:{}})}let l=e.sample?.drawn.has(ze)?void 0:i.find(T=>T.objectApiName===ze),f=i.find(T=>T.objectApiName===We),p=l?await this.rolesThePlatformWritesOfTheTables(e,t,i,d):void 0;if(l&&p!==void 0&&p>0){let T=Math.min(p,l.counted.rows);l.counted={...l.counted,rows:l.counted.rows-T},l.leftOut={...l.leftOut,byThePlatform:T}}let h=f?.leftOut?.writtenBefore??0,g=l?this.rolesThePlatformMayWriteOfTheCounts(e,l.counted.rows,(p===void 0?f?.counted.rows??0:0)+h):0;if(l&&g>0&&(l.mayBeByThePlatform=p!==void 0?{rows:g,before:!0}:{rows:g}),await this.personContactsBeyondThePlan(e,i),this.isAborted)throw new Re("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 w=s?await this.measureTheWholeOrg(e,i,c,u,m):void 0,O=w&&e.sample?{...w,sample:{report:e.sample.report,byThePlatform:e.sample.counts.byThePlatform}}:w;if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let S=Ls(n),R=n.dryRun&&!s?0:await this.readBackRequests(e,i),b=await o({objects:i,...S!==void 0&&a.length>0?{capped:{perObject:S,objects:a}}:{},...R>0?{readBack:R}:{},...O?{wholeOrg:O}:{},dryRun:n.dryRun});await this.afterTheGate(e,b,i)}async heldAtTheGate(e,t,n){let{config:o}=e,s=t.filter(m=>m.included&&e.writtenObjects.has(m.objectApiName)&&!o.referenceDataObjects.has(m.objectApiName)),i=new Map(s.map((m,w)=>[m.objectApiName,w])),a=new Map,d=new Map,c=new Map,u=cg,l=new Map,f=new Set,p=(m,w,O)=>{let S=a.get(m)??new Map;return S.has(w)||u<=0?!1:(S.set(w,O),a.set(m,S),u--,!0)},h={requests:0,lookups:new Map},g=async(m,w)=>{let O=await this.idsUnder(e,m,w);return h.requests+=Math.max(1,Math.ceil((O?.length??0)/Kn)),O};for(let m of s){if(this.isAborted)break;let w=m.objectApiName;if(e.sample?.drawn.has(w))continue;if(u>0&&this.streamsNode(m,e)){let S=await this.recordTypesOfTable(e,m);if(S&&S.closed.length>0&&this.typesHeldRowByRow(e,S)){let R=new Set(S.lackingInSource);for(let[b,T]of[[S.closedInSource.filter(k=>!R.has(k)),d],[S.lackingInSource,c]]){let k=b.map($=>`'${$}'`).join(", ");if(!k)continue;let v=a.get(w)?.size??0;for(let $ of await g(w,`RecordTypeId IN (${k})`)??[])p(w,$,"held");T.set(w,(a.get(w)?.size??0)-v)}}}let O=await this.deps.describeFields(e.sourceOrgId,w).catch(()=>[]);for(let S of O){let[R]=S.referenceTo??[],b=R===void 0?void 0:i.get(R);if(!S.isReference||(S.referenceTo??[]).length!==1||b===void 0||b>=(i.get(w)??0)||!S.createable||(o.fieldExclusions[w]??[]).includes(S.name)||!Qe(w,S.name,S.nillable)||(h.lookups.set(w,(h.lookups.get(w)??0)+1),u<=0))continue;let T=Be(S.name),k=Be(R),v=await g(w,`${T} != null AND ${T} NOT IN (SELECT Id FROM ${k})`);for(let z of v??[])p(w,z,{field:S.name,parentObject:R,reason:Td(S.name,R)});let $=o.objectSoqlFilters?.[R];if($&&v!==void 0){let z=await g(w,`${T} != null AND ${T} NOT IN (SELECT Id FROM ${k} WHERE (${$}))`);for(let _ of z??[]){let ee={field:S.name,parentObject:R,reason:Ad(S.name,R)};p(w,_,ee)&&f.add(_)}}let E=a.get(R);if(!E||E.size===0)continue;let B=[...E].filter(([,z])=>z==="held").map(([z])=>z),I=[...E].filter(([z,_])=>_!=="held"&&!f.has(z)).map(([z])=>z),G=[...E].filter(([z])=>f.has(z)).map(([z])=>z),re={field:S.name,parentObject:R,reason:lg(S.name,R)};for(let[z,_,ee]of[[B,"held",!1],[I,re,!1],[G,re,!0]])for(let ve of jn(z)){if(u<=0)break;for(let he of await g(w,`${T} IN (${ve})`)??[])p(w,he,_)&&ee&&f.add(he)}}for(let S of O){if(!S.isReference||S.name==="RecordTypeId"||!S.createable||(o.fieldExclusions[w]??[]).includes(S.name)||(S.referenceTo??[]).length===1&&Qe(w,S.name,S.nillable))continue;let R=new Set;for(let T of S.referenceTo??[]){let k=T===w?void 0:a.get(T);if(!(!k||k.size===0))for(let v of jn([...k.keys()])){let $=await g(w,`${Be(S.name)} IN (${v})`);for(let E of $??[])R.add(E)}}for(let T of a.get(w)?.keys()??[])R.delete(T);if(R.size===0)continue;let b=l.get(w)??[];b.push({field:S.name,rows:R.size}),l.set(w,b)}}for(let m of n){let w=l.get(m.objectApiName);w&&(m.leftEmpty=w)}for(let m of n){let w=a.get(m.objectApiName);if(!w||w.size===0)continue;let O=d.get(m.objectApiName)??0,S=c.get(m.objectApiName)??0,R=[...w.values()].filter($=>$==="held").length,b=[...w.keys()].filter($=>f.has($)).length,T=w.size-R-b,k=Math.max(0,m.counted.rows-w.size),v=m.counted.personAccounts;m.counted={rows:k,...v!==void 0&&Math.min(v,k)>0?{personAccounts:Math.min(v,k)}:{}},m.leftOut={...m.leftOut,...O>0?{heldBack:(m.leftOut?.heldBack??0)+O}:{},...S>0?{recordTypeNotInTarget:(m.leftOut?.recordTypeNotInTarget??0)+S}:{},...R-O-S>0?{withoutParent:R-O-S}:{},...T>0?{noParentInSource:T}:{},...b>0?{outsideFilter:b}:{}}}for(let m of a.values())for(let[w,O]of m)e.heldInTheOrg.set(w,O);return h}async pricesReplacedAtTheGate(e,t){let n=t.find(g=>g.objectApiName===tt);if(!n||n.counted.rows<=0||!e.standardPricebookId||(e.counted.get(tt)??0)>cg)return 0;let o=await this.deps.describeFields(e.sourceOrgId,tt).catch(()=>[]);if(!o.some(g=>g.name===yt))return 0;let s=["Id",rn,Mn,yt,...o.some(g=>g.name==="IsActive")?["IsActive"]:[],...e.sellingModels&&o.some(g=>g.name===Zn)?[Zn]:[]],i=this.filterOf(e,tt),a=e.sample,d;try{d=a?.drawn.has(tt)?await this.rowsOfThePlan(e,a,tt,s):await this.readWholeOf(e,tt,`SELECT ${s.join(", ")} FROM ${tt}`+(i?` WHERE ${i}`:""))}catch(g){return Ve.warn(`[forge] the prices replaced in another currency could not be counted at the gate: ${Q(g)}`),1}let c=Math.max(1,Math.ceil(d.length/Kn)),u=e.currencies===void 0,l=d.filter(g=>!e.heldInTheOrg.has(String(g.Id))),f=await this.priceCurrencyInput(e,l,o),p=c+(u&&e.currencies!==void 0?Yw:0);if(!f){let g=e.oneCurrency===void 0,m=await this.pricesKeyOf(e);if(!m.oneCurrency)return p;let w=Math.min(n.counted.rows,$i(l,m).standsFor.length);return w>0&&(n.counted={...n.counted,rows:n.counted.rows-w},n.leftOut={...n.leftOut,currencyReplaced:w}),p+(g&&this.deps.orgCurrency?1:0)}let h=Math.min(n.counted.rows,Va(f,[]).standsFor.size);return h===0||(n.counted={...n.counted,rows:n.counted.rows-h},n.leftOut={...n.leftOut,currencyReplaced:h}),p}async directRelationsAtTheGate(e,t,n){if(e.sample?.drawn.has(Wn))return 0;let o=t.find(p=>p.objectApiName===Wn);if(!o||o.counted.rows<=0||!t.some(p=>p.objectApiName===ae)||n.has(ae)||n.has(Wn))return 0;let s=this.deps.countRecords;if(!s)return 0;let i=e.config.stream?.resumeAfter.get(Wn),a=this.filterOf(e,Wn),d=[...a?[`(${a})`]:[],...i&&Mt.test(i.lastId)?[`Id > '${i.lastId}'`]:[],"IsDirect = true"],c;try{c=await s(e.sourceOrgId,`SELECT COUNT() FROM ${Wn} WHERE ${d.join(" AND ")}`)}catch(p){return Ve.warn(`[forge] the relations the platform writes with the contacts could not be counted at the gate: ${Q(p)}`),1}let u=o.leftOut,l=(u?.writtenBefore??0)+(u?.withoutParent??0)+(u?.noParentInSource??0)+(u?.outsideFilter??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&&Mt.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){Ve.warn(`[forge] the ${t} records held back could not be counted at the gate: ${Q(a)}`);return}}async measureTheWholeOrg(e,t,n,o,s){let{config:i}=e,a=i.stream?.wholeReadBound,d=a===void 0?[]:n.filter(({rows:S})=>S>a).map(({objectApiName:S,rows:R})=>({objectApiName:S,rows:R,bound:a})),c=new Set(o.filter(S=>S.whole).map(S=>S.node.objectApiName)),{writes:u,restOnly:l}=await this.writesOfTheWholeOrg(e,t,c),f=o.find(({node:S})=>S.objectApiName===Ee&&S.included),p=t.find(S=>S.objectApiName===Ee)?.counted?.rows??0,h=f&&p>0?await this.emailBytesOf(e,f.node):void 0,g=i.files?await this.filesOfTheOrg(e,i.files.maxFileBytes):void 0,m=i.keepContactPoints?0:await this.phoneNumbersPastTheFiction(e,o),w=t.find(S=>S.objectApiName===Te)?.counted?.personAccounts??0,O=w>0&&await this.personAccountsInTarget(e)===!1?w:0;return{writes:u,...l?{restOnly:l}:{},...h!==void 0?{emailTextBytes:h}:{},...i.files?{files:g??{unmeasured:!0}}:{},sourceReads:await this.sourceReadsOf(e,o,n,g)+Xw(o,s?.lookups),...s&&s.requests>0?{heldReads:s.requests}:{},...d.length>0?{readWholeOver:d}:{},...m>0?{contactPointsBlanked:m}:{},...O>0?{personAccountsAsBusiness:O}:{}}}async writesOfTheWholeOrg(e,t,n){let{config:o}=e,s=o.writeApi==="auto"&&this.deps.bulkWriteRecords!==void 0,i=await this.restOnlyOfTheWholeOrg(e)??new Set,a=o.stream?.writeWindow??o.stream?.pageSize??Kn,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]:[]],h=0,g=0;for(let m of f?p:[])for(let w=0;w<m;w+=zr){let O=Math.min(zr,m-w);O<2e3||(h++,g+=O)}return{objectApiName:c,rows:l,jobs:h,jobRows:g,restRows:l-g}});return s?{writes:d,restOnly:i}:{writes:d}}restOnlyOfTheWholeOrg(e){return e.config.writeApi==="auto"&&this.deps.bulkWriteRecords!==void 0?e.bulk?Promise.resolve(e.bulk.restOnly):(e.restOnlyRead??=(async()=>{let n=await this.deps.duplicateRuleObjects?.(e.targetOrgId).catch(()=>{});return new Set([...ds,...n??wa])})(),e.restOnlyRead):Promise.resolve(void 0)}async sourceReadsOf(e,t,n,o){let s=c=>Math.max(1,Math.ceil(Math.max(0,c)/Kn)),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===Ee);if(d&&d.read>0&&t.some(({node:c})=>c.objectApiName===lt)){let c=await this.countOf(e,Ee,"ActivityId != null");a+=s(Math.min(c??d.read,d.read))}if(e.config.files){let c=o?.count??0;a+=Md.length+Math.ceil(c/Kn),a+=Math.ceil(c/Nd)+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=Dg(o,e.config.fieldExclusions[n]);if(s.length===0)return 0;let i=e.sample;if(i?.drawn.has(n)){let h=0,g=await this.rowsOfThePlan(e,i,n,["Id",...s.map(m=>m.name)],e.config.stream?.resumeAfter.get(n)?.lastId);for(let m of g)for(let[w,O]of Object.entries(m))w!=="Id"&&typeof O=="string"&&(h+=Buffer.byteLength(O,"utf8"));return h}let a=e.config.stream?.resumeAfter.get(n),d=this.filterOf(e,n),c=[...d?[`(${d})`]:[],...a&&Mt.test(a.lastId)?[`Id > '${a.lastId}'`]:[]],u=c.length>0?` WHERE ${c.join(" AND ")}`:"",l=["Id",...s.map(h=>h.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 h of p){for(let g of h)for(let[m,w]of Object.entries(g))m!=="Id"&&typeof w=="string"&&(f+=Buffer.byteLength(w,"utf8"));if(this.isAborted)break}}finally{await p.return(void 0)}return f}catch(o){Ve.warn("[forge] the size of the emails could not be read \u2014 measured by their count: "+Q(o));return}}async filesOfTheOrg(e,t){let n=0,o=0,s=0;for(let{object:i,size:a,where:d}of Md){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){Ve.warn(`[forge] the files of ${t} could not be measured: ${Q(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 qa(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-ap)}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 _=>{if(!d)return;let ee=[...i?[`(${i})`]:[],..._?[_]:[],...s&&Mt.test(s.lastId)?[`Id > '${s.lastId}'`]:[]],ve=ee.length>0?` WHERE ${ee.join(" AND ")}`:"",he=`SELECT COUNT() FROM ${Be(n)}${ve}`;try{return await(a?d(e.sourceOrgId,he,a):d(e.sourceOrgId,he))}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,h=l===void 0?p:Math.min(p,l),g=Ls(e.config),m=g===void 0?void 0:Math.max(0,g-(s?.read??0)),w=m!==void 0&&l===m&&p>m,O=o?await this.recordTypesOfTable(e,t):void 0;if(O&&O.closed.length>0&&!this.typesHeldRowByRow(e,O))return{read:h,counted:{rows:0},...h>0?{leftOut:pg(O.closed,h)}:{}};let S=Math.min(h,await this.writtenBeforeOf(e,t,s)),R=n===zt?Math.min(h-S,await this.standardBookOfTheTable(e,c)):0,b=h-S-R,T=S>0||R>0?{...S>0?{writtenBefore:S}:{},...R>0?{linkedToTarget:R}:{}}:void 0,k=_=>_===void 0?{rows:b}:{rows:b,personAccounts:_},v=h<p,$=_=>({read:h,counted:k(_),...T?{leftOut:T}:{},...w?{capped:!0}:{},...v?{partial:!0}:{}});if(n!==Te&&n!==ae||!(await this.deps.describeFields(e.sourceOrgId,n).catch(()=>[])).some(_=>_.name==="IsPersonAccount"))return $();let B=await c("IsPersonAccount = true"),I=B===void 0?void 0:Math.min(B,b);if(n!==ae||B===void 0||f===void 0)return $(I);let G=await this.personContactsTakenAsBusinessAtTheGate(e,c);if(G===void 0)return $(I);let re=Math.max(0,B-G-(f-h)-S);if(re===0)return $(I);let z=(I??0)-re;return{read:h,counted:{rows:b-re,...z>0?{personAccounts:z}:{}},leftOut:{...T,byThePlatform:re},...w?{capped:!0}:{},...v?{partial:!0}:{}}}async standardBookOfTheTable(e,t){let n=e.standardPricebookId;return!n||!Mt.test(n)||e.config.writtenBefore.has(n)?0:this.filterOf(e,zt)?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,Te).catch(()=>[])).some(d=>d.name==="RecordTypeId"&&d.createable)&&!(o.fieldExclusions[Te]??[]).includes("RecordTypeId")&&o.fieldMappings[Te]?.RecordTypeId===void 0)){let d=Ga((await this.objectInfoOf(e.targetOrgId,Te))?.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=>Mt.test(d)))return t(`IsPersonAccount = true AND Account.RecordTypeId IN (${a.map(d=>`'${d}'`).join(", ")})`)}async idsTheTargetLacks(e,t,n,o){return jp({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=>Ns(e,s)})}async inactiveOwnersToLeaveOut(e,t,n){if(!n||e.inactiveUsers.size===0)return;let o=$p(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=Id(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=Pd(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&&!Ns(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=ty(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(st(String(l.Id)))){i.set(f,{field:Mn,parentObject:tt,reason:Uy}),c.add(f);return}for(let{field:h,parent:g}of d){let m=l[h];if(typeof m!="string"||m===""||t.remapper.get(m))continue;let w=t.sample;if(w?.drawn.has(g)){this.inThePlan(w,g,m)?w.gone.get(g)?.has(st(m))?a.set(f,{field:h,parentObject:g,reason:ey(h,g)}):i.set(f,{field:h,parentObject:g}):(i.set(f,{field:h,parentObject:g,reason:Zw(h,g)}),c.add(f));return}let O=t.heldInTheOrg.get(m);if(O==="held"){i.set(f,{field:h,parentObject:g});return}if(O){let R=O===Sd?Td(h,g):O===ug?Ad(h,g):lg(h,g);a.set(f,{field:h,parentObject:g,reason:R});return}let S=u.get(g)??new Map;S.set(m,[...S.get(m)??[],{index:f,field:h}]),u.set(g,S)}});for(let[l,f]of u){let p=[...f.keys()],h=t.config.objectSoqlFilters?.[l],g=h===void 0?void 0:await this.idsInTheSource(t,l,p,h),m=g?p.filter(S=>!g.has(S.slice(0,15))):p,w=m.length>0?await this.idsInTheSource(t,l,m):new Set,O=S=>{let R=S.slice(0,15);if(!(g?.has(R)===!0||w===void 0))return w.has(R)?g?ug:void 0:Sd};for(let[S,R]of f){let b=O(S);b&&t.heldInTheOrg.set(S,b);for(let{index:T,field:k}of R)i.has(T)||a.has(T)||(b?a.set(T,{field:k,parentObject:l,reason:b===Sd?Td(k,l):Ad(k,l)}):i.set(T,{field:k,parentObject: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,o){let s=new Set,i=o===void 0?"":`(${o}) AND `;try{for(let a of jn(n)){let d=await this.deps.queryRecords(e.sourceOrgId,`SELECT Id FROM ${Be(t)} WHERE ${i}Id IN (${a})`);for(let c of d)s.add(String(c.Id).slice(0,15))}return s}catch(a){Ve.warn(`[forge] whether the source holds the ${t} records named could not be read: ${Q(a)}`);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 h of jn(d)){let g=`SELECT COUNT() FROM ${Be(s)} WHERE (${f}) AND Id IN (${h})`;p+=await(l?u(e.sourceOrgId,g,l):u(e.sourceOrgId,g))}return p}catch{return d.length}}async streamNode(e,t,n){let o=e.objectApiName,s=o===Ee&&t.emailsInTwoPasses&&!n;s&&(t.emailsFirstPassRan=!0);let i=t.config.stream?.resumeAfter.get(Jo(o,n?.name)),a={ended:!1,taken:0,read:i?.read??0,...i?{resumeAfter:i.lastId,lastId:i.lastId}:{},carry:Nw(),...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)??sg(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 Re("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===Te&&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!==Ee||!e.emailsInTwoPasses)return{};let o=e.emailsLeftForTheirTask;return{say:this.endOfTheEmails(e,!1),...o>0?{note:`, ${Cs(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),cn(this.deps.describeFields,s,i).catch(()=>{})]);if(!c.some(E=>E.name==="RecordTypeId"&&E.createable)||u&&!u.creatable.has("RecordTypeId"))return d;let f=n.stream?.resumeAfter.get(i),p=this.filterOf(e,i),h=[...p?[`(${p})`]:[],...f&&Mt.test(f.lastId)?[`Id > '${f.lastId}'`]:[]],g=h.length>0?` WHERE ${h.join(" AND ")}`:"",m=`FROM ${Be(i)}${g}`,w=await this.readWholeOf(e,i,`SELECT RecordTypeId, COUNT(Id) n ${m} GROUP BY RecordTypeId`),O=w.reduce((E,B)=>E+(typeof B.n=="number"&&B.n>0?B.n:0),0),S=nl(w),R=async E=>[...tl(i,E,a.recordTypes),...await this.typesTheTargetLacks(e,i,E,a)],b=await R(this.recordTypesAsSent(e,S)),T=E=>{let B=new Set(E.map(I=>I.recordTypeId));return[...S.keys()].filter(I=>[...this.recordTypesAsSent(e,[[I,1]]).keys()].some(G=>B.has(G)))},k=(E,B)=>({closed:E,rows:B,target:a,closedInSource:T(E),lackingInSource:T(E.filter(I=>I.unmapped))}),v=this.readBound(e,t),$=v===void 0?void 0:Math.max(0,v-(f?.read??0));if(b.length>0&&$!==void 0&&O>$){let E=await this.recordTypesOfTheRowsRead(e,i,m,$);if(E)return k(await R(this.recordTypesAsSent(e,E.counts)),E.rows)}return k(b,O)}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(qo(t,n,o.recordTypes,[]).length===0)return[];let i=await this.sourceRecordTypesOf(e,t);return e.gaps?.knowRecordTypes(t,"source",i),qo(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 qo(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(hg(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:[Go(i)]}))}),t.onProgress({objectName:s,status:"error",progress:100,message:`${Pn(s,o,Qt(t,s))}: `+n.closed.map(Uo).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?kd:0,c;for(let f=0;;f++)try{c=await n.pages.next();break}catch(p){let h=Eg(p);if(!h&&!Ig(p)||f>=d||this.isAborted)throw p;let g=n.lastId===void 0?o:s?.(n.lastId);if(g===void 0)throw p;h||await xg(ng*2**f),Ve.warn(`[forge] ${t.objectApiName}: the source ${h?"let its cursor expire":"did not answer"} after ${n.read} row(s) \u2014 reading on from the last one (${f+1}/${d}): `+Q(p)),n.pages=a(g)}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 qs(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=Ls(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=[...Od(n),...d],l=Vn(u),f=v=>{t.failedObjects.add(a),i({objectName:a,status:"error",progress:100,message:v})};if(n.heldWhole!==void 0){f(`${Pn(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(Qr(a,c));return}let p=Zh(n);if(n.personContactsUnlinked>0&&n.withTheirAccount===0&&n.sent===0&&n.writtenBefore===0&&n.withoutParent===0){f(`${Pn(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(`${Pn(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 h=p+n.failed,g=h>0?n.failed/h:0,m=n.failed>0&&n.alreadyExists===n.failed,w=n.failed>0&&!m&&(p===0||g>.5),O=Xo(n.picklists.list())+Lo(n.currencies.list())+vd(n.lookupsNotCarried)+Fd(n.ownersInactive)+Ed(n.lookupsOutsideTheRun)+xd(n.lookupsHeldBack)+Bd(t,a),S=cs(n.writtenWithoutFields),R=Mg(t,a),b=rg(t,a),T=bg(n.sentOnTheirOwn);if(w){p>0&&t.failedInPart.add(a),f(p===0?`Failed all ${a} records: ${n.failed+l} failed${ln(u)}${T}${O}${b}`:`${n.failed+l}/${h+l} ${a} records failed (>50%)${ln(u)}${T}${O}${S}${R}${b}`+gg);return}let k=eg(n);i({objectName:a,status:"done",progress:100,message:`${o.label??`${s.dryRun?"Simulated":"Completed"} ${a}`}: ${$d(s,a,n,u,jd(t,a))}${o.note??""}${T}${k}${O}${S}${R}${Ws(t,a)}${b}`})}stopStreamedNode(e,t,n,o,s){let i=e.objectApiName,a=o+n.rowsLeft();Cd(t,i,a),this.mergePageReports(t,i,n),this.saySentOnTheirOwn(t,n.sentOnTheirOwn,n.onTheirOwnWhy);let d=[...Od(n),...Qt(t,i)],c=Zh(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}: ${$d(t.config,i,n,d,jd(t,i))}, ${a} not sent${bg(n.sentOnTheirOwn)}${eg(n)}${Xo(n.picklists.list())}${Lo(n.currencies.list())}${vd(n.lookupsNotCarried)}${Fd(n.ownersInactive)}${Ed(n.lookupsOutsideTheRun)}${xd(n.lookupsHeldBack)}${Bd(t,i)}${cs(n.writtenWithoutFields)}${Ws(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,py)},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=vo(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(!vo(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=Ou[t];if(!n||!this.deps.updateRecords)return;let o=e.lifecycles.get(t);return o||(o=ku(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&&Ir[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"&&vo(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 Bg(n)){let i=0,a=[];for(let d=0;d<s.length;d+=us.rest){let c=s.slice(d,d+us.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:[Q(l)]}))}c.forEach(({id:l,status:f},p)=>{let h=u[p];h?.success||(i++,a.length<3&&a.push({recordSummary:`${o} ${l} Status=${f}`,messages:h?.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:[Q(l)]}))}d.forEach(({id:l,status:f},p)=>{let h=u[p];if(h?.success){n.gaveStatus(a,l);return}c.failed++,c.samples.length<3&&c.samples.push({recordSummary:`${a} ${l} Status=${f}`,messages:h?.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>=us.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(Ir)){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 g=d.held.get(u);g&&(p=`none of its ${i.object} records can be written without ${g.excluded}`+(g.target?Xr(g.target):", which is excluded from this run"))}if(!p)continue;f&&n.add(f);let h=f!==void 0&&!e.simulated?.has(f)?f:u;c.push({recordSummary:`${s} ${h} 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 Bg(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=>Jw(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=>!un(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)+Vn(d);return t.onProgress({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (parent failed)`+(c>0?`: ${c} failed${ln(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 h=u[f.name];if(typeof h=="string"&&h&&!t.remapper.get(h)){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){Lw(u)&&i.push(c);for(let l of u)if(!(!l.isReference||!Er(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=uf(o,i),d=t.get(tt)?.some(c=>c.name===yt);return ga(ss(n,t),[...s,...a,...d?wp(o,i,[...s,...a]):[],...Ni(o),...Bi(o,t),...Op(o,t),...qi(o)])}async singlePassOrder(e){let t=e.graph.nodes.filter(o=>o.included);if(!t.some(o=>wt(o.objectApiName))){let o=new Set(t.map(i=>i.objectApiName)),s=new Map;return o.has(Te)&&o.has(ae)&&(await Promise.allSettled([Te,ae].map(a=>this.deps.describeFields(e.sourceOrgId,a)))).forEach((a,d)=>{a.status==="fulfilled"&&s.set([Te,ae][d],a.value)}),ga(ss(e.graph,s),[...Ni(o),...Bi(o,s),...qi(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=Ir[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(Vr(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=Cw[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(Vr(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=sf(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:h})=>this.deps.describeFields(t,h)))).forEach((h,g)=>{if(h.status!=="fulfilled")return;let{objectApiName:m,level:w}=f[g];a.set(m,h.value);for(let O of h.value){let S=O.referenceTo??[];if(!O.isReference||S.length!==1)continue;let[R]=S;R===m||!(o.has(R)||i.has(R))||of(m,O)&&(o.delete(R)&&(i.set(R,w+1),u.push({objectApiName:R,level:w+1})),!s.has(`${R}|${m}`)&&(s.add(`${R}|${m}`),d.push({sourceObject:R,targetObject:m,relationshipName:O.name,type:"lookup",required:Qe(m,O.name,O.nillable)})))}})}c=u}return i.size===0?e:{...e,nodes:[...e.nodes,...[...i].map(([u,l])=>Vr(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(rs),i=o(xr);if(!o(tt)||!s||!i||n.has(Ht)||e.nodes.some(u=>u.objectApiName===Ht))return e;let a;try{a=await this.deps.describeFields(t,Ht)}catch{return e}let d=Vr(Ht,a,Math.max(s.level,i.level)+1),c=(u,l)=>({sourceObject:u,targetObject:Ht,relationshipName:l,type:"lookup",required:!0});return{...e,nodes:[...e.nodes,d],edges:[...e.edges,c(rs,"Product2Id"),c(xr,"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=jg(e),d=[...e.mayHaveBeenWritten].map(([c,u])=>({objectApiName:c,sourceIds:[...u]}));return{successCount:e.successCount,updatedCount:e.updatedCount,linkedCount:e.linkedCount,...e.linkedToCreatedCount>0?{linkedToCreatedCount:e.linkedToCreatedCount}:{},wouldInsertCount:e.wouldInsertCount,failedCount:e.failedCount,skippedCount:e.skippedCount,remapCount:Object.keys(s).length,errors:[...e.errors,...ly(e),...ay(e),...yy(e),...by(e),...Oy(e),...Fy(e)],truncatedObjects:[...e.truncatedObjects],...dg(e),...e.fieldExclusionsUnmatched.length>0?{fieldExclusionsUnmatched:[...e.fieldExclusionsUnmatched]}:{},...Kw(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])=>_y(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}:{},...Gy(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(jg(e)),l=new Map((e.preread.get(t.objectApiName)?.records??[]).map(m=>[String(m.Id),m])),f=m=>{let w=l.get(m);return e.simulated!==null&&t.objectApiName===ae&&w!==void 0&&sn(w)&&!e.contactsOnTheirOwn.has(m)&&typeof w.AccountId=="string"&&e.remapper.wasCreated(w.AccountId)},p=0,h=[],g=(m,w)=>{if(h.length>=Sn)return;let O=w&&e.simulated===null?e.remapper.get(m):void 0;h.push(O!==void 0?{source:m,target:O}:{source:m})};for(let m of t.ids){if(!e.idsRead.has(m)){n.push(m),g(m,!1);continue}s++,e.remapper.wasCreated(m)||c.has(m)?(i++,g(m,!0)):u.has(m)||f(m)?(i++,p++,g(m,!0)):e.remapper.isExisting(m)?(a++,g(m,!0)):(o.push({id:m,reason:d}),g(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:h,...t.ids.size>h.length?{idsLeftOut:t.ids.size-h.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 Kr,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 xp({scope:e.fileScope,sourceOrgId:e.sourceOrgId,maxFileBytes:o.maxFileBytes,queryRecords:s.queryRecords}),a=Pp(i);if(a&&!t.dryRun)throw new xn(`${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 Mp(s,e.targetOrgId)}catch(p){let h=`The file storage the target has left could not be read (${Q(p)}), so the files could not be checked against it.`;if(!t.dryRun)throw new xn(`${h} Nothing was written.`,"FILE_STORAGE_UNREAD");e.errors.push(td(h))}e.files=Bp(c,o.maxFileBytes,u),a&&(e.files.lookupFailure=a);let l=Cp(c.files),f=u===void 0?null:Np(l,u);if(f&&u!==void 0&&!t.dryRun)throw new xn(`${f} Nothing was written.`,"FILE_STORAGE_EXCEEDED",{neededBytes:l,remainingBytes:u});if(f&&e.errors.push(td(f)),t.dryRun){e.files.wouldCopy=c.files.map(({objectApiName:p,sourceId:h,name:g,bytes:m})=>({objectApiName:p,sourceId:h,name:g,bytes:m}));for(let p of e.files.objects)n({objectName:p.objectApiName,status:"done",progress:100,message:Lp(p)});return[]}return d}async filesCopiedBefore(e,t,n){let{store:o}=e;if(!o||e.config.dryRun)return t;let s=await Fp({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 nd({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:Ms(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??Ty;for(let d of Md){let{counted:c}=d,u=e.config.stream?.resumeAfter.get(Jo(c,$g));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,h=u&&Mt.test(u.lastId)?u.lastId:void 0;for(let g=!1;!g;){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let m=await this.filesPageAfter(e,c,f,h,a);if(!m)break;g=m.length<a;let w=!0;for(let S=0;S<m.length;S+=Nd){let R=m.slice(S,S+Nd),b=d.object==="ContentVersion"?await this.documentsOnTheRunsRecords(e,R):Ay(e,R);if(!b){w=!1;break}if(b.length===0)continue;let T=await this.filesCopiedBefore(e,b,n);for(let v of T){if(v.into?.unchanged)continue;let $=vg(o,v.objectApiName);$.planned++,$.plannedBytes+=v.bytes}s+=T.filter(v=>v.into?.unchanged).length,e.failedCount+=await nd({files:T,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:v=>e.remapper.wasCreated(v),get:v=>e.remapper.get(v),add:(v,$,E)=>e.remapper.add(v,$,E),persist:()=>e.remapper.persist()},deps:n,report:o,errors:e.errors,waitIfPaused:()=>this.waitIfPaused(),onProgress:()=>{},...e.store?{calls:Ms(e.store)}:{}});let k=vg(o,c);i(c,`Copying files: ${k.copied} of ${k.planned} copied so far`)}if(!w)break;p+=m.length;let O=m[m.length-1]?.Id;typeof O=="string"&&(h=O),h!==void 0&&e.store?.checkpoint(c,{lastId:h,read:p,...g?{done:!0}:{}},$g)}}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&&Ve.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: ${Q(a)}`]}]});return}}async readOnPassingFailure(e,t){for(let n=0;;n++)try{return await t()}catch(o){let s=Eg(o);if(!s&&!Ig(o)||n>=kd||this.isAborted)throw o;s||await xg(ng*2**n),Ve.warn(`[forge] ${e}: the source ${s?"let its cursor expire":"did not answer"} \u2014 asking again (${n+1}/${kd}): ${Q(o)}`)}}async documentsOnTheRunsRecords(e,t){let n=new Map;for(let d of t){let c=d.ContentDocumentId;typeof c=="string"&&Mt.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(g=>g.id===l))continue;let p=c.ShareType,h=c.Visibility;f.push({id:l,...typeof p=="string"?{shareType:p}:{},...typeof h=="string"?{visibility:h}:{}}),o.set(u,f)}}catch(d){s(`Not read, so not copied \u2014 a run taken up reads them again: ${Q(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,h=u.PathOnClient,g=u.ContentSize;a.push({objectApiName:"ContentDocument",sourceId:d,body:{objectApiName:"ContentVersion",id:l},name:p,bytes:typeof g=="number"&&Number.isFinite(g)?g:0,hosts:c,fields:{Title:p,PathOnClient:typeof h=="string"&&h!==""?h: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 Re("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&&!_g(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=an({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:Je,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>=_w)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 Re("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||Je.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)||!Er(c)||!Qe(t,c.name,c.nillable))continue;let[l]=u;if(l===t||l===i.rootObjectApiName||Je.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),h=e.heldForExclusions.get(l);for(let g of o){let m=g[c.name];typeof m!="string"||m===""||f?.has(m)||p?.has(m)||h?.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 Re("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 h=_t(p.fields,i.fieldExclusions[c]);(await this.readMore(e,l,p.fields,new vn().buildById({objectApiName:c,selectFields:h.length>0?h:["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<Uw&&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 Re("Forge execution was aborted by user request. Remaining objects were not processed.");let h=await this.refusalOf(e,f,n.get(f),o);h?await this.holdBackForARefusedParent(e,f,h,p,s):u.push([f,p])}let l=[];for(let[f,p]of u){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let h=Gw(e,p);if(h.ids.size===0)continue;let g=await this.readParentsById(e,f,n.get(f),h);g&&l.push(g)}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 h=p.referenceTo??[];if(!p.isReference||h.length!==1||f.has(p.name)||!Er(p)||!Qe(c,p.name,p.nillable))continue;let[g]=h;if(g===c||g===s.rootObjectApiName||Je.has(g)||s.referenceDataObjects.has(g)||s.excludedObjects.has(g)||Ns(e,g))continue;let m=o.get(g);if(m&&(!n||!m.included||e.failedObjects.has(g)))continue;let w=e.askedForRowsThatNeedThem.get(g),O=e.heldForExclusions.get(g);for(let S of l){let R=S[p.name];if(typeof R!="string"||R===""||un(s,S)||e.remapper.get(R)||e.leftToThePlatform.has(R)||w?.has(R)||O?.has(R)||d(g).has(R))continue;let b=i.get(g);b||(b={ids:new Set,neededBy:new Set,rows:[]},i.set(g,b)),b.ids.add(R),b.neededBy.add(c),b.rows.push({objectApiName:c,row:S,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){sr(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 cn(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(k){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:[Q(k)]}]});return}u=l.filter(k=>!kn(k))}let f=e.askedForRowsThatNeedThem.get(t)??new Set;for(let k of o.ids)f.add(k);e.askedForRowsThatNeedThem.set(t,f);let p=_t(u,s.fieldExclusions[t]),h=new vn().buildById({objectApiName:t,selectFields:p.length>0?p:["Id"],ids:o.ids,extraWhere:s.objectSoqlFilters?.[t]});this.holdTheRootsReading(e,t,h.length);let g;try{g=await Gr(d>0?ma(h,d,{byIdCount:h.length}):{kind:"query",statements:h,byIdCount:h.length},k=>this.deps.queryRecords(e.sourceOrgId,k,()=>e.truncatedObjects.add(t)),void 0,()=>e.cappedObjects.add(t))}catch(k){if(k instanceof Re)throw k;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:[Q(k)]}]});return}Jr(e,g);let m=new Set((c?.records??[]).flatMap(k=>typeof k.Id=="string"?[k.Id]:[])),w=g.filter(k=>typeof k.Id!="string"||!m.has(k.Id)),O=k=>(e.graph.nodes.find(v=>v.objectApiName===k)??e.parentsOutside.get(k))?.level??0,S=n??e.parentsOutside.get(t)??Vr(t,u,1+Math.max(0,...[...o.neededBy].map(O))),R=new Set(e.heldForExclusions.get(t)?.keys()??[]);this.holdBackWhatExclusionsCost(e,S,u,w,void 0,await this.excludedByKeyPrefix(e,t,u));let b=[...e.heldForExclusions.get(t)??[]].filter(([k])=>!R.has(k));if(this.leaveToThePlatform(e,t,w,u),w.length===0&&b.length===0)return;let T=c?.createableSet??new Set(u.filter(k=>k.createable).map(k=>k.name));if(w.length>0){e.preread.set(t,c?{...c,records:[...c.records,...w]}:{fieldInfos:u,createableSet:T,records:w,targetSetsPending:null}),l&&this.withoutFileContent(e,t,l,!0),n?c||e.skippedCount--:(e.parentsOutside.set(t,S),e.writtenObjects.add(t));let k=w.find($=>typeof $.Id=="string")?.Id;typeof k=="string"&&!e.sourceKeyPrefixes.has(t)&&e.sourceKeyPrefixes.set(t,k.slice(0,3));let v=e.readAsParents.get(t)??{count:0,neededBy:new Set};v.count+=w.length;for(let $ of o.neededBy)v.neededBy.add($);e.readAsParents.set(t,v)}else if(!n){let k=e.heldForExclusions.get(t);k&&e.onProgress({objectName:t,status:"error",progress:100,message:Qr(t,k,!1)})}if(e.readByObject.set(t,(e.readByObject.get(t)??0)+w.length+b.length),this.holdTheRootsRows(e,t),s.dryRun){let k=w.length>0?await this.writtenWithTheirAccountOnADryRun(e,t,w,T):0,v=c?"more ":"";e.onProgress({objectName:t,status:"running",progress:0,message:`[dry-run] ${t}: ${w.length-k} ${v}record(s) would be inserted`+(k>0?`, ${k} ${v}would be written by the platform with ${Dn(t)}`:"")+`, which the ${i} records cannot be written without: read by id, nothing read under them`+_s(Ds(b.map(([,$])=>$)),c!==void 0)})}return w.length>0?{objectApiName:t,fieldInfos:u,records:w}: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 Re("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(I=>!kn(I)),p=new Set(f.filter(I=>I.createable).map(I=>I.name));if(await this.skipForFailedParent(e,t,f))return!1;if(n&&e.objectApiName!==s.rootObjectApiName){let I=Ww(e.objectApiName,f,t.turnsAhead);if(I)return t.waitingFor.set(I,[...t.waitingFor.get(I)??[],e]),!1}let h={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:jy(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:Je,rootReadAgain:!n&&e.objectApiName===s.rootObjectApiName},g=an(h);if(n&&this.waitsForWhatPointsAtIt(e,g,t))return t.catalogNodes.push({node:e,fieldInfos:f}),!1;if(g.kind==="skip"){if(n&&g.reason===ha)return t.deferredNodes.push(e),!1;let I=t.heldForExclusions.get(e.objectApiName);return I&&I.size>0?(t.readByObject.set(e.objectApiName,I.size),d({objectName:e.objectApiName,status:"error",progress:100,message:Qr(e.objectApiName,I,!1)}),!1):(t.skippedCount++,d({objectName:e.objectApiName,status:"skipped",progress:100,message:`Skipped ${e.objectApiName} (out of scope: ${g.reason})`}),!1)}if(t.notCreatable.has(e.objectApiName)){let I=an({...h,maxRecordsPerObject:1}),G=I.kind==="query"?await Gr(I,re=>this.deps.queryRecords(i,re)):[];return this.reportNotCreatable(e,t,G.length>0),!1}if(this.holdTheRootsReading(t,e.objectApiName,g.statements.length),t.roots&&g.readUnder){let I=t.readUnder.get(e.objectApiName)??new Set;for(let G of g.readUnder)I.add(G);t.readUnder.set(e.objectApiName,I)}let w=o&&!s.referenceDataObjects.has(e.objectApiName)?u?.targetSets??cn(this.deps.describeFields,a,e.objectApiName).then(I=>({ok:!0,sets:I}),I=>({ok:!1,error:I})):null;u&&(u.targetSets=w);let O=t.scopeCache?new Set:void 0,S=u?I=>{let G=an({...h,maxRecordsPerObject:u.room===void 0?void 0:Math.max(1,u.room),inIdOrder:{afterId:I}});return G.kind==="query"&&G.statements.length===1?G.statements[0]:void 0}:void 0,R=await Gr(g,I=>u?this.nextPage(t,e,u,I,S):this.readWhole(t,e.objectApiName,I),O,()=>t.cappedObjects.add(e.objectApiName));if(u?.ended&&R.length===0&&u.taken>0)return!1;let b=u?.pass?R.filter(u.pass.keep):R;Jr(t,b),this.keepWhatStatusesNeed(t,e,b,O);let T=this.holdBackWhatExclusionsCost(t,e,f,b,O,await this.excludedByKeyPrefix(t,e.objectApiName,f));O&&t.scopeCache?.addReached(e.objectApiName,O);let k=b.find(I=>typeof I.Id=="string")?.Id;if(typeof k=="string"&&!t.sourceKeyPrefixes.has(e.objectApiName)&&t.sourceKeyPrefixes.set(e.objectApiName,k.slice(0,3)),s.referenceDataObjects.has(e.objectApiName)){t.readByObject.set(e.objectApiName,b.length);let I=await t.referenceDataMapper.resolve(e.objectApiName,b,a);for(let G of I.mappings)c.addExisting(G.sourceId,G.targetId);return I.unmatched.length>0&&t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:I.unmatched.length,attemptedCount:b.length,referenceData:!0,samples:Hw(e.objectApiName,I.unmatched)}),t.scopeCache&&ff(t.scopeCache,e.objectApiName,b),t.linkedCount+=I.mappings.length,d({objectName:e.objectApiName,status:"done",progress:100,message:`Mapped ${e.objectApiName} via reference-data lookup: ${I.mappings.length} resolved, ${I.unmatched.length} unmatched`}),!1}if(this.leaveToThePlatform(t,e.objectApiName,b,f),e.objectApiName===zt&&t.standardPricebookId){let I=t.standardPricebookId,G=b.filter(re=>re.Id!==I);G.length!==b.length&&(b.length=0,b.push(...G))}let v=t.scopeCache;if(n&&v&&Je.has(e.objectApiName))return as(v,e.objectApiName,b,f,{settle:!1,keyPrefixes:await this.keyPrefixesNamedBy(t,f)}),t.catalogNodes.push({node:e,fieldInfos:f}),t.readAtItsTurn.set(e.objectApiName,{records:b,fieldInfos:f}),!1;let $=t.heldForExclusions.get(e.objectApiName);if(T>0&&b.length===0&&$&&!u)return t.failedObjects.add(e.objectApiName),t.readByObject.set(e.objectApiName,$.size),d({objectName:e.objectApiName,status:"error",progress:100,message:Qr(e.objectApiName,$)}),!1;if(wt(e.objectApiName)&&t.standardPricebookId){await this.addStandardPricebookEntries(e,t,b,f);let I=t.sample;if(I?.drawn.has(e.objectApiName)){let re=b.filter(ee=>this.inThePlan(I,e.objectApiName,String(ee.Id)));b.length=0,b.push(...re);let z=t.standardPricebookId,_=new Set(b.filter(ee=>ee[rn]===z).map(ee=>Ld(ee,t.sellingModels)));for(let ee of b)ee[rn]!==z&&(_.has(Ld(ee,t.sellingModels))||I.withoutStandard.add(st(String(ee.Id))))}t.readsEverythingFirst||await this.pricesInTheCurrencyWritten(e,t,b,f);let G=await this.keptPrices(t,b);G.length!==b.length&&(b.length=0,b.push(...G))}t.scopeCache&&as(t.scopeCache,e.objectApiName,b,f,{keyPrefixes:await this.keyPrefixesNamedBy(t,f)}),await this.notePastDraft(t,e.objectApiName,b);let E=e.objectApiName===s.rootObjectApiName||Je.has(e.objectApiName)?[]:Dw(e.objectApiName,f,t),B=new Set(n?[...t.waitingFor.values()].flat().map(I=>I.objectApiName):[]);for(let I of E){let G=t.readAgainUnder.get(I)??[];t.readAgainUnder.set(I,[...G,{node:e,fieldInfos:f,whileWaiting:B.has(I)}])}if(s.files&&s.stream?.everything!==!0){let I=b.flatMap(G=>typeof G.Id=="string"&&!s.writtenBefore.retried(G.Id)?[G.Id]:[]);t.fileScope.set(e.objectApiName,I)}if(this.withoutFileContent(t,e.objectApiName,l,b.length>0),u&&(u.carry.rows+=b.length),u?.pass||t.readByObject.set(e.objectApiName,(u?u.carry.rows:b.length)+($?.size??0)),this.holdTheRootsRows(t,e.objectApiName),t.preread.set(e.objectApiName,{fieldInfos:f,createableSet:p,records:b,targetSetsPending:w}),s.dryRun){let I=await this.writtenWithTheirAccountOnADryRun(t,e.objectApiName,b,p),G=b.length-I;d({objectName:e.objectApiName,status:"running",progress:0,message:`[dry-run] ${e.objectApiName}: ${G} record(s) would be inserted`+(I>0?`, ${I} would be written by the platform with ${Dn(e.objectApiName)}`:"")+wg(t,e.objectApiName)})}return await this.readWhatTheyCannotBeWrittenWithout(t,e.objectApiName,f,b),!0}catch(l){if(l instanceof Re||l instanceof qs||Ba(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,sg(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:[Q(l)]}]}),d({objectName:e.objectApiName,status:"error",progress:100,message:`Error on ${e.objectApiName}: ${Q(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(R=>R.isReference&&Qe(d,R.name,R.nillable)),u=c.filter(R=>{let b=R.referenceTo??[];return b.length===1&&b[0]!==d&&a.has(b[0])}),l=c.filter(R=>{let b=R.referenceTo??[];return b.length>1&&b.some(T=>a.has(T))}),f=d===tt&&e.sellingModels&&a.has(Ht),p=kg(d),h=c.length>0&&e.heldForExclusions.size>0;if(u.length===0&&l.length===0&&!h&&!f&&!p)return 0;let g=R=>{for(let k of u){let v=R[k.name];if(typeof v=="string"&&v!==""&&!e.remapper.get(v))return{field:k.name,excluded:(k.referenceTo??[])[0]}}for(let k of l){let v=R[k.name];if(typeof v!="string"||v===""||e.remapper.get(v))continue;let $=i.get(v.slice(0,3));if($!==void 0&&(k.referenceTo??[]).includes($))return{field:k.name,excluded:$}}let b=h?yg(e,R,c):void 0;if(b)return b;let T=R[Zn];if(f&&typeof T=="string"&&T!=="")return{field:Zn,excluded:Ht}},m=e.heldForExclusions.get(d)??new Map,w=p?e.statusChildrenRead.get(p.parent)??{kept:new Set,held:new Map}:void 0,O=[];for(let R of o){let b=g(R),T=p?R[p.lookup]:void 0;if(!b){O.push(R),w&&typeof T=="string"&&w.kept.add(T);continue}w&&typeof T=="string"&&!w.held.has(T)&&w.held.set(T,b);let k=R.Id;typeof k=="string"&&(s?.delete(k),!m.has(k)&&(m.set(k,b),e.failedCount++))}w&&p&&e.statusChildrenRead.set(p.parent,w),m.size>0&&e.heldForExclusions.set(d,m);let S=o.length-O.length;return S>0&&(o.length=0,o.push(...O)),S}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"&&!un(t,c)?yg(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=Rg(e),n=!1;for(let[o,s]of[...e.preread]){if(!Je.has(o))continue;let i=[],a=[];for(let d of s.records){let c=d.Id,u=typeof c=="string"?Og(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=Rg(e),i=e.heldForExclusions.get(t)??new Map,a=[];for(let d of o){let c=Og(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 h of c){let g=f[h.name];typeof g!="string"||g===""||e.namedByRowsHeldBack.has(g)||e.namedByRowsHeldBack.set(g,{field:h.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`+_s(Ds(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:Qr(t,d)})}noteStatusRowsHeld(e,t,n,o){let s=kg(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,my(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===lt))return t;let n=e.readsEverythingFirst?new Set((e.preread.get(lt)?.records??[]).map(s=>String(s.Id))):void 0,o=[];for(let s of t)Ao(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===Ee);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===Ee),o=e.config.stream?.resumeAfter,s=o?.has(Ee)===!0||o?.has(Jo(Ee,tg))===!0;if(!(n!==void 0&&e.emailsFirstPassRan&&(t>0||s)&&!e.failedObjects.has(Ee)&&e.graph.nodes.some(u=>u.included&&u.objectApiName===lt))||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:tg,where:"ActivityId != null",keep:u=>Ao(u),expected:t,stopped:`Stopped ${Ee} after their task`,end:{say:this.endOfTheEmails(e,!0),label:a?"after their task":`${d} ${Ee} 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&&(Cd(e,Ee,t),e.onProgress(ky(o,t,n,wg(e,Ee))))}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(Ee)?.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 Mi(c=>this.deps.queryRecords(e.targetOrgId,c),o)}catch(c){return e.errors.push({objectApiName:lt,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(tasks the platform wrote with the emails)",messages:[`Not looked up, so written as read: ${Q(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,lt),fr(e,u),!1)}),d=t.length-a.length;return d>0&&(e.linkedCount+=d),Hn(e,lt,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),Hn(e,lt,o),{rows:n,linked:o}}async linkTasksOfTheEmailsWritten(e){let t=new Map;for(let i of e.preread.get(Ee)?.records??[]){let a=i.ActivityId,d=i.Id;if(typeof a!="string"||a===""||typeof d!="string"||Ao(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 Mi(i=>this.deps.queryRecords(e.targetOrgId,i),n)}catch(i){if(e.emailTasksNotLookedUp)return;e.emailTasksNotLookedUp=!0,e.errors.push({objectApiName:lt,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(tasks the platform wrote with the emails)",messages:[`Not looked up, so written as read: ${Q(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,lt),fr(e,d))}}async teamOfTheOpportunities(e,t,n,o,s){let i={notKept:new Map,unread:new Map};if(!$o(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=Li[t],l=a.decisions.defaultOf(t,u),f=c?await this.writesAs(e):void 0,p=await Ui(t,n,{source:w=>this.deps.queryRecords(e.sourceOrgId,w),target:w=>this.deps.queryRecords(e.targetOrgId,w),targetIdOf:w=>d.get(w),mappedUser:w=>a.ownerMappings[w],...l!==void 0?{defaultUser:l}:{},written:s,...c?{simulated:{ownerOf:w=>a.ownerMappings[w]??(f??=c.idFor(Lg)),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:w,parentObject:O}]of p.held)O==="User"&&e.gaps?.add({kind:"required_field_missing",severity:"blocking",objectApiName:t,field:w,rows:1,detail:{type:"reference"},decisions:[...rl.required_field_missing??[]]});let h=0,g=0;for(let[w,{id:O,owners:S,notKept:R,unread:b=[]}]of p.linked){let T=String(w.Id);d.addExisting(T,O,t),d.isCreated(String(w.OpportunityId))&&(fr(e,T),g++),S&&h++;for(let k of R)i.notKept.set(k,(i.notKept.get(k)??0)+1);for(let k of b)i.unread.set(k,(i.unread.get(k)??0)+1)}let m=p.linked.size;return m>0&&(e.linkedCount+=m),Hn(e,t,g),m>g&&e.existingRecords.push({objectApiName:t,linked:m-g,unidentified:0}),{rows:m>0?n.filter(w=>!p.linked.has(w)):n,lookups:p.lookups,held:p.held,linked:m,owners:h,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=g=>a.wasCreated(g)||c.writtenBefore.has(g),l=[];if(t.forEach(({source:g},m)=>{let w=g[Xa],O=g[Za];if(typeof w!="string"||typeof O!="string"||!u(w)||!u(O))return;let S=a.get(w),R=a.get(O);S&&R&&l.push({index:m,quote:S,product:R})}),l.length===0)return i;let f=g=>s.updatable?s.updatable.has(g):s.fields?.find(m=>m.name===g)?.updateable!==!1,p;if(d)p=this.copiesASimulationFinds(e,t,l,s.keyPrefix);else{let g=S=>s.fields===void 0||s.fields.some(R=>R.name===S&&R.queryable!==!1),m=[...new Set(l.flatMap(({index:S})=>Object.keys(n[S]??{})))].filter(S=>f(S)&&g(S)),w;try{w=await kp(S=>this.deps.queryRecords(e.targetOrgId,S),l,m)}catch(S){return e.errors.push({objectApiName:ir,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. ${Q(S)}`]}]}),i}let O=new Set;for(let S of o){let R=a.get(String(S.Id));R&&O.add(R.slice(0,15))}p=Sp(l,w,O)}if(p.size===0)return i;let h=d?0:await this.giveTheCopiesTheirFields(e,t,n,p,f);for(let[g,m]of p){let w=t[g],O=typeof w.source.Id=="string"?w.source.Id:void 0,S=String(m.Id);O!==void 0&&a.add(O,S,ir),w.nullifiedFks.length>0&&this.oweToTheSecondPass(e,w.nullifiedFks.map(R=>({objectApiName:ir,newId:S,sourceId:O,fieldName:R.field,sourceRefId:R.sourceRefId,...R.insertOnly?{insertOnly:!0}:{}})))}a.persist();for(let g of[...p.keys()].sort((m,w)=>w-m))t.splice(g,1),n.splice(g,1);return{taken:p.size,given:h}}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===Ss&&f&&p&&d.set(f,p)}if(d.size===0)return s;let c=new Map;for(let l of e.preread.get(Rp)?.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[Za]),h=a(f[Xa]),g=p?c.get(p):void 0;!p||!h||!g||d.get(g)!==h||u.has(p)||(u.add(p),s.set(l,{Id:i.idFor(o)}))}return s}async giveTheCopiesTheirFields(e,t,n,o,s,i={objectApiName:ir,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(g=>g.field)),h=Tp(n[l]??{},f,s,p);Object.keys(h).length>0&&a.push({Id:f.Id,...h})}if(a.length===0)return 0;let d=this.deps.updateRecords,c=[],u=0;for(let l=0;l<a.length;l+=Cg){let f=a.slice(l,l+Cg);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((h,g)=>{let m=p[g];m?.success?u++:c.push(`${String(h.Id)}: ${m?.errors.join("; ")??"no answer"}`)})}catch(p){c.push(`${f.length} not updated: ${Q(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:w},O)=>{let S=w.OpportunityId,R=n[O]?.[Le];typeof S!="string"||typeof R!="string"||R===""||Wi(w)&&d.writtenBefore.has(S)&&c.set(S,R)}),e.contactSentWith.size===0&&c.size===0)return s;let u=Nr(t.map(({source:w},O)=>({OpportunityId:w.OpportunityId,[Le]:n[O]?.[Le],IsPrimary:w.IsPrimary})),w=>i.isCreated(w)?e.contactSentWith.get(w):c.get(w));if(u.length===0)return s;let l=w=>o.updatable?o.updatable.has(w):o.fields?.find(O=>O.name===w)?.updateable!==!1,f=a?u.filter(w=>i.isCreated(String(t[w].source.OpportunityId))):[],p=u.filter(w=>!f.includes(w)),h=new Map(f.map(w=>[w,{Id:a?.idFor(o.keyPrefix)??""}]));if(p.length>0){let w=k=>o.fields===void 0||o.fields.some(v=>v.name===k&&v.queryable!==!1),O=a?[]:[...new Set(p.flatMap(k=>Object.keys(n[k]??{})))].filter(k=>l(k)&&w(k)),S=new Map(p.map(k=>[k,{opportunity:String(i.get(String(t[k].source.OpportunityId))),contact:String(n[k]?.[Le])}])),R;try{R=await Di(k=>this.deps.queryRecords(e.targetOrgId,k),[...new Set([...S.values()].map(({opportunity:k})=>k))],O)}catch(k){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. ${Q(k)}`]}]}),R=[]}let{found:b,alike:T}=_i(S,R);for(let[k,v]of b)h.set(k,v);if(T.length>0){for(let k of T)e.contactSentWith.delete(String(t[k].source.OpportunityId));e.errors.push({objectApiName:ze,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(contact roles the platform wrote with their opportunities)",messages:[bu(T.length)]}]})}}if(h.size===0)return s;let g=a?0:await this.giveTheCopiesTheirFields(e,t,n,h,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[w,O]of h){let S=t[w],R=typeof S.source.Id=="string"?S.source.Id:void 0,b=String(O.Id);if(R===void 0)continue;let T=String(S.source.OpportunityId);e.contactSentWith.delete(T),i.addExisting(R,b,ze),i.wasCreated(T)&&(fr(e,R),m++),S.nullifiedFks.length>0&&this.oweToTheSecondPass(e,S.nullifiedFks.map(k=>({objectApiName:ze,newId:b,sourceId:R,fieldName:k.field,sourceRefId:k.sourceRefId,...k.insertOnly?{insertOnly:!0}:{}})))}i.persist();for(let w of[...h.keys()].sort((O,S)=>S-O))t.splice(w,1),n.splice(w,1);return e.linkedCount+=h.size,Hn(e,ze,m),h.size>m&&e.existingRecords.push({objectApiName:ze,linked:h.size-m,unidentified:0}),{linked:h.size,given:g}}async mapContactsOfPersonAccounts(e,t=e.preread.get(Te)?.records??[]){let n=new Map;for(let i of t){let a=i[Cr],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),ae),e.remapper.isCreated(a)&&this.contactWithItsAccount(e,i));return}let s;try{s=await yu(i=>this.deps.queryRecords(e.targetOrgId,i),[...n.keys()])}catch(i){e.errors.push({objectApiName:Te,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: ${Q(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,ae),e.remapper.isCreated(d)&&this.contactWithItsAccount(e,a)}}contactWithItsAccount(e,t){fr(e,t);let n=e.sample;(n?.drawn.has(ae)?this.inThePlan(n,ae,t):e.writtenObjects.has(ae))||(e.linkedCount++,Hn(e,ae,1),n?.drawn.has(ae)&&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,Te).then(t=>t.some(n=>n.name===Cr),()=>{}),e.personAccountsInTarget}personRecordTypesInTarget(e){return e.personRecordTypes??=this.deps.queryRecords(e.targetOrgId,`SELECT Id, IsPersonType FROM RecordType WHERE SobjectType = '${Te}'`).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(sn);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)?Ga((await this.objectInfoOf(e.targetOrgId,Te))?.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[Te]??[]).includes("RecordTypeId")&&e.config.fieldMappings[Te]?.RecordTypeId===void 0;for(let s of await this.takenAsBusinessAccounts(e,t,o)){let i=s[Cr];typeof i=="string"&&i!==""&&e.contactsOnTheirOwn.add(i)}}async writtenWithTheirAccountOnADryRun(e,t,n,o){if($o(t)){let i=new Set((e.preread.get("Opportunity")?.records??[]).filter(a=>!un(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(ae)?.records??[],n)).size;if(t===Te)return await this.noteContactsOfBusinessAccounts(e,n,o),0;if(t!==ae)return 0;let s=n.filter(i=>sn(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:ae,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,ae),n++,Sy(e,u)&&o++;continue}let f=c.AccountId;typeof f=="string"&&e.remapper.get(f)?i++:s++}n>0&&(e.linkedCount+=n),Hn(e,ae,o),n>o&&e.existingRecords.push({objectApiName:ae,linked:n-o,unidentified:0});let a=[...s>0?[{count:s,why:mg.accountNotWritten}]:[],...i>0?[{count:i,why:mg.contactNotFound}]:[]],d=s+i;return d>0&&(e.failedCount+=d,e.errors.push({objectApiName:ae,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=this.filterOf(e,t.objectApiName),s=n&&an({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:Je,...o?{extraWhere:o}:{}});if(s?.kind!=="skip"||s.reason!==ha){let i=s?.kind==="query"?await this.countedInScope(e,t.objectApiName,s.statements):void 0;if(i?.count!==0){this.reportNotInTarget(t,e,i);continue}e.skippedCount++,e.onProgress({objectName:t.objectApiName,status:"skipped",progress:100,message:`Skipped ${t.objectApiName} (not in the target org; the source holds none of its records under what the run read)`});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)`})}}async countedInScope(e,t,n){let o=this.deps.countRecords;if(!o||n.length===0)return;let s=0;for(let i of n){let a=i.indexOf(" FROM "),d=i.slice(a).replace(/ LIMIT \d+$/,"");if(!i.startsWith("SELECT ")||a<0||!d.startsWith(` FROM ${t}`))return;try{s=Math.max(s,await o(e.sourceOrgId,`SELECT COUNT()${d}`))}catch(c){Ve.warn(`[forge] the records of ${t}, which the target does not have, could not be counted under what the run read: ${Q(c)}`);return}}return{count:s,exact:n.length===1}}reportNotInTarget(e,t,n){t.skippedCount++;let o=n?`; the source holds ${n.exact?"":"at least "}${n.count} of them under what the run read`:"";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${o}`]}]}),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||!Je.has(e.objectApiName)?!1:t.kind==="skip"||!lf(t)}async readCatalogAgain(e,t){let n=e.scopeCache;if(!n)return;let{config:o}=e,s=rf.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})=>og(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 Re("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===zt&&e.standardPricebookId?m.filter(w=>w.Id!==e.standardPricebookId):wt(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===Ht){if(!a.has(rs)&&!a.has(xr))continue;let m=an({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:Je});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 h=_t(l,o.fieldExclusions[u]),g=new Set;for(let m=0;m<qw;m++){if(this.isAborted)throw new Re("Forge execution was aborted by user request. Remaining objects were not processed.");let w=[...og(n,u)].filter(S=>!g.has(S));if(w.length===0)break;for(let S of w)g.add(S);if((await this.readMore(e,d,l,new vn().buildById({objectApiName:u,selectFields:h.length>0?h:["Id"],ids:new Set(w),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 Re("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(O=>!c?.has(O)&&!u?.has(O))),f=new Set(e.graph.edges.filter(O=>O.targetObject===d&&i.has(O.sourceObject)).map(O=>O.sourceObject));if(l.size===0&&f.size===0)continue;let p=await this.fieldsReadAgain(e,a);if(!p)continue;let{fields:h}=p,g=s.objectSoqlFilters?.[d],m=[];if(l.size>0){let O=_t(h,s.fieldExclusions[d]);m.push(...new vn().buildById({objectApiName:d,selectFields:O.length>0?O:["Id"],ids:l,extraWhere:g}))}if(f.size>0){let O=an({node:a,edges:e.graph.edges,fieldInfos:h,scopedBuilder:e.scopedBuilder,scopeCache:o,rootObjectApiName:s.rootObjectApiName,rootRecordId:s.rootRecordId,rootRecordIds:e.roots?.ids,extraWhere:g,fieldsLeftOut:s.fieldExclusions[d],readObjects:e.readObjects,catalog:Je,under:f});O.kind==="query"&&m.push(...O.statements)}m.length===0||(await this.readMore(e,a,h,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=>!kn(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)??[]:[]),h=m=>typeof m.Id!="string"||!p.has(m.Id);this.holdTheRootsReading(e,c,o.length);let g;try{let m=await Gr(l>0?ma(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));Jr(e,m);let w=m.filter(h);this.keepWhatStatusesNeed(e,t,w,void 0);let O=e.heldForExclusions.get(c),S=0;for(let B of O?w:[]){let I=B.Id;typeof I!="string"||O?.get(I)?.namedBy===void 0||(O.delete(I),S++)}S>0&&(O?.size===0&&e.heldForExclusions.delete(c),e.failedCount-=S,e.readByObject.set(c,(e.readByObject.get(c)??S)-S));let R=new Set(e.heldForExclusions.get(c)?.keys()??[]);this.holdBackWhatExclusionsCost(e,t,n,w,void 0,await this.excludedByKeyPrefix(e,c,n));let b=[...e.heldForExclusions.get(c)??[]].filter(([B])=>!R.has(B));if(this.leaveToThePlatform(e,c,w,n),g=(await i(w)).filter(h),as(a,c,g,n,{settle:!1,keyPrefixes:await this.keyPrefixesNamedBy(e,n)}),a.addReadAgain(c,g.flatMap(B=>typeof B.Id=="string"?[B.Id]:[])),await this.notePastDraft(e,c,g),g.length===0&&b.length===0)return[];if(d.files&&d.stream?.everything!==!0){let B=g.flatMap(I=>typeof I.Id=="string"?[I.Id]:[]);e.fileScope.set(c,[...e.fileScope.get(c)??[],...B])}f||e.skippedCount--;let T=e.preread.get(c),k=T?.records??[],v=wt(c)?await this.keptPrices(e,[...k,...g]):[...k,...g],$=v.length-k.length,E=T?.createableSet??new Set(n.filter(B=>B.createable).map(B=>B.name));if(e.preread.set(c,T?{...T,records:v}:{fieldInfos:n,createableSet:E,records:v,targetSetsPending:null}),e.readByObject.set(c,(e.readByObject.get(c)??0)+$+b.length),this.holdTheRootsRows(e,c),d.dryRun){let B=await this.writtenWithTheirAccountOnADryRun(e,c,wt(c)?[]:g,E);e.onProgress({objectName:c,status:"running",progress:0,message:`[dry-run] ${c}: ${$-B} more record(s) would be inserted`+(B>0?`, ${B} more would be written by the platform with ${Dn(c)}`:"")+`, ${s}`+_s(Ds(b.map(([,I])=>I)),!0)})}}catch(m){if(m instanceof Re||Ba(m))throw m;return e.errors.push({objectApiName:c,stage:"query",failedCount:0,attemptedCount:0,samples:[{recordSummary:`(more rows, ${s})`,messages:[Q(m)]}]}),[]}return await this.readWhatTheyCannotBeWrittenWithout(e,c,n,g),g}async keptPrices(e,t){let n=await this.pricesKeyOf(e),{kept:o,standsFor:s}=$i(t,n);if(this.pricesStandFor(e,s),n.oneCurrency)for(let i of o){let a=i.Id,d=i[yt];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,tt).catch(()=>[]),[o,s]=await Promise.all([n(e.sourceOrgId),n(e.targetOrgId)]),i=a=>a.some(d=>d.name===yt);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 Ve.warn(`[forge] the target's one currency could not be read: ${Q(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[yt],d=o[yt];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=>Ld(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[rn]===s)continue;let f=u[Mn];typeof f=="string"&&f&&(a.add(f),d.add(i(u)))}if(a.size!==0)try{let u=new vn().buildJoining({objectApiName:e.objectApiName,selectFields:_t(o,t.config.fieldExclusions[e.objectApiName]),split:{field:Mn,ids:a},whole:{field:rn,ids:new Set([s])}}),l=0;for(let f of u)for(let p of await this.deps.queryRecords(t.sourceOrgId,f)){let h=p.Id;typeof h=="string"&&c.has(h)||d.has(i(p))&&(n.push(p),Jr(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:[Q(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=Ka(a).filter(g=>!d||d.has(Ha(g))),u=[],l=[...new Set(c.map(({currency:g})=>g))].filter(g=>/^[A-Z]{3}$/.test(g));if(l.length>0)try{let g=new vn().buildJoining({objectApiName:e.objectApiName,selectFields:_t(o,t.config.fieldExclusions[e.objectApiName]),split:{field:Mn,ids:new Set(c.map(({product:m})=>m).filter(m=>m!==""))},whole:{field:rn,ids:new Set(c.map(({book:m})=>m).filter(m=>m!==""))},extraWhere:`${yt} IN (${l.map(m=>`'${m}'`).join(", ")})`});for(let m of g)u.push(...await this.deps.queryRecords(t.sourceOrgId,m))}catch(g){t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:0,attemptedCount:0,samples:[{recordSummary:"(prices in the currency written)",messages:[Q(g)]}]});return}let f=t.sample;if(f?.drawn.has(e.objectApiName)){let g=u.filter(m=>this.inThePlan(f,e.objectApiName,String(m.Id)));u.length=0,u.push(...g)}let p=Va(a,d?u.filter(g=>d.has(za(yp(g,t.sellingModels),String(g[yt])))):u),h=new Set(n);n.length=0,n.push(...p.rows),Jr(t,p.rows.filter(g=>!h.has(g)));for(let[g,m]of p.standsFor)t.remapper.alias(g,m),t.prices.standsFor.set(g,m);for(let[g,m]of t.prices.standsFor){let w=p.standsFor.get(m);w!==void 0&&(t.remapper.alias(g,w),t.prices.standsFor.set(g,w))}for(let[g,m]of p.convertedInto)t.prices.convertedInto.set(g,m);for(let[g,m]of p.written)t.prices.written.set(g,m);for(let[g,m]of p.keys)t.prices.keys.set(g,m);t.pricesSwappedSaid.push(...p.said),!(p.said.length===0||s)&&t.onProgress({objectName:e.objectApiName,status:"scanning",progress:50,message:Ja(p.said).join("; ")})}async priceCurrencyInput(e,t,n){let{standardPricebookId:o}=e;if(!o||!n.some(d=>d.name===yt)||!t.some(d=>typeof d[yt]=="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={[yt]:n};e.config.decisions.applyToRow(tt,o,void 0,new ua);let s=o[yt];return typeof s=="string"&&t.active.has(s)?s:Ku(void 0,t)?.to}}async pricesTheGateCounts(e){let t=e.preread.get(tt);if(!t||!e.readsEverythingFirst)return 0;let n=await this.priceCurrencyInput(e,t.records,t.fieldInfos);if(!n)return 0;let o=Ka({...n,wanted:this.currenciesTheirLinesMayWant(e,t.records,n.active)});return e.pricesTheGateCounted=new Set(o.map(Ha)),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(!Mo(d))return!1;let c=e.preread.get(d)?.fieldInfos.find(u=>u.name===Vu[d])?.referenceTo?.[0];return c===void 0||i(c)},a=new Map;for(let[d,{record:c,field:u}]of Object.entries(Os)){let l=i(c);for(let f of e.preread.get(d)?.records??[]){let p=f[Hr];if(typeof p!="string"||typeof f[u]!="string")continue;let h=e.prices.standsFor.get(p)??p;if(!o.has(h))continue;let g=f[He],m=!l&&typeof g=="string"&&n.has(g)?[g]:[...n],w=a.get(h)??new Set;for(let O of m)w.add(O);a.set(h,w)}}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(Os))for(let a of e.preread.get(s)?.records??[]){let d=a[Hr];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=Os[t]?.field;return o===void 0||e.prices.written.size===0?n:n.map(s=>{let i=s[Hr];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(za(d,c));return u===void 0||u===a||u===i||e.remapper.get(u)===void 0?s:{...s,[Hr]: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=>!un(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?pg(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(!(!$o(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(Te),n(ae));i.size>0&&o.set(ae,i);let a=await this.rolesThePlatformWritesOfTheRead(e,n(We),n(ae),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??cn(this.deps.describeFields,e.targetOrgId,i).then(b=>({ok:!0,sets:b}),b=>({ok:!1,error:b})));if(!c.ok){o.push(s);continue}let u=lr(d.createableSet,c.sets.creatable),l=new Set(n.fieldExclusions[i]??[]),f=n.fieldMappings[i]??{},p=new Set(Object.values(f)),h=new Set(await e.maskedSourceFields(i).catch(()=>[])),g=n.anonymization,m=new Set(e.anonymize&&g?g.fields[i]??this.detectedPersonalFields(e,g,i,d.fieldInfos):[]),w=new Set(e.contactPoints?qa(d.fieldInfos).map(({name:b})=>b):[]),O=n.decisions.truncatedFieldsOf(i),S=c.sets.fields.filter(({name:b,unique:T,externalId:k})=>T===!0&&u.has(b)&&!(n.upsertMode==="auto"&&k===!0)&&!l.has(b)&&f[b]===void 0&&!p.has(b)&&!h.has(b)&&!m.has(b)&&!w.has(b)&&!O.has(b)&&!(i===Te&&b.endsWith("__pc"))),R=new Map;for(let b of S){let{name:T}=b,k=new Map;for(let E of a){let B=E[T];if(typeof B!="string"||B===""||Gd.test(B))continue;let I=$n(b,B);k.has(I)||k.set(I,B)}let v=[...k.values()];if(v.length===0)continue;let $=new Set;try{let E=Be(i),B=Be(T);for(let I of jn(v,Fg)){let G=await this.deps.queryRecords(e.targetOrgId,`SELECT ${B} FROM ${E} WHERE ${B} IN (${I})`);for(let re of G){let z=re[T];typeof z=="string"&&$.add($n(b,z))}}}catch{continue}for(let E of a){let B=E[T];typeof B=="string"&&$.has($n(b,B))&&!R.has(E)&&R.set(E,T)}}if(R.size===0){o.push(s);continue}o.push({...s,rows:a.filter(b=>!R.has(b)),leftOut:{...s.leftOut,linkedByValue:{rows:R.size,fields:[...new Set(R.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===""||Wi(u)&&n.writtenBefore.has(l)&&i.set(s(l),f)}if(i.size===0)return o;let a=Nr(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 Di(f=>this.deps.queryRecords(e.targetOrgId,f),[...new Set([...c.values()].map(({opportunity:f})=>f))]),{found:l}=_i(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,ae].some(u=>o.has(u)))return;let d=u=>t.findIndex(l=>l.objectApiName===u),c=i.has(ae)&&d(ae)<d(We);try{if(!(await this.deps.describeFields(e.sourceOrgId,We)).some(b=>b.name===Le&&b.createable)||!(await cn(this.deps.describeFields,e.targetOrgId,We)).creatable.has(Le))return 0;let f=b=>s.objectSoqlFilters?.[b],p=s.stream?.resumeAfter.get(ze),h=f(We),g=f(ae),m=[...f(ze)?[`(${f(ze)})`]:[],`Opportunity.${Le} != null`,...p&&Mt.test(p.lastId)?[`Id > '${p.lastId}'`]:[],...h?[`OpportunityId IN (SELECT Id FROM ${We} WHERE (${h}))`]:[],...c&&g?[`${Le} IN (SELECT Id FROM ${ae} WHERE (${g}))`]:[]],w=await this.deps.queryRecords(e.sourceOrgId,`SELECT Id, OpportunityId, ${Le}, IsPrimary, Opportunity.${Le} FROM ${ze} WHERE ${m.join(" AND ")} ORDER BY Id LIMIT ${Xh+1}`);if(w.length>Xh)return;let O=b=>c||s.writtenBefore.has(b)||e.remapper.get(b)!==void 0,S=b=>{let T=b.Opportunity,k=T!==null&&typeof T=="object"?T[Le]:void 0;return typeof k=="string"&&k!==""?k:void 0},R=new Map;for(let b of w){let T=b.OpportunityId,k=S(b);typeof T!="string"||k===void 0||s.writtenBefore.has(T)||!O(k)||R.set(T.slice(0,15),k)}return Nr(w,b=>R.get(b.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??cn(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,h=f[Le];typeof p!="string"||typeof h!="string"||h===""||un(s,f)||!u.has(c(h))&&i.get(h)===void 0||l.set(c(p),h)}return l.size===0?new Set:new Set(Nr(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,Li[t]),a=await this.writesAs(e);try{let d=await Ui(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??`${Lg}gate`,idFor:()=>""}});return new Set(d.linked.keys())}catch{return new Set}}async personContactsThePlatformWrites(e,t,n){let o=n.filter(d=>sn(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(Te)?.createableSet??new Set).has("RecordTypeId")&&!(e.config.fieldExclusions[Te]??[]).includes("RecordTypeId")&&e.config.fieldMappings[Te]?.RecordTypeId===void 0,a=new Set([...await this.takenAsBusinessAccounts(e,t,i)].map(d=>String(d[Cr])));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??cn(this.deps.describeFields,e.targetOrgId,t).then(u=>({ok:!0,sets:u}),u=>({ok:!1,error:u}))),c=d.ok?lr(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[...el(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!==Ss);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}.${Ss})`,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 Ng(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:i,recordId:a}of n.leftEmptyByFilter??[])this.noteLeftEmptyByFilter(e,t,i,a);for(let i of n.withTheirRecord??[])fr(e,i);let o=Math.min(n.linkedExistingCount,n.writtenByThePlatformCount??0);Hn(e,t,o);let s=n.linkedExistingCount-o;(s>0||n.unidentifiedExistingCount>0)&&e.existingRecords.push({objectApiName:t,linked:s,...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,ya(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<Mw&&i.ids.push(o),s.set(n,i)}sayRecordTypeNote(e,t,n){e.errors.push({objectApiName:t,stage:"scope",failedCount:0,attemptedCount:0,samples:[_l(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)&&bd(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 h of u){let g=l[h.name];if(typeof g!="string"||!g||i.writtenBefore.has(g)&&!e.store?.owesUntold(f))continue;let[m]=this.withoutSyncedQuotes(e,[{objectApiName:t.objectApiName,newId:p,sourceId:f,fieldName:c[h.name]??h.name,sourceRefId:g}]);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 Ip({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:Ng(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??Bw,i=e.pendingFkUpdates.splice(0,e.pendingFkUpdates.length),a=l=>t.wasPatched(l.newId,l.fieldName),d=new Ep;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:h})=>!a(p)&&(!h||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||Ey.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,h=d?Wg(e.config,d):[],g=new Set,m=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[w,O]of n.cleaned.entries()){let S=n.records[w]??{},R=d?il(l,S,O.source,d):[];if(R.length>0){s.failureCount++,s.errorSamples.length<3&&s.errorSamples.push({recordSummary:Of(S),messages:[`REQUIRED_FIELD_MISSING: Required fields are missing: [${R.map(E=>E.name).join(", ")}]`]});continue}let b=u.idFor(o),T=typeof O.source.Id=="string"?O.source.Id:void 0,k=c.get(S);if(k!==void 0){s.linkedExistingCount++,p++,f.add(k),T!==void 0&&e.remapper.addExisting(T,b,l);continue}let v=h.flatMap(E=>{let B=Ly(S,E.name);return B===void 0?[]:[{field:E.name,key:$n(E,B)}]}),$=v.map(({field:E,key:B})=>({field:E,id:u.holderOf(l,E,B)})).find(E=>E.id!==void 0);if($?.id!==void 0){s.linkedExistingCount++,s.linkedToCreatedCount=(s.linkedToCreatedCount??0)+1,m++,g.add($.field),T!==void 0&&e.remapper.addExisting(T,$.id,l);continue}s.successCount++;for(let{field:E,key:B}of v)u.hold(l,E,B,b);a&&!wf(n.records[w]??{})&&a(O),T!==void 0&&e.remapper.add(T,b,l);for(let E of O.nullifiedFks)s.pendingFkUpdates.push({objectApiName:l,newId:b,sourceId:T,fieldName:E.field,sourceRefId:E.sourceRefId,...E.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`}),m>0&&i({objectName:l,status:"running",progress:0,message:`[dry-run] ${l}: ${m} fewer would be inserted, linked to the record${m===1?"":"s"} the run creates under the same ${[...g].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 h=d.get(p)??p;return a.has(h)?void 0:l[h]},Pg(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=sl(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(Xi("record_type_unmapped",s,l,u,Kg(n.targetObject)))}}let a=n.targetFields;return a?(al({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&&!Mo(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??=Hu(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(dl(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;for(let i of Wg(e.config,n)){let a=new Map;for(let l of o){let f=l[i.name];if(typeof f!="string"||f===""||Gd.test(f))continue;let p=$n(i,f),h=a.get(p);h?h.rows++:a.set(p,{value:f,rows:1})}if(a.size===0)continue;let d=new Set;try{let l=Be(t),f=Be(i.name),p=[...a.values()].map(({value:h})=>h);for(let h of jn(p,Fg)){let g=await this.deps.queryRecords(e.targetOrgId,`SELECT ${f} FROM ${l} WHERE ${f} IN (${h})`);for(let m of g){let w=m[i.name];typeof w=="string"&&d.add($n(i,w))}}}catch{continue}let c=0,u=0;for(let[l,{rows:f}]of a)d.has(l)&&(c+=f,u++);c>0&&e.gaps?.add(cl(t,i.name,c,u));for(let l of o){let f=l[i.name];typeof f=="string"&&d.has($n(i,f))&&!s.has(l)&&s.set(l,i.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===Ee?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:h,createableSet:g,targetSetsPending:m}=p;if(wt(e.objectApiName)&&t.readsEverythingFirst&&n===void 0&&!o){await this.pricesInTheCurrencyWritten(e,t,p.records,h,this.currenciesTheirLinesWant(t,p.records));let $=await this.keptPrices(t,p.records);$.length!==p.records.length&&(p.records.length=0,p.records.push(...$))}let w=n??p.records,O=w.filter($=>un(s,$)),S=e.objectApiName===ae?w.filter($=>sn($)&&!un(s,$)):[],R=await this.personContactsOnTheirOwn(t,S),b=new Set(S.filter($=>!R.rows.has($))),T=O.length>0||b.size>0?w.filter($=>!un(s,$)&&!b.has($)):w,k=T,v=[];try{let $=null,E,B=null,I,G,re=await(m??cn(this.deps.describeFields,a,e.objectApiName).then(j=>({ok:!0,sets:j}),j=>({ok:!1,error:j})));if(re.ok)$=re.sets.creatable,E=re.sets.updateable,B=re.sets.picklistValuesByField,I=re.sets.picklistFields,G=re.sets.fields;else{let j=re.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:[j instanceof Error?j.message:String(j)]}]})}let z=$?lr(g,$):g,_=this.linkPersonContacts(t,[...b]);if(o&&(o.withTheirAccount+=_.linked,Rd(o,_.notSent),_.linked===0&&(o.personContactsUnlinked+=b.size)),b.size>0&&_.linked===0&&T.length===0&&O.length===0){if(o)return;t.failedObjects.add(e.objectApiName),c({objectName:e.objectApiName,status:"error",progress:100,message:`${Pn(e.objectApiName,b.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(O.length>0&&(t.linkedCount+=O.length,o&&(o.writtenBefore+=O.length),this.oweLookupsOfRowsWrittenBefore(t,e,O,h,E),await this.oweStatusesFoundAfterStop(t,e.objectApiName,O),T.length===0&&b.size===0)){o||c({objectName:e.objectApiName,status:"done",progress:100,message:`${l}: 0 succeeded, ${Ud(s,O.length)}, 0 failed`});return}let ee=await this.targetObjectInfoOf(t,e.objectApiName),ve=$y(ee);t.gaps?.knowRecordTypes(e.objectApiName,"target",ee?.recordTypes??[]);let he=await this.recordTypesHeldBack(e,T,ee,z,t),de=he.length>0&&s.stream?.everything===!0?this.rowsOfClosedTypes(t,e,T,he):void 0,K=de!==void 0&&de.size>0&&(o!==void 0||de.size<T.length);if(K){k=T.filter(L=>!de.has(L)),t.failedCount+=de.size;for(let L of de.keys())t.heldInTheOrg.set(String(L.Id),"held");let j=[...de.values()];if(v.push(...j),o?(o.withoutParent+=j.length,Yr(j,o.withoutParentGroups),Rd(o,fg(j))):t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:j.length,attemptedCount:0,samples:_d(Yr(j),t.failedObjects)}),o&&k.length===0)return}else if(o?.heldWhole!==void 0&&he.length===0){t.failedCount+=T.length,o.heldWholeRows+=T.length;return}if(he.length>0&&!K){for(let L of he)t.gaps?.add(hg(L,ee));if(t.failedObjects.add(e.objectApiName),t.failedCount+=T.length,t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:T.length,attemptedCount:0,samples:he.map(L=>({recordSummary:`RecordType=${L.developerName} (${L.recordCount} record${L.recordCount===1?"":"s"})`,messages:[Go(L)]}))}),o){o.heldWhole??=he.map(Uo).join(" "),o.heldWholeRows+=T.length;return}let j=Qt(t,e.objectApiName);c({objectName:e.objectApiName,status:"error",progress:100,message:`${Pn(e.objectApiName,T.length,j)}: `+he.map(Uo).join(" ")+" Objects that cannot be written without it will be skipped."});return}k=this.holdBackSkippedRows(t,e,k,c,ve),k=this.leaveWhatHangsFromThePlatform(t,e,h,k);let ne=0;if(e.objectApiName===Ee&&n===void 0){let j=this.holdEmailsForTheirTask(t,k);if(ne=k.length-j.length,k=j,ne>0&&k.length===0){let L={objectName:e.objectApiName,status:"running",progress:0,message:`${e.objectApiName}: ${Cs(ne)}`};c(L),o||(t.emailsAllWaiting={...L,status:"done",progress:100});return}}let fe=0;if(e.objectApiName===lt){let j=await this.linkTasksWrittenWithEmails(t,k);k=j.rows,fe=j.linked,o&&(o.withTheirEmail+=j.linked)}let Ae=new Set(s.fieldExclusions[e.objectApiName]??[]),me=s.fieldMappings[e.objectApiName]??{},ce=await this.teamOfTheOpportunities(t,e.objectApiName,k,ee?.keyPrefix,h.flatMap(j=>!j.isReference&&z.has(j.name)&&!Ae.has(j.name)&&me[j.name]===void 0?[j.name]:[]));k=ce.rows,o&&(o.teamOwners+=ce.owners,o.teamOthers+=ce.linked-ce.owners,gy(o.teamValues,ce.values));let W=await this.rowsWithoutTheirParent(e,t,h,k);for(let[j,L]of await this.rowsWhoseParentTheTargetLacks(e,t,h,k,le=>z.has(le)&&!Ae.has(le)&&me[le]===void 0))W.has(j)||W.set(j,L);let J=await this.rowsHeldInTheWholeOrg(e,t,h,k,j=>z.has(j)&&!Ae.has(j)&&me[j]===void 0);for(let[j,L]of J.held)W.has(j)||W.set(j,L);if(J.aside.size>0){for(let pe of W.keys())J.aside.delete(pe);oy(t,e.objectApiName,J.aside.values()),k.forEach((pe,Se)=>{let ut=J.aside.get(Se);ut&&t.heldInTheOrg.set(String(pe.Id),ut)});let j=k.filter((pe,Se)=>!J.aside.has(Se)),L=new Map;k.forEach((pe,Se)=>{J.aside.has(Se)||L.set(Se,L.size)});let le=new Map;for(let[pe,Se]of W){let ut=L.get(pe);ut!==void 0&&le.set(ut,Se)}W.clear();for(let[pe,Se]of le)W.set(pe,Se);k=j}if(k.forEach((j,L)=>{let le=ce.held.get(j);le&&!W.has(L)&&W.set(L,{field:le.field,parentObject:le.parentObject,reason:le.why})}),W.size>0&&(s.stream?.everything===!0&&k.forEach((j,L)=>{W.has(L)&&t.heldInTheOrg.set(String(j.Id),"held")}),k=k.filter((j,L)=>!W.has(L)),t.failedCount+=W.size,o?(o.withoutParent+=W.size,Yr(W.values(),o.withoutParentGroups),Rd(o,[{count:W.size,why:qd}])):t.errors.push({objectApiName:e.objectApiName,stage:"scope",failedCount:W.size,attemptedCount:0,samples:Qw(W,t.failedObjects)}),k.length===0&&ce.linked===0)){if(o)return;t.failedObjects.add(e.objectApiName);let j=ne===0?Qt(t,e.objectApiName):[];c({objectName:e.objectApiName,status:"error",progress:100,message:`${Pn(e.objectApiName,W.size,j)}: 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:h,records:k,sourceOrgId:i,targetOrgId:a,remapper:d,scopeCache:t.scopeCache,recordTypeMappings:s.recordTypeMappings,recordTypeMapper:t.recordTypeMapper,enabled:s.expandOrphanParents,maxExpansions:s.maxOrphanParentExpansions,anonymize:t.anonymize?(j,L,le,pe)=>this.anonymizeRows(t,j,[L],[le],pe,{})[0]:void 0,contactPoints:t.contactPoints??void 0,withoutFileContent:(j,L)=>this.withoutFileContent(t,j,L,!0),startAsDraft:async(j,L)=>(await this.startAsDrafts(t,j,[L])).get(0),oweStatus:(j,L,le)=>this.oweStatus(t,j,L,le),objectOf:(j,L)=>this.objectOfSourceId(t,j,L),leftToThePlatform:t.leftToThePlatform,recordTypePicklists:t.recordTypePicklists,onRecordTypeNote:(j,L)=>this.sayRecordTypeNote(t,j,L),picklistChanges:t.picklistChanges,currencies:()=>this.runCurrencies(t),currencyChanges:t.currencyChanges,currencyChangesById:t.currencyChangesById,onWrittenWithoutFields:(j,L)=>this.countWrittenWithoutFields(t,j,L),linkPersonContacts:j=>this.mapContactsOfPersonAccounts(t,j),personAccountsInTarget:()=>this.personAccountsInTarget(t),fieldExclusions:s.fieldExclusions,fieldMappings:s.fieldMappings,maskedFieldsOf:j=>t.maskedSourceFields(j),onMaskedLeftOut:(j,L)=>this.noteEncryptedLeftOut(t,j,L),businessAccountsAmong:(j,L)=>this.takenAsBusinessAccounts(t,j,L),contactOnItsOwn:j=>t.contactsOnTheirOwn.has(j),...t.store?{calls:Ms(t.store)}:{}}),k=this.leaveWhatHangsFromThePlatform(t,e,h,k);let we=s.fieldMappings[e.objectApiName]??{},Y=await this.withMaskedLeftOut(t,e.objectApiName,new Set(s.fieldExclusions[e.objectApiName]??[]),k,j=>z.has(j)||we[j]!==void 0),Ce=I?await t.recordTypePicklists.forRows({objectApiName:e.objectApiName,rows:k,fields:I,written:j=>z.has(j)&&!Y.has(j)&&we[j]===void 0,recordTypeMappings:s.recordTypeMappings,withoutRecordTypes:G!==void 0&&!G.some(j=>j.name==="RecordTypeId")}):void 0;for(let j of Ce?.notes??[])this.sayRecordTypeNote(t,e.objectApiName,j);let Oe=z.has("RecordTypeId")&&!Y.has("RecordTypeId")&&we.RecordTypeId===void 0,Ne=e.objectApiName===Te?await this.takenAsBusinessAccounts(t,k,Oe):void 0,Ke=Mo(e.objectApiName)?void 0:await this.currenciesFor(t,G,k,j=>z.has(j)&&!Y.has(j)&&we[j]===void 0),q=Ke?void 0:await this.parentCurrenciesFor(t,e.objectApiName,G,k);k=this.pricedInTheirRecordsCurrency(t,e.objectApiName,k);let P=wt(e.objectApiName)?j=>t.prices.convertedInto.get(String(j.Id)):void 0,D=s.referenceFallback==="keep"?await this.idsTheTargetLacks(t,h,k,j=>z.has(j)&&!Y.has(j)&&we[j]===void 0):void 0,X=s.referenceFallback==="keep"?await this.inactiveOwnersToLeaveOut(t,k,z.has("OwnerId")&&!Y.has("OwnerId")&&we.OwnerId===void 0):void 0,H=Kh({objectApiName:e.objectApiName,records:k,...P?{pricedIn:P}:{},fieldInfos:h,remapper:d,referenceFallback:s.referenceFallback,failedObjects:t.failedObjects,writtenObjects:t.writtenObjects,neverCopied:j=>Ns(t,j),ownerMappings:s.ownerMappings,...ce.lookups.size>0?{resolvedLookups:ce.lookups}:{},...D&&D.size>0?{targetLacks:D}:{},...X?{inactiveOwners:X}:{},...t.sample?{outsideTheSample:(j,L)=>this.outsideTheSample(t,j.referenceTo??[],L)||t.heldInTheOrg.has(L)}:s.stream?.everything===!0?{heldByTheRun:j=>t.heldInTheOrg.has(j)}:{},excludedFields:Y,fieldRename:we,creatableFields:z,updatableFields:E,picklistValuesByField:B,picklistFields:I,recordTypeValues:Ce?.byRecordType,businessAccounts:Ne,contactPoints:t.contactPoints??void 0,decide:(j,L)=>s.decisions.applyToRow(e.objectApiName,j,Pg(s,L),t.decisionsApplied,ve),...Ke||q?{currencyFields:Co(G??[])}:{},...Ke?{currencies:Ke}:{},...q?{parentCurrencies:q}:{}}),je=new Yo,U=new Bo;for(let{picklistChanges:j=[],currencyChange:L,source:le}of H){je.add(e.objectApiName,j),t.picklistChanges.add(e.objectApiName,j),o?.picklists.add(e.objectApiName,j),U.add(e.objectApiName,L),t.currencyChanges.add(e.objectApiName,L),o?.currencies.add(e.objectApiName,L);let pe=le.Id;L&&typeof pe=="string"&&t.currencyChangesById.set(pe,L)}let oe=Xo(je.list())+Lo(U.list())+vd(Sg(new Map,H))+Fd(Ag(H))+Ed(Id(new Map,H))+xd(Pd(new Map,H))+(o?"":Bd(t,e.objectApiName));o&&(Sg(o.lookupsNotCarried,H),Id(o.lookupsOutsideTheRun,H),Pd(o.lookupsHeldBack,H),o.ownersInactive+=Ag(H)),this.noteLookupsOutsideTheRun(t,e.objectApiName,h,H),await this.noteLookupsHeldBack(t,e.objectApiName,h,H);for(let j of H)for(let L of j.lookupsOutsideTheSample??[])this.noteLeftOutsideTheSample(t,e.objectApiName,L);Ry(t,e.objectApiName,H);let ge=H.map(j=>j.cleaned);t.recordTypeMapper&&s.recordTypeMappings&&(ge=t.recordTypeMapper.apply(ge,s.recordTypeMappings,j=>bs(e.objectApiName,j)));let ue=this.applyRecordTypeDecisions(t,e.objectApiName,H,ge);ge=this.anonymizeRows(t,e.objectApiName,ge,H.map(j=>String(j.source.Id??"")),h,s.fieldMappings[e.objectApiName]??{});let It=new Map((G??[]).flatMap(j=>j.length!==void 0&&j.length>0?[[j.name,j.length]]:[]));if(s.decisions.truncatedFieldsOf(e.objectApiName).size>0)for(let j of ge)s.decisions.truncate(e.objectApiName,j,It,t.decisionsApplied);let pt=new Map;t.gaps&&(pt=await this.findGaps(t,e,{cleanedRecords:H,recordsToInsert:ge,targetFields:G,targetObject:ee,picklistValuesByField:B,picklistFields:I,recordTypes:Ce?.byRecordType,unmapped:ue}));let bt=e.objectApiName===ir?await this.takeTheSyncCopies(t,H,ge,O,{fields:G,updatable:E,keyPrefix:ee?.keyPrefix}):{taken:0,given:0};e.objectApiName===We&&hy(t,H,ge);let at=e.objectApiName===ze?await this.linkTheRolesThePlatformWrote(t,H,ge,{fields:G,updatable:E,keyPrefix:ee?.keyPrefix}):{linked:0,given:0},Qn=await this.startAsDrafts(t,e.objectApiName,ge),Rt=new Map;if(t.store)for(let[j,L]of Qn){let le=H[j];le&&Rt.set(le,L)}let De=[];if(wt(e.objectApiName)&&t.standardPricebookId){let j=H.map((pe,Se)=>Se),{standard:L,custom:le}=Jc(j.map(pe=>({index:pe,[rn]:H[pe].source[rn]})),t.standardPricebookId);for(let pe of[L,le])pe.length!==0&&De.push({records:pe.map(Se=>ge[Se.index]),cleaned:pe.map(Se=>H[Se.index])})}De.length===0&&(ge.length>0||bt.taken===0&&at.linked===0)&&De.push({records:ge,cleaned:H});let Xt=await this.recordTypeCounter(t,e.objectApiName,ee,Oe),ye=bf();ye.successCount+=bt.taken;let Ot;try{for(let j of De){if(t.simulated){this.simulateWrite(t,e,j,ee?.keyPrefix,ye,c,Xt,G,pt);continue}await t.batchWriter.writeNode({node:e,records:j.records,cleanedRecords:j.cleaned,fieldInfos:h,creatableFields:z,upsertMode:s.upsertMode,...o?.tableKeys?{tableKeys:o.tableKeys}:{},targetOrgId:a,targetKeyPrefix:ee?.keyPrefix,picklistFields:I,remapper:d,...t.store?{oweLookups:L=>this.oweToTheSecondPass(t,L)}:{},...t.store?{calls:Ms(t.store)}:{},...Rt.size>0?{onWritten:(L,le)=>{let pe=Rt.get(L);pe!==void 0&&(Rt.delete(L),this.oweStatus(t,e.objectApiName,le,pe))}}:{},...Xt?{onCreatedWithoutRecordType:Xt}:{},...Object.keys(s.ownerMappings).length>0?{ownersMapped:new Set(Object.values(s.ownerMappings).map(L=>L.slice(0,15)))}:{},...t.bulk?{bulk:t.bulk}:{},...t.contactPoints?{contactPoints:{fieldOf:dp(h,we),count:L=>t.contactPoints?.countForms(e.objectApiName,L)}}:{},waitIfPaused:()=>this.waitIfPaused(),stopped:()=>this.isAborted,onProgress:c},ye)}}catch(j){if(!(j instanceof Re))throw j;Ot=j}finally{for(let[j,L]of Qn){let le=H[j];if(le&&t.store&&!Rt.has(le))continue;let pe=le?.source.Id;if(typeof pe!="string")continue;let Se=d.get(pe);!Se||d.isExisting(pe)||this.oweStatus(t,e.objectApiName,Se,L)}this.countWrites(t,e.objectApiName,ye)}let ht=ye.successCount,$t=ye.updatedCount,dt=ye.linkedExistingCount,C=ye.failureCount,Z=ye.unidentifiedExistingCount;if(o){let j=De.reduce((ut,Xn)=>ut+Xn.records.length,0),L=De.flatMap(ut=>ut.cleaned);o.sent+=j,o.succeeded+=ht,o.updated+=$t,o.linked+=dt,o.linkedToCreated+=ye.linkedToCreatedCount??0,o.linkedByThePlatform+=ye.writtenByThePlatformCount??0,o.failed+=C,o.alreadyExists+=ye.alreadyExistsCount,o.unidentified+=Z,o.rolesOfTheirOpportunity+=at.linked,o.rolesGiven+=at.given,o.writtenWithoutFields=ye.writtenWithoutFields?ya(o.writtenWithoutFields,ye.writtenWithoutFields):o.writtenWithoutFields,ye.flagsNotKept&&(o.flagsNotKept=Ru(o.flagsNotKept,ye.flagsNotKept));let le=Ot?j-(ht+$t+dt+C):0,pe=L.slice(0,j-le).filter(ut=>R.rows.has(ut.source)).length;o.sentOnTheirOwn+=pe,pe>0&&(o.onTheirOwnWhy=R.why);let Se=[...Od(o),...Qt(t,e.objectApiName)];if(Ot)throw this.stopStreamedNode(e,t,o,le,f),Ot;c({objectName:e.objectApiName,status:"running",progress:0,message:`${e.objectApiName}, page ${o.pages}: ${$d(s,e.objectApiName,o,Se)}`});return}let se=ht+$t+dt+O.length+_.linked+ce.linked+at.linked,Ie=se+C,V=Ie>0?C/Ie:0,be=C>0&&ye.alreadyExistsCount===C,ct=C>0&&!be&&(se===0||V>.5),_e=Ug(s,dt,ye.linkedToCreatedCount??0,{objectApiName:e.objectApiName,rows:ye.writtenByThePlatformCount??0}),Ye=$t>0?`, ${$t} updated through their external id`:"",Ge=Z>0?` (${Z} already in the target without Salesforce naming the record \u2014 their children lose the link)`:"",kt=j=>[...fg(v),...W.size>0?[{count:W.size,why:qd}]:[],..._.notSent,...j?Qt(t,e.objectApiName):[]],Me=kt(ne===0),St=fe>0?`, ${fe} written by the platform with their email`:"",vt=qg(_.linked,jd(t,e.objectApiName)),Zt=Gg(ce.owners,ce.linked-ce.owners)+zg(at.linked,at.given),Nn=De.flatMap(j=>j.cleaned),Xe=j=>Nn.slice(0,j).filter(L=>R.rows.has(L.source)).length,Bt=j=>j>0?`, ${j} ${j===1?"person account's contact":"person accounts' contacts"} sent on their own: the target wrote none with their account`:"",rt=Bt(Xe(Nn.length)),xt=O.length>0?`, ${Ud(s,O.length)}`:"",mn=ne>0?`, ${Cs(ne)}`:"",en=[Gi(ye.flagsNotKept),Hg(ce.values)].flatMap(j=>j?[`, ${j}`]:[]).join(""),tn=cs(ye.writtenWithoutFields),Pt=Mg(t,e.objectApiName),gt=Ws(t,e.objectApiName),Lt=n===void 0?rg(t,e.objectApiName):"",Yn=s.dryRun?"would be inserted":"succeeded",Wt=bt.taken>0?` (${Ap(bt.taken,bt.given,s.dryRun)})`:"",Ze=j=>`${ht} ${Yn}${Wt}${Ye}${_e}${St}${vt}${Zt}${xt}, ${C+Vn(j)} failed${Ge}${ln(j)}`,wr=`${rt}${mn}${en}${oe}${tn}${Pt}${ne===0?gt:""}${Lt}`;if(Ot){let j=De.reduce((Se,ut)=>Se+ut.records.length,0),L=j-(ht+$t+dt+C)+ne;Cd(t,e.objectApiName,L);let le=ne>0?` (${Cs(ne)})`:"",pe=Xe(j-L+ne);throw this.saySentOnTheirOwn(t,pe,R.why),(n===void 0?t.onProgress:c)({objectName:e.objectApiName,status:ct?"error":"stopped",progress:100,message:`${f}: ${Ze(kt(!0))}, ${L} not sent${le}${Bt(pe)}${en}${oe}${tn}${Pt}${gt}`}),Ot}if(this.saySentOnTheirOwn(t,Xe(Nn.length),R.why),ct){t.failedObjects.add(e.objectApiName),se>0&&t.failedInPart.add(e.objectApiName);let j=Vn(Me);c({objectName:e.objectApiName,status:"error",progress:100,message:se===0?`Failed all ${e.objectApiName} records: ${C+j} failed${ln(Me)}${rt}${oe}${Lt}`:`${C+j}/${Ie+j} ${e.objectApiName} records failed (>50%)${ln(Me)}${rt}${oe}${tn}${Pt}${Lt}${gg}`})}else c({objectName:e.objectApiName,status:"done",progress:100,message:`${l}: ${Ze(Me)}${wr}`})}catch($){if($ instanceof Re)throw $;t.failedObjects.add(e.objectApiName),t.failedCount+=k.length,t.errors.push({objectApiName:e.objectApiName,stage:"query",failedCount:k.length,attemptedCount:k.length,samples:[{recordSummary:"(stage failed before insert)",messages:[Q($)]}]}),c({objectName:e.objectApiName,status:"error",progress:100,message:`Error on ${e.objectApiName}: ${Q($)}`})}}};function Hy(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 Kd(r,e,t,n){let o=t?.recordTypeMappings,s=As(e.anonymizePII,r,t?.anonymizationRules,n,e.anonymizationMode),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=Hy(e,u?.sample),f=c?{...u,everything:!0,writeWindow:Hd,secondPassPageSize:Hd,ceiling:void 0,wholeReadBound:u?.wholeReadBound??u?.ceiling??mo,...l?{sample:l}:{}}:u,p=[...new Set([...r.nodes.filter(Bc).map(R=>R.objectApiName),...e.excludedObjects??[]])],h=p.length>0?p:void 0,g=e.dryRun===!0?!0:void 0,m=Zo(e),w=e.keepContactPoints===!0?!0:void 0,O=Ky(r,e,t?.roots);return O||e.inputMode==="record"&&typeof e.recordId=="string"?{...O?{roots:O}:{rootRecordId:e.recordId},rootObjectApiName:O?.objectApiName??r.nodes[0]?.objectApiName,expandOrphanParents:e.expandOrphanParents,maxRecordsPerObject:e.maxRecordsPerObject,fieldExclusions:e.fieldExclusions,excludedObjects:h,ownerMappings:e.ownerMappings,objectSoqlFilters:e.objectSoqlFilters,fieldMappings:e.fieldMappings,recordTypeMappings:o,anonymization:s,keepContactPoints:w,files:i,writtenBefore:a,beforeWrite:d,stream:f,dryRun:g,decisions:m}:e.maxRecordsPerObject!=null||e.fieldExclusions||h||e.ownerMappings||e.objectSoqlFilters||e.fieldMappings||o||s||w||i||a||d||f||g||m?{maxRecordsPerObject:c?void 0:e.maxRecordsPerObject,...c?{writeApi:"auto"}:{},fieldExclusions:e.fieldExclusions,excludedObjects:h,ownerMappings:e.ownerMappings,objectSoqlFilters:e.objectSoqlFilters,fieldMappings:e.fieldMappings,recordTypeMappings:o,anonymization:s,keepContactPoints:w,files:i,writtenBefore:a,beforeWrite:d,stream:f,dryRun:g,decisions:m}:void 0}function Ky(r,e,t){let n=e.maxRoots??$r,o=r.nodes.find(a=>a.level===0)??r.nodes[0],s={...t?.plan?{plan:t.plan}:{},...t?.plan&&t.planOfTheRunRetried?{planOfTheRunRetried:!0}:{},...!t?.plan&&t?.planPastItsDay?{planPastItsDay:t.planPastItsDay}:{},...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(!_c(e)||e.inputMode!=="soql")return;let i=Hl(e.soqlQuery??"");if("issue"in i)throw Pe.of(ts(i.issue,o?.objectApiName));return{objectApiName:o?.objectApiName??i.objectApiName,query:i.query,cap:n,...s}}var eo="--checkpoint-first",Vd={switches:[eo],values:["--checkpoint-keep-days","--checkpoint-exclude-object"]},Vy=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function Jg(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 Zr(r){process.stderr.write(`${r}
9
+ `),process.exit(2)}function Qg(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(eo)){let a=[...n.length>0?["--checkpoint-keep-days"]:[],...o.length>0?["--checkpoint-exclude-object"]:[]];a.length>0&&Zr(`${a.join(" and ")} ${a.length===1?"goes":"go"} with ${eo}, which takes the checkpoint they set. Run with --help.`);return}for(let{flag:a,why:d}of e)r.includes(a)&&Zr(`${eo} does not go with ${a}: ${d}`);n.length>1&&Zr(`--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{Ta(s,void 0)}catch{Zr(`--checkpoint-keep-days takes a whole number of days from 0 to 3650, not "${a}".`)}}let i=[];for(let a of o)Vy.test(a)||Zr(`--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 Vg(r,e){return r!==void 0&&r.length>=15&&r.slice(0,15)===e.slice(0,15)}function Jy(r){let e=r.self??Sl,t=r.elsewhere??(s=>Tl(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||!(Vg(d.targetOrganizationId,s)||Vg(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 Yg(r,e){return{id:e.id,orgType:Xc({isScratch:r.scratch===!0,isSandbox:e.sandbox,edition:e.edition}),...e.edition!==void 0?{edition:e.edition}:{}}}function Qy(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 Yy(r){let e=-1;return({percentage:t})=>{let n=Math.floor(t/10);n<=e||(e=n,r(` ${Lf(t)}`))}}function Xg(r){let e,t=()=>e??=(async()=>{let{join:o}=await import("node:path"),{takeOrgOf:s}=await import("./chunk-TTU5EQZ6.mjs"),{openCheckpointStore:i}=await import("./chunk-YGTOX7IL.mjs"),{nodeSyncRunCreations:a}=await import("./chunk-OCUVAA5E.mjs"),{nodeSeedRunCreations:d}=await import("./chunk-KH4KLCYG.mjs"),{envLockHolder:c,envLockLine:u}=await import("./chunk-MR262Y3B.mjs"),l=i({root:r.storeRoot??o(r.journalDir,"checkpoints"),...r.locksDir!==void 0?{locksDir:r.locksDir}:{}});if("refusal"in l)throw new Error(Qy(l.refusal));let{store:f}=l,{session:p}=r,h=r.connect(p),g={id:r.org.id,alias:p.alias,username:p.username,instanceUrl:p.instanceUrl,orgType:r.org.orgType,metadata:{apiVersion:h.version,...r.org.edition!==void 0?{edition:r.org.edition}:{}}},m={log:w=>{w.startsWith("[WARN] ")&&r.say(`warning: ${w.slice(7)}`)},orgManager:{getOrg:w=>w===g.id?g:void 0},orgRegistry:{getCredentials:async w=>w===g.id?{accessToken:p.accessToken,instanceUrl:p.instanceUrl}:void 0}};return{deps:{org:s(h),store:f,handler:m,runWriting:Jy({orgName:p.alias,alias:p.alias,runs:[a(r.journalDir),d(r.journalDir)],envLock:w=>{let O=c(f.locksDir,w);return O!==void 0?u(O):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:Ta(r.request.keepDays,void 0)});return{async scope(o){let s=await import("./chunk-OO2WY3UB.mjs"),{deps:i,org:a}=await t();return s.scopeBeforeRun(i,a,n(o))},async take(o,s,i={}){let a=await import("./chunk-OO2WY3UB.mjs"),{deps:d,org:c}=await t();return a.takeBeforeRun({...d,...i.signal?{signal:i.signal}:{},onProgress:Yy(r.say)},c,n(o),s)},async settle(o,s){let i=await import("./chunk-OO2WY3UB.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 Jd(r){return $l(r).map(e=>` ${e}`)}var Xy=new Set(["TOO_MANY_RECORDS","API_BUDGET","DISK"]);function Us(r){let e=r.message.replace(/\s*No record was read\.$/,""),t=Xy.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 ${eo} to write without one.`}function Qd(r){return r.code!==En?zf:r.refusal!==void 0?`${Us(r.refusal)} Nothing was written.`:r.message}function Zy(r){return r===null?"kept until it is deleted":`kept until ${r.slice(0,10)}`}function Zg(r,e,t){return[`checkpoint before the run: ${r.checkpointId} '${r.name}', ${r.objects.length} object(s), ${r.records} record(s), ${Zy(r.expiresAt)}`,` rewind to it: ${Gt("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 Yd(r){return r.state==="deleted"?[Bf]:[]}async function PT(r,e,t,n,o){try{let s=await r.settle(e,t);for(let i of Yd(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 ${Gt("checkpoint")} delete --org ${n} --checkpoint ${e.checkpointId}`),e}}var Gs="--leave-undeletable",Xd="UNDELETABLE_NOT_LEFT";function eb(r,e){let t=r.map(o=>`${o.objectApiName} (${o.records} records)`).join(", "),n=jt(Gs)?`run again with ${Gs}`:`run ${it(Gs,"removal")}`;return{code:Xd,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 em(r,e,t,n=o=>process.stderr.write(`${o}
10
+ `)){return async o=>{if(!r)return t(eb(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 (${Gs}).`),!0}}function tm(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,Wo).then(Do,()=>[]),_o(o.recordTypes,await t))}}var bc=`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
+ --anonymize-everything anonymize, besides the fields the detector names and
354
+ those the org classifies, the names of people and
355
+ companies, every part of an address, the birthdates and
356
+ the long texts, redacted where they stand. ${tu}=
357
+ everything does the same unless --no-anonymize is given
358
+ --keep-contact-points write emails and phone numbers as read (default: off)
359
+ Off, every record is written with its email addresses
360
+ under .invalid and its phone numbers in a fictional
361
+ range, anonymized or not, so what the target's flows
362
+ and email alerts send to them reaches no one. On,
363
+ they may reach the real people the records name.
364
+ --dry-run skip writes, surface scoped queries (default: off)
365
+ It reads the automation and counts the records as a
366
+ real run does, and says what would stop that run,
367
+ each under the code that run is refused with: a real
368
+ run would be refused (CODE): ... With --json, under
369
+ wouldBeRefused, and the codes under wouldBeRefusedCodes.
370
+ --rehearse have the target judge the rows, keep none (default: off)
371
+ Reads and prepares every row as a real run would,
372
+ then creates a sample of them in the target \u2014 every
373
+ row up to 200, one per object, record type and set of
374
+ fields given a value past it, with the records they
375
+ name \u2014 in composite calls that each fail on purpose,
376
+ so that every write is rolled back. Prints each
377
+ refusal (status code, field, rows) and what could not
378
+ be judged (with --json, under rehearsal). The target's
379
+ automation runs inside each call: emails, @future and
380
+ Queueable jobs, platform events published after
381
+ commit and the asynchronous paths of Flows never
382
+ leave it; platform events published immediately and
383
+ callouts do. Refused against a production org, and,
384
+ like a real run, without --accept-automation when the
385
+ target runs automation on insert. Not with --dry-run,
386
+ --upsert, --files, --remap-csv or --list-objects.
387
+ --accept-automation write although the target runs flows or Apex
388
+ triggers as the clone inserts, or as it updates the
389
+ records it inserted, or could not say what it runs
390
+ (default: off)
391
+ --accept-emails write although the target delivers every email of
392
+ what still runs as the clone writes, or would not say
393
+ whether it does; --accept-automation never stands for
394
+ it. Asked only when what still runs sends one: flows,
395
+ processes and workflow rules with an email action,
396
+ those whose definition was not read, and the
397
+ assignment rules --apply-assignment-rules applies,
398
+ whatever --mute-automation leaves. Whether the org
399
+ delivers them is read with one line of anonymous Apex
400
+ that sends nothing,
401
+ Messaging.reserveSingleEmailCapacity(1), as the user
402
+ the run writes as, never in a production org; on
403
+ System email only or No access, none of them goes
404
+ out, the org still counts them against its daily
405
+ limits, and nothing is asked. What an Apex trigger
406
+ sends is read nowhere (default: off)
407
+ --mute-automation mute the target's automation for the run through its
408
+ own bypass: assign the user the run writes as, for the
409
+ run alone, the permission sets holding the custom
410
+ permissions its flows, processes and workflow rules
411
+ test to stay quiet, and take them back as it ends.
412
+ What no bypass keeps quiet (an Apex trigger, a managed
413
+ package's flow) still runs, and still needs
414
+ --accept-automation. Refused on a production org and
415
+ for a user who cannot assign permission sets, exit 1;
416
+ a dry run says what would be muted and assigns nothing
417
+ (default: off)
418
+ ${Jg({run:"the run",simulation:"--dry-run"})}
419
+ --max-total <n> most records the run may write in all (default: 10000)
420
+ Counted once every row is read: past it, nothing is
421
+ written. --max caps each object, this the whole run.
422
+ --max-records-per-object <n>
423
+ most records one read of an object takes
424
+ (default: 50000)
425
+ An object with more is read to it and said
426
+ TRUNCATED. A clone of a record holds what it reads,
427
+ so a higher number takes more memory; 1000000 at most.
428
+ --upsert use external Id upsert when available (default: insert)
429
+ Skips DUPLICATE_VALUE on re-runs of the same source records.
430
+ --expand-orphans single-hop expand orphan parent FKs (default: off)
431
+ Clones missing parents (out-of-graph) so child FKs resolve.
432
+ --max-orphans <n> with --expand-orphans, most parents from outside the
433
+ run it copies, 1 to 1000 (default: 20)
434
+ Past it, the rows that cannot be written without one
435
+ are refused, and the summary says how many parents
436
+ were left and of which objects.
437
+ --apply-assignment-rules
438
+ apply the target's assignment rules (default: off)
439
+ Off, every write says Sforce-Auto-Assign: FALSE and
440
+ keeps the owner the run sets. On, the target's active
441
+ assignment rules may give the Cases, Leads and
442
+ Accounts the run writes another owner, and mail them.
443
+ --skip-preflight skip pre-execute target row count (default: off)
444
+ The preflight queries each object on target so the user
445
+ can see existing volume before pressing through.
446
+ --json emit JSON summary on stdout (CI mode) (default: off)
447
+ stdout then carries the JSON alone, and every other
448
+ line goes to stderr. Saved to a file, the summary is
449
+ what --remove takes the run back from. With
450
+ --list-objects, the JSON is the objects of the graph.
451
+ A run refused before its first write prints
452
+ "refused": {"code", "message"} instead, the code its
453
+ line names: refused (MAX_TOTAL_EXCEEDED): ..., each
454
+ other reason under "alsoRefused", on a line of its own.
455
+ How a run ended is under result.status: success,
456
+ partial or failure, as its status: line says it.
457
+ --fail-on-partial exit 3, not 0, when the run wrote some records and
458
+ the target refused others (default: off)
459
+ --summary <file> write the summary to <file> as the run goes
460
+ The JSON --json prints, written after each object
461
+ with what the run has created so far ("running":
462
+ true), then whole once it ends. Ctrl-C stops the run
463
+ between two calls to the org and writes what it had
464
+ created by then ("interrupted": true), as --json then
465
+ prints it: --remove takes the run back from either.
466
+ A file already there is not overwritten. Not with
467
+ --list-objects or --rehearse.
468
+ --resume <journal|id> take up where it stopped a run that did not end \u2014 a
469
+ Ctrl-C, a failure, a process killed \u2014 from its journal:
470
+ its file, or its run id in the journal directory. Each
471
+ record that run wrote is linked to and never written
472
+ again, the lookups and statuses it still owed are
473
+ given, and the rest is written. The same record, orgs,
474
+ depth, choices and flags as the run it takes up, or it
475
+ is refused; a run that ended is refused too. Every run
476
+ that writes keeps its journal there (see
477
+ SANDFORGE_JOURNAL_DIR), and says where as it starts.
478
+ The calls the run had under way when it stopped are
479
+ looked for in the target first: a row found there is
480
+ kept as written by the run, never sent again; one the
481
+ target may hold already stops the resume before it
482
+ writes (see --write-uncertain).
483
+ Not with --dry-run, --rehearse or --list-objects.
484
+ --write-uncertain with --resume: write all the same the rows of a call
485
+ under way when the run stopped that the target may
486
+ already hold, records the resume cannot tell from
487
+ them being there \u2014 each may then be there twice.
488
+ --exclude <obj.field> skip a field on an object during clone (repeatable)
489
+ e.g. --exclude Account.Description --exclude Account.NumberOfEmployees
490
+ Matched whatever its case. One that names no object
491
+ or field of the source refuses the run before a row
492
+ is read, exit 2, naming the field nearest it
493
+ (FIELD_EXCLUSION_UNMATCHED); a dry run says it, as
494
+ the summary's result.fieldExclusionsUnmatched does.
495
+ --exclude-object <obj> leave an object out of the clone (repeatable)
496
+ e.g. --exclude-object PricebookEntry
497
+ Out whether discovery reaches it or the run would
498
+ add it past the cap. What it costs is said, not
499
+ written: the records that cannot be written without
500
+ one of its records, and the orders left drafts.
501
+ --owner-map <src=tgt> remap OwnerId from source User Id to target User Id (repeatable)
502
+ e.g. --owner-map 005AB...=005XY...
503
+ Useful when source records were authored by users
504
+ that don't exist on the target sandbox (ex-employees).
505
+ A target user the target holds inactive is refused
506
+ before anything is read (OWNER_MAP_INACTIVE), and
507
+ one it holds no user of (OWNER_MAP_UNKNOWN).
508
+ --filter <obj=where> per-object SOQL WHERE filter (repeatable)
509
+ e.g. --filter "Case=Status = 'Open' AND CreatedDate > LAST_N_DAYS:30"
510
+ Lets BAs narrow a clone to a subset without changing
511
+ graph topology. Filter is appended via AND (...) to
512
+ the scope-derived clause. Max 512 chars per filter,
513
+ max 50 filters total.
514
+ --map <obj.src=tgt> per-object source\u2192target field rename (repeatable)
515
+ e.g. --map Account.Region__c=Region__pc
516
+ Handles schema drift between source and target
517
+ (managed-package re-key, namespace change). The
518
+ source field is dropped and the value written to
519
+ the target field name on insert.
520
+ --config <file.json> the run's choices from a JSON file: the decisions
521
+ taken in Review's Gaps row (picklistValueMappings,
522
+ recordTypeMappings, defaultValues, truncateFields,
523
+ skippedRows, ignoredGaps), the fields and objects
524
+ left out (fieldExclusions, excludedObjects), the
525
+ filters (objectSoqlFilters) and the mappings
526
+ (ownerMappings, fieldMappings), as a Forge config
527
+ names them. Checked as the panel checks a run's
528
+ config; any other key is refused. The flags above
529
+ win over the file: their exclusions are added, their
530
+ filters and mappings replace the file's for the same
531
+ object, user or field.
532
+ --template <file.json> a template the Template tab exported: its decisions,
533
+ exclusions, filters and mappings, as --config takes
534
+ them, and its depth, caps, anonymization, contact
535
+ points and orphan parents, each unless its flag is
536
+ given. Its record is cloned when --record is not
537
+ given; a template of a query needs --record, or
538
+ --object. Not with --config.
539
+ --remap-csv <file> write the source\u2192target ID remap table to a CSV
540
+ file (header: sourceId,targetId). BA reconciliation:
541
+ "where did source X go on the target sandbox?"
542
+ --files copy the files of the cloned records (default: off)
543
+ Salesforce Files (the latest version of each) and
544
+ attachments, after the records they hang on. The
545
+ total is checked against the target's file storage
546
+ before anything is written: past it, refused
547
+ (FILE_STORAGE_EXCEEDED), as when that storage could
548
+ not be read (FILE_STORAGE_UNREAD) or the files not
549
+ all looked up (FILES_UNREAD).
550
+ --max-file-size <MB> largest file --files copies, 1 to 35 (default: 10)
551
+ A larger file is left out and listed, never cut.
552
+ --files-as-is accept that files are copied as they are: their
553
+ content cannot be anonymized. Required with --files
554
+ when --anonymize is on.
555
+ --audit <file> record the run in an audit trail kept in <file>
556
+ The entry the panel keeps in Reports -> Audit trail:
557
+ per object the records created, updated and lost,
558
+ the orgs, the outcome, the user as a hash of the
559
+ username, and, for a run refused before it wrote,
560
+ the code of what refused it. Counts only, never a
561
+ value of a record. Each run adds its entry to the
562
+ file; a dry run, --list-objects and --rehearse write
563
+ nothing, and add none.
564
+ -h, --help show this help and exit
565
+
566
+ Remove what a run created:
567
+ --remove <file> the summary a run printed with --json, saved to a file,
568
+ or the journal of a run: every part of it, the run it
569
+ took up and each time it was taken up
570
+ Deletes from --target the records that run created,
571
+ as the wizard removes a run from History: children
572
+ first, never a record the target already held, and a
573
+ record kept while records that stay depend on it. The
574
+ target must be the org the run wrote to. A dry run's
575
+ summary is refused: it created nothing. So is a run
576
+ that still writes its journal, from a terminal or
577
+ from VS Code, and the preview of its removal
578
+ (RUN_WRITING), the run named: stop it, or let it end.
579
+ The removal holds the journal while it deletes: a
580
+ --resume of it meanwhile is refused (RUN_WRITING).
581
+ What a removal wrote to the records it left is kept
582
+ beside the summary, clone-summary.removals.json for
583
+ clone-summary.json, and the next --remove of that
584
+ summary reads it: what a removal wrote is no change
585
+ since the run. Keep that file with the summary.
586
+ A summary of a run past 50 000 records keeps their ids
587
+ in its journal, which the removal reads them from.
588
+ Of a run stopped and taken up with --resume, one
589
+ summary per part, it is kept beside the journal too:
590
+ the removal of any part, or of the journal, reads what
591
+ the others wrote, and once a part's own records are
592
+ gone, takes what an earlier removal of another part
593
+ left. What the run wrote to a record of another part
594
+ is no change since the run. The journal's removal
595
+ takes the parts the last first, each read against
596
+ its own span: what someone changed, or made, between
597
+ two parts stays.
598
+ --include-changed remove also the records changed since the run, and
599
+ what was added to them since (default: kept)
600
+ --accept-automation delete although the target runs flows, Apex triggers,
601
+ processes or workflow rules as the records go, those
602
+ --sweep deletes included \u2014 before or after a delete,
603
+ or as an activated order is set back to Draft for
604
+ its delete \u2014 or could not say what it runs
605
+ (default: off)
606
+ --mute-automation mute the target's automation for the removal through
607
+ its own bypass, as for a run: the permission sets
608
+ holding the bypasses of what fires as the records go,
609
+ those --sweep deletes included, assigned to the user
610
+ it deletes as, for the removal alone, and taken back
611
+ as it ends; what no bypass keeps quiet still needs
612
+ --accept-automation (default: off)
613
+ --leave-undeletable remove the rest when the user the removal runs as
614
+ may not delete the records of some objects of the
615
+ run, leaving those with what they hang from; without
616
+ it the removal stops before its first delete and
617
+ names them (default: off)
618
+ --preview say what the removal would do, and do nothing: per
619
+ object the records it would delete, those gone
620
+ already, those changed since the run and who changed
621
+ them, those it could not see, and what a removal run
622
+ now would be refused for, each under the code it is
623
+ refused with: a removal would be refused (CODE): ...,
624
+ with --json the codes under "refusalCodes", in the
625
+ order of "refusals". It reads the records, as
626
+ the removal reads them before its first delete, and
627
+ writes nothing: not to the org, not beside the
628
+ summary. With --sweep, it lists what the sweep would
629
+ take, and reads what fires on it with the run's own.
630
+ Not with --sweep-list or --audit.
631
+ A removal takes no --dry-run: one that did not read
632
+ it would delete for real.
633
+ --sweep before the run's records go, delete too what the
634
+ target's automation made for the run, that the run's
635
+ id map does not hold: what the run's user created
636
+ under the run's records, what they point at, or what
637
+ hangs from those, three links at most, at most a
638
+ minute after the record it is tied to \u2014 in the
639
+ objects the run wrote and their children, tasks,
640
+ events, feed, email messages, notes, case comments,
641
+ and the objects the target's flows create. What a
642
+ record of the run points at by a lookup the org
643
+ refuses the delete for (an asset its case names)
644
+ goes once that record is gone. Listed and kept: what
645
+ is tied to the run but came later, up to 15 minutes,
646
+ or as the org's Automated Process user; and what the
647
+ run's user created in the run's window, a second
648
+ before its first write to a minute after its last,
649
+ tied to nothing of it.
650
+ What anyone changed more than 2 s after the run's
651
+ last write, and after its own creation, stays \u2014 the
652
+ run's user and its automation too \u2014 unless
653
+ --include-changed, and the sweep then ends partial,
654
+ exit 3; a change made before the run's last write
655
+ reads as unchanged. Runs alone when an earlier
656
+ --remove took every record of the run. Of a clone of
657
+ the whole org, the removal says the sweep is off
658
+ unless given: the run's window spans hours, and a
659
+ sweep looks at 300 objects at most
660
+ (default: off)
661
+ --sweep-late with --sweep, take too what it lists as made late;
662
+ with --sweep-list, say what it would take
663
+ --sweep-untied with --sweep, take too what it lists as tied to
664
+ nothing of the run; with --sweep-list, say what it
665
+ would take; refused when another run of this
666
+ machine wrote to the target in the run's window, or
667
+ when that user created records there on objects
668
+ neither the run nor the automation reaches (hand
669
+ work, likely)
670
+ --sweep-user <id> with --sweep or --sweep-list, the user the run wrote as,
671
+ for a run whose summary does not keep it: the sweep
672
+ reads it otherwise from the run's records, and is
673
+ refused when none is left or several users made them
674
+ --sweep-list list what --sweep would delete, per object with a few
675
+ names and how many it ties to the run, and delete
676
+ nothing, the run's records included; exit 3, as a
677
+ refused --sweep, when it says the sweep is refused
678
+ What a sweep leaves, and why: what another user
679
+ created, a colleague's or an integration's; what is
680
+ tied to nothing, unless --sweep-untied; what came
681
+ more than 15 minutes after its record, or after the
682
+ removal began, which cannot be told from work done
683
+ by hand; what anyone changed after the run's last
684
+ write, the run's own user included, unless
685
+ --include-changed; what the
686
+ automation changed or deleted rather than created,
687
+ which a checkpoint taken before the run takes back;
688
+ what left the org (emails, outbound messages); more
689
+ than 10 000 records of one object; and what the
690
+ panel, another machine or a CI wrote meanwhile, which
691
+ a sweep does not see
692
+ --json print what became of the records as JSON on stdout,
693
+ every other line on stderr; refused before its first
694
+ delete, "refused": {"code", "message"}, the code its
695
+ line names: refused (CODE): ... \u2014 a production org
696
+ (PRODUCTION_TARGET), what fires as it deletes
697
+ (AUTOMATION_NOT_ACCEPTED), its mute (MUTE_PRODUCTION,
698
+ MUTE_NO_RIGHT, MUTE_FAILED), objects its user may not
699
+ delete (UNDELETABLE_NOT_LEFT), an org that is not the
700
+ one the run wrote to (OTHER_ORG, its --preview too)
701
+ --audit <file> record the removal, and the sweep, in the audit trail
702
+ kept in <file>
703
+
704
+ Verify what a run created:
705
+ --verify <file> the summary a run printed with --json, saved to a file,
706
+ or the journal of a run, every part of it
707
+ Reads back from --target every record the run created,
708
+ after a pause and again until two readings agree (three
709
+ at most, two seconds apart): those there, those in the
710
+ recycle bin, those neither, out of the user's sight;
711
+ checks on twenty records of each object that the
712
+ lookups the run set point at the ids their parents got,
713
+ reading the source records in --source; and lists the
714
+ records changed since the run, which --remove keeps
715
+ unless --include-changed. Only reads, from either org.
716
+ Exits 0 when VERIFIED, 3 when PARTIAL (a record not
717
+ there, a lookup that does not hold, or a part that could
718
+ not be checked) and 4 when UNSTABLE (no two readings
719
+ agreed: something still writes to the records).
720
+ --source <alias> the org the run read from (default: the summary's)
721
+ A lookup the clone left out with --exclude reads as
722
+ one left empty.
723
+ --json print the verification as JSON on stdout, every other
724
+ line on stderr; refused for an org that is not the
725
+ one the run wrote to, exit 1, "refused": {"code",
726
+ "message"}, the code its line names: refused
727
+ (OTHER_ORG): ...
728
+ --audit <file> record the verification in the audit trail kept in
729
+ <file>
730
+
731
+ Environment:
732
+ SANDFORGE_FORGE_PAGE_SIZE=<n>
733
+ a diagnostic: read every statement through the org's
734
+ cursor and hand it on in pages of <n> rows, as a run of
735
+ whole tables reads, to see a clone's paged read against
736
+ a real org. Not a setting: an org answers in pages of
737
+ 200 to 2000 rows, and a page of <n> is cut from them.
738
+ SANDFORGE_JOURNAL_DIR=<dir>
739
+ where every run that writes keeps its journal, in
740
+ <dir>/forge-runs/ (default: ~/.sandforge)
741
+ What the run wrote, read and still owes, line by line
742
+ as it goes, ids only: what --resume takes a run up
743
+ from, and what --remove takes it back from however it
744
+ ended.
745
+
746
+ Exit codes:
747
+ 0 the clone ran, a run the target refused some records of too unless
748
+ --fail-on-partial; the rehearsal ran, whatever it found refused; the removal
749
+ took every record it set out to take; the preview said what a removal
750
+ would do, refusals included
751
+ 1 the clone or the removal could not run; the clone produced only failures,
752
+ or its files were refused; --resume could not take the run up
753
+ (RESUME_UNAVAILABLE, RESUME_TARGET_CHANGED, RESUME_CHANGED,
754
+ RESUME_UNCERTAIN); the target is a production org; the target
755
+ runs automation on insert or on the updates the clone makes after its
756
+ inserts, or the removal's deletes fire automation, and
757
+ --accept-automation was not given; the target delivers the emails of
758
+ what still runs, or would not say whether it does, and --accept-emails
759
+ was not given (EMAILS_NOT_ACCEPTED); the checkpoint asked first was
760
+ refused or could not be taken (CHECKPOINT_REFUSED); the run would write
761
+ more than --max-total records, more than the target's data storage
762
+ has left or more emails than it has left today, or would take more API
763
+ requests than it has left today (nothing is written or deleted then);
764
+ a clone of the whole org nobody answered the question of
765
+ (CONFIRMATION_UNAVAILABLE) or that was declined (WRITE_DECLINED), or
766
+ whose dry run says a real run would be refused; a sample of it that
767
+ could not be drawn (SAMPLE_STORAGE_UNREAD, SAMPLE_CANNOT_FIT,
768
+ SAMPLE_TOO_LARGE), or whose draw leaves no root (SAMPLE_DRAW_EMPTY);
769
+ a query that chooses no record (NO_ROOTS) or more than --max-roots
770
+ (ROOTS_EXCEEDED), records that reach more than --max-read-total
771
+ (READ_BOUND_EXCEEDED); a removal of a run that still
772
+ writes its journal, or its preview, and a --resume of it, or of a run
773
+ whose removal is under way (RUN_WRITING)
774
+ 2 a bad command line, an --exclude that names no field of the source
775
+ (FIELD_EXCLUSION_UNMATCHED), an --object no clone writes
776
+ (TABLE_NEVER_CLONED), or a summary --remove cannot take a run back from, or
777
+ a file beside it that is not what a removal kept there; the plan of a
778
+ sample --fit-plan gives or --resume takes up gone, or drawn of another
779
+ org or setup (SAMPLE_PLAN_GONE, SAMPLE_PLAN_MISMATCH); a draw whose
780
+ --fit-window, --fit-where or --fit-strata the source cannot take
781
+ (SAMPLE_DRAW_INVALID); a query that cannot choose the records it
782
+ clones (ROOTS_QUERY_REFUSED); the plan of roots --roots-plan gives
783
+ gone, or of another org, query or records
784
+ (ROOTS_PLAN_GONE, ROOTS_PLAN_MISMATCH), and a run taken up whose journal
785
+ names none of the roots it read (ROOTS_PLAN_GONE)
786
+ 3 the run was partial and --fail-on-partial was given, or was a clone of
787
+ the whole org; the removal left
788
+ records of the run in the org: kept, or refused, or found neither in the
789
+ org nor in its recycle bin, as the user it ran as sees them; or the sweep
790
+ was refused, or did not take all it was asked to (a --sweep-untied
791
+ refused included)
792
+ 130 Ctrl-C stopped the clone: the summary says what it created by then
793
+ 143 a SIGTERM stopped it \u2014 a CI job cancelled or timed out \u2014, 129 a SIGHUP:
794
+ as Ctrl-C does, the summary and the journal say what it created
795
+ `,mr=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,nt=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function ib(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 ab={"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"},db={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"},Nm=["fieldExclusions","excludedObjects","ownerMappings","objectSoqlFilters","fieldMappings","picklistValueMappings","recordTypeMappings","defaultValues","truncateFields","skippedRows","ignoredGaps"],cb=M.strictObject(Hc.pick(Object.fromEntries(Nm.map(r=>[r,!0]))).shape);function ub(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 lb(r){let e=[];function t(n){process.stderr.write(`${n}
796
+ `),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"){nt.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 Mm(r){let[e]=r;return`SELECT Id FROM ${e.objectApiName}${e.where?` WHERE ${e.where}`:""}`}function fb(r,e){let t=new Set(e.map(n=>n.objectApiName));return r.nodes.map(n=>n.objectApiName).filter(n=>!t.has(n))}function pb(r,e){let t=new Set(r.nodes.map(n=>n.objectApiName));return e.map(n=>n.objectApiName).filter(n=>!t.has(n))}function hb(r){if(!Mr(r))return;let e=Kt(),t=e?`the table ${r}`:`--object ${r}`;return Vc(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 gb=10;function mb(r,e){let t=r.filter(i=>Eo(i)&&!Mr(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<gb?[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(`
797
+ `)}function wb(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 yb(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 om=1e3;function bb(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.
798
+ `),process.exit(2));let t=Number(r);return(r===void 0||!/^\d{1,4}$/.test(r)||t<1||t>om)&&(process.stderr.write(`--max-orphans takes a whole number of parents, 1 to ${om}, not "${r??""}".
799
+ `),process.exit(2)),t}function Rb(r,e){let t=r.tables??[],n=[...new Set([...r.excludedObjects,...fb(e,t)])];return{inputMode:"soql",soqlQuery:Mm(t),depth:r.depth,...r.depth==="custom"?{customDepth:r.customDepth}:{},sourceOrgId:r.source,targetOrgId:r.target,anonymizePII:r.anonymize,...Xs(r),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 Ob(r,e,t,n,o){let s=Kd(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 dc(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:Mm(r.tables)}:{inputMode:"record",recordId:r.record}}function kb(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 Zd=12;function Sb(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 Tb(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<=Zd?e.join(", "):`${e.slice(0,Zd).join(", ")} and ${e.length-Zd} more object(s)`;return r.wholeOrg?e.length>0?`the whole org (${t})`:"the whole org":e.length>0?t:"the run"}function sm(r,e){return r.anonymize?"anonymize: on"+(r.anonymizationMode==="everything"?", every personal field":"")+(e!==void 0?`, ${e}`:""):`anonymize: off, the personal data copied as ${r.source} holds it`}function im(r){return{anonymize:r.anonymize,anonymizationMode:r.anonymize?r.anonymizationMode:"standard"}}function Xs(r){return r.anonymizationMode==="everything"?{anonymizationMode:"everything"}:{}}function Ab(r){return{inputMode:"org",depth:"all",sourceOrgId:r.source,targetOrgId:r.target,anonymizePII:r.anonymize,...Xs(r),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:Bm(r.sample)}:{}}}function Bm(r){let e={...r.options};return delete e.plan,e}function jb(r,e,t,n,o,s){return Kd(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 $b(r,e){return e.size===0?r:{...r,nodes:r.nodes.map(t=>e.has(t.objectApiName)?{...t,included:!1,leftOutByUser:!0}:t)}}var am=1e6;function vb(r,e){if(e.length>am)return{refusal:[`${r}: the file is larger than ${am} 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=Kc.safeParse(t);return s.success?{file:{kind:"template",template:s.data}}:{refusal:n(s.error)}}let o=cb.safeParse(t);return o.success?{file:{kind:"config",config:o.data}}:{refusal:[...n(o.error),`${r} takes ${Nm.join(", ")}; the other choices have flags of their own.`]}}var si=["--fit-within","--fit-seed","--fit-draw","--fit-window","--fit-where","--fit-strata","--fit-parents","--fit-children","--fit-whole","--fit-floor","--fit-plan"],Eb={switches:["--list-objects","--anonymize",Pr,"--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",...Vd.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",...si,"--query","--max-roots","--roots-plan","--max-read-total",...Vd.values]},Ib=[["--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 ${Gt("empty")} --target <alias> --objects <A,B> --dry-run says what emptying the target's objects would delete, every record of them`]];function xb(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.
800
+ `),process.exit(2)}let t=Ib.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}.
801
+ `);process.exit(2)}}var Pb=["--fit-whole","--fit-where","--fit-strata"],Fb=si.filter(r=>!Pb.includes(r)),Cb={created:"CreatedDate",modified:"LastModifiedDate"},Nb=`--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 ${wo}`;function Mb(r){let e=r.indexOf(":"),t=e>0?Cb[r.slice(0,e)]:void 0,n=r.slice(e+1),o=l=>({refusal:`${Nb}, 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>wo?o(`: ${l} days is out of 1 to ${wo}`):{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:Ti(a,!1),u=d===""?void 0:Ti(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 Bb(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(!nt.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(!qc.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>Si)return{refusal:`--fit-where filters the roots of ${Si} 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 Lb(r){let e=[];for(let n of r){if(!Gc.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>ki)return{refusal:`--fit-strata stratifies the roots by ${ki} fields at most, not ${e.length}.`};let t=zc.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 dm=1e4,cm=1e6,um=1e6,Wb="sample.json";function Db(r,e){let t=b=>(process.stderr.write(`${b}
802
+ `),process.exit(2)),n=b=>r.flatMap((T,k)=>T===b&&k+1<r.length?[r[k+1]]:[]),o=b=>r.includes(b),s=si.filter(b=>o(b));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 b of Fb)n(b).length>1&&t(`${b} is given twice: give it once.`);let a=b=>n(b)[0],d={maxTotal:e.maxTotal},c=a("--fit-within");if(c!==void 0){let b=Number(c);(!/^\d+(?:\.\d+)?$/.test(c)||b<=0||b>um)&&t(`--fit-within takes a number of MB above 0, up to ${um}, not "${c}".`),d.withinMB=b}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 b=Mb(f);"refusal"in b?t(b.refusal):d.window=b}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 h=a("--fit-children");if(h!==void 0){let b=Number(h);h==="all"?d.children="all":/^\d{1,7}$/.test(h)&&b>=1&&b<=cm?d.children=b:t(`--fit-children takes a whole number of children from 1 to ${cm}, or all, not "${h}".`)}let g=[];for(let b of n("--fit-whole"))nt.test(b)||t(`Invalid --fit-whole value "${b}" (must match SObject API name pattern)`),g.includes(b)||g.push(b);let m=g.filter(b=>e.excludedObjects.includes(b));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.`),g.length>0&&(d.whole=g);let w=Bb(n("--fit-where"),{whole:g,excludedObjects:e.excludedObjects});"refusal"in w?t(w.refusal):Object.keys(w.where).length>0&&(d.rootWhere=w.where);let O=Lb(n("--fit-strata"));"refusal"in O?t(O.refusal):O.strata.length>0&&(d.strata=O.strata);let S=a("--fit-floor");if(S!==void 0){let b=Number(S);(!/^\d{1,5}$/.test(S)||b>dm)&&t(`--fit-floor takes a whole number of records from 0 to ${dm}, not "${S}".`),d.floor=b}let R=a("--fit-plan");if(R!==void 0){let b=Ut(R);d.plan=yc(b)===Wb?ob(b):b}return{options:d,maxTotalGiven:e.maxTotalGiven}}var _b=["--query","--max-roots","--roots-plan","--max-read-total"],qb=["--record","--object","--where","--fit",...si];function Ub(r){let e=O=>r.includes(O),t=O=>r.flatMap((S,R)=>S===O?[r[R+1]]:[]),n=O=>(process.stderr.write(`${O}
803
+ `),process.exit(2)),o=t("--query"),s=t("--record");if(o.length===0&&s.length<2){let O=_b.filter(S=>e(S));O.length>0&&n(`${O.join(", ")} ${O.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=(O,S,R)=>{let b=Number(S);return S===void 0||S.startsWith("--")||!Number.isInteger(b)||b<1||b>R?n(`${O} takes a whole number, 1 to ${R.toLocaleString("en-US")}.`):b},a=O=>{let S=t(O);return S.length>1&&n(`${O} is given ${S.length} times: give it once.`),S[0]},d=a("--max-roots"),c=d===void 0&&!e("--max-roots")?$r:i("--max-roots",d,Sn),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 S=[["--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(([R])=>e(R));S.length>0&&n(`--roots-plan does not go with ${S.map(([R,b])=>`${R}: ${b}`).join("; ")}.`)}let p=f!==void 0?Ut(f):void 0,h={cap:c,...p!==void 0?{plan:p}:{},...l?{readTotal:l}:{}};if(o.length>0){let O=[...qb.filter(T=>e(T)),...t("--depth").includes("all")?["--depth all"]:[]];O.length>0&&n(`--query clones the records a query chooses, each with what the clone of that record copies: it does not go with ${O.join(", ")} (--record names records one by one, --object reads whole tables, --depth all copies the whole org or a sample of it).`);let S=a("--query");if(S===void 0||S.trim()===""||S.startsWith("--"))return n("--query takes a SOQL query, as SELECT Id FROM Account WHERE \u2026");let R=Wc(S),b=Lc(S);return R!==void 0||!b?n(Tt({code:"ROOTS_QUERY_REFUSED",message:`${Dc(R??{kind:"noObject"})}. Nothing was read or written.`})):(b.limit!==null&&b.limit>c&&n(`--query: its LIMIT ${b.limit} is past the ${c} records a run clones: give --max-roots ${b.limit} (up to ${Sn.toLocaleString("en-US")}), or a lower LIMIT.`),{query:{soql:S.trim(),objectApiName:b.objectApiName,roots:{...b.where!==null?{where:b.where}:{},...b.orderBy!==null?{orderBy:b.orderBy}:{},...b.limit!==null?{limit:b.limit}:{}}},...h})}let g=[],m=new Set;for(let O of s){(O===void 0||!mr.test(O))&&n(`--record takes the 15- or 18-character id of a record: "${O??""}" is none.`);let S=(O??"").slice(0,15);m.has(S)||(m.add(S),g.push(O??""))}let w=[...new Set(g.map(O=>O.slice(0,3)))];return w.length>1&&n(`--record names records of ${w.length} objects (${w.map(O=>`${O}\u2026`).join(", ")}): a clone from records takes the records of one object; clone each object\u2019s apart, or choose them with --query.`),g.length>c&&n(`--record names ${g.length} records, past the ${c} a run clones: give --max-roots ${Math.min(g.length,Sn)} (up to ${Sn.toLocaleString("en-US")}), or name fewer.`),{ids:g,...h}}function Gb(r,e=process.env){let t=r.slice(2);(t.includes("-h")||t.includes("--help"))&&(process.stdout.write(bc),process.exit(0)),du(t,Eb);let n=(P,D)=>{let X=t.indexOf(P);return X>=0&&X+1<t.length?t[X+1]:D},o=P=>t.includes(P);o("--config")&&o("--template")&&(process.stderr.write(`--config and --template: give one of them.
804
+ `),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.
805
+ `),process.exit(2));let P;try{P=gn(i,"utf8")}catch(X){process.stderr.write(`${s}: cannot read ${i}: ${Q(X)}
806
+ `),process.exit(2)}let D=vb(s,P);if("refusal"in D){for(let X of D.refusal)process.stderr.write(`${X}
807
+ `);process.exit(2)}a=D.file}let d=a?.kind==="template"?a.template:void 0,c=Ub(t),u=n("--depth")==="all";xb(o,u);let l=a?.kind==="template"?{...a.template.config}:a?.config??{},f=d?.config.soqlQuery!==void 0?ub(d.config.soqlQuery):void 0,p=f!==void 0?l.objectSoqlFilters?.[f]:void 0;if(f!==void 0&&l.objectSoqlFilters?.[f]!==void 0){let P={...l.objectSoqlFilters};delete P[f],l.objectSoqlFilters=P}let h=lb(t);if(h){let P=["--record","--expand-orphans","--max-orphans","--rehearse"].filter(D=>o(D));if(P.length>0){let D=P.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 ${P.join(", ")}, which ${P.length===1?"goes":"go"} with a clone of one record (--record).${D}
808
+ `),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.
809
+ `),process.exit(2))}let g=d?.config.inputMode==="record"?d.config.recordId:void 0;d&&!h&&!c?.query&&!o("--record")&&!g&&(process.stderr.write(`${wb(d.config.inputMode,f,p)}
810
+ `),process.exit(2));let m=h||u||c?.query?void 0:n("--record")??g,w=n("--source"),O=n("--target"),S=[...!m&&!h&&!u&&!c?["what to clone"]:[],...w?[]:["--source"],...O?[]:["--target"]];(S.length>0||!w||!O)&&(process.stderr.write(`${yb(S)}
811
+ `),process.exit(2)),o("--include-changed")&&(process.stderr.write(`--include-changed goes with --remove.
812
+ `),process.exit(2));let R=["--dry-run","--upsert","--files","--remap-csv","--list-objects"].filter(P=>o(P));o("--rehearse")&&R.length>0&&(process.stderr.write(`--rehearse does not go with ${R.join(", ")}.
813
+ `),process.exit(2));let b=tR(t),T=Qg(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."}]),k=n("--depth")??d?.config.depth??"custom",v=n("--custom-depth")??(d?.config.customDepth!==void 0?String(d.config.customDepth):"5"),$=n("--max")??(d?.config.maxRecordsPerObject!==void 0?String(d.config.maxRecordsPerObject):void 0),E=n("--max-nodes")??(d?.config.maxNodes!==void 0?String(d.config.maxNodes):void 0),B=n("--max-total"),I=n("--max-records-per-object"),G=P=>{let D=[];for(let X=0;X<t.length;X++)t[X]===P&&X+1<t.length&&D.push(t[X+1]);return D},re=Object.fromEntries(Object.entries(l.fieldExclusions??{}).map(([P,D])=>[P,[...D]]));for(let P of G("--exclude")){let D=P.indexOf(".");(D<=0||D===P.length-1)&&(process.stderr.write(`Invalid --exclude value "${P}" (expected Object.field)
814
+ `),process.exit(2));let X=P.slice(0,D),H=P.slice(D+1);(!nt.test(X)||!nt.test(H))&&(process.stderr.write(`Invalid --exclude name in "${P}" (must match SObject API name pattern)
815
+ `),process.exit(2));let je=re[X]??=[];je.includes(H)||je.push(H)}let z=[...l.excludedObjects??[]];for(let P of G("--exclude-object"))nt.test(P)||(process.stderr.write(`Invalid --exclude-object value "${P}" (must match SObject API name pattern)
816
+ `),process.exit(2)),z.includes(P)||z.push(P);let _={...l.ownerMappings};for(let P of G("--owner-map")){let D=P.indexOf("=");(D<=0||D===P.length-1)&&(process.stderr.write(`Invalid --owner-map value "${P}" (expected sourceId=targetId)
817
+ `),process.exit(2));let X=P.slice(0,D),H=P.slice(D+1);(!mr.test(X)||!mr.test(H))&&(process.stderr.write(`Invalid --owner-map IDs in "${P}" (must be 15 or 18 char Salesforce IDs)
818
+ `),process.exit(2)),_[X]=H}let ee={...l.objectSoqlFilters};for(let P of G("--filter")){let D=P.indexOf("=");(D<=0||D===P.length-1)&&(process.stderr.write(`Invalid --filter value "${P}" (expected Object=where-clause)
819
+ `),process.exit(2));let X=P.slice(0,D),H=P.slice(D+1);H.length>512&&(process.stderr.write(`--filter where-clause for "${X}" exceeds 512 chars
820
+ `),process.exit(2)),/--|\/\*|\*\/|;\s*$/.test(H)&&(process.stderr.write(`--filter where-clause for "${X}" contains forbidden tokens (--, /*, */, trailing ;)
821
+ `),process.exit(2)),ee[X]=H}let ve=new Set(G("--filter").map(P=>P.slice(0,P.indexOf("="))));for(let P of h??[])P.where!==void 0&&(ve.has(P.objectApiName)&&(process.stderr.write(`--where and --filter both filter ${P.objectApiName}: give one of them.
822
+ `),process.exit(2)),P.where.length>512&&(process.stderr.write(`--where for "${P.objectApiName}" exceeds 512 chars
823
+ `),process.exit(2)),/--|\/\*|\*\/|;\s*$/.test(P.where)&&(process.stderr.write(`--where for "${P.objectApiName}" contains forbidden tokens (--, /*, */, trailing ;)
824
+ `),process.exit(2)),ee[P.objectApiName]=P.where);let he=Object.fromEntries(Object.entries(l.fieldMappings??{}).map(([P,D])=>[P,{...D}]));for(let P of G("--map")){let D=P.indexOf("."),X=P.indexOf("=");(D<=0||X<=D+1||X===P.length-1)&&(process.stderr.write(`Invalid --map value "${P}" (expected Object.sourceField=targetField)
825
+ `),process.exit(2));let H=P.slice(0,D),je=P.slice(D+1,X),U=P.slice(X+1);(!nt.test(je)||!nt.test(U))&&(process.stderr.write(`Invalid --map field name in "${P}" (must match SObject API name pattern)
826
+ `),process.exit(2)),(he[H]??={})[je]=U}let de=v?Number(v):5,K=$?Number($):void 0,ne=E?Number(E):void 0;ne!==void 0&&(!Number.isInteger(ne)||ne<1)&&(process.stderr.write(`--max-nodes takes a whole number of objects, 1 or more.
827
+ `),process.exit(2));let fe=bb(n("--max-orphans"),{given:o("--max-orphans"),expands:o("--expand-orphans")||d?.config.expandOrphanParents===!0}),Ae=B===void 0?qn:Number(B);(!Number.isInteger(Ae)||Ae<1)&&(process.stderr.write(`--max-total takes a whole number of records, 1 or more.
828
+ `),process.exit(2));let me=I===void 0?mo:Number(I);(!Number.isInteger(me)||me<1||me>Oi)&&(process.stderr.write(`--max-records-per-object takes a whole number of records, 1 to ${Oi}.
829
+ `),process.exit(2));let ce=e.SANDFORGE_FORGE_PAGE_SIZE,W=ce===void 0||ce===""?void 0:Number(ce);W!==void 0&&(!Number.isInteger(W)||W<1)&&(process.stderr.write(`SANDFORGE_FORGE_PAGE_SIZE takes a whole number of rows, 1 or more.
830
+ `),process.exit(2)),o(Pr)&&o("--no-anonymize")&&(process.stderr.write(`${Pr} anonymizes every personal field, and --no-anonymize none: give one of them.
831
+ `),process.exit(2));let J=!o("--no-anonymize")&&nu(o(Pr),e)==="everything"?"everything":"standard",we=o("--anonymize")||J==="everything"||d?.config.anonymizePII===!0,Y=o("--keep-contact-points")||d?.config.keepContactPoints===!0,Ce=rR(t,we),Oe=Zo(l),Ne=Db(t,{wholeOrg:u,maxTotal:Ae,maxTotalGiven:B!==void 0,excludedObjects:z}),q=(u?Ai:Ai.safeExtend({depth:Uc})).safeParse({...dc({record:m,tables:h,depth:u?"all":void 0,roots:c}),depth:k,customDepth:k==="custom"?de:void 0,sourceOrgId:w,targetOrgId:O,anonymizePII:we,...J==="everything"?{anonymizationMode:J}:{},keepContactPoints:Y,skipEmpty:!0,batchSize:"auto",maxRecordsPerObject:K,fieldExclusions:re,excludedObjects:z,ownerMappings:_,objectSoqlFilters:ee,fieldMappings:he,...Oe,...Ne?{sample:Ne.options}:{}});if(!q.success){for(let P of q.error.issues){let[D,...X]=P.path.map(String),H=db[D??""]??(s&&D?`${s} ${D}`:D??"arguments"),je=X.length>0?` (${X.join(".")})`:"";process.stderr.write(`Invalid ${H}${je}: ${P.message}
832
+ `)}process.exit(2)}return{record:m,...c?{roots:c}:{},tables:h,source:w,target:O,depth:q.data.depth,customDepth:de,maxNodes:ne,maxRecordsPerObject:K,anonymize:we,anonymizationMode:J,anonymizeGiven:o("--anonymize")||o("--no-anonymize")||J==="everything",yes:o("--yes"),keepContactPoints:q.data.keepContactPoints===!0,dryRun:o("--dry-run"),listObjects:o("--list-objects"),upsert:o("--upsert"),expandOrphans:o("--expand-orphans")||d?.config.expandOrphanParents===!0,...fe!==void 0?{maxOrphans:fe}:{},applyAssignmentRules:o("--apply-assignment-rules")||d?.config.applyAssignmentRules===!0,skipPreflight:o("--skip-preflight"),json:o("--json"),failOnPartial:o("--fail-on-partial"),summary:b,fieldExclusions:re,excludedObjects:z,ownerMappings:_,objectSoqlFilters:ee,fieldMappings:he,remapCsv:nR(t),files:Ce,acceptAutomation:o("--accept-automation"),acceptEmails:o("--accept-emails"),muteAutomation:o("--mute-automation"),...T!==void 0?{checkpointFirst:T}:{},maxTotal:Ae,readCeiling:me,...W!==void 0?{pageSize:W}:{},rehearse:o("--rehearse"),decisions:Oe,anonymizationRules:{...d?.anonymization?.rules},anonymizeFields:d?.anonymization?.fields,choicesFrom:s&&i?{flag:s,path:i}:void 0,audit:Rc(t),resume:Vb(t),writeUncertain:zb(t),...Ne?{sample:Ne}:{}}}function zb(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.
833
+ `),process.exit(2)),!0):!1}function Hb(r,e){let t=Es(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 Kb(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(Es(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(wl(a,"save")*1e3)}o=Math.max(o,i)}return new Date(o).toISOString()}function Vb(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.
834
+ `),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(", ")}.
835
+ `),process.exit(2)),t}function lm(r,e){return r.endsWith(".ndjson")||/[\\/]/.test(r)?Ut(r):e.pathOf(r)}function fm(r,e,t={}){return{...r.sample?{sample:fh(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,...r.anonymizationMode==="everything"?{anonymizationMode:"everything"}:{},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 Jb(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 ${Ar(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=Zb(r,e),a=t.sample?.asked===!0;if(i===void 0&&a)return{code:gs,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:gs,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 dr.open(i.dir,{sha256:i.sha256})}catch(c){let u=ms(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(!ph(n.resume.fingerprint,t.graph,s))return{code:"RESUME_CHANGED",message:`The clone is set up otherwise than the run to take up: ${Xb(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 ${Ar(e)}, and run the clone again as it is now. Nothing was written.`}}var Qb={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"},Yb=new Set(["inputMode","targetOrgId","skipEmpty","batchSize","dryRun"]);function Xb(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=>!Yb.has(p)&&p!=="recordId"),a=new Set;for(let p of i)JSON.stringify(o[p]??null)!==JSON.stringify(s[p]??null)&&a.add(Qb[p]??p);a.size>0&&t.push(`${[...a].join(", ")} differ`);let d=p=>new Set(p.nodes.filter(h=>h.included||jr(h)).map(h=>h.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 ${hn(l)}, which this one leaves`),f.length>0&&t.push(`this one takes ${hn(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 Zb(r,e){let t=r.openAt(e);try{return t.samplePlan}finally{t.close()}}function Rc(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.
836
+ `),process.exit(2));try{Ya(t)}catch(n){process.stderr.write(`--audit ${t} is not an audit trail the command can add to (${Q(n)}): give another file, or move it.
837
+ `),process.exit(2)}return t}function eR(r,e){return{configStore:Ya(r),orgManager:{getOrg:t=>e.get(t)},log:t=>process.stderr.write(`${t}
838
+ `)}}function Zs(r,e,t){if(!r){ju(t);return}try{vu(eR(r,e),t)}catch(n){process.stderr.write(`The run's entry could not be added to the audit trail in ${r} (${Q(n)}).
839
+ `)}}function tR(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.
840
+ `),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(", ")}.
841
+ `),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.
842
+ `),process.exit(2)),t}function nR(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.
843
+ `),process.exit(2));let n=Ut(process.cwd(),t),o=Ut(process.cwd());return n===o||n.startsWith(o+sb)||(process.stderr.write(`--remap-csv must stay inside cwd: "${t}" resolves outside ${o}
844
+ `),process.exit(2)),n.toLowerCase().endsWith(".csv")||(process.stderr.write(`--remap-csv must use a .csv extension: "${t}"
845
+ `),process.exit(2)),Yt(n)&&(process.stderr.write(`--remap-csv refuses to overwrite existing file: "${n}". Give another file, or move it.
846
+ `),process.exit(2)),n}function rR(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.
847
+ `),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.
848
+ `),process.exit(2)),ho(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.
849
+ `),process.exit(2)),{maxFileSizeMB:i,acceptedAsIs:n}}function oR(r){let e=Uu(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}:{},...Gu(t,e),...typeof t.groupable=="boolean"?{groupable:t.groupable}:{},...typeof t.sortable=="boolean"?{sortable:t.sortable}:{},...typeof t.aggregatable=="boolean"?{aggregatable:t.aggregatable}:{}}))}function sR(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 iR(r,e,t){let n="SELECT Id, Name, DeveloperName, NamespacePrefix, SobjectType FROM RecordType WHERE IsActive = true",o=async u=>(await Po({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 up(d,c))t?.(lp(u));return new Rs().buildMapping(d,c)}function aR(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 ec(r,e,t=!1){let n=t?await r.sobject(e).describe():await r.describe$(e);return{keyPrefix:n.keyPrefix??null,recordTypes:Xu(n.recordTypeInfos)}}function Pj(r){return xo(r)==="failure"}var tc={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 cc({developerName:r,label:e}){return e!==""&&e!==r?`${r} (${e})`:r}function nc(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=cc(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 dR(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 ${cc(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} ${cc(a)}`).join(", ");return`read back on ${t}: ${i}; the describe said ${n}: an automation of the target sets the record type`}function cR(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(tc).filter(d=>(n.why[d]??0)>0),s=o.length===1?` ${tc[o[0]]}`:o.length>1?` (${o.map(d=>`${n.why[d]} ${tc[d]}`).join(", ")})`:"",{readBack:i}=n,a=e?nc(n,"would go in"):i?i.unread!==void 0?`${nc(n,"went in, its describe says,")}; the record types they hold could not be read back: ${i.unread}`:dR(n,i):nc(n,"went in, its describe says,");t.push(` ${n.objectApiName} ${n.rows} record(s)${s}: ${a}`)}return t}function uR(r,e){let t=er(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=er(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} ${er(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: ${er(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} ${er(o.bytes)} \u2014 ${s}`)}}return n}function Lm(r,e){let t=r.truncatedObjects??[];if(t.length!==0)return{...e!==void 0?{perObject:e}:{},objects:[...t]}}function lR(r,e=!1){let t=new Map;for(let{objectApiName:a,rows:d}of r.writtenByThePlatform??[]){let c=Dn(a);t.set(c,(t.get(c)??0)+d)}let n=[...t.values()].reduce((a,d)=>a+d,0),o=r.linkedToCreatedCount??0;if(n===0&&o===0)return`linked: ${r.linkedCount} (already in the target, not created)`;let s=r.linkedCount-n-o,i=[...s>0?[`${s} already in the target, not created`]:[],...o>0?[e?`${o} to records the run would create: the target would refuse them as copies of those`:`${o} to records the run created, the target refusing them as copies of those`]:[],...[...t].map(([a,d])=>`${d} written by the platform with ${a}`)];return`linked: ${r.linkedCount} (${i.join("; ")})`}var rc="FIELD_EXCLUSION_UNMATCHED";function Wm(r){let e=`${In("--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 fR(r){return[`left nothing out, naming no field of the source (${r.length}):`,...r.map(e=>` ${Wm(e)}`)]}function pm(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(Wm).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 pR(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,sr(d)?void 0:null)}}return is(r,o,i=>s.has(i)?s.get(i):null).unmatched}function hR(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 hm(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)`]:[],lR(r,e),`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 h of r.existingRecords){let g=h.linkedToCreated??0,m=[...h.linked-g>0||g===0?[`${h.linked-g} linked`]:[],...g>0?[e?`${g} linked to records the run would create (the target would refuse them as copies of those)`:`${g} linked to records the run created (refused as copies of those)`]:[]];h.unidentified>0&&m.push(`${h.unidentified} not identified \u2014 their children lost the link`),o.push(` ${h.objectApiName} ${m.join(", ")}`)}}if(r.cappedObjects){let{perObject:h,objects:g}=r.cappedObjects;o.push("",`stopped at ${h} records per object (${In("--max","maxRecordsPerObject")}), the source holding more, which were not cloned (${g.length} object(s)):`,...g.map(m=>` ${m}`))}let s=Lm(r,t);if(s){let h=s.perObject!==void 0?`${s.perObject} `:"",g=Kt()?"":" (--max-records-per-object)";o.push("",`TRUNCATED at ${h}records per object${g}, 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("",...fR(i)),r.orphanParentsCapped&&o.push("",hR(r.orphanParentsCapped)),r.files&&o.push("",...uR(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:h,fields:g}of a)o.push(` ${h} ${g.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:h,fields:g}of d)o.push(` ${h} ${g.join(", ")}`)}let c=r.picklistValuesChanged??[];if(c.length>0){let h=new Set(c.map(g=>g.objectApiName)).size;o.push("",`picklist values not written as read (${h} object(s)):`);for(let g of c)o.push(` ${g.objectApiName} ${ql(g)}`)}let u=r.currenciesReplaced??[];if(u.length>0){let h=new Set(u.map(g=>g.objectApiName)).size;o.push("",`written in another currency (${h} object(s)):`);for(let g of u)o.push(` ${g.objectApiName} ${Yu(g)}`)}let l=cR(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:h,fields:g}of f)for(let{field:m,refusedBy:w="validation-rule",reason:O,rows:S}of g)o.push(` ${h}.${m} ${S} record(s) \u2014 ${ab[w]} \u2014 ${O}`)}r.contactPoints&&o.push("",...SR(r.contactPoints,e));let p=r.mayHaveBeenWritten??[];if(p.length>0){o.push("",`may be in the target, under ids the run never learned (${In("--remove","destroy")} cannot reach them):`);for(let{objectApiName:h,sourceIds:g}of p)o.push(` ${h} ${g.length} record(s)`)}if(r.decisionsApplied&&r.decisionsApplied.length>0&&o.push("",...kR(r.decisionsApplied)),r.gaps&&o.push("",...RR(r.gaps)),r.errors.length>0){o.push("",`errors (${r.errors.length} object(s)):`);for(let h of r.errors){o.push(` [${h.stage}] ${h.objectApiName} ${h.failedCount}/${h.attemptedCount}`);for(let g of h.samples){o.push(` ${g.recordSummary}`);for(let m of g.messages)o.push(` \u2514 ${m}`)}}}return o}function gR(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 no=10;function mR(r){let e=r.length-no;return`${r.slice(0,no).join(", ")}${e>0?` and ${e} more`:""}`}function Cn(r,e){return`${r.toLocaleString("en-US")} ${e}${r===1?"":"s"}`}function wR(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: ${Cn(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: ${Cn(t.read,`${n} record`)} the query returns (${o}at most ${t.cap})`:`roots: ${Cn(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} (${Cn(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} (${mR(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: ${Cn(d,"record")} of ${Cn(a.length,"object")}`+(r.reads?`, ${Cn(r.reads.source,"request")} of ${e.source}`:""));for(let l of a)i.push(...yR(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,no))i.push(` ${l}: ${f}`);t.failed.length>no&&i.push(` and ${t.failed.length-no} more`)}return i}function yR(r){let e=r.origin;if(!e)return[];let t=[...e.roots>0?[Cn(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 bR(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 RR(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)${bR(e)}`})]}function OR(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=Nc(a.gapId),c=Ul(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 kR(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 SR(r,e){if(!r.neutralized)return[`contact points: written as read (${In("--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`]:[],...mf(r).map(n=>` ${n}`)]}function TR(r){return r.flatMap(({objectApiName:e,fields:t})=>t.flatMap(n=>{if(n.externalId!==!0||n.createable===!1)return[];let o=Bu(n.name,String(n.type).toLowerCase());return o?[{objectApiName:e,field:n.name,kind:o}]:[]}))}function AR(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 jR(r,e,t,n){if(!r)return{};let o=ou(Mc(e.gaps,t??[]).filter(s=>!go(s,n)));return o.length>0?{adminChanges:o}:{}}function $R(r,e){let t=Lm(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:ZR(r.sample)}:{},...r.roots?{roots:r.roots}:{},...r.reads?{reads:r.reads}:{}}}function vR(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 ER(r){let e=new Set(r.nodes.filter(jr).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=jt("--list-objects")?"; --list-objects names them":"";return` Skipped ${e.size} objects (excluded: empty tables${o})`}return vR(n)}}function IR(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(Nf).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}=Km(r),l=c.length>0?`, ${c.length} not counted (${hn(c)})`:"",f=u.length>0?`, ${u.length} of them kept though their count got no answer (${hn(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 Dm={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 xR(r,e,t){let n=r.nodes.filter(a=>a.included).length,{objects:o,counts:s}=hs(r),i=s.map(({reason:a,count:d})=>`${d} ${Dm[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 PR={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 FR(r,e,t){let n;try{return await r.discover(e,{onProgress:o=>{if(o.phase===n)return;n=o.phase;let s=PR[o.phase];s&&t(s(o.total))}})}catch(o){process.stderr.write(`The whole org could not be discovered: ${Q(o)}
850
+ `),process.exit(1)}}function oc(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 gm=10;function hn(r){let e=r.length-gm;return e>0?`${r.slice(0,gm).join(", ")} and ${e} more`:r.join(", ")}function CR(r,e,t,n=[]){let{source:o,bulk:s}=r,i=s?.restRows??n.reduce((w,O)=>w+Math.max(0,O.restRows??0),0),a=n.filter(({jobs:w})=>w>0),d=a.length>0?` (${hn(a.map(w=>`${w.objectApiName}: ${w.jobs} of ${w.jobRows}`))}; rows of a job carrying the same values go by REST instead)`:"",c=[` writes: ${s?.jobs??0} Bulk API job(s) of ${s?.jobRows??0} record(s) at most${d}, ${i} 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`,oc("API requests",r.targetApi,t),...s?.batches?[oc("Bulk API batches",s.batches,t)]:[],oc("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`]:[]],u=r.fileStorage;u&&c.push(` files: ${u.files} file(s), about ${qt(u.estimateMB)} MB of file storage, of the ${u.remainingMB} MB ${t} has left of ${u.maxMB} MB`+(u.overCeiling>0?`; ${u.overCeiling} past the largest file copied, left out`:""));let l=e.map(({reason:w,count:O})=>`${O} ${Dm[w]}`).join(", ");c.push(` left out of ${o}: ${r.leftOut} object(s)${l?`: ${l}`:""}`);let{carried:f}=r,p=f?[["read through a filter",f.filters],["left out by name",f.excluded],["with rows held back by a decision",f.heldBack],["copied without some of their fields",f.fieldsLeftOut]]:[];for(let[w,O]of p)O.length>0&&c.push(` ${w}: ${hn(O)}`);let h=r.personalAsIs??[],g=h.reduce((w,{fields:O})=>w+O.length,0);c.push(g>0?` personal data: ${g} field(s) of ${h.length} object(s) copied as ${o} holds them: `+hn(h.map(({objectApiName:w,fields:O})=>`${w} (${O.join(", ")})`)):" personal data: no personal field copied as it is");let m=r.managedPackages??[];return m.length>0&&c.push(` managed packages: ${m.length} object(s) written, whose triggers and flows no mute reaches: ${hn(m)}`),r.contactPointsBlanked!==void 0&&c.push(` phone numbers: up to ${r.contactPointsBlanked} past the fictional range go in empty`),c}function NR(r,e,t){return`discovery: ${r.source} API request(s) sent to ${e} and ${r.target} to ${t}, before any row is read`}function hr(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 mm(r){return`Write ${r}?`}function wm(r,e,t,n){let{source:o,bulk:s}=r,i=e.objects.filter(({rows:g})=>g>0).length,a=r.managedPackages??[],d=r.personalAsIs??[],c=d.reduce((g,{fields:m})=>g+m.length,0),u=r.sample,l=u?.roots?Gm(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 ${qt(u.storageMB)} MB`+(Oc(n.budget)?` of the ${qt(u.budgetMB)} MB it may take`:"")+(u.automationMB!==void 0?`, ${qt(u.automationMB)} MB of it for what the target's automation creates`:"")+`; ${[kc(u),...l].join("; ")}, ${ii(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 (${hn(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 ym(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 MR=[[/--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 ro(r){return Kt()?MR.reduce((e,[t,n])=>e.replace(t,n),r):r}function BR(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 LR(r,e,t=!1,n=!1){return!jt("--max-total")&&ks()?Tc(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 _m(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}: ${it("--query")} "${Jl(e,n,o)}" clones ${d}, its dry run first, or narrow its WHERE`}function qm(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 WR(r,e,t,n=!1){if(ks())return Tc(r,e,n);let o=_m(t),s=`leave objects out (${it("--exclude-object")}) or narrow them (${it("--filter")})`;return`The run would write ${r} records, more than the ${e} ${it("--max-total")} holds it to: `+(o!==void 0?`${o}; or ${s}, or raise ${it("--max-total")}.`:`${qm(t)}: ${s}, clone less deep (${it("--depth")} direct), or raise ${it("--max-total")}.`)}function DR(r,e,t){if(r.verdict!=="exceeds")return;let n=_m(t),o=`leave objects out (${it("--exclude-object")})`;return`The records to write take ${Ea(r)}, and ${e} has ${r.remainingMB} MB left of ${r.maxMB} MB${va(fs(r),e)}: `+(n!==void 0?`${n}; or ${o}, or free data storage in ${e}.`:`${qm(t)}: ${o}, clone less deep (${it("--depth")} direct), or free data storage in ${e}.`)}function bm(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:Vl(n.count,t.taken,t.room),each:t.each(t.taken/n.count),past:t.past}}function _R(r,e){if(r.verdict==="exceeds")return`The records to write take ${Ea(r)}, and ${e} has ${r.remainingMB} MB left of ${r.maxMB} MB${va(fs(r),e)}: 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 qR=2*1024;function UR(r){let{storage:e,sample:t,target:n}=r,{withinMB:o}=t.options,s=t.options.maxTotal??qn,i=Xf({storage:e,bounds:uc(t),target:n});if(i)throw Pe.of(i);let a=r.automation?{automation:r.automation}:{},d=r.allowances?{allowances:r.allowances}:{},c=od({storage:e,...o!==void 0?{withinMB:o}:{},...a,...d});if(c)return{...c,budget:{...c.budget,maxTotal:s}};let u=od({storage:{maxMB:0,remainingMB:0},...a,...d});return{budget:{bytes:Number.MAX_SAFE_INTEGER,maxTotal:s,limitedBy:"maxTotal"},bytesLimit:"within",roomBytes:s*qR,...u?.automationBytes?{automationBytes:u.automationBytes}:{},...u?.requests?{requests:u.requests}:{}}}function uc(r){let{withinMB:e}=r.options;return{...e!==void 0?{withinMB:e}:{},...r.maxTotalGiven?{maxTotal:r.options.maxTotal??qn}:{}}}function Oc(r){return r.remainingMB!==void 0||r.withinMB!==void 0}function ii(r){return String(Number((r*100).toPrecision(2)))}function kc(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 Um(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 Gm(r){return[...r.window?[Um(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 GR(r){return(r??[]).map(({objectApiName:e,field:t,values:n,more:o})=>({objectApiName:e,field:t,values:n.length+(o??0)}))}function zm(r){return r?.window!==void 0||(r?.where??[]).length>0}function zR(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??qn}`;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 ro("limited by the draw: every root --fit-window and --fit-where leave is in the sample; widen them to take more")}}function HR(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 KR(r,e){let{budget:t}=r,n=`about ${qt(r.storageBytes/1048576)} MB`;if(!Oc(t))return`${n}, held to ${t.maxTotal??qn} records (--max-total): ${e} would not say its data storage`;let o=`${n} of the ${qt(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=[`${ii(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.uncountedMB!==void 0&&t.uncountedMB>0?[`${qt(t.uncountedMB)} MB off for what runs from this machine wrote to it that Salesforce has not counted yet`]:[],...t.automationMB!==void 0&&t.automationMB>0?[`${qt(t.automationMB)} MB for what its automation creates`]:[],...t.withinMB!==void 0?[`--fit-within ${t.withinMB}`]:[]];return`${o} (${s.join(", ")})`}var Hm={referenceData:"reference data, matched by name",catalog:"the price catalog",smallParent:"a small parent",asked:"--fit-whole"};function VR(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 JR(r,e){if(r.whole){let t=e.find(n=>n.objectApiName===r.objectApiName)?.why;return`copied whole${t?` (${Hm[t]})`:""}`}return`${r.roots} drawn, ${r.below} under a parent, ${r.asParents} as parents`}function QR(r){return r.label!==void 0?r.label:r.value===null?"(no value)":String(r.value)}function YR(r,e){let t=r.roots;if(!t)return[];let n=[];if(zm(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=>`${QR(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 XR(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?Gm({...r.roots,strata:GR(r.roots.strata)}):[],i=[`sample: ${r.rows} of ${o} record(s) of ${t}, of ${r.objects.length} object(s): ${ii(r.share)} % of the roots ${zm(r.roots)?"in the draw ":""}of each object (${[kc(r),...s].join("; ")}), with the records they reach and name; ${KR(r,n)}; ${zR(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} (${JR(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=>`; ${HR(f)}`).join(""))}if(i.push(...YR(r,t)),r.whole.length>0&&i.push(`whole: ${r.whole.map(({objectApiName:c,why:u})=>`${c} (${Hm[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}, ${VR(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 Rm(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:Oc(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 ZR(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 eO(r,e){let t=r.roots,n=t?[...t.window?[Um(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 (${[kc(r),...n].join("; ")}, ${ii(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 tO(r,e,t){let n=e.draw??Tn.draw,o=e.maxTotal??qn,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/nO)}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 ro(`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 nO=2e3,rO={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 oO(r){let e;return t=>{t.step!==e&&(e=t.step,r(`sampling: ${rO[t.step]}\u2026 (${t.requests} request(s) so far)`))}}var sO=new Set([Yf,gs,"SAMPLE_DRAW_INVALID","ROOTS_QUERY_REFUSED","ROOTS_PLAN_MISMATCH","ROOTS_PLAN_GONE"]);function Om(r){return sO.has(r)?2:1}function iO(r){let e=0,t=0,n=0,o=0;for(let s of r.nodes)s.included?e++:jr(s)?t++:s.status==="error"||s.errors.length>0?n++:o++;return{included:e,emptyTables:t,notCounted:n,leftOut:o}}function Km(r){let e=[],t=[];for(let n of r.nodes)n.included&&n.recordCountUnknown===!0?t.push(n.objectApiName):!n.included&&!jr(n)&&(n.status==="error"||n.errors.length>0)&&e.push(n.objectApiName);return{refused:e,unanswered:t}}function zs(r,e){let{refused:t,unanswered:n}=Km(r);return{nodes:r.nodes.length,...iO(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 aO(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 km(r,e,t,n,o={}){let s=dO(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:As(r.anonymize,e,r.anonymizationRules,n,r.anonymizationMode),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 dO(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 cO(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??$r,a;try{a=await e(es(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?qr(o,i,"query",s):d.length===0?ns(o,s,i):void 0;return c?{refused:{code:c.code,message:c.message}}:{chosen:{ids:d,readAt:new Date().toISOString()}}}function uO(r,e){return e?{...r,stream:{...r.stream,store:e,summaryBound:ah}}:r}function lO(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 ai(r){return new If({query:async(e,t)=>_n({query:async n=>r.query(n),queryMore:async n=>r.queryMore(n)},t),toolingQuery:async(e,t)=>_n({query:async n=>r.tooling.query(n),queryMore:async n=>r.tooling.queryMore(n)},t),toolingQueries:async(e,t)=>Ef(await r.request({method:"POST",url:"/tooling/composite",body:JSON.stringify(vf(`/services/data/v${r.version}`,t)),headers:{"Content-Type":"application/json"}}),t.length),toolingRetrieves:(e,t)=>Sa(r)(t)})}function fO(r,e,t){let n=o=>{let s=r.get(o);if(!s)throw new Error(`No connection for ${o}`);return s};return new jf({query:async(o,s)=>_n({query:async i=>n(o).query(i),queryMore:async i=>n(o).queryMore(i)},s),toolingQuery:async(o,s)=>_n({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(Oa)}},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)=>Af(n(o))(s),toolingRetrieves:(o,s)=>Sa(n(o))(s)})}async function fn(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 oo(r,e,t){if(e.sandbox||Yc(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 pO={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 hO(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 gO(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 h=go(a,t.lifted);if(h){i.push(` refused ${a.objectApiName}${c}: ${d}, ${a.rows} row(s)${p}, validation rule "${String(a.detail?.rule)}": the mute lifts it (${h.permission}, in ${h.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), ${pO[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 mO(r,e){return{...r,gaps:r.gaps.map(t=>{let n=go(t,e);return n?{...t,detail:{...t.detail,liftedByPermission:n.permission,liftedByPermissionSet:n.permissionSet}}:t})}}var wO=new Set(["--remove","--target","--preview","--include-changed","--json","--accept-automation","--leave-undeletable","--sweep","--sweep-list","--sweep-late","--sweep-untied","--audit","--mute-automation","--sweep-user"]),yO=new Set(["--remove","--target","--audit","--sweep-user"]);function bO(r){let e=r.slice(2);(e.includes("-h")||e.includes("--help"))&&(process.stdout.write(bc),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(yO.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.
851
+ `),process.exit(2)),wO.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.
852
+ `),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.
853
+ `),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.
854
+ `),process.exit(2));let i=["--sweep-list",...n("--sweep")?[]:rw,"--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.
855
+ `),process.exit(2));let a=DO(e);"refusal"in a&&(process.stderr.write(`${a.refusal} Run with --help for usage.
856
+ `),process.exit(2));let d=RO(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:Rc(e),...n("--preview")?{preview:!0}:{},...d!==void 0?{sweepUser:d}:{}}}function RO(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.
857
+ `),process.exit(2)),(r===void 0||!mr.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.
858
+ `),process.exit(2)),r}function lc(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 ft=M.string().regex(mr,"not a Salesforce id"),Ks=M.iso.datetime(),Sm=M.object({objectApiName:M.string().regex(nt,"not an API name"),kind:M.enum(["flow","trigger","process","workflowRule"]),name:M.string().max(255)}),OO=M.object({silenced:M.array(Sm.extend({permission:M.string().max(255)})),stillRan:M.array(Sm.extend({why:M.enum(["noBypass","managedPackage","notRead","noPermissionSet"])}))});function Fj(...r){for(let e of r)if(typeof e=="string"&&mr.test(e))return e}var Vm=M.object({tool:M.literal("sandforge-clone"),version:M.literal(1),source:M.string(),target:M.string().min(1),targetOrgId:ft.optional(),record:M.string().optional(),objects:M.array(M.object({objectApiName:M.string().regex(nt,"not an API name"),where:M.string().max(512).optional()})).max(2e3).optional(),wholeOrg:M.literal(!0).optional(),roots:M.object({objectApiName:M.string().regex(nt,"not an API name"),from:M.enum(["query","records"])}).optional().catch(void 0),dryRun:M.literal(!1),elapsedMs:M.number().transform(r=>Math.max(0,r)),finishedAt:Ks.optional(),journal:M.string().min(1).max(4096).optional(),part:M.number().int().nonnegative().optional(),result:M.object({remapInJournal:M.literal(!0).optional(),roots:M.object({read:M.number().int().nonnegative()}).optional().catch(void 0),remapTable:M.record(ft,ft),existingSourceIds:M.array(ft),updatedSourceIds:M.array(ft),createdByObject:M.array(M.object({objectApiName:M.string().regex(nt,"not an API name"),sourceIds:M.array(ft)})),withTheirRecordSourceIds:M.array(ft).optional(),unattributed:M.array(M.object({objectApiName:M.string().regex(nt,"not an API name"),ids:M.array(ft)})).optional(),writtenBetween:M.object({first:Ks,last:Ks}).optional(),mayHaveBeenWritten:M.array(M.object({objectApiName:M.string().regex(nt,"not an API name"),sourceIds:M.array(ft)})).optional(),runUserId:ft.optional()}),mutedAutomation:OO.optional().catch(void 0)});async function fc(r,e,t,n=Nt(At())){let o=e.indexOf(`
859
+ `),s=o>=0?e.slice(0,o):e;if(/^\{"run":/.test(s))return kO(r,t,n);let i=SO(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. "+Tm(t,u)}:{refusal:`keeps the ids of its records in ${a}, which cannot be read. `+Tm(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 Tm(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: ${Gt("checkpoint")} list --org ${r} names them, ${Gt("checkpoint")} rewind --org ${r} --checkpoint <id> rewinds to one. Without one, ${Gt("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 kO(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??Fm(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(g=>g.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(g=>g.included).map(({objectApiName:g})=>{let m=a.config.objectSoqlFilters?.[g];return m!==void 0?{objectApiName:g,where:m}:{objectApiName:g}}):void 0,h=Vm.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 h.success?{summary:h.data}:{refusal:`is a journal the command cannot take a run back from: ${h.error.issues.slice(0,5).map(m=>`${m.path.map(String).join(".")||"the journal"}: ${m.message}`).join("; ")}.`}}function SO(r){let e;try{e=JSON.parse(r)}catch(a){return{refusal:`is not JSON (${a instanceof Error?a.message:String(a)}).`}}let n=M.object({tool:M.literal("sandforge-clone"),dryRun:M.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=Fi(e,"sandforge-clone");if(o)return{refusal:Ci(o)};if(!M.object({result:M.object({createdByObject:M.array(M.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=Vm.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 Sc(r){let{result:e}=r,t=Zc({idRemapTable:e.remapTable,idRemapExisting:[...e.existingSourceIds,...e.updatedSourceIds],idRemapCreated:e.createdByObject});return dh(t,e.unattributed)}function Jm(r){return`${Qm(r)} record(s) the target already held, which the run linked to or wrote over, stay`}function Qm(r){return eu({idRemapTable:r.result.remapTable,idRemapExisting:r.result.existingSourceIds,idRemapCreated:r.result.createdByObject,idRemapWithTheirRecord:r.result.withTheirRecordSourceIds}).length+r.result.updatedSourceIds.length}function TO(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 ${Tb(Sb(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}`),...jO(e),Jm(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 (${it("--include-changed","removal")} takes them)`]}function AO(r){return r.flatMap(({part:e,plan:t})=>[`then the ${zn(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 jO(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 Ym(r){let e=r.platformCopies??0;if(e<=0)return"";let t=r.planned-e;return r.objectApiName===zo?` (${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 $O(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 vO(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 EO(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 IO(r,e,t=0){let n=[...new Set(e.flatMap(o=>o.unchecked))];return[`removal: ${r.toUpperCase()}`,...e.flatMap(o=>[` ${o.objectApiName}: ${vO(o)||"nothing"} of ${o.planned}${Ym(o)}`,...$O(o),...o.reasons.map(s=>` ${s}`),...o.filesLeft&&o.filesLeft.count>0?[` ${EO(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 Xm(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 Zm(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 Am=10;function Tc(r,e,t=!1){return jt("--max-total")?`The run would write ${r} records, more than --max-total ${e}: narrow the clone (--max, --exclude-object, --filter), or raise --max-total.`:ks()?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} ${it("--max-total")} holds it to: narrow the clone with this script's own --max, --exclude-object or --filter, or raise its --max-total.`}function pn(r){return jt(r)?r:`this script's own removal with ${r==="--sweep-list"||r==="--sweep"?"":"--sweep "}${r}`}function pc(r){let e=Qa();return e===void 0?`${r} takes them`:`${e} keeps them; ${pn(r)} takes them`}function ei(r){let e=r.length-Am;return`${r.slice(0,Am).join(", ")}${e>0?` and ${e} more`:""}`}function Jn(r){return r.map(e=>`${e.objectApiName}: ${e.count}`).join(", ")}function xO(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 to(r,e,t){return r[e]-(t.includeChanged===!0?0:r.changedIn?.[e]??0)}function PO(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+to(s,"made",e)+to(s,"madeOver",e)+(e.sweepLate===!0?to(s,"late",e):0)+(t?to(s,"untied",e):0):n},0)}function jm(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,to(s,e,n)):o.count;return i>0?[{objectApiName:o.objectApiName,count:i}]:[]})}function FO(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: ${Jn(o)} (${pc("--sweep-late")})`);else if(t&&e.sweepLate===!0){let i=jm(r,"late",o,e);n.push("of what it would delete, made late, which --sweep-late takes: "+(i.length>0?Jn(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: ${Jn(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: ${Jn(s.objects)} (${pc("--sweep-untied")})`);else if(t){let i=jm(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?Jn(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 ${ud} objects a sweep counts: `+ei(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: ${ei(a.map(d=>`${d.name} (${d.objectApiName})`))}`:"nothing of what the run fired still ran"))}return t&&n.push(...CO(r,e)),n}function CO(r,e){let t=s=>r.found.some(i=>!i.overBound&&(i.classes?.[s]??0)>0),n=t("made")||t("madeOver"),o=[n?ew:"",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?[]:[`${tw(`${o.join(", or ")}${o.length>1?",":""}`)}: check the names before a --sweep`]}var ew="under the run's records within a minute of them";function tw(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 Vs(r,e,t,n=t===void 0){let o=PO(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: ${ei(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 ${xO(a.classes,t??{})}`:"")+(a.names.length>0?` (${a.names.join(", ")}${a.count>a.names.length?", \u2026":""})`:""))]:r.window?["it finds nothing to delete"]:[],...FO(r,t??{},n),...Xm(r),...Zm(r),...r.refusal?[`sweep refused: ${r.refusal}`]:[]]}function NO(r,e){let t=r?.listing;return e===void 0&&t?.refusal===void 0?t:void 0}function sc(r,e){let t=r.reduce((g,m)=>g+(m.heldByAutomation??0),0);if(t===0)return[];let n=Math.min(t,r.reduce((g,m)=>g+(m.heldByAutomationAfterRun??0),0)),o=Math.min(t,r.reduce((g,m)=>g+(m.heldByAutomationAlong??0),0)),s=MO(t,o),i=[...new Set(r.flatMap(g=>g.automationHolders??[]))],a=i.length>0?` (${ei(i)})`:"",d=`likely by the target's automation${a}`,c=`delete them by hand, then remove the run again; ${it("--preview","removal")} says what of it their delete leaves changed since, which ${it("--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}`),h=tw(ew);if(e.part!==void 0){let g=m=>`${Qa()===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; ")+`${g("--sweep")} ${s} (${g("--sweep-list")} shows them; ${h}: check the names before it), or ${c}`]}return[e.sweep===!0?`${p}: the sweep left them \u2014 ${pn("--sweep-list")} says why; ${pn("--sweep-late")} takes those it lists as late, ${it("--include-changed","removal")} those changed after the run's last write`:`${p}: ${pn("--sweep")} ${s} (${pn("--sweep-list")} shows them); ${h}: check the names before `+(jt("--sweep")?"a --sweep":pn("--sweep"))]}function MO(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 nw={late:"made late",untied:"tied to nothing of the run"};function BO(r){return r.map(({class:e,objects:t,option:n,refusal:o})=>{let s=` left, ${nw[e]}: ${Jn(t)}`;return o!==void 0?`${s} \u2014 ${n} is refused: ${o}`:`${s} (${pc(n)})`})}function LO(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}`)]}),...BO(r.left??[]),...(r.goneAlong??[]).map(({class:e,objects:t})=>` ${nw[e]}, no longer in the org once the records of the run were gone: ${Jn(t)}`),...Xm(r),...Zm(r),...r.refusal?[` ${r.refusal}`]:[]]}function WO(r){return di(r).flatMap(e=>[...zn(e.created),...e.linked])}function di(r){let e=r?.part;return e===void 0?[]:(r?.parts??[]).filter(t=>t.part!==e)}function Js(r,e){let t=new Set(r?.earlier?.partsRemoved??[]);return di(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=zn(dn(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 hc(r,e,t,n,o,{signal:s,ofTheRun:i,user:a}={}){let d;try{d=await ai(r).read(e,n.map(l=>l.objectApiName))}catch(l){d={error:Q(l)}}let c=t.result.runUserId??a,u=di(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),...WO(i)].map(l=>l.slice(0,15))),...u.length>0?{otherParts:u}:{},automation:$h(d),...c?{runUserId:c}:{},ties:o,...s?{signal:s}:{}}}var rw=["--sweep-late","--sweep-untied"];function DO(r){let e=rw.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 _O(r){return{...r.sweepLate?{sweepLate:!0}:{},...r.sweepUntied?{sweepUntied:!0}:{}}}function qO(r){return r?{sweep:e=>r.first(e),automationMade:r.automationMade,afterRemoval:e=>r.afterRemoval(e)}:{}}function gc(r,e,t){let n=nr(r,e),o=Object.create(n);return o.counts=vh(Bl(Ml(r),t)),o}function Cj(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 ic(r,e){return r!==void 0&&r.length>=15&&r.slice(0,15)===e.slice(0,15)}async function UO(r){let e=r.journalDir??At(),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+jh&&u>=r.span.from-Ah,o=[],s=c=>{c.length===0||c.some(u=>t.has(u.slice(0,15)))||o.push({ids:[...c]})},i=Ys(e,"forge-runs"),a=[];try{a=rb(i).filter(c=>c.endsWith(".ndjson"))}catch{}let d=Nt(e);for(let c of a){let u=Ys(i,c);if(!(r.own.journal!==void 0&&Ut(r.own.journal)===Ut(u)))try{let l=await d.headAt(u);if(!l||!ic(l.targetOrgId,r.organizationId))continue;let f=await d.lastEndAt(u),p=Date.parse(f?.at??"")||Fm(u).mtimeMs;if(!n(Date.parse(l.startedAt),p))continue;let h=await d.readAt(u,"all");s(h?.created.flatMap(g=>g.ids)??[])}catch{}}for(let c of r.own.otherParts??[])n(c.from,c.to)&&s(c.ids);for(let c of[ia(e),ia(e,Ch)]){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||!(ic(l.targetOrganizationId,r.organizationId)||l.targetOrganizationId===void 0&&(ic(l.targetOrgId,r.organizationId)||r.alias!==void 0&&l.targetOrgId===r.alias)))continue;let p=Date.parse(l.firstWrittenAt??l.startedAt),h=l.end?Date.parse(l.end.at):Date.parse(l.lastWriteAt??l.lastWrittenAt??"")||Date.now();n(p,h)&&s([...l.created,...l.overwritten??[]].flatMap(g=>g.ids))}}return o}function GO(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 ow(r,e,t,n,o,s){let i=Date.parse(t.finishedAt??""),a=di(s).map(d=>({ids:zn(d.created),from:Date.parse(d.startedAt??""),to:Date.parse(d.endedAt??"")}));return GO({otherRuns:await UO({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 $m=3;function ci(r){return/\.json$/i.test(r)?r.replace(/\.json$/i,".removals.json"):`${r}.removals.json`}function ui(r){let e=r.flatMap(t=>t.ids.map(n=>n.slice(0,15))).sort();return nb("sha256").update(e.join(",")).digest("hex")}var ac=M.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"),zO=M.object({tool:M.literal("sandforge-clone"),version:M.literal(1),run:M.string(),removalStamps:M.record(ft,ac),removalSpans:M.array(M.object({first:ac,last:ac,userId:ft})),removalLeft:M.array(ft).optional(),sweep:M.object({sweptAt:Ks,deleted:M.number().int().nonnegative(),keptChanged:M.number().int().nonnegative(),refused:M.number().int().nonnegative()}).optional(),made:M.array(ft).max(1e4*100).optional(),late:M.array(ft).max(1e4*100).optional(),partsRemoved:M.array(M.number().int().nonnegative()).max(1e4).optional()});function li(r,e){if(r===void 0)return{};let t;try{t=JSON.parse(r)}catch{}let n=M.object({tool:M.literal("sandforge-clone"),run:M.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=zO.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 HO(r,e,t,n=[],o,s=[],i=[],a=[]){let d=new Set(t.gone??[]),c=[...a],u=ra(e?.made,s,c),l=ra(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,h=d.size>0?n.flatMap(({ids:g})=>g.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]:[]],...h?{removalLeft:h}:{},...p?{sweep:p}:{},...u.length>0?{made:u}:{},...l.length>0?{late:l}:{},...e?.partsRemoved?{partsRemoved:e.partsRemoved}:{}}}async function sw(r,e=Nt(At())){let t=r.journal;if(t===void 0||!Yt(t))return;let n=await Hh(t,e),o=n.length>1?await e.readAt(t,"all"):void 0;if(!o)return;let s=ci(t),i;try{i=gn(s,"utf8")}catch(c){if(c?.code!=="ENOENT")return{refusal:`${s} cannot be read: ${c instanceof Error?c.message:String(c)}`}}let a=ui(o.created),d=li(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 iw(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=dn(t.created,r.earlier?.removalLeft);return n.length>0?[{part:t,plan:n}]:[]})}function aw(r,e){if(!(r.parts.length<2))return[...r.parts].sort((t,n)=>n.part-t.part).flatMap(t=>{let n=dn(e,zn(t.created));return n.length>0?[{part:t,plan:n}]:[]})}function KO(r,e){let t=[...new Set(e.flatMap(s=>s.keptDependents>0?s.heldBy:[]))],n=new Set(r.earlier?.partsRemoved??[]),o=s=>dn(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(Ho(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 vm(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 dw(r,e,t){return r.parts.flatMap(n=>{if(n.part===e)return[];let o=dn(n.created,r.earlier?.removalLeft),s=Gn(n);if(o.length===0||!s)return[];let i=ur(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 cw(r){return r?.part===void 0?[]:[...new Set(r.parts.flatMap(e=>e.part===r.part?[]:dn(e.created,r.earlier?.removalLeft).map(t=>t.objectApiName)))]}function VO(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??zn(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:Wr(t?.removalSpans,e.spans),removalLeft:s,...t?.sweep?{sweep:t.sweep}:{},...t?.made?{made:t.made}:{},...t?.late?{late:t.late}:{},partsRemoved:n}}function JO(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 uw(r,e){return e?{...r,removalStamps:{...r?.removalStamps,...e.removalStamps},removalSpans:Wr(r?.removalSpans,e.removalSpans)}:r}function mc(r,e,t=!1){let n=`${r}.${process.pid}.tmp`;try{Cm(n,JSON.stringify(e,null,2)+`
860
+ `,{encoding:"utf8",...t?{mode:zi}:{}}),t&&Au(n,zi),Pm(n,r);return}catch(o){try{Hs(n,{force:!0})}catch{}return o instanceof Error?o.message:String(o)}}async function QO(r=process.argv){let e={};try{await YO(r,e)}finally{e.lock?.release()}}async function YO(r,e){let t=Date.now(),n=bO(r),o=C=>n.json?console.error(C):console.log(C),s;try{s=gn(n.summaryPath,"utf8")}catch(C){process.stderr.write(`--remove ${n.summaryPath} cannot be read: ${C instanceof Error?C.message:String(C)}
861
+ `),process.exit(2)}let i=await fc(n.summaryPath,s,n.target);"refusal"in i&&(process.stderr.write(`--remove ${n.summaryPath} ${i.refusal}
862
+ `),process.exit(2));let a=C=>({code:xi,message:`${fd(C)}. A removal now would delete under it what it goes on writing: ${pd(C)}, then remove it. Nothing was read or deleted.`}),d=i.summary.journal;if(n.preview){let C=d!==void 0?Bh(d):void 0;return C&&bt(a(C)),tk(n,i.summary,o,t)}if(d!==void 0){let C=Is(d,{journalId:yc(d).replace(/\.ndjson$/,""),ranFrom:"commandLine",target:n.target,removes:!0});"busy"in C&&bt(a(C.busy)),e.lock=C.lock}let c,u=async()=>{if(!c){let C=await Bn(n.target),Z=An(C);c={session:C,conn:Z,org:await fn(Z)}}return c},l=i.summary.journal;if(l!==void 0&&Yt(l)&&Nt(At()).callsInFlightAt(l)>0){let{conn:C,org:Z}=await u();i.summary.targetOrgId!==void 0&&!ni(i.summary.targetOrgId,Z.id)&&bt(at(i.summary.targetOrgId));let se=await Nt(At()).reconcileAt(l,$s(C));for(let be of vs(se,n.target,"removal"))o(be);let Ie=(se.underway??[]).reduce((be,{rows:ct})=>be+ct,0),V=ih(se)-Ie;V>0&&o(` the journal names none of the ${V} row(s) that may be in ${n.target}: they stay, and ${pn("--sweep-list")} shows what the run's user created in the run's window`),i=await fc(n.summaryPath,gn(n.summaryPath,"utf8"),n.target),"refusal"in i&&(process.stderr.write(`--remove ${n.summaryPath} ${i.refusal}
863
+ `),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}.
864
+ `),process.exit(2));let p=(f.result.mayHaveBeenWritten??[]).reduce((C,{sourceIds:Z})=>C+Z.length,0),h=0,g,m,w,O=[],S=!1,R=!1,b,T=C=>{let Z={sweep:n.sweep,windowUntold:S,inParts:R};return b?[...sc(b.own,Z),...b.others.flatMap(({part:se,objects:Ie})=>sc(Ie,{...Z,part:se}))]:sc(C,Z)},k=(C,Z,se,Ie,V)=>{if(n.json){process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"remove",summary:n.summaryPath,target:n.target,...se?{targetOrgId:se}:{},includeChanged:n.includeChanged,result:{status:C,planned:Z.reduce((be,ct)=>be+ct.planned,0),objects:Z,...p>0?{mayHaveBeenWritten:p}:{},...h>0?{removedEarlier:h}:{},...V?{sweep:V}:{},...g?{sweepListing:g}:{},...Em(f,n)!==void 0?{wholeOrgNotSwept:!0}:{},...m?{mutedAutomation:m}:{},...O.length>0?{heldByOtherParts:O}:{}},...Ie?{removalsFile:Ie}:{},elapsedMs:Fe(t)},null,2)+`
865
+ `);for(let be of T(Z))console.error(be);for(let be of vm(O))console.error(be);return}if(Z.length>0||!V)for(let be of IO(C,Z,p))console.log(be);if(V)for(let be of LO(V))console.log(be);for(let be of T(Z))console.log(be);for(let be of vm(O))console.log(be);Ie&&console.log(`what this removal left on the run's records is kept in ${Ie}, which the next --remove of this summary reads`),console.log(`
866
+ done in ${Fe(t)}ms`)},v=Sc(f);if(v.length===0){o("The run created no record: there is nothing of it to remove."),k("success",[]);return}let $=ui(v),E=ci(n.summaryPath),B;try{B=gn(E,"utf8")}catch(C){C?.code!=="ENOENT"&&(process.stderr.write(`${E} cannot be read: ${C instanceof Error?C.message:String(C)}
867
+ `),process.exit(2))}let I=li(B,$);"refusal"in I&&(process.stderr.write(`${E} ${I.refusal}
868
+ `),process.exit(2));let{otherRun:G,earlier:re}=I,z=await sw(f);z&&"refusal"in z&&(process.stderr.write(`${z.refusal}
869
+ `),process.exit(2)),R=z!==void 0;let _=z&&Ut(E)!==Ut(z.file)?z:void 0,ee=uw(re,_?.earlier);o(`sandforge clone --remove ${n.summaryPath} from ${n.target}`);let ve=Em(f,n);ve!==void 0&&o(ve);let he=bo({objects:v,removalLeft:re?.removalLeft}),de=dn(he,_?.earlier?.removalLeft),K=C=>C.reduce((Z,se)=>Z+se.ids.length,0);h=K(v)-K(de),K(v)>K(he)&&o(`${K(v)-K(he)} record(s) removed by an earlier --remove of this summary`),K(he)>K(de)&&o(`${K(he)-K(de)} record(s) removed by an earlier --remove of the run's other part or of its journal`);let ne=_?iw(_):[],fe=z&&!("refusal"in z)&&!_?z:void 0,Ae=fe?aw(fe,de):void 0,me=n.includeChanged&&f.result.runUserId!==void 0;if(de.length===0&&ne.length===0&&!n.sweep&&!n.sweepList&&!me){o("nothing left of the run to remove"),k("success",[]);return}let{session:ce,conn:W,org:J}=await u(),we=new Map([[J.id,{alias:n.target,username:ce.username}]]),Y=`sandforge-clone-${Qs()}`,Ce,Oe=C=>Zs(n.audit,we,{action:"cleanup_delete",module:"forge",operationId:Y,orgId:J.id,...C,...m?{muted:Ro(m)}:{}}),Ne=n.sweepList?void 0:oo(n.target,J,"remove");Ne&&pt({code:"PRODUCTION_TARGET",message:Ne}),f.targetOrgId!==void 0&&!ni(f.targetOrgId,J.id)&&bt(at(f.targetOrgId));let Ke=f.result.writtenBetween===void 0?f:void 0;f=await ti(W,f);let q=()=>ow(J.id,n.target,f,v,ee,_);if(n.sweepList){let C=await ld(gc(W,"sandforge clone --sweep-list"),await hc(W,n.target,f,v,await q(),{ofTheRun:_,...n.sweepUser!==void 0?{user:n.sweepUser}:{}}),ee?.removalSpans??[]);for(let se of Vs(C,n.target,n,!0))o(se);let Z=lc(C.refusal,{kept:f.result.runUserId!==void 0,given:n.sweepUser!==void 0,target:n.target});Z!==void 0&&o(Z);for(let se of Js(_,C))o(se);n.json?process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"sweep-list",summary:n.summaryPath,target:n.target,targetOrgId:J.id,listing:C,elapsedMs:Fe(t)},null,2)+`
870
+ `):console.log(`
871
+ done in ${Fe(t)}ms`),C.refusal!==void 0&&process.exit($m);return}let P=f.result.runUserId,D=new AbortController,X=()=>D.abort(),H=de.length>0||ne.length>0||me;de.length>0||ne.length>0?It():o(me?"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 je=n.sweep?Eh(gc(W,"sandforge clone --sweep",D.signal),await hc(W,n.target,f,v,await q(),{signal:D.signal,ofTheRun:_,...n.sweepUser!==void 0?{user:n.sweepUser}:{}}),{includeChanged:n.includeChanged,removalSpans:ee?.removalSpans??[],..._O(n),approve:async C=>{g=C,o("");for(let se of Vs(C,n.target,n))o(se);let Z=lc(C.refusal,{kept:f.result.runUserId!==void 0,given:n.sweepUser!==void 0,target:n.target});Z!==void 0&&o(Z);for(let se of Js(_,C))o(se)}}):void 0;if(je){let C=tr(X);try{await je.ask()}finally{C()}let Z=NO(je,g);if(Z){g=Z,o("");for(let se of Vs(Z,n.target,n))o(se);for(let se of Js(_,Z))o(se)}}let U=je?.takes??[];(H||U.length>0)&&!D.signal.aborted&&await Qn(U);let oe,ge=[];if(H)oe=await De(),oe.stoppedForUndeletable&&(w&&pt(w),process.exit(1));else if(je){let C=await Rt(),Z=tr(X);try{await je.first(),await je.afterRemoval()}finally{if(Z(),C){m=await C.release();for(let se of rr(m,n.target))o(se)}}}let ue=je?.result();ue&&Zs(n.audit,we,{action:"cleanup_delete",module:"forge",operationId:`${Y}-sweep`,orgId:J.id,outcome:ue.status==="refused"?"stopped":ue.status,...ue.status==="refused"?{code:"SWEEP_REFUSED"}:{},objects:xh(ue),details:Ph(ue,$),...!H&&m?{muted:Ro(m)}:{}});function It(){for(let C of TO(f,de,n))o(C);for(let C of AO(ne))o(C);re?o(`what earlier removals of this summary left on the run's records, read from ${E}, is not a change since the run`):G&&o(`${E} is of another run: it is not read, and what this removal leaves on the records, if anything, takes its place`),_?.earlier&&o(`what the removals of the run's other part or of its journal left on its records, read from ${_.file}, is no change since the run`)}function pt(C){return Oe({outcome:"stopped",code:C.code}),bt(C)}function bt(C){return process.stderr.write(`${Tt(C)}
872
+ `),n.json&&process.stdout.write(So({tool:"sandforge-clone",summary:n.summaryPath,target:n.target,elapsedMs:Fe(t)},C)),process.exit(1)}function at(C){return{code:ko,message:`${n.target} is not the org the run wrote to (${C}), and its records are removed from that org only. Nothing was deleted.`}}async function Qn(C){let Z=[...new Set([...de,...ne.flatMap(_e=>_e.plan)].map(_e=>_e.objectApiName))],se=[...new Set([...Ho(Z,cw(_),{userKept:P!==void 0}),...Z.length===0&&me?[zo]:[],...C])],Ie=na(Z),V=await ai(W).read(n.target,se);o("");for(let _e of _a(V,n.target,se.length,Ie))o(_e);if(n.muteAutomation){let _e=new Set(Ie);try{Ce=await ca(async()=>aa(W),V,{writes:(Ye,Ge)=>Ge==="delete"||Ge==="update"&&_e.has(Ye)}),m=Ce.muted;for(let Ye of rr(Ce.muted,n.target))o(` ${Ye}`)}catch(Ye){if(!Dr(Ye))throw Ye;pt(Ye.refusal)}}let be=Ce?.automation??V,ct=Da(be,n.target,{drafted:Ie,assign:ws(be,Ei(be,Ie)),mayMute:Ce===void 0&&jt("--mute-automation")});ct&&!n.acceptAutomation&&pt({code:"AUTOMATION_NOT_ACCEPTED",message:ct})}async function Rt(){let C=Ce?.prepared&&!D.signal.aborted?await Ce.prepared.acquire(`sandforge clone --remove ${Y}`).catch(Z=>{if(!Dr(Z))throw Z;return pt(Z.refusal)}):void 0;return C&&(m=C.outcome),C}async function De(){let C,Z=tr(X),se=f.result.writtenBetween,Ie=se?{runStartedAt:new Date(se.first),runEndedAt:new Date(se.last)}:{runDurationMs:f.elapsedMs,...f.finishedAt?{runRecordedAt:new Date(f.finishedAt)}:{}},V=bl,be=[],ct=em(n.leaveUndeletable,n.target,Xe=>{w=Xe}),[_e,...Ye]=Ae??[],Ge=_??(_e?fe:void 0),kt=_?.part??_e?.part.part,Me=Ge&&kt!==void 0?dw(Ge,kt,ee?.removalStamps??{}):[],St=Ge&&kt!==void 0?ur(Ge.parts,kt):[];try{if(de.length>0||me){let rt=_e?_e.plan:de;V=await Lr(nr(W,"sandforge clone --remove"),rt,{...(_e&&Gn(_e.part))??Ie,...ee?{removalStamps:ee.removalStamps,removalSpans:ee.removalSpans}:{},...qO(je),...P?{runUserId:P}:{},...St.length>0?{laterParts:St}:{},...Me.length>0?{otherParts:Me.map(xt=>xt.alongside)}:{},includeChanged:n.includeChanged,onUndeletable:ct,beforeFirstWrite:async()=>{C=await Rt()},signal:D.signal})}else C=await Rt();let Xe={...ee?.removalStamps,...V.stamps};for(let rt of V.otherPartStamps??[])Object.assign(Xe,rt);let Bt=[...kt!==void 0?[{part:kt,plan:_e?_e.plan:de}]:[],...[...Ye,...ne].map(rt=>({part:rt.part.part,plan:rt.plan}))];for(let{part:rt,plan:xt}of[...Ye,...ne]){if(V.stoppedForUndeletable||V.cancelled||D.signal.aborted)break;let mn=Gn(rt)??(_e?Ie:void 0);if(!mn)continue;let en=Wr(ee?.removalSpans,[V,...ge].flatMap(gt=>gt.span?[gt.span]:[])),tn=ur(Ge?.parts??[],rt.part),Pt=await Lr(nr(W,"sandforge clone --remove"),xt,{...mn,removalStamps:Xe,removalSpans:en,...P?{runUserId:P}:{},...tn.length>0?{laterParts:tn}:{},otherPartRecords:Bt.flatMap(gt=>gt.part===rt.part?[]:gt.plan),includeChanged:n.includeChanged,onUndeletable:ct,signal:D.signal});Object.assign(Xe,Pt.stamps),ge.push(Pt),_&&be.push({part:rt.part,objects:Pt.objects})}}finally{if(Z(),C){m=await C.release();for(let Xe of rr(m,n.target))o(Xe)}}if(be.length>0&&(b={own:V.objects,others:be}),V.stoppedForUndeletable)return V;let vt=ee?.removalSpans.at(-1)?.last,Zt=Ko(V.objects,...ge.map(Xe=>Xe.objects)),Nn=V.cancelled||ge.some(Xe=>Xe.cancelled);return Oe({outcome:Ol({status:oa(Zt,Nn)}),objects:kl(Zt),...vt?{leftBy:vt}:{}}),V}let Xt=ue&&Ih(ue,new Date().toISOString(),ee?.sweep),ye=HO($,ee,oe&&Ae?JO([oe,...ge]):oe??{stamps:{}},de,Xt,je?.made??[],je?.late??[],je?.gone??[]);ye&&z&&!_&&(ye.partsRemoved=z.parts.map(C=>C.part));let Ot=ye?mc(E,ye,!0):void 0;if(Ot&&process.stderr.write(`What this removal left on the run's records could not be kept in ${E} (${Ot}): a later --remove of this summary may keep a record this removal wrote to as changed since the run, which --include-changed then takes.
873
+ `),_?.part!==void 0&&oe&&!oe.stoppedForUndeletable){let C=[oe,...ge],Z={};for(let V of C)for(let be of[V.stamps,...V.otherPartStamps??[]])Object.assign(Z,be);let se=VO(_,{stamps:Z,spans:C.flatMap(V=>V.span?[V.span]:[]),gone:C.flatMap(V=>V.gone),parts:[_.part,...ne.map(V=>V.part.part)]}),Ie=se?mc(_.file,se,!0):void 0;Ie&&process.stderr.write(`What this removal left on the run's records could not be kept in ${_.file} (${Ie}): 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.
874
+ `)}let ht=Ko(oe?.objects??[],...ge.map(C=>C.objects)),$t=oe?.cancelled===!0||ge.some(C=>C.cancelled),dt=Rl(oe?oa(ht,$t):"success",ue);_?.part!==void 0&&(O=KO(_,ht)),Ke&&!n.sweep&&ht.some(C=>(C.heldByAutomation??0)>0)&&(S=(await ti(W,Ke)).result.writtenBetween===void 0),k(dt,ht,J.id,ye&&!Ot?E:void 0,ue),dt!=="success"&&process.exit($m)}var XO="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 ZO(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)}
875
+ `}function ek(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}${Ym(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(Ln(i,"a removal"));return[...s,...t]}async function tk(r,e,t,n){let o=e,s=[],i,a=(q,P,D)=>{if(s.push(XO),r.json){process.stdout.write(ZO({summary:r.summaryPath,target:r.target,...D!==void 0?{targetOrgId:D}:{},includeChanged:r.includeChanged,preview:q,refusals:P,notes:s,elapsedMs:Fe(n),...i?{sweepListing:i}:{}}));return}t("");for(let X of ek(q,P,s,r.includeChanged))t(X);t(`
876
+ 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}.
877
+ `),process.exit(2));let d,c=async()=>{if(d)return d;let q=An(await Bn(r.target)),P=await fn(q);if(o.targetOrgId!==void 0&&!ni(o.targetOrgId,P.id)){let D={code:ko,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(`${Tt(D)}
878
+ `),r.json&&process.stdout.write(So({tool:"sandforge-clone",action:"remove-preview",summary:r.summaryPath,target:r.target,elapsedMs:Fe(n)},D)),process.exit(1)}return d={conn:q,org:P},d},u=o.journal;if(u!==void 0&&Yt(u)&&Nt(At()).callsInFlightAt(u)>0){let{conn:q}=await c(),P=await Nt(At()).reconcileAt(u,$s(q,{leaveOpen:!0}),{keep:!1});s.push(...vs(P,r.target,"preview"))}let l=(o.result.mayHaveBeenWritten??[]).reduce((q,{sourceIds:P})=>q+P.length,0);l>0&&s.push(`${l} 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 f=Sc(o);if(f.length===0){s.push("The run created no record: there is nothing of it to remove."),a({planned:0,objects:[],userNames:{}},[]);return}let p=ci(r.summaryPath),h;try{h=gn(p,"utf8")}catch(q){q?.code!=="ENOENT"&&(process.stderr.write(`${p} cannot be read: ${q instanceof Error?q.message:String(q)}
879
+ `),process.exit(2))}let g=li(h,ui(f));"refusal"in g&&(process.stderr.write(`${p} ${g.refusal}
880
+ `),process.exit(2));let m=await sw(o);m&&"refusal"in m&&(process.stderr.write(`${m.refusal}
881
+ `),process.exit(2));let w=m&&Ut(p)!==Ut(m.file)?m:void 0,O=uw(g.earlier,w?.earlier),S=bo({objects:f,removalLeft:g.earlier?.removalLeft}),R=dn(S,w?.earlier?.removalLeft),b=w?iw(w):[],T=q=>q.reduce((P,D)=>P+D.ids.length,0);T(f)>T(S)&&s.push(`${T(f)-T(S)} record(s) removed by an earlier --remove of this summary`),T(S)>T(R)&&s.push(`${T(S)-T(R)} record(s) removed by an earlier --remove of the run's other part or of its journal`);for(let{part:q,plan:P}of b)s.push(`with them, ${T(P)} record(s) of the run's part ${q.part} an earlier --remove of that part left, read against that part, once these are gone`);let k=r.includeChanged&&o.result.runUserId!==void 0;if(R.length===0&&b.length===0&&!r.sweep&&!k){s.push("nothing left of the run to remove"),a({planned:0,objects:[],userNames:{}},[]);return}let{conn:v,org:$}=await c(),E=[],B=oo(r.target,$,"remove");if(B&&E.push({code:"PRODUCTION_TARGET",message:B}),o=await ti(v,o),r.sweep){i=await ld(gc(v,"sandforge clone --remove --preview --sweep"),await hc(v,r.target,o,f,await ow($.id,r.target,o,f,O,w),{ofTheRun:w,...r.sweepUser!==void 0?{user:r.sweepUser}:{}}),O?.removalSpans??[]),t("");for(let P of Vs(i,r.target,r,!0))t(P);let q=lc(i.refusal,{kept:o.result.runUserId!==void 0,given:r.sweepUser!==void 0,target:r.target});q!==void 0&&t(q);for(let P of Js(w,i))t(P)}let I=[...new Set([...R,...b.flatMap(q=>q.plan)].map(q=>q.objectApiName))],G=i?su(i,r):[],re=[...new Set([...Ho(I,cw(w),{userKept:o.result.runUserId!==void 0}),...I.length===0&&k?[zo]:[],...G])],z=na(I),_=await ai(v).read(r.target,re);t("");for(let q of _a(_,r.target,re.length,z))t(q);let ee=Da(_,r.target,{drafted:z,assign:ws(_,Ei(_,z)),mayMute:!r.muteAutomation&&jt("--mute-automation")});if(ee&&!r.acceptAutomation&&E.push({code:"AUTOMATION_NOT_ACCEPTED",message:ee}),R.length===0&&b.length===0&&!k){s.push("nothing left of the run to remove"),a({planned:0,objects:[],userNames:{}},E,$.id);return}R.length===0&&b.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 ve=new AbortController,he,de=tr(q=>{he=q,ve.abort()}),K=o.result.writtenBetween,ne=K?{runStartedAt:new Date(K.first),runEndedAt:new Date(K.last)}:{runDurationMs:o.elapsedMs,...o.finishedAt?{runRecordedAt:new Date(o.finishedAt)}:{}},fe,Ae=[],[me,...ce]=(m&&!w?aw(m,R):[])??[],W=w??(me?m:void 0),J=w?.part??me?.part.part,we=W&&J!==void 0?ur(W.parts,J):[],Y=W&&J!==void 0?dw(W,J,O?.removalStamps??{}):[],Ce=[...J!==void 0?[{part:J,plan:me?me.plan:R}]:[],...[...ce,...b].map(q=>({part:q.part.part,plan:q.plan}))];try{fe=await Lr(nr(v,"sandforge clone --remove --preview"),me?me.plan:R,{...(me&&Gn(me.part))??ne,...O?{removalStamps:O.removalStamps,removalSpans:O.removalSpans}:{},...we.length>0?{laterParts:we}:{},...Y.length>0?{otherParts:Y.map(q=>q.alongside)}:{},...o.result.runUserId?{runUserId:o.result.runUserId}:{},includeChanged:r.includeChanged,previewOnly:!0,signal:ve.signal});for(let{part:q,plan:P}of[...ce,...b]){let D=Gn(q)??(me?ne:void 0);if(!D||!fe.preview||ve.signal.aborted)continue;let X=ur(W?.parts??[],q.part);Ae.push(await Lr(nr(v,"sandforge clone --remove --preview"),P,{...D,...O?{removalStamps:O.removalStamps,removalSpans:O.removalSpans}:{},...X.length>0?{laterParts:X}:{},...o.result.runUserId?{runUserId:o.result.runUserId}:{},otherPartRecords:Ce.flatMap(H=>H.part===q.part?[]:H.plan),includeChanged:r.includeChanged,previewOnly:!0,signal:ve.signal}))}}finally{de()}let Oe=fe.preview&&Ae.every(q=>q.preview)?{objects:sa(fe.preview.objects,...Ae.map(q=>q.preview?.objects??[])),userNames:Object.assign({},fe.preview.userNames,...Ae.map(q=>q.preview?.userNames??{}))}:void 0;Oe||(process.stderr.write(`interrupted: the preview stopped before it was through, and wrote nothing
882
+ `),process.exit(Fr(he??"SIGINT")));let Ne=[fe,...Ae].flatMap(q=>q.undeletable??[]);if(Ne.length>0&&!r.leaveUndeletable){let q=Ne.map(P=>`${P.objectApiName} (${P.records} records)`).join(", ");E.push({code:Xd,message:`The user SandForge connects as may not delete the records of ${q} in ${r.target}: a removal stops before its first delete, unless given --leave-undeletable, which removes the rest and leaves those.`})}let Ke=R.length>0||b.length>0;Ke&&s.push(Jm(o)),a({planned:Oe.objects.reduce((q,P)=>q+P.planned,0),objects:Oe.objects,...Ne.length>0?{undeletable:Ne}:{},userNames:Oe.userNames,...Ke?{alreadyHeld:Qm(o)}:{}},E,$.id)}async function ti(r,e,t=Nt(At())){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 ni(r,e){return r.slice(0,15)===e.slice(0,15)}var nk=new Set(["--verify","--target","--source","--json","--audit"]),rk=new Set(["--verify","--target","--source","--audit"]);function ok(r){let e=r.slice(2);(e.includes("-h")||e.includes("--help"))&&(process.stdout.write(bc),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(rk.has(i)){e[s+1]!==void 0&&!e[s+1].startsWith("--")&&s++;continue}nk.has(i)||(process.stderr.write(`--verify takes --target, --source, --json and --audit, not "${i}". Run with --help for usage.
883
+ `),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.
884
+ `),process.exit(2)),{summaryPath:n,target:o,source:t("--source"),json:e.includes("--json"),audit:Rc(e)}}var sk=M.object({result:M.object({writtenWithoutFields:M.array(M.object({objectApiName:M.string().regex(nt),fields:M.array(M.object({field:M.string().regex(nt)}))}))})}),ik=M.object({result:M.object({lookupsLeftEmptyByFilter:M.array(M.object({objectApiName:M.string().regex(nt),field:M.string().regex(nt),records:M.number().int().nonnegative(),recordIds:M.array(ft)}))})}),ak={verified:0,partial:3,unstable:4};function dk(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 h of s.brokenLinks)t.push(h.found===null?` ${h.recordId}: ${h.field} is empty, the run set it to ${h.expected}`:` ${h.recordId}: ${h.field} points at ${h.found}, the run set it to ${h.expected}`);for(let h of s.explainedLinks??[])t.push(h.cause==="automation"?` ${h.recordId}: ${h.field} points at ${h.found??""}, which the target's automation created during the run; the run set it to ${h.expected}`:h.cause==="run"?` ${h.recordId}: ${h.field} is empty: left empty by the run, as it said, rather than set to ${h.expected}`:` ${h.recordId}: ${h.field} is empty: the target's lookup filter refused ${h.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 h of s.changedRecords)n.push(` ${s.objectApiName} ${h.recordId}: modified ${h.modifiedAt}`+(h.modifiedById?` by ${h.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 ck(r=process.argv){let e=Date.now(),t=ok(r),n=I=>t.json?console.error(I):console.log(I),o;try{o=gn(t.summaryPath,"utf8")}catch(I){process.stderr.write(`--verify ${t.summaryPath} cannot be read: ${I instanceof Error?I.message:String(I)}
885
+ `),process.exit(2)}let s;try{s=JSON.parse(o)}catch{}M.object({tool:M.literal("sandforge-clone"),dryRun:M.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.
886
+ `),process.exit(2));let a=Fi(s,"sandforge-clone");a&&(process.stderr.write(`--verify ${t.summaryPath} ${Ci(a,"verify")}
887
+ `),process.exit(2));let d=await fc(t.summaryPath,o,t.target);"refusal"in d&&(process.stderr.write(`--verify ${t.summaryPath} ${d.refusal}
888
+ `),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}.
889
+ `),process.exit(2));let u=Sc(c);if(u.length===0){n("The run created no record: there is nothing of it to verify.");return}let l,f=ci(t.summaryPath),p;try{p=gn(f,"utf8")}catch{}let h=li(p,ui(u)),g=u;if("refusal"in h)n(`${f} ${h.refusal}`);else if(l=h.earlier?.removalStamps,g=bo({objects:u,removalLeft:h.earlier?.removalLeft}),g.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=sk.safeParse(s),w=ik.safeParse(s);n(`sandforge clone --verify ${t.summaryPath} in ${t.target}`);let O=await Bn(t.target),S=An(O),R=await fn(S);if(c.targetOrgId!==void 0&&!ni(c.targetOrgId,R.id)){let I={code:ko,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(`${Tt(I)}
890
+ `),t.json&&process.stdout.write(So({tool:"sandforge-clone",action:"verify",summary:t.summaryPath,target:t.target,elapsedMs:Fe(e)},I)),process.exit(1)}c=await ti(S,c);let b=c.roots!==void 0&&c.journal!==void 0&&Yt(c.journal)?(await Nt(At()).readAt(c.journal,"all"))?.roots:void 0,T=t.source??c.source,k;try{k=md(An(await Bn(T)),"sandforge clone --verify source")}catch(I){k={unavailable:`the org the run read from, ${T}, could not be reached: ${Q(I)}`}}let v=new Map([[R.id,{alias:t.target,username:O.username}]]),$=I=>Zs(t.audit,v,{action:"forge_verify",module:"forge",operationId:`sandforge-clone-${Qs()}`,orgId:R.id,...I}),E;try{E=await new Dh({target:md(S,"sandforge clone --verify"),source:k}).verify({records:g,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:Uh(m.data.result.writtenWithoutFields)}:{},...w.success?{leftEmptyByFilter:w.data.result.lookupsLeftEmptyByFilter}:{},leftEmptyByTheRun:qh(c.wholeOrg===!0),...c.result.withTheirRecordSourceIds?{withTheirRecord:c.result.withTheirRecordSourceIds}:{},...b?{roots:{objectApiName:b.objectApiName,sourceIds:b.ids}}:{}})}catch(I){throw $({outcome:"failure"}),I}if($({outcome:E.verdict==="verified"?"success":"partial",verdict:E.verdict,details:_h(E)}),t.json)process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"verify",summary:t.summaryPath,target:t.target,targetOrgId:R.id,source:T,result:E,elapsedMs:Fe(e)},null,2)+`
891
+ `);else{for(let I of dk(E,t.target))console.log(I);console.log(`
892
+ done in ${Fe(e)}ms`)}let B=ak[E.verdict];B!==0&&process.exit(B)}var uk=new Set(["done","error","stopped"]);function lk(r){return r?`interrupted: the clone stopped before it was through; ${r} says what it created, and --remove ${Ar(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 Em(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 ${ud} objects at most; ${pn("--sweep-list")} lists what the target's automation made for it, and ${pn("--sweep")} takes it`}var Im="ROOT_NEVER_CREATED",fk="TABLE_NEVER_CLONED",wc="No record was read or written.";async function pk(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=>Io(i.objectApiName));if(o){let i=o.objectApiName;return{code:Im,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. ${wc}`}}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||!Sf(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:Im,message:`${i.named}: no user can create ${d} records in ${e}, ${c}, and a clone has nothing to write of what it starts from. ${wc}`}}}async function hk(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 xm(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(Oa),sent:i}},query:async(o,s)=>_n({query:async i=>n(o).query(i),queryMore:async i=>n(o).queryMore(i)},s)}}function gr(r,e){let t=r.get(e);if(!t)throw new Error(`No connection for ${e}`);return t}var gk=new Set(["Lead","Case"]);function mk(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&&gk.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 gf(ta(gr(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 hf&&(n(),t?.note({orgId:o,objectApiName:s,...c.jobId?{jobId:c.jobId}:{}})),c}},duplicateRuleObjects:async o=>bh(gr(r,o))}}async function wk(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 yk(r,e,t){let n=r.get(e);if(!n)throw new Error(`No connection for ${e}`);return _n({query:async o=>n.tooling.query(o),queryMore:async o=>n.tooling.queryMore(o)},t)}async function bk(r=process.argv){if(await Rk(),r.slice(2).includes("--verify"))return ck(r);if(r.slice(2).includes("--remove"))return QO(r);let e={};try{await kk(r,e)}finally{e.release?.(),e.journalLock?.release()}}async function Rk(){let r=At();try{await Vp(r,new Date)}catch(e){process.stderr.write(`The plans of samples drawn a day ago or more could not all be removed from ${Ys(r,"forge-samples")} (${Q(e)}).
893
+ `)}}var ri=class extends Error{constructor(e){super(e),this.name="CheckpointTakeInterrupted"}},oi=class extends Error{constructor(e){super(e),this.name="QuestionInterrupted"}};async function Ok(r,e){let t=r.roots?.plan;if(t===void 0)return;let n=s=>(process.stderr.write(`${Tt(s)}
894
+ `),r.json&&process.stdout.write(on({tool:"sandforge-clone",source:r.source,target:r.target,dryRun:r.dryRun,elapsedMs:Fe(e)},s)),process.exit(2)),o=`${Gt("clone")} \u2026 --dry-run --roots-plan ${t}`;if(r.dryRun){if(!Yt(t))return;try{await ad(t)}catch(s){if(!(s instanceof id))throw s;let i=!1;try{let a=JSON.parse(gn(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.
895
+ `),process.exit(2))}return}try{return await ad(t)}catch(s){if(!(s instanceof id))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 kk(r,e){let t=Date.now(),n=Gb(r),o=n.depth==="all",s=y=>n.json?console.error(y):console.log(y);s(`sandforge clone ${n.source} -> ${n.target} ${kb(n)}`);for(let y of OR(n))s(y);if(n.resume&&n.files===void 0){let y=Nt(At()),A=await y.headAt(lm(n.resume,y));A?.resume?.files&&(n={...n,files:A.resume.files},s("files: copied as the run taken up was begun, with --files"))}let i=await Ok(n,t),a=await Bn(n.source),d=await Bn(n.target),c,u=()=>c??=new Nh({...dc(n),depth:n.depth,sourceOrgId:n.source,targetOrgId:n.target,anonymizePII:n.anonymize,...Xs(n),keepContactPoints:n.keepContactPoints,skipEmpty:!0,batchSize:"auto",excludedObjects:n.excludedObjects,...n.decisions},{reviewSkipped:!0}),l=new Map;l.set(n.source,An(a)),l.set(n.target,An(d));let f=new Map([...l].map(([y,A])=>[y,[Oo(A)]])),p=y=>(f.get(y)??[]).reduce((A,F)=>A+F(),0),h,g=new Map,m,w=`sandforge-clone-${Qs()}`,O,S=y=>{if(h===void 0||n.dryRun||n.listObjects||n.rehearse)return;let A=c?.fit();Zs(n.audit,g,{action:"forge_execute",module:"forge",operationId:w,orgId:h,...y,...O?{muted:Ro(O)}:{},...A?{fit:A}:{}})},R;if(!n.dryRun&&!n.listObjects){let y=await fn(l.get(n.target));R=y,h=y.id,g.set(y.id,{alias:n.target,username:d.username}),n.audit&&!n.rehearse&&(m=(await fn(l.get(n.source))).id,g.set(m,{alias:n.source,username:a.username}));let A=oo(n.target,y,"clone");A&&(S({outcome:"stopped",code:"PRODUCTION_TARGET",context:u().context()}),process.stderr.write(`${A}
896
+ `),process.exit(1))}let b;if(o){let y=await fn(l.get(n.source));b=y.id;let A=oo(n.source,y,"clone")!==void 0;A&&!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.
897
+ `),process.exit(2))),s(sm(n,A&&!n.anonymizeGiven?`${n.source} being a production org (--no-anonymize copies its personal data as it is)`:void 0))}else s(sm(n));let T=await cO(n,async y=>{let A=l.get(n.source);return(await Po({query:async F=>A.query(F),queryMore:async F=>A.queryMore(F)},y,Sn+1)).records},i);if(T&&"refused"in T){let{refused:y}=T;S({outcome:"stopped",code:y.code,context:u().context()}),process.stderr.write(`${Tt(y)}
898
+ `),n.json&&process.stdout.write(on({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:hr({target:p(n.target),source:p(n.source)},{})},y)),process.exit(1)}let k=T?.chosen;if(!n.listObjects){let y=await Ts(n.ownerMappings,async A=>(await l.get(n.target).query(A)).records);if(y){S({outcome:"stopped",code:y.code,context:u().context()});let A={code:y.code,message:y.message};process.stderr.write(`${Tt(A)}
899
+ `),n.json&&process.stdout.write(on({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:hr({target:p(n.target),source:p(n.source)},{})},A)),process.exit(1)}}let v=n.checkpointFirst?Xg({module:"forge",operationId:w,request:n.checkpointFirst,session:d,org:Yg(d,R??await fn(l.get(n.target))),connect:y=>{let A=An(y);return f.get(n.target)?.push(Oo(A)),A},journalDir:At(),say:s}):void 0,$=[...l.values()].map(Oo),E=()=>$.reduce((y,A)=>y+A(),0),B={...dc(n),depth:n.depth,customDepth:n.depth==="custom"?n.customDepth:void 0,sourceOrgId:n.source,targetOrgId:n.target,anonymizePII:n.anonymize,...Xs(n),skipEmpty:!0,batchSize:"auto",...(n.tables||o)&&Object.keys(n.objectSoqlFilters).length>0?{objectSoqlFilters:n.objectSoqlFilters}:{},...o&&n.excludedObjects.length>0?{excludedObjects:n.excludedObjects}:{}},I=new Wu,G=new Set,re=aR(async(y,A)=>{G.add(`${y}::${A}`);let F=l.get(y);if(!F)throw new Error(`No connection for ${y}`);return F.sobject(A).describe()}),z=new Map,_={describeObject:async(y,A)=>sR(await re(y,A)),queryCount:async(y,A,F,N)=>{let x=l.get(y);if(!x)throw new Error(`No connection for ${y}`);return(await x.query(A,N?.all?{scanAll:!0}:void 0)).totalSize},detectPII:y=>Lu(I,y),readFieldClassification:async(y,A)=>{let F=l.get(y);if(!F)throw new Error(`No connection for ${y}`);return Nu(Mu(F),A)},describeGlobal:y=>{let A=z.get(y);if(!A){let F=l.get(y);if(!F)throw new Error(`No connection for ${y}`);A=F.describeGlobal().then(N=>N.sobjects.map(x=>o?{name:x.name,keyPrefix:x.keyPrefix??null,queryable:x.queryable,createable:x.createable,updateable:x.updateable,deletable:x.deletable,customSetting:x.customSetting,layoutable:x.layoutable}:{name:x.name,keyPrefix:x.keyPrefix??null})),z.set(y,A)}return A},...o?{toolingObjects:async y=>{let A=l.get(y);if(!A)throw new Error(`No connection for ${y}`);return(await A.tooling.describeGlobal()).sobjects.map(F=>F.name)},recordCounts:async y=>{let A=l.get(y);if(!A)throw new Error(`No connection for ${y}`);return A.request(`/services/data/v${A.version}/limits/recordCount`)},createFacts:async y=>(await Ra(xm(l,re,G),y)).facts}:{}},ee=await hk(n,_.describeGlobal),ve=await pk(ee,n.target,{createable:async y=>(await re(n.target,y)).createable!==!1,whyNot:y=>Tf((A,F)=>yk(l,A,F),async A=>(await Ra(xm(l,re,G),A)).facts)(n.target,y)});ve&&(S({outcome:"stopped",code:ve.code,context:u().context()}),process.stderr.write(`${Tt(ve)}
900
+ `),n.json&&process.stdout.write(`${JSON.stringify({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,refused:ve,elapsedMs:Fe(t)},null,2)}
901
+ `),process.exit(1));let he=(n.tables??[]).flatMap(({objectApiName:y})=>{let A=hb(y);return A!==void 0?[A]:[]});if(he.length>0){let y={code:fk,message:`${he.join(" ")} ${wc}`};S({outcome:"stopped",code:y.code,context:u().context()}),process.stderr.write(`${Tt(y)}
902
+ `),n.json&&process.stdout.write(on({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t)},y)),process.exit(2)}s("discovery\u2026");let de=new Mf(_),K={source:p(n.source),target:p(n.target)},ne=o?await FR(de,B,s):await de.discover(B,n.maxNodes===void 0?void 0:{maxNodes:n.maxNodes}),fe={source:p(n.source)-K.source,target:p(n.target)-K.target};o&&s(NR(fe,n.source,n.target));let Ae=o?void 0:ne.nodes[0]?.objectApiName;Ae!==void 0&&n.excludedObjects.includes(Ae)&&(process.stderr.write(`${In(`--exclude-object ${Ae}`,`the resource's template leaves out ${Ae}`)}: the ${n.tables?"first table":"record"} to clone is of this object, and nothing would be left to clone.
903
+ `),process.exit(2));let me=n.tables?pb(ne,n.tables):[];me.length>0&&(process.stderr.write(`${mb(me,{root:Ae??n.tables?.[0]?.objectApiName??"",objects:ne.nodes.length,depth:n.depth,customDepth:n.customDepth,truncated:ne.truncated===!0,env:Kt()})}
904
+ `),process.exit(2));let ce=n.tables?Rb(n,ne):o?Ab(n):B,W=ce.excludedObjects??n.excludedObjects,J=o?$b(ne,new Set(W)):lO(os(ne,new Set(W)),n.anonymizeFields),we=n.anonymize?await de.readClassification(B.sourceOrgId,J.nodes.filter(y=>y.included).map(y=>y.objectApiName)):void 0,Y=we?ru(J,we,!0):J;if(we)for(let y of Ff(we))s(y);let Ce=new kf().generate(Y);if(s(o?xR(Y,Ce,n.source):IR(Y,Ce,n.maxNodes??Cf)),n.listObjects){let y=aO(Y),A=y.map(F=>` ${F.objectApiName.padEnd(42)}${String(F.recordCount).padStart(8)} depth ${F.depth}${F.included?"":" (excluded)"}`);s(`
905
+ objects in the graph (${Y.nodes.length}):`),s(A.join(`
906
+ `)),Y.truncated&&s(`
907
+ 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:zs(Y,Ce),objects:y,...o?{leftOut:hs(Y)}:{},elapsedMs:Fe(t)},null,2)+`
908
+ `);return}let Oe=await pR(n.fieldExclusions,Y,async y=>(await re(n.source,y)).fields.map(A=>A.name)),Ne=Oe.length>0?{code:rc,message:pm(Oe,n.choicesFrom).replace(/ Nothing was read or written\.$/,"")}:void 0;if(Ne!==void 0&&!n.dryRun){S({outcome:"stopped",code:rc,context:u().context()});let y={code:rc,message:pm(Oe,n.choicesFrom)};process.stderr.write(`${Tt(y)}
909
+ `),n.json&&process.stdout.write(on({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:hr({target:p(n.target),source:p(n.source)},{},o?fe:void 0)},y)),process.exit(2)}Ne!==void 0&&s(` ${Ln(Ne)}`);let Ke=o?gh(Y):void 0;Ke&&(S({outcome:"stopped",code:Ke.code,context:u().context()}),process.stderr.write(`${Tt(Ke)}
910
+ `),n.json&&process.stdout.write(on({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:hr({target:p(n.target),source:p(n.source)},{},fe)},Ke)),process.exit(1));let q=y=>(S({outcome:"stopped",code:y.code,context:u().context()}),process.stderr.write(`${Tt(y)}
911
+ `),n.json&&process.stdout.write(on({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),apiRequests:hr({target:p(n.target),source:p(n.source)},{},fe)},y)),process.exit(Om(y.code))),P=At(),D="",X;if(n.sample){let y=h??(await fn(l.get(n.target))).id,A={...b?{sourceOrgId:b}:{}};D=dd(Y,fm(n,y,A));let F=n.sample.options.plan;if(F!==void 0)try{if(X=await dr.open(F,{sourceOrgId:n.source,fingerprint:D}),X.ageMs(new Date)>=qp)throw new js("gone","The plan of this sample is a day old or more.")}catch(N){let x=ms(N,"replay");if(!x)throw N;q({code:x.code,message:x.message.replace(/ Nothing was written\.$/,` Given: ${F}. Nothing was written.`)})}}let H=!n.dryRun&&!n.rehearse?Nt(P):void 0,je=(y,A)=>fm(n,y,{...b?{sourceOrgId:b}:{},...A?{planSha256:A}:{}}),U=h!==void 0?dd(Y,je(h,X?.sha256)):"",oe,ge,ue=n.muteAutomation;if(H&&h!==void 0&&n.resume){oe=lm(n.resume,H);let y=Is(oe,{journalId:yc(oe).replace(/\.ndjson$/,""),ranFrom:"commandLine",target:n.target,resumes:!0});if("busy"in y)return q({code:xi,message:`--resume ${oe}: ${fd(y.busy)}. Two runs would write it at once: ${pd(y.busy)}, then take it up. Nothing was written.`});e.journalLock=y.lock;let A=h,F=await Jb(H,oe,{target:n.target,targetOrgId:h,graph:Y,setup:je(h),sample:{asked:n.sample!==void 0,setupWith:x=>je(A,x)},config:ce,...n.record?{record:n.record}:{}});F&&q(F),ge=await H.lastEndAt(oe),(await H.headAt(oe))?.resume?.muteAutomation===!0&&(ue=!0),s(`taking up the run of ${oe}`);let N=await H.reconcileAt(oe,$s(l.get(n.target)));for(let x of vs(N,n.target))s(x);if(Es(N)>0&&!n.writeUncertain){let x=Kb(N),te={code:"RESUME_UNCERTAIN",message:Hb(N,n.target),...x!==void 0?{retryAt:x}:{}};q(te)}}let It=new Rh,pt=new AbortController,bt={},at,Qn=y=>{at=y,lu("the clone stops after the call under way, and says what it created",y),It.stop(void 0,{discovery:()=>{},run:()=>{pt.abort(),bt.executor?.abort()}})};if(!n.dryRun&&!n.rehearse&&!n.listObjects){It.beginRun(w,pt);let y=tr(Qn);e.release=()=>{y(),It.endRun(w)}}let Rt=async y=>{pt.signal.aborted&&(S({outcome:"stopped",code:Hi,context:u().context()}),await y?.(),s("interrupted: the clone stopped before it wrote anything"),process.exit(Fr(at??"SIGINT")))},De=await ai(l.get(n.target)).readForGraph(n.target,Y,new Set(W));s("");for(let y of xf(De,n.target,{applyAssignmentRules:n.applyAssignmentRules,mayMute:jt("--mute-automation"),mayApplyAssignmentRules:jt("--apply-assignment-rules")}))s(y);let Xt=iu(De,new Set(W));for(let y of sp(Xt,n.target,De.unread,In("--remove","destroy, or a replace")))s(y);s(n.keepContactPoints?`contact points: written as read (${In("--keep-contact-points","keepContactPoints")})`:"contact points: neutralized before writing (emails under .invalid, phone numbers in a fictional range)");let ye=await fO(l,re,G).read(n.source,n.target,Y,{inputMode:B.inputMode,recordId:B.recordId,maxRecordsPerObject:n.maxRecordsPerObject,fieldExclusions:n.fieldExclusions,fieldMappings:n.fieldMappings,excludedObjects:W,...n.keepContactPoints?{keepContactPoints:!0}:{}}),Ot={...n.decisions,fieldExclusions:n.fieldExclusions,excludedObjects:W},ht=rp(Y,{leftOut:new Set(W),upsert:n.upsert}),$t=new Set(ht.map(y=>y.objectApiName)),dt=(y,A)=>A==="insert"||A==="update"&&$t.has(y),C=ue?Pl(De,dt).plan.alsoLifts:void 0,Z=dt,se;s("");for(let y of $f(ye,n.target,{decisions:Ot,...C?{lifted:C}:{}}))s(y);let Ie=n.upsert&&!n.keepContactPoints?TR(await Promise.all(Y.nodes.filter(y=>y.included).map(async({objectApiName:y})=>({objectApiName:y,fields:await re(n.source,y).then(A=>A.fields).catch(()=>[])})))):[];for(let y of AR(Ie,n.target))s(y);let V,be,ct={},_e=()=>({apiRequests:hr({target:p(n.target),source:p(n.source)},ct,o?fe:void 0)}),Ye=(y,A=[],F=1)=>{let N={...y,message:ro(y.message)},x=A.map(te=>({...te,message:ro(te.message)}));for(let te of[N,...x])process.stderr.write(`${Tt(te)}
912
+ `);return n.json&&process.stdout.write(on({tool:"sandforge-clone",source:n.source,target:n.target,dryRun:n.dryRun,elapsedMs:Fe(t),..._e()},N,x)),process.exit(F)};if(ue){n.muteAutomation||s(" mute: the run taken up was muted, and so is this part of it");try{V=await ca(async()=>aa(l.get(n.target)),De,{writes:dt});for(let y of rr(V.muted,n.target))s(` ${y}`)}catch(y){if(!Dr(y))throw y;n.dryRun||(S({outcome:"stopped",code:y.code,context:u().context()}),Ye(y.refusal)),be=y.refusal,s(` ${Ln(y.refusal)}`)}}let Ge=V?.automation??De,kt=ip(Ge,n.target,{updated:ht,assign:ws(Ge,op(Ge,ht.map(y=>y.objectApiName))),mayMute:!ue&&jt("--mute-automation")});u().automationRead({automation:Ge},ht),kt&&n.acceptAutomation&&u().confirm("automation");let Me=n.rehearse?void 0:await xl({read:De,...V?.plan?{plan:V.plan}:{},writes:dt,applyAssignmentRules:n.applyAssignmentRules,readDeliverability:async()=>{let y=l.get(n.target),A=R??await fn(y);return oo(n.target,A,"clone")!==void 0?El:Il(y)},accepted:n.acceptEmails,target:n.target,run:"clone",keepsAddresses:n.keepContactPoints,mayMute:!ue&&jt("--mute-automation")});Me?.gate.line!==void 0&&s(` ${Me.gate.line}`),u().emailsRead(Me?.gate.audit),Me?.gate.verdict==="asks"&&n.acceptEmails&&u().confirm("emails");let St=Me?.gate.stop,vt=[...Ne!==void 0?[Ne]:[],...be!==void 0?[be]:[]],Zt=kt!==void 0&&!n.acceptAutomation;(Zt||St)&&!n.dryRun&&(S({outcome:"stopped",code:Zt?"AUTOMATION_NOT_ACCEPTED":ep,context:u().context()}),Zt&&Ye({code:"AUTOMATION_NOT_ACCEPTED",message:kt},St?[St]:[]),St&&Ye(St)),Zt&&(vt.push({code:"AUTOMATION_NOT_ACCEPTED",message:kt}),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")),St&&(vt.push(St),s(` ${Ln(St)}`)),await Rt(),s("record-type mapping\u2026");let Nn=E(),Xe=[],Bt=await iR(l.get(n.source),l.get(n.target),y=>Xe.push(y)),rt=E()-Nn;s(`record-types: ${Bt.length} mappings`);for(let y of Xe)s(` warning: ${y}`);await Rt();let xt={statements:0,pages:0},mn=!1,en=y=>(y.some(A=>A.success)&&(mn=!0),y),tn=o?new yh(async(y,A)=>(await ta(gr(l,y)).bulk2.job("ingest",{id:A}).check()).state):void 0,Pt={...o?mk(l,n,tn,()=>mn=!0):{},queryRecords:async(y,A,F)=>{let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);let{records:x,truncated:te}=await Po({query:async $e=>N.query($e),queryMore:async $e=>N.queryMore($e)},A,n.readCeiling);return te&&F?.(),x},queryPages:(y,A,F)=>{let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);return xt.statements++,qu({query:async x=>(xt.pages++,N.query(x)),queryAll:async x=>(xt.pages++,N.query(x,{scanAll:!0})),queryMore:async x=>(xt.pages++,N.queryMore(x))},A,F)},countRecords:async(y,A,F)=>{let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);return(await N.query(A,F?.all?{scanAll:!0}:void 0)).totalSize},queryTooling:async(y,A)=>{let F=l.get(y);if(!F)throw new Error(`No connection for ${y}`);return(await F.tooling.query(A)).records},insertRecords:async(y,A,F)=>{if(n.dryRun)return F.map(()=>({id:"",success:!0,errors:[]}));let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);let x=await N.sobject(A).create(F,{headers:vr({applyAssignmentRules:n.applyAssignmentRules})});return en(ea(x,A))},updateRecords:async(y,A,F)=>{if(n.dryRun)return[];let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);let x=await N.sobject(A).update(F,{headers:vr({applyAssignmentRules:n.applyAssignmentRules})}),te=Array.isArray(x)?x:[x];return en(te.map(($e,qe)=>({id:$e.id??F[qe].Id??"",success:$e.success,errors:($e.errors??[]).map(gl),errorDetails:($e.errors??[]).map(hl)})))},describeFields:async(y,A)=>oR(await re(y,A)),isObjectCreatable:async(y,A)=>(await re(y,A)).createable!==!1,describeObject:async(y,A)=>{let F=l.get(y);if(!F)throw new Error(`No connection for ${y}`);return ec(F,A)},describeObjectAgain:async(y,A)=>{let F=l.get(y);if(!F)throw new Error(`No connection for ${y}`);return ec(F,A,!0)},recordTypePicklists:async(y,A,F)=>{let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);return Oh(N,A,F)},upsertRecords:async(y,A,F,N)=>{if(n.dryRun)return N.map(()=>({id:"",success:!0,errors:[]}));let x=l.get(y);if(!x)throw new Error(`No connection for ${y}`);let te=await x.sobject(A).upsert(N,F,{headers:vr({applyAssignmentRules:n.applyAssignmentRules})});return en(ea(te,A))},readFileBody:async(y,A,F)=>{let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);return kh(N,A,F)},insertFile:async(y,A,F)=>{if(n.dryRun)return{id:"",success:!0,errors:[]};let N=l.get(y);if(!N)throw new Error(`No connection for ${y}`);let[x]=en([await Sh(N,A,F)]);return x},remainingFileStorageMB:async y=>{let A=l.get(y);if(!A)throw new Error(`No connection for ${y}`);return Th(A)},requestsSent:E,runningUser:async y=>{let A=l.get(y);if(!A)throw new Error(`No connection for ${y}`);return(await A.identity()).user_id},orgCurrency:async y=>{let A=l.get(y);if(!A)throw new Error(`No connection for ${y}`);return zu(await A.soap.getUserInfo())}},gt={};if(n.roots){try{gt.sourceRequestsLeft=(await Un(l.get(n.source))).remaining}catch{}i&&(gt.plan=i),k&&(gt.chosen=k),n.dryRun&&n.roots.plan!==void 0&&(Hs(n.roots.plan,{force:!0}),gt.keepAt=n.roots.plan)}if(n.rehearse){let y=l.get(n.target),A=vr({applyAssignmentRules:n.applyAssignmentRules});s(`
913
+ rehearsing\u2026 (the rows are read and prepared as the run would; nothing stays in the target)`);let F;try{F=await gd({prepare:async x=>{await new pr(hd(Pt,x)).execute(Y,n.source,n.target,()=>{},{...km(n,Y,Bt,te=>de.personalFields(te),gt),dryRun:!1,files:void 0})},keyPrefixOf:async x=>(await ec(y,x)).keyPrefix,runningUser:async()=>(await y.identity()).user_id,composite:x=>y.request({method:"POST",url:"/composite",body:JSON.stringify(x),headers:{"Content-Type":"application/json",...A}}),apiPath:`/services/data/v${y.version}`,writeHeaders:A,recordTypeNames:new Map(Bt.map(x=>[x.targetId.slice(0,15),x.developerName])),targetRecordTypes:tm(Pt,n.target),targetFields:x=>Pt.describeFields(n.target,x),validationRules:async()=>Lh(ye.gaps),confirm:async x=>{s("");for(let te of hO(x,n.target))s(te)},onProgress:x=>{x.phase==="rehearsing"&&s(` call ${x.call} of ${x.calls}\u2026`)}})}catch(x){throw x instanceof Wh&&(process.stderr.write(`${x.message}
914
+ `),process.exit(1)),x}let N=Fe(t);s("");for(let x of gO(F,n.target,C?{lifted:C}:{}))s(x);n.json?process.stdout.write(JSON.stringify({tool:"sandforge-clone",version:1,action:"rehearse",source:n.source,target:n.target,...h?{targetOrgId:h}:{},record:n.record,graph:zs(Y,Ce),targetAutomation:De,rehearsal:mO(F,C),elapsedMs:N},null,2)+`
915
+ `):console.log(`
916
+ done in ${N}ms`);return}if(!n.skipPreflight){s(`
917
+ preflight (target row counts)\u2026`);let y=l.get(n.target),A=Y.nodes.slice(0,30),F=[];for(let x of A)try{let te=await y.query(`SELECT COUNT() FROM ${x.objectApiName}`);F.push({name:x.objectApiName,existing:te.totalSize})}catch{F.push({name:x.objectApiName,existing:-1})}let N=F.filter(x=>x.existing>0);if(N.length===0)s(" target is empty for all sampled objects.");else{let x=N.sort((te,$e)=>$e.existing-te.existing).slice(0,10);s(` ${N.length}/${F.length} sampled objects have existing rows. Top 10:`);for(let te of x){let $e=te.existing>1e3?" \u26A0":"";s(` ${te.name.padEnd(40)} ${String(te.existing).padStart(8)}${$e}`)}Y.nodes.length>A.length&&s(` (sampled first ${A.length}/${Y.nodes.length} nodes; --skip-preflight to bypass)`)}}await Rt();let Lt=l.get(n.target),Yn=qf(Lt,h??d.orgId),Wt,Ze,wr=[],j={},L,le,pe=async(y,A,F)=>{if(!v||A.totalRows===0)return;let N=new Set(A.objects.map(({objectApiName:te})=>te)),x={written:y.objects.map(({objectApiName:te})=>te).filter(te=>N.has(te)),running:F};try{Ze={ask:x,estimate:await v.scope(x)};return}catch(te){return Aa(te).replace(/ Nothing was written\.$/,"")}},Se=y=>({unread:Q(y)}),ut=(y,A)=>{Z=Mh(y.objects,A,dt);let F=[];if(V){let N=V.plan;V=Fl(V,Z),ue&&(C=V.plan?.alsoLifts),se=Cl(N,V,Z)??se,F.push(...Nl(N,V,Z).map(x=>` ${x}`))}return{running:{firing:Ii(V?.automation??Ge,void 0,Z).firing},lines:F}},Xn=()=>({target:Math.max(0,p(n.target)-(Me?.ofRun.read?.requests??0)),source:p(n.source)}),lw=async y=>{let A=y.wholeOrg;if(!A)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 F=Kf(A.readWholeOver);if(F&&!y.dryRun)throw Pe.of({...F,message:ym(F.message,A.sample!==void 0)});let N=Jf(y.objects,A),{running:x,lines:te}=ut(y,N),$e=ys(x,(ie,Ct)=>Z(ie,Ct)).perRecord,qe=A.sample?.report;qe&&(le=qe,u().sampled(qe));let bn=await pe(y,N,x),Dt=[...$t],et,ot,mt,nn,Rn;if(y.dryRun)et=await Qf({objects:y.objects,measures:A,graph:Y,anonymizePII:n.anonymize,updatedAfterInsert:Dt,...Ze?{checkpoint:Ze.estimate}:{},...y.readBack!==void 0?{readBack:y.readBack}:{},mute:Vo(V?.plan),deliverability:Me?.ofRun.read?.requests??0,sentBefore:Xn,...qe?{sample:qe}:{},...qe&&n.sample?{sampleAsked:uc(n.sample)}:{},automation:$e,target:{org:n.target,limits:Yn},source:{org:n.source,limits:gr(l,n.source)}}),ot=mh(et),mt=et.storage,nn=et.files,Rn=et.wouldBeRefused;else{let ie=await ls(Yn).catch(Se),Ct="unread"in ie?await Un(Lt).catch(Se):ie.dailyApiRequests;mt=$a(N,ie,ps(N,$e));let po=La(mt,n.target),bi=qe?Zf({sample:qe,storage:ie,target:n.target,...n.sample?{asked:uc(n.sample)}:{}}):void 0,Ri=Vf(A.files,ie,n.target);nn=Ri.files;let kw=await Un(gr(l,n.source)).catch(Se),Cc=Xn(),Tr=ja({plan:N,updatedAfterInsert:Dt,...y.readBack!==void 0?{readBack:y.readBack}:{},...Ze?{checkpoint:Ze.estimate}:{},mute:Vo(V?.plan),...Ma(Me?.ofRun),sentBefore:Cc.target,budget:Ct,target:n.target,wholeOrg:{measures:A,bulkBatches:"unread"in ie?ie:ie.dailyBulkApiBatches,sourceBudget:kw,source:n.source,sourceSentBefore:Cc.source}});ot={api:Tr.api,wholeOrg:Tr.wholeOrg},Rn=[...bi?[bi]:[],...bi===void 0&&po!==void 0&&mt.verdict==="exceeds"?[{code:"STORAGE_EXCEEDED",message:`${po} Nothing was written.`,storage:{estimateMB:Number(qt(mt.estimateMB)),remainingMB:mt.remainingMB,...fs(mt)}}]:[],...Ri.stop?[Ri.stop]:[],...Tr.stop?[Tr.stop]:[],...Tr.alsoRefused??[]]}let Rr=qe?void 0:_R(mt,n.target);Rr!==void 0&&(Rn=Rn.map(ie=>ie.code==="STORAGE_EXCEEDED"?{...ie,message:`${Rr} Nothing was written.`}:ie));let Or={...wh({run:{source:n.source,graph:Y,anonymizePII:n.anonymize,...fw()},measures:A,plan:N,budget:ot,...nn?{files:nn}:{},...qe?{sample:qe,now:Date.now()}:{}}),discovery:fe};if(ct={target:ot.api,source:ot.wholeOrg.source},L={...et?{dry:et}:{},question:Or},s(""),qe)for(let ie of XR(qe,{source:n.source,target:n.target,dryRun:y.dryRun===!0,replayed:n.sample?.options.plan!==void 0}))s(ie);for(let ie of Wa(N,mt,n.target))s(ie);for(let ie of te)s(ie);let kr=BR(A,n.source,n.target);kr!==void 0&&s(kr);for(let ie of CR(Or,hs(Y).counts,n.target,A.writes))s(ie);if(Ze)for(let ie of Jd(Ze.estimate))s(ie);let lo=vi(Ge),Sr;if(lo.length>0){let ie=await Ia(Lt).catch(Se),Ct=xa(N,lo,ie);for(let po of Na(Ct,n.target))s(po);Sr=Ca(Ct,n.target)}let fo=Fa(Ge,Pa(N));fo!==void 0&&s(` emails: not counted, ${fo} could not be read`);let On=ie=>ro(ym(ie,qe!==void 0)).replace(/ Nothing was written\.$/,""),ke=[...N.totalRows>n.maxTotal?[{code:"MAX_TOTAL_EXCEEDED",message:LR(N.totalRows,n.maxTotal,qe!==void 0,n.dryRun)}]:[],...bn!==void 0?[{code:En,message:bn}]:[],...Rn.map(ie=>({code:ie.code,message:ie.code===En&&ie.refusal!==void 0?Us(ie.refusal):On(ie.message),stop:ie})),...Sr!==void 0?[{code:"EMAILS_EXCEEDED",message:Sr}]:[]];if(et){for(let{code:ie,message:Ct}of ke)s(` ${Ln({code:ie,message:Ct})}`);throw vt.push(...ke.map(({code:ie,message:Ct})=>({code:ie,message:Ct}))),Wt={totalRows:N.totalRows,storageBytes:N.storageBytes,objects:N.objects,...N.leftOut?{leftOut:N.leftOut}:{}},new cd(et)}let Ue=ie=>`${ie} Nothing was written.`,[xe,...yi]=ke;if(xe)throw wr=yi.map(({code:ie,message:Ct})=>({code:ie,message:Ue(Ct)})),xe.stop?Pe.of({...xe.stop,message:Ue(xe.message)}):new Pe(xe.code,Ue(xe.message));j=Zi(ot.api),await pw(Or,N,qe)},fw=()=>{let y=hh(ce);return y?{carried:y}:{}},pw=async(y,A,F)=>{let N=wm(y,A,n.target,F);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 x=await uu(mm(N),void 0,pt.signal);if(pt.signal.aborted)throw new oi("interrupted at its question: the clone stopped before it wrote anything");if(!x)throw new Pe("WRITE_DECLINED","The clone of the whole org was declined at its question. Nothing was written.");u().confirm("volume")},hw=async y=>{if(o)return lw(y);let A=_f(y.objects),F;try{F=await ls(Yn)}catch(ke){F={unread:Q(ke)}}let{running:N,lines:x}=ut(y,A),te=ys(N,(ke,Ue)=>Z(ke,Ue)).perRecord,$e=$a(A,F,ps(A,te));s("");for(let ke of Wa(A,$e,n.target))s(ke);for(let ke of x)s(ke);let qe="unread"in F?await Un(Lt).catch(ke=>({unread:Q(ke)})):F.dailyApiRequests,bn;if(v&&A.totalRows>0){let ke=new Set(A.objects.map(({objectApiName:xe})=>xe)),Ue={written:y.objects.map(({objectApiName:xe})=>xe).filter(xe=>ke.has(xe)),running:N};try{Ze={ask:Ue,estimate:await v.scope(Ue)}}catch(xe){bn=Aa(xe).replace(/ Nothing was written\.$/,"")}}let Dt=ja({plan:A,updatedAfterInsert:[...$t],...y.readBack!==void 0?{readBack:y.readBack}:{},...Ze?{checkpoint:Ze.estimate}:{},mute:Vo(V?.plan),...Ma(Me?.ofRun),sentBefore:Xn().target,budget:qe,target:n.target});if(j=Zi(Dt.api),ct={target:Dt.api},s(ib(Dt.api,n.target)),Ze)for(let ke of Jd(Ze.estimate))s(ke);let et=vi(Ge),ot,mt;if(et.length>0){let ke=await Ia(Lt).catch(xe=>({unread:Q(xe)})),Ue=xa(A,et,ke);for(let xe of Na(Ue,n.target))s(xe);ot=Ca(Ue,n.target),mt=Ue.map(xe=>({limit:xe.limit,emails:xe.emails}))}let nn=Fa(Ge,Pa(A));nn!==void 0&&s(` emails: not counted, ${nn} could not be read`);let Rn=n.roots?.query?.roots,Rr=bm(y,Rn,{taken:A.totalRows,room:n.maxTotal,each:ke=>`about ${Math.ceil(ke)} records`,past:`the ${n.maxTotal} --max-total holds the run to`}),Or=A.totalRows>n.maxTotal?Rr?WR(A.totalRows,n.maxTotal,Rr,n.dryRun):Tc(A.totalRows,n.maxTotal,n.dryRun):void 0,kr=$e.verdict==="exceeds"?bm(y,Rn,{taken:$e.estimateMB,room:Wf($e),each:ke=>`about ${qt(ke)} MB`,past:`what ${n.target} has left`}):void 0,lo=kr?DR($e,n.target,kr):La($e,n.target),Sr=bn??(Dt.stop?.refusal!==void 0?Us(Dt.stop.refusal):void 0),fo=Gf(Dt.api,n.target,yl)?.replace(/ Nothing was written\.$/,""),On=[[En,Sr],["MAX_TOTAL_EXCEEDED",Or],["STORAGE_EXCEEDED",lo],["EMAILS_EXCEEDED",ot],[Uf,fo]].flatMap(([ke,Ue])=>Ue!==void 0?[{code:ke,message:Ue}]:[]);if(y.dryRun){for(let yi of On)s(` ${Ln(yi)}`);vt.push(...On);let ke=St&&Me?tp(Me.ofRun.senders,A):[],Ue=np(ke);Ue!==void 0&&s(Ue);let xe=ps(A,te);Wt={totalRows:A.totalRows,storageBytes:A.storageBytes,...xe>0?{automationBytes:xe}:{},objects:A.objects,...A.leftOut?{leftOut:A.leftOut}:{},...mt!==void 0?{emails:mt}:{},...nn!==void 0?{emailsUncounted:nn}:{},...ke.length>0?{emailSendersOfNothingWritten:ke}:{}};return}if(On.length>0){let ke=Ue=>`${Ue} Nothing was written.`;throw wr=On.slice(1).map(({code:Ue,message:xe})=>({code:Ue,message:ke(xe)})),new Pe(On[0].code,ke(On[0].message))}h!==void 0&&!n.rehearse&&$u({action:"forge_execute",orgId:h,operationId:w},{mb:$e.estimateMB,rowBytes:Df(A)})},fi=n.dryRun||n.rehearse?void 0:await Fh(()=>Lt.identity(),"sandforge clone");s(`
918
+ 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 so=y=>y.apiCalls===void 0?y:{...y,apiCalls:y.apiCalls+rt},io=(y,A,F={},N)=>({tool:"sandforge-clone",version:1,source:n.source,target:n.target,...h?{targetOrgId:h}:{},...n.tables?{objects:n.tables}:o?{wholeOrg:!0}:n.roots?{roots:gR(n.roots,Y)}:{record:n.record},dryRun:n.dryRun,...im(n),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:zs(Y,Ce),...le?{sample:Rm(le)}:{},targetAutomation:Me?.ofRun.read?{...De,deliverability:Me.ofRun.read.reading}:De,...O?{mutedAutomation:O}:n.dryRun?da(V):{},...se?{mutePlannedAgain:se}:{},..._e(),removalRisks:Xt,targetGaps:ka(ye,Ot),...jR(n.dryRun,ye,y.gaps,C),...Ie.length>0?{neutralizedUpsertKeys:Ie}:{},result:{...N?{status:N}:{},...$R(y,n.readCeiling),...fi?{runUserId:fi}:{}},...n.dryRun&&Wt!==void 0?{writePlan:Wt}:{},...Ac(),...n.dryRun?Pi(vt):{},elapsedMs:Fe(t,A.getTime()),finishedAt:A.toISOString(),...oe&&yn?{journal:oe}:{},...hi()!==void 0?{part:hi()}:{},...mi.length>0?{bulkJobsPastMute:mi}:{},...F}),gw=y=>{let A=L?.question;return{tool:"sandforge-clone",version:1,source:n.source,target:n.target,dryRun:!0,...im(n),files:n.files!==void 0,graph:zs(Y,Ce),result:{wouldInsertCount:Wt?.totalRows??y.totalRows,failedCount:0},...Wt!==void 0?{writePlan:Wt}:{},targetAutomation:Me?.ofRun.read?{...De,deliverability:Me.ofRun.read.reading}:De,...da(V),...se?{mutePlannedAgain:se}:{},removalRisks:Xt,targetGaps:ka(ye,Ot),wholeOrg:{...y.sample?{sample:Rm(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:A?.managedPackages??[],...A?.contactPointsBlanked!==void 0?{contactPointsBlanked:A.contactPointsBlanked}:{},...A?.carried?{carried:A.carried}:{},...A&&Wt&&vt.length===0?{question:mm(wm(A,Wt,n.target,le))}:{}},...Ac(),..._e(),...Pi(vt),elapsedMs:Fe(t)}},wn,yr,Ac=()=>{let y=n.dryRun?Ze?.estimate:yr??wn;return y!==void 0?{checkpoint:y}:{}},pi=async()=>{if(!(!v||!wn||yr)){try{yr=await v.settle(wn,mn)}catch(y){yr=wn,s(`warning: the checkpoint '${wn.name}' taken before the run, which wrote nothing, could not be deleted (${Q(y)}): delete it with ${Gt("checkpoint")} delete --org ${n.target} --checkpoint ${wn.checkpointId}`)}for(let y of Yd(yr))s(y)}},yn,Ft;if(H&&h!==void 0){if(oe&&n.resume)await H.resumingAt(oe),Ft=(await H.headAt(oe))?.journalId;else{Ft=`sandforge-clone-${new Date(t).toISOString().replace(/[:.]/g,"-")}-${Qs().slice(0,8)}`,oe=H.pathOf(Ft);let y=Is(oe,{journalId:Ft,ranFrom:"commandLine",target:n.target});"lock"in y&&(e.journalLock=y.lock),await H.begin(Ft,h,new Date,{sourceOrgId:n.source,fingerprint:U,targetSalesforceOrgId:h,...n.record?{recordId:n.record}:{},...n.muteAutomation?{muteAutomation:!0}:{},...n.files?{files:n.files}:{},startedWith:{graph:Y,config:ce}},fi)}yn=H.openAt(oe),s(Kt()?`journal: ${oe}`:`journal: ${oe} (--resume ${Ar(oe)} takes the run up if it stops)`)}let hi=()=>yn&&yn.partCount>0?yn.partCount-1:void 0,mw=async()=>{if(!n.sample||n.dryRun||n.resume||Ft===void 0)return;let y=rd(P,Ft);if(X&&Yt(y)&&!Yt(X.dir))try{Pm(y,X.dir);return}catch{}await Kp(y)},br=async(y,A)=>{if(!H||!oe||!yn)return;yn.close();let F=oe;try{!A&&ge?await H.stopAt(F,ge.status,ge.forgeId):!A&&!n.resume?(Hs(F,{force:!0}),Hs(F.replace(/\.ndjson$/,".end.json"),{force:!0}),await mw()):await H.stopAt(F,y,`${Ft??"run"}#${hi()??0}`)}catch(N){process.stderr.write(`The journal ${F} could not be ended (${Q(N)}).
919
+ `)}finally{e.journalLock?.release()}},jc;if(n.sample){let y=n.sample,A=X;if(X&&!n.dryRun&&Ft!==void 0)try{A=await Hp(X,P,Ft)}catch(x){await br("failure",!1),process.stderr.write(`The plan of --fit-plan ${X.dir} could not be moved beside the run's journal (${Q(x)}): keep it in ${Ys(P,"forge-samples")}, where its dry run put it. Nothing was written.
920
+ `),process.exit(1)}if(A)s(`sample: takes up the plan ${A.dir}, drawn ${A.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(tO(Y,y.options,n.source));let x=n.dryRun?void 0:await zp(P,D,new Date).catch(()=>{});x instanceof dr&&s(` a dry run drew a plan of this setup at ${x.manifest.drawnAt}: this run draws its own; --fit-plan ${x.dir} writes that one's records instead`)}let F=ys({firing:Ii(Ge,void 0,dt).firing},(x,te)=>dt(x,te)).perRecord,N=A||n.resume?void 0:await Un(gr(l,n.source)).catch(Se);jc={options:Bm(y),budget:async()=>{let x=await ls(Yn).catch(Se),te="unread"in x?await Un(Lt).catch(Se):x.dailyApiRequests,$e="unread"in x?void 0:x.dailyBulkApiBatches;return UR({storage:x,sample:y,target:n.target,automation:F,allowances:{...te?{requests:te}:{},...$e?{bulkBatches:$e}:{},sentBefore:Xn().target,updatedAfterInsert:[...$t]}})},keepAt:n.dryRun||Ft===void 0?Up(P,D):rd(P,Ft),fingerprint:D,...A?{plan:A}:{},...N&&"remaining"in N?{sourceRequestsLeft:N.remaining}:{},onProgress:oO(s)}}let Et,ww=ER(Y),gi=new pr(Pt),$c=!1,ao=y=>{if(!n.summary)return;let A=mc(n.summary,y);A&&!$c&&($c=!0,process.stderr.write(`The summary could not be written to ${n.summary} (${A}).
921
+ `))},vc=-1,yw=()=>{let y=gi.summarySoFar();if(!y)return;let A=y.successCount+y.linkedCount+y.updatedCount+y.failedCount;A!==vc&&(vc=A,ao(io(so(y),new Date,{running:!0})))};bt.executor=gi,await Rt(()=>br("cancelled",!1));let co,mi=[],bw,Ec=()=>bw??=wk(tn,n.target,s).then(y=>{mi=y.map(({objectApiName:A,jobId:F})=>({objectApiName:A,...F?{jobId:F}:{}}))}),Rw=async y=>{if(await hw(y),y.dryRun||n.dryRun)return;if(v&&Ze&&!wn){let N=Ze,x=await Hf(()=>v.take(N.ask,N.estimate,{signal:pt.signal}));if("stop"in x)throw x.stop.code!==En?new ri(Qd(x.stop)):new Pe(En,Qd(x.stop));wn=x.checkpoint;for(let te of Zg(x.checkpoint,n.target,ue))s(te)}if(!V?.prepared||co)return j;let A=await V.prepared.acquire(`sandforge clone ${t}`).catch(async N=>{if(!Dr(N))throw N;return S({outcome:"stopped",code:N.code,context:u().context()}),await pi(),Ye(N.refusal)});co=A,O=A.outcome;let F=Me?.afterLease(A.outcome,n.acceptEmails,V.plan?{plan:V.plan,writes:Z}:void 0);if(F)throw new Pe(F.code,F.message);return{...j,lease:{assigned:A.outcome.assigned.length,giveBack:async()=>(await Ec(),A.release())}}};try{let y=await gi.execute(Y,n.source,n.target,A=>{let F=ww(A);F&&s(F),n.summary&&uk.has(A.status)&&yw()},uO({...o?jb(n,ce,Y,Bt,A=>de.personalFields(A),jc):n.tables?Ob(n,ce,Y,Bt,A=>de.personalFields(A)):km(n,Y,Bt,A=>de.personalFields(A),gt),beforeWrite:Rw},yn)).finally(async()=>{if(co){await Ec(),O=await co.release();for(let A of rr(O,n.target))s(A)}});Et=so(y),await pi(),n.pageSize!==void 0&&s(`read in pages of ${n.pageSize}: ${xt.statements} statement(s) through the org's cursor, ${xt.pages} page(s) answered`)}catch(y){if(y instanceof cd){let ot=gw(y.dryRun);n.json?process.stdout.write(`${JSON.stringify(ot,null,2)}
922
+ `):console.log(`
923
+ done in ${ot.elapsedMs}ms`),vt.length>0&&process.exit(1);return}(y instanceof ri||y instanceof oi)&&(S({outcome:"stopped",code:Hi,context:u().context()}),await br("cancelled",!1),s(y.message),process.exit(Fr(at??"SIGINT"))),await pi();let A=y instanceof Pe?y:n.sample?ms(y,n.resume?"resume":"draw"):void 0,F=y instanceof xn?y:void 0,N=A??F,x=N?void 0:_p(y),te=x?Vi(x):void 0,$e=te?Ji(te):[],qe=at!==void 0||y instanceof Re,bn=N?"stopped":qe?_u(x,$e):"failure";S({outcome:bn,...N?{code:N.code}:bn==="stopped"?{code:Du}:{},...te?{objects:$e,...m?{source:{origin:"org",orgId:m}}:{},carried:Yi(te)}:{},...Qi(x?.contactPoints),context:u().context(x?.decisionsApplied)});let Dt=x!==void 0&&x.successCount+x.updatedCount+x.linkedCount>0;if(await br(qe?"cancelled":"failure",Dt),N){let ot={code:N.code,message:N.message,...A?.sample?{sample:A.sample}:{}};Ye(ot,A?wr:[],Om(N.code))}let et=x;if(et&&(at!==void 0||y instanceof Re)){let ot=io(so(et),new Date,{interrupted:!0});if(ao(ot),n.json)process.stdout.write(JSON.stringify(ot,null,2)+`
924
+ `);else{console.log("");for(let mt of hm(et,n.dryRun,n.readCeiling))console.log(mt)}s(lk(n.summary)),process.exit(Fr(at??"SIGINT"))}throw et&&ao(io(so(et),new Date,{error:Q(y)})),y}finally{e.release?.()}await br("success",!0);let Ic=Vi(Et),uo=xo(Et);S({outcome:uo,objects:Ji(Ic),...m?{source:{origin:"org",orgId:m}}:{},carried:Yi(Ic),...Qi(Et.contactPoints),context:u().context(Et.decisionsApplied)});let xc=new Date,Ow=Fe(t,xc.getTime()),Pc=io(Et,xc,{},uo);ao(Pc);let wi;if(n.remapCsv){let y=["sourceId,targetId"];for(let[A,F]of Object.entries(Et.remapTable))y.push(`"${A.replace(/"/g,'""')}","${F.replace(/"/g,'""')}"`);try{Cm(n.remapCsv,y.join(`
925
+ `)+`
926
+ `,{encoding:"utf8",flag:"wx"}),s(`remap-csv: wrote ${Object.keys(Et.remapTable).length} mappings to ${n.remapCsv}`)}catch(A){wi=A?.code==="EEXIST"?`--remap-csv refuses to overwrite existing file: "${n.remapCsv}"`:`--remap-csv ${n.remapCsv} could not be written: ${Q(A)}`}}if(n.json)process.stdout.write(JSON.stringify(Pc,null,2)+`
927
+ `);else{console.log(""),console.log(`status: ${uo}`);let y=(V?.plan?.assign.length??0)>0;for(let A of hm(Et,n.dryRun,n.readCeiling,y))console.log(A);if(Et.roots){console.log("");let A={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 F of wR(Et,A))console.log(F)}if(Et.sample){console.log("");for(let A of eO(Et.sample,n.source))console.log(A)}console.log(`
928
+ done in ${Ow}ms`)}wi!==void 0&&(process.stderr.write(`${wi}: the summary names what the run created.
929
+ `),process.exit(1));let Fc=fu(uo,n.failOnPartial||o);Fc!==0&&process.exit(Fc)}function Sk(r){return r instanceof cu?{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]??"")&&(Gh(),bk().catch(r=>{let e=Sk(r);process.stderr.write(`${e.line}
930
+ `),process.exit(e.exitCode)}));export{wd as a,Fe as b,eo as c,Vd as d,Jg as e,Qg as f,Yg as g,Xg as h,Jd as i,Us as j,Qd as k,Zg as l,Yd as m,PT as n,Xd as o,em as p,ib as q,ub as r,Mm as s,fb as t,pb as u,hb as v,mb as w,wb as x,yb as y,Rb as z,Ob as A,dc as B,kb as C,Tb as D,sm as E,im as F,Ab as G,jb as H,$b as I,vb as J,Db as K,Ub as L,Gb as M,Hb as N,Kb as O,lm as P,fm as Q,Jb as R,Xb as S,eR as T,oR as U,sR as V,iR as W,aR as X,ec as Y,Pj as Z,cR as _,uR as $,rc as aa,Wm as ba,fR as ca,pm as da,pR as ea,hR as fa,hm as ga,gR as ha,wR as ia,RR as ja,OR as ka,kR as la,SR as ma,TR as na,AR as oa,jR as pa,$R as qa,vR as ra,ER as sa,IR as ta,xR as ua,CR as va,NR as wa,hr as xa,mm as ya,wm as za,ym as Aa,ro as Ba,BR as Ca,LR as Da,_m as Ea,WR as Fa,DR as Ga,bm as Ha,UR as Ia,uc as Ja,XR as Ka,Rm as La,ZR as Ma,eO as Na,tO as Oa,oO as Pa,Om as Qa,iO as Ra,Km as Sa,aO as Ta,km as Ua,dO as Va,cO as Wa,uO as Xa,lO as Ya,ai as Za,fO as _a,fn as $a,oo as ab,hO as bb,gO as cb,bO as db,lc as eb,OO as fb,Fj as gb,fc as hb,Tm as ib,SO as jb,Sc as kb,TO as lb,AO as mb,jO as nb,Ym as ob,$O as pb,IO as qb,Tc as rb,pn as sb,Vs as tb,NO as ub,sc as vb,LO as wb,WO as xb,Js as yb,hc as zb,rw as Ab,DO as Bb,_O as Cb,qO as Db,gc as Eb,Cj as Fb,UO as Gb,GO as Hb,ci as Ib,ui as Jb,li as Kb,HO as Lb,sw as Mb,iw as Nb,aw as Ob,dw as Pb,VO as Qb,JO as Rb,uw as Sb,mc as Tb,QO as Ub,XO as Vb,ZO as Wb,ek as Xb,ti as Yb,ok as Zb,dk as _b,ck as $b,lk as ac,Em as bc,Im as cc,fk as dc,pk as ec,mk as fc,wk as gc,bk as hc,Sk as ic};