sandforge 1.80.0 → 1.81.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 (239) hide show
  1. package/bin/sandforge-pipeline.mjs +12 -0
  2. package/lib/{chunk-EMNC6YI4.mjs → chunk-2IB7I3IQ.mjs} +1 -1
  3. package/lib/{chunk-3RZQZHEB.mjs → chunk-2NAIUKVL.mjs} +1 -1
  4. package/lib/{chunk-AEKONPF4.mjs → chunk-2OIRJEYE.mjs} +1 -1
  5. package/lib/{chunk-BV6VTP3J.mjs → chunk-2OZG6GRW.mjs} +1 -1
  6. package/lib/{chunk-JEERQRLW.mjs → chunk-2Z54GB6X.mjs} +1 -1
  7. package/lib/chunk-2ZMGVBLW.mjs +7 -0
  8. package/lib/{chunk-FKG7Q3WH.mjs → chunk-33ZX3A56.mjs} +1 -1
  9. package/lib/{chunk-HLWMJF6Y.mjs → chunk-3AOKLIVE.mjs} +1 -1
  10. package/lib/{chunk-GGD7ON3M.mjs → chunk-3B5H24ZG.mjs} +1 -1
  11. package/lib/chunk-43K2C6H2.mjs +7 -0
  12. package/lib/chunk-4JKR4PTZ.mjs +8 -0
  13. package/lib/chunk-4L7FBOJS.mjs +8 -0
  14. package/lib/chunk-5344TZBT.mjs +11 -0
  15. package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
  16. package/lib/chunk-55LQD3Y3.mjs +7 -0
  17. package/lib/chunk-56MPPWLA.mjs +7 -0
  18. package/lib/chunk-5C5XEVZN.mjs +11 -0
  19. package/lib/chunk-5CKWGZX4.mjs +9 -0
  20. package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
  21. package/lib/{chunk-BKDV4ENO.mjs → chunk-5UT2ZBGF.mjs} +1 -1
  22. package/lib/chunk-5VQNKDFU.mjs +7 -0
  23. package/lib/{chunk-XAMBCQPU.mjs → chunk-5WGA5CZB.mjs} +1 -1
  24. package/lib/chunk-5ZKCLBTN.mjs +474 -0
  25. package/lib/{chunk-UCD54V2M.mjs → chunk-67CC7RAE.mjs} +1 -1
  26. package/lib/{chunk-TSLJUSLW.mjs → chunk-6CDIIFNX.mjs} +1 -1
  27. package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
  28. package/lib/{chunk-FPKYYFM7.mjs → chunk-6FMLW7PH.mjs} +1 -1
  29. package/lib/chunk-6IGEASOF.mjs +7 -0
  30. package/lib/{chunk-XUWL6ZPC.mjs → chunk-6NADW3OI.mjs} +1 -1
  31. package/lib/chunk-6SEDOIO3.mjs +10 -0
  32. package/lib/{chunk-PJ5I73CK.mjs → chunk-742SSN7I.mjs} +1 -1
  33. package/lib/chunk-7DALDJMO.mjs +7 -0
  34. package/lib/chunk-7PK5QDQI.mjs +7 -0
  35. package/lib/chunk-AELFEK3G.mjs +7 -0
  36. package/lib/chunk-AITNZWLB.mjs +9 -0
  37. package/lib/{chunk-2UZPIMUC.mjs → chunk-AJPSGVMD.mjs} +1 -1
  38. package/lib/{chunk-GSKCGQIP.mjs → chunk-BNO5GIJ6.mjs} +1 -1
  39. package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
  40. package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
  41. package/lib/chunk-BZFIOZS3.mjs +156 -0
  42. package/lib/{chunk-J525F5KI.mjs → chunk-C4YGSK6W.mjs} +1 -1
  43. package/lib/chunk-CAFUNR6D.mjs +7 -0
  44. package/lib/chunk-CULAOP3U.mjs +7 -0
  45. package/lib/chunk-D62KWDDT.mjs +7 -0
  46. package/lib/{chunk-OHWNPXWW.mjs → chunk-D7P7DTWL.mjs} +1 -1
  47. package/lib/{chunk-COFG7Q6R.mjs → chunk-DHGPDSXS.mjs} +1 -1
  48. package/lib/{chunk-WU3GLFZO.mjs → chunk-DHIW4IO5.mjs} +1 -1
  49. package/lib/{chunk-6XYKJSGX.mjs → chunk-DMBR24CK.mjs} +1 -1
  50. package/lib/chunk-DPYTG6DM.mjs +48 -0
  51. package/lib/{chunk-BY2HJFFG.mjs → chunk-DQR5NDMI.mjs} +1 -1
  52. package/lib/chunk-DXOXLUZA.mjs +7 -0
  53. package/lib/{chunk-YRQGKDHM.mjs → chunk-E2OBAWSH.mjs} +1 -1
  54. package/lib/chunk-E2YJVSX6.mjs +10 -0
  55. package/lib/{chunk-JWTSEDIQ.mjs → chunk-EAFLDSQ2.mjs} +1 -1
  56. package/lib/{chunk-MILU7WFN.mjs → chunk-EH5YUA5W.mjs} +1 -1
  57. package/lib/{chunk-BGUEWRK2.mjs → chunk-EOSEMFPU.mjs} +1 -1
  58. package/lib/chunk-ETT5GP4P.mjs +13 -0
  59. package/lib/{chunk-MYW5QNGI.mjs → chunk-FDGFUEK3.mjs} +1 -1
  60. package/lib/{chunk-NTFIRZP6.mjs → chunk-FLNLG43R.mjs} +1 -1
  61. package/lib/{chunk-CHYDMRSV.mjs → chunk-FSDO4DJA.mjs} +1 -1
  62. package/lib/{chunk-MJVTDA5Q.mjs → chunk-FSZTXLNW.mjs} +1 -1
  63. package/lib/{chunk-SOU4FRYN.mjs → chunk-FTA5LOVX.mjs} +1 -1
  64. package/lib/chunk-G4VXPS3A.mjs +7 -0
  65. package/lib/chunk-GF247DA7.mjs +7 -0
  66. package/lib/{chunk-BTWDMNN3.mjs → chunk-GK7VEYFM.mjs} +1 -1
  67. package/lib/{chunk-SE4QEZUG.mjs → chunk-GR3NGDVM.mjs} +1 -1
  68. package/lib/{chunk-3TJON4F3.mjs → chunk-GTIXJCGS.mjs} +1 -1
  69. package/lib/{chunk-NZC67CGR.mjs → chunk-GWRKS3AL.mjs} +1 -1
  70. package/lib/{chunk-XLXIPIEW.mjs → chunk-GYKNCYES.mjs} +1 -1
  71. package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
  72. package/lib/{chunk-KDGMAGQR.mjs → chunk-HVC5CYIB.mjs} +1 -1
  73. package/lib/{chunk-WR4Q363I.mjs → chunk-HYBH5PFM.mjs} +1 -1
  74. package/lib/chunk-HYOOJVR6.mjs +7 -0
  75. package/lib/{chunk-5K5VLULK.mjs → chunk-IBURU7T7.mjs} +1 -1
  76. package/lib/chunk-ICIYL45C.mjs +7 -0
  77. package/lib/{chunk-QR3WELJQ.mjs → chunk-IKGHRYCN.mjs} +1 -1
  78. package/lib/chunk-IM2XA6JI.mjs +7 -0
  79. package/lib/{chunk-IWDREM66.mjs → chunk-J6G23RUI.mjs} +1 -1
  80. package/lib/{chunk-2BA2XKAY.mjs → chunk-JU2XEKEO.mjs} +1 -1
  81. package/lib/{chunk-MHMH6MTP.mjs → chunk-K55LH4ZQ.mjs} +1 -1
  82. package/lib/chunk-K5HV4YRO.mjs +7 -0
  83. package/lib/{chunk-M3ROUWDX.mjs → chunk-K77NR3UK.mjs} +1 -1
  84. package/lib/chunk-KE2PGD6C.mjs +7 -0
  85. package/lib/chunk-KGYXLSQ5.mjs +37 -0
  86. package/lib/{chunk-E5AHXLS6.mjs → chunk-KNIRA333.mjs} +1 -1
  87. package/lib/chunk-KOQV4WXC.mjs +8 -0
  88. package/lib/{chunk-L77FJZEP.mjs → chunk-KRNFVAGC.mjs} +1 -1
  89. package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
  90. package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
  91. package/lib/{chunk-IZQZ6ZUF.mjs → chunk-LO527YLT.mjs} +1 -1
  92. package/lib/chunk-MAHZMPMZ.mjs +7 -0
  93. package/lib/{chunk-F6GUDTOB.mjs → chunk-MHW6DV6T.mjs} +1 -1
  94. package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
  95. package/lib/{chunk-FGRG7ANU.mjs → chunk-MKNAZPOT.mjs} +1 -1
  96. package/lib/{chunk-PZPJKATS.mjs → chunk-MNITSYI2.mjs} +8 -8
  97. package/lib/{chunk-OLSGVAIL.mjs → chunk-MO3N5XVV.mjs} +53 -53
  98. package/lib/chunk-MWLFFVQV.mjs +8 -0
  99. package/lib/chunk-N6HHNR6J.mjs +7 -0
  100. package/lib/chunk-N7J6NJQ6.mjs +7 -0
  101. package/lib/chunk-NJ3EOEHS.mjs +9 -0
  102. package/lib/chunk-NWPQF5XR.mjs +7 -0
  103. package/lib/{chunk-IG2MTQRP.mjs → chunk-NWVVCZUK.mjs} +1 -1
  104. package/lib/{chunk-2NBYT7GR.mjs → chunk-O6ADMP36.mjs} +1 -1
  105. package/lib/chunk-O7DAFE6M.mjs +14 -0
  106. package/lib/chunk-OEHVAJAB.mjs +7 -0
  107. package/lib/chunk-OETEC3P7.mjs +7 -0
  108. package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
  109. package/lib/chunk-OIIL4NVI.mjs +7 -0
  110. package/lib/chunk-OMZJ37JI.mjs +15 -0
  111. package/lib/{chunk-CEX3NEZL.mjs → chunk-ONMBSACW.mjs} +1 -1
  112. package/lib/chunk-OQQHNYR7.mjs +272 -0
  113. package/lib/{chunk-SOGQW4IG.mjs → chunk-OU5W7SCB.mjs} +1 -1
  114. package/lib/{chunk-O2HDYYUV.mjs → chunk-OVOLG3AL.mjs} +1 -1
  115. package/lib/{chunk-DYFALGRT.mjs → chunk-OXKZ4Y3B.mjs} +1 -1
  116. package/lib/{chunk-2GTBABKU.mjs → chunk-OZNLOV4U.mjs} +1 -1
  117. package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
  118. package/lib/chunk-PPGDAUEQ.mjs +7 -0
  119. package/lib/{chunk-IGYH7GMA.mjs → chunk-PYUEHBA6.mjs} +1 -1
  120. package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
  121. package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
  122. package/lib/{chunk-BXU6WFMH.mjs → chunk-QXLZINZB.mjs} +1 -1
  123. package/lib/chunk-R2BJWO5N.mjs +20 -0
  124. package/lib/chunk-R6TF26V4.mjs +10 -0
  125. package/lib/{chunk-YKKRIEH4.mjs → chunk-RKALOKAU.mjs} +1 -1
  126. package/lib/chunk-SQGP46QS.mjs +7 -0
  127. package/lib/chunk-SW2NUKQL.mjs +9 -0
  128. package/lib/{chunk-MFG4MUIO.mjs → chunk-T26C576X.mjs} +1 -1
  129. package/lib/{chunk-LKQ5RKIV.mjs → chunk-T3PLRQ2T.mjs} +1 -1
  130. package/lib/chunk-T5VAULLQ.mjs +7 -0
  131. package/lib/{chunk-KYEDBS54.mjs → chunk-TEIBWMJM.mjs} +1 -1
  132. package/lib/chunk-TKQQVB2D.mjs +9 -0
  133. package/lib/{chunk-ELFXJHU7.mjs → chunk-TPHXRHOA.mjs} +1 -1
  134. package/lib/chunk-TQ2TQHTT.mjs +9 -0
  135. package/lib/{chunk-RPI7LRTW.mjs → chunk-TQM2XJ27.mjs} +1 -1
  136. package/lib/{chunk-IOIWJ3DJ.mjs → chunk-UCHAZ4ZU.mjs} +1 -1
  137. package/lib/{chunk-G35N4P7D.mjs → chunk-UIUPPEFB.mjs} +1 -1
  138. package/lib/{chunk-DBB3EMIN.mjs → chunk-UT27HXE7.mjs} +1 -1
  139. package/lib/{chunk-KBJ5VERV.mjs → chunk-UUSLTW5V.mjs} +1 -1
  140. package/lib/chunk-V2QO6KOE.mjs +19 -0
  141. package/lib/chunk-V473C7LY.mjs +7 -0
  142. package/lib/chunk-V4RKM4QZ.mjs +8 -0
  143. package/lib/chunk-VSU74RQ3.mjs +9 -0
  144. package/lib/chunk-VV3B6IC3.mjs +7 -0
  145. package/lib/chunk-W2AAGIZF.mjs +7 -0
  146. package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
  147. package/lib/chunk-WD47PGUS.mjs +10 -0
  148. package/lib/{chunk-HEKAZJRH.mjs → chunk-WEZLXE34.mjs} +1 -1
  149. package/lib/{chunk-W622GUAW.mjs → chunk-WI4HYWV6.mjs} +1 -1
  150. package/lib/{chunk-WA7EYLAQ.mjs → chunk-WM5JI4JI.mjs} +1 -1
  151. package/lib/chunk-WWTXRWNZ.mjs +7 -0
  152. package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
  153. package/lib/{chunk-FXXLX4O6.mjs → chunk-X2ZVSQ54.mjs} +1 -1
  154. package/lib/{chunk-ZVAED4QV.mjs → chunk-XC2QKQT5.mjs} +1 -1
  155. package/lib/chunk-XC54KKKC.mjs +7 -0
  156. package/lib/chunk-XEB6HZ34.mjs +7 -0
  157. package/lib/chunk-XGKSSCW7.mjs +7 -0
  158. package/lib/chunk-XIZ5LMQM.mjs +7 -0
  159. package/lib/{chunk-74Q6DORA.mjs → chunk-Y5ZCPY36.mjs} +1 -1
  160. package/lib/{chunk-UNJA4J37.mjs → chunk-YCSFP6ER.mjs} +4 -4
  161. package/lib/{chunk-X5JYBPXP.mjs → chunk-YHIOS2PU.mjs} +1 -1
  162. package/lib/chunk-YIGFYZQY.mjs +7 -0
  163. package/lib/chunk-YJEXE6HZ.mjs +925 -0
  164. package/lib/{chunk-TTKXMDBN.mjs → chunk-YOGMP72T.mjs} +4 -4
  165. package/lib/chunk-ZRUDYB7O.mjs +7 -0
  166. package/lib/{chunk-CU2INBND.mjs → chunk-ZUA5BNAO.mjs} +1 -1
  167. package/lib/chunk-ZWCRWF7E.mjs +7 -0
  168. package/lib/{chunk-N652NMZ4.mjs → chunk-ZWZXQTAK.mjs} +52 -52
  169. package/lib/sandforge-autopilot.mjs +11 -11
  170. package/lib/sandforge-backup.mjs +63 -32
  171. package/lib/sandforge-checkpoint.mjs +1 -348
  172. package/lib/sandforge-cleanup.mjs +1 -1
  173. package/lib/sandforge-clone.mjs +1 -1
  174. package/lib/sandforge-compare.mjs +1 -1
  175. package/lib/sandforge-dataops.mjs +1 -1
  176. package/lib/sandforge-empty.mjs +11 -11
  177. package/lib/sandforge-env.mjs +104 -104
  178. package/lib/sandforge-frozen.mjs +1 -266
  179. package/lib/sandforge-mcp.mjs +33 -14
  180. package/lib/sandforge-monitor.mjs +1 -1
  181. package/lib/sandforge-pipeline.mjs +88 -0
  182. package/lib/sandforge-seed.mjs +1 -1
  183. package/lib/sandforge-sync.mjs +1 -1
  184. package/lib/sandforge.mjs +6 -6
  185. package/package.json +2 -1
  186. package/lib/chunk-2CNCDM56.mjs +0 -7
  187. package/lib/chunk-3F6Q5E7I.mjs +0 -14
  188. package/lib/chunk-4VS2V6WU.mjs +0 -25
  189. package/lib/chunk-5P4PHJRL.mjs +0 -9
  190. package/lib/chunk-5TC3QB4U.mjs +0 -10
  191. package/lib/chunk-7ABODJ4G.mjs +0 -7
  192. package/lib/chunk-7EGQP6S4.mjs +0 -7
  193. package/lib/chunk-7FFGJWHN.mjs +0 -7
  194. package/lib/chunk-7YDNUBO5.mjs +0 -7
  195. package/lib/chunk-A527W53V.mjs +0 -7
  196. package/lib/chunk-ADOAS63R.mjs +0 -7
  197. package/lib/chunk-B5QQJ4SI.mjs +0 -7
  198. package/lib/chunk-CION3VMZ.mjs +0 -7
  199. package/lib/chunk-CSBS5U5I.mjs +0 -7
  200. package/lib/chunk-DB7RBE5D.mjs +0 -7
  201. package/lib/chunk-E5ZB3LU5.mjs +0 -7
  202. package/lib/chunk-EFR2Y7E4.mjs +0 -7
  203. package/lib/chunk-EHQ3FX6X.mjs +0 -7
  204. package/lib/chunk-EQNW3UC2.mjs +0 -7
  205. package/lib/chunk-F43REJDZ.mjs +0 -10
  206. package/lib/chunk-GSG7WZHM.mjs +0 -7
  207. package/lib/chunk-HOJYWTP7.mjs +0 -20
  208. package/lib/chunk-HS4YRX4J.mjs +0 -7
  209. package/lib/chunk-I7O6C2B5.mjs +0 -8
  210. package/lib/chunk-IFETCRWE.mjs +0 -10
  211. package/lib/chunk-IQXHJEYB.mjs +0 -7
  212. package/lib/chunk-JPUR2CFX.mjs +0 -10
  213. package/lib/chunk-K327QKMD.mjs +0 -7
  214. package/lib/chunk-KRCA6IPH.mjs +0 -8
  215. package/lib/chunk-LPBMBW3O.mjs +0 -13
  216. package/lib/chunk-LWW4U276.mjs +0 -7
  217. package/lib/chunk-MJU2PGZQ.mjs +0 -15
  218. package/lib/chunk-OAZRPP4I.mjs +0 -7
  219. package/lib/chunk-OO6CLPEH.mjs +0 -7
  220. package/lib/chunk-OPXCV2KL.mjs +0 -7
  221. package/lib/chunk-P33PSCXK.mjs +0 -7
  222. package/lib/chunk-Q3DM32KF.mjs +0 -11
  223. package/lib/chunk-QROPNEGY.mjs +0 -14
  224. package/lib/chunk-QWT2C74M.mjs +0 -7
  225. package/lib/chunk-R3X3LV64.mjs +0 -14
  226. package/lib/chunk-RMBPOTD7.mjs +0 -7
  227. package/lib/chunk-SIHORWVK.mjs +0 -7
  228. package/lib/chunk-T62WNR54.mjs +0 -7
  229. package/lib/chunk-TTFDUKUS.mjs +0 -47
  230. package/lib/chunk-VE6XKGGD.mjs +0 -7
  231. package/lib/chunk-VGW4MXXZ.mjs +0 -7
  232. package/lib/chunk-VS7ZXUII.mjs +0 -824
  233. package/lib/chunk-VXQLDM4R.mjs +0 -7
  234. package/lib/chunk-VYXMVJL5.mjs +0 -7
  235. package/lib/chunk-W7U5E5ZL.mjs +0 -9
  236. package/lib/chunk-WXAQ7FK3.mjs +0 -115
  237. package/lib/chunk-YS4G22C2.mjs +0 -7
  238. package/lib/chunk-ZM6OJGIG.mjs +0 -7
  239. package/lib/chunk-ZUTYVST5.mjs +0 -7
@@ -1,20 +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{b as da,c as ca,d as te,e as ln,f as la,g as ua,h as Vt,i as fa,j as pa,l as yr,m as ga,o as ha,p as no,q as oo,r as _e,s as un,t as Ut,u as so,v as ma}from"./chunk-R3X3LV64.mjs";import{G as ia,N as ro,O as aa,i as Qi,l as cn,m as ea,n as ta,o as ra,p as na,v as oa}from"./chunk-ZM6OJGIG.mjs";import{l as sa}from"./chunk-COFG7Q6R.mjs";import{a as ai,b as rn}from"./chunk-XCA5AONB.mjs";import{$a as Vn,Bc as tn,Cc as Kn,Xa as Cs,Ya as Ds,Za as Ms,_a as xs,a as As,ab as $s,b as ft,bb as _s,cb as qs,db as Gs,eb as Ws,g as _n,h as Ps,j as ce,k as js,l as ur,m as Fs,n as at,o as Z,s as qn,uc as $e}from"./chunk-2CNCDM56.mjs";import{a as Zr}from"./chunk-CE6ZDGBB.mjs";import{a as fi,b as pi}from"./chunk-BOGNK4LV.mjs";import{Qa as eo,a as ns,b as os,bb as Hi,hb as Ji,ob as Yi,qb as to,s as qi,tb as Zi,ub as Xi,v as Gi,x as Wi,z as Qn}from"./chunk-4VS2V6WU.mjs";import{a as Bi,b as Xn,c as mr,d as an,i as dn,j as Vi,l as Ui,m as Ki}from"./chunk-KYEDBS54.mjs";import{a as Ys,b as Un,c as Zs,d as Xs,e as Qs,k as si,l as ii}from"./chunk-F43REJDZ.mjs";import{B as Vs,C as Us,J as Ks,N as At,O as Hs,P as en,Q as Js,S as ei,U as ti,V as ri}from"./chunk-JPUR2CFX.mjs";import{c as ni,d as oi}from"./chunk-T63U4OZJ.mjs";import{f as vi,i as Hn,j as on}from"./chunk-G35N4P7D.mjs";import{r as ue,s as fr,t as nn,x as ui,z as pr}from"./chunk-MFG4MUIO.mjs";import{Aa as Ni,Ba as Ci,Ca as Di,D as Jn,K as Yn,L as Oi,O as ki,Oa as Mi,P as Zn,Pa as xi,Q as Ii,Qa as $i,S as hr,T as Si,U as Ai,W as Pi,Za as _i,b as ks,c as Is,e as xe,f as Ss,ka as ji,o as Ye,p as pt,pa as Fi,r as di,ra as Ti,s as ci,sa as Ei,w as li,wa as Li,xa as zi}from"./chunk-VYXMVJL5.mjs";import{q as sn}from"./chunk-AEKONPF4.mjs";import{a as st}from"./chunk-4TLYUZD5.mjs";import{D as Ri,p as gi,r as hi,t as gr,u as mi,v as yi,w as wi,x as bi}from"./chunk-CION3VMZ.mjs";import{b as Xr}from"./chunk-WIO4XO4F.mjs";import{a as Es}from"./chunk-EADHKH3A.mjs";import{b as Ls,c as St,e as Gn,g as zs,h as Wn,i as Ns,j as Bn}from"./chunk-GCOB7K5N.mjs";import{i as Ts}from"./chunk-INIT2UKJ.mjs";import{h as Bs}from"./chunk-L77FJZEP.mjs";import{D as ps,E as kt,F as it,H as xn,K as gs,L as hs,M as ms,X as $n,Y as ys,_ as ws,a as lr,b as De,c as _t,ca as It,d as Jr,da as bs,e as qt,f as ss,fa as Rs,ga as vs,ha as Os,ia as Wt,j as is,ja as Bt,k as Dn,l as as,m as ds,n as cs,o as ls,p as Le,q as Fe,r as Yr,s as Mn,t as us,u as Gt,y as fs}from"./chunk-A527W53V.mjs";import{a as Pe,h as de}from"./chunk-TZE3Y7IQ.mjs";import{b as Qr}from"./chunk-UNDIBZWG.mjs";import{b as K}from"./chunk-CA5NAXSU.mjs";import{$b as Xo,Cb as xt,Fb as qr,Hb as Je,Ib as Gr,Jb as Ot,Kb as dr,Lb as Wr,Ob as Ne,Pb as Ce,Pc as ts,Qb as Br,Rb as ve,Sb as Vr,Tb as Yo,Ub as Zo,Vb as Ur,Wc as rs,Yc as cr,ec as Qo,ed as $t,fd as Hr,ic as es,jc as Kr,r as Jo}from"./chunk-TTFDUKUS.mjs";import{b as je,e as Bo,f as Vo,k as vt,l as ot,s as Uo,u as Ko,v as Ho,z as Cn}from"./chunk-7EANH5PY.mjs";var ze=class extends Error{constructor(t,r,n={}){super(r);this.code=t;this.params=n;this.name="LoadGuardError"}code;params};function Kt(s){return s.objects.reduce((e,t)=>e+t.records.length,0)}async function ya(s){if(s.orgTier==="staging")throw new ze("non-sandbox",`Refusing frozen-dataset load on ${s.orgId}: it is a sandbox marked Staging, which holds real data, and a load never goes into one. Remediation: pick another sandbox, or, if this one holds no real data, untick Staging in its Edit dialog on the Organizations page.`,{orgId:s.orgId,tier:s.orgTier});if(s.orgTier!=="development"&&s.orgTier!=="scratch")throw new ze("non-sandbox",`Refusing frozen-dataset load on ${s.orgTier} org ${s.orgId}: loads go into sandboxes and Developer Edition orgs only. Remediation: target a Developer/Scratch sandbox or a Developer Edition org \u2014 deploy the required configuration THERE; never run DML against a shared or source org.`,{orgId:s.orgId,tier:s.orgTier});if(s.protectedOrgIds?.includes(s.orgId))throw new ze("protected-environment",`Refusing frozen-dataset load on protected environment ${s.orgId}: it is listed in the protectedOrgIds configuration. Remediation: pick an unprotected sandbox, or review the protected-environment configuration if this org was retired.`,{orgId:s.orgId});if(s.manifest&&s.manifest.source.orgId===s.orgId)throw new ze("source-is-target",`Refusing frozen-dataset load on ${s.orgId}: this org is the dataset SOURCE (manifest source.orgId). Loading would mix pseudonymized records with their origin. Remediation: target a fresh dev sandbox instead.`,{orgId:s.orgId});if(!await s.mockDetector.areCalloutsMocked(s.orgId))throw new ze("unmocked-callouts",`Refusing frozen-dataset load on ${s.orgId}: unmocked callouts detected. Records under load would trigger real external calls. Remediation: deploy the mock configuration to the TARGET org (e.g. the custom metadata flag read by CustomMetadataCalloutMockDetector), then retry \u2014 never edit data on the source org.`,{orgId:s.orgId});if(Kt(s.dataset)===0)throw new ze("empty-dataset","Refusing frozen-dataset load: the dataset contains zero records. Remediation: re-run the selection/extraction with a coverage matrix that matches the source data, then freeze a new dataset version.")}var wr=class{constructor(e,t){this.orgAccess=e;this.config=t}orgAccess;config;async areCalloutsMocked(e){let t=`SELECT Id FROM ${de(this.config.metadataTypeApiName)} WHERE ${de(this.config.isMockedFieldApiName)} = true LIMIT 1`;try{return(await this.orgAccess.query(e,t)).length>0}catch{return!1}}};var fn=class{constructor(e){this.orgAccess=e}orgAccess;uiApiCache=new Map;async alignObject(e){let t=new Map(e.describe.fields.map(d=>[d.name,d])),r=new Map,n=[],o=[],i=[];for(let d of e.records){let a={},c=e.accountKindOf?.(d.referenceId);for(let[f,l]of Object.entries(d.fields)){if(c!==void 0&&es(Le,f,c))continue;let u=t.get(f);if(!u){this.countRemoval(r,f,"not-in-target");continue}if(!u.createable){this.countRemoval(r,f,"not-createable");continue}if(e.leaveOutEncrypted===!0&&u.type===ei){l!=null&&l!==""&&this.countRemoval(r,f,"may-hold-masks");continue}let p=l;typeof p=="string"&&p!==""&&u.restrictedPicklist===!0&&(u.type==="picklist"||u.type==="multipicklist")&&(p=await this.alignPicklistValue(e,u.name,u.type,d,p,n,o)),a[f]=p}i.push(a)}return{objectApiName:e.objectApiName,alignedRecords:i,removals:[...r.entries()].map(([d,a])=>({objectApiName:e.objectApiName,field:d,reason:a.reason,affectedRecords:a.count})),adjustments:n,missingRequired:this.detectMissingRequired(e,i),uiApiWarnings:o}}detectMissingRequired(e,t){let r=t.filter((a,c)=>!e.linked?.has(e.records[c].referenceId));if(r.length===0)return[];let n=[],o=e.accountKindOf,i=o?e.records.filter(a=>!e.linked?.has(a.referenceId)).map(a=>o(a.referenceId)):[];for(let a of e.describe.fields){let c=o?Kr(Le,a.name):void 0;if(!a.createable||a.nillable&&c===void 0||a.defaultedOnCreate)continue;let f=r.filter((u,p)=>c===void 0||Gt(c,i[p]));if(f.length===0)continue;if(!f.some(u=>{let p=u[a.name];return p!=null&&p!==""})){let u=a.unique?"unique":a.nameField?"name":void 0,p=(a.referenceTo?.length??0)>0,g=(a.picklistValues??[]).filter(h=>h.active).map(h=>h.value);n.push({objectApiName:e.objectApiName,field:a.name,isLookup:p,referenceTo:a.referenceTo??[],...u?{distinct:u}:{},...c?{accountKind:c}:{},...!p&&a.type?{fieldType:a.type}:{},...!p&&g.length>0?{activeValues:g}:{}})}}let d=Ur(e.objectApiName,a=>e.describe.fields.some(c=>c.name===a&&c.createable),a=>r.some(c=>c[a]!==void 0&&c[a]!==null&&c[a]!==""));if(d!==void 0&&!n.some(a=>a.field===d)){let a=e.describe.fields.find(c=>c.name===d)?.type;n.push({objectApiName:e.objectApiName,field:d,isLookup:!1,referenceTo:[],...a?{fieldType:a}:{}})}return n}async alignPicklistValue(e,t,r,n,o,i,d){let a=r==="multipicklist",c=a?o.split(";"):[o],f=e.describe.fields.find(y=>y.name===t),l=new Set((f?.picklistValues??[]).filter(y=>y.active).map(y=>y.value)),u=c.filter(y=>!l.has(y));if(u.length>0){let y=e.ruleFor(e.objectApiName,t);return i.push({objectApiName:e.objectApiName,field:t,referenceId:n.referenceId,value:o,rule:y,scope:"global"}),this.applyRule(y,c,u,a)}let p=e.resolvedRecordTypes.get(n.referenceId);if(!p)return o;let g=await this.uiApiValues(e,p,t,d);if(g===null)return o;let h=c.filter(y=>!g.includes(y));if(h.length===0)return o;let m=e.ruleFor(e.objectApiName,t);return i.push({objectApiName:e.objectApiName,field:t,referenceId:n.referenceId,value:o,rule:m,scope:"record-type"}),this.applyRule(m,c,h,a)}async uiApiValues(e,t,r,n){let o=`${e.orgId}|${e.objectApiName}|${t}|${r}`,i=this.uiApiCache.get(o);if(i!==void 0)return i;try{let d=await this.orgAccess.picklistValues(e.orgId,e.objectApiName,t,r);return this.uiApiCache.set(o,d),d}catch(d){return this.uiApiCache.set(o,null),n.push(`UI API picklist-values read failed for ${e.objectApiName}.${r} (recordType ${t}): ${d instanceof Error?d.message:String(d)}. Record-type assignment gap check skipped for this field.`),null}}applyRule(e,t,r,n){return e.action==="replace"?e.value:n?t.filter(o=>!r.includes(o)).join(";"):""}countRemoval(e,t,r){let n=e.get(t);n?n.count++:e.set(t,{reason:r,count:1})}};var br="Opportunity",Rr="SyncedQuoteId",Gd="OpportunityLineItem",io="QuoteLineItem";function ao(s,e){let t=(d,a)=>{let c=new Map;for(let{referenceId:f,fields:l}of s.get(d)??[]){let u=l[a];typeof u!="string"||u===""||!e(f)||c.set(u,(c.get(u)??0)+1)}return c},r=t(Gd,"OpportunityId"),n=t(io,"QuoteId"),o=new Set((s.get("Quote")??[]).map(d=>d.referenceId)),i=[];for(let{referenceId:d,fields:a}of s.get(br)??[]){let c=a[Rr];if(typeof c!="string"||!o.has(c)||!e(d)||!e(c))continue;let f=r.get(d)??0,l=n.get(c)??0;f>l&&i.push({opportunity:d,quote:c,products:f,lines:l})}return i}function wa(s,e,t=!1){if(s.length===0)return;let r=s.length===1,n=s.reduce((f,l)=>f+l.products,0),o=s.reduce((f,l)=>f+l.lines,0),i=r?"its":"their",d=r?"the quote's":"the quotes'",a=o===0?`none of ${d} lines`:`${o} of ${d} lines`,c=e&&o===0?", which excludedObjects leaves out":"";return{objectApiName:br,count:s.length,note:`${s.length} ${t?"would be ":""}left unsynced with ${i} quote: the load ${t?"would write":"wrote"} ${n} of ${i} products and ${a}${c} \u2014 synced, the platform replaces an opportunity's products with its quote's lines; ${Rr} left empty, the products kept`}}import*as Ht from"node:fs";import*as pn from"node:path";function Wd(s){return`counting-contract.${da(s)}.json`}function vr(s,e,t){return s.assertOutsideRepo(pn.join(e,Wd(t)))}function ba(s,e,t){let r=vr(s,e,t.orgId);return Ht.mkdirSync(pn.dirname(r),{recursive:!0}),Ht.writeFileSync(r,`${JSON.stringify(t,null,2)}
8
- `,"utf8"),r}function gn(s,e){let t=s.assertOutsideRepo(e),r=JSON.parse(Ht.readFileSync(t,"utf8"));if(r.version!==1||typeof r.objects!="object"||r.objects===null)throw new Error(`Invalid counting contract at ${t}: version 1 with objects expected`);return r}function Ra(s,e){if(s.loadStartedAt!==void 0)return s.loadStartedAt===e.startedAt;let t=Date.parse(s.writtenAt),r=Date.parse(e.endedAt);return Number.isFinite(t)&&Number.isFinite(r)&&t>=r}var Ge=class extends Error{constructor(t,r,n){super(t);this.gaps=r;this.recordTypesUntold=n;this.name="LoadConfigError"}gaps;recordTypesUntold},kr=class extends Error{constructor(e){super(e),this.name="LoadRecordsExceededError"}},Jt=class extends Error{constructor(t){let r=t.reduce((n,o)=>n+o.count,0);super(`This reload finds in the target ${r} record(s) that its purge would delete along with what the loads before it created \u2014 ${t.map(n=>`${n.objectApiName} (${n.count}, under ${n.under.join(", ")})`).join("; ")}: the target deletes them with the record they hang from, which the reload does not find again, and the load would then write against records no longer there. Nothing was written. Give the records they hang from identity keys too, so that the reload finds them again, or take the load back first with a removal, then load the dataset again.`);this.found=t;this.name="ReloadTakesAlongError"}found};function Bd(s){return s.perObject.reduce((e,t)=>e+t.toInsert,0)}function Vd(s,e){if(!(e===void 0||s<=e))return`This load would insert ${s} record(s), more than the ${e} it may: nothing was written. The dataset or the target changed since that count was taken: preview the load again, and load with the count it gives.`}var qe=class extends Error{constructor(t,r=!0){super(r?`The load was cancelled ${Na(t,void 0)}`:"The load was cancelled before it created or purged a record: the mapping is left as it was.");this.written=t;this.name="FrozenLoadCancelledError"}written},jt=class extends Error{constructor(t,r,n){super(Ud(t,r,n),{cause:t});this.written=r;this.name="FrozenLoadFailedError",this.mappingKept=n===void 0}written;mappingKept};function Ud(s,e,t){return`${K(s)}
9
- The load failed ${Na(e,t)}`}function Na(s,e){let t=new Map,r=(a,c)=>{c!==0&&t.set(a,(t.get(a)??0)+c)};for(let a of s.placeholders)r(a.placeholderObjectApiName,1);for(let a of s.perObject)r(a.objectApiName,a.inserted);let n=[...t.values()].reduce((a,c)=>a+c,0),o=[...Object.values(s.purge.deleted),...Object.values(s.purge.deactivated)].reduce((a,c)=>a+c,0),i=[...n>0?[`created ${n} record(s) (`+[...t].map(([a,c])=>`${a}: ${c}`).join(", ")+")"]:[],...o>0?[`purged ${o} record(s) that earlier loads created`]:[]].join(" and "),d;return e!==void 0?d=n>0?`The mapping could not be written, and nothing names what it created \u2014 no removal or reload will find it: ${e}`:`The mapping could not be written: ${e}`:d=n>0?"What it created is kept in the mapping: a removal takes it back, and a reload purges it or finds it again.":"What the earlier loads created and it did not purge is still named in the mapping, for a removal or the next reload.",i===""?`before it had written the whole dataset. ${d}`:`after it had ${i}. ${d}`}function Ca(s,e){let t=[];for(let[r,n]of s.givenRules){let o=[],i={};for(let{referenceId:a,fields:c}of s.alignedByObject.get(r)??[]){if(!Xe(c.RecordTypeId)||!e(a))continue;o.push(a);let f=s.withoutRecordType.get(a)??"notRead";i[f]=(i[f]??0)+1}if(o.length===0)continue;let{predicted:d}=n;t.push({given:{objectApiName:r,rows:o.length,why:i,...d?{predicted:d}:{}},rule:n,keys:o})}return t}function Da(s){return{namespacePrefix:s.namespacePrefix,developerName:s.developerName}}function Kd(s){if(!s)return"the user's default record type applies";if(s.kind==="master")return"the target leaves it on Master for that user";let{developerName:e}=s.info;return s.basis==="userDefault"?`the target gives it ${e}, the user's default record type`:`the target gives it ${e}, the only other record type open to the user`}async function Hd(s,e){if(!e.mappingKept())try{await e.keepMapping()}catch(t){return new jt(s,e.written,K(t))}return new jt(s,e.written)}function Ma(s,e,t){let r=t.map(n=>St(n.namespacePrefix,n.developerName));return new Ge(`The dataset's ${s} records name record type "${e}" by its label, which ${r.join(" and ")} share in the source: which one each record had cannot be told, the dataset having been extracted before SandForge kept each record's record type by its name. Extract the dataset again. Nothing was written.`,void 0,{reason:"label",objectApiName:s,name:e,recordTypes:r})}function Jd(s){for(let{objectApiName:e,records:t}of s.objects){let r=s.recordTypes[e]??[];if(!(r.length<2))for(let n of t){let o=n.fields.RecordTypeId;if(typeof o!="string"||o==="")continue;if(n.recordTypeDeveloperName!==void 0){let d=Wn(n.recordTypeDeveloperName,r,Da);if(d&&"found"in d)continue}let i=r.filter(d=>d.name===o);if(i.length>1)return Ma(e,o,i)}}}var xa="Opportunity",mn="placeholder:",lo=class{byObject=new Map;auditDated=new Set;add(e,t,r=!1){let n=this.byObject.get(e)??[];n.push(t),this.byObject.set(e,n),r&&this.auditDated.add(e)}sentAuditDates(e){return this.auditDated.has(e)}list(e=[]){let t=new Map,r=(n,o)=>{t.set(n,[...t.get(n)??[],...o])};for(let{objectApiName:n,referenceIds:o}of e)r(n,o);for(let[n,o]of this.byObject)r(n,o);return[...t].map(([n,o])=>({objectApiName:n,referenceIds:o}))}};function Yd(s){if(s.startsWith(mn))return s.split(":")[1]??"Unknown";let e=s.lastIndexOf("-");return e>0?s.slice(0,e):"Unknown"}function Zd(s){return typeof s=="number"?String(s):typeof s=="boolean"?s?"TRUE":"FALSE":`'${Pe(String(s))}'`}var gt=200;function re(s){return s.slice(0,15)}var Xd=["CreatedDate","LastModifiedDate"],Qd=[["CreatedDate","LastModifiedDate","SystemModstamp"],["SystemModstamp"]];function Pt(s){return typeof s=="string"?Date.parse(s):Number.NaN}function va(s){return s.success||s.errors.some(e=>e.includes("ENTITY_IS_DELETED"))}function Oa(s){if(s.tried===0)return"";let e=s.tried-s.went,t=[s.went>0?`${s.went} went`:"",e>0?`${e} refused again`:""].filter(Boolean);return` \u2014 ${s.tried} refused at first, sent again once the rest had gone: ${t.join(", ")}`}function ka(s,e,t){let r=`Status set to ${e.draft} for the purge, and left there: ${e.status} could not be given back \u2014 ${t}`,n=s.failures.find(o=>o.objectApiName===e.objectApiName&&re(o.recordId)===re(e.id));n?n.errors=[...n.errors,r]:s.failures.push({objectApiName:e.objectApiName,recordId:e.id,errors:[r]})}function co(s,e){let t=(s.notInserted??0)+(e.notInserted??0),r=[s.writtenWithoutFields,e.writtenWithoutFields].reduce((n,o)=>o?Hn(n,o):n,void 0);return{objectApiName:e.objectApiName,fromFiles:s.fromFiles+e.fromFiles,inserted:s.inserted+e.inserted,reused:s.reused+e.reused,skippedDuplicates:[...s.skippedDuplicates,...e.skippedDuplicates],failed:[...s.failed,...e.failed],...r?{writtenWithoutFields:r}:{},...t>0?{notInserted:t}:{}}}function Ia(s){let e=s.filter(r=>r.replacedWith===void 0).map(r=>r.field),t=s.filter(r=>r.replacedWith!==void 0).map(r=>`${r.field} set to "${r.replacedWith}"`);return[...e.length>0?[`without ${e.join(", ")}`]:[],...t.length>0?[`with ${t.join(", ")}`]:[]].join(" and ")}function yn(s,e="inserted"){return s>0?`, ${s} not ${e}: the load was cancelled first`:""}function uo(s,e="inserted"){return s>0?`, ${s} not ${e}: the load failed`:""}function ec(s,e){return s>0?"error":e>0?"stopped":"done"}function Ze(s,e,t,r){return{phase:s,status:"error",progress:e,message:`${t} \u2014 ${K(r)}`}}var Sa={phase:"guards",status:"started",progress:0,message:"Evaluating entry guards"};function hn(s,e){let{phase:t,progress:r,did:n,refused:o,notDone:i,done:d,notes:a=""}=s;return e?{phase:t,status:"error",progress:r,message:`${n}${uo(i,d)}${a} \u2014 ${K(e.cause)}`}:{phase:t,status:ec(o,i),progress:r,message:`${n}${yn(i,d)}${a}`}}var Or={accountNotInDataset:"its person account is not in the dataset",accountNotLoaded:"person account was not loaded (see perObject failures/skips)",noPersonAccounts:"the target org has no person accounts: it holds the account as a business account, which takes the contact as one of its own",businessAccount:"the target holds the account as a business account, which takes the contact as one of its own"};function tc(s){return s.accountReferenceId===""?"Not written: a person account's contact goes in with its account, which the dataset does not hold":"Not written: a person account's contact goes in with its account, which the load did not write"}function rc(s,e){let t=new Map;for(let{accountReferenceId:r,contactReferenceId:n}of s.personContactSidecar??[])e.get(n)===Fe&&t.set(n,r);for(let r of s.objects.find(n=>n.objectApiName===Fe)?.records??[]){if(t.has(r.referenceId)||!Mn(r.fields))continue;let n=r.fields.AccountId;t.set(r.referenceId,typeof n=="string"&&e.get(n)===Le?n:"")}return t}function nc(s){let e=new Set;for(let{accountReferenceId:t}of s.personContactSidecar??[])t!==""&&e.add(t);for(let t of s.objects.find(r=>r.objectApiName===Le)?.records??[]){let r=t.fields.LastName;(Mn(t.fields)||r!=null)&&e.add(t.referenceId)}return e}function wn(s,e,t){let r=s.accountKind;return r===void 0?[...e]:e.filter(n=>Gt(r,t(n.referenceId)))}var Ir=class{constructor(e){this.deps=e;this.config=e.config??{},this.sasGuard=e.sasGuard??new te}deps;config;sasGuard;journal;async gateLoad(e){try{await this.passEntryGuards(e)}catch(o){throw e.onProgress?.(Sa),e.onProgress?.(Ze("guards",2,"Entry guards not passed",o)),o}let t=e.dataset;if(e.pilot)try{t=this.filterPilotScope(e.dataset,e.pilot.rootReferenceId)}catch(o){throw e.onProgress?.({phase:"pilot",status:"started",progress:3,message:"Selecting the root folder"}),e.onProgress?.(Ze("pilot",4,"Root folder not selected",o)),o}let r=Jd(t);if(r)throw e.onProgress?.({phase:"align",status:"started",progress:12,message:"Resolving record types"}),e.onProgress?.(Ze("align",20,"Schema not aligned",r)),r;let n=e.reload===!0&&!e.pilot;return this.consultGuard(e,{orgId:e.orgId,orgTier:e.orgTier,operation:n?"delete":"insert",objectName:e.dataset.objects.filter(o=>o.records.length>0).map(o=>o.objectApiName).join(", "),recordCount:{atMost:Kt(e.dataset)},module:"frozendataset"})}passEntryGuards(e){return ya({orgId:e.orgId,orgTier:e.orgTier,dataset:e.dataset,manifest:e.manifest,mockDetector:this.deps.mockDetector,protectedOrgIds:this.config.protectedOrgIds})}async load(e){let t={};try{return await this.loadKeeping(e,t)}finally{await this.journal?.close().catch(()=>{}),this.journal=void 0}}async loadKeeping(e,t){try{return await this.loadInto(e,t)}catch(r){t.endOpenLine?.(r);let n=t.load;throw r instanceof qe||!n?.wroteSome()?r:await Hd(r,n)}}async planLoad(e){let t=e.now??(()=>new Date),r=d=>e.onProgress?.(d),n=await this.prepare(e,r,{}),o=e.reload&&!e.pilot?await this.planPurge(e.orgId,n.previousLoads,n.mapping):void 0;if(o){let d=await this.foundUnderThePurge(e.orgId,o.residuals,n.mapping,n.refIndex);if(d.length>0)throw new Jt(d)}let i=Pa(n,o,{orgId:e.orgId,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},plannedAt:t().toISOString(),undeletableObjects:this.config.undeletableObjects??{},requiredFieldDefaults:this.config.requiredFieldDefaults??{},excludedObjects:this.config.excludedObjects??[]});return this.withValidationRules(i)}async withValidationRules(e){let t=this.deps.readValidationRules,r=e.perObject.filter(a=>a.toInsert>0).map(a=>a.objectApiName),n=[...new Set([...r,...e.placeholders.map(a=>a.placeholderObjectApiName)])];if(!t||n.length===0)return e;let o=new Map,i=new Map;try{for(let{objectApiName:a,onChangeOnly:c,...f}of await t(n))c?i.set(a,[...i.get(a)??[],f.name]):o.set(a,[...o.get(a)??[],f])}catch(a){return{...e,validationRulesUnread:K(a)}}let d=new Set(r);return{...e,perObject:e.perObject.map(a=>{if(a.toInsert===0)return a;let c=o.get(a.objectApiName)??[],f=i.get(a.objectApiName)??[];return{...a,...c.length>0?{validationRules:c}:{},...f.length>0?{validationRulesOnChange:f}:{}}}),placeholders:e.placeholders.map(a=>{let c=d.has(a.placeholderObjectApiName)?[]:o.get(a.placeholderObjectApiName)??[];return c.length>0?{...a,validationRules:c}:a})}}async prepare(e,t,r){let{orgId:n}=e;t(Sa);try{await this.passEntryGuards(e)}catch(D){throw t(Ze("guards",2,"Entry guards not passed",D)),D}t({phase:"guards",status:"done",progress:2,message:"Entry guards passed"}),t({phase:"mapping",status:"started",progress:2,message:"Reading the mapping of earlier loads"});let o=await this.deps.mappingStore.previousLoads().catch(D=>{throw t(Ze("mapping",3,"Mapping not read",D)),D});t({phase:"mapping",status:"done",progress:3,message:`Mapping read: ${o.length} earlier load(s)`});let i=e.dataset;if(e.pilot){t({phase:"pilot",status:"started",progress:3,message:"Selecting the root folder"});try{i=this.filterPilotScope(e.dataset,e.pilot.rootReferenceId)}catch(x){throw t(Ze("pilot",4,"Root folder not selected",x)),x}let D=i.objects.reduce((x,V)=>x+V.records.length,0);t({phase:"pilot",status:"done",progress:4,message:`Root folder selected: ${D} record(s)`})}let d=Ta(i),a=ac(e.dataset),c=rc(i,d),f=mc(i,d,c),l=ns(f),u=l.flat(),p=new qt,g=new qt(hc),h={...i,objects:i.objects.map(D=>({...D,records:D.records.filter(x=>!p.leaveOut(D.objectApiName,x.referenceId,is(D.objectApiName,x.fields,typeof x.fields.RelationId=="string"?d.get(x.fields.RelationId):void 0))&&!g.leaveOut(D.objectApiName,x.referenceId,x.fields))}))},m=new Map,y=new Set,v=new Set;if(e.reload){t({phase:"reload",status:"started",progress:5,message:"Reusing reference data"}),r.endOpenLine=D=>t(Ze("reload",10,"Reference data not reused",D)),await this.reuseByIdentityKeys(e,h,m,y);for(let D of y)v.add(D);t({phase:"reload",status:"done",progress:10,message:`Reference data: ${y.size} reused`}),r.endOpenLine=void 0}if(h.standardPricebook||Ea(h).length>0){t({phase:"catalog",status:"started",progress:10,message:"Looking up the catalog the target already holds"});let D;try{D=await this.lookUpTheCatalog(n,h,m,y)}catch(x){throw t(Ze("catalog",11,"Catalog not looked up",x)),x}t({phase:"catalog",status:"done",progress:11,message:`Catalog looked up: ${D.join("; ")}`})}t({phase:"align",status:"started",progress:12,message:"Resolving record types"}),r.endOpenLine=D=>t(Ze("align",20,"Schema not aligned",D));let P=[],S=new Map,I=new Map,E=new Map;for(let D of h.objects){let x=[];for(let V of D.records)x.push(await this.resolveRecordType(e,i,D.objectApiName,V,I,P,E));S.set(D.objectApiName,x)}let z=new fn(this.deps.orgAccess),O={objectResults:[],excludedObjects:[],removals:[],adjustments:[],recordTypeIssues:P},w=new Map,R=new Map,k=new Map,j=new Map,N=new Map,$,B=nc(i),H=D=>B.has(D)?$===!1?"personAsBusiness":"person":"business",T=new Map,A=new Map,q=e.writeEncrypted!==!0&&e.manifest?.coverage?.encryptedNotKept===void 0;for(let D of h.objects){let x=D.objectApiName;if(D.records.length===0)continue;let V=D.records.filter(C=>!y.has(C.referenceId)),Oe=(C,ie)=>{O.excludedObjects.push({objectApiName:x,reason:C}),N.set(x,{objectApiName:x,fromFiles:i.objects.find(Se=>Se.objectApiName===x)?.records.length??D.records.length,inserted:0,reused:D.records.length-V.length,skippedDuplicates:[],failed:V.map(Se=>({objectApiName:x,referenceId:Se.referenceId,errors:[ie]}))}),V.length!==0&&t({phase:"align",objectName:x,status:"error",progress:12,message:`Skipped ${x} \u2014 ${C}`})},ke;try{ke=await this.deps.orgAccess.describe(n,x)}catch(C){let ie=`Not present in target org: ${C instanceof Error?C.message:String(C)}. Deploy it to the target, or give the loading user Read on it, then load again; or leave it out of the configuration (excludedObjects) and extract again`;Oe(ie,ie);continue}if(x===Le&&($=ke.fields.some(C=>C.name===Yr)),ke.createable===!1&&V.length>0){Oe(`Not createable in target org: ${V.length} record${V.length===1?"":"s"} of the dataset not loaded. Give the loading user Create on it in a permission set, where the platform lets a user create it; otherwise leave it out of the configuration (excludedObjects) and extract again`,"Not createable in target org: the running user may not insert it");continue}k.set(x,new Set(ke.fields.filter(C=>C.updateable===!1).map(C=>C.name)));let ge=ke.fields.filter(C=>C.lookupFilter!==void 0&&C.createable&&(C.referenceTo?.length??0)>0).map(C=>({field:C.name,referenceTo:[...C.referenceTo??[]]}));ge.length>0&&j.set(x,ge);let Ie=Xr(ke.recordTypeInfos);if(Ie.some(C=>!C.master)){let C=Vi(dn(Ie));A.set(x,{types:Ie,...C?{predicted:C}:{}})}let he=fc(x,ke,this.config);he.length>0&&T.set(x,he),R.set(x,new Set(ke.fields.filter(C=>C.createable&&!C.nillable&&!C.defaultedOnCreate&&(C.referenceTo?.length??0)>0).map(C=>C.name)));let M=await z.alignObject({orgId:n,objectApiName:x,records:S.get(x)??[],describe:ke,resolvedRecordTypes:I,ruleFor:(C,ie)=>this.picklistRuleFor(C,ie),linked:y,...x===Le?{accountKindOf:H}:{},...q?{leaveOutEncrypted:q}:{}});O.objectResults.push(M),O.removals.push(...M.removals),O.adjustments.push(...M.adjustments),w.set(x,M.alignedRecords.map((C,ie)=>({referenceId:(S.get(x)??[])[ie].referenceId,fields:C})))}let J=await this.linkWhatThePlatformKeeps(n,O.objectResults,w,a,m,y,H),F=e.reload?await this.reuseByKeysAsWritten(n,h,O.objectResults,w,a,m,y,H):{linked:[],said:[],leftEmpty:[]};for(let D of[...J.linked,...F.linked])v.add(D);let _=[...J.said,...F.said];t({phase:"align",status:"done",progress:20,message:`Schema aligned${_.length>0?` \u2014 ${_.join("; ")}`:""}`}),r.endOpenLine=void 0;let U=new qt(pc(T));uc(w,R,[p,g,U]);for(let D of O.objectResults){let x=(w.get(D.objectApiName)??[]).filter(V=>!y.has(V.referenceId));D.missingRequired=D.missingRequired.filter(V=>wn(V,x,H).some(Oe=>Xe(Oe.fields[V.field])))}t({phase:"placeholders",status:"started",progress:22,message:"Checking required fields"});let ee=await this.planRequiredFields(e,O.objectResults).catch(D=>{throw t(Ze("placeholders",22,"Required fields not covered",D)),D});return t({phase:"placeholders",status:"done",progress:22,message:"Required fields checked"}),{previousLoads:o,working:i,refIndex:d,personContacts:c,groups:l,groupOrder:u,leftToThePlatform:p,untypedFeedItems:g,heldForExclusions:U,loading:h,mapping:m,reused:y,reusedByKeys:v,ranks:a,recordTypeIssues:P,alignment:O,alignedByObject:w,requiredLookups:R,fixedAtInsert:k,filteredLookups:j,lostObjects:N,targetHasPersonAccounts:$,accountKindOf:H,plans:ee,givenRules:A,withoutRecordType:E,keysLeftEmpty:[...J.leftEmpty,...F.leftEmpty]}}async loadInto(e,t){let r=e.now??(()=>new Date),n=r(),o=b=>e.onProgress?.(b),{orgId:i}=e;this.journal=this.deps.mappingStore.journal?.(n);let d=await this.prepare(e,o,t),{previousLoads:a,working:c,refIndex:f,personContacts:l,groups:u,groupOrder:p,leftToThePlatform:g,untypedFeedItems:h,heldForExclusions:m,mapping:y,reused:v,ranks:P,recordTypeIssues:S,alignment:I,alignedByObject:E,requiredLookups:z,fixedAtInsert:O,lostObjects:w,targetHasPersonAccounts:R,accountKindOf:k,plans:j}=d,N=Vd(Bd(Pa(d,void 0,{orgId:i,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},plannedAt:n.toISOString(),undeletableObjects:this.config.undeletableObjects??{},requiredFieldDefaults:this.config.requiredFieldDefaults??{},excludedObjects:this.config.excludedObjects??[]})),e.maxRecords);if(N)throw new kr(N);let $=await this.runUserIdOf(i);$&&this.journal?.writtenAs($);let B={deleted:{},deactivated:{},failures:[]},H=[],T=[],A=new lo,q=new Map,J=[],F=new Set,_,U=new Map,ee=!1,D=async()=>{let b=await this.readWrittenBetween(i,A,y),L=_?.linked??new Map,W=e.pilot?void 0:e.purgeSweep?.stillToSweep?.();await this.deps.mappingStore.persist(y,{created:A.list(J),startedAt:n,...b?{writtenBetween:b}:{},earlier:{settled:[...F],...W&&W.length>0?{stillToSweep:[...W]}:{}},...L.size>0?{personContacts:Object.fromEntries(L)}:{},...U.size>0?{withTheirRecord:Object.fromEntries(U)}:{},...$?{runUserId:$}:{}}),ee=!0},x=()=>A.list().length>0||Object.keys(B.deleted).length>0||Object.keys(B.deactivated).length>0,V=async()=>{if(!e.signal?.aborted)return;let b=x();throw b&&await D(),new qe({perObject:T,placeholders:H,purge:B},b)};t.load={keepMapping:D,mappingKept:()=>ee,wroteSome:x,written:{perObject:T,placeholders:H,purge:B}};let Oe=[];if(e.reload){let b="",L={residuals:0},W={tried:0,went:0},ne=oe=>{let pe=we=>Object.values(we).reduce((se,X)=>se+X,0);return hn({phase:"reload",progress:24,did:`Purge: ${pe(B.deleted)} deleted, ${pe(B.deactivated)} deactivated, ${B.failures.length} failed`,refused:B.failures.length,notDone:L.residuals,done:"purged",notes:`${Oa(W)}${b}`},oe)};if(!e.pilot){o({phase:"reload",status:"started",progress:23,message:"Purging what earlier loads created"});let oe=await this.planPurge(i,a,y),pe=await this.foundUnderThePurge(i,oe.residuals,y,f);if(pe.length>0){let X=new Jt(pe);throw o(ne({cause:X})),X}J=oe.carried;for(let X of J.flatMap(Y=>Y.referenceIds)){let Y=y.get(X);Y&&F.add(re(Y))}let we=Object.values(oe.leftUnrecorded).reduce((X,Y)=>X+Y,0);we>0&&(B.leftUnrecorded=oe.leftUnrecorded,b=` \u2014 ${we} record(s) left in place of a load recorded before loads kept what they created: it may have linked them`);let se=Object.entries(oe.keptByThePlatform);se.length>0&&(B.keptByThePlatform=oe.keptByThePlatform,b+=" \u2014 kept, the platform does not delete them: "+se.map(([X,Y])=>`${X} (${Y})`).join(", "));try{e.purgeSweep&&(await V(),await e.purgeSweep.first()),await this.purgeResiduals(e,oe,[...p].reverse(),B,V,F,L,W),e.purgeSweep&&!e.signal?.aborted&&await e.purgeSweep.afterPurge()}catch(X){throw o(ne(X instanceof qe?void 0:{cause:X})),X}for(let X of a)if(!X.created)for(let Y of X.mapping.values())F.add(re(Y));o(L.residuals>0||B.failures.length>0?ne():{phase:"reload",status:"done",progress:24,message:`Reload pass done${Oa(W)}${b}`})}}let ke=b=>(E.get(b)??[]).filter(L=>!v.has(L.referenceId)),ge=j.filter(b=>b.kind==="placeholder").length,Ie=b=>hn({phase:"placeholders",progress:25,did:`Placeholders: ${H.length} created`,refused:0,notDone:ge-H.length,done:"created"},b);ge>0&&(await V(),o({phase:"placeholders",status:"started",progress:24,message:"Creating placeholders"}));try{for(let b of j)b.kind==="placeholder"?(await V(),await this.createPlaceholder(e,b,ke(b.missing.objectApiName),y,H,A)):this.applyScalarDefault(b.missing,wn(b.missing,ke(b.missing.objectApiName),k),Oe,P)}catch(b){throw o(Ie(b instanceof qe?void 0:{cause:b})),b}ge>0&&o(Ie());let he=u.flatMap(b=>b.length>1?os(b,yc(E,z,f,l)):b),M=[],C=[],ie=this.config.duplicateErrorPatterns??ga,Se=new Set(he.includes(_t)?(E.get(_t)??[]).map(b=>b.referenceId):[]),Te=[],Qe=null,et=0,nr=!1,Ee=b=>b===De&&Te.length>0?`, ${Te.length} on a case waiting for ${Te.length===1?"its task":"their tasks"}`:"",tt=new Set,or=async()=>{if(_)return _;let b=await this.linkPersonContacts(i,l,y,v,R,S);for(let L of b.linked.keys())v.add(L);return tt=new Set(b.unlinked.map(L=>L.contactReferenceId).filter(L=>!v.has(L))),_=b,b},rt=b=>{if(b.objectApiName!==Fe||!_)return b;let L=_.unlinked.filter(W=>tt.has(W.contactReferenceId));return L.length===0?b:{...b,failed:[...b.failed,...L.map(W=>({objectApiName:Fe,referenceId:W.contactReferenceId,errors:[tc(W)]}))]}},sr=()=>{if(_)for(let[b,L]of _.own)y.has(b)||(_.own.delete(b),_.unlinked.push({accountReferenceId:L.accountReferenceId,contactReferenceId:b,cause:"target-not-loaded",detail:`contact ${b} was not loaded (skipped, failed or excluded)`}))},Ue=()=>{let b=_?.linked.size??0,L=_?.own.size??0,W=tt.size;return[...b>0?[`${b} linked to the contact the platform wrote with ${b===1?"its":"their"} person account`]:[],...L>0?[`${L} sent as ${L===1?"a contact of its own":"contacts of their own"}: the target holds ${L===1?"its":"their"} account as a business account`]:[],...W>0?[`${W} not written: a person account's contact goes in with its account`]:[]]},mt=(b,L)=>[...b===Fe?Ue():[],...L?[L]:[],...g.counts(b).map(({why:W,count:ne})=>ss(ne,W)),...h.counts(b).map(({why:W,count:ne})=>Fa(ne,W)),...m.counts(b).map(({why:W,count:ne})=>Ga(ne,W))].map(W=>`, ${W}`).join(""),Lt=(b,L,W,ne,oe)=>{let pe=T.findIndex(ut=>ut.objectApiName===b),we=pe>=0?T[pe]:void 0,se=W.filter(ut=>v.has(ut.referenceId)).length,X=we?.inserted??0,Y=we?.skippedDuplicates??[],be=we?.failed??[],Be=we?.writtenWithoutFields,ae=W.length-se-X-Y.length-be.length,Rt=rt({objectApiName:b,fromFiles:L,inserted:X,reused:se,skippedDuplicates:Y,failed:be,...Be?{writtenWithoutFields:Be}:{},...ae>0?{notInserted:ae}:{}});we?T[pe]=Rt:T.push(Rt),o({phase:"insert",objectName:b,status:"error",progress:25+Math.round(55*et/Math.max(he.length,1)),message:`${b}: ${X} inserted, ${Rt.reused} reused, ${Y.length} duplicates skipped, ${Rt.failed.length} failed${Ee(b)}${uo(ae)}${on(Be)}${mt(b,ne)} \u2014 ${K(oe)}`})},yt,dt=(b,L,W)=>{if(b.waiting>0){let se=T.find(X=>X.objectApiName===De);se&&(se.notInserted=(se.notInserted??0)+b.waiting)}let ne=L==="cancel"&&b.waiting>0,oe="";ne?oe=yn(b.waiting):b.waiting>0&&(oe=uo(b.waiting));let pe=b.status;W?pe="error":ne&&b.status!=="error"&&(pe="stopped");let we=W?` \u2014 ${K(W.cause)}`:"";o({phase:"insert",objectName:De,status:pe,progress:25+Math.round(55*et/Math.max(he.length,1)),message:`${b.message}${oe}${b.notes}${we}`})},xr=async()=>{let b=Qe;b&&e.signal?.aborted&&(Qe=null,dt(b,"cancel")),await V()};t.endOpenLine=b=>{let L=yt;yt=void 0,L&&!(b instanceof qe)&&L(b);let W=Qe;Qe=null,W&&dt(W,b instanceof qe?"cancel":"failure")};let zt=async()=>{nr=!0;let b=Te.splice(0,Te.length),L=Qe;if(Qe=null,b.length===0)return;let W=25+Math.round(55*et/Math.max(he.length,1)),ne;try{await V()}catch(Y){throw L&&dt(L,Y instanceof qe?"cancel":"failure"),Y}let oe=Y=>`${Y.inserted} inserted, ${Y.reused} reused, ${Y.skippedDuplicates.length} duplicates skipped, ${Y.failed.length} failed${yn(Y.notInserted??0)}${on(Y.writtenWithoutFields)}`,pe=Y=>{let be=T.findIndex(Be=>Be.objectApiName===De);be>=0?T[be]=co(T[be],Y):T.push(Y)},we={};try{ne=await this.insertObject(e,De,0,b,f,y,v,M,ie,A,q,Aa(T),Y=>{we.result=Y})}catch(Y){let be=we.result;if(be&&pe(be),L&&be){let Be=be.inserted+be.skippedDuplicates.length+be.failed.length;dt({...L,waiting:Math.max(L.waiting-Be,0),message:`${L.message}; after their task: ${oe(be)}`},"failure",{cause:Y})}else L&&dt(L,"failure",{cause:Y});throw Y}pe(ne);let se=oe(ne),X="done";ne.failed.length>0||L?.status==="error"?X="error":(ne.notInserted??0)>0&&(X="stopped"),o({phase:"insert",objectName:De,status:X,progress:W,message:L?`${L.message}; after their task: ${se}${L.notes}`:`${De} after their task: ${se}`})};for(let b of he){await xr();let L=E.get(b);if(!L){let Q=w.get(b);if(Q&&b===Fe&&l.size>0){try{await or()}catch(Re){throw o({phase:"insert",objectName:b,status:"error",progress:25+Math.round(55*et/Math.max(he.length,1)),message:`${b}: person accounts' contacts not linked \u2014 ${K(Re)}`}),Re}sr();let me=_?.linked??new Map,ye=Q.failed.filter(Re=>!me.has(Re.referenceId));T.push({...Q,reused:Q.reused+Q.failed.length-ye.length,failed:ye})}else Q&&T.push(Q);continue}et++,o({phase:"insert",objectName:b,status:"started",progress:25+Math.round(55*et/Math.max(he.length,1)),message:`Inserting ${b}`});let W,ne=c.objects.find(Q=>Q.objectApiName===b)?.records.length??L.length,oe=L;if(yt=Q=>Lt(b,ne,oe,W,Q),b===Fe&&l.size>0){let Q=await or();oe=L.filter(me=>!tt.has(me.referenceId));for(let me of oe){let ye=Q.own.get(me.referenceId),Re=me.fields.AccountId;ye&&(Re==null||Re==="")&&(me.fields.AccountId=ye.accountReferenceId)}}b===lr&&await this.matchDirectRelations(i,c,L,y,v,U),b===_t&&await this.matchTasksWrittenWithEmails(i,c,L,y,v,U),$n[b]!==void 0&&(W=await this.matchActivityRelations(e,b,L,y,v,O.get(b)??new Set));let pe=0;if(b===kt){let Q=await this.matchContactRolesWrittenWithOpportunities(e,{working:c,aligned:L,refIndex:f,mapping:y,reused:v,withTheirRecord:U,pendingFk:M,fixedAtInsert:O.get(b)??new Set});pe=Q.linked,W=Q.note}let we=It[b],se=we?await this.startAsDrafts(i,b,we,oe,C):oe;if(b===De&&!nr&&Se.size>0){let Q=me=>cs(me,ye=>f.get(ye))&&Se.has(String(me.ActivityId));Te.push(...se.filter(me=>Q(me.fields))),se=se.filter(me=>!Q(me.fields))}let X=se.filter(Q=>!v.has(Q.referenceId)).length,Y=e.signal?.aborted===!0&&X>0,be=(Q,me,ye=Re=>T.push(Re))=>this.insertObject(e,b,me,Q,f,y,v,M,ie,A,q,Aa(T),ye),Be=c.standardPricebook,ae;if(Y)ae={objectApiName:b,fromFiles:ne,inserted:0,reused:se.length-X,skippedDuplicates:[],failed:[],notInserted:X};else if(Wr(b)&&Be){let Q=await be(se.filter(ye=>ye.fields[Ot]===Be),0),me=se.filter(ye=>ye.fields[Ot]!==Be);if(e.signal?.aborted){let ye=me.filter(qd=>v.has(qd.referenceId)).length,Re={...Q,fromFiles:ne,reused:Q.reused+ye},Mt=se.length-Re.inserted-Re.reused-Re.skippedDuplicates.length-Re.failed.length;ae={...Re,...Mt>0?{notInserted:Mt}:{}}}else{let ye={},Re=await be(me,ne,Mt=>{ye.result=Mt}).catch(Mt=>{throw T.push(ye.result?co(Q,ye.result):{...Q,fromFiles:ne}),Mt});ae=co(Q,Re)}}else ae=await be(se,ne);yt=void 0,b===Fe&&sr(),ae=rt(ae),pe>0&&(ae={...ae,writtenByThePlatform:pe});let Rt=b===De?Te.filter(Q=>!v.has(Q.referenceId)).length:0;(ae.notInserted??0)>0&&(ae.notInserted=(ae.notInserted??0)+Rt);let ut=ae.notInserted??0;T.push(ae);let _o=mt(b,W),qo=Ee(b),zn=ae.failed.length>0,Go=zn?"error":"done";!zn&&ut>0&&(Go="stopped");let Wo=25+Math.round(55*et/Math.max(he.length,1)),Nn=`${b}: ${ae.inserted} inserted, ${ae.reused} reused, ${ae.skippedDuplicates.length} duplicates skipped, ${ae.failed.length} failed${qo}${yn(ut)}${on(ae.writtenWithoutFields)}`;qo&&ut===0?(Qe={status:zn?"error":"done",message:Nn,notes:_o,waiting:Rt},o({phase:"insert",objectName:b,status:"started",progress:Wo,message:Nn})):o({phase:"insert",objectName:b,status:Go,progress:Wo,message:`${Nn}${_o}`}),b===_t&&await zt(),ut>0&&await xr()}await zt(),await V(),o({phase:"pass2",status:"started",progress:82,message:"Patching cycle FKs"});let Ae={report:{resolved:0,unresolved:[]},unanswered:0},nt=ao(E,b=>y.has(b)),$r=new Set(nt.map(b=>b.opportunity)),$o=M.filter(b=>b.objectApiName!==br||b.field!==Rr||!$r.has(b.referenceId)),Ke=nt.length>0?`, ${nt.length} synced quote${nt.length===1?"":"s"} left unset`:"",Nt=b=>hn({phase:"pass2",progress:88,did:`Pass 2: ${Ae.report.resolved} resolved, ${Ae.report.unresolved.length} unresolved${Ke}`,refused:Ae.report.unresolved.length,notDone:Ae.unanswered,done:"resolved"},b);try{await this.patchCycleFks(e,$o,y,Ae)}catch(b){throw o(Nt({cause:b})),b}o(Nt());let ir=Ae.report;await V();let He={report:{restored:0,refused:[]},unanswered:0},Ct=b=>hn({phase:"pass2",progress:89,did:`Statuses: ${He.report.restored} applied, ${He.report.refused.length} refused`,refused:He.report.refused.length,notDone:He.unanswered,done:"applied"},b);try{await this.applyDeferredStatuses(e,C,y,He)}catch(b){throw o(Ct({cause:b})),b}let ct=He.report;ct.restored+ct.refused.length+He.unanswered>0&&o(Ct()),await V();let Me=await or(),wt={restored:Me.linked.size,sent:[...Me.own.values()],unresolved:Me.unlinked};l.size>0&&o({phase:"personcontact",status:Me.unlinked.length>0?"error":"done",progress:94,message:`Person contacts: ${Me.linked.size} linked to the contact the platform wrote with their account, ${Me.own.size} sent as contacts of their own, ${Me.unlinked.length} not linked`}),await V(),await e.lease?.giveBack().catch(()=>{}),o({phase:"persist",status:"started",progress:96,message:"Persisting mapping and contract"}),await D();let Dt=g.counts(),ar=h.counts(),bt=m.counts(),_r=this.writeContract(e,c,T,H,{now:r,startedAt:n},new Set(w.keys()),[...Dt.map(({objectApiName:b,count:L})=>({objectApiName:b,count:L,reason:"left-to-the-platform"})),...ar.map(({objectApiName:b,count:L})=>({objectApiName:b,count:L,reason:"untyped-feed-item"})),...bt.map(({objectApiName:b,count:L})=>({objectApiName:b,count:L,reason:"excluded-parent"}))],tt.size,q,ir.unresolved.filter(b=>b.cause==="target-not-loaded"));o({phase:"persist",status:"done",progress:98,message:"Sas artifacts written"});let En=T.some(b=>b.failed.length>0)||ir.unresolved.length>0||wt.unresolved.length>0||ct.refused.length>0||B.failures.length>0,G=new Set(A.list().flatMap(({referenceIds:b})=>b)),lt=await this.readBackRecordTypes(i,Ca(d,b=>G.has(b)),y),Ln={status:En?"completed-with-errors":"completed",orgId:i,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},startedAt:n.toISOString(),durationMs:r().getTime()-n.getTime(),alignment:I,placeholders:H,requiredDefaults:Oe,perObject:T,pass2:ir,personContact:wt,statuses:ct,purge:B,...Dt.length>0?{leftToThePlatform:ln(Dt)}:{},...ar.length>0?{untypedFeedItems:ar.map(({objectApiName:b,why:L,count:W})=>({objectApiName:b,count:W,note:Fa(W,L)}))}:{},...bt.length>0?{heldForExcludedParents:Wa(bt)}:{},...qa(nt,this.config),..._a(d.keysLeftEmpty),...lt.length>0?{recordTypesGiven:lt}:{},...$?{runUserId:$}:{},mappingPath:this.deps.mappingStore.filePath,contractPath:_r};return o({phase:"done",status:Ln.status==="completed"?"done":"error",progress:100,message:`Load ${Ln.status}`}),Ln}async checkGuard(e,t,r,n){await this.consultGuard(e,{orgId:e.orgId,orgTier:e.orgTier,operation:t,objectName:r,recordCount:n,module:"frozendataset"})}async consultGuard(e,t){let{check:r,decision:n}=await tn(this.deps.guard,t);if(e.onGuardDecision?.(n),n==="refused"||n==="declined")throw new ze("guard-refused",`Production guard refused ${t.operation} on ${t.objectName}: ${r.blockedReason??"confirmation declined"}`,{decision:n,...n==="refused"&&r.blockedReason!==void 0?{reason:r.blockedReason}:{}});return n}filterPilotScope(e,t){let r=this.config.rootObjectApiName;if(!r)throw new Ge("Pilot mode requires config.rootObjectApiName (the business-folder root object).");let n=e.objects.find(l=>l.objectApiName===r)?.records??[],o=t??n[0]?.referenceId;if(!o||!n.some(l=>l.referenceId===o))throw new Ge(`Pilot root ${t??"<first>"} not found in ${r} records (${n.length} in dataset). Provide pilot.rootReferenceId of an existing root record.`);let i=Ta(e),d=new Set([o]),a=!0;for(;a;){a=!1;for(let l of e.objects)for(let u of l.records)d.has(u.referenceId)||Object.values(u.fields).some(p=>typeof p=="string"&&d.has(p))&&(d.add(u.referenceId),a=!0)}let c=l=>{for(;l.length>0;){let u=l.pop(),p=bc(e,u);if(p)for(let g of Object.values(p.fields))typeof g=="string"&&i.has(g)&&!d.has(g)&&(d.add(g),l.push(g))}};c([...d]);let f=wc(e,d).filter(l=>!d.has(l));for(let l of f)d.add(l);return c(f),{...e,objects:e.objects.map(l=>({...l,records:l.records.filter(u=>d.has(u.referenceId))})).filter(l=>l.records.length>0)}}async reuseByIdentityKeys(e,t,r,n){for(let[o,i]of Object.entries(this.config.identityKeys??{})){let d=t.objects.find(a=>a.objectApiName===o)?.records??[];for(let[a,c]of await this.findByKeys(e.orgId,o,i,d))r.set(a,c),n.add(a)}}async findByKeys(e,t,r,n){let o=new Map,i=n.filter(f=>r.every(l=>!Xe(f.fields[l])));if(i.length===0)return o;let d=["Id",...r].map(de).join(", "),a=new Map,c=100;for(let f=0;f<i.length;f+=c){let l=i.slice(f,f+c).map(p=>`(${r.map(g=>`${de(g)} = ${Zd(p.fields[g])}`).join(" AND ")})`).join(" OR "),u=`SELECT ${d} FROM ${de(t)} WHERE ${l}`;for(let p of await this.deps.orgAccess.query(e,u))typeof p.Id=="string"&&a.set(La(r.map(g=>p[g])),p.Id)}for(let f of i){let l=a.get(La(r.map(u=>f.fields[u])));l&&o.set(f.referenceId,l)}return o}async linkWhatThePlatformKeeps(e,t,r,n,o,i,d){let a={linked:[],said:[],leftEmpty:[]};for(let[c,f]of Object.entries(yr)){let l=this.config.identityKeys?.[c]??f,u=(r.get(c)??[]).filter(g=>!i.has(g.referenceId));if(u.length===0)continue;let p=await this.linkByKeysAsWritten(e,{objectApiName:c,keyFields:l,records:u,missingRequired:t.find(g=>g.objectApiName===c)?.missingRequired??[],ranks:n,accountKindOf:d},o,i,a);p>0&&a.said.push(`${c}: ${p} found by ${l.join(", ")}, which the platform does not delete`)}return a}async reuseByKeysAsWritten(e,t,r,n,o,i,d,a){let c={linked:[],said:[],leftEmpty:[]};for(let[f,l]of Object.entries(this.config.identityKeys??{})){if(Object.prototype.hasOwnProperty.call(yr,f))continue;let u=new Set((t.objects.find(h=>h.objectApiName===f)?.records??[]).filter(h=>l.some(m=>Xe(h.fields[m]))).map(h=>h.referenceId)),p=(n.get(f)??[]).filter(h=>u.has(h.referenceId)&&!d.has(h.referenceId));if(p.length===0)continue;let g=await this.linkByKeysAsWritten(e,{objectApiName:f,keyFields:l,records:p,missingRequired:r.find(h=>h.objectApiName===f)?.missingRequired??[],ranks:o,accountKindOf:a},i,d,c);g>0&&c.said.push(`${f}: ${g} found by ${l.join(", ")}, as the load writes `+(g===1?"it":"them"))}return c}async linkByKeysAsWritten(e,t,r,n,o){let{objectApiName:i,keyFields:d}=t,a=ic(t,this.config.requiredFieldDefaults??{}),c=a.flatMap(l=>{let u=d.filter(p=>Xe(l.fields[p]));return u.length>0?[u]:[]});if(c.length>0){let l=d.filter(u=>c.some(p=>p.includes(u)));o.leftEmpty.push({objectApiName:i,fields:l,count:c.length}),o.said.push(`${i}: ${c.length} not looked up, ${l.join(", ")} left empty`)}let f=await this.findByKeys(e,i,d,a);for(let[l,u]of f)r.set(l,u),n.add(l),o.linked.push(l);return f.size}async lookUpTheCatalog(e,t,r,n){let o=[],i=t.standardPricebook;if(i){let[c]=await this.deps.orgAccess.query(e,dr);typeof c?.Id=="string"?(r.set(i,c.Id),n.add(i),o.push("standard price book linked")):o.push("standard price book not found")}let d=await this.matchByNaturalKey(e,t,r,n),a=await this.matchSellingModelOptions(e,t,r,n);Ea(t).includes(ve)&&d.push({objectApiName:ve,linked:a});for(let{objectApiName:c,linked:f,notAsked:l}of d)l===void 0&&o.push(`${c}: ${f} linked`);for(let{objectApiName:c,notAsked:f}of d)f!==void 0&&o.push(`${c} not looked up \u2014 ${f}`);return o}async matchByNaturalKey(e,t,r,n){let o=[];for(let[i,d]of Object.entries(Jr)){let a=t.objects.find(u=>u.objectApiName===i)?.records??[];if(a.length===0)continue;let c=a.filter(u=>!r.has(u.referenceId)&&d.every(p=>u.fields[p]!==void 0&&u.fields[p]!=="")),f=[];if(c.length>0)try{f=await Os(u=>this.deps.orgAccess.query(e,u),i,d,c.map(u=>u.fields))}catch(u){o.push({objectApiName:i,linked:0,notAsked:K(u)});continue}let l=0;c.forEach((u,p)=>{let g=f[p];g!==void 0&&(r.set(u.referenceId,g),n.add(u.referenceId),l++)}),o.push({objectApiName:i,linked:l})}return o}async matchSellingModelOptions(e,t,r,n){let o=[];for(let d of t.objects.find(a=>a.objectApiName===ve)?.records??[]){if(r.has(d.referenceId))continue;let a=d.fields[Ne],c=d.fields[Ce],f=typeof a=="string"?r.get(a):void 0,l=typeof c=="string"?r.get(c):void 0;f===void 0||l===void 0||o.push({referenceId:d.referenceId,pair:{[Ne]:f,[Ce]:l}})}if(o.length===0)return 0;let i=await vs(d=>this.deps.orgAccess.query(e,d),o.map(d=>d.pair));for(let[d,a]of i)r.set(o[d].referenceId,a),n.add(o[d].referenceId);return i.size}async planPurge(e,t,r){let n={residuals:new Map,datedBy:new Map,carried:[],leftUnrecorded:{},keptByThePlatform:{}},o=new Map;for(let[g,h]of r)o.has(re(h))||o.set(re(h),g);let i=new Set,d=(g,h)=>{n.residuals.set(g,[...n.residuals.get(g)??[],h])},a=(g,h)=>{let m=n.carried.at(-1);m?.objectApiName===g?m.referenceIds.push(h):n.carried.push({objectApiName:g,referenceIds:[h]})},c=g=>{n.leftUnrecorded[g]=(n.leftUnrecorded[g]??0)+1},f=[],l=t.some(g=>g.created&&!g.writtenBetween)?await this.targetClockAheadMs():Number.NaN,u=t.map(g=>{let h=new Set;if(!g.created)return h;let m=new Set(g.created.flatMap(y=>y.referenceIds));for(let[y,v]of g.mapping)m.has(y)||h.add(re(v));return h}),p=new Set(u.flatMap(g=>[...g]));if(t.forEach((g,h)=>{if(!g.created){for(let[v,P]of g.mapping){let S=re(P);if(o.has(S)||i.has(S))continue;i.add(S);let I=Yd(v);this.mayHaveLinked(I,v)||p.has(S)?c(I):I==="Pricebook2"&&!v.startsWith(mn)?f.push(P):d(I,P)}return}let m=g.writtenBetween?Pt(g.writtenBetween.last):Pt(g.endedAt)+l+Ks,y=new Map(Object.entries(g.removalStamps??{}).map(([v,P])=>[re(v),Pt(P)]));for(let{objectApiName:v,referenceIds:P}of g.created)for(let S of P){let I=g.mapping.get(S);if(I===void 0)continue;let E=re(I);if(u[h].has(E)||i.has(E))continue;i.add(E);let z=o.get(E);if(z!==void 0){a(v,z);continue}if(this.keptByThePlatform(v)){n.keptByThePlatform[v]=(n.keptByThePlatform[v]??0)+1;continue}d(v,I);let O=[m,y.get(E)??Number.NaN].filter(Number.isFinite);O.length>0&&n.datedBy.set(E,Math.max(...O))}}),f.length>0){let g;try{let[h]=await this.deps.orgAccess.query(e,dr);g=typeof h?.Id=="string"?re(h.Id):""}catch{g=void 0}for(let h of f)g===void 0||re(h)===g?c("Pricebook2"):d("Pricebook2",h)}return n}async targetClockAheadMs(){let e=this.deps.serverTime;if(!e)return Number.NaN;let t=Date.now();try{return Pt(await e())-(t+Date.now())/2}catch{return Number.NaN}}async foundUnderThePurge(e,t,r,n){let o=new Set([...t.values()].flat().map(re)),i=new Map;for(let[c,f]of r){let l=n.get(c);l===void 0||o.has(re(f))||i.set(l,[...i.get(l)??[],f])}if(o.size===0||i.size===0)return[];let d=new Map,a=(c,f,l)=>{let u=d.get(c)??{keys:new Set,under:new Set};u.keys.add(re(f)),u.under.add(l),d.set(c,u)};for(let c of t.keys()){let f;try{f=(await this.deps.orgAccess.describe(e,c)).cascadeChildren??[]}catch{continue}for(let{childSObject:l,field:u}of f){let p=i.get(l);if(!p)continue;let g;try{g=await this.readRecords(e,l,[u],p)}catch{for(let h of p)a(l,h,c);continue}for(let h of g){let m=h[u];typeof h.Id!="string"||typeof m!="string"||o.has(re(m))&&a(l,h.Id,c)}}}return[...d].map(([c,{keys:f,under:l}])=>({objectApiName:c,count:f.size,under:[...l]}))}mayHaveLinked(e,t){return t.startsWith(mn)?!1:e==="Unknown"||e===ve||Object.prototype.hasOwnProperty.call(Jr,e)||Object.prototype.hasOwnProperty.call(yr,e)||Object.prototype.hasOwnProperty.call(this.config.identityKeys??{},e)}keptByThePlatform(e){return Object.prototype.hasOwnProperty.call(yr,e)&&this.config.undeletableObjects?.[e]===void 0}async purgeResiduals(e,t,r,n,o,i,d,a){let c=t.residuals,f=[],l=[...c.values()].reduce((S,I)=>S+I.length,0),u=0,p=()=>{d.residuals=l-u},g=async()=>{let S=f.splice(0);S.length>0&&await this.giveStatusesBack(e,S,n)},h=async()=>{e.signal?.aborted&&await g(),await o()},m=r.filter(S=>c.has(S)),y=[...c.keys()].filter(S=>!r.includes(S)).sort(),v=[...m,...y],P=new Set;try{P=await this.residualsInSight(e.orgId,c),await this.draftResiduals(e,t,f,h);for(let S of v){let I=c.get(S)??[],E=this.config.undeletableObjects?.[S];if(E!==void 0){await h(),await this.checkGuard(e,"update",S,I.length);let z=await this.deps.writer.update(e.orgId,S,I.map(O=>({Id:O,[E]:!1})));z.forEach((O,w)=>{O.success?(n.deactivated[S]=(n.deactivated[S]??0)+1,i.add(re(I[w]))):n.failures.push({objectApiName:S,recordId:I[w],errors:O.errors})}),u+=z.length}else{let z=Wr(S)?await this.customPricesFirst(e.orgId,I):S===lr?[await this.withoutDirectRelations(e.orgId,I)]:[I];u+=I.length-z.reduce((O,w)=>O+w.length,0);for(let O of z){if(O.length===0)continue;await h(),await this.checkGuard(e,"delete",S,O.length);let w=await this.deps.writer.delete(e.orgId,S,O);w.forEach((R,k)=>{va(R)?(n.deleted[S]=(n.deleted[S]??0)+1,i.add(re(O[k]))):n.failures.push({objectApiName:S,recordId:O[k],errors:R.errors})}),u+=w.length}}}await this.purgeAgain(e,v,n,i,h,a)}catch(S){throw await g(),p(),S}e.signal?.aborted||await this.settleTakenAlong(e.orgId,n,i,P),await g(),p()}async residualsInSight(e,t){let r=new Set;for(let[n,o]of t)try{for(let i of await this.readRecords(e,n,[],o))typeof i.Id=="string"&&r.add(re(i.Id))}catch{}return r}async purgeAgain(e,t,r,n,o,i){for(let d of t){if(this.config.undeletableObjects?.[d]!==void 0)continue;let a=r.failures.filter(f=>f.objectApiName===d).map(f=>f.recordId);if(a.length===0)continue;let c=Wr(d)?await this.customPricesFirst(e.orgId,a).catch(()=>[a]):[a];for(let f of c){if(f.length===0)continue;await o(),await this.checkGuard(e,"delete",d,f.length),(await this.deps.writer.delete(e.orgId,d,f)).forEach((u,p)=>{let g=r.failures.findIndex(h=>h.objectApiName===d&&h.recordId===f[p]);g<0||(i.tried++,va(u)?(r.failures.splice(g,1),r.deleted[d]=(r.deleted[d]??0)+1,n.add(re(f[p])),i.went++):r.failures[g]={objectApiName:d,recordId:f[p],errors:u.errors})})}}}async settleTakenAlong(e,t,r,n){for(let o of new Set(t.failures.map(i=>i.objectApiName))){let i=t.failures.filter(h=>h.objectApiName===o).map(h=>h.recordId),d=h=>this.readRecords(e,o,[],h),{gone:a,unchecked:c,failure:f}=await Vs(i,d,h=>n.has(re(h))),l=f?`Not checked: not read back once the purge was through, to tell whether a parent deleted after it took it along \u2014 ${f}`:"Not checked: the purge could not read it before its delete, nor after \u2014 gone, or out of the session's sight",u=new Set(c.map(re));for(let h of t.failures)h.objectApiName!==o||!u.has(re(h.recordId))||h.errors.includes(l)||(h.errors=[...h.errors,l]);let p=new Set(a.map(re));if(p.size===0)continue;let g=t.failures.filter(h=>h.objectApiName!==o||!p.has(re(h.recordId)));t.failures.splice(0,t.failures.length,...g),t.deleted[o]=(t.deleted[o]??0)+p.size;for(let h of p)r.add(h)}}async draftResiduals(e,t,r,n){for(let[o,i]of Object.entries(It)){if(bs.has(o))continue;let d=t.residuals.get(o);if(!d||d.length===0)continue;let a=await this.statusCategories(e.orgId,i),c=a?.draft;if(!a||!c)continue;let f;try{f=await this.readRecords(e.orgId,o,["Status","LastModifiedDate"],d)}catch{continue}let l=f.flatMap(u=>{let p=a.categoryOf.get(String(u.Status));if(typeof u.Id!="string"||p===void 0||p==="Draft")return[];let g=t.datedBy.get(re(u.Id))??Number.NaN;return[{objectApiName:o,id:u.Id,draft:c,status:String(u.Status),unchanged:Pt(u.LastModifiedDate)<=g}]});l.length!==0&&(await n(),await this.checkGuard(e,"update",o,l.length),r.push(...l),await this.deps.writer.update(e.orgId,o,l.map(({id:u})=>({Id:u,Status:c}))))}}async giveStatusesBack(e,t,r){let n=this.deps.restoringWriter??this.deps.writer,o=await this.runningUser(e.orgId),i={};for(let d of new Set(t.map(a=>a.objectApiName))){let a=t.filter(p=>p.objectApiName===d),c=new Map(a.map(p=>[re(p.id),p])),f;try{f=await this.readRecords(e.orgId,d,["Status"],a.map(p=>p.id))}catch(p){for(let g of a)ka(r,g,`its status was not read back: ${K(p)}`);continue}let l=f.flatMap(p=>{let g=typeof p.Id=="string"?c.get(re(p.Id)):void 0;return g&&p.Status===g.draft?[g]:[]});for(let p=0;p<l.length;p+=gt){let g=l.slice(p,p+gt),h;try{await this.checkGuard(e,"update",d,g.length),h=await n.update(e.orgId,d,g.map(({id:m,status:y})=>({Id:m,Status:y})))}catch(m){let y=K(m);h=g.map(()=>({success:!1,errors:[y]}))}g.forEach((m,y)=>{let v=h[y];v?.success||ka(r,m,v?.errors.join("; ")||"the org gave no reason")})}let u=l.filter(p=>p.unchanged);if(!(u.length===0||o===void 0))try{let p=await this.readRecords(e.orgId,d,["LastModifiedDate","LastModifiedById"],u.map(g=>g.id));for(let g of p)typeof g.Id=="string"&&typeof g.LastModifiedDate=="string"&&typeof g.LastModifiedById=="string"&&re(g.LastModifiedById)===o&&(i[g.Id]=g.LastModifiedDate)}catch{}}if(Object.keys(i).length!==0)try{await this.deps.mappingStore.recordStamps(i)}catch{}}async runningUser(e){let t=await this.runUserIdOf(e);return t?re(t):void 0}async runUserIdOf(e){let t=this.deps.orgAccess.userId;if(t)try{return await t.call(this.deps.orgAccess,e)||void 0}catch{return}}async readBackRecordTypes(e,t,r){let n=[];for(let{given:o,rule:i,keys:d}of t){let a=d.flatMap(c=>r.get(c)??[]);try{let c=await this.deps.orgAccess.query(e,Ui(o.objectApiName,a));n.push({...o,readBack:Ki(c,i.types)})}catch(c){let f=K(c);n.push({...o,readBack:{read:0,types:[],unread:f}})}}return n}async readRecords(e,t,r,n){let o=["Id",...r].map(de).join(", "),i=[];for(let d=0;d<n.length;d+=gt){let a=n.slice(d,d+gt).map(c=>`'${Pe(c)}'`).join(", ");i.push(...await this.deps.orgAccess.query(e,`SELECT ${o} FROM ${de(t)} WHERE Id IN (${a})`))}return i}async resolveRecordType(e,t,r,n,o,i,d){let a={...n.fields};r===Le&&delete a[Yr];let c=a.RecordTypeId;if(typeof c!="string"||c==="")return"RecordTypeId"in a&&d.set(n.referenceId,"masterInSource"),delete a.RecordTypeId,{referenceId:n.referenceId,fields:a};let f=t.recordTypes[r]??[],l=n.recordTypeDeveloperName===void 0?void 0:Wn(n.recordTypeDeveloperName,f,Da),u=l&&"found"in l?[l.found]:f.filter(m=>m.name===c),p=u[0];if(!p)return delete a.RecordTypeId,d.set(n.referenceId,"dropped"),i.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:c,detail:"RecordType name absent from the dataset recordTypes map \u2014 RecordTypeId dropped"}),{referenceId:n.referenceId,fields:a};if(u.length>1)throw Ma(r,c,u);let g=St(p.namespacePrefix,p.developerName),h=await this.deps.recordTypeResolver.resolveByDeveloperName(e.orgId,r,p.developerName,...p.namespacePrefix!==void 0?[p.namespacePrefix]:[]);if(h!==null&&typeof h=="object"&&"ambiguous"in h)throw new Ge(`The dataset names ${r} record type ${p.developerName} without its namespace \u2014 it was extracted before SandForge read one \u2014 and ${Bn(r,p.developerName,"the target org",h.carriers)}. Extract the dataset again: a dataset extracted now names each record type with its namespace. Nothing was written.`,void 0,{reason:"namespace",objectApiName:r,name:p.developerName,recordTypes:h.carriers.map(m=>St(m.namespacePrefix,m.developerName))});if(h!==null&&typeof h=="object"){let m=await this.deps.recordTypeResolver.givenRecordType?.(e.orgId,r).catch(()=>{});return delete a.RecordTypeId,d.set(n.referenceId,"dropped"),i.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:c,detail:`RecordType ${g} is in the target org but not available to the running user \u2014 RecordTypeId dropped, ${Kd(m)}. Assign it to the user's profile or a permission set to keep it.`}),{referenceId:n.referenceId,fields:a}}return h?(a.RecordTypeId=h,o.set(n.referenceId,h),{referenceId:n.referenceId,fields:a}):(delete a.RecordTypeId,d.set(n.referenceId,"dropped"),i.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:c,detail:`RecordType ${g} not found in target org \u2014 RecordTypeId dropped`}),{referenceId:n.referenceId,fields:a})}async planRequiredFields(e,t){let r=[],n=[];for(let o of t)for(let i of o.missingRequired){let d=`${i.objectApiName}.${i.field}`;if(!i.isLookup){if(this.config.requiredFieldDefaults?.[d]===void 0){let l=i.accountKind?` of a ${i.accountKind} account`:"";n.push(`requiredFieldDefaults["${d}"]: ${lc(i)} for this required field${l}`)}else r.push({kind:"default",missing:i});continue}let a=this.config.requiredLookupPlaceholders?.[d];if(!a){n.push(`requiredLookupPlaceholders["${d}"]: a placeholder (name + recordTypeDeveloperName) for this required lookup to ${i.referenceTo.join(" or ")||"its parent"}`);continue}let c=a.targetObjectApiName??i.referenceTo[0];if(!c){n.push(`requiredLookupPlaceholders["${d}"].targetObjectApiName: the target describe names no object this lookup points at`);continue}let f;if(a.recordTypeDeveloperName){let l=await this.deps.recordTypeResolver.resolveByDeveloperName(e.orgId,c,a.recordTypeDeveloperName);if(l!==null&&typeof l=="object"&&"ambiguous"in l){let u=l.carriers.find(p=>p.namespacePrefix);n.push(`requiredLookupPlaceholders["${d}"]: `+Bn(c,a.recordTypeDeveloperName,"the target org",l.carriers)+(u?" \u2014 a package's is named with its namespace: "+St(u.namespacePrefix,u.developerName):""));continue}if(l!==null&&typeof l=="object"){n.push(`requiredLookupPlaceholders["${d}"]: record type ${a.recordTypeDeveloperName} on ${c} is not available to the running user`);continue}if(f=l??void 0,!f){n.push(`requiredLookupPlaceholders["${d}"]: record type ${a.recordTypeDeveloperName} is not on ${c} in the target org \u2014 deploy it before loading`);continue}}r.push({kind:"placeholder",missing:i,key:d,name:a.name,targetObject:c,recordTypeId:f})}if(n.length>0)throw new Ge(`The dataset leaves ${n.length} required field(s) empty that the configuration does not cover. Nothing was written. Declare them all, then load again \u2014 records are never silently excluded:
10
- - ${n.join(`
11
- - `)}`,n);return r}async createPlaceholder(e,t,r,n,o,i){let{missing:d,key:a,targetObject:c}=t,f={Name:t.name};t.recordTypeId&&(f.RecordTypeId=t.recordTypeId),await this.checkGuard(e,"insert",c,1);let[l]=await this.deps.writer.insert(e.orgId,c,[f]);if(l===void 0&&e.signal?.aborted)return;if(!l?.success||!l.id)throw new Ge(`Placeholder insert failed for required lookup ${a} on ${c}: ${l?.errors.join("; ")||"no id returned"}. Fix the target org configuration and retry.`);let u=`${mn}${c}:${a}`;n.set(u,l.id),i.add(c,u),this.journal?.created(c,[[u,l.id]]);let p=0;for(let g of r){let h=g.fields[d.field];(h==null||h==="")&&(g.fields[d.field]=l.id,p++)}o.push({objectApiName:d.objectApiName,field:d.field,placeholderObjectApiName:c,placeholderName:t.name,placeholderId:l.id,affectedRecords:p})}applyScalarDefault(e,t,r,n){let o=`${e.objectApiName}.${e.field}`,i=this.config.requiredFieldDefaults?.[o],d=fo(i,e.distinct),a=0;for(let c of t)Xe(c.fields[e.field])&&(c.fields[e.field]=po(i,d,{referenceId:c.referenceId,rank:n.get(c.referenceId)??0}),a++);r.push({objectApiName:e.objectApiName,field:e.field,value:i,affectedRecords:a,...d?{perRecord:d}:{}})}async insertObject(e,t,r,n,o,i,d,a,c,f,l,u,p){let g={objectApiName:t,fromFiles:r,inserted:0,reused:0,skippedDuplicates:[],failed:[]},h=n.filter(O=>!d.has(O.referenceId));g.reused=n.length-h.length;let m=[];for(let O of h){let w=oc(t,O.fields,o,u);w?g.failed.push({objectApiName:t,referenceId:O.referenceId,errors:[w]}):m.push(O)}if(m.length===0)return g;let y=m.map(O=>{let w={},R=[];for(let[j,N]of Object.entries(O.fields))if(!(N===""||N===null||N===void 0))if(typeof N=="string"&&o.has(N)){let $=i.get(N);$&&!(t===br&&j===Rr)?w[j]=$:R.push({objectApiName:t,referenceId:O.referenceId,field:j,targetReferenceId:N})}else w[j]=N;let k=as(t,w);for(let j of k)delete w[j];a.push(...R.filter(j=>!k.includes(j.field)));for(let j of Zo(t,w))delete w[j];return w}),v=(O,w,R)=>{i.set(O,w),f.add(t,O,Xd.some(k=>k in R)),g.inserted++};await this.checkGuard(e,"insert",t,y.length);let P=await this.deps.writer.insert(e.orgId,t,y,(O,w)=>this.journalBatch(t,m,O,w)),S=[];P.forEach((O,w)=>{let R=m[w].referenceId;if(O.success&&O.id){v(R,O.id,y[w]);return}if(za(O.errors,c)){g.skippedDuplicates.push({objectApiName:t,referenceId:R,errors:O.errors});return}let k=this.sentAgain(t,y[w],O);k?S.push({...k,referenceId:R,errors:O.errors}):g.failed.push({objectApiName:t,referenceId:R,errors:O.errors})});let I=m.length-P.length;if(I>0&&e.signal?.aborted&&(g.notInserted=I),S.length===0)return g;let E=(O,w)=>{for(let R of O)g.failed.push({objectApiName:t,referenceId:R.referenceId,errors:[...R.errors,`Not written again ${Ia(R.fields)}: ${w}`]})};if(e.signal?.aborted)return E(S,"the load was cancelled first"),g;let z;try{await this.checkGuard(e,"insert",t,S.length),z=await this.deps.writer.insert(e.orgId,t,S.map(O=>O.payload),(O,w)=>this.journalBatch(t,S,O,w))}catch(O){throw E(S,K(O)),p?.(g),O}return S.forEach((O,w)=>{let R=z[w];if(!R){E([O],e.signal?.aborted?"the load was cancelled first":"no answer came for it");return}if(R.success&&R.id){v(O.referenceId,R.id,O.payload),g.writtenWithoutFields=Hn(g.writtenWithoutFields,{rows:1,fields:O.fields.map(j=>({...j,rows:1}))});for(let{field:j,replacedWith:N}of O.fields){if(N!==void 0)continue;let $=l.get(t)??new Map;$.set(j,[...$.get(j)??[],O.referenceId]),l.set(t,$)}return}let k=[...R.errors,`Sent again ${Ia(O.fields)} after the first refusal: ${O.errors.join("; ")}`];za(R.errors,c)?g.skippedDuplicates.push({objectApiName:t,referenceId:O.referenceId,errors:k}):g.failed.push({objectApiName:t,referenceId:O.referenceId,errors:k})}),g}journalBatch(e,t,r,n){let o=this.journal;o&&o.created(e,n.flatMap((i,d)=>{let a=t[r+d];return i.success&&i.id&&a?[[a.referenceId,i.id]]:[]}))}sentAgain(e,t,r){let n=vi(r.errorDetails,t,void 0);if(!n)return;let o={...t},i=n.map(d=>{let a=d.refusedBy==="restricted-picklist"?this.picklistRuleFor(e,d.field):void 0;return a?.action==="replace"&&a.value!==""&&a.value!==t[d.field]?(o[d.field]=a.value,{...d,replacedWith:a.value}):(delete o[d.field],{...d})});return{payload:o,fields:i}}async matchDirectRelations(e,t,r,n,o,i){let d=new Map;for(let u of t.objects.find(p=>p.objectApiName==="Contact")?.records??[])d.set(u.referenceId,u.fields.AccountId);let a=r.filter(u=>{let p=u.fields.ContactId;return typeof p=="string"&&u.fields.AccountId!==void 0&&d.get(p)===u.fields.AccountId&&n.has(p)&&typeof u.fields.AccountId=="string"&&n.has(u.fields.AccountId)});if(a.length===0)return;let c=[...new Set(a.map(u=>n.get(u.fields.ContactId)))],f=await this.deps.orgAccess.query(e,`SELECT Id, AccountId, ContactId FROM AccountContactRelation WHERE IsDirect = true AND ContactId IN (${c.map(u=>`'${Pe(String(u))}'`).join(", ")})`),l=new Map(f.map(u=>[`${String(u.AccountId)}|${String(u.ContactId)}`,u.Id]));for(let u of a){let p=n.get(u.fields.AccountId),g=n.get(u.fields.ContactId),h=l.get(`${String(p)}|${String(g)}`);typeof h=="string"&&(n.set(u.referenceId,h),o.add(u.referenceId),i.set(u.referenceId,u.fields.ContactId))}}async matchTasksWrittenWithEmails(e,t,r,n,o,i){let d=new Set(r.map(f=>f.referenceId)),a=new Map;for(let f of t.objects.find(l=>l.objectApiName===De)?.records??[]){let l=f.fields.ActivityId;if(typeof l!="string"||!d.has(l)||o.has(f.referenceId))continue;let u=n.get(f.referenceId);u&&a.set(l,{id:u,key:f.referenceId})}if(a.size===0)return;let c=await ls(f=>this.deps.orgAccess.query(e,f),[...new Set([...a.values()].map(f=>f.id))]);for(let[f,l]of a){let u=c.get(l.id);u!==void 0&&(n.set(f,u),o.add(f),i.set(f,l.key))}}async matchContactRolesWrittenWithOpportunities(e,t){let{aligned:r,refIndex:n,mapping:o,reused:i}=t,d=w=>typeof w=="string"?o.get(w):void 0,a=new Map;for(let w of t.working.objects.find(R=>R.objectApiName===xa)?.records??[]){let R=o.get(w.referenceId),k=d(w.fields[it]);R&&k&&!i.has(w.referenceId)&&a.set(R,k)}if(a.size===0)return{linked:0};let c=r.map(w=>({OpportunityId:d(w.fields.OpportunityId),[it]:d(w.fields[it]),IsPrimary:w.fields.IsPrimary})),f=xn(c,w=>a.get(w)).filter(w=>!i.has(r[w].referenceId));if(f.length===0)return{linked:0};let l=w=>{let R={},k=[];for(let[j,N]of Object.entries(w.fields))if(!(j==="OpportunityId"||j===it)&&!t.fixedAtInsert.has(j)&&!(N===""||N===null||N===void 0))if(typeof N=="string"&&n.has(N)){let $=o.get(N);$?R[j]=$:k.push({objectApiName:kt,referenceId:w.referenceId,field:j,targetReferenceId:N})}else R[j]=N;return{fields:R,owed:k}},u=new Map(f.map(w=>[w,{opportunity:String(c[w].OpportunityId),contact:String(c[w][it])}])),p=[...new Set(f.flatMap(w=>Object.keys(l(r[w]).fields)))],g=await gs(w=>this.deps.orgAccess.query(e.orgId,w),[...new Set([...u.values()].map(({opportunity:w})=>w))],p),{found:h,alike:m}=hs(u,g),y=m.length>0?ms(m.length):void 0;if(h.size===0)return y?{linked:0,note:y}:{linked:0};let v=w=>y?`${w}; ${y}`:w,P=[];for(let[w,R]of h){let k=r[w],j=String(R.Id);o.set(k.referenceId,j),i.add(k.referenceId),t.withTheirRecord.set(k.referenceId,String(k.fields.OpportunityId));let{fields:N,owed:$}=l(k);t.pendingFk.push(...$);let B=Object.entries(N).filter(([H,T])=>String(R[H]??"")!==String(T));B.length>0&&P.push({Id:j,...Object.fromEntries(B)})}let S=h.size,I=`${S} written by the platform with ${ps(kt)}`;if(P.length===0)return{linked:S,note:v(I)};let E=(w,R)=>`${I}, ${w} of them left as it wrote ${w===1?"it":"them"}, without the fields of the source's role: ${R}`;if(e.signal?.aborted)return{linked:S,note:v(E(P.length,"the load was cancelled before the update"))};await this.checkGuard(e,"update",kt,P.length);let z=await this.deps.writer.update(e.orgId,kt,P),O=P.flatMap((w,R)=>{let k=z[R];return k?.success?[]:[k?k.errors.join("; ")||"refused":"no answer came for it"]});return O.length===0?{linked:S,note:v(I)}:{linked:S,note:v(E(O.length,O[0]))}}async matchActivityRelations(e,t,r,n,o,i){let{orgId:d}=e,a=$n[t],c=l=>typeof l=="string"?n.get(l):void 0,f=await ys(l=>this.deps.orgAccess.query(d,l),t,r.map(l=>({[a]:c(l.fields[a]),RelationId:c(l.fields.RelationId)})));for(let[l,u]of f)n.set(r[l].referenceId,u),o.add(r[l].referenceId);return ws(t,[...f].map(([l,u])=>[r[l].fields,u]),l=>!i.has(l),async l=>(await this.checkGuard(e,"update",t,l.length),this.deps.writer.update(d,t,l)),()=>e.signal?.aborted===!0)}async startAsDrafts(e,t,r,n,o){let i=await this.statusCategories(e,r);return i?.draft?n.map(d=>{let a=Bt(d.fields.Status,i);return a?(o.push({objectApiName:t,referenceId:d.referenceId,status:String(d.fields.Status)}),{referenceId:d.referenceId,fields:{...d.fields,Status:a}}):d}):n}async withoutDirectRelations(e,t){let r=new Set;for(let n=0;n<t.length;n+=gt){let o=t.slice(n,n+gt).map(d=>`'${Pe(d)}'`).join(", "),i=await this.deps.orgAccess.query(e,`SELECT Id FROM ${lr} WHERE Id IN (${o}) AND IsDirect = true`);for(let d of i)r.add(String(d.Id))}return t.filter(n=>!r.has(n))}async customPricesFirst(e,t){let r=await Rs(n=>this.deps.orgAccess.query(e,n),t);return[t.filter(n=>!r.has(n)),t.filter(n=>r.has(n))]}async readWrittenBetween(e,t,r){let n=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(let{objectApiName:i,referenceIds:d}of t.list()){let a=[...new Set(d.flatMap(f=>{let l=r.get(f);return l?[l]:[]}))],c=t.sentAuditDates(i);for(let f=0;f<a.length;f+=gt){let l=await this.writtenDatesOf(e,i,a.slice(f,f+gt));if(!l)return;for(let u of l){let p=Pt(u.SystemModstamp),g=y=>{let v=c?Number.NaN:Pt(u[y]);return Number.isFinite(v)?v:p},h=g("CreatedDate"),m=g("LastModifiedDate");Number.isFinite(h)&&(n=Math.min(n,h)),Number.isFinite(m)&&(o=Math.max(o,m))}}}if(!(!Number.isFinite(n)||!Number.isFinite(o)))return{first:new Date(n).toISOString(),last:new Date(Math.max(n,o)).toISOString()}}async writtenDatesOf(e,t,r){let n=r.map(o=>`'${Pe(o)}'`).join(", ");for(let o of Qd)try{return await this.deps.orgAccess.query(e,`SELECT Id, ${o.join(", ")} FROM ${de(t)} WHERE Id IN (${n})`)}catch{}}async statusCategories(e,t){return Wt(r=>this.deps.orgAccess.query(e,r),t)}async applyDeferredStatuses(e,t,r,n){let{refused:o}=n.report,i=new Map;for(let d of t){let a=r.get(d.referenceId);a&&i.set(d.objectApiName,[...i.get(d.objectApiName)??[],{...d,id:a}])}n.unanswered=[...i.values()].reduce((d,a)=>d+a.length,0);for(let[d,a]of i){if(e.signal?.aborted)continue;let c=a.map(l=>({Id:l.id,Status:l.status}));await this.checkGuard(e,"update",d,c.length);let f=await this.deps.writer.update(e.orgId,d,c);f.forEach((l,u)=>{l.success?n.report.restored++:o.push({objectApiName:d,referenceId:a[u].referenceId,status:a[u].status,detail:l.errors.join("; ")})}),n.unanswered-=f.length}}async patchCycleFks(e,t,r,n){let{unresolved:o}=n.report,i=new Map,d=new Map;for(let c of t){let f=r.get(c.referenceId),l=r.get(c.targetReferenceId);if(!f||!l){o.push({objectApiName:c.objectApiName,referenceId:c.referenceId,field:c.field,cause:f?"target-not-loaded":"record-not-loaded",detail:f?`referenced record ${c.targetReferenceId} was not loaded (skipped, failed or excluded)`:"child record was not loaded (see perObject failures/skips)"});continue}d.set(f,c.referenceId);let u=i.get(c.objectApiName)??new Map,p=u.get(f)??{Id:f};p[c.field]=l,u.set(f,p),i.set(c.objectApiName,u)}let a=c=>c.reduce((f,l)=>f+Object.keys(l).length-1,0);n.unanswered=[...i.values()].reduce((c,f)=>c+a([...f.values()]),0);for(let[c,f]of i){let l=[...f.values()];if(e.signal?.aborted)continue;await this.checkGuard(e,"update",c,l.length);let u=await this.deps.writer.update(e.orgId,c,l);u.forEach((p,g)=>{p.success?n.report.resolved+=Object.keys(l[g]).length-1:o.push({objectApiName:c,referenceId:d.get(String(l[g].Id))??String(l[g].Id),field:Object.keys(l[g]).filter(h=>h!=="Id").join(","),cause:"update-refused",detail:p.errors.join("; ")})}),n.unanswered-=a(l.slice(0,u.length))}}async linkPersonContacts(e,t,r,n,o,i){let d={linked:new Map,own:new Map,unlinked:[]},a=new Map,c=[...t].map(([u,p])=>({accountReferenceId:p,contactReferenceId:u}));for(let u of c){let p=u.accountReferenceId===""?void 0:r.get(u.accountReferenceId);p!==void 0&&a.set(p,[...a.get(p)??[],u])}let f=a.size===0||o===!1?new Map:await fs(u=>this.deps.orgAccess.query(e,u),[...a.keys()]),l=new Map;for(let[u,p]of a){let g=f.get(u);if(g!==void 0)for(let h of p)l.set(h.contactReferenceId,g)}for(let u of c){let p=l.get(u.contactReferenceId);if(p!==void 0){r.set(u.contactReferenceId,p),d.linked.set(u.contactReferenceId,u.accountReferenceId);continue}if(u.accountReferenceId===""||!r.has(u.accountReferenceId)){d.unlinked.push({...u,cause:"record-not-loaded",detail:u.accountReferenceId===""?Or.accountNotInDataset:Or.accountNotLoaded});continue}if(n.has(u.contactReferenceId))continue;let g=i.find(m=>m.objectApiName===Le&&m.referenceId===u.accountReferenceId),h=Or.noPersonAccounts;o!==!1&&(h=g?`${Or.businessAccount}: ${g.detail}`:`${Or.businessAccount}: its record type there is no person account's`),d.own.set(u.contactReferenceId,{...u,detail:h})}return d}writeContract(e,t,r,n,o,i,d,a=0,c=new Map,f=[]){let l=new Map;for(let{objectApiName:h,referenceId:m,field:y}of f){let v=l.get(h)??{};v[y]=[...v[y]??[],m],l.set(h,v)}let u=new Map;for(let{objectApiName:h,count:m,reason:y}of d){let v=u.get(h)??{};v[y]=(v[y]??0)+m,u.set(h,v)}let p=[...r];for(let[h,m]of u)p.some(y=>y.objectApiName===h)||p.push({objectApiName:h,fromFiles:t.objects.find(y=>y.objectApiName===h)?.records.length??Object.values(m).reduce((y,v)=>y+v,0),inserted:0,reused:0,skippedDuplicates:[],failed:[]});let g={};for(let h of p){let m={};h.skippedDuplicates.length>0&&(m["duplicate-skipped"]=h.skippedDuplicates.length);let y=h.objectApiName===Fe?a:0,v=h.failed.filter(O=>sc(O.errors)).length;if(v>0&&(m["parent-refused"]=v),h.failed.length-v>y){let O=i.has(h.objectApiName)?"object-not-loaded":"dml-failed";m[O]=h.failed.length-v-y}y>0&&(m["person-contact-not-sent"]=y);let P=0;for(let[O,w]of Object.entries(u.get(h.objectApiName)??{}))m[O]=w,P+=w;let S=h.skippedDuplicates.length+h.failed.length+P,I=n.filter(O=>O.placeholderObjectApiName===h.objectApiName).length,E=c.get(h.objectApiName),z=l.get(h.objectApiName);g[h.objectApiName]={fromFiles:h.fromFiles,exclusionReasons:m,excluded:S,added:I,expected:h.inserted+h.reused+I,...E&&E.size>0?{writtenWithout:Object.fromEntries(E)}:{},...z?{parentNotLoaded:z}:{}}}return ba(this.sasGuard,e.sasDir,{version:1,orgId:e.orgId,datasetVersion:t.datasetVersion,writtenAt:o.now().toISOString(),loadStartedAt:o.startedAt.toISOString(),objects:g})}picklistRuleFor(e,t){return this.config.picklistRules?.[`${e}.${t}`]??this.config.defaultPicklistRule??{action:"clear"}}contractPath(e,t){return vr(this.sasGuard,e,t)}};function Aa(s){let e=new Map;for(let t of s)for(let r of t.failed)e.set(r.referenceId,t.objectApiName);return e}function oc(s,e,t,r){if(r.size===0)return;let n=new Set(s===De&&!Dn(e,o=>t.get(o))?["ActivityId"]:[]);for(let[o,i]of Object.entries(e)){if(typeof i!="string"||n.has(o)||!t.has(i))continue;let d=r.get(i);if(d!==void 0)return`PARENT_REFUSED: the ${d} record its ${o} names was refused in this load, and written without it this record would stand without its ${d}.`}}function sc(s){return s.length===1&&s[0].startsWith("PARENT_REFUSED:")}function Xe(s){return s==null||s===""}var $a=/\{(n|referenceId)\}/g;function fo(s,e){if(typeof s=="string")return s.match($a)?"token":e}function po(s,e,t){return typeof s!="string"||e===void 0?s:e==="token"?s.replace($a,(r,n)=>n==="n"?String(t.rank):t.referenceId):`${s} ${t.rank}`}function ic(s,e){let{objectApiName:t,keyFields:r,ranks:n,accountKindOf:o}=s,i=s.missingRequired.filter(d=>!d.isLookup&&r.includes(d.field));return s.records.map(d=>{let a={...d.fields};for(let c of i){let f=e[`${t}.${c.field}`];f===void 0||!Xe(a[c.field])||wn(c,[d],o).length!==0&&(a[c.field]=po(f,fo(f,c.distinct),{referenceId:d.referenceId,rank:n.get(d.referenceId)??0}))}return{referenceId:d.referenceId,fields:a}})}function _a(s,e=!1){return s.length===0?{}:{keysLeftEmpty:s.map(({objectApiName:t,fields:r,count:n})=>{let o=n===1?"its":"their",i=r.join(", "),d="the dataset holds no value, and no default fills it";return{objectApiName:t,fields:[...r],count:n,note:e?`${n} not looked up by ${o} identity keys: ${i} stays empty in what the load would write \u2014 ${d} \u2014 so ${n===1?"it":"they"} would be inserted, never matched`:`${n} not looked up by ${o} identity keys: ${i} stayed empty in what the load wrote \u2014 ${d} \u2014 so ${n===1?"it was":"they were"} sent to be inserted, never matched`}})}}function ac(s){let e=new Map;for(let t of s.objects)t.records.forEach((r,n)=>e.set(r.referenceId,n+1));return e}function dc(s,e){let t=(s.get(kt)??[]).filter(a=>!e.has(a.referenceId));if(t.length===0)return new Set;let r=new Map,n=a=>{if(typeof a!="string"||a==="")return;let c=r.get(a);return c===void 0&&(c=String(r.size+1).padStart(15,"0"),r.set(a,c)),c},o=new Set((s.get(Fe)??[]).map(a=>a.referenceId)),i=new Map;for(let a of s.get(xa)??[]){if(e.has(a.referenceId))continue;let c=a.fields[it];typeof c!="string"||!o.has(c)||i.set(n(a.referenceId),n(c))}if(i.size===0)return new Set;let d=t.map(a=>({OpportunityId:n(a.fields.OpportunityId),[it]:n(a.fields[it]),IsPrimary:a.fields.IsPrimary}));return new Set(xn(d,a=>i.get(a)).map(a=>t[a].referenceId))}function cc(s,e,t,r){let n=f=>(s.get(f)??[]).filter(l=>!e.has(l.referenceId)),o=new Set,i=new Map;for(let f of n(Fe))t.has(f.referenceId)||i.set(f.referenceId,f.fields.AccountId);let d=new Set((s.get("Account")??[]).map(f=>f.referenceId));for(let f of n(lr)){let{AccountId:l,ContactId:u}=f.fields;typeof l!="string"||typeof u!="string"||i.get(u)===l&&d.has(l)&&o.add(f.referenceId)}let a=new Set([...s.values()].flatMap(f=>f.map(l=>l.referenceId))),c=new Set(n(_t).map(f=>f.referenceId));for(let f of n(De)){let l=f.fields.ActivityId,u=f.fields.RelatedToId;typeof l!="string"||!c.has(l)||typeof u!="string"||!a.has(u)||Dn(f.fields,r)||o.add(l)}return o}function Pa(s,e,t){let{working:r,loading:n,alignedByObject:o,reused:i,reusedByKeys:d,alignment:a,ranks:c}=s,f=s.targetHasPersonAccounts===!1?new Set:s.personContacts,l=w=>(o.get(w)??[]).filter(R=>!i.has(R.referenceId)),u=[...new Set([...s.groupOrder,...r.objects.map(w=>w.objectApiName),...e?[...e.residuals.keys()].sort():[]])],p=0,g=dc(o,i),h=cc(o,i,f,w=>s.refIndex.get(w)),m=[];for(let w of u){let R=r.objects.find(F=>F.objectApiName===w)?.records.length??0,k=e?.residuals.get(w)?.length??0;if(R===0&&k===0)continue;let j=o.get(w),$=(j??n.objects.find(F=>F.objectApiName===w)?.records??[]).filter(F=>i.has(F.referenceId)),B=$.filter(F=>d.has(F.referenceId)).length,H=j?l(w):[],T=H.filter(F=>f.has(F.referenceId)).length;p+=T;let A=H.filter(F=>g.has(F.referenceId)||h.has(F.referenceId)).length,q=(s.filteredLookups.get(w)??[]).flatMap(({field:F,referenceTo:_})=>{let U=H.filter(ee=>!Xe(ee.fields[F])).length;return U>0?[{field:F,referenceTo:_,records:U}]:[]}),J=t.undeletableObjects[w]!==void 0;m.push({objectApiName:w,fromFiles:R,toInsert:H.length-T-A,reusedByKeys:B,reusedFromCatalog:$.length-B,...A>0?{writtenByThePlatform:A}:{},fieldsDropped:a.removals.filter(F=>F.objectApiName===w).length,picklistsRewritten:a.adjustments.filter(F=>F.objectApiName===w).length,notSent:R-(j?j.length:$.length),toPurge:J?0:k,toDeactivate:J?k:0,...q.length>0?{lookupFilters:q}:{}})}let y=(w,R)=>l(w).filter(k=>Xe(k.fields[R])),v=(w,R)=>y(w,R).length,P=w=>{let R=wn(w,y(w.objectApiName,w.field),s.accountKindOf),k=t.requiredFieldDefaults[`${w.objectApiName}.${w.field}`],j=fo(k,w.distinct),N=R[0];return{objectApiName:w.objectApiName,field:w.field,affectedRecords:R.length,...j?{perRecord:j}:{},...j&&N?{example:String(po(k,j,{referenceId:N.referenceId,rank:c.get(N.referenceId)??0}))}:{}}},S=e?.leftUnrecorded??{},I=e?.keptByThePlatform??{},E=s.heldForExclusions.counts(),z=Ca(s,w=>!i.has(w)&&!f.has(w)).map(({given:w})=>w),O=new Set([...o.values()].flatMap(w=>w.map(R=>R.referenceId)));return{orgId:t.orgId,mode:t.mode,plannedAt:t.plannedAt,perObject:m,excludedObjects:a.excludedObjects,removals:a.removals,placeholders:s.plans.flatMap(w=>w.kind==="placeholder"?[{objectApiName:w.missing.objectApiName,field:w.missing.field,placeholderObjectApiName:w.targetObject,placeholderName:w.name,affectedRecords:v(w.missing.objectApiName,w.missing.field)}]:[]),requiredDefaults:s.plans.flatMap(w=>w.kind==="default"?[P(w.missing)]:[]),recordTypeIssues:s.recordTypeIssues.length,personContacts:p,earlierLoads:s.previousLoads.length,...Object.keys(S).length>0?{leftUnrecorded:S}:{},...Object.keys(I).length>0?{keptByThePlatform:I}:{},...E.length>0?{heldForExcludedParents:Wa(E)}:{},...qa(ao(o,w=>O.has(w)),t,!0),..._a(s.keysLeftEmpty,!0),...z.length>0?{recordTypesGiven:z}:{}}}var ja=5;function lc(s){switch(s.fieldType){case"date":return'a date, as "2026-12-31",';case"datetime":return'a date and time, as "2026-12-31T09:00:00Z",';case"time":return'a time, as "09:00:00.000Z",';case"double":case"currency":case"percent":return"a number";case"int":case"long":return"a whole number";case"boolean":return"true or false";case"picklist":case"multipicklist":{let e=s.activeValues??[];return e.length===0?"one of its values":`one of its active values (${e.slice(0,ja).join(", ")}${e.length>ja?", \u2026":""})`}case"email":return"an email address";case"string":case"textarea":case"phone":case"url":case"encryptedstring":case"combobox":return"a string";default:return"a value"}}function qa(s,e,t=!1){let r=wa(s,(e.excludedObjects??[]).includes(io),t);return r?{quotesLeftUnsynced:[r]}:{}}function uc(s,e,t){for(let r=!0;r;){r=!1;for(let[n,o]of s){let i=[...e.get(n)??[]],d=o.filter(a=>!t.some(c=>c.leaveOut(n,a.referenceId,a.fields,i)));d.length!==o.length&&(s.set(n,d),r=!0)}}}function fc(s,e,t){let r=new Set(t.excludedObjects??[]);if(r.size===0)return[];let n=[];for(let o of e.fields){let i=o.referenceTo??[];i.length===0||!i.every(d=>r.has(d))||!o.createable||o.defaultedOnCreate||xt(s,o.name,o.nillable)&&(t.requiredLookupPlaceholders?.[`${s}.${o.name}`]||n.push({field:o.name,excludedObject:i[0]}))}return n}function pc(s){return(e,t)=>{for(let{field:r,excludedObject:n}of s.get(e)??[])if(Xe(t[r]))return{field:r,value:"",noun:n}}}function Ga(s,e){return e.through?`${s} left out: ${e.through} names a record left out for the ${e.rows.noun} excludedObjects leaves out`:`${s} left out: ${e.rows.field??"a lookup"} names ${/^[AEIOU]/i.test(e.rows.noun)?"an":"a"} ${e.rows.noun} record, which excludedObjects leaves out \u2014 declare a placeholder in requiredLookupPlaceholders to load them`}function Wa(s){return s.map(({objectApiName:e,why:t,count:r})=>({objectApiName:e,count:r,note:Ga(r,t)}))}var gc={field:"Type",value:"",noun:"feed item whose type the dataset does not carry"};function hc(s,e){if(s!=="FeedItem")return;let t=e.Type;return typeof t=="string"&&t!==""?void 0:gc}function Fa(s,e){let t="extract the dataset again, with rules that keep FeedItem.Type";return e.through?`${s} left out: ${e.through} names a feed item whose type the dataset does not carry \u2014 ${t}`:`${s} feed item${s===1?"":"s"} left out: the dataset does not carry ${s===1?"its":"their"} type, and a tracked change cannot be told from a post \u2014 ${t}`}function Ta(s){let e=new Map;for(let t of s.objects)for(let r of t.records)e.set(r.referenceId,t.objectApiName);return e}function mc(s,e,t=new Map){let r=new Map;for(let n of s.objects){let o=r.get(n.objectApiName)??new Set;for(let i of n.records)for(let[d,a]of Object.entries(i.fields))if(!(n.objectApiName===Le&&d===Yr)&&typeof a=="string"){let c=e.get(a);c&&c!==n.objectApiName&&o.add(c)}r.set(n.objectApiName,o)}t.size>0&&r.has(Le)&&r.get(Fe)?.add(Le);for(let{sourceObject:n,targetObject:o}of Ri(new Set(r.keys()),[]))r.get(o)?.add(n);for(let{sourceObject:n,targetObject:o}of ds(new Set(r.keys())))r.get(n)?.delete(o),r.get(o)?.add(n);return r}function yc(s,e,t,r=new Map){let n=new Map;for(let[o,i]of s){let d=e.get(o),a=new Set;if(d)for(let c of i)for(let f of d){let l=c.fields[f],u=typeof l=="string"?t.get(l):void 0;u&&u!==o&&a.add(u)}n.set(o,a)}return r.size>0&&n.set(Fe,new Set([...n.get(Fe)??[],Le])),n}function wc(s,e){let t=h=>s.objects.find(m=>m.objectApiName===h)?.records??[],r=(h,m)=>m.map(y=>String(h[y]??"")).join("|"),n=[Ne,Ce,Vr],o=[Ne,Ce],i=(h,m)=>typeof h[m]=="string"&&h[m]!=="",d=t(Je),a=d.filter(h=>e.has(h.referenceId)&&i(h.fields,Ne)),c=s.standardPricebook,f=h=>c!==void 0&&h.fields[Ot]===c,l=new Set(a.filter(h=>!f(h)).map(h=>r(h.fields,n))),u=d.filter(h=>f(h)&&l.has(r(h.fields,n))),p=new Set([...a,...u].filter(h=>i(h.fields,Ce)).map(h=>r(h.fields,o))),g=t(ve).filter(h=>p.has(r(h.fields,o)));return[...u,...g].map(h=>h.referenceId)}function Ea(s){return[...Object.keys(Jr),ve].filter(e=>s.objects.some(t=>t.objectApiName===e&&t.records.length>0))}function bc(s,e){for(let t of s.objects){let r=t.records.find(n=>n.referenceId===e);if(r)return r}}function La(s){return JSON.stringify(s.map(e=>e===void 0?null:e))}function za(s,e){return s.some(t=>e.some(r=>t.toLowerCase().includes(r.toLowerCase())))}import{randomBytes as Rc}from"node:crypto";import{readFile as vc}from"node:fs/promises";var go="frozen.salt";function Oc(){return Rc(32).toString("base64url")}function Ba(s){let e=s[Bi];return e?{salt:e,source:"environment"}:void 0}function Pu(s,e=process.env){let t=async()=>{let r=Ba(e);if(r)return r;let n=await s.getSecret(go);return n?{salt:n,source:"secretStorage"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(r)return r;let n=Oc();if(await s.storeSecret(go,n),await s.getSecret(go)!==n)throw new mr;return{salt:n,source:"secretStorage",created:!0}}}}function Va(s=process.env,e){let t=async()=>{let r=Ba(s);if(r)return r;if(e===void 0)return;let n=(await vc(e,"utf8")).trim();return n?{salt:n,source:"file"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(!r)throw new mr;return r}}}import{createHash as kc}from"node:crypto";import{appendFileSync as Ic,mkdirSync as Sc,readFileSync as Ac}from"node:fs";import*as Sr from"node:path";var Pc=15*6e4;function ho(s){return`sha256:${kc("sha256").update(Sr.resolve(s)).digest("hex").slice(0,16)}`}function Ua(s,e){if(!s?.writtenBetween)return;let t=Date.parse(s.endedAt),r=Date.parse(e);if(!Number.isFinite(t)||!Number.isFinite(r)||t<r)return;let n=Date.parse(s.writtenBetween.first),o=Date.parse(s.writtenBetween.last);if(!(!Number.isFinite(n)||!Number.isFinite(o)))return new Date(Math.max(n,o)).toISOString()}function jc(s,e){return e.some(t=>{let r=Date.parse(t.endedAt),n=Date.parse(t.startedAt??t.endedAt);return Number.isFinite(r)&&s>=(Number.isFinite(n)?n:r)-6e4&&s<=r+Pc})}function Ka(s,e){let t=[];for(let r of s){let n=Date.parse(r.endedAt);if(!Number.isFinite(n)||(r.sas!==void 0?r.sas===e.sasMark:jc(n,e.own)))continue;let o=Date.parse(r.lastWriteAt??""),i=Number.isFinite(o)?o:n,d=Date.parse(r.startedAt??r.endedAt);t.push({ids:[],idsUntold:!0,from:Number.isFinite(d)?Math.min(d,i):i,to:i})}return t}var Ha="frozen-loads.ndjson";function Eu(s,e){Sc(s,{recursive:!0}),Ic(Sr.join(s,Ha),`${JSON.stringify(e)}
12
- `)}function Fc(s,e){return s.slice(0,15)===e.slice(0,15)}function Lu(s,e){let t;try{t=Ac(Sr.join(s,Ha),"utf8")}catch{return[]}let r=[];for(let n of t.split(`
13
- `)){if(n.trim()==="")continue;let o;try{o=JSON.parse(n)}catch{continue}let{organizationId:i,sas:d,startedAt:a,endedAt:c,lastWriteAt:f}=o??{};typeof i!="string"||typeof c!="string"||Fc(i,e)&&r.push({endedAt:c,...typeof d=="string"?{sas:d}:{},...typeof a=="string"?{startedAt:a}:{},...typeof f=="string"?{lastWriteAt:f}:{}})}return r}function Ja(s){return s.filter(e=>e.action==="frozen_load"&&e.outcome!=="stopped").map(e=>{let t=e.details?.sas,r=e.details?.startedAt,n=e.details?.lastWriteAt;return{endedAt:e.timestamp,...typeof t=="string"?{sas:t}:{},...typeof r=="string"?{startedAt:r}:{},...typeof n=="string"?{lastWriteAt:n}:{}}})}var Tc="FROZEN_EMAILS_EXCEEDED";function xu(s,e){return[...zi(s.counted,e),...s.uncounted!==void 0?[` emails: not counted, ${s.uncounted} could not be read`]:[],...s.deliverability?[` ${Di(s.deliverability.reading)}`]:[]]}function Ec(s){return typeof s.unread=="string"}async function Ya(s){let{read:e,plan:t,writes:r,target:n}=s,o=await li({read:e,...t?{plan:t}:{},writes:r,readDeliverability:s.readDeliverability,accepted:s.accepted,target:n,run:"load",keepsAddresses:!0,mayMute:s.mayMute}),i=[],d;if(Ec(e))d=`the target's automation: ${e.unread}`;else{let l=$t(e,t,r).automation,u={objects:s.inserts.map(g=>({...g,storageBytes:0}))};d=Ei(l,Ti(u));let p=ts(l);if(p.length>0){let g=await s.readLimits().catch(h=>({unread:K(h)}));i=Fi(u,p,g)}}let a=Li(i,n),c=a?{code:Tc,message:`${a} Nothing was written.`}:o.gate.stop,{deliverability:f}=o.gate;return{run:o,info:{counted:i.map(l=>({...l,objects:[...l.objects]})),...d!==void 0?{uncounted:d}:{},verdict:o.gate.verdict,...f?{deliverability:f}:{},accepted:s.accepted,...c?{refused:{code:c.code,message:c.message}}:{}},...c?{stop:c}:{}}}var Lc="AUTOMATION_NOT_ACCEPTED";function zc(s){let e=new Set(s);return(t,r)=>e.has(t)&&(r==="insert"||r==="update")}function Nc(s){return typeof s.unread=="string"}function Cc({kind:s,name:e}){return s==="flow"?`flow "${e}"`:s==="process"?`process "${e}"`:s==="workflowRule"?`workflow rule "${e}"`:`Apex trigger ${e}`}var Za={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"what runs"};function Xa(s){return`${s.objectApiName}: ${Cc(s)} (${s.writes.join(", ")})`}function Dc(s,e,t){let r=[];s.firing.length>0&&r.push(`${e} runs automation as this load inserts its records and updates them: ${s.firing.map(Xa).join("; ")}.`);for(let{part:n,reason:o}of s.unread??[]){let i=Za[n];r.push(`${i[0].toUpperCase()}${i.slice(1)} of ${e} could not be read (${o}), so what fires as the load writes is not known.`)}return r.push(...t),r.push(`Nothing was written. Add --accept-automation to load all the same, or turn that automation off in ${e} first.`),r.join(" ")}function mo(s){let{read:e,target:t}=s,r=zc(s.written),n=[],o=[],i=[];if(Nc(e))o=[{part:"automation",reason:e.unread}];else{let c=$t(e,s.plan,r),f=new Map;for(let p of c.firing){if(p.write!=="insert"&&p.write!=="update")continue;let g=`${p.objectApiName}\0${p.kind}\0${p.name}`,h=f.get(g);h?h.writes.includes(p.write)||h.writes.push(p.write):f.set(g,{objectApiName:p.objectApiName,kind:p.kind,name:p.name,writes:[p.write]})}n=[...f.values()].map(p=>({...p,writes:["insert","update"].filter(g=>p.writes.includes(g))})),o=$i(e);let l=xi(c.automation,Mi(c.automation,[...s.written])),u=[...new Set(l.flatMap(p=>p.permissionSet??[]))];i=[..._i(l,t,"the load"),...s.mayMute&&u.length>0?[`With --mute-automation, the load assigns ${u.join(", ")} to the user it writes as for the load alone, under a lease, and what ${u.length===1?"it keeps":"they keep"} quiet does not fire.`]:[]]}if(n.length===0&&o.length===0)return{};let d={firing:n,...o.length>0?{unread:o}:{},accepted:s.accepted};if(s.accepted)return{info:d};let a={code:Lc,message:Dc(d,t,i)};return{info:{...d,refused:a},stop:a}}function Gu(s,e){return[`target automation: what ${e} runs as the load inserts its records and updates them`,...s.firing.map(t=>` ${Xa(t)}`),...(s.unread??[]).map(({part:t,reason:r})=>` ${Za[t]} could not be read: ${r}`),...s.accepted?[" accepted (--accept-automation): the load writes all the same"]:[]]}import*as le from"node:fs/promises";import*as Dd from"node:os";import*as fe from"node:path";var Yt=class extends Error{constructor(t,r=[]){super(r.length>0?`${t}:
14
- - ${r.join(`
15
- - `)}`:t);this.violations=r;this.name="RulesFileError"}violations},Mc=/^\d+\.\d+\.\d+$/,Qa=/^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/,xc=new Set(Xn);function yo(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function bn(s){let e=[];if(!yo(s))throw new Yt("Rules file must be a JSON object");let t=s.rulesVersion;(typeof t!="string"||!Mc.test(t))&&e.push('rulesVersion is required and must be semver (e.g. "1.0.0")');let r=s.rules;if(!yo(r))throw e.push('rules is required and must be an object keyed by "Object.Field"'),new Yt("Invalid rules file",e);let n={};for(let[o,i]of Object.entries(r)){if(!Qa.test(o)){e.push(`"${o}": key must match "ObjectApiName.FieldApiName"`);continue}if(!yo(i)){e.push(`"${o}": rule must be an object with a "generator" property`);continue}let d=i.generator;if(typeof d!="string"||!xc.has(d)){e.push(`"${o}": unknown generator ${JSON.stringify(d)} (supported: ${Xn.join(", ")})`);continue}let a=i.approved===!0;if(d==="keep"&&!a){e.push(`"${o}": generator "keep" requires "approved": true (explicit human review)`);continue}let c={generator:d};i.approved!==void 0&&(c.approved=a),typeof i.comment=="string"&&(c.comment=i.comment),n[o]=c}if(e.length>0)throw new Yt("Invalid rules file",e);return{rulesVersion:t,rules:n}}function ed(s){let e=Object.keys(s.rules).sort(),t={};for(let r of e)t[r]=s.rules[r];return`${JSON.stringify({rulesVersion:s.rulesVersion,rules:t},null,2)}
16
- `}var td={rulesVersion:"1.0.0",rules:{}};function rd(s){if(s===null)return{found:!1};try{let e=bn(JSON.parse(s));return{found:!0,rulesVersion:e.rulesVersion,ruleCount:Object.keys(e.rules).length}}catch(e){return{found:!0,invalid:e instanceof Error?e.message:String(e)}}}var $c=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],_c=new Set(["FeedItem.Type","Pricebook2.IsActive","PricebookEntry.IsActive","Product2.IsActive",...$c.flatMap(s=>[`BusinessHours.${s}StartTime`,`BusinessHours.${s}EndTime`]),"BusinessHours.TimeZoneSidKey","OperatingHours.TimeZone","TimeSlot.DayOfWeek","TimeSlot.StartTime","TimeSlot.EndTime","TimeSlot.Type"]),qc=new Set(["TimeZoneSidKey","LocaleSidKey","LanguageLocaleKey","CurrencyIsoCode","EmailEncodingKey"]);function Ve(s,e,t){let r=`${e}.${t}`,n=s.rules[r]?.generator;return n||(s.personalBySchema?.has(r)===!0?"clear":_c.has(r)||qc.has(t)||s.keptBySchema?.has(r)===!0?"keep":"clear")}function nd(s,e,t){let r=new Set(s.keptBySchema??[]),n=new Set(s.personalBySchema??[]);for(let[o,i]of e){let d=new Set(t.detectPII(o,i.map(a=>({apiName:a.name,label:a.label??a.name,type:a.type}))).piiFields.map(a=>a.fieldApiName));for(let a of i){let c=`${o}.${a.name}`;d.has(a.name)?n.add(c):a.type==="picklist"&&(a.restrictedPicklist===!0||a.nillable===!1)&&a.compoundFieldName===void 0&&r.add(c)}}return{...s,keptBySchema:r,personalBySchema:n}}function od(s,e){let t=new Set;for(let r of s.objects)for(let n of r.records)for(let o of Object.keys(n.fields)){let i=`${r.objectApiName}.${o}`;e.rules[i]===void 0&&Ve(e,r.objectApiName,o)==="keep"&&t.add(i)}return[...t].sort()}function sd(s,e,t){let r=[];for(let n of s.objects){let o=t.get(n.objectApiName)??[];for(let f of o){let l=Kr(n.objectApiName,f.name);if(f.name==="Id"||f.createable===!1||f.nillable!==!1&&l===void 0||f.defaultedOnCreate===!0||f.type==="reference"||(f.referenceTo?.length??0)>0||Ve(e,n.objectApiName,f.name)!=="clear")continue;n.records.some(p=>{if(l!==void 0&&!Gt(l,us(p.fields,!1)))return!1;let g=p.fields[f.name];return g!=null&&g!==""})&&r.push(`${n.objectApiName}.${f.name}`)}let i=n.objectApiName,d=Ur(i,f=>o.some(l=>l.name===f&&l.createable!==!1),f=>Ve(e,i,f)!=="clear"),a=`${i}.${d}`;d!==void 0&&n.records.some(f=>{let l=f.fields[d];return l!=null&&l!==""})&&!r.includes(a)&&r.push(a)}return r.sort()}var Gc="Cleared on review of the extraction result: kept in clear text without a rule before.";function id(s,e){let t=bn(s),r=e.filter(c=>!Qa.test(c));if(r.length>0)throw new Yt('Fields to clear must be named "ObjectApiName.FieldApiName"',r.map(c=>JSON.stringify(c)));let n=s,o={...n.rules},i=[],d=[];for(let c of[...new Set(e)].sort()){if(t.rules[c]!==void 0){d.push(c);continue}o[c]={generator:"clear",comment:Gc},i.push(c)}let a=i.length>0?Wc(t.rulesVersion):t.rulesVersion;return{payload:{...n,rulesVersion:a,rules:o},rulesVersion:a,cleared:i,alreadyRuled:d}}function Wc(s){let[e,t]=s.split(".").map(Number);return`${e}.${t+1}.0`}import*as ad from"node:fs/promises";import*as dd from"node:path";var wo=/\{\{([A-Z][A-Z0-9_]*)\}\}/g,cd=/^[A-Z][A-Z0-9_]*$/,ht=class extends Error{constructor(e){super(e),this.name="QueryTemplateError"}};function Ar(s,e){for(let i of Object.keys(e))if(!cd.test(i))throw new ht(`Invalid token name ${JSON.stringify(i)}`);let t=new Set;for(let i of s.matchAll(wo))t.add(i[1]);let r=[...t].filter(i=>!(i in e));if(r.length>0)throw new ht(`Query template references token(s) without a value: ${r.join(", ")}. Token values (ID lists, date bounds) must be provided from the sas at execution time.`);let n=s.replace(wo,(i,d)=>e[d]),o=n.match(wo);if(o)throw new ht(`Unresolved placeholder(s) after render: ${o.join(", ")}`);return n}async function ld(s,e,t){let n=(t??new te).assertOutsideRepo(dd.join(s,e)),o=JSON.parse(await ad.readFile(n,"utf8"));if(typeof o!="object"||o===null||Array.isArray(o))throw new ht(`Token file ${n} must contain a JSON object`);let i={};for(let[d,a]of Object.entries(o)){if(!cd.test(d))throw new ht(`Invalid token name ${JSON.stringify(d)} in ${n}`);if(typeof a!="string")throw new ht(`Token ${d} in ${n} must be a string`);i[d]=a}return i}var Pr=class extends Error{constructor(){super("Selection stopped"),this.name="SelectionStopped"}};function Bc(s,e){return e?e.aborted?(s.catch(()=>{}),Promise.reject(new Pr)):new Promise((t,r)=>{let n=()=>r(new Pr);e.addEventListener("abort",n,{once:!0}),s.then(o=>{e.removeEventListener("abort",n),t(o)},o=>{e.removeEventListener("abort",n),r(o)})}):s}var Vc=2500,Uc=3,Kc=5;function Hc(s,e){return Object.entries(s).filter(([t,r])=>t!==e&&r>0).sort(([t,r],[n,o])=>o-r||t.localeCompare(n)).slice(0,Kc).map(([t,r])=>({objectApiName:t,count:r}))}var Ft=class extends Error{constructor(t,r,n,o){let i=Hc(t,o),d=i.map(c=>`${c.objectApiName} ${c.count}`),a=i.length>0?`The heaviest: ${d.join(", ")}. Leave out those the dataset does not need with excludedObjects (${JSON.stringify(i.map(c=>c.objectApiName))}), narrow the coverage axes/edge cases, or raise budgetMaxRecords explicitly. `:"Narrow the coverage axes/edge cases or raise budgetMaxRecords explicitly. ";super(`Volumetry budget exceeded: ${r} records measured for a budget of ${n}. ${a}Per-object counts: ${JSON.stringify(t)}`);this.measured=t;this.total=r;this.budgetMax=n;this.name="VolumetryBudgetExceededError",this.heaviest=d}measured;total;budgetMax;heaviest},bo=class extends Error{constructor(e){super(e),this.name="CoverageSelectionError"}},Rn=class{deps;constructor(e){this.deps=e}async select(e,t={}){let r=e.budgetMaxRecords??Vc,n=e.candidatesPerCombination??Uc,o=de(e.rootObject),{signal:i}=t,d=p=>t.onProgress?.(p),a=[],c=[],f=[],l={during:"axes",pending:[]},u=()=>{let p={};for(let h of f)for(let[m,y]of Object.entries(h))p[m]=(p[m]??0)+y;let g=Object.values(p).reduce((h,m)=>h+m,0);if(g>r)throw new Ft(p,g,r,o);return{roots:a,uncovered:c,volumetry:{measured:p,total:g,budgetMax:r,summed:!0},selectedAt:(this.deps.now?.()??new Date).toISOString(),stopped:{reason:i?.reason==="timeout"?"timeout":"cancelled",during:l.during,...l.combinationKey!==void 0?{combinationKey:l.combinationKey}:{},...l.candidate!==void 0?{candidate:l.candidate,candidates:n}:{},notProbed:l.pending}}};try{return await this.run(e,{rootObject:o,budgetMax:r,candidateLimit:n,signal:i,tell:d},{roots:a,uncovered:c,ownMeasures:f,at:l})}catch(p){if(p instanceof Pr)return u();throw p}}async run(e,t,r){let{rootObject:n,budgetMax:o,candidateLimit:i,signal:d,tell:a}=t,{roots:c,uncovered:f,ownMeasures:l,at:u}=r,p=I=>Bc(I,d),g=new Map,h=new Map;for(let I of e.axes)a({phase:"axis",axis:I.name}),g.set(I.name,await p(this.enumerateAxisValues(I,e.tokens))),h.set(I.name,await p(this.deps.fieldType?.(n,I.filterField).catch(()=>{})??Promise.resolve(void 0)));let m=e.axes.length===0?[[]]:Zc(e.axes.map(I=>({axis:I.name,values:g.get(I.name)??[]}))),y=I=>I.length===0?"all":I.map(E=>`${E.axis}=${E.value??"NULL"}`).join("|");u.pending=[...m.map(y),...e.edgeCases.map(I=>`edge:${I.name}`)];let v=async(I,E)=>(u.during="combination",u.combinationKey=I,u.candidate=void 0,u.pending=u.pending.filter(z=>z!==I),this.pickHealthyRoot(n,E,i,e.tokens,{step:p,onCandidate:z=>{u.candidate=z,a({phase:"candidate",combinationKey:I,candidate:z,candidates:i})}}));for(let[I,E]of m.entries()){let z=y(E);a({phase:"combination",combinationKey:z,index:I+1,of:m.length});let O=E.map(k=>{let j=de(e.axes.find(N=>N.name===k.axis)?.filterField??"");return k.value===null?`${j} = NULL`:`${j} = ${Yc(k.value,h.get(k.axis))}`}).join(" AND "),w=await v(z,O),R={};for(let k of E)R[k.axis]=k.value;w.id?(c.push({rootRecordId:w.id,combinationKey:z,axisValues:R}),w.measured&&l.push(w.measured)):f.push({combinationKey:z,reason:ud(w,i)})}for(let[I,E]of e.edgeCases.entries()){let z=`edge:${E.name}`;a({phase:"combination",combinationKey:z,index:I+1,of:e.edgeCases.length});let O=await v(z,`(${E.whereFragment})`);O.id?(c.push({rootRecordId:O.id,combinationKey:z,axisValues:{},edgeCase:E.name}),O.measured&&l.push(O.measured)):f.push({combinationKey:`edge:${E.name}`,reason:O.probed===0?"no record matches the edge-case marker":ud(O,i)})}u.during="measure",u.combinationKey=void 0,u.candidate=void 0,c.length>0&&a({phase:"measure",roots:c.length});let P=c.length===0?{}:await p(this.deps.measureVolumetry(c.map(I=>I.rootRecordId))),S=Object.values(P).reduce((I,E)=>I+E,0);if(S>o)throw new Ft(P,S,o,n);return{roots:c,uncovered:f,volumetry:{measured:P,total:S,budgetMax:o},selectedAt:(this.deps.now?.()??new Date).toISOString()}}async enumerateAxisValues(e,t){let r=Ar(e.valuesSoql,t??{}),n=await this.deps.query(r),o=[];for(let i of n){if(!("axisValue"in i))throw new bo(`Axis "${e.name}" query must alias its grouped value as axisValue (e.g. SELECT ${e.filterField} axisValue, COUNT(Id) cnt ... GROUP BY ${e.filterField})`);let d=i.axisValue;d==null?o.push(null):typeof d=="string"?o.push(d):o.push(String(d))}return[...new Set(o)].sort((i,d)=>(i??"").localeCompare(d??""))}async pickHealthyRoot(e,t,r,n,o){let i=t===""?`SELECT Id FROM ${e} ORDER BY Id ASC LIMIT ${Math.max(1,Math.floor(r))}`:`SELECT Id FROM ${e} WHERE ${t} ORDER BY Id ASC LIMIT ${Math.max(1,Math.floor(r))}`,d=await o.step(this.deps.query(Ar(i,n??{}))),a=0,c;for(let f of d){let l=f.Id;if(typeof l!="string"||l==="")continue;a++,o.onCandidate(a);let u=await o.step(this.deps.checkHealth.check(l));if(u.healthy)return{id:l,probed:a,...u.measured?{measured:u.measured}:{}};c=u.reason}return{id:null,probed:a,lastReason:c}}};function ud(s,e){if(s.probed===0)return"no candidate record";let t=`no healthy candidate among the ${s.probed} probed (limit ${e})`;return s.lastReason?`${t} \u2014 last: ${s.lastReason}`:t}var Jc=new Set(["int","long","double","currency","percent"]);function Yc(s,e){let t=`'${Pe(s)}'`;switch(e){case"boolean":return/^(true|false)$/i.test(s)?s.toLowerCase():t;case"date":return/^\d{4}-\d{2}-\d{2}$/.test(s)?s:t;case"datetime":return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:?\d{2})$/.test(s)?s:t;default:return e!==void 0&&Jc.has(e)&&/^-?\d+(\.\d+)?$/.test(s)?s:t}}function Zc(s){let e=[[]];for(let{axis:t,values:r}of s){let n=[];for(let o of e)for(let i of r)n.push([...o,{axis:t,value:i}]);e=n}return e}var vn=class{constructor(e,t){this.measure=e;this.expectedObjects=t}measure;expectedObjects;async check(e){let t;try{t=await this.measure([e])}catch(r){return{healthy:!1,reason:`extraction failed: ${r instanceof Error?r.message:String(r)}`}}for(let r of this.expectedObjects)if((t[r]??0)===0)return{healthy:!1,reason:`no ${r} record in this dossier`};return{healthy:!0,measured:t}}};import*as Zt from"node:fs/promises";import*as Ro from"node:path";var jr="selection.json";async function fd(s,e,t){let r=t??new te,n=r.assertOutsideRepo(s);await Zt.mkdir(n,{recursive:!0});let o=r.assertOutsideRepo(Ro.join(n,jr));return await Zt.writeFile(o,`${JSON.stringify({fileVersion:1,selection:e},null,2)}
17
- `,"utf8"),o}async function vo(s,e){let r=(e??new te).assertOutsideRepo(Ro.join(s,jr)),n=JSON.parse(await Zt.readFile(r,"utf8"));if(typeof n!="object"||n===null||n.fileVersion!==1||typeof n.selection!="object")throw new Error(`Invalid selection file at ${r} (expected fileVersion 1)`);return n.selection}import*as Xt from"node:fs/promises";import*as Oo from"node:path";var pd="discovery.json",Xc=1440*6e4,Qc=ot({name:je(),fields:vt(ot({name:je(),type:je(),referenceTo:vt(je())}).loose()),childRelationships:vt(ot({childSObject:je(),field:je(),relationshipName:je()}).loose())}).loose(),el=ot({fileVersion:Ho(1),sourceOrgId:je().min(1),rootObject:je().min(1),maxNodes:Bo().int().positive(),step:Ko(["select","extract"]),discoveredAt:Cn.datetime(),schemaStamp:Cn.datetime().optional(),graph:ot({nodes:vt(ot({objectApiName:je(),included:Vo()}).loose()),edges:vt(ot({sourceObject:je(),targetObject:je()}).loose())}).loose(),describes:Uo(je(),Qc),objects:vt(ot({name:je(),keyPrefix:je().nullable()}))});async function gd(s,e,t=new te){let r=t.assertOutsideRepo(s);await Xt.mkdir(r,{recursive:!0});let n=t.assertOutsideRepo(Oo.join(r,pd));return await Xt.writeFile(n,`${JSON.stringify(e)}
18
- `,"utf8"),n}async function hd(s,e=new te){let t=e.assertOutsideRepo(Oo.join(s,pd)),r;try{r=await Xt.readFile(t,"utf8")}catch{return{none:"no graph kept in the sas"}}let n;try{n=JSON.parse(r)}catch{return{none:"the graph kept in the sas could not be read"}}let o=el.safeParse(n);return o.success?{kept:o.data}:{none:"the graph kept in the sas could not be read"}}function md(s,e,t=new Date){if(s.sourceOrgId!==e.sourceOrgId)return"the graph kept is of another org";if(s.rootObject!==e.rootObject)return`the graph kept is of ${s.rootObject}, not ${e.rootObject}`;if(s.maxNodes!==e.maxNodes)return`the graph kept was discovered at a cap of ${s.maxNodes}, not ${e.maxNodes}`;let r=t.getTime()-Date.parse(s.discoveredAt);if(!(r>=0&&r<=Xc))return`the graph kept was discovered on ${s.discoveredAt}, more than a day ago`;if(!s.schemaStamp)return"the org did not give its clock when the graph kept was discovered"}function yd(s){let e=Date.parse(s);if(!Number.isNaN(e))return new Date(Math.floor(e/1e3)*1e3-1e3).toISOString()}import*as kn from"node:fs/promises";import*as wd from"node:path";var tl="SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name FROM RecordType ORDER BY SobjectType, DeveloperName",rl="rt-map.json",nl=10;function ol(s,e){return gr.has(s)?e:e.map(t=>t.type==="reference"&&t.referenceTo.some(r=>gr.has(r))?{...t,nillable:!0}:t)}function Tt(s){if(!("attributes"in s))return s;let e={...s};return delete e.attributes,e}var ko=class{constructor(e){this.keyPrefixes=e}keyPrefixes;prefixes=new Map;known=new Set;fromOrg;learnFrom(e){for(let[t,r]of e){let n=r.keys().next();n.done||this.note(t,n.value.slice(0,3))}}async objectsOf(e,t){return t.length<2?t:(!this.known.has(e.slice(0,3))&&this.keyPrefixes&&(this.fromOrg??=this.keyPrefixes().then(r=>{for(let[n,o]of r)this.prefixes.has(n)||this.note(n,o)},()=>{}),await this.fromOrg),bi(e,t,this.prefixes))}note(e,t){this.prefixes.set(e,t),this.known.add(t)}};function Fr(s,e){return e.filter(t=>t.type==="reference"&&xt(s,t.name,t.nillable)).map(t=>t.name)}function sl(s,e,t){return{objectApiName:s,recordCount:0,fieldCount:e.length,status:"idle",progress:0,included:!0,piiFields:[],anonymizeFields:[],level:t,successCount:0,failureCount:0,errors:[],createableFieldCount:0,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}}var il=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/,On=class extends Error{constructor(e){super(e),this.name="FrozenExtractionError"}},Tr=class{deps;soqlBuilder=new gi;constructor(e){this.deps=e}query(e){return Ts(e,t=>this.deps.query(t))}async extract(e){if(!il.test(e.asOf))throw new On(`asOf must be a strict ISO instant (e.g. 2026-08-03T09:44:52Z), got ${JSON.stringify(e.asOf)}`);if(e.rootRecordIds.length===0)throw new On("No root record IDs provided \u2014 empty selection refused");let t=e.guard??new te,r=t.assertOutsideRepo(e.sasDir),n=`CreatedDate <= ${e.asOf}`,o=new Qn;o.add(e.rootObject,e.rootRecordIds),o.addReached(e.rootObject,e.rootRecordIds);let i=new Map,d=new qt,a=new Set,c={},f=new ko(this.deps.keyPrefixes),l=new Map,u=async R=>{let k=l.get(R);if(k)return k;let j=await this.deps.describeFields(R);return l.set(R,j),j},p=async R=>{let k=await u(R);k.some(N=>N.name==="CreatedDate")||a.add(R);let j=k.filter(N=>N.type==="base64").map(N=>N.name);return j.length>0&&(c[R]=j),k},g=new Set(e.excludedObjects??[]),h=await this.withWhatStatusesNeed(wi(e.graph,g),u,g),m=h.graph,y=[...m.nodes].filter(R=>R.included).sort((R,k)=>R.level-k.level),v=new Set(y.map(R=>R.objectApiName));for(let R of y){let k=await p(R.objectApiName),j=this.selectFields(R.objectApiName,k,e.excludedFields),N=k.some(F=>F.name==="CreatedDate"),$=this.soqlBuilder.build({node:R,fields:ol(R.objectApiName,k),selectFields:j,edges:m.edges,cache:o,rootObjectApiName:`__frozen_root_${e.rootObject}__`,rootRecordId:e.rootRecordIds[0],extraWhere:N?n:void 0,everyEdge:!gr.has(R.objectApiName),readObjects:v,catalog:gr,fromAboveOnly:!0});if(!$.scoped)continue;let B=[],H=[];for(let[F,_]of $.statements.entries()){let U=await this.query(_);if(B.push(...U),!(F<$.byIdCount))for(let ee of U)typeof ee.Id=="string"&&H.push(ee.Id)}let T=d.keep(R.objectApiName,await this.keepWhatStatusesNeed(h.added.get(R.objectApiName),B,i),Fr(R.objectApiName,k)),A=i.get(R.objectApiName);A||(A=new Map,i.set(R.objectApiName,A));let q=[];for(let F of T){let _=F.Id;typeof _!="string"||_===""||(q.push(_),A.has(_)||A.set(_,Tt(F)))}o.addRead(R.objectApiName,q);let J=new Set(q);o.addReached(R.objectApiName,H.filter(F=>J.has(F))),f.learnFrom(i);for(let F of k)if(F.type==="reference")for(let _ of T){let U=_[F.name];if(!(typeof U!="string"||U===""))for(let ee of await f.objectsOf(U,F.referenceTo))o.add(ee,[U])}R.objectApiName===e.rootObject&&await this.readWhatTheRootsName({rootObject:e.rootObject,fields:k,selectFields:j,bucket:A,cache:o,owners:f,recordsByObject:i,leftToThePlatform:d,extraWhere:N?n:void 0})}await this.readWhatNamedStatusesNeed({nodes:y,edges:m.edges,cache:o,recordsByObject:i,describe:p,asOfWhere:n,excludedFields:e.excludedFields,leftToThePlatform:d}),await this.completeRequiredParents({...e,graph:m},i,p,n,f,d,g),await al(i,p,d);let P=await this.addStandardPrices(e,i,n);await this.addSellingModelOptions({...e,graph:m},i,p,n,g);let S=(i.get(Br)?.size??0)>0,I=await this.exclusionCosts(i,p,g,S),E=await this.leaveOutWhatReadsMasked(i,u),z=[...i.entries()].sort(([R],[k])=>R.localeCompare(k)).map(([R,k])=>{let j=[...k.values()].sort(($,B)=>String($.Id).localeCompare(String(B.Id)));R===Je&&(j=Yo(j,{sellingModel:S}));let N=j.map(($,B)=>({referenceId:`${R}-${String(B+1).padStart(6,"0")}`,sourceId:String($.Id),fields:$}));return{objectApiName:R,records:N}}),O=await this.pullRecordTypes(e);await kn.mkdir(r,{recursive:!0});let w=t.assertOutsideRepo(wd.join(r,rl));return await kn.writeFile(w,`${JSON.stringify(O,null,2)}
19
- `,"utf8"),{objects:z,asOf:e.asOf,recordTypeMap:O,unboundedObjects:[...a],fileFields:c,...P?{standardPricebookSourceId:P}:{},leftToThePlatform:d.counts(),...I.length>0?{exclusionCosts:I}:{},...E.length>0?{encryptedNotKept:E}:{}}}async leaveOutWhatReadsMasked(e,t){let r=ri(ti(o=>this.deps.query(o)),async o=>({fields:await t(o)})),n=[];for(let[o,i]of e)if(i.size!==0)for(let d of await r(o)){let a=!1;for(let c of i.values())d in c&&(a||=c[d]!==null&&c[d]!==void 0,delete c[d]);a&&n.push(`${o}.${d}`)}return n.sort()}async withWhatStatusesNeed(e,t,r){let n=new Set(e.nodes.map(a=>a.objectApiName)),o=new Map,i=[],d=[];for(let a of e.nodes){let c=qr[a.objectApiName];if(!a.included||!c||n.has(c.object)||o.has(c.object)||r.has(c.object))continue;let f;try{f=await t(c.object)}catch{continue}let l=f.find(u=>u.name===c.lookup&&u.type==="reference"&&u.referenceTo.includes(a.objectApiName));l&&(o.set(c.object,{parent:a.objectApiName,lookup:l.name}),i.push(sl(c.object,f,a.level+1)),d.push({sourceObject:a.objectApiName,targetObject:c.object,relationshipName:l.name,type:"lookup",required:xt(c.object,l.name,l.nillable)}))}return o.size===0?{graph:e,added:o}:{graph:{...e,nodes:[...e.nodes,...i],edges:[...e.edges,...d]},added:o}}async readWhatTheRootsName(e){let{rootObject:t,bucket:r,cache:n}=e,o=new Set([...n.get(t)??[]].filter(a=>!r.has(a)));if(o.size===0)return;let i=[];for(let a of this.soqlBuilder.buildById({objectApiName:t,selectFields:e.selectFields,ids:o,extraWhere:e.extraWhere}))i.push(...await this.query(a));let d=e.leftToThePlatform.keep(t,i,Fr(t,e.fields));for(let a of d)typeof a.Id=="string"&&!r.has(a.Id)&&r.set(a.Id,Tt(a));e.owners.learnFrom(e.recordsByObject);for(let a of e.fields)if(a.type==="reference")for(let c of d){let f=c[a.name];if(!(typeof f!="string"||f===""))for(let l of await e.owners.objectsOf(f,a.referenceTo))n.add(l,[f])}}async keepWhatStatusesNeed(e,t,r){if(!e)return t;let n=It[e.parent],o=n?await Wt(d=>this.query(d),n):void 0,i=new Set;for(let[d,a]of r.get(e.parent)??[])o&&Bt(a.Status,o)&&i.add(d);return t.filter(d=>{let a=d[e.lookup];return typeof a=="string"&&i.has(a)})}async readWhatNamedStatusesNeed(e){for(let[t,r]of Object.entries(qr)){let n=e.nodes.find(m=>m.objectApiName===r.object),o=e.recordsByObject.get(t),i=It[t];if(!n||!o||o.size===0||!i)continue;let d=e.cache.reachedOf(t),a=[...o].filter(([m])=>!d?.has(m));if(a.length===0)continue;let c=await Wt(m=>this.query(m),i);if(!c)continue;let f=a.filter(([,m])=>Bt(m.Status,c)).map(([m])=>m);if(f.length===0)continue;let l=await e.describe(r.object),u=new Qn;u.addRead(t,f);let p=this.soqlBuilder.build({node:n,fields:l,selectFields:this.selectFields(r.object,l,e.excludedFields),edges:e.edges,cache:u,rootObjectApiName:`__frozen_root_${t}__`,rootRecordId:f[0],extraWhere:l.some(m=>m.name==="CreatedDate")?e.asOfWhere:void 0,under:new Set([t])});if(!p.scoped)continue;let g=e.recordsByObject.get(r.object);g||(g=new Map,e.recordsByObject.set(r.object,g));let h=Fr(r.object,l);for(let m of p.statements){let y=e.leftToThePlatform.keep(r.object,await this.query(m),h);for(let v of y)typeof v.Id=="string"&&!g.has(v.Id)&&g.set(v.Id,Tt(v))}}}async completeRequiredParents(e,t,r,n,o,i,d){let a=new Set(e.graph.nodes.filter(u=>u.included).map(u=>u.objectApiName)),c=yi(e.graph,d),f=u=>a.has(u)||c.has(u),l=new Map;for(let u=0;u<nl;u++){o.learnFrom(t);let p=new Map;for(let[g,h]of t){let m=(await r(g)).filter(y=>y.type==="reference"&&mi(g,y));for(let y of h.values())for(let v of m){let P=y[v.name];if(typeof P!="string"||P===""||i.has(P)||!v.referenceTo.some(f))continue;let S=(await o.objectsOf(P,v.referenceTo)).filter(f);for(let I of S)t.get(I)?.has(P)||l.get(I)?.has(P)||p.set(I,(p.get(I)??new Set).add(P))}}if(p.size===0)return;for(let[g,h]of p){l.set(g,new Set([...l.get(g)??[],...h]));let m=await r(g),y=t.get(g);y||(y=new Map,t.set(g,y));let v=this.soqlBuilder.buildById({objectApiName:g,selectFields:this.selectFields(g,m,e.excludedFields),ids:h,extraWhere:m.some(S=>S.name==="CreatedDate")?n:void 0}),P=Fr(g,m);for(let S of v)for(let I of i.keep(g,await this.query(S),P))typeof I.Id=="string"&&!y.has(I.Id)&&y.set(I.Id,Tt(I))}}}async addStandardPrices(e,t,r){let n=t.get(Je);if(!n||n.size===0)return;let[o]=await this.query(dr),i=typeof o?.Id=="string"?o.Id:void 0;if(!i)return;let d=g=>[Ne,Ce,Vr].map(h=>String(g[h]??"")).join("|"),a=new Set,c=new Set;for(let g of n.values()){if(g[Ot]===i)continue;let h=g[Ne];typeof h=="string"&&h!==""&&(a.add(h),c.add(d(g)))}if(a.size===0)return;let f=async(g,h)=>{let m=await this.deps.describeFields(g),y=this.selectFields(g,m,e.excludedFields).map(P=>de(P)).join(", "),v=m.some(P=>P.name==="CreatedDate")?` AND ${r}`:"";return this.query(`SELECT ${y} FROM ${g} WHERE ${h}${v}`)},l=t.get(Gr);if(l||(l=new Map,t.set(Gr,l)),!l.has(i))for(let g of await f(Gr,`Id = '${Pe(i)}'`))l.set(i,Tt(g));let u=await this.deps.describeFields(Je),p=this.soqlBuilder.buildJoining({objectApiName:Je,selectFields:this.selectFields(Je,u,e.excludedFields),split:{field:Ne,ids:a},whole:{field:Ot,ids:new Set([i])},extraWhere:u.some(g=>g.name==="CreatedDate")?r:void 0});for(let g of p)for(let h of await this.query(g))typeof h.Id!="string"||n.has(h.Id)||c.has(d(h))&&n.set(h.Id,Tt(h));return i}async addSellingModelOptions(e,t,r,n,o){if(o.has(ve)||e.graph.nodes.some(m=>m.objectApiName===ve&&!m.included))return;let i=t.get(Je),d=t.get(hi),a=t.get(Br);if(!i||!d||!a)return;let c=m=>`${String(m[Ne]??"")}|${String(m[Ce]??"")}`,f=new Set,l=new Set,u=new Set;for(let m of i.values()){let y=m[Ne],v=m[Ce];typeof y!="string"||!d.has(y)||typeof v!="string"||!a.has(v)||(f.add(y),l.add(v),u.add(c(m)))}if(u.size===0)return;let p=await r(ve),g=this.soqlBuilder.buildJoining({objectApiName:ve,selectFields:this.selectFields(ve,p,e.excludedFields),split:{field:Ne,ids:f},whole:{field:Ce,ids:l},extraWhere:p.some(m=>m.name==="CreatedDate")?n:void 0}),h=t.get(ve);h||(h=new Map,t.set(ve,h));for(let m of g)for(let y of await this.query(m))typeof y.Id!="string"||h.has(y.Id)||u.has(c(y))&&h.set(y.Id,Tt(y))}async exclusionCosts(e,t,r,n){if(r.size===0)return[];let o=[],i=a=>`record${a===1?"":"s"}`,d=new Map;for(let[a,c]of e){if(c.size===0)continue;let f=(await t(a)).filter(g=>g.type==="reference"&&g.referenceTo.length===1&&g.referenceTo[0]!==a&&r.has(g.referenceTo[0])&&xt(a,g.name,g.nillable)),l=a===Je&&n&&r.has(ve);if(f.length===0&&!l)continue;let u=new Map,p=new Map;for(let[g,h]of c){let m;for(let P of f){let S=h[P.name],I=P.referenceTo[0];if(!(typeof S!="string"||S==="")&&!e.get(I)?.has(S)){m={field:P.name,excluded:I};break}}let y=h[Ce];if(!m&&l&&typeof y=="string"&&e.get(Br)?.has(y)&&(m={field:Ce,excluded:ve}),!m)continue;u.set(g,m.excluded);let v=p.get(m.excluded)??{field:m.field,count:0};v.count++,p.set(m.excluded,v)}u.size>0&&d.set(a,u);for(let[g,{field:h,count:m}]of p)o.push({objectApiName:a,excludedObject:g,count:m,note:g===ve?`${m} ${a} ${i(m)} sold under a selling model cannot be loaded without the option that sells the product under it, and excludedObjects leaves ${g} out`:`${m} ${a} ${i(m)} cannot be loaded without the ${g} named by ${h}, which excludedObjects leaves out`})}for(let[a,c]of Object.entries(qr)){let f=e.get(a),l=It[a];if(!f||f.size===0||!l)continue;let u=await Wt(y=>this.query(y),l);if(!u)continue;let p=new Set,g=new Map,h=d.get(c.object);for(let[y,v]of e.get(c.object)??[]){let P=v[c.lookup];if(typeof P!="string")continue;let S=h?.get(y);S?g.has(P)||g.set(P,S):p.add(P)}let m=new Map;for(let[y,v]of f){if(!Bt(v.Status,u))continue;let P=r.has(c.object)?c.object:p.has(y)?void 0:g.get(y);P&&m.set(P,(m.get(P)??0)+1)}for(let[y,v]of m){let P=v===1;o.push({objectApiName:a,excludedObject:y,count:v,note:`${v} ${a} ${i(v)} past Draft will be loaded as ${P?"a draft":"drafts"} and stay so: `+(y===c.object?`the platform gives ${a} this status only with ${c.object} records under it, and excludedObjects leaves ${c.object} out`:`none of ${P?"its":"their"} ${c.object} records can be loaded without ${y}, which excludedObjects leaves out`)})}}return o}selectFields(e,t,r){let n=new Set(r?.[e]??[]),o=t.map(i=>i.name).filter(i=>!n.has(i));return o.includes("Id")||o.unshift("Id"),o}async pullRecordTypes(e){let t=e.recordTypesSoqlTemplate??tl,r=Ar(t,e.tokens??{}),n=await this.query(r),o=[];for(let i of n)typeof i.Id=="string"&&typeof i.SobjectType=="string"&&typeof i.DeveloperName=="string"&&typeof i.Name=="string"&&o.push({id:i.Id,sobjectType:i.SobjectType,developerName:i.DeveloperName,..."NamespacePrefix"in i?{namespacePrefix:typeof i.NamespacePrefix=="string"&&i.NamespacePrefix!==""?i.NamespacePrefix:null}:{},name:i.Name});return o}};async function al(s,e,t){for(let r=!0;r;){r=!1;for(let[n,o]of s){let i=[...o.values()],d=Fr(n,await e(n)),a=t.keep(n,i,d);if(a.length===i.length)continue;r=!0;let c=new Set(a.map(f=>f.Id));for(let f of o.keys())c.has(f)||o.delete(f)}}}var In=class{anonymize(e){let{rules:t,pseudonymizer:r}=e,n=Object.entries(e.extracted.fileFields??{}).filter(([l,u])=>u.some(p=>Ve(t,l,p)!=="keep")).map(([l])=>l).filter(l=>e.extracted.objects.some(u=>u.objectApiName===l&&u.records.length>0)).sort(),o={...e.extracted,objects:e.extracted.objects.filter(l=>!n.includes(l.objectApiName))},i=new Map;for(let l of o.objects)for(let u of l.records)i.set(u.sourceId,u.referenceId);let d=new Map(o.recordTypeMap.map(l=>[l.id,l])),a={};for(let l of o.objects)a[l.objectApiName]=o.recordTypeMap.filter(u=>u.sobjectType===l.objectApiName).map(u=>({name:u.name,developerName:u.developerName,...u.namespacePrefix!==void 0?{namespacePrefix:u.namespacePrefix}:{}}));let c=[];for(let l of o.objects){let u=l.records.map(p=>{let g=this.anonymizeRecordFields(l.objectApiName,p.fields,i,d,t,r),h=p.fields.RecordTypeId,m=typeof h=="string"?d.get(h):void 0;return{referenceId:p.referenceId,fields:g,...m?{recordTypeDeveloperName:St(m.namespacePrefix,m.developerName)}:{}}});c.push({objectApiName:l.objectApiName,records:u})}let f=o.standardPricebookSourceId?i.get(o.standardPricebookSourceId):void 0;return{datasetVersion:e.datasetVersion,objects:c,recordTypes:a,personContactSidecar:dl(o,i),...f?{standardPricebook:f}:{},...n.length>0?{filesLeftOut:n}:{}}}anonymizeRecordFields(e,t,r,n,o,i){let d={};for(let[a,c]of Object.entries(t)){if(a==="Id")continue;if(c==null){d[a]=c;continue}if(a==="RecordTypeId"&&typeof c=="string"){let l=n.get(c);d[a]=l?l.name:"";continue}if(typeof c=="string"){let l=r.get(c);if(l!==void 0){d[a]=l;continue}}let f=Ve(o,e,a);d[a]=i.pseudonymize(f,c)}for(let[a,c]of Object.entries(d))typeof c=="string"&&Qr(c)&&(d[a]="");return d}};function dl(s,e){let t=[],r=s.objects.find(n=>n.objectApiName==="Account");if(!r)return t;for(let n of r.records){let o=n.fields.PersonContactId;if(typeof o!="string"||o==="")continue;let i=e.get(o);i!==void 0&&t.push({accountReferenceId:n.referenceId,contactReferenceId:i})}return t}var cl=/^[A-Z]{2}-\d{3}-[A-Z]{2}$/,ll=/^\+3363998\d{4}$/,ul=/^[a-z0-9-]+@example\.invalid$/,fl=/^\d{2}0+$/,pl=3,Sn=class{run(e,t,r,n={}){let o=new Set,i=new Map;for(let l of t.objects)for(let u of l.records)o.add(u.referenceId),i.set(u.referenceId,{objectApiName:l.objectApiName,record:u});let d={substitution:[],"clear-empty":[],formats:[],"no-residual-id":[]},a=new Map(e.recordTypeMap.map(l=>[l.id,[l.name,l.developerName]])),c=new Set(t.filesLeftOut??[]);for(let l of e.objects)if(!c.has(l.objectApiName))for(let u of l.records){let p=i.get(u.referenceId);if(!p){d.substitution.push({check:"substitution",objectApiName:l.objectApiName,referenceId:u.referenceId,detail:"record missing from the frozen dataset"});continue}let g=u.fields.RecordTypeId;this.checkSubstitution(l.objectApiName,u,p.record,r,d.substitution,new Set(typeof g=="string"?a.get(g)??[]:[]))}for(let l of t.objects)for(let u of l.records)this.checkClearEmpty(l.objectApiName,u,r,o,d["clear-empty"]),this.checkNoResidualId(l.objectApiName,u,o,d["no-residual-id"]);this.checkFormats(e,t,r,i,d.formats);let f=["substitution","clear-empty","formats","no-residual-id"].map(l=>({name:l,passed:d[l].length===0,violations:d[l]}));return{passed:f.every(l=>l.passed),checks:f,author:n.author??"frozen-dataset-engine",checkedAt:(n.now?.()??new Date).toISOString()}}checkSubstitution(e,t,r,n,o,i){for(let[d,a]of Object.entries(t.fields)){if(d==="Id"||a===null||a===void 0||a===""||Ve(n,e,d)==="keep")continue;let f=r.fields[d];if(gl(f,a)){o.push({check:"substitution",objectApiName:e,referenceId:t.referenceId,field:d,detail:"original value still present in its own field"});continue}if(typeof a=="string"&&a.length>=pl)for(let[l,u]of Object.entries(r.fields))l===d||typeof u!="string"||u!==a||Ve(n,e,l)==="keep"||l==="RecordTypeId"&&i.has(u)||o.push({check:"substitution",objectApiName:e,referenceId:t.referenceId,field:l,detail:`transversal leak: original value of "${d}" found in "${l}"`})}}checkClearEmpty(e,t,r,n,o){for(let[i,d]of Object.entries(t.fields))i!=="RecordTypeId"&&(typeof d=="string"&&n.has(d)||Ve(r,e,i)==="clear"&&d!==""&&d!==null&&d!==void 0&&o.push({check:"clear-empty",objectApiName:e,referenceId:t.referenceId,field:i,detail:`residual value under "clear" generator: ${JSON.stringify(d)}`}))}checkFormats(e,t,r,n,o){let i={registrationSIV:d=>cl.test(d),phoneE164:d=>ll.test(d),email:d=>ul.test(d),postalCodeGeneralize:(d,a)=>fl.test(d)&&d.length===a.trim().length};for(let d of e.objects)for(let a of d.records){let c=n.get(a.referenceId);if(c)for(let[f,l]of Object.entries(a.fields)){if(typeof l!="string"||l==="")continue;let u=Ve(r,d.objectApiName,f),p=i[u];if(!p)continue;let g=c.record.fields[f];typeof g!="string"||g===""||p(g,l)||o.push({check:"formats",objectApiName:d.objectApiName,referenceId:a.referenceId,field:f,detail:`format not conserved for ${u}: ${JSON.stringify(g)}`})}}}checkNoResidualId(e,t,r,n){for(let[o,i]of Object.entries(t.fields))typeof i=="string"&&Qr(i)&&n.push({check:"no-residual-id",objectApiName:e,referenceId:t.referenceId,field:o,detail:"checksum-valid Salesforce ID survived the sweep"})}};function gl(s,e){return s===e?!0:s==null||e===null||e===void 0?!1:String(s)===String(e)}var Er=class{constructor(e){this.orgAccess=e}orgAccess;cache=new Map;describes=new Map;async resolveByDeveloperName(e,t,r,n){let o=n===void 0?zs(r):{namespacePrefix:n,developerName:r},i=`${e}|${t}|${String(o.namespacePrefix)}|${o.developerName}`,d=this.cache.get(i);if(d!==void 0)return d;let a=`SELECT Id, DeveloperName, NamespacePrefix FROM RecordType WHERE SobjectType = '${Pe(t)}' AND DeveloperName = '${Pe(o.developerName)}'`,c=Ls(await this.orgAccess.query(e,a)),f=Ns(o,c,Gn),l;if("ambiguous"in f)l={ambiguous:!0,carriers:f.ambiguous.map(Gn)};else if("found"in f){let u=f.found.id;l=await this.isUnavailable(e,t,u)?{unavailable:!0,id:u}:u}else l=null;return this.cache.set(i,l),l}async isUnavailable(e,t,r){let n=this.describeOf(e,t);return n?(await n).recordTypeInfos?.find(i=>i.recordTypeId===r)?.available===!1:!1}async givenRecordType(e,t){let r=this.describeOf(e,t);if(r)return dn(Xr((await r).recordTypeInfos))}describeOf(e,t){let r=this.orgAccess.describe;if(!r)return;let n=`${e}|${t}`,o=this.describes.get(n);return o||(o=r(e,t),this.describes.set(n,o)),o}};import*as Pn from"node:fs";var hl=2e3,ml=3,yl=10,wl=s=>new Promise(e=>setTimeout(e,s)),An=class{constructor(e){this.deps=e;this.sasGuard=e.sasGuard??new te}deps;sasGuard;personAccounts=new Map;async verify(e){let t=e.now??(()=>new Date),r=e.sleep??wl,n=g=>e.onProgress?.(g),o=e.measurementIntervalMs??hl,i=e.maxAttempts??ml,d=gn(this.sasGuard,e.contractPath);n({phase:"verify",status:"started",progress:0,message:"Measuring org state"});let a=null,c=null,f=null,l=0;for(let g=1;g<=i;g++){l=g,f=await this.measure(e,d);let h=Io(f);if(a!==null&&h===a){c=f;break}a=h,g<i&&await r(o)}let u=this.buildChecks(e,d,c??f,c!==null),p={status:Il(u,d,c),checks:u,attempts:l,measuredAt:t().toISOString(),objects:Sl(d,c??f)};return e.manifestPath&&(this.consignVerdict(e.manifestPath,p,e.author),p.manifestPath=this.sasGuard.assertOutsideRepo(e.manifestPath)),n({phase:"verify",status:p.status==="passed"?"done":"error",progress:100,message:`Post-load verification: ${p.status} (${l} measurement(s))`}),p}async measure(e,t){return{counts:await this.measureCounts(e,t),orphans:await this.measureOrphans(e,t),personContact:await this.measurePersonContacts(e),presence:await this.measurePresence(e,t)}}async measureCounts(e,t){let r=e.mapping?vd(e.mapping):void 0,n={};for(let o of Object.keys(t.objects).sort()){let i=`SELECT COUNT() FROM ${de(o)}`;if(!r){n[o]=await this.deps.orgAccess.count(e.orgId,i);continue}let d=0;for(let a of Od(r.get(o)??[]))d+=await this.deps.orgAccess.count(e.orgId,`${i} WHERE ${a}`);n[o]=d}return n}async measureOrphans(e,t){let r={},n=e.orphanSampleSize??yl,o=e.mapping?vd(e.mapping):void 0;for(let[i,d]of Object.entries(e.mandatoryLookups??{}))for(let a of d){let c=new Set([...bd(t,i,a),...So(t.objects[i]?.parentNotLoaded,a)].flatMap(u=>{let p=e.mapping?.get(u);return p===void 0?[]:[p]})),f=o?Od((o.get(i)??[]).filter(u=>!c.has(u))):[""],l=[];for(let u of f){let p=`SELECT Id FROM ${de(i)} WHERE ${de(a)} = null${u?` AND ${u}`:""} ORDER BY Id LIMIT ${n}`,g=await this.deps.orgAccess.query(e.orgId,p);l.push(...g.map(h=>String(h.Id)))}r[`${i}.${a}`]=l.sort().slice(0,n)}return r}async measurePersonContacts(e){let t=e.dataset?.personContactSidecar??[];if(t.length===0||!e.mapping)return{checked:0,unrestored:[]};let r=t.filter(f=>e.mapping?.has(f.accountReferenceId));if(r.length===0||!await this.describesPersonAccounts(e.orgId))return{checked:0,unrestored:[]};let o="SELECT Id, PersonContactId FROM Account WHERE Id IN ("+r.map(f=>e.mapping?.get(f.accountReferenceId)).map(f=>`'${Pe(f)}'`).join(", ")+")",i=await this.deps.orgAccess.query(e.orgId,o),d=new Map(i.map(f=>[String(f.Id),f.PersonContactId===null||f.PersonContactId===void 0?null:String(f.PersonContactId)])),a=[],c=0;for(let f of r){let l=e.mapping.get(f.accountReferenceId),u=d.get(l);u!=null&&(c++,e.mapping.get(f.contactReferenceId)!==u&&a.push(f.accountReferenceId))}return{checked:c,unrestored:a.sort()}}describesPersonAccounts(e){let t=this.personAccounts.get(e);if(!t){let r=this.deps.orgAccess.describe;t=r?r.call(this.deps.orgAccess,e,"Account").then(n=>n.fields.some(o=>o.name==="PersonContactId")).catch(()=>!0):Promise.resolve(!0),this.personAccounts.set(e,t)}return t}async measurePresence(e,t){let r={};if(!e.dataset)return r;for(let[n,o]of Object.entries(e.presenceKeys??{})){let i=new Set(bd(t,n,o)),d=(e.dataset.objects.find(u=>u.objectApiName===n)?.records??[]).filter(u=>!i.has(u.referenceId)),a=[...new Set(d.map(u=>u.fields[o]).filter(u=>typeof u=="string"&&u!==""))].sort();if(a.length===0){r[n]=[];continue}let c=`SELECT ${de(o)} k FROM ${de(n)} WHERE ${de(o)} IN (${a.map(u=>`'${Pe(u)}'`).join(", ")})`,f=await this.deps.orgAccess.query(e.orgId,c),l=new Set(f.map(u=>String(u.k)));r[n]=a.filter(u=>!l.has(u))}return r}buildChecks(e,t,r,n){let o=[];if(o.push({name:"stability",passed:n,detail:n?"Two identical consecutive measurements \u2014 org reads are stable":"No two identical measurements within the attempt budget \u2014 org reads are transiently inconsistent"}),!r)return o;let i=Object.entries(t.objects).filter(([u,p])=>r.counts[u]!==p.expected).map(([u,p])=>`${u}: expected ${p.expected}, got ${r.counts[u]??0}`);o.push({name:"counts",passed:i.length===0,detail:i.length===0?"All object counts match the counting contract":`Count mismatches \u2014 ${i.join("; ")}`});let d=kd(t),a=bl(t,r);o.push({name:"load",passed:d.records===0&&a.length===0,detail:vl(d,a)});let c=Object.entries(r.orphans).filter(([,u])=>u.length>0),f=kl(t),l=[...c.length>0?[`Orphans \u2014 ${c.map(([u,p])=>`${u} (${p.length}: ${p.join(", ")})`).join("; ")}`]:[],...f.length>0?["Lookups the load left empty because the record they name was not loaded \u2014 "+f.map(({link:u,count:p})=>`${u} (${p})`).join("; ")]:[]];if(o.push({name:"orphans",passed:l.length===0,detail:l.length===0?"No orphans on the mandatory lookups of the graph":l.join("; ")}),(e.dataset?.personContactSidecar?.length??0)>0&&e.mapping&&o.push({name:"personcontact",passed:r.personContact.unrestored.length===0,detail:r.personContact.unrestored.length===0?`All ${r.personContact.checked} person account(s) hold the contact the load linked`:`Person accounts without the contact the load linked \u2014 accounts: ${r.personContact.unrestored.join(", ")}`}),e.dataset&&Object.keys(e.presenceKeys??{}).length>0){let u=Object.entries(r.presence).filter(([,p])=>p.length>0);o.push({name:"presence",passed:u.length===0,detail:u.length===0?"All referential keys present in the org":`Missing keys \u2014 ${u.map(([p,g])=>`${p}: ${g.join(", ")}`).join("; ")}`})}return o}consignVerdict(e,t,r){let n=this.sasGuard.assertOutsideRepo(e),o=Vt(JSON.parse(Pn.readFileSync(n,"utf8")));o.controls.dryRunLoad={status:t.status==="passed"?"passed":"failed",at:t.measuredAt,detail:`post-load check by ${r??"unknown"}: verdict=${t.status}; `+t.checks.map(i=>`${i.name}=${i.passed?"OK":"KO"}`).join(", ")},Pn.writeFileSync(n,ua(o),"utf8")}};function Io(s){return Array.isArray(s)?`[${s.map(Io).join(",")}]`:typeof s=="object"&&s!==null?`{${Object.entries(s).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${Io(r)}`).join(",")}}`:JSON.stringify(s)}function bd(s,e,t){return So(s.objects[e]?.writtenWithout,t)}function So(s,e){let t=s?.[e];return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}var Lr={refused:["dml-failed","person-contact-not-sent"],heldBack:["parent-refused"],notLoadable:["object-not-loaded"]};function kd(s){let e={whole:[],part:[],refused:0,heldBack:0,notLoadable:[],records:0};for(let[t,r]of Object.entries(s.objects).sort(([n],[o])=>n.localeCompare(o))){let n=c=>c.reduce((f,l)=>f+(r.exclusionReasons[l]??0),0),o=n(Lr.notLoadable);o>0&&e.notLoadable.push({objectApiName:t,records:o});let i=n(Lr.refused),d=n(Lr.heldBack),a=i+d;a!==0&&(e.refused+=i,e.heldBack+=d,e.records+=a,r.expected===0?e.whole.push({objectApiName:t,notLoaded:a}):e.part.push({objectApiName:t,notLoaded:a,of:a+r.expected}))}return e}function bl(s,e){return Object.entries(s.objects).sort(([t],[r])=>t.localeCompare(r)).flatMap(([t,r])=>{let n=e.counts[t]??0;return n<r.expected?[{objectApiName:t,gone:r.expected-n,of:r.expected}]:[]})}function Rl(s){return s.length===0?"":`${s.reduce((t,r)=>t+r.gone,0)} record(s) it wrote or linked are no longer in the target \u2014 `+s.map(t=>`${t.objectApiName} (${t.gone} of ${t.of})`).join(", ")}function vl(s,e=[]){let t=Ol(s),r=Rl(e);if(s.records===0)return r===""?`Every record the load had to write went in${t}`:`The load wrote every record it had to, and ${r}${t}`;let n=[...s.whole.length>0?["Objects the load wrote none of \u2014 "+s.whole.map(i=>`${i.objectApiName} (${i.notLoaded} not loaded)`).join(", ")]:[],...s.part.length>0?["Objects it wrote part of \u2014 "+s.part.map(i=>`${i.objectApiName} (${i.notLoaded} of ${i.of} not loaded)`).join(", ")]:[]],o=[...s.refused>0?[`${s.refused} refused by the target org`]:[],...s.heldBack>0?[`${s.heldBack} held back for a parent the target org refused`]:[]];return`${s.records} record(s) not loaded: ${o.join(", ")}. ${n.join("; ")}${r===""?"":`; ${r}`}${t}`}function Ol(s){return s.notLoadable.length===0?"":`; ${s.notLoadable.reduce((t,r)=>t+r.records,0)} record(s) not loadable, as the preview said \u2014 `+s.notLoadable.map(t=>`${t.objectApiName} (${t.records})`).join(", ")}function kl(s){let e=[];for(let[t,r]of Object.entries(s.objects).sort(([n],[o])=>n.localeCompare(o)))for(let n of Object.keys(r.parentNotLoaded??{}).sort()){let o=So(r.parentNotLoaded,n).length;o>0&&e.push({link:`${t}.${n}`,count:o})}return e}function Il(s,e,t){if(t===null)return"unstable";let r=s.filter(i=>!i.passed);if(r.length===0)return"passed";let n=Object.values(t.orphans).some(i=>i.length>0);return r.every(i=>i.name==="load"||i.name==="orphans")&&!n&&kd(e).whole.length===0?"partial":"failed"}function Sl(s,e){let t=r=>r.slice(0,r.indexOf("."));return Object.entries(s.objects).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>{let o=[...Lr.refused,...Lr.heldBack].reduce((l,u)=>l+(n.exclusionReasons[u]??0),0),i=e?.counts[r]??0,d=Object.entries(e?.orphans??{}).filter(([l])=>t(l)===r).reduce((l,[,u])=>l+u.length,0),a=e?.presence[r]?.length??0,c=r==="Account"?e?.personContact.unrestored.length??0:0,f=e!==null&&i===n.expected&&o===0&&d===0&&a===0&&c===0;return{objectApiName:r,status:f?"passed":"failed",expected:n.expected,found:i,notLoaded:o,orphans:d,missingKeys:a,...c>0?{personContactsUnlinked:c}:{}}})}var Rd=200;function vd(s){let e=new Map;for(let[t,r]of s){let n=t.startsWith("placeholder:")?t.split(":")[1]:t.slice(0,t.lastIndexOf("-"));if(!n)continue;let o=e.get(n)??[];o.push(r),e.set(n,o)}return e}function Od(s){let e=[];for(let t=0;t<s.length;t+=Rd){let r=s.slice(t,t+Rd).map(n=>`'${Pe(n)}'`);e.push(`Id IN (${r.join(", ")})`)}return e}var Po=200;function jo(s,e=Po){return{insert:(t,r,n,o)=>Ao(s.insert(r,n,e,o?Al(o):void 0)),update:(t,r,n)=>Ao(s.update(r,n,e)),delete:(t,r,n)=>Ao(s.delete(r,n,e))}}function Al(s){let e=0,t=0;return{sending:(r,n,o)=>{t=o},answered:(r,n,o,i)=>{i?o.forEach((d,a)=>{let c=i[a];c!==void 0&&s(c,[d])}):(s(e,o),e+=t),t=0}}}async function Ao(s){try{return await s}catch(e){if(e instanceof sa)return e.written;throw e}}var Pl=200;function Id(s){let e={threshold:s.threshold,perCall:Po,...s.duplicateRules?{duplicateRules:s.duplicateRules}:{}},t=s.inserts.filter(({rows:n})=>n>0),r=t.reduce((n,{rows:o})=>n+Math.ceil(o/Pl),0);return ro(t,e)+ro((s.purged??[]).filter(({rows:n})=>n>0),e)+aa(t.length,s.automationRead??0)+r}var jl={insert:async()=>{throw new Error("A preview writes nothing.")},update:async()=>{throw new Error("A preview writes nothing.")},delete:async()=>{throw new Error("A preview writes nothing.")}},Fl=new Set(["frozen:config:get","frozen:config:save","frozen:select","frozen:extract","frozen:manifest:get","frozen:load","frozen:load:preview","frozen:verify","frozen:remove","frozen:remove:sweep","frozen:remove:automation","frozen:remove:preview","frozen:status","frozen:rules:clear","frozen:rules:create"]),jn="REPLACE_LEAVES_RECORDS",er=class extends Error{constructor(t){super(t.message);this.stop=t;this.name="RemovalStopped"}stop;get code(){return this.stop.code}},tr=class extends Error{constructor(t,r,n,o){super(r);this.code=t;this.emails=n;this.orgId=o;this.name="LoadEmailsStop"}code;emails;orgId},Cr=class extends Error{constructor(t,r,n,o){super(r);this.code=t;this.automation=n;this.orgId=o;this.name="LoadAutomationStop"}code;automation;orgId},Dr=class extends Error{constructor(t,r,n){super(t);this.apiRequests=r;this.orgId=n;this.name="LoadBudgetStop"}apiRequests;orgId;code=Zn},Md="FROZEN_STORAGE_EXCEEDED",Mr=class extends Error{constructor(t,r,n){super(t);this.storage=r;this.orgId=n;this.name="LoadStorageStop"}storage;orgId;code=Md};function Sd(s){let e=s<10?100:10;return String(s<=0?0:Math.ceil(s*e-1e-9)/e)}function xd(s){if("unread"in s.storage)return;let e=s.dataset.objects.reduce((i,d)=>i+Jn(d.objectApiName,{rows:d.records.length}),0),t=(s.purged??[]).filter(i=>i.deletes).reduce((i,d)=>i+Jn(d.objectApiName,{rows:d.rows}),0),r=1024*1024,{remainingMB:n,maxMB:o}=s.storage;return{storage:{estimateMB:e/r,remainingMB:n,maxMB:o,...t>0?{freedMB:t/r}:{}},fits:e<=n*r+t}}function Tl(s){let e=xd(s);if(!e)return;let t=$d(s);return{...e.storage,...t?{refusal:{code:Md,message:t.message}}:{}}}function $d(s){let e=xd(s);if(!e||e.fits)return;let{storage:t}=e,{remainingMB:r,maxMB:n}=t,o=t.freedMB!==void 0?`, and the reload's purge frees about ${Sd(t.freedMB)} MB first`:"";return{storage:t,message:`The load was refused before it wrote anything: the dataset's records take about ${Sd(t.estimateMB)} MB of data storage, and ${s.target} has ${r} MB left of ${n} MB${o}. Load a pilot first, one root folder of it; or extract a smaller dataset, with a lower budget in the configuration, a new selection and a new extraction; or free data storage in ${s.target}. Nothing was written.`}}function El(s,e){let t=Ii(s,e);return{verdict:s.verdict,estimate:s.estimate,...s.verdict==="unread"?{unread:s.unread}:{remaining:s.remaining,max:s.max},...s.parts?{parts:{...s.parts}}:{},...t!==void 0?{refused:{code:Zn,message:t}}:{}}}function zr(s,e){let t=[...new Set(s.map(r=>r.objectApiName))];return rs({setToDraft:Us(t),delete:Js(t)},e)}function Fo(s){return s.status==="success"&&(s.left??[]).length===0}function Ad(s){return s.verdict!=="nothingSends"||s.counted.length>0||s.uncounted!==void 0}function Ll(s,e){if(e.includeChanged||s.refusal!==void 0||s.status!=="partial"&&s.status!=="failure")return s;let t=s.objects.every(o=>o.refused===0&&o.deleted+o.alreadyGone+o.keptChanged===o.found),r=(s.left??[]).some(o=>o.class==="late"&&e.sweepLate||o.class==="untied"&&e.sweepUntied),n=s.objects.some(o=>o.keptChanged>0);return t&&!r&&n?{...s,status:"success"}:s}var Nr="frozen",Pd="frozen:config",Qt="frozen:lastRun",jd="frozen:lastRuns",To="frozen:lastVerify",Eo="frozen:lastVerifies",Fd="tokens.json",zl="rules.json",rr=class extends Error{constructor(t,r){super(r);this.rulesPath=t;this.name="RulesFileMissingError"}rulesPath},Nl=async s=>{let e=await import("vscode");await e.window.showTextDocument(e.Uri.file(s),{preview:!1})},Cl="0.1.0",Dl=10*6e4,Lo=15*6e4,Ml="EXTRACT_TIMEOUT",Td=30*6e4,zo=6e4,Ed=12e4,xl=50;function $l(s,e){let t=0,r=null,n=null,o=d=>{s(...d),t=Date.now(),r=null},i=((...d)=>{r=d;let a=e-(Date.now()-t);a<=0?(n&&(clearTimeout(n),n=null),o(d)):n||(n=setTimeout(()=>{n=null,r&&o(r)},a))});return i.flush=()=>{n&&(clearTimeout(n),n=null),r&&o(r)},i}function Ld(s,e){let t=$l(s,e);return Object.assign(n=>{if(n.status==="started"){t(n);return}t.flush(),s(n)},{flush:t.flush})}async function We(s){try{return await le.access(s),!0}catch{return!1}}function _l(s){return s.check==="clear-empty"?'residual value under "clear" generator (value redacted at the bridge)':s.detail.length>200?`${s.detail.slice(0,200)}\u2026`:s.detail}function _d(s){return{passed:s.passed,author:s.author,checkedAt:s.checkedAt,checks:s.checks.map(e=>({name:e.name,passed:e.passed,violations:e.violations.slice(0,xl).map(t=>({check:t.check,objectApiName:t.objectApiName,referenceId:t.referenceId,field:t.field,detail:_l(t)}))}))}}function No(s){return{version:s.version,status:s.status,frozenAt:s.frozenAt,source:s.source,saltFingerprint:s.saltFingerprint,rulesVersion:s.rulesVersion,volumetry:s.volumetry,controls:{nonReidentification:_d(s.controls.nonReidentification),dryRunLoad:s.controls.dryRunLoad,author:s.controls.author,date:s.controls.date},...s.coverage?{coverage:s.coverage}:{}}}function ql(s,e,t){return{combinations:s.roots.map(r=>({combinationKey:r.combinationKey,axisValues:r.axisValues,edgeCase:r.edgeCase})),uncovered:s.uncovered,volumetry:s.volumetry,selectedAt:s.selectedAt,selectionPath:e,...t?{graph:t}:{},...s.stopped?{stopped:s.stopped}:{}}}function Co(s,e){if(!e||e.length===0)return s;let t=new Set(e);return{...s,nodes:s.nodes.map(r=>t.has(r.objectApiName)?{...r,included:!1}:r)}}function zd(s,e){return{objects:s.nodes.filter(Gi).length,truncated:s.truncated===!0,maxNodes:e}}function Gl(s){return s.length===0?"":` Kept in the org, the platform does not delete them: ${s.map(({objectApiName:t,count:r})=>`${t} (${r})`).join(", ")}.`}function Do(s,e){if(!s)return{message:"No load into this org was recorded in this sas: there is nothing to remove.",code:"NO_LOAD"};if(s.orgId!==e.targetOrgId||s.endedAt!==e.loadedAt)return{message:"Another load was recorded since this one was shown, and nothing was removed: check what a removal takes now, then confirm it again.",code:"LOAD_CHANGED"};if(!s.created)return{message:"This load was recorded before loads kept what they created: its records cannot be told from the ones it linked, and cannot be removed from here, nor replaced by a reload, which would delete what someone changed since. Refresh the sandbox to start again from its copy, or find the records the loading user created that day and delete them yourself.",code:"NOT_RECORDED"};if(_e(s).length>0)return;let t=Gl(un(s));return s.removal?{message:`The records this load created were already removed, on ${s.removal.removedAt}.${t}`,code:"ALREADY_REMOVED"}:t?{message:`This load created no record a removal takes.${t}`,code:"NOTHING_TO_REMOVE"}:{message:"This load created no record to remove.",code:"NOTHING_TO_REMOVE"}}function Mo(s){let e=s.writtenBetween,t=s.startedAt===void 0?Number.NaN:Date.parse(s.startedAt),r=Date.parse(s.endedAt);return{...e?{runStartedAt:new Date(e.first),runEndedAt:new Date(e.last)}:{...Number.isFinite(t)&&Number.isFinite(r)?{runDurationMs:Math.max(0,r-t)}:{},...Number.isFinite(r)?{runRecordedAt:new Date(r),endedByItsWrites:!0}:{}},removalStamps:s.removalStamps,removalSpans:s.removalSpans,...s.runUserId?{runUserId:s.runUserId}:{}}}function Wl(s,e=!1){let t=new Map;for(let{objects:r}of s)for(let n of r){let o=n.heldByAutomation??0,i=(n.keptDependents??0)-(e?o:0),d=n.heldBy&&n.heldBy.length>0?n.heldBy.join(", "):"",a=[n.keptChanged>0?`${n.keptChanged} changed since the load`:"",i>0?(d?`${i} kept for records that stay under them (${d})`:`${i} kept as what hangs from them could not be read`)+(!e&&o>0?`, ${o} of them for what the target's automation likely made for the load, which a sweep takes first`:""):"",n.undeletable>0?`${n.undeletable} the user may not delete`:"",n.notVisible>0?`${n.notVisible} out of the user's sight`:"",n.unread>0?`${n.unread} that could not be read`:""].filter(Boolean),c=n.keptChanged+Math.max(0,i)+n.undeletable+n.notVisible+n.unread;if(c===0)continue;let f=t.get(n.objectApiName)??{left:0,why:new Set};f.left+=c;for(let l of a)f.why.add(l);t.set(n.objectApiName,f)}return[...t].map(([r,{left:n,why:o}])=>({objectApiName:r,left:n,why:[...o]}))}function Bl(s){return{status:s.status,orgId:s.orgId,mode:s.mode,startedAt:s.startedAt,durationMs:s.durationMs,alignment:{excludedObjects:s.alignment.excludedObjects,removals:s.alignment.removals,adjustments:s.alignment.adjustments,recordTypeIssues:s.alignment.recordTypeIssues},placeholders:s.placeholders,requiredDefaults:s.requiredDefaults,perObject:s.perObject,pass2:s.pass2,personContact:s.personContact,statuses:s.statuses,purge:s.purge,...s.leftToThePlatform?{leftToThePlatform:s.leftToThePlatform}:{},...s.untypedFeedItems?{untypedFeedItems:s.untypedFeedItems}:{},...s.heldForExcludedParents?{heldForExcludedParents:s.heldForExcludedParents}:{},...s.quotesLeftUnsynced?{quotesLeftUnsynced:s.quotesLeftUnsynced}:{},...s.keysLeftEmpty?{keysLeftEmpty:s.keysLeftEmpty}:{},...s.recordTypesGiven?{recordTypesGiven:s.recordTypesGiven}:{},...s.runUserId?{runUserId:s.runUserId}:{},mappingPath:s.mappingPath,contractPath:s.contractPath}}function Vl(s){return s.status==="completed"?"success":s.perObject.reduce((t,r)=>t+r.inserted+r.reused,0)>0?"partial":"failure"}function Ul(s){let e=s.perObject.reduce((t,r)=>t+r.failed.length,0)+s.purge.failures.length;return Tn(s)===0&&e===0?"stopped":"cancelled"}function Tn(s){let e=t=>Object.values(t).reduce((r,n)=>r+n,0);return s.perObject.reduce((t,r)=>t+r.inserted,0)+s.placeholders.length+e(s.purge.deleted)+e(s.purge.deactivated)}function Nd(s){return`frozen:${s}`}var Fn=(s,e)=>e==="insert"||e==="update",Et=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointFirstStop"}code};function xo(s){let e=new Map,t=r=>{let n=e.get(r)??Ss(r);return e.set(r,n),n};for(let r of s.perObject){let n=t(r.objectApiName);n.created+=r.inserted,n.failed+=r.failed.length+r.skippedDuplicates.length,r.notInserted&&(n.notSent=(n.notSent??0)+r.notInserted),r.writtenWithoutFields&&(n.writtenWithoutFields=(n.writtenWithoutFields??0)+r.writtenWithoutFields.rows)}for(let r of s.placeholders)t(r.placeholderObjectApiName).created+=1;for(let[r,n]of Object.entries(s.purge.deleted))t(r).deleted+=n;for(let[r,n]of Object.entries(s.purge.deactivated))t(r).updated+=n;for(let r of s.purge.failures)t(r.objectApiName).failed+=1;return[...e.values()]}async function Kl(s,e){try{let t=await e.load();return Object.fromEntries(s.objects.map(r=>[r.objectApiName,r.records.filter(n=>t.has(n.referenceId)).length]))}catch{return}}var Cd=class{constructor(e){this.deps=e}deps;registry;liveTracker;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;saltKeeper=Va();openInEditor=Nl;otherModuleRuns=()=>Promise.resolve([]);removing=new Set;writing=new ai;loading=new Map;beforeRunCheckpoints;describeCache=new eo({defaultTtl:5*6e4,maxSize:2e3,maxSizeBytes:200*1024*1024,releaseExpired:!0});describeGlobalCache=new eo({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});forgetOrg(e){this.describeCache.invalidateByPrefix(`${e}::`),this.describeGlobalCache.invalidate(e)}setRegistry(e){this.registry=e}setRulesEditor(e){this.openInEditor=e}setLiveOperationTracker(e){this.liveTracker=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}muteLeases={};setMuteOffered(e){this.muteOffered=e}muteOffered=!0;setRemovalAsker(e){this.removalAsker=e}removalAsker;ownReader(){return this.reader??=import("./chunk-7YDNUBO5.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>ue(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}setSaltKeeper(e){this.saltKeeper=e}isWritingTo(e,t){if(this.writing.has(e))return!0;for(let[r,n]of this.loading)if(n===e&&(t===void 0||t!==Nd(r)))return!0;return!1}async loadingDuring(e,t){let r=rn(e,"targetOrgId");if(r===void 0)return t();this.loading.set(e.id,r);try{await t()}finally{this.loading.delete(e.id)}}async handle(e){if(!Fl.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"frozen:config:get":return this.handleConfigGet(e),!0;case"frozen:config:save":return this.handleConfigSave(e),!0;case"frozen:select":return await this.handleSelect(e),!0;case"frozen:extract":return await this.handleExtract(e),!0;case"frozen:manifest:get":return await this.handleManifestGet(e),!0;case"frozen:load":return await this.loadingDuring(e,()=>this.handleLoad(e)),!0;case"frozen:load:preview":return await this.handlePreview(e),!0;case"frozen:verify":return await this.handleVerify(e),!0;case"frozen:remove":return await this.writing.during(rn(e,"targetOrgId"),()=>this.handleRemove(e)),!0;case"frozen:remove:sweep":return await this.writing.during(rn(e,"targetOrgId"),()=>this.handleRemoveSweep(e)),!0;case"frozen:remove:automation":return await this.handleRemoveAutomation(e),!0;case"frozen:remove:preview":return await this.handleRemovePreview(e),!0;case"frozen:status":return await this.handleStatus(e),!0;case"frozen:rules:clear":return await this.handleRulesClear(e),!0;case"frozen:rules:create":return await this.handleRulesCreate(e),!0;default:return!1}}loadConfig(){return this.deps.configStore.get(Pd)??null}handleConfigGet(e){let t=this.loadConfig(),r=ce(this.deps,e,"frozen:config:get:response",{config:t,sasDir:this.resolveSasDir(t),datasetDir:this.resolveDatasetDir(t)});this.deps.broker.postToWebview(r)}handleConfigSave(e){let t=$e(Cs,e,"frozen:config:save:error",this.deps);if(!t)return;this.deps.configStore.set(Pd,t.config,Nr);let r=ce(this.deps,e,"frozen:config:save:response",{success:!0});this.deps.broker.postToWebview(r)}resolveSasDir(e){return e?.sasDir??fe.join(Dd.homedir(),".sandforge-sas")}resolveDatasetDir(e){return e?.datasetDir??fe.join(this.resolveSasDir(e),"dataset")}resolveRulesPath(e){return fe.resolve(e?.rulesFilePath??fe.join(this.resolveSasDir(e),zl))}async rulesFileInfo(e){let t=this.resolveRulesPath(e),r=null;try{r=await We(t)?await le.readFile(t,"utf8"):null}catch(n){return{path:t,found:!0,invalid:K(n)}}return{path:t,...rd(r)}}async loadTokens(e,t){return await We(fe.join(e,Fd))?ld(e,Fd,t):{}}async describeObject(e,t){let r=`${e}::${t}`,n=this.describeCache.get(r);if(n)return n;let o=await new pt(3e4).withTimeout(`frozen:describe:${t}`,async()=>{let d=await(await ue(e,this.deps.orgRegistry,this.deps.orgManager)).describe(t);return{name:d.name,fields:d.fields.map(a=>({name:a.name,label:a.label,type:a.type,referenceTo:a.referenceTo??[],relationshipName:a.relationshipName??null,isMasterDetail:a.cascadeDelete===!0,nillable:a.nillable!==!1,createable:a.createable!==!1,updateable:a.updateable!==!1,restrictedPicklist:a.restrictedPicklist===!0,defaultedOnCreate:a.defaultedOnCreate===!0,...a.compoundFieldName?{compoundFieldName:a.compoundFieldName}:{}})),childRelationships:(d.childRelationships??[]).map(a=>({childSObject:a.childSObject,field:a.field,relationshipName:a.relationshipName??a.field,isCascadeDelete:a.cascadeDelete===!0}))}},3e4);return this.describeCache.set(r,o),o}buildDiscoveryService(){return new Wi({describeObject:(e,t)=>this.describeObject(e,t),queryCount:async(e,t)=>(await(await ue(e,this.deps.orgRegistry,this.deps.orgManager)).query(t)).totalSize,detectPII:e=>{let t=this.deps.infraServices?.piiDetector;return t?ni(t,e):[]},describeGlobal:e=>this.describeGlobal(e)})}async describeGlobal(e){let t=this.describeGlobalCache.get(e);if(t)return t;let o=(await(await ue(e,this.deps.orgRegistry,this.deps.orgManager)).describeGlobal()).sobjects.map(i=>({name:i.name,keyPrefix:i.keyPrefix??null}));return this.describeGlobalCache.set(e,o),o}async keyPrefixes(e){let t=new Map;for(let{name:r,keyPrefix:n}of await this.describeGlobal(e))n&&t.set(r,n);return t}discoveryConfig(e,t){return{inputMode:"record",recordId:t,depth:"full",sourceOrgId:e,targetOrgId:e,anonymizePII:!1,skipEmpty:!0,batchSize:"auto"}}discoveryOptions(e){return{maxNodes:e.maxNodes??qi}}async graphOfStep(e){let{sourceOrgId:t,config:r,sasDir:n,guard:o}=e,{maxNodes:i}=this.discoveryOptions(r),d={sourceOrgId:t,rootObject:r.rootObject,maxNodes:i},a=await hd(n,o),c;if("kept"in a){let p=a.kept,g=md(p,d)??await this.schemaChangeSince(t,p);if(g===void 0)return this.holdKeptDescribes(t,p),{graph:p.graph,origin:{reusedFrom:p.step,discoveredAt:p.discoveredAt}};c=g}else c=a.none;let f;try{let p=await ue(t,this.deps.orgRegistry,this.deps.orgManager);f=yd((await p.soap.getServerTimestamp()).timestamp)}catch(p){this.deps.log(`[WARN] frozen: the source did not give its clock: ${String(p)}`)}let l=await this.buildDiscoveryService().discover(this.discoveryConfig(t,e.rootRecordId),{maxNodes:i,...e.signal?{signal:e.signal}:{},...e.onProgress?{onProgress:e.onProgress}:{}}),u=new Date().toISOString();return{graph:l,origin:{rediscovered:c},keep:async p=>{let g=new Set([...l.nodes.filter(m=>m.included).map(m=>m.objectApiName),...p]),h={};for(let m of g){let y=this.describeCache.get(`${t}::${m}`);y&&(h[m]=y)}await gd(n,{fileVersion:1,...d,step:e.step,discoveredAt:u,...f?{schemaStamp:f}:{},graph:l,describes:h,objects:this.describeGlobalCache.get(t)??[]},o)}}}async schemaChangeSince(e,t){if(!t.schemaStamp)return"the graph kept carries no stamp of the org";try{let n=await(await ue(e,this.deps.orgRegistry,this.deps.orgManager)).request({method:"GET",url:"/sobjects",headers:{"If-Modified-Since":new Date(t.schemaStamp).toUTCString()}}),o=typeof n=="object"&&n!==null?n.sobjects:void 0;return Array.isArray(o)?(this.forgetOrg(e),this.describeGlobalCache.set(e,o.flatMap(i=>{let{name:d,keyPrefix:a}=i??{};return typeof d=="string"?[{name:d,keyPrefix:typeof a=="string"?a:null}]:[]})),`the source's schema changed since the graph kept was discovered, on ${t.discoveredAt}`):void 0}catch(r){return`the source could not say whether its schema changed: ${K(r)}`}}holdKeptDescribes(e,t){for(let[r,n]of Object.entries(t.describes))this.describeCache.set(`${e}::${r}`,n,Td);t.objects.length>0&&this.describeGlobalCache.set(e,t.objects,Td)}async describeScopableFields(e,t){return(await this.describeObject(e,t)).fields.map(n=>({name:n.name,type:n.type,referenceTo:n.referenceTo,nillable:n.nillable!==!1}))}async ruleSchemaOf(e,t){let r=new Map;for(let{objectApiName:n}of t)try{let o=await this.describeObject(e,n);r.set(n,o.fields)}catch(o){this.deps.log(`[WARN] frozen: ${n} could not be described for the rules: ${String(o)}`)}return r}mappingStoreFor(e,t,r){let n=async()=>{try{let[o]=await this.buildTargetOrgAccess().query(t,"SELECT Id FROM Organization");return typeof o?.Id=="string"?o.Id:void 0}catch(o){this.deps.log(`[WARN] frozen: the target did not say which org it is: ${String(o)}`);return}};return new no(e,{orgId:t,organizationId:n,guard:r})}buildTargetOrgAccess(){return{query:async(e,t)=>{let r=await ue(e,this.deps.orgRegistry,this.deps.orgManager);return Zr(r,t)},count:async(e,t)=>(await(await ue(e,this.deps.orgRegistry,this.deps.orgManager)).query(t)).totalSize,describe:async(e,t)=>{let n=await(await ue(e,this.deps.orgRegistry,this.deps.orgManager)).describe(t);return{name:n.name,createable:n.createable,cascadeChildren:(n.childRelationships??[]).flatMap(o=>o.cascadeDelete===!0&&typeof o.field=="string"&&o.field!==""?[{childSObject:o.childSObject,field:o.field}]:[]),fields:n.fields.map(o=>({name:o.name,type:o.type,createable:o.createable??!1,nillable:o.nillable??!0,defaultedOnCreate:o.defaultedOnCreate??!1,referenceTo:o.referenceTo??[],restrictedPicklist:o.restrictedPicklist??!1,picklistValues:(o.picklistValues??[]).map(i=>({value:i.value,active:i.active??!0})),updateable:o.updateable!==!1,unique:o.unique===!0,nameField:o.nameField===!0,...typeof o.filteredLookupInfo=="object"&&o.filteredLookupInfo!==null?{lookupFilter:{optional:o.filteredLookupInfo.optionalFilter===!0}}:{}})),recordTypeInfos:(n.recordTypeInfos??[]).flatMap(o=>{let{developerName:i,active:d}=o;return i?[{developerName:i,recordTypeId:o.recordTypeId,available:o.available,name:o.name,master:o.master,defaultRecordTypeMapping:o.defaultRecordTypeMapping,...d===void 0?{}:{active:d}}]:[]})}},picklistValues:async(e,t,r,n)=>{let o=await ue(e,this.deps.orgRegistry,this.deps.orgManager);return Ji(o,t,r,n)},userId:async e=>(await(await ue(e,this.deps.orgRegistry,this.deps.orgManager)).soap.getUserInfo()).userId}}toLoadConfig(e){return{protectedOrgIds:e.protectedOrgIds,identityKeys:e.identityKeys,undeletableObjects:e.undeletableObjects,requiredLookupPlaceholders:e.requiredLookupPlaceholders,excludedObjects:e.excludedObjects,requiredFieldDefaults:e.requiredFieldDefaults,picklistRules:e.picklistRules,defaultPicklistRule:e.defaultPicklistRule,duplicateErrorPatterns:e.duplicateErrorPatterns,rootObjectApiName:e.rootObject}}async readFrozenDataset(e,t){let r=t.assertOutsideRepo(e),n=t.assertOutsideRepo(fe.join(r,"manifest.json"));if(!await We(n))throw new Error(`No frozen dataset found at ${r} \u2014 run a selection (frozen:select) then an extraction (frozen:extract) first.`);let o=Vt(JSON.parse(await le.readFile(n,"utf8"))),i=[],d=t.assertOutsideRepo(fe.join(r,"data"));if(await We(d))for(let u of(await le.readdir(d)).sort()){if(!u.endsWith(".json"))continue;let p=t.assertOutsideRepo(fe.join(d,u)),g=JSON.parse(await le.readFile(p,"utf8"));i.push({objectApiName:g.objectApiName,records:g.records})}let a=async(u,p)=>{let g=t.assertOutsideRepo(fe.join(r,u));return await We(g)?JSON.parse(await le.readFile(g,"utf8")):p},c=await a("record-types.json",{}),f=await a("personcontact-sidecar.json",[]),l=await a(fa,{});return{dataset:{datasetVersion:o.version,objects:i,recordTypes:c,personContactSidecar:f,...l.standardPricebook?{standardPricebook:l.standardPricebook}:{}},manifest:o}}errorCodeFor(e,t){return e instanceof rr?"RULES_MISSING":e instanceof ze?"GUARD_REFUSED":e instanceof ca?"SAS_PATH_REFUSED":e instanceof mr?"SALT_MISSING":e instanceof Ft?"BUDGET_EXCEEDED":e instanceof Ge?"LOAD_CONFIG":e instanceof kr?"MAX_RECORDS":e instanceof Jt?jn:e instanceof Ye?"TIMEOUT":t}errorDetailOf(e){if(e instanceof rr)return{rulesPath:e.rulesPath};if(e instanceof ze)return{guard:e.code,...e.params};if(e instanceof Ft)return{total:e.total,budgetMax:e.budgetMax,heaviest:e.heaviest};if(e instanceof Ge&&e.gaps)return{gaps:e.gaps};if(e instanceof Ge&&e.recordTypesUntold)return{recordTypesUntold:e.recordTypesUntold};if(e instanceof tr)return{emails:e.emails,orgId:e.orgId};if(e instanceof Cr)return{automation:e.automation,orgId:e.orgId};if(e instanceof Dr)return{apiRequests:e.apiRequests,orgId:e.orgId};if(e instanceof Mr)return{storage:e.storage,orgId:e.orgId}}loadEmailsFor(e){return Ya({read:e.read,...e.plan?{plan:e.plan}:{},writes:e.writes,inserts:e.dataset.objects.map(t=>({objectApiName:t.objectApiName,rows:t.records.length})).filter(t=>t.rows>0),readLimits:()=>ji(e.conn),readDeliverability:()=>e.orgTier==="production"?Promise.resolve(di):ci(e.conn),accepted:e.accepted,target:this.orgNameOf(e.orgId),mayMute:e.mayMute})}async loadApiCheck(e){let t=await Oi(e.conn).catch(o=>({unread:K(o)})),r=Hi(e.read),n=ki({run:Id({inserts:e.dataset.objects.map(o=>({objectApiName:o.objectApiName,rows:o.records.length})),...e.purged?{purged:e.purged}:{},threshold:_n(this.deps).bulk.threshold,...r?{duplicateRules:r}:{},automationRead:Ni(e.read)}),...Si(e.checkpoint),...ui(e.plan),...Ci(e.emails?.run.ofRun)},t);return n.verdict==="unread"&&this.deps.log(`[WARN] ${e.operation}: the daily API requests the target has left could not be read (${n.unread})`),El(n,this.orgNameOf(e.orgId))}async purgedOf(e,t){if(await e.isStale())return[];let r=t.undeletableObjects??{};return(await e.recordedLoads()).flatMap(n=>_e(n)).map(({objectApiName:n,ids:o})=>({objectApiName:n,rows:o.length,deletes:!Object.hasOwn(r,n)}))}orgNameOf(e){let t=this.deps.orgManager.getOrg(e);return Qo(t,e)}requireConfig(e,t){let r=this.loadConfig();return r||(Z(this.deps,e.type,t,e,new Error("No frozen dataset configuration saved \u2014 save the project configuration first (frozen:config:save: coverage axes, root object, budget, load rules)."),{code:"CONFIG_MISSING"}),null)}async handleSelect(e){let t=$e(Ds,e,"frozen:select:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:select:error");if(!r)return;let n=`frozen-select-${this.deps.nextId()}`;ur(this.deps,n,"frozen","Running coverage-matrix selection");let o="Coverage-matrix selection",i=new AbortController,d=setTimeout(()=>i.abort("timeout"),Dl),a=()=>{},c=new Promise((l,u)=>{a=p=>p===void 0?l():u(p)});c.catch(()=>{}),this.registry?.register(e.id,"frozen",o,c,i),this.liveTracker?.register(e.id,"frozen",o);let f=l=>{this.deps.broker.postToWebview(ce(this.deps,e,"frozen:select:progress",{...l})),l.phase==="combination"&&l.index!==void 0&&l.of&&this.liveTracker?.updateProgress(e.id,Math.round((l.index-1)/l.of*100),l.index-1,l.of,l.combinationKey??"")};try{let l=new te,u=l.assertOutsideRepo(this.resolveSasDir(r)),p=await ue(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),g=new Map,h=async T=>{let A=g.get(T);return A||(A=Zr(p,T),g.set(T,A),A.catch(()=>g.delete(T))),(await A).map(q=>({...q}))},m=await this.loadTokens(u,l),y=this.discoveryOptions(r),v=new Set,P=new Tr({query:h,describeFields:T=>(v.add(T),this.describeScopableFields(t.sourceOrgId,T)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),S=new Date().toISOString(),I,E=0,z=async T=>(I??=this.graphOfStep({step:"select",sourceOrgId:t.sourceOrgId,config:r,sasDir:u,guard:l,rootRecordId:T,signal:i.signal,onProgress:A=>{A.phase==="object"&&(A.discoveredCount-E<10&&A.queueRemaining>0||(E=A.discoveredCount,f({phase:"discovery",objects:A.discoveredCount})))}}),Co((await I).graph,r.excludedObjects)),O=async T=>{if(T.length===0)return{};let A=await z(T[0]),q=await P.extract({graph:A,rootObject:r.rootObject,rootRecordIds:T,asOf:S,sasDir:u,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:m,guard:l}),J={};for(let F of q.objects)J[F.objectApiName]=F.records.length;return J},w=new vn(O,r.expectedObjects??[]),R=async(T,A)=>(await this.describeObject(t.sourceOrgId,T)).fields.find(q=>q.name.toLowerCase()===A.toLowerCase())?.type,j=await new Rn({query:h,checkHealth:w,measureVolumetry:O,fieldType:R}).select({rootObject:r.rootObject,axes:r.axes,edgeCases:r.edgeCases,budgetMaxRecords:r.budgetMaxRecords,candidatesPerCombination:r.candidatesPerCombination,tokens:m},{signal:i.signal,onProgress:f}),N=await fd(u,j,l),$=I&&!j.stopped?await I.catch(()=>{}):void 0;$?.keep&&await $.keep(v).catch(T=>{this.deps.log(`[WARN] frozen: the graph could not be kept in the sas: ${String(T)}`)});let B=$?Co($.graph,r.excludedObjects):void 0,H=ce(this.deps,e,"frozen:select:response",{selection:{...ql(j,N,B?zd(B,y.maxNodes):void 0),...$?{discovery:$.origin}:{}}});this.deps.broker.postToWebview(H),at(this.deps,n,{roots:j.roots.length,total:j.volumetry.total,...j.stopped?{stopped:j.stopped.reason}:{}}),j.stopped?.reason==="cancelled"?this.liveTracker?.cancel(e.id):this.liveTracker?.complete(e.id),a()}catch(l){this.liveTracker?.fail(e.id,K(l)),a(l),Z(this.deps,"frozen:select","frozen:select:error",e,l,{code:this.errorCodeFor(l,"SELECT_ERROR"),retryable:l instanceof Ye,extraPayload:this.errorDetailOf(l)})}finally{clearTimeout(d)}}async handleExtract(e){let t=$e(xs,e,"frozen:extract:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:extract:error");if(!r)return;let n=`frozen-extract-${this.deps.nextId()}`;ur(this.deps,n,"frozen","Extracting + pseudonymizing dataset");try{let o=new te,i=o.assertOutsideRepo(this.resolveSasDir(r)),d=o.assertOutsideRepo(this.resolveDatasetDir(r)),a=await this.saltKeeper.forExtraction(),c=new an(a.salt);if(a.created&&this.sayTheSaltWasMade(c.saltFingerprint),!await We(fe.join(i,jr))){Z(this.deps,"frozen:extract","frozen:extract:error",e,new Error(`No selection found in ${i} \u2014 run the coverage-matrix selection first (frozen:select).`),{code:"SELECTION_MISSING"});return}let f=await vo(i,o),l=f.roots.map(q=>q.rootRecordId);if(l.length===0){Z(this.deps,"frozen:extract","frozen:extract:error",e,new Error("The last selection kept no root: every combination was uncovered, and the selection says why for each. Adjust the axes or the expected objects, then run the selection again."),{code:"SELECTION_EMPTY"});return}let u=await this.loadTokens(i,o),p=this.resolveRulesPath(r);if(!await We(p))throw new rr(p,`Pseudonymization rules file not found at ${p} \u2014 it is the source of truth (object.field \u2192 generator). Create it, or set rulesFilePath in the configuration.`);let g=bn(JSON.parse(await le.readFile(p,"utf8"))),h=await ue(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),m=this.discoveryOptions(r),y=await this.graphOfStep({step:"extract",sourceOrgId:t.sourceOrgId,config:r,sasDir:i,guard:o,rootRecordId:l[0]}),v=Co(y.graph,r.excludedObjects),P=new Set,S,I=new Tr({query:q=>S?.aborted?Promise.reject(new Error("The extraction ran out of time and stopped.")):Zr(h,q),describeFields:q=>(P.add(q),this.describeScopableFields(t.sourceOrgId,q)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),E=t.author??"sandforge",z=r.datasetVersion??Cl,{extracted:O,frozen:w,report:R,requiredLeftEmpty:k,keptUnruled:j}=await new pt(Lo).withTimeout("frozen:extract",async q=>{S=q;let J=await I.extract({graph:v,rootObject:r.rootObject,rootRecordIds:l,asOf:new Date().toISOString(),sasDir:i,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:u,guard:o}),F=await this.ruleSchemaOf(t.sourceOrgId,J.objects),_=nd(g,F,this.deps.infraServices?.piiDetector??new oi),U=new In().anonymize({extracted:J,rules:_,pseudonymizer:c,datasetVersion:z}),ee=new Sn().run(J,U,_,{author:E});return{extracted:J,frozen:U,report:ee,requiredLeftEmpty:sd(J,_,F),keptUnruled:od(J,_)}});k.length>0&&this.deps.log(`[WARN] frozen: the rules leave ${k.length} required field(s) empty, which a load will ask a value for: ${k.join(", ")}`),y.keep&&await y.keep(P).catch(q=>{this.deps.log(`[WARN] frozen: the graph could not be kept in the sas: ${String(q)}`)});let N=ce(this.deps,e,"frozen:control:result",{report:_d(R)});if(this.deps.broker.postToWebview(N),!R.passed){Z(this.deps,"frozen:extract","frozen:extract:error",e,new Error("Non-reidentification control FAILED \u2014 nothing was written. Fix the rules file and re-run the extraction (see frozen:control:result for the failing checks)."),{code:"CONTROL_FAILED"});return}let $={};for(let q of w.objects)$[q.objectApiName]=q.records.length;let B=this.deps.orgManager.getOrg(t.sourceOrgId),H=la({version:z,source:{orgId:t.sourceOrgId,orgAlias:B?.alias,decisionDate:f.selectedAt},saltFingerprint:c.saltFingerprint,rulesVersion:g.rulesVersion,volumetry:{budgetMax:f.volumetry.budgetMax,measured:$,measuredAt:new Date().toISOString()},nonReidentification:R,author:E,coverage:{...zd(v,m.maxNodes),unboundedObjects:O.unboundedObjects,filesLeftOut:w.filesLeftOut??[],...(O.leftToThePlatform??[]).length>0?{leftToThePlatform:ln(O.leftToThePlatform??[])}:{},...O.exclusionCosts?{exclusionCosts:O.exclusionCosts}:{},...k.length>0?{requiredLeftEmpty:k}:{},...j.length>0?{keptWithoutARule:j}:{},encryptedNotKept:O.encryptedNotKept??[]}}),T=await new pa(o).write(d,w,H,R),A=ce(this.deps,e,"frozen:extract:response",{datasetDir:T.dir,files:T.files,recordCount:Kt(w),manifest:No(H),discovery:y.origin});this.deps.broker.postToWebview(A),at(this.deps,n,{records:Kt(w),version:H.version})}catch(o){let i=o instanceof Ye,d=i?new Error(`The extraction ran out of its ${Lo/6e4} minutes and stopped, and nothing was written: it reads every record of the roots the selection kept, so run again it would stop again. Keep fewer roots: lower the budget in the configuration, or narrow the axes, then run the selection and the extraction again.`):o;Z(this.deps,"frozen:extract","frozen:extract:error",e,d,{code:i?Ml:this.errorCodeFor(o,"EXTRACT_ERROR"),retryable:!1,extraPayload:i?{minutes:Lo/6e4}:this.errorDetailOf(o)})}}async handleRulesClear(e){let t=$e(Ms,e,"frozen:rules:clear:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:rules:clear:error");if(r)try{let n=this.resolveRulesPath(r);if(!await We(n))throw new rr(n,`Pseudonymization rules file not found at ${n} \u2014 nothing was written. Create it, or set rulesFilePath in the configuration.`);let o=id(JSON.parse(await le.readFile(n,"utf8")),t.fields);if(o.cleared.length>0){let d=`${n}.${process.pid}.writing`;await le.writeFile(d,`${JSON.stringify(o.payload,null,2)}
20
- `,"utf8"),await le.rename(d,n),this.deps.log(`[INFO] frozen: ${o.cleared.length} field(s) given a clear rule in ${n} (rules ${o.rulesVersion}): ${o.cleared.join(", ")}`)}let i=ce(this.deps,e,"frozen:rules:clear:response",{rulesPath:n,rulesVersion:o.rulesVersion,cleared:o.cleared,alreadyRuled:o.alreadyRuled});this.deps.broker.postToWebview(i)}catch(n){Z(this.deps,"frozen:rules:clear","frozen:rules:clear:error",e,n,{code:this.errorCodeFor(n,"RULES_CLEAR_ERROR"),extraPayload:this.errorDetailOf(n)})}}async handleRulesCreate(e){let t=this.resolveRulesPath(this.loadConfig()),r=!1;try{await le.mkdir(fe.dirname(t),{recursive:!0});try{await le.writeFile(t,ed(td),{encoding:"utf8",flag:"wx"}),r=!0,this.deps.log(`[INFO] frozen: empty rules file written at ${t}`)}catch(o){if(o.code!=="EEXIST")throw o;if(!(await le.stat(t)).isFile())throw new Error(`${t} is not a file: no rules file can be written there.`)}}catch(o){Z(this.deps,"frozen:rules:create","frozen:rules:create:error",e,o,{code:"RULES_CREATE_ERROR"});return}let n=!1;try{await this.openInEditor(t),n=!0}catch(o){this.deps.log(`[WARN] frozen: rules file not opened: ${K(o)}`)}this.deps.broker.postToWebview(ce(this.deps,e,"frozen:rules:create:response",{rulesPath:t,created:r,opened:n}))}async handleManifestGet(e){let t=this.loadConfig(),r=this.resolveDatasetDir(t),n=null;try{let d=new te().assertOutsideRepo(fe.join(r,"manifest.json"));await We(d)&&(n=No(Vt(JSON.parse(await le.readFile(d,"utf8")))))}catch(i){st.warn(`frozen:manifest:get \u2014 unreadable manifest: ${String(i)}`)}let o=ce(this.deps,e,"frozen:manifest:get:response",{manifest:n,datasetDir:r});this.deps.broker.postToWebview(o)}targetTier(e){let t=this.deps.orgManager.getOrg(e);return Xo(t)}async handleLoad(e){let t=$e(Vn,e,"frozen:load:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:load:error");if(!r)return;let n=this.deps.infraServices?.productionGuard;if(!n){xe(this.deps,{action:"frozen_load",module:"frozen",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:ft.code}),Z(this.deps,"frozen:load","frozen:load:error",e,new Error(ft.message),{code:ft.code});return}let o=await this.replaceRefusal(t,r),i=o&&"error"in o?o:void 0,d=o&&"cameAlong"in o?o.cameAlong:void 0;if(i){i.code===jn&&xe(this.deps,{action:"frozen_load",module:"frozen",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:jn}),Z(this.deps,"frozen:load","frozen:load:error",e,i.error,{code:i.code,retryable:i.retryable});return}let a=e.id,c=t.pilot?"Pilot load (one root folder)":"Loading frozen dataset";ur(this.deps,a,"frozen",c),this.liveTracker?.register(a,"frozen",c);let f=!1,l=!1,u=new AbortController,p=()=>{},g=new Promise((A,q)=>{p=J=>J===void 0?A():q(J)});g.catch(()=>{}),this.registry?.register(a,"frozen",c,g,u);let h=Ld(A=>{let q=ce(this.deps,e,"frozen:load:progress",{...A});this.deps.broker.postToWebview(q),!f&&!l&&this.liveTracker?.updateProgress(a,A.progress,0,0,A.message)},100),m,y=!1,v=!1,P,S=new Date().toISOString(),I,E,z,O,w,R=(A,q,J,F)=>{if(v)return;v=!0;let _=A!=="stopped"&&I!==void 0,U=z?pi(fi(z.run.gate,z.info.accepted&&z.info.verdict==="asks").emails):{},ee={..._?{sas:I,startedAt:S,...E?{lastWriteAt:E}:{}}:{},...U};xe(this.deps,{action:"frozen_load",module:"frozen",operationId:a,orgId:t.targetOrgId,outcome:A,guard:m,objects:q,source:{origin:"dataset",label:P},carried:J,...F?{code:F}:{},...k?{muted:Hr(k)}:{},...N?.state==="taken"?{checkpointId:N.checkpointId}:{},...Object.keys(ee).length>0?{details:ee}:{}})},k,j,N,$=!1,B=!1,H=!1,T=[];try{let A=new te,q=A.assertOutsideRepo(this.resolveSasDir(r));I=ho(q);let J=A.assertOutsideRepo(this.resolveDatasetDir(r)),{dataset:F,manifest:_}=await this.readFrozenDataset(J,A);P=_.version;let U=this.buildTargetOrgAccess(),ee=await ue(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),D=_n(this.deps),x=Ps(this.deps),V=G=>new ia({connection:ee,bulkExecutor:new Bs(D.bulk.threshold),bulkManager:x,retryConfig:D.retry,...G?{signal:G}:{},onProgress:()=>{},log:lt=>this.deps.log(lt)}),Oe=V(u.signal),ke=r.mockDetection?new wr(U,r.mockDetection):{areCalloutsMocked:async()=>!0},ge=this.mappingStoreFor(q,t.targetOrgId,A),Ie=At(ee,"frozen:load"),he=new Ir({orgAccess:U,writer:jo(Oe),restoringWriter:jo(V(void 0)),guard:n,mockDetector:ke,recordTypeResolver:new Er(U),mappingStore:ge,config:this.toLoadConfig(r),sasGuard:A,serverTime:()=>Ie.serverTime()});if(t.sweep===!0&&t.reload===!0&&!t.pilot){T=await this.reloadSweepsOf({conn:ee,store:ge,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,includeChanged:t.includeChanged===!0,signal:u.signal,guard:n,operationId:a});for(let{sweep:G}of T)await G.ask()}let M=zr([],T.flatMap(({sweep:G})=>G.takes)),C=(M.delete??[]).length>0?this.removalAsker:void 0,ie=F.objects.map(G=>G.objectApiName),Se=t.reload===!0&&!t.pilot?await this.purgeStepsOf(ge,r):void 0,Te=await this.targetAutomation.read(t.targetOrgId,[...new Set([...ie,...Se?.delete??[],...M.delete??[]])]).catch(G=>({unread:K(G)})),Qe=Se?cr(Se):void 0,et=cr(M),nr=(G,lt)=>Fn(G,lt)||Qe?.(G,lt)===!0||et(G,lt),Ee=t.muteAutomation===!0?await pr(async()=>fr(ee),Te,{...this.muteLeases,writes:nr}):void 0;if(k=Ee?.muted,C&&!u.signal.aborted){let G=await C({read:Te,steps:M,mute:Ee});if(G)throw new er(G)}let tt=this.targetTier(t.targetOrgId),or=await he.gateLoad({orgId:t.targetOrgId,orgTier:tt,dataset:F,manifest:_,reload:t.reload,pilot:t.pilot?{}:void 0,onProgress:G=>h(G),onGuardDecision:G=>{m=Kn(m,G)}}),rt=mo({read:Te,...Ee?.plan?{plan:Ee.plan}:{},written:ie,accepted:t.acceptAutomation===!0,target:this.orgNameOf(t.targetOrgId),mayMute:t.muteAutomation!==!0&&this.muteOffered});if(O=rt.info,rt.stop&&rt.info)throw new Cr(rt.stop.code,rt.stop.message,rt.info,t.targetOrgId);let sr=t.acceptEmails===!0,Ue=await this.loadEmailsFor({conn:ee,orgId:t.targetOrgId,orgTier:tt,read:Te,...Ee?.plan?{plan:Ee.plan}:{},writes:nr,dataset:F,accepted:sr,mayMute:t.muteAutomation!==!0&&this.muteOffered});if(z=Ue,Ue.stop)throw new tr(Ue.stop.code,Ue.stop.message,Ue.info,t.targetOrgId);let mt=t.checkpointFirst!==void 0?await this.scopeLoadCheckpoint({msg:e,orgId:t.targetOrgId,written:ie,read:Te,mute:Ee,request:t.checkpointFirst}):void 0,Lt=Se?await this.purgedOf(ge,r):void 0,yt=Promise.resolve().then(()=>ee.request({method:"GET",url:"/limits"}));yt.catch(()=>{});let dt={request:()=>yt},xr=await Yn(dt).catch(G=>({unread:K(G)})),zt=t.pilot?void 0:$d({dataset:F,storage:xr,...Lt?{purged:Lt}:{},target:this.orgNameOf(t.targetOrgId)});if(zt)throw new Mr(zt.message,zt.storage,t.targetOrgId);if(w=await this.loadApiCheck({conn:dt,dataset:F,...Lt?{purged:Lt}:{},read:Te,...mt?{checkpoint:mt.estimate}:{},...Ee?.plan?{plan:Ee.plan}:{},emails:Ue,orgId:t.targetOrgId,operation:`frozen:load ${a}`}),w.refused)throw new Dr(w.refused.message,w,t.targetOrgId);mt&&(j=await this.takeLoadCheckpoint(mt,u.signal));let Ae=Ee?.prepared?await Ee.prepared.acquire(a):void 0;Ae&&(k=Ae.outcome,H=!0);let nt=Ae?Ue.run.afterLease(Ae.outcome,sr):void 0;if(Ae&&nt)throw k=await Ae.release(),new tr(nt.code,nt.message,Ue.info,t.targetOrgId);$=!0;let $r=()=>he.load({orgId:t.targetOrgId,orgTier:tt,dataset:F,manifest:_,sasDir:q,reload:t.reload,pilot:t.pilot?{}:void 0,...t.writeEncrypted?{writeEncrypted:!0}:{},...t.maxRecords!==void 0?{maxRecords:t.maxRecords}:{},onProgress:G=>h(G),onGuardDecision:G=>{m=Kn(m,G),(G==="allowed"||G==="confirmed")&&(y=!0)},signal:u.signal,...Ae?{lease:{giveBack:()=>Ae.release()}}:{},...T.length>0?{purgeSweep:{first:async()=>{for(let{sweep:G}of T)await G.first()},afterPurge:async()=>{for(let{sweep:G}of T)await G.afterRemoval()},stillToSweep:()=>T.filter(({sweep:G})=>!Fo(G.result())).map(({loadedAt:G})=>G)}}:{}}),Ke=await(or==="confirmed"?si({approved:!0},$r):$r()).finally(async()=>{Ae&&(k=await Ae.release())});B=!0,h.flush();let Nt=await this.settleReloadSweeps(T),ir=Nt.some(G=>G.result.status!=="success");j&&(N=await this.settleCheckpoint(j,Tn(Ke)>0)),E=Ua(await ge.recorded().catch(()=>{}),S);let He=fe.join(J,"manifest.json");l=!0;let Ct=await this.verifyLoad({orgId:t.targetOrgId,contractPath:Ke.contractPath,manifestPath:He,dataset:F,mappingStore:ge,config:r,onProgress:h}),ct="verdict"in Ct?Ct.verdict.status:void 0,Me=ct==="failed"||ct==="partial"?ct:void 0,wt=Ke.status==="completed"&&(ir||Me!==void 0)?"partial":Ke.status,Dt=Vl(Ke);R(Me!==void 0&&Dt==="success"?"partial":Dt,xo(Ke),await Kl(F,ge));let ar={contractPath:Ke.contractPath,datasetDir:J,manifestPath:He,targetOrgId:t.targetOrgId,status:wt,at:new Date().toISOString()};this.recordLastRun(ar);let bt=Bl(Ke),_r=Object.fromEntries(Object.entries(d??{}).filter(([G])=>(bt.purge.deleted[G]??0)>0)),En=ce(this.deps,e,"frozen:load:response",{report:{...bt,...Object.keys(_r).length>0?{purge:{...bt.purge,cameAlong:_r}}:{},status:wt,...Me?{verification:Me}:{},...k?{mutedAutomation:k}:{},...N?{checkpoint:N}:{},...Nt.length>0?{sweeps:Nt}:{},...z&&Ad(z.info)?{emails:z.info}:{},...O?{automation:O}:{},...w?{apiRequests:w}:{}}});this.deps.broker.postToWebview(En),at(this.deps,a,{status:wt}),f=!0,wt!=="completed"?this.liveTracker?.partial(a):this.liveTracker?.complete(a),this.postVerification(e,Ct),p()}catch(A){h.flush();let q=await this.settleReloadSweeps(T).catch(()=>[]),J=q.length>0?{sweeps:q}:{};if(j&&N===void 0){let Ie=A instanceof qe||A instanceof jt?A.written:void 0;N=await this.settleCheckpoint(j,Ie?Tn(Ie)>0:$&&!nn(A))}let F=N?{checkpoint:N}:{},_=H&&k?{mutedAutomation:k}:{};if(A instanceof Et){R("stopped",void 0,void 0,A.code),Z(this.deps,"frozen:load","frozen:load:error",e,A,{code:A.code,...A.code==="LOAD_CANCELLED"?{extraPayload:{written:0}}:{}}),A.code==="LOAD_CANCELLED"?(this.registry?.abort(a),at(this.deps,a,{aborted:!0}),this.liveTracker?.cancel(a),p()):(qn(this.deps,a,A.message,!0),this.liveTracker?.fail(a,A.message),p(A));return}if(A instanceof qe){let Ie=Ul(A.written);R(Ie,xo(A.written),void 0,Ie==="stopped"?"LOAD_CANCELLED":void 0),this.registry?.abort(a),at(this.deps,a,{aborted:!0}),this.liveTracker?.cancel(a),Z(this.deps,"frozen:load","frozen:load:error",e,A,{code:"LOAD_CANCELLED",extraPayload:{written:Tn(A.written),...F,...J,..._}}),p();return}let U=nn(A)||A instanceof er||A instanceof tr||A instanceof Cr||A instanceof Dr||A instanceof Mr?A:void 0,ee=U!==void 0||(m==="refused"||m==="declined")&&!y,D=A instanceof jt?A:void 0,x=D?D.cause:A,V=U?.code??this.errorCodeFor(x,"LOAD_ERROR"),Oe=D===void 0&&!B&&!y;R(ee||Oe?"stopped":"failure",D?xo(D.written):void 0,void 0,U?.code??(Oe?V:void 0));let ge={...D&&x instanceof ze?{guard:x.code}:this.errorDetailOf(x),...F,...J,..._,...Oe?{written:0}:{}};Z(this.deps,"frozen:load","frozen:load:error",e,A,{code:V,retryable:x instanceof Ye,extraPayload:Object.keys(ge).length>0?ge:void 0}),f||(qn(this.deps,a,K(A),!0),this.liveTracker?.fail(a,K(A))),p(A)}}loadCheckpointAsk(e){let{read:t}=e;return{module:"frozen",orgId:e.orgId,operationId:e.operationId,written:[...e.written],running:"objects"in t?$t(t,e.mute?.plan,Fn):{firing:[]},request:e.request}}async previewCheckpoint(e){let t=this.beforeRunCheckpoints;if(!t)return;let r=await this.targetAutomation.read(e.orgId,e.written).catch(i=>({unread:K(i)})),n=e.muteAutomation?await pr(async()=>fr(e.conn),r,{...this.muteLeases,writes:Fn}).catch(i=>{st.warn(`Frozen preview: the mute could not be planned (${K(i)})`)}):void 0,o=this.loadCheckpointAsk({...e,operationId:e.msg.id,read:r,...n?{mute:n}:{}});return t.scope(o,{}).catch(i=>{st.warn(`Frozen preview: ${sn(i)}`)})}async scopeLoadCheckpoint(e){let t=this.beforeRunCheckpoints;if(!t)throw new Et(hr,sn(new Error("SandForge's checkpoints are not set up in this window")));let r=this.loadCheckpointAsk({...e,operationId:e.msg.id}),n={operationId:Nd(e.msg.id)},o;try{o=await t.scope(r,n)}catch(d){throw new Et(hr,sn(d))}let i=Ai(o);if(i)throw new Et(i.code,i.message);return{checkpoints:t,ask:r,own:n,estimate:o}}async takeLoadCheckpoint(e,t){let{checkpoints:r,ask:n,own:o,estimate:i}=e,d=await Pi(()=>r.take(n,o,{planned:i,signal:t}));if("stop"in d)throw new Et(d.stop.code===hr?hr:"LOAD_CANCELLED",d.stop.message);return d.checkpoint}async settleCheckpoint(e,t){let r=this.beforeRunCheckpoints;if(!r)return e;try{return await r.settle(e,t)}catch(n){return st.warn(`Frozen load: the checkpoint '${e.name}' taken before it is kept, as it could not be settled (${K(n)})`),e}}recordLastRun(e){this.moveOldVerify();let t={...this.lastRuns()},r=this.deps.configStore.get(Qt);r&&t[r.targetOrgId]===void 0&&(t[r.targetOrgId]=r),t[e.targetOrgId]=e,this.deps.configStore.set(jd,t,Nr),this.deps.configStore.set(Qt,e,Nr)}recordLastVerify(e,t){this.moveOldVerify(),this.deps.configStore.set(Eo,{...this.lastVerifies(),[e]:t},Nr)}lastVerifies(){return this.deps.configStore.get(Eo)??{}}orgOfOldVerify(e){let t=this.deps.configStore.get(Qt);return!t||Date.parse(t.at)>Date.parse(e.measuredAt)?void 0:Object.keys(this.lastRuns()).filter(n=>n!==t.targetOrgId).length===0?t.targetOrgId:void 0}moveOldVerify(){let e=this.deps.configStore.get(To);if(!e)return;let t=this.orgOfOldVerify(e),r=this.lastVerifies();t!==void 0&&r[t]===void 0&&this.deps.configStore.set(Eo,{...r,[t]:e},Nr),this.deps.configStore.delete(To)}lastVerifyInfos(){let e={...this.lastVerifies()},t=this.deps.configStore.get(To),r=t?this.orgOfOldVerify(t):void 0;return t&&r!==void 0&&e[r]===void 0&&(e[r]=t),Object.entries(e).map(([n,o])=>({orgId:n,status:o.status,measuredAt:o.measuredAt}))}lastRuns(){return this.deps.configStore.get(jd)??{}}lastRunOf(e){let t=this.lastRuns()[e];if(t)return t;let r=this.deps.configStore.get(Qt);return r?.targetOrgId===e?r:void 0}lastLoadInfos(){let e={...this.lastRuns()},t=this.deps.configStore.get(Qt);return t&&e[t.targetOrgId]===void 0&&(e[t.targetOrgId]=t),Object.values(e).map(r=>({status:r.status,orgId:r.targetOrgId,at:r.at}))}async handlePreview(e){let t=$e(Vn,e,"frozen:load:preview:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:load:preview:error");if(!r)return;let n=await this.replaceRefusal(t,r,t.goneFirst),o=n&&"error"in n?n:void 0;if(o){Z(this.deps,"frozen:load:preview","frozen:load:preview:error",e,o.error,{code:o.code,retryable:o.retryable});return}try{let i=new te,d=i.assertOutsideRepo(this.resolveSasDir(r)),a=i.assertOutsideRepo(this.resolveDatasetDir(r)),{dataset:c,manifest:f}=await this.readFrozenDataset(a,i),l=this.buildTargetOrgAccess(),u=await ue(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),p=At(u,"frozen:load:preview"),h=await new Ir({orgAccess:l,writer:jl,guard:this.deps.infraServices?.productionGuard??new ii,mockDetector:r.mockDetection?new wr(l,r.mockDetection):{areCalloutsMocked:async()=>!0},recordTypeResolver:new Er(l),mappingStore:this.mappingStoreFor(d,t.targetOrgId,i),config:this.toLoadConfig(r),sasGuard:i,serverTime:()=>p.serverTime(),readValidationRules:async I=>{let{toolingQueriesOver:E,toolingValidationRules:z}=await import("./chunk-7ABODJ4G.mjs"),{toolingRetrievesOver:O}=await import("./chunk-7YDNUBO5.mjs"),w=u.tooling;return z(async R=>(await Es({query:async k=>w.query(k),queryMore:async k=>w.queryMore(k)},R)).records,E(u),O(u))(I)}}).planLoad({orgId:t.targetOrgId,orgTier:this.targetTier(t.targetOrgId),dataset:c,manifest:f,sasDir:d,reload:t.reload,pilot:t.pilot?{}:void 0,...t.writeEncrypted?{writeEncrypted:!0}:{}}),m=t.checkpointFirst!==void 0?await this.previewCheckpoint({msg:e,orgId:t.targetOrgId,written:c.objects.map(I=>I.objectApiName),request:t.checkpointFirst,muteAutomation:t.muteAutomation===!0,conn:u}):void 0,{emails:y,automation:v,apiRequests:P,storage:S}=await this.previewWhatRuns({conn:u,orgId:t.targetOrgId,dataset:c,store:this.mappingStoreFor(d,t.targetOrgId,i),config:r,parsed:t,...m?{checkpoint:m}:{}});this.deps.broker.postToWebview(ce(this.deps,e,"frozen:load:preview:response",{plan:{...h,...m?{checkpoint:m}:{},...y?{emails:y}:{},...v?{automation:v}:{},...P?{apiRequests:P}:{},...S?{storage:S}:{}}}))}catch(i){Z(this.deps,"frozen:load:preview","frozen:load:preview:error",e,i,{code:this.errorCodeFor(i,"PREVIEW_ERROR"),retryable:i instanceof Ye,extraPayload:this.errorDetailOf(i)})}}async previewWhatRuns(e){let{parsed:t}=e;try{let r=t.reload===!0&&!t.pilot?await this.purgeStepsOf(e.store,e.config):void 0,n=r?await this.purgedOf(e.store,e.config):void 0,o=r?cr(r):void 0,i=(h,m)=>Fn(h,m)||o?.(h,m)===!0,d=await this.targetAutomation.read(e.orgId,[...new Set([...e.dataset.objects.map(h=>h.objectApiName),...r?.delete??[]])]).catch(h=>({unread:K(h)})),a=t.muteAutomation===!0?await pr(async()=>fr(e.conn),d,{...this.muteLeases,writes:i}).catch(()=>{}):void 0,{info:c}=mo({read:d,...a?.plan?{plan:a.plan}:{},written:e.dataset.objects.map(h=>h.objectApiName),accepted:t.acceptAutomation===!0,target:this.orgNameOf(e.orgId),mayMute:t.muteAutomation!==!0&&this.muteOffered}),f=await this.loadEmailsFor({conn:e.conn,orgId:e.orgId,orgTier:this.targetTier(e.orgId),read:d,...a?.plan?{plan:a.plan}:{},writes:i,dataset:e.dataset,accepted:t.acceptEmails===!0,mayMute:t.muteAutomation!==!0&&this.muteOffered}).catch(h=>{st.warn(`Frozen preview: the emails could not be judged (${K(h)})`)}),l=Promise.resolve().then(()=>e.conn.request({method:"GET",url:"/limits"}));l.catch(()=>{});let u={request:()=>l},p=t.pilot?void 0:await Yn(u).then(h=>Tl({dataset:e.dataset,storage:h,...n?{purged:n}:{},target:this.orgNameOf(e.orgId)})).catch(h=>{st.warn(`Frozen preview: the data storage could not be judged (${K(h)})`)}),g=await this.loadApiCheck({conn:u,dataset:e.dataset,...n?{purged:n}:{},read:d,...e.checkpoint?{checkpoint:e.checkpoint}:{},...a?.plan?{plan:a.plan}:{},...f?{emails:f}:{},orgId:e.orgId,operation:"frozen:load:preview"}).catch(h=>{st.warn(`Frozen preview: the API requests could not be judged (${K(h)})`)});return{...f&&Ad(f.info)?{emails:f.info}:{},...c?{automation:c}:{},...g?{apiRequests:g}:{},...p?{storage:p}:{}}}catch(r){return st.warn(`Frozen preview: what the target runs could not be judged (${K(r)})`),{}}}async handleVerify(e){let t=$e($s,e,"frozen:verify:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:verify:error");if(!r)return;let n=this.lastRunOf(t.targetOrgId);if(!n){Z(this.deps,"frozen:verify","frozen:verify:error",e,new Error("No load into this org is recorded \u2014 run a load (frozen:load) into it before verifying."),{code:"NO_LOAD"});return}let o=Ld(i=>{let d=ce(this.deps,e,"frozen:load:progress",{...i});this.deps.broker.postToWebview(d)},100);try{let i=new te,d=i.assertOutsideRepo(this.resolveSasDir(r)),a=fe.dirname(n.contractPath)!==fe.dirname(vr(i,d,t.targetOrgId)),c=await We(n.contractPath);if(a||!c){let g=fe.dirname(n.contractPath),h;a?c?h=`The sas directory changed since the last load: its counting contract is in ${g}, and the mapping read is the one in ${d}. Set sasDir back to the sas the load wrote to, or load the dataset again, then verify.`:h=`The sas directory changed since the last load: the load wrote to ${g}, which no longer holds its counting contract, and the mapping read is the one in ${d}. Move the sas back to ${g} and set sasDir to it, or load the dataset again, then verify.`:h=`The sas changed since the last load: ${d} no longer holds the counting contract the last load wrote there. Load the dataset again, then verify.`,Z(this.deps,"frozen:verify","frozen:verify:error",e,new Error(h),{code:"SAS_CHANGED",extraPayload:{sasDir:d,loadSas:g,sasMoved:a,contractThere:c}});return}let f=this.mappingStoreFor(d,t.targetOrgId,i);if(await f.isStale()){Z(this.deps,"frozen:verify","frozen:verify:error",e,new Error("The target org was refreshed after the last load: the records that load wrote are gone. Load the dataset again, then verify."),{code:"TARGET_REFRESHED"});return}let l=await f.recorded(),u=l?.removal;if(l&&u){let g=_e(l).reduce((h,m)=>h+m.ids.length,0);Z(this.deps,"frozen:verify","frozen:verify:error",e,new Error(g>0?`The removal of ${u.removedAt} took part of the records the last load created and left ${g} in the org: a verification would read the ones it took as missing. Remove what is left, or reload the dataset, which purges or finds it again; then verify.`:`The records the last load created were removed on ${u.removedAt}. Load the dataset again, then verify.`),{code:"LOAD_REMOVED",extraPayload:{left:g}});return}if(!l){Z(this.deps,"frozen:verify","frozen:verify:error",e,new Error("The sas holds no mapping of the last load: nothing names the records to verify. Load the dataset again, then verify."),{code:"NO_LOAD"});return}if(!Ra(gn(i,n.contractPath),l)){Z(this.deps,"frozen:verify","frozen:verify:error",e,new Error("The last load stopped part way \u2014 it was cancelled, or failed once it had written \u2014 and wrote no counting contract: the one in the sas counts an earlier load, and would judge this one by it. Reload the dataset, which purges or finds again what the stopped load wrote, or remove that load before loading the dataset again; then verify. Loaded again without a reload, the dataset would go in beside what the stopped load wrote."),{code:"LOAD_STOPPED"});return}let{dataset:p}=await this.readFrozenDataset(n.datasetDir,i);await this.runVerification(e,{orgId:t.targetOrgId,contractPath:n.contractPath,manifestPath:n.manifestPath,dataset:p,mappingStore:f,config:r,onProgress:o})}catch(i){Z(this.deps,"frozen:verify","frozen:verify:error",e,i,{code:this.errorCodeFor(i,"VERIFY_ERROR"),retryable:i instanceof Ye})}}async runVerification(e,t){this.postVerification(e,await this.verifyLoad(t))}async verifyLoad(e){try{let t=new An({orgAccess:this.buildTargetOrgAccess(),sasGuard:new te}),r=await e.mappingStore.load(),n=await t.verify({orgId:e.orgId,contractPath:e.contractPath,dataset:e.dataset,mapping:r,mandatoryLookups:e.config.mandatoryLookups,presenceKeys:e.config.presenceKeys,manifestPath:e.manifestPath,author:"sandforge",onProgress:e.onProgress});return this.recordLastVerify(e.orgId,{status:n.status,measuredAt:n.measuredAt}),{verdict:n}}catch(t){return{error:t}}}postVerification(e,t){if("verdict"in t){let{verdict:n}=t,o=ce(this.deps,e,"frozen:verify:result",{verdict:n});this.deps.broker.postToWebview(o);return}let r=t.error;Z(this.deps,"frozen:verify","frozen:verify:error",e,r,{code:this.errorCodeFor(r,"VERIFY_ERROR"),retryable:r instanceof Ye})}async handleRemove(e){let t=$e(_s,e,"frozen:remove:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:remove:error");if(!r)return;let n=(p,g)=>this.refuseRemove(e,p,g),o,i,d;try{let p=new te,g=p.assertOutsideRepo(this.resolveSasDir(r));o=this.mappingStoreFor(g,t.targetOrgId,p),i=await o.recordedLoads(),d=Ut(i)}catch(p){Z(this.deps,"frozen:remove","frozen:remove:error",e,p,{code:this.errorCodeFor(p,"REMOVE_ERROR")});return}let a=Do(d,t),c=t.sweep===!0&&a?.code==="ALREADY_REMOVED";if(a&&!c||!d){a&&n(a.message,a.code);return}let f=_e(d),l=o.filePath;if(this.removing.has(l)){n("The records of this load are being removed already.","DUPLICATE");return}this.removing.add(l);let u=this.registry?.holdUntilStart(e.id);try{await this.removeLoad(e,{store:o,load:d,plan:f,includeChanged:t.includeChanged===!0,sweep:t.sweep===!0,sweepLate:t.sweep===!0&&t.sweepLate===!0,sweepUntied:t.sweep===!0&&t.sweepUntied===!0,alongside:t.sweep===!0?so(i,d):[],muteAutomation:t.muteAutomation===!0,pending:u})}finally{this.removing.delete(l),u?.release()}}async handleRemoveAutomation(e){let t=$e(Gs,e,"frozen:remove:automation:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:remove:automation:error");if(r)try{let n=new te,o=n.assertOutsideRepo(this.resolveSasDir(r)),i=this.mappingStoreFor(o,t.targetOrgId,n),d,a;if(t.reload===!0)d=await this.purgeStepsOf(i,r,t.sweptObjects??[]),(t.sweptObjects??[]).length>0&&(a=await this.purgeStepsOf(i,r));else{let l=Ut(await i.recordedLoads()),u=Do(l,t),p=t.sweptObjects!==void 0&&u?.code==="ALREADY_REMOVED";if(u&&!p||!l){u&&Z(this.deps,"frozen:remove:automation","frozen:remove:automation:error",e,new Error(u.message),{code:u.code});return}d=zr(_e(l),t.sweptObjects??[])}let c=this.targetAutomation,f=await new pt(zo).withTimeout("frozen:remove:automation",()=>c.read(t.targetOrgId,d.delete??[]));this.deps.broker.postToWebview(ce(this.deps,e,"frozen:remove:automation:response",{loadedAt:t.loadedAt,automation:f,steps:d,...a?{purge:a}:{}}))}catch(n){Z(this.deps,"frozen:remove:automation","frozen:remove:automation:error",e,n,{code:n instanceof Ye?"TIMEOUT":this.errorCodeFor(n,"AUTOMATION_ERROR"),retryable:!0})}}async purgeStepsOf(e,t,r=[]){if(await e.isStale())return zr([],[]);let n=t.undeletableObjects??{},o=(await e.recordedLoads()).flatMap(i=>_e(i)).filter(({objectApiName:i})=>!Object.hasOwn(n,i));return zr(o,r)}async handleRemovePreview(e){let t=$e(Ws,e,"frozen:remove:preview:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:remove:preview:error");if(!r)return;let n=(o,i,d=!1)=>Z(this.deps,"frozen:remove:preview","frozen:remove:preview:error",e,o,{code:i,retryable:d});try{let o=new te,i=o.assertOutsideRepo(this.resolveSasDir(r)),d=this.mappingStoreFor(i,t.targetOrgId,o),a=Ut(await d.recordedLoads()),c=Do(a,t);if(c||!a){c&&n(new Error(c.message),c.code);return}let f=_e(a).reduce((p,g)=>p+g.ids.length,0),l=this.removalGuardRefusals(a.orgId,f),u;if(await d.isStale())l.push({code:"TARGET_REFRESHED",message:"The target org was refreshed after the load: the records it created went with the refresh, and a removal removes nothing."}),u={...this.unreadPreviewOf(a,t.includeChanged===!0),planned:f};else{let p=await ue(a.orgId,this.deps.orgRegistry,this.deps.orgManager);u=await this.previewRemovalOf(p,a,t.includeChanged===!0)}this.deps.broker.postToWebview(ce(this.deps,e,"frozen:remove:preview:response",{preview:{...u,refusals:l.map(({message:p})=>p),refusalCodes:l.map(({code:p})=>p)}}))}catch(o){n(o,this.errorCodeFor(o,"REMOVE_PREVIEW_ERROR"),!0)}}removalGuardRefusals(e,t){let r=this.deps.infraServices?.productionGuard;if(!r)return[{...ft}];let n=this.targetTier(e),o=r.check({orgId:e,orgTier:n,operation:"delete",objectName:"the records a Frozen load created",recordCount:t,module:"frozen"});if(!o.allowed)return[{code:"GUARD_BLOCKED",message:`Operation blocked by Production Guard: ${o.blockedReason??o.impactSummary}`}];let i=r.declinedWithoutAsking(o,n);return i===void 0?[]:[{code:"GUARD_DECLINED",message:`Production Guard asks before this delete, and its question is answered no: ${i} (${o.impactSummary}). Nothing would be deleted.`}]}async previewRemovalOf(e,t,r){let n=_e(t),o=await en(At(e,"frozen:remove:preview"),n,{...Mo(t),includeChanged:r,previewOnly:!0});if(!o.preview)throw new Error("The removal preview stopped before it was through.");return{...this.unreadPreviewOf(t,r),planned:n.reduce((i,d)=>i+d.ids.length,0),objects:o.preview.objects.map(i=>({objectApiName:i.objectApiName,planned:i.planned,toDelete:i.toDelete,alreadyGone:i.alreadyGone,changedSince:i.changedSince,keptChanged:i.keptChanged,changedBy:i.changedBy,undeletable:i.undeletable,notVisible:i.notVisible,unread:i.unread,reasons:i.reasons})),userNames:o.preview.userNames}}unreadPreviewOf(e,t){let r=un(e);return{loadedAt:e.endedAt,includeChanged:t,planned:0,objects:[],userNames:{},...e.removal?{leftBy:e.removal.removedAt}:{},...r.length>0?{keptByThePlatform:r}:{}}}async replaceRefusal(e,t,r=[]){if(e.reload!==!0||e.pilot===!0)return;let n,o={};try{let i=new te,d=i.assertOutsideRepo(this.resolveSasDir(t)),a=this.mappingStoreFor(d,e.targetOrgId,i),c=await a.recordedLoads();if(c.length===0||await a.isStale())return;if(c.some(f=>!f.created))n="A load recorded before loads kept what they created is in this sas: which of its records it created cannot be told, and a reload leaves in place those it may have linked, so it would not replace that load whole, and no removal takes it. Refresh the sandbox to start again from its copy, or find the records the loading user created that day and delete them yourself, then load without reloading. Nothing was written.";else{let f=await ue(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),l=c.filter(h=>_e(h).length>0),u=new Set([...l.flatMap(h=>_e(h).flatMap(m=>m.ids.map(y=>y.slice(0,15)))),...r.map(h=>h.slice(0,15))]),p=[];for(let h of l){let m=await en(At(f,"frozen:load:replace"),_e(h),{...Mo(h),includeChanged:!1,previewOnly:!0,previewHeld:!0,goesWithParent:y=>typeof y.Id=="string"&&u.has(y.Id.slice(0,15))});if(!m.preview)throw new Error("The removal preview stopped before it was through.");p.push(m.preview);for(let{objectApiName:y,cameAlong:v}of m.preview.objects){if(!v)continue;let P=o[y];o[y]={count:(P?.count??0)+v.count,objects:[...new Set([...P?.objects??[],...v.objects])]}}}let g=Wl(p,e.sweep===!0);g.length>0&&(n=`A removal of the loads this reload replaces would leave ${g.reduce((m,y)=>m+y.left,0)} of their records in the org \u2014 ${g.map(m=>`${m.objectApiName} (${m.left}: ${m.why.join(", ")})`).join("; ")}: loaded again, the dataset would stand beside them, and the reload would delete what was changed since, and what stays under them along with them. Nothing was written. Take the load back first with a removal \u2014 records changed since, and what was added under them since, go too when it is told to include them \u2014 then load the dataset again.`)}}catch(i){return{error:i,code:this.errorCodeFor(i,"LOAD_ERROR"),retryable:!0}}return n!==void 0?{error:new Error(n),code:jn,retryable:!1}:Object.keys(o).length>0?{cameAlong:o}:void 0}refuseRemove(e,t,r){Z(this.deps,"frozen:remove","frozen:remove:error",e,new Error(t),{code:r})}async removeLoad(e,t){let{store:r,load:n,plan:o,includeChanged:i,sweep:d,pending:a}=t,c=n.orgId,f=o.reduce((R,k)=>R+k.ids.length,0),l=(R,k)=>this.refuseRemove(e,R,k),u=this.deps.infraServices?.productionGuard;if(!u){xe(this.deps,{action:"cleanup_delete",module:"frozen",operationId:e.id,orgId:c,outcome:"stopped",code:ft.code}),l(ft.message,ft.code);return}let{check:p,decision:g}=f>0?await tn(u,{orgId:c,orgTier:this.targetTier(c),operation:"delete",objectName:o.map(R=>R.objectApiName).join(", "),recordCount:f,module:"frozen"}):{check:void 0,decision:"allowed"};if(p&&(g==="refused"||g==="declined")){xe(this.deps,{action:"cleanup_delete",module:"frozen",operationId:e.id,orgId:c,outcome:"stopped",guard:g}),g==="refused"?l(`Operation blocked by Production Guard: ${p.blockedReason??p.impactSummary}`,"GUARD_BLOCKED"):Z(this.deps,"frozen:remove","frozen:remove:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}let h=()=>{if(!a?.signal.aborted)return!1;xe(this.deps,{action:"cleanup_delete",module:"frozen",operationId:e.id,orgId:c,outcome:"stopped",guard:g,code:Is});let R={status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};return this.deps.broker.postToWebview(ce(this.deps,e,"frozen:remove:response",{result:R,operationId:e.id})),!0};if(h())return;let m;try{m=await r.isStale()}catch(R){xe(this.deps,{action:"cleanup_delete",module:"frozen",operationId:e.id,orgId:c,outcome:"failure",guard:g}),Z(this.deps,"frozen:remove","frozen:remove:error",e,R,{code:this.errorCodeFor(R,"REMOVE_ERROR"),retryable:!0});return}if(m){xe(this.deps,{action:"cleanup_delete",module:"frozen",operationId:e.id,orgId:c,outcome:"stopped",guard:g,code:"TARGET_REFRESHED"}),l("The target org was refreshed after the load: the records it created went with the refresh, and nothing is removed.","TARGET_REFRESHED");return}if(h())return;let y=e.id,v=f>0?`Removing ${f} record(s) a Frozen load created`:"Sweeping what the target's automation made for a Frozen load",P=new AbortController,S=()=>{},I=new Promise((R,k)=>{S=j=>j===void 0?R():k(j)});I.catch(()=>{}),ur(this.deps,y,"frozen",v),this.registry?.register(y,"frozen",v,I,P),this.liveTracker?.register(y,"frozen",v,f);let E,z,O=[],w;try{let R=await ue(c,this.deps.orgRegistry,this.deps.orgManager),k=new Set([n,...t.alongside].map(M=>M.endedAt));z=d?await this.sweepOfRemoval({conn:R,load:n,store:r,includeChanged:i,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,signal:P.signal,guard:u,operationId:y,muted:()=>f===0?w:void 0,sweptWith:k}):void 0;for(let[M,C]of(z?t.alongside:[]).entries())O.push({loadedAt:C.endedAt,sweep:await this.sweepOfRemoval({conn:R,load:C,store:r,includeChanged:i,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,signal:P.signal,guard:u,operationId:`${y}-${M+2}`,muted:()=>{},sweptWith:k})});let j=z,N=[...z?[z]:[],...O.map(({sweep:M})=>M)],$=async M=>{let C=!1;for(let ie of N)await M(ie)&&(C=!0);return C};for(let M of N)await M.ask();let B,H=this.removalAsker,T=zr(o,N.flatMap(M=>M.takes));if((t.muteAutomation||H)&&!P.signal.aborted&&(T.delete??[]).length>0){let M=this.targetAutomation,C=await new pt(zo).withTimeout("frozen:remove automation",()=>M.read(c,T.delete??[])).catch(Se=>({unread:K(Se)}));t.muteAutomation&&(B=await pr(async()=>fr(R),C,{...this.muteLeases,writes:cr(T)}));let ie=await H?.({read:C,steps:T,mute:B});if(ie)throw new er(ie)}w=B?.muted;let A,q=async()=>{let M=B?.prepared;!M||P.signal.aborted||(A=await M.acquire(y),w=A.outcome)},F=await(f===0?(async()=>(await q(),await $(M=>M.first()),await $(M=>M.afterRemoval()),Hs))():en(At(R,"frozen:remove"),o,{...Mo(n),...j?{sweep:M=>$(C=>C.first(M)),afterRemoval:M=>$(C=>C.afterRemoval(M)),automationMade:j.automationMade}:{},onUndeletable:As(this.deps,c,"frozen:remove"),beforeFirstWrite:q,includeChanged:i,signal:P.signal,onProgress:(M,C,ie)=>{let Se=Math.min(100,Math.round(M/Math.max(C,1)*100));Fs(this.deps,y,Se,M,C,ie),P.signal.aborted||this.registry?.updateProgress(y,Se),this.liveTracker?.updateProgress(y,Se,M,C,ie)}})).finally(async()=>{A&&(w=await A.release())}),_=await z?.settle(),U=await this.settleReloadSweeps(O),ee=n.removal?.removedAt,D=un(n),x=Ys(F.objects,F.cancelled),V={status:U.reduce((M,C)=>Un(M,C.result),Un(x,_)),includeChanged:i,objects:F.objects,finishedAt:new Date().toISOString(),...ee?{leftBy:ee}:{},..._?{sweep:_}:{},...U.length>0?{otherLoadSweeps:U}:{},...D.length>0?{keptByThePlatform:D}:{},...w?{mutedAutomation:w}:{}};f>0&&xe(this.deps,{action:"cleanup_delete",module:"frozen",operationId:y,orgId:c,outcome:Zs({status:x}),guard:g,objects:Xs(V.objects),...ee?{leftBy:ee}:{},...w?{muted:Hr(w)}:{}});let Oe=Qs(V,f,n.removal);(F.gone.length>0||Object.keys(F.stamps).length>0||F.span||Oe)&&(await r.recordRemoval(n.endedAt,{gone:F.gone,stamps:F.stamps,...F.span?{span:F.span}:{},...Oe?{mark:Oe}:{}})||this.deps.log("[WARN] frozen:remove: a load wrote its own mapping during the removal; the removal is not recorded in it"));let ke=[..._&&Fo(_)?[n.endedAt]:[],...U.filter(M=>Fo(M.result)).map(M=>M.loadedAt)];await r.letSweptGo(ke).catch(()=>!1);let ge=ce(this.deps,e,"frozen:remove:response",{result:V,operationId:y});this.deps.broker.postToWebview(ge);let Ie=[_,...U.map(M=>M.result)].find(M=>M!==void 0&&M.status!=="success"),he=V.status==="failure"?"No record this load created could be removed.":f===0&&Ie?Ie.refusal??"The sweep left records in the org.":void 0;V.status==="cancelled"||_?.status==="cancelled"||U.some(M=>M.result.status==="cancelled")?(at(this.deps,y,{aborted:!0}),this.liveTracker?.cancel(y)):(at(this.deps,y,{status:he&&f===0?"failure":V.status}),he?(E=new Error(he),this.liveTracker?.fail(y,he)):V.status==="partial"?this.liveTracker?.partial(y):this.liveTracker?.complete(y))}catch(R){E=R,await z?.settle().catch(()=>{});for(let{sweep:j}of O)await j.settle().catch(()=>{});let k=nn(R)||R instanceof er?R:void 0;xe(this.deps,{action:"cleanup_delete",module:"frozen",operationId:y,orgId:c,outcome:k?"stopped":"failure",guard:g,...k?{code:k.code}:{}}),Z(this.deps,"frozen:remove","frozen:remove:error",e,R,{code:k?.code??"REMOVE_ERROR",retryable:!0}),at(this.deps,y,{status:"failure"}),this.liveTracker?.fail(y,K(R))}finally{S(E)}}async reloadSweepsOf(e){if(await e.store.isStale())return[];let t=(await e.store.recordedLoads()).filter(d=>d.created),r=new Set(t.map(d=>d.endedAt)),n={includeChanged:e.includeChanged,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},o=d=>Ll(d,n),i=[];for(let[d,a]of t.entries())i.push({loadedAt:a.endedAt,judged:o,sweep:await this.sweepOfRemoval({conn:e.conn,load:a,store:e.store,includeChanged:e.includeChanged,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied,signal:e.signal,guard:e.guard,operationId:d===0?e.operationId:`${e.operationId}-${d+1}`,muted:()=>{},sweptWith:r,judged:o})});return i}async settleReloadSweeps(e){let t=[];for(let{loadedAt:r,sweep:n,judged:o}of e){let i=await n.settle();t.push({loadedAt:r,result:o?o(i):i})}return t}sweepOfRemoval(e){let{conn:t,load:r}=e;return ta({input:()=>this.sweepInputOfLoad(At(t,"frozen:remove sweep"),r,e.signal,e.store,e.sweptWith),org:cn(t,"frozen:remove sweep",e.signal),options:{includeChanged:e.includeChanged,removalSpans:r.removalSpans,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},guard:e.guard,guardOf:{orgId:r.orgId,orgTier:this.targetTier(r.orgId),operation:"delete",module:"frozen"},onGuardDecision:(n,o)=>{let i=e.judged?e.judged(n):n,d=Xi(i,"");delete d.forgeId;let a=e.muted();xe(this.deps,{action:"cleanup_delete",module:"frozen",operationId:`${e.operationId}-sweep`,orgId:r.orgId,outcome:i.status==="refused"?"stopped":i.status,...o?{guard:o}:{},...i.status==="refused"?{code:ra(o)}:{},objects:Zi(i),details:{...d,loadedAt:r.endedAt},...a?{muted:Hr(a)}:{}})},keepMade:async(n,o,i)=>{await e.store.recordMade(r.endedAt,n,o,i)}})}async sweepInputOfLoad(e,t,r,n,o=new Set){let i=oo(t),d=this.targetAutomation,a;try{a=await new pt(zo).withTimeout("frozen:remove sweep automation",()=>d.read(t.orgId,i.map(p=>p.objectApiName)))}catch(p){a={error:K(p)}}let c=t.writtenBetween??await Qi(e,i,r),{ties:f,sweptAlong:l}=await this.tiesOfLoad(t,c,n,o),u=new Set([...t.mapping.values(),...l].map(p=>p.slice(0,15)));return ea({writtenBetween:c,created:i,remap:u,automation:Yi(a),...t.runUserId?{runUserId:t.runUserId}:{},ties:f,...r?{signal:r}:{}},e)}setOtherModuleRuns(e){this.otherModuleRuns=e}auditedLoadsInto(e){try{return Ja(new ks(this.deps.configStore).list({orgId:e,limit:Jo}).entries)}catch{return[]}}sasMarkInUse(){let e=this.loadConfig();return e?ho(this.resolveSasDir(e)):void 0}async tiesOfLoad(e,t,r,n){let o=[],i=[],d=await r?.recordedLoads().catch(()=>[])??[];for(let c of d){if(c.endedAt===e.endedAt||c.orgId!==e.orgId)continue;let f=oo(c).flatMap(p=>p.ids);if(n.has(c.endedAt)){i.push(...f);continue}let l=Date.parse(c.writtenBetween?.first??c.startedAt??c.endedAt),u=Date.parse(c.writtenBetween?.last??c.endedAt);o.push({ids:f,from:l,to:Number.isFinite(u)?u:l})}o.push(...await this.otherModuleRuns(e.orgId,t).catch(()=>[])),o.push(...Ka(this.auditedLoadsInto(e.orgId),{sasMark:this.sasMarkInUse(),own:d.filter(c=>c.orgId===e.orgId)}));let a=oa(e.removalSpans);return{ties:{otherRuns:na(t,o),...a?{removalBegan:a}:{},...e.madeEarlier?{madeEarlier:e.madeEarlier}:{},...e.lateEarlier?{lateEarlier:e.lateEarlier}:{}},sweptAlong:i}}async handleRemoveSweep(e){let t=$e(qs,e,"frozen:remove:sweep:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:remove:sweep:error");if(!r)return;let n=(o,i)=>Z(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,new Error(o),{code:i});try{let o=new te,i=o.assertOutsideRepo(this.resolveSasDir(r)),d=this.mappingStoreFor(i,t.targetOrgId,o);if(t.reload===!0){await this.listReloadSweeps(e,d,t);return}let a=await d.recordedLoads(),c=Ut(a);if(!c){n("No load into this org was recorded in this sas: there is nothing to sweep.","NO_LOAD");return}if(c.orgId!==t.targetOrgId||c.endedAt!==t.loadedAt){n("Another load was recorded since this one was shown: check what a removal takes now.","LOAD_CHANGED");return}let f=so(a,c),l=new Set([c,...f].map(g=>g.endedAt)),{listing:u,otherLoads:p}=await new pt(Ed).withTimeout("frozen:remove:sweep",async()=>{let g=await ue(c.orgId,this.deps.orgRegistry,this.deps.orgManager),h=cn(g,"frozen:remove:sweep"),m=async v=>to(h,await this.sweepInputOfLoad(h,v,void 0,d,l),v.removalSpans),y=[];for(let v of f)y.push({loadedAt:v.endedAt,listing:await m(v)});return{listing:await m(c),otherLoads:y}});this.deps.broker.postToWebview(ce(this.deps,e,"frozen:remove:sweep:response",{loadedAt:c.endedAt,listing:u,...p.length>0?{otherLoads:p}:{}}))}catch(o){Z(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,o,{code:o instanceof Ye?"TIMEOUT":this.errorCodeFor(o,"SWEEP_ERROR"),retryable:!0})}}async listReloadSweeps(e,t,r){let n=await t.isStale()?void 0:await t.recordedLoads(),o=(n??[]).filter(d=>d.created);if(n&&!n.some(d=>d.endedAt===r.loadedAt)){Z(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,new Error("Another load was recorded since this one was shown: check what a reload replaces now."),{code:"LOAD_CHANGED"});return}let i=await new pt(Ed).withTimeout("frozen:remove:sweep",async()=>{if(o.length===0)return[];let d=await ue(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=cn(d,"frozen:remove:sweep"),c=new Set(o.map(l=>l.endedAt)),f=[];for(let l of o)f.push({loadedAt:l.endedAt,listing:await to(a,await this.sweepInputOfLoad(a,l,void 0,t,c),l.removalSpans)});return f});this.deps.broker.postToWebview(ce(this.deps,e,"frozen:remove:sweep:response",{loadedAt:r.loadedAt,reload:!0,loads:i}))}sayTheSaltWasMade(e){js(this.deps,"info","Frozen dataset salt",`This first extraction made the salt every pseudonym is drawn with (fingerprint ${e}) and keeps it in VS Code's secret storage: every later extraction pseudonymizes the same records the same way. A teammate who extracts this dataset needs the same salt: copy it with "SandForge: Copy Frozen Dataset Salt" and give it to them as you would a password; they set it with "SandForge: Use a Frozen Dataset Salt". Whoever holds it can tell which source value a pseudonym was drawn from.`,{autoDismissMs:null,code:"FROZEN_SALT_CREATED"})}async handleStatus(e){let t=this.loadConfig(),r=this.resolveSasDir(t),n=this.resolveDatasetDir(t),o={present:!1};try{let u=await this.saltKeeper.read();u&&(o={present:!0,fingerprint:new an(u.salt).saltFingerprint,source:u.source})}catch{o={present:!1}}let i=null;try{let u=new te;if(await We(fe.join(r,jr))){let p=await vo(r,u);i={selectedAt:p.selectedAt,rootCount:p.roots.length,total:p.volumetry.total,budgetMax:p.volumetry.budgetMax}}}catch{i=null}let d=null;try{let p=new te().assertOutsideRepo(fe.join(n,"manifest.json"));await We(p)&&(d=No(Vt(JSON.parse(await le.readFile(p,"utf8")))))}catch{d=null}let a=this.deps.configStore.get(Qt),c=[];try{let u=new te,p=u.assertOutsideRepo(r);for(let g of await ha(p,u))try{let h=Ut(await new no(p,{guard:u,orgId:g}).recordedLoads());h&&c.push(ma(h))}catch{}}catch{c.length=0}let f={configured:t!==null,sasDir:r,datasetDir:n,salt:o,mockDetectionConfigured:t?.mockDetection!==void 0,selection:i,manifest:d,lastLoad:a?{status:a.status,orgId:a.targetOrgId,at:a.at}:null,lastLoads:this.lastLoadInfos(),lastVerifies:this.lastVerifyInfos(),...c.length>0?{loadRecords:c}:{},rules:await this.rulesFileInfo(t)},l=ce(this.deps,e,"frozen:status:response",{status:f});this.deps.broker.postToWebview(l)}};export{Bd as a,Vd as b,Pu as c,Va as d,ho as e,Ua as f,Ka as g,Eu as h,Lu as i,xu as j,Gu as k,Cd as l};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as c}from"./chunk-SU65Z2BA.mjs";import{b as d}from"./chunk-CA5NAXSU.mjs";import{Yb as a,_b as u}from"./chunk-TTFDUKUS.mjs";var f=["INVALID_SESSION_ID","INVALID_AUTH_HEADER","SESSION_EXPIRED"];function p(t){if(typeof t=="object"&&t!==null){let{errorCode:e,statusCode:o}=t;if(typeof e=="string"&&f.includes(e)||o===401)return!0}let n=d(t);return f.some(e=>n.includes(e))||n.includes("Session expired")?!0:/\b401\b/.test(n)&&/unauthorized/i.test(n)}async function S(t){let e=(await t.query("SELECT Id, IsSandbox FROM Organization LIMIT 1")).records[0];if(typeof e?.Id!="string")throw new Error("The org gave no Organization record: whether it is a sandbox cannot be told.");if(e.IsSandbox===!0)return{id:e.Id,sandbox:!0};try{let r=(await t.query("SELECT OrganizationType FROM Organization LIMIT 1")).records[0]?.OrganizationType;return typeof r=="string"&&r!==""?{id:e.Id,sandbox:!1,edition:r}:{id:e.Id,sandbox:!1}}catch{return{id:e.Id,sandbox:!1}}}function O(t){let n=a({isSandbox:t.sandbox,edition:t.edition});return u(n,t.edition)==="production"}function y(t){let{errorCode:n,statusCode:e}=typeof t=="object"&&t!==null?t:{},o=t instanceof Error?t.message:String(t);return e===403||typeof n=="string"&&/^INSUFFICIENT_ACCESS/.test(n)||/\bINSUFFICIENT_ACCESS/.test(o)||(n==="INVALID_TYPE"||/\bINVALID_TYPE\b/.test(o))&&/\bOrganization\b/.test(o)}function x(t){if(p(t))return"auth";if(c(t))return"network";if(y(t))return"organizationRefused"}function m(t,n,e){let o=n instanceof Error?n.message:String(n);switch(e){case"auth":return`${t} refused the session SandForge holds for it (${o}): reconnect it \u2014 Reconnect on the Organizations page, or "sf org login web --alias ${t}" for a command line \u2014 then try again.`;case"network":return`${t} did not answer (${o}): try again once it answers.`;case"organizationRefused":return`${t} would not show its Organization record (${o}): reading it takes the View Setup and Configuration permission, which the user SandForge connects as lacks: give it to them, or connect as a user who has it.`}}var I=/\/services\/Soap\//,g=/\/services\/data\/v\d+\.\d+\/jobs\/(?:ingest|query)(?:[/?]|$)/,b=/^\/jobs\/(?:ingest|query)(?:[/?]|$)/;function l(t){let n=typeof t=="string"?t:t?.url??"";return g.test(n)||b.test(n)}function R(t){let n=0;if(typeof t.request!="function")return()=>n;let e=t._transport,o=t.request.bind(t);if(t.request=(...r)=>((e===void 0||!l(r[0]))&&n++,o(...r)),e!==void 0){let r=e.httpRequest.bind(e);e.httpRequest=(...s)=>{let i=s[0].url;return(I.test(i)||g.test(i))&&n++,r(...s)}}return()=>n}export{p as a,S as b,O as c,y as d,x as e,m as f,R as g};
@@ -1,8 +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{mkdirSync as s,statSync as i}from"node:fs";import{homedir as d}from"node:os";import{join as o,resolve as u}from"node:path";var a=448;function h(e=process.env){return c("backups",e)}function c(e,n=process.env){let r=n.SANDFORGE_JOURNAL_DIR,t=r!==void 0&&r.trim()!==""?u(r):o(d(),".sandforge");return o(t,e)}var f={mkdir:(e,n)=>{s(e,n)},stat:e=>i(e),...typeof process.getuid=="function"?{uid:()=>process.getuid?.()??-1}:{}};function y(e,n=f){try{n.mkdir(e,{recursive:!0,mode:a});let r=n.stat(e);if(!r.isDirectory())return`The store ${e} is not a folder.`;let t=n.uid?.();return t!==void 0&&r.uid!==t?`The store ${e} belongs to another user, who can read its snapshots and change them: name a folder of your own with --store.`:void 0}catch(r){return`The store ${e} could not be made: ${r instanceof Error?r.message:String(r)}`}}function k(e){if(e!==void 0)return/^\d{1,5}$/.test(e)||(process.stderr.write(`Not a number of days: "${e}"
8
- `),process.exit(2)),Number(e)}function b(e){return(n,r)=>n==="backup.maxRecordsPerObject"&&e.maxRecords!==void 0?e.maxRecords:n==="backup.maxAgeDays"&&e.maxAgeDays!==void 0?e.maxAgeDays:r}function l(e){let n=`removed snapshot ${e.operationId}${e.takenAt!==void 0?`, taken ${e.takenAt}`:""}: past the retention of ${e.days} day(s) (--max-age-days, 0 keeps them all)`;return e.syncRunId!==void 0?`${n}. It held what the Sync run ${e.syncRunId||"(unknown)"} wrote over: removing that run with sandforge sync --remove no longer puts those values back`:n}export{h as a,c as b,y as c,k as d,b as e,l as f};