sandforge 1.80.0 → 1.82.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 (266) hide show
  1. package/README.md +48 -0
  2. package/bin/sandforge-pipeline.mjs +12 -0
  3. package/bin/sandforge-users.mjs +12 -0
  4. package/lib/{chunk-J525F5KI.mjs → chunk-27Z76O2O.mjs} +1 -1
  5. package/lib/chunk-2JZGCCPG.mjs +9 -0
  6. package/lib/{chunk-ELFXJHU7.mjs → chunk-2UU42PTD.mjs} +1 -1
  7. package/lib/{chunk-N652NMZ4.mjs → chunk-32EUNQT6.mjs} +52 -52
  8. package/lib/chunk-3C2ZZIFN.mjs +7 -0
  9. package/lib/chunk-3CX7GPCR.mjs +7 -0
  10. package/lib/chunk-3HEMJTAP.mjs +925 -0
  11. package/lib/{chunk-BY2HJFFG.mjs → chunk-3HROD5RE.mjs} +1 -1
  12. package/lib/{chunk-OHWNPXWW.mjs → chunk-3MGMNK3Q.mjs} +1 -1
  13. package/lib/{chunk-PZPJKATS.mjs → chunk-3SKLBRPL.mjs} +8 -8
  14. package/lib/chunk-3XG25GTF.mjs +7 -0
  15. package/lib/chunk-42BFLWHR.mjs +7 -0
  16. package/lib/chunk-466F37VD.mjs +7 -0
  17. package/lib/chunk-47UHTN3Q.mjs +7 -0
  18. package/lib/chunk-4JKR4PTZ.mjs +8 -0
  19. package/lib/{chunk-COFG7Q6R.mjs → chunk-52EXDVPN.mjs} +1 -1
  20. package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
  21. package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
  22. package/lib/chunk-5K2I2DMP.mjs +11 -0
  23. package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
  24. package/lib/{chunk-BV6VTP3J.mjs → chunk-6GQUZ4IP.mjs} +1 -1
  25. package/lib/chunk-6KP6WETK.mjs +9 -0
  26. package/lib/{chunk-MJVTDA5Q.mjs → chunk-6VSZNZHH.mjs} +1 -1
  27. package/lib/{chunk-XUWL6ZPC.mjs → chunk-7CVDVBEE.mjs} +1 -1
  28. package/lib/{chunk-UCD54V2M.mjs → chunk-7EYQYZJP.mjs} +1 -1
  29. package/lib/{chunk-5K5VLULK.mjs → chunk-7LKI7OAS.mjs} +1 -1
  30. package/lib/chunk-7PY3VQP3.mjs +7 -0
  31. package/lib/chunk-7SDZR6SR.mjs +7 -0
  32. package/lib/chunk-7WSLT5VX.mjs +8 -0
  33. package/lib/chunk-A32ISQ6M.mjs +28 -0
  34. package/lib/{chunk-M3ROUWDX.mjs → chunk-A65ADTCR.mjs} +1 -1
  35. package/lib/chunk-A7JJWOLT.mjs +7 -0
  36. package/lib/chunk-AUS6NFLZ.mjs +8 -0
  37. package/lib/chunk-BMTNTBBM.mjs +7 -0
  38. package/lib/{chunk-SOU4FRYN.mjs → chunk-BN33LVPQ.mjs} +1 -1
  39. package/lib/chunk-BNKT3R3F.mjs +7 -0
  40. package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
  41. package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
  42. package/lib/{chunk-WA7EYLAQ.mjs → chunk-C2N2TNEU.mjs} +1 -1
  43. package/lib/{chunk-BKDV4ENO.mjs → chunk-C3LNYAVJ.mjs} +1 -1
  44. package/lib/{chunk-XLXIPIEW.mjs → chunk-CBL42DUU.mjs} +1 -1
  45. package/lib/chunk-CCEH7L53.mjs +7 -0
  46. package/lib/chunk-CELEBWEZ.mjs +7 -0
  47. package/lib/chunk-CV47FDQW.mjs +7 -0
  48. package/lib/{chunk-2UZPIMUC.mjs → chunk-CZLJZQCS.mjs} +1 -1
  49. package/lib/chunk-DBBPDSFN.mjs +7 -0
  50. package/lib/chunk-DIL62SUN.mjs +7 -0
  51. package/lib/chunk-DIS254AN.mjs +7 -0
  52. package/lib/{chunk-BTWDMNN3.mjs → chunk-DJCGURW7.mjs} +1 -1
  53. package/lib/{chunk-F6GUDTOB.mjs → chunk-DT3T7FRD.mjs} +1 -1
  54. package/lib/{chunk-IGYH7GMA.mjs → chunk-DWMRIWV5.mjs} +1 -1
  55. package/lib/{chunk-YRQGKDHM.mjs → chunk-EEFUE2ES.mjs} +1 -1
  56. package/lib/{chunk-FGRG7ANU.mjs → chunk-EOFO3PHS.mjs} +1 -1
  57. package/lib/{chunk-KBJ5VERV.mjs → chunk-FA4ZKDCU.mjs} +1 -1
  58. package/lib/{chunk-WU3GLFZO.mjs → chunk-FKK5YBGZ.mjs} +1 -1
  59. package/lib/chunk-FOIWWK7G.mjs +156 -0
  60. package/lib/chunk-FZF23M6R.mjs +7 -0
  61. package/lib/chunk-G2JR3F63.mjs +7 -0
  62. package/lib/{chunk-JEERQRLW.mjs → chunk-GBGHJTPC.mjs} +1 -1
  63. package/lib/{chunk-3RZQZHEB.mjs → chunk-GCGHHN4K.mjs} +1 -1
  64. package/lib/{chunk-RPI7LRTW.mjs → chunk-GGNUACTY.mjs} +1 -1
  65. package/lib/{chunk-EMNC6YI4.mjs → chunk-GGUOIDWP.mjs} +1 -1
  66. package/lib/chunk-GHPR5UVV.mjs +7 -0
  67. package/lib/{chunk-X5JYBPXP.mjs → chunk-GJ6SZVHT.mjs} +1 -1
  68. package/lib/{chunk-W622GUAW.mjs → chunk-H4JUYUSL.mjs} +1 -1
  69. package/lib/{chunk-XAMBCQPU.mjs → chunk-H4OBZIX3.mjs} +1 -1
  70. package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
  71. package/lib/{chunk-L77FJZEP.mjs → chunk-HFUDCNU5.mjs} +1 -1
  72. package/lib/chunk-HIHCYMSL.mjs +7 -0
  73. package/lib/chunk-HKUWHVI7.mjs +9 -0
  74. package/lib/chunk-HQQVANWQ.mjs +20 -0
  75. package/lib/chunk-ICIYL45C.mjs +7 -0
  76. package/lib/chunk-IRZJU2PG.mjs +22 -0
  77. package/lib/chunk-ISSP2FZ5.mjs +7 -0
  78. package/lib/chunk-IVZJSDJD.mjs +7 -0
  79. package/lib/chunk-J24TIGSI.mjs +10 -0
  80. package/lib/{chunk-UNJA4J37.mjs → chunk-JESRFE2Z.mjs} +4 -4
  81. package/lib/chunk-JFNLKHY6.mjs +8 -0
  82. package/lib/chunk-JH27IKCO.mjs +9 -0
  83. package/lib/chunk-JJITOWZK.mjs +7 -0
  84. package/lib/{chunk-E5AHXLS6.mjs → chunk-JKT5YAQ2.mjs} +1 -1
  85. package/lib/{chunk-IWDREM66.mjs → chunk-JLZRZL5E.mjs} +1 -1
  86. package/lib/{chunk-FPKYYFM7.mjs → chunk-JPEVIXNH.mjs} +1 -1
  87. package/lib/chunk-JQZTMFO7.mjs +7 -0
  88. package/lib/chunk-KIMQQ6JQ.mjs +7 -0
  89. package/lib/{chunk-MILU7WFN.mjs → chunk-KJYEQHYP.mjs} +1 -1
  90. package/lib/chunk-KKOA62S4.mjs +474 -0
  91. package/lib/chunk-KP5G6FUC.mjs +7 -0
  92. package/lib/{chunk-JWTSEDIQ.mjs → chunk-L4INJ5TZ.mjs} +1 -1
  93. package/lib/{chunk-OLSGVAIL.mjs → chunk-LAUOSXMN.mjs} +53 -53
  94. package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
  95. package/lib/{chunk-KDGMAGQR.mjs → chunk-LHU6CPGE.mjs} +1 -1
  96. package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
  97. package/lib/chunk-LXDSRP2W.mjs +7 -0
  98. package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
  99. package/lib/{chunk-TTKXMDBN.mjs → chunk-MKTXJCXN.mjs} +4 -4
  100. package/lib/chunk-MUEQRIK7.mjs +9 -0
  101. package/lib/{chunk-IOIWJ3DJ.mjs → chunk-NLB3RGIY.mjs} +1 -1
  102. package/lib/{chunk-O2HDYYUV.mjs → chunk-NWOI25WY.mjs} +1 -1
  103. package/lib/chunk-O2PUGRNW.mjs +10 -0
  104. package/lib/chunk-O4BROUGM.mjs +7 -0
  105. package/lib/chunk-OETEC3P7.mjs +7 -0
  106. package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
  107. package/lib/chunk-P55MKIZX.mjs +37 -0
  108. package/lib/chunk-P63WJMXQ.mjs +7 -0
  109. package/lib/chunk-PBE44M2Y.mjs +7 -0
  110. package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
  111. package/lib/chunk-PE435FVH.mjs +15 -0
  112. package/lib/chunk-PPGDAUEQ.mjs +7 -0
  113. package/lib/{chunk-SE4QEZUG.mjs → chunk-PPHVWUFY.mjs} +1 -1
  114. package/lib/{chunk-CU2INBND.mjs → chunk-PR74GYVI.mjs} +1 -1
  115. package/lib/chunk-PWVDNN2C.mjs +7 -0
  116. package/lib/{chunk-6XYKJSGX.mjs → chunk-PYRZFUVU.mjs} +1 -1
  117. package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
  118. package/lib/{chunk-DYFALGRT.mjs → chunk-Q3DY7TO2.mjs} +1 -1
  119. package/lib/{chunk-BGUEWRK2.mjs → chunk-Q6SXNKV2.mjs} +1 -1
  120. package/lib/chunk-QAPVKPEC.mjs +7 -0
  121. package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
  122. package/lib/{chunk-TSLJUSLW.mjs → chunk-RCYEBY42.mjs} +1 -1
  123. package/lib/chunk-RLWB7F26.mjs +7 -0
  124. package/lib/{chunk-FXXLX4O6.mjs → chunk-RTWYLOCA.mjs} +1 -1
  125. package/lib/chunk-RYRMUPMY.mjs +7 -0
  126. package/lib/chunk-SAMWHL22.mjs +13 -0
  127. package/lib/{chunk-IZQZ6ZUF.mjs → chunk-SFGZFB4F.mjs} +1 -1
  128. package/lib/{chunk-FKG7Q3WH.mjs → chunk-SNEOKYV7.mjs} +1 -1
  129. package/lib/{chunk-3TJON4F3.mjs → chunk-STRMWSIQ.mjs} +1 -1
  130. package/lib/chunk-SZGGFST2.mjs +272 -0
  131. package/lib/{chunk-SOGQW4IG.mjs → chunk-T7WREYA5.mjs} +1 -1
  132. package/lib/{chunk-NTFIRZP6.mjs → chunk-TCBAE65A.mjs} +1 -1
  133. package/lib/{chunk-KYEDBS54.mjs → chunk-TEIBWMJM.mjs} +1 -1
  134. package/lib/{chunk-YKKRIEH4.mjs → chunk-TMA34QMA.mjs} +1 -1
  135. package/lib/chunk-TQ2TQHTT.mjs +9 -0
  136. package/lib/{chunk-HEKAZJRH.mjs → chunk-TWV4A5RK.mjs} +1 -1
  137. package/lib/{chunk-CEX3NEZL.mjs → chunk-UHFLKP26.mjs} +1 -1
  138. package/lib/chunk-UV74P4H2.mjs +7 -0
  139. package/lib/{chunk-WR4Q363I.mjs → chunk-V3R45ZWT.mjs} +1 -1
  140. package/lib/{chunk-GSKCGQIP.mjs → chunk-VPDEJGPS.mjs} +1 -1
  141. package/lib/{chunk-HLWMJF6Y.mjs → chunk-VQJMP3DC.mjs} +1 -1
  142. package/lib/chunk-VV3B6IC3.mjs +7 -0
  143. package/lib/{chunk-PJ5I73CK.mjs → chunk-VYOYXTCU.mjs} +1 -1
  144. package/lib/{chunk-NZC67CGR.mjs → chunk-VZT4E2OJ.mjs} +1 -1
  145. package/lib/{chunk-AEKONPF4.mjs → chunk-VZVICK7Q.mjs} +1 -1
  146. package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
  147. package/lib/chunk-WEMLDUQA.mjs +7 -0
  148. package/lib/{chunk-MYW5QNGI.mjs → chunk-WOOUISSO.mjs} +1 -1
  149. package/lib/{chunk-G35N4P7D.mjs → chunk-WSUKC2U3.mjs} +1 -1
  150. package/lib/{chunk-ZVAED4QV.mjs → chunk-WT3SCUHS.mjs} +1 -1
  151. package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
  152. package/lib/{chunk-DBB3EMIN.mjs → chunk-XFU3HRUV.mjs} +1 -1
  153. package/lib/chunk-XK5W7BVE.mjs +7 -0
  154. package/lib/{chunk-2GTBABKU.mjs → chunk-XO5FBOQF.mjs} +1 -1
  155. package/lib/{chunk-CHYDMRSV.mjs → chunk-XSKPYGMT.mjs} +1 -1
  156. package/lib/chunk-XU25YA46.mjs +9 -0
  157. package/lib/chunk-XZISAZA6.mjs +7 -0
  158. package/lib/chunk-Y4TDVDP2.mjs +13 -0
  159. package/lib/chunk-YAIIRFKJ.mjs +8 -0
  160. package/lib/{chunk-LKQ5RKIV.mjs → chunk-YAJQS3OL.mjs} +1 -1
  161. package/lib/{chunk-74Q6DORA.mjs → chunk-YGJF55VJ.mjs} +1 -1
  162. package/lib/chunk-YH4DYI6D.mjs +7 -0
  163. package/lib/chunk-YMDFF657.mjs +10 -0
  164. package/lib/{chunk-2BA2XKAY.mjs → chunk-YT22LMF7.mjs} +1 -1
  165. package/lib/{chunk-IG2MTQRP.mjs → chunk-Z42PHCVZ.mjs} +1 -1
  166. package/lib/{chunk-2NBYT7GR.mjs → chunk-ZHIZY3ZC.mjs} +1 -1
  167. package/lib/chunk-ZQO5PDX5.mjs +48 -0
  168. package/lib/chunk-ZRUDYB7O.mjs +7 -0
  169. package/lib/{chunk-BXU6WFMH.mjs → chunk-ZUBBEP75.mjs} +1 -1
  170. package/lib/chunk-ZUOPC4W2.mjs +7 -0
  171. package/lib/{chunk-GGD7ON3M.mjs → chunk-ZUTUYBNW.mjs} +1 -1
  172. package/lib/{chunk-MHMH6MTP.mjs → chunk-ZXFL2MSN.mjs} +1 -1
  173. package/lib/sandforge-autopilot.mjs +11 -11
  174. package/lib/sandforge-backup.mjs +63 -32
  175. package/lib/sandforge-checkpoint.mjs +1 -348
  176. package/lib/sandforge-cleanup.mjs +1 -1
  177. package/lib/sandforge-clone.mjs +1 -1
  178. package/lib/sandforge-compare.mjs +1 -1
  179. package/lib/sandforge-dataops.mjs +1 -1
  180. package/lib/sandforge-empty.mjs +11 -11
  181. package/lib/sandforge-env.mjs +186 -140
  182. package/lib/sandforge-frozen.mjs +1 -266
  183. package/lib/sandforge-mcp.mjs +33 -14
  184. package/lib/sandforge-monitor.mjs +1 -1
  185. package/lib/sandforge-pipeline.mjs +88 -0
  186. package/lib/sandforge-seed.mjs +1 -1
  187. package/lib/sandforge-sync.mjs +1 -1
  188. package/lib/sandforge-users.mjs +157 -0
  189. package/lib/sandforge.mjs +1 -22
  190. package/lib/sf/sandforge/autopilot.mjs +20 -0
  191. package/lib/sf/sandforge/backup.mjs +20 -0
  192. package/lib/sf/sandforge/checkpoint.mjs +20 -0
  193. package/lib/sf/sandforge/cleanup.mjs +20 -0
  194. package/lib/sf/sandforge/clone.mjs +20 -0
  195. package/lib/sf/sandforge/compare.mjs +20 -0
  196. package/lib/sf/sandforge/dataops.mjs +20 -0
  197. package/lib/sf/sandforge/empty.mjs +20 -0
  198. package/lib/sf/sandforge/env.mjs +20 -0
  199. package/lib/sf/sandforge/frozen.mjs +20 -0
  200. package/lib/sf/sandforge/hardis-commands.mjs +20 -0
  201. package/lib/sf/sandforge/index.mjs +20 -0
  202. package/lib/sf/sandforge/mcp.mjs +20 -0
  203. package/lib/sf/sandforge/monitor.mjs +20 -0
  204. package/lib/sf/sandforge/pipeline.mjs +20 -0
  205. package/lib/sf/sandforge/seed.mjs +20 -0
  206. package/lib/sf/sandforge/sync.mjs +20 -0
  207. package/lib/sf/sandforge/users.mjs +20 -0
  208. package/lib/sfHelpHook.mjs +7 -0
  209. package/lib/sfPlugin.mjs +11 -0
  210. package/oclif.manifest.json +1 -0
  211. package/package.json +18 -3
  212. package/lib/chunk-2CNCDM56.mjs +0 -7
  213. package/lib/chunk-3F6Q5E7I.mjs +0 -14
  214. package/lib/chunk-4VS2V6WU.mjs +0 -25
  215. package/lib/chunk-5P4PHJRL.mjs +0 -9
  216. package/lib/chunk-5TC3QB4U.mjs +0 -10
  217. package/lib/chunk-7ABODJ4G.mjs +0 -7
  218. package/lib/chunk-7EGQP6S4.mjs +0 -7
  219. package/lib/chunk-7FFGJWHN.mjs +0 -7
  220. package/lib/chunk-7YDNUBO5.mjs +0 -7
  221. package/lib/chunk-A527W53V.mjs +0 -7
  222. package/lib/chunk-ADOAS63R.mjs +0 -7
  223. package/lib/chunk-B5QQJ4SI.mjs +0 -7
  224. package/lib/chunk-CION3VMZ.mjs +0 -7
  225. package/lib/chunk-CSBS5U5I.mjs +0 -7
  226. package/lib/chunk-DB7RBE5D.mjs +0 -7
  227. package/lib/chunk-E5ZB3LU5.mjs +0 -7
  228. package/lib/chunk-EFR2Y7E4.mjs +0 -7
  229. package/lib/chunk-EHQ3FX6X.mjs +0 -7
  230. package/lib/chunk-EQNW3UC2.mjs +0 -7
  231. package/lib/chunk-F43REJDZ.mjs +0 -10
  232. package/lib/chunk-GSG7WZHM.mjs +0 -7
  233. package/lib/chunk-HOJYWTP7.mjs +0 -20
  234. package/lib/chunk-HS4YRX4J.mjs +0 -7
  235. package/lib/chunk-I7O6C2B5.mjs +0 -8
  236. package/lib/chunk-IFETCRWE.mjs +0 -10
  237. package/lib/chunk-IQXHJEYB.mjs +0 -7
  238. package/lib/chunk-JPUR2CFX.mjs +0 -10
  239. package/lib/chunk-K327QKMD.mjs +0 -7
  240. package/lib/chunk-KRCA6IPH.mjs +0 -8
  241. package/lib/chunk-LPBMBW3O.mjs +0 -13
  242. package/lib/chunk-LWW4U276.mjs +0 -7
  243. package/lib/chunk-MFG4MUIO.mjs +0 -9
  244. package/lib/chunk-MJU2PGZQ.mjs +0 -15
  245. package/lib/chunk-OAZRPP4I.mjs +0 -7
  246. package/lib/chunk-OO6CLPEH.mjs +0 -7
  247. package/lib/chunk-OPXCV2KL.mjs +0 -7
  248. package/lib/chunk-P33PSCXK.mjs +0 -7
  249. package/lib/chunk-Q3DM32KF.mjs +0 -11
  250. package/lib/chunk-QR3WELJQ.mjs +0 -7
  251. package/lib/chunk-QWT2C74M.mjs +0 -7
  252. package/lib/chunk-R3X3LV64.mjs +0 -14
  253. package/lib/chunk-RMBPOTD7.mjs +0 -7
  254. package/lib/chunk-SIHORWVK.mjs +0 -7
  255. package/lib/chunk-T62WNR54.mjs +0 -7
  256. package/lib/chunk-TTFDUKUS.mjs +0 -47
  257. package/lib/chunk-VE6XKGGD.mjs +0 -7
  258. package/lib/chunk-VGW4MXXZ.mjs +0 -7
  259. package/lib/chunk-VS7ZXUII.mjs +0 -824
  260. package/lib/chunk-VXQLDM4R.mjs +0 -7
  261. package/lib/chunk-VYXMVJL5.mjs +0 -7
  262. package/lib/chunk-W7U5E5ZL.mjs +0 -9
  263. package/lib/chunk-WXAQ7FK3.mjs +0 -115
  264. package/lib/chunk-YS4G22C2.mjs +0 -7
  265. package/lib/chunk-ZM6OJGIG.mjs +0 -7
  266. package/lib/chunk-ZUTYVST5.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{c as zt,d as Is,e as Ps,f as qt}from"./chunk-MHMH6MTP.mjs";import{a as _e,b as Es,c as Ts,d as Ms,f as Fs,g as js,h as vs,i as Ns,j as Ds,l as Z,n as Kt,o as Ht,p as xs,q as Ls,s as We}from"./chunk-COFG7Q6R.mjs";import{b as at,c as dt,d as Yt,e as Jt,f as $s,g as Vt}from"./chunk-PJ5I73CK.mjs";import{b as Bs,d as _s}from"./chunk-BKDV4ENO.mjs";import{a as Ws,c as Gs}from"./chunk-X5JYBPXP.mjs";import{Bc as br}from"./chunk-2CNCDM56.mjs";import{a as Te,c as Ut}from"./chunk-BOGNK4LV.mjs";import{R as cs,S as ls,X as us,Y as ps,_ as fs,ab as gs,bb as hs,g as is,ib as ms,jb as ys,kb as ws,lb as Ss,mb as Rs,ob as bs,pb as ks,rb as Os,vb as As,wb as Cs}from"./chunk-4VS2V6WU.mjs";import{l as os,m as as}from"./chunk-KYEDBS54.mjs";import{k as ds}from"./chunk-6XYKJSGX.mjs";import{i as kr,p as Br}from"./chunk-F43REJDZ.mjs";import{$ as $r,G as Sr,N as Rr,Z as Lr,m as Wt,r as wr}from"./chunk-JPUR2CFX.mjs";import{a as Gt}from"./chunk-QSRAEUGZ.mjs";import{f as Pr,h as Er,i as $e,k as Tr,l as Mr,m as Fr,o as jr,p as vr,q as Nr,r as Dr,s as xr}from"./chunk-G35N4P7D.mjs";import{l as yr}from"./chunk-SAR5622P.mjs";import{t as Cr,x as Ir}from"./chunk-MFG4MUIO.mjs";import{A as xt,B as nt,C as Lt,E as $t,F as ir,G as or,H as Ee,n as Jn,o as De,q as Vn,r as Xn,s as Zn,t as Qn,u as er,w as rr,x as xe,y as Ae,z as sr}from"./chunk-EQNW3UC2.mjs";import{b as Bt,c as Le,d as ee}from"./chunk-GSKCGQIP.mjs";import{a as Hn,v as Yn}from"./chunk-ZUTYVST5.mjs";import{c as tr,d as nr}from"./chunk-CU2INBND.mjs";import{Aa as Qr,Ba as es,D as Wr,E as Gr,Ga as ts,Ha as ns,Ia as rs,K as Ur,L as zr,N as me,O as rt,P as qr,Q as st,R as Kr,S as Hr,T as it,U as ot,W as Yr,Wa as ss,_ as Be,qa as Jr,ta as Vr,ua as Xr,v as Or,w as Ar,wa as Zr}from"./chunk-VYXMVJL5.mjs";import{q as _r}from"./chunk-AEKONPF4.mjs";import{a as Kn}from"./chunk-EADHKH3A.mjs";import{a as pr,d as fr,e as gr,f as hr,g as mr}from"./chunk-L77FJZEP.mjs";import{E as X,F as ie,H as Dt,M as zn,O as qn,e as tt,f as Gn,l as Un,q as Nt}from"./chunk-A527W53V.mjs";import{f as Wn,h as he}from"./chunk-TZE3Y7IQ.mjs";import{c as ar,d as dr,f as cr,h as lr,j as ur,k as _t}from"./chunk-GGD7ON3M.mjs";import{b as Y}from"./chunk-CA5NAXSU.mjs";import{$b as vn,Hb as Pe,Ib as pe,Mb as Ze,Rc as _n,Wb as Qe,Ya as Fn,Za as Ve,ed as vt,f as Tn,gc as et,h as jt,i as Mn,j as Oe,jb as jn,kc as Nn,lc as Dn,mc as xn,nc as Ln,oc as $n,pc as Bn,yb as Xe}from"./chunk-TTFDUKUS.mjs";import{b as Ne,k as Tt,l as Mt,u as Pn,v as En,z as Ft}from"./chunk-7EANH5PY.mjs";var ct=class{classify(e){let t=Ve(e.statusCode),s=this.getSuggestedAction(e.statusCode,t);return{originalError:e,classification:t,suggestedAction:s}}classifyBatch(e){let t=e.map(a=>this.classify(a)),s={auth:0,permission:0,schema:0,data:0,validation:0,limit:0,network:0,trigger:0,reference:0,unknown:0},r={},i=0;for(let a of t){a.classification.retryable&&i++;let d=a.classification.category??"unknown";s[d]=(s[d]??0)+1,r[a.originalError.statusCode]=(r[a.originalError.statusCode]??0)+1}let o={totalErrors:e.length,retryableCount:i,nonRetryableCount:e.length-i,byCategory:s,byErrorCode:r,sampleErrors:e.slice(0,5)};return{classified:t,summary:o}}isRetryable(e){return Ve(e).retryable}hasBlockingError(e){return e.some(t=>Ve(t.statusCode).blockAll===!0)}get knownErrorCount(){return Object.keys(Fn).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 qi(n,e){return new Promise(t=>{if(e?.aborted){t();return}let s=()=>{clearTimeout(r),e?.removeEventListener("abort",s),t()},r=setTimeout(s,n);e?.addEventListener("abort",s,{once:!0})})}var lt=class{constructor(e={}){this.options=e;this.strategy=new Mr({...e.retryConfig,jitter:e.retryConfig?.jitter??!0}),this.classifier=new ct}options;strategy;classifier;async execute(e){let t=this.strategy.getConfig(),s,r=0;for(let i=0;i<=t.maxRetries;i++)try{return{success:!0,result:await e(),attempts:i+1,totalDelay:r}}catch(o){s=o instanceof Error?o:new Error(String(o));let a=Ki(o),d=this.classifier.classify(a);if(!d.classification.retryable)return{success:!1,error:s,attempts:i+1,totalDelay:r};if(i<t.maxRetries){let c={success:!1,error:s,attempts:i+1,totalDelay:r,cancelled:!0};if(this.options.signal?.aborted)return c;let l=this.strategy.calculateDelay(i);if(this.options.onRetry?.(i,d,l),r+=l,await qi(l,this.options.signal),this.options.signal?.aborted)return{...c,totalDelay:r}}}return{success:!1,error:s,attempts:t.maxRetries+1,totalDelay:r}}async executeBatch(e,t){let s=[...e],r=[],i=[],o=0,a=this.options.retryConfig?.maxRetries??3;for(;s.length>0&&o<=a;){let d=await t(s);r.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(s=c,s.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:r,failures:i}}getClassifier(){return this.classifier}getStrategy(){return this.strategy}};function Ki(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(r=>typeof r=="string"&&r.length>0&&r!=="Error"),s=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(s)?s.filter(r=>typeof r=="string"):void 0}}var Hi=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function Yi(n){if(n===!0||n==="true")return!0;if(n===!1||n==="false")return!1}async function Ji(n,e,t,s=()=>Date.now()){let r=await yr(n,e,{now:s,successfulOnly:!0});return r.state==="running"?{state:"running"}:r.state!=="ended"?r:{state:"ended",created:(r.results.successfulResults??[]).flatMap(o=>{let a=o.sf__Id;return typeof a!="string"||!Hi.test(a)?[]:t&&Yi(o.sf__Created)!==!0?[]:[a]}),...typeof r.info.systemModstamp=="string"?{at:r.info.systemModstamp}:{}}}async function sd(n,e,t,s,r=()=>new Date){let i,o=()=>(i??=(async()=>{if(!s)return 0;try{let d=r().getTime(),c=Date.parse(await s());return Number.isFinite(c)?c-(d+r().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 Ji(t,d.job,d.upsert===!0,()=>r().getTime());if(l.state==="running"||l.state==="unread"){a.push({...c,read:l,answered:!1});continue}let u=r().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 id(n,e){return e.map(({job:t,read:s})=>{let r=`${n}, job ${t}`;switch(s.state){case"ended":return`[INFO] ${r}: the job no line of the run answered ended in the org; ${s.created.length} record(s) it created kept with the run`;case"never-closed":return`[INFO] ${r}: the job was never closed, and wrote nothing`;case"running":return`[INFO] ${r}: the job is still running in the org; read again later`;default:return`[WARN] ${r}: the job could not be read back: ${s.reason}`}})}var Fe=5e3,Qt=200,ut=Ne().refine(n=>Le(n),"not a record id"),Vi=Mt({sourceOrgId:Ne().min(1).max(200),targetOrgId:Ne().min(1).max(200),objectApiName:Ne().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),kind:Pn(["document","attachment"]),sourceId:ut,targetId:ut,sourceVersionId:ut.optional(),sourceModifiedAt:Ft.datetime().optional(),linked:Tt(ut).max(Qt),copiedAt:Ft.datetime()}),Xi=Mt({version:En(1),entries:Tt(Vi).max(Fe)});function zs(n){if(n==null)return{kind:"none"};let e=Xi.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 yd(n,e,t){return n?n.check({orgId:e,orgTier:vn(t),operation:"delete",objectName:"Attachment",recordCount:1,module:"sync"}).allowed:!1}var ce=class extends Error{constructor(e){super(e),this.name="SyncFilesRefusedError"}},Ge=class extends Error{};function Zi(){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 pt(n,e){let t=n;for(let s of e.split(".")){if(typeof t!="object"||t===null)return null;t=t[s]}return Lt(t)}function Me(n,e){return e==null?n:n===void 0||Date.parse(e)>Date.parse(n)?e:n}function Qi(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)?t:0}function Ue(n,e,t){return`${n}|${e}|${t}`}function eo(n,e){let t=e.load(n.id);if(t===null)throw new ce("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 ce(`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 s=new Map;if(t.kind==="stored")for(let r of t.map.entries)s.set(Ue(r.sourceOrgId,r.targetOrgId,r.sourceId),r);return s}var Xt="ContentDocument.LatestPublishedVersion.SystemModstamp";async function to(n,e,t,s){let r=Qe(t.objectApiName),i=t.where?.trim()?` WHERE (${Wn(t.where)})`:"",o=`SELECT Id FROM ${r}${i}`,a=xt(s),d=new Set,c,l=await n.copy.queryRecords(e.sourceOrgId,`SELECT LinkedEntityId, SystemModstamp, ${Xt} FROM ContentDocumentLink WHERE LinkedEntityId IN (${o}) AND (SystemModstamp > ${a} OR ${Xt} > ${a})`);for(let f of l){let p=te(f,"LinkedEntityId");p&&Le(p)&&d.add(p),c=Me(Me(c,pt(f,"SystemModstamp")),pt(f,Xt))}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&&Le(p)&&d.add(p),c=Me(c,pt(f,"LastModifiedDate"))}return{ids:[...d],...c!==void 0?{newest:c}:{}}}async function no(n,e,t){let s=new Map;for(let r of ee(t)){let i=await n.copy.queryRecords(e.sourceOrgId,`SELECT Id, LastModifiedDate FROM Attachment WHERE Id IN (${r})`);for(let o of i){let a=te(o,"Id"),d=Lt(o.LastModifiedDate);a&&d&&s.set(a,d)}}return s}function ro(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 so(n,e,t,s,r,i){let o=[...r.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=xt(s),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=Me(c,pt(f,"SystemModstamp"));let p=te(f,"ContentDocumentId"),h=te(f,"Id");if(!p||!h||(te(f,"ContentLocation")??"S")!=="S")continue;let m=te(f,"Title")??p;d.push({objectApiName:"ContentDocument",sourceId:p,body:{objectApiName:"ContentVersion",id:h},name:m,bytes:Qi(f,"ContentSize"),hosts:[],fields:{Title:m,PathOnClient:te(f,"PathOnClient")??m}})}}return{files:d,...c!==void 0?{newest:c}:{}}}async function io(n,e,t,s){let r=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=s.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 h=te(f,"LatestPublishedVersionId");r.set(p,o("document",p,h?{sourceVersionId:h}:{}))}}let d=[...r.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"),h=te(f,"LinkedEntityId"),m=p?r.get(p):void 0;m&&h&&Le(h)&&m.linked.length<Qt&&m.linked.push(h)}}let c=s.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&&r.set(p,o("attachment",p,{}))}}return r}async function qs(n){let{config:e,option:t,objects:s,deps:r}=n,i=eo(e,r.store),o;try{o=await us(r.copy,e.targetOrgId)}catch(p){throw new ce(`The file storage the target has left could not be read (${Y(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:h,filesSeen:m}of s){if(p.operation==="delete")continue;let y=p.objectApiName,R=await r.sourceIds(p,h),w=[],b=h===void 0?void 0:m!==void 0&&Date.parse(m)>Date.parse(h)?sr(m):h,O=h===void 0?void 0:m,g=new Map;if(b!==void 0)try{let N=new Set(R),D=await to(r,e,p,b);O=Me(O,D.newest);let W=D.ids.filter(z=>!N.has(z));if(W.length>0){let z=n.tie?await n.tie(p,W):{held:new Map};g=z.held;let q=W.filter(G=>!g.has(G)).length;q>0&&w.push(`${q} 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(N){throw new ce(`${y}: the files its records gained since the last run could not be looked up (${Y(N)}). Run it again, or turn the files off. Nothing was written.`)}let S=[...R,...g.keys()],T=await cs({scope:new Map([[y,S]]),sourceOrgId:e.sourceOrgId,maxFileBytes:a,queryRecords:r.copy.queryRecords});if(ls(T)){let N=new Set(T.errors.flatMap(D=>D.samples.flatMap(W=>W.messages)));throw new ce(`${y}: the files of its records could not all be looked up in the source (${[...N].join("; ")}). Run it again, or turn the files off. Nothing was written.`)}let A=Zi();for(let N of T.leftOut)N.reason==="too-large"?A.tooLarge++:N.reason==="external"&&A.external++;A.tooLarge>0&&w.push(`${A.tooLarge} file(s) larger than ${t.maxFileSizeMB} MB were not copied.`);let k=T.files,M=[],F=new Map;try{if(b!==void 0){let W=new Set(k.map(q=>q.sourceId)),z=await so(r,e,y,b,i,W);O=Me(O,z.newest);for(let q of z.files)q.bytes>a?A.tooLarge++:k=[...k,q]}let N=k.filter(W=>!i.has(Ue(e.sourceOrgId,e.targetOrgId,W.sourceId)));if(N.length>0)for(let[W,z]of await io(r,e,y,N))i.set(Ue(e.sourceOrgId,e.targetOrgId,W),z),M.push(z);let D=k.filter(W=>W.objectApiName==="Attachment");D.length>0&&(F=await no(r,e,D.map(W=>W.sourceId)))}catch(N){throw new ce(`${y}: the files an earlier run copied could not be looked up (${Y(N)}), so a run could copy them twice. Nothing was written.`)}let v=[],$=new Map,E=0,j=0;for(let N of k){if(u.has(N.sourceId)){A.unchanged++,v.push(N);continue}let D=i.get(Ue(e.sourceOrgId,e.targetOrgId,N.sourceId)),W=D?.kind==="attachment"&&ro(D,F.get(N.sourceId),h);if(W&&!r.deleteFromTarget){j++;continue}if(D&&!W&&(D.kind==="attachment"||D.sourceVersionId===N.body.id)){A.unchanged++,D.kind==="document"&&v.push({...N,into:{documentId:D.targetId,linked:D.linked,unchanged:!0}});continue}if(!D&&l>=Fe-i.size){E++,A.pastRunCap++;continue}if(c+N.bytes>d){A.pastRunCap++;continue}c+=N.bytes,A.bytes+=N.bytes,u.add(N.sourceId),D&&W?(A.replaced=(A.replaced??0)+1,$.set(N.sourceId,D.targetId),v.push(N)):D?(A.versions++,v.push({...N,into:{documentId:D.targetId,linked:D.linked}})):(l++,A.copied++,v.push(N))}A.pastRunCap>E&&w.push(`${A.pastRunCap-E} file(s) past the ${t.maxRunMB} MB a run copies were not copied: the next run copies them.`),j>0&&w.push(`${j} 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.`),E>0&&w.push(`${E} file(s) were not copied: this configuration keeps the record of ${Fe} 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(y,{scope:new Set(S),files:v,outcome:A,notes:w,shared:M,held:g,replacing:$,attachmentsChangedAt:F,...O!==void 0?{filesSeen:O}:{}})}return f.storage={remainingBytes:o,plannedBytes:c,...c>o?{shortfall:`The files to copy take ${et(c)} and the target has ${et(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 oo(n){return n.flatMap(e=>e.samples.map(t=>`${e.objectApiName}: ${t.recordSummary}: ${t.messages.join("; ")}`))}async function Ks(n){let{config:e,option:t,objectApiName:s,planned:r,written:i,deps:o,signal:a}=n,d={...r.outcome,copied:0,versions:0,bytes:0,...r.outcome.replaced!==void 0?{replaced:0}:{}},c=[...r.notes],l=[...i.keys()].filter(g=>!r.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 r.shared)o.store.record(e.id,g)}catch(g){c.push(`The files the target already held could not be recorded (${Y(g)}): the next run looks them up again.`)}if(r.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=r.files.map(g=>{let S=g.into?void 0:f.get(g.sourceId);return S&&S.kind==="document"?{...g,into:{documentId:S.targetId,linked:S.linked,unchanged:!0}}:g}),h=ps({files:p.filter(g=>!g.into?.unchanged),leftOut:[],errors:[]},t.maxFileSizeMB*1048576),m=[],y,R=!1,w=[],b={ids:[],note:void 0},O=(g,S)=>{let T=Ue(e.sourceOrgId,e.targetOrgId,g.sourceId),A=[...new Set([...g.into?.linked??[],...S.linked])].slice(0,Qt),k=g.objectApiName==="ContentDocument",M=r.replacing.get(g.sourceId),F=r.attachmentsChangedAt.get(g.sourceId);S.asVersion?(d.versions++,d.bytes+=g.bytes):M!==void 0?(d.replaced=(d.replaced??0)+1,d.bytes+=g.bytes):g.into?.unchanged||(d.copied++,d.bytes+=g.bytes),!S.asVersion&&!g.into&&n.onCreated?.(k?"ContentDocument":"Attachment",S.targetId);try{o.store.record(e.id,{sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:s,kind:k?"document":"attachment",sourceId:g.sourceId,targetId:S.targetId,...k?{sourceVersionId:g.body.id}:{},...!k&&F!==void 0?{sourceModifiedAt:F}:{},linked:A,copiedAt:new Date().toISOString()}),M!==void 0&&M!==S.targetId&&w.push(M)}catch(v){y=`${Y(v)} (${T})`}};try{await fs({files:p,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,remapper:{isCreated:g=>i.has(g)||r.held.has(g),get:g=>i.get(g)??r.held.get(g),add:()=>{}},deps:o.copy,report:h,errors:m,waitIfPaused:async()=>{if(y!==void 0)throw new Ge;if(await n.waitIfPaused?.(),a?.aborted)throw new Ge},onProgress:g=>{g.status==="running"&&o.onProgress?.(g.progress,`${s}: ${g.message}`)},onCopied:O})}catch(g){if(!(g instanceof Ge))throw g;R=y===void 0}finally{w.length>0&&(b=await ao(o,w))}return d.links=h.links,d.failed=h.objects.reduce((g,S)=>g+S.failed,0)+b.ids.length,d.recordNotWritten=h.leftOut.filter(g=>g.reason==="record-not-created").length,c.push(...oo(m)),b.note!==void 0&&c.push(b.note),d.recordNotWritten>0&&c.push(`${d.recordNotWritten} file(s) were not copied: no record they hang on was written.`),y!==void 0&&(d.failed++,c.push(`A copied file could not be recorded, so no more files were copied: ${y}. Check the copies of the last files in the target before running it again.`)),{outcome:d,notes:c,unplanned:l,cancelled:R}}var Us=200;async function ao(n,e){let t=[],s=new Set;for(let r=0;r<e.length;r+=Us){let i=e.slice(r,r+Us);try{let o=await n.deleteFromTarget?.("Attachment",i)??[];i.forEach((a,d)=>{let c=o[d];c?.success||(t.push(a),s.add(c?.errors.join("; ")||"The target gave no reason."))})}catch(o){t.push(...i),s.add(Y(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 (${[...s].join("; ")}): the record holds the new copy and the old one, ${t.join(", ")}.`}}function wd(n){let e=t=>{let s=n[t];if(!s)throw new Error(`No connection for the org ${t}.`);return s};return{queryRecords:async(t,s)=>(await Kn(e(t).pages,s)).records,readFileBody:(t,s,r)=>ms(e(t).transport,s,r),insertFile:(t,s,r)=>ys(e(t).transport,s,r),insertRecords:async(t,s,r)=>ur(await e(t).create(s,r),s).map(i=>({id:i.id,success:i.success,errors:i.errors})),remainingFileStorageMB:t=>ws(e(t).transport)}}function Sd(n){let e=0,t=0,s=0;for(let r of n)e+=r.copied+r.versions+(r.replaced??0),t+=r.bytes,s+=r.tooLarge+r.pastRunCap;return`${e} file(s), ${et(t)} copied, ${s} skipped past the caps`}var en="sync:config:",Hs="syncConfigs",ze="sync:delta:",tn="syncDelta",ft="sync:files:",Ys="syncFiles",Js=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${en}${e.id}`,e,Hs)}load(e){return this.configStore.get(`${en}${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(Hs);return Object.values(e).sort((s,r)=>r.updatedAt.localeCompare(s.updatedAt))}delete(e){return this.configStore.delete(`${ze}${e}`),this.configStore.delete(`${ft}${e}`),this.configStore.delete(`${en}${e}`)}loadDelta(e){return rr(this.configStore.get(`${ze}${e}`))}recordWatermark(e,t){let s=this.loadDelta(e),o={version:1,entries:[...(s.kind==="stored"?s.state.entries:[]).filter(a=>a.sourceOrgId!==t.sourceOrgId||a.targetOrgId!==t.targetOrgId||a.objectApiName!==t.objectApiName),t],...s.kind==="stored"&&s.state.resetAt?{resetAt:s.state.resetAt}:{}};this.configStore.set(`${ze}${e}`,o,tn)}loadFiles(e){return zs(this.configStore.get(`${ft}${e}`))}recordFile(e,t){let s=this.loadFiles(e);if(s.kind==="unreadable")throw new Error(`the record of copied files does not read: ${s.issue}`);let i=(s.kind==="stored"?s.map.entries:[]).filter(a=>a.sourceOrgId!==t.sourceOrgId||a.targetOrgId!==t.targetOrgId||a.sourceId!==t.sourceId);if(i.length>=Fe)throw new Error(`the record of copied files holds ${Fe} files already`);let o={version:1,entries:[...i,t]};this.configStore.set(`${ft}${e}`,o,Ys)}forgetFiles(e,t,s){let r=this.loadFiles(e);if(r.kind!=="stored"||s.length===0)return[];let i=new Set(s.map(d=>d.slice(0,15))),o=[],a=r.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(`${ft}${e}`,d,Ys)}return o}markRemoved(e,t,s,r){let i=this.loadDelta(e);if(i.kind!=="stored"||s.length===0)return[];let o=[],a=i.state.entries.map(d=>d.sourceOrgId!==t.sourceOrgId||d.targetOrgId!==t.targetOrgId||!s.includes(d.objectApiName)?d:(o.push(d.objectApiName),{...d,removedAt:r}));if(o.length>0){let d={...i.state,entries:a};this.configStore.set(`${ze}${e}`,d,tn)}return o}clearDelta(e){let t=this.loadDelta(e),s=t.kind==="stored"?t.state.entries.length:0,r={version:1,entries:[],resetAt:new Date().toISOString()};return this.configStore.set(`${ze}${e}`,r,tn),s}};async function co(n,e,t){let s=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let{objectApiName:i,ids:o}of e){let a=he(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)&&(s=Math.min(s,u),r=Math.max(r,u))}}}if(!(!Number.isFinite(s)||!Number.isFinite(r)))return{first:new Date(s).toISOString(),last:new Date(r).toISOString()}}async function Td(n,e){let t=r=>({note:`What the duplicate rules of the target reported of the run could not be read (${Y(r)}): the empty DuplicateRecordSet records it left, if any, stay.`}),s=new Set;try{for(let{ids:r}of e)for(let i of ee(r)){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"&&s.add(d)}}}catch(r){return{take:async()=>t(r)}}return{take:async()=>{if(s.size===0)return{};let r=new Set;try{for(let a of ee([...s])){let{records:d}=await n.query(`SELECT DuplicateRecordSetId FROM DuplicateRecordItem WHERE DuplicateRecordSetId IN (${a})`);for(let c of d)r.add(String(c.DuplicateRecordSetId))}}catch(a){return t(a)}let i=[...s].filter(a=>!r.has(a));if(i.length===0)return{};let o={objectApiName:"DuplicateRecordSet",planned:i.length,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],unchecked:[],reasons:[]};for(let a=0;a<i.length;a+=Bt){let d=i.slice(a,a+Bt);for(let c of await wr(n,o.objectApiName,d))c.kind==="deleted"?o.deleted+=1:c.kind==="gone"?o.alreadyGone+=1:(o.refused+=1,o.reasons.includes(c.reason)||o.reasons.push(c.reason))}return{object:o}}}}async function lo(n,e){if(!n||!e)return n;let t=Date.parse(e.at),s=Date.parse(e.lastAt??""),r=Date.parse(n.first),i=Date.parse(n.last);if(!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(t)&&!Number.isFinite(s))return n;let o=await Vs(e);if(o===void 0)return n;let a=Number.isFinite(t)?Math.min(r,t+o):r,d=Number.isFinite(s)?Math.max(i,s+o):i;return a===r&&d===i?n:{first:a===r?n.first:new Date(a).toISOString(),last:d===i?n.last:new Date(d).toISOString()}}async function Vs(n){let e=n.now??(()=>new Date);try{let t=e().getTime(),s=Date.parse(await n.serverTime());return Number.isFinite(s)?s-(t+e().getTime())/2:void 0}catch{return}}async function uo(n){if(!n)return;let e=Date.parse(n.at);if(!Number.isFinite(e))return;let t=Date.parse(n.lastAt??""),s=await Vs(n);if(s===void 0)return;let r=Number.isFinite(t)?Math.max(e,t):e;return{first:new Date(e+s).toISOString(),last:new Date(r+s).toISOString()}}var po=50,fo=3,Xs=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;async function go(n,e,t,s){let r=Date.parse(t.first)-Ss,i=Date.parse(t.last)+Rs;if(!Number.isFinite(r)||!Number.isFinite(i))return;let o=new Map,a=0;for(let{objectApiName:d,ids:c}of e){if(a>=fo||o.size>1||s?.aborted)break;let l=c.slice(0,po);if(l.length===0)continue;let u;try{let[p]=ee(l,l.length);u=(await n.query(`SELECT Id, LastModifiedById, LastModifiedDate FROM ${he(d)} WHERE Id IN (${p})`)).records}catch{continue}let f=!1;for(let p of u){let{LastModifiedById:h,LastModifiedDate:m}=p??{},y=typeof m=="string"?Date.parse(m):Number.NaN;typeof h!="string"||!Xs.test(h)||!(y>=r&&y<=i)||(o.has(h.slice(0,15))||o.set(h.slice(0,15),h),f=!0)}f&&a++}return o.size===1?[...o.values()][0]:void 0}async function Md(n,e,t,s,r,i,o){let a=e.some(({ids:p})=>p.length>0),d=a?await lo(await co(n,e,s),r):await uo(r),c=o.runUserId!==void 0&&Xs.test(o.runUserId)?o.runUserId:void 0,l=n.query?.bind(n),u=!c&&!a&&d&&l?await go({query:l},i,d,s):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(h=>h.slice(0,15)))),automation:bs(t),...c?{runUserId:c}:{},...u?{user:u}:{},ties:{...o.ties,...f.length>0?{writtenOver:f}:{}},...s?{signal:s}:{}}}var gt={status:"cancelled",objects:[],unread:[],handWork:[]};function Bd(n,e,t){return{...Rr(n,e),counts:ks($r(Lr(n),t))}}async function _d(n,e){let t=Date.parse(n.writtenBetween?.first??""),s=Date.parse(n.writtenBetween?.last??"");if(!Number.isFinite(t)||!Number.isFinite(s))return n;let{created:r}=n,i=new Set(r.flatMap(({ids:c})=>c.map(l=>l.slice(0,15)))),o=await Sr(e,{has:c=>i.has(c),start:t,end:s,...n.runUserId?{user:n.runUserId.slice(0,15)}:{}},r.filter(c=>c.objectApiName==="Quote").flatMap(({ids:c})=>c),new Set(r.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 Wd(n){let e,t,s;try{let o=await n.input();"refused"in o?s={...gt,status:"refused",refusal:o.refused}:t=Os(n.org,o,{...n.options,approve:async a=>{let{check:d,decision:c}=await br(n.guard,{...n.guardOf,objectName:Cs(a).join(", "),recordCount:As(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){s={...gt,status:"failure",refusal:Y(o)}}let r=async o=>{if(!t||s)return!1;try{return await o(t)}catch(a){return s={...t.result(),status:"failure",refusal:Y(a)},!1}},i;return{automationMade:t?.automationMade??new Set,ask:async()=>{await r(async o=>(await o.ask(),!1))},get takes(){return s?[]:t?.takes??[]},first:o=>r(a=>a.first(o)),afterRemoval:o=>r(a=>a.afterRemoval(o)),result:()=>s??t?.result()??gt,settle:()=>(i??=(async()=>{let o=s??t?.result()??gt;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 Gd(n){return n?"GUARD_BLOCKED":"SWEEP_REFUSED"}var Zs=6e4;function yo(n,e){return e.filter(t=>(t.ids.length>0||t.idsUntold===!0)&&wo(n,t)).map(t=>({ids:[...t.ids],...t.idsUntold?{idsUntold:!0}:{}}))}function wo(n,e){let t=Date.parse(n?.first??""),s=Math.max(t,Date.parse(n?.last??""));return!Number.isFinite(t)||!Number.isFinite(s)?!1:Number.isFinite(e.from)&&Number.isFinite(e.to)&&e.from<=s+9e5+Zs&&Math.max(e.from,e.to)>=t-2e3-Zs}var So=new Set(["autopilot_execute","anonymize_execute","subject_erase","backup_restore","checkpoint_rewind","checkpoint_undo","frozen_load"]);function Ud(n,e){return n.filter(t=>So.has(t.action)&&t.action!==e&&t.outcome!=="stopped").map(t=>{let s=Date.parse(t.timestamp);return{ids:[],idsUntold:!0,from:s,to:s}})}function Ro(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:s})=>s),from:e,to:Number.isFinite(t)?t:e}}function bo(n,e,t){return n.filter(s=>s.targetOrgId===e&&s.runId!==t).map(Ro)}async function zd(n,e,t,s){let r=await s(n.targetOrgId,e).catch(()=>[]),i=ko(n.removal?.removalSpans),o=n.removal?.madeEarlier,a=n.removal?.lateEarlier;return{otherRuns:yo(e,[...bo(t,n.targetOrgId,n.runId),...r]),...i?{removalBegan:i}:{},...o&&o.length>0?{madeEarlier:o}:{},...a&&a.length>0?{lateEarlier:a}:{}}}function qd(n,e,t,s=[]){let r=[...s],i=Gt(n.madeEarlier,e,r),o=Gt(n.lateEarlier,t,r),a={...n};return delete a.madeEarlier,delete a.lateEarlier,{...a,...i.length>0?{madeEarlier:i}:{},...o.length>0?{lateEarlier:o}:{}}}function ko(n){let e;for(let t of n??[]){let s=Date.parse(t.first);Number.isFinite(s)&&(!e||s<e.at)&&(e={at:s,first:t.first})}return e?.first}var oe=class extends Error{constructor(t,s,r){super(t);this.result=s;this.cause=r;this.name="SyncRunFailure"}result;cause},je=class extends oe{constructor(t,s,r){super(t,s);this.code=r;this.name="SyncRunRefused"}code};function Yd(n){return typeof n!="number"||!Number.isFinite(n)?5e4:Math.min(5e4,Math.max(1,Math.floor(n)))}var Oo=/\b(QUERY_TIMEOUT|OPERATION_TOO_LARGE)\b/;function nn(n){return Oo.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 Ao={raise:"the sandforge.sync.maxRecordsPerObject setting",sample:"Forge, with Depth ALL and Records per object set to A sample that fits the target"};function Co(n,e,t){let s=e<5e4?`raise ${t.raise} (50000 at most), or `:"";return n==="target"?`To compare every record, ${s}narrow the object's filter.`:`To copy the rest, ${s}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 Jd(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"}. `+Co("source",n.readCap,Ao)}var Io=2e3,Po=5e3,ht=class{chunkSize;pollIntervalMs;signal;constructor(e={}){this.chunkSize=e.chunkSize??Io,this.pollIntervalMs=e.pollIntervalMs??Po,this.signal=e.signal}async executeChunked(e,t,s,r,i,o){if(!e.bulkManager.canStartNewJob())throw new Error("Maximum concurrent bulk jobs reached");let a=e.connection.bulk2.createJob({operation:s,object:t,...o?{externalIdFieldName:o}:{}}),d=a.id??`bulk-${crypto.randomUUID()}`,c={id:d,operation:s,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=gr(a);l!==void 0&&e.onOpened?.(l);let u=[];for await(let S of r){if(this.signal?.aborted)break;for(let T of S)u.push(T);e.onProgress?.(u.length,i)}let f,p=0;if(this.signal?.aborted||(f=pr(s,u,o),await a.uploadData(f.text),p=u.length),this.signal?.aborted||f===void 0)return await mr(a),e.bulkManager.updateJobState(d,"Aborted"),this.buildAbortedResult(p);await a.close();let h=await a.check();for(;h.state==="InProgress"||h.state==="UploadComplete";)e.bulkManager.updateJobState(d,h.state),e.onProgress?.(h.numberRecordsProcessed??0,i),await new Promise(S=>setTimeout(S,this.pollIntervalMs)),h=await a.check();let m=await a.getAllResults(),y=fr(m,f,hr(h)),R=y.outcomes,w=[],b=[],O=y.unattributedSuccessIds.length;for(let S of R)S.success?(O++,S.id!==void 0&&w.push(S.id)):b.push(S.error??"Unknown error");w.push(...y.unattributedSuccessIds),b.push(...y.unattributedFailures);let g=h.state==="JobComplete"?"JobComplete":"Failed";return e.bulkManager.updateJobState(d,g),e.bulkManager.updateJobCounts(d,h.numberRecordsProcessed??i,b.length),{totalRecords:p,successCount:O,failureCount:b.length,successIds:w,errors:b,aborted:!1,outcomes:R,...y.unattributedSuccessIds.length>0?{unmatchedIds:y.unattributedSuccessIds}:{}}}catch(l){throw e.bulkManager.updateJobState(d,"Failed"),l}}async*createChunkGenerator(e,t){let s=t??this.chunkSize;for(let r=0;r<e.length;r+=s)yield e.slice(r,r+s)}buildAbortedResult(e){return{totalRecords:e,successCount:0,failureCount:0,successIds:[],errors:[],aborted:!0}}};var Eo=1e4,Qs=Oe.REST_API_BATCH_SIZE;function To(n){return!n.success&&n.errors.some(e=>e.startsWith("DUPLICATES_DETECTED"))}function Mo(n){return!n.success&&jr(n.errors,n.errorDetails)}function Fo(n,e){let[t,...s]=n.errors;return t===void 0?n:{...n,errors:[Nr(t,e),...s]}}function rn(n){return typeof n.created=="boolean"?{created:n.created}:{}}function ni(n){return n.some(e=>e.fields.length>0)?{errorDetails:n}:{}}function ei(n){let e=n===void 0?void 0:dr(n);return e?ni([e]):{}}function sn(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 jo(n,e){return!n||!e?n??e:{before:async(t,s,r,i)=>await n.before?.(t,s,r,i)??await e.before?.(t,s,r,i),sending:(t,s,r)=>{n.sending(t,s,r),e.sending(t,s,r)},opened:(t,s,r,i)=>{n.opened?.(t,s,r,i),e.opened?.(t,s,r,i)},answered:(t,s,r,i)=>{n.answered(t,s,r,i),e.answered(t,s,r,i)}}}function ac(n,e){let t=s=>s==="insert"||s==="upsert";return{...e?{before:(s,r,i,o)=>e.before(s,r,i,o)}:{},sending:(s,r,i)=>{t(r)?n.sending?.(s,i,r==="upsert"?{upsert:!0}:void 0):n.writing?.(s,i)},opened:(s,r,i,o)=>{t(r)&&n.sending?.(s,i,{job:o,...r==="upsert"?{upsert:!0}:{}})},answered:(s,r,i)=>{t(r)?n.answered?.(s,sn(r,i)):i.length>0&&n.writing?.(s,i.length),e?.answered(s,r,i)}}}var ti=class{constructor(e){this.deps=e;this.wait=e.wait??(t=>vr(t,e.signal)),this.retryOp=new lt({retryConfig:e.retryConfig,signal:e.signal,onRetry:(t,s,r)=>{e.log(`[RETRY] sync attempt=${t} code=${s.originalError.statusCode} delay=${r}ms`)}})}deps;retryOp;wait;async insert(e,t,s,r){let i=jo(this.deps.calls,r),o=l=>this.deps.connection.sobject(e).create(l,{headers:Xe()}),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,s,o,a,i);return this.locksAgain("insert",e,t,c,o,a,i)}async upsert(e,t,s,r){let i=c=>this.deps.connection.sobject(e).upsert(c,t,{headers:Xe()}),o="Upsert failed after retries",a=await this.tryStreaming("upsert",e,s,t)??await this.tryBulk("upsert",e,s,t),d=a?await this.duplicatesAgain("upsert",e,s,a,i,o,this.deps.calls,t):await this.executeRestBatches("upsert",e,s,r,i,o,this.deps.calls,t);return this.locksAgain("upsert",e,s,d,i,o,this.deps.calls,t)}async update(e,t,s){let r=d=>this.deps.connection.sobject(e).update(d,{headers:Xe()}),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,r,i):await this.executeRestBatches("update",e,t,s,r,i);return this.locksAgain("update",e,t,a,r,i)}async delete(e,t,s){let r=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,s,r,i);return this.locksAgain("delete",e,t,a,r,i)}async tryStreaming(e,t,s,r,i=this.deps.calls){if(s.length<=Eo)return;if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new Z(t);let o=await this.refusedBefore(i,t,e,s,r);if(o)return o;let a=new ht({signal:this.deps.signal});i?.sending(t,e,s.length);let d={connection:Wt(this.deps.connection),bulkManager:this.deps.bulkManager,onProgress:(u,f)=>{this.deps.onProgress(u,f,`Streaming ${e} ${t}`)},onOpened:u=>i?.opened?.(t,e,s.length,u)},c=await a.executeChunked(d,t,e,a.createChunkGenerator(s),s.length,r);if(c.aborted)throw i?.answered(t,e,[]),new Z(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"],...rn(u),...u.success?{}:ei(u.error)}));return i?.answered(t,e,l),l}async tryBulk(e,t,s,r,i=this.deps.calls){if(!this.deps.bulkExecutor.shouldUseBulkApi(s.length))return;if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new Z(t);let o={connection:Wt(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,s.length,l)},a=await this.refusedBefore(i,t,e,s,r);if(a)return a;i?.sending(t,e,s.length);let d=await this.deps.bulkExecutor.executeBulk(o,t,e,s,r);if(d.aborted)throw i?.answered(t,e,[]),new Z(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"],...rn(l),...l.success?{}:ei(l.error)}));return i?.answered(t,e,c),c}async refusedBefore(e,t,s,r,i){if(s==="delete"||!e?.before)return;let o=await e.before(t,s,r,i);if(o!==void 0)return this.deps.log(`[WARN] ${s} ${t}: ${r.length} row(s) not sent: ${o}`),r.map(()=>({success:!1,errors:[o]}))}async duplicatesAgain(e,t,s,r,i,o,a=this.deps.calls,d){let c=r.flatMap((p,h)=>h<s.length&&To(p)?[h]:[]);if(c.length===0||this.deps.signal?.aborted)return r;let l;try{l=await this.executeRestBatches(e,t,c.map(p=>s[p]),Qs,i,o,a,d,c)}catch(p){if(!(p instanceof Z))throw p;l=p.written}let u=[...r];l.forEach((p,h)=>{u[c[h]]=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,s,r,i,o,a=this.deps.calls,d){let c=new Map,l=await Dr({outcomes:r.slice(0,s.length),locked:Mo,written:p=>p.success,send:async p=>{let h;try{h=await this.executeRestBatches(e,t,p.map(m=>s[m]),Qs,i,o,a,d,p)}catch(m){if(!(m instanceof Z))throw m;h=m.written}for(let m of p.slice(0,h.length))c.set(m,(c.get(m)??0)+1);return h},note:Fo,wait:p=>this.wait(p),stopped:()=>this.deps.signal?.aborted===!0}),u=xr("row(s)",l);return u===void 0?r:(this.deps.log(`[INFO] ${e} ${t}: ${u}`),[...l.outcomes.map((p,h)=>{let m=c.get(h);return m===void 0?p:{...p,lockResends:m}}),...r.slice(s.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 s=_t(t,this.deps.keyPrefixOf?.(e));return s.kind==="linked"?{...t,existingId:s.id}:t}async executeRestBatches(e,t,s,r,i,o,a=this.deps.calls,d,c){let l=[];for(let u=0;u<s.length;u+=r){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)throw new Z(t,l);let f=s.slice(u,u+r);if(e!=="delete"){let m=await this.refusedBefore(a,t,e,f,d);if(m){l.push(...m);continue}if(this.deps.signal?.aborted)throw new Z(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 Z(t,l);let h=[];if(p.success&&p.result)for(let m of Array.isArray(p.result)?p.result:[p.result])h.push(this.restOutcome(t,m));else h.push(...f.map(()=>({success:!1,errors:[p.error?.message??o]})));l.push(...h),a?.answered(t,e,h,c?.slice(u,u+f.length))}return l}restOutcome(e,t){if(t.success)return{id:t.id,success:!0,errors:[],...rn(t)};let s=t.errors??[],r=s.map(cr),i={id:t.id,success:!1,errors:[r[0]??"Unknown error"],...ni(s.map(ar))},o=_t({success:!1,errors:r,duplicateMatchIds:s.flatMap(a=>lr(a,e))},this.deps.keyPrefixOf?.(e));return o.kind==="linked"?{...i,existingId:o.id}:i}};function ri(n,e){if(n.operation==="delete")return[];let t=nr(n.fieldMappings,n.excludedFields??[]),s=new Set([...tr(n.fieldMappings),...n.addOnFields.map(i=>i.fieldApiName.toLowerCase())]),r=i=>!t.has(i.toLowerCase())||s.has(i.toLowerCase());return(e.fields??[]).flatMap(i=>i.isReference&&i.createable&&i.name!=="RecordTypeId"&&(i.referenceTo?.length??0)>0&&r(i.name)?[{field:i.name,referenceTo:i.referenceTo??[]}]:[])}function si(n,e){let t=[...n].sort((b,O)=>b.insertOrder-O.insertOrder),s=new Map(t.map((b,O)=>[b.objectApiName,O])),r=new Set(t.filter(b=>b.operation!=="delete").map(b=>b.objectApiName)),i=new Map([...r].map(b=>[b.toLowerCase(),b])),o=[],a=new Set;for(let b of t){let O=b.objectApiName;if(r.has(O))for(let{field:g,referenceTo:S}of e.get(O)??[])for(let T of S){let A=i.get(T.toLowerCase());if(A===void 0||A===O)continue;let k=`${A}>${O}`;a.has(k)||(a.add(k),o.push({parent:A,child:O,field:g}))}}let d=vo(t.map(b=>b.objectApiName),o),c=new Map;d.forEach((b,O)=>{for(let g of b)c.set(g,O)});let l=d.map(b=>[...b].sort((O,g)=>(s.get(O)??0)-(s.get(g)??0))),u=l.map(b=>s.get(b[0])??0),f=l.map(()=>new Set);for(let{parent:b,child:O}of o){let g=c.get(b)??0,S=c.get(O)??0;g!==S&&f[S].add(g)}let p=new Set,h=[];for(;p.size<l.length;){let b;if(l.forEach((O,g)=>{p.has(g)||[...f[g]].some(S=>!p.has(S))||(b===void 0||u[g]<u[b])&&(b=g)}),b===void 0)break;p.add(b),h.push(...l[b])}let m=new Map(t.map(b=>[b.objectApiName,b])),y=h.flatMap(b=>{let O=m.get(b);return O?[O]:[]}),R=new Map(h.map((b,O)=>[b,O])),w=[];for(let b of y){let O=b.objectApiName,g=o.filter(S=>S.child===O&&(s.get(S.parent)??0)>(s.get(O)??0)&&(R.get(S.parent)??0)<(R.get(O)??0)).sort((S,T)=>(R.get(T.parent)??0)-(R.get(S.parent)??0));g.length>0&&w.push({objectApiName:O,after:g[0].parent,field:g[0].field})}return{ordered:y,order:{objects:h,moved:w,cycles:l.filter(b=>b.length>1)}}}function vo(n,e){let t=new Map(n.map(l=>[l,[]]));for(let{parent:l,child:u}of e)t.get(l)?.push(u);let s=0,r=new Map,i=new Map,o=[],a=new Set,d=[],c=l=>{r.set(l,s),i.set(l,s),s++,o.push(l),a.add(l);for(let p of t.get(l)??[])r.has(p)?a.has(p)&&i.set(l,Math.min(i.get(l)??0,r.get(p)??0)):(c(p),i.set(l,Math.min(i.get(l)??0,i.get(p)??0)));if(i.get(l)!==r.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)r.has(l)||c(l);return d}var No=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ae=n=>n.toLowerCase();function mt(n){return n==="insert"||n==="upsert"}function Do(n,e){let t=ae(e);if(n.addOnFields.some(r=>ae(r.fieldApiName)===t)||n.transformRules.some(r=>r.field&&ae(r.field)===t))return;let s=n.fieldMappings.find(r=>r.type!=="exclude"&&ae(r.targetField)===t);return s?(s.type==="direct"||s.type==="rename")&&(s.transformRules??[]).length===0?s.sourceField:void 0:e}function xo(n){return n!==void 0&&[...n.source.active].some(e=>!n.target.active.has(e))}async function ii(n){let e=new Map,t=new _e(n.earlier),s=new Set,r=new Set([...n.leftOut].map(ae)),i,o=async l=>{let u=await n.read(l);return u.length>0&&at(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===pe&&f!==void 0?u.filter(p=>p.Id===f).length:0};for(let l of n.ordered){let u=l.objectApiName;if(r.has(ae(u))){if(!mt(l.operation))continue;let A=await o(l);for(let k of A){let M=k.Id;typeof M=="string"&&M!==""&&t.noteRefused(M,u)}d(u,c(u,A)),s.add(ae(u));continue}if(l.operation==="delete")continue;let f=(n.lookups.get(u)??[]).flatMap(({field:A,referenceTo:k})=>{let F=k.filter(v=>ae(v)!==ae(u)&&s.has(ae(v))).length>0?Do(l,A):void 0;return F!==void 0?[{field:A,source:F}]:[]}),p=a!==void 0&&mt(l.operation),h=p&&u===pe&&await n.standardPricebooks?.()!==void 0,m=p&&u===Pe&&await n.standardPricebooks?.()?await n.currencies?.():void 0,y=xo(m);if(f.length===0&&!h&&!y)continue;let R=new Map,w=A=>{let k=`${A.parent}|${A.field}`,M=R.get(k);M?M.rows++:R.set(k,{...A,rows:1})},b=n.copied?.get(u),O=(await o(l)).filter(A=>{let k=A.Id;return!(b&&typeof k=="string"&&b.has(k.slice(0,15)))}),g=new Map;for(let A of f.length>0?O:[]){let k=A.Id,M=f.find(({source:v})=>{let $=A[v];return typeof $=="string"&&No.test($)&&t.refusedObjectOf($)!==void 0});if(!M)continue;let F={parent:t.refusedObjectOf(A[M.source])??"",field:M.field};w(F),typeof k=="string"&&k!==""&&g.set(k,F),mt(l.operation)&&typeof k=="string"&&k!==""&&t.noteRefused(k,u)}if(h&&d(u,c(u,O)),y){let A=dt(Pe,{records:O,sources:O,sourceIds:O.map(M=>typeof M.Id=="string"?M.Id:void 0)},i,m,M=>t.refusedObjectOf(M)!==void 0),k=0;for(let[M,F]of A.standsFor){if(g.has(M))continue;let v=t.refusedObjectOf(F)!==void 0?g.get(F):void 0;if(v){w(v),g.set(M,v),t.noteRefused(M,u);continue}k++}d(u,k)}let S=[...R.values()],T=S.reduce((A,k)=>A+k.rows,0);T>0&&(e.set(u,{objectApiName:u,rows:T,parent:S[0].parent,field:S[0].field,parents:S}),mt(l.operation)&&s.add(ae(u)))}return e}var oi=Symbol("not written");function Lo(n,e){if(n==="delete")return{rules:[],onChange:[]};let t=[],s=[];for(let{onChangeOnly:r,...i}of e)r&&n==="insert"?s.push(i.name):t.push(i);return{rules:t,onChange:s}}function $o(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 Bo=/^012000000000000(AAA)?$/;function _o(n){let e=n.RecordTypeId;return typeof e=="string"&&e.length>=15&&!Bo.test(e)}function an(n){let e=n?.[Hn];return typeof e=="string"&&e!==""}async function ai(n,e,t,s){let r=e.some(_o)?await n.recordTypes():void 0,i=t.some(an)||e.some(an)?await n.currencies():void 0,o=n.later?.get(s),a=n.recordTypesUnderTheLease?.get(s);return{links:n.links,sources:t,...r?{recordTypes:r}:{},...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 di(n){let e=new Map;for(let t of n?.cycles??[])t.forEach((s,r)=>{r<t.length-1&&e.set(s,new Set(t.slice(r+1)))});return e}function Wo(n,e,t){return{...n,...e.set?{lookupsSetAfter:{...e.set,after:[...t]}}:{},...e.leftOut.length>0?{lookupsLeftOut:[...n.lookupsLeftOut??[],...e.leftOut]}:{}}}function ci(n,e){return e.flatMap((t,s)=>{let r=n[s];return t.success&&r!==void 0?[r]:[]})}function li(n,e){let t=e.encryptedLeftOut??[];return t.length>0?{...n,encryptedLeftOut:[...t]}:n}function re(n){return n.slice(0,15)}function Go(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:s,refusal:r,alike:i}=e,o=i!==void 0?{...n,errors:[...n.errors,zn(i)]}:n;return t===0?o:{...o,skipped:o.skipped+t,writtenByThePlatform:{records:t,given:s,...r!==void 0?{refusal:r}:{}}}}function Uo(n,e,t){if(n.objectApiName!==X||!le(n.operation)||!t.sentWithAContact||e.records.length===0)return{prepared:e,linked:0};let s=a=>typeof a=="string"&&a!==""?t.targetOf(a):void 0,r=e.records.map((a,d)=>({OpportunityId:s(a.OpportunityId),[ie]:s(a[ie]),IsPrimary:e.sources[d]?.IsPrimary??a.IsPrimary})),i=new Set(Dt(r,a=>t.contactSentWith(a)));if(i.size===0)return{prepared:e,linked:0};for(let a of i){t.roleLinkedFor(String(r[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 zo=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,on=200;function qo(n,e,t){let s=c=>{let l=t?.fields?.find(u=>u.name===c);return l?.nillable===!1&&l.defaultedOnCreate!==!0},r=[],i=new Set,o=new Set,a=0;for(let[c,l]of n){let u=e[c]==="insert"?l.filter(s):[];if(u.length>0){r.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.`),r.length>0&&d.push(`${r.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:r,notes:d}}function Ko(n){return`${n} record(s) would be linked to the contact role the platform writes with their opportunity, for its contact, not written.`}function dn(n){let e=n.alreadyLinked,t=n.alreadyCopied-e;return{...t>0?{alreadyCopied:t}:{},...e>0?{alreadyLinked:e}:{}}}function Ho(n,e){return e.alreadyCopied===0?n:{...n,skipped:n.skipped+e.alreadyCopied,...dn(e)}}function ui(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 Yo="SYNC_EARLIER_UNREAD",Jo=new Set(["account","contact"]);function le(n){return n==="insert"||n==="upsert"}function pi(n,e,t,s=new Map,r=new Set,i=new Map,o=new Map,a=new Set,d,c={}){let l=0,u=0,f=n.map(g=>{let S=g.objectApiName,T=e.get(S)??{rows:0},A=t.get(S)??new Set,k=A.size,M=Math.min(k,T.rows),F=Math.min([...A].filter(j=>a.has(j)).length,M);u+=F,l+=M-F;let $=(s.has(S)?0:i.get(S)?.rows??0)+(o.get(S)??0),E=c.keys?.get(S);return{objectApiName:S,operation:g.operation,rows:Math.max(0,T.rows-k-$),...T.personAccounts!==void 0?{personAccounts:T.personAccounts}:{},batchSize:g.batchSize,...E?{overwriteKey:E}:{}}}),p=f.flatMap(g=>{let S=s.get(g.objectApiName);return S?[{...g,why:S.why,...S.key?{key:S.key}:{}}]:[]}),h=f.find(g=>g.objectApiName===X),m=h&&d!==void 0?Math.min(d,h.rows):0;h&&m>0&&(h.rows-=m);let y=f.filter(g=>!s.has(g.objectApiName)),R=y.filter(g=>g.rows>0&&le(g.operation)&&r.has(g.objectApiName)).length,w=[...i.values()].filter(({objectApiName:g})=>!s.has(g)),b=d===void 0?Vo(n,y):0,O=y.filter(g=>c.typed?.has(g.objectApiName)).length;return{objects:y,alreadyCopied:l,...u>0?{alreadyLinked:u}:{},...p.length>0?{unwritable:p}:{},...w.length>0?{heldBack:w}:{},...R>0?{readBack:R}:{},...b>0?{rolesByThePlatform:b}:{},...m>0?{rolesLinked:m}:{},...O>0?{describedAgain:O}:{}}}var Ie="Opportunity";function Vo(n,e){let t=o=>e.find(a=>a.objectApiName===o&&le(a.operation)),s=t(Ie),r=t(X);return!s||!r||n.find(o=>o.objectApiName===Ie)?.excludedFields.includes(ie)?0:Math.min(s.rows,r.rows)}function Xo(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 fi(n,e,t){if(le(e.operation))for(let s of t){let r=s?.Id;typeof r=="string"&&r!==""&&n.noteRefused(r,e.objectApiName)}}function yt(n,e,t){let s=[];for(let[r,i]of t){let o=n.targetOf(i);o!==void 0?n.noteMatched(r,o):le(e.operation)&&n.refusedObjectOf(i)!==void 0&&(n.noteRefused(r,e.objectApiName),s.push(r))}return s}function gi(n,e,t){let s=Yt(e,t),r=Vt(n,{...e,prices:s});return t.length===0?r:{...r,processed:r.processed+t.length,failed:r.failed+t.length,errors:[...r.errors,Jt(n.objectApiName,t.length)]}}function hi(n){let e=Dn(n.objects);return e.length>0?`${xn(e)} Nothing was read or written.`:void 0}function mi(n){let e=$n(n.objects);return e.length>0?`${Bn(e)} Nothing was read or written.`:void 0}var yi=class{deps;constructor(e){this.deps=e}async execute(e){let t=Date.now(),s=`sync-${Date.now()}`,r=[],i=hi(e);if(i!==void 0)throw new je(i,{...se(e.id,s,[],t,"failure"),error:i},Nn);let o=mi(e);if(o!==void 0)throw new je(o,{...se(e.id,s,[],t,"failure"),error:o},Ln);let{ordered:a,order:d,refused:c,typed:l,lookups:u,keys:f}=await this.writeOrderOf(e.objects),p=di(d),h=this.deps.queryTargetRows?l:new Set,m=this.deltaLoadOf(e),y=(C,I)=>new je(C,{...se(e.id,s,[],t,"failure"),error:C},I),R;try{R=await this.planFiles(e,a,m)}catch(C){let I=C instanceof Error?C.message:String(C);throw new oe(I,se(e.id,s,[],t,"failure"),C)}if(R?.storage.shortfall)throw new oe(`${R.storage.shortfall} Nothing was written.`,{...se(e.id,s,[],t,"failure"),files:R.storage});let w=await this.earlierLinks(e),b=a.filter(C=>C.operation==="insert");if(w.unread!==void 0&&b.length>0)throw y(ui(w.unread,b),Yo);let O;try{O=await this.alreadyCopiedOf(e,a,w.links)}catch(C){let I=`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 oe(I,{...se(e.id,s,[],t,"failure"),error:I},C)}let g=await this.countRun(e,a,m,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.`+nn(g.unread);throw new oe(C,{...se(e.id,s,[],t,"failure"),error:C})}let S=new Map,T=this.standardPricebooksOnce(),A=this.currenciesOnce(),k=m===void 0?new Map:void 0;if(this.deps.writeGate&&"counted"in g){let C;try{C=await this.heldBackOfRun(e,a,c,u,m,w.links,O,T,A,k)}catch(B){let H=B instanceof Error?B.message:String(B);throw new oe(H,{...se(e.id,s,[],t,"failure"),error:H},B)}let I=pi(a,g.counted,O,c,h,C.heldBack,C.matched,w.linked,await this.rolesLinkedAtTheGate(e,a,c,C.heldBack,O,w.links,k),{keys:f,...this.deps.describeTargetFieldsAgain?{typed:l}:{}}),{answer:x}=await this.deps.writeGate.hold(I);if(!x.go)throw y(x.message,x.code);for(let B of I.unwritable??[])S.set(B.objectApiName,B.rows)}let M=this.deps.leaseOfTheGate?.(),F=M&&M.assigned>0?await this.recordTypesReadAgain(a.map(C=>C.objectApiName).filter(C=>l.has(C)&&!S.has(C))):void 0,v=new Map,$=async()=>{let C=M;M=void 0,await C?.giveBack().catch(()=>{});for(let[I,x]of await this.readBackRecordTypes(v))for(let B=r.length-1;B>=0;B--)if(r[B].objectApiName===I){r[B]={...r[B],recordTypeGiven:x};break}},E=new _e(w.links),j=this.recordTypesOnce(),N=new Map,D=Ns(e),W=this.deps.idMap,z={sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId},q=Promise.resolve(),G,ne=(C,I,x)=>{if(!W)return;let B=Zo(C.operation,I,x);for(let[H,J]of[[B.written,!1],[B.linked,!0]])H.length!==0&&(q=q.then(()=>W.record(e.id,z,C.objectApiName,H,J).catch(ue=>{G??=ue instanceof Error?ue.message:String(ue)})))},fe=0,Ke=(C,I)=>{if(I.length===0)return;this.deps.creations?.deleted?.(C,I),fe+=I.length,E.noteDeleted(I);let x=W?.forget?.bind(W);x&&(q=q.then(()=>x(e.id,z,I).then(()=>{},B=>{G??=B instanceof Error?B.message:String(B)})))},K=this.deps.creations,P=new Map,_=0,Q=(C,I)=>{if(!K)return;let x=sn(C.operation,I);if(x.length===0)return;let B=C.objectApiName;K.noteUnanswered?K.noteUnanswered(B,x):K.note(B,x),P.set(B,(P.get(B)??0)+x.length)},ye=(C,I)=>{K&&(K.note(C,[I]),_++)},ve=!1,yn=!1,wn=!1,Bi=async C=>{let I=await K?.flush();await q;let x=[];return w.unread!==void 0&&!wn&&(wn=!0,x.push(`What earlier runs of this configuration wrote could not be read (${w.unread}): a lookup at a record one of them wrote went as the source holds it.`)),I!==void 0&&!ve&&(ve=!0,x.push(`What this run created could not all be kept (${I}): removing the run may leave some of it in the target.`)),G!==void 0&&!yn&&(yn=!0,x.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.`)),x.length===0?C:{...C,errors:[...C.errors,...x]}},de=async C=>{r.push(await Bi(C))},we=new Map,_i=new Set((d?.cycles??[]).map(C=>C[C.length-1])),Sn=(C,I)=>{for(let x=r.length-1;x>=0;x--)if(r[x].objectApiName===C){r[x]=Wo(r[x],I,[...p.get(C)??[]]);return}},He=new Map,Wi=(C,I)=>{for(let x=r.length-1;x>=0;x--)if(r[x].objectApiName===C){r[x]={...r[x],errors:[...r[x].errors,I]};return}},kt=(C,I,x)=>{for(let B=r.length-1;B>=0;B--){let H=r[B];if(H.objectApiName!==C)continue;if(!H.delta)return;let J=(H.delta.lookupsOwed??0)+I;r[B]={...H,delta:{...H.delta,...x!==void 0?{recorded:x}:{},...J>0?{lookupsOwed:J}:{}}};return}},Gi=async()=>{for(let[C,I]of[...we]){we.delete(C),await this.deps.pauseGate?.whilePaused(this.deps.signal);let x=this.deps.signal?.aborted?{leftOut:Ht(I.pending),unset:Kt(I.pending)}:await this.deps.dataSync.setLookups(I.objectConfig,I.pending,E,!0);"set"in x&&x.set&&K?.touched?.(C,x.set.records),Sn(C,x);let B=He.get(C);if(He.delete(C),x.unset===0){let H=B?.();H!==void 0&&kt(C,0,H)}else kt(C,x.unset)}},Ot=()=>{for(let[C,I]of[...we])we.delete(C),He.delete(C),Sn(C,{leftOut:Ht(I.pending)}),kt(C,Kt(I.pending))},Ye=C=>{let I=Ds(D,C.objectResults.some(J=>J.success>0)),x={...C,...R?{files:R.storage}:{},...I?{contactPoints:I}:{}},B=K?.overwrittenCount?.()??0,H=K?.deleted?fe:0;return!K||P.size===0&&_===0&&B===0&&H===0?x:{...x,created:{runId:K.runId,objects:[...P].map(([J,ue])=>({objectApiName:J,count:ue})),files:_,...B>0?{overwritten:B}:{},...H>0?{deleted:H}:{}}}},Rn="counted"in g?[...g.counted.values()].reduce((C,{rows:I})=>C+I,0):void 0,At=this.isGrappeActive(Rn);At&&this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:s,totalPartitions:a.length,totalRecords:Rn}});let bn=()=>{if(!At)return;let C=0,I=0;for(let x of r)C+=x.processed,I+=x.failed;this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:s,totalProcessed:C,totalFailed:I}})},Se=async(C,I)=>(Ot(),await $(),bn(),await K?.flush(),await q,Ye(ea(e.id,s,r,t,C,I))),Ct=0;for(let[C,I]of a.entries()){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return Se(a.slice(C));let x=c.get(I.objectApiName),B=S.get(I.objectApiName);if(x&&B!==void 0){let L=Xo(I,x,B);try{await this.noteLeftOutRefused(e,I,m,{links:E,...w.linked?{earlierLinked:w.linked}:{},recordTypes:j,currencies:A,currencyChangesById:N,standardPricebooks:T,...k?{gateReads:k}:{}},O.get(I.objectApiName))}catch(U){let ge=U instanceof Error?U.message:String(U);throw await de({...L,errors:[...L.errors,ge]}),Ot(),new oe(ge,Ye(se(e.id,s,r,t,"failure")),U)}await de(L);continue}let H=new tt,{plan:J,mark:ue}=await this.readPlan(e,I,m),Re={changedSince:J?.read==="delta"?Ae(J.since):void 0,rows:0,cut:!1},be=(L,U)=>J?{...L,delta:Ee(J,Re.rows,U)}:L,Je=R?.objects.get(I.objectApiName),It=Je?new Map:void 0,Pt;try{Pt=await this.syncObject(e,I,H,{links:E,...w.linked?{earlierLinked:w.linked}:{},recordTypes:j,currencies:A,currencyChangesById:N,standardPricebooks:T,...D?{contactPoints:D}:{},later:p,...F?{recordTypesUnderTheLease:F}:{},createdWithoutRecordType:v,...k?{gateReads:k}:{}},J?Re:void 0,It,K||W?(L,U)=>{Q(I,L),ne(I,L,U)}:void 0,O.get(I.objectApiName),(p.get(I.objectApiName)?.size??0)>0?L=>{let U=we.get(I.objectApiName);U?U.pending.push(...L):we.set(I.objectApiName,{objectConfig:I,pending:L})}:void 0)}catch(L){if(L instanceof Z){let U=Ce(We(I.objectApiName,I.operation,L.written,L.notes,L.lookupsLeftOut,L.writtenWithoutFields),H);return(U.processed>0||U.skipped>0)&&await de(be(U)),Se(a.slice(C))}throw await de(be(Ce({...wt(I),failed:1,errors:[L instanceof Error?L.message:String(L)]},H))),Ot(),new oe(L instanceof Error?L.message:String(L),Ye(se(e.id,s,r,t,"failure")),L)}if(Pt===oi){let L=Ce(wt(I),H);return L.skipped>0&&await de(be(L)),Se(a.slice(C))}let V=Pt,kn=!0;if(Je&&It&&e.files){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return await de(be(V)),Se(a.slice(C+1),wi(I));let L=await Ks({config:e,option:e.files,objectApiName:I.objectApiName,planned:Je,written:It,deps:this.deps.files,signal:this.deps.signal,waitIfPaused:()=>this.deps.pauseGate?.whilePaused(this.deps.signal)??Promise.resolve(),onCreated:ye});if(V={...V,files:L.outcome,errors:[...V.errors,...L.notes]},kn=L.outcome.failed===0&&L.outcome.pastRunCap===0&&L.unplanned===0,L.cancelled)return await de(be(V)),Se(a.slice(C+1),wi(I))}let ke;if(J?.read==="delta"&&e.propagateDeletes===!0&&Re.changedSince){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return await de(be(V)),Se(a.slice(C));try{ke=await this.carryDeletions(I,Re.changedSince,L=>Ke(I.objectApiName,L))}catch(L){if(!(L instanceof Z))throw L;let U=We(I.objectApiName,"delete",L.written);return await de(be({...V,errors:[...V.errors,...U.errors,...L.notes]},{deleted:U.success,deleteFailed:U.failed,notes:[],complete:!1})),Se(a.slice(C))}V={...V,errors:[...V.errors,...ke.notes]}}let On=Re.lookupsUnset??0,zi=V.failed===0&&kn&&!Re.cut&&On===0&&(ke===void 0||ke.deleteFailed===0&&ke.error===void 0&&ke.complete),An=(L,U,ge)=>{let In=Je?.filesSeen;try{return this.deps.deltaStore?.record(e.id,{sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,objectApiName:I.objectApiName,watermark:L,fingerprint:U,recordedAt:new Date().toISOString(),...In!==void 0?{filesSeen:In}:{}}),L}catch(Et){ge(`The watermark could not be saved, so the next run reads from the previous one: ${Et instanceof Error?Et.message:String(Et)}`);return}},Cn;if(J&&ue!==null&&zi){let{fingerprint:L}=J,U=I.objectApiName;we.has(U)?He.set(U,()=>An(ue,L,ge=>Wi(U,ge))):Cn=An(ue,L,ge=>{V={...V,errors:[...V.errors,ge]}})}J&&(V={...V,delta:Ee(J,Re.rows,ke,Cn,On)}),await de(V),_i.has(I.objectApiName)&&await Gi(),At&&(Ct++,this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:`sync-partition-${Ct}`,percentage:Math.round(Ct/a.length*100),processedRecords:V.processed}}))}await $();let Ui=Si(r);return bn(),await K?.flush(),await q,Ye(se(e.id,s,r,t,Ui))}async recordTypesReadAgain(e){let t=this.deps.describeTargetFieldsAgain,s=new Map;return t&&await Promise.all(e.map(async r=>{try{s.set(r,(await t(r)).recordTypes??[])}catch{}})),s}async readBackRecordTypes(e){let t=this.deps.queryTargetRows,s=new Map;return await Promise.all([...e].map(async([r,{given:i,types:o,ids:a}])=>{if(!t||a.length===0){s.set(r,i);return}try{let d=await t(os(r,a));s.set(r,{...i,readBack:as(d,o)})}catch(d){let c=d instanceof Error?d.message:String(d);s.set(r,{...i,readBack:{read:0,types:[],unread:c}})}})),s}async earlierLinks(e){let t=this.deps.idMap;if(!t)return{};try{let s={sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId},r=await t.load(e.id,s);if(!r)return{};let i=await t.linked?.(e.id,s);return{links:r,...i!==void 0&&i.size>0?{linked:i}:{}}}catch(s){return{unread:s instanceof Error?s.message:String(s)}}}recordTypesOnce(){let e;return()=>{let t=this.deps.recordTypes;return t?(e??=t().catch(s=>{throw new Error(`The record types of the two orgs could not be read, so none of these records was sent: ${s instanceof Error?s.message:String(s)}`)}),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,s){let r=e.objectApiName,i=e.operation!=="delete"&&at(r,t.sources)?await s.standardPricebooks?.():void 0;i&&s.links.noteMatched(i.source,i.target);let o=i&&r===Pe&&t.sources.some(an)?await s.currencies():void 0;return dt(r,t,i,o,a=>s.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,s){if(s===void 0)return{plan:null,mark:null};let r=xe(e,t,s),i=this.deps.deltaReads;if(!i||r.read==="full"&&r.reason==="not_saved")return{plan:r,mark:null};try{return{plan:r,mark:await i.latestModstamp(t.objectApiName)}}catch{return{plan:{read:"full",reason:"no_modstamp",fingerprint:r.fingerprint},mark:null}}}async carryDeletions(e,t,s){let r=await this.tallyObjectDeletions(e,t);if("error"in r)return{deleted:0,deleteFailed:0,error:r.error,notes:[r.error],complete:!1};let{tally:i,notes:o}=r;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 Z&&s(ci(i.ids,l.written)),l}s(ci(i.ids,d.outcomes));let c=We(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 s=this.deps.deltaReads;if(!s)return{error:"Deletions need the source's recycle bin, and none was given."};let r=$t(e);if("refused"in r)return{error:r.refused};let i=nt(e.where,t)??"";try{let o=await ir(s,e,r,i,a=>{if(r.sourceField==="Id")return a.Id;let d=this.deps.fieldMapping.apply(a,e.fieldMappings,e.excludedFields);return this.deps.transformPipeline.transformRecord(d,e)[r.keyField]});return{tally:o,notes:or(o,r.keyField)}}catch(o){if(this.deps.signal?.aborted)throw new Z(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,s,r){let i=this.deps.countSource;if(!r&&!this.deps.grappeConfig?.enabled||!i)return{none:!0};let o=new Map;try{for(let a of t){let d=s===void 0?null:xe(e,a,s),c=d?.read==="delta"?{changedSince:Ae(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=r&&l>0&&this.deps.countPersonAccounts&&Jo.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,s){let r=new Map,i=this.deps.readSourceIds,o=this.deps.findInTarget;if(!s||s.size===0||!i||!o)return r;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=s.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&&r.set(a.objectApiName,u)}return r}async writeOrderOf(e){let t=this.deps.describeTargetFields,s=new Map,r=new Set,i=new Map;if(!t)return{ordered:[...e].sort((d,c)=>d.insertOrder-c.insertOrder),refused:s,typed:r,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 vs(t,d.objectApiName,d.operation,d.externalIdField);"refused"in c&&s.set(d.objectApiName,c.refused);let l="target"in c&&c.target?js(Fs(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,Ps(l.operation==="upsert"?l.externalIdField??"Id":"Id","target"in c?c.target:void 0)),"target"in c&&c.target&&(o.set(d.objectApiName,ri(l,c.target)),le(d.operation)&&(c.target.recordTypes??[]).some(u=>!u.master)&&r.add(d.objectApiName))}return{...si(a,o),refused:s,typed:r,lookups:o,keys:i}}async heldBackOfRun(e,t,s,r,i,o,a,d,c,l){let u=new Map,f=t.some(h=>le(h.operation)&&(h.objectApiName===pe||h.objectApiName===Pe));return s.size===0&&!f?{heldBack:new Map,matched:u}:{heldBack:await ii({ordered:t,lookups:r,leftOut:new Set(s.keys()),...o?{earlier:o}:{},copied:a,standardPricebooks:d,currencies:c,matched:u,read:async h=>{let m=i===void 0?null:xe(e,h,i);if(m?.read==="delta")return this.deps.querySource(e.sourceOrgId,h,{changedSince:Ae(m.since)});let y=await this.deps.querySource(e.sourceOrgId,h);return l?.set(h.objectApiName,y),y}}),matched:u}}async rolesLinkedAtTheGate(e,t,s,r,i,o,a){let d=y=>t.find(R=>R.objectApiName===y),c=d(Ie),l=d(X);if(!c||!l||!le(l.operation))return;if(!this.deps.queryTargetRows||c.excludedFields.includes(ie))return 0;if(!a||c.operation!=="insert")return;let u=y=>y.fieldMappings.length===0&&y.addOnFields.length===0&&y.transformRules.length===0;if(!u(c)||!u(l)||[Ie,X,Nt].some(y=>s.has(y)||r.has(y)))return;let p=await this.deps.describeTargetFields?.(Ie).catch(()=>{});if(!p)return;if(!p.creatable.has(ie))return 0;let h=async y=>{let R=a.get(y.objectApiName);if(R)return R;let w=await this.deps.querySource(e.sourceOrgId,y);return a.set(y.objectApiName,w),w},m=y=>typeof y.Id=="string"&&y.Id!==""?y.Id:void 0;try{let y=new Set([...o?.keys()??[]].map(re)),R=d(Nt);if(R&&le(R.operation)&&t.indexOf(R)<t.indexOf(c))for(let g of await h(R)){let S=m(g);S&&y.add(re(S))}let w=g=>i.get(g)??new Set,b=new Map;for(let g of await h(c)){let S=m(g),T=g[ie];!S||typeof T!="string"||T===""||w(Ie).has(re(S))||!y.has(re(T))||b.set(re(S),T)}if(b.size===0)return 0;let O=(await h(l)).filter(g=>{let S=m(g);return S!==void 0&&!w(X).has(re(S))});return Dt(O,g=>b.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=hi(e);if(t!==void 0)throw new Error(t);let s=mi(e);if(s!==void 0)throw new Error(s);let r=Date.now(),i=[],{ordered:o,order:a,refused:d,typed:c,lookups:l,keys:u}=await this.writeOrderOf(e.objects),f,p,h,m=await this.validationRulesOf(o),y=(F={})=>({configId:e.id,operationId:`sync-simulation-${r}`,direction:e.direction,conflictStrategy:e.conflictStrategy,objects:i,duration:Date.now()-r,timestamp:new Date().toISOString(),...f?{files:f.storage}:{},...m.unread!==void 0?{validationRulesUnread:m.unread}:{},...a?{writeOrder:a}:{},...p?{writeCheck:p}:{},...h!==void 0?{writeCheckUnread:h}:{},...F}),R=this.deltaLoadOf(e);try{f=await this.planFiles(e,o,R)}catch(F){return this.deps.signal?.aborted?y({cancelled:!0}):y({error:F instanceof Error?F.message:String(F)})}let w=await this.earlierLinks(e),b=o.filter(F=>F.operation==="insert");if(w.unread!==void 0&&b.length>0)return y({error:ui(w.unread,b)});let O;try{O=await this.alreadyCopiedOf(e,o,w.links)}catch(F){return this.deps.signal?.aborted?y({cancelled:!0}):y({error:F instanceof Error?F.message:String(F)})}let g=this.deps.writeGate,S=this.standardPricebooksOnce(),T=this.currenciesOnce(),A=R===void 0?new Map:void 0,k=g?await this.countRun(e,o,R,!0):void 0;if(g&&k&&"unread"in k&&(h=`${k.unread}${nn(k.unread)}`),g&&k&&"counted"in k)try{let F=await this.heldBackOfRun(e,o,d,l,R,w.links,O,S,T,A);p=await g.measure(pi(o,k.counted,O,d,this.deps.queryTargetRows?c:new Set,F.heldBack,F.matched,w.linked,await this.rolesLinkedAtTheGate(e,o,d,F.heldBack,O,w.links,A),{keys:u,typed:c}))}catch(F){h=F instanceof Error?F.message:String(F)}let M={links:new _e(w.links),...w.linked?{earlierLinked:w.linked}:{},recordTypes:this.recordTypesOnce(),currencies:T,currencyChangesById:new Map,standardPricebooks:S,later:di(a),...A?{gateReads:A}:{}};for(let[F,v]of o.entries()){if(this.deps.signal?.aborted)return y({cancelled:!0});this.deps.onSimulationProgress?.(F,o.length,v.objectApiName);try{let $=await this.simulateObject(e,v,R,M,O.get(v.objectApiName),d.get(v.objectApiName)),E=f?.objects.get(v.objectApiName),{rules:j,onChange:N}=Lo(v.operation,m.byObject.get(v.objectApiName)??[]),D=[...$.notes,...E?.notes??[],...N.length>0?[$o(N)]:[]];i.push({...$,...E?{files:E.outcome}:{},notes:D,...j.length>0?{validationRules:j}:{}})}catch($){return this.deps.signal?.aborted?y({cancelled:!0}):y({error:$ instanceof Error?$.message:String($),failedObject:v.objectApiName})}}if(p){let F=new Set([...p.objects.map(G=>G.objectApiName),...(p.rolesLinked??0)>0?[X]:[]]),v=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 E=i.filter(G=>F.has(G.objectApiName)).reduce((G,ne)=>G+(ne.writtenByThePlatform??0),0),j=(p.rolesLinked??0)-E,N=p.total+j,D=N-v,W={objectApiName:X,rows:0},z=$.objects.some(G=>G.objectApiName===X)?$.objects:[...$.objects,W],q=N>0&&v===0;p={...$,objects:z.map(G=>G.objectApiName===X?{...G,rows:Math.max(0,G.rows+j)}:G).filter(G=>G.rows>0),total:N,...E>0?{rolesLinked:E}:{},...D>0?{notWritten:D}:{},...q?{total:0}:{},...q&&$.verdict==="writes"?{verdict:"nothing"}:{}}}return y()}async validationRulesOf(e){let t=this.deps.readValidationRules,s=e.filter(i=>i.operation!=="delete").map(i=>i.objectApiName),r=new Map;if(!t||s.length===0)return{byObject:r};try{for(let{objectApiName:i,...o}of await t(s))r.set(i,[...r.get(i)??[],o]);return{byObject:r}}catch(i){return{byObject:r,unread:i instanceof Error?i.message:String(i)}}}async simulateObject(e,t,s,r,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 tt,{plan:c}=await this.readPlan(e,t,s),l={changedSince:c?.read==="delta"?Ae(c.since):void 0,rows:0,cut:!1},u=await this.prepare(e,t,d,c?l:void 0,i,r.gateReads,r.earlierLinked),f=u.records.length>0?await this.pricesSettled(t,u,r):void 0,p=f?{...u,...f}:u;if(o&&p.records.length>0){fi(r.links,t,p.sources);let P=f?yt(r.links,t,f.standsFor):[];return li({objectApiName:t.objectApiName,operation:t.operation,read:p.read,insert:0,update:0,delete:0,skipped:p.alreadyCopied,...dn(p),refused:p.records.length+P.length,conflicts:0,conflictFields:[],notes:[o.message]},p)}let h=Uo(t,p,r.links),m=h.prepared,y=null;if(m.records.length>0&&this.deps.describeTargetFields)try{let P=await this.deps.describeTargetFields(t.objectApiName);y=P.creatable.size>0?P:null}catch{y=null}let R=await ai(r,m.records,m.sources,t.objectApiName),w=Ms({config:{...t,fieldMappings:[],addOnFields:[]},records:m.records,target:y,run:R}),b=w.sentAt.map(P=>m.records[P]),O=Jn(t),g=new Map;if(O!==null){let P=new Map;for(let _ of b){let Q=_[O],ye=De(Q);ye!==null&&P.set(ye,Q)}P.size>0&&(g=await a(e.targetOrgId,t,O,[...P.values()]))}let S=b.map(P=>Xn(t,P,g)),T=S.flatMap((P,_)=>P==="insert"||P==="update"?[_]:[]),A=y?.fields!==void 0&&T.length>0?Qn(t.objectApiName,T.map(P=>({payload:w.payloads[P],source:m.sources[w.sentAt[P]]??{},creates:S[P]==="insert"})),y.fields):{refused:new Set,notes:[]},k=new Set([...A.refused].map(P=>T[P])),M=await this.lookupsTheTargetLacks(T.filter(P=>!k.has(P)),w.payloads,w.settled,y),F=qo(M,S,y);for(let P of F.refused)k.add(P);let v=T.filter(P=>S[P]==="insert"&&!k.has(P)),$=t.operation==="insert"?(y?.fields??[]).filter(P=>P.unique===!0&&P.createable):[],E=new Map;for(let P of $){let _=new Map;for(let Q of v){let ye=w.payloads[Q][P.name],ve=De(ye);ve!==null&&_.set(ve,ye)}_.size!==0&&E.set(P.name,await a(e.targetOrgId,t,P.name,[..._.values()]))}let j=er(v.map(P=>w.payloads[P]),E);for(let P of j.refused)k.add(v[P]);let N=new Set([...j.linked].map(P=>v[P])),D=b.flatMap((P,_)=>k.has(_)||N.has(_)?[]:[_]),W=new Set(D.map(P=>w.sentAt[P])),z=m.unsettled.filter((P,_)=>W.has(_)),q=Zn({objectConfig:t,read:m.read,records:D.map(P=>b[P]),leftOut:d.counts(t.objectApiName),inTarget:g,conflicts:m.conflicts,unsettled:z,matchField:m.matchField,writable:y?.creatable??null}),G=t.operation==="insert"||t.operation==="upsert",ne=P=>{let _=m.sources[P]?.Id;return typeof _=="string"&&_!==""?_:void 0},fe=[];if(t.operation!=="delete"){for(let{index:P}of w.held){let _=ne(P);_&&G&&r.links.noteRefused(_,t.objectApiName)}if(w.sentAt.forEach((P,_)=>{let Q=ne(P);Q&&(k.has(_)||Vn.has(S[_])?G&&r.links.noteRefused(Q,t.objectApiName):r.links.noteWritten(Q,Q))}),t.objectApiName===Ie&&G)for(let P of D){let _=ne(w.sentAt[P]),Q=w.payloads[P]?.[ie];S[P]!=="insert"||!_||typeof Q!="string"||Q===""||r.links.noteSentWithContact(_,Q)}f&&(fe=yt(r.links,t,f.standsFor))}let Ke=Es(t.objectApiName,D.flatMap(P=>{let _=S[P]==="insert"?w.withoutRecordType.get(w.sentAt[P]):void 0;return _?[_]:[]}),Ts(y?.recordTypes??[],R.recordTypes)),K={...q,skipped:q.skipped+N.size+m.alreadyCopied+h.linked,...dn(m),...h.linked>0?{writtenByThePlatform:h.linked}:{},...m.encryptedLeftOut?{encryptedLeftOut:[...m.encryptedLeftOut]}:{},...Ke?{recordTypeGiven:Ke}:{},refused:q.refused+w.held.length+k.size+fe.length,notes:[...f?.standardMatched?[$s]:[],...ds(f?Yt(f,fe):[]).map(P=>`${P}.`),...h.linked>0?[Ko(h.linked)]:[],...q.notes,...w.notes,...fe.length>0?[Jt(t.objectApiName,fe.length)]:[],...w.currencies.map(P=>`${Yn(P)}.`),...A.notes,...F.notes,...j.notes]};if(!c)return K;if(c.read==="delta"&&e.propagateDeletes===!0&&l.changedSince){let P=await this.tallyObjectDeletions(t,l.changedSince);if("error"in P)return{...K,notes:[...K.notes,P.error],delta:Ee(c,l.rows,{deleted:0,deleteFailed:0,error:P.error})};let _=P.tally.ids.length;return{...K,delete:K.delete+_,notes:[...K.notes,...P.notes],delta:Ee(c,l.rows,{deleted:_,deleteFailed:0})}}return{...K,delta:Ee(c,l.rows)}}async lookupsTheTargetLacks(e,t,s,r){let i=this.deps.queryTargetRows,o=new Map;if(!i||!r?.fields||r.references.size===0)return o;let a=new Map,d=new Map;for(let u of e){let f=t[u]??{},p=[];for(let[h,m]of Object.entries(f)){if(h==="RecordTypeId"||!r.references.has(h)||s[u]?.has(h)||typeof m!="string"||!zo.test(m))continue;p.push({field:h,id:m});let y=r.fields.find(R=>R.name===h)?.referenceTo??[];for(let R of y)d.set(R,(d.get(R)??new Set).add(m))}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[h,m]of ee(p,on).entries())try{let y=await i(`SELECT Id FROM ${he(u)} WHERE Id IN (${m})`);for(let R of y){let w=R.Id;typeof w=="string"&&c.add(w.slice(0,15))}}catch{let y=h*on;for(let R of p.slice(y,y+on))l.add(R.slice(0,15))}}for(let[u,f]of a)f.some(({id:h})=>!c.has(h.slice(0,15))&&!l.has(h.slice(0,15)))&&o.set(u,f.map(({field:h})=>h).sort());return o}async noteLeftOutRefused(e,t,s,r,i){if(!le(t.operation))return;let{plan:o}=await this.readPlan(e,t,s),a={changedSince:o?.read==="delta"?Ae(o.since):void 0,rows:0,cut:!1},d=await this.prepare(e,t,new tt,o?a:void 0,i,r.gateReads,r.earlierLinked);if(d.records.length===0)return;let c=await this.pricesSettled(t,d,r);fi(r.links,t,c.sources),yt(r.links,t,c.standsFor)}async syncObject(e,t,s,r,i,o,a,d,c){let l=await this.prepare(e,t,s,i,d,r.gateReads,r.earlierLinked),u=await this.rolesWrittenWithTheirOpportunity(t,l,r,a),f=u.prepared,p=S=>Go(li(Ho(S,f),f),u.said);if(f.records.length===0)return p(Ce(wt(t),s));let h=await this.pricesSettled(t,f,r),{records:m,sourceIds:y,sources:R}=h;if(m.length===0)return p(Ce(Vt(wt(t),h),s));let w={...await ai(r,m,R,t.objectApiName),...h.standardFirst>0?{standardFirst:h.standardFirst}:{}},b=()=>yt(r.links,t,h.standsFor);if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return oi;if(o||a||c||i){let S=T=>{T.forEach((A,k)=>{let M=y[k];o&&A.success&&A.id&&M&&o.set(M,A.id)}),a?.(T,y)};try{let{outcomes:T,notes:A,currencies:k,lookupsLeftOut:M,writtenWithoutFields:F,lookupsToSet:v,lookupsUnset:$}=await this.deps.dataSync.write({...t,fieldMappings:[],addOnFields:[]},m,w);i&&$!==void 0&&(i.lookupsUnset=$),S(T);let E=b();return v&&c?.(v),p(Ce(gi(Ls(We(t.objectApiName,t.operation,T,A,M,F),k),h,E),s))}catch(T){throw T instanceof Z&&S(T.written),T}}let O=await this.deps.dataSync.sync({...t,fieldMappings:[],addOnFields:[]},m,w),g=b();return p(Ce(gi(O,h,g),s))}async rolesWrittenWithTheirOpportunity(e,t,s,r){let i=this.deps.queryTargetRows;if(e.objectApiName!==X||e.operation!=="insert"&&e.operation!=="upsert"||!i||!s.links.sentWithAContact||t.records.length===0)return{prepared:t};let o=g=>typeof g=="string"&&g!==""?s.links.targetOf(g):void 0,a=t.records.map((g,S)=>({OpportunityId:o(g.OpportunityId),[ie]:o(g[ie]),IsPrimary:t.sources[S]?.IsPrimary??g.IsPrimary})),d=await this.deps.describeTargetFields?.(X).catch(()=>{}),c=g=>g!=="Id"&&g!=="OpportunityId"&&g!==ie&&(d?.creatable.has(g)??!0),l=[...new Set(t.records.flatMap(g=>Object.keys(g)))].filter(c),u;try{u=await qn(async g=>await i(g),a,g=>s.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)s.links.roleLinkedFor(String(a[g].OpportunityId));let h=p.length>0?{alike:p.length}:{};if(f.size===0)return p.length>0?{prepared:t,said:{records:0,given:0,...h}}:{prepared:t};let m=[];for(let[g,S]of f){let T=Object.entries(t.records[g]??{}).filter(([A,k])=>c(A)&&k!==null&&k!==void 0&&String(S[A]??"")!==String(k));T.length>0&&m.push({Id:String(S.Id),...Object.fromEntries(T)})}let y=0,R;if(m.length>0)try{let g=await this.deps.dataSync.updateRecords(X,m,e.batchSize);m.forEach((S,T)=>{let A=g[T];A?.success?y++:R??=`${String(S.Id)}: ${A?.errors[0]??"not updated"}`})}catch(g){R=g instanceof Error?g.message:String(g)}let w=[],b=[];for(let[g,S]of f){let T=t.sourceIds[g],A=String(S.Id);s.links.roleLinkedFor(String(a[g].OpportunityId)),T!==void 0&&(s.links.noteWritten(T,A),w.push(T),b.push({success:!1,errors:[],existingId:A}))}r?.(b,w);let O=(g,S)=>!f.has(S);return{prepared:{...t,records:t.records.filter(O),sourceIds:t.sourceIds.filter(O),sources:t.sources.filter(O)},said:{records:f.size,given:y,...R!==void 0?{refusal:R}:{},...h}}}async prepare(e,t,s,r,i,o,a){let d=r?void 0:o?.get(t.objectApiName);d&&o?.delete(t.objectApiName);let c=r?await this.deps.querySource(e.sourceOrgId,t,{changedSince:r.changedSince,onBoundReached:()=>{r.cut=!0}}):d??await this.deps.querySource(e.sourceOrgId,t);r&&(r.rows=c.length);let l=t.externalIdField??"Id",u=this.deps.maskedSourceFields,p=(c.length>0&&u?await u(t.objectApiName).catch(()=>[]):[]).filter(k=>c.some(M=>Object.prototype.hasOwnProperty.call(M,k)));for(let k of c)for(let M of p)delete k[M];let h=p.length>0?{encryptedLeftOut:p}:{},m=t.operation==="insert"||t.operation==="upsert",y=m?s.keep(t.objectApiName,c):c,R=i&&i.size>0&&t.operation==="insert"?y.filter(k=>!(typeof k.Id=="string"&&i.has(re(k.Id)))):y,w=y.length-R.length,b=w>0&&a&&a.size>0?y.filter(k=>typeof k.Id=="string"&&i?.has(re(k.Id))===!0&&a.has(re(k.Id))).length:0;if(R.length===0)return{read:c.length,records:[],sourceIds:[],sources:[],conflicts:[],unsettled:[],matchField:l,alreadyCopied:w,alreadyLinked:b,...h};let g=R.map(k=>{let M=this.deps.fieldMapping.apply(k,t.fieldMappings,t.excludedFields);return this.deps.transformPipeline.transformRecord(M,t)}).map(k=>{let M=this.deps.fieldMapping.applyAddOns(k,t.addOnFields);return m?Qo(t.objectApiName,M):M}),S=g,T=[],A=t.operation==="upsert"||t.operation==="update";if(e.direction==="bidirectional"&&A){let k=await this.deps.queryTarget(e.targetOrgId,t);for(let M of k)for(let F of p)delete M[F];if(T=this.deps.conflictResolver.detectConflicts(g,k,l),T.length>0){let M=this.deps.conflictResolver.resolve(T,e.conflictStrategy),F=new Map(M.map(v=>[v.recordId,v.resolvedValues]));S=g.map(v=>{let $=String(v[l]??""),E=F.get($);return E?{...v,...E}:v})}}return{read:c.length,records:S,sourceIds:R.map(k=>typeof k.Id=="string"?k.Id:void 0),sources:R,conflicts:T,unsettled:g,matchField:l,alreadyCopied:w,alreadyLinked:b,...h}}async planFiles(e,t,s){let r=e.files;if(!r)return;let i=this.deps.files;if(!i)throw new ce("This session cannot copy files: it reads no file content or file storage. Nothing was read or written.");return qs({config:e,option:r,deps:i,tie:(o,a)=>this.tieToTarget(e,o,a),objects:t.map(o=>{let a=s===void 0?null:xe(e,o,s);return{objectConfig:o,...a?.read==="delta"?{changedSince:Ae(a.since),...a.filesSeen!==void 0?{filesSeen:a.filesSeen}:{}}:{}}})})}async tieToTarget(e,t,s){let r=this.deps.deltaReads,i=this.deps.files;if(!r||!i)return{held:new Map,refused:"the target cannot be asked"};let o=$t(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 s)d.set(u,u);else{let u=Qe(a),f=he(o.sourceField);for(let p of ee(s)){let h=await i.copy.queryRecords(e.sourceOrgId,`SELECT Id, ${f} FROM ${u} WHERE Id IN (${p})`);for(let m of h){let y=this.deps.fieldMapping.apply(m,t.fieldMappings,t.excludedFields),R=this.deps.transformPipeline.transformRecord(y,t)[o.keyField];typeof m.Id=="string"&&De(R)!==null&&d.set(m.Id,R)}}}if(d.size===0)return{held:new Map};let c=await r.targetIdsByKey(a,o.keyField,[...new Set(d.values())]),l=new Map;for(let[u,f]of d){let p=c.get(De(f))??[];p.length===1&&l.set(u,p[0])}return{held:l}}};function Zo(n,e,t){let s=[],r=[];return n!=="insert"&&n!=="upsert"?{written:s,linked:r}:(e.forEach((i,o)=>{let a=t[o];if(a===void 0)return;if(i.success&&typeof i.id=="string"&&i.id!==""){s.push([a,i.id]);return}let d=xs(n,i);d!==void 0&&r.push([a,d])}),{written:s,linked:r})}function Qo(n,e){let t=Un(n,e);if(t.length===0)return e;let s={...e};for(let r of t)delete s[r];return s}function Ce(n,e){let t=e.counts();return t.length===0?n:{...n,skipped:n.skipped+t.reduce((s,{count:r})=>s+r,0),errors:[...n.errors,...t.map(({why:s,count:r})=>Gn(r,s))]}}function wt(n){return{objectApiName:n.objectApiName,operation:n.operation,processed:0,success:0,failed:0,skipped:0,conflictCount:0,errors:[]}}function ea(n,e,t,s,r,i){let o=Si(t)==="failure"?"failure":"partial",a=r.map(c=>c.objectApiName),d=a.length>0?`Cancelled before ${a.join(", ")} ${a.length===1?"was":"were"} synced.`:"Cancelled.";return{...se(n,e,t,s,o),cancelled:!0,error:i?`${i} ${a.length>0?d:""}`.trim():d}}function wi(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 Si(n){return n.length===0?"success":n.every(s=>s.failed>0&&s.success===0)?"failure":n.some(s=>s.failed>0||ta(s.delta)||(s.files?.failed??0)>0)?"partial":"success"}function ta(n){return n!==void 0&&(n.deleteFailed>0||n.deletionError!==void 0)}function se(n,e,t,s,r){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:r,objectResults:t,totalProcessed:i,totalSuccess:o,totalFailed:a,totalSkipped:d,duration:Date.now()-s,timestamp:new Date().toISOString()}}var na=2;async function Ri(n,e,t,s,r=()=>!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<na&&!r();f++){let p=[],h=[],m=[];if(o.forEach((w,b)=>{if(w.id)return;let O=Pr(w.errorDetails,a[b],void 0);!O||O.some(({field:g})=>s.has(g))||(p.push(b),h.push(Er(a[b],O)),m.push(O))}),p.length===0)break;let y;try{y=await n(h)}catch(w){let b=[...new Set(m.flat().map(({field:O})=>O))].sort();c.push(`${p.length} record(s) refused on ${b.join(", ")} could not be written again without ${b.length===1?"it":"them"}: ${Y(w)}`);break}if(ra(y,h.length).forEach((w,b)=>{let O=p[b];o[O]=w,a[O]=h[b],d[O].push(...m[b])}),y.stopped){l=!0;break}}let u;return o.forEach((f,p)=>{!f.id||d[p].length===0||(u=$e(u,{rows:1,fields:d[p].map(h=>({...h,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 ra(n,e){if(n.rows&&(n.rows.length===e||n.stopped))return n.rows.slice(0,e);let t=[...n.successIds.map(r=>({id:r})),...n.errors.map(r=>({error:r}))];return(e===1?t:t.map(r=>({...r,unmatched:!0}))).slice(0,e)}var sa=1e4,ia=5e5,un=200;function Rt(n){let e=Math.floor(ia/Math.max(1,n.fieldRules.length));return Math.max(un,Math.min(sa,e))}var bi=class{deps;constructor(e){this.deps=e}async execute(e,t,s){let r=s??this.deps.generateId(),i=Date.now(),o=this.deps.validator.validate(e);if(!o.valid)return Ii(e.id,r,o.errors.map(l=>l.message),this.deps.now());let a=await _s(e.relations,{...this.deps.describeKeyPrefix?{keyPrefixOf:this.deps.describeKeyPrefix}:{},...this.deps.readPresentParentIds?{presentIds:this.deps.readPresentParentIds}:{}});if(a.length>0)return Ii(e.id,r,a,this.deps.now());let d=e.objects.reduce((l,u)=>l+u.recordCount,0);return this.shouldActivateGrappe(d)?this.executeWithGrappe(e,t,r,i):this.executeSequential(e,t,r,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,s,r=0){let i=t.reduce((o,a)=>o+a.recordsCreated+a.recordsFailed,r);this.deps.onProgress?.({objectApiName:e,processedRecords:i,totalRecords:s,percentage:Math.round(i/Math.max(s,1)*100)})}async executeSequential(e,t,s,r){let i=ki(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,s,i,r);let c=await this.readyToWrite(d,i,a);if(!c)continue;let l={},u={successIds:[],errors:[]},f={result:u,unsent:[]},p=Oi(c),h=0,m=0,y=!1,R=Rt(c.config);for await(let w of this.slicesOf(c,i,R,l)){if(this.deps.signal?.aborted){y=!0;break}h>0&&this.reportProgress(d.objectApiName,i.objectResults,a,u.successIds.length+u.errors.length);let b=await this.insert(t,d,w,c,i);if(h++,Ai(p,c.config.rows,m,w.length,b.result),m+=w.length,ya(f,b),b.result.stopped){y=!0;break}}if(h>0&&St(i,d,ln(u,c),[...c.notes,...cn(f)],l,p),y)return this.stoppedResult(e,s,i,r)}return this.ended(e,s,i,r)}async ended(e,t,s,r){let i,o=!1;try{i=await this.deps.knowledge?.({ids:ca(s),results:s.objectResults})}catch(l){o=!0,i={skipped:`The articles were neither published nor linked: ${Y(l)}`}}let a=Ci(e.id,t,s.objectResults,r,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,s){let r=jt(e.objectApiName,t.relations),i=Mn(e,t.relations).filter(y=>t.wroteNothing.has(y));if(i.length>0)return qe(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 qe(t,e.objectApiName,o,e.optional===!0);this.reportProgress(e.objectApiName,t.objectResults,s);let a=Mi(e,r),{config:d,dropped:c}=await Pi(a,this.deps.describeCreateableFields),l=await this.whyDropped(e.objectApiName,c),u=y=>y.fieldRules.length===0&&pn(y.rows).length===0;if(u(d)&&!u(a))return qe(t,e.objectApiName,`Skipped: none of the fields the template names can be written (${l.join("; ")}).`);let{config:f,filled:p}=await Ei(await this.withTheOrgsPicklistValues(d),r,this.deps.describeRequiredFields),h=await this.matchStandardPricebook(f,t);if(h)return qe(t,e.objectApiName,h);let m;if(r){let y=await this.placeChildren(f,r,t);if("skipped"in y)return qe(t,e.objectApiName,y.skipped);if(y.parentIds.length===0&&y.unwritten){let{lines:R,keys:w}=y.unwritten;return St(t,e,{successIds:[],errors:R},[],{},w),null}m=y}return{relation:r,config:m?{...f,recordCount:m.parentIds.length,...m.rows?{rows:m.rows}:{}}:f,placed:m,...f.rows?{lengths:await this.fieldLengths(e.objectApiName)}:{},notes:[...l.map(y=>`Written without ${y}.`),...p.length>0?[`Written with ${p.join(", ")}, which this org requires and the template names no rule for.`]:[],...m?.notes??[]]}}async placeChildren(e,t,s){let{childObject:r,lookupField:i,parentObject:o}=t;if(!await this.orgTakesField(r,i))return{skipped:`Skipped: this org does not let a seed write ${r}.${i}, the lookup the relation fills.`};if(t.distribution.mode==="byKey")return da(e.rows??[],t,s.keys.get(o));let a=s.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 ${r} 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 (${Y(p)}), so ${r} 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 ${r} to point at.`}}let c=Tn(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 h=0;h<p&&u.length<e.recordCount;h++)u.push(d[f]);return u.length===0?{skipped:`Skipped: the relation gives none of the ${d.length} ${o} records a ${r}.`}:{parentIds:u,notes:l>u.length?[`Stopped at ${u.length} ${r} records, the most the template asks for: the relation spreads ${l} over ${d.length} ${o} records.`]:[]}}async*slicesOf(e,t,s,r){let i=e.config.recordCount,o=Math.max(1,Math.floor(s)),a=0;do{let d=Math.max(0,Math.min(o,i-a)),c=fa(e.config,e.relation)?ga(d):await this.deps.fieldMapper.mapFields(d===i?e.config:{...e.config,recordCount:d},t.existingIds,l=>{r.aiFallback=ma(r.aiFallback,l)},a,e.lengths);ha(c,e.relation,e.placed,a),yield c,a+=d}while(a<i)}async insert(e,t,s,r,i){let o=f=>this.deps.insert(e,t.objectApiName,f,t.batchSize),a=t.objectApiName===X?await i.platformRoles.link(s):new Map,d=a.size>0?s.filter((f,p)=>!a.has(p)):s,c=d.length===0&&s.length>0?{successIds:[],errors:[],rows:[]}:await o(d),l=await Ri(o,d,c,oa(r),()=>this.deps.signal?.aborted===!0);t.objectApiName===Ws&&i.platformRoles.opportunitiesWritten(d,l.result);let u=a.size>0?la(l,s.length,a):l;return c.notes&&c.notes.length>0?{...u,notes:c.notes}:u}platformRolesOf(e){return new Gs({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 s=t.reason?` (${t.reason})`:"";return t.access==="absent"?`Skipped: this org has no ${e} object${s}.`:`Skipped: the user this seed runs as may not create ${e} records${s}`+(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 s=!1,r=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:(s=!0,{...i,config:{...i.config,picklistValues:d.length?d:[...o]}})});return s?{...e,fieldRules:r}:e}async matchStandardPricebook(e,t){if(!e.fieldRules.some(o=>Ze(o,t.written))||t.existingIds.has(pe))return;let s=this.deps.readExistingParentIds,r=`${e.objectApiName} points at the org's standard price book`;if(!s)return`Skipped: ${r}, and this run cannot read it.`;let i;try{i=await s(pe,"IsStandard = true",1)}catch(o){return`Skipped: ${r}, and reading it failed (${Y(o)}).`}if(i.length===0)return`Skipped: ${r}, 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(pe,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 s=new Set;try{this.deps.describeVisibleFields&&(s=await this.deps.describeVisibleFields(e))}catch{}let r;try{this.deps.describeComputedFields&&(r=await this.deps.describeComputedFields(e))}catch{}let i=t.filter(c=>s.has(c)&&r?.has(c)===!0),o=t.filter(c=>s.has(c)&&r?.has(c)!==!0),a=t.filter(c=>!s.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")}`+(r!==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,s,r){let o=this.deps.grappeAdapter.partition(e),a=o.reduce((m,y)=>m+y.recordCount,0);this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:s,totalPartitions:o.length,totalRecords:a}});let d=ki(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 m=d.objectResults.reduce((R,w)=>R+w.recordsCreated,0),y=d.objectResults.reduce((R,w)=>R+w.recordsFailed,0);this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:s,totalProcessed:m,totalFailed:y}})},h=()=>(p(),this.stoppedResult(e,s,d,r));for(let m of c){if(this.deps.signal?.aborted)return h();let y=Math.ceil(m.recordCount/f),R=await this.readyToWrite(m,d,a);if(!R){u=this.settleUnusedPartitions(o,u,y,0);continue}let w={},b=Math.max(1,Math.ceil(R.config.recordCount/f)),O=0,g=0,S=[],T=[],A={result:{successIds:[],errors:[]},unsent:[]},k,M=Oi(R),F=0,v=-1;for await(let $ of this.slicesOf(R,d,f,w)){if(v++,this.deps.signal?.aborted){k=v;break}v>0&&this.reportProgress(m.objectApiName,d.objectResults,a,O+g);let E=Date.now(),j=o[u]?.id??this.deps.generateId(),N=await this.insert(t,m,$,R,d),D=N.result;Ai(M,R.config.rows,F,$.length,D),F+=$.length,N.written&&(A.written=$e(A.written,N.written)),A.unsent.push(...N.unsent);for(let z of N.notes??[])(A.notes??[]).includes(z)||(A.notes=[...A.notes??[],z]);O+=D.successIds.length,g+=D.errors.length,S.push(...D.errors),T.push(...D.successIds),l.push({grappeId:j,status:D.errors.length===0?"success":D.successIds.length>0?"partial":"failure",processedRecords:$.length,successCount:D.successIds.length,failureCount:D.errors.length,errors:D.errors,duration:Date.now()-E}),u++;let W=Math.round(u/Math.max(o.length,1)*100);if(this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:j,percentage:W,processedRecords:O+g}}),D.stopped){k=v+1;break}}if(k!==void 0)return k>0&&St(d,m,ln({successIds:T,errors:S},R),[...R.notes,...cn(A)],w,M),h();u=this.settleUnusedPartitions(o,u,y-b,O+g),St(d,m,ln({successIds:T,errors:S},R),[...R.notes,...cn(A)],w,M)}return p(),this.ended(e,s,d,r)}stoppedResult(e,t,s,r){let i=Ci(e.id,t,s.objectResults,r,this.deps.now());return{...i,status:i.status==="success"?"partial":i.status,cancelled:!0}}settleUnusedPartitions(e,t,s,r){let i=t;for(let o=s;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:r}})}return i}};function ki(n,e,t){return{relations:n.relations??[],written:new Set(n.objects.map(s=>s.objectApiName)),existingIds:new Map,wroteNothing:new Set,keys:new Map,...t?{onRowIds:t}:{},platformRoles:e,objectResults:[]}}function oa(n){return new Set(["RecordTypeId",...n.relation?[n.relation.lookupField]:[],...n.config.fieldRules.filter(e=>e.ruleType==="reference").map(e=>e.fieldApiName)])}function cn(n){return[...n.notes??[],...n.written?[Tr(n.written)]:[],...n.unsent]}function qe(n,e,t,s=!1){let r=wa(e,t);return n.objectResults.push(s?{...r,optional:!0}:r),n.wroteNothing.add(e),null}function St(n,e,t,s,r,i){i&&(n.keys.set(e.objectApiName,i),n.onRowIds?.(e.objectApiName,aa(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,...s,...o.notes],...r,...o.writtenByThePlatform?{writtenByThePlatform:o.writtenByThePlatform}:{}})}function aa(n){let e={};for(let[t,s]of n)"id"in s&&(e[t]=s.id);return e}function da(n,e,t){let{childObject:s,parentObject:r}=e;if(!t)return{skipped:`Skipped: ${s} is placed by key, and ${r} 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 ${r} row`:`its ${r} ${l} ${u?u.why:`is no ${r} row this run wrote`}`;a.push(`${s} ${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 ca(n){let e=new Map;for(let[t,s]of n.keys){let r=new Map;for(let[i,o]of s)"id"in o&&r.set(i,o.id);e.set(t,r)}return e}function Oi(n){if(n.config.rows)return new Map(n.placed?.unwritten?.keys??[])}function Ai(n,e,t,s,r){if(!n||!e)return;let i=r.rows&&(r.rows.length===s||r.stopped)?r.rows:void 0;for(let o=0;o<s;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 ln(n,e){let t=e.placed?.unwritten?.lines??[];return t.length===0?n:{...n,errors:[...n.errors,...t]}}function la(n,e,t){let s=n.result.rows;if(!s)return n;let r=[],i=0;for(let o=0;o<e;o++){let a=t.get(o);if(a){r.push({id:String(a.Id)});continue}let d=s[i++];if(!d)break;r.push(d)}return{...n,result:{...n.result,rows:r}}}function pn(n){return[...new Set((n??[]).flatMap(e=>Object.keys(e.values)))]}function ua(n){return!n||n.length===0?[]:pn(n).filter(e=>n.every(t=>e in t.values))}function pa(n,e){return e.size===0?[...n]:n.map(t=>({...t,values:Object.fromEntries(Object.entries(t.values).filter(([s])=>!e.has(s)))}))}async function Pi(n,e){if(!e)return{config:n,dropped:[]};let t;try{t=await e(n.objectApiName)}catch{return{config:n,dropped:[]}}let s=n.fieldRules.filter(a=>a.ruleType==="reference"||t.has(a.fieldApiName)),r=pn(n.rows).filter(a=>!t.has(a));if(s.length===n.fieldRules.length&&r.length===0)return{config:n,dropped:[]};let i=[...new Set([...n.fieldRules.filter(a=>!s.includes(a)).map(a=>a.fieldApiName),...r])],o=n.rows&&pa(n.rows,new Set(r));return{config:{...n,fieldRules:s,...o?{rows:o}:{}},dropped:i}}async function Ei(n,e,t){if(!t)return{config:n,filled:[]};let s;try{s=await t(n.objectApiName)}catch{return{config:n,filled:[]}}let r=new Set([...n.fieldRules.map(o=>o.fieldApiName),...ua(n.rows),...e?[e.lookupField]:[]]),i=[];for(let o of s){if(r.has(o.fieldApiName))continue;let a=jn(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 Ti(n,e,t){let s=jt(n.objectApiName,e),{config:r}=await Pi(Mi(n,s),t.describeCreateableFields),{config:i}=await Ei(r,s,t.describeRequiredFields);return Rt(i)}function Mi(n,e){if(!e)return n;let t=n.fieldRules.filter(s=>s.fieldApiName!==e.lookupField);return t.length===n.fieldRules.length?n:{...n,fieldRules:t}}function fa(n,e){return e!==void 0&&n.fieldRules.length===0&&!n.rows}function ga(n){return Array.from({length:n},()=>({}))}function ha(n,e,t,s=0){if(!(!e||!t))for(let[r,i]of n.entries())i[e.lookupField]=t.parentIds[s+r]}function ma(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 ya(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=$e(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 wa(n,e){return{objectApiName:n,recordsCreated:0,recordsFailed:0,createdIds:[],errors:[e]}}function Ci(n,e,t,s,r){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:Sa(i,o,a),objectResults:t,totalRecordsCreated:i,totalRecordsFailed:o,duration:Date.now()-s,timestamp:r}}function Sa(n,e,t){return e===0&&!t?"success":n===0?"failure":"partial"}function Ii(n,e,t,s){return{templateId:n,operationId:e,status:"failure",objectResults:[{objectApiName:"validation",recordsCreated:0,recordsFailed:0,createdIds:[],errors:t}],totalRecordsCreated:0,totalRecordsFailed:0,duration:0,timestamp:s}}var Ra=200,ba=1,ka=1,fn=2,Oa=2,Fi=3,Aa=1,Ca=200,Ia="Campaign";function ji(n,e){if(!n)return;let t=e.toLowerCase();for(let[s,r]of n)if(s.toLowerCase()===t)return r}function Pa(n,e){let t=Math.max(1,Math.floor(e)),s=[],r=0;do{let i=Math.max(0,Math.min(t,n-r));s.push(i),r+=i}while(r<n);return s}function Ea(n,e={}){let t=e.bulkThreshold??Ra,s=!1;return n.objects.flatMap(i=>{let o=ji(e.duplicateRules,i.objectApiName),a=o===!1&&!gs.has(i.objectApiName),d=e.partition??e.slices?.get(i.objectApiName)??Rt(i);return Pa(i.recordCount,d).map(c=>{let l=me([{rows:c,perCall:i.batchSize}]);if(c<=t||(s=!0,o===!0))return l;let u=me([{rows:c,bulk:!0}]);return a?u:Math.max(u,l)})}).reduce((i,o)=>i+o,0)+(s?ba:0)+me(Fa(n))}function Ta(n,e={}){return Ea(n,e)+Ma(n,e)}function Ma(n,e={}){let t=new Set(n.objects.map(i=>i.objectApiName)),s=n.objects.some(i=>i.fieldRules.some(o=>Ze(o,t))),r=(n.relations??[]).reduce((i,{parents:o})=>o.kind==="existing"?i+me([{rows:0,readRows:o.limit}]):o.kind==="records"?i+Math.ceil(o.ids.length/Bs):i,0);return ka+n.objects.length+fn+(t.has(Ia)?fn+1:0)+r+(s?Aa:0)+(e.typedFirst?Oa:0)+Fi+Math.max(0,e.sentBefore??0)+Math.max(0,e.automationRead??0)+Math.max(0,e.slicesRead??0)}async function tl(n,e,t){let s=new Map;if(t!==void 0)return s;for(let r of n.objects)r.recordCount<=un||s.set(r.objectApiName,await Ti(r,n.relations,e));return s}function nl(n,e){return n?.enabled&&e.objects.reduce((s,r)=>s+r.recordCount,0)>=n.autoActivateThreshold?n.grappeSize:void 0}function bt(n,e){return n.reduce((t,{objectApiName:s,rows:r,perCall:i,deletes:o})=>{if(r<=e.threshold)return t+me([{rows:r,perCall:i??e.perCall}]);let a=o===!0||ji(e.duplicateRules,s)===!1?0:r;return t+me([{rows:r,bulk:!0},{rows:a}])},0)}function gn(n=0,e=0){return Fi+fn+Math.max(0,n)+Math.max(0,e)}function rl(n,e){let t=i=>n.find(o=>o.objectApiName===i)?.rows??0,s=Math.min(t("Opportunity"),t("OpportunityContactRole")),r=n.filter(({objectApiName:i})=>e.secondPass?.has(i)===!0).map(({rows:i})=>({rows:i}));return bt(n,e)+(s>0?Math.ceil(s/Ca)+bt([{objectApiName:"OpportunityContactRole",rows:s}],e):0)+me(r)+gn(n.length,e.automationRead)}function Fa(n){let e=s=>n.objects.find(r=>r.objectApiName===s)?.recordCount??0,t=Math.min(e("OpportunityContactRole"),e("Opportunity"));return t>0?[{rows:t},{rows:t}]:[]}function ja(n,e){return n.objects.reduce((t,s)=>t+Wr(s.objectApiName,{rows:s.recordCount,personAccounts:e.includes(s.objectApiName)?s.recordCount:0}),0)}var il="SEED_STORAGE_EXCEEDED";async function ol(n,e,t,s,r,i={},o={}){let a={storageBytes:ja(e,t)},d;try{d=await Ur(n)}catch(m){d={unread:Y(m)}}let c=Be(a,d),l="unread"in d?await zr(n).catch(m=>({unread:Y(m)})):d.dailyApiRequests,u=rt({run:Ta(e,o),...it(r),...i},l),f=ot(r);if(f)return{check:c,api:u,refusal:f.message,refusedFor:"checkpoint",checkpointRefusal:f.refusal};let p=ss(c,s);if(p)return{check:c,api:u,refusal:`${p} Nothing was written.`,refusedFor:"storage"};let h=st(u,s);return h?{check:c,api:u,refusal:h,refusedFor:"apiRequests"}:{check:c,api:u}}function al(n,e){let{check:t,api:s}=n,r=s.parts??{},i={checkpoint:r.checkpoint??0,mute:r.mute??0,readBack:r.readBack??0,deliverability:r.deliverability??0,fit:r.fit??0};return is({storage:t.verdict==="unread"?{unread:t.unread}:{maxMB:t.maxMB,remainingMB:t.remainingMB},...e!==void 0?{withinMB:e}:{},api:s.verdict==="unread"?{unread:s.unread}:{max:s.max,remaining:s.remaining},otherRequests:i})}function va(n){return n==="insert"||n==="upsert"}function Di(n){return n==="update"||n==="upsert"}function Na(n){return Gr(n.objects.filter(e=>va(e.operation)).map(({objectApiName:e,rows:t,personAccounts:s})=>({objectApiName:e,rows:[],counted:{rows:t,...s!==void 0?{personAccounts:s}:{}}})))}var xi=Oe.REST_API_BATCH_SIZE;function Da(n,e){return bt(n.filter(t=>t.rows>0).map(({objectApiName:t,operation:s,rows:r,batchSize:i})=>({objectApiName:t,rows:r,...i!==void 0?{perCall:i}:{},...s==="delete"?{deletes:!0}:{}})),{threshold:e.bulkThreshold??xi,...e.duplicateRules?{duplicateRules:e.duplicateRules}:{}})}var xa="Opportunity",La="OpportunityContactRole",$a=200,Ba={update:{characters:zt,wide:!0},upsert:{characters:Is(),wide:!0}},_a=2,vi=Array.from({length:_a},()=>1),Wa=1;function Ga(n){let e=Math.min(Math.max(0,n),5e4);return Wa+Math.max(1,Math.ceil(e/Br))}function mn(n,e){let t=Math.max(1,Math.floor(e));return Array.from({length:Math.ceil(Math.max(0,n)/t)},(s,r)=>Math.min(t,n-r*t))}function Ua(n,e){if(n.rows<=(e.bulkThreshold??xi))return mn(n.rows,n.batchSize??Oe.REST_API_BATCH_SIZE);let t=e.duplicateRules?[...e.duplicateRules].find(([s])=>s.toLowerCase()===n.objectApiName.toLowerCase())?.[1]:void 0;return[n.rows,...t===!1?[]:mn(n.rows,Oe.REST_API_BATCH_SIZE)]}function za(n,e){let t=0,s=!1;for(let d of e.targetHeld?.values()??[])t+=Ga(d);for(let d of n.objects)d.rows<=0||d.operation==="delete"||(t+=vi.length,!(d.operation!=="update"&&d.operation!=="upsert")&&(s=!0,t+=qt([...Ua(d,e),...vi],d.overwriteKey??Ba[d.operation])));let r=d=>n.objects.find(c=>c.objectApiName===d&&(c.operation==="insert"||c.operation==="upsert")),i=r(xa),o=r(La),a=i&&o?Math.min(i.rows,o.rows+(n.rolesLinked??0)):0;if(o&&a>0){let d=mn(a,o.batchSize??Oe.REST_API_BATCH_SIZE);s=!0,t+=Math.ceil(a/$a)+d.length+qt(d,{characters:zt,wide:o.overwriteKey?.wide??!0})}return s&&(t+=1),e.leaseAssigns===!0&&(t+=Math.max(0,n.describedAgain??0)),t}function Li(n){let e=new Map;for(let{objectApiName:t,operation:s}of n.objects){let r=e.get(t)??new Set;(s==="insert"||s==="upsert")&&r.add("insert"),(s==="update"||s==="upsert")&&r.add("update"),s==="delete"&&r.add("delete"),e.set(t,r)}return(t,s)=>e.get(t)?.has(s)===!0}function $i(n,e){let t=new Set(e);return{...n,objectsRead:n.objectsRead.filter(s=>t.has(s)),objects:n.objects.filter(s=>t.has(s.objectApiName))}}function qa(n){let e;return t=>{if(e&&t.every(r=>e?.objects.includes(r)))return e.answer.then(r=>$i(r,t));let s=n(t);return e??={objects:[...t],answer:s},s}}function Al(n,e){if(n.direction==="bidirectional")return async t=>{let s=n.objects.find(i=>i.objectApiName===t),r=nt(s?.where,void 0);return e(`SELECT COUNT() FROM ${he(t)}${r?` WHERE ${r}`:""}`)}}async function Ka(n,e){let t=new Set((n.heldBack??[]).filter(({rows:r})=>r>0).map(({objectApiName:r})=>r)),s=new Map;for(let{objectApiName:r,operation:i,rows:o}of n.objects){if(!Di(i)||s.has(r)||o<=0&&!t.has(r))continue;let a=await e(r).catch(()=>5e4);s.set(r,Number.isFinite(a)&&a>=0?a:5e4)}return s}async function Ni(n,e){let t=Na(n),s=n.objects.filter(E=>E.rows>0).map(({objectApiName:E,rows:j})=>({objectApiName:E,rows:j})).sort((E,j)=>j.rows-E.rows||E.objectApiName.localeCompare(j.objectApiName)),r=s.reduce((E,j)=>E+j.rows,0),i=n.objects.filter(E=>Di(E.operation)).reduce((E,j)=>E+j.rows,0),o=Be(t,{maxMB:0,remainingMB:0}),a=[],d,c=r>0?qa(e.readAutomation):e.readAutomation,l,u,f,p=Li(n),h;if(r>0){let E=n.objects.filter(j=>j.rows>0).map(j=>j.objectApiName);if(h=await c(E).catch(j=>({unread:j instanceof Error?j.message:String(j)})),e.checkpointFirst){let j="objects"in h?vt(h,void 0,p):{firing:[]};try{l=await e.checkpointFirst.scope(E,j)}catch(N){u=_r(N)}}}let m={unread:"not read"};if(r>0){let E=await e.readStorage().catch(j=>({unread:j instanceof Error?j.message:String(j)}));m="unread"in E?await e.readApiBudget().catch(j=>({unread:j instanceof Error?j.message:String(j)})):E.dailyApiRequests,t.totalRows>0&&(o=Be(t,E))}if(t.totalRows>0){let E=await Jr({plan:t,objects:t.objects.map(j=>j.objectApiName),readAutomation:c,readLimits:e.readLimits});a=E.checks,d=E.unread}h!==void 0&&(f=await Ar({...e.emails,read:h,writes:p,readDeliverability:e.readDeliverability,run:"sync"}));let y=r>0&&e.countTarget?await Ka(n,e.countTarget):void 0,R=es(f?.ofRun),w=e.sentBefore?.(),b=r===0?0:w!==void 0?Math.max(0,w-(R.deliverability??0)):gn(0,h!==void 0?Qr(h):0)+(y?.size??0),O=h!==void 0?hs(h):void 0,g=r===0?0:za(n,{bulkThreshold:e.bulkThreshold,duplicateRules:O,leaseAssigns:(e.mutePlan?.()?.assign.length??0)>0,...y?{targetHeld:y}:{}}),S=rt({run:Da(n.objects,{bulkThreshold:e.bulkThreshold,duplicateRules:O})+b+g,...it(l),...Ir(e.mutePlan?.()),...n.readBack!==void 0&&n.readBack>0?{readBack:n.readBack}:{},...R},m),T=e.confirmAboveRecords,A=T>0&&r>T?T:void 0,k=(n.unwritable??[]).map(({objectApiName:E,rows:j,why:N,key:D})=>({...D!==void 0?{key:D}:{},objectApiName:E,rows:j,why:N})),M=(n.heldBack??[]).map(({objectApiName:E,rows:j,parent:N,field:D,parents:W})=>({objectApiName:E,rows:j,parent:N,field:D,...W!==void 0?{parents:W.map(z=>({...z}))}:{}})),F=f?.gate,v=r===0?k.length>0?"refused":"writes":o.verdict==="exceeds"||S.verdict==="exceeds"||u!==void 0||l?.refusal!==void 0?"refused":A!==void 0||k.length>0||t.totalRows>0&&o.verdict!=="fits"||a.some(E=>E.verdict!=="fits")||d!==void 0||l!==void 0||F?.verdict==="asks"?"asks":"writes";return{check:{objects:s,total:r,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(E=>({limit:E.limit,emails:E.emails,verdict:E.verdict,...E.remaining!==void 0?{remaining:E.remaining}:{},...E.max!==void 0?{max:E.max}:{},...E.alertsCounted?{alertsCounted:!0}:{},objects:E.objects.map(({objectApiName:j,perRecord:N})=>({objectApiName:j,perRecord:N})),...E.unread!==void 0?{unread:E.unread}:{}})),...d!==void 0?{emailsUnread:d}:{},...F?.deliverability?{deliverability:F.deliverability}:{},...k.length>0?{unwritable:k}:{},...M.length>0?{heldBack:M}:{},...r>0?{apiRequests:S.verdict==="unread"?{verdict:"unread",estimate:S.estimate,unread:S.unread}:{verdict:S.verdict,estimate:S.estimate,remaining:S.remaining,max:S.max}}:{},verdict:v,...u!==void 0?{checkpointUnread:u}:{}},plan:t,storage:o,emails:a,api:S,...l!==void 0?{checkpoint:l}:{},...u!==void 0?{checkpointFailed:u}:{},...f!==void 0?{runEmails:f}:{},emailsAccepted:e.emails.accepted}}function Ha(n,e){let{check:t,storage:s,emails:r,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:Va(d,e.org,t.heldBack)}),t.total===0)return a;if(n.checkpointFailed!==void 0)a.push({code:Hr,message:n.checkpointFailed});else{let l=ot(n.checkpoint);l&&a.push(l)}i.totalRows>0&&s.verdict==="exceeds"&&a.push({code:"SYNC_STORAGE_EXCEEDED",message:`The records to write take about ${rs(s.estimateMB)} MB of data storage, and ${e.org} has ${s.remainingMB} MB left of ${s.maxMB} MB: 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=st(o,e.org,Fr);if(c&&a.push({code:qr,message:c}),e.policy!=="ask"){let l=Zr(r,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:Ut(f.message,"sync",e.emailsLiftedBy),...Te(u,!1)})}return a}async function Ya(n,e){let{check:t,storage:s,emails:r,api:i}=n,[o]=Ha(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,...Te(a,n.emailsAccepted)};let d=t.unwritable??[];if(t.verdict==="writes")return{go:!0,asked:!1,...Te(a,!1)};let c=kr(e.orgTier),l=r.filter(h=>h.verdict==="exceeds").map(Vr),u=r.filter(h=>h.verdict==="unread").map(Xr),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:ns(s),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}:{},...Kr(i),...n.checkpoint!==void 0?{checkpoint:n.checkpoint}:{},...a?.confirmation}):"unavailable";if(f==="confirmed")return{go:!0,asked:!0,...Te(a,a?.verdict==="asks")};let p=Te(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 Ja={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 Va(n,e,t=[]){let s=n.map(({objectApiName:R,rows:w,why:b,key:O})=>`${R} (${w} record${w===1?"":"s"}): ${Ja[b](e,O)}`).join("; "),r=n.length===1?"it":"them",i=n.filter(({why:R})=>R==="notAKey"),o=n.filter(({why:R})=>R!=="notAKey"),a=i.length>0&&o.length>0,d=R=>R.map(({objectApiName:w})=>w).join(" and "),c=`give the user SandForge writes as access to ${a?d(o):r} 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:R})=>R)),p=({parent:R,field:w})=>`whose ${w} names ${/^[aeiou]/i.test(R)?"an":"a"} ${R} record `+(f.has(R)?"left out":"held back"),h=t.flatMap(({objectApiName:R,rows:w,parent:b,field:O,parents:g})=>(g??[{parent:b,field:O,rows:w}]).map(S=>`${S.rows} ${R} record${S.rows===1?"":"s"}, ${p(S)}`)).join("; "),m=n.filter(({why:R})=>R==="notInTarget"),y=m.length>0?` Where ${e} has not ${d(m)}, Compare deploys ${m.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 ${s}.`+(h!==""?` Left out, ${r==="it"?"it holds":"they hold"} back ${h}.`:"")+` Leave ${r} out of the run, ${u}.${y} Nothing was written.`}function Cl(n,e){return{measure:async t=>(await Ni(t,n)).check,hold:async t=>{let s=await Ni(t,n),r=await Ya(s,e);return{check:s.check,answer:await Xa(s,r,n.checkpointFirst)}}}}async function Xa(n,e,t){let s=n.checkpoint;if(!e.go||s===void 0||t===void 0)return e;let r=await Yr(()=>t.take(s));return"stop"in r?{go:!1,...r.stop}:{...e,checkpoint:r.checkpoint}}function Il(n,e){return e==="insert"||e==="update"||e==="delete"}function Pl(n,e,t,s,r){let i,o,a,d,c=n(async u=>{let f=i?.automation;return f&&u.every(p=>f.objectsRead.includes(p))?$i(f,u):e(u)},()=>i?.plan),l=u=>{if(!Cr(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(h=>h.rows>0).map(h=>h.objectApiName);if(!i&&f.length>0){d=await e(f).catch(h=>({unread:h instanceof Error?h.message:String(h)}));try{i=await t(d),a=i.muted}catch(h){return{check:await c.measure(u),answer:l(h)}}}let p=await c.hold(u);if(p.answer.go&&i?.prepared&&!o){try{o=await i.prepared.acquire(s),a=o.outcome}catch(b){let{checkpoint:O}=p.answer;return{check:p.check,answer:{...l(b),...O?{checkpoint:O}:{}}}}let{checkpoint:h,emails:m}=p.answer,{deliverability:y}=p.check,R=Li(u),w=i.plan&&d&&"objects"in d?ts({planned:y?.senders??[],held:_n(vt(d,Or(i.plan,o.outcome),R),{writes:R}),...y?{reading:y.reading}:{},accepted:m?.accepted===!0,target:r.target,run:"sync"}):void 0;if(w)return{check:p.check,answer:{go:!1,code:w.code,message:Ut(w.message,"sync",r.liftedBy),...h?{checkpoint:h}:{},...m?{emails:m}:{}}}}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{lt as a,ht as b,sd as c,id as d,yd as e,wd as f,Sd as g,Js as h,co as i,Td as j,Md as k,Bd as l,_d as m,Wd as n,Gd as o,yo as p,wo as q,Ud as r,bo as s,zd as t,qd as u,ko as v,oe as w,je as x,ri as y,si as z,Yd as A,Ao as B,Co as C,Jd as D,sn as E,ac as F,ti as G,yi as H,bi as I,ji as J,Ta as K,tl as L,nl as M,bt as N,gn as O,rl as P,ja as Q,il as R,ol as S,al as T,Al as U,Ni as V,Ha as W,Ya as X,Va as Y,Cl as Z,Xa as _,Il as $,Pl as aa};
@@ -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
- var u="CurrencyIsoCode",S="SELECT IsoCode, ConversionRate, DecimalPlaces, IsActive, IsCorporate FROM CurrencyType",I="SELECT Metadata FROM CurrencySettings",x="SELECT RunningUserEntityAccess.IsCreatable FROM EntityDefinition WHERE QualifiedApiName = 'DatedConversionRate'",D="SELECT IsoCode, ConversionRate, StartDate, NextStartDate FROM DatedConversionRate ORDER BY IsoCode, StartDate";function g(e){let n=typeof e=="string"&&e.trim()!==""?Number(e):e;return typeof n=="number"&&Number.isFinite(n)?n:void 0}function m(e){return e===!0||e==="true"}function E(e){let n=new Set,r=new Map,t=new Map,o;for(let d of e){let i=d.IsoCode;if(typeof i!="string"||i==="")continue;let a=g(d.ConversionRate);a!==void 0&&a>0&&r.set(i,a);let s=g(d.DecimalPlaces);s!==void 0&&s>=0&&t.set(i,s),(d.IsActive===void 0||m(d.IsActive))&&n.add(i),m(d.IsCorporate)&&(o=i)}if(!(n.size===0&&r.size===0))return{...o!==void 0?{corporate:o}:{},active:n,rates:r,decimals:t}}function C(e){return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}/.test(e)?e.slice(0,10):void 0}function v(e){let n=new Map;for(let r of e){let t=r.IsoCode,o=C(r.StartDate),d=C(r.NextStartDate),i=g(r.ConversionRate);if(typeof t!="string"||t===""||!o||!d||i===void 0||i<=0)continue;let a=n.get(t)??[];a.push({start:o,next:d,rate:i}),n.set(t,a)}for(let r of n.values())r.sort((t,o)=>t.start.localeCompare(o.start));return n}async function B(e){if(e)try{let[n]=await e(I),r=n?.Metadata,t=typeof r=="object"&&r!==null?r.enableCurrencyEffectiveDates:void 0;return t===!0||t==="true"?!0:t===!1||t==="false"?!1:void 0}catch{return}}async function M(e){try{let[n]=await e(x),r=n?.RunningUserEntityAccess;return typeof r=="object"&&r!==null&&m(r.IsCreatable)}catch{return!1}}async function T(e,n){let r=await B(n);if(r===!1)return{};if(r===void 0&&!await M(e))return{unconfirmed:!0};try{let t=v(await e(D));return t.size>0?{dated:t}:{}}catch{return{unconfirmed:!0}}}async function R(e,n){let r;try{r=E(await e(S))}catch{return}if(!r)return;let{dated:t,unconfirmed:o}=await T(e,n);return{...r,...t?{dated:t}:{},...o?{datedUnconfirmed:!0}:{}}}async function A(e,n,r={}){let[t,o]=await Promise.all([R(e,r.source),R(n,r.target)]);return t&&o?{source:t,target:o}:void 0}var U={Opportunity:"CloseDate"};function _(e,n){let r=U[e],t=r!==void 0?C(n?.[r]):void 0;return r!==void 0&&t!==void 0?{field:r,on:t}:void 0}function l(e,n,r){if(r!==void 0){let o=e.dated?.get(n)?.find(d=>d.start<=r&&r<d.next);if(o)return{rate:o.rate,dated:!0}}let t=e.rates.get(n);return t===void 0?void 0:{rate:t,dated:!1}}function O(e,n,r,t){let{source:o,target:d}=r,i=l(o,e,t),a=l(d,n,t);if(i===void 0||a===void 0)return;let s=1,c=i.dated||a.dated,f=t!==void 0&&(o.datedUnconfirmed===!0&&!i.dated&&e!==o.corporate||d.datedUnconfirmed===!0&&!a.dated&&n!==d.corporate);if(o.corporate!==d.corporate){let y=d.corporate!==void 0?l(o,d.corporate,t):void 0,p=o.corporate!==void 0?l(d,o.corporate,t):void 0;if(y!==void 0)s=y.rate;else if(p!==void 0)s=1/p.rate;else return;c||=(y??p)?.dated===!0}return{factor:s*a.rate/i.rate,dated:c,unconfirmed:f}}function P(e,n,r,t){return O(e,n,r,t)?.factor}function F(e,n){let t=10**Math.max(0,Math.min(Math.trunc(n),15)),o=Math.abs(e)*t,d=Math.round(o+o*Number.EPSILON)/t;return e<0?-d:d}function q(e){return new Map(e.filter(n=>n.type==="currency").map(n=>[n.name,typeof n.scale=="number"&&n.scale>=0?n.scale:void 0]))}function k(e,n){if(typeof e=="string"&&n.active.has(e))return{to:e,chosenBy:"record-type-default"};if(n.corporate!==void 0&&n.active.has(n.corporate))return{to:n.corporate,chosenBy:"corporate"}}function Q(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.trim()==="")return;let n=Number(e);return Number.isFinite(n)?n:void 0}function Y(e,n,r){let t=typeof n.read=="string"&&n.read!==""?n.read:void 0,o=e[u];if(t===void 0||typeof o!="string"||o==="")return;let{target:d}=r,i,a;if(n.pricedIn!==void 0&&d.active.has(n.pricedIn)){if(e[u]=n.pricedIn,n.pricedIn===t)return;i=n.pricedIn,a="lines"}else if(d.active.has(o)){if(o===t)return;i=o,a="decision"}else{let f=k(n.recordTypeDefault,d);if(!f)return;({to:i,chosenBy:a}=f),e[u]=i}let s=O(t,i,r,n.ratesOn?.on),c=w(e,n.currencyFields,s?.factor,d.decimals.get(i));return{from:t,to:i,chosenBy:a,fields:c,...s===void 0?{notConverted:!0}:{factor:s.factor},...s!==void 0&&i!==d.corporate?{atTargetRate:!0}:{},...s?.dated&&n.ratesOn?{datedBy:n.ratesOn.field}:{},...s?.unconfirmed&&n.ratesOn?{datedUnconfirmed:n.ratesOn.field}:{}}}function w(e,n,r,t){let o=[];if(r===void 0)return o;for(let[d,i]of n){let a=Q(e[d]);a!==void 0&&(e[d]=F(a*r,i??t??2),o.push(d))}return o}var h={OpportunityLineItem:"OpportunityId",OpportunityLineItemSchedule:"OpportunityLineItemId",OpportunitySplit:"OpportunityId",Quote:"OpportunityId",QuoteLineItem:"QuoteId",OrderItem:"OrderId",ContractLineItem:"ServiceContractId"};function j(e){return h[e]!==void 0}function z(e,n,r,t){let o=n[u];if(typeof o!="string"||o==="")return;let d=h[e];for(let i of d!==void 0?[d]:r){let a=n[i];if(typeof a!="string"||a==="")continue;let s=t(a);if(s&&s.from===o)return s}}function W(e,n,r){let{parent:t}=n;if(!t||n.read!==t.from)return;typeof e[u]=="string"&&(e[u]=t.to);let o=w(e,n.currencyFields,t.factor,r?.target.decimals.get(t.to));return{from:t.from,to:t.to,chosenBy:"parent",fields:o,...t.factor===void 0?{notConverted:!0}:{factor:t.factor},...t.atTargetRate?{atTargetRate:!0}:{},...t.datedBy!==void 0?{datedBy:t.datedBy}:{},...t.datedUnconfirmed!==void 0?{datedUnconfirmed:t.datedUnconfirmed}:{}}}var b=class{entries=new Map;get size(){return this.entries.size}add(n,r){if(!r)return;let t=[n,r.from,r.to,r.chosenBy,r.notConverted?"kept":"",r.datedBy??"",r.datedUnconfirmed??""].join("\0"),o=this.entries.get(t);if(o){o.entry.rows++;for(let d of r.fields)o.fields.add(d);return}this.entries.set(t,{entry:{objectApiName:n,from:r.from,to:r.to,chosenBy:r.chosenBy,rows:1,fields:[],...r.notConverted?{notConverted:!0}:{},...r.atTargetRate?{atTargetRate:!0}:{},...r.datedBy!==void 0?{datedBy:r.datedBy}:{},...r.datedUnconfirmed!==void 0?{datedUnconfirmed:r.datedUnconfirmed}:{}},fields:new Set(r.fields)})}list(){return[...this.entries.values()].map(({entry:n,fields:r})=>({...n,fields:[...r].sort()}))}};function L(e){switch(e.chosenBy){case"decision":return"as decided";case"record-type-default":return`the default of their record type, ${e.from} not being active in the target`;case"corporate":return`the target's corporate currency, ${e.from} not being active there`;case"parent":return"the currency of the record they belong to";case"lines":return"the currency of the records their lines belong to"}}function N(e){if(e.notConverted)return`amounts written as read: no rate converts ${e.from} into ${e.to}`;if(e.fields.length===0)return"no amount to convert";let n=e.atTargetRate?`at the source's rate for ${e.from} and the target's for ${e.to}`:"at the source's rates",r=e.datedBy!==void 0?`, dated by ${e.datedBy}`:e.datedUnconfirmed!==void 0?`, the static ones: dated rates by ${e.datedUnconfirmed} could not be confirmed`:"";return`amounts converted ${n}${r} (${e.fields.join(", ")})`}function $(e){return`${e.rows} row(s) in ${e.from} written in ${e.to}, ${L(e)}: `+N(e)}function G(e){return e.length===0?"":`, written in another currency: ${e.map($).join("; ")}`}export{u as a,S as b,I as c,x as d,D as e,E as f,v as g,R as h,A as i,U as j,_ as k,P as l,F as m,q as n,k as o,Y as p,h as q,j as r,z as s,W as t,b as u,$ as v,G as w};