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
@@ -1,21 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as $n,b as Pd,c as _n,d as Fr}from"./chunk-VLAU5QQT.mjs";import{a as zn,b as hd,c as Mn,d as md,f as bd,g as xn,i as Rd,j as kd}from"./chunk-TSTCHIBU.mjs";import{a as jr,b as yd,c as qo,d as ot,e as Dn,f as ar,g as Wo,h as wd}from"./chunk-U4S27YRP.mjs";import{j as Id,k as vd,n as Od,o as Sd,p as Ad}from"./chunk-YTBM3TSW.mjs";import{l as Oa}from"./chunk-GG5I52UT.mjs";import{c as gd,d as fe}from"./chunk-UV74P4H2.mjs";import{k as pd}from"./chunk-SKGAERV4.mjs";import{i as Sa}from"./chunk-MRN72UEO.mjs";import{e as va,f as No}from"./chunk-A3QNSALB.mjs";import{H as ud,O as Bo,P as fd,i as od,m as Cn,n as sd,o as id,p as ad,q as dd,w as cd}from"./chunk-TFGJDZFE.mjs";import{l as ld}from"./chunk-2JRVBXJL.mjs";import{a as ra,b as Pn}from"./chunk-XCA5AONB.mjs";import{$a as Po,Ec as An,Fc as jo,Xa as Fi,Ya as Ei,Za as Li,_a as Ni,a as ki,ab as Ci,b as Ot,bb as zi,cb as Mi,db as Di,eb as xi,g as Io,h as Ii,j as Se,k as vi,l as vr,m as Oi,n as Rt,o as te,s as vo,xc as nt}from"./chunk-RIIJJRGF.mjs";import{a as bn}from"./chunk-CE6ZDGBB.mjs";import{a as da,b as ca}from"./chunk-BOGNK4LV.mjs";import{$a as nd,Ia as Qa,Oa as ed,R as Za,Va as td,Xa as _o,_a as rd,a as Qs,b as ei,i as Ua,j as Ka,o as xo,va as $o}from"./chunk-SAHGDSZQ.mjs";import{a as Vi,b as To,c as Hi,d as Yi,e as Ji,l as ea,m as ta}from"./chunk-TG52WNGV.mjs";import{A as qi,B as Wi,I as Gi,M as $t,N as Ui,O as vn,P as Ki}from"./chunk-CSSOLHE3.mjs";import{a as Va,b as Do,c as Tr,d as Ln,h as Ha,i as Nn,j as Ya,l as Ja,m as Xa}from"./chunk-TEIBWMJM.mjs";import{c as On,d as Sn}from"./chunk-T63U4OZJ.mjs";import{e as Ra,h as ka,j as Ia}from"./chunk-5EESNYE3.mjs";import{f as ba,i as Lo,j as Fn}from"./chunk-EINEGS6E.mjs";import{a as Xi,c as Zi,d as Qi,r as Eo}from"./chunk-YGE4AUXG.mjs";import{H as Fo,L as ua,i as la,k as jn}from"./chunk-SF52ZSIV.mjs";import{r as Oe}from"./chunk-3EOIAC2M.mjs";import{b as na,c as oa,g as sa}from"./chunk-AIUAEBHR.mjs";import{Dc as Ba,Ec as qa,Fc as Wa,Pc as Ga,Za as Co,_b as La,ec as Na,gc as Ca,hb as zo,hc as za,i as Or,ib as Aa,j as Tn,k as ia,lc as Ma,mb as Pa,mc as Da,nb as Mo,ob as Ta,p as aa,pc as xa,qb as Pr,qc as $a,r as Sr,rb as ja,rc as _a,sb as Fa,ub as Ea}from"./chunk-O3ZQSWDN.mjs";import{e as wi,f as bi,j as Qe,k as Ri}from"./chunk-DNE7JI3A.mjs";import{q as En}from"./chunk-5T3LFDJ5.mjs";import{a as lt,b as St}from"./chunk-VV3B6IC3.mjs";import{a as Mt}from"./chunk-4TLYUZD5.mjs";import{b as fa,d as pa,f as Ar,g as ga,h as ha,i as ma,j as ya,p as wa}from"./chunk-AX3YF7SC.mjs";import{i as Si}from"./chunk-INIT2UKJ.mjs";import{h as _i}from"./chunk-JBOGAUGH.mjs";import{b as Bi,d as In}from"./chunk-4N425UJC.mjs";import{b as Rn}from"./chunk-HFSBDM7B.mjs";import{b as Pi,c as ct,e as Oo,g as Ti,h as So,i as ji,j as Ao}from"./chunk-OHEOJISY.mjs";import{a as Ai}from"./chunk-EADHKH3A.mjs";import{h as ir}from"./chunk-FG4Y4ZVL.mjs";import{$ as fi,E as ai,F as Dt,G as bt,I as Ro,L as di,M as ci,N as li,Y as ko,Z as ui,a as kr,b as Ze,c as tr,d as hn,da as xt,ea as pi,f as rr,fa as gi,g as ti,ga as hi,ha as mi,ia as yi,ja as or,k as ri,ka as sr,l as bo,m as ni,n as oi,o as si,p as ii,q as Ve,r as We,s as mn,t as Ir,u as yn,v as nr,z as wn}from"./chunk-Z354SAEF.mjs";import{a as $e,h as me}from"./chunk-TZE3Y7IQ.mjs";import{b as Q}from"./chunk-CA5NAXSU.mjs";import{a as $i}from"./chunk-THYQOG24.mjs";import{b as kn}from"./chunk-UNDIBZWG.mjs";import{Cc as an,Ec as _e,Fc as dn,Gc as wt,Hc as Ct,Ic as cn,Lc as qe,Mc as Xe,Nc as ln,Oc as xe,Pc as er,Qc as Vs,Qd as Xs,Sc as Hs,Tc as un,Xd as Zs,Zc as Ys,Zd as Rr,dd as Js,fe as zt,ge as gn,id as fn,jd as pn,s as Us,yc as Ks,zc as Qt}from"./chunk-CRPLDXJU.mjs";import{b as De,e as Bs,f as sn,k as yt,l as rt,s as qs,u as Ws,v as Gs,z as wo}from"./chunk-WZQEK4WT.mjs";import{createHash as Td}from"node:crypto";import*as qn from"node:fs/promises";import*as Lr from"node:path";import*as kt from"node:fs/promises";import*as At from"node:path";var Er="platform-records.json",Go=class extends Error{constructor(e){let t=e.checks.filter(r=>!r.passed).map(r=>`${r.name} (${r.violations.length} violation(s))`).join(", ");super(`Refusing to write the frozen dataset: non-reidentification control FAILED [${t}]. A FAIL means nothing is written or versioned.`),this.name="ControlNotPassedError"}},Bn=class{guard;constructor(e){this.guard=e??new fe}async write(e,t,r,n){if(!n.passed)throw new Go(n);let s=this.guard.assertOutsideRepo(e),i=this.guard.assertOutsideRepo(At.join(s,"data"));await kt.mkdir(i,{recursive:!0});for(let l of await kt.readdir(i))l.endsWith(".json")&&await kt.rm(this.guard.assertOutsideRepo(At.join(i,l)));let d=[],a=async(l,c)=>{let f=this.guard.assertOutsideRepo(l);await kt.writeFile(f,`${JSON.stringify(c)}
8
- `,"utf8"),d.push(f)},u=this.guard.assertOutsideRepo(At.join(s,"manifest.json"));await kt.writeFile(u,_n(r),"utf8"),d.push(u);for(let l of t.objects)await a(At.join(i,`${l.objectApiName}.json`),{objectApiName:l.objectApiName,records:l.records});return await a(At.join(s,"record-types.json"),t.recordTypes),await a(At.join(s,"personcontact-sidecar.json"),t.personContactSidecar),await a(At.join(s,Er),{...t.standardPricebook?{standardPricebook:t.standardPricebook}:{}}),{dir:s,files:d}}};var Uo="manifest.json",gl=["record-types.json","personcontact-sidecar.json",Er],Ko="data",hl="sha256:";async function Kf(o){let e=await Vo(Lr.join(o,Uo));if(e===void 0)throw new Error(`No frozen dataset at ${o}: it holds no ${Uo}.`);let t=[{name:Uo,content:yl(e)}];for(let n of gl){let s=await Vo(Lr.join(o,n));s!==void 0&&t.push({name:n,content:s})}for(let n of await ml(Lr.join(o,Ko))){let s=await Vo(Lr.join(o,Ko,n));s!==void 0&&t.push({name:`${Ko}/${n}`,content:s})}let r=Td("sha256");for(let{name:n,content:s}of t.sort((i,d)=>jd(i.name,d.name)))r.update(`${n}\0${Td("sha256").update(s).digest("hex")}
9
- `);return`${hl}${r.digest("hex")}`}async function ml(o){let e;try{e=await qn.readdir(o)}catch(t){if(t.code==="ENOENT")return[];throw t}return e.filter(t=>t.endsWith(".json"))}async function Vo(o){try{return await qn.readFile(o)}catch(e){if(e.code==="ENOENT")return;throw e}}function yl(o){let e;try{e=JSON.parse(o.toString("utf8"))}catch{return o}if(Yo(e)&&Yo(e.controls)){let t={...e.controls};delete t.dryRunLoad,e={...e,controls:t}}return Buffer.from(Ho(e),"utf8")}function Ho(o){return Array.isArray(o)?`[${o.map(Ho).join(",")}]`:Yo(o)?`{${Object.keys(o).sort(jd).map(t=>`${JSON.stringify(t)}:${Ho(o[t])}`).join(",")}}`:JSON.stringify(o)??"null"}function Yo(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function jd(o,e){return o===e?0:o<e?-1:1}var He=class extends Error{constructor(t,r,n={}){super(r);this.code=t;this.params=n;this.name="LoadGuardError"}code;params};function dr(o){return o.objects.reduce((e,t)=>e+t.records.length,0)}function Nr(o){return o.orgName??o.orgId}async function Fd(o){if(Jo(o),o.protectedOrgIds?.includes(o.orgId))throw new He("protected-environment",`Refusing frozen-dataset load on protected environment ${Nr(o)}: it is listed in the protectedOrgIds configuration. Remediation: pick an unprotected sandbox, or review the protected-environment configuration if this org was retired.`,{orgId:o.orgId});if(o.manifest&&o.manifest.source.orgId===o.orgId)throw new He("source-is-target",`Refusing frozen-dataset load on ${Nr(o)}: this org is the dataset SOURCE (manifest source.orgId). Loading would mix pseudonymized records with their origin. Remediation: target a fresh dev sandbox instead.`,{orgId:o.orgId});if(!await o.mockDetector.areCalloutsMocked(o.orgId))throw new He("unmocked-callouts",`Refusing frozen-dataset load on ${Nr(o)}: unmocked callouts detected. Records under load would trigger real external calls. Remediation: deploy the mock configuration to the TARGET org (e.g. the custom metadata flag read by CustomMetadataCalloutMockDetector), then retry \u2014 never edit data on the source org.`,{orgId:o.orgId});if(dr(o.dataset)===0)throw new He("empty-dataset","Refusing frozen-dataset load: the dataset contains zero records. Remediation: re-run the selection/extraction with a coverage matrix that matches the source data, then freeze a new dataset version.")}function Jo(o){if(!(o.orgTier==="staging"&&o.stagingReplay===!0)){if(o.orgTier==="staging")throw new He("non-sandbox",`Refusing frozen-dataset load on ${Nr(o)}: it is a sandbox marked Staging, which holds real data, and a load never goes into one. Remediation: pick another sandbox, or, if this one holds no real data, untick Staging in its Edit dialog on the Organizations page.`,{orgId:o.orgId,tier:o.orgTier});if(o.orgTier!=="development"&&o.orgTier!=="scratch")throw new He("non-sandbox",`Refusing frozen-dataset load on ${o.orgTier} org ${Nr(o)}: loads go into sandboxes and Developer Edition orgs only. Remediation: target a Developer/Scratch sandbox or a Developer Edition org \u2014 deploy the required configuration THERE; never run DML against a shared or source org.`,{orgId:o.orgId,tier:o.orgTier})}}var Cr=class{constructor(e,t){this.orgAccess=e;this.config=t}orgAccess;config;async areCalloutsMocked(e){let t=`SELECT Id FROM ${me(this.config.metadataTypeApiName)} WHERE ${me(this.config.isMockedFieldApiName)} = true LIMIT 1`;try{return(await this.orgAccess.query(e,t)).length>0}catch{return!1}}};var Wn=class{constructor(e){this.orgAccess=e}orgAccess;uiApiCache=new Map;async alignObject(e){let t=new Map(e.describe.fields.map(d=>[d.name,d])),r=new Map,n=[],s=[],i=[];for(let d of e.records){let a={},u=e.accountKindOf?.(d.referenceId);for(let[l,c]of Object.entries(d.fields)){if(u!==void 0&&fn(Ve,l,u))continue;let f=t.get(l);if(!f){this.countRemoval(r,l,"not-in-target");continue}if(!f.createable){this.countRemoval(r,l,"not-createable");continue}if(e.leaveOutEncrypted===!0&&f.type===Xi){c!=null&&c!==""&&this.countRemoval(r,l,"may-hold-masks");continue}let p=c;typeof p=="string"&&p!==""&&f.restrictedPicklist===!0&&(f.type==="picklist"||f.type==="multipicklist")&&(p=await this.alignPicklistValue(e,f.name,f.type,d,p,n,s)),a[l]=p}i.push(a)}return{objectApiName:e.objectApiName,alignedRecords:i,removals:[...r.entries()].map(([d,a])=>({objectApiName:e.objectApiName,field:d,reason:a.reason,affectedRecords:a.count})),adjustments:n,missingRequired:this.detectMissingRequired(e,i),uiApiWarnings:s}}detectMissingRequired(e,t){let r=t.filter((a,u)=>!e.linked?.has(e.records[u].referenceId));if(r.length===0)return[];let n=[],s=e.accountKindOf,i=s?e.records.filter(a=>!e.linked?.has(a.referenceId)).map(a=>s(a.referenceId)):[];for(let a of e.describe.fields){let u=s?pn(Ve,a.name):void 0;if(!a.createable||a.nillable&&u===void 0||a.defaultedOnCreate)continue;let l=r.filter((f,p)=>u===void 0||nr(u,i[p]));if(l.length===0)continue;if(!l.some(f=>{let p=f[a.name];return p!=null&&p!==""})){let f=a.unique?"unique":a.nameField?"name":void 0,p=(a.referenceTo?.length??0)>0,g=(a.picklistValues??[]).filter(h=>h.active).map(h=>h.value);n.push({objectApiName:e.objectApiName,field:a.name,isLookup:p,referenceTo:a.referenceTo??[],...f?{distinct:f}:{},...u?{accountKind:u}:{},...!p&&a.type?{fieldType:a.type}:{},...!p&&g.length>0?{activeValues:g}:{}})}}let d=un(e.objectApiName,a=>e.describe.fields.some(u=>u.name===a&&u.createable),a=>r.some(u=>u[a]!==void 0&&u[a]!==null&&u[a]!==""));if(d!==void 0&&!n.some(a=>a.field===d)){let a=e.describe.fields.find(u=>u.name===d)?.type;n.push({objectApiName:e.objectApiName,field:d,isLookup:!1,referenceTo:[],...a?{fieldType:a}:{}})}return n}async alignPicklistValue(e,t,r,n,s,i,d){let a=r==="multipicklist",u=a?s.split(";"):[s],l=e.describe.fields.find(w=>w.name===t),c=new Set((l?.picklistValues??[]).filter(w=>w.active).map(w=>w.value)),f=u.filter(w=>!c.has(w));if(f.length>0){let w=e.ruleFor(e.objectApiName,t);return i.push({objectApiName:e.objectApiName,field:t,referenceId:n.referenceId,value:s,rule:w,scope:"global"}),this.applyRule(w,u,f,a)}let p=e.resolvedRecordTypes.get(n.referenceId);if(!p)return s;let g=await this.uiApiValues(e,p,t,d);if(g===null)return s;let h=u.filter(w=>!g.includes(w));if(h.length===0)return s;let m=e.ruleFor(e.objectApiName,t);return i.push({objectApiName:e.objectApiName,field:t,referenceId:n.referenceId,value:s,rule:m,scope:"record-type"}),this.applyRule(m,u,h,a)}async uiApiValues(e,t,r,n){let s=`${e.orgId}|${e.objectApiName}|${t}|${r}`,i=this.uiApiCache.get(s);if(i!==void 0)return i;try{let d=await this.orgAccess.picklistValues(e.orgId,e.objectApiName,t,r);return this.uiApiCache.set(s,d),d}catch(d){return this.uiApiCache.set(s,null),n.push(`UI API picklist-values read failed for ${e.objectApiName}.${r} (recordType ${t}): ${d instanceof Error?d.message:String(d)}. Record-type assignment gap check skipped for this field.`),null}}applyRule(e,t,r,n){return e.action==="replace"?e.value:n?t.filter(s=>!r.includes(s)).join(";"):""}countRemoval(e,t,r){let n=e.get(t);n?n.count++:e.set(t,{reason:r,count:1})}};function wl(o){return o.slice(0,15)}var Gn=class{met=new Map;updated(e,t){let r=t.filter(n=>n.lockResends!==void 0);r.length>0&&this.of(e,"update").updates.push(...r)}deleted(e,t,r){let n=this.met.get(Ed(e,"delete"))?.deletes;r.forEach((s,i)=>{let d=t[i];if(d===void 0)return;let a=wl(d);s.lockResends===void 0&&!n?.has(a)||this.of(e,"delete").deletes.set(a,{id:d,outcome:s})})}list(e){return[...this.met.values()].map(({objectApiName:t,write:r,updates:n,deletes:s})=>{let i=r==="update"?n.map(u=>({outcome:u,taken:u.success})):[...s.values()].map(({id:u,outcome:l})=>({outcome:l,taken:e(t,u)})),d=0,a=0;for(let{outcome:u,taken:l}of i)l?d++:In(u.errors,u.errorDetails)&&a++;return{objectApiName:t,write:r,rows:i.length,written:d,stillLocked:a}})}of(e,t){let r=Ed(e,t),n=this.met.get(r);return n||(n={objectApiName:e,write:t,updates:[],deletes:new Map},this.met.set(r,n)),n}};function Ed(o,e){return`${e}:${o}`}var zr="Opportunity",Mr="SyncedQuoteId",bl="OpportunityLineItem",Xo="QuoteLineItem";function Zo(o,e){let t=(d,a)=>{let u=new Map;for(let{referenceId:l,fields:c}of o.get(d)??[]){let f=c[a];typeof f!="string"||f===""||!e(l)||u.set(f,(u.get(f)??0)+1)}return u},r=t(bl,"OpportunityId"),n=t(Xo,"QuoteId"),s=new Set((o.get("Quote")??[]).map(d=>d.referenceId)),i=[];for(let{referenceId:d,fields:a}of o.get(zr)??[]){let u=a[Mr];if(typeof u!="string"||!s.has(u)||!e(d)||!e(u))continue;let l=r.get(d)??0,c=n.get(u)??0;l>c&&i.push({opportunity:d,quote:u,products:l,lines:c})}return i}function Ld(o,e,t=!1){if(o.length===0)return;let r=o.length===1,n=o.reduce((l,c)=>l+c.products,0),s=o.reduce((l,c)=>l+c.lines,0),i=r?"its":"their",d=r?"the quote's":"the quotes'",a=s===0?`none of ${d} lines`:`${s} of ${d} lines`,u=e&&s===0?", which excludedObjects leaves out":"";return{objectApiName:zr,count:o.length,note:`${o.length} ${t?"would be ":""}left unsynced with ${i} quote: the load ${t?"would write":"wrote"} ${n} of ${i} products and ${a}${u} \u2014 synced, the platform replaces an opportunity's products with its quote's lines; ${Mr} left empty, the products kept`}}var et=class extends Error{constructor(t,r,n){super(t);this.gaps=r;this.recordTypesUntold=n;this.name="LoadConfigError"}gaps;recordTypesUntold;refusedBeside},xr=class extends Error{constructor(e){super(e),this.name="LoadRecordsExceededError"}},cr=class extends Error{constructor(t){let r=t.reduce((n,s)=>n+s.count,0);super(`This reload finds in the target ${r} record(s) that its purge would delete along with what the loads before it created \u2014 ${t.map(n=>`${n.objectApiName} (${n.count}, under ${n.under.join(", ")})`).join("; ")}: the target deletes them with the record they hang from, which the reload does not find again, and the load would then write against records no longer there. Nothing was written. Give the records they hang from identity keys too, so that the reload finds them again, or take the load back first with a removal, then load the dataset again.`);this.found=t;this.name="ReloadTakesAlongError"}found};function Rl(o){return o.perObject.reduce((e,t)=>e+t.toInsert,0)}function kl(o,e){if(!(e===void 0||o<=e))return`This load would insert ${o} record(s), more than the ${e} it may: nothing was written. The dataset or the target changed since that count was taken: preview the load again, and load with the count it gives.`}var st=class extends Error{constructor(t,r=!0){super(r?`The load was cancelled ${Ud(t,void 0)}`:"The load was cancelled before it created or purged a record: the mapping is left as it was.");this.written=t;this.name="FrozenLoadCancelledError"}written},Bt=class extends Error{constructor(t,r,n){super(Il(t,r,n),{cause:t});this.written=r;this.name="FrozenLoadFailedError",this.mappingKept=n===void 0}written;mappingKept};function Il(o,e,t){return`${Q(o)}
10
- The load failed ${Ud(e,t)}`}function Ud(o,e){let t=new Map,r=(a,u)=>{u!==0&&t.set(a,(t.get(a)??0)+u)};for(let a of o.placeholders)r(a.placeholderObjectApiName,1);for(let a of o.perObject)r(a.objectApiName,a.inserted);let n=[...t.values()].reduce((a,u)=>a+u,0),s=[...Object.values(o.purge.deleted),...Object.values(o.purge.deactivated)].reduce((a,u)=>a+u,0),i=[...n>0?[`created ${n} record(s) (`+[...t].map(([a,u])=>`${a}: ${u}`).join(", ")+")"]:[],...s>0?[`purged ${s} record(s) that earlier loads created`]:[]].join(" and "),d;return e!==void 0?d=n>0?`The mapping could not be written, and nothing names what it created \u2014 no removal or reload will find it: ${e}`:`The mapping could not be written: ${e}`:d=n>0?"What it created is kept in the mapping: a removal takes it back, and a reload purges it or finds it again.":"What the earlier loads created and it did not purge is still named in the mapping, for a removal or the next reload.",i===""?`before it had written the whole dataset. ${d}`:`after it had ${i}. ${d}`}function Kd(o,e){let t=[];for(let[r,n]of o.givenRules){let s=[],i={};for(let{referenceId:a,fields:u}of o.alignedByObject.get(r)??[]){if(!gt(u.RecordTypeId)||!e(a))continue;s.push(a);let l=o.withoutRecordType.get(a)??"notRead";i[l]=(i[l]??0)+1}if(s.length===0)continue;let{predicted:d}=n;t.push({given:{objectApiName:r,rows:s.length,why:i,...d?{predicted:d}:{}},rule:n,keys:s})}return t}function Vd(o){return{namespacePrefix:o.namespacePrefix,developerName:o.developerName}}function vl(o){if(!o)return"the user's default record type applies";if(o.kind==="master")return"the target leaves it on Master for that user";let{developerName:e}=o.info;return o.basis==="userDefault"?`the target gives it ${e}, the user's default record type`:`the target gives it ${e}, the only other record type open to the user`}async function Ol(o,e){if(!e.mappingKept())try{await e.keepMapping()}catch(t){return new Bt(o,e.written,Q(t))}return new Bt(o,e.written)}function Hd(o,e,t){let r=t.map(n=>ct(n.namespacePrefix,n.developerName));return new et(`The dataset's ${o} records name record type "${e}" by its label, which ${r.join(" and ")} share in the source: which one each record had cannot be told, the dataset having been extracted before SandForge kept each record's record type by its name. Extract the dataset again. Nothing was written.`,void 0,{reason:"label",objectApiName:o,name:e,recordTypes:r})}function Sl(o){for(let{objectApiName:e,records:t}of o.objects){let r=o.recordTypes[e]??[];if(!(r.length<2))for(let n of t){let s=n.fields.RecordTypeId;if(typeof s!="string"||s==="")continue;if(n.recordTypeDeveloperName!==void 0){let d=So(n.recordTypeDeveloperName,r,Vd);if(d&&"found"in d)continue}let i=r.filter(d=>d.name===s);if(i.length>1)return Hd(e,s,i)}}}var Yd="Opportunity",Kn="placeholder:",es=class{byObject=new Map;auditDated=new Set;add(e,t,r=!1){let n=this.byObject.get(e)??[];n.push(t),this.byObject.set(e,n),r&&this.auditDated.add(e)}sentAuditDates(e){return this.auditDated.has(e)}list(e=[]){let t=new Map,r=(n,s)=>{t.set(n,[...t.get(n)??[],...s])};for(let{objectApiName:n,referenceIds:s}of e)r(n,s);for(let[n,s]of this.byObject)r(n,s);return[...t].map(([n,s])=>({objectApiName:n,referenceIds:s}))}};function Al(o){if(o.startsWith(Kn))return o.split(":")[1]??"Unknown";let e=o.lastIndexOf("-");return e>0?o.slice(0,e):"Unknown"}function Pl(o){return typeof o=="number"?String(o):typeof o=="boolean"?o?"TRUE":"FALSE":`'${$e(String(o))}'`}var Pt=200;function ie(o){return o.slice(0,15)}var Tl=["CreatedDate","LastModifiedDate"],jl=[["CreatedDate","LastModifiedDate","SystemModstamp"],["SystemModstamp"]];function _t(o){return typeof o=="string"?Date.parse(o):Number.NaN}function Nd(o){return o.success||o.errors.some(e=>e.includes("ENTITY_IS_DELETED"))}function Cd(o){if(o.tried===0)return"";let e=o.tried-o.went,t=[o.went>0?`${o.went} went`:"",e>0?`${e} refused again`:""].filter(Boolean);return` \u2014 ${o.tried} refused at first, sent again once the rest had gone: ${t.join(", ")}`}function zd(o,e,t){let r=`Status set to ${e.draft} for the purge, and left there: ${e.status} could not be given back \u2014 ${t}`,n=o.failures.find(s=>s.objectApiName===e.objectApiName&&ie(s.recordId)===ie(e.id));n?n.errors=[...n.errors,r]:o.failures.push({objectApiName:e.objectApiName,recordId:e.id,errors:[r]})}function Qo(o,e){let t=(o.notInserted??0)+(e.notInserted??0),r=[o.writtenWithoutFields,e.writtenWithoutFields].reduce((s,i)=>i?Lo(s,i):s,void 0),n=[o.sentAgainForALock,e.sentAgainForALock].reduce((s,i)=>i?{rows:(s?.rows??0)+i.rows,written:(s?.written??0)+i.written,stillLocked:(s?.stillLocked??0)+i.stillLocked}:s,void 0);return{objectApiName:e.objectApiName,fromFiles:o.fromFiles+e.fromFiles,inserted:o.inserted+e.inserted,reused:o.reused+e.reused,skippedDuplicates:[...o.skippedDuplicates,...e.skippedDuplicates],failed:[...o.failed,...e.failed],...r?{writtenWithoutFields:r}:{},...t>0?{notInserted:t}:{},...n?{sentAgainForALock:n}:{}}}function Fl(o){if(o.size===0)return;let e=0,t=0;for(let r of o.values())r.success?e++:In(r.errors,r.errorDetails)&&t++;return{rows:o.size,written:e,stillLocked:t}}function Md(o){let e=o.filter(r=>r.replacedWith===void 0).map(r=>r.field),t=o.filter(r=>r.replacedWith!==void 0).map(r=>`${r.field} set to "${r.replacedWith}"`);return[...e.length>0?[`without ${e.join(", ")}`]:[],...t.length>0?[`with ${t.join(", ")}`]:[]].join(" and ")}function Vn(o,e="inserted"){return o>0?`, ${o} not ${e}: the load was cancelled first`:""}function ts(o,e="inserted"){return o>0?`, ${o} not ${e}: the load failed`:""}function El(o,e){return o>0?"error":e>0?"stopped":"done"}function pt(o,e,t,r){return{phase:o,status:"error",progress:e,message:`${t} \u2014 ${Q(r)}`}}var Dd={phase:"guards",status:"started",progress:0,message:"Running the safety checks"};function Un(o,e){let{phase:t,progress:r,did:n,refused:s,notDone:i,done:d,notes:a=""}=o;return e?{phase:t,status:"error",progress:r,message:`${n}${ts(i,d)}${a} \u2014 ${Q(e.cause)}`}:{phase:t,status:El(s,i),progress:r,message:`${n}${Vn(i,d)}${a}`}}var Dr={accountNotInDataset:"its person account is not in the dataset",accountNotLoaded:"person account was not loaded (see perObject failures/skips)",noPersonAccounts:"the target org has no person accounts: it holds the account as a business account, which takes the contact as one of its own",businessAccount:"the target holds the account as a business account, which takes the contact as one of its own"};function Ll(o){return o.accountReferenceId===""?"Not written: a person account's contact goes in with its account, which the dataset does not hold":"Not written: a person account's contact goes in with its account, which the load did not write"}function Jd(o,e){let t=new Map;for(let{accountReferenceId:r,contactReferenceId:n}of o.personContactSidecar??[])e.get(n)===We&&t.set(n,r);for(let r of o.objects.find(n=>n.objectApiName===We)?.records??[]){if(t.has(r.referenceId)||!Ir(r.fields))continue;let n=r.fields.AccountId;t.set(r.referenceId,typeof n=="string"&&e.get(n)===Ve?n:"")}return t}function Nl(o){let e=new Set;for(let{accountReferenceId:t}of o.personContactSidecar??[])t!==""&&e.add(t);for(let t of o.objects.find(r=>r.objectApiName===Ve)?.records??[]){let r=t.fields.LastName;(Ir(t.fields)||r!=null)&&e.add(t.referenceId)}return e}function Hn(o,e,t){let r=o.accountKind;return r===void 0?[...e]:e.filter(n=>nr(r,t(n.referenceId)))}var $r=class{constructor(e){this.deps=e;this.config=e.config??{},this.sasGuard=e.sasGuard??new fe}deps;config;sasGuard;journal;lockResent;async gateLoad(e){try{await this.passEntryGuards(e)}catch(s){throw e.onProgress?.(Dd),e.onProgress?.(pt("guards",2,"Safety checks not passed",s)),s}let t=e.dataset;if(e.pilot)try{t=this.filterPilotScope(e.dataset,e.pilot.rootReferenceId)}catch(s){throw e.onProgress?.({phase:"pilot",status:"started",progress:3,message:"Selecting the root folder"}),e.onProgress?.(pt("pilot",4,"Root folder not selected",s)),s}let r=Sl(t);if(r)throw e.onProgress?.({phase:"align",status:"started",progress:12,message:"Resolving record types"}),e.onProgress?.(pt("align",20,"Schema not aligned",r)),r;let n=e.reload===!0&&!e.pilot;return this.consultGuard(e,{orgId:e.orgId,orgTier:e.orgTier,operation:n?"delete":"insert",objectName:e.dataset.objects.filter(s=>s.records.length>0).map(s=>s.objectApiName).join(", "),recordCount:{atMost:dr(e.dataset)},module:"frozendataset"})}passEntryGuards(e){return Fd({orgId:e.orgId,...e.orgName!==void 0?{orgName:e.orgName}:{},orgTier:e.orgTier,...e.stagingReplay?{stagingReplay:!0}:{},dataset:e.dataset,manifest:e.manifest,mockDetector:this.deps.mockDetector,protectedOrgIds:this.config.protectedOrgIds})}async load(e){let t={};try{return await this.loadKeeping(e,t)}finally{await this.journal?.close().catch(()=>{}),this.journal=void 0,this.lockResent=void 0}}async loadKeeping(e,t){try{return await this.loadInto(e,t)}catch(r){t.endOpenLine?.(r);let n=t.load;throw r instanceof st||!n?.wroteSome()?r:await Ol(r,n)}}async planLoad(e){let t=e.now??(()=>new Date),r=d=>e.onProgress?.(d),n=await this.prepare(e,r,{}),s=e.reload&&!e.pilot?await this.planPurge(e.orgId,n.previousLoads,n.mapping):void 0;if(s){let d=await this.foundUnderThePurge(e.orgId,s.residuals,n.mapping,n.refIndex);if(d.length>0)throw new cr(d)}let i=$d(n,s,{orgId:e.orgId,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},plannedAt:t().toISOString(),undeletableObjects:this.config.undeletableObjects??{},requiredFieldDefaults:this.config.requiredFieldDefaults??{},excludedObjects:this.config.excludedObjects??[]});return this.withValidationRules(i)}async withValidationRules(e){let t=this.deps.readValidationRules,r=e.perObject.filter(a=>a.toInsert>0).map(a=>a.objectApiName),n=[...new Set([...r,...e.placeholders.map(a=>a.placeholderObjectApiName)])];if(!t||n.length===0)return e;let s=new Map,i=new Map;try{for(let{objectApiName:a,onChangeOnly:u,...l}of await t(n))u?i.set(a,[...i.get(a)??[],l.name]):s.set(a,[...s.get(a)??[],l])}catch(a){return{...e,validationRulesUnread:Q(a)}}let d=new Set(r);return{...e,perObject:e.perObject.map(a=>{if(a.toInsert===0)return a;let u=s.get(a.objectApiName)??[],l=i.get(a.objectApiName)??[];return{...a,...u.length>0?{validationRules:u}:{},...l.length>0?{validationRulesOnChange:l}:{}}}),placeholders:e.placeholders.map(a=>{let u=d.has(a.placeholderObjectApiName)?[]:s.get(a.placeholderObjectApiName)??[];return u.length>0?{...a,validationRules:u}:a})}}async prepare(e,t,r){let{orgId:n}=e;t(Dd);try{await this.passEntryGuards(e)}catch(_){throw t(pt("guards",2,"Safety checks not passed",_)),_}t({phase:"guards",status:"done",progress:2,message:"Safety checks passed"}),t({phase:"mapping",status:"started",progress:2,message:"Reading the mapping of earlier loads"});let s=await this.deps.mappingStore.previousLoads().catch(_=>{throw t(pt("mapping",3,"Mapping not read",_)),_});t({phase:"mapping",status:"done",progress:3,message:`Mapping read: ${s.length} earlier load(s)`});let i=e.dataset;if(e.pilot){t({phase:"pilot",status:"started",progress:3,message:"Selecting the root folder"});try{i=this.filterPilotScope(e.dataset,e.pilot.rootReferenceId)}catch(U){throw t(pt("pilot",4,"Root folder not selected",U)),U}let _=i.objects.reduce((U,de)=>U+de.records.length,0);t({phase:"pilot",status:"done",progress:4,message:`Root folder selected: ${_} record(s)`})}let d=os(i),a=Dl(e.dataset),u=Jd(i,d),l=Gl(i,d,u),c=Qs(l),f=c.flat(),p=new rr,g=new rr(Wl),h={...i,objects:i.objects.map(_=>({..._,records:_.records.filter(U=>!p.leaveOut(_.objectApiName,U.referenceId,ri(_.objectApiName,U.fields,typeof U.fields.RelationId=="string"?d.get(U.fields.RelationId):void 0))&&!g.leaveOut(_.objectApiName,U.referenceId,U.fields))}))},m=new Map,w=new Set,R=new Set;if(e.reload||e.linkByKeys){t({phase:"reload",status:"started",progress:5,message:"Reusing reference data"}),r.endOpenLine=_=>t(pt("reload",10,"Reference data not reused",_)),await this.reuseByIdentityKeys(e,h,m,w);for(let _ of w)R.add(_);t({phase:"reload",status:"done",progress:10,message:`Reference data: ${w.size} reused`}),r.endOpenLine=void 0}if(h.standardPricebook||qd(h).length>0){t({phase:"catalog",status:"started",progress:10,message:"Looking up the catalog the target already holds"});let _;try{_=await this.lookUpTheCatalog(n,h,m,w)}catch(U){throw t(pt("catalog",11,"Catalog not looked up",U)),U}t({phase:"catalog",status:"done",progress:11,message:`Catalog looked up: ${_.join("; ")}`})}t({phase:"align",status:"started",progress:12,message:"Resolving record types"}),r.endOpenLine=_=>t(pt("align",20,"Schema not aligned",_));let P=[],j=new Map,T=new Map,$=new Map;for(let _ of h.objects){let U=[];for(let de of _.records)U.push(await this.resolveRecordType(e,i,_.objectApiName,de,T,P,$));j.set(_.objectApiName,U)}let q=new Wn(this.deps.orgAccess),C={objectResults:[],excludedObjects:[],removals:[],adjustments:[],recordTypeIssues:P},I=new Map,b=new Map,O=new Map,F=new Map,v=new Map,A,N=Nl(i),M=_=>N.has(_)?A===!1?"personAsBusiness":"person":"business",B=new Map,D=new Map,G=e.writeEncrypted!==!0&&e.manifest?.coverage?.encryptedNotKept===void 0;for(let _ of h.objects){let U=_.objectApiName;if(_.records.length===0)continue;let de=_.records.filter(S=>!w.has(S.referenceId)),X=(S,J,ne)=>{C.excludedObjects.push({objectApiName:U,reason:S,cause:ne}),v.set(U,{objectApiName:U,fromFiles:i.objects.find(Z=>Z.objectApiName===U)?.records.length??_.records.length,inserted:0,reused:_.records.length-de.length,skippedDuplicates:[],failed:de.map(Z=>({objectApiName:U,referenceId:Z.referenceId,errors:[J]}))}),de.length!==0&&t({phase:"align",objectName:U,status:"error",progress:12,message:`Skipped ${U} \u2014 ${S}`})},pe;try{pe=await this.deps.orgAccess.describe(n,U)}catch(S){let J=`Not present in target org: ${S instanceof Error?S.message:String(S)}. Deploy it to the target, or give the loading user Read on it, then load again; or leave it out of the configuration (excludedObjects) and extract again`;X(J,J,"notInTarget");continue}if(U===Ve&&(A=pe.fields.some(S=>S.name===mn)),pe.createable===!1&&de.length>0){X(`Not createable in target org: ${de.length} record${de.length===1?"":"s"} of the dataset not loaded. Give the loading user Create on it in a permission set, where the platform lets a user create it; otherwise leave it out of the configuration (excludedObjects) and extract again`,"Not createable in target org: the running user may not insert it","notCreateable");continue}O.set(U,new Set(pe.fields.filter(S=>S.updateable===!1).map(S=>S.name)));let Be=pe.fields.filter(S=>S.lookupFilter!==void 0&&S.createable&&(S.referenceTo?.length??0)>0).map(S=>({field:S.name,referenceTo:[...S.referenceTo??[]]}));Be.length>0&&F.set(U,Be);let Ne=Rn(pe.recordTypeInfos);if(Ne.some(S=>!S.master)){let S=Ya(Nn(Ne));D.set(U,{types:Ne,...S?{predicted:S}:{}})}let k=_l(U,pe,this.config);k.length>0&&B.set(U,k),b.set(U,new Set(pe.fields.filter(S=>S.createable&&!S.nillable&&!S.defaultedOnCreate&&(S.referenceTo?.length??0)>0).map(S=>S.name)));let E=await q.alignObject({orgId:n,objectApiName:U,records:j.get(U)??[],describe:pe,resolvedRecordTypes:T,ruleFor:(S,J)=>this.picklistRuleFor(S,J),linked:w,...U===Ve?{accountKindOf:M}:{},...G?{leaveOutEncrypted:G}:{}});C.objectResults.push(E),C.removals.push(...E.removals),C.adjustments.push(...E.adjustments),I.set(U,E.alignedRecords.map((S,J)=>({referenceId:(j.get(U)??[])[J].referenceId,fields:S})))}let V=await this.linkWhatThePlatformKeeps(n,C.objectResults,I,a,m,w,M),L=e.reload||e.linkByKeys?await this.reuseByKeysAsWritten(n,h,C.objectResults,I,a,m,w,M):{linked:[],said:[],leftEmpty:[]};for(let _ of[...V.linked,...L.linked])R.add(_);let H=[...V.said,...L.said];t({phase:"align",status:"done",progress:20,message:`Schema aligned${H.length>0?` \u2014 ${H.join("; ")}`:""}`}),r.endOpenLine=void 0;let K=new rr(Bl(B));$l(I,b,[p,g,K]);for(let _ of C.objectResults){let U=(I.get(_.objectApiName)??[]).filter(de=>!w.has(de.referenceId));_.missingRequired=_.missingRequired.filter(de=>Hn(de,U,M).some(X=>gt(X.fields[de.field])))}t({phase:"placeholders",status:"started",progress:22,message:"Checking required fields"});let re=await this.planRequiredFields(e,C.objectResults).catch(_=>{throw t(pt("placeholders",22,"Required fields not covered",_)),_});return t({phase:"placeholders",status:"done",progress:22,message:"Required fields checked"}),{previousLoads:s,working:i,refIndex:d,personContacts:u,groups:c,groupOrder:f,leftToThePlatform:p,untypedFeedItems:g,heldForExclusions:K,loading:h,mapping:m,reused:w,reusedByKeys:R,ranks:a,recordTypeIssues:P,alignment:C,alignedByObject:I,requiredLookups:b,fixedAtInsert:O,filteredLookups:F,lostObjects:v,targetHasPersonAccounts:A,accountKindOf:M,plans:re,givenRules:D,withoutRecordType:$,keysLeftEmpty:[...V.leftEmpty,...L.leftEmpty]}}async loadInto(e,t){let r=e.now??(()=>new Date),n=r(),s=y=>e.onProgress?.(y),{orgId:i}=e;this.journal=this.deps.mappingStore.journal?.(n);let d=new Gn;this.lockResent=d;let a=await this.prepare(e,s,t),{previousLoads:u,working:l,refIndex:c,personContacts:f,groups:p,groupOrder:g,leftToThePlatform:h,untypedFeedItems:m,heldForExclusions:w,mapping:R,reused:P,ranks:j,recordTypeIssues:T,alignment:$,alignedByObject:q,requiredLookups:C,fixedAtInsert:I,lostObjects:b,targetHasPersonAccounts:O,accountKindOf:F,plans:v}=a,A=kl(Rl($d(a,void 0,{orgId:i,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},plannedAt:n.toISOString(),undeletableObjects:this.config.undeletableObjects??{},requiredFieldDefaults:this.config.requiredFieldDefaults??{},excludedObjects:this.config.excludedObjects??[]})),e.maxRecords);if(A)throw new xr(A);let N=await this.runUserIdOf(i);N&&this.journal?.writtenAs(N);let M={deleted:{},deactivated:{},failures:[]},B=[],D=[],G=new es,V=new Map,L=[],H=new Set,K,re=new Map,_=!1,U=async()=>{let y=await this.readWrittenBetween(i,G,R),x=K?.linked??new Map,Y=e.pilot?void 0:e.purgeSweep?.stillToSweep?.();await this.deps.mappingStore.persist(R,{created:G.list(L),startedAt:n,...y?{writtenBetween:y}:{},earlier:{settled:[...H],...Y&&Y.length>0?{stillToSweep:[...Y]}:{}},...x.size>0?{personContacts:Object.fromEntries(x)}:{},...re.size>0?{withTheirRecord:Object.fromEntries(re)}:{},...N?{runUserId:N}:{}}),_=!0},de=()=>G.list().length>0||Object.keys(M.deleted).length>0||Object.keys(M.deactivated).length>0,X=async()=>{if(!e.signal?.aborted)return;let y=de();throw y&&await U(),new st({perObject:D,placeholders:B,purge:M},y)};t.load={keepMapping:U,mappingKept:()=>_,wroteSome:de,written:{perObject:D,placeholders:B,purge:M}};let pe=[];if(e.reload){let y="",x={residuals:0},Y={tried:0,went:0},he=we=>{let Te=Fe=>Object.values(Fe).reduce((be,le)=>be+le,0);return Un({phase:"reload",progress:24,did:`Purge: ${Te(M.deleted)} deleted, ${Te(M.deactivated)} deactivated, ${M.failures.length} failed`,refused:M.failures.length,notDone:x.residuals,done:"purged",notes:`${Cd(Y)}${y}`},we)};if(!e.pilot){s({phase:"reload",status:"started",progress:23,message:"Purging what earlier loads created"});let we=await this.planPurge(i,u,R),Te=await this.foundUnderThePurge(i,we.residuals,R,c);if(Te.length>0){let le=new cr(Te);throw s(he({cause:le})),le}L=we.carried;for(let le of L.flatMap(oe=>oe.referenceIds)){let oe=R.get(le);oe&&H.add(ie(oe))}let Fe=Object.values(we.leftUnrecorded).reduce((le,oe)=>le+oe,0);Fe>0&&(M.leftUnrecorded=we.leftUnrecorded,y=` \u2014 ${Fe} record(s) left in place of a load recorded before loads kept what they created: it may have linked them`);let be=Object.entries(we.keptByThePlatform);be.length>0&&(M.keptByThePlatform=we.keptByThePlatform,y+=" \u2014 kept, the platform does not delete them: "+be.map(([le,oe])=>`${le} (${oe})`).join(", "));try{e.purgeSweep&&(await X(),await e.purgeSweep.first()),await this.purgeResiduals(e,we,[...g].reverse(),M,X,H,x,Y),e.purgeSweep&&!e.signal?.aborted&&await e.purgeSweep.afterPurge()}catch(le){throw s(he(le instanceof st?void 0:{cause:le})),le}for(let le of u)if(!le.created)for(let oe of le.mapping.values())H.add(ie(oe));s(x.residuals>0||M.failures.length>0?he():{phase:"reload",status:"done",progress:24,message:`Reload pass done${Cd(Y)}${y}`})}}let Be=y=>(q.get(y)??[]).filter(x=>!P.has(x.referenceId)),Ne=v.filter(y=>y.kind==="placeholder").length,k=y=>Un({phase:"placeholders",progress:25,did:`Placeholders: ${B.length} created`,refused:0,notDone:Ne-B.length,done:"created"},y);Ne>0&&(await X(),s({phase:"placeholders",status:"started",progress:24,message:"Creating placeholders"}));try{for(let y of v)y.kind==="placeholder"?(await X(),await this.createPlaceholder(e,y,Be(y.missing.objectApiName),R,B,G)):this.applyScalarDefault(y.missing,Hn(y.missing,Be(y.missing.objectApiName),F),pe,j)}catch(y){throw s(k(y instanceof st?void 0:{cause:y})),y}Ne>0&&s(k());let E=p.flatMap(y=>y.length>1?ei(y,Ul(q,C,c,f)):y),S=[],J=[],ne=this.config.duplicateErrorPatterns??yd,Z=new Set(E.includes(tr)?(q.get(tr)??[]).map(y=>y.referenceId):[]),ge=[],ee=null,Ie=0,z=!1,ve=y=>y===Ze&&ge.length>0?`, ${ge.length} on a case waiting for ${ge.length===1?"its task":"their tasks"}`:"",Ge=new Set,Ye=async()=>{if(K)return K;let y=await this.linkPersonContacts(i,f,R,P,O,T);for(let x of y.linked.keys())P.add(x);return Ge=new Set(y.unlinked.map(x=>x.contactReferenceId).filter(x=>!P.has(x))),K=y,y},W=y=>{if(y.objectApiName!==We||!K)return y;let x=K.unlinked.filter(Y=>Ge.has(Y.contactReferenceId));return x.length===0?y:{...y,failed:[...y.failed,...x.map(Y=>({objectApiName:We,referenceId:Y.contactReferenceId,errors:[Ll(Y)]}))]}},se=()=>{if(K)for(let[y,x]of K.own)R.has(y)||(K.own.delete(y),K.unlinked.push({accountReferenceId:x.accountReferenceId,contactReferenceId:y,cause:"target-not-loaded",detail:`contact ${y} was not loaded (skipped, failed or excluded)`}))},jt=()=>{let y=K?.linked.size??0,x=K?.own.size??0,Y=Ge.size;return[...y>0?[`${y} linked to the contact the platform wrote with ${y===1?"its":"their"} person account`]:[],...x>0?[`${x} sent as ${x===1?"a contact of its own":"contacts of their own"}: the target holds ${x===1?"its":"their"} account as a business account`]:[],...Y>0?[`${Y} not written: a person account's contact goes in with its account`]:[]]},ce=(y,x)=>[...y===We?jt():[],...x?[x]:[],...h.counts(y).map(({why:Y,count:he})=>ti(he,Y)),...m.counts(y).map(({why:Y,count:he})=>Bd(he,Y)),...w.counts(y).map(({why:Y,count:he})=>nc(he,Y))].map(Y=>`, ${Y}`).join(""),Ft=(y,x,Y,he,we)=>{let Te=D.findIndex(Xt=>Xt.objectApiName===y),Fe=Te>=0?D[Te]:void 0,be=Y.filter(Xt=>P.has(Xt.referenceId)).length,le=Fe?.inserted??0,oe=Fe?.skippedDuplicates??[],ze=Fe?.failed??[],dt=Fe?.writtenWithoutFields,ke=Fe?.sentAgainForALock,Jt=Y.length-be-le-oe.length-ze.length,mt=W({objectApiName:y,fromFiles:x,inserted:le,reused:be,skippedDuplicates:oe,failed:ze,...dt?{writtenWithoutFields:dt}:{},...Jt>0?{notInserted:Jt}:{},...ke?{sentAgainForALock:ke}:{}});Fe?D[Te]=mt:D.push(mt),s({phase:"insert",objectName:y,status:"error",progress:25+Math.round(55*Ie/Math.max(E.length,1)),message:`${y}: ${le} inserted, ${mt.reused} reused, ${oe.length} duplicates skipped, ${mt.failed.length} failed${ve(y)}${ts(Jt)}${Fn(dt)}${ce(y,he)} \u2014 ${Q(we)}`})},Ue,Pe=(y,x,Y)=>{if(y.waiting>0){let be=D.find(le=>le.objectApiName===Ze);be&&(be.notInserted=(be.notInserted??0)+y.waiting)}let he=x==="cancel"&&y.waiting>0,we="";he?we=Vn(y.waiting):y.waiting>0&&(we=ts(y.waiting));let Te=y.status;Y?Te="error":he&&y.status!=="error"&&(Te="stopped");let Fe=Y?` \u2014 ${Q(Y.cause)}`:"";s({phase:"insert",objectName:Ze,status:Te,progress:25+Math.round(55*Ie/Math.max(E.length,1)),message:`${y.message}${we}${y.notes}${Fe}`})},ye=async()=>{let y=ee;y&&e.signal?.aborted&&(ee=null,Pe(y,"cancel")),await X()};t.endOpenLine=y=>{let x=Ue;Ue=void 0,x&&!(y instanceof st)&&x(y);let Y=ee;ee=null,Y&&Pe(Y,y instanceof st?"cancel":"failure")};let Ce=async()=>{z=!0;let y=ge.splice(0,ge.length),x=ee;if(ee=null,y.length===0)return;let Y=25+Math.round(55*Ie/Math.max(E.length,1)),he;try{await X()}catch(oe){throw x&&Pe(x,oe instanceof st?"cancel":"failure"),oe}let we=oe=>`${oe.inserted} inserted, ${oe.reused} reused, ${oe.skippedDuplicates.length} duplicates skipped, ${oe.failed.length} failed${Vn(oe.notInserted??0)}${Fn(oe.writtenWithoutFields)}`,Te=oe=>{let ze=D.findIndex(dt=>dt.objectApiName===Ze);ze>=0?D[ze]=Qo(D[ze],oe):D.push(oe)},Fe={};try{he=await this.insertObject(e,Ze,0,y,c,R,P,S,ne,G,V,xd(D),oe=>{Fe.result=oe})}catch(oe){let ze=Fe.result;if(ze&&Te(ze),x&&ze){let dt=ze.inserted+ze.skippedDuplicates.length+ze.failed.length;Pe({...x,waiting:Math.max(x.waiting-dt,0),message:`${x.message}; after their task: ${we(ze)}`},"failure",{cause:oe})}else x&&Pe(x,"failure",{cause:oe});throw oe}Te(he);let be=we(he),le="done";he.failed.length>0||x?.status==="error"?le="error":(he.notInserted??0)>0&&(le="stopped"),s({phase:"insert",objectName:Ze,status:le,progress:Y,message:x?`${x.message}; after their task: ${be}${x.notes}`:`${Ze} after their task: ${be}`})};for(let y of E){await ye();let x=q.get(y);if(!x){let ue=b.get(y);if(ue&&y===We&&f.size>0){try{await Ye()}catch(Me){throw s({phase:"insert",objectName:y,status:"error",progress:25+Math.round(55*Ie/Math.max(E.length,1)),message:`${y}: person accounts' contacts not linked \u2014 ${Q(Me)}`}),Me}se();let Ee=K?.linked??new Map,Le=ue.failed.filter(Me=>!Ee.has(Me.referenceId));D.push({...ue,reused:ue.reused+ue.failed.length-Le.length,failed:Le})}else ue&&D.push(ue);continue}Ie++,s({phase:"insert",objectName:y,status:"started",progress:25+Math.round(55*Ie/Math.max(E.length,1)),message:`Inserting ${y}`});let Y,he=l.objects.find(ue=>ue.objectApiName===y)?.records.length??x.length,we=x;if(Ue=ue=>Ft(y,he,we,Y,ue),y===We&&f.size>0){let ue=await Ye();we=x.filter(Ee=>!Ge.has(Ee.referenceId));for(let Ee of we){let Le=ue.own.get(Ee.referenceId),Me=Ee.fields.AccountId;Le&&(Me==null||Me==="")&&(Ee.fields.AccountId=Le.accountReferenceId)}}y===kr&&await this.matchDirectRelations(i,l,x,R,P,re),y===tr&&await this.matchTasksWrittenWithEmails(i,l,x,R,P,re),ko[y]!==void 0&&(Y=await this.matchActivityRelations(e,y,x,R,P,I.get(y)??new Set));let Te=0;if(y===Dt){let ue=await this.matchContactRolesWrittenWithOpportunities(e,{working:l,aligned:x,refIndex:c,mapping:R,reused:P,withTheirRecord:re,pendingFk:S,fixedAtInsert:I.get(y)??new Set});Te=ue.linked,Y=ue.note}let Fe=xt[y],be=Fe?await this.startAsDrafts(i,y,Fe,we,J):we;if(y===Ze&&!z&&Z.size>0){let ue=Ee=>si(Ee,Le=>c.get(Le))&&Z.has(String(Ee.ActivityId));ge.push(...be.filter(Ee=>ue(Ee.fields))),be=be.filter(Ee=>!ue(Ee.fields))}let le=be.filter(ue=>!P.has(ue.referenceId)).length,oe=e.signal?.aborted===!0&&le>0,ze=(ue,Ee,Le=Me=>D.push(Me))=>this.insertObject(e,y,Ee,ue,c,R,P,S,ne,G,V,xd(D),Le),dt=l.standardPricebook,ke;if(oe)ke={objectApiName:y,fromFiles:he,inserted:0,reused:be.length-le,skippedDuplicates:[],failed:[],notInserted:le};else if(cn(y)&&dt){let ue=await ze(be.filter(Le=>Le.fields[wt]===dt),0),Ee=be.filter(Le=>Le.fields[wt]!==dt);if(e.signal?.aborted){let Le=Ee.filter(pl=>P.has(pl.referenceId)).length,Me={...ue,fromFiles:he,reused:ue.reused+Le},Zt=be.length-Me.inserted-Me.reused-Me.skippedDuplicates.length-Me.failed.length;ke={...Me,...Zt>0?{notInserted:Zt}:{}}}else{let Le={},Me=await ze(Ee,he,Zt=>{Le.result=Zt}).catch(Zt=>{throw D.push(Le.result?Qo(ue,Le.result):{...ue,fromFiles:he}),Zt});ke=Qo(ue,Me)}}else ke=await ze(be,he);Ue=void 0,y===We&&se(),ke=W(ke),Te>0&&(ke={...ke,writtenByThePlatform:Te});let Jt=y===Ze?ge.filter(ue=>!P.has(ue.referenceId)).length:0;(ke.notInserted??0)>0&&(ke.notInserted=(ke.notInserted??0)+Jt);let mt=ke.notInserted??0;D.push(ke);let Xt=ce(y,Y),xs=ve(y),mo=ke.failed.length>0,$s=mo?"error":"done";!mo&&mt>0&&($s="stopped");let _s=25+Math.round(55*Ie/Math.max(E.length,1)),yo=`${y}: ${ke.inserted} inserted, ${ke.reused} reused, ${ke.skippedDuplicates.length} duplicates skipped, ${ke.failed.length} failed${xs}${Vn(mt)}${Fn(ke.writtenWithoutFields)}`;xs&&mt===0?(ee={status:mo?"error":"done",message:yo,notes:Xt,waiting:Jt},s({phase:"insert",objectName:y,status:"started",progress:_s,message:yo})):s({phase:"insert",objectName:y,status:$s,progress:_s,message:`${yo}${Xt}`}),y===tr&&await Ce(),mt>0&&await ye()}await Ce(),await X(),s({phase:"pass2",status:"started",progress:82,message:"Patching cycle FKs"});let ht={report:{resolved:0,unresolved:[]},unanswered:0},It=Zo(q,y=>R.has(y)),go=new Set(It.map(y=>y.opportunity)),rn=S.filter(y=>y.objectApiName!==zr||y.field!==Mr||!go.has(y.referenceId)),yr=It.length>0?`, ${It.length} synced quote${It.length===1?"":"s"} left unset`:"",Je=y=>Un({phase:"pass2",progress:88,did:`Pass 2: ${ht.report.resolved} resolved, ${ht.report.unresolved.length} unresolved${yr}`,refused:ht.report.unresolved.length,notDone:ht.unanswered,done:"resolved"},y);try{await this.patchCycleFks(e,rn,R,ht)}catch(y){throw s(Je({cause:y})),y}s(Je());let Et=ht.report;await X();let ft={report:{restored:0,refused:[]},unanswered:0},ho=y=>Un({phase:"pass2",progress:89,did:`Statuses: ${ft.report.restored} applied, ${ft.report.refused.length} refused`,refused:ft.report.refused.length,notDone:ft.unanswered,done:"applied"},y);try{await this.applyDeferredStatuses(e,J,R,ft)}catch(y){throw s(ho({cause:y})),y}let Ke=ft.report;Ke.restored+Ke.refused.length+ft.unanswered>0&&s(ho()),await X();let at=await Ye(),nn={restored:at.linked.size,sent:[...at.own.values()],unresolved:at.unlinked};f.size>0&&s({phase:"personcontact",status:at.unlinked.length>0?"error":"done",progress:94,message:`Person contacts: ${at.linked.size} linked to the contact the platform wrote with their account, ${at.own.size} sent as contacts of their own, ${at.unlinked.length} not linked`}),await X(),await e.lease?.giveBack().catch(()=>{}),s({phase:"persist",status:"started",progress:96,message:"Persisting mapping and contract"}),await U();let vt=h.counts(),Lt=m.counts(),Nt=w.counts(),Vt=this.writeContract(e,l,D,B,{now:r,startedAt:n},new Set(b.keys()),[...vt.map(({objectApiName:y,count:x})=>({objectApiName:y,count:x,reason:"left-to-the-platform"})),...Lt.map(({objectApiName:y,count:x})=>({objectApiName:y,count:x,reason:"untyped-feed-item"})),...Nt.map(({objectApiName:y,count:x})=>({objectApiName:y,count:x,reason:"excluded-parent"}))],Ge.size,V,Et.unresolved.filter(y=>y.cause==="target-not-loaded"));s({phase:"persist",status:"done",progress:98,message:"Sas artifacts written"});let Ht=D.some(y=>y.failed.length>0)||Et.unresolved.length>0||nn.unresolved.length>0||Ke.refused.length>0||M.failures.length>0,on=new Set(G.list().flatMap(({referenceIds:y})=>y)),Yt=await this.readBackRecordTypes(i,Kd(a,y=>on.has(y)),R),wr=d.list((y,x)=>!M.failures.some(Y=>Y.objectApiName===y&&ie(Y.recordId)===ie(x))),br={status:Ht?"completed-with-errors":"completed",orgId:i,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},startedAt:n.toISOString(),durationMs:r().getTime()-n.getTime(),alignment:$,placeholders:B,requiredDefaults:pe,perObject:D,...wr.length>0?{sentAgainForALock:wr}:{},pass2:Et,personContact:nn,statuses:Ke,purge:M,...vt.length>0?{leftToThePlatform:$n(vt)}:{},...Lt.length>0?{untypedFeedItems:Lt.map(({objectApiName:y,why:x,count:Y})=>({objectApiName:y,count:Y,note:Bd(Y,x)}))}:{},...Nt.length>0?{heldForExcludedParents:oc(Nt)}:{},...rc(It,this.config),...Zd(a.keysLeftEmpty),...Yt.length>0?{recordTypesGiven:Yt}:{},...N?{runUserId:N}:{},mappingPath:this.deps.mappingStore.filePath,contractPath:Vt};return s({phase:"done",status:br.status==="completed"?"done":"error",progress:100,message:`Load ${br.status}`}),br}async checkGuard(e,t,r,n){await this.consultGuard(e,{orgId:e.orgId,orgTier:e.orgTier,operation:t,objectName:r,recordCount:n,module:"frozendataset"})}async consultGuard(e,t){let{check:r,decision:n}=await An(this.deps.guard,t);if(e.onGuardDecision?.(n),n==="refused"||n==="declined")throw new He("guard-refused",`Production guard refused ${t.operation} on ${t.objectName}: ${r.blockedReason??"confirmation declined"}`,{decision:n,...n==="refused"&&r.blockedReason!==void 0?{reason:r.blockedReason}:{}});return n}filterPilotScope(e,t){return ss(e,this.config.rootObjectApiName,t)}async reuseByIdentityKeys(e,t,r,n){for(let[s,i]of Object.entries(this.config.identityKeys??{})){let d=t.objects.find(a=>a.objectApiName===s)?.records??[];for(let[a,u]of await this.findByKeys(e.orgId,s,i,d))r.set(a,u),n.add(a)}}async findByKeys(e,t,r,n){let s=new Map,i=n.filter(l=>r.every(c=>!gt(l.fields[c])));if(i.length===0)return s;let d=["Id",...r].map(me).join(", "),a=new Map,u=100;for(let l=0;l<i.length;l+=u){let c=i.slice(l,l+u).map(p=>`(${r.map(g=>`${me(g)} = ${Pl(p.fields[g])}`).join(" AND ")})`).join(" OR "),f=`SELECT ${d} FROM ${me(t)} WHERE ${c}`;for(let p of await this.deps.orgAccess.query(e,f))typeof p.Id=="string"&&a.set(Wd(r.map(g=>p[g])),p.Id)}for(let l of i){let c=a.get(Wd(r.map(f=>l.fields[f])));c&&s.set(l.referenceId,c)}return s}async linkWhatThePlatformKeeps(e,t,r,n,s,i,d){let a={linked:[],said:[],leftEmpty:[]};for(let[u,l]of Object.entries(jr)){let c=this.config.identityKeys?.[u]??l,f=(r.get(u)??[]).filter(g=>!i.has(g.referenceId));if(f.length===0)continue;let p=await this.linkByKeysAsWritten(e,{objectApiName:u,keyFields:c,records:f,missingRequired:t.find(g=>g.objectApiName===u)?.missingRequired??[],ranks:n,accountKindOf:d},s,i,a);p>0&&a.said.push(`${u}: ${p} found by ${c.join(", ")}, which the platform does not delete`)}return a}async reuseByKeysAsWritten(e,t,r,n,s,i,d,a){let u={linked:[],said:[],leftEmpty:[]};for(let[l,c]of Object.entries(this.config.identityKeys??{})){if(Object.prototype.hasOwnProperty.call(jr,l))continue;let f=new Set((t.objects.find(h=>h.objectApiName===l)?.records??[]).filter(h=>c.some(m=>gt(h.fields[m]))).map(h=>h.referenceId)),p=(n.get(l)??[]).filter(h=>f.has(h.referenceId)&&!d.has(h.referenceId));if(p.length===0)continue;let g=await this.linkByKeysAsWritten(e,{objectApiName:l,keyFields:c,records:p,missingRequired:r.find(h=>h.objectApiName===l)?.missingRequired??[],ranks:s,accountKindOf:a},i,d,u);g>0&&u.said.push(`${l}: ${g} found by ${c.join(", ")}, as the load writes `+(g===1?"it":"them"))}return u}async linkByKeysAsWritten(e,t,r,n,s){let{objectApiName:i,keyFields:d}=t,a=Ml(t,this.config.requiredFieldDefaults??{}),u=a.flatMap(c=>{let f=d.filter(p=>gt(c.fields[p]));return f.length>0?[f]:[]});if(u.length>0){let c=d.filter(f=>u.some(p=>p.includes(f)));s.leftEmpty.push({objectApiName:i,fields:c,count:u.length}),s.said.push(`${i}: ${u.length} not looked up, ${c.join(", ")} left empty`)}let l=await this.findByKeys(e,i,d,a);for(let[c,f]of l)r.set(c,f),n.add(c),s.linked.push(c);return l.size}async lookUpTheCatalog(e,t,r,n){let s=[],i=t.standardPricebook;if(i){let[u]=await this.deps.orgAccess.query(e,Ct);typeof u?.Id=="string"?(r.set(i,u.Id),n.add(i),s.push("standard price book linked")):s.push("standard price book not found")}let d=await this.matchByNaturalKey(e,t,r,n),a=await this.matchSellingModelOptions(e,t,r,n);qd(t).includes(xe)&&d.push({objectApiName:xe,linked:a});for(let{objectApiName:u,linked:l,notAsked:c}of d)c===void 0&&s.push(`${u}: ${l} linked`);for(let{objectApiName:u,notAsked:l}of d)l!==void 0&&s.push(`${u} not looked up \u2014 ${l}`);return s}async matchByNaturalKey(e,t,r,n){let s=[];for(let[i,d]of Object.entries(hn)){let a=t.objects.find(f=>f.objectApiName===i)?.records??[];if(a.length===0)continue;let u=a.filter(f=>!r.has(f.referenceId)&&d.every(p=>f.fields[p]!==void 0&&f.fields[p]!=="")),l=[];if(u.length>0)try{l=await yi(f=>this.deps.orgAccess.query(e,f),i,d,u.map(f=>f.fields))}catch(f){s.push({objectApiName:i,linked:0,notAsked:Q(f)});continue}let c=0;u.forEach((f,p)=>{let g=l[p];g!==void 0&&(r.set(f.referenceId,g),n.add(f.referenceId),c++)}),s.push({objectApiName:i,linked:c})}return s}async matchSellingModelOptions(e,t,r,n){let s=[];for(let d of t.objects.find(a=>a.objectApiName===xe)?.records??[]){if(r.has(d.referenceId))continue;let a=d.fields[qe],u=d.fields[Xe],l=typeof a=="string"?r.get(a):void 0,c=typeof u=="string"?r.get(u):void 0;l===void 0||c===void 0||s.push({referenceId:d.referenceId,pair:{[qe]:l,[Xe]:c}})}if(s.length===0)return 0;let i=await mi(d=>this.deps.orgAccess.query(e,d),s.map(d=>d.pair));for(let[d,a]of i)r.set(s[d].referenceId,a),n.add(s[d].referenceId);return i.size}async planPurge(e,t,r){let n={residuals:new Map,datedBy:new Map,carried:[],leftUnrecorded:{},keptByThePlatform:{}},s=new Map;for(let[g,h]of r)s.has(ie(h))||s.set(ie(h),g);let i=new Set,d=(g,h)=>{n.residuals.set(g,[...n.residuals.get(g)??[],h])},a=(g,h)=>{let m=n.carried.at(-1);m?.objectApiName===g?m.referenceIds.push(h):n.carried.push({objectApiName:g,referenceIds:[h]})},u=g=>{n.leftUnrecorded[g]=(n.leftUnrecorded[g]??0)+1},l=[],c=t.some(g=>g.created&&!g.writtenBetween)?await this.targetClockAheadMs():Number.NaN,f=t.map(g=>{let h=new Set;if(!g.created)return h;let m=new Set(g.created.flatMap(w=>w.referenceIds));for(let[w,R]of g.mapping)m.has(w)||h.add(ie(R));return h}),p=new Set(f.flatMap(g=>[...g]));if(t.forEach((g,h)=>{if(!g.created){for(let[R,P]of g.mapping){let j=ie(P);if(s.has(j)||i.has(j))continue;i.add(j);let T=Al(R);this.mayHaveLinked(T,R)||p.has(j)?u(T):T==="Pricebook2"&&!R.startsWith(Kn)?l.push(P):d(T,P)}return}let m=g.writtenBetween?_t(g.writtenBetween.last):_t(g.endedAt)+c+Gi,w=new Map(Object.entries(g.removalStamps??{}).map(([R,P])=>[ie(R),_t(P)]));for(let{objectApiName:R,referenceIds:P}of g.created)for(let j of P){let T=g.mapping.get(j);if(T===void 0)continue;let $=ie(T);if(f[h].has($)||i.has($))continue;i.add($);let q=s.get($);if(q!==void 0){a(R,q);continue}if(this.keptByThePlatform(R)){n.keptByThePlatform[R]=(n.keptByThePlatform[R]??0)+1;continue}d(R,T);let C=[m,w.get($)??Number.NaN].filter(Number.isFinite);C.length>0&&n.datedBy.set($,Math.max(...C))}}),l.length>0){let g;try{let[h]=await this.deps.orgAccess.query(e,Ct);g=typeof h?.Id=="string"?ie(h.Id):""}catch{g=void 0}for(let h of l)g===void 0||ie(h)===g?u("Pricebook2"):d("Pricebook2",h)}return n}async targetClockAheadMs(){let e=this.deps.serverTime;if(!e)return Number.NaN;let t=Date.now();try{return _t(await e())-(t+Date.now())/2}catch{return Number.NaN}}async foundUnderThePurge(e,t,r,n){let s=new Set([...t.values()].flat().map(ie)),i=new Map;for(let[u,l]of r){let c=n.get(u);c===void 0||s.has(ie(l))||i.set(c,[...i.get(c)??[],l])}if(s.size===0||i.size===0)return[];let d=new Map,a=(u,l,c)=>{let f=d.get(u)??{keys:new Set,under:new Set};f.keys.add(ie(l)),f.under.add(c),d.set(u,f)};for(let u of t.keys()){let l;try{l=(await this.deps.orgAccess.describe(e,u)).cascadeChildren??[]}catch{continue}for(let{childSObject:c,field:f}of l){let p=i.get(c);if(!p)continue;let g;try{g=await this.readRecords(e,c,[f],p)}catch{for(let h of p)a(c,h,u);continue}for(let h of g){let m=h[f];typeof h.Id!="string"||typeof m!="string"||s.has(ie(m))&&a(c,h.Id,u)}}}return[...d].map(([u,{keys:l,under:c}])=>({objectApiName:u,count:l.size,under:[...c]}))}mayHaveLinked(e,t){return t.startsWith(Kn)?!1:e==="Unknown"||e===xe||Object.prototype.hasOwnProperty.call(hn,e)||Object.prototype.hasOwnProperty.call(jr,e)||Object.prototype.hasOwnProperty.call(this.config.identityKeys??{},e)}keptByThePlatform(e){return Object.prototype.hasOwnProperty.call(jr,e)&&this.config.undeletableObjects?.[e]===void 0}async purgeResiduals(e,t,r,n,s,i,d,a){let u=t.residuals,l=[],c=[...u.values()].reduce((j,T)=>j+T.length,0),f=0,p=()=>{d.residuals=c-f},g=async()=>{let j=l.splice(0);j.length>0&&await this.giveStatusesBack(e,j,n)},h=async()=>{e.signal?.aborted&&await g(),await s()},m=r.filter(j=>u.has(j)),w=[...u.keys()].filter(j=>!r.includes(j)).sort(),R=[...m,...w],P=new Set;try{P=await this.residualsInSight(e.orgId,u),await this.draftResiduals(e,t,l,h);for(let j of R){let T=u.get(j)??[],$=this.config.undeletableObjects?.[j];if($!==void 0){await h(),await this.checkGuard(e,"update",j,T.length);let q=await this.updateRecords(e.orgId,j,T.map(C=>({Id:C,[$]:!1})));q.forEach((C,I)=>{C.success?(n.deactivated[j]=(n.deactivated[j]??0)+1,i.add(ie(T[I]))):n.failures.push({objectApiName:j,recordId:T[I],errors:C.errors})}),f+=q.length}else{let q=cn(j)?await this.customPricesFirst(e.orgId,T):j===kr?[await this.withoutDirectRelations(e.orgId,T)]:[T];f+=T.length-q.reduce((C,I)=>C+I.length,0);for(let C of q){if(C.length===0)continue;await h(),await this.checkGuard(e,"delete",j,C.length);let I=await this.deleteRecords(e.orgId,j,C);I.forEach((b,O)=>{Nd(b)?(n.deleted[j]=(n.deleted[j]??0)+1,i.add(ie(C[O]))):n.failures.push({objectApiName:j,recordId:C[O],errors:b.errors})}),f+=I.length}}}await this.purgeAgain(e,R,n,i,h,a)}catch(j){throw await g(),p(),j}e.signal?.aborted||await this.settleTakenAlong(e.orgId,n,i,P),await g(),p()}async residualsInSight(e,t){let r=new Set;for(let[n,s]of t)try{for(let i of await this.readRecords(e,n,[],s))typeof i.Id=="string"&&r.add(ie(i.Id))}catch{}return r}async purgeAgain(e,t,r,n,s,i){for(let d of t){if(this.config.undeletableObjects?.[d]!==void 0)continue;let a=r.failures.filter(l=>l.objectApiName===d).map(l=>l.recordId);if(a.length===0)continue;let u=cn(d)?await this.customPricesFirst(e.orgId,a).catch(()=>[a]):[a];for(let l of u){if(l.length===0)continue;await s(),await this.checkGuard(e,"delete",d,l.length),(await this.deleteRecords(e.orgId,d,l)).forEach((f,p)=>{let g=r.failures.findIndex(h=>h.objectApiName===d&&h.recordId===l[p]);g<0||(i.tried++,Nd(f)?(r.failures.splice(g,1),r.deleted[d]=(r.deleted[d]??0)+1,n.add(ie(l[p])),i.went++):r.failures[g]={objectApiName:d,recordId:l[p],errors:f.errors})})}}}async settleTakenAlong(e,t,r,n){for(let s of new Set(t.failures.map(i=>i.objectApiName))){let i=t.failures.filter(h=>h.objectApiName===s).map(h=>h.recordId),d=h=>this.readRecords(e,s,[],h),{gone:a,unchecked:u,failure:l}=await qi(i,d,h=>n.has(ie(h))),c=l?`Not checked: not read back once the purge was through, to tell whether a parent deleted after it took it along \u2014 ${l}`:"Not checked: the purge could not read it before its delete, nor after \u2014 gone, or out of the session's sight",f=new Set(u.map(ie));for(let h of t.failures)h.objectApiName!==s||!f.has(ie(h.recordId))||h.errors.includes(c)||(h.errors=[...h.errors,c]);let p=new Set(a.map(ie));if(p.size===0)continue;let g=t.failures.filter(h=>h.objectApiName!==s||!p.has(ie(h.recordId)));t.failures.splice(0,t.failures.length,...g),t.deleted[s]=(t.deleted[s]??0)+p.size;for(let h of p)r.add(h)}}async draftResiduals(e,t,r,n){for(let[s,i]of Object.entries(xt)){if(pi.has(s))continue;let d=t.residuals.get(s);if(!d||d.length===0)continue;let a=await this.statusCategories(e.orgId,i),u=a?.draft;if(!a||!u)continue;let l;try{l=await this.readRecords(e.orgId,s,["Status","LastModifiedDate"],d)}catch{continue}let c=l.flatMap(f=>{let p=a.categoryOf.get(String(f.Status));if(typeof f.Id!="string"||p===void 0||p==="Draft")return[];let g=t.datedBy.get(ie(f.Id))??Number.NaN;return[{objectApiName:s,id:f.Id,draft:u,status:String(f.Status),unchanged:_t(f.LastModifiedDate)<=g}]});c.length!==0&&(await n(),await this.checkGuard(e,"update",s,c.length),r.push(...c),await this.updateRecords(e.orgId,s,c.map(({id:f})=>({Id:f,Status:u}))))}}async giveStatusesBack(e,t,r){let n=this.deps.restoringWriter??this.deps.writer,s=await this.runningUser(e.orgId),i={};for(let d of new Set(t.map(a=>a.objectApiName))){let a=t.filter(p=>p.objectApiName===d),u=new Map(a.map(p=>[ie(p.id),p])),l;try{l=await this.readRecords(e.orgId,d,["Status"],a.map(p=>p.id))}catch(p){for(let g of a)zd(r,g,`its status was not read back: ${Q(p)}`);continue}let c=l.flatMap(p=>{let g=typeof p.Id=="string"?u.get(ie(p.Id)):void 0;return g&&p.Status===g.draft?[g]:[]});for(let p=0;p<c.length;p+=Pt){let g=c.slice(p,p+Pt),h;try{await this.checkGuard(e,"update",d,g.length),h=await this.updateRecords(e.orgId,d,g.map(({id:m,status:w})=>({Id:m,Status:w})),n)}catch(m){let w=Q(m);h=g.map(()=>({success:!1,errors:[w]}))}g.forEach((m,w)=>{let R=h[w];R?.success||zd(r,m,R?.errors.join("; ")||"the org gave no reason")})}let f=c.filter(p=>p.unchanged);if(!(f.length===0||s===void 0))try{let p=await this.readRecords(e.orgId,d,["LastModifiedDate","LastModifiedById"],f.map(g=>g.id));for(let g of p)typeof g.Id=="string"&&typeof g.LastModifiedDate=="string"&&typeof g.LastModifiedById=="string"&&ie(g.LastModifiedById)===s&&(i[g.Id]=g.LastModifiedDate)}catch{}}if(Object.keys(i).length!==0)try{await this.deps.mappingStore.recordStamps(i)}catch{}}async updateRecords(e,t,r,n=this.deps.writer){let s=await n.update(e,t,r);return this.lockResent?.updated(t,s),s}async deleteRecords(e,t,r){let n=await this.deps.writer.delete(e,t,r);return this.lockResent?.deleted(t,r,n),n}async runningUser(e){let t=await this.runUserIdOf(e);return t?ie(t):void 0}async runUserIdOf(e){let t=this.deps.orgAccess.userId;if(t)try{return await t.call(this.deps.orgAccess,e)||void 0}catch{return}}async readBackRecordTypes(e,t,r){let n=[];for(let{given:s,rule:i,keys:d}of t){let a=d.flatMap(u=>r.get(u)??[]);try{let u=await this.deps.orgAccess.query(e,Ja(s.objectApiName,a));n.push({...s,readBack:Xa(u,i.types)})}catch(u){let l=Q(u);n.push({...s,readBack:{read:0,types:[],unread:l}})}}return n}async readRecords(e,t,r,n){let s=["Id",...r].map(me).join(", "),i=[];for(let d=0;d<n.length;d+=Pt){let a=n.slice(d,d+Pt).map(u=>`'${$e(u)}'`).join(", ");i.push(...await this.deps.orgAccess.query(e,`SELECT ${s} FROM ${me(t)} WHERE Id IN (${a})`))}return i}async resolveRecordType(e,t,r,n,s,i,d){let a={...n.fields};r===Ve&&delete a[mn];let u=a.RecordTypeId;if(typeof u!="string"||u==="")return"RecordTypeId"in a&&d.set(n.referenceId,"masterInSource"),delete a.RecordTypeId,{referenceId:n.referenceId,fields:a};let l=t.recordTypes[r]??[],c=n.recordTypeDeveloperName===void 0?void 0:So(n.recordTypeDeveloperName,l,Vd),f=c&&"found"in c?[c.found]:l.filter(m=>m.name===u),p=f[0];if(!p)return delete a.RecordTypeId,d.set(n.referenceId,"dropped"),i.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:u,detail:"RecordType name absent from the dataset recordTypes map \u2014 RecordTypeId dropped"}),{referenceId:n.referenceId,fields:a};if(f.length>1)throw Hd(r,u,f);let g=ct(p.namespacePrefix,p.developerName),h=await this.deps.recordTypeResolver.resolveByDeveloperName(e.orgId,r,p.developerName,...p.namespacePrefix!==void 0?[p.namespacePrefix]:[]);if(h!==null&&typeof h=="object"&&"ambiguous"in h)throw new et(`The dataset names ${r} record type ${p.developerName} without its namespace \u2014 it was extracted before SandForge read one \u2014 and ${Ao(r,p.developerName,"the target org",h.carriers)}. Extract the dataset again: a dataset extracted now names each record type with its namespace. Nothing was written.`,void 0,{reason:"namespace",objectApiName:r,name:p.developerName,recordTypes:h.carriers.map(m=>ct(m.namespacePrefix,m.developerName))});if(h!==null&&typeof h=="object"){let m=await this.deps.recordTypeResolver.givenRecordType?.(e.orgId,r).catch(()=>{});return delete a.RecordTypeId,d.set(n.referenceId,"dropped"),i.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:u,detail:`RecordType ${g} is in the target org but not available to the running user \u2014 RecordTypeId dropped, ${vl(m)}. Assign it to the user's profile or a permission set to keep it.`}),{referenceId:n.referenceId,fields:a}}return h?(a.RecordTypeId=h,s.set(n.referenceId,h),{referenceId:n.referenceId,fields:a}):(delete a.RecordTypeId,d.set(n.referenceId,"dropped"),i.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:u,detail:`RecordType ${g} not found in target org \u2014 RecordTypeId dropped`}),{referenceId:n.referenceId,fields:a})}async planRequiredFields(e,t){let r=[],n=[];for(let s of t)for(let i of s.missingRequired){let d=`${i.objectApiName}.${i.field}`;if(!i.isLookup){if(this.config.requiredFieldDefaults?.[d]===void 0){let c=i.accountKind?` of a ${i.accountKind} account`:"";n.push(`requiredFieldDefaults["${d}"]: ${xl(i)} for this required field${c}`)}else r.push({kind:"default",missing:i});continue}let a=this.config.requiredLookupPlaceholders?.[d];if(!a){n.push(`requiredLookupPlaceholders["${d}"]: a placeholder (name + recordTypeDeveloperName) for this required lookup to ${i.referenceTo.join(" or ")||"its parent"}`);continue}let u=a.targetObjectApiName??i.referenceTo[0];if(!u){n.push(`requiredLookupPlaceholders["${d}"].targetObjectApiName: the target describe names no object this lookup points at`);continue}let l;if(a.recordTypeDeveloperName){let c=await this.deps.recordTypeResolver.resolveByDeveloperName(e.orgId,u,a.recordTypeDeveloperName);if(c!==null&&typeof c=="object"&&"ambiguous"in c){let f=c.carriers.find(p=>p.namespacePrefix);n.push(`requiredLookupPlaceholders["${d}"]: `+Ao(u,a.recordTypeDeveloperName,"the target org",c.carriers)+(f?" \u2014 a package's is named with its namespace: "+ct(f.namespacePrefix,f.developerName):""));continue}if(c!==null&&typeof c=="object"){n.push(`requiredLookupPlaceholders["${d}"]: record type ${a.recordTypeDeveloperName} on ${u} is not available to the running user`);continue}if(l=c??void 0,!l){n.push(`requiredLookupPlaceholders["${d}"]: record type ${a.recordTypeDeveloperName} is not on ${u} in the target org \u2014 deploy it before loading`);continue}}r.push({kind:"placeholder",missing:i,key:d,name:a.name,targetObject:u,recordTypeId:l})}if(n.length>0)throw new et(`The dataset leaves ${n.length} required field(s) empty that the configuration does not cover. Nothing was written. Declare them all, then load again \u2014 records are never silently excluded:
11
- - ${n.join(`
12
- - `)}`,n);return r}async createPlaceholder(e,t,r,n,s,i){let{missing:d,key:a,targetObject:u}=t,l={Name:t.name};t.recordTypeId&&(l.RecordTypeId=t.recordTypeId),await this.checkGuard(e,"insert",u,1);let[c]=await this.deps.writer.insert(e.orgId,u,[l]);if(c===void 0&&e.signal?.aborted)return;if(!c?.success||!c.id)throw new et(`Placeholder insert failed for required lookup ${a} on ${u}: ${c?.errors.join("; ")||"no id returned"}. Fix the target org configuration and retry.`);let f=`${Kn}${u}:${a}`;n.set(f,c.id),i.add(u,f),this.journal?.created(u,[[f,c.id]]);let p=0;for(let g of r){let h=g.fields[d.field];(h==null||h==="")&&(g.fields[d.field]=c.id,p++)}s.push({objectApiName:d.objectApiName,field:d.field,placeholderObjectApiName:u,placeholderName:t.name,placeholderId:c.id,affectedRecords:p})}applyScalarDefault(e,t,r,n){let s=`${e.objectApiName}.${e.field}`,i=this.config.requiredFieldDefaults?.[s],d=rs(i,e.distinct),a=0;for(let u of t)gt(u.fields[e.field])&&(u.fields[e.field]=ns(i,d,{referenceId:u.referenceId,rank:n.get(u.referenceId)??0}),a++);r.push({objectApiName:e.objectApiName,field:e.field,value:i,affectedRecords:a,...d?{perRecord:d}:{}})}async insertObject(e,t,r,n,s,i,d,a,u,l,c,f,p){let g={objectApiName:t,fromFiles:r,inserted:0,reused:0,skippedDuplicates:[],failed:[]},h=n.filter(b=>!d.has(b.referenceId));g.reused=n.length-h.length;let m=[];for(let b of h){let O=Cl(t,b.fields,s,f);O?g.failed.push({objectApiName:t,referenceId:b.referenceId,errors:[O]}):m.push(b)}if(m.length===0)return g;let w=m.map(b=>{let O={},F=[];for(let[A,N]of Object.entries(b.fields))if(!(N===""||N===null||N===void 0))if(typeof N=="string"&&s.has(N)){let M=i.get(N);M&&!(t===zr&&A===Mr)?O[A]=M:F.push({objectApiName:t,referenceId:b.referenceId,field:A,targetReferenceId:N})}else O[A]=N;let v=ni(t,O);for(let A of v)delete O[A];a.push(...F.filter(A=>!v.includes(A.field)));for(let A of Hs(t,O))delete O[A];return O}),R=(b,O,F)=>{i.set(b,O),l.add(t,b,Tl.some(v=>v in F)),g.inserted++};await this.checkGuard(e,"insert",t,w.length);let P=await this.deps.writer.insert(e.orgId,t,w,(b,O)=>this.journalBatch(t,m,b,O)),j=[],T=new Map;P.forEach((b,O)=>{let F=m[O].referenceId;if(b.lockResends!==void 0&&T.set(F,b),b.success&&b.id){R(F,b.id,w[O]);return}if(Gd(b.errors,u)){g.skippedDuplicates.push({objectApiName:t,referenceId:F,errors:b.errors});return}let v=this.sentAgain(t,w[O],b);v?j.push({...v,referenceId:F,errors:b.errors}):g.failed.push({objectApiName:t,referenceId:F,errors:b.errors})});let $=m.length-P.length;$>0&&e.signal?.aborted&&(g.notInserted=$);let q=()=>{let b=Fl(T);b&&(g.sentAgainForALock=b)};if(q(),j.length===0)return g;let C=(b,O)=>{for(let F of b)g.failed.push({objectApiName:t,referenceId:F.referenceId,errors:[...F.errors,`Not written again ${Md(F.fields)}: ${O}`]})};if(e.signal?.aborted)return C(j,"the load was cancelled first"),g;let I;try{await this.checkGuard(e,"insert",t,j.length),I=await this.deps.writer.insert(e.orgId,t,j.map(b=>b.payload),(b,O)=>this.journalBatch(t,j,b,O))}catch(b){throw C(j,Q(b)),p?.(g),b}return j.forEach((b,O)=>{let F=I[O];if(!F){C([b],e.signal?.aborted?"the load was cancelled first":"no answer came for it");return}if((F.lockResends!==void 0||T.has(b.referenceId))&&T.set(b.referenceId,F),F.success&&F.id){R(b.referenceId,F.id,b.payload),g.writtenWithoutFields=Lo(g.writtenWithoutFields,{rows:1,fields:b.fields.map(A=>({...A,rows:1}))});for(let{field:A,replacedWith:N}of b.fields){if(N!==void 0)continue;let M=c.get(t)??new Map;M.set(A,[...M.get(A)??[],b.referenceId]),c.set(t,M)}return}let v=[...F.errors,`Sent again ${Md(b.fields)} after the first refusal: ${b.errors.join("; ")}`];Gd(F.errors,u)?g.skippedDuplicates.push({objectApiName:t,referenceId:b.referenceId,errors:v}):g.failed.push({objectApiName:t,referenceId:b.referenceId,errors:v})}),q(),g}journalBatch(e,t,r,n){let s=this.journal;s&&s.created(e,n.flatMap((i,d)=>{let a=t[r+d];return i.success&&i.id&&a?[[a.referenceId,i.id]]:[]}))}sentAgain(e,t,r){let n=ba(r.errorDetails,t,void 0);if(!n)return;let s={...t},i=n.map(d=>{let a=d.refusedBy==="restricted-picklist"?this.picklistRuleFor(e,d.field):void 0;return a?.action==="replace"&&a.value!==""&&a.value!==t[d.field]?(s[d.field]=a.value,{...d,replacedWith:a.value}):(delete s[d.field],{...d})});return{payload:s,fields:i}}async matchDirectRelations(e,t,r,n,s,i){let d=new Map;for(let l of t.objects.find(c=>c.objectApiName==="Contact")?.records??[])d.set(l.referenceId,l.fields.AccountId);let a=r.filter(l=>{let c=l.fields.ContactId;return typeof c=="string"&&l.fields.AccountId!==void 0&&d.get(c)===l.fields.AccountId&&n.has(c)&&typeof l.fields.AccountId=="string"&&n.has(l.fields.AccountId)});if(a.length===0)return;let u=await gi(l=>this.deps.orgAccess.query(e,l),a.map(l=>({AccountId:n.get(l.fields.AccountId),ContactId:n.get(l.fields.ContactId)})));for(let[l,c]of a.entries()){let f=u.get(l);typeof f=="string"&&(n.set(c.referenceId,f),s.add(c.referenceId),i.set(c.referenceId,c.fields.ContactId))}}async matchTasksWrittenWithEmails(e,t,r,n,s,i){let d=new Set(r.map(l=>l.referenceId)),a=new Map;for(let l of t.objects.find(c=>c.objectApiName===Ze)?.records??[]){let c=l.fields.ActivityId;if(typeof c!="string"||!d.has(c)||s.has(l.referenceId))continue;let f=n.get(l.referenceId);f&&a.set(c,{id:f,key:l.referenceId})}if(a.size===0)return;let u=await ii(l=>this.deps.orgAccess.query(e,l),[...new Set([...a.values()].map(l=>l.id))]);for(let[l,c]of a){let f=u.get(c.id);f!==void 0&&(n.set(l,f),s.add(l),i.set(l,c.key))}}async matchContactRolesWrittenWithOpportunities(e,t){let{aligned:r,refIndex:n,mapping:s,reused:i}=t,d=I=>typeof I=="string"?s.get(I):void 0,a=new Map;for(let I of t.working.objects.find(b=>b.objectApiName===Yd)?.records??[]){let b=s.get(I.referenceId),O=d(I.fields[bt]);b&&O&&!i.has(I.referenceId)&&a.set(b,O)}if(a.size===0)return{linked:0};let u=r.map(I=>({OpportunityId:d(I.fields.OpportunityId),[bt]:d(I.fields[bt]),IsPrimary:I.fields.IsPrimary})),l=Ro(u,I=>a.get(I)).filter(I=>!i.has(r[I].referenceId));if(l.length===0)return{linked:0};let c=I=>{let b={},O=[];for(let[F,v]of Object.entries(I.fields))if(!(F==="OpportunityId"||F===bt)&&!t.fixedAtInsert.has(F)&&!(v===""||v===null||v===void 0))if(typeof v=="string"&&n.has(v)){let A=s.get(v);A?b[F]=A:O.push({objectApiName:Dt,referenceId:I.referenceId,field:F,targetReferenceId:v})}else b[F]=v;return{fields:b,owed:O}},f=new Map(l.map(I=>[I,{opportunity:String(u[I].OpportunityId),contact:String(u[I][bt])}])),p=[...new Set(l.flatMap(I=>Object.keys(c(r[I]).fields)))],g=await di(I=>this.deps.orgAccess.query(e.orgId,I),[...new Set([...f.values()].map(({opportunity:I})=>I))],p),{found:h,alike:m}=ci(f,g),w=m.length>0?li(m.length):void 0;if(h.size===0)return w?{linked:0,note:w}:{linked:0};let R=I=>w?`${I}; ${w}`:I,P=[];for(let[I,b]of h){let O=r[I],F=String(b.Id);s.set(O.referenceId,F),i.add(O.referenceId),t.withTheirRecord.set(O.referenceId,String(O.fields.OpportunityId));let{fields:v,owed:A}=c(O);t.pendingFk.push(...A);let N=Object.entries(v).filter(([M,B])=>String(b[M]??"")!==String(B));N.length>0&&P.push({Id:F,...Object.fromEntries(N)})}let j=h.size,T=`${j} written by the platform with ${ai(Dt)}`;if(P.length===0)return{linked:j,note:R(T)};let $=(I,b)=>`${T}, ${I} of them left as it wrote ${I===1?"it":"them"}, without the fields of the source's role: ${b}`;if(e.signal?.aborted)return{linked:j,note:R($(P.length,"the load was cancelled before the update"))};await this.checkGuard(e,"update",Dt,P.length);let q=await this.updateRecords(e.orgId,Dt,P),C=P.flatMap((I,b)=>{let O=q[b];return O?.success?[]:[O?O.errors.join("; ")||"refused":"no answer came for it"]});return C.length===0?{linked:j,note:R(T)}:{linked:j,note:R($(C.length,C[0]))}}async matchActivityRelations(e,t,r,n,s,i){let{orgId:d}=e,a=ko[t],u=c=>typeof c=="string"?n.get(c):void 0,l=await ui(c=>this.deps.orgAccess.query(d,c),t,r.map(c=>({[a]:u(c.fields[a]),RelationId:u(c.fields.RelationId)})));for(let[c,f]of l)n.set(r[c].referenceId,f),s.add(r[c].referenceId);return fi(t,[...l].map(([c,f])=>[r[c].fields,f]),c=>!i.has(c),async c=>(await this.checkGuard(e,"update",t,c.length),this.updateRecords(d,t,c)),()=>e.signal?.aborted===!0)}async startAsDrafts(e,t,r,n,s){let i=await this.statusCategories(e,r);return i?.draft?n.map(d=>{let a=sr(d.fields.Status,i);return a?(s.push({objectApiName:t,referenceId:d.referenceId,status:String(d.fields.Status)}),{referenceId:d.referenceId,fields:{...d.fields,Status:a}}):d}):n}async withoutDirectRelations(e,t){let r=new Set;for(let n=0;n<t.length;n+=Pt){let s=t.slice(n,n+Pt).map(d=>`'${$e(d)}'`).join(", "),i=await this.deps.orgAccess.query(e,`SELECT Id FROM ${kr} WHERE Id IN (${s}) AND IsDirect = true`);for(let d of i)r.add(String(d.Id))}return t.filter(n=>!r.has(n))}async customPricesFirst(e,t){let r=await hi(n=>this.deps.orgAccess.query(e,n),t);return[t.filter(n=>!r.has(n)),t.filter(n=>r.has(n))]}async readWrittenBetween(e,t,r){let n=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let{objectApiName:i,referenceIds:d}of t.list()){let a=[...new Set(d.flatMap(l=>{let c=r.get(l);return c?[c]:[]}))],u=t.sentAuditDates(i);for(let l=0;l<a.length;l+=Pt){let c=await this.writtenDatesOf(e,i,a.slice(l,l+Pt));if(!c)return;for(let f of c){let p=_t(f.SystemModstamp),g=w=>{let R=u?Number.NaN:_t(f[w]);return Number.isFinite(R)?R:p},h=g("CreatedDate"),m=g("LastModifiedDate");Number.isFinite(h)&&(n=Math.min(n,h)),Number.isFinite(m)&&(s=Math.max(s,m))}}}if(!(!Number.isFinite(n)||!Number.isFinite(s)))return{first:new Date(n).toISOString(),last:new Date(Math.max(n,s)).toISOString()}}async writtenDatesOf(e,t,r){let n=r.map(s=>`'${$e(s)}'`).join(", ");for(let s of jl)try{return await this.deps.orgAccess.query(e,`SELECT Id, ${s.join(", ")} FROM ${me(t)} WHERE Id IN (${n})`)}catch{}}async statusCategories(e,t){return or(r=>this.deps.orgAccess.query(e,r),t)}async applyDeferredStatuses(e,t,r,n){let{refused:s}=n.report,i=new Map;for(let d of t){let a=r.get(d.referenceId);a&&i.set(d.objectApiName,[...i.get(d.objectApiName)??[],{...d,id:a}])}n.unanswered=[...i.values()].reduce((d,a)=>d+a.length,0);for(let[d,a]of i){if(e.signal?.aborted)continue;let u=a.map(c=>({Id:c.id,Status:c.status}));await this.checkGuard(e,"update",d,u.length);let l=await this.updateRecords(e.orgId,d,u);l.forEach((c,f)=>{c.success?n.report.restored++:s.push({objectApiName:d,referenceId:a[f].referenceId,status:a[f].status,detail:c.errors.join("; ")})}),n.unanswered-=l.length}}async patchCycleFks(e,t,r,n){let{unresolved:s}=n.report,i=new Map,d=new Map;for(let u of t){let l=r.get(u.referenceId),c=r.get(u.targetReferenceId);if(!l||!c){s.push({objectApiName:u.objectApiName,referenceId:u.referenceId,field:u.field,cause:l?"target-not-loaded":"record-not-loaded",detail:l?`referenced record ${u.targetReferenceId} was not loaded (skipped, failed or excluded)`:"child record was not loaded (see perObject failures/skips)"});continue}d.set(l,u.referenceId);let f=i.get(u.objectApiName)??new Map,p=f.get(l)??{Id:l};p[u.field]=c,f.set(l,p),i.set(u.objectApiName,f)}let a=u=>u.reduce((l,c)=>l+Object.keys(c).length-1,0);n.unanswered=[...i.values()].reduce((u,l)=>u+a([...l.values()]),0);for(let[u,l]of i){let c=[...l.values()];if(e.signal?.aborted)continue;await this.checkGuard(e,"update",u,c.length);let f=await this.updateRecords(e.orgId,u,c);f.forEach((p,g)=>{p.success?n.report.resolved+=Object.keys(c[g]).length-1:s.push({objectApiName:u,referenceId:d.get(String(c[g].Id))??String(c[g].Id),field:Object.keys(c[g]).filter(h=>h!=="Id").join(","),cause:"update-refused",detail:p.errors.join("; ")})}),n.unanswered-=a(c.slice(0,f.length))}}async linkPersonContacts(e,t,r,n,s,i){let d={linked:new Map,own:new Map,unlinked:[]},a=new Map,u=[...t].map(([f,p])=>({accountReferenceId:p,contactReferenceId:f}));for(let f of u){let p=f.accountReferenceId===""?void 0:r.get(f.accountReferenceId);p!==void 0&&a.set(p,[...a.get(p)??[],f])}let l=a.size===0||s===!1?new Map:await wn(f=>this.deps.orgAccess.query(e,f),[...a.keys()]),c=new Map;for(let[f,p]of a){let g=l.get(f);if(g!==void 0)for(let h of p)c.set(h.contactReferenceId,g)}for(let f of u){let p=c.get(f.contactReferenceId);if(p!==void 0){r.set(f.contactReferenceId,p),d.linked.set(f.contactReferenceId,f.accountReferenceId);continue}if(f.accountReferenceId===""||!r.has(f.accountReferenceId)){d.unlinked.push({...f,cause:"record-not-loaded",detail:f.accountReferenceId===""?Dr.accountNotInDataset:Dr.accountNotLoaded});continue}if(n.has(f.contactReferenceId))continue;let g=i.find(m=>m.objectApiName===Ve&&m.referenceId===f.accountReferenceId),h=Dr.noPersonAccounts;s!==!1&&(h=g?`${Dr.businessAccount}: ${g.detail}`:`${Dr.businessAccount}: its record type there is no person account's`),d.own.set(f.contactReferenceId,{...f,detail:h})}return d}writeContract(e,t,r,n,s,i,d,a=0,u=new Map,l=[]){let c=new Map;for(let{objectApiName:h,referenceId:m,field:w}of l){let R=c.get(h)??{};R[w]=[...R[w]??[],m],c.set(h,R)}let f=new Map;for(let{objectApiName:h,count:m,reason:w}of d){let R=f.get(h)??{};R[w]=(R[w]??0)+m,f.set(h,R)}let p=[...r];for(let[h,m]of f)p.some(w=>w.objectApiName===h)||p.push({objectApiName:h,fromFiles:t.objects.find(w=>w.objectApiName===h)?.records.length??Object.values(m).reduce((w,R)=>w+R,0),inserted:0,reused:0,skippedDuplicates:[],failed:[]});let g={};for(let h of p){let m={};h.skippedDuplicates.length>0&&(m["duplicate-skipped"]=h.skippedDuplicates.length);let w=h.objectApiName===We?a:0,R=h.failed.filter(C=>zl(C.errors)).length;if(R>0&&(m["parent-refused"]=R),h.failed.length-R>w){let C=i.has(h.objectApiName)?"object-not-loaded":"dml-failed";m[C]=h.failed.length-R-w}w>0&&(m["person-contact-not-sent"]=w);let P=0;for(let[C,I]of Object.entries(f.get(h.objectApiName)??{}))m[C]=I,P+=I;let j=h.skippedDuplicates.length+h.failed.length+P,T=n.filter(C=>C.placeholderObjectApiName===h.objectApiName).length,$=u.get(h.objectApiName),q=c.get(h.objectApiName);g[h.objectApiName]={fromFiles:h.fromFiles,exclusionReasons:m,excluded:j,added:T,expected:h.inserted+h.reused+T,...$&&$.size>0?{writtenWithout:Object.fromEntries($)}:{},...q?{parentNotLoaded:q}:{}}}return hd(this.sasGuard,e.sasDir,{version:1,orgId:e.contractOrgId??e.orgId,datasetVersion:t.datasetVersion,writtenAt:s.now().toISOString(),loadStartedAt:s.startedAt.toISOString(),objects:g})}picklistRuleFor(e,t){return this.config.picklistRules?.[`${e}.${t}`]??this.config.defaultPicklistRule??{action:"clear"}}contractPath(e,t){return zn(this.sasGuard,e,t)}};function xd(o){let e=new Map;for(let t of o)for(let r of t.failed)e.set(r.referenceId,t.objectApiName);return e}function Cl(o,e,t,r){if(r.size===0)return;let n=new Set(o===Ze&&!bo(e,s=>t.get(s))?["ActivityId"]:[]);for(let[s,i]of Object.entries(e)){if(typeof i!="string"||n.has(s)||!t.has(i))continue;let d=r.get(i);if(d!==void 0)return`PARENT_REFUSED: the ${d} record its ${s} names was refused in this load, and written without it this record would stand without its ${d}.`}}function zl(o){return o.length===1&&o[0].startsWith("PARENT_REFUSED:")}function gt(o){return o==null||o===""}var Xd=/\{(n|referenceId)\}/g;function rs(o,e){if(typeof o=="string")return o.match(Xd)?"token":e}function ns(o,e,t){return typeof o!="string"||e===void 0?o:e==="token"?o.replace(Xd,(r,n)=>n==="n"?String(t.rank):t.referenceId):`${o} ${t.rank}`}function Ml(o,e){let{objectApiName:t,keyFields:r,ranks:n,accountKindOf:s}=o,i=o.missingRequired.filter(d=>!d.isLookup&&r.includes(d.field));return o.records.map(d=>{let a={...d.fields};for(let u of i){let l=e[`${t}.${u.field}`];l===void 0||!gt(a[u.field])||Hn(u,[d],s).length!==0&&(a[u.field]=ns(l,rs(l,u.distinct),{referenceId:d.referenceId,rank:n.get(d.referenceId)??0}))}return{referenceId:d.referenceId,fields:a}})}function Zd(o,e=!1){return o.length===0?{}:{keysLeftEmpty:o.map(({objectApiName:t,fields:r,count:n})=>{let s=n===1?"its":"their",i=r.join(", "),d="the dataset holds no value, and no default fills it";return{objectApiName:t,fields:[...r],count:n,note:e?`${n} not looked up by ${s} identity keys: ${i} stays empty in what the load would write \u2014 ${d} \u2014 so ${n===1?"it":"they"} would be inserted, never matched`:`${n} not looked up by ${s} identity keys: ${i} stayed empty in what the load wrote \u2014 ${d} \u2014 so ${n===1?"it was":"they were"} sent to be inserted, never matched`}})}}function Dl(o){let e=new Map;for(let t of o.objects)t.records.forEach((r,n)=>e.set(r.referenceId,n+1));return e}function Qd(o){let e=os(o),t=new Map(o.objects.map(n=>[n.objectApiName,n.records])),r=new Set;return new Set([...ec(t,r),...tc(t,r,Jd(o,e),n=>e.get(n))])}function ec(o,e){let t=(o.get(Dt)??[]).filter(a=>!e.has(a.referenceId));if(t.length===0)return new Set;let r=new Map,n=a=>{if(typeof a!="string"||a==="")return;let u=r.get(a);return u===void 0&&(u=String(r.size+1).padStart(15,"0"),r.set(a,u)),u},s=new Set((o.get(We)??[]).map(a=>a.referenceId)),i=new Map;for(let a of o.get(Yd)??[]){if(e.has(a.referenceId))continue;let u=a.fields[bt];typeof u!="string"||!s.has(u)||i.set(n(a.referenceId),n(u))}if(i.size===0)return new Set;let d=t.map(a=>({OpportunityId:n(a.fields.OpportunityId),[bt]:n(a.fields[bt]),IsPrimary:a.fields.IsPrimary}));return new Set(Ro(d,a=>i.get(a)).map(a=>t[a].referenceId))}function tc(o,e,t,r){let n=l=>(o.get(l)??[]).filter(c=>!e.has(c.referenceId)),s=new Set,i=new Map;for(let l of n(We))t.has(l.referenceId)||i.set(l.referenceId,l.fields.AccountId);let d=new Set((o.get("Account")??[]).map(l=>l.referenceId));for(let l of n(kr)){let{AccountId:c,ContactId:f}=l.fields;typeof c!="string"||typeof f!="string"||i.get(f)===c&&d.has(c)&&s.add(l.referenceId)}let a=new Set([...o.values()].flatMap(l=>l.map(c=>c.referenceId))),u=new Set(n(tr).map(l=>l.referenceId));for(let l of n(Ze)){let c=l.fields.ActivityId,f=l.fields.RelatedToId;typeof c!="string"||!u.has(c)||typeof f!="string"||!a.has(f)||bo(l.fields,r)||s.add(c)}return s}function $d(o,e,t){let{working:r,loading:n,alignedByObject:s,reused:i,reusedByKeys:d,alignment:a,ranks:u}=o,l=o.targetHasPersonAccounts===!1?new Set:o.personContacts,c=I=>(s.get(I)??[]).filter(b=>!i.has(b.referenceId)),f=[...new Set([...o.groupOrder,...r.objects.map(I=>I.objectApiName),...e?[...e.residuals.keys()].sort():[]])],p=0,g=ec(s,i),h=tc(s,i,l,I=>o.refIndex.get(I)),m=[];for(let I of f){let b=r.objects.find(L=>L.objectApiName===I)?.records.length??0,O=e?.residuals.get(I)?.length??0;if(b===0&&O===0)continue;let F=s.get(I),A=(F??n.objects.find(L=>L.objectApiName===I)?.records??[]).filter(L=>i.has(L.referenceId)),N=A.filter(L=>d.has(L.referenceId)).length,M=F?c(I):[],B=M.filter(L=>l.has(L.referenceId)).length;p+=B;let D=M.filter(L=>g.has(L.referenceId)||h.has(L.referenceId)).length,G=(o.filteredLookups.get(I)??[]).flatMap(({field:L,referenceTo:H})=>{let K=M.filter(re=>!gt(re.fields[L])).length;return K>0?[{field:L,referenceTo:H,records:K}]:[]}),V=t.undeletableObjects[I]!==void 0;m.push({objectApiName:I,fromFiles:b,toInsert:M.length-B-D,reusedByKeys:N,reusedFromCatalog:A.length-N,...D>0?{writtenByThePlatform:D}:{},fieldsDropped:a.removals.filter(L=>L.objectApiName===I).length,picklistsRewritten:a.adjustments.filter(L=>L.objectApiName===I).length,notSent:b-(F?F.length:A.length),toPurge:V?0:O,toDeactivate:V?O:0,...G.length>0?{lookupFilters:G}:{}})}let w=(I,b)=>c(I).filter(O=>gt(O.fields[b])),R=(I,b)=>w(I,b).length,P=I=>{let b=Hn(I,w(I.objectApiName,I.field),o.accountKindOf),O=t.requiredFieldDefaults[`${I.objectApiName}.${I.field}`],F=rs(O,I.distinct),v=b[0];return{objectApiName:I.objectApiName,field:I.field,affectedRecords:b.length,...F?{perRecord:F}:{},...F&&v?{example:String(ns(O,F,{referenceId:v.referenceId,rank:u.get(v.referenceId)??0}))}:{}}},j=e?.leftUnrecorded??{},T=e?.keptByThePlatform??{},$=o.heldForExclusions.counts(),q=Kd(o,I=>!i.has(I)&&!l.has(I)).map(({given:I})=>I),C=new Set([...s.values()].flatMap(I=>I.map(b=>b.referenceId)));return{orgId:t.orgId,mode:t.mode,plannedAt:t.plannedAt,perObject:m,excludedObjects:a.excludedObjects,removals:a.removals,placeholders:o.plans.flatMap(I=>I.kind==="placeholder"?[{objectApiName:I.missing.objectApiName,field:I.missing.field,placeholderObjectApiName:I.targetObject,placeholderName:I.name,affectedRecords:R(I.missing.objectApiName,I.missing.field)}]:[]),requiredDefaults:o.plans.flatMap(I=>I.kind==="default"?[P(I.missing)]:[]),recordTypeIssues:o.recordTypeIssues.length,personContacts:p,earlierLoads:o.previousLoads.length,...Object.keys(j).length>0?{leftUnrecorded:j}:{},...Object.keys(T).length>0?{keptByThePlatform:T}:{},...$.length>0?{heldForExcludedParents:oc($)}:{},...rc(Zo(s,I=>C.has(I)),t,!0),...Zd(o.keysLeftEmpty,!0),...q.length>0?{recordTypesGiven:q}:{}}}var _d=5;function xl(o){switch(o.fieldType){case"date":return'a date, as "2026-12-31",';case"datetime":return'a date and time, as "2026-12-31T09:00:00Z",';case"time":return'a time, as "09:00:00.000Z",';case"double":case"currency":case"percent":return"a number";case"int":case"long":return"a whole number";case"boolean":return"true or false";case"picklist":case"multipicklist":{let e=o.activeValues??[];return e.length===0?"one of its values":`one of its active values (${e.slice(0,_d).join(", ")}${e.length>_d?", \u2026":""})`}case"email":return"an email address";case"string":case"textarea":case"phone":case"url":case"encryptedstring":case"combobox":return"a string";default:return"a value"}}function rc(o,e,t=!1){let r=Ld(o,(e.excludedObjects??[]).includes(Xo),t);return r?{quotesLeftUnsynced:[r]}:{}}function $l(o,e,t){for(let r=!0;r;){r=!1;for(let[n,s]of o){let i=[...e.get(n)??[]],d=s.filter(a=>!t.some(u=>u.leaveOut(n,a.referenceId,a.fields,i)));d.length!==s.length&&(o.set(n,d),r=!0)}}}function _l(o,e,t){let r=new Set(t.excludedObjects??[]);if(r.size===0)return[];let n=[];for(let s of e.fields){let i=s.referenceTo??[];i.length===0||!i.every(d=>r.has(d))||!s.createable||s.defaultedOnCreate||Qt(o,s.name,s.nillable)&&(t.requiredLookupPlaceholders?.[`${o}.${s.name}`]||n.push({field:s.name,excludedObject:i[0]}))}return n}function Bl(o){return(e,t)=>{for(let{field:r,excludedObject:n}of o.get(e)??[])if(gt(t[r]))return{field:r,value:"",noun:n}}}function nc(o,e){return e.through?`${o} left out: ${e.through} names a record left out for the ${e.rows.noun} excludedObjects leaves out`:`${o} left out: ${e.rows.field??"a lookup"} names ${/^[AEIOU]/i.test(e.rows.noun)?"an":"a"} ${e.rows.noun} record, which excludedObjects leaves out \u2014 declare a placeholder in requiredLookupPlaceholders to load them`}function oc(o){return o.map(({objectApiName:e,why:t,count:r})=>({objectApiName:e,count:r,note:nc(r,t)}))}var ql={field:"Type",value:"",noun:"feed item whose type the dataset does not carry"};function Wl(o,e){if(o!=="FeedItem")return;let t=e.Type;return typeof t=="string"&&t!==""?void 0:ql}function Bd(o,e){let t="extract the dataset again, with rules that keep FeedItem.Type";return e.through?`${o} left out: ${e.through} names a feed item whose type the dataset does not carry \u2014 ${t}`:`${o} feed item${o===1?"":"s"} left out: the dataset does not carry ${o===1?"its":"their"} type, and a tracked change cannot be told from a post \u2014 ${t}`}function os(o){let e=new Map;for(let t of o.objects)for(let r of t.records)e.set(r.referenceId,t.objectApiName);return e}function Gl(o,e,t=new Map){let r=new Map;for(let n of o.objects){let s=r.get(n.objectApiName)??new Set;for(let i of n.records)for(let[d,a]of Object.entries(i.fields))if(!(n.objectApiName===Ve&&d===mn)&&typeof a=="string"){let u=e.get(a);u&&u!==n.objectApiName&&s.add(u)}r.set(n.objectApiName,s)}t.size>0&&r.has(Ve)&&r.get(We)?.add(Ve);for(let{sourceObject:n,targetObject:s}of wa(new Set(r.keys()),[]))r.get(s)?.add(n);for(let{sourceObject:n,targetObject:s}of oi(new Set(r.keys())))r.get(n)?.delete(s),r.get(s)?.add(n);return r}function Ul(o,e,t,r=new Map){let n=new Map;for(let[s,i]of o){let d=e.get(s),a=new Set;if(d)for(let u of i)for(let l of d){let c=u.fields[l],f=typeof c=="string"?t.get(c):void 0;f&&f!==s&&a.add(f)}n.set(s,a)}return r.size>0&&n.set(We,new Set([...n.get(We)??[],Ve])),n}function Kl(o,e){let t=h=>o.objects.find(m=>m.objectApiName===h)?.records??[],r=(h,m)=>m.map(w=>String(h[w]??"")).join("|"),n=[qe,Xe,er],s=[qe,Xe],i=(h,m)=>typeof h[m]=="string"&&h[m]!=="",d=t(_e),a=d.filter(h=>e.has(h.referenceId)&&i(h.fields,qe)),u=o.standardPricebook,l=h=>u!==void 0&&h.fields[wt]===u,c=new Set(a.filter(h=>!l(h)).map(h=>r(h.fields,n))),f=d.filter(h=>l(h)&&c.has(r(h.fields,n))),p=new Set([...a,...f].filter(h=>i(h.fields,Xe)).map(h=>r(h.fields,s))),g=t(xe).filter(h=>p.has(r(h.fields,s)));return[...f,...g].map(h=>h.referenceId)}function qd(o){return[...Object.keys(hn),xe].filter(e=>o.objects.some(t=>t.objectApiName===e&&t.records.length>0))}function Vl(o,e){for(let t of o.objects){let r=t.records.find(n=>n.referenceId===e);if(r)return r}}function Wd(o){return JSON.stringify(o.map(e=>e===void 0?null:e))}function Gd(o,e){return o.some(t=>e.some(r=>t.toLowerCase().includes(r.toLowerCase())))}function ss(o,e,t){if(!e)throw new et("Pilot mode requires config.rootObjectApiName (the business-folder root object).");let r=o.objects.find(l=>l.objectApiName===e)?.records??[],n=t??r[0]?.referenceId;if(!n||!r.some(l=>l.referenceId===n))throw new et(`Pilot root ${t??"<first>"} not found in ${e} records (${r.length} in dataset). Provide pilot.rootReferenceId of an existing root record.`);let s=os(o),i=new Set([n]),d=!0;for(;d;){d=!1;for(let l of o.objects)for(let c of l.records)i.has(c.referenceId)||Object.values(c.fields).some(f=>typeof f=="string"&&i.has(f))&&(i.add(c.referenceId),d=!0)}let a=l=>{for(;l.length>0;){let c=l.pop(),f=Vl(o,c);if(f)for(let p of Object.values(f.fields))typeof p=="string"&&s.has(p)&&!i.has(p)&&(i.add(p),l.push(p))}};a([...i]);let u=Kl(o,i).filter(l=>!i.has(l));for(let l of u)i.add(l);return a(u),{...o,objects:o.objects.map(l=>({...l,records:l.records.filter(c=>i.has(c.referenceId))})).filter(l=>l.records.length>0)}}import{randomBytes as Hl}from"node:crypto";import{readFile as Yl}from"node:fs/promises";var is="frozen.salt";function Jl(){return Hl(32).toString("base64url")}function sc(o){let e=o[Va];return e?{salt:e,source:"environment"}:void 0}function Tp(o,e=process.env){let t=async()=>{let r=sc(e);if(r)return r;let n=await o.getSecret(is);return n?{salt:n,source:"secretStorage"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(r)return r;let n=Jl();if(await o.storeSecret(is,n),await o.getSecret(is)!==n)throw new Tr;return{salt:n,source:"secretStorage",created:!0}}}}function ic(o=process.env,e){let t=async()=>{let r=sc(o);if(r)return r;if(e===void 0)return;let n=(await Yl(e,"utf8")).trim();return n?{salt:n,source:"file"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(!r)throw new Tr;return r}}}import{createHash as Xl}from"node:crypto";import{appendFileSync as Zl,mkdirSync as Ql,readFileSync as eu}from"node:fs";import*as _r from"node:path";var tu=15*6e4;function Yn(o){return`sha256:${Xl("sha256").update(_r.resolve(o)).digest("hex").slice(0,16)}`}function ac(o,e){if(!o?.writtenBetween)return;let t=Date.parse(o.endedAt),r=Date.parse(e);if(!Number.isFinite(t)||!Number.isFinite(r)||t<r)return;let n=Date.parse(o.writtenBetween.first),s=Date.parse(o.writtenBetween.last);if(!(!Number.isFinite(n)||!Number.isFinite(s)))return new Date(Math.max(n,s)).toISOString()}function ru(o,e){return e.some(t=>{let r=Date.parse(t.endedAt),n=Date.parse(t.startedAt??t.endedAt);return Number.isFinite(r)&&o>=(Number.isFinite(n)?n:r)-6e4&&o<=r+tu})}function dc(o,e){let t=[];for(let r of o){let n=Date.parse(r.endedAt);if(!Number.isFinite(n)||(r.sas!==void 0?r.sas===e.sasMark:ru(n,e.own)))continue;let s=Date.parse(r.lastWriteAt??""),i=Number.isFinite(s)?s:n,d=Date.parse(r.startedAt??r.endedAt);t.push({ids:[],idsUntold:!0,from:Number.isFinite(d)?Math.min(d,i):i,to:i})}return t}var cc="frozen-loads.ndjson";function Lp(o,e){Ql(o,{recursive:!0}),Zl(_r.join(o,cc),`${JSON.stringify(e)}
13
- `)}function nu(o,e){return o.slice(0,15)===e.slice(0,15)}function Np(o,e){let t;try{t=eu(_r.join(o,cc),"utf8")}catch{return[]}let r=[];for(let n of t.split(`
14
- `)){if(n.trim()==="")continue;let s;try{s=JSON.parse(n)}catch{continue}let{organizationId:i,sas:d,startedAt:a,endedAt:u,lastWriteAt:l}=s??{};typeof i!="string"||typeof u!="string"||nu(i,e)&&r.push({endedAt:u,...typeof d=="string"?{sas:d}:{},...typeof a=="string"?{startedAt:a}:{},...typeof l=="string"?{lastWriteAt:l}:{}})}return r}function lc(o){return o.filter(e=>(e.action==="frozen_load"||e.action==="checkpoint_replay")&&e.outcome!=="stopped").map(e=>{let t=e.details?.sas,r=e.details?.startedAt,n=e.details?.lastWriteAt;return{endedAt:e.timestamp,...typeof t=="string"?{sas:t}:{},...typeof r=="string"?{startedAt:r}:{},...typeof n=="string"?{lastWriteAt:n}:{}}})}var ou="FROZEN_EMAILS_EXCEEDED";function $p(o,e){return[...Da(o.counted,e),...o.uncounted!==void 0?[` emails: not counted, ${o.uncounted} could not be read`]:[],...o.deliverability?[` ${_a(o.deliverability.reading)}`]:[]]}function su(o){return typeof o.unread=="string"}async function uc(o){let{read:e,plan:t,writes:r,target:n}=o,s=await sa({read:e,...t?{plan:t}:{},writes:r,readDeliverability:o.readDeliverability,accepted:o.accepted,target:n,run:"load",keepsAddresses:!0,mayMute:o.mayMute}),i=[],d;if(su(e))d=`the target's automation: ${e.unread}`;else{let c=zt(e,t,r).automation,f={objects:o.inserts.map(g=>({...g,storageBytes:0}))};d=za(c,Ca(f));let p=Xs(c);if(p.length>0){let g=await o.readLimits().catch(h=>({unread:Q(h)}));i=Na(f,p,g)}}let a=Ma(i,n),u=a?{code:ou,message:`${a} Nothing was written.`}:s.gate.stop,{deliverability:l}=s.gate;return{run:s,info:{counted:i.map(c=>({...c,objects:[...c.objects]})),...d!==void 0?{uncounted:d}:{},verdict:s.gate.verdict,...l?{deliverability:l}:{},accepted:o.accepted,...u?{refused:{code:u.code,message:u.message}}:{}},...u?{stop:u}:{}}}var iu="AUTOMATION_NOT_ACCEPTED";function au(o){let e=new Set(o);return(t,r)=>e.has(t)&&(r==="insert"||r==="update")}function du(o){return typeof o.unread=="string"}function cu({kind:o,name:e}){return o==="flow"?`flow "${e}"`:o==="process"?`process "${e}"`:o==="workflowRule"?`workflow rule "${e}"`:`Apex trigger ${e}`}var fc={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"what runs"};function pc(o){return`${o.objectApiName}: ${cu(o)} (${o.writes.join(", ")})`}function lu(o,e,t){let r=[];o.firing.length>0&&r.push(`${e} runs automation as this load inserts its records and updates them: ${o.firing.map(pc).join("; ")}.`);for(let{part:n,reason:s}of o.unread??[]){let i=fc[n];r.push(`${i[0].toUpperCase()}${i.slice(1)} of ${e} could not be read (${s}), so what fires as the load writes is not known.`)}return r.push(...t),r.push(`Nothing was written. Add --accept-automation to load all the same, or turn that automation off in ${e} first.`),r.join(" ")}function as(o){let{read:e,target:t}=o,r=au(o.written),n=[],s=[],i=[];if(du(e))s=[{part:"automation",reason:e.unread}];else{let u=zt(e,o.plan,r),l=new Map;for(let p of u.firing){if(p.write!=="insert"&&p.write!=="update")continue;let g=`${p.objectApiName}\0${p.kind}\0${p.name}`,h=l.get(g);h?h.writes.includes(p.write)||h.writes.push(p.write):l.set(g,{objectApiName:p.objectApiName,kind:p.kind,name:p.name,writes:[p.write]})}n=[...l.values()].map(p=>({...p,writes:["insert","update"].filter(g=>p.writes.includes(g))})),s=Wa(e);let c=qa(u.automation,Ba(u.automation,[...o.written])),f=[...new Set(c.flatMap(p=>p.permissionSet??[]))];i=[...Ga(c,t,"the load"),...o.mayMute&&f.length>0?[e.cannotAssign===!0?`--mute-automation would be refused: ${ia}.`:`With --mute-automation, the load assigns ${f.join(", ")} to the user it writes as for the load alone, under a lease, and what ${f.length===1?"it keeps":"they keep"} quiet does not fire.`]:[]]}if(n.length===0&&s.length===0)return{};let d={firing:n,...s.length>0?{unread:s}:{},accepted:o.accepted};if(o.accepted)return{info:d};let a={code:iu,message:lu(d,t,i)};return{info:{...d,refused:a},stop:a}}function Gp(o,e){return[`target automation: what ${e} runs as the load inserts its records and updates them`,...o.firing.map(t=>` ${pc(t)}`),...(o.unread??[]).map(({part:t,reason:r})=>` ${fc[t]} could not be read: ${r}`),...o.accepted?[" accepted (--accept-automation): the load writes all the same"]:[]]}import{existsSync as mf}from"node:fs";import*as Ae from"node:fs/promises";import*as cl from"node:os";import*as je from"node:path";var lr=class extends Error{constructor(t,r=[]){super(r.length>0?`${t}:
15
- - ${r.join(`
16
- - `)}`:t);this.violations=r;this.name="RulesFileError"}violations},uu=/^\d+\.\d+\.\d+$/,gc=/^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/,fu=new Set(Do);function ds(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Jn(o){let e=[];if(!ds(o))throw new lr("Rules file must be a JSON object");let t=o.rulesVersion;(typeof t!="string"||!uu.test(t))&&e.push('rulesVersion is required and must be semver (e.g. "1.0.0")');let r=o.rules;if(!ds(r))throw e.push('rules is required and must be an object keyed by "Object.Field"'),new lr("Invalid rules file",e);let n={};for(let[s,i]of Object.entries(r)){if(!gc.test(s)){e.push(`"${s}": key must match "ObjectApiName.FieldApiName"`);continue}if(!ds(i)){e.push(`"${s}": rule must be an object with a "generator" property`);continue}let d=i.generator;if(typeof d!="string"||!fu.has(d)){e.push(`"${s}": unknown generator ${JSON.stringify(d)} (supported: ${Do.join(", ")})`);continue}let a=i.approved===!0;if(d==="keep"&&!a){e.push(`"${s}": generator "keep" requires "approved": true (explicit human review)`);continue}let u={generator:d};i.approved!==void 0&&(u.approved=a),typeof i.comment=="string"&&(u.comment=i.comment),n[s]=u}if(e.length>0)throw new lr("Invalid rules file",e);return{rulesVersion:t,rules:n}}function hc(o){let e=Object.keys(o.rules).sort(),t={};for(let r of e)t[r]=o.rules[r];return`${JSON.stringify({rulesVersion:o.rulesVersion,rules:t},null,2)}
17
- `}var mc={rulesVersion:"1.0.0",rules:{}};function yc(o){if(o===null)return{found:!1};try{let e=Jn(JSON.parse(o));return{found:!0,rulesVersion:e.rulesVersion,ruleCount:Object.keys(e.rules).length}}catch(e){return{found:!0,invalid:e instanceof Error?e.message:String(e)}}}var pu=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],gu=new Set(["FeedItem.Type","Pricebook2.IsActive","PricebookEntry.IsActive","Product2.IsActive",...pu.flatMap(o=>[`BusinessHours.${o}StartTime`,`BusinessHours.${o}EndTime`]),"BusinessHours.TimeZoneSidKey","OperatingHours.TimeZone","TimeSlot.DayOfWeek","TimeSlot.StartTime","TimeSlot.EndTime","TimeSlot.Type"]),hu=new Set(["TimeZoneSidKey","LocaleSidKey","LanguageLocaleKey","CurrencyIsoCode","EmailEncodingKey"]);function ut(o,e,t){let r=`${e}.${t}`,n=o.rules[r]?.generator;return n||(o.personalBySchema?.has(r)===!0?"clear":gu.has(r)||hu.has(t)||o.keptBySchema?.has(r)===!0?"keep":"clear")}function wc(o,e,t){let r=new Set(o.keptBySchema??[]),n=new Set(o.personalBySchema??[]);for(let[s,i]of e){let d=new Set(t.detectPII(s,i.map(a=>({apiName:a.name,label:a.label??a.name,type:a.type}))).piiFields.map(a=>a.fieldApiName));for(let a of i){let u=`${s}.${a.name}`;d.has(a.name)?n.add(u):a.type==="picklist"&&(a.restrictedPicklist===!0||a.nillable===!1)&&a.compoundFieldName===void 0&&r.add(u)}}return{...o,keptBySchema:r,personalBySchema:n}}function bc(o,e){let t=new Set;for(let r of o.objects)for(let n of r.records)for(let s of Object.keys(n.fields)){let i=`${r.objectApiName}.${s}`;e.rules[i]===void 0&&ut(e,r.objectApiName,s)==="keep"&&t.add(i)}return[...t].sort()}function Rc(o,e,t){let r=[];for(let n of o.objects){let s=t.get(n.objectApiName)??[];for(let l of s){let c=pn(n.objectApiName,l.name);if(l.name==="Id"||l.createable===!1||l.nillable!==!1&&c===void 0||l.defaultedOnCreate===!0||l.type==="reference"||(l.referenceTo?.length??0)>0||ut(e,n.objectApiName,l.name)!=="clear")continue;n.records.some(p=>{if(c!==void 0&&!nr(c,yn(p.fields,!1)))return!1;let g=p.fields[l.name];return g!=null&&g!==""})&&r.push(`${n.objectApiName}.${l.name}`)}let i=n.objectApiName,d=un(i,l=>s.some(c=>c.name===l&&c.createable!==!1),l=>ut(e,i,l)!=="clear"),a=`${i}.${d}`;d!==void 0&&n.records.some(l=>{let c=l.fields[d];return c!=null&&c!==""})&&!r.includes(a)&&r.push(a)}return r.sort()}var mu="Cleared on review of the extraction result: kept in clear text without a rule before.";function kc(o,e){let t=Jn(o),r=e.filter(u=>!gc.test(u));if(r.length>0)throw new lr('Fields to clear must be named "ObjectApiName.FieldApiName"',r.map(u=>JSON.stringify(u)));let n=o,s={...n.rules},i=[],d=[];for(let u of[...new Set(e)].sort()){if(t.rules[u]!==void 0){d.push(u);continue}s[u]={generator:"clear",comment:mu},i.push(u)}let a=i.length>0?yu(t.rulesVersion):t.rulesVersion;return{payload:{...n,rulesVersion:a,rules:s},rulesVersion:a,cleared:i,alreadyRuled:d}}function yu(o){let[e,t]=o.split(".").map(Number);return`${e}.${t+1}.0`}import*as Ic from"node:fs/promises";import*as vc from"node:path";var cs=/\{\{([A-Z][A-Z0-9_]*)\}\}/g,Oc=/^[A-Z][A-Z0-9_]*$/,Tt=class extends Error{constructor(e){super(e),this.name="QueryTemplateError"}};function Br(o,e){for(let i of Object.keys(e))if(!Oc.test(i))throw new Tt(`Invalid token name ${JSON.stringify(i)}`);let t=new Set;for(let i of o.matchAll(cs))t.add(i[1]);let r=[...t].filter(i=>!(i in e));if(r.length>0)throw new Tt(`Query template references token(s) without a value: ${r.join(", ")}. Token values (ID lists, date bounds) must be provided from the sas at execution time.`);let n=o.replace(cs,(i,d)=>e[d]),s=n.match(cs);if(s)throw new Tt(`Unresolved placeholder(s) after render: ${s.join(", ")}`);return n}async function Sc(o,e,t){let n=(t??new fe).assertOutsideRepo(vc.join(o,e)),s=JSON.parse(await Ic.readFile(n,"utf8"));if(typeof s!="object"||s===null||Array.isArray(s))throw new Tt(`Token file ${n} must contain a JSON object`);let i={};for(let[d,a]of Object.entries(s)){if(!Oc.test(d))throw new Tt(`Invalid token name ${JSON.stringify(d)} in ${n}`);if(typeof a!="string")throw new Tt(`Token ${d} in ${n} must be a string`);i[d]=a}return i}var qr=class extends Error{constructor(){super("Selection stopped"),this.name="SelectionStopped"}};function wu(o,e){return e?e.aborted?(o.catch(()=>{}),Promise.reject(new qr)):new Promise((t,r)=>{let n=()=>r(new qr);e.addEventListener("abort",n,{once:!0}),o.then(s=>{e.removeEventListener("abort",n),t(s)},s=>{e.removeEventListener("abort",n),r(s)})}):o}var bu=2500,Ru=3,ku=5;function Iu(o,e){return Object.entries(o).filter(([t,r])=>t!==e&&r>0).sort(([t,r],[n,s])=>s-r||t.localeCompare(n)).slice(0,ku).map(([t,r])=>({objectApiName:t,count:r}))}var qt=class extends Error{constructor(t,r,n,s){let i=Iu(t,s),d=i.map(u=>`${u.objectApiName} ${u.count}`),a=i.length>0?`The heaviest: ${d.join(", ")}. Leave out those the dataset does not need with excludedObjects (${JSON.stringify(i.map(u=>u.objectApiName))}), narrow the coverage axes/edge cases, or raise budgetMaxRecords explicitly. `:"Narrow the coverage axes/edge cases or raise budgetMaxRecords explicitly. ";super(`Volumetry budget exceeded: ${r} records measured for a budget of ${n}. ${a}Per-object counts: ${JSON.stringify(t)}`);this.measured=t;this.total=r;this.budgetMax=n;this.name="VolumetryBudgetExceededError",this.heaviest=d}measured;total;budgetMax;heaviest},ls=class extends Error{constructor(e){super(e),this.name="CoverageSelectionError"}},Xn=class{deps;constructor(e){this.deps=e}async select(e,t={}){let r=e.budgetMaxRecords??bu,n=e.candidatesPerCombination??Ru,s=me(e.rootObject),{signal:i}=t,d=p=>t.onProgress?.(p),a=[],u=[],l=[],c={during:"axes",pending:[]},f=()=>{let p={};for(let h of l)for(let[m,w]of Object.entries(h))p[m]=(p[m]??0)+w;let g=Object.values(p).reduce((h,m)=>h+m,0);if(g>r)throw new qt(p,g,r,s);return{roots:a,uncovered:u,volumetry:{measured:p,total:g,budgetMax:r,summed:!0},selectedAt:(this.deps.now?.()??new Date).toISOString(),stopped:{reason:i?.reason==="timeout"?"timeout":"cancelled",during:c.during,...c.combinationKey!==void 0?{combinationKey:c.combinationKey}:{},...c.candidate!==void 0?{candidate:c.candidate,candidates:n}:{},notProbed:c.pending}}};try{return await this.run(e,{rootObject:s,budgetMax:r,candidateLimit:n,signal:i,tell:d},{roots:a,uncovered:u,ownMeasures:l,at:c})}catch(p){if(p instanceof qr)return f();throw p}}async run(e,t,r){let{rootObject:n,budgetMax:s,candidateLimit:i,signal:d,tell:a}=t,{roots:u,uncovered:l,ownMeasures:c,at:f}=r,p=T=>wu(T,d),g=new Map,h=new Map;for(let T of e.axes)a({phase:"axis",axis:T.name}),g.set(T.name,await p(this.enumerateAxisValues(T,e.tokens))),h.set(T.name,await p(this.deps.fieldType?.(n,T.filterField).catch(()=>{})??Promise.resolve(void 0)));let m=e.axes.length===0?[[]]:Su(e.axes.map(T=>({axis:T.name,values:g.get(T.name)??[]}))),w=T=>T.length===0?"all":T.map($=>`${$.axis}=${$.value??"NULL"}`).join("|");f.pending=[...m.map(w),...e.edgeCases.map(T=>`edge:${T.name}`)];let R=async(T,$)=>(f.during="combination",f.combinationKey=T,f.candidate=void 0,f.pending=f.pending.filter(q=>q!==T),this.pickHealthyRoot(n,$,i,e.tokens,{step:p,onCandidate:q=>{f.candidate=q,a({phase:"candidate",combinationKey:T,candidate:q,candidates:i})}}));for(let[T,$]of m.entries()){let q=w($);a({phase:"combination",combinationKey:q,index:T+1,of:m.length});let C=$.map(O=>{let F=me(e.axes.find(v=>v.name===O.axis)?.filterField??"");return O.value===null?`${F} = NULL`:`${F} = ${Ou(O.value,h.get(O.axis))}`}).join(" AND "),I=await R(q,C),b={};for(let O of $)b[O.axis]=O.value;I.id?(u.push({rootRecordId:I.id,combinationKey:q,axisValues:b}),I.measured&&c.push(I.measured)):l.push({combinationKey:q,reason:Ac(I,i)})}for(let[T,$]of e.edgeCases.entries()){let q=`edge:${$.name}`;a({phase:"combination",combinationKey:q,index:T+1,of:e.edgeCases.length});let C=await R(q,`(${$.whereFragment})`);C.id?(u.push({rootRecordId:C.id,combinationKey:q,axisValues:{},edgeCase:$.name}),C.measured&&c.push(C.measured)):l.push({combinationKey:`edge:${$.name}`,reason:C.probed===0?"no record matches the edge-case marker":Ac(C,i)})}f.during="measure",f.combinationKey=void 0,f.candidate=void 0,u.length>0&&a({phase:"measure",roots:u.length});let P=u.length===0?{}:await p(this.deps.measureVolumetry(u.map(T=>T.rootRecordId))),j=Object.values(P).reduce((T,$)=>T+$,0);if(j>s)throw new qt(P,j,s,n);return{roots:u,uncovered:l,volumetry:{measured:P,total:j,budgetMax:s},selectedAt:(this.deps.now?.()??new Date).toISOString()}}async enumerateAxisValues(e,t){let r=Br(e.valuesSoql,t??{}),n=await this.deps.query(r),s=[];for(let i of n){if(!("axisValue"in i))throw new ls(`Axis "${e.name}" query must alias its grouped value as axisValue (e.g. SELECT ${e.filterField} axisValue, COUNT(Id) cnt ... GROUP BY ${e.filterField})`);let d=i.axisValue;d==null?s.push(null):typeof d=="string"?s.push(d):s.push(String(d))}return[...new Set(s)].sort((i,d)=>(i??"").localeCompare(d??""))}async pickHealthyRoot(e,t,r,n,s){let i=t===""?`SELECT Id FROM ${e} ORDER BY Id ASC LIMIT ${Math.max(1,Math.floor(r))}`:`SELECT Id FROM ${e} WHERE ${t} ORDER BY Id ASC LIMIT ${Math.max(1,Math.floor(r))}`,d=await s.step(this.deps.query(Br(i,n??{}))),a=0,u;for(let l of d){let c=l.Id;if(typeof c!="string"||c==="")continue;a++,s.onCandidate(a);let f=await s.step(this.deps.checkHealth.check(c));if(f.healthy)return{id:c,probed:a,...f.measured?{measured:f.measured}:{}};u=f.reason}return{id:null,probed:a,lastReason:u}}};function Ac(o,e){if(o.probed===0)return"no candidate record";let t=`no healthy candidate among the ${o.probed} probed (limit ${e})`;return o.lastReason?`${t} \u2014 last: ${o.lastReason}`:t}var vu=new Set(["int","long","double","currency","percent"]);function Ou(o,e){let t=`'${$e(o)}'`;switch(e){case"boolean":return/^(true|false)$/i.test(o)?o.toLowerCase():t;case"date":return/^\d{4}-\d{2}-\d{2}$/.test(o)?o:t;case"datetime":return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:?\d{2})$/.test(o)?o:t;default:return e!==void 0&&vu.has(e)&&/^-?\d+(\.\d+)?$/.test(o)?o:t}}function Su(o){let e=[[]];for(let{axis:t,values:r}of o){let n=[];for(let s of e)for(let i of r)n.push([...s,{axis:t,value:i}]);e=n}return e}var Zn=class{constructor(e,t){this.measure=e;this.expectedObjects=t}measure;expectedObjects;async check(e){let t;try{t=await this.measure([e])}catch(r){return{healthy:!1,reason:`extraction failed: ${r instanceof Error?r.message:String(r)}`}}for(let r of this.expectedObjects)if((t[r]??0)===0)return{healthy:!1,reason:`no ${r} record in this dossier`};return{healthy:!0,measured:t}}};import*as ur from"node:fs/promises";import*as us from"node:path";var Wr="selection.json";async function Pc(o,e,t){let r=t??new fe,n=r.assertOutsideRepo(o);await ur.mkdir(n,{recursive:!0});let s=r.assertOutsideRepo(us.join(n,Wr));return await ur.writeFile(s,`${JSON.stringify({fileVersion:1,selection:e},null,2)}
18
- `,"utf8"),s}async function fs(o,e){let r=(e??new fe).assertOutsideRepo(us.join(o,Wr)),n=JSON.parse(await ur.readFile(r,"utf8"));if(typeof n!="object"||n===null||n.fileVersion!==1||typeof n.selection!="object")throw new Error(`Invalid selection file at ${r} (expected fileVersion 1)`);return n.selection}import*as fr from"node:fs/promises";import*as ps from"node:path";var Tc="discovery.json",Pu=1440*6e4,Tu=rt({name:De(),fields:yt(rt({name:De(),type:De(),referenceTo:yt(De())}).loose()),childRelationships:yt(rt({childSObject:De(),field:De(),relationshipName:De()}).loose())}).loose(),ju=rt({fileVersion:Gs(1),sourceOrgId:De().min(1),rootObject:De().min(1),maxNodes:Bs().int().positive(),step:Ws(["select","extract"]),discoveredAt:wo.datetime(),schemaStamp:wo.datetime().optional(),graph:rt({nodes:yt(rt({objectApiName:De(),included:sn()}).loose()),edges:yt(rt({sourceObject:De(),targetObject:De()}).loose())}).loose(),describes:qs(De(),Tu),objects:yt(rt({name:De(),keyPrefix:De().nullable()}))});async function jc(o,e,t=new fe){let r=t.assertOutsideRepo(o);await fr.mkdir(r,{recursive:!0});let n=t.assertOutsideRepo(ps.join(r,Tc));return await fr.writeFile(n,`${JSON.stringify(e)}
19
- `,"utf8"),n}async function Fc(o,e=new fe){let t=e.assertOutsideRepo(ps.join(o,Tc)),r;try{r=await fr.readFile(t,"utf8")}catch{return{none:"no graph kept in the sas"}}let n;try{n=JSON.parse(r)}catch{return{none:"the graph kept in the sas could not be read"}}let s=ju.safeParse(n);return s.success?{kept:s.data}:{none:"the graph kept in the sas could not be read"}}function Ec(o,e,t=new Date){if(o.sourceOrgId!==e.sourceOrgId)return"the graph kept is of another org";if(o.rootObject!==e.rootObject)return`the graph kept is of ${o.rootObject}, not ${e.rootObject}`;if(o.maxNodes!==e.maxNodes)return`the graph kept was discovered at a cap of ${o.maxNodes}, not ${e.maxNodes}`;let r=t.getTime()-Date.parse(o.discoveredAt);if(!(r>=0&&r<=Pu))return`the graph kept was discovered on ${o.discoveredAt}, more than a day ago`;if(!o.schemaStamp)return"the org did not give its clock when the graph kept was discovered"}function Lc(o){let e=Date.parse(o);if(!Number.isNaN(e))return new Date(Math.floor(e/1e3)*1e3-1e3).toISOString()}import*as eo from"node:fs/promises";import*as Nc from"node:path";var Fu="SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name FROM RecordType ORDER BY SobjectType, DeveloperName",Eu="rt-map.json",Lu=10;function Nu(o,e){return Ar.has(o)?e:e.map(t=>t.type==="reference"&&t.referenceTo.some(r=>Ar.has(r))?{...t,nillable:!0}:t)}function Wt(o){if(!("attributes"in o))return o;let e={...o};return delete e.attributes,e}var gs=class{constructor(e){this.keyPrefixes=e}keyPrefixes;prefixes=new Map;known=new Set;fromOrg;learnFrom(e){for(let[t,r]of e){let n=r.keys().next();n.done||this.note(t,n.value.slice(0,3))}}async objectsOf(e,t){return t.length<2?t:(!this.known.has(e.slice(0,3))&&this.keyPrefixes&&(this.fromOrg??=this.keyPrefixes().then(r=>{for(let[n,s]of r)this.prefixes.has(n)||this.note(n,s)},()=>{}),await this.fromOrg),ya(e,t,this.prefixes))}note(e,t){this.prefixes.set(e,t),this.known.add(t)}};function Gr(o,e){return e.filter(t=>t.type==="reference"&&Qt(o,t.name,t.nillable)).map(t=>t.name)}function Cu(o,e,t){return{objectApiName:o,recordCount:0,fieldCount:e.length,status:"idle",progress:0,included:!0,piiFields:[],anonymizeFields:[],level:t,successCount:0,failureCount:0,errors:[],createableFieldCount:0,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}}var zu=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/,Qn=class extends Error{constructor(e){super(e),this.name="FrozenExtractionError"}},Ur=class{deps;soqlBuilder=new fa;constructor(e){this.deps=e}query(e){return Si(e,t=>this.deps.query(t))}async extract(e){if(!zu.test(e.asOf))throw new Qn(`asOf must be a strict ISO instant (e.g. 2026-08-03T09:44:52Z), got ${JSON.stringify(e.asOf)}`);if(e.rootRecordIds.length===0)throw new Qn("No root record IDs provided \u2014 empty selection refused");let t=e.guard??new fe,r=t.assertOutsideRepo(e.sasDir),n=`CreatedDate <= ${e.asOf}`,s=new xo;s.add(e.rootObject,e.rootRecordIds),s.addReached(e.rootObject,e.rootRecordIds);let i=new Map,d=new rr,a=new Set,u={},l=new gs(this.deps.keyPrefixes),c=new Map,f=async b=>{let O=c.get(b);if(O)return O;let F=await this.deps.describeFields(b);return c.set(b,F),F},p=async b=>{let O=await f(b);O.some(v=>v.name==="CreatedDate")||a.add(b);let F=O.filter(v=>v.type==="base64").map(v=>v.name);return F.length>0&&(u[b]=F),O},g=new Set(e.excludedObjects??[]),h=await this.withWhatStatusesNeed(ma(e.graph,g),f,g),m=h.graph,w=[...m.nodes].filter(b=>b.included).sort((b,O)=>b.level-O.level),R=new Set(w.map(b=>b.objectApiName));for(let b of w){let O=await p(b.objectApiName),F=this.selectFields(b.objectApiName,O,e.excludedFields),v=O.some(L=>L.name==="CreatedDate"),A=this.soqlBuilder.build({node:b,fields:Nu(b.objectApiName,O),selectFields:F,edges:m.edges,cache:s,rootObjectApiName:`__frozen_root_${e.rootObject}__`,rootRecordId:e.rootRecordIds[0],extraWhere:v?n:void 0,everyEdge:!Ar.has(b.objectApiName),readObjects:R,catalog:Ar,fromAboveOnly:!0});if(!A.scoped)continue;let N=[],M=[];for(let[L,H]of A.statements.entries()){let K=await this.query(H);if(N.push(...K),!(L<A.byIdCount))for(let re of K)typeof re.Id=="string"&&M.push(re.Id)}let B=d.keep(b.objectApiName,await this.keepWhatStatusesNeed(h.added.get(b.objectApiName),N,i),Gr(b.objectApiName,O)),D=i.get(b.objectApiName);D||(D=new Map,i.set(b.objectApiName,D));let G=[];for(let L of B){let H=L.Id;typeof H!="string"||H===""||(G.push(H),D.has(H)||D.set(H,Wt(L)))}s.addRead(b.objectApiName,G);let V=new Set(G);s.addReached(b.objectApiName,M.filter(L=>V.has(L))),l.learnFrom(i);for(let L of O)if(L.type==="reference")for(let H of B){let K=H[L.name];if(!(typeof K!="string"||K===""))for(let re of await l.objectsOf(K,L.referenceTo))s.add(re,[K])}b.objectApiName===e.rootObject&&await this.readWhatTheRootsName({rootObject:e.rootObject,fields:O,selectFields:F,bucket:D,cache:s,owners:l,recordsByObject:i,leftToThePlatform:d,extraWhere:v?n:void 0})}await this.readWhatNamedStatusesNeed({nodes:w,edges:m.edges,cache:s,recordsByObject:i,describe:p,asOfWhere:n,excludedFields:e.excludedFields,leftToThePlatform:d}),await this.completeRequiredParents({...e,graph:m},i,p,n,l,d,g),await Mu(i,p,d);let P=await this.addStandardPrices(e,i,n);await this.addSellingModelOptions({...e,graph:m},i,p,n,g);let j=(i.get(ln)?.size??0)>0,T=await this.exclusionCosts(i,p,g,j),$=await this.leaveOutWhatReadsMasked(i,f),q=[...i.entries()].sort(([b],[O])=>b.localeCompare(O)).map(([b,O])=>{let F=[...O.values()].sort((A,N)=>String(A.Id).localeCompare(String(N.Id)));b===_e&&(F=Vs(F,{sellingModel:j}));let v=F.map((A,N)=>({referenceId:`${b}-${String(N+1).padStart(6,"0")}`,sourceId:String(A.Id),fields:A}));return{objectApiName:b,records:v}}),C=await this.pullRecordTypes(e);await eo.mkdir(r,{recursive:!0});let I=t.assertOutsideRepo(Nc.join(r,Eu));return await eo.writeFile(I,`${JSON.stringify(C,null,2)}
20
- `,"utf8"),{objects:q,asOf:e.asOf,recordTypeMap:C,unboundedObjects:[...a],fileFields:u,...P?{standardPricebookSourceId:P}:{},leftToThePlatform:d.counts(),...T.length>0?{exclusionCosts:T}:{},...$.length>0?{encryptedNotKept:$}:{}}}async leaveOutWhatReadsMasked(e,t){let r=Qi(Zi(s=>this.deps.query(s)),async s=>({fields:await t(s)})),n=[];for(let[s,i]of e)if(i.size!==0)for(let d of await r(s)){let a=!1;for(let u of i.values())d in u&&(a||=u[d]!==null&&u[d]!==void 0,delete u[d]);a&&n.push(`${s}.${d}`)}return n.sort()}async withWhatStatusesNeed(e,t,r){let n=new Set(e.nodes.map(a=>a.objectApiName)),s=new Map,i=[],d=[];for(let a of e.nodes){let u=an[a.objectApiName];if(!a.included||!u||n.has(u.object)||s.has(u.object)||r.has(u.object))continue;let l;try{l=await t(u.object)}catch{continue}let c=l.find(f=>f.name===u.lookup&&f.type==="reference"&&f.referenceTo.includes(a.objectApiName));c&&(s.set(u.object,{parent:a.objectApiName,lookup:c.name}),i.push(Cu(u.object,l,a.level+1)),d.push({sourceObject:a.objectApiName,targetObject:u.object,relationshipName:c.name,type:"lookup",required:Qt(u.object,c.name,c.nillable)}))}return s.size===0?{graph:e,added:s}:{graph:{...e,nodes:[...e.nodes,...i],edges:[...e.edges,...d]},added:s}}async readWhatTheRootsName(e){let{rootObject:t,bucket:r,cache:n}=e,s=new Set([...n.get(t)??[]].filter(a=>!r.has(a)));if(s.size===0)return;let i=[];for(let a of this.soqlBuilder.buildById({objectApiName:t,selectFields:e.selectFields,ids:s,extraWhere:e.extraWhere}))i.push(...await this.query(a));let d=e.leftToThePlatform.keep(t,i,Gr(t,e.fields));for(let a of d)typeof a.Id=="string"&&!r.has(a.Id)&&r.set(a.Id,Wt(a));e.owners.learnFrom(e.recordsByObject);for(let a of e.fields)if(a.type==="reference")for(let u of d){let l=u[a.name];if(!(typeof l!="string"||l===""))for(let c of await e.owners.objectsOf(l,a.referenceTo))n.add(c,[l])}}async keepWhatStatusesNeed(e,t,r){if(!e)return t;let n=xt[e.parent],s=n?await or(d=>this.query(d),n):void 0,i=new Set;for(let[d,a]of r.get(e.parent)??[])s&&sr(a.Status,s)&&i.add(d);return t.filter(d=>{let a=d[e.lookup];return typeof a=="string"&&i.has(a)})}async readWhatNamedStatusesNeed(e){for(let[t,r]of Object.entries(an)){let n=e.nodes.find(m=>m.objectApiName===r.object),s=e.recordsByObject.get(t),i=xt[t];if(!n||!s||s.size===0||!i)continue;let d=e.cache.reachedOf(t),a=[...s].filter(([m])=>!d?.has(m));if(a.length===0)continue;let u=await or(m=>this.query(m),i);if(!u)continue;let l=a.filter(([,m])=>sr(m.Status,u)).map(([m])=>m);if(l.length===0)continue;let c=await e.describe(r.object),f=new xo;f.addRead(t,l);let p=this.soqlBuilder.build({node:n,fields:c,selectFields:this.selectFields(r.object,c,e.excludedFields),edges:e.edges,cache:f,rootObjectApiName:`__frozen_root_${t}__`,rootRecordId:l[0],extraWhere:c.some(m=>m.name==="CreatedDate")?e.asOfWhere:void 0,under:new Set([t])});if(!p.scoped)continue;let g=e.recordsByObject.get(r.object);g||(g=new Map,e.recordsByObject.set(r.object,g));let h=Gr(r.object,c);for(let m of p.statements){let w=e.leftToThePlatform.keep(r.object,await this.query(m),h);for(let R of w)typeof R.Id=="string"&&!g.has(R.Id)&&g.set(R.Id,Wt(R))}}}async completeRequiredParents(e,t,r,n,s,i,d){let a=new Set(e.graph.nodes.filter(f=>f.included).map(f=>f.objectApiName)),u=ha(e.graph,d),l=f=>a.has(f)||u.has(f),c=new Map;for(let f=0;f<Lu;f++){s.learnFrom(t);let p=new Map;for(let[g,h]of t){let m=(await r(g)).filter(w=>w.type==="reference"&&ga(g,w));for(let w of h.values())for(let R of m){let P=w[R.name];if(typeof P!="string"||P===""||i.has(P)||!R.referenceTo.some(l))continue;let j=(await s.objectsOf(P,R.referenceTo)).filter(l);for(let T of j)t.get(T)?.has(P)||c.get(T)?.has(P)||p.set(T,(p.get(T)??new Set).add(P))}}if(p.size===0)return;for(let[g,h]of p){c.set(g,new Set([...c.get(g)??[],...h]));let m=await r(g),w=t.get(g);w||(w=new Map,t.set(g,w));let R=this.soqlBuilder.buildById({objectApiName:g,selectFields:this.selectFields(g,m,e.excludedFields),ids:h,extraWhere:m.some(j=>j.name==="CreatedDate")?n:void 0}),P=Gr(g,m);for(let j of R)for(let T of i.keep(g,await this.query(j),P))typeof T.Id=="string"&&!w.has(T.Id)&&w.set(T.Id,Wt(T))}}}async addStandardPrices(e,t,r){let n=t.get(_e);if(!n||n.size===0)return;let[s]=await this.query(Ct),i=typeof s?.Id=="string"?s.Id:void 0;if(!i)return;let d=g=>[qe,Xe,er].map(h=>String(g[h]??"")).join("|"),a=new Set,u=new Set;for(let g of n.values()){if(g[wt]===i)continue;let h=g[qe];typeof h=="string"&&h!==""&&(a.add(h),u.add(d(g)))}if(a.size===0)return;let l=async(g,h)=>{let m=await this.deps.describeFields(g),w=this.selectFields(g,m,e.excludedFields).map(P=>me(P)).join(", "),R=m.some(P=>P.name==="CreatedDate")?` AND ${r}`:"";return this.query(`SELECT ${w} FROM ${g} WHERE ${h}${R}`)},c=t.get(dn);if(c||(c=new Map,t.set(dn,c)),!c.has(i))for(let g of await l(dn,`Id = '${$e(i)}'`))c.set(i,Wt(g));let f=await this.deps.describeFields(_e),p=this.soqlBuilder.buildJoining({objectApiName:_e,selectFields:this.selectFields(_e,f,e.excludedFields),split:{field:qe,ids:a},whole:{field:wt,ids:new Set([i])},extraWhere:f.some(g=>g.name==="CreatedDate")?r:void 0});for(let g of p)for(let h of await this.query(g))typeof h.Id!="string"||n.has(h.Id)||u.has(d(h))&&n.set(h.Id,Wt(h));return i}async addSellingModelOptions(e,t,r,n,s){if(s.has(xe)||e.graph.nodes.some(m=>m.objectApiName===xe&&!m.included))return;let i=t.get(_e),d=t.get(pa),a=t.get(ln);if(!i||!d||!a)return;let u=m=>`${String(m[qe]??"")}|${String(m[Xe]??"")}`,l=new Set,c=new Set,f=new Set;for(let m of i.values()){let w=m[qe],R=m[Xe];typeof w!="string"||!d.has(w)||typeof R!="string"||!a.has(R)||(l.add(w),c.add(R),f.add(u(m)))}if(f.size===0)return;let p=await r(xe),g=this.soqlBuilder.buildJoining({objectApiName:xe,selectFields:this.selectFields(xe,p,e.excludedFields),split:{field:qe,ids:l},whole:{field:Xe,ids:c},extraWhere:p.some(m=>m.name==="CreatedDate")?n:void 0}),h=t.get(xe);h||(h=new Map,t.set(xe,h));for(let m of g)for(let w of await this.query(m))typeof w.Id!="string"||h.has(w.Id)||f.has(u(w))&&h.set(w.Id,Wt(w))}async exclusionCosts(e,t,r,n){if(r.size===0)return[];let s=[],i=a=>`record${a===1?"":"s"}`,d=new Map;for(let[a,u]of e){if(u.size===0)continue;let l=(await t(a)).filter(g=>g.type==="reference"&&g.referenceTo.length===1&&g.referenceTo[0]!==a&&r.has(g.referenceTo[0])&&Qt(a,g.name,g.nillable)),c=a===_e&&n&&r.has(xe);if(l.length===0&&!c)continue;let f=new Map,p=new Map;for(let[g,h]of u){let m;for(let P of l){let j=h[P.name],T=P.referenceTo[0];if(!(typeof j!="string"||j==="")&&!e.get(T)?.has(j)){m={field:P.name,excluded:T};break}}let w=h[Xe];if(!m&&c&&typeof w=="string"&&e.get(ln)?.has(w)&&(m={field:Xe,excluded:xe}),!m)continue;f.set(g,m.excluded);let R=p.get(m.excluded)??{field:m.field,count:0};R.count++,p.set(m.excluded,R)}f.size>0&&d.set(a,f);for(let[g,{field:h,count:m}]of p)s.push({objectApiName:a,excludedObject:g,count:m,note:g===xe?`${m} ${a} ${i(m)} sold under a selling model cannot be loaded without the option that sells the product under it, and excludedObjects leaves ${g} out`:`${m} ${a} ${i(m)} cannot be loaded without the ${g} named by ${h}, which excludedObjects leaves out`})}for(let[a,u]of Object.entries(an)){let l=e.get(a),c=xt[a];if(!l||l.size===0||!c)continue;let f=await or(w=>this.query(w),c);if(!f)continue;let p=new Set,g=new Map,h=d.get(u.object);for(let[w,R]of e.get(u.object)??[]){let P=R[u.lookup];if(typeof P!="string")continue;let j=h?.get(w);j?g.has(P)||g.set(P,j):p.add(P)}let m=new Map;for(let[w,R]of l){if(!sr(R.Status,f))continue;let P=r.has(u.object)?u.object:p.has(w)?void 0:g.get(w);P&&m.set(P,(m.get(P)??0)+1)}for(let[w,R]of m){let P=R===1;s.push({objectApiName:a,excludedObject:w,count:R,note:`${R} ${a} ${i(R)} past Draft will be loaded as ${P?"a draft":"drafts"} and stay so: `+(w===u.object?`the platform gives ${a} this status only with ${u.object} records under it, and excludedObjects leaves ${u.object} out`:`none of ${P?"its":"their"} ${u.object} records can be loaded without ${w}, which excludedObjects leaves out`)})}}return s}selectFields(e,t,r){let n=new Set(r?.[e]??[]),s=t.map(i=>i.name).filter(i=>!n.has(i));return s.includes("Id")||s.unshift("Id"),s}async pullRecordTypes(e){let t=e.recordTypesSoqlTemplate??Fu,r=Br(t,e.tokens??{}),n=await this.query(r),s=[];for(let i of n)typeof i.Id=="string"&&typeof i.SobjectType=="string"&&typeof i.DeveloperName=="string"&&typeof i.Name=="string"&&s.push({id:i.Id,sobjectType:i.SobjectType,developerName:i.DeveloperName,..."NamespacePrefix"in i?{namespacePrefix:typeof i.NamespacePrefix=="string"&&i.NamespacePrefix!==""?i.NamespacePrefix:null}:{},name:i.Name});return s}};async function Mu(o,e,t){for(let r=!0;r;){r=!1;for(let[n,s]of o){let i=[...s.values()],d=Gr(n,await e(n)),a=t.keep(n,i,d);if(a.length===i.length)continue;r=!0;let u=new Set(a.map(l=>l.Id));for(let l of s.keys())u.has(l)||s.delete(l)}}}var to=class{anonymize(e){let{rules:t,pseudonymizer:r}=e,n=Object.entries(e.extracted.fileFields??{}).filter(([c,f])=>f.some(p=>ut(t,c,p)!=="keep")).map(([c])=>c).filter(c=>e.extracted.objects.some(f=>f.objectApiName===c&&f.records.length>0)).sort(),s={...e.extracted,objects:e.extracted.objects.filter(c=>!n.includes(c.objectApiName))},i=new Map;for(let c of s.objects)for(let f of c.records)i.set(f.sourceId,f.referenceId);let d=new Map(s.recordTypeMap.map(c=>[c.id,c])),a={};for(let c of s.objects)a[c.objectApiName]=s.recordTypeMap.filter(f=>f.sobjectType===c.objectApiName).map(f=>({name:f.name,developerName:f.developerName,...f.namespacePrefix!==void 0?{namespacePrefix:f.namespacePrefix}:{}}));let u=[];for(let c of s.objects){let f=c.records.map(p=>{let g=this.anonymizeRecordFields(c.objectApiName,p.fields,i,d,t,r),h=p.fields.RecordTypeId,m=typeof h=="string"?d.get(h):void 0;return{referenceId:p.referenceId,fields:g,...m?{recordTypeDeveloperName:ct(m.namespacePrefix,m.developerName)}:{}}});u.push({objectApiName:c.objectApiName,records:f})}let l=s.standardPricebookSourceId?i.get(s.standardPricebookSourceId):void 0;return{datasetVersion:e.datasetVersion,objects:u,recordTypes:a,personContactSidecar:Du(s,i),...l?{standardPricebook:l}:{},...n.length>0?{filesLeftOut:n}:{}}}anonymizeRecordFields(e,t,r,n,s,i){let d={};for(let[a,u]of Object.entries(t)){if(a==="Id")continue;if(u==null){d[a]=u;continue}if(a==="RecordTypeId"&&typeof u=="string"){let c=n.get(u);d[a]=c?c.name:"";continue}if(typeof u=="string"){let c=r.get(u);if(c!==void 0){d[a]=c;continue}}let l=ut(s,e,a);d[a]=i.pseudonymize(l,u)}for(let[a,u]of Object.entries(d))typeof u=="string"&&kn(u)&&(d[a]="");return d}};function Du(o,e){let t=[],r=o.objects.find(n=>n.objectApiName==="Account");if(!r)return t;for(let n of r.records){let s=n.fields.PersonContactId;if(typeof s!="string"||s==="")continue;let i=e.get(s);i!==void 0&&t.push({accountReferenceId:n.referenceId,contactReferenceId:i})}return t}var xu=/^[A-Z]{2}-\d{3}-[A-Z]{2}$/,$u=/^\+3363998\d{4}$/,_u=/^[a-z0-9-]+@example\.invalid$/,Bu=/^\d{2}0+$/,qu=3,ro=class{run(e,t,r,n={}){let s=new Set,i=new Map;for(let c of t.objects)for(let f of c.records)s.add(f.referenceId),i.set(f.referenceId,{objectApiName:c.objectApiName,record:f});let d={substitution:[],"clear-empty":[],formats:[],"no-residual-id":[]},a=new Map(e.recordTypeMap.map(c=>[c.id,[c.name,c.developerName]])),u=new Set(t.filesLeftOut??[]);for(let c of e.objects)if(!u.has(c.objectApiName))for(let f of c.records){let p=i.get(f.referenceId);if(!p){d.substitution.push({check:"substitution",objectApiName:c.objectApiName,referenceId:f.referenceId,detail:"record missing from the frozen dataset"});continue}let g=f.fields.RecordTypeId;this.checkSubstitution(c.objectApiName,f,p.record,r,d.substitution,new Set(typeof g=="string"?a.get(g)??[]:[]))}for(let c of t.objects)for(let f of c.records)this.checkClearEmpty(c.objectApiName,f,r,s,d["clear-empty"]),this.checkNoResidualId(c.objectApiName,f,s,d["no-residual-id"]);this.checkFormats(e,t,r,i,d.formats);let l=["substitution","clear-empty","formats","no-residual-id"].map(c=>({name:c,passed:d[c].length===0,violations:d[c]}));return{passed:l.every(c=>c.passed),checks:l,author:n.author??"frozen-dataset-engine",checkedAt:(n.now?.()??new Date).toISOString()}}checkSubstitution(e,t,r,n,s,i){for(let[d,a]of Object.entries(t.fields)){if(d==="Id"||a===null||a===void 0||a===""||ut(n,e,d)==="keep")continue;let l=r.fields[d];if(Wu(l,a)){s.push({check:"substitution",objectApiName:e,referenceId:t.referenceId,field:d,detail:"original value still present in its own field"});continue}if(typeof a=="string"&&a.length>=qu)for(let[c,f]of Object.entries(r.fields))c===d||typeof f!="string"||f!==a||ut(n,e,c)==="keep"||c==="RecordTypeId"&&i.has(f)||s.push({check:"substitution",objectApiName:e,referenceId:t.referenceId,field:c,detail:`transversal leak: original value of "${d}" found in "${c}"`})}}checkClearEmpty(e,t,r,n,s){for(let[i,d]of Object.entries(t.fields))i!=="RecordTypeId"&&(typeof d=="string"&&n.has(d)||ut(r,e,i)==="clear"&&d!==""&&d!==null&&d!==void 0&&s.push({check:"clear-empty",objectApiName:e,referenceId:t.referenceId,field:i,detail:`residual value under "clear" generator: ${JSON.stringify(d)}`}))}checkFormats(e,t,r,n,s){let i={registrationSIV:d=>xu.test(d),phoneE164:d=>$u.test(d),email:d=>_u.test(d),postalCodeGeneralize:(d,a)=>Bu.test(d)&&d.length===a.trim().length};for(let d of e.objects)for(let a of d.records){let u=n.get(a.referenceId);if(u)for(let[l,c]of Object.entries(a.fields)){if(typeof c!="string"||c==="")continue;let f=ut(r,d.objectApiName,l),p=i[f];if(!p)continue;let g=u.record.fields[l];typeof g!="string"||g===""||p(g,c)||s.push({check:"formats",objectApiName:d.objectApiName,referenceId:a.referenceId,field:l,detail:`format not conserved for ${f}: ${JSON.stringify(g)}`})}}}checkNoResidualId(e,t,r,n){for(let[s,i]of Object.entries(t.fields))typeof i=="string"&&kn(i)&&n.push({check:"no-residual-id",objectApiName:e,referenceId:t.referenceId,field:s,detail:"checksum-valid Salesforce ID survived the sweep"})}};function Wu(o,e){return o===e?!0:o==null||e===null||e===void 0?!1:String(o)===String(e)}var Kr=class{constructor(e){this.orgAccess=e}orgAccess;cache=new Map;describes=new Map;async resolveByDeveloperName(e,t,r,n){let s=n===void 0?Ti(r):{namespacePrefix:n,developerName:r},i=`${e}|${t}|${String(s.namespacePrefix)}|${s.developerName}`,d=this.cache.get(i);if(d!==void 0)return d;let a=`SELECT Id, DeveloperName, NamespacePrefix FROM RecordType WHERE SobjectType = '${$e(t)}' AND DeveloperName = '${$e(s.developerName)}'`,u=Pi(await this.orgAccess.query(e,a)),l=ji(s,u,Oo),c;if("ambiguous"in l)c={ambiguous:!0,carriers:l.ambiguous.map(Oo)};else if("found"in l){let f=l.found.id;c=await this.isUnavailable(e,t,f)?{unavailable:!0,id:f}:f}else c=null;return this.cache.set(i,c),c}async isUnavailable(e,t,r){let n=this.describeOf(e,t);return n?(await n).recordTypeInfos?.find(i=>i.recordTypeId===r)?.available===!1:!1}async givenRecordType(e,t){let r=this.describeOf(e,t);if(r)return Nn(Rn((await r).recordTypeInfos))}describeOf(e,t){let r=this.orgAccess.describe;if(!r)return;let n=`${e}|${t}`,s=this.describes.get(n);return s||(s=r(e,t),this.describes.set(n,s)),s}};import*as so from"node:fs";var Gu=2e3,Uu=3,Ku=10,Vu=o=>new Promise(e=>setTimeout(e,o)),no=class{constructor(e){this.deps=e;this.sasGuard=e.sasGuard??new fe}deps;sasGuard;personAccounts=new Map;async verify(e){let t=e.now??(()=>new Date),r=e.sleep??Vu,n=g=>e.onProgress?.(g),s=e.measurementIntervalMs??Gu,i=e.maxAttempts??Uu,d=Mn(this.sasGuard,e.contractPath);n({phase:"verify",status:"started",progress:0,message:"Measuring org state"});let a=null,u=null,l=null,c=0;for(let g=1;g<=i;g++){c=g,l=await this.measure(e,d);let h=hs(l);if(a!==null&&h===a){u=l;break}a=h,g<i&&await r(s)}let f=this.buildChecks(e,d,u??l,u!==null),p={status:Qu(f,d,u),checks:f,attempts:c,measuredAt:t().toISOString(),objects:ef(d,u??l)};return e.manifestPath&&(this.consignVerdict(e.manifestPath,p,e.author),p.manifestPath=this.sasGuard.assertOutsideRepo(e.manifestPath)),n({phase:"verify",status:p.status==="passed"?"done":"error",progress:100,message:`Post-load verification: ${p.status} (${c} measurement(s))`}),p}async measure(e,t){return{counts:await this.measureCounts(e,t),orphans:await this.measureOrphans(e,t),personContact:await this.measurePersonContacts(e),presence:await this.measurePresence(e,t)}}async measureCounts(e,t){let r=e.mapping?zc(e.mapping):void 0,n={};for(let s of Object.keys(t.objects).sort()){let i=`SELECT COUNT() FROM ${me(s)}`;if(!r){n[s]=await this.deps.orgAccess.count(e.orgId,i);continue}let d=0;for(let a of Mc(r.get(s)??[]))d+=await this.deps.orgAccess.count(e.orgId,`${i} WHERE ${a}`);n[s]=d}return n}async measureOrphans(e,t){let r={},n=e.orphanSampleSize??Ku,s=e.mapping?zc(e.mapping):void 0;for(let[i,d]of Object.entries(e.mandatoryLookups??{}))for(let a of d){let u=new Set([...Cc(t,i,a),...ms(t.objects[i]?.parentNotLoaded,a)].flatMap(f=>{let p=e.mapping?.get(f);return p===void 0?[]:[p]})),l=s?Mc((s.get(i)??[]).filter(f=>!u.has(f))):[""],c=[];for(let f of l){let p=`SELECT Id FROM ${me(i)} WHERE ${me(a)} = null${f?` AND ${f}`:""} ORDER BY Id LIMIT ${n}`,g=await this.deps.orgAccess.query(e.orgId,p);c.push(...g.map(h=>String(h.Id)))}r[`${i}.${a}`]=c.sort().slice(0,n)}return r}async measurePersonContacts(e){let t=e.dataset?.personContactSidecar??[];if(t.length===0||!e.mapping)return{checked:0,unrestored:[]};let r=t.filter(a=>e.mapping?.has(a.accountReferenceId));if(r.length===0||!await this.describesPersonAccounts(e.orgId))return{checked:0,unrestored:[]};let n=r.map(a=>e.mapping?.get(a.accountReferenceId)),s=await wn(a=>this.deps.orgAccess.query(e.orgId,a),n),i=[],d=0;for(let a of r){let u=e.mapping.get(a.accountReferenceId),l=s.get(u);l!==void 0&&(d++,e.mapping.get(a.contactReferenceId)!==l&&i.push(a.accountReferenceId))}return{checked:d,unrestored:i.sort()}}describesPersonAccounts(e){let t=this.personAccounts.get(e);if(!t){let r=this.deps.orgAccess.describe;t=r?r.call(this.deps.orgAccess,e,"Account").then(n=>n.fields.some(s=>s.name==="PersonContactId")).catch(()=>!0):Promise.resolve(!0),this.personAccounts.set(e,t)}return t}async measurePresence(e,t){let r={};if(!e.dataset)return r;for(let[n,s]of Object.entries(e.presenceKeys??{})){let i=new Set(Cc(t,n,s)),d=(e.dataset.objects.find(l=>l.objectApiName===n)?.records??[]).filter(l=>!i.has(l.referenceId)),a=[...new Set(d.map(l=>l.fields[s]).filter(l=>typeof l=="string"&&l!==""))].sort();if(a.length===0){r[n]=[];continue}let u=new Set;for(let l=0;l<a.length;l+=oo){let c=a.slice(l,l+oo).map(p=>`'${$e(p)}'`).join(", "),f=await this.deps.orgAccess.query(e.orgId,`SELECT ${me(s)} k FROM ${me(n)} WHERE ${me(s)} IN (${c})`);for(let p of f)u.add(String(p.k))}r[n]=a.filter(l=>!u.has(l))}return r}buildChecks(e,t,r,n){let s=[];if(s.push({name:"stability",passed:n,detail:n?"Two identical consecutive measurements \u2014 org reads are stable":"No two identical measurements within the attempt budget \u2014 org reads are transiently inconsistent"}),!r)return s;let i=Object.entries(t.objects).filter(([f,p])=>r.counts[f]!==p.expected).map(([f,p])=>`${f}: expected ${p.expected}, got ${r.counts[f]??0}`);s.push({name:"counts",passed:i.length===0,detail:i.length===0?"All object counts match the counting contract":`Count mismatches \u2014 ${i.join("; ")}`});let d=Dc(t),a=Hu(t,r);s.push({name:"load",passed:d.records===0&&a.length===0,detail:Ju(d,a)});let u=Object.entries(r.orphans).filter(([,f])=>f.length>0),l=Zu(t),c=[...u.length>0?[`Orphans \u2014 ${u.map(([f,p])=>`${f} (${p.length}: ${p.join(", ")})`).join("; ")}`]:[],...l.length>0?["Lookups the load left empty because the record they name was not loaded \u2014 "+l.map(({link:f,count:p})=>`${f} (${p})`).join("; ")]:[]];if(s.push({name:"orphans",passed:c.length===0,detail:c.length===0?"No orphans on the mandatory lookups of the graph":c.join("; ")}),(e.dataset?.personContactSidecar?.length??0)>0&&e.mapping&&s.push({name:"personcontact",passed:r.personContact.unrestored.length===0,detail:r.personContact.unrestored.length===0?`All ${r.personContact.checked} person account(s) hold the contact the load linked`:`Person accounts without the contact the load linked \u2014 accounts: ${r.personContact.unrestored.join(", ")}`}),e.dataset&&Object.keys(e.presenceKeys??{}).length>0){let f=Object.entries(r.presence).filter(([,p])=>p.length>0);s.push({name:"presence",passed:f.length===0,detail:f.length===0?"All referential keys present in the org":`Missing keys \u2014 ${f.map(([p,g])=>`${p}: ${g.join(", ")}`).join("; ")}`})}return s}consignVerdict(e,t,r){let n=this.sasGuard.assertOutsideRepo(e),s=Fr(JSON.parse(so.readFileSync(n,"utf8")));s.controls.dryRunLoad={status:t.status==="passed"?"passed":"failed",at:t.measuredAt,detail:`post-load check by ${r??"unknown"}: verdict=${t.status}; `+t.checks.map(i=>`${i.name}=${i.passed?"OK":"KO"}`).join(", ")},so.writeFileSync(n,_n(s),"utf8")}};function hs(o){return Array.isArray(o)?`[${o.map(hs).join(",")}]`:typeof o=="object"&&o!==null?`{${Object.entries(o).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${hs(r)}`).join(",")}}`:JSON.stringify(o)}function Cc(o,e,t){return ms(o.objects[e]?.writtenWithout,t)}function ms(o,e){let t=o?.[e];return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}var Vr={refused:["dml-failed","person-contact-not-sent"],heldBack:["parent-refused"],notLoadable:["object-not-loaded"]};function Dc(o){let e={whole:[],part:[],refused:0,heldBack:0,notLoadable:[],records:0};for(let[t,r]of Object.entries(o.objects).sort(([n],[s])=>n.localeCompare(s))){let n=u=>u.reduce((l,c)=>l+(r.exclusionReasons[c]??0),0),s=n(Vr.notLoadable);s>0&&e.notLoadable.push({objectApiName:t,records:s});let i=n(Vr.refused),d=n(Vr.heldBack),a=i+d;a!==0&&(e.refused+=i,e.heldBack+=d,e.records+=a,r.expected===0?e.whole.push({objectApiName:t,notLoaded:a}):e.part.push({objectApiName:t,notLoaded:a,of:a+r.expected}))}return e}function Hu(o,e){return Object.entries(o.objects).sort(([t],[r])=>t.localeCompare(r)).flatMap(([t,r])=>{let n=e.counts[t]??0;return n<r.expected?[{objectApiName:t,gone:r.expected-n,of:r.expected}]:[]})}function Yu(o){return o.length===0?"":`${o.reduce((t,r)=>t+r.gone,0)} record(s) it wrote or linked are no longer in the target \u2014 `+o.map(t=>`${t.objectApiName} (${t.gone} of ${t.of})`).join(", ")}function Ju(o,e=[]){let t=Xu(o),r=Yu(e);if(o.records===0)return r===""?`Every record the load had to write went in${t}`:`The load wrote every record it had to, and ${r}${t}`;let n=[...o.whole.length>0?["Objects the load wrote none of \u2014 "+o.whole.map(i=>`${i.objectApiName} (${i.notLoaded} not loaded)`).join(", ")]:[],...o.part.length>0?["Objects it wrote part of \u2014 "+o.part.map(i=>`${i.objectApiName} (${i.notLoaded} of ${i.of} not loaded)`).join(", ")]:[]],s=[...o.refused>0?[`${o.refused} refused by the target org`]:[],...o.heldBack>0?[`${o.heldBack} held back for a parent the target org refused`]:[]];return`${o.records} record(s) not loaded: ${s.join(", ")}. ${n.join("; ")}${r===""?"":`; ${r}`}${t}`}function Xu(o){return o.notLoadable.length===0?"":`; ${o.notLoadable.reduce((t,r)=>t+r.records,0)} record(s) not loadable, as the simulation said \u2014 `+o.notLoadable.map(t=>`${t.objectApiName} (${t.records})`).join(", ")}function Zu(o){let e=[];for(let[t,r]of Object.entries(o.objects).sort(([n],[s])=>n.localeCompare(s)))for(let n of Object.keys(r.parentNotLoaded??{}).sort()){let s=ms(r.parentNotLoaded,n).length;s>0&&e.push({link:`${t}.${n}`,count:s})}return e}function Qu(o,e,t){if(t===null)return"unstable";let r=o.filter(i=>!i.passed);if(r.length===0)return"passed";let n=Object.values(t.orphans).some(i=>i.length>0);return r.every(i=>i.name==="load"||i.name==="orphans")&&!n&&Dc(e).whole.length===0?"partial":"failed"}function ef(o,e){let t=r=>r.slice(0,r.indexOf("."));return Object.entries(o.objects).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>{let s=[...Vr.refused,...Vr.heldBack].reduce((c,f)=>c+(n.exclusionReasons[f]??0),0),i=e?.counts[r]??0,d=Object.entries(e?.orphans??{}).filter(([c])=>t(c)===r).reduce((c,[,f])=>c+f.length,0),a=e?.presence[r]?.length??0,u=r==="Account"?e?.personContact.unrestored.length??0:0,l=e!==null&&i===n.expected&&s===0&&d===0&&a===0&&u===0;return{objectApiName:r,status:l?"passed":"failed",expected:n.expected,found:i,notLoaded:s,orphans:d,missingKeys:a,...u>0?{personContactsUnlinked:u}:{}}})}var oo=200;function zc(o){let e=new Map;for(let[t,r]of o){let n=t.startsWith("placeholder:")?t.split(":")[1]:t.slice(0,t.lastIndexOf("-"));if(!n)continue;let s=e.get(n)??[];s.push(r),e.set(n,s)}return e}function Mc(o){let e=[];for(let t=0;t<o.length;t+=oo){let r=o.slice(t,t+oo).map(n=>`'${$e(n)}'`);e.push(`Id IN (${r.join(", ")})`)}return e}var ws=200;function bs(o,e=ws){return{insert:(t,r,n,s)=>ys(o.insert(r,n,e,s?tf(s):void 0)),update:(t,r,n)=>ys(o.update(r,n,e)),delete:(t,r,n)=>ys(o.delete(r,n,e))}}function tf(o){let e=0,t=0;return{sending:(r,n,s)=>{t=s},answered:(r,n,s,i)=>{i?s.forEach((d,a)=>{let u=i[a];u!==void 0&&o(u,[d])}):(o(e,s),e+=t),t=0}}}async function ys(o){try{return await o}catch(e){if(e instanceof ld)return e.written;throw e}}var rf=200;function xc(o){let e={threshold:o.threshold,perCall:ws,...o.duplicateRules?{duplicateRules:o.duplicateRules}:{}},t=o.inserts.filter(({rows:n})=>n>0),r=t.reduce((n,{rows:s})=>n+Math.ceil(s/rf),0);return Bo(t,e)+Bo((o.purged??[]).filter(({rows:n})=>n>0),e)+fd(t.length,o.automationRead??0)+r}function ae(o){return o.slice(0,15)}var Bc=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function Re(o){return $i(o)??o}function $c(o,e){return`${o}-${Re(e)}`}var Rs="005",ks="00G",qc="00D",Is="00e",Wc="OwnerId",As="RecordTypeId",vs="SetupOwnerId",Yr="CurrencyIsoCode",ao="Pricebook2",Gt=200,Os=new Set([...va,No]),nf=["Title","Name"];async function*Ss(o,e){let t=await Eo.read(o.folder,o.checkpoint.snapshotId,e);for await(let r of t.records())typeof r.Id=="string"&&(yield r)}async function of(o,e){let t=await Eo.read(o.folder,o.checkpoint.snapshotId,e),r=[];for(let n=0;n<t.size;n++)r.push(t.idAt(n));return r}function co(o,e){return o!==void 0&&!o.unread.some(t=>t.part===e)}async function sf(o){let e=vd(o.checkpoint,o.choices),t=new Map;for(let p of o.checkpoint.objects)for(let g of await of(o,p.objectApiName))t.set(ae(g),p.objectApiName);let r=new Set,n=new Set,s=new Set,i=new Set,d=new Map,a=new Set,u=[],l=new Set;for(let p of e.replayed)for await(let g of Ss(o,p.objectApiName)){l.add(ae(g.Id));for(let[h,m]of Object.entries(g)){if(Os.has(h)||typeof m!="string"||(h===Yr&&m!==""&&a.add(m),!Bc.test(m)))continue;let w=ae(m);if(h===As)s.add(w);else if(w.startsWith(Rs))r.add(w);else if(w.startsWith(ks)&&h===Wc)n.add(w);else if(w.startsWith(Is)&&h===vs)i.add(w);else if(!t.has(w)&&!w.startsWith(qc)){let R=`${p.objectApiName}.${h}`,P=d.get(R)??new Set;P.add(w),d.set(R,P)}}if(p.objectApiName===_e){let h=g[wt],m=g[qe];if(typeof h=="string"&&typeof m=="string"){let w=g[er];u.push({book:ae(h),product:ae(m),currency:typeof w=="string"?w:""})}}}let c=[];if((o.checkpoint.files?.links??0)>0)for await(let p of Oa(o.folder))l.has(ae(p.LinkedEntityId))&&c.push({ContentDocumentId:p.ContentDocumentId,LinkedEntityId:p.LinkedEntityId,ShareType:p.ShareType,Visibility:p.Visibility});let f=[];for(let p of e.leftOut)if(p.reason==="fileContentNotKept")for await(let g of Ss(o,p.objectApiName)){let h=nf.map(m=>g[m]).find(m=>typeof m=="string"&&m!=="");f.push({objectApiName:p.objectApiName,id:Re(g.Id),...h!==void 0?{name:h}:{}})}return{objects:e,heldBy:t,users:r,queues:n,recordTypes:s,profiles:i,notHeld:d,currencies:a,standardPricebook:af(o,u,t),fileLinks:c,filesLeft:f}}function af(o,e,t){let r=o.checkpoint.objects.some(a=>a.objectApiName===ao||a.objectApiName===_e);if(co(o.annex,"standardPricebook")&&o.annex.standardPricebookId)return{id:Re(o.annex.standardPricebookId),how:"annex"};let n=e.filter(a=>t.has(a.product));if(n.length===0||!r)return{how:"none"};let s=new Set(n.map(a=>`${a.product}|${a.currency}`)),i=new Map;for(let a of n){let u=i.get(a.book)??new Set;u.add(`${a.product}|${a.currency}`),i.set(a.book,u)}let d=[...i].filter(([,a])=>a.size===s.size).map(([a])=>a);return d.length===1?{id:Re(d[0]),how:"deduced"}:{how:"ambiguous"}}function Hr(o,e){let t=[];for(let r=0;r<o.length;r+=e)t.push(o.slice(r,r+e));return t}function io(o){return o.map(e=>`'${$e(e)}'`).join(", ")}function Gc(o){let e=o.lastIndexOf("@"),t=o.lastIndexOf("."),r=o.slice(e+1);return e>=0&&t>e&&r.split(".").length>2?o.slice(0,t):o}function df(o){if(o===void 0)return;let e=Gc(o);return e===o?void 0:o.slice(e.length)}async function cf(o){let{access:e,orgId:t,survey:r,source:n}=o,s=0,i=async v=>(s++,e.query(t,v)),d=new Map,a=new Map,u=async v=>{s++;try{d.set(v,await e.describe(t,v))}catch(A){a.set(v,Q(A))}};for(let v of r.objects.replayed)await u(v.objectApiName);r.fileLinks.length>0&&await u(ir);let l=new Map,c=v=>typeof v.Id=="string"&&typeof v.Username=="string"?{id:Re(v.Id),username:v.Username,isActive:v.IsActive===!0,userType:typeof v.UserType=="string"?v.UserType:""}:void 0,f=[...new Set([...r.users,...Object.values(n.choices.ownerMap??{}).map(ae)])].sort();for(let v of Hr(f,Gt))for(let A of await i(`SELECT Id, Username, IsActive, UserType FROM User WHERE Id IN (${io(v)})`)){let N=c(A);N&&l.set(ae(N.id),N)}let p=new Map;if(co(n.annex,"users")){let v=o.tier==="sandbox"?df(o.username):void 0,A=new Map;for(let B of n.annex.users){let D=ae(B.id),G=l.get(D);if(G?.isActive===!0&&G.userType==="Standard")continue;let V=n.checkpoint.org.tier==="sandbox"?Gc(B.username):B.username,L=[B.username,V,...v!==void 0?[`${V}${v}`]:[]];A.set(D,[...new Set(L.map(H=>H.toLowerCase()))])}let N=[...new Set([...A.values()].flat())].sort(),M=new Map;for(let B of Hr(N,Gt)){let D=B.map(G=>`'${$e(G)}'`).join(", ");for(let G of await i(`SELECT Id, Username, IsActive, UserType FROM User WHERE Username IN (${D})`)){let V=c(G);V&&M.set(V.username.toLowerCase(),V)}}for(let[B,D]of A){let G=D.map(V=>M.get(V)).find(V=>V!==void 0);G&&p.set(B,G)}}let g=[],h=[...d.keys()].filter(v=>d.get(v)?.fields.some(A=>A.name===As));if(h.length>0){let v=Uc(d),A=await i(`SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name, IsActive${v?", IsPersonType":""} FROM RecordType WHERE SobjectType IN (${h.map(N=>`'${me(N)}'`).join(", ")})`);for(let N of A)typeof N.Id!="string"||typeof N.SobjectType!="string"||typeof N.DeveloperName!="string"||g.push({id:Re(N.Id),sobjectType:N.SobjectType,developerName:N.DeveloperName,...typeof N.NamespacePrefix=="string"&&N.NamespacePrefix!==""?{namespacePrefix:N.NamespacePrefix}:{},name:typeof N.Name=="string"?N.Name:N.DeveloperName,isActive:N.IsActive!==!1,...typeof N.IsPersonType=="boolean"?{isPersonType:N.IsPersonType}:{}})}let m=[];if(r.queues.size>0){let v=new Map;for(let A of await i("SELECT QueueId, SobjectType FROM QueueSobject"))typeof A.QueueId!="string"||typeof A.SobjectType!="string"||v.set(ae(A.QueueId),[...v.get(ae(A.QueueId))??[],A.SobjectType]);for(let A of await i("SELECT Id, DeveloperName FROM Group WHERE Type = 'Queue'"))typeof A.Id!="string"||typeof A.DeveloperName!="string"||m.push({id:Re(A.Id),developerName:A.DeveloperName,sobjectTypes:v.get(ae(A.Id))??[]})}let w;if([...d.values()].some(v=>v.fields.some(A=>A.name===Yr))&&r.currencies.size>0){w=new Set;for(let v of await i("SELECT IsoCode, IsActive FROM CurrencyType"))typeof v.IsoCode=="string"&&v.IsActive===!0&&w.add(v.IsoCode)}let P;if(r.standardPricebook.id!==void 0){let[v]=await i(Ct);typeof v?.Id=="string"&&(P=Re(v.Id))}let j=new Set,T=new Map;for(let[v,A]of r.heldBy){let N=T.get(A);N?N.push(v):T.set(A,[v])}let $=async(v,A)=>{let N=0;for(let M of Hr(A,Gt))for(let B of await i(`SELECT Id FROM ${me(v)} WHERE Id IN (${io(M)})`))typeof B.Id=="string"&&(j.add(ae(B.Id)),N++);return N},q=new Set(r.objects.replayed.map(v=>v.objectApiName));for(let[v,A]of T){if(a.has(v)||Id(v))continue;let N=[...A].sort(),M=N.slice(0,Gt);try{await $(v,M)>0&&await $(v,N.slice(Gt))}catch(B){if(q.has(v))throw B}}let C=new Map;for(let[v,A]of r.notHeld){let[N,M]=v.split("."),B=d.get(N)?.fields.find(V=>V.name===M),D=B?.type==="reference"?B.referenceTo??[]:[];if(D.length!==1)continue;let G=C.get(D[0])??new Set;for(let V of A)G.add(V);C.set(D[0],G)}for(let[v,A]of C)try{await $(v,[...A].sort())}catch{}let I=new Map;for(let v of r.objects.replayed){if(v.customSetting===void 0||a.has(v.objectApiName))continue;let A={names:new Set,owners:new Set};for(let N of await i(`SELECT Id, Name, SetupOwnerId FROM ${me(v.objectApiName)}`))typeof N.Name=="string"&&A.names.add(N.Name),typeof N.SetupOwnerId=="string"&&A.owners.add(ae(N.SetupOwnerId));I.set(v.objectApiName,A)}let b=new Set;for(let v of Hr([...r.profiles].sort(),Gt))for(let A of await i(`SELECT Id FROM Profile WHERE Id IN (${io(v)})`))typeof A.Id=="string"&&b.add(ae(A.Id));let O=new Set,F=[...new Set(r.fileLinks.map(v=>ae(v.ContentDocumentId)))];if(!a.has(ir))for(let v of Hr(F.sort(),Gt))for(let A of await i(`SELECT Id FROM ContentDocument WHERE Id IN (${io(v)})`))typeof A.Id=="string"&&O.add(ae(A.Id));return{organizationId:Re(o.organizationId),runningUserId:Re(o.runningUserId),describes:d,missing:a,usersById:l,usersByUsername:p,recordTypes:g,queues:m,...w!==void 0?{currencies:w}:{},...P!==void 0?{standardPricebookId:P}:{},sameIds:j,customSettings:I,profiles:b,files:O,requests:s}}function Uc(o){return o.get("Account")?.fields.some(e=>e.name===No)===!0}function lf(o,e,t){let r=[...new Set(Object.values(o.ownerMap??{}).map(ae))].sort(),n=r.filter(i=>{let d=e.usersById.get(i);return d===void 0||d.userType!=="Standard"});if(n.length>0)return{code:"OWNER_MAP_UNKNOWN",users:n.map(Re),message:`The owners chosen give records to users ${t} does not hold as standard users: ${n.map(Re).join(", ")}. Choose users of ${t}. Nothing was written.`};let s=r.filter(i=>e.usersById.get(i)?.isActive!==!0);if(s.length>0)return{code:"OWNER_MAP_INACTIVE",users:s.map(Re),message:`The owners chosen give records to users ${t} holds inactive: ${s.map(Re).join(", ")}. It refuses a record owned by an inactive user: choose an active user, or reactivate them there. Nothing was written.`}}var Ut=class{constructor(e){this.id=e}id;counts=new Map;add(e,t=1){let r=this.id(e),n=this.counts.get(r);n?n.n+=t:this.counts.set(r,{key:e,n:t})}entries(){return[...this.counts.values()]}};function uf(o,e){return e.createable&&e.nillable===!1&&e.defaultedOnCreate!==!0||Ks(o,e.name)}function ff(o){let e=o.length;return typeof e=="number"&&e>0?e:void 0}var pf=new Set(["id","reference","boolean","double","int","long","percent","currency","date","datetime","time","picklist","multipicklist"]);async function gf(o){let{survey:e,target:t,choices:r,annex:n}=o,s=lf(r,t,o.targetName);if(s)return{refusal:s};let i=new Ut(k=>`${k.object}|${k.reason}`);for(let k of e.objects.leftOut)i.add({object:k.objectApiName,reason:k.reason},k.records);let d=e.objects.replayed.filter(k=>t.missing.has(k.objectApiName)?(i.add({object:k.objectApiName,reason:"notInTarget"},k.records),!1):t.describes.get(k.objectApiName)?.createable===!1?(i.add({object:k.objectApiName,reason:"notCreateable"},k.records),!1):!0),a=new Set(d.map(k=>k.objectApiName)),u=new Ut(k=>`${k.field}|${k.reason}`),l={kept:0,toRunningUser:0,reasons:{notInTarget:0,inactive:0,queueMissing:0}},c=new Ut(k=>`${k.object}|${k.recordType}|${k.outcome}`),f=new Ut(k=>k),p=new Map,g=!1,h={inserted:0,alreadyThere:0},m=new Map,w=new Map,R=Uc(t.describes),P=new Set,j=e.standardPricebook,T=j.id!==void 0?ae(j.id):void 0,$=new Map(Object.entries(r.ownerMap??{}).map(([k,E])=>[ae(k),Re(E)])),q=k=>{let E=t.usersById.get(k);if(E?.userType==="Standard"&&E.isActive)return{id:E.id};let S=t.usersByUsername.get(k);return S?.userType==="Standard"&&S.isActive?{id:S.id}:{why:E!==void 0||S!==void 0?"inactive":"notInTarget"}},C=(k,E)=>{let S=Z=>Z.sobjectTypes.includes(k),J=t.queues.find(Z=>ae(Z.id)===E&&S(Z));if(J)return J.id;let ne=co(n,"queues")?n.queues.find(Z=>ae(Z.id)===E):void 0;if(ne!==void 0)return t.queues.find(Z=>Z.developerName===ne.developerName&&S(Z))?.id},I=(k,E,S)=>{let J=ae(E),ne=co(n,"recordTypes")?n.recordTypes.find(W=>ae(W.id)===J):void 0,Z=t.recordTypes.filter(W=>W.sobjectType===k&&W.isActive),ge,ee="default";if(ne!==void 0&&(ge=Z.find(W=>W.developerName===ne.developerName&&(W.namespacePrefix??null)===(ne.namespacePrefix??null)),ge&&(ee="byName")),ge===void 0&&(ge=Z.find(W=>ae(W.id)===J),ge&&(ee="byId")),ge===void 0&&S){let W=Z.filter(se=>se.isPersonType===!0);if(W.length!==1)return{refused:`the checkpoint does not say which of the person account record types of ${o.targetName} its person accounts had: take it again with SandForge 1.81 or later, or leave Account out`};ge=W[0]}let Ie={recordType:ne!==void 0?ct(ne.namespacePrefix,ne.developerName):Re(E),outcome:ee};if(ge===void 0)return{given:Ie};let z=ge,ve=t.describes.get(k)?.recordTypeInfos?.find(W=>ae(W.recordTypeId)===ae(z.id));if(ve!==void 0&&!ve.available)return{refused:`${ct(z.namespacePrefix,z.developerName)} is not assigned to the user who replays in ${o.targetName}: assign it to them, or leave ${k} out`};let Ge={name:z.name,developerName:z.developerName,namespacePrefix:z.namespacePrefix??null},Ye=w.get(k)??new Map;return Ye.set(z.id,Ge),w.set(k,Ye),{ref:Ge,given:Ie}},b=[];for(let k of d){let E=k.objectApiName,S=t.describes.get(E);if(S===void 0)continue;let J=new Map(S.fields.map(ee=>[ee.name,ee])),ne=k.fields.filter(ee=>!Os.has(ee)&&!J.has(ee)&&!(ee===Yr&&t.currencies===void 0));ne.length>0&&p.set(E,new Set(ne));let Z=k.customSetting,ge=t.customSettings.get(E);for await(let ee of Ss(o,E)){let Ie=ae(ee.Id);if(t.sameIds.has(Ie)){m.set($c(E,ee.Id),Re(ee.Id));continue}let z={objectApiName:E,key:Ie,referenceId:$c(E,ee.Id),fields:{},pointsAt:new Map,sourceId:Re(ee.Id),emptied:[]},ve=(W,se)=>{z.refused??={reason:W,...se!==void 0?{path:se}:{}}},Ge=(E==="Account"||E==="Contact")&&Ir(ee);Ge&&!R&&ve("personAccountsUnsupported",`turn person accounts on in ${o.targetName}, or leave ${E} out`),Ge&&E==="Contact"&&P.add(Ie);let Ye=E==="Account"?yn(ee,!1):void 0;for(let[W,se]of Object.entries(ee)){if(Os.has(W)||Ye!==void 0&&fn(E,W,Ye))continue;let jt=J.get(W);if(jt===void 0){W===Yr&&typeof se=="string"&&se!==""&&(g||=t.currencies===void 0);continue}if(se==null||se==="")continue;if(W===Yr&&typeof se=="string"){t.currencies!==void 0&&!t.currencies.has(se)&&(ve("inactiveCurrency",`activate ${se} in ${o.targetName}, or leave ${E} out`),f.add(se)),z.fields[W]=se;continue}if(W===As&&typeof se=="string"){let ye=I(E,se,Ge);ye.given!==void 0&&(z.recordType=ye.given),ye.refused!==void 0?ve("recordTypeUnavailable",ye.refused):ye.ref!==void 0&&(z.fields[W]=ye.ref.name,z.recordTypeDeveloperName=ct(ye.ref.namespacePrefix,ye.ref.developerName));continue}if(jt.type!=="reference"||typeof se!="string"||!Bc.test(se)){z.fields[W]=se;continue}let ce=ae(se),Ft=uf(E,jt),Ue=(ye,Ce)=>{Ft?ve("requiredLookupMissing",Ce):z.emptied.push({field:`${E}.${W}`,reason:ye})};if(ce.startsWith(qc)){z.fields[W]=t.organizationId;continue}if(W===vs){(ce.startsWith(Is)?t.profiles.has(ce):t.usersById.has(ce))?z.fields[W]=Re(se):ve("requiredLookupMissing",`the ${ce.startsWith(Is)?"profile":"user"} its row is of is not in ${o.targetName}`);continue}if(W===Wc&&(ce.startsWith(Rs)||ce.startsWith(ks))){let ye=$.get(ce);if(ye!==void 0)z.owner="kept",z.fields[W]=ye;else if(r.owners==="me")z.owner="toRunningUser";else if(ce.startsWith(ks)){let Ce=C(E,ce);z.owner=Ce!==void 0?"kept":"queueMissing",Ce!==void 0&&(z.fields[W]=Ce)}else{let Ce=q(ce);z.owner=Ce.id!==void 0?"kept":Ce.why??"notInTarget",Ce.id!==void 0&&(z.fields[W]=Ce.id)}continue}if(ce.startsWith(Rs)){let ye=q(ce);ye.id!==void 0?z.fields[W]=ye.id:Ft?z.fields[W]=t.runningUserId:z.emptied.push({field:`${E}.${W}`,reason:"userNotInTarget"});continue}if(T!==void 0&&ce===T){t.sameIds.has(ce)?z.fields[W]=Re(se):a.has(ao)&&e.heldBy.has(ce)?z.pointsAt.set(W,ce):t.standardPricebookId!==void 0?z.fields[W]=t.standardPricebookId:Ue("objectNotHeld",`${o.targetName} has no standard price book`);continue}let Pe=e.heldBy.get(ce);Pe!==void 0&&t.sameIds.has(ce)?z.fields[W]=Re(se):Pe!==void 0&&a.has(Pe)?z.pointsAt.set(W,ce):Pe!==void 0?Ue("objectNotReplayed",`replay ${Pe} too`):t.sameIds.has(ce)?z.fields[W]=Re(se):Ue("objectNotHeld",`the checkpoint holds no record it points at, and ${o.targetName} holds none under its Id`)}if(E===_e&&j.how==="ambiguous"&&ve("requiredLookupMissing",`the checkpoint does not say which of its price books is the standard one, which every other price needs first: take it again with SandForge 1.81 or later, or leave ${_e} out`),Z!==void 0&&ge!==void 0){let W=z.fields[vs];if(Z==="list"?typeof ee.Name=="string"&&ge.names.has(ee.Name):typeof W=="string"&&ge.owners.has(ae(W))){h.alreadyThere++;continue}}b.push(z)}}let O=new Map(b.map(k=>[k.key,k])),F=new Map;for(let k of b)for(let E of k.pointsAt.values()){let S=F.get(E);S?S.push(k):F.set(E,[k])}let v=b.filter(k=>k.refused!==void 0);for(let k=0;k<v.length;k++){let E=v[k];for(let S of F.get(E.key)??[])S.refused===void 0&&(S.refused={reason:"parentRefused",path:`its ${E.objectApiName} is refused: lift that first`},v.push(S))}let A=new Ut(k=>`${k.object}|${k.reason}`),N=new Map,M=[];for(let k of b){if(k.refused!==void 0){A.add({object:k.objectApiName,...k.refused});continue}for(let S of k.emptied)u.add(S);k.recordType!==void 0&&c.add({object:k.objectApiName,...k.recordType}),k.owner==="kept"?l.kept++:k.owner!==void 0&&(l.toRunningUser++,k.owner!=="toRunningUser"&&l.reasons[k.owner]++);for(let[S,J]of k.pointsAt){let ne=O.get(J);ne!==void 0&&ne.refused===void 0?k.fields[S]=ne.referenceId:u.add({field:`${k.objectApiName}.${S}`,reason:"objectNotReplayed"})}P.has(k.key)&&typeof k.fields.AccountId=="string"&&M.push({accountReferenceId:k.fields.AccountId,contactReferenceId:k.referenceId});let E=N.get(k.objectApiName)??[];E.push({referenceId:k.referenceId,fields:k.fields,...k.recordTypeDeveloperName!==void 0?{recordTypeDeveloperName:k.recordTypeDeveloperName}:{}}),N.set(k.objectApiName,E)}for(let k of d)k.customSetting!==void 0&&(h.inserted+=N.get(k.objectApiName)?.length??0);let B=t.describes.get(ir);if(B!==void 0&&B.createable!==!1){let k=[];for(let E of e.fileLinks){let S=O.get(ae(E.LinkedEntityId));S===void 0||S.refused!==void 0||t.files.has(ae(E.ContentDocumentId))&&k.push({referenceId:`${ir}-${Re(E.ContentDocumentId)}_${S.sourceId}`,fields:{ContentDocumentId:Re(E.ContentDocumentId),LinkedEntityId:S.referenceId,ShareType:E.ShareType,Visibility:E.Visibility}})}k.length>0&&N.set(ir,k)}let D=new Ha(o.salt),G=r.mask?new Za(void 0,o.salt):void 0,V=r.mask?new Sn:void 0,L=[],H=[];for(let[k,E]of N){let S=t.describes.get(k);if(S===void 0)continue;let J=new Set(E.flatMap(z=>Object.keys(z.fields))),ne=S.fields.filter(z=>J.has(z.name)).map(z=>{let ve=ff(z);return{name:z.name,queryable:!0,createable:z.createable,isReference:z.type==="reference",type:z.type,...ve!==void 0?{length:ve}:{}}});if(r.contactPoints==="neutralized"){let z=D.forObject(k,ne);if(z)for(let ve of E)z(ve.fields)}if(G===void 0||V===void 0)continue;let Z=ne.filter(z=>!pf.has((z.type??"").toLowerCase())),ge=new Set(On(V,Z.map(z=>({name:z.name,type:z.type??"string"})))),ee=Z.filter(z=>ge.has(z.name)).map(z=>({name:z.name,type:z.type??"string",...z.length!==void 0?{length:z.length}:{}}));for(let z of ee)L.push(`${k}.${z.name}`);for(let z of Z)!ge.has(z.name)&&(z.type??"").toLowerCase()==="textarea"&&H.push(`${k}.${z.name}`);if(ee.length===0)continue;let Ie=G.anonymize({objectApiName:k,records:E.map(z=>z.fields),sourceIds:E.map(z=>z.referenceId),fields:ee,methods:{}});E.forEach((z,ve)=>{z.fields=Ie[ve]??z.fields})}let K={};for(let[k,E]of w)K[k]=[...E.values()];let re=[...N].map(([k,E])=>({objectApiName:k,records:E})),_=T!==void 0?O.get(T):void 0,U=_!==void 0&&_.refused===void 0&&_.objectApiName===ao?_.referenceId:void 0,de={datasetVersion:"1.0.0",objects:re,recordTypes:K,personContactSidecar:M,...U!==void 0?{standardPricebook:U}:{}},X=re.reduce((k,E)=>k+E.records.length,0),pe=e.objects.replayed.some(k=>k.objectApiName===ao||k.objectApiName===_e),Be=A.entries(),Ne={records:{toCreate:X-(U!==void 0?1:0),linkedById:m.size,linkedByKey:0,refusedBeforeWrite:Be.reduce((k,E)=>k+E.n,0)},owners:l,recordTypes:c.entries().map(({key:k,n:E})=>({...k,records:E})).sort((k,E)=>_c(`${k.object}.${k.recordType}`,`${E.object}.${E.recordType}`)),notReplayed:i.entries().map(({key:k,n:E})=>({...k,records:E})),lookupsEmptied:u.entries().map(({key:k,n:E})=>({...k,records:E})).sort((k,E)=>_c(k.field,E.field)),refused:Be.map(({key:k,n:E})=>({object:k.object,records:E,reason:k.reason,...k.path!==void 0?{path:k.path}:{}})),fieldsNotInTarget:[...p].map(([k,E])=>({object:k,fields:[...E].sort()})),...e.objects.replayed.some(k=>k.customSetting!==void 0)?{customSettings:h}:{},currencies:{refused:f.entries().map(({key:k,n:E})=>({code:k,records:E})),...g?{singleCurrencyTarget:!0}:{}},...pe?{standardPricebook:j.how}:{},masked:{fields:L.sort(),...r.mask?{unmaskedFreeText:H.sort()}:{}},contactPoints:r.contactPoints,degraded:hf(n),auditDates:"new"};return{conversion:{dataset:de,summary:Ne,identityKeys:Object.fromEntries(r.link.map(k=>[k.objectApiName,[...k.fields]])),linkedById:m,filesLeft:e.filesLeft}}}function hf(o){return o===void 0?["recordTypes","users","queues","standardPricebook"]:[...new Set(o.unread.map(e=>e.part))]}function _c(o,e){return o<e?-1:o>e?1:0}async function Kc(o){let e={folder:o.folder,checkpoint:o.checkpoint,annex:o.annex,choices:o.choices},t=await sf(e),r=await cf({...o,source:e,survey:t});return{...await gf({...e,survey:t,target:r,targetName:o.targetName,...o.salt!==void 0?{salt:o.salt}:{}}),target:r,survey:t}}var yf={insert:async()=>{throw new Error("A preview writes nothing.")},update:async()=>{throw new Error("A preview writes nothing.")},delete:async()=>{throw new Error("A preview writes nothing.")}},wf=new Set(["frozen:config:get","frozen:config:save","frozen:select","frozen:extract","frozen:load","frozen:load:preview","frozen:verify","frozen:remove","frozen:remove:sweep","frozen:remove:automation","frozen:remove:preview","frozen:status","frozen:rules:clear","frozen:rules:create"]),lo="REPLACE_LEAVES_RECORDS",gr=class extends Error{constructor(t){super(t.message);this.stop=t;this.name="RemovalStopped"}stop;get code(){return this.stop.code}},hr=class extends Error{constructor(t,r,n,s){super(r);this.code=t;this.emails=n;this.orgId=s;this.name="LoadEmailsStop"}code;emails;orgId},Qr=class extends Error{constructor(t,r,n,s){super(r);this.code=t;this.automation=n;this.orgId=s;this.name="LoadAutomationStop"}code;automation;orgId},en=class extends Error{constructor(t,r,n){super(t);this.apiRequests=r;this.orgId=n;this.name="LoadBudgetStop"}apiRequests;orgId;code=Mo},ll="FROZEN_STORAGE_EXCEEDED",tn=class extends Error{constructor(t,r,n){super(t);this.storage=r;this.orgId=n;this.name="LoadStorageStop"}storage;orgId;code=ll};function Jr(o){let e=o<10?100:10;return String(o<=0?0:Math.ceil(o*e-1e-9)/e)}function Vc(o){let e;return{request:t=>(e===void 0&&(e=Promise.resolve().then(()=>o.request(t)),e.catch(()=>{})),e)}}function Hc(o){if("unread"in o.storage)return;let e=Math.max(0,o.automationBytes??0),t=ul(o.dataset,o.sent)+e,r=(o.purged??[]).filter(l=>l.deletes).reduce((l,c)=>l+Co(c.objectApiName,{rows:c.rows}),0),n=1024*1024,{remainingMB:s,maxMB:i}=o.storage;if(t<=s*n+r)return;let d={estimateMB:t/n,...e>0?{automationMB:e/n}:{},remainingMB:s,maxMB:i,...r>0?{freedMB:r/n}:{},...o.pilot===!0?{pilot:!0}:{}},a=d.freedMB!==void 0?`, and the reload's purge frees about ${Jr(d.freedMB)} MB first`:"",u=d.automationMB!==void 0?`, about ${Jr(d.automationMB)} MB of it for what the target's automation creates under them`:"";return o.replay===!0?{storage:d,message:`The replay was refused before it wrote anything: the checkpoint's records take about ${Jr(d.estimateMB)} MB of data storage${u}, and ${o.target} has ${s} MB left of ${i} MB${a}. To replay part of it, ${Od.fewerObjects}; or free data storage in ${o.target}. Nothing was written.`}:o.pilot===!0?{storage:d,message:`The pilot was refused before it wrote anything: the records of its root folder take about ${Jr(d.estimateMB)} MB of data storage${u}, and ${o.target} has ${s} MB left of ${i} MB. Extract a smaller dataset, with a lower budget in the configuration, a new selection and a new extraction; or free data storage in ${o.target}. Nothing was written.`}:{storage:d,message:`The load was refused before it wrote anything: the dataset's records take about ${Jr(d.estimateMB)} MB of data storage${u}, and ${o.target} has ${s} MB left of ${i} MB${a}. Load a pilot first, one root folder of it; or extract a smaller dataset, with a lower budget in the configuration, a new selection and a new extraction; or free data storage in ${o.target}. Nothing was written.`}}var bf=rt({sobjects:yt(rt({name:De().min(1),createable:sn().optional()}).loose())}).loose();function ul(o,e){return o.objects.reduce((t,r)=>{if(e!==void 0&&!e.takes(r.objectApiName))return t;let n=e===void 0?r.records.length:r.records.filter(s=>!e.byThePlatform.has(s.referenceId)).length;return t+Co(r.objectApiName,{rows:n})},0)}function Yc(o,e,t,r){if(!("objects"in o))return 0;let n=Ua(zt(o,e,r),r),s=new Map(t.objects.map(i=>[i.objectApiName,i.records.length]));return Ka(n,i=>s.get(i)??0)}function Rf(o){return{estimateMB:o.estimateMB,...o.automationMB!==void 0?{automationMB:o.automationMB}:{},remainingMB:o.remainingMB,maxMB:o.maxMB,...o.freedMB!==void 0?{freedMB:o.freedMB}:{},...o.pilot===!0?{pilot:!0}:{}}}function Ps(o,e,t){if(t!==!0)return o;try{return ss(o,e.rootObject)}catch{return o}}function Jc(o){return o?{replay:o}:{}}function kf(o,e){let t=0;for(let r of o.perObject){let n=r.reused-(r.writtenByThePlatform??0),s=e.standardPricebook!==void 0&&r.objectApiName==="Pricebook2"&&n>0?1:0;t+=n-s}return t}function If(o,e){let t=Ta(o,e,Bi);return{verdict:o.verdict,estimate:o.estimate,...o.verdict==="unread"?{unread:o.unread}:{remaining:o.remaining,max:o.max},...o.parts?{parts:{...o.parts}}:{},...t!==void 0?{refused:{code:Mo,message:t}}:{}}}function Xr(o,e,t){let r=[...new Set(o.map(s=>s.objectApiName))],n=!!t?.runUserId;return Zs({setToDraft:Wi(r),delete:Ki(r,[],{userKept:n})},e)}function Ts(o){return o.status==="success"&&(o.left??[]).length===0}function Xc(o){return o.verdict!=="nothingSends"||o.counted.length>0||o.uncounted!==void 0}function vf(o,e){if(e.includeChanged||o.refusal!==void 0||o.status!=="partial"&&o.status!=="failure")return o;let t=o.objects.every(s=>s.refused===0&&s.deleted+s.alreadyGone+s.keptChanged===s.found),r=(o.left??[]).some(s=>s.class==="late"&&e.sweepLate||s.class==="untied"&&e.sweepUntied),n=o.objects.some(s=>s.keptChanged>0);return t&&!r&&n?{...o,status:"success"}:o}var Zr="frozen",Zc="frozen:config",pr="frozen:lastRun",Qc="frozen:lastRuns",js="frozen:lastVerify",Fs="frozen:lastVerifies",el="tokens.json",Of="rules.json",mr=class extends Error{constructor(t,r){super(r);this.rulesPath=t;this.name="RulesFileMissingError"}rulesPath},Sf=async o=>{let e=await import("vscode");await e.window.showTextDocument(e.Uri.file(o),{preview:!1})},Af="0.1.0",Pf=10*6e4,Es=15*6e4,Tf="EXTRACT_TIMEOUT",tl=30*6e4,Ls=6e4,rl=12e4,jf=50;function Ff(o,e){let t=0,r=null,n=null,s=d=>{o(...d),t=Date.now(),r=null},i=((...d)=>{r=d;let a=e-(Date.now()-t);a<=0?(n&&(clearTimeout(n),n=null),s(d)):n||(n=setTimeout(()=>{n=null,r&&s(r)},a))});return i.flush=()=>{n&&(clearTimeout(n),n=null),r&&s(r)},i}function nl(o,e){let t=Ff(o,e);return Object.assign(n=>{if(n.status==="started"){t(n);return}t.flush(),o(n)},{flush:t.flush})}async function it(o){try{return await Ae.access(o),!0}catch{return!1}}function Ef(o){return o.check==="clear-empty"?'residual value under "clear" generator (value redacted at the bridge)':o.detail.length>200?`${o.detail.slice(0,200)}\u2026`:o.detail}function fl(o){return{passed:o.passed,author:o.author,checkedAt:o.checkedAt,checks:o.checks.map(e=>({name:e.name,passed:e.passed,violations:e.violations.slice(0,jf).map(t=>({check:t.check,objectApiName:t.objectApiName,referenceId:t.referenceId,field:t.field,detail:Ef(t)}))}))}}function ol(o){return{version:o.version,status:o.status,frozenAt:o.frozenAt,source:o.source,saltFingerprint:o.saltFingerprint,rulesVersion:o.rulesVersion,volumetry:o.volumetry,controls:{nonReidentification:fl(o.controls.nonReidentification),dryRunLoad:o.controls.dryRunLoad,author:o.controls.author,date:o.controls.date},...o.coverage?{coverage:o.coverage}:{}}}function Lf(o,e,t){return{combinations:o.roots.map(r=>({combinationKey:r.combinationKey,axisValues:r.axisValues,edgeCase:r.edgeCase})),uncovered:o.uncovered,volumetry:o.volumetry,selectedAt:o.selectedAt,selectionPath:e,...t?{graph:t}:{},...o.stopped?{stopped:o.stopped}:{}}}function Ns(o,e){if(!e||e.length===0)return o;let t=new Set(e);return{...o,nodes:o.nodes.map(r=>t.has(r.objectApiName)?{...r,included:!1}:r)}}function sl(o,e){return{objects:o.nodes.filter(ka).length,truncated:o.truncated===!0,maxNodes:e}}function Nf(o){return o.length===0?"":` Kept in the org, the platform does not delete them: ${o.map(({objectApiName:t,count:r})=>`${t} (${r})`).join(", ")}.`}function Cs(o,e){if(!o)return{message:"No load into this org was recorded in this sas: there is nothing to remove.",code:"NO_LOAD"};if(o.orgId!==e.targetOrgId||o.endedAt!==e.loadedAt)return{message:"Another load was recorded since this one was shown, and nothing was removed: check what a removal takes now, then confirm it again.",code:"LOAD_CHANGED"};if(!o.created)return{message:"This load was recorded before loads kept what they created: its records cannot be told from the ones it linked, and cannot be removed from here, nor replaced by a reload, which would delete what someone changed since. Refresh the sandbox to start again from its copy, or find the records the loading user created that day and delete them yourself.",code:"NOT_RECORDED"};if(ot(o).length>0)return;let t=Nf(Dn(o));return o.removal?{message:`The records this load created were already removed, on ${o.removal.removedAt}.${t}`,code:"ALREADY_REMOVED"}:t?{message:`This load created no record a removal takes.${t}`,code:"NOTHING_TO_REMOVE"}:{message:"This load created no record to remove.",code:"NOTHING_TO_REMOVE"}}function zs(o){let e=o.writtenBetween,t=o.startedAt===void 0?Number.NaN:Date.parse(o.startedAt),r=Date.parse(o.endedAt);return{...e?{runStartedAt:new Date(e.first),runEndedAt:new Date(e.last)}:{...Number.isFinite(t)&&Number.isFinite(r)?{runDurationMs:Math.max(0,r-t)}:{},...Number.isFinite(r)?{runRecordedAt:new Date(r),endedByItsWrites:!0}:{}},removalStamps:o.removalStamps,removalSpans:o.removalSpans,...o.runUserId?{runUserId:o.runUserId}:{}}}function Cf(o,e=!1){let t=new Map;for(let{objects:r}of o)for(let n of r){let s=n.heldByAutomation??0,i=(n.keptDependents??0)-(e?s:0),d=n.heldBy&&n.heldBy.length>0?n.heldBy.join(", "):"",a=[n.keptChanged>0?`${n.keptChanged} changed since the load`:"",i>0?(d?`${i} kept for records that stay under them (${d})`:`${i} kept as what hangs from them could not be read`)+(!e&&s>0?`, ${s} of them for what the target's automation likely made for the load, which a sweep takes first`:""):"",n.undeletable>0?`${n.undeletable} the user may not delete`:"",n.notVisible>0?`${n.notVisible} out of the user's sight`:"",n.unread>0?`${n.unread} that could not be read`:""].filter(Boolean),u=n.keptChanged+Math.max(0,i)+n.undeletable+n.notVisible+n.unread;if(u===0)continue;let l=t.get(n.objectApiName)??{left:0,why:new Set};l.left+=u;for(let c of a)l.why.add(c);t.set(n.objectApiName,l)}return[...t].map(([r,{left:n,why:s}])=>({objectApiName:r,left:n,why:[...s]}))}function zf(o){return{status:o.status,orgId:o.orgId,mode:o.mode,startedAt:o.startedAt,durationMs:o.durationMs,alignment:{excludedObjects:o.alignment.excludedObjects,removals:o.alignment.removals,adjustments:o.alignment.adjustments,recordTypeIssues:o.alignment.recordTypeIssues},placeholders:o.placeholders,requiredDefaults:o.requiredDefaults,perObject:o.perObject,...o.sentAgainForALock?{sentAgainForALock:o.sentAgainForALock}:{},pass2:o.pass2,personContact:o.personContact,statuses:o.statuses,purge:o.purge,...o.leftToThePlatform?{leftToThePlatform:o.leftToThePlatform}:{},...o.untypedFeedItems?{untypedFeedItems:o.untypedFeedItems}:{},...o.heldForExcludedParents?{heldForExcludedParents:o.heldForExcludedParents}:{},...o.quotesLeftUnsynced?{quotesLeftUnsynced:o.quotesLeftUnsynced}:{},...o.keysLeftEmpty?{keysLeftEmpty:o.keysLeftEmpty}:{},...o.recordTypesGiven?{recordTypesGiven:o.recordTypesGiven}:{},...o.runUserId?{runUserId:o.runUserId}:{},mappingPath:o.mappingPath,contractPath:o.contractPath}}function Mf(o){return o.status==="completed"?"success":o.perObject.reduce((t,r)=>t+r.inserted+r.reused,0)>0?"partial":"failure"}function Df(o){let e=o.perObject.reduce((t,r)=>t+r.failed.length,0)+o.purge.failures.length;return po(o)===0&&e===0?"stopped":"cancelled"}function po(o){let e=t=>Object.values(t).reduce((r,n)=>r+n,0);return o.perObject.reduce((t,r)=>t+r.inserted,0)+o.placeholders.length+e(o.purge.deleted)+e(o.purge.deactivated)}function il(o){return`frozen:${o}`}var uo=(o,e)=>e==="insert"||e==="update",Kt=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointFirstStop"}code};function Ms(o){let e=new Map,t=r=>{let n=e.get(r)??Ri(r);return e.set(r,n),n};for(let r of o.perObject){let n=t(r.objectApiName);n.created+=r.inserted,n.failed+=r.failed.length+r.skippedDuplicates.length,r.notInserted&&(n.notSent=(n.notSent??0)+r.notInserted),r.writtenWithoutFields&&(n.writtenWithoutFields=(n.writtenWithoutFields??0)+r.writtenWithoutFields.rows)}for(let r of o.placeholders)t(r.placeholderObjectApiName).created+=1;for(let[r,n]of Object.entries(o.purge.deleted))t(r).deleted+=n;for(let[r,n]of Object.entries(o.purge.deactivated))t(r).updated+=n;for(let r of o.purge.failures)t(r.objectApiName).failed+=1;return[...e.values()]}async function xf(o,e){try{let t=await e.load();return Object.fromEntries(o.objects.map(r=>[r.objectApiName,r.records.filter(n=>t.has(n.referenceId)).length]))}catch{return}}var tt=class extends Error{constructor(t,r,n={}){super(r);this.code=t;this.params=n;this.name="ReplayRefused"}code;params},Ds=class extends xn{constructor(t,r,n){super(t,r);this.registeredAs=n}registeredAs;async recorded(){let t=await super.recorded();return t&&{...t,orgId:this.registeredAs}}async recordedLoads(){return(await super.recordedLoads()).map(t=>({...t,orgId:this.registeredAs}))}};function $f(){let o=la();return{checkpoints:()=>[o,pd(o)].flatMap(e=>{if(!mf(e))return[];let t=ua({root:e});return"store"in t?[t.store]:[]}),replays:new kd({root:Rd()})}}function al(o,e){let t=Object.fromEntries((e?.link??[]).map(n=>[n.objectApiName,[...n.fields]])),r={...o?.identityKeys,...t};return{rootObject:"",axes:[],edgeCases:[],...o,...Object.keys(r).length>0?{identityKeys:r}:{}}}function fo(o){return o.replay?{module:"checkpoint",sasMark:Yn(o.replay.folder.dir)}:{module:"frozen"}}function _f(o){return o.replay?{action:"checkpoint_replay",module:"checkpoint"}:{action:"frozen_load",module:"frozen"}}var dl=class{constructor(e){this.deps=e}deps;registry;liveTracker;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;saltKeeper=ic();openInEditor=Sf;otherModuleRuns=()=>Promise.resolve([]);removing=new Set;writing=new ra;loading=new Map;beforeRunCheckpoints;describeCache=new $o({defaultTtl:5*6e4,maxSize:2e3,maxSizeBytes:200*1024*1024,releaseExpired:!0});describeGlobalCache=new $o({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});forgetOrg(e){this.describeCache.invalidateByPrefix(`${e}::`),this.describeGlobalCache.invalidate(e)}setRegistry(e){this.registry=e}setRulesEditor(e){this.openInEditor=e}setLiveOperationTracker(e){this.liveTracker=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}muteLeases={};setMuteOffered(e){this.muteOffered=e}muteOffered=!0;setRemovalAsker(e){this.removalAsker=e}removalAsker;ownReader(){return this.reader??=import("./chunk-FH5UR35W.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>Oe(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}setSaltKeeper(e){this.saltKeeper=e}isWritingTo(e,t){if(this.writing.has(e))return!0;for(let[r,n]of this.loading)if(n===e&&(t===void 0||t!==il(r)))return!0;return!1}async loadingDuring(e,t){let r=Pn(e,"targetOrgId");if(r===void 0)return t();this.loading.set(e.id,r);try{await t()}finally{this.loading.delete(e.id)}}async handle(e){if(!wf.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"frozen:config:get":return this.handleConfigGet(e),!0;case"frozen:config:save":return this.handleConfigSave(e),!0;case"frozen:select":return await this.handleSelect(e),!0;case"frozen:extract":return await this.handleExtract(e),!0;case"frozen:load":return await this.loadingDuring(e,()=>this.handleLoad(e)),!0;case"frozen:load:preview":return await this.handlePreview(e),!0;case"frozen:verify":return await this.handleVerify(e),!0;case"frozen:remove":return await this.writing.during(Pn(e,"targetOrgId"),()=>this.handleRemove(e)),!0;case"frozen:remove:sweep":return await this.writing.during(Pn(e,"targetOrgId"),()=>this.handleRemoveSweep(e)),!0;case"frozen:remove:automation":return await this.handleRemoveAutomation(e),!0;case"frozen:remove:preview":return await this.handleRemovePreview(e),!0;case"frozen:status":return await this.handleStatus(e),!0;case"frozen:rules:clear":return await this.handleRulesClear(e),!0;case"frozen:rules:create":return await this.handleRulesCreate(e),!0;default:return!1}}loadConfig(){return this.deps.configStore.get(Zc)??null}handleConfigGet(e){let t=this.loadConfig(),r=Se(this.deps,e,"frozen:config:get:response",{config:t,sasDir:this.resolveSasDir(t),datasetDir:this.resolveDatasetDir(t)});this.deps.broker.postToWebview(r)}handleConfigSave(e){let t=nt(Fi,e,"frozen:config:save:error",this.deps);if(!t)return;this.deps.configStore.set(Zc,t.config,Zr);let r=Se(this.deps,e,"frozen:config:save:response",{success:!0});this.deps.broker.postToWebview(r)}resolveSasDir(e){return e?.sasDir??je.join(cl.homedir(),".sandforge-sas")}resolveDatasetDir(e){return e?.datasetDir??je.join(this.resolveSasDir(e),"dataset")}resolveRulesPath(e){return je.resolve(e?.rulesFilePath??je.join(this.resolveSasDir(e),Of))}async rulesFileInfo(e){let t=this.resolveRulesPath(e),r=null;try{r=await it(t)?await Ae.readFile(t,"utf8"):null}catch(n){return{path:t,found:!0,invalid:Q(n)}}return{path:t,...yc(r)}}async loadTokens(e,t){return await it(je.join(e,el))?Sc(e,el,t):{}}async describeObject(e,t){let r=`${e}::${t}`,n=this.describeCache.get(r);if(n)return n;let s=await new St(3e4).withTimeout(`frozen:describe:${t}`,async()=>{let d=await(await Oe(e,this.deps.orgRegistry,this.deps.orgManager)).describe(t);return{name:d.name,fields:d.fields.map(a=>({name:a.name,label:a.label,type:a.type,referenceTo:a.referenceTo??[],relationshipName:a.relationshipName??null,isMasterDetail:a.cascadeDelete===!0,nillable:a.nillable!==!1,createable:a.createable!==!1,updateable:a.updateable!==!1,restrictedPicklist:a.restrictedPicklist===!0,defaultedOnCreate:a.defaultedOnCreate===!0,...a.compoundFieldName?{compoundFieldName:a.compoundFieldName}:{}})),childRelationships:(d.childRelationships??[]).map(a=>({childSObject:a.childSObject,field:a.field,relationshipName:a.relationshipName??a.field,isCascadeDelete:a.cascadeDelete===!0}))}},3e4);return this.describeCache.set(r,s),s}buildDiscoveryService(){return new Ia({describeObject:(e,t)=>this.describeObject(e,t),queryCount:async(e,t)=>(await(await Oe(e,this.deps.orgRegistry,this.deps.orgManager)).query(t)).totalSize,detectPII:e=>{let t=this.deps.infraServices?.piiDetector;return t?On(t,e):[]},describeGlobal:e=>this.describeGlobal(e)})}async describeGlobal(e){let t=this.describeGlobalCache.get(e);if(t)return t;let s=(await(await Oe(e,this.deps.orgRegistry,this.deps.orgManager)).describeGlobal()).sobjects.map(i=>({name:i.name,keyPrefix:i.keyPrefix??null}));return this.describeGlobalCache.set(e,s),s}async keyPrefixes(e){let t=new Map;for(let{name:r,keyPrefix:n}of await this.describeGlobal(e))n&&t.set(r,n);return t}discoveryConfig(e,t){return{inputMode:"record",recordId:t,depth:"full",sourceOrgId:e,targetOrgId:e,anonymizePII:!1,skipEmpty:!0,batchSize:"auto"}}discoveryOptions(e){return{maxNodes:e.maxNodes??Ra}}async graphOfStep(e){let{sourceOrgId:t,config:r,sasDir:n,guard:s}=e,{maxNodes:i}=this.discoveryOptions(r),d={sourceOrgId:t,rootObject:r.rootObject,maxNodes:i},a=await Fc(n,s),u;if("kept"in a){let p=a.kept,g=Ec(p,d)??await this.schemaChangeSince(t,p);if(g===void 0)return this.holdKeptDescribes(t,p),{graph:p.graph,origin:{reusedFrom:p.step,discoveredAt:p.discoveredAt}};u=g}else u=a.none;let l;try{let p=await Oe(t,this.deps.orgRegistry,this.deps.orgManager);l=Lc((await p.soap.getServerTimestamp()).timestamp)}catch(p){this.deps.log(`[WARN] frozen: the source did not give its clock: ${String(p)}`)}let c=await this.buildDiscoveryService().discover(this.discoveryConfig(t,e.rootRecordId),{maxNodes:i,...e.signal?{signal:e.signal}:{},...e.onProgress?{onProgress:e.onProgress}:{}}),f=new Date().toISOString();return{graph:c,origin:{rediscovered:u},keep:async p=>{let g=new Set([...c.nodes.filter(m=>m.included).map(m=>m.objectApiName),...p]),h={};for(let m of g){let w=this.describeCache.get(`${t}::${m}`);w&&(h[m]=w)}await jc(n,{fileVersion:1,...d,step:e.step,discoveredAt:f,...l?{schemaStamp:l}:{},graph:c,describes:h,objects:this.describeGlobalCache.get(t)??[]},s)}}}async schemaChangeSince(e,t){if(!t.schemaStamp)return"the graph kept carries no stamp of the org";try{let n=await(await Oe(e,this.deps.orgRegistry,this.deps.orgManager)).request({method:"GET",url:"/sobjects",headers:{"If-Modified-Since":new Date(t.schemaStamp).toUTCString()}}),s=typeof n=="object"&&n!==null?n.sobjects:void 0;return Array.isArray(s)?(this.forgetOrg(e),this.describeGlobalCache.set(e,s.flatMap(i=>{let{name:d,keyPrefix:a}=i??{};return typeof d=="string"?[{name:d,keyPrefix:typeof a=="string"?a:null}]:[]})),`the source's schema changed since the graph kept was discovered, on ${t.discoveredAt}`):void 0}catch(r){return`the source could not say whether its schema changed: ${Q(r)}`}}holdKeptDescribes(e,t){for(let[r,n]of Object.entries(t.describes))this.describeCache.set(`${e}::${r}`,n,tl);t.objects.length>0&&this.describeGlobalCache.set(e,t.objects,tl)}async describeScopableFields(e,t){return(await this.describeObject(e,t)).fields.map(n=>({name:n.name,type:n.type,referenceTo:n.referenceTo,nillable:n.nillable!==!1}))}async ruleSchemaOf(e,t){let r=new Map;for(let{objectApiName:n}of t)try{let s=await this.describeObject(e,n);r.set(n,s.fields)}catch(s){this.deps.log(`[WARN] frozen: ${n} could not be described for the rules: ${String(s)}`)}return r}mappingStoreFor(e,t,r){let n=async()=>{try{let[s]=await this.buildTargetOrgAccess().query(t,"SELECT Id FROM Organization");return typeof s?.Id=="string"?s.Id:void 0}catch(s){this.deps.log(`[WARN] frozen: the target did not say which org it is: ${String(s)}`);return}};return new xn(e,{orgId:t,organizationId:n,guard:r})}buildTargetOrgAccess(){return{query:async(e,t)=>{let r=await Oe(e,this.deps.orgRegistry,this.deps.orgManager);return bn(r,t)},count:async(e,t)=>(await(await Oe(e,this.deps.orgRegistry,this.deps.orgManager)).query(t)).totalSize,describe:async(e,t)=>{let n=await(await Oe(e,this.deps.orgRegistry,this.deps.orgManager)).describe(t);return{name:n.name,createable:n.createable,cascadeChildren:(n.childRelationships??[]).flatMap(s=>s.cascadeDelete===!0&&typeof s.field=="string"&&s.field!==""?[{childSObject:s.childSObject,field:s.field}]:[]),fields:n.fields.map(s=>({name:s.name,type:s.type,createable:s.createable??!1,nillable:s.nillable??!0,defaultedOnCreate:s.defaultedOnCreate??!1,referenceTo:s.referenceTo??[],restrictedPicklist:s.restrictedPicklist??!1,picklistValues:(s.picklistValues??[]).map(i=>({value:i.value,active:i.active??!0})),updateable:s.updateable!==!1,unique:s.unique===!0,nameField:s.nameField===!0,...typeof s.filteredLookupInfo=="object"&&s.filteredLookupInfo!==null?{lookupFilter:{optional:s.filteredLookupInfo.optionalFilter===!0}}:{}})),recordTypeInfos:(n.recordTypeInfos??[]).flatMap(s=>{let{developerName:i,active:d}=s;return i?[{developerName:i,recordTypeId:s.recordTypeId,available:s.available,name:s.name,master:s.master,defaultRecordTypeMapping:s.defaultRecordTypeMapping,...d===void 0?{}:{active:d}}]:[]})}},picklistValues:async(e,t,r,n)=>{let s=await Oe(e,this.deps.orgRegistry,this.deps.orgManager);return ed(s,t,r,n)},userId:async e=>(await(await Oe(e,this.deps.orgRegistry,this.deps.orgManager)).soap.getUserInfo()).userId}}toLoadConfig(e){return{protectedOrgIds:e.protectedOrgIds,identityKeys:e.identityKeys,undeletableObjects:e.undeletableObjects,requiredLookupPlaceholders:e.requiredLookupPlaceholders,excludedObjects:e.excludedObjects,requiredFieldDefaults:e.requiredFieldDefaults,picklistRules:e.picklistRules,defaultPicklistRule:e.defaultPicklistRule,duplicateErrorPatterns:e.duplicateErrorPatterns,rootObjectApiName:e.rootObject}}async readFrozenDataset(e,t){let r=t.assertOutsideRepo(e),n=t.assertOutsideRepo(je.join(r,"manifest.json"));if(!await it(n))throw new Error(`No frozen dataset found at ${r} \u2014 run a selection (frozen:select) then an extraction (frozen:extract) first.`);let s=Fr(JSON.parse(await Ae.readFile(n,"utf8"))),i=[],d=t.assertOutsideRepo(je.join(r,"data"));if(await it(d))for(let f of(await Ae.readdir(d)).sort()){if(!f.endsWith(".json"))continue;let p=t.assertOutsideRepo(je.join(d,f)),g=JSON.parse(await Ae.readFile(p,"utf8"));i.push({objectApiName:g.objectApiName,records:g.records})}let a=async(f,p)=>{let g=t.assertOutsideRepo(je.join(r,f));return await it(g)?JSON.parse(await Ae.readFile(g,"utf8")):p},u=await a("record-types.json",{}),l=await a("personcontact-sidecar.json",[]),c=await a(Er,{});return{dataset:{datasetVersion:s.version,objects:i,recordTypes:u,personContactSidecar:l,...c.standardPricebook?{standardPricebook:c.standardPricebook}:{}},manifest:s}}errorCodeFor(e,t){return e instanceof mr?"RULES_MISSING":e instanceof He?"GUARD_REFUSED":e instanceof gd?"SAS_PATH_REFUSED":e instanceof Tr?"SALT_MISSING":e instanceof qt?"BUDGET_EXCEEDED":e instanceof et?"LOAD_CONFIG":e instanceof xr?"MAX_RECORDS":e instanceof cr?lo:e instanceof lt?"TIMEOUT":e instanceof tt?e.code:e instanceof Fo&&e.code==="invalid"?"INVALID_PAYLOAD":t}errorDetailOf(e){if(e instanceof tt)return{params:e.params};if(e instanceof mr)return{rulesPath:e.rulesPath};if(e instanceof He)return{guard:e.code,...e.params};if(e instanceof qt)return{total:e.total,budgetMax:e.budgetMax,heaviest:e.heaviest};if(e instanceof et&&e.gaps)return{gaps:e.gaps,...(e.refusedBeside??[]).length>0?{refusedBeside:e.refusedBeside}:{}};if(e instanceof et&&e.recordTypesUntold)return{recordTypesUntold:e.recordTypesUntold};if(e instanceof hr)return{emails:e.emails,orgId:e.orgId};if(e instanceof Qr)return{automation:e.automation,orgId:e.orgId};if(e instanceof en)return{apiRequests:e.apiRequests,orgId:e.orgId};if(e instanceof tn)return{storage:e.storage,orgId:e.orgId}}loadEmailsFor(e){return uc({read:e.read,...e.plan?{plan:e.plan}:{},writes:e.writes,inserts:e.dataset.objects.map(t=>({objectApiName:t.objectApiName,rows:t.records.length})).filter(t=>t.rows>0),readLimits:()=>La(e.conn),readDeliverability:()=>e.orgTier==="production"?Promise.resolve(na):oa(e.conn),accepted:e.accepted,target:this.orgNameOf(e.orgId),mayMute:e.mayMute})}async loadApiCheck(e){let t=await Aa(e.conn).catch(s=>({unread:Q(s)})),r=Qa(e.read),n=Pa({run:xc({inserts:e.dataset.objects.map(s=>({objectApiName:s.objectApiName,rows:s.records.length})),...e.purged?{purged:e.purged}:{},threshold:Io(this.deps).bulk.threshold,...r?{duplicateRules:r}:{},automationRead:xa(e.read)})+(e.replayReads??0),...ja(e.checkpoint),...aa(e.plan),...$a(e.emails?.run.ofRun)},t);return n.verdict==="unread"&&this.deps.log(`[WARN] ${e.operation}: the daily API requests the target has left could not be read (${n.unread})`),If(n,this.orgNameOf(e.orgId))}async purgedOf(e,t){if(await e.isStale())return[];let r=t.undeletableObjects??{};return(await e.recordedLoads()).flatMap(n=>ot(n)).map(({objectApiName:n,ids:s})=>({objectApiName:n,rows:s.length,deletes:!Object.hasOwn(r,n)}))}orgNameOf(e){let t=this.deps.orgManager.getOrg(e);return Js(t,e)}requireConfig(e,t){let r=this.loadConfig();return r||(te(this.deps,e.type,t,e,new Error("No frozen dataset configuration saved \u2014 save the project configuration first (frozen:config:save: coverage axes, root object, budget, load rules)."),{code:"CONFIG_MISSING"}),null)}setReplayStores(e){this.replayStores=e}replayStores;replayStoresInUse(){return this.replayStores??=$f(),this.replayStores}async sourceOf(e,t,r,n,s){if(t.replay===void 0){let i=this.requireConfig(e,r);return i?this.datasetSource(i,t.targetOrgId):void 0}try{if(t.pilot===!0)throw new tt("REPLAY_NO_PILOT","A replay loads no pilot: simulate it, then replay it whole. Nothing was read or written.");return await this.replaySourceOf(t.targetOrgId,t.replay,n)}catch(i){let d=this.errorCodeFor(i,"REPLAY_ERROR");s?.(d);let a=this.errorDetailOf(i);te(this.deps,e.type,r,e,i,{code:d,retryable:i instanceof lt,...a?{extraPayload:a}:{}});return}}datasetSource(e,t){let r=n=>n.assertOutsideRepo(this.resolveSasDir(e));return{config:e,sasDir:r,mappingStore:n=>this.mappingStoreFor(r(n),t,n),read:async n=>{let s=n.assertOutsideRepo(this.resolveDatasetDir(e)),{dataset:i,manifest:d}=await this.readFrozenDataset(s,n);return{dataset:i,manifest:d,datasetDir:s,label:d.version}}}}async replaySourceOf(e,t,r){let n=this.targetTier(e),s=n==="staging"?this.stagingReplayOf(e,t,r):void 0;Jo({orgId:e,orgName:this.orgNameOf(e),orgTier:n,...s?{stagingReplay:s}:{}});let i=this.replayStoresInUse(),d=i.replays.folderOf(t.organizationId,t.checkpointId),a=await this.replayTargetOf(e),u=jn(a.organizationId),l={folder:d,target:a,contractPath:i.replays.contractPathOf(d,u),...s?{stagingReplay:s}:{}},c=m=>new Ds(d.dir,{guard:m,orgId:u,organizationId:a.organizationId},e);if(r==="mapping")return{config:al(t.config,void 0),sasDir:()=>d.dir,mappingStore:c,read:()=>Promise.reject(new Error("A removal of a replay reads no checkpoint")),replay:l};let f=await this.replayedCheckpointOf(i,t),p=t.choices??(await i.replays.read(d))?.targets.find(m=>m.organizationId===u)?.choices;if(p===void 0)throw new tt("NO_LOAD",`No replay of checkpoint ${t.checkpointId} into ${a.name} is recorded on this machine: replay it there first, then verify. Nothing was read or written.`,{checkpoint:t.checkpointId,target:a.name});let g=Sd({checkpoint:f.checkpoint,checkpointId:t.checkpointId,choices:p,target:a});if(g)throw new tt(g.code,g.message,g.params);if(f.checkpoint===void 0)throw new tt("REPLAY_CHECKPOINT_UNUSABLE","The checkpoint does not read.");let h=f.checkpoint;return l.checkpoint={checkpoint:h,folder:f.folder,annex:f.annex},l.choices=p,{config:al(t.config,p),sasDir:()=>d.dir,mappingStore:c,read:async()=>(l.converted??=await this.convertReplay(l,p,e),{dataset:l.converted.conversion.dataset,label:h.name}),replay:l}}stagingReplayOf(e,t,r){if(r!=="load")return!0;let n=this.orgNameOf(e);if(t.confirmStaging===n)return!0;throw new tt("REPLAY_STAGING_UNCONFIRMED",`${n} is a sandbox marked Staging, which may hold real data: a replay goes into it once its name is typed to confirm it. Nothing was read or written.`,{target:n})}async replayedCheckpointOf(e,t){for(let r of e.checkpoints()){let n=(await r.checkpointsOf(t.organizationId)).find(s=>s.folder.checkpointId===t.checkpointId);if(n!==void 0){if(n.checkpoint===void 0)return{folder:n.folder,annex:void 0};try{return{checkpoint:n.checkpoint,folder:n.folder,annex:await Sa(n.folder)}}catch(s){throw s instanceof Fo?new tt("REPLAY_CHECKPOINT_UNUSABLE",`${s.message}: what checkpoint '${n.checkpoint.name}' says of its record types, users and catalogue cannot be told. Nothing was read or written.`,{checkpoint:n.checkpoint.name,why:"damaged"}):s}}}throw new tt("CHECKPOINT_NOT_FOUND",`No checkpoint ${t.checkpointId} of org ${t.organizationId} is kept on this machine: import its file first, or name one the checkpoint list shows. Nothing was read or written.`,{checkpoint:t.checkpointId})}async replayTargetOf(e){let t=this.buildTargetOrgAccess(),r=this.orgNameOf(e),[n]=await t.query(e,"SELECT Id FROM Organization");if(typeof n?.Id!="string")throw new Error(`${r} did not say which org it is: nothing was read or written.`);let s=n.Id,i=await t.userId?.(e);if(i===void 0)throw new Error(`${r} did not say which user the replay writes as.`);let d=this.deps.orgManager.getOrg(e),a=this.deps.sandboxRefreshes,u=[d?.orgId,a?.organizationIdOf(e),...a?.refreshesOf(e).map(l=>l.previousOrganizationId)??[]].filter(l=>typeof l=="string"&&l.slice(0,15)!==s.slice(0,15));return{name:r,organizationId:s,runningUserId:i,...d?.username?{username:d.username}:{},...d?.instanceUrl?{instanceUrl:d.instanceUrl}:{},formerOrganizationIds:[...new Set(u)],tier:d?.orgType==="Sandbox"?"sandbox":d?.orgType==="Scratch"?"scratch":"developer"}}async convertReplay(e,t,r){let n=e.checkpoint;if(n===void 0)throw new Error("The checkpoint of the replay was not read");let s=await Kc({folder:n.folder,checkpoint:n.checkpoint,annex:n.annex,choices:t,access:this.buildTargetOrgAccess(),orgId:r,organizationId:e.target.organizationId,runningUserId:e.target.runningUserId,tier:e.target.tier,...e.target.username!==void 0?{username:e.target.username}:{},targetName:e.target.name});if("refusal"in s)throw new tt(s.refusal.code,s.refusal.message,{users:s.refusal.users.join(", ")});return{conversion:s.conversion,target:s.target}}replayInfoOf(e,t,r){let n=e.checkpoint,s=e.converted;if(n===void 0||s===void 0||e.choices===void 0)return;let{checkpoint:i}=n,{summary:d,filesLeft:a}=s.conversion;return{checkpoint:{checkpointId:i.checkpointId,name:i.name,organizationId:i.org.organizationId,...i.org.alias!==void 0?{alias:i.org.alias}:{},takenAt:i.takenAt,tier:i.org.tier,annex:n.annex!==void 0},target:{organizationId:jn(e.target.organizationId),name:e.target.name},choices:e.choices,summary:{...d,records:{...d.records,toCreate:Math.max(0,d.records.toCreate-t),linkedByKey:t}},filesLeft:a.map(({objectApiName:u,name:l})=>({objectApiName:u,...l!==void 0?{name:l}:{}})),...r?{storage:r}:{},requests:s.target.requests}}async loadSentOf(e,t){let r;try{r=await e.request({method:"GET",url:"/sobjects"})}catch{return}let n=bf.safeParse(r);if(!n.success)return;let s=new Set(n.data.sobjects.filter(i=>i.createable!==!1).map(i=>i.name.toLowerCase()));return{takes:i=>s.has(i.toLowerCase()),byThePlatform:Qd(t)}}async loadStorageOf(e){let t=await zo(e.conn).catch(()=>{});if(t===void 0)return;let r=Math.max(0,e.automationBytes??0),n=Hc({dataset:e.dataset,storage:t,...e.sent?{sent:e.sent}:{},...e.purged?{purged:e.purged}:{},automationBytes:r,target:this.orgNameOf(e.targetOrgId),...e.replay===!0?{replay:!0}:{},...e.pilot===!0?{pilot:!0}:{}}),s=1024*1024;return{estimateMB:n?.storage.estimateMB??(ul(e.dataset,e.sent)+r)/s,...r>0?{automationMB:r/s}:{},remainingMB:t.remainingMB,maxMB:t.maxMB,...n?.storage.freedMB!==void 0?{freedMB:n.storage.freedMB}:{},...e.pilot===!0?{pilot:!0}:{},...n?{refusal:{code:ll,message:n.message}}:{}}}async handleSelect(e){let t=nt(Ei,e,"frozen:select:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:select:error");if(!r)return;let n=`frozen-select-${this.deps.nextId()}`;vr(this.deps,n,"frozen","Running coverage-matrix selection");let s="Coverage-matrix selection",i=new AbortController,d=setTimeout(()=>i.abort("timeout"),Pf),a=()=>{},u=new Promise((c,f)=>{a=p=>p===void 0?c():f(p)});u.catch(()=>{}),this.registry?.register(e.id,"frozen",s,u,i),this.liveTracker?.register(e.id,"frozen",s);let l=c=>{this.deps.broker.postToWebview(Se(this.deps,e,"frozen:select:progress",{...c})),c.phase==="combination"&&c.index!==void 0&&c.of&&this.liveTracker?.updateProgress(e.id,Math.round((c.index-1)/c.of*100),c.index-1,c.of,c.combinationKey??"")};try{let c=new fe,f=c.assertOutsideRepo(this.resolveSasDir(r)),p=await Oe(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),g=new Map,h=async B=>{let D=g.get(B);return D||(D=bn(p,B),g.set(B,D),D.catch(()=>g.delete(B))),(await D).map(G=>({...G}))},m=await this.loadTokens(f,c),w=this.discoveryOptions(r),R=new Set,P=new Ur({query:h,describeFields:B=>(R.add(B),this.describeScopableFields(t.sourceOrgId,B)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),j=new Date().toISOString(),T,$=0,q=async B=>(T??=this.graphOfStep({step:"select",sourceOrgId:t.sourceOrgId,config:r,sasDir:f,guard:c,rootRecordId:B,signal:i.signal,onProgress:D=>{D.phase==="object"&&(D.discoveredCount-$<10&&D.queueRemaining>0||($=D.discoveredCount,l({phase:"discovery",objects:D.discoveredCount})))}}),Ns((await T).graph,r.excludedObjects)),C=async B=>{if(B.length===0)return{};let D=await q(B[0]),G=await P.extract({graph:D,rootObject:r.rootObject,rootRecordIds:B,asOf:j,sasDir:f,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:m,guard:c}),V={};for(let L of G.objects)V[L.objectApiName]=L.records.length;return V},I=new Zn(C,r.expectedObjects??[]),b=async(B,D)=>(await this.describeObject(t.sourceOrgId,B)).fields.find(G=>G.name.toLowerCase()===D.toLowerCase())?.type,F=await new Xn({query:h,checkHealth:I,measureVolumetry:C,fieldType:b}).select({rootObject:r.rootObject,axes:r.axes,edgeCases:r.edgeCases,budgetMaxRecords:r.budgetMaxRecords,candidatesPerCombination:r.candidatesPerCombination,tokens:m},{signal:i.signal,onProgress:l}),v=await Pc(f,F,c),A=T&&!F.stopped?await T.catch(()=>{}):void 0;A?.keep&&await A.keep(R).catch(B=>{this.deps.log(`[WARN] frozen: the graph could not be kept in the sas: ${String(B)}`)});let N=A?Ns(A.graph,r.excludedObjects):void 0,M=Se(this.deps,e,"frozen:select:response",{selection:{...Lf(F,v,N?sl(N,w.maxNodes):void 0),...A?{discovery:A.origin}:{}}});this.deps.broker.postToWebview(M),Rt(this.deps,n,{roots:F.roots.length,total:F.volumetry.total,...F.stopped?{stopped:F.stopped.reason}:{}}),F.stopped?.reason==="cancelled"?this.liveTracker?.cancel(e.id):this.liveTracker?.complete(e.id),a()}catch(c){this.liveTracker?.fail(e.id,Q(c)),a(c),te(this.deps,"frozen:select","frozen:select:error",e,c,{code:this.errorCodeFor(c,"SELECT_ERROR"),retryable:c instanceof lt,extraPayload:this.errorDetailOf(c)})}finally{clearTimeout(d)}}async handleExtract(e){let t=nt(Ni,e,"frozen:extract:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:extract:error");if(!r)return;let n=`frozen-extract-${this.deps.nextId()}`;vr(this.deps,n,"frozen","Extracting + pseudonymizing dataset");try{let s=new fe,i=s.assertOutsideRepo(this.resolveSasDir(r)),d=s.assertOutsideRepo(this.resolveDatasetDir(r)),a=await this.saltKeeper.forExtraction(),u=new Ln(a.salt);if(a.created&&this.sayTheSaltWasMade(u.saltFingerprint),!await it(je.join(i,Wr))){te(this.deps,"frozen:extract","frozen:extract:error",e,new Error(`No selection found in ${i} \u2014 run the coverage-matrix selection first (frozen:select).`),{code:"SELECTION_MISSING"});return}let l=await fs(i,s),c=l.roots.map(G=>G.rootRecordId);if(c.length===0){te(this.deps,"frozen:extract","frozen:extract:error",e,new Error("The last selection kept no root: every combination was uncovered, and the selection says why for each. Adjust the axes or the expected objects, then run the selection again."),{code:"SELECTION_EMPTY"});return}let f=await this.loadTokens(i,s),p=this.resolveRulesPath(r);if(!await it(p))throw new mr(p,`Pseudonymization rules file not found at ${p} \u2014 it is the source of truth (object.field \u2192 generator). Create it, or set rulesFilePath in the configuration.`);let g=Jn(JSON.parse(await Ae.readFile(p,"utf8"))),h=await Oe(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),m=this.discoveryOptions(r),w=await this.graphOfStep({step:"extract",sourceOrgId:t.sourceOrgId,config:r,sasDir:i,guard:s,rootRecordId:c[0]}),R=Ns(w.graph,r.excludedObjects),P=new Set,j,T=new Ur({query:G=>j?.aborted?Promise.reject(new Error("The extraction ran out of time and stopped.")):bn(h,G),describeFields:G=>(P.add(G),this.describeScopableFields(t.sourceOrgId,G)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),$=t.author??"sandforge",q=r.datasetVersion??Af,{extracted:C,frozen:I,report:b,requiredLeftEmpty:O,keptUnruled:F}=await new St(Es).withTimeout("frozen:extract",async G=>{j=G;let V=await T.extract({graph:R,rootObject:r.rootObject,rootRecordIds:c,asOf:new Date().toISOString(),sasDir:i,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:f,guard:s}),L=await this.ruleSchemaOf(t.sourceOrgId,V.objects),H=wc(g,L,this.deps.infraServices?.piiDetector??new Sn),K=new to().anonymize({extracted:V,rules:H,pseudonymizer:u,datasetVersion:q}),re=new ro().run(V,K,H,{author:$});return{extracted:V,frozen:K,report:re,requiredLeftEmpty:Rc(V,H,L),keptUnruled:bc(V,H)}});O.length>0&&this.deps.log(`[WARN] frozen: the rules leave ${O.length} required field(s) empty, which a load will ask a value for: ${O.join(", ")}`),w.keep&&await w.keep(P).catch(G=>{this.deps.log(`[WARN] frozen: the graph could not be kept in the sas: ${String(G)}`)});let v=Se(this.deps,e,"frozen:control:result",{report:fl(b)});if(this.deps.broker.postToWebview(v),!b.passed){te(this.deps,"frozen:extract","frozen:extract:error",e,new Error("Non-reidentification control FAILED \u2014 nothing was written. Fix the rules file and re-run the extraction (see frozen:control:result for the failing checks)."),{code:"CONTROL_FAILED"});return}let A={};for(let G of I.objects)A[G.objectApiName]=G.records.length;let N=this.deps.orgManager.getOrg(t.sourceOrgId),M=Pd({version:q,source:{orgId:t.sourceOrgId,orgAlias:N?.alias,decisionDate:l.selectedAt},saltFingerprint:u.saltFingerprint,rulesVersion:g.rulesVersion,volumetry:{budgetMax:l.volumetry.budgetMax,measured:A,measuredAt:new Date().toISOString()},nonReidentification:b,author:$,coverage:{...sl(R,m.maxNodes),unboundedObjects:C.unboundedObjects,filesLeftOut:I.filesLeftOut??[],...(C.leftToThePlatform??[]).length>0?{leftToThePlatform:$n(C.leftToThePlatform??[])}:{},...C.exclusionCosts?{exclusionCosts:C.exclusionCosts}:{},...O.length>0?{requiredLeftEmpty:O}:{},...F.length>0?{keptWithoutARule:F}:{},encryptedNotKept:C.encryptedNotKept??[]}}),B=await new Bn(s).write(d,I,M,b),D=Se(this.deps,e,"frozen:extract:response",{datasetDir:B.dir,files:B.files,recordCount:dr(I),manifest:ol(M),discovery:w.origin});this.deps.broker.postToWebview(D),Rt(this.deps,n,{records:dr(I),version:M.version})}catch(s){let i=s instanceof lt,d=i?new Error(`The extraction ran out of its ${Es/6e4} minutes and stopped, and nothing was written: it reads every record of the roots the selection kept, so run again it would stop again. Keep fewer roots: lower the budget in the configuration, or narrow the axes, then run the selection and the extraction again.`):s;te(this.deps,"frozen:extract","frozen:extract:error",e,d,{code:i?Tf:this.errorCodeFor(s,"EXTRACT_ERROR"),retryable:!1,extraPayload:i?{minutes:Es/6e4}:this.errorDetailOf(s)})}}async handleRulesClear(e){let t=nt(Li,e,"frozen:rules:clear:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:rules:clear:error");if(r)try{let n=this.resolveRulesPath(r);if(!await it(n))throw new mr(n,`Pseudonymization rules file not found at ${n} \u2014 nothing was written. Create it, or set rulesFilePath in the configuration.`);let s=kc(JSON.parse(await Ae.readFile(n,"utf8")),t.fields);if(s.cleared.length>0){let d=`${n}.${process.pid}.writing`;await Ae.writeFile(d,`${JSON.stringify(s.payload,null,2)}
21
- `,"utf8"),await Ae.rename(d,n),this.deps.log(`[INFO] frozen: ${s.cleared.length} field(s) given a clear rule in ${n} (rules ${s.rulesVersion}): ${s.cleared.join(", ")}`)}let i=Se(this.deps,e,"frozen:rules:clear:response",{rulesPath:n,rulesVersion:s.rulesVersion,cleared:s.cleared,alreadyRuled:s.alreadyRuled});this.deps.broker.postToWebview(i)}catch(n){te(this.deps,"frozen:rules:clear","frozen:rules:clear:error",e,n,{code:this.errorCodeFor(n,"RULES_CLEAR_ERROR"),extraPayload:this.errorDetailOf(n)})}}async handleRulesCreate(e){let t=this.resolveRulesPath(this.loadConfig()),r=!1;try{await Ae.mkdir(je.dirname(t),{recursive:!0});try{await Ae.writeFile(t,hc(mc),{encoding:"utf8",flag:"wx"}),r=!0,this.deps.log(`[INFO] frozen: empty rules file written at ${t}`)}catch(s){if(s.code!=="EEXIST")throw s;if(!(await Ae.stat(t)).isFile())throw new Error(`${t} is not a file: no rules file can be written there.`)}}catch(s){te(this.deps,"frozen:rules:create","frozen:rules:create:error",e,s,{code:"RULES_CREATE_ERROR"});return}let n=!1;try{await this.openInEditor(t),n=!0}catch(s){this.deps.log(`[WARN] frozen: rules file not opened: ${Q(s)}`)}this.deps.broker.postToWebview(Se(this.deps,e,"frozen:rules:create:response",{rulesPath:t,created:r,opened:n}))}targetTier(e){let t=this.deps.orgManager.getOrg(e);return Ys(t)}async handleLoad(e){let t=nt(Po,e,"frozen:load:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:load:error","load",L=>Qe(this.deps,{action:"checkpoint_replay",module:"checkpoint",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:L}));if(!r)return;let{config:n}=r,s=_f(r),i=r.replay,d=this.deps.infraServices?.productionGuard;if(!d){Qe(this.deps,{...s,operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:Ot.code}),te(this.deps,"frozen:load","frozen:load:error",e,new Error(Ot.message),{code:Ot.code});return}let a=await this.replaceRefusal(t,r),u=a&&"error"in a?a:void 0,l=a&&"cameAlong"in a?a.cameAlong:void 0;if(u){u.code===lo&&Qe(this.deps,{...s,operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:lo}),te(this.deps,"frozen:load","frozen:load:error",e,u.error,{code:u.code,retryable:u.retryable});return}let c=e.id,f=i?`Replaying checkpoint '${i.checkpoint?.checkpoint.name??""}'`:t.pilot?"Pilot load (one root folder)":"Loading frozen dataset";vr(this.deps,c,s.module,f),this.liveTracker?.register(c,s.module,f);let p=!1,g=!1,h=new AbortController,m=()=>{},w=new Promise((L,H)=>{m=K=>K===void 0?L():H(K)});w.catch(()=>{}),this.registry?.register(c,s.module,f,w,h);let R=nl(L=>{let H=Se(this.deps,e,"frozen:load:progress",{...L});this.deps.broker.postToWebview(H),!p&&!g&&this.liveTracker?.updateProgress(c,L.progress,0,0,L.message)},100),P,j=!1,T=!1,$,q=new Date().toISOString(),C,I,b,O,F,v=(L,H,K,re)=>{if(T)return;T=!0;let _=L!=="stopped"&&C!==void 0,U=b?ca(da(b.run.gate,b.info.accepted&&b.info.verdict==="asks").emails):{},de=i?.checkpoint&&i.choices?{replayCheckpoint:i.checkpoint.checkpoint.checkpointId,...Ad(i.checkpoint.checkpoint,i.choices,i.target),...i.stagingReplay?{replayIntoStaging:!0}:{}}:{},X={..._?{sas:C,startedAt:q,...I?{lastWriteAt:I}:{}}:{},...U,...de};Qe(this.deps,{...s,operationId:c,orgId:t.targetOrgId,outcome:L,guard:P,objects:H,source:{origin:i?"checkpoint":"dataset",label:$},carried:K,...re?{code:re}:{},...A?{muted:gn(A)}:{},...M?.state==="taken"?{checkpointId:M.checkpointId}:{},...Object.keys(X).length>0?{details:X}:{}})},A,N,M,B=!1,D=!1,G=!1,V=[];try{let L=new fe,H=r.sasDir(L);C=Yn(H);let{dataset:K,manifest:re,datasetDir:_,label:U}=await r.read(L);$=U;let de=this.buildTargetOrgAccess(),X=await Oe(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),pe=Io(this.deps),Be=Ii(this.deps),Ne=y=>new ud({connection:X,bulkExecutor:new _i(pe.bulk.threshold),bulkManager:Be,retryConfig:pe.retry,...y?{signal:y}:{},onProgress:()=>{},log:x=>this.deps.log(x)}),k=Ne(h.signal),E=n.mockDetection?new Cr(de,n.mockDetection):{areCalloutsMocked:async()=>!0},S=r.mappingStore(L),J=$t(X,"frozen:load"),ne=new $r({orgAccess:de,writer:bs(k),restoringWriter:bs(Ne(void 0)),guard:d,mockDetector:E,recordTypeResolver:new Kr(de),mappingStore:S,config:this.toLoadConfig(n),sasGuard:L,serverTime:()=>J.serverTime()});if(t.sweep===!0&&t.reload===!0&&!t.pilot){V=await this.reloadSweepsOf({conn:X,store:S,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,includeChanged:t.includeChanged===!0,signal:h.signal,guard:d,operationId:c,audit:fo(r)});for(let{sweep:y}of V)await y.ask()}let Z=Xr([],V.flatMap(({sweep:y})=>y.takes)),ge=(Z.delete??[]).length>0?this.removalAsker:void 0,ee=K.objects.map(y=>y.objectApiName),Ie=t.reload===!0&&!t.pilot?await this.purgeStepsOf(S,n):void 0,z=await this.targetAutomation.read(t.targetOrgId,[...new Set([...ee,...Ie?.delete??[],...Z.delete??[]])]).catch(y=>({unread:Q(y)})),ve=Ie?Rr(Ie):void 0,Ge=Rr(Z),Ye=(y,x)=>uo(y,x)||ve?.(y,x)===!0||Ge(y,x),W=t.muteAutomation===!0?await Sr(async()=>Or(X),z,{...this.muteLeases,writes:Ye}):void 0;if(A=W?.muted,ge&&!h.signal.aborted){let y=await ge({read:z,steps:Z,mute:W});if(y)throw new gr(y)}let se=this.targetTier(t.targetOrgId),jt=await ne.gateLoad({orgId:t.targetOrgId,orgName:this.orgNameOf(t.targetOrgId),orgTier:se,...i?.stagingReplay?{stagingReplay:!0}:{},dataset:K,manifest:re,reload:t.reload,pilot:t.pilot?{}:void 0,onProgress:y=>R(y),onGuardDecision:y=>{P=jo(P,y)}}),ce=as({read:z,...W?.plan?{plan:W.plan}:{},written:ee,accepted:t.acceptAutomation===!0,target:this.orgNameOf(t.targetOrgId),mayMute:t.muteAutomation!==!0&&this.muteOffered});if(O=ce.info,ce.stop&&ce.info)throw new Qr(ce.stop.code,ce.stop.message,ce.info,t.targetOrgId);let Ft=t.acceptEmails===!0,Ue=Ps(K,n,t.pilot),Pe=await this.loadEmailsFor({conn:X,orgId:t.targetOrgId,orgTier:se,read:z,...W?.plan?{plan:W.plan}:{},writes:Ye,dataset:Ue,accepted:Ft,mayMute:t.muteAutomation!==!0&&this.muteOffered});if(b=Pe,Pe.stop)throw new hr(Pe.stop.code,Pe.stop.message,Pe.info,t.targetOrgId);let ye=t.checkpointFirst!==void 0?await this.scopeLoadCheckpoint({msg:e,orgId:t.targetOrgId,written:ee,read:z,mute:W,request:t.checkpointFirst,replay:i!==void 0}):void 0,Ce=Ie?await this.purgedOf(S,n):void 0,ht=Promise.resolve().then(()=>X.request({method:"GET",url:"/limits"}));ht.catch(()=>{});let It={request:()=>ht},go=await zo(It).catch(y=>({unread:Q(y)})),rn=await this.loadSentOf(X,Ue),yr=Hc({dataset:Ue,storage:go,...rn?{sent:rn}:{},...Ce?{purged:Ce}:{},automationBytes:Yc(z,W?.plan,Ue,Ye),target:this.orgNameOf(t.targetOrgId),...i?{replay:!0}:{},...t.pilot===!0?{pilot:!0}:{}});if(yr)throw new tn(yr.message,yr.storage,t.targetOrgId);if(F=await this.loadApiCheck({conn:It,dataset:Ue,...Ce?{purged:Ce}:{},read:z,...ye?{checkpoint:ye.estimate}:{},...W?.plan?{plan:W.plan}:{},emails:Pe,orgId:t.targetOrgId,operation:`frozen:load ${c}`,...i?.converted?{replayReads:i.converted.target.requests}:{}}),F.refused)throw new en(F.refused.message,F,t.targetOrgId);i?.checkpoint&&i.choices&&await this.replayStoresInUse().replays.record(i.checkpoint.checkpoint,{organizationId:i.target.organizationId,name:i.target.name},i.choices),ye&&(N=await this.takeLoadCheckpoint(ye,h.signal));let Je=W?.prepared?await W.prepared.acquire(c):void 0;Je&&(A=Je.outcome,G=!0);let Et=Je?Pe.run.afterLease(Je.outcome,Ft):void 0;if(Je&&Et)throw A=await Je.release(),new hr(Et.code,Et.message,Pe.info,t.targetOrgId);B=!0;let ft=()=>ne.load({orgId:t.targetOrgId,orgName:this.orgNameOf(t.targetOrgId),orgTier:se,...i?.stagingReplay?{stagingReplay:!0}:{},dataset:K,manifest:re,sasDir:H,reload:t.reload,pilot:t.pilot?{}:void 0,...t.writeEncrypted?{writeEncrypted:!0}:{},...t.maxRecords!==void 0?{maxRecords:t.maxRecords}:{},...i?{linkByKeys:!0,contractOrgId:jn(i.target.organizationId)}:{},onProgress:y=>R(y),onGuardDecision:y=>{P=jo(P,y),(y==="allowed"||y==="confirmed")&&(j=!0)},signal:h.signal,...Je?{lease:{giveBack:()=>Je.release()}}:{},...V.length>0?{purgeSweep:{first:async()=>{for(let{sweep:y}of V)await y.first()},afterPurge:async()=>{for(let{sweep:y}of V)await y.afterRemoval()},stillToSweep:()=>V.filter(({sweep:y})=>!Ts(y.result())).map(({loadedAt:y})=>y)}}:{}}),Ke=await(jt==="confirmed"?ea({approved:!0},ft):ft()).finally(async()=>{Je&&(A=await Je.release())});D=!0,R.flush();let at=await this.settleReloadSweeps(V),nn=at.some(y=>y.result.status!=="success");N&&(M=await this.settleCheckpoint(N,po(Ke)>0)),I=ac(await S.recorded().catch(()=>{}),q);let vt=_!==void 0?je.join(_,"manifest.json"):void 0;g=!0;let Lt=await this.verifyLoad({orgId:t.targetOrgId,contractPath:Ke.contractPath,...vt!==void 0?{manifestPath:vt}:{},dataset:K,mappingStore:S,config:n,onProgress:R}),Nt="verdict"in Lt?Lt.verdict.status:void 0,Vt=Nt==="failed"||Nt==="partial"?Nt:void 0,Ht=Ke.status==="completed"&&(nn||Vt!==void 0)?"partial":Ke.status,on=Mf(Ke);if(v(Vt!==void 0&&on==="success"?"partial":on,Ms(Ke),await xf(K,S)),_!==void 0&&vt!==void 0){let y={contractPath:Ke.contractPath,datasetDir:_,manifestPath:vt,targetOrgId:t.targetOrgId,status:Ht,at:new Date().toISOString()};this.recordLastRun(y)}let Yt=zf(Ke),wr=Object.fromEntries(Object.entries(l??{}).filter(([y])=>(Yt.purge.deleted[y]??0)>0)),br=Se(this.deps,e,"frozen:load:response",{report:{...Yt,...Object.keys(wr).length>0?{purge:{...Yt.purge,cameAlong:wr}}:{},status:Ht,...Vt?{verification:Vt}:{},...A?{mutedAutomation:A}:{},...M?{checkpoint:M}:{},...at.length>0?{sweeps:at}:{},...b&&Xc(b.info)?{emails:b.info}:{},...O?{automation:O}:{},...F?{apiRequests:F}:{}},...i?Jc(this.replayInfoOf(i,kf(Ke,K))):{}});this.deps.broker.postToWebview(br),Rt(this.deps,c,{status:Ht}),p=!0,Ht!=="completed"?this.liveTracker?.partial(c):this.liveTracker?.complete(c),this.postVerification(e,Lt),m()}catch(L){R.flush();let H=await this.settleReloadSweeps(V).catch(()=>[]),K=H.length>0?{sweeps:H}:{};if(N&&M===void 0){let S=L instanceof st||L instanceof Bt?L.written:void 0;M=await this.settleCheckpoint(N,S?po(S)>0:B&&!Tn(L))}let re=M?{checkpoint:M}:{},_=G&&A?{mutedAutomation:A}:{};if(L instanceof Kt){v("stopped",void 0,void 0,L.code),te(this.deps,"frozen:load","frozen:load:error",e,L,{code:L.code,...L.code==="LOAD_CANCELLED"?{extraPayload:{written:0}}:{}}),L.code==="LOAD_CANCELLED"?(this.registry?.abort(c),Rt(this.deps,c,{aborted:!0}),this.liveTracker?.cancel(c),m()):(vo(this.deps,c,L.message,!0),this.liveTracker?.fail(c,L.message),m(L));return}if(L instanceof st){let S=Df(L.written);v(S,Ms(L.written),void 0,S==="stopped"?"LOAD_CANCELLED":void 0),this.registry?.abort(c),Rt(this.deps,c,{aborted:!0}),this.liveTracker?.cancel(c),te(this.deps,"frozen:load","frozen:load:error",e,L,{code:"LOAD_CANCELLED",extraPayload:{written:po(L.written),...re,...K,..._}}),m();return}let U=Tn(L)||L instanceof tt||L instanceof gr||L instanceof hr||L instanceof Qr||L instanceof en||L instanceof tn?L:void 0,de=U!==void 0||(P==="refused"||P==="declined")&&!j,X=L instanceof Bt?L:void 0,pe=X?X.cause:L,Be=U?.code??this.errorCodeFor(pe,"LOAD_ERROR"),Ne=X===void 0&&!D&&!j;v(de||Ne?"stopped":"failure",X?Ms(X.written):void 0,void 0,U?.code??(Ne?Be:void 0));let E={...X&&pe instanceof He?{guard:pe.code}:this.errorDetailOf(pe),...re,...K,..._,...Ne?{written:0}:{}};te(this.deps,"frozen:load","frozen:load:error",e,L,{code:Be,retryable:pe instanceof lt,extraPayload:Object.keys(E).length>0?E:void 0}),p||(vo(this.deps,c,Q(L),!0),this.liveTracker?.fail(c,Q(L))),m(L)}}loadCheckpointAsk(e){let{read:t}=e;return{module:e.replay===!0?"replay":"frozen",orgId:e.orgId,operationId:e.operationId,written:[...e.written],running:"objects"in t?zt(t,e.mute?.plan,uo):{firing:[]},request:e.request}}async previewCheckpoint(e){let t=this.beforeRunCheckpoints;if(!t)return;let r=await this.targetAutomation.read(e.orgId,e.written).catch(i=>({unread:Q(i)})),n=e.muteAutomation?await Sr(async()=>Or(e.conn),r,{...this.muteLeases,writes:uo}).catch(i=>{Mt.warn(`Frozen preview: the mute could not be planned (${Q(i)})`)}):void 0,s=this.loadCheckpointAsk({...e,operationId:e.msg.id,read:r,...n?{mute:n}:{}});return t.scope(s,{}).catch(i=>{Mt.warn(`Frozen preview: ${En(i)}`)})}async scopeLoadCheckpoint(e){let t=this.beforeRunCheckpoints;if(!t)throw new Kt(Pr,En(new Error("SandForge's checkpoints are not set up in this window")));let r=this.loadCheckpointAsk({...e,operationId:e.msg.id}),n={operationId:il(e.msg.id)},s;try{s=await t.scope(r,n)}catch(d){throw new Kt(Pr,En(d))}let i=Fa(s);if(i)throw new Kt(i.code,i.message);return{checkpoints:t,ask:r,own:n,estimate:s}}async takeLoadCheckpoint(e,t){let{checkpoints:r,ask:n,own:s,estimate:i}=e,d=await Ea(()=>r.take(n,s,{planned:i,signal:t}));if("stop"in d)throw new Kt(d.stop.code===Pr?Pr:"LOAD_CANCELLED",d.stop.message);return d.checkpoint}async settleCheckpoint(e,t){let r=this.beforeRunCheckpoints;if(!r)return e;try{return await r.settle(e,t)}catch(n){return Mt.warn(`Frozen load: the checkpoint '${e.name}' taken before it is kept, as it could not be settled (${Q(n)})`),e}}recordLastRun(e){this.moveOldVerify();let t={...this.lastRuns()},r=this.deps.configStore.get(pr);r&&t[r.targetOrgId]===void 0&&(t[r.targetOrgId]=r),t[e.targetOrgId]=e,this.deps.configStore.set(Qc,t,Zr),this.deps.configStore.set(pr,e,Zr)}recordLastVerify(e,t){this.moveOldVerify(),this.deps.configStore.set(Fs,{...this.lastVerifies(),[e]:t},Zr)}lastVerifies(){return this.deps.configStore.get(Fs)??{}}orgOfOldVerify(e){let t=this.deps.configStore.get(pr);return!t||Date.parse(t.at)>Date.parse(e.measuredAt)?void 0:Object.keys(this.lastRuns()).filter(n=>n!==t.targetOrgId).length===0?t.targetOrgId:void 0}moveOldVerify(){let e=this.deps.configStore.get(js);if(!e)return;let t=this.orgOfOldVerify(e),r=this.lastVerifies();t!==void 0&&r[t]===void 0&&this.deps.configStore.set(Fs,{...r,[t]:e},Zr),this.deps.configStore.delete(js)}lastVerifyInfos(){let e={...this.lastVerifies()},t=this.deps.configStore.get(js),r=t?this.orgOfOldVerify(t):void 0;return t&&r!==void 0&&e[r]===void 0&&(e[r]=t),Object.entries(e).map(([n,s])=>({orgId:n,status:s.status,measuredAt:s.measuredAt}))}lastRuns(){return this.deps.configStore.get(Qc)??{}}lastRunOf(e){let t=this.lastRuns()[e];if(t)return t;let r=this.deps.configStore.get(pr);return r?.targetOrgId===e?r:void 0}lastLoadInfos(){let e={...this.lastRuns()},t=this.deps.configStore.get(pr);return t&&e[t.targetOrgId]===void 0&&(e[t.targetOrgId]=t),Object.values(e).map(r=>({status:r.status,orgId:r.targetOrgId,at:r.at}))}async handlePreview(e){let t=nt(Po,e,"frozen:load:preview:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:load:preview:error","checkpoint");if(!r)return;let{config:n,replay:s}=r,i=await this.replaceRefusal(t,r,t.goneFirst),d=i&&"error"in i?i:void 0;if(d){te(this.deps,"frozen:load:preview","frozen:load:preview:error",e,d.error,{code:d.code,retryable:d.retryable});return}try{let a=new fe,u=r.sasDir(a),{dataset:l,manifest:c}=await r.read(a),f=this.buildTargetOrgAccess(),p=await Oe(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),g=$t(p,"frozen:load:preview"),m=await new $r({orgAccess:f,writer:yf,guard:this.deps.infraServices?.productionGuard??new ta,mockDetector:n.mockDetection?new Cr(f,n.mockDetection):{areCalloutsMocked:async()=>!0},recordTypeResolver:new Kr(f),mappingStore:r.mappingStore(a),config:this.toLoadConfig(n),sasGuard:a,serverTime:()=>g.serverTime(),readValidationRules:async b=>{let{toolingQueriesOver:O,toolingValidationRules:F}=await import("./chunk-HV63UGL5.mjs"),{toolingRetrievesOver:v}=await import("./chunk-FH5UR35W.mjs"),A=p.tooling;return F(async N=>(await Ai({query:async M=>A.query(M),queryMore:async M=>A.queryMore(M)},N)).records,O(p),v(p))(b)}}).planLoad({orgId:t.targetOrgId,orgName:this.orgNameOf(t.targetOrgId),orgTier:this.targetTier(t.targetOrgId),...s?.stagingReplay?{stagingReplay:!0}:{},dataset:l,manifest:c,sasDir:u,reload:t.reload,pilot:t.pilot?{}:void 0,...t.writeEncrypted?{writeEncrypted:!0}:{},...s?{linkByKeys:!0}:{}}).catch(async b=>{throw b instanceof et&&b.gaps!==void 0&&(b.refusedBeside=await this.refusedBesideOf({conn:p,orgId:t.targetOrgId,dataset:l,store:r.mappingStore(a),config:n,parsed:t,...s?{replay:s}:{}}).catch(()=>[])),b}),w=t.checkpointFirst!==void 0?await this.previewCheckpoint({msg:e,orgId:t.targetOrgId,written:l.objects.map(b=>b.objectApiName),request:t.checkpointFirst,muteAutomation:t.muteAutomation===!0,conn:p,replay:s!==void 0}):void 0,R=r.mappingStore(a),P=Vc(p),{emails:j,automation:T,apiRequests:$,automationBytes:q}=await this.previewWhatRuns({conn:p,limits:P,orgId:t.targetOrgId,dataset:l,store:R,config:n,parsed:t,...w?{checkpoint:w}:{},...s?.converted?{replayReads:s.converted.target.requests}:{}}),C=await this.previewStorageOf({conn:P,org:p,dataset:l,store:R,config:n,parsed:t,...q!==void 0?{automationBytes:q}:{},targetOrgId:t.targetOrgId,replay:s!==void 0}),I=s?this.replayInfoOf(s,m.perObject.reduce((b,O)=>b+O.reusedByKeys,0),C):void 0;this.deps.broker.postToWebview(Se(this.deps,e,"frozen:load:preview:response",{plan:{...m,...w?{checkpoint:w}:{},...j?{emails:j}:{},...T?{automation:T}:{},...$?{apiRequests:$}:{},...C&&!s?{storage:C}:{}},...Jc(I)}))}catch(a){te(this.deps,"frozen:load:preview","frozen:load:preview:error",e,a,{code:this.errorCodeFor(a,"PREVIEW_ERROR"),retryable:a instanceof lt,extraPayload:this.errorDetailOf(a)})}}async refusedBesideOf(e){let{replay:t,...r}=e,n=Vc(e.conn),{emails:s,automation:i,apiRequests:d,automationBytes:a}=await this.previewWhatRuns({...r,limits:n,...t?.converted?{replayReads:t.converted.target.requests}:{}}),u=await this.previewStorageOf({conn:n,org:e.conn,dataset:e.dataset,store:e.store,config:e.config,parsed:e.parsed,...a!==void 0?{automationBytes:a}:{},targetOrgId:e.orgId,replay:t!==void 0}),{orgId:l}=e,c=[];return i?.refused&&c.push({...i.refused,orgId:l,automation:i}),s?.refused&&c.push({...s.refused,orgId:l,emails:s}),u?.refusal&&c.push({...u.refusal,orgId:l,storage:Rf(u)}),d?.refused&&c.push({...d.refused,orgId:l,apiRequests:d}),c}async previewStorageOf(e){let t=e.parsed.pilot===!0,r=Ps(e.dataset,e.config,e.parsed.pilot),n=await this.loadSentOf(e.org,r);return this.loadStorageOf({conn:e.conn,dataset:r,...n?{sent:n}:{},...e.parsed.reload===!0&&!t?{purged:await this.purgedOf(e.store,e.config).catch(()=>[])}:{},...e.automationBytes!==void 0?{automationBytes:e.automationBytes}:{},targetOrgId:e.targetOrgId,replay:e.replay,...t?{pilot:!0}:{}})}async previewWhatRuns(e){let{parsed:t}=e;try{let r=t.reload===!0&&!t.pilot?await this.purgeStepsOf(e.store,e.config):void 0,n=r?Rr(r):void 0,s=(f,p)=>uo(f,p)||n?.(f,p)===!0,i=await this.targetAutomation.read(e.orgId,[...new Set([...e.dataset.objects.map(f=>f.objectApiName),...r?.delete??[]])]).catch(f=>({unread:Q(f)})),d=t.muteAutomation===!0?await Sr(async()=>Or(e.conn),i,{...this.muteLeases,writes:s}).catch(()=>{}):void 0,{info:a}=as({read:i,...d?.plan?{plan:d.plan}:{},written:e.dataset.objects.map(f=>f.objectApiName),accepted:t.acceptAutomation===!0,target:this.orgNameOf(e.orgId),mayMute:t.muteAutomation!==!0&&this.muteOffered}),u=Ps(e.dataset,e.config,t.pilot),l=await this.loadEmailsFor({conn:e.conn,orgId:e.orgId,orgTier:this.targetTier(e.orgId),read:i,...d?.plan?{plan:d.plan}:{},writes:s,dataset:u,accepted:t.acceptEmails===!0,mayMute:t.muteAutomation!==!0&&this.muteOffered}).catch(f=>{Mt.warn(`Frozen preview: the emails could not be judged (${Q(f)})`)}),c=await this.loadApiCheck({conn:e.limits,dataset:u,...r?{purged:await this.purgedOf(e.store,e.config)}:{},read:i,...e.checkpoint?{checkpoint:e.checkpoint}:{},...d?.plan?{plan:d.plan}:{},...l?{emails:l}:{},orgId:e.orgId,operation:"frozen:load:preview",...e.replayReads!==void 0?{replayReads:e.replayReads}:{}}).catch(f=>{Mt.warn(`Frozen preview: the API requests could not be judged (${Q(f)})`)});return{...l&&Xc(l.info)?{emails:l.info}:{},...a?{automation:a}:{},...c?{apiRequests:c}:{},automationBytes:Yc(i,d?.plan,u,s)}}catch(r){return Mt.warn(`Frozen preview: what the target runs could not be judged (${Q(r)})`),{}}}async handleVerify(e){let t=nt(Ci,e,"frozen:verify:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:verify:error","checkpoint");if(!r)return;let{config:n,replay:s}=r,i=s?void 0:this.lastRunOf(t.targetOrgId);if(!s&&!i){te(this.deps,"frozen:verify","frozen:verify:error",e,new Error("No load into this org is recorded \u2014 run a load (frozen:load) into it before verifying."),{code:"NO_LOAD"});return}let d=nl(a=>{let u=Se(this.deps,e,"frozen:load:progress",{...a});this.deps.broker.postToWebview(u)},100);try{let a=new fe,u=i?.contractPath??s?.contractPath??"";if(s&&!await it(u)){te(this.deps,"frozen:verify","frozen:verify:error",e,new Error(`No replay of this checkpoint into ${s.target.name} wrote its counting contract on this machine: replay it there, then verify.`),{code:"NO_LOAD"});return}if(i){let g=a.assertOutsideRepo(this.resolveSasDir(n)),h=je.dirname(i.contractPath)!==je.dirname(zn(a,g,t.targetOrgId)),m=await it(i.contractPath);if(h||!m){let w=je.dirname(i.contractPath),R;h?m?R=`The sas directory changed since the last load: its counting contract is in ${w}, and the mapping read is the one in ${g}. Set sasDir back to the sas the load wrote to, or load the dataset again, then verify.`:R=`The sas directory changed since the last load: the load wrote to ${w}, which no longer holds its counting contract, and the mapping read is the one in ${g}. Move the sas back to ${w} and set sasDir to it, or load the dataset again, then verify.`:R=`The sas changed since the last load: ${g} no longer holds the counting contract the last load wrote there. Load the dataset again, then verify.`,te(this.deps,"frozen:verify","frozen:verify:error",e,new Error(R),{code:"SAS_CHANGED",extraPayload:{sasDir:g,loadSas:w,sasMoved:h,contractThere:m}});return}}let l=r.mappingStore(a);if(await l.isStale()){te(this.deps,"frozen:verify","frozen:verify:error",e,new Error("The target org was refreshed after the last load: the records that load wrote are gone. Load the dataset again, then verify."),{code:"TARGET_REFRESHED"});return}let c=await l.recorded(),f=c?.removal;if(c&&f){let g=ot(c).reduce((h,m)=>h+m.ids.length,0);te(this.deps,"frozen:verify","frozen:verify:error",e,new Error(g>0?`The removal of ${f.removedAt} took part of the records the last load created and left ${g} in the org: a verification would read the ones it took as missing. Remove what is left, or reload the dataset, which purges or finds it again; then verify.`:`The records the last load created were removed on ${f.removedAt}. Load the dataset again, then verify.`),{code:"LOAD_REMOVED",extraPayload:{left:g}});return}if(!c){te(this.deps,"frozen:verify","frozen:verify:error",e,new Error("The sas holds no mapping of the last load: nothing names the records to verify. Load the dataset again, then verify."),{code:"NO_LOAD"});return}if(!md(Mn(a,u),c)){te(this.deps,"frozen:verify","frozen:verify:error",e,new Error("The last load stopped part way \u2014 it was cancelled, or failed once it had written \u2014 and wrote no counting contract: the one in the sas counts an earlier load, and would judge this one by it. Reload the dataset, which purges or finds again what the stopped load wrote, or remove that load before loading the dataset again; then verify. Loaded again without a reload, the dataset would go in beside what the stopped load wrote."),{code:"LOAD_STOPPED"});return}let{dataset:p}=i?await this.readFrozenDataset(i.datasetDir,a):await r.read(a);await this.runVerification(e,{orgId:t.targetOrgId,contractPath:u,...i?{manifestPath:i.manifestPath}:{},dataset:p,mappingStore:l,config:n,onProgress:d})}catch(a){te(this.deps,"frozen:verify","frozen:verify:error",e,a,{code:this.errorCodeFor(a,"VERIFY_ERROR"),retryable:a instanceof lt})}}async runVerification(e,t){this.postVerification(e,await this.verifyLoad(t))}async verifyLoad(e){try{let t=new no({orgAccess:this.buildTargetOrgAccess(),sasGuard:new fe}),r=await e.mappingStore.load(),n=await t.verify({orgId:e.orgId,contractPath:e.contractPath,dataset:e.dataset,mapping:r,mandatoryLookups:e.config.mandatoryLookups,presenceKeys:e.config.presenceKeys,...e.manifestPath!==void 0?{manifestPath:e.manifestPath}:{},author:"sandforge",onProgress:e.onProgress});return this.recordLastVerify(e.orgId,{status:n.status,measuredAt:n.measuredAt}),{verdict:n}}catch(t){return{error:t}}}postVerification(e,t){if("verdict"in t){let{verdict:n}=t,s=Se(this.deps,e,"frozen:verify:result",{verdict:n});this.deps.broker.postToWebview(s);return}let r=t.error;te(this.deps,"frozen:verify","frozen:verify:error",e,r,{code:this.errorCodeFor(r,"VERIFY_ERROR"),retryable:r instanceof lt})}async handleRemove(e){let t=nt(zi,e,"frozen:remove:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:error","mapping");if(!r)return;let n=(p,g)=>this.refuseRemove(e,p,g),s,i,d;try{s=r.mappingStore(new fe),i=await s.recordedLoads(),d=ar(i)}catch(p){te(this.deps,"frozen:remove","frozen:remove:error",e,p,{code:this.errorCodeFor(p,"REMOVE_ERROR")});return}let a=Cs(d,t),u=t.sweep===!0&&a?.code==="ALREADY_REMOVED";if(a&&!u||!d){a&&n(a.message,a.code);return}let l=ot(d),c=s.filePath;if(this.removing.has(c)){n("The records of this load are being removed already.","DUPLICATE");return}this.removing.add(c);let f=this.registry?.holdUntilStart(e.id);try{await this.removeLoad(e,{store:s,load:d,plan:l,includeChanged:t.includeChanged===!0,sweep:t.sweep===!0,sweepLate:t.sweep===!0&&t.sweepLate===!0,sweepUntied:t.sweep===!0&&t.sweepUntied===!0,alongside:t.sweep===!0?Wo(i,d):[],muteAutomation:t.muteAutomation===!0,pending:f,audit:fo(r)})}finally{this.removing.delete(c),f?.release()}}async handleRemoveAutomation(e){let t=nt(Di,e,"frozen:remove:automation:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:automation:error","mapping");if(!r)return;let{config:n}=r;try{let s=r.mappingStore(new fe),i,d;if(t.reload===!0)i=await this.purgeStepsOf(s,n,t.sweptObjects??[]),(t.sweptObjects??[]).length>0&&(d=await this.purgeStepsOf(s,n));else{let l=ar(await s.recordedLoads()),c=Cs(l,t),f=t.sweptObjects!==void 0&&c?.code==="ALREADY_REMOVED";if(c&&!f||!l){c&&te(this.deps,"frozen:remove:automation","frozen:remove:automation:error",e,new Error(c.message),{code:c.code});return}i=Xr(ot(l),t.sweptObjects??[],l)}let a=this.targetAutomation,u=await new St(Ls).withTimeout("frozen:remove:automation",()=>a.read(t.targetOrgId,i.delete??[]));this.deps.broker.postToWebview(Se(this.deps,e,"frozen:remove:automation:response",{loadedAt:t.loadedAt,automation:u,steps:i,...d?{purge:d}:{}}))}catch(s){te(this.deps,"frozen:remove:automation","frozen:remove:automation:error",e,s,{code:s instanceof lt?"TIMEOUT":this.errorCodeFor(s,"AUTOMATION_ERROR"),retryable:!0})}}async purgeStepsOf(e,t,r=[]){if(await e.isStale())return Xr([],[]);let n=t.undeletableObjects??{},s=(await e.recordedLoads()).flatMap(i=>ot(i)).filter(({objectApiName:i})=>!Object.hasOwn(n,i));return Xr(s,r)}async handleRemovePreview(e){let t=nt(xi,e,"frozen:remove:preview:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:preview:error","mapping");if(!r)return;let n=(s,i,d=!1)=>te(this.deps,"frozen:remove:preview","frozen:remove:preview:error",e,s,{code:i,retryable:d});try{let s=r.mappingStore(new fe),i=ar(await s.recordedLoads()),d=Cs(i,t);if(d||!i){d&&n(new Error(d.message),d.code);return}let a=ot(i).reduce((c,f)=>c+f.ids.length,0),u=this.removalGuardRefusals(i.orgId,a),l;if(await s.isStale())u.push({code:"TARGET_REFRESHED",message:"The target org was refreshed after the load: the records it created went with the refresh, and a removal removes nothing."}),l={...this.unreadPreviewOf(i,t.includeChanged===!0),planned:a};else{let c=await Oe(i.orgId,this.deps.orgRegistry,this.deps.orgManager);l=await this.previewRemovalOf(c,i,t.includeChanged===!0)}this.deps.broker.postToWebview(Se(this.deps,e,"frozen:remove:preview:response",{preview:{...l,refusals:u.map(({message:c})=>c),refusalCodes:u.map(({code:c})=>c)}}))}catch(s){n(s,this.errorCodeFor(s,"REMOVE_PREVIEW_ERROR"),!0)}}removalGuardRefusals(e,t){let r=this.deps.infraServices?.productionGuard;if(!r)return[{...Ot}];let n=this.targetTier(e),s=r.check({orgId:e,orgTier:n,operation:"delete",objectName:"the records a Frozen load created",recordCount:t,module:"frozen"});if(!s.allowed)return[{code:"GUARD_BLOCKED",message:`Operation blocked by Production Guard: ${s.blockedReason??s.impactSummary}`}];let i=r.declinedWithoutAsking(s,n);return i===void 0?[]:[{code:"GUARD_DECLINED",message:`Production Guard asks before this delete, and its question is answered no: ${i} (${s.impactSummary}). Nothing would be deleted.`}]}async previewRemovalOf(e,t,r){let n=ot(t),s=await vn($t(e,"frozen:remove:preview"),n,{...zs(t),includeChanged:r,previewOnly:!0});if(!s.preview)throw new Error("The removal preview stopped before it was through.");return{...this.unreadPreviewOf(t,r),planned:n.reduce((i,d)=>i+d.ids.length,0),objects:s.preview.objects.map(i=>({objectApiName:i.objectApiName,planned:i.planned,toDelete:i.toDelete,alreadyGone:i.alreadyGone,changedSince:i.changedSince,keptChanged:i.keptChanged,changedBy:i.changedBy,undeletable:i.undeletable,notVisible:i.notVisible,unread:i.unread,reasons:i.reasons})),userNames:s.preview.userNames}}unreadPreviewOf(e,t){let r=Dn(e);return{loadedAt:e.endedAt,includeChanged:t,planned:0,objects:[],userNames:{},...e.removal?{leftBy:e.removal.removedAt}:{},...r.length>0?{keptByThePlatform:r}:{}}}async replaceRefusal(e,t,r=[]){if(e.reload!==!0||e.pilot===!0)return;let n,s={};try{let i=t.mappingStore(new fe),d=await i.recordedLoads();if(d.length===0||await i.isStale())return;if(d.some(a=>!a.created))n="A load recorded before loads kept what they created is in this sas: which of its records it created cannot be told, and a reload leaves in place those it may have linked, so it would not replace that load whole, and no removal takes it. Refresh the sandbox to start again from its copy, or find the records the loading user created that day and delete them yourself, then load without reloading. Nothing was written.";else{let a=await Oe(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),u=d.filter(p=>ot(p).length>0),l=new Set([...u.flatMap(p=>ot(p).flatMap(g=>g.ids.map(h=>h.slice(0,15)))),...r.map(p=>p.slice(0,15))]),c=[];for(let p of u){let g=await vn($t(a,"frozen:load:replace"),ot(p),{...zs(p),includeChanged:!1,previewOnly:!0,previewHeld:!0,goesWithParent:h=>typeof h.Id=="string"&&l.has(h.Id.slice(0,15))});if(!g.preview)throw new Error("The removal preview stopped before it was through.");c.push(g.preview);for(let{objectApiName:h,cameAlong:m}of g.preview.objects){if(!m)continue;let w=s[h];s[h]={count:(w?.count??0)+m.count,objects:[...new Set([...w?.objects??[],...m.objects])]}}}let f=Cf(c,e.sweep===!0);f.length>0&&(n=`A removal of the loads this reload replaces would leave ${f.reduce((g,h)=>g+h.left,0)} of their records in the org \u2014 ${f.map(g=>`${g.objectApiName} (${g.left}: ${g.why.join(", ")})`).join("; ")}: loaded again, the dataset would stand beside them, and the reload would delete what was changed since, and what stays under them along with them. Nothing was written. Take the load back first with a removal \u2014 records changed since, and what was added under them since, go too when it is told to include them \u2014 then load the dataset again.`)}}catch(i){return{error:i,code:this.errorCodeFor(i,"LOAD_ERROR"),retryable:!0}}return n!==void 0?{error:new Error(n),code:lo,retryable:!1}:Object.keys(s).length>0?{cameAlong:s}:void 0}refuseRemove(e,t,r){te(this.deps,"frozen:remove","frozen:remove:error",e,new Error(t),{code:r})}async removeLoad(e,t){let{store:r,load:n,plan:s,includeChanged:i,sweep:d,pending:a}=t,u=t.audit??{module:"frozen"},l=n.orgId,c=s.reduce((O,F)=>O+F.ids.length,0),f=(O,F)=>this.refuseRemove(e,O,F),p=this.deps.infraServices?.productionGuard;if(!p){Qe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",code:Ot.code}),f(Ot.message,Ot.code);return}let{check:g,decision:h}=c>0?await An(p,{orgId:l,orgTier:this.targetTier(l),operation:"delete",objectName:s.map(O=>O.objectApiName).join(", "),recordCount:c,module:"frozen"}):{check:void 0,decision:"allowed"};if(g&&(h==="refused"||h==="declined")){Qe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",guard:h}),h==="refused"?f(`Operation blocked by Production Guard: ${g.blockedReason??g.impactSummary}`,"GUARD_BLOCKED"):te(this.deps,"frozen:remove","frozen:remove:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}let m=()=>{if(!a?.signal.aborted)return!1;Qe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",guard:h,code:bi});let O={status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};return this.deps.broker.postToWebview(Se(this.deps,e,"frozen:remove:response",{result:O,operationId:e.id})),!0};if(m())return;let w;try{w=await r.isStale()}catch(O){Qe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"failure",guard:h}),te(this.deps,"frozen:remove","frozen:remove:error",e,O,{code:this.errorCodeFor(O,"REMOVE_ERROR"),retryable:!0});return}if(w){Qe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",guard:h,code:"TARGET_REFRESHED"}),f("The target org was refreshed after the load: the records it created went with the refresh, and nothing is removed.","TARGET_REFRESHED");return}if(m())return;let R=e.id,P=c>0?`Removing ${c} record(s) a Frozen load created`:"Sweeping what the target's automation made for a Frozen load",j=new AbortController,T=()=>{},$=new Promise((O,F)=>{T=v=>v===void 0?O():F(v)});$.catch(()=>{}),vr(this.deps,R,"frozen",P),this.registry?.register(R,"frozen",P,$,j),this.liveTracker?.register(R,"frozen",P,c);let q,C,I=[],b;try{let O=await Oe(l,this.deps.orgRegistry,this.deps.orgManager),F=new Set([n,...t.alongside].map(S=>S.endedAt));C=d?await this.sweepOfRemoval({conn:O,load:n,store:r,includeChanged:i,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,audit:u,signal:j.signal,guard:p,operationId:R,muted:()=>c===0?b:void 0,sweptWith:F}):void 0;for(let[S,J]of(C?t.alongside:[]).entries())I.push({loadedAt:J.endedAt,sweep:await this.sweepOfRemoval({conn:O,load:J,store:r,includeChanged:i,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,audit:u,signal:j.signal,guard:p,operationId:`${R}-${S+2}`,muted:()=>{},sweptWith:F})});let v=C,A=[...C?[C]:[],...I.map(({sweep:S})=>S)],N=async S=>{let J=!1;for(let ne of A)await S(ne)&&(J=!0);return J};for(let S of A)await S.ask();let M,B=this.removalAsker,D=Xr(s,A.flatMap(S=>S.takes),n);if((t.muteAutomation||B)&&!j.signal.aborted&&(D.delete??[]).length>0){let S=this.targetAutomation,J=await new St(Ls).withTimeout("frozen:remove automation",()=>S.read(l,D.delete??[])).catch(Z=>({unread:Q(Z)}));t.muteAutomation&&(M=await Sr(async()=>Or(O),J,{...this.muteLeases,writes:Rr(D)}));let ne=await B?.({read:J,steps:D,mute:M});if(ne)throw new gr(ne)}b=M?.muted;let G,V=async()=>{let S=M?.prepared;!S||j.signal.aborted||(G=await S.acquire(R),b=G.outcome)},H=await(c===0?(async()=>(await V(),await N(S=>S.first()),await N(S=>S.afterRemoval()),Ui))():vn($t(O,"frozen:remove"),s,{...zs(n),...v?{sweep:S=>N(J=>J.first(S)),afterRemoval:S=>N(J=>J.afterRemoval(S)),automationMade:v.automationMade}:{},onUndeletable:ki(this.deps,l,"frozen:remove"),beforeFirstWrite:V,includeChanged:i,signal:j.signal,onProgress:(S,J,ne)=>{let Z=Math.min(100,Math.round(S/Math.max(J,1)*100));Oi(this.deps,R,Z,S,J,ne),j.signal.aborted||this.registry?.updateProgress(R,Z),this.liveTracker?.updateProgress(R,Z,S,J,ne)}})).finally(async()=>{G&&(b=await G.release())}),K=await C?.settle(),re=await this.settleReloadSweeps(I),_=n.removal?.removedAt,U=Dn(n),de=Vi(H.objects,H.cancelled),X={status:re.reduce((S,J)=>To(S,J.result),To(de,K)),includeChanged:i,objects:H.objects,finishedAt:new Date().toISOString(),..._?{leftBy:_}:{},...K?{sweep:K}:{},...re.length>0?{otherLoadSweeps:re}:{},...U.length>0?{keptByThePlatform:U}:{},...b?{mutedAutomation:b}:{}};c>0&&Qe(this.deps,{action:"cleanup_delete",module:u.module,operationId:R,orgId:l,outcome:Hi({status:de}),guard:h,objects:Yi(X.objects),..._?{leftBy:_}:{},...b?{muted:gn(b)}:{}});let pe=Ji(X,c,n.removal);(H.gone.length>0||Object.keys(H.stamps).length>0||H.span||pe)&&(await r.recordRemoval(n.endedAt,{gone:H.gone,stamps:H.stamps,...H.span?{span:H.span}:{},...pe?{mark:pe}:{}})||this.deps.log("[WARN] frozen:remove: a load wrote its own mapping during the removal; the removal is not recorded in it"));let Be=[...K&&Ts(K)?[n.endedAt]:[],...re.filter(S=>Ts(S.result)).map(S=>S.loadedAt)];await r.letSweptGo(Be).catch(()=>!1);let Ne=Se(this.deps,e,"frozen:remove:response",{result:X,operationId:R});this.deps.broker.postToWebview(Ne);let k=[K,...re.map(S=>S.result)].find(S=>S!==void 0&&S.status!=="success"),E=X.status==="failure"?"No record this load created could be removed.":c===0&&k?k.refusal??"The sweep left records in the org.":void 0;X.status==="cancelled"||K?.status==="cancelled"||re.some(S=>S.result.status==="cancelled")?(Rt(this.deps,R,{aborted:!0}),this.liveTracker?.cancel(R)):(Rt(this.deps,R,{status:E&&c===0?"failure":X.status}),E?(q=new Error(E),this.liveTracker?.fail(R,E)):X.status==="partial"?this.liveTracker?.partial(R):this.liveTracker?.complete(R))}catch(O){q=O,await C?.settle().catch(()=>{});for(let{sweep:v}of I)await v.settle().catch(()=>{});let F=Tn(O)||O instanceof gr?O:void 0;Qe(this.deps,{action:"cleanup_delete",module:u.module,operationId:R,orgId:l,outcome:F?"stopped":"failure",guard:h,...F?{code:F.code}:{}}),te(this.deps,"frozen:remove","frozen:remove:error",e,O,{code:F?.code??"REMOVE_ERROR",retryable:!0}),Rt(this.deps,R,{status:"failure"}),this.liveTracker?.fail(R,Q(O))}finally{T(q)}}async reloadSweepsOf(e){if(await e.store.isStale())return[];let t=(await e.store.recordedLoads()).filter(d=>d.created),r=new Set(t.map(d=>d.endedAt)),n={includeChanged:e.includeChanged,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},s=d=>vf(d,n),i=[];for(let[d,a]of t.entries())i.push({loadedAt:a.endedAt,judged:s,sweep:await this.sweepOfRemoval({conn:e.conn,load:a,store:e.store,includeChanged:e.includeChanged,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied,signal:e.signal,guard:e.guard,operationId:d===0?e.operationId:`${e.operationId}-${d+1}`,muted:()=>{},sweptWith:r,judged:s,...e.audit?{audit:e.audit}:{}})});return i}async settleReloadSweeps(e){let t=[];for(let{loadedAt:r,sweep:n,judged:s}of e){let i=await n.settle();t.push({loadedAt:r,result:s?s(i):i})}return t}sweepOfRemoval(e){let{conn:t,load:r}=e;return id({input:()=>this.sweepInputOfLoad($t(t,"frozen:remove sweep"),r,e.signal,e.store,e.sweptWith,e.audit?.sasMark),org:Cn(t,"frozen:remove sweep",e.signal),options:{includeChanged:e.includeChanged,removalSpans:r.removalSpans,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},guard:e.guard,guardOf:{orgId:r.orgId,orgTier:this.targetTier(r.orgId),operation:"delete",module:"frozen"},onGuardDecision:(n,s)=>{let i=e.judged?e.judged(n):n,d=nd(i,"");delete d.forgeId;let a=e.muted();Qe(this.deps,{action:"cleanup_delete",module:e.audit?.module??"frozen",operationId:`${e.operationId}-sweep`,orgId:r.orgId,outcome:i.status==="refused"?"stopped":i.status,...s?{guard:s}:{},...i.status==="refused"?{code:ad(s)}:{},objects:rd(i),details:{...d,loadedAt:r.endedAt},...a?{muted:gn(a)}:{}})},keepMade:async(n,s,i)=>{await e.store.recordMade(r.endedAt,n,s,i)}})}async sweepInputOfLoad(e,t,r,n,s=new Set,i=this.sasMarkInUse()){let d=qo(t),a=this.targetAutomation,u;try{u=await new St(Ls).withTimeout("frozen:remove sweep automation",()=>a.read(t.orgId,d.map(g=>g.objectApiName)))}catch(g){u={error:Q(g)}}let l=t.writtenBetween??await od(e,d,r),{ties:c,sweptAlong:f}=await this.tiesOfLoad(t,l,n,s,i),p=new Set([...t.mapping.values(),...f].map(g=>g.slice(0,15)));return sd({writtenBetween:l,created:d,remap:p,automation:td(u),...t.runUserId?{runUserId:t.runUserId}:{},ties:c,...r?{signal:r}:{}},e)}setOtherModuleRuns(e){this.otherModuleRuns=e}auditedLoadsInto(e){try{return lc(new wi(this.deps.configStore).list({orgId:e,limit:Us}).entries)}catch{return[]}}sasMarkInUse(){let e=this.loadConfig();return e?Yn(this.resolveSasDir(e)):void 0}async tiesOfLoad(e,t,r,n,s){let i=[],d=[],a=await r?.recordedLoads().catch(()=>[])??[];for(let l of a){if(l.endedAt===e.endedAt||l.orgId!==e.orgId)continue;let c=qo(l).flatMap(g=>g.ids);if(n.has(l.endedAt)){d.push(...c);continue}let f=Date.parse(l.writtenBetween?.first??l.startedAt??l.endedAt),p=Date.parse(l.writtenBetween?.last??l.endedAt);i.push({ids:c,from:f,to:Number.isFinite(p)?p:f})}i.push(...await this.otherModuleRuns(e.orgId,t).catch(()=>[])),i.push(...dc(this.auditedLoadsInto(e.orgId),{sasMark:s,own:a.filter(l=>l.orgId===e.orgId)}));let u=cd(e.removalSpans);return{ties:{otherRuns:dd(t,i),...u?{removalBegan:u}:{},...e.madeEarlier?{madeEarlier:e.madeEarlier}:{},...e.lateEarlier?{lateEarlier:e.lateEarlier}:{}},sweptAlong:d}}async handleRemoveSweep(e){let t=nt(Mi,e,"frozen:remove:sweep:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:sweep:error","mapping");if(!r)return;let n=(s,i)=>te(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,new Error(s),{code:i});try{let s=r.mappingStore(new fe);if(t.reload===!0){await this.listReloadSweeps(e,s,t,fo(r).sasMark);return}let i=await s.recordedLoads(),d=ar(i);if(!d){n("No load into this org was recorded in this sas: there is nothing to sweep.","NO_LOAD");return}if(d.orgId!==t.targetOrgId||d.endedAt!==t.loadedAt){n("Another load was recorded since this one was shown: check what a removal takes now.","LOAD_CHANGED");return}let a=Wo(i,d),u=new Set([d,...a].map(f=>f.endedAt)),{listing:l,otherLoads:c}=await new St(rl).withTimeout("frozen:remove:sweep",async()=>{let f=await Oe(d.orgId,this.deps.orgRegistry,this.deps.orgManager),p=Cn(f,"frozen:remove:sweep"),g=async m=>_o(p,await this.sweepInputOfLoad(p,m,void 0,s,u,fo(r).sasMark),m.removalSpans),h=[];for(let m of a)h.push({loadedAt:m.endedAt,listing:await g(m)});return{listing:await g(d),otherLoads:h}});this.deps.broker.postToWebview(Se(this.deps,e,"frozen:remove:sweep:response",{loadedAt:d.endedAt,listing:l,...c.length>0?{otherLoads:c}:{}}))}catch(s){te(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,s,{code:s instanceof lt?"TIMEOUT":this.errorCodeFor(s,"SWEEP_ERROR"),retryable:!0})}}async listReloadSweeps(e,t,r,n){let s=await t.isStale()?void 0:await t.recordedLoads(),i=(s??[]).filter(a=>a.created);if(s&&!s.some(a=>a.endedAt===r.loadedAt)){te(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,new Error("Another load was recorded since this one was shown: check what a reload replaces now."),{code:"LOAD_CHANGED"});return}let d=await new St(rl).withTimeout("frozen:remove:sweep",async()=>{if(i.length===0)return[];let a=await Oe(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),u=Cn(a,"frozen:remove:sweep"),l=new Set(i.map(f=>f.endedAt)),c=[];for(let f of i)c.push({loadedAt:f.endedAt,listing:await _o(u,await this.sweepInputOfLoad(u,f,void 0,t,l,n),f.removalSpans)});return c});this.deps.broker.postToWebview(Se(this.deps,e,"frozen:remove:sweep:response",{loadedAt:r.loadedAt,reload:!0,loads:d}))}sayTheSaltWasMade(e){vi(this.deps,"info","Frozen dataset salt",`This first extraction made the salt every pseudonym is drawn with (fingerprint ${e}) and keeps it in VS Code's secret storage: every later extraction pseudonymizes the same records the same way. A teammate who extracts this dataset needs the same salt: copy it with "SandForge: Copy Frozen Dataset Salt" and give it to them as you would a password; they set it with "SandForge: Use a Frozen Dataset Salt". Whoever holds it can tell which source value a pseudonym was drawn from.`,{autoDismissMs:null,code:"FROZEN_SALT_CREATED"})}async handleStatus(e){let t=this.loadConfig(),r=this.resolveSasDir(t),n=this.resolveDatasetDir(t),s={present:!1};try{let f=await this.saltKeeper.read();f&&(s={present:!0,fingerprint:new Ln(f.salt).saltFingerprint,source:f.source})}catch{s={present:!1}}let i=null;try{let f=new fe;if(await it(je.join(r,Wr))){let p=await fs(r,f);i={selectedAt:p.selectedAt,rootCount:p.roots.length,total:p.volumetry.total,budgetMax:p.volumetry.budgetMax}}}catch{i=null}let d=null;try{let p=new fe().assertOutsideRepo(je.join(n,"manifest.json"));await it(p)&&(d=ol(Fr(JSON.parse(await Ae.readFile(p,"utf8")))))}catch{d=null}let a=this.deps.configStore.get(pr),u=[];try{let f=new fe,p=f.assertOutsideRepo(r);for(let g of await bd(p,f))try{let h=ar(await new xn(p,{guard:f,orgId:g}).recordedLoads());h&&u.push(wd(h))}catch{}}catch{u.length=0}let l={configured:t!==null,sasDir:r,datasetDir:n,salt:s,mockDetectionConfigured:t?.mockDetection!==void 0,selection:i,manifest:d,lastLoad:a?{status:a.status,orgId:a.targetOrgId,at:a.at}:null,lastLoads:this.lastLoadInfos(),lastVerifies:this.lastVerifyInfos(),...u.length>0?{loadRecords:u}:{},rules:await this.rulesFileInfo(t)},c=Se(this.deps,e,"frozen:status:response",{status:l});this.deps.broker.postToWebview(c)}};export{Kf as a,Rl as b,kl as c,Tp as d,ic as e,Yn as f,ac as g,dc as h,Lp as i,Np as j,$p as k,Gp as l,dl as m};