sandforge 1.79.0 → 1.80.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 (192) hide show
  1. package/lib/{chunk-JVL444U5.mjs → chunk-2BA2XKAY.mjs} +1 -1
  2. package/lib/chunk-2CNCDM56.mjs +7 -0
  3. package/lib/{chunk-W7KFAY55.mjs → chunk-2GTBABKU.mjs} +1 -1
  4. package/lib/{chunk-DLDX6RRC.mjs → chunk-2NBYT7GR.mjs} +1 -1
  5. package/lib/{chunk-HV2MXMGI.mjs → chunk-2UZPIMUC.mjs} +1 -1
  6. package/lib/chunk-3F6Q5E7I.mjs +14 -0
  7. package/lib/{chunk-PBI4BYWW.mjs → chunk-3RZQZHEB.mjs} +1 -1
  8. package/lib/{chunk-P7GSGFJO.mjs → chunk-3TJON4F3.mjs} +1 -1
  9. package/lib/chunk-4VS2V6WU.mjs +25 -0
  10. package/lib/{chunk-TQX3PURV.mjs → chunk-5K5VLULK.mjs} +1 -1
  11. package/lib/{chunk-MYTIL2JD.mjs → chunk-5TC3QB4U.mjs} +1 -1
  12. package/lib/{chunk-NM4MDLK4.mjs → chunk-6XYKJSGX.mjs} +1 -1
  13. package/lib/{chunk-RFEO2KAN.mjs → chunk-74Q6DORA.mjs} +1 -1
  14. package/lib/chunk-7ABODJ4G.mjs +7 -0
  15. package/lib/{chunk-ZPYJPGDK.mjs → chunk-7EGQP6S4.mjs} +1 -1
  16. package/lib/chunk-7FFGJWHN.mjs +7 -0
  17. package/lib/chunk-7YDNUBO5.mjs +7 -0
  18. package/lib/{chunk-CGWXQX75.mjs → chunk-A527W53V.mjs} +1 -1
  19. package/lib/chunk-ADOAS63R.mjs +7 -0
  20. package/lib/chunk-AEKONPF4.mjs +7 -0
  21. package/lib/{chunk-4HFRHFGQ.mjs → chunk-B5QQJ4SI.mjs} +1 -1
  22. package/lib/{chunk-2BVTCNWA.mjs → chunk-BGUEWRK2.mjs} +1 -1
  23. package/lib/{chunk-GNC27UEU.mjs → chunk-BKDV4ENO.mjs} +1 -1
  24. package/lib/{chunk-QRV2OSIS.mjs → chunk-BTWDMNN3.mjs} +1 -1
  25. package/lib/{chunk-FOVVHGEP.mjs → chunk-BV6VTP3J.mjs} +1 -1
  26. package/lib/{chunk-PZTSVQSF.mjs → chunk-BXU6WFMH.mjs} +1 -1
  27. package/lib/{chunk-ZQOZ4EFW.mjs → chunk-BY2HJFFG.mjs} +1 -1
  28. package/lib/{chunk-NZ5ZZLKS.mjs → chunk-CEX3NEZL.mjs} +1 -1
  29. package/lib/{chunk-HTJ5OGP5.mjs → chunk-CHYDMRSV.mjs} +1 -1
  30. package/lib/chunk-CION3VMZ.mjs +7 -0
  31. package/lib/chunk-COFG7Q6R.mjs +7 -0
  32. package/lib/chunk-CSBS5U5I.mjs +7 -0
  33. package/lib/{chunk-55HEMHEG.mjs → chunk-CU2INBND.mjs} +1 -1
  34. package/lib/chunk-DB7RBE5D.mjs +7 -0
  35. package/lib/{chunk-QPF6C5MX.mjs → chunk-DBB3EMIN.mjs} +1 -1
  36. package/lib/{chunk-F74IHMGL.mjs → chunk-DYFALGRT.mjs} +1 -1
  37. package/lib/{chunk-TEOLMRDO.mjs → chunk-E5AHXLS6.mjs} +1 -1
  38. package/lib/{chunk-LRFAIUN7.mjs → chunk-E5ZB3LU5.mjs} +1 -1
  39. package/lib/chunk-EFR2Y7E4.mjs +7 -0
  40. package/lib/chunk-EHQ3FX6X.mjs +7 -0
  41. package/lib/{chunk-RAAANPPG.mjs → chunk-ELFXJHU7.mjs} +1 -1
  42. package/lib/{chunk-BN7A4GRQ.mjs → chunk-EMNC6YI4.mjs} +1 -1
  43. package/lib/{chunk-HJC7AIBK.mjs → chunk-EQNW3UC2.mjs} +1 -1
  44. package/lib/{chunk-Z7X534S4.mjs → chunk-F43REJDZ.mjs} +2 -2
  45. package/lib/{chunk-QQZZMKU3.mjs → chunk-F6GUDTOB.mjs} +1 -1
  46. package/lib/{chunk-6EBMEGZB.mjs → chunk-FGRG7ANU.mjs} +1 -1
  47. package/lib/{chunk-4NAHW2D3.mjs → chunk-FKG7Q3WH.mjs} +1 -1
  48. package/lib/{chunk-7UQD6V6F.mjs → chunk-FPKYYFM7.mjs} +1 -1
  49. package/lib/{chunk-ZJKCWBRJ.mjs → chunk-FXXLX4O6.mjs} +1 -1
  50. package/lib/chunk-G35N4P7D.mjs +7 -0
  51. package/lib/{chunk-SIOZXPFG.mjs → chunk-GGD7ON3M.mjs} +1 -1
  52. package/lib/chunk-GSG7WZHM.mjs +7 -0
  53. package/lib/{chunk-OTWRDD6L.mjs → chunk-GSKCGQIP.mjs} +1 -1
  54. package/lib/{chunk-3CA767QB.mjs → chunk-HEKAZJRH.mjs} +1 -1
  55. package/lib/{chunk-4SNDMJP2.mjs → chunk-HLWMJF6Y.mjs} +1 -1
  56. package/lib/chunk-HOJYWTP7.mjs +20 -0
  57. package/lib/chunk-HS4YRX4J.mjs +7 -0
  58. package/lib/chunk-IFETCRWE.mjs +10 -0
  59. package/lib/{chunk-PUOX4NBJ.mjs → chunk-IG2MTQRP.mjs} +1 -1
  60. package/lib/{chunk-RACDTRZA.mjs → chunk-IGYH7GMA.mjs} +1 -1
  61. package/lib/{chunk-X65MT4W3.mjs → chunk-IOIWJ3DJ.mjs} +1 -1
  62. package/lib/{chunk-4U6NXJNL.mjs → chunk-IQXHJEYB.mjs} +1 -1
  63. package/lib/{chunk-P2PJYWGQ.mjs → chunk-IWDREM66.mjs} +1 -1
  64. package/lib/{chunk-ZOVSMN5C.mjs → chunk-IZQZ6ZUF.mjs} +1 -1
  65. package/lib/{chunk-XBG5SP6Q.mjs → chunk-J525F5KI.mjs} +1 -1
  66. package/lib/{chunk-5CD257T7.mjs → chunk-JEERQRLW.mjs} +1 -1
  67. package/lib/{chunk-6QSM2WIH.mjs → chunk-JPUR2CFX.mjs} +1 -1
  68. package/lib/chunk-JWTSEDIQ.mjs +7 -0
  69. package/lib/chunk-K327QKMD.mjs +7 -0
  70. package/lib/{chunk-J7HVXMSW.mjs → chunk-KBJ5VERV.mjs} +1 -1
  71. package/lib/chunk-KDGMAGQR.mjs +7 -0
  72. package/lib/chunk-KRCA6IPH.mjs +8 -0
  73. package/lib/chunk-KYEDBS54.mjs +7 -0
  74. package/lib/chunk-L5FGY6YA.mjs +7 -0
  75. package/lib/{chunk-PNCONNFJ.mjs → chunk-L77FJZEP.mjs} +1 -1
  76. package/lib/{chunk-3OHPD72J.mjs → chunk-LKQ5RKIV.mjs} +1 -1
  77. package/lib/{chunk-WJY54JO7.mjs → chunk-LPBMBW3O.mjs} +1 -1
  78. package/lib/{chunk-LV6G4XTK.mjs → chunk-LWW4U276.mjs} +1 -1
  79. package/lib/{chunk-IAZB4WIL.mjs → chunk-M3ROUWDX.mjs} +1 -1
  80. package/lib/chunk-MFG4MUIO.mjs +9 -0
  81. package/lib/{chunk-H45UXY6G.mjs → chunk-MHMH6MTP.mjs} +1 -1
  82. package/lib/{chunk-HCIDVIOW.mjs → chunk-MILU7WFN.mjs} +1 -1
  83. package/lib/chunk-MJU2PGZQ.mjs +15 -0
  84. package/lib/{chunk-HJKM3E56.mjs → chunk-MJVTDA5Q.mjs} +1 -1
  85. package/lib/{chunk-SBIMVCXT.mjs → chunk-MS4FJDFD.mjs} +9 -9
  86. package/lib/{chunk-3SRXFZSD.mjs → chunk-MYW5QNGI.mjs} +1 -1
  87. package/lib/{chunk-VHI54FBK.mjs → chunk-N652NMZ4.mjs} +26 -26
  88. package/lib/{chunk-3DCUADVK.mjs → chunk-NTFIRZP6.mjs} +1 -1
  89. package/lib/{chunk-342FN7AO.mjs → chunk-NZC67CGR.mjs} +1 -1
  90. package/lib/{chunk-RSYICMZG.mjs → chunk-O2HDYYUV.mjs} +1 -1
  91. package/lib/chunk-OAZRPP4I.mjs +7 -0
  92. package/lib/{chunk-BILZ3SSR.mjs → chunk-OHWNPXWW.mjs} +1 -1
  93. package/lib/chunk-OLSGVAIL.mjs +341 -0
  94. package/lib/chunk-OO6CLPEH.mjs +7 -0
  95. package/lib/chunk-OPXCV2KL.mjs +7 -0
  96. package/lib/chunk-P33PSCXK.mjs +7 -0
  97. package/lib/{chunk-AUTM6H6Z.mjs → chunk-PJ5I73CK.mjs} +1 -1
  98. package/lib/{chunk-NTDN2JQZ.mjs → chunk-PZPJKATS.mjs} +1 -1
  99. package/lib/{chunk-5QKTYCWE.mjs → chunk-Q3DM32KF.mjs} +1 -1
  100. package/lib/{chunk-K22PA4XL.mjs → chunk-QR3WELJQ.mjs} +1 -1
  101. package/lib/{chunk-42RER7V4.mjs → chunk-R3X3LV64.mjs} +1 -1
  102. package/lib/chunk-RMBPOTD7.mjs +7 -0
  103. package/lib/{chunk-IEYG5ATY.mjs → chunk-RPI7LRTW.mjs} +1 -1
  104. package/lib/{chunk-5MMXFWPD.mjs → chunk-SE4QEZUG.mjs} +1 -1
  105. package/lib/{chunk-ALJVEUUS.mjs → chunk-SIHORWVK.mjs} +1 -1
  106. package/lib/{chunk-AAVJ5XVX.mjs → chunk-SOGQW4IG.mjs} +1 -1
  107. package/lib/chunk-SOU4FRYN.mjs +7 -0
  108. package/lib/chunk-SU65Z2BA.mjs +7 -0
  109. package/lib/chunk-T62WNR54.mjs +7 -0
  110. package/lib/{chunk-5O6JOMHS.mjs → chunk-TSLJUSLW.mjs} +1 -1
  111. package/lib/chunk-TTFDUKUS.mjs +47 -0
  112. package/lib/{chunk-57VHUYNG.mjs → chunk-TTKXMDBN.mjs} +1 -1
  113. package/lib/chunk-UCD54V2M.mjs +7 -0
  114. package/lib/{chunk-TBZMC2VV.mjs → chunk-UNJA4J37.mjs} +1 -1
  115. package/lib/{chunk-NGSMZZDA.mjs → chunk-VE6XKGGD.mjs} +1 -1
  116. package/lib/chunk-VS7ZXUII.mjs +824 -0
  117. package/lib/{chunk-ALUFROGA.mjs → chunk-VXQLDM4R.mjs} +1 -1
  118. package/lib/chunk-VYXMVJL5.mjs +7 -0
  119. package/lib/{chunk-WFEB5X4U.mjs → chunk-W622GUAW.mjs} +1 -1
  120. package/lib/chunk-W7U5E5ZL.mjs +9 -0
  121. package/lib/{chunk-AR7BE5O2.mjs → chunk-WA7EYLAQ.mjs} +1 -1
  122. package/lib/{chunk-EQF2IJS2.mjs → chunk-WR4Q363I.mjs} +1 -1
  123. package/lib/{chunk-ZXH4MBWP.mjs → chunk-WU3GLFZO.mjs} +1 -1
  124. package/lib/chunk-WXAQ7FK3.mjs +115 -0
  125. package/lib/{chunk-YBU4Z4QV.mjs → chunk-X5JYBPXP.mjs} +1 -1
  126. package/lib/chunk-XAMBCQPU.mjs +7 -0
  127. package/lib/{chunk-LQ4DRFUH.mjs → chunk-XLXIPIEW.mjs} +1 -1
  128. package/lib/{chunk-H2PJNIYJ.mjs → chunk-XUWL6ZPC.mjs} +1 -1
  129. package/lib/{chunk-P42X3B4D.mjs → chunk-YKKRIEH4.mjs} +1 -1
  130. package/lib/chunk-YRQGKDHM.mjs +7 -0
  131. package/lib/chunk-ZM6OJGIG.mjs +7 -0
  132. package/lib/{chunk-SFURUNJM.mjs → chunk-ZVAED4QV.mjs} +1 -1
  133. package/lib/sandforge-autopilot.mjs +29 -24
  134. package/lib/sandforge-backup.mjs +25 -21
  135. package/lib/sandforge-checkpoint.mjs +15 -14
  136. package/lib/sandforge-cleanup.mjs +14 -10
  137. package/lib/sandforge-clone.mjs +1 -1
  138. package/lib/sandforge-compare.mjs +9 -8
  139. package/lib/sandforge-dataops.mjs +1 -1
  140. package/lib/sandforge-empty.mjs +15 -15
  141. package/lib/sandforge-env.mjs +88 -88
  142. package/lib/sandforge-frozen.mjs +43 -34
  143. package/lib/sandforge-mcp.mjs +12 -12
  144. package/lib/sandforge-monitor.mjs +7 -7
  145. package/lib/sandforge-seed.mjs +1 -1
  146. package/lib/sandforge-sync.mjs +1 -1
  147. package/lib/sandforge.mjs +4 -4
  148. package/package.json +1 -1
  149. package/lib/chunk-2S5OMIIA.mjs +0 -7
  150. package/lib/chunk-36U7IQ6Y.mjs +0 -25
  151. package/lib/chunk-3F5YMM2F.mjs +0 -7
  152. package/lib/chunk-3RYLICRX.mjs +0 -7
  153. package/lib/chunk-4GL773D5.mjs +0 -7
  154. package/lib/chunk-4XZ5YT5O.mjs +0 -7
  155. package/lib/chunk-5AJRHRXA.mjs +0 -20
  156. package/lib/chunk-5HMAPZBV.mjs +0 -7
  157. package/lib/chunk-6LAXTAVN.mjs +0 -7
  158. package/lib/chunk-6MUEPV7M.mjs +0 -9
  159. package/lib/chunk-75ADZS6B.mjs +0 -7
  160. package/lib/chunk-B45CNPUX.mjs +0 -47
  161. package/lib/chunk-BS5T3MOQ.mjs +0 -7
  162. package/lib/chunk-D3QRXG63.mjs +0 -787
  163. package/lib/chunk-EEVVGGM6.mjs +0 -7
  164. package/lib/chunk-ENLBYECD.mjs +0 -7
  165. package/lib/chunk-EQOQASDQ.mjs +0 -7
  166. package/lib/chunk-FQBRBBY4.mjs +0 -7
  167. package/lib/chunk-GAM726CK.mjs +0 -7
  168. package/lib/chunk-HUMEKZT5.mjs +0 -8
  169. package/lib/chunk-I3JKJTLO.mjs +0 -110
  170. package/lib/chunk-KLX67VPL.mjs +0 -7
  171. package/lib/chunk-L776PUMV.mjs +0 -7
  172. package/lib/chunk-NEVXIGR6.mjs +0 -10
  173. package/lib/chunk-NHWE66K5.mjs +0 -7
  174. package/lib/chunk-OQOZAPCI.mjs +0 -7
  175. package/lib/chunk-PA3MKJVH.mjs +0 -7
  176. package/lib/chunk-RH3N2H7P.mjs +0 -7
  177. package/lib/chunk-SRQDABQ2.mjs +0 -15
  178. package/lib/chunk-SVS6UMDU.mjs +0 -323
  179. package/lib/chunk-TNXUU6W7.mjs +0 -14
  180. package/lib/chunk-VXHDBYMI.mjs +0 -7
  181. package/lib/chunk-WRU5FJFC.mjs +0 -7
  182. package/lib/chunk-X2PY6MWZ.mjs +0 -7
  183. package/lib/chunk-XEFDB2R4.mjs +0 -7
  184. package/lib/chunk-XETCPL7E.mjs +0 -7
  185. package/lib/chunk-Y5CGXLUB.mjs +0 -7
  186. package/lib/chunk-Y6J6QFI2.mjs +0 -7
  187. package/lib/chunk-YMJVMFPY.mjs +0 -7
  188. package/lib/chunk-YPSRZRIT.mjs +0 -7
  189. package/lib/chunk-YW2SBL4Z.mjs +0 -7
  190. package/lib/chunk-ZE6HKRR4.mjs +0 -9
  191. package/lib/chunk-ZLZRU6MO.mjs +0 -7
  192. package/lib/chunk-ZYEE34WO.mjs +0 -7
@@ -1,323 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as eo,b as At,c as jt,d as hn,e as gn,f as $t,g as mn}from"./chunk-AUTM6H6Z.mjs";import{a as so}from"./chunk-INIQ23K6.mjs";import{a as oo}from"./chunk-RAAANPPG.mjs";import{a as Dn}from"./chunk-ZE6HKRR4.mjs";import{A as Je,B as Qs,C as Xs,D as to,E as no,F as ro,S as io,T as yn,U as wn,V as ao,W as co,Y as uo,Z as bn,_ as lo,c as Ts,e as Is,f as Cs,g as Ps,h as Es,i as Fs,k as Ns,m as Ms,n as xs,x as Ls,z as Fe}from"./chunk-XEFDB2R4.mjs";import{b as Ws,e as Ds,g as _s}from"./chunk-H45UXY6G.mjs";import{a as rt,b as Bs,c as Us,d as qs,e as ln,f as Gs,g as zs,h as Hs,i as Ks,j as Js,l as Ke,m as Ys,n as fn,o as pn,p as Vs,q as Zs,s as st}from"./chunk-WRU5FJFC.mjs";import{a as Xt,b as en}from"./chunk-5P4PHJRL.mjs";import{Ba as Ot,Ia as ms,Ja as sn,K as kt,Qa as ys,Ra as ws,Ua as on,V as gs,Va as vt,Wa as bs,Xa as an,Ya as Rs,ab as Ss,bb as ks,c as Xr,cb as Os,d as es,db as vs,eb as dn,fb as As,g as nn,gb as js,h as os,hb as $s,i as is,j as as,k as ds,l as rn,m as cs,n as us,o as ls,q as fs,s as ps}from"./chunk-D3QRXG63.mjs";import{k as Rt}from"./chunk-NM4MDLK4.mjs";import{k as Lr,n as Wr}from"./chunk-FQBRBBY4.mjs";import{b as ft,e as Wt}from"./chunk-BZ24IAP5.mjs";import{a as _n,b as Bn,c as pt,d as Un,e as qn,g as Gn,h as zn,j as Hn}from"./chunk-AV5SWEHP.mjs";import{a as cn,c as un}from"./chunk-I7O6C2B5.mjs";import{B as gr,Ec as Fr,wc as Cr,x as pr,y as hr}from"./chunk-YMJVMFPY.mjs";import{pb as ts,qb as ns,wb as rs,x as St,yb as ss}from"./chunk-36U7IQ6Y.mjs";import{l as Zr,m as Qr}from"./chunk-XETCPL7E.mjs";import{b as Rr,l as Er}from"./chunk-Z7X534S4.mjs";import{C as wr,N as mt,Q as br,U as Qt,V as Pr,a as Zn}from"./chunk-6QSM2WIH.mjs";import{a as Kt,b as Sr,c as Or,f as vr,h as Jt,k as Ar,l as jr,m as $r,n as Tr,o as Yt,r as Vt,t as Zt,w as Ir}from"./chunk-NTDN2JQZ.mjs";import{b as lt,c as et}from"./chunk-L776PUMV.mjs";import{A as ze,r as yt,s as wt,x as xr,y as bt}from"./chunk-6MUEPV7M.mjs";import{B as Ee,D as ur,E as zt,F as lr,G as fr,H as Ge,n as tr,o as tt,p as nr,q as rr,r as sr,s as or,t as ir,u as ar,x as nt,y as We}from"./chunk-HJC7AIBK.mjs";import{d as Ht}from"./chunk-OTWRDD6L.mjs";import{a as Xe,b as Ln,c as Lt}from"./chunk-RH3N2H7P.mjs";import{a as Xn,i as er,v as gt}from"./chunk-ZUTYVST5.mjs";import{a as cr}from"./chunk-55HEMHEG.mjs";import{a as dr}from"./chunk-P42X3B4D.mjs";import{d as kr}from"./chunk-TUACWKIH.mjs";import{Ca as Hr,Ia as Kr,K as Br,L as Ur,P as qr,Pa as Jr,S as He,bb as Yr,cb as Vr,i as Gt,ka as Gr,r as Nr,s as Mr,va as zr,x as _r,ya as tn}from"./chunk-VXHDBYMI.mjs";import{ga as Dr}from"./chunk-ZLZRU6MO.mjs";import{a as Le}from"./chunk-EADHKH3A.mjs";import{i as Qn}from"./chunk-INIT2UKJ.mjs";import{h as yr}from"./chunk-PNCONNFJ.mjs";import{E as le,F as Oe,H as qt,M as Yn,O as Vn,e as ht,f as Kn,l as Jn,q as Ut}from"./chunk-CGWXQX75.mjs";import{h as Bt}from"./chunk-TZE3Y7IQ.mjs";import{j as mr}from"./chunk-SIOZXPFG.mjs";import{a as Wn,c as Dt,e as _t,g as hs}from"./chunk-MTMH6H2A.mjs";import{Eb as qe,Fb as Qe,Tb as $n,Tc as Nn,Ub as Tn,Vb as xt,Vc as Mn,Wc as xn,Yb as In,hc as Cn,ic as ct,jc as ut,kc as Pn,lc as En,mc as Fn,vb as jn}from"./chunk-B45CNPUX.mjs";import{A as H}from"./chunk-7EANH5PY.mjs";import{b as Mo}from"./chunk-SBIMVCXT.mjs";import{d as No}from"./chunk-NTOVCTRS.mjs";var li=No(Mo());import{randomUUID as oi}from"node:crypto";import{existsSync as ot,mkdirSync as ii,readFileSync as it,renameSync as ai,writeFileSync as di}from"node:fs";import{dirname as ci,join as Ye,resolve as ui}from"node:path";var xo=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ve=n=>n.toLowerCase();function Tt(n){return n==="insert"||n==="upsert"}function Lo(n,t){let e=ve(t);if(n.addOnFields.some(s=>ve(s.fieldApiName)===e)||n.transformRules.some(s=>s.field&&ve(s.field)===e))return;let r=n.fieldMappings.find(s=>s.type!=="exclude"&&ve(s.targetField)===e);return r?(r.type==="direct"||r.type==="rename")&&(r.transformRules??[]).length===0?r.sourceField:void 0:t}function Wo(n){return n!==void 0&&[...n.source.active].some(t=>!n.target.active.has(t))}async function fo(n){let t=new Map,e=new rt(n.earlier),r=new Set,s=new Set([...n.leftOut].map(ve)),o,i=async l=>{let f=await n.read(l);return f.length>0&&At(l.objectApiName,f)&&(o=await n.standardPricebooks?.(),o&&e.noteMatched(o.source,o.target)),f},d=n.matched,c=(l,f)=>{d&&f>0&&d.set(l,(d.get(l)??0)+f)},a=(l,f)=>{let y=o?.source;return l===Qe&&y!==void 0?f.filter(m=>m.Id===y).length:0};for(let l of n.ordered){let f=l.objectApiName;if(s.has(ve(f))){if(!Tt(l.operation))continue;let I=await i(l);for(let k of I){let C=k.Id;typeof C=="string"&&C!==""&&e.noteRefused(C,f)}c(f,a(f,I)),r.add(ve(f));continue}if(l.operation==="delete")continue;let y=(n.lookups.get(f)??[]).flatMap(({field:I,referenceTo:k})=>{let P=k.filter(M=>ve(M)!==ve(f)&&r.has(ve(M))).length>0?Lo(l,I):void 0;return P!==void 0?[{field:I,source:P}]:[]}),m=d!==void 0&&Tt(l.operation),R=m&&f===Qe&&await n.standardPricebooks?.()!==void 0,w=m&&f===qe&&await n.standardPricebooks?.()?await n.currencies?.():void 0,p=Wo(w);if(y.length===0&&!R&&!p)continue;let S=new Map,A=I=>{let k=`${I.parent}|${I.field}`,C=S.get(k);C?C.rows++:S.set(k,{...I,rows:1})},U=n.copied?.get(f),x=(await i(l)).filter(I=>{let k=I.Id;return!(U&&typeof k=="string"&&U.has(k.slice(0,15)))}),h=new Map;for(let I of y.length>0?x:[]){let k=I.Id,C=y.find(({source:M})=>{let q=I[M];return typeof q=="string"&&xo.test(q)&&e.refusedObjectOf(q)!==void 0});if(!C)continue;let P={parent:e.refusedObjectOf(I[C.source])??"",field:C.field};A(P),typeof k=="string"&&k!==""&&h.set(k,P),Tt(l.operation)&&typeof k=="string"&&k!==""&&e.noteRefused(k,f)}if(R&&c(f,a(f,x)),p){let I=jt(qe,{records:x,sources:x,sourceIds:x.map(C=>typeof C.Id=="string"?C.Id:void 0)},o,w,C=>e.refusedObjectOf(C)!==void 0),k=0;for(let[C,P]of I.standsFor){if(h.has(C))continue;let M=e.refusedObjectOf(P)!==void 0?h.get(P):void 0;if(M){A(M),h.set(C,M),e.noteRefused(C,f);continue}k++}c(f,k)}let j=[...S.values()],E=j.reduce((I,k)=>I+k.rows,0);E>0&&(t.set(f,{objectApiName:f,rows:E,parent:j[0].parent,field:j[0].field,parents:j}),Tt(l.operation)&&r.add(ve(f)))}return t}var po=Symbol("not written");function Do(n,t){if(n==="delete")return{rules:[],onChange:[]};let e=[],r=[];for(let{onChangeOnly:s,...o}of t)s&&n==="insert"?r.push(o.name):e.push(o);return{rules:e,onChange:r}}function _o(n){return`${n.length} active validation rule(s) of the target left out of what may refuse these inserts: their formula holds only on a change of a record (ISCHANGED, PRIORVALUE, NOT(ISNEW())), which an insert never is \u2014 ${n.join(", ")}`}var Bo=/^012000000000000(AAA)?$/;function Uo(n){let t=n.RecordTypeId;return typeof t=="string"&&t.length>=15&&!Bo.test(t)}function Sn(n){let t=n?.[Xn];return typeof t=="string"&&t!==""}async function ho(n,t,e,r){let s=t.some(Uo)?await n.recordTypes():void 0,o=e.some(Sn)||t.some(Sn)?await n.currencies():void 0,i=n.later?.get(r),d=n.recordTypesUnderTheLease?.get(r);return{links:n.links,sources:e,...s?{recordTypes:s}:{},...o?{currencies:o,currencyChangesById:n.currencyChangesById}:{},...n.contactPoints?{contactPoints:n.contactPoints}:{},...i&&i.size>0?{later:i}:{},...d?{recordTypesUnderTheLease:d}:{},...n.createdWithoutRecordType?{createdWithoutRecordType:n.createdWithoutRecordType}:{}}}function go(n){let t=new Map;for(let e of n?.cycles??[])e.forEach((r,s)=>{s<e.length-1&&t.set(r,new Set(e.slice(s+1)))});return t}function qo(n,t,e){return{...n,...t.set?{lookupsSetAfter:{...t.set,after:[...e]}}:{},...t.leftOut.length>0?{lookupsLeftOut:[...n.lookupsLeftOut??[],...t.leftOut]}:{}}}function mo(n,t){return t.flatMap((e,r)=>{let s=n[r];return e.success&&s!==void 0?[s]:[]})}function yo(n,t){let e=t.encryptedLeftOut??[];return e.length>0?{...n,encryptedLeftOut:[...e]}:n}function we(n){return n.slice(0,15)}function Go(n,t){if(!t)return n;if(t.unread!==void 0)return{...n,errors:[...n.errors,`The contact roles the platform wrote with the run's opportunities were not looked up, so written as read: an opportunity may hold the role of its contact twice. ${t.unread}`]};let{records:e,given:r,refusal:s,alike:o}=t,i=o!==void 0?{...n,errors:[...n.errors,Yn(o)]}:n;return e===0?i:{...i,skipped:i.skipped+e,writtenByThePlatform:{records:e,given:r,...s!==void 0?{refusal:s}:{}}}}function zo(n,t,e){if(n.objectApiName!==le||!Te(n.operation)||!e.sentWithAContact||t.records.length===0)return{prepared:t,linked:0};let r=d=>typeof d=="string"&&d!==""?e.targetOf(d):void 0,s=t.records.map((d,c)=>({OpportunityId:r(d.OpportunityId),[Oe]:r(d[Oe]),IsPrimary:t.sources[c]?.IsPrimary??d.IsPrimary})),o=new Set(qt(s,d=>e.contactSentWith(d)));if(o.size===0)return{prepared:t,linked:0};for(let d of o){e.roleLinkedFor(String(s[d].OpportunityId));let c=t.sourceIds[d];c!==void 0&&e.noteWritten(c,c)}let i=(d,c)=>!o.has(c);return{prepared:{...t,records:t.records.filter(i),sourceIds:t.sourceIds.filter(i),sources:t.sources.filter(i),unsettled:t.unsettled.length===t.records.length?t.unsettled.filter(i):t.unsettled},linked:o.size}}var Ho=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Rn=200;function Ko(n,t,e){let r=a=>{let l=e?.fields?.find(f=>f.name===a);return l?.nillable===!1&&l.defaultedOnCreate!==!0},s=[],o=new Set,i=new Set,d=0;for(let[a,l]of n){let f=t[a]==="insert"?l.filter(r):[];if(f.length>0){s.push(a);for(let y of f)o.add(y);continue}d++;for(let y of l)i.add(y)}let c=[];return d>0&&c.push(`${d} record(s) would be written without ${[...i].sort().join(", ")}: a lookup held an id from the source org that the target does not have, which the run learns from its first refusal and sends the record again without the lookups it did not settle.`),s.length>0&&c.push(`${s.length} record(s) would be refused: a lookup held an id from the source org that the target does not have, and sent again without the lookups the run did not settle, the record lacks ${[...o].sort().join(", ")}, which the target requires (REQUIRED_FIELD_MISSING).`),{refused:s,notes:c}}function Jo(n){return`${n} record(s) would be linked to the contact role the platform writes with their opportunity, for its contact, not written.`}function kn(n){let t=n.alreadyLinked,e=n.alreadyCopied-t;return{...e>0?{alreadyCopied:e}:{},...t>0?{alreadyLinked:t}:{}}}function Yo(n,t){return t.alreadyCopied===0?n:{...n,skipped:n.skipped+t.alreadyCopied,...kn(t)}}function wo(n,t){return`What earlier runs of this configuration copied could not be read (${n}), and ${t.map(e=>e.objectApiName).join(", ")} ${t.length===1?"is":"are"} inserted: the records they copied would be copied a second time. Nothing was written.`}var Vo="SYNC_EARLIER_UNREAD",Zo=new Set(["account","contact"]);function Te(n){return n==="insert"||n==="upsert"}function bo(n,t,e,r=new Map,s=new Set,o=new Map,i=new Map,d=new Set,c,a={}){let l=0,f=0,y=n.map(h=>{let j=h.objectApiName,E=t.get(j)??{rows:0},I=e.get(j)??new Set,k=I.size,C=Math.min(k,E.rows),P=Math.min([...I].filter(ne=>d.has(ne)).length,C);f+=P,l+=C-P;let q=(r.has(j)?0:o.get(j)?.rows??0)+(i.get(j)??0),G=a.keys?.get(j);return{objectApiName:j,operation:h.operation,rows:Math.max(0,E.rows-k-q),...E.personAccounts!==void 0?{personAccounts:E.personAccounts}:{},batchSize:h.batchSize,...G?{overwriteKey:G}:{}}}),m=y.flatMap(h=>{let j=r.get(h.objectApiName);return j?[{...h,why:j.why,...j.key?{key:j.key}:{}}]:[]}),R=y.find(h=>h.objectApiName===le),w=R&&c!==void 0?Math.min(c,R.rows):0;R&&w>0&&(R.rows-=w);let p=y.filter(h=>!r.has(h.objectApiName)),S=p.filter(h=>h.rows>0&&Te(h.operation)&&s.has(h.objectApiName)).length,A=[...o.values()].filter(({objectApiName:h})=>!r.has(h)),U=c===void 0?Qo(n,p):0,x=p.filter(h=>a.typed?.has(h.objectApiName)).length;return{objects:p,alreadyCopied:l,...f>0?{alreadyLinked:f}:{},...m.length>0?{unwritable:m}:{},...A.length>0?{heldBack:A}:{},...S>0?{readBack:S}:{},...U>0?{rolesByThePlatform:U}:{},...w>0?{rolesLinked:w}:{},...x>0?{describedAgain:x}:{}}}var _e="Opportunity";function Qo(n,t){let e=i=>t.find(d=>d.objectApiName===i&&Te(d.operation)),r=e(_e),s=e(le);return!r||!s||n.find(i=>i.objectApiName===_e)?.excludedFields.includes(Oe)?0:Math.min(r.rows,s.rows)}function Xo(n,t,e){return{objectApiName:n.objectApiName,operation:n.operation,processed:0,success:0,failed:0,skipped:e,conflictCount:0,errors:[`${t.message} Left out of the run, as confirmed before it wrote.`]}}function Ro(n,t,e){if(Te(t.operation))for(let r of e){let s=r?.Id;typeof s=="string"&&s!==""&&n.noteRefused(s,t.objectApiName)}}function It(n,t,e){let r=[];for(let[s,o]of e){let i=n.targetOf(o);i!==void 0?n.noteMatched(s,i):Te(t.operation)&&n.refusedObjectOf(o)!==void 0&&(n.noteRefused(s,t.objectApiName),r.push(s))}return r}function So(n,t,e){let r=hn(t,e),s=mn(n,{...t,prices:r});return e.length===0?s:{...s,processed:s.processed+e.length,failed:s.failed+e.length,errors:[...s.errors,gn(n.objectApiName,e.length)]}}function ko(n){let t=ct(n.objects);return t.length>0?`${ut(t)} Nothing was read or written.`:void 0}function Oo(n){let t=En(n.objects);return t.length>0?`${Fn(t)} Nothing was read or written.`:void 0}var Pt=class{deps;constructor(t){this.deps=t}async execute(t){let e=Date.now(),r=`sync-${Date.now()}`,s=[],o=ko(t);if(o!==void 0)throw new Je(o,{...be(t.id,r,[],e,"failure"),error:o},Cn);let i=Oo(t);if(i!==void 0)throw new Je(i,{...be(t.id,r,[],e,"failure"),error:i},Pn);let{ordered:d,order:c,refused:a,typed:l,lookups:f,keys:y}=await this.writeOrderOf(t.objects),m=go(c),R=this.deps.queryTargetRows?l:new Set,w=this.deltaLoadOf(t),p=(b,O)=>new Je(b,{...be(t.id,r,[],e,"failure"),error:b},O),S;try{S=await this.planFiles(t,d,w)}catch(b){let O=b instanceof Error?b.message:String(b);throw new Fe(O,be(t.id,r,[],e,"failure"),b)}if(S?.storage.shortfall)throw new Fe(`${S.storage.shortfall} Nothing was written.`,{...be(t.id,r,[],e,"failure"),files:S.storage});let A=await this.earlierLinks(t),U=d.filter(b=>b.operation==="insert");if(A.unread!==void 0&&U.length>0)throw p(wo(A.unread,U),Vo);let x;try{x=await this.alreadyCopiedOf(t,d,A.links)}catch(b){let O=`What earlier runs of this configuration copied could not be looked up in the target (${b instanceof Error?b.message:String(b)}), so nothing was written.`;throw new Fe(O,{...be(t.id,r,[],e,"failure"),error:O},b)}let h=await this.countRun(t,d,w,this.deps.writeGate!==void 0);if(this.deps.writeGate&&"unread"in h){let b=`The records to write could not be counted (${h.unread}), so nothing was written.`;throw new Fe(b,{...be(t.id,r,[],e,"failure"),error:b})}let j=new Map,E=this.standardPricebooksOnce(),I=this.currenciesOnce(),k=w===void 0?new Map:void 0;if(this.deps.writeGate&&"counted"in h){let b;try{b=await this.heldBackOfRun(t,d,a,f,w,A.links,x,E,I,k)}catch(D){let Z=D instanceof Error?D.message:String(D);throw new Fe(Z,{...be(t.id,r,[],e,"failure"),error:Z},D)}let O=bo(d,h.counted,x,a,R,b.heldBack,b.matched,A.linked,await this.rolesLinkedAtTheGate(t,d,a,b.heldBack,x,A.links,k),{keys:y,...this.deps.describeTargetFieldsAgain?{typed:l}:{}}),{answer:F}=await this.deps.writeGate.hold(O);if(!F.go)throw p(F.message,F.code);for(let D of O.unwritable??[])j.set(D.objectApiName,D.rows)}let C=this.deps.leaseOfTheGate?.(),P=C&&C.assigned>0?await this.recordTypesReadAgain(d.map(b=>b.objectApiName).filter(b=>l.has(b)&&!j.has(b))):void 0,M=new Map,q=async()=>{let b=C;C=void 0,await b?.giveBack().catch(()=>{});for(let[O,F]of await this.readBackRecordTypes(M))for(let D=s.length-1;D>=0;D--)if(s[D].objectApiName===O){s[D]={...s[D],recordTypeGiven:F};break}},G=new rt(A.links),ne=this.recordTypesOnce(),Q=new Map,z=Ks(t),ae=this.deps.idMap,te={sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId},re=Promise.resolve(),B,ce=(b,O,F)=>{if(!ae)return;let D=ei(b.operation,O,F);for(let[Z,ee]of[[D.written,!1],[D.linked,!0]])Z.length!==0&&(re=re.then(()=>ae.record(t.id,te,b.objectApiName,Z,ee).catch(he=>{B??=he instanceof Error?he.message:String(he)})))},oe=0,Re=(b,O)=>{if(O.length===0)return;this.deps.creations?.deleted?.(b,O),oe+=O.length,G.noteDeleted(O);let F=ae?.forget?.bind(ae);F&&(re=re.then(()=>F(t.id,te,O).then(()=>{},D=>{B??=D instanceof Error?D.message:String(D)})))},K=this.deps.creations,v=new Map,L=0,se=(b,O)=>{if(!K)return;let F=to(b.operation,O);if(F.length===0)return;let D=b.objectApiName;K.noteUnanswered?K.noteUnanswered(D,F):K.note(D,F),v.set(D,(v.get(D)??0)+F.length)},fe=(b,O)=>{K&&(K.note(b,[O]),L++)},$=!1,W=!1,X=!1,V=async b=>{let O=await K?.flush();await re;let F=[];return A.unread!==void 0&&!X&&(X=!0,F.push(`What earlier runs of this configuration wrote could not be read (${A.unread}): a lookup at a record one of them wrote went as the source holds it.`)),O!==void 0&&!$&&($=!0,F.push(`What this run created could not all be kept (${O}): removing the run may leave some of it in the target.`)),B!==void 0&&!W&&(W=!0,F.push(`Which record of the target each record this run wrote became could not all be kept (${B}): a later run may send a lookup at one of them as the source holds it.`)),F.length===0?b:{...b,errors:[...b.errors,...F]}},J=async b=>{s.push(await V(b))},ue=new Map,Ie=new Set((c?.cycles??[]).map(b=>b[b.length-1])),Ce=(b,O)=>{for(let F=s.length-1;F>=0;F--)if(s[F].objectApiName===b){s[F]=qo(s[F],O,[...m.get(b)??[]]);return}},ie=new Map,Ne=(b,O)=>{for(let F=s.length-1;F>=0;F--)if(s[F].objectApiName===b){s[F]={...s[F],errors:[...s[F].errors,O]};return}},je=(b,O,F)=>{for(let D=s.length-1;D>=0;D--){let Z=s[D];if(Z.objectApiName!==b)continue;if(!Z.delta)return;let ee=(Z.delta.lookupsOwed??0)+O;s[D]={...Z,delta:{...Z.delta,...F!==void 0?{recorded:F}:{},...ee>0?{lookupsOwed:ee}:{}}};return}},at=async()=>{for(let[b,O]of[...ue]){ue.delete(b),await this.deps.pauseGate?.whilePaused(this.deps.signal);let F=this.deps.signal?.aborted?{leftOut:pn(O.pending),unset:fn(O.pending)}:await this.deps.dataSync.setLookups(O.objectConfig,O.pending,G,!0);"set"in F&&F.set&&K?.touched?.(b,F.set.records),Ce(b,F);let D=ie.get(b);if(ie.delete(b),F.unset===0){let Z=D?.();Z!==void 0&&je(b,0,Z)}else je(b,F.unset)}},me=()=>{for(let[b,O]of[...ue])ue.delete(b),ie.delete(b),Ce(b,{leftOut:pn(O.pending)}),je(b,fn(O.pending))},Se=b=>{let O=Js(z,b.objectResults.some(ee=>ee.success>0)),F={...b,...S?{files:S.storage}:{},...O?{contactPoints:O}:{}},D=K?.overwrittenCount?.()??0,Z=K?.deleted?oe:0;return!K||v.size===0&&L===0&&D===0&&Z===0?F:{...F,created:{runId:K.runId,objects:[...v].map(([ee,he])=>({objectApiName:ee,count:he})),files:L,...D>0?{overwritten:D}:{},...Z>0?{deleted:Z}:{}}}},Nt="counted"in h?[...h.counted.values()].reduce((b,{rows:O})=>b+O,0):void 0,Ve=this.isGrappeActive(Nt);Ve&&this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:r,totalPartitions:d.length,totalRecords:Nt}});let Ze=()=>{if(!Ve)return;let b=0,O=0;for(let F of s)b+=F.processed,O+=F.failed;this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:r,totalProcessed:b,totalFailed:O}})},de=async(b,O)=>(me(),await q(),Ze(),await K?.flush(),await re,Se(ni(t.id,r,s,e,b,O))),Me=0;for(let[b,O]of d.entries()){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return de(d.slice(b));let F=a.get(O.objectApiName),D=j.get(O.objectApiName);if(F&&D!==void 0){let N=Xo(O,F,D);try{await this.noteLeftOutRefused(t,O,w,{links:G,...A.linked?{earlierLinked:A.linked}:{},recordTypes:ne,currencies:I,currencyChangesById:Q,standardPricebooks:E,...k?{gateReads:k}:{}},x.get(O.objectApiName))}catch(Y){let ye=Y instanceof Error?Y.message:String(Y);throw await J({...N,errors:[...N.errors,ye]}),me(),new Fe(ye,Se(be(t.id,r,s,e,"failure")),Y)}await J(N);continue}let Z=new ht,{plan:ee,mark:he}=await this.readPlan(t,O,w),$e={changedSince:ee?.read==="delta"?We(ee.since):void 0,rows:0,cut:!1},ge=(N,Y)=>ee?{...N,delta:Ge(ee,$e.rows,Y)}:N,xe=S?.objects.get(O.objectApiName),Be=xe?new Map:void 0,Ue;try{Ue=await this.syncObject(t,O,Z,{links:G,...A.linked?{earlierLinked:A.linked}:{},recordTypes:ne,currencies:I,currencyChangesById:Q,standardPricebooks:E,...z?{contactPoints:z}:{},later:m,...P?{recordTypesUnderTheLease:P}:{},createdWithoutRecordType:M,...k?{gateReads:k}:{}},ee?$e:void 0,Be,K||ae?(N,Y)=>{se(O,N),ce(O,N,Y)}:void 0,x.get(O.objectApiName),(m.get(O.objectApiName)?.size??0)>0?N=>{let Y=ue.get(O.objectApiName);Y?Y.pending.push(...N):ue.set(O.objectApiName,{objectConfig:O,pending:N})}:void 0)}catch(N){if(N instanceof Ke){let Y=De(st(O.objectApiName,O.operation,N.written,N.notes,N.lookupsLeftOut,N.writtenWithoutFields),Z);return(Y.processed>0||Y.skipped>0)&&await J(ge(Y)),de(d.slice(b))}throw await J(ge(De({...Ct(O),failed:1,errors:[N instanceof Error?N.message:String(N)]},Z))),me(),new Fe(N instanceof Error?N.message:String(N),Se(be(t.id,r,s,e,"failure")),N)}if(Ue===po){let N=De(Ct(O),Z);return N.skipped>0&&await J(ge(N)),de(d.slice(b))}let u=Ue,g=!0;if(xe&&Be&&t.files){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return await J(ge(u)),de(d.slice(b+1),vo(O));let N=await Es({config:t,option:t.files,objectApiName:O.objectApiName,planned:xe,written:Be,deps:this.deps.files,signal:this.deps.signal,waitIfPaused:()=>this.deps.pauseGate?.whilePaused(this.deps.signal)??Promise.resolve(),onCreated:fe});if(u={...u,files:N.outcome,errors:[...u.errors,...N.notes]},g=N.outcome.failed===0&&N.outcome.pastRunCap===0&&N.unplanned===0,N.cancelled)return await J(ge(u)),de(d.slice(b+1),vo(O))}let T;if(ee?.read==="delta"&&t.propagateDeletes===!0&&$e.changedSince){if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return await J(ge(u)),de(d.slice(b));try{T=await this.carryDeletions(O,$e.changedSince,N=>Re(O.objectApiName,N))}catch(N){if(!(N instanceof Ke))throw N;let Y=st(O.objectApiName,"delete",N.written);return await J(ge({...u,errors:[...u.errors,...Y.errors,...N.notes]},{deleted:Y.success,deleteFailed:Y.failed,notes:[],complete:!1})),de(d.slice(b))}u={...u,errors:[...u.errors,...T.notes]}}let _=$e.lookupsUnset??0,pe=u.failed===0&&g&&!$e.cut&&_===0&&(T===void 0||T.deleteFailed===0&&T.error===void 0&&T.complete),ke=(N,Y,ye)=>{let An=xe?.filesSeen;try{return this.deps.deltaStore?.record(t.id,{sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,objectApiName:O.objectApiName,watermark:N,fingerprint:Y,recordedAt:new Date().toISOString(),...An!==void 0?{filesSeen:An}:{}}),N}catch(Mt){ye(`The watermark could not be saved, so the next run reads from the previous one: ${Mt instanceof Error?Mt.message:String(Mt)}`);return}},Pe;if(ee&&he!==null&&pe){let{fingerprint:N}=ee,Y=O.objectApiName;ue.has(Y)?ie.set(Y,()=>ke(he,N,ye=>Ne(Y,ye))):Pe=ke(he,N,ye=>{u={...u,errors:[...u.errors,ye]}})}ee&&(u={...u,delta:Ge(ee,$e.rows,T,Pe,_)}),await J(u),Ie.has(O.objectApiName)&&await at(),Ve&&(Me++,this.deps.onGrappeEvent?.({type:"grappe:partitionProgress",payload:{grappeId:`sync-partition-${Me}`,percentage:Math.round(Me/d.length*100),processedRecords:u.processed}}))}await q();let dt=Ao(s);return Ze(),await K?.flush(),await re,Se(be(t.id,r,s,e,dt))}async recordTypesReadAgain(t){let e=this.deps.describeTargetFieldsAgain,r=new Map;return e&&await Promise.all(t.map(async s=>{try{r.set(s,(await e(s)).recordTypes??[])}catch{}})),r}async readBackRecordTypes(t){let e=this.deps.queryTargetRows,r=new Map;return await Promise.all([...t].map(async([s,{given:o,types:i,ids:d}])=>{if(!e||d.length===0){r.set(s,o);return}try{let c=await e(Zr(s,d));r.set(s,{...o,readBack:Qr(c,i)})}catch(c){let a=c instanceof Error?c.message:String(c);r.set(s,{...o,readBack:{read:0,types:[],unread:a}})}})),r}async earlierLinks(t){let e=this.deps.idMap;if(!e)return{};try{let r={sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId},s=await e.load(t.id,r);if(!s)return{};let o=await e.linked?.(t.id,r);return{links:s,...o!==void 0&&o.size>0?{linked:o}:{}}}catch(r){return{unread:r instanceof Error?r.message:String(r)}}}recordTypesOnce(){let t;return()=>{let e=this.deps.recordTypes;return e?(t??=e().catch(r=>{throw new Error(`The record types of the two orgs could not be read, so none of these records was sent: ${r instanceof Error?r.message:String(r)}`)}),t):Promise.resolve(void 0)}}currenciesOnce(){let t;return()=>{let e=this.deps.currencies;return e?(t??=e().catch(()=>{}),t):Promise.resolve(void 0)}}standardPricebooksOnce(){let t;return()=>{let e=this.deps.standardPricebooks;return e?(t??=e().catch(()=>{}),t):Promise.resolve(void 0)}}async pricesSettled(t,e,r){let s=t.objectApiName,o=t.operation!=="delete"&&At(s,e.sources)?await r.standardPricebooks?.():void 0;o&&r.links.noteMatched(o.source,o.target);let i=o&&s===qe&&e.sources.some(Sn)?await r.currencies():void 0;return jt(s,e,o,i,d=>r.links.refusedObjectOf(d)!==void 0)}deltaLoadOf(t){if(t.mode==="delta")return!this.deps.deltaStore||!this.deps.deltaReads?null:this.deps.deltaStore.load(t.id)}async readPlan(t,e,r){if(r===void 0)return{plan:null,mark:null};let s=nt(t,e,r),o=this.deps.deltaReads;if(!o||s.read==="full"&&s.reason==="not_saved")return{plan:s,mark:null};try{return{plan:s,mark:await o.latestModstamp(e.objectApiName)}}catch{return{plan:{read:"full",reason:"no_modstamp",fingerprint:s.fingerprint},mark:null}}}async carryDeletions(t,e,r){let s=await this.tallyObjectDeletions(t,e);if("error"in s)return{deleted:0,deleteFailed:0,error:s.error,notes:[s.error],complete:!1};let{tally:o,notes:i}=s;if(o.ids.length===0)return{deleted:0,deleteFailed:0,notes:i,complete:!o.truncated};let d={...t,operation:"delete",fieldMappings:[],transformRules:[],addOnFields:[]},c;try{c=await this.deps.dataSync.write(d,o.ids.map(l=>({Id:l})))}catch(l){throw l instanceof Ke&&r(mo(o.ids,l.written)),l}r(mo(o.ids,c.outcomes));let a=st(t.objectApiName,"delete",c.outcomes,c.notes);return{deleted:a.success,deleteFailed:a.failed,notes:[...a.errors,...i],complete:!o.truncated}}async tallyObjectDeletions(t,e){let r=this.deps.deltaReads;if(!r)return{error:"Deletions need the source's recycle bin, and none was given."};let s=zt(t);if("refused"in s)return{error:s.refused};let o=Ee(t.where,e)??"";try{let i=await lr(r,t,s,o,d=>{if(s.sourceField==="Id")return d.Id;let c=this.deps.fieldMapping.apply(d,t.fieldMappings,t.excludedFields);return this.deps.transformPipeline.transformRecord(c,t)[s.keyField]});return{tally:i,notes:fr(i,s.keyField)}}catch(i){if(this.deps.signal?.aborted)throw new Ke(t.objectApiName,[]);return{error:`The source's deletions could not be read, so none was carried; the next run looks for them again: ${i instanceof Error?i.message:String(i)}`}}}async countRun(t,e,r,s){let o=this.deps.countSource;if(!s&&!this.deps.grappeConfig?.enabled||!o)return{none:!0};let i=new Map;try{for(let d of e){let c=r===void 0?null:nt(t,d,r),a=c?.read==="delta"?{changedSince:We(c.since)}:void 0,l=a?await o(t.sourceOrgId,d,a):await o(t.sourceOrgId,d);if(!Number.isFinite(l)||l<0)throw new Error(`the source answered no count of ${d.objectApiName}`);let f=s&&l>0&&this.deps.countPersonAccounts&&Zo.has(d.objectApiName.toLowerCase())?await this.deps.countPersonAccounts(d,a):void 0;i.set(d.objectApiName,{rows:l,...f!==void 0&&f>0?{personAccounts:f}:{}})}}catch(d){return{unread:d instanceof Error?d.message:String(d)}}return{counted:i}}async alreadyCopiedOf(t,e,r){let s=new Map,o=this.deps.readSourceIds,i=this.deps.findInTarget;if(!r||r.size===0||!o||!i)return s;for(let d of e){if(d.operation!=="insert")continue;if(this.deps.signal?.aborted)break;let c=new Map;for(let y of await o(d)){let m=r.get(we(y));m!==void 0&&c.set(we(y),m)}if(c.size===0)continue;let a=await i(t.targetOrgId,d,"Id",[...new Set(c.values())]),l=new Set([...a.keys()].map(y=>y.slice(0,15))),f=new Set;for(let[y,m]of c)l.has(m.slice(0,15).toLowerCase())&&f.add(y);f.size>0&&s.set(d.objectApiName,f)}return s}async writeOrderOf(t){let e=this.deps.describeTargetFields,r=new Map,s=new Set,o=new Map;if(!e)return{ordered:[...t].sort((c,a)=>c.insertOrder-a.insertOrder),refused:r,typed:s,lookups:new Map,keys:o};let i=new Map,d=[];for(let c of t){if(c.operation==="delete"){d.push(c);continue}let a=await Hs(e,c.objectApiName,c.operation,c.externalIdField);"refused"in a&&r.set(c.objectApiName,a.refused);let l="target"in a&&a.target?zs(Gs(c,a.target),a.target):c;d.push(l),!("refused"in a)&&(l.operation==="update"||l.operation==="upsert"||l.objectApiName===le)&&o.set(c.objectApiName,Ds(l.operation==="upsert"?l.externalIdField??"Id":"Id","target"in a?a.target:void 0)),"target"in a&&a.target&&(i.set(c.objectApiName,Qs(l,a.target)),Te(c.operation)&&(a.target.recordTypes??[]).some(f=>!f.master)&&s.add(c.objectApiName))}return{...Xs(d,i),refused:r,typed:s,lookups:i,keys:o}}async heldBackOfRun(t,e,r,s,o,i,d,c,a,l){let f=new Map,y=e.some(R=>Te(R.operation)&&(R.objectApiName===Qe||R.objectApiName===qe));return r.size===0&&!y?{heldBack:new Map,matched:f}:{heldBack:await fo({ordered:e,lookups:s,leftOut:new Set(r.keys()),...i?{earlier:i}:{},copied:d,standardPricebooks:c,currencies:a,matched:f,read:async R=>{let w=o===void 0?null:nt(t,R,o);if(w?.read==="delta")return this.deps.querySource(t.sourceOrgId,R,{changedSince:We(w.since)});let p=await this.deps.querySource(t.sourceOrgId,R);return l?.set(R.objectApiName,p),p}}),matched:f}}async rolesLinkedAtTheGate(t,e,r,s,o,i,d){let c=p=>e.find(S=>S.objectApiName===p),a=c(_e),l=c(le);if(!a||!l||!Te(l.operation))return;if(!this.deps.queryTargetRows||a.excludedFields.includes(Oe))return 0;if(!d||a.operation!=="insert")return;let f=p=>p.fieldMappings.length===0&&p.addOnFields.length===0&&p.transformRules.length===0;if(!f(a)||!f(l)||[_e,le,Ut].some(p=>r.has(p)||s.has(p)))return;let m=await this.deps.describeTargetFields?.(_e).catch(()=>{});if(!m)return;if(!m.creatable.has(Oe))return 0;let R=async p=>{let S=d.get(p.objectApiName);if(S)return S;let A=await this.deps.querySource(t.sourceOrgId,p);return d.set(p.objectApiName,A),A},w=p=>typeof p.Id=="string"&&p.Id!==""?p.Id:void 0;try{let p=new Set([...i?.keys()??[]].map(we)),S=c(Ut);if(S&&Te(S.operation)&&e.indexOf(S)<e.indexOf(a))for(let h of await R(S)){let j=w(h);j&&p.add(we(j))}let A=h=>o.get(h)??new Set,U=new Map;for(let h of await R(a)){let j=w(h),E=h[Oe];!j||typeof E!="string"||E===""||A(_e).has(we(j))||!p.has(we(E))||U.set(we(j),E)}if(U.size===0)return 0;let x=(await R(l)).filter(h=>{let j=w(h);return j!==void 0&&!A(le).has(we(j))});return qt(x,h=>U.get(we(h))).length}catch{return}}isGrappeActive(t){let e=this.deps.grappeConfig;return!!(e?.enabled&&t!==void 0&&t>=e.autoActivateThreshold)}async simulate(t){let e=ko(t);if(e!==void 0)throw new Error(e);let r=Oo(t);if(r!==void 0)throw new Error(r);let s=Date.now(),o=[],{ordered:i,order:d,refused:c,typed:a,lookups:l,keys:f}=await this.writeOrderOf(t.objects),y,m,R,w=await this.validationRulesOf(i),p=(P={})=>({configId:t.id,operationId:`sync-simulation-${s}`,direction:t.direction,conflictStrategy:t.conflictStrategy,objects:o,duration:Date.now()-s,timestamp:new Date().toISOString(),...y?{files:y.storage}:{},...w.unread!==void 0?{validationRulesUnread:w.unread}:{},...d?{writeOrder:d}:{},...m?{writeCheck:m}:{},...R!==void 0?{writeCheckUnread:R}:{},...P}),S=this.deltaLoadOf(t);try{y=await this.planFiles(t,i,S)}catch(P){return this.deps.signal?.aborted?p({cancelled:!0}):p({error:P instanceof Error?P.message:String(P)})}let A=await this.earlierLinks(t),U=i.filter(P=>P.operation==="insert");if(A.unread!==void 0&&U.length>0)return p({error:wo(A.unread,U)});let x;try{x=await this.alreadyCopiedOf(t,i,A.links)}catch(P){return this.deps.signal?.aborted?p({cancelled:!0}):p({error:P instanceof Error?P.message:String(P)})}let h=this.deps.writeGate,j=this.standardPricebooksOnce(),E=this.currenciesOnce(),I=S===void 0?new Map:void 0,k=h?await this.countRun(t,i,S,!0):void 0;if(h&&k&&"unread"in k&&(R=k.unread),h&&k&&"counted"in k)try{let P=await this.heldBackOfRun(t,i,c,l,S,A.links,x,j,E,I);m=await h.measure(bo(i,k.counted,x,c,this.deps.queryTargetRows?a:new Set,P.heldBack,P.matched,A.linked,await this.rolesLinkedAtTheGate(t,i,c,P.heldBack,x,A.links,I),{keys:f,typed:a}))}catch(P){R=P instanceof Error?P.message:String(P)}let C={links:new rt(A.links),...A.linked?{earlierLinked:A.linked}:{},recordTypes:this.recordTypesOnce(),currencies:E,currencyChangesById:new Map,standardPricebooks:j,later:go(d),...I?{gateReads:I}:{}};for(let[P,M]of i.entries()){if(this.deps.signal?.aborted)return p({cancelled:!0});this.deps.onSimulationProgress?.(P,i.length,M.objectApiName);try{let q=await this.simulateObject(t,M,S,C,x.get(M.objectApiName),c.get(M.objectApiName)),G=y?.objects.get(M.objectApiName),{rules:ne,onChange:Q}=Do(M.operation,w.byObject.get(M.objectApiName)??[]),z=[...q.notes,...G?.notes??[],...Q.length>0?[_o(Q)]:[]];o.push({...q,...G?{files:G.outcome}:{},notes:z,...ne.length>0?{validationRules:ne}:{}})}catch(q){return this.deps.signal?.aborted?p({cancelled:!0}):p({error:q instanceof Error?q.message:String(q),failedObject:M.objectApiName})}}if(m){let P=new Set([...m.objects.map(B=>B.objectApiName),...(m.rolesLinked??0)>0?[le]:[]]),M=o.filter(B=>P.has(B.objectApiName)).reduce((B,ce)=>B+(ce.operation==="delete"?ce.delete:ce.insert+ce.update),0),q={...m};delete q.rolesByThePlatform,delete q.rolesLinked;let G=o.filter(B=>P.has(B.objectApiName)).reduce((B,ce)=>B+(ce.writtenByThePlatform??0),0),ne=(m.rolesLinked??0)-G,Q=m.total+ne,z=Q-M,ae={objectApiName:le,rows:0},te=q.objects.some(B=>B.objectApiName===le)?q.objects:[...q.objects,ae],re=Q>0&&M===0;m={...q,objects:te.map(B=>B.objectApiName===le?{...B,rows:Math.max(0,B.rows+ne)}:B).filter(B=>B.rows>0),total:Q,...G>0?{rolesLinked:G}:{},...z>0?{notWritten:z}:{},...re?{total:0}:{},...re&&q.verdict==="writes"?{verdict:"nothing"}:{}}}return p()}async validationRulesOf(t){let e=this.deps.readValidationRules,r=t.filter(o=>o.operation!=="delete").map(o=>o.objectApiName),s=new Map;if(!e||r.length===0)return{byObject:s};try{for(let{objectApiName:o,...i}of await e(r))s.set(o,[...s.get(o)??[],i]);return{byObject:s}}catch(o){return{byObject:s,unread:o instanceof Error?o.message:String(o)}}}async simulateObject(t,e,r,s,o,i){let d=this.deps.findInTarget;if(!d)throw new Error("A simulation needs to look records up in the target org.");let c=new ht,{plan:a}=await this.readPlan(t,e,r),l={changedSince:a?.read==="delta"?We(a.since):void 0,rows:0,cut:!1},f=await this.prepare(t,e,c,a?l:void 0,o,s.gateReads,s.earlierLinked),y=f.records.length>0?await this.pricesSettled(e,f,s):void 0,m=y?{...f,...y}:f;if(i&&m.records.length>0){Ro(s.links,e,m.sources);let v=y?It(s.links,e,y.standsFor):[];return yo({objectApiName:e.objectApiName,operation:e.operation,read:m.read,insert:0,update:0,delete:0,skipped:m.alreadyCopied,...kn(m),refused:m.records.length+v.length,conflicts:0,conflictFields:[],notes:[i.message]},m)}let R=zo(e,m,s.links),w=R.prepared,p=null;if(w.records.length>0&&this.deps.describeTargetFields)try{let v=await this.deps.describeTargetFields(e.objectApiName);p=v.creatable.size>0?v:null}catch{p=null}let S=await ho(s,w.records,w.sources,e.objectApiName),A=qs({config:{...e,fieldMappings:[],addOnFields:[]},records:w.records,target:p,run:S}),U=A.sentAt.map(v=>w.records[v]),x=tr(e),h=new Map;if(x!==null){let v=new Map;for(let L of U){let se=L[x],fe=tt(se);fe!==null&&v.set(fe,se)}v.size>0&&(h=await d(t.targetOrgId,e,x,[...v.values()]))}let j=U.map(v=>sr(e,v,h)),E=j.flatMap((v,L)=>v==="insert"||v==="update"?[L]:[]),I=p?.fields!==void 0&&E.length>0?ir(e.objectApiName,E.map(v=>({payload:A.payloads[v],source:w.sources[A.sentAt[v]]??{},creates:j[v]==="insert"})),p.fields):{refused:new Set,notes:[]},k=new Set([...I.refused].map(v=>E[v])),C=await this.lookupsTheTargetLacks(E.filter(v=>!k.has(v)),A.payloads,A.settled,p),P=Ko(C,j,p);for(let v of P.refused)k.add(v);let M=E.filter(v=>j[v]==="insert"&&!k.has(v)),q=e.operation==="insert"?(p?.fields??[]).filter(v=>v.unique===!0&&v.createable):[],G=new Map;for(let v of q){let L=new Map;for(let se of M){let fe=A.payloads[se][v.name],$=tt(fe);$!==null&&L.set($,fe)}L.size!==0&&G.set(v.name,await d(t.targetOrgId,e,v.name,[...L.values()]))}let ne=ar(M.map(v=>A.payloads[v]),G);for(let v of ne.refused)k.add(M[v]);let Q=new Set([...ne.linked].map(v=>M[v])),z=U.flatMap((v,L)=>k.has(L)||Q.has(L)?[]:[L]),ae=new Set(z.map(v=>A.sentAt[v])),te=w.unsettled.filter((v,L)=>ae.has(L)),re=or({objectConfig:e,read:w.read,records:z.map(v=>U[v]),leftOut:c.counts(e.objectApiName),inTarget:h,conflicts:w.conflicts,unsettled:te,matchField:w.matchField,writable:p?.creatable??null}),B=e.operation==="insert"||e.operation==="upsert",ce=v=>{let L=w.sources[v]?.Id;return typeof L=="string"&&L!==""?L:void 0},oe=[];if(e.operation!=="delete"){for(let{index:v}of A.held){let L=ce(v);L&&B&&s.links.noteRefused(L,e.objectApiName)}if(A.sentAt.forEach((v,L)=>{let se=ce(v);se&&(k.has(L)||rr.has(j[L])?B&&s.links.noteRefused(se,e.objectApiName):s.links.noteWritten(se,se))}),e.objectApiName===_e&&B)for(let v of z){let L=ce(A.sentAt[v]),se=A.payloads[v]?.[Oe];j[v]!=="insert"||!L||typeof se!="string"||se===""||s.links.noteSentWithContact(L,se)}y&&(oe=It(s.links,e,y.standsFor))}let Re=Bs(e.objectApiName,z.flatMap(v=>{let L=j[v]==="insert"?A.withoutRecordType.get(A.sentAt[v]):void 0;return L?[L]:[]}),Us(p?.recordTypes??[],S.recordTypes)),K={...re,skipped:re.skipped+Q.size+w.alreadyCopied+R.linked,...kn(w),...R.linked>0?{writtenByThePlatform:R.linked}:{},...w.encryptedLeftOut?{encryptedLeftOut:[...w.encryptedLeftOut]}:{},...Re?{recordTypeGiven:Re}:{},refused:re.refused+A.held.length+k.size+oe.length,notes:[...y?.standardMatched?[$t]:[],...Rt(y?hn(y,oe):[]).map(v=>`${v}.`),...R.linked>0?[Jo(R.linked)]:[],...re.notes,...A.notes,...oe.length>0?[gn(e.objectApiName,oe.length)]:[],...A.currencies.map(v=>`${gt(v)}.`),...I.notes,...P.notes,...ne.notes]};if(!a)return K;if(a.read==="delta"&&t.propagateDeletes===!0&&l.changedSince){let v=await this.tallyObjectDeletions(e,l.changedSince);if("error"in v)return{...K,notes:[...K.notes,v.error],delta:Ge(a,l.rows,{deleted:0,deleteFailed:0,error:v.error})};let L=v.tally.ids.length;return{...K,delete:K.delete+L,notes:[...K.notes,...v.notes],delta:Ge(a,l.rows,{deleted:L,deleteFailed:0})}}return{...K,delta:Ge(a,l.rows)}}async lookupsTheTargetLacks(t,e,r,s){let o=this.deps.queryTargetRows,i=new Map;if(!o||!s?.fields||s.references.size===0)return i;let d=new Map,c=new Map;for(let f of t){let y=e[f]??{},m=[];for(let[R,w]of Object.entries(y)){if(R==="RecordTypeId"||!s.references.has(R)||r[f]?.has(R)||typeof w!="string"||!Ho.test(w))continue;m.push({field:R,id:w});let p=s.fields.find(S=>S.name===R)?.referenceTo??[];for(let S of p)c.set(S,(c.get(S)??new Set).add(w))}m.length>0&&d.set(f,m)}if(d.size===0)return i;let a=new Set,l=new Set;for(let[f,y]of c){let m=[...y];for(let[R,w]of Ht(m,Rn).entries())try{let p=await o(`SELECT Id FROM ${Bt(f)} WHERE Id IN (${w})`);for(let S of p){let A=S.Id;typeof A=="string"&&a.add(A.slice(0,15))}}catch{let p=R*Rn;for(let S of m.slice(p,p+Rn))l.add(S.slice(0,15))}}for(let[f,y]of d)y.some(({id:R})=>!a.has(R.slice(0,15))&&!l.has(R.slice(0,15)))&&i.set(f,y.map(({field:R})=>R).sort());return i}async noteLeftOutRefused(t,e,r,s,o){if(!Te(e.operation))return;let{plan:i}=await this.readPlan(t,e,r),d={changedSince:i?.read==="delta"?We(i.since):void 0,rows:0,cut:!1},c=await this.prepare(t,e,new ht,i?d:void 0,o,s.gateReads,s.earlierLinked);if(c.records.length===0)return;let a=await this.pricesSettled(e,c,s);Ro(s.links,e,a.sources),It(s.links,e,a.standsFor)}async syncObject(t,e,r,s,o,i,d,c,a){let l=await this.prepare(t,e,r,o,c,s.gateReads,s.earlierLinked),f=await this.rolesWrittenWithTheirOpportunity(e,l,s,d),y=f.prepared,m=j=>Go(yo(Yo(j,y),y),f.said);if(y.records.length===0)return m(De(Ct(e),r));let R=await this.pricesSettled(e,y,s),{records:w,sourceIds:p,sources:S}=R;if(w.length===0)return m(De(mn(Ct(e),R),r));let A={...await ho(s,w,S,e.objectApiName),...R.standardFirst>0?{standardFirst:R.standardFirst}:{}},U=()=>It(s.links,e,R.standsFor);if(await this.deps.pauseGate?.whilePaused(this.deps.signal),this.deps.signal?.aborted)return po;if(i||d||a||o){let j=E=>{E.forEach((I,k)=>{let C=p[k];i&&I.success&&I.id&&C&&i.set(C,I.id)}),d?.(E,p)};try{let{outcomes:E,notes:I,currencies:k,lookupsLeftOut:C,writtenWithoutFields:P,lookupsToSet:M,lookupsUnset:q}=await this.deps.dataSync.write({...e,fieldMappings:[],addOnFields:[]},w,A);o&&q!==void 0&&(o.lookupsUnset=q),j(E);let G=U();return M&&a?.(M),m(De(So(Zs(st(e.objectApiName,e.operation,E,I,C,P),k),R,G),r))}catch(E){throw E instanceof Ke&&j(E.written),E}}let x=await this.deps.dataSync.sync({...e,fieldMappings:[],addOnFields:[]},w,A),h=U();return m(De(So(x,R,h),r))}async rolesWrittenWithTheirOpportunity(t,e,r,s){let o=this.deps.queryTargetRows;if(t.objectApiName!==le||t.operation!=="insert"&&t.operation!=="upsert"||!o||!r.links.sentWithAContact||e.records.length===0)return{prepared:e};let i=h=>typeof h=="string"&&h!==""?r.links.targetOf(h):void 0,d=e.records.map((h,j)=>({OpportunityId:i(h.OpportunityId),[Oe]:i(h[Oe]),IsPrimary:e.sources[j]?.IsPrimary??h.IsPrimary})),c=await this.deps.describeTargetFields?.(le).catch(()=>{}),a=h=>h!=="Id"&&h!=="OpportunityId"&&h!==Oe&&(c?.creatable.has(h)??!0),l=[...new Set(e.records.flatMap(h=>Object.keys(h)))].filter(a),f;try{f=await Vn(async h=>await o(h),d,h=>r.links.contactSentWith(h),l)}catch(h){return{prepared:e,said:{records:0,given:0,unread:h instanceof Error?h.message:String(h)}}}let{found:y,alike:m}=f;for(let h of m)r.links.roleLinkedFor(String(d[h].OpportunityId));let R=m.length>0?{alike:m.length}:{};if(y.size===0)return m.length>0?{prepared:e,said:{records:0,given:0,...R}}:{prepared:e};let w=[];for(let[h,j]of y){let E=Object.entries(e.records[h]??{}).filter(([I,k])=>a(I)&&k!==null&&k!==void 0&&String(j[I]??"")!==String(k));E.length>0&&w.push({Id:String(j.Id),...Object.fromEntries(E)})}let p=0,S;if(w.length>0)try{let h=await this.deps.dataSync.updateRecords(le,w,t.batchSize);w.forEach((j,E)=>{let I=h[E];I?.success?p++:S??=`${String(j.Id)}: ${I?.errors[0]??"not updated"}`})}catch(h){S=h instanceof Error?h.message:String(h)}let A=[],U=[];for(let[h,j]of y){let E=e.sourceIds[h],I=String(j.Id);r.links.roleLinkedFor(String(d[h].OpportunityId)),E!==void 0&&(r.links.noteWritten(E,I),A.push(E),U.push({success:!1,errors:[],existingId:I}))}s?.(U,A);let x=(h,j)=>!y.has(j);return{prepared:{...e,records:e.records.filter(x),sourceIds:e.sourceIds.filter(x),sources:e.sources.filter(x)},said:{records:y.size,given:p,...S!==void 0?{refusal:S}:{},...R}}}async prepare(t,e,r,s,o,i,d){let c=s?void 0:i?.get(e.objectApiName);c&&i?.delete(e.objectApiName);let a=s?await this.deps.querySource(t.sourceOrgId,e,{changedSince:s.changedSince,onBoundReached:()=>{s.cut=!0}}):c??await this.deps.querySource(t.sourceOrgId,e);s&&(s.rows=a.length);let l=e.externalIdField??"Id",f=this.deps.maskedSourceFields,m=(a.length>0&&f?await f(e.objectApiName).catch(()=>[]):[]).filter(k=>a.some(C=>Object.prototype.hasOwnProperty.call(C,k)));for(let k of a)for(let C of m)delete k[C];let R=m.length>0?{encryptedLeftOut:m}:{},w=e.operation==="insert"||e.operation==="upsert",p=w?r.keep(e.objectApiName,a):a,S=o&&o.size>0&&e.operation==="insert"?p.filter(k=>!(typeof k.Id=="string"&&o.has(we(k.Id)))):p,A=p.length-S.length,U=A>0&&d&&d.size>0?p.filter(k=>typeof k.Id=="string"&&o?.has(we(k.Id))===!0&&d.has(we(k.Id))).length:0;if(S.length===0)return{read:a.length,records:[],sourceIds:[],sources:[],conflicts:[],unsettled:[],matchField:l,alreadyCopied:A,alreadyLinked:U,...R};let h=S.map(k=>{let C=this.deps.fieldMapping.apply(k,e.fieldMappings,e.excludedFields);return this.deps.transformPipeline.transformRecord(C,e)}).map(k=>{let C=this.deps.fieldMapping.applyAddOns(k,e.addOnFields);return w?ti(e.objectApiName,C):C}),j=h,E=[],I=e.operation==="upsert"||e.operation==="update";if(t.direction==="bidirectional"&&I){let k=await this.deps.queryTarget(t.targetOrgId,e);for(let C of k)for(let P of m)delete C[P];if(E=this.deps.conflictResolver.detectConflicts(h,k,l),E.length>0){let C=this.deps.conflictResolver.resolve(E,t.conflictStrategy),P=new Map(C.map(M=>[M.recordId,M.resolvedValues]));j=h.map(M=>{let q=String(M[l]??""),G=P.get(q);return G?{...M,...G}:M})}}return{read:a.length,records:j,sourceIds:S.map(k=>typeof k.Id=="string"?k.Id:void 0),sources:S,conflicts:E,unsettled:h,matchField:l,alreadyCopied:A,alreadyLinked:U,...R}}async planFiles(t,e,r){let s=t.files;if(!s)return;let o=this.deps.files;if(!o)throw new Cs("This session cannot copy files: it reads no file content or file storage. Nothing was read or written.");return Ps({config:t,option:s,deps:o,tie:(i,d)=>this.tieToTarget(t,i,d),objects:e.map(i=>{let d=r===void 0?null:nt(t,i,r);return{objectConfig:i,...d?.read==="delta"?{changedSince:We(d.since),...d.filesSeen!==void 0?{filesSeen:d.filesSeen}:{}}:{}}})})}async tieToTarget(t,e,r){let s=this.deps.deltaReads,o=this.deps.files;if(!s||!o)return{held:new Map,refused:"the target cannot be asked"};let i=zt(e);if("refused"in i)return{held:new Map,refused:i.refused};let d=e.objectApiName,c=new Map;if(i.sourceField==="Id")for(let f of r)c.set(f,f);else{let f=$n(d),y=Bt(i.sourceField);for(let m of Ht(r)){let R=await o.copy.queryRecords(t.sourceOrgId,`SELECT Id, ${y} FROM ${f} WHERE Id IN (${m})`);for(let w of R){let p=this.deps.fieldMapping.apply(w,e.fieldMappings,e.excludedFields),S=this.deps.transformPipeline.transformRecord(p,e)[i.keyField];typeof w.Id=="string"&&tt(S)!==null&&c.set(w.Id,S)}}}if(c.size===0)return{held:new Map};let a=await s.targetIdsByKey(d,i.keyField,[...new Set(c.values())]),l=new Map;for(let[f,y]of c){let m=a.get(tt(y))??[];m.length===1&&l.set(f,m[0])}return{held:l}}};function ei(n,t,e){let r=[],s=[];return n!=="insert"&&n!=="upsert"?{written:r,linked:s}:(t.forEach((o,i)=>{let d=e[i];if(d===void 0)return;if(o.success&&typeof o.id=="string"&&o.id!==""){r.push([d,o.id]);return}let c=Vs(n,o);c!==void 0&&s.push([d,c])}),{written:r,linked:s})}function ti(n,t){let e=Jn(n,t);if(e.length===0)return t;let r={...t};for(let s of e)delete r[s];return r}function De(n,t){let e=t.counts();return e.length===0?n:{...n,skipped:n.skipped+e.reduce((r,{count:s})=>r+s,0),errors:[...n.errors,...e.map(({why:r,count:s})=>Kn(s,r))]}}function Ct(n){return{objectApiName:n.objectApiName,operation:n.operation,processed:0,success:0,failed:0,skipped:0,conflictCount:0,errors:[]}}function ni(n,t,e,r,s,o){let i=Ao(e)==="failure"?"failure":"partial",d=s.map(a=>a.objectApiName),c=d.length>0?`Cancelled before ${d.join(", ")} ${d.length===1?"was":"were"} synced.`:"Cancelled.";return{...be(n,t,e,r,i),cancelled:!0,error:o?`${o} ${d.length>0?c:""}`.trim():c}}function vo(n){return`Cancelled while the files of ${n.objectApiName} were copied: those copied stay in the target, the others are copied by the next run.`}function Ao(n){return n.length===0?"success":n.every(r=>r.failed>0&&r.success===0)?"failure":n.some(r=>r.failed>0||ri(r.delta)||(r.files?.failed??0)>0)?"partial":"success"}function ri(n){return n!==void 0&&(n.deleteFailed>0||n.deletionError!==void 0)}function be(n,t,e,r,s){let o=0,i=0,d=0,c=0;for(let a of e)o+=a.processed,i+=a.success,d+=a.failed,c+=a.skipped;return{configId:n,operationId:t,status:s,objectResults:e,totalProcessed:o,totalSuccess:i,totalFailed:d,totalSkipped:c,duration:Date.now()-r,timestamp:new Date().toISOString()}}var fi=`sandforge sync \u2014 run a Sync between two orgs, without the editor.
8
-
9
- Usage:
10
- npx sandforge sync \\
11
- --source <alias> --target <alias> --object <ApiName> [options]
12
-
13
- Required:
14
- --source <alias> sf CLI alias of the source org
15
- --target <alias> sf CLI alias of the target org
16
- --object <ApiName> object to sync; repeat for more. The run writes the
17
- parents their lookups name first, and keeps the
18
- order given otherwise.
19
- Append ":<Field>" to match on an external Id, which
20
- turns that object's operation into an upsert.
21
-
22
- Options:
23
- --operation <op> insert | upsert | update (default: insert)
24
- Per-object ":<Field>" wins over this.
25
- --where <obj=clause> SOQL WHERE for one object (repeatable)
26
- e.g. --where "Account=BillingCountry = 'France'"
27
- --batch-size <n> records per write call (default: 200)
28
- --dry-run simulate: read both orgs and say what the run
29
- would insert, update, skip or refuse, writing
30
- nothing (default: off)
31
- --files copy the files of the records each object writes:
32
- Salesforce Files and legacy attachments, 10 MB each
33
- and 100 MB a run at most, as a configuration that
34
- copies files does. The command keeps no record of
35
- the files it copied: run again, it copies them
36
- again (default: off)
37
- --keep-contact-points write emails and phone numbers as read. Without
38
- it, as in the panel, every address is written
39
- under .invalid and every phone number as a
40
- fictional one (default: off)
41
- --json emit the run summary as JSON (default: off)
42
- Saved to a file, it is what --remove takes the
43
- run back from: it names what the run created.
44
- The run's file does too, whatever becomes of the
45
- run (see SANDFORGE_JOURNAL_DIR). A dry run's names
46
- under wouldBeRefused what a real run would be
47
- refused for, the code of each under
48
- wouldBeRefusedCodes, as its line names it. A real
49
- run refused before its first write prints
50
- "refused": {"code", "message"} instead, the code its
51
- line names: refused (CODE): ..., each other reason
52
- of its gate under "alsoRefused", on a line of its own.
53
- --fail-on-partial exit 3, not 0, when the run wrote some records and
54
- the target refused others (default: off)
55
- --mute-automation mute the target's automation for the run through
56
- its own bypass: assign the user the run writes as,
57
- for the run alone, the permission sets holding the
58
- custom permissions its flows, processes and
59
- workflow rules test to stay quiet, and take them
60
- back as it ends; what no bypass keeps quiet still
61
- runs, and is named. Refused on a production org and
62
- for a user who cannot assign permission sets, exit
63
- 1; with --dry-run, says what would be muted and
64
- assigns nothing (default: off)
65
- --accept-emails write although the target delivers the emails its
66
- flows, processes and workflow rules send as the run
67
- writes (Setup > Deliverability: All email), or would
68
- not say whether it does. Read only when something
69
- that still runs sends one, with one line of
70
- anonymous Apex that sends nothing; without the flag
71
- the run is refused, exit 1 (EMAILS_NOT_ACCEPTED),
72
- nothing written. On System email only or No access
73
- it is not needed. --mute-automation keeps quiet what
74
- tests the org's bypass; what an Apex trigger sends is
75
- read nowhere (default: off)
76
- ${os({run:"the run",simulation:"--dry-run"})}
77
- --help this text
78
-
79
- Run a saved configuration:
80
- npx sandforge sync \\
81
- --config-file <config.json> --store <dir> --source <alias> --target <alias> \\
82
- [--dry-run] [--json]
83
-
84
- --config-file <file> a Sync configuration as the panel saves one, checked
85
- as the panel checks it: its objects, filters,
86
- mappings, add-ons, mode, and whether it copies files.
87
- It runs between the two orgs given, whatever orgs it
88
- names. In delta mode, each object reads only what the
89
- source changed since its last good run. A transform
90
- rule that names no field is refused before any org is
91
- reached, exit 1: it would change every field of every
92
- record.
93
- --store <dir> where the configuration is kept between runs, with
94
- its watermarks, the files it copied and which record
95
- of the target each source record it wrote became, as
96
- the panel keeps them beside it: give every run of it
97
- the same directory, and --remove too. A later run
98
- points a lookup at the copy an earlier run wrote.
99
- --object, --where, --operation, --batch-size, --files and
100
- --keep-contact-points come from the file (keepContactPoints), and are refused
101
- with it. A legacy attachment the source changed since it was copied is
102
- replaced, its earlier copy deleted, on a sandbox or a Developer Edition org,
103
- as in the panel; a production org keeps the copy.
104
-
105
- Remove what a run created:
106
- npx sandforge sync \\
107
- --remove <summary.json | run file | run id> --target <alias>
108
- [--include-changed] [--accept-automation] [--store <dir>]
109
- [--sweep | --sweep-list] [--sweep-late] [--sweep-untied] [--json]
110
-
111
- --remove <file | id> the summary a run printed with --json, saved to a
112
- file; or the run's file, which it names as it
113
- begins, or its run id. Deletes from the target what
114
- the run created: the records it inserted, or
115
- upserted where the target held none, the last object
116
- written first, into the target's recycle bin. Before
117
- that, gives the records it wrote over \u2014 an update,
118
- an upsert that found the record \u2014 the values they
119
- held before the run, of the fields it wrote, which
120
- the run kept first in <dir>/backups (below); one
121
- changed since the run stays as it is unless
122
- --include-changed. First of all, what a delta run
123
- deleted as the source had is brought back from the
124
- target's recycle bin, while it is there. A run
125
- another process still writes is refused, exit 1.
126
- From its file, a run killed,
127
- stopped or ended by an error is taken back too: a
128
- Bulk API job it had under way, which ran on in the
129
- target, is read back by its id first, and its
130
- records go with the rest.
131
- --target <alias> the org the run wrote to, and no other. It must be a
132
- sandbox or a Developer Edition org.
133
- --include-changed remove also the records changed since the run, which
134
- are kept otherwise, and give back their values from
135
- before the run to the records it wrote over that
136
- were changed since
137
- --accept-automation remove although the target runs flows, Apex
138
- triggers, processes or workflow rules as the removal
139
- brings records back from the recycle bin, gives them
140
- their values back, sets them back to Draft or
141
- deletes them, those --sweep deletes included, or
142
- could not say what it runs. Each is named before
143
- anything is written; without the flag the removal
144
- then writes nothing, exit 1 (default: off)
145
- --mute-automation mute the target's automation for the removal through
146
- its own bypass, as for a run; what no bypass keeps
147
- quiet still needs --accept-automation (default: off)
148
- --store <dir> for a run of a saved configuration: its store, which
149
- the removal tells what it took, so that the next
150
- delta run reads those objects whole and copies the
151
- files it deleted again
152
- --sweep before the run's records go, delete too what the
153
- target's automation made for the run, that the run did
154
- not write: what the run's user created under the
155
- records it created or wrote over, what they point
156
- at, or what hangs from those, three links at most, at
157
- most a minute after the record it is tied to \u2014 in the
158
- objects whose records it created and their children,
159
- tasks, events, feed, email messages, notes, case
160
- comments, and the objects the target's flows create.
161
- What a record of the run points at by a lookup the
162
- org refuses the delete for goes once that record is
163
- gone. The window runs from a second
164
- before the run's first write \u2014 its first call, an
165
- update before anything was created included, which
166
- the summary dates by this machine's clock, read on
167
- the org's \u2014 to a minute after its last write: the
168
- last record it created, read back from the org, or
169
- a later call, an update included, as the summary
170
- dates it. Listed and kept: what is tied to the run
171
- but came later, up to 15 minutes, or as the org's
172
- Automated Process user; and what the run's user
173
- created in the window tied to nothing of the run.
174
- What anyone changed more than 2 s after the run's
175
- last write, and after its own creation, stays \u2014 the
176
- run's user and its automation too \u2014 unless
177
- --include-changed, and the sweep then ends partial,
178
- exit 3; a change made before the run's last write
179
- reads as unchanged
180
- (default: off)
181
- --sweep-late with --sweep, take too what it lists as made late;
182
- with --sweep-list, say what it would take
183
- --sweep-untied with --sweep, take too what it lists as tied to
184
- nothing of the run; with --sweep-list, say what it
185
- would take; refused when another run of this
186
- machine wrote to the target in the window, or when
187
- that user created records in the window on objects
188
- neither the run nor the automation reaches (hand
189
- work, likely)
190
- --sweep-list list what --sweep would delete, per object with a few
191
- names and how many it ties to the run, and delete
192
- nothing, the run's records included; exit 3, as a
193
- refused --sweep, when it says the sweep is refused.
194
- What a sweep leaves: what another user created; what
195
- is tied to nothing, unless --sweep-untied; what came
196
- more than 15 minutes after its record, or after the
197
- removal began; what anyone changed after the run's
198
- last write, the run's own user included, unless
199
- --include-changed; what the automation changed
200
- rather than created; what left the org; and what the
201
- panel or another machine wrote
202
- --leave-undeletable remove the rest when the user the removal runs as
203
- may not delete the records of some objects of the
204
- run, leaving those with what they hang from; without
205
- it the removal stops before its first delete and
206
- names them (default: off)
207
- --json print the removal as JSON; refused before its first
208
- write, "refused": {"code", "message"}, the code its
209
- line names: refused (CODE): ... \u2014 a production org
210
- (PRODUCTION_TARGET), what fires as it writes
211
- (AUTOMATION_NOT_ACCEPTED), its mute (MUTE_PRODUCTION,
212
- MUTE_NO_RIGHT, MUTE_FAILED), objects its user may not
213
- delete (UNDELETABLE_NOT_LEFT), an org that is not the
214
- one the run wrote to (OTHER_ORG), a run still writing
215
- (RUN_WRITING)
216
-
217
- What the removal left on the run's records is kept beside the summary, in
218
- <summary>.removals.json, or beside the run's file, in <run id>.removal.json,
219
- and the next --remove of the same summary or file reads it.
220
-
221
- Environment:
222
- SANDFORGE_JOURNAL_DIR=<dir>
223
- where every run that writes keeps its file, in
224
- <dir>/sync-runs/<run id>.ndjson (default: ~/.sandforge),
225
- said as it begins: what it created, its calls as
226
- they went and answered, a Bulk API job's id once the
227
- org opened it, and how it ended. Ids and dates only.
228
- What a run writes over \u2014 an update, an upsert that
229
- finds the record \u2014 is read from the target first and
230
- kept in <dir>/backups, readable by you alone, as
231
- sandforge backup keeps a snapshot: the values the
232
- records held, of the fields the run writes, which
233
- --remove gives back. A call whose values cannot be
234
- kept is not sent, its rows refused with why.
235
-
236
- Before its first write, a run counts the records it writes under each filter,
237
- and is refused, with nothing written, when they would take more data storage
238
- than the target has left, or make the target's automation send more emails
239
- than it has left today; --dry-run says what it would meet. A run of a saved
240
- configuration leaves as they are the records an earlier run of it copied that
241
- are still in the target, and inserts the others.
242
-
243
- Exit codes: 0 the run finished, some of its records refused included (read
244
- the summary for per-object failures), or the removal took every record it set
245
- out to; 1 the run or the removal could not be started, either was refused
246
- before it wrote anything \u2014 a production target among the reasons; for the
247
- run, more data storage than the target has left, more emails or API requests
248
- than it has left today, emails it delivers without --accept-emails
249
- (EMAILS_NOT_ACCEPTED), a checkpoint asked first refused or not taken
250
- (CHECKPOINT_REFUSED); for the removal, what the target runs as it writes,
251
- without --accept-automation \u2014 or the run produced only failures, or it
252
- stopped on an error (its file keeps what it created); 2 a bad command line,
253
- or a summary or a file --remove cannot take a run back from; 3 the removal
254
- left records of the run in the target, or its sweep was refused or did not
255
- take all it was asked to (a --sweep-untied refused included), or the run was
256
- partial and --fail-on-partial was given; 130 a Ctrl-C stopped the run, 143 a
257
- SIGTERM (a CI job cancelled or timed out), 129 a SIGHUP: its file keeps what it
258
- created.
259
- `,pi=["--object","--where","--operation","--batch-size","--files","--keep-contact-points"],Ae=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,hi=new Set(["SYNC_TARGET_UNWRITABLE",He,tn]),gi={switches:["--dry-run","--files","--keep-contact-points","--json","--fail-on-partial","--mute-automation","--accept-emails",...nn.switches],values:["--source","--target","--object","--operation","--where","--batch-size","--config-file","--store",...nn.values]};function mi(n){let t=n.slice(2);(t.includes("--help")||t.includes("-h"))&&(process.stdout.write(fi),process.exit(0)),Wn(t,gi);let e=(w,p)=>{let S=t.indexOf(w);return S>=0&&S+1<t.length?t[S+1]:p},r=w=>{let p=[];for(let S=0;S<t.length;S++)t[S]===w&&S+1<t.length&&p.push(t[S+1]);return p},s=w=>t.includes(w),o=is(t),i=o!==void 0?{checkpointFirst:o}:{},d=e("--source"),c=e("--target");if(s("--config-file")){let w=e("--config-file"),p=e("--store");(!w||!p||!d||!c)&&(process.stderr.write(`--config-file wants the file, --store <dir> where it is kept between runs, --source and --target. Run with --help.
260
- `),process.exit(2));let S=pi.filter(s);return S.length>0&&(process.stderr.write(`--config-file takes its objects, filters and files from the file: ${S.join(", ")} cannot be given with it.
261
- `),process.exit(2)),{source:d,target:c,objects:[],operation:"insert",where:{},batchSize:200,dryRun:s("--dry-run"),files:!1,keepContactPoints:!1,json:s("--json"),failOnPartial:s("--fail-on-partial"),muteAutomation:s("--mute-automation"),acceptEmails:s("--accept-emails"),...i,configFile:w,store:p}}s("--store")&&(process.stderr.write(`--store keeps a saved configuration between runs: give it with --config-file.
262
- `),process.exit(2));let a=r("--object");(!d||!c||a.length===0)&&(process.stderr.write(`Missing --source, --target or --object. Run with --help.
263
- `),process.exit(2));let l=a.map(w=>{let[p,S]=w.split(":");return Ae.test(p)||(process.stderr.write(`Not an SObject API name: "${p}"
264
- `),process.exit(2)),pr(p)&&(process.stderr.write(`${hr(p)}
265
- `),process.exit(2)),S!==void 0&&!Ae.test(S)&&(process.stderr.write(`Not a field API name: "${S}"
266
- `),process.exit(2)),{objectApiName:p,externalIdField:S}}),f=e("--operation","insert")??"insert";f!=="insert"&&f!=="upsert"&&f!=="update"&&(process.stderr.write(`--operation takes insert, upsert or update, not "${f}".
267
- `),process.exit(2));let y={};for(let w of r("--where")){let p=w.indexOf("="),S=p>0?w.slice(0,p):"";Ae.test(S)||(process.stderr.write(`--where wants "Object=clause", not "${w}".
268
- `),process.exit(2)),y[S]=w.slice(p+1)}let m=e("--batch-size","200")??"200",R=Number(m);return(!Number.isInteger(R)||R<1||R>1e4)&&(process.stderr.write(`--batch-size takes a whole number between 1 and 10000.
269
- `),process.exit(2)),{source:d,target:c,objects:l,operation:f,where:y,batchSize:R,dryRun:s("--dry-run"),files:s("--files"),keepContactPoints:s("--keep-contact-points"),json:s("--json"),failOnPartial:s("--fail-on-partial"),muteAutomation:s("--mute-automation"),acceptEmails:s("--accept-emails"),...i}}function yi(n){let t=new Date().toISOString(),e=n.objects.map((r,s)=>({objectApiName:r.objectApiName,externalIdField:r.externalIdField,operation:r.externalIdField?"upsert":n.operation,fieldMappings:[],transformRules:[],excludedFields:[],addOnFields:[],batchSize:n.batchSize,where:n.where[r.objectApiName],insertOrder:s}));return{id:`cli-${Date.now()}`,name:"sandforge-sync",description:"Headless run",sourceOrgId:n.source,targetOrgId:n.target,direction:"source_to_target",mode:"full",objects:e,conflictStrategy:"source_wins",enableRollback:!1,createdAt:t,updatedAt:t,...n.files?{files:{maxFileSizeMB:10,maxRunMB:100}}:{},...n.keepContactPoints?{keepContactPoints:!0}:{}}}function wi(n,t){let e;try{e=JSON.parse(n)}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 r=gr.safeParse({config:{...e,sourceOrgId:t.source,targetOrgId:t.target}});if(!r.success){let i=r.error.issues[0];return{refusal:`is not a configuration a run takes (${i.path.slice(1).join(".")||"configuration"}: ${i.message})`}}let s=r.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 o=new Date().toISOString();return{config:{...s,id:s.id,createdAt:s.createdAt??o,updatedAt:s.updatedAt??o,objects:s.objects.map(i=>({...i,batchSize:i.batchSize??200}))}}}function Io(n){return ii(n,{recursive:!0}),new Ns(St(Ye(n,"configStore.json")))}function bi(n,t,e,r,s=!1){let o=c=>({query:async a=>c.query(a),queryMore:async a=>c.queryMore(a)}),i=c=>({pages:o(c),transport:c,create:async(a,l)=>c.sobject(a).create(l,{headers:jn()})}),d=new Map;return{copy:Fs({[n.sourceOrgId]:i(t),[n.targetOrgId]:i(e)}),sourceIds:async(c,a)=>{let l=c.objectApiName;if(!Ae.test(l))throw new Error(`Not an SObject API name: ${l}`);let f=Ee(c.where,a),{records:y}=await Le(o(t),`SELECT Id FROM ${l}${f?` WHERE ${f}`:""}`);return y.flatMap(m=>typeof m.Id=="string"?[m.Id]:[])},store:r??{load:()=>d.size===0?{kind:"none"}:{kind:"stored",map:{version:1,entries:[...d.values()]}},record:(c,a)=>{d.set(`${a.sourceOrgId}|${a.targetOrgId}|${a.sourceId}`,a)}},...s?{deleteFromTarget:async(c,a)=>mr(await e.sobject(c).destroy(a),c).map(l=>({id:l.id,success:l.success,errors:l.errors}))}:{}}}function Ri(n){let t=xt({isSandbox:n.sandbox,edition:n.edition});return Is(new Er,n.id,{orgType:t})}function jo(n){return async(t,e,r)=>{let s=e.objectApiName;if(!Ae.test(s))throw new Error(`Not an SObject API name: ${s}`);let o=Ee(e.where,r?.changedSince),i=o?` WHERE ${o}`:"",d={query:async y=>n.query(y),queryMore:async y=>n.queryMore(y)},a=(await n.sobject(s).describe()).fields.filter(y=>y.type!=="address"&&y.type!=="location").map(y=>y.name),l=!1,f=await Qn(`SELECT ${(a.length>0?a:["Id"]).join(", ")} FROM ${s}${i}`,async y=>{let m=await Le(d,y);return l||=m.truncated,m.records});return l&&r?.onBoundReached?.(),f}}function Si(n){return async(t,e,r)=>{let s=e.objectApiName;if(!Ae.test(s))throw new Error(`Not an SObject API name: ${s}`);let o=Ee(e.where,r?.changedSince);return(await n.query(`SELECT COUNT() FROM ${s}${o?` WHERE ${o}`:""}`)).totalSize}}function ki(n){return async(t,e)=>{let r=t.objectApiName;if(!Ae.test(r))return 0;let s=Ee(t.where,e?.changedSince);try{return(await n.query(`SELECT COUNT() FROM ${r} WHERE IsPersonAccount = true`+(s?` AND (${s})`:""))).totalSize}catch{return 0}}}function Oi(n){return async t=>{let e=t.objectApiName;if(!Ae.test(e))throw new Error(`Not an SObject API name: ${e}`);let r=Ee(t.where,void 0),{records:s}=await Le({query:async o=>n.query(o),queryMore:async o=>n.queryMore(o)},`SELECT Id FROM ${e}${r?` WHERE ${r}`:""}`);return s.flatMap(o=>typeof o.Id=="string"?[o.Id]:[])}}function $o(n){if(n.go||n.code!==He&&n.code!==Gt)return n;let{code:t,message:e,refusal:r}=n;return{...n,message:us({code:t,message:e,...r?{refusal:r}:{}})}}var vi={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 On(n,t){return{...n??{},sent:t}}function Co(n,t){let e=n.notWritten??0,r=n.total>0?n.total:e,s=[`write gate: ${r-e} record(s) to write to ${t}, about ${Kr(n.storage.estimateMB)} MB of data storage`];for(let a of n.objects)s.push(` ${a.objectApiName.padEnd(42)}${String(a.rows).padStart(8)}`);e>0&&s.push(` of the ${r} 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`),n.alreadyCopied>0&&s.push(` not counted: ${n.alreadyCopied} record(s) an earlier run of this configuration copied, still in the target, left as they are`),(n.alreadyLinked??0)>0&&s.push(` not counted: ${n.alreadyLinked} record(s) an earlier run of this configuration linked to records the target held, left as they are`),(n.overwrites??0)>0&&s.push(` of them, up to ${n.overwrites} written by an update or an upsert over records ${t} holds: their values are kept first, and --remove puts them back`),(n.rolesLinked??0)>0&&s.push(` not counted: ${n.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`),(n.rolesByThePlatform??0)>0&&s.push(` of them, up to ${n.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:o}=n;o.verdict==="unread"?s.push(` the data storage ${t} has left could not be read (${o.unread??""}): whether the records fit is not known`):o.remainingMB!==void 0&&o.maxMB!==void 0&&s.push(` data storage of ${t}: ${o.remainingMB} MB left of ${o.maxMB} MB`+(o.verdict==="exceeds"?": the records do not fit":o.verdict==="near"?": the records take more than 80 % of it":""));for(let a of n.emails){let l=a.objects.map(y=>`${y.perRecord} per ${y.objectApiName}`).join("; "),f=` emails: these records make ${t} send about ${zr(a.emails,a.limit)} (${l})`+(a.alertsCounted?", its email alerts among them, as a Developer Edition counts them":"");s.push(a.verdict==="unread"?`${f}; what it has left today could not be read (${a.unread??""})`:a.verdict==="fits"?`${f}; it has ${a.remaining??"?"} of ${a.max??"?"} left today`:`${f}, more than the ${a.remaining??"?"} of ${a.max??"?"} it has left today`)}n.emailsUnread!==void 0&&s.push(` emails: not counted, ${n.emailsUnread} could not be read`),n.deliverability&&s.push(` ${Hr(n.deliverability.reading)}`);let i=n.apiRequests;i&&s.push(i.verdict==="unread"?` API requests: about ${i.estimate}; what ${t} has left today could not be read (${i.unread??""})`:` API requests: about ${i.estimate}, of the ${i.remaining??"?"} ${t} has left of its ${i.max??"?"} a day`+(i.verdict==="exceeds"?": more than it has left":i.verdict==="near"?": it would leave less than a tenth of them":""));for(let a of n.unwritable??[])s.push(` ${a.objectApiName}: ${a.rows} record(s) ${t} takes none of \u2014 ${vi[a.why]}${a.key!==void 0?` (${a.key})`:""}`);let d=new Set((n.unwritable??[]).map(({objectApiName:a})=>a)),c=({parent:a,field:l})=>`${l} names ${a} records ${d.has(a)?"left out":"held back"}`;for(let a of n.heldBack??[]){let l=a.parents??[a];s.push(` ${a.objectApiName}: ${a.rows} record(s) held back, not written \u2014 `+(l.length===1?`their ${c(l[0])}`:l.map(f=>`${f.rows} whose ${c(f)}`).join("; ")))}return n.aboveRecords!==void 0&&s.push(` more than ${n.aboveRecords} records: the panel asks before it writes (sandforge.safety.confirmAboveRecords)`),s}function Po(n,t,e=!1){let r=n.flatMap(o=>o.recordTypeGiven?[o.recordTypeGiven]:[]),s=gs(r,t);return s.length>0&&t&&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 Eo(n){return`${n} already linked by an earlier run of this configuration to records the target held, left as they are`}function Ai(n,t="the target",e=!1,r,s){let o=[`
270
- simulation: ${n.objects.length} object(s), nothing written`];if(n.writeOrder){o.push(` write order: ${n.writeOrder.objects.join(", ")}`);for(let i of n.writeOrder.moved)o.push(` ${i.objectApiName} after ${i.after}: its ${i.field} names one`);for(let i of n.writeOrder.cycles)o.push(` ${i.join(", ")} name each other: in this order, the lookup at the one written later is left empty`)}if(n.writeCheck){for(let d of Co(n.writeCheck,t))o.push(` ${d}`);for(let d of n.checkpoint?rn(n.checkpoint):[])o.push(` ${d}`);if(n.writeCheck.verdict==="refused"){let d=n.writeCheck,[c,a]=(d.unwritable??[]).length>0?["SYNC_TARGET_UNWRITABLE","the target takes none of the records of an object it writes"]:r!==void 0?[He,r]:d.storage.verdict==="exceeds"?["SYNC_STORAGE_EXCEEDED","the records do not fit"]:d.apiRequests?.verdict==="exceeds"?[qr,"it takes more API requests than the target has left today"]:[He,d.checkpointUnread??"the checkpoint asked first is refused"];o.push(` a run would be refused before it writes (${c}): ${a}`)}else(n.writeCheck.unwritable??[]).length>0&&o.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 i=n.writeCheck.emails.some(d=>d.verdict==="exceeds");n.writeCheck.verdict!=="refused"&&i?o.push(" a run of the command would be refused before it writes (SYNC_EMAILS_EXCEEDED): past a daily email limit"):n.writeCheck.verdict!=="refused"&&s!==void 0&&o.push(` a run of the command would be refused before it writes (${tn}): `+s)}n.writeCheckUnread!==void 0&&o.push(` the records to write could not be counted: ${n.writeCheckUnread}`);for(let i of n.objects){o.push(` ${i.objectApiName} (${i.operation}): ${i.read} read, would insert ${i.insert}, update ${i.update}, delete ${i.delete}, skip ${i.skipped}, refuse ${i.refused}`+(n.direction==="bidirectional"?`, ${i.conflicts} in conflict`:"")),i.alreadyCopied!==void 0&&o.push(` ${i.alreadyCopied} already copied by an earlier run of this configuration, left as they are`),i.alreadyLinked!==void 0&&o.push(` ${Eo(i.alreadyLinked)}`),(i.encryptedLeftOut??[]).length>0&&o.push(` ${Fo(i.encryptedLeftOut??[])}`),i.conflictFields.length>0&&o.push(` differ on: ${i.conflictFields.join(", ")}`),i.files&&o.push(` files: would copy ${i.files.copied}, add ${i.files.versions} version(s), ${i.files.unchanged} unchanged, ${i.files.tooLarge+i.files.pastRunCap} skipped past the caps`);for(let d of i.notes)o.push(` ${d}`);if(i.validationRules&&i.validationRules.length>0){o.push(` ${i.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 d of i.validationRules)o.push(` ${d.name}${d.field?` (${d.field})`:""}: ${d.message||"(no message)"}`)}}n.validationRulesUnread&&o.push(` the target's validation rules could not be listed (${n.validationRulesUnread}): any of them may refuse a record counted as written`);for(let i of Po(n.objects,!0,e))o.push(` ${i}`);return n.cancelled&&o.push(" stopped by a cancel before its last object"),n.error&&o.push(` stopped at ${n.failedObject??"an object"}: ${n.error}`),o}var ji=/^(PARENT_REFUSED|RECORD_TYPE_UNAVAILABLE|RECORD_TYPE_UNMAPPED):/;function $i(n){let t=n.slice(0,3);for(let e of n.slice(3))ji.test(e)&&t.push(e);return t}var Ti={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."},Ii={"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 Ci(n){let t=Pi(n),e=Math.max(0,(n.skipped??0)-t);return`${n.objectApiName}: ${n.processed??0} processed, ${n.success??0} succeeded, ${n.failed??0} failed, ${e} skipped`+(t>0?`, ${t} linked`:"")}function Pi(n){return(n.writtenByThePlatform?.records??0)+(n.linkedToExisting?.records??0)}function Ei(n){let t=[];(n.encryptedLeftOut??[]).length>0&&t.push(Fo(n.encryptedLeftOut??[]));let e=n.linkedToExisting;e&&t.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 r=n.writtenByThePlatform;r&&t.push(`${r.records} record(s) linked to the contact role the platform wrote with their opportunity, for its contact, not written; ${r.given} given the source's fields ${r.given===1?"it":"they"} lacked`+(r.refusal?`, the others left as the platform wrote them (${r.refusal}).`:"."));for(let{records:i,fields:d,reason:c,refusal:a}of n.lookupsLeftOut??[]){let l=c==="notSet"?`${a?` (${a})`:""}.`:"";t.push(`${i} record(s) written without ${d.join(", ")}${Ti[c]}${l}`)}let s=n.lookupsSetAfter;s&&t.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 o=n.writtenWithoutFields;return o&&t.push(`${o.rows} record(s) written again without the fields the target refused them on:`,...o.fields.map(({field:i,rows:d,refusedBy:c="validation-rule",reason:a})=>` ${d} without ${i}: ${Ii[c]}, ${a}`)),t}function Fo(n){return`${n.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 Fi(n){return n?n.neutralized?[`emails and phone numbers: ${n.values} value(s) in ${n.fields.length} field(s) neutralized, addresses under .invalid and numbers fictional, so what the target's automation sends to them reaches no one`,...n.fields.map(({objectApiName:t,field:e,values:r})=>` ${t}.${e} ${r}`),...n.numbersExhausted?[` ${n.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 Ni(n){return(n??[]).map(t=>`${gt(t)}.`)}function Mi(n,t=!1){return[...t?[$t]:[],...Rt(n??[]).map(e=>`${e}.`)]}function xi(n){let t=n.read==="delta"?`delta: ${n.changed} record(s) changed since ${n.since??"the last run"}`:`delta: read whole (${n.reason??"no watermark"}), ${n.changed} record(s)`,e=n.deletionsChecked?`, ${n.deleted} deleted as the source deleted them`+(n.deleteFailed>0?`, ${n.deleteFailed} refused`:""):"",r=n.recorded!==void 0?"; watermark recorded":"; watermark kept as it was: the next run reads from the same point",s=(n.lookupsOwed??0)>0?`, ${n.lookupsOwed} record(s) left without a lookup this run was to set among them`:"";return`${t}${e}${r}${s}`}function Li(n){let t=new Map,e=new Tr,r=new Map,s=new Set,o,i,d,c=a=>{if(a<=0)return;let l=new Date().toISOString();i??=l,d=l};return{runId:n,sending:(a,l)=>c(l),writing:(a,l)=>c(l),answered:()=>{d=new Date().toISOString()},note:(a,l)=>{if(l.length===0)return;let f=l.filter(y=>{let m=y.slice(0,15);return s.has(m)?!1:(s.add(m),!0)});f.length>0&&t.set(a,[...t.get(a)??[],...f]),o=new Date().toISOString(),i??=o,d=o},touched:(a,l)=>{l<=0||(o=new Date().toISOString(),d=o)},overwriting:(a,l,f)=>{f.length!==0&&(e.candidates(a,l,f),c(f.length))},overwrote:(a,l)=>{e.answer(a,l),d=new Date().toISOString()},deleted:(a,l)=>{if(l.length===0)return;let f=r.get(a)??new Map;for(let y of l)f.has(y.slice(0,15))||f.set(y.slice(0,15),y);r.set(a,f),c(l.length)},overwrittenCount:()=>e.count,flush:async()=>{},created:()=>[...t].map(([a,l])=>({objectApiName:a,ids:[...l]})),lastWrittenAt:()=>o,firstWrittenAt:()=>i,lastWriteAt:()=>d,overwritten:()=>e.read(),deletions:()=>[...r].map(([a,l])=>({objectApiName:a,ids:[...l.values()]}))}}function Wi(n,t){return t?{runId:n.runId,note:(e,r,s)=>{n.note(e,r,s),t.note(e,r,s)},noteUnanswered:(e,r)=>{n.note(e,r),t.noteUnanswered?t.noteUnanswered(e,r):t.note(e,r)},sending:(e,r,s)=>{n.sending?.(e,r,s),t.sending?.(e,r,s)},answered:(e,r)=>{n.answered?.(e,r),t.answered?.(e,r)},writing:(e,r)=>{n.writing?.(e,r),t.writing?.(e,r)},touched:(e,r)=>{n.touched?.(e,r),t.touched?.(e,r)},overwriting:(e,r,s,o)=>{n.overwriting?.(e,r,s),t.overwriting?.(e,r,s,o)},overwrote:(e,r)=>{n.overwrote?.(e,r),t.overwrote?.(e,r)},deleted:(e,r)=>{n.deleted?.(e,r),t.deleted?.(e,r)},checkpoint:e=>{n.checkpoint?.(e),t.checkpoint?.(e)},overwrittenCount:()=>n.overwrittenCount?.()??t.overwrittenCount?.()??0,flush:async()=>await n.flush()??await t.flush()}:n}var vn="sandforge-sync";function Di(n,t){let e=new Set(t);return{...n,objectsRead:n.objectsRead.filter(r=>e.has(r)),objects:n.objects.filter(r=>e.has(r.objectApiName))}}async function _i(n){try{let e=(await n.query("SELECT Id FROM Organization LIMIT 1")).records[0]?.Id;return typeof e=="string"?e:void 0}catch{return}}async function Bi(n=process.argv){if(n.slice(2).includes("--remove"))return oa(n);let t=Date.now(),e=mi(n),r=u=>{e.json||process.stdout.write(`${u}
271
- `)},s=u=>{process[e.json?"stderr":"stdout"].write(`${u}
272
- `)},o,i;if(e.configFile!==void 0&&e.store!==void 0){let u;try{u=it(e.configFile,"utf8")}catch(_){process.stderr.write(`--config-file ${e.configFile} cannot be read: ${_ instanceof Error?_.message:String(_)}
273
- `),process.exit(2)}let g=wi(u,e);"refusal"in g&&(process.stderr.write(`--config-file ${e.configFile} ${g.refusal}
274
- `),process.exit(2));let T=ct(g.config.objects);T.length>0&&(process.stderr.write(`--config-file ${e.configFile}: ${ut(T)} Nothing was read or written.
275
- `),process.exit(1)),o=g.config,i=Io(e.store),i.save(o)}else o=yi(e);r(`sandforge sync ${e.source} -> ${e.target}`),r(`objects: ${o.objects.map(u=>u.objectApiName).join(", ")}`+(i?` (configuration ${o.id}, ${o.mode})`:""));let d=et(await lt(e.source)),c=await lt(e.target),a=et(c),l=[Lt(a)],f=()=>l.reduce((u,g)=>u+g(),0),y=new Map,m=new AbortController,R=e.dryRun?await Xe(a).catch(()=>{}):await Dn(a,e.target,{tool:"sandforge sync",action:"write",readOnly:"--dry-run"}),w=`sandforge-sync-${oi()}`,p=Li(w),S=e.dryRun?void 0:Jt(kt()),A=S?.recorder({runId:w,configId:i?o.id:vn,configName:i?o.name:vn,sourceOrgId:e.source,targetOrgId:R?.id??e.target,targetAlias:e.target,...R?{targetOrganizationId:R.id}:{}});ss(A,()=>a.identity(),"sandforge sync");let U=!1,x=()=>{let u=S?.pathOf(w);U||u===void 0||(U=!0,s(`run file: ${u} (--remove ${u} takes back what the run creates)`))},h=Wi(p,A),j=A?{...h,note:(u,g,T)=>{x(),h.note(u,g,T)},sending:(u,g,T)=>{x(),h.sending?.(u,g,T)}}:h,E=e.checkpointFirst?ds({module:"sync",operationId:w,request:e.checkpointFirst,session:c,org:as(c,R??await Xe(a)),connect:u=>{let g=et(u);return l.push(Lt(g)),g},journalDir:kt(),say:s,own:{runId:w}}):void 0,I=async u=>{let g=y.get(u);if(g)return g;let T=await a.sobject(u).describe(),_=ln(T);return y.set(u,_),_},k=o.objects.some(u=>u.operation==="update"||u.operation==="upsert"),C=cn(),P;if(!e.dryRun&&k){let u=un(C);u!==void 0&&(process.stderr.write(`${u} What the run would write over could not be kept, so nothing was written.
276
- `),process.exit(1)),P=Ws({runId:w,orgId:e.target,...R?{organizationId:R.id}:{},files:new en(Xt(C)),meta:St(Ye(C,"snapshots.json"))})}let M=async u=>(await Le({query:async g=>a.query(g),queryMore:async g=>a.queryMore(g)},u)).records,q=P?_s({query:M,backup:P,recorder:j,describe:u=>I(u),viewsEncrypted:Qt(M)}):void 0,G=new ro({connection:a,bulkExecutor:new yr,bulkManager:new Zn,retryConfig:{},signal:m.signal,onProgress:(u,g,T)=>r(` ${T}: ${u}/${g}`),log:r,calls:no(j,q)}),ne=!1,Q=async(u,g,T,_,pe)=>{if(e.dryRun)throw new Error(`A dry run writes nothing: ${u} ${g} refused.`);return x(),T.length>0&&(ne=!0),u==="delete"?G.delete(g,T,_):u==="upsert"?G.upsert(g,pe??"Id",T,_):u==="update"?G.update(g,T,_):G.insert(g,T,_)},z=new Date().toISOString(),ae,te,re,B,ce=io(o,async u=>(await a.query(u)).totalSize),oe={readStorage:()=>Br(a),readApiBudget:()=>Ur(a),readAutomation:u=>Ot(a).read(e.target,u),readLimits:()=>Gr(a),readDeliverability:async()=>Ln(R??await Xe(a))?Nr:Mr(a),emails:{target:e.target,accepted:e.acceptEmails,keepsAddresses:o.keepContactPoints===!0,mayMute:!e.muteAutomation},confirmAboveRecords:_r,sentBefore:()=>f()+(e.dryRun?rs:0),...ce?{countTarget:ce}:{},...E?{checkpointFirst:{scope:async(u,g)=>(ae={written:u,running:g},te=await E.scope(ae),te),take:async u=>{if(!ae)throw new Error("its scope was not read");let g=await E.take(ae,u,{signal:m.signal});if(g.taken){re=g.checkpoint,j.checkpoint?.(g.checkpoint);for(let T of ls(g.checkpoint,e.target,e.muteAutomation))s(T)}return g}}}:{}},Re=R?In({orgType:xt({isSandbox:R.sandbox,edition:R.edition}),metadata:{edition:R.edition}}):"production",K,v,L,se=[],fe=[],$=u=>{let g=$o({go:!1,...u});return g.go?u:{code:g.code,message:g.message}},W=(u,g)=>({measure:async T=>{let _=await yn(T,{...oe,readAutomation:u,...g?{mutePlan:g}:{}});v=_.checkpointFailed,L=_.runEmails?.gate.stop;let pe=wn(_,{policy:"refuse",org:e.target});return se=pe.filter(ke=>!hi.has(ke.code)).map(({code:ke,message:Pe})=>({code:ke,message:Pe})),e.dryRun||(fe=pe.map($)),_.check},hold:async T=>{let _=await yn(T,{...oe,readAutomation:u,...g?{mutePlan:g}:{}});K=_.check,r("");for(let N of Co(_.check,e.target))r(N);for(let N of _.checkpoint?rn(_.checkpoint):[])s(N);let pe=await ao(_,{policy:"refuse",org:e.target,orgTier:Re}),[ke,...Pe]=wn(_,{policy:"refuse",org:e.target});return fe=!pe.go&&ke?.code===pe.code?Pe.map($):[],{check:_.check,answer:$o(await uo(_,pe,oe.checkpointFirst))}}}),X=e.muteAutomation&&!e.dryRun?lo(W,oe.readAutomation,async u=>{let g=await bt(async()=>yt(a),u,{writes:bn});for(let T of ze(g.muted,e.target))r(` ${T}`);return g},`sandforge sync ${w}`,{target:e.target}):void 0,V,J,ue=()=>V??=(async()=>{let u=o.objects.map(T=>T.objectApiName),g=await oe.readAutomation(u).catch(T=>({unread:T instanceof Error?T.message:String(T)}));try{let T=await bt(async()=>yt(a),g,{writes:bn});for(let _ of ze(T.muted,e.target))r(_);return J=T,{planned:T}}catch(T){if(!wt(T))throw T;return r(Un(T.refusal)),{refused:T.refusal}}})(),Ie=async u=>{let g=(await ue()).planned?.automation;return g&&u.every(T=>g.objectsRead.includes(T))?Di(g,u):oe.readAutomation(u)},Ce=X?.gate??(e.dryRun&&e.muteAutomation?W(Ie,()=>J?.plan):W(oe.readAutomation)),ie={measure:u=>Ce.measure(u),hold:async u=>{let g=await Ce.hold(u);return g.answer.go&&x(),g}},Ne,je;if(o.files!==void 0){let u=R?Ri(R):!1;je=bi(o,d,a,i?.fileStore(),u),e.dryRun&&je.deleteFromTarget&&(je={...je,deleteFromTarget:async g=>{throw new Error(`A dry run writes nothing: delete ${g} refused.`)}})}let at=new Pt({...e.dryRun?{}:{creations:j},signal:m.signal,...je?{files:je}:{},...i&&e.store!==void 0?{idMap:Sr(Kt(e.store),u=>i.isSaved(u))}:{},...i?{deltaStore:i.deltaStore(),deltaReads:ur({query:async(u,g)=>d.query(u,g),queryMore:async u=>d.queryMore(u)},{query:async u=>a.query(u),queryMore:async u=>a.queryMore(u)},m.signal)}:{},dataSync:new Ys({insert:(u,g,T)=>Q("insert",u,g,T),update:(u,g,T)=>Q("update",u,g,T),upsert:(u,g,T,_)=>Q("upsert",u,T,_,g),delete:(u,g,T)=>Q("delete",u,g,T),describeTargetFields:I}),conflictResolver:new so,fieldMapping:new cr,transformPipeline:new dr,querySource:jo(d),queryTarget:jo(a),maskedSourceFields:Pr(Qt(async u=>(await Le({query:async g=>d.query(g),queryMore:async g=>d.queryMore(g)},u)).records),u=>d.sobject(u).describe()),findInTarget:nr({query:async u=>a.query(u),queryMore:async u=>a.queryMore(u)}),describeTargetFields:I,describeTargetFieldsAgain:async u=>ln(await a.sobject(u).describe()),leaseOfTheGate:()=>X?.lease(),queryTargetRows:M,countSource:Si(d),countPersonAccounts:ki(d),readSourceIds:Oi(d),writeGate:ie,readValidationRules:Wr(async u=>(await Le({query:async g=>a.tooling.query(g),queryMore:async g=>a.tooling.queryMore(g)},u)).records,Lr(a),Dr(a)),currencies:()=>er(async u=>(await d.query(u)).records,async u=>(await a.query(u)).records,{source:async u=>(await d.tooling.query(u)).records,target:async u=>(await a.tooling.query(u)).records}),standardPricebooks:()=>eo(async u=>(await d.query(u)).records,async u=>(await a.query(u)).records),recordTypes:()=>oo({query:async u=>d.query(u),queryMore:async u=>d.queryMore(u)},{query:async u=>a.query(u),queryMore:async u=>a.queryMore(u)})});if(e.dryRun){r(`
277
- simulating\u2026 (DRY-RUN: nothing is written)`);let g={...await at.simulate(o),...te?{checkpoint:te}:{}},{planned:T,refused:_}=e.muteAutomation?await ue():{},pe=v??(te?.refusal?cs(te.refusal):void 0),ke=g.writeCheck?.unwritable??[],Pe=[_,ke.length>0?{code:"SYNC_TARGET_UNWRITABLE",message:co(ke,e.target,g.writeCheck?.heldBack)}:void 0,pe!==void 0?{code:He,message:pe}:void 0,...se,L].filter(ye=>ye!==void 0),N=Date.now()-t;if(e.json){process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",source:e.source,target:e.target,dryRun:!0,simulation:g,...xr(T),...te?{checkpoint:te}:{},apiRequests:On(g.writeCheck?.apiRequests,f()),...qn(Pe),elapsedMs:N},null,2)}
278
- `);return}let Y=(T?.plan?.assign.length??0)>0;for(let ye of Ai(g,e.target,Y,pe,L?.message))r(ye);r(`
279
- done in ${N}ms`);return}r(`
280
- executing\u2026 (REAL)`);let me=S?.pathOf(w),Se,Ve=Wt(u=>{Se=u,process.stderr.write(`
281
- interrupted: the run stops before its next call, and its file keeps what it created (Ctrl-C again ends it at once)
282
- `),m.abort()}),Ze=async()=>{!E||!re||B||(B=await fs(E,re,ne,e.target,s))},de,Me={status:"failure"};try{de=await at.execute(o).finally(async()=>{Ne=await X?.release()}),Ne&&(de={...de,mutedAutomation:Ne}),Me={status:de.status,...de.cancelled?{cancelled:!0}:{}},await Ze()}catch(u){if(P?.close(),await Ze(),!(u instanceof Je))throw await A?.end(Me),me!==void 0&&ot(me)&&process.stderr.write(`the run stopped on an error; what it created is kept in ${me}, and --remove ${me} takes it back
283
- `),u;let g=u.code===Gt,T=g?[]:fe;e.json?(g||process.stderr.write(`${[u,...T].map(pt).join(`
284
- `)}
285
- `),process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",source:e.source,target:e.target,dryRun:!1,refused:{code:u.code,message:u.message},...T.length>0?{alsoRefused:T}:{},...K?{writeCheck:K}:{},...B?{checkpoint:B}:{},apiRequests:On(K?.apiRequests,f()),elapsedMs:Date.now()-t},null,2)}
286
- `)):r(g?`
287
- ${u.message}`:`
288
- ${[u,...T].map(pt).join(`
289
- `)}`),process.exit(g?ft(Se??"SIGINT"):1)}finally{Ve()}await A?.end(Me),P?.close();let dt=await A?.flush();dt!==void 0&&process.stderr.write(`what the run created could not all be written to ${me??"its file"} (${dt}): --remove takes it back from the --json summary
290
- `);let b=Date.now()-t,O=p.created(),F=p.lastWrittenAt(),D=p.firstWrittenAt(),Z=p.lastWriteAt(),ee=p.overwritten(),he=p.deletions(),$e=O.length>0||ee.length>0||he.length>0?R?.id??await _i(a):void 0,ge=me!==void 0&&ot(me)?me:void 0;if(e.json){process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",source:e.source,target:e.target,...$e?{targetOrgId:$e}:{},...i?{configId:o.id}:{},dryRun:e.dryRun,startedAt:z,finishedAt:new Date().toISOString(),result:de,...B?{checkpoint:B}:{},apiRequests:On(K?.apiRequests,f()),created:{runId:p.runId,...F?{lastWrittenAt:F}:{},...D?{firstWrittenAt:D}:{},...Z?{lastWriteAt:Z}:{},...ge?{runFile:ge}:{},objects:O,...ee.length>0?{overwritten:ee}:{},...he.length>0?{deleted:he}:{}},elapsedMs:b},null,2)}
291
- `),Se&&process.exit(ft(Se)),_t(Dt(de.status,e.failOnPartial));return}let xe=de.objectResults??[];r(`
292
- status: ${de.status??"unknown"}`);for(let u of Ne?ze(Ne,e.target):[])r(u);for(let u of xe){r(` ${Ci(u)}`),typeof u.alreadyCopied=="number"&&r(` ${u.alreadyCopied} already copied by an earlier run of this configuration, left as they are`),typeof u.alreadyLinked=="number"&&r(` ${Eo(u.alreadyLinked)}`);for(let _ of $i(u.errors??[]))r(` ${_}`);for(let _ of Ei(u))r(` ${_}`);for(let _ of Ni(u.currenciesReplaced))r(` ${_}`);for(let _ of Mi(u.pricesSettled,u.standardPricebookMatched===!0))r(` ${_}`);let g=u.files;g&&r(` files: ${g.copied??0} copied, ${g.versions??0} version(s) added, ${g.failed??0} failed`);let T=u.delta;T&&r(` ${xi(T)}`)}for(let u of Po(xe,!1))r(` ${u}`);for(let u of Fi(de.contactPoints))r(` ${u}`);let Be=O.reduce((u,g)=>u+g.ids.length,0),Ue=ee.reduce((u,g)=>u+g.ids.length,0);Ue>0&&r(`
293
- wrote over ${Ue} record(s) of ${e.target}, their values from before kept in ${Ye(C,"backups")}: --remove ${ge??"with the --json summary"} gives them back`),Be>0&&r(`
294
- created ${Be} record(s) and file(s) in ${e.target}: `+(ge!==void 0?`--remove ${ge} takes them back`:"run with --json and save the summary to a file, and --remove takes them back from it")),r(`
295
- done in ${b}ms`),Se&&process.exit(ft(Se)),_t(Dt(de.status,e.failOnPartial))}var Et=new Set(["--remove","--target","--include-changed","--accept-automation","--mute-automation","--store","--sweep","--sweep-list",...Ss,"--leave-undeletable","--json"]),Ui=new Set(["--remove","--target","--store"]);function qi(n){let t=n.slice(2);for(let d=0;d<t.length;d++){let c=t[d];if(Ui.has(c)){d++;continue}Et.has(c)||(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 "${c}". Run with --help.
296
- `),process.exit(2))}let e=d=>{let c=t.indexOf(d);return c>=0&&c+1<t.length?t[c+1]:void 0},r=e("--remove"),s=e("--target"),o=e("--store");t.includes("--store")&&(!o||Et.has(o))&&(process.stderr.write(`--store wants the directory the configuration of the run is kept in.
297
- `),process.exit(2)),(!r||!s||Et.has(r)||Et.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.
298
- `),process.exit(2)),t.includes("--sweep")&&t.includes("--sweep-list")&&(process.stderr.write(`--sweep deletes and --sweep-list only lists: give one of them. Run with --help.
299
- `),process.exit(2));let i=ks(t);return"refusal"in i&&(process.stderr.write(`${i.refusal} Run with --help.
300
- `),process.exit(2)),{summaryPath:r,target:s,includeChanged:t.includes("--include-changed"),acceptAutomation:t.includes("--accept-automation"),muteAutomation:t.includes("--mute-automation"),json:t.includes("--json"),...o!==void 0?{store:o}:{},sweep:t.includes("--sweep"),sweepList:t.includes("--sweep-list"),...i,leaveUndeletable:t.includes("--leave-undeletable")}}var Ft=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Gi=H.object({tool:H.literal("sandforge-sync"),source:H.string().min(1),target:H.string().min(1),targetOrgId:H.string().regex(Ft).optional(),configId:H.string().min(1).max(200).optional(),dryRun:H.boolean().optional(),startedAt:H.string().min(1).max(40).optional(),finishedAt:H.string().min(1).max(40).optional(),result:H.object({status:H.enum(["success","partial","failure"])}).loose(),created:H.object({runId:H.string().min(1).max(200),lastWrittenAt:H.string().min(1).max(40).optional(),firstWrittenAt:H.string().min(1).max(40).optional(),lastWriteAt:H.string().min(1).max(40).optional(),objects:H.array(H.object({objectApiName:H.string().regex(Ae),ids:H.array(H.string().regex(Ft))})),overwritten:H.array(H.object({objectApiName:H.string().regex(Ae),backup:Ar,ids:H.array(H.string().regex(Ft))})).optional(),deleted:H.array(H.object({objectApiName:H.string().regex(Ae),ids:H.array(H.string().regex(Ft))})).optional()}).optional()}).loose();function zi(n){let t;try{t=JSON.parse(n)}catch{return{refusal:"is not JSON: save the output of a run printed with --json."}}let e=zn(t,"sandforge-sync");if(e)return{refusal:Hn(e)};let r=Gi.safeParse(t);if(!r.success){let s=r.error.issues[0];return{refusal:`is not the summary of a sandforge sync run (${s.path.join(".")||"summary"}: ${s.message}).`}}return r.data.dryRun===!0?{refusal:"is the summary of a dry run, which wrote nothing: there is nothing to remove."}:r.data.created?{summary:r.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 Hi(n){return/\.json$/i.test(n)?n.replace(/\.json$/i,".removals.json"):`${n}.removals.json`}function Ki(n,t){let e=n.created,r=n.finishedAt??e?.lastWrittenAt??new Date().toISOString();return{runId:e?.runId??"sandforge-sync",configId:n.configId??"sandforge-sync",configName:n.configId??"sandforge-sync",sourceOrgId:n.source,targetOrgId:n.target,startedAt:n.startedAt??r,end:{at:r,status:n.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)}:{},...t?{removal:t}:{}}}function Ji(n,t,e="sandforge sync"){if(t.sandbox||Tn(t.edition))return;let r=t.edition?`IsSandbox false, edition ${t.edition}`:"IsSandbox false, and no edition";return`${n} is a production org (its Organization record says ${r}): ${e} removes records from sandboxes and Developer Edition orgs only. Nothing was deleted.`}function Yi(n,t){let e=r=>[r.deleted>0?`${r.deleted} deleted`:"",r.alreadyGone>0?`${r.alreadyGone} already gone`:"",(r.notVisible??0)>0?`${r.notVisible} not visible`:"",r.keptChanged>0?`${r.keptChanged} kept, changed since the run`:"",r.keptDependents>0?`${r.keptDependents} kept, records that stay depend on them`:"",r.refused>0?`${r.refused} refused`:"",(r.notReached??0)>0?`${r.notReached} not reached`:""].filter(Boolean).join(", ");return[`removal: ${n.toUpperCase()}`,...t.flatMap(r=>[` ${r.objectApiName}: ${e(r)||"nothing"} of ${r.planned}${ys(r)}`,...ws(r),...r.reasons.map(s=>` ${s}`)])]}function Vi(n){return n.flatMap(t=>{let e=[t.keptChanged>0?`${t.keptChanged} left as they are, changed since the run`:"",t.alreadyGone>0?`${t.alreadyGone} no longer in the org`:"",t.refused>0?`${t.refused} refused`:"",t.notKept>0?`${t.notKept} whose values from before are no longer kept (their backup was deleted, or past its retention)`:"",(t.notReached??0)>0?`${t.notReached} not reached`:"",(t.restoredWithout??0)>0?`${t.restoredWithout} given back but for fields the org no longer takes, which keep the run's values`:""].filter(Boolean);return[` ${t.objectApiName}: ${t.restored} of ${t.planned} given back their values from before the run${e.length>0?`; ${e.join(", ")}`:""}`,...t.reasons.map(r=>` ${r}`)]})}function Zi(n){return n.flatMap(t=>{let e=[t.alreadyBack>0?`${t.alreadyBack} back in the org already`:"",t.goneForGood>0?`${t.goneForGood} no longer in the recycle bin, gone for good`:"",t.refused>0?`${t.refused} refused`:"",(t.notReached??0)>0?`${t.notReached} not reached`:""].filter(Boolean);return[` ${t.objectApiName}: ${t.undeleted} of ${t.planned} the run deleted brought back from the recycle bin${e.length>0?`; ${e.join(", ")}`:""}`,...t.reasons.map(r=>` ${r}`)]})}function Qi(n,t){return n===void 0?[]:[...t.readWhole&&t.readWhole.length>0?[`configuration ${n}: its next run reads ${t.readWhole.join(", ")} whole`]:[],...(t.filesForgotten??0)>0?[`configuration ${n}: ${t.filesForgotten} copied file(s) forgotten, copied again by its next run`]:[],...(t.linksForgotten??0)>0?[`configuration ${n}: ${t.linksForgotten} record(s) forgotten, which no later run points a lookup at`]:[]]}var To=3,Xi=/^[A-Za-z0-9][A-Za-z0-9_-]{0,199}$/;function ea(n,t=kt(),e=Or){if(ot(n)){let s;try{s=it(n,"utf8").split(`
301
- `).find(i=>i.trim()!=="")}catch{return}let o;try{o=JSON.parse(s??"")}catch{return}return typeof o=="object"&&o!==null&&"run"in o?ui(n):void 0}if(!Xi.test(n))return;let r=Ye(t,e,`${n}.ndjson`);return ot(r)?r:void 0}function ta(n){let t=sn(n.runUserId),e=ms.safeParse(n.mutedAutomation);return{...t?{runUserId:t}:{},...e.success?{muted:e.data}:{}}}function na(n,t){let e;try{e=it(n.summaryPath,"utf8")}catch(l){process.stderr.write(`--remove ${n.summaryPath} cannot be read: ${l instanceof Error?l.message:String(l)}
302
- `),process.exit(2)}let r=zi(e);"refusal"in r&&(process.stderr.write(`--remove ${n.summaryPath} ${r.refusal}
303
- `),process.exit(2));let{summary:s}=r;s.targetOrgId===void 0&&s.target!==n.target&&(process.stderr.write(`The run wrote to ${s.target}, and what it created is removed from that org only: give --target ${s.target}.
304
- `),process.exit(2));let o=Hi(n.summaryPath),i,d;try{d=it(o,"utf8")}catch(l){l?.code!=="ENOENT"&&(process.stderr.write(`${o} cannot be read: ${l instanceof Error?l.message:String(l)}
305
- `),process.exit(2))}if(d!==void 0){let l;try{l=JSON.parse(d)}catch{l=void 0}let f=l?.runId;i=f===s.created?.runId?jr(l):void 0,f!==s.created?.runId?t(`${o} is of another run: it is not read, and this removal's takes its place`):i||(process.stderr.write(`${o} does not read as what earlier removals did.
306
- `),process.exit(2))}let c=Ki(s,i),a=i??{};return{run:c,...s.configId!==void 0?{configId:s.configId}:{},...s.targetOrgId!==void 0?{targetOrgId:s.targetOrgId}:{},...i?{earlier:i}:{},...ta(s.result),updateRemoval:async l=>{a=l(a);let f=`${o}.${process.pid}.tmp`;di(f,`${JSON.stringify({version:1,runId:c.runId,...a},null,2)}
307
- `),ai(f,o)}}}async function ra(n,t){let e=Jt(ci(n),""),r;try{r=$r(it(n,"utf8"))}catch(i){process.stderr.write(`--remove ${n} cannot be read: ${i instanceof Error?i.message:String(i)}
308
- `),process.exit(2)}r||(process.stderr.write(`--remove ${n} names no run of sandforge sync.
309
- `),process.exit(2)),e.pathOf(r.runId)!==n&&(process.stderr.write(`--remove ${n} is the file of the run ${r.runId} under another name: give it as ${e.pathOf(r.runId)}, where what its removals did is kept beside it.
310
- `),process.exit(2));let s=await e.get(r.runId)??r;s.targetOrganizationId===void 0&&s.targetOrgId!==t.target&&(process.stderr.write(`The run wrote to ${s.targetOrgId}, and what it created is removed from that org only: give --target ${s.targetOrgId}.
311
- `),process.exit(2));let o=sn(s.runUserId);return{run:s,...s.configId!==vn?{configId:s.configId}:{},...s.targetOrganizationId!==void 0?{targetOrgId:s.targetOrganizationId}:{},...s.removal?{earlier:s.removal}:{},updateRemoval:i=>e.updateRemoval(s.runId,i),runs:e,...o?{runUserId:o}:{}}}function sa(n,t){return n.map(({job:e,objectApiName:r,read:s})=>{let o=` Bulk API job ${e} (${r})`;switch(s.state){case"ended":return`${o}: the run's file holds no answer of it; it ended in ${t}, and the ${s.created.length} record(s) it created are removed with the rest`;case"never-closed":return`${o}: never closed, it wrote nothing`;case"running":return`${o}: still running in ${t}: what it creates stays, and the next --remove of the run reads it again`;default:return`${o}: could not be read back (${s.reason}): what it created stays`}})}async function oa(n=process.argv){let t=Date.now(),e=qi(n),r=$=>{process[e.json?"stderr":"stdout"].write(`${$}
312
- `)},s=ea(e.summaryPath),o=s!==void 0?await ra(s,e):na(e,r),{earlier:i}=o,d;e.store!==void 0&&(o.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).
313
- `),process.exit(2)),d=ot(Ye(e.store,"configStore.json"))?Io(e.store):void 0,d?.isSaved(o.configId)||(process.stderr.write(`${e.store} holds no configuration ${o.configId}: give the --store the run was made with.
314
- `),process.exit(2)));let c=o.run;kr(c)&&G({code:Bn,message:`The run is still writing, in process ${c.writer?.pid??"?"}: remove it once it has ended. Nothing was deleted.`});let a,l=($,W,X,V={},J,ue,Ie,Ce)=>{if(e.json){process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",action:"remove",summary:e.summaryPath,target:e.target,includeChanged:e.includeChanged,result:{status:$,planned:X,objects:W,...V,...J?{sweep:J}:{},...a?{sweepListing:a}:{},...ue?{restored:ue}:{},...Ie?{undeleted:Ie}:{},...Ce?{mutedAutomation:Ce}:{}},elapsedMs:Date.now()-t},null,2)}
315
- `);for(let ie of an(W,e))r(ie);return}for(let ie of J?Rs(J):[])r(ie);for(let ie of Yi($,W))r(ie);for(let ie of an(W,e))r(ie);for(let ie of Ie?Zi(Ie):[])r(ie);for(let ie of ue?Vi(ue):[])r(ie);for(let ie of Qi(o.configId,V))r(ie);r(`
316
- done in ${Date.now()-t}ms`)},f=o.runs!==void 0&&(c.jobs??[]).length>0;if(Yt(c).length===0&&Vt(c).length===0&&Zt(c).length===0&&!f&&!e.sweep&&!e.sweepList){let $=i?.undo?.removedAt??i?.restoredAt??i?.undeletedAt;r($!==void 0?`what the run created was removed already, on ${$}`:"The run created nothing: there is nothing of it to remove."),l("success",[],0);return}let y=await lt(e.target),m=et(y),R=await Xe(m),w=e.sweepList?void 0:Ji(e.target,R);if(w&&G({code:"PRODUCTION_TARGET",message:w}),o.targetOrgId!==void 0&&o.targetOrgId.slice(0,15)!==R.id.slice(0,15)&&G({code:_n,message:`${e.target} is not the org the run wrote to (${o.targetOrgId}), and what it created is removed from that org only. Nothing was deleted.`}),f&&o.runs){let $=o.runs,W=await Ts($,c,m,()=>mt(m,"sandforge sync --remove").serverTime());for(let X of sa(W,e.target))r(X);W.some(X=>X.answered)&&(c=await $.get(c.runId)??c)}!c.end&&c.inFlight&&c.inFlight.job===void 0&&r(` the run stopped during a call of ${c.inFlight.rows} ${c.inFlight.objectApiName} row(s): those ${e.target} took are not in its file, and stay; ${on("--sweep-list")} shows what the run's user created in the run's window`);let p=Yt(c),S=async $=>{let W;try{W=await Ot(m).read(e.target,[...new Set([...c.created,...c.overwritten??[]].map(J=>J.objectApiName).filter(J=>!vr.includes(J)))])}catch(J){W={error:J instanceof Error?J.message:String(J)}}let X=mt(m,"sandforge sync --sweep"),V=$s({otherRuns:await js({organizationId:R.id,alias:e.target,span:As(c),own:{runId:c.runId,ids:c.created.flatMap(J=>J.ids)}}),...o.muted?{muted:o.muted}:{},...i?.removalSpans?{removalSpans:i.removalSpans}:{},...i?.madeEarlier?{made:i.madeEarlier}:{},...i?.lateEarlier?{late:i.lateEarlier}:{}});return xs(X,c.created,W,$,c.firstWrittenAt!==void 0?{at:c.firstWrittenAt,...c.lastWriteAt!==void 0?{lastAt:c.lastWriteAt}:{},serverTime:()=>X.serverTime()}:void 0,c.overwritten??[],{...o.runUserId?{runUserId:o.runUserId}:{},ties:V})};if(e.sweepList){let $=await ts(dn(m,"sandforge sync --sweep-list"),await S(),i?.removalSpans??[]);for(let W of vt($,e.target,e,!0))r(W);e.json?process.stdout.write(`${JSON.stringify({tool:"sandforge-sync",action:"sweep-list",summary:e.summaryPath,target:e.target,listing:$,elapsedMs:Date.now()-t},null,2)}
317
- `):r(`
318
- done in ${Date.now()-t}ms`),$.refusal!==void 0&&process.exit(To);return}let A=Vt(c),U,x={kept:[...A],notKept:0};if(A.length>0){let $=cn(),W=un($);if(W!==void 0)r(W);else{U=new en(Xt($));let X=St(Ye($,"snapshots.json"));x=Fr(A,V=>X.get(`backup:${V}`),30)}}r(`sandforge sync --remove ${e.summaryPath} from ${e.target}`);for(let{objectApiName:$,ids:W}of x.kept)r(` ${$}: ${W.length} to give back their values from before the run`);x.notKept>0&&r(` values from before no longer kept (past sandforge.backup.maxAgeDays, or deleted): ${x.notKept} record(s) the run wrote over keep its values`),x.keptUntil!==void 0&&x.kept.length>0&&r(` values from before kept until ${x.keptUntil}, at the default retention`);let h=Zt(c);for(let{objectApiName:$,ids:W}of h)r(` ${$}: ${W.length} the run deleted, as the source had, to bring back from the recycle bin`);for(let{objectApiName:$,ids:W}of p)r(` ${$}: ${W.length} to remove`);p.length===0&&A.length===0&&h.length===0&&r("nothing left of the run to remove"),e.sweep&&r(`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 ${on("--sweep-list")} to see what`);let j=new AbortController,E=Wt(()=>j.abort()),I=i??{},k=e.sweep?ns(dn(m,"sandforge sync --sweep",j.signal),await S(j.signal),{includeChanged:e.includeChanged,removalSpans:I.removalSpans??[],...Os(e),approve:async $=>{a=$,r("");for(let W of vt($,e.target,e))r(W)}}):void 0;await k?.ask();let C=bs(k,a);if(C){a=C,r("");for(let $ of vt(C,e.target,e))r($)}let P=$=>[...new Set($.map(({objectApiName:W})=>W))],M=Nn({bringBack:P(h),giveBack:P(x.kept),setToDraft:wr(P(p)),delete:br(P(p))},k?.takes??[]),q=[...new Set(Object.values(M).flat())];function G($){return process.stderr.write(`${pt($)}
319
- `),e.json&&process.stdout.write(Gn({tool:"sandforge-sync",summary:e.summaryPath,target:e.target,elapsedMs:Date.now()-t},$)),process.exit(1)}let ne=$=>(E(),G($)),Q;if(q.length>0&&!j.signal.aborted){let $=await Ot(m).read(e.target,q,{undeletes:!0});r("");for(let V of Yr($,e.target,M))r(V);if(e.muteAutomation)try{Q=await bt(async()=>yt(m),$,{writes:Mn(M)});for(let V of ze(Q.muted,e.target))r(` ${V}`)}catch(V){if(!wt(V))throw V;ne(V.refusal)}let W=Q?.automation??$,X=Vr(W,e.target,{steps:M,assign:Jr(W,xn(W,M)),mayMute:Q===void 0&&Xr("--mute-automation")});X&&!e.acceptAutomation&&ne({code:"AUTOMATION_NOT_ACCEPTED",message:X})}let z,ae,te=Q?.muted,re=async()=>{!Q?.prepared||j.signal.aborted||(ae=await Q.prepared.acquire(`sandforge sync --remove ${c.runId}`).catch($=>{if(!wt($))throw $;return ne($.refusal)}),te=ae.outcome)},B=mt(m,"sandforge sync --remove"),ce=await Ms(B,c.created),oe;try{z=await Cr({run:c,org:B,includeChanged:e.includeChanged,...vs(k),...o.runUserId?{runUserId:o.runUserId}:{},onUndeletable:ps(e.leaveUndeletable,e.target,$=>{oe=$}),beforeFirstWrite:re,signal:j.signal,...d&&e.store!==void 0?{configs:d,links:Kt(e.store)}:{},...U?{backups:U}:{},undelete:$=>m.soap.undelete($),...o.runs?{earlierRuns:Ir(c,await o.runs.list())}:{},store:{updateRemoval:($,W)=>$!==c.runId&&o.runs?o.runs.updateRemoval($,W):o.updateRemoval(X=>(I=W(X),I))}})}finally{E();let $=k?.made??new Set,W=k?.late??new Set,X=k?.gone??new Set;if(($.size>0||W.size>0||X.size>0)&&await o.updateRemoval(V=>Ls(V,$,W,X)).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.
320
- `)}),ae){te=await ae.release();for(let V of ze(te,e.target))r(V)}}te&&(z={...z,result:{...z.result,mutedAutomation:te}}),z.stoppedForUndeletable&&(oe&&G(oe),process.exit(1));let Re=z.result.status==="cancelled"?{}:await ce.take();for(let $ of[...z.notes,...Re.note?[Re.note]:[]])process.stderr.write(`${$}
321
- `);let K=z.result.objects.some($=>$.deleted+$.alreadyGone>0);o.configId!==void 0&&!d&&K&&process.stderr.write(`The run was of the saved configuration ${o.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 ${es("--store")} with the next removal, or run the configuration full next time.
322
- `);let{readWhole:v,filesForgotten:L}=z.result,se=k?.result(),fe=Rr(z.result.status,se);l(fe,Re.object?[...z.result.objects,Re.object]:z.result.objects,z.planned,{...v?{readWhole:v}:{},...L!==void 0?{filesForgotten:L}:{},...z.linksForgotten!==void 0?{linksForgotten:z.linksForgotten}:{}},se,z.result.restored,z.result.undeleted,te),fe!=="success"&&process.exit(To)}process.argv[1]?.includes("sandforge-sync")&&(hs(),Bi().then(()=>process.exit(process.exitCode??0)).catch(n=>{process.stderr.write(`${n instanceof Error?n.message:String(n)}
323
- `),process.exit(1)}));export{li as a,mi as b,yi as c,wi as d,Io as e,bi as f,Ri as g,jo as h,Si as i,ki as j,Oi as k,$o as l,On as m,Co as n,Po as o,Eo as p,Ai as q,$i as r,Ci as s,Ei as t,Fo as u,Fi as v,Ni as w,Mi as x,xi as y,Li as z,Wi as A,vn as B,Bi as C,qi as D,zi as E,Hi as F,Ki as G,Ji as H,Yi as I,Vi as J,Zi as K,Qi as L,ea as M,sa as N,oa as O};