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
@@ -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{Ub as o,Xc as d}from"./chunk-ZQO5PDX5.mjs";var u=new Set(["picklist","multipicklist"]);function c(a){return(a.picklistValues??[]).filter(s=>s.active!==!1&&typeof s.value=="string"&&s.value!=="").map(s=>s.value)}function m(a){let s=new Map,r=i=>{let t=s.get(i);return t||(t=a(i),s.set(i,t)),t};return{async createable(i){let{fields:t}=await r(i);return new Set(t.filter(e=>e.createable===!0).map(e=>e.name))},async visible(i){let{fields:t}=await r(i);return new Set(t.map(e=>e.name))},async computed(i){let{fields:t}=await r(i);return new Set(t.filter(e=>e.calculated===!0||e.autoNumber===!0).map(e=>e.name))},async picklistValues(i){let{fields:t}=await r(i),e=new Map;for(let n of t){if(!u.has(n.type??""))continue;let l=c(n);l.length>0&&e.set(n.name,l)}return e},async keyPrefix(i){let{keyPrefix:t}=await r(i);return typeof t=="string"&&t.length===3?t:void 0},async lengths(i){let{fields:t}=await r(i);return new Map(t.flatMap(e=>typeof e.length=="number"&&e.length>0?[[e.name,e.length]]:[]))},async unset(i){let{fields:t}=await r(i),e=n=>n.type==="reference"||(n.referenceTo??[]).length>0;return{empty:new Set(t.filter(n=>e(n)&&n.nillable===!0&&n.defaultedOnCreate!==!0).map(n=>n.name)),filled:new Set(t.filter(n=>n.nillable===!1||n.defaultedOnCreate===!0).map(n=>n.name))}},async required(i){let{fields:t}=await r(i);return t.filter(e=>e.createable===!0&&e.nillable===!1&&e.defaultedOnCreate!==!0&&(e.referenceTo??[]).length===0).map(e=>({fieldApiName:e.name,type:e.type??"string",picklistValues:c(e),referenceTo:[],length:e.length??0,integerDigits:o({...e,type:e.type??"string"}),objectApiName:i,required:!0}))}}}function p(a,s){return async r=>(await a.required(r)).filter(i=>!d(r,i.fieldApiName,s.includes(r)?"person":"business"))}export{m as a,p as b};
@@ -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{Ab as O,zb as S}from"./chunk-TTFDUKUS.mjs";import{b as y,f as b,l as R}from"./chunk-7EANH5PY.mjs";var v=["User","Group","Profile","UserRole","RecordType","Organization","Queue","PermissionSet","BusinessProcess","CurrencyType","DandBCompany","DuplicateRecordItem","DuplicateRecordSet","ProcessInstance","LoginHistory","LoginEvent","LoginIp","LoginGeo","AsyncApexJob","ApexLog","ApexTestResult","ApexTestQueueItem","LightningUsageByPageMetrics","LightningExitByPageMetrics","EventBusSubscriber","PlatformEventUsageMetric","CronTrigger","CronJobDetail","AttachedContentDocument","AttachedContentNote","CombinedAttachment","ContentBody","NoteAndAttachment","OwnedContentDocument","EntitySubscription","TopicAssignment","UserRecordAccess","DeclinedEventRelation","UndecidedEventRelation","AcceptedEventRelation","OpenActivity","ActivityHistory","AppUsageAssignment","AuthProvider","Folder","ContentDocument","ContentDocumentLink","OpportunityRelatedDeleteLog","CaseHistory2","Calendar","SlaProcess","AccountCleanInfo","ContactCleanInfo","LeadCleanInfo","ApprovalSubmission","ApprovalSubmissionDetail","ApprovalWorkItem","AIRecordInsight","AIInsightValue","MatchingInformation","Invoice","InvoiceLine","CreditMemo","CreditMemoLine","AppDefinition","BackgroundOperation","ContentTaxonomyTermRelationshipType","Dashboard","DashboardComponent","DeleteEvent","ManagedContentChannel","ManagedContentSpace","ManagedContentVariant","Report","ServiceSetupProvisioning","TabDefinition"],P=new Set(v.map(e=>e.toLowerCase())),W=["History","Feed","Share","ChangeEvent","__hd","__Tag","EventStore"].map(e=>e.toLowerCase()),F=/^vlocity_[a-z0-9]+__/;function B(e,t){return I(e,t,{byNamespace:!0})}function I(e,t,r){let n=e.toLowerCase();return P.has(n)||S(e)||t&&(t.has(e)||U(t).has(n))||r.byNamespace&&F.test(n)?!0:W.some(i=>n.endsWith(i))}var w=new WeakMap;function U(e){let t=w.get(e);if(t&&t.size===e.size)return t.names;let r=new Set([...e].map(n=>n.toLowerCase()));return w.set(e,{size:e.size,names:r}),r}function z(e,t){return O(e)||B(e,t)}function E(e){return O(e)||I(e,void 0,{byNamespace:!1})}function x(e,t=[]){let r=new Set(t);for(let n of e)n.createable===!1&&r.add(n.name);return r}function le(e,t=r=>z(r)){return new Set(e.filter(r=>{let n=r.referenceTo??[];return n.length>0&&n.every(i=>t(i))}).map(r=>r.name))}var ge=R({name:y(),queryable:b().optional(),createable:b().optional(),updateable:b().optional(),deletable:b().optional(),undeletable:b().optional(),customSetting:b().optional(),layoutable:b().optional(),keyPrefix:y().nullish()}).loose(),D="ContentDocument",H="ContentDocumentLink",G="ContentVersion",L="Attachment",J=[D,L],K={AccountContactRelation:["Contact"]},V=new Set(["feeditem","feedcomment","feedattachment"]),X=new Set(["casehistory2"]),Y=new Set(["AccountCleanInfo","ContactCleanInfo","LeadCleanInfo","ApprovalSubmission","ApprovalSubmissionDetail","ApprovalWorkItem","ProcessInstance","ProcessInstanceNode","ProcessInstanceStep","ProcessInstanceWorkitem","AIRecordInsight","AIInsightValue","AIInsightAction","AIInsightFeedback","AIInsightReason","MatchingInformation","Invoice","InvoiceLine","CreditMemo","CreditMemoLine","CreditMemoInvApplication"].map(e=>e.toLowerCase())),Q=new Set([G,H].map(e=>e.toLowerCase())),Z=["__b","__x","__dlm","__kav","__ka","__e"],$=new Set(["AccountContactRole",L,"CaseTeamMember","EmailMessageRelation","EventRelation","OpportunityCompetitor"].map(e=>e.toLowerCase()));function q(e,t,r,n,i){let o=e.name.toLowerCase();return V.has(o)||o.endsWith("feed")?"chatter":o.endsWith("history")||o.endsWith("__hd")||X.has(o)?"history":o.endsWith("share")?"sharing":o.endsWith("changeevent")?"changeEvent":Z.some(c=>o.endsWith(c))?"unsupportedKind":e.customSetting===!0?n?A(e,i)?void 0:"notWritable":"customSetting":Q.has(o)?"heldWithFiles":o===D.toLowerCase()?(i==="delete"?_(e):T(e))?void 0:"notWritable":o===L.toLowerCase()?A(e,i)?void 0:"notWritable":S(e.name)?"files":Y.has(o)?"platformCreated":E(e.name)||r==="everything"&&e.layoutable===!1&&!$.has(o)?"setup":t.out.has(o)?t.tooling.has(o)?"metadata":"notWritable":A(e,i)?void 0:"notWritable"}function A(e,t){return t==="delete"?_(e):ee(e)}function ee(e){return e.createable===!0&&T(e)}function _(e){return e.queryable===!0&&e.deletable===!0}function T(e){return e.queryable===!0&&e.updateable===!0&&e.deletable===!0}function k(e,t){return e.objectApiName<t.objectApiName?-1:e.objectApiName>t.objectApiName?1:0}var te="all";function ne(e){return e.customSetting===!0}function oe(e,t){let r=e.filter(ne);if(t===void 0)return{held:new Set,unknown:[]};if(t===te)return{held:new Set(r.map(c=>c.name.toLowerCase())),unknown:[]};let n=new Set(r.map(c=>c.name.toLowerCase())),i=new Set,o=[];for(let c of t){let p=c.toLowerCase();i.has(p)||o.some(u=>u.toLowerCase()===p)||(n.has(p)?i.add(p):o.push(c))}return{held:i,unknown:o}}function he(e,t,r=[]){let n=t.access??"write",i=n==="delete"?r:x(e,r),o={out:new Set([...i].map(a=>a.toLowerCase())),tooling:new Set(r.map(a=>a.toLowerCase()))},c=new Set((t.excluded??[]).map(a=>a.toLowerCase())),p=new Map(e.map(a=>[a.name.toLowerCase(),a])),u=oe(e,t.customSettings),h=u.unknown.map(a=>({objectApiName:a,reason:"notCustomSetting"})),g=[],f=[],s=[];if(t.mode==="picked"){let a=new Set;for(let d of t.objects??[]){let l=d.toLowerCase();if(a.has(l))continue;a.add(l);let m=p.get(l);m?f.push(m):h.push({objectApiName:d,reason:"notFound"})}for(let d of J){let l=d.toLowerCase(),m=p.get(l);if(!(a.has(l)||m===void 0)){if(c.has(l)){h.push({objectApiName:m.name,reason:"excludedByUser"});continue}f.push(m),s.push(m.name)}}for(let[d,l]of Object.entries(K)){let m=d.toLowerCase(),C=p.get(m);if(!(a.has(m)||C===void 0)&&l.some(j=>a.has(j.toLowerCase()))){if(a.add(m),c.has(m)){h.push({objectApiName:C.name,reason:"excludedByUser"});continue}f.push(C)}}for(let d of u.held){let l=p.get(d);a.has(d)||l===void 0||(a.add(d),f.push(l))}}else f.push(...p.values());for(let a of f){let d=a.name.toLowerCase(),l=c.has(d)?"excludedByUser":q(a,o,t.mode,u.held.has(d),n);l===void 0?g.push(a.name):h.push({objectApiName:a.name,reason:l})}return g.sort(),h.sort(k),{mode:t.mode,candidates:g,leftOut:h,addedToPicked:s}}function be(e){return e.fields.find(r=>r.name==="Name")?.nillable===!0?"hierarchy":"list"}function Ce(e){return e==="hierarchy"?"SetupOwnerId":"Name"}function Se(e){return e.objects.some(t=>t.customSetting!==void 0)}function re(e){let t=e.split("__");return t.length>=3&&t[0]!==""?t[0]:void 0}var se=()=>({first:"child",firmness:0});function ie(e,t,r=se){let n=new Map(e.map((o,c)=>[o.toLowerCase(),c])),i=e.map(()=>new Map);return e.forEach((o,c)=>{for(let p of t.get(o)?.childRelationships??[]){let u=n.get(p.childSObject.toLowerCase());if(u===void 0||u===c)continue;let h=r(p);if(h===void 0)continue;let[g,f]=h.first==="child"?[u,c]:[c,u],s=i[g].get(f);(s===void 0||h.firmness>s)&&i[g].set(f,h.firmness)}}),N(e.map((o,c)=>c),i,Number.NEGATIVE_INFINITY).map(o=>e[o])}function N(e,t,r){let n=new Set(e),i=f=>[...t[f]].filter(([s,a])=>n.has(s)&&a>r).map(([s])=>s),o=ae(e,i,t.length),c=new Map;o.forEach((f,s)=>{for(let a of f)c.set(a,s)});let p=o.map(()=>0),u=o.map(()=>new Set);for(let f of e){let s=c.get(f)??0;for(let a of i(f)){let d=c.get(a)??0;d===s||u[s].has(d)||(u[s].add(d),p[d]++)}}let h=o.map(()=>!1),g=[];for(let f=o.length;f>0;f--){let s=-1;for(let d=0;d<o.length;d++){if(h[d]||p[d]>0)continue;let l=o[d].length===1,m=s>=0&&o[s].length===1;(s<0||l&&!m||l===m&&o[d][0]<o[s][0])&&(s=d)}h[s]=!0;let a=o[s];if(a.length===1)g.push(a[0]);else{let d=Number.POSITIVE_INFINITY;for(let l of a)for(let[m,C]of t[l])C>r&&c.get(m)===s&&C<d&&(d=C);g.push(...N(a,t,d))}for(let d of u[s])p[d]--}return g}function ae(e,t,r){let n=new Array(r).fill(-1),i=new Array(r).fill(0),o=new Array(r).fill(!1),c=[],p=[],u=0;for(let h of e){if(n[h]>=0)continue;let g=[],f=s=>{n[s]=u,i[s]=u,u++,c.push(s),o[s]=!0,g.push({node:s,edges:t(s),at:0})};for(f(h);g.length>0;){let s=g[g.length-1];if(s.at<s.edges.length){let l=s.edges[s.at++];n[l]<0?f(l):o[l]&&(i[s.node]=Math.min(i[s.node],n[l]));continue}g.pop();let a=g[g.length-1];if(a&&(i[a.node]=Math.min(i[a.node],i[s.node])),i[s.node]!==n[s.node])continue;let d=[];for(let l=c.pop();l!==void 0&&(o[l]=!1,d.push(l),l!==s.node);l=c.pop());p.push(d.sort((l,m)=>l-m))}}return p}function M(e){let t=new Map;for(let{objectApiName:r,namespace:n}of e)n!==void 0&&t.set(n,[...t.get(n)??[],r]);return[...t].sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>({namespace:r,objects:n.sort()}))}function ce(e,t){return ie(e,t).map((r,n)=>{let i=re(r);return{objectApiName:r,readOrder:n,...i===void 0?{}:{namespace:i}}})}function ye(e,t,r=new Map){let n=[...e.leftOut],i=[];for(let c of e.candidates){let p=t.get(c);if(p)p.fields.some(u=>u.name==="SystemModstamp")?p.fields.some(u=>u.name==="IsDeleted")?i.push(c):n.push({objectApiName:c,reason:"noRecycleBin"}):n.push({objectApiName:c,reason:"noSystemModstamp"});else{let u=r.get(c);n.push({objectApiName:c,reason:"notDescribed",...u===void 0?{}:{detail:u}})}}let o=ce(i,t);return{mode:e.mode,objects:o,leftOut:n.sort(k),packages:M(o)}}function Oe(e,t){if(t.size===0)return e;let r=[...e.leftOut],n=[];for(let i of e.objects){let o=t.get(i.objectApiName);o===void 0?n.push({...i,readOrder:n.length}):r.push({objectApiName:i.objectApiName,reason:"unreadable",detail:o})}return{...e,objects:n,leftOut:r.sort(k),packages:M(n)}}export{B as a,z as b,E as c,x as d,le as e,ge as f,D as g,H as h,G as i,L as j,J as k,te as l,ne as m,he as n,be as o,Ce as p,Se as q,re as r,ie as s,ye as t,Oe as u};
7
+ import{jc as S,kc as O}from"./chunk-ZQO5PDX5.mjs";import{b as y,f as b,l as R}from"./chunk-WZQEK4WT.mjs";var v=["User","Group","Profile","UserRole","RecordType","Organization","Queue","PermissionSet","BusinessProcess","CurrencyType","DandBCompany","DuplicateRecordItem","DuplicateRecordSet","ProcessInstance","LoginHistory","LoginEvent","LoginIp","LoginGeo","AsyncApexJob","ApexLog","ApexTestResult","ApexTestQueueItem","LightningUsageByPageMetrics","LightningExitByPageMetrics","EventBusSubscriber","PlatformEventUsageMetric","CronTrigger","CronJobDetail","AttachedContentDocument","AttachedContentNote","CombinedAttachment","ContentBody","NoteAndAttachment","OwnedContentDocument","EntitySubscription","TopicAssignment","UserRecordAccess","DeclinedEventRelation","UndecidedEventRelation","AcceptedEventRelation","OpenActivity","ActivityHistory","AppUsageAssignment","AuthProvider","Folder","ContentDocument","ContentDocumentLink","OpportunityRelatedDeleteLog","CaseHistory2","Calendar","SlaProcess","AccountCleanInfo","ContactCleanInfo","LeadCleanInfo","ApprovalSubmission","ApprovalSubmissionDetail","ApprovalWorkItem","AIRecordInsight","AIInsightValue","MatchingInformation","Invoice","InvoiceLine","CreditMemo","CreditMemoLine","AppDefinition","BackgroundOperation","ContentTaxonomyTermRelationshipType","Dashboard","DashboardComponent","DeleteEvent","ManagedContentChannel","ManagedContentSpace","ManagedContentVariant","Report","ServiceSetupProvisioning","TabDefinition"],P=new Set(v.map(e=>e.toLowerCase())),W=["History","Feed","Share","ChangeEvent","__hd","__Tag","EventStore"].map(e=>e.toLowerCase()),F=/^vlocity_[a-z0-9]+__/;function B(e,t){return I(e,t,{byNamespace:!0})}function I(e,t,r){let n=e.toLowerCase();return P.has(n)||S(e)||t&&(t.has(e)||U(t).has(n))||r.byNamespace&&F.test(n)?!0:W.some(i=>n.endsWith(i))}var w=new WeakMap;function U(e){let t=w.get(e);if(t&&t.size===e.size)return t.names;let r=new Set([...e].map(n=>n.toLowerCase()));return w.set(e,{size:e.size,names:r}),r}function z(e,t){return O(e)||B(e,t)}function E(e){return O(e)||I(e,void 0,{byNamespace:!1})}function x(e,t=[]){let r=new Set(t);for(let n of e)n.createable===!1&&r.add(n.name);return r}function le(e,t=r=>z(r)){return new Set(e.filter(r=>{let n=r.referenceTo??[];return n.length>0&&n.every(i=>t(i))}).map(r=>r.name))}var ge=R({name:y(),queryable:b().optional(),createable:b().optional(),updateable:b().optional(),deletable:b().optional(),undeletable:b().optional(),customSetting:b().optional(),layoutable:b().optional(),keyPrefix:y().nullish()}).loose(),D="ContentDocument",H="ContentDocumentLink",G="ContentVersion",L="Attachment",J=[D,L],K={AccountContactRelation:["Contact"]},V=new Set(["feeditem","feedcomment","feedattachment"]),X=new Set(["casehistory2"]),Y=new Set(["AccountCleanInfo","ContactCleanInfo","LeadCleanInfo","ApprovalSubmission","ApprovalSubmissionDetail","ApprovalWorkItem","ProcessInstance","ProcessInstanceNode","ProcessInstanceStep","ProcessInstanceWorkitem","AIRecordInsight","AIInsightValue","AIInsightAction","AIInsightFeedback","AIInsightReason","MatchingInformation","Invoice","InvoiceLine","CreditMemo","CreditMemoLine","CreditMemoInvApplication"].map(e=>e.toLowerCase())),Q=new Set([G,H].map(e=>e.toLowerCase())),Z=["__b","__x","__dlm","__kav","__ka","__e"],$=new Set(["AccountContactRole",L,"CaseTeamMember","EmailMessageRelation","EventRelation","OpportunityCompetitor"].map(e=>e.toLowerCase()));function q(e,t,r,n,i){let o=e.name.toLowerCase();return V.has(o)||o.endsWith("feed")?"chatter":o.endsWith("history")||o.endsWith("__hd")||X.has(o)?"history":o.endsWith("share")?"sharing":o.endsWith("changeevent")?"changeEvent":Z.some(c=>o.endsWith(c))?"unsupportedKind":e.customSetting===!0?n?A(e,i)?void 0:"notWritable":"customSetting":Q.has(o)?"heldWithFiles":o===D.toLowerCase()?(i==="delete"?_(e):T(e))?void 0:"notWritable":o===L.toLowerCase()?A(e,i)?void 0:"notWritable":S(e.name)?"files":Y.has(o)?"platformCreated":E(e.name)||r==="everything"&&e.layoutable===!1&&!$.has(o)?"setup":t.out.has(o)?t.tooling.has(o)?"metadata":"notWritable":A(e,i)?void 0:"notWritable"}function A(e,t){return t==="delete"?_(e):ee(e)}function ee(e){return e.createable===!0&&T(e)}function _(e){return e.queryable===!0&&e.deletable===!0}function T(e){return e.queryable===!0&&e.updateable===!0&&e.deletable===!0}function k(e,t){return e.objectApiName<t.objectApiName?-1:e.objectApiName>t.objectApiName?1:0}var te="all";function ne(e){return e.customSetting===!0}function oe(e,t){let r=e.filter(ne);if(t===void 0)return{held:new Set,unknown:[]};if(t===te)return{held:new Set(r.map(c=>c.name.toLowerCase())),unknown:[]};let n=new Set(r.map(c=>c.name.toLowerCase())),i=new Set,o=[];for(let c of t){let p=c.toLowerCase();i.has(p)||o.some(u=>u.toLowerCase()===p)||(n.has(p)?i.add(p):o.push(c))}return{held:i,unknown:o}}function he(e,t,r=[]){let n=t.access??"write",i=n==="delete"?r:x(e,r),o={out:new Set([...i].map(a=>a.toLowerCase())),tooling:new Set(r.map(a=>a.toLowerCase()))},c=new Set((t.excluded??[]).map(a=>a.toLowerCase())),p=new Map(e.map(a=>[a.name.toLowerCase(),a])),u=oe(e,t.customSettings),h=u.unknown.map(a=>({objectApiName:a,reason:"notCustomSetting"})),g=[],f=[],s=[];if(t.mode==="picked"){let a=new Set;for(let d of t.objects??[]){let l=d.toLowerCase();if(a.has(l))continue;a.add(l);let m=p.get(l);m?f.push(m):h.push({objectApiName:d,reason:"notFound"})}for(let d of J){let l=d.toLowerCase(),m=p.get(l);if(!(a.has(l)||m===void 0)){if(c.has(l)){h.push({objectApiName:m.name,reason:"excludedByUser"});continue}f.push(m),s.push(m.name)}}for(let[d,l]of Object.entries(K)){let m=d.toLowerCase(),C=p.get(m);if(!(a.has(m)||C===void 0)&&l.some(j=>a.has(j.toLowerCase()))){if(a.add(m),c.has(m)){h.push({objectApiName:C.name,reason:"excludedByUser"});continue}f.push(C)}}for(let d of u.held){let l=p.get(d);a.has(d)||l===void 0||(a.add(d),f.push(l))}}else f.push(...p.values());for(let a of f){let d=a.name.toLowerCase(),l=c.has(d)?"excludedByUser":q(a,o,t.mode,u.held.has(d),n);l===void 0?g.push(a.name):h.push({objectApiName:a.name,reason:l})}return g.sort(),h.sort(k),{mode:t.mode,candidates:g,leftOut:h,addedToPicked:s}}function be(e){return e.fields.find(r=>r.name==="Name")?.nillable===!0?"hierarchy":"list"}function Ce(e){return e==="hierarchy"?"SetupOwnerId":"Name"}function Se(e){return e.objects.some(t=>t.customSetting!==void 0)}function re(e){let t=e.split("__");return t.length>=3&&t[0]!==""?t[0]:void 0}var se=()=>({first:"child",firmness:0});function ie(e,t,r=se){let n=new Map(e.map((o,c)=>[o.toLowerCase(),c])),i=e.map(()=>new Map);return e.forEach((o,c)=>{for(let p of t.get(o)?.childRelationships??[]){let u=n.get(p.childSObject.toLowerCase());if(u===void 0||u===c)continue;let h=r(p);if(h===void 0)continue;let[g,f]=h.first==="child"?[u,c]:[c,u],s=i[g].get(f);(s===void 0||h.firmness>s)&&i[g].set(f,h.firmness)}}),N(e.map((o,c)=>c),i,Number.NEGATIVE_INFINITY).map(o=>e[o])}function N(e,t,r){let n=new Set(e),i=f=>[...t[f]].filter(([s,a])=>n.has(s)&&a>r).map(([s])=>s),o=ae(e,i,t.length),c=new Map;o.forEach((f,s)=>{for(let a of f)c.set(a,s)});let p=o.map(()=>0),u=o.map(()=>new Set);for(let f of e){let s=c.get(f)??0;for(let a of i(f)){let d=c.get(a)??0;d===s||u[s].has(d)||(u[s].add(d),p[d]++)}}let h=o.map(()=>!1),g=[];for(let f=o.length;f>0;f--){let s=-1;for(let d=0;d<o.length;d++){if(h[d]||p[d]>0)continue;let l=o[d].length===1,m=s>=0&&o[s].length===1;(s<0||l&&!m||l===m&&o[d][0]<o[s][0])&&(s=d)}h[s]=!0;let a=o[s];if(a.length===1)g.push(a[0]);else{let d=Number.POSITIVE_INFINITY;for(let l of a)for(let[m,C]of t[l])C>r&&c.get(m)===s&&C<d&&(d=C);g.push(...N(a,t,d))}for(let d of u[s])p[d]--}return g}function ae(e,t,r){let n=new Array(r).fill(-1),i=new Array(r).fill(0),o=new Array(r).fill(!1),c=[],p=[],u=0;for(let h of e){if(n[h]>=0)continue;let g=[],f=s=>{n[s]=u,i[s]=u,u++,c.push(s),o[s]=!0,g.push({node:s,edges:t(s),at:0})};for(f(h);g.length>0;){let s=g[g.length-1];if(s.at<s.edges.length){let l=s.edges[s.at++];n[l]<0?f(l):o[l]&&(i[s.node]=Math.min(i[s.node],n[l]));continue}g.pop();let a=g[g.length-1];if(a&&(i[a.node]=Math.min(i[a.node],i[s.node])),i[s.node]!==n[s.node])continue;let d=[];for(let l=c.pop();l!==void 0&&(o[l]=!1,d.push(l),l!==s.node);l=c.pop());p.push(d.sort((l,m)=>l-m))}}return p}function M(e){let t=new Map;for(let{objectApiName:r,namespace:n}of e)n!==void 0&&t.set(n,[...t.get(n)??[],r]);return[...t].sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>({namespace:r,objects:n.sort()}))}function ce(e,t){return ie(e,t).map((r,n)=>{let i=re(r);return{objectApiName:r,readOrder:n,...i===void 0?{}:{namespace:i}}})}function ye(e,t,r=new Map){let n=[...e.leftOut],i=[];for(let c of e.candidates){let p=t.get(c);if(p)p.fields.some(u=>u.name==="SystemModstamp")?p.fields.some(u=>u.name==="IsDeleted")?i.push(c):n.push({objectApiName:c,reason:"noRecycleBin"}):n.push({objectApiName:c,reason:"noSystemModstamp"});else{let u=r.get(c);n.push({objectApiName:c,reason:"notDescribed",...u===void 0?{}:{detail:u}})}}let o=ce(i,t);return{mode:e.mode,objects:o,leftOut:n.sort(k),packages:M(o)}}function Oe(e,t){if(t.size===0)return e;let r=[...e.leftOut],n=[];for(let i of e.objects){let o=t.get(i.objectApiName);o===void 0?n.push({...i,readOrder:n.length}):r.push({objectApiName:i.objectApiName,reason:"unreadable",detail:o})}return{...e,objects:n,leftOut:r.sort(k),packages:M(n)}}export{B as a,z as b,E as c,x as d,le as e,ge as f,D as g,H as h,G as i,L as j,J as k,te as l,ne as m,he as n,be as o,Ce as p,Se as q,re as r,ie as s,ye as t,Oe as u};
@@ -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{a as qr}from"./chunk-INIQ23K6.mjs";import{a as Gr}from"./chunk-ELFXJHU7.mjs";import{b as Kt}from"./chunk-W7U5E5ZL.mjs";import{$ as yt,C as _r,F as Wr,G as Ur,H as Br,U as zr,V as mt,W as wt,X as Jr,Y as Hr,_ as Kr,aa as Yr,c as Or,e as jr,f as Cr,h as xr,j as Ir,k as Er,u as Tr,x as Mr}from"./chunk-ZM6OJGIG.mjs";import{b as Fr,g as Pr}from"./chunk-MHMH6MTP.mjs";import{e as gt,m as Nr}from"./chunk-COFG7Q6R.mjs";import{a as Lr,f as Dr}from"./chunk-PJ5I73CK.mjs";import{a as ot,b as st}from"./chunk-5P4PHJRL.mjs";import{Na as We,O as De,Va as pr,Wa as ct,_ as hr,c as Xn,cb as gr,d as Zn,db as mr,g as at,gb as ut,h as rr,hb as Ue,i as or,ib as wr,j as sr,jb as lt,k as ir,kb as yr,l as dt,m as ar,n as dr,o as cr,ob as br,pb as Rr,q as ur,qb as kr,rb as Sr,s as lr,sb as ft,tb as vr,ub as $r,vb as Ar}from"./chunk-VS7ZXUII.mjs";import{k as Mn,n as _n}from"./chunk-OO6CLPEH.mjs";import{b as Ie,e as Ve}from"./chunk-BZ24IAP5.mjs";import{a as _t}from"./chunk-SCKUIE3R.mjs";import{a as Yt,b as Vt,c as Fe,d as Xt,e as Zt,g as Qt,h as en,j as tn}from"./chunk-AV5SWEHP.mjs";import{a as ht,c as pt}from"./chunk-I7O6C2B5.mjs";import{B as hn,Ec as En,wc as Cn,x as ln,y as fn}from"./chunk-2CNCDM56.mjs";import{qb as Qn,rb as er,xb as tr,y as Le,zb as nr}from"./chunk-4VS2V6WU.mjs";import{k as Vn}from"./chunk-6XYKJSGX.mjs";import{b as yn,l as In}from"./chunk-F43REJDZ.mjs";import{C as mn,N as Pe,Q as wn,U as rt,V as xn,a as nn}from"./chunk-JPUR2CFX.mjs";import{a as Ze,b as bn,c as kn,f as Sn,h as Qe,k as vn,l as $n,m as An,n as On,o as et,r as tt,t as nt,w as jn}from"./chunk-PZPJKATS.mjs";import{n as Nn}from"./chunk-G35N4P7D.mjs";import{b as xe,c as Se}from"./chunk-KDGMAGQR.mjs";import{B as le,s as Ne,t as Me,y as Pn,z as _e}from"./chunk-MFG4MUIO.mjs";import{B as ue,D as un,p as an}from"./chunk-EQNW3UC2.mjs";import{b as ke,c as Jt,g as Ye}from"./chunk-HS4YRX4J.mjs";import{i as on,v as sn}from"./chunk-ZUTYVST5.mjs";import{a as cn}from"./chunk-CU2INBND.mjs";import{a as dn}from"./chunk-YKKRIEH4.mjs";import{d as Rn}from"./chunk-TUACWKIH.mjs";import{Ca as zn,Ia as Jn,K as Wn,L as Un,P as Bn,Pa as Hn,S as fe,bb as Kn,cb as Yn,i as Xe,ka as qn,r as Tn,s as Fn,va as Gn,x as Dn,ya as it}from"./chunk-VYXMVJL5.mjs";import{ea as Ln}from"./chunk-CION3VMZ.mjs";import{a as te}from"./chunk-EADHKH3A.mjs";import{i as rn}from"./chunk-INIT2UKJ.mjs";import{h as gn}from"./chunk-L77FJZEP.mjs";import{j as pn}from"./chunk-GGD7ON3M.mjs";import{a as Ht,c as Ee,e as Te,g as fr}from"./chunk-MTMH6H2A.mjs";import{$b as Wt,Wc as qt,Xb as Dt,Yb as Ke,Yc as Gt,Zc as zt,lc as Ut,mc as Bt,yb as Lt}from"./chunk-TTFDUKUS.mjs";import{A as R}from"./chunk-7EANH5PY.mjs";import{b as ao}from"./chunk-MS4FJDFD.mjs";import{d as io}from"./chunk-NTOVCTRS.mjs";var Ro=io(ao());import{randomUUID as po}from"node:crypto";import{existsSync as ve,mkdirSync as go,readFileSync as $e,renameSync as mo,writeFileSync as wo}from"node:fs";import{dirname as yo,join as he,resolve as bo}from"node:path";var ko=`sandforge sync \u2014 run a Sync between two orgs, without the editor.
7
+ import{a as qr}from"./chunk-INIQ23K6.mjs";import{a as Gr}from"./chunk-2UU42PTD.mjs";import{b as Kt}from"./chunk-2JZGCCPG.mjs";import{$ as Kr,C as _r,F as Wr,G as Ur,H as Br,V as zr,W as mt,X as wt,Y as Jr,Z as Hr,aa as yt,ba as Yr,c as Or,e as jr,f as Cr,h as xr,j as Ir,k as Er,u as Tr,x as Mr}from"./chunk-A7JJWOLT.mjs";import{b as Fr,g as Pr}from"./chunk-ZXFL2MSN.mjs";import{a as Lr,f as Dr}from"./chunk-VYOYXTCU.mjs";import{e as gt,m as Nr}from"./chunk-52EXDVPN.mjs";import{Ab as Sr,Bb as ft,Cb as vr,Db as $r,Eb as Ar,Wa as De,Y as hr,cb as pr,d as at,db as ct,e as rr,f as or,g as sr,h as ir,i as dt,j as ar,k as dr,l as cr,lb as gr,mb as mr,n as ur,p as lr,pb as ut,qb as We,rb as wr,sb as lt,tb as yr,xb as br,yb as Rr,zb as kr}from"./chunk-3HEMJTAP.mjs";import{k as Mn,n as _n}from"./chunk-QAPVKPEC.mjs";import{a as _e,j as Xn,k as Zn}from"./chunk-BNKT3R3F.mjs";import{b as xe,e as Ve}from"./chunk-BZ24IAP5.mjs";import{a as _t}from"./chunk-SCKUIE3R.mjs";import{a as Yt,b as Vt,c as Te,d as Xt,e as Zt,g as Qt,h as en,j as tn}from"./chunk-6FARZYMJ.mjs";import{a as ht,c as pt}from"./chunk-MUEQRIK7.mjs";import{B as hn,Gc as En,x as ln,y as fn,yc as Cn}from"./chunk-ISSP2FZ5.mjs";import{h as ot,i as st}from"./chunk-XU25YA46.mjs";import{Wa as Qn,Xa as er,bb as tr,db as nr,m as Le}from"./chunk-P55MKIZX.mjs";import{k as Vn}from"./chunk-PYRZFUVU.mjs";import{b as yn,l as In}from"./chunk-O2PUGRNW.mjs";import{C as mn,N as Fe,Q as wn,a as nn}from"./chunk-7SDZR6SR.mjs";import{n as Nn}from"./chunk-WSUKC2U3.mjs";import{a as Ze,b as bn,c as kn,f as Sn,h as Qe,k as vn,l as $n,n as An,o as On,p as et,s as tt,u as nt,x as jn}from"./chunk-3SKLBRPL.mjs";import{c as rt,d as xn}from"./chunk-SAMWHL22.mjs";import{a as Pe,b as Ne,g as Pn,h as Me,j as fe}from"./chunk-HKUWHVI7.mjs";import{b as Ce,c as ke}from"./chunk-LHU6CPGE.mjs";import{a as Re,b as Jt,f as Ye}from"./chunk-ZUOPC4W2.mjs";import{b as Tn,c as Fn}from"./chunk-JQZTMFO7.mjs";import{$a as Un,$b as Gn,Ic as Kn,Jc as Yn,La as Dn,Pb as qn,_a as Wn,cc as it,eb as Bn,gc as zn,hb as he,i as Xe,mc as Jn,na as Ln,tc as Hn}from"./chunk-JFNLKHY6.mjs";import{i as rn}from"./chunk-INIT2UKJ.mjs";import{h as gn}from"./chunk-HFUDCNU5.mjs";import{b as co}from"./chunk-MS4FJDFD.mjs";import{D as le,F as un,p as an}from"./chunk-XZISAZA6.mjs";import{b as Ht,d as Ie,f as Ee,h as fr}from"./chunk-LCDPCUXS.mjs";import{a as re}from"./chunk-EADHKH3A.mjs";import{j as pn}from"./chunk-ZUTUYBNW.mjs";import{j as on,w as sn}from"./chunk-ICIYL45C.mjs";import{a as cn}from"./chunk-PR74GYVI.mjs";import{a as dn}from"./chunk-TMA34QMA.mjs";import{d as Rn}from"./chunk-TUACWKIH.mjs";import{$c as Bt,Ic as Dt,Jc as Ke,Jd as qt,Ld as Gt,Mc as Wt,Md as zt,_c as Ut,ic as Lt}from"./chunk-ZQO5PDX5.mjs";import{A as R}from"./chunk-WZQEK4WT.mjs";import{d as ao}from"./chunk-NTOVCTRS.mjs";var ko=ao(co());import{randomUUID as go}from"node:crypto";import{existsSync as Se,mkdirSync as mo,readFileSync as ve,renameSync as wo,writeFileSync as yo}from"node:fs";import{dirname as bo,join as pe,resolve as Ro}from"node:path";var So=`sandforge sync \u2014 run a Sync between two orgs, without the editor.
8
8
 
9
9
  Usage:
10
10
  npx sandforge sync \\
@@ -270,72 +270,72 @@ partial \u2014 records refused, or an object read up to --max-records-per-object
270
270
  a dry run's read among them \u2014 and --fail-on-partial was given; 130 a Ctrl-C
271
271
  stopped the run, 143 a SIGTERM (a CI job cancelled or timed out), 129 a
272
272
  SIGHUP: its file keeps what it created.
273
- `,So=["--object","--where","--operation","--batch-size","--files","--max-file-mb","--max-run-mb","--keep-contact-points"],_=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,vo=new Set(["SYNC_TARGET_UNWRITABLE",fe,it]),$o={switches:["--dry-run","--files","--keep-contact-points","--json","--fail-on-partial","--mute-automation","--accept-emails",...at.switches],values:["--source","--target","--object","--operation","--where","--batch-size","--max-records-per-object","--max-file-mb","--max-run-mb","--config-file","--store",...at.values]};function bt(t,r,e,n){if(t===void 0)return n;let s=Number(t);return(!/^\d+$/.test(t)||s<e.min||s>e.max)&&(process.stderr.write(`${r} takes a whole number from ${e.min} to ${e.max}, not "${t}".
274
- `),process.exit(2)),s}function Ao(t){let r=t.slice(2);(r.includes("--help")||r.includes("-h"))&&(process.stdout.write(ko),process.exit(0)),Ht(r,$o);let e=(S,$)=>{let b=r.indexOf(S);return b>=0&&b+1<r.length?r[b+1]:$},n=S=>{let $=[];for(let b=0;b<r.length;b++)r[b]===S&&b+1<r.length&&$.push(r[b+1]);return $},s=S=>r.includes(S),i=or(r),d=i!==void 0?{checkpointFirst:i}:{},u=bt(e("--max-records-per-object"),"--max-records-per-object",{min:1,max:5e4},5e4),l=e("--source"),a=e("--target");if(s("--config-file")){let S=e("--config-file"),$=e("--store");(!S||!$||!l||!a)&&(process.stderr.write(`--config-file wants the file, --store <dir> where it is kept between runs, --source and --target. Run with --help.
275
- `),process.exit(2));let b=So.filter(s);return b.length>0&&(process.stderr.write(`--config-file takes its objects, filters and files from the file: ${b.join(", ")} cannot be given with it.
276
- `),process.exit(2)),{source:l,target:a,objects:[],operation:"insert",where:{},batchSize:200,dryRun:s("--dry-run"),files:!1,maxRecordsPerObject:u,keepContactPoints:!1,json:s("--json"),failOnPartial:s("--fail-on-partial"),muteAutomation:s("--mute-automation"),acceptEmails:s("--accept-emails"),...d,configFile:S,store:$}}s("--store")&&(process.stderr.write(`--store keeps a saved configuration between runs: give it with --config-file.
273
+ `,vo=["--object","--where","--operation","--batch-size","--files","--max-file-mb","--max-run-mb","--keep-contact-points"],M=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,$o=new Set(["SYNC_TARGET_UNWRITABLE",he,it]),Ao={switches:["--dry-run","--files","--keep-contact-points","--json","--fail-on-partial","--mute-automation","--accept-emails",...at.switches],values:["--source","--target","--object","--operation","--where","--batch-size","--max-records-per-object","--max-file-mb","--max-run-mb","--config-file","--store",...at.values]};function bt(t,r,e,n){if(t===void 0)return n;let s=Number(t);return(!/^\d+$/.test(t)||s<e.min||s>e.max)&&(process.stderr.write(`${r} takes a whole number from ${e.min} to ${e.max}, not "${t}".
274
+ `),process.exit(2)),s}function Oo(t){let r=t.slice(2);(r.includes("--help")||r.includes("-h"))&&(process.stdout.write(So),process.exit(0)),Ht(r,Ao);let e=(S,A)=>{let b=r.indexOf(S);return b>=0&&b+1<r.length?r[b+1]:A},n=S=>{let A=[];for(let b=0;b<r.length;b++)r[b]===S&&b+1<r.length&&A.push(r[b+1]);return A},s=S=>r.includes(S),i=or(r),d=i!==void 0?{checkpointFirst:i}:{},u=bt(e("--max-records-per-object"),"--max-records-per-object",{min:1,max:5e4},5e4),l=e("--source"),a=e("--target");if(s("--config-file")){let S=e("--config-file"),A=e("--store");(!S||!A||!l||!a)&&(process.stderr.write(`--config-file wants the file, --store <dir> where it is kept between runs, --source and --target. Run with --help.
275
+ `),process.exit(2));let b=vo.filter(s);return b.length>0&&(process.stderr.write(`--config-file takes its objects, filters and files from the file: ${b.join(", ")} cannot be given with it.
276
+ `),process.exit(2)),{source:l,target:a,objects:[],operation:"insert",where:{},batchSize:200,dryRun:s("--dry-run"),files:!1,maxRecordsPerObject:u,keepContactPoints:!1,json:s("--json"),failOnPartial:s("--fail-on-partial"),muteAutomation:s("--mute-automation"),acceptEmails:s("--accept-emails"),...d,configFile:S,store:A}}s("--store")&&(process.stderr.write(`--store keeps a saved configuration between runs: give it with --config-file.
277
277
  `),process.exit(2));let f=n("--object");(!l||!a||f.length===0)&&(process.stderr.write(`Missing --source, --target or --object. Run with --help.
278
- `),process.exit(2));let g=f.map(S=>{let[$,b]=S.split(":");return _.test($)||(process.stderr.write(`Not an SObject API name: "${$}"
279
- `),process.exit(2)),ln($)&&(process.stderr.write(`${fn($,"give --files")}
280
- `),process.exit(2)),b!==void 0&&!_.test(b)&&(process.stderr.write(`Not a field API name: "${b}"
281
- `),process.exit(2)),{objectApiName:$,externalIdField:b}}),v=e("--operation","insert")??"insert";v!=="insert"&&v!=="upsert"&&v!=="update"&&(process.stderr.write(`--operation takes insert, upsert or update, not "${v}".
282
- `),process.exit(2));let k={};for(let S of n("--where")){let $=S.indexOf("="),b=$>0?S.slice(0,$):"";_.test(b)||(process.stderr.write(`--where wants "Object=clause", not "${S}".
283
- `),process.exit(2)),k[b]=S.slice($+1)}let y=e("--batch-size","200")??"200",j=Number(y);(!Number.isInteger(j)||j<1||j>1e4)&&(process.stderr.write(`--batch-size takes a whole number between 1 and 10000.
278
+ `),process.exit(2));let g=f.map(S=>{let[A,b]=S.split(":");return M.test(A)||(process.stderr.write(`Not an SObject API name: "${A}"
279
+ `),process.exit(2)),ln(A)&&(process.stderr.write(`${fn(A,"give --files")}
280
+ `),process.exit(2)),b!==void 0&&!M.test(b)&&(process.stderr.write(`Not a field API name: "${b}"
281
+ `),process.exit(2)),{objectApiName:A,externalIdField:b}}),$=e("--operation","insert")??"insert";$!=="insert"&&$!=="upsert"&&$!=="update"&&(process.stderr.write(`--operation takes insert, upsert or update, not "${$}".
282
+ `),process.exit(2));let k={};for(let S of n("--where")){let A=S.indexOf("="),b=A>0?S.slice(0,A):"";M.test(b)||(process.stderr.write(`--where wants "Object=clause", not "${S}".
283
+ `),process.exit(2)),k[b]=S.slice(A+1)}let y=e("--batch-size","200")??"200",C=Number(y);(!Number.isInteger(C)||C<1||C>1e4)&&(process.stderr.write(`--batch-size takes a whole number between 1 and 10000.
284
284
  `),process.exit(2)),!s("--files")&&(s("--max-file-mb")||s("--max-run-mb"))&&(process.stderr.write(`--max-file-mb and --max-run-mb go with --files.
285
- `),process.exit(2));let I=bt(e("--max-file-mb"),"--max-file-mb",{min:1,max:35}),U=bt(e("--max-run-mb"),"--max-run-mb",{min:1,max:2e3});return{source:l,target:a,objects:g,operation:v,where:k,batchSize:j,dryRun:s("--dry-run"),files:s("--files"),...I!==void 0?{maxFileMB:I}:{},...U!==void 0?{maxRunMB:U}:{},maxRecordsPerObject:u,keepContactPoints:s("--keep-contact-points"),json:s("--json"),failOnPartial:s("--fail-on-partial"),muteAutomation:s("--mute-automation"),acceptEmails:s("--accept-emails"),...d}}function Oo(t){let r=new Date().toISOString(),e=t.objects.map((n,s)=>({objectApiName:n.objectApiName,externalIdField:n.externalIdField,operation:n.externalIdField?"upsert":t.operation,fieldMappings:[],transformRules:[],excludedFields:[],addOnFields:[],batchSize:t.batchSize,where:t.where[n.objectApiName],insertOrder:s}));return{id:`cli-${Date.now()}`,name:"sandforge-sync",description:"Headless run",sourceOrgId:t.source,targetOrgId:t.target,direction:"source_to_target",mode:"full",objects:e,conflictStrategy:"source_wins",enableRollback:!1,createdAt:r,updatedAt:r,...t.files?{files:{maxFileSizeMB:t.maxFileMB??10,maxRunMB:t.maxRunMB??100}}:{},...t.keepContactPoints?{keepContactPoints:!0}:{}}}function jo(t,r){let e;try{e=JSON.parse(t)}catch{return{refusal:"is not JSON: give a Sync configuration as the panel saves one."}}if(typeof e!="object"||e===null||Array.isArray(e))return{refusal:"is not a Sync configuration: it holds no object."};let n=hn.safeParse({config:{...e,sourceOrgId:r.source,targetOrgId:r.target}});if(!n.success){let d=n.error.issues[0];return{refusal:`is not a configuration a run takes (${d.path.slice(1).join(".")||"configuration"}: ${d.message})`}}let s=n.data.config;if(s.id===void 0)return{refusal:"names no id: a saved configuration keeps its watermarks and the files it copied under its id."};let i=new Date().toISOString();return{config:{...s,id:s.id,createdAt:s.createdAt??i,updatedAt:s.updatedAt??i,objects:s.objects.map(d=>({...d,batchSize:d.batchSize??200}))}}}function Qr(t){return go(t,{recursive:!0}),new xr(Le(he(t,"configStore.json")))}function Co(t,r,e,n,s=!1,i=5e4){let d=a=>({query:async f=>a.query(f),queryMore:async f=>a.queryMore(f)}),u=a=>({pages:d(a),transport:a,create:async(f,g)=>a.sobject(f).create(g,{headers:Lt()})}),l=new Map;return{copy:Cr({[t.sourceOrgId]:u(r),[t.targetOrgId]:u(e)}),sourceIds:async(a,f)=>{let g=a.objectApiName;if(!_.test(g))throw new Error(`Not an SObject API name: ${g}`);let v=ue(a.where,f),{records:k}=await te(d(r),`SELECT Id FROM ${g}${v?` WHERE ${v}`:""}`,i);return k.flatMap(y=>typeof y.Id=="string"?[y.Id]:[])},store:n??{load:()=>l.size===0?{kind:"none"}:{kind:"stored",map:{version:1,entries:[...l.values()]}},record:(a,f)=>{l.set(`${f.sourceOrgId}|${f.targetOrgId}|${f.sourceId}`,f)}},...s?{deleteFromTarget:async(a,f)=>pn(await e.sobject(a).destroy(f),a).map(g=>({id:g.id,success:g.success,errors:g.errors}))}:{}}}function xo(t){let r=Ke({isSandbox:t.sandbox,edition:t.edition});return jr(new In,t.id,{orgType:r})}function Vr(t,r=5e4,e){return async(n,s,i)=>{let d=s.objectApiName;if(!_.test(d))throw new Error(`Not an SObject API name: ${d}`);let u=ue(s.where,i?.changedSince),l=u?` WHERE ${u}`:"",a={query:async y=>t.query(y),queryMore:async y=>t.queryMore(y)},g=(await t.sobject(d).describe()).fields.filter(y=>y.type!=="address"&&y.type!=="location").map(y=>y.name),v=!1,k=await rn(`SELECT ${(g.length>0?g:["Id"]).join(", ")} FROM ${d}${l}`,async y=>{let j=await te(a,y,r);return v||=j.truncated,j.records});return v&&(i?.onBoundReached?.(),e?.(d,k.length)),k}}function Io(t,r){let e=`${_t("clone")} --depth all --source ${r.source} --target ${r.target} --fit share --dry-run`;return t.map(n=>`${n.objectApiName}: the read of the source stopped at ${n.read} records (--max-records-per-object ${n.bound}): this run copied part of the object. `+_r("source",n.bound,{raise:"--max-records-per-object",sample:e}))}function Rt(t,r){return t==="success"&&r.length>0?"partial":t}function Eo(t,r){return async(e,n,s)=>{let i=n.objectApiName;if(!_.test(i))throw new Error(`Not an SObject API name: ${i}`);let d=ue(n.where,s?.changedSince),{totalSize:u}=await t.query(`SELECT COUNT() FROM ${i}${d?` WHERE ${d}`:""}`);return r===void 0?u:Math.min(u,r)}}function To(t){return async(r,e)=>{let n=r.objectApiName;if(!_.test(n))return 0;let s=ue(r.where,e?.changedSince);try{return(await t.query(`SELECT COUNT() FROM ${n} WHERE IsPersonAccount = true`+(s?` AND (${s})`:""))).totalSize}catch{return 0}}}function Fo(t){return async r=>{let e=r.objectApiName;if(!_.test(e))throw new Error(`Not an SObject API name: ${e}`);let n=ue(r.where,void 0),{records:s}=await te({query:async i=>t.query(i),queryMore:async i=>t.queryMore(i)},`SELECT Id FROM ${e}${n?` WHERE ${n}`:""}`);return s.flatMap(i=>typeof i.Id=="string"?[i.Id]:[])}}function Xr(t){if(t.go||t.code!==fe&&t.code!==Xe)return t;let{code:r,message:e,refusal:n}=t;return{...t,message:dr({code:r,message:e,...n?{refusal:n}:{}})}}var Po={notInTarget:"it has no such object, or the user the run writes as cannot see it",notCreateable:"the user the run writes as may not create its records",notUpdateable:"the user the run writes as may not edit its records",unread:"it did not describe the object",notAKey:"its upsert matches on a field that is neither an External ID nor an idLookup field"};function kt(t,r){return{...t??{},sent:r}}function eo(t,r){let e=t.notWritten??0,n=t.total>0?t.total:e,s=[`write gate: ${n-e} record(s) to write to ${r}, about ${Jn(t.storage.estimateMB)} MB of data storage`];for(let a of t.objects)s.push(` ${a.objectApiName.padEnd(42)}${String(a.rows).padStart(8)}`);e>0&&s.push(` of the ${n} a run counts from the source, ${e} would not be written: held back or refused, as each object says; what follows is measured on all of them`),t.alreadyCopied>0&&s.push(` not counted: ${t.alreadyCopied} record(s) an earlier run of this configuration copied, still in the target, left as they are`),(t.alreadyLinked??0)>0&&s.push(` not counted: ${t.alreadyLinked} record(s) an earlier run of this configuration linked to records the target held, left as they are`),(t.overwrites??0)>0&&s.push(` of them, up to ${t.overwrites} written by an update or an upsert over records ${r} holds: their values are kept first, and --remove puts them back`),(t.rolesLinked??0)>0&&s.push(` not counted: ${t.rolesLinked} OpportunityContactRole record(s) the platform writes itself with the opportunities the run creates, for their contact: the run links each and does not send it`),(t.rolesByThePlatform??0)>0&&s.push(` of them, up to ${t.rolesByThePlatform} OpportunityContactRole record(s) the platform writes itself with the opportunities the run creates, for their contact: the run links each and does not send it`);let{storage:i}=t;i.verdict==="unread"?s.push(` the data storage ${r} has left could not be read (${i.unread??""}): whether the records fit is not known`):i.remainingMB!==void 0&&i.maxMB!==void 0&&s.push(` data storage of ${r}: ${i.remainingMB} MB left of ${i.maxMB} MB`+(i.verdict==="exceeds"?": the records do not fit":i.verdict==="near"?": the records take more than 80 % of it":""));for(let a of t.emails){let f=a.objects.map(v=>`${v.perRecord} per ${v.objectApiName}`).join("; "),g=` emails: these records make ${r} send about ${Gn(a.emails,a.limit)} (${f})`+(a.alertsCounted?", its email alerts among them, as a Developer Edition counts them":"");s.push(a.verdict==="unread"?`${g}; what it has left today could not be read (${a.unread??""})`:a.verdict==="fits"?`${g}; it has ${a.remaining??"?"} of ${a.max??"?"} left today`:`${g}, more than the ${a.remaining??"?"} of ${a.max??"?"} it has left today`)}t.emailsUnread!==void 0&&s.push(` emails: not counted, ${t.emailsUnread} could not be read`),t.deliverability&&s.push(` ${zn(t.deliverability.reading)}`);let d=t.apiRequests;d&&(s.push(d.verdict==="unread"?` API requests: about ${d.estimate}; what ${r} has left today could not be read (${d.unread??""})`:` API requests: about ${d.estimate}, of the ${d.remaining??"?"} ${r} has left of its ${d.max??"?"} a day`+(d.verdict==="exceeds"?": more than it has left":d.verdict==="near"?": it would leave less than a tenth of them":"")),s.push(` ${Nn}`));for(let a of t.unwritable??[])s.push(` ${a.objectApiName}: ${a.rows} record(s) ${r} takes none of \u2014 ${Po[a.why]}${a.key!==void 0?` (${a.key})`:""}`);let u=new Set((t.unwritable??[]).map(({objectApiName:a})=>a)),l=({parent:a,field:f})=>`${f} names ${a} records ${u.has(a)?"left out":"held back"}`;for(let a of t.heldBack??[]){let f=a.parents??[a];s.push(` ${a.objectApiName}: ${a.rows} record(s) held back, not written \u2014 `+(f.length===1?`their ${l(f[0])}`:f.map(g=>`${g.rows} whose ${l(g)}`).join("; ")))}return t.aboveRecords!==void 0&&s.push(` more than ${t.aboveRecords} records: the panel asks before it writes (sandforge.safety.confirmAboveRecords)`),s}function to(t,r,e=!1){let n=t.flatMap(i=>i.recordTypeGiven?[i.recordTypeGiven]:[]),s=hr(n,r);return s.length>0&&r&&e&&s.push(" the permission sets a real run assigns to mute the automation may open other record types to the user it writes as: it reads them again once assigned, and its summary says what the target gave"),s}function no(t){return`${t} already linked by an earlier run of this configuration to records the target held, left as they are`}function No(t,r="the target",e=!1,n,s){let i=[`
286
- simulation: ${t.objects.length} object(s), nothing written`];if(t.writeOrder){i.push(` write order: ${t.writeOrder.objects.join(", ")}`);for(let d of t.writeOrder.moved)i.push(` ${d.objectApiName} after ${d.after}: its ${d.field} names one`);for(let d of t.writeOrder.cycles)i.push(` ${d.join(", ")} name each other: in this order, the lookup at the one written later is left empty`)}if(t.writeCheck){for(let u of eo(t.writeCheck,r))i.push(` ${u}`);for(let u of t.checkpoint?dt(t.checkpoint):[])i.push(` ${u}`);if(t.writeCheck.verdict==="refused"){let u=t.writeCheck,[l,a]=(u.unwritable??[]).length>0?["SYNC_TARGET_UNWRITABLE","the target takes none of the records of an object it writes"]:n!==void 0?[fe,n]:u.storage.verdict==="exceeds"?["SYNC_STORAGE_EXCEEDED","the records do not fit"]:u.apiRequests?.verdict==="exceeds"?[Bn,"it takes more API requests than the target has left today"]:[fe,u.checkpointUnread??"the checkpoint asked first is refused"];i.push(` a run would be refused before it writes (${l}): ${a}`)}else(t.writeCheck.unwritable??[]).length>0&&i.push(" a run of the command would be refused before it writes (SYNC_TARGET_UNWRITABLE): the target takes none of the records of an object it writes; leave it out of the configuration");let d=t.writeCheck.emails.some(u=>u.verdict==="exceeds");t.writeCheck.verdict!=="refused"&&d?i.push(" a run of the command would be refused before it writes (SYNC_EMAILS_EXCEEDED): past a daily email limit"):t.writeCheck.verdict!=="refused"&&s!==void 0&&i.push(` a run of the command would be refused before it writes (${it}): `+s)}t.writeCheckUnread!==void 0&&i.push(` the records to write could not be counted: ${t.writeCheckUnread}`);for(let d of t.objects){i.push(` ${d.objectApiName} (${d.operation}): ${d.read} read, would insert ${d.insert}, update ${d.update}, delete ${d.delete}, skip ${d.skipped}, refuse ${d.refused}`+(t.direction==="bidirectional"?`, ${d.conflicts} in conflict`:"")),d.alreadyCopied!==void 0&&i.push(` ${d.alreadyCopied} already copied by an earlier run of this configuration, left as they are`),d.alreadyLinked!==void 0&&i.push(` ${no(d.alreadyLinked)}`),(d.encryptedLeftOut??[]).length>0&&i.push(` ${ro(d.encryptedLeftOut??[])}`),d.conflictFields.length>0&&i.push(` differ on: ${d.conflictFields.join(", ")}`),d.files&&i.push(` files: would copy ${d.files.copied}, add ${d.files.versions} version(s), ${d.files.unchanged} unchanged, ${d.files.tooLarge+d.files.pastRunCap} skipped past the caps`);for(let u of d.notes)i.push(` ${u}`);if(d.validationRules&&d.validationRules.length>0){i.push(` ${d.validationRules.length} active validation rule(s) of the target, which a simulation cannot evaluate \u2014 a record one of them refuses is counted as written:`);for(let u of d.validationRules)i.push(` ${u.name}${u.field?` (${u.field})`:""}: ${u.message||"(no message)"}`)}}t.validationRulesUnread&&i.push(` the target's validation rules could not be listed (${t.validationRulesUnread}): any of them may refuse a record counted as written`);for(let d of to(t.objects,!0,e))i.push(` ${d}`);return t.cancelled&&i.push(" stopped by a cancel before its last object"),t.error&&i.push(` stopped at ${t.failedObject??"an object"}: ${t.error}`),i}var Mo=/^(PARENT_REFUSED|RECORD_TYPE_UNAVAILABLE|RECORD_TYPE_UNMAPPED):/;function _o(t){let r=t.slice(0,3);for(let e of t.slice(3))Mo.test(e)&&r.push(e);return r}var Lo={notInTarget:": the lookup held an id from the source org that the target does not have.",ownerRefusedEarlier:", left out from the start: the target refused the same owner earlier in this run, an id from the source org that the target does not have.",parentRefused:": the record it names, written after them, was refused in this run.",notSet:": the target refused setting it once the record it names was written",notReached:": the run was stopped before it was set, once the record it names was written."},Do={"validation-rule":"a validation rule of the target refused it","restricted-picklist":"a restricted picklist of the target refused its value","lookup-filter":"a lookup filter of the target refused the record it names","inactive-owner":"the target holds the owner it names inactive"};function Wo(t){let r=Uo(t),e=Math.max(0,(t.skipped??0)-r);return`${t.objectApiName}: ${t.processed??0} processed, ${t.success??0} succeeded, ${t.failed??0} failed, ${e} skipped`+(r>0?`, ${r} linked`:"")}function Uo(t){return(t.writtenByThePlatform?.records??0)+(t.linkedToExisting?.records??0)}function Bo(t){let r=[];(t.encryptedLeftOut??[]).length>0&&r.push(ro(t.encryptedLeftOut??[]));let e=t.linkedToExisting;e&&r.push(`${e.records} record(s) linked to a record the target holds, not written: the target refused them as a duplicate of it${e.refusal?` (${e.refusal})`:""}; what the run writes under them points at that record.`);let n=t.writtenByThePlatform;n&&r.push(`${n.records} record(s) linked to the contact role the platform wrote with their opportunity, for its contact, not written; ${n.given} given the source's fields ${n.given===1?"it":"they"} lacked`+(n.refusal?`, the others left as the platform wrote them (${n.refusal}).`:"."));for(let{records:d,fields:u,reason:l,refusal:a}of t.lookupsLeftOut??[]){let f=l==="notSet"?`${a?` (${a})`:""}.`:"";r.push(`${d} record(s) written without ${u.join(", ")}${Lo[l]}${f}`)}let s=t.lookupsSetAfter;s&&r.push(`${s.records} record(s) given ${s.fields.join(", ")} by a second write once ${s.after.join(", ")} ${s.after.length===1?"was":"were"} written: the objects name each other, and no order writes both first.`);let i=t.writtenWithoutFields;return i&&r.push(`${i.rows} record(s) written again without the fields the target refused them on:`,...i.fields.map(({field:d,rows:u,refusedBy:l="validation-rule",reason:a})=>` ${u} without ${d}: ${Do[l]}, ${a}`)),r}function ro(t){return`${t.join(", ")}: encrypted, and read masked by the user the source is read as (it lacks View Encrypted Data): left out of every record written, never copied as masks`}function qo(t){return t?t.neutralized?[`emails and phone numbers: ${t.values} value(s) in ${t.fields.length} field(s) neutralized, addresses under .invalid and numbers fictional, so what the target's automation sends to them reaches no one`,...t.fields.map(({objectApiName:r,field:e,values:n})=>` ${r}.${e} ${n}`),...t.numbersExhausted?[` ${t.numbersExhausted} phone number(s) left out, their field empty: the 10 000 fictional numbers were all given to other numbers of the run`]:[]]:["emails and phone numbers: written as read (--keep-contact-points): the target's automation may have emailed or texted the people the records name"]:[]}function Go(t){return(t??[]).map(r=>`${sn(r)}.`)}function zo(t,r=!1){return[...r?[Dr]:[],...Vn(t??[]).map(e=>`${e}.`)]}function Jo(t){let r=t.read==="delta"?`delta: ${t.changed} record(s) changed since ${t.since??"the last run"}`:`delta: read whole (${t.reason??"no watermark"}), ${t.changed} record(s)`,e=t.deletionsChecked?`, ${t.deleted} deleted as the source deleted them`+(t.deleteFailed>0?`, ${t.deleteFailed} refused`:""):"",n=t.recorded!==void 0?"; watermark recorded":"; watermark kept as it was: the next run reads from the same point",s=(t.lookupsOwed??0)>0?`, ${t.lookupsOwed} record(s) left without a lookup this run was to set among them`:"";return`${r}${e}${n}${s}`}function Ho(t){let r=new Map,e=new On,n=new Map,s=new Set,i,d,u,l=a=>{if(a<=0)return;let f=new Date().toISOString();d??=f,u=f};return{runId:t,sending:(a,f)=>l(f),writing:(a,f)=>l(f),answered:()=>{u=new Date().toISOString()},note:(a,f)=>{if(f.length===0)return;let g=f.filter(v=>{let k=v.slice(0,15);return s.has(k)?!1:(s.add(k),!0)});g.length>0&&r.set(a,[...r.get(a)??[],...g]),i=new Date().toISOString(),d??=i,u=i},touched:(a,f)=>{f<=0||(i=new Date().toISOString(),u=i)},overwriting:(a,f,g)=>{g.length!==0&&(e.candidates(a,f,g),l(g.length))},overwrote:(a,f)=>{e.answer(a,f),u=new Date().toISOString()},deleted:(a,f)=>{if(f.length===0)return;let g=n.get(a)??new Map;for(let v of f)g.has(v.slice(0,15))||g.set(v.slice(0,15),v);n.set(a,g),l(f.length)},overwrittenCount:()=>e.count,flush:async()=>{},created:()=>[...r].map(([a,f])=>({objectApiName:a,ids:[...f]})),lastWrittenAt:()=>i,firstWrittenAt:()=>d,lastWriteAt:()=>u,overwritten:()=>e.read(),deletions:()=>[...n].map(([a,f])=>({objectApiName:a,ids:[...f.values()]}))}}function Ko(t,r){return r?{runId:t.runId,note:(e,n,s)=>{t.note(e,n,s),r.note(e,n,s)},noteUnanswered:(e,n)=>{t.note(e,n),r.noteUnanswered?r.noteUnanswered(e,n):r.note(e,n)},sending:(e,n,s)=>{t.sending?.(e,n,s),r.sending?.(e,n,s)},answered:(e,n)=>{t.answered?.(e,n),r.answered?.(e,n)},writing:(e,n)=>{t.writing?.(e,n),r.writing?.(e,n)},touched:(e,n)=>{t.touched?.(e,n),r.touched?.(e,n)},overwriting:(e,n,s,i)=>{t.overwriting?.(e,n,s),r.overwriting?.(e,n,s,i)},overwrote:(e,n)=>{t.overwrote?.(e,n),r.overwrote?.(e,n)},deleted:(e,n)=>{t.deleted?.(e,n),r.deleted?.(e,n)},checkpoint:e=>{t.checkpoint?.(e),r.checkpoint?.(e)},overwrittenCount:()=>t.overwrittenCount?.()??r.overwrittenCount?.()??0,flush:async()=>await t.flush()??await r.flush()}:t}var St="sandforge-sync";function Yo(t,r){let e=new Set(r);return{...t,objectsRead:t.objectsRead.filter(n=>e.has(n)),objects:t.objects.filter(n=>e.has(n.objectApiName))}}async function Vo(t){try{let e=(await t.query("SELECT Id FROM Organization LIMIT 1")).records[0]?.Id;return typeof e=="string"?e:void 0}catch{return}}async function Xo(t=process.argv){if(t.slice(2).includes("--remove"))return gs(t);let r=Date.now(),e=Ao(t),n=o=>{e.json||process.stdout.write(`${o}
285
+ `),process.exit(2));let x=bt(e("--max-file-mb"),"--max-file-mb",{min:1,max:35}),U=bt(e("--max-run-mb"),"--max-run-mb",{min:1,max:2e3});return{source:l,target:a,objects:g,operation:$,where:k,batchSize:C,dryRun:s("--dry-run"),files:s("--files"),...x!==void 0?{maxFileMB:x}:{},...U!==void 0?{maxRunMB:U}:{},maxRecordsPerObject:u,keepContactPoints:s("--keep-contact-points"),json:s("--json"),failOnPartial:s("--fail-on-partial"),muteAutomation:s("--mute-automation"),acceptEmails:s("--accept-emails"),...d}}function jo(t){let r=new Date().toISOString(),e=t.objects.map((n,s)=>({objectApiName:n.objectApiName,externalIdField:n.externalIdField,operation:n.externalIdField?"upsert":t.operation,fieldMappings:[],transformRules:[],excludedFields:[],addOnFields:[],batchSize:t.batchSize,where:t.where[n.objectApiName],insertOrder:s}));return{id:`cli-${Date.now()}`,name:"sandforge-sync",description:"Headless run",sourceOrgId:t.source,targetOrgId:t.target,direction:"source_to_target",mode:"full",objects:e,conflictStrategy:"source_wins",enableRollback:!1,createdAt:r,updatedAt:r,...t.files?{files:{maxFileSizeMB:t.maxFileMB??10,maxRunMB:t.maxRunMB??100}}:{},...t.keepContactPoints?{keepContactPoints:!0}:{}}}function Co(t,r){let e;try{e=JSON.parse(t)}catch{return{refusal:"is not JSON: give a Sync configuration as the panel saves one."}}if(typeof e!="object"||e===null||Array.isArray(e))return{refusal:"is not a Sync configuration: it holds no object."};let n=hn.safeParse({config:{...e,sourceOrgId:r.source,targetOrgId:r.target}});if(!n.success){let d=n.error.issues[0];return{refusal:`is not a configuration a run takes (${d.path.slice(1).join(".")||"configuration"}: ${d.message})`}}let s=n.data.config;if(s.id===void 0)return{refusal:"names no id: a saved configuration keeps its watermarks and the files it copied under its id."};let i=new Date().toISOString();return{config:{...s,id:s.id,createdAt:s.createdAt??i,updatedAt:s.updatedAt??i,objects:s.objects.map(d=>({...d,batchSize:d.batchSize??200}))}}}function Qr(t){return mo(t,{recursive:!0}),new xr(Le(pe(t,"configStore.json")))}function xo(t,r,e,n,s=!1,i=5e4){let d=a=>({query:async f=>a.query(f),queryMore:async f=>a.queryMore(f)}),u=a=>({pages:d(a),transport:a,create:async(f,g)=>a.sobject(f).create(g,{headers:Lt()})}),l=new Map;return{copy:Cr({[t.sourceOrgId]:u(r),[t.targetOrgId]:u(e)}),sourceIds:async(a,f)=>{let g=a.objectApiName;if(!M.test(g))throw new Error(`Not an SObject API name: ${g}`);let $=le(a.where,f),{records:k}=await re(d(r),`SELECT Id FROM ${g}${$?` WHERE ${$}`:""}`,i);return k.flatMap(y=>typeof y.Id=="string"?[y.Id]:[])},store:n??{load:()=>l.size===0?{kind:"none"}:{kind:"stored",map:{version:1,entries:[...l.values()]}},record:(a,f)=>{l.set(`${f.sourceOrgId}|${f.targetOrgId}|${f.sourceId}`,f)}},...s?{deleteFromTarget:async(a,f)=>pn(await e.sobject(a).destroy(f),a).map(g=>({id:g.id,success:g.success,errors:g.errors}))}:{}}}function Io(t){let r=Ke({isSandbox:t.sandbox,edition:t.edition});return jr(new In,t.id,{orgType:r})}function Vr(t,r=5e4,e){return async(n,s,i)=>{let d=s.objectApiName;if(!M.test(d))throw new Error(`Not an SObject API name: ${d}`);let u=le(s.where,i?.changedSince),l=u?` WHERE ${u}`:"",a={query:async y=>t.query(y),queryMore:async y=>t.queryMore(y)},g=(await t.sobject(d).describe()).fields.filter(y=>y.type!=="address"&&y.type!=="location").map(y=>y.name),$=!1,k=await rn(`SELECT ${(g.length>0?g:["Id"]).join(", ")} FROM ${d}${l}`,async y=>{let C=await re(a,y,r);return $||=C.truncated,C.records});return $&&(i?.onBoundReached?.(),e?.(d,k.length)),k}}function Eo(t,r){let e=`${_t("clone")} --depth all --source ${r.source} --target ${r.target} --fit share --dry-run`;return t.map(n=>`${n.objectApiName}: the read of the source stopped at ${n.read} records (--max-records-per-object ${n.bound}): this run copied part of the object. `+_r("source",n.bound,{raise:"--max-records-per-object",sample:e}))}function Rt(t,r){return t==="success"&&r.length>0?"partial":t}function To(t,r){return async(e,n,s)=>{let i=n.objectApiName;if(!M.test(i))throw new Error(`Not an SObject API name: ${i}`);let d=le(n.where,s?.changedSince),{totalSize:u}=await t.query(`SELECT COUNT() FROM ${i}${d?` WHERE ${d}`:""}`);return r===void 0?u:Math.min(u,r)}}function Fo(t){return async(r,e)=>{let n=r.objectApiName;if(!M.test(n))return 0;let s=le(r.where,e?.changedSince);try{return(await t.query(`SELECT COUNT() FROM ${n} WHERE IsPersonAccount = true`+(s?` AND (${s})`:""))).totalSize}catch{return 0}}}function Po(t){return async r=>{let e=r.objectApiName;if(!M.test(e))throw new Error(`Not an SObject API name: ${e}`);let n=le(r.where,void 0),{records:s}=await re({query:async i=>t.query(i),queryMore:async i=>t.queryMore(i)},`SELECT Id FROM ${e}${n?` WHERE ${n}`:""}`);return s.flatMap(i=>typeof i.Id=="string"?[i.Id]:[])}}function Xr(t){if(t.go||t.code!==he&&t.code!==Xe)return t;let{code:r,message:e,refusal:n}=t;return{...t,message:dr({code:r,message:e,...n?{refusal:n}:{}})}}var No={notInTarget:"it has no such object, or the user the run writes as cannot see it",notCreateable:"the user the run writes as may not create its records",notUpdateable:"the user the run writes as may not edit its records",unread:"it did not describe the object",notAKey:"its upsert matches on a field that is neither an External ID nor an idLookup field"};function kt(t,r){return{...t??{},sent:r}}function eo(t,r){let e=t.notWritten??0,n=t.total>0?t.total:e,s=[`write gate: ${n-e} record(s) to write to ${r}, about ${Jn(t.storage.estimateMB)} MB of data storage`];for(let a of t.objects)s.push(` ${a.objectApiName.padEnd(42)}${String(a.rows).padStart(8)}`);e>0&&s.push(` of the ${n} a run counts from the source, ${e} would not be written: held back or refused, as each object says; what follows is measured on all of them`),t.alreadyCopied>0&&s.push(` not counted: ${t.alreadyCopied} record(s) an earlier run of this configuration copied, still in the target, left as they are`),(t.alreadyLinked??0)>0&&s.push(` not counted: ${t.alreadyLinked} record(s) an earlier run of this configuration linked to records the target held, left as they are`),(t.overwrites??0)>0&&s.push(` of them, up to ${t.overwrites} written by an update or an upsert over records ${r} holds: their values are kept first, and --remove puts them back`),(t.rolesLinked??0)>0&&s.push(` not counted: ${t.rolesLinked} OpportunityContactRole record(s) the platform writes itself with the opportunities the run creates, for their contact: the run links each and does not send it`),(t.rolesByThePlatform??0)>0&&s.push(` of them, up to ${t.rolesByThePlatform} OpportunityContactRole record(s) the platform writes itself with the opportunities the run creates, for their contact: the run links each and does not send it`);let{storage:i}=t;i.verdict==="unread"?s.push(` the data storage ${r} has left could not be read (${i.unread??""}): whether the records fit is not known`):i.remainingMB!==void 0&&i.maxMB!==void 0&&s.push(` data storage of ${r}: ${i.remainingMB} MB left of ${i.maxMB} MB`+(i.verdict==="exceeds"?": the records do not fit":i.verdict==="near"?": the records take more than 80 % of it":""));for(let a of t.emails){let f=a.objects.map($=>`${$.perRecord} per ${$.objectApiName}`).join("; "),g=` emails: these records make ${r} send about ${Gn(a.emails,a.limit)} (${f})`+(a.alertsCounted?", its email alerts among them, as a Developer Edition counts them":"");s.push(a.verdict==="unread"?`${g}; what it has left today could not be read (${a.unread??""})`:a.verdict==="fits"?`${g}; it has ${a.remaining??"?"} of ${a.max??"?"} left today`:`${g}, more than the ${a.remaining??"?"} of ${a.max??"?"} it has left today`)}t.emailsUnread!==void 0&&s.push(` emails: not counted, ${t.emailsUnread} could not be read`),t.deliverability&&s.push(` ${zn(t.deliverability.reading)}`);let d=t.apiRequests;d&&(s.push(d.verdict==="unread"?` API requests: about ${d.estimate}; what ${r} has left today could not be read (${d.unread??""})`:` API requests: about ${d.estimate}, of the ${d.remaining??"?"} ${r} has left of its ${d.max??"?"} a day`+(d.verdict==="exceeds"?": more than it has left":d.verdict==="near"?": it would leave less than a tenth of them":"")),s.push(` ${Nn}`));for(let a of t.unwritable??[])s.push(` ${a.objectApiName}: ${a.rows} record(s) ${r} takes none of \u2014 ${No[a.why]}${a.key!==void 0?` (${a.key})`:""}`);let u=new Set((t.unwritable??[]).map(({objectApiName:a})=>a)),l=({parent:a,field:f})=>`${f} names ${a} records ${u.has(a)?"left out":"held back"}`;for(let a of t.heldBack??[]){let f=a.parents??[a];s.push(` ${a.objectApiName}: ${a.rows} record(s) held back, not written \u2014 `+(f.length===1?`their ${l(f[0])}`:f.map(g=>`${g.rows} whose ${l(g)}`).join("; ")))}return t.aboveRecords!==void 0&&s.push(` more than ${t.aboveRecords} records: the panel asks before it writes (sandforge.safety.confirmAboveRecords)`),s}function to(t,r,e=!1){let n=t.flatMap(i=>i.recordTypeGiven?[i.recordTypeGiven]:[]),s=hr(n,r);return s.length>0&&r&&e&&s.push(" the permission sets a real run assigns to mute the automation may open other record types to the user it writes as: it reads them again once assigned, and its summary says what the target gave"),s}function no(t){return`${t} already linked by an earlier run of this configuration to records the target held, left as they are`}function Mo(t,r="the target",e=!1,n,s){let i=[`
286
+ simulation: ${t.objects.length} object(s), nothing written`];if(t.writeOrder){i.push(` write order: ${t.writeOrder.objects.join(", ")}`);for(let d of t.writeOrder.moved)i.push(` ${d.objectApiName} after ${d.after}: its ${d.field} names one`);for(let d of t.writeOrder.cycles)i.push(` ${d.join(", ")} name each other: in this order, the lookup at the one written later is left empty`)}if(t.writeCheck){for(let u of eo(t.writeCheck,r))i.push(` ${u}`);for(let u of t.checkpoint?dt(t.checkpoint):[])i.push(` ${u}`);if(t.writeCheck.verdict==="refused"){let u=t.writeCheck,[l,a]=(u.unwritable??[]).length>0?["SYNC_TARGET_UNWRITABLE","the target takes none of the records of an object it writes"]:n!==void 0?[he,n]:u.storage.verdict==="exceeds"?["SYNC_STORAGE_EXCEEDED","the records do not fit"]:u.apiRequests?.verdict==="exceeds"?[Bn,"it takes more API requests than the target has left today"]:[he,u.checkpointUnread??"the checkpoint asked first is refused"];i.push(` a run would be refused before it writes (${l}): ${a}`)}else(t.writeCheck.unwritable??[]).length>0&&i.push(" a run of the command would be refused before it writes (SYNC_TARGET_UNWRITABLE): the target takes none of the records of an object it writes; leave it out of the configuration");let d=t.writeCheck.emails.some(u=>u.verdict==="exceeds");t.writeCheck.verdict!=="refused"&&d?i.push(" a run of the command would be refused before it writes (SYNC_EMAILS_EXCEEDED): past a daily email limit"):t.writeCheck.verdict!=="refused"&&s!==void 0&&i.push(` a run of the command would be refused before it writes (${it}): `+s)}t.writeCheckUnread!==void 0&&i.push(` the records to write could not be counted: ${t.writeCheckUnread}`);for(let d of t.objects){i.push(` ${d.objectApiName} (${d.operation}): ${d.read} read, would insert ${d.insert}, update ${d.update}, delete ${d.delete}, skip ${d.skipped}, refuse ${d.refused}`+(t.direction==="bidirectional"?`, ${d.conflicts} in conflict`:"")),d.alreadyCopied!==void 0&&i.push(` ${d.alreadyCopied} already copied by an earlier run of this configuration, left as they are`),d.alreadyLinked!==void 0&&i.push(` ${no(d.alreadyLinked)}`),(d.encryptedLeftOut??[]).length>0&&i.push(` ${ro(d.encryptedLeftOut??[])}`),d.conflictFields.length>0&&i.push(` differ on: ${d.conflictFields.join(", ")}`),d.files&&i.push(` files: would copy ${d.files.copied}, add ${d.files.versions} version(s), ${d.files.unchanged} unchanged, ${d.files.tooLarge+d.files.pastRunCap} skipped past the caps`);for(let u of d.notes)i.push(` ${u}`);if(d.validationRules&&d.validationRules.length>0){i.push(` ${d.validationRules.length} active validation rule(s) of the target, which a simulation cannot evaluate \u2014 a record one of them refuses is counted as written:`);for(let u of d.validationRules)i.push(` ${u.name}${u.field?` (${u.field})`:""}: ${u.message||"(no message)"}`)}}t.validationRulesUnread&&i.push(` the target's validation rules could not be listed (${t.validationRulesUnread}): any of them may refuse a record counted as written`);for(let d of to(t.objects,!0,e))i.push(` ${d}`);return t.cancelled&&i.push(" stopped by a cancel before its last object"),t.error&&i.push(` stopped at ${t.failedObject??"an object"}: ${t.error}`),i}var _o=/^(PARENT_REFUSED|RECORD_TYPE_UNAVAILABLE|RECORD_TYPE_UNMAPPED):/;function Lo(t){let r=t.slice(0,3);for(let e of t.slice(3))_o.test(e)&&r.push(e);return r}var Do={notInTarget:": the lookup held an id from the source org that the target does not have.",ownerRefusedEarlier:", left out from the start: the target refused the same owner earlier in this run, an id from the source org that the target does not have.",parentRefused:": the record it names, written after them, was refused in this run.",notSet:": the target refused setting it once the record it names was written",notReached:": the run was stopped before it was set, once the record it names was written."},Wo={"validation-rule":"a validation rule of the target refused it","restricted-picklist":"a restricted picklist of the target refused its value","lookup-filter":"a lookup filter of the target refused the record it names","inactive-owner":"the target holds the owner it names inactive"};function Uo(t){let r=Bo(t),e=Math.max(0,(t.skipped??0)-r);return`${t.objectApiName}: ${t.processed??0} processed, ${t.success??0} succeeded, ${t.failed??0} failed, ${e} skipped`+(r>0?`, ${r} linked`:"")}function Bo(t){return(t.writtenByThePlatform?.records??0)+(t.linkedToExisting?.records??0)}function qo(t){let r=[];(t.encryptedLeftOut??[]).length>0&&r.push(ro(t.encryptedLeftOut??[]));let e=t.linkedToExisting;e&&r.push(`${e.records} record(s) linked to a record the target holds, not written: the target refused them as a duplicate of it${e.refusal?` (${e.refusal})`:""}; what the run writes under them points at that record.`);let n=t.writtenByThePlatform;n&&r.push(`${n.records} record(s) linked to the contact role the platform wrote with their opportunity, for its contact, not written; ${n.given} given the source's fields ${n.given===1?"it":"they"} lacked`+(n.refusal?`, the others left as the platform wrote them (${n.refusal}).`:"."));for(let{records:d,fields:u,reason:l,refusal:a}of t.lookupsLeftOut??[]){let f=l==="notSet"?`${a?` (${a})`:""}.`:"";r.push(`${d} record(s) written without ${u.join(", ")}${Do[l]}${f}`)}let s=t.lookupsSetAfter;s&&r.push(`${s.records} record(s) given ${s.fields.join(", ")} by a second write once ${s.after.join(", ")} ${s.after.length===1?"was":"were"} written: the objects name each other, and no order writes both first.`);let i=t.writtenWithoutFields;return i&&r.push(`${i.rows} record(s) written again without the fields the target refused them on:`,...i.fields.map(({field:d,rows:u,refusedBy:l="validation-rule",reason:a})=>` ${u} without ${d}: ${Wo[l]}, ${a}`)),r}function ro(t){return`${t.join(", ")}: encrypted, and read masked by the user the source is read as (it lacks View Encrypted Data): left out of every record written, never copied as masks`}function Go(t){return t?t.neutralized?[`emails and phone numbers: ${t.values} value(s) in ${t.fields.length} field(s) neutralized, addresses under .invalid and numbers fictional, so what the target's automation sends to them reaches no one`,...t.fields.map(({objectApiName:r,field:e,values:n})=>` ${r}.${e} ${n}`),...t.numbersExhausted?[` ${t.numbersExhausted} phone number(s) left out, their field empty: the 10 000 fictional numbers were all given to other numbers of the run`]:[]]:["emails and phone numbers: written as read (--keep-contact-points): the target's automation may have emailed or texted the people the records name"]:[]}function zo(t){return(t??[]).map(r=>`${sn(r)}.`)}function Jo(t,r=!1){return[...r?[Dr]:[],...Vn(t??[]).map(e=>`${e}.`)]}function Ho(t){let r=t.read==="delta"?`delta: ${t.changed} record(s) changed since ${t.since??"the last run"}`:`delta: read whole (${t.reason??"no watermark"}), ${t.changed} record(s)`,e=t.deletionsChecked?`, ${t.deleted} deleted as the source deleted them`+(t.deleteFailed>0?`, ${t.deleteFailed} refused`:""):"",n=t.recorded!==void 0?"; watermark recorded":"; watermark kept as it was: the next run reads from the same point",s=(t.lookupsOwed??0)>0?`, ${t.lookupsOwed} record(s) left without a lookup this run was to set among them`:"";return`${r}${e}${n}${s}`}function Ko(t){let r=new Map,e=new On,n=new Map,s=new Set,i,d,u,l=a=>{if(a<=0)return;let f=new Date().toISOString();d??=f,u=f};return{runId:t,sending:(a,f)=>l(f),writing:(a,f)=>l(f),answered:()=>{u=new Date().toISOString()},note:(a,f)=>{if(f.length===0)return;let g=f.filter($=>{let k=$.slice(0,15);return s.has(k)?!1:(s.add(k),!0)});g.length>0&&r.set(a,[...r.get(a)??[],...g]),i=new Date().toISOString(),d??=i,u=i},touched:(a,f)=>{f<=0||(i=new Date().toISOString(),u=i)},overwriting:(a,f,g)=>{g.length!==0&&(e.candidates(a,f,g),l(g.length))},overwrote:(a,f)=>{e.answer(a,f),u=new Date().toISOString()},deleted:(a,f)=>{if(f.length===0)return;let g=n.get(a)??new Map;for(let $ of f)g.has($.slice(0,15))||g.set($.slice(0,15),$);n.set(a,g),l(f.length)},overwrittenCount:()=>e.count,flush:async()=>{},created:()=>[...r].map(([a,f])=>({objectApiName:a,ids:[...f]})),lastWrittenAt:()=>i,firstWrittenAt:()=>d,lastWriteAt:()=>u,overwritten:()=>e.read(),deletions:()=>[...n].map(([a,f])=>({objectApiName:a,ids:[...f.values()]}))}}function Yo(t,r){return r?{runId:t.runId,note:(e,n,s)=>{t.note(e,n,s),r.note(e,n,s)},noteUnanswered:(e,n)=>{t.note(e,n),r.noteUnanswered?r.noteUnanswered(e,n):r.note(e,n)},sending:(e,n,s)=>{t.sending?.(e,n,s),r.sending?.(e,n,s)},answered:(e,n)=>{t.answered?.(e,n),r.answered?.(e,n)},writing:(e,n)=>{t.writing?.(e,n),r.writing?.(e,n)},touched:(e,n)=>{t.touched?.(e,n),r.touched?.(e,n)},overwriting:(e,n,s,i)=>{t.overwriting?.(e,n,s),r.overwriting?.(e,n,s,i)},overwrote:(e,n)=>{t.overwrote?.(e,n),r.overwrote?.(e,n)},deleted:(e,n)=>{t.deleted?.(e,n),r.deleted?.(e,n)},checkpoint:e=>{t.checkpoint?.(e),r.checkpoint?.(e)},overwrittenCount:()=>t.overwrittenCount?.()??r.overwrittenCount?.()??0,flush:async()=>await t.flush()??await r.flush()}:t}var St="sandforge-sync";function Vo(t,r){let e=new Set(r);return{...t,objectsRead:t.objectsRead.filter(n=>e.has(n)),objects:t.objects.filter(n=>e.has(n.objectApiName))}}async function Xo(t){try{let e=(await t.query("SELECT Id FROM Organization LIMIT 1")).records[0]?.Id;return typeof e=="string"?e:void 0}catch{return}}async function Zo(t=process.argv){if(t.slice(2).includes("--remove"))return ms(t);let r=Date.now(),e=Oo(t),n=o=>{e.json||process.stdout.write(`${o}
287
287
  `)},s=o=>{process[e.json?"stderr":"stdout"].write(`${o}
288
- `)},i,d;if(e.configFile!==void 0&&e.store!==void 0){let o;try{o=$e(e.configFile,"utf8")}catch(w){process.stderr.write(`--config-file ${e.configFile} cannot be read: ${w instanceof Error?w.message:String(w)}
289
- `),process.exit(2)}let c=jo(o,e);"refusal"in c&&(process.stderr.write(`--config-file ${e.configFile} ${c.refusal}
288
+ `)},i,d;if(e.configFile!==void 0&&e.store!==void 0){let o;try{o=ve(e.configFile,"utf8")}catch(w){process.stderr.write(`--config-file ${e.configFile} cannot be read: ${w instanceof Error?w.message:String(w)}
289
+ `),process.exit(2)}let c=Co(o,e);"refusal"in c&&(process.stderr.write(`--config-file ${e.configFile} ${c.refusal}
290
290
  `),process.exit(2));let p=Ut(c.config.objects);p.length>0&&(process.stderr.write(`--config-file ${e.configFile}: ${Bt(p)} Nothing was read or written.
291
- `),process.exit(1)),i=c.config,d=Qr(e.store),d.save(i)}else i=Oo(e);n(`sandforge sync ${e.source} -> ${e.target}`),n(`objects: ${i.objects.map(o=>o.objectApiName).join(", ")}`+(d?` (configuration ${i.id}, ${i.mode})`:""));let u=Se(await xe(e.source)),l=await xe(e.target),a=Se(l),f=[Ye(a)],g=()=>f.reduce((o,c)=>o+c(),0),v=new Map,k=new AbortController,y=e.dryRun?await ke(a).catch(()=>{}):await Kt(a,e.target,{tool:"sandforge sync",action:"write",readOnly:"--dry-run"}),j=`sandforge-sync-${po()}`,I=Ho(j),U=e.dryRun?void 0:Qe(De()),S=U?.recorder({runId:j,configId:d?i.id:St,configName:d?i.name:St,sourceOrgId:e.source,targetOrgId:y?.id??e.target,targetAlias:e.target,...y?{targetOrganizationId:y.id}:{}});nr(S,()=>a.identity(),"sandforge sync");let $=!1,b=()=>{let o=U?.pathOf(j);$||o===void 0||($=!0,s(`run file: ${o} (--remove ${o} takes back what the run creates)`))},J=Ko(I,S),N=S?{...J,note:(o,c,p)=>{b(),J.note(o,c,p)},sending:(o,c,p)=>{b(),J.sending?.(o,c,p)}}:J,H=e.checkpointFirst?ir({module:"sync",operationId:j,request:e.checkpointFirst,session:l,org:sr(l,y??await ke(a)),connect:o=>{let c=Se(o);return f.push(Ye(c)),c},journalDir:De(),say:s,own:{runId:j}}):void 0,X=async o=>{let c=v.get(o);if(c)return c;let p=await a.sobject(o).describe(),w=gt(p);return v.set(o,w),w},L=i.objects.some(o=>o.operation==="update"||o.operation==="upsert"),K=ht(),D;if(!e.dryRun&&L){let o=pt(K);o!==void 0&&(process.stderr.write(`${o} What the run would write over could not be kept, so nothing was written.
292
- `),process.exit(1)),D=Fr({runId:j,orgId:e.target,...y?{organizationId:y.id}:{},files:new st(ot(K)),meta:Le(he(K,"snapshots.json"))})}let B=async o=>(await te({query:async c=>a.query(c),queryMore:async c=>a.queryMore(c)},o)).records,Ae=D?Pr({query:B,backup:D,recorder:N,describe:o=>X(o),viewsEncrypted:rt(B)}):void 0,W=new Ur({connection:a,bulkExecutor:new gn,bulkManager:new nn,retryConfig:{},signal:k.signal,onProgress:(o,c,p)=>n(` ${p}: ${o}/${c}`),log:n,calls:Wr(N,Ae)}),ne=!1,F=async(o,c,p,w,P)=>{if(e.dryRun)throw new Error(`A dry run writes nothing: ${o} ${c} refused.`);return b(),p.length>0&&(ne=!0),o==="delete"?W.delete(c,p,w):o==="upsert"?W.upsert(c,P??"Id",p,w):o==="update"?W.update(c,p,w):W.insert(c,p,w)},C=new Date().toISOString(),q,E,pe,G,Oe=zr(i,async o=>(await a.query(o)).totalSize),M={readStorage:()=>Wn(a),readApiBudget:()=>Un(a),readAutomation:o=>We(a).read(e.target,o),readLimits:()=>qn(a),readDeliverability:async()=>Jt(y??await ke(a))?Tn:Fn(a),emails:{target:e.target,accepted:e.acceptEmails,keepsAddresses:i.keepContactPoints===!0,mayMute:!e.muteAutomation},confirmAboveRecords:Dn,sentBefore:()=>g()+(e.dryRun?tr:0),...Oe?{countTarget:Oe}:{},...H?{checkpointFirst:{scope:async(o,c)=>(q={written:o,running:c},E=await H.scope(q),E),take:async o=>{if(!q)throw new Error("its scope was not read");let c=await H.take(q,o,{signal:k.signal});if(c.taken){pe=c.checkpoint,N.checkpoint?.(c.checkpoint);for(let p of cr(c.checkpoint,e.target,e.muteAutomation))s(p)}return c}}}:{}},re=y?Wt({orgType:Ke({isSandbox:y.sandbox,edition:y.edition}),metadata:{edition:y.edition}}):"production",Z,ge,oe,me=[],se=[],h=o=>{let c=Xr({go:!1,...o});return c.go?o:{code:c.code,message:c.message}},m=(o,c)=>({measure:async p=>{let w=await mt(p,{...M,readAutomation:o,...c?{mutePlan:c}:{}});ge=w.checkpointFailed,oe=w.runEmails?.gate.stop;let P=wt(w,{policy:"refuse",org:e.target});return me=P.filter(V=>!vo.has(V.code)).map(({code:V,message:Re})=>({code:V,message:Re})),e.dryRun||(se=P.map(h)),w.check},hold:async p=>{let w=await mt(p,{...M,readAutomation:o,...c?{mutePlan:c}:{}});Z=w.check,n("");for(let ce of eo(w.check,e.target))n(ce);for(let ce of w.checkpoint?dt(w.checkpoint):[])s(ce);let P=await Jr(w,{policy:"refuse",org:e.target,orgTier:re}),[V,...Re]=wt(w,{policy:"refuse",org:e.target});return se=!P.go&&V?.code===P.code?Re.map(h):[],{check:w.check,answer:Xr(await Kr(w,P,M.checkpointFirst))}}}),O=e.muteAutomation&&!e.dryRun?Yr(m,M.readAutomation,async o=>{let c=await _e(async()=>Ne(a),o,{writes:yt});for(let p of le(c.muted,e.target))n(` ${p}`);return c},`sandforge sync ${j}`,{target:e.target}):void 0,A,x,Q=()=>A??=(async()=>{let o=i.objects.map(p=>p.objectApiName),c=await M.readAutomation(o).catch(p=>({unread:p instanceof Error?p.message:String(p)}));try{let p=await _e(async()=>Ne(a),c,{writes:yt});for(let w of le(p.muted,e.target))n(w);return x=p,{planned:p}}catch(p){if(!Me(p))throw p;return n(Xt(p.refusal)),{refused:p.refusal}}})(),ie=async o=>{let c=(await Q()).planned?.automation;return c&&o.every(p=>c.objectsRead.includes(p))?Yo(c,o):M.readAutomation(o)},we=O?.gate??(e.dryRun&&e.muteAutomation?m(ie,()=>x?.plan):m(M.readAutomation)),T={measure:o=>we.measure(o),hold:async o=>{let c=await we.hold(o);return c.answer.go&&b(),c}},ye,ae;if(i.files!==void 0){let o=y?xo(y):!1;ae=Co(i,u,a,d?.fileStore(),o,e.maxRecordsPerObject),e.dryRun&&ae.deleteFromTarget&&(ae={...ae,deleteFromTarget:async c=>{throw new Error(`A dry run writes nothing: delete ${c} refused.`)}})}let ee=new Map,$t=()=>{let o=Io([...ee.values()],e);o.length>0&&process.stderr.write(`${o.join(`
291
+ `),process.exit(1)),i=c.config,d=Qr(e.store),d.save(i)}else i=jo(e);n(`sandforge sync ${e.source} -> ${e.target}`),n(`objects: ${i.objects.map(o=>o.objectApiName).join(", ")}`+(d?` (configuration ${i.id}, ${i.mode})`:""));let u=ke(await Ce(e.source)),l=await Ce(e.target),a=ke(l),f=[Ye(a)],g=()=>f.reduce((o,c)=>o+c(),0),$=new Map,k=new AbortController,y=e.dryRun?await Re(a).catch(()=>{}):await Kt(a,e.target,{tool:"sandforge sync",action:"write",readOnly:"--dry-run"}),C=`sandforge-sync-${go()}`,x=Ko(C),U=e.dryRun?void 0:Qe(_e()),S=U?.recorder({runId:C,configId:d?i.id:St,configName:d?i.name:St,sourceOrgId:e.source,targetOrgId:y?.id??e.target,targetAlias:e.target,...y?{targetOrganizationId:y.id}:{}});nr(S,()=>a.identity(),"sandforge sync");let A=!1,b=()=>{let o=U?.pathOf(C);A||o===void 0||(A=!0,s(`run file: ${o} (--remove ${o} takes back what the run creates)`))},G=Yo(x,S),P=S?{...G,note:(o,c,p)=>{b(),G.note(o,c,p)},sending:(o,c,p)=>{b(),G.sending?.(o,c,p)}}:G,z=e.checkpointFirst?ir({module:"sync",operationId:C,request:e.checkpointFirst,session:l,org:sr(l,y??await Re(a)),connect:o=>{let c=ke(o);return f.push(Ye(c)),c},journalDir:_e(),say:s,own:{runId:C}}):void 0,Q=async o=>{let c=$.get(o);if(c)return c;let p=await a.sobject(o).describe(),w=gt(p);return $.set(o,w),w},_=i.objects.some(o=>o.operation==="update"||o.operation==="upsert"),J=ht(),L;if(!e.dryRun&&_){let o=pt(J);o!==void 0&&(process.stderr.write(`${o} What the run would write over could not be kept, so nothing was written.
292
+ `),process.exit(1)),L=Fr({runId:C,orgId:e.target,...y?{organizationId:y.id}:{},files:new st(ot(J)),meta:Le(pe(J,"snapshots.json"))})}let B=async o=>(await re({query:async c=>a.query(c),queryMore:async c=>a.queryMore(c)},o)).records,$e=L?Pr({query:B,backup:L,recorder:P,describe:o=>Q(o),viewsEncrypted:rt(B)}):void 0,H=new gn,K=new Ur({connection:a,bulkExecutor:H,bulkManager:new nn,retryConfig:{},signal:k.signal,onProgress:(o,c,p)=>n(` ${p}: ${o}/${c}`),log:n,calls:Wr(P,$e)}),D=!1,O=async(o,c,p,w,F)=>{if(e.dryRun)throw new Error(`A dry run writes nothing: ${o} ${c} refused.`);return b(),p.length>0&&(D=!0),o==="delete"?K.delete(c,p,w):o==="upsert"?K.upsert(c,F??"Id",p,w):o==="update"?K.update(c,p,w):K.insert(c,p,w)},oe=new Date().toISOString(),N,W,se,Y,ie=zr(i,async o=>(await a.query(o)).totalSize),T={readStorage:()=>Wn(a),readApiBudget:()=>Un(a),readAutomation:o=>De(a).read(e.target,o),readLimits:()=>qn(a),readDeliverability:async()=>Jt(y??await Re(a))?Tn:Fn(a),emails:{target:e.target,accepted:e.acceptEmails,keepsAddresses:i.keepContactPoints===!0,mayMute:!e.muteAutomation},confirmAboveRecords:Dn,sentBefore:()=>g()+(e.dryRun?tr:0),...ie?{countTarget:ie}:{},...z?{checkpointFirst:{scope:async(o,c)=>(N={written:o,running:c},W=await z.scope(N),W),take:async o=>{if(!N)throw new Error("its scope was not read");let c=await z.take(N,o,{signal:k.signal});if(c.taken){se=c.checkpoint,P.checkpoint?.(c.checkpoint);for(let p of cr(c.checkpoint,e.target,e.muteAutomation))s(p)}return c}}}:{}},qe=y?Wt({orgType:Ke({isSandbox:y.sandbox,edition:y.edition}),metadata:{edition:y.edition}}):"production",V,ge,ae,me=[],h=[],m=o=>{let c=Xr({go:!1,...o});return c.go?o:{code:c.code,message:c.message}},j=(o,c)=>({measure:async p=>{let w=await mt(p,{...T,readAutomation:o,...c?{mutePlan:c}:{}});ge=w.checkpointFailed,ae=w.runEmails?.gate.stop;let F=wt(w,{policy:"refuse",org:e.target});return me=F.filter(Z=>!$o.has(Z.code)).map(({code:Z,message:be})=>({code:Z,message:be})),e.dryRun||(h=F.map(m)),w.check},hold:async p=>{let w=await mt(p,{...T,readAutomation:o,...c?{mutePlan:c}:{}});V=w.check,n("");for(let ue of eo(w.check,e.target))n(ue);for(let ue of w.checkpoint?dt(w.checkpoint):[])s(ue);let F=await Jr(w,{policy:"refuse",org:e.target,orgTier:qe}),[Z,...be]=wt(w,{policy:"refuse",org:e.target});return h=!F.go&&Z?.code===F.code?be.map(m):[],{check:w.check,answer:Xr(await Kr(w,F,T.checkpointFirst))}}}),v=e.muteAutomation&&!e.dryRun?Yr(j,T.readAutomation,async o=>{let c=await Me(async()=>Pe(a),o,{writes:yt});for(let p of fe(c.muted,e.target))n(` ${p}`);return c},`sandforge sync ${C}`,{target:e.target}):void 0,I,ee,te=()=>I??=(async()=>{let o=i.objects.map(p=>p.objectApiName),c=await T.readAutomation(o).catch(p=>({unread:p instanceof Error?p.message:String(p)}));try{let p=await Me(async()=>Pe(a),c,{writes:yt});for(let w of fe(p.muted,e.target))n(w);return ee=p,{planned:p}}catch(p){if(!Ne(p))throw p;return n(Xt(p.refusal)),{refused:p.refusal}}})(),Ae=async o=>{let c=(await te()).planned?.automation;return c&&o.every(p=>c.objectsRead.includes(p))?Vo(c,o):T.readAutomation(o)},E=v?.gate??(e.dryRun&&e.muteAutomation?j(Ae,()=>ee?.plan):j(T.readAutomation)),oo={measure:o=>E.measure(o),hold:async o=>{let c=await E.hold(o);return c.answer.go&&b(),c}},we,de;if(i.files!==void 0){let o=y?Io(y):!1;de=xo(i,u,a,d?.fileStore(),o,e.maxRecordsPerObject),e.dryRun&&de.deleteFromTarget&&(de={...de,deleteFromTarget:async c=>{throw new Error(`A dry run writes nothing: delete ${c} refused.`)}})}let ne=new Map,$t=()=>{let o=Eo([...ne.values()],e);o.length>0&&process.stderr.write(`${o.join(`
293
293
  `)}
294
- `)},At=()=>ee.size>0?{readCut:[...ee.values()]}:{},Ot=new Br({...e.dryRun?{}:{creations:N},signal:k.signal,...ae?{files:ae}:{},...d&&e.store!==void 0?{idMap:bn(Ze(e.store),o=>d.isSaved(o))}:{},...d?{deltaStore:d.deltaStore(),deltaReads:un({query:async(o,c)=>u.query(o,c),queryMore:async o=>u.queryMore(o)},{query:async o=>a.query(o),queryMore:async o=>a.queryMore(o)},k.signal)}:{},dataSync:new Nr({insert:(o,c,p)=>F("insert",o,c,p),update:(o,c,p)=>F("update",o,c,p),upsert:(o,c,p,w)=>F("upsert",o,p,w,c),delete:(o,c,p)=>F("delete",o,c,p),describeTargetFields:X}),conflictResolver:new qr,fieldMapping:new cn,transformPipeline:new dn,querySource:Vr(u,e.maxRecordsPerObject,(o,c)=>{ee.set(o,{objectApiName:o,read:c,bound:e.maxRecordsPerObject})}),queryTarget:Vr(a,e.maxRecordsPerObject),maskedSourceFields:xn(rt(async o=>(await te({query:async c=>u.query(c),queryMore:async c=>u.queryMore(c)},o)).records),o=>u.sobject(o).describe()),findInTarget:an({query:async o=>a.query(o),queryMore:async o=>a.queryMore(o)}),describeTargetFields:X,describeTargetFieldsAgain:async o=>gt(await a.sobject(o).describe()),leaseOfTheGate:()=>O?.lease(),queryTargetRows:B,countSource:Eo(u,e.maxRecordsPerObject),countPersonAccounts:To(u),readSourceIds:Fo(u),writeGate:T,readValidationRules:_n(async o=>(await te({query:async c=>a.tooling.query(c),queryMore:async c=>a.tooling.queryMore(c)},o)).records,Mn(a),Ln(a)),currencies:()=>on(async o=>(await u.query(o)).records,async o=>(await a.query(o)).records,{source:async o=>(await u.tooling.query(o)).records,target:async o=>(await a.tooling.query(o)).records}),standardPricebooks:()=>Lr(async o=>(await u.query(o)).records,async o=>(await a.query(o)).records),recordTypes:()=>Gr({query:async o=>u.query(o),queryMore:async o=>u.queryMore(o)},{query:async o=>a.query(o),queryMore:async o=>a.queryMore(o)})});if(e.dryRun){n(`
295
- simulating\u2026 (DRY-RUN: nothing is written)`);let c={...await Ot.simulate(i),...E?{checkpoint:E}:{}},{planned:p,refused:w}=e.muteAutomation?await Q():{},P=ge??(E?.refusal?ar(E.refusal):void 0),V=c.writeCheck?.unwritable??[],Re=[w,V.length>0?{code:"SYNC_TARGET_UNWRITABLE",message:Hr(V,e.target,c.writeCheck?.heldBack)}:void 0,P!==void 0?{code:fe,message:P}:void 0,...me,oe].filter(He=>He!==void 0),ce=Date.now()-r;if($t(),Te(Ee(Rt("success",[...ee.values()]),e.failOnPartial)),e.json){process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",source:e.source,target:e.target,dryRun:!0,simulation:c,...At(),...Pn(p),...E?{checkpoint:E}:{},apiRequests:kt(c.writeCheck?.apiRequests,g()),...Zt(Re),elapsedMs:ce},null,2)}
296
- `);return}let so=(p?.plan?.assign.length??0)>0;for(let He of No(c,e.target,so,P,oe?.message))n(He);n(`
297
- done in ${ce}ms`);return}n(`
298
- executing\u2026 (REAL)`);let Y=U?.pathOf(j),de,oo=Ve(o=>{de=o,process.stderr.write(`
294
+ `)},At=()=>ne.size>0?{readCut:[...ne.values()]}:{},Ot=new Br({...e.dryRun?{}:{creations:P},signal:k.signal,...de?{files:de}:{},...d&&e.store!==void 0?{idMap:bn(Ze(e.store),o=>d.isSaved(o))}:{},...d?{deltaStore:d.deltaStore(),deltaReads:un({query:async(o,c)=>u.query(o,c),queryMore:async o=>u.queryMore(o)},{query:async o=>a.query(o),queryMore:async o=>a.queryMore(o)},k.signal)}:{},dataSync:new Nr({insert:(o,c,p)=>O("insert",o,c,p),update:(o,c,p)=>O("update",o,c,p),upsert:(o,c,p,w)=>O("upsert",o,p,w,c),delete:(o,c,p)=>O("delete",o,c,p),describeTargetFields:Q}),conflictResolver:new qr,fieldMapping:new cn,transformPipeline:new dn,querySource:Vr(u,e.maxRecordsPerObject,(o,c)=>{ne.set(o,{objectApiName:o,read:c,bound:e.maxRecordsPerObject})}),queryTarget:Vr(a,e.maxRecordsPerObject),maskedSourceFields:xn(rt(async o=>(await re({query:async c=>u.query(c),queryMore:async c=>u.queryMore(c)},o)).records),o=>u.sobject(o).describe()),findInTarget:an({query:async o=>a.query(o),queryMore:async o=>a.queryMore(o)}),bulkThreshold:H.getThreshold(),describeTargetFields:Q,describeTargetFieldsAgain:async o=>gt(await a.sobject(o).describe()),leaseOfTheGate:()=>v?.lease(),queryTargetRows:B,countSource:To(u,e.maxRecordsPerObject),countPersonAccounts:Fo(u),readSourceIds:Po(u),writeGate:oo,readValidationRules:_n(async o=>(await re({query:async c=>a.tooling.query(c),queryMore:async c=>a.tooling.queryMore(c)},o)).records,Mn(a),Ln(a)),currencies:()=>on(async o=>(await u.query(o)).records,async o=>(await a.query(o)).records,{source:async o=>(await u.tooling.query(o)).records,target:async o=>(await a.tooling.query(o)).records}),standardPricebooks:()=>Lr(async o=>(await u.query(o)).records,async o=>(await a.query(o)).records),recordTypes:()=>Gr({query:async o=>u.query(o),queryMore:async o=>u.queryMore(o)},{query:async o=>a.query(o),queryMore:async o=>a.queryMore(o)})});if(e.dryRun){n(`
295
+ simulating\u2026 (DRY-RUN: nothing is written)`);let c={...await Ot.simulate(i),...W?{checkpoint:W}:{}},{planned:p,refused:w}=e.muteAutomation?await te():{},F=ge??(W?.refusal?ar(W.refusal):void 0),Z=c.writeCheck?.unwritable??[],be=[w,Z.length>0?{code:"SYNC_TARGET_UNWRITABLE",message:Hr(Z,e.target,c.writeCheck?.heldBack)}:void 0,F!==void 0?{code:he,message:F}:void 0,...me,ae].filter(He=>He!==void 0),ue=Date.now()-r;if($t(),Ee(Ie(Rt("success",[...ne.values()]),e.failOnPartial)),e.json){process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",source:e.source,target:e.target,dryRun:!0,simulation:c,...At(),...Pn(p),...W?{checkpoint:W}:{},apiRequests:kt(c.writeCheck?.apiRequests,g()),...Zt(be),elapsedMs:ue},null,2)}
296
+ `);return}let io=(p?.plan?.assign.length??0)>0;for(let He of Mo(c,e.target,io,F,ae?.message))n(He);n(`
297
+ done in ${ue}ms`);return}n(`
298
+ executing\u2026 (REAL)`);let X=U?.pathOf(C),ce,so=Ve(o=>{ce=o,process.stderr.write(`
299
299
  interrupted: the run stops before its next call, and its file keeps what it created (Ctrl-C again ends it at once)
300
- `),k.abort()}),jt=async()=>{!H||!pe||G||(G=await ur(H,pe,ne,e.target,s))},z,Ge={status:"failure"};try{z=await Ot.execute(i).finally(async()=>{ye=await O?.release()}),ye&&(z={...z,mutedAutomation:ye}),Ge={status:Rt(z.status,[...ee.values()]),...z.cancelled?{cancelled:!0}:{}},await jt()}catch(o){if(D?.close(),await jt(),!(o instanceof Mr))throw await S?.end(Ge),Y!==void 0&&ve(Y)&&process.stderr.write(`the run stopped on an error; what it created is kept in ${Y}, and --remove ${Y} takes it back
301
- `),o;let c=o.code===Xe,p=c?[]:se;e.json?(c||process.stderr.write(`${[o,...p].map(Fe).join(`
300
+ `),k.abort()}),jt=async()=>{!z||!se||Y||(Y=await ur(z,se,D,e.target,s))},q,Ge={status:"failure"};try{q=await Ot.execute(i).finally(async()=>{we=await v?.release()}),we&&(q={...q,mutedAutomation:we}),Ge={status:Rt(q.status,[...ne.values()]),...q.cancelled?{cancelled:!0}:{}},await jt()}catch(o){if(L?.close(),await jt(),!(o instanceof Mr))throw await S?.end(Ge),X!==void 0&&Se(X)&&process.stderr.write(`the run stopped on an error; what it created is kept in ${X}, and --remove ${X} takes it back
301
+ `),o;let c=o.code===Xe,p=c?[]:h;e.json?(c||process.stderr.write(`${[o,...p].map(Te).join(`
302
302
  `)}
303
- `),process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",source:e.source,target:e.target,dryRun:!1,refused:{code:o.code,message:o.message},...p.length>0?{alsoRefused:p}:{},...Z?{writeCheck:Z}:{},...G?{checkpoint:G}:{},apiRequests:kt(Z?.apiRequests,g()),elapsedMs:Date.now()-r},null,2)}
303
+ `),process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",source:e.source,target:e.target,dryRun:!1,refused:{code:o.code,message:o.message},...p.length>0?{alsoRefused:p}:{},...V?{writeCheck:V}:{},...Y?{checkpoint:Y}:{},apiRequests:kt(V?.apiRequests,g()),elapsedMs:Date.now()-r},null,2)}
304
304
  `)):n(c?`
305
305
  ${o.message}`:`
306
- ${[o,...p].map(Fe).join(`
307
- `)}`),process.exit(c?Ie(de??"SIGINT"):1)}finally{oo()}await S?.end(Ge),D?.close();let Ct=await S?.flush();Ct!==void 0&&process.stderr.write(`what the run created could not all be written to ${Y??"its file"} (${Ct}): --remove takes it back from the --json summary
308
- `);let xt=Date.now()-r,ze=I.created(),It=I.lastWrittenAt(),Et=I.firstWrittenAt(),Tt=I.lastWriteAt(),je=I.overwritten(),Je=I.deletions(),Ft=ze.length>0||je.length>0||Je.length>0?y?.id??await Vo(a):void 0,be=Y!==void 0&&ve(Y)?Y:void 0;$t();let Ce=Rt(z.status,[...ee.values()]);if(e.json){process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",source:e.source,target:e.target,...Ft?{targetOrgId:Ft}:{},...d?{configId:i.id}:{},dryRun:e.dryRun,startedAt:C,finishedAt:new Date().toISOString(),result:{...z,status:Ce},...At(),...G?{checkpoint:G}:{},apiRequests:kt(Z?.apiRequests,g()),created:{runId:I.runId,...It?{lastWrittenAt:It}:{},...Et?{firstWrittenAt:Et}:{},...Tt?{lastWriteAt:Tt}:{},...be?{runFile:be}:{},objects:ze,...je.length>0?{overwritten:je}:{},...Je.length>0?{deleted:Je}:{}},elapsedMs:xt},null,2)}
309
- `),de&&process.exit(Ie(de)),Te(Ee(Ce,e.failOnPartial));return}let Pt=z.objectResults??[];n(`
310
- status: ${Ce}`);for(let o of ye?le(ye,e.target):[])n(o);for(let o of Pt){n(` ${Wo(o)}`),typeof o.alreadyCopied=="number"&&n(` ${o.alreadyCopied} already copied by an earlier run of this configuration, left as they are`),typeof o.alreadyLinked=="number"&&n(` ${no(o.alreadyLinked)}`);for(let w of _o(o.errors??[]))n(` ${w}`);for(let w of Bo(o))n(` ${w}`);for(let w of Go(o.currenciesReplaced))n(` ${w}`);for(let w of zo(o.pricesSettled,o.standardPricebookMatched===!0))n(` ${w}`);let c=o.files;c&&n(` files: ${c.copied??0} copied, ${c.versions??0} version(s) added, ${c.failed??0} failed`);let p=o.delta;p&&n(` ${Jo(p)}`)}for(let o of to(Pt,!1))n(` ${o}`);for(let o of qo(z.contactPoints))n(` ${o}`);let Nt=ze.reduce((o,c)=>o+c.ids.length,0),Mt=je.reduce((o,c)=>o+c.ids.length,0);Mt>0&&n(`
311
- wrote over ${Mt} record(s) of ${e.target}, their values from before kept in ${he(K,"backups")}: --remove ${be??"with the --json summary"} gives them back`),Nt>0&&n(`
312
- created ${Nt} record(s) and file(s) in ${e.target}: `+(be!==void 0?`--remove ${be} takes them back`:"run with --json and save the summary to a file, and --remove takes them back from it")),n(`
313
- done in ${xt}ms`),de&&process.exit(Ie(de)),Te(Ee(Ce,e.failOnPartial))}var Be=new Set(["--remove","--target","--include-changed","--accept-automation","--mute-automation","--store","--sweep","--sweep-list",...br,"--leave-undeletable","--json"]),Zo=new Set(["--remove","--target","--store"]);function Qo(t){let r=t.slice(2);for(let u=0;u<r.length;u++){let l=r[u];if(Zo.has(l)){u++;continue}Be.has(l)||(process.stderr.write(`--remove takes --target, --include-changed, --accept-automation, --mute-automation, --store, --sweep, --sweep-late, --sweep-untied, --sweep-list, --leave-undeletable and --json, not "${l}". Run with --help.
314
- `),process.exit(2))}let e=u=>{let l=r.indexOf(u);return l>=0&&l+1<r.length?r[l+1]:void 0},n=e("--remove"),s=e("--target"),i=e("--store");r.includes("--store")&&(!i||Be.has(i))&&(process.stderr.write(`--store wants the directory the configuration of the run is kept in.
315
- `),process.exit(2)),(!n||!s||Be.has(n)||Be.has(s))&&(process.stderr.write(`--remove takes the file a run printed its --json summary to, or the run file it named as it began, or its run id, and --target the org the run wrote to. Run with --help.
306
+ ${[o,...p].map(Te).join(`
307
+ `)}`),process.exit(c?xe(ce??"SIGINT"):1)}finally{so()}await S?.end(Ge),L?.close();let Ct=await S?.flush();Ct!==void 0&&process.stderr.write(`what the run created could not all be written to ${X??"its file"} (${Ct}): --remove takes it back from the --json summary
308
+ `);let xt=Date.now()-r,ze=x.created(),It=x.lastWrittenAt(),Et=x.firstWrittenAt(),Tt=x.lastWriteAt(),Oe=x.overwritten(),Je=x.deletions(),Ft=ze.length>0||Oe.length>0||Je.length>0?y?.id??await Xo(a):void 0,ye=X!==void 0&&Se(X)?X:void 0;$t();let je=Rt(q.status,[...ne.values()]);if(e.json){process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",source:e.source,target:e.target,...Ft?{targetOrgId:Ft}:{},...d?{configId:i.id}:{},dryRun:e.dryRun,startedAt:oe,finishedAt:new Date().toISOString(),result:{...q,status:je},...At(),...Y?{checkpoint:Y}:{},apiRequests:kt(V?.apiRequests,g()),created:{runId:x.runId,...It?{lastWrittenAt:It}:{},...Et?{firstWrittenAt:Et}:{},...Tt?{lastWriteAt:Tt}:{},...ye?{runFile:ye}:{},objects:ze,...Oe.length>0?{overwritten:Oe}:{},...Je.length>0?{deleted:Je}:{}},elapsedMs:xt},null,2)}
309
+ `),ce&&process.exit(xe(ce)),Ee(Ie(je,e.failOnPartial));return}let Pt=q.objectResults??[];n(`
310
+ status: ${je}`);for(let o of we?fe(we,e.target):[])n(o);for(let o of Pt){n(` ${Uo(o)}`),typeof o.alreadyCopied=="number"&&n(` ${o.alreadyCopied} already copied by an earlier run of this configuration, left as they are`),typeof o.alreadyLinked=="number"&&n(` ${no(o.alreadyLinked)}`);for(let w of Lo(o.errors??[]))n(` ${w}`);for(let w of qo(o))n(` ${w}`);for(let w of zo(o.currenciesReplaced))n(` ${w}`);for(let w of Jo(o.pricesSettled,o.standardPricebookMatched===!0))n(` ${w}`);let c=o.files;c&&n(` files: ${c.copied??0} copied, ${c.versions??0} version(s) added, ${c.failed??0} failed`);let p=o.delta;p&&n(` ${Ho(p)}`)}for(let o of to(Pt,!1))n(` ${o}`);for(let o of Go(q.contactPoints))n(` ${o}`);let Nt=ze.reduce((o,c)=>o+c.ids.length,0),Mt=Oe.reduce((o,c)=>o+c.ids.length,0);Mt>0&&n(`
311
+ wrote over ${Mt} record(s) of ${e.target}, their values from before kept in ${pe(J,"backups")}: --remove ${ye??"with the --json summary"} gives them back`),Nt>0&&n(`
312
+ created ${Nt} record(s) and file(s) in ${e.target}: `+(ye!==void 0?`--remove ${ye} takes them back`:"run with --json and save the summary to a file, and --remove takes them back from it")),n(`
313
+ done in ${xt}ms`),ce&&process.exit(xe(ce)),Ee(Ie(je,e.failOnPartial))}var Ue=new Set(["--remove","--target","--include-changed","--accept-automation","--mute-automation","--store","--sweep","--sweep-list",...br,"--leave-undeletable","--json"]),Qo=new Set(["--remove","--target","--store"]);function es(t){let r=t.slice(2);for(let u=0;u<r.length;u++){let l=r[u];if(Qo.has(l)){u++;continue}Ue.has(l)||(process.stderr.write(`--remove takes --target, --include-changed, --accept-automation, --mute-automation, --store, --sweep, --sweep-late, --sweep-untied, --sweep-list, --leave-undeletable and --json, not "${l}". Run with --help.
314
+ `),process.exit(2))}let e=u=>{let l=r.indexOf(u);return l>=0&&l+1<r.length?r[l+1]:void 0},n=e("--remove"),s=e("--target"),i=e("--store");r.includes("--store")&&(!i||Ue.has(i))&&(process.stderr.write(`--store wants the directory the configuration of the run is kept in.
315
+ `),process.exit(2)),(!n||!s||Ue.has(n)||Ue.has(s))&&(process.stderr.write(`--remove takes the file a run printed its --json summary to, or the run file it named as it began, or its run id, and --target the org the run wrote to. Run with --help.
316
316
  `),process.exit(2)),r.includes("--sweep")&&r.includes("--sweep-list")&&(process.stderr.write(`--sweep deletes and --sweep-list only lists: give one of them. Run with --help.
317
317
  `),process.exit(2));let d=Rr(r);return"refusal"in d&&(process.stderr.write(`${d.refusal} Run with --help.
318
- `),process.exit(2)),{summaryPath:n,target:s,includeChanged:r.includes("--include-changed"),acceptAutomation:r.includes("--accept-automation"),muteAutomation:r.includes("--mute-automation"),json:r.includes("--json"),...i!==void 0?{store:i}:{},sweep:r.includes("--sweep"),sweepList:r.includes("--sweep-list"),...d,leaveUndeletable:r.includes("--leave-undeletable")}}var qe=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,es=R.object({tool:R.literal("sandforge-sync"),source:R.string().min(1),target:R.string().min(1),targetOrgId:R.string().regex(qe).optional(),configId:R.string().min(1).max(200).optional(),dryRun:R.boolean().optional(),startedAt:R.string().min(1).max(40).optional(),finishedAt:R.string().min(1).max(40).optional(),result:R.object({status:R.enum(["success","partial","failure"])}).loose(),created:R.object({runId:R.string().min(1).max(200),lastWrittenAt:R.string().min(1).max(40).optional(),firstWrittenAt:R.string().min(1).max(40).optional(),lastWriteAt:R.string().min(1).max(40).optional(),objects:R.array(R.object({objectApiName:R.string().regex(_),ids:R.array(R.string().regex(qe))})),overwritten:R.array(R.object({objectApiName:R.string().regex(_),backup:vn,ids:R.array(R.string().regex(qe))})).optional(),deleted:R.array(R.object({objectApiName:R.string().regex(_),ids:R.array(R.string().regex(qe))})).optional()}).optional()}).loose();function ts(t){let r;try{r=JSON.parse(t)}catch{return{refusal:"is not JSON: save the output of a run printed with --json."}}let e=en(r,"sandforge-sync");if(e)return{refusal:tn(e)};let n=es.safeParse(r);if(!n.success){let s=n.error.issues[0];return{refusal:`is not the summary of a sandforge sync run (${s.path.join(".")||"summary"}: ${s.message}).`}}return n.data.dryRun===!0?{refusal:"is the summary of a dry run, which wrote nothing: there is nothing to remove."}:n.data.created?{summary:n.data}:{refusal:"names nothing the run created: it was printed before runs named what they created, so its records cannot be told from the ones it updated."}}function ns(t){return/\.json$/i.test(t)?t.replace(/\.json$/i,".removals.json"):`${t}.removals.json`}function rs(t,r){let e=t.created,n=t.finishedAt??e?.lastWrittenAt??new Date().toISOString();return{runId:e?.runId??"sandforge-sync",configId:t.configId??"sandforge-sync",configName:t.configId??"sandforge-sync",sourceOrgId:t.source,targetOrgId:t.target,startedAt:t.startedAt??n,end:{at:n,status:t.result.status},...e?.lastWrittenAt?{lastWrittenAt:e.lastWrittenAt}:{},...e?.firstWrittenAt?{firstWrittenAt:e.firstWrittenAt}:{},...e?.lastWriteAt?{lastWriteAt:e.lastWriteAt}:{},created:(e?.objects??[]).filter(s=>s.ids.length>0),...(e?.overwritten??[]).some(s=>s.ids.length>0)?{overwritten:(e?.overwritten??[]).filter(s=>s.ids.length>0)}:{},...(e?.deleted??[]).some(s=>s.ids.length>0)?{deleted:(e?.deleted??[]).filter(s=>s.ids.length>0)}:{},...r?{removal:r}:{}}}function os(t,r,e="sandforge sync"){if(r.sandbox||Dt(r.edition))return;let n=r.edition?`IsSandbox false, edition ${r.edition}`:"IsSandbox false, and no edition";return`${t} is a production org (its Organization record says ${n}): ${e} removes records from sandboxes and Developer Edition orgs only. Nothing was deleted.`}function ss(t,r){let e=n=>[n.deleted>0?`${n.deleted} deleted`:"",n.alreadyGone>0?`${n.alreadyGone} already gone`:"",(n.notVisible??0)>0?`${n.notVisible} not visible`:"",n.keptChanged>0?`${n.keptChanged} kept, changed since the run`:"",n.keptDependents>0?`${n.keptDependents} kept, records that stay depend on them`:"",n.refused>0?`${n.refused} refused`:"",(n.notReached??0)>0?`${n.notReached} not reached`:""].filter(Boolean).join(", ");return[`removal: ${t.toUpperCase()}`,...r.flatMap(n=>[` ${n.objectApiName}: ${e(n)||"nothing"} of ${n.planned}${gr(n)}`,...mr(n),...n.reasons.map(s=>` ${s}`)])]}function is(t){return t.flatMap(r=>{let e=[r.keptChanged>0?`${r.keptChanged} left as they are, changed since the run`:"",r.alreadyGone>0?`${r.alreadyGone} no longer in the org`:"",r.refused>0?`${r.refused} refused`:"",r.notKept>0?`${r.notKept} whose values from before are no longer kept (their backup was deleted, or past its retention)`:"",(r.notReached??0)>0?`${r.notReached} not reached`:"",(r.restoredWithout??0)>0?`${r.restoredWithout} given back but for fields the org no longer takes, which keep the run's values`:""].filter(Boolean);return[` ${r.objectApiName}: ${r.restored} of ${r.planned} given back their values from before the run${e.length>0?`; ${e.join(", ")}`:""}`,...r.reasons.map(n=>` ${n}`)]})}function as(t){return t.flatMap(r=>{let e=[r.alreadyBack>0?`${r.alreadyBack} back in the org already`:"",r.goneForGood>0?`${r.goneForGood} no longer in the recycle bin, gone for good`:"",r.refused>0?`${r.refused} refused`:"",(r.notReached??0)>0?`${r.notReached} not reached`:""].filter(Boolean);return[` ${r.objectApiName}: ${r.undeleted} of ${r.planned} the run deleted brought back from the recycle bin${e.length>0?`; ${e.join(", ")}`:""}`,...r.reasons.map(n=>` ${n}`)]})}function ds(t,r){return t===void 0?[]:[...r.readWhole&&r.readWhole.length>0?[`configuration ${t}: its next run reads ${r.readWhole.join(", ")} whole`]:[],...(r.filesForgotten??0)>0?[`configuration ${t}: ${r.filesForgotten} copied file(s) forgotten, copied again by its next run`]:[],...(r.linksForgotten??0)>0?[`configuration ${t}: ${r.linksForgotten} record(s) forgotten, which no later run points a lookup at`]:[]]}var Zr=3,cs=/^[A-Za-z0-9][A-Za-z0-9_-]{0,199}$/;function us(t,r=De(),e=kn){if(ve(t)){let s;try{s=$e(t,"utf8").split(`
319
- `).find(d=>d.trim()!=="")}catch{return}let i;try{i=JSON.parse(s??"")}catch{return}return typeof i=="object"&&i!==null&&"run"in i?bo(t):void 0}if(!cs.test(t))return;let n=he(r,e,`${t}.ndjson`);return ve(n)?n:void 0}function ls(t){let r=ct(t.runUserId),e=pr.safeParse(t.mutedAutomation);return{...r?{runUserId:r}:{},...e.success?{muted:e.data}:{}}}function fs(t,r){let e;try{e=$e(t.summaryPath,"utf8")}catch(f){process.stderr.write(`--remove ${t.summaryPath} cannot be read: ${f instanceof Error?f.message:String(f)}
320
- `),process.exit(2)}let n=ts(e);"refusal"in n&&(process.stderr.write(`--remove ${t.summaryPath} ${n.refusal}
318
+ `),process.exit(2)),{summaryPath:n,target:s,includeChanged:r.includes("--include-changed"),acceptAutomation:r.includes("--accept-automation"),muteAutomation:r.includes("--mute-automation"),json:r.includes("--json"),...i!==void 0?{store:i}:{},sweep:r.includes("--sweep"),sweepList:r.includes("--sweep-list"),...d,leaveUndeletable:r.includes("--leave-undeletable")}}var Be=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ts=R.object({tool:R.literal("sandforge-sync"),source:R.string().min(1),target:R.string().min(1),targetOrgId:R.string().regex(Be).optional(),configId:R.string().min(1).max(200).optional(),dryRun:R.boolean().optional(),startedAt:R.string().min(1).max(40).optional(),finishedAt:R.string().min(1).max(40).optional(),result:R.object({status:R.enum(["success","partial","failure"])}).loose(),created:R.object({runId:R.string().min(1).max(200),lastWrittenAt:R.string().min(1).max(40).optional(),firstWrittenAt:R.string().min(1).max(40).optional(),lastWriteAt:R.string().min(1).max(40).optional(),objects:R.array(R.object({objectApiName:R.string().regex(M),ids:R.array(R.string().regex(Be))})),overwritten:R.array(R.object({objectApiName:R.string().regex(M),backup:vn,ids:R.array(R.string().regex(Be))})).optional(),deleted:R.array(R.object({objectApiName:R.string().regex(M),ids:R.array(R.string().regex(Be))})).optional()}).optional()}).loose();function ns(t){let r;try{r=JSON.parse(t)}catch{return{refusal:"is not JSON: save the output of a run printed with --json."}}let e=en(r,"sandforge-sync");if(e)return{refusal:tn(e)};let n=ts.safeParse(r);if(!n.success){let s=n.error.issues[0];return{refusal:`is not the summary of a sandforge sync run (${s.path.join(".")||"summary"}: ${s.message}).`}}return n.data.dryRun===!0?{refusal:"is the summary of a dry run, which wrote nothing: there is nothing to remove."}:n.data.created?{summary:n.data}:{refusal:"names nothing the run created: it was printed before runs named what they created, so its records cannot be told from the ones it updated."}}function rs(t){return/\.json$/i.test(t)?t.replace(/\.json$/i,".removals.json"):`${t}.removals.json`}function os(t,r){let e=t.created,n=t.finishedAt??e?.lastWrittenAt??new Date().toISOString();return{runId:e?.runId??"sandforge-sync",configId:t.configId??"sandforge-sync",configName:t.configId??"sandforge-sync",sourceOrgId:t.source,targetOrgId:t.target,startedAt:t.startedAt??n,end:{at:n,status:t.result.status},...e?.lastWrittenAt?{lastWrittenAt:e.lastWrittenAt}:{},...e?.firstWrittenAt?{firstWrittenAt:e.firstWrittenAt}:{},...e?.lastWriteAt?{lastWriteAt:e.lastWriteAt}:{},created:(e?.objects??[]).filter(s=>s.ids.length>0),...(e?.overwritten??[]).some(s=>s.ids.length>0)?{overwritten:(e?.overwritten??[]).filter(s=>s.ids.length>0)}:{},...(e?.deleted??[]).some(s=>s.ids.length>0)?{deleted:(e?.deleted??[]).filter(s=>s.ids.length>0)}:{},...r?{removal:r}:{}}}function ss(t,r,e="sandforge sync"){if(r.sandbox||Dt(r.edition))return;let n=r.edition?`IsSandbox false, edition ${r.edition}`:"IsSandbox false, and no edition";return`${t} is a production org (its Organization record says ${n}): ${e} removes records from sandboxes and Developer Edition orgs only. Nothing was deleted.`}function is(t,r){let e=n=>[n.deleted>0?`${n.deleted} deleted`:"",n.alreadyGone>0?`${n.alreadyGone} already gone`:"",(n.notVisible??0)>0?`${n.notVisible} not visible`:"",n.keptChanged>0?`${n.keptChanged} kept, changed since the run`:"",n.keptDependents>0?`${n.keptDependents} kept, records that stay depend on them`:"",n.refused>0?`${n.refused} refused`:"",(n.notReached??0)>0?`${n.notReached} not reached`:""].filter(Boolean).join(", ");return[`removal: ${t.toUpperCase()}`,...r.flatMap(n=>[` ${n.objectApiName}: ${e(n)||"nothing"} of ${n.planned}${gr(n)}`,...mr(n),...n.reasons.map(s=>` ${s}`)])]}function as(t){return t.flatMap(r=>{let e=[r.keptChanged>0?`${r.keptChanged} left as they are, changed since the run`:"",r.alreadyGone>0?`${r.alreadyGone} no longer in the org`:"",r.refused>0?`${r.refused} refused`:"",r.notKept>0?`${r.notKept} whose values from before are no longer kept (their backup was deleted, or past its retention)`:"",(r.notReached??0)>0?`${r.notReached} not reached`:"",(r.restoredWithout??0)>0?`${r.restoredWithout} given back but for fields the org no longer takes, which keep the run's values`:""].filter(Boolean);return[` ${r.objectApiName}: ${r.restored} of ${r.planned} given back their values from before the run${e.length>0?`; ${e.join(", ")}`:""}`,...r.reasons.map(n=>` ${n}`)]})}function ds(t){return t.flatMap(r=>{let e=[r.alreadyBack>0?`${r.alreadyBack} back in the org already`:"",r.goneForGood>0?`${r.goneForGood} no longer in the recycle bin, gone for good`:"",r.refused>0?`${r.refused} refused`:"",(r.notReached??0)>0?`${r.notReached} not reached`:""].filter(Boolean);return[` ${r.objectApiName}: ${r.undeleted} of ${r.planned} the run deleted brought back from the recycle bin${e.length>0?`; ${e.join(", ")}`:""}`,...r.reasons.map(n=>` ${n}`)]})}function cs(t,r){return t===void 0?[]:[...r.readWhole&&r.readWhole.length>0?[`configuration ${t}: its next run reads ${r.readWhole.join(", ")} whole`]:[],...(r.filesForgotten??0)>0?[`configuration ${t}: ${r.filesForgotten} copied file(s) forgotten, copied again by its next run`]:[],...(r.linksForgotten??0)>0?[`configuration ${t}: ${r.linksForgotten} record(s) forgotten, which no later run points a lookup at`]:[]]}var Zr=3,us=/^[A-Za-z0-9][A-Za-z0-9_-]{0,199}$/;function ls(t,r=_e(),e=kn){if(Se(t)){let s;try{s=ve(t,"utf8").split(`
319
+ `).find(d=>d.trim()!=="")}catch{return}let i;try{i=JSON.parse(s??"")}catch{return}return typeof i=="object"&&i!==null&&"run"in i?Ro(t):void 0}if(!us.test(t))return;let n=pe(r,e,`${t}.ndjson`);return Se(n)?n:void 0}function fs(t){let r=ct(t.runUserId),e=pr.safeParse(t.mutedAutomation);return{...r?{runUserId:r}:{},...e.success?{muted:e.data}:{}}}function hs(t,r){let e;try{e=ve(t.summaryPath,"utf8")}catch(f){process.stderr.write(`--remove ${t.summaryPath} cannot be read: ${f instanceof Error?f.message:String(f)}
320
+ `),process.exit(2)}let n=ns(e);"refusal"in n&&(process.stderr.write(`--remove ${t.summaryPath} ${n.refusal}
321
321
  `),process.exit(2));let{summary:s}=n;s.targetOrgId===void 0&&s.target!==t.target&&(process.stderr.write(`The run wrote to ${s.target}, and what it created is removed from that org only: give --target ${s.target}.
322
- `),process.exit(2));let i=ns(t.summaryPath),d,u;try{u=$e(i,"utf8")}catch(f){f?.code!=="ENOENT"&&(process.stderr.write(`${i} cannot be read: ${f instanceof Error?f.message:String(f)}
322
+ `),process.exit(2));let i=rs(t.summaryPath),d,u;try{u=ve(i,"utf8")}catch(f){f?.code!=="ENOENT"&&(process.stderr.write(`${i} cannot be read: ${f instanceof Error?f.message:String(f)}
323
323
  `),process.exit(2))}if(u!==void 0){let f;try{f=JSON.parse(u)}catch{f=void 0}let g=f?.runId;d=g===s.created?.runId?$n(f):void 0,g!==s.created?.runId?r(`${i} is of another run: it is not read, and this removal's takes its place`):d||(process.stderr.write(`${i} does not read as what earlier removals did.
324
- `),process.exit(2))}let l=rs(s,d),a=d??{};return{run:l,...s.configId!==void 0?{configId:s.configId}:{},...s.targetOrgId!==void 0?{targetOrgId:s.targetOrgId}:{},...d?{earlier:d}:{},...ls(s.result),updateRemoval:async f=>{a=f(a);let g=`${i}.${process.pid}.tmp`;wo(g,`${JSON.stringify({version:1,runId:l.runId,...a},null,2)}
325
- `),mo(g,i)}}}async function hs(t,r){let e=Qe(yo(t),""),n;try{n=An($e(t,"utf8"))}catch(d){process.stderr.write(`--remove ${t} cannot be read: ${d instanceof Error?d.message:String(d)}
324
+ `),process.exit(2))}let l=os(s,d),a=d??{};return{run:l,...s.configId!==void 0?{configId:s.configId}:{},...s.targetOrgId!==void 0?{targetOrgId:s.targetOrgId}:{},...d?{earlier:d}:{},...fs(s.result),updateRemoval:async f=>{a=f(a);let g=`${i}.${process.pid}.tmp`;yo(g,`${JSON.stringify({version:1,runId:l.runId,...a},null,2)}
325
+ `),wo(g,i)}}}async function ps(t,r){let e=Qe(bo(t),""),n;try{n=An(ve(t,"utf8"))}catch(d){process.stderr.write(`--remove ${t} cannot be read: ${d instanceof Error?d.message:String(d)}
326
326
  `),process.exit(2)}n||(process.stderr.write(`--remove ${t} names no run of sandforge sync.
327
327
  `),process.exit(2)),e.pathOf(n.runId)!==t&&(process.stderr.write(`--remove ${t} is the file of the run ${n.runId} under another name: give it as ${e.pathOf(n.runId)}, where what its removals did is kept beside it.
328
328
  `),process.exit(2));let s=await e.get(n.runId)??n;s.targetOrganizationId===void 0&&s.targetOrgId!==r.target&&(process.stderr.write(`The run wrote to ${s.targetOrgId}, and what it created is removed from that org only: give --target ${s.targetOrgId}.
329
- `),process.exit(2));let i=ct(s.runUserId);return{run:s,...s.configId!==St?{configId:s.configId}:{},...s.targetOrganizationId!==void 0?{targetOrgId:s.targetOrganizationId}:{},...s.removal?{earlier:s.removal}:{},updateRemoval:d=>e.updateRemoval(s.runId,d),runs:e,...i?{runUserId:i}:{}}}function ps(t,r){return t.map(({job:e,objectApiName:n,read:s})=>{let i=` Bulk API job ${e} (${n})`;switch(s.state){case"ended":return`${i}: the run's file holds no answer of it; it ended in ${r}, and the ${s.created.length} record(s) it created are removed with the rest`;case"never-closed":return`${i}: never closed, it wrote nothing`;case"running":return`${i}: still running in ${r}: what it creates stays, and the next --remove of the run reads it again`;default:return`${i}: could not be read back (${s.reason}): what it created stays`}})}async function gs(t=process.argv){let r=Date.now(),e=Qo(t),n=h=>{process[e.json?"stderr":"stdout"].write(`${h}
330
- `)},s=us(e.summaryPath),i=s!==void 0?await hs(s,e):fs(e,n),{earlier:d}=i,u;e.store!==void 0&&(i.configId===void 0&&(process.stderr.write(`--store tells the configuration a run was of what its removal took, and ${e.summaryPath} names none: the run was not of a saved configuration (--config-file).
331
- `),process.exit(2)),u=ve(he(e.store,"configStore.json"))?Qr(e.store):void 0,u?.isSaved(i.configId)||(process.stderr.write(`${e.store} holds no configuration ${i.configId}: give the --store the run was made with.
332
- `),process.exit(2)));let l=i.run;Rn(l)&&W({code:Vt,message:`The run is still writing, in process ${l.writer?.pid??"?"}: remove it once it has ended. Nothing was deleted.`});let a,f=(h,m,O,A={},x,Q,ie,we)=>{if(e.json){process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",action:"remove",summary:e.summaryPath,target:e.target,includeChanged:e.includeChanged,result:{status:h,planned:O,objects:m,...A,...x?{sweep:x}:{},...a?{sweepListing:a}:{},...Q?{restored:Q}:{},...ie?{undeleted:ie}:{},...we?{mutedAutomation:we}:{}},elapsedMs:Date.now()-r},null,2)}
333
- `);for(let T of lt(m,e))n(T);return}for(let T of x?yr(x):[])n(T);for(let T of ss(h,m))n(T);for(let T of lt(m,e))n(T);for(let T of ie?as(ie):[])n(T);for(let T of Q?is(Q):[])n(T);for(let T of ds(i.configId,A))n(T);n(`
334
- done in ${Date.now()-r}ms`)},g=i.runs!==void 0&&(l.jobs??[]).length>0;if(et(l).length===0&&tt(l).length===0&&nt(l).length===0&&!g&&!e.sweep&&!e.sweepList){let h=d?.undo?.removedAt??d?.restoredAt??d?.undeletedAt;n(h!==void 0?`what the run created was removed already, on ${h}`:"The run created nothing: there is nothing of it to remove."),f("success",[],0);return}let v=await xe(e.target),k=Se(v),y=await ke(k),j=e.sweepList?void 0:os(e.target,y);if(j&&W({code:"PRODUCTION_TARGET",message:j}),i.targetOrgId!==void 0&&i.targetOrgId.slice(0,15)!==y.id.slice(0,15)&&W({code:Yt,message:`${e.target} is not the org the run wrote to (${i.targetOrgId}), and what it created is removed from that org only. Nothing was deleted.`}),g&&i.runs){let h=i.runs,m=await Or(h,l,k,()=>Pe(k,"sandforge sync --remove").serverTime());for(let O of ps(m,e.target))n(O);m.some(O=>O.answered)&&(l=await h.get(l.runId)??l)}!l.end&&l.inFlight&&l.inFlight.job===void 0&&n(` the run stopped during a call of ${l.inFlight.rows} ${l.inFlight.objectApiName} row(s): those ${e.target} took are not in its file, and stay; ${ut("--sweep-list")} shows what the run's user created in the run's window`);let I=et(l),U=async h=>{let m;try{m=await We(k).read(e.target,[...new Set([...l.created,...l.overwritten??[]].map(x=>x.objectApiName).filter(x=>!Sn.includes(x)))])}catch(x){m={error:x instanceof Error?x.message:String(x)}}let O=Pe(k,"sandforge sync --sweep"),A=Ar({otherRuns:await $r({organizationId:y.id,alias:e.target,span:vr(l),own:{runId:l.runId,ids:l.created.flatMap(x=>x.ids)}}),...i.muted?{muted:i.muted}:{},...d?.removalSpans?{removalSpans:d.removalSpans}:{},...d?.madeEarlier?{made:d.madeEarlier}:{},...d?.lateEarlier?{late:d.lateEarlier}:{}});return Er(O,l.created,m,h,l.firstWrittenAt!==void 0?{at:l.firstWrittenAt,...l.lastWriteAt!==void 0?{lastAt:l.lastWriteAt}:{},serverTime:()=>O.serverTime()}:void 0,l.overwritten??[],{...i.runUserId?{runUserId:i.runUserId}:{},ties:A})};if(e.sweepList){let h=await Qn(ft(k,"sandforge sync --sweep-list"),await U(),d?.removalSpans??[]);for(let m of Ue(h,e.target,e,!0))n(m);e.json?process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",action:"sweep-list",summary:e.summaryPath,target:e.target,listing:h,elapsedMs:Date.now()-r},null,2)}
329
+ `),process.exit(2));let i=ct(s.runUserId);return{run:s,...s.configId!==St?{configId:s.configId}:{},...s.targetOrganizationId!==void 0?{targetOrgId:s.targetOrganizationId}:{},...s.removal?{earlier:s.removal}:{},updateRemoval:d=>e.updateRemoval(s.runId,d),runs:e,...i?{runUserId:i}:{}}}function gs(t,r){return t.map(({job:e,objectApiName:n,read:s})=>{let i=` Bulk API job ${e} (${n})`;switch(s.state){case"ended":return`${i}: the run's file holds no answer of it; it ended in ${r}, and the ${s.created.length} record(s) it created are removed with the rest`;case"never-closed":return`${i}: never closed, it wrote nothing`;case"running":return`${i}: still running in ${r}: what it creates stays, and the next --remove of the run reads it again`;default:return`${i}: could not be read back (${s.reason}): what it created stays`}})}async function ms(t=process.argv){let r=Date.now(),e=es(t),n=h=>{process[e.json?"stderr":"stdout"].write(`${h}
330
+ `)},s=ls(e.summaryPath),i=s!==void 0?await ps(s,e):hs(e,n),{earlier:d}=i,u;e.store!==void 0&&(i.configId===void 0&&(process.stderr.write(`--store tells the configuration a run was of what its removal took, and ${e.summaryPath} names none: the run was not of a saved configuration (--config-file).
331
+ `),process.exit(2)),u=Se(pe(e.store,"configStore.json"))?Qr(e.store):void 0,u?.isSaved(i.configId)||(process.stderr.write(`${e.store} holds no configuration ${i.configId}: give the --store the run was made with.
332
+ `),process.exit(2)));let l=i.run;Rn(l)&&H({code:Vt,message:`The run is still writing, in process ${l.writer?.pid??"?"}: remove it once it has ended. Nothing was deleted.`});let a,f=(h,m,j,v={},I,ee,te,Ae)=>{if(e.json){process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",action:"remove",summary:e.summaryPath,target:e.target,includeChanged:e.includeChanged,result:{status:h,planned:j,objects:m,...v,...I?{sweep:I}:{},...a?{sweepListing:a}:{},...ee?{restored:ee}:{},...te?{undeleted:te}:{},...Ae?{mutedAutomation:Ae}:{}},elapsedMs:Date.now()-r},null,2)}
333
+ `);for(let E of lt(m,e))n(E);return}for(let E of I?yr(I):[])n(E);for(let E of is(h,m))n(E);for(let E of lt(m,e))n(E);for(let E of te?ds(te):[])n(E);for(let E of ee?as(ee):[])n(E);for(let E of cs(i.configId,v))n(E);n(`
334
+ done in ${Date.now()-r}ms`)},g=i.runs!==void 0&&(l.jobs??[]).length>0;if(et(l).length===0&&tt(l).length===0&&nt(l).length===0&&!g&&!e.sweep&&!e.sweepList){let h=d?.undo?.removedAt??d?.restoredAt??d?.undeletedAt;n(h!==void 0?`what the run created was removed already, on ${h}`:"The run created nothing: there is nothing of it to remove."),f("success",[],0);return}let $=await Ce(e.target),k=ke($),y=await Re(k),C=e.sweepList?void 0:ss(e.target,y);if(C&&H({code:"PRODUCTION_TARGET",message:C}),i.targetOrgId!==void 0&&i.targetOrgId.slice(0,15)!==y.id.slice(0,15)&&H({code:Yt,message:`${e.target} is not the org the run wrote to (${i.targetOrgId}), and what it created is removed from that org only. Nothing was deleted.`}),g&&i.runs){let h=i.runs,m=await Or(h,l,k,()=>Fe(k,"sandforge sync --remove").serverTime());for(let j of gs(m,e.target))n(j);m.some(j=>j.answered)&&(l=await h.get(l.runId)??l)}!l.end&&l.inFlight&&l.inFlight.job===void 0&&n(` the run stopped during a call of ${l.inFlight.rows} ${l.inFlight.objectApiName} row(s): those ${e.target} took are not in its file, and stay; ${ut("--sweep-list")} shows what the run's user created in the run's window`);let x=et(l),U=async h=>{let m;try{m=await De(k).read(e.target,[...new Set([...l.created,...l.overwritten??[]].map(I=>I.objectApiName).filter(I=>!Sn.includes(I)))])}catch(I){m={error:I instanceof Error?I.message:String(I)}}let j=Fe(k,"sandforge sync --sweep"),v=Ar({otherRuns:await $r({organizationId:y.id,alias:e.target,span:vr(l),own:{runId:l.runId,ids:l.created.flatMap(I=>I.ids)}}),...i.muted?{muted:i.muted}:{},...d?.removalSpans?{removalSpans:d.removalSpans}:{},...d?.madeEarlier?{made:d.madeEarlier}:{},...d?.lateEarlier?{late:d.lateEarlier}:{}});return Er(j,l.created,m,h,l.firstWrittenAt!==void 0?{at:l.firstWrittenAt,...l.lastWriteAt!==void 0?{lastAt:l.lastWriteAt}:{},serverTime:()=>j.serverTime()}:void 0,l.overwritten??[],{...i.runUserId?{runUserId:i.runUserId}:{},ties:v})};if(e.sweepList){let h=await Qn(ft(k,"sandforge sync --sweep-list"),await U(),d?.removalSpans??[]);for(let m of We(h,e.target,e,!0))n(m);e.json?process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",action:"sweep-list",summary:e.summaryPath,target:e.target,listing:h,elapsedMs:Date.now()-r},null,2)}
335
335
  `):n(`
336
- done in ${Date.now()-r}ms`),h.refusal!==void 0&&process.exit(Zr);return}let S=tt(l),$,b={kept:[...S],notKept:0};if(S.length>0){let h=ht(),m=pt(h);if(m!==void 0)n(m);else{$=new st(ot(h));let O=Le(he(h,"snapshots.json"));b=En(S,A=>O.get(`backup:${A}`),30)}}n(`sandforge sync --remove ${e.summaryPath} from ${e.target}`);for(let{objectApiName:h,ids:m}of b.kept)n(` ${h}: ${m.length} to give back their values from before the run`);b.notKept>0&&n(` values from before no longer kept (past sandforge.backup.maxAgeDays, or deleted): ${b.notKept} record(s) the run wrote over keep its values`),b.keptUntil!==void 0&&b.kept.length>0&&n(` values from before kept until ${b.keptUntil}, at the default retention`);let J=nt(l);for(let{objectApiName:h,ids:m}of J)n(` ${h}: ${m.length} the run deleted, as the source had, to bring back from the recycle bin`);for(let{objectApiName:h,ids:m}of I)n(` ${h}: ${m.length} to remove`);I.length===0&&S.length===0&&J.length===0&&n("nothing left of the run to remove"),e.sweep&&n(`before them, a sweep deletes what the target's automation made for the run, as the run's user, tied to its records \u2014 run ${ut("--sweep-list")} to see what`);let N=new AbortController,H=Ve(()=>N.abort()),X=d??{},L=e.sweep?er(ft(k,"sandforge sync --sweep",N.signal),await U(N.signal),{includeChanged:e.includeChanged,removalSpans:X.removalSpans??[],...kr(e),approve:async h=>{a=h,n("");for(let m of Ue(h,e.target,e))n(m)}}):void 0;await L?.ask();let K=wr(L,a);if(K){a=K,n("");for(let h of Ue(K,e.target,e))n(h)}let D=h=>[...new Set(h.map(({objectApiName:m})=>m))],B=qt({bringBack:D(J),giveBack:D(b.kept),setToDraft:mn(D(I)),delete:wn(D(I))},L?.takes??[]),Ae=[...new Set(Object.values(B).flat())];function W(h){return process.stderr.write(`${Fe(h)}
337
- `),e.json&&process.stdout.write(Qt({tool:"sandforge-sync",summary:e.summaryPath,target:e.target,elapsedMs:Date.now()-r},h)),process.exit(1)}let ne=h=>(H(),W(h)),F;if(Ae.length>0&&!N.signal.aborted){let h=await We(k).read(e.target,Ae,{undeletes:!0});n("");for(let A of Kn(h,e.target,B))n(A);if(e.muteAutomation)try{F=await _e(async()=>Ne(k),h,{writes:Gt(B)});for(let A of le(F.muted,e.target))n(` ${A}`)}catch(A){if(!Me(A))throw A;ne(A.refusal)}let m=F?.automation??h,O=Yn(m,e.target,{steps:B,assign:Hn(m,zt(m,B)),mayMute:F===void 0&&Xn("--mute-automation")});O&&!e.acceptAutomation&&ne({code:"AUTOMATION_NOT_ACCEPTED",message:O})}let C,q,E=F?.muted,pe=async()=>{!F?.prepared||N.signal.aborted||(q=await F.prepared.acquire(`sandforge sync --remove ${l.runId}`).catch(h=>{if(!Me(h))throw h;return ne(h.refusal)}),E=q.outcome)},G=Pe(k,"sandforge sync --remove"),Oe=await Ir(G,l.created),M;try{C=await Cn({run:l,org:G,includeChanged:e.includeChanged,...Sr(L),...i.runUserId?{runUserId:i.runUserId}:{},onUndeletable:lr(e.leaveUndeletable,e.target,h=>{M=h}),beforeFirstWrite:pe,signal:N.signal,...u&&e.store!==void 0?{configs:u,links:Ze(e.store)}:{},...$?{backups:$}:{},undelete:h=>k.soap.undelete(h),...i.runs?{earlierRuns:jn(l,await i.runs.list())}:{},store:{updateRemoval:(h,m)=>h!==l.runId&&i.runs?i.runs.updateRemoval(h,m):i.updateRemoval(O=>(X=m(O),X))}})}finally{H();let h=L?.made??new Set,m=L?.late??new Set,O=L?.gone??new Set;if((h.size>0||m.size>0||O.size>0)&&await i.updateRemoval(A=>Tr(A,h,m,O)).catch(A=>{process.stderr.write(`What the sweep found made for the run could not be kept (${A instanceof Error?A.message:String(A)}): a later --sweep may list it as tied to nothing.
338
- `)}),q){E=await q.release();for(let A of le(E,e.target))n(A)}}E&&(C={...C,result:{...C.result,mutedAutomation:E}}),C.stoppedForUndeletable&&(M&&W(M),process.exit(1));let re=C.result.status==="cancelled"?{}:await Oe.take();for(let h of[...C.notes,...re.note?[re.note]:[]])process.stderr.write(`${h}
339
- `);let Z=C.result.objects.some(h=>h.deleted+h.alreadyGone>0);i.configId!==void 0&&!u&&Z&&process.stderr.write(`The run was of the saved configuration ${i.configId}, and its store was not given: its next delta run is not told what this removal took, and a later run may point a lookup at a record it deleted. Give ${Zn("--store")} with the next removal, or run the configuration full next time.
340
- `);let{readWhole:ge,filesForgotten:oe}=C.result,me=L?.result(),se=yn(C.result.status,me);f(se,re.object?[...C.result.objects,re.object]:C.result.objects,C.planned,{...ge?{readWhole:ge}:{},...oe!==void 0?{filesForgotten:oe}:{},...C.linksForgotten!==void 0?{linksForgotten:C.linksForgotten}:{}},me,C.result.restored,C.result.undeleted,E),se!=="success"&&process.exit(Zr)}process.argv[1]?.includes("sandforge-sync")&&(fr(),Xo().then(()=>process.exit(process.exitCode??0)).catch(t=>{process.stderr.write(`${t instanceof Error?t.message:String(t)}
341
- `),process.exit(1)}));export{Ro as a,Ao as b,Oo as c,jo as d,Qr as e,Co as f,xo as g,Vr as h,Io as i,Rt as j,Eo as k,To as l,Fo as m,Xr as n,kt as o,eo as p,to as q,no as r,No as s,_o as t,Wo as u,Bo as v,ro as w,qo as x,Go as y,zo as z,Jo as A,Ho as B,Ko as C,St as D,Xo as E,Qo as F,ts as G,ns as H,rs as I,os as J,ss as K,is as L,as as M,ds as N,us as O,ps as P,gs as Q};
336
+ done in ${Date.now()-r}ms`),h.refusal!==void 0&&process.exit(Zr);return}let S=tt(l),A,b={kept:[...S],notKept:0};if(S.length>0){let h=ht(),m=pt(h);if(m!==void 0)n(m);else{A=new st(ot(h));let j=Le(pe(h,"snapshots.json"));b=En(S,v=>j.get(`backup:${v}`),30)}}n(`sandforge sync --remove ${e.summaryPath} from ${e.target}`);for(let{objectApiName:h,ids:m}of b.kept)n(` ${h}: ${m.length} to give back their values from before the run`);b.notKept>0&&n(` values from before no longer kept (past sandforge.backup.maxAgeDays, or deleted): ${b.notKept} record(s) the run wrote over keep its values`),b.keptUntil!==void 0&&b.kept.length>0&&n(` values from before kept until ${b.keptUntil}, at the default retention`);let G=nt(l);for(let{objectApiName:h,ids:m}of G)n(` ${h}: ${m.length} the run deleted, as the source had, to bring back from the recycle bin`);for(let{objectApiName:h,ids:m}of x)n(` ${h}: ${m.length} to remove`);x.length===0&&S.length===0&&G.length===0&&n("nothing left of the run to remove"),e.sweep&&n(`before them, a sweep deletes what the target's automation made for the run, as the run's user, tied to its records \u2014 run ${ut("--sweep-list")} to see what`);let P=new AbortController,z=Ve(()=>P.abort()),Q=d??{},_=e.sweep?er(ft(k,"sandforge sync --sweep",P.signal),await U(P.signal),{includeChanged:e.includeChanged,removalSpans:Q.removalSpans??[],...kr(e),approve:async h=>{a=h,n("");for(let m of We(h,e.target,e))n(m)}}):void 0;await _?.ask();let J=wr(_,a);if(J){a=J,n("");for(let h of We(J,e.target,e))n(h)}let L=h=>[...new Set(h.map(({objectApiName:m})=>m))],B=qt({bringBack:L(G),giveBack:L(b.kept),setToDraft:mn(L(x)),delete:wn(L(x))},_?.takes??[]),$e=[...new Set(Object.values(B).flat())];function H(h){return process.stderr.write(`${Te(h)}
337
+ `),e.json&&process.stdout.write(Qt({tool:"sandforge-sync",summary:e.summaryPath,target:e.target,elapsedMs:Date.now()-r},h)),process.exit(1)}let K=h=>(z(),H(h)),D;if($e.length>0&&!P.signal.aborted){let h=await De(k).read(e.target,$e,{undeletes:!0});n("");for(let v of Kn(h,e.target,B))n(v);if(e.muteAutomation)try{D=await Me(async()=>Pe(k),h,{writes:Gt(B)});for(let v of fe(D.muted,e.target))n(` ${v}`)}catch(v){if(!Ne(v))throw v;K(v.refusal)}let m=D?.automation??h,j=Yn(m,e.target,{steps:B,assign:Hn(m,zt(m,B)),mayMute:D===void 0&&Xn("--mute-automation")});j&&!e.acceptAutomation&&K({code:"AUTOMATION_NOT_ACCEPTED",message:j})}let O,oe,N=D?.muted,W=async()=>{!D?.prepared||P.signal.aborted||(oe=await D.prepared.acquire(`sandforge sync --remove ${l.runId}`).catch(h=>{if(!Ne(h))throw h;return K(h.refusal)}),N=oe.outcome)},se=Fe(k,"sandforge sync --remove"),Y=await Ir(se,l.created),ie;try{O=await Cn({run:l,org:se,includeChanged:e.includeChanged,...Sr(_),...i.runUserId?{runUserId:i.runUserId}:{},onUndeletable:lr(e.leaveUndeletable,e.target,h=>{ie=h}),beforeFirstWrite:W,signal:P.signal,...u&&e.store!==void 0?{configs:u,links:Ze(e.store)}:{},...A?{backups:A}:{},undelete:h=>k.soap.undelete(h),...i.runs?{earlierRuns:jn(l,await i.runs.list())}:{},store:{updateRemoval:(h,m)=>h!==l.runId&&i.runs?i.runs.updateRemoval(h,m):i.updateRemoval(j=>(Q=m(j),Q))}})}finally{z();let h=_?.made??new Set,m=_?.late??new Set,j=_?.gone??new Set;if((h.size>0||m.size>0||j.size>0)&&await i.updateRemoval(v=>Tr(v,h,m,j)).catch(v=>{process.stderr.write(`What the sweep found made for the run could not be kept (${v instanceof Error?v.message:String(v)}): a later --sweep may list it as tied to nothing.
338
+ `)}),oe){N=await oe.release();for(let v of fe(N,e.target))n(v)}}N&&(O={...O,result:{...O.result,mutedAutomation:N}}),O.stoppedForUndeletable&&(ie&&H(ie),process.exit(1));let T=O.result.status==="cancelled"?{}:await Y.take(O.duplicateSets);for(let h of[...O.notes,...T.note?[T.note]:[]])process.stderr.write(`${h}
339
+ `);let qe=O.result.objects.some(h=>h.deleted+h.alreadyGone>0);i.configId!==void 0&&!u&&qe&&process.stderr.write(`The run was of the saved configuration ${i.configId}, and its store was not given: its next delta run is not told what this removal took, and a later run may point a lookup at a record it deleted. Give ${Zn("--store")} with the next removal, or run the configuration full next time.
340
+ `);let{readWhole:V,filesForgotten:ge}=O.result,ae=_?.result(),me=yn(O.result.status,ae);f(me,T.object?[...O.result.objects,T.object]:O.result.objects,O.planned,{...V?{readWhole:V}:{},...ge!==void 0?{filesForgotten:ge}:{},...O.linksForgotten!==void 0?{linksForgotten:O.linksForgotten}:{}},ae,O.result.restored,O.result.undeleted,N),me!=="success"&&process.exit(Zr)}process.argv[1]?.includes("sandforge-sync")&&(fr(),Zo().then(()=>process.exit(process.exitCode??0)).catch(t=>{process.stderr.write(`${t instanceof Error?t.message:String(t)}
341
+ `),process.exit(1)}));export{ko as a,Oo as b,jo as c,Co as d,Qr as e,xo as f,Io as g,Vr as h,Eo as i,Rt as j,To as k,Fo as l,Po as m,Xr as n,kt as o,eo as p,to as q,no as r,Mo as s,Lo as t,Uo as u,qo as v,ro as w,Go as x,zo as y,Jo as z,Ho as A,Ko as B,Yo as C,St as D,Zo as E,es as F,ns as G,rs as H,os as I,ss as J,is as K,as as L,ds as M,cs as N,ls as O,gs as P,ms as Q};
@@ -5,4 +5,4 @@ const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
7
  var l=["--help","-h"];function f(e,t){let r=new Set([...t.switches,...l]),a=new Set(t.values);for(let o=t.words??0;o<e.length;o++){let n=e[o];if(a.has(n)){let u=e[o+1];if(u===void 0||u.startsWith("--"))return`${n} wants a value. Nothing was run.`;o++;continue}if(r.has(n))continue;let s=n.indexOf("="),i=s>0?n.slice(0,s):n;return n.startsWith("-")&&s>0&&r.has(i)?`"${n}" is not read: ${i} takes no value, it is on when given and off when left out. Nothing was run.`:n.startsWith("-")&&s>0&&a.has(i)?`"${n}" is not read: give its value after a space, as ${i} ${n.slice(s+1)}. Nothing was run.`:n.startsWith("-")?`"${n}" is not a flag this command reads. Nothing was run.`:`"${n}" is not read: a value goes after the flag it is for. Nothing was run.`}}function c(e,t){let r=f(e,t);r!==void 0&&(process.stderr.write(`${r} Run with --help.
8
- `),process.exit(2))}var E=/^[A-Za-z0-9_][A-Za-z0-9_.@+-]{0,254}$/;function p(e,t){return e==="failure"?1:e==="partial"&&t?3:0}function I(e){return e.status==="failure"?1:Number(e.totalFailed??0)>0||e.partial===!0||e.keptChanged!==void 0?3:0}function T(e){e!==0&&(process.exitCode!==void 0&&process.exitCode!==0||(process.exitCode=e))}var d=[0,3,4,1];function g(e){return e.reduce((t,r)=>d.indexOf(r)>d.indexOf(t)?r:t,0)}function _(){for(let e of[process.stdout,process.stderr])e._handle?.setBlocking?.(!0)}export{c as a,E as b,p as c,I as d,T as e,g as f,_ as g};
8
+ `),process.exit(2))}var E=/^[A-Za-z0-9_][A-Za-z0-9_.@+-]{0,254}$/;function p(e,t){return e==="failure"?1:e==="partial"&&t?3:0}function I(e){return e.status==="failure"?1:Number(e.totalFailed??0)>0||e.partial===!0||e.keptChanged!==void 0?3:0}function T(e){e!==0&&(process.exitCode!==void 0&&process.exitCode!==0||(process.exitCode=e))}var d=[0,3,4,1];function g(e){return e.reduce((t,r)=>d.indexOf(r)>d.indexOf(t)?r:t,0)}function _(){for(let e of[process.stdout,process.stderr])e._handle?.setBlocking?.(!0)}export{f as a,c as b,E as c,p as d,I as e,T as f,g,_ as h};
@@ -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{i as g,n as p,o as m}from"./chunk-MFG4MUIO.mjs";import{b as w}from"./chunk-MTMH6H2A.mjs";import{dc as l,o as d,p as u}from"./chunk-TTFDUKUS.mjs";import{A as c}from"./chunk-7EANH5PY.mjs";import{a as b,b as I}from"./chunk-MS4FJDFD.mjs";import{d as f}from"./chunk-NTOVCTRS.mjs";var a=class extends Error{constructor(t,r){super(`${r} Nothing was read from ${t}.`);this.alias=t;this.reason=r;this.name="SfSessionError",this.stack=this.message}alias;reason},$=c.object({name:c.string().optional(),message:c.string().optional()}).loose();function h(e){if(typeof e!="string")return;let n=e.replace(/\u001b\[[0-9;]*m/g,""),t=n.indexOf("{");if(t!==-1)try{let r=$.safeParse(JSON.parse(n.slice(t)));return r.success?r.data:void 0}catch{return}}function C(e,n=process.platform){let t=typeof e=="object"&&e!==null?e:{};return t.code==="ENOENT"?!0:n==="win32"&&(t.status===9009||/is not recognized as an internal or external command/i.test(String(t.stderr??"")))}function S(e,n,t=process.platform){if(C(n,t))return new a(e,`${d} SandForge reads each org through the Salesforce CLI: install it with "npm install -g @salesforce/cli" (${u}), sign in to the org with "sf org login web --alias ${e}", and run again.`);let r=typeof n=="object"&&n!==null?n:{},o=h(r.stdout)??h(r.stderr);if(o?.name==="NamedOrgNotFoundError"||/^No authorization information found for /.test(o?.message??""))return new a(e,`sf does not know ${e}: "sf org list" names the orgs it knows; "sf org login web --alias ${e}" adds it (in a CI job, "sf org login jwt" or "sf org login sfdx-url").`);let s=typeof r.stderr=="string"?r.stderr.split(/\r?\n/).find(y=>y.trim()!==""):void 0,i=o?.message?.trim()||s?.trim()||(n instanceof Error?n.message:String(n));return new a(e,`sf could not show ${e}: ${i}`)}var k=f(I()),x=f(b());import{execFileSync as E}from"node:child_process";function T(e){try{return E("sf",["org","display","--target-org",e,"--json"],{encoding:"utf8",maxBuffer:50*1024*1024,shell:process.platform==="win32"})}catch(n){throw S(e,n)}}async function A(e,n=m){if(!w.test(e))throw new Error(`Invalid SF org alias: "${e}" (an alias or a username: letters, digits, _ . @ + and -, not starting with . @ + or -)`);let t=T(e),r=JSON.parse(t),o=r.result;if(typeof o?.devHubId=="string"&&o.devHubId!==""){let i=typeof o.expirationDate=="string"?l({orgType:"Scratch",metadata:{expirationDate:o.expirationDate}},new Date().toISOString().slice(0,10)):void 0;if(i!==void 0||o.status==="Deleted")throw new Error(`The scratch org '${e}' ${i!==void 0?`expired on ${i}`:"is deleted"}: Salesforce deletes a scratch org when it expires, and no sign-in brings it back. Create a new one ("sf org create scratch") and give its alias.`)}if(!r.result?.instanceUrl)throw new Error(`sf org display did not return a usable session for alias '${e}'.`);let s=await n(e);if(!p(s.accessToken))throw new Error(`The Salesforce CLI showed no usable access token for alias '${e}'. Sign in again with "sf org login web --alias ${e}" where a browser opens; in a CI job, with "sf org login jwt --alias ${e}" (a client id, a key file and a username) or "sf org login sfdx-url --alias ${e} --sfdx-url-file <file>" (see ci-examples/README.md).`);return{alias:e,username:r.result.username??"",instanceUrl:s.instanceUrl??r.result.instanceUrl,accessToken:s.accessToken,...typeof r.result.devHubId=="string"&&r.result.devHubId!==""?{scratch:!0}:{}}}function H(e,n=process.env){let t=g(e.instanceUrl,n),r=new k.default.Connection({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:"66.0",...t!==void 0?{httpProxy:t}:{}});return t===void 0&&(r._transport=new x.HttpProxyTransport("")),r}export{a,A as b,H as c};
7
+ import{i as g,n as p,o as m}from"./chunk-PBE44M2Y.mjs";import{a as b,b as I}from"./chunk-MS4FJDFD.mjs";import{c as w}from"./chunk-LCDPCUXS.mjs";import{Qc as l,p as d,q as u}from"./chunk-ZQO5PDX5.mjs";import{A as c}from"./chunk-WZQEK4WT.mjs";import{d as f}from"./chunk-NTOVCTRS.mjs";var a=class extends Error{constructor(t,r){super(`${r} Nothing was read from ${t}.`);this.alias=t;this.reason=r;this.name="SfSessionError",this.stack=this.message}alias;reason},$=c.object({name:c.string().optional(),message:c.string().optional()}).loose();function h(e){if(typeof e!="string")return;let n=e.replace(/\u001b\[[0-9;]*m/g,""),t=n.indexOf("{");if(t!==-1)try{let r=$.safeParse(JSON.parse(n.slice(t)));return r.success?r.data:void 0}catch{return}}function C(e,n=process.platform){let t=typeof e=="object"&&e!==null?e:{};return t.code==="ENOENT"?!0:n==="win32"&&(t.status===9009||/is not recognized as an internal or external command/i.test(String(t.stderr??"")))}function S(e,n,t=process.platform){if(C(n,t))return new a(e,`${d} SandForge reads each org through the Salesforce CLI: install it with "npm install -g @salesforce/cli" (${u}), sign in to the org with "sf org login web --alias ${e}", and run again.`);let r=typeof n=="object"&&n!==null?n:{},o=h(r.stdout)??h(r.stderr);if(o?.name==="NamedOrgNotFoundError"||/^No authorization information found for /.test(o?.message??""))return new a(e,`sf does not know ${e}: "sf org list" names the orgs it knows; "sf org login web --alias ${e}" adds it (in a CI job, "sf org login jwt" or "sf org login sfdx-url").`);let s=typeof r.stderr=="string"?r.stderr.split(/\r?\n/).find(y=>y.trim()!==""):void 0,i=o?.message?.trim()||s?.trim()||(n instanceof Error?n.message:String(n));return new a(e,`sf could not show ${e}: ${i}`)}var k=f(I()),x=f(b());import{execFileSync as E}from"node:child_process";function T(e){try{return E("sf",["org","display","--target-org",e,"--json"],{encoding:"utf8",maxBuffer:50*1024*1024,shell:process.platform==="win32"})}catch(n){throw S(e,n)}}async function A(e,n=m){if(!w.test(e))throw new Error(`Invalid SF org alias: "${e}" (an alias or a username: letters, digits, _ . @ + and -, not starting with . @ + or -)`);let t=T(e),r=JSON.parse(t),o=r.result;if(typeof o?.devHubId=="string"&&o.devHubId!==""){let i=typeof o.expirationDate=="string"?l({orgType:"Scratch",metadata:{expirationDate:o.expirationDate}},new Date().toISOString().slice(0,10)):void 0;if(i!==void 0||o.status==="Deleted")throw new Error(`The scratch org '${e}' ${i!==void 0?`expired on ${i}`:"is deleted"}: Salesforce deletes a scratch org when it expires, and no sign-in brings it back. Create a new one ("sf org create scratch") and give its alias.`)}if(!r.result?.instanceUrl)throw new Error(`sf org display did not return a usable session for alias '${e}'.`);let s=await n(e);if(!p(s.accessToken))throw new Error(`The Salesforce CLI showed no usable access token for alias '${e}'. Sign in again with "sf org login web --alias ${e}" where a browser opens; in a CI job, with "sf org login jwt --alias ${e}" (a client id, a key file and a username) or "sf org login sfdx-url --alias ${e} --sfdx-url-file <file>" (see ci-examples/README.md).`);return{alias:e,username:r.result.username??"",instanceUrl:s.instanceUrl??r.result.instanceUrl,accessToken:s.accessToken,...typeof r.result.devHubId=="string"&&r.result.devHubId!==""?{scratch:!0}:{}}}function H(e,n=process.env){let t=g(e.instanceUrl,n),r=new k.default.Connection({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:"66.0",...t!==void 0?{httpProxy:t}:{}});return t===void 0&&(r._transport=new x.HttpProxyTransport("")),r}export{a,A as b,H as c};
@@ -4,5 +4,5 @@ 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 _,b as I}from"./chunk-GMY5427L.mjs";import{b as j,c as E,e as T}from"./chunk-TZE3Y7IQ.mjs";import{b as c,e as C,f,k as m,l as R,n as S,o as L}from"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";import{basename as X,dirname as Z,join as ee}from"node:path";var v="FieldMapping.csv",N="ValueMapping.csv";function Y(e,t){let n=[],r=[],i="",o=!1,a=()=>{r.push(i),i=""},d=()=>{a(),r.some(l=>l!=="")&&n.push(r),r=[]};for(let l=0;l<e.length;l++){let s=e[l];o?s!=='"'?i+=s:e[l+1]==='"'?i+=e[++l]:o=!1:s==='"'&&i===""?o=!0:e.startsWith(t,l)?(a(),l+=t.length-1):s===`
7
+ import{a as _,b as I}from"./chunk-GMY5427L.mjs";import{b as j,c as E,e as T}from"./chunk-TZE3Y7IQ.mjs";import{b as c,e as C,f,k as m,l as R,n as S,o as L}from"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";import{basename as X,dirname as Z,join as ee}from"node:path";var v="FieldMapping.csv",N="ValueMapping.csv";function Y(e,t){let n=[],r=[],i="",o=!1,a=()=>{r.push(i),i=""},d=()=>{a(),r.some(l=>l!=="")&&n.push(r),r=[]};for(let l=0;l<e.length;l++){let s=e[l];o?s!=='"'?i+=s:e[l+1]==='"'?i+=e[++l]:o=!1:s==='"'&&i===""?o=!0:e.startsWith(t,l)?(a(),l+=t.length-1):s===`
8
8
  `?d():s!=="\r"&&(i+=s)}return d(),n}function V(e,t,n,r){let[i,...o]=Y(e.replace(/^\uFEFF/,""),t),a=(i??[]).map(d=>d.trim());if(!r.some(d=>!a.includes(d)))return o.map(d=>Object.fromEntries(n.map(l=>[l,(d[a.indexOf(l)]??"").trim()])))}function A(e,t){return V(e,t,["ObjectName","FieldName","Target"],["ObjectName","Target"])?.filter(r=>r.ObjectName!==""&&r.Target!=="").map(r=>({object:r.ObjectName,field:r.FieldName,target:r.Target}))}function $(e,t){let n=["ObjectName","FieldName","RawValue","Value"];return V(e,t,n,n)?.filter(i=>i.ObjectName!==""&&i.FieldName!=="").map(i=>({object:i.ObjectName,field:i.FieldName,rawValue:i.RawValue,value:i.Value}))}var te=R({targetObject:c().optional(),sourceField:c().optional(),targetField:c().optional()}),ne=R({fieldName:c().min(1),rawValue:c(),mappedValue:c()}),ie=L([c().min(1),S({name:c().min(1)})]),B=S({query:c().optional(),name:c().optional(),objectName:c().optional(),operation:c().optional(),externalId:c().optional(),master:f().optional().default(!0),excluded:f().optional(),excludedFields:m(c()).optional().default([]),useFieldMapping:f().optional(),fieldMapping:m(te).optional().default([]),useValuesMapping:f().optional(),valuesMapping:m(ne).optional().default([]),deleteOldData:f().optional().default(!1),deleteFromSource:f().optional(),deleteByHierarchy:f().optional(),hardDelete:f().optional(),updateWithMockData:f().optional().default(!1),mockFields:m(ie).optional().default([]),where:c().optional(),orderBy:c().optional(),limit:C().optional()}),re=S({objects:m(B).optional().default([]),objectSets:m(S({objects:m(B).optional().default([])})).optional(),csvFileDelimiter:c().optional(),csvReadFileDelimiter:c().optional()}).refine(e=>oe(e).length>0,{message:"An export lists its objects under objects or objectSets."});function oe(e){return[...e.objects,...(e.objectSets??[]).flatMap(t=>t.objects)]}var h=class extends Error{code;objects;constructor(t,n,r=[]){super(n),this.name="SfdmuRefusal",this.code=t,this.objects=r}},x=class extends h{constructor(t){super("TARGET_OBJECT_MAPPED",`Nothing was imported: Sync writes an object to the same object in the target org, and this export sends one to another: ${t.join("; ")}. Take out its targetObject entries, or those objects, then import it again.`,t),this.name="SfdmuTargetObjectError"}};function ae(e){return e.reduce((t,n)=>typeof n=="number"?`${t}[${n}]`:`${t}${t===""?"":"."}${String(n)}`,"")}function se(e,t){let n;try{n=JSON.parse(e)}catch(a){let d=a instanceof Error?a.message:String(a);throw new h("NOT_JSON",`Nothing was imported: ${t} is not JSON (${d}).`)}let r=new h("NO_OBJECTS",`Nothing was imported: ${t} lists no object, under objects or objectSets.`);if(typeof n!="object"||n===null||Array.isArray(n))throw r;let i=re.safeParse(n);if(i.success)return i.data;let o=[...new Set(i.error.issues.map(a=>ae(a.path)))];throw o.every(a=>a==="")?r:new h("INVALID_EXPORT",`Nothing was imported: these entries of ${t} are not of the kind SFDMU's format holds there: ${o.join(", ")}. Correct them, then import it again.`,o)}var de=["Insert","Update","Upsert","Readonly","Delete","DeleteSource","DeleteHierarchy","HardDelete"];function y(e){return(e.query?I(e.query).object:void 0)??[e.name,e.objectName].find(t=>t!==void 0&&t.trim()!=="")}function le(e){let t=(e.operation??"Readonly").trim().toLowerCase();return de.find(n=>n.toLowerCase()===t)}function ce(e){let t=[...e.objects.map((r,i)=>({entry:r,set:0,place:`objects[${i}]`})),...(e.objectSets??[]).flatMap((r,i)=>r.objects.map((o,a)=>({entry:o,set:i+1,place:`objectSets[${i}].objects[${a}]`})))],n=t.filter(({entry:r})=>y(r)===void 0).map(({entry:r,place:i})=>r.query?`${i} (${r.query.slice(0,80)})`:i);if(n.length>0)throw new h("OBJECT_NOT_NAMED",`Nothing was imported: no object can be read in these entries, neither in the FROM of a query nor under name: ${n.join("; ")}. Correct them, then import it again.`,n);return t.map(({entry:r,set:i,place:o})=>{let a=I(r.query??"");return{...r,place:o,set:i,object:y(r)??"",read:a,sfdmuOperation:le(r),settingsLeft:[...H(r,ge),...z({...r,read:a})!==r.where&&K(r.where)?["where"]:[]]}})}function z(e){return e.read.where!==void 0?e.read.where:e.where?.trim()?e.where:void 0}var pe="all";function q(e){return e.updateWithMockData?[...new Set(e.mockFields.map(t=>typeof t=="string"?t:t.name))]:[]}function ue(e){let t=e.sfdmuOperation;if(e.excluded)return{code:"excluded"};if(!e.query?.trim())return{code:"noQuery"};if(t===void 0)return{code:"unknownOperation",detail:e.operation};if(t==="Readonly")return{code:"readonly"};if(t==="DeleteSource"||t==="DeleteHierarchy")return{code:"deletesElsewhere",detail:t};let n=t==="Delete"||t==="HardDelete";if(n&&e.deleteFromSource)return{code:"deletesElsewhere",detail:"deleteFromSource"};if(n&&e.deleteByHierarchy)return{code:"deletesElsewhere",detail:"deleteByHierarchy"};if(!n&&q(e).includes(pe))return{code:"mockAllFields"}}var fe=new Set(["null","NULL","undefined","#N/A"]);function U(e){return j(e.field)&&!/^\/.*\/$/.test(e.rawValue)&&!/^eval[(].*[)]$/i.test(e.value)&&!fe.has(e.value.trim())}function K(e){return Array.isArray(e)?e.length>0:e!==!1&&e!==null&&e!==void 0&&e!==""}var ge=new Set(["query","name","objectName","operation","externalId","master","excluded","excludedFields","useFieldMapping","fieldMapping","useValuesMapping","valuesMapping","deleteOldData","deleteFromSource","deleteByHierarchy","hardDelete","updateWithMockData","mockFields","where","orderBy","limit"]),me=new Set(["objects","objectSets","orgs","csvFileDelimiter","csvReadFileDelimiter"]);function H(e,t){return Object.entries(e).filter(([n,r])=>!t.has(n)&&!n.startsWith("$")&&K(r)).map(([n])=>n)}function he(e){let t=[],n=(F,w)=>{t.push({code:F,object:e.object,...w===void 0?{}:{detail:w}})},{read:r,sfdmuOperation:i}=e,o=J(e),a=o??"Id",d=i==="Delete"||i==="HardDelete";r.object===void 0&&n("queryUnread");let l=d?void 0:_(e.query??"");l&&"every"in l&&n("everyField",l.every);let s=e.name||e.objectName;s&&s.toLowerCase()!==e.object.toLowerCase()&&n("nameDiffers",s),d&&n("delete",e.hardDelete?"HardDelete":i),o===void 0&&(i==="Update"||i==="Upsert")&&n("defaultKey"),i==="Update"&&a!=="Id"&&n("updateKey",a),a!=="Id"&&!j(a)?n("unusableKey",a):i==="Upsert"&&a!=="Id"&&!a.endsWith("__c")&&n("upsertKey",a),e.fieldMappingsIgnored>0&&n("fieldMappingOff",String(e.fieldMappingsIgnored)),e.valueRowsLeft.length>0&&n("valueRows",e.valueRowsLeft.join(", ")),e.master===!1&&n("notMaster");let u=e.limit??r.limit;u!==void 0&&n("limit",String(u));let g=z(e);g!==void 0&&!T(g)&&n("whereRefused");let b=e.orderBy??r.orderBy;b!==void 0&&!E(b)&&n("queryClause",`ORDER BY ${b}`);for(let F of r.otherClauses)n("queryClause",F);return e.deleteOldData&&!d&&n("deleteOldData"),e.mockedFields.length>0&&n("mockFields",e.mockedFields.join(", ")),e.settingsLeft.length>0&&n("settings",e.settingsLeft.join(", ")),t}function W(e){return!!e.sourceField&&!!e.targetField}function be(e){return W(e)||!!e.targetObject}function J(e){let t=e.externalId;if(!(t===void 0||t.trim()===""))return k(e.fieldMapping).find(n=>n.sourceField===t)?.targetField??t}function k(e){return[...new Map(e.filter(W).map(t=>[t.sourceField,t])).values()]}function Fe(e){return e.flatMap(t=>{let n=t.fieldMapping.flatMap(i=>i.targetObject||[]).at(-1);if(n===void 0||n.toLowerCase()===t.object.toLowerCase())return[];let r=k(t.fieldMapping).map(i=>`${i.sourceField} \u2192 ${i.targetField}`);return[`${t.object} \u2192 ${n}${r.length>0?` (${r.join(", ")})`:""}`]})}function Me(e){let t=e.csvFileDelimiter??e.csvReadFileDelimiter??"";return new Map([["comma",","],["semicolon",";"],["tab"," "],["\\t"," "]]).get(t.trim().toLowerCase())??(t||",")}var P=class{fileReader;constructor(t){this.fileReader=t}async import(t){let n=await this.fileReader.readFile(t),r=se(n,X(t)),i=ce(r),o=[],a=new Set,d=[];for(let p of i){let M=ue(p);M?o.push({...M,object:p.object}):a.has(p.object.toLowerCase())?o.push({code:"duplicate",object:p.object,detail:p.place}):(a.add(p.object.toLowerCase()),d.push(p))}let l=await this.readMappingFiles(t,r,d),s=d.map(p=>we(p,l)),u=Fe(s);if(u.length>0)throw new x(u);let g=[...l.notes],b=(r.objects.length>0?1:0)+(r.objectSets?.length??0);b>1&&g.push({code:"objectSets",detail:String(b)}),s.some(p=>O(p.sfdmuOperation)!=="delete")&&g.push({code:"contactPoints"});let F=H(r,me);F.length>0&&g.push({code:"settings",detail:F.join(", ")});let w=p=>i.findIndex(M=>M.object===p.object),Q=[...o,...s.flatMap(he)].sort((p,M)=>w(p)-w(M)),G=r.keepObjectOrderWhileExecute===!0;return{config:this.convert(Se(s,G)),notes:[...g,...Q]}}async readMappingFiles(t,n,r){let i=Me(n),o={fieldRows:[],valueRows:[],notes:[]};if(r.some(a=>a.useFieldMapping)){let a=await this.readBeside(t,v),d=a===void 0?[]:A(a,i);d?o.fieldRows=d:o.notes.push({code:"mappingFileUnread",detail:v})}if(r.some(a=>a.useValuesMapping)){let a=await this.readBeside(t,N),d=a===void 0?[]:$(a,i);d?o.valueRows=d:o.notes.push({code:"mappingFileUnread",detail:N})}return o}async readBeside(t,n){try{return await this.fileReader.readFile(ee(Z(t),n))}catch(r){if(r?.code==="ENOENT")return;throw r}}extractDependencies(t){let n=[],r=new Map(t.objects.flatMap(i=>{let o=y(i);return o===void 0?[]:[[o.toLowerCase(),o]]}));for(let i of t.objects){let o=y(i);if(i.master===!1||o===void 0)continue;let a=je(i.query??"");for(let d of a)if(d.includes(".")){let s=d.split(".")[0],u=r.get(ye(s).toLowerCase());u!==void 0&&n.push({parent:u,child:o,field:s})}}return n}convert(t){let n=new Date().toISOString(),r=t.map((i,o)=>this.convertObject(i,o));return{id:D(),name:"SFDMU Import",description:"Imported from SFDMU export.json",sourceOrgId:D(),targetOrgId:D(),direction:"source_to_target",mode:"full",objects:r,conflictStrategy:"source_wins",enableRollback:!1,createdAt:n,updatedAt:n}}convertObject(t,n){let r=this.convertFieldMappings(t.fieldMapping),i=this.convertValuesMapping(t.valuesMapping,r),o=t.orderBy??t.read.orderBy,a=J(t);return{objectApiName:t.object,externalIdField:a!==void 0&&a!=="Id"&&j(a)?a:void 0,operation:O(t.sfdmuOperation),query:t.query,fieldMappings:r,transformRules:i,excludedFields:t.excludedFields,addOnFields:[],batchSize:200,orderBy:o!==void 0&&E(o)?o:void 0,where:z(t),insertOrder:n+1}}convertFieldMappings(t){return k(t).map(n=>{let r=n.sourceField===n.targetField?"direct":"rename";return{sourceField:n.sourceField,targetField:n.targetField,type:r}})}convertValuesMapping(t,n){if(t.length===0)return[];let r=new Map;for(let o of t){let d=n.find(s=>s.sourceField===o.fieldName)?.targetField??o.fieldName,l=r.get(d)??{};l[o.rawValue]=o.mappedValue,r.set(d,l)}let i=[];for(let[o,a]of r)i.push({type:"map_value",field:o,config:{valueMap:a}});return i}};function we(e,t){let n=s=>s.object.toLowerCase()===e.object.toLowerCase(),i=(e.useFieldMapping?t.fieldRows.filter(n):[]).map(({field:s,target:u})=>s===""?{targetObject:u}:{sourceField:s,targetField:u}),o=e.useValuesMapping?t.valueRows.filter(s=>n(s)&&s.value.trim()!==""):[],a=o.filter(U).map(({field:s,rawValue:u,value:g})=>({fieldName:s,rawValue:u,mappedValue:g})),l=O(e.sfdmuOperation)==="delete"?[]:q(e);return{...e,fieldMapping:e.useFieldMapping?[...i,...e.fieldMapping]:[],fieldMappingsIgnored:e.useFieldMapping?0:e.fieldMapping.filter(be).length,valuesMapping:[...a,...e.valuesMapping],excludedFields:[...new Set([...e.excludedFields,...l])],mockedFields:l,valueRowsLeft:o.filter(s=>!U(s)).map(s=>`${s.field} (${s.rawValue})`)}}function Se(e,t){let n=i=>O(i.sfdmuOperation)==="delete",r=(i,o)=>n(i)?[i.set,0,t?o:-o]:[i.set,1,o];return e.map((i,o)=>({entry:i,rank:r(i,o)})).sort((i,o)=>i.rank[0]-o.rank[0]||i.rank[1]-o.rank[1]||i.rank[2]-o.rank[2]).map(({entry:i})=>i)}function O(e){return{Insert:"insert",Update:"update",Upsert:"upsert",Delete:"delete",HardDelete:"delete"}[e]}function je(e){let t=e.match(/SELECT\s+(.+?)\s+FROM/i);return t?t[1].split(",").map(n=>n.trim()):[]}function ye(e){let t={Account:"Account",Contact:"Contact",Owner:"User",CreatedBy:"User",LastModifiedBy:"User",Parent:"Account",RecordType:"RecordType"};return t[e]?t[e]:e.endsWith("__r")?e.replace(/__r$/,"__c"):e}function D(){return globalThis.crypto.randomUUID()}export{P as SfdmuImporter,h as SfdmuRefusal,x as SfdmuTargetObjectError,re as sfdmuExportSchema};