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,7 +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,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-ZLQHBI6V.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-AIUAEBHR.mjs";import"./chunk-O3ZQSWDN.mjs";import"./chunk-DNE7JI3A.mjs";import"./chunk-CI2O7WBH.mjs";import"./chunk-5T3LFDJ5.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-AX3YF7SC.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-Q7TLC3I2.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-JBOGAUGH.mjs";import"./chunk-4N425UJC.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-FG4Y4ZVL.mjs";import"./chunk-Z354SAEF.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-THYQOG24.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-CRPLDXJU.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{p as actDeliverability,o as actEmailsGate,n as actSendersOf,q as afterLeaseEmailsRefusal,l as checkpointEmails,j as checkpointEmailsUncounted,c as draftedByDiff,d as draftedByPlan,a as emailsOfLimit,m as emailsRefusal,k as emailsUncountedWords,r as pageEmailsRefusal,e as statusBackByDiff,f as statusBackByPlan,b as updatedByDiff,g as writtenByDiff,h as writtenByPlan,i as writtenByUndo};
@@ -1,7 +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
- function r(...a){return new RegExp(`(?<![a-z\xE0-\xFF])(?:${a.join("|")})(?![a-z\xE0-\xFF])`)}var p=[{regex:r("sexual orientation","sexual preference","orientation sexuelle"),classification:"Confidential",confidence:.85,label:"sexual_orientation",words:!0},{regex:r("gender identity","gender","sexe?","pronouns?","pronoms?","identit[e\xE9] de genre"),classification:"PII",confidence:.85,label:"gender",words:!0},{regex:r("salutations?","civility","honorifics?","civilit[e\xE9]s?"),classification:"PII",confidence:.8,label:"salutation",words:!0},{regex:r("marital status","marital","situation familiale","situation matrimoniale"),classification:"PII",confidence:.85,label:"marital_status",words:!0},{regex:r("nationality","nationalities","citizenship","nationalit[e\xE9]s?","citoyennet[e\xE9]"),classification:"PII",confidence:.85,label:"nationality",words:!0},{regex:r("ethnicity","ethnic","race","racial","ethnie","ethnique"),classification:"Confidential",confidence:.85,label:"ethnic_origin",words:!0},{regex:r("religion","religions","religious","religieux","religieuse"),classification:"Confidential",confidence:.85,label:"religion",words:!0},{regex:r("political (?:opinion|affiliation|party|view)s?","opinions? politiques?","parti politique"),classification:"Confidential",confidence:.85,label:"political_opinion",words:!0},{regex:r("trade union","labou?r union","union member(?:ship)?","syndicat","syndicale?"),classification:"Confidential",confidence:.85,label:"union_membership",words:!0},{regex:r("disability","disabilities","handicaps?"),classification:"PHI",confidence:.85,label:"disability",words:!0}],d=/(?<![a-z])(?:(?:first|last|middle|maiden)[\s_]?name(?:local)?|surname|suppliedname)(?![a-z])/,g=new Set(["string","textarea","encryptedstring"]);function C(a){return d.test(a.toLowerCase().replace(/__c$/i,""))}var u=new Set(["string","textarea","encryptedstring"]),I=new Set(["email","emails","mail","mails","courriel","courriels"]),m=new Set(["ToAddress","CcAddress","BccAddress"]),P=new Set(["phone","phones","telephone","tel","mobile","cell","fax","sms","gsm","whatsapp","portable"]);function f(a){return a.replace(/__[a-z]+$/i,"").replace(/^[a-z0-9]+__/i,"").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([A-Za-z])(\d)/g,"$1 $2").replace(/(\d)([A-Za-z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(i=>i!=="").map(i=>i.toLowerCase())}function h(a,i){let n=i.toLowerCase();if(n==="email")return"email";if(n==="phone")return"phone";if(!u.has(n))return;if(m.has(a))return"email";let e;for(let t of f(a))I.has(t)||t.endsWith("email")?e="email":(P.has(t)||t.endsWith("phone"))&&(e="phone");return e}function N(a,i){let n=new Set(a.detectPII("unknown",i.map(e=>({apiName:e.name,label:e.name,type:e.type}))).piiFields.map(e=>e.fieldApiName));return i.filter(e=>n.has(e.name)||h(e.name,e.type)!==void 0).map(e=>e.name)}var l=class{namePatterns;contentPatterns;constructor(){this.namePatterns=x(),this.contentPatterns=_()}detectPII(i,n,e){let t=new Map;for(let s of n)this.detectByName(s,t),this.detectByType(s,t);if(e&&e.length>0)for(let s of n)this.detectByContent(s,e,t);let c=Array.from(t.values());return{objectName:i,totalFields:n.length,piiFields:c,riskLevel:w(c.length)}}getPatterns(){let i={};for(let n of this.contentPatterns)i[n.label]=n.regex;return i}detectByName(i,n){let e=i.apiName.toLowerCase().replace(/__c$/i,""),t=f(i.apiName).join(" "),c=i.label.toLowerCase(),s=i.type.toLowerCase();for(let o of this.namePatterns){if(o.types&&!o.types.has(s))continue;let b=o.words?t:e;if(o.regex.test(b)||o.regex.test(c)){this.addDetection(n,i,{classification:o.classification,detectionMethod:"name_pattern",confidence:o.confidence,pattern:o.label});return}}}detectByType(i,n){if(n.has(i.apiName))return;let e=i.type.toLowerCase();e==="email"?this.addDetection(n,i,{classification:"PII",detectionMethod:"type_analysis",confidence:.95,pattern:"email_type"}):e==="phone"&&this.addDetection(n,i,{classification:"PII",detectionMethod:"type_analysis",confidence:.9,pattern:"phone_type"})}detectByContent(i,n,e){if(!e.has(i.apiName))for(let t of this.contentPatterns){let c=y(i.apiName,n,t.regex);if(c>0){let s=c/n.length,o=t.confidence*Math.min(s*2,1);this.addDetection(e,i,{classification:t.classification,detectionMethod:"content_pattern",confidence:o,pattern:t.label});return}}}addDetection(i,n,e){let t=i.get(n.apiName);t&&t.confidence>=e.confidence||i.set(n.apiName,{fieldApiName:n.apiName,fieldLabel:n.label,classification:e.classification,detectionMethod:e.detectionMethod,confidence:e.confidence,pattern:e.pattern})}};function x(){return[{regex:/\bemail\b/i,classification:"PII",confidence:.95,label:"email"},{regex:/\bphone\b/i,classification:"PII",confidence:.9,label:"phone"},{regex:/\bmobilephone\b/i,classification:"PII",confidence:.9,label:"mobile_phone"},{regex:/\bpersonemail\b/i,classification:"PII",confidence:.95,label:"person_email"},{regex:/\bmailingstreet\b/i,classification:"PII",confidence:.85,label:"mailing_street"},{regex:/\bbillingstreet\b/i,classification:"PII",confidence:.85,label:"billing_street"},{regex:/\bssn\b/i,classification:"PII",confidence:.99,label:"ssn"},{regex:/\bsocialsecuritynumber\b/i,classification:"PII",confidence:.99,label:"social_security_number"},{regex:/\bsocial_security\b/i,classification:"PII",confidence:.99,label:"social_security"},{regex:/\bbirthdate\b/i,classification:"PII",confidence:.9,label:"birthdate"},{regex:/\bdateofbirth\b/i,classification:"PII",confidence:.9,label:"date_of_birth"},{regex:/\bdate_of_birth\b/i,classification:"PII",confidence:.9,label:"date_of_birth_underscore"},{regex:/\bnationalid\b/i,classification:"PII",confidence:.95,label:"national_id"},{regex:/\bnational_id\b/i,classification:"PII",confidence:.95,label:"national_id_underscore"},{regex:/\bcreditcardnumber\b/i,classification:"PCI",confidence:.99,label:"credit_card_number"},{regex:/\bcreditcard\b/i,classification:"PCI",confidence:.95,label:"credit_card"},{regex:/\bcredit_card\b/i,classification:"PCI",confidence:.95,label:"credit_card_underscore"},{regex:/\biban\b/i,classification:"PCI",confidence:.95,label:"iban"},{regex:/\bbankaccount\b/i,classification:"PCI",confidence:.95,label:"bank_account"},{regex:/\bbank_account\b/i,classification:"PCI",confidence:.95,label:"bank_account_underscore"},{regex:/\bmedical\b/i,classification:"PHI",confidence:.85,label:"medical"},{regex:/\bdiagnos/i,classification:"PHI",confidence:.9,label:"diagnosis"},{regex:/\bhealth\b/i,classification:"PHI",confidence:.8,label:"health"},{regex:/\bpatient\b/i,classification:"PHI",confidence:.8,label:"patient"},{regex:/\bpassport\b/i,classification:"PII",confidence:.95,label:"passport"},{regex:/\bdriver.?licen/i,classification:"PII",confidence:.95,label:"driver_license"},{regex:/\baddress\b/i,classification:"PII",confidence:.8,label:"address"},{regex:d,classification:"PII",confidence:.85,label:"person_name",types:g},...p]}function _(){return[{regex:/[\w.-]+@[\w.-]+\.\w{2,}/,classification:"PII",confidence:.9,label:"email_content"},{regex:/\d{3}-\d{2}-\d{4}/,classification:"PII",confidence:.95,label:"ssn_content"},{regex:/\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}/,classification:"PCI",confidence:.95,label:"credit_card_content"},{regex:/[A-Z]{2}\d{2}[A-Z0-9]{4,}/,classification:"PCI",confidence:.85,label:"iban_content"},{regex:/\+?\d[\d\s-]{7,}/,classification:"PII",confidence:.7,label:"phone_content"}]}function y(a,i,n){let e=0;for(let t of i){let c=t[a];typeof c=="string"&&n.test(c)&&e++}return e}function w(a){return a===0?"none":a<=2?"low":a<=5?"medium":a<=10?"high":"critical"}export{C as a,h as b,N as c,l as d};
@@ -1,10 +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{c as Lt,d as vt}from"./chunk-FBYFCKPG.mjs";import{a as en,c as Pn,d as Se,e as Pt,f as It,g as Dt,h as Nt,j as jt,l as Wn,m as xn}from"./chunk-GG5I52UT.mjs";import{d as dn,f as hn,g as mt,h as kt,i as yt,k as bt,l as Sn,m as _n}from"./chunk-A3QNSALB.mjs";import{a as En}from"./chunk-EYFP3NA6.mjs";import{B as ct}from"./chunk-CSSOLHE3.mjs";import{A as $n,B as ae,C as Ct,E as _e,F as wn,G as St,e as dt,i as oe,l as Ye,p as Mn,q as wt,r as Ve,s as pt,t as Ot,x as Rt,y as At,z as Te}from"./chunk-YGE4AUXG.mjs";import{b as Q,e as Je,g as Tn}from"./chunk-C2MHMI7U.mjs";import{J as ht,a as ft,b as lt,d as cn,o as ut,x as gt,z as Cn}from"./chunk-SF52ZSIV.mjs";import{b as gn,d as Me,e as at}from"./chunk-P6A22FMQ.mjs";import{i as rt}from"./chunk-INIT2UKJ.mjs";import{E as an}from"./chunk-TWYNQ2OO.mjs";import{f as it,g as le,h as be,i as st,p as An}from"./chunk-FG4Y4ZVL.mjs";import{a as ot,q as Rn,r as he}from"./chunk-Z354SAEF.mjs";import{h as On}from"./chunk-TZE3Y7IQ.mjs";import{b as je}from"./chunk-CA5NAXSU.mjs";import{Uc as ye}from"./chunk-CRPLDXJU.mjs";import{b as tt,k as yn,l as bn}from"./chunk-WZQEK4WT.mjs";import{randomBytes as Ai}from"node:crypto";import{appendFile as Ci,readdir as Si,rm as Pi}from"node:fs/promises";import{join as Fn}from"node:path";import{appendFile as Bo,rm as Zn}from"node:fs/promises";import{join as Fo}from"node:path";import{appendFile as ko}from"node:fs/promises";import{join as yo}from"node:path";var vn=dt*10,bo=2e3,Oo="005",Ro=["Id","IsDeleted","CreatedDate","LastModifiedById","LastModifiedDate","LatestPublishedVersionId","ContentSize"],xt=1,Ut=2,Gt=4,Bt=8,zn=16,Dn=32,Nn=64,Ft=1,Et=2,Mt=4,In=32768,jn={toDelete:["createdSince","broughtBackSince"],comesBack:["inBin","withParent","deletedWhileTaken"],lost:["goneForGood","toRecreate"]},Un={toDelete:["createdSince","broughtBackSince","comesBackWithParent"],comesBack:["inBin","withParent","deletedWhileTaken"],lost:["goneForGood","deletedWithCreatedParent","deletedWithParentOutside"]};function $e(e){return typeof e=="string"&&e.length>=15?e.slice(0,15):void 0}function qn(e){return`${e.ContentDocumentId.slice(0,15)}${e.LinkedEntityId.slice(0,15)}`}function zt(e){return`${e.ShareType}/${e.Visibility}`}async function*pn(e){try{for await(let n of ae(e))yield n}catch(n){if(n.code==="ENOENT")return;throw n}}function Tt(e){return typeof e=="string"&&/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/.test(e)?e:null}function Gn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function Ao(e){let n=an(e);return n===null?Number.NaN:Date.parse(n)}var Qe=class{constructor(n){this.file=n}file;lines=[];count=0;async add(n){this.lines.push(`${JSON.stringify(n)}
8
- `),this.count++,this.lines.length>=bo&&await this.flush()}async flush(){if(this.lines.length===0)return;let n=this.lines.join("");this.lines=[],await ko(this.file,n,{encoding:"utf8",mode:cn,flag:"a"})}};function _t(e,n,t){let o=ye(n);return yo(e,`${o}.links${t===void 0?"":`.${t}`}.ndjson`)}function*qt(e,n){let t=[];for(let o of e)t.push(o),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}var Co=bn({sobjects:yn(it)}).loose(),Hn=class{files=new Q;held=new Map;sharings=[];prefixes;now;constructor(n,t){this.prefixes=n,this.now=t}anchoredNow(n){return(this.files.flagsOf(n)&Gt)!==0}anchoredThen(n){return(this.files.flagsOf(n)&Ut)!==0}sharingAt(n){let t=this.sharings.indexOf(n);return t>=0?t:(this.sharings.push(n),this.sharings.length-1)}};function So(e,n){let t=n.fields.find(s=>s.name.toLowerCase()==="linkedentityid"),o=new Set((t?.referenceTo??[]).map(s=>s.toLowerCase()));if(o.size===0)throw new Error(`The describe of ${be} names no record a link ties a file to.`);return e.objects.map(({objectApiName:s})=>s).filter(s=>{if(s.toLowerCase()===le.toLowerCase()||!o.has(s.toLowerCase()))return!1;let i=e.changes.get(s);return i!==void 0&&!("unread"in i)&&(i.count??0)>0})}async function*Po(e,n){let t=await Ve.read(e.folder,e.snapshotId,n);for(let s=0;s<t.size;s++)yield t.idAt(s);let o=e.changes.get(n);if(!(o===void 0||"unread"in o||!o.live))for await(let s of ae(o.live.file))typeof s.Id=="string"&&!t.has(s.Id)&&(yield s.Id)}async function Io(e,n){let{reader:t,previewDir:o,signal:s}=e,i=n.map(l=>({...Nt(l),file:_t(o,l)})),r=await $n(t,i,s),a=[];for(let[l,w]of r.entries()){let p=n[l];if(w.read){a.push({objectApiName:p,file:i[l].file});continue}let c=0,g=Po(e,p);for await(let f of Do(g,en*vn)){let h=[...qt(f,en)].map(L=>({...jt(p,L),file:_t(o,p,c++)})),A=(await $n(t,h,s)).find(L=>!L.read);if(A&&!A.read)throw new Error(`The links of the files of ${p} could not be read whole: ${w.reason}; read by the ids of its records, ${A.reason}`);for(let L of h)a.push({objectApiName:p,file:L.file})}}return a}async function*Do(e,n){let t=[];for await(let o of e)t.push(o),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}async function Ht(e){let n=Co.safeParse(await e.describeGlobal());if(!n.success)throw new Error("The org\u2019s global describe does not read as one.");let t=It(n.data.sobjects,e.objects.map(({objectApiName:a})=>a)),o=So(e,await e.linkDescribe),s=await Io(e,o),i=new Hn(t,s);for await(let a of xn(e.folder))i.files.add(a.Id,xt|(a.anchored?Ut:0));let r=await Mn.read(e.folder);for await(let a of Wn(e.folder))i.held.set(qn(Kt(a,r)),i.sharingAt(zt(a)));for(let{file:a}of s)for await(let l of ae(a))typeof l.ContentDocumentId=="string"&&i.files.add(l.ContentDocumentId,Gt);return i}function Kt(e,n){let t=$e(e.LinkedEntityId),o=t===void 0?void 0:n.currentOf(t);return o===void 0?e:{...e,LinkedEntityId:o}}async function Ln(e,n,t,o,s){for(let i of o)for await(let r of pn(n(t,i)))typeof r.Id=="string"&&e.add(r.Id,s)}async function $t(e){let n=0;for await(let t of pn(e))typeof t.Id=="string"&&n++;return n}async function Wt(e,n,t){let o=new Map;if(n.length===0)return o;let s=Me([...n],en).map(a=>({objectApiName:le,soql:`SELECT ${Ro.join(", ")} FROM ${le} WHERE Id IN (${a})`,scanAll:!0})),r=(await Te(e,s,(a,l)=>{for(let w of l){let p=$e(w.Id);p!==void 0&&o.set(p,w)}},t)).find(a=>!a.read);if(r&&!r.read)throw new Error(`The files the checkpoint names could not be read by their ids: ${r.reason}`);return o}function No(e,n){return n===void 0||n.version===null||e.LatestPublishedVersionId===null?!1:$e(n.version)!==$e(e.LatestPublishedVersionId)}async function Vt(e){let{anchors:n,reader:t,classFileOf:o,signal:s}=e,i=n.files,r=le;await Ln(i,o,r,jn.toDelete,zn),await Ln(i,o,r,jn.comesBack,Dn),await Ln(i,o,r,jn.lost,Nn);let a=new Map,l=e.fileChanges;if(!("unread"in l)){for(let D of[l.live,l.deleted])if(D!==void 0)for await(let v of ae(D.file)){let N=$e(v.Id);N!==void 0&&(i.add(String(v.Id),Bt),a.set(N,{version:Tt(v.LatestPublishedVersionId),size:Gn(v.ContentSize)}))}}let w=await Ve.read(e.folder,e.snapshotId,r),p=D=>(i.flagsOf(D)&Bt)===0&&!w.has(D),c=new Qe(o(r,"createdSince")),g=new Qe(o(r,"deletedWhileTaken")),f=new Qe(o(r,"goneForGood")),d=new Qe(o(r,"newFileVersion")),h=0,R=0,A=async D=>{let v=await Wt(t,D.filter(N=>N.anchored&&p(N.Id)).map(N=>N.Id),s);for(let N of D){if(!N.anchored)continue;let V=$e(N.Id)??"",J=a.get(V);if(p(N.Id)){let x=v.get(V);if(x===void 0){i.add(N.Id,Nn),await f.add({Id:N.Id});continue}J={version:Tt(x.LatestPublishedVersionId),size:Gn(x.ContentSize)},x.IsDeleted===!0&&(i.add(N.Id,Dn),await g.add({Id:N.Id}))}let Y=i.flagsOf(N.Id);(Y&Nn)===0&&((Y&Dn)!==0&&(h+=J?.size??N.ContentSize??0),No(N,J)&&await d.add({Id:N.Id}))}},L=[];for await(let D of xn(e.folder))L.push(D),L.length>=en*vn&&(await A(L),L=[]);await A(L);let P=new Q,B=[],C=async D=>{let v=await Wt(t,D,s);for(let N of D){let V=v.get($e(N)??"");V===void 0||V.IsDeleted===!0||Ao(V.CreatedDate)>=e.t0s&&(i.add(N,zn),await c.add({Id:N}),B.push(V))}},F=[];for(let{file:D}of n.now)for await(let v of ae(D)){let N=v.ContentDocumentId;typeof N!="string"||(i.flagsOf(N)&xt)!==0||!p(N)||P.add(N)&&(F.push(N),F.length>=en*vn&&(await C(F),F=[]))}await C(F);for await(let D of pn(o(r,"createdSince"))){let v=$e(D.Id);v!==void 0&&(R+=a.get(v)?.size??0)}for await(let D of pn(o(r,"broughtBackSince")))R+=a.get($e(D.Id)??"")?.size??0;for(let D of B)R+=Gn(D.ContentSize)??0;for(let D of[c,g,f,d])await D.flush();return{files:{...await jo(e),outsideAdded:await $t(o(r,"outsideAdded")),outsideDeleted:await $t(o(r,"outsideDeleted")),storage:{bringBack:h,undo:R},...e.queryAllFiles?{}:{blindSpot:!0}},createdSince:c.count,deletedWhileTaken:g.count,goneForGood:f.count,newFileVersion:d.count,changedBy:B}}async function jo(e){let{anchors:n,classFileOf:t}=e,o=new Q,s=new Set;for(let{objectApiName:c}of e.objects){if(c.toLowerCase()===le.toLowerCase())continue;if(!e.told.has(c)){for(let[f,d]of n.prefixes)d.toLowerCase()===c.toLowerCase()&&s.add(f);continue}let g=(f,d)=>Ln(o,t,c,f,d);await g(Un.toDelete,Ft),await g(Un.comesBack,Et),await g(Un.lost,Mt)}let i=c=>s.has(c.LinkedEntityId.slice(0,3)),r=c=>new Qe(Se(e.previewDir,c)),a=r("linkAdded"),l=r("linkRemoved"),w=r("linkChanged");for(let{file:c}of n.now)for await(let g of ae(c)){let f=Pn.safeParse(g);if(!f.success)throw new Error(`The org answered a link that does not read as one: ${f.error.message}`);let d=f.data,h=qn(d),R=n.held.get(h);if(R!==void 0){if(n.held.set(h,R|In),i(d)||n.sharings[R&~In]===zt(d))continue;let[A,L]=(n.sharings[R&~In]??"").split("/"),P={...d,ShareType:A,Visibility:L,now:{ShareType:d.ShareType,Visibility:d.Visibility}};await w.add(P);continue}i(d)||(n.files.flagsOf(d.ContentDocumentId)&zn)===0&&(o.flagsOf(d.LinkedEntityId)&Ft)===0&&await a.add(d)}let p=await Mn.read(e.folder);for await(let c of Wn(e.folder)){let g=Kt(c,p);((n.held.get(qn(g))??0)&In)!==0||i(g)||(n.files.flagsOf(g.ContentDocumentId)&(Dn|Nn))===0&&(o.flagsOf(g.LinkedEntityId)&(Et|Mt))===0&&await l.add(g)}for(let c of[a,l,w])await c.flush();return{unlink:a.count,relink:l.count,updateLinks:w.count}}async function Jt(e){let{anchors:n,reader:t,classFileOf:o,signal:s}=e,i=[];for(let l of jn.toDelete)for await(let w of pn(o(le,l)))typeof w.Id=="string"&&i.push(w.Id);if(i.length===0)return{links:0,files:0};let r=new Map,a=0;for(let l of qt(Me(i,en),vn)){let w=l.map(g=>({objectApiName:be,soql:`SELECT Id, ContentDocumentId, LinkedEntityId FROM ${be} WHERE ContentDocumentId IN (${g})`,scanAll:!1})),c=(await Te(t,w,(g,f)=>{for(let d of f){let h=d.LinkedEntityId,R=d.ContentDocumentId;typeof h!="string"||typeof R!="string"||h.startsWith(Oo)||Dt({LinkedEntityId:h},n.prefixes)===void 0&&(a++,r.set(R.slice(0,15),R))}},s)).find(g=>!g.read);if(c&&!c.read)throw new Error(`The links of the files to delete to what the checkpoint does not hold could not be read: ${c.reason}`)}if(r.size>0){let l=new Qe(o(le,"outsideParents"));for(let w of r.values())await l.add({Id:w});await l.flush()}return{links:a,files:r.size}}var Vn=Object.freeze({kind:"org",notHeld:new Map,heldAs:()=>"org",unseenOf:()=>Promise.resolve([]),requests:()=>0,diffAccess:()=>({kind:"org"})});function Kn(e){return e.slice(0,15)}function Lo(e,n,t,o){let s=n.detail!==void 0?` (${n.detail})`:"";switch(n.reason){case"noViewAll":case"noModifyAll":return`${t} ${o} View All and Modify All on ${e}`;case"parentNotSeen":return`${t} ${o} View All and Modify All on every record ${e} hangs from`+s;case"activities":return`${t} doesn't have View All Data and Modify All Data, which tasks and events need: Salesforce has no View All for activities`;case"catalog":return`${t} doesn't have View All Data and Modify All Data, which products and price books need: Salesforce has no View All or Modify All for them`;case"filesNotProven":return`${t} doesn't have View All Data and Modify All Data, which files need: nothing else proves who sees every file`;case"settingNotProven":return`${t} doesn't have View All Data and Modify All Data, which custom settings need: no permission on an object proves who sees and writes every row`}}async function ls(e){let{grants:n,reader:t}=e;if(n.kind==="org"||e.userId===void 0)return Vn;let o=e.checkpoint.objects,s=o.filter(d=>d.customSetting!==void 0).map(d=>d.objectApiName),i=new Map,r=n.requests,a=async d=>{let h=[...new Set(d)].filter(L=>!i.has(L.toLowerCase()));if(h.length===0)return;let R=t.calls(),A=await Promise.allSettled(h.map(L=>t.describe(L)));r+=t.calls()-R,A.forEach((L,P)=>{if(L.status==="rejected"&&L.reason instanceof oe)throw L.reason;let B=L.status==="fulfilled"&&"body"in L.value?L.value.body:void 0,C=dn.safeParse(B);i.set(h[P].toLowerCase(),C.success?C.data:void 0)})},l=()=>[...i.values()].filter(d=>d!==void 0),w=async d=>{let h=d.filter(A=>!n.objects.has(A.toLowerCase()));await a(h);let R={grants:n.objects,describes:l(),customSettings:s};return await a(Lt(d,R)),vt(d,{...R,describes:l()})},p=await w(o.map(d=>d.objectApiName)),c=Kn(e.userId)===Kn(e.checkpoint.takenBy.userId)?"no longer has":"doesn't have",g=new Map,f=new Map;for(let[d,h]of p)"access"in h?g.set(d,h.access):f.set(d,Lo(d,h,e.username,c));return{kind:"perObject",userKey:Kn(e.userId),notHeld:f,heldAs:d=>g.get(d),unseenOf:async d=>{let h=await w(d);return d.filter(R=>{let A=h.get(R);return A===void 0||!("access"in A)})},requests:()=>r,diffAccess:()=>({kind:"perObject",requests:r})}}var Eo=["giveBack","touched","createdSince","broughtBackSince","comesBackWithParent","unexplained","inBin","withParent","deletedWhileTaken","toRecreate","goneForGood","convertedLead","activatedContract","carrier","deletedWithCreatedParent","deletedWithParentOutside","deletedByOther","outOfReach","undoCannot","outsideParents","outsideAdded","outsideDeleted","newFileVersion"],Mo="Lead",To="IsConverted",_o="Contract",$o="Status",Qt="StatusCode",Wo="Activated",xo=["createdSince","broughtBackSince"];function X(e,n,t){return Fo(e,`${ye(n)}.${t}.ndjson`)}var Bn=1e3,Uo=1440*6e4,Go=60*6e4,zo=100,qo=2e3,eo=["LastModifiedById","LastModifiedDate"];function ne(e){return typeof e=="string"&&e.length>=15?e.slice(0,15):void 0}function Oe(e){let n=an(e);return n===null?Number.NaN:Date.parse(n)}function Xn(e){return e.toLowerCase()===le.toLowerCase()}function Ho(e){return e==null||e===""}function Le(e,n){let t=n.toLowerCase();return e.find(o=>o.toLowerCase()===t)}function Ko(e){return!e.leftOutFields.some(n=>n.reason==="base64")}var mn=class{constructor(n){this.file=n}file;lines=[];written=!1;count=0;async add(n){this.lines.push(`${JSON.stringify(n)}
9
- `),this.count++,this.lines.length>=qo&&await this.flush()}async flush(){if(this.lines.length===0)return;let n=this.lines.join("");this.lines=[],await Bo(this.file,n,{encoding:"utf8",mode:cn,flag:this.written?"a":"w"}),this.written=!0}async discard(){this.lines=[],this.written&&await Zn(this.file,{force:!0})}};async function Yn(e,n){await Promise.all(Eo.map(t=>Zn(X(e,n,t),{force:!0})))}var Jn=class{constructor(n){this.activeFrom=n}activeFrom;counts=new Map;active=new Set;add(n){let t=n.LastModifiedById;typeof t!="string"||t===""||(this.counts.set(t,(this.counts.get(t)??0)+1),Oe(n.LastModifiedDate)>=this.activeFrom&&this.active.add(t))}byUser(){return Object.fromEntries([...this.counts].sort(([n],[t])=>n<t?-1:n>t?1:0))}};function no(e,n){let t,o=async()=>{let s=new Set;try{for await(let i of ae(ut(e,n))){let r=ne(i.Id);r!==void 0&&s.add(r)}}catch(i){throw i.code!=="ENOENT"?i:new Error(`The checkpoint\u2019s list of what ${n} held in the recycle bin is not on this machine.`)}return s};return async s=>(await(t??=o())).has(s)}async function Vo(e,n,t,o){let s=ye(n.objectApiName),i=n.readMode==="scanAllLive",r=i?" AND IsDeleted = false":"",a=async p=>{let c=e.lane(),g=[];try{let f=await At(c,{objectApiName:s,soql:p,scanAll:i},d=>{g.push(...d)});if(!f.read)throw new Error(f.reason);return g}finally{c.close()}},l=t.length>zo?gn/4:gn,w=new Map;for(let p of Me(o,l)){let c=await rt(`SELECT ${t.join(", ")} FROM ${s} WHERE Id IN (${p})${r}`,a,{stamp:"SystemModstamp",...i?{idsWhere:"IsDeleted = false"}:{}});for(let g of c){let f=ne(g.Id);f!==void 0&&w.set(f,g)}}return w}var Jo=/__(?:c|pc|s)$/i,Qo=/^(.+)__[A-Za-z]+__s$/i,Zo=/^(.+)__pc$/i,Xo=/^[A-Za-z][A-Za-z0-9_]*$/,Yo=200;function ei(e,n){if(!Jo.test(n)||!Xo.test(n))return;let t=Zo.exec(n);if(t)return{entity:he,name:`${t[1]}__c`};let o=Qo.exec(n);return o?{entity:e,name:`${o[1]}__c`}:{entity:e,name:n}}var ni=yn(bn({QualifiedApiName:tt()}).loose());function ti(e,n){let t=`SELECT QualifiedApiName FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName = '${ye(e)}' AND QualifiedApiName IN (`,o=r=>`${t}${r.map(a=>`'${a}'`).join(", ")})`,s=[],i=[];for(let r of n){let a=[...i,r],l=a.length>Yo||encodeURIComponent(o(a)).length>14e3;i.length>0&&l?(s.push({soql:o(i),names:i}),i=[r]):i=a}return i.length>0&&s.push({soql:o(i),names:i}),s}async function oi(e,n){let t=new Map,o=new Map;for(let[r,a]of n){let l={removed:[],hidden:[]};t.set(r,l);for(let w of a){let p=ei(r,w);if(p===void 0){l.hidden.push(w);continue}let c=o.get(p.entity)??new Map;o.set(p.entity,c);let g=p.name.toLowerCase(),f=c.get(g)??{name:p.name,fields:[]};c.set(g,f),f.fields.push({objectApiName:r,field:w})}}let s=0,i=new Map;for(let[r,a]of o){let l=new Set,w=new Map,p=ti(r,[...a.values()].map(({name:c})=>c));for(let c of p){s++;try{let g=await e.tooling(c.soql);if(!g.done)throw new Error("FieldDefinition answered more than one page");let f=ni.safeParse(g.records);if(!f.success)throw new Error("FieldDefinition answered rows with no field name");for(let d of f.data)l.add(d.QualifiedApiName.toLowerCase())}catch(g){if(g instanceof oe)throw g;let f=je(g);for(let d of c.names)w.set(d.toLowerCase(),f)}}for(let[c,{fields:g}]of a){let f=w.get(c);for(let{objectApiName:d,field:h}of g){let R=t.get(d);if(R!==void 0)if(f!==void 0){let A=i.get(d)??{fields:[],reasons:[]};i.set(d,A),A.fields.push(h),A.reasons.includes(f)||A.reasons.push(f)}else l.has(c)?R.hidden.push(h):R.removed.push(h)}}}for(let[r,a]of t){a.removed.sort(),a.hidden.sort();let l=i.get(r);l!==void 0&&(a.uncertain={fields:l.fields.sort(),...l.reasons.length>0?{reason:l.reasons.join("; ")}:{}})}return{gone:t,requests:s}}async function Zt(e,n,t){let{checkpoint:o,folder:s,reader:i}=e,r=new Date(Date.parse(o.readFrom)-Uo).toISOString(),a=await Promise.allSettled(n.map(({objectApiName:h})=>i.describe(h,r))),l,w=new Map,p=new Map;for(let[h,R]of a.entries()){let A=n[h].objectApiName;if(R.status==="rejected"){if(R.reason instanceof oe)throw R.reason;w.set(A,{unread:`The org did not answer the describe of ${A}: ${je(R.reason)}`});continue}if("notModified"in R.value){w.set(A,{gone:new Set});continue}let L=dn.safeParse(R.value.body);if(!L.success){w.set(A,{unread:`The describe of ${A} does not read as one.`});continue}t.set(A,L.data);try{let P=(await(l??=ht(s,o.objects))).get(A);if(P===void 0)throw new Error(`The checkpoint holds no field prints of ${A}.`);p.set(A,lt(P,ft(L.data.fields)))}catch(P){w.set(A,{unread:je(P)})}}let c=new Map(n.map(h=>[h.objectApiName,new Set(Sn(h.objectApiName,h.fields,o.ignoredFields).map(R=>R.toLowerCase()))])),g=(h,R)=>R.filter(A=>c.get(h)?.has(A.toLowerCase())===!0),f=new Map([...p].map(([h,R])=>[h,g(h,R.removed)]).filter(([,h])=>h.length>0)),d=f.size>0?await oi(i,f):{gone:new Map,requests:0};for(let[h,{removed:R,added:A,changed:L}]of p){let P=d.gone.get(h);w.set(h,{...g(h,R).length+A.length+L.length>0?{drift:{removed:P?.removed??[],added:A,changed:L,...P!==void 0&&P.hidden.length>0?{hidden:P.hidden}:{},...P?.uncertain!==void 0?{uncertain:P.uncertain}:{}}}:{},gone:new Set(R.map(B=>B.toLowerCase()))})}return{now:w,requests:d.requests}}function ii(e,n){let t=i=>{let r=n.get(i);return r!==void 0&&!("unread"in r)&&r.moved},o=e.find(({objectApiName:i})=>i===he),s=o!==void 0&&Le(o.fields,hn)!==void 0&&t(he);return e.filter(({objectApiName:i})=>t(i)||s&&i===Rn)}function si(e,n){let t=[...e.cascadeParents,...e.restrictParents??[]].filter(s=>!n.has(s.toLowerCase()));if(e.customSetting!==void 0){let s=Le(e.fields,An(e.customSetting));s!==void 0&&!n.has(s.toLowerCase())&&!t.includes(s)&&t.push(s)}if(Xn(e.objectApiName))for(let s of mt){let i=Le(e.fields,s);i!==void 0&&!n.has(i.toLowerCase())&&t.push(i)}let o=Le(e.fields,hn);if(e.objectApiName===he&&o!==void 0){let s=Le(e.fields,"AccountId");for(let i of[o,s])i!==void 0&&!n.has(i.toLowerCase())&&t.push(i)}return[...t,...eo]}async function ri(e,n,t){let{folder:o,checkpoint:s}=e.input,i=new Map,r=new Map;for(let{objectApiName:a,cascadeParents:l,restrictParents:w=[]}of n){let p=t.get(a);if(!p||"unread"in p||!p.deleted||p.deleted.rows===0)continue;let c=new Map,g=new Map;try{let f=await Ve.read(o,s.snapshotId,a),d=no(o,a);for await(let h of ae(p.deleted.file)){let R=ne(h.Id);if(R===void 0)continue;let A=B=>B.map(C=>ne(h[C])).filter(C=>C!==void 0&&C!==R),L=ne(h.LastModifiedById),P=()=>({objectApiName:a,id:String(h.Id),stamp:Oe(h.SystemModstamp),parents:A(l),restricts:A(w),...L!==void 0?{by:L}:{}});if(!f.retired(h.Id)){if(!f.has(h.Id)){if(await d(R)){g.set(R,P());continue}if(Oe(h.CreatedDate)>=e.t0s&&g.set(R,P()),!(Oe(h.CreatedDate)<e.t0s))continue}c.set(R,P())}}}catch(f){if(f instanceof oe)throw f;continue}for(let[f,d]of c)i.set(f,d);for(let[f,d]of g)r.set(f,d)}return{back:i,gone:r}}function ai(e,n){let t=s=>e.get(s)?.stamp??n.get(s)?.stamp,o=new Set;for(let s of[e,n])for(let[i,r]of s)[...r.parents,...r.restricts].some(l=>(t(l)??0)>r.stamp)&&o.add(i);return Qn(o,e,n),o}function Qn(e,n,t){let o=s=>n.get(s)?.stamp??t.get(s)?.stamp;for(let s=e.size>0;s;){s=!1;for(let i of[n,t])for(let[r,a]of i){if(e.has(r))continue;a.parents.some(w=>e.has(w)&&o(w)===a.stamp)&&(e.add(r),s=!0)}}for(let s of e)n.delete(s)}function ci(e,n){if(n===void 0)return new Set;let t=[...e].filter(([,o])=>o.by!==n).map(([o])=>o);return to(t,e)}function to(e,n){let t=new Set(e);for(let o=t.size>0;o;){o=!1;for(let[s,i]of n){if(t.has(s))continue;i.parents.some(a=>t.has(a)&&n.get(a)?.stamp===i.stamp)&&(t.add(s),o=!0)}}return t}function di(e,n,t){let o=new Map(e.map(l=>[l.objectApiName,l.undeletable])),s=new Set,i=new Set,r=(l,w)=>l.parents.find(p=>!w.has(p)&&t.get(p)?.stamp===l.stamp),a=l=>l.parents.some(w=>n.get(w)?.stamp===l.stamp);for(let l of[...n.values()]){if(a(l))continue;let w=new Set,p=[],c=r(l,w),g=!1;for(;c!==void 0;){w.add(c),p.push(c);let h=t.get(c);if(!h)break;if(a(h)){g=!0;break}c=r(h,w)}let f=p[p.length-1];if(f===void 0||g)continue;let d=t.get(f);if(!(!d||o.get(d.objectApiName)!==!0)){s.add(f);for(let h of p.slice(0,-1))i.add(h)}}for(let l of[...s,...i]){let w=t.get(l);w&&n.set(l,w)}return s}function fi(e,n,t){let o=new Map;for(let[s,i]of e){if(t.has(s)){o.set(s,"deletedWithParentOutside");continue}if(n.has(s))continue;i.parents.some(a=>!e.has(a)&&n.get(a)?.stamp===i.stamp)&&o.set(s,"deletedWithCreatedParent")}for(let s=o.size>0;s;){s=!1;for(let[i,r]of e){if(o.has(i))continue;let a=r.parents.find(w=>o.has(w)&&e.get(w)?.stamp===r.stamp),l=a===void 0?void 0:o.get(a);l!==void 0&&(o.set(i,l),s=!0)}}for(let s of o.keys())e.delete(s);return o}async function li(e,n,t,o,s,i){let r=new Set,a=new Set,l=new Set(n.map(({objectApiName:f})=>f.toLowerCase())),w=new Map(n.map(f=>[f.objectApiName,f])),p=new Map;for(let[f,d]of t)o.has(f)||s.has(f)||d.parents.some(R=>(t.get(R)??o.get(R))?.stamp===d.stamp)||p.set(d.objectApiName,[...p.get(d.objectApiName)??[],d]);if(p.size===0)return{outside:r,stuck:a,requests:0};let c=e.reader.calls(),g=async f=>{try{return await i(f)}catch(d){if(d instanceof oe)throw d;return}};for(let[f,d]of p){let h=w.get(f),R=await g(f);if(!h||!R)continue;let A=new Set([...h.cascadeParents,...h.restrictParents??[]].map(I=>I.toLowerCase())),L=R.fields.filter(I=>I.type==="reference"&&!A.has(I.name.toLowerCase())&&(I.referenceTo??[]).some(q=>!l.has(q.toLowerCase())));if(L.length===0)continue;let P=[...new Set(L.flatMap(I=>(I.referenceTo??[]).filter(q=>!l.has(q.toLowerCase()))))],B=await Promise.all(P.map(g)),C=new Map;if(B.forEach((I,q)=>{if(!I)return;let Z=I.keyPrefix;for(let U of I.childRelationships??[]){if(U.cascadeDelete!==!0||U.childSObject.toLowerCase()!==f.toLowerCase())continue;let de=L.find(se=>se.name.toLowerCase()===U.field.toLowerCase());de&&C.set(de.name,[...C.get(de.name)??[],{object:P[q],...typeof Z=="string"?{prefix:Z}:{}}])}}),C.size===0)continue;let F=[...C.keys()].map(On),_=ye(f),D=d.map(I=>I.id),v=new Map,N=Me(D).map(I=>({objectApiName:_,soql:`SELECT Id, ${F.join(", ")} FROM ${_} WHERE Id IN (${I}) AND IsDeleted = true`,scanAll:!0}));if((await Te(e.reader,N,(I,q)=>{for(let Z of q){let U=ne(Z.Id);if(U!==void 0)for(let[de,se]of C){let ue=Z[de];if(typeof ue!="string"||ne(ue)===void 0)continue;let ve=se.length===1?se[0]:se.find(we=>we.prefix!==void 0&&ue.startsWith(we.prefix));ve&&v.set(U,[...v.get(U)??[],{object:ve.object,id:ue}])}}},e.signal)).some(I=>!I.read))continue;let J=new Map;for(let I of v.values())for(let{object:q,id:Z}of I)J.set(q,[...J.get(q)??[],Z]);let Y=[];for(let[I,q]of J){let Z=ye(I);for(let U of Me([...new Set(q)]))Y.push({object:I,read:{objectApiName:Z,soql:`SELECT Id, IsDeleted, SystemModstamp FROM ${Z} WHERE Id IN (${U})`,scanAll:!0}})}let x=new Map;await Te(e.reader,Y.map(({read:I})=>I),(I,q)=>{for(let Z of q){let U=ne(Z.Id);U!==void 0&&Z.IsDeleted===!0&&x.set(U,Oe(Z.SystemModstamp))}},e.signal);for(let I of d){let q=ne(I.id);if(q!==void 0)for(let{id:Z}of v.get(q)??[]){let U=x.get(ne(Z)??"");U!==void 0&&(U===I.stamp?r.add(q):U>I.stamp&&a.add(q))}}}return{outside:r,stuck:a,requests:e.reader.calls()-c}}async function ui(e,n,t,o){let s=[...new Set([...e.values()].map(({objectApiName:l})=>l))],i=await Promise.allSettled(s.map(t)),r=new Map([...n.keys()].map(l=>[l.toLowerCase(),l])),a=new Map;for(let[l,w]of i.entries()){if(w.status==="rejected"){if(w.reason instanceof oe)throw w.reason;let p=s[l];o.set(p,je(w.reason));for(let[c,g]of e)g.objectApiName===p&&e.delete(c);continue}for(let p of w.value.childRelationships??[]){let c=r.get(p.childSObject.toLowerCase());if(c===void 0)continue;let g=Le(n.get(c)??[],p.field);if(g===void 0)continue;let f=a.get(c);f||(f=new Set,a.set(c,f)),f.add(g)}}return new Map([...a].map(([l,w])=>[l,[...w]]))}async function gi(e,n){let t=new Set,o=e.find(({objectApiName:i})=>i===he);if(!o||Le(o.fields,hn)===void 0)return t;let s=n.get(he);if(!s||"unread"in s||!s.live)return t;try{for await(let i of ae(s.live.file)){let r=ne(i.AccountId);r!==void 0&&_n(he,i)&&t.add(r)}}catch{return new Set}return t}async function hi(e,n,t,o){if("unread"in t)return{unread:t.unread};let{input:s,previewDir:i,t0s:r,back:a,carriers:l,stranded:w,stuck:p,others:c,personAccounts:g}=e,{folder:f,reader:d,checkpoint:h,signal:R}=s,A=n.objectApiName,L=Xn(A)?e.files:void 0,P=v=>L===void 0||L.anchoredThen(v),B=new Map,C=v=>{let N=B.get(v);return N||(N=new mn(X(i,A,v)),B.set(v,N)),N},F=v=>B.get(v)?.count??0,_=new Jn(e.activeFrom),D=[];try{let v=await Ve.read(f,h.snapshotId,A),N=no(f,A),{gone:V}=o,J=bt(A,h.ignoredFields),Y=Sn(A,n.fields,[]),x=u=>J.has(u.toLowerCase())||V.has(u.toLowerCase()),I=Y.filter(u=>!x(u)).map(On),q=Y.filter(x),Z=A===Mo?Le(n.fields,To):void 0,U=Z!==void 0&&!V.has(Z.toLowerCase())?Z:void 0,de=A===_o?Le(n.fields,$o):void 0,se=de!==void 0&&I.includes(de)?de:void 0,ue=["Id","SystemModstamp",...eo,...I,...U!==void 0&&!I.includes(U)?[U]:[],...se!==void 0?[Qt]:[]],ve=n.cascadeParents.filter(u=>!V.has(u.toLowerCase())),we=(n.restrictParents??[]).filter(u=>!V.has(u.toLowerCase())),re=A===he&&Le(n.fields,hn)!==void 0,Pe=u=>re&&_n(A,u),pe=Ko(n)?"toRecreate":"goneForGood",xe=e.access.heldAs(A)==="parent"?"outOfReach":pe,Ae=r-Bn,te={fields:0,cleared:0,liveNotHeld:0,deletedHeld:0},Ue=u=>{let m=ne(u.Id);if(m===void 0)throw new Error(`${A} answered a record without its Id.`);return{id:String(u.Id),key:m}},me=(u,m,y)=>u.map(j=>ne(m[j])).filter(j=>j!==void 0&&j!==y),Ie=(u,m)=>me(ve,u,m),Ge=(u,m)=>{let y=Oe(u.SystemModstamp);return Ie(u,m).some(j=>a.get(j)?.stamp===y)},on=Date.parse(h.takenAt),De=Date.parse(s.readAt)-Bn,ze=(u,m,y,j)=>{_.add(u);let M=Ie(u,y),T=me(we,u,y),W=j&&Oe(u.CreatedDate)>=on&&Oe(u.LastModifiedDate)<=De;n.undeletable&&M.length+T.length===0||D.push({id:m,parents:M,restricts:T,goesAlong:W,undeletable:n.undeletable})},ge=new Map,sn=e.lookups.get(A)??[];if(sn.length>0&&v.size>0)for await(let u of v.records()){if(Pe(u))continue;let m=ne(u.Id);if(m===void 0)continue;let y=sn.filter(j=>{let M=ne(u[j]);return M!==void 0&&a.has(M)});y.length>0&&ge.set(m,{id:String(u.Id),fields:y})}let qe=async u=>{if(u.length===0)return;if(I.length===0){for(let T of u)T.stamp!==T.held&&await C("touched").add({Id:T.id});return}let m=u.map(T=>T.id),y=new Map,j=await v.chunk(m).batches(h.snapshotId,A,gn);for await(let T of j??[])for(let W of T){let S=ne(W.Id);S!==void 0&&y.set(S,W)}if(R?.aborted)throw new oe;let M=await Vo(d,n,ue,m);for(let T of u){let W=M.get(T.key);if(!W)continue;let S=y.get(T.key);if(!S)throw new Error(`The checkpoint\u2019s snapshot of ${A} does not hold record ${T.id}, which its index names.`);if(U!==void 0&&S[U]!==!0&&W[U]===!0){await C("convertedLead").add({Id:T.id});continue}if(se!==void 0&&W[Qt]===Wo&&!En(S[se],W[se])){await C("activatedContract").add({Id:T.id});continue}let $=I.filter(ee=>!En(S[ee],W[ee]));if($.length>0){te.fields+=$.length;let ee=(T.cleared??[]).filter(K=>$.includes(K)&&Ho(W[K]));ee.length>0&&te.cleared++,await C("giveBack").add({Id:T.id,fields:$,...ee.length>0?{cleared:ee}:{}}),_.add(W)}else Oe(W.SystemModstamp)!==T.held&&await C("touched").add({Id:T.id})}},Ce=[],Be=async u=>{Ce.push(u),Ce.length>=Ye&&(await qe(Ce),Ce=[])};if(t.live)for await(let u of ae(t.live.file)){let{id:m,key:y}=Ue(u),j=Pe(u),M=v.stampOf(m);if(M!==void 0){if(j||!P(m))continue;let W=ge.get(y)?.fields;W&&ge.delete(y);let S=A===Rn&&g.delete(y),$=Oe(u.SystemModstamp);(W||S||$!==M||M>=Ae)&&await Be({id:m,key:y,held:M,stamp:$,...W?{cleared:W}:{}});continue}if(te.liveNotHeld++,j)continue;let T=await N(y)?"broughtBackSince":Oe(u.CreatedDate)>=r?"createdSince":void 0;T===void 0?await C("unexplained").add({Id:m}):L!==void 0&&!L.anchoredNow(m)?await C("outsideAdded").add({Id:m}):(await C(T).add({Id:m}),ze(u,m,y,!0))}for(let[u,m]of ge){let y=v.stampOf(m.id);y!==void 0&&await Be({id:m.id,key:u,held:y,stamp:y,cleared:m.fields})}if(A===Rn)for(let u of g){let m=v.rowOf(u);if(m<0||(g.delete(u),ge.has(u)))continue;let y=v.idAt(m),j=v.stampOf(y);j!==void 0&&await Be({id:y,key:u,held:j,stamp:j})}if(await qe(Ce),t.deleted)for await(let u of ae(t.deleted.file)){let{id:m,key:y}=Ue(u);if(v.retired(m))continue;let j=Pe(u);if(v.has(m)){if(te.deletedHeld++,j)continue;if(!P(m)){await C("outsideDeleted").add({Id:m});continue}let M=w.get(y);c.has(y)?await C("deletedByOther").add({Id:m}):p.has(y)?await C(e.answeredGone.has(y)?xe:pe).add({Id:m}):M!==void 0?await C(M).add({Id:m}):Ge(u,y)?await C("withParent").add({Id:m}):n.undeletable?await C("inBin").add({Id:m}):await C(pe).add({Id:m});continue}if(l.has(y)&&!j){await C("carrier").add({Id:m});continue}if(!(j||await N(y)))if(Oe(u.CreatedDate)<r){let M=w.get(y),T=P(m)?c.has(y)?"deletedByOther":p.has(y)?"goneForGood":M??"deletedWhileTaken":"outsideDeleted";await C(T).add({Id:m})}else Ge(u,y)&&(await C("comesBackWithParent").add({Id:m}),ze(u,m,y,!1))}let Ze=t.count;if(v.size>0&&Ze===void 0)throw new Error(`The org gave no count of the ${A} records it holds.`);if(v.size-((Ze??0)-te.liveNotHeld)-te.deletedHeld>0){let u=new pt(v);if(t.deleted)for await(let M of ae(t.deleted.file))u.mark(M.Id);let[m]=await Te(d,[Rt(A,n.readMode)],(M,T)=>{for(let W of T)u.mark(W.Id)},R);if(!m.read)throw new Error(m.reason);let y=[],j=async()=>{let M=new Set;if(re){let T=await v.chunk(y).batches(h.snapshotId,A,gn);for await(let W of T??[])for(let S of W){let $=ne(S.Id);$!==void 0&&Pe(S)&&M.add($)}}for(let T of y)M.has(T.slice(0,15))||await C(P(T)?xe:"outsideDeleted").add({Id:T});y=[]};for(let M of u.ids())y.push(M),y.length>=Ye&&await j();await j()}for(let u of B.values())await u.flush();let Xe=F("toRecreate"),He=F("goneForGood"),b=F("convertedLead"),E=F("activatedContract"),H=F("deletedWithCreatedParent"),z=F("deletedWithParentOutside"),ke=F("deletedByOther"),un=F("outOfReach"),k=F("carrier");return{told:{diff:{objectApiName:A,toDelete:{createdSince:F("createdSince"),broughtBackSince:F("broughtBackSince"),comesBackWithParent:F("comesBackWithParent")},toGiveBack:{records:F("giveBack"),fields:te.fields,clearedLookups:te.cleared},toBringBack:{inBin:F("inBin"),withParent:F("withParent"),deletedWhileTaken:F("deletedWhileTaken"),...k>0?{carriers:k}:{}},...Xe>0?{toRecreate:Xe}:{},cannotUndo:[...He>0?[{reason:"goneForGood",count:He}]:[],...b>0?[{reason:"convertedLead",count:b}]:[],...E>0?[{reason:"activatedContract",count:E}]:[],...H>0?[{reason:"deletedWithCreatedParent",count:H}]:[],...z>0?[{reason:"deletedWithParentOutside",count:z}]:[],...ke>0?[{reason:"deletedByOther",count:ke}]:[],...un>0?[{reason:"outOfReach",count:un}]:[]],outside:[],touched:F("touched"),unexplained:F("unexplained"),lastChangedBy:_.byUser(),...o.drift?{schemaDrift:o.drift}:{},notCompared:q},people:_,pending:D}}}catch(v){for(let N of B.values())await N.discard();if(v instanceof oe)throw v;return{unread:je(v)}}}async function*oo(e,n){let t=[];for(let o of xo)if(n.diff.toDelete[o]!==0)for await(let s of ae(X(e,n.diff.objectApiName,o)))typeof s.Id=="string"&&(t.push(s.Id),t.length>=Ye&&(yield t,t=[]));t.length>0&&(yield t)}async function wi(e,n,t,o,s){let{input:i,previewDir:r}=e,a=n.diff.objectApiName,w=((await t(a)).childRelationships??[]).filter(P=>P.cascadeDelete===!0&&!s.has(P.childSObject.toLowerCase()));if(w.length===0)return[];let p=await o(),c=w.filter(P=>p.has(P.childSObject));if(c.length===0)return[];let g=new Set(await e.access.unseenOf([...new Set(c.map(({childSObject:P})=>P))])),f=c.filter(({childSObject:P})=>!g.has(P));if(f.length===0)return[];let d=Date.parse(i.checkpoint.takenAt);if(!Number.isFinite(d))throw new Error(`Not a date: ${i.checkpoint.takenAt}`);let h=Ot(Math.ceil(d/Bn)*Bn),R=new Map,A=new Map,L=new Map;for await(let P of oo(r,n)){let B=f;for(;B.length>0;){let C=[];for(let D of B){let v=ye(D.childSObject),N=On(D.field),V=kt(v)==="scanAllLive",J=L.get(v)??"CreatedDate";for(let Y of Me(P))C.push({child:v,field:N,read:{objectApiName:v,soql:`SELECT Id, ${N} FROM ${v} WHERE ${N} IN (${Y}) AND ${J} >= ${h}${V?" AND IsDeleted = false":""}`,scanAll:V}})}let F=await Te(i.reader,C.map(({read:D})=>D),(D,v)=>{let{child:N,field:V}=C[D],J=R.get(N);J||(J={records:new Set,parents:new Set},R.set(N,J));for(let Y of v){let x=ne(Y.Id),I=ne(Y[V]);x!==void 0&&J.records.add(x),I!==void 0&&(J.parents.add(I),A.set(I,String(Y[V])))}},i.signal),_=new Set;F.forEach((D,v)=>{if(D.read)return;let{child:N}=C[v];if(!L.has(N)&&/No such column 'CreatedDate'/.test(D.reason)){_.add(N);return}throw new Error(`The ${D.objectApiName} records its deletion would take along could not be read: `+D.reason)});for(let D of _)L.set(D,"SystemModstamp");B=B.filter(D=>_.has(ye(D.childSObject)))}}if(A.size>0){let P=new mn(X(r,a,"outsideParents"));for(let B of A.values())await P.add({Id:B});await P.flush()}return[...R].filter(([,{records:P}])=>P.size>0).sort(([P],[B])=>P<B?-1:P>B?1:0).map(([P,{records:B,parents:C}])=>({objectApiName:P,count:B.size,parents:C.size}))}async function pi(e,n,t,o){if(e.kind==="org")return;let{objectApiName:s,toDelete:i}=n.diff,r=i.createdSince+i.broughtBackSince;if(r===0)return;let l=((await t(s)).childRelationships??[]).filter(f=>f.cascadeDelete===!0).map(f=>f.childSObject);if(l.length===0)return;let w=await o(),p=[...new Set(l.filter(f=>w.has(f)))].sort(),g=[...p.length>0?await e.unseenOf(p):[]].sort((f,d)=>+!Xt.has(f)-+!Xt.has(d));return g.length>0?{objectApiName:s,children:g,records:r}:void 0}var Xt=new Set(["Event","Task"]);async function mi(e,n){let t=new Set(n.flatMap(({pending:c})=>c.flatMap(({parents:g,restricts:f})=>[...g,...f]))),o=new Set;if(t.size>0)for(let c of n)for await(let g of oo(e,c))for(let f of g){let d=f.slice(0,15);t.has(d)&&o.add(d)}let s=new Map(n.flatMap(({pending:c})=>c.map(g=>[g.id.slice(0,15),g]))),i=c=>c.goesAlong?c.parents.find(g=>o.has(g)):void 0,r=(c,g=new Set)=>{let f=s.get(c),d=f&&!g.has(c)?i(f):void 0;return d===void 0?c:r(d,new Set([...g,c]))},a=new Map,l=(c,g)=>{let f=a.get(c);if(f!==void 0)return f;a.set(c,!1);let d=r(c),h=g.restricts.some(R=>o.has(R)&&r(R)!==d)||g.parents.some(R=>{let A=s.get(R);return A!==void 0&&i(A)!==void 0&&l(R,A)});return a.set(c,h),h},w=[],p=[];for(let{diff:c,pending:g}of n){let f=c.objectApiName,d=C=>i(C)!==void 0&&!l(C.id.slice(0,15),C),h=g.filter(d).length;h>0&&p.push({objectApiName:f,count:h});let R=g.filter(C=>!d(C)),A=R.filter(C=>[...C.parents,...C.restricts].some(F=>o.has(F))),L=new Set(A.map(({id:C})=>C)),P=R.filter(C=>!C.undeletable&&!L.has(C.id));if(P.length+A.length===0)continue;let B=new mn(X(e,f,"undoCannot"));for(let{id:C}of P)await B.add({Id:C});for(let{id:C}of A)await B.add({Id:C,reason:"deletedBeforeParent"});await B.flush(),P.length>0&&w.push({objectApiName:f,count:P.length}),A.length>0&&w.push({objectApiName:f,count:A.length,reason:"deletedBeforeParent"})}return{undoCannot:w,withParentDeleted:p}}async function ki(e,n,t){let o={};if(n.length===0)return o;let s=Me([...n].sort()).map(i=>({objectApiName:"User",soql:`SELECT Id, Name FROM User WHERE Id IN (${i})`,scanAll:!1}));return await Te(e,s,(i,r)=>{for(let a of r)typeof a.Id=="string"&&typeof a.Name=="string"&&(o[a.Id]=a.Name)},t),o}function Yt(e){let{toDelete:n,toGiveBack:t,toBringBack:o}=e;return n.createdSince+n.broughtBackSince+n.comesBackWithParent+t.records+o.inBin+o.withParent+o.deletedWhileTaken+(o.carriers??0)+(e.toRecreate??0)+e.touched+e.unexplained+e.cannotUndo.reduce((s,i)=>s+i.count,0)>0||e.schemaDrift!==void 0}async function yi(e){let n=await e.describe(be),t=dn.safeParse("body"in n?n.body:null);if(!t.success)throw new Error(`The org gave no describe of ${be}.`);return t.data}function io(e){return(n,t)=>X(e,n,t)}async function bi(e,n){let t=n.fileObject.objectApiName,o=n.changes.get(t);if(!(n.unread.has(t)||o===void 0||"unread"in o))try{return{anchors:await Ht({reader:e.reader,folder:e.folder,previewDir:n.previewDir,snapshotId:e.checkpoint.snapshotId,objects:n.ordered,changes:n.changes,linkDescribe:n.linkDescribe,describeGlobal:e.describeGlobal,...e.signal?{signal:e.signal}:{}})}}catch(s){if(s instanceof oe)throw s;return{unread:"The links of its files to the records of the checkpoint could not be read: "+je(s)}}}async function so(e){await Promise.all(["linkAdded","linkRemoved","linkChanged"].map(n=>Zn(Se(e,n),{force:!0})))}async function Oi(e,n){let t=n.fileObject.objectApiName,o=n.outcomes.get(t),s=n.changes.get(t);if(o===void 0||!("told"in o)||s===void 0)return;let i=new Set([...n.outcomes].filter(([,r])=>"told"in r).map(([r])=>r));try{let r=await Vt({anchors:n.anchors,reader:e.reader,folder:e.folder,snapshotId:e.checkpoint.snapshotId,t0s:n.t0s,objects:n.ordered,fileChanges:s,told:i,classFileOf:io(n.previewDir),previewDir:n.previewDir,queryAllFiles:e.checkpoint.takenBy?.queryAllFiles===!0&&e.queryAllFiles!==!1,...e.signal?{signal:e.signal}:{}}),{diff:a,people:l}=o.told;a.toDelete.createdSince+=r.createdSince,a.toBringBack.deletedWhileTaken+=r.deletedWhileTaken;for(let g of r.changedBy)l.add(g);a.lastChangedBy=l.byUser();let w=r.goneForGood,p=r.newFileVersion,c=a.cannotUndo.find(g=>g.reason==="goneForGood");return c!==void 0?c.count+=w:w>0&&a.cannotUndo.unshift({reason:"goneForGood",count:w}),a.cannotUndo.push(...p>0?[{reason:"newFileVersion",count:p}]:[]),r.files}catch(r){if(r instanceof oe)throw r;await Yn(n.previewDir,t),await so(n.previewDir),n.outcomes.set(t,{unread:je(r)});return}}async function Ri(e,n){let t=n.fileObject.objectApiName,o=n.outcomes.get(t);if(o===void 0||!("told"in o))return;let{diff:s}=o.told;if(s.toDelete.createdSince+s.toDelete.broughtBackSince!==0)try{let{links:i,files:r}=await Jt({anchors:n.anchors,reader:e.reader,classFileOf:io(n.previewDir),...e.signal?{signal:e.signal}:{}});if(i===0)return;s.outside=[...s.outside.filter(({objectApiName:a})=>a!==be),{objectApiName:be,count:i,parents:r}].sort((a,l)=>a.objectApiName<l.objectApiName?-1:a.objectApiName>l.objectApiName?1:0)}catch(i){if(i instanceof oe)throw i;await Yn(n.previewDir,t),await so(n.previewDir),n.outcomes.set(t,{unread:je(i)})}}async function Bs(e){let{checkpoint:n,folder:t,reader:o,previewId:s,readAt:i,signal:r}=e,a=Date.parse(n.readFrom);if(!Number.isFinite(a))throw new Error(`Not a date: ${n.readFrom}`);let l=Date.parse(i);if(!Number.isFinite(l))throw new Error(`Not a date: ${i}`);if(r?.aborted)throw new oe;let w=a-(a%1e3+1e3)%1e3,p=gt(t,s);await Cn(p);let c=[...n.objects].sort((b,E)=>b.readOrder-E.readOrder),g=e.access??Vn,f=c.filter(({objectApiName:b})=>!g.notHeld.has(b)),d=new Map,h=n.files!==void 0?f.find(({objectApiName:b})=>Xn(b)):void 0,R=await Ct(o,f.map(({objectApiName:b})=>b),n.readFrom,r),A=new Map(f.map(({objectApiName:b},E)=>[b,R[E]])),L=ii(f,A),P=h!==void 0?yi(o):void 0;P?.catch(()=>{});let B=await Zt(e,L,d),C=B.requests,F=new Map,_=new Set,D=[];for(let b of c){let E=b.objectApiName,H=g.notHeld.get(E);if(H!==void 0){F.set(E,H);continue}let z=A.get(E);if(z===void 0||"unread"in z){F.set(E,z?.unread??"Its newest record was not read.");continue}let ke=B.now.get(E);ke===void 0?(_.add(E),D.push({object:b,fields:{gone:new Set},check:z})):"unread"in ke?F.set(E,ke.unread):D.push({object:b,fields:ke,check:z})}let v=await St(o,D.map(({object:b,fields:E})=>({objectApiName:b.objectApiName,readMode:b.readMode,held:b.records>0,fields:si(b,E.gone)})),n.readFrom,p,r,D.map(({check:b})=>b)),N=new Map(D.map(({object:b},E)=>[b.objectApiName,v[E]])),V=D.filter(({object:b})=>{if(!_.has(b.objectApiName))return!1;let E=N.get(b.objectApiName);return E!==void 0&&!("unread"in E)&&E.count!==void 0&&E.count<b.records});if(V.length>0){let b=await Zt(e,V.map(({object:E})=>E),d);C+=b.requests;for(let E of V){let H=E.object.objectApiName;_.delete(H);let z=b.now.get(H);z===void 0||"unread"in z?F.set(H,z?.unread??"Its describe was not read."):E.fields=z}}let J=new Map,Y=b=>{let E=d.get(b);if(E)return Promise.resolve(E);let H=J.get(b);return H||(H=(async()=>{let z=await o.describe(b),ke=dn.safeParse("body"in z?z.body:null);if(!ke.success)throw new Error(`The org gave no describe of ${b}.`);return ke.data})(),J.set(b,H)),H},{back:x,gone:I}=await ri({input:e,t0s:w},c,N),q=ci(x,g.userKey),Z=new Map([...I,...x]),U=ai(x,I),de=await wt.read(t);for(let b of de.keys())(x.has(b)||I.has(b))&&U.add(b);let se=to([...de.keys()].filter(b=>Z.has(b)),Z);Qn(U,x,I);for(let b of q)x.delete(b),U.delete(b);let ue=di(c,x,I),ve=new Map(D.map(({object:b,fields:E})=>[b.objectApiName,Sn(b.objectApiName,b.fields,n.ignoredFields).filter(H=>!E.gone.has(H.toLowerCase()))])),we=await ui(x,ve,Y,F),re=await li(e,D.map(({object:b})=>b),x,I,ue,Y);for(let b of re.stuck)U.add(b);Qn(U,x,I);for(let b of[...ue])x.has(b)||ue.delete(b);let Pe=fi(x,I,re.outside),pe=0,xe=o.calls(),Ae=h!==void 0&&P!==void 0?await bi(e,{previewDir:p,ordered:c,changes:N,linkDescribe:P,fileObject:h,unread:F}):void 0;pe+=o.calls()-xe;let te=Ae!==void 0&&"anchors"in Ae?Ae.anchors:void 0,Ue={input:e,previewDir:p,t0s:w,activeFrom:l-Go,back:x,carriers:ue,stranded:Pe,stuck:U,answeredGone:se,others:q,access:g,lookups:we,personAccounts:await gi(c,N),...te!==void 0?{files:te}:{}},me=new Map;for(let{object:b,fields:E}of D){if(r?.aborted)throw new oe;let H=F.get(b.objectApiName)??(Ae!==void 0&&"unread"in Ae&&b===h?Ae.unread:void 0),z=N.get(b.objectApiName);me.set(b.objectApiName,H!==void 0||z===void 0?{unread:H??"Its changes were not read."}:await hi(Ue,b,z,E))}let Ie;if(te!==void 0&&h!==void 0){let b=o.calls();Ie=await Oi(e,{anchors:te,fileObject:h,changes:N,outcomes:me,ordered:c,previewDir:p,t0s:w}),pe+=o.calls()-b}let Ge=new Set(c.map(({objectApiName:b})=>b.toLowerCase()));if(n.files!==void 0&&h!==void 0)for(let b of[be,st])Ge.add(b.toLowerCase());let on,De=()=>on??=at({describeGlobal:e.describeGlobal}),ze=[];for(let[b,E]of me){if(!("told"in E))continue;let{toDelete:H}=E.told.diff;if(H.createdSince+H.broughtBackSince!==0)try{E.told.diff.outside=await wi(Ue,E.told,Y,De,Ge);let z=await pi(g,E.told,Y,De);z!==void 0&&ze.push(z)}catch(z){if(z instanceof oe)throw z;await Yn(p,b),me.set(b,{unread:je(z)})}}if(te!==void 0&&h!==void 0){let b=o.calls();await Ri(e,{anchors:te,fileObject:h,outcomes:me,previewDir:p}),pe+=o.calls()-b,"told"in(me.get(h.objectApiName)??{unread:""})||(Ie=void 0)}let ge=c.flatMap(({objectApiName:b})=>{let E=me.get(b);return E&&"told"in E?[E.told]:[]}),{undoCannot:sn,withParentDeleted:qe}=await mi(p,ge),Ce=new Set(ge.map(({diff:b})=>b.objectApiName)),Be=ze.filter(({objectApiName:b})=>Ce.has(b)),Ze=[...new Set(ge.flatMap(({diff:b})=>Object.keys(b.lastChangedBy)))],ln=await ki(o,Ze,r),Xe=new Set(ge.flatMap(({people:b})=>[...b.active])),He=ge.filter(({diff:b})=>_.has(b.objectApiName)&&!Yt(b)).length;return{checkpointId:n.checkpointId,previewId:s,readAt:i,objects:ge.map(({diff:b})=>b).filter(Yt),undoCannot:sn,...qe.length>0?{withParentDeleted:qe}:{},...re.requests>0?{parentsOutsideRequests:re.requests}:{},...C>0?{fieldsRequests:C}:{},described:{first:L.length,later:V.length},...He>0?{fieldsNotChecked:He}:{},...Ie!==void 0?{files:Ie}:{},...h!==void 0?{filesRequests:pe}:{},access:g.diffAccess(),...Be.length>0?{unseen:Be}:{},unread:c.flatMap(({objectApiName:b})=>{let E=me.get(b),H=E&&"unread"in E?E.unread:E?void 0:F.get(b);return H===void 0?[]:[{objectApiName:b,reason:H}]}),userNames:ln,activeLastHour:[...Xe].sort()}}var Ii=1e3,Di=25,Ni=2e3,Re=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ro=["createdSince","broughtBackSince","comesBackWithParent","giveBack","inBin","withParent","deletedWhileTaken","toRecreate","carrier"],ce={createdSince:1,broughtBackSince:2,comesBackWithParent:4,giveBack:8,inBin:16,withParent:32,deletedWhileTaken:64,toRecreate:128,carrier:256},ao=32768,ji={createdSince:ce.createdSince|ce.comesBackWithParent|ce.carrier,broughtBackSince:ce.broughtBackSince|ce.carrier,comesBackWithParent:ce.comesBackWithParent,giveBack:ce.giveBack|ce.inBin|ce.withParent,inBin:ce.inBin,withParent:ce.withParent,deletedWhileTaken:ce.deletedWhileTaken,toRecreate:ce.toRecreate,carrier:ce.carrier},fn=new Set(["createdSince","broughtBackSince"]),We={changedSincePreview:1,changedDuringRewind:2,outsideNotAccepted:4,holdsLeft:8,noUndoNotAccepted:16,beforeParentNotAccepted:32,recreateNotAccepted:64,keyTaken:128,needsUnpickedParent:256,heldByUnpicked:512,contactKept:1024},Li=[{cls:"linkAdded",as:"unlink"},{cls:"linkRemoved",as:"relink"},{cls:"linkChanged",as:"share"}];function Zs(e,n){return[n,e.automatedProcessUserId].filter(t=>typeof t=="string"&&t!=="")}function Xs(e,n){let t=n.length>0?n.join(", "):"child";return`${e}: given back once the ${t} records hanging from it that the rewind deletes were gone, as those records held some of its values in place`}function nn(e){let n=an(e);return n===null?Number.NaN:Date.parse(n)}function ie(e,n){let t=e.Id;if(typeof t!="string"||!Re.test(t))throw new Error(`A line of ${n} names no record: the diff it was read from is not whole.`);return t}async function*G(e){try{for await(let n of ae(e))yield n}catch(n){if(n.code!=="ENOENT")throw n}}function vi(e,n){return Fn(e,`${ye(n)}.beforeParent.ndjson`)}function Bi(e,n){return Fn(e,`${ye(n)}.along.ndjson`)}var tn=class{constructor(n){this.file=n}file;lines=[];written=!1;async add(n){this.lines.push(`${JSON.stringify(n)}
10
- `),this.lines.length>=Ni&&await this.flush()}async flush(){if(this.lines.length===0)return;let n=this.lines.join("");this.lines=[],await Ci(this.file,n,{encoding:"utf8",mode:cn,flag:this.written?"a":"w"}),this.written=!0}},et=class{entries=new Map;add(n,t,o,s,i){let r=`${n}\0${t}\0${s??""}\0${i??""}`,a=this.entries.get(r);a||(a={objectApiName:n,reason:t,...s!==void 0?{by:s}:{},...i!==void 0?{needs:i}:{},count:0,ids:[]},this.entries.set(r,a)),a.count++,a.ids.length<Di&&a.ids.push(o)}all(n){let t=(o,s)=>(o??"")<(s??"")?-1:(o??"")>(s??"")?1:0;return[...this.entries.values()].sort((o,s)=>(n.get(o.objectApiName)??0)-(n.get(s.objectApiName)??0)||t(o.reason,s.reason)||t(o.by,s.by)||t(o.needs,s.needs))}};function co(e,n){if(!(typeof n!="string"||n===""))return e==="SetupOwnerId"&&Re.test(n)?n.slice(0,15):n}async function Fi(e,n,t,o){let s=new Q;if(e.customSetting===void 0)return s;let i=An(e.customSetting).toLowerCase(),r=e.fields.find(w=>w.toLowerCase()===i);if(r===void 0)return s;let a=new Q;for(let w of o){let p=X(t,e.objectApiName,w);for await(let c of G(p))a.add(ie(c,p))}if(a.size===0)return s;let l=new Set;for await(let w of G(_e(n,e.objectApiName))){let p=co(r,w[r]);p!==void 0&&l.add(p)}if(l.size===0)return s;for await(let w of G(wn(n,e.objectApiName))){if(typeof w.Id!="string"||!a.has(w.Id))continue;let p=co(r,w[r]);p!==void 0&&l.has(p)&&s.add(w.Id)}return s}function fo(e){return{objectApiName:e,deleted:0,withParentDeleted:0,undoCannot:0,nextPassDeleted:0,broughtBack:0,backWithParent:0,recreated:0,givenBackFirst:0,givenBackAfter:0,givenBackNextPass:0,skipped:0}}function Ei(e){return Object.entries(e).some(([n,t])=>n!=="objectApiName"&&t!==0)}function lo(e){return`${e.ContentDocumentId.slice(0,15)}:${e.LinkedEntityId.slice(0,15)}`}function uo(e,n,t){let s=(n==="linkChanged"?Pt:Pn).safeParse(e);if(!s.success)throw new Error(`A line of ${t} names no link: the diff it was read from is not whole.`);return s.data}function ho(e){return{unlink:{file:Se(e,"linkAdded"),count:0},relink:{file:Se(e,"linkRemoved"),count:0},share:{file:Se(e,"linkChanged"),count:0}}}async function Mi(e){let n={};for(let{cls:o,as:s}of Li){let i=new Set,r=Se(e.confirmedDir,o);for await(let p of G(r))i.add(lo(uo(p,o,r)));let a=Se(e.freshDir,o),l=new tn(Se(e.dir,o)),w=0;for await(let p of G(a)){let c=uo(p,o,a);if(e.deleted(c.ContentDocumentId)||e.deleted(c.LinkedEntityId))continue;let g=e.pass===2&&o==="linkRemoved"&&(e.earlier(c.ContentDocumentId)||e.earlier(c.LinkedEntityId));if(!i.has(lo(c))&&!g){e.left.add(be,"changedSincePreview",c.Id);continue}await l.add(p),w++}await l.flush(),n[s]={file:l.file,count:w}}let t=ho(e.dir);return{unlink:n.unlink??t.unlink,relink:n.relink??t.relink,share:n.share??t.share}}var Ti=["inBin","withParent","deletedWhileTaken","carrier"],_i=new Set(["id","createdbyid","lastmodifiedbyid","systemmodstamp","createddate","lastmodifieddate"]);function $i(e,n){return e.flatMap(t=>{let o=n[t];return typeof o=="string"&&Re.test(o)?[o.slice(0,15)]:[]})}function go(e,n,t){let o=t===void 0?void 0:new Set(t.map(s=>s.toLowerCase()));return Object.entries(e).flatMap(([s,i])=>{let r=s.toLowerCase();if(_i.has(r)||o!==void 0&&!o.has(r))return[];if(typeof i!="string"||!Re.test(i))return[];let a=i.slice(0,15);return n.has(a)?[{field:s,needs:n.get(a)}]:[]})}async function Wi(e,n,t){let{freshDir:o,heldRows:s}=e,i=new Map,r=new Map;for(let f of n)for(let d of[...Ti,"toRecreate","comesBackWithParent"]){let h=X(o,f.objectApiName,d);for await(let R of G(h)){let A=ie(R,h).slice(0,15);i.set(A,f.objectApiName),r.set(A,d)}}let a=new Map;for(let f of n)if(f.cascadeParents.length!==0)for await(let d of G(wn(o,f.objectApiName))){if(typeof d.Id!="string"||!Re.test(d.Id))continue;let h=d.Id.slice(0,15),R=r.get(h);(R==="withParent"||R==="comesBackWithParent")&&a.set(h,$i(f.cascadeParents,d))}let l=new Set;for(let[f,d]of r)(d==="inBin"||d==="deletedWhileTaken"||d==="carrier")&&t(i.get(f)??"")&&l.add(f);for(let f=l.size>0;f;){f=!1;for(let[d,h]of a)l.has(d)||!h.some(R=>l.has(R))||(l.add(d),f=!0)}let w=(f,d=new Set)=>{let h=i.get(f);if(!(h===void 0||d.has(f))){if(!t(h))return h;d.add(f);for(let R of a.get(f)??[]){if(l.has(R))continue;let A=w(R,d);if(A!==void 0)return A}}},p=new Map,c=new Map;for(let[f,d]of r){if(l.has(f)||d==="comesBackWithParent")continue;let h=i.get(f)??"";if(!t(h))p.set(f,h);else if(d==="withParent"){let R=w(f);c.set(f,R),p.set(f,R)}}let g=new Map;if(s===void 0)return{comes:l,left:c,fields:g};for(let f of[...n].reverse()){let d=f.objectApiName;if(!t(d))continue;let h=new Set(f.cascadeParents.map(B=>B.toLowerCase())),R=[],A=X(o,d,"toRecreate");for await(let B of G(A))R.push(ie(B,A));if(R.length>0)for await(let B of s(d,R)){if(typeof B.Id!="string"||!Re.test(B.Id))continue;let C=B.Id.slice(0,15),F=go(B,p,void 0);if(F.length===0)continue;let _=F.find(({field:D})=>h.has(D.toLowerCase()));_!==void 0?(c.set(C,_.needs),p.set(C,_.needs)):g.set(C,{fields:F.map(({field:D})=>D),needs:F[0].needs})}let L=new Map,P=X(o,d,"giveBack");for await(let B of G(P)){let C=ie(B,P),F=Array.isArray(B.fields)?B.fields.filter(_=>typeof _=="string"):void 0;L.set(C.slice(0,15),{id:C,differ:F})}for(let B of["inBin","withParent"]){let C=X(o,d,B);for await(let F of G(C)){let _=ie(F,C);l.has(_.slice(0,15))&&L.set(_.slice(0,15),{id:_,differ:void 0})}}if(L.size!==0)for await(let B of s(d,[...L.values()].map(({id:C})=>C))){if(typeof B.Id!="string"||!Re.test(B.Id))continue;let C=B.Id.slice(0,15),F=L.get(C);if(F===void 0)continue;let _=go(B,p,F.differ);_.length>0&&g.set(C,{fields:_.map(({field:D})=>D),needs:_[0].needs})}}return{comes:l,left:c,fields:g}}function xi(e,n){let t=n!==void 0?` Rewind ${n} with it to put it back.`:"",o=n??"an object this rewind was not limited to";switch(e){case"needsUnpickedParent":return`Left: it comes back only with a parent this rewind leaves deleted, or a lookup of it names a record this rewind leaves deleted (${o}), which the org refuses to point at.${t}`;case"heldByUnpicked":return`Given back but for the values records of ${o} created since hold in place: this rewind leaves them, so the org refuses to change those values.${t}`;case"outsideNotAccepted":return`Kept: records of ${o} created since hang from it, which its deletion would take along, and deleting them was not accepted.${t}`;case"contactKept":return`Kept: the relation of a contact made since to its own account, which Salesforce deletes only with the contact, and this rewind leaves the contact (${o}).${t}`;default:return`Kept: records of ${o} this rewind leaves as they are hang from it, and its deletion would take them along.${t}`}}async function Ui(e){let{checkpoint:n,pass:t,confirmedDir:o,freshDir:s,dir:i,signal:r}=e,a=Date.parse(n.takenAt);if(!Number.isFinite(a))throw new Error(`Not a date: ${n.takenAt}`);let l=Date.parse(e.readAt);if(!Number.isFinite(l))throw new Error(`Not a date: ${e.readAt}`);let w=l-Ii;if(await Cn(i),(await Si(i)).length>0)throw new Error(`A rewind's plan is written to a folder of its own: ${i} is not empty.`);let p=()=>{if(r?.aborted)throw new oe},c=[...n.objects].map(yt).sort((k,O)=>k.readOrder-O.readOrder),g=new Map(c.map(({objectApiName:k},O)=>[k,O])),f=new Map(c.map(({objectApiName:k})=>[k,fo(k)])),d=k=>f.get(k)??fo(k),h=new Set(e.ownWriters.map(k=>k.slice(0,15))),R=new Map(Object.entries(e.removalStamps??{}).map(([k,O])=>[k.slice(0,15),nn(O)])),A=k=>wo(k,w,h,R),L=(k,O)=>k.flatMap(u=>{let m=O[u];return typeof m=="string"&&Re.test(m)?[m]:[]}),P=(k,O)=>L(k.cascadeParents,O),B=(k,O)=>L(k.restrictParents??[],O),C=new et,F=k=>e.objects===void 0||e.objects.has(k),_=e.objects!==void 0?await Wi(e,c,F):void 0,D=new Map,v=new Map,N=new tn(Fn(i,"leftFields.ndjson")),V=0,J=(k,O,u,m)=>{if(C.add(k,O,u,void 0,m),D.set(u.slice(0,15),xi(O,m)),m===void 0)return;let y=v.get(m);y||(y=new Q,v.set(m,y)),y.add(u)},Y=new Q,x=new Q,I=new Q,q=new Q,Z=new Q,U=new Q,de=[];for(let k of c){p();let O=k.objectApiName,u=F(O),m=(g.get(O)??0)+1,y=d(O),j=new Q;for(let S of ro){let $=X(o,O,S);for await(let ee of G($))j.add(ie(ee,$),ce[S])}let M=t===2?await Vi(s,O,w,h,R,de):void 0,T=new Map,W=S=>{let $=T.get(S);return $||($=new tn(X(i,O,S)),T.set(S,$)),$};for(let S of ro){if(!u&&S!=="comesBackWithParent"&&S!=="createdSince")continue;let $=X(s,O,S);for await(let ee of G($)){let K=ie(ee,$),rn=(j.flagsOf(K)&ji[S])!==0;if(!u&&!(t===2?rn:S==="comesBackWithParent"&&rn&&_?.comes.has(K.slice(0,15))))continue;rn&&j.add(K,ao),rn&&fn.has(S)&&(j.flagsOf(K)&ce.carrier)!==0&&U.add(K);let Ne=M?.other.flagsOf(K)??0,kn=u&&M?.own.has(K)===!0;if(Ne>0||!(rn||kn)){let fe=Ne>0?"changedDuringRewind":"changedSincePreview";C.add(O,fe,K,Ne>0?de[Ne-1]:void 0),fn.has(S)&&I.add(K,We[fe]);continue}if(_!==void 0&&u){let fe=K.slice(0,15);if(S==="comesBackWithParent"&&!_.comes.has(fe))continue;if((S==="withParent"||S==="toRecreate")&&_.left.has(fe)){J(O,"needsUnpickedParent",K,_.left.get(fe));continue}let Fe=_.fields.get(fe);if(Fe!==void 0&&(S==="giveBack"||S==="toRecreate"||S==="inBin"||S==="withParent")){J(O,"needsUnpickedParent",K,Fe.needs),await N.add({Id:K,fields:Fe.fields}),V++;let Ke=Array.isArray(ee.fields)?ee.fields:[],Ee=Ke.filter(nt=>typeof nt=="string"&&!Fe.fields.some(po=>po.toLowerCase()===nt.toLowerCase()));if(S==="giveBack"&&Ke.length>0&&Ee.length===0)continue}}if(S==="toRecreate"&&!e.acceptRecreate){C.add(O,"recreateNotAccepted",K);continue}await W(S).add(S==="giveBack"?ee:{Id:K}),S==="giveBack"&&_!==void 0&&Y.add(K,m),fn.has(S)?x.add(K,m):S==="comesBackWithParent"?(q.add(K),y.nextPassDeleted++):S==="carrier"?(q.add(K),Z.add(K),y.carriers=(y.carriers??0)+1,y.nextPassDeleted++):S==="inBin"||S==="deletedWhileTaken"?y.broughtBack++:S==="withParent"?y.backWithParent++:S==="toRecreate"&&y.recreated++,(S==="inBin"||S==="withParent")&&await W("giveBack").add({Id:K})}}for(let S of T.values())await S.flush();y.skipped=u?j.count(S=>(S&ao)===0):0}await N.flush();let se=new Map,ue=new Q;if(_!==void 0){let k=new Q;for(let O of c){let u=O.objectApiName;if(F(u)||O.cascadeParents.length===0)continue;let m=new Q;for(let y of fn){let j=X(s,u,y);for await(let M of G(j))m.add(ie(M,j))}for await(let y of G(_e(s,u))){if(typeof y.Id!="string"||!Re.test(y.Id)||x.has(y.Id))continue;let j=m.has(y.Id),M=j&&nn(y.CreatedDate)>=a&&nn(y.LastModifiedDate)<=w;M&&e.acceptOutside&&ue.add(y.Id);for(let T of P(O,y)){let W=x.flagsOf(T);if(W>0){if(I.has(T)||M&&e.acceptOutside)continue;let $=c[W-1].objectApiName;se.set(T.slice(0,15),u),M?(I.add(T,We.outsideNotAccepted),J($,"outsideNotAccepted",T,u)):I.add(T,We.holdsLeft);continue}let S=Y.flagsOf(T);j&&S>0&&k.add(T)&&J(c[S-1].objectApiName,"heldByUnpicked",T,u)}}}}if(n.scope.mode==="picked"&&!e.acceptOutside)for(let k of c){let O=X(s,k.objectApiName,"outsideParents");for await(let u of G(O)){let m=ie(u,O);!x.has(m)||I.has(m)||U.has(m)||(I.add(m,We.outsideNotAccepted),C.add(k.objectApiName,"outsideNotAccepted",m))}}let ve=c.map(k=>({object:k,file:_e(s,k.objectApiName)}));for(let k=I.size>0;k;){p(),k=!1;for(let{object:O,file:u}of ve)for await(let m of G(u)){if(!I.has(m.Id))continue;let y=se.get(String(m.Id).slice(0,15));for(let j of P(O,m))!x.has(j)||I.has(j)||(I.add(j,We.holdsLeft),y!==void 0&&se.set(j.slice(0,15),y),k=!0)}}for(let{object:k,file:O}of ve)for await(let u of G(O))if(x.has(u.Id)&&I.flagsOf(u.Id)===We.holdsLeft){let m=ie(u,O),y=se.get(m.slice(0,15));y!==void 0?J(k.objectApiName,"holdsLeft",m,y):C.add(k.objectApiName,"holdsLeft",m)}let we=new Q,re=k=>x.has(k)&&!I.has(k),Pe=new Map,pe=k=>{let O=k.slice(0,15);return Pe.get(O)??O},xe=new Q,Ae=[...c].reverse(),te=[],Ue=[],me=async()=>{let k=new Q;for(let u of fn){let m=X(s,he,u);for await(let y of G(m))k.add(ie(y,m))}let O=new Map;if(k.size===0)return O;for await(let u of G(_e(s,he))){let m=typeof u.Id=="string"?u.Id:"";if(!k.has(m)||re(m)||we.has(m))continue;let y=u.AccountId;typeof y=="string"&&Re.test(y)&&O.set(m.slice(0,15),y.slice(0,15))}return O};for(let k of Ae){p();let O=k.objectApiName,u=_e(s,O),m=new tn(vi(i,O)),y=new tn(Bi(i,O)),j=0,M=0,T=_!==void 0&&!F(O),W=O===ot?await me():void 0;for await(let S of G(u)){let $=typeof S.Id=="string"?S.Id:"";if(!re($)){if(T&&ue.has($)){let fe=P(k,S).filter(Ee=>re(Ee)||we.has(Ee));if(fe.length===0)continue;let Fe=pe(fe[0]);if(fe.some(Ee=>xe.has(Ee))||B(k,S).some(Ee=>re(Ee)&&pe(Ee)!==Fe))continue;we.add($),Pe.set($.slice(0,15),Fe),d(O).withParentDeleted++,await y.add({Id:$,parent:Fe}),M++}continue}let ee=nn(S.LastModifiedDate),K=P(k,S).filter(re);if(K.length>0&&nn(S.CreatedDate)>=a&&(ee<=w||ee<=(R.get($.slice(0,15))??Number.NaN))){let fe=pe(K[0]);if(!(K.some(Ke=>xe.has(Ke))||B(k,S).some(Ke=>re(Ke)&&pe(Ke)!==fe))){we.add($),Pe.set($.slice(0,15),fe),d(O).withParentDeleted++,await y.add({Id:$,parent:fe}),M++;continue}xe.add($)}let Ne=[...P(k,S),...B(k,S)].filter(re);if(Ne.length===0&&W!==void 0&&Ki(S,W)){I.add($,We.contactKept),_!==void 0&&!F(he)?J(O,"contactKept",$,he):C.add(O,"contactKept",$);continue}if(k.undeletable&&Ne.length===0)continue;let kn=Ne.length>0?"beforeParentNotAccepted":"noUndoNotAccepted";e.acceptNoUndo?(d(O).undoCannot++,Ne.length>0&&(await m.add({Id:$,parents:Ne}),j++)):(I.add($,We[kn]),C.add(O,kn,$))}await m.flush(),j>0&&te.push({objectApiName:O,count:j,file:m.file}),await y.flush(),M>0&&Ue.push({objectApiName:O,count:M,file:y.file})}let Ie=new Je(`${i}/deletes`),Ge=new Je(`${i}/along-to-draft`),on={},De=new Q,ze=0;for(let k of c){p();let O=k.objectApiName,u=_e(s,O),m=0;for await(let y of G(u)){let j=typeof y.Id=="string"?y.Id:"";if(x.has(j)&&(ze++,!I.has(j))){for(let M of P(k,y))De.has(M)||De.add(M,(g.get(O)??0)+1);if(we.has(j)){ct([O]).length>0&&await Ge.add(O,j);continue}await Ie.add(O,j),m++,t===2&&A(y)&&typeof y.LastModifiedDate=="string"&&(on[j]=y.LastModifiedDate)}}d(O).deleted=m}if(ze!==x.size)throw new Error("The fresh diff's reads do not hold every record its classes name to delete.");let ge=await Tn.of(Ie),sn=await Tn.of(Ge),qe=new Q;if(t===1&&q.size>0){for(let k of c)for await(let O of G(wn(s,k.objectApiName)))if(q.has(O.Id))for(let u of P(k,O))qe.add(u)}let Ce=new Map;for(let k of c){let O=await Fi(k,s,i,["inBin","deletedWhileTaken"]);if(O.size===0)continue;Ce.set(k.objectApiName,O);let u=d(k.objectApiName);u.broughtBack-=O.size,u.keyTaken=O.size;for(let m of["inBin","deletedWhileTaken"]){let y=X(i,k.objectApiName,m);for await(let j of G(y)){let M=ie(j,y);O.has(M)&&C.add(k.objectApiName,"keyTaken",M)}}}let Be=new Je(`${i}/giveBackFirst`),Ze=new Je(`${i}/giveBackAfter`),ln=[];for(let k of c){p();let O=k.objectApiName,u=X(i,O,"giveBack"),m=!1;for await(let W of G(u))if(De.has(W.Id)){m=!0;break}let y=new Q;if(m)for await(let W of G(_e(s,O)))De.has(W.Id)&&P(k,W).some(re)&&y.add(String(W.Id));let j=d(O),M=new Set,T=Ce.get(O);for await(let W of G(u)){let S=ie(W,u);if(T?.has(S)===!0)continue;let $=De.flagsOf(S),ee=y.has(S);if($>0){if(await Ze.add(O,S),j.givenBackAfter++,M.add(c[$-1].objectApiName),!ee)continue}else if(!ee&&qe.has(S)){j.givenBackNextPass++;continue}await Be.add(O,S),j.givenBackFirst++}M.size>0&&ln.push({objectApiName:O,by:[...M]})}let Xe=new Je(`${i}/bringBack`),He=new Je(`${i}/recreate`);for(let k of Ae){let O=Ce.get(k.objectApiName);for(let m of["carrier","inBin","deletedWhileTaken"]){let y=X(i,k.objectApiName,m);for await(let j of G(y)){let M=ie(j,y);O?.has(M)!==!0&&await Xe.add(k.objectApiName,M)}}let u=X(i,k.objectApiName,"toRecreate");for await(let m of G(u))await He.add(k.objectApiName,ie(m,u))}let b=new Q;if(t===2)for(let k of c)for(let O of["inBin","withParent","deletedWhileTaken","carrier","toRecreate"]){let u=X(o,k.objectApiName,O);for await(let m of G(u))b.add(ie(m,u))}let E=n.files===void 0||!F(le)?ho(i):await Mi({confirmedDir:o,freshDir:s,dir:i,pass:t,deleted:k=>Re.test(k)&&re(k),earlier:k=>Re.test(k)&&(b.has(k)||b.has(e.recreated?.originalOf(k.slice(0,15))??k)),left:C}),H=new Je(`${i}/unlinkFrom`);for(let k of fn){let O=X(i,le,k);for await(let u of G(O)){let m=ie(u,O);(I.flagsOf(m)&We.outsideNotAccepted)!==0&&await H.add(le,m)}}let z={...e.removalStamps,...on},ke=Object.keys(z).length>0,un=c.map(({objectApiName:k})=>d(k)).filter(Ei);return{pass:t,dir:i,deletes:ge,removal:{runStartedAt:new Date(a),runEndedAt:new Date(w),includeChanged:!1,...ke?{removalStamps:z}:{},...e.removalSpans&&e.removalSpans.length>0?{removalSpans:[...e.removalSpans]}:{}},bringBack:await Xe.finish(),carriers:Z,goesAlong:we,along:Ue.reverse(),alongToDraft:sn,recreate:await He.finish(),giveBack:{beforeDeletes:await Be.finish(),afterDeletes:await Ze.finish(),heldBy:ln},restore:{changedAfter:e.readAt,ownWriters:[...e.ownWriters],includeChanged:!1,...ke?{stamps:z}:{}},objects:un,undoCannot:un.filter(k=>k.undoCannot>0).map(({objectApiName:k,undoCannot:O})=>({objectApiName:k,count:O})),beforeParent:te.reverse(),left:C.all(g),links:{...E,unlinkFrom:await H.finish()},..._!==void 0?{limited:{objects:c.map(({objectApiName:k})=>k).filter(F),needs:[...v].sort(([k],[O])=>(g.get(k)??0)-(g.get(O)??0)).map(([k,O])=>({objectApiName:k,records:O.size})),why:D,leftFields:{file:N.file,count:V}}}:{}}}function Ys(e,n){if(n===void 0)return e;let t=i=>i.filter(r=>n.has(r.objectApiName)),{files:o,...s}=e;return{...s,objects:t(e.objects),undoCannot:t(e.undoCannot),unread:t(e.unread),...e.withParentDeleted?{withParentDeleted:t(e.withParentDeleted)}:{},...e.unseen?{unseen:t(e.unseen)}:{},...o!==void 0&&n.has(le)?{files:o}:{}}}var Gi=200;function er(e,n){return async function*(t,o){if(o.length===0)return;let s=await Ve.read(n,e.snapshotId,t);for(let i=0;i<o.length;i+=Ye){let r=await s.chunk(o.slice(i,i+Ye)).batches(e.snapshotId,t,Gi);for await(let a of r??[])yield*a}}}var zi=new Set(["needsUnpickedParent","heldByUnpicked","outsideNotAccepted","holdsLeft","contactKept","keyTaken"]);async function qi(e,n){let t=0;for await(let o of G(X(e,n,"giveBack")))Array.isArray(o.fields)&&t++;return t}async function Hi(e){let n=new Set(e.limited?.objects??e.objects.map(i=>i.objectApiName)),t=[];for(let i of e.objects){let r={objectApiName:i.objectApiName,picked:n.has(i.objectApiName),toDelete:i.deleted+i.withParentDeleted+i.nextPassDeleted-(i.carriers??0),...i.withParentDeleted>0?{withParent:i.withParentDeleted}:{},toGiveBack:await qi(e.dir,i.objectApiName),toBringBack:i.broughtBack+i.backWithParent,toRecreate:i.recreated};r.toDelete+r.toGiveBack+r.toBringBack+r.toRecreate>0&&t.push(r)}let o=new Map;for(let i of e.left){if(!n.has(i.objectApiName)||!zi.has(i.reason))continue;let r=`${i.objectApiName}\0${i.reason}`,a=o.get(r);a?a.count+=i.count:o.set(r,{objectApiName:i.objectApiName,reason:i.reason,count:i.count})}let s=e.undoCannot.flatMap(({objectApiName:i,count:r})=>{let a=e.beforeParent.find(w=>w.objectApiName===i),l=r-(a?.count??0);return[...l>0?[{objectApiName:i,count:l}]:[],...a!==void 0&&a.count>0?[{objectApiName:i,count:a.count,reason:"deletedBeforeParent"}]:[]]});return{objects:[...n],acts:t,left:[...o.values()],needs:e.limited?.needs??[],undoCannot:s}}async function nr(e){let n=Fn(e.previewDir,`selection-${Ai(4).toString("hex")}`);try{let t=await Ui({checkpoint:e.checkpoint,pass:1,confirmedDir:e.previewDir,freshDir:e.previewDir,readAt:e.readAt,ownWriters:[],acceptOutside:e.acceptOutside,acceptNoUndo:!0,acceptRecreate:!0,...e.objects?{objects:e.objects}:{},...e.heldRows?{heldRows:e.heldRows}:{},dir:n,...e.signal?{signal:e.signal}:{}});return await Hi(t)}finally{await Pi(n,{recursive:!0,force:!0})}}function Ki(e,n){let{ContactId:t,AccountId:o}=e;if(typeof t!="string"||typeof o!="string")return!1;let s=n.get(t.slice(0,15));return s!==void 0&&s===o.slice(0,15)}function wo(e,n,t,o){let s=nn(e.LastModifiedDate);if(!(s>n))return!1;let i=typeof e.Id=="string"?e.Id:"",r=typeof e.LastModifiedById=="string"?e.LastModifiedById:"";return s<=(o.get(i.slice(0,15))??Number.NaN)||t.has(r.slice(0,15))}async function Vi(e,n,t,o,s,i){let r={own:new Q,other:new Q};for(let a of[_e(e,n),wn(e,n)])for await(let l of G(a)){if(!(nn(l.LastModifiedDate)>t))continue;let p=ie(l,a);if(wo(l,t,o,s)){r.own.add(p);continue}let c=typeof l.LastModifiedById=="string"?l.LastModifiedById:"",g=i.indexOf(c);g<0&&(i.push(c),g=i.length-1),r.other.add(p,g+1)}return r}export{Vn as a,ls as b,X as c,Ko as d,Bs as e,Zs as f,Xs as g,Ui as h,Ys as i,er as j,Hi as k,nr as l};
@@ -1,7 +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{c as E}from"./chunk-BWWQXU2B.mjs";import{b as S}from"./chunk-T63U4OZJ.mjs";import{h as N}from"./chunk-TZE3Y7IQ.mjs";import{b as h,e as m,k as y,l as b}from"./chunk-WZQEK4WT.mjs";var z={kind:"master"};function w(i){return i.available&&i.active&&!i.master}function B(i){let t=i.find(n=>n.defaultRecordTypeMapping);if(t&&w(t))return{kind:"given",info:t,basis:"userDefault"};let e=i.filter(w);return e.length===1?{kind:"given",info:e[0],basis:"onlyOneOpen"}:z}function ie(i){if(i.kind!=="master")return{developerName:i.info.developerName,label:i.info.name,basis:i.basis}}var L=200,j=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/;function se(i,t){let e=t.filter(n=>j.test(n)).slice(0,L).map(n=>`'${n}'`);return`SELECT RecordTypeId, COUNT(Id) n FROM ${N(i)} WHERE Id IN (${e.join(", ")}) GROUP BY RecordTypeId`}var U=b({RecordTypeId:h().nullish(),n:m().int().nonnegative()});function oe(i,t){let e=y(U).safeParse(i);if(!e.success)return{read:0,types:[],unread:"the org answered rows that name no record type count"};let n=new Map;for(let{RecordTypeId:s,n:o}of e.data){let a=K(s??null,t),d=n.get(a.developerName);d?d.rows+=o:n.set(a.developerName,{...a,rows:o})}let r=[...n.values()].sort((s,o)=>o.rows-s.rows);return{read:r.reduce((s,o)=>s+o.rows,0),types:r}}function K(i,t){if(i===null||E(i)){let n=t.find(r=>r.master);return{developerName:n?.developerName??"Master",label:n?.name??"Master"}}let e=t.find(n=>n.recordTypeId.slice(0,15)===i.slice(0,15));return e?{developerName:e.developerName,label:e.name}:{developerName:i,label:i}}function ae(i){if(!i)return;let t=B(i);return t.kind==="given"?t.info.recordTypeId:i.find(e=>e.master)?.recordTypeId}function fe(i){if(typeof i!="object"||i===null)return!1;let{errorCode:t,name:e}=i;return t==="NOT_FOUND"||e==="NOT_FOUND"}import{createHash as R,createHmac as T}from"node:crypto";var p="SANDFORGE_FROZEN_SALT",me=["keep","clear","firstName","lastName","companyName","phoneE164","email","registrationSIV","contractNumber","postalCodeGeneralize","dateMonthStart","dateShift","geoRound1","kmRound10"],f=class extends Error{constructor(){super(`No pseudonymization salt. In VS Code, the first extraction makes one and keeps it in the editor's secret storage, which could not keep it here. On the command line, give it with --salt-file <file>, or set ${p} (bash or zsh: export ${p}="<salt>"; PowerShell: $env:${p} = "<salt>") and start VS Code from that shell. Use the salt the dataset was built with: another one gives the same records other pseudonyms.`),this.name="MissingSaltError"}},V=["Alix","Camille","Dominique","\xC9loi","Faustine","Gabin","H\xE9lo\xEFse","Ibrahim","Jasmine","Kylian","L\xE9a","Mathis","Nour","Oc\xE9ane","Paul","Quitterie","Rayan","Salom\xE9","Th\xE9o","Ursule","Victor","Wendy","Xavier","Yasmine","Zacharie","Ambre","Bastien","Chlo\xE9","Dorian","Emma","Fabien","Gabrielle","Hugo","In\xE8s","Jules","Klara","Louis","Manon","No\xE9","Oph\xE9lie"],H=["Arnaud","Berthelot","Chevallier","Deschamps","Etcheverry","Fontaine","Guibert","Hamonic","Imbert","Jacquin","Kermarrec","Lefebvre","Mignard","Noirot","Ollivier","Perrin","Quentin","Rochefort","Seguin","Thibault","Uberti","Vasseur","Wagner","Xuereb","Yverneau","Zimmermann","Aubry","Barbier","Charpentier","Delattre","Esnault","Fournier","Gosselin","Hervieux","Leloup","Marchand","Navarro","Pasquier","Renard","Sauvage"],v=["Aster","Boreal","C\xE9drat","Delta","Ellipse","Fulmen","Granit","Halcyon","Isatis","Jaspe","Kelvin","Lumen","M\xE9ridien","Noroit","Obsidienne","Pulsar"],k=["Conseil","Services","Industries","Solutions","Groupe","SAS","Partenaires","Logistique"],$="ABCDEFGHJKLMNPRSTUVWXYZ",x=/^(\d{4})-(\d{2})-(\d{2})$/,A=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{1,3})?(Z|[+-]\d{2}:?\d{2})$/;function Z(i){return Date.parse(i.replace(/([+-]\d{2})(\d{2})$/,"$1:$2"))}var D=864e5,u=class{salt;constructor(t){if(!t)throw new f;this.salt=t}get saltFingerprint(){return R("sha256").update(this.salt).digest("hex").slice(0,12)}get dateShiftDays(){return 200+R("sha256").update(`${this.salt}|dateShift-offset`).digest().readUInt32BE(0)%201}pseudonymize(t,e){if(e==null)return e;switch(t){case"keep":return e;case"clear":return"";case"firstName":return this.pick(t,String(e),V);case"lastName":return this.pick(t,String(e),H);case"companyName":return this.companyName(String(e));case"phoneE164":return this.phoneE164(String(e));case"email":return this.email(String(e));case"registrationSIV":return this.registrationSIV(String(e));case"contractNumber":return this.contractNumber(String(e));case"postalCodeGeneralize":return this.postalCodeGeneralize(String(e));case"dateMonthStart":return this.dateMonthStart(String(e));case"dateShift":return this.dateShift(e);case"geoRound1":return this.roundNumber(e,1);case"kmRound10":return this.roundTo(e,10)}}digest(t,e){return T("sha256",this.salt).update(`${t}|${e}`).digest()}*bytes(t,e){let n=this.digest(t,e),r=0;for(;;){for(let s of n)yield s;r+=1,n=T("sha256",this.salt).update(`${t}|${e}|#${r}`).digest()}}pick(t,e,n){let r=this.digest(t,e);return n[r.readUInt32BE(0)%n.length]}companyName(t){let e=this.digest("companyName",t),n=v[e.readUInt32BE(0)%v.length],r=k[e.readUInt32BE(4)%k.length];return`${n} ${r}`}phoneE164(t){let e=this.bytes("phoneE164",t),n="";for(let r=0;r<4;r++)n+=String(e.next().value%10);return`+3363998${n}`}email(t){return`user-${this.digest("email",t).subarray(0,4).toString("hex")}@example.invalid`}registrationSIV(t){let e=this.bytes("registrationSIV",t),n=()=>$[e.next().value%$.length],r=()=>String(e.next().value%10);return`${n()}${n()}-${r()}${r()}${r()}-${n()}${n()}`}contractNumber(t){let e=this.bytes("contractNumber",t),n="";for(let r of t)r>="0"&&r<="9"?n+=String(e.next().value%10):r>="A"&&r<="Z"?n+=String.fromCharCode(65+e.next().value%26):r>="a"&&r<="z"?n+=String.fromCharCode(97+e.next().value%26):n+=r;return n}postalCodeGeneralize(t){let e=t.trim();if(e.length<=2)return e;if(/^\d+$/.test(e))return e.slice(0,2)+"0".repeat(e.length-2);let n=e.slice(0,2);for(let r of e.slice(2))r>="0"&&r<="9"?n+="0":r>="A"&&r<="Z"||r>="a"&&r<="z"?n+="X":n+=r;return n}dateMonthStart(t){let e=x.exec(t)??A.exec(t);return e?`${e[1]}-${e[2]}-01`:""}dateShift(t){if(typeof t=="string"&&x.test(t))return new Date(Date.parse(`${t}T00:00:00Z`)-this.dateShiftDays*D).toISOString().slice(0,10);if(typeof t=="string"&&A.test(t)){let e=Z(t);if(Number.isFinite(e))return new Date(e-this.dateShiftDays*D).toISOString()}return""}roundNumber(t,e){let n=typeof t=="number"?t:Number(String(t).trim());if(!Number.isFinite(n))return"";let r=10**e,s=Math.round(n*r)/r;return typeof t=="number"?s:String(s)}roundTo(t,e){let n=typeof t=="number"?t:Number(String(t).trim());if(!Number.isFinite(n))return"";let r=Math.round(n/e)*e;return typeof t=="number"?r:String(r)}};import{createHash as Y,randomBytes as X}from"node:crypto";var G=80,W=40,F=1e4,q=64,I=".invalid",g=/\.invalid$/i,C=/[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+/g,J=/\+?(?<!\d)\d(?:[\s.()/-]{0,2}\d){6,}/g;function M(i){return/^(?:(?:00)?330?|0)63998\d{4}$/.test(i.replace(/\D/g,""))}function O(i){return`+3363998${i.replace(/\D/g,"").slice(-4)}`}var Q=/^[\d\s.()/+-]+$/;function _(i,t){if(!Q.test(i))return null;let e=t.slice(3),n=/^[\s(]*\+/.test(i)?[`33${e}`,`330${e}`]:[`0${e}`,`33${e}`,`330${e}`,`0033${e}`,`00330${e}`],r=i.replace(/\D/g,"").length,s=n.find(a=>a.length===r);if(s===void 0)return null;let o=0;return i.replace(/\d/g,()=>s[o++])}function ee(i,t={}){let e=[];for(let n of i){let r=(n.type??"").toLowerCase(),s=S(n.name,r);if(!s)continue;let o=r==="email"||r==="phone",a=r==="email"?G:r==="phone"?W:0,d=n.length!==void 0&&n.length>0?n.length:a;e.push({name:t[n.name]??n.name,kind:s,typed:o,...d>0?{maxLength:d}:{},...n.externalId===!0?{key:!0}:{}})}return e}var P=class{pseudonymizer;upsertKeys;drawnFor=new Map;taken=new Set;exhausted=0;counted=new Map;constructor(t=X(32).toString("hex"),e={}){this.pseudonymizer=new u(t),this.upsertKeys=e.upsertKeys===!0}forObject(t,e,n={}){let r=ee(e,n);if(r.length!==0)return s=>{for(let o of r){let a=s[o.name];if(typeof a!="string")continue;let d=this.neutralize(o,a);d!==a&&(d===null?delete s[o.name]:s[o.name]=d,this.count(t,o))}}}email(t,e=G,n=!1){let r=t.trim();if(r===""||g.test(r))return t;let s=`${r}${I}`;if(s.length<=e)return s;let o=this.shortAddress(r,n);return o.length<=e?o:null}phone(t,e){return/\d/.test(t)?M(t)?(this.taken.add(O(t)),t):this.fictional(t,e):t}report(){let t=[],e=0;for(let[n,r]of this.counted)for(let[s,{kind:o,values:a}]of r)t.push({objectApiName:n,field:s,kind:o,values:a}),e+=a;return{neutralized:!0,fields:t,values:e,...this.exhausted>0?{numbersExhausted:this.exhausted}:{}}}neutralize(t,e){let n=this.upsertKeys&&t.key===!0;return t.typed?t.kind==="email"?this.email(e,t.maxLength,n):this.phone(e,t.maxLength):t.kind==="email"?this.addressesIn(e,t.maxLength,n):this.numbersIn(e,t.maxLength)}addressesIn(t,e,n=!1){let r=a=>e===void 0||a.length<=e,s=t.replace(C,a=>g.test(a)?a:`${a}${I}`);if(s===t||r(s))return s;let o=t.replace(C,a=>g.test(a)?a:this.shortAddress(a,n));return r(o)?o:null}numbersIn(t,e){let n=d=>e===void 0||d.length<=e,r=!1,s=d=>t.replace(J,c=>{if(M(c))return this.taken.add(O(c)),c;let l=this.drawnNumber(c);return l===null?(r=!0,c):_(c,l)??(d?`0${l.slice(3)}`:l)}),o=s(!1);if(r)return null;if(o===t||n(o))return o;let a=s(!0);return n(a)?a:null}fictional(t,e){let n=this.drawnNumber(t);if(n===null)return null;let r=_(t,n);if(r!==null&&(e===void 0||r.length<=e))return r;if(e===void 0||n.length<=e)return n;let s=`0${n.slice(3)}`;return s.length<=e?s:null}drawnNumber(t){let e=t.replace(/[^\d+]/g,""),n=this.drawnFor.get(e);if(n!==void 0)return n;if(this.taken.size>=F)return this.exhausted+=1,null;let r=o=>String(this.pseudonymizer.pseudonymize("phoneE164",o)),s=r(e);for(let o=1;this.taken.has(s)&&o<=q;o+=1)s=r(`${e}#${o}`);for(let o=Number(s.slice(-4));this.taken.has(s);)o=(o+1)%F,s=`+3363998${String(o).padStart(4,"0")}`;return this.drawnFor.set(e,s),this.taken.add(s),s}shortAddress(t,e=!1){let n=t.toLowerCase();return e?`user-${Y("sha256").update(n).digest("hex").slice(0,16)}@example.invalid`:String(this.pseudonymizer.pseudonymize("email",n))}count(t,e){let n=this.counted.get(t)??new Map,r=n.get(e.name)??{kind:e.kind,values:0};r.values+=1,n.set(e.name,r),this.counted.set(t,n)}};export{p as a,me as b,f as c,u as d,G as e,F as f,ee as g,P as h,B as i,ie as j,L as k,se as l,oe as m,ae as n,fe as o};
@@ -1,7 +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{c as gt,d as Ds,e as Ls,f as mt}from"./chunk-G6IYOZEH.mjs";import{b as ht,c as yt,d as rn,e as sn,f as Ys,g as on}from"./chunk-45375WT5.mjs";import{b as Js,d as Vs}from"./chunk-DCJBP3LE.mjs";import{a as Xs,c as Zs}from"./chunk-YV7JYHJP.mjs";import{a as ze,b as $s,c as Bs,d as _s,f as Ws,g as Gs,h as Us,i as zs,j as qs,l as Q,n as tn,o as nn,p as Ks,q as Hs,s as qe}from"./chunk-2JRVBXJL.mjs";import{Ec as Br}from"./chunk-RIIJJRGF.mjs";import{a as ve,c as Qt}from"./chunk-BOGNK4LV.mjs";import{G as Ss,H as bs,Ha as As,Ia as Cs,M as Rs,N as ks,P as Os,Pa as Ps,Qa as Is,Ra as Es,Sa as Ts,Ta as Ms,Va as Fs,Wa as js,Ya as vs,ab as Ns,bb as xs,h as ms,j as en}from"./chunk-SAHGDSZQ.mjs";import{k as ws}from"./chunk-32ZB5ICW.mjs";import{j as _r,p as Hr}from"./chunk-TG52WNGV.mjs";import{F as Dr,G as Zt,M as Lr,P as $r,l as Vt,q as xr}from"./chunk-CSSOLHE3.mjs";import{l as hs,m as ys}from"./chunk-TEIBWMJM.mjs";import{l as Er}from"./chunk-YDXMTWAT.mjs";import{f as Yr,h as Jr,i as Ue,k as Vr}from"./chunk-EINEGS6E.mjs";import{a as Xt}from"./chunk-QSRAEUGZ.mjs";import{h as qr,j as Kr}from"./chunk-YGE4AUXG.mjs";import{b as Yt,c as Ge,d as ee}from"./chunk-P6A22FMQ.mjs";import{f as Wr,g as Gr}from"./chunk-AIUAEBHR.mjs";import{Ib as Ne,Jb as pt,Kb as ft,Lc as gs,Za as Zr,_a as Qr,fc as os,hb as es,ib as ts,ic as as,j as Ur,jc as ds,kb as we,lc as cs,mb as dt,nb as ns,ob as ct,p as zr,pb as rs,pc as ls,qb as ss,qc as us,rb as lt,sb as ut,ub as is,vc as ps,wc as fs,xc as xe}from"./chunk-O3ZQSWDN.mjs";import{q as Xr}from"./chunk-5T3LFDJ5.mjs";import{b as Qn,f as er}from"./chunk-INIT2UKJ.mjs";import{a as Or,d as Ar,e as Cr,f as Pr,g as Ir}from"./chunk-JBOGAUGH.mjs";import{a as Tr,b as at,d as Mr,e as Fr,f as jr,g as vr,h as Nr}from"./chunk-4N425UJC.mjs";import{A as Pe,B as mr,C as qt,D as ot,E as Kt,G as Ht,H as hr,I as yr,J as je,n as sr,o as Fe,q as ir,r as or,s as ar,t as dr,u as cr,v as lr,w as ur,y as gr,z as We}from"./chunk-TWYNQ2OO.mjs";import{a as tr}from"./chunk-EADHKH3A.mjs";import{F as X,G as oe,I as zt,N as Xn,P as Zn,f as it,g as Jn,m as Vn,r as Ut}from"./chunk-Z354SAEF.mjs";import{f as Yn,h as ye}from"./chunk-TZE3Y7IQ.mjs";import{b as K}from"./chunk-CA5NAXSU.mjs";import{c as wr,d as Sr,f as br,h as Rr,j as kr,k as Jt}from"./chunk-THYQOG24.mjs";import{a as nr,w as rr}from"./chunk-ICIYL45C.mjs";import{c as pr,d as fr}from"./chunk-JFVY66BS.mjs";import{Ec as Me,Fc as ge,Jc as nt,Sd as Hn,Uc as rt,Vb as $n,Wb as et,Zc as _n,fd as st,fe as Gt,g as Dn,gc as Bn,i as Wt,j as Ln,k as fe,kd as Wn,ld as Gn,md as Un,nd as zn,od as qn,pd as Kn,vc as tt}from"./chunk-CRPLDXJU.mjs";import{b as _e,k as $t,l as Bt,u as Nn,v as xn,z as _t}from"./chunk-WZQEK4WT.mjs";var wt=class{classify(e){let t=et(e.statusCode),r=this.getSuggestedAction(e.statusCode,t);return{originalError:e,classification:t,suggestedAction:r}}classifyBatch(e){let t=e.map(a=>this.classify(a)),r={auth:0,permission:0,schema:0,data:0,validation:0,limit:0,network:0,trigger:0,reference:0,unknown:0},s={},i=0;for(let a of t){a.classification.retryable&&i++;let d=a.classification.category??"unknown";r[d]=(r[d]??0)+1,s[a.originalError.statusCode]=(s[a.originalError.statusCode]??0)+1}let o={totalErrors:e.length,retryableCount:i,nonRetryableCount:e.length-i,byCategory:r,byErrorCode:s,sampleErrors:e.slice(0,5)};return{classified:t,summary:o}}isRetryable(e){return et(e).retryable}hasBlockingError(e){return e.some(t=>et(t.statusCode).blockAll===!0)}get knownErrorCount(){return Object.keys($n).length}getSuggestedAction(e,t){return t.suggestUpsert?"Consider using upsert with external ID":t.suggestTruncate?"Truncate field values to fit within limits":t.blockAll?"Operation blocked: resolve storage/limit issue first":t.strategy==="reauth_then_retry"?"Re-authenticate and retry":t.strategy==="reduce_batch"?"Reduce batch size and retry":t.retryable?`Retry after ${t.delay??0}ms`:`Fix ${e} error and retry manually`}};function ro(n,e){return new Promise(t=>{if(e?.aborted){t();return}let r=()=>{clearTimeout(s),e?.removeEventListener("abort",r),t()},s=setTimeout(r,n);e?.addEventListener("abort",r,{once:!0})})}var St=class{constructor(e={}){this.options=e;this.strategy=new Tr({...e.retryConfig,jitter:e.retryConfig?.jitter??!0}),this.classifier=new wt}options;strategy;classifier;async execute(e){let t=this.strategy.getConfig(),r,s=0;for(let i=0;i<=t.maxRetries;i++)try{return{success:!0,result:await e(),attempts:i+1,totalDelay:s}}catch(o){r=o instanceof Error?o:new Error(String(o));let a=so(o),d=this.classifier.classify(a);if(!d.classification.retryable)return{success:!1,error:r,attempts:i+1,totalDelay:s};if(i<t.maxRetries){let c={success:!1,error:r,attempts:i+1,totalDelay:s,cancelled:!0};if(this.options.signal?.aborted)return c;let l=this.strategy.calculateDelay(i);if(this.options.onRetry?.(i,d,l),s+=l,await ro(l,this.options.signal),this.options.signal?.aborted)return{...c,totalDelay:s}}}return{success:!1,error:r,attempts:t.maxRetries+1,totalDelay:s}}async executeBatch(e,t){let r=[...e],s=[],i=[],o=0,a=this.options.retryConfig?.maxRetries??3;for(;r.length>0&&o<=a;){let d=await t(r);s.push(...d.successes);let c=[];for(let l of d.failures)this.classifier.classify(l.error).classification.retryable&&o<a?c.push(l.record):i.push(l);if(r=c,r.length>0){let l=this.options.retryConfig?.initialDelay??1e3,u=this.options.retryConfig?.maxDelay??3e4,f=l*Math.pow(2,o);await new Promise(p=>setTimeout(p,Math.min(f,u))),o++}}return{successes:s,failures:i}}getClassifier(){return this.classifier}getStrategy(){return this.strategy}};function so(n){if(typeof n!="object"||n===null)return{statusCode:"UNKNOWN_ERROR",message:String(n)};let e=n,t=[e.errorCode,e.statusCode,e.name].find(s=>typeof s=="string"&&s.length>0&&s!=="Error"),r=e.fields??e.data?.fields;return{statusCode:t??"UNKNOWN_ERROR",errorCode:typeof e.errorCode=="string"?e.errorCode:void 0,message:typeof e.message=="string"?e.message:String(n),fields:Array.isArray(r)?r.filter(s=>typeof s=="string"):void 0}}var io=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function oo(n){if(n===!0||n==="true")return!0;if(n===!1||n==="false")return!1}async function ao(n,e,t,r=()=>Date.now()){let s=await Er(n,e,{now:r,successfulOnly:!0});return s.state==="running"?{state:"running"}:s.state!=="ended"?s:{state:"ended",created:(s.results.successfulResults??[]).flatMap(o=>{let a=o.sf__Id;return typeof a!="string"||!io.test(a)?[]:t&&oo(o.sf__Created)!==!0?[]:[a]}),...typeof s.info.systemModstamp=="string"?{at:s.info.systemModstamp}:{}}}async function wd(n,e,t,r,s=()=>new Date){let i,o=()=>(i??=(async()=>{if(!r)return 0;try{let d=s().getTime(),c=Date.parse(await r());return Number.isFinite(c)?c-(d+s().getTime())/2:0}catch{return 0}})(),i),a=[];for(let d of e.jobs??[]){if(d.job===void 0)continue;let c={job:d.job,objectApiName:d.objectApiName},l=await ao(t,d.job,d.upsert===!0,()=>s().getTime());if(l.state==="running"||l.state==="unread"){a.push({...c,read:l,answered:!1});continue}let u=s().toISOString();l.state==="ended"&&l.at!==void 0&&Number.isFinite(Date.parse(l.at))?u=new Date(Date.parse(l.at)-await o()).toISOString():e.lastWrittenAt!==void 0&&(u=e.lastWrittenAt);let f=l.state==="ended"?l.created:[],p=await n.answerInFlight(e.runId,d.objectApiName,f,u,d.job);a.push({...c,read:l,answered:p})}return a}function Sd(n,e){return e.map(({job:t,read:r})=>{let s=`${n}, job ${t}`;switch(r.state){case"ended":return`[INFO] ${s}: the job no line of the run answered ended in the org; ${r.created.length} record(s) it created kept with the run`;case"never-closed":return`[INFO] ${s}: the job was never closed, and wrote nothing`;case"running":return`[INFO] ${s}: the job is still running in the org; read again later`;default:return`[WARN] ${s}: the job could not be read back: ${r.reason}`}})}var Le=5e3,dn=200,bt=_e().refine(n=>Ge(n),"not a record id"),co=Bt({sourceOrgId:_e().min(1).max(200),targetOrgId:_e().min(1).max(200),objectApiName:_e().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),kind:Nn(["document","attachment"]),sourceId:bt,targetId:bt,sourceVersionId:bt.optional(),sourceModifiedAt:_t.datetime().optional(),linked:$t(bt).max(dn),copiedAt:_t.datetime()}),lo=Bt({version:xn(1),entries:$t(co).max(Le)});function ei(n){if(n==null)return{kind:"none"};let e=lo.safeParse(n);if(e.success)return{kind:"stored",map:e.data};let t=e.error.issues[0];return{kind:"unreadable",issue:`${t.path.join(".")||"map"}: ${t.message}`}}function Fd(n,e,t){return n?n.check({orgId:e,orgTier:_n(t),operation:"delete",objectName:"Attachment",recordCount:1,module:"sync"}).allowed:!1}var ue=class extends Error{constructor(e){super(e),this.name="SyncFilesRefusedError"}},Ke=class extends Error{};function uo(){return{copied:0,versions:0,bytes:0,links:0,unchanged:0,tooLarge:0,pastRunCap:0,external:0,recordNotWritten:0,failed:0}}function te(n,e){let t=n[e];return typeof t=="string"&&t!==""?t:void 0}function Rt(n,e){let t=n;for(let r of e.split(".")){if(typeof t!="object"||t===null)return null;t=t[r]}return Kt(t)}function De(n,e){return e==null?n:n===void 0||Date.parse(e)>Date.parse(n)?e:n}function po(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0}function He(n,e,t){return`${n}|${e}|${t}`}function fo(n,e){let t=e.load(n.id);if(t===null)throw new ue("Files are copied by a saved configuration only: it keeps which file it copied where, so that running it again copies none of them twice. Save the configuration, then run it. Nothing was read or written.");if(t.kind==="unreadable")throw new ue(`The record of the files this configuration copied could not be read (${t.issue}), so a run could copy them a second time. Turn the files off, or save the configuration again under a new name. Nothing was read or written.`);let r=new Map;if(t.kind==="stored")for(let s of t.map.entries)r.set(He(s.sourceOrgId,s.targetOrgId,s.sourceId),s);return r}var an="ContentDocument.LatestPublishedVersion.SystemModstamp";async function go(n,e,t,r){let s=rt(t.objectApiName),i=t.where?.trim()?` WHERE (${Yn(t.where)})`:"",o=`SELECT Id FROM ${s}${i}`,a=qt(r),d=new Set,c,l=await n.copy.queryRecords(e.sourceOrgId,`SELECT LinkedEntityId, SystemModstamp, ${an} FROM ContentDocumentLink WHERE LinkedEntityId IN (${o}) AND (SystemModstamp > ${a} OR ${an} > ${a})`);for(let f of l){let p=te(f,"LinkedEntityId");p&&Ge(p)&&d.add(p),c=De(De(c,Rt(f,"SystemModstamp")),Rt(f,an))}let u=await n.copy.queryRecords(e.sourceOrgId,`SELECT ParentId, LastModifiedDate FROM Attachment WHERE ParentId IN (${o}) AND LastModifiedDate > ${a}`);for(let f of u){let p=te(f,"ParentId");p&&Ge(p)&&d.add(p),c=De(c,Rt(f,"LastModifiedDate"))}return{ids:[...d],...c!==void 0?{newest:c}:{}}}async function mo(n,e,t){let r=new Map;for(let s of ee(t)){let i=await n.copy.queryRecords(e.sourceOrgId,`SELECT Id, LastModifiedDate FROM Attachment WHERE Id IN (${s})`);for(let o of i){let a=te(o,"Id"),d=Kt(o.LastModifiedDate);a&&d&&r.set(a,d)}}return r}function ho(n,e,t){return e===void 0||n.targetId===n.sourceId?!1:n.sourceModifiedAt!==void 0?n.sourceModifiedAt!==e:t!==void 0&&Date.parse(e)>Date.parse(t)}async function yo(n,e,t,r,s,i){let o=[...s.values()].filter(l=>l.kind==="document"&&l.objectApiName===t&&l.sourceOrgId===e.sourceOrgId&&l.targetOrgId===e.targetOrgId&&!i.has(l.sourceId)).map(l=>l.sourceId),a=qt(r),d=[],c;for(let l of ee(o)){let u=await n.copy.queryRecords(e.sourceOrgId,`SELECT Id, ContentDocumentId, Title, PathOnClient, ContentSize, ContentLocation, SystemModstamp FROM ContentVersion WHERE ContentDocumentId IN (${l}) AND IsLatest = true AND SystemModstamp > ${a}`);for(let f of u){c=De(c,Rt(f,"SystemModstamp"));let p=te(f,"ContentDocumentId"),m=te(f,"Id");if(!p||!m||(te(f,"ContentLocation")??"S")!=="S")continue;let y=te(f,"Title")??p;d.push({objectApiName:"ContentDocument",sourceId:p,body:{objectApiName:"ContentVersion",id:m},name:y,bytes:po(f,"ContentSize"),hosts:[],fields:{Title:y,PathOnClient:te(f,"PathOnClient")??y}})}}return{files:d,...c!==void 0?{newest:c}:{}}}async function wo(n,e,t,r){let s=new Map,i=new Date().toISOString(),o=(l,u,f)=>({sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:t,kind:l,sourceId:u,targetId:u,linked:[],copiedAt:i,...f}),a=r.filter(l=>l.objectApiName==="ContentDocument").map(l=>l.sourceId);for(let l of ee(a)){let u=await n.copy.queryRecords(e.targetOrgId,`SELECT Id, LatestPublishedVersionId FROM ContentDocument WHERE Id IN (${l})`);for(let f of u){let p=te(f,"Id");if(!p)continue;let m=te(f,"LatestPublishedVersionId");s.set(p,o("document",p,m?{sourceVersionId:m}:{}))}}let d=[...s.keys()];for(let l of ee(d)){let u=await n.copy.queryRecords(e.targetOrgId,`SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN (${l})`);for(let f of u){let p=te(f,"ContentDocumentId"),m=te(f,"LinkedEntityId"),y=p?s.get(p):void 0;y&&m&&Ge(m)&&y.linked.length<dn&&y.linked.push(m)}}let c=r.filter(l=>l.objectApiName==="Attachment").map(l=>l.sourceId);for(let l of ee(c)){let u=await n.copy.queryRecords(e.targetOrgId,`SELECT Id FROM Attachment WHERE Id IN (${l})`);for(let f of u){let p=te(f,"Id");p&&s.set(p,o("attachment",p,{}))}}return s}async function ti(n){let{config:e,option:t,objects:r,deps:s}=n,i=fo(e,s.store),o;try{o=await Rs(s.copy,e.targetOrgId)}catch(p){throw new ue(`The file storage the target has left could not be read (${K(p)}), so the files could not be measured against it. Nothing was written.`)}let a=t.maxFileSizeMB*1048576,d=t.maxRunMB*1048576,c=0,l=0,u=new Set,f={objects:new Map,storage:{remainingBytes:o,plannedBytes:0}};for(let{objectConfig:p,changedSince:m,filesSeen:y}of r){if(p.operation==="delete")continue;let h=p.objectApiName,b=await s.sourceIds(p,m),S=[],R=m===void 0?void 0:y!==void 0&&Date.parse(y)>Date.parse(m)?mr(y):m,k=m===void 0?void 0:y,g=new Map;if(R!==void 0)try{let j=new Set(b),x=await go(s,e,p,R);k=De(k,x.newest);let _=x.ids.filter(z=>!j.has(z));if(_.length>0){let z=n.tie?await n.tie(p,_):{held:new Map};g=z.held;let H=_.filter(G=>!g.has(G)).length;H>0&&S.push(`${H} record(s) whose files changed since the last run, and nothing else of them, could not be tied to their copy in the target`+(z.refused?` (${z.refused})`:"")+": their new files are copied when the record changes, or on a full read.")}}catch(j){throw new ue(`${h}: the files its records gained since the last run could not be looked up (${K(j)}). Run it again, or turn the files off. Nothing was written.`)}let w=[...b,...g.keys()],M=await Ss({scope:new Map([[h,w]]),sourceOrgId:e.sourceOrgId,maxFileBytes:a,queryRecords:s.copy.queryRecords});if(bs(M)){let j=new Set(M.errors.flatMap(x=>x.samples.flatMap(_=>_.messages)));throw new ue(`${h}: the files of its records could not all be looked up in the source (${[...j].join("; ")}). Run it again, or turn the files off. Nothing was written.`)}let A=uo();for(let j of M.leftOut)j.reason==="too-large"?A.tooLarge++:j.reason==="external"&&A.external++;A.tooLarge>0&&S.push(`${A.tooLarge} file(s) larger than ${t.maxFileSizeMB} MB were not copied.`);let O=M.files,E=[],F=new Map;try{if(R!==void 0){let _=new Set(O.map(H=>H.sourceId)),z=await yo(s,e,h,R,i,_);k=De(k,z.newest);for(let H of z.files)H.bytes>a?A.tooLarge++:O=[...O,H]}let j=O.filter(_=>!i.has(He(e.sourceOrgId,e.targetOrgId,_.sourceId)));if(j.length>0)for(let[_,z]of await wo(s,e,h,j))i.set(He(e.sourceOrgId,e.targetOrgId,_),z),E.push(z);let x=O.filter(_=>_.objectApiName==="Attachment");x.length>0&&(F=await mo(s,e,x.map(_=>_.sourceId)))}catch(j){throw new ue(`${h}: the files an earlier run copied could not be looked up (${K(j)}), so a run could copy them twice. Nothing was written.`)}let N=[],$=new Map,T=0,v=0;for(let j of O){if(u.has(j.sourceId)){A.unchanged++,N.push(j);continue}let x=i.get(He(e.sourceOrgId,e.targetOrgId,j.sourceId)),_=x?.kind==="attachment"&&ho(x,F.get(j.sourceId),m);if(_&&!s.deleteFromTarget){v++;continue}if(x&&!_&&(x.kind==="attachment"||x.sourceVersionId===j.body.id)){A.unchanged++,x.kind==="document"&&N.push({...j,into:{documentId:x.targetId,linked:x.linked,unchanged:!0}});continue}if(!x&&l>=Le-i.size){T++,A.pastRunCap++;continue}if(c+j.bytes>d){A.pastRunCap++;continue}c+=j.bytes,A.bytes+=j.bytes,u.add(j.sourceId),x&&_?(A.replaced=(A.replaced??0)+1,$.set(j.sourceId,x.targetId),N.push(j)):x?(A.versions++,N.push({...j,into:{documentId:x.targetId,linked:x.linked}})):(l++,A.copied++,N.push(j))}A.pastRunCap>T&&S.push(`${A.pastRunCap-T} file(s) past the ${t.maxRunMB} MB a run copies were not copied: the next run copies them.`),v>0&&S.push(`${v} legacy attachment(s) the source changed since they were copied were left as copied: replacing one deletes its earlier copy, and this run may not delete in the target.`),T>0&&S.push(`${T} file(s) were not copied: this configuration keeps the record of ${Le} copied files at most, which it holds already. Removing an earlier run of it frees the entries of the files that run copied: Remove what this run created on its History entry, or --remove on the command line.`),f.objects.set(h,{scope:new Set(w),files:N,outcome:A,notes:S,shared:E,held:g,replacing:$,attachmentsChangedAt:F,...k!==void 0?{filesSeen:k}:{}})}return f.storage={remainingBytes:o,plannedBytes:c,...c>o?{shortfall:`The files to copy take ${st(c)} and the target has ${st(Math.max(0,o))} of file storage left. Lower the largest file or the most a run copies, or leave the files out.`}:{}},f}function So(n){return n.flatMap(e=>e.samples.map(t=>`${e.objectApiName}: ${t.recordSummary}: ${t.messages.join("; ")}`))}async function ni(n){let{config:e,option:t,objectApiName:r,planned:s,written:i,deps:o,signal:a}=n,d={...s.outcome,copied:0,versions:0,bytes:0,...s.outcome.replaced!==void 0?{replaced:0}:{}},c=[...s.notes],l=[...i.keys()].filter(g=>!s.scope.has(g)).length;l>0&&c.push(`${l} record(s) written were not in the source when the files were looked up: their files are copied by the next run.`);try{for(let g of s.shared)o.store.record(e.id,g)}catch(g){c.push(`The files the target already held could not be recorded (${K(g)}): the next run looks them up again.`)}if(s.files.length===0)return{outcome:d,notes:c,unplanned:l,cancelled:!1};let u=o.store.load(e.id),f=new Map((u?.kind==="stored"?u.map.entries:[]).filter(g=>g.sourceOrgId===e.sourceOrgId&&g.targetOrgId===e.targetOrgId).map(g=>[g.sourceId,g])),p=s.files.map(g=>{let w=g.into?void 0:f.get(g.sourceId);return w&&w.kind==="document"?{...g,into:{documentId:w.targetId,linked:w.linked,unchanged:!0}}:g}),m=ks({files:p.filter(g=>!g.into?.unchanged),leftOut:[],errors:[]},t.maxFileSizeMB*1048576),y=[],h,b=!1,S=[],R={ids:[],note:void 0},k=(g,w)=>{let M=He(e.sourceOrgId,e.targetOrgId,g.sourceId),A=[...new Set([...g.into?.linked??[],...w.linked])].slice(0,dn),O=g.objectApiName==="ContentDocument",E=s.replacing.get(g.sourceId),F=s.attachmentsChangedAt.get(g.sourceId);w.asVersion?(d.versions++,d.bytes+=g.bytes):E!==void 0?(d.replaced=(d.replaced??0)+1,d.bytes+=g.bytes):g.into?.unchanged||(d.copied++,d.bytes+=g.bytes),!w.asVersion&&!g.into&&n.onCreated?.(O?"ContentDocument":"Attachment",w.targetId);try{o.store.record(e.id,{sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:r,kind:O?"document":"attachment",sourceId:g.sourceId,targetId:w.targetId,...O?{sourceVersionId:g.body.id}:{},...!O&&F!==void 0?{sourceModifiedAt:F}:{},linked:A,copiedAt:new Date().toISOString()}),E!==void 0&&E!==w.targetId&&S.push(E)}catch(N){h=`${K(N)} (${M})`}};try{await Os({files:p,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:g=>i.has(g)||s.held.has(g),get:g=>i.get(g)??s.held.get(g),add:()=>{}},deps:o.copy,report:m,errors:y,waitIfPaused:async()=>{if(h!==void 0)throw new Ke;if(await n.waitIfPaused?.(),a?.aborted)throw new Ke},onProgress:g=>{g.status==="running"&&o.onProgress?.(g.progress,`${r}: ${g.message}`)},onCopied:k})}catch(g){if(!(g instanceof Ke))throw g;b=h===void 0}finally{S.length>0&&(R=await bo(o,S))}return d.links=m.links,d.failed=m.objects.reduce((g,w)=>g+w.failed,0)+R.ids.length,d.recordNotWritten=m.leftOut.filter(g=>g.reason==="record-not-created").length,c.push(...So(y)),R.note!==void 0&&c.push(R.note),d.recordNotWritten>0&&c.push(`${d.recordNotWritten} file(s) were not copied: no record they hang on was written.`),h!==void 0&&(d.failed++,c.push(`A copied file could not be recorded, so no more files were copied: ${h}. Check the copies of the last files in the target before running it again.`)),{outcome:d,notes:c,unplanned:l,cancelled:b}}var Qs=200;async function bo(n,e){let t=[],r=new Set;for(let s=0;s<e.length;s+=Qs){let i=e.slice(s,s+Qs);try{let o=await n.deleteFromTarget?.("Attachment",i)??[];i.forEach((a,d)=>{let c=o[d];c?.success||(t.push(a),r.add(c?.errors.join("; ")||"The target gave no reason."))})}catch(o){t.push(...i),r.add(K(o))}}return t.length===0?{ids:[],note:void 0}:{ids:t,note:`${t.length} earlier copy(ies) of an attachment replaced could not be deleted from the target (${[...r].join("; ")}): the record holds the new copy and the old one, ${t.join(", ")}.`}}function jd(n){let e=t=>{let r=n[t];if(!r)throw new Error(`No connection for the org ${t}.`);return r};return{queryRecords:async(t,r)=>(await tr(e(t).pages,r)).records,readFileBody:(t,r,s)=>Ps(e(t).transport,r,s),insertFile:(t,r,s)=>Is(e(t).transport,r,s),insertRecords:async(t,r,s)=>kr(await e(t).create(r,s),r).map(i=>({id:i.id,success:i.success,errors:i.errors})),remainingFileStorageMB:t=>Es(e(t).transport)}}function vd(n){let e=0,t=0,r=0;for(let s of n)e+=s.copied+s.versions+(s.replaced??0),t+=s.bytes,r+=s.tooLarge+s.pastRunCap;return`${e} file(s), ${st(t)} copied, ${r} skipped past the caps`}var cn="sync:config:",ri="syncConfigs",Je="sync:delta:",ln="syncDelta",kt="sync:files:",si="syncFiles",ii=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${cn}${e.id}`,e,ri)}load(e){return this.configStore.get(`${cn}${e}`)}isSaved(e){return this.load(e)!==void 0}deltaStore(){return{load:e=>this.isSaved(e)?this.loadDelta(e):null,record:(e,t)=>this.recordWatermark(e,t)}}fileStore(){return{load:e=>this.isSaved(e)?this.loadFiles(e):null,record:(e,t)=>this.recordFile(e,t)}}list(){let e=this.configStore.getByCategory(ri);return Object.values(e).sort((r,s)=>s.updatedAt.localeCompare(r.updatedAt))}delete(e){return this.configStore.delete(`${Je}${e}`),this.configStore.delete(`${kt}${e}`),this.configStore.delete(`${cn}${e}`)}loadDelta(e){return gr(this.configStore.get(`${Je}${e}`))}recordWatermark(e,t){let r=this.loadDelta(e),o={version:1,entries:[...(r.kind==="stored"?r.state.entries:[]).filter(a=>a.sourceOrgId!==t.sourceOrgId||a.targetOrgId!==t.targetOrgId||a.objectApiName!==t.objectApiName),t],...r.kind==="stored"&&r.state.resetAt?{resetAt:r.state.resetAt}:{}};this.configStore.set(`${Je}${e}`,o,ln)}loadFiles(e){return ei(this.configStore.get(`${kt}${e}`))}recordFile(e,t){let r=this.loadFiles(e);if(r.kind==="unreadable")throw new Error(`the record of copied files does not read: ${r.issue}`);let i=(r.kind==="stored"?r.map.entries:[]).filter(a=>a.sourceOrgId!==t.sourceOrgId||a.targetOrgId!==t.targetOrgId||a.sourceId!==t.sourceId);if(i.length>=Le)throw new Error(`the record of copied files holds ${Le} files already`);let o={version:1,entries:[...i,t]};this.configStore.set(`${kt}${e}`,o,si)}forgetFiles(e,t,r){let s=this.loadFiles(e);if(s.kind!=="stored"||r.length===0)return[];let i=new Set(r.map(d=>d.slice(0,15))),o=[],a=s.map.entries.filter(d=>{let c=d.sourceOrgId===t.sourceOrgId&&d.targetOrgId===t.targetOrgId&&i.has(d.targetId.slice(0,15));return c&&o.push(d),!c});if(o.length>0){let d={version:1,entries:a};this.configStore.set(`${kt}${e}`,d,si)}return o}markRemoved(e,t,r,s){let i=this.loadDelta(e);if(i.kind!=="stored"||r.length===0)return[];let o=[],a=i.state.entries.map(d=>d.sourceOrgId!==t.sourceOrgId||d.targetOrgId!==t.targetOrgId||!r.includes(d.objectApiName)?d:(o.push(d.objectApiName),{...d,removedAt:s}));if(o.length>0){let d={...i.state,entries:a};this.configStore.set(`${Je}${e}`,d,ln)}return o}clearDelta(e){let t=this.loadDelta(e),r=t.kind==="stored"?t.state.entries.length:0,s={version:1,entries:[],resetAt:new Date().toISOString()};return this.configStore.set(`${Je}${e}`,s,ln),r}};async function Ro(n,e,t){let r=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let{objectApiName:i,ids:o}of e){let a=ye(i);for(let d of ee(o)){if(t?.aborted)return;let c=await n.queryDeleted(`SELECT Id, CreatedDate FROM ${a} WHERE Id IN (${d})`);for(let l of c.records){let u=Date.parse(String(l.CreatedDate??""));Number.isFinite(u)&&(r=Math.min(r,u),s=Math.max(s,u))}}}if(!(!Number.isFinite(r)||!Number.isFinite(s)))return{first:new Date(r).toISOString(),last:new Date(s).toISOString()}}async function zd(n,e){let t=s=>({note:`What the duplicate rules of the target reported of the run could not be read (${K(s)}): the empty DuplicateRecordSet records it left, if any, stay.`}),r=new Set;try{for(let{ids:s}of e)for(let i of ee(s)){let{records:o}=await n.query(`SELECT DuplicateRecordSetId FROM DuplicateRecordItem WHERE RecordId IN (${i})`);for(let a of o){let d=a.DuplicateRecordSetId;typeof d=="string"&&r.add(d)}}}catch(s){return{objects:[],take:async()=>t(s)}}return{objects:r.size>0?[Zt]:[],take:async(s=[])=>{let i=new Set(s.map(l=>l.slice(0,15))),o=[...r].filter(l=>!i.has(l.slice(0,15)));if(o.length===0)return{};let a=new Set;try{for(let l of ee(o)){let{records:u}=await n.query(`SELECT DuplicateRecordSetId FROM DuplicateRecordItem WHERE DuplicateRecordSetId IN (${l})`);for(let f of u)a.add(String(f.DuplicateRecordSetId))}}catch(l){return t(l)}let d=o.filter(l=>!a.has(l));if(d.length===0)return{};let c={objectApiName:Zt,planned:d.length,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],unchecked:[],reasons:[]};for(let l=0;l<d.length;l+=Yt){let u=d.slice(l,l+Yt);for(let f of await xr(n,c.objectApiName,u))f.kind==="deleted"?c.deleted+=1:f.kind==="gone"?c.alreadyGone+=1:(c.refused+=1,c.reasons.includes(f.reason)||c.reasons.push(f.reason))}return{object:c}}}}function qd(n,e,t){return[...new Set([...$r(n,[],t),...e.objects])]}async function ko(n,e){if(!n||!e)return n;let t=Date.parse(e.at),r=Date.parse(e.lastAt??""),s=Date.parse(n.first),i=Date.parse(n.last);if(!Number.isFinite(s)||!Number.isFinite(i)||!Number.isFinite(t)&&!Number.isFinite(r))return n;let o=await oi(e);if(o===void 0)return n;let a=Number.isFinite(t)?Math.min(s,t+o):s,d=Number.isFinite(r)?Math.max(i,r+o):i;return a===s&&d===i?n:{first:a===s?n.first:new Date(a).toISOString(),last:d===i?n.last:new Date(d).toISOString()}}async function oi(n){let e=n.now??(()=>new Date);try{let t=e().getTime(),r=Date.parse(await n.serverTime());return Number.isFinite(r)?r-(t+e().getTime())/2:void 0}catch{return}}async function Oo(n){if(!n)return;let e=Date.parse(n.at);if(!Number.isFinite(e))return;let t=Date.parse(n.lastAt??""),r=await oi(n);if(r===void 0)return;let s=Number.isFinite(t)?Math.max(e,t):e;return{first:new Date(e+r).toISOString(),last:new Date(s+r).toISOString()}}var Ao=50,Co=3,ai=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function Po(n,e,t,r){let s=Date.parse(t.first)-Ts,i=Date.parse(t.last)+Ms;if(!Number.isFinite(s)||!Number.isFinite(i))return;let o=new Map,a=0;for(let{objectApiName:d,ids:c}of e){if(a>=Co||o.size>1||r?.aborted)break;let l=c.slice(0,Ao);if(l.length===0)continue;let u;try{let[p]=ee(l,l.length);u=(await n.query(`SELECT Id, LastModifiedById, LastModifiedDate FROM ${ye(d)} WHERE Id IN (${p})`)).records}catch{continue}let f=!1;for(let p of u){let{LastModifiedById:m,LastModifiedDate:y}=p??{},h=typeof y=="string"?Date.parse(y):Number.NaN;typeof m!="string"||!ai.test(m)||!(h>=s&&h<=i)||(o.has(m.slice(0,15))||o.set(m.slice(0,15),m),f=!0)}f&&a++}return o.size===1?[...o.values()][0]:void 0}async function Kd(n,e,t,r,s,i,o){let a=e.some(({ids:p})=>p.length>0),d=a?await ko(await Ro(n,e,r),s):await Oo(s),c=o.runUserId!==void 0&&ai.test(o.runUserId)?o.runUserId:void 0,l=n.query?.bind(n),u=!c&&!a&&d&&l?await Po({query:l},i,d,r):void 0,f=i.filter(({ids:p})=>p.length>0);return{writtenBetween:d,created:e,remap:new Set([...e,...i].flatMap(({ids:p})=>p.map(m=>m.slice(0,15)))),automation:Fs(t),...c?{runUserId:c}:{},...u?{user:u}:{},ties:{...o.ties,...f.length>0?{writtenOver:f}:{}},...r?{signal:r}:{}}}var Ot={status:"cancelled",objects:[],unread:[],handWork:[]};function tc(n,e,t){return{...Lr(n,e),counts:js(Kr(qr(n),t))}}async function nc(n,e){let t=Date.parse(n.writtenBetween?.first??""),r=Date.parse(n.writtenBetween?.last??"");if(!Number.isFinite(t)||!Number.isFinite(r))return n;let{created:s}=n,i=new Set(s.flatMap(({ids:c})=>c.map(l=>l.slice(0,15)))),o=await Dr(e,{has:c=>i.has(c),start:t,end:r,...n.runUserId?{user:n.runUserId.slice(0,15)}:{}},s.filter(c=>c.objectApiName==="Quote").flatMap(({ids:c})=>c),new Set(s.map(c=>c.objectApiName))),a=new Set(o.flatMap(c=>c.copies.map(l=>l.id.slice(0,15))));if(a.size===0)return n;let{remap:d}=n;return{...n,remap:{has:c=>d.has(c)||a.has(c)}}}async function rc(n){let e,t,r;try{let o=await n.input();"refused"in o?r={...Ot,status:"refused",refusal:o.refused}:t=vs(n.org,o,{...n.options,approve:async a=>{let{check:d,decision:c}=await Br(n.guard,{...n.guardOf,objectName:xs(a).join(", "),recordCount:Ns(a)});if(e=c,c==="refused")return`Operation blocked by Production Guard: ${d.blockedReason??d.impactSummary}`;if(c==="declined")return"Operation cancelled by user (confirmation declined)."}})}catch(o){r={...Ot,status:"failure",refusal:K(o)}}let s=async o=>{if(!t||r)return!1;try{return await o(t)}catch(a){return r={...t.result(),status:"failure",refusal:K(a)},!1}},i;return{automationMade:t?.automationMade??new Set,ask:async()=>{await s(async o=>(await o.ask(),!1))},get takes(){return r?[]:t?.takes??[]},first:o=>s(a=>a.first(o)),afterRemoval:o=>s(a=>a.afterRemoval(o)),result:()=>r??t?.result()??Ot,settle:()=>(i??=(async()=>{let o=r??t?.result()??Ot;return n.onGuardDecision(o,e),t&&(t.made.size>0||t.late.size>0||t.gone.size>0)&&await n.keepMade?.(t.made,t.late,t.gone).catch(()=>{}),o})(),i)}}function sc(n){return n?"GUARD_BLOCKED":"SWEEP_REFUSED"}var di=6e4;function To(n,e){return e.filter(t=>(t.ids.length>0||t.idsUntold===!0)&&Mo(n,t)).map(t=>({ids:[...t.ids],...t.idsUntold?{idsUntold:!0}:{}}))}function Mo(n,e){let t=Date.parse(n?.first??""),r=Math.max(t,Date.parse(n?.last??""));return!Number.isFinite(t)||!Number.isFinite(r)?!1:Number.isFinite(e.from)&&Number.isFinite(e.to)&&e.from<=r+9e5+di&&Math.max(e.from,e.to)>=t-2e3-di}var Fo=new Set(["autopilot_execute","anonymize_execute","subject_erase","backup_restore","checkpoint_rewind","checkpoint_undo","frozen_load"]);function ic(n,e){return n.filter(t=>Fo.has(t.action)&&t.action!==e&&t.outcome!=="stopped").map(t=>{let r=Date.parse(t.timestamp);return{ids:[],idsUntold:!0,from:r,to:r}})}function jo(n){let e=Date.parse(n.firstWrittenAt??n.startedAt),t=Date.parse(n.lastWriteAt??n.lastWrittenAt??n.end?.at??n.startedAt);return{ids:[...n.created,...n.overwritten??[]].flatMap(({ids:r})=>r),from:e,to:Number.isFinite(t)?t:e}}function vo(n,e,t){return n.filter(r=>r.targetOrgId===e&&r.runId!==t).map(jo)}async function oc(n,e,t,r){let s=await r(n.targetOrgId,e).catch(()=>[]),i=No(n.removal?.removalSpans),o=n.removal?.madeEarlier,a=n.removal?.lateEarlier;return{otherRuns:To(e,[...vo(t,n.targetOrgId,n.runId),...s]),...i?{removalBegan:i}:{},...o&&o.length>0?{madeEarlier:o}:{},...a&&a.length>0?{lateEarlier:a}:{}}}function ac(n,e,t,r=[]){let s=[...r],i=Xt(n.madeEarlier,e,s),o=Xt(n.lateEarlier,t,s),a={...n};return delete a.madeEarlier,delete a.lateEarlier,{...a,...i.length>0?{madeEarlier:i}:{},...o.length>0?{lateEarlier:o}:{}}}function No(n){let e;for(let t of n??[]){let r=Date.parse(t.first);Number.isFinite(r)&&(!e||r<e.at)&&(e={at:r,first:t.first})}return e?.first}var ae=class extends Error{constructor(t,r,s){super(t);this.result=r;this.cause=s;this.name="SyncRunFailure"}result;cause},$e=class extends ae{constructor(t,r,s){super(t,r);this.code=s;this.name="SyncRunRefused"}code};function lc(n){return typeof n!="number"||!Number.isFinite(n)?5e4:Math.min(5e4,Math.max(1,Math.floor(n)))}var xo=/\b(QUERY_TIMEOUT|OPERATION_TOO_LARGE)\b/;function un(n){return xo.test(n)?" Salesforce gave up on the count: filter the object on an indexed field (CreatedDate, SystemModstamp, Id, Name or an External ID) or on a narrower range of CreatedDate, then run it again. A user with View All Data reads the source without its sharing, which is what slows such a count most.":""}var Do={raise:"the sandforge.sync.maxRecordsPerObject setting",sample:"Forge, with Depth ALL and Records per object set to A sample that fits the target"};function Lo(n,e,t){let r=e<5e4?`raise ${t.raise} (50000 at most), or `:"";return n==="target"?`To compare every record, ${r}narrow the object's filter.`:`To copy the rest, ${r}read it in slices: a filter on CreatedDate, one range per run. To copy a sample of the source that fits the target instead, use ${t.sample}.`}function uc(n){let e=n.cutAtReadCap??[];if(!(n.readCap===void 0||e.length===0))return`the read of the source stopped at ${n.readCap} records of ${e.join(", ")} (sandforge.sync.maxRecordsPerObject): the run copied part of ${e.length===1?"it":"each"}. `+Lo("source",n.readCap,Do)}var $o=2e3,Bo=5e3,At=class{chunkSize;pollIntervalMs;signal;constructor(e={}){this.chunkSize=e.chunkSize??$o,this.pollIntervalMs=e.pollIntervalMs??Bo,this.signal=e.signal}async executeChunked(e,t,r,s,i,o){if(!e.bulkManager.canStartNewJob())throw new Error("Maximum concurrent bulk jobs reached");let a=e.connection.bulk2.createJob({operation:r,object:t,...o?{externalIdFieldName:o}:{}}),d=a.id??`bulk-${crypto.randomUUID()}`,c={id:d,operation:r,object:t,state:"UploadComplete",numberRecordsProcessed:0,numberRecordsFailed:0,totalProcessingTime:0,createdDate:new Date().toISOString(),totalRecords:i};e.bulkManager.registerJob(c);try{await a.open();let l=Cr(a);l!==void 0&&e.onOpened?.(l);let u=[];for await(let w of s){if(this.signal?.aborted)break;for(let M of w)u.push(M);e.onProgress?.(u.length,i)}let f,p=0;if(this.signal?.aborted||(f=Or(r,u,o),await a.uploadData(f.text),p=u.length),this.signal?.aborted||f===void 0)return await Ir(a),e.bulkManager.updateJobState(d,"Aborted"),this.buildAbortedResult(p);await a.close();let m=await a.check();for(;m.state==="InProgress"||m.state==="UploadComplete";)e.bulkManager.updateJobState(d,m.state),e.onProgress?.(m.numberRecordsProcessed??0,i),await new Promise(w=>setTimeout(w,this.pollIntervalMs)),m=await a.check();let y=await a.getAllResults(),h=Ar(y,f,Pr(m)),b=h.outcomes,S=[],R=[],k=h.unattributedSuccessIds.length;for(let w of b)w.success?(k++,w.id!==void 0&&S.push(w.id)):R.push(w.error??"Unknown error");S.push(...h.unattributedSuccessIds),R.push(...h.unattributedFailures);let g=m.state==="JobComplete"?"JobComplete":"Failed";return e.bulkManager.updateJobState(d,g),e.bulkManager.updateJobCounts(d,m.numberRecordsProcessed??i,R.length),{totalRecords:p,successCount:k,failureCount:R.length,successIds:S,errors:R,aborted:!1,outcomes:b,...h.unattributedSuccessIds.length>0?{unmatchedIds:h.unattributedSuccessIds}:{}}}catch(l){throw e.bulkManager.updateJobState(d,"Failed"),l}}async*createChunkGenerator(e,t){let r=t??this.chunkSize;for(let s=0;s<e.length;s+=r)yield e.slice(s,s+r)}buildAbortedResult(e){return{totalRecords:e,successCount:0,failureCount:0,successIds:[],errors:[],aborted:!0}}};var _o=1e4,ci=fe.REST_API_BATCH_SIZE;function Wo(n){return!n.success&&n.errors.some(e=>e.startsWith("DUPLICATES_DETECTED"))}function Go(n){return!n.success&&Mr(n.errors,n.errorDetails)}function Uo(n,e){let[t,...r]=n.errors;return t===void 0?n:{...n,errors:[jr(t,e),...r]}}function pn(n){return typeof n.created=="boolean"?{created:n.created}:{}}function pi(n){return n.some(e=>e.fields.length>0)?{errorDetails:n}:{}}function li(n){let e=n===void 0?void 0:Sr(n);return e?pi([e]):{}}function fn(n,e){return n!=="insert"&&n!=="upsert"?[]:e.flatMap(t=>t.success&&typeof t.id=="string"&&t.id!==""&&(n==="insert"||t.created===!0)?[t.id]:[])}function zo(n,e){return!n||!e?n??e:{before:async(t,r,s,i)=>await n.before?.(t,r,s,i)??await e.before?.(t,r,s,i),sending:(t,r,s)=>{n.sending(t,r,s),e.sending(t,r,s)},opened:(t,r,s,i)=>{n.opened?.(t,r,s,i),e.opened?.(t,r,s,i)},answered:(t,r,s,i)=>{n.answered(t,r,s,i),e.answered(t,r,s,i)}}}function Oc(n,e){let t=r=>r==="insert"||r==="upsert";return{...e?{before:(r,s,i,o)=>e.before(r,s,i,o)}:{},sending:(r,s,i)=>{t(s)?n.sending?.(r,i,s==="upsert"?{upsert:!0}:void 0):n.writing?.(r,i)},opened:(r,s,i,o)=>{t(s)&&n.sending?.(r,i,{job:o,...s==="upsert"?{upsert:!0}:{}})},answered:(r,s,i)=>{t(s)?n.answered?.(r,fn(s,i)):i.length>0&&n.writing?.(r,i.length),e?.answered(r,s,i)}}}var ui=class{constructor(e){this.deps=e;this.wait=e.wait??(t=>Fr(t,e.signal)),this.retryOp=new St({retryConfig:e.retryConfig,signal:e.signal,onRetry:(t,r,s)=>{e.log(`[RETRY] sync attempt=${t} code=${r.originalError.statusCode} delay=${s}ms`)}})}deps;retryOp;wait;async insert(e,t,r,s){let i=zo(this.deps.calls,s),o=l=>this.deps.connection.sobject(e).create(l,{headers:tt()}),a="Insert failed after retries",d=await this.tryStreaming("insert",e,t,void 0,i)??await this.tryBulk("insert",e,t,void 0,i),c=d?await this.duplicatesAgain("insert",e,t,d,o,a,i):await this.executeRestBatches("insert",e,t,r,o,a,i);return this.locksAgain("insert",e,t,c,o,a,i)}async upsert(e,t,r,s){let i=c=>this.deps.connection.sobject(e).upsert(c,t,{headers:tt()}),o="Upsert failed after retries",a=await this.tryStreaming("upsert",e,r,t)??await this.tryBulk("upsert",e,r,t),d=a?await this.duplicatesAgain("upsert",e,r,a,i,o,this.deps.calls,t):await this.executeRestBatches("upsert",e,r,s,i,o,this.deps.calls,t);return this.locksAgain("upsert",e,r,d,i,o,this.deps.calls,t)}async update(e,t,r){let s=d=>this.deps.connection.sobject(e).update(d,{headers:tt()}),i="Update failed after retries",o=await this.tryStreaming("update",e,t)??await this.tryBulk("update",e,t),a=o?await this.duplicatesAgain("update",e,t,o,s,i):await this.executeRestBatches("update",e,t,r,s,i);return this.locksAgain("update",e,t,a,s,i)}async delete(e,t,r){let s=d=>this.deps.connection.sobject(e).destroy(d),i="Delete failed after retries",o=t.map(d=>({Id:d})),a=await this.tryBulk("delete",e,o)??await this.executeRestBatches("delete",e,t,r,s,i);return this.locksAgain("delete",e,t,a,s,i)}async tryStreaming(e,t,r,s,i=this.deps.calls){if(r.length<=_o)return;if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new Q(t);let o=await this.refusedBefore(i,t,e,r,s);if(o)return o;let a=new At({signal:this.deps.signal});i?.sending(t,e,r.length);let d={connection:Vt(this.deps.connection),bulkManager:this.deps.bulkManager,onProgress:(u,f)=>{this.deps.onProgress(u,f,`Streaming ${e} ${t}`)},onOpened:u=>i?.opened?.(t,e,r.length,u)},c=await a.executeChunked(d,t,e,a.createChunkGenerator(r),r.length,s);if(c.aborted)throw i?.answered(t,e,[]),new Q(t);this.logUnmatched(`Streaming ${e} ${t}`,c.unmatchedIds);let l=(c.outcomes??[]).map(u=>this.withExistingRecord(t,{id:u.id,success:u.success,errors:u.success?[]:[u.error??"Streaming error"],...pn(u),...u.success?{}:li(u.error)}));return i?.answered(t,e,l),l}async tryBulk(e,t,r,s,i=this.deps.calls){if(!this.deps.bulkExecutor.shouldUseBulkApi(r.length))return;if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new Q(t);let o={connection:Vt(this.deps.connection),bulkManager:this.deps.bulkManager,onProgress:(l,u)=>{this.deps.onProgress(l,u,`Bulk ${e} ${t}`)},signal:this.deps.signal,onOpened:l=>i?.opened?.(t,e,r.length,l)},a=await this.refusedBefore(i,t,e,r,s);if(a)return a;i?.sending(t,e,r.length);let d=await this.deps.bulkExecutor.executeBulk(o,t,e,r,s);if(d.aborted)throw i?.answered(t,e,[]),new Q(t);this.logUnmatched(`Bulk ${e} ${t}`,d.unmatchedIds);let c=d.outcomes.map(l=>this.withExistingRecord(t,{id:l.id,success:l.success,errors:l.success?[]:[l.error??"Bulk error"],...pn(l),...l.success?{}:li(l.error)}));return i?.answered(t,e,c),c}async refusedBefore(e,t,r,s,i){if(r==="delete"||!e?.before)return;let o=await e.before(t,r,s,i);if(o!==void 0)return this.deps.log(`[WARN] ${r} ${t}: ${s.length} row(s) not sent: ${o}`),s.map(()=>({success:!1,errors:[o]}))}async duplicatesAgain(e,t,r,s,i,o,a=this.deps.calls,d){let c=s.flatMap((p,m)=>m<r.length&&Wo(p)?[m]:[]);if(c.length===0||this.deps.signal?.aborted)return s;let l;try{l=await this.executeRestBatches(e,t,c.map(p=>r[p]),ci,i,o,a,d,c)}catch(p){if(!(p instanceof Q))throw p;l=p.written}let u=[...s];l.forEach((p,m)=>{u[c[m]]=p});let f=l.filter(p=>p.success).length;return this.deps.log(`[INFO] ${e} ${t}: ${c.length} row(s) a duplicate rule refused in the Bulk API job, which cannot carry the header that lets a rule's matches be saved, went again through REST with it: ${f} saved`+(l.length<c.length?`, ${c.length-l.length} not sent (cancelled)`:"")),u}async locksAgain(e,t,r,s,i,o,a=this.deps.calls,d){let c=new Map,l=await vr({outcomes:s.slice(0,r.length),locked:Go,written:p=>p.success,send:async p=>{let m;try{m=await this.executeRestBatches(e,t,p.map(y=>r[y]),ci,i,o,a,d,p)}catch(y){if(!(y instanceof Q))throw y;m=y.written}for(let y of p.slice(0,m.length))c.set(y,(c.get(y)??0)+1);return m},note:Uo,wait:p=>this.wait(p),stopped:()=>this.deps.signal?.aborted===!0}),u=Nr("row(s)",l);return u===void 0?s:(this.deps.log(`[INFO] ${e} ${t}: ${u}`),[...l.outcomes.map((p,m)=>{let y=c.get(m);return y===void 0?p:{...p,lockResends:y}}),...s.slice(r.length)])}logUnmatched(e,t){t&&t.length>0&&this.deps.log(`[WARN] ${e}: the job wrote ${t.length} record(s) no row was matched to: ${t.join(", ")}`)}withExistingRecord(e,t){if(t.success)return t;let r=Jt(t,this.deps.keyPrefixOf?.(e));return r.kind==="linked"?{...t,existingId:r.id}:t}async executeRestBatches(e,t,r,s,i,o,a=this.deps.calls,d,c){let l=[];for(let u=0;u<r.length;u+=s){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new Q(t,l);let f=r.slice(u,u+s);if(e!=="delete"){let y=await this.refusedBefore(a,t,e,f,d);if(y){l.push(...y);continue}if(this.deps.signal?.aborted)throw new Q(t,l)}a?.sending(t,e,f.length);let p=await this.retryOp.execute(()=>i(f));if(p.cancelled)throw a?.answered(t,e,[],c&&[]),new Q(t,l);let m=[];if(p.success&&p.result)for(let y of Array.isArray(p.result)?p.result:[p.result])m.push(this.restOutcome(t,y));else m.push(...f.map(()=>({success:!1,errors:[p.error?.message??o]})));l.push(...m),a?.answered(t,e,m,c?.slice(u,u+f.length))}return l}restOutcome(e,t){if(t.success)return{id:t.id,success:!0,errors:[],...pn(t)};let r=t.errors??[],s=r.map(br),i={id:t.id,success:!1,errors:[s[0]??"Unknown error"],...pi(r.map(wr))},o=Jt({success:!1,errors:s,duplicateMatchIds:r.flatMap(a=>Rr(a,e))},this.deps.keyPrefixOf?.(e));return o.kind==="linked"?{...i,existingId:o.id}:i}};function fi(n,e){if(n.operation==="delete")return[];let t=fr(n.fieldMappings,n.excludedFields??[]),r=new Set([...pr(n.fieldMappings),...n.addOnFields.map(i=>i.fieldApiName.toLowerCase())]),s=i=>!t.has(i.toLowerCase())||r.has(i.toLowerCase());return(e.fields??[]).flatMap(i=>i.isReference&&i.createable&&i.name!=="RecordTypeId"&&(i.referenceTo?.length??0)>0&&s(i.name)?[{field:i.name,referenceTo:i.referenceTo??[]}]:[])}function gi(n,e){let t=[...n].sort((R,k)=>R.insertOrder-k.insertOrder),r=new Map(t.map((R,k)=>[R.objectApiName,k])),s=new Set(t.filter(R=>R.operation!=="delete").map(R=>R.objectApiName)),i=new Map([...s].map(R=>[R.toLowerCase(),R])),o=[],a=new Set;for(let R of t){let k=R.objectApiName;if(s.has(k))for(let{field:g,referenceTo:w}of e.get(k)??[])for(let M of w){let A=i.get(M.toLowerCase());if(A===void 0||A===k)continue;let O=`${A}>${k}`;a.has(O)||(a.add(O),o.push({parent:A,child:k,field:g}))}}let d=qo(t.map(R=>R.objectApiName),o),c=new Map;d.forEach((R,k)=>{for(let g of R)c.set(g,k)});let l=d.map(R=>[...R].sort((k,g)=>(r.get(k)??0)-(r.get(g)??0))),u=l.map(R=>r.get(R[0])??0),f=l.map(()=>new Set);for(let{parent:R,child:k}of o){let g=c.get(R)??0,w=c.get(k)??0;g!==w&&f[w].add(g)}let p=new Set,m=[];for(;p.size<l.length;){let R;if(l.forEach((k,g)=>{p.has(g)||[...f[g]].some(w=>!p.has(w))||(R===void 0||u[g]<u[R])&&(R=g)}),R===void 0)break;p.add(R),m.push(...l[R])}let y=new Map(t.map(R=>[R.objectApiName,R])),h=m.flatMap(R=>{let k=y.get(R);return k?[k]:[]}),b=new Map(m.map((R,k)=>[R,k])),S=[];for(let R of h){let k=R.objectApiName,g=o.filter(w=>w.child===k&&(r.get(w.parent)??0)>(r.get(k)??0)&&(b.get(w.parent)??0)<(b.get(k)??0)).sort((w,M)=>(b.get(M.parent)??0)-(b.get(w.parent)??0));g.length>0&&S.push({objectApiName:k,after:g[0].parent,field:g[0].field})}return{ordered:h,order:{objects:m,moved:S,cycles:l.filter(R=>R.length>1)}}}function qo(n,e){let t=new Map(n.map(l=>[l,[]]));for(let{parent:l,child:u}of e)t.get(l)?.push(u);let r=0,s=new Map,i=new Map,o=[],a=new Set,d=[],c=l=>{s.set(l,r),i.set(l,r),r++,o.push(l),a.add(l);for(let p of t.get(l)??[])s.has(p)?a.has(p)&&i.set(l,Math.min(i.get(l)??0,s.get(p)??0)):(c(p),i.set(l,Math.min(i.get(l)??0,i.get(p)??0)));if(i.get(l)!==s.get(l))return;let u=[],f;do{if(f=o.pop(),f===void 0)break;a.delete(f),u.push(f)}while(f!==l);d.push(u)};for(let l of n)s.has(l)||c(l);return d}var Ko=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,de=n=>n.toLowerCase();function Ct(n){return n==="insert"||n==="upsert"}function Ho(n,e){let t=de(e);if(n.addOnFields.some(s=>de(s.fieldApiName)===t)||n.transformRules.some(s=>s.field&&de(s.field)===t))return;let r=n.fieldMappings.find(s=>s.type!=="exclude"&&de(s.targetField)===t);return r?(r.type==="direct"||r.type==="rename")&&(r.transformRules??[]).length===0?r.sourceField:void 0:e}function Yo(n){return n!==void 0&&[...n.source.active].some(e=>!n.target.active.has(e))}async function mi(n){let e=new Map,t=new ze(n.earlier),r=new Set,s=new Set([...n.leftOut].map(de)),i,o=async l=>{let u=await n.read(l);return u.length>0&&ht(l.objectApiName,u)&&(i=await n.standardPricebooks?.(),i&&t.noteMatched(i.source,i.target)),u},a=n.matched,d=(l,u)=>{a&&u>0&&a.set(l,(a.get(l)??0)+u)},c=(l,u)=>{let f=i?.source;return l===ge&&f!==void 0?u.filter(p=>p.Id===f).length:0};for(let l of n.ordered){let u=l.objectApiName;if(s.has(de(u))){if(!Ct(l.operation))continue;let A=await o(l);for(let O of A){let E=O.Id;typeof E=="string"&&E!==""&&t.noteRefused(E,u)}d(u,c(u,A)),r.add(de(u));continue}if(l.operation==="delete")continue;let f=(n.lookups.get(u)??[]).flatMap(({field:A,referenceTo:O})=>{let F=O.filter(N=>de(N)!==de(u)&&r.has(de(N))).length>0?Ho(l,A):void 0;return F!==void 0?[{field:A,source:F}]:[]}),p=a!==void 0&&Ct(l.operation),m=p&&u===ge&&await n.standardPricebooks?.()!==void 0,y=p&&u===Me&&await n.standardPricebooks?.()?await n.currencies?.():void 0,h=Yo(y);if(f.length===0&&!m&&!h)continue;let b=new Map,S=A=>{let O=`${A.parent}|${A.field}`,E=b.get(O);E?E.rows++:b.set(O,{...A,rows:1})},R=n.copied?.get(u),k=(await o(l)).filter(A=>{let O=A.Id;return!(R&&typeof O=="string"&&R.has(O.slice(0,15)))}),g=new Map;for(let A of f.length>0?k:[]){let O=A.Id,E=f.find(({source:N})=>{let $=A[N];return typeof $=="string"&&Ko.test($)&&t.refusedObjectOf($)!==void 0});if(!E)continue;let F={parent:t.refusedObjectOf(A[E.source])??"",field:E.field};S(F),typeof O=="string"&&O!==""&&g.set(O,F),Ct(l.operation)&&typeof O=="string"&&O!==""&&t.noteRefused(O,u)}if(m&&d(u,c(u,k)),h){let A=yt(Me,{records:k,sources:k,sourceIds:k.map(E=>typeof E.Id=="string"?E.Id:void 0)},i,y,E=>t.refusedObjectOf(E)!==void 0),O=0;for(let[E,F]of A.standsFor){if(g.has(E))continue;let N=t.refusedObjectOf(F)!==void 0?g.get(F):void 0;if(N){S(N),g.set(E,N),t.noteRefused(E,u);continue}O++}d(u,O)}let w=[...b.values()],M=w.reduce((A,O)=>A+O.rows,0);M>0&&(e.set(u,{objectApiName:u,rows:M,parent:w[0].parent,field:w[0].field,parents:w}),Ct(l.operation)&&r.add(de(u)))}return e}var hi=Symbol("not written");function Jo(n,e){if(n==="delete")return{rules:[],onChange:[]};let t=[],r=[];for(let{onChangeOnly:s,...i}of e)s&&n==="insert"?r.push(i.name):t.push(i);return{rules:t,onChange:r}}function Vo(n){return`${n.length} active validation rule(s) of the target left out of what may refuse these inserts: their formula holds only on a change of a record (ISCHANGED, PRIORVALUE, NOT(ISNEW())), which an insert never is \u2014 ${n.join(", ")}`}var Xo=/^012000000000000(AAA)?$/;function Zo(n){let e=n.RecordTypeId;return typeof e=="string"&&e.length>=15&&!Xo.test(e)}function hn(n){let e=n?.[nr];return typeof e=="string"&&e!==""}async function yi(n,e,t,r){let s=e.some(Zo)?await n.recordTypes():void 0,i=t.some(hn)||e.some(hn)?await n.currencies():void 0,o=n.later?.get(r),a=n.recordTypesUnderTheLease?.get(r);return{links:n.links,sources:t,...s?{recordTypes:s}:{},...i?{currencies:i,currencyChangesById:n.currencyChangesById}:{},...n.contactPoints?{contactPoints:n.contactPoints}:{},...o&&o.size>0?{later:o}:{},...a?{recordTypesUnderTheLease:a}:{},...n.createdWithoutRecordType?{createdWithoutRecordType:n.createdWithoutRecordType}:{}}}function gn(n){let e=new Map;for(let t of n?.cycles??[])t.forEach((r,s)=>{s<t.length-1&&e.set(r,new Set(t.slice(s+1)))});return e}function Qo(n,e,t){return{...n,...e.set?{lookupsSetAfter:{...e.set,after:[...t]}}:{},...e.leftOut.length>0?{lookupsLeftOut:[...n.lookupsLeftOut??[],...e.leftOut]}:{}}}function wi(n,e){return e.flatMap((t,r)=>{let s=n[r];return t.success&&s!==void 0?[s]:[]})}function Si(n,e){let t=e.encryptedLeftOut??[];return t.length>0?{...n,encryptedLeftOut:[...t]}:n}function re(n){return n.slice(0,15)}function ea(n,e){if(!e)return n;if(e.unread!==void 0)return{...n,errors:[...n.errors,`The contact roles the platform wrote with the run's opportunities were not looked up, so written as read: an opportunity may hold the role of its contact twice. ${e.unread}`]};let{records:t,given:r,refusal:s,alike:i}=e,o=i!==void 0?{...n,errors:[...n.errors,Xn(i)]}:n;return t===0?o:{...o,skipped:o.skipped+t,writtenByThePlatform:{records:t,given:r,...s!==void 0?{refusal:s}:{}}}}function ta(n,e,t){if(n.objectApiName!==X||!ce(n.operation)||!t.sentWithAContact||e.records.length===0)return{prepared:e,linked:0};let r=a=>typeof a=="string"&&a!==""?t.targetOf(a):void 0,s=e.records.map((a,d)=>({OpportunityId:r(a.OpportunityId),[oe]:r(a[oe]),IsPrimary:e.sources[d]?.IsPrimary??a.IsPrimary})),i=new Set(zt(s,a=>t.contactSentWith(a)));if(i.size===0)return{prepared:e,linked:0};for(let a of i){t.roleLinkedFor(String(s[a].OpportunityId));let d=e.sourceIds[a];d!==void 0&&t.noteWritten(d,d)}let o=(a,d)=>!i.has(d);return{prepared:{...e,records:e.records.filter(o),sourceIds:e.sourceIds.filter(o),sources:e.sources.filter(o),unsettled:e.unsettled.length===e.records.length?e.unsettled.filter(o):e.unsettled},linked:i.size}}var na=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,mn=200;function ra(n,e,t){let r=c=>{let l=t?.fields?.find(u=>u.name===c);return l?.nillable===!1&&l.defaultedOnCreate!==!0},s=[],i=new Set,o=new Set,a=0;for(let[c,l]of n){let u=e[c]==="insert"?l.filter(r):[];if(u.length>0){s.push(c);for(let f of u)i.add(f);continue}a++;for(let f of l)o.add(f)}let d=[];return a>0&&d.push(`${a} record(s) would be written without ${[...o].sort().join(", ")}: a lookup held an id from the source org that the target does not have, which the run learns from its first refusal and sends the record again without the lookups it did not settle.`),s.length>0&&d.push(`${s.length} record(s) would be refused: a lookup held an id from the source org that the target does not have, and sent again without the lookups the run did not settle, the record lacks ${[...i].sort().join(", ")}, which the target requires (REQUIRED_FIELD_MISSING).`),{refused:s,notes:d}}function sa(n){return`${n} record(s) would be linked to the contact role the platform writes with their opportunity, for its contact, not written.`}function yn(n){let e=n.alreadyLinked,t=n.alreadyCopied-e;return{...t>0?{alreadyCopied:t}:{},...e>0?{alreadyLinked:e}:{}}}function ia(n,e){return e.alreadyCopied===0?n:{...n,skipped:n.skipped+e.alreadyCopied,...yn(e)}}function bi(n,e){return`What earlier runs of this configuration copied could not be read (${n}), and ${e.map(t=>t.objectApiName).join(", ")} ${e.length===1?"is":"are"} inserted: the records they copied would be copied a second time. Nothing was written.`}var oa="SYNC_EARLIER_UNREAD",aa=new Set(["account","contact"]);function ce(n){return n==="insert"||n==="upsert"}function da(n,e,t=[],r=new Set){if(e<=0||!ce(n.operation))return;let s=n.objectApiName.toLowerCase(),i=new Set([...r].map(c=>c.toLowerCase())),o=t.flatMap(({referenceTo:c})=>c.map(l=>l.toLowerCase())),a=o.includes(s),d=o.some(c=>i.has(c));if(!(!a&&!d))return{...a?{within:e}:{},...d?{cycle:e}:{}}}function Ri(n,e,t,r=new Map,s=new Set,i=new Map,o=new Map,a=new Set,d,c={}){let l=0,u=0,f=n.map(g=>{let w=g.objectApiName,M=e.get(w)??{rows:0},A=t.get(w)??new Set,O=A.size,E=Math.min(O,M.rows),F=Math.min([...A].filter(x=>a.has(x)).length,E);u+=F,l+=E-F;let $=(r.has(w)?0:i.get(w)?.rows??0)+(o.get(w)??0),T=c.keys?.get(w),v=Math.max(0,M.rows-O-$),j=da(g,v,c.lookups?.get(w),c.later?.get(w));return{objectApiName:w,operation:g.operation,rows:v,...M.personAccounts!==void 0?{personAccounts:M.personAccounts}:{},batchSize:g.batchSize,...T?{overwriteKey:T}:{},...j?{lookupPasses:j}:{}}}),p=f.flatMap(g=>{let w=r.get(g.objectApiName);return w?[{...g,why:w.why,...w.key?{key:w.key}:{}}]:[]}),m=f.find(g=>g.objectApiName===X),y=m&&d!==void 0?Math.min(d,m.rows):0;m&&y>0&&(m.rows-=y);let h=f.filter(g=>!r.has(g.objectApiName)),b=h.filter(g=>g.rows>0&&ce(g.operation)&&s.has(g.objectApiName)).length,S=[...i.values()].filter(({objectApiName:g})=>!r.has(g)),R=d===void 0?ca(n,h):0,k=h.filter(g=>c.typed?.has(g.objectApiName)).length;return{objects:h,alreadyCopied:l,...u>0?{alreadyLinked:u}:{},...p.length>0?{unwritable:p}:{},...S.length>0?{heldBack:S}:{},...b>0?{readBack:b}:{},...R>0?{rolesByThePlatform:R}:{},...y>0?{rolesLinked:y}:{},...k>0?{describedAgain:k}:{}}}var Ee="Opportunity";function ca(n,e){let t=o=>e.find(a=>a.objectApiName===o&&ce(a.operation)),r=t(Ee),s=t(X);return!r||!s||n.find(o=>o.objectApiName===Ee)?.excludedFields.includes(oe)?0:Math.min(r.rows,s.rows)}function la(n,e,t){return{objectApiName:n.objectApiName,operation:n.operation,processed:0,success:0,failed:0,skipped:t,conflictCount:0,errors:[`${e.message} Left out of the run, as confirmed before it wrote.`]}}function ki(n,e,t){if(ce(e.operation))for(let r of t){let s=r?.Id;typeof s=="string"&&s!==""&&n.noteRefused(s,e.objectApiName)}}function Pt(n,e,t){let r=[];for(let[s,i]of t){let o=n.targetOf(i);o!==void 0?n.noteMatched(s,o):ce(e.operation)&&n.refusedObjectOf(i)!==void 0&&(n.noteRefused(s,e.objectApiName),r.push(s))}return r}function Oi(n,e,t){let r=rn(e,t),s=on(n,{...e,prices:r});return t.length===0?s:{...s,processed:s.processed+t.length,failed:s.failed+t.length,errors:[...s.errors,sn(n.objectApiName,t.length)]}}function Ai(n){let e=Gn(n.objects);return e.length>0?`${Un(e)} Nothing was read or written.`:void 0}function Ci(n){let e=qn(n.objects);return e.length>0?`${Kn(e)} Nothing was read or written.`:void 0}var Pi=class{deps;constructor(e){this.deps=e}async execute(e){let t=Date.now(),r=`sync-${Date.now()}`,s=[],i=Ai(e);if(i!==void 0)throw new $e(i,{...se(e.id,r,[],t,"failure"),error:i},Wn);let o=Ci(e);if(o!==void 0)throw new $e(o,{...se(e.id,r,[],t,"failure"),error:o},zn);let{ordered:a,order:d,refused:c,typed:l,lookups:u,keys:f}=await this.writeOrderOf(e.objects),p=gn(d),m=this.deps.queryTargetRows?l:new Set,y=this.deltaLoadOf(e),h=(C,P)=>new $e(C,{...se(e.id,r,[],t,"failure"),error:C},P),b;try{b=await this.planFiles(e,a,y)}catch(C){let P=C instanceof Error?C.message:String(C);throw new ae(P,se(e.id,r,[],t,"failure"),C)}if(b?.storage.shortfall)throw new ae(`${b.storage.shortfall} Nothing was written.`,{...se(e.id,r,[],t,"failure"),files:b.storage});let S=await this.earlierLinks(e),R=a.filter(C=>C.operation==="insert");if(S.unread!==void 0&&R.length>0)throw h(bi(S.unread,R),oa);let k;try{k=await this.alreadyCopiedOf(e,a,S.links)}catch(C){let P=`What earlier runs of this configuration copied could not be looked up in the target (${C instanceof Error?C.message:String(C)}), so nothing was written.`;throw new ae(P,{...se(e.id,r,[],t,"failure"),error:P},C)}let g=await this.countRun(e,a,y,this.deps.writeGate!==void 0);if(this.deps.writeGate&&"unread"in g){let C=`The records to write could not be counted (${g.unread}), so nothing was written.`+un(g.unread);throw new ae(C,{...se(e.id,r,[],t,"failure"),error:C})}let w=new Map,M=this.standardPricebooksOnce(),A=this.currenciesOnce(),O=y===void 0?new Map:void 0;if(this.deps.writeGate&&"counted"in g){let C;try{C=await this.heldBackOfRun(e,a,c,u,y,S.links,k,M,A,O)}catch(B){let q=B instanceof Error?B.message:String(B);throw new ae(q,{...se(e.id,r,[],t,"failure"),error:q},B)}let P=Ri(a,g.counted,k,c,m,C.heldBack,C.matched,S.linked,await this.rolesLinkedAtTheGate(e,a,c,C.heldBack,k,S.links,O),{keys:f,...this.deps.describeTargetFieldsAgain?{typed:l}:{},lookups:u,later:p}),{answer:D}=await this.deps.writeGate.hold(P);if(!D.go)throw h(D.message,D.code);for(let B of P.unwritable??[])w.set(B.objectApiName,B.rows)}let E=this.deps.leaseOfTheGate?.(),F=E&&E.assigned>0?await this.recordTypesReadAgain(a.map(C=>C.objectApiName).filter(C=>l.has(C)&&!w.has(C))):void 0,N=new Map,$=async()=>{let C=E;E=void 0,await C?.giveBack().catch(()=>{});for(let[P,D]of await this.readBackRecordTypes(N))for(let B=s.length-1;B>=0;B--)if(s[B].objectApiName===P){s[B]={...s[B],recordTypeGiven:D};break}},T=new ze(S.links),v=this.recordTypesOnce(),j=new Map,x=zs(e),_=this.deps.idMap,z={sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId},H=Promise.resolve(),G,ne=(C,P,D)=>{if(!_)return;let B=ua(C.operation,P,D);for(let[q,Y]of[[B.written,!1],[B.linked,!0]])q.length!==0&&(H=H.then(()=>_.record(e.id,z,C.objectApiName,q,Y).catch(pe=>{G??=pe instanceof Error?pe.message:String(pe)})))},Te=0,Se=(C,P)=>{if(P.length===0)return;this.deps.creations?.deleted?.(C,P),Te+=P.length,T.noteDeleted(P);let D=_?.forget?.bind(_);D&&(H=H.then(()=>D(e.id,z,P).then(()=>{},B=>{G??=B instanceof Error?B.message:String(B)})))},V=this.deps.creations,be=new Map,ie=0,I=(C,P)=>{if(!V)return;let D=fn(C.operation,P);if(D.length===0)return;let B=C.objectApiName;V.noteUnanswered?V.noteUnanswered(B,D):V.note(B,D),be.set(B,(be.get(B)??0)+D.length)},W=(C,P)=>{V&&(V.note(C,[P]),ie++)},Z=!1,me=!1,Be=!1,Xi=async C=>{let P=await V?.flush();await H;let D=[];return S.unread!==void 0&&!Be&&(Be=!0,D.push(`What earlier runs of this configuration wrote could not be read (${S.unread}): a lookup at a record one of them wrote went as the source holds it.`)),P!==void 0&&!Z&&(Z=!0,D.push(`What this run created could not all be kept (${P}): removing the run may leave some of it in the target.`)),G!==void 0&&!me&&(me=!0,D.push(`Which record of the target each record this run wrote became could not all be kept (${G}): a later run may send a lookup at one of them as the source holds it.`)),D.length===0?C:{...C,errors:[...C.errors,...D]}},le=async C=>{s.push(await Xi(C))},Re=new Map,Zi=new Set((d?.cycles??[]).map(C=>C[C.length-1])),Pn=(C,P)=>{for(let D=s.length-1;D>=0;D--)if(s[D].objectApiName===C){s[D]=Qo(s[D],P,[...p.get(C)??[]]);return}},Xe=new Map,Qi=(C,P)=>{for(let D=s.length-1;D>=0;D--)if(s[D].objectApiName===C){s[D]={...s[D],errors:[...s[D].errors,P]};return}},Ft=(C,P,D)=>{for(let B=s.length-1;B>=0;B--){let q=s[B];if(q.objectApiName!==C)continue;if(!q.delta)return;let Y=(q.delta.lookupsOwed??0)+P;s[B]={...q,delta:{...q.delta,...D!==void 0?{recorded:D}:{},...Y>0?{lookupsOwed:Y}:{}}};return}},eo=async()=>{for(let[C,P]of[...Re]){Re.delete(C),await this.deps.pauseGate?.whilePaused(this.deps.signal);let D=this.deps.signal?.aborted?{leftOut:nn(P.pending),unset:tn(P.pending)}:await this.deps.dataSync.setLookups(P.objectConfig,P.pending,T,!0);"set"in D&&D.set&&V?.touched?.(C,D.set.records),Pn(C,D);let B=Xe.get(C);if(Xe.delete(C),D.unset===0){let q=B?.();q!==void 0&&Ft(C,0,q)}else Ft(C,D.unset)}},jt=()=>{for(let[C,P]of[...Re])Re.delete(C),Xe.delete(C),Pn(C,{leftOut:nn(P.pending)}),Ft(C,tn(P.pending))},Ze=C=>{let P=qs(x,C.objectResults.some(Y=>Y.success>0)),D={...C,...b?{files:b.storage}:{},...P?{contactPoints:P}:{}},B=V?.overwrittenCount?.()??0,q=V?.deleted?Te:0;return!V||be.size===0&&ie===0&&B===0&&q===0?D:{...D,created:{runId:V.runId,objects:[...be].map(([Y,pe])=>({objectApiName:Y,count:pe})),files:ie,...B>0?{overwritten:B}:{},...q>0?{deleted:q}:{}}}},In="counted"in g?[...g.counted.values()].reduce((C,{rows:P})=>C+P,0):void 0,vt=this.isGrappeActive(In);vt&&this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:r,totalPartitions:a.length,totalRecords:In}});let En=()=>{if(!vt)return;let C=0,P=0;for(let D of s)C+=D.processed,P+=D.failed;this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:r,totalProcessed:C,totalFailed:P}})},ke=async(C,P)=>(jt(),await $(),En(),await V?.flush(),await H,Ze(fa(e.id,r,s,t,C,P))),Nt=0;for(let[C,P]of a.entries()){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return ke(a.slice(C));let D=c.get(P.objectApiName),B=w.get(P.objectApiName);if(D&&B!==void 0){let L=la(P,D,B);try{await this.noteLeftOutRefused(e,P,y,{links:T,...S.linked?{earlierLinked:S.linked}:{},recordTypes:v,currencies:A,currencyChangesById:j,standardPricebooks:M,...O?{gateReads:O}:{}},k.get(P.objectApiName))}catch(U){let he=U instanceof Error?U.message:String(U);throw await le({...L,errors:[...L.errors,he]}),jt(),new ae(he,Ze(se(e.id,r,s,t,"failure")),U)}await le(L);continue}let q=new it,{plan:Y,mark:pe}=await this.readPlan(e,P,y),Oe={changedSince:Y?.read==="delta"?Pe(Y.since):void 0,rows:0,cut:!1},Ae=(L,U)=>Y?{...L,delta:je(Y,Oe.rows,U)}:L,Qe=b?.objects.get(P.objectApiName),xt=Qe?new Map:void 0,Dt;try{Dt=await this.syncObject(e,P,q,{links:T,...S.linked?{earlierLinked:S.linked}:{},recordTypes:v,currencies:A,currencyChangesById:j,standardPricebooks:M,...x?{contactPoints:x}:{},later:p,...F?{recordTypesUnderTheLease:F}:{},createdWithoutRecordType:N,...O?{gateReads:O}:{}},Y?Oe:void 0,xt,V||_?(L,U)=>{I(P,L),ne(P,L,U)}:void 0,k.get(P.objectApiName),(p.get(P.objectApiName)?.size??0)>0?L=>{let U=Re.get(P.objectApiName);U?U.pending.push(...L):Re.set(P.objectApiName,{objectConfig:P,pending:L})}:void 0)}catch(L){if(L instanceof Q){let U=Ie(qe(P.objectApiName,P.operation,L.written,L.notes,L.lookupsLeftOut,L.writtenWithoutFields),q);return(U.processed>0||U.skipped>0)&&await le(Ae(U)),ke(a.slice(C))}throw await le(Ae(Ie({...It(P),failed:1,errors:[L instanceof Error?L.message:String(L)]},q))),jt(),new ae(L instanceof Error?L.message:String(L),Ze(se(e.id,r,s,t,"failure")),L)}if(Dt===hi){let L=Ie(It(P),q);return L.skipped>0&&await le(Ae(L)),ke(a.slice(C))}let J=Dt,Tn=!0;if(Qe&&xt&&e.files){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return await le(Ae(J)),ke(a.slice(C+1),Ii(P));let L=await ni({config:e,option:e.files,objectApiName:P.objectApiName,planned:Qe,written:xt,deps:this.deps.files,signal:this.deps.signal,waitIfPaused:()=>this.deps.pauseGate?.whilePaused(this.deps.signal)??Promise.resolve(),onCreated:W});if(J={...J,files:L.outcome,errors:[...J.errors,...L.notes]},Tn=L.outcome.failed===0&&L.outcome.pastRunCap===0&&L.unplanned===0,L.cancelled)return await le(Ae(J)),ke(a.slice(C+1),Ii(P))}let Ce;if(Y?.read==="delta"&&e.propagateDeletes===!0&&Oe.changedSince){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return await le(Ae(J)),ke(a.slice(C));try{Ce=await this.carryDeletions(P,Oe.changedSince,L=>Se(P.objectApiName,L))}catch(L){if(!(L instanceof Q))throw L;let U=qe(P.objectApiName,"delete",L.written);return await le(Ae({...J,errors:[...J.errors,...U.errors,...L.notes]},{deleted:U.success,deleteFailed:U.failed,notes:[],complete:!1})),ke(a.slice(C))}J={...J,errors:[...J.errors,...Ce.notes]}}let Mn=Oe.lookupsUnset??0,no=J.failed===0&&Tn&&!Oe.cut&&Mn===0&&(Ce===void 0||Ce.deleteFailed===0&&Ce.error===void 0&&Ce.complete),Fn=(L,U,he)=>{let vn=Qe?.filesSeen;try{return this.deps.deltaStore?.record(e.id,{sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:P.objectApiName,watermark:L,fingerprint:U,recordedAt:new Date().toISOString(),...vn!==void 0?{filesSeen:vn}:{}}),L}catch(Lt){he(`The watermark could not be saved, so the next run reads from the previous one: ${Lt instanceof Error?Lt.message:String(Lt)}`);return}},jn;if(Y&&pe!==null&&no){let{fingerprint:L}=Y,U=P.objectApiName;Re.has(U)?Xe.set(U,()=>Fn(pe,L,he=>Qi(U,he))):jn=Fn(pe,L,he=>{J={...J,errors:[...J.errors,he]}})}Y&&(J={...J,delta:je(Y,Oe.rows,Ce,jn,Mn)}),await le(J),Zi.has(P.objectApiName)&&await eo(),vt&&(Nt++,this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:`sync-partition-${Nt}`,percentage:Math.round(Nt/a.length*100),processedRecords:J.processed}}))}await $();let to=Ei(s);return En(),await V?.flush(),await H,Ze(se(e.id,r,s,t,to))}async recordTypesReadAgain(e){let t=this.deps.describeTargetFieldsAgain,r=new Map;return t&&await Promise.all(e.map(async s=>{try{r.set(s,(await t(s)).recordTypes??[])}catch{}})),r}async readBackRecordTypes(e){let t=this.deps.queryTargetRows,r=new Map;return await Promise.all([...e].map(async([s,{given:i,types:o,ids:a}])=>{if(!t||a.length===0){r.set(s,i);return}try{let d=await t(hs(s,a));r.set(s,{...i,readBack:ys(d,o)})}catch(d){let c=d instanceof Error?d.message:String(d);r.set(s,{...i,readBack:{read:0,types:[],unread:c}})}})),r}async earlierLinks(e){let t=this.deps.idMap;if(!t)return{};try{let r={sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId},s=await t.load(e.id,r);if(!s)return{};let i=await t.linked?.(e.id,r);return{links:s,...i!==void 0&&i.size>0?{linked:i}:{}}}catch(r){return{unread:r instanceof Error?r.message:String(r)}}}recordTypesOnce(){let e;return()=>{let t=this.deps.recordTypes;return t?(e??=t().catch(r=>{throw new Error(`The record types of the two orgs could not be read, so none of these records was sent: ${r instanceof Error?r.message:String(r)}`)}),e):Promise.resolve(void 0)}}currenciesOnce(){let e;return()=>{let t=this.deps.currencies;return t?(e??=t().catch(()=>{}),e):Promise.resolve(void 0)}}standardPricebooksOnce(){let e;return()=>{let t=this.deps.standardPricebooks;return t?(e??=t().catch(()=>{}),e):Promise.resolve(void 0)}}async pricesSettled(e,t,r){let s=e.objectApiName,i=e.operation!=="delete"&&ht(s,t.sources)?await r.standardPricebooks?.():void 0;i&&r.links.noteMatched(i.source,i.target);let o=i&&s===Me&&t.sources.some(hn)?await r.currencies():void 0;return yt(s,t,i,o,a=>r.links.refusedObjectOf(a)!==void 0)}deltaLoadOf(e){if(e.mode==="delta")return!this.deps.deltaStore||!this.deps.deltaReads?null:this.deps.deltaStore.load(e.id)}async readPlan(e,t,r){if(r===void 0)return{plan:null,mark:null};let s=We(e,t,r),i=this.deps.deltaReads;if(!i||s.read==="full"&&s.reason==="not_saved")return{plan:s,mark:null};try{return{plan:s,mark:await i.latestModstamp(t.objectApiName)}}catch{return{plan:{read:"full",reason:"no_modstamp",fingerprint:s.fingerprint},mark:null}}}async carryDeletions(e,t,r){let s=await this.tallyObjectDeletions(e,t);if("error"in s)return{deleted:0,deleteFailed:0,error:s.error,notes:[s.error],complete:!1};let{tally:i,notes:o}=s;if(i.ids.length===0)return{deleted:0,deleteFailed:0,notes:o,complete:!i.truncated};let a={...e,operation:"delete",fieldMappings:[],transformRules:[],addOnFields:[]},d;try{d=await this.deps.dataSync.write(a,i.ids.map(l=>({Id:l})))}catch(l){throw l instanceof Q&&r(wi(i.ids,l.written)),l}r(wi(i.ids,d.outcomes));let c=qe(e.objectApiName,"delete",d.outcomes,d.notes);return{deleted:c.success,deleteFailed:c.failed,notes:[...c.errors,...o],complete:!i.truncated}}async tallyObjectDeletions(e,t){let r=this.deps.deltaReads;if(!r)return{error:"Deletions need the source's recycle bin, and none was given."};let s=Ht(e);if("refused"in s)return{error:s.refused};let i=ot(e.where,t)??"";try{let o=await hr(r,e,s,i,a=>{if(s.sourceField==="Id")return a.Id;let d=this.deps.fieldMapping.apply(a,e.fieldMappings,e.excludedFields);return this.deps.transformPipeline.transformRecord(d,e)[s.keyField]});return{tally:o,notes:yr(o,s.keyField)}}catch(o){if(this.deps.signal?.aborted)throw new Q(e.objectApiName,[]);return{error:`The source's deletions could not be read, so none was carried; the next run looks for them again: ${o instanceof Error?o.message:String(o)}`}}}async countRun(e,t,r,s){let i=this.deps.countSource;if(!s&&!this.deps.grappeConfig?.enabled||!i)return{none:!0};let o=new Map;try{for(let a of t){let d=r===void 0?null:We(e,a,r),c=d?.read==="delta"?{changedSince:Pe(d.since)}:void 0,l=c?await i(e.sourceOrgId,a,c):await i(e.sourceOrgId,a);if(!Number.isFinite(l)||l<0)throw new Error(`the source answered no count of ${a.objectApiName}`);let u=s&&l>0&&this.deps.countPersonAccounts&&aa.has(a.objectApiName.toLowerCase())?await this.deps.countPersonAccounts(a,c):void 0;o.set(a.objectApiName,{rows:l,...u!==void 0&&u>0?{personAccounts:u}:{}})}}catch(a){return{unread:a instanceof Error?a.message:String(a)}}return{counted:o}}async alreadyCopiedOf(e,t,r){let s=new Map,i=this.deps.readSourceIds,o=this.deps.findInTarget;if(!r||r.size===0||!i||!o)return s;for(let a of t){if(a.operation!=="insert")continue;if(this.deps.signal?.aborted)break;let d=new Map;for(let f of await i(a)){let p=r.get(re(f));p!==void 0&&d.set(re(f),p)}if(d.size===0)continue;let c=await o(e.targetOrgId,a,"Id",[...new Set(d.values())]),l=new Set([...c.keys()].map(f=>f.slice(0,15))),u=new Set;for(let[f,p]of d)l.has(p.slice(0,15).toLowerCase())&&u.add(f);u.size>0&&s.set(a.objectApiName,u)}return s}async writeOrderOf(e){let t=this.deps.describeTargetFields,r=new Map,s=new Set,i=new Map;if(!t)return{ordered:[...e].sort((d,c)=>d.insertOrder-c.insertOrder),refused:r,typed:s,lookups:new Map,keys:i};let o=new Map,a=[];for(let d of e){if(d.operation==="delete"){a.push(d);continue}let c=await Us(t,d.objectApiName,d.operation,d.externalIdField);"refused"in c&&r.set(d.objectApiName,c.refused);let l="target"in c&&c.target?Gs(Ws(d,c.target),c.target):d;a.push(l),!("refused"in c)&&(l.operation==="update"||l.operation==="upsert"||l.objectApiName===X)&&i.set(d.objectApiName,Ls(l.operation==="upsert"?l.externalIdField??"Id":"Id","target"in c?c.target:void 0)),"target"in c&&c.target&&(o.set(d.objectApiName,fi(l,c.target)),ce(d.operation)&&(c.target.recordTypes??[]).some(u=>!u.master)&&s.add(d.objectApiName))}return{...gi(a,o),refused:r,typed:s,lookups:o,keys:i}}async heldBackOfRun(e,t,r,s,i,o,a,d,c,l){let u=new Map,f=t.some(m=>ce(m.operation)&&(m.objectApiName===ge||m.objectApiName===Me));return r.size===0&&!f?{heldBack:new Map,matched:u}:{heldBack:await mi({ordered:t,lookups:s,leftOut:new Set(r.keys()),...o?{earlier:o}:{},copied:a,standardPricebooks:d,currencies:c,matched:u,read:async m=>{let y=i===void 0?null:We(e,m,i);if(y?.read==="delta")return this.deps.querySource(e.sourceOrgId,m,{changedSince:Pe(y.since)});let h=await this.deps.querySource(e.sourceOrgId,m);return l?.set(m.objectApiName,h),h}}),matched:u}}async rolesLinkedAtTheGate(e,t,r,s,i,o,a){let d=h=>t.find(b=>b.objectApiName===h),c=d(Ee),l=d(X);if(!c||!l||!ce(l.operation))return;if(!this.deps.queryTargetRows||c.excludedFields.includes(oe))return 0;if(!a||c.operation!=="insert")return;let u=h=>h.fieldMappings.length===0&&h.addOnFields.length===0&&h.transformRules.length===0;if(!u(c)||!u(l)||[Ee,X,Ut].some(h=>r.has(h)||s.has(h)))return;let p=await this.deps.describeTargetFields?.(Ee).catch(()=>{});if(!p)return;if(!p.creatable.has(oe))return 0;let m=async h=>{let b=a.get(h.objectApiName);if(b)return b;let S=await this.deps.querySource(e.sourceOrgId,h);return a.set(h.objectApiName,S),S},y=h=>typeof h.Id=="string"&&h.Id!==""?h.Id:void 0;try{let h=new Set([...o?.keys()??[]].map(re)),b=d(Ut);if(b&&ce(b.operation)&&t.indexOf(b)<t.indexOf(c))for(let g of await m(b)){let w=y(g);w&&h.add(re(w))}let S=g=>i.get(g)??new Set,R=new Map;for(let g of await m(c)){let w=y(g),M=g[oe];!w||typeof M!="string"||M===""||S(Ee).has(re(w))||!h.has(re(M))||R.set(re(w),M)}if(R.size===0)return 0;let k=(await m(l)).filter(g=>{let w=y(g);return w!==void 0&&!S(X).has(re(w))});return zt(k,g=>R.get(re(g))).length}catch{return}}isGrappeActive(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&e!==void 0&&e>=t.autoActivateThreshold)}async simulate(e){let t=Ai(e);if(t!==void 0)throw new Error(t);let r=Ci(e);if(r!==void 0)throw new Error(r);let s=Date.now(),i=[],{ordered:o,order:a,refused:d,typed:c,lookups:l,keys:u}=await this.writeOrderOf(e.objects),f,p,m,y=await this.validationRulesOf(o),h=(F={})=>({configId:e.id,operationId:`sync-simulation-${s}`,direction:e.direction,conflictStrategy:e.conflictStrategy,objects:i,duration:Date.now()-s,timestamp:new Date().toISOString(),...f?{files:f.storage}:{},...y.unread!==void 0?{validationRulesUnread:y.unread}:{},...a?{writeOrder:a}:{},...p?{writeCheck:p}:{},...m!==void 0?{writeCheckUnread:m}:{},...F}),b=this.deltaLoadOf(e);try{f=await this.planFiles(e,o,b)}catch(F){return this.deps.signal?.aborted?h({cancelled:!0}):h({error:F instanceof Error?F.message:String(F)})}let S=await this.earlierLinks(e),R=o.filter(F=>F.operation==="insert");if(S.unread!==void 0&&R.length>0)return h({error:bi(S.unread,R)});let k;try{k=await this.alreadyCopiedOf(e,o,S.links)}catch(F){return this.deps.signal?.aborted?h({cancelled:!0}):h({error:F instanceof Error?F.message:String(F)})}let g=this.deps.writeGate,w=this.standardPricebooksOnce(),M=this.currenciesOnce(),A=b===void 0?new Map:void 0,O=g?await this.countRun(e,o,b,!0):void 0;if(g&&O&&"unread"in O&&(m=`${O.unread}${un(O.unread)}`),g&&O&&"counted"in O)try{let F=await this.heldBackOfRun(e,o,d,l,b,S.links,k,w,M,A);p=await g.measure(Ri(o,O.counted,k,d,this.deps.queryTargetRows?c:new Set,F.heldBack,F.matched,S.linked,await this.rolesLinkedAtTheGate(e,o,d,F.heldBack,k,S.links,A),{keys:u,typed:c,lookups:l,later:gn(a)}))}catch(F){m=F instanceof Error?F.message:String(F)}let E={links:new ze(S.links),...S.linked?{earlierLinked:S.linked}:{},recordTypes:this.recordTypesOnce(),currencies:M,currencyChangesById:new Map,standardPricebooks:w,later:gn(a),...A?{gateReads:A}:{}};for(let[F,N]of o.entries()){if(this.deps.signal?.aborted)return h({cancelled:!0});this.deps.onSimulationProgress?.(F,o.length,N.objectApiName);try{let $=await this.simulateObject(e,N,b,E,k.get(N.objectApiName),d.get(N.objectApiName)),T=f?.objects.get(N.objectApiName),{rules:v,onChange:j}=Jo(N.operation,y.byObject.get(N.objectApiName)??[]),x=[...$.notes,...T?.notes??[],...j.length>0?[Vo(j)]:[]];i.push({...$,...T?{files:T.outcome}:{},notes:x,...v.length>0?{validationRules:v}:{}})}catch($){return this.deps.signal?.aborted?h({cancelled:!0}):h({error:$ instanceof Error?$.message:String($),failedObject:N.objectApiName})}}if(p){let F=new Set([...p.objects.map(G=>G.objectApiName),...(p.rolesLinked??0)>0?[X]:[]]),N=i.filter(G=>F.has(G.objectApiName)).reduce((G,ne)=>G+(ne.operation==="delete"?ne.delete:ne.insert+ne.update),0),$={...p};delete $.rolesByThePlatform,delete $.rolesLinked;let T=i.filter(G=>F.has(G.objectApiName)).reduce((G,ne)=>G+(ne.writtenByThePlatform??0),0),v=(p.rolesLinked??0)-T,j=p.total+v,x=j-N,_={objectApiName:X,rows:0},z=$.objects.some(G=>G.objectApiName===X)?$.objects:[...$.objects,_],H=j>0&&N===0;p={...$,objects:z.map(G=>G.objectApiName===X?{...G,rows:Math.max(0,G.rows+v)}:G).filter(G=>G.rows>0),total:j,...T>0?{rolesLinked:T}:{},...x>0?{notWritten:x}:{},...H?{total:0}:{},...H&&$.verdict==="writes"?{verdict:"nothing"}:{}}}return h()}async validationRulesOf(e){let t=this.deps.readValidationRules,r=e.filter(i=>i.operation!=="delete").map(i=>i.objectApiName),s=new Map;if(!t||r.length===0)return{byObject:s};try{for(let{objectApiName:i,...o}of await t(r))s.set(i,[...s.get(i)??[],o]);return{byObject:s}}catch(i){return{byObject:s,unread:i instanceof Error?i.message:String(i)}}}async simulateObject(e,t,r,s,i,o){let a=this.deps.findInTarget;if(!a)throw new Error("A simulation needs to look records up in the target org.");let d=new it,{plan:c}=await this.readPlan(e,t,r),l={changedSince:c?.read==="delta"?Pe(c.since):void 0,rows:0,cut:!1},u=await this.prepare(e,t,d,c?l:void 0,i,s.gateReads,s.earlierLinked),f=u.records.length>0?await this.pricesSettled(t,u,s):void 0,p=f?{...u,...f}:u;if(o&&p.records.length>0){ki(s.links,t,p.sources);let I=f?Pt(s.links,t,f.standsFor):[];return Si({objectApiName:t.objectApiName,operation:t.operation,read:p.read,insert:0,update:0,delete:0,skipped:p.alreadyCopied,...yn(p),refused:p.records.length+I.length,conflicts:0,conflictFields:[],notes:[o.message]},p)}let m=ta(t,p,s.links),y=m.prepared,h=null;if(y.records.length>0&&this.deps.describeTargetFields)try{let I=await this.deps.describeTargetFields(t.objectApiName);h=I.creatable.size>0?I:null}catch{h=null}let b=await yi(s,y.records,y.sources,t.objectApiName),S=_s({config:{...t,fieldMappings:[],addOnFields:[]},records:y.records,target:h,run:b}),R=S.sentAt.map(I=>y.records[I]),k=sr(t),g=new Map;if(k!==null){let I=new Map;for(let W of R){let Z=W[k],me=Fe(Z);me!==null&&I.set(me,Z)}I.size>0&&(g=await a(e.targetOrgId,t,k,[...I.values()]))}let w=R.map(I=>or(t,I,g)),M=t.operation==="upsert"&&k!==null&&k.toLowerCase()!=="id"?dr(k,R.map(I=>Fe(I[k])),w,ar(R.length,t.batchSize,this.deps.bulkThreshold??fe.REST_API_BATCH_SIZE)):void 0;for(let I of M?.updated??[])w[I]="update";let A=w.flatMap((I,W)=>(I==="insert"||I==="update")&&M?.refused.has(W)!==!0?[W]:[]),O=h?.fields!==void 0&&A.length>0?lr(t.objectApiName,A.map(I=>({payload:S.payloads[I],source:y.sources[S.sentAt[I]]??{},creates:w[I]==="insert"})),h.fields):{refused:new Set,notes:[],refusedFor:[]},E=new Set([...[...O.refused].map(I=>A[I]),...M?.refused??[]]),F=await this.lookupsTheTargetLacks(A.filter(I=>!E.has(I)),S.payloads,S.settled,h),N=ra(F,w,h);for(let I of N.refused)E.add(I);let $=A.filter(I=>w[I]==="insert"&&!E.has(I)),T=t.operation==="insert"?(h?.fields??[]).filter(I=>I.unique===!0&&I.createable):[],v=new Map;for(let I of T){let W=new Map;for(let Z of $){let me=S.payloads[Z][I.name],Be=Fe(me);Be!==null&&W.set(Be,me)}W.size!==0&&v.set(I.name,await a(e.targetOrgId,t,I.name,[...W.values()]))}let j=ur($.map(I=>S.payloads[I]),v);for(let I of j.refused)E.add($[I]);let x=new Set([...j.linked].map(I=>$[I])),_=R.flatMap((I,W)=>E.has(W)||x.has(W)?[]:[W]),z=new Set(_.map(I=>S.sentAt[I])),H=y.unsettled.filter((I,W)=>z.has(W)),G=cr({objectConfig:t,read:y.read,records:_.map(I=>R[I]),leftOut:d.counts(t.objectApiName),inTarget:g,simulated:_.map(I=>w[I]),conflicts:y.conflicts,unsettled:H,matchField:y.matchField,writable:h?.creatable??null}),ne=t.operation==="insert"||t.operation==="upsert",Te=I=>{let W=y.sources[I]?.Id;return typeof W=="string"&&W!==""?W:void 0},Se=[];if(t.operation!=="delete"){for(let{index:I}of S.held){let W=Te(I);W&&ne&&s.links.noteRefused(W,t.objectApiName)}if(S.sentAt.forEach((I,W)=>{let Z=Te(I);Z&&(E.has(W)||ir.has(w[W])?ne&&s.links.noteRefused(Z,t.objectApiName):s.links.noteWritten(Z,Z))}),t.objectApiName===Ee&&ne)for(let I of _){let W=Te(S.sentAt[I]),Z=S.payloads[I]?.[oe];w[I]!=="insert"||!W||typeof Z!="string"||Z===""||s.links.noteSentWithContact(W,Z)}f&&(Se=Pt(s.links,t,f.standsFor))}let V=$s(t.objectApiName,_.flatMap(I=>{let W=w[I]==="insert"?S.withoutRecordType.get(S.sentAt[I]):void 0;return W?[W]:[]}),Bs(h?.recordTypes??[],b.recordTypes)),be=[...M?.refusedFor??[],...O.refusedFor,...j.refusedFor],ie={...G,skipped:G.skipped+x.size+y.alreadyCopied+m.linked,...yn(y),...m.linked>0?{writtenByThePlatform:m.linked}:{},...y.encryptedLeftOut?{encryptedLeftOut:[...y.encryptedLeftOut]}:{},...V?{recordTypeGiven:V}:{},refused:G.refused+S.held.length+E.size+Se.length,...be.length>0?{refusedFor:be}:{},notes:[...f?.standardMatched?[Ys]:[],...ws(f?rn(f,Se):[]).map(I=>`${I}.`),...m.linked>0?[sa(m.linked)]:[],...G.notes,...M?.notes??[],...S.notes,...Se.length>0?[sn(t.objectApiName,Se.length)]:[],...S.currencies.map(I=>`${rr(I)}.`),...O.notes,...N.notes,...j.notes]};if(!c)return ie;if(c.read==="delta"&&e.propagateDeletes===!0&&l.changedSince){let I=await this.tallyObjectDeletions(t,l.changedSince);if("error"in I)return{...ie,notes:[...ie.notes,I.error],delta:je(c,l.rows,{deleted:0,deleteFailed:0,error:I.error})};let W=I.tally.ids.length;return{...ie,delete:ie.delete+W,notes:[...ie.notes,...I.notes],delta:je(c,l.rows,{deleted:W,deleteFailed:0})}}return{...ie,delta:je(c,l.rows)}}async lookupsTheTargetLacks(e,t,r,s){let i=this.deps.queryTargetRows,o=new Map;if(!i||!s?.fields||s.references.size===0)return o;let a=new Map,d=new Map;for(let u of e){let f=t[u]??{},p=[];for(let[m,y]of Object.entries(f)){if(m==="RecordTypeId"||!s.references.has(m)||r[u]?.has(m)||typeof y!="string"||!na.test(y))continue;p.push({field:m,id:y});let h=s.fields.find(b=>b.name===m)?.referenceTo??[];for(let b of h)d.set(b,(d.get(b)??new Set).add(y))}p.length>0&&a.set(u,p)}if(a.size===0)return o;let c=new Set,l=new Set;for(let[u,f]of d){let p=[...f];for(let[m,y]of ee(p,mn).entries())try{let h=await i(`SELECT Id FROM ${ye(u)} WHERE Id IN (${y})`);for(let b of h){let S=b.Id;typeof S=="string"&&c.add(S.slice(0,15))}}catch{let h=m*mn;for(let b of p.slice(h,h+mn))l.add(b.slice(0,15))}}for(let[u,f]of a)f.some(({id:m})=>!c.has(m.slice(0,15))&&!l.has(m.slice(0,15)))&&o.set(u,f.map(({field:m})=>m).sort());return o}async noteLeftOutRefused(e,t,r,s,i){if(!ce(t.operation))return;let{plan:o}=await this.readPlan(e,t,r),a={changedSince:o?.read==="delta"?Pe(o.since):void 0,rows:0,cut:!1},d=await this.prepare(e,t,new it,o?a:void 0,i,s.gateReads,s.earlierLinked);if(d.records.length===0)return;let c=await this.pricesSettled(t,d,s);ki(s.links,t,c.sources),Pt(s.links,t,c.standsFor)}async syncObject(e,t,r,s,i,o,a,d,c){let l=await this.prepare(e,t,r,i,d,s.gateReads,s.earlierLinked),u=await this.rolesWrittenWithTheirOpportunity(t,l,s,a),f=u.prepared,p=w=>ea(Si(ia(w,f),f),u.said);if(f.records.length===0)return p(Ie(It(t),r));let m=await this.pricesSettled(t,f,s),{records:y,sourceIds:h,sources:b}=m;if(y.length===0)return p(Ie(on(It(t),m),r));let S={...await yi(s,y,b,t.objectApiName),...m.standardFirst>0?{standardFirst:m.standardFirst}:{}},R=()=>Pt(s.links,t,m.standsFor);if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return hi;if(o||a||c||i){let w=M=>{M.forEach((A,O)=>{let E=h[O];o&&A.success&&A.id&&E&&o.set(E,A.id)}),a?.(M,h)};try{let{outcomes:M,notes:A,currencies:O,lookupsLeftOut:E,writtenWithoutFields:F,lookupsToSet:N,lookupsUnset:$}=await this.deps.dataSync.write({...t,fieldMappings:[],addOnFields:[]},y,S);i&&$!==void 0&&(i.lookupsUnset=$),w(M);let T=R();return N&&c?.(N),p(Ie(Oi(Hs(qe(t.objectApiName,t.operation,M,A,E,F),O),m,T),r))}catch(M){throw M instanceof Q&&w(M.written),M}}let k=await this.deps.dataSync.sync({...t,fieldMappings:[],addOnFields:[]},y,S),g=R();return p(Ie(Oi(k,m,g),r))}async rolesWrittenWithTheirOpportunity(e,t,r,s){let i=this.deps.queryTargetRows;if(e.objectApiName!==X||e.operation!=="insert"&&e.operation!=="upsert"||!i||!r.links.sentWithAContact||t.records.length===0)return{prepared:t};let o=g=>typeof g=="string"&&g!==""?r.links.targetOf(g):void 0,a=t.records.map((g,w)=>({OpportunityId:o(g.OpportunityId),[oe]:o(g[oe]),IsPrimary:t.sources[w]?.IsPrimary??g.IsPrimary})),d=await this.deps.describeTargetFields?.(X).catch(()=>{}),c=g=>g!=="Id"&&g!=="OpportunityId"&&g!==oe&&(d?.creatable.has(g)??!0),l=[...new Set(t.records.flatMap(g=>Object.keys(g)))].filter(c),u;try{u=await Zn(async g=>await i(g),a,g=>r.links.contactSentWith(g),l)}catch(g){return{prepared:t,said:{records:0,given:0,unread:g instanceof Error?g.message:String(g)}}}let{found:f,alike:p}=u;for(let g of p)r.links.roleLinkedFor(String(a[g].OpportunityId));let m=p.length>0?{alike:p.length}:{};if(f.size===0)return p.length>0?{prepared:t,said:{records:0,given:0,...m}}:{prepared:t};let y=[];for(let[g,w]of f){let M=Object.entries(t.records[g]??{}).filter(([A,O])=>c(A)&&O!==null&&O!==void 0&&String(w[A]??"")!==String(O));M.length>0&&y.push({Id:String(w.Id),...Object.fromEntries(M)})}let h=0,b;if(y.length>0)try{let g=await this.deps.dataSync.updateRecords(X,y,e.batchSize);y.forEach((w,M)=>{let A=g[M];A?.success?h++:b??=`${String(w.Id)}: ${A?.errors[0]??"not updated"}`})}catch(g){b=g instanceof Error?g.message:String(g)}let S=[],R=[];for(let[g,w]of f){let M=t.sourceIds[g],A=String(w.Id);r.links.roleLinkedFor(String(a[g].OpportunityId)),M!==void 0&&(r.links.noteWritten(M,A),S.push(M),R.push({success:!1,errors:[],existingId:A}))}s?.(R,S);let k=(g,w)=>!f.has(w);return{prepared:{...t,records:t.records.filter(k),sourceIds:t.sourceIds.filter(k),sources:t.sources.filter(k)},said:{records:f.size,given:h,...b!==void 0?{refusal:b}:{},...m}}}async prepare(e,t,r,s,i,o,a){let d=s?void 0:o?.get(t.objectApiName);d&&o?.delete(t.objectApiName);let c=s?await this.deps.querySource(e.sourceOrgId,t,{changedSince:s.changedSince,onBoundReached:()=>{s.cut=!0}}):d??await this.deps.querySource(e.sourceOrgId,t);s&&(s.rows=c.length);let l=t.externalIdField??"Id",u=this.deps.maskedSourceFields,p=(c.length>0&&u?await u(t.objectApiName).catch(()=>[]):[]).filter(O=>c.some(E=>Object.prototype.hasOwnProperty.call(E,O)));for(let O of c)for(let E of p)delete O[E];let m=p.length>0?{encryptedLeftOut:p}:{},y=t.operation==="insert"||t.operation==="upsert",h=y?r.keep(t.objectApiName,c):c,b=i&&i.size>0&&t.operation==="insert"?h.filter(O=>!(typeof O.Id=="string"&&i.has(re(O.Id)))):h,S=h.length-b.length,R=S>0&&a&&a.size>0?h.filter(O=>typeof O.Id=="string"&&i?.has(re(O.Id))===!0&&a.has(re(O.Id))).length:0;if(b.length===0)return{read:c.length,records:[],sourceIds:[],sources:[],conflicts:[],unsettled:[],matchField:l,alreadyCopied:S,alreadyLinked:R,...m};let g=b.map(O=>{let E=this.deps.fieldMapping.apply(O,t.fieldMappings,t.excludedFields);return this.deps.transformPipeline.transformRecord(E,t)}).map(O=>{let E=this.deps.fieldMapping.applyAddOns(O,t.addOnFields);return y?pa(t.objectApiName,E):E}),w=g,M=[],A=t.operation==="upsert"||t.operation==="update";if(e.direction==="bidirectional"&&A){let O=await this.deps.queryTarget(e.targetOrgId,t);for(let E of O)for(let F of p)delete E[F];if(M=this.deps.conflictResolver.detectConflicts(g,O,l),M.length>0){let E=this.deps.conflictResolver.resolve(M,e.conflictStrategy),F=new Map(E.map(N=>[N.recordId,N.resolvedValues]));w=g.map(N=>{let $=String(N[l]??""),T=F.get($);return T?{...N,...T}:N})}}return{read:c.length,records:w,sourceIds:b.map(O=>typeof O.Id=="string"?O.Id:void 0),sources:b,conflicts:M,unsettled:g,matchField:l,alreadyCopied:S,alreadyLinked:R,...m}}async planFiles(e,t,r){let s=e.files;if(!s)return;let i=this.deps.files;if(!i)throw new ue("This session cannot copy files: it reads no file content or file storage. Nothing was read or written.");return ti({config:e,option:s,deps:i,tie:(o,a)=>this.tieToTarget(e,o,a),objects:t.map(o=>{let a=r===void 0?null:We(e,o,r);return{objectConfig:o,...a?.read==="delta"?{changedSince:Pe(a.since),...a.filesSeen!==void 0?{filesSeen:a.filesSeen}:{}}:{}}})})}async tieToTarget(e,t,r){let s=this.deps.deltaReads,i=this.deps.files;if(!s||!i)return{held:new Map,refused:"the target cannot be asked"};let o=Ht(t);if("refused"in o)return{held:new Map,refused:o.refused};let a=t.objectApiName,d=new Map;if(o.sourceField==="Id")for(let u of r)d.set(u,u);else{let u=rt(a),f=ye(o.sourceField);for(let p of ee(r)){let m=await i.copy.queryRecords(e.sourceOrgId,`SELECT Id, ${f} FROM ${u} WHERE Id IN (${p})`);for(let y of m){let h=this.deps.fieldMapping.apply(y,t.fieldMappings,t.excludedFields),b=this.deps.transformPipeline.transformRecord(h,t)[o.keyField];typeof y.Id=="string"&&Fe(b)!==null&&d.set(y.Id,b)}}}if(d.size===0)return{held:new Map};let c=await s.targetIdsByKey(a,o.keyField,[...new Set(d.values())]),l=new Map;for(let[u,f]of d){let p=c.get(Fe(f))??[];p.length===1&&l.set(u,p[0])}return{held:l}}};function ua(n,e,t){let r=[],s=[];return n!=="insert"&&n!=="upsert"?{written:r,linked:s}:(e.forEach((i,o)=>{let a=t[o];if(a===void 0)return;if(i.success&&typeof i.id=="string"&&i.id!==""){r.push([a,i.id]);return}let d=Ks(n,i);d!==void 0&&s.push([a,d])}),{written:r,linked:s})}function pa(n,e){let t=Vn(n,e);if(t.length===0)return e;let r={...e};for(let s of t)delete r[s];return r}function Ie(n,e){let t=e.counts();return t.length===0?n:{...n,skipped:n.skipped+t.reduce((r,{count:s})=>r+s,0),errors:[...n.errors,...t.map(({why:r,count:s})=>Jn(s,r))]}}function It(n){return{objectApiName:n.objectApiName,operation:n.operation,processed:0,success:0,failed:0,skipped:0,conflictCount:0,errors:[]}}function fa(n,e,t,r,s,i){let o=Ei(t)==="failure"?"failure":"partial",a=s.map(c=>c.objectApiName),d=a.length>0?`Cancelled before ${a.join(", ")} ${a.length===1?"was":"were"} synced.`:"Cancelled.";return{...se(n,e,t,r,o),cancelled:!0,error:i?`${i} ${a.length>0?d:""}`.trim():d}}function Ii(n){return`Cancelled while the files of ${n.objectApiName} were copied: those copied stay in the target, the others are copied by the next run.`}function Ei(n){return n.length===0?"success":n.every(r=>r.failed>0&&r.success===0)?"failure":n.some(r=>r.failed>0||ga(r.delta)||(r.files?.failed??0)>0)?"partial":"success"}function ga(n){return n!==void 0&&(n.deleteFailed>0||n.deletionError!==void 0)}function se(n,e,t,r,s){let i=0,o=0,a=0,d=0;for(let c of t)i+=c.processed,o+=c.success,a+=c.failed,d+=c.skipped;return{configId:n,operationId:e,status:s,objectResults:t,totalProcessed:i,totalSuccess:o,totalFailed:a,totalSkipped:d,duration:Date.now()-r,timestamp:new Date().toISOString()}}var ma=2;async function Ti(n,e,t,r,s=()=>!1){let i=t.rows;if(!i||i.length!==e.length||t.stopped)return{result:t,unsent:[]};let o=[...i],a=[...e],d=e.map(()=>[]),c=[],l=!1;for(let f=0;f<ma&&!s();f++){let p=[],m=[],y=[];if(o.forEach((S,R)=>{if(S.id)return;let k=Yr(S.errorDetails,a[R],void 0);!k||k.some(({field:g})=>r.has(g))||(p.push(R),m.push(Jr(a[R],k)),y.push(k))}),p.length===0)break;let h;try{h=await n(m)}catch(S){let R=[...new Set(y.flat().map(({field:k})=>k))].sort();c.push(`${p.length} record(s) refused on ${R.join(", ")} could not be written again without ${R.length===1?"it":"them"}: ${K(S)}`);break}if(ha(h,m.length).forEach((S,R)=>{let k=p[R];o[k]=S,a[k]=m[R],d[k].push(...y[R])}),h.stopped){l=!0;break}}let u;return o.forEach((f,p)=>{!f.id||d[p].length===0||(u=Ue(u,{rows:1,fields:d[p].map(m=>({...m,rows:1}))}))}),{result:{successIds:o.flatMap(f=>f.id?[f.id]:[]),errors:o.flatMap(f=>f.id?[]:[f.error??"Unknown insert error"]),rows:o,...l?{stopped:!0}:{}},...u?{written:u}:{},unsent:c}}function ha(n,e){if(n.rows&&(n.rows.length===e||n.stopped))return n.rows.slice(0,e);let t=[...n.successIds.map(s=>({id:s})),...n.errors.map(s=>({error:s}))];return(e===1?t:t.map(s=>({...s,unmatched:!0}))).slice(0,e)}var ya=1e4,wa=5e5,bn=200;function Tt(n){let e=Math.floor(wa/Math.max(1,n.fieldRules.length));return Math.max(bn,Math.min(ya,e))}var Mi=class{deps;constructor(e){this.deps=e}async execute(e,t,r){let s=r??this.deps.generateId(),i=Date.now(),o=this.deps.validator.validate(e);if(!o.valid)return xi(e.id,s,o.errors.map(l=>l.message),this.deps.now());let a=await Vs(e.relations,{...this.deps.describeKeyPrefix?{keyPrefixOf:this.deps.describeKeyPrefix}:{},...this.deps.readPresentParentIds?{presentIds:this.deps.readPresentParentIds}:{}});if(a.length>0)return xi(e.id,s,a,this.deps.now());let d=e.objects.reduce((l,u)=>l+u.recordCount,0);return this.shouldActivateGrappe(d)?this.executeWithGrappe(e,t,s,i):this.executeSequential(e,t,s,i)}preview(e){return this.deps.planBuilder.build(e)}shouldActivateGrappe(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&this.deps.grappeAdapter&&e>=t.autoActivateThreshold)}reportProgress(e,t,r,s=0){let i=t.reduce((o,a)=>o+a.recordsCreated+a.recordsFailed,s);this.deps.onProgress?.({objectApiName:e,processedRecords:i,totalRecords:r,percentage:Math.round(i/Math.max(r,1)*100)})}async executeSequential(e,t,r,s){let i=Fi(e,this.platformRolesOf(t),this.deps.onRowIds),o=this.deps.referenceLinker.resolveInsertOrder(e.objects,i.relations),a=e.objects.reduce((d,c)=>d+c.recordCount,0);for(let d of o){if(this.deps.signal?.aborted)return this.stoppedResult(e,r,i,s);let c=await this.readyToWrite(d,i,a);if(!c)continue;let l={},u={successIds:[],errors:[]},f={result:u,unsent:[]},p=ji(c),m=0,y=0,h=!1,b=Tt(c.config);for await(let S of this.slicesOf(c,i,b,l)){if(this.deps.signal?.aborted){h=!0;break}m>0&&this.reportProgress(d.objectApiName,i.objectResults,a,u.successIds.length+u.errors.length);let R=await this.insert(t,d,S,c,i);if(m++,vi(p,c.config.rows,y,S.length,R.result),y+=S.length,Ma(f,R),R.result.stopped){h=!0;break}}if(m>0&&Et(i,d,Sn(u,c),[...c.notes,...wn(f)],l,p),h)return this.stoppedResult(e,r,i,s)}return this.ended(e,r,i,s)}async ended(e,t,r,s){let i,o=!1;try{i=await this.deps.knowledge?.({ids:ka(r),results:r.objectResults})}catch(l){o=!0,i={skipped:`The articles were neither published nor linked: ${K(l)}`}}let a=Ni(e.id,t,r.objectResults,s,this.deps.now());if(!i)return a;let d=o||[i.publish,i.links].some(l=>(l?.notDone.length??0)>0),c=this.deps.signal?.aborted===!0;return{...a,knowledge:i,...(d||c)&&a.status==="success"?{status:"partial"}:{},...c?{cancelled:!0}:{}}}async readyToWrite(e,t,r){let s=Wt(e.objectApiName,t.relations),i=Ln(e,t.relations).filter(h=>t.wroteNothing.has(h));if(i.length>0)return Ve(t,e.objectApiName,`Skipped: ${i.join(", ")} wrote no records, so there is nothing for ${e.objectApiName} to point at.`);let o=await this.closedObject(e.objectApiName);if(o)return Ve(t,e.objectApiName,o,e.optional===!0);this.reportProgress(e.objectApiName,t.objectResults,r);let a=Bi(e,s),{config:d,dropped:c}=await Di(a,this.deps.describeCreateableFields),l=await this.whyDropped(e.objectApiName,c),u=h=>h.fieldRules.length===0&&Rn(h.rows).length===0;if(u(d)&&!u(a))return Ve(t,e.objectApiName,`Skipped: none of the fields the template names can be written (${l.join("; ")}).`);let{config:f,filled:p}=await Li(await this.withTheOrgsPicklistValues(d),s,this.deps.describeRequiredFields),m=await this.matchStandardPricebook(f,t);if(m)return Ve(t,e.objectApiName,m);let y;if(s){let h=await this.placeChildren(f,s,t);if("skipped"in h)return Ve(t,e.objectApiName,h.skipped);if(h.parentIds.length===0&&h.unwritten){let{lines:b,keys:S}=h.unwritten;return Et(t,e,{successIds:[],errors:b},[],{},S),null}y=h}return{relation:s,config:y?{...f,recordCount:y.parentIds.length,...y.rows?{rows:y.rows}:{}}:f,placed:y,...f.rows?{lengths:await this.fieldLengths(e.objectApiName)}:{},notes:[...l.map(h=>`Written without ${h}.`),...p.length>0?[`Written with ${p.join(", ")}, which this org requires and the template names no rule for.`]:[],...y?.notes??[]]}}async placeChildren(e,t,r){let{childObject:s,lookupField:i,parentObject:o}=t;if(!await this.orgTakesField(s,i))return{skipped:`Skipped: this org does not let a seed write ${s}.${i}, the lookup the relation fills.`};if(t.distribution.mode==="byKey")return Ra(e.rows??[],t,r.keys.get(o));let a=r.existingIds,d;if(t.parents.kind==="generated")d=a.get(o)??[];else if(t.parents.kind==="records")d=[...t.parents.ids];else{let f=this.deps.readExistingParentIds;if(!f)return{skipped:`Skipped: this run cannot read the ${o} records already in the org, so ${s} has nothing to point at.`};try{d=await f(o,t.parents.where,t.parents.limit)}catch(p){return{skipped:`Skipped: reading the ${o} records already in the org failed (${K(p)}), so ${s} has nothing to point at.`}}}if(d.length===0){let f=t.parents.kind==="existing"?t.parents.where?.trim():"";return{skipped:`Skipped: ${t.parents.kind==="generated"?`${o} wrote no records`:`no ${o} record in the org matches ${f?`"${f}"`:"the relation"}`}, so there is nothing for ${s} to point at.`}}let c=Dn(t.distribution,d.length,this.deps.random),l=c.reduce((f,p)=>f+p,0),u=[];for(let[f,p]of c.entries())for(let m=0;m<p&&u.length<e.recordCount;m++)u.push(d[f]);return u.length===0?{skipped:`Skipped: the relation gives none of the ${d.length} ${o} records a ${s}.`}:{parentIds:u,notes:l>u.length?[`Stopped at ${u.length} ${s} records, the most the template asks for: the relation spreads ${l} over ${d.length} ${o} records.`]:[]}}async*slicesOf(e,t,r,s){let i=e.config.recordCount,o=Math.max(1,Math.floor(r)),a=0;do{let d=Math.max(0,Math.min(o,i-a)),c=Pa(e.config,e.relation)?Ia(d):await this.deps.fieldMapper.mapFields(d===i?e.config:{...e.config,recordCount:d},t.existingIds,l=>{s.aiFallback=Ta(s.aiFallback,l)},a,e.lengths);Ea(c,e.relation,e.placed,a),yield c,a+=d}while(a<i)}async insert(e,t,r,s,i){let o=f=>this.deps.insert(e,t.objectApiName,f,t.batchSize),a=t.objectApiName===X?await i.platformRoles.link(r):new Map,d=a.size>0?r.filter((f,p)=>!a.has(p)):r,c=d.length===0&&r.length>0?{successIds:[],errors:[],rows:[]}:await o(d),l=await Ti(o,d,c,Sa(s),()=>this.deps.signal?.aborted===!0);t.objectApiName===Xs&&i.platformRoles.opportunitiesWritten(d,l.result);let u=a.size>0?Oa(l,r.length,a):l;return c.notes&&c.notes.length>0?{...u,notes:c.notes}:u}platformRolesOf(e){return new Zs({orgId:e,readTarget:this.deps.readTarget,update:this.deps.update,stopped:()=>this.deps.signal?.aborted===!0})}async closedObject(e){if(!this.deps.objectAccess)return;let t;try{t=await this.deps.objectAccess(e)}catch{return}if(t.access==="createable")return;let r=t.reason?` (${t.reason})`:"";return t.access==="absent"?`Skipped: this org has no ${e} object${r}.`:`Skipped: the user this seed runs as may not create ${e} records${r}`+(t.reason?".":`: give that user Create on ${e} in a permission set.`)}async withTheOrgsPicklistValues(e){if(!this.deps.describePicklistValues||!e.fieldRules.some(i=>i.ruleType==="picklist_random"))return e;let t;try{t=await this.deps.describePicklistValues(e.objectApiName)}catch{return e}let r=!1,s=e.fieldRules.map(i=>{let o=t.get(i.fieldApiName),a=i.config.picklistValues;if(i.ruleType!=="picklist_random"||!o?.length||!a)return i;let d=a.filter(c=>o.includes(c));return d.length===a.length?i:(r=!0,{...i,config:{...i.config,picklistValues:d.length?d:[...o]}})});return r?{...e,fieldRules:s}:e}async matchStandardPricebook(e,t){if(!e.fieldRules.some(o=>nt(o,t.written))||t.existingIds.has(ge))return;let r=this.deps.readExistingParentIds,s=`${e.objectApiName} points at the org's standard price book`;if(!r)return`Skipped: ${s}, and this run cannot read it.`;let i;try{i=await r(ge,"IsStandard = true",1)}catch(o){return`Skipped: ${s}, and reading it failed (${K(o)}).`}if(i.length===0)return`Skipped: ${s}, and the org shows this user no standard price book (Pricebook2): give that user Read on Price Books in a permission set.`;t.existingIds.set(ge,i)}async orgTakesField(e,t){if(!this.deps.describeCreateableFields)return!0;try{return(await this.deps.describeCreateableFields(e)).has(t)}catch{return!0}}async whyDropped(e,t){if(t.length===0)return[];let r=new Set;try{this.deps.describeVisibleFields&&(r=await this.deps.describeVisibleFields(e))}catch{}let s;try{this.deps.describeComputedFields&&(s=await this.deps.describeComputedFields(e))}catch{}let i=t.filter(c=>r.has(c)&&s?.has(c)===!0),o=t.filter(c=>r.has(c)&&s?.has(c)!==!0),a=t.filter(c=>!r.has(c)),d=(c,l,u)=>c.length===1?l:u;return[...a.length>0?[`${a.join(", ")}: this org does not have ${d(a,"that field","those fields")}, or field-level security hides ${d(a,"it","them")} from the user SandForge connects as`]:[],...i.length>0?[`${i.join(", ")}: ${d(i,"a formula or auto-number field","formula or auto-number fields")}, which the org fills itself and no user sets: take ${d(i,"its rule","their rules")} out of the template`]:[],...o.length>0?[`${o.join(", ")}: ${d(o,"it exists","they exist")}, but the user SandForge connects as may not set ${d(o,"it","them")}`+(s!==void 0?`: give that user Edit on ${d(o,"it","them")} (field-level security, in a permission set)`:`: give that user Edit on ${d(o,"it","them")} (field-level security, in a permission set), unless it is a formula or auto-number field, whose rule comes out of the template`)]:[]]}async fieldLengths(e){if(!this.deps.describeFieldLengths)return new Map;try{return await this.deps.describeFieldLengths(e)}catch{return new Map}}async executeWithGrappe(e,t,r,s){let o=this.deps.grappeAdapter.partition(e),a=o.reduce((y,h)=>y+h.recordCount,0);this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:r,totalPartitions:o.length,totalRecords:a}});let d=Fi(e,this.platformRolesOf(t),this.deps.onRowIds),c=this.deps.referenceLinker.resolveInsertOrder(e.objects,d.relations),l=[],u=0,f=this.deps.grappeConfig?.grappeSize??2e3,p=()=>{let y=d.objectResults.reduce((b,S)=>b+S.recordsCreated,0),h=d.objectResults.reduce((b,S)=>b+S.recordsFailed,0);this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:r,totalProcessed:y,totalFailed:h}})},m=()=>(p(),this.stoppedResult(e,r,d,s));for(let y of c){if(this.deps.signal?.aborted)return m();let h=Math.ceil(y.recordCount/f),b=await this.readyToWrite(y,d,a);if(!b){u=this.settleUnusedPartitions(o,u,h,0);continue}let S={},R=Math.max(1,Math.ceil(b.config.recordCount/f)),k=0,g=0,w=[],M=[],A={result:{successIds:[],errors:[]},unsent:[]},O,E=ji(b),F=0,N=-1;for await(let $ of this.slicesOf(b,d,f,S)){if(N++,this.deps.signal?.aborted){O=N;break}N>0&&this.reportProgress(y.objectApiName,d.objectResults,a,k+g);let T=Date.now(),v=o[u]?.id??this.deps.generateId(),j=await this.insert(t,y,$,b,d),x=j.result;vi(E,b.config.rows,F,$.length,x),F+=$.length,j.written&&(A.written=Ue(A.written,j.written)),A.unsent.push(...j.unsent);for(let z of j.notes??[])(A.notes??[]).includes(z)||(A.notes=[...A.notes??[],z]);k+=x.successIds.length,g+=x.errors.length,w.push(...x.errors),M.push(...x.successIds),l.push({grappeId:v,status:x.errors.length===0?"success":x.successIds.length>0?"partial":"failure",processedRecords:$.length,successCount:x.successIds.length,failureCount:x.errors.length,errors:x.errors,duration:Date.now()-T}),u++;let _=Math.round(u/Math.max(o.length,1)*100);if(this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:v,percentage:_,processedRecords:k+g}}),x.stopped){O=N+1;break}}if(O!==void 0)return O>0&&Et(d,y,Sn({successIds:M,errors:w},b),[...b.notes,...wn(A)],S,E),m();u=this.settleUnusedPartitions(o,u,h-R,k+g),Et(d,y,Sn({successIds:M,errors:w},b),[...b.notes,...wn(A)],S,E)}return p(),this.ended(e,r,d,s)}stoppedResult(e,t,r,s){let i=Ni(e.id,t,r.objectResults,s,this.deps.now());return{...i,status:i.status==="success"?"partial":i.status,cancelled:!0}}settleUnusedPartitions(e,t,r,s){let i=t;for(let o=r;o>0;o--){let a=e[i]?.id??this.deps.generateId();i++,this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:a,percentage:Math.round(i/Math.max(e.length,1)*100),processedRecords:s}})}return i}};function Fi(n,e,t){return{relations:n.relations??[],written:new Set(n.objects.map(r=>r.objectApiName)),existingIds:new Map,wroteNothing:new Set,keys:new Map,...t?{onRowIds:t}:{},platformRoles:e,objectResults:[]}}function Sa(n){return new Set(["RecordTypeId",...n.relation?[n.relation.lookupField]:[],...n.config.fieldRules.filter(e=>e.ruleType==="reference").map(e=>e.fieldApiName)])}function wn(n){return[...n.notes??[],...n.written?[Vr(n.written)]:[],...n.unsent]}function Ve(n,e,t,r=!1){let s=Fa(e,t);return n.objectResults.push(r?{...s,optional:!0}:s),n.wroteNothing.add(e),null}function Et(n,e,t,r,s,i){i&&(n.keys.set(e.objectApiName,i),n.onRowIds?.(e.objectApiName,ba(i)));let o=n.platformRoles.resultOf(e.objectApiName),a=[...t.successIds,...o.linkedIds];n.existingIds.set(e.objectApiName,a),e.recordCount>0&&a.length===0&&n.wroteNothing.add(e.objectApiName),n.objectResults.push({objectApiName:e.objectApiName,recordsCreated:t.successIds.length,recordsFailed:t.errors.length,createdIds:t.successIds,errors:[...t.errors,...r,...o.notes],...s,...o.writtenByThePlatform?{writtenByThePlatform:o.writtenByThePlatform}:{}})}function ba(n){let e={};for(let[t,r]of n)"id"in r&&(e[t]=r.id);return e}function Ra(n,e,t){let{childObject:r,parentObject:s}=e;if(!t)return{skipped:`Skipped: ${r} is placed by key, and ${s} wrote no rows to place it under.`};let i=[],o=[],a=[],d=new Map;for(let c of n){let l=c.parentKey,u=l===void 0?void 0:t.get(l);if(u&&"id"in u){i.push(u.id),o.push(c);continue}let f=l===void 0?`it names no ${s} row`:`its ${s} ${l} ${u?u.why:`is no ${s} row this run wrote`}`;a.push(`${r} ${c.key} not written: ${f}.`),d.set(c.key,{why:`was not written, as ${f}`})}return{parentIds:i,notes:[],rows:o,unwritten:{lines:a,keys:d}}}function ka(n){let e=new Map;for(let[t,r]of n.keys){let s=new Map;for(let[i,o]of r)"id"in o&&s.set(i,o.id);e.set(t,s)}return e}function ji(n){if(n.config.rows)return new Map(n.placed?.unwritten?.keys??[])}function vi(n,e,t,r,s){if(!n||!e)return;let i=s.rows&&(s.rows.length===r||s.stopped)?s.rows:void 0;for(let o=0;o<r;o++){let a=e[t+o];if(!a)continue;let d=i?.[o];i?d?d.id&&d.unmatched?n.set(a.key,{why:"has no id this run can tell: the org did not say which of the ids it answered is its"}):d.id?n.set(a.key,{id:d.id}):n.set(a.key,{why:`was refused (${d.error??"Unknown insert error"})`}):n.set(a.key,{why:"was not sent: the run was stopped before it"}):n.set(a.key,{why:"has no id this run can tell: the insert did not answer record by record"})}}function Sn(n,e){let t=e.placed?.unwritten?.lines??[];return t.length===0?n:{...n,errors:[...n.errors,...t]}}function Oa(n,e,t){let r=n.result.rows;if(!r)return n;let s=[],i=0;for(let o=0;o<e;o++){let a=t.get(o);if(a){s.push({id:String(a.Id)});continue}let d=r[i++];if(!d)break;s.push(d)}return{...n,result:{...n.result,rows:s}}}function Rn(n){return[...new Set((n??[]).flatMap(e=>Object.keys(e.values)))]}function Aa(n){return!n||n.length===0?[]:Rn(n).filter(e=>n.every(t=>e in t.values))}function Ca(n,e){return e.size===0?[...n]:n.map(t=>({...t,values:Object.fromEntries(Object.entries(t.values).filter(([r])=>!e.has(r)))}))}async function Di(n,e){if(!e)return{config:n,dropped:[]};let t;try{t=await e(n.objectApiName)}catch{return{config:n,dropped:[]}}let r=n.fieldRules.filter(a=>a.ruleType==="reference"||t.has(a.fieldApiName)),s=Rn(n.rows).filter(a=>!t.has(a));if(r.length===n.fieldRules.length&&s.length===0)return{config:n,dropped:[]};let i=[...new Set([...n.fieldRules.filter(a=>!r.includes(a)).map(a=>a.fieldApiName),...s])],o=n.rows&&Ca(n.rows,new Set(s));return{config:{...n,fieldRules:r,...o?{rows:o}:{}},dropped:i}}async function Li(n,e,t){if(!t)return{config:n,filled:[]};let r;try{r=await t(n.objectApiName)}catch{return{config:n,filled:[]}}let s=new Set([...n.fieldRules.map(o=>o.fieldApiName),...Aa(n.rows),...e?[e.lookupField]:[]]),i=[];for(let o of r){if(s.has(o.fieldApiName))continue;let a=Bn(o);a.ruleType==="static"&&a.config.staticValue===void 0||i.push({fieldApiName:o.fieldApiName,fieldType:o.type,...a})}return i.length===0?{config:n,filled:[]}:{config:{...n,fieldRules:[...n.fieldRules,...i]},filled:i.map(o=>o.fieldApiName)}}async function $i(n,e,t){let r=Wt(n.objectApiName,e),{config:s}=await Di(Bi(n,r),t.describeCreateableFields),{config:i}=await Li(s,r,t.describeRequiredFields);return Tt(i)}function Bi(n,e){if(!e)return n;let t=n.fieldRules.filter(r=>r.fieldApiName!==e.lookupField);return t.length===n.fieldRules.length?n:{...n,fieldRules:t}}function Pa(n,e){return e!==void 0&&n.fieldRules.length===0&&!n.rows}function Ia(n){return Array.from({length:n},()=>({}))}function Ea(n,e,t,r=0){if(!(!e||!t))for(let[s,i]of n.entries())i[e.lookupField]=t.parentIds[r+s]}function Ta(n,e){return n?{fields:[...new Set([...n.fields,...e.fields])],reason:n.reason==="no-answer"&&e.reason==="no-answer"?"no-answer":"short-answer"}:e}function Ma(n,e){for(let t of e.result.successIds)n.result.successIds.push(t);for(let t of e.result.errors)n.result.errors.push(t);e.written&&(n.written=Ue(n.written,e.written)),n.unsent.push(...e.unsent);for(let t of e.notes??[])(n.notes??[]).includes(t)||(n.notes=[...n.notes??[],t])}function Fa(n,e){return{objectApiName:n,recordsCreated:0,recordsFailed:0,createdIds:[],errors:[e]}}function Ni(n,e,t,r,s){let i=t.reduce((d,c)=>d+c.recordsCreated,0),o=t.reduce((d,c)=>d+c.recordsFailed,0),a=t.some(d=>!d.optional&&d.recordsCreated===0&&d.recordsFailed===0&&d.errors.length>0);return{templateId:n,operationId:e,status:ja(i,o,a),objectResults:t,totalRecordsCreated:i,totalRecordsFailed:o,duration:Date.now()-r,timestamp:s}}function ja(n,e,t){return e===0&&!t?"success":n===0?"failure":"partial"}function xi(n,e,t,r){return{templateId:n,operationId:e,status:"failure",objectResults:[{objectApiName:"validation",recordsCreated:0,recordsFailed:0,createdIds:[],errors:t}],totalRecordsCreated:0,totalRecordsFailed:0,duration:0,timestamp:r}}var va=200,Na=1,xa=1,kn=2,Da=2,Gi=3,La=1,$a=200,Ba="Campaign";function Ui(n,e){if(!n)return;let t=e.toLowerCase();for(let[r,s]of n)if(r.toLowerCase()===t)return s}function _a(n,e){let t=Math.max(1,Math.floor(e)),r=[],s=0;do{let i=Math.max(0,Math.min(t,n-s));r.push(i),s+=i}while(s<n);return r}function Wa(n,e={}){let t=e.bulkThreshold??va,r=!1;return n.objects.flatMap(i=>{let o=Ui(e.duplicateRules,i.objectApiName),a=o===!1&&!As.has(i.objectApiName),d=e.partition??e.slices?.get(i.objectApiName)??Tt(i);return _a(i.recordCount,d).map(c=>{let l=we([{rows:c,perCall:i.batchSize}]);if(c<=t||(r=!0,o===!0))return l;let u=we([{rows:c,bulk:!0}]);return a?u:Math.max(u,l)})}).reduce((i,o)=>i+o,0)+(r?Na:0)+we(za(n))}function Ga(n,e={}){return Wa(n,e)+Ua(n,e)}function Ua(n,e={}){let t=new Set(n.objects.map(i=>i.objectApiName)),r=n.objects.some(i=>i.fieldRules.some(o=>nt(o,t))),s=(n.relations??[]).reduce((i,{parents:o})=>o.kind==="existing"?i+we([{rows:0,readRows:o.limit}]):o.kind==="records"?i+Math.ceil(o.ids.length/Js):i,0);return xa+n.objects.length+kn+(t.has(Ba)?kn+1:0)+s+(r?La:0)+(e.typedFirst?Da:0)+Gi+Math.max(0,e.sentBefore??0)+Math.max(0,e.automationRead??0)+Math.max(0,e.slicesRead??0)}async function wl(n,e,t){let r=new Map;if(t!==void 0)return r;for(let s of n.objects)s.recordCount<=bn||r.set(s.objectApiName,await $i(s,n.relations,e));return r}function Sl(n,e){return n?.enabled&&e.objects.reduce((r,s)=>r+s.recordCount,0)>=n.autoActivateThreshold?n.grappeSize:void 0}function Mt(n,e){return n.reduce((t,{objectApiName:r,rows:s,perCall:i,deletes:o})=>{if(s<=e.threshold)return t+we([{rows:s,perCall:i??e.perCall}]);let a=o===!0||Ui(e.duplicateRules,r)===!1?0:s;return t+we([{rows:s,bulk:!0},{rows:a}])},0)}function On(n=0,e=0){return Gi+kn+Math.max(0,n)+Math.max(0,e)}function bl(n,e){let t=i=>n.find(o=>o.objectApiName===i)?.rows??0,r=Math.min(t("Opportunity"),t("OpportunityContactRole")),s=n.filter(({objectApiName:i})=>e.secondPass?.has(i)===!0).map(({rows:i})=>({rows:i}));return Mt(n,e)+(r>0?Math.ceil(r/$a)+Mt([{objectApiName:"OpportunityContactRole",rows:r}],e):0)+we(s)+On(n.length,e.automationRead)}function za(n){let e=r=>n.objects.find(s=>s.objectApiName===r)?.recordCount??0,t=Math.min(e("OpportunityContactRole"),e("Opportunity"));return t>0?[{rows:t},{rows:t}]:[]}function qa(n,e){return n.objects.reduce((t,r)=>t+Zr(r.objectApiName,{rows:r.recordCount,personAccounts:e.includes(r.objectApiName)?r.recordCount:0}),0)}function kl(n,e){let t=n.automationStarts??[],r=t.filter(a=>a.why!=="leftEmpty"),s=n.automationAtMostMB!==void 0&&n.automationAtMostMB>0&&r.length>0?` (${xe(n.automationAtMostMB)} MB of it at most: ${r.map(a=>`${_i(a)} ${Wi(a)}`).join("; ")})`:"",i=`data storage: about ${xe(n.estimateMB)} MB to write`+(n.automationMB!==void 0&&n.automationMB>0?`, about ${xe(n.automationMB)} MB of it for what the target's automation creates under them${s}`:""),o=t.filter(a=>a.why==="leftEmpty").map(a=>`; nothing counted for ${_i(a)}: it ${Wi(a)}`).join("");return n.verdict==="unread"?`${i}; what ${e} has left could not be read (${n.unread})${o}`:`${i}, ${e} has ${n.remainingMB} MB left of ${n.maxMB} MB`+ft(pt(n),e)+(n.verdict==="near"?": close to what it has left":"")+o}function _i(n){return`${n.name} on ${n.objectApiName}`}function Wi(n){let e=n.why==="leftEmpty"?"which the seed leaves empty":n.why==="automationMayFill"?"which the seed leaves empty and the target's automation may fill first":"which the seed may leave empty";return`starts only on a record whose ${n.fields.join(" and ")} ${n.fields.length===1?"is":"are"} filled, ${e}`}var Ol="SEED_STORAGE_EXCEEDED";async function Al(n,e,t,r,s,i={},o={},a={perRecord:[]}){let d={storageBytes:qa(e,t)},c;try{c=await es(n)}catch(w){c={unread:K(w)}}let l=new Map(e.objects.map(w=>[w.objectApiName,w.recordCount])),u=w=>l.get(w)??0,f=en(a,u),p=a.atMost?en({perRecord:a.atMost},u):0,m=Ne(d,c,f),h={...m.verdict==="exceeds"&&p>0&&Ne(d,c,f-p).verdict!=="exceeds"?{...m,verdict:"near"}:m,...p>0?{automationAtMostMB:p/1048576}:{},...a.starts&&a.starts.length>0?{automationStarts:a.starts}:{}},b="unread"in c?await ts(n).catch(w=>({unread:K(w)})):c.dailyApiRequests,S=dt({run:Ga(e,o),...lt(s),...i},b),R=ut(s);if(R)return{check:h,api:S,refusal:R.message,refusedFor:"checkpoint",checkpointRefusal:R.refusal};let k=gs(h,r);if(k)return{check:h,api:S,refusal:`${k} Nothing was written.`,refusedFor:"storage"};let g=ct(S,r,at);return g?{check:h,api:S,refusal:g,refusedFor:"apiRequests"}:{check:h,api:S}}function Cl(n,e){let{check:t,api:r}=n,s=r.parts??{},i={checkpoint:s.checkpoint??0,mute:s.mute??0,readBack:s.readBack??0,deliverability:s.deliverability??0,fit:s.fit??0};return ms({storage:t.verdict==="unread"?{unread:t.unread}:{maxMB:t.maxMB,remainingMB:t.remainingMB,...t.uncountedWrites?{uncountedWrites:t.uncountedWrites}:{}},...e!==void 0?{withinMB:e}:{},api:r.verdict==="unread"?{unread:r.unread}:{max:r.max,remaining:r.remaining},otherRequests:i})}function Ka(n){return n==="insert"||n==="upsert"}function Hi(n){return n==="update"||n==="upsert"}function Ha(n){return Qr(n.objects.filter(e=>Ka(e.operation)).map(({objectApiName:e,rows:t,personAccounts:r})=>({objectApiName:e,rows:[],counted:{rows:t,...r!==void 0?{personAccounts:r}:{}}})))}var Yi=fe.REST_API_BATCH_SIZE;function Ya(n,e){return Mt(n.filter(t=>t.rows>0).map(({objectApiName:t,operation:r,rows:s,batchSize:i})=>({objectApiName:t,rows:s,...i!==void 0?{perCall:i}:{},...r==="delete"?{deletes:!0}:{}})),{threshold:e.bulkThreshold??Yi,...e.duplicateRules?{duplicateRules:e.duplicateRules}:{}})}var Ja="Opportunity",Va="OpportunityContactRole",Xa=200,Za={update:{characters:gt,wide:!0},upsert:{characters:Ds(),wide:!0}},Qa=2,zi=Array.from({length:Qa},()=>1),ed={characters:gt,wide:!1},td=1;function nd(n,e=[]){let t=Math.min(Math.max(0,n),5e4),r=e.reduce((s,i)=>s+Math.ceil(t/Math.max(1,i)),0);return td+Math.max(1,Math.ceil(t/Hr))+r}function rd(n,e){let[,...t]=Qn(e.length>0?e:["Id"]);return t.map(r=>er(n,r))}function Cn(n,e){let t=Math.max(1,Math.floor(e));return Array.from({length:Math.ceil(Math.max(0,n)/t)},(r,s)=>Math.min(t,n-s*t))}function qi(n,e){if(n.rows<=(e.bulkThreshold??Yi))return Cn(n.rows,n.batchSize??fe.REST_API_BATCH_SIZE);let t=e.duplicateRules?[...e.duplicateRules].find(([r])=>r.toLowerCase()===n.objectApiName.toLowerCase())?.[1]:void 0;return[n.rows,...t===!1?[]:Cn(n.rows,fe.REST_API_BATCH_SIZE)]}function sd(n,e){let t=0,r=!1;for(let[d,c]of e.targetHeld??[])t+=nd(c,e.targetGroups?.get(d));for(let d of n.objects){if(d.rows<=0||d.operation==="delete")continue;t+=zi.length;let{within:c=0,cycle:l=0}=d.lookupPasses??{};for(let[u,f]of[[c,[]],[l,[1]]]){if(u<=0)continue;let p=[...qi({...d,rows:u},e),...f];r=!0,t+=p.length+mt(p,ed)}d.operation!=="update"&&d.operation!=="upsert"||(r=!0,t+=mt([...qi(d,e),...zi],d.overwriteKey??Za[d.operation]))}let s=d=>n.objects.find(c=>c.objectApiName===d&&(c.operation==="insert"||c.operation==="upsert")),i=s(Ja),o=s(Va),a=i&&o?Math.min(i.rows,o.rows+(n.rolesLinked??0)):0;if(o&&a>0){let d=Cn(a,o.batchSize??fe.REST_API_BATCH_SIZE);r=!0,t+=Math.ceil(a/Xa)+d.length+mt(d,{characters:gt,wide:o.overwriteKey?.wide??!0})}return r&&(t+=1),e.leaseAssigns===!0&&(t+=Math.max(0,n.describedAgain??0)),t}function Ji(n){let e=new Map;for(let{objectApiName:t,operation:r}of n.objects){let s=e.get(t)??new Set;(r==="insert"||r==="upsert")&&s.add("insert"),(r==="update"||r==="upsert")&&s.add("update"),r==="delete"&&s.add("delete"),e.set(t,s)}return(t,r)=>e.get(t)?.has(r)===!0}function Vi(n,e){let t=new Set(e);return{...n,objectsRead:n.objectsRead.filter(r=>t.has(r)),objects:n.objects.filter(r=>t.has(r.objectApiName))}}function id(n){let e;return t=>{if(e&&t.every(s=>e?.objects.includes(s)))return e.answer.then(s=>Vi(s,t));let r=n(t);return e??={objects:[...t],answer:r},r}}function Ul(n,e){if(n.direction==="bidirectional")return async t=>{let r=n.objects.find(i=>i.objectApiName===t),s=ot(r?.where,void 0);return e(`SELECT COUNT() FROM ${ye(t)}${s?` WHERE ${s}`:""}`)}}async function od(n,e,t){let r=new Set((n.heldBack??[]).filter(({rows:o})=>o>0).map(({objectApiName:o})=>o)),s=new Map,i=new Map;for(let{objectApiName:o,operation:a,rows:d}of n.objects){if(!Hi(a)||s.has(o)||d<=0&&!r.has(o))continue;let c=await e(o).catch(()=>5e4);s.set(o,Number.isFinite(c)&&c>=0?c:5e4);let l=await t?.(o).catch(()=>{}),u=l?rd(o,l):[];u.length>0&&i.set(o,u)}return{held:s,groups:i}}async function Ki(n,e){let t=Ha(n),r=n.objects.filter(T=>T.rows>0).map(({objectApiName:T,rows:v})=>({objectApiName:T,rows:v})).sort((T,v)=>v.rows-T.rows||T.objectApiName.localeCompare(v.objectApiName)),s=r.reduce((T,v)=>T+v.rows,0),i=n.objects.filter(T=>Hi(T.operation)).reduce((T,v)=>T+v.rows,0),o=Ne(t,{maxMB:0,remainingMB:0}),a=[],d,c=s>0?id(e.readAutomation):e.readAutomation,l,u,f,p=Ji(n),m;if(s>0){let T=n.objects.filter(v=>v.rows>0).map(v=>v.objectApiName);if(m=await c(T).catch(v=>({unread:v instanceof Error?v.message:String(v)})),e.checkpointFirst){let v="objects"in m?Gt(m,void 0,p):{firing:[]};try{l=await e.checkpointFirst.scope(T,v)}catch(j){u=Xr(j)}}}let y={unread:"not read"};if(s>0){let T=await e.readStorage().catch(v=>({unread:v instanceof Error?v.message:String(v)}));y="unread"in T?await e.readApiBudget().catch(v=>({unread:v instanceof Error?v.message:String(v)})):T.dailyApiRequests,t.totalRows>0&&(o=Ne(t,T))}if(t.totalRows>0){let T=await os({plan:t,objects:t.objects.map(v=>v.objectApiName),readAutomation:c,readLimits:e.readLimits});a=T.checks,d=T.unread}m!==void 0&&(f=await Gr({...e.emails,read:m,writes:p,readDeliverability:e.readDeliverability,run:"sync"}));let h=s>0&&e.countTarget?await od(n,e.countTarget,e.targetFields):void 0,b=us(f?.ofRun),S=e.sentBefore?.(),R=s===0?0:S!==void 0?Math.max(0,S-(b.deliverability??0)):On(0,m!==void 0?ls(m):0)+(h?.held.size??0),k=m!==void 0?Cs(m):void 0,g=s===0?0:sd(n,{bulkThreshold:e.bulkThreshold,duplicateRules:k,leaseAssigns:(e.mutePlan?.()?.assign.length??0)>0,...h?{targetHeld:h.held,targetGroups:h.groups}:{}}),w=dt({run:Ya(n.objects,{bulkThreshold:e.bulkThreshold,duplicateRules:k})+R+g,...lt(l),...zr(e.mutePlan?.()),...n.readBack!==void 0&&n.readBack>0?{readBack:n.readBack}:{},...b},y),M=e.confirmAboveRecords,A=M>0&&s>M?M:void 0,O=(n.unwritable??[]).map(({objectApiName:T,rows:v,why:j,key:x})=>({...x!==void 0?{key:x}:{},objectApiName:T,rows:v,why:j})),E=(n.heldBack??[]).map(({objectApiName:T,rows:v,parent:j,field:x,parents:_})=>({objectApiName:T,rows:v,parent:j,field:x,..._!==void 0?{parents:_.map(z=>({...z}))}:{}})),F=f?.gate,N=s===0?O.length>0?"refused":"writes":o.verdict==="exceeds"||w.verdict==="exceeds"||u!==void 0||l?.refusal!==void 0?"refused":A!==void 0||O.length>0||t.totalRows>0&&o.verdict!=="fits"||a.some(T=>T.verdict!=="fits")||d!==void 0||l!==void 0||F?.verdict==="asks"?"asks":"writes";return{check:{objects:r,total:s,alreadyCopied:n.alreadyCopied,...(n.alreadyLinked??0)>0?{alreadyLinked:n.alreadyLinked}:{},...i>0?{overwrites:i}:{},...(n.rolesByThePlatform??0)>0?{rolesByThePlatform:n.rolesByThePlatform}:{},...(n.rolesLinked??0)>0?{rolesLinked:n.rolesLinked}:{},...A!==void 0?{aboveRecords:A}:{},storage:o.verdict==="unread"?{verdict:"unread",estimateMB:o.estimateMB,unread:o.unread}:t.totalRows===0?{verdict:"fits",estimateMB:0}:{verdict:o.verdict,estimateMB:o.estimateMB,maxMB:o.maxMB,remainingMB:o.remainingMB},emails:a.map(T=>({limit:T.limit,emails:T.emails,verdict:T.verdict,...T.remaining!==void 0?{remaining:T.remaining}:{},...T.max!==void 0?{max:T.max}:{},...T.alertsCounted?{alertsCounted:!0}:{},objects:T.objects.map(({objectApiName:v,perRecord:j})=>({objectApiName:v,perRecord:j})),...T.unread!==void 0?{unread:T.unread}:{}})),...d!==void 0?{emailsUnread:d}:{},...F?.deliverability?{deliverability:F.deliverability}:{},...O.length>0?{unwritable:O}:{},...E.length>0?{heldBack:E}:{},...s>0?{apiRequests:w.verdict==="unread"?{verdict:"unread",estimate:w.estimate,unread:w.unread}:{verdict:w.verdict,estimate:w.estimate,remaining:w.remaining,max:w.max}}:{},verdict:N,...u!==void 0?{checkpointUnread:u}:{}},plan:t,storage:o,emails:a,api:w,...l!==void 0?{checkpoint:l}:{},...u!==void 0?{checkpointFailed:u}:{},...f!==void 0?{runEmails:f}:{},emailsAccepted:e.emails.accepted}}function ad(n,e){let{check:t,storage:r,emails:s,plan:i,api:o}=n,a=[],d=t.unwritable??[];if(d.length>0&&(e.policy!=="ask"||t.total===0)&&a.push({code:"SYNC_TARGET_UNWRITABLE",message:ld(d,e.org,t.heldBack)}),t.total===0)return a;if(n.checkpointFailed!==void 0)a.push({code:ss,message:n.checkpointFailed});else{let l=ut(n.checkpoint);l&&a.push(l)}i.totalRows>0&&r.verdict==="exceeds"&&a.push({code:"SYNC_STORAGE_EXCEEDED",message:`The records to write take about ${xe(r.estimateMB)} MB of data storage, and ${e.org} has ${r.remainingMB} MB left of ${r.maxMB} MB${ft(pt(r),e.org)}: leave objects out, narrow their filters, or free data storage in ${e.org}. To copy a sample of the source that fits ${e.org} instead, use Forge with Depth ALL and a sample that fits the target (sandforge clone --depth all --fit share). Nothing was written.`});let c=ct(o,e.org,at);if(c&&a.push({code:ns,message:c}),e.policy!=="ask"){let l=cs(s,e.org);l&&a.push({code:"SYNC_EMAILS_EXCEEDED",message:`${l} Nothing was written.`});let u=n.runEmails?.gate,f=u?.stop;f&&a.push({code:f.code,message:Qt(f.message,"sync",e.emailsLiftedBy),...ve(u,!1)})}return a}async function dd(n,e){let{check:t,storage:r,emails:s,api:i}=n,[o]=ad(n,e);if(o)return{go:!1,...o};if(t.total===0)return{go:!0,asked:!1};let a=n.runEmails?.gate;if(e.policy!=="ask")return{go:!0,asked:!1,...ve(a,n.emailsAccepted)};let d=t.unwritable??[];if(t.verdict==="writes")return{go:!0,asked:!1,...ve(a,!1)};let c=_r(e.orgTier),l=s.filter(m=>m.verdict==="exceeds").map(as),u=s.filter(m=>m.verdict==="unread").map(ds),f=e.confirm?await e.confirm({stage:"write",module:"sync",org:e.org,orgTier:e.orgTier,objects:t.objects,total:t.total,...t.aboveRecords!==void 0?{aboveRecords:t.aboveRecords}:{},...c!==void 0&&t.total>c?{largeVolume:c}:{},storage:fs(r),counted:!0,...t.overwrites!==void 0?{overwrites:t.overwrites}:{},...l.length>0?{emails:l}:{},...u.length>0?{emailsUnread:u}:{},...t.emailsUnread!==void 0?{emailsUncounted:t.emailsUnread}:{},...t.alreadyCopied>0?{alreadyCopied:t.alreadyCopied}:{},...(t.alreadyLinked??0)>0?{alreadyLinked:t.alreadyLinked}:{},...(t.rolesLinked??0)>0?{rolesLinked:t.rolesLinked}:{},...d.length>0?{unwritable:d}:{},...t.heldBack!==void 0&&t.heldBack.length>0?{heldBack:t.heldBack}:{},...rs(i),...n.checkpoint!==void 0?{checkpoint:n.checkpoint}:{},...a?.confirmation}):"unavailable";if(f==="confirmed")return{go:!0,asked:!0,...ve(a,a?.verdict==="asks")};let p=ve(a,!1);return f==="declined"?{go:!1,code:"SYNC_WRITE_DECLINED",message:"The sync was cancelled before it wrote anything. Nothing was written.",...p}:{go:!1,code:"SYNC_CONFIRMATION_UNAVAILABLE",message:"The sync needed a confirmation before it wrote, and there was no one to ask. Nothing was written.",...p}}var cd={notInTarget:n=>`${n} has no such object, or the user the run writes as cannot see it`,notCreateable:n=>`the user the run writes as may not create its records in ${n}`,notUpdateable:n=>`the user the run writes as may not edit its records in ${n}`,unread:n=>`${n} did not describe it, so what it takes could not be told`,notAKey:(n,e)=>`its upsert matches on ${e??"a field"}, neither an External ID nor an idLookup field in ${n}`};function ld(n,e,t=[]){let r=n.map(({objectApiName:b,rows:S,why:R,key:k})=>`${b} (${S} record${S===1?"":"s"}): ${cd[R](e,k)}`).join("; "),s=n.length===1?"it":"them",i=n.filter(({why:b})=>b==="notAKey"),o=n.filter(({why:b})=>b!=="notAKey"),a=i.length>0&&o.length>0,d=b=>b.map(({objectApiName:S})=>S).join(" and "),c=`give the user SandForge writes as access to ${a?d(o):s} in ${e}`,l=`match ${a?`${d(i)} `:""}on an External ID field of ${e}`,u=a?`${c}, or ${l}`:i.length>0?`or ${l}`:`or ${c}`,f=new Set(n.map(({objectApiName:b})=>b)),p=({parent:b,field:S})=>`whose ${S} names ${/^[aeiou]/i.test(b)?"an":"a"} ${b} record `+(f.has(b)?"left out":"held back"),m=t.flatMap(({objectApiName:b,rows:S,parent:R,field:k,parents:g})=>(g??[{parent:R,field:k,rows:S}]).map(w=>`${w.rows} ${b} record${w.rows===1?"":"s"}, ${p(w)}`)).join("; "),y=n.filter(({why:b})=>b==="notInTarget"),h=y.length>0?` Where ${e} has not ${d(y)}, Compare deploys ${y.length===1?"it":"them"} from the source: tick Data Model, compare, then Deploy from Diff.`:"";return`${e} would take no record of ${n.length===1?"one object":`${n.length} objects`} the sync writes \u2014 ${r}.`+(m!==""?` Left out, ${s==="it"?"it holds":"they hold"} back ${m}.`:"")+` Leave ${s} out of the run, ${u}.${h} Nothing was written.`}function zl(n,e){return{measure:async t=>(await Ki(t,n)).check,hold:async t=>{let r=await Ki(t,n),s=await dd(r,e);return{check:r.check,answer:await ud(r,s,n.checkpointFirst)}}}}async function ud(n,e,t){let r=n.checkpoint;if(!e.go||r===void 0||t===void 0)return e;let s=await is(()=>t.take(r));return"stop"in s?{go:!1,...s.stop}:{...e,checkpoint:s.checkpoint}}function ql(n,e){return e==="insert"||e==="update"||e==="delete"}function Kl(n,e,t,r,s){let i,o,a,d,c=n(async u=>{let f=i?.automation;return f&&u.every(p=>f.objectsRead.includes(p))?Vi(f,u):e(u)},()=>i?.plan),l=u=>{if(!Ur(u))throw u;return{go:!1,code:u.code,message:u.message}};return{gate:{measure:u=>c.measure(u),hold:async u=>{let f=u.objects.filter(m=>m.rows>0).map(m=>m.objectApiName);if(!i&&f.length>0){d=await e(f).catch(m=>({unread:m instanceof Error?m.message:String(m)}));try{i=await t(d),a=i.muted}catch(m){return{check:await c.measure(u),answer:l(m)}}}let p=await c.hold(u);if(p.answer.go&&i?.prepared&&!o){try{o=await i.prepared.acquire(r),a=o.outcome}catch(R){let{checkpoint:k}=p.answer;return{check:p.check,answer:{...l(R),...k?{checkpoint:k}:{}}}}let{checkpoint:m,emails:y}=p.answer,{deliverability:h}=p.check,b=Ji(u),S=i.plan&&d&&"objects"in d?ps({planned:h?.senders??[],held:Hn(Gt(d,Wr(i.plan,o.outcome),b),{writes:b}),...h?{reading:h.reading}:{},accepted:y?.accepted===!0,target:s.target,run:"sync"}):void 0;if(S)return{check:p.check,answer:{go:!1,code:S.code,message:Qt(S.message,"sync",s.liftedBy),...m?{checkpoint:m}:{},...y?{emails:y}:{}}}}return p}},release:async()=>(o&&(a=await o.release()),a),lease:()=>{let u=o;if(u)return{assigned:u.outcome.assigned.length,giveBack:async()=>(a=await u.release(),a)}}}}export{St as a,At as b,wd as c,Sd as d,Fd as e,jd as f,vd as g,ii as h,Ro as i,zd as j,qd as k,Kd as l,tc as m,nc as n,rc as o,sc as p,To as q,Mo as r,ic as s,vo as t,oc as u,ac as v,No as w,ae as x,$e as y,fi as z,gi as A,lc as B,Do as C,Lo as D,uc as E,fn as F,Oc as G,ui as H,Pi as I,Mi as J,Ui as K,Ga as L,wl as M,Sl as N,Mt as O,On as P,bl as Q,qa as R,kl as S,Ol as T,Al as U,Cl as V,Ul as W,Ki as X,ad as Y,dd as Z,ld as _,zl as $,ud as aa,ql as ba,Kl as ca};