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
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a,b}from"./chunk-LWW4U276.mjs";import"./chunk-MJVTDA5Q.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as StepCancelledError,b as StepExecutor};
7
+ import{a,b,c,d}from"./chunk-PWVDNN2C.mjs";import"./chunk-6VSZNZHH.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as StepCancelledError,d as StepExecutor,b as delayMs,c as waitedWords};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d}from"./chunk-M3ROUWDX.mjs";import"./chunk-GSKCGQIP.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as ARTICLE_VERSION_OBJECT,b as articleBodyFields,c as articleBodyOptions,d as seedKnowledge};
7
+ import{a,b,c,d}from"./chunk-A65ADTCR.mjs";import"./chunk-VPDEJGPS.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as ARTICLE_VERSION_OBJECT,b as articleBodyFields,c as articleBodyOptions,d as seedKnowledge};
@@ -4,16 +4,16 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as le}from"./chunk-TUACWKIH.mjs";import{Aa as de,ta as ce,zc as ue}from"./chunk-TTFDUKUS.mjs";import{b as k,e as I,k as b,l as p,r as ae,s as oe,u as G,v as E}from"./chunk-7EANH5PY.mjs";import{appendFile as Be,mkdir as Te,readFile as Je,readdir as $e,rename as Ue,rm as We,stat as He,writeFile as Ze}from"node:fs/promises";import*as M from"node:path";import{appendFile as ke,mkdir as Re,readFile as je,readdir as xe,rename as Oe,rm as Ie,stat as Ae,writeFile as Fe}from"node:fs/promises";import*as $ from"node:path";var Ne="sync-links",Me=2e5,_e=16*1024*1024,J=k().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),Y=k().min(1).max(200),Ee=p({s:Y,t:Y,o:k().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),p:b(ae([J,J])).max(5e4),l:E(!0).optional()}),De=p({s:Y,t:Y,f:b(J).max(1e6)});function T(s){return s.slice(0,15)}function Ke(s){return s.replace(/[^A-Za-z0-9_-]/g,"_")}function Ce(s){try{return JSON.parse(s)}catch{return}}function Le(s){let e=new Map;for(let t of s.split(`
8
- `)){if(t.trim()==="")continue;let n=Ce(t),r=Ee.safeParse(n);if(r.success){let{s:y,t:R,o:C,p:P,l:D}=r.data;for(let[_,K]of P){let c=`${y}|${R}|${T(_)}`;e.delete(c),e.set(c,{s:y,t:R,o:C,source:_,target:K,...D===!0?{linked:!0}:{}})}continue}let i=De.safeParse(n);if(!i.success)continue;let{s:o,t:f,f:a}=i.data,g=new Set(a.map(T));for(let[y,R]of e)R.s===o&&R.t===f&&g.has(T(R.target))&&e.delete(y)}return e}function ht(s){return new H({storagePath:s,readFile:e=>je(e,"utf8"),writeFile:(e,t)=>Fe(e,t,"utf8"),appendFile:(e,t)=>ke(e,t,"utf8"),rename:(e,t)=>Oe(e,t),mkdir:async e=>{await Re(e,{recursive:!0})},rm:e=>Ie(e,{force:!0}),listFiles:async e=>{let t;try{t=await xe(e)}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of t){let i=await Ae($.join(e,r)).catch(()=>{});i?.isFile()&&n.push({name:r,size:i.size})}return n}})}var H=class{constructor(e){this.deps=e;this.dir=$.join(e.storagePath,Ne),this.maxPairs=e.maxPairs??Me,this.compactBytes=e.compactBytes??_e}deps;dir;maxPairs;compactBytes;queue=Promise.resolve();fileOf(e){return $.join(this.dir,`${Ke(e)}.ndjson`)}inTurn(e){let t=this.queue.then(e);return this.queue=t.catch(()=>{}),t}async read(e){let t;try{t=await this.deps.readFile(this.fileOf(e))}catch(n){if(n?.code==="ENOENT")return new Map;throw n}return Le(t)}async load(e,t){await this.queue;let n=new Map;for(let r of(await this.read(e)).values())r.s===t.sourceOrgId&&r.t===t.targetOrgId&&n.set(T(r.source),r.target);return n}async linked(e,t){await this.queue;let n=new Set;for(let r of(await this.read(e)).values())r.linked&&r.s===t.sourceOrgId&&r.t===t.targetOrgId&&n.add(T(r.source));return n}record(e,t,n,r,i=!1){let o=r.filter(([f,a])=>J.safeParse(f).success&&J.safeParse(a).success);return o.length===0?Promise.resolve():this.inTurn(async()=>{await this.deps.mkdir(this.dir);let f=this.fileOf(e);for(let a=0;a<o.length;a+=5e4){let g={s:t.sourceOrgId,t:t.targetOrgId,o:n,p:o.slice(a,a+5e4),...i?{l:!0}:{}};await this.deps.appendFile(f,`${JSON.stringify(g)}
9
- `)}await this.keepWithinBounds(e)})}forget(e,t,n){let r=new Set(n.filter(i=>J.safeParse(i).success).map(T));return r.size===0?Promise.resolve(0):this.inTurn(async()=>{let i=0,o=[];for(let a of(await this.read(e)).values())a.s!==t.sourceOrgId||a.t!==t.targetOrgId||r.has(T(a.target))&&(i++,o.push(a.target));if(i===0)return 0;let f={s:t.sourceOrgId,t:t.targetOrgId,f:[...new Set(o)]};return await this.deps.appendFile(this.fileOf(e),`${JSON.stringify(f)}
10
- `),await this.keepWithinBounds(e),i})}delete(e){return this.inTurn(()=>this.deps.rm(this.fileOf(e)))}async keepWithinBounds(e){let t=this.fileOf(e),n=$.basename(t);if(((await this.deps.listFiles(this.dir)).find(a=>a.name===n)?.size??0)<=this.compactBytes)return;let i=[...(await this.read(e)).values()].slice(-this.maxPairs),o=[];for(let a of i){let g=o[o.length-1];if(g?.s===a.s&&g.t===a.t&&g.o===a.o&&g.l===a.linked&&g.p.length<5e4){g.p.push([a.source,a.target]);continue}o.push({s:a.s,t:a.t,o:a.o,p:[[a.source,a.target]],...a.linked?{l:!0}:{}})}let f=`${t}.${process.pid}.tmp`;await this.deps.writeFile(f,o.map(a=>`${JSON.stringify(a)}
11
- `).join("")),await this.deps.rename(f,t)}};function yt(s,e){return{load:async(t,n)=>e(t)?s.load(t,n):null,record:async(t,n,r,i,o)=>{e(t)&&await s.record(t,n,r,i,o)},linked:async(t,n)=>e(t)&&s.linked?s.linked(t,n):new Set,forget:async(t,n,r)=>e(t)&&s.forget?s.forget(t,n,r):0}}var qe="sync-runs",Ye=4*1024*1024,Xe=64*1024*1024,ge=["ContentDocument","Attachment"],Ge=".scenario.json";function kt(s,e,t){return new te({storagePath:s,...e!==void 0?{runsDir:e}:{},...t?{onDropped:t}:{},readFile:n=>Je(n,"utf8"),writeFile:(n,r)=>Ze(n,r,"utf8"),appendFile:(n,r)=>Be(n,r,"utf8"),rename:(n,r)=>Ue(n,r),mkdir:async n=>{await Te(n,{recursive:!0})},rm:n=>We(n,{force:!0}),listFiles:async n=>{let r;try{r=await $e(n)}catch(o){if(o.code==="ENOENT")return[];throw o}let i=[];for(let o of r){let f=await He(M.join(n,o)).catch(()=>{});f?.isFile()&&i.push({name:o,size:f.size})}return i}})}var j=5e4,h=k().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),S=k().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),w=k().min(1).max(40),Ve=500,Qe=p({run:p({runId:k().min(1).max(200),configId:k().min(1).max(200),configName:k().max(500),sourceOrgId:k().min(1).max(200),targetOrgId:k().min(1).max(200),targetAlias:k().min(1).max(200).optional(),startedAt:w,origin:G(["csv","clone"]).optional(),pipeline:p({name:k().max(Ve)}).optional(),realtime:E(!0).optional(),targetOrganizationId:h.optional(),answersNameJobs:E(!0).optional(),writer:p({pid:I().int().positive(),hostStartedAt:w}).optional(),runUserId:h.optional()})}),et=p({object:S,created:b(h).max(j),at:w.optional(),job:h.optional()}),tt=p({sending:p({object:S,rows:I().int().positive(),at:w,job:h.optional(),upsert:E(!0).optional()})}),nt=p({writing:p({object:S,rows:I().int().positive(),at:w})}),rt=p({touched:p({object:S,rows:I().int().positive(),at:w})}),Se=k().regex(/^[A-Za-z0-9_-]{1,200}$/).refine(s=>!s.includes("__")),it=p({overwriting:p({object:S,backup:Se,ids:b(h).min(1).max(j),held:b(p({id:h,at:w,by:h.optional()})).max(j).optional(),at:w})}),st=p({overwrote:p({object:S,notWritten:b(h).max(j),at:w})}),at=p({unkept:p({object:S,fields:b(S).min(1).max(800),why:E("encrypted"),at:w})}),ot=p({deleted:p({object:S,ids:b(h).min(1).max(j),at:w})}),ct=p({runUser:h}),V=1e3,pe=p({objectApiName:S,reason:k().max(4e3),...de}),we=p({checkpoint:p({state:E("taken"),checkpointId:ce,name:k().min(1).max(500),takenAt:w,expiresAt:w.nullable(),objects:b(S).max(V),records:I().int().nonnegative(),bytes:I().int().nonnegative(),requests:I().int().nonnegative(),added:b(pe).max(V),notHeld:b(pe).max(V)})}),dt=p({end:p({at:w,status:G(["success","partial","failure"]),cancelled:E(!0).optional()})}),me=100,ut=p({version:E(1),undo:p({removedAt:w,deleted:I().int().nonnegative(),alreadyGone:I().int().nonnegative(),kept:I().int().nonnegative(),refused:I().int().nonnegative(),notReached:I().int().nonnegative().optional(),notVisible:I().int().nonnegative().optional()}).optional(),removalStamps:oe(h,w).optional(),removalSpans:b(p({first:w,last:w,userId:h})).optional(),removalLeft:b(h).optional(),restoreLeft:b(h).optional(),restoredAt:w.optional(),undeleteLeft:b(h).optional(),undeletedAt:w.optional(),madeEarlier:b(h).max(1e4*me).optional().catch(void 0),lateEarlier:b(h).max(1e4*me).optional().catch(void 0)});function lt(s){let e=ut.safeParse(s);if(!e.success)return;let{undo:t,removalStamps:n,removalSpans:r,removalLeft:i,restoreLeft:o,restoredAt:f,undeleteLeft:a,undeletedAt:g,madeEarlier:y,lateEarlier:R}=e.data;return{...t?{undo:t}:{},...n?{removalStamps:n}:{},...r?{removalSpans:r}:{},...i?{removalLeft:i}:{},...o?{restoreLeft:o}:{},...f!==void 0?{restoredAt:f}:{},...a?{undeleteLeft:a}:{},...g!==void 0?{undeletedAt:g}:{},...y?{madeEarlier:y}:{},...R?{lateEarlier:R}:{}}}function Q(s){return s.replace(/[^A-Za-z0-9_-]/g,"_")}function ft(s){try{return JSON.parse(s)}catch{return}}function he(s){let e,t,n,r,i,o,f,a=(d,u=!0)=>{d===void 0||!Number.isFinite(Date.parse(d))||(u&&(o===void 0||Date.parse(d)<Date.parse(o))&&(o=d),(f===void 0||Date.parse(d)>Date.parse(f))&&(f=d))},g,y=new Map,R=new Map,C=new Set,P=new X,D=new Map,_=new Map,K=new Map;for(let d of s.split(`
12
- `)){if(d.trim()==="")continue;let u=ft(d);if(!e){let v=Qe.safeParse(u);v.success&&(e=v.data.run);continue}let m=it.safeParse(u);if(m.success){let{object:v,backup:A,ids:x,at:O,held:N}=m.data.overwriting;a(O),P.candidates(v,A,x);for(let B of N??[]){let se=B.id.slice(0,15);K.has(se)||K.set(se,{at:B.at,...B.by!==void 0?{by:B.by}:{}})}continue}let L=st.safeParse(u);if(L.success){let{object:v,notWritten:A,at:x}=L.data.overwrote;a(x,!1),P.answer(v,A);continue}let Z=nt.safeParse(u);if(Z.success){a(Z.data.writing.at);continue}let z=at.safeParse(u);if(z.success){let{object:v,fields:A}=z.data.unkept,x=_.get(v)??new Set;for(let O of A)x.add(O);_.set(v,x);continue}let U=ot.safeParse(u);if(U.success){let{object:v,ids:A,at:x}=U.data.deleted;a(x);let O=D.get(v)??new Map;for(let N of A)O.has(N.slice(0,15))||O.set(N.slice(0,15),N);D.set(v,O);continue}let W=tt.safeParse(u);if(W.success){let{object:v,rows:A,at:x,job:O,upsert:N}=W.data.sending;a(x),g={objectApiName:v,rows:A,at:x,...O!==void 0?{job:O}:{},...N?{upsert:N}:{}},O!==void 0&&y.set(O,g);continue}let q=rt.safeParse(u);if(q.success){let{at:v}=q.data.touched;a(v),(i===void 0||Date.parse(v)>Date.parse(i))&&(i=v);continue}let F=et.safeParse(u);if(F.success){let{object:v,job:A}=F.data;A!==void 0?(y.delete(A),g?.job===A&&(g=void 0)):g?.objectApiName===v&&(e.answersNameJobs!==!0&&g.job!==void 0&&y.delete(g.job),g=void 0);let x=F.data.at;a(x,F.data.created.length>0),x!==void 0&&F.data.created.length>0&&(i===void 0||Date.parse(x)>Date.parse(i))&&(i=x);let O=R.get(F.data.object)??[];for(let N of F.data.created){let B=N.slice(0,15);C.has(B)||(C.add(B),O.push(N))}R.set(F.data.object,O);continue}let ne=we.safeParse(u);if(ne.success){n=ne.data.checkpoint;continue}let re=ct.safeParse(u);if(re.success){r=re.data.runUser;continue}let ie=dt.safeParse(u);ie.success&&(t=ie.data.end)}if(!e)return;let c={...e};delete c.answersNameJobs;let l=P.read();return{...c,...c.runUserId===void 0&&r!==void 0?{runUserId:r}:{},...t?{end:t}:{},...i!==void 0?{lastWrittenAt:i}:{},...o!==void 0?{firstWrittenAt:o}:{},...f!==void 0?{lastWriteAt:f}:{},...!t&&g?{inFlight:g}:{},...y.size>0?{jobs:[...y.values()]}:{},created:[...R].flatMap(([d,u])=>u.length>0?[{objectApiName:d,ids:u}]:[]),...l.length>0?{overwritten:l}:{},...K.size>0?{heldBefore:Object.fromEntries(K)}:{},..._.size>0?{unkept:[..._].map(([d,u])=>({objectApiName:d,fields:[...u]}))}:{},...D.size>0?{deleted:[...D].map(([d,u])=>({objectApiName:d,ids:[...u.values()]}))}:{},...n?{checkpoint:n}:{}}}var X=class{byObject=new Map;pending=new Map;written=new Set;candidates(e,t,n){let r=this.byObject.get(e)??{backup:t,ids:new Map};this.byObject.set(e,r);let i=this.pending.get(e);if(!i||i.answered){for(let o of i?.ids??[])this.written.add(o);i={ids:new Set,answered:!1},this.pending.set(e,i)}for(let o of n){let f=o.slice(0,15);r.ids.has(f)||r.ids.set(f,o),i.ids.add(f)}}answer(e,t){let n=this.pending.get(e);if(!n)return;n.answered=!0;let r=this.byObject.get(e);for(let i of t){let o=i.slice(0,15);n.ids.has(o)&&(n.ids.delete(o),this.written.has(o)||r?.ids.delete(o))}}read(){return[...this.byObject].flatMap(([e,{backup:t,ids:n}])=>n.size>0?[{objectApiName:e,backup:t,ids:[...n.values()]}]:[])}get count(){let e=0;for(let{ids:t}of this.byObject.values())e+=t.size;return e}};function ve(s,e=!1){let t=ge.flatMap(i=>s.created.filter(o=>o.objectApiName===i)),n=s.created.filter(i=>!ge.includes(i.objectApiName)),r=[...t,...[...n].reverse()].map(({objectApiName:i,ids:o})=>({objectApiName:i,ids:[...o].reverse()}));return e?r.filter(({ids:i})=>i.length>0):ue({objects:r,undo:s.removal?.undo,removalLeft:s.removal?.removalLeft})}function Rt(s){return s.created.reduce((e,t)=>e+t.ids.length,0)}function jt(s){return(s.overwritten??[]).reduce((e,t)=>e+t.ids.length,0)}function be(s){let e=s.removal?.restoreLeft,t=e?new Set(e.map(n=>n.slice(0,15))):void 0;return(s.overwritten??[]).flatMap(n=>{let r=t?n.ids.filter(i=>t.has(i.slice(0,15))):[...n.ids];return r.length>0?[{...n,ids:r}]:[]})}function xt(s){return(s.deleted??[]).reduce((e,t)=>e+t.ids.length,0)}function gt(s){let e=s.removal?.undeleteLeft,t=e?new Set(e.map(n=>n.slice(0,15))):void 0;return(s.deleted??[]).flatMap(n=>{let r=t?n.ids.filter(i=>t.has(i.slice(0,15))):[...n.ids];return r.length>0?[{objectApiName:n.objectApiName,ids:r}]:[]})}function ee(s){return ve(s).length>0||be(s).length>0||gt(s).length>0?!1:s.removal?.undo!==void 0||s.removal?.restoredAt!==void 0||s.removal?.undeletedAt!==void 0}function ye(s){return new Set([...ve(s),...be(s)].flatMap(({ids:e})=>e.map(t=>t.slice(0,15))))}function Ot(s){return s.targetAlias??s.targetOrgId}function Pe(s,e){return e.filter(t=>t.runId!==s.runId&&pt(s,t)&&!ee(t))}function pt(s,e){return s.targetOrganizationId!==void 0&&e.targetOrganizationId!==void 0?s.targetOrganizationId.slice(0,15)===e.targetOrganizationId.slice(0,15):s.targetOrgId===e.targetOrgId}function It(s,e){let t=Date.parse(s.startedAt);return Pe(s,e).filter(n=>Date.parse(n.startedAt)<t)}function At(s,e){let t=ye(s);if(t.size===0)return[];let n=Date.parse(s.startedAt);return Pe(s,e).filter(r=>Date.parse(r.startedAt)>n).flatMap(r=>{let i=0;for(let o of ye(r))t.has(o)&&i++;return i>0?[{runId:r.runId,configName:r.configName,startedAt:r.startedAt,records:i,...r.realtime?{realtime:!0}:{}}]:[]}).sort((r,i)=>Date.parse(i.startedAt)-Date.parse(r.startedAt)||0)}var te=class{constructor(e){this.deps=e;this.dir=M.join(e.storagePath,e.runsDir??qe),this.maxBytes=e.maxBytes??Ye,this.hardMaxBytes=Math.max(this.maxBytes,e.hardMaxBytes??Xe)}deps;dir;maxBytes;hardMaxBytes;queue=Promise.resolve();links;runPath(e){return M.join(this.dir,`${Q(e)}.ndjson`)}pathOf(e){return this.runPath(e)}removalPath(e){return M.join(this.dir,`${Q(e)}.removal.json`)}scenarioPath(e){return M.join(this.dir,`${Q(e)}${Ge}`)}get storagePath(){return this.deps.storagePath}recorder(e){let t=this.runPath(e.runId),n=this.deps.host??le,r={...e,startedAt:e.startedAt??new Date().toISOString(),answersNameJobs:!0,writer:{pid:n.pid,hostStartedAt:n.startedAt}},i=new Map,o=new X,f=!1,a=Promise.resolve(),g,y=!1,R,C,P=c=>{y=!0;let l=R;R=void 0;let d=C;C=void 0,a=a.then(async()=>{if(g===void 0)try{f||(f=!0,await this.deps.mkdir(this.dir),await this.keepWithinBounds(e.runId).catch(()=>{}),await this.deps.appendFile(t,`${JSON.stringify({run:r})}
7
+ import{a as le}from"./chunk-TUACWKIH.mjs";import{Ra as ce,Ya as de,md as ue}from"./chunk-ZQO5PDX5.mjs";import{b as k,e as I,k as b,l as p,r as ae,s as oe,u as V,v as E}from"./chunk-WZQEK4WT.mjs";import{appendFile as Be,mkdir as Te,readFile as Je,readdir as $e,rename as Ue,rm as We,stat as He,writeFile as Ze}from"node:fs/promises";import*as M from"node:path";import{appendFile as ke,mkdir as Re,readFile as je,readdir as xe,rename as Oe,rm as Ie,stat as Ae,writeFile as Fe}from"node:fs/promises";import*as $ from"node:path";var Ne="sync-links",Me=2e5,_e=16*1024*1024,J=k().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),Y=k().min(1).max(200),Ee=p({s:Y,t:Y,o:k().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),p:b(ae([J,J])).max(5e4),l:E(!0).optional()}),De=p({s:Y,t:Y,f:b(J).max(1e6)});function T(i){return i.slice(0,15)}function Ke(i){return i.replace(/[^A-Za-z0-9_-]/g,"_")}function Ce(i){try{return JSON.parse(i)}catch{return}}function Le(i){let e=new Map;for(let t of i.split(`
8
+ `)){if(t.trim()==="")continue;let n=Ce(t),r=Ee.safeParse(n);if(r.success){let{s:y,t:R,o:C,p:P,l:D}=r.data;for(let[_,K]of P){let c=`${y}|${R}|${T(_)}`;e.delete(c),e.set(c,{s:y,t:R,o:C,source:_,target:K,...D===!0?{linked:!0}:{}})}continue}let s=De.safeParse(n);if(!s.success)continue;let{s:o,t:f,f:a}=s.data,g=new Set(a.map(T));for(let[y,R]of e)R.s===o&&R.t===f&&g.has(T(R.target))&&e.delete(y)}return e}function ht(i){return new H({storagePath:i,readFile:e=>je(e,"utf8"),writeFile:(e,t)=>Fe(e,t,"utf8"),appendFile:(e,t)=>ke(e,t,"utf8"),rename:(e,t)=>Oe(e,t),mkdir:async e=>{await Re(e,{recursive:!0})},rm:e=>Ie(e,{force:!0}),listFiles:async e=>{let t;try{t=await xe(e)}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of t){let s=await Ae($.join(e,r)).catch(()=>{});s?.isFile()&&n.push({name:r,size:s.size})}return n}})}var H=class{constructor(e){this.deps=e;this.dir=$.join(e.storagePath,Ne),this.maxPairs=e.maxPairs??Me,this.compactBytes=e.compactBytes??_e}deps;dir;maxPairs;compactBytes;queue=Promise.resolve();fileOf(e){return $.join(this.dir,`${Ke(e)}.ndjson`)}inTurn(e){let t=this.queue.then(e);return this.queue=t.catch(()=>{}),t}async read(e){let t;try{t=await this.deps.readFile(this.fileOf(e))}catch(n){if(n?.code==="ENOENT")return new Map;throw n}return Le(t)}async load(e,t){await this.queue;let n=new Map;for(let r of(await this.read(e)).values())r.s===t.sourceOrgId&&r.t===t.targetOrgId&&n.set(T(r.source),r.target);return n}async linked(e,t){await this.queue;let n=new Set;for(let r of(await this.read(e)).values())r.linked&&r.s===t.sourceOrgId&&r.t===t.targetOrgId&&n.add(T(r.source));return n}record(e,t,n,r,s=!1){let o=r.filter(([f,a])=>J.safeParse(f).success&&J.safeParse(a).success);return o.length===0?Promise.resolve():this.inTurn(async()=>{await this.deps.mkdir(this.dir);let f=this.fileOf(e);for(let a=0;a<o.length;a+=5e4){let g={s:t.sourceOrgId,t:t.targetOrgId,o:n,p:o.slice(a,a+5e4),...s?{l:!0}:{}};await this.deps.appendFile(f,`${JSON.stringify(g)}
9
+ `)}await this.keepWithinBounds(e)})}forget(e,t,n){let r=new Set(n.filter(s=>J.safeParse(s).success).map(T));return r.size===0?Promise.resolve(0):this.inTurn(async()=>{let s=0,o=[];for(let a of(await this.read(e)).values())a.s!==t.sourceOrgId||a.t!==t.targetOrgId||r.has(T(a.target))&&(s++,o.push(a.target));if(s===0)return 0;let f={s:t.sourceOrgId,t:t.targetOrgId,f:[...new Set(o)]};return await this.deps.appendFile(this.fileOf(e),`${JSON.stringify(f)}
10
+ `),await this.keepWithinBounds(e),s})}delete(e){return this.inTurn(()=>this.deps.rm(this.fileOf(e)))}async keepWithinBounds(e){let t=this.fileOf(e),n=$.basename(t);if(((await this.deps.listFiles(this.dir)).find(a=>a.name===n)?.size??0)<=this.compactBytes)return;let s=[...(await this.read(e)).values()].slice(-this.maxPairs),o=[];for(let a of s){let g=o[o.length-1];if(g?.s===a.s&&g.t===a.t&&g.o===a.o&&g.l===a.linked&&g.p.length<5e4){g.p.push([a.source,a.target]);continue}o.push({s:a.s,t:a.t,o:a.o,p:[[a.source,a.target]],...a.linked?{l:!0}:{}})}let f=`${t}.${process.pid}.tmp`;await this.deps.writeFile(f,o.map(a=>`${JSON.stringify(a)}
11
+ `).join("")),await this.deps.rename(f,t)}};function yt(i,e){return{load:async(t,n)=>e(t)?i.load(t,n):null,record:async(t,n,r,s,o)=>{e(t)&&await i.record(t,n,r,s,o)},linked:async(t,n)=>e(t)&&i.linked?i.linked(t,n):new Set,forget:async(t,n,r)=>e(t)&&i.forget?i.forget(t,n,r):0}}var qe="sync-runs",Ye=4*1024*1024,Xe=64*1024*1024,ge=["ContentDocument","Attachment"],Ge=".scenario.json";function kt(i,e,t){return new te({storagePath:i,...e!==void 0?{runsDir:e}:{},...t?{onDropped:t}:{},readFile:n=>Je(n,"utf8"),writeFile:(n,r)=>Ze(n,r,"utf8"),appendFile:(n,r)=>Be(n,r,"utf8"),rename:(n,r)=>Ue(n,r),mkdir:async n=>{await Te(n,{recursive:!0})},rm:n=>We(n,{force:!0}),listFiles:async n=>{let r;try{r=await $e(n)}catch(o){if(o.code==="ENOENT")return[];throw o}let s=[];for(let o of r){let f=await He(M.join(n,o)).catch(()=>{});f?.isFile()&&s.push({name:o,size:f.size})}return s}})}var j=5e4,h=k().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),S=k().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),w=k().min(1).max(40),Ve=500,Qe=p({run:p({runId:k().min(1).max(200),configId:k().min(1).max(200),configName:k().max(500),sourceOrgId:k().min(1).max(200),targetOrgId:k().min(1).max(200),targetAlias:k().min(1).max(200).optional(),startedAt:w,origin:V(["csv","clone"]).optional(),pipeline:p({name:k().max(Ve)}).optional(),realtime:E(!0).optional(),targetOrganizationId:h.optional(),answersNameJobs:E(!0).optional(),writer:p({pid:I().int().positive(),hostStartedAt:w}).optional(),runUserId:h.optional()})}),et=p({object:S,created:b(h).max(j),at:w.optional(),job:h.optional()}),tt=p({sending:p({object:S,rows:I().int().positive(),at:w,job:h.optional(),upsert:E(!0).optional()})}),nt=p({writing:p({object:S,rows:I().int().positive(),at:w})}),rt=p({touched:p({object:S,rows:I().int().positive(),at:w})}),Se=k().regex(/^[A-Za-z0-9_-]{1,200}$/).refine(i=>!i.includes("__")),it=p({overwriting:p({object:S,backup:Se,ids:b(h).min(1).max(j),held:b(p({id:h,at:w,by:h.optional()})).max(j).optional(),at:w})}),st=p({overwrote:p({object:S,notWritten:b(h).max(j),at:w})}),at=p({unkept:p({object:S,fields:b(S).min(1).max(800),why:E("encrypted"),at:w})}),ot=p({deleted:p({object:S,ids:b(h).min(1).max(j),at:w})}),ct=p({runUser:h}),Q=1e3,pe=p({objectApiName:S,reason:k().max(4e3),...de}),we=p({checkpoint:p({state:E("taken"),checkpointId:ce,name:k().min(1).max(500),takenAt:w,expiresAt:w.nullable(),objects:b(S).max(Q),records:I().int().nonnegative(),bytes:I().int().nonnegative(),requests:I().int().nonnegative(),added:b(pe).max(Q),notHeld:b(pe).max(Q)})}),dt=p({end:p({at:w,status:V(["success","partial","failure"]),cancelled:E(!0).optional()})}),me=100,ut=p({version:E(1),undo:p({removedAt:w,deleted:I().int().nonnegative(),alreadyGone:I().int().nonnegative(),kept:I().int().nonnegative(),refused:I().int().nonnegative(),notReached:I().int().nonnegative().optional(),notVisible:I().int().nonnegative().optional()}).optional(),removalStamps:oe(h,w).optional(),removalSpans:b(p({first:w,last:w,userId:h})).optional(),removalLeft:b(h).optional(),restoreLeft:b(h).optional(),restoredAt:w.optional(),undeleteLeft:b(h).optional(),undeletedAt:w.optional(),madeEarlier:b(h).max(1e4*me).optional().catch(void 0),lateEarlier:b(h).max(1e4*me).optional().catch(void 0)});function lt(i){let e=ut.safeParse(i);if(!e.success)return;let{undo:t,removalStamps:n,removalSpans:r,removalLeft:s,restoreLeft:o,restoredAt:f,undeleteLeft:a,undeletedAt:g,madeEarlier:y,lateEarlier:R}=e.data;return{...t?{undo:t}:{},...n?{removalStamps:n}:{},...r?{removalSpans:r}:{},...s?{removalLeft:s}:{},...o?{restoreLeft:o}:{},...f!==void 0?{restoredAt:f}:{},...a?{undeleteLeft:a}:{},...g!==void 0?{undeletedAt:g}:{},...y?{madeEarlier:y}:{},...R?{lateEarlier:R}:{}}}function X(i){return i.replace(/[^A-Za-z0-9_-]/g,"_")}function Rt(i){return X(i)}function ft(i){try{return JSON.parse(i)}catch{return}}function he(i){let e,t,n,r,s,o,f,a=(d,u=!0)=>{d===void 0||!Number.isFinite(Date.parse(d))||(u&&(o===void 0||Date.parse(d)<Date.parse(o))&&(o=d),(f===void 0||Date.parse(d)>Date.parse(f))&&(f=d))},g,y=new Map,R=new Map,C=new Set,P=new G,D=new Map,_=new Map,K=new Map;for(let d of i.split(`
12
+ `)){if(d.trim()==="")continue;let u=ft(d);if(!e){let v=Qe.safeParse(u);v.success&&(e=v.data.run);continue}let m=it.safeParse(u);if(m.success){let{object:v,backup:A,ids:x,at:O,held:N}=m.data.overwriting;a(O),P.candidates(v,A,x);for(let B of N??[]){let se=B.id.slice(0,15);K.has(se)||K.set(se,{at:B.at,...B.by!==void 0?{by:B.by}:{}})}continue}let L=st.safeParse(u);if(L.success){let{object:v,notWritten:A,at:x}=L.data.overwrote;a(x,!1),P.answer(v,A);continue}let Z=nt.safeParse(u);if(Z.success){a(Z.data.writing.at);continue}let z=at.safeParse(u);if(z.success){let{object:v,fields:A}=z.data.unkept,x=_.get(v)??new Set;for(let O of A)x.add(O);_.set(v,x);continue}let U=ot.safeParse(u);if(U.success){let{object:v,ids:A,at:x}=U.data.deleted;a(x);let O=D.get(v)??new Map;for(let N of A)O.has(N.slice(0,15))||O.set(N.slice(0,15),N);D.set(v,O);continue}let W=tt.safeParse(u);if(W.success){let{object:v,rows:A,at:x,job:O,upsert:N}=W.data.sending;a(x),g={objectApiName:v,rows:A,at:x,...O!==void 0?{job:O}:{},...N?{upsert:N}:{}},O!==void 0&&y.set(O,g);continue}let q=rt.safeParse(u);if(q.success){let{at:v}=q.data.touched;a(v),(s===void 0||Date.parse(v)>Date.parse(s))&&(s=v);continue}let F=et.safeParse(u);if(F.success){let{object:v,job:A}=F.data;A!==void 0?(y.delete(A),g?.job===A&&(g=void 0)):g?.objectApiName===v&&(e.answersNameJobs!==!0&&g.job!==void 0&&y.delete(g.job),g=void 0);let x=F.data.at;a(x,F.data.created.length>0),x!==void 0&&F.data.created.length>0&&(s===void 0||Date.parse(x)>Date.parse(s))&&(s=x);let O=R.get(F.data.object)??[];for(let N of F.data.created){let B=N.slice(0,15);C.has(B)||(C.add(B),O.push(N))}R.set(F.data.object,O);continue}let ne=we.safeParse(u);if(ne.success){n=ne.data.checkpoint;continue}let re=ct.safeParse(u);if(re.success){r=re.data.runUser;continue}let ie=dt.safeParse(u);ie.success&&(t=ie.data.end)}if(!e)return;let c={...e};delete c.answersNameJobs;let l=P.read();return{...c,...c.runUserId===void 0&&r!==void 0?{runUserId:r}:{},...t?{end:t}:{},...s!==void 0?{lastWrittenAt:s}:{},...o!==void 0?{firstWrittenAt:o}:{},...f!==void 0?{lastWriteAt:f}:{},...!t&&g?{inFlight:g}:{},...y.size>0?{jobs:[...y.values()]}:{},created:[...R].flatMap(([d,u])=>u.length>0?[{objectApiName:d,ids:u}]:[]),...l.length>0?{overwritten:l}:{},...K.size>0?{heldBefore:Object.fromEntries(K)}:{},..._.size>0?{unkept:[..._].map(([d,u])=>({objectApiName:d,fields:[...u]}))}:{},...D.size>0?{deleted:[...D].map(([d,u])=>({objectApiName:d,ids:[...u.values()]}))}:{},...n?{checkpoint:n}:{}}}var G=class{byObject=new Map;pending=new Map;written=new Set;candidates(e,t,n){let r=this.byObject.get(e)??{backup:t,ids:new Map};this.byObject.set(e,r);let s=this.pending.get(e);if(!s||s.answered){for(let o of s?.ids??[])this.written.add(o);s={ids:new Set,answered:!1},this.pending.set(e,s)}for(let o of n){let f=o.slice(0,15);r.ids.has(f)||r.ids.set(f,o),s.ids.add(f)}}answer(e,t){let n=this.pending.get(e);if(!n)return;n.answered=!0;let r=this.byObject.get(e);for(let s of t){let o=s.slice(0,15);n.ids.has(o)&&(n.ids.delete(o),this.written.has(o)||r?.ids.delete(o))}}read(){return[...this.byObject].flatMap(([e,{backup:t,ids:n}])=>n.size>0?[{objectApiName:e,backup:t,ids:[...n.values()]}]:[])}get count(){let e=0;for(let{ids:t}of this.byObject.values())e+=t.size;return e}};function ve(i,e=!1){let t=ge.flatMap(s=>i.created.filter(o=>o.objectApiName===s)),n=i.created.filter(s=>!ge.includes(s.objectApiName)),r=[...t,...[...n].reverse()].map(({objectApiName:s,ids:o})=>({objectApiName:s,ids:[...o].reverse()}));return e?r.filter(({ids:s})=>s.length>0):ue({objects:r,undo:i.removal?.undo,removalLeft:i.removal?.removalLeft})}function jt(i){return i.created.reduce((e,t)=>e+t.ids.length,0)}function xt(i){return(i.overwritten??[]).reduce((e,t)=>e+t.ids.length,0)}function be(i){let e=i.removal?.restoreLeft,t=e?new Set(e.map(n=>n.slice(0,15))):void 0;return(i.overwritten??[]).flatMap(n=>{let r=t?n.ids.filter(s=>t.has(s.slice(0,15))):[...n.ids];return r.length>0?[{...n,ids:r}]:[]})}function Ot(i){return(i.deleted??[]).reduce((e,t)=>e+t.ids.length,0)}function gt(i){let e=i.removal?.undeleteLeft,t=e?new Set(e.map(n=>n.slice(0,15))):void 0;return(i.deleted??[]).flatMap(n=>{let r=t?n.ids.filter(s=>t.has(s.slice(0,15))):[...n.ids];return r.length>0?[{objectApiName:n.objectApiName,ids:r}]:[]})}function ee(i){return ve(i).length>0||be(i).length>0||gt(i).length>0?!1:i.removal?.undo!==void 0||i.removal?.restoredAt!==void 0||i.removal?.undeletedAt!==void 0}function ye(i){return new Set([...ve(i),...be(i)].flatMap(({ids:e})=>e.map(t=>t.slice(0,15))))}function It(i){return i.targetAlias??i.targetOrgId}function Pe(i,e){return e.filter(t=>t.runId!==i.runId&&pt(i,t)&&!ee(t))}function pt(i,e){return i.targetOrganizationId!==void 0&&e.targetOrganizationId!==void 0?i.targetOrganizationId.slice(0,15)===e.targetOrganizationId.slice(0,15):i.targetOrgId===e.targetOrgId}function At(i,e){let t=Date.parse(i.startedAt);return Pe(i,e).filter(n=>Date.parse(n.startedAt)<t)}function Ft(i,e){let t=ye(i);if(t.size===0)return[];let n=Date.parse(i.startedAt);return Pe(i,e).filter(r=>Date.parse(r.startedAt)>n).flatMap(r=>{let s=0;for(let o of ye(r))t.has(o)&&s++;return s>0?[{runId:r.runId,configName:r.configName,startedAt:r.startedAt,records:s,...r.realtime?{realtime:!0}:{}}]:[]}).sort((r,s)=>Date.parse(s.startedAt)-Date.parse(r.startedAt)||0)}var te=class{constructor(e){this.deps=e;this.dir=M.join(e.storagePath,e.runsDir??qe),this.maxBytes=e.maxBytes??Ye,this.hardMaxBytes=Math.max(this.maxBytes,e.hardMaxBytes??Xe)}deps;dir;maxBytes;hardMaxBytes;queue=Promise.resolve();links;runPath(e){return M.join(this.dir,`${X(e)}.ndjson`)}pathOf(e){return this.runPath(e)}removalPath(e){return M.join(this.dir,`${X(e)}.removal.json`)}scenarioPath(e){return M.join(this.dir,`${X(e)}${Ge}`)}get storagePath(){return this.deps.storagePath}recorder(e){let t=this.runPath(e.runId),n=this.deps.host??le,r={...e,startedAt:e.startedAt??new Date().toISOString(),answersNameJobs:!0,writer:{pid:n.pid,hostStartedAt:n.startedAt}},s=new Map,o=new G,f=!1,a=Promise.resolve(),g,y=!1,R,C,P=c=>{y=!0;let l=R;R=void 0;let d=C;C=void 0,a=a.then(async()=>{if(g===void 0)try{f||(f=!0,await this.deps.mkdir(this.dir),await this.keepWithinBounds(e.runId).catch(()=>{}),await this.deps.appendFile(t,`${JSON.stringify({run:r})}
13
13
  `)),d!==void 0&&await this.deps.appendFile(t,`${JSON.stringify(d)}
14
14
  `),l!==void 0&&await this.deps.appendFile(t,`${JSON.stringify(l)}
15
15
  `),await this.deps.appendFile(t,`${JSON.stringify(c)}
16
- `)}catch(u){g=u instanceof Error?u.message:String(u)}})},D=new Set,_=(c,l,d,u=0)=>{for(let m=u;m<l.length;m+=j)P({object:c,created:l.slice(m,m+j),at:d})},K=(c,l,d)=>{let u=l.filter(m=>h.safeParse(m).success);u.length===0||!S.safeParse(c).success||_(c,u,d??new Date().toISOString())};return{runId:e.runId,note:K,noteUnanswered:(c,l)=>K(c,l.filter(d=>!D.delete(d.slice(0,15)))),sending:(c,l,d)=>{if(l<=0||!S.safeParse(c).success)return;let u=d?.job!==void 0&&h.safeParse(d.job).success?d.job:"";u!==""?i.set(c,u):i.delete(c),P({sending:{object:c,rows:l,at:new Date().toISOString(),...u!==""?{job:u}:{},...d?.upsert?{upsert:!0}:{}}})},answered:(c,l)=>{if(!S.safeParse(c).success)return;let d=l.filter(L=>h.safeParse(L).success),u=i.get(c);i.delete(c);for(let L of d)D.add(L.slice(0,15));let m=new Date().toISOString();P({object:c,created:d.slice(0,j),at:m,...u!==void 0?{job:u}:{}}),_(c,d,m,j)},writing:(c,l)=>{if(l<=0||!S.safeParse(c).success)return;let d={writing:{object:c,rows:l,at:new Date().toISOString()}};y?P(d):R??=d},touched:(c,l)=>{l<=0||!S.safeParse(c).success||P({touched:{object:c,rows:l,at:new Date().toISOString()}})},overwriting:(c,l,d,u)=>{if(!S.safeParse(c).success||!Se.safeParse(l).success)return;let m=d.filter(z=>h.safeParse(z).success);if(m.length===0)return;o.candidates(c,l,m);let L=new Date().toISOString(),Z=new Map((u??[]).flatMap(z=>h.safeParse(z.id).success&&w.safeParse(z.at).success?[[z.id.slice(0,15),{id:z.id,at:z.at,...z.by!==void 0&&h.safeParse(z.by).success?{by:z.by}:{}}]]:[]));for(let z=0;z<m.length;z+=j){let U=m.slice(z,z+j),W=U.flatMap(q=>{let F=Z.get(q.slice(0,15));return F?[F]:[]});P({overwriting:{object:c,backup:l,ids:U,...W.length>0?{held:W}:{},at:L}})}},overwrote:(c,l)=>{if(!S.safeParse(c).success)return;let d=l.filter(m=>h.safeParse(m).success);o.answer(c,d);let u=new Date().toISOString();for(let m=0;m===0||m<d.length;m+=j)P({overwrote:{object:c,notWritten:d.slice(m,m+j),at:u}})},deleted:(c,l)=>{if(!S.safeParse(c).success)return;let d=l.filter(m=>h.safeParse(m).success),u=new Date().toISOString();for(let m=0;m<d.length;m+=j)P({deleted:{object:c,ids:d.slice(m,m+j),at:u}})},unkept:(c,l)=>{if(!S.safeParse(c).success)return;let d=l.filter(u=>S.safeParse(u).success);d.length!==0&&P({unkept:{object:c,fields:d.slice(0,800),why:"encrypted",at:new Date().toISOString()}})},checkpoint:c=>{let l=we.safeParse({checkpoint:c});l.success&&(y?P(l.data):C=l.data)},runUser:c=>{h.safeParse(c).success&&(y?P({runUser:c}):r.runUserId=c)},overwrittenCount:()=>o.count,flush:async()=>(await a,g),end:async c=>{await a,!(!f||g!==void 0)&&(P({end:{at:c.at??new Date().toISOString(),status:c.status,...c.cancelled?{cancelled:!0}:{}}}),await a)}}}idMap(){return this.links??=new H(this.deps),this.links}async get(e){let t;try{t=await this.deps.readFile(this.runPath(e))}catch{return}let n=he(t);if(!n||n.runId!==e)return;let r=await this.readRemoval(e);return r?{...n,removal:r}:n}async list(){let e=[];for(let t of await this.deps.listFiles(this.dir)){if(!t.name.endsWith(".ndjson"))continue;let n;try{n=await this.deps.readFile(M.join(this.dir,t.name))}catch{continue}let r=he(n);if(!r)continue;let i=await this.readRemoval(r.runId);e.push(i?{...r,removal:i}:r)}return e.sort((t,n)=>Date.parse(n.startedAt)-Date.parse(t.startedAt)||0)}updateRemoval(e,t){let n=this.queue.then(async()=>{let r=t(await this.readRemoval(e)??{}),i=this.removalPath(e),o=`${i}.${process.pid}.tmp`;await this.deps.mkdir(this.dir),await this.deps.writeFile(o,JSON.stringify({version:1,...r})),await this.deps.rename(o,i)});return this.queue=n.catch(()=>{}),n}async answerInFlight(e,t,n,r,i){if(!S.safeParse(t).success)return!1;let o=this.runPath(e);try{await this.deps.readFile(o)}catch{return!1}let f=n.filter(y=>h.safeParse(y).success),a=i!==void 0&&h.safeParse(i).success?{job:i}:{},g=[];for(let y=0;y===0||y<f.length;y+=j)g.push(JSON.stringify({object:t,created:f.slice(y,y+j),at:r,...a}));return await this.deps.appendFile(o,`
16
+ `)}catch(u){g=u instanceof Error?u.message:String(u)}})},D=new Set,_=(c,l,d,u=0)=>{for(let m=u;m<l.length;m+=j)P({object:c,created:l.slice(m,m+j),at:d})},K=(c,l,d)=>{let u=l.filter(m=>h.safeParse(m).success);u.length===0||!S.safeParse(c).success||_(c,u,d??new Date().toISOString())};return{runId:e.runId,note:K,noteUnanswered:(c,l)=>K(c,l.filter(d=>!D.delete(d.slice(0,15)))),sending:(c,l,d)=>{if(l<=0||!S.safeParse(c).success)return;let u=d?.job!==void 0&&h.safeParse(d.job).success?d.job:"";u!==""?s.set(c,u):s.delete(c),P({sending:{object:c,rows:l,at:new Date().toISOString(),...u!==""?{job:u}:{},...d?.upsert?{upsert:!0}:{}}})},answered:(c,l)=>{if(!S.safeParse(c).success)return;let d=l.filter(L=>h.safeParse(L).success),u=s.get(c);s.delete(c);for(let L of d)D.add(L.slice(0,15));let m=new Date().toISOString();P({object:c,created:d.slice(0,j),at:m,...u!==void 0?{job:u}:{}}),_(c,d,m,j)},writing:(c,l)=>{if(l<=0||!S.safeParse(c).success)return;let d={writing:{object:c,rows:l,at:new Date().toISOString()}};y?P(d):R??=d},touched:(c,l)=>{l<=0||!S.safeParse(c).success||P({touched:{object:c,rows:l,at:new Date().toISOString()}})},overwriting:(c,l,d,u)=>{if(!S.safeParse(c).success||!Se.safeParse(l).success)return;let m=d.filter(z=>h.safeParse(z).success);if(m.length===0)return;o.candidates(c,l,m);let L=new Date().toISOString(),Z=new Map((u??[]).flatMap(z=>h.safeParse(z.id).success&&w.safeParse(z.at).success?[[z.id.slice(0,15),{id:z.id,at:z.at,...z.by!==void 0&&h.safeParse(z.by).success?{by:z.by}:{}}]]:[]));for(let z=0;z<m.length;z+=j){let U=m.slice(z,z+j),W=U.flatMap(q=>{let F=Z.get(q.slice(0,15));return F?[F]:[]});P({overwriting:{object:c,backup:l,ids:U,...W.length>0?{held:W}:{},at:L}})}},overwrote:(c,l)=>{if(!S.safeParse(c).success)return;let d=l.filter(m=>h.safeParse(m).success);o.answer(c,d);let u=new Date().toISOString();for(let m=0;m===0||m<d.length;m+=j)P({overwrote:{object:c,notWritten:d.slice(m,m+j),at:u}})},deleted:(c,l)=>{if(!S.safeParse(c).success)return;let d=l.filter(m=>h.safeParse(m).success),u=new Date().toISOString();for(let m=0;m<d.length;m+=j)P({deleted:{object:c,ids:d.slice(m,m+j),at:u}})},unkept:(c,l)=>{if(!S.safeParse(c).success)return;let d=l.filter(u=>S.safeParse(u).success);d.length!==0&&P({unkept:{object:c,fields:d.slice(0,800),why:"encrypted",at:new Date().toISOString()}})},checkpoint:c=>{let l=we.safeParse({checkpoint:c});l.success&&(y?P(l.data):C=l.data)},runUser:c=>{h.safeParse(c).success&&(y?P({runUser:c}):r.runUserId=c)},overwrittenCount:()=>o.count,flush:async()=>(await a,g),end:async c=>{await a,!(!f||g!==void 0)&&(P({end:{at:c.at??new Date().toISOString(),status:c.status,...c.cancelled?{cancelled:!0}:{}}}),await a)}}}idMap(){return this.links??=new H(this.deps),this.links}async get(e){let t;try{t=await this.deps.readFile(this.runPath(e))}catch{return}let n=he(t);if(!n||n.runId!==e)return;let r=await this.readRemoval(e);return r?{...n,removal:r}:n}async list(){let e=[];for(let t of await this.deps.listFiles(this.dir)){if(!t.name.endsWith(".ndjson"))continue;let n;try{n=await this.deps.readFile(M.join(this.dir,t.name))}catch{continue}let r=he(n);if(!r)continue;let s=await this.readRemoval(r.runId);e.push(s?{...r,removal:s}:r)}return e.sort((t,n)=>Date.parse(n.startedAt)-Date.parse(t.startedAt)||0)}updateRemoval(e,t){let n=this.queue.then(async()=>{let r=t(await this.readRemoval(e)??{}),s=this.removalPath(e),o=`${s}.${process.pid}.tmp`;await this.deps.mkdir(this.dir),await this.deps.writeFile(o,JSON.stringify({version:1,...r})),await this.deps.rename(o,s)});return this.queue=n.catch(()=>{}),n}async answerInFlight(e,t,n,r,s){if(!S.safeParse(t).success)return!1;let o=this.runPath(e);try{await this.deps.readFile(o)}catch{return!1}let f=n.filter(y=>h.safeParse(y).success),a=s!==void 0&&h.safeParse(s).success?{job:s}:{},g=[];for(let y=0;y===0||y<f.length;y+=j)g.push(JSON.stringify({object:t,created:f.slice(y,y+j),at:r,...a}));return await this.deps.appendFile(o,`
17
17
  ${g.join(`
18
18
  `)}
19
- `),!0}async forget(e){await this.deps.rm(this.runPath(e)),await this.deps.rm(this.removalPath(e)),await this.deps.rm(this.scenarioPath(e))}async readRemoval(e){let t;try{t=JSON.parse(await this.deps.readFile(this.removalPath(e)))}catch{return}return lt(t)}async keepWithinBounds(e){let t=await this.deps.listFiles(this.dir),n=t.reduce((a,g)=>a+g.size,0);if(n<=this.maxBytes)return;let r=new Map(t.map(a=>[a.name,a.size])),i=(await this.list()).filter(a=>a.runId!==e).reverse(),o=a=>(r.get(M.basename(this.runPath(a.runId)))??0)+(r.get(M.basename(this.removalPath(a.runId)))??0)+(r.get(M.basename(this.scenarioPath(a.runId)))??0),f=async a=>{await this.forget(a.runId),n-=o(a)};for(let a of i){if(n<=this.maxBytes)return;ee(a)&&await f(a)}for(let a of i){if(n<=this.hardMaxBytes)return;if(!ee(a)){await f(a);try{this.deps.onDropped?.(a)}catch{}}}}};export{ht as a,yt as b,qe as c,Ye as d,Xe as e,ge as f,Ge as g,kt as h,j as i,Ve as j,Se as k,lt as l,he as m,X as n,ve as o,Rt as p,jt as q,be as r,xt as s,gt as t,ee as u,Ot as v,It as w,At as x,te as y};
19
+ `),!0}async forget(e){await this.deps.rm(this.runPath(e)),await this.deps.rm(this.removalPath(e)),await this.deps.rm(this.scenarioPath(e))}async readRemoval(e){let t;try{t=JSON.parse(await this.deps.readFile(this.removalPath(e)))}catch{return}return lt(t)}async keepWithinBounds(e){let t=await this.deps.listFiles(this.dir),n=t.reduce((a,g)=>a+g.size,0);if(n<=this.maxBytes)return;let r=new Map(t.map(a=>[a.name,a.size])),s=(await this.list()).filter(a=>a.runId!==e).reverse(),o=a=>(r.get(M.basename(this.runPath(a.runId)))??0)+(r.get(M.basename(this.removalPath(a.runId)))??0)+(r.get(M.basename(this.scenarioPath(a.runId)))??0),f=async a=>{await this.forget(a.runId),n-=o(a)};for(let a of s){if(n<=this.maxBytes)return;ee(a)&&await f(a)}for(let a of s){if(n<=this.hardMaxBytes)return;if(!ee(a)){await f(a);try{this.deps.onDropped?.(a)}catch{}}}}};export{ht as a,yt as b,qe as c,Ye as d,Xe as e,ge as f,Ge as g,kt as h,j as i,Ve as j,Se as k,lt as l,Rt as m,he as n,G as o,ve as p,jt as q,xt as r,be as s,Ot as t,gt as u,ee as v,It as w,At as x,Ft as y,te as z};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a as Se}from"./chunk-YYZL7UGV.mjs";import{a as be,f as we,i as ke,j as ve,l as te}from"./chunk-54HYHHVL.mjs";import{a as Le,b as je,c as $e,d as Pe,e as _,f as _e,g as xe,h as D,i as ne,l as Me,o as Je}from"./chunk-WSUKC2U3.mjs";import{a as E}from"./chunk-4TLYUZD5.mjs";import{c as Oe}from"./chunk-HF6LAK3G.mjs";import{a as P,b as Fe,d as Be,e as Ce,f as ee,h as Ne,i as We,j as Ee}from"./chunk-HFUDCNU5.mjs";import{Y as ce,Z as fe,_ as he,a as X,ba as pe,ca as ge,d as Q,fa as ye,ha as me,ia as Re}from"./chunk-KIMQQ6JQ.mjs";import{b as I}from"./chunk-CA5NAXSU.mjs";import{d as Ie,e as Z,f as Ae,k as Te}from"./chunk-ZUTUYBNW.mjs";import{Bc as le,dd as ue,gc as Y}from"./chunk-ZQO5PDX5.mjs";function Ye(a){return Array.isArray(a)?a.length:(a.successfulResults?.length??0)+(a.failedResults?.length??0)}function Ue(a,e){let t=!1,n=!1,s,r={},o=0,i=0,d=(c,p)=>(i+=c,e?.(c),p()),l=async c=>{let p=await d(We,c);return o=Ye(p),p},u={createJob:c=>{let p=a.bulk2.createJob(c);return{get id(){return p.id},open:async()=>{await d(1,()=>p.open()),s=Ce(p)},uploadData:w=>d(1,()=>p.uploadData(w)),close:async()=>{t=!0,await d(1,()=>p.close()),n=!0},abort:()=>d(1,()=>p.abort()),check:async()=>{let w=await d(1,()=>p.check());return r={state:w.state,message:w.errorMessage},w},getAllResults:()=>l(()=>p.getAllResults())}}};if("job"in a.bulk2){let c=a.bulk2;u.job=(p,w)=>{let R=c.job(p,w);return{check:async()=>{let y=await d(1,()=>R.check());return r={state:y.state,message:y.errorMessage??void 0},y},getSuccessfulResults:()=>d(1,()=>R.getSuccessfulResults()),getAllResults:()=>l(()=>R.getAllResults()),abort:()=>d(1,()=>R.abort())}}}return{connection:{bulk2:u},closeSent:()=>t,closed:()=>n,jobId:()=>s,last:()=>r,processed:()=>o,requests:()=>i}}var L=class extends Error{constructor(t,n,s=0,r=[]){super(`Bulk API job ${t||"(no id)"} was closed, and what it wrote could not be read back: ${n}`);this.jobId=t;this.requests=s;this.twins=r;this.name="BulkJobLostError"}jobId;requests;twins},M=1e4,q=50*1024*1024,Xe=10,Qe=/not supported by the Bulk API|InvalidEntity/i,Ze={unprocessed:"The Bulk API job did not write this row.",twin:"Kept out of the Bulk API job: another row carries the same values, and the job's results could not tell them apart.","may-have-written":"The Bulk API job may have written this row without saying so: it is not sent again."};async function Pt(a,e,t,n,s,r={}){let o=n==="insert"?s.map(nt):s,i=Fe(P(n,o,r.externalIdField)),d=[];o.forEach((k,A)=>{i.has(A)||d.push(A)});let l=d.map(k=>o[k]),u=o.map((k,A)=>i.has(A)?"twin":"unprocessed"),c=k=>({answers:u.map(A=>x(A==="twin"?"twin":"unprocessed")),rows:u,unmatchedIds:[],...k});if(l.length===0)return c({requests:0});let p=P(n,l,r.externalIdField),w=Buffer.byteLength(p.text,"utf8");if(l.length>M||w>q)return c({requests:0,untouched:{reason:`${l.length} rows, ${w} bytes of CSV: past what one job takes (${M} rows, ${q} bytes)`}});let R=(k,A,h,v)=>{let F={requests:k.requests,...k.jobId?{jobId:k.jobId}:{}};if(k.info.state!=="JobComplete"&&k.processed===0&&v===0)return c({...F,untouched:re(ee(k.info)??"job not complete")});let W=new Map(A.map(m=>[m.recordIndex,m])),f=u.map(m=>x(m==="twin"?"twin":"unprocessed"));return d.forEach((m,S)=>{let N=tt(W.get(S),v>0);u[m]=N.state,f[m]=N.answer}),{answers:f,rows:u,unmatchedIds:[...h],...F}},y=Ue(a),b,T=()=>b?{jobId:b}:{},B=r.pollDelay??Ee,g;try{g=await new Ne().executeBulk({connection:y.connection,bulkManager:e,pollIntervalMs:B,...r.signal?{signal:r.signal}:{},...r.onProgress?{onProgress:r.onProgress}:{},onOpened:k=>{b=k,r.onOpened?.(k)}},t,n,l,r.externalIdField)}catch(k){let A=I(k);if(!y.closeSent())return c({requests:y.requests(),...T(),untouched:re(A)});if(b===void 0)throw new L("",A,y.requests(),[...i]);let h=await et(y.connection,b,B);if(h.state==="never-closed")return c({requests:y.requests(),jobId:b,untouched:re(A)});if(h.state!=="ended")throw new L(b,h.state==="unread"?h.reason:"still running",y.requests(),[...i]);let v=Be(h.results,p,ee(h.info));return R({info:h.info,processed:y.processed(),requests:y.requests(),jobId:b},v.outcomes,v.unattributedSuccessIds,v.unattributedSuccesses)}if(g.aborted)return c({requests:y.requests(),...T(),aborted:!0});let C=y.last();return R({info:{state:C.state??"JobComplete",...C.message?{errorMessage:C.message}:{}},processed:y.processed(),requests:y.requests(),...T()},g.outcomes,g.unmatchedIds??[],g.unmatchedWrites??0)}async function et(a,e,t){let n=await te(a,e,{openGraceMs:0});for(let s=1;s<Xe;s++){if(n.state==="ended"||n.state==="never-closed")return n;await new Promise(r=>setTimeout(r,t(s-1))),n=await te(a,e,{openGraceMs:0})}return n}function re(a){return Qe.test(a)?{reason:a,unsupported:!0}:{reason:a}}function x(a){return{id:"",success:!1,errors:[Ze[a]]}}function tt(a,e){if(a===void 0||a.state==="no-result"){let s=e?"may-have-written":"unprocessed";return{state:s,answer:x(s)}}if(a.state==="unprocessed")return{state:"unprocessed",answer:x("unprocessed")};if(a.success)return a.id?{state:"answered",answer:{id:a.id,success:!0,errors:[],...a.created!==void 0?{created:a.created}:{}}}:{state:"may-have-written",answer:x("may-have-written")};let t=a.error??"Unknown error",n=Ie(t);return{state:"answered",answer:n?{id:"",success:!1,errors:[Ae(n)],errorDetails:[n]}:{id:"",success:!1,errors:[t]}}}function nt(a){let e;for(let[t,n]of Object.entries(a))n===""&&(e??={...a},e[t]=null);return e??a}var ae={rest:200,bulk:1e4},Ke=3,ot=3,De=3,it=2e3;function at(a){return new Promise(e=>setTimeout(e,a))}function dt(a,e,t={bulk:!1}){let n=t.bulk&&a.api==="bulk"&&e>=2e3?"bulk":"rest",s=Math.min(a.batchSize,ae[n]);return{api:n,batchSize:s,batchCount:Math.ceil(e/s),clamped:s<a.batchSize}}function z(a){return a.refusals.flatMap(e=>e.leftOut)}function se(a){let e=a.built?.source.Id;return typeof e=="string"?e:void 0}function qe(a){return(a.built?.nullifiedFks??[]).map(({field:e,sourceRefId:t,insertOnly:n})=>({field:e,sourceRefId:t,...n?{insertOnly:n}:{}}))}function lt(a){let e=a.RecordTypeId;return typeof e=="string"&&e!==""}function oe(a){return a.refusals.length===0?a.payload:D(a.payload,z(a))}function He(a,e){let t=new Map;return e?.refusedIn?.answers.forEach((n,s)=>{let r=a[s];n&&r&&t.set(r,n.errors)}),t}var ut=new Set,ct=new Map;function H(a){return{objectApiName:a.objectApiName,op:a.upsertField?"upsert":"insert"}}function Ve(a){return a!==void 0&&!a.success?ue(a.errors):void 0}function ft(a){let e=a.automation??"the target's automation";E.warn(`[forge] ${a.objectApiName}: ${e} hit ${a.limit??"a Salesforce limit"} on a call of ${a.from} \u2014 sending a record on its own, then smaller calls`+(a.op==="upsert"?" (upsert).":"."))}var V={"validation-rule":"a validation rule","restricted-picklist":"a restricted picklist","lookup-filter":"a lookup filter","inactive-owner":"the target, the owner being inactive there"};function ht(a){let e=new Set(a.map(o=>o.refusedBy)),t=Object.keys(V).filter(o=>o!=="inactive-owner"&&e.has(o)).map(o=>V[o]),n=t.length>1?`${t.slice(0,-1).join(", ")} or ${t[t.length-1]}`:t[0],s=n===void 0?void 0:`${n} of the target`;if(!e.has("inactive-owner"))return s??`${V["validation-rule"]} of the target`;let r=`${V["inactive-owner"]},`;return s===void 0?r:`${s} or ${r}`}function ie(a,e){if(!a.ownersMapped||a.ownersMapped.size===0)return!1;let t=_(e,"OwnerId"),n=t===void 0?void 0:e[t];return typeof n=="string"&&a.ownersMapped.has(n.slice(0,15))}function pt(a,e,t,n,s){let r=a.errorDetails??[];if(r.length===a.errors.length)return _e(r,e,t,n,s)}function ze(a){a.linkedToCreatedCount=(a.linkedToCreatedCount??0)+1}function gt(a){let e=a.errorDetails??[];return Je(a.errors,e.length===a.errors.length?e:void 0)}function G(a){return a.map(e=>e.field).join(", ")}function yt(a,e){return`Sent again without ${G(a)} after the first refusal: ${e.join("; ")}`}var mt=["first","second","third"];function J(a){return a.map(({leftOut:e,errors:t},n)=>n===0?yt(e,t):`Sent again without ${G(e)} too after the ${mt[n]} refusal: `+t.join("; "))}function U(a){let e=(t,n)=>t.length===0?[]:[`Sent without ${G(t)}: ${n} earlier in the run, `+[...new Set(t.map(s=>s.reason))].join("; ")];return[...e(a.filter(t=>t.refusedBy!=="inactive-owner"),"the target refused the same value under the same record type"),...e(a.filter(t=>t.refusedBy==="inactive-owner"),"the target refused the same owner, inactive there,")]}function O(a){return`${a} record${a===1?"":"s"}`}var Rt="The call was sent and its answer never came back: the target may hold any of these records, and which of them is unknown. Counted as failed and never sent again, they are not among the records the run created, which removing its records takes back.",bt="Counted as failed and never sent again, they are not among the records the run created; the records the job wrote that no row was matched to are, and removing the run's records takes them back.",wt="DUPLICATES_DETECTED";function kt(a,e){if(a==="twin"||a==="unprocessed")return!0;if(a!=="answered"||e.success)return!1;let t=e.errorDetails;return t?.length!==1||t[0].statusCode===wt}function vt(a,e){let t=i=>i.reduce((d,l)=>d+Math.max(Buffer.byteLength(l,"utf8"),4)+(l.split('"').length-1)+3,1),n=t(e.columns),s=[],r=0,o=n;return e.rows.forEach((i,d)=>{let l=t(i);d>r&&o+l>a&&(s.push([r,d]),r=d,o=n),o+=l}),e.rows.length>r&&s.push([r,e.rows.length]),s}function It(a,e,t){let n=a.find(r=>r.isReference&&r.nillable===!1&&r.name!=="OwnerId"&&e.has(r.name))?.name;if(n===void 0)return;let s=r=>{let o=t[r][n];return typeof o=="string"?o:""};if(t.some((r,o)=>s(o)!==""))return t.map((r,o)=>o).sort((r,o)=>{let i=s(r),d=s(o);return i===d?r-o:i===""?1:d===""||i<d?-1:1})}var At="The target refused the call for its API request limit, which no retry gets past: the node stopped there.",Tt="A validation rule of the target, or a trigger with its code, refused the row without naming a field: there was none to send it again without.";function Ft(){return{successCount:0,updatedCount:0,linkedExistingCount:0,failureCount:0,alreadyExistsCount:0,unidentifiedExistingCount:0,errorSamples:[],pendingFkUpdates:[]}}var Ge=class{constructor(e,t,n=at,s=be()){this.deps=e;this.wait=n;this.splitting=s;this.batchStrategy=t??new Oe}deps;wait;splitting;batchStrategy;refusedValues=new Map;refusedOwners=new Map;backoff=new Me({initialDelay:it});async writeNode(e,t=Ft()){let{node:n,fieldInfos:s,creatableFields:r,targetOrgId:o,remapper:i}=e,d=await this.heldBeforeInsert(n.objectApiName,o,e.records);for(let[h,v]of d){let F=e.cleanedRecords[h]?.source,W=F?.Id;if(typeof W!="string")continue;i.addExisting(W,v,n.objectApiName);let f=F?.ContactId;n.objectApiName===X&&typeof f=="string"&&i.wasCreated(f)&&(t.withTheirRecord=[...t.withTheirRecord??[],W])}t.linkedExistingCount+=d.size;let l=await this.giveFlagsBack(n.objectApiName,o,e,d);l&&(t.flagsNotKept=pe(t.flagsNotKept,l));let u=e.records.filter((h,v)=>!d.has(v)),c=e.cleanedRecords.filter((h,v)=>!d.has(v)),p=this.batchStrategy.resolve(n.batchStrategy,u.length),{api:w,batchSize:R,batchCount:y,clamped:b}=dt(p,u.length,{bulk:this.jobsCanCarry(e.bulk,n.objectApiName)});if(b&&E.warn(`[forge] ${n.objectApiName}: batch strategy asked for ${p.batchSize} records per call (api="${p.api}") but the write path is "${w}" (max ${ae[w]}) \u2014 using ${R} per call (${y} batch(es)).`),w==="bulk"){let h=It(s,r,u);if(h){let v={records:u,cleanedRecords:c};u=h.map(F=>v.records[F]),c=h.map(F=>v.cleanedRecords[F])}}e.onProgress({objectName:n.objectApiName,status:"running",progress:0,recordCount:u.length,fieldCount:s.length,createableFieldCount:r.size,message:`Inserting ${u.length} ${n.objectApiName} records in ${y} batch(es)...`});let T=0,B=this.pickUpsertField(s,r,u,e.upsertMode==="auto"&&this.deps.upsertRecords?"auto":"off",e.tableKeys),g={objectApiName:n.objectApiName,targetOrgId:o,targetKeyPrefix:e.targetKeyPrefix,remapper:i,tally:t,oweLookups:e.oweLookups,onWritten:e.onWritten,onCreatedWithoutRecordType:e.onCreatedWithoutRecordType,calls:e.calls,bulk:e.bulk,byNaturalKey:[],refusedOnTheirFields:[],locked:[],upsertField:B,ownersMapped:e.ownersMapped,remembered:new Set([...e.picklistFields??[]].filter(([,h])=>h.controllerName===void 0).map(([h])=>h.toLowerCase()))},{byNaturalKey:C}=g,k=h=>{let v=I(h);this.leaveLockedAsFailed(g,g.locked.splice(0),v),this.leaveRefusedAsFailed(g,g.refusedOnTheirFields.splice(0),v),this.settleByNaturalKey(n.objectApiName,C,[],i,t,`The record the target holds under the same key was not looked up: ${v}`)};for(let h=0;h<y;h++){let v=u.slice(h*R,(h+1)*R).map((m,S)=>{let{sent:N,before:$}=this.withoutRefusedValues(g,m);return{payload:N,built:c[T+S],before:$,refusals:[],lockResends:0}}),F=`${n.objectApiName} batch ${h+1}/${y}`,W;try{W=await this.sendRows(g,e,v,F,u.length-T-v.length)}catch(m){throw k(m),m}if(W){let m=I(W.thrown);this.leaveLockedAsFailed(g,g.locked.splice(0),m),this.leaveRefusedAsFailed(g,g.refusedOnTheirFields.splice(0),m);break}T+=v.length;let f;try{f=await this.sendLockedAgain(g,e,u.length-T)}catch(m){throw k(m),m}if(f){this.leaveRefusedAsFailed(g,g.refusedOnTheirFields.splice(0),I(f.thrown));break}e.onProgress({objectName:n.objectApiName,status:"running",progress:Math.round((h+1)/y*100),message:`batch ${h+1}/${y} \u2014 ${Math.min((h+1)*R,u.length)}/${u.length} records`})}try{await this.writeAgainWithoutTheirFields(g,e,Math.min(R,ae.rest))}catch(h){throw k(h),h}let A=Q[n.objectApiName];if(A&&C.length>0){let h,v;try{h=await this.recordsByNaturalKey(o,n.objectApiName,A,C.map(F=>F.payload))}catch(F){h=[],v=`The record the target holds under the same key could not be looked up: ${I(F)}`}this.settleByNaturalKey(n.objectApiName,C,h,i,t,v)}return t}send(e,t){return e.upsertField&&this.deps.upsertRecords?this.deps.upsertRecords(e.targetOrgId,e.objectApiName,e.upsertField,t):this.deps.insertRecords(e.targetOrgId,e.objectApiName,t)}jobsCanCarry(e,t){return e!==void 0&&this.deps.bulkWriteRecords!==void 0&&!e.restOnly.has(t)&&!e.bulkUnsupported.has(t)}goesSmallerByRest(e){return this.splitting.sizes.of(e)<200}async sendRows(e,t,n,s,r,o){let{bulk:i}=e;if(!i||!this.jobsCanCarry(i,e.objectApiName)||n.length<2e3)return this.sendByRest(e,t,n,s,r,o);for(let d=0;d<n.length;d+=M){let l=n.slice(d,d+M),u=n.length-d-l.length+r,c;try{c=l.length>=2e3?await this.writeAsJobs(e,t,i,l,s,u,o):await this.sendByRest(e,t,l,s,u,o)}catch(p){throw o?.(n.slice(d+l.length),I(p)),p}if(c)return c}}async sendByRest(e,t,n,s,r,o,i){if(n.length===0)return;try{await t.waitIfPaused()}catch(l){let u=I(l);throw o?o(n,u):this.leaveLimitedAsFailed(e,n,He(n,i),u),l}let d=await this.callAndSettle(e,t,n,o,i);if(d)return this.settleThrown(e,d.threw,d.rows,s,d.rest.length+r),d.threw}async writeAsJobs(e,t,n,s,r,o,i){let d=this.deps.bulkWriteRecords;if(!d)return this.sendByRest(e,t,s,r,o,i);let l=H(e);if(this.goesSmallerByRest(l))return this.sendJobByRest(e,t,n,s,r,o,i);let u=e.upsertField?"upsert":"insert",c=s.map(oe),p=vt(q,P(u,c,e.upsertField));for(let[w,R]of p){let y=s.slice(w,R),b=s.length-R+o;if(this.goesSmallerByRest(l)){let f;try{f=await this.sendJobByRest(e,t,n,y,r,b,i)}catch(m){throw i?.(s.slice(R),I(m)),m}if(f)return f;continue}try{await t.waitIfPaused()}catch(f){throw i?.(s.slice(w),I(f)),f}let T=c.slice(w,R),B=e.calls?.sending(e.objectApiName,y.map((f,m)=>({sourceId:se(f),payload:T[m],owes:qe(f)})),e.upsertField,!0),g;try{g=await d(e.targetOrgId,e.objectApiName,u,T,{bulkManager:n.manager,signal:n.signal,...e.upsertField?{externalIdField:e.upsertField}:{},onOpened:f=>{B!==void 0&&e.calls?.opened?.(B,f)}})}catch(f){if(f instanceof L){let m={thrown:f,left:"may-have-written",tries:1},S=new Set(f.twins),N=y.filter(($,de)=>!S.has(de));return this.settleThrown(e,m,N,`${r} (Bulk API job)`,b),this.leaveTwinsUnsent(e,y.length-N.length,r,f),m}g={answers:[],rows:[],unmatchedIds:[],untouched:{reason:I(f)},requests:0}}if(g.aborted){try{await t.waitIfPaused()}catch(f){throw B!==void 0&&e.calls?.answered(B),i?.(s.slice(w),I(f)),f}g={...g,untouched:{reason:"the job was aborted"}}}if(g.untouched){B!==void 0&&e.calls?.answered(B),g.untouched.unsupported&&n.bulkUnsupported.add(e.objectApiName),E.warn(`[forge] ${e.objectApiName}: a Bulk API job of ${O(y.length)} wrote nothing (${g.untouched.reason}) \u2014 sent by REST`+(g.untouched.unsupported?", as every write of the object in the run.":"."));let f;try{f=await this.sendByRest(e,t,y,r,b,i)}catch(m){throw i?.(s.slice(R),I(m)),m}if(f)return f;continue}g.unmatchedIds.length>0&&(e.calls?.unattributed?.(e.objectApiName,g.unmatchedIds),E.warn(`[forge] ${e.objectApiName}: Bulk API job ${g.jobId??""} wrote ${O(g.unmatchedIds.length)} no row was matched to \u2014 kept for removal.`));let C=[],k=[],A=[],h=[],v=[],F=[],W;if(y.forEach((f,m)=>{let S=g.rows[m]??"unprocessed",N=g.answers[m],$=S==="answered"?Ve(N):void 0;S==="may-have-written"?F.push(f):$!==void 0&&N!==void 0?(W??=$,h.push(f),v.push(N)):!N||kt(S,N)?A.push(f):(C.push(f),k.push(N))}),this.settleMayHaveBeenWritten(e,F,r,g.jobId),await this.settleAnswers(e,C,B===void 0?{answers:k}:{answers:k,callId:B}),A.length>0){let f;try{f=await this.sendByRest(e,t,A,`${r}, by REST`,h.length+b,i)}catch(m){throw i?.([...h,...s.slice(R)],I(m)),m}if(f)return f}if(h.length>0){let f;try{f=await this.sendByRest(e,t,h,`${r}, by REST`,b,i,{refusedIn:{from:200,answers:v,...W?{cause:W}:{}}})}catch(m){throw i?.(s.slice(R),I(m)),m}if(f)return f}}}async sendJobByRest(e,t,n,s,r,o,i){let d=H(e),{sizes:l,allowance:u}=this.splitting,c=l.of(d),p=Math.ceil(s.length/c),w=u.take(d,p);l.countExtraCalls(d,w);let R=s.slice(0,w*c),y=s.slice(R.length);if(R.length>0){let b;try{b=await this.sendByRest(e,t,R,r,y.length+o,i,{pricedAs:"job",paid:{calls:w}})}catch(T){throw i?.(y,I(T)),T}finally{w<p&&l.spend(d)}if(b)return b}else w<p&&l.spend(d);if(y.length!==0)return y.length>=2e3?this.writeAsJobs(e,t,n,y,r,o,i):this.sendByRest(e,t,y,r,o,i)}leaveTwinsUnsent(e,t,n,s){t!==0&&(e.tally.failureCount+=t,this.sample(e.tally,{recordSummary:`${n}: ${O(t)} not written`,messages:[I(s),"Kept out of the Bulk API job as twins of other rows, to be written by REST once it answered: never sent, the target holds none of them."]}))}settleMayHaveBeenWritten(e,t,n,s){if(t.length===0)return;let{tally:r}=e;r.failureCount+=t.length;let o=t.map(se).filter(i=>i!==void 0);r.mayHaveBeenWritten=[...r.mayHaveBeenWritten??[],...o],this.sampleAhead(r,{recordSummary:`${n}: ${O(t.length)} may have been written`,messages:[`Bulk API job ${s??""} gave them no result of their own, and wrote records no row was matched to: the target may hold any of these records, and which of them is unknown.`,bt]})}async call(e,t,n){let s=n.map(oe);for(let r=0;;r++){let o=e.calls?.sending(e.objectApiName,n.map((i,d)=>({sourceId:se(i),payload:s[d],owes:qe(i)})),e.upsertField);try{let i=await this.send(e,s);return o===void 0?{answers:i}:{answers:i,callId:o}}catch(i){let d=Se(i);if(o!==void 0&&d!=="may-have-written"&&e.calls?.answered(o),d!=="not-received"||r===Ke)return{thrown:i,left:d,tries:r+1};let l=this.backoff.calculateDelay(r);E.warn(`[forge] ${e.objectApiName}: a call of ${O(s.length)} never reached the target (${I(i)}) \u2014 sent again in ${l} ms (${r+1}/${Ke}).`),await this.wait(l),await t.waitIfPaused()}}}async callAndSettle(e,t,n,s,r){let o,i={answers:[]},d=He(n,r),{stopped:l}=await ve(n,{key:H(e),sizes:this.splitting.sizes,allowance:this.splitting.allowance,...r,beforeEachSend:()=>t.waitIfPaused(),send:async u=>{let c=await this.call(e,t,u);return"thrown"in c?(o=c,"stop"):(i=c,{answers:c.answers})},limited:(u,c)=>{let p=Ve(u);return p&&u&&d.set(c,u.errors),p},settle:(u,c,p,w,R)=>this.settleAnswers(e,u,R?{answers:c}:i,p,w),onThrow:(u,c)=>{let p=I(c);s?s(u,p):this.leaveLimitedAsFailed(e,u,d,p)},onFirstRefusal:ft});if(!(!l||o===void 0))return{threw:o,rows:l.part,rest:l.rest}}sample(e,t){e.errorSamples.length<3&&e.errorSamples.push(t)}sampleAhead(e,t){e.errorSamples.unshift(t),e.errorSamples.splice(3)}async settleAnswers(e,t,{answers:n,callId:s},r=ut,o=ct){t.forEach((i,d)=>{let l=n[d];l?.success&&!r.has(d)&&this.settle(e,l,i)}),e.remapper.persist(),await this.readWhatMayBeEmpty(e,n.filter(i=>i!==void 0)),t.forEach((i,d)=>{if(r.has(d))return;let l=n[d];if(l){l.success||this.settle(e,l,i,o.get(d));return}e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(i.payload),messages:[`No result returned for record (API truncated batch: ${n.length}/${t.length})`,...J(i.refusals),...U(i.before)]})}),e.remapper.persist(),s!==void 0&&e.calls?.answered(s)}async readWhatMayBeEmpty(e,t){if(e.mayBeEmpty!==void 0||!t.some(r=>(r.errorDetails??[]).some(o=>o.statusCode===je)))return;let s=await this.deps.describeFields?.(e.targetOrgId,e.objectApiName).catch(()=>{});e.mayBeEmpty=new Set((s??[]).filter(r=>r.nillable===!0).map(r=>r.name.toLowerCase()))}settleThrown(e,t,n,s,r){let{tally:o}=e,i=I(t.thrown);if(o.failureCount+=n.length+r,t.left==="may-have-written"){let l=n.map(u=>u.built?.source.Id).filter(u=>typeof u=="string");o.mayHaveBeenWritten=[...o.mayHaveBeenWritten??[],...l],this.sampleAhead(o,{recordSummary:`${s}: ${O(n.length)} may have been written`,messages:[i,Rt,...r>0?[`${O(r)} after them not sent.`]:[]]});return}let d=n.length+r;this.sample(o,{recordSummary:`${s}: ${O(d)} not written`,messages:[i,...t.left==="request-limit"?[At]:[],...t.left==="not-received"?[`Sent ${t.tries} times, the call never reached the target: it holds none of them.`]:[]]})}async sendLockedAgain(e,t,n){for(let s=0;e.locked.length>0;s++){let r=this.backoff.calculateDelay(s);E.warn(`[forge] ${e.objectApiName}: the target could not lock a record for ${O(e.locked.length)} \u2014 sent again in ${r} ms.`),await this.wait(r),await t.waitIfPaused();let o=e.locked.splice(0),i=o.map(({row:u})=>({...u,lockResends:u.lockResends+1})),d=new Map(i.map((u,c)=>[u,o[c]])),l=await this.callAndSettle(e,t,i,(u,c)=>this.leaveLockedAsFailed(e,u.flatMap(p=>d.get(p)??[]),c));if(l)return this.settleThrown(e,l.threw,l.rows,`${e.objectApiName}, sent again`,n+l.rest.length),this.leaveLockedAsFailed(e,e.locked.splice(0),I(l.threw.thrown)),l.threw}}settle(e,t,n,s){let{tally:r,remapper:o,objectApiName:i}=e,{built:d,before:l}=n,u=oe(n);if(t.success){let b=d?.source.Id,T=t.created===!1;if(T?r.updatedCount++:r.successCount++,typeof b=="string"&&(T?o.addUpdated(b,t.id,i):o.add(b,t.id,i)),d&&e.onWritten?.(d,t.id),!T&&!lt(u)&&e.onCreatedWithoutRecordType?.(d,t.id),d&&d.nullifiedFks.length>0){let g=typeof d.source.Id=="string"?d.source.Id:void 0,C=d.nullifiedFks.map(k=>({objectApiName:i,newId:t.id,sourceId:g,fieldName:k.field,sourceRefId:k.sourceRefId,...k.insertOnly?{insertOnly:!0}:{}}));e.oweLookups?e.oweLookups(C):r.pendingFkUpdates.push(...C)}let B=[...l,...z(n)];B.length>0&&(r.writtenWithoutFields=ne(r.writtenWithoutFields,{rows:1,fields:B.map(g=>({...g,rows:1}))}));for(let{field:g,refusedBy:C}of B)C!=="lookup-filter"||!t.id||(r.leftEmptyByFilter??=[]).push({field:g,recordId:t.id});return}this.rememberRefusedValues(e,t,u),this.rememberRefusedOwners(e,t,u);let c=Te(t,e.targetKeyPrefix);if(c.kind==="linked"){r.linkedExistingCount++,o.createdTarget(c.id)&&ze(r);let b=d?.source.Id;typeof b=="string"&&o.addExisting(b,c.id,i);return}if(c.kind==="unidentified"&&Q[i]){e.byNaturalKey.push({payload:u,sourceId:d?.source.Id,errors:t.errors});return}let p=gt(t);if(p&&n.lockResends<ot){e.locked.push({row:n,errors:t.errors});return}let w=b=>e.mayBeEmpty?.has(b.toLowerCase())??!1,R=pt(t,u,e.upsertField,w,{inactiveOwner:!ie(e,u)}),y=n.refusals.length<De;if(R&&y){e.refusedOnTheirFields.push({...n,refusals:[...n.refusals,{errors:t.errors,leftOut:R}]});return}r.failureCount++,c.kind==="unidentified"&&r.unidentifiedExistingCount++,t.errors.every(b=>Y(b))&&r.alreadyExistsCount++,this.sample(r,{recordSummary:j(n.payload),messages:[...t.errors,...J(n.refusals),...p?[`Sent again ${n.lockResends} times, the target still could not lock a record the write needed.`]:[],...R&&!y?[`Not sent again: a row goes again without the fields the target refused ${De} times at most.`]:[],...xe(t.errorDetails)?[Tt]:[],...s?[we(s,ke(this.splitting.allowance,H(e)),"run")]:[],...U(l)]})}refusedValueKey(e,t,n){let s=t.RecordTypeId,r=t[n];if(typeof s!="string"||s===""||typeof r!="string"||r==="")return;let o=n.toLowerCase();if(!(!e.remembered.has(o)||o===e.upsertField?.toLowerCase()))return[e.objectApiName,s,o,r].join("\0")}rememberRefusedValues(e,t,n){for(let s of t.errorDetails??[])if(s.statusCode===Le)for(let r of s.fields){let o=_(n,r),i=o===void 0?void 0:this.refusedValueKey(e,n,o);o===void 0||i===void 0||this.refusedValues.has(i)||this.refusedValues.set(i,{field:o,refusedBy:"restricted-picklist",reason:Z(s)})}}rememberRefusedOwners(e,t,n){let s=_(n,"OwnerId");if(!(s===void 0||s.toLowerCase()===e.upsertField?.toLowerCase())&&!ie(e,n))for(let r of t.errorDetails??[]){if(r.statusCode!==$e)continue;let o=Pe(r,n);o===void 0||this.refusedOwners.has(o)||this.refusedOwners.set(o,{field:"OwnerId",refusedBy:"inactive-owner",reason:Z(r)})}}withoutRefusedValues(e,t){let n=[];if(this.refusedValues.size===0&&this.refusedOwners.size===0)return{sent:t,before:n};for(let o of Object.keys(t)){let i=this.refusedValueKey(e,t,o),d=i===void 0?void 0:this.refusedValues.get(i);d&&n.push({...d,field:o})}let s=_(t,"OwnerId"),r=s===void 0?void 0:t[s];if(s!==void 0&&typeof r=="string"&&s.toLowerCase()!==e.upsertField?.toLowerCase()&&!ie(e,t)){let o=this.refusedOwners.get(r.slice(0,15));o&&n.push({...o,field:s})}return n.length===0?{sent:t,before:n}:{sent:D(t,n),before:n}}leaveRefusedAsFailed(e,t,n){for(let s of t){let r=s.refusals[s.refusals.length-1];e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(s.payload),messages:[...r?.errors??[],...J(s.refusals.slice(0,-1)),`Not written again without ${G(z(s))}: ${n}`,...U(s.before)]})}}leaveLimitedAsFailed(e,t,n,s){for(let r of t){let o=n.get(r);o&&(e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(r.payload),messages:[...o,...J(r.refusals),`Not sent again in a smaller call: ${s}`,...U(r.before)]}))}}leaveLockedAsFailed(e,t,n){for(let{row:s,errors:r}of t)e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(s.payload),messages:[...r,...J(s.refusals),`Not sent again: ${n}`,...U(s.before)]})}async writeAgainWithoutTheirFields(e,t,n){for(;e.refusedOnTheirFields.length>0;){let s=e.refusedOnTheirFields.splice(0);if(t.onProgress({objectName:e.objectApiName,status:"running",progress:100,message:`Writing ${s.length} ${e.objectApiName} record${s.length===1?"":"s"} again without the fields ${ht(s.flatMap(z))} refused...`}),this.jobsCanCarry(e.bulk,e.objectApiName)&&s.length>=2e3){let r=`${e.objectApiName}, sent again`,o=await this.sendRows(e,t,s,r,0,(i,d)=>this.leaveRefusedAsFailed(e,i,d));if(o??=await this.sendLockedAgain(e,t,0),o){let i=I(o.thrown);this.leaveLockedAsFailed(e,e.locked.splice(0),i),this.leaveRefusedAsFailed(e,e.refusedOnTheirFields.splice(0),i);return}continue}for(let r=0;r<s.length;r+=n){let o=s.slice(r,r+n),i;try{await t.waitIfPaused()}catch(l){throw this.leaveRefusedAsFailed(e,s.slice(r),I(l)),l}try{i=await this.callAndSettle(e,t,o,(l,u)=>this.leaveRefusedAsFailed(e,l,u))}catch(l){throw this.leaveRefusedAsFailed(e,s.slice(r+n),I(l)),l}let d;if(i){d=i.threw;let l=I(i.threw.thrown),u=[...i.rest,...s.slice(r+n)];i.threw.left==="may-have-written"?(this.settleThrown(e,i.threw,i.rows,`${e.objectApiName}, sent again`,0),this.leaveRefusedAsFailed(e,u,l)):this.leaveRefusedAsFailed(e,[...i.rows,...u],l)}else{try{d=await this.sendLockedAgain(e,t,0)}catch(l){throw this.leaveRefusedAsFailed(e,s.slice(r+n),I(l)),l}d&&this.leaveRefusedAsFailed(e,s.slice(r+n),I(d.thrown))}if(d){this.leaveRefusedAsFailed(e,e.refusedOnTheirFields.splice(0),I(d.thrown));return}}}}settleByNaturalKey(e,t,n,s,r,o){t.forEach((i,d)=>{let l=n[d];if(l&&typeof i.sourceId=="string"){s.createdTarget(l)&&ze(r),s.addExisting(i.sourceId,l,e),r.linkedExistingCount++;return}r.failureCount++,r.unidentifiedExistingCount++,i.errors.every(u=>Y(u))&&r.alreadyExistsCount++,r.errorSamples.length<3&&r.errorSamples.push({recordSummary:j(i.payload),messages:o?[...i.errors,o]:i.errors})})}async recordsByNaturalKey(e,t,n,s){let r=this.deps.queryRecords;return r?Re(o=>r(e,o),t,n,s):s.map(()=>{})}async giveFlagsBack(e,t,n,s){let r=this.deps.updateRecords;if(!r||s.size===0||!he[e])return;let o=[];for(let[d,l]of s){let u=n.cleanedRecords[d]?.source;u&&o.push([u,l])}let i=await this.deps.describeFields?.(t,e).catch(()=>{});return ge(e,o,d=>i?.find(l=>l.name===d)?.updateable!==!1,d=>r(t,e,d),n.stopped)}async heldBeforeInsert(e,t,n){let s=this.deps.queryRecords;if(!s)return new Map;let r=o=>s(t,o);return e===X?ye(r,n):ce[e]!==void 0?fe(r,e,n):e===le?me(r,n):new Map}pickUpsertField(e,t,n,s,r){if(s==="off"||!this.deps.upsertRecords)return;let o=e.filter(i=>i.externalId&&t.has(i.name)).sort((i,d)=>i.name.localeCompare(d.name));if(r)return this.tableKeyOfThePage(o,n,r);if(o.length!==0){for(let i of o){let d=new Set,l=!0;for(let u of n){let c=u[i.name];if(typeof c!="string"||c.length===0){l=!1;break}if(d.has(c)){l=!1;break}d.add(c)}if(l)return E.info(`[forge] upsert: using "${i.name}" as external Id (unique across ${n.length} records)`),i.name}E.warn(`[forge] upsert: no externalId candidate is non-null+unique across batch (${o.map(i=>i.name).join(", ")}) \u2014 falling back to insert`)}}tableKeyOfThePage(e,t,n){let s=e.find(o=>n.unique.has(o.name))?.name;if(s===void 0){e.length>0&&E.warn(`[forge] upsert: no externalId candidate is non-null+unique across the rows read (${e.map(o=>o.name).join(", ")}) \u2014 falling back to insert`);return}let r=new Set;for(let o of t){let i=o[s];if(typeof i!="string"||i.length===0||r.has(i)){E.warn(`[forge] upsert: a row of this page leaves "${s}" empty or repeats it \u2014 inserting the page`);return}if(n.sent.has(i)){E.warn(`[forge] upsert: a row of this page repeats a "${s}" an earlier page sent \u2014 inserting the page`);return}r.add(i)}n.sent.size===0&&E.info(`[forge] upsert: using "${s}" as external Id (unique across the rows read of the object)`);for(let o of r)n.sent.add(o);return s}};function j(a){let e=Object.keys(a).slice(0,4),t=[];for(let n of e){let s=a[n],r;if(s===null)r="null";else if(s===void 0)r="undefined";else if(typeof s=="string")r=s.length>30?s.slice(0,30)+"\u2026":s;else if(typeof s=="object")try{let o=JSON.stringify(s);r=o.length>30?o.slice(0,30)+"\u2026":o}catch{r="<unserializable>"}else r=String(s);t.push(`${n}=${r}`)}return t.join(" ")||"(empty)"}export{L as a,M as b,Pt as c,ae as d,dt as e,lt as f,pt as g,yt as h,Ft as i,Ge as j,j as k};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-QAPVKPEC.mjs";import"./chunk-Q3DY7TO2.mjs";import"./chunk-3XG25GTF.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-54HYHHVL.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-WSUKC2U3.mjs";import"./chunk-JFNLKHY6.mjs";import"./chunk-VZVICK7Q.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-7PY3VQP3.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-HFUDCNU5.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-L4INJ5TZ.mjs";import"./chunk-KIMQQ6JQ.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-ZUTUYBNW.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{h as ACTIVE_DUPLICATE_RULES_SOQL,a as FORMULAS_BOUND,c as FORMULAS_IN_COMPOSITES_BOUND,b as FORMULA_REQUESTS_BOUND,o as TargetGapReader,i as bypassesOf,j as callsEstimateOf,f as fieldLabelsSoql,p as gapAnsweredBy,d as gapFieldOf,r as gapLines,q as gapsWithAnswers,l as readActiveValidationRules,m as readValidationRuleBypasses,k as toolingQueriesOver,n as toolingValidationRules,g as validationFormulaSoql,e as validationRulesSoql};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a as b}from"./chunk-YGJF55VJ.mjs";import"./chunk-JESRFE2Z.mjs";import{a}from"./chunk-CBL42DUU.mjs";import"./chunk-MKTXJCXN.mjs";import"./chunk-RCYEBY42.mjs";import"./chunk-AUS6NFLZ.mjs";import"./chunk-DBBPDSFN.mjs";import"./chunk-GBGHJTPC.mjs";import"./chunk-YMDFF657.mjs";import"./chunk-7WSLT5VX.mjs";import"./chunk-YT22LMF7.mjs";import"./chunk-ZXFL2MSN.mjs";import"./chunk-PE435FVH.mjs";import"./chunk-PWVDNN2C.mjs";import"./chunk-6VSZNZHH.mjs";import"./chunk-XCA5AONB.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-WB2RIVO3.mjs";import"./chunk-ISSP2FZ5.mjs";import"./chunk-XU25YA46.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-IVZJSDJD.mjs";import"./chunk-VZT4E2OJ.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-O2PUGRNW.mjs";import"./chunk-7SDZR6SR.mjs";import"./chunk-T63U4OZJ.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-54HYHHVL.mjs";import"./chunk-QIRO4HTE.mjs";import"./chunk-3SKLBRPL.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-SAMWHL22.mjs";import"./chunk-6KP6WETK.mjs";import"./chunk-4JKR4PTZ.mjs";import"./chunk-J24TIGSI.mjs";import"./chunk-HKUWHVI7.mjs";import"./chunk-VPDEJGPS.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-PBE44M2Y.mjs";import"./chunk-ZUOPC4W2.mjs";import"./chunk-JQZTMFO7.mjs";import"./chunk-JFNLKHY6.mjs";import"./chunk-VZVICK7Q.mjs";import"./chunk-PPGDAUEQ.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-7PY3VQP3.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-HFUDCNU5.mjs";import"./chunk-XZISAZA6.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-L4INJ5TZ.mjs";import"./chunk-KIMQQ6JQ.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-ZUTUYBNW.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-ICIYL45C.mjs";import"./chunk-PR74GYVI.mjs";import"./chunk-TMA34QMA.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as objectsWrittenBy,b as previewCheckpoint};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a,b,c,d,e,f,g,h,i,j,k,l}from"./chunk-5K2I2DMP.mjs";import"./chunk-7WSLT5VX.mjs";import"./chunk-YT22LMF7.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-SAMWHL22.mjs";import"./chunk-4JKR4PTZ.mjs";import"./chunk-J24TIGSI.mjs";import"./chunk-XZISAZA6.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-L4INJ5TZ.mjs";import"./chunk-KIMQQ6JQ.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-ZUTUYBNW.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-ICIYL45C.mjs";import"./chunk-PR74GYVI.mjs";import"./chunk-TMA34QMA.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{b as ARCHIVE_CHUNK_BYTES,a as ARCHIVE_EXTENSION,f as CheckpointExportError,d as archiveKeyText,h as exportCheckpointArchive,j as importCheckpointArchive,l as importReceivedArchive,c as newArchiveKey,e as parseArchiveKey,g as portableCheckpointOf,i as readArchiveHeader,k as receivedStoreRootOf};
@@ -0,0 +1,8 @@
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{closeSync as D,fstatSync as J,openSync as W,readSync as $,writeSync as G}from"node:fs";function at(a){let e=W(a,"a+"),t=J(e).size;return{size:()=>t,append:n=>{let i=Buffer.from(n,"utf8"),r=0;for(;r<i.length;)r+=G(e,i,r);t+=i.length},read:(n,i)=>{let r=Buffer.alloc(i),s=0;for(;s<i;){let o=$(e,r,s,i-s,n+s);if(o===0)break;s+=o}return r.subarray(0,s)},close:()=>D(e)}}function j(a,e){return e===void 0?a:`${a}/${e}`}var E=/^[A-Za-z][A-Za-z0-9]*$/,T=/^[0-9a-f]{64}$/,K=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function M(a){if(typeof a!="object"||a===null)return;let{objectApiName:e,ids:t,sha256:n,readAt:i,query:r}=a;if(typeof e!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,79}$/.test(e)||!Array.isArray(t)||!t.every(o=>typeof o=="string"&&K.test(o))||typeof n!="string"||!T.test(n)||typeof i!="string"||!Number.isFinite(Date.parse(i)))return;let s;if(typeof r=="object"&&r!==null){let{where:o,orderBy:c,limit:u}=r;s={...typeof o=="string"?{where:o}:{},...typeof c=="string"?{orderBy:c}:{},...typeof u=="number"&&Number.isInteger(u)?{limit:u}:{}}}return{objectApiName:e,ids:t,sha256:n,readAt:i,...s?{query:s}:{}}}var y=1,k=2,v=3,S=4,H={created:y,existing:k,updated:v},P={[y]:"created",[k]:"existing",[v]:"updated"},_={[y]:"c",[k]:"e",[v]:"u",[S]:"i"},N={c:y,e:k,u:v,i:S},Y="x",Z="a",q="j",z="d",R="n",O="t",U="found",V="found-owed";function dt(a,e,t,n){return JSON.stringify([z,a,e,t,n])}function ct(a){if(!a.startsWith(`["${z}"`))return;let e;try{e=JSON.parse(a)}catch{return}if(!Array.isArray(e))return;let[,,,t,n]=e;if(!(typeof t!="string"||!Number.isFinite(Date.parse(t)))&&!(typeof n!="string"||!Number.isFinite(Date.parse(n))))return{orgAt:t,at:n}}function Q(a,e=!1){return JSON.stringify([e?"w":"o",a.objectApiName,a.newId,a.sourceId??"",a.fieldName,a.sourceRefId,a.insertOnly?1:0])}var X=1024*1024,tt=1024*1024,et=2e4,nt=2e4,it=.6,rt=3;function l(a){let e=2166136261;for(let t=0;t<a.length;t++)e^=a.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function p(a){let e=2538058380;for(let t=0;t<a.length;t++)e=Math.imul(e^a.charCodeAt(t),1540483477),e^=e>>>15;return e>>>0}var x=class{constructor(e){this.keyAt=e}keyAt;capacity=1024;used=0;h1=new Uint32Array(this.capacity);h2=new Uint32Array(this.capacity);at=new Float64Array(this.capacity);len=new Uint16Array(this.capacity);code=new Uint8Array(this.capacity);get size(){return this.used}get slots(){return this.capacity}find(e,t,n,i){let r=this.capacity-1,s=n&r;for(;;){let o=this.at[s];if(o===0)return~s;if(this.h1[s]===t&&this.h2[s]===n&&(i===o-1||this.keyAt(o-1,this.len[s])===e))return s;s=s+1&r}}offsetOf(e){return this.at[e]-1}lengthOf(e){return this.len[e]}codeOf(e){return this.code[e]}put(e,t,n,i,r,s){let o=e;e<0&&(this.used+1>this.capacity*it?(this.grow(),o=this.freeSlotFor(n)):o=~e,this.used++,this.h1[o]=t,this.h2[o]=n),this.at[o]=i+1,this.len[o]=r,this.code[o]=s}freeSlotFor(e){let t=this.capacity-1,n=e&t;for(;this.at[n]!==0;)n=n+1&t;return n}grow(){let{h1:e,h2:t,at:n,len:i,code:r}=this;this.capacity*=2,this.h1=new Uint32Array(this.capacity),this.h2=new Uint32Array(this.capacity),this.at=new Float64Array(this.capacity),this.len=new Uint16Array(this.capacity),this.code=new Uint8Array(this.capacity);for(let s=0;s<n.length;s++){if(n[s]===0)continue;let o=this.freeSlotFor(t[s]);this.h1[o]=e[s],this.h2[o]=t[s],this.at[o]=n[s],this.len[o]=i[s],this.code[o]=r[s]}}};function F(a){return a?a[0]==="p"&&a.length>=3?B(String(a[1]),String(a[2])):a[0]==="g"&&a.length>=3?C(String(a[2])):a[0]===O&&a.length>=2?I(String(a[1])):"":""}function I(a){return`t\0${a}`}function B(a,e){return`p\0${a}\0${e}`}function C(a){return`g\0${a}`}function*st(a){let e=a.size(),t=0,n=Buffer.alloc(0),i=0;for(;t<e;){let r=a.read(t,Math.min(tt,e-t));if(r.length===0)break;t+=r.length;let s=n.length>0?Buffer.concat([n,r]):r,o=0;for(;;){let c=s.indexOf(10,o);if(c<0)break;c>o&&(yield{offset:i+o,length:c-o,text:s.toString("utf8",o,c)}),o=c+1}n=s.subarray(o),i+=o}}var L=class a{constructor(e){this.file=e;this.index=new x((t,n)=>this.idOfLine(t,n)),this.marks=new x((t,n)=>F(m(this.lineAt(t,n)))),this.createdTargets=new x((t,n)=>{let i=m(this.lineAt(t,n));return i?A(String(i[2]??"")):""})}file;index;cache=new Map;pending=[];pendingBytes=0;flushQueued=!1;partStart=Number.POSITIVE_INFINITY;parts=0;mappedCount=0;counts=new Map;earlierByObject=new Map;earlierPastCheckpoint=new Map;checkpointsByObject=new Map;owedCount=0;statuses=new Map;given=new Map;marks;createdTargets;createdUnattributedKeys=new Set;readsHeld=[];withTheirRecordMarked=0;callsSent=0;foundAfterStop=new Set;foundOwingUntold=new Set;plan;rootsNamed;static open(e){let t=new a(e);return t.readWhatIsThere(),t}get partCount(){return this.parts}get resumes(){return this.checkpointsByObject.size>0||this.earlierByObject.size>0||this.owedCount>0}get earlierMapped(){return this.partStart===Number.POSITIVE_INFINITY?this.mappedCount:this.mappedBeforePart}mappedBeforePart=0;beginPart(e){this.flush(),this.mappedBeforePart=this.mappedCount,this.withTheirRecordMarked=0,this.partStart=this.file.size(),this.write({part:{n:this.parts,startedAt:e.toISOString()}}),this.parts++,this.flush()}nameSamplePlan(e){if(!T.test(e.sha256))throw new Error("Not the SHA-256 of a plan.");this.write({sample:{dir:e.dir,sha256:e.sha256}}),this.plan={dir:e.dir,sha256:e.sha256},this.flush()}get samplePlan(){return this.plan?{...this.plan}:void 0}nameRoots(e){let t=M(e);if(!t)throw new Error("Not the roots of a clone from records.");this.write({roots:t}),this.rootsNamed=t,this.flush()}get roots(){return this.rootsNamed?{...this.rootsNamed,ids:[...this.rootsNamed.ids]}:void 0}setMapping(e,t,n,i){let r=H[e],s=l(t),o=p(t),c=this.cache.get(t),u=this.index.find(t,s,o,c?.at),g=u>=0&&this.index.codeOf(u)!==S;g&&this.uncount(t,u,c);let d=JSON.stringify([_[r],t,n,i??""]),f=this.write(d);if(this.index.put(u,s,o,f,Buffer.byteLength(d),r),r===y&&this.indexCreated(n,f,Buffer.byteLength(d)),g||this.mappedCount++,i){let h=this.countsOf(i);r===y?h.created++:r===k?h.linked++:h.updated++}this.remember(t,{at:f,code:r,targetId:n,objectApiName:i??""})}uncount(e,t,n){let i=this.index.offsetOf(t);if(i<this.partStart)return;let r=this.index.codeOf(t),s=n?.at===i?n:this.recordAt(e,t),o=s?.objectApiName?this.counts.get(s.objectApiName):void 0;o&&(r===y?o.created--:r===k?o.linked--:o.updated--)}countsOf(e){let t=this.counts.get(e);return t||(t={created:0,linked:0,updated:0},this.counts.set(e,t)),t}mapping(e){let t=this.lookUp(e);if(!(!t||t.code===S))return{kind:P[t.code],sourceId:e,targetId:t.targetId,...t.objectApiName?{objectApiName:t.objectApiName}:{},earlier:t.at<this.partStart}}createdTarget(e){let t=A(e);if(this.createdUnattributedKeys.has(t))return!0;if(this.createdTargets.size===0)return!1;let n=this.createdTargets.find(t,l(t),p(t));if(n<0)return!1;let i=this.createdTargets.offsetOf(n),r=m(this.lineAt(i,this.createdTargets.lengthOf(n)));if(!r)return!1;let s=String(r[1]),o=this.index.find(s,l(s),p(s));return o>=0&&this.index.offsetOf(o)===i&&this.index.codeOf(o)===y}indexCreated(e,t,n){let i=A(e);if(!i)return;let r=l(i),s=p(i);this.createdTargets.put(this.createdTargets.find(i,r,s),r,s,t,n,y)}targetOf(e){let t=this.lookUp(e);return t&&t.code!==S?t.targetId:void 0}get mappedSize(){return this.mappedCount}countsByObject(){let e=[];for(let[t,{created:n,linked:i,updated:r}]of this.counts)n+i+r!==0&&e.push(r>0?{objectApiName:t,created:n,linked:i,updated:r}:{objectApiName:t,created:n,linked:i});return e}linkedToCreatedCount(){let e=0;for(let d of this.counts.values())e+=d.linked;if(e===0)return 0;let t=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart,n=(d,f)=>{let h=m(this.lineAt(d,f));return h?String(h[2]).slice(0,15):""},i=(d,f)=>{if(d.offset<t)return;let h=N[String(f[0])];if(h===void 0||h===S||!f[3])return;let b=String(f[1]),w=this.index.find(b,l(b),p(b),d.offset);return w>=0&&this.index.offsetOf(w)===d.offset?h:void 0},r=(d,f,h)=>{let b=l(f),w=p(f);d.put(d.find(f,b,w),b,w,h.offset,h.length,0)},s=(d,f)=>d.size>0&&d.find(f,l(f),p(f))>=0,o=new x(n);for(let d of this.lines()){if(!d.text.startsWith('["'))continue;let f=m(d.text);!f||i(d,f)!==k||this.markedWithTheirRecord(String(f[1]))||r(o,String(f[2]).slice(0,15),d)}if(o.size===0)return 0;let c=new x(n),u=new Set;for(let d of this.lines()){if(!d.text.startsWith('["')||d.offset<t)continue;let f=m(d.text);if(!f)continue;if(f[0]===R&&Array.isArray(f[2])){for(let b of f[2]){let w=String(b).slice(0,15);s(o,w)&&u.add(w)}continue}if(i(d,f)!==y)continue;let h=String(f[2]).slice(0,15);s(o,h)&&r(c,h,d)}if(c.size===0&&u.size===0)return 0;let g=0;for(let d of this.lines()){if(!d.text.startsWith('["'))continue;let f=m(d.text);if(!f||i(d,f)!==k||this.markedWithTheirRecord(String(f[1])))continue;let h=String(f[2]).slice(0,15);(s(c,h)||u.has(h))&&g++}return g}earlierRecordsOf(e,t=!1){return(t?this.earlierPastCheckpoint:this.earlierByObject).get(e)??0}*mappings(){for(let e of this.lines()){if(!e.text.startsWith('["'))continue;let t=m(e.text);if(!t)continue;let n=N[String(t[0])];if(n===void 0||n===S)continue;let i=String(t[1]),r=this.index.find(i,l(i),p(i),e.offset);if(r<0||this.index.offsetOf(r)!==e.offset)continue;let s=String(t[3]??"");yield{kind:P[n],sourceId:i,targetId:String(t[2]),...s?{objectApiName:s}:{},earlier:e.offset<this.partStart}}}noteRead(e){this.readsHeld.push(e),this.readsHeld.length>=nt&&this.settleReads()}settleReads(){let e=this.readsHeld;this.readsHeld=[];for(let t of e){let n=l(t),i=p(t),r=this.index.find(t,n,i,this.cache.get(t)?.at);if(r>=0)continue;let s=JSON.stringify([_[S],t]),o=this.write(s);this.index.put(r,n,i,o,Buffer.byteLength(s),S)}}wasRead(e){return this.readsHeld.includes(e)?!0:this.index.find(e,l(e),p(e),this.cache.get(e)?.at)>=0}checkpoint(e,t,n){if(n!==void 0&&!E.test(n))throw new Error(`Not the name of a pass: ${JSON.stringify(n.slice(0,40))}`);this.settleReads(),this.write({at:{object:e,...n!==void 0?{pass:n}:{},...t}}),this.checkpointsByObject.set(j(e,n),{...t}),this.flush()}checkpoints(){return new Map(this.checkpointsByObject)}owe(e,t=!1){this.owedCount++,this.write(Q(e,t))}get owed(){return this.owedCount}*owedPages(e){let t=[];for(let n of this.lines()){if(!n.text.startsWith('["o"')&&!n.text.startsWith('["w"'))continue;let i=m(n.text);if(!i||i.length<7)continue;let[r,s,o,c,u,g,d]=i;t.push({update:{objectApiName:String(s),newId:String(o),sourceId:c?String(c):void 0,fieldName:String(u),sourceRefId:String(g),...d===1?{insertOnly:!0}:{}},toRowWrittenBefore:r==="w"}),t.length>=e&&(yield t,t=[])}t.length>0&&(yield t)}patched(e,t){this.mark(JSON.stringify(["p",e,t]),B(e,t))}wasPatched(e,t){return this.hasMark(B(e,t))}mark(e,t){let n=l(t),i=p(t),r=this.marks.find(t,n,i),s=this.write(e);this.marks.put(r,n,i,s,Buffer.byteLength(e),0)}hasMark(e){return this.marks.size>0&&this.marks.find(e,l(e),p(e))>=0}owedLeftByEarlierParts(){let e=new Set;for(let n of this.lines()){if(n.offset>=this.partStart)break;if(!n.text.startsWith('["p"'))continue;let i=m(n.text);i&&i.length>=3&&e.add(`${String(i[1])}\0${String(i[2])}`)}let t=[];for(let n of this.lines()){if(n.offset>=this.partStart)break;if(!n.text.startsWith('["o"'))continue;let i=m(n.text);if(!i||i.length<7)continue;let[,r,s,o,c,u,g]=i;e.has(`${String(s)}\0${String(c)}`)||t.push({objectApiName:String(r),newId:String(s),sourceId:o?String(o):void 0,fieldName:String(c),sourceRefId:String(u),...g===1?{insertOnly:!0}:{}})}return t}oweStatus(e,t,n){this.write(JSON.stringify(["s",e,t,n])),this.tallyStatus({objectApiName:e,id:t,status:n})}tallyStatus(e){let t=this.statuses.get(e.objectApiName);t||(t={count:0,samples:[]},this.statuses.set(e.objectApiName,t)),t.count++,t.samples.length<rt&&t.samples.push(e)}gaveStatus(e,t){this.statusGiven(t)||(this.mark(JSON.stringify(["g",e,t]),C(t)),this.given.set(e,(this.given.get(e)??0)+1))}statusGiven(e){return this.hasMark(C(e))}statusesOwed(){let e=new Map;for(let[t,n]of this.statuses){let i=n.count-(this.given.get(t)??0);i<=0||e.set(t,{count:i,samples:n.samples.filter(({id:r})=>!this.statusGiven(r))})}return e}*statusLines(){for(let e of this.lines()){if(!e.text.startsWith('["s"'))continue;let t=m(e.text);!t||t.length<4||(yield{objectApiName:String(t[1]),id:String(t[2]),status:String(t[3])})}}withTheirRecord(e){let t=I(e),n=l(t),i=p(t),r=this.marks.find(t,n,i),s=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart;if(r>=0&&this.marks.offsetOf(r)>=s)return;let o=JSON.stringify([O,e]),c=this.write(o);this.marks.put(r,n,i,c,Buffer.byteLength(o),0),this.withTheirRecordMarked++}get withTheirRecordCount(){return this.withTheirRecordMarked}markedWithTheirRecord(e){if(this.withTheirRecordMarked===0)return!1;let t=I(e),n=this.marks.find(t,l(t),p(t)),i=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart;return n>=0&&this.marks.offsetOf(n)>=i}*withTheirRecordIds(){if(this.withTheirRecordMarked!==0)for(let e of this.lines()){if(e.offset<this.partStart||!e.text.startsWith(`["${O}"`))continue;let t=m(e.text);t&&t.length>=2&&(yield String(t[1]))}}sent(e,t,n,i=new Date,r){this.callsSent++;let s=`${Math.max(0,this.parts-1)}.${this.callsSent}`;return this.write(JSON.stringify([Y,s,e,i.toISOString(),t,n.map(({sourceId:o,fingerprint:c,externalKey:u,jobKey:g})=>r!==void 0&&u!==void 0?[o,c,u]:g!==void 0?[o,c,"",g]:[o,c]),n.flatMap(({owes:o},c)=>(o??[]).map(({field:u,sourceRefId:g,insertOnly:d})=>[c,u,g,d?1:0])),...r!==void 0?[r]:[]])),this.flush(),s}answered(e){this.write(JSON.stringify([Z,e]))}jobOpened(e,t){this.write(JSON.stringify([q,e,t])),this.flush()}createdUnattributed(e,t){if(t.length!==0){this.write(JSON.stringify([R,e,[...t]]));for(let n of t)this.createdUnattributedKeys.add(A(n))}}wasFoundAfterStop(e){return this.foundAfterStop.has(e)}owesUntold(e){return this.foundOwingUntold.has(e)}flush(){if(this.pending.length===0)return;let e=this.pending.join("");this.pending=[],this.pendingBytes=0,this.file.append(e)}close(){this.settleReads(),this.flush(),this.file.close()}write(e){let t=typeof e=="string"?e:JSON.stringify(e),n=this.file.size()+this.pendingBytes,i=`${t}
8
+ `;return this.pending.push(i),this.pendingBytes+=Buffer.byteLength(i),this.pendingBytes>=X?this.flush():this.flushQueued||(this.flushQueued=!0,queueMicrotask(()=>{this.flushQueued=!1,this.flush()})),n}lineAt(e,t){return e+t>this.file.size()&&this.flush(),this.file.read(e,t).toString("utf8")}idOfLine(e,t){let n=m(this.lineAt(e,t));return n?String(n[1]):""}lookUp(e){let t=this.cache.get(e);if(t)return this.cache.delete(e),this.cache.set(e,t),t;let n=this.index.find(e,l(e),p(e));if(n<0)return;let i=this.recordAt(e,n);return i&&this.remember(e,i),i}recordAt(e,t){let n=this.index.offsetOf(t),i=m(this.lineAt(n,this.index.lengthOf(t)));if(!(!i||String(i[1])!==e))return{at:n,code:this.index.codeOf(t),targetId:String(i[2]??""),objectApiName:String(i[3]??"")}}remember(e,t){if(this.cache.delete(e),this.cache.set(e,t),this.cache.size>et){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}}*lines(){this.flush(),yield*st(this.file)}readWhatIsThere(){for(let e of this.lines()){if(e.text.startsWith('["')){let n=m(e.text);n&&this.readRegistration(e,n);continue}let t;try{t=JSON.parse(e.text)}catch{continue}if(!(typeof t!="object"||t===null)){if("part"in t)this.parts++;else if("sample"in t){let n=t.sample;if(typeof n!="object"||n===null)continue;let{dir:i,sha256:r}=n;if(typeof i!="string"||i===""||typeof r!="string"||!T.test(r))continue;this.plan={dir:i,sha256:r}}else if("roots"in t){let n=M(t.roots);n&&(this.rootsNamed=n)}else if("at"in t){let n=t.at;if(typeof n!="object"||n===null)continue;let{object:i,pass:r,lastId:s,read:o,done:c}=n;if(typeof i!="string"||typeof s!="string"||typeof o!="number"||r!==void 0&&(typeof r!="string"||!E.test(r)))continue;this.checkpointsByObject.set(j(i,r),{lastId:s,read:o,...c===!0?{done:c}:{}}),r===void 0&&this.earlierPastCheckpoint.delete(i)}}}}readRegistration(e,t){let n=String(t[0]);if(n==="o"||n==="w"){this.owedCount++;return}if(n==="s"){t.length>=4&&this.tallyStatus({objectApiName:String(t[1]),id:String(t[2]),status:String(t[3])});return}if(n==="p"||n==="g"||n===O){let d=F(t);if(!d)return;let f=l(d),h=p(d),b=this.marks.find(d,f,h);if(n==="g"&&b<0){let w=String(t[1]);this.given.set(w,(this.given.get(w)??0)+1)}this.marks.put(b,f,h,e.offset,e.length,0);return}if(n===R){if(Array.isArray(t[2]))for(let d of t[2])this.createdUnattributedKeys.add(A(String(d)));return}let i=N[n];if(i===void 0)return;let r=String(t[1]);i===y&&(t[4]===U||t[4]===V)&&(this.foundAfterStop.add(r),t[4]===U&&this.foundOwingUntold.add(r));let s=l(r),o=p(r),c=this.index.find(r,s,o),u=c>=0&&this.index.codeOf(c)!==S;if(i===S&&c>=0||(this.index.put(c,s,o,e.offset,e.length,i),i===S))return;i===y&&this.indexCreated(String(t[2]??""),e.offset,e.length),u||this.mappedCount++;let g=String(t[3]??"");g&&(this.earlierByObject.set(g,(this.earlierByObject.get(g)??0)+1),this.earlierPastCheckpoint.set(g,(this.earlierPastCheckpoint.get(g)??0)+1))}};function A(a){return a.slice(0,15)}function m(a){try{let e=JSON.parse(a);return Array.isArray(e)?e:void 0}catch{return}}export{at as a,j as b,M as c,Y as d,Z as e,q as f,z as g,R as h,O as i,U as j,V as k,dt as l,ct as m,Q as n,l as o,p,x as q,st as r,L as s};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as Ce}from"./chunk-GMY5427L.mjs";import{h as Re,i as be,j as Se,k as ke,n as Te,o as Fe}from"./chunk-KYEDBS54.mjs";import{c as Oe}from"./chunk-K2FBZIXY.mjs";import{f as he,i as me,o as we}from"./chunk-G35N4P7D.mjs";import{a as z,k as ie,n as ae,p as de,s as ce,t as ue,u as le}from"./chunk-ZUTYVST5.mjs";import{b as ye,e as ge}from"./chunk-CU2INBND.mjs";import{b as fe,c as q,m as pe}from"./chunk-WIO4XO4F.mjs";import{d as K}from"./chunk-GCOB7K5N.mjs";import{F as se,p as te,r as ne,s as re,t as oe}from"./chunk-A527W53V.mjs";import{b as ee}from"./chunk-CA5NAXSU.mjs";import{Ub as X,ic as B}from"./chunk-TTFDUKUS.mjs";var H=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function b(t){return t.slice(0,15)}var We=class{constructor(e=new Map){this.earlier=e}earlier;written=new Map;refused=new Map;deleted=new Set;ownersRefused=new Set;contactsSentWith=new Map;noteSentWithContact(e,n){this.contactsSentWith.set(b(e),n)}contactSentWith(e){return this.contactsSentWith.get(b(e))}roleLinkedFor(e){this.contactsSentWith.delete(b(e))}get sentWithAContact(){return this.contactsSentWith.size>0}noteOwnerRefused(e){this.ownersRefused.add(b(e))}isOwnerRefused(e){return this.ownersRefused.has(b(e))}noteDeleted(e){for(let n of e)this.deleted.add(b(n))}standing(e){return e!==void 0&&this.deleted.has(b(e))?void 0:e}noteMatched(e,n){this.noteWritten(e,n)}noteWritten(e,n){this.written.set(b(e),n),this.refused.delete(b(e))}noteRefused(e,n){this.written.has(b(e))||this.refused.set(b(e),n)}targetOf(e){return this.standing(this.written.get(b(e)))??this.standing(this.earlier.get(b(e)))}refusedObjectOf(e){if(this.standing(this.earlier.get(b(e)))===void 0)return this.refused.get(b(e))}};function Ae(t,e,n){if(e.length===0||!n.some(o=>!o.master))return;let r={};for(let o of e)r[o]=(r[o]??0)+1;let s=Se(be(n));return{objectApiName:t,rows:e.length,why:r,...s?{predicted:s}:{}}}function Ie(t,e){return q(t,e?.target??[])}function Y(t){switch(t.operation){case"insert":return null;case"upsert":return t.externalIdField??"Id";case"update":case"delete":return"Id"}}function ze(t,e,n,r,s){let o=ge(t,e);for(let i of n)(!(i.fieldApiName in o)||i.overwriteExisting)&&(o[i.fieldApiName]=i.value);if(!r)return o;let a={};for(let i of Object.keys(o))i!=="attributes"&&(r.has(i)||i===s)&&(a[i]=o[i]);return a}function ve(t,e){return`${t} ${e} record${t===1?"":"s"}`}function Ue(t,e,n){let r=a=>e.find(i=>b(i.recordTypeId)===b(a)),s=t;if(!r(t)&&n){let a=n.mappings.find(i=>b(i.sourceId)===b(t));if(!a){let i=n.source.find(c=>b(c.id)===b(t)),y=i?(n.target??[]).filter(c=>c.sobjectType===i.sobjectType&&c.developerName===i.developerName):[];return{unmapped:i?K(i):"",namesakes:y.map(K)}}s=a.targetId}let o=q(e.filter(a=>b(a.recordTypeId)===b(s)),n?.target??[])[0];return o&&!o.available&&!o.master?{unavailable:o}:o?{sent:s,info:o}:{sent:s}}function Ge(t,e,n){if(t?.personAccounts===!1)return!0;if(!n)return!1;let r=e??Te(t?.recordTypes);return r!==void 0&&!n.has(b(r))}function Le(t,e,n){return{group:`parent:${e}:${n}`,reason:`PARENT_REFUSED: the ${n} record its ${e} names was refused in this run.`,say:r=>`PARENT_REFUSED: ${ve(r,t)} held back, not sent: the ${n} record their ${e} names was refused in this run, and written without it they would stand without their ${n}.`}}function Ee(t){let{config:e,records:n,target:r,run:s}=t,o=e.objectApiName,a=Y(e),i=r?.recordTypes??[],y=r?.references??new Set,c={payloads:[],sentAt:[],settled:[],held:[],deferred:[],deferredAcross:[],notes:[],currencies:[],withoutRecordType:new Map},h=new Map,m=new Map,T=(d,l,g,k)=>{c.held.push({index:d,reason:g}),h.delete(d);let I=m.get(l);I?I.count++:m.set(l,{count:1,say:k})},w=e.operation==="insert"||e.operation==="upsert",W=w&&i.some(d=>!d.master),f=new Map;s&&w&&s.sources.forEach((d,l)=>{let g=d?.Id;typeof g=="string"&&H.test(g)&&f.set(b(g),l)});let v=new Set([...s&&w?s.later??[]:[]].map(d=>d.toLowerCase())),R=new Set(v.size===0?[]:(r?.fields??[]).flatMap(d=>d.isReference&&(d.referenceTo??[]).some(l=>v.has(l.toLowerCase()))&&!(d.nillable===!1&&d.defaultedOnCreate!==!0)?[d.name]:[]));n.forEach((d,l)=>{let g=ze(d,e.fieldMappings,e.addOnFields,r?.creatable??null,a);if(e.operation==="delete"){h.set(l,{payload:g,settled:new Set});return}let k=new Set;if(s)for(let p of Object.keys(g)){let C=g[p];if(p==="RecordTypeId"||!y.has(p)||typeof C!="string"||!H.test(C))continue;if(f.has(b(C))){delete g[p],c.deferred.push({index:l,field:p,parent:C});continue}let _=s.links.targetOf(C);if(_){g[p]=_,k.add(p);continue}let M=s.links.refusedObjectOf(C);if(M===void 0){R.has(p)&&(delete g[p],c.deferredAcross.push({index:l,field:p,parent:C}));continue}let G=Le(o,p,M);T(l,G.group,G.reason,G.say);return}let I=g.RecordTypeId,E,j=Oe(I);if(j)delete g.RecordTypeId;else if(typeof I=="string"&&H.test(I)){let p=Ue(I,i,s?.recordTypes);if("unmapped"in p){let C=p.unmapped,_=p.namesakes.length>0?` The target org's ${p.namesakes.join(" and ")} carries its DeveloperName under another namespace, and a record type is mapped to one of the same namespace only.`:"";T(l,`unmapped:${C}`,"RECORD_TYPE_UNMAPPED: its record type has no counterpart in the target org.",M=>`RECORD_TYPE_UNMAPPED: ${ve(M,o)} held back, not sent: `+(C?`their record type ${C} has no active ${o} record type of that API name in the target org.${_} Create or activate record type ${C} on ${o} in the target org.`:"their record type is inactive in the source org, and has no counterpart in the target org."));return}if("unavailable"in p){let C=p.unavailable;T(l,`unavailable:${C.recordTypeId}`,`RECORD_TYPE_UNAVAILABLE: record type ${C.developerName} is closed to the running user in the target org.`,_=>`${pe({objectApiName:o,recordTypeId:C.recordTypeId,developerName:C.developerName,name:C.name,inactive:!C.active,recordCount:_})} Held back, not sent.`);return}g.RecordTypeId=p.sent,E=p.sent,p.info&&k.add("RecordTypeId")}let $=s?.sources[l]??d;if(re($)){let p=oe($,Ge(r,E,s?.recordTypes?.personTypes));for(let C of Object.keys(g))B(o,C,p)&&delete g[C]}else for(let p of Object.keys(g))B(o,p,"business")&&delete g[p];W&&!("RecordTypeId"in g)&&c.withoutRecordType.set(l,j?"masterInSource":"notRead"),h.set(l,{payload:g,settled:k})});let L=!0;for(;L;){L=!1;for(let{index:d,field:l,parent:g}of c.deferred){let k=f.get(b(g));if(!h.has(d)||k===void 0||h.has(k)||s?.links.targetOf(g)!==void 0)continue;let I=Le(o,l,o);T(d,I.group,I.reason,I.say),L=!0}}c.deferred=c.deferred.filter(({index:d})=>h.has(d)),c.deferredAcross=c.deferredAcross.filter(({index:d})=>h.has(d));for(let d of[...c.withoutRecordType.keys()])h.has(d)||c.withoutRecordType.delete(d);c.held.sort((d,l)=>d.index-l.index);let S=e.operation==="delete"?void 0:s?.currencies,O=r?.creatable.has(z)===!0,u=!O&&(s?.currencyChangesById?.size??0)>0&&r?.fields?.some(d=>d.name===z)===!0,F=S&&(O||u)?ae(r?.fields??[]):void 0,P=[...r?.references??[]],A=new le;for(let[d,{payload:l,settled:g}]of[...h].sort(([k],[I])=>k-I)){for(let k of X(o,l))delete l[k];if(S&&F){let k=s?.sources[d]??n[d],I=k?.[z],E=O?de(l,{read:I,currencyFields:F,ratesOn:ie(o,k)},S):ue(l,{read:I,parent:k?ce(o,k,P,$=>s?.currencyChangesById?.get($)):void 0,currencyFields:F},S);A.add(o,E);let j=k?.Id;E&&typeof j=="string"&&s?.currencyChangesById?.set(j,E)}c.payloads.push(l),c.sentAt.push(d),c.settled.push(g)}return c.notes=[...m.values()].map(({count:d,say:l})=>l(d)),c.currencies=A.list(),c}function V(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}function Be(t){let e=V(t.length),n=V(t.precision),r=V(t.digits);return{name:t.name,queryable:t.queryable!==!1,createable:t.createable===!0,isReference:t.type==="reference",...t.type!==void 0?{type:t.type}:{},...e!==void 0?{length:e}:{},...t.nillable!==void 0?{nillable:t.nillable}:{},...t.defaultedOnCreate!==void 0?{defaultedOnCreate:t.defaultedOnCreate}:{},...t.calculated===!0?{calculated:!0}:{},...n!==void 0?{precision:n}:{},...n!==void 0&&typeof t.scale=="number"&&t.scale>=0?{scale:t.scale}:{},...r!==void 0?{digits:r}:{},...t.unique===!0?{unique:!0}:{},...t.referenceTo?{referenceTo:[...t.referenceTo]}:{}}}function yt(t){let e=t.fields.filter(r=>r.createable===!0),n=t.fields.some(r=>typeof r.idLookup=="boolean");return{creatable:new Set(e.map(r=>r.name)),references:new Set(e.filter(r=>r.type==="reference").map(r=>r.name)),...typeof t.createable=="boolean"?{objectCreateable:t.createable}:{},...typeof t.updateable=="boolean"?{objectUpdateable:t.updateable}:{},recordTypes:fe(t.recordTypeInfos),...t.name===te?{personAccounts:t.fields.some(r=>r.name===ne)}:{},fields:t.fields.map(Be),...n?{upsertKeys:new Set(t.fields.filter(r=>r.externalId===!0||r.idLookup===!0).map(r=>r.name.toLowerCase()))}:{}}}function Z(t,e,n){switch(e){case"notInTarget":return`Object is not in the target org, or the user the run writes as cannot see it: ${t}. None of its records were sent.`;case"notCreateable":return`Object is not createable on target org: the user the run writes as may not create ${t} records there. None of its records were sent.`;case"notUpdateable":return`Object is not updateable on target org: the user the run writes as may not edit ${t} records there. None of its records were sent.`;case"unread":return`The target org did not describe ${t}${n?` (${n})`:""}, so what it takes could not be told and none of its records were sent.`;case"notAKey":return`The upsert of ${t} matches on ${n??"a field"}, which the target org does not match an upsert on: it takes an External ID field, the Id, or a field its describe marks idLookup. None of its records were sent.`}}function gt(t,e){let n=t.externalIdField?.trim().toLowerCase();if(t.operation!=="upsert"||!n)return t;let r=e.fields?.find(s=>s.name.toLowerCase()===n)?.name;return r===void 0?t:{...t,externalIdField:r}}function ht(t,e){if(t.operation==="delete"||t.query===void 0)return t;let n=Ce(t.query);if(!("list"in n))return t;let r=new Set([...n.list,t.externalIdField??"",...t.fieldMappings.filter(o=>ye.has(o.type)).map(o=>o.sourceField)].map(o=>o.toLowerCase())),s=[...e.creatable].filter(o=>!r.has(o.toLowerCase()));return s.length===0?t:{...t,excludedFields:[...new Set([...t.excludedFields??[],...s])]}}async function Pe(t,e,n,r){let s;try{s=await t(e)}catch(c){if(n==="delete")return{notAsked:!0};let h=Fe(c)?"notInTarget":"unread";return{refused:{why:h,message:Z(e,h,ee(c))}}}let o=n==="insert"||n==="upsert",a=n==="update"||n==="upsert",i=o&&s.objectCreateable===!1?"notCreateable":a&&s.objectUpdateable===!1?"notUpdateable":void 0;if(i)return{refused:{why:i,message:Z(e,i)},target:s};let y=r?.trim()||"Id";return n==="upsert"&&s.upsertKeys&&!s.upsertKeys.has(y.toLowerCase())?{refused:{why:"notAKey",message:Z(e,"notAKey",y),key:y},target:s}:{target:s}}function Rt(t){return t.keepContactPoints===!0?void 0:new Re}function Ot(t,e){if(!t)return e?{neutralized:!1,fields:[],values:0}:void 0;let n=t.report();return n.values>0?n:void 0}function xe(t,e,n,r,s){let o=s?n.filter(i=>i.name!==s):n,a=t.forObject(e,o);if(a)for(let i of r)a(i)}var x=class extends Error{constructor(n,r=[],s=[],o=[],a){super(r.length===0?`The write of ${n} was cancelled before any of its records was written.`:`The write of ${n} was cancelled after ${r.length} of its records were sent.`);this.objectApiName=n;this.written=r;this.notes=s;this.lookupsLeftOut=o;this.writtenWithoutFields=a;this.name="WriteCancelledError"}objectApiName;written;notes;lookupsLeftOut;writtenWithoutFields};var Ne=class{deps;constructor(e){this.deps=e}async sync(e,n,r){let{outcomes:s,notes:o,currencies:a,lookupsLeftOut:i,writtenWithoutFields:y}=await this.write(e,n,r);return Je(Qe(e.objectApiName,e.operation,s,o,i,y),a)}updateRecords(e,n,r){return this.executeOperation(e,"update",n,r)}async write(e,n,r){let s=null;if(this.deps.describeTargetFields){let u=await Pe(this.deps.describeTargetFields,e.objectApiName,e.operation,e.externalIdField);if("refused"in u){let F=n.map(()=>({success:!1,errors:[u.refused.message]}));return r&&$e(e,F,r),{outcomes:F,notes:[],currencies:[],lookupsLeftOut:[]}}"target"in u&&u.target.creatable.size>0&&(s=u.target)}let o=Ee({config:e,records:n,target:s,run:r}),a=r?r.contactPoints:this.deps.contactPoints;a&&s?.fields&&xe(a,e.objectApiName,s.fields,o.payloads,e.externalIdField);let i=He(o.payloads,o.settled,r),y=new Map(o.held.map(({index:u,reason:F})=>[u,F])),c=u=>{let F=[],P=0;for(let A=0;A<n.length;A++){let d=y.get(A);if(d!==void 0){F.push({success:!1,errors:[d],heldBack:!0});continue}if(P>=u.length)break;F.push(u[P++])}return F},h,m=o.sentAt.filter(u=>u<(r?.standardFirst??0)).length,T=u=>this.executeOperation(e.objectApiName,e.operation,u,e.batchSize,e.externalIdField);try{h=o.payloads.length===0&&n.length>0?[]:m>0&&m<o.payloads.length?await Ve(e.objectApiName,T,o.payloads.slice(0,m),o.payloads.slice(m)):await T(o.payloads)}catch(u){if(!(u instanceof x))throw u;let F=je(i,u.written),P=c(u.written);throw De(e,o.withoutRecordType,P,s,r),new x(e.objectApiName,P,[...o.notes,...u.notes],[...F?[F]:[],...u.lookupsLeftOut,...Q(U([...o.deferred,...o.deferredAcross],P))],u.writtenWithoutFields)}let w=await this.retryRefused(e,o.payloads,h,s?.references??null,o.settled);if(r)for(let u of w.ownersRefused)r.links.noteOwnerRefused(u);let W=c(w.outcomes);De(e,o.withoutRecordType,W,s,r);let f=je(i,w.outcomes),v=[...o.notes,...w.notes],R=[...f?[f]:[],...w.lookupsLeftOut],{writtenWithoutFields:L}=w,S=U(o.deferredAcross,W),O=0;if(w.cancelled)throw new x(e.objectApiName,W,v,[...R,...Q([...U(o.deferred,W),...S])],L);if(r){$e(e,W,r),Ze(e,o.payloads,w.outcomes,r.links);let u=await this.setLookups(e,U(o.deferred,W),r.links,!1);if(R.push(...u.leftOut),O=u.unset,u.cancelled)throw new x(e.objectApiName,W,v,[...R,...Q(S)],L)}return{outcomes:W,notes:v,currencies:o.currencies,lookupsLeftOut:R,...L?{writtenWithoutFields:L}:{},...S.length>0?{lookupsToSet:S}:{},...O>0?{lookupsUnset:O}:{}}}async setLookups(e,n,r,s){let o=e.objectApiName,a=new Map,i=new Map,y=new D;for(let{id:f,field:v,parent:R}of n){let L=r.targetOf(R),S=L!==void 0?a:s&&r.refusedObjectOf(R)===void 0?i:void 0;if(!S){y.add(f,v);continue}let O=S.get(f)??{Id:f};O[v]=L??R,S.set(f,O)}let c=new D,h=new D,m=new D,T=new D,w=!1;for(let f of[[...a.values()],[...i.values()]]){if(f.length===0)continue;if(w){for(let R of f)T.addRow(R);continue}let v;try{v=await this.executeOperation(o,"update",f,e.batchSize)}catch(R){if(!(R instanceof x)){let L=R instanceof Error?R.message:String(R);for(let S of f)m.addRow(S,L);continue}v=R.written,w=!0}f.forEach((R,L)=>{let S=v[L];S===void 0?T.addRow(R):S.success?c.addRow(R):S.errors.some(O=>J(O))?h.addRow(R):m.addRow(R,S.errors[0])})}let W=[y,h,m,T];return{...c.records>0?{set:{records:c.records,fields:c.fields()}}:{},leftOut:[y.leftOut("parentRefused"),h.leftOut("notInTarget"),m.leftOut("notSet"),T.leftOut("notReached")].flatMap(f=>f?[f]:[]),unset:new Set(W.flatMap(f=>[...f.recordIds])).size,cancelled:w}}async retryRefused(e,n,r,s,o){let a=Y(e)??void 0,i=[...r],y=[...n],c=n.map(()=>new Set),h=n.map(()=>[]),m=n.map(()=>[]),T=[],w,W=new Set;for(let S=0;S<2&&!w;S++){let O=[],u=[],F=[];if(i.forEach((A,d)=>{if(A.success)return;let l=y[d],g=o[d]??new Set;if(A.errors.some(E=>J(E))){let E=n[d]?.[N];if(typeof E=="string"&&!g.has(N)&&(A.errorDetails??[]).some(p=>J(p.statusCode)&&p.fields.includes(N))&&W.add(E),c[d].has("lookup")||!s||s.size===0)return;let j={},$=!1;for(let p of Object.keys(l)){if(s.has(p)&&!g.has(p)&&l[p]!==null&&l[p]!==void 0){$=!0;continue}j[p]=l[p]}if(!$)return;O.push(d),u.push(j),F.push(null);return}if(c[d].has("fields"))return;let k=he(A.errorDetails,l,a);if(!k||k.some(({field:E})=>g.has(E)))return;let I=new Set(k.map(({field:E})=>E));O.push(d),u.push(Object.fromEntries(Object.entries(l).filter(([E])=>!I.has(E)))),F.push(k)}),O.length===0)break;let P;try{P=await this.executeOperation(e.objectApiName,e.operation,u,e.batchSize,e.externalIdField)}catch(A){if(!(A instanceof x)){T.push(...Ye(O,y,u,F,A));break}P=A.written,w=A}P.forEach((A,d)=>{let l=O[d],g=F[d];c[l].add(g===null?"lookup":"fields"),g===null?h[l].push(...Object.keys(y[l]).filter(k=>!(k in u[d]))):m[l].push(...g),y[l]=u[d],i[l]=A})}let f=new Set,v=0,R,L=new Set(W);return i.forEach((S,O)=>{if(!(!S.success||c[O].size===0)){if(h[O].length>0){v++;for(let F of h[O])f.add(F);let u=n[O]?.[N];typeof u=="string"&&h[O].length===1&&h[O][0]===N&&L.add(u)}m[O].length>0&&(R=me(R,{rows:1,fields:m[O].map(u=>({...u,rows:1}))}))}}),{outcomes:i,notes:[...T,...w?.notes??[]],...R?{writtenWithoutFields:R}:{},cancelled:w!==void 0,ownersRefused:[...L],lookupsLeftOut:[...v>0?[{records:v,fields:[...f].sort(),reason:"notInTarget"}]:[],...w?.lookupsLeftOut??[]]}}async executeOperation(e,n,r,s,o){if(this.deps.crudFlsGuard){let a=r.length>0?Object.keys(r[0]):[],i=await this.deps.crudFlsGuard.checkCrudAndFls(e,n,a);if(!i.allowed)throw new Error(`CRUD/FLS check failed for ${n} on ${e}: ${i.reason}`)}switch(n){case"insert":return this.deps.insert(e,r,s);case"update":return this.deps.update(e,r,s);case"upsert":return this.deps.upsert(e,o??"Id",r,s);case"delete":{let a=r.map(i=>i.Id).filter(i=>typeof i=="string");return this.deps.delete(e,a,s)}}}},Ke=["INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY","INVALID_CROSS_REFERENCE_KEY"],qe=/cross[- ]reference id|r[ée]f[ée]rence crois[ée]e/i;function J(t){return Ke.some(e=>t.includes(e))||qe.test(t)}var N="OwnerId";function He(t,e,n){let r=new Set;return n&&t.forEach((s,o)=>{let a=s[N];typeof a!="string"||e[o]?.has(N)||n.links.isOwnerRefused(a)&&(delete s[N],r.add(o))}),r}function je(t,e){let n=0;for(let r of t)e[r]?.success&&n++;if(n!==0)return{records:n,fields:[N],reason:"ownerRefusedEarlier"}}function Ye(t,e,n,r,s){let o=s instanceof Error?s.message:String(s),a=new Set,i=new Set,y=0;return r.forEach((c,h)=>{if(c===null){y++;let m=n[h];for(let T of Object.keys(e[t[h]]))T in m||a.add(T)}else for(let{field:m}of c)i.add(m)}),[...y>0?[`${y} record(s) the target refused for a lookup it does not have could not be written again without ${[...a].sort().join(", ")}: ${o}`]:[],...i.size>0?[`${t.length-y} record(s) the target refused on fields it named could not be written again without ${[...i].sort().join(", ")}: ${o}`]:[]]}var D=class{ids=new Set;named=new Set;said;add(e,n){this.ids.add(e),this.named.add(n)}addRow(e,n){let r=String(e.Id);for(let s of Object.keys(e))s!=="Id"&&this.add(r,s);n!==void 0&&n!==""&&(this.said??=n)}get records(){return this.ids.size}get recordIds(){return this.ids}fields(){return[...this.named].sort()}leftOut(e){if(this.ids.size!==0)return{records:this.ids.size,fields:this.fields(),reason:e,...this.said!==void 0?{refusal:this.said}:{}}}};function U(t,e){return t.flatMap(({index:n,field:r,parent:s})=>{let o=e[n];return o?.success&&typeof o.id=="string"&&o.id!==""?[{id:o.id,field:r,parent:s}]:[]})}function vt(t){return new Set(t.map(({id:e})=>e)).size}function Q(t){let e=new D;for(let{id:r,field:s}of t)e.add(r,s);let n=e.leftOut("notReached");return n?[n]:[]}function Me(t,e){if(!(e.success||t!=="insert"&&t!=="upsert"))return e.existingId!==void 0&&e.existingId!==""?e.existingId:void 0}async function Ve(t,e,n,r){let s=await e(n);try{return[...s,...await e(r)]}catch(o){throw o instanceof x?new x(t,[...s,...o.written],o.notes,o.lookupsLeftOut,o.writtenWithoutFields):o}}function De(t,e,n,r,s){if(!s?.createdWithoutRecordType||e.size===0)return;let o=[],a=[];for(let[c,h]of e){let m=n[c];!m?.success||typeof m.id!="string"||m.id===""||t.operation!=="insert"&&m.created!==!0||(o.push(h),a.length<ke&&a.push(m.id))}let i=Ie(s.recordTypesUnderTheLease??r?.recordTypes??[],s.recordTypes),y=Ae(t.objectApiName,o,i);y&&s.createdWithoutRecordType.set(t.objectApiName,{given:y,types:i,ids:a})}function Ze(t,e,n,r){t.objectApiName==="Opportunity"&&(t.operation!=="insert"&&t.operation!=="upsert"||e.forEach((s,o)=>{let a=n[o],i=s[se];!a?.success||typeof a.id!="string"||a.id===""||t.operation!=="insert"&&a.created!==!0||typeof i=="string"&&i!==""&&r.noteSentWithContact(a.id,i)}))}function $e(t,e,n){if(t.operation==="delete")return;let r=t.operation==="insert"||t.operation==="upsert";e.forEach((s,o)=>{let a=n.sources[o]?.Id;if(typeof a!="string"||a==="")return;let i=Me(t.operation,s);s.success&&typeof s.id=="string"&&s.id!==""?n.links.noteWritten(a,s.id):i!==void 0?n.links.noteWritten(a,i):!s.success&&r&&n.links.noteRefused(a,t.objectApiName)})}function Je(t,e){return e.length>0?{...t,currenciesReplaced:[...e]}:t}var _e=1e3;function Qe(t,e,n,r=[],s=[],o){let a=0,i=0,y=0,c,h=[],m=0,T={created:0,updated:0},w={rows:0,written:0,stillLocked:0};for(let f of n)f.lockResends!==void 0&&(w.rows++,f.success?w.written++:we(f.errors,f.errorDetails)&&w.stillLocked++),f.success?(a++,f.created===!0?T.created++:f.created===!1&&T.updated++):Me(e,f)!==void 0?(y++,c??=f.errors[0]):(i++,!f.heldBack&&m++<_e&&h.push(...f.errors));let W=Math.max(0,m-_e);return{objectApiName:t,operation:e,processed:n.length,success:a,failed:i,skipped:y,conflictCount:0,errors:[...h,...r],...y>0?{linkedToExisting:{records:y,...c?{refusal:c}:{}}}:{},...s.length>0?{lookupsLeftOut:[...s]}:{},...o?{writtenWithoutFields:o}:{},...w.rows>0?{sentAgainForALock:w}:{},...W>0?{refusalsDropped:W}:{},...e==="upsert"?{upsertSplit:T}:{}}}export{We as a,Ae as b,Ie as c,Ee as d,yt as e,gt as f,ht as g,Pe as h,Rt as i,Ot as j,xe as k,x as l,Ne as m,vt as n,Q as o,Me as p,Je as q,_e as r,Qe as s};
7
+ import{a as Ce}from"./chunk-GMY5427L.mjs";import{h as Re,i as be,j as Se,k as ke,n as Te,o as Fe}from"./chunk-TEIBWMJM.mjs";import{c as Oe}from"./chunk-BWWQXU2B.mjs";import{f as he,i as me,o as we}from"./chunk-WSUKC2U3.mjs";import{b as fe,c as q,m as pe}from"./chunk-HFSBDM7B.mjs";import{d as K}from"./chunk-OHEOJISY.mjs";import{G as se,q as te,s as ne,t as re,u as oe}from"./chunk-KIMQQ6JQ.mjs";import{b as ee}from"./chunk-CA5NAXSU.mjs";import{a as z,l as ie,o as ae,q as de,t as ce,u as ue,v as le}from"./chunk-ICIYL45C.mjs";import{b as ye,e as ge}from"./chunk-PR74GYVI.mjs";import{Fc as X,Xc as B}from"./chunk-ZQO5PDX5.mjs";var H=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function b(t){return t.slice(0,15)}var We=class{constructor(e=new Map){this.earlier=e}earlier;written=new Map;refused=new Map;deleted=new Set;ownersRefused=new Set;contactsSentWith=new Map;noteSentWithContact(e,n){this.contactsSentWith.set(b(e),n)}contactSentWith(e){return this.contactsSentWith.get(b(e))}roleLinkedFor(e){this.contactsSentWith.delete(b(e))}get sentWithAContact(){return this.contactsSentWith.size>0}noteOwnerRefused(e){this.ownersRefused.add(b(e))}isOwnerRefused(e){return this.ownersRefused.has(b(e))}noteDeleted(e){for(let n of e)this.deleted.add(b(n))}standing(e){return e!==void 0&&this.deleted.has(b(e))?void 0:e}noteMatched(e,n){this.noteWritten(e,n)}noteWritten(e,n){this.written.set(b(e),n),this.refused.delete(b(e))}noteRefused(e,n){this.written.has(b(e))||this.refused.set(b(e),n)}targetOf(e){return this.standing(this.written.get(b(e)))??this.standing(this.earlier.get(b(e)))}refusedObjectOf(e){if(this.standing(this.earlier.get(b(e)))===void 0)return this.refused.get(b(e))}};function Ae(t,e,n){if(e.length===0||!n.some(o=>!o.master))return;let r={};for(let o of e)r[o]=(r[o]??0)+1;let s=Se(be(n));return{objectApiName:t,rows:e.length,why:r,...s?{predicted:s}:{}}}function Ie(t,e){return q(t,e?.target??[])}function Y(t){switch(t.operation){case"insert":return null;case"upsert":return t.externalIdField??"Id";case"update":case"delete":return"Id"}}function ze(t,e,n,r,s){let o=ge(t,e);for(let i of n)(!(i.fieldApiName in o)||i.overwriteExisting)&&(o[i.fieldApiName]=i.value);if(!r)return o;let a={};for(let i of Object.keys(o))i!=="attributes"&&(r.has(i)||i===s)&&(a[i]=o[i]);return a}function ve(t,e){return`${t} ${e} record${t===1?"":"s"}`}function Ue(t,e,n){let r=a=>e.find(i=>b(i.recordTypeId)===b(a)),s=t;if(!r(t)&&n){let a=n.mappings.find(i=>b(i.sourceId)===b(t));if(!a){let i=n.source.find(c=>b(c.id)===b(t)),y=i?(n.target??[]).filter(c=>c.sobjectType===i.sobjectType&&c.developerName===i.developerName):[];return{unmapped:i?K(i):"",namesakes:y.map(K)}}s=a.targetId}let o=q(e.filter(a=>b(a.recordTypeId)===b(s)),n?.target??[])[0];return o&&!o.available&&!o.master?{unavailable:o}:o?{sent:s,info:o}:{sent:s}}function Ge(t,e,n){if(t?.personAccounts===!1)return!0;if(!n)return!1;let r=e??Te(t?.recordTypes);return r!==void 0&&!n.has(b(r))}function Le(t,e,n){return{group:`parent:${e}:${n}`,reason:`PARENT_REFUSED: the ${n} record its ${e} names was refused in this run.`,say:r=>`PARENT_REFUSED: ${ve(r,t)} held back, not sent: the ${n} record their ${e} names was refused in this run, and written without it they would stand without their ${n}.`}}function Ee(t){let{config:e,records:n,target:r,run:s}=t,o=e.objectApiName,a=Y(e),i=r?.recordTypes??[],y=r?.references??new Set,c={payloads:[],sentAt:[],settled:[],held:[],deferred:[],deferredAcross:[],notes:[],currencies:[],withoutRecordType:new Map},h=new Map,m=new Map,T=(d,l,g,k)=>{c.held.push({index:d,reason:g}),h.delete(d);let I=m.get(l);I?I.count++:m.set(l,{count:1,say:k})},w=e.operation==="insert"||e.operation==="upsert",W=w&&i.some(d=>!d.master),f=new Map;s&&w&&s.sources.forEach((d,l)=>{let g=d?.Id;typeof g=="string"&&H.test(g)&&f.set(b(g),l)});let v=new Set([...s&&w?s.later??[]:[]].map(d=>d.toLowerCase())),R=new Set(v.size===0?[]:(r?.fields??[]).flatMap(d=>d.isReference&&(d.referenceTo??[]).some(l=>v.has(l.toLowerCase()))&&!(d.nillable===!1&&d.defaultedOnCreate!==!0)?[d.name]:[]));n.forEach((d,l)=>{let g=ze(d,e.fieldMappings,e.addOnFields,r?.creatable??null,a);if(e.operation==="delete"){h.set(l,{payload:g,settled:new Set});return}let k=new Set;if(s)for(let p of Object.keys(g)){let C=g[p];if(p==="RecordTypeId"||!y.has(p)||typeof C!="string"||!H.test(C))continue;if(f.has(b(C))){delete g[p],c.deferred.push({index:l,field:p,parent:C});continue}let _=s.links.targetOf(C);if(_){g[p]=_,k.add(p);continue}let M=s.links.refusedObjectOf(C);if(M===void 0){R.has(p)&&(delete g[p],c.deferredAcross.push({index:l,field:p,parent:C}));continue}let G=Le(o,p,M);T(l,G.group,G.reason,G.say);return}let I=g.RecordTypeId,E,j=Oe(I);if(j)delete g.RecordTypeId;else if(typeof I=="string"&&H.test(I)){let p=Ue(I,i,s?.recordTypes);if("unmapped"in p){let C=p.unmapped,_=p.namesakes.length>0?` The target org's ${p.namesakes.join(" and ")} carries its DeveloperName under another namespace, and a record type is mapped to one of the same namespace only.`:"";T(l,`unmapped:${C}`,"RECORD_TYPE_UNMAPPED: its record type has no counterpart in the target org.",M=>`RECORD_TYPE_UNMAPPED: ${ve(M,o)} held back, not sent: `+(C?`their record type ${C} has no active ${o} record type of that API name in the target org.${_} Create or activate record type ${C} on ${o} in the target org.`:"their record type is inactive in the source org, and has no counterpart in the target org."));return}if("unavailable"in p){let C=p.unavailable;T(l,`unavailable:${C.recordTypeId}`,`RECORD_TYPE_UNAVAILABLE: record type ${C.developerName} is closed to the running user in the target org.`,_=>`${pe({objectApiName:o,recordTypeId:C.recordTypeId,developerName:C.developerName,name:C.name,inactive:!C.active,recordCount:_})} Held back, not sent.`);return}g.RecordTypeId=p.sent,E=p.sent,p.info&&k.add("RecordTypeId")}let $=s?.sources[l]??d;if(re($)){let p=oe($,Ge(r,E,s?.recordTypes?.personTypes));for(let C of Object.keys(g))B(o,C,p)&&delete g[C]}else for(let p of Object.keys(g))B(o,p,"business")&&delete g[p];W&&!("RecordTypeId"in g)&&c.withoutRecordType.set(l,j?"masterInSource":"notRead"),h.set(l,{payload:g,settled:k})});let L=!0;for(;L;){L=!1;for(let{index:d,field:l,parent:g}of c.deferred){let k=f.get(b(g));if(!h.has(d)||k===void 0||h.has(k)||s?.links.targetOf(g)!==void 0)continue;let I=Le(o,l,o);T(d,I.group,I.reason,I.say),L=!0}}c.deferred=c.deferred.filter(({index:d})=>h.has(d)),c.deferredAcross=c.deferredAcross.filter(({index:d})=>h.has(d));for(let d of[...c.withoutRecordType.keys()])h.has(d)||c.withoutRecordType.delete(d);c.held.sort((d,l)=>d.index-l.index);let S=e.operation==="delete"?void 0:s?.currencies,O=r?.creatable.has(z)===!0,u=!O&&(s?.currencyChangesById?.size??0)>0&&r?.fields?.some(d=>d.name===z)===!0,F=S&&(O||u)?ae(r?.fields??[]):void 0,P=[...r?.references??[]],A=new le;for(let[d,{payload:l,settled:g}]of[...h].sort(([k],[I])=>k-I)){for(let k of X(o,l))delete l[k];if(S&&F){let k=s?.sources[d]??n[d],I=k?.[z],E=O?de(l,{read:I,currencyFields:F,ratesOn:ie(o,k)},S):ue(l,{read:I,parent:k?ce(o,k,P,$=>s?.currencyChangesById?.get($)):void 0,currencyFields:F},S);A.add(o,E);let j=k?.Id;E&&typeof j=="string"&&s?.currencyChangesById?.set(j,E)}c.payloads.push(l),c.sentAt.push(d),c.settled.push(g)}return c.notes=[...m.values()].map(({count:d,say:l})=>l(d)),c.currencies=A.list(),c}function V(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}function Be(t){let e=V(t.length),n=V(t.precision),r=V(t.digits);return{name:t.name,queryable:t.queryable!==!1,createable:t.createable===!0,isReference:t.type==="reference",...t.type!==void 0?{type:t.type}:{},...e!==void 0?{length:e}:{},...t.nillable!==void 0?{nillable:t.nillable}:{},...t.defaultedOnCreate!==void 0?{defaultedOnCreate:t.defaultedOnCreate}:{},...t.calculated===!0?{calculated:!0}:{},...n!==void 0?{precision:n}:{},...n!==void 0&&typeof t.scale=="number"&&t.scale>=0?{scale:t.scale}:{},...r!==void 0?{digits:r}:{},...t.unique===!0?{unique:!0}:{},...t.referenceTo?{referenceTo:[...t.referenceTo]}:{}}}function yt(t){let e=t.fields.filter(r=>r.createable===!0),n=t.fields.some(r=>typeof r.idLookup=="boolean");return{creatable:new Set(e.map(r=>r.name)),references:new Set(e.filter(r=>r.type==="reference").map(r=>r.name)),...typeof t.createable=="boolean"?{objectCreateable:t.createable}:{},...typeof t.updateable=="boolean"?{objectUpdateable:t.updateable}:{},recordTypes:fe(t.recordTypeInfos),...t.name===te?{personAccounts:t.fields.some(r=>r.name===ne)}:{},fields:t.fields.map(Be),...n?{upsertKeys:new Set(t.fields.filter(r=>r.externalId===!0||r.idLookup===!0).map(r=>r.name.toLowerCase()))}:{}}}function Z(t,e,n){switch(e){case"notInTarget":return`Object is not in the target org, or the user the run writes as cannot see it: ${t}. None of its records were sent.`;case"notCreateable":return`Object is not createable on target org: the user the run writes as may not create ${t} records there. None of its records were sent.`;case"notUpdateable":return`Object is not updateable on target org: the user the run writes as may not edit ${t} records there. None of its records were sent.`;case"unread":return`The target org did not describe ${t}${n?` (${n})`:""}, so what it takes could not be told and none of its records were sent.`;case"notAKey":return`The upsert of ${t} matches on ${n??"a field"}, which the target org does not match an upsert on: it takes an External ID field, the Id, or a field its describe marks idLookup. None of its records were sent.`}}function gt(t,e){let n=t.externalIdField?.trim().toLowerCase();if(t.operation!=="upsert"||!n)return t;let r=e.fields?.find(s=>s.name.toLowerCase()===n)?.name;return r===void 0?t:{...t,externalIdField:r}}function ht(t,e){if(t.operation==="delete"||t.query===void 0)return t;let n=Ce(t.query);if(!("list"in n))return t;let r=new Set([...n.list,t.externalIdField??"",...t.fieldMappings.filter(o=>ye.has(o.type)).map(o=>o.sourceField)].map(o=>o.toLowerCase())),s=[...e.creatable].filter(o=>!r.has(o.toLowerCase()));return s.length===0?t:{...t,excludedFields:[...new Set([...t.excludedFields??[],...s])]}}async function Pe(t,e,n,r){let s;try{s=await t(e)}catch(c){if(n==="delete")return{notAsked:!0};let h=Fe(c)?"notInTarget":"unread";return{refused:{why:h,message:Z(e,h,ee(c))}}}let o=n==="insert"||n==="upsert",a=n==="update"||n==="upsert",i=o&&s.objectCreateable===!1?"notCreateable":a&&s.objectUpdateable===!1?"notUpdateable":void 0;if(i)return{refused:{why:i,message:Z(e,i)},target:s};let y=r?.trim()||"Id";return n==="upsert"&&s.upsertKeys&&!s.upsertKeys.has(y.toLowerCase())?{refused:{why:"notAKey",message:Z(e,"notAKey",y),key:y},target:s}:{target:s}}function Rt(t){return t.keepContactPoints===!0?void 0:new Re}function Ot(t,e){if(!t)return e?{neutralized:!1,fields:[],values:0}:void 0;let n=t.report();return n.values>0?n:void 0}function xe(t,e,n,r,s){let o=s?n.filter(i=>i.name!==s):n,a=t.forObject(e,o);if(a)for(let i of r)a(i)}var x=class extends Error{constructor(n,r=[],s=[],o=[],a){super(r.length===0?`The write of ${n} was cancelled before any of its records was written.`:`The write of ${n} was cancelled after ${r.length} of its records were sent.`);this.objectApiName=n;this.written=r;this.notes=s;this.lookupsLeftOut=o;this.writtenWithoutFields=a;this.name="WriteCancelledError"}objectApiName;written;notes;lookupsLeftOut;writtenWithoutFields};var Ne=class{deps;constructor(e){this.deps=e}async sync(e,n,r){let{outcomes:s,notes:o,currencies:a,lookupsLeftOut:i,writtenWithoutFields:y}=await this.write(e,n,r);return Je(Qe(e.objectApiName,e.operation,s,o,i,y),a)}updateRecords(e,n,r){return this.executeOperation(e,"update",n,r)}async write(e,n,r){let s=null;if(this.deps.describeTargetFields){let u=await Pe(this.deps.describeTargetFields,e.objectApiName,e.operation,e.externalIdField);if("refused"in u){let F=n.map(()=>({success:!1,errors:[u.refused.message]}));return r&&$e(e,F,r),{outcomes:F,notes:[],currencies:[],lookupsLeftOut:[]}}"target"in u&&u.target.creatable.size>0&&(s=u.target)}let o=Ee({config:e,records:n,target:s,run:r}),a=r?r.contactPoints:this.deps.contactPoints;a&&s?.fields&&xe(a,e.objectApiName,s.fields,o.payloads,e.externalIdField);let i=He(o.payloads,o.settled,r),y=new Map(o.held.map(({index:u,reason:F})=>[u,F])),c=u=>{let F=[],P=0;for(let A=0;A<n.length;A++){let d=y.get(A);if(d!==void 0){F.push({success:!1,errors:[d],heldBack:!0});continue}if(P>=u.length)break;F.push(u[P++])}return F},h,m=o.sentAt.filter(u=>u<(r?.standardFirst??0)).length,T=u=>this.executeOperation(e.objectApiName,e.operation,u,e.batchSize,e.externalIdField);try{h=o.payloads.length===0&&n.length>0?[]:m>0&&m<o.payloads.length?await Ve(e.objectApiName,T,o.payloads.slice(0,m),o.payloads.slice(m)):await T(o.payloads)}catch(u){if(!(u instanceof x))throw u;let F=je(i,u.written),P=c(u.written);throw De(e,o.withoutRecordType,P,s,r),new x(e.objectApiName,P,[...o.notes,...u.notes],[...F?[F]:[],...u.lookupsLeftOut,...Q(U([...o.deferred,...o.deferredAcross],P))],u.writtenWithoutFields)}let w=await this.retryRefused(e,o.payloads,h,s?.references??null,o.settled);if(r)for(let u of w.ownersRefused)r.links.noteOwnerRefused(u);let W=c(w.outcomes);De(e,o.withoutRecordType,W,s,r);let f=je(i,w.outcomes),v=[...o.notes,...w.notes],R=[...f?[f]:[],...w.lookupsLeftOut],{writtenWithoutFields:L}=w,S=U(o.deferredAcross,W),O=0;if(w.cancelled)throw new x(e.objectApiName,W,v,[...R,...Q([...U(o.deferred,W),...S])],L);if(r){$e(e,W,r),Ze(e,o.payloads,w.outcomes,r.links);let u=await this.setLookups(e,U(o.deferred,W),r.links,!1);if(R.push(...u.leftOut),O=u.unset,u.cancelled)throw new x(e.objectApiName,W,v,[...R,...Q(S)],L)}return{outcomes:W,notes:v,currencies:o.currencies,lookupsLeftOut:R,...L?{writtenWithoutFields:L}:{},...S.length>0?{lookupsToSet:S}:{},...O>0?{lookupsUnset:O}:{}}}async setLookups(e,n,r,s){let o=e.objectApiName,a=new Map,i=new Map,y=new D;for(let{id:f,field:v,parent:R}of n){let L=r.targetOf(R),S=L!==void 0?a:s&&r.refusedObjectOf(R)===void 0?i:void 0;if(!S){y.add(f,v);continue}let O=S.get(f)??{Id:f};O[v]=L??R,S.set(f,O)}let c=new D,h=new D,m=new D,T=new D,w=!1;for(let f of[[...a.values()],[...i.values()]]){if(f.length===0)continue;if(w){for(let R of f)T.addRow(R);continue}let v;try{v=await this.executeOperation(o,"update",f,e.batchSize)}catch(R){if(!(R instanceof x)){let L=R instanceof Error?R.message:String(R);for(let S of f)m.addRow(S,L);continue}v=R.written,w=!0}f.forEach((R,L)=>{let S=v[L];S===void 0?T.addRow(R):S.success?c.addRow(R):S.errors.some(O=>J(O))?h.addRow(R):m.addRow(R,S.errors[0])})}let W=[y,h,m,T];return{...c.records>0?{set:{records:c.records,fields:c.fields()}}:{},leftOut:[y.leftOut("parentRefused"),h.leftOut("notInTarget"),m.leftOut("notSet"),T.leftOut("notReached")].flatMap(f=>f?[f]:[]),unset:new Set(W.flatMap(f=>[...f.recordIds])).size,cancelled:w}}async retryRefused(e,n,r,s,o){let a=Y(e)??void 0,i=[...r],y=[...n],c=n.map(()=>new Set),h=n.map(()=>[]),m=n.map(()=>[]),T=[],w,W=new Set;for(let S=0;S<2&&!w;S++){let O=[],u=[],F=[];if(i.forEach((A,d)=>{if(A.success)return;let l=y[d],g=o[d]??new Set;if(A.errors.some(E=>J(E))){let E=n[d]?.[N];if(typeof E=="string"&&!g.has(N)&&(A.errorDetails??[]).some(p=>J(p.statusCode)&&p.fields.includes(N))&&W.add(E),c[d].has("lookup")||!s||s.size===0)return;let j={},$=!1;for(let p of Object.keys(l)){if(s.has(p)&&!g.has(p)&&l[p]!==null&&l[p]!==void 0){$=!0;continue}j[p]=l[p]}if(!$)return;O.push(d),u.push(j),F.push(null);return}if(c[d].has("fields"))return;let k=he(A.errorDetails,l,a);if(!k||k.some(({field:E})=>g.has(E)))return;let I=new Set(k.map(({field:E})=>E));O.push(d),u.push(Object.fromEntries(Object.entries(l).filter(([E])=>!I.has(E)))),F.push(k)}),O.length===0)break;let P;try{P=await this.executeOperation(e.objectApiName,e.operation,u,e.batchSize,e.externalIdField)}catch(A){if(!(A instanceof x)){T.push(...Ye(O,y,u,F,A));break}P=A.written,w=A}P.forEach((A,d)=>{let l=O[d],g=F[d];c[l].add(g===null?"lookup":"fields"),g===null?h[l].push(...Object.keys(y[l]).filter(k=>!(k in u[d]))):m[l].push(...g),y[l]=u[d],i[l]=A})}let f=new Set,v=0,R,L=new Set(W);return i.forEach((S,O)=>{if(!(!S.success||c[O].size===0)){if(h[O].length>0){v++;for(let F of h[O])f.add(F);let u=n[O]?.[N];typeof u=="string"&&h[O].length===1&&h[O][0]===N&&L.add(u)}m[O].length>0&&(R=me(R,{rows:1,fields:m[O].map(u=>({...u,rows:1}))}))}}),{outcomes:i,notes:[...T,...w?.notes??[]],...R?{writtenWithoutFields:R}:{},cancelled:w!==void 0,ownersRefused:[...L],lookupsLeftOut:[...v>0?[{records:v,fields:[...f].sort(),reason:"notInTarget"}]:[],...w?.lookupsLeftOut??[]]}}async executeOperation(e,n,r,s,o){if(this.deps.crudFlsGuard){let a=r.length>0?Object.keys(r[0]):[],i=await this.deps.crudFlsGuard.checkCrudAndFls(e,n,a);if(!i.allowed)throw new Error(`CRUD/FLS check failed for ${n} on ${e}: ${i.reason}`)}switch(n){case"insert":return this.deps.insert(e,r,s);case"update":return this.deps.update(e,r,s);case"upsert":return this.deps.upsert(e,o??"Id",r,s);case"delete":{let a=r.map(i=>i.Id).filter(i=>typeof i=="string");return this.deps.delete(e,a,s)}}}},Ke=["INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY","INVALID_CROSS_REFERENCE_KEY"],qe=/cross[- ]reference id|r[ée]f[ée]rence crois[ée]e/i;function J(t){return Ke.some(e=>t.includes(e))||qe.test(t)}var N="OwnerId";function He(t,e,n){let r=new Set;return n&&t.forEach((s,o)=>{let a=s[N];typeof a!="string"||e[o]?.has(N)||n.links.isOwnerRefused(a)&&(delete s[N],r.add(o))}),r}function je(t,e){let n=0;for(let r of t)e[r]?.success&&n++;if(n!==0)return{records:n,fields:[N],reason:"ownerRefusedEarlier"}}function Ye(t,e,n,r,s){let o=s instanceof Error?s.message:String(s),a=new Set,i=new Set,y=0;return r.forEach((c,h)=>{if(c===null){y++;let m=n[h];for(let T of Object.keys(e[t[h]]))T in m||a.add(T)}else for(let{field:m}of c)i.add(m)}),[...y>0?[`${y} record(s) the target refused for a lookup it does not have could not be written again without ${[...a].sort().join(", ")}: ${o}`]:[],...i.size>0?[`${t.length-y} record(s) the target refused on fields it named could not be written again without ${[...i].sort().join(", ")}: ${o}`]:[]]}var D=class{ids=new Set;named=new Set;said;add(e,n){this.ids.add(e),this.named.add(n)}addRow(e,n){let r=String(e.Id);for(let s of Object.keys(e))s!=="Id"&&this.add(r,s);n!==void 0&&n!==""&&(this.said??=n)}get records(){return this.ids.size}get recordIds(){return this.ids}fields(){return[...this.named].sort()}leftOut(e){if(this.ids.size!==0)return{records:this.ids.size,fields:this.fields(),reason:e,...this.said!==void 0?{refusal:this.said}:{}}}};function U(t,e){return t.flatMap(({index:n,field:r,parent:s})=>{let o=e[n];return o?.success&&typeof o.id=="string"&&o.id!==""?[{id:o.id,field:r,parent:s}]:[]})}function vt(t){return new Set(t.map(({id:e})=>e)).size}function Q(t){let e=new D;for(let{id:r,field:s}of t)e.add(r,s);let n=e.leftOut("notReached");return n?[n]:[]}function Me(t,e){if(!(e.success||t!=="insert"&&t!=="upsert"))return e.existingId!==void 0&&e.existingId!==""?e.existingId:void 0}async function Ve(t,e,n,r){let s=await e(n);try{return[...s,...await e(r)]}catch(o){throw o instanceof x?new x(t,[...s,...o.written],o.notes,o.lookupsLeftOut,o.writtenWithoutFields):o}}function De(t,e,n,r,s){if(!s?.createdWithoutRecordType||e.size===0)return;let o=[],a=[];for(let[c,h]of e){let m=n[c];!m?.success||typeof m.id!="string"||m.id===""||t.operation!=="insert"&&m.created!==!0||(o.push(h),a.length<ke&&a.push(m.id))}let i=Ie(s.recordTypesUnderTheLease??r?.recordTypes??[],s.recordTypes),y=Ae(t.objectApiName,o,i);y&&s.createdWithoutRecordType.set(t.objectApiName,{given:y,types:i,ids:a})}function Ze(t,e,n,r){t.objectApiName==="Opportunity"&&(t.operation!=="insert"&&t.operation!=="upsert"||e.forEach((s,o)=>{let a=n[o],i=s[se];!a?.success||typeof a.id!="string"||a.id===""||t.operation!=="insert"&&a.created!==!0||typeof i=="string"&&i!==""&&r.noteSentWithContact(a.id,i)}))}function $e(t,e,n){if(t.operation==="delete")return;let r=t.operation==="insert"||t.operation==="upsert";e.forEach((s,o)=>{let a=n.sources[o]?.Id;if(typeof a!="string"||a==="")return;let i=Me(t.operation,s);s.success&&typeof s.id=="string"&&s.id!==""?n.links.noteWritten(a,s.id):i!==void 0?n.links.noteWritten(a,i):!s.success&&r&&n.links.noteRefused(a,t.objectApiName)})}function Je(t,e){return e.length>0?{...t,currenciesReplaced:[...e]}:t}var _e=1e3;function Qe(t,e,n,r=[],s=[],o){let a=0,i=0,y=0,c,h=[],m=0,T={created:0,updated:0},w={rows:0,written:0,stillLocked:0};for(let f of n)f.lockResends!==void 0&&(w.rows++,f.success?w.written++:we(f.errors,f.errorDetails)&&w.stillLocked++),f.success?(a++,f.created===!0?T.created++:f.created===!1&&T.updated++):Me(e,f)!==void 0?(y++,c??=f.errors[0]):(i++,!f.heldBack&&m++<_e&&h.push(...f.errors));let W=Math.max(0,m-_e);return{objectApiName:t,operation:e,processed:n.length,success:a,failed:i,skipped:y,conflictCount:0,errors:[...h,...r],...y>0?{linkedToExisting:{records:y,...c?{refusal:c}:{}}}:{},...s.length>0?{lookupsLeftOut:[...s]}:{},...o?{writtenWithoutFields:o}:{},...w.rows>0?{sentAgainForALock:w}:{},...W>0?{refusalsDropped:W}:{},...e==="upsert"?{upsertSplit:T}:{}}}export{We as a,Ae as b,Ie as c,Ee as d,yt as e,gt as f,ht as g,Pe as h,Rt as i,Ot as j,xe as k,x as l,Ne as m,vt as n,Q as o,Me as p,Je as q,_e as r,Qe as s};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{b as W}from"./chunk-CA5NAXSU.mjs";import{b as I,e as z,l as F,u as U}from"./chunk-7EANH5PY.mjs";function p(n){return`${n.op}\0${n.objectApiName}`}var j=class{entries=new Map;keys=new Map;of(t){let e=this.entries.get(p(t));return!e||e.spent?200:e.size}wasRefused(t){return this.entries.has(p(t))}wasCut(t){let e=this.entries.get(p(t));return e!==void 0&&e.size<200}firstRefusal(t,e,r){if(this.entries.has(p(t)))return;let o=this.entry(t,e);o.limit=r?.limit,o.automation=r?.automation,o.event=r?.event}refusedAt(t,e,r){this.firstRefusal(t,e,r);let o=this.entry(t,e);return o.size=Math.min(o.size,Math.max(1,Math.ceil(e/2))),this.of(t)}probes(t){return this.entries.get(p(t))?.probes??0}probed(t){let e=this.entries.get(p(t));e&&e.probes++}keepWhole(t){let e=this.entries.get(p(t));e&&(e.wholeAlone=!0)}isKeptWhole(t){return this.entries.get(p(t))?.wholeAlone===!0}spend(t){let e=this.entries.get(p(t));e&&(e.spent=!0)}isSpent(t){return this.entries.get(p(t))?.spent===!0}countExtraCalls(t,e){let r=this.entries.get(p(t));r&&e>0&&(r.extraCalls+=e)}countSmallCallRows(t,e){let r=this.entries.get(p(t));r&&e>0&&(r.rows+=e)}countNoted(t,e,r=1){let o=this.entries.get(p(t));!o||r<=0||(e===T?o.alone+=r:e===L?o.notSplit+=r:o.keptWhole+=r)}report(t){let e=this.entries.get(p(t));if(e)return{objectApiName:t.objectApiName,op:t.op,from:e.from,to:e.size,rows:e.rows,extraCalls:e.extraCalls,...e.limit!==void 0?{limit:e.limit}:{},...e.automation!==void 0?{automation:e.automation}:{},...e.event!==void 0?{event:e.event}:{},alone:e.alone,notSplit:e.notSplit,keptWhole:e.keptWhole,wholeAlone:e.wholeAlone,spent:e.spent}}reports(t){let e=[];for(let r of this.keys.values()){if(t!==void 0&&r.op!==t)continue;let o=this.report(r);o&&e.push(o)}return e}entry(t,e){let r=p(t),o=this.entries.get(r);return o||(o={size:200,from:e,spent:!1,wholeAlone:!1,probes:0,rows:0,extraCalls:0,alone:0,notSplit:0,keptWhole:0},this.entries.set(r,o),this.keys.set(r,{objectApiName:t.objectApiName,op:t.op})),o}};function E(n){return Math.max(0,Math.floor(Number.isFinite(n)?n:0))}var J=class{grantedCalls;perObject;takenInAll=0;byObject=new Map;constructor(t=2e3,e=500){this.grantedCalls=E(t),this.perObject=E(e)}get granted(){return this.grantedCalls}limitTo(t){this.grantedCalls=Math.min(this.grantedCalls,E(t))}left(t){let e=this.byObject.get(t.objectApiName)??0;return Math.max(0,Math.min(this.grantedCalls-this.takenInAll,this.perObject-e))}take(t,e){let r=Math.max(0,Math.min(Math.floor(e),this.left(t)));return r>0&&(this.takenInAll+=r,this.byObject.set(t.objectApiName,(this.byObject.get(t.objectApiName)??0)+r)),r}get spent(){return this.takenInAll}taken(t){return this.byObject.get(t.objectApiName)??0}};function se(n=2e3){return{sizes:new j,allowance:new J(n)}}function D(n,t){let e=Math.floor((n-t)/2);return Number.isFinite(e)?Math.min(2e3,Math.max(0,e)):0}function oe(n){return n.remaining===void 0?{}:{splitAllowance:D(n.remaining,n.estimate)}}function N(n,t,e,r){if(r<=0||n.isSpent(e))return 0;let o=t.take(e,r);return n.countExtraCalls(e,o),o<r&&n.spend(e),o}var T="alone",L="notSplit",v="keptWhole",Q="Sent on its own, the record still made the target's automation hit a Salesforce limit: the automation does too much for this record alone \u2014 fix it, or have it honour the bypass Forge's automation mute sets.",V="Not sent in smaller calls: records of the same object sent on their own were refused for a Salesforce limit too, so a smaller call would not take it \u2014 fix the target's automation, or have it honour the bypass Forge's automation mute sets.";function B(n,t){return n>0?`the ${t} had spent the ${n} smaller calls it allows itself`:`what the org has left today allowed the ${t} none`}function q(n,t="run"){return`Not sent in smaller calls: ${B(n,t)}.`}function ie(n,t,e="run"){return n===T?Q:n===v?V:q(t,e)}function M(n){return`${n} ${n===1?"call":"calls"} more`}function X(n){return`${n} ${n===1?"record":"records"}`}function Y(n){return n.automation===void 0?"The target's automation":n.event===void 0?n.automation:`${n.automation} (${n.event})`}function ae(n){let t=`${Y(n)} hit ${n.limit??"a Salesforce limit"} on a call of ${n.from}`;return n.wholeAlone?`${t}, and ${X(n.alone)} sent on ${n.alone===1?"its":"their"} own were refused too: not sent in smaller calls, ${M(n.extraCalls)}.`:n.to<200&&n.rows>0?`${t}: sent ${n.to} at a time, ${M(n.extraCalls)}.`:n.extraCalls>0?`${t}: ${M(n.extraCalls)}.`:`${t}.`}function le(n,t,e="run"){return`${n} not sent in smaller calls: ${B(t,e)}.`}function ue(n,t){let e=n.perObject-n.taken(t),r=n.granted-n.spent;return e<r?n.perObject:n.granted}function ee(n,t,e=200){return n<=t?!1:Math.ceil(n/e)===Math.ceil((n-t)/e)}var te=new Set;async function ce(n,t){let{key:e,sizes:r,allowance:o}=t,c=Math.min(t.maxSize??200,200),h=[],m,f=0,S=()=>[...h.flatMap(s=>s.items),...m?.items??[],...n.slice(f)],K=()=>{let s=Math.min(c,r.of(e)),l=s<c,g=t.pricedAs==="job"||ee(n.length-f,s,c);l&&g&&(t.paid&&t.paid.calls>0?t.paid.calls--:N(r,o,e,1)===0&&(s=c,l=!1));let i=n.slice(f,f+s);return f+=i.length,{items:i,reduced:l}},A=async s=>{let l=m;if(m=void 0,!l||l.items.length===0)return;r.countNoted(e,s,l.items.length);let g=new Map(l.items.map((i,d)=>[d,s]));try{await t.settle(l.items,l.answers,te,g,!0)}catch(i){throw t.onThrow?.(S(),i),i}},k=async()=>{let s=m;if(!s)return;if(s.items.length===0){m=void 0;return}let l=r.refusedAt(e,s.from,s.cause),g=N(r,o,e,Math.ceil(s.items.length/l)),i=Math.min(s.items.length,g*l),d=[];for(let b=0;b<i;b+=l)d.push({items:s.items.slice(b,Math.min(i,b+l)),reduced:!0});h.unshift(...d),m={...s,items:s.items.slice(i),answers:s.answers.slice(i)},await A(L)},_=async()=>{let s=m;if(!s||s.items.length===0){m=void 0;return}if(N(r,o,e,1)===0){await A(L);return}r.probed(e),h.unshift({items:[s.items[0]],reduced:!0,probe:!0}),m={...s,items:s.items.slice(1),answers:s.answers.slice(1)}},P=!0,w=t.refusedIn;if(w&&n.length>0){if(f=n.length,P=!1,!r.wasRefused(e)){r.firstRefusal(e,w.from,w.cause);let s=r.report(e);s&&t.onFirstRefusal?.(s)}m={items:[...n],answers:[...w.answers],from:w.from,...w.cause?{cause:w.cause}:{}},r.isSpent(e)?await A(L):r.isKeptWhole(e)?await A(v):!r.wasCut(e)&&r.probes(e)<2?await _():await k()}for(;;){let s;if(P){if(n.length===0)return{};s=K()}else{if(s=h.shift()??(f<n.length?K():void 0),!s)return{};try{if(await t.beforeEachSend?.()==="stop")return{stopped:{part:s.items,rest:S(),sent:!1}}}catch(u){throw t.onThrow?.([...s.items,...S()],u),u}}P=!1;let l;try{l=await t.send(s.items)}catch(u){throw t.onThrow?.([...s.items,...S()],u),u}if(l==="stop")return{stopped:{part:s.items,rest:S(),sent:!0}};let{answers:g}=l,i=s.items,d=[],b;for(let u=0;u<i.length;u++){let a=t.limited(g[u],i[u]);a&&(d.push(u),b??=a)}let R=new Set,C=new Map,x;if(s.probe)d.length>0?(C.set(0,T),x=r.probes(e)<2&&(m?.items.length??0)>0?_:async()=>{r.probes(e)>=2&&r.keepWhole(e),await A(v)}):x=k;else if(d.length>0){if(!r.wasRefused(e)){r.firstRefusal(e,i.length,b);let a=r.report(e);a&&t.onFirstRefusal?.(a)}let u=!r.wasCut(e)&&!r.isKeptWhole(e)&&r.probes(e)<2;if(i.length===1)C.set(0,T),u&&!r.isSpent(e)&&(r.probed(e),r.probes(e)>=2&&r.keepWhole(e));else if(r.isSpent(e))for(let a of d)C.set(a,L);else if(r.isKeptWhole(e))for(let a of d)C.set(a,v);else if(u){for(let a of d)R.add(a);m={items:d.map(a=>i[a]),answers:d.map(a=>g[a]),from:i.length,...b?{cause:b}:{}},x=_}else{let a=r.refusedAt(e,i.length,b),Z=N(r,o,e,Math.ceil(d.length/a)),O=d.slice(0,Z*a);for(let y of O)R.add(y);for(let y of d.slice(O.length))C.set(y,L);let $=[];for(let y=0;y<O.length;y+=a)$.push({items:O.slice(y,y+a).map(H=>i[H]),reduced:!0});h.unshift(...$)}}for(let u of C.values())r.countNoted(e,u);s.reduced&&r.countSmallCallRows(e,i.length-R.size);try{await t.settle(i,g,R,C)}catch(u){throw t.onThrow?.(S(),u),u}await x?.()}}var ne=60*6e4,re=F({state:U(["Open","UploadComplete","InProgress","JobComplete","Failed","Aborted"]),numberRecordsProcessed:z().int().nonnegative().optional(),errorMessage:I().nullish(),systemModstamp:I().optional(),createdDate:I().optional()});function G(n,t){let e=re.safeParse(t);if(e.success)return e.data;let r=typeof t=="object"&&t!==null&&"state"in t?String(JSON.stringify(t.state)):"none";throw new Error(`The org's answer about Bulk API job ${n||"(no id)"} is not an ingest job's state (state: ${r})`)}async function fe(n,t,e={}){let r=e.now??(()=>Date.now());try{let o=n.bulk2.job("ingest",{id:t}),c=G(t,await o.check());if(c.state==="Open"){let h=Date.parse(c.createdDate??""),m=e.openGraceMs??ne,f=m-(r()-h);if(Number.isFinite(h)&&f>0)return{state:"running",info:c,openUntil:new Date(h+m).toISOString(),graceLeftMs:f};if(!await o.abort().then(()=>!1,()=>!0)&&m>0)return{state:"never-closed"};if(c=G(t,await o.check()),c.state==="Open"||c.state==="Aborted"&&c.numberRecordsProcessed===0)return{state:"never-closed"}}if(c.state==="UploadComplete"||c.state==="InProgress")return{state:"running",info:c};if(e.successfulOnly)return{state:"ended",info:c,results:{successfulResults:[...await o.getSuccessfulResults()]}};if(o.getAllResults===void 0)throw new Error(`Bulk API job ${t}: this connection reads no failed or unprocessed rows`);return{state:"ended",info:c,results:await o.getAllResults()}}catch(o){return{state:"unread",reason:W(o)}}}export{se as a,D as b,oe as c,Q as d,V as e,ie as f,ae as g,le as h,ue as i,ce as j,G as k,fe as l};
7
+ import{b as W}from"./chunk-CA5NAXSU.mjs";import{b as I,e as z,l as F,u as U}from"./chunk-WZQEK4WT.mjs";function p(n){return`${n.op}\0${n.objectApiName}`}var j=class{entries=new Map;keys=new Map;of(t){let e=this.entries.get(p(t));return!e||e.spent?200:e.size}wasRefused(t){return this.entries.has(p(t))}wasCut(t){let e=this.entries.get(p(t));return e!==void 0&&e.size<200}firstRefusal(t,e,r){if(this.entries.has(p(t)))return;let o=this.entry(t,e);o.limit=r?.limit,o.automation=r?.automation,o.event=r?.event}refusedAt(t,e,r){this.firstRefusal(t,e,r);let o=this.entry(t,e);return o.size=Math.min(o.size,Math.max(1,Math.ceil(e/2))),this.of(t)}probes(t){return this.entries.get(p(t))?.probes??0}probed(t){let e=this.entries.get(p(t));e&&e.probes++}keepWhole(t){let e=this.entries.get(p(t));e&&(e.wholeAlone=!0)}isKeptWhole(t){return this.entries.get(p(t))?.wholeAlone===!0}spend(t){let e=this.entries.get(p(t));e&&(e.spent=!0)}isSpent(t){return this.entries.get(p(t))?.spent===!0}countExtraCalls(t,e){let r=this.entries.get(p(t));r&&e>0&&(r.extraCalls+=e)}countSmallCallRows(t,e){let r=this.entries.get(p(t));r&&e>0&&(r.rows+=e)}countNoted(t,e,r=1){let o=this.entries.get(p(t));!o||r<=0||(e===T?o.alone+=r:e===L?o.notSplit+=r:o.keptWhole+=r)}report(t){let e=this.entries.get(p(t));if(e)return{objectApiName:t.objectApiName,op:t.op,from:e.from,to:e.size,rows:e.rows,extraCalls:e.extraCalls,...e.limit!==void 0?{limit:e.limit}:{},...e.automation!==void 0?{automation:e.automation}:{},...e.event!==void 0?{event:e.event}:{},alone:e.alone,notSplit:e.notSplit,keptWhole:e.keptWhole,wholeAlone:e.wholeAlone,spent:e.spent}}reports(t){let e=[];for(let r of this.keys.values()){if(t!==void 0&&r.op!==t)continue;let o=this.report(r);o&&e.push(o)}return e}entry(t,e){let r=p(t),o=this.entries.get(r);return o||(o={size:200,from:e,spent:!1,wholeAlone:!1,probes:0,rows:0,extraCalls:0,alone:0,notSplit:0,keptWhole:0},this.entries.set(r,o),this.keys.set(r,{objectApiName:t.objectApiName,op:t.op})),o}};function E(n){return Math.max(0,Math.floor(Number.isFinite(n)?n:0))}var J=class{grantedCalls;perObject;takenInAll=0;byObject=new Map;constructor(t=2e3,e=500){this.grantedCalls=E(t),this.perObject=E(e)}get granted(){return this.grantedCalls}limitTo(t){this.grantedCalls=Math.min(this.grantedCalls,E(t))}left(t){let e=this.byObject.get(t.objectApiName)??0;return Math.max(0,Math.min(this.grantedCalls-this.takenInAll,this.perObject-e))}take(t,e){let r=Math.max(0,Math.min(Math.floor(e),this.left(t)));return r>0&&(this.takenInAll+=r,this.byObject.set(t.objectApiName,(this.byObject.get(t.objectApiName)??0)+r)),r}get spent(){return this.takenInAll}taken(t){return this.byObject.get(t.objectApiName)??0}};function se(n=2e3){return{sizes:new j,allowance:new J(n)}}function D(n,t){let e=Math.floor((n-t)/2);return Number.isFinite(e)?Math.min(2e3,Math.max(0,e)):0}function oe(n){return n.remaining===void 0?{}:{splitAllowance:D(n.remaining,n.estimate)}}function N(n,t,e,r){if(r<=0||n.isSpent(e))return 0;let o=t.take(e,r);return n.countExtraCalls(e,o),o<r&&n.spend(e),o}var T="alone",L="notSplit",v="keptWhole",Q="Sent on its own, the record still made the target's automation hit a Salesforce limit: the automation does too much for this record alone \u2014 fix it, or have it honour the bypass Forge's automation mute sets.",V="Not sent in smaller calls: records of the same object sent on their own were refused for a Salesforce limit too, so a smaller call would not take it \u2014 fix the target's automation, or have it honour the bypass Forge's automation mute sets.";function B(n,t){return n>0?`the ${t} had spent the ${n} smaller calls it allows itself`:`what the org has left today allowed the ${t} none`}function q(n,t="run"){return`Not sent in smaller calls: ${B(n,t)}.`}function ie(n,t,e="run"){return n===T?Q:n===v?V:q(t,e)}function M(n){return`${n} ${n===1?"call":"calls"} more`}function X(n){return`${n} ${n===1?"record":"records"}`}function Y(n){return n.automation===void 0?"The target's automation":n.event===void 0?n.automation:`${n.automation} (${n.event})`}function ae(n){let t=`${Y(n)} hit ${n.limit??"a Salesforce limit"} on a call of ${n.from}`;return n.wholeAlone?`${t}, and ${X(n.alone)} sent on ${n.alone===1?"its":"their"} own were refused too: not sent in smaller calls, ${M(n.extraCalls)}.`:n.to<200&&n.rows>0?`${t}: sent ${n.to} at a time, ${M(n.extraCalls)}.`:n.extraCalls>0?`${t}: ${M(n.extraCalls)}.`:`${t}.`}function le(n,t,e="run"){return`${n} not sent in smaller calls: ${B(t,e)}.`}function ue(n,t){let e=n.perObject-n.taken(t),r=n.granted-n.spent;return e<r?n.perObject:n.granted}function ee(n,t,e=200){return n<=t?!1:Math.ceil(n/e)===Math.ceil((n-t)/e)}var te=new Set;async function ce(n,t){let{key:e,sizes:r,allowance:o}=t,c=Math.min(t.maxSize??200,200),h=[],m,f=0,S=()=>[...h.flatMap(s=>s.items),...m?.items??[],...n.slice(f)],K=()=>{let s=Math.min(c,r.of(e)),l=s<c,g=t.pricedAs==="job"||ee(n.length-f,s,c);l&&g&&(t.paid&&t.paid.calls>0?t.paid.calls--:N(r,o,e,1)===0&&(s=c,l=!1));let i=n.slice(f,f+s);return f+=i.length,{items:i,reduced:l}},A=async s=>{let l=m;if(m=void 0,!l||l.items.length===0)return;r.countNoted(e,s,l.items.length);let g=new Map(l.items.map((i,d)=>[d,s]));try{await t.settle(l.items,l.answers,te,g,!0)}catch(i){throw t.onThrow?.(S(),i),i}},k=async()=>{let s=m;if(!s)return;if(s.items.length===0){m=void 0;return}let l=r.refusedAt(e,s.from,s.cause),g=N(r,o,e,Math.ceil(s.items.length/l)),i=Math.min(s.items.length,g*l),d=[];for(let b=0;b<i;b+=l)d.push({items:s.items.slice(b,Math.min(i,b+l)),reduced:!0});h.unshift(...d),m={...s,items:s.items.slice(i),answers:s.answers.slice(i)},await A(L)},_=async()=>{let s=m;if(!s||s.items.length===0){m=void 0;return}if(N(r,o,e,1)===0){await A(L);return}r.probed(e),h.unshift({items:[s.items[0]],reduced:!0,probe:!0}),m={...s,items:s.items.slice(1),answers:s.answers.slice(1)}},P=!0,w=t.refusedIn;if(w&&n.length>0){if(f=n.length,P=!1,!r.wasRefused(e)){r.firstRefusal(e,w.from,w.cause);let s=r.report(e);s&&t.onFirstRefusal?.(s)}m={items:[...n],answers:[...w.answers],from:w.from,...w.cause?{cause:w.cause}:{}},r.isSpent(e)?await A(L):r.isKeptWhole(e)?await A(v):!r.wasCut(e)&&r.probes(e)<2?await _():await k()}for(;;){let s;if(P){if(n.length===0)return{};s=K()}else{if(s=h.shift()??(f<n.length?K():void 0),!s)return{};try{if(await t.beforeEachSend?.()==="stop")return{stopped:{part:s.items,rest:S(),sent:!1}}}catch(u){throw t.onThrow?.([...s.items,...S()],u),u}}P=!1;let l;try{l=await t.send(s.items)}catch(u){throw t.onThrow?.([...s.items,...S()],u),u}if(l==="stop")return{stopped:{part:s.items,rest:S(),sent:!0}};let{answers:g}=l,i=s.items,d=[],b;for(let u=0;u<i.length;u++){let a=t.limited(g[u],i[u]);a&&(d.push(u),b??=a)}let R=new Set,C=new Map,x;if(s.probe)d.length>0?(C.set(0,T),x=r.probes(e)<2&&(m?.items.length??0)>0?_:async()=>{r.probes(e)>=2&&r.keepWhole(e),await A(v)}):x=k;else if(d.length>0){if(!r.wasRefused(e)){r.firstRefusal(e,i.length,b);let a=r.report(e);a&&t.onFirstRefusal?.(a)}let u=!r.wasCut(e)&&!r.isKeptWhole(e)&&r.probes(e)<2;if(i.length===1)C.set(0,T),u&&!r.isSpent(e)&&(r.probed(e),r.probes(e)>=2&&r.keepWhole(e));else if(r.isSpent(e))for(let a of d)C.set(a,L);else if(r.isKeptWhole(e))for(let a of d)C.set(a,v);else if(u){for(let a of d)R.add(a);m={items:d.map(a=>i[a]),answers:d.map(a=>g[a]),from:i.length,...b?{cause:b}:{}},x=_}else{let a=r.refusedAt(e,i.length,b),Z=N(r,o,e,Math.ceil(d.length/a)),O=d.slice(0,Z*a);for(let y of O)R.add(y);for(let y of d.slice(O.length))C.set(y,L);let $=[];for(let y=0;y<O.length;y+=a)$.push({items:O.slice(y,y+a).map(H=>i[H]),reduced:!0});h.unshift(...$)}}for(let u of C.values())r.countNoted(e,u);s.reduced&&r.countSmallCallRows(e,i.length-R.size);try{await t.settle(i,g,R,C)}catch(u){throw t.onThrow?.(S(),u),u}await x?.()}}var ne=60*6e4,re=F({state:U(["Open","UploadComplete","InProgress","JobComplete","Failed","Aborted"]),numberRecordsProcessed:z().int().nonnegative().optional(),errorMessage:I().nullish(),systemModstamp:I().optional(),createdDate:I().optional()});function G(n,t){let e=re.safeParse(t);if(e.success)return e.data;let r=typeof t=="object"&&t!==null&&"state"in t?String(JSON.stringify(t.state)):"none";throw new Error(`The org's answer about Bulk API job ${n||"(no id)"} is not an ingest job's state (state: ${r})`)}async function fe(n,t,e={}){let r=e.now??(()=>Date.now());try{let o=n.bulk2.job("ingest",{id:t}),c=G(t,await o.check());if(c.state==="Open"){let h=Date.parse(c.createdDate??""),m=e.openGraceMs??ne,f=m-(r()-h);if(Number.isFinite(h)&&f>0)return{state:"running",info:c,openUntil:new Date(h+m).toISOString(),graceLeftMs:f};if(!await o.abort().then(()=>!1,()=>!0)&&m>0)return{state:"never-closed"};if(c=G(t,await o.check()),c.state==="Open"||c.state==="Aborted"&&c.numberRecordsProcessed===0)return{state:"never-closed"}}if(c.state==="UploadComplete"||c.state==="InProgress")return{state:"running",info:c};if(e.successfulOnly)return{state:"ended",info:c,results:{successfulResults:[...await o.getSuccessfulResults()]}};if(o.getAllResults===void 0)throw new Error(`Bulk API job ${t}: this connection reads no failed or unprocessed rows`);return{state:"ended",info:c,results:await o.getAllResults()}}catch(o){return{state:"unread",reason:W(o)}}}export{se as a,D as b,oe as c,Q as d,V as e,ie as f,ae as g,le as h,ue as i,ce as j,G as k,fe as l};
@@ -4,7 +4,7 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{d as s}from"./chunk-AV5SWEHP.mjs";var i=["--accept-automation","--accept-emails","--mute-automation"];function n(t){return{...t.includes("--accept-automation")?{acceptAutomation:!0}:{},...t.includes("--accept-emails")?{acceptEmails:!0}:{},...t.includes("--mute-automation")?{muteAutomation:!0}:{}}}function r(t,e){let a=e?`exit 1; with ${e}, says what
7
+ import{d as s}from"./chunk-6FARZYMJ.mjs";var i=["--accept-automation","--accept-emails","--mute-automation"];function n(t){return{...t.includes("--accept-automation")?{acceptAutomation:!0}:{},...t.includes("--accept-emails")?{acceptEmails:!0}:{},...t.includes("--mute-automation")?{muteAutomation:!0}:{}}}function r(t,e){let a=e?`exit 1; with ${e}, says what
8
8
  would be muted and assigns nothing`:"exit 1";return` --accept-automation write although the org runs flows, Apex triggers,
9
9
  processes or workflow rules as the records are
10
10
  ${t}, or could not say what it runs:
@@ -0,0 +1,11 @@
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{g as ae,i as V}from"./chunk-7WSLT5VX.mjs";import{m as oe,o as ie}from"./chunk-SAMWHL22.mjs";import{B as q,H as ee,I as te,J as ne,L as re,d as M,k as B,s as W,t as E,u as Z,v as z,w as Q,z as j}from"./chunk-J24TIGSI.mjs";import{$a as J,ab as U,bb as D}from"./chunk-ZQO5PDX5.mjs";import{b as N,e as K,m as F,v as L}from"./chunk-WZQEK4WT.mjs";import{createCipheriv as Se,createDecipheriv as Ce,createHash as m,hkdfSync as Te,randomBytes as C,timingSafeEqual as Pe}from"node:crypto";import{createReadStream as He}from"node:fs";import{lstat as se,open as _,rename as _e,rm as $e,statfs as Ne}from"node:fs/promises";import{basename as de,dirname as le,join as ue}from"node:path";import{Readable as pe}from"node:stream";import{pipeline as ye}from"node:stream/promises";import{createGunzip as Ke,createGzip as Fe}from"node:zlib";var bt=".sfcheckpoint",De=1024*1024,Me=new Set([1]),ze=new Set([1,2]),$=32,O=16,je=4096,Ve=1024,Xe=64*1024*1024,me=2**32,ge="sandforge-checkpoint/1 block key",we="sandforge-checkpoint/1 key check",X="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",Ye=Math.ceil($*8/5),g="Nothing was imported.";function Bt(){return C($)}function At(n){if(n.length!==$)throw new RangeError("Not a key of a checkpoint file");let e="",t=0,r=0;for(let o of n)for(t=(t<<8|o)&65535,r+=8;r>=5;)e+=X[t>>>r-5&31],r-=5;return r>0&&(e+=X[t<<5-r&31]),(e.match(/.{1,4}/g)??[]).join("-")}function Et(n){let e=n.replace(/[\s-]/g,"").toUpperCase();if(e.length!==Ye||!/^[A-Z2-7]+$/.test(e))return;let t=Buffer.alloc($),r=0,o=0,i=0;for(let a of e)r=(r<<5|X.indexOf(a))&65535,o+=5,o>=8&&(t[i++]=r>>>o-8&255,o-=8);if((r&(1<<o)-1)===0)return t}function T(n,e,t,r){return Buffer.from(Te("sha256",n,e,t,r))}function ke(n,e){let t=Buffer.alloc(12);return n.copy(t,0),t.writeUInt32BE(e,8),t}function be(n,e,t){let r=Buffer.alloc(37);return n.copy(r,0),r.writeUInt32BE(e,32),r[36]=t?1:0,r}function Ge(n,e,t,r){let o=Se("aes-256-gcm",n.blockKey,ke(n.prefix,e),{authTagLength:O});return o.setAAD(be(n.headerHash,e,t)),Buffer.concat([o.update(r),o.final(),o.getAuthTag()])}function Le(n,e,t,r){let o=Ce("aes-256-gcm",n.blockKey,ke(n.prefix,e),{authTagLength:O});o.setAAD(be(n.headerHash,e,t)),o.setAuthTag(r.subarray(r.length-O));try{let i=o.update(r.subarray(0,r.length-O));return Buffer.concat([i,o.final()])}catch{return}}var P=class extends Error{constructor(t){super(t.message);this.refusal=t;this.name="ImportRefused"}refusal};function f(n){return new P({code:"IMPORT_DAMAGED",message:`This checkpoint file ${n}: it was changed or damaged after it was exported. ${g}`})}var I=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointExportError"}code};function Je(n){return{...H(n,Be),org:H(n.org,Ae)}}var Be=["lastRewind","takenOn","expiresAt","bytes","importedFrom"],Ae=["alias"];function H(n,e){return Object.fromEntries(Object.entries(n).filter(([t])=>!e.includes(t)))}async function*Ee(n,e){if(e===0)return;let t=0;for await(let r of He(n,{start:0,end:e-1})){let o=r;t+=o.length,yield o}if(t!==e)throw new I("EXPORT_CHANGED",`${de(n)} of the checkpoint shrank while it was exported: export it again.`)}async function xe(n,e){let t=m("sha256");for await(let r of Ee(n,e))t.update(r);return t.digest("hex")}async function xt(n){let{folder:e,checkpoint:t,out:r,key:o}=n,i=n.chunkBytes??De;if(await se(r).catch(()=>{}))throw new I("EXPORT_EXISTS",`${r} is there already: name another file, or move that one away first.`);let a=Buffer.from(`${JSON.stringify(Je(t))}
8
+ `,"utf8"),s=[{path:E,bytes:a.length,sha256:m("sha256").update(a).digest("hex"),content:a}];for(let u of await z(e))u.path!==E&&s.push({...u,sha256:await xe(u.file,u.bytes)});let h=s.some(u=>u.path===W);h&&await V(e);let c=C(32),d=C(8),{dataStorageMaxMB:l,staging:p}=t.org,v={format:"sandforge-checkpoint",formatVersion:h?2:1,checkpointFormat:1,sandforgeVersion:n.sandforgeVersion,organizationId:B(t.org.organizationId),orgTier:t.org.tier,...l!==void 0?{dataStorageMaxMB:l}:{},...p===!0?{staging:p}:{},checkpointId:t.checkpointId,takenAt:t.takenAt,records:Ie(t),objects:t.objects.length,files:s.length,bytes:s.reduce((u,b)=>u+b.bytes,0),cipher:"aes-256-gcm",kdf:"hkdf-sha256",salt:c.toString("hex"),noncePrefix:d.toString("hex"),keyCheck:T(o,c,we,16).toString("hex"),chunkBytes:i},R=Buffer.from(`${JSON.stringify(D.parse(v))}
9
+ `),w={blockKey:T(o,c,ge,32),prefix:d,headerHash:m("sha256").update(R).digest()},S=ue(le(r),`.${de(r)}.${process.pid}-${C(4).toString("hex")}.tmp`),y=m("sha256"),k=0,A=await _(S,"wx",M);try{try{let u=async b=>{y.update(b),k+=b.length,await Oe(A,b)};await u(R),await ye(pe.from(Ue(s)),Fe({level:6}),async b=>{await We(b,i,w,u)}),await A.sync()}finally{await A.close()}if(await se(r).catch(()=>{}))throw new I("EXPORT_EXISTS",`${r} appeared while the checkpoint was exported: name another file.`);await _e(S,r)}catch(u){throw await $e(S,{force:!0}),u}return{header:v,bytes:k,sha256:y.digest("hex")}}async function Oe(n,e){for(let t=0;t<e.length;){let{bytesWritten:r}=await n.write(e,t,e.length-t);t+=r}}function Ie(n){return n.objects.reduce((e,t)=>e+t.records,0)}async function*Ue(n){for(let e of n){let{path:t,bytes:r,sha256:o}=e;if(yield Buffer.from(`${JSON.stringify({path:t,bytes:r,sha256:o})}
10
+ `,"utf8"),e.content!==void 0){yield e.content;continue}let i=m("sha256");for await(let a of Ee(e.file??"",r))i.update(a),yield a;if(i.digest("hex")!==o)throw new I("EXPORT_CHANGED",`${t} of the checkpoint changed while it was exported: export it again.`)}yield Buffer.from(`${JSON.stringify({end:!0,files:n.length})}
11
+ `,"utf8")}async function We(n,e,t,r){let o=0,i,a=[],s=0,h=async c=>{if(i!==void 0){if(o>=me)throw new RangeError("The checkpoint is too large for one file");await r(Ge(t,o,c,i)),o++,i=void 0}};for await(let c of n)for(a.push(c),s+=c.length;s>=e;){let d=Buffer.concat(a);await h(!1),i=d.subarray(0,e),a=[d.subarray(e)],s=d.length-e}s>0&&(await h(!1),i=Buffer.concat(a)),await h(!0)}async function Y(n,e,t){let r=Buffer.alloc(t),o=0;for(;o<t;){let{bytesRead:i}=await n.read(r,o,t-o,e+o);if(i===0)break;o+=i}return o===t?r:r.subarray(0,o)}function x(n){return{refusal:{code:"IMPORT_NOT_ARCHIVE",message:`This is not a checkpoint file SandForge exported: ${n}. ${g}`}}}async function ve(n){let e;try{e=await _(n,"r")}catch(t){let r=t.code;return x(r==="ENOENT"?"there is no such file":"it cannot be read")}try{let t=await e.stat();if(!t.isFile())return x("it is not a file");let r=await Y(e,0,Math.min(t.size,je)),o=r.indexOf(10);if(o<0)return x("it does not start with a checkpoint file\u2019s header");let i=r.subarray(0,o+1),a;try{a=JSON.parse(i.toString("utf8"))}catch{return x("it does not start with a checkpoint file\u2019s header")}let s=U.safeParse(a);if(!s.success)return x("it does not start with a checkpoint file\u2019s header");let{formatVersion:h,checkpointFormat:c,sandforgeVersion:d}=s.data;if(!ze.has(h)||!Me.has(c))return{refusal:{code:"IMPORT_VERSION",message:`This file was made by SandForge ${d}, with checkpoint format ${c} in file format ${h}, which this SandForge does not read: update SandForge, then import it. ${g}`}};let l=D.safeParse(a);return l.success?{read:{header:l.data,headerBytes:i.length,headerHash:m("sha256").update(i).digest(),size:t.size}}:x("its header does not read")}finally{await e.close()}}async function Ze(n){try{let e=await Ne(n);return Number(e.bavail)*Number(e.bsize)}catch{return}}async function Qe(n){try{return await qe(n)}catch(e){if(e instanceof P)return{imported:!1,refusal:e.refusal};if(e instanceof ee&&e.code==="damaged")return{imported:!1,refusal:{code:"IMPORT_DAMAGED",message:`${e.message} ${g}`}};throw e}}async function qe(n){let{store:e,file:t,key:r}=n,o=n.now??new Date,i=await ve(t);if("refusal"in i)return{imported:!1,refusal:i.refusal};if(!i.read.headerHash.equals(n.read.headerHash))throw f("changed since its header was read");let a=i.read,{header:s}=a,h=Buffer.from(s.salt,"hex");if(!Pe(T(r,h,we,16),Buffer.from(s.keyCheck,"hex")))return{imported:!1,refusal:{code:"IMPORT_KEY",message:`This key is not the one the file was exported with. ${g}`}};let c={blockKey:T(r,h,ge,32),prefix:Buffer.from(s.noncePrefix,"hex"),headerHash:a.headerHash},d=await e.read(s.checkpointId);if(d!==void 0)return he(d,t,a,c);let l=await(n.freeBytes??Ze)(e.root),p=s.bytes+oe(s.records,2)+s.objects*8;if(l!==void 0&&l<p)return{imported:!1,refusal:{code:"IMPORT_DISK",message:`The checkpoint takes about ${ce(p)} on this machine, and its disk has ${ce(l)} free: make room, then import it. ${g}`}};let v=await e.importInto(s.organizationId,s.checkpointId,async w=>{let S=await Re(t,a,c,w.dir),y=ot(S,a,{...n.alias!==void 0?{alias:n.alias}:{},keepDays:n.keepDays,takenOn:n.takenOn,now:o});await it(w,y,s),await j(w.indexDir);for(let k of y.objects){let A=await ie(w,y.snapshotId,k.objectApiName);if(A.rows!==k.records)throw f(`holds ${A.rows} records of ${k.objectApiName} where its checkpoint counts ${k.records}`)}return await ne(w,y.objects),y});if(v.outcome==="imported")return{imported:!0,outcome:"imported",checkpoint:v.checkpoint};let R=await e.read(s.checkpointId);if(R===void 0)throw f("could not be kept");return he(R,t,a,c)}function ce(n){return`${(n/(1024*1024)).toFixed(1)} MB`}async function he(n,e,t,r){let o=c=>({imported:!1,refusal:{code:"IMPORT_KEPT_OTHER",message:`A checkpoint ${t.header.checkpointId} is kept on this machine already, ${c}: delete it first to import this file. ${g}`}});if(n.folder.organizationId!==B(t.header.organizationId))return o("of another org");if(n.checkpoint===void 0)return o("damaged");let i=o("and differs from this one"),a=await Re(e,t,r),s=new Map(a.hashes.filter(([c])=>c!==E).map(([c,d])=>[c,d])),h=(await z(n.folder)).filter(c=>c.path!==E);if(h.length!==s.size)return i;for(let c of h)if(s.get(c.path)!==await xe(c.file,c.bytes))return i;return{imported:!0,outcome:"alreadyKept",checkpoint:n.checkpoint}}var et=F({path:N().min(1).max(300),bytes:K().int().nonnegative(),sha256:N().regex(/^[0-9a-f]{64}$/)}),tt=F({end:L(!0),files:K().int().positive()});async function Re(n,e,t,r){let o=await _(n,"r"),i=m("sha256");try{let a=new G(e.header,r);try{await ye(pe.from(nt(o,e,t,i)),Ke(),async h=>{for await(let c of h)await a.take(c)})}catch(h){throw String(h.code??"").startsWith("Z_")?f("does not inflate"):h}finally{await a.close()}return{...a.ended(),sha256:i.digest("hex")}}finally{await o.close()}}async function*nt(n,e,t,r){r.update(await Y(n,0,e.headerBytes));let o=e.header.chunkBytes+O,i=e.size-e.headerBytes;if(i<=0)throw f("holds nothing after its header");let a=Math.ceil(i/o),s=i-(a-1)*o;if(s<=O)throw f("ends inside a block");if(a>me)throw f("holds more blocks than a file can");for(let h=0;h<a;h++){let c=h===a-1,d=c?s:o,l=await Y(n,e.headerBytes+h*o,d);if(l.length<d)throw f("is cut short");r.update(l);let p=Le(t,h,c,l);if(p===void 0)throw f(`holds a block, the ${rt(h+1)} of ${a}, that does not decrypt`);yield p}}function rt(n){let e=n%100,t=e>=11&&e<=13?"th":["th","st","nd","rd"][n%10]??"th";return`${n}${t}`}var G=class{constructor(e,t){this.header=e;this.into=t}header;into;line=[];lineBytes=0;current;seen=new Set;hashes=[];portable;bytes=0;end=!1;async take(e){let t=0;for(;t<e.length;){if(this.end)throw f("holds bytes after its last entry");let r=this.current;if(r!==void 0){let s=e.subarray(t,t+Math.min(r.left,e.length-t));t+=s.length,r.left-=s.length,r.hash.update(s),r.handle!==void 0&&await Oe(r.handle,s),r.held?.push(Buffer.from(s)),r.left===0&&await this.endEntry();continue}let o=e.indexOf(10,t),i=o<0?e.length:o;if(this.lineBytes+=i-t,this.lineBytes>Ve)throw f("holds a line too long for an entry");if(this.line.push(e.subarray(t,i)),t=i,o<0)continue;t++;let a=Buffer.concat(this.line).toString("utf8");this.line=[],this.lineBytes=0,await this.startEntry(a)}}async startEntry(e){let t;try{t=JSON.parse(e)}catch{throw f("holds an entry that does not read")}let r=tt.safeParse(t);if(r.success){if(r.data.files!==this.hashes.length||r.data.files!==this.header.files)throw f("counts other files than it holds");this.end=!0;return}let o=et.safeParse(t);if(!o.success)throw f("holds an entry that does not read");let{path:i,bytes:a,sha256:s}=o.data;if(!Z(i))throw f(`names a file no checkpoint holds, ${JSON.stringify(i)}`);if(this.seen.has(i))throw f(`holds ${i} twice`);if(this.seen.add(i),this.bytes+=a,this.bytes>this.header.bytes||this.seen.size>this.header.files)throw f("holds more than its header says");let h=i===E;if(h&&a>Xe)throw f("holds a checkpoint.json larger than any checkpoint\u2019s");let c;if(!h&&this.into!==void 0){let d=Q(this.into,i);await j(le(d)),c=await _(d,"wx",M)}this.current={path:i,left:a,sha256:s,hash:m("sha256"),...c!==void 0?{handle:c}:{},...h?{held:[]}:{}},a===0&&await this.endEntry()}async endEntry(){let e=this.current;if(e!==void 0){if(this.current=void 0,e.handle!==void 0)try{await e.handle.sync()}finally{await e.handle.close()}if(e.hash.digest("hex")!==e.sha256)throw f(`holds ${e.path} with other bytes than its sha256 says`);e.held!==void 0&&(this.portable=Buffer.concat(e.held)),this.hashes.push([e.path,e.sha256])}}async close(){await this.current?.handle?.close().catch(()=>{})}ended(){if(!this.end||this.current!==void 0)throw f("is cut short");if(this.bytes!==this.header.bytes)throw f("holds other bytes than its header says");if(this.portable===void 0)throw f("holds no checkpoint.json");return{portable:this.portable,hashes:this.hashes}}};function ot(n,e,t){let r;try{r=JSON.parse(n.portable.toString("utf8"))}catch{throw f("holds a checkpoint.json that does not read")}if(!fe(r)||!fe(r.org))throw f("holds a checkpoint.json that does not read");let o=J.safeParse({...H(r,Be),org:{...H(r.org,Ae),...t.alias!==void 0?{alias:t.alias}:{}},takenOn:t.takenOn,expiresAt:q(t.now,t.keepDays),bytes:0,importedFrom:{at:t.now.toISOString(),sandforgeVersion:e.header.sandforgeVersion,sha256:n.sha256}});if(!o.success)throw f("holds a checkpoint.json that does not parse");let i=o.data,{header:a}=e;if(i.checkpointId!==a.checkpointId||B(i.org.organizationId)!==B(a.organizationId)||i.takenAt!==a.takenAt||i.status!=="ready"||Ie(i)!==a.records||i.objects.length!==a.objects)throw f("holds another checkpoint than its header says");return i}function fe(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}async function it(n,e,t){let r=await V(n);if(r===void 0){if(t.formatVersion===2)throw f("says it carries a replay annex, and holds none");return}if(t.formatVersion!==2)throw f("carries a replay annex, which its file format does not");if(B(r.organizationId)!==B(e.org.organizationId))throw f("holds the replay annex of another org");let o=e.replayAnnex,i=ae(r);if(o!==void 0&&(o.recordTypes!==i.recordTypes||o.users!==i.users||o.queues!==i.queues||o.standardPricebook!==i.standardPricebook))throw f("holds another replay annex than its checkpoint counts")}var at=".received";function st(n){return ue(n,at)}async function Ot(n){let e=await ve(n.file);if("refusal"in e)return{imported:!1,refusal:e.refusal};let t=st(n.storeRoot),r=re({root:t,...n.locksDir!==void 0?{locksDir:n.locksDir}:{}});if("refusal"in r)throw new Error(`The checkpoints of files received cannot be kept in ${t}: ${te(r.refusal,t,"Another store")} ${g}`);let o=await Qe({store:r.store,file:n.file,read:e.read,key:n.key,keepDays:n.keepDays,takenOn:n.takenOn,...n.now!==void 0?{now:n.now}:{},...n.freeBytes!==void 0?{freeBytes:n.freeBytes}:{}});return o.imported?{...o,store:r.store}:o}export{bt as a,De as b,Bt as c,At as d,Et as e,I as f,Je as g,xt as h,ve as i,Qe as j,st as k,Ot as l};
@@ -4,6 +4,6 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{A as n}from"./chunk-7EANH5PY.mjs";var d="OTHER_ORG",f="RUN_WRITING";function R({code:e,message:r}){return`refused (${e}): ${r}`}function l({code:e,message:r},t="a real run"){return`${t} would be refused (${e}): ${r}`}function g(e){return e.length>0?{wouldBeRefused:e.map(({message:r})=>r),wouldBeRefusedCodes:e.map(({code:r})=>r)}:{}}function c(e,r,t=[]){let{tool:u,source:s,target:o,elapsedMs:i}=e;return`${JSON.stringify({tool:u,...s!==void 0?{source:s}:{},target:o,dryRun:e.dryRun===!0,refused:r,...t.length>0?{alsoRefused:t}:{},...e.apiRequests!==void 0?{apiRequests:e.apiRequests}:{},elapsedMs:i},null,2)}
7
+ import{A as n}from"./chunk-WZQEK4WT.mjs";var d="OTHER_ORG",f="RUN_WRITING";function R({code:e,message:r}){return`refused (${e}): ${r}`}function l({code:e,message:r},t="a real run"){return`${t} would be refused (${e}): ${r}`}function g(e){return e.length>0?{wouldBeRefused:e.map(({message:r})=>r),wouldBeRefusedCodes:e.map(({code:r})=>r)}:{}}function c(e,r,t=[]){let{tool:u,source:s,target:o,elapsedMs:i}=e;return`${JSON.stringify({tool:u,...s!==void 0?{source:s}:{},target:o,dryRun:e.dryRun===!0,refused:r,...t.length>0?{alsoRefused:t}:{},...e.apiRequests!==void 0?{apiRequests:e.apiRequests}:{},elapsedMs:i},null,2)}
8
8
  `}function m(e,r){let{tool:t,action:u="remove",summary:s,target:o,elapsedMs:i}=e;return`${JSON.stringify({tool:t,action:u,summary:s,target:o,refused:r,elapsedMs:i},null,2)}
9
9
  `}function p(e,r){let t=n.object({tool:n.literal(r),dryRun:n.literal(!1),refused:n.object({code:n.string().min(1),message:n.string()}),result:n.never().optional()}).safeParse(e);return t.success?t.data.refused:void 0}function y(e,r){let t=n.object({tool:n.literal(r),dryRun:n.literal(!0),refused:n.object({code:n.string().min(1),message:n.string()}),result:n.never().optional()}).safeParse(e);return t.success?t.data.refused:void 0}function w({code:e},r="remove"){return`is the summary of a run refused before its first write (${e}), which wrote nothing to the target: there is nothing of it to ${r}.`}export{d as a,f as b,R as c,l as d,g as e,c as f,m as g,p as h,y as i,w as j};