sandforge 1.80.0 → 1.82.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (266) hide show
  1. package/README.md +48 -0
  2. package/bin/sandforge-pipeline.mjs +12 -0
  3. package/bin/sandforge-users.mjs +12 -0
  4. package/lib/{chunk-J525F5KI.mjs → chunk-27Z76O2O.mjs} +1 -1
  5. package/lib/chunk-2JZGCCPG.mjs +9 -0
  6. package/lib/{chunk-ELFXJHU7.mjs → chunk-2UU42PTD.mjs} +1 -1
  7. package/lib/{chunk-N652NMZ4.mjs → chunk-32EUNQT6.mjs} +52 -52
  8. package/lib/chunk-3C2ZZIFN.mjs +7 -0
  9. package/lib/chunk-3CX7GPCR.mjs +7 -0
  10. package/lib/chunk-3HEMJTAP.mjs +925 -0
  11. package/lib/{chunk-BY2HJFFG.mjs → chunk-3HROD5RE.mjs} +1 -1
  12. package/lib/{chunk-OHWNPXWW.mjs → chunk-3MGMNK3Q.mjs} +1 -1
  13. package/lib/{chunk-PZPJKATS.mjs → chunk-3SKLBRPL.mjs} +8 -8
  14. package/lib/chunk-3XG25GTF.mjs +7 -0
  15. package/lib/chunk-42BFLWHR.mjs +7 -0
  16. package/lib/chunk-466F37VD.mjs +7 -0
  17. package/lib/chunk-47UHTN3Q.mjs +7 -0
  18. package/lib/chunk-4JKR4PTZ.mjs +8 -0
  19. package/lib/{chunk-COFG7Q6R.mjs → chunk-52EXDVPN.mjs} +1 -1
  20. package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
  21. package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
  22. package/lib/chunk-5K2I2DMP.mjs +11 -0
  23. package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
  24. package/lib/{chunk-BV6VTP3J.mjs → chunk-6GQUZ4IP.mjs} +1 -1
  25. package/lib/chunk-6KP6WETK.mjs +9 -0
  26. package/lib/{chunk-MJVTDA5Q.mjs → chunk-6VSZNZHH.mjs} +1 -1
  27. package/lib/{chunk-XUWL6ZPC.mjs → chunk-7CVDVBEE.mjs} +1 -1
  28. package/lib/{chunk-UCD54V2M.mjs → chunk-7EYQYZJP.mjs} +1 -1
  29. package/lib/{chunk-5K5VLULK.mjs → chunk-7LKI7OAS.mjs} +1 -1
  30. package/lib/chunk-7PY3VQP3.mjs +7 -0
  31. package/lib/chunk-7SDZR6SR.mjs +7 -0
  32. package/lib/chunk-7WSLT5VX.mjs +8 -0
  33. package/lib/chunk-A32ISQ6M.mjs +28 -0
  34. package/lib/{chunk-M3ROUWDX.mjs → chunk-A65ADTCR.mjs} +1 -1
  35. package/lib/chunk-A7JJWOLT.mjs +7 -0
  36. package/lib/chunk-AUS6NFLZ.mjs +8 -0
  37. package/lib/chunk-BMTNTBBM.mjs +7 -0
  38. package/lib/{chunk-SOU4FRYN.mjs → chunk-BN33LVPQ.mjs} +1 -1
  39. package/lib/chunk-BNKT3R3F.mjs +7 -0
  40. package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
  41. package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
  42. package/lib/{chunk-WA7EYLAQ.mjs → chunk-C2N2TNEU.mjs} +1 -1
  43. package/lib/{chunk-BKDV4ENO.mjs → chunk-C3LNYAVJ.mjs} +1 -1
  44. package/lib/{chunk-XLXIPIEW.mjs → chunk-CBL42DUU.mjs} +1 -1
  45. package/lib/chunk-CCEH7L53.mjs +7 -0
  46. package/lib/chunk-CELEBWEZ.mjs +7 -0
  47. package/lib/chunk-CV47FDQW.mjs +7 -0
  48. package/lib/{chunk-2UZPIMUC.mjs → chunk-CZLJZQCS.mjs} +1 -1
  49. package/lib/chunk-DBBPDSFN.mjs +7 -0
  50. package/lib/chunk-DIL62SUN.mjs +7 -0
  51. package/lib/chunk-DIS254AN.mjs +7 -0
  52. package/lib/{chunk-BTWDMNN3.mjs → chunk-DJCGURW7.mjs} +1 -1
  53. package/lib/{chunk-F6GUDTOB.mjs → chunk-DT3T7FRD.mjs} +1 -1
  54. package/lib/{chunk-IGYH7GMA.mjs → chunk-DWMRIWV5.mjs} +1 -1
  55. package/lib/{chunk-YRQGKDHM.mjs → chunk-EEFUE2ES.mjs} +1 -1
  56. package/lib/{chunk-FGRG7ANU.mjs → chunk-EOFO3PHS.mjs} +1 -1
  57. package/lib/{chunk-KBJ5VERV.mjs → chunk-FA4ZKDCU.mjs} +1 -1
  58. package/lib/{chunk-WU3GLFZO.mjs → chunk-FKK5YBGZ.mjs} +1 -1
  59. package/lib/chunk-FOIWWK7G.mjs +156 -0
  60. package/lib/chunk-FZF23M6R.mjs +7 -0
  61. package/lib/chunk-G2JR3F63.mjs +7 -0
  62. package/lib/{chunk-JEERQRLW.mjs → chunk-GBGHJTPC.mjs} +1 -1
  63. package/lib/{chunk-3RZQZHEB.mjs → chunk-GCGHHN4K.mjs} +1 -1
  64. package/lib/{chunk-RPI7LRTW.mjs → chunk-GGNUACTY.mjs} +1 -1
  65. package/lib/{chunk-EMNC6YI4.mjs → chunk-GGUOIDWP.mjs} +1 -1
  66. package/lib/chunk-GHPR5UVV.mjs +7 -0
  67. package/lib/{chunk-X5JYBPXP.mjs → chunk-GJ6SZVHT.mjs} +1 -1
  68. package/lib/{chunk-W622GUAW.mjs → chunk-H4JUYUSL.mjs} +1 -1
  69. package/lib/{chunk-XAMBCQPU.mjs → chunk-H4OBZIX3.mjs} +1 -1
  70. package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
  71. package/lib/{chunk-L77FJZEP.mjs → chunk-HFUDCNU5.mjs} +1 -1
  72. package/lib/chunk-HIHCYMSL.mjs +7 -0
  73. package/lib/chunk-HKUWHVI7.mjs +9 -0
  74. package/lib/chunk-HQQVANWQ.mjs +20 -0
  75. package/lib/chunk-ICIYL45C.mjs +7 -0
  76. package/lib/chunk-IRZJU2PG.mjs +22 -0
  77. package/lib/chunk-ISSP2FZ5.mjs +7 -0
  78. package/lib/chunk-IVZJSDJD.mjs +7 -0
  79. package/lib/chunk-J24TIGSI.mjs +10 -0
  80. package/lib/{chunk-UNJA4J37.mjs → chunk-JESRFE2Z.mjs} +4 -4
  81. package/lib/chunk-JFNLKHY6.mjs +8 -0
  82. package/lib/chunk-JH27IKCO.mjs +9 -0
  83. package/lib/chunk-JJITOWZK.mjs +7 -0
  84. package/lib/{chunk-E5AHXLS6.mjs → chunk-JKT5YAQ2.mjs} +1 -1
  85. package/lib/{chunk-IWDREM66.mjs → chunk-JLZRZL5E.mjs} +1 -1
  86. package/lib/{chunk-FPKYYFM7.mjs → chunk-JPEVIXNH.mjs} +1 -1
  87. package/lib/chunk-JQZTMFO7.mjs +7 -0
  88. package/lib/chunk-KIMQQ6JQ.mjs +7 -0
  89. package/lib/{chunk-MILU7WFN.mjs → chunk-KJYEQHYP.mjs} +1 -1
  90. package/lib/chunk-KKOA62S4.mjs +474 -0
  91. package/lib/chunk-KP5G6FUC.mjs +7 -0
  92. package/lib/{chunk-JWTSEDIQ.mjs → chunk-L4INJ5TZ.mjs} +1 -1
  93. package/lib/{chunk-OLSGVAIL.mjs → chunk-LAUOSXMN.mjs} +53 -53
  94. package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
  95. package/lib/{chunk-KDGMAGQR.mjs → chunk-LHU6CPGE.mjs} +1 -1
  96. package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
  97. package/lib/chunk-LXDSRP2W.mjs +7 -0
  98. package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
  99. package/lib/{chunk-TTKXMDBN.mjs → chunk-MKTXJCXN.mjs} +4 -4
  100. package/lib/chunk-MUEQRIK7.mjs +9 -0
  101. package/lib/{chunk-IOIWJ3DJ.mjs → chunk-NLB3RGIY.mjs} +1 -1
  102. package/lib/{chunk-O2HDYYUV.mjs → chunk-NWOI25WY.mjs} +1 -1
  103. package/lib/chunk-O2PUGRNW.mjs +10 -0
  104. package/lib/chunk-O4BROUGM.mjs +7 -0
  105. package/lib/chunk-OETEC3P7.mjs +7 -0
  106. package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
  107. package/lib/chunk-P55MKIZX.mjs +37 -0
  108. package/lib/chunk-P63WJMXQ.mjs +7 -0
  109. package/lib/chunk-PBE44M2Y.mjs +7 -0
  110. package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
  111. package/lib/chunk-PE435FVH.mjs +15 -0
  112. package/lib/chunk-PPGDAUEQ.mjs +7 -0
  113. package/lib/{chunk-SE4QEZUG.mjs → chunk-PPHVWUFY.mjs} +1 -1
  114. package/lib/{chunk-CU2INBND.mjs → chunk-PR74GYVI.mjs} +1 -1
  115. package/lib/chunk-PWVDNN2C.mjs +7 -0
  116. package/lib/{chunk-6XYKJSGX.mjs → chunk-PYRZFUVU.mjs} +1 -1
  117. package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
  118. package/lib/{chunk-DYFALGRT.mjs → chunk-Q3DY7TO2.mjs} +1 -1
  119. package/lib/{chunk-BGUEWRK2.mjs → chunk-Q6SXNKV2.mjs} +1 -1
  120. package/lib/chunk-QAPVKPEC.mjs +7 -0
  121. package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
  122. package/lib/{chunk-TSLJUSLW.mjs → chunk-RCYEBY42.mjs} +1 -1
  123. package/lib/chunk-RLWB7F26.mjs +7 -0
  124. package/lib/{chunk-FXXLX4O6.mjs → chunk-RTWYLOCA.mjs} +1 -1
  125. package/lib/chunk-RYRMUPMY.mjs +7 -0
  126. package/lib/chunk-SAMWHL22.mjs +13 -0
  127. package/lib/{chunk-IZQZ6ZUF.mjs → chunk-SFGZFB4F.mjs} +1 -1
  128. package/lib/{chunk-FKG7Q3WH.mjs → chunk-SNEOKYV7.mjs} +1 -1
  129. package/lib/{chunk-3TJON4F3.mjs → chunk-STRMWSIQ.mjs} +1 -1
  130. package/lib/chunk-SZGGFST2.mjs +272 -0
  131. package/lib/{chunk-SOGQW4IG.mjs → chunk-T7WREYA5.mjs} +1 -1
  132. package/lib/{chunk-NTFIRZP6.mjs → chunk-TCBAE65A.mjs} +1 -1
  133. package/lib/{chunk-KYEDBS54.mjs → chunk-TEIBWMJM.mjs} +1 -1
  134. package/lib/{chunk-YKKRIEH4.mjs → chunk-TMA34QMA.mjs} +1 -1
  135. package/lib/chunk-TQ2TQHTT.mjs +9 -0
  136. package/lib/{chunk-HEKAZJRH.mjs → chunk-TWV4A5RK.mjs} +1 -1
  137. package/lib/{chunk-CEX3NEZL.mjs → chunk-UHFLKP26.mjs} +1 -1
  138. package/lib/chunk-UV74P4H2.mjs +7 -0
  139. package/lib/{chunk-WR4Q363I.mjs → chunk-V3R45ZWT.mjs} +1 -1
  140. package/lib/{chunk-GSKCGQIP.mjs → chunk-VPDEJGPS.mjs} +1 -1
  141. package/lib/{chunk-HLWMJF6Y.mjs → chunk-VQJMP3DC.mjs} +1 -1
  142. package/lib/chunk-VV3B6IC3.mjs +7 -0
  143. package/lib/{chunk-PJ5I73CK.mjs → chunk-VYOYXTCU.mjs} +1 -1
  144. package/lib/{chunk-NZC67CGR.mjs → chunk-VZT4E2OJ.mjs} +1 -1
  145. package/lib/{chunk-AEKONPF4.mjs → chunk-VZVICK7Q.mjs} +1 -1
  146. package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
  147. package/lib/chunk-WEMLDUQA.mjs +7 -0
  148. package/lib/{chunk-MYW5QNGI.mjs → chunk-WOOUISSO.mjs} +1 -1
  149. package/lib/{chunk-G35N4P7D.mjs → chunk-WSUKC2U3.mjs} +1 -1
  150. package/lib/{chunk-ZVAED4QV.mjs → chunk-WT3SCUHS.mjs} +1 -1
  151. package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
  152. package/lib/{chunk-DBB3EMIN.mjs → chunk-XFU3HRUV.mjs} +1 -1
  153. package/lib/chunk-XK5W7BVE.mjs +7 -0
  154. package/lib/{chunk-2GTBABKU.mjs → chunk-XO5FBOQF.mjs} +1 -1
  155. package/lib/{chunk-CHYDMRSV.mjs → chunk-XSKPYGMT.mjs} +1 -1
  156. package/lib/chunk-XU25YA46.mjs +9 -0
  157. package/lib/chunk-XZISAZA6.mjs +7 -0
  158. package/lib/chunk-Y4TDVDP2.mjs +13 -0
  159. package/lib/chunk-YAIIRFKJ.mjs +8 -0
  160. package/lib/{chunk-LKQ5RKIV.mjs → chunk-YAJQS3OL.mjs} +1 -1
  161. package/lib/{chunk-74Q6DORA.mjs → chunk-YGJF55VJ.mjs} +1 -1
  162. package/lib/chunk-YH4DYI6D.mjs +7 -0
  163. package/lib/chunk-YMDFF657.mjs +10 -0
  164. package/lib/{chunk-2BA2XKAY.mjs → chunk-YT22LMF7.mjs} +1 -1
  165. package/lib/{chunk-IG2MTQRP.mjs → chunk-Z42PHCVZ.mjs} +1 -1
  166. package/lib/{chunk-2NBYT7GR.mjs → chunk-ZHIZY3ZC.mjs} +1 -1
  167. package/lib/chunk-ZQO5PDX5.mjs +48 -0
  168. package/lib/chunk-ZRUDYB7O.mjs +7 -0
  169. package/lib/{chunk-BXU6WFMH.mjs → chunk-ZUBBEP75.mjs} +1 -1
  170. package/lib/chunk-ZUOPC4W2.mjs +7 -0
  171. package/lib/{chunk-GGD7ON3M.mjs → chunk-ZUTUYBNW.mjs} +1 -1
  172. package/lib/{chunk-MHMH6MTP.mjs → chunk-ZXFL2MSN.mjs} +1 -1
  173. package/lib/sandforge-autopilot.mjs +11 -11
  174. package/lib/sandforge-backup.mjs +63 -32
  175. package/lib/sandforge-checkpoint.mjs +1 -348
  176. package/lib/sandforge-cleanup.mjs +1 -1
  177. package/lib/sandforge-clone.mjs +1 -1
  178. package/lib/sandforge-compare.mjs +1 -1
  179. package/lib/sandforge-dataops.mjs +1 -1
  180. package/lib/sandforge-empty.mjs +11 -11
  181. package/lib/sandforge-env.mjs +186 -140
  182. package/lib/sandforge-frozen.mjs +1 -266
  183. package/lib/sandforge-mcp.mjs +33 -14
  184. package/lib/sandforge-monitor.mjs +1 -1
  185. package/lib/sandforge-pipeline.mjs +88 -0
  186. package/lib/sandforge-seed.mjs +1 -1
  187. package/lib/sandforge-sync.mjs +1 -1
  188. package/lib/sandforge-users.mjs +157 -0
  189. package/lib/sandforge.mjs +1 -22
  190. package/lib/sf/sandforge/autopilot.mjs +20 -0
  191. package/lib/sf/sandforge/backup.mjs +20 -0
  192. package/lib/sf/sandforge/checkpoint.mjs +20 -0
  193. package/lib/sf/sandforge/cleanup.mjs +20 -0
  194. package/lib/sf/sandforge/clone.mjs +20 -0
  195. package/lib/sf/sandforge/compare.mjs +20 -0
  196. package/lib/sf/sandforge/dataops.mjs +20 -0
  197. package/lib/sf/sandforge/empty.mjs +20 -0
  198. package/lib/sf/sandforge/env.mjs +20 -0
  199. package/lib/sf/sandforge/frozen.mjs +20 -0
  200. package/lib/sf/sandforge/hardis-commands.mjs +20 -0
  201. package/lib/sf/sandforge/index.mjs +20 -0
  202. package/lib/sf/sandforge/mcp.mjs +20 -0
  203. package/lib/sf/sandforge/monitor.mjs +20 -0
  204. package/lib/sf/sandforge/pipeline.mjs +20 -0
  205. package/lib/sf/sandforge/seed.mjs +20 -0
  206. package/lib/sf/sandforge/sync.mjs +20 -0
  207. package/lib/sf/sandforge/users.mjs +20 -0
  208. package/lib/sfHelpHook.mjs +7 -0
  209. package/lib/sfPlugin.mjs +11 -0
  210. package/oclif.manifest.json +1 -0
  211. package/package.json +18 -3
  212. package/lib/chunk-2CNCDM56.mjs +0 -7
  213. package/lib/chunk-3F6Q5E7I.mjs +0 -14
  214. package/lib/chunk-4VS2V6WU.mjs +0 -25
  215. package/lib/chunk-5P4PHJRL.mjs +0 -9
  216. package/lib/chunk-5TC3QB4U.mjs +0 -10
  217. package/lib/chunk-7ABODJ4G.mjs +0 -7
  218. package/lib/chunk-7EGQP6S4.mjs +0 -7
  219. package/lib/chunk-7FFGJWHN.mjs +0 -7
  220. package/lib/chunk-7YDNUBO5.mjs +0 -7
  221. package/lib/chunk-A527W53V.mjs +0 -7
  222. package/lib/chunk-ADOAS63R.mjs +0 -7
  223. package/lib/chunk-B5QQJ4SI.mjs +0 -7
  224. package/lib/chunk-CION3VMZ.mjs +0 -7
  225. package/lib/chunk-CSBS5U5I.mjs +0 -7
  226. package/lib/chunk-DB7RBE5D.mjs +0 -7
  227. package/lib/chunk-E5ZB3LU5.mjs +0 -7
  228. package/lib/chunk-EFR2Y7E4.mjs +0 -7
  229. package/lib/chunk-EHQ3FX6X.mjs +0 -7
  230. package/lib/chunk-EQNW3UC2.mjs +0 -7
  231. package/lib/chunk-F43REJDZ.mjs +0 -10
  232. package/lib/chunk-GSG7WZHM.mjs +0 -7
  233. package/lib/chunk-HOJYWTP7.mjs +0 -20
  234. package/lib/chunk-HS4YRX4J.mjs +0 -7
  235. package/lib/chunk-I7O6C2B5.mjs +0 -8
  236. package/lib/chunk-IFETCRWE.mjs +0 -10
  237. package/lib/chunk-IQXHJEYB.mjs +0 -7
  238. package/lib/chunk-JPUR2CFX.mjs +0 -10
  239. package/lib/chunk-K327QKMD.mjs +0 -7
  240. package/lib/chunk-KRCA6IPH.mjs +0 -8
  241. package/lib/chunk-LPBMBW3O.mjs +0 -13
  242. package/lib/chunk-LWW4U276.mjs +0 -7
  243. package/lib/chunk-MFG4MUIO.mjs +0 -9
  244. package/lib/chunk-MJU2PGZQ.mjs +0 -15
  245. package/lib/chunk-OAZRPP4I.mjs +0 -7
  246. package/lib/chunk-OO6CLPEH.mjs +0 -7
  247. package/lib/chunk-OPXCV2KL.mjs +0 -7
  248. package/lib/chunk-P33PSCXK.mjs +0 -7
  249. package/lib/chunk-Q3DM32KF.mjs +0 -11
  250. package/lib/chunk-QR3WELJQ.mjs +0 -7
  251. package/lib/chunk-QWT2C74M.mjs +0 -7
  252. package/lib/chunk-R3X3LV64.mjs +0 -14
  253. package/lib/chunk-RMBPOTD7.mjs +0 -7
  254. package/lib/chunk-SIHORWVK.mjs +0 -7
  255. package/lib/chunk-T62WNR54.mjs +0 -7
  256. package/lib/chunk-TTFDUKUS.mjs +0 -47
  257. package/lib/chunk-VE6XKGGD.mjs +0 -7
  258. package/lib/chunk-VGW4MXXZ.mjs +0 -7
  259. package/lib/chunk-VS7ZXUII.mjs +0 -824
  260. package/lib/chunk-VXQLDM4R.mjs +0 -7
  261. package/lib/chunk-VYXMVJL5.mjs +0 -7
  262. package/lib/chunk-W7U5E5ZL.mjs +0 -9
  263. package/lib/chunk-WXAQ7FK3.mjs +0 -115
  264. package/lib/chunk-YS4G22C2.mjs +0 -7
  265. package/lib/chunk-ZM6OJGIG.mjs +0 -7
  266. package/lib/chunk-ZUTYVST5.mjs +0 -7
@@ -0,0 +1,22 @@
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 $n,b as Pd,c as _n,d as Td,f as Fd,g as qn,i as Ld,j as Nd}from"./chunk-Y4TDVDP2.mjs";import{a as Fr,b as jd,c as Ko,d as st,e as Bn,f as ar,g as Vo,h as Ed}from"./chunk-JJITOWZK.mjs";import{l as Mi}from"./chunk-YMDFF657.mjs";import{c as Ad,d as de}from"./chunk-UV74P4H2.mjs";import{k as Sd}from"./chunk-5K2I2DMP.mjs";import{i as Di}from"./chunk-7WSLT5VX.mjs";import{e as zi,f as Do}from"./chunk-YT22LMF7.mjs";import{G as Id,N as Uo,O as Od,i as md,l as xn,m as yd,n as wd,o as bd,p as Rd,v as kd}from"./chunk-A7JJWOLT.mjs";import{l as vd}from"./chunk-52EXDVPN.mjs";import{a as hi,b as Fn}from"./chunk-XCA5AONB.mjs";import{$a as Fo,Dc as En,Ec as No,Xa as Wa,Ya as Ua,Za as Ka,_a as Va,a as za,ab as Ha,b as At,bb as Ya,cb as Ja,db as Xa,eb as Za,g as Ao,h as Ma,j as Oe,k as Da,l as Sr,m as xa,n as bt,o as re,s as Po,wc as ot}from"./chunk-ISSP2FZ5.mjs";import{a as On}from"./chunk-CE6ZDGBB.mjs";import{a as Ri,b as ki}from"./chunk-BOGNK4LV.mjs";import{Ha as ud,Na as fd,Q as ld,Ua as pd,Wa as Wo,Za as gd,_a as hd,a as ua,b as fa,h as nd,i as od,n as qo,ua as Go}from"./chunk-P55MKIZX.mjs";import{a as ai,b as Lo,c as ii,d as di,e as ci,k as pi,l as gi}from"./chunk-O2PUGRNW.mjs";import{B as ti,C as ri,J as ni,N as xt,O as oi,P as Pn,Q as si}from"./chunk-7SDZR6SR.mjs";import{a as sd,b as Bo,c as Er,d as Mn,h as ad,i as Dn,j as id,l as dd,m as cd}from"./chunk-TEIBWMJM.mjs";import{c as Tn,d as jn}from"./chunk-T63U4OZJ.mjs";import{e as Li,h as Ni,j as Ci}from"./chunk-YAIIRFKJ.mjs";import{f as Fi,i as Mo,j as Cn}from"./chunk-WSUKC2U3.mjs";import{a as li,c as ui,d as fi,r as zo}from"./chunk-SAMWHL22.mjs";import{H as Co,L as Ii,i as vi,k as Nn}from"./chunk-J24TIGSI.mjs";import{a as Ar,b as Ln,f as bi,h as Pr}from"./chunk-HKUWHVI7.mjs";import{r as Ae}from"./chunk-PBE44M2Y.mjs";import{a as ia,b as da,d as ca,e as la}from"./chunk-ZUOPC4W2.mjs";import{b as mi,c as yi,g as wi}from"./chunk-JQZTMFO7.mjs";import{$a as xi,Ec as rd,Pb as Wi,Ra as xo,Vb as Ui,Xb as Ki,Yb as Vi,_a as $o,ac as Hi,b as La,bc as Yi,c as Na,db as $i,e as Xe,eb as _o,ec as Ji,f as Ca,fb as _i,fc as Xi,gc as Zi,hb as jr,ib as Bi,jb as qi,lb as Gi,sc as Qi,tc as ed,uc as td}from"./chunk-JFNLKHY6.mjs";import{q as zn}from"./chunk-VZVICK7Q.mjs";import{a as ut,b as Pt}from"./chunk-VV3B6IC3.mjs";import{a as St}from"./chunk-4TLYUZD5.mjs";import{b as Oi,d as Si,f as Tr,g as Ai,h as Pi,i as Ti,j as ji,p as Ei}from"./chunk-7PY3VQP3.mjs";import{i as $a}from"./chunk-INIT2UKJ.mjs";import{h as ei}from"./chunk-HFUDCNU5.mjs";import{b as Sn}from"./chunk-HFSBDM7B.mjs";import{b as Ba,c as lt,e as To,g as qa,h as jo,i as Ga,j as Eo}from"./chunk-OHEOJISY.mjs";import{a as _a}from"./chunk-EADHKH3A.mjs";import{g as ja,h as sr,i as Ea,j as Fa}from"./chunk-L4INJ5TZ.mjs";import{$ as Ia,E as wa,F as Mt,G as wt,I as Oo,L as ba,M as Ra,N as ka,Y as So,Z as va,a as Ir,b as Je,c as er,d as bn,da as Dt,ea as Oa,f as tr,fa as Sa,g as Rn,ga as Aa,ha as Pa,ia as Ta,ja as nr,k as pa,ka as or,l as Io,m as ga,n as ha,o as ma,p as ya,q as Ve,r as Ue,s as kn,t as Or,u as vn,v as rr,z as In}from"./chunk-KIMQQ6JQ.mjs";import{a as Me,h as ge}from"./chunk-TZE3Y7IQ.mjs";import{b as X}from"./chunk-CA5NAXSU.mjs";import{a as Qa}from"./chunk-ZUTUYBNW.mjs";import{b as An}from"./chunk-UNDIBZWG.mjs";import{Ac as pn,B as Qs,Bc as ze,Cc as Qt,Cd as sa,Dc as ta,Fc as ra,Gc as gn,Jd as aa,Ld as vr,Mc as hn,Nc as na,Sc as oa,Td as zt,Ud as wn,Xc as mn,Yc as yn,lc as ea,mc as Zt,pc as ln,rc as qe,s as Zs,sc as un,tc as yt,uc as Ct,vc as fn,yc as We,zc as Ye}from"./chunk-ZQO5PDX5.mjs";import{b as Ce,e as dn,f as cn,k as mt,l as Ge,s as Ys,u as Js,v as Xs,z as vo}from"./chunk-WZQEK4WT.mjs";import{createHash as Md}from"node:crypto";import*as Kn from"node:fs/promises";import*as Nr from"node:path";import*as Rt from"node:fs/promises";import*as Tt from"node:path";function Gn(o){return o.map(({objectApiName:e,why:t,count:r})=>({objectApiName:e,count:r,note:Rn(r,t)}))}var Cd=/^\d+\.\d+\.\d+$/,Ll=/^[0-9a-f]{12}$/,Ze=class extends Error{constructor(e){super(e),this.name="ManifestError"}};function zd(o){let e=(o.now?.()??new Date).toISOString(),t={version:o.version,status:"frozen",frozenAt:e,source:o.source,saltFingerprint:o.saltFingerprint,rulesVersion:o.rulesVersion,volumetry:o.volumetry,controls:{nonReidentification:o.nonReidentification,dryRunLoad:null,author:o.author,date:e},...o.coverage?{coverage:o.coverage}:{}};return Ho(t),t}function Ho(o){if(!Cd.test(o.version))throw new Ze(`version must be semver, got ${JSON.stringify(o.version)}`);if(o.status!=="frozen")throw new Ze(`status must be "frozen", got ${JSON.stringify(o.status)}`);if(!o.frozenAt)throw new Ze("frozenAt is required");if(!o.source?.orgId||!o.source.decisionDate)throw new Ze("source.orgId and source.decisionDate are required");if(!Ll.test(o.saltFingerprint))throw new Ze("saltFingerprint must be 12 lowercase hex chars of the salt SHA-256");if(!Cd.test(o.rulesVersion))throw new Ze(`rulesVersion must be semver, got ${JSON.stringify(o.rulesVersion)}`);if(typeof o.volumetry?.budgetMax!="number"||!o.volumetry.measured)throw new Ze("volumetry.budgetMax and volumetry.measured are required");if(!o.controls?.nonReidentification)throw new Ze("controls.nonReidentification is required");if(!o.controls.author||!o.controls.date)throw new Ze("controls.author and controls.date are required");let e=o.coverage;if(e!==void 0&&(typeof e.objects!="number"||typeof e.truncated!="boolean"||typeof e.maxNodes!="number"||!Array.isArray(e.unboundedObjects)||!Array.isArray(e.filesLeftOut)||e.leftToThePlatform!==void 0&&!Array.isArray(e.leftToThePlatform)||e.exclusionCosts!==void 0&&!Array.isArray(e.exclusionCosts)||e.requiredLeftEmpty!==void 0&&!Array.isArray(e.requiredLeftEmpty)||e.keptWithoutARule!==void 0&&!Array.isArray(e.keptWithoutARule)||e.encryptedNotKept!==void 0&&!Array.isArray(e.encryptedNotKept)))throw new Ze("coverage, when present, needs objects, truncated, maxNodes, unboundedObjects and filesLeftOut, and a list of what it left to the platform, of what its exclusions cost, of the required fields the rules leave empty, of the fields kept without a rule, or of the encrypted fields not kept, if it names any")}function Wn(o){return Ho(o),`${JSON.stringify(o,null,2)}
8
+ `}function ir(o){if(typeof o!="object"||o===null||Array.isArray(o))throw new Ze("Manifest must be a JSON object");let e=o;return Ho(e),e}var Lr="platform-records.json",Yo=class extends Error{constructor(e){let t=e.checks.filter(r=>!r.passed).map(r=>`${r.name} (${r.violations.length} violation(s))`).join(", ");super(`Refusing to write the frozen dataset: non-reidentification control FAILED [${t}]. A FAIL means nothing is written or versioned.`),this.name="ControlNotPassedError"}},Un=class{guard;constructor(e){this.guard=e??new de}async write(e,t,r,n){if(!n.passed)throw new Yo(n);let s=this.guard.assertOutsideRepo(e),a=this.guard.assertOutsideRepo(Tt.join(s,"data"));await Rt.mkdir(a,{recursive:!0});for(let l of await Rt.readdir(a))l.endsWith(".json")&&await Rt.rm(this.guard.assertOutsideRepo(Tt.join(a,l)));let d=[],i=async(l,c)=>{let f=this.guard.assertOutsideRepo(l);await Rt.writeFile(f,`${JSON.stringify(c)}
9
+ `,"utf8"),d.push(f)},u=this.guard.assertOutsideRepo(Tt.join(s,"manifest.json"));await Rt.writeFile(u,Wn(r),"utf8"),d.push(u);for(let l of t.objects)await i(Tt.join(a,`${l.objectApiName}.json`),{objectApiName:l.objectApiName,records:l.records});return await i(Tt.join(s,"record-types.json"),t.recordTypes),await i(Tt.join(s,"personcontact-sidecar.json"),t.personContactSidecar),await i(Tt.join(s,Lr),{...t.standardPricebook?{standardPricebook:t.standardPricebook}:{}}),{dir:s,files:d}}};var Jo="manifest.json",Nl=["record-types.json","personcontact-sidecar.json",Lr],Xo="data",Cl="sha256:";async function Rp(o){let e=await Zo(Nr.join(o,Jo));if(e===void 0)throw new Error(`No frozen dataset at ${o}: it holds no ${Jo}.`);let t=[{name:Jo,content:Ml(e)}];for(let n of Nl){let s=await Zo(Nr.join(o,n));s!==void 0&&t.push({name:n,content:s})}for(let n of await zl(Nr.join(o,Xo))){let s=await Zo(Nr.join(o,Xo,n));s!==void 0&&t.push({name:`${Xo}/${n}`,content:s})}let r=Md("sha256");for(let{name:n,content:s}of t.sort((a,d)=>Dd(a.name,d.name)))r.update(`${n}\0${Md("sha256").update(s).digest("hex")}
10
+ `);return`${Cl}${r.digest("hex")}`}async function zl(o){let e;try{e=await Kn.readdir(o)}catch(t){if(t.code==="ENOENT")return[];throw t}return e.filter(t=>t.endsWith(".json"))}async function Zo(o){try{return await Kn.readFile(o)}catch(e){if(e.code==="ENOENT")return;throw e}}function Ml(o){let e;try{e=JSON.parse(o.toString("utf8"))}catch{return o}if(es(e)&&es(e.controls)){let t={...e.controls};delete t.dryRunLoad,e={...e,controls:t}}return Buffer.from(Qo(e),"utf8")}function Qo(o){return Array.isArray(o)?`[${o.map(Qo).join(",")}]`:es(o)?`{${Object.keys(o).sort(Dd).map(t=>`${JSON.stringify(t)}:${Qo(o[t])}`).join(",")}}`:JSON.stringify(o)??"null"}function es(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Dd(o,e){return o===e?0:o<e?-1:1}var He=class extends Error{constructor(t,r,n={}){super(r);this.code=t;this.params=n;this.name="LoadGuardError"}code;params};function dr(o){return o.objects.reduce((e,t)=>e+t.records.length,0)}async function xd(o){if(ts(o),o.protectedOrgIds?.includes(o.orgId))throw new He("protected-environment",`Refusing frozen-dataset load on protected environment ${o.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:o.orgId});if(o.manifest&&o.manifest.source.orgId===o.orgId)throw new He("source-is-target",`Refusing frozen-dataset load on ${o.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:o.orgId});if(!await o.mockDetector.areCalloutsMocked(o.orgId))throw new He("unmocked-callouts",`Refusing frozen-dataset load on ${o.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:o.orgId});if(dr(o.dataset)===0)throw new He("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.")}function ts(o){if(o.orgTier==="staging")throw new He("non-sandbox",`Refusing frozen-dataset load on ${o.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:o.orgId,tier:o.orgTier});if(o.orgTier!=="development"&&o.orgTier!=="scratch")throw new He("non-sandbox",`Refusing frozen-dataset load on ${o.orgTier} org ${o.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:o.orgId,tier:o.orgTier})}var Cr=class{constructor(e,t){this.orgAccess=e;this.config=t}orgAccess;config;async areCalloutsMocked(e){let t=`SELECT Id FROM ${ge(this.config.metadataTypeApiName)} WHERE ${ge(this.config.isMockedFieldApiName)} = true LIMIT 1`;try{return(await this.orgAccess.query(e,t)).length>0}catch{return!1}}};var Vn=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=[],s=[],a=[];for(let d of e.records){let i={},u=e.accountKindOf?.(d.referenceId);for(let[l,c]of Object.entries(d.fields)){if(u!==void 0&&mn(Ve,l,u))continue;let f=t.get(l);if(!f){this.countRemoval(r,l,"not-in-target");continue}if(!f.createable){this.countRemoval(r,l,"not-createable");continue}if(e.leaveOutEncrypted===!0&&f.type===li){c!=null&&c!==""&&this.countRemoval(r,l,"may-hold-masks");continue}let p=c;typeof p=="string"&&p!==""&&f.restrictedPicklist===!0&&(f.type==="picklist"||f.type==="multipicklist")&&(p=await this.alignPicklistValue(e,f.name,f.type,d,p,n,s)),i[l]=p}a.push(i)}return{objectApiName:e.objectApiName,alignedRecords:a,removals:[...r.entries()].map(([d,i])=>({objectApiName:e.objectApiName,field:d,reason:i.reason,affectedRecords:i.count})),adjustments:n,missingRequired:this.detectMissingRequired(e,a),uiApiWarnings:s}}detectMissingRequired(e,t){let r=t.filter((i,u)=>!e.linked?.has(e.records[u].referenceId));if(r.length===0)return[];let n=[],s=e.accountKindOf,a=s?e.records.filter(i=>!e.linked?.has(i.referenceId)).map(i=>s(i.referenceId)):[];for(let i of e.describe.fields){let u=s?yn(Ve,i.name):void 0;if(!i.createable||i.nillable&&u===void 0||i.defaultedOnCreate)continue;let l=r.filter((f,p)=>u===void 0||rr(u,a[p]));if(l.length===0)continue;if(!l.some(f=>{let p=f[i.name];return p!=null&&p!==""})){let f=i.unique?"unique":i.nameField?"name":void 0,p=(i.referenceTo?.length??0)>0,g=(i.picklistValues??[]).filter(h=>h.active).map(h=>h.value);n.push({objectApiName:e.objectApiName,field:i.name,isLookup:p,referenceTo:i.referenceTo??[],...f?{distinct:f}:{},...u?{accountKind:u}:{},...!p&&i.type?{fieldType:i.type}:{},...!p&&g.length>0?{activeValues:g}:{}})}}let d=gn(e.objectApiName,i=>e.describe.fields.some(u=>u.name===i&&u.createable),i=>r.some(u=>u[i]!==void 0&&u[i]!==null&&u[i]!==""));if(d!==void 0&&!n.some(i=>i.field===d)){let i=e.describe.fields.find(u=>u.name===d)?.type;n.push({objectApiName:e.objectApiName,field:d,isLookup:!1,referenceTo:[],...i?{fieldType:i}:{}})}return n}async alignPicklistValue(e,t,r,n,s,a,d){let i=r==="multipicklist",u=i?s.split(";"):[s],l=e.describe.fields.find(y=>y.name===t),c=new Set((l?.picklistValues??[]).filter(y=>y.active).map(y=>y.value)),f=u.filter(y=>!c.has(y));if(f.length>0){let y=e.ruleFor(e.objectApiName,t);return a.push({objectApiName:e.objectApiName,field:t,referenceId:n.referenceId,value:s,rule:y,scope:"global"}),this.applyRule(y,u,f,i)}let p=e.resolvedRecordTypes.get(n.referenceId);if(!p)return s;let g=await this.uiApiValues(e,p,t,d);if(g===null)return s;let h=u.filter(y=>!g.includes(y));if(h.length===0)return s;let m=e.ruleFor(e.objectApiName,t);return a.push({objectApiName:e.objectApiName,field:t,referenceId:n.referenceId,value:s,rule:m,scope:"record-type"}),this.applyRule(m,u,h,i)}async uiApiValues(e,t,r,n){let s=`${e.orgId}|${e.objectApiName}|${t}|${r}`,a=this.uiApiCache.get(s);if(a!==void 0)return a;try{let d=await this.orgAccess.picklistValues(e.orgId,e.objectApiName,t,r);return this.uiApiCache.set(s,d),d}catch(d){return this.uiApiCache.set(s,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(s=>!r.includes(s)).join(";"):""}countRemoval(e,t,r){let n=e.get(t);n?n.count++:e.set(t,{reason:r,count:1})}};var zr="Opportunity",Mr="SyncedQuoteId",Dl="OpportunityLineItem",rs="QuoteLineItem";function ns(o,e){let t=(d,i)=>{let u=new Map;for(let{referenceId:l,fields:c}of o.get(d)??[]){let f=c[i];typeof f!="string"||f===""||!e(l)||u.set(f,(u.get(f)??0)+1)}return u},r=t(Dl,"OpportunityId"),n=t(rs,"QuoteId"),s=new Set((o.get("Quote")??[]).map(d=>d.referenceId)),a=[];for(let{referenceId:d,fields:i}of o.get(zr)??[]){let u=i[Mr];if(typeof u!="string"||!s.has(u)||!e(d)||!e(u))continue;let l=r.get(d)??0,c=n.get(u)??0;l>c&&a.push({opportunity:d,quote:u,products:l,lines:c})}return a}function $d(o,e,t=!1){if(o.length===0)return;let r=o.length===1,n=o.reduce((l,c)=>l+c.products,0),s=o.reduce((l,c)=>l+c.lines,0),a=r?"its":"their",d=r?"the quote's":"the quotes'",i=s===0?`none of ${d} lines`:`${s} of ${d} lines`,u=e&&s===0?", which excludedObjects leaves out":"";return{objectApiName:zr,count:o.length,note:`${o.length} ${t?"would be ":""}left unsynced with ${a} quote: the load ${t?"would write":"wrote"} ${n} of ${a} products and ${i}${u} \u2014 synced, the platform replaces an opportunity's products with its quote's lines; ${Mr} left empty, the products kept`}}var Qe=class extends Error{constructor(t,r,n){super(t);this.gaps=r;this.recordTypesUntold=n;this.name="LoadConfigError"}gaps;recordTypesUntold;refusedBeside},xr=class extends Error{constructor(e){super(e),this.name="LoadRecordsExceededError"}},cr=class extends Error{constructor(t){let r=t.reduce((n,s)=>n+s.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 xl(o){return o.perObject.reduce((e,t)=>e+t.toInsert,0)}function $l(o,e){if(!(e===void 0||o<=e))return`This load would insert ${o} 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 at=class extends Error{constructor(t,r=!0){super(r?`The load was cancelled ${Zd(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},_t=class extends Error{constructor(t,r,n){super(_l(t,r,n),{cause:t});this.written=r;this.name="FrozenLoadFailedError",this.mappingKept=n===void 0}written;mappingKept};function _l(o,e,t){return`${X(o)}
11
+ The load failed ${Zd(e,t)}`}function Zd(o,e){let t=new Map,r=(i,u)=>{u!==0&&t.set(i,(t.get(i)??0)+u)};for(let i of o.placeholders)r(i.placeholderObjectApiName,1);for(let i of o.perObject)r(i.objectApiName,i.inserted);let n=[...t.values()].reduce((i,u)=>i+u,0),s=[...Object.values(o.purge.deleted),...Object.values(o.purge.deactivated)].reduce((i,u)=>i+u,0),a=[...n>0?[`created ${n} record(s) (`+[...t].map(([i,u])=>`${i}: ${u}`).join(", ")+")"]:[],...s>0?[`purged ${s} 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.",a===""?`before it had written the whole dataset. ${d}`:`after it had ${a}. ${d}`}function Qd(o,e){let t=[];for(let[r,n]of o.givenRules){let s=[],a={};for(let{referenceId:i,fields:u}of o.alignedByObject.get(r)??[]){if(!ht(u.RecordTypeId)||!e(i))continue;s.push(i);let l=o.withoutRecordType.get(i)??"notRead";a[l]=(a[l]??0)+1}if(s.length===0)continue;let{predicted:d}=n;t.push({given:{objectApiName:r,rows:s.length,why:a,...d?{predicted:d}:{}},rule:n,keys:s})}return t}function ec(o){return{namespacePrefix:o.namespacePrefix,developerName:o.developerName}}function Bl(o){if(!o)return"the user's default record type applies";if(o.kind==="master")return"the target leaves it on Master for that user";let{developerName:e}=o.info;return o.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 ql(o,e){if(!e.mappingKept())try{await e.keepMapping()}catch(t){return new _t(o,e.written,X(t))}return new _t(o,e.written)}function tc(o,e,t){let r=t.map(n=>lt(n.namespacePrefix,n.developerName));return new Qe(`The dataset's ${o} 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:o,name:e,recordTypes:r})}function Gl(o){for(let{objectApiName:e,records:t}of o.objects){let r=o.recordTypes[e]??[];if(!(r.length<2))for(let n of t){let s=n.fields.RecordTypeId;if(typeof s!="string"||s==="")continue;if(n.recordTypeDeveloperName!==void 0){let d=jo(n.recordTypeDeveloperName,r,ec);if(d&&"found"in d)continue}let a=r.filter(d=>d.name===s);if(a.length>1)return tc(e,s,a)}}}var rc="Opportunity",Yn="placeholder:",ss=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,s)=>{t.set(n,[...t.get(n)??[],...s])};for(let{objectApiName:n,referenceIds:s}of e)r(n,s);for(let[n,s]of this.byObject)r(n,s);return[...t].map(([n,s])=>({objectApiName:n,referenceIds:s}))}};function Wl(o){if(o.startsWith(Yn))return o.split(":")[1]??"Unknown";let e=o.lastIndexOf("-");return e>0?o.slice(0,e):"Unknown"}function Ul(o){return typeof o=="number"?String(o):typeof o=="boolean"?o?"TRUE":"FALSE":`'${Me(String(o))}'`}var jt=200;function pe(o){return o.slice(0,15)}var Kl=["CreatedDate","LastModifiedDate"],Vl=[["CreatedDate","LastModifiedDate","SystemModstamp"],["SystemModstamp"]];function $t(o){return typeof o=="string"?Date.parse(o):Number.NaN}function _d(o){return o.success||o.errors.some(e=>e.includes("ENTITY_IS_DELETED"))}function Bd(o){if(o.tried===0)return"";let e=o.tried-o.went,t=[o.went>0?`${o.went} went`:"",e>0?`${e} refused again`:""].filter(Boolean);return` \u2014 ${o.tried} refused at first, sent again once the rest had gone: ${t.join(", ")}`}function qd(o,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=o.failures.find(s=>s.objectApiName===e.objectApiName&&pe(s.recordId)===pe(e.id));n?n.errors=[...n.errors,r]:o.failures.push({objectApiName:e.objectApiName,recordId:e.id,errors:[r]})}function os(o,e){let t=(o.notInserted??0)+(e.notInserted??0),r=[o.writtenWithoutFields,e.writtenWithoutFields].reduce((n,s)=>s?Mo(n,s):n,void 0);return{objectApiName:e.objectApiName,fromFiles:o.fromFiles+e.fromFiles,inserted:o.inserted+e.inserted,reused:o.reused+e.reused,skippedDuplicates:[...o.skippedDuplicates,...e.skippedDuplicates],failed:[...o.failed,...e.failed],...r?{writtenWithoutFields:r}:{},...t>0?{notInserted:t}:{}}}function Gd(o){let e=o.filter(r=>r.replacedWith===void 0).map(r=>r.field),t=o.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 Jn(o,e="inserted"){return o>0?`, ${o} not ${e}: the load was cancelled first`:""}function as(o,e="inserted"){return o>0?`, ${o} not ${e}: the load failed`:""}function Hl(o,e){return o>0?"error":e>0?"stopped":"done"}function gt(o,e,t,r){return{phase:o,status:"error",progress:e,message:`${t} \u2014 ${X(r)}`}}var Wd={phase:"guards",status:"started",progress:0,message:"Evaluating entry guards"};function Hn(o,e){let{phase:t,progress:r,did:n,refused:s,notDone:a,done:d,notes:i=""}=o;return e?{phase:t,status:"error",progress:r,message:`${n}${as(a,d)}${i} \u2014 ${X(e.cause)}`}:{phase:t,status:Hl(s,a),progress:r,message:`${n}${Jn(a,d)}${i}`}}var Dr={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 Yl(o){return o.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 nc(o,e){let t=new Map;for(let{accountReferenceId:r,contactReferenceId:n}of o.personContactSidecar??[])e.get(n)===Ue&&t.set(n,r);for(let r of o.objects.find(n=>n.objectApiName===Ue)?.records??[]){if(t.has(r.referenceId)||!Or(r.fields))continue;let n=r.fields.AccountId;t.set(r.referenceId,typeof n=="string"&&e.get(n)===Ve?n:"")}return t}function Jl(o){let e=new Set;for(let{accountReferenceId:t}of o.personContactSidecar??[])t!==""&&e.add(t);for(let t of o.objects.find(r=>r.objectApiName===Ve)?.records??[]){let r=t.fields.LastName;(Or(t.fields)||r!=null)&&e.add(t.referenceId)}return e}function Xn(o,e,t){let r=o.accountKind;return r===void 0?[...e]:e.filter(n=>rr(r,t(n.referenceId)))}var $r=class{constructor(e){this.deps=e;this.config=e.config??{},this.sasGuard=e.sasGuard??new de}deps;config;sasGuard;journal;async gateLoad(e){try{await this.passEntryGuards(e)}catch(s){throw e.onProgress?.(Wd),e.onProgress?.(gt("guards",2,"Entry guards not passed",s)),s}let t=e.dataset;if(e.pilot)try{t=this.filterPilotScope(e.dataset,e.pilot.rootReferenceId)}catch(s){throw e.onProgress?.({phase:"pilot",status:"started",progress:3,message:"Selecting the root folder"}),e.onProgress?.(gt("pilot",4,"Root folder not selected",s)),s}let r=Gl(t);if(r)throw e.onProgress?.({phase:"align",status:"started",progress:12,message:"Resolving record types"}),e.onProgress?.(gt("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(s=>s.records.length>0).map(s=>s.objectApiName).join(", "),recordCount:{atMost:dr(e.dataset)},module:"frozendataset"})}passEntryGuards(e){return xd({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 at||!n?.wroteSome()?r:await ql(r,n)}}async planLoad(e){let t=e.now??(()=>new Date),r=d=>e.onProgress?.(d),n=await this.prepare(e,r,{}),s=e.reload&&!e.pilot?await this.planPurge(e.orgId,n.previousLoads,n.mapping):void 0;if(s){let d=await this.foundUnderThePurge(e.orgId,s.residuals,n.mapping,n.refIndex);if(d.length>0)throw new cr(d)}let a=Kd(n,s,{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(a)}async withValidationRules(e){let t=this.deps.readValidationRules,r=e.perObject.filter(i=>i.toInsert>0).map(i=>i.objectApiName),n=[...new Set([...r,...e.placeholders.map(i=>i.placeholderObjectApiName)])];if(!t||n.length===0)return e;let s=new Map,a=new Map;try{for(let{objectApiName:i,onChangeOnly:u,...l}of await t(n))u?a.set(i,[...a.get(i)??[],l.name]):s.set(i,[...s.get(i)??[],l])}catch(i){return{...e,validationRulesUnread:X(i)}}let d=new Set(r);return{...e,perObject:e.perObject.map(i=>{if(i.toInsert===0)return i;let u=s.get(i.objectApiName)??[],l=a.get(i.objectApiName)??[];return{...i,...u.length>0?{validationRules:u}:{},...l.length>0?{validationRulesOnChange:l}:{}}}),placeholders:e.placeholders.map(i=>{let u=d.has(i.placeholderObjectApiName)?[]:s.get(i.placeholderObjectApiName)??[];return u.length>0?{...i,validationRules:u}:i})}}async prepare(e,t,r){let{orgId:n}=e;t(Wd);try{await this.passEntryGuards(e)}catch($){throw t(gt("guards",2,"Entry guards not passed",$)),$}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 s=await this.deps.mappingStore.previousLoads().catch($=>{throw t(gt("mapping",3,"Mapping not read",$)),$});t({phase:"mapping",status:"done",progress:3,message:`Mapping read: ${s.length} earlier load(s)`});let a=e.dataset;if(e.pilot){t({phase:"pilot",status:"started",progress:3,message:"Selecting the root folder"});try{a=this.filterPilotScope(e.dataset,e.pilot.rootReferenceId)}catch(K){throw t(gt("pilot",4,"Root folder not selected",K)),K}let $=a.objects.reduce((K,Z)=>K+Z.records.length,0);t({phase:"pilot",status:"done",progress:4,message:`Root folder selected: ${$} record(s)`})}let d=cs(a),i=eu(e.dataset),u=nc(a,d),l=iu(a,d,u),c=ua(l),f=c.flat(),p=new tr,g=new tr(au),h={...a,objects:a.objects.map($=>({...$,records:$.records.filter(K=>!p.leaveOut($.objectApiName,K.referenceId,pa($.objectApiName,K.fields,typeof K.fields.RelationId=="string"?d.get(K.fields.RelationId):void 0))&&!g.leaveOut($.objectApiName,K.referenceId,K.fields))}))},m=new Map,y=new Set,R=new Set;if(e.reload||e.linkByKeys){t({phase:"reload",status:"started",progress:5,message:"Reusing reference data"}),r.endOpenLine=$=>t(gt("reload",10,"Reference data not reused",$)),await this.reuseByIdentityKeys(e,h,m,y);for(let $ of y)R.add($);t({phase:"reload",status:"done",progress:10,message:`Reference data: ${y.size} reused`}),r.endOpenLine=void 0}if(h.standardPricebook||Yd(h).length>0){t({phase:"catalog",status:"started",progress:10,message:"Looking up the catalog the target already holds"});let $;try{$=await this.lookUpTheCatalog(n,h,m,y)}catch(K){throw t(gt("catalog",11,"Catalog not looked up",K)),K}t({phase:"catalog",status:"done",progress:11,message:`Catalog looked up: ${$.join("; ")}`})}t({phase:"align",status:"started",progress:12,message:"Resolving record types"}),r.endOpenLine=$=>t(gt("align",20,"Schema not aligned",$));let L=[],T=new Map,j=new Map,x=new Map;for(let $ of h.objects){let K=[];for(let Z of $.records)K.push(await this.resolveRecordType(e,a,$.objectApiName,Z,j,L,x));T.set($.objectApiName,K)}let U=new Vn(this.deps.orgAccess),S={objectResults:[],excludedObjects:[],removals:[],adjustments:[],recordTypeIssues:L},w=new Map,v=new Map,A=new Map,N=new Map,I=new Map,P,C=Jl(a),G=$=>C.has($)?P===!1?"personAsBusiness":"person":"business",D=new Map,W=new Map,V=e.writeEncrypted!==!0&&e.manifest?.coverage?.encryptedNotKept===void 0;for(let $ of h.objects){let K=$.objectApiName;if($.records.length===0)continue;let Z=$.records.filter(O=>!y.has(O.referenceId)),ne=(O,J)=>{S.excludedObjects.push({objectApiName:K,reason:O}),I.set(K,{objectApiName:K,fromFiles:a.objects.find(ee=>ee.objectApiName===K)?.records.length??$.records.length,inserted:0,reused:$.records.length-Z.length,skippedDuplicates:[],failed:Z.map(ee=>({objectApiName:K,referenceId:ee.referenceId,errors:[J]}))}),Z.length!==0&&t({phase:"align",objectName:K,status:"error",progress:12,message:`Skipped ${K} \u2014 ${O}`})},he;try{he=await this.deps.orgAccess.describe(n,K)}catch(O){let J=`Not present in target org: ${O instanceof Error?O.message:String(O)}. 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`;ne(J,J);continue}if(K===Ve&&(P=he.fields.some(O=>O.name===kn)),he.createable===!1&&Z.length>0){ne(`Not createable in target org: ${Z.length} record${Z.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}A.set(K,new Set(he.fields.filter(O=>O.updateable===!1).map(O=>O.name)));let _e=he.fields.filter(O=>O.lookupFilter!==void 0&&O.createable&&(O.referenceTo?.length??0)>0).map(O=>({field:O.name,referenceTo:[...O.referenceTo??[]]}));_e.length>0&&N.set(K,_e);let De=Sn(he.recordTypeInfos);if(De.some(O=>!O.master)){let O=id(Dn(De));W.set(K,{types:De,...O?{predicted:O}:{}})}let k=nu(K,he,this.config);k.length>0&&D.set(K,k),v.set(K,new Set(he.fields.filter(O=>O.createable&&!O.nillable&&!O.defaultedOnCreate&&(O.referenceTo?.length??0)>0).map(O=>O.name)));let F=await U.alignObject({orgId:n,objectApiName:K,records:T.get(K)??[],describe:he,resolvedRecordTypes:j,ruleFor:(O,J)=>this.picklistRuleFor(O,J),linked:y,...K===Ve?{accountKindOf:G}:{},...V?{leaveOutEncrypted:V}:{}});S.objectResults.push(F),S.removals.push(...F.removals),S.adjustments.push(...F.adjustments),w.set(K,F.alignedRecords.map((O,J)=>({referenceId:(T.get(K)??[])[J].referenceId,fields:O})))}let H=await this.linkWhatThePlatformKeeps(n,S.objectResults,w,i,m,y,G),E=e.reload||e.linkByKeys?await this.reuseByKeysAsWritten(n,h,S.objectResults,w,i,m,y,G):{linked:[],said:[],leftEmpty:[]};for(let $ of[...H.linked,...E.linked])R.add($);let q=[...H.said,...E.said];t({phase:"align",status:"done",progress:20,message:`Schema aligned${q.length>0?` \u2014 ${q.join("; ")}`:""}`}),r.endOpenLine=void 0;let Y=new tr(ou(D));ru(w,v,[p,g,Y]);for(let $ of S.objectResults){let K=(w.get($.objectApiName)??[]).filter(Z=>!y.has(Z.referenceId));$.missingRequired=$.missingRequired.filter(Z=>Xn(Z,K,G).some(ne=>ht(ne.fields[Z.field])))}t({phase:"placeholders",status:"started",progress:22,message:"Checking required fields"});let ae=await this.planRequiredFields(e,S.objectResults).catch($=>{throw t(gt("placeholders",22,"Required fields not covered",$)),$});return t({phase:"placeholders",status:"done",progress:22,message:"Required fields checked"}),{previousLoads:s,working:a,refIndex:d,personContacts:u,groups:c,groupOrder:f,leftToThePlatform:p,untypedFeedItems:g,heldForExclusions:Y,loading:h,mapping:m,reused:y,reusedByKeys:R,ranks:i,recordTypeIssues:L,alignment:S,alignedByObject:w,requiredLookups:v,fixedAtInsert:A,filteredLookups:N,lostObjects:I,targetHasPersonAccounts:P,accountKindOf:G,plans:ae,givenRules:W,withoutRecordType:x,keysLeftEmpty:[...H.leftEmpty,...E.leftEmpty]}}async loadInto(e,t){let r=e.now??(()=>new Date),n=r(),s=b=>e.onProgress?.(b),{orgId:a}=e;this.journal=this.deps.mappingStore.journal?.(n);let d=await this.prepare(e,s,t),{previousLoads:i,working:u,refIndex:l,personContacts:c,groups:f,groupOrder:p,leftToThePlatform:g,untypedFeedItems:h,heldForExclusions:m,mapping:y,reused:R,ranks:L,recordTypeIssues:T,alignment:j,alignedByObject:x,requiredLookups:U,fixedAtInsert:S,lostObjects:w,targetHasPersonAccounts:v,accountKindOf:A,plans:N}=d,I=$l(xl(Kd(d,void 0,{orgId:a,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(I)throw new xr(I);let P=await this.runUserIdOf(a);P&&this.journal?.writtenAs(P);let C={deleted:{},deactivated:{},failures:[]},G=[],D=[],W=new ss,V=new Map,H=[],E=new Set,q,Y=new Map,ae=!1,$=async()=>{let b=await this.readWrittenBetween(a,W,y),_=q?.linked??new Map,z=e.pilot?void 0:e.purgeSweep?.stillToSweep?.();await this.deps.mappingStore.persist(y,{created:W.list(H),startedAt:n,...b?{writtenBetween:b}:{},earlier:{settled:[...E],...z&&z.length>0?{stillToSweep:[...z]}:{}},..._.size>0?{personContacts:Object.fromEntries(_)}:{},...Y.size>0?{withTheirRecord:Object.fromEntries(Y)}:{},...P?{runUserId:P}:{}}),ae=!0},K=()=>W.list().length>0||Object.keys(C.deleted).length>0||Object.keys(C.deactivated).length>0,Z=async()=>{if(!e.signal?.aborted)return;let b=K();throw b&&await $(),new at({perObject:D,placeholders:G,purge:C},b)};t.load={keepMapping:$,mappingKept:()=>ae,wroteSome:K,written:{perObject:D,placeholders:G,purge:C}};let ne=[];if(e.reload){let b="",_={residuals:0},z={tried:0,went:0},se=be=>{let Te=Fe=>Object.values(Fe).reduce((Re,le)=>Re+le,0);return Hn({phase:"reload",progress:24,did:`Purge: ${Te(C.deleted)} deleted, ${Te(C.deactivated)} deactivated, ${C.failures.length} failed`,refused:C.failures.length,notDone:_.residuals,done:"purged",notes:`${Bd(z)}${b}`},be)};if(!e.pilot){s({phase:"reload",status:"started",progress:23,message:"Purging what earlier loads created"});let be=await this.planPurge(a,i,y),Te=await this.foundUnderThePurge(a,be.residuals,y,l);if(Te.length>0){let le=new cr(Te);throw s(se({cause:le})),le}H=be.carried;for(let le of H.flatMap(oe=>oe.referenceIds)){let oe=y.get(le);oe&&E.add(pe(oe))}let Fe=Object.values(be.leftUnrecorded).reduce((le,oe)=>le+oe,0);Fe>0&&(C.leftUnrecorded=be.leftUnrecorded,b=` \u2014 ${Fe} record(s) left in place of a load recorded before loads kept what they created: it may have linked them`);let Re=Object.entries(be.keptByThePlatform);Re.length>0&&(C.keptByThePlatform=be.keptByThePlatform,b+=" \u2014 kept, the platform does not delete them: "+Re.map(([le,oe])=>`${le} (${oe})`).join(", "));try{e.purgeSweep&&(await Z(),await e.purgeSweep.first()),await this.purgeResiduals(e,be,[...p].reverse(),C,Z,E,_,z),e.purgeSweep&&!e.signal?.aborted&&await e.purgeSweep.afterPurge()}catch(le){throw s(se(le instanceof at?void 0:{cause:le})),le}for(let le of i)if(!le.created)for(let oe of le.mapping.values())E.add(pe(oe));s(_.residuals>0||C.failures.length>0?se():{phase:"reload",status:"done",progress:24,message:`Reload pass done${Bd(z)}${b}`})}}let he=b=>(x.get(b)??[]).filter(_=>!R.has(_.referenceId)),_e=N.filter(b=>b.kind==="placeholder").length,De=b=>Hn({phase:"placeholders",progress:25,did:`Placeholders: ${G.length} created`,refused:0,notDone:_e-G.length,done:"created"},b);_e>0&&(await Z(),s({phase:"placeholders",status:"started",progress:24,message:"Creating placeholders"}));try{for(let b of N)b.kind==="placeholder"?(await Z(),await this.createPlaceholder(e,b,he(b.missing.objectApiName),y,G,W)):this.applyScalarDefault(b.missing,Xn(b.missing,he(b.missing.objectApiName),A),ne,L)}catch(b){throw s(De(b instanceof at?void 0:{cause:b})),b}_e>0&&s(De());let k=f.flatMap(b=>b.length>1?fa(b,du(x,U,l,c)):b),F=[],O=[],J=this.config.duplicateErrorPatterns??jd,ee=new Set(k.includes(er)?(x.get(er)??[]).map(b=>b.referenceId):[]),Q=[],me=null,te=0,Be=!1,M=b=>b===Je&&Q.length>0?`, ${Q.length} on a case waiting for ${Q.length===1?"its task":"their tasks"}`:"",we=new Set,tt=async()=>{if(q)return q;let b=await this.linkPersonContacts(a,c,y,R,v,T);for(let _ of b.linked.keys())R.add(_);return we=new Set(b.unlinked.map(_=>_.contactReferenceId).filter(_=>!R.has(_))),q=b,b},rt=b=>{if(b.objectApiName!==Ue||!q)return b;let _=q.unlinked.filter(z=>we.has(z.contactReferenceId));return _.length===0?b:{...b,failed:[...b.failed,..._.map(z=>({objectApiName:Ue,referenceId:z.contactReferenceId,errors:[Yl(z)]}))]}},B=()=>{if(q)for(let[b,_]of q.own)y.has(b)||(q.own.delete(b),q.unlinked.push({accountReferenceId:_.accountReferenceId,contactReferenceId:b,cause:"target-not-loaded",detail:`contact ${b} was not loaded (skipped, failed or excluded)`}))},ie=()=>{let b=q?.linked.size??0,_=q?.own.size??0,z=we.size;return[...b>0?[`${b} linked to the contact the platform wrote with ${b===1?"its":"their"} person account`]:[],..._>0?[`${_} sent as ${_===1?"a contact of its own":"contacts of their own"}: the target holds ${_===1?"its":"their"} account as a business account`]:[],...z>0?[`${z} not written: a person account's contact goes in with its account`]:[]]},kt=(b,_)=>[...b===Ue?ie():[],..._?[_]:[],...g.counts(b).map(({why:z,count:se})=>Rn(se,z)),...h.counts(b).map(({why:z,count:se})=>Hd(se,z)),...m.counts(b).map(({why:z,count:se})=>lc(se,z))].map(z=>`, ${z}`).join(""),fe=(b,_,z,se,be)=>{let Te=D.findIndex(Ot=>Ot.objectApiName===b),Fe=Te>=0?D[Te]:void 0,Re=z.filter(Ot=>R.has(Ot.referenceId)).length,le=Fe?.inserted??0,oe=Fe?.skippedDuplicates??[],Le=Fe?.failed??[],ct=Fe?.writtenWithoutFields,ve=z.length-Re-le-oe.length-Le.length,Nt=rt({objectApiName:b,fromFiles:_,inserted:le,reused:Re,skippedDuplicates:oe,failed:Le,...ct?{writtenWithoutFields:ct}:{},...ve>0?{notInserted:ve}:{}});Fe?D[Te]=Nt:D.push(Nt),s({phase:"insert",objectName:b,status:"error",progress:25+Math.round(55*te/Math.max(k.length,1)),message:`${b}: ${le} inserted, ${Nt.reused} reused, ${oe.length} duplicates skipped, ${Nt.failed.length} failed${M(b)}${as(ve)}${Cn(ct)}${kt(b,se)} \u2014 ${X(be)}`})},pt,nt=(b,_,z)=>{if(b.waiting>0){let Re=D.find(le=>le.objectApiName===Je);Re&&(Re.notInserted=(Re.notInserted??0)+b.waiting)}let se=_==="cancel"&&b.waiting>0,be="";se?be=Jn(b.waiting):b.waiting>0&&(be=as(b.waiting));let Te=b.status;z?Te="error":se&&b.status!=="error"&&(Te="stopped");let Fe=z?` \u2014 ${X(z.cause)}`:"";s({phase:"insert",objectName:Je,status:Te,progress:25+Math.round(55*te/Math.max(k.length,1)),message:`${b.message}${be}${b.notes}${Fe}`})},xe=async()=>{let b=me;b&&e.signal?.aborted&&(me=null,nt(b,"cancel")),await Z()};t.endOpenLine=b=>{let _=pt;pt=void 0,_&&!(b instanceof at)&&_(b);let z=me;me=null,z&&nt(z,b instanceof at?"cancel":"failure")};let ye=async()=>{Be=!0;let b=Q.splice(0,Q.length),_=me;if(me=null,b.length===0)return;let z=25+Math.round(55*te/Math.max(k.length,1)),se;try{await Z()}catch(oe){throw _&&nt(_,oe instanceof at?"cancel":"failure"),oe}let be=oe=>`${oe.inserted} inserted, ${oe.reused} reused, ${oe.skippedDuplicates.length} duplicates skipped, ${oe.failed.length} failed${Jn(oe.notInserted??0)}${Cn(oe.writtenWithoutFields)}`,Te=oe=>{let Le=D.findIndex(ct=>ct.objectApiName===Je);Le>=0?D[Le]=os(D[Le],oe):D.push(oe)},Fe={};try{se=await this.insertObject(e,Je,0,b,l,y,R,F,J,W,V,Ud(D),oe=>{Fe.result=oe})}catch(oe){let Le=Fe.result;if(Le&&Te(Le),_&&Le){let ct=Le.inserted+Le.skippedDuplicates.length+Le.failed.length;nt({..._,waiting:Math.max(_.waiting-ct,0),message:`${_.message}; after their task: ${be(Le)}`},"failure",{cause:oe})}else _&&nt(_,"failure",{cause:oe});throw oe}Te(se);let Re=be(se),le="done";se.failed.length>0||_?.status==="error"?le="error":(se.notInserted??0)>0&&(le="stopped"),s({phase:"insert",objectName:Je,status:le,progress:z,message:_?`${_.message}; after their task: ${Re}${_.notes}`:`${Je} after their task: ${Re}`})};for(let b of k){await xe();let _=x.get(b);if(!_){let ue=w.get(b);if(ue&&b===Ue&&c.size>0){try{await tt()}catch(Ne){throw s({phase:"insert",objectName:b,status:"error",progress:25+Math.round(55*te/Math.max(k.length,1)),message:`${b}: person accounts' contacts not linked \u2014 ${X(Ne)}`}),Ne}B();let je=q?.linked??new Map,Ee=ue.failed.filter(Ne=>!je.has(Ne.referenceId));D.push({...ue,reused:ue.reused+ue.failed.length-Ee.length,failed:Ee})}else ue&&D.push(ue);continue}te++,s({phase:"insert",objectName:b,status:"started",progress:25+Math.round(55*te/Math.max(k.length,1)),message:`Inserting ${b}`});let z,se=u.objects.find(ue=>ue.objectApiName===b)?.records.length??_.length,be=_;if(pt=ue=>fe(b,se,be,z,ue),b===Ue&&c.size>0){let ue=await tt();be=_.filter(je=>!we.has(je.referenceId));for(let je of be){let Ee=ue.own.get(je.referenceId),Ne=je.fields.AccountId;Ee&&(Ne==null||Ne==="")&&(je.fields.AccountId=Ee.accountReferenceId)}}b===Ir&&await this.matchDirectRelations(a,u,_,y,R,Y),b===er&&await this.matchTasksWrittenWithEmails(a,u,_,y,R,Y),So[b]!==void 0&&(z=await this.matchActivityRelations(e,b,_,y,R,S.get(b)??new Set));let Te=0;if(b===Mt){let ue=await this.matchContactRolesWrittenWithOpportunities(e,{working:u,aligned:_,refIndex:l,mapping:y,reused:R,withTheirRecord:Y,pendingFk:F,fixedAtInsert:S.get(b)??new Set});Te=ue.linked,z=ue.note}let Fe=Dt[b],Re=Fe?await this.startAsDrafts(a,b,Fe,be,O):be;if(b===Je&&!Be&&ee.size>0){let ue=je=>ma(je,Ee=>l.get(Ee))&&ee.has(String(je.ActivityId));Q.push(...Re.filter(je=>ue(je.fields))),Re=Re.filter(je=>!ue(je.fields))}let le=Re.filter(ue=>!R.has(ue.referenceId)).length,oe=e.signal?.aborted===!0&&le>0,Le=(ue,je,Ee=Ne=>D.push(Ne))=>this.insertObject(e,b,je,ue,l,y,R,F,J,W,V,Ud(D),Ee),ct=u.standardPricebook,ve;if(oe)ve={objectApiName:b,fromFiles:se,inserted:0,reused:Re.length-le,skippedDuplicates:[],failed:[],notInserted:le};else if(fn(b)&&ct){let ue=await Le(Re.filter(Ee=>Ee.fields[yt]===ct),0),je=Re.filter(Ee=>Ee.fields[yt]!==ct);if(e.signal?.aborted){let Ee=je.filter(Fl=>R.has(Fl.referenceId)).length,Ne={...ue,fromFiles:se,reused:ue.reused+Ee},Xt=Re.length-Ne.inserted-Ne.reused-Ne.skippedDuplicates.length-Ne.failed.length;ve={...Ne,...Xt>0?{notInserted:Xt}:{}}}else{let Ee={},Ne=await Le(je,se,Xt=>{Ee.result=Xt}).catch(Xt=>{throw D.push(Ee.result?os(ue,Ee.result):{...ue,fromFiles:se}),Xt});ve=os(ue,Ne)}}else ve=await Le(Re,se);pt=void 0,b===Ue&&B(),ve=rt(ve),Te>0&&(ve={...ve,writtenByThePlatform:Te});let Nt=b===Je?Q.filter(ue=>!R.has(ue.referenceId)).length:0;(ve.notInserted??0)>0&&(ve.notInserted=(ve.notInserted??0)+Nt);let Ot=ve.notInserted??0;D.push(ve);let Us=kt(b,z),Ks=M(b),Ro=ve.failed.length>0,Vs=Ro?"error":"done";!Ro&&Ot>0&&(Vs="stopped");let Hs=25+Math.round(55*te/Math.max(k.length,1)),ko=`${b}: ${ve.inserted} inserted, ${ve.reused} reused, ${ve.skippedDuplicates.length} duplicates skipped, ${ve.failed.length} failed${Ks}${Jn(Ot)}${Cn(ve.writtenWithoutFields)}`;Ks&&Ot===0?(me={status:Ro?"error":"done",message:ko,notes:Us,waiting:Nt},s({phase:"insert",objectName:b,status:"started",progress:Hs,message:ko})):s({phase:"insert",objectName:b,status:Vs,progress:Hs,message:`${ko}${Us}`}),b===er&&await ye(),Ot>0&&await xe()}await ye(),await Z(),s({phase:"pass2",status:"started",progress:82,message:"Patching cycle FKs"});let Ie={report:{resolved:0,unresolved:[]},unanswered:0},vt=ns(x,b=>y.has(b)),sn=new Set(vt.map(b=>b.opportunity)),bo=F.filter(b=>b.objectApiName!==zr||b.field!==Mr||!sn.has(b.referenceId)),an=vt.length>0?`, ${vt.length} synced quote${vt.length===1?"":"s"} left unset`:"",Vt=b=>Hn({phase:"pass2",progress:88,did:`Pass 2: ${Ie.report.resolved} resolved, ${Ie.report.unresolved.length} unresolved${an}`,refused:Ie.report.unresolved.length,notDone:Ie.unanswered,done:"resolved"},b);try{await this.patchCycleFks(e,bo,y,Ie)}catch(b){throw s(Vt({cause:b})),b}s(Vt());let Ke=Ie.report;await Z();let dt={report:{restored:0,refused:[]},unanswered:0},yr=b=>Hn({phase:"pass2",progress:89,did:`Statuses: ${dt.report.restored} applied, ${dt.report.refused.length} refused`,refused:dt.report.refused.length,notDone:dt.unanswered,done:"applied"},b);try{await this.applyDeferredStatuses(e,O,y,dt)}catch(b){throw s(yr({cause:b})),b}let wr=dt.report;wr.restored+wr.refused.length+dt.unanswered>0&&s(yr()),await Z();let $e=await tt(),Ht={restored:$e.linked.size,sent:[...$e.own.values()],unresolved:$e.unlinked};c.size>0&&s({phase:"personcontact",status:$e.unlinked.length>0?"error":"done",progress:94,message:`Person contacts: ${$e.linked.size} linked to the contact the platform wrote with their account, ${$e.own.size} sent as contacts of their own, ${$e.unlinked.length} not linked`}),await Z(),await e.lease?.giveBack().catch(()=>{}),s({phase:"persist",status:"started",progress:96,message:"Persisting mapping and contract"}),await $();let br=g.counts(),It=h.counts(),Ft=m.counts(),Rr=this.writeContract(e,u,D,G,{now:r,startedAt:n},new Set(w.keys()),[...br.map(({objectApiName:b,count:_})=>({objectApiName:b,count:_,reason:"left-to-the-platform"})),...It.map(({objectApiName:b,count:_})=>({objectApiName:b,count:_,reason:"untyped-feed-item"})),...Ft.map(({objectApiName:b,count:_})=>({objectApiName:b,count:_,reason:"excluded-parent"}))],we.size,V,Ke.unresolved.filter(b=>b.cause==="target-not-loaded"));s({phase:"persist",status:"done",progress:98,message:"Sas artifacts written"});let Yt=D.some(b=>b.failed.length>0)||Ke.unresolved.length>0||Ht.unresolved.length>0||wr.refused.length>0||C.failures.length>0,Jt=new Set(W.list().flatMap(({referenceIds:b})=>b)),kr=await this.readBackRecordTypes(a,Qd(d,b=>Jt.has(b)),y),Lt={status:Yt?"completed-with-errors":"completed",orgId:a,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},startedAt:n.toISOString(),durationMs:r().getTime()-n.getTime(),alignment:j,placeholders:G,requiredDefaults:ne,perObject:D,pass2:Ke,personContact:Ht,statuses:wr,purge:C,...br.length>0?{leftToThePlatform:Gn(br)}:{},...It.length>0?{untypedFeedItems:It.map(({objectApiName:b,why:_,count:z})=>({objectApiName:b,count:z,note:Hd(z,_)}))}:{},...Ft.length>0?{heldForExcludedParents:uc(Ft)}:{},...cc(vt,this.config),...sc(d.keysLeftEmpty),...kr.length>0?{recordTypesGiven:kr}:{},...P?{runUserId:P}:{},mappingPath:this.deps.mappingStore.filePath,contractPath:Rr};return s({phase:"done",status:Lt.status==="completed"?"done":"error",progress:100,message:`Load ${Lt.status}`}),Lt}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 En(this.deps.guard,t);if(e.onGuardDecision?.(n),n==="refused"||n==="declined")throw new He("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){return ls(e,this.config.rootObjectApiName,t)}async reuseByIdentityKeys(e,t,r,n){for(let[s,a]of Object.entries(this.config.identityKeys??{})){let d=t.objects.find(i=>i.objectApiName===s)?.records??[];for(let[i,u]of await this.findByKeys(e.orgId,s,a,d))r.set(i,u),n.add(i)}}async findByKeys(e,t,r,n){let s=new Map,a=n.filter(l=>r.every(c=>!ht(l.fields[c])));if(a.length===0)return s;let d=["Id",...r].map(ge).join(", "),i=new Map,u=100;for(let l=0;l<a.length;l+=u){let c=a.slice(l,l+u).map(p=>`(${r.map(g=>`${ge(g)} = ${Ul(p.fields[g])}`).join(" AND ")})`).join(" OR "),f=`SELECT ${d} FROM ${ge(t)} WHERE ${c}`;for(let p of await this.deps.orgAccess.query(e,f))typeof p.Id=="string"&&i.set(Jd(r.map(g=>p[g])),p.Id)}for(let l of a){let c=i.get(Jd(r.map(f=>l.fields[f])));c&&s.set(l.referenceId,c)}return s}async linkWhatThePlatformKeeps(e,t,r,n,s,a,d){let i={linked:[],said:[],leftEmpty:[]};for(let[u,l]of Object.entries(Fr)){let c=this.config.identityKeys?.[u]??l,f=(r.get(u)??[]).filter(g=>!a.has(g.referenceId));if(f.length===0)continue;let p=await this.linkByKeysAsWritten(e,{objectApiName:u,keyFields:c,records:f,missingRequired:t.find(g=>g.objectApiName===u)?.missingRequired??[],ranks:n,accountKindOf:d},s,a,i);p>0&&i.said.push(`${u}: ${p} found by ${c.join(", ")}, which the platform does not delete`)}return i}async reuseByKeysAsWritten(e,t,r,n,s,a,d,i){let u={linked:[],said:[],leftEmpty:[]};for(let[l,c]of Object.entries(this.config.identityKeys??{})){if(Object.prototype.hasOwnProperty.call(Fr,l))continue;let f=new Set((t.objects.find(h=>h.objectApiName===l)?.records??[]).filter(h=>c.some(m=>ht(h.fields[m]))).map(h=>h.referenceId)),p=(n.get(l)??[]).filter(h=>f.has(h.referenceId)&&!d.has(h.referenceId));if(p.length===0)continue;let g=await this.linkByKeysAsWritten(e,{objectApiName:l,keyFields:c,records:p,missingRequired:r.find(h=>h.objectApiName===l)?.missingRequired??[],ranks:s,accountKindOf:i},a,d,u);g>0&&u.said.push(`${l}: ${g} found by ${c.join(", ")}, as the load writes `+(g===1?"it":"them"))}return u}async linkByKeysAsWritten(e,t,r,n,s){let{objectApiName:a,keyFields:d}=t,i=Ql(t,this.config.requiredFieldDefaults??{}),u=i.flatMap(c=>{let f=d.filter(p=>ht(c.fields[p]));return f.length>0?[f]:[]});if(u.length>0){let c=d.filter(f=>u.some(p=>p.includes(f)));s.leftEmpty.push({objectApiName:a,fields:c,count:u.length}),s.said.push(`${a}: ${u.length} not looked up, ${c.join(", ")} left empty`)}let l=await this.findByKeys(e,a,d,i);for(let[c,f]of l)r.set(c,f),n.add(c),s.linked.push(c);return l.size}async lookUpTheCatalog(e,t,r,n){let s=[],a=t.standardPricebook;if(a){let[u]=await this.deps.orgAccess.query(e,Ct);typeof u?.Id=="string"?(r.set(a,u.Id),n.add(a),s.push("standard price book linked")):s.push("standard price book not found")}let d=await this.matchByNaturalKey(e,t,r,n),i=await this.matchSellingModelOptions(e,t,r,n);Yd(t).includes(ze)&&d.push({objectApiName:ze,linked:i});for(let{objectApiName:u,linked:l,notAsked:c}of d)c===void 0&&s.push(`${u}: ${l} linked`);for(let{objectApiName:u,notAsked:l}of d)l!==void 0&&s.push(`${u} not looked up \u2014 ${l}`);return s}async matchByNaturalKey(e,t,r,n){let s=[];for(let[a,d]of Object.entries(bn)){let i=t.objects.find(f=>f.objectApiName===a)?.records??[];if(i.length===0)continue;let u=i.filter(f=>!r.has(f.referenceId)&&d.every(p=>f.fields[p]!==void 0&&f.fields[p]!=="")),l=[];if(u.length>0)try{l=await Ta(f=>this.deps.orgAccess.query(e,f),a,d,u.map(f=>f.fields))}catch(f){s.push({objectApiName:a,linked:0,notAsked:X(f)});continue}let c=0;u.forEach((f,p)=>{let g=l[p];g!==void 0&&(r.set(f.referenceId,g),n.add(f.referenceId),c++)}),s.push({objectApiName:a,linked:c})}return s}async matchSellingModelOptions(e,t,r,n){let s=[];for(let d of t.objects.find(i=>i.objectApiName===ze)?.records??[]){if(r.has(d.referenceId))continue;let i=d.fields[We],u=d.fields[Ye],l=typeof i=="string"?r.get(i):void 0,c=typeof u=="string"?r.get(u):void 0;l===void 0||c===void 0||s.push({referenceId:d.referenceId,pair:{[We]:l,[Ye]:c}})}if(s.length===0)return 0;let a=await Pa(d=>this.deps.orgAccess.query(e,d),s.map(d=>d.pair));for(let[d,i]of a)r.set(s[d].referenceId,i),n.add(s[d].referenceId);return a.size}async planPurge(e,t,r){let n={residuals:new Map,datedBy:new Map,carried:[],leftUnrecorded:{},keptByThePlatform:{}},s=new Map;for(let[g,h]of r)s.has(pe(h))||s.set(pe(h),g);let a=new Set,d=(g,h)=>{n.residuals.set(g,[...n.residuals.get(g)??[],h])},i=(g,h)=>{let m=n.carried.at(-1);m?.objectApiName===g?m.referenceIds.push(h):n.carried.push({objectApiName:g,referenceIds:[h]})},u=g=>{n.leftUnrecorded[g]=(n.leftUnrecorded[g]??0)+1},l=[],c=t.some(g=>g.created&&!g.writtenBetween)?await this.targetClockAheadMs():Number.NaN,f=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,R]of g.mapping)m.has(y)||h.add(pe(R));return h}),p=new Set(f.flatMap(g=>[...g]));if(t.forEach((g,h)=>{if(!g.created){for(let[R,L]of g.mapping){let T=pe(L);if(s.has(T)||a.has(T))continue;a.add(T);let j=Wl(R);this.mayHaveLinked(j,R)||p.has(T)?u(j):j==="Pricebook2"&&!R.startsWith(Yn)?l.push(L):d(j,L)}return}let m=g.writtenBetween?$t(g.writtenBetween.last):$t(g.endedAt)+c+ni,y=new Map(Object.entries(g.removalStamps??{}).map(([R,L])=>[pe(R),$t(L)]));for(let{objectApiName:R,referenceIds:L}of g.created)for(let T of L){let j=g.mapping.get(T);if(j===void 0)continue;let x=pe(j);if(f[h].has(x)||a.has(x))continue;a.add(x);let U=s.get(x);if(U!==void 0){i(R,U);continue}if(this.keptByThePlatform(R)){n.keptByThePlatform[R]=(n.keptByThePlatform[R]??0)+1;continue}d(R,j);let S=[m,y.get(x)??Number.NaN].filter(Number.isFinite);S.length>0&&n.datedBy.set(x,Math.max(...S))}}),l.length>0){let g;try{let[h]=await this.deps.orgAccess.query(e,Ct);g=typeof h?.Id=="string"?pe(h.Id):""}catch{g=void 0}for(let h of l)g===void 0||pe(h)===g?u("Pricebook2"):d("Pricebook2",h)}return n}async targetClockAheadMs(){let e=this.deps.serverTime;if(!e)return Number.NaN;let t=Date.now();try{return $t(await e())-(t+Date.now())/2}catch{return Number.NaN}}async foundUnderThePurge(e,t,r,n){let s=new Set([...t.values()].flat().map(pe)),a=new Map;for(let[u,l]of r){let c=n.get(u);c===void 0||s.has(pe(l))||a.set(c,[...a.get(c)??[],l])}if(s.size===0||a.size===0)return[];let d=new Map,i=(u,l,c)=>{let f=d.get(u)??{keys:new Set,under:new Set};f.keys.add(pe(l)),f.under.add(c),d.set(u,f)};for(let u of t.keys()){let l;try{l=(await this.deps.orgAccess.describe(e,u)).cascadeChildren??[]}catch{continue}for(let{childSObject:c,field:f}of l){let p=a.get(c);if(!p)continue;let g;try{g=await this.readRecords(e,c,[f],p)}catch{for(let h of p)i(c,h,u);continue}for(let h of g){let m=h[f];typeof h.Id!="string"||typeof m!="string"||s.has(pe(m))&&i(c,h.Id,u)}}}return[...d].map(([u,{keys:l,under:c}])=>({objectApiName:u,count:l.size,under:[...c]}))}mayHaveLinked(e,t){return t.startsWith(Yn)?!1:e==="Unknown"||e===ze||Object.prototype.hasOwnProperty.call(bn,e)||Object.prototype.hasOwnProperty.call(Fr,e)||Object.prototype.hasOwnProperty.call(this.config.identityKeys??{},e)}keptByThePlatform(e){return Object.prototype.hasOwnProperty.call(Fr,e)&&this.config.undeletableObjects?.[e]===void 0}async purgeResiduals(e,t,r,n,s,a,d,i){let u=t.residuals,l=[],c=[...u.values()].reduce((T,j)=>T+j.length,0),f=0,p=()=>{d.residuals=c-f},g=async()=>{let T=l.splice(0);T.length>0&&await this.giveStatusesBack(e,T,n)},h=async()=>{e.signal?.aborted&&await g(),await s()},m=r.filter(T=>u.has(T)),y=[...u.keys()].filter(T=>!r.includes(T)).sort(),R=[...m,...y],L=new Set;try{L=await this.residualsInSight(e.orgId,u),await this.draftResiduals(e,t,l,h);for(let T of R){let j=u.get(T)??[],x=this.config.undeletableObjects?.[T];if(x!==void 0){await h(),await this.checkGuard(e,"update",T,j.length);let U=await this.deps.writer.update(e.orgId,T,j.map(S=>({Id:S,[x]:!1})));U.forEach((S,w)=>{S.success?(n.deactivated[T]=(n.deactivated[T]??0)+1,a.add(pe(j[w]))):n.failures.push({objectApiName:T,recordId:j[w],errors:S.errors})}),f+=U.length}else{let U=fn(T)?await this.customPricesFirst(e.orgId,j):T===Ir?[await this.withoutDirectRelations(e.orgId,j)]:[j];f+=j.length-U.reduce((S,w)=>S+w.length,0);for(let S of U){if(S.length===0)continue;await h(),await this.checkGuard(e,"delete",T,S.length);let w=await this.deps.writer.delete(e.orgId,T,S);w.forEach((v,A)=>{_d(v)?(n.deleted[T]=(n.deleted[T]??0)+1,a.add(pe(S[A]))):n.failures.push({objectApiName:T,recordId:S[A],errors:v.errors})}),f+=w.length}}}await this.purgeAgain(e,R,n,a,h,i)}catch(T){throw await g(),p(),T}e.signal?.aborted||await this.settleTakenAlong(e.orgId,n,a,L),await g(),p()}async residualsInSight(e,t){let r=new Set;for(let[n,s]of t)try{for(let a of await this.readRecords(e,n,[],s))typeof a.Id=="string"&&r.add(pe(a.Id))}catch{}return r}async purgeAgain(e,t,r,n,s,a){for(let d of t){if(this.config.undeletableObjects?.[d]!==void 0)continue;let i=r.failures.filter(l=>l.objectApiName===d).map(l=>l.recordId);if(i.length===0)continue;let u=fn(d)?await this.customPricesFirst(e.orgId,i).catch(()=>[i]):[i];for(let l of u){if(l.length===0)continue;await s(),await this.checkGuard(e,"delete",d,l.length),(await this.deps.writer.delete(e.orgId,d,l)).forEach((f,p)=>{let g=r.failures.findIndex(h=>h.objectApiName===d&&h.recordId===l[p]);g<0||(a.tried++,_d(f)?(r.failures.splice(g,1),r.deleted[d]=(r.deleted[d]??0)+1,n.add(pe(l[p])),a.went++):r.failures[g]={objectApiName:d,recordId:l[p],errors:f.errors})})}}}async settleTakenAlong(e,t,r,n){for(let s of new Set(t.failures.map(a=>a.objectApiName))){let a=t.failures.filter(h=>h.objectApiName===s).map(h=>h.recordId),d=h=>this.readRecords(e,s,[],h),{gone:i,unchecked:u,failure:l}=await ti(a,d,h=>n.has(pe(h))),c=l?`Not checked: not read back once the purge was through, to tell whether a parent deleted after it took it along \u2014 ${l}`:"Not checked: the purge could not read it before its delete, nor after \u2014 gone, or out of the session's sight",f=new Set(u.map(pe));for(let h of t.failures)h.objectApiName!==s||!f.has(pe(h.recordId))||h.errors.includes(c)||(h.errors=[...h.errors,c]);let p=new Set(i.map(pe));if(p.size===0)continue;let g=t.failures.filter(h=>h.objectApiName!==s||!p.has(pe(h.recordId)));t.failures.splice(0,t.failures.length,...g),t.deleted[s]=(t.deleted[s]??0)+p.size;for(let h of p)r.add(h)}}async draftResiduals(e,t,r,n){for(let[s,a]of Object.entries(Dt)){if(Oa.has(s))continue;let d=t.residuals.get(s);if(!d||d.length===0)continue;let i=await this.statusCategories(e.orgId,a),u=i?.draft;if(!i||!u)continue;let l;try{l=await this.readRecords(e.orgId,s,["Status","LastModifiedDate"],d)}catch{continue}let c=l.flatMap(f=>{let p=i.categoryOf.get(String(f.Status));if(typeof f.Id!="string"||p===void 0||p==="Draft")return[];let g=t.datedBy.get(pe(f.Id))??Number.NaN;return[{objectApiName:s,id:f.Id,draft:u,status:String(f.Status),unchanged:$t(f.LastModifiedDate)<=g}]});c.length!==0&&(await n(),await this.checkGuard(e,"update",s,c.length),r.push(...c),await this.deps.writer.update(e.orgId,s,c.map(({id:f})=>({Id:f,Status:u}))))}}async giveStatusesBack(e,t,r){let n=this.deps.restoringWriter??this.deps.writer,s=await this.runningUser(e.orgId),a={};for(let d of new Set(t.map(i=>i.objectApiName))){let i=t.filter(p=>p.objectApiName===d),u=new Map(i.map(p=>[pe(p.id),p])),l;try{l=await this.readRecords(e.orgId,d,["Status"],i.map(p=>p.id))}catch(p){for(let g of i)qd(r,g,`its status was not read back: ${X(p)}`);continue}let c=l.flatMap(p=>{let g=typeof p.Id=="string"?u.get(pe(p.Id)):void 0;return g&&p.Status===g.draft?[g]:[]});for(let p=0;p<c.length;p+=jt){let g=c.slice(p,p+jt),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=X(m);h=g.map(()=>({success:!1,errors:[y]}))}g.forEach((m,y)=>{let R=h[y];R?.success||qd(r,m,R?.errors.join("; ")||"the org gave no reason")})}let f=c.filter(p=>p.unchanged);if(!(f.length===0||s===void 0))try{let p=await this.readRecords(e.orgId,d,["LastModifiedDate","LastModifiedById"],f.map(g=>g.id));for(let g of p)typeof g.Id=="string"&&typeof g.LastModifiedDate=="string"&&typeof g.LastModifiedById=="string"&&pe(g.LastModifiedById)===s&&(a[g.Id]=g.LastModifiedDate)}catch{}}if(Object.keys(a).length!==0)try{await this.deps.mappingStore.recordStamps(a)}catch{}}async runningUser(e){let t=await this.runUserIdOf(e);return t?pe(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:s,rule:a,keys:d}of t){let i=d.flatMap(u=>r.get(u)??[]);try{let u=await this.deps.orgAccess.query(e,dd(s.objectApiName,i));n.push({...s,readBack:cd(u,a.types)})}catch(u){let l=X(u);n.push({...s,readBack:{read:0,types:[],unread:l}})}}return n}async readRecords(e,t,r,n){let s=["Id",...r].map(ge).join(", "),a=[];for(let d=0;d<n.length;d+=jt){let i=n.slice(d,d+jt).map(u=>`'${Me(u)}'`).join(", ");a.push(...await this.deps.orgAccess.query(e,`SELECT ${s} FROM ${ge(t)} WHERE Id IN (${i})`))}return a}async resolveRecordType(e,t,r,n,s,a,d){let i={...n.fields};r===Ve&&delete i[kn];let u=i.RecordTypeId;if(typeof u!="string"||u==="")return"RecordTypeId"in i&&d.set(n.referenceId,"masterInSource"),delete i.RecordTypeId,{referenceId:n.referenceId,fields:i};let l=t.recordTypes[r]??[],c=n.recordTypeDeveloperName===void 0?void 0:jo(n.recordTypeDeveloperName,l,ec),f=c&&"found"in c?[c.found]:l.filter(m=>m.name===u),p=f[0];if(!p)return delete i.RecordTypeId,d.set(n.referenceId,"dropped"),a.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:u,detail:"RecordType name absent from the dataset recordTypes map \u2014 RecordTypeId dropped"}),{referenceId:n.referenceId,fields:i};if(f.length>1)throw tc(r,u,f);let g=lt(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 Qe(`The dataset names ${r} record type ${p.developerName} without its namespace \u2014 it was extracted before SandForge read one \u2014 and ${Eo(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=>lt(m.namespacePrefix,m.developerName))});if(h!==null&&typeof h=="object"){let m=await this.deps.recordTypeResolver.givenRecordType?.(e.orgId,r).catch(()=>{});return delete i.RecordTypeId,d.set(n.referenceId,"dropped"),a.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:u,detail:`RecordType ${g} is in the target org but not available to the running user \u2014 RecordTypeId dropped, ${Bl(m)}. Assign it to the user's profile or a permission set to keep it.`}),{referenceId:n.referenceId,fields:i}}return h?(i.RecordTypeId=h,s.set(n.referenceId,h),{referenceId:n.referenceId,fields:i}):(delete i.RecordTypeId,d.set(n.referenceId,"dropped"),a.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:u,detail:`RecordType ${g} not found in target org \u2014 RecordTypeId dropped`}),{referenceId:n.referenceId,fields:i})}async planRequiredFields(e,t){let r=[],n=[];for(let s of t)for(let a of s.missingRequired){let d=`${a.objectApiName}.${a.field}`;if(!a.isLookup){if(this.config.requiredFieldDefaults?.[d]===void 0){let c=a.accountKind?` of a ${a.accountKind} account`:"";n.push(`requiredFieldDefaults["${d}"]: ${tu(a)} for this required field${c}`)}else r.push({kind:"default",missing:a});continue}let i=this.config.requiredLookupPlaceholders?.[d];if(!i){n.push(`requiredLookupPlaceholders["${d}"]: a placeholder (name + recordTypeDeveloperName) for this required lookup to ${a.referenceTo.join(" or ")||"its parent"}`);continue}let u=i.targetObjectApiName??a.referenceTo[0];if(!u){n.push(`requiredLookupPlaceholders["${d}"].targetObjectApiName: the target describe names no object this lookup points at`);continue}let l;if(i.recordTypeDeveloperName){let c=await this.deps.recordTypeResolver.resolveByDeveloperName(e.orgId,u,i.recordTypeDeveloperName);if(c!==null&&typeof c=="object"&&"ambiguous"in c){let f=c.carriers.find(p=>p.namespacePrefix);n.push(`requiredLookupPlaceholders["${d}"]: `+Eo(u,i.recordTypeDeveloperName,"the target org",c.carriers)+(f?" \u2014 a package's is named with its namespace: "+lt(f.namespacePrefix,f.developerName):""));continue}if(c!==null&&typeof c=="object"){n.push(`requiredLookupPlaceholders["${d}"]: record type ${i.recordTypeDeveloperName} on ${u} is not available to the running user`);continue}if(l=c??void 0,!l){n.push(`requiredLookupPlaceholders["${d}"]: record type ${i.recordTypeDeveloperName} is not on ${u} in the target org \u2014 deploy it before loading`);continue}}r.push({kind:"placeholder",missing:a,key:d,name:i.name,targetObject:u,recordTypeId:l})}if(n.length>0)throw new Qe(`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:
12
+ - ${n.join(`
13
+ - `)}`,n);return r}async createPlaceholder(e,t,r,n,s,a){let{missing:d,key:i,targetObject:u}=t,l={Name:t.name};t.recordTypeId&&(l.RecordTypeId=t.recordTypeId),await this.checkGuard(e,"insert",u,1);let[c]=await this.deps.writer.insert(e.orgId,u,[l]);if(c===void 0&&e.signal?.aborted)return;if(!c?.success||!c.id)throw new Qe(`Placeholder insert failed for required lookup ${i} on ${u}: ${c?.errors.join("; ")||"no id returned"}. Fix the target org configuration and retry.`);let f=`${Yn}${u}:${i}`;n.set(f,c.id),a.add(u,f),this.journal?.created(u,[[f,c.id]]);let p=0;for(let g of r){let h=g.fields[d.field];(h==null||h==="")&&(g.fields[d.field]=c.id,p++)}s.push({objectApiName:d.objectApiName,field:d.field,placeholderObjectApiName:u,placeholderName:t.name,placeholderId:c.id,affectedRecords:p})}applyScalarDefault(e,t,r,n){let s=`${e.objectApiName}.${e.field}`,a=this.config.requiredFieldDefaults?.[s],d=is(a,e.distinct),i=0;for(let u of t)ht(u.fields[e.field])&&(u.fields[e.field]=ds(a,d,{referenceId:u.referenceId,rank:n.get(u.referenceId)??0}),i++);r.push({objectApiName:e.objectApiName,field:e.field,value:a,affectedRecords:i,...d?{perRecord:d}:{}})}async insertObject(e,t,r,n,s,a,d,i,u,l,c,f,p){let g={objectApiName:t,fromFiles:r,inserted:0,reused:0,skippedDuplicates:[],failed:[]},h=n.filter(S=>!d.has(S.referenceId));g.reused=n.length-h.length;let m=[];for(let S of h){let w=Xl(t,S.fields,s,f);w?g.failed.push({objectApiName:t,referenceId:S.referenceId,errors:[w]}):m.push(S)}if(m.length===0)return g;let y=m.map(S=>{let w={},v=[];for(let[N,I]of Object.entries(S.fields))if(!(I===""||I===null||I===void 0))if(typeof I=="string"&&s.has(I)){let P=a.get(I);P&&!(t===zr&&N===Mr)?w[N]=P:v.push({objectApiName:t,referenceId:S.referenceId,field:N,targetReferenceId:I})}else w[N]=I;let A=ga(t,w);for(let N of A)delete w[N];i.push(...v.filter(N=>!A.includes(N.field)));for(let N of ra(t,w))delete w[N];return w}),R=(S,w,v)=>{a.set(S,w),l.add(t,S,Kl.some(A=>A in v)),g.inserted++};await this.checkGuard(e,"insert",t,y.length);let L=await this.deps.writer.insert(e.orgId,t,y,(S,w)=>this.journalBatch(t,m,S,w)),T=[];L.forEach((S,w)=>{let v=m[w].referenceId;if(S.success&&S.id){R(v,S.id,y[w]);return}if(Xd(S.errors,u)){g.skippedDuplicates.push({objectApiName:t,referenceId:v,errors:S.errors});return}let A=this.sentAgain(t,y[w],S);A?T.push({...A,referenceId:v,errors:S.errors}):g.failed.push({objectApiName:t,referenceId:v,errors:S.errors})});let j=m.length-L.length;if(j>0&&e.signal?.aborted&&(g.notInserted=j),T.length===0)return g;let x=(S,w)=>{for(let v of S)g.failed.push({objectApiName:t,referenceId:v.referenceId,errors:[...v.errors,`Not written again ${Gd(v.fields)}: ${w}`]})};if(e.signal?.aborted)return x(T,"the load was cancelled first"),g;let U;try{await this.checkGuard(e,"insert",t,T.length),U=await this.deps.writer.insert(e.orgId,t,T.map(S=>S.payload),(S,w)=>this.journalBatch(t,T,S,w))}catch(S){throw x(T,X(S)),p?.(g),S}return T.forEach((S,w)=>{let v=U[w];if(!v){x([S],e.signal?.aborted?"the load was cancelled first":"no answer came for it");return}if(v.success&&v.id){R(S.referenceId,v.id,S.payload),g.writtenWithoutFields=Mo(g.writtenWithoutFields,{rows:1,fields:S.fields.map(N=>({...N,rows:1}))});for(let{field:N,replacedWith:I}of S.fields){if(I!==void 0)continue;let P=c.get(t)??new Map;P.set(N,[...P.get(N)??[],S.referenceId]),c.set(t,P)}return}let A=[...v.errors,`Sent again ${Gd(S.fields)} after the first refusal: ${S.errors.join("; ")}`];Xd(v.errors,u)?g.skippedDuplicates.push({objectApiName:t,referenceId:S.referenceId,errors:A}):g.failed.push({objectApiName:t,referenceId:S.referenceId,errors:A})}),g}journalBatch(e,t,r,n){let s=this.journal;s&&s.created(e,n.flatMap((a,d)=>{let i=t[r+d];return a.success&&a.id&&i?[[i.referenceId,a.id]]:[]}))}sentAgain(e,t,r){let n=Fi(r.errorDetails,t,void 0);if(!n)return;let s={...t},a=n.map(d=>{let i=d.refusedBy==="restricted-picklist"?this.picklistRuleFor(e,d.field):void 0;return i?.action==="replace"&&i.value!==""&&i.value!==t[d.field]?(s[d.field]=i.value,{...d,replacedWith:i.value}):(delete s[d.field],{...d})});return{payload:s,fields:a}}async matchDirectRelations(e,t,r,n,s,a){let d=new Map;for(let l of t.objects.find(c=>c.objectApiName==="Contact")?.records??[])d.set(l.referenceId,l.fields.AccountId);let i=r.filter(l=>{let c=l.fields.ContactId;return typeof c=="string"&&l.fields.AccountId!==void 0&&d.get(c)===l.fields.AccountId&&n.has(c)&&typeof l.fields.AccountId=="string"&&n.has(l.fields.AccountId)});if(i.length===0)return;let u=await Sa(l=>this.deps.orgAccess.query(e,l),i.map(l=>({AccountId:n.get(l.fields.AccountId),ContactId:n.get(l.fields.ContactId)})));for(let[l,c]of i.entries()){let f=u.get(l);typeof f=="string"&&(n.set(c.referenceId,f),s.add(c.referenceId),a.set(c.referenceId,c.fields.ContactId))}}async matchTasksWrittenWithEmails(e,t,r,n,s,a){let d=new Set(r.map(l=>l.referenceId)),i=new Map;for(let l of t.objects.find(c=>c.objectApiName===Je)?.records??[]){let c=l.fields.ActivityId;if(typeof c!="string"||!d.has(c)||s.has(l.referenceId))continue;let f=n.get(l.referenceId);f&&i.set(c,{id:f,key:l.referenceId})}if(i.size===0)return;let u=await ya(l=>this.deps.orgAccess.query(e,l),[...new Set([...i.values()].map(l=>l.id))]);for(let[l,c]of i){let f=u.get(c.id);f!==void 0&&(n.set(l,f),s.add(l),a.set(l,c.key))}}async matchContactRolesWrittenWithOpportunities(e,t){let{aligned:r,refIndex:n,mapping:s,reused:a}=t,d=w=>typeof w=="string"?s.get(w):void 0,i=new Map;for(let w of t.working.objects.find(v=>v.objectApiName===rc)?.records??[]){let v=s.get(w.referenceId),A=d(w.fields[wt]);v&&A&&!a.has(w.referenceId)&&i.set(v,A)}if(i.size===0)return{linked:0};let u=r.map(w=>({OpportunityId:d(w.fields.OpportunityId),[wt]:d(w.fields[wt]),IsPrimary:w.fields.IsPrimary})),l=Oo(u,w=>i.get(w)).filter(w=>!a.has(r[w].referenceId));if(l.length===0)return{linked:0};let c=w=>{let v={},A=[];for(let[N,I]of Object.entries(w.fields))if(!(N==="OpportunityId"||N===wt)&&!t.fixedAtInsert.has(N)&&!(I===""||I===null||I===void 0))if(typeof I=="string"&&n.has(I)){let P=s.get(I);P?v[N]=P:A.push({objectApiName:Mt,referenceId:w.referenceId,field:N,targetReferenceId:I})}else v[N]=I;return{fields:v,owed:A}},f=new Map(l.map(w=>[w,{opportunity:String(u[w].OpportunityId),contact:String(u[w][wt])}])),p=[...new Set(l.flatMap(w=>Object.keys(c(r[w]).fields)))],g=await ba(w=>this.deps.orgAccess.query(e.orgId,w),[...new Set([...f.values()].map(({opportunity:w})=>w))],p),{found:h,alike:m}=Ra(f,g),y=m.length>0?ka(m.length):void 0;if(h.size===0)return y?{linked:0,note:y}:{linked:0};let R=w=>y?`${w}; ${y}`:w,L=[];for(let[w,v]of h){let A=r[w],N=String(v.Id);s.set(A.referenceId,N),a.add(A.referenceId),t.withTheirRecord.set(A.referenceId,String(A.fields.OpportunityId));let{fields:I,owed:P}=c(A);t.pendingFk.push(...P);let C=Object.entries(I).filter(([G,D])=>String(v[G]??"")!==String(D));C.length>0&&L.push({Id:N,...Object.fromEntries(C)})}let T=h.size,j=`${T} written by the platform with ${wa(Mt)}`;if(L.length===0)return{linked:T,note:R(j)};let x=(w,v)=>`${j}, ${w} of them left as it wrote ${w===1?"it":"them"}, without the fields of the source's role: ${v}`;if(e.signal?.aborted)return{linked:T,note:R(x(L.length,"the load was cancelled before the update"))};await this.checkGuard(e,"update",Mt,L.length);let U=await this.deps.writer.update(e.orgId,Mt,L),S=L.flatMap((w,v)=>{let A=U[v];return A?.success?[]:[A?A.errors.join("; ")||"refused":"no answer came for it"]});return S.length===0?{linked:T,note:R(j)}:{linked:T,note:R(x(S.length,S[0]))}}async matchActivityRelations(e,t,r,n,s,a){let{orgId:d}=e,i=So[t],u=c=>typeof c=="string"?n.get(c):void 0,l=await va(c=>this.deps.orgAccess.query(d,c),t,r.map(c=>({[i]:u(c.fields[i]),RelationId:u(c.fields.RelationId)})));for(let[c,f]of l)n.set(r[c].referenceId,f),s.add(r[c].referenceId);return Ia(t,[...l].map(([c,f])=>[r[c].fields,f]),c=>!a.has(c),async c=>(await this.checkGuard(e,"update",t,c.length),this.deps.writer.update(d,t,c)),()=>e.signal?.aborted===!0)}async startAsDrafts(e,t,r,n,s){let a=await this.statusCategories(e,r);return a?.draft?n.map(d=>{let i=or(d.fields.Status,a);return i?(s.push({objectApiName:t,referenceId:d.referenceId,status:String(d.fields.Status)}),{referenceId:d.referenceId,fields:{...d.fields,Status:i}}):d}):n}async withoutDirectRelations(e,t){let r=new Set;for(let n=0;n<t.length;n+=jt){let s=t.slice(n,n+jt).map(d=>`'${Me(d)}'`).join(", "),a=await this.deps.orgAccess.query(e,`SELECT Id FROM ${Ir} WHERE Id IN (${s}) AND IsDirect = true`);for(let d of a)r.add(String(d.Id))}return t.filter(n=>!r.has(n))}async customPricesFirst(e,t){let r=await Aa(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,s=Number.NEGATIVE_INFINITY;for(let{objectApiName:a,referenceIds:d}of t.list()){let i=[...new Set(d.flatMap(l=>{let c=r.get(l);return c?[c]:[]}))],u=t.sentAuditDates(a);for(let l=0;l<i.length;l+=jt){let c=await this.writtenDatesOf(e,a,i.slice(l,l+jt));if(!c)return;for(let f of c){let p=$t(f.SystemModstamp),g=y=>{let R=u?Number.NaN:$t(f[y]);return Number.isFinite(R)?R:p},h=g("CreatedDate"),m=g("LastModifiedDate");Number.isFinite(h)&&(n=Math.min(n,h)),Number.isFinite(m)&&(s=Math.max(s,m))}}}if(!(!Number.isFinite(n)||!Number.isFinite(s)))return{first:new Date(n).toISOString(),last:new Date(Math.max(n,s)).toISOString()}}async writtenDatesOf(e,t,r){let n=r.map(s=>`'${Me(s)}'`).join(", ");for(let s of Vl)try{return await this.deps.orgAccess.query(e,`SELECT Id, ${s.join(", ")} FROM ${ge(t)} WHERE Id IN (${n})`)}catch{}}async statusCategories(e,t){return nr(r=>this.deps.orgAccess.query(e,r),t)}async applyDeferredStatuses(e,t,r,n){let{refused:s}=n.report,a=new Map;for(let d of t){let i=r.get(d.referenceId);i&&a.set(d.objectApiName,[...a.get(d.objectApiName)??[],{...d,id:i}])}n.unanswered=[...a.values()].reduce((d,i)=>d+i.length,0);for(let[d,i]of a){if(e.signal?.aborted)continue;let u=i.map(c=>({Id:c.id,Status:c.status}));await this.checkGuard(e,"update",d,u.length);let l=await this.deps.writer.update(e.orgId,d,u);l.forEach((c,f)=>{c.success?n.report.restored++:s.push({objectApiName:d,referenceId:i[f].referenceId,status:i[f].status,detail:c.errors.join("; ")})}),n.unanswered-=l.length}}async patchCycleFks(e,t,r,n){let{unresolved:s}=n.report,a=new Map,d=new Map;for(let u of t){let l=r.get(u.referenceId),c=r.get(u.targetReferenceId);if(!l||!c){s.push({objectApiName:u.objectApiName,referenceId:u.referenceId,field:u.field,cause:l?"target-not-loaded":"record-not-loaded",detail:l?`referenced record ${u.targetReferenceId} was not loaded (skipped, failed or excluded)`:"child record was not loaded (see perObject failures/skips)"});continue}d.set(l,u.referenceId);let f=a.get(u.objectApiName)??new Map,p=f.get(l)??{Id:l};p[u.field]=c,f.set(l,p),a.set(u.objectApiName,f)}let i=u=>u.reduce((l,c)=>l+Object.keys(c).length-1,0);n.unanswered=[...a.values()].reduce((u,l)=>u+i([...l.values()]),0);for(let[u,l]of a){let c=[...l.values()];if(e.signal?.aborted)continue;await this.checkGuard(e,"update",u,c.length);let f=await this.deps.writer.update(e.orgId,u,c);f.forEach((p,g)=>{p.success?n.report.resolved+=Object.keys(c[g]).length-1:s.push({objectApiName:u,referenceId:d.get(String(c[g].Id))??String(c[g].Id),field:Object.keys(c[g]).filter(h=>h!=="Id").join(","),cause:"update-refused",detail:p.errors.join("; ")})}),n.unanswered-=i(c.slice(0,f.length))}}async linkPersonContacts(e,t,r,n,s,a){let d={linked:new Map,own:new Map,unlinked:[]},i=new Map,u=[...t].map(([f,p])=>({accountReferenceId:p,contactReferenceId:f}));for(let f of u){let p=f.accountReferenceId===""?void 0:r.get(f.accountReferenceId);p!==void 0&&i.set(p,[...i.get(p)??[],f])}let l=i.size===0||s===!1?new Map:await In(f=>this.deps.orgAccess.query(e,f),[...i.keys()]),c=new Map;for(let[f,p]of i){let g=l.get(f);if(g!==void 0)for(let h of p)c.set(h.contactReferenceId,g)}for(let f of u){let p=c.get(f.contactReferenceId);if(p!==void 0){r.set(f.contactReferenceId,p),d.linked.set(f.contactReferenceId,f.accountReferenceId);continue}if(f.accountReferenceId===""||!r.has(f.accountReferenceId)){d.unlinked.push({...f,cause:"record-not-loaded",detail:f.accountReferenceId===""?Dr.accountNotInDataset:Dr.accountNotLoaded});continue}if(n.has(f.contactReferenceId))continue;let g=a.find(m=>m.objectApiName===Ve&&m.referenceId===f.accountReferenceId),h=Dr.noPersonAccounts;s!==!1&&(h=g?`${Dr.businessAccount}: ${g.detail}`:`${Dr.businessAccount}: its record type there is no person account's`),d.own.set(f.contactReferenceId,{...f,detail:h})}return d}writeContract(e,t,r,n,s,a,d,i=0,u=new Map,l=[]){let c=new Map;for(let{objectApiName:h,referenceId:m,field:y}of l){let R=c.get(h)??{};R[y]=[...R[y]??[],m],c.set(h,R)}let f=new Map;for(let{objectApiName:h,count:m,reason:y}of d){let R=f.get(h)??{};R[y]=(R[y]??0)+m,f.set(h,R)}let p=[...r];for(let[h,m]of f)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,R)=>y+R,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===Ue?i:0,R=h.failed.filter(S=>Zl(S.errors)).length;if(R>0&&(m["parent-refused"]=R),h.failed.length-R>y){let S=a.has(h.objectApiName)?"object-not-loaded":"dml-failed";m[S]=h.failed.length-R-y}y>0&&(m["person-contact-not-sent"]=y);let L=0;for(let[S,w]of Object.entries(f.get(h.objectApiName)??{}))m[S]=w,L+=w;let T=h.skippedDuplicates.length+h.failed.length+L,j=n.filter(S=>S.placeholderObjectApiName===h.objectApiName).length,x=u.get(h.objectApiName),U=c.get(h.objectApiName);g[h.objectApiName]={fromFiles:h.fromFiles,exclusionReasons:m,excluded:T,added:j,expected:h.inserted+h.reused+j,...x&&x.size>0?{writtenWithout:Object.fromEntries(x)}:{},...U?{parentNotLoaded:U}:{}}}return Pd(this.sasGuard,e.sasDir,{version:1,orgId:e.contractOrgId??e.orgId,datasetVersion:t.datasetVersion,writtenAt:s.now().toISOString(),loadStartedAt:s.startedAt.toISOString(),objects:g})}picklistRuleFor(e,t){return this.config.picklistRules?.[`${e}.${t}`]??this.config.defaultPicklistRule??{action:"clear"}}contractPath(e,t){return $n(this.sasGuard,e,t)}};function Ud(o){let e=new Map;for(let t of o)for(let r of t.failed)e.set(r.referenceId,t.objectApiName);return e}function Xl(o,e,t,r){if(r.size===0)return;let n=new Set(o===Je&&!Io(e,s=>t.get(s))?["ActivityId"]:[]);for(let[s,a]of Object.entries(e)){if(typeof a!="string"||n.has(s)||!t.has(a))continue;let d=r.get(a);if(d!==void 0)return`PARENT_REFUSED: the ${d} record its ${s} names was refused in this load, and written without it this record would stand without its ${d}.`}}function Zl(o){return o.length===1&&o[0].startsWith("PARENT_REFUSED:")}function ht(o){return o==null||o===""}var oc=/\{(n|referenceId)\}/g;function is(o,e){if(typeof o=="string")return o.match(oc)?"token":e}function ds(o,e,t){return typeof o!="string"||e===void 0?o:e==="token"?o.replace(oc,(r,n)=>n==="n"?String(t.rank):t.referenceId):`${o} ${t.rank}`}function Ql(o,e){let{objectApiName:t,keyFields:r,ranks:n,accountKindOf:s}=o,a=o.missingRequired.filter(d=>!d.isLookup&&r.includes(d.field));return o.records.map(d=>{let i={...d.fields};for(let u of a){let l=e[`${t}.${u.field}`];l===void 0||!ht(i[u.field])||Xn(u,[d],s).length!==0&&(i[u.field]=ds(l,is(l,u.distinct),{referenceId:d.referenceId,rank:n.get(d.referenceId)??0}))}return{referenceId:d.referenceId,fields:i}})}function sc(o,e=!1){return o.length===0?{}:{keysLeftEmpty:o.map(({objectApiName:t,fields:r,count:n})=>{let s=n===1?"its":"their",a=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 ${s} identity keys: ${a} 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 ${s} identity keys: ${a} stayed empty in what the load wrote \u2014 ${d} \u2014 so ${n===1?"it was":"they were"} sent to be inserted, never matched`}})}}function eu(o){let e=new Map;for(let t of o.objects)t.records.forEach((r,n)=>e.set(r.referenceId,n+1));return e}function ac(o){let e=cs(o),t=new Map(o.objects.map(n=>[n.objectApiName,n.records])),r=new Set;return new Set([...ic(t,r),...dc(t,r,nc(o,e),n=>e.get(n))])}function ic(o,e){let t=(o.get(Mt)??[]).filter(i=>!e.has(i.referenceId));if(t.length===0)return new Set;let r=new Map,n=i=>{if(typeof i!="string"||i==="")return;let u=r.get(i);return u===void 0&&(u=String(r.size+1).padStart(15,"0"),r.set(i,u)),u},s=new Set((o.get(Ue)??[]).map(i=>i.referenceId)),a=new Map;for(let i of o.get(rc)??[]){if(e.has(i.referenceId))continue;let u=i.fields[wt];typeof u!="string"||!s.has(u)||a.set(n(i.referenceId),n(u))}if(a.size===0)return new Set;let d=t.map(i=>({OpportunityId:n(i.fields.OpportunityId),[wt]:n(i.fields[wt]),IsPrimary:i.fields.IsPrimary}));return new Set(Oo(d,i=>a.get(i)).map(i=>t[i].referenceId))}function dc(o,e,t,r){let n=l=>(o.get(l)??[]).filter(c=>!e.has(c.referenceId)),s=new Set,a=new Map;for(let l of n(Ue))t.has(l.referenceId)||a.set(l.referenceId,l.fields.AccountId);let d=new Set((o.get("Account")??[]).map(l=>l.referenceId));for(let l of n(Ir)){let{AccountId:c,ContactId:f}=l.fields;typeof c!="string"||typeof f!="string"||a.get(f)===c&&d.has(c)&&s.add(l.referenceId)}let i=new Set([...o.values()].flatMap(l=>l.map(c=>c.referenceId))),u=new Set(n(er).map(l=>l.referenceId));for(let l of n(Je)){let c=l.fields.ActivityId,f=l.fields.RelatedToId;typeof c!="string"||!u.has(c)||typeof f!="string"||!i.has(f)||Io(l.fields,r)||s.add(c)}return s}function Kd(o,e,t){let{working:r,loading:n,alignedByObject:s,reused:a,reusedByKeys:d,alignment:i,ranks:u}=o,l=o.targetHasPersonAccounts===!1?new Set:o.personContacts,c=w=>(s.get(w)??[]).filter(v=>!a.has(v.referenceId)),f=[...new Set([...o.groupOrder,...r.objects.map(w=>w.objectApiName),...e?[...e.residuals.keys()].sort():[]])],p=0,g=ic(s,a),h=dc(s,a,l,w=>o.refIndex.get(w)),m=[];for(let w of f){let v=r.objects.find(E=>E.objectApiName===w)?.records.length??0,A=e?.residuals.get(w)?.length??0;if(v===0&&A===0)continue;let N=s.get(w),P=(N??n.objects.find(E=>E.objectApiName===w)?.records??[]).filter(E=>a.has(E.referenceId)),C=P.filter(E=>d.has(E.referenceId)).length,G=N?c(w):[],D=G.filter(E=>l.has(E.referenceId)).length;p+=D;let W=G.filter(E=>g.has(E.referenceId)||h.has(E.referenceId)).length,V=(o.filteredLookups.get(w)??[]).flatMap(({field:E,referenceTo:q})=>{let Y=G.filter(ae=>!ht(ae.fields[E])).length;return Y>0?[{field:E,referenceTo:q,records:Y}]:[]}),H=t.undeletableObjects[w]!==void 0;m.push({objectApiName:w,fromFiles:v,toInsert:G.length-D-W,reusedByKeys:C,reusedFromCatalog:P.length-C,...W>0?{writtenByThePlatform:W}:{},fieldsDropped:i.removals.filter(E=>E.objectApiName===w).length,picklistsRewritten:i.adjustments.filter(E=>E.objectApiName===w).length,notSent:v-(N?N.length:P.length),toPurge:H?0:A,toDeactivate:H?A:0,...V.length>0?{lookupFilters:V}:{}})}let y=(w,v)=>c(w).filter(A=>ht(A.fields[v])),R=(w,v)=>y(w,v).length,L=w=>{let v=Xn(w,y(w.objectApiName,w.field),o.accountKindOf),A=t.requiredFieldDefaults[`${w.objectApiName}.${w.field}`],N=is(A,w.distinct),I=v[0];return{objectApiName:w.objectApiName,field:w.field,affectedRecords:v.length,...N?{perRecord:N}:{},...N&&I?{example:String(ds(A,N,{referenceId:I.referenceId,rank:u.get(I.referenceId)??0}))}:{}}},T=e?.leftUnrecorded??{},j=e?.keptByThePlatform??{},x=o.heldForExclusions.counts(),U=Qd(o,w=>!a.has(w)&&!l.has(w)).map(({given:w})=>w),S=new Set([...s.values()].flatMap(w=>w.map(v=>v.referenceId)));return{orgId:t.orgId,mode:t.mode,plannedAt:t.plannedAt,perObject:m,excludedObjects:i.excludedObjects,removals:i.removals,placeholders:o.plans.flatMap(w=>w.kind==="placeholder"?[{objectApiName:w.missing.objectApiName,field:w.missing.field,placeholderObjectApiName:w.targetObject,placeholderName:w.name,affectedRecords:R(w.missing.objectApiName,w.missing.field)}]:[]),requiredDefaults:o.plans.flatMap(w=>w.kind==="default"?[L(w.missing)]:[]),recordTypeIssues:o.recordTypeIssues.length,personContacts:p,earlierLoads:o.previousLoads.length,...Object.keys(T).length>0?{leftUnrecorded:T}:{},...Object.keys(j).length>0?{keptByThePlatform:j}:{},...x.length>0?{heldForExcludedParents:uc(x)}:{},...cc(ns(s,w=>S.has(w)),t,!0),...sc(o.keysLeftEmpty,!0),...U.length>0?{recordTypesGiven:U}:{}}}var Vd=5;function tu(o){switch(o.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=o.activeValues??[];return e.length===0?"one of its values":`one of its active values (${e.slice(0,Vd).join(", ")}${e.length>Vd?", \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 cc(o,e,t=!1){let r=$d(o,(e.excludedObjects??[]).includes(rs),t);return r?{quotesLeftUnsynced:[r]}:{}}function ru(o,e,t){for(let r=!0;r;){r=!1;for(let[n,s]of o){let a=[...e.get(n)??[]],d=s.filter(i=>!t.some(u=>u.leaveOut(n,i.referenceId,i.fields,a)));d.length!==s.length&&(o.set(n,d),r=!0)}}}function nu(o,e,t){let r=new Set(t.excludedObjects??[]);if(r.size===0)return[];let n=[];for(let s of e.fields){let a=s.referenceTo??[];a.length===0||!a.every(d=>r.has(d))||!s.createable||s.defaultedOnCreate||Zt(o,s.name,s.nillable)&&(t.requiredLookupPlaceholders?.[`${o}.${s.name}`]||n.push({field:s.name,excludedObject:a[0]}))}return n}function ou(o){return(e,t)=>{for(let{field:r,excludedObject:n}of o.get(e)??[])if(ht(t[r]))return{field:r,value:"",noun:n}}}function lc(o,e){return e.through?`${o} left out: ${e.through} names a record left out for the ${e.rows.noun} excludedObjects leaves out`:`${o} 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 uc(o){return o.map(({objectApiName:e,why:t,count:r})=>({objectApiName:e,count:r,note:lc(r,t)}))}var su={field:"Type",value:"",noun:"feed item whose type the dataset does not carry"};function au(o,e){if(o!=="FeedItem")return;let t=e.Type;return typeof t=="string"&&t!==""?void 0:su}function Hd(o,e){let t="extract the dataset again, with rules that keep FeedItem.Type";return e.through?`${o} left out: ${e.through} names a feed item whose type the dataset does not carry \u2014 ${t}`:`${o} feed item${o===1?"":"s"} left out: the dataset does not carry ${o===1?"its":"their"} type, and a tracked change cannot be told from a post \u2014 ${t}`}function cs(o){let e=new Map;for(let t of o.objects)for(let r of t.records)e.set(r.referenceId,t.objectApiName);return e}function iu(o,e,t=new Map){let r=new Map;for(let n of o.objects){let s=r.get(n.objectApiName)??new Set;for(let a of n.records)for(let[d,i]of Object.entries(a.fields))if(!(n.objectApiName===Ve&&d===kn)&&typeof i=="string"){let u=e.get(i);u&&u!==n.objectApiName&&s.add(u)}r.set(n.objectApiName,s)}t.size>0&&r.has(Ve)&&r.get(Ue)?.add(Ve);for(let{sourceObject:n,targetObject:s}of Ei(new Set(r.keys()),[]))r.get(s)?.add(n);for(let{sourceObject:n,targetObject:s}of ha(new Set(r.keys())))r.get(n)?.delete(s),r.get(s)?.add(n);return r}function du(o,e,t,r=new Map){let n=new Map;for(let[s,a]of o){let d=e.get(s),i=new Set;if(d)for(let u of a)for(let l of d){let c=u.fields[l],f=typeof c=="string"?t.get(c):void 0;f&&f!==s&&i.add(f)}n.set(s,i)}return r.size>0&&n.set(Ue,new Set([...n.get(Ue)??[],Ve])),n}function cu(o,e){let t=h=>o.objects.find(m=>m.objectApiName===h)?.records??[],r=(h,m)=>m.map(y=>String(h[y]??"")).join("|"),n=[We,Ye,Qt],s=[We,Ye],a=(h,m)=>typeof h[m]=="string"&&h[m]!=="",d=t(qe),i=d.filter(h=>e.has(h.referenceId)&&a(h.fields,We)),u=o.standardPricebook,l=h=>u!==void 0&&h.fields[yt]===u,c=new Set(i.filter(h=>!l(h)).map(h=>r(h.fields,n))),f=d.filter(h=>l(h)&&c.has(r(h.fields,n))),p=new Set([...i,...f].filter(h=>a(h.fields,Ye)).map(h=>r(h.fields,s))),g=t(ze).filter(h=>p.has(r(h.fields,s)));return[...f,...g].map(h=>h.referenceId)}function Yd(o){return[...Object.keys(bn),ze].filter(e=>o.objects.some(t=>t.objectApiName===e&&t.records.length>0))}function lu(o,e){for(let t of o.objects){let r=t.records.find(n=>n.referenceId===e);if(r)return r}}function Jd(o){return JSON.stringify(o.map(e=>e===void 0?null:e))}function Xd(o,e){return o.some(t=>e.some(r=>t.toLowerCase().includes(r.toLowerCase())))}function ls(o,e,t){if(!e)throw new Qe("Pilot mode requires config.rootObjectApiName (the business-folder root object).");let r=o.objects.find(l=>l.objectApiName===e)?.records??[],n=t??r[0]?.referenceId;if(!n||!r.some(l=>l.referenceId===n))throw new Qe(`Pilot root ${t??"<first>"} not found in ${e} records (${r.length} in dataset). Provide pilot.rootReferenceId of an existing root record.`);let s=cs(o),a=new Set([n]),d=!0;for(;d;){d=!1;for(let l of o.objects)for(let c of l.records)a.has(c.referenceId)||Object.values(c.fields).some(f=>typeof f=="string"&&a.has(f))&&(a.add(c.referenceId),d=!0)}let i=l=>{for(;l.length>0;){let c=l.pop(),f=lu(o,c);if(f)for(let p of Object.values(f.fields))typeof p=="string"&&s.has(p)&&!a.has(p)&&(a.add(p),l.push(p))}};i([...a]);let u=cu(o,a).filter(l=>!a.has(l));for(let l of u)a.add(l);return i(u),{...o,objects:o.objects.map(l=>({...l,records:l.records.filter(c=>a.has(c.referenceId))})).filter(l=>l.records.length>0)}}import{randomBytes as uu}from"node:crypto";import{readFile as fu}from"node:fs/promises";var us="frozen.salt";function pu(){return uu(32).toString("base64url")}function fc(o){let e=o[sd];return e?{salt:e,source:"environment"}:void 0}function Zp(o,e=process.env){let t=async()=>{let r=fc(e);if(r)return r;let n=await o.getSecret(us);return n?{salt:n,source:"secretStorage"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(r)return r;let n=pu();if(await o.storeSecret(us,n),await o.getSecret(us)!==n)throw new Er;return{salt:n,source:"secretStorage",created:!0}}}}function pc(o=process.env,e){let t=async()=>{let r=fc(o);if(r)return r;if(e===void 0)return;let n=(await fu(e,"utf8")).trim();return n?{salt:n,source:"file"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(!r)throw new Er;return r}}}import{createHash as gu}from"node:crypto";import{appendFileSync as hu,mkdirSync as mu,readFileSync as yu}from"node:fs";import*as _r from"node:path";var wu=15*6e4;function Zn(o){return`sha256:${gu("sha256").update(_r.resolve(o)).digest("hex").slice(0,16)}`}function gc(o,e){if(!o?.writtenBetween)return;let t=Date.parse(o.endedAt),r=Date.parse(e);if(!Number.isFinite(t)||!Number.isFinite(r)||t<r)return;let n=Date.parse(o.writtenBetween.first),s=Date.parse(o.writtenBetween.last);if(!(!Number.isFinite(n)||!Number.isFinite(s)))return new Date(Math.max(n,s)).toISOString()}function bu(o,e){return e.some(t=>{let r=Date.parse(t.endedAt),n=Date.parse(t.startedAt??t.endedAt);return Number.isFinite(r)&&o>=(Number.isFinite(n)?n:r)-6e4&&o<=r+wu})}function hc(o,e){let t=[];for(let r of o){let n=Date.parse(r.endedAt);if(!Number.isFinite(n)||(r.sas!==void 0?r.sas===e.sasMark:bu(n,e.own)))continue;let s=Date.parse(r.lastWriteAt??""),a=Number.isFinite(s)?s:n,d=Date.parse(r.startedAt??r.endedAt);t.push({ids:[],idsUntold:!0,from:Number.isFinite(d)?Math.min(d,a):a,to:a})}return t}var mc="frozen-loads.ndjson";function rg(o,e){mu(o,{recursive:!0}),hu(_r.join(o,mc),`${JSON.stringify(e)}
14
+ `)}function Ru(o,e){return o.slice(0,15)===e.slice(0,15)}function ng(o,e){let t;try{t=yu(_r.join(o,mc),"utf8")}catch{return[]}let r=[];for(let n of t.split(`
15
+ `)){if(n.trim()==="")continue;let s;try{s=JSON.parse(n)}catch{continue}let{organizationId:a,sas:d,startedAt:i,endedAt:u,lastWriteAt:l}=s??{};typeof a!="string"||typeof u!="string"||Ru(a,e)&&r.push({endedAt:u,...typeof d=="string"?{sas:d}:{},...typeof i=="string"?{startedAt:i}:{},...typeof l=="string"?{lastWriteAt:l}:{}})}return r}function yc(o){return o.filter(e=>(e.action==="frozen_load"||e.action==="checkpoint_replay")&&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 ku="FROZEN_EMAILS_EXCEEDED";function cg(o,e){return[...Yi(o.counted,e),...o.uncounted!==void 0?[` emails: not counted, ${o.uncounted} could not be read`]:[],...o.deliverability?[` ${Zi(o.deliverability.reading)}`]:[]]}function vu(o){return typeof o.unread=="string"}async function wc(o){let{read:e,plan:t,writes:r,target:n}=o,s=await wi({read:e,...t?{plan:t}:{},writes:r,readDeliverability:o.readDeliverability,accepted:o.accepted,target:n,run:"load",keepsAddresses:!0,mayMute:o.mayMute}),a=[],d;if(vu(e))d=`the target's automation: ${e.unread}`;else{let c=zt(e,t,r).automation,f={objects:o.inserts.map(g=>({...g,storageBytes:0}))};d=Vi(c,Ki(f));let p=sa(c);if(p.length>0){let g=await o.readLimits().catch(h=>({unread:X(h)}));a=Ui(f,p,g)}}let i=Hi(a,n),u=i?{code:ku,message:`${i} Nothing was written.`}:s.gate.stop,{deliverability:l}=s.gate;return{run:s,info:{counted:a.map(c=>({...c,objects:[...c.objects]})),...d!==void 0?{uncounted:d}:{},verdict:s.gate.verdict,...l?{deliverability:l}:{},accepted:o.accepted,...u?{refused:{code:u.code,message:u.message}}:{}},...u?{stop:u}:{}}}var Iu="AUTOMATION_NOT_ACCEPTED";function Ou(o){let e=new Set(o);return(t,r)=>e.has(t)&&(r==="insert"||r==="update")}function Su(o){return typeof o.unread=="string"}function Au({kind:o,name:e}){return o==="flow"?`flow "${e}"`:o==="process"?`process "${e}"`:o==="workflowRule"?`workflow rule "${e}"`:`Apex trigger ${e}`}var bc={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"what runs"};function Rc(o){return`${o.objectApiName}: ${Au(o)} (${o.writes.join(", ")})`}function Pu(o,e,t){let r=[];o.firing.length>0&&r.push(`${e} runs automation as this load inserts its records and updates them: ${o.firing.map(Rc).join("; ")}.`);for(let{part:n,reason:s}of o.unread??[]){let a=bc[n];r.push(`${a[0].toUpperCase()}${a.slice(1)} of ${e} could not be read (${s}), 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 fs(o){let{read:e,target:t}=o,r=Ou(o.written),n=[],s=[],a=[];if(Su(e))s=[{part:"automation",reason:e.unread}];else{let u=zt(e,o.plan,r),l=new Map;for(let p of u.firing){if(p.write!=="insert"&&p.write!=="update")continue;let g=`${p.objectApiName}\0${p.kind}\0${p.name}`,h=l.get(g);h?h.writes.includes(p.write)||h.writes.push(p.write):l.set(g,{objectApiName:p.objectApiName,kind:p.kind,name:p.name,writes:[p.write]})}n=[...l.values()].map(p=>({...p,writes:["insert","update"].filter(g=>p.writes.includes(g))})),s=td(e);let c=ed(u.automation,Qi(u.automation,[...o.written])),f=[...new Set(c.flatMap(p=>p.permissionSet??[]))];a=[...rd(c,t,"the load"),...o.mayMute&&f.length>0?[`With --mute-automation, the load assigns ${f.join(", ")} to the user it writes as for the load alone, under a lease, and what ${f.length===1?"it keeps":"they keep"} quiet does not fire.`]:[]]}if(n.length===0&&s.length===0)return{};let d={firing:n,...s.length>0?{unread:s}:{},accepted:o.accepted};if(o.accepted)return{info:d};let i={code:Iu,message:Pu(d,t,a)};return{info:{...d,refused:i},stop:i}}function pg(o,e){return[`target automation: what ${e} runs as the load inserts its records and updates them`,...o.firing.map(t=>` ${Rc(t)}`),...(o.unread??[]).map(({part:t,reason:r})=>` ${bc[t]} could not be read: ${r}`),...o.accepted?[" accepted (--accept-automation): the load writes all the same"]:[]]}var qr="No record was read or deleted.",Tu="Nothing was deleted.";function Br(o,e){return{allowed:!1,refusal:{code:"PRODUCTION",message:`${o} is a production org, or cannot be told from one: ${e}. Emptying is for sandboxes, scratch orgs and Developer Edition orgs: SandForge never empties objects of a production org, and nothing lifts this. ${qr}`}}}async function bg(o,e){let{orgName:t,registered:r}=e;if(r===void 0)return Br(t,"SandForge has no record of what kind of org it is");if(!na(r))return Br(t,"SandForge has it registered as a production org");let n;try{n=await ia(o)}catch(a){let d=ca(a);return d!==void 0?{allowed:!1,refusal:{code:"ORG_UNTYPED",message:`${la(t,a,d)} SandForge empties no org it cannot tell from a production one. ${qr}`}}:Br(t,`it did not say what org it is (${X(a)})`)}if(da(n))return Br(t,n.edition?`its Organization record says IsSandbox false, edition ${n.edition}`:"its Organization record says IsSandbox false, and no edition");let s=hn(r);return s==="production"?Br(t,"SandForge has it registered as a production org"):s==="staging"&&e.mode==="org"?{allowed:!1,refusal:{code:"STAGING_ORG",message:`${t} is a sandbox marked Staging: it holds real data, and SandForge never empties the whole of it. Pick the objects to empty instead, which Production Guard asks about, or unmark it on the Organizations page if it holds nobody's work. ${qr}`}}:{allowed:!0,org:n,tier:s}}var kc=["PermissionsViewAllData","PermissionsModifyAllData","PermissionsBulkApiHardDelete"];async function Rg(o){let e=async n=>(await o.query(`SELECT ${n.join(", ")} FROM UserPermissionAccess`)).records[0]??{},t,r;try{t=await e(kc)}catch(n){try{t=await e(kc.slice(0,2)),r=`whether the user has Bulk API Hard Delete could not be read: ${X(n)}`}catch(s){return{viewAllData:!1,modifyAllData:!1,hardDelete:!1,unread:X(s)}}}return{viewAllData:t.PermissionsViewAllData===!0,modifyAllData:t.PermissionsModifyAllData===!0,hardDelete:t.PermissionsBulkApiHardDelete===!0,...r!==void 0?{unread:r}:{}}}function kg(o){return{code:"HARD_DELETE_NOT_PERMITTED",message:"Deleting for good needs Bulk API Hard Delete, and the user SandForge deletes as "+(o.unread!==void 0?`could not be read to have it (${o.unread}). `:"doesn't have it: Salesforce refuses the job as it is opened. ")+"Give the user a permission set with Bulk API Hard Delete, or empty to the recycle bin, which Undo brings back. Nothing was deleted."}}var vg=60*6e4,vc=2e3,Ic=/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/;async function Ig(o,e,t,r){let n=t.filter(l=>Ic.test(l)).map(l=>l.slice(0,15)),s=n.length>0?` AND LastModifiedById NOT IN (${n.map(l=>`'${l}'`).join(", ")})`:"",a=new Map,d=[],i=!1;for(let l of e){let c=ge(l);try{let f=await o.query(`SELECT LastModifiedById, LastModifiedDate FROM ${c} WHERE LastModifiedDate >= ${r}${s} LIMIT ${vc}`);f.records.length>=vc&&(i=!0);for(let p of f.records){let{LastModifiedById:g,LastModifiedDate:h}=p;if(typeof g!="string"||!Ic.test(g))continue;let m=g.slice(0,15),y=typeof h=="string"&&!Number.isNaN(Date.parse(h))?h:"",R=a.get(m);if(!R){a.set(m,{userId:g,records:1,lastChangedAt:y});continue}R.records+=1,y!==""&&(R.lastChangedAt===""||Date.parse(y)>Date.parse(R.lastChangedAt))&&(R.lastChangedAt=y)}}catch(f){d.push(`${l}: ${X(f)}`)}}let u=[...a.keys()].sort();return{people:u.map(l=>a.get(l).userId),...i?{atLeast:!0}:{},who:u.map(l=>a.get(l)),unread:d}}var ju=200;async function Og(o,e){let t=e.who.map(s=>s.userId).slice(0,ju);if(t.length===0)return e;let r;try{r=(await o.query(`SELECT Id, Name FROM User WHERE Id IN (${t.map(s=>`'${s}'`).join(", ")})`)).records}catch{return e}let n=new Map;for(let s of r){let{Id:a,Name:d}=s;typeof a=="string"&&typeof d=="string"&&d.trim()!==""&&n.set(a.slice(0,15),d.trim())}return{...e,who:e.who.map(s=>{let a=n.get(s.userId.slice(0,15));return a!==void 0?{...s,name:a}:s})}}function Eu(o){let e;for(let t of o)t.lastChangedAt!==""&&(e===void 0||Date.parse(t.lastChangedAt)>Date.parse(e))&&(e=t.lastChangedAt);return e}function Sg(o,e,t={}){if(t.accepted===!0)return;let r=new Set((t.accepted??[]).map(l=>l.slice(0,15))),n=e.people.filter(l=>!r.has(l.slice(0,15)));if(n.length===0)return;let s=n.length,a=`${e.atLeast?"At least ":""}${s} ${s===1?"person":"people"}`,d=Eu(e.who.filter(l=>n.includes(l.userId))),i=r.size>0?" the preview did not name":"",u=t.voice==="page"?"or tick the box that lets their work go, to empty all the same":"or add --accept-people-active to empty all the same";return{code:"PEOPLE_ACTIVE",message:`${a}${i} other than the user SandForge deletes as changed records of these objects in ${o} in the last hour${d!==void 0?`, the last at ${d}`:""}: emptying them would take their work. Empty once they have stopped, ${u}. `+Tu}}var Gr=1024,Oc="COPY_SANDBOX",Fu=Ge({DataStorageMB:Ge({Max:dn()}).loose()}).loose();async function jg(o){if(o.orgType!=="Sandbox")return;let e="Empty it whole from DataOps Cleanup in the panel, which knows whether it is marked Staging, or pick the objects to empty with --objects, which Production Guard asks about. "+qr,t;try{t=Fu.parse(await o.limits()).DataStorageMB.Max}catch(r){return{code:Oc,message:`${o.target} is a sandbox whose data storage could not be read (${X(r)}): this command cannot tell a Partial Copy or Full sandbox, which may hold real data, from a developer's. ${e}`}}if(!(t<=Gr))return{code:Oc,message:`${o.target} is a Partial Copy or Full sandbox, by its data storage (${t.toLocaleString("en-US")} MB, past the ${Gr.toLocaleString("en-US")} MB of a Developer Pro): it may hold real data, and this command cannot see whether it is marked Staging in the extension, where such a sandbox is never emptied whole. ${e}`}}import{existsSync as qf}from"node:fs";import*as Se from"node:fs/promises";import*as Pl from"node:os";import*as Pe from"node:path";var lr=class extends Error{constructor(t,r=[]){super(r.length>0?`${t}:
16
+ - ${r.join(`
17
+ - `)}`:t);this.violations=r;this.name="RulesFileError"}violations},Lu=/^\d+\.\d+\.\d+$/,Ac=/^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/,Nu=new Set(Bo);function ps(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Qn(o){let e=[];if(!ps(o))throw new lr("Rules file must be a JSON object");let t=o.rulesVersion;(typeof t!="string"||!Lu.test(t))&&e.push('rulesVersion is required and must be semver (e.g. "1.0.0")');let r=o.rules;if(!ps(r))throw e.push('rules is required and must be an object keyed by "Object.Field"'),new lr("Invalid rules file",e);let n={};for(let[s,a]of Object.entries(r)){if(!Ac.test(s)){e.push(`"${s}": key must match "ObjectApiName.FieldApiName"`);continue}if(!ps(a)){e.push(`"${s}": rule must be an object with a "generator" property`);continue}let d=a.generator;if(typeof d!="string"||!Nu.has(d)){e.push(`"${s}": unknown generator ${JSON.stringify(d)} (supported: ${Bo.join(", ")})`);continue}let i=a.approved===!0;if(d==="keep"&&!i){e.push(`"${s}": generator "keep" requires "approved": true (explicit human review)`);continue}let u={generator:d};a.approved!==void 0&&(u.approved=i),typeof a.comment=="string"&&(u.comment=a.comment),n[s]=u}if(e.length>0)throw new lr("Invalid rules file",e);return{rulesVersion:t,rules:n}}function Pc(o){let e=Object.keys(o.rules).sort(),t={};for(let r of e)t[r]=o.rules[r];return`${JSON.stringify({rulesVersion:o.rulesVersion,rules:t},null,2)}
18
+ `}var Tc={rulesVersion:"1.0.0",rules:{}};function jc(o){if(o===null)return{found:!1};try{let e=Qn(JSON.parse(o));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 Cu=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],zu=new Set(["FeedItem.Type","Pricebook2.IsActive","PricebookEntry.IsActive","Product2.IsActive",...Cu.flatMap(o=>[`BusinessHours.${o}StartTime`,`BusinessHours.${o}EndTime`]),"BusinessHours.TimeZoneSidKey","OperatingHours.TimeZone","TimeSlot.DayOfWeek","TimeSlot.StartTime","TimeSlot.EndTime","TimeSlot.Type"]),Mu=new Set(["TimeZoneSidKey","LocaleSidKey","LanguageLocaleKey","CurrencyIsoCode","EmailEncodingKey"]);function ft(o,e,t){let r=`${e}.${t}`,n=o.rules[r]?.generator;return n||(o.personalBySchema?.has(r)===!0?"clear":zu.has(r)||Mu.has(t)||o.keptBySchema?.has(r)===!0?"keep":"clear")}function Ec(o,e,t){let r=new Set(o.keptBySchema??[]),n=new Set(o.personalBySchema??[]);for(let[s,a]of e){let d=new Set(t.detectPII(s,a.map(i=>({apiName:i.name,label:i.label??i.name,type:i.type}))).piiFields.map(i=>i.fieldApiName));for(let i of a){let u=`${s}.${i.name}`;d.has(i.name)?n.add(u):i.type==="picklist"&&(i.restrictedPicklist===!0||i.nillable===!1)&&i.compoundFieldName===void 0&&r.add(u)}}return{...o,keptBySchema:r,personalBySchema:n}}function Fc(o,e){let t=new Set;for(let r of o.objects)for(let n of r.records)for(let s of Object.keys(n.fields)){let a=`${r.objectApiName}.${s}`;e.rules[a]===void 0&&ft(e,r.objectApiName,s)==="keep"&&t.add(a)}return[...t].sort()}function Lc(o,e,t){let r=[];for(let n of o.objects){let s=t.get(n.objectApiName)??[];for(let l of s){let c=yn(n.objectApiName,l.name);if(l.name==="Id"||l.createable===!1||l.nillable!==!1&&c===void 0||l.defaultedOnCreate===!0||l.type==="reference"||(l.referenceTo?.length??0)>0||ft(e,n.objectApiName,l.name)!=="clear")continue;n.records.some(p=>{if(c!==void 0&&!rr(c,vn(p.fields,!1)))return!1;let g=p.fields[l.name];return g!=null&&g!==""})&&r.push(`${n.objectApiName}.${l.name}`)}let a=n.objectApiName,d=gn(a,l=>s.some(c=>c.name===l&&c.createable!==!1),l=>ft(e,a,l)!=="clear"),i=`${a}.${d}`;d!==void 0&&n.records.some(l=>{let c=l.fields[d];return c!=null&&c!==""})&&!r.includes(i)&&r.push(i)}return r.sort()}var Du="Cleared on review of the extraction result: kept in clear text without a rule before.";function Nc(o,e){let t=Qn(o),r=e.filter(u=>!Ac.test(u));if(r.length>0)throw new lr('Fields to clear must be named "ObjectApiName.FieldApiName"',r.map(u=>JSON.stringify(u)));let n=o,s={...n.rules},a=[],d=[];for(let u of[...new Set(e)].sort()){if(t.rules[u]!==void 0){d.push(u);continue}s[u]={generator:"clear",comment:Du},a.push(u)}let i=a.length>0?xu(t.rulesVersion):t.rulesVersion;return{payload:{...n,rulesVersion:i,rules:s},rulesVersion:i,cleared:a,alreadyRuled:d}}function xu(o){let[e,t]=o.split(".").map(Number);return`${e}.${t+1}.0`}import*as Cc from"node:fs/promises";import*as zc from"node:path";var gs=/\{\{([A-Z][A-Z0-9_]*)\}\}/g,Mc=/^[A-Z][A-Z0-9_]*$/,Et=class extends Error{constructor(e){super(e),this.name="QueryTemplateError"}};function Wr(o,e){for(let a of Object.keys(e))if(!Mc.test(a))throw new Et(`Invalid token name ${JSON.stringify(a)}`);let t=new Set;for(let a of o.matchAll(gs))t.add(a[1]);let r=[...t].filter(a=>!(a in e));if(r.length>0)throw new Et(`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=o.replace(gs,(a,d)=>e[d]),s=n.match(gs);if(s)throw new Et(`Unresolved placeholder(s) after render: ${s.join(", ")}`);return n}async function Dc(o,e,t){let n=(t??new de).assertOutsideRepo(zc.join(o,e)),s=JSON.parse(await Cc.readFile(n,"utf8"));if(typeof s!="object"||s===null||Array.isArray(s))throw new Et(`Token file ${n} must contain a JSON object`);let a={};for(let[d,i]of Object.entries(s)){if(!Mc.test(d))throw new Et(`Invalid token name ${JSON.stringify(d)} in ${n}`);if(typeof i!="string")throw new Et(`Token ${d} in ${n} must be a string`);a[d]=i}return a}var Ur=class extends Error{constructor(){super("Selection stopped"),this.name="SelectionStopped"}};function $u(o,e){return e?e.aborted?(o.catch(()=>{}),Promise.reject(new Ur)):new Promise((t,r)=>{let n=()=>r(new Ur);e.addEventListener("abort",n,{once:!0}),o.then(s=>{e.removeEventListener("abort",n),t(s)},s=>{e.removeEventListener("abort",n),r(s)})}):o}var _u=2500,Bu=3,qu=5;function Gu(o,e){return Object.entries(o).filter(([t,r])=>t!==e&&r>0).sort(([t,r],[n,s])=>s-r||t.localeCompare(n)).slice(0,qu).map(([t,r])=>({objectApiName:t,count:r}))}var Bt=class extends Error{constructor(t,r,n,s){let a=Gu(t,s),d=a.map(u=>`${u.objectApiName} ${u.count}`),i=a.length>0?`The heaviest: ${d.join(", ")}. Leave out those the dataset does not need with excludedObjects (${JSON.stringify(a.map(u=>u.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}. ${i}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},hs=class extends Error{constructor(e){super(e),this.name="CoverageSelectionError"}},eo=class{deps;constructor(e){this.deps=e}async select(e,t={}){let r=e.budgetMaxRecords??_u,n=e.candidatesPerCombination??Bu,s=ge(e.rootObject),{signal:a}=t,d=p=>t.onProgress?.(p),i=[],u=[],l=[],c={during:"axes",pending:[]},f=()=>{let p={};for(let h of l)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 Bt(p,g,r,s);return{roots:i,uncovered:u,volumetry:{measured:p,total:g,budgetMax:r,summed:!0},selectedAt:(this.deps.now?.()??new Date).toISOString(),stopped:{reason:a?.reason==="timeout"?"timeout":"cancelled",during:c.during,...c.combinationKey!==void 0?{combinationKey:c.combinationKey}:{},...c.candidate!==void 0?{candidate:c.candidate,candidates:n}:{},notProbed:c.pending}}};try{return await this.run(e,{rootObject:s,budgetMax:r,candidateLimit:n,signal:a,tell:d},{roots:i,uncovered:u,ownMeasures:l,at:c})}catch(p){if(p instanceof Ur)return f();throw p}}async run(e,t,r){let{rootObject:n,budgetMax:s,candidateLimit:a,signal:d,tell:i}=t,{roots:u,uncovered:l,ownMeasures:c,at:f}=r,p=j=>$u(j,d),g=new Map,h=new Map;for(let j of e.axes)i({phase:"axis",axis:j.name}),g.set(j.name,await p(this.enumerateAxisValues(j,e.tokens))),h.set(j.name,await p(this.deps.fieldType?.(n,j.filterField).catch(()=>{})??Promise.resolve(void 0)));let m=e.axes.length===0?[[]]:Ku(e.axes.map(j=>({axis:j.name,values:g.get(j.name)??[]}))),y=j=>j.length===0?"all":j.map(x=>`${x.axis}=${x.value??"NULL"}`).join("|");f.pending=[...m.map(y),...e.edgeCases.map(j=>`edge:${j.name}`)];let R=async(j,x)=>(f.during="combination",f.combinationKey=j,f.candidate=void 0,f.pending=f.pending.filter(U=>U!==j),this.pickHealthyRoot(n,x,a,e.tokens,{step:p,onCandidate:U=>{f.candidate=U,i({phase:"candidate",combinationKey:j,candidate:U,candidates:a})}}));for(let[j,x]of m.entries()){let U=y(x);i({phase:"combination",combinationKey:U,index:j+1,of:m.length});let S=x.map(A=>{let N=ge(e.axes.find(I=>I.name===A.axis)?.filterField??"");return A.value===null?`${N} = NULL`:`${N} = ${Uu(A.value,h.get(A.axis))}`}).join(" AND "),w=await R(U,S),v={};for(let A of x)v[A.axis]=A.value;w.id?(u.push({rootRecordId:w.id,combinationKey:U,axisValues:v}),w.measured&&c.push(w.measured)):l.push({combinationKey:U,reason:xc(w,a)})}for(let[j,x]of e.edgeCases.entries()){let U=`edge:${x.name}`;i({phase:"combination",combinationKey:U,index:j+1,of:e.edgeCases.length});let S=await R(U,`(${x.whereFragment})`);S.id?(u.push({rootRecordId:S.id,combinationKey:U,axisValues:{},edgeCase:x.name}),S.measured&&c.push(S.measured)):l.push({combinationKey:`edge:${x.name}`,reason:S.probed===0?"no record matches the edge-case marker":xc(S,a)})}f.during="measure",f.combinationKey=void 0,f.candidate=void 0,u.length>0&&i({phase:"measure",roots:u.length});let L=u.length===0?{}:await p(this.deps.measureVolumetry(u.map(j=>j.rootRecordId))),T=Object.values(L).reduce((j,x)=>j+x,0);if(T>s)throw new Bt(L,T,s,n);return{roots:u,uncovered:l,volumetry:{measured:L,total:T,budgetMax:s},selectedAt:(this.deps.now?.()??new Date).toISOString()}}async enumerateAxisValues(e,t){let r=Wr(e.valuesSoql,t??{}),n=await this.deps.query(r),s=[];for(let a of n){if(!("axisValue"in a))throw new hs(`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=a.axisValue;d==null?s.push(null):typeof d=="string"?s.push(d):s.push(String(d))}return[...new Set(s)].sort((a,d)=>(a??"").localeCompare(d??""))}async pickHealthyRoot(e,t,r,n,s){let a=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 s.step(this.deps.query(Wr(a,n??{}))),i=0,u;for(let l of d){let c=l.Id;if(typeof c!="string"||c==="")continue;i++,s.onCandidate(i);let f=await s.step(this.deps.checkHealth.check(c));if(f.healthy)return{id:c,probed:i,...f.measured?{measured:f.measured}:{}};u=f.reason}return{id:null,probed:i,lastReason:u}}};function xc(o,e){if(o.probed===0)return"no candidate record";let t=`no healthy candidate among the ${o.probed} probed (limit ${e})`;return o.lastReason?`${t} \u2014 last: ${o.lastReason}`:t}var Wu=new Set(["int","long","double","currency","percent"]);function Uu(o,e){let t=`'${Me(o)}'`;switch(e){case"boolean":return/^(true|false)$/i.test(o)?o.toLowerCase():t;case"date":return/^\d{4}-\d{2}-\d{2}$/.test(o)?o: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(o)?o:t;default:return e!==void 0&&Wu.has(e)&&/^-?\d+(\.\d+)?$/.test(o)?o:t}}function Ku(o){let e=[[]];for(let{axis:t,values:r}of o){let n=[];for(let s of e)for(let a of r)n.push([...s,{axis:t,value:a}]);e=n}return e}var to=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 ur from"node:fs/promises";import*as ms from"node:path";var Kr="selection.json";async function $c(o,e,t){let r=t??new de,n=r.assertOutsideRepo(o);await ur.mkdir(n,{recursive:!0});let s=r.assertOutsideRepo(ms.join(n,Kr));return await ur.writeFile(s,`${JSON.stringify({fileVersion:1,selection:e},null,2)}
19
+ `,"utf8"),s}async function ys(o,e){let r=(e??new de).assertOutsideRepo(ms.join(o,Kr)),n=JSON.parse(await ur.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 fr from"node:fs/promises";import*as ws from"node:path";var _c="discovery.json",Vu=1440*6e4,Hu=Ge({name:Ce(),fields:mt(Ge({name:Ce(),type:Ce(),referenceTo:mt(Ce())}).loose()),childRelationships:mt(Ge({childSObject:Ce(),field:Ce(),relationshipName:Ce()}).loose())}).loose(),Yu=Ge({fileVersion:Xs(1),sourceOrgId:Ce().min(1),rootObject:Ce().min(1),maxNodes:dn().int().positive(),step:Js(["select","extract"]),discoveredAt:vo.datetime(),schemaStamp:vo.datetime().optional(),graph:Ge({nodes:mt(Ge({objectApiName:Ce(),included:cn()}).loose()),edges:mt(Ge({sourceObject:Ce(),targetObject:Ce()}).loose())}).loose(),describes:Ys(Ce(),Hu),objects:mt(Ge({name:Ce(),keyPrefix:Ce().nullable()}))});async function Bc(o,e,t=new de){let r=t.assertOutsideRepo(o);await fr.mkdir(r,{recursive:!0});let n=t.assertOutsideRepo(ws.join(r,_c));return await fr.writeFile(n,`${JSON.stringify(e)}
20
+ `,"utf8"),n}async function qc(o,e=new de){let t=e.assertOutsideRepo(ws.join(o,_c)),r;try{r=await fr.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 s=Yu.safeParse(n);return s.success?{kept:s.data}:{none:"the graph kept in the sas could not be read"}}function Gc(o,e,t=new Date){if(o.sourceOrgId!==e.sourceOrgId)return"the graph kept is of another org";if(o.rootObject!==e.rootObject)return`the graph kept is of ${o.rootObject}, not ${e.rootObject}`;if(o.maxNodes!==e.maxNodes)return`the graph kept was discovered at a cap of ${o.maxNodes}, not ${e.maxNodes}`;let r=t.getTime()-Date.parse(o.discoveredAt);if(!(r>=0&&r<=Vu))return`the graph kept was discovered on ${o.discoveredAt}, more than a day ago`;if(!o.schemaStamp)return"the org did not give its clock when the graph kept was discovered"}function Wc(o){let e=Date.parse(o);if(!Number.isNaN(e))return new Date(Math.floor(e/1e3)*1e3-1e3).toISOString()}import*as no from"node:fs/promises";import*as Uc from"node:path";var Ju="SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name FROM RecordType ORDER BY SobjectType, DeveloperName",Xu="rt-map.json",Zu=10;function Qu(o,e){return Tr.has(o)?e:e.map(t=>t.type==="reference"&&t.referenceTo.some(r=>Tr.has(r))?{...t,nillable:!0}:t)}function qt(o){if(!("attributes"in o))return o;let e={...o};return delete e.attributes,e}var bs=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,s]of r)this.prefixes.has(n)||this.note(n,s)},()=>{}),await this.fromOrg),ji(e,t,this.prefixes))}note(e,t){this.prefixes.set(e,t),this.known.add(t)}};function Vr(o,e){return e.filter(t=>t.type==="reference"&&Zt(o,t.name,t.nillable)).map(t=>t.name)}function ef(o,e,t){return{objectApiName:o,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 tf=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/,ro=class extends Error{constructor(e){super(e),this.name="FrozenExtractionError"}},Hr=class{deps;soqlBuilder=new Oi;constructor(e){this.deps=e}query(e){return $a(e,t=>this.deps.query(t))}async extract(e){if(!tf.test(e.asOf))throw new ro(`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 ro("No root record IDs provided \u2014 empty selection refused");let t=e.guard??new de,r=t.assertOutsideRepo(e.sasDir),n=`CreatedDate <= ${e.asOf}`,s=new qo;s.add(e.rootObject,e.rootRecordIds),s.addReached(e.rootObject,e.rootRecordIds);let a=new Map,d=new tr,i=new Set,u={},l=new bs(this.deps.keyPrefixes),c=new Map,f=async v=>{let A=c.get(v);if(A)return A;let N=await this.deps.describeFields(v);return c.set(v,N),N},p=async v=>{let A=await f(v);A.some(I=>I.name==="CreatedDate")||i.add(v);let N=A.filter(I=>I.type==="base64").map(I=>I.name);return N.length>0&&(u[v]=N),A},g=new Set(e.excludedObjects??[]),h=await this.withWhatStatusesNeed(Ti(e.graph,g),f,g),m=h.graph,y=[...m.nodes].filter(v=>v.included).sort((v,A)=>v.level-A.level),R=new Set(y.map(v=>v.objectApiName));for(let v of y){let A=await p(v.objectApiName),N=this.selectFields(v.objectApiName,A,e.excludedFields),I=A.some(E=>E.name==="CreatedDate"),P=this.soqlBuilder.build({node:v,fields:Qu(v.objectApiName,A),selectFields:N,edges:m.edges,cache:s,rootObjectApiName:`__frozen_root_${e.rootObject}__`,rootRecordId:e.rootRecordIds[0],extraWhere:I?n:void 0,everyEdge:!Tr.has(v.objectApiName),readObjects:R,catalog:Tr,fromAboveOnly:!0});if(!P.scoped)continue;let C=[],G=[];for(let[E,q]of P.statements.entries()){let Y=await this.query(q);if(C.push(...Y),!(E<P.byIdCount))for(let ae of Y)typeof ae.Id=="string"&&G.push(ae.Id)}let D=d.keep(v.objectApiName,await this.keepWhatStatusesNeed(h.added.get(v.objectApiName),C,a),Vr(v.objectApiName,A)),W=a.get(v.objectApiName);W||(W=new Map,a.set(v.objectApiName,W));let V=[];for(let E of D){let q=E.Id;typeof q!="string"||q===""||(V.push(q),W.has(q)||W.set(q,qt(E)))}s.addRead(v.objectApiName,V);let H=new Set(V);s.addReached(v.objectApiName,G.filter(E=>H.has(E))),l.learnFrom(a);for(let E of A)if(E.type==="reference")for(let q of D){let Y=q[E.name];if(!(typeof Y!="string"||Y===""))for(let ae of await l.objectsOf(Y,E.referenceTo))s.add(ae,[Y])}v.objectApiName===e.rootObject&&await this.readWhatTheRootsName({rootObject:e.rootObject,fields:A,selectFields:N,bucket:W,cache:s,owners:l,recordsByObject:a,leftToThePlatform:d,extraWhere:I?n:void 0})}await this.readWhatNamedStatusesNeed({nodes:y,edges:m.edges,cache:s,recordsByObject:a,describe:p,asOfWhere:n,excludedFields:e.excludedFields,leftToThePlatform:d}),await this.completeRequiredParents({...e,graph:m},a,p,n,l,d,g),await rf(a,p,d);let L=await this.addStandardPrices(e,a,n);await this.addSellingModelOptions({...e,graph:m},a,p,n,g);let T=(a.get(pn)?.size??0)>0,j=await this.exclusionCosts(a,p,g,T),x=await this.leaveOutWhatReadsMasked(a,f),U=[...a.entries()].sort(([v],[A])=>v.localeCompare(A)).map(([v,A])=>{let N=[...A.values()].sort((P,C)=>String(P.Id).localeCompare(String(C.Id)));v===qe&&(N=ta(N,{sellingModel:T}));let I=N.map((P,C)=>({referenceId:`${v}-${String(C+1).padStart(6,"0")}`,sourceId:String(P.Id),fields:P}));return{objectApiName:v,records:I}}),S=await this.pullRecordTypes(e);await no.mkdir(r,{recursive:!0});let w=t.assertOutsideRepo(Uc.join(r,Xu));return await no.writeFile(w,`${JSON.stringify(S,null,2)}
21
+ `,"utf8"),{objects:U,asOf:e.asOf,recordTypeMap:S,unboundedObjects:[...i],fileFields:u,...L?{standardPricebookSourceId:L}:{},leftToThePlatform:d.counts(),...j.length>0?{exclusionCosts:j}:{},...x.length>0?{encryptedNotKept:x}:{}}}async leaveOutWhatReadsMasked(e,t){let r=fi(ui(s=>this.deps.query(s)),async s=>({fields:await t(s)})),n=[];for(let[s,a]of e)if(a.size!==0)for(let d of await r(s)){let i=!1;for(let u of a.values())d in u&&(i||=u[d]!==null&&u[d]!==void 0,delete u[d]);i&&n.push(`${s}.${d}`)}return n.sort()}async withWhatStatusesNeed(e,t,r){let n=new Set(e.nodes.map(i=>i.objectApiName)),s=new Map,a=[],d=[];for(let i of e.nodes){let u=ln[i.objectApiName];if(!i.included||!u||n.has(u.object)||s.has(u.object)||r.has(u.object))continue;let l;try{l=await t(u.object)}catch{continue}let c=l.find(f=>f.name===u.lookup&&f.type==="reference"&&f.referenceTo.includes(i.objectApiName));c&&(s.set(u.object,{parent:i.objectApiName,lookup:c.name}),a.push(ef(u.object,l,i.level+1)),d.push({sourceObject:i.objectApiName,targetObject:u.object,relationshipName:c.name,type:"lookup",required:Zt(u.object,c.name,c.nillable)}))}return s.size===0?{graph:e,added:s}:{graph:{...e,nodes:[...e.nodes,...a],edges:[...e.edges,...d]},added:s}}async readWhatTheRootsName(e){let{rootObject:t,bucket:r,cache:n}=e,s=new Set([...n.get(t)??[]].filter(i=>!r.has(i)));if(s.size===0)return;let a=[];for(let i of this.soqlBuilder.buildById({objectApiName:t,selectFields:e.selectFields,ids:s,extraWhere:e.extraWhere}))a.push(...await this.query(i));let d=e.leftToThePlatform.keep(t,a,Vr(t,e.fields));for(let i of d)typeof i.Id=="string"&&!r.has(i.Id)&&r.set(i.Id,qt(i));e.owners.learnFrom(e.recordsByObject);for(let i of e.fields)if(i.type==="reference")for(let u of d){let l=u[i.name];if(!(typeof l!="string"||l===""))for(let c of await e.owners.objectsOf(l,i.referenceTo))n.add(c,[l])}}async keepWhatStatusesNeed(e,t,r){if(!e)return t;let n=Dt[e.parent],s=n?await nr(d=>this.query(d),n):void 0,a=new Set;for(let[d,i]of r.get(e.parent)??[])s&&or(i.Status,s)&&a.add(d);return t.filter(d=>{let i=d[e.lookup];return typeof i=="string"&&a.has(i)})}async readWhatNamedStatusesNeed(e){for(let[t,r]of Object.entries(ln)){let n=e.nodes.find(m=>m.objectApiName===r.object),s=e.recordsByObject.get(t),a=Dt[t];if(!n||!s||s.size===0||!a)continue;let d=e.cache.reachedOf(t),i=[...s].filter(([m])=>!d?.has(m));if(i.length===0)continue;let u=await nr(m=>this.query(m),a);if(!u)continue;let l=i.filter(([,m])=>or(m.Status,u)).map(([m])=>m);if(l.length===0)continue;let c=await e.describe(r.object),f=new qo;f.addRead(t,l);let p=this.soqlBuilder.build({node:n,fields:c,selectFields:this.selectFields(r.object,c,e.excludedFields),edges:e.edges,cache:f,rootObjectApiName:`__frozen_root_${t}__`,rootRecordId:l[0],extraWhere:c.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=Vr(r.object,c);for(let m of p.statements){let y=e.leftToThePlatform.keep(r.object,await this.query(m),h);for(let R of y)typeof R.Id=="string"&&!g.has(R.Id)&&g.set(R.Id,qt(R))}}}async completeRequiredParents(e,t,r,n,s,a,d){let i=new Set(e.graph.nodes.filter(f=>f.included).map(f=>f.objectApiName)),u=Pi(e.graph,d),l=f=>i.has(f)||u.has(f),c=new Map;for(let f=0;f<Zu;f++){s.learnFrom(t);let p=new Map;for(let[g,h]of t){let m=(await r(g)).filter(y=>y.type==="reference"&&Ai(g,y));for(let y of h.values())for(let R of m){let L=y[R.name];if(typeof L!="string"||L===""||a.has(L)||!R.referenceTo.some(l))continue;let T=(await s.objectsOf(L,R.referenceTo)).filter(l);for(let j of T)t.get(j)?.has(L)||c.get(j)?.has(L)||p.set(j,(p.get(j)??new Set).add(L))}}if(p.size===0)return;for(let[g,h]of p){c.set(g,new Set([...c.get(g)??[],...h]));let m=await r(g),y=t.get(g);y||(y=new Map,t.set(g,y));let R=this.soqlBuilder.buildById({objectApiName:g,selectFields:this.selectFields(g,m,e.excludedFields),ids:h,extraWhere:m.some(T=>T.name==="CreatedDate")?n:void 0}),L=Vr(g,m);for(let T of R)for(let j of a.keep(g,await this.query(T),L))typeof j.Id=="string"&&!y.has(j.Id)&&y.set(j.Id,qt(j))}}}async addStandardPrices(e,t,r){let n=t.get(qe);if(!n||n.size===0)return;let[s]=await this.query(Ct),a=typeof s?.Id=="string"?s.Id:void 0;if(!a)return;let d=g=>[We,Ye,Qt].map(h=>String(g[h]??"")).join("|"),i=new Set,u=new Set;for(let g of n.values()){if(g[yt]===a)continue;let h=g[We];typeof h=="string"&&h!==""&&(i.add(h),u.add(d(g)))}if(i.size===0)return;let l=async(g,h)=>{let m=await this.deps.describeFields(g),y=this.selectFields(g,m,e.excludedFields).map(L=>ge(L)).join(", "),R=m.some(L=>L.name==="CreatedDate")?` AND ${r}`:"";return this.query(`SELECT ${y} FROM ${g} WHERE ${h}${R}`)},c=t.get(un);if(c||(c=new Map,t.set(un,c)),!c.has(a))for(let g of await l(un,`Id = '${Me(a)}'`))c.set(a,qt(g));let f=await this.deps.describeFields(qe),p=this.soqlBuilder.buildJoining({objectApiName:qe,selectFields:this.selectFields(qe,f,e.excludedFields),split:{field:We,ids:i},whole:{field:yt,ids:new Set([a])},extraWhere:f.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)||u.has(d(h))&&n.set(h.Id,qt(h));return a}async addSellingModelOptions(e,t,r,n,s){if(s.has(ze)||e.graph.nodes.some(m=>m.objectApiName===ze&&!m.included))return;let a=t.get(qe),d=t.get(Si),i=t.get(pn);if(!a||!d||!i)return;let u=m=>`${String(m[We]??"")}|${String(m[Ye]??"")}`,l=new Set,c=new Set,f=new Set;for(let m of a.values()){let y=m[We],R=m[Ye];typeof y!="string"||!d.has(y)||typeof R!="string"||!i.has(R)||(l.add(y),c.add(R),f.add(u(m)))}if(f.size===0)return;let p=await r(ze),g=this.soqlBuilder.buildJoining({objectApiName:ze,selectFields:this.selectFields(ze,p,e.excludedFields),split:{field:We,ids:l},whole:{field:Ye,ids:c},extraWhere:p.some(m=>m.name==="CreatedDate")?n:void 0}),h=t.get(ze);h||(h=new Map,t.set(ze,h));for(let m of g)for(let y of await this.query(m))typeof y.Id!="string"||h.has(y.Id)||f.has(u(y))&&h.set(y.Id,qt(y))}async exclusionCosts(e,t,r,n){if(r.size===0)return[];let s=[],a=i=>`record${i===1?"":"s"}`,d=new Map;for(let[i,u]of e){if(u.size===0)continue;let l=(await t(i)).filter(g=>g.type==="reference"&&g.referenceTo.length===1&&g.referenceTo[0]!==i&&r.has(g.referenceTo[0])&&Zt(i,g.name,g.nillable)),c=i===qe&&n&&r.has(ze);if(l.length===0&&!c)continue;let f=new Map,p=new Map;for(let[g,h]of u){let m;for(let L of l){let T=h[L.name],j=L.referenceTo[0];if(!(typeof T!="string"||T==="")&&!e.get(j)?.has(T)){m={field:L.name,excluded:j};break}}let y=h[Ye];if(!m&&c&&typeof y=="string"&&e.get(pn)?.has(y)&&(m={field:Ye,excluded:ze}),!m)continue;f.set(g,m.excluded);let R=p.get(m.excluded)??{field:m.field,count:0};R.count++,p.set(m.excluded,R)}f.size>0&&d.set(i,f);for(let[g,{field:h,count:m}]of p)s.push({objectApiName:i,excludedObject:g,count:m,note:g===ze?`${m} ${i} ${a(m)} sold under a selling model cannot be loaded without the option that sells the product under it, and excludedObjects leaves ${g} out`:`${m} ${i} ${a(m)} cannot be loaded without the ${g} named by ${h}, which excludedObjects leaves out`})}for(let[i,u]of Object.entries(ln)){let l=e.get(i),c=Dt[i];if(!l||l.size===0||!c)continue;let f=await nr(y=>this.query(y),c);if(!f)continue;let p=new Set,g=new Map,h=d.get(u.object);for(let[y,R]of e.get(u.object)??[]){let L=R[u.lookup];if(typeof L!="string")continue;let T=h?.get(y);T?g.has(L)||g.set(L,T):p.add(L)}let m=new Map;for(let[y,R]of l){if(!or(R.Status,f))continue;let L=r.has(u.object)?u.object:p.has(y)?void 0:g.get(y);L&&m.set(L,(m.get(L)??0)+1)}for(let[y,R]of m){let L=R===1;s.push({objectApiName:i,excludedObject:y,count:R,note:`${R} ${i} ${a(R)} past Draft will be loaded as ${L?"a draft":"drafts"} and stay so: `+(y===u.object?`the platform gives ${i} this status only with ${u.object} records under it, and excludedObjects leaves ${u.object} out`:`none of ${L?"its":"their"} ${u.object} records can be loaded without ${y}, which excludedObjects leaves out`)})}}return s}selectFields(e,t,r){let n=new Set(r?.[e]??[]),s=t.map(a=>a.name).filter(a=>!n.has(a));return s.includes("Id")||s.unshift("Id"),s}async pullRecordTypes(e){let t=e.recordTypesSoqlTemplate??Ju,r=Wr(t,e.tokens??{}),n=await this.query(r),s=[];for(let a of n)typeof a.Id=="string"&&typeof a.SobjectType=="string"&&typeof a.DeveloperName=="string"&&typeof a.Name=="string"&&s.push({id:a.Id,sobjectType:a.SobjectType,developerName:a.DeveloperName,..."NamespacePrefix"in a?{namespacePrefix:typeof a.NamespacePrefix=="string"&&a.NamespacePrefix!==""?a.NamespacePrefix:null}:{},name:a.Name});return s}};async function rf(o,e,t){for(let r=!0;r;){r=!1;for(let[n,s]of o){let a=[...s.values()],d=Vr(n,await e(n)),i=t.keep(n,a,d);if(i.length===a.length)continue;r=!0;let u=new Set(i.map(l=>l.Id));for(let l of s.keys())u.has(l)||s.delete(l)}}}var oo=class{anonymize(e){let{rules:t,pseudonymizer:r}=e,n=Object.entries(e.extracted.fileFields??{}).filter(([c,f])=>f.some(p=>ft(t,c,p)!=="keep")).map(([c])=>c).filter(c=>e.extracted.objects.some(f=>f.objectApiName===c&&f.records.length>0)).sort(),s={...e.extracted,objects:e.extracted.objects.filter(c=>!n.includes(c.objectApiName))},a=new Map;for(let c of s.objects)for(let f of c.records)a.set(f.sourceId,f.referenceId);let d=new Map(s.recordTypeMap.map(c=>[c.id,c])),i={};for(let c of s.objects)i[c.objectApiName]=s.recordTypeMap.filter(f=>f.sobjectType===c.objectApiName).map(f=>({name:f.name,developerName:f.developerName,...f.namespacePrefix!==void 0?{namespacePrefix:f.namespacePrefix}:{}}));let u=[];for(let c of s.objects){let f=c.records.map(p=>{let g=this.anonymizeRecordFields(c.objectApiName,p.fields,a,d,t,r),h=p.fields.RecordTypeId,m=typeof h=="string"?d.get(h):void 0;return{referenceId:p.referenceId,fields:g,...m?{recordTypeDeveloperName:lt(m.namespacePrefix,m.developerName)}:{}}});u.push({objectApiName:c.objectApiName,records:f})}let l=s.standardPricebookSourceId?a.get(s.standardPricebookSourceId):void 0;return{datasetVersion:e.datasetVersion,objects:u,recordTypes:i,personContactSidecar:nf(s,a),...l?{standardPricebook:l}:{},...n.length>0?{filesLeftOut:n}:{}}}anonymizeRecordFields(e,t,r,n,s,a){let d={};for(let[i,u]of Object.entries(t)){if(i==="Id")continue;if(u==null){d[i]=u;continue}if(i==="RecordTypeId"&&typeof u=="string"){let c=n.get(u);d[i]=c?c.name:"";continue}if(typeof u=="string"){let c=r.get(u);if(c!==void 0){d[i]=c;continue}}let l=ft(s,e,i);d[i]=a.pseudonymize(l,u)}for(let[i,u]of Object.entries(d))typeof u=="string"&&An(u)&&(d[i]="");return d}};function nf(o,e){let t=[],r=o.objects.find(n=>n.objectApiName==="Account");if(!r)return t;for(let n of r.records){let s=n.fields.PersonContactId;if(typeof s!="string"||s==="")continue;let a=e.get(s);a!==void 0&&t.push({accountReferenceId:n.referenceId,contactReferenceId:a})}return t}var of=/^[A-Z]{2}-\d{3}-[A-Z]{2}$/,sf=/^\+3363998\d{4}$/,af=/^[a-z0-9-]+@example\.invalid$/,df=/^\d{2}0+$/,cf=3,so=class{run(e,t,r,n={}){let s=new Set,a=new Map;for(let c of t.objects)for(let f of c.records)s.add(f.referenceId),a.set(f.referenceId,{objectApiName:c.objectApiName,record:f});let d={substitution:[],"clear-empty":[],formats:[],"no-residual-id":[]},i=new Map(e.recordTypeMap.map(c=>[c.id,[c.name,c.developerName]])),u=new Set(t.filesLeftOut??[]);for(let c of e.objects)if(!u.has(c.objectApiName))for(let f of c.records){let p=a.get(f.referenceId);if(!p){d.substitution.push({check:"substitution",objectApiName:c.objectApiName,referenceId:f.referenceId,detail:"record missing from the frozen dataset"});continue}let g=f.fields.RecordTypeId;this.checkSubstitution(c.objectApiName,f,p.record,r,d.substitution,new Set(typeof g=="string"?i.get(g)??[]:[]))}for(let c of t.objects)for(let f of c.records)this.checkClearEmpty(c.objectApiName,f,r,s,d["clear-empty"]),this.checkNoResidualId(c.objectApiName,f,s,d["no-residual-id"]);this.checkFormats(e,t,r,a,d.formats);let l=["substitution","clear-empty","formats","no-residual-id"].map(c=>({name:c,passed:d[c].length===0,violations:d[c]}));return{passed:l.every(c=>c.passed),checks:l,author:n.author??"frozen-dataset-engine",checkedAt:(n.now?.()??new Date).toISOString()}}checkSubstitution(e,t,r,n,s,a){for(let[d,i]of Object.entries(t.fields)){if(d==="Id"||i===null||i===void 0||i===""||ft(n,e,d)==="keep")continue;let l=r.fields[d];if(lf(l,i)){s.push({check:"substitution",objectApiName:e,referenceId:t.referenceId,field:d,detail:"original value still present in its own field"});continue}if(typeof i=="string"&&i.length>=cf)for(let[c,f]of Object.entries(r.fields))c===d||typeof f!="string"||f!==i||ft(n,e,c)==="keep"||c==="RecordTypeId"&&a.has(f)||s.push({check:"substitution",objectApiName:e,referenceId:t.referenceId,field:c,detail:`transversal leak: original value of "${d}" found in "${c}"`})}}checkClearEmpty(e,t,r,n,s){for(let[a,d]of Object.entries(t.fields))a!=="RecordTypeId"&&(typeof d=="string"&&n.has(d)||ft(r,e,a)==="clear"&&d!==""&&d!==null&&d!==void 0&&s.push({check:"clear-empty",objectApiName:e,referenceId:t.referenceId,field:a,detail:`residual value under "clear" generator: ${JSON.stringify(d)}`}))}checkFormats(e,t,r,n,s){let a={registrationSIV:d=>of.test(d),phoneE164:d=>sf.test(d),email:d=>af.test(d),postalCodeGeneralize:(d,i)=>df.test(d)&&d.length===i.trim().length};for(let d of e.objects)for(let i of d.records){let u=n.get(i.referenceId);if(u)for(let[l,c]of Object.entries(i.fields)){if(typeof c!="string"||c==="")continue;let f=ft(r,d.objectApiName,l),p=a[f];if(!p)continue;let g=u.record.fields[l];typeof g!="string"||g===""||p(g,c)||s.push({check:"formats",objectApiName:d.objectApiName,referenceId:i.referenceId,field:l,detail:`format not conserved for ${f}: ${JSON.stringify(g)}`})}}}checkNoResidualId(e,t,r,n){for(let[s,a]of Object.entries(t.fields))typeof a=="string"&&An(a)&&n.push({check:"no-residual-id",objectApiName:e,referenceId:t.referenceId,field:s,detail:"checksum-valid Salesforce ID survived the sweep"})}};function lf(o,e){return o===e?!0:o==null||e===null||e===void 0?!1:String(o)===String(e)}var Yr=class{constructor(e){this.orgAccess=e}orgAccess;cache=new Map;describes=new Map;async resolveByDeveloperName(e,t,r,n){let s=n===void 0?qa(r):{namespacePrefix:n,developerName:r},a=`${e}|${t}|${String(s.namespacePrefix)}|${s.developerName}`,d=this.cache.get(a);if(d!==void 0)return d;let i=`SELECT Id, DeveloperName, NamespacePrefix FROM RecordType WHERE SobjectType = '${Me(t)}' AND DeveloperName = '${Me(s.developerName)}'`,u=Ba(await this.orgAccess.query(e,i)),l=Ga(s,u,To),c;if("ambiguous"in l)c={ambiguous:!0,carriers:l.ambiguous.map(To)};else if("found"in l){let f=l.found.id;c=await this.isUnavailable(e,t,f)?{unavailable:!0,id:f}:f}else c=null;return this.cache.set(a,c),c}async isUnavailable(e,t,r){let n=this.describeOf(e,t);return n?(await n).recordTypeInfos?.find(a=>a.recordTypeId===r)?.available===!1:!1}async givenRecordType(e,t){let r=this.describeOf(e,t);if(r)return Dn(Sn((await r).recordTypeInfos))}describeOf(e,t){let r=this.orgAccess.describe;if(!r)return;let n=`${e}|${t}`,s=this.describes.get(n);return s||(s=r(e,t),this.describes.set(n,s)),s}};import*as co from"node:fs";var uf=2e3,ff=3,pf=10,gf=o=>new Promise(e=>setTimeout(e,o)),ao=class{constructor(e){this.deps=e;this.sasGuard=e.sasGuard??new de}deps;sasGuard;personAccounts=new Map;async verify(e){let t=e.now??(()=>new Date),r=e.sleep??gf,n=g=>e.onProgress?.(g),s=e.measurementIntervalMs??uf,a=e.maxAttempts??ff,d=_n(this.sasGuard,e.contractPath);n({phase:"verify",status:"started",progress:0,message:"Measuring org state"});let i=null,u=null,l=null,c=0;for(let g=1;g<=a;g++){c=g,l=await this.measure(e,d);let h=Rs(l);if(i!==null&&h===i){u=l;break}i=h,g<a&&await r(s)}let f=this.buildChecks(e,d,u??l,u!==null),p={status:Rf(f,d,u),checks:f,attempts:c,measuredAt:t().toISOString(),objects:kf(d,u??l)};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} (${c} 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?Vc(e.mapping):void 0,n={};for(let s of Object.keys(t.objects).sort()){let a=`SELECT COUNT() FROM ${ge(s)}`;if(!r){n[s]=await this.deps.orgAccess.count(e.orgId,a);continue}let d=0;for(let i of Hc(r.get(s)??[]))d+=await this.deps.orgAccess.count(e.orgId,`${a} WHERE ${i}`);n[s]=d}return n}async measureOrphans(e,t){let r={},n=e.orphanSampleSize??pf,s=e.mapping?Vc(e.mapping):void 0;for(let[a,d]of Object.entries(e.mandatoryLookups??{}))for(let i of d){let u=new Set([...Kc(t,a,i),...ks(t.objects[a]?.parentNotLoaded,i)].flatMap(f=>{let p=e.mapping?.get(f);return p===void 0?[]:[p]})),l=s?Hc((s.get(a)??[]).filter(f=>!u.has(f))):[""],c=[];for(let f of l){let p=`SELECT Id FROM ${ge(a)} WHERE ${ge(i)} = null${f?` AND ${f}`:""} ORDER BY Id LIMIT ${n}`,g=await this.deps.orgAccess.query(e.orgId,p);c.push(...g.map(h=>String(h.Id)))}r[`${a}.${i}`]=c.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(i=>e.mapping?.has(i.accountReferenceId));if(r.length===0||!await this.describesPersonAccounts(e.orgId))return{checked:0,unrestored:[]};let n=r.map(i=>e.mapping?.get(i.accountReferenceId)),s=await In(i=>this.deps.orgAccess.query(e.orgId,i),n),a=[],d=0;for(let i of r){let u=e.mapping.get(i.accountReferenceId),l=s.get(u);l!==void 0&&(d++,e.mapping.get(i.contactReferenceId)!==l&&a.push(i.accountReferenceId))}return{checked:d,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(s=>s.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,s]of Object.entries(e.presenceKeys??{})){let a=new Set(Kc(t,n,s)),d=(e.dataset.objects.find(l=>l.objectApiName===n)?.records??[]).filter(l=>!a.has(l.referenceId)),i=[...new Set(d.map(l=>l.fields[s]).filter(l=>typeof l=="string"&&l!==""))].sort();if(i.length===0){r[n]=[];continue}let u=new Set;for(let l=0;l<i.length;l+=io){let c=i.slice(l,l+io).map(p=>`'${Me(p)}'`).join(", "),f=await this.deps.orgAccess.query(e.orgId,`SELECT ${ge(s)} k FROM ${ge(n)} WHERE ${ge(s)} IN (${c})`);for(let p of f)u.add(String(p.k))}r[n]=i.filter(l=>!u.has(l))}return r}buildChecks(e,t,r,n){let s=[];if(s.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 s;let a=Object.entries(t.objects).filter(([f,p])=>r.counts[f]!==p.expected).map(([f,p])=>`${f}: expected ${p.expected}, got ${r.counts[f]??0}`);s.push({name:"counts",passed:a.length===0,detail:a.length===0?"All object counts match the counting contract":`Count mismatches \u2014 ${a.join("; ")}`});let d=Yc(t),i=hf(t,r);s.push({name:"load",passed:d.records===0&&i.length===0,detail:yf(d,i)});let u=Object.entries(r.orphans).filter(([,f])=>f.length>0),l=bf(t),c=[...u.length>0?[`Orphans \u2014 ${u.map(([f,p])=>`${f} (${p.length}: ${p.join(", ")})`).join("; ")}`]:[],...l.length>0?["Lookups the load left empty because the record they name was not loaded \u2014 "+l.map(({link:f,count:p})=>`${f} (${p})`).join("; ")]:[]];if(s.push({name:"orphans",passed:c.length===0,detail:c.length===0?"No orphans on the mandatory lookups of the graph":c.join("; ")}),(e.dataset?.personContactSidecar?.length??0)>0&&e.mapping&&s.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 f=Object.entries(r.presence).filter(([,p])=>p.length>0);s.push({name:"presence",passed:f.length===0,detail:f.length===0?"All referential keys present in the org":`Missing keys \u2014 ${f.map(([p,g])=>`${p}: ${g.join(", ")}`).join("; ")}`})}return s}consignVerdict(e,t,r){let n=this.sasGuard.assertOutsideRepo(e),s=ir(JSON.parse(co.readFileSync(n,"utf8")));s.controls.dryRunLoad={status:t.status==="passed"?"passed":"failed",at:t.measuredAt,detail:`post-load check by ${r??"unknown"}: verdict=${t.status}; `+t.checks.map(a=>`${a.name}=${a.passed?"OK":"KO"}`).join(", ")},co.writeFileSync(n,Wn(s),"utf8")}};function Rs(o){return Array.isArray(o)?`[${o.map(Rs).join(",")}]`:typeof o=="object"&&o!==null?`{${Object.entries(o).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${Rs(r)}`).join(",")}}`:JSON.stringify(o)}function Kc(o,e,t){return ks(o.objects[e]?.writtenWithout,t)}function ks(o,e){let t=o?.[e];return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}var Jr={refused:["dml-failed","person-contact-not-sent"],heldBack:["parent-refused"],notLoadable:["object-not-loaded"]};function Yc(o){let e={whole:[],part:[],refused:0,heldBack:0,notLoadable:[],records:0};for(let[t,r]of Object.entries(o.objects).sort(([n],[s])=>n.localeCompare(s))){let n=u=>u.reduce((l,c)=>l+(r.exclusionReasons[c]??0),0),s=n(Jr.notLoadable);s>0&&e.notLoadable.push({objectApiName:t,records:s});let a=n(Jr.refused),d=n(Jr.heldBack),i=a+d;i!==0&&(e.refused+=a,e.heldBack+=d,e.records+=i,r.expected===0?e.whole.push({objectApiName:t,notLoaded:i}):e.part.push({objectApiName:t,notLoaded:i,of:i+r.expected}))}return e}function hf(o,e){return Object.entries(o.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 mf(o){return o.length===0?"":`${o.reduce((t,r)=>t+r.gone,0)} record(s) it wrote or linked are no longer in the target \u2014 `+o.map(t=>`${t.objectApiName} (${t.gone} of ${t.of})`).join(", ")}function yf(o,e=[]){let t=wf(o),r=mf(e);if(o.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=[...o.whole.length>0?["Objects the load wrote none of \u2014 "+o.whole.map(a=>`${a.objectApiName} (${a.notLoaded} not loaded)`).join(", ")]:[],...o.part.length>0?["Objects it wrote part of \u2014 "+o.part.map(a=>`${a.objectApiName} (${a.notLoaded} of ${a.of} not loaded)`).join(", ")]:[]],s=[...o.refused>0?[`${o.refused} refused by the target org`]:[],...o.heldBack>0?[`${o.heldBack} held back for a parent the target org refused`]:[]];return`${o.records} record(s) not loaded: ${s.join(", ")}. ${n.join("; ")}${r===""?"":`; ${r}`}${t}`}function wf(o){return o.notLoadable.length===0?"":`; ${o.notLoadable.reduce((t,r)=>t+r.records,0)} record(s) not loadable, as the preview said \u2014 `+o.notLoadable.map(t=>`${t.objectApiName} (${t.records})`).join(", ")}function bf(o){let e=[];for(let[t,r]of Object.entries(o.objects).sort(([n],[s])=>n.localeCompare(s)))for(let n of Object.keys(r.parentNotLoaded??{}).sort()){let s=ks(r.parentNotLoaded,n).length;s>0&&e.push({link:`${t}.${n}`,count:s})}return e}function Rf(o,e,t){if(t===null)return"unstable";let r=o.filter(a=>!a.passed);if(r.length===0)return"passed";let n=Object.values(t.orphans).some(a=>a.length>0);return r.every(a=>a.name==="load"||a.name==="orphans")&&!n&&Yc(e).whole.length===0?"partial":"failed"}function kf(o,e){let t=r=>r.slice(0,r.indexOf("."));return Object.entries(o.objects).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>{let s=[...Jr.refused,...Jr.heldBack].reduce((c,f)=>c+(n.exclusionReasons[f]??0),0),a=e?.counts[r]??0,d=Object.entries(e?.orphans??{}).filter(([c])=>t(c)===r).reduce((c,[,f])=>c+f.length,0),i=e?.presence[r]?.length??0,u=r==="Account"?e?.personContact.unrestored.length??0:0,l=e!==null&&a===n.expected&&s===0&&d===0&&i===0&&u===0;return{objectApiName:r,status:l?"passed":"failed",expected:n.expected,found:a,notLoaded:s,orphans:d,missingKeys:i,...u>0?{personContactsUnlinked:u}:{}}})}var io=200;function Vc(o){let e=new Map;for(let[t,r]of o){let n=t.startsWith("placeholder:")?t.split(":")[1]:t.slice(0,t.lastIndexOf("-"));if(!n)continue;let s=e.get(n)??[];s.push(r),e.set(n,s)}return e}function Hc(o){let e=[];for(let t=0;t<o.length;t+=io){let r=o.slice(t,t+io).map(n=>`'${Me(n)}'`);e.push(`Id IN (${r.join(", ")})`)}return e}var Is=200;function Os(o,e=Is){return{insert:(t,r,n,s)=>vs(o.insert(r,n,e,s?vf(s):void 0)),update:(t,r,n)=>vs(o.update(r,n,e)),delete:(t,r,n)=>vs(o.delete(r,n,e))}}function vf(o){let e=0,t=0;return{sending:(r,n,s)=>{t=s},answered:(r,n,s,a)=>{a?s.forEach((d,i)=>{let u=a[i];u!==void 0&&o(u,[d])}):(o(e,s),e+=t),t=0}}}async function vs(o){try{return await o}catch(e){if(e instanceof vd)return e.written;throw e}}var If=200;function Jc(o){let e={threshold:o.threshold,perCall:Is,...o.duplicateRules?{duplicateRules:o.duplicateRules}:{}},t=o.inserts.filter(({rows:n})=>n>0),r=t.reduce((n,{rows:s})=>n+Math.ceil(s/If),0);return Uo(t,e)+Uo((o.purged??[]).filter(({rows:n})=>n>0),e)+Od(t.length,o.automationRead??0)+r}var Of="Nothing was read or written.",Sf=new Set([ja,Ea,Fa,"Document"].map(o=>o.toLowerCase()));function Ss(o){return Sf.has(o.toLowerCase())}function As(o,e){let t=new Map(o.objects.map(i=>[i.objectApiName.toLowerCase(),i])),r=new Set(e.objects.map(i=>i.toLowerCase())),n=new Set(e.excluded.map(i=>i.toLowerCase())),s=[...e.objects,...e.excluded].filter(i=>!t.has(i.toLowerCase())),a=[],d=[];for(let i of o.objects){let u=i.objectApiName.toLowerCase(),l=c=>{d.push({objectApiName:i.objectApiName,records:i.records,reason:c})};Ss(i.objectApiName)?l("fileContentNotKept"):r.size>0&&!r.has(u)||n.has(u)||i.customSetting!==void 0&&!e.customSettings?l("excluded"):a.push(i)}return{replayed:a,leftOut:d,unknown:[...new Set(s)],records:a.reduce((i,u)=>i+u.records,0)}}function Zc(o){let e=o.dataStorageMaxMB!==void 0?{dataStorageMaxMB:o.dataStorageMaxMB}:{};return o.staging===!0?{kind:"real",why:"staging",...e}:o.tier==="scratch"?{kind:"free",why:"scratch",...e}:o.tier==="developer"?{kind:"free",why:"developer",...e}:o.dataStorageMaxMB===void 0?{kind:"unknown"}:o.dataStorageMaxMB>Gr?{kind:"real",why:"storage",dataStorageMaxMB:o.dataStorageMaxMB}:{kind:"free",why:"developerSandbox",dataStorageMaxMB:o.dataStorageMaxMB}}function Qc(o,e){return o!==void 0&&e!==void 0&&o.slice(0,15)===e.slice(0,15)}var Af=/\.my\.salesforce\.com$/;function Xc(o){if(o!==void 0)try{let e=new URL(o).hostname.toLowerCase();return Af.test(e)?e:void 0}catch{return}}function el(o,e){if(o.tier!=="sandbox")return;if((e.formerOrganizationIds??[]).some(r=>Qc(r,o.organizationId)))return"formerOrganizationId";if(e.username!==void 0&&e.username.trim().toLowerCase()===o.username.trim().toLowerCase())return"username";let t=Xc(e.instanceUrl);if(t!==void 0&&t===Xc(o.instanceUrl))return"myDomain"}var Xr={mask:"replay it masked (--mask)",noRealData:"declare that it holds no real data (--no-real-data), which the audit trail keeps",fewerObjects:"name the objects to replay (--objects A,B) or leave some out (--exclude-object X)",rewind:"rewind that org to the checkpoint instead"};function Gt(o,e,t){return{code:o,message:`${e} ${Of}`,params:t}}function lo(o){return o.toLocaleString("en-US")}function tl(o){let e={...Xr,...o.words},{checkpoint:t,target:r}=o;if(t===void 0)return Gt("REPLAY_CHECKPOINT_UNUSABLE",`Checkpoint ${o.checkpointId} does not read: its file is damaged, and what it holds cannot be told.`,{checkpoint:o.checkpointId,why:"damaged"});let n=t.name;if(t.status!=="ready")return Gt("REPLAY_CHECKPOINT_UNUSABLE",t.status==="taking"?`Checkpoint '${n}' is still being taken, or its take stopped before its end: it holds part of its org at most.`:`The take of checkpoint '${n}' failed: it holds part of its org at most.`,{checkpoint:n,why:t.status});let s=Tf(t,r,e);if(s!==void 0)return s;let a=jf(t,o.choices,r,e);if(a!==void 0)return a;let d=As(t,o.choices);if(d.records===0){let u=d.replayed.length===0?"every object it holds is left out":"the objects replayed hold no record";return Gt("REPLAY_NOTHING",`Nothing of checkpoint '${n}' is left to replay into ${r.name}: ${u}${Pf(d)?", and a checkpoint keeps no file\u2019s content":""}.`,{checkpoint:n,target:r.name})}let i=o.maxRecords??Qs;if(d.records>i)return Gt("REPLAY_TOO_MANY",`Checkpoint '${n}' would replay ${lo(d.records)} records into ${r.name}, past the ${lo(i)} a replay sets up at once: ${e.fewerObjects}.`,{checkpoint:n,target:r.name,records:d.records,max:i})}function Pf(o){return o.leftOut.length>0&&o.leftOut.every(e=>e.reason==="fileContentNotKept")}function Tf(o,e,t={}){if(!Qc(e.organizationId,o.org.organizationId))return;let r=t.rewind??Xr.rewind;return Gt("REPLAY_SAME_ORG",`${e.name} is the org checkpoint '${o.name}' was taken of: a replay creates copies of its records in another org, beside what that org holds. To bring ${e.name} back to that moment, ${r}.`,{checkpoint:o.name,target:e.name})}function jf(o,e,t,r={}){let n={...Xr,...r},s=Zc(o.org);if(s.kind==="free"||e.mask||el(o.org,t)!==void 0)return;let a=o.name;if(s.kind==="unknown")return e.noRealData===!0?void 0:Gt("REPLAY_COPY_UNKNOWN",`Checkpoint '${a}' is of a sandbox and does not say which: taken before SandForge 1.81, it keeps no data storage, and a Partial Copy or a Full sandbox holds production\u2019s records. To replay it into ${t.name}, ${n.mask}, or ${n.noRealData}.`,{checkpoint:a,target:t.name});let d=s.why==="staging"?"a sandbox marked Staging, which holds real data":`a Partial Copy or Full sandbox, by its data storage (${lo(s.dataStorageMaxMB??0)} MB, past the ${lo(Gr)} MB of a Developer Pro), which may hold real data`;return Gt("REPLAY_REAL_DATA",`Checkpoint '${a}' is of ${d}: it goes into another org masked only. To replay it into ${t.name}, ${n.mask}.`,{checkpoint:a,target:t.name,why:s.why,...s.dataStorageMaxMB!==void 0?{mb:s.dataStorageMaxMB}:{}})}function rl(o,e,t){let r=Zc(o.org),n=el(o.org,t),s=r.kind==="unknown"&&!e.mask&&e.noRealData===!0;return{replaySource:r.kind==="free"||r.kind==="real"?r.why:"unknown",...r.kind!=="unknown"&&r.dataStorageMaxMB!==void 0?{replaySourceStorageMB:r.dataStorageMaxMB}:{},replayMasked:e.mask,replayContactPoints:e.contactPoints,...s?{replayNoRealDataDeclared:!0}:{},...n!==void 0&&!e.mask&&r.kind!=="free"?{replayIntoSameSandbox:n}:{}}}function ce(o){return o.slice(0,15)}var sl=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function ke(o){return Qa(o)??o}function nl(o,e){return`${o}-${ke(e)}`}var Ps="005",Ts="00G",al="00D",js="00e",il="OwnerId",Ns="RecordTypeId",Es="SetupOwnerId",Qr="CurrencyIsoCode",fo="Pricebook2",Wt=200,Fs=new Set([...zi,Do]),Ef=["Title","Name"];async function*Ls(o,e){let t=await zo.read(o.folder,o.checkpoint.snapshotId,e);for await(let r of t.records())typeof r.Id=="string"&&(yield r)}async function Ff(o,e){let t=await zo.read(o.folder,o.checkpoint.snapshotId,e),r=[];for(let n=0;n<t.size;n++)r.push(t.idAt(n));return r}function po(o,e){return o!==void 0&&!o.unread.some(t=>t.part===e)}async function Lf(o){let e=As(o.checkpoint,o.choices),t=new Map;for(let p of o.checkpoint.objects)for(let g of await Ff(o,p.objectApiName))t.set(ce(g),p.objectApiName);let r=new Set,n=new Set,s=new Set,a=new Set,d=new Map,i=new Set,u=[],l=new Set;for(let p of e.replayed)for await(let g of Ls(o,p.objectApiName)){l.add(ce(g.Id));for(let[h,m]of Object.entries(g)){if(Fs.has(h)||typeof m!="string"||(h===Qr&&m!==""&&i.add(m),!sl.test(m)))continue;let y=ce(m);if(h===Ns)s.add(y);else if(y.startsWith(Ps))r.add(y);else if(y.startsWith(Ts)&&h===il)n.add(y);else if(y.startsWith(js)&&h===Es)a.add(y);else if(!t.has(y)&&!y.startsWith(al)){let R=`${p.objectApiName}.${h}`,L=d.get(R)??new Set;L.add(y),d.set(R,L)}}if(p.objectApiName===qe){let h=g[yt],m=g[We];if(typeof h=="string"&&typeof m=="string"){let y=g[Qt];u.push({book:ce(h),product:ce(m),currency:typeof y=="string"?y:""})}}}let c=[];if((o.checkpoint.files?.links??0)>0)for await(let p of Mi(o.folder))l.has(ce(p.LinkedEntityId))&&c.push({ContentDocumentId:p.ContentDocumentId,LinkedEntityId:p.LinkedEntityId,ShareType:p.ShareType,Visibility:p.Visibility});let f=[];for(let p of e.leftOut)if(p.reason==="fileContentNotKept")for await(let g of Ls(o,p.objectApiName)){let h=Ef.map(m=>g[m]).find(m=>typeof m=="string"&&m!=="");f.push({objectApiName:p.objectApiName,id:ke(g.Id),...h!==void 0?{name:h}:{}})}return{objects:e,heldBy:t,users:r,queues:n,recordTypes:s,profiles:a,notHeld:d,currencies:i,standardPricebook:Nf(o,u,t),fileLinks:c,filesLeft:f}}function Nf(o,e,t){let r=o.checkpoint.objects.some(i=>i.objectApiName===fo||i.objectApiName===qe);if(po(o.annex,"standardPricebook")&&o.annex.standardPricebookId)return{id:ke(o.annex.standardPricebookId),how:"annex"};let n=e.filter(i=>t.has(i.product));if(n.length===0||!r)return{how:"none"};let s=new Set(n.map(i=>`${i.product}|${i.currency}`)),a=new Map;for(let i of n){let u=a.get(i.book)??new Set;u.add(`${i.product}|${i.currency}`),a.set(i.book,u)}let d=[...a].filter(([,i])=>i.size===s.size).map(([i])=>i);return d.length===1?{id:ke(d[0]),how:"deduced"}:{how:"ambiguous"}}function Zr(o,e){let t=[];for(let r=0;r<o.length;r+=e)t.push(o.slice(r,r+e));return t}function uo(o){return o.map(e=>`'${Me(e)}'`).join(", ")}function dl(o){let e=o.lastIndexOf("@"),t=o.lastIndexOf("."),r=o.slice(e+1);return e>=0&&t>e&&r.split(".").length>2?o.slice(0,t):o}function Cf(o){if(o===void 0)return;let e=dl(o);return e===o?void 0:o.slice(e.length)}async function zf(o){let{access:e,orgId:t,survey:r,source:n}=o,s=0,a=async I=>(s++,e.query(t,I)),d=new Map,i=new Map,u=async I=>{s++;try{d.set(I,await e.describe(t,I))}catch(P){i.set(I,X(P))}};for(let I of r.objects.replayed)await u(I.objectApiName);r.fileLinks.length>0&&await u(sr);let l=new Map,c=I=>typeof I.Id=="string"&&typeof I.Username=="string"?{id:ke(I.Id),username:I.Username,isActive:I.IsActive===!0,userType:typeof I.UserType=="string"?I.UserType:""}:void 0,f=[...new Set([...r.users,...Object.values(n.choices.ownerMap??{}).map(ce)])].sort();for(let I of Zr(f,Wt))for(let P of await a(`SELECT Id, Username, IsActive, UserType FROM User WHERE Id IN (${uo(I)})`)){let C=c(P);C&&l.set(ce(C.id),C)}let p=new Map;if(po(n.annex,"users")){let I=o.tier==="sandbox"?Cf(o.username):void 0,P=new Map;for(let D of n.annex.users){let W=ce(D.id),V=l.get(W);if(V?.isActive===!0&&V.userType==="Standard")continue;let H=n.checkpoint.org.tier==="sandbox"?dl(D.username):D.username,E=[D.username,H,...I!==void 0?[`${H}${I}`]:[]];P.set(W,[...new Set(E.map(q=>q.toLowerCase()))])}let C=[...new Set([...P.values()].flat())].sort(),G=new Map;for(let D of Zr(C,Wt)){let W=D.map(V=>`'${Me(V)}'`).join(", ");for(let V of await a(`SELECT Id, Username, IsActive, UserType FROM User WHERE Username IN (${W})`)){let H=c(V);H&&G.set(H.username.toLowerCase(),H)}}for(let[D,W]of P){let V=W.map(H=>G.get(H)).find(H=>H!==void 0);V&&p.set(D,V)}}let g=[],h=[...d.keys()].filter(I=>d.get(I)?.fields.some(P=>P.name===Ns));if(h.length>0){let I=cl(d),P=await a(`SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name, IsActive${I?", IsPersonType":""} FROM RecordType WHERE SobjectType IN (${h.map(C=>`'${ge(C)}'`).join(", ")})`);for(let C of P)typeof C.Id!="string"||typeof C.SobjectType!="string"||typeof C.DeveloperName!="string"||g.push({id:ke(C.Id),sobjectType:C.SobjectType,developerName:C.DeveloperName,...typeof C.NamespacePrefix=="string"&&C.NamespacePrefix!==""?{namespacePrefix:C.NamespacePrefix}:{},name:typeof C.Name=="string"?C.Name:C.DeveloperName,isActive:C.IsActive!==!1,...typeof C.IsPersonType=="boolean"?{isPersonType:C.IsPersonType}:{}})}let m=[];if(r.queues.size>0){let I=new Map;for(let P of await a("SELECT QueueId, SobjectType FROM QueueSobject"))typeof P.QueueId!="string"||typeof P.SobjectType!="string"||I.set(ce(P.QueueId),[...I.get(ce(P.QueueId))??[],P.SobjectType]);for(let P of await a("SELECT Id, DeveloperName FROM Group WHERE Type = 'Queue'"))typeof P.Id!="string"||typeof P.DeveloperName!="string"||m.push({id:ke(P.Id),developerName:P.DeveloperName,sobjectTypes:I.get(ce(P.Id))??[]})}let y;if([...d.values()].some(I=>I.fields.some(P=>P.name===Qr))&&r.currencies.size>0){y=new Set;for(let I of await a("SELECT IsoCode, IsActive FROM CurrencyType"))typeof I.IsoCode=="string"&&I.IsActive===!0&&y.add(I.IsoCode)}let L;if(r.standardPricebook.id!==void 0){let[I]=await a(Ct);typeof I?.Id=="string"&&(L=ke(I.Id))}let T=new Set,j=new Map;for(let[I,P]of r.heldBy){let C=j.get(P);C?C.push(I):j.set(P,[I])}let x=async(I,P)=>{let C=0;for(let G of Zr(P,Wt))for(let D of await a(`SELECT Id FROM ${ge(I)} WHERE Id IN (${uo(G)})`))typeof D.Id=="string"&&(T.add(ce(D.Id)),C++);return C},U=new Set(r.objects.replayed.map(I=>I.objectApiName));for(let[I,P]of j){if(i.has(I)||Ss(I))continue;let C=[...P].sort(),G=C.slice(0,Wt);try{await x(I,G)>0&&await x(I,C.slice(Wt))}catch(D){if(U.has(I))throw D}}let S=new Map;for(let[I,P]of r.notHeld){let[C,G]=I.split("."),D=d.get(C)?.fields.find(H=>H.name===G),W=D?.type==="reference"?D.referenceTo??[]:[];if(W.length!==1)continue;let V=S.get(W[0])??new Set;for(let H of P)V.add(H);S.set(W[0],V)}for(let[I,P]of S)try{await x(I,[...P].sort())}catch{}let w=new Map;for(let I of r.objects.replayed){if(I.customSetting===void 0||i.has(I.objectApiName))continue;let P={names:new Set,owners:new Set};for(let C of await a(`SELECT Id, Name, SetupOwnerId FROM ${ge(I.objectApiName)}`))typeof C.Name=="string"&&P.names.add(C.Name),typeof C.SetupOwnerId=="string"&&P.owners.add(ce(C.SetupOwnerId));w.set(I.objectApiName,P)}let v=new Set;for(let I of Zr([...r.profiles].sort(),Wt))for(let P of await a(`SELECT Id FROM Profile WHERE Id IN (${uo(I)})`))typeof P.Id=="string"&&v.add(ce(P.Id));let A=new Set,N=[...new Set(r.fileLinks.map(I=>ce(I.ContentDocumentId)))];if(!i.has(sr))for(let I of Zr(N.sort(),Wt))for(let P of await a(`SELECT Id FROM ContentDocument WHERE Id IN (${uo(I)})`))typeof P.Id=="string"&&A.add(ce(P.Id));return{organizationId:ke(o.organizationId),runningUserId:ke(o.runningUserId),describes:d,missing:i,usersById:l,usersByUsername:p,recordTypes:g,queues:m,...y!==void 0?{currencies:y}:{},...L!==void 0?{standardPricebookId:L}:{},sameIds:T,customSettings:w,profiles:v,files:A,requests:s}}function cl(o){return o.get("Account")?.fields.some(e=>e.name===Do)===!0}function Mf(o,e,t){let r=[...new Set(Object.values(o.ownerMap??{}).map(ce))].sort(),n=r.filter(a=>{let d=e.usersById.get(a);return d===void 0||d.userType!=="Standard"});if(n.length>0)return{code:"OWNER_MAP_UNKNOWN",users:n.map(ke),message:`The owners chosen give records to users ${t} does not hold as standard users: ${n.map(ke).join(", ")}. Choose users of ${t}. Nothing was written.`};let s=r.filter(a=>e.usersById.get(a)?.isActive!==!0);if(s.length>0)return{code:"OWNER_MAP_INACTIVE",users:s.map(ke),message:`The owners chosen give records to users ${t} holds inactive: ${s.map(ke).join(", ")}. It refuses a record owned by an inactive user: choose an active user, or reactivate them there. Nothing was written.`}}var Ut=class{constructor(e){this.id=e}id;counts=new Map;add(e,t=1){let r=this.id(e),n=this.counts.get(r);n?n.n+=t:this.counts.set(r,{key:e,n:t})}entries(){return[...this.counts.values()]}};function Df(o,e){return e.createable&&e.nillable===!1&&e.defaultedOnCreate!==!0||ea(o,e.name)}function xf(o){let e=o.length;return typeof e=="number"&&e>0?e:void 0}var $f=new Set(["id","reference","boolean","double","int","long","percent","currency","date","datetime","time","picklist","multipicklist"]);async function _f(o){let{survey:e,target:t,choices:r,annex:n}=o,s=Mf(r,t,o.targetName);if(s)return{refusal:s};let a=new Ut(k=>`${k.object}|${k.reason}`);for(let k of e.objects.leftOut)a.add({object:k.objectApiName,reason:k.reason},k.records);let d=e.objects.replayed.filter(k=>t.missing.has(k.objectApiName)?(a.add({object:k.objectApiName,reason:"notInTarget"},k.records),!1):t.describes.get(k.objectApiName)?.createable===!1?(a.add({object:k.objectApiName,reason:"notCreateable"},k.records),!1):!0),i=new Set(d.map(k=>k.objectApiName)),u=new Ut(k=>`${k.field}|${k.reason}`),l={kept:0,toRunningUser:0,reasons:{notInTarget:0,inactive:0,queueMissing:0}},c=new Ut(k=>`${k.object}|${k.recordType}|${k.outcome}`),f=new Ut(k=>k),p=new Map,g=!1,h={inserted:0,alreadyThere:0},m=new Map,y=new Map,R=cl(t.describes),L=new Set,T=e.standardPricebook,j=T.id!==void 0?ce(T.id):void 0,x=new Map(Object.entries(r.ownerMap??{}).map(([k,F])=>[ce(k),ke(F)])),U=k=>{let F=t.usersById.get(k);if(F?.userType==="Standard"&&F.isActive)return{id:F.id};let O=t.usersByUsername.get(k);return O?.userType==="Standard"&&O.isActive?{id:O.id}:{why:F!==void 0||O!==void 0?"inactive":"notInTarget"}},S=(k,F)=>{let O=Q=>Q.sobjectTypes.includes(k),J=t.queues.find(Q=>ce(Q.id)===F&&O(Q));if(J)return J.id;let ee=po(n,"queues")?n.queues.find(Q=>ce(Q.id)===F):void 0;if(ee!==void 0)return t.queues.find(Q=>Q.developerName===ee.developerName&&O(Q))?.id},w=(k,F,O)=>{let J=ce(F),ee=po(n,"recordTypes")?n.recordTypes.find(B=>ce(B.id)===J):void 0,Q=t.recordTypes.filter(B=>B.sobjectType===k&&B.isActive),me,te="default";if(ee!==void 0&&(me=Q.find(B=>B.developerName===ee.developerName&&(B.namespacePrefix??null)===(ee.namespacePrefix??null)),me&&(te="byName")),me===void 0&&(me=Q.find(B=>ce(B.id)===J),me&&(te="byId")),me===void 0&&O){let B=Q.filter(ie=>ie.isPersonType===!0);if(B.length!==1)return{refused:`the checkpoint does not say which of the person account record types of ${o.targetName} its person accounts had: take it again with SandForge 1.81 or later, or leave Account out`};me=B[0]}let Be={recordType:ee!==void 0?lt(ee.namespacePrefix,ee.developerName):ke(F),outcome:te};if(me===void 0)return{given:Be};let M=me,we=t.describes.get(k)?.recordTypeInfos?.find(B=>ce(B.recordTypeId)===ce(M.id));if(we!==void 0&&!we.available)return{refused:`${lt(M.namespacePrefix,M.developerName)} is not assigned to the user who replays in ${o.targetName}: assign it to them, or leave ${k} out`};let tt={name:M.name,developerName:M.developerName,namespacePrefix:M.namespacePrefix??null},rt=y.get(k)??new Map;return rt.set(M.id,tt),y.set(k,rt),{ref:tt,given:Be}},v=[];for(let k of d){let F=k.objectApiName,O=t.describes.get(F);if(O===void 0)continue;let J=new Map(O.fields.map(te=>[te.name,te])),ee=k.fields.filter(te=>!Fs.has(te)&&!J.has(te)&&!(te===Qr&&t.currencies===void 0));ee.length>0&&p.set(F,new Set(ee));let Q=k.customSetting,me=t.customSettings.get(F);for await(let te of Ls(o,F)){let Be=ce(te.Id);if(t.sameIds.has(Be)){m.set(nl(F,te.Id),ke(te.Id));continue}let M={objectApiName:F,key:Be,referenceId:nl(F,te.Id),fields:{},pointsAt:new Map,sourceId:ke(te.Id),emptied:[]},we=(B,ie)=>{M.refused??={reason:B,...ie!==void 0?{path:ie}:{}}},tt=(F==="Account"||F==="Contact")&&Or(te);tt&&!R&&we("personAccountsUnsupported",`turn person accounts on in ${o.targetName}, or leave ${F} out`),tt&&F==="Contact"&&L.add(Be);let rt=F==="Account"?vn(te,!1):void 0;for(let[B,ie]of Object.entries(te)){if(Fs.has(B)||rt!==void 0&&mn(F,B,rt))continue;let kt=J.get(B);if(kt===void 0){B===Qr&&typeof ie=="string"&&ie!==""&&(g||=t.currencies===void 0);continue}if(ie==null||ie==="")continue;if(B===Qr&&typeof ie=="string"){t.currencies!==void 0&&!t.currencies.has(ie)&&(we("inactiveCurrency",`activate ${ie} in ${o.targetName}, or leave ${F} out`),f.add(ie)),M.fields[B]=ie;continue}if(B===Ns&&typeof ie=="string"){let ye=w(F,ie,tt);ye.given!==void 0&&(M.recordType=ye.given),ye.refused!==void 0?we("recordTypeUnavailable",ye.refused):ye.ref!==void 0&&(M.fields[B]=ye.ref.name,M.recordTypeDeveloperName=lt(ye.ref.namespacePrefix,ye.ref.developerName));continue}if(kt.type!=="reference"||typeof ie!="string"||!sl.test(ie)){M.fields[B]=ie;continue}let fe=ce(ie),pt=Df(F,kt),nt=(ye,Ie)=>{pt?we("requiredLookupMissing",Ie):M.emptied.push({field:`${F}.${B}`,reason:ye})};if(fe.startsWith(al)){M.fields[B]=t.organizationId;continue}if(B===Es){(fe.startsWith(js)?t.profiles.has(fe):t.usersById.has(fe))?M.fields[B]=ke(ie):we("requiredLookupMissing",`the ${fe.startsWith(js)?"profile":"user"} its row is of is not in ${o.targetName}`);continue}if(B===il&&(fe.startsWith(Ps)||fe.startsWith(Ts))){let ye=x.get(fe);if(ye!==void 0)M.owner="kept",M.fields[B]=ye;else if(r.owners==="me")M.owner="toRunningUser";else if(fe.startsWith(Ts)){let Ie=S(F,fe);M.owner=Ie!==void 0?"kept":"queueMissing",Ie!==void 0&&(M.fields[B]=Ie)}else{let Ie=U(fe);M.owner=Ie.id!==void 0?"kept":Ie.why??"notInTarget",Ie.id!==void 0&&(M.fields[B]=Ie.id)}continue}if(fe.startsWith(Ps)){let ye=U(fe);ye.id!==void 0?M.fields[B]=ye.id:pt?M.fields[B]=t.runningUserId:M.emptied.push({field:`${F}.${B}`,reason:"userNotInTarget"});continue}if(j!==void 0&&fe===j){t.sameIds.has(fe)?M.fields[B]=ke(ie):i.has(fo)&&e.heldBy.has(fe)?M.pointsAt.set(B,fe):t.standardPricebookId!==void 0?M.fields[B]=t.standardPricebookId:nt("objectNotHeld",`${o.targetName} has no standard price book`);continue}let xe=e.heldBy.get(fe);xe!==void 0&&t.sameIds.has(fe)?M.fields[B]=ke(ie):xe!==void 0&&i.has(xe)?M.pointsAt.set(B,fe):xe!==void 0?nt("objectNotReplayed",`replay ${xe} too`):t.sameIds.has(fe)?M.fields[B]=ke(ie):nt("objectNotHeld",`the checkpoint holds no record it points at, and ${o.targetName} holds none under its Id`)}if(F===qe&&T.how==="ambiguous"&&we("requiredLookupMissing",`the checkpoint does not say which of its price books is the standard one, which every other price needs first: take it again with SandForge 1.81 or later, or leave ${qe} out`),Q!==void 0&&me!==void 0){let B=M.fields[Es];if(Q==="list"?typeof te.Name=="string"&&me.names.has(te.Name):typeof B=="string"&&me.owners.has(ce(B))){h.alreadyThere++;continue}}v.push(M)}}let A=new Map(v.map(k=>[k.key,k])),N=new Map;for(let k of v)for(let F of k.pointsAt.values()){let O=N.get(F);O?O.push(k):N.set(F,[k])}let I=v.filter(k=>k.refused!==void 0);for(let k=0;k<I.length;k++){let F=I[k];for(let O of N.get(F.key)??[])O.refused===void 0&&(O.refused={reason:"parentRefused",path:`its ${F.objectApiName} is refused: lift that first`},I.push(O))}let P=new Ut(k=>`${k.object}|${k.reason}`),C=new Map,G=[];for(let k of v){if(k.refused!==void 0){P.add({object:k.objectApiName,...k.refused});continue}for(let O of k.emptied)u.add(O);k.recordType!==void 0&&c.add({object:k.objectApiName,...k.recordType}),k.owner==="kept"?l.kept++:k.owner!==void 0&&(l.toRunningUser++,k.owner!=="toRunningUser"&&l.reasons[k.owner]++);for(let[O,J]of k.pointsAt){let ee=A.get(J);ee!==void 0&&ee.refused===void 0?k.fields[O]=ee.referenceId:u.add({field:`${k.objectApiName}.${O}`,reason:"objectNotReplayed"})}L.has(k.key)&&typeof k.fields.AccountId=="string"&&G.push({accountReferenceId:k.fields.AccountId,contactReferenceId:k.referenceId});let F=C.get(k.objectApiName)??[];F.push({referenceId:k.referenceId,fields:k.fields,...k.recordTypeDeveloperName!==void 0?{recordTypeDeveloperName:k.recordTypeDeveloperName}:{}}),C.set(k.objectApiName,F)}for(let k of d)k.customSetting!==void 0&&(h.inserted+=C.get(k.objectApiName)?.length??0);let D=t.describes.get(sr);if(D!==void 0&&D.createable!==!1){let k=[];for(let F of e.fileLinks){let O=A.get(ce(F.LinkedEntityId));O===void 0||O.refused!==void 0||t.files.has(ce(F.ContentDocumentId))&&k.push({referenceId:`${sr}-${ke(F.ContentDocumentId)}_${O.sourceId}`,fields:{ContentDocumentId:ke(F.ContentDocumentId),LinkedEntityId:O.referenceId,ShareType:F.ShareType,Visibility:F.Visibility}})}k.length>0&&C.set(sr,k)}let W=new ad(o.salt),V=r.mask?new ld(void 0,o.salt):void 0,H=r.mask?new jn:void 0,E=[],q=[];for(let[k,F]of C){let O=t.describes.get(k);if(O===void 0)continue;let J=new Set(F.flatMap(M=>Object.keys(M.fields))),ee=O.fields.filter(M=>J.has(M.name)).map(M=>{let we=xf(M);return{name:M.name,queryable:!0,createable:M.createable,isReference:M.type==="reference",type:M.type,...we!==void 0?{length:we}:{}}});if(r.contactPoints==="neutralized"){let M=W.forObject(k,ee);if(M)for(let we of F)M(we.fields)}if(V===void 0||H===void 0)continue;let Q=ee.filter(M=>!$f.has((M.type??"").toLowerCase())),me=new Set(Tn(H,Q.map(M=>({name:M.name,type:M.type??"string"})))),te=Q.filter(M=>me.has(M.name)).map(M=>({name:M.name,type:M.type??"string",...M.length!==void 0?{length:M.length}:{}}));for(let M of te)E.push(`${k}.${M.name}`);for(let M of Q)!me.has(M.name)&&(M.type??"").toLowerCase()==="textarea"&&q.push(`${k}.${M.name}`);if(te.length===0)continue;let Be=V.anonymize({objectApiName:k,records:F.map(M=>M.fields),sourceIds:F.map(M=>M.referenceId),fields:te,methods:{}});F.forEach((M,we)=>{M.fields=Be[we]??M.fields})}let Y={};for(let[k,F]of y)Y[k]=[...F.values()];let ae=[...C].map(([k,F])=>({objectApiName:k,records:F})),$=j!==void 0?A.get(j):void 0,K=$!==void 0&&$.refused===void 0&&$.objectApiName===fo?$.referenceId:void 0,Z={datasetVersion:"1.0.0",objects:ae,recordTypes:Y,personContactSidecar:G,...K!==void 0?{standardPricebook:K}:{}},ne=ae.reduce((k,F)=>k+F.records.length,0),he=e.objects.replayed.some(k=>k.objectApiName===fo||k.objectApiName===qe),_e=P.entries(),De={records:{toCreate:ne-(K!==void 0?1:0),linkedById:m.size,linkedByKey:0,refusedBeforeWrite:_e.reduce((k,F)=>k+F.n,0)},owners:l,recordTypes:c.entries().map(({key:k,n:F})=>({...k,records:F})).sort((k,F)=>ol(`${k.object}.${k.recordType}`,`${F.object}.${F.recordType}`)),notReplayed:a.entries().map(({key:k,n:F})=>({...k,records:F})),lookupsEmptied:u.entries().map(({key:k,n:F})=>({...k,records:F})).sort((k,F)=>ol(k.field,F.field)),refused:_e.map(({key:k,n:F})=>({object:k.object,records:F,reason:k.reason,...k.path!==void 0?{path:k.path}:{}})),fieldsNotInTarget:[...p].map(([k,F])=>({object:k,fields:[...F].sort()})),...e.objects.replayed.some(k=>k.customSetting!==void 0)?{customSettings:h}:{},currencies:{refused:f.entries().map(({key:k,n:F})=>({code:k,records:F})),...g?{singleCurrencyTarget:!0}:{}},...he?{standardPricebook:T.how}:{},masked:{fields:E.sort(),...r.mask?{unmaskedFreeText:q.sort()}:{}},contactPoints:r.contactPoints,degraded:Bf(n),auditDates:"new"};return{conversion:{dataset:Z,summary:De,identityKeys:Object.fromEntries(r.link.map(k=>[k.objectApiName,[...k.fields]])),linkedById:m,filesLeft:e.filesLeft}}}function Bf(o){return o===void 0?["recordTypes","users","queues","standardPricebook"]:[...new Set(o.unread.map(e=>e.part))]}function ol(o,e){return o<e?-1:o>e?1:0}async function ll(o){let e={folder:o.folder,checkpoint:o.checkpoint,annex:o.annex,choices:o.choices},t=await Lf(e),r=await zf({...o,source:e,survey:t});return{...await _f({...e,survey:t,target:r,targetName:o.targetName,...o.salt!==void 0?{salt:o.salt}:{}}),target:r,survey:t}}var Gf={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.")}},Wf=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"]),go="REPLACE_LEAVES_RECORDS",gr=class extends Error{constructor(t){super(t.message);this.stop=t;this.name="RemovalStopped"}stop;get code(){return this.stop.code}},hr=class extends Error{constructor(t,r,n,s){super(r);this.code=t;this.emails=n;this.orgId=s;this.name="LoadEmailsStop"}code;emails;orgId},rn=class extends Error{constructor(t,r,n,s){super(r);this.code=t;this.automation=n;this.orgId=s;this.name="LoadAutomationStop"}code;automation;orgId},nn=class extends Error{constructor(t,r,n){super(t);this.apiRequests=r;this.orgId=n;this.name="LoadBudgetStop"}apiRequests;orgId;code=_o},Tl="FROZEN_STORAGE_EXCEEDED",on=class extends Error{constructor(t,r,n){super(t);this.storage=r;this.orgId=n;this.name="LoadStorageStop"}storage;orgId;code=Tl};function ho(o){let e=o<10?100:10;return String(o<=0?0:Math.ceil(o*e-1e-9)/e)}function ul(o){let e;return{request:t=>(e===void 0&&(e=Promise.resolve().then(()=>o.request(t)),e.catch(()=>{})),e)}}function fl(o){if("unread"in o.storage)return;let e=Math.max(0,o.automationBytes??0),t=jl(o.dataset,o.sent)+e,r=(o.purged??[]).filter(l=>l.deletes).reduce((l,c)=>l+xo(c.objectApiName,{rows:c.rows}),0),n=1024*1024,{remainingMB:s,maxMB:a}=o.storage;if(t<=s*n+r)return;let d={estimateMB:t/n,...e>0?{automationMB:e/n}:{},remainingMB:s,maxMB:a,...r>0?{freedMB:r/n}:{}},i=d.freedMB!==void 0?`, and the reload's purge frees about ${ho(d.freedMB)} MB first`:"",u=d.automationMB!==void 0?`, about ${ho(d.automationMB)} MB of it for what the target's automation creates under them`:"";return o.replay===!0?{storage:d,message:`The replay was refused before it wrote anything: the checkpoint's records take about ${ho(d.estimateMB)} MB of data storage${u}, and ${o.target} has ${s} MB left of ${a} MB${i}. To replay part of it, ${Xr.fewerObjects}; or free data storage in ${o.target}. Nothing was written.`}:{storage:d,message:`The load was refused before it wrote anything: the dataset's records take about ${ho(d.estimateMB)} MB of data storage${u}, and ${o.target} has ${s} MB left of ${a} MB${i}. 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 ${o.target}. Nothing was written.`}}var Uf=Ge({sobjects:mt(Ge({name:Ce().min(1),createable:cn().optional()}).loose())}).loose();function jl(o,e){return o.objects.reduce((t,r)=>{if(e!==void 0&&!e.takes(r.objectApiName))return t;let n=e===void 0?r.records.length:r.records.filter(s=>!e.byThePlatform.has(s.referenceId)).length;return t+xo(r.objectApiName,{rows:n})},0)}function pl(o,e,t,r){if(!("objects"in o))return 0;let n=nd(zt(o,e,r),r),s=new Map(t.objects.map(a=>[a.objectApiName,a.records.length]));return od(n,a=>s.get(a)??0)}function Kf(o){return{estimateMB:o.estimateMB,...o.automationMB!==void 0?{automationMB:o.automationMB}:{},remainingMB:o.remainingMB,maxMB:o.maxMB,...o.freedMB!==void 0?{freedMB:o.freedMB}:{}}}function gl(o,e,t){if(t!==!0)return o;try{return ls(o,e.rootObject)}catch{return o}}function hl(o){return o?{replay:o}:{}}function Vf(o,e){let t=0;for(let r of o.perObject){let n=r.reused-(r.writtenByThePlatform??0),s=e.standardPricebook!==void 0&&r.objectApiName==="Pricebook2"&&n>0?1:0;t+=n-s}return t}function Hf(o,e){let t=_i(o,e);return{verdict:o.verdict,estimate:o.estimate,...o.verdict==="unread"?{unread:o.unread}:{remaining:o.remaining,max:o.max},...o.parts?{parts:{...o.parts}}:{},...t!==void 0?{refused:{code:_o,message:t}}:{}}}function en(o,e){let t=[...new Set(o.map(r=>r.objectApiName))];return aa({setToDraft:ri(t),delete:si(t)},e)}function Cs(o){return o.status==="success"&&(o.left??[]).length===0}function ml(o){return o.verdict!=="nothingSends"||o.counted.length>0||o.uncounted!==void 0}function Yf(o,e){if(e.includeChanged||o.refusal!==void 0||o.status!=="partial"&&o.status!=="failure")return o;let t=o.objects.every(s=>s.refused===0&&s.deleted+s.alreadyGone+s.keptChanged===s.found),r=(o.left??[]).some(s=>s.class==="late"&&e.sweepLate||s.class==="untied"&&e.sweepUntied),n=o.objects.some(s=>s.keptChanged>0);return t&&!r&&n?{...o,status:"success"}:o}var tn="frozen",yl="frozen:config",pr="frozen:lastRun",wl="frozen:lastRuns",zs="frozen:lastVerify",Ms="frozen:lastVerifies",bl="tokens.json",Jf="rules.json",mr=class extends Error{constructor(t,r){super(r);this.rulesPath=t;this.name="RulesFileMissingError"}rulesPath},Xf=async o=>{let e=await import("vscode");await e.window.showTextDocument(e.Uri.file(o),{preview:!1})},Zf="0.1.0",Qf=10*6e4,Ds=15*6e4,ep="EXTRACT_TIMEOUT",Rl=30*6e4,xs=6e4,kl=12e4,tp=50;function rp(o,e){let t=0,r=null,n=null,s=d=>{o(...d),t=Date.now(),r=null},a=((...d)=>{r=d;let i=e-(Date.now()-t);i<=0?(n&&(clearTimeout(n),n=null),s(d)):n||(n=setTimeout(()=>{n=null,r&&s(r)},i))});return a.flush=()=>{n&&(clearTimeout(n),n=null),r&&s(r)},a}function vl(o,e){let t=rp(o,e);return Object.assign(n=>{if(n.status==="started"){t(n);return}t.flush(),o(n)},{flush:t.flush})}async function et(o){try{return await Se.access(o),!0}catch{return!1}}function np(o){return o.check==="clear-empty"?'residual value under "clear" generator (value redacted at the bridge)':o.detail.length>200?`${o.detail.slice(0,200)}\u2026`:o.detail}function El(o){return{passed:o.passed,author:o.author,checkedAt:o.checkedAt,checks:o.checks.map(e=>({name:e.name,passed:e.passed,violations:e.violations.slice(0,tp).map(t=>({check:t.check,objectApiName:t.objectApiName,referenceId:t.referenceId,field:t.field,detail:np(t)}))}))}}function $s(o){return{version:o.version,status:o.status,frozenAt:o.frozenAt,source:o.source,saltFingerprint:o.saltFingerprint,rulesVersion:o.rulesVersion,volumetry:o.volumetry,controls:{nonReidentification:El(o.controls.nonReidentification),dryRunLoad:o.controls.dryRunLoad,author:o.controls.author,date:o.controls.date},...o.coverage?{coverage:o.coverage}:{}}}function op(o,e,t){return{combinations:o.roots.map(r=>({combinationKey:r.combinationKey,axisValues:r.axisValues,edgeCase:r.edgeCase})),uncovered:o.uncovered,volumetry:o.volumetry,selectedAt:o.selectedAt,selectionPath:e,...t?{graph:t}:{},...o.stopped?{stopped:o.stopped}:{}}}function _s(o,e){if(!e||e.length===0)return o;let t=new Set(e);return{...o,nodes:o.nodes.map(r=>t.has(r.objectApiName)?{...r,included:!1}:r)}}function Il(o,e){return{objects:o.nodes.filter(Ni).length,truncated:o.truncated===!0,maxNodes:e}}function sp(o){return o.length===0?"":` Kept in the org, the platform does not delete them: ${o.map(({objectApiName:t,count:r})=>`${t} (${r})`).join(", ")}.`}function Bs(o,e){if(!o)return{message:"No load into this org was recorded in this sas: there is nothing to remove.",code:"NO_LOAD"};if(o.orgId!==e.targetOrgId||o.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(!o.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(st(o).length>0)return;let t=sp(Bn(o));return o.removal?{message:`The records this load created were already removed, on ${o.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 qs(o){let e=o.writtenBetween,t=o.startedAt===void 0?Number.NaN:Date.parse(o.startedAt),r=Date.parse(o.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:o.removalStamps,removalSpans:o.removalSpans,...o.runUserId?{runUserId:o.runUserId}:{}}}function ap(o,e=!1){let t=new Map;for(let{objects:r}of o)for(let n of r){let s=n.heldByAutomation??0,a=(n.keptDependents??0)-(e?s:0),d=n.heldBy&&n.heldBy.length>0?n.heldBy.join(", "):"",i=[n.keptChanged>0?`${n.keptChanged} changed since the load`:"",a>0?(d?`${a} kept for records that stay under them (${d})`:`${a} kept as what hangs from them could not be read`)+(!e&&s>0?`, ${s} 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),u=n.keptChanged+Math.max(0,a)+n.undeletable+n.notVisible+n.unread;if(u===0)continue;let l=t.get(n.objectApiName)??{left:0,why:new Set};l.left+=u;for(let c of i)l.why.add(c);t.set(n.objectApiName,l)}return[...t].map(([r,{left:n,why:s}])=>({objectApiName:r,left:n,why:[...s]}))}function ip(o){return{status:o.status,orgId:o.orgId,mode:o.mode,startedAt:o.startedAt,durationMs:o.durationMs,alignment:{excludedObjects:o.alignment.excludedObjects,removals:o.alignment.removals,adjustments:o.alignment.adjustments,recordTypeIssues:o.alignment.recordTypeIssues},placeholders:o.placeholders,requiredDefaults:o.requiredDefaults,perObject:o.perObject,pass2:o.pass2,personContact:o.personContact,statuses:o.statuses,purge:o.purge,...o.leftToThePlatform?{leftToThePlatform:o.leftToThePlatform}:{},...o.untypedFeedItems?{untypedFeedItems:o.untypedFeedItems}:{},...o.heldForExcludedParents?{heldForExcludedParents:o.heldForExcludedParents}:{},...o.quotesLeftUnsynced?{quotesLeftUnsynced:o.quotesLeftUnsynced}:{},...o.keysLeftEmpty?{keysLeftEmpty:o.keysLeftEmpty}:{},...o.recordTypesGiven?{recordTypesGiven:o.recordTypesGiven}:{},...o.runUserId?{runUserId:o.runUserId}:{},mappingPath:o.mappingPath,contractPath:o.contractPath}}function dp(o){return o.status==="completed"?"success":o.perObject.reduce((t,r)=>t+r.inserted+r.reused,0)>0?"partial":"failure"}function cp(o){let e=o.perObject.reduce((t,r)=>t+r.failed.length,0)+o.purge.failures.length;return wo(o)===0&&e===0?"stopped":"cancelled"}function wo(o){let e=t=>Object.values(t).reduce((r,n)=>r+n,0);return o.perObject.reduce((t,r)=>t+r.inserted,0)+o.placeholders.length+e(o.purge.deleted)+e(o.purge.deactivated)}function Ol(o){return`frozen:${o}`}var mo=(o,e)=>e==="insert"||e==="update",Kt=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointFirstStop"}code};function Gs(o){let e=new Map,t=r=>{let n=e.get(r)??Ca(r);return e.set(r,n),n};for(let r of o.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 o.placeholders)t(r.placeholderObjectApiName).created+=1;for(let[r,n]of Object.entries(o.purge.deleted))t(r).deleted+=n;for(let[r,n]of Object.entries(o.purge.deactivated))t(r).updated+=n;for(let r of o.purge.failures)t(r.objectApiName).failed+=1;return[...e.values()]}async function lp(o,e){try{let t=await e.load();return Object.fromEntries(o.objects.map(r=>[r.objectApiName,r.records.filter(n=>t.has(n.referenceId)).length]))}catch{return}}var it=class extends Error{constructor(t,r,n={}){super(r);this.code=t;this.params=n;this.name="ReplayRefused"}code;params},Ws=class extends qn{constructor(t,r,n){super(t,r);this.registeredAs=n}registeredAs;async recorded(){let t=await super.recorded();return t&&{...t,orgId:this.registeredAs}}async recordedLoads(){return(await super.recordedLoads()).map(t=>({...t,orgId:this.registeredAs}))}};function up(){let o=vi();return{checkpoints:()=>[o,Sd(o)].flatMap(e=>{if(!qf(e))return[];let t=Ii({root:e});return"store"in t?[t.store]:[]}),replays:new Nd({root:Ld()})}}function Sl(o,e){let t=Object.fromEntries((e?.link??[]).map(n=>[n.objectApiName,[...n.fields]])),r={...o?.identityKeys,...t};return{rootObject:"",axes:[],edgeCases:[],...o,...Object.keys(r).length>0?{identityKeys:r}:{}}}function yo(o){return o.replay?{module:"checkpoint",sasMark:Zn(o.replay.folder.dir)}:{module:"frozen"}}function fp(o){return o.replay?{action:"checkpoint_replay",module:"checkpoint"}:{action:"frozen_load",module:"frozen"}}var Al=class{constructor(e){this.deps=e}deps;registry;liveTracker;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;saltKeeper=pc();openInEditor=Xf;otherModuleRuns=()=>Promise.resolve([]);removing=new Set;writing=new hi;loading=new Map;beforeRunCheckpoints;describeCache=new Go({defaultTtl:5*6e4,maxSize:2e3,maxSizeBytes:200*1024*1024,releaseExpired:!0});describeGlobalCache=new Go({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-DIL62SUN.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>Ae(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!==Ol(r)))return!0;return!1}async loadingDuring(e,t){let r=Fn(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(!Wf.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(Fn(e,"targetOrgId"),()=>this.handleRemove(e)),!0;case"frozen:remove:sweep":return await this.writing.during(Fn(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(yl)??null}handleConfigGet(e){let t=this.loadConfig(),r=Oe(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=ot(Wa,e,"frozen:config:save:error",this.deps);if(!t)return;this.deps.configStore.set(yl,t.config,tn);let r=Oe(this.deps,e,"frozen:config:save:response",{success:!0});this.deps.broker.postToWebview(r)}resolveSasDir(e){return e?.sasDir??Pe.join(Pl.homedir(),".sandforge-sas")}resolveDatasetDir(e){return e?.datasetDir??Pe.join(this.resolveSasDir(e),"dataset")}resolveRulesPath(e){return Pe.resolve(e?.rulesFilePath??Pe.join(this.resolveSasDir(e),Jf))}async rulesFileInfo(e){let t=this.resolveRulesPath(e),r=null;try{r=await et(t)?await Se.readFile(t,"utf8"):null}catch(n){return{path:t,found:!0,invalid:X(n)}}return{path:t,...jc(r)}}async loadTokens(e,t){return await et(Pe.join(e,bl))?Dc(e,bl,t):{}}async describeObject(e,t){let r=`${e}::${t}`,n=this.describeCache.get(r);if(n)return n;let s=await new Pt(3e4).withTimeout(`frozen:describe:${t}`,async()=>{let d=await(await Ae(e,this.deps.orgRegistry,this.deps.orgManager)).describe(t);return{name:d.name,fields:d.fields.map(i=>({name:i.name,label:i.label,type:i.type,referenceTo:i.referenceTo??[],relationshipName:i.relationshipName??null,isMasterDetail:i.cascadeDelete===!0,nillable:i.nillable!==!1,createable:i.createable!==!1,updateable:i.updateable!==!1,restrictedPicklist:i.restrictedPicklist===!0,defaultedOnCreate:i.defaultedOnCreate===!0,...i.compoundFieldName?{compoundFieldName:i.compoundFieldName}:{}})),childRelationships:(d.childRelationships??[]).map(i=>({childSObject:i.childSObject,field:i.field,relationshipName:i.relationshipName??i.field,isCascadeDelete:i.cascadeDelete===!0}))}},3e4);return this.describeCache.set(r,s),s}buildDiscoveryService(){return new Ci({describeObject:(e,t)=>this.describeObject(e,t),queryCount:async(e,t)=>(await(await Ae(e,this.deps.orgRegistry,this.deps.orgManager)).query(t)).totalSize,detectPII:e=>{let t=this.deps.infraServices?.piiDetector;return t?Tn(t,e):[]},describeGlobal:e=>this.describeGlobal(e)})}async describeGlobal(e){let t=this.describeGlobalCache.get(e);if(t)return t;let s=(await(await Ae(e,this.deps.orgRegistry,this.deps.orgManager)).describeGlobal()).sobjects.map(a=>({name:a.name,keyPrefix:a.keyPrefix??null}));return this.describeGlobalCache.set(e,s),s}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??Li}}async graphOfStep(e){let{sourceOrgId:t,config:r,sasDir:n,guard:s}=e,{maxNodes:a}=this.discoveryOptions(r),d={sourceOrgId:t,rootObject:r.rootObject,maxNodes:a},i=await qc(n,s),u;if("kept"in i){let p=i.kept,g=Gc(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}};u=g}else u=i.none;let l;try{let p=await Ae(t,this.deps.orgRegistry,this.deps.orgManager);l=Wc((await p.soap.getServerTimestamp()).timestamp)}catch(p){this.deps.log(`[WARN] frozen: the source did not give its clock: ${String(p)}`)}let c=await this.buildDiscoveryService().discover(this.discoveryConfig(t,e.rootRecordId),{maxNodes:a,...e.signal?{signal:e.signal}:{},...e.onProgress?{onProgress:e.onProgress}:{}}),f=new Date().toISOString();return{graph:c,origin:{rediscovered:u},keep:async p=>{let g=new Set([...c.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 Bc(n,{fileVersion:1,...d,step:e.step,discoveredAt:f,...l?{schemaStamp:l}:{},graph:c,describes:h,objects:this.describeGlobalCache.get(t)??[]},s)}}}async schemaChangeSince(e,t){if(!t.schemaStamp)return"the graph kept carries no stamp of the org";try{let n=await(await Ae(e,this.deps.orgRegistry,this.deps.orgManager)).request({method:"GET",url:"/sobjects",headers:{"If-Modified-Since":new Date(t.schemaStamp).toUTCString()}}),s=typeof n=="object"&&n!==null?n.sobjects:void 0;return Array.isArray(s)?(this.forgetOrg(e),this.describeGlobalCache.set(e,s.flatMap(a=>{let{name:d,keyPrefix:i}=a??{};return typeof d=="string"?[{name:d,keyPrefix:typeof i=="string"?i: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: ${X(r)}`}}holdKeptDescribes(e,t){for(let[r,n]of Object.entries(t.describes))this.describeCache.set(`${e}::${r}`,n,Rl);t.objects.length>0&&this.describeGlobalCache.set(e,t.objects,Rl)}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 s=await this.describeObject(e,n);r.set(n,s.fields)}catch(s){this.deps.log(`[WARN] frozen: ${n} could not be described for the rules: ${String(s)}`)}return r}mappingStoreFor(e,t,r){let n=async()=>{try{let[s]=await this.buildTargetOrgAccess().query(t,"SELECT Id FROM Organization");return typeof s?.Id=="string"?s.Id:void 0}catch(s){this.deps.log(`[WARN] frozen: the target did not say which org it is: ${String(s)}`);return}};return new qn(e,{orgId:t,organizationId:n,guard:r})}buildTargetOrgAccess(){return{query:async(e,t)=>{let r=await Ae(e,this.deps.orgRegistry,this.deps.orgManager);return On(r,t)},count:async(e,t)=>(await(await Ae(e,this.deps.orgRegistry,this.deps.orgManager)).query(t)).totalSize,describe:async(e,t)=>{let n=await(await Ae(e,this.deps.orgRegistry,this.deps.orgManager)).describe(t);return{name:n.name,createable:n.createable,cascadeChildren:(n.childRelationships??[]).flatMap(s=>s.cascadeDelete===!0&&typeof s.field=="string"&&s.field!==""?[{childSObject:s.childSObject,field:s.field}]:[]),fields:n.fields.map(s=>({name:s.name,type:s.type,createable:s.createable??!1,nillable:s.nillable??!0,defaultedOnCreate:s.defaultedOnCreate??!1,referenceTo:s.referenceTo??[],restrictedPicklist:s.restrictedPicklist??!1,picklistValues:(s.picklistValues??[]).map(a=>({value:a.value,active:a.active??!0})),updateable:s.updateable!==!1,unique:s.unique===!0,nameField:s.nameField===!0,...typeof s.filteredLookupInfo=="object"&&s.filteredLookupInfo!==null?{lookupFilter:{optional:s.filteredLookupInfo.optionalFilter===!0}}:{}})),recordTypeInfos:(n.recordTypeInfos??[]).flatMap(s=>{let{developerName:a,active:d}=s;return a?[{developerName:a,recordTypeId:s.recordTypeId,available:s.available,name:s.name,master:s.master,defaultRecordTypeMapping:s.defaultRecordTypeMapping,...d===void 0?{}:{active:d}}]:[]})}},picklistValues:async(e,t,r,n)=>{let s=await Ae(e,this.deps.orgRegistry,this.deps.orgManager);return fd(s,t,r,n)},userId:async e=>(await(await Ae(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(Pe.join(r,"manifest.json"));if(!await et(n))throw new Error(`No frozen dataset found at ${r} \u2014 run a selection (frozen:select) then an extraction (frozen:extract) first.`);let s=ir(JSON.parse(await Se.readFile(n,"utf8"))),a=[],d=t.assertOutsideRepo(Pe.join(r,"data"));if(await et(d))for(let f of(await Se.readdir(d)).sort()){if(!f.endsWith(".json"))continue;let p=t.assertOutsideRepo(Pe.join(d,f)),g=JSON.parse(await Se.readFile(p,"utf8"));a.push({objectApiName:g.objectApiName,records:g.records})}let i=async(f,p)=>{let g=t.assertOutsideRepo(Pe.join(r,f));return await et(g)?JSON.parse(await Se.readFile(g,"utf8")):p},u=await i("record-types.json",{}),l=await i("personcontact-sidecar.json",[]),c=await i(Lr,{});return{dataset:{datasetVersion:s.version,objects:a,recordTypes:u,personContactSidecar:l,...c.standardPricebook?{standardPricebook:c.standardPricebook}:{}},manifest:s}}errorCodeFor(e,t){return e instanceof mr?"RULES_MISSING":e instanceof He?"GUARD_REFUSED":e instanceof Ad?"SAS_PATH_REFUSED":e instanceof Er?"SALT_MISSING":e instanceof Bt?"BUDGET_EXCEEDED":e instanceof Qe?"LOAD_CONFIG":e instanceof xr?"MAX_RECORDS":e instanceof cr?go:e instanceof ut?"TIMEOUT":e instanceof it?e.code:e instanceof Co&&e.code==="invalid"?"INVALID_PAYLOAD":t}errorDetailOf(e){if(e instanceof it)return{params:e.params};if(e instanceof mr)return{rulesPath:e.rulesPath};if(e instanceof He)return{guard:e.code,...e.params};if(e instanceof Bt)return{total:e.total,budgetMax:e.budgetMax,heaviest:e.heaviest};if(e instanceof Qe&&e.gaps)return{gaps:e.gaps,...(e.refusedBeside??[]).length>0?{refusedBeside:e.refusedBeside}:{}};if(e instanceof Qe&&e.recordTypesUntold)return{recordTypesUntold:e.recordTypesUntold};if(e instanceof hr)return{emails:e.emails,orgId:e.orgId};if(e instanceof rn)return{automation:e.automation,orgId:e.orgId};if(e instanceof nn)return{apiRequests:e.apiRequests,orgId:e.orgId};if(e instanceof on)return{storage:e.storage,orgId:e.orgId}}loadEmailsFor(e){return wc({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:()=>Wi(e.conn),readDeliverability:()=>e.orgTier==="production"?Promise.resolve(mi):yi(e.conn),accepted:e.accepted,target:this.orgNameOf(e.orgId),mayMute:e.mayMute})}async loadApiCheck(e){let t=await xi(e.conn).catch(s=>({unread:X(s)})),r=ud(e.read),n=$i({run:Jc({inserts:e.dataset.objects.map(s=>({objectApiName:s.objectApiName,rows:s.records.length})),...e.purged?{purged:e.purged}:{},threshold:Ao(this.deps).bulk.threshold,...r?{duplicateRules:r}:{},automationRead:Ji(e.read)})+(e.replayReads??0),...Bi(e.checkpoint),...bi(e.plan),...Xi(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})`),Hf(n,this.orgNameOf(e.orgId))}async purgedOf(e,t){if(await e.isStale())return[];let r=t.undeletableObjects??{};return(await e.recordedLoads()).flatMap(n=>st(n)).map(({objectApiName:n,ids:s})=>({objectApiName:n,rows:s.length,deletes:!Object.hasOwn(r,n)}))}orgNameOf(e){let t=this.deps.orgManager.getOrg(e);return oa(t,e)}requireConfig(e,t){let r=this.loadConfig();return r||(re(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)}setReplayStores(e){this.replayStores=e}replayStores;replayStoresInUse(){return this.replayStores??=up(),this.replayStores}async sourceOf(e,t,r,n,s){if(t.replay===void 0){let a=this.requireConfig(e,r);return a?this.datasetSource(a,t.targetOrgId):void 0}try{if(t.pilot===!0)throw new it("REPLAY_NO_PILOT","A replay loads no pilot: preview it, then replay it whole. Nothing was read or written.");return await this.replaySourceOf(t.targetOrgId,t.replay,n)}catch(a){let d=this.errorCodeFor(a,"REPLAY_ERROR");s?.(d);let i=this.errorDetailOf(a);re(this.deps,e.type,r,e,a,{code:d,retryable:a instanceof ut,...i?{extraPayload:i}:{}});return}}datasetSource(e,t){let r=n=>n.assertOutsideRepo(this.resolveSasDir(e));return{config:e,sasDir:r,mappingStore:n=>this.mappingStoreFor(r(n),t,n),read:async n=>{let s=n.assertOutsideRepo(this.resolveDatasetDir(e)),{dataset:a,manifest:d}=await this.readFrozenDataset(s,n);return{dataset:a,manifest:d,datasetDir:s,label:d.version}}}}async replaySourceOf(e,t,r){ts({orgId:e,orgTier:this.targetTier(e)});let n=this.replayStoresInUse(),s=n.replays.folderOf(t.organizationId,t.checkpointId),a=await this.replayTargetOf(e),d=Nn(a.organizationId),i={folder:s,target:a,contractPath:n.replays.contractPathOf(s,d)},u=g=>new Ws(s.dir,{guard:g,orgId:d,organizationId:a.organizationId},e);if(r==="mapping")return{config:Sl(t.config,void 0),sasDir:()=>s.dir,mappingStore:u,read:()=>Promise.reject(new Error("A removal of a replay reads no checkpoint")),replay:i};let l=await this.replayedCheckpointOf(n,t),c=t.choices??(await n.replays.read(s))?.targets.find(g=>g.organizationId===d)?.choices;if(c===void 0)throw new it("NO_LOAD",`No replay of checkpoint ${t.checkpointId} into ${a.name} is recorded on this machine: replay it there first, then verify. Nothing was read or written.`,{checkpoint:t.checkpointId,target:a.name});let f=tl({checkpoint:l.checkpoint,checkpointId:t.checkpointId,choices:c,target:a});if(f)throw new it(f.code,f.message,f.params);if(l.checkpoint===void 0)throw new it("REPLAY_CHECKPOINT_UNUSABLE","The checkpoint does not read.");let p=l.checkpoint;return i.checkpoint={checkpoint:p,folder:l.folder,annex:l.annex},i.choices=c,{config:Sl(t.config,c),sasDir:()=>s.dir,mappingStore:u,read:async()=>(i.converted??=await this.convertReplay(i,c,e),{dataset:i.converted.conversion.dataset,label:p.name}),replay:i}}async replayedCheckpointOf(e,t){for(let r of e.checkpoints()){let n=(await r.checkpointsOf(t.organizationId)).find(s=>s.folder.checkpointId===t.checkpointId);if(n!==void 0){if(n.checkpoint===void 0)return{folder:n.folder,annex:void 0};try{return{checkpoint:n.checkpoint,folder:n.folder,annex:await Di(n.folder)}}catch(s){throw s instanceof Co?new it("REPLAY_CHECKPOINT_UNUSABLE",`${s.message}: what checkpoint '${n.checkpoint.name}' says of its record types, users and catalogue cannot be told. Nothing was read or written.`,{checkpoint:n.checkpoint.name,why:"damaged"}):s}}}throw new it("CHECKPOINT_NOT_FOUND",`No checkpoint ${t.checkpointId} of org ${t.organizationId} is kept on this machine: import its file first, or name one the checkpoint list shows. Nothing was read or written.`,{checkpoint:t.checkpointId})}async replayTargetOf(e){let t=this.buildTargetOrgAccess(),r=this.orgNameOf(e),[n]=await t.query(e,"SELECT Id FROM Organization");if(typeof n?.Id!="string")throw new Error(`${r} did not say which org it is: nothing was read or written.`);let s=n.Id,a=await t.userId?.(e);if(a===void 0)throw new Error(`${r} did not say which user the replay writes as.`);let d=this.deps.orgManager.getOrg(e),i=this.deps.sandboxRefreshes,u=[d?.orgId,i?.organizationIdOf(e),...i?.refreshesOf(e).map(l=>l.previousOrganizationId)??[]].filter(l=>typeof l=="string"&&l.slice(0,15)!==s.slice(0,15));return{name:r,organizationId:s,runningUserId:a,...d?.username?{username:d.username}:{},...d?.instanceUrl?{instanceUrl:d.instanceUrl}:{},formerOrganizationIds:[...new Set(u)],tier:d?.orgType==="Sandbox"?"sandbox":d?.orgType==="Scratch"?"scratch":"developer"}}async convertReplay(e,t,r){let n=e.checkpoint;if(n===void 0)throw new Error("The checkpoint of the replay was not read");let s=await ll({folder:n.folder,checkpoint:n.checkpoint,annex:n.annex,choices:t,access:this.buildTargetOrgAccess(),orgId:r,organizationId:e.target.organizationId,runningUserId:e.target.runningUserId,tier:e.target.tier,...e.target.username!==void 0?{username:e.target.username}:{},targetName:e.target.name});if("refusal"in s)throw new it(s.refusal.code,s.refusal.message,{users:s.refusal.users.join(", ")});return{conversion:s.conversion,target:s.target}}replayInfoOf(e,t,r){let n=e.checkpoint,s=e.converted;if(n===void 0||s===void 0||e.choices===void 0)return;let{checkpoint:a}=n,{summary:d,filesLeft:i}=s.conversion;return{checkpoint:{checkpointId:a.checkpointId,name:a.name,organizationId:a.org.organizationId,...a.org.alias!==void 0?{alias:a.org.alias}:{},takenAt:a.takenAt,tier:a.org.tier,annex:n.annex!==void 0},target:{organizationId:Nn(e.target.organizationId),name:e.target.name},choices:e.choices,summary:{...d,records:{...d.records,toCreate:Math.max(0,d.records.toCreate-t),linkedByKey:t}},filesLeft:i.map(({objectApiName:u,name:l})=>({objectApiName:u,...l!==void 0?{name:l}:{}})),...r?{storage:r}:{},requests:s.target.requests}}async loadSentOf(e,t){let r;try{r=await e.request({method:"GET",url:"/sobjects"})}catch{return}let n=Uf.safeParse(r);if(!n.success)return;let s=new Set(n.data.sobjects.filter(a=>a.createable!==!1).map(a=>a.name.toLowerCase()));return{takes:a=>s.has(a.toLowerCase()),byThePlatform:ac(t)}}async loadStorageOf(e){let t=await $o(e.conn).catch(()=>{});if(t===void 0)return;let r=Math.max(0,e.automationBytes??0),n=fl({dataset:e.dataset,storage:t,...e.sent?{sent:e.sent}:{},...e.purged?{purged:e.purged}:{},automationBytes:r,target:this.orgNameOf(e.targetOrgId),...e.replay===!0?{replay:!0}:{}}),s=1024*1024;return{estimateMB:n?.storage.estimateMB??(jl(e.dataset,e.sent)+r)/s,...r>0?{automationMB:r/s}:{},remainingMB:t.remainingMB,maxMB:t.maxMB,...n?.storage.freedMB!==void 0?{freedMB:n.storage.freedMB}:{},...n?{refusal:{code:Tl,message:n.message}}:{}}}async handleSelect(e){let t=ot(Ua,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()}`;Sr(this.deps,n,"frozen","Running coverage-matrix selection");let s="Coverage-matrix selection",a=new AbortController,d=setTimeout(()=>a.abort("timeout"),Qf),i=()=>{},u=new Promise((c,f)=>{i=p=>p===void 0?c():f(p)});u.catch(()=>{}),this.registry?.register(e.id,"frozen",s,u,a),this.liveTracker?.register(e.id,"frozen",s);let l=c=>{this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:select:progress",{...c})),c.phase==="combination"&&c.index!==void 0&&c.of&&this.liveTracker?.updateProgress(e.id,Math.round((c.index-1)/c.of*100),c.index-1,c.of,c.combinationKey??"")};try{let c=new de,f=c.assertOutsideRepo(this.resolveSasDir(r)),p=await Ae(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),g=new Map,h=async D=>{let W=g.get(D);return W||(W=On(p,D),g.set(D,W),W.catch(()=>g.delete(D))),(await W).map(V=>({...V}))},m=await this.loadTokens(f,c),y=this.discoveryOptions(r),R=new Set,L=new Hr({query:h,describeFields:D=>(R.add(D),this.describeScopableFields(t.sourceOrgId,D)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),T=new Date().toISOString(),j,x=0,U=async D=>(j??=this.graphOfStep({step:"select",sourceOrgId:t.sourceOrgId,config:r,sasDir:f,guard:c,rootRecordId:D,signal:a.signal,onProgress:W=>{W.phase==="object"&&(W.discoveredCount-x<10&&W.queueRemaining>0||(x=W.discoveredCount,l({phase:"discovery",objects:W.discoveredCount})))}}),_s((await j).graph,r.excludedObjects)),S=async D=>{if(D.length===0)return{};let W=await U(D[0]),V=await L.extract({graph:W,rootObject:r.rootObject,rootRecordIds:D,asOf:T,sasDir:f,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:m,guard:c}),H={};for(let E of V.objects)H[E.objectApiName]=E.records.length;return H},w=new to(S,r.expectedObjects??[]),v=async(D,W)=>(await this.describeObject(t.sourceOrgId,D)).fields.find(V=>V.name.toLowerCase()===W.toLowerCase())?.type,N=await new eo({query:h,checkHealth:w,measureVolumetry:S,fieldType:v}).select({rootObject:r.rootObject,axes:r.axes,edgeCases:r.edgeCases,budgetMaxRecords:r.budgetMaxRecords,candidatesPerCombination:r.candidatesPerCombination,tokens:m},{signal:a.signal,onProgress:l}),I=await $c(f,N,c),P=j&&!N.stopped?await j.catch(()=>{}):void 0;P?.keep&&await P.keep(R).catch(D=>{this.deps.log(`[WARN] frozen: the graph could not be kept in the sas: ${String(D)}`)});let C=P?_s(P.graph,r.excludedObjects):void 0,G=Oe(this.deps,e,"frozen:select:response",{selection:{...op(N,I,C?Il(C,y.maxNodes):void 0),...P?{discovery:P.origin}:{}}});this.deps.broker.postToWebview(G),bt(this.deps,n,{roots:N.roots.length,total:N.volumetry.total,...N.stopped?{stopped:N.stopped.reason}:{}}),N.stopped?.reason==="cancelled"?this.liveTracker?.cancel(e.id):this.liveTracker?.complete(e.id),i()}catch(c){this.liveTracker?.fail(e.id,X(c)),i(c),re(this.deps,"frozen:select","frozen:select:error",e,c,{code:this.errorCodeFor(c,"SELECT_ERROR"),retryable:c instanceof ut,extraPayload:this.errorDetailOf(c)})}finally{clearTimeout(d)}}async handleExtract(e){let t=ot(Va,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()}`;Sr(this.deps,n,"frozen","Extracting + pseudonymizing dataset");try{let s=new de,a=s.assertOutsideRepo(this.resolveSasDir(r)),d=s.assertOutsideRepo(this.resolveDatasetDir(r)),i=await this.saltKeeper.forExtraction(),u=new Mn(i.salt);if(i.created&&this.sayTheSaltWasMade(u.saltFingerprint),!await et(Pe.join(a,Kr))){re(this.deps,"frozen:extract","frozen:extract:error",e,new Error(`No selection found in ${a} \u2014 run the coverage-matrix selection first (frozen:select).`),{code:"SELECTION_MISSING"});return}let l=await ys(a,s),c=l.roots.map(V=>V.rootRecordId);if(c.length===0){re(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 f=await this.loadTokens(a,s),p=this.resolveRulesPath(r);if(!await et(p))throw new mr(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=Qn(JSON.parse(await Se.readFile(p,"utf8"))),h=await Ae(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),m=this.discoveryOptions(r),y=await this.graphOfStep({step:"extract",sourceOrgId:t.sourceOrgId,config:r,sasDir:a,guard:s,rootRecordId:c[0]}),R=_s(y.graph,r.excludedObjects),L=new Set,T,j=new Hr({query:V=>T?.aborted?Promise.reject(new Error("The extraction ran out of time and stopped.")):On(h,V),describeFields:V=>(L.add(V),this.describeScopableFields(t.sourceOrgId,V)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),x=t.author??"sandforge",U=r.datasetVersion??Zf,{extracted:S,frozen:w,report:v,requiredLeftEmpty:A,keptUnruled:N}=await new Pt(Ds).withTimeout("frozen:extract",async V=>{T=V;let H=await j.extract({graph:R,rootObject:r.rootObject,rootRecordIds:c,asOf:new Date().toISOString(),sasDir:a,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:f,guard:s}),E=await this.ruleSchemaOf(t.sourceOrgId,H.objects),q=Ec(g,E,this.deps.infraServices?.piiDetector??new jn),Y=new oo().anonymize({extracted:H,rules:q,pseudonymizer:u,datasetVersion:U}),ae=new so().run(H,Y,q,{author:x});return{extracted:H,frozen:Y,report:ae,requiredLeftEmpty:Lc(H,q,E),keptUnruled:Fc(H,q)}});A.length>0&&this.deps.log(`[WARN] frozen: the rules leave ${A.length} required field(s) empty, which a load will ask a value for: ${A.join(", ")}`),y.keep&&await y.keep(L).catch(V=>{this.deps.log(`[WARN] frozen: the graph could not be kept in the sas: ${String(V)}`)});let I=Oe(this.deps,e,"frozen:control:result",{report:El(v)});if(this.deps.broker.postToWebview(I),!v.passed){re(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 P={};for(let V of w.objects)P[V.objectApiName]=V.records.length;let C=this.deps.orgManager.getOrg(t.sourceOrgId),G=zd({version:U,source:{orgId:t.sourceOrgId,orgAlias:C?.alias,decisionDate:l.selectedAt},saltFingerprint:u.saltFingerprint,rulesVersion:g.rulesVersion,volumetry:{budgetMax:l.volumetry.budgetMax,measured:P,measuredAt:new Date().toISOString()},nonReidentification:v,author:x,coverage:{...Il(R,m.maxNodes),unboundedObjects:S.unboundedObjects,filesLeftOut:w.filesLeftOut??[],...(S.leftToThePlatform??[]).length>0?{leftToThePlatform:Gn(S.leftToThePlatform??[])}:{},...S.exclusionCosts?{exclusionCosts:S.exclusionCosts}:{},...A.length>0?{requiredLeftEmpty:A}:{},...N.length>0?{keptWithoutARule:N}:{},encryptedNotKept:S.encryptedNotKept??[]}}),D=await new Un(s).write(d,w,G,v),W=Oe(this.deps,e,"frozen:extract:response",{datasetDir:D.dir,files:D.files,recordCount:dr(w),manifest:$s(G),discovery:y.origin});this.deps.broker.postToWebview(W),bt(this.deps,n,{records:dr(w),version:G.version})}catch(s){let a=s instanceof ut,d=a?new Error(`The extraction ran out of its ${Ds/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.`):s;re(this.deps,"frozen:extract","frozen:extract:error",e,d,{code:a?ep:this.errorCodeFor(s,"EXTRACT_ERROR"),retryable:!1,extraPayload:a?{minutes:Ds/6e4}:this.errorDetailOf(s)})}}async handleRulesClear(e){let t=ot(Ka,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 et(n))throw new mr(n,`Pseudonymization rules file not found at ${n} \u2014 nothing was written. Create it, or set rulesFilePath in the configuration.`);let s=Nc(JSON.parse(await Se.readFile(n,"utf8")),t.fields);if(s.cleared.length>0){let d=`${n}.${process.pid}.writing`;await Se.writeFile(d,`${JSON.stringify(s.payload,null,2)}
22
+ `,"utf8"),await Se.rename(d,n),this.deps.log(`[INFO] frozen: ${s.cleared.length} field(s) given a clear rule in ${n} (rules ${s.rulesVersion}): ${s.cleared.join(", ")}`)}let a=Oe(this.deps,e,"frozen:rules:clear:response",{rulesPath:n,rulesVersion:s.rulesVersion,cleared:s.cleared,alreadyRuled:s.alreadyRuled});this.deps.broker.postToWebview(a)}catch(n){re(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 Se.mkdir(Pe.dirname(t),{recursive:!0});try{await Se.writeFile(t,Pc(Tc),{encoding:"utf8",flag:"wx"}),r=!0,this.deps.log(`[INFO] frozen: empty rules file written at ${t}`)}catch(s){if(s.code!=="EEXIST")throw s;if(!(await Se.stat(t)).isFile())throw new Error(`${t} is not a file: no rules file can be written there.`)}}catch(s){re(this.deps,"frozen:rules:create","frozen:rules:create:error",e,s,{code:"RULES_CREATE_ERROR"});return}let n=!1;try{await this.openInEditor(t),n=!0}catch(s){this.deps.log(`[WARN] frozen: rules file not opened: ${X(s)}`)}this.deps.broker.postToWebview(Oe(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 de().assertOutsideRepo(Pe.join(r,"manifest.json"));await et(d)&&(n=$s(ir(JSON.parse(await Se.readFile(d,"utf8")))))}catch(a){St.warn(`frozen:manifest:get \u2014 unreadable manifest: ${String(a)}`)}let s=Oe(this.deps,e,"frozen:manifest:get:response",{manifest:n,datasetDir:r});this.deps.broker.postToWebview(s)}targetTier(e){let t=this.deps.orgManager.getOrg(e);return hn(t)}async handleLoad(e){let t=ot(Fo,e,"frozen:load:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:load:error","checkpoint",E=>Xe(this.deps,{action:"checkpoint_replay",module:"checkpoint",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:E}));if(!r)return;let{config:n}=r,s=fp(r),a=r.replay,d=this.deps.infraServices?.productionGuard;if(!d){Xe(this.deps,{...s,operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:At.code}),re(this.deps,"frozen:load","frozen:load:error",e,new Error(At.message),{code:At.code});return}let i=await this.replaceRefusal(t,r),u=i&&"error"in i?i:void 0,l=i&&"cameAlong"in i?i.cameAlong:void 0;if(u){u.code===go&&Xe(this.deps,{...s,operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:go}),re(this.deps,"frozen:load","frozen:load:error",e,u.error,{code:u.code,retryable:u.retryable});return}let c=e.id,f=a?`Replaying checkpoint '${a.checkpoint?.checkpoint.name??""}'`:t.pilot?"Pilot load (one root folder)":"Loading frozen dataset";Sr(this.deps,c,s.module,f),this.liveTracker?.register(c,s.module,f);let p=!1,g=!1,h=new AbortController,m=()=>{},y=new Promise((E,q)=>{m=Y=>Y===void 0?E():q(Y)});y.catch(()=>{}),this.registry?.register(c,s.module,f,y,h);let R=vl(E=>{let q=Oe(this.deps,e,"frozen:load:progress",{...E});this.deps.broker.postToWebview(q),!p&&!g&&this.liveTracker?.updateProgress(c,E.progress,0,0,E.message)},100),L,T=!1,j=!1,x,U=new Date().toISOString(),S,w,v,A,N,I=(E,q,Y,ae)=>{if(j)return;j=!0;let $=E!=="stopped"&&S!==void 0,K=v?ki(Ri(v.run.gate,v.info.accepted&&v.info.verdict==="asks").emails):{},Z=a?.checkpoint&&a.choices?{replayCheckpoint:a.checkpoint.checkpoint.checkpointId,...rl(a.checkpoint.checkpoint,a.choices,a.target)}:{},ne={...$?{sas:S,startedAt:U,...w?{lastWriteAt:w}:{}}:{},...K,...Z};Xe(this.deps,{...s,operationId:c,orgId:t.targetOrgId,outcome:E,guard:L,objects:q,source:{origin:a?"checkpoint":"dataset",label:x},carried:Y,...ae?{code:ae}:{},...P?{muted:wn(P)}:{},...G?.state==="taken"?{checkpointId:G.checkpointId}:{},...Object.keys(ne).length>0?{details:ne}:{}})},P,C,G,D=!1,W=!1,V=!1,H=[];try{let E=new de,q=r.sasDir(E);S=Zn(q);let{dataset:Y,manifest:ae,datasetDir:$,label:K}=await r.read(E);x=K;let Z=this.buildTargetOrgAccess(),ne=await Ae(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),he=Ao(this.deps),_e=Ma(this.deps),De=z=>new Id({connection:ne,bulkExecutor:new ei(he.bulk.threshold),bulkManager:_e,retryConfig:he.retry,...z?{signal:z}:{},onProgress:()=>{},log:se=>this.deps.log(se)}),k=De(h.signal),F=n.mockDetection?new Cr(Z,n.mockDetection):{areCalloutsMocked:async()=>!0},O=r.mappingStore(E),J=xt(ne,"frozen:load"),ee=new $r({orgAccess:Z,writer:Os(k),restoringWriter:Os(De(void 0)),guard:d,mockDetector:F,recordTypeResolver:new Yr(Z),mappingStore:O,config:this.toLoadConfig(n),sasGuard:E,serverTime:()=>J.serverTime()});if(t.sweep===!0&&t.reload===!0&&!t.pilot){H=await this.reloadSweepsOf({conn:ne,store:O,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,includeChanged:t.includeChanged===!0,signal:h.signal,guard:d,operationId:c,audit:yo(r)});for(let{sweep:z}of H)await z.ask()}let Q=en([],H.flatMap(({sweep:z})=>z.takes)),me=(Q.delete??[]).length>0?this.removalAsker:void 0,te=Y.objects.map(z=>z.objectApiName),Be=t.reload===!0&&!t.pilot?await this.purgeStepsOf(O,n):void 0,M=await this.targetAutomation.read(t.targetOrgId,[...new Set([...te,...Be?.delete??[],...Q.delete??[]])]).catch(z=>({unread:X(z)})),we=Be?vr(Be):void 0,tt=vr(Q),rt=(z,se)=>mo(z,se)||we?.(z,se)===!0||tt(z,se),B=t.muteAutomation===!0?await Pr(async()=>Ar(ne),M,{...this.muteLeases,writes:rt}):void 0;if(P=B?.muted,me&&!h.signal.aborted){let z=await me({read:M,steps:Q,mute:B});if(z)throw new gr(z)}let ie=this.targetTier(t.targetOrgId),kt=await ee.gateLoad({orgId:t.targetOrgId,orgTier:ie,dataset:Y,manifest:ae,reload:t.reload,pilot:t.pilot?{}:void 0,onProgress:z=>R(z),onGuardDecision:z=>{L=No(L,z)}}),fe=fs({read:M,...B?.plan?{plan:B.plan}:{},written:te,accepted:t.acceptAutomation===!0,target:this.orgNameOf(t.targetOrgId),mayMute:t.muteAutomation!==!0&&this.muteOffered});if(A=fe.info,fe.stop&&fe.info)throw new rn(fe.stop.code,fe.stop.message,fe.info,t.targetOrgId);let pt=t.acceptEmails===!0,nt=gl(Y,n,t.pilot),xe=await this.loadEmailsFor({conn:ne,orgId:t.targetOrgId,orgTier:ie,read:M,...B?.plan?{plan:B.plan}:{},writes:rt,dataset:nt,accepted:pt,mayMute:t.muteAutomation!==!0&&this.muteOffered});if(v=xe,xe.stop)throw new hr(xe.stop.code,xe.stop.message,xe.info,t.targetOrgId);let ye=t.checkpointFirst!==void 0?await this.scopeLoadCheckpoint({msg:e,orgId:t.targetOrgId,written:te,read:M,mute:B,request:t.checkpointFirst,replay:a!==void 0}):void 0,Ie=Be?await this.purgedOf(O,n):void 0,vt=Promise.resolve().then(()=>ne.request({method:"GET",url:"/limits"}));vt.catch(()=>{});let sn={request:()=>vt},bo=await $o(sn).catch(z=>({unread:X(z)})),an=t.pilot?void 0:await this.loadSentOf(ne,Y),Vt=t.pilot?void 0:fl({dataset:Y,storage:bo,...an?{sent:an}:{},...Ie?{purged:Ie}:{},automationBytes:pl(M,B?.plan,Y,rt),target:this.orgNameOf(t.targetOrgId),...a?{replay:!0}:{}});if(Vt)throw new on(Vt.message,Vt.storage,t.targetOrgId);if(N=await this.loadApiCheck({conn:sn,dataset:nt,...Ie?{purged:Ie}:{},read:M,...ye?{checkpoint:ye.estimate}:{},...B?.plan?{plan:B.plan}:{},emails:xe,orgId:t.targetOrgId,operation:`frozen:load ${c}`,...a?.converted?{replayReads:a.converted.target.requests}:{}}),N.refused)throw new nn(N.refused.message,N,t.targetOrgId);a?.checkpoint&&a.choices&&await this.replayStoresInUse().replays.record(a.checkpoint.checkpoint,{organizationId:a.target.organizationId,name:a.target.name},a.choices),ye&&(C=await this.takeLoadCheckpoint(ye,h.signal));let Ke=B?.prepared?await B.prepared.acquire(c):void 0;Ke&&(P=Ke.outcome,V=!0);let dt=Ke?xe.run.afterLease(Ke.outcome,pt):void 0;if(Ke&&dt)throw P=await Ke.release(),new hr(dt.code,dt.message,xe.info,t.targetOrgId);D=!0;let yr=()=>ee.load({orgId:t.targetOrgId,orgTier:ie,dataset:Y,manifest:ae,sasDir:q,reload:t.reload,pilot:t.pilot?{}:void 0,...t.writeEncrypted?{writeEncrypted:!0}:{},...t.maxRecords!==void 0?{maxRecords:t.maxRecords}:{},...a?{linkByKeys:!0,contractOrgId:Nn(a.target.organizationId)}:{},onProgress:z=>R(z),onGuardDecision:z=>{L=No(L,z),(z==="allowed"||z==="confirmed")&&(T=!0)},signal:h.signal,...Ke?{lease:{giveBack:()=>Ke.release()}}:{},...H.length>0?{purgeSweep:{first:async()=>{for(let{sweep:z}of H)await z.first()},afterPurge:async()=>{for(let{sweep:z}of H)await z.afterRemoval()},stillToSweep:()=>H.filter(({sweep:z})=>!Cs(z.result())).map(({loadedAt:z})=>z)}}:{}}),$e=await(kt==="confirmed"?pi({approved:!0},yr):yr()).finally(async()=>{Ke&&(P=await Ke.release())});W=!0,R.flush();let Ht=await this.settleReloadSweeps(H),br=Ht.some(z=>z.result.status!=="success");C&&(G=await this.settleCheckpoint(C,wo($e)>0)),w=gc(await O.recorded().catch(()=>{}),U);let It=$!==void 0?Pe.join($,"manifest.json"):void 0;g=!0;let Ft=await this.verifyLoad({orgId:t.targetOrgId,contractPath:$e.contractPath,...It!==void 0?{manifestPath:It}:{},dataset:Y,mappingStore:O,config:n,onProgress:R}),Rr="verdict"in Ft?Ft.verdict.status:void 0,Yt=Rr==="failed"||Rr==="partial"?Rr:void 0,Jt=$e.status==="completed"&&(br||Yt!==void 0)?"partial":$e.status,kr=dp($e);if(I(Yt!==void 0&&kr==="success"?"partial":kr,Gs($e),await lp(Y,O)),$!==void 0&&It!==void 0){let z={contractPath:$e.contractPath,datasetDir:$,manifestPath:It,targetOrgId:t.targetOrgId,status:Jt,at:new Date().toISOString()};this.recordLastRun(z)}let Lt=ip($e),b=Object.fromEntries(Object.entries(l??{}).filter(([z])=>(Lt.purge.deleted[z]??0)>0)),_=Oe(this.deps,e,"frozen:load:response",{report:{...Lt,...Object.keys(b).length>0?{purge:{...Lt.purge,cameAlong:b}}:{},status:Jt,...Yt?{verification:Yt}:{},...P?{mutedAutomation:P}:{},...G?{checkpoint:G}:{},...Ht.length>0?{sweeps:Ht}:{},...v&&ml(v.info)?{emails:v.info}:{},...A?{automation:A}:{},...N?{apiRequests:N}:{}},...a?hl(this.replayInfoOf(a,Vf($e,Y))):{}});this.deps.broker.postToWebview(_),bt(this.deps,c,{status:Jt}),p=!0,Jt!=="completed"?this.liveTracker?.partial(c):this.liveTracker?.complete(c),this.postVerification(e,Ft),m()}catch(E){R.flush();let q=await this.settleReloadSweeps(H).catch(()=>[]),Y=q.length>0?{sweeps:q}:{};if(C&&G===void 0){let O=E instanceof at||E instanceof _t?E.written:void 0;G=await this.settleCheckpoint(C,O?wo(O)>0:D&&!Ln(E))}let ae=G?{checkpoint:G}:{},$=V&&P?{mutedAutomation:P}:{};if(E instanceof Kt){I("stopped",void 0,void 0,E.code),re(this.deps,"frozen:load","frozen:load:error",e,E,{code:E.code,...E.code==="LOAD_CANCELLED"?{extraPayload:{written:0}}:{}}),E.code==="LOAD_CANCELLED"?(this.registry?.abort(c),bt(this.deps,c,{aborted:!0}),this.liveTracker?.cancel(c),m()):(Po(this.deps,c,E.message,!0),this.liveTracker?.fail(c,E.message),m(E));return}if(E instanceof at){let O=cp(E.written);I(O,Gs(E.written),void 0,O==="stopped"?"LOAD_CANCELLED":void 0),this.registry?.abort(c),bt(this.deps,c,{aborted:!0}),this.liveTracker?.cancel(c),re(this.deps,"frozen:load","frozen:load:error",e,E,{code:"LOAD_CANCELLED",extraPayload:{written:wo(E.written),...ae,...Y,...$}}),m();return}let K=Ln(E)||E instanceof it||E instanceof gr||E instanceof hr||E instanceof rn||E instanceof nn||E instanceof on?E:void 0,Z=K!==void 0||(L==="refused"||L==="declined")&&!T,ne=E instanceof _t?E:void 0,he=ne?ne.cause:E,_e=K?.code??this.errorCodeFor(he,"LOAD_ERROR"),De=ne===void 0&&!W&&!T;I(Z||De?"stopped":"failure",ne?Gs(ne.written):void 0,void 0,K?.code??(De?_e:void 0));let F={...ne&&he instanceof He?{guard:he.code}:this.errorDetailOf(he),...ae,...Y,...$,...De?{written:0}:{}};re(this.deps,"frozen:load","frozen:load:error",e,E,{code:_e,retryable:he instanceof ut,extraPayload:Object.keys(F).length>0?F:void 0}),p||(Po(this.deps,c,X(E),!0),this.liveTracker?.fail(c,X(E))),m(E)}}loadCheckpointAsk(e){let{read:t}=e;return{module:e.replay===!0?"replay":"frozen",orgId:e.orgId,operationId:e.operationId,written:[...e.written],running:"objects"in t?zt(t,e.mute?.plan,mo):{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(a=>({unread:X(a)})),n=e.muteAutomation?await Pr(async()=>Ar(e.conn),r,{...this.muteLeases,writes:mo}).catch(a=>{St.warn(`Frozen preview: the mute could not be planned (${X(a)})`)}):void 0,s=this.loadCheckpointAsk({...e,operationId:e.msg.id,read:r,...n?{mute:n}:{}});return t.scope(s,{}).catch(a=>{St.warn(`Frozen preview: ${zn(a)}`)})}async scopeLoadCheckpoint(e){let t=this.beforeRunCheckpoints;if(!t)throw new Kt(jr,zn(new Error("SandForge's checkpoints are not set up in this window")));let r=this.loadCheckpointAsk({...e,operationId:e.msg.id}),n={operationId:Ol(e.msg.id)},s;try{s=await t.scope(r,n)}catch(d){throw new Kt(jr,zn(d))}let a=qi(s);if(a)throw new Kt(a.code,a.message);return{checkpoints:t,ask:r,own:n,estimate:s}}async takeLoadCheckpoint(e,t){let{checkpoints:r,ask:n,own:s,estimate:a}=e,d=await Gi(()=>r.take(n,s,{planned:a,signal:t}));if("stop"in d)throw new Kt(d.stop.code===jr?jr:"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 (${X(n)})`),e}}recordLastRun(e){this.moveOldVerify();let t={...this.lastRuns()},r=this.deps.configStore.get(pr);r&&t[r.targetOrgId]===void 0&&(t[r.targetOrgId]=r),t[e.targetOrgId]=e,this.deps.configStore.set(wl,t,tn),this.deps.configStore.set(pr,e,tn)}recordLastVerify(e,t){this.moveOldVerify(),this.deps.configStore.set(Ms,{...this.lastVerifies(),[e]:t},tn)}lastVerifies(){return this.deps.configStore.get(Ms)??{}}orgOfOldVerify(e){let t=this.deps.configStore.get(pr);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(zs);if(!e)return;let t=this.orgOfOldVerify(e),r=this.lastVerifies();t!==void 0&&r[t]===void 0&&this.deps.configStore.set(Ms,{...r,[t]:e},tn),this.deps.configStore.delete(zs)}lastVerifyInfos(){let e={...this.lastVerifies()},t=this.deps.configStore.get(zs),r=t?this.orgOfOldVerify(t):void 0;return t&&r!==void 0&&e[r]===void 0&&(e[r]=t),Object.entries(e).map(([n,s])=>({orgId:n,status:s.status,measuredAt:s.measuredAt}))}lastRuns(){return this.deps.configStore.get(wl)??{}}lastRunOf(e){let t=this.lastRuns()[e];if(t)return t;let r=this.deps.configStore.get(pr);return r?.targetOrgId===e?r:void 0}lastLoadInfos(){let e={...this.lastRuns()},t=this.deps.configStore.get(pr);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=ot(Fo,e,"frozen:load:preview:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:load:preview:error","checkpoint");if(!r)return;let{config:n,replay:s}=r,a=await this.replaceRefusal(t,r,t.goneFirst),d=a&&"error"in a?a:void 0;if(d){re(this.deps,"frozen:load:preview","frozen:load:preview:error",e,d.error,{code:d.code,retryable:d.retryable});return}try{let i=new de,u=r.sasDir(i),{dataset:l,manifest:c}=await r.read(i),f=this.buildTargetOrgAccess(),p=await Ae(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),g=xt(p,"frozen:load:preview"),m=await new $r({orgAccess:f,writer:Gf,guard:this.deps.infraServices?.productionGuard??new gi,mockDetector:n.mockDetection?new Cr(f,n.mockDetection):{areCalloutsMocked:async()=>!0},recordTypeResolver:new Yr(f),mappingStore:r.mappingStore(i),config:this.toLoadConfig(n),sasGuard:i,serverTime:()=>g.serverTime(),readValidationRules:async v=>{let{toolingQueriesOver:A,toolingValidationRules:N}=await import("./chunk-42BFLWHR.mjs"),{toolingRetrievesOver:I}=await import("./chunk-DIL62SUN.mjs"),P=p.tooling;return N(async C=>(await _a({query:async G=>P.query(G),queryMore:async G=>P.queryMore(G)},C)).records,A(p),I(p))(v)}}).planLoad({orgId:t.targetOrgId,orgTier:this.targetTier(t.targetOrgId),dataset:l,manifest:c,sasDir:u,reload:t.reload,pilot:t.pilot?{}:void 0,...t.writeEncrypted?{writeEncrypted:!0}:{},...s?{linkByKeys:!0}:{}}).catch(async v=>{throw v instanceof Qe&&v.gaps!==void 0&&(v.refusedBeside=await this.refusedBesideOf({conn:p,orgId:t.targetOrgId,dataset:l,store:r.mappingStore(i),config:n,parsed:t,...s?{replay:s}:{}}).catch(()=>[])),v}),y=t.checkpointFirst!==void 0?await this.previewCheckpoint({msg:e,orgId:t.targetOrgId,written:l.objects.map(v=>v.objectApiName),request:t.checkpointFirst,muteAutomation:t.muteAutomation===!0,conn:p,replay:s!==void 0}):void 0,R=r.mappingStore(i),L=ul(p),{emails:T,automation:j,apiRequests:x,automationBytes:U}=await this.previewWhatRuns({conn:p,limits:L,orgId:t.targetOrgId,dataset:l,store:R,config:n,parsed:t,...y?{checkpoint:y}:{},...s?.converted?{replayReads:s.converted.target.requests}:{}}),S=await this.previewStorageOf({conn:L,org:p,dataset:l,store:R,config:n,parsed:t,...U!==void 0?{automationBytes:U}:{},targetOrgId:t.targetOrgId,replay:s!==void 0}),w=s?this.replayInfoOf(s,m.perObject.reduce((v,A)=>v+A.reusedByKeys,0),S):void 0;this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:load:preview:response",{plan:{...m,...y?{checkpoint:y}:{},...T?{emails:T}:{},...j?{automation:j}:{},...x?{apiRequests:x}:{},...S&&!s?{storage:S}:{}},...hl(w)}))}catch(i){re(this.deps,"frozen:load:preview","frozen:load:preview:error",e,i,{code:this.errorCodeFor(i,"PREVIEW_ERROR"),retryable:i instanceof ut,extraPayload:this.errorDetailOf(i)})}}async refusedBesideOf(e){let{replay:t,...r}=e,n=ul(e.conn),{emails:s,automation:a,apiRequests:d,automationBytes:i}=await this.previewWhatRuns({...r,limits:n,...t?.converted?{replayReads:t.converted.target.requests}:{}}),u=await this.previewStorageOf({conn:n,org:e.conn,dataset:e.dataset,store:e.store,config:e.config,parsed:e.parsed,...i!==void 0?{automationBytes:i}:{},targetOrgId:e.orgId,replay:t!==void 0}),{orgId:l}=e,c=[];return a?.refused&&c.push({...a.refused,orgId:l,automation:a}),s?.refused&&c.push({...s.refused,orgId:l,emails:s}),u?.refusal&&c.push({...u.refusal,orgId:l,storage:Kf(u)}),d?.refused&&c.push({...d.refused,orgId:l,apiRequests:d}),c}async previewStorageOf(e){if(e.parsed.pilot===!0)return;let t=await this.loadSentOf(e.org,e.dataset);return this.loadStorageOf({conn:e.conn,dataset:e.dataset,...t?{sent:t}:{},...e.parsed.reload===!0?{purged:await this.purgedOf(e.store,e.config).catch(()=>[])}:{},...e.automationBytes!==void 0?{automationBytes:e.automationBytes}:{},targetOrgId:e.targetOrgId,replay:e.replay})}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?vr(r):void 0,s=(f,p)=>mo(f,p)||n?.(f,p)===!0,a=await this.targetAutomation.read(e.orgId,[...new Set([...e.dataset.objects.map(f=>f.objectApiName),...r?.delete??[]])]).catch(f=>({unread:X(f)})),d=t.muteAutomation===!0?await Pr(async()=>Ar(e.conn),a,{...this.muteLeases,writes:s}).catch(()=>{}):void 0,{info:i}=fs({read:a,...d?.plan?{plan:d.plan}:{},written:e.dataset.objects.map(f=>f.objectApiName),accepted:t.acceptAutomation===!0,target:this.orgNameOf(e.orgId),mayMute:t.muteAutomation!==!0&&this.muteOffered}),u=gl(e.dataset,e.config,t.pilot),l=await this.loadEmailsFor({conn:e.conn,orgId:e.orgId,orgTier:this.targetTier(e.orgId),read:a,...d?.plan?{plan:d.plan}:{},writes:s,dataset:u,accepted:t.acceptEmails===!0,mayMute:t.muteAutomation!==!0&&this.muteOffered}).catch(f=>{St.warn(`Frozen preview: the emails could not be judged (${X(f)})`)}),c=await this.loadApiCheck({conn:e.limits,dataset:u,...r?{purged:await this.purgedOf(e.store,e.config)}:{},read:a,...e.checkpoint?{checkpoint:e.checkpoint}:{},...d?.plan?{plan:d.plan}:{},...l?{emails:l}:{},orgId:e.orgId,operation:"frozen:load:preview",...e.replayReads!==void 0?{replayReads:e.replayReads}:{}}).catch(f=>{St.warn(`Frozen preview: the API requests could not be judged (${X(f)})`)});return{...l&&ml(l.info)?{emails:l.info}:{},...i?{automation:i}:{},...c?{apiRequests:c}:{},automationBytes:pl(a,d?.plan,e.dataset,s)}}catch(r){return St.warn(`Frozen preview: what the target runs could not be judged (${X(r)})`),{}}}async handleVerify(e){let t=ot(Ha,e,"frozen:verify:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:verify:error","checkpoint");if(!r)return;let{config:n,replay:s}=r,a=s?void 0:this.lastRunOf(t.targetOrgId);if(!s&&!a){re(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 d=vl(i=>{let u=Oe(this.deps,e,"frozen:load:progress",{...i});this.deps.broker.postToWebview(u)},100);try{let i=new de,u=a?.contractPath??s?.contractPath??"";if(s&&!await et(u)){re(this.deps,"frozen:verify","frozen:verify:error",e,new Error(`No replay of this checkpoint into ${s.target.name} wrote its counting contract on this machine: replay it there, then verify.`),{code:"NO_LOAD"});return}if(a){let g=i.assertOutsideRepo(this.resolveSasDir(n)),h=Pe.dirname(a.contractPath)!==Pe.dirname($n(i,g,t.targetOrgId)),m=await et(a.contractPath);if(h||!m){let y=Pe.dirname(a.contractPath),R;h?m?R=`The sas directory changed since the last load: its counting contract is in ${y}, and the mapping read is the one in ${g}. Set sasDir back to the sas the load wrote to, or load the dataset again, then verify.`:R=`The sas directory changed since the last load: the load wrote to ${y}, which no longer holds its counting contract, and the mapping read is the one in ${g}. Move the sas back to ${y} and set sasDir to it, or load the dataset again, then verify.`:R=`The sas changed since the last load: ${g} no longer holds the counting contract the last load wrote there. Load the dataset again, then verify.`,re(this.deps,"frozen:verify","frozen:verify:error",e,new Error(R),{code:"SAS_CHANGED",extraPayload:{sasDir:g,loadSas:y,sasMoved:h,contractThere:m}});return}}let l=r.mappingStore(i);if(await l.isStale()){re(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 c=await l.recorded(),f=c?.removal;if(c&&f){let g=st(c).reduce((h,m)=>h+m.ids.length,0);re(this.deps,"frozen:verify","frozen:verify:error",e,new Error(g>0?`The removal of ${f.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 ${f.removedAt}. Load the dataset again, then verify.`),{code:"LOAD_REMOVED",extraPayload:{left:g}});return}if(!c){re(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(!Td(_n(i,u),c)){re(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}=a?await this.readFrozenDataset(a.datasetDir,i):await r.read(i);await this.runVerification(e,{orgId:t.targetOrgId,contractPath:u,...a?{manifestPath:a.manifestPath}:{},dataset:p,mappingStore:l,config:n,onProgress:d})}catch(i){re(this.deps,"frozen:verify","frozen:verify:error",e,i,{code:this.errorCodeFor(i,"VERIFY_ERROR"),retryable:i instanceof ut})}}async runVerification(e,t){this.postVerification(e,await this.verifyLoad(t))}async verifyLoad(e){try{let t=new ao({orgAccess:this.buildTargetOrgAccess(),sasGuard:new de}),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,...e.manifestPath!==void 0?{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,s=Oe(this.deps,e,"frozen:verify:result",{verdict:n});this.deps.broker.postToWebview(s);return}let r=t.error;re(this.deps,"frozen:verify","frozen:verify:error",e,r,{code:this.errorCodeFor(r,"VERIFY_ERROR"),retryable:r instanceof ut})}async handleRemove(e){let t=ot(Ya,e,"frozen:remove:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:error","mapping");if(!r)return;let n=(p,g)=>this.refuseRemove(e,p,g),s,a,d;try{s=r.mappingStore(new de),a=await s.recordedLoads(),d=ar(a)}catch(p){re(this.deps,"frozen:remove","frozen:remove:error",e,p,{code:this.errorCodeFor(p,"REMOVE_ERROR")});return}let i=Bs(d,t),u=t.sweep===!0&&i?.code==="ALREADY_REMOVED";if(i&&!u||!d){i&&n(i.message,i.code);return}let l=st(d),c=s.filePath;if(this.removing.has(c)){n("The records of this load are being removed already.","DUPLICATE");return}this.removing.add(c);let f=this.registry?.holdUntilStart(e.id);try{await this.removeLoad(e,{store:s,load:d,plan:l,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?Vo(a,d):[],muteAutomation:t.muteAutomation===!0,pending:f,audit:yo(r)})}finally{this.removing.delete(c),f?.release()}}async handleRemoveAutomation(e){let t=ot(Xa,e,"frozen:remove:automation:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:automation:error","mapping");if(!r)return;let{config:n}=r;try{let s=r.mappingStore(new de),a,d;if(t.reload===!0)a=await this.purgeStepsOf(s,n,t.sweptObjects??[]),(t.sweptObjects??[]).length>0&&(d=await this.purgeStepsOf(s,n));else{let l=ar(await s.recordedLoads()),c=Bs(l,t),f=t.sweptObjects!==void 0&&c?.code==="ALREADY_REMOVED";if(c&&!f||!l){c&&re(this.deps,"frozen:remove:automation","frozen:remove:automation:error",e,new Error(c.message),{code:c.code});return}a=en(st(l),t.sweptObjects??[])}let i=this.targetAutomation,u=await new Pt(xs).withTimeout("frozen:remove:automation",()=>i.read(t.targetOrgId,a.delete??[]));this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:remove:automation:response",{loadedAt:t.loadedAt,automation:u,steps:a,...d?{purge:d}:{}}))}catch(s){re(this.deps,"frozen:remove:automation","frozen:remove:automation:error",e,s,{code:s instanceof ut?"TIMEOUT":this.errorCodeFor(s,"AUTOMATION_ERROR"),retryable:!0})}}async purgeStepsOf(e,t,r=[]){if(await e.isStale())return en([],[]);let n=t.undeletableObjects??{},s=(await e.recordedLoads()).flatMap(a=>st(a)).filter(({objectApiName:a})=>!Object.hasOwn(n,a));return en(s,r)}async handleRemovePreview(e){let t=ot(Za,e,"frozen:remove:preview:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:preview:error","mapping");if(!r)return;let n=(s,a,d=!1)=>re(this.deps,"frozen:remove:preview","frozen:remove:preview:error",e,s,{code:a,retryable:d});try{let s=r.mappingStore(new de),a=ar(await s.recordedLoads()),d=Bs(a,t);if(d||!a){d&&n(new Error(d.message),d.code);return}let i=st(a).reduce((c,f)=>c+f.ids.length,0),u=this.removalGuardRefusals(a.orgId,i),l;if(await s.isStale())u.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."}),l={...this.unreadPreviewOf(a,t.includeChanged===!0),planned:i};else{let c=await Ae(a.orgId,this.deps.orgRegistry,this.deps.orgManager);l=await this.previewRemovalOf(c,a,t.includeChanged===!0)}this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:remove:preview:response",{preview:{...l,refusals:u.map(({message:c})=>c),refusalCodes:u.map(({code:c})=>c)}}))}catch(s){n(s,this.errorCodeFor(s,"REMOVE_PREVIEW_ERROR"),!0)}}removalGuardRefusals(e,t){let r=this.deps.infraServices?.productionGuard;if(!r)return[{...At}];let n=this.targetTier(e),s=r.check({orgId:e,orgTier:n,operation:"delete",objectName:"the records a Frozen load created",recordCount:t,module:"frozen"});if(!s.allowed)return[{code:"GUARD_BLOCKED",message:`Operation blocked by Production Guard: ${s.blockedReason??s.impactSummary}`}];let a=r.declinedWithoutAsking(s,n);return a===void 0?[]:[{code:"GUARD_DECLINED",message:`Production Guard asks before this delete, and its question is answered no: ${a} (${s.impactSummary}). Nothing would be deleted.`}]}async previewRemovalOf(e,t,r){let n=st(t),s=await Pn(xt(e,"frozen:remove:preview"),n,{...qs(t),includeChanged:r,previewOnly:!0});if(!s.preview)throw new Error("The removal preview stopped before it was through.");return{...this.unreadPreviewOf(t,r),planned:n.reduce((a,d)=>a+d.ids.length,0),objects:s.preview.objects.map(a=>({objectApiName:a.objectApiName,planned:a.planned,toDelete:a.toDelete,alreadyGone:a.alreadyGone,changedSince:a.changedSince,keptChanged:a.keptChanged,changedBy:a.changedBy,undeletable:a.undeletable,notVisible:a.notVisible,unread:a.unread,reasons:a.reasons})),userNames:s.preview.userNames}}unreadPreviewOf(e,t){let r=Bn(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,s={};try{let a=t.mappingStore(new de),d=await a.recordedLoads();if(d.length===0||await a.isStale())return;if(d.some(i=>!i.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 i=await Ae(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),u=d.filter(p=>st(p).length>0),l=new Set([...u.flatMap(p=>st(p).flatMap(g=>g.ids.map(h=>h.slice(0,15)))),...r.map(p=>p.slice(0,15))]),c=[];for(let p of u){let g=await Pn(xt(i,"frozen:load:replace"),st(p),{...qs(p),includeChanged:!1,previewOnly:!0,previewHeld:!0,goesWithParent:h=>typeof h.Id=="string"&&l.has(h.Id.slice(0,15))});if(!g.preview)throw new Error("The removal preview stopped before it was through.");c.push(g.preview);for(let{objectApiName:h,cameAlong:m}of g.preview.objects){if(!m)continue;let y=s[h];s[h]={count:(y?.count??0)+m.count,objects:[...new Set([...y?.objects??[],...m.objects])]}}}let f=ap(c,e.sweep===!0);f.length>0&&(n=`A removal of the loads this reload replaces would leave ${f.reduce((g,h)=>g+h.left,0)} of their records in the org \u2014 ${f.map(g=>`${g.objectApiName} (${g.left}: ${g.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(a){return{error:a,code:this.errorCodeFor(a,"LOAD_ERROR"),retryable:!0}}return n!==void 0?{error:new Error(n),code:go,retryable:!1}:Object.keys(s).length>0?{cameAlong:s}:void 0}refuseRemove(e,t,r){re(this.deps,"frozen:remove","frozen:remove:error",e,new Error(t),{code:r})}async removeLoad(e,t){let{store:r,load:n,plan:s,includeChanged:a,sweep:d,pending:i}=t,u=t.audit??{module:"frozen"},l=n.orgId,c=s.reduce((A,N)=>A+N.ids.length,0),f=(A,N)=>this.refuseRemove(e,A,N),p=this.deps.infraServices?.productionGuard;if(!p){Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",code:At.code}),f(At.message,At.code);return}let{check:g,decision:h}=c>0?await En(p,{orgId:l,orgTier:this.targetTier(l),operation:"delete",objectName:s.map(A=>A.objectApiName).join(", "),recordCount:c,module:"frozen"}):{check:void 0,decision:"allowed"};if(g&&(h==="refused"||h==="declined")){Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",guard:h}),h==="refused"?f(`Operation blocked by Production Guard: ${g.blockedReason??g.impactSummary}`,"GUARD_BLOCKED"):re(this.deps,"frozen:remove","frozen:remove:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}let m=()=>{if(!i?.signal.aborted)return!1;Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",guard:h,code:Na});let A={status:"cancelled",includeChanged:a,objects:[],finishedAt:new Date().toISOString()};return this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:remove:response",{result:A,operationId:e.id})),!0};if(m())return;let y;try{y=await r.isStale()}catch(A){Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"failure",guard:h}),re(this.deps,"frozen:remove","frozen:remove:error",e,A,{code:this.errorCodeFor(A,"REMOVE_ERROR"),retryable:!0});return}if(y){Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",guard:h,code:"TARGET_REFRESHED"}),f("The target org was refreshed after the load: the records it created went with the refresh, and nothing is removed.","TARGET_REFRESHED");return}if(m())return;let R=e.id,L=c>0?`Removing ${c} record(s) a Frozen load created`:"Sweeping what the target's automation made for a Frozen load",T=new AbortController,j=()=>{},x=new Promise((A,N)=>{j=I=>I===void 0?A():N(I)});x.catch(()=>{}),Sr(this.deps,R,"frozen",L),this.registry?.register(R,"frozen",L,x,T),this.liveTracker?.register(R,"frozen",L,c);let U,S,w=[],v;try{let A=await Ae(l,this.deps.orgRegistry,this.deps.orgManager),N=new Set([n,...t.alongside].map(O=>O.endedAt));S=d?await this.sweepOfRemoval({conn:A,load:n,store:r,includeChanged:a,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,audit:u,signal:T.signal,guard:p,operationId:R,muted:()=>c===0?v:void 0,sweptWith:N}):void 0;for(let[O,J]of(S?t.alongside:[]).entries())w.push({loadedAt:J.endedAt,sweep:await this.sweepOfRemoval({conn:A,load:J,store:r,includeChanged:a,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,audit:u,signal:T.signal,guard:p,operationId:`${R}-${O+2}`,muted:()=>{},sweptWith:N})});let I=S,P=[...S?[S]:[],...w.map(({sweep:O})=>O)],C=async O=>{let J=!1;for(let ee of P)await O(ee)&&(J=!0);return J};for(let O of P)await O.ask();let G,D=this.removalAsker,W=en(s,P.flatMap(O=>O.takes));if((t.muteAutomation||D)&&!T.signal.aborted&&(W.delete??[]).length>0){let O=this.targetAutomation,J=await new Pt(xs).withTimeout("frozen:remove automation",()=>O.read(l,W.delete??[])).catch(Q=>({unread:X(Q)}));t.muteAutomation&&(G=await Pr(async()=>Ar(A),J,{...this.muteLeases,writes:vr(W)}));let ee=await D?.({read:J,steps:W,mute:G});if(ee)throw new gr(ee)}v=G?.muted;let V,H=async()=>{let O=G?.prepared;!O||T.signal.aborted||(V=await O.acquire(R),v=V.outcome)},q=await(c===0?(async()=>(await H(),await C(O=>O.first()),await C(O=>O.afterRemoval()),oi))():Pn(xt(A,"frozen:remove"),s,{...qs(n),...I?{sweep:O=>C(J=>J.first(O)),afterRemoval:O=>C(J=>J.afterRemoval(O)),automationMade:I.automationMade}:{},onUndeletable:za(this.deps,l,"frozen:remove"),beforeFirstWrite:H,includeChanged:a,signal:T.signal,onProgress:(O,J,ee)=>{let Q=Math.min(100,Math.round(O/Math.max(J,1)*100));xa(this.deps,R,Q,O,J,ee),T.signal.aborted||this.registry?.updateProgress(R,Q),this.liveTracker?.updateProgress(R,Q,O,J,ee)}})).finally(async()=>{V&&(v=await V.release())}),Y=await S?.settle(),ae=await this.settleReloadSweeps(w),$=n.removal?.removedAt,K=Bn(n),Z=ai(q.objects,q.cancelled),ne={status:ae.reduce((O,J)=>Lo(O,J.result),Lo(Z,Y)),includeChanged:a,objects:q.objects,finishedAt:new Date().toISOString(),...$?{leftBy:$}:{},...Y?{sweep:Y}:{},...ae.length>0?{otherLoadSweeps:ae}:{},...K.length>0?{keptByThePlatform:K}:{},...v?{mutedAutomation:v}:{}};c>0&&Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:R,orgId:l,outcome:ii({status:Z}),guard:h,objects:di(ne.objects),...$?{leftBy:$}:{},...v?{muted:wn(v)}:{}});let he=ci(ne,c,n.removal);(q.gone.length>0||Object.keys(q.stamps).length>0||q.span||he)&&(await r.recordRemoval(n.endedAt,{gone:q.gone,stamps:q.stamps,...q.span?{span:q.span}:{},...he?{mark:he}:{}})||this.deps.log("[WARN] frozen:remove: a load wrote its own mapping during the removal; the removal is not recorded in it"));let _e=[...Y&&Cs(Y)?[n.endedAt]:[],...ae.filter(O=>Cs(O.result)).map(O=>O.loadedAt)];await r.letSweptGo(_e).catch(()=>!1);let De=Oe(this.deps,e,"frozen:remove:response",{result:ne,operationId:R});this.deps.broker.postToWebview(De);let k=[Y,...ae.map(O=>O.result)].find(O=>O!==void 0&&O.status!=="success"),F=ne.status==="failure"?"No record this load created could be removed.":c===0&&k?k.refusal??"The sweep left records in the org.":void 0;ne.status==="cancelled"||Y?.status==="cancelled"||ae.some(O=>O.result.status==="cancelled")?(bt(this.deps,R,{aborted:!0}),this.liveTracker?.cancel(R)):(bt(this.deps,R,{status:F&&c===0?"failure":ne.status}),F?(U=new Error(F),this.liveTracker?.fail(R,F)):ne.status==="partial"?this.liveTracker?.partial(R):this.liveTracker?.complete(R))}catch(A){U=A,await S?.settle().catch(()=>{});for(let{sweep:I}of w)await I.settle().catch(()=>{});let N=Ln(A)||A instanceof gr?A:void 0;Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:R,orgId:l,outcome:N?"stopped":"failure",guard:h,...N?{code:N.code}:{}}),re(this.deps,"frozen:remove","frozen:remove:error",e,A,{code:N?.code??"REMOVE_ERROR",retryable:!0}),bt(this.deps,R,{status:"failure"}),this.liveTracker?.fail(R,X(A))}finally{j(U)}}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},s=d=>Yf(d,n),a=[];for(let[d,i]of t.entries())a.push({loadedAt:i.endedAt,judged:s,sweep:await this.sweepOfRemoval({conn:e.conn,load:i,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:s,...e.audit?{audit:e.audit}:{}})});return a}async settleReloadSweeps(e){let t=[];for(let{loadedAt:r,sweep:n,judged:s}of e){let a=await n.settle();t.push({loadedAt:r,result:s?s(a):a})}return t}sweepOfRemoval(e){let{conn:t,load:r}=e;return wd({input:()=>this.sweepInputOfLoad(xt(t,"frozen:remove sweep"),r,e.signal,e.store,e.sweptWith,e.audit?.sasMark),org:xn(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,s)=>{let a=e.judged?e.judged(n):n,d=hd(a,"");delete d.forgeId;let i=e.muted();Xe(this.deps,{action:"cleanup_delete",module:e.audit?.module??"frozen",operationId:`${e.operationId}-sweep`,orgId:r.orgId,outcome:a.status==="refused"?"stopped":a.status,...s?{guard:s}:{},...a.status==="refused"?{code:bd(s)}:{},objects:gd(a),details:{...d,loadedAt:r.endedAt},...i?{muted:wn(i)}:{}})},keepMade:async(n,s,a)=>{await e.store.recordMade(r.endedAt,n,s,a)}})}async sweepInputOfLoad(e,t,r,n,s=new Set,a=this.sasMarkInUse()){let d=Ko(t),i=this.targetAutomation,u;try{u=await new Pt(xs).withTimeout("frozen:remove sweep automation",()=>i.read(t.orgId,d.map(g=>g.objectApiName)))}catch(g){u={error:X(g)}}let l=t.writtenBetween??await md(e,d,r),{ties:c,sweptAlong:f}=await this.tiesOfLoad(t,l,n,s,a),p=new Set([...t.mapping.values(),...f].map(g=>g.slice(0,15)));return yd({writtenBetween:l,created:d,remap:p,automation:pd(u),...t.runUserId?{runUserId:t.runUserId}:{},ties:c,...r?{signal:r}:{}},e)}setOtherModuleRuns(e){this.otherModuleRuns=e}auditedLoadsInto(e){try{return yc(new La(this.deps.configStore).list({orgId:e,limit:Zs}).entries)}catch{return[]}}sasMarkInUse(){let e=this.loadConfig();return e?Zn(this.resolveSasDir(e)):void 0}async tiesOfLoad(e,t,r,n,s){let a=[],d=[],i=await r?.recordedLoads().catch(()=>[])??[];for(let l of i){if(l.endedAt===e.endedAt||l.orgId!==e.orgId)continue;let c=Ko(l).flatMap(g=>g.ids);if(n.has(l.endedAt)){d.push(...c);continue}let f=Date.parse(l.writtenBetween?.first??l.startedAt??l.endedAt),p=Date.parse(l.writtenBetween?.last??l.endedAt);a.push({ids:c,from:f,to:Number.isFinite(p)?p:f})}a.push(...await this.otherModuleRuns(e.orgId,t).catch(()=>[])),a.push(...hc(this.auditedLoadsInto(e.orgId),{sasMark:s,own:i.filter(l=>l.orgId===e.orgId)}));let u=kd(e.removalSpans);return{ties:{otherRuns:Rd(t,a),...u?{removalBegan:u}:{},...e.madeEarlier?{madeEarlier:e.madeEarlier}:{},...e.lateEarlier?{lateEarlier:e.lateEarlier}:{}},sweptAlong:d}}async handleRemoveSweep(e){let t=ot(Ja,e,"frozen:remove:sweep:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:sweep:error","mapping");if(!r)return;let n=(s,a)=>re(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,new Error(s),{code:a});try{let s=r.mappingStore(new de);if(t.reload===!0){await this.listReloadSweeps(e,s,t,yo(r).sasMark);return}let a=await s.recordedLoads(),d=ar(a);if(!d){n("No load into this org was recorded in this sas: there is nothing to sweep.","NO_LOAD");return}if(d.orgId!==t.targetOrgId||d.endedAt!==t.loadedAt){n("Another load was recorded since this one was shown: check what a removal takes now.","LOAD_CHANGED");return}let i=Vo(a,d),u=new Set([d,...i].map(f=>f.endedAt)),{listing:l,otherLoads:c}=await new Pt(kl).withTimeout("frozen:remove:sweep",async()=>{let f=await Ae(d.orgId,this.deps.orgRegistry,this.deps.orgManager),p=xn(f,"frozen:remove:sweep"),g=async m=>Wo(p,await this.sweepInputOfLoad(p,m,void 0,s,u,yo(r).sasMark),m.removalSpans),h=[];for(let m of i)h.push({loadedAt:m.endedAt,listing:await g(m)});return{listing:await g(d),otherLoads:h}});this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:remove:sweep:response",{loadedAt:d.endedAt,listing:l,...c.length>0?{otherLoads:c}:{}}))}catch(s){re(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,s,{code:s instanceof ut?"TIMEOUT":this.errorCodeFor(s,"SWEEP_ERROR"),retryable:!0})}}async listReloadSweeps(e,t,r,n){let s=await t.isStale()?void 0:await t.recordedLoads(),a=(s??[]).filter(i=>i.created);if(s&&!s.some(i=>i.endedAt===r.loadedAt)){re(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 d=await new Pt(kl).withTimeout("frozen:remove:sweep",async()=>{if(a.length===0)return[];let i=await Ae(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),u=xn(i,"frozen:remove:sweep"),l=new Set(a.map(f=>f.endedAt)),c=[];for(let f of a)c.push({loadedAt:f.endedAt,listing:await Wo(u,await this.sweepInputOfLoad(u,f,void 0,t,l,n),f.removalSpans)});return c});this.deps.broker.postToWebview(Oe(this.deps,e,"frozen:remove:sweep:response",{loadedAt:r.loadedAt,reload:!0,loads:d}))}sayTheSaltWasMade(e){Da(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),s={present:!1};try{let f=await this.saltKeeper.read();f&&(s={present:!0,fingerprint:new Mn(f.salt).saltFingerprint,source:f.source})}catch{s={present:!1}}let a=null;try{let f=new de;if(await et(Pe.join(r,Kr))){let p=await ys(r,f);a={selectedAt:p.selectedAt,rootCount:p.roots.length,total:p.volumetry.total,budgetMax:p.volumetry.budgetMax}}}catch{a=null}let d=null;try{let p=new de().assertOutsideRepo(Pe.join(n,"manifest.json"));await et(p)&&(d=$s(ir(JSON.parse(await Se.readFile(p,"utf8")))))}catch{d=null}let i=this.deps.configStore.get(pr),u=[];try{let f=new de,p=f.assertOutsideRepo(r);for(let g of await Fd(p,f))try{let h=ar(await new qn(p,{guard:f,orgId:g}).recordedLoads());h&&u.push(Ed(h))}catch{}}catch{u.length=0}let l={configured:t!==null,sasDir:r,datasetDir:n,salt:s,mockDetectionConfigured:t?.mockDetection!==void 0,selection:a,manifest:d,lastLoad:i?{status:i.status,orgId:i.targetOrgId,at:i.at}:null,lastLoads:this.lastLoadInfos(),lastVerifies:this.lastVerifyInfos(),...u.length>0?{loadRecords:u}:{},rules:await this.rulesFileInfo(t)},c=Oe(this.deps,e,"frozen:status:response",{status:l});this.deps.broker.postToWebview(c)}};export{qr as a,bg as b,Rg as c,kg as d,vg as e,Ig as f,Og as g,Sg as h,Rp as i,xl as j,$l as k,Zp as l,pc as m,Zn as n,gc as o,hc as p,rg as q,ng as r,cg as s,pg as t,jg as u,Zc as v,el as w,Xr as x,Al as y};