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
@@ -4,10 +4,10 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{c as er}from"./chunk-LOO42EW5.mjs";import"./chunk-4RNP65FV.mjs";import"./chunk-SES5HPBZ.mjs";import"./chunk-FZF6FB65.mjs";import"./chunk-LJNRN7MY.mjs";import"./chunk-QBYK5XIT.mjs";import"./chunk-3OKDWZ32.mjs";import"./chunk-YXOPKGDX.mjs";import"./chunk-J3FJ3BWE.mjs";import"./chunk-A7YP27GQ.mjs";import"./chunk-OUWR5M5G.mjs";import"./chunk-H4OBZIX3.mjs";import"./chunk-VKA5OZBJ.mjs";import"./chunk-LU7M5URW.mjs";import"./chunk-FCZDWGQI.mjs";import{q as Lt}from"./chunk-PP7PJXRJ.mjs";import"./chunk-INIQ23K6.mjs";import"./chunk-RC25QQVF.mjs";import{a as go,b as yo,c as _e,d as Ot,e as wo,f as bo,g as ko,h as Ro,i as Ao,j as So,k as _o,l as qo,m as qe,n as Mt,o as Ft,p as ze,q as zo,r as Oe,s as Te,t as Go}from"./chunk-5C7LQXYS.mjs";import"./chunk-BRN42U26.mjs";import"./chunk-VPGX5Z5D.mjs";import"./chunk-55VBV2WK.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-TFGJDZFE.mjs";import"./chunk-G6IYOZEH.mjs";import"./chunk-45375WT5.mjs";import"./chunk-DCJBP3LE.mjs";import"./chunk-YV7JYHJP.mjs";import"./chunk-2JRVBXJL.mjs";import"./chunk-GMY5427L.mjs";import{c as Kt}from"./chunk-NMF55UBQ.mjs";import{Xa as jt,a as vo,d as It,e as Uo,f as Ho,g as Ko,h as Xo,i as Qo,j as Yo,k as xt,l as Jo,m as Vo,q as we}from"./chunk-WQO7RXEB.mjs";import{a as To}from"./chunk-RY7WUJXH.mjs";import"./chunk-UX4AOSMU.mjs";import"./chunk-UZMLPKW6.mjs";import{a as Wo}from"./chunk-2METQHGG.mjs";import{c as Yt,d as Jt,f as Vt}from"./chunk-6FARZYMJ.mjs";import"./chunk-WB2RIVO3.mjs";import"./chunk-W6SLQZKQ.mjs";import"./chunk-RIIJJRGF.mjs";import"./chunk-EYFP3NA6.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-4BQPAVMP.mjs";import{b as st,e as Xt}from"./chunk-RKTFFCNS.mjs";import{b as Zt,c as en,d as xe,e as tn,f as co,g as uo,h as lo,i as po,j as fo,k as ho,l as mo,m as vt}from"./chunk-SAHGDSZQ.mjs";import{h as No,i as Do,k as Bo}from"./chunk-32ZB5ICW.mjs";import"./chunk-TG52WNGV.mjs";import"./chunk-CSSOLHE3.mjs";import"./chunk-HGJFATSI.mjs";import{h as Oo,i as Io,j as xo,k as jo,l as Ct,m as Lo,n as $o}from"./chunk-TEIBWMJM.mjs";import{a as Eo,b as Tt,c as Et,d as Po,e as Co,f as Mo,g as Fo,h as Pt}from"./chunk-BWWQXU2B.mjs";import{d as zn}from"./chunk-T63U4OZJ.mjs";import"./chunk-5EESNYE3.mjs";import"./chunk-QAXKUEJT.mjs";import"./chunk-JKFCGYJE.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-YDXMTWAT.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-EINEGS6E.mjs";import{d as qn}from"./chunk-QIRO4HTE.mjs";import"./chunk-RM5G4IP6.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-B5A4JHNN.mjs";import"./chunk-YGE4AUXG.mjs";import"./chunk-C2MHMI7U.mjs";import"./chunk-RFD6NPWJ.mjs";import"./chunk-SF52ZSIV.mjs";import{a as Je}from"./chunk-AL4C3GFT.mjs";import"./chunk-P6A22FMQ.mjs";import"./chunk-5LFSFYFJ.mjs";import{b as rt,c as Ie}from"./chunk-XZRON54U.mjs";import"./chunk-3EOIAC2M.mjs";import{b as Gn,c as Wn,g as Un}from"./chunk-AIUAEBHR.mjs";import{Cb as to,Ib as At,Lc as ao,Mc as St,Sa as Qn,Za as bt,_b as no,fb as Yn,hb as Jn,i as Hn,ib as kt,j as yt,kb as Vn,lc as oo,mc as ro,ob as Rt,p as ve,q as Kn,qb as Be,qc as so,r as Xn,rb as Zn,t as De,ub as eo,xc as ye,yc as io}from"./chunk-O3ZQSWDN.mjs";import{h as Rn,i as An,k as Sn}from"./chunk-DNE7JI3A.mjs";import{a as ot,b as Ut}from"./chunk-CI2O7WBH.mjs";import{q as wt}from"./chunk-5T3LFDJ5.mjs";import"./chunk-VV3B6IC3.mjs";import{a as de}from"./chunk-4TLYUZD5.mjs";import"./chunk-AX3YF7SC.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-Q7TLC3I2.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-JBOGAUGH.mjs";import{b as Bn,d as ht,e as _n,f as mt,g as gt,h as Se}from"./chunk-4N425UJC.mjs";import"./chunk-MS4FJDFD.mjs";import"./chunk-TWYNQ2OO.mjs";import{b as Ht,d as Qt,f as it,h as Zo}from"./chunk-LCDPCUXS.mjs";import"./chunk-TQ2TQHTT.mjs";import{a as xn,b as ut,c as lt,f as jn,h as Ln,j as $e,l as $n,m as Nn}from"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import{a as vn}from"./chunk-EADHKH3A.mjs";import{e as kn}from"./chunk-FG4Y4ZVL.mjs";import{$ as mn,Y as pn,Z as fn,_ as hn,a as nn,b as V,c as Le,d as on,da as Ae,f as rn,fa as gn,g as sn,ia as yn,ja as wn,ka as bn,m as at,n as an,o as cn,p as dn,q as ue,r as le,s as ct,t as Re,u as un,z as ln}from"./chunk-Z354SAEF.mjs";import{a as je}from"./chunk-TZE3Y7IQ.mjs";import{b as ee}from"./chunk-CA5NAXSU.mjs";import"./chunk-PC247GKX.mjs";import{b as Ne,c as pt,j as ft,k as Dn}from"./chunk-THYQOG24.mjs";import"./chunk-UNDIBZWG.mjs";import{a as he,j as dt,l as On,o as Tn,p as En,q as Pn,t as Cn,u as Mn,v as Fn,w as In}from"./chunk-ICIYL45C.mjs";import"./chunk-JFVY66BS.mjs";import"./chunk-GUYEXPJ4.mjs";import"./chunk-TUACWKIH.mjs";import{Ec as et,Fc as ge,Hc as tt,Ic as _t,Kc as nt,Mc as qt,Sc as zt,Uc as Gt,Y as Ve,fe as Fe,id as Wt,vc as Ze,yc as Bt}from"./chunk-CRPLDXJU.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";var tr=3,Rr="the source changed since the plan: plan again";function sr(u,e){return{holds:[...u.links.filter(t=>t.kind==="holds"),...u.requiredOfParents,...u.outward.filter(t=>t.required)],kept:e}}function nr(u,e){return typeof u!="string"||u===""?!1:e===void 0||e!==null&&u.startsWith(e)}function ir(u,e,t){let n=new Map(t.map((s,i)=>[s,i])),o=new Set(e),r={links:[],outward:[],requiredOfParents:[]};for(let[s,i]of u)for(let a of ko(s,i))for(let c of a.targets.filter(d=>u.has(d))){let d=a.polymorphic?{prefix:u.get(c)?.keyPrefix??null}:{},m={objectApiName:s,field:a.field,parent:c,...d};if(!o.has(s))o.has(c)&&a.required&&r.requiredOfParents.push({...m,kind:"holds"});else if(!o.has(c))r.outward.push({...m,required:a.required});else if(a.required)r.links.push({...m,kind:"holds"});else if(c===s)r.links.push({...m,kind:"selfReference"});else{let p=(n.get(c)??0)<(n.get(s)??0);r.links.push({...m,kind:p?"holds":"owed"})}}return r}function ar(u,e){let t=new Set(u),n=new Set(e.links.filter(o=>o.kind!=="holds").map(o=>o.objectApiName));return(o,r)=>t.has(o)&&(r==="insert"||r==="update"&&(n.has(o)||Ae[o]!==void 0))}function cr(u,e,t){return typeof u.unread=="string"?{perRecord:[],notCounted:[],unread:u.unread}:po(Fe(u,e,t),t)}function Ar(u){let e=new Map(u.order.map((t,n)=>[t,n]));return u.order.map(t=>{let n=u.rows.get(t)??[],o=u.lookups.links.filter(i=>i.objectApiName===t),r=u.lookups.outward.filter(i=>i.objectApiName===t),s={name:t,rows:n,at:new Map(n.map((i,a)=>[i.Id,a])),heldBefore:[],heldAfter:[],loose:[],named:[],roots:[],followers:[],persons:new Set(t===ue||t===le?n.flatMap((i,a)=>i[Ot]===!0?[a]:[]):[])};return n.forEach((i,a)=>{let c=[],d=[],m=[];for(let p of o){let l=i[p.field];if(!nr(l,p.prefix))continue;let g={link:p,id:l};p.kind!=="holds"?m.push(g):(e.get(p.parent)??0)<(e.get(t)??0)?c.push(g):d.push(g)}s.heldBefore.push(c),s.heldAfter.push(d),s.loose.push(m),s.named.push(r.flatMap(p=>{let l=i[p.field];return nr(l,p.prefix)?[{parent:p.parent,id:l}]:[]})),(c.length>0?s.followers:s.roots).push(a)}),s})}function or(u,e){let t=new Map(u.map(r=>[r.name,r])),n=new Map,o=[...e].flatMap(([r,s])=>[...s].map(i=>({name:r,id:i})));for(let r=o.pop();r;r=o.pop()){let s=t.get(r.name),i=s?.at.get(r.id);if(!s||i===void 0)continue;let a=n.get(r.name)??new Set;if(n.set(r.name,a),!a.has(i)){a.add(i);for(let c of[...s.heldBefore[i],...s.heldAfter[i]])o.push({name:c.link.parent,id:c.id})}}return n}function rr(u){return`${u} record${u===1?"":"s"}`}function Sr(u,e){return[...u.parentIds].every(([t,n])=>{let o=new Set(e.get(t)?.ids??[]);return n.every(r=>o.has(r))})}async function dr(u){let{budget:e,room:t,mode:n,parents:o,maxRecords:r}=u,s=Ar(u),i=b=>{let k=n.caps?.[b]??n.all;return k===void 0?void 0:Math.max(1,Math.floor(k))},a=s.some(b=>b.heldAfter.some(k=>k.length>0)),c=new Map;for(let b of s){if(b.name!==ge)continue;let k=b.rows.filter(M=>M[wo]===!0);k.length>0&&c.set(b.name,new Set(k.map(M=>M.Id)))}let d=or(s,c),m=b=>{let k={kept:new Map,ids:new Map,cut:new Map},M=new Set;for(let I of s){let P=d.get(I.name)??M,z=i(I.name),C=I.roots.filter(W=>!P.has(W)),$=C.length===0?0:Math.max(1,Math.round(b*Math.min(C.length,z??1/0))),D=vt(C.length,$).map(W=>C[W]),j=new Map;for(let W of I.followers){if(P.has(W))continue;let pe=I.heldBefore[W].find(fe=>!k.ids.get(fe.link.parent)?.has(fe.id));pe?j.set(W,pe.link):D.push(W)}D.sort((W,pe)=>W-pe);let oe=I.name===le?D.filter(W=>I.persons.has(W)):[],Y=oe.length>0?D.filter(W=>!I.persons.has(W)):D,G=z===void 0?Y.length:Math.max(0,z-P.size-oe.length),J=Y.length>G?vt(Y.length,G).map(W=>Y[W]):Y,ce=new Set([...P,...oe,...J]);k.kept.set(I.name,ce),k.ids.set(I.name,new Set([...ce].map(W=>I.rows[W].Id))),k.cut.set(I.name,j)}if(!a)return k;for(let I=!0;I;){I=!1;for(let P of s){let z=d.get(P.name)??M,C=k.kept.get(P.name)??new Set;for(let $ of[...C]){if(z.has($))continue;let D=[...P.heldAfter[$],...P.heldBefore[$]].find(j=>!k.ids.get(j.link.parent)?.has(j.id));D&&(C.delete($),k.ids.get(P.name)?.delete(P.rows[$].Id),k.cut.get(P.name)?.set($,D.link),I=!0)}}}return k},p=b=>{let k=new Map;for(let M of s){let I=0;for(let P of b.kept.get(M.name)??[])M.loose[P].some(C=>b.ids.get(C.link.parent)?.has(C.id))&&I++;I>0&&k.set(M.name,I)}return k},l=(b,k)=>{let M=new Map,I=0;for(let C of s){let $=b.kept.get(C.name)??new Set,D=0;for(let j of $)C.persons.has(j)&&D++;M.set(C.name,$.size),I+=bt(C.name,{rows:$.size,personAccounts:D})}for(let[C,{records:$,personAccounts:D}]of k)M.set(C,(M.get(C)??0)+$),I+=bt(C,{rows:$,...D!==void 0?{personAccounts:D}:{}});let P=p(b),z=fo(t,(C,$)=>{let D=M.get(C)??0;return $==="insert"||Ae[C]!==void 0?D:P.get(C)??0});return{records:[...M.values()].reduce((C,$)=>C+$,0),bytes:I,roomBytes:z,requests:Vn([...M.values()].map(C=>({rows:C})))}},g=new Map;for(let b of s)for(let k of b.named)for(let{parent:M,id:I}of k){let P=g.get(M)??new Set;g.set(M,P),P.add(I)}let w=[...g.values()].reduce((b,k)=>b+k.size,0),f=b=>{let k=new Map,M=0;for(let z of s)for(let C of b.kept.get(z.name)??[])for(let{parent:$,id:D}of z.named[C]){let j=k.get($)??new Set;k.set($,j),j.has(D)||M++,j.add(D)}let I=w>0?M/w:0,P=new Map;for(let[z,{ids:C,personAccounts:$}]of o){let D=Math.max(0,C.length-(g.get(z)?.size??0)),j=Math.min(C.length,(k.get(z)?.size??0)+Math.ceil(D*I));j!==0&&P.set(z,{records:j,...$!==void 0?{personAccounts:Math.ceil($*j/C.length)}:{}})}return P},R=b=>new Map(b.added.map(k=>{let M=b.personAccounts.get(k);return[k,{records:b.parentIds.get(k)?.length??0,...M!==void 0?{personAccounts:M}:{}}]})),y=b=>b.bytes+b.roomBytes<=e.bytes,L=b=>e.runRequests===void 0||b.requests<=e.runRequests,v=b=>r===void 0||b.records<=r,B=b=>y(b)&&L(b)&&v(b),K=b=>y(b)?L(b)?"maxTotal":"apiRequests":e.terms.limitedBy,O=b=>y(b)?L(b)?{bound:"maxTotal",records:b.records,allowed:r??0}:{bound:"apiRequests",requests:b.requests,allowed:e.runRequests??0}:{bound:"storage",takesMB:(b.bytes+b.roomBytes)/1048576,fitsMB:e.bytes/1048576},A=b=>{if(!y(b)){let k=io((b.bytes+b.roomBytes)/1048576,e.bytes/1048576);return`${k.over} MB`+(b.roomBytes>0?", room for what the org's automation creates under them included":"")+`, past the ${k.bound} MB that fit`}return L(b)?`${rr(b.records)}, past the ${r??0} the run may write`:`about ${b.requests} API requests, past the ${e.runRequests??0} that leave the org a tenth of its daily requests`},F=b=>new Map(s.map(k=>[k.name,[...b.kept.get(k.name)??[]].sort((M,I)=>M-I).map(M=>k.rows[M])])),E=(b,k,M,I,P,z)=>{let C=s.map(j=>{let oe=k.cut.get(j.name)??new Map,Y=new Map;for(let J of oe.values()){let ce=`${J.field}
8
- ${J.parent}`,W=Y.get(ce)??{field:J.field,parent:J.parent,count:0};Y.set(ce,{...W,count:W.count+1})}let G=k.kept.get(j.name)?.size??0;return{objectApiName:j.name,inSource:j.rows.length,kept:G,cutSpread:j.rows.length-G-oe.size,cutWithParent:[...Y.values()].sort((J,ce)=>ce.count-J.count)}}),$=new Map,D=(j,oe,Y)=>{let G=`${j}
9
- ${oe}
10
- ${Y}`,J=($.get(G)?.count??0)+1;$.set(G,{objectApiName:j,field:oe,count:J,why:Y})};for(let j of s)for(let oe of k.kept.get(j.name)??[])for(let Y of j.loose[oe])k.ids.get(Y.link.parent)?.has(Y.id)||D(j.name,Y.link.field,Y.link.kind==="owed"?"owed":"selfReference");for(let j of P?.namingSelected??[])j.required||k.ids.get(j.target)?.has(j.id)||D(j.objectApiName,j.field,"onParent");return{heldBy:I,...z?{cannotFit:z.words}:{},kept:F(k),...P?{walk:P}:{},report:{mode:n,heldBy:I,...z?{cannotFit:z.said}:{},budget:{...ho(e,M.roomBytes,t),...I==="apiRequests"?{limitedBy:"apiRequests"}:{}},...b!==void 0?{share:b}:{},objects:C,emptied:[...$.values()],parents:P?P.added.map(j=>({objectApiName:j,records:P.parentIds.get(j)?.length??0})):[...o].map(([j,{ids:oe}])=>({objectApiName:j,records:oe.length})),records:M.records,estimateMB:M.bytes/1048576}}},Q={words:Rr,said:{why:"sourceChanged"}},re=b=>({words:`with these caps the plan takes ${A(b)}: lower them, or fit by share`,said:{why:"caps",over:O(b)}}),Z=Object.keys(n.caps??{}).find(b=>!s.some(k=>k.name===b)),x=s.reduce((b,k)=>Math.max(b,Math.min(k.roots.length,i(k.name)??1/0)),0),H=m(1),N=l(H,f(H));if(Z!==void 0)return E(void 0,H,N,"caps",void 0,{words:`the plan selects no ${Z}: a cap holds an object it selects`,said:{why:"capNotSelected",object:Z}});if(s.some(b=>b.rows.length>(u.planned.get(b.name)??0)))return E(void 0,H,N,e.terms.limitedBy,void 0,Q);let be=n.all!==void 0||Object.keys(n.caps??{}).length>0,te=n.share===!0||!be,X=b=>{let k=m(b/x);return l(k,f(k))};if(s.every(b=>H.kept.get(b.name)?.size===b.rows.length)&&B(N))return E(te?1:void 0,H,N,"whole",void 0);if(x===0)return E(void 0,H,N,e.terms.limitedBy,void 0,Q);let q=x;if(!B(N)){if(!te)return E(void 0,H,N,K(N),void 0,re(N));if(q=mo(x,b=>B(X(b))),q===0){let b=m(1/x),k=l(b,f(b));return E(1/x,b,k,K(k),void 0,{words:`the least it can be cut to \u2014 one record of each object with none to follow, and what follows them, ${rr(k.records)} \u2014 takes ${A(k)}`,said:{why:"least",over:O(k)}})}}let ie=q<x?K(X(q+1)):be?"caps":e.terms.limitedBy,se=b=>te?b/x:void 0;if(o.size===0){let b=m(q/x);return E(se(q),b,l(b,new Map),ie,void 0)}for(let b=1;b<=tr;b++){let k=m(q/x),M=await u.walk(F(k));if(!Sr(M,o)){let C=l(k,R(M));return E(se(q),k,C,ie,void 0,Q)}let I=M.namingSelected.filter(C=>C.required&&s.find($=>$.name===C.target)?.at.has(C.id)===!0&&!k.ids.get(C.target)?.has(C.id));if(I.length>0){for(let{target:C,id:$}of I){let D=c.get(C)??new Set;c.set(C,D),D.add($)}d=or(s,c);continue}let P=l(k,R(M));if(B(P))return E(se(q),k,P,ie,M);if(ie=K(P),!te)return E(void 0,k,P,ie,M,re(P));if(q===1)return E(se(q),k,P,ie,M,{words:"the least it can be cut to, with the parents its records name, takes "+A(P),said:{why:"least",over:O(P)}});let z=Math.max((P.bytes+P.roomBytes)/Math.max(1,e.bytes),e.runRequests!==void 0?P.requests/Math.max(1,e.runRequests):0,r!==void 0?P.records/Math.max(1,r):0);q=Math.max(1,Math.min(q-1,Math.floor(q/z)))}let ke=m(q/x),Xe=l(ke,f(ke));return E(se(q),ke,Xe,ie,void 0,{words:`could not fit in ${tr} rounds: fit by caps`,said:{why:"rounds"}})}function ur(u,e,t){let{selected:n}=u.scope,o=e.walk?.added??[],r=new Set([...n,...o]),s=new Map(e.walk?.parentIds??[]),i=new Map,a=new Map;for(let f of n){let R=e.kept.get(f)??[];s.set(f,R.map(y=>y.Id)),i.set(f,R.length),u.personAccounts.has(f)&&a.set(f,R.filter(y=>y[Ot]===!0).length)}for(let f of o)i.set(f,e.walk?.parentIds.get(f)?.length??0),u.personAccounts.has(f)&&a.set(f,e.walk?.personAccounts.get(f)??0);let c=new Map([...u.scope.leftEmpty,...e.walk?.leftEmpty??[]].filter(f=>r.has(f.objectApiName)&&!r.has(f.target)).map(f=>[`${f.objectApiName}.${f.fieldApiName}>${f.target}`,f])),{maxDepth:d,maxObjects:m,followedByDefault:p,currencies:l}=u.scope,g=p?.filter(f=>r.has(f.objectApiName)),w=l?.objects.filter(f=>r.has(f));return{...u,objectDescribes:new Map([...u.objectDescribes].filter(([f])=>r.has(f))),autoDiscoveredObjects:o,missingInTarget:u.missingInTarget.filter(f=>r.has(f)),recordCounts:i,totalObjectsScanned:r.size,parentIds:s,personAccounts:a,scope:{maxDepth:d,maxObjects:m,selected:n,parents:o.map(f=>({objectApiName:f,records:i.get(f)??0})),leftEmpty:[...c.values()],standardNeeded:u.scope.standardNeeded.filter(f=>r.has(f.objectApiName)),...g!==void 0&&g.length>0?{followedByDefault:g}:{},...l&&w!==void 0&&w.length>0?{currencies:{...l,objects:w}}:{},fitted:t}}}var Ge=class{deps;eventListeners=[];runningExecutors=[];pendingSkips=new Set;constructor(e){this.deps=e}onEvent(e){return this.eventListeners.push(e),()=>{this.eventListeners=this.eventListeners.filter(t=>t!==e)}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch{}}listObjects(e,t,n){return this.deps.schemaScanner.listObjects(e,t,n)}countObjects(e,t){return this.deps.schemaScanner.countObjects(e,t)}async scanSchemas(e,t,n,o){this.emitEvent({type:"scan-started",timestamp:new Date().toISOString()});let r=await this.deps.schemaScanner.scan(e,t,n.selectedObjects,n.includeStandardObjects,{...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.maxObjects!==void 0?{maxObjects:n.maxObjects}:{},...n.maxRecordsPerObject!==void 0&&n.maxRecordsPerObject>0?{maxRecordsPerObject:n.maxRecordsPerObject}:{},...o?{onProgress:o}:{}});return this.emitEvent({type:"scan-completed",timestamp:new Date().toISOString()}),r}buildGraph(e,t){let n=new Map;for(let[o,r]of e.objectDescribes){let s=r.fields.map(i=>({name:i.name,type:i.type,nillable:i.nillable,referenceTo:i.referenceTo,relationshipName:i.relationshipName}));n.set(o,{name:r.name,fields:s})}return this.deps.graphBuilder.build(n,e.recordCounts,t)}buildCompliance(e,t,n=[]){let o=this.deps.complianceEngine.buildProfile(e,Ao(n,t)),r=this.deps.complianceEngine.generateRules(o);return{profile:o,rules:r}}generatePlan(e,t,n,o){let r=So(t,e.nodes.map(c=>c.objectApiName),n),s={...this.deps.complianceEngine.buildSummary(n),...r.length>0?{notCovered:r}:{}},i=this.deps.planGenerator.generate(e,t,s),a=o?{...i,scope:o}:i;return this.emitEvent({type:"plan-generated",timestamp:new Date().toISOString()}),a}async fitPlan(e,t){let{scan:n,graph:o,plan:r,rules:s,mode:i,budget:a,maxRecords:c,onProgress:d}=t,{schemaScanner:m}=this.deps,p=0,l={describe:x=>e.describe(x),describeGlobal:()=>e.describeGlobal(),query:x=>(p++,e.query(x)),...e.queryMore?{queryMore:x=>(p++,e.queryMore.call(e,x))}:{}},g=r.waves.map(x=>x.objects),w=new Map,f=g.flatMap(x=>xe(x,o.edges).groups.filter(H=>H.length>1));for(let x of new Set(f.flat()))w.set(x,await t.describeLookups?.(x).catch(()=>null)??null);let R=tn(g,o.edges,x=>w.get(x)),{selected:y}=n.scope,L=ir(n.objectDescribes,y,R),v=ar(R,L),B=cr(t.automation,t.mutePlan,v),K=await m.readFitRows(l,n,d),O=await dr({order:R.filter(x=>y.includes(x)),rows:K,planned:n.recordCounts,lookups:L,parents:new Map(n.scope.parents.map(({objectApiName:x})=>{let H=n.personAccounts.get(x);return[x,{ids:n.parentIds.get(x)??[],...H!==void 0?{personAccounts:H}:{}}]})),budget:a,room:B,mode:i,...c!==void 0?{maxRecords:c}:{},walk:x=>m.walkFrom(l,n,x,d)}),A=B.unread!==void 0?{automationUnread:B.unread}:{},F={...O.report,requestsRead:p,...A,...t.mutePlan?{countedMuted:!0}:{},...c!==void 0?{maxTotal:c}:{}},E=new Map([...O.kept].map(([x,H])=>[x,H.map(N=>N.Id)])),Q={heldBy:O.heldBy,report:F,keptIds:E,...A};if(O.cannotFit!==void 0)return{...Q,cannotFit:O.cannotFit};if(O.heldBy==="whole")return Q;let re=ur(n,O,F),Z=this.buildGraph(re,t.batchSize);return{...Q,fitted:{scan:re,graph:Z,plan:this.generatePlan(Z,r.complianceFramework,s,re.scope),run:sr(L,re.parentIds)}}}async executePlan(e,t,n,o,r,s,i,a){let c=Array.from(o.values()).reduce((y,L)=>y+L,0),d=this.isGrappeActive(c),m=`autopilot-${Date.now()}`;d&&this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:m,totalPartitions:e.waves.length,totalRecords:c}}),this.emitEvent({type:"execution-started",timestamp:new Date().toISOString()});let p=this.deps.createExecutor(),l=()=>{},g=r?p.on("node-completed",r):l,w=r?p.on("node-failed",r):l,f=d?this.relayWavesAsPartitions(p,m):l;for(let y of this.pendingSkips)p.skip(y);this.pendingSkips.clear(),this.runningExecutors.push(p);let R;try{R=await p.execute(e,t.edges,n,o,s,i,a)}finally{this.runningExecutors.splice(this.runningExecutors.indexOf(p),1),g(),w(),f()}return this.emitEvent({type:"execution-completed",timestamp:new Date().toISOString()}),d&&this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:m,totalProcessed:R.totalSuccess+R.totalSkipped,totalFailed:R.totalFailure}}),R}relayWavesAsPartitions(e,t){let n=0,o=0,r=e.on("node-completed",a=>{o+=a.successCount+a.failureCount}),s=e.on("node-failed",a=>{o+=a.partialSuccessCount+a.failureCount}),i=e.on("wave-completed",()=>{n++,this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:`${t}-wave-${n}`,percentage:100,processedRecords:o}}),o=0});return()=>{r(),s(),i()}}isGrappeActive(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&this.deps.grappeAdapter&&e>=t.autoActivateThreshold)}generateReport(e,t,n,o,r,s){return this.deps.complianceEngine.generateReport(e,t,n,o,r,s)}latestRunningExecutor(){return this.runningExecutors[this.runningExecutors.length-1]}pause(){this.latestRunningExecutor()?.pause()}resume(){this.latestRunningExecutor()?.resume()}skip(e){let t=this.latestRunningExecutor();if(t){t.skip(e);return}this.pendingSkips.add(e)}};var We=class{build(e,t,n=200){let o=this.extractEdges(e),r=vr(o,new Set(e.keys())),s=this.tarjanSCC(Array.from(e.keys()),r),i=this.resolveCycles(s,r),{order:a,levels:c}=this.topologicalSort(Array.from(e.keys()),r,s),d=this.buildNodes(e,t,a,c,n),m=this.computeStats(d,o,i);return{nodes:d,edges:o,cycles:i,stats:m}}extractEdges(e){let t=[],n=new Set(e.keys());for(let[o,r]of e)for(let s of r.fields){if(s.type!=="reference"||s.referenceTo.length===0)continue;let i=s.referenceTo.filter(d=>n.has(d));if(i.length===0)continue;if(i.length>1){for(let d of i)t.push({from:d,to:o,fieldApiName:s.name,relationshipType:"polymorphic",required:!s.nillable});continue}let a=i[0],c;a===o?c="hierarchical":s.nillable?c="lookup":c="master_detail",t.push({from:a,to:o,fieldApiName:s.name,relationshipType:c,required:!s.nillable})}return t}tarjanSCC(e,t){let n=new Map;for(let s of e)n.set(s,[]);for(let s of t){let i=n.get(s.to);i&&i.push(s.from)}let o={index:0,stack:[],onStack:new Set,indices:new Map,lowLinks:new Map,sccs:[]},r=[...e].sort();for(let s of r)o.indices.has(s)||this.tarjanStrongConnect(s,n,o);return o.sccs}tarjanStrongConnect(e,t,n){n.indices.set(e,n.index),n.lowLinks.set(e,n.index),n.index++,n.stack.push(e),n.onStack.add(e);let o=t.get(e)??[];for(let r of o)if(n.indices.has(r)){if(n.onStack.has(r)){let s=n.lowLinks.get(e)??0,i=n.indices.get(r)??0;n.lowLinks.set(e,Math.min(s,i))}}else{this.tarjanStrongConnect(r,t,n);let s=n.lowLinks.get(e)??0,i=n.lowLinks.get(r)??0;n.lowLinks.set(e,Math.min(s,i))}if(n.lowLinks.get(e)===n.indices.get(e)){let r=[],s;do s=n.stack.pop(),n.onStack.delete(s),r.push(s);while(s!==e);n.sccs.push(r.sort())}}resolveCycles(e,t){let n=[],o=new Set;for(let r of t)r.from===r.to&&r.relationshipType==="hierarchical"&&o.add(r.from);for(let r of o)n.push({objects:[r],strategy:"two_pass",description:`Insert ${r} without self-lookup, update in 2nd pass`});for(let r of e){if(r.length<=1)continue;let s=new Set(r),i=t.filter(d=>s.has(d.from)&&s.has(d.to)&&d.from!==d.to),a,c;r.length===2&&i.some(m=>!m.required)?(a="nullable_lookup",c=`Insert ${r[0]} without ${r[1]} lookup, insert ${r[1]} with ${r[0]} lookup, update ${r[0]}`):(a="upsert_external_id",c="Decompose cycle into waves with upsert + external ID"),n.push({objects:[...r],strategy:a,description:c})}return n}topologicalSort(e,t,n){let o=new Map;for(let l=0;l<n.length;l++)for(let g of n[l])o.set(g,l);let r=n.length,s=new Map;for(let l=0;l<r;l++)s.set(l,new Set);for(let l of t){let g=o.get(l.from),w=o.get(l.to);g!==void 0&&w!==void 0&&g!==w&&s.get(w).add(g)}let i=new Map;for(let[l,g]of s)i.set(l,new Set(g));let a=[],c=new Map;for(;i.size>0;){let l=[];for(let[g,w]of i)w.size===0&&l.push(g);if(l.length===0){for(let g of i.keys())a.push(g),c.has(g)||c.set(g,0);break}l.sort((g,w)=>g-w);for(let g of l){a.push(g);let w=s.get(g)??new Set,f=-1;for(let R of w)f=Math.max(f,c.get(R)??0);c.set(g,w.size===0?0:f+1),i.delete(g);for(let R of i.values())R.delete(g)}}let d=new Map,m=new Map,p=0;for(let l of a){let g=n[l],w=c.get(l)??0,f=[...g].sort();for(let R of f)d.set(R,p),m.set(R,w),p++}for(let l of e)d.has(l)||(d.set(l,p),m.set(l,0),p++);return{order:d,levels:m}}buildNodes(e,t,n,o,r){let s=[];for(let i of e.keys()){let a=t.get(i)??0;s.push({objectApiName:i,recordCount:a,estimatedApiCalls:a===0?0:Math.ceil(a/r),piiFields:[],anonymizationRules:[],status:"pending",progress:0,insertOrder:n.get(i)??0,level:o.get(i)??0,successCount:0,failureCount:0,errors:[],elapsedMs:0,apiCallsUsed:0})}return s.sort((i,a)=>i.insertOrder-a.insertOrder),s}computeStats(e,t,n){return{totalObjects:e.length,totalRelationships:t.length,cycleCount:n.length,maxDepth:Math.max(0,...e.map(o=>o.level)),totalRecords:e.reduce((o,r)=>o+r.recordCount,0),totalEstimatedApiCalls:e.reduce((o,r)=>o+r.estimatedApiCalls,0)}}};function vr(u,e){let t=an(e);return t.length===0?[...u]:[...u.filter(n=>!(n.to===V&&n.fieldApiName==="ActivityId")),...t.map(n=>({from:n.sourceObject,to:n.targetObject,fieldApiName:n.relationshipName,relationshipType:"lookup",required:!0}))]}import{createHash as Or,randomUUID as Tr}from"node:crypto";var Er=["fake","mask","hash","nullify","redact","shuffle","truncate","preserve_format","age_band","generalize"],Ue=class{builtInRules;constructor(){this.builtInRules=new Map,this.builtInRules.set("gdpr",this.buildGDPRRules()),this.builtInRules.set("ccpa",this.buildCCPARules()),this.builtInRules.set("hipaa",this.buildHIPAARules()),this.builtInRules.set("pci_dss",this.buildPCIDSSRules())}buildProfile(e,t,n=[]){let o=this.builtInRules.get(e)??[];return{framework:e,rules:o,autoDetectedPII:t,userOverrides:n,auditRequired:e!=="none"&&e!=="custom"}}generateRules(e){if(e.framework==="none")return[];let t=new Map;for(let o of e.userOverrides){let r=`${o.objectApiName}.${o.fieldApiName}`;t.set(r,o)}let n=[];for(let o of e.autoDetectedPII){let r=`${o.objectApiName}.${o.fieldApiName}`,s=t.get(r);if(s){if(s.method==="skip")continue;n.push({objectApiName:o.objectApiName,fieldApiName:o.fieldApiName,method:s.method,piiCategory:o.piiCategory,aiConfidence:o.confidence,userOverridden:!0,fieldType:o.fieldType});continue}let i=this.findMatchingRule(e.rules,o.piiCategory),a=i&&i.requiredMethod!=="any"?i.requiredMethod:o.suggestedMethod;n.push({objectApiName:o.objectApiName,fieldApiName:o.fieldApiName,method:a,piiCategory:o.piiCategory,aiConfidence:o.confidence,userOverridden:!1,fieldType:o.fieldType})}return n}buildSummary(e){let t={};for(let o of Er)t[o]=0;for(let o of e)t[o.method]++;let n=[...new Set(e.map(o=>o.objectApiName))];return{totalPiiFields:e.length,totalFieldsToAnonymize:e.length,methodBreakdown:t,objectsWithPii:n}}generateReport(e,t,n,o,r,s){let i=new Set(e.userOverrides.map(w=>`${w.objectApiName}.${w.fieldApiName}`)),a=t.map(w=>{let f=this.findMatchingRule(e.rules,w.piiCategory),R=f?f.id:"custom",y=n.get(w.objectApiName)??0,L=`${w.objectApiName}.${w.fieldApiName}`;return{objectApiName:w.objectApiName,fieldApiName:w.fieldApiName,piiCategory:w.piiCategory,anonymizationMethod:w.method,recordsAnonymized:y,ruleApplied:R,userOverridden:i.has(L)||w.userOverridden}}),c=this.buildObjectSummaries(t,n,e),d=this.computeOverallStatus(c),m=new Date().toISOString(),p=Tr(),l=JSON.stringify(a),g=Or("sha256").update(l).digest("hex");return{id:p,framework:e.framework,generatedAt:m,sourceOrgId:o,targetOrgId:r,totalFieldsScanned:s,piiFieldsDetected:e.autoDetectedPII.length,piiFieldsAnonymized:t.length,entries:a,objectSummaries:c,overallStatus:d,checksumSha256:g}}findMatchingRule(e,t){return e.find(n=>n.targetPiiCategories.includes(t))}buildObjectSummaries(e,t,n){let o=new Set;for(let s of e)o.add(s.objectApiName);for(let s of n.autoDetectedPII)o.add(s.objectApiName);let r=[];for(let s of o){let i=e.filter(l=>l.objectApiName===s),a=n.autoDetectedPII.filter(l=>l.objectApiName===s),c=[...new Set(i.map(l=>l.method))],d=t.get(s)??0,m=a.length>0&&a.every(l=>i.some(g=>g.fieldApiName===l.fieldApiName)),p=a.length===0||m?"pass":i.length>0?"partial":"fail";r.push({objectApiName:s,recordCount:d,piiFieldCount:a.length,anonymizationMethods:c,status:p})}return r}computeOverallStatus(e){return e.length===0||e.every(o=>o.status==="pass")?"pass":e.every(o=>o.status==="fail")?"fail":"partial"}buildGDPRRules(){return[{id:"gdpr-01",framework:"gdpr",category:"data_minimization",description:"Anonymize personal identifiers (name, email, phone, address)",targetPiiCategories:["PII"],requiredMethod:"fake",articleReference:"GDPR Art. 25"},{id:"gdpr-02",framework:"gdpr",category:"data_protection",description:"Hash sensitive identifiers for pseudonymization",targetPiiCategories:["SENSITIVE"],requiredMethod:"hash",articleReference:"GDPR Art. 32"},{id:"gdpr-03",framework:"gdpr",category:"health_data",description:"Nullify health-related data",targetPiiCategories:["PHI"],requiredMethod:"nullify",articleReference:"GDPR Art. 9"},{id:"gdpr-04",framework:"gdpr",category:"financial_data",description:"Mask payment card data",targetPiiCategories:["PCI"],requiredMethod:"mask",articleReference:"GDPR Art. 32"}]}buildCCPARules(){return[{id:"ccpa-01",framework:"ccpa",category:"personal_info",description:"Anonymize personal information (name, email, phone)",targetPiiCategories:["PII"],requiredMethod:"fake"},{id:"ccpa-02",framework:"ccpa",category:"commercial_info",description:"Mask commercial and financial data",targetPiiCategories:["PCI","SENSITIVE"],requiredMethod:"mask"},{id:"ccpa-03",framework:"ccpa",category:"biometric",description:"Nullify biometric and health data",targetPiiCategories:["PHI"],requiredMethod:"nullify"}]}buildHIPAARules(){return[{id:"hipaa-01",framework:"hipaa",category:"safe_harbor",description:"Anonymize patient identifiers (name, address, phone)",targetPiiCategories:["PII","PHI"],requiredMethod:"fake",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"},{id:"hipaa-02",framework:"hipaa",category:"safe_harbor_dates",description:"Generalize dates to year only",targetPiiCategories:["SENSITIVE"],requiredMethod:"age_band",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"},{id:"hipaa-03",framework:"hipaa",category:"safe_harbor_ids",description:"Hash medical record numbers and SSNs",targetPiiCategories:["PHI"],requiredMethod:"hash",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"}]}buildPCIDSSRules(){return[{id:"pci-01",framework:"pci_dss",category:"card_data",description:"Mask PAN to show only last 4 digits",targetPiiCategories:["PCI"],requiredMethod:"mask",articleReference:"PCI-DSS Requirement 3.3"},{id:"pci-02",framework:"pci_dss",category:"auth_data",description:"Nullify CVV, expiration, and magnetic strip data",targetPiiCategories:["PCI"],requiredMethod:"nullify",articleReference:"PCI-DSS Requirement 3.2"},{id:"pci-03",framework:"pci_dss",category:"cardholder",description:"Anonymize cardholder personal data",targetPiiCategories:["PII"],requiredMethod:"fake",articleReference:"PCI-DSS Requirement 3.4"}]}};var He=class{avgSecondsPerApiCall;batchSize;constructor(e){this.avgSecondsPerApiCall=e?.avgSecondsPerApiCall??.5,this.batchSize=e?.batchSize??200}getBatchSize(){return this.batchSize}generate(e,t,n){let o=this.buildWaves(e),r=e.stats.totalRecords,s=e.stats.totalEstimatedApiCalls,i=this.estimateDuration(o,e);return{waves:o,totalRecords:r,estimatedDurationSec:i,estimatedApiCalls:s,complianceFramework:t,anonymizationSummary:n,cycleResolutions:e.cycles}}buildWaves(e){if(e.nodes.length===0)return[];let t=[...e.nodes].sort((i,a)=>i.insertOrder-a.insertOrder),n=new Map;for(let i of t){let a=n.get(i.level);a?a.push(i.objectApiName):n.set(i.level,[i.objectApiName])}let o=[...n.keys()].sort((i,a)=>i-a),r=new Map;for(let i=0;i<o.length;i++){let a=o[i],c=n.get(a);if(c)for(let d of c)r.set(d,i)}let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=n.get(a)??[],d=new Set;for(let p of c)for(let l of e.edges)if(l.to===p){let g=r.get(l.from);g!==void 0&&g<i&&d.add(g)}let m=[...d].sort((p,l)=>p-l);s.push({order:i,objects:c,dependsOn:m})}return s}estimateDuration(e,t){let n=new Map;for(let s of t.nodes)n.set(s.objectApiName,s.estimatedApiCalls);let o=new Map;t.cycles.forEach((s,i)=>{for(let a of s.objects)o.set(a,i)});let r=0;for(let s of e){let i=new Map;for(let a of s.objects){let c=o.get(a),d=c===void 0?`object:${a}`:`cycle:${c}`;i.set(d,(i.get(d)??0)+(n.get(a)??0))}r+=Math.max(0,...i.values())*this.avgSecondsPerApiCall}return r}};var Pe=class{idMaps=new Map;registerMappings(e,t){let n=this.idMaps.get(e);n||(n=new Map,this.idMaps.set(e,n));for(let[o,r]of t)n.set(o,r)}remapRecords(e,t,n){let o=t.filter(c=>c.to===n),r=0,s=0,i=0,a=[];for(let[c,d]of e.entries()){let m=new Set,p=new Map;for(let l of o){let g=d[l.fieldApiName];if(g==null||g===""){i++;continue}if(typeof g!="string"){i++;continue}let f=this.idMaps.get(l.from)?.get(g);if(f!==void 0)d[l.fieldApiName]=f,m.add(l.fieldApiName),r++;else{let R=p.get(l.fieldApiName);R?R.parents.push(l.from):p.set(l.fieldApiName,{sourceId:g,parents:[l.from]}),s++}}for(let[l,{sourceId:g,parents:w}]of p)m.has(l)||(d[l]=null,a.push({index:c,fieldApiName:l,sourceId:g,parents:w}))}return{remapped:r,missing:s,skipped:i,unresolved:a}}getTargetId(e,t){return this.idMaps.get(e)?.get(t)}hasObject(e){return this.idMaps.has(e)}getMappingCount(e){return this.idMaps.get(e)?.size??0}get totalMappings(){let e=0;for(let t of this.idMaps.values())e+=t.size;return e}clear(){this.idMaps.clear()}};var Pr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function yr(u,e,t){let n=Gt(u);if(e!==void 0&&!Pr.test(e))throw new Error(`Not a record id to read after: "${e}".`);let o=e===void 0?"":` WHERE Id > '${e}'`;return`SELECT FIELDS(ALL) FROM ${n}${o} ORDER BY Id LIMIT ${Math.trunc(t)}`}var Cr={statusCode:Ne,message:"No result returned for the record",fields:[]},Mr={statusCode:Ne,message:"Refused without a reason",fields:[]},lr="PARENT_REFUSED",pr="PARENT_NOT_WRITTEN",Dt="CUT_WITH_PARENT",fr={skipped:u=>`${u} was skipped in this run`,failed:u=>`the run's write of ${u} failed`},Fr="PERSON_ACCOUNT_NOT_WRITTEN",Ir="PERSON_CONTACT_NOT_LOOKED_UP",xr=`SELECT Id FROM RecordType WHERE SobjectType = '${ue}' AND IsPersonType = true`;function ne(u){return u.slice(0,15)}var me=class{byReason=new Map;add(e){let t=new Set;for(let n of e){let o=`${n.statusCode}\0${n.fields.join(",")}`;if(t.has(o))continue;t.add(o);let r=this.byReason.get(o);this.byReason.set(o,r?{...r,count:r.count+1}:{statusCode:n.statusCode,fields:[...n.fields],count:1,message:n.message})}}addCounted(e){let t=`${e.statusCode}\0${e.fields.join(",")}`,n=this.byReason.get(t);this.byReason.set(t,n?{...n,count:n.count+e.count}:e)}list(){return[...this.byReason.values()].sort((e,t)=>t.count-e.count)}};function hr(u,e){let[t,...n]=u.errors,[o,...r]=u.errorDetails??[];return{...u,...t===void 0?{}:{errors:[mt(t,e),...n]},...o===void 0?{}:{errorDetails:[{...o,message:mt(o.message,e)},...r]}}}function mr(){return{written:0,linked:0,failed:0,errors:[],refusals:new me,apiCallsUsed:0,defaulted:new Map,cutSinceFit:0,heldForRecordType:new Map,sentAgainForALock:{rows:0,written:0,stillLocked:0}}}function jr(u){return{statusCode:xn,fields:["RecordTypeId"],count:u.recordCount,message:$n(u)}}function Lr(u,e){return{objectApiName:u,rows:e.rows,why:{...e.why},...e.predicted?{predicted:e.predicted}:{},...e.readBack?{readBack:e.readBack}:{}}}function gr(u){let e=0;for(let[t,n]of u)Et(t)&&(e+=n);return e}function $r(u){let e=new Map;for(let t of u.holds)e.set(t.objectApiName,[...e.get(t.objectApiName)??[],t]);return{holds:e,kept:new Map([...u.kept].map(([t,n])=>[t,new Set(n.map(ne))])),stayedOut:new Map}}var Ce=class extends vo{deps;batchSize;paused=!1;pausePromise=null;pauseResolve=null;skippedObjects=new Set;signal;contactPoints;creatableByObject=new Map;currencies;currencyChanges=new Fn;pricesSettled=new Map;currencyChangesByWrittenId=new Map;keyPrefixByObject=new Map;lifecycleByObject=new Map;standardPricebook;deferredStatuses=[];lookupsByObject=new Map;recordTypeMappings;targetRecordTypes=[];planned=new Set;parentIds=new Map;owedLookups=[];unmappedRecordTypes=new Set;leftToThePlatform=new rn;taskOfEmail=new Map;emailsAfterTheirTask=[];taskTurnOver=!1;emailsHeldAndNotSent=0;leftByStop=new Map;lookupsLeftEmpty=new Map;refusedRecords=new Map;notWritten=new Map;reached=new Set;personTypes;personContactsLinked=0;recordTypesGiven=new Map;recordTypesUnderTheLease=new Map;givenRules=new Map;lease;fit;async creatableFieldsOf(e){if(!this.deps.describeCreateableFields)return null;let t=this.creatableByObject.get(e);if(t!==void 0)return t;try{let n=await this.deps.describeCreateableFields(e),o=n.size>0?n:null;return this.creatableByObject.set(e,o),o}catch{return this.creatableByObject.set(e,null),null}}lookupsOf(e){let t=this.deps.describeLookups;if(!t)return Promise.resolve(null);let n=this.lookupsByObject.get(e);return n||(n=t(e).catch(()=>null),this.lookupsByObject.set(e,n)),n}keyPrefixOf(e){let t=this.deps.describeKeyPrefix;if(!t)return Promise.resolve(void 0);let n=this.keyPrefixByObject.get(e);return n||(n=t(e).catch(()=>{}),this.keyPrefixByObject.set(e,n)),n}constructor(e){super(),this.deps=e,this.batchSize=e.batchSize??200}async recordTypesHeldBack(e){let{describeRecordTypes:t,countRecordTypes:n}=this.deps;if(!t||!n)return[];let o=await this.creatableFieldsOf(e);if(o&&!o.has("RecordTypeId"))return[];try{let r=await t(e);if(!r.some(i=>!i.available&&!i.master))return[];let s=this.inTargetRecordTypes(await n(e));return jn(e,s,lt(r,this.targetRecordTypes))}catch{return[]}}inTargetRecordTypes(e){let t=new Map;for(let[n,o]of e){if(n===null)continue;let r=this.targetRecordTypeOf(n);t.set(r,(t.get(r)??0)+o)}return t}targetRecordTypeOf(e){return this.recordTypeMappings?.find(t=>t.sourceId===e)?.targetId??e}async recordTypesGivenOf(e,t,n=new Map,o=[]){await this.mapRecordTypes(e);let r=new Map;for(let s of new Set(e.waves.flatMap(i=>i.objects))){let i=t.get(s)??0;if(i===0)continue;let a=await this.givenRuleOf(s);if(!a)continue;let c=await this.creatableFieldsOf(s),d,m="masterInSource";if(c&&!c.has("RecordTypeId"))d=i,m="notRead";else{let p=await this.onMasterInSource(s,n.get(s));if(p===void 0)continue;d=o.find(g=>g.objectApiName===s)?Math.min(p,i):p}d!==0&&r.set(s,{objectApiName:s,rows:d,why:{[m]:d},...a.predicted?{predicted:a.predicted}:{}})}return r}async onMasterInSource(e,t){try{if(t===void 0){let r=this.deps.countRecordTypes;return r?gr(await r(e)):void 0}let n=this.deps.querySource;if(!n)return;let o=0;for(let r=0;r<t.length;r+=_e){let s=await n(Ct(e,t.slice(r,r+_e)));o+=gr($e(s))}return o}catch{return}}givenRuleOf(e){let t=this.givenRules.get(e);return t||(t=(async()=>{let n=this.recordTypesUnderTheLease.get(e)??await this.deps.describeRecordTypes?.(e).catch(()=>{});if(!n?.some(s=>!s.master))return;let o=lt(n,this.targetRecordTypes),r=xo(Io(o));return{types:o,...r?{predicted:r}:{}}})(),this.givenRules.set(e,t)),t}async readAgainUnderTheLease(e,t){let n=this.deps.describeRecordTypesAgain;if(!n||!this.lease||this.lease.assigned===0)return;let o=[...new Set(e.waves.flatMap(r=>r.objects))].filter(r=>(t.get(r)??0)>0);await Promise.all(o.map(async r=>{if((await this.deps.describeRecordTypes?.(r).catch(()=>{}))?.some(i=>!i.master))try{this.recordTypesUnderTheLease.set(r,await n(r))}catch{}}))}countCreatedWithoutRecordType(e,t,n,o){let r=this.recordTypesGiven.get(e);r||(r={...t,rows:0,why:{},ids:[]},this.recordTypesGiven.set(e,r)),r.rows++,r.why[n]=(r.why[n]??0)+1,o&&r.ids.length<jo&&r.ids.push(o)}async afterTheWrites(e){await this.giveTheLeaseBack(),await this.readBackRecordTypes();for(let[t,n]of this.recordTypesGiven){let o=e[t];o&&(e[t]={...o,recordTypeGiven:Lr(t,n)})}}async giveTheLeaseBack(){let e=this.lease;if(e){this.lease=void 0;try{await e.giveBack()}catch(t){de.warn(`[autopilot] the mute's lease was not given back as the writes ended: ${ee(t)}`)}}}async readBackRecordTypes(){let e=this.deps.queryTarget;e&&await Promise.all([...this.recordTypesGiven].map(async([t,n])=>{if(n.ids.length!==0)try{let o=await e(Ct(t,n.ids));n.readBack=Lo(o,n.types)}catch(o){n.readBack={read:0,types:[],unread:ee(o)}}}))}holdOnClosedRecordTypes(e,t,n){let o=n.closedRecordTypes;if(!o)return t;let r=[];for(let s of t){let i=s.RecordTypeId,a=e===le&&Re(s),c=typeof i=="string"&&i.length>=15&&!a?o.get(ne(this.targetRecordTypeOf(i))):void 0;if(!c){r.push(s);continue}n.failed++;let d=n.heldForRecordType.get(c.recordTypeId);n.heldForRecordType.set(c.recordTypeId,{...c,recordCount:(d?.recordCount??0)+1});let m=s.Id;typeof m=="string"&&m!==""&&this.refusedRecords.set(ne(m),e)}return r}async mapRecordTypes(e){let{querySource:t,queryTarget:n}=this.deps;if(!t||!n)return;let o=[...new Set(e.waves.flatMap(s=>s.objects))];if(o.length===0)return;let r=`${Eo} AND SobjectType IN (${o.map(s=>`'${je(s)}'`).join(", ")})`;try{let[s,i]=await Promise.all([t(r),n(r)]),a=Tt(s);this.targetRecordTypes=Tt(i),this.recordTypeMappings=new Pt().buildMapping(a,this.targetRecordTypes);for(let c of Mo(a,this.targetRecordTypes))de.warn(`[autopilot] ${Fo(c)}`)}catch(s){de.warn("Autopilot could not match the record types of the two orgs",{error:ee(s)})}}async matchStandardPricebooks(e){let{querySource:t,queryTarget:n}=this.deps;if(!t||!n)return;let o=new Set(e.waves.flatMap(r=>r.objects));if(!(!o.has(ge)&&!o.has(et)))try{let[r,s]=await Promise.all([t(tt),n(tt)]),i=r[0]?.Id,a=s[0]?.Id;if(typeof i!="string"||typeof a!="string")return;this.standardPricebook={source:i,target:a},this.deps.remapper.registerMappings(ge,[[i,a]])}catch(r){de.warn("Autopilot could not match the standard price books",{error:ee(r)})}}async execute(e,t,n,o,r,s=new Map,i={}){if(!this.deps.queryByIds&&[...s.values()].some(f=>f.length>0))throw new Error("This plan reads the parents its objects reference by id, and the run has no read by id.");this.parentIds=s,this.contactPoints=i.keepContactPoints===!0?void 0:new Oo,this.lease=i.lease,this.fit=i.fit?$r(i.fit):void 0;let a=Date.now();this.signal=r;let c=()=>this.pauseResolve?.();r?.addEventListener("abort",c,{once:!0});let d={},m={},p={totalSuccess:0,totalFailure:0,totalSkipped:0,totalLinked:0,elapsedMs:0,completedObjects:[],failedObjects:[],skippedObjects:[],nodeErrors:d,objectOutcomes:m},l=[];this.emit("execution-started",this.makeEvent({type:"execution-started",timestamp:""}));let g=async f=>{await w(f),f===Le&&await this.writeEmailsAfterTheirTask(t,p)},w=async f=>{if(this.skippedObjects.has(f)){let y=o.get(f)??0;p.skippedObjects.push(f),p.totalSkipped+=y,this.notWritten.set(f,"skipped");return}this.reached.add(f);let R=o.get(f)??0;if(await this.checkPause()){l.push(f),m[f]={written:0,linked:0,failed:0,refusals:[],...R>0?{notSent:R}:{}};return}try{let y=await this.executeObject(f,t,n,R);p.totalSuccess+=y.success,p.totalFailure+=y.failure,p.totalLinked=(p.totalLinked??0)+y.linked,y.cutSinceFit>0&&(p.cutSinceFit=(p.cutSinceFit??0)+y.cutSinceFit);let L=this.leftToThePlatform.counts(f);if(m[f]={written:y.success,linked:y.linked,failed:y.failure,refusals:y.refusals,...y.leftToDefault.length>0?{leftToDefault:y.leftToDefault}:{},...L.length>0?{leftToThePlatform:L}:{},...y.notSent!==void 0&&y.notSent>0?{notSent:y.notSent}:{},...this.currenciesReplacedOf(f),...this.pricesSettledOf(f),...f===le&&this.personContactsLinked>0?{withTheirPersonAccount:this.personContactsLinked}:{},...y.cutSinceFit>0?{cutSinceFit:y.cutSinceFit}:{},...y.threw!==void 0?{threw:y.threw}:{},...y.sentAgainForALock.rows>0?{sentAgainForALock:y.sentAgainForALock}:{}},y.notSent!==void 0){l.push(f);return}let{threw:v}=y;if(v!==void 0||y.errors.length>0&&y.success+y.linked===0){p.failedObjects.push(f),v!==void 0&&this.notWritten.set(f,"failed");let B=v!==void 0?[v,...y.errors]:y.errors;d[f]=B[0],this.emit("node-failed",this.makeEvent({type:"node-failed",timestamp:"",objectApiName:f,errors:B,partialSuccessCount:y.success,failureCount:y.failure,linkedCount:y.linked,refusals:y.refusals}))}else p.completedObjects.push(f),this.emit("node-completed",this.makeEvent({type:"node-completed",timestamp:"",objectApiName:f,successCount:y.success,failureCount:y.failure,linkedCount:y.linked,refusals:y.refusals,elapsedMs:y.elapsedMs,apiCallsUsed:y.apiCallsUsed}))}catch(y){p.failedObjects.push(f),this.notWritten.set(f,"failed");let L=ee(y);d[f]=L,this.emit("node-failed",this.makeEvent({type:"node-failed",timestamp:"",objectApiName:f,errors:[L],partialSuccessCount:0,failureCount:0,linkedCount:0,refusals:[]}))}};try{await this.matchStandardPricebooks(e),await this.mapRecordTypes(e),await this.readAgainUnderTheLease(e,o),this.planned=new Set(e.waves.flatMap(y=>y.objects));let f={};for(let y of e.waves){if(await this.writeWave(y.objects,t,g),this.stopped())break;await this.fillOwedLookups(f),this.emit("wave-completed",this.makeEvent({type:"wave-completed",timestamp:""}))}if(this.stopped()){let y=new Set([...p.completedObjects,...p.failedObjects,...p.skippedObjects,...l]);for(let L of e.waves.flatMap(v=>v.objects)){if(y.has(L))continue;let v=o.get(L)??0;l.push(L),m[L]={written:0,linked:0,failed:0,refusals:[],...v>0?{notSent:v}:{}}}return p.stopped=!0,p.stoppedObjects=l,this.countEmailsTheStopHeld(p,l,m),this.countWhatTheStopLeft(l,m),await this.sayLookupsLeftOwed(t,f),Object.keys(f).length>0&&(p.lookups=f),await this.afterTheWrites(m),this.reportContactPoints(p),p.elapsedMs=Date.now()-a,p}this.emailsAfterTheirTask.length>0&&(await this.writeEmailsAfterTheirTask(t,p),await this.fillOwedLookups(f)),await this.sayLookupsLeftOwed(t,f);let R=await this.applyDeferredStatuses();return Object.keys(R).length>0&&(p.statuses=R),Object.keys(f).length>0&&(p.lookups=f),await this.afterTheWrites(m),this.stopped()&&(p.stopped=!0,p.stoppedObjects=l,this.countEmailsTheStopHeld(p,l,m),this.countWhatTheStopLeft(l,m)),this.reportContactPoints(p),p.elapsedMs=Date.now()-a,this.emit("execution-completed",this.makeEvent({type:"execution-completed",timestamp:""})),p}catch(f){throw p.elapsedMs=Date.now()-a,p.fatalError=ee(f),de.error("Autopilot execution crashed",{error:p.fatalError}),this.emit("execution-failed",this.makeEvent({type:"execution-failed",timestamp:"",error:p.fatalError})),f}finally{r?.removeEventListener("abort",c),await this.giveTheLeaseBack()}}async writeWave(e,t,n){let{within:o,deps:r,groups:s}=xe(e,t),i=new Map;s.forEach((m,p)=>m.forEach(l=>i.set(l,p)));let a=[];for(let[m,p]of s.entries()){let l=new Set;for(let g of p)for(let w of r.get(g)??[]){let f=i.get(w);f!==void 0&&f!==m&&l.add(a[f])}a.push((async()=>{await Promise.all(l);let g=p.length>1?Zt(p,await this.setAtInsert(p,o)):p;for(let w of g)await n(w)})())}let d=(await Promise.allSettled(a)).find(m=>m.status==="rejected");if(d)throw d.reason}async setAtInsert(e,t){let n=new Set(e),o=new Map;for(let r of t)!n.has(r.to)||!n.has(r.from)||o.has(r.to)||o.set(r.to,await this.lookupsOf(r.to));return en(e,t,r=>o.get(r))}async fillOwedLookups(e){let t=this.owedLookups.splice(0,this.owedLookups.length),{update:n}=this.deps;if(!n||t.length===0)return;let o=new To;for(let r of t){let s=r.parents.map(i=>this.deps.remapper.getTargetId(i,r.sourceId)).find(i=>i!==void 0);if(!s){this.owedLookups.push(r);continue}o.add({objectApiName:r.objectApiName,recordId:r.recordId,fieldName:r.fieldApiName,value:s})}for(let[r,s]of o.updates()){let i=e[r],a=i?.filled??0,c=new me;for(let d of i?.refusals??[])c.addCounted(d);for(let d=0;d<s.length;d+=this.batchSize){if(await this.checkPause()){this.noteLeftByStop(r,"lookups",s.slice(d).map(l=>String(l.Id)));break}let m=s.slice(d,d+this.batchSize),p=await this.updateSendingLocksAgain(n,r,m,"lookup update(s)");m.forEach((l,g)=>{let w=p[g];if(w?.success){a++;return}let f=Object.keys(l).filter(R=>R!=="Id");c.add(Nt(w).map(R=>({...R,fields:f}))),this.noteLookupLeftEmpty(r,String(l.Id))})}e[r]=this.lookupOutcome(r,a,c)}}noteLookupLeftEmpty(e,t){let n=this.lookupsLeftEmpty.get(e);n||(n=new Set,this.lookupsLeftEmpty.set(e,n)),n.add(t)}lookupOutcome(e,t,n){let o=this.lookupsLeftEmpty.get(e)?.size??0;return{filled:t,refusals:n.list(),...o>0?{leftEmpty:o}:{}}}async sayLookupsLeftOwed(e,t){let n=new Map;for(let o of this.owedLookups.splice(0,this.owedLookups.length)){let r=await this.whyLeftOwed(o,e);if(!r)continue;let s=n.get(o.objectApiName);if(!s){s=new me;for(let i of t[o.objectApiName]?.refusals??[])s.addCounted(i);n.set(o.objectApiName,s)}s.add([{...r,fields:[o.fieldApiName]}]),this.noteLookupLeftEmpty(o.objectApiName,o.recordId)}for(let[o,r]of n){let s=t[o]?.filled??0;t[o]=this.lookupOutcome(o,s,r)}}async whyLeftOwed(e,t){let{fieldApiName:n,sourceId:o}=e,r=this.refusedRecords.get(ne(o)),s=e.parents.find(c=>c===r);if(s)return{statusCode:lr,message:`the ${s} record its ${n} names was refused in this run, and this record, written before it, keeps its ${n} empty.`};let i=this.fit?.stayedOut.get(ne(o)),a=e.parents.find(c=>c===i);if(a)return{statusCode:Dt,message:`the ${a} record its ${n} names stayed out with a record the fit cut, and this record, written before it, keeps its ${n} empty.`};for(let c of e.parents){let d=this.notWrittenOf(c);if(d===void 0)continue;let m=t.find(p=>p.from===c&&p.to===e.objectApiName&&p.fieldApiName===n);if(!(m&&!await this.namesARecordOf(e.objectApiName,m,o,e.parents.length)))return{statusCode:pr,message:`the ${c} record its ${n} names was not written: ${fr[d](c)}, and this record, written before it, keeps its ${n} empty.`}}}async executeObject(e,t,n,o){let r=Date.now(),s=mr(),i=()=>{let a=[...s.heldForRecordType.values()];return{success:s.written,linked:s.linked,failure:s.failed,errors:[...a.map(Nn),...s.errors],refusals:[...s.refusals.list(),...a.map(jr)].sort((c,d)=>d.count-c.count),apiCallsUsed:s.apiCallsUsed,elapsedMs:Date.now()-r,leftToDefault:[...s.defaulted].map(([c,d])=>({field:c,count:d})),...s.notSent!==void 0?{notSent:s.notSent}:{},cutSinceFit:s.cutSinceFit,sentAgainForALock:s.sentAgainForALock}};try{return await this.writeEveryPage(e,t,n,o,s,i)}catch(a){return{...i(),threw:ee(a)}}}async writeEveryPage(e,t,n,o,r,s){let i=o>0?await this.recordTypesHeldBack(e):[];i.length>0&&(r.closedRecordTypes=new Map(i.map(p=>[ne(p.recordTypeId),p])));let a=p=>{let l=Math.min(p,o);this.emit("node-progress",this.makeEvent({type:"node-progress",timestamp:"",objectApiName:e,progress:o>0?Math.round(l/o*100):100,recordsProcessed:l,recordsTotal:o,apiCallsUsed:r.apiCallsUsed}))},c=0,d,m=this.standardPricebook;if(_t(e)&&m){let p=[];for(;c<o;){if(await this.checkPause())return r.notSent=o,s();let{rows:v,advance:B,next:K,last:O}=await this.readPage(e,c,d);if(r.apiCallsUsed++,B===0)break;c+=B,d=K;let A=this.leaveToThePlatform(e,v,t);if(this.deps.anonymizer.anonymize(A,n,e),await this.neutralizeContactPoints(e,A),p.push(...A),O)break}let l=await this.pricesInOneCurrencyEach(p,m.source),{standard:g,custom:w}=nt(l.rows,m.source),f=nt(p.filter(v=>l.standsFor.has(String(v.Id))),m.source);l.said.length>0&&this.pricesSettled.set(e,Do(l.said));let R=0,y=0,L=async v=>{for(let B=0;B<v.length;B+=this.batchSize){if(await this.checkPause())return r.notSent=p.length-R-y,!1;let K=v.slice(B,B+this.batchSize);await this.writeBatch(e,K,t,r),R+=K.length,a(R+y)}return!0};for(let[v,B]of[[g,f.standard],[w,f.custom]]){if(!await L(v))return s();let K=this.linkWhatStoodIn(B,l.standsFor,r);if(y+=B.length-K.length,!await L(K))return s()}return s()}for(;c<o;){if(await this.checkPause()){r.notSent=o-c;break}let{rows:p,advance:l,next:g,last:w}=await this.readPage(e,c,d);if(r.apiCallsUsed++,l===0)break;d=g;let f=this.leaveToThePlatform(e,p,t);if(this.deps.anonymizer.anonymize(f,n,e),await this.neutralizeContactPoints(e,f),await this.writeBatch(e,f,t,r),c+=l,a(c),w)break}return s()}async neutralizeContactPoints(e,t){let{contactPoints:n}=this,o=this.deps.describeFields;if(!n||!o||t.length===0)return;let r=await o(e).catch(()=>{});if(!r)return;let s=n.forObject(e,r);if(s)for(let i of t)s(i)}reportContactPoints(e){this.contactPoints&&(e.contactPoints=this.contactPoints.report())}async readPage(e,t,n){let o=this.parentIds.get(e);if(o&&this.deps.queryByIds){let i=o.slice(t,t+Math.min(this.batchSize,_e));return i.length===0?{rows:[],advance:0,next:n,last:!0}:{rows:await this.deps.queryByIds(e,i),advance:i.length,next:n,last:!1}}let r=await this.deps.query(e,n,this.batchSize),s=r.at(-1)?.Id;return{rows:r,advance:r.length,next:typeof s=="string"?s:n,last:r.length>0&&typeof s!="string"}}leaveToThePlatform(e,t,n){let o=new Set(n.filter(r=>r.to===e&&(r.required||Bt(r.to,r.fieldApiName))).map(r=>r.fieldApiName));return this.leftToThePlatform.keep(e,t,[...o])}async writeBatch(e,t,n,o){let r=[],s=t,i=this.standardPricebook;if(e===ge&&i&&(s=t.filter(O=>O.Id!==i.source),o.linked+=t.length-s.length),s=this.holdOnClosedRecordTypes(e,s,o),s=await this.holdBehindRefusedParents(e,s,n,o),s=this.holdBehindCutParents(e,s,o),e===V&&(s=this.holdEmailsForTheirTask(s)),e===le&&(s=await this.linkPersonContacts(s,o,r)),s.length===0){this.register(e,r);return}let a=this.deps.remapper.remapRecords(s,n,e);await this.leaveToDefault(e,s,o);let c=await this.creatableFieldsOf(e),d=c?s.map(O=>{let A={};for(let F of Object.keys(O))(F==="Id"||F==="attributes"||c.has(F))&&(A[F]=O[F]);return A}):s;d=this.translateRecordTypes(e,d);let m=new Map;d.forEach((O,A)=>{if(O.RecordTypeId!==void 0)return;let F=s[A]?.RecordTypeId,E=!c||c.has("RecordTypeId");m.set(O,E&&Et(F)?"masterInSource":"notRead")});for(let O of d)for(let A of zt(e,O))delete O[A];let p=await this.replaceCurrencies(e,s,d,c);e===ue&&await this.leaveOutForAccountKind(s,d);let l=new Map;d.forEach((O,A)=>{let F=at(e,O);for(let E of F)delete O[E];F.length>0&&l.set(A,F)});let g=await this.lookupsOwed(e,s,a.unresolved.filter(O=>!l.get(O.index)?.includes(O.fieldApiName)),c),w=this.deps.queryTarget,f=w?O=>(o.apiCallsUsed++,w(O)):void 0;if(e===nn&&f){let O=await gn(f,d);for(let[A,F]of O){let E=d[A].Id;typeof E=="string"&&r.push([E,F])}o.linked+=O.size,d=d.filter((A,F)=>!O.has(F))}if(pn[e]!==void 0&&f){let O=await fn(f,e,d);for(let[A,F]of O){let E=d[A].Id;typeof E=="string"&&r.push([E,F])}o.linked+=O.size,await this.giveFlagsBack(e,[...O].map(([A,F])=>[d[A],F]),o),d=d.filter((A,F)=>!O.has(F))}if(e===Le&&f){let O=await this.tasksWrittenWithTheirEmail(d,f);for(let[A,F]of O)r.push([A,F]);o.linked+=O.size,d=d.filter(A=>!O.has(String(A.Id)))}if(d.length===0){this.register(e,r);return}let R=await this.startAsDrafts(e,d),y=m.size>0?await this.givenRuleOf(e):void 0,L=await this.insertSendingLocksAgain(e,d,o),v=await this.keyPrefixOf(e),B=on[e],K=[];if(d.forEach((O,A)=>{let F=typeof O.Id=="string"?O.Id:void 0,E=L[A];if(!E){this.refuse(e,F,o,void 0);return}if(E.success){o.written++;let re=y?m.get(O):void 0;y&&re&&this.countCreatedWithoutRecordType(e,y,re,E.id);let Z=p.get(O);this.currencyChanges.add(e,Z),Z&&E.id&&this.currencyChangesByWrittenId.set(E.id,Z),F&&E.id&&r.push([F,E.id]);let x=R.get(A);x&&E.id&&this.deferredStatuses.push({objectApiName:e,id:E.id,status:x});let H=F?g.get(F):void 0;for(let N of E.id?H??[]:[])this.owedLookups.push({objectApiName:e,recordId:E.id,fieldApiName:N.fieldApiName,sourceId:N.sourceId,parents:N.parents});return}let Q=Dn(E,v);if(Q.kind==="linked"){o.linked++,F&&r.push([F,Q.id]);return}if(Q.kind==="unidentified"&&B&&f){K.push({payload:O,sourceId:F,outcome:E});return}this.refuse(e,F,o,E)}),B&&f&&K.length>0){let O=await yn(f,e,B,K.map(A=>A.payload));K.forEach((A,F)=>{let E=O[F];if(E&&A.sourceId){o.linked++,r.push([A.sourceId,E]);return}this.refuse(e,A.sourceId,o,A.outcome)})}this.register(e,r)}async insertSendingLocksAgain(e,t,n){let o=async i=>(n.apiCallsUsed++,this.deps.insert(e,i)),r=await o(t),s=await gt({outcomes:r.slice(0,t.length),locked:i=>!i.success&&ht(i.errors,i.errorDetails),written:i=>i.success,send:i=>$t((a,c)=>o(c),e,i.map(a=>t[a])),note:hr,wait:async i=>{await this.wait(i),await this.checkPause()},stopped:()=>this.stopped()});return s.refused===0?r:(n.sentAgainForALock={rows:n.sentAgainForALock.rows+s.sentAgain,written:n.sentAgainForALock.written+s.written,stillLocked:n.sentAgainForALock.stillLocked+s.stillLocked},de.info(`[autopilot] ${e}: ${Se("record(s)",s)??""}`),[...s.outcomes,...r.slice(t.length)])}async updateSendingLocksAgain(e,t,n,o){let r=await $t(e,t,n),s=await gt({outcomes:r.slice(0,n.length),locked:i=>!i.success&&ht(i.errors,i.errorDetails),written:i=>i.success,send:i=>$t(e,t,i.map(a=>n[a])),note:hr,wait:async i=>{await this.wait(i),await this.checkPause()},stopped:()=>this.stopped()});return s.refused===0?r:(de.info(`[autopilot] ${t}: ${Se(o,s)??""}`),[...s.outcomes,...r.slice(n.length)])}async giveFlagsBack(e,t,n){let o=this.deps.update;if(!o||t.length===0||!hn[e])return;let r=await this.deps.describeFieldsFixedAtInsert?.(e).catch(()=>{}),s=await mn(e,t,i=>!r?.has(i),async i=>(n.apiCallsUsed++,o(e,i)),()=>this.stopped());s&&de.warn("Autopilot linked relations without a flag or an answer their rows carried",{objectApiName:e,note:s})}holdEmailsForTheirTask(e){for(let n of e){let o=n.ActivityId;typeof n.Id=="string"&&typeof o=="string"&&o!==""&&this.taskOfEmail.set(n.Id,o)}if(this.taskTurnOver||!this.planned.has(Le))return e;let t=[];for(let n of e)cn(n)?this.emailsAfterTheirTask.push(n):t.push(n);return t}async tasksWrittenWithTheirEmail(e,t){let n=new Map;for(let[i,a]of this.taskOfEmail){let c=this.deps.remapper.getTargetId(V,i);c&&n.set(a,c)}let o=e.map(i=>String(i.Id)).filter(i=>n.has(i));if(o.length===0)return new Map;let r;try{r=await dn(t,[...new Set(o.map(i=>n.get(i)??""))])}catch(i){return de.warn("Autopilot could not look up the tasks written with its emails",{error:ee(i)}),new Map}let s=new Map;for(let i of o){let a=r.get(n.get(i)??"");a&&s.set(i,a)}return s}async writeEmailsAfterTheirTask(e,t){this.taskTurnOver=!0;let n=this.emailsAfterTheirTask.splice(0,this.emailsAfterTheirTask.length);if(n.length===0)return;let o=mr();for(let d=0;d<n.length;d+=this.batchSize){if(await this.checkPause()){this.emailsHeldAndNotSent+=n.length-d;break}await this.writeBatch(V,n.slice(d,d+this.batchSize),e,o)}t.totalSuccess+=o.written,t.totalFailure+=o.failed,t.totalLinked=(t.totalLinked??0)+o.linked;let r=t.objectOutcomes??{};t.objectOutcomes=r;let s=r[V],i=new me;for(let d of[...s?.refusals??[],...o.refusals.list()])i.addCounted(d);let a=new Map((s?.leftToDefault??[]).map(d=>[d.field,d.count]));for(let[d,m]of o.defaulted)a.set(d,(a.get(d)??0)+m);let c={...s,written:(s?.written??0)+o.written,linked:(s?.linked??0)+o.linked,failed:(s?.failed??0)+o.failed,refusals:i.list(),...a.size>0?{leftToDefault:[...a].map(([d,m])=>({field:d,count:m}))}:{}};r[V]=c,c.written+c.linked>0&&t.failedObjects.includes(V)&&(t.failedObjects.splice(t.failedObjects.indexOf(V),1),delete t.nodeErrors?.[V],t.completedObjects.push(V)),this.emit("node-completed",this.makeEvent({type:"node-completed",timestamp:"",objectApiName:V,successCount:c.written,failureCount:c.failed,linkedCount:c.linked,refusals:c.refusals,elapsedMs:0,apiCallsUsed:o.apiCallsUsed}))}async leaveToDefault(e,t,n){let o=await this.lookupsOf(e);if(!o)return;let r=kn(o.filter(i=>i.name!=="RecordTypeId"),i=>!this.planned.has(i));if(r.size===0)return;let s=await this.creatableFieldsOf(e);for(let i of t)for(let a of r){let c=i[a];c!=null&&c!==""&&(!s||s.has(a))&&n.defaulted.set(a,(n.defaulted.get(a)??0)+1),delete i[a]}}async replaceCurrencies(e,t,n,o){let r=new Map,{querySource:s,queryTarget:i}=this.deps;if(!s||!i)return r;let a=!o||o.has(he);if(!a&&this.currencyChangesByWrittenId.size===0)return r;let c=l=>typeof l?.[he]=="string"&&l[he]!=="";if(!(a?n.some(c):t.some(c)))return r;this.currencies??=dt(s,i,{source:this.deps.toolingSource,target:this.deps.toolingTarget});let d=await this.currencies;if(!d)return r;let m=await this.deps.describeCurrencyFields?.(e).catch(()=>{})??new Map,p=a?[]:(await this.lookupsOf(e)??[]).map(l=>l.name);return n.forEach((l,g)=>{let w=t[g],f=w?.[he],R=a?Pn(l,{read:f,currencyFields:m,ratesOn:On(e,w)},d):Mn(l,{read:f,parent:w?Cn(e,w,p,y=>this.currencyChangesByWrittenId.get(y)):void 0,currencyFields:m},d);R&&r.set(l,R)}),r}async pricesInOneCurrencyEach(e,t){let n={rows:e,standsFor:new Map,said:[]},{querySource:o,queryTarget:r}=this.deps;if(!o||!r)return n;let s=d=>typeof d[he]=="string"&&d[he]!=="";if(!e.some(s))return n;this.currencies??=dt(o,r,{source:this.deps.toolingSource,target:this.deps.toolingTarget});let i=await this.currencies;if(!i)return n;let{target:a}=i,c=No({prices:e,standardBookId:t,sellingModels:e.some(d=>typeof d[qt]=="string"),writtenIn:d=>a.active.has(d)?d:En(void 0,a)?.to,active:a.active},[]);return{rows:c.rows,standsFor:c.standsFor,said:c.said}}linkWhatStoodIn(e,t,n){let o=et,r=[],s=[];for(let i of e){let a=String(i.Id),c=t.get(a),d=c===void 0?void 0:this.deps.remapper.getTargetId(o,c);if(d===void 0){s.push(i);continue}r.push([a,d]),n.linked++}return this.register(o,r),s}pricesSettledOf(e){let t=this.pricesSettled.get(e)??[];return t.length>0?{pricesSettled:t}:{}}currenciesReplacedOf(e){let t=this.currencyChanges.list().filter(n=>n.objectApiName===e);return t.length>0?{currenciesReplaced:t}:{}}translateRecordTypes(e,t){let n=this.recordTypeMappings;return!n||!t.some(o=>typeof o.RecordTypeId=="string")?t.map(Po):new Pt().apply(t,n,o=>{this.unmappedRecordTypes.has(o)||(this.unmappedRecordTypes.add(o),Co(e,o,"autopilot"))})}async lookupsOwed(e,t,n,o){let r=new Map;if(!this.deps.update||n.length===0)return r;let s=await this.lookupsOf(e);for(let i of n){if(o&&!o.has(i.fieldApiName))continue;let a=s?.find(d=>d.name===i.fieldApiName);if(a&&!a.updateable)continue;let c=t[i.index]?.Id;typeof c=="string"&&r.set(c,[...r.get(c)??[],i])}return r}refuse(e,t,n,o){n.failed++;let r=Nt(o);n.errors.push(o?.errors[0]??Nr(r[0])),n.refusals.add(r),t&&this.refusedRecords.set(ne(t),e)}async holdBehindRefusedParents(e,t,n,o){if(this.refusedRecords.size===0&&this.notWritten.size===0&&this.skippedObjects.size===0)return t;let r=n.filter(a=>a.to===e);if(r.length===0)return t;let s=new Map;for(let a of r)s.set(a.fieldApiName,(s.get(a.fieldApiName)??0)+1);let i=[];for(let a of t){let c=at(e,a),d;for(let w of r){let f=a[w.fieldApiName];if(typeof f!="string"||f===""||c.includes(w.fieldApiName)||this.deps.remapper.getTargetId(w.from,f)!==void 0)continue;let R=this.refusedRecords.get(ne(f))===w.from,y=this.notWrittenOf(w.from);if(!R&&y===void 0)continue;let L=s.get(w.fieldApiName)??0;if(!R&&!await this.namesARecordOf(e,w,f,L))continue;let{from:v,fieldApiName:B}=w;d=R||y===void 0?{edge:w,statusCode:lr,message:`the ${v} record its ${B} names was refused in this run, and written without it this record would stand without its ${v}.`}:{edge:w,statusCode:pr,message:`the ${v} record its ${B} names was not written: ${fr[y](v)}, and written without it this record would stand without its ${v}.`};break}if(!d){i.push(a);continue}let{statusCode:m,message:p,edge:l}=d;o.failed++,o.errors.push(`${m}: ${p}`),o.refusals.add([{statusCode:m,message:p,fields:[l.fieldApiName]}]);let g=a.Id;typeof g=="string"&&g!==""&&this.refusedRecords.set(ne(g),e)}return i}holdBehindCutParents(e,t,n){let o=this.fit,r=o?.holds.get(e);return!o||!r?t:t.filter(s=>{if(!r.some(c=>{let d=s[c.field];if(typeof d!="string"||d==="")return!1;let{prefix:m}=c;if(m!==void 0&&(m===null||!d.startsWith(m))||this.deps.remapper.getTargetId(c.parent,d)!==void 0)return!1;let p=ne(d);return o.stayedOut.has(p)||o.kept.get(c.parent)?.has(p)!==!0}))return!0;n.cutSinceFit++;let a=s.Id;return typeof a=="string"&&a!==""&&o.stayedOut.set(ne(a),e),!1})}notWrittenOf(e){if(!this.planned.has(e))return;let t=this.notWritten.get(e);return t||(this.skippedObjects.has(e)&&!this.reached.has(e)?"skipped":void 0)}async namesARecordOf(e,t,n,o){let r=(await this.lookupsOf(e))?.find(s=>s.name===t.fieldApiName);if(r?.referenceTo.length===1)return r.referenceTo[0]===t.from;if(r&&r.referenceTo.length>1){let s=await this.keyPrefixOf(t.from);return typeof s=="string"&&s!==""&&n.startsWith(s)}return o===1}async linkPersonContacts(e,t,n){let o=e.filter(Re),r=this.deps.queryTarget;if(o.length===0||!r)return e;let s=await this.lookupsOf(ue);if(s&&!s.some(p=>p.name===ct))return e;let i=new Map;for(let p of o){let l=p.AccountId,g=typeof l=="string"&&l!==""?this.deps.remapper.getTargetId(ue,l):void 0;g&&i.set(p,g)}let a=new Map,c;if(i.size>0)try{t.apiCallsUsed++,a=await ln(r,[...new Set(i.values())])}catch(p){c=ee(p)}let d=(p,l,g)=>{t.failed++,t.errors.push(`${l}: ${g}`),t.refusals.add([{statusCode:l,message:g,fields:["AccountId"]}]);let w=p.Id;typeof w=="string"&&w!==""&&this.refusedRecords.set(ne(w),le)},m=[];for(let p of e){if(!Re(p)){m.push(p);continue}let l=i.get(p);if(l===void 0){d(p,Fr,"the person account this contact belongs to is not in the target: the platform writes the contact with the account, and sent on its own it would stand as a contact of no account.");continue}if(c!==void 0){d(p,Ir,`the contact the platform wrote with its person account could not be looked up (${c}): sent, this one would stand beside it as a second contact.`);continue}let g=a.get(l),w=p.Id;if(g===void 0||typeof w!="string"){m.push(p);continue}n.push([w,g]),t.linked++,this.personContactsLinked++}return m}async leaveOutForAccountKind(e,t){let o=e.some(Re)?await this.takenAsBusiness(t):()=>!1,r=e.map((s,i)=>un(s,o(t[i])));t.forEach((s,i)=>{for(let a of Object.keys(s))Wt(ue,a,r[i])&&delete s[a]})}async takenAsBusiness(e){let t=await this.lookupsOf(ue);if(t&&!t.some(a=>a.name===ct))return()=>!0;let n=this.deps.queryTarget;if(!n)return()=>!1;this.personTypes??=n(xr).then(a=>new Set(a.flatMap(c=>typeof c.Id=="string"?[ne(c.Id)]:[])),()=>{});let o=await this.personTypes;if(!o)return()=>!1;let r=await this.deps.describeRecordTypes?.(ue).catch(()=>{}),s=new Set((r??[]).map(a=>ne(a.recordTypeId))),i=e.some(a=>typeof a.RecordTypeId!="string")?$o(r):void 0;return a=>{let c=a.RecordTypeId,d=typeof c=="string"&&c!==""?c:i;if(d===void 0)return!1;let m=ne(d);return!o.has(m)&&s.has(m)}}register(e,t){t.length>0&&this.deps.remapper.registerMappings(e,t)}async startAsDrafts(e,t){let n=new Map,o=Ae[e],{queryTarget:r,update:s}=this.deps;if(!o||!r||!s)return n;let i=this.lifecycleByObject.get(e);i||(i=wn(r,o),this.lifecycleByObject.set(e,i));let a=await i;return a&&t.forEach((c,d)=>{let m=bn(c.Status,a);m&&(n.set(d,String(c.Status)),c.Status=m)}),n}async applyDeferredStatuses(){let e={},{update:t}=this.deps;if(!t||this.deferredStatuses.length===0)return e;let n=new Map;for(let o of this.deferredStatuses)n.set(o.objectApiName,[...n.get(o.objectApiName)??[],o]);for(let[o,r]of n){let s=0,i=0,a=new me;for(let c=0;c<r.length;c+=this.batchSize){if(await this.checkPause()){this.noteLeftByStop(o,"statuses",r.slice(c).map(p=>p.id));break}let d=r.slice(c,c+this.batchSize),m=await this.updateSendingLocksAgain(t,o,d.map(p=>({Id:p.id,Status:p.status})),"status update(s)");d.forEach((p,l)=>{let g=m[l];if(g?.success){s++;return}i++,a.add(Nt(g))})}e[o]={applied:s,refusals:a.list(),...i>0?{leftDraft:i}:{}}}return this.deferredStatuses.length=0,e}noteLeftByStop(e,t,n){if(n.length===0)return;let o=this.leftByStop.get(e);o||(o={lookups:new Set,statuses:new Set},this.leftByStop.set(e,o));for(let r of n)o[t].add(r)}countEmailsTheStopHeld(e,t,n){let o=this.emailsAfterTheirTask.splice(0,this.emailsAfterTheirTask.length),r=this.emailsHeldAndNotSent+o.length;if(this.emailsHeldAndNotSent=0,r===0)return;let s=n[V]??{written:0,linked:0,failed:0,refusals:[]};n[V]={...s,notSent:(s.notSent??0)+r,heldForTheirTask:r};for(let d of[e.completedObjects,e.failedObjects]){let m=d.indexOf(V);m>=0&&d.splice(m,1)}if(t.includes(V))return;let i=[...this.planned],a=i.indexOf(V),c=t.findIndex(d=>i.indexOf(d)>a);t.splice(c<0?t.length:c,0,V)}countWhatTheStopLeft(e,t){let n=new Set(e);for(let r of this.owedLookups.splice(0,this.owedLookups.length))r.parents.some(i=>n.has(i)||this.deps.remapper.getTargetId(i,r.sourceId)!==void 0)?this.noteLeftByStop(r.objectApiName,"lookups",[r.recordId]):this.owedLookups.push(r);let o=this.deferredStatuses.splice(0,this.deferredStatuses.length);for(let r of o)this.noteLeftByStop(r.objectApiName,"statuses",[r.id]);for(let[r,s]of this.leftByStop){let i=t[r]??{written:0,linked:0,failed:0,refusals:[]};t[r]={...i,...s.lookups.size>0?{lookupsLeftEmpty:s.lookups.size}:{},...s.statuses.size>0?{statusesNotGivenBack:s.statuses.size}:{}}}}pause(){this.paused||(this.paused=!0,this.pausePromise=new Promise(e=>{this.pauseResolve=e}),this.emit("paused",this.makeEvent({type:"paused",timestamp:""})))}resume(){this.paused&&(this.paused=!1,this.pauseResolve?.(),this.pausePromise=null,this.pauseResolve=null,this.emit("resumed",this.makeEvent({type:"resumed",timestamp:""})))}skip(e){this.skippedObjects.add(e)}stopped(){return this.signal?.aborted===!0}wait(e){return this.deps.wait?this.deps.wait(e):_n(e,this.signal)}async checkPause(){return this.stopped()?!0:(this.paused&&this.pausePromise&&await this.pausePromise,this.stopped())}makeEvent(e){return{...e,timestamp:new Date().toISOString()}}};async function $t(u,e,t){try{return await u(e,t)}catch(n){let o=ee(n);return t.map(()=>({id:"",success:!1,errors:[o],errorDetails:[pt(o)]}))}}function Nt(u){return u?u.errorDetails&&u.errorDetails.length>0?u.errorDetails:u.errors.length>0?u.errors.map(e=>pt(e)):[Mr]:[Cr]}function Nr(u){return u.statusCode===Ne?u.message:`${u.statusCode}: ${u.message}`}var Ke=class{threshold;partitionSize;constructor(e=5e3,t=2e3){this.threshold=e,this.partitionSize=t}shouldUseGrappe(e){return e>this.threshold}partition(e,t){if(t<=this.partitionSize)return[{id:`${e}-0`,objectApiName:e,offset:0,limit:t,recordCount:t}];let n=[],o=0,r=0;for(;o<t;){let s=Math.min(this.partitionSize,t-o);n.push({id:`${e}-${r}`,objectApiName:e,offset:o,limit:s,recordCount:s}),o+=s,r++}return n}getThreshold(){return this.threshold}getPartitionSize(){return this.partitionSize}};var Br=`sandforge autopilot \u2014 run an Autopilot copy between two orgs, without the editor.
7
+ import{a as ks,b as Rs,f as As,g as Ss}from"./chunk-IAB5H7WN.mjs";import{c as bs}from"./chunk-C7CKDZMC.mjs";import"./chunk-RCW5BZNW.mjs";import"./chunk-DYHF6DNT.mjs";import"./chunk-KQVLZVOP.mjs";import"./chunk-YZQN7BRB.mjs";import"./chunk-QACFTHJM.mjs";import"./chunk-3HAVVEXF.mjs";import"./chunk-CZXDJXQP.mjs";import"./chunk-VRBETPHY.mjs";import"./chunk-BNHJCJJM.mjs";import"./chunk-IRQ4WANV.mjs";import"./chunk-H4OBZIX3.mjs";import"./chunk-JRLYWVF4.mjs";import"./chunk-PIQ2I67B.mjs";import"./chunk-FM4QCTO7.mjs";import{s as _t}from"./chunk-PBHDPTT6.mjs";import"./chunk-INIQ23K6.mjs";import"./chunk-SUIPDW5O.mjs";import{a as Io,b as xo,c as Ue,d as Mt,e as jo,f as Lo,g as $o,h as No,i as Do,j as Bo,k as _o,l as qo,m as rs,n as is,o as He,p as Lt,q as $t,r as Ee,s as as,t as Pe,u as Ce,w as cs}from"./chunk-YRULC27A.mjs";import"./chunk-GYDTM62J.mjs";import"./chunk-5JMQXHJ2.mjs";import"./chunk-HLROVOR6.mjs";import"./chunk-WF5S4FW5.mjs";import"./chunk-FV6MOSHD.mjs";import"./chunk-T542Z54E.mjs";import"./chunk-DO6PSHQZ.mjs";import"./chunk-ZIKLQZBG.mjs";import"./chunk-FYG47CNA.mjs";import"./chunk-GMY5427L.mjs";import{c as en}from"./chunk-Z5IUK2QO.mjs";import{Za as Bt,a as zo,d as Nt,e as us,f as ls,g as ps,h as fs,i as hs,j as ms,k as Dt,l as gs,m as ys,q as Re}from"./chunk-E5FSPXYH.mjs";import{a as Uo}from"./chunk-IQ5UKRHU.mjs";import"./chunk-VT6P3X6R.mjs";import"./chunk-ALWVNR34.mjs";import{a as ds}from"./chunk-QHE2RUWX.mjs";import{c as sn,d as rn,f as an}from"./chunk-6FARZYMJ.mjs";import"./chunk-TZXYVMZC.mjs";import"./chunk-TMIV3IWH.mjs";import"./chunk-CJAWKLAL.mjs";import"./chunk-PE7CHD2W.mjs";import"./chunk-VKREON6Q.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-BOGNK4LV.mjs";import{f as ut,h as tn,k as nn}from"./chunk-DDNCJVZ2.mjs";import{b as cn,c as dn,d as De,e as un,f as Oo,g as To,h as Eo,i as Po,j as Co,k as Mo,l as Fo,m as Ct}from"./chunk-C5AUNG6T.mjs";import{h as ns,i as os,k as ss}from"./chunk-3I6FXFCN.mjs";import{c as In,d as xn}from"./chunk-7O6EFNQS.mjs";import"./chunk-3LRFPGYZ.mjs";import"./chunk-34SMB5PA.mjs";import{a as Qo,b as Jo,c as Zo,d as jt,e as es,f as ts}from"./chunk-GB6W4Q56.mjs";import{h as Go,i as Wo}from"./chunk-AVY742BJ.mjs";import{a as Ho,b as Ft,c as It,d as Ko,e as Xo,f as Yo,g as Vo,h as xt}from"./chunk-BWWQXU2B.mjs";import"./chunk-KWUS7UAV.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-HZCS6EED.mjs";import"./chunk-NV5QA2HY.mjs";import"./chunk-EGL3I3IX.mjs";import"./chunk-CSMGP53U.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-YDXMTWAT.mjs";import"./chunk-M6P5ZZLE.mjs";import{f as ro,m as io,o as ao,p as co,q as uo}from"./chunk-35B73566.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-PVZ72OOQ.mjs";import{d as Ln}from"./chunk-QIRO4HTE.mjs";import{g as jn}from"./chunk-TYUYPFDJ.mjs";import"./chunk-TICZXC53.mjs";import"./chunk-DLSU66MY.mjs";import"./chunk-ATQML7ZK.mjs";import"./chunk-H6BHWAX7.mjs";import"./chunk-4CSBZZAL.mjs";import{a as nt}from"./chunk-AL4C3GFT.mjs";import"./chunk-GP5J3DGS.mjs";import"./chunk-5LFSFYFJ.mjs";import{b as dt,c as Ne}from"./chunk-WQCXOZEJ.mjs";import"./chunk-OT2NHL2V.mjs";import{b as Zn,c as eo,g as to}from"./chunk-ZVU7MD2S.mjs";import{Cc as ke,Dc as So,Hb as wo,Nb as Et,Qc as vo,Rc as Pt,Wa as lo,bb as vt,cb as po,dc as bo,j as no,k as At,kb as fo,mb as ho,nb as Ot,pb as mo,q as Te,qc as ko,r as oo,rc as Ro,s as so,tb as Tt,vb as We,vc as Ao,wb as go,x as Ge,zb as yo}from"./chunk-OLCS7JCT.mjs";import{i as Cn,j as Mn,l as Fn}from"./chunk-TQ6HEJ73.mjs";import{a as ct,b as Jt}from"./chunk-65AMXOQU.mjs";import{q as St}from"./chunk-6HHSAPIM.mjs";import"./chunk-K5PUMHZU.mjs";import"./chunk-VV3B6IC3.mjs";import{a as ue}from"./chunk-4TLYUZD5.mjs";import"./chunk-EUIALBMX.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-Q7TLC3I2.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-ATBQIE2V.mjs";import{b as Qn,d as bt,e as Jn,f as kt,g as Rt,h as Oe}from"./chunk-UCUFLFNK.mjs";import"./chunk-MS4FJDFD.mjs";import"./chunk-4XROG5CT.mjs";import{b as Zt,d as on,f as lt,h as ws}from"./chunk-LCDPCUXS.mjs";import"./chunk-TQ2TQHTT.mjs";import{a as Un,b as mt,c as gt,f as Hn,h as Kn,j as qe,l as Xn,m as Yn}from"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import{a as $n}from"./chunk-EADHKH3A.mjs";import{e as Pn}from"./chunk-DAUX63UB.mjs";import{$ as Sn,Y as kn,Z as Rn,_ as An,a as ln,b as J,c as _e,d as pn,da as ve,f as fn,fa as vn,g as hn,ia as On,ja as Tn,ka as En,m as pt,n as mn,o as gn,p as yn,q as le,r as me,s as ft,t as Se,u as wn,z as bn}from"./chunk-SZOJ7BEJ.mjs";import{a as Be}from"./chunk-TZE3Y7IQ.mjs";import{b as ee}from"./chunk-CA5NAXSU.mjs";import"./chunk-PC247GKX.mjs";import{b as ze,c as yt,j as wt,k as Vn}from"./chunk-22L43JMK.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TUACWKIH.mjs";import{a as ye,j as ht,l as Nn,o as Dn,p as Bn,q as _n,t as qn,u as zn,v as Gn,w as Wn}from"./chunk-ICIYL45C.mjs";import"./chunk-3KJCSYXY.mjs";import"./chunk-HDDJ3CVN.mjs";import{$ as ot,$c as Xt,Cc as st,Fc as Wt,Lc as rt,Mc as be,Oc as it,Pc as Ut,Qd as Vt,Rc as at,Rd as Le,Tc as Ht,Vd as Qt,Zc as Kt,qd as Yt,te as $e}from"./chunk-J347SPU6.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";var vs=3,Us="the source changed since the plan: plan again";function Ps(u,e){return{holds:[...u.links.filter(t=>t.kind==="holds"),...u.requiredOfParents,...u.outward.filter(t=>t.required)],kept:e}}function Os(u,e){return typeof u!="string"||u===""?!1:e===void 0||e!==null&&u.startsWith(e)}function Cs(u,e,t){let n=new Map(t.map((r,i)=>[r,i])),s=new Set(e),o={links:[],outward:[],requiredOfParents:[]};for(let[r,i]of u)for(let a of $o(r,i))for(let c of a.targets.filter(d=>u.has(d))){let d=a.polymorphic?{prefix:u.get(c)?.keyPrefix??null}:{},m={objectApiName:r,field:a.field,parent:c,...d};if(!s.has(r))s.has(c)&&a.required&&o.requiredOfParents.push({...m,kind:"holds"});else if(!s.has(c))o.outward.push({...m,required:a.required});else if(a.required)o.links.push({...m,kind:"holds"});else if(c===r)o.links.push({...m,kind:"selfReference"});else{let p=(n.get(c)??0)<(n.get(r)??0);o.links.push({...m,kind:p?"holds":"owed"})}}return o}function Ms(u,e){let t=new Set(u),n=new Set(e.links.filter(s=>s.kind!=="holds").map(s=>s.objectApiName));return(s,o)=>t.has(s)&&(o==="insert"||o==="update"&&(n.has(s)||ve[s]!==void 0))}function Fs(u,e,t){return typeof u.unread=="string"?{perRecord:[],notCounted:[],unread:u.unread}:Po($e(u,e,t),t)}function Hs(u){let e=new Map(u.order.map((t,n)=>[t,n]));return u.order.map(t=>{let n=u.rows.get(t)??[],s=u.lookups.links.filter(i=>i.objectApiName===t),o=u.lookups.outward.filter(i=>i.objectApiName===t),r={name:t,rows:n,at:new Map(n.map((i,a)=>[i.Id,a])),heldBefore:[],heldAfter:[],loose:[],named:[],roots:[],followers:[],persons:new Set(t===le||t===me?n.flatMap((i,a)=>i[Mt]===!0?[a]:[]):[])};return n.forEach((i,a)=>{let c=[],d=[],m=[];for(let p of s){let l=i[p.field];if(!Os(l,p.prefix))continue;let g={link:p,id:l};p.kind!=="holds"?m.push(g):(e.get(p.parent)??0)<(e.get(t)??0)?c.push(g):d.push(g)}r.heldBefore.push(c),r.heldAfter.push(d),r.loose.push(m),r.named.push(o.flatMap(p=>{let l=i[p.field];return Os(l,p.prefix)?[{parent:p.parent,id:l}]:[]})),(c.length>0?r.followers:r.roots).push(a)}),r})}function Ts(u,e){let t=new Map(u.map(o=>[o.name,o])),n=new Map,s=[...e].flatMap(([o,r])=>[...r].map(i=>({name:o,id:i})));for(let o=s.pop();o;o=s.pop()){let r=t.get(o.name),i=r?.at.get(o.id);if(!r||i===void 0)continue;let a=n.get(o.name)??new Set;if(n.set(o.name,a),!a.has(i)){a.add(i);for(let c of[...r.heldBefore[i],...r.heldAfter[i]])s.push({name:c.link.parent,id:c.id})}}return n}function Es(u){return`${u} record${u===1?"":"s"}`}function Ks(u,e){return[...u.parentIds].every(([t,n])=>{let s=new Set(e.get(t)?.ids??[]);return n.every(o=>s.has(o))})}async function Is(u){let{budget:e,room:t,mode:n,parents:s,maxRecords:o}=u,r=Hs(u),i=b=>{let k=n.caps?.[b]??n.all;return k===void 0?void 0:Math.max(1,Math.floor(k))},a=r.some(b=>b.heldAfter.some(k=>k.length>0)),c=new Map;for(let b of r){if(b.name!==be)continue;let k=b.rows.filter(C=>C[jo]===!0);k.length>0&&c.set(b.name,new Set(k.map(C=>C.Id)))}let d=Ts(r,c),m=b=>{let k={kept:new Map,ids:new Map,cut:new Map},C=new Set;for(let M of r){let F=d.get(M.name)??C,z=i(M.name),T=M.roots.filter(H=>!F.has(H)),D=T.length===0?0:Math.max(1,Math.round(b*Math.min(T.length,z??1/0))),B=Ct(T.length,D).map(H=>T[H]),I=new Map;for(let H of M.followers){if(F.has(H))continue;let K=M.heldBefore[H].find(de=>!k.ids.get(de.link.parent)?.has(de.id));K?I.set(H,K.link):B.push(H)}B.sort((H,K)=>H-K);let te=M.name===me?B.filter(H=>M.persons.has(H)):[],Y=te.length>0?B.filter(H=>!M.persons.has(H)):B,re=z===void 0?Y.length:Math.max(0,z-F.size-te.length),se=Y.length>re?Ct(Y.length,re).map(H=>Y[H]):Y,he=new Set([...F,...te,...se]);k.kept.set(M.name,he),k.ids.set(M.name,new Set([...he].map(H=>M.rows[H].Id))),k.cut.set(M.name,I)}if(!a)return k;for(let M=!0;M;){M=!1;for(let F of r){let z=d.get(F.name)??C,T=k.kept.get(F.name)??new Set;for(let D of[...T]){if(z.has(D))continue;let B=[...F.heldAfter[D],...F.heldBefore[D]].find(I=>!k.ids.get(I.link.parent)?.has(I.id));B&&(T.delete(D),k.ids.get(F.name)?.delete(F.rows[D].Id),k.cut.get(F.name)?.set(D,B.link),M=!0)}}}return k},p=b=>{let k=new Map;for(let C of r){let M=0;for(let F of b.kept.get(C.name)??[])C.loose[F].some(T=>b.ids.get(T.link.parent)?.has(T.id))&&M++;M>0&&k.set(C.name,M)}return k},l=(b,k)=>{let C=new Map,M=0;for(let T of r){let D=b.kept.get(T.name)??new Set,B=0;for(let I of D)T.persons.has(I)&&B++;C.set(T.name,D.size),M+=vt(T.name,{rows:D.size,personAccounts:B})}for(let[T,{records:D,personAccounts:B}]of k)C.set(T,(C.get(T)??0)+D),M+=vt(T,{rows:D,...B!==void 0?{personAccounts:B}:{}});let F=p(b),z=Co(t,(T,D)=>{let B=C.get(T)??0;return D==="insert"||ve[T]!==void 0?B:F.get(T)??0});return{records:[...C.values()].reduce((T,D)=>T+D,0),bytes:M,roomBytes:z,requests:mo([...C.values()].map(T=>({rows:T})))}},g=new Map;for(let b of r)for(let k of b.named)for(let{parent:C,id:M}of k){let F=g.get(C)??new Set;g.set(C,F),F.add(M)}let y=[...g.values()].reduce((b,k)=>b+k.size,0),f=b=>{let k=new Map,C=0;for(let z of r)for(let T of b.kept.get(z.name)??[])for(let{parent:D,id:B}of z.named[T]){let I=k.get(D)??new Set;k.set(D,I),I.has(B)||C++,I.add(B)}let M=y>0?C/y:0,F=new Map;for(let[z,{ids:T,personAccounts:D}]of s){let B=Math.max(0,T.length-(g.get(z)?.size??0)),I=Math.min(T.length,(k.get(z)?.size??0)+Math.ceil(B*M));I!==0&&F.set(z,{records:I,...D!==void 0?{personAccounts:Math.ceil(D*I/T.length)}:{}})}return F},R=b=>new Map(b.added.map(k=>{let C=b.personAccounts.get(k);return[k,{records:b.parentIds.get(k)?.length??0,...C!==void 0?{personAccounts:C}:{}}]})),w=b=>b.bytes+b.roomBytes<=e.bytes,x=b=>e.runRequests===void 0||b.requests<=e.runRequests,$=b=>o===void 0||b.records<=o,E=b=>w(b)&&x(b)&&$(b),L=b=>w(b)?x(b)?"maxTotal":"apiRequests":e.terms.limitedBy,S=b=>w(b)?x(b)?{bound:"maxTotal",records:b.records,allowed:o??0}:{bound:"apiRequests",requests:b.requests,allowed:e.runRequests??0}:{bound:"storage",takesMB:(b.bytes+b.roomBytes)/1048576,fitsMB:e.bytes/1048576},j=b=>{if(!w(b)){let k=So((b.bytes+b.roomBytes)/1048576,e.bytes/1048576);return`${k.over} MB`+(b.roomBytes>0?", room for what the org's automation creates under them included":"")+`, past the ${k.bound} MB that fit`}return x(b)?`${Es(b.records)}, past the ${o??0} the run may write`:`about ${b.requests} API requests, past the ${e.runRequests??0} that leave the org a tenth of its daily requests`},P=b=>new Map(r.map(k=>[k.name,[...b.kept.get(k.name)??[]].sort((C,M)=>C-M).map(C=>k.rows[C])])),A=(b,k,C,M,F,z)=>{let T=r.map(I=>{let te=k.cut.get(I.name)??new Map,Y=new Map;for(let se of te.values()){let he=`${se.field}
8
+ ${se.parent}`,H=Y.get(he)??{field:se.field,parent:se.parent,count:0};Y.set(he,{...H,count:H.count+1})}let re=k.kept.get(I.name)?.size??0;return{objectApiName:I.name,inSource:I.rows.length,kept:re,cutSpread:I.rows.length-re-te.size,cutWithParent:[...Y.values()].sort((se,he)=>he.count-se.count)}}),D=new Map,B=(I,te,Y)=>{let re=`${I}
9
+ ${te}
10
+ ${Y}`,se=(D.get(re)?.count??0)+1;D.set(re,{objectApiName:I,field:te,count:se,why:Y})};for(let I of r)for(let te of k.kept.get(I.name)??[])for(let Y of I.loose[te])k.ids.get(Y.link.parent)?.has(Y.id)||B(I.name,Y.link.field,Y.link.kind==="owed"?"owed":"selfReference");for(let I of F?.namingSelected??[])I.required||k.ids.get(I.target)?.has(I.id)||B(I.objectApiName,I.field,"onParent");return{heldBy:M,...z?{cannotFit:z.words}:{},kept:P(k),...F?{walk:F}:{},report:{mode:n,heldBy:M,...z?{cannotFit:z.said}:{},budget:{...Mo(e,C.roomBytes,t),...M==="apiRequests"?{limitedBy:"apiRequests"}:{}},...b!==void 0?{share:b}:{},objects:T,emptied:[...D.values()],parents:F?F.added.map(I=>({objectApiName:I,records:F.parentIds.get(I)?.length??0})):[...s].map(([I,{ids:te}])=>({objectApiName:I,records:te.length})),records:C.records,estimateMB:C.bytes/1048576}}},oe={words:Us,said:{why:"sourceChanged"}},X=b=>({words:`with these caps the plan takes ${j(b)}: lower them, or fit by share`,said:{why:"caps",over:S(b)}}),Z=Object.keys(n.caps??{}).find(b=>!r.some(k=>k.name===b)),N=r.reduce((b,k)=>Math.max(b,Math.min(k.roots.length,i(k.name)??1/0)),0),U=m(1),V=l(U,f(U));if(Z!==void 0)return A(void 0,U,V,"caps",void 0,{words:`the plan selects no ${Z}: a cap holds an object it selects`,said:{why:"capNotSelected",object:Z}});if(r.some(b=>b.rows.length>(u.planned.get(b.name)??0)))return A(void 0,U,V,e.terms.limitedBy,void 0,oe);let ge=n.all!==void 0||Object.keys(n.caps??{}).length>0,G=n.share===!0||!ge,Ae=b=>{let k=m(b/N);return l(k,f(k))};if(r.every(b=>U.kept.get(b.name)?.size===b.rows.length)&&E(V))return A(G?1:void 0,U,V,"whole",void 0);if(N===0)return A(void 0,U,V,e.terms.limitedBy,void 0,oe);let _=N;if(!E(V)){if(!G)return A(void 0,U,V,L(V),void 0,X(V));if(_=Fo(N,b=>E(Ae(b))),_===0){let b=m(1/N),k=l(b,f(b));return A(1/N,b,k,L(k),void 0,{words:`the least it can be cut to \u2014 one record of each object with none to follow, and what follows them, ${Es(k.records)} \u2014 takes ${j(k)}`,said:{why:"least",over:S(k)}})}}let ce=_<N?L(Ae(_+1)):ge?"caps":e.terms.limitedBy,Q=b=>G?b/N:void 0;if(s.size===0){let b=m(_/N);return A(Q(_),b,l(b,new Map),ce,void 0)}for(let b=1;b<=vs;b++){let k=m(_/N),C=await u.walk(P(k));if(!Ks(C,s)){let T=l(k,R(C));return A(Q(_),k,T,ce,void 0,oe)}let M=C.namingSelected.filter(T=>T.required&&r.find(D=>D.name===T.target)?.at.has(T.id)===!0&&!k.ids.get(T.target)?.has(T.id));if(M.length>0){for(let{target:T,id:D}of M){let B=c.get(T)??new Set;c.set(T,B),B.add(D)}d=Ts(r,c);continue}let F=l(k,R(C));if(E(F))return A(Q(_),k,F,ce,C);if(ce=L(F),!G)return A(void 0,k,F,ce,C,X(F));if(_===1)return A(Q(_),k,F,ce,C,{words:"the least it can be cut to, with the parents its records name, takes "+j(F),said:{why:"least",over:S(F)}});let z=Math.max((F.bytes+F.roomBytes)/Math.max(1,e.bytes),e.runRequests!==void 0?F.requests/Math.max(1,e.runRequests):0,o!==void 0?F.records/Math.max(1,o):0);_=Math.max(1,Math.min(_-1,Math.floor(_/z)))}let fe=m(_/N),pe=l(fe,f(fe));return A(Q(_),fe,pe,ce,void 0,{words:`could not fit in ${vs} rounds: fit by caps`,said:{why:"rounds"}})}function xs(u,e,t){let{selected:n}=u.scope,s=e.walk?.added??[],o=new Set([...n,...s]),r=new Map(e.walk?.parentIds??[]),i=new Map,a=new Map;for(let f of n){let R=e.kept.get(f)??[];r.set(f,R.map(w=>w.Id)),i.set(f,R.length),u.personAccounts.has(f)&&a.set(f,R.filter(w=>w[Mt]===!0).length)}for(let f of s)i.set(f,e.walk?.parentIds.get(f)?.length??0),u.personAccounts.has(f)&&a.set(f,e.walk?.personAccounts.get(f)??0);let c=new Map([...u.scope.leftEmpty,...e.walk?.leftEmpty??[]].filter(f=>o.has(f.objectApiName)&&!o.has(f.target)).map(f=>[`${f.objectApiName}.${f.fieldApiName}>${f.target}`,f])),{maxDepth:d,maxObjects:m,followedByDefault:p,currencies:l}=u.scope,g=p?.filter(f=>o.has(f.objectApiName)),y=l?.objects.filter(f=>o.has(f));return{...u,objectDescribes:new Map([...u.objectDescribes].filter(([f])=>o.has(f))),autoDiscoveredObjects:s,missingInTarget:u.missingInTarget.filter(f=>o.has(f)),recordCounts:i,totalObjectsScanned:o.size,parentIds:r,personAccounts:a,scope:{maxDepth:d,maxObjects:m,selected:n,parents:s.map(f=>({objectApiName:f,records:i.get(f)??0})),leftEmpty:[...c.values()],standardNeeded:u.scope.standardNeeded.filter(f=>o.has(f.objectApiName)),...g!==void 0&&g.length>0?{followedByDefault:g}:{},...l&&y!==void 0&&y.length>0?{currencies:{...l,objects:y}}:{},fitted:t}}}var Ke=class{deps;eventListeners=[];runningExecutors=[];pendingSkips=new Set;constructor(e){this.deps=e}onEvent(e){return this.eventListeners.push(e),()=>{this.eventListeners=this.eventListeners.filter(t=>t!==e)}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch{}}listObjects(e,t,n){return this.deps.schemaScanner.listObjects(e,t,n)}countObjects(e,t){return this.deps.schemaScanner.countObjects(e,t)}async scanSchemas(e,t,n,s){this.emitEvent({type:"scan-started",timestamp:new Date().toISOString()});let o=await this.deps.schemaScanner.scan(e,t,n.selectedObjects,n.includeStandardObjects,{...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.maxObjects!==void 0?{maxObjects:n.maxObjects}:{},...n.maxRecordsPerObject!==void 0&&n.maxRecordsPerObject>0?{maxRecordsPerObject:n.maxRecordsPerObject}:{},...s?{onProgress:s}:{}});return this.emitEvent({type:"scan-completed",timestamp:new Date().toISOString()}),o}buildGraph(e,t){let n=new Map;for(let[s,o]of e.objectDescribes){let r=o.fields.map(i=>({name:i.name,type:i.type,nillable:i.nillable,referenceTo:i.referenceTo,relationshipName:i.relationshipName}));n.set(s,{name:o.name,fields:r})}return this.deps.graphBuilder.build(n,e.recordCounts,t)}buildCompliance(e,t,n=[]){let s=this.deps.complianceEngine.buildProfile(e,Do(n,t)),o=this.deps.complianceEngine.generateRules(s);return{profile:s,rules:o}}generatePlan(e,t,n,s){let o=Bo(t,e.nodes.map(c=>c.objectApiName),n),r={...this.deps.complianceEngine.buildSummary(n),...o.length>0?{notCovered:o}:{}},i=this.deps.planGenerator.generate(e,t,r),a=s?{...i,scope:s}:i;return this.emitEvent({type:"plan-generated",timestamp:new Date().toISOString()}),a}async fitPlan(e,t){let{scan:n,graph:s,plan:o,rules:r,mode:i,budget:a,maxRecords:c,onProgress:d}=t,{schemaScanner:m}=this.deps,p=0,l={describe:N=>e.describe(N),describeGlobal:()=>e.describeGlobal(),query:N=>(p++,e.query(N)),...e.queryMore?{queryMore:N=>(p++,e.queryMore.call(e,N))}:{}},g=o.waves.map(N=>N.objects),y=new Map,f=g.flatMap(N=>De(N,s.edges).groups.filter(U=>U.length>1));for(let N of new Set(f.flat()))y.set(N,await t.describeLookups?.(N).catch(()=>null)??null);let R=un(g,s.edges,N=>y.get(N)),{selected:w}=n.scope,x=Cs(n.objectDescribes,w,R),$=Ms(R,x),E=Fs(t.automation,t.mutePlan,$),L=await m.readFitRows(l,n,d),S=await Is({order:R.filter(N=>w.includes(N)),rows:L,planned:n.recordCounts,lookups:x,parents:new Map(n.scope.parents.map(({objectApiName:N})=>{let U=n.personAccounts.get(N);return[N,{ids:n.parentIds.get(N)??[],...U!==void 0?{personAccounts:U}:{}}]})),budget:a,room:E,mode:i,...c!==void 0?{maxRecords:c}:{},walk:N=>m.walkFrom(l,n,N,d)}),j=E.unread!==void 0?{automationUnread:E.unread}:{},P={...S.report,requestsRead:p,...j,...t.mutePlan?{countedMuted:!0}:{},...c!==void 0?{maxTotal:c}:{}},A=new Map([...S.kept].map(([N,U])=>[N,U.map(V=>V.Id)])),oe={heldBy:S.heldBy,report:P,keptIds:A,...j};if(S.cannotFit!==void 0)return{...oe,cannotFit:S.cannotFit};if(S.heldBy==="whole")return oe;let X=xs(n,S,P),Z=this.buildGraph(X,t.batchSize);return{...oe,fitted:{scan:X,graph:Z,plan:this.generatePlan(Z,o.complianceFramework,r,X.scope),run:Ps(x,X.parentIds)}}}async executePlan(e,t,n,s,o,r,i,a){let c=Array.from(s.values()).reduce((w,x)=>w+x,0),d=this.isGrappeActive(c),m=`autopilot-${Date.now()}`;d&&this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:m,totalPartitions:e.waves.length,totalRecords:c}}),this.emitEvent({type:"execution-started",timestamp:new Date().toISOString()});let p=this.deps.createExecutor(),l=()=>{},g=o?p.on("node-completed",o):l,y=o?p.on("node-failed",o):l,f=d?this.relayWavesAsPartitions(p,m):l;for(let w of this.pendingSkips)p.skip(w);this.pendingSkips.clear(),this.runningExecutors.push(p);let R;try{R=await p.execute(e,t.edges,n,s,r,i,a)}finally{this.runningExecutors.splice(this.runningExecutors.indexOf(p),1),g(),y(),f()}return this.emitEvent({type:"execution-completed",timestamp:new Date().toISOString()}),d&&this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:m,totalProcessed:R.totalSuccess+R.totalSkipped,totalFailed:R.totalFailure}}),R}relayWavesAsPartitions(e,t){let n=0,s=0,o=e.on("node-completed",a=>{s+=a.successCount+a.failureCount}),r=e.on("node-failed",a=>{s+=a.partialSuccessCount+a.failureCount}),i=e.on("wave-completed",()=>{n++,this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:`${t}-wave-${n}`,percentage:100,processedRecords:s}}),s=0});return()=>{o(),r(),i()}}isGrappeActive(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&this.deps.grappeAdapter&&e>=t.autoActivateThreshold)}generateReport(e,t,n,s,o,r){return this.deps.complianceEngine.generateReport(e,t,n,s,o,r)}latestRunningExecutor(){return this.runningExecutors[this.runningExecutors.length-1]}pause(){this.latestRunningExecutor()?.pause()}resume(){this.latestRunningExecutor()?.resume()}skip(e){let t=this.latestRunningExecutor();if(t){t.skip(e);return}this.pendingSkips.add(e)}};var Xe=class{build(e,t,n=200){let s=this.extractEdges(e),o=Xs(s,new Set(e.keys())),r=this.tarjanSCC(Array.from(e.keys()),o),i=this.resolveCycles(r,o),{order:a,levels:c}=this.topologicalSort(Array.from(e.keys()),o,r),d=this.buildNodes(e,t,a,c,n),m=this.computeStats(d,s,i);return{nodes:d,edges:s,cycles:i,stats:m}}extractEdges(e){let t=[],n=new Set(e.keys());for(let[s,o]of e)for(let r of o.fields){if(r.type!=="reference"||r.referenceTo.length===0)continue;let i=r.referenceTo.filter(d=>n.has(d));if(i.length===0)continue;if(i.length>1){for(let d of i)t.push({from:d,to:s,fieldApiName:r.name,relationshipType:"polymorphic",required:!r.nillable});continue}let a=i[0],c;a===s?c="hierarchical":r.nillable?c="lookup":c="master_detail",t.push({from:a,to:s,fieldApiName:r.name,relationshipType:c,required:!r.nillable})}return t}tarjanSCC(e,t){let n=new Map;for(let r of e)n.set(r,[]);for(let r of t){let i=n.get(r.to);i&&i.push(r.from)}let s={index:0,stack:[],onStack:new Set,indices:new Map,lowLinks:new Map,sccs:[]},o=[...e].sort();for(let r of o)s.indices.has(r)||this.tarjanStrongConnect(r,n,s);return s.sccs}tarjanStrongConnect(e,t,n){n.indices.set(e,n.index),n.lowLinks.set(e,n.index),n.index++,n.stack.push(e),n.onStack.add(e);let s=t.get(e)??[];for(let o of s)if(n.indices.has(o)){if(n.onStack.has(o)){let r=n.lowLinks.get(e)??0,i=n.indices.get(o)??0;n.lowLinks.set(e,Math.min(r,i))}}else{this.tarjanStrongConnect(o,t,n);let r=n.lowLinks.get(e)??0,i=n.lowLinks.get(o)??0;n.lowLinks.set(e,Math.min(r,i))}if(n.lowLinks.get(e)===n.indices.get(e)){let o=[],r;do r=n.stack.pop(),n.onStack.delete(r),o.push(r);while(r!==e);n.sccs.push(o.sort())}}resolveCycles(e,t){let n=[],s=new Set;for(let o of t)o.from===o.to&&o.relationshipType==="hierarchical"&&s.add(o.from);for(let o of s)n.push({objects:[o],strategy:"two_pass",description:`Insert ${o} without self-lookup, update in 2nd pass`});for(let o of e){if(o.length<=1)continue;let r=new Set(o),i=t.filter(d=>r.has(d.from)&&r.has(d.to)&&d.from!==d.to),a,c;o.length===2&&i.some(m=>!m.required)?(a="nullable_lookup",c=`Insert ${o[0]} without ${o[1]} lookup, insert ${o[1]} with ${o[0]} lookup, update ${o[0]}`):(a="upsert_external_id",c="Decompose cycle into waves with upsert + external ID"),n.push({objects:[...o],strategy:a,description:c})}return n}topologicalSort(e,t,n){let s=new Map;for(let l=0;l<n.length;l++)for(let g of n[l])s.set(g,l);let o=n.length,r=new Map;for(let l=0;l<o;l++)r.set(l,new Set);for(let l of t){let g=s.get(l.from),y=s.get(l.to);g!==void 0&&y!==void 0&&g!==y&&r.get(y).add(g)}let i=new Map;for(let[l,g]of r)i.set(l,new Set(g));let a=[],c=new Map;for(;i.size>0;){let l=[];for(let[g,y]of i)y.size===0&&l.push(g);if(l.length===0){for(let g of i.keys())a.push(g),c.has(g)||c.set(g,0);break}l.sort((g,y)=>g-y);for(let g of l){a.push(g);let y=r.get(g)??new Set,f=-1;for(let R of y)f=Math.max(f,c.get(R)??0);c.set(g,y.size===0?0:f+1),i.delete(g);for(let R of i.values())R.delete(g)}}let d=new Map,m=new Map,p=0;for(let l of a){let g=n[l],y=c.get(l)??0,f=[...g].sort();for(let R of f)d.set(R,p),m.set(R,y),p++}for(let l of e)d.has(l)||(d.set(l,p),m.set(l,0),p++);return{order:d,levels:m}}buildNodes(e,t,n,s,o){let r=[];for(let i of e.keys()){let a=t.get(i)??0;r.push({objectApiName:i,recordCount:a,estimatedApiCalls:a===0?0:Math.ceil(a/o),piiFields:[],anonymizationRules:[],status:"pending",progress:0,insertOrder:n.get(i)??0,level:s.get(i)??0,successCount:0,failureCount:0,errors:[],elapsedMs:0,apiCallsUsed:0})}return r.sort((i,a)=>i.insertOrder-a.insertOrder),r}computeStats(e,t,n){return{totalObjects:e.length,totalRelationships:t.length,cycleCount:n.length,maxDepth:Math.max(0,...e.map(s=>s.level)),totalRecords:e.reduce((s,o)=>s+o.recordCount,0),totalEstimatedApiCalls:e.reduce((s,o)=>s+o.estimatedApiCalls,0)}}};function Xs(u,e){let t=mn(e);return t.length===0?[...u]:[...u.filter(n=>!(n.to===J&&n.fieldApiName==="ActivityId")),...t.map(n=>({from:n.sourceObject,to:n.targetObject,fieldApiName:n.relationshipName,relationshipType:"lookup",required:!0}))]}import{createHash as Ys,randomUUID as Vs}from"node:crypto";var Qs=["fake","mask","hash","nullify","redact","shuffle","truncate","preserve_format","age_band","generalize"],Ye=class{builtInRules;constructor(){this.builtInRules=new Map,this.builtInRules.set("gdpr",this.buildGDPRRules()),this.builtInRules.set("ccpa",this.buildCCPARules()),this.builtInRules.set("hipaa",this.buildHIPAARules()),this.builtInRules.set("pci_dss",this.buildPCIDSSRules())}buildProfile(e,t,n=[]){let s=this.builtInRules.get(e)??[];return{framework:e,rules:s,autoDetectedPII:t,userOverrides:n,auditRequired:e!=="none"&&e!=="custom"}}generateRules(e){if(e.framework==="none")return[];let t=new Map;for(let s of e.userOverrides){let o=`${s.objectApiName}.${s.fieldApiName}`;t.set(o,s)}let n=[];for(let s of e.autoDetectedPII){let o=`${s.objectApiName}.${s.fieldApiName}`,r=t.get(o);if(r){if(r.method==="skip")continue;n.push({objectApiName:s.objectApiName,fieldApiName:s.fieldApiName,method:r.method,piiCategory:s.piiCategory,aiConfidence:s.confidence,userOverridden:!0,fieldType:s.fieldType});continue}let i=this.findMatchingRule(e.rules,s.piiCategory),a=i&&i.requiredMethod!=="any"?i.requiredMethod:s.suggestedMethod;n.push({objectApiName:s.objectApiName,fieldApiName:s.fieldApiName,method:a,piiCategory:s.piiCategory,aiConfidence:s.confidence,userOverridden:!1,fieldType:s.fieldType,...s.detectionMethod==="org_classification"?{orgClassified:!0}:{}})}return n}buildSummary(e){let t={};for(let o of Qs)t[o]=0;for(let o of e)t[o.method]++;let n=[...new Set(e.map(o=>o.objectApiName))],s=e.filter(o=>o.orgClassified===!0).length;return{totalPiiFields:e.length,totalFieldsToAnonymize:e.length,methodBreakdown:t,objectsWithPii:n,...s>0?{orgClassification:{fields:s,refused:[]}}:{}}}generateReport(e,t,n,s,o,r){let i=new Set(e.userOverrides.map(y=>`${y.objectApiName}.${y.fieldApiName}`)),a=t.map(y=>{let f=this.findMatchingRule(e.rules,y.piiCategory),R=f?f.id:"custom",w=n.get(y.objectApiName)??0,x=`${y.objectApiName}.${y.fieldApiName}`;return{objectApiName:y.objectApiName,fieldApiName:y.fieldApiName,piiCategory:y.piiCategory,anonymizationMethod:y.method,recordsAnonymized:w,ruleApplied:R,userOverridden:i.has(x)||y.userOverridden}}),c=this.buildObjectSummaries(t,n,e),d=this.computeOverallStatus(c),m=new Date().toISOString(),p=Vs(),l=JSON.stringify(a),g=Ys("sha256").update(l).digest("hex");return{id:p,framework:e.framework,generatedAt:m,sourceOrgId:s,targetOrgId:o,totalFieldsScanned:r,piiFieldsDetected:e.autoDetectedPII.length,piiFieldsAnonymized:t.length,entries:a,objectSummaries:c,overallStatus:d,checksumSha256:g}}findMatchingRule(e,t){return e.find(n=>n.targetPiiCategories.includes(t))}buildObjectSummaries(e,t,n){let s=new Set;for(let r of e)s.add(r.objectApiName);for(let r of n.autoDetectedPII)s.add(r.objectApiName);let o=[];for(let r of s){let i=e.filter(l=>l.objectApiName===r),a=n.autoDetectedPII.filter(l=>l.objectApiName===r),c=[...new Set(i.map(l=>l.method))],d=t.get(r)??0,m=a.length>0&&a.every(l=>i.some(g=>g.fieldApiName===l.fieldApiName)),p=a.length===0||m?"pass":i.length>0?"partial":"fail";o.push({objectApiName:r,recordCount:d,piiFieldCount:a.length,anonymizationMethods:c,status:p})}return o}computeOverallStatus(e){return e.length===0||e.every(s=>s.status==="pass")?"pass":e.every(s=>s.status==="fail")?"fail":"partial"}buildGDPRRules(){return[{id:"gdpr-01",framework:"gdpr",category:"data_minimization",description:"Anonymize personal identifiers (name, email, phone, address)",targetPiiCategories:["PII"],requiredMethod:"fake",articleReference:"GDPR Art. 25"},{id:"gdpr-02",framework:"gdpr",category:"data_protection",description:"Hash sensitive identifiers for pseudonymization",targetPiiCategories:["SENSITIVE"],requiredMethod:"hash",articleReference:"GDPR Art. 32"},{id:"gdpr-03",framework:"gdpr",category:"health_data",description:"Nullify health-related data",targetPiiCategories:["PHI"],requiredMethod:"nullify",articleReference:"GDPR Art. 9"},{id:"gdpr-04",framework:"gdpr",category:"financial_data",description:"Mask payment card data",targetPiiCategories:["PCI"],requiredMethod:"mask",articleReference:"GDPR Art. 32"}]}buildCCPARules(){return[{id:"ccpa-01",framework:"ccpa",category:"personal_info",description:"Anonymize personal information (name, email, phone)",targetPiiCategories:["PII"],requiredMethod:"fake"},{id:"ccpa-02",framework:"ccpa",category:"commercial_info",description:"Mask commercial and financial data",targetPiiCategories:["PCI","SENSITIVE"],requiredMethod:"mask"},{id:"ccpa-03",framework:"ccpa",category:"biometric",description:"Nullify biometric and health data",targetPiiCategories:["PHI"],requiredMethod:"nullify"}]}buildHIPAARules(){return[{id:"hipaa-01",framework:"hipaa",category:"safe_harbor",description:"Anonymize patient identifiers (name, address, phone)",targetPiiCategories:["PII","PHI"],requiredMethod:"fake",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"},{id:"hipaa-02",framework:"hipaa",category:"safe_harbor_dates",description:"Generalize dates to year only",targetPiiCategories:["SENSITIVE"],requiredMethod:"age_band",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"},{id:"hipaa-03",framework:"hipaa",category:"safe_harbor_ids",description:"Hash medical record numbers and SSNs",targetPiiCategories:["PHI"],requiredMethod:"hash",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"}]}buildPCIDSSRules(){return[{id:"pci-01",framework:"pci_dss",category:"card_data",description:"Mask PAN to show only last 4 digits",targetPiiCategories:["PCI"],requiredMethod:"mask",articleReference:"PCI-DSS Requirement 3.3"},{id:"pci-02",framework:"pci_dss",category:"auth_data",description:"Nullify CVV, expiration, and magnetic strip data",targetPiiCategories:["PCI"],requiredMethod:"nullify",articleReference:"PCI-DSS Requirement 3.2"},{id:"pci-03",framework:"pci_dss",category:"cardholder",description:"Anonymize cardholder personal data",targetPiiCategories:["PII"],requiredMethod:"fake",articleReference:"PCI-DSS Requirement 3.4"}]}};var Ve=class{avgSecondsPerApiCall;batchSize;constructor(e){this.avgSecondsPerApiCall=e?.avgSecondsPerApiCall??.5,this.batchSize=e?.batchSize??200}getBatchSize(){return this.batchSize}generate(e,t,n){let s=this.buildWaves(e),o=e.stats.totalRecords,r=e.stats.totalEstimatedApiCalls,i=this.estimateDuration(s,e);return{waves:s,totalRecords:o,estimatedDurationSec:i,estimatedApiCalls:r,complianceFramework:t,anonymizationSummary:n,cycleResolutions:e.cycles}}buildWaves(e){if(e.nodes.length===0)return[];let t=[...e.nodes].sort((i,a)=>i.insertOrder-a.insertOrder),n=new Map;for(let i of t){let a=n.get(i.level);a?a.push(i.objectApiName):n.set(i.level,[i.objectApiName])}let s=[...n.keys()].sort((i,a)=>i-a),o=new Map;for(let i=0;i<s.length;i++){let a=s[i],c=n.get(a);if(c)for(let d of c)o.set(d,i)}let r=[];for(let i=0;i<s.length;i++){let a=s[i],c=n.get(a)??[],d=new Set;for(let p of c)for(let l of e.edges)if(l.to===p){let g=o.get(l.from);g!==void 0&&g<i&&d.add(g)}let m=[...d].sort((p,l)=>p-l);r.push({order:i,objects:c,dependsOn:m})}return r}estimateDuration(e,t){let n=new Map;for(let r of t.nodes)n.set(r.objectApiName,r.estimatedApiCalls);let s=new Map;t.cycles.forEach((r,i)=>{for(let a of r.objects)s.set(a,i)});let o=0;for(let r of e){let i=new Map;for(let a of r.objects){let c=s.get(a),d=c===void 0?`object:${a}`:`cycle:${c}`;i.set(d,(i.get(d)??0)+(n.get(a)??0))}o+=Math.max(0,...i.values())*this.avgSecondsPerApiCall}return o}};var Fe=class{idMaps=new Map;registerMappings(e,t){let n=this.idMaps.get(e);n||(n=new Map,this.idMaps.set(e,n));for(let[s,o]of t)n.set(s,o)}remapRecords(e,t,n){let s=t.filter(c=>c.to===n),o=0,r=0,i=0,a=[];for(let[c,d]of e.entries()){let m=new Set,p=new Map;for(let l of s){let g=d[l.fieldApiName];if(g==null||g===""){i++;continue}if(typeof g!="string"){i++;continue}let f=this.idMaps.get(l.from)?.get(g);if(f!==void 0)d[l.fieldApiName]=f,m.add(l.fieldApiName),o++;else{let R=p.get(l.fieldApiName);R?R.parents.push(l.from):p.set(l.fieldApiName,{sourceId:g,parents:[l.from]}),r++}}for(let[l,{sourceId:g,parents:y}]of p)m.has(l)||(d[l]=null,a.push({index:c,fieldApiName:l,sourceId:g,parents:y}))}return{remapped:o,missing:r,skipped:i,unresolved:a}}getTargetId(e,t){return this.idMaps.get(e)?.get(t)}hasObject(e){return this.idMaps.has(e)}getMappingCount(e){return this.idMaps.get(e)?.size??0}get totalMappings(){let e=0;for(let t of this.idMaps.values())e+=t.size;return e}clear(){this.idMaps.clear()}};var Js=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function _s(u,e,t){let n=Xt(u);if(e!==void 0&&!Js.test(e))throw new Error(`Not a record id to read after: "${e}".`);let s=e===void 0?"":` WHERE Id > '${e}'`;return`SELECT FIELDS(ALL) FROM ${n}${s} ORDER BY Id LIMIT ${Math.trunc(t)}`}var Zs={statusCode:ze,message:"No result returned for the record",fields:[]},er={statusCode:ze,message:"Refused without a reason",fields:[]},js="PARENT_REFUSED",Ls="PARENT_NOT_WRITTEN",zt="CUT_WITH_PARENT",$s={skipped:u=>`${u} was skipped in this run`,failed:u=>`the run's write of ${u} failed`},tr="PERSON_ACCOUNT_NOT_WRITTEN",nr="PERSON_CONTACT_NOT_LOOKED_UP",or=`SELECT Id FROM RecordType WHERE SobjectType = '${le}' AND IsPersonType = true`;function ne(u){return u.slice(0,15)}var we=class{byReason=new Map;add(e){let t=new Set;for(let n of e){let s=`${n.statusCode}\0${n.fields.join(",")}`;if(t.has(s))continue;t.add(s);let o=this.byReason.get(s);this.byReason.set(s,o?{...o,count:o.count+1}:{statusCode:n.statusCode,fields:[...n.fields],count:1,message:n.message})}}addCounted(e){let t=`${e.statusCode}\0${e.fields.join(",")}`,n=this.byReason.get(t);this.byReason.set(t,n?{...n,count:n.count+e.count}:e)}list(){return[...this.byReason.values()].sort((e,t)=>t.count-e.count)}};function Ns(u,e){let[t,...n]=u.errors,[s,...o]=u.errorDetails??[];return{...u,...t===void 0?{}:{errors:[kt(t,e),...n]},...s===void 0?{}:{errorDetails:[{...s,message:kt(s.message,e)},...o]}}}function Ds(){return{written:0,linked:0,failed:0,errors:[],refusals:new we,apiCallsUsed:0,defaulted:new Map,cutSinceFit:0,heldForRecordType:new Map,sentAgainForALock:{rows:0,written:0,stillLocked:0}}}function sr(u){return{statusCode:Un,fields:["RecordTypeId"],count:u.recordCount,message:Xn(u)}}function rr(u,e){return{objectApiName:u,rows:e.rows,why:{...e.why},...e.predicted?{predicted:e.predicted}:{},...e.readBack?{readBack:e.readBack}:{}}}function Bs(u){let e=0;for(let[t,n]of u)It(t)&&(e+=n);return e}function ir(u){let e=new Map;for(let t of u.holds)e.set(t.objectApiName,[...e.get(t.objectApiName)??[],t]);return{holds:e,kept:new Map([...u.kept].map(([t,n])=>[t,new Set(n.map(ne))])),stayedOut:new Map}}var Ie=class extends zo{deps;batchSize;paused=!1;pausePromise=null;pauseResolve=null;skippedObjects=new Set;signal;contactPoints;creatableByObject=new Map;currencies;currencyChanges=new Gn;pricesSettled=new Map;currencyChangesByWrittenId=new Map;keyPrefixByObject=new Map;lifecycleByObject=new Map;standardPricebook;deferredStatuses=[];lookupsByObject=new Map;recordTypeMappings;targetRecordTypes=[];planned=new Set;parentIds=new Map;owedLookups=[];unmappedRecordTypes=new Set;leftToThePlatform=new fn;taskOfEmail=new Map;emailsAfterTheirTask=[];taskTurnOver=!1;emailsHeldAndNotSent=0;leftByStop=new Map;lookupsLeftEmpty=new Map;refusedRecords=new Map;notWritten=new Map;reached=new Set;personTypes;personContactsLinked=0;recordTypesGiven=new Map;recordTypesUnderTheLease=new Map;givenRules=new Map;lease;fit;async creatableFieldsOf(e){if(!this.deps.describeCreateableFields)return null;let t=this.creatableByObject.get(e);if(t!==void 0)return t;try{let n=await this.deps.describeCreateableFields(e),s=n.size>0?n:null;return this.creatableByObject.set(e,s),s}catch{return this.creatableByObject.set(e,null),null}}lookupsOf(e){let t=this.deps.describeLookups;if(!t)return Promise.resolve(null);let n=this.lookupsByObject.get(e);return n||(n=t(e).catch(()=>null),this.lookupsByObject.set(e,n)),n}keyPrefixOf(e){let t=this.deps.describeKeyPrefix;if(!t)return Promise.resolve(void 0);let n=this.keyPrefixByObject.get(e);return n||(n=t(e).catch(()=>{}),this.keyPrefixByObject.set(e,n)),n}constructor(e){super(),this.deps=e,this.batchSize=e.batchSize??200}async recordTypesHeldBack(e){let{describeRecordTypes:t,countRecordTypes:n}=this.deps;if(!t||!n)return[];let s=await this.creatableFieldsOf(e);if(s&&!s.has("RecordTypeId"))return[];try{let o=await t(e);if(!o.some(i=>!i.available&&!i.master))return[];let r=this.inTargetRecordTypes(await n(e));return Hn(e,r,gt(o,this.targetRecordTypes))}catch{return[]}}inTargetRecordTypes(e){let t=new Map;for(let[n,s]of e){if(n===null)continue;let o=this.targetRecordTypeOf(n);t.set(o,(t.get(o)??0)+s)}return t}targetRecordTypeOf(e){return this.recordTypeMappings?.find(t=>t.sourceId===e)?.targetId??e}async recordTypesGivenOf(e,t,n=new Map,s=[]){await this.mapRecordTypes(e);let o=new Map;for(let r of new Set(e.waves.flatMap(i=>i.objects))){let i=t.get(r)??0;if(i===0)continue;let a=await this.givenRuleOf(r);if(!a)continue;let c=await this.creatableFieldsOf(r),d,m="masterInSource";if(c&&!c.has("RecordTypeId"))d=i,m="notRead";else{let p=await this.onMasterInSource(r,n.get(r));if(p===void 0)continue;d=s.find(g=>g.objectApiName===r)?Math.min(p,i):p}d!==0&&o.set(r,{objectApiName:r,rows:d,why:{[m]:d},...a.predicted?{predicted:a.predicted}:{}})}return o}async onMasterInSource(e,t){try{if(t===void 0){let o=this.deps.countRecordTypes;return o?Bs(await o(e)):void 0}let n=this.deps.querySource;if(!n)return;let s=0;for(let o=0;o<t.length;o+=Ue){let r=await n(jt(e,t.slice(o,o+Ue)));s+=Bs(qe(r))}return s}catch{return}}givenRuleOf(e){let t=this.givenRules.get(e);return t||(t=(async()=>{let n=this.recordTypesUnderTheLease.get(e)??await this.deps.describeRecordTypes?.(e).catch(()=>{});if(!n?.some(r=>!r.master))return;let s=gt(n,this.targetRecordTypes),o=Jo(Qo(s));return{types:s,...o?{predicted:o}:{}}})(),this.givenRules.set(e,t)),t}async readAgainUnderTheLease(e,t){let n=this.deps.describeRecordTypesAgain;if(!n||!this.lease||this.lease.assigned===0)return;let s=[...new Set(e.waves.flatMap(o=>o.objects))].filter(o=>(t.get(o)??0)>0);await Promise.all(s.map(async o=>{if((await this.deps.describeRecordTypes?.(o).catch(()=>{}))?.some(i=>!i.master))try{this.recordTypesUnderTheLease.set(o,await n(o))}catch{}}))}countCreatedWithoutRecordType(e,t,n,s){let o=this.recordTypesGiven.get(e);o||(o={...t,rows:0,why:{},ids:[]},this.recordTypesGiven.set(e,o)),o.rows++,o.why[n]=(o.why[n]??0)+1,s&&o.ids.length<Zo&&o.ids.push(s)}async afterTheWrites(e){await this.giveTheLeaseBack(),await this.readBackRecordTypes();for(let[t,n]of this.recordTypesGiven){let s=e[t];s&&(e[t]={...s,recordTypeGiven:rr(t,n)})}}async giveTheLeaseBack(){let e=this.lease;if(e){this.lease=void 0;try{await e.giveBack()}catch(t){ue.warn(`[autopilot] the mute's lease was not given back as the writes ended: ${ee(t)}`)}}}async readBackRecordTypes(){let e=this.deps.queryTarget;e&&await Promise.all([...this.recordTypesGiven].map(async([t,n])=>{if(n.ids.length!==0)try{let s=await e(jt(t,n.ids));n.readBack=es(s,n.types)}catch(s){n.readBack={read:0,types:[],unread:ee(s)}}}))}holdOnClosedRecordTypes(e,t,n){let s=n.closedRecordTypes;if(!s)return t;let o=[];for(let r of t){let i=r.RecordTypeId,a=e===me&&Se(r),c=typeof i=="string"&&i.length>=15&&!a?s.get(ne(this.targetRecordTypeOf(i))):void 0;if(!c){o.push(r);continue}n.failed++;let d=n.heldForRecordType.get(c.recordTypeId);n.heldForRecordType.set(c.recordTypeId,{...c,recordCount:(d?.recordCount??0)+1});let m=r.Id;typeof m=="string"&&m!==""&&this.refusedRecords.set(ne(m),e)}return o}async mapRecordTypes(e){let{querySource:t,queryTarget:n}=this.deps;if(!t||!n)return;let s=[...new Set(e.waves.flatMap(r=>r.objects))];if(s.length===0)return;let o=`${Ho} AND SobjectType IN (${s.map(r=>`'${Be(r)}'`).join(", ")})`;try{let[r,i]=await Promise.all([t(o),n(o)]),a=Ft(r);this.targetRecordTypes=Ft(i),this.recordTypeMappings=new xt().buildMapping(a,this.targetRecordTypes);for(let c of Yo(a,this.targetRecordTypes))ue.warn(`[autopilot] ${Vo(c)}`)}catch(r){ue.warn("Autopilot could not match the record types of the two orgs",{error:ee(r)})}}async matchStandardPricebooks(e){let{querySource:t,queryTarget:n}=this.deps;if(!t||!n)return;let s=new Set(e.waves.flatMap(o=>o.objects));if(!(!s.has(be)&&!s.has(rt)))try{let[o,r]=await Promise.all([t(it),n(it)]),i=o[0]?.Id,a=r[0]?.Id;if(typeof i!="string"||typeof a!="string")return;this.standardPricebook={source:i,target:a},this.deps.remapper.registerMappings(be,[[i,a]])}catch(o){ue.warn("Autopilot could not match the standard price books",{error:ee(o)})}}async execute(e,t,n,s,o,r=new Map,i={}){if(!this.deps.queryByIds&&[...r.values()].some(f=>f.length>0))throw new Error("This plan reads the parents its objects reference by id, and the run has no read by id.");this.parentIds=r,this.contactPoints=i.keepContactPoints===!0?void 0:new Wo,this.lease=i.lease,this.fit=i.fit?ir(i.fit):void 0;let a=Date.now();this.signal=o;let c=()=>this.pauseResolve?.();o?.addEventListener("abort",c,{once:!0});let d={},m={},p={totalSuccess:0,totalFailure:0,totalSkipped:0,totalLinked:0,elapsedMs:0,completedObjects:[],failedObjects:[],skippedObjects:[],nodeErrors:d,objectOutcomes:m},l=[];this.emit("execution-started",this.makeEvent({type:"execution-started",timestamp:""}));let g=async f=>{await y(f),f===_e&&await this.writeEmailsAfterTheirTask(t,p)},y=async f=>{if(this.skippedObjects.has(f)){let w=s.get(f)??0;p.skippedObjects.push(f),p.totalSkipped+=w,this.notWritten.set(f,"skipped");return}this.reached.add(f);let R=s.get(f)??0;if(await this.checkPause()){l.push(f),m[f]={written:0,linked:0,failed:0,refusals:[],...R>0?{notSent:R}:{}};return}try{let w=await this.executeObject(f,t,n,R);p.totalSuccess+=w.success,p.totalFailure+=w.failure,p.totalLinked=(p.totalLinked??0)+w.linked,w.cutSinceFit>0&&(p.cutSinceFit=(p.cutSinceFit??0)+w.cutSinceFit);let x=this.leftToThePlatform.counts(f);if(m[f]={written:w.success,linked:w.linked,failed:w.failure,refusals:w.refusals,...w.leftToDefault.length>0?{leftToDefault:w.leftToDefault}:{},...x.length>0?{leftToThePlatform:x}:{},...w.notSent!==void 0&&w.notSent>0?{notSent:w.notSent}:{},...this.currenciesReplacedOf(f),...this.pricesSettledOf(f),...f===me&&this.personContactsLinked>0?{withTheirPersonAccount:this.personContactsLinked}:{},...w.cutSinceFit>0?{cutSinceFit:w.cutSinceFit}:{},...w.threw!==void 0?{threw:w.threw}:{},...w.sentAgainForALock.rows>0?{sentAgainForALock:w.sentAgainForALock}:{}},w.notSent!==void 0){l.push(f);return}let{threw:$}=w;if($!==void 0||w.errors.length>0&&w.success+w.linked===0){p.failedObjects.push(f),$!==void 0&&this.notWritten.set(f,"failed");let E=$!==void 0?[$,...w.errors]:w.errors;d[f]=E[0],this.emit("node-failed",this.makeEvent({type:"node-failed",timestamp:"",objectApiName:f,errors:E,partialSuccessCount:w.success,failureCount:w.failure,linkedCount:w.linked,refusals:w.refusals}))}else p.completedObjects.push(f),this.emit("node-completed",this.makeEvent({type:"node-completed",timestamp:"",objectApiName:f,successCount:w.success,failureCount:w.failure,linkedCount:w.linked,refusals:w.refusals,elapsedMs:w.elapsedMs,apiCallsUsed:w.apiCallsUsed}))}catch(w){p.failedObjects.push(f),this.notWritten.set(f,"failed");let x=ee(w);d[f]=x,this.emit("node-failed",this.makeEvent({type:"node-failed",timestamp:"",objectApiName:f,errors:[x],partialSuccessCount:0,failureCount:0,linkedCount:0,refusals:[]}))}};try{await this.matchStandardPricebooks(e),await this.mapRecordTypes(e),await this.readAgainUnderTheLease(e,s),this.planned=new Set(e.waves.flatMap(w=>w.objects));let f={};for(let w of e.waves){if(await this.writeWave(w.objects,t,g),this.stopped())break;await this.fillOwedLookups(f),this.emit("wave-completed",this.makeEvent({type:"wave-completed",timestamp:""}))}if(this.stopped()){let w=new Set([...p.completedObjects,...p.failedObjects,...p.skippedObjects,...l]);for(let x of e.waves.flatMap($=>$.objects)){if(w.has(x))continue;let $=s.get(x)??0;l.push(x),m[x]={written:0,linked:0,failed:0,refusals:[],...$>0?{notSent:$}:{}}}return p.stopped=!0,p.stoppedObjects=l,this.countEmailsTheStopHeld(p,l,m),this.countWhatTheStopLeft(l,m),await this.sayLookupsLeftOwed(t,f),Object.keys(f).length>0&&(p.lookups=f),await this.afterTheWrites(m),this.reportContactPoints(p),p.elapsedMs=Date.now()-a,p}this.emailsAfterTheirTask.length>0&&(await this.writeEmailsAfterTheirTask(t,p),await this.fillOwedLookups(f)),await this.sayLookupsLeftOwed(t,f);let R=await this.applyDeferredStatuses();return Object.keys(R).length>0&&(p.statuses=R),Object.keys(f).length>0&&(p.lookups=f),await this.afterTheWrites(m),this.stopped()&&(p.stopped=!0,p.stoppedObjects=l,this.countEmailsTheStopHeld(p,l,m),this.countWhatTheStopLeft(l,m)),this.reportContactPoints(p),p.elapsedMs=Date.now()-a,this.emit("execution-completed",this.makeEvent({type:"execution-completed",timestamp:""})),p}catch(f){throw p.elapsedMs=Date.now()-a,p.fatalError=ee(f),ue.error("Autopilot execution crashed",{error:p.fatalError}),this.emit("execution-failed",this.makeEvent({type:"execution-failed",timestamp:"",error:p.fatalError})),f}finally{o?.removeEventListener("abort",c),await this.giveTheLeaseBack()}}async writeWave(e,t,n){let{within:s,deps:o,groups:r}=De(e,t),i=new Map;r.forEach((m,p)=>m.forEach(l=>i.set(l,p)));let a=[];for(let[m,p]of r.entries()){let l=new Set;for(let g of p)for(let y of o.get(g)??[]){let f=i.get(y);f!==void 0&&f!==m&&l.add(a[f])}a.push((async()=>{await Promise.all(l);let g=p.length>1?cn(p,await this.setAtInsert(p,s)):p;for(let y of g)await n(y)})())}let d=(await Promise.allSettled(a)).find(m=>m.status==="rejected");if(d)throw d.reason}async setAtInsert(e,t){let n=new Set(e),s=new Map;for(let o of t)!n.has(o.to)||!n.has(o.from)||s.has(o.to)||s.set(o.to,await this.lookupsOf(o.to));return dn(e,t,o=>s.get(o))}async fillOwedLookups(e){let t=this.owedLookups.splice(0,this.owedLookups.length),{update:n}=this.deps;if(!n||t.length===0)return;let s=new Uo;for(let o of t){let r=o.parents.map(i=>this.deps.remapper.getTargetId(i,o.sourceId)).find(i=>i!==void 0);if(!r){this.owedLookups.push(o);continue}s.add({objectApiName:o.objectApiName,recordId:o.recordId,fieldName:o.fieldApiName,value:r})}for(let[o,r]of s.updates()){let i=e[o],a=i?.filled??0,c=new we;for(let d of i?.refusals??[])c.addCounted(d);for(let d=0;d<r.length;d+=this.batchSize){if(await this.checkPause()){this.noteLeftByStop(o,"lookups",r.slice(d).map(l=>String(l.Id)));break}let m=r.slice(d,d+this.batchSize),p=await this.updateSendingLocksAgain(n,o,m,"lookup update(s)");m.forEach((l,g)=>{let y=p[g];if(y?.success){a++;return}let f=Object.keys(l).filter(R=>R!=="Id");c.add(qt(y).map(R=>({...R,fields:f}))),this.noteLookupLeftEmpty(o,String(l.Id))})}e[o]=this.lookupOutcome(o,a,c)}}noteLookupLeftEmpty(e,t){let n=this.lookupsLeftEmpty.get(e);n||(n=new Set,this.lookupsLeftEmpty.set(e,n)),n.add(t)}lookupOutcome(e,t,n){let s=this.lookupsLeftEmpty.get(e)?.size??0;return{filled:t,refusals:n.list(),...s>0?{leftEmpty:s}:{}}}async sayLookupsLeftOwed(e,t){let n=new Map;for(let s of this.owedLookups.splice(0,this.owedLookups.length)){let o=await this.whyLeftOwed(s,e);if(!o)continue;let r=n.get(s.objectApiName);if(!r){r=new we;for(let i of t[s.objectApiName]?.refusals??[])r.addCounted(i);n.set(s.objectApiName,r)}r.add([{...o,fields:[s.fieldApiName]}]),this.noteLookupLeftEmpty(s.objectApiName,s.recordId)}for(let[s,o]of n){let r=t[s]?.filled??0;t[s]=this.lookupOutcome(s,r,o)}}async whyLeftOwed(e,t){let{fieldApiName:n,sourceId:s}=e,o=this.refusedRecords.get(ne(s)),r=e.parents.find(c=>c===o);if(r)return{statusCode:js,message:`the ${r} record its ${n} names was refused in this run, and this record, written before it, keeps its ${n} empty.`};let i=this.fit?.stayedOut.get(ne(s)),a=e.parents.find(c=>c===i);if(a)return{statusCode:zt,message:`the ${a} record its ${n} names stayed out with a record the fit cut, and this record, written before it, keeps its ${n} empty.`};for(let c of e.parents){let d=this.notWrittenOf(c);if(d===void 0)continue;let m=t.find(p=>p.from===c&&p.to===e.objectApiName&&p.fieldApiName===n);if(!(m&&!await this.namesARecordOf(e.objectApiName,m,s,e.parents.length)))return{statusCode:Ls,message:`the ${c} record its ${n} names was not written: ${$s[d](c)}, and this record, written before it, keeps its ${n} empty.`}}}async executeObject(e,t,n,s){let o=Date.now(),r=Ds(),i=()=>{let a=[...r.heldForRecordType.values()];return{success:r.written,linked:r.linked,failure:r.failed,errors:[...a.map(Yn),...r.errors],refusals:[...r.refusals.list(),...a.map(sr)].sort((c,d)=>d.count-c.count),apiCallsUsed:r.apiCallsUsed,elapsedMs:Date.now()-o,leftToDefault:[...r.defaulted].map(([c,d])=>({field:c,count:d})),...r.notSent!==void 0?{notSent:r.notSent}:{},cutSinceFit:r.cutSinceFit,sentAgainForALock:r.sentAgainForALock}};try{return await this.writeEveryPage(e,t,n,s,r,i)}catch(a){return{...i(),threw:ee(a)}}}async writeEveryPage(e,t,n,s,o,r){let i=s>0?await this.recordTypesHeldBack(e):[];i.length>0&&(o.closedRecordTypes=new Map(i.map(p=>[ne(p.recordTypeId),p])));let a=p=>{let l=Math.min(p,s);this.emit("node-progress",this.makeEvent({type:"node-progress",timestamp:"",objectApiName:e,progress:s>0?Math.round(l/s*100):100,recordsProcessed:l,recordsTotal:s,apiCallsUsed:o.apiCallsUsed}))},c=0,d,m=this.standardPricebook;if(Ut(e)&&m){let p=[];for(;c<s;){if(await this.checkPause())return o.notSent=s,r();let{rows:$,advance:E,next:L,last:S}=await this.readPage(e,c,d,s-c);if(o.apiCallsUsed++,E===0)break;c+=E,d=L;let j=this.leaveToThePlatform(e,$,t);if(this.deps.anonymizer.anonymize(j,n,e),await this.neutralizeContactPoints(e,j),p.push(...j),S)break}let l=await this.pricesInOneCurrencyEach(p,m.source),{standard:g,custom:y}=at(l.rows,m.source),f=at(p.filter($=>l.standsFor.has(String($.Id))),m.source);l.said.length>0&&this.pricesSettled.set(e,os(l.said));let R=0,w=0,x=async $=>{for(let E=0;E<$.length;E+=this.batchSize){if(await this.checkPause())return o.notSent=p.length-R-w,!1;let L=$.slice(E,E+this.batchSize);await this.writeBatch(e,L,t,o),R+=L.length,a(R+w)}return!0};for(let[$,E]of[[g,f.standard],[y,f.custom]]){if(!await x($))return r();let L=this.linkWhatStoodIn(E,l.standsFor,o);if(w+=E.length-L.length,!await x(L))return r()}return r()}for(;c<s;){if(await this.checkPause()){o.notSent=s-c;break}let{rows:p,advance:l,next:g,last:y}=await this.readPage(e,c,d,s-c);if(o.apiCallsUsed++,l===0)break;d=g;let f=this.leaveToThePlatform(e,p,t);if(this.deps.anonymizer.anonymize(f,n,e),await this.neutralizeContactPoints(e,f),await this.writeBatch(e,f,t,o),c+=l,a(c),y)break}return r()}async neutralizeContactPoints(e,t){let{contactPoints:n}=this,s=this.deps.describeFields;if(!n||!s||t.length===0)return;let o=await s(e).catch(()=>{});if(!o)return;let r=n.forObject(e,o);if(r)for(let i of t)r(i)}reportContactPoints(e){this.contactPoints&&(e.contactPoints=this.contactPoints.report())}async readPage(e,t,n,s){let o=Math.max(0,Math.min(this.batchSize,s));if(o===0)return{rows:[],advance:0,next:n,last:!0};let r=this.parentIds.get(e);if(r&&this.deps.queryByIds){let c=r.slice(t,t+Math.min(o,Ue));return c.length===0?{rows:[],advance:0,next:n,last:!0}:{rows:await this.deps.queryByIds(e,c),advance:c.length,next:n,last:!1}}let i=(await this.deps.query(e,n,o)).slice(0,o),a=i.at(-1)?.Id;return{rows:i,advance:i.length,next:typeof a=="string"?a:n,last:i.length>0&&typeof a!="string"}}leaveToThePlatform(e,t,n){let s=new Set(n.filter(o=>o.to===e&&(o.required||Wt(o.to,o.fieldApiName))).map(o=>o.fieldApiName));return this.leftToThePlatform.keep(e,t,[...s])}async writeBatch(e,t,n,s){let o=[],r=t,i=this.standardPricebook;if(e===be&&i&&(r=t.filter(S=>S.Id!==i.source),s.linked+=t.length-r.length),r=this.holdOnClosedRecordTypes(e,r,s),r=await this.holdBehindRefusedParents(e,r,n,s),r=this.holdBehindCutParents(e,r,s),e===J&&(r=this.holdEmailsForTheirTask(r)),e===me&&(r=await this.linkPersonContacts(r,s,o)),r.length===0){this.register(e,o);return}let a=this.deps.remapper.remapRecords(r,n,e);await this.leaveToDefault(e,r,s);let c=await this.creatableFieldsOf(e),d=c?r.map(S=>{let j={};for(let P of Object.keys(S))(P==="Id"||P==="attributes"||c.has(P))&&(j[P]=S[P]);return j}):r;d=this.translateRecordTypes(e,d);let m=new Map;d.forEach((S,j)=>{if(S.RecordTypeId!==void 0)return;let P=r[j]?.RecordTypeId,A=!c||c.has("RecordTypeId");m.set(S,A&&It(P)?"masterInSource":"notRead")});for(let S of d)for(let j of Kt(e,S))delete S[j];let p=await this.replaceCurrencies(e,r,d,c);e===le&&await this.leaveOutForAccountKind(r,d);let l=new Map;d.forEach((S,j)=>{let P=pt(e,S);for(let A of P)delete S[A];P.length>0&&l.set(j,P)});let g=await this.lookupsOwed(e,r,a.unresolved.filter(S=>!l.get(S.index)?.includes(S.fieldApiName)),c),y=this.deps.queryTarget,f=y?S=>(s.apiCallsUsed++,y(S)):void 0;if(e===ln&&f){let S=await vn(f,d);for(let[j,P]of S){let A=d[j].Id;typeof A=="string"&&o.push([A,P])}s.linked+=S.size,d=d.filter((j,P)=>!S.has(P))}if(kn[e]!==void 0&&f){let S=await Rn(f,e,d);for(let[j,P]of S){let A=d[j].Id;typeof A=="string"&&o.push([A,P])}s.linked+=S.size,await this.giveFlagsBack(e,[...S].map(([j,P])=>[d[j],P]),s),d=d.filter((j,P)=>!S.has(P))}if(e===_e&&f){let S=await this.tasksWrittenWithTheirEmail(d,f);for(let[j,P]of S)o.push([j,P]);s.linked+=S.size,d=d.filter(j=>!S.has(String(j.Id)))}if(d.length===0){this.register(e,o);return}let R=await this.startAsDrafts(e,d),w=m.size>0?await this.givenRuleOf(e):void 0,x=await this.sendFormsAgain(e,d,await this.insertSendingLocksAgain(e,d,s),s),$=await this.keyPrefixOf(e),E=pn[e],L=[];if(d.forEach((S,j)=>{let P=typeof S.Id=="string"?S.Id:void 0,A=x[j];if(!A){this.refuse(e,P,s,void 0);return}if(A.success){s.written++;let X=w?m.get(S):void 0;w&&X&&this.countCreatedWithoutRecordType(e,w,X,A.id);let Z=p.get(S);this.currencyChanges.add(e,Z),Z&&A.id&&this.currencyChangesByWrittenId.set(A.id,Z),P&&A.id&&o.push([P,A.id]);let N=R.get(j);N&&A.id&&this.deferredStatuses.push({objectApiName:e,id:A.id,status:N});let U=P?g.get(P):void 0;for(let V of A.id?U??[]:[])this.owedLookups.push({objectApiName:e,recordId:A.id,fieldApiName:V.fieldApiName,sourceId:V.sourceId,parents:V.parents});return}let oe=Vn(A,$);if(oe.kind==="linked"){s.linked++,P&&o.push([P,oe.id]);return}if(oe.kind==="unidentified"&&E&&f){L.push({payload:S,sourceId:P,outcome:A});return}this.refuse(e,P,s,A)}),E&&f&&L.length>0){let S=await On(f,e,E,L.map(j=>j.payload));L.forEach((j,P)=>{let A=S[P];if(A&&j.sourceId){s.linked++,o.push([j.sourceId,A]);return}this.refuse(e,j.sourceId,s,j.outcome)})}this.register(e,o)}async insertSendingLocksAgain(e,t,n){let s=async i=>(n.apiCallsUsed++,this.deps.insert(e,i)),o=await s(t),r=await Rt({outcomes:o.slice(0,t.length),locked:i=>!i.success&&bt(i.errors,i.errorDetails),written:i=>i.success,send:i=>Qe((a,c)=>s(c),e,i.map(a=>t[a])),note:Ns,wait:async i=>{await this.wait(i),await this.checkPause()},stopped:()=>this.stopped()});return r.refused===0?o:(n.sentAgainForALock={rows:n.sentAgainForALock.rows+r.sentAgain,written:n.sentAgainForALock.written+r.written,stillLocked:n.sentAgainForALock.stillLocked+r.stillLocked},ue.info(`[autopilot] ${e}: ${Oe("record(s)",r)??""}`),[...r.outcomes,...o.slice(t.length)])}async sendFormsAgain(e,t,n,s){let o=this.contactPoints,r=this.deps.describeFields;if(!o||!r||n.every(p=>p?.success!==!1))return n;let i=await r(e).catch(()=>{});if(!i)return n;let a=Go(i),c=[...n],d=t.map(()=>new Map),m=t.map(()=>[]);for(let p=0;p<=io&&!this.stopped();p++){let l=[];if(c.forEach((y,f)=>{let R=t[f];if(!y||y.success||!R)return;let w=ro(y.errorDetails,R,void 0);if(!w||w.some($=>$.refusedBy!=="validation-rule"||!a($.field)))return;let x=ao(w,R,a,d[f]);if(!(Object.keys(x.forms).length===0&&x.leftOut.length===0)){for(let{field:$}of x.leftOut)delete R[$];Object.assign(R,x.forms),m[f].push(...x.leftOut),l.push(f)}}),l.length===0)break;s.apiCallsUsed++;let g=await Qe((y,f)=>this.deps.insert(e,f),e,l.map(y=>t[y]));l.forEach((y,f)=>{let R=g[f];R&&(c[y]=R)})}return c.forEach((p,l)=>{!p?.success||d[l].size===0&&m[l].length===0||o.countForms(e,co(d[l],m[l],a))}),c}async updateSendingLocksAgain(e,t,n,s){let o=await Qe(e,t,n),r=await Rt({outcomes:o.slice(0,n.length),locked:i=>!i.success&&bt(i.errors,i.errorDetails),written:i=>i.success,send:i=>Qe(e,t,i.map(a=>n[a])),note:Ns,wait:async i=>{await this.wait(i),await this.checkPause()},stopped:()=>this.stopped()});return r.refused===0?o:(ue.info(`[autopilot] ${t}: ${Oe(s,r)??""}`),[...r.outcomes,...o.slice(n.length)])}async giveFlagsBack(e,t,n){let s=this.deps.update;if(!s||t.length===0||!An[e])return;let o=await this.deps.describeFieldsFixedAtInsert?.(e).catch(()=>{}),r=await Sn(e,t,i=>!o?.has(i),async i=>(n.apiCallsUsed++,s(e,i)),()=>this.stopped());r&&ue.warn("Autopilot linked relations without a flag or an answer their rows carried",{objectApiName:e,note:r})}holdEmailsForTheirTask(e){for(let n of e){let s=n.ActivityId;typeof n.Id=="string"&&typeof s=="string"&&s!==""&&this.taskOfEmail.set(n.Id,s)}if(this.taskTurnOver||!this.planned.has(_e))return e;let t=[];for(let n of e)gn(n)?this.emailsAfterTheirTask.push(n):t.push(n);return t}async tasksWrittenWithTheirEmail(e,t){let n=new Map;for(let[i,a]of this.taskOfEmail){let c=this.deps.remapper.getTargetId(J,i);c&&n.set(a,c)}let s=e.map(i=>String(i.Id)).filter(i=>n.has(i));if(s.length===0)return new Map;let o;try{o=await yn(t,[...new Set(s.map(i=>n.get(i)??""))])}catch(i){return ue.warn("Autopilot could not look up the tasks written with its emails",{error:ee(i)}),new Map}let r=new Map;for(let i of s){let a=o.get(n.get(i)??"");a&&r.set(i,a)}return r}async writeEmailsAfterTheirTask(e,t){this.taskTurnOver=!0;let n=this.emailsAfterTheirTask.splice(0,this.emailsAfterTheirTask.length);if(n.length===0)return;let s=Ds();for(let d=0;d<n.length;d+=this.batchSize){if(await this.checkPause()){this.emailsHeldAndNotSent+=n.length-d;break}await this.writeBatch(J,n.slice(d,d+this.batchSize),e,s)}t.totalSuccess+=s.written,t.totalFailure+=s.failed,t.totalLinked=(t.totalLinked??0)+s.linked;let o=t.objectOutcomes??{};t.objectOutcomes=o;let r=o[J],i=new we;for(let d of[...r?.refusals??[],...s.refusals.list()])i.addCounted(d);let a=new Map((r?.leftToDefault??[]).map(d=>[d.field,d.count]));for(let[d,m]of s.defaulted)a.set(d,(a.get(d)??0)+m);let c={...r,written:(r?.written??0)+s.written,linked:(r?.linked??0)+s.linked,failed:(r?.failed??0)+s.failed,refusals:i.list(),...a.size>0?{leftToDefault:[...a].map(([d,m])=>({field:d,count:m}))}:{}};o[J]=c,c.written+c.linked>0&&t.failedObjects.includes(J)&&(t.failedObjects.splice(t.failedObjects.indexOf(J),1),delete t.nodeErrors?.[J],t.completedObjects.push(J)),this.emit("node-completed",this.makeEvent({type:"node-completed",timestamp:"",objectApiName:J,successCount:c.written,failureCount:c.failed,linkedCount:c.linked,refusals:c.refusals,elapsedMs:0,apiCallsUsed:s.apiCallsUsed}))}async leaveToDefault(e,t,n){let s=await this.lookupsOf(e);if(!s)return;let o=Pn(s.filter(i=>i.name!=="RecordTypeId"),i=>!this.planned.has(i));if(o.size===0)return;let r=await this.creatableFieldsOf(e);for(let i of t)for(let a of o){let c=i[a];c!=null&&c!==""&&(!r||r.has(a))&&n.defaulted.set(a,(n.defaulted.get(a)??0)+1),delete i[a]}}async replaceCurrencies(e,t,n,s){let o=new Map,{querySource:r,queryTarget:i}=this.deps;if(!r||!i)return o;let a=!s||s.has(ye);if(!a&&this.currencyChangesByWrittenId.size===0)return o;let c=l=>typeof l?.[ye]=="string"&&l[ye]!=="";if(!(a?n.some(c):t.some(c)))return o;this.currencies??=ht(r,i,{source:this.deps.toolingSource,target:this.deps.toolingTarget});let d=await this.currencies;if(!d)return o;let m=await this.deps.describeCurrencyFields?.(e).catch(()=>{})??new Map,p=a?[]:(await this.lookupsOf(e)??[]).map(l=>l.name);return n.forEach((l,g)=>{let y=t[g],f=y?.[ye],R=a?_n(l,{read:f,currencyFields:m,ratesOn:Nn(e,y)},d):zn(l,{read:f,parent:y?qn(e,y,p,w=>this.currencyChangesByWrittenId.get(w)):void 0,currencyFields:m},d);R&&o.set(l,R)}),o}async pricesInOneCurrencyEach(e,t){let n={rows:e,standsFor:new Map,said:[]},{querySource:s,queryTarget:o}=this.deps;if(!s||!o)return n;let r=d=>typeof d[ye]=="string"&&d[ye]!=="";if(!e.some(r))return n;this.currencies??=ht(s,o,{source:this.deps.toolingSource,target:this.deps.toolingTarget});let i=await this.currencies;if(!i)return n;let{target:a}=i,c=ns({prices:e,standardBookId:t,sellingModels:e.some(d=>typeof d[Ht]=="string"),writtenIn:d=>a.active.has(d)?d:Bn(void 0,a)?.to,active:a.active},[]);return{rows:c.rows,standsFor:c.standsFor,said:c.said}}linkWhatStoodIn(e,t,n){let s=rt,o=[],r=[];for(let i of e){let a=String(i.Id),c=t.get(a),d=c===void 0?void 0:this.deps.remapper.getTargetId(s,c);if(d===void 0){r.push(i);continue}o.push([a,d]),n.linked++}return this.register(s,o),r}pricesSettledOf(e){let t=this.pricesSettled.get(e)??[];return t.length>0?{pricesSettled:t}:{}}currenciesReplacedOf(e){let t=this.currencyChanges.list().filter(n=>n.objectApiName===e);return t.length>0?{currenciesReplaced:t}:{}}translateRecordTypes(e,t){let n=this.recordTypeMappings;return!n||!t.some(s=>typeof s.RecordTypeId=="string")?t.map(Ko):new xt().apply(t,n,s=>{this.unmappedRecordTypes.has(s)||(this.unmappedRecordTypes.add(s),Xo(e,s,"autopilot"))})}async lookupsOwed(e,t,n,s){let o=new Map;if(!this.deps.update||n.length===0)return o;let r=await this.lookupsOf(e);for(let i of n){if(s&&!s.has(i.fieldApiName))continue;let a=r?.find(d=>d.name===i.fieldApiName);if(a&&!a.updateable)continue;let c=t[i.index]?.Id;typeof c=="string"&&o.set(c,[...o.get(c)??[],i])}return o}refuse(e,t,n,s){n.failed++;let o=qt(s);n.errors.push(s?.errors[0]??ar(o[0])),n.refusals.add(o),t&&this.refusedRecords.set(ne(t),e)}async holdBehindRefusedParents(e,t,n,s){if(this.refusedRecords.size===0&&this.notWritten.size===0&&this.skippedObjects.size===0)return t;let o=n.filter(a=>a.to===e);if(o.length===0)return t;let r=new Map;for(let a of o)r.set(a.fieldApiName,(r.get(a.fieldApiName)??0)+1);let i=[];for(let a of t){let c=pt(e,a),d;for(let y of o){let f=a[y.fieldApiName];if(typeof f!="string"||f===""||c.includes(y.fieldApiName)||this.deps.remapper.getTargetId(y.from,f)!==void 0)continue;let R=this.refusedRecords.get(ne(f))===y.from,w=this.notWrittenOf(y.from);if(!R&&w===void 0)continue;let x=r.get(y.fieldApiName)??0;if(!R&&!await this.namesARecordOf(e,y,f,x))continue;let{from:$,fieldApiName:E}=y;d=R||w===void 0?{edge:y,statusCode:js,message:`the ${$} record its ${E} names was refused in this run, and written without it this record would stand without its ${$}.`}:{edge:y,statusCode:Ls,message:`the ${$} record its ${E} names was not written: ${$s[w]($)}, and written without it this record would stand without its ${$}.`};break}if(!d){i.push(a);continue}let{statusCode:m,message:p,edge:l}=d;s.failed++,s.errors.push(`${m}: ${p}`),s.refusals.add([{statusCode:m,message:p,fields:[l.fieldApiName]}]);let g=a.Id;typeof g=="string"&&g!==""&&this.refusedRecords.set(ne(g),e)}return i}holdBehindCutParents(e,t,n){let s=this.fit,o=s?.holds.get(e);return!s||!o?t:t.filter(r=>{if(!o.some(c=>{let d=r[c.field];if(typeof d!="string"||d==="")return!1;let{prefix:m}=c;if(m!==void 0&&(m===null||!d.startsWith(m))||this.deps.remapper.getTargetId(c.parent,d)!==void 0)return!1;let p=ne(d);return s.stayedOut.has(p)||s.kept.get(c.parent)?.has(p)!==!0}))return!0;n.cutSinceFit++;let a=r.Id;return typeof a=="string"&&a!==""&&s.stayedOut.set(ne(a),e),!1})}notWrittenOf(e){if(!this.planned.has(e))return;let t=this.notWritten.get(e);return t||(this.skippedObjects.has(e)&&!this.reached.has(e)?"skipped":void 0)}async namesARecordOf(e,t,n,s){let o=(await this.lookupsOf(e))?.find(r=>r.name===t.fieldApiName);if(o?.referenceTo.length===1)return o.referenceTo[0]===t.from;if(o&&o.referenceTo.length>1){let r=await this.keyPrefixOf(t.from);return typeof r=="string"&&r!==""&&n.startsWith(r)}return s===1}async linkPersonContacts(e,t,n){let s=e.filter(Se),o=this.deps.queryTarget;if(s.length===0||!o)return e;let r=await this.lookupsOf(le);if(r&&!r.some(p=>p.name===ft))return e;let i=new Map;for(let p of s){let l=p.AccountId,g=typeof l=="string"&&l!==""?this.deps.remapper.getTargetId(le,l):void 0;g&&i.set(p,g)}let a=new Map,c;if(i.size>0)try{t.apiCallsUsed++,a=await bn(o,[...new Set(i.values())])}catch(p){c=ee(p)}let d=(p,l,g)=>{t.failed++,t.errors.push(`${l}: ${g}`),t.refusals.add([{statusCode:l,message:g,fields:["AccountId"]}]);let y=p.Id;typeof y=="string"&&y!==""&&this.refusedRecords.set(ne(y),me)},m=[];for(let p of e){if(!Se(p)){m.push(p);continue}let l=i.get(p);if(l===void 0){d(p,tr,"the person account this contact belongs to is not in the target: the platform writes the contact with the account, and sent on its own it would stand as a contact of no account.");continue}if(c!==void 0){d(p,nr,`the contact the platform wrote with its person account could not be looked up (${c}): sent, this one would stand beside it as a second contact.`);continue}let g=a.get(l),y=p.Id;if(g===void 0||typeof y!="string"){m.push(p);continue}n.push([y,g]),t.linked++,this.personContactsLinked++}return m}async leaveOutForAccountKind(e,t){let s=e.some(Se)?await this.takenAsBusiness(t):()=>!1,o=e.map((r,i)=>wn(r,s(t[i])));t.forEach((r,i)=>{for(let a of Object.keys(r))Yt(le,a,o[i])&&delete r[a]})}async takenAsBusiness(e){let t=await this.lookupsOf(le);if(t&&!t.some(a=>a.name===ft))return()=>!0;let n=this.deps.queryTarget;if(!n)return()=>!1;this.personTypes??=n(or).then(a=>new Set(a.flatMap(c=>typeof c.Id=="string"?[ne(c.Id)]:[])),()=>{});let s=await this.personTypes;if(!s)return()=>!1;let o=await this.deps.describeRecordTypes?.(le).catch(()=>{}),r=new Set((o??[]).map(a=>ne(a.recordTypeId))),i=e.some(a=>typeof a.RecordTypeId!="string")?ts(o):void 0;return a=>{let c=a.RecordTypeId,d=typeof c=="string"&&c!==""?c:i;if(d===void 0)return!1;let m=ne(d);return!s.has(m)&&r.has(m)}}register(e,t){t.length>0&&this.deps.remapper.registerMappings(e,t)}async startAsDrafts(e,t){let n=new Map,s=ve[e],{queryTarget:o,update:r}=this.deps;if(!s||!o||!r)return n;let i=this.lifecycleByObject.get(e);i||(i=Tn(o,s),this.lifecycleByObject.set(e,i));let a=await i;return a&&t.forEach((c,d)=>{let m=En(c.Status,a);m&&(n.set(d,String(c.Status)),c.Status=m)}),n}async applyDeferredStatuses(){let e={},{update:t}=this.deps;if(!t||this.deferredStatuses.length===0)return e;let n=new Map;for(let s of this.deferredStatuses)n.set(s.objectApiName,[...n.get(s.objectApiName)??[],s]);for(let[s,o]of n){let r=0,i=0,a=new we;for(let c=0;c<o.length;c+=this.batchSize){if(await this.checkPause()){this.noteLeftByStop(s,"statuses",o.slice(c).map(p=>p.id));break}let d=o.slice(c,c+this.batchSize),m=await this.updateSendingLocksAgain(t,s,d.map(p=>({Id:p.id,Status:p.status})),"status update(s)");d.forEach((p,l)=>{let g=m[l];if(g?.success){r++;return}i++,a.add(qt(g))})}e[s]={applied:r,refusals:a.list(),...i>0?{leftDraft:i}:{}}}return this.deferredStatuses.length=0,e}noteLeftByStop(e,t,n){if(n.length===0)return;let s=this.leftByStop.get(e);s||(s={lookups:new Set,statuses:new Set},this.leftByStop.set(e,s));for(let o of n)s[t].add(o)}countEmailsTheStopHeld(e,t,n){let s=this.emailsAfterTheirTask.splice(0,this.emailsAfterTheirTask.length),o=this.emailsHeldAndNotSent+s.length;if(this.emailsHeldAndNotSent=0,o===0)return;let r=n[J]??{written:0,linked:0,failed:0,refusals:[]};n[J]={...r,notSent:(r.notSent??0)+o,heldForTheirTask:o};for(let d of[e.completedObjects,e.failedObjects]){let m=d.indexOf(J);m>=0&&d.splice(m,1)}if(t.includes(J))return;let i=[...this.planned],a=i.indexOf(J),c=t.findIndex(d=>i.indexOf(d)>a);t.splice(c<0?t.length:c,0,J)}countWhatTheStopLeft(e,t){let n=new Set(e);for(let o of this.owedLookups.splice(0,this.owedLookups.length))o.parents.some(i=>n.has(i)||this.deps.remapper.getTargetId(i,o.sourceId)!==void 0)?this.noteLeftByStop(o.objectApiName,"lookups",[o.recordId]):this.owedLookups.push(o);let s=this.deferredStatuses.splice(0,this.deferredStatuses.length);for(let o of s)this.noteLeftByStop(o.objectApiName,"statuses",[o.id]);for(let[o,r]of this.leftByStop){let i=t[o]??{written:0,linked:0,failed:0,refusals:[]};t[o]={...i,...r.lookups.size>0?{lookupsLeftEmpty:r.lookups.size}:{},...r.statuses.size>0?{statusesNotGivenBack:r.statuses.size}:{}}}}pause(){this.paused||(this.paused=!0,this.pausePromise=new Promise(e=>{this.pauseResolve=e}),this.emit("paused",this.makeEvent({type:"paused",timestamp:""})))}resume(){this.paused&&(this.paused=!1,this.pauseResolve?.(),this.pausePromise=null,this.pauseResolve=null,this.emit("resumed",this.makeEvent({type:"resumed",timestamp:""})))}skip(e){this.skippedObjects.add(e)}stopped(){return this.signal?.aborted===!0}wait(e){return this.deps.wait?this.deps.wait(e):Jn(e,this.signal)}async checkPause(){return this.stopped()?!0:(this.paused&&this.pausePromise&&await this.pausePromise,this.stopped())}makeEvent(e){return{...e,timestamp:new Date().toISOString()}}};async function Qe(u,e,t){try{return await u(e,t)}catch(n){let s=ee(n);return t.map(()=>({id:"",success:!1,errors:[s],errorDetails:[yt(s)]}))}}function qt(u){return u?u.errorDetails&&u.errorDetails.length>0?u.errorDetails:u.errors.length>0?u.errors.map(e=>yt(e)):[er]:[Zs]}function ar(u){return u.statusCode===ze?u.message:`${u.statusCode}: ${u.message}`}var Je=class{threshold;partitionSize;constructor(e=5e3,t=2e3){this.threshold=e,this.partitionSize=t}shouldUseGrappe(e){return e>this.threshold}partition(e,t){if(t<=this.partitionSize)return[{id:`${e}-0`,objectApiName:e,offset:0,limit:t,recordCount:t}];let n=[],s=0,o=0;for(;s<t;){let r=Math.min(this.partitionSize,t-s);n.push({id:`${e}-${o}`,objectApiName:e,offset:s,limit:r,recordCount:r}),s+=r,o++}return n}getThreshold(){return this.threshold}getPartitionSize(){return this.partitionSize}};var dr=`sandforge autopilot \u2014 run an Autopilot copy between two orgs, without the editor.
11
11
 
12
12
  Usage:
13
13
  npx sandforge autopilot \\
@@ -32,7 +32,14 @@ Options:
32
32
  --max-records-per-object <n>
33
33
  records of a selected object copied at most, the
34
34
  first by Id, 1 to 1000000 (default: 50000)
35
- --compliance <name> none | gdpr | ccpa | hipaa | pci_dss (default: none)
35
+ --compliance <name> none | gdpr | ccpa | hipaa | pci_dss | every_personal_field
36
+ (default: none). every_personal_field anonymizes the
37
+ fields the detector names and those the org classifies,
38
+ and the names of people and companies, every part of an
39
+ address, the birthdates and the long texts
40
+ --anonymize-everything the same as --compliance every_personal_field;
41
+ ${Vt}=everything does the same when
42
+ --compliance is not given
36
43
  --keep-contact-points write emails and phone numbers as read. Without it,
37
44
  as in the panel, every address is written under
38
45
  .invalid and every phone number as a fictional one,
@@ -92,7 +99,7 @@ Options:
92
99
  it is not needed. --mute-automation keeps quiet what
93
100
  tests the org's bypass; what an Apex trigger sends is
94
101
  read nowhere (default: off)
95
- ${Uo({run:"the run",simulation:"--plan-only",note:["An Autopilot run has no removal: a rewind to this","checkpoint is what takes it back."]})}
102
+ ${us({run:"the run",simulation:"--plan-only",note:["An Autopilot run has no removal: a rewind to this","checkpoint is what takes it back."]})}
96
103
  --json emit the run summary as JSON, with the id
97
104
  of every record the run created (default: off)
98
105
  --fail-on-partial exit 3, not 0, when the run was partial: the target
@@ -137,26 +144,25 @@ asked first refused or not taken, or it died or produced only failures -- a run
137
144
  that died prints no summary, and what it wrote before it died stays; 2 a bad
138
145
  command line; 3 the run was partial and --fail-on-partial was given; 130 Ctrl-C
139
146
  stopped the run, 143 a SIGTERM (a CI job cancelled or timed out), 129 a SIGHUP.
140
- `,_r=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,qr="MAX_TOTAL_EXCEEDED",zr="AUTOPILOT_EMAILS_EXCEEDED",Gr="AUTOPILOT_CANNOT_FIT",Wr={switches:["--standard-objects","--keep-contact-points","--plan-only","--json","--fail-on-partial","--mute-automation","--accept-emails",...It.switches],values:["--source","--target","--object","--max-depth","--max-objects","--max-total","--max-records-per-object","--compliance","--batch-size","--fit","--fit-cap","--fit-within",...It.values]};function Ur(u){let e=u.slice(2);(e.includes("--help")||e.includes("-h"))&&(process.stdout.write(Br),process.exit(0)),Ht(e,Wr);let t=(y,L)=>{let v=e.indexOf(y);return v>=0&&v+1<e.length?e[v+1]:L},n=y=>{let L=[];for(let v=0;v<e.length;v++)e[v]===y&&v+1<e.length&&L.push(e[v+1]);return L},o=t("--source"),r=t("--target"),s=n("--object");(!o||!r||s.length===0)&&(process.stderr.write(`Missing --source, --target or --object. Run with --help.
141
- `),process.exit(2));for(let y of s)_r.test(y)||(process.stderr.write(`Not an SObject API name: "${y}"
142
- `),process.exit(2));let i=["none","gdpr","ccpa","hipaa","pci_dss"],a=t("--compliance","none")??"none";i.includes(a)||(process.stderr.write(`--compliance takes ${i.join(", ")} \u2014 not "${a}".
143
- `),process.exit(2));let c=Number(t("--batch-size","200")??"200");(!Number.isInteger(c)||c<1||c>1e4)&&(process.stderr.write(`--batch-size takes a whole number between 1 and 10000.
144
- `),process.exit(2));let d=(y,L)=>{let v=Number(t(y,String(L))??L);return(!Number.isInteger(v)||v<1)&&(process.stderr.write(`${y} takes a whole number, 1 or more.
145
- `),process.exit(2)),v},m=d("--max-depth",go),p=d("--max-objects",yo),l=d("--max-total",Qn),g=d("--max-records-per-object",5e4);g>Ve&&(process.stderr.write(`--max-records-per-object takes a whole number of records, 1 to ${Ve}.
146
- `),process.exit(2));let w=Ho(e),f=y=>{process.stderr.write(`${y}
147
- `),process.exit(2)},R=er(e,f);for(let y of Object.keys(R?.caps?.objects??{}))s.includes(y)||f(`--fit-cap ${y}: give ${y} with --object too.`);return{source:o,target:r,objects:s,includeStandardObjects:e.includes("--standard-objects"),compliance:a,batchSize:c,maxDepth:m,maxObjects:p,maxTotal:l,maxRecordsPerObject:g,planOnly:e.includes("--plan-only"),keepContactPoints:e.includes("--keep-contact-points"),json:e.includes("--json"),failOnPartial:e.includes("--fail-on-partial"),muteAutomation:e.includes("--mute-automation"),acceptEmails:e.includes("--accept-emails"),...w!==void 0?{checkpointFirst:w}:{},...R?{fit:R}:{}}}function Hr(u){return{...u.share?{share:!0}:{},...u.caps?.objects?{caps:u.caps.objects}:{},...u.caps?.all!==void 0?{all:u.caps.all}:{},...u.withinMB!==void 0?{withinMB:u.withinMB}:{}}}function Kr(u){return async e=>(await vn({query:async t=>u.query(t),queryMore:async t=>u.queryMore(t)},e)).records}async function Xr(u=process.argv){let e=Date.now(),t=Ur(u),n=h=>{process[t.json?"stderr":"stdout"].write(`${h}
148
- `)};n(`sandforge autopilot ${t.source} -> ${t.target}`),n(`objects: ${t.objects.join(", ")}`);let o=Ie(await rt(t.source)),r=await rt(t.target),s=Ie(r),i=t.planOnly?void 0:await Kt(s,t.target,{tool:"sandforge autopilot",action:"write",readOnly:"--plan-only"}),a=t.checkpointFirst?Xo({module:"autopilot",operationId:`sandforge-autopilot-${e}`,request:t.checkpointFirst,session:r,org:Ko(r,i??await ot(s)),connect:Ie,journalDir:Wo(),say:n}):void 0,c=!1,d=new Map,m=new Map,p=async h=>{let S=m.get(h);if(S)return S;let T=await s.sobject(h).describe(),_={creatable:new Set(T.fields.filter(U=>U.createable).map(U=>U.name)),recordTypes:ut(T.recordTypeInfos),keyPrefix:T.keyPrefix??null,lookups:qo(T.fields),currencyFields:Tn(T.fields),fields:T.fields.map(U=>({name:U.name,queryable:!0,createable:U.createable,isReference:U.type==="reference",type:U.type,...U.length>0?{length:U.length}:{},...U.externalId?{externalId:!0}:{}}))};return m.set(h,_),_},l=new qn,g=()=>({query:async(h,S,T)=>(await o.query(yr(h,S,T))).records,queryByIds:async(h,S)=>{let T=S.map(U=>`'${je(U)}'`).join(", ");return(await o.query(`SELECT FIELDS(ALL) FROM ${h} WHERE Id IN (${T}) LIMIT ${S.length}`)).records},insert:async(h,S)=>{let T=S.map(ae=>{let Ye={...ae};return delete Ye.Id,delete Ye.attributes,Ye}),_=ft(await s.sobject(h).create(T,{headers:Ze()}),h);_.some(ae=>ae.success)&&(c=!0);let U=_.filter(ae=>ae.success&&ae.id).map(ae=>ae.id);return d.set(h,[...d.get(h)??[],...U]),_},update:async(h,S)=>{let T=ft(await s.sobject(h).update(S,{headers:Ze()}),h);return T.some(_=>_.success)&&(c=!0),T},querySource:async h=>(await o.query(h)).records,queryTarget:Kr(s),toolingSource:async h=>(await o.tooling.query(h)).records,toolingTarget:async h=>(await s.tooling.query(h)).records,describeKeyPrefix:async h=>(await p(h)).keyPrefix,describeLookups:async h=>(await p(h)).lookups,describeFields:async h=>(await p(h)).fields,anonymizer:l,remapper:new Pe,describeCreateableFields:async h=>(await p(h)).creatable,describeRecordTypes:async h=>(await p(h)).recordTypes,describeRecordTypesAgain:async h=>ut((await s.sobject(h).describe()).recordTypeInfos),describeCurrencyFields:async h=>(await p(h)).currencyFields,countRecordTypes:async h=>{let S=await o.query(Ln(h));return $e(S.records)}}),w=new Ge({schemaScanner:new bo,graphBuilder:new We,complianceEngine:new Ue,anonymizer:l,planGenerator:new He,remapper:new Pe,createExecutor:()=>new Ce(g()),grappeAdapter:new Ke});n(`
149
- scanning\u2026`);let f=await w.scanSchemas(o,s,{selectedObjects:t.objects,includeStandardObjects:t.includeStandardObjects,maxDepth:t.maxDepth,maxObjects:t.maxObjects,maxRecordsPerObject:t.maxRecordsPerObject},h=>n(` ${h}`)),R=w.buildGraph(f,t.batchSize);n(`graph: ${R.nodes.length} node(s), ${R.edges.length} edge(s)`);let y=t.compliance==="none"?[]:Ro(new zn,f.objectDescribes),{rules:L}=w.buildCompliance(t.compliance,[],y),v=w.generatePlan(R,t.compliance,L,f.scope),B=()=>{n(`plan: ${v.waves.length} wave(s), ${v.totalRecords} record(s)`),v.waves.forEach((h,S)=>{n(` wave ${S+1}: ${h.objects.join(", ")}`)});for(let h of Zr(f.scope,t))n(h);for(let h of es(v))n(h)};B();let K=h=>new Map(h.map(S=>[S.objectApiName,S.recordCount])),O=K(R.nodes),A=Ft(v,O,f.personAccounts),F=async()=>{try{return await Jn(Yn(s,i?.id??r.orgId))}catch(h){return{unread:ee(h)}}},E=await F(),Q=At(A,E),re,Z=()=>re??=kt(s),x,H=()=>x??=jt(s).read(t.target,ze(v)).catch(h=>({unread:h instanceof Error?h.message:String(h)})),N,be;if(t.muteAutomation){let h=await H();try{N=await Xn(async()=>Hn(s),h,{writes:(S,T)=>T==="insert"||T==="update"})}catch(S){if(!yt(S))throw S;be={code:S.code,message:S.message.replace(/ Nothing was assigned\.$/,"")}}}let te=await Te(A,E,Z,void 0,{readBack:Oe(A),...ve(N?.plan)});n("");for(let h of St(A,Q,t.target))n(h);a||n(we(te,t.target));for(let h of kr(f.personAccounts))n(h);if(N)for(let h of De(N.muted,t.target))n(` ${h}`);let X,Me;if(a&&A.totalRows>0){let h=new Set(A.objects.map(({objectApiName:_})=>_)),S=N?.automation??await H(),T={written:ze(v).filter(_=>h.has(_)),running:typeof S.unread=="string"?{firing:[]}:{firing:Fe(S,void 0,(_,U)=>U==="insert"||U==="update").firing}};try{X={ask:T,estimate:await a.scope(T)}}catch(_){Me=wt(_).replace(/ Nothing was written\.$/,"")}}if(a&&(te=await Te(A,E,Z,X?.estimate,{readBack:Oe(A),...ve(N?.plan)}),n(we(te,t.target)),X))for(let h of Qo(X.estimate))n(h);let q,ie;if(t.fit){n(`
150
- fitting\u2026`);let h=lo({storage:E,...t.fit.withinMB!==void 0?{withinMB:t.fit.withinMB}:{},api:"unread"in E?await Z().catch(S=>({unread:ee(S)})):E.dailyApiRequests??{unread:`${t.target}'s /limits did not list them`},otherRequests:Zn(X?.estimate)});if("unread"in h)ie={code:Mt.STORAGE_UNREAD,message:`The plan cannot be fitted to ${t.target}, whose data storage left could not be read (${h.unread}): give --fit-within <MB>, the most it may take, to fit it to that.`};else try{q=await w.fitPlan(o,{scan:f,graph:R,plan:v,rules:L,mode:Hr(t.fit),budget:h,automation:await H(),...N?.plan?{mutePlan:N.plan}:{},describeLookups:async T=>(await p(T)).lookups,maxRecords:t.maxTotal,batchSize:t.batchSize,onProgress:T=>n(` ${T}`)});let S=(N?.plan?.assign.length??0)>0;for(let T of Vr(q,t.target,S))n(T);q.cannotFit!==void 0&&(ie={code:Gr,message:`The plan cannot be fitted to ${t.target}: ${q.cannotFit}.`})}catch(S){ie={code:Mt.READ_REFUSED,message:`The plan could not be fitted: the source refused a read of it (${ee(S)}). Run it again; if the source refuses again, narrow the selection (--object, --max-depth), or run it without --fit where it fits.`}}if(q?.fitted){({scan:f,graph:R,plan:v}=q.fitted),O=K(R.nodes),A=Ft(v,O,f.personAccounts),E=await F(),Q=At(A,E),re=void 0;let S=new Set(A.objects.map(({objectApiName:T})=>T));if(a&&X){let{ask:T}=X,_=T.written.filter(U=>S.has(U));if(_.length<T.written.length){let U={written:_,running:{firing:T.running.firing.filter(ae=>S.has(ae.objectApiName))}};try{X={ask:U,estimate:await a.scope(U)}}catch(ae){X=void 0,Me=wt(ae).replace(/ Nothing was written\.$/,"")}}}te=await Te(A,E,Z,X?.estimate,{readBack:Oe(A),...ve(N?.plan)}),n(""),B(),n("");for(let T of St(A,Q,t.target))n(T);n(we(te,t.target));for(let T of kr(f.personAccounts))n(T)}}let se=await zo({plan:A,objects:ze(v),readAutomation:async h=>{if(N?.automation)return N.automation;let S=x?await x:void 0;return S!==void 0&&typeof S.unread!="string"?S:jt(s).read(t.target,h)},readLimits:()=>no(s)});for(let h of ro(se.checks,t.target))n(h);se.unread!==void 0&&n(` emails: not counted, ${se.unread} could not be read`);let ke=new Set(A.objects.map(({objectApiName:h})=>h)),Xe=(h,S)=>ke.has(h)&&(S==="insert"||S==="update"),b=A.totalRows>0?await Un({read:await H(),...N?.plan?{plan:N.plan}:{},writes:Xe,readDeliverability:async()=>Ut(i??await ot(s))?Gn:Wn(s),accepted:t.acceptEmails,target:t.target,run:"autopilot",keepsAddresses:t.keepContactPoints,mayMute:!t.muteAutomation}):void 0,k=b?.gate;k?.line!==void 0&&n(` ${k.line}`);let M=so(b?.ofRun);M.deliverability!==void 0&&(te=await Te(A,E,Z,X?.estimate,{readBack:Oe(A),...ve(N?.plan),...M}),n(we(te,t.target)));let I=A.totalRows>0?await Go(A,()=>kt(o)):void 0;I&&n(ts(I,t.source));let P=(h,S)=>S===void 0?void 0:{code:h,message:S},z=[P(Be,Me??(X?.estimate.refusal!==void 0?Yo(X.estimate.refusal):void 0)),P(qr,A.totalRows>t.maxTotal?`The run would write ${A.totalRows} records, more than --max-total ${t.maxTotal}: narrow it (--object, --max-depth, --max-objects), or raise --max-total.`:void 0),P(qe.STORAGE_EXCEEDED,ao(Q,t.target)),P(qe.API_BUDGET_EXCEEDED,Rt(te,t.target,Bn)?.replace(/ Nothing was written\.$/,"")),P(qe.API_BUDGET_EXCEEDED,I&&to(I,t.source)?.replace(/ Nothing was written\.$/,"")),P(zr,oo(se.checks,t.target)),k?.stop?P(k.stop.code,k.stop.message.replace(/ Nothing was written\./,"")):void 0,be,ie].filter(h=>h!==void 0),C=z.map(({message:h})=>h);if(!t.fit&&!("unread"in E)&&(Q.verdict==="exceeds"||A.totalRows>t.maxTotal||Rt(te,t.target)!==void 0)&&n(" --fit share keeps the largest share of the plan that fits, its records whole"),t.planOnly){let h=await new Ce(g()).recordTypesGivenOf(v,O,f.parentIds,f.scope.cutShort);for(let T of R.nodes){let _=h.get(T.objectApiName);_&&(T.recordTypeGiven=_)}let S=(N?.plan?.assign.length??0)>0;for(let T of Lt(R.nodes,!0,S))n(T);for(let T of z)n(` ${Jt(T)}`);t.json&&process.stdout.write(`${JSON.stringify({tool:"sandforge-autopilot",planOnly:!0,graph:R,plan:v,writeGate:{records:A.totalRows,storage:Q,apiRequests:te,...I?{sourceApiRequests:I}:{},personAccounts:Object.fromEntries(f.personAccounts),emails:se.checks,...se.unread!==void 0?{emailsUnread:se.unread}:{},...k?.deliverability?{deliverability:k.deliverability}:{},refusals:C,refusalCodes:z.map(({code:T})=>T)},...Kn(N),...X?{checkpoint:X.estimate}:{},...q?{fit:br(q)}:{}},null,2)}
151
- `);return}let $=(h,S=[])=>{throw t.json&&process.stdout.write(Vt({tool:"sandforge-autopilot",source:t.source,target:t.target,elapsedMs:Date.now()-e},h,S)),new Error([h,...S].map(Yt).join(`
152
- `))};if(z.length>0){let[h,...S]=z.map(({code:T,message:_})=>({code:T,message:`${_} Nothing was written.`}));$(h,S)}n(`
153
- executing\u2026 (REAL)`);let D=new AbortController,j,Y=Xt(h=>{j=h,process.stderr.write(`
154
- interrupted: the run stops after the call under way, and says what it wrote (Ctrl-C again ends it at once)
155
- `),D.abort()}),G,J,ce,W;try{if(a&&X){let T=X,_=await eo(()=>a.take(T.ask,T.estimate,{signal:D.signal}));if("stop"in _){_.stop.code===Be&&$({code:Be,message:xt(_.stop)}),process.stderr.write(`${xt(_.stop)}
156
- `),it(st(j??"SIGINT"));return}ce=_.checkpoint;for(let U of Jo(_.checkpoint,t.target,t.muteAutomation))n(U)}let h=N?.prepared?await N.prepared.acquire(`sandforge autopilot ${e}`).catch(T=>{if(!yt(T))throw T;return $(T.refusal)}):void 0;J=h?.outcome??N?.muted;let S=h?b?.afterLease(h.outcome,t.acceptEmails):void 0;if(h&&S){J=await h.release();for(let T of De(J,t.target))n(T);$({code:S.code,message:S.message})}i&&An({action:"autopilot_execute",orgId:i.id,operationId:`sandforge-autopilot-${e}`},Q.estimateMB),G=await w.executePlan(v,R,L,O,void 0,D.signal,f.parentIds,{...t.keepContactPoints?{keepContactPoints:!0}:{},...h?{lease:{assigned:h.outcome.assigned.length,giveBack:()=>h.release()}}:{},...q?.fitted?{fit:q.fitted.run}:{}}).finally(async()=>{h&&(J=await h.release())})}finally{if(Y(),i&&Rn({action:"autopilot_execute",orgId:i.id,operationId:`sandforge-autopilot-${e}`,objects:[...d].map(([h,S])=>({...Sn(h),created:S.length}))}),a&&ce){let h=ce;W=await a.settle(h,c).catch(S=>(n(`warning: the checkpoint '${h.name}' taken before the run, which wrote nothing, could not be deleted (${ee(S)}): delete it with ${Je("checkpoint")} delete --org ${t.target} --checkpoint ${h.checkpointId}`),h));for(let S of Vo(W))n(S)}}for(let h of J?De(J,t.target):[])n(h);let pe=Date.now()-e,fe=D.signal.aborted,Qe=_o(G);if(it(fe?st(j??"SIGINT"):Qt(Qe,t.failOnPartial)),t.json){let h={status:Qe,...G,...G.stopped===!0?{cancelled:!0}:{}};process.stdout.write(`${JSON.stringify({tool:"sandforge-autopilot",source:t.source,target:t.target,result:h,created:Object.fromEntries(d),...J?{mutedAutomation:J}:{},...W?{checkpoint:W}:{},...q?{fit:br(q)}:{},elapsedMs:pe,...fe?{interrupted:!0}:{}},null,2)}
157
- `),fe&&process.stderr.write(`${wr(G)}
147
+ `,ur=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,lr="MAX_TOTAL_EXCEEDED",pr="AUTOPILOT_EMAILS_EXCEEDED",fr="AUTOPILOT_CANNOT_FIT",hr={switches:["--standard-objects","--keep-contact-points","--plan-only","--json","--fail-on-partial","--mute-automation","--accept-emails",Le,...Nt.switches],values:["--source","--target","--object","--max-depth","--max-objects","--max-total","--max-records-per-object","--compliance","--batch-size","--fit","--fit-cap","--fit-within",...Nt.values]};function qs(u){return u==="every_personal_field"?"everything":"standard"}function mr(u,e=process.env){let t=u.slice(2);(t.includes("--help")||t.includes("-h"))&&(process.stdout.write(dr),process.exit(0)),Zt(t,hr);let n=(E,L)=>{let S=t.indexOf(E);return S>=0&&S+1<t.length?t[S+1]:L},s=E=>{let L=[];for(let S=0;S<t.length;S++)t[S]===E&&S+1<t.length&&L.push(t[S+1]);return L},o=n("--source"),r=n("--target"),i=s("--object");(!o||!r||i.length===0)&&(process.stderr.write(`Missing --source, --target or --object. Run with --help.
148
+ `),process.exit(2));for(let E of i)ur.test(E)||(process.stderr.write(`Not an SObject API name: "${E}"
149
+ `),process.exit(2));let a=["none","gdpr","ccpa","hipaa","pci_dss","every_personal_field"],c=n("--compliance"),d=t.includes(Le);d&&c!==void 0&&c!=="every_personal_field"&&(process.stderr.write(`${Le} anonymizes every personal field: drop --compliance ${c}, or the flag.
150
+ `),process.exit(2));let m=c??(Qt(d,e)==="everything"?"every_personal_field":"none");a.includes(m)||(process.stderr.write(`--compliance takes ${a.join(", ")} \u2014 not "${m}".
151
+ `),process.exit(2));let p=Number(n("--batch-size","200")??"200");(!Number.isInteger(p)||p<1||p>1e4)&&(process.stderr.write(`--batch-size takes a whole number between 1 and 10000.
152
+ `),process.exit(2));let l=(E,L)=>{let S=Number(n(E,String(L))??L);return(!Number.isInteger(S)||S<1)&&(process.stderr.write(`${E} takes a whole number, 1 or more.
153
+ `),process.exit(2)),S},g=l("--max-depth",Io),y=l("--max-objects",xo),f=l("--max-total",lo),R=l("--max-records-per-object",5e4);R>ot&&(process.stderr.write(`--max-records-per-object takes a whole number of records, 1 to ${ot}.
154
+ `),process.exit(2));let w=ls(t),x=E=>{process.stderr.write(`${E}
155
+ `),process.exit(2)},$=bs(t,x);for(let E of Object.keys($?.caps?.objects??{}))i.includes(E)||x(`--fit-cap ${E}: give ${E} with --object too.`);return{source:o,target:r,objects:i,includeStandardObjects:t.includes("--standard-objects"),compliance:m,batchSize:p,maxDepth:g,maxObjects:y,maxTotal:f,maxRecordsPerObject:R,planOnly:t.includes("--plan-only"),keepContactPoints:t.includes("--keep-contact-points"),json:t.includes("--json"),failOnPartial:t.includes("--fail-on-partial"),muteAutomation:t.includes("--mute-automation"),acceptEmails:t.includes("--accept-emails"),...w!==void 0?{checkpointFirst:w}:{},...$?{fit:$}:{}}}function gr(u){return{...u.share?{share:!0}:{},...u.caps?.objects?{caps:u.caps.objects}:{},...u.caps?.all!==void 0?{all:u.caps.all}:{},...u.withinMB!==void 0?{withinMB:u.withinMB}:{}}}function yr(u){return async e=>(await $n({query:async t=>u.query(t),queryMore:async t=>u.queryMore(t)},e)).records}async function wr(u=process.argv){let e=Date.now(),t=mr(u),n=h=>{process[t.json?"stderr":"stdout"].write(`${h}
156
+ `)};n(`sandforge autopilot ${t.source} -> ${t.target}`),n(`objects: ${t.objects.join(", ")}`);let s=Ne(await dt(t.source)),o=await dt(t.target),r=Ne(o),i=t.planOnly?void 0:await en(r,t.target,{tool:"sandforge autopilot",action:"write",readOnly:"--plan-only"}),a=t.checkpointFirst?fs({module:"autopilot",operationId:`sandforge-autopilot-${e}`,request:t.checkpointFirst,session:o,org:ps(o,i??await ct(r)),connect:Ne,journalDir:ds(),say:n}):void 0,c=!1,d=new Map,m=new Map,p=async h=>{let v=m.get(h);if(v)return v;let O=await r.sobject(h).describe(),q={creatable:new Set(O.fields.filter(W=>W.createable).map(W=>W.name)),recordTypes:mt(O.recordTypeInfos),keyPrefix:O.keyPrefix??null,lookups:is(O.fields),currencyFields:Dn(O.fields),fields:O.fields.map(W=>({name:W.name,queryable:!0,createable:W.createable,isReference:W.type==="reference",type:W.type,...W.length>0?{length:W.length}:{},...W.externalId?{externalId:!0}:{}}))};return m.set(h,q),q},l=new Ln,g=()=>({query:async(h,v,O)=>(await s.query(_s(h,v,O))).records,queryByIds:async(h,v)=>{let O=v.map(W=>`'${Be(W)}'`).join(", ");return(await s.query(`SELECT FIELDS(ALL) FROM ${h} WHERE Id IN (${O}) LIMIT ${v.length}`)).records},insert:async(h,v)=>{let O=v.map(ie=>{let tt={...ie};return delete tt.Id,delete tt.attributes,tt}),q=wt(await r.sobject(h).create(O,{headers:st()}),h);q.some(ie=>ie.success)&&(c=!0);let W=q.filter(ie=>ie.success&&ie.id).map(ie=>ie.id);return d.set(h,[...d.get(h)??[],...W]),q},update:async(h,v)=>{let O=wt(await r.sobject(h).update(v,{headers:st()}),h);return O.some(q=>q.success)&&(c=!0),O},querySource:async h=>(await s.query(h)).records,queryTarget:yr(r),toolingSource:async h=>(await s.tooling.query(h)).records,toolingTarget:async h=>(await r.tooling.query(h)).records,describeKeyPrefix:async h=>(await p(h)).keyPrefix,describeLookups:async h=>(await p(h)).lookups,describeFields:async h=>(await p(h)).fields,anonymizer:l,remapper:new Fe,describeCreateableFields:async h=>(await p(h)).creatable,describeRecordTypes:async h=>(await p(h)).recordTypes,describeRecordTypesAgain:async h=>mt((await r.sobject(h).describe()).recordTypeInfos),describeCurrencyFields:async h=>(await p(h)).currencyFields,countRecordTypes:async h=>{let v=await s.query(Kn(h));return qe(v.records)}}),y=new Ke({schemaScanner:new Lo,graphBuilder:new Xe,complianceEngine:new Ye,anonymizer:l,planGenerator:new Ve,remapper:new Fe,createExecutor:()=>new Ie(g()),grappeAdapter:new Je});n(`
157
+ scanning\u2026`);let f=await y.scanSchemas(s,r,{selectedObjects:t.objects,includeStandardObjects:t.includeStandardObjects,maxDepth:t.maxDepth,maxObjects:t.maxObjects,maxRecordsPerObject:t.maxRecordsPerObject},h=>n(` ${h}`)),R=f.sourceRequests,w=y.buildGraph(f,t.batchSize);n(`graph: ${w.nodes.length} node(s), ${w.edges.length} edge(s)`);let x=t.compliance==="none"?void 0:await In(xn(s),[...f.objectDescribes.keys()]),$=t.compliance==="none"?[]:No(new jn,f.objectDescribes,x?.objects,t.compliance==="every_personal_field");if(x)for(let h of qo(x,$,f.objectDescribes))n(h);let{rules:E}=y.buildCompliance(t.compliance,[],$),L=_o(y.generatePlan(w,t.compliance,E,f.scope),x,f.objectDescribes),S=()=>{n(`plan: ${L.waves.length} wave(s), ${L.totalRecords} record(s)`),L.waves.forEach((h,v)=>{n(` wave ${v+1}: ${h.objects.join(", ")}`)});for(let h of Sr(f.scope,t))n(h);for(let h of vr(L))n(h)};S();let j=h=>new Map(h.map(v=>[v.objectApiName,v.recordCount])),P=j(w.nodes),A=$t(L,P,f.personAccounts),oe=async()=>{try{return await ho(fo(r,i?.id??o.orgId))}catch(h){return{unread:ee(h)}}},X=await oe(),Z=Et(A,X),N,U=()=>N??=Ot(r),V,ge=()=>V??=Bt(r).read(t.target,Ee(L)).catch(h=>({unread:h instanceof Error?h.message:String(h)})),G,Ae;if(t.muteAutomation){let h=await ge();try{G=await so(async()=>no(r),h,{writes:(v,O)=>O==="insert"||O==="update"})}catch(v){if(!At(v))throw v;Ae={code:v.code,message:v.message.replace(/ Nothing was assigned\.$/,"")}}}let ae=await Ce(A,X,U,void 0,{readBack:Pe(A),...Te(G?.plan)});n("");for(let h of Pt(A,Z,t.target))n(h);a||n(Re(ae,t.target));for(let h of Ws(f.personAccounts))n(h);if(G)for(let h of Ge(G.muted,t.target))n(` ${h}`);let _,ce;if(a&&A.totalRows>0){let h=new Set(A.objects.map(({objectApiName:q})=>q)),v=G?.automation??await ge(),O={written:Ee(L).filter(q=>h.has(q)),running:typeof v.unread=="string"?{firing:[]}:{firing:$e(v,void 0,(q,W)=>W==="insert"||W==="update").firing}};try{_={ask:O,estimate:await a.scope(O)}}catch(q){ce=St(q).replace(/ Nothing was written\.$/,"")}}if(a&&(ae=await Ce(A,X,U,_?.estimate,{readBack:Pe(A),...Te(G?.plan)}),n(Re(ae,t.target)),_))for(let h of hs(_.estimate))n(h);let Q,fe;if(t.fit){n(`
158
+ fitting\u2026`);let h=Eo({storage:X,...t.fit.withinMB!==void 0?{withinMB:t.fit.withinMB}:{},api:"unread"in X?await U().catch(v=>({unread:ee(v)})):X.dailyApiRequests??{unread:`${t.target}'s /limits did not list them`},otherRequests:go(_?.estimate)});if("unread"in h)fe={code:Lt.STORAGE_UNREAD,message:`The plan cannot be fitted to ${t.target}, whose data storage left could not be read (${h.unread}): give --fit-within <MB>, the most it may take, to fit it to that.`};else try{Q=await y.fitPlan(s,{scan:f,graph:w,plan:L,rules:E,mode:gr(t.fit),budget:h,automation:await ge(),...G?.plan?{mutePlan:G.plan}:{},describeLookups:async O=>(await p(O)).lookups,maxRecords:t.maxTotal,batchSize:t.batchSize,onProgress:O=>n(` ${O}`)});let v=(G?.plan?.assign.length??0)>0;for(let O of Ar(Q,t.target,v))n(O);Q.cannotFit!==void 0&&(fe={code:fr,message:`The plan cannot be fitted to ${t.target}: ${Q.cannotFit}.`})}catch(v){fe={code:Lt.READ_REFUSED,message:`The plan could not be fitted: the source refused a read of it (${ee(v)}). Run it again; if the source refuses again, narrow the selection (--object, --max-depth), or run it without --fit where it fits.`}}if(Q?.fitted){({scan:f,graph:w,plan:L}=Q.fitted),P=j(w.nodes),A=$t(L,P,f.personAccounts),X=await oe(),Z=Et(A,X),N=void 0;let v=new Set(A.objects.map(({objectApiName:O})=>O));if(a&&_){let{ask:O}=_,q=O.written.filter(W=>v.has(W));if(q.length<O.written.length){let W={written:q,running:{firing:O.running.firing.filter(ie=>v.has(ie.objectApiName))}};try{_={ask:W,estimate:await a.scope(W)}}catch(ie){_=void 0,ce=St(ie).replace(/ Nothing was written\.$/,"")}}}ae=await Ce(A,X,U,_?.estimate,{readBack:Pe(A),...Te(G?.plan)}),n(""),S(),n("");for(let O of Pt(A,Z,t.target))n(O);n(Re(ae,t.target));for(let O of Ws(f.personAccounts))n(O)}}let pe=await as({plan:A,objects:Ee(L),readAutomation:async h=>{if(G?.automation)return G.automation;let v=V?await V:void 0;return v!==void 0&&typeof v.unread!="string"?v:Bt(r).read(t.target,h)},readLimits:()=>bo(r)});for(let h of Ro(pe.checks,t.target))n(h);pe.unread!==void 0&&n(` emails: not counted, ${pe.unread} could not be read`);let b=new Set(A.objects.map(({objectApiName:h})=>h)),k=(h,v)=>b.has(h)&&(v==="insert"||v==="update"),C=A.totalRows>0?await to({read:await ge(),...G?.plan?{plan:G.plan}:{},writes:k,readDeliverability:async()=>Jt(i??await ct(r))?Zn:eo(r),accepted:t.acceptEmails,target:t.target,run:"autopilot",keepsAddresses:t.keepContactPoints,mayMute:!t.muteAutomation}):void 0,M=C?.gate;M?.line!==void 0&&n(` ${M.line}`);let F=Ao(C?.ofRun);F.deliverability!==void 0&&(ae=await Ce(A,X,U,_?.estimate,{readBack:Pe(A),...Te(G?.plan),...F}),n(Re(ae,t.target)));let z=A.totalRows>0?await cs(A,()=>Ot(s)):void 0,T=Tr(R,Q?.report);z&&n(Or(z,t.source,T));let D=A.totalRows>0?await Rs(ks(r),Ee(L).filter(h=>A.objects.some(({objectApiName:v,rows:O})=>v===h&&O>0)),G?.plan?.alsoLifts):void 0;if(D)for(let h of As(D,t.target,t.keepContactPoints))n(h);let B=(h,v)=>v===void 0?void 0:{code:h,message:v},I=[B(We,ce??(_?.estimate.refusal!==void 0?ms(_.estimate.refusal):void 0)),B(lr,A.totalRows>t.maxTotal?`The run would write ${A.totalRows} records, more than --max-total ${t.maxTotal}: narrow it (--object, --max-depth, --max-objects), or raise --max-total.`:void 0),B(He.STORAGE_EXCEEDED,vo(Z,t.target)),B(He.API_BUDGET_EXCEEDED,Tt(ae,t.target,Qn)?.replace(/ Nothing was written\.$/,"")),B(He.API_BUDGET_EXCEEDED,z&&wo(z,t.source)?.replace(/ Nothing was written\.$/,"")),B(pr,ko(pe.checks,t.target)),M?.stop?B(M.stop.code,M.stop.message.replace(/ Nothing was written\./,"")):void 0,Ae,fe].filter(h=>h!==void 0),te=I.map(({message:h})=>h);if(!t.fit&&!("unread"in X)&&(Z.verdict==="exceeds"||A.totalRows>t.maxTotal||Tt(ae,t.target)!==void 0)&&n(" --fit share keeps the largest share of the plan that fits, its records whole"),t.planOnly){let h=await new Ie(g()).recordTypesGivenOf(L,P,f.parentIds,f.scope.cutShort);for(let O of w.nodes){let q=h.get(O.objectApiName);q&&(O.recordTypeGiven=q)}let v=(G?.plan?.assign.length??0)>0;for(let O of _t(w.nodes,!0,v))n(O);for(let O of I)n(` ${rn(O)}`);t.json&&process.stdout.write(`${JSON.stringify({tool:"sandforge-autopilot",planOnly:!0,anonymizationMode:qs(t.compliance),graph:w,plan:L,writeGate:{records:A.totalRows,storage:Z,apiRequests:ae,...z?{sourceApiRequests:z}:{},...T?{sourceRequestsRead:T}:{},personAccounts:Object.fromEntries(f.personAccounts),emails:pe.checks,...pe.unread!==void 0?{emailsUnread:pe.unread}:{},...M?.deliverability?{deliverability:M.deliverability}:{},refusals:te,refusalCodes:I.map(({code:O})=>O)},...D?{validationRules:D}:{},...oo(G),..._?{checkpoint:_.estimate}:{},...Q?{fit:Gs(Q)}:{}},null,2)}
159
+ `);return}let Y=(h,v=[])=>{throw t.json&&process.stdout.write(an({tool:"sandforge-autopilot",source:t.source,target:t.target,elapsedMs:Date.now()-e},h,v)),new Error([h,...v].map(sn).join(`
160
+ `))};if(I.length>0){let[h,...v]=I.map(({code:O,message:q})=>({code:O,message:`${q} Nothing was written.`}));Y(h,v)}n(`
161
+ executing\u2026 (REAL)`);let re=new AbortController,se,H=nn(h=>{se=h,tn("the run stops after the call under way, and says what it wrote",h),re.abort()}),K,de,Ze,xe;try{if(a&&_){let O=_,q=await yo(()=>a.take(O.ask,O.estimate,{signal:re.signal}));if("stop"in q){q.stop.code===We&&Y({code:We,message:Dt(q.stop)}),process.stderr.write(`${Dt(q.stop)}
162
+ `),lt(ut(se??"SIGINT"));return}Ze=q.checkpoint;for(let W of gs(q.checkpoint,t.target,t.muteAutomation))n(W)}let h=G?.prepared?await G.prepared.acquire(`sandforge autopilot ${e}`).catch(O=>{if(!At(O))throw O;return Y(O.refusal)}):void 0;de=h?.outcome??G?.muted;let v=h?C?.afterLease(h.outcome,t.acceptEmails):void 0;if(h&&v){de=await h.release();for(let O of Ge(de,t.target))n(O);Y({code:v.code,message:v.message})}i&&Mn({action:"autopilot_execute",orgId:i.id,operationId:`sandforge-autopilot-${e}`},{mb:Z.estimateMB,rowBytes:po(A)}),K=await y.executePlan(L,w,E,P,void 0,re.signal,f.parentIds,{...t.keepContactPoints?{keepContactPoints:!0}:{},...h?{lease:{assigned:h.outcome.assigned.length,giveBack:()=>h.release()}}:{},...Q?.fitted?{fit:Q.fitted.run}:{}}).finally(async()=>{h&&(de=await h.release())})}finally{if(H(),i&&Cn({action:"autopilot_execute",orgId:i.id,operationId:`sandforge-autopilot-${e}`,objects:[...d].map(([h,v])=>({...Fn(h),created:v.length}))}),a&&Ze){let h=Ze;xe=await a.settle(h,c).catch(v=>(n(`warning: the checkpoint '${h.name}' taken before the run, which wrote nothing, could not be deleted (${ee(v)}): delete it with ${nt("checkpoint")} delete --org ${t.target} --checkpoint ${h.checkpointId}`),h));for(let v of ys(xe))n(v)}}for(let h of de?Ge(de,t.target):[])n(h);let Gt=Date.now()-e,je=re.signal.aborted,et=rs(K);if(lt(je?ut(se??"SIGINT"):on(et,t.failOnPartial)),t.json){let h={status:et,...K,...K.stopped===!0?{cancelled:!0}:{}};process.stdout.write(`${JSON.stringify({tool:"sandforge-autopilot",source:t.source,target:t.target,anonymizationMode:qs(t.compliance),result:h,created:Object.fromEntries(d),...de?{mutedAutomation:de}:{},...xe?{checkpoint:xe}:{},...Q?{fit:Gs(Q)}:{},...D?{validationRules:D}:{},elapsedMs:Gt,...je?{interrupted:!0}:{}},null,2)}
163
+ `),je&&process.stderr.write(`${zs(K)}
158
164
  `);return}n(`
159
- status: ${Qe}`),n(`written: ${G.totalSuccess} linked: ${G.totalLinked??0} refused: ${G.totalFailure} skipped: ${G.totalSkipped}`),G.skippedObjects.length>0&&n(` skipped: ${G.skippedObjects.join(", ")}`),G.cutSinceFit!==void 0&&n(` cut since the fit: ${G.cutSinceFit}, read naming a record the fit cut`),G.fatalError&&n(` the run died with: ${G.fatalError}`);for(let h of Qr(G))n(h);for(let h of ns(G))n(h);if(fe){process.stderr.write(`${wr(G)}
165
+ status: ${et}`),n(`written: ${K.totalSuccess} linked: ${K.totalLinked??0} refused: ${K.totalFailure} skipped: ${K.totalSkipped}`),K.skippedObjects.length>0&&n(` skipped: ${K.skippedObjects.join(", ")}`),K.cutSinceFit!==void 0&&n(` cut since the fit: ${K.cutSinceFit}, read naming a record the fit cut`),K.fatalError&&n(` the run died with: ${K.fatalError}`);for(let h of br(K))n(h);for(let h of Er(K,D))n(h);if(je){process.stderr.write(`${zs(K)}
160
166
  `);return}n(`
161
- done in ${pe}ms`)}function wr(u){let e=u.stoppedObjects??[];return`interrupted: the run stopped before it was through, ${u.totalSuccess} record(s) written${e.length>0?`, ${e.join(", ")} cut short or not written`:""}; --json names every record it created`}function Qr(u){let e=u.contactPoints;if(!e)return["emails and phone numbers: written as read (--keep-contact-points)"];if(e.values===0)return["emails and phone numbers: none to neutralize"];let t=e.fields.map(n=>`${n.objectApiName}.${n.field} ${n.values}`).join(", ");return[`emails and phone numbers: ${e.values} neutralized (${t}) -- addresses under .invalid, numbers fictional`]}function Yr(u){return`${Math.floor(u*1e3)/10} %`}function Jr(u){switch(u.kind){case"trigger":return`what Apex trigger ${u.name} on ${u.objectApiName} creates`;case"notRead":return`what "${u.name}" on ${u.objectApiName} creates: it was not read`;case"share":return`the ${u.name} rows the flows of ${u.objectApiName} create`}}function Vr(u,e,t){let{heldBy:n,report:o}=u,{budget:r}=o;if(u.cannotFit!==void 0)return[`fit: the plan cannot be fitted: ${u.cannotFit}`];if(n==="whole")return[`fit: the plan fits as it is, ${o.records} record(s), about ${ye(o.estimateMB)} MB: nothing cut`];let s=ye(r.budgetMB+r.automationMB),i={apiRequests:`the largest whose writes leave ${e} a tenth of its daily API requests`,maxTotal:"the largest --max-total lets through",within:`the largest that fits the ${r.withinMB??s} MB asked (--fit-within)`,storage:`the largest that fits ${s} MB: ${r.share*100} % of the ${r.remainingMB} MB ${e} says it has left of ${r.maxMB}, ${r.roundingMB} MB kept first for the rounding of what it says`+uo(r)},a=u.automationUnread!==void 0?`no room kept for what its automation creates: it could not be read (${u.automationUnread})`:r.automationMB>0?`${ye(r.automationMB)} MB of it kept for what its flows still running create under these records`:"nothing kept for its flows: none still running creates records under these"+(t?" (--mute-automation keeps the others quiet)":""),c=n==="caps"?`fit: the caps asked, within the ${s} MB that fit`:`fit: share ${Yr(o.share??1)}, ${i[n]}`,d=Math.max(...o.objects.map(l=>l.objectApiName.length)),m=l=>{let g=l.cutWithParent.reduce((R,y)=>R+y.count,0),w=l.cutSpread+g,f=[...l.cutWithParent.map(R=>`${R.count} with their ${R.parent} (${R.field})`),...l.cutSpread>0?[`${l.cutSpread} spread over the table`]:[]];return` ${l.objectApiName.padEnd(d)} ${l.kept} of ${l.inSource}`+(w>0?` cut ${w}: ${f.join(", ")}`:"")},p=o.emptied.map(l=>`${l.objectApiName}.${l.field} on ${l.count} (`+(l.why==="selfReference"?"the record of its own object it names was cut":"the record it names, written after, was cut")+")");return[`${c}; ${a}`,...o.objects.map(m),...o.parents.map(l=>` ${l.objectApiName}: ${l.records}, those the kept records name`),...p.length>0?[` left empty: ${p.join(", ")}`]:[],...(r.notCounted??[]).map(l=>` not counted: ${Jr(l)}`),` fitted plan: ${o.records} record(s), about ${ye(o.estimateMB)} MB`+(r.automationMB>0?` and ${ye(r.automationMB)} MB for what its flows create under them`:"")+`; ${o.requestsRead} requests read to fit it`,` ${co(e)}`]}function br(u){return{applied:u.fitted!==void 0,...u.report,heldBy:u.heldBy,...u.cannotFit!==void 0?{cannotFit:u.cannotFit}:{},...u.automationUnread!==void 0?{automationUnread:u.automationUnread}:{},...u.fitted?{keptIds:Object.fromEntries(u.keptIds)}:{}}}function Zr(u,e){let t=new Set((u.cutShort??[]).map(a=>a.objectApiName)),n=u.selected.filter(a=>!t.has(a)),o=[`scope: depth ${u.maxDepth}, at most ${u.maxObjects} object(s)`];if(u.fitted){let a=u.fitted.objects.map(c=>`${c.objectApiName} ${c.kept} of ${c.inSource}`);o.push(` fitted to the target's storage, read by id: ${a.join(", ")}`)}else(n.length>0||u.selected.length===0)&&o.push(` copied whole, as selected: ${n.join(", ")||"(none)"}`);let r=`${Je("clone")} --depth all --source ${e.source} --target ${e.target} --fit share --dry-run`;for(let a of u.cutShort??[]){let c=a.total!==void 0?` of ${a.total}`:"";o.push(` ${a.objectApiName}: ${a.copied}${c} record(s) copied, the first by Id -- --max-records-per-object copies more, up to 1000000; a sample of the whole org that fits the target: ${r}`)}if(u.parents.length>0){o.push(" read by id, only the records the selection references:");for(let a of u.parents)o.push(` ${a.objectApiName.padEnd(40)}${String(a.records).padStart(8)}`)}for(let a of u.standardNeeded)o.push(` ${a.objectApiName} taken though standard objects are off: ${a.neededBy} cannot be left empty`);for(let a of u.followedByDefault??[])o.push(` ${a.objectApiName} followed by default though standard objects are off: ${a.referencedBy.join(", ")} reference${a.referencedBy.length===1?"s":""} it`);let s={depth:`further than ${u.maxDepth} lookup(s)`,objects:`past ${u.maxObjects} object(s)`,standard:"a standard object (--standard-objects to take it)"};if(u.leftEmpty.length>0){o.push(` left empty (${u.leftEmpty.length} lookup(s)):`);for(let a of u.leftEmpty)o.push(` ${a.objectApiName}.${a.fieldApiName} -> ${a.target}: ${s[a.reason]}`+(a.required?" \u2014 required: its records will be refused":""))}let i=u.currencies;return i&&o.push(` currencies the target does not hold active: ${i.notInTarget.join(", ")} \u2014 a record in one is written in ${i.writtenIn}, its corporate currency, its amounts converted at the source's rates (${i.objects.join(", ")})`),o}function kr(u){let e=u.get("Account")??0,t=u.get("Contact")??0;return e===0&&t===0?[]:[` sized as Salesforce counts them: ${[...e>0?[`${e} person account(s) at 4 KB each`]:[],...t>0?[`${t} contact(s) of person accounts at none of their own`]:[]].join(", ")}`]}function es(u){if(u.complianceFramework==="none")return[];let e=u.anonymizationSummary,t=[`anonymization (${u.complianceFramework}): ${e.totalFieldsToAnonymize} field(s) on ${e.objectsWithPii.join(", ")||"no object"}`];for(let n of e.notCovered??[])t.push(` ${n.objectApiName}: no rule for its ${n.missing.join(", ")} \u2014 copied as the source holds them`);return t}function ts(u,e){return we(u,e).replace(/^ {2}API requests:/," API requests read from the source:")}function ns(u){let e=[],t=n=>{for(let o of n){let r=o.fields.length>0?` [${o.fields.join(", ")}]`:"";e.push(` ${o.statusCode}${r} x${o.count}: ${o.message}`)}};for(let[n,o]of Object.entries(u.objectOutcomes??{})){let r=o.notSent??0;e.push(` ${n.padEnd(28)} written ${o.written} linked ${o.linked} refused ${o.failed}${r>0?` not sent ${r}`:""}`),t(o.refusals);let s=o.sentAgainForALock,i=s&&Se("record(s)",{refused:s.rows,sentAgain:s.rows,written:s.written,stillLocked:s.stillLocked,notSentAgain:0});i&&e.push(` ${i}`),o.threw!==void 0&&e.push(` FAILED part way: ${o.threw}`),o.lookupsLeftEmpty!==void 0&&e.push(` ${o.lookupsLeftEmpty} record(s) keep a lookup empty: the stop came before the second pass filled it`),o.statusesNotGivenBack!==void 0&&e.push(` ${o.statusesNotGivenBack} record(s) stay drafts: the stop came before their status was given back`);for(let a of o.leftToDefault??[])e.push(` left to the target's default: ${a.field} x${a.count}`);for(let a of o.leftToThePlatform??[])e.push(` ${sn(a.count,a.why)}`);o.withTheirPersonAccount!==void 0&&o.withTheirPersonAccount>0&&e.push(` ${o.withTheirPersonAccount} contact(s) of person accounts left to the platform, which wrote each with its account: linked to it, not sent`),o.cutSinceFit!==void 0&&e.push(` ${Dt} x${o.cutSinceFit}: read naming a record the fit cut, and left out with it: neither written nor refused`);for(let a of o.currenciesReplaced??[])e.push(` ${In(a)}`);for(let a of Bo(o.pricesSettled??[]))e.push(` ${a}`)}for(let n of u.failedObjects)u.objectOutcomes?.[n]||e.push(` ${n.padEnd(28)} FAILED: ${u.nodeErrors?.[n]??"(no message)"}`);for(let[n,o]of Object.entries(u.lookups??{}))e.push(` ${n.padEnd(28)} lookups filled ${o.filled} refused ${o.leftEmpty??0}`),t(o.refusals);for(let[n,o]of Object.entries(u.statuses??{}))e.push(` ${n.padEnd(28)} statuses applied ${o.applied} refused ${o.leftDraft??0}`),t(o.refusals);return e.push(...Lt(Object.values(u.objectOutcomes??{}),!1)),e}process.argv[1]?.includes("sandforge-autopilot")&&(Zo(),Xr().catch(u=>{process.stderr.write(`${u instanceof Error?u.message:String(u)}
162
- `),process.exit(1)}));export{es as anonymizationLines,br as autopilotFitJson,Vr as autopilotFitLines,wr as autopilotInterruptedLine,Qr as contactPointLines,Kr as everyPage,Xr as main,ns as outcomeLines,Ur as parseArgs,kr as personAccountLines,Zr as scopeLines,ts as sourceReadsLine};
167
+ done in ${Gt}ms`)}function zs(u){let e=u.stoppedObjects??[];return`interrupted: the run stopped before it was through, ${u.totalSuccess} record(s) written${e.length>0?`, ${e.join(", ")} cut short or not written`:""}; --json names every record it created`}function br(u){let e=u.contactPoints;if(!e)return["emails and phone numbers: written as read (--keep-contact-points)"];if(e.values===0)return["emails and phone numbers: none to neutralize"];let t=e.fields.map(n=>`${n.objectApiName}.${n.field} ${n.values}`).join(", ");return[`emails and phone numbers: ${e.values} neutralized (${t}) -- addresses under .invalid, numbers fictional`,...uo(e).map(n=>` ${n}`)]}function kr(u){return`${Math.floor(u*1e3)/10} %`}function Rr(u){switch(u.kind){case"trigger":return`what Apex trigger ${u.name} on ${u.objectApiName} creates`;case"notRead":return`what "${u.name}" on ${u.objectApiName} creates: it was not read`;case"share":return`the ${u.name} rows the flows of ${u.objectApiName} create`}}function Ar(u,e,t){let{heldBy:n,report:s}=u,{budget:o}=s;if(u.cannotFit!==void 0)return[`fit: the plan cannot be fitted: ${u.cannotFit}`];if(n==="whole")return[`fit: the plan fits as it is, ${s.records} record(s), about ${ke(s.estimateMB)} MB: nothing cut`];let r=ke(o.budgetMB+o.automationMB),i={apiRequests:`the largest whose writes leave ${e} a tenth of its daily API requests`,maxTotal:"the largest --max-total lets through",within:`the largest that fits the ${o.withinMB??r} MB asked (--fit-within)`,storage:`the largest that fits ${r} MB: ${o.share*100} % of the ${o.remainingMB} MB ${e} says it has left of ${o.maxMB}, ${o.roundingMB} MB kept first for the rounding of what it says`+To(o)},a=u.automationUnread!==void 0?`no room kept for what its automation creates: it could not be read (${u.automationUnread})`:o.automationMB>0?`${ke(o.automationMB)} MB of it kept for what its flows still running create under these records`:"nothing kept for its flows: none still running creates records under these"+(t?" (--mute-automation keeps the others quiet)":""),c=n==="caps"?`fit: the caps asked, within the ${r} MB that fit`:`fit: share ${kr(s.share??1)}, ${i[n]}`,d=Math.max(...s.objects.map(l=>l.objectApiName.length)),m=l=>{let g=l.cutWithParent.reduce((R,w)=>R+w.count,0),y=l.cutSpread+g,f=[...l.cutWithParent.map(R=>`${R.count} with their ${R.parent} (${R.field})`),...l.cutSpread>0?[`${l.cutSpread} spread over the table`]:[]];return` ${l.objectApiName.padEnd(d)} ${l.kept} of ${l.inSource}`+(y>0?` cut ${y}: ${f.join(", ")}`:"")},p=s.emptied.map(l=>`${l.objectApiName}.${l.field} on ${l.count} (`+(l.why==="selfReference"?"the record of its own object it names was cut":"the record it names, written after, was cut")+")");return[`${c}; ${a}`,...s.objects.map(m),...s.parents.map(l=>` ${l.objectApiName}: ${l.records}, those the kept records name`),...p.length>0?[` left empty: ${p.join(", ")}`]:[],...(o.notCounted??[]).map(l=>` not counted: ${Rr(l)}`),` fitted plan: ${s.records} record(s), about ${ke(s.estimateMB)} MB`+(o.automationMB>0?` and ${ke(o.automationMB)} MB for what its flows create under them`:"")+`; ${s.requestsRead} requests read to fit it`,` ${Oo(e)}`]}function Gs(u){return{applied:u.fitted!==void 0,...u.report,heldBy:u.heldBy,...u.cannotFit!==void 0?{cannotFit:u.cannotFit}:{},...u.automationUnread!==void 0?{automationUnread:u.automationUnread}:{},...u.fitted?{keptIds:Object.fromEntries(u.keptIds)}:{}}}function Sr(u,e){let t=new Set((u.cutShort??[]).map(a=>a.objectApiName)),n=u.selected.filter(a=>!t.has(a)),s=[`scope: depth ${u.maxDepth}, at most ${u.maxObjects} object(s)`];if(u.fitted){let a=u.fitted.objects.map(c=>`${c.objectApiName} ${c.kept} of ${c.inSource}`);s.push(` fitted to the target's storage, read by id: ${a.join(", ")}`)}else(n.length>0||u.selected.length===0)&&s.push(` copied whole, as selected: ${n.join(", ")||"(none)"}`);let o=`${nt("clone")} --depth all --source ${e.source} --target ${e.target} --fit share --dry-run`;for(let a of u.cutShort??[]){let c=a.total!==void 0?` of ${a.total}`:"";s.push(` ${a.objectApiName}: ${a.copied}${c} record(s) copied, the first by Id -- --max-records-per-object copies more, up to 1000000; a sample of the whole org that fits the target: ${o}`)}if(u.parents.length>0){s.push(" read by id, only the records the selection references:");for(let a of u.parents)s.push(` ${a.objectApiName.padEnd(40)}${String(a.records).padStart(8)}`)}for(let a of u.standardNeeded)s.push(` ${a.objectApiName} taken though standard objects are off: ${a.neededBy} cannot be left empty`);for(let a of u.followedByDefault??[])s.push(` ${a.objectApiName} followed by default though standard objects are off: ${a.referencedBy.join(", ")} reference${a.referencedBy.length===1?"s":""} it`);let r={depth:`further than ${u.maxDepth} lookup(s)`,objects:`past ${u.maxObjects} object(s)`,standard:"a standard object (--standard-objects to take it)"};if(u.leftEmpty.length>0){s.push(` left empty (${u.leftEmpty.length} lookup(s)):`);for(let a of u.leftEmpty)s.push(` ${a.objectApiName}.${a.fieldApiName} -> ${a.target}: ${r[a.reason]}`+(a.required?" \u2014 required: its records will be refused":""))}let i=u.currencies;return i&&s.push(` currencies the target does not hold active: ${i.notInTarget.join(", ")} \u2014 a record in one is written in ${i.writtenIn}, its corporate currency, its amounts converted at the source's rates (${i.objects.join(", ")})`),s}function Ws(u){let e=u.get("Account")??0,t=u.get("Contact")??0;return e===0&&t===0?[]:[` sized as Salesforce counts them: ${[...e>0?[`${e} person account(s) at 4 KB each`]:[],...t>0?[`${t} contact(s) of person accounts at none of their own`]:[]].join(", ")}`]}function vr(u){if(u.complianceFramework==="none")return[];let e=u.anonymizationSummary,t=[`anonymization (${u.complianceFramework}): ${e.totalFieldsToAnonymize} field(s) on ${e.objectsWithPii.join(", ")||"no object"}`];for(let n of e.notCovered??[])t.push(` ${n.objectApiName}: no rule for its ${n.missing.join(", ")} \u2014 copied as the source holds them`);return t}function Or(u,e,t={}){let n=Re(u,e).replace(/^ {2}API requests:/," API requests read from the source:"),{scan:s=0,fit:o=0}=t;if(s+o===0)return n;let r=s>0&&o>0?"the scan and the fit":s>0?"the scan":"the fit";return`${n}; beside them, ${r} read ${s+o} request(s) of ${e} to make the plan`}function Tr(u,e){let t={...u!==void 0&&u>0?{scan:u}:{},...e!==void 0&&e.requestsRead>0?{fit:e.requestsRead}:{}};return Object.keys(t).length>0?t:void 0}function Er(u,e){let t=[],n=(s,o)=>{for(let r of s){let i=r.fields.length>0?` [${r.fields.join(", ")}]`:"";t.push(` ${r.statusCode}${i} x${r.count}: ${r.message}`);let a=o!==void 0?Ss(e,o,r):void 0;a&&t.push(` ${a}`)}};for(let[s,o]of Object.entries(u.objectOutcomes??{})){let r=o.notSent??0;t.push(` ${s.padEnd(28)} written ${o.written} linked ${o.linked} refused ${o.failed}${r>0?` not sent ${r}`:""}`),n(o.refusals,s);let i=o.sentAgainForALock,a=i&&Oe("record(s)",{refused:i.rows,sentAgain:i.rows,written:i.written,stillLocked:i.stillLocked,notSentAgain:0});a&&t.push(` ${a}`),o.threw!==void 0&&t.push(` FAILED part way: ${o.threw}`),o.lookupsLeftEmpty!==void 0&&t.push(` ${o.lookupsLeftEmpty} record(s) keep a lookup empty: the stop came before the second pass filled it`),o.statusesNotGivenBack!==void 0&&t.push(` ${o.statusesNotGivenBack} record(s) stay drafts: the stop came before their status was given back`);for(let c of o.leftToDefault??[])t.push(` left to the target's default: ${c.field} x${c.count}`);for(let c of o.leftToThePlatform??[])t.push(` ${hn(c.count,c.why)}`);o.withTheirPersonAccount!==void 0&&o.withTheirPersonAccount>0&&t.push(` ${o.withTheirPersonAccount} contact(s) of person accounts left to the platform, which wrote each with its account: linked to it, not sent`),o.cutSinceFit!==void 0&&t.push(` ${zt} x${o.cutSinceFit}: read naming a record the fit cut, and left out with it: neither written nor refused`);for(let c of o.currenciesReplaced??[])t.push(` ${Wn(c)}`);for(let c of ss(o.pricesSettled??[]))t.push(` ${c}`)}for(let s of u.failedObjects)u.objectOutcomes?.[s]||t.push(` ${s.padEnd(28)} FAILED: ${u.nodeErrors?.[s]??"(no message)"}`);for(let[s,o]of Object.entries(u.lookups??{}))t.push(` ${s.padEnd(28)} lookups filled ${o.filled} refused ${o.leftEmpty??0}`),n(o.refusals);for(let[s,o]of Object.entries(u.statuses??{}))t.push(` ${s.padEnd(28)} statuses applied ${o.applied} refused ${o.leftDraft??0}`),n(o.refusals);return t.push(..._t(Object.values(u.objectOutcomes??{}),!1)),t}process.argv[1]?.includes("sandforge-autopilot")&&(ws(),wr().catch(u=>{process.stderr.write(`${u instanceof Error?u.message:String(u)}
168
+ `),process.exit(1)}));export{vr as anonymizationLines,Gs as autopilotFitJson,Ar as autopilotFitLines,zs as autopilotInterruptedLine,br as contactPointLines,yr as everyPage,wr as main,Er as outcomeLines,mr as parseArgs,Ws as personAccountLines,Sr as scopeLines,Or as sourceReadsLine,Tr as sourceRequestsReadOf};