sandforge 1.80.0 → 1.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/bin/sandforge-pipeline.mjs +12 -0
  2. package/lib/{chunk-EMNC6YI4.mjs → chunk-2IB7I3IQ.mjs} +1 -1
  3. package/lib/{chunk-3RZQZHEB.mjs → chunk-2NAIUKVL.mjs} +1 -1
  4. package/lib/{chunk-AEKONPF4.mjs → chunk-2OIRJEYE.mjs} +1 -1
  5. package/lib/{chunk-BV6VTP3J.mjs → chunk-2OZG6GRW.mjs} +1 -1
  6. package/lib/{chunk-JEERQRLW.mjs → chunk-2Z54GB6X.mjs} +1 -1
  7. package/lib/chunk-2ZMGVBLW.mjs +7 -0
  8. package/lib/{chunk-FKG7Q3WH.mjs → chunk-33ZX3A56.mjs} +1 -1
  9. package/lib/{chunk-HLWMJF6Y.mjs → chunk-3AOKLIVE.mjs} +1 -1
  10. package/lib/{chunk-GGD7ON3M.mjs → chunk-3B5H24ZG.mjs} +1 -1
  11. package/lib/chunk-43K2C6H2.mjs +7 -0
  12. package/lib/chunk-4JKR4PTZ.mjs +8 -0
  13. package/lib/chunk-4L7FBOJS.mjs +8 -0
  14. package/lib/chunk-5344TZBT.mjs +11 -0
  15. package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
  16. package/lib/chunk-55LQD3Y3.mjs +7 -0
  17. package/lib/chunk-56MPPWLA.mjs +7 -0
  18. package/lib/chunk-5C5XEVZN.mjs +11 -0
  19. package/lib/chunk-5CKWGZX4.mjs +9 -0
  20. package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
  21. package/lib/{chunk-BKDV4ENO.mjs → chunk-5UT2ZBGF.mjs} +1 -1
  22. package/lib/chunk-5VQNKDFU.mjs +7 -0
  23. package/lib/{chunk-XAMBCQPU.mjs → chunk-5WGA5CZB.mjs} +1 -1
  24. package/lib/chunk-5ZKCLBTN.mjs +474 -0
  25. package/lib/{chunk-UCD54V2M.mjs → chunk-67CC7RAE.mjs} +1 -1
  26. package/lib/{chunk-TSLJUSLW.mjs → chunk-6CDIIFNX.mjs} +1 -1
  27. package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
  28. package/lib/{chunk-FPKYYFM7.mjs → chunk-6FMLW7PH.mjs} +1 -1
  29. package/lib/chunk-6IGEASOF.mjs +7 -0
  30. package/lib/{chunk-XUWL6ZPC.mjs → chunk-6NADW3OI.mjs} +1 -1
  31. package/lib/chunk-6SEDOIO3.mjs +10 -0
  32. package/lib/{chunk-PJ5I73CK.mjs → chunk-742SSN7I.mjs} +1 -1
  33. package/lib/chunk-7DALDJMO.mjs +7 -0
  34. package/lib/chunk-7PK5QDQI.mjs +7 -0
  35. package/lib/chunk-AELFEK3G.mjs +7 -0
  36. package/lib/chunk-AITNZWLB.mjs +9 -0
  37. package/lib/{chunk-2UZPIMUC.mjs → chunk-AJPSGVMD.mjs} +1 -1
  38. package/lib/{chunk-GSKCGQIP.mjs → chunk-BNO5GIJ6.mjs} +1 -1
  39. package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
  40. package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
  41. package/lib/chunk-BZFIOZS3.mjs +156 -0
  42. package/lib/{chunk-J525F5KI.mjs → chunk-C4YGSK6W.mjs} +1 -1
  43. package/lib/chunk-CAFUNR6D.mjs +7 -0
  44. package/lib/chunk-CULAOP3U.mjs +7 -0
  45. package/lib/chunk-D62KWDDT.mjs +7 -0
  46. package/lib/{chunk-OHWNPXWW.mjs → chunk-D7P7DTWL.mjs} +1 -1
  47. package/lib/{chunk-COFG7Q6R.mjs → chunk-DHGPDSXS.mjs} +1 -1
  48. package/lib/{chunk-WU3GLFZO.mjs → chunk-DHIW4IO5.mjs} +1 -1
  49. package/lib/{chunk-6XYKJSGX.mjs → chunk-DMBR24CK.mjs} +1 -1
  50. package/lib/chunk-DPYTG6DM.mjs +48 -0
  51. package/lib/{chunk-BY2HJFFG.mjs → chunk-DQR5NDMI.mjs} +1 -1
  52. package/lib/chunk-DXOXLUZA.mjs +7 -0
  53. package/lib/{chunk-YRQGKDHM.mjs → chunk-E2OBAWSH.mjs} +1 -1
  54. package/lib/chunk-E2YJVSX6.mjs +10 -0
  55. package/lib/{chunk-JWTSEDIQ.mjs → chunk-EAFLDSQ2.mjs} +1 -1
  56. package/lib/{chunk-MILU7WFN.mjs → chunk-EH5YUA5W.mjs} +1 -1
  57. package/lib/{chunk-BGUEWRK2.mjs → chunk-EOSEMFPU.mjs} +1 -1
  58. package/lib/chunk-ETT5GP4P.mjs +13 -0
  59. package/lib/{chunk-MYW5QNGI.mjs → chunk-FDGFUEK3.mjs} +1 -1
  60. package/lib/{chunk-NTFIRZP6.mjs → chunk-FLNLG43R.mjs} +1 -1
  61. package/lib/{chunk-CHYDMRSV.mjs → chunk-FSDO4DJA.mjs} +1 -1
  62. package/lib/{chunk-MJVTDA5Q.mjs → chunk-FSZTXLNW.mjs} +1 -1
  63. package/lib/{chunk-SOU4FRYN.mjs → chunk-FTA5LOVX.mjs} +1 -1
  64. package/lib/chunk-G4VXPS3A.mjs +7 -0
  65. package/lib/chunk-GF247DA7.mjs +7 -0
  66. package/lib/{chunk-BTWDMNN3.mjs → chunk-GK7VEYFM.mjs} +1 -1
  67. package/lib/{chunk-SE4QEZUG.mjs → chunk-GR3NGDVM.mjs} +1 -1
  68. package/lib/{chunk-3TJON4F3.mjs → chunk-GTIXJCGS.mjs} +1 -1
  69. package/lib/{chunk-NZC67CGR.mjs → chunk-GWRKS3AL.mjs} +1 -1
  70. package/lib/{chunk-XLXIPIEW.mjs → chunk-GYKNCYES.mjs} +1 -1
  71. package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
  72. package/lib/{chunk-KDGMAGQR.mjs → chunk-HVC5CYIB.mjs} +1 -1
  73. package/lib/{chunk-WR4Q363I.mjs → chunk-HYBH5PFM.mjs} +1 -1
  74. package/lib/chunk-HYOOJVR6.mjs +7 -0
  75. package/lib/{chunk-5K5VLULK.mjs → chunk-IBURU7T7.mjs} +1 -1
  76. package/lib/chunk-ICIYL45C.mjs +7 -0
  77. package/lib/{chunk-QR3WELJQ.mjs → chunk-IKGHRYCN.mjs} +1 -1
  78. package/lib/chunk-IM2XA6JI.mjs +7 -0
  79. package/lib/{chunk-IWDREM66.mjs → chunk-J6G23RUI.mjs} +1 -1
  80. package/lib/{chunk-2BA2XKAY.mjs → chunk-JU2XEKEO.mjs} +1 -1
  81. package/lib/{chunk-MHMH6MTP.mjs → chunk-K55LH4ZQ.mjs} +1 -1
  82. package/lib/chunk-K5HV4YRO.mjs +7 -0
  83. package/lib/{chunk-M3ROUWDX.mjs → chunk-K77NR3UK.mjs} +1 -1
  84. package/lib/chunk-KE2PGD6C.mjs +7 -0
  85. package/lib/chunk-KGYXLSQ5.mjs +37 -0
  86. package/lib/{chunk-E5AHXLS6.mjs → chunk-KNIRA333.mjs} +1 -1
  87. package/lib/chunk-KOQV4WXC.mjs +8 -0
  88. package/lib/{chunk-L77FJZEP.mjs → chunk-KRNFVAGC.mjs} +1 -1
  89. package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
  90. package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
  91. package/lib/{chunk-IZQZ6ZUF.mjs → chunk-LO527YLT.mjs} +1 -1
  92. package/lib/chunk-MAHZMPMZ.mjs +7 -0
  93. package/lib/{chunk-F6GUDTOB.mjs → chunk-MHW6DV6T.mjs} +1 -1
  94. package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
  95. package/lib/{chunk-FGRG7ANU.mjs → chunk-MKNAZPOT.mjs} +1 -1
  96. package/lib/{chunk-PZPJKATS.mjs → chunk-MNITSYI2.mjs} +8 -8
  97. package/lib/{chunk-OLSGVAIL.mjs → chunk-MO3N5XVV.mjs} +53 -53
  98. package/lib/chunk-MWLFFVQV.mjs +8 -0
  99. package/lib/chunk-N6HHNR6J.mjs +7 -0
  100. package/lib/chunk-N7J6NJQ6.mjs +7 -0
  101. package/lib/chunk-NJ3EOEHS.mjs +9 -0
  102. package/lib/chunk-NWPQF5XR.mjs +7 -0
  103. package/lib/{chunk-IG2MTQRP.mjs → chunk-NWVVCZUK.mjs} +1 -1
  104. package/lib/{chunk-2NBYT7GR.mjs → chunk-O6ADMP36.mjs} +1 -1
  105. package/lib/chunk-O7DAFE6M.mjs +14 -0
  106. package/lib/chunk-OEHVAJAB.mjs +7 -0
  107. package/lib/chunk-OETEC3P7.mjs +7 -0
  108. package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
  109. package/lib/chunk-OIIL4NVI.mjs +7 -0
  110. package/lib/chunk-OMZJ37JI.mjs +15 -0
  111. package/lib/{chunk-CEX3NEZL.mjs → chunk-ONMBSACW.mjs} +1 -1
  112. package/lib/chunk-OQQHNYR7.mjs +272 -0
  113. package/lib/{chunk-SOGQW4IG.mjs → chunk-OU5W7SCB.mjs} +1 -1
  114. package/lib/{chunk-O2HDYYUV.mjs → chunk-OVOLG3AL.mjs} +1 -1
  115. package/lib/{chunk-DYFALGRT.mjs → chunk-OXKZ4Y3B.mjs} +1 -1
  116. package/lib/{chunk-2GTBABKU.mjs → chunk-OZNLOV4U.mjs} +1 -1
  117. package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
  118. package/lib/chunk-PPGDAUEQ.mjs +7 -0
  119. package/lib/{chunk-IGYH7GMA.mjs → chunk-PYUEHBA6.mjs} +1 -1
  120. package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
  121. package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
  122. package/lib/{chunk-BXU6WFMH.mjs → chunk-QXLZINZB.mjs} +1 -1
  123. package/lib/chunk-R2BJWO5N.mjs +20 -0
  124. package/lib/chunk-R6TF26V4.mjs +10 -0
  125. package/lib/{chunk-YKKRIEH4.mjs → chunk-RKALOKAU.mjs} +1 -1
  126. package/lib/chunk-SQGP46QS.mjs +7 -0
  127. package/lib/chunk-SW2NUKQL.mjs +9 -0
  128. package/lib/{chunk-MFG4MUIO.mjs → chunk-T26C576X.mjs} +1 -1
  129. package/lib/{chunk-LKQ5RKIV.mjs → chunk-T3PLRQ2T.mjs} +1 -1
  130. package/lib/chunk-T5VAULLQ.mjs +7 -0
  131. package/lib/{chunk-KYEDBS54.mjs → chunk-TEIBWMJM.mjs} +1 -1
  132. package/lib/chunk-TKQQVB2D.mjs +9 -0
  133. package/lib/{chunk-ELFXJHU7.mjs → chunk-TPHXRHOA.mjs} +1 -1
  134. package/lib/chunk-TQ2TQHTT.mjs +9 -0
  135. package/lib/{chunk-RPI7LRTW.mjs → chunk-TQM2XJ27.mjs} +1 -1
  136. package/lib/{chunk-IOIWJ3DJ.mjs → chunk-UCHAZ4ZU.mjs} +1 -1
  137. package/lib/{chunk-G35N4P7D.mjs → chunk-UIUPPEFB.mjs} +1 -1
  138. package/lib/{chunk-DBB3EMIN.mjs → chunk-UT27HXE7.mjs} +1 -1
  139. package/lib/{chunk-KBJ5VERV.mjs → chunk-UUSLTW5V.mjs} +1 -1
  140. package/lib/chunk-V2QO6KOE.mjs +19 -0
  141. package/lib/chunk-V473C7LY.mjs +7 -0
  142. package/lib/chunk-V4RKM4QZ.mjs +8 -0
  143. package/lib/chunk-VSU74RQ3.mjs +9 -0
  144. package/lib/chunk-VV3B6IC3.mjs +7 -0
  145. package/lib/chunk-W2AAGIZF.mjs +7 -0
  146. package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
  147. package/lib/chunk-WD47PGUS.mjs +10 -0
  148. package/lib/{chunk-HEKAZJRH.mjs → chunk-WEZLXE34.mjs} +1 -1
  149. package/lib/{chunk-W622GUAW.mjs → chunk-WI4HYWV6.mjs} +1 -1
  150. package/lib/{chunk-WA7EYLAQ.mjs → chunk-WM5JI4JI.mjs} +1 -1
  151. package/lib/chunk-WWTXRWNZ.mjs +7 -0
  152. package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
  153. package/lib/{chunk-FXXLX4O6.mjs → chunk-X2ZVSQ54.mjs} +1 -1
  154. package/lib/{chunk-ZVAED4QV.mjs → chunk-XC2QKQT5.mjs} +1 -1
  155. package/lib/chunk-XC54KKKC.mjs +7 -0
  156. package/lib/chunk-XEB6HZ34.mjs +7 -0
  157. package/lib/chunk-XGKSSCW7.mjs +7 -0
  158. package/lib/chunk-XIZ5LMQM.mjs +7 -0
  159. package/lib/{chunk-74Q6DORA.mjs → chunk-Y5ZCPY36.mjs} +1 -1
  160. package/lib/{chunk-UNJA4J37.mjs → chunk-YCSFP6ER.mjs} +4 -4
  161. package/lib/{chunk-X5JYBPXP.mjs → chunk-YHIOS2PU.mjs} +1 -1
  162. package/lib/chunk-YIGFYZQY.mjs +7 -0
  163. package/lib/chunk-YJEXE6HZ.mjs +925 -0
  164. package/lib/{chunk-TTKXMDBN.mjs → chunk-YOGMP72T.mjs} +4 -4
  165. package/lib/chunk-ZRUDYB7O.mjs +7 -0
  166. package/lib/{chunk-CU2INBND.mjs → chunk-ZUA5BNAO.mjs} +1 -1
  167. package/lib/chunk-ZWCRWF7E.mjs +7 -0
  168. package/lib/{chunk-N652NMZ4.mjs → chunk-ZWZXQTAK.mjs} +52 -52
  169. package/lib/sandforge-autopilot.mjs +11 -11
  170. package/lib/sandforge-backup.mjs +63 -32
  171. package/lib/sandforge-checkpoint.mjs +1 -348
  172. package/lib/sandforge-cleanup.mjs +1 -1
  173. package/lib/sandforge-clone.mjs +1 -1
  174. package/lib/sandforge-compare.mjs +1 -1
  175. package/lib/sandforge-dataops.mjs +1 -1
  176. package/lib/sandforge-empty.mjs +11 -11
  177. package/lib/sandforge-env.mjs +104 -104
  178. package/lib/sandforge-frozen.mjs +1 -266
  179. package/lib/sandforge-mcp.mjs +33 -14
  180. package/lib/sandforge-monitor.mjs +1 -1
  181. package/lib/sandforge-pipeline.mjs +88 -0
  182. package/lib/sandforge-seed.mjs +1 -1
  183. package/lib/sandforge-sync.mjs +1 -1
  184. package/lib/sandforge.mjs +6 -6
  185. package/package.json +2 -1
  186. package/lib/chunk-2CNCDM56.mjs +0 -7
  187. package/lib/chunk-3F6Q5E7I.mjs +0 -14
  188. package/lib/chunk-4VS2V6WU.mjs +0 -25
  189. package/lib/chunk-5P4PHJRL.mjs +0 -9
  190. package/lib/chunk-5TC3QB4U.mjs +0 -10
  191. package/lib/chunk-7ABODJ4G.mjs +0 -7
  192. package/lib/chunk-7EGQP6S4.mjs +0 -7
  193. package/lib/chunk-7FFGJWHN.mjs +0 -7
  194. package/lib/chunk-7YDNUBO5.mjs +0 -7
  195. package/lib/chunk-A527W53V.mjs +0 -7
  196. package/lib/chunk-ADOAS63R.mjs +0 -7
  197. package/lib/chunk-B5QQJ4SI.mjs +0 -7
  198. package/lib/chunk-CION3VMZ.mjs +0 -7
  199. package/lib/chunk-CSBS5U5I.mjs +0 -7
  200. package/lib/chunk-DB7RBE5D.mjs +0 -7
  201. package/lib/chunk-E5ZB3LU5.mjs +0 -7
  202. package/lib/chunk-EFR2Y7E4.mjs +0 -7
  203. package/lib/chunk-EHQ3FX6X.mjs +0 -7
  204. package/lib/chunk-EQNW3UC2.mjs +0 -7
  205. package/lib/chunk-F43REJDZ.mjs +0 -10
  206. package/lib/chunk-GSG7WZHM.mjs +0 -7
  207. package/lib/chunk-HOJYWTP7.mjs +0 -20
  208. package/lib/chunk-HS4YRX4J.mjs +0 -7
  209. package/lib/chunk-I7O6C2B5.mjs +0 -8
  210. package/lib/chunk-IFETCRWE.mjs +0 -10
  211. package/lib/chunk-IQXHJEYB.mjs +0 -7
  212. package/lib/chunk-JPUR2CFX.mjs +0 -10
  213. package/lib/chunk-K327QKMD.mjs +0 -7
  214. package/lib/chunk-KRCA6IPH.mjs +0 -8
  215. package/lib/chunk-LPBMBW3O.mjs +0 -13
  216. package/lib/chunk-LWW4U276.mjs +0 -7
  217. package/lib/chunk-MJU2PGZQ.mjs +0 -15
  218. package/lib/chunk-OAZRPP4I.mjs +0 -7
  219. package/lib/chunk-OO6CLPEH.mjs +0 -7
  220. package/lib/chunk-OPXCV2KL.mjs +0 -7
  221. package/lib/chunk-P33PSCXK.mjs +0 -7
  222. package/lib/chunk-Q3DM32KF.mjs +0 -11
  223. package/lib/chunk-QROPNEGY.mjs +0 -14
  224. package/lib/chunk-QWT2C74M.mjs +0 -7
  225. package/lib/chunk-R3X3LV64.mjs +0 -14
  226. package/lib/chunk-RMBPOTD7.mjs +0 -7
  227. package/lib/chunk-SIHORWVK.mjs +0 -7
  228. package/lib/chunk-T62WNR54.mjs +0 -7
  229. package/lib/chunk-TTFDUKUS.mjs +0 -47
  230. package/lib/chunk-VE6XKGGD.mjs +0 -7
  231. package/lib/chunk-VGW4MXXZ.mjs +0 -7
  232. package/lib/chunk-VS7ZXUII.mjs +0 -824
  233. package/lib/chunk-VXQLDM4R.mjs +0 -7
  234. package/lib/chunk-VYXMVJL5.mjs +0 -7
  235. package/lib/chunk-W7U5E5ZL.mjs +0 -9
  236. package/lib/chunk-WXAQ7FK3.mjs +0 -115
  237. package/lib/chunk-YS4G22C2.mjs +0 -7
  238. package/lib/chunk-ZM6OJGIG.mjs +0 -7
  239. package/lib/chunk-ZUTYVST5.mjs +0 -7
@@ -4,152 +4,152 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as Ec,c as Me,d as Sc,e as Rc,f as $c,g as or}from"./chunk-WU3GLFZO.mjs";import{a as Dc}from"./chunk-BV6VTP3J.mjs";import{a as rc}from"./chunk-W7U5E5ZL.mjs";import{a as cr,d as Oe,k as Tc,o as Xt,p as lr,q as Pc,r as Lc}from"./chunk-R3X3LV64.mjs";import{f as Nc}from"./chunk-FQGHL7GR.mjs";import{b as Fc,d as ti,e as ni}from"./chunk-WXAQ7FK3.mjs";import"./chunk-TW3N6W5Z.mjs";import"./chunk-5P4PHJRL.mjs";import"./chunk-RSWDYIHY.mjs";import{Xa as ar,_a as Oc,xb as Cc,yb as jc}from"./chunk-VS7ZXUII.mjs";import"./chunk-SOU4FRYN.mjs";import{b as Ae,c as bc}from"./chunk-E5AHXLS6.mjs";import"./chunk-OO6CLPEH.mjs";import{a as ct,b as wc}from"./chunk-YS4G22C2.mjs";import{b as kc}from"./chunk-QROPNEGY.mjs";import{a as sc,b as be,e as Le}from"./chunk-BZ24IAP5.mjs";import{a as ue,b as Pe}from"./chunk-SCKUIE3R.mjs";import{i as ic}from"./chunk-AV5SWEHP.mjs";import{b as Ic}from"./chunk-I7O6C2B5.mjs";import"./chunk-YRQGKDHM.mjs";import{a as Zs}from"./chunk-MJU2PGZQ.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-LWW4U276.mjs";import"./chunk-MJVTDA5Q.mjs";import"./chunk-XCA5AONB.mjs";import"./chunk-WR2GIKWE.mjs";import{Wa as cc,_ as oc,za as ac}from"./chunk-2CNCDM56.mjs";import"./chunk-SIHORWVK.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-B5QQJ4SI.mjs";import"./chunk-NZC67CGR.mjs";import"./chunk-BOGNK4LV.mjs";import{La as ir,y as vc}from"./chunk-4VS2V6WU.mjs";import"./chunk-KYEDBS54.mjs";import"./chunk-6XYKJSGX.mjs";import"./chunk-K2FBZIXY.mjs";import"./chunk-F43REJDZ.mjs";import{N as lc}from"./chunk-JPUR2CFX.mjs";import"./chunk-LPBMBW3O.mjs";import"./chunk-T63U4OZJ.mjs";import"./chunk-DBFJB2B6.mjs";import{K as pc,k as xe}from"./chunk-IFETCRWE.mjs";import{h as uc,l as dc,m as fc,o as ei}from"./chunk-PZPJKATS.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-DYFALGRT.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-7FFGJWHN.mjs";import"./chunk-G35N4P7D.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-SAR5622P.mjs";import{a as Xs,b as tc,c as nc}from"./chunk-KDGMAGQR.mjs";import"./chunk-MFG4MUIO.mjs";import"./chunk-EQNW3UC2.mjs";import"./chunk-GSKCGQIP.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-TYYOBZMU.mjs";import{b as rr,c as sr,e as Za}from"./chunk-HS4YRX4J.mjs";import"./chunk-ZUTYVST5.mjs";import"./chunk-CU2INBND.mjs";import"./chunk-YKKRIEH4.mjs";import"./chunk-TUACWKIH.mjs";import{D as hc,Ia as at,K as mc,L as gc,ka as yc}from"./chunk-VYXMVJL5.mjs";import"./chunk-AEKONPF4.mjs";import"./chunk-JWTSEDIQ.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-CION3VMZ.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-L77FJZEP.mjs";import"./chunk-A527W53V.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-GGD7ON3M.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import{a as ec,e as Fe,f as Qt,g as Ac}from"./chunk-MTMH6H2A.mjs";import{Ga as Va,Ka as Gt,La as Wa,Ma as Ja,Na as Ya,Oa as Ga,Pa as nr,Qa as Ha,Ra as Qa,Sa as Ht,Ta as Hs,d as tr,eb as Qs,fa as Gs,i as Ua,ta as ot,uc as Xa}from"./chunk-TTFDUKUS.mjs";import{A as p}from"./chunk-7EANH5PY.mjs";import"./chunk-MS4FJDFD.mjs";import{a as er,b as C,d as sm}from"./chunk-NTOVCTRS.mjs";var x=C(H=>{"use strict";var ji=Symbol.for("yaml.alias"),ud=Symbol.for("yaml.document"),Lr=Symbol.for("yaml.map"),dd=Symbol.for("yaml.pair"),Ni=Symbol.for("yaml.scalar"),Fr=Symbol.for("yaml.seq"),je=Symbol.for("yaml.node.type"),Mg=e=>!!e&&typeof e=="object"&&e[je]===ji,_g=e=>!!e&&typeof e=="object"&&e[je]===ud,qg=e=>!!e&&typeof e=="object"&&e[je]===Lr,zg=e=>!!e&&typeof e=="object"&&e[je]===dd,fd=e=>!!e&&typeof e=="object"&&e[je]===Ni,Bg=e=>!!e&&typeof e=="object"&&e[je]===Fr;function pd(e){if(e&&typeof e=="object")switch(e[je]){case Lr:case Fr:return!0}return!1}function Kg(e){if(e&&typeof e=="object")switch(e[je]){case ji:case Lr:case Ni:case Fr:return!0}return!1}var Ug=e=>(fd(e)||pd(e))&&!!e.anchor;H.ALIAS=ji;H.DOC=ud;H.MAP=Lr;H.NODE_TYPE=je;H.PAIR=dd;H.SCALAR=Ni;H.SEQ=Fr;H.hasAnchor=Ug;H.isAlias=Mg;H.isCollection=pd;H.isDocument=_g;H.isMap=qg;H.isNode=Kg;H.isPair=zg;H.isScalar=fd;H.isSeq=Bg});var gn=C(Ii=>{"use strict";var W=x(),ie=Symbol("break visit"),hd=Symbol("skip children"),Re=Symbol("remove node");function xr(e,t){let n=md(t);W.isDocument(e)?Pt(null,e.contents,n,Object.freeze([e]))===Re&&(e.contents=null):Pt(null,e,n,Object.freeze([]))}xr.BREAK=ie;xr.SKIP=hd;xr.REMOVE=Re;function Pt(e,t,n,r){let s=gd(e,t,n,r);if(W.isNode(s)||W.isPair(s))return yd(e,r,s),Pt(e,s,n,r);if(typeof s!="symbol"){if(W.isCollection(t)){r=Object.freeze(r.concat(t));for(let i=0;i<t.items.length;++i){let o=Pt(i,t.items[i],n,r);if(typeof o=="number")i=o-1;else{if(o===ie)return ie;o===Re&&(t.items.splice(i,1),i-=1)}}}else if(W.isPair(t)){r=Object.freeze(r.concat(t));let i=Pt("key",t.key,n,r);if(i===ie)return ie;i===Re&&(t.key=null);let o=Pt("value",t.value,n,r);if(o===ie)return ie;o===Re&&(t.value=null)}}return s}async function Mr(e,t){let n=md(t);W.isDocument(e)?await Lt(null,e.contents,n,Object.freeze([e]))===Re&&(e.contents=null):await Lt(null,e,n,Object.freeze([]))}Mr.BREAK=ie;Mr.SKIP=hd;Mr.REMOVE=Re;async function Lt(e,t,n,r){let s=await gd(e,t,n,r);if(W.isNode(s)||W.isPair(s))return yd(e,r,s),Lt(e,s,n,r);if(typeof s!="symbol"){if(W.isCollection(t)){r=Object.freeze(r.concat(t));for(let i=0;i<t.items.length;++i){let o=await Lt(i,t.items[i],n,r);if(typeof o=="number")i=o-1;else{if(o===ie)return ie;o===Re&&(t.items.splice(i,1),i-=1)}}}else if(W.isPair(t)){r=Object.freeze(r.concat(t));let i=await Lt("key",t.key,n,r);if(i===ie)return ie;i===Re&&(t.key=null);let o=await Lt("value",t.value,n,r);if(o===ie)return ie;o===Re&&(t.value=null)}}return s}function md(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function gd(e,t,n,r){if(typeof n=="function")return n(e,t,r);if(W.isMap(t))return n.Map?.(e,t,r);if(W.isSeq(t))return n.Seq?.(e,t,r);if(W.isPair(t))return n.Pair?.(e,t,r);if(W.isScalar(t))return n.Scalar?.(e,t,r);if(W.isAlias(t))return n.Alias?.(e,t,r)}function yd(e,t,n){let r=t[t.length-1];if(W.isCollection(r))r.items[e]=n;else if(W.isPair(r))e==="key"?r.key=n:r.value=n;else if(W.isDocument(r))r.contents=n;else{let s=W.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}Ii.visit=xr;Ii.visitAsync=Mr});var Di=C(vd=>{"use strict";var wd=x(),Vg=gn(),Wg={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Jg=e=>e.replace(/[!,[\]{}]/g,t=>Wg[t]),yn=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),s=r.shift();switch(s){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[i,o]=r;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[i]=r;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let o=/^\d+\.\d+$/.test(i);return n(6,`Unsupported YAML version ${i}`,o),!1}}default:return n(0,`Unknown directive ${s}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,r,s]=t.match(/^(.*!)([^!]*)$/s);s||n(`The ${t} tag has no suffix`);let i=this.tags[r];if(i)try{return i+decodeURIComponent(s)}catch(o){return n(String(o)),null}return r==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[n,r]of Object.entries(this.tags))if(t.startsWith(r))return n+Jg(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),s;if(t&&r.length>0&&wd.isNode(t.contents)){let i={};Vg.visit(t.contents,(o,a)=>{wd.isNode(a)&&a.tag&&(i[a.tag]=!0)}),s=Object.keys(i)}else s=[];for(let[i,o]of r)i==="!!"&&o==="tag:yaml.org,2002:"||(!t||s.some(a=>a.startsWith(o)))&&n.push(`%TAG ${i} ${o}`);return n.join(`
8
- `)}};yn.defaultYaml={explicit:!1,version:"1.2"};yn.defaultTags={"!!":"tag:yaml.org,2002:"};vd.Directives=yn});var _r=C(wn=>{"use strict";var kd=x(),Yg=gn();function Gg(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function bd(e){let t=new Set;return Yg.visit(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function Ed(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function Hg(e,t){let n=[],r=new Map,s=null;return{onAnchor:i=>{n.push(i),s??(s=bd(e));let o=Ed(t,s);return s.add(o),o},setAnchors:()=>{for(let i of n){let o=r.get(i);if(typeof o=="object"&&o.anchor&&(kd.isScalar(o.node)||kd.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:r}}wn.anchorIsValid=Gg;wn.anchorNames=bd;wn.createNodeAnchors=Hg;wn.findNewAnchor=Ed});var Ti=C(Sd=>{"use strict";function vn(e,t,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let s=0,i=r.length;s<i;++s){let o=r[s],a=vn(e,r,String(s),o);a===void 0?delete r[s]:a!==o&&(r[s]=a)}else if(r instanceof Map)for(let s of Array.from(r.keys())){let i=r.get(s),o=vn(e,r,s,i);o===void 0?r.delete(s):o!==i&&r.set(s,o)}else if(r instanceof Set)for(let s of Array.from(r)){let i=vn(e,r,s,s);i===void 0?r.delete(s):i!==s&&(r.delete(s),r.add(i))}else for(let[s,i]of Object.entries(r)){let o=vn(e,r,s,i);o===void 0?delete r[s]:o!==i&&(r[s]=o)}return e.call(t,n,r)}Sd.applyReviver=vn});var We=C($d=>{"use strict";var Qg=x();function Rd(e,t,n){if(Array.isArray(e))return e.map((r,s)=>Rd(r,String(s),n));if(e&&typeof e.toJSON=="function"){if(!n||!Qg.hasAnchor(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=i=>{r.res=i,delete n.onCreate};let s=e.toJSON(t,n);return n.onCreate&&n.onCreate(s),s}return typeof e=="bigint"&&!n?.keep?Number(e):e}$d.toJS=Rd});var qr=C(Od=>{"use strict";var Xg=Ti(),Ad=x(),Zg=We(),Pi=class{constructor(t){Object.defineProperty(this,Ad.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:r,onAnchor:s,reviver:i}={}){if(!Ad.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=Zg.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?Xg.applyReviver(i,{"":a},"",a):a}};Od.NodeBase=Pi});var kn=C(Cd=>{"use strict";var ey=_r(),ty=gn(),Ft=x(),ny=qr(),ry=We(),Li=class extends ny.NodeBase{constructor(t){super(Ft.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],ty.visit(t,{Node:(i,o)=>{(Ft.isAlias(o)||Ft.hasAnchor(o))&&r.push(o)}}),n&&(n.aliasResolveCache=r));let s;for(let i of r){if(i===this)break;i.anchor===this.source&&(s=i)}if(s&&n){let{anchors:i,doc:o,maxAliasCount:a}=n,c=i.get(s);if(c||(ry.toJS(s,null,n),c=i.get(s)),c?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=zr(o,s,i)),c.count*c.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}}return s}toJSON(t,n){if(!n)return{source:this.source};let r=this.resolve(n.doc,n);if(!r){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(s)}return n.anchors.get(r).res}toString(t,n,r){let s=`*${this.source}`;if(t){if(ey.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(t.implicitKey)return`${s} `}return s}};function zr(e,t,n){if(Ft.isAlias(t)){let r=t.resolve(e),s=n&&r&&n.get(r);return s?s.count*s.aliasCount:0}else if(Ft.isCollection(t)){let r=0;for(let s of t.items){let i=zr(e,s,n);i>r&&(r=i)}return r}else if(Ft.isPair(t)){let r=zr(e,t.key,n),s=zr(e,t.value,n);return Math.max(r,s)}return 1}Cd.Alias=Li});var V=C(Fi=>{"use strict";var sy=x(),iy=qr(),oy=We(),ay=e=>!e||typeof e!="function"&&typeof e!="object",Je=class extends iy.NodeBase{constructor(t){super(sy.SCALAR),this.value=t}toJSON(t,n){return n?.keep?this.value:oy.toJS(this.value,t,n)}toString(){return String(this.value)}};Je.BLOCK_FOLDED="BLOCK_FOLDED";Je.BLOCK_LITERAL="BLOCK_LITERAL";Je.PLAIN="PLAIN";Je.QUOTE_DOUBLE="QUOTE_DOUBLE";Je.QUOTE_SINGLE="QUOTE_SINGLE";Fi.Scalar=Je;Fi.isScalarValue=ay});var bn=C(Nd=>{"use strict";var cy=kn(),ut=x(),jd=V(),ly="tag:yaml.org,2002:";function uy(e,t,n){if(t){let r=n.filter(i=>i.tag===t),s=r.find(i=>!i.format)??r[0];if(!s)throw new Error(`Tag ${t} not found`);return s}return n.find(r=>r.identify?.(e)&&!r.format)}function dy(e,t,n){if(ut.isDocument(e)&&(e=e.contents),ut.isNode(e))return e;if(ut.isPair(e)){let d=n.schema[ut.MAP].createNode?.(n.schema,null,n);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:s,onTagObj:i,schema:o,sourceObjects:a}=n,c;if(r&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=s(e)),new cy.Alias(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=ly+t.slice(2));let l=uy(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new jd.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[ut.MAP]:Symbol.iterator in Object(e)?o[ut.SEQ]:o[ut.MAP]}i&&(i(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,e,n):new jd.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Nd.createNode=dy});var Kr=C(Br=>{"use strict";var fy=bn(),$e=x(),py=qr();function xi(e,t,n){let r=n;for(let s=t.length-1;s>=0;--s){let i=t[s];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let o=[];o[i]=r,r=o}else r=new Map([[i,r]])}return fy.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Id=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Mi=class extends py.NodeBase{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(r=>$e.isNode(r)||$e.isPair(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(Id(t))this.add(n);else{let[r,...s]=t,i=this.get(r,!0);if($e.isCollection(i))i.addIn(s,n);else if(i===void 0&&this.schema)this.set(r,xi(this.schema,s,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`)}}deleteIn(t){let[n,...r]=t;if(r.length===0)return this.delete(n);let s=this.get(n,!0);if($e.isCollection(s))return s.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(t,n){let[r,...s]=t,i=this.get(r,!0);return s.length===0?!n&&$e.isScalar(i)?i.value:i:$e.isCollection(i)?i.getIn(s,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!$e.isPair(n))return!1;let r=n.value;return r==null||t&&$e.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[n,...r]=t;if(r.length===0)return this.has(n);let s=this.get(n,!0);return $e.isCollection(s)?s.hasIn(r):!1}setIn(t,n){let[r,...s]=t;if(s.length===0)this.set(r,n);else{let i=this.get(r,!0);if($e.isCollection(i))i.setIn(s,n);else if(i===void 0&&this.schema)this.set(r,xi(this.schema,s,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`)}}};Br.Collection=Mi;Br.collectionFromPath=xi;Br.isEmptyPath=Id});var En=C(Ur=>{"use strict";var hy=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function _i(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var my=(e,t,n)=>e.endsWith(`
9
- `)?_i(n,t):n.includes(`
7
+ import{a as Nc,c as Me,d as Ic,e as Dc,f as Pc,g as or}from"./chunk-DHIW4IO5.mjs";import{a as qc}from"./chunk-2OZG6GRW.mjs";import{a as ac}from"./chunk-TKQQVB2D.mjs";import{g as Kc}from"./chunk-WD47PGUS.mjs";import{a as cr,d as Oe,f as Xt,g as lr}from"./chunk-5C5XEVZN.mjs";import{c as zc,d as Bc}from"./chunk-DXOXLUZA.mjs";import{f as Mc}from"./chunk-FQGHL7GR.mjs";import{b as Uc,e as ri,f as si}from"./chunk-BZFIOZS3.mjs";import"./chunk-TW3N6W5Z.mjs";import"./chunk-5GBO4KD5.mjs";import{Gb as Lc,Hb as xc,eb as ar,hb as Fc}from"./chunk-YJEXE6HZ.mjs";import"./chunk-FTA5LOVX.mjs";import{b as Ae,c as jc}from"./chunk-KNIRA333.mjs";import"./chunk-7DALDJMO.mjs";import{b as ut,c as Rc,m as Ac}from"./chunk-O7DAFE6M.mjs";import{a as cc,b as be,e as Fe}from"./chunk-BZ24IAP5.mjs";import{a as ce,b as Te}from"./chunk-SCKUIE3R.mjs";import{i as lc}from"./chunk-6FARZYMJ.mjs";import"./chunk-E2OBAWSH.mjs";import{a as ti}from"./chunk-OMZJ37JI.mjs";import"./chunk-43K2C6H2.mjs";import"./chunk-FSZTXLNW.mjs";import"./chunk-XCA5AONB.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-WB2RIVO3.mjs";import{b as _c}from"./chunk-VSU74RQ3.mjs";import{Wa as fc,_ as uc,za as dc}from"./chunk-CAFUNR6D.mjs";import"./chunk-AITNZWLB.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-OEHVAJAB.mjs";import"./chunk-GWRKS3AL.mjs";import"./chunk-BOGNK4LV.mjs";import{ha as ir,m as $c,oa as Oc,ta as Cc}from"./chunk-KGYXLSQ5.mjs";import"./chunk-TEIBWMJM.mjs";import"./chunk-DMBR24CK.mjs";import"./chunk-BWWQXU2B.mjs";import"./chunk-4L7FBOJS.mjs";import"./chunk-OXKZ4Y3B.mjs";import"./chunk-MAHZMPMZ.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-UIUPPEFB.mjs";import"./chunk-6SEDOIO3.mjs";import{N as pc}from"./chunk-ZWCRWF7E.mjs";import"./chunk-T63U4OZJ.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-54HYHHVL.mjs";import"./chunk-QIRO4HTE.mjs";import{h as hc,l as mc,n as gc,p as ni}from"./chunk-MNITSYI2.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-NJ3EOEHS.mjs";import"./chunk-ETT5GP4P.mjs";import"./chunk-SW2NUKQL.mjs";import"./chunk-4JKR4PTZ.mjs";import{M as yc,k as xe}from"./chunk-E2YJVSX6.mjs";import{a as ei,b as ic,c as oc}from"./chunk-HVC5CYIB.mjs";import"./chunk-T26C576X.mjs";import"./chunk-BNO5GIJ6.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-4TLYUZD5.mjs";import{a as rr,b as sr,d as rc}from"./chunk-SQGP46QS.mjs";import"./chunk-PPGDAUEQ.mjs";import"./chunk-MS4FJDFD.mjs";import"./chunk-6IGEASOF.mjs";import{$a as Ec,F as wc,K as vc,Pb as Sc,Ra as kc,_a as bc,mc as lt}from"./chunk-KOQV4WXC.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-CULAOP3U.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-KRNFVAGC.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-2OIRJEYE.mjs";import{b as sc,f as Le,g as Qt,h as Tc}from"./chunk-LCDPCUXS.mjs";import"./chunk-XEB6HZ34.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-ICIYL45C.mjs";import"./chunk-ZUA5BNAO.mjs";import"./chunk-RKALOKAU.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-55LQD3Y3.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-3B5H24ZG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-EAFLDSQ2.mjs";import"./chunk-CA5NAXSU.mjs";import{Da as Qs,Eb as Zs,Ra as ct,Xc as nc,e as tr,eb as Ga,ib as Gt,j as Ja,jb as Ha,kb as Qa,lb as Xa,mb as Za,nb as nr,ob as ec,pb as tc,qb as Ht,rb as Xs,x as Ya}from"./chunk-DPYTG6DM.mjs";import{A as p}from"./chunk-WZQEK4WT.mjs";import{a as er,b as C,d as fm}from"./chunk-NTOVCTRS.mjs";var x=C(Q=>{"use strict";var Di=Symbol.for("yaml.alias"),wd=Symbol.for("yaml.document"),xr=Symbol.for("yaml.map"),vd=Symbol.for("yaml.pair"),Pi=Symbol.for("yaml.scalar"),Mr=Symbol.for("yaml.seq"),je=Symbol.for("yaml.node.type"),Wg=e=>!!e&&typeof e=="object"&&e[je]===Di,Jg=e=>!!e&&typeof e=="object"&&e[je]===wd,Yg=e=>!!e&&typeof e=="object"&&e[je]===xr,Gg=e=>!!e&&typeof e=="object"&&e[je]===vd,kd=e=>!!e&&typeof e=="object"&&e[je]===Pi,Hg=e=>!!e&&typeof e=="object"&&e[je]===Mr;function bd(e){if(e&&typeof e=="object")switch(e[je]){case xr:case Mr:return!0}return!1}function Qg(e){if(e&&typeof e=="object")switch(e[je]){case Di:case xr:case Pi:case Mr:return!0}return!1}var Xg=e=>(kd(e)||bd(e))&&!!e.anchor;Q.ALIAS=Di;Q.DOC=wd;Q.MAP=xr;Q.NODE_TYPE=je;Q.PAIR=vd;Q.SCALAR=Pi;Q.SEQ=Mr;Q.hasAnchor=Xg;Q.isAlias=Wg;Q.isCollection=bd;Q.isDocument=Jg;Q.isMap=Yg;Q.isNode=Qg;Q.isPair=Gg;Q.isScalar=kd;Q.isSeq=Hg});var gn=C(Ti=>{"use strict";var W=x(),ie=Symbol("break visit"),Ed=Symbol("skip children"),Re=Symbol("remove node");function _r(e,t){let n=Sd(t);W.isDocument(e)?Lt(null,e.contents,n,Object.freeze([e]))===Re&&(e.contents=null):Lt(null,e,n,Object.freeze([]))}_r.BREAK=ie;_r.SKIP=Ed;_r.REMOVE=Re;function Lt(e,t,n,r){let s=Rd(e,t,n,r);if(W.isNode(s)||W.isPair(s))return $d(e,r,s),Lt(e,s,n,r);if(typeof s!="symbol"){if(W.isCollection(t)){r=Object.freeze(r.concat(t));for(let i=0;i<t.items.length;++i){let o=Lt(i,t.items[i],n,r);if(typeof o=="number")i=o-1;else{if(o===ie)return ie;o===Re&&(t.items.splice(i,1),i-=1)}}}else if(W.isPair(t)){r=Object.freeze(r.concat(t));let i=Lt("key",t.key,n,r);if(i===ie)return ie;i===Re&&(t.key=null);let o=Lt("value",t.value,n,r);if(o===ie)return ie;o===Re&&(t.value=null)}}return s}async function qr(e,t){let n=Sd(t);W.isDocument(e)?await xt(null,e.contents,n,Object.freeze([e]))===Re&&(e.contents=null):await xt(null,e,n,Object.freeze([]))}qr.BREAK=ie;qr.SKIP=Ed;qr.REMOVE=Re;async function xt(e,t,n,r){let s=await Rd(e,t,n,r);if(W.isNode(s)||W.isPair(s))return $d(e,r,s),xt(e,s,n,r);if(typeof s!="symbol"){if(W.isCollection(t)){r=Object.freeze(r.concat(t));for(let i=0;i<t.items.length;++i){let o=await xt(i,t.items[i],n,r);if(typeof o=="number")i=o-1;else{if(o===ie)return ie;o===Re&&(t.items.splice(i,1),i-=1)}}}else if(W.isPair(t)){r=Object.freeze(r.concat(t));let i=await xt("key",t.key,n,r);if(i===ie)return ie;i===Re&&(t.key=null);let o=await xt("value",t.value,n,r);if(o===ie)return ie;o===Re&&(t.value=null)}}return s}function Sd(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Rd(e,t,n,r){if(typeof n=="function")return n(e,t,r);if(W.isMap(t))return n.Map?.(e,t,r);if(W.isSeq(t))return n.Seq?.(e,t,r);if(W.isPair(t))return n.Pair?.(e,t,r);if(W.isScalar(t))return n.Scalar?.(e,t,r);if(W.isAlias(t))return n.Alias?.(e,t,r)}function $d(e,t,n){let r=t[t.length-1];if(W.isCollection(r))r.items[e]=n;else if(W.isPair(r))e==="key"?r.key=n:r.value=n;else if(W.isDocument(r))r.contents=n;else{let s=W.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}Ti.visit=_r;Ti.visitAsync=qr});var Fi=C(Od=>{"use strict";var Ad=x(),Zg=gn(),ey={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},ty=e=>e.replace(/[!,[\]{}]/g,t=>ey[t]),yn=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),s=r.shift();switch(s){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[i,o]=r;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[i]=r;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let o=/^\d+\.\d+$/.test(i);return n(6,`Unsupported YAML version ${i}`,o),!1}}default:return n(0,`Unknown directive ${s}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,r,s]=t.match(/^(.*!)([^!]*)$/s);s||n(`The ${t} tag has no suffix`);let i=this.tags[r];if(i)try{return i+decodeURIComponent(s)}catch(o){return n(String(o)),null}return r==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[n,r]of Object.entries(this.tags))if(t.startsWith(r))return n+ty(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),s;if(t&&r.length>0&&Ad.isNode(t.contents)){let i={};Zg.visit(t.contents,(o,a)=>{Ad.isNode(a)&&a.tag&&(i[a.tag]=!0)}),s=Object.keys(i)}else s=[];for(let[i,o]of r)i==="!!"&&o==="tag:yaml.org,2002:"||(!t||s.some(a=>a.startsWith(o)))&&n.push(`%TAG ${i} ${o}`);return n.join(`
8
+ `)}};yn.defaultYaml={explicit:!1,version:"1.2"};yn.defaultTags={"!!":"tag:yaml.org,2002:"};Od.Directives=yn});var zr=C(wn=>{"use strict";var Cd=x(),ny=gn();function ry(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function jd(e){let t=new Set;return ny.visit(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function Nd(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function sy(e,t){let n=[],r=new Map,s=null;return{onAnchor:i=>{n.push(i),s??(s=jd(e));let o=Nd(t,s);return s.add(o),o},setAnchors:()=>{for(let i of n){let o=r.get(i);if(typeof o=="object"&&o.anchor&&(Cd.isScalar(o.node)||Cd.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:r}}wn.anchorIsValid=ry;wn.anchorNames=jd;wn.createNodeAnchors=sy;wn.findNewAnchor=Nd});var Li=C(Id=>{"use strict";function vn(e,t,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let s=0,i=r.length;s<i;++s){let o=r[s],a=vn(e,r,String(s),o);a===void 0?delete r[s]:a!==o&&(r[s]=a)}else if(r instanceof Map)for(let s of Array.from(r.keys())){let i=r.get(s),o=vn(e,r,s,i);o===void 0?r.delete(s):o!==i&&r.set(s,o)}else if(r instanceof Set)for(let s of Array.from(r)){let i=vn(e,r,s,s);i===void 0?r.delete(s):i!==s&&(r.delete(s),r.add(i))}else for(let[s,i]of Object.entries(r)){let o=vn(e,r,s,i);o===void 0?delete r[s]:o!==i&&(r[s]=o)}return e.call(t,n,r)}Id.applyReviver=vn});var Je=C(Pd=>{"use strict";var iy=x();function Dd(e,t,n){if(Array.isArray(e))return e.map((r,s)=>Dd(r,String(s),n));if(e&&typeof e.toJSON=="function"){if(!n||!iy.hasAnchor(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=i=>{r.res=i,delete n.onCreate};let s=e.toJSON(t,n);return n.onCreate&&n.onCreate(s),s}return typeof e=="bigint"&&!n?.keep?Number(e):e}Pd.toJS=Dd});var Br=C(Fd=>{"use strict";var oy=Li(),Td=x(),ay=Je(),xi=class{constructor(t){Object.defineProperty(this,Td.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:r,onAnchor:s,reviver:i}={}){if(!Td.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=ay.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?oy.applyReviver(i,{"":a},"",a):a}};Fd.NodeBase=xi});var kn=C(Ld=>{"use strict";var cy=zr(),ly=gn(),Mt=x(),uy=Br(),dy=Je(),Mi=class extends uy.NodeBase{constructor(t){super(Mt.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],ly.visit(t,{Node:(i,o)=>{(Mt.isAlias(o)||Mt.hasAnchor(o))&&r.push(o)}}),n&&(n.aliasResolveCache=r));let s;for(let i of r){if(i===this)break;i.anchor===this.source&&(s=i)}if(s&&n){let{anchors:i,doc:o,maxAliasCount:a}=n,c=i.get(s);if(c||(dy.toJS(s,null,n),c=i.get(s)),c?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=Kr(o,s,i)),c.count*c.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}}return s}toJSON(t,n){if(!n)return{source:this.source};let r=this.resolve(n.doc,n);if(!r){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(s)}return n.anchors.get(r).res}toString(t,n,r){let s=`*${this.source}`;if(t){if(cy.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(t.implicitKey)return`${s} `}return s}};function Kr(e,t,n){if(Mt.isAlias(t)){let r=t.resolve(e),s=n&&r&&n.get(r);return s?s.count*s.aliasCount:0}else if(Mt.isCollection(t)){let r=0;for(let s of t.items){let i=Kr(e,s,n);i>r&&(r=i)}return r}else if(Mt.isPair(t)){let r=Kr(e,t.key,n),s=Kr(e,t.value,n);return Math.max(r,s)}return 1}Ld.Alias=Mi});var V=C(_i=>{"use strict";var fy=x(),py=Br(),hy=Je(),my=e=>!e||typeof e!="function"&&typeof e!="object",Ye=class extends py.NodeBase{constructor(t){super(fy.SCALAR),this.value=t}toJSON(t,n){return n?.keep?this.value:hy.toJS(this.value,t,n)}toString(){return String(this.value)}};Ye.BLOCK_FOLDED="BLOCK_FOLDED";Ye.BLOCK_LITERAL="BLOCK_LITERAL";Ye.PLAIN="PLAIN";Ye.QUOTE_DOUBLE="QUOTE_DOUBLE";Ye.QUOTE_SINGLE="QUOTE_SINGLE";_i.Scalar=Ye;_i.isScalarValue=my});var bn=C(Md=>{"use strict";var gy=kn(),ft=x(),xd=V(),yy="tag:yaml.org,2002:";function wy(e,t,n){if(t){let r=n.filter(i=>i.tag===t),s=r.find(i=>!i.format)??r[0];if(!s)throw new Error(`Tag ${t} not found`);return s}return n.find(r=>r.identify?.(e)&&!r.format)}function vy(e,t,n){if(ft.isDocument(e)&&(e=e.contents),ft.isNode(e))return e;if(ft.isPair(e)){let d=n.schema[ft.MAP].createNode?.(n.schema,null,n);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:s,onTagObj:i,schema:o,sourceObjects:a}=n,c;if(r&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=s(e)),new gy.Alias(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=yy+t.slice(2));let l=wy(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new xd.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[ft.MAP]:Symbol.iterator in Object(e)?o[ft.SEQ]:o[ft.MAP]}i&&(i(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,e,n):new xd.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Md.createNode=vy});var Vr=C(Ur=>{"use strict";var ky=bn(),$e=x(),by=Br();function qi(e,t,n){let r=n;for(let s=t.length-1;s>=0;--s){let i=t[s];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let o=[];o[i]=r,r=o}else r=new Map([[i,r]])}return ky.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var _d=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,zi=class extends by.NodeBase{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(r=>$e.isNode(r)||$e.isPair(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(_d(t))this.add(n);else{let[r,...s]=t,i=this.get(r,!0);if($e.isCollection(i))i.addIn(s,n);else if(i===void 0&&this.schema)this.set(r,qi(this.schema,s,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`)}}deleteIn(t){let[n,...r]=t;if(r.length===0)return this.delete(n);let s=this.get(n,!0);if($e.isCollection(s))return s.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(t,n){let[r,...s]=t,i=this.get(r,!0);return s.length===0?!n&&$e.isScalar(i)?i.value:i:$e.isCollection(i)?i.getIn(s,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!$e.isPair(n))return!1;let r=n.value;return r==null||t&&$e.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[n,...r]=t;if(r.length===0)return this.has(n);let s=this.get(n,!0);return $e.isCollection(s)?s.hasIn(r):!1}setIn(t,n){let[r,...s]=t;if(s.length===0)this.set(r,n);else{let i=this.get(r,!0);if($e.isCollection(i))i.setIn(s,n);else if(i===void 0&&this.schema)this.set(r,qi(this.schema,s,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`)}}};Ur.Collection=zi;Ur.collectionFromPath=qi;Ur.isEmptyPath=_d});var En=C(Wr=>{"use strict";var Ey=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Bi(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Sy=(e,t,n)=>e.endsWith(`
9
+ `)?Bi(n,t):n.includes(`
10
10
  `)?`
11
- `+_i(n,t):(e.endsWith(" ")?"":" ")+n;Ur.indentComment=_i;Ur.lineComment=my;Ur.stringifyComment=hy});var Td=C(Sn=>{"use strict";var gy="flow",qi="block",Vr="quoted";function yy(e,t,n="flow",{indentAtStart:r,lineWidth:s=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!s||s<0)return e;s<i&&(i=0);let c=Math.max(1+i,1+s-t.length);if(e.length<=c)return e;let l=[],u={},d=s-t.length;typeof r=="number"&&(r>s-Math.max(2,i)?l.push(0):d=s-r);let f,g,y=!1,m=-1,h=-1,w=-1;n===qi&&(m=Dd(e,m,t.length),m!==-1&&(d=m+c));for(let k;k=e[m+=1];){if(n===Vr&&k==="\\"){switch(h=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}w=m}if(k===`
12
- `)n===qi&&(m=Dd(e,m,t.length)),d=m+t.length+c,f=void 0;else{if(k===" "&&g&&g!==" "&&g!==`
13
- `&&g!==" "){let b=e[m+1];b&&b!==" "&&b!==`
14
- `&&b!==" "&&(f=m)}if(m>=d)if(f)l.push(f),d=f+c,f=void 0;else if(n===Vr){for(;g===" "||g===" ";)g=k,k=e[m+=1],y=!0;let b=m>w+1?m-2:h-1;if(u[b])return e;l.push(b),u[b]=!0,d=b+c,f=void 0}else y=!0}g=k}if(y&&a&&a(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let k=0;k<l.length;++k){let b=l[k],S=l[k+1]||e.length;b===0?v=`
15
- ${t}${e.slice(0,S)}`:(n===Vr&&u[b]&&(v+=`${e[b]}\\`),v+=`
16
- ${t}${e.slice(b+1,S)}`)}return v}function Dd(e,t,n){let r=t,s=t+1,i=e[s];for(;i===" "||i===" ";)if(t<s+n)i=e[++t];else{do i=e[++t];while(i&&i!==`
17
- `);r=t,s=t+1,i=e[s]}return r}Sn.FOLD_BLOCK=qi;Sn.FOLD_FLOW=gy;Sn.FOLD_QUOTED=Vr;Sn.foldFlowLines=yy});var $n=C(Pd=>{"use strict";var we=V(),Ye=Td(),Jr=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Yr=e=>/^(%|---|\.\.\.)/m.test(e);function wy(e,t,n){if(!t||t<0)return!1;let r=t-n,s=e.length;if(s<=r)return!1;for(let i=0,o=0;i<s;++i)if(e[i]===`
18
- `){if(i-o>r)return!0;if(o=i+1,s-o<=r)return!1}return!0}function Rn(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,s=t.options.doubleQuotedMinMultiLineLength,i=t.indent||(Yr(e)?" ":""),o="",a=0;for(let c=0,l=n[c];l;l=n[++c])if(l===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(o+=n.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(n[c+1]){case"u":{o+=n.slice(a,c);let u=n.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(r||n[c+2]==='"'||n.length<s)c+=1;else{for(o+=n.slice(a,c)+`
11
+ `+Bi(n,t):(e.endsWith(" ")?"":" ")+n;Wr.indentComment=Bi;Wr.lineComment=Sy;Wr.stringifyComment=Ey});var zd=C(Sn=>{"use strict";var Ry="flow",Ki="block",Jr="quoted";function $y(e,t,n="flow",{indentAtStart:r,lineWidth:s=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!s||s<0)return e;s<i&&(i=0);let c=Math.max(1+i,1+s-t.length);if(e.length<=c)return e;let l=[],u={},d=s-t.length;typeof r=="number"&&(r>s-Math.max(2,i)?l.push(0):d=s-r);let f,y,g=!1,m=-1,h=-1,w=-1;n===Ki&&(m=qd(e,m,t.length),m!==-1&&(d=m+c));for(let k;k=e[m+=1];){if(n===Jr&&k==="\\"){switch(h=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}w=m}if(k===`
12
+ `)n===Ki&&(m=qd(e,m,t.length)),d=m+t.length+c,f=void 0;else{if(k===" "&&y&&y!==" "&&y!==`
13
+ `&&y!==" "){let E=e[m+1];E&&E!==" "&&E!==`
14
+ `&&E!==" "&&(f=m)}if(m>=d)if(f)l.push(f),d=f+c,f=void 0;else if(n===Jr){for(;y===" "||y===" ";)y=k,k=e[m+=1],g=!0;let E=m>w+1?m-2:h-1;if(u[E])return e;l.push(E),u[E]=!0,d=E+c,f=void 0}else g=!0}y=k}if(g&&a&&a(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let k=0;k<l.length;++k){let E=l[k],S=l[k+1]||e.length;E===0?v=`
15
+ ${t}${e.slice(0,S)}`:(n===Jr&&u[E]&&(v+=`${e[E]}\\`),v+=`
16
+ ${t}${e.slice(E+1,S)}`)}return v}function qd(e,t,n){let r=t,s=t+1,i=e[s];for(;i===" "||i===" ";)if(t<s+n)i=e[++t];else{do i=e[++t];while(i&&i!==`
17
+ `);r=t,s=t+1,i=e[s]}return r}Sn.FOLD_BLOCK=Ki;Sn.FOLD_FLOW=Ry;Sn.FOLD_QUOTED=Jr;Sn.foldFlowLines=$y});var $n=C(Bd=>{"use strict";var ye=V(),Ge=zd(),Gr=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Hr=e=>/^(%|---|\.\.\.)/m.test(e);function Ay(e,t,n){if(!t||t<0)return!1;let r=t-n,s=e.length;if(s<=r)return!1;for(let i=0,o=0;i<s;++i)if(e[i]===`
18
+ `){if(i-o>r)return!0;if(o=i+1,s-o<=r)return!1}return!0}function Rn(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,s=t.options.doubleQuotedMinMultiLineLength,i=t.indent||(Hr(e)?" ":""),o="",a=0;for(let c=0,l=n[c];l;l=n[++c])if(l===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(o+=n.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(n[c+1]){case"u":{o+=n.slice(a,c);let u=n.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(r||n[c+2]==='"'||n.length<s)c+=1;else{for(o+=n.slice(a,c)+`
19
19
 
20
20
  `;n[c+2]==="\\"&&n[c+3]==="n"&&n[c+4]!=='"';)o+=`
21
- `,c+=2;o+=i,n[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+n.slice(a):n,r?o:Ye.foldFlowLines(o,i,Ye.FOLD_QUOTED,Jr(t,!1))}function zi(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
22
- `)||/[ \t]\n|\n[ \t]/.test(e))return Rn(e,t);let n=t.indent||(Yr(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
23
- ${n}`)+"'";return t.implicitKey?r:Ye.foldFlowLines(r,n,Ye.FOLD_FLOW,Jr(t,!1))}function xt(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=Rn;else{let s=e.includes('"'),i=e.includes("'");s&&!i?r=zi:i&&!s?r=Rn:r=n?zi:Rn}return r(e,t)}var Bi;try{Bi=new RegExp(`(^|(?<!
21
+ `,c+=2;o+=i,n[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+n.slice(a):n,r?o:Ge.foldFlowLines(o,i,Ge.FOLD_QUOTED,Gr(t,!1))}function Ui(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
22
+ `)||/[ \t]\n|\n[ \t]/.test(e))return Rn(e,t);let n=t.indent||(Hr(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
23
+ ${n}`)+"'";return t.implicitKey?r:Ge.foldFlowLines(r,n,Ge.FOLD_FLOW,Gr(t,!1))}function _t(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=Rn;else{let s=e.includes('"'),i=e.includes("'");s&&!i?r=Ui:i&&!s?r=Rn:r=n?Ui:Rn}return r(e,t)}var Vi;try{Vi=new RegExp(`(^|(?<!
24
24
  ))
25
25
  +(?!
26
- |$)`,"g")}catch{Bi=/\n+(?!\n|$)/g}function Wr({comment:e,type:t,value:n},r,s,i){let{blockQuote:o,commentString:a,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return xt(n,r);let l=r.indent||(r.forceBlockIndent||Yr(n)?" ":""),u=o==="literal"?!0:o==="folded"||t===we.Scalar.BLOCK_FOLDED?!1:t===we.Scalar.BLOCK_LITERAL?!0:!wy(n,c,l.length);if(!n)return u?`|
26
+ |$)`,"g")}catch{Vi=/\n+(?!\n|$)/g}function Yr({comment:e,type:t,value:n},r,s,i){let{blockQuote:o,commentString:a,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return _t(n,r);let l=r.indent||(r.forceBlockIndent||Hr(n)?" ":""),u=o==="literal"?!0:o==="folded"||t===ye.Scalar.BLOCK_FOLDED?!1:t===ye.Scalar.BLOCK_LITERAL?!0:!Ay(n,c,l.length);if(!n)return u?`|
27
27
  `:`>
28
28
  `;let d,f;for(f=n.length;f>0;--f){let S=n[f-1];if(S!==`
29
- `&&S!==" "&&S!==" ")break}let g=n.substring(f),y=g.indexOf(`
30
- `);y===-1?d="-":n===g||y!==g.length-1?(d="+",i&&i()):d="",g&&(n=n.slice(0,-g.length),g[g.length-1]===`
31
- `&&(g=g.slice(0,-1)),g=g.replace(Bi,`$&${l}`));let m=!1,h,w=-1;for(h=0;h<n.length;++h){let S=n[h];if(S===" ")m=!0;else if(S===`
32
- `)w=h;else break}let v=n.substring(0,w<h?w+1:h);v&&(n=n.substring(v.length),v=v.replace(/\n+/g,`$&${l}`));let b=(m?l?"2":"1":"")+d;if(e&&(b+=" "+a(e.replace(/ ?[\r\n]+/g," ")),s&&s()),!u){let S=n.replace(/\n+/g,`
33
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),$=!1,E=Jr(r,!0);o!=="folded"&&t!==we.Scalar.BLOCK_FOLDED&&(E.onOverflow=()=>{$=!0});let R=Ye.foldFlowLines(`${v}${S}${g}`,l,Ye.FOLD_BLOCK,E);if(!$)return`>${b}
34
- ${l}${R}`}return n=n.replace(/\n+/g,`$&${l}`),`|${b}
35
- ${l}${v}${n}${g}`}function vy(e,t,n,r){let{type:s,value:i}=e,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=t;if(a&&i.includes(`
36
- `)||u&&/[[\]{},]/.test(i))return xt(i,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||u||!i.includes(`
37
- `)?xt(i,t):Wr(e,t,n,r);if(!a&&!u&&s!==we.Scalar.PLAIN&&i.includes(`
38
- `))return Wr(e,t,n,r);if(Yr(i)){if(c==="")return t.forceBlockIndent=!0,Wr(e,t,n,r);if(a&&c===l)return xt(i,t)}let d=i.replace(/\n+/g,`$&
39
- ${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:g,tags:y}=t.doc.schema;if(y.some(f)||g?.some(f))return xt(i,t)}return a?d:Ye.foldFlowLines(d,c,Ye.FOLD_FLOW,Jr(t,!1))}function ky(e,t,n,r){let{implicitKey:s,inFlow:i}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;a!==we.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=we.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case we.Scalar.BLOCK_FOLDED:case we.Scalar.BLOCK_LITERAL:return s||i?xt(o.value,t):Wr(o,t,n,r);case we.Scalar.QUOTE_DOUBLE:return Rn(o.value,t);case we.Scalar.QUOTE_SINGLE:return zi(o.value,t);case we.Scalar.PLAIN:return vy(o,t,n,r);default:return null}},l=c(a);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=s&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Pd.stringifyString=ky});var An=C(Ki=>{"use strict";var by=_r(),Ge=x(),Ey=En(),Sy=$n();function Ry(e,t){let n=Object.assign({blockQuote:!0,commentString:Ey.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function $y(e,t){if(t.tag){let s=e.filter(i=>i.tag===t.tag);if(s.length>0)return s.find(i=>i.format===t.format)??s[0]}let n,r;if(Ge.isScalar(t)){r=t.value;let s=e.filter(i=>i.identify?.(r));if(s.length>1){let i=s.filter(o=>o.test);i.length>0&&(s=i)}n=s.find(i=>i.format===t.format)??s.find(i=>!i.format)}else r=t,n=e.find(s=>s.nodeClass&&r instanceof s.nodeClass);if(!n){let s=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${s} value`)}return n}function Ay(e,t,{anchors:n,doc:r}){if(!r.directives)return"";let s=[],i=(Ge.isScalar(e)||Ge.isCollection(e))&&e.anchor;i&&by.anchorIsValid(i)&&(n.add(i),s.push(`&${i}`));let o=e.tag??(t.default?null:t.tag);return o&&s.push(r.directives.tagString(o)),s.join(" ")}function Oy(e,t,n,r){if(Ge.isPair(e))return e.toString(t,n,r);if(Ge.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let s,i=Ge.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>s=c});s??(s=$y(t.doc.schema.tags,i));let o=Ay(i,s,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let a=typeof s.stringify=="function"?s.stringify(i,t,n,r):Ge.isScalar(i)?Sy.stringifyString(i,t,n,r):i.toString(t,n,r);return o?Ge.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
40
- ${t.indent}${a}`:a}Ki.createStringifyContext=Ry;Ki.stringify=Oy});var Md=C(xd=>{"use strict";var Ne=x(),Ld=V(),Fd=An(),On=En();function Cy({key:e,value:t},n,r,s){let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=Ne.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ne.isCollection(e)||!Ne.isNode(e)&&typeof e=="object"){let E="With simple keys, collection cannot be used as a key value";throw new Error(E)}}let g=!d&&(!e||f&&t==null&&!n.inFlow||Ne.isCollection(e)||(Ne.isScalar(e)?e.type===Ld.Scalar.BLOCK_FOLDED||e.type===Ld.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!g&&(d||!i),indent:a+c});let y=!1,m=!1,h=Fd.stringify(e,n,()=>y=!0,()=>m=!0);if(!g&&!n.inFlow&&h.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(n.inFlow){if(i||t==null)return y&&r&&r(),h===""?"?":g?`? ${h}`:h}else if(i&&!d||t==null&&g)return h=`? ${h}`,f&&!y?h+=On.lineComment(h,n.indent,l(f)):m&&s&&s(),h;y&&(f=null),g?(f&&(h+=On.lineComment(h,n.indent,l(f))),h=`? ${h}
41
- ${a}:`):(h=`${h}:`,f&&(h+=On.lineComment(h,n.indent,l(f))));let w,v,k;Ne.isNode(t)?(w=!!t.spaceBefore,v=t.commentBefore,k=t.comment):(w=!1,v=null,k=null,t&&typeof t=="object"&&(t=o.createNode(t))),n.implicitKey=!1,!g&&!f&&Ne.isScalar(t)&&(n.indentAtStart=h.length+1),m=!1,!u&&c.length>=2&&!n.inFlow&&!g&&Ne.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,S=Fd.stringify(t,n,()=>b=!0,()=>m=!0),$=" ";if(f||w||v){if($=w?`
42
- `:"",v){let E=l(v);$+=`
43
- ${On.indentComment(E,n.indent)}`}S===""&&!n.inFlow?$===`
44
- `&&k&&($=`
29
+ `&&S!==" "&&S!==" ")break}let y=n.substring(f),g=y.indexOf(`
30
+ `);g===-1?d="-":n===y||g!==y.length-1?(d="+",i&&i()):d="",y&&(n=n.slice(0,-y.length),y[y.length-1]===`
31
+ `&&(y=y.slice(0,-1)),y=y.replace(Vi,`$&${l}`));let m=!1,h,w=-1;for(h=0;h<n.length;++h){let S=n[h];if(S===" ")m=!0;else if(S===`
32
+ `)w=h;else break}let v=n.substring(0,w<h?w+1:h);v&&(n=n.substring(v.length),v=v.replace(/\n+/g,`$&${l}`));let E=(m?l?"2":"1":"")+d;if(e&&(E+=" "+a(e.replace(/ ?[\r\n]+/g," ")),s&&s()),!u){let S=n.replace(/\n+/g,`
33
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),R=!1,b=Gr(r,!0);o!=="folded"&&t!==ye.Scalar.BLOCK_FOLDED&&(b.onOverflow=()=>{R=!0});let $=Ge.foldFlowLines(`${v}${S}${y}`,l,Ge.FOLD_BLOCK,b);if(!R)return`>${E}
34
+ ${l}${$}`}return n=n.replace(/\n+/g,`$&${l}`),`|${E}
35
+ ${l}${v}${n}${y}`}function Oy(e,t,n,r){let{type:s,value:i}=e,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=t;if(a&&i.includes(`
36
+ `)||u&&/[[\]{},]/.test(i))return _t(i,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||u||!i.includes(`
37
+ `)?_t(i,t):Yr(e,t,n,r);if(!a&&!u&&s!==ye.Scalar.PLAIN&&i.includes(`
38
+ `))return Yr(e,t,n,r);if(Hr(i)){if(c==="")return t.forceBlockIndent=!0,Yr(e,t,n,r);if(a&&c===l)return _t(i,t)}let d=i.replace(/\n+/g,`$&
39
+ ${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:y,tags:g}=t.doc.schema;if(g.some(f)||y?.some(f))return _t(i,t)}return a?d:Ge.foldFlowLines(d,c,Ge.FOLD_FLOW,Gr(t,!1))}function Cy(e,t,n,r){let{implicitKey:s,inFlow:i}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;a!==ye.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=ye.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case ye.Scalar.BLOCK_FOLDED:case ye.Scalar.BLOCK_LITERAL:return s||i?_t(o.value,t):Yr(o,t,n,r);case ye.Scalar.QUOTE_DOUBLE:return Rn(o.value,t);case ye.Scalar.QUOTE_SINGLE:return Ui(o.value,t);case ye.Scalar.PLAIN:return Oy(o,t,n,r);default:return null}},l=c(a);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=s&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Bd.stringifyString=Cy});var An=C(Wi=>{"use strict";var jy=zr(),He=x(),Ny=En(),Iy=$n();function Dy(e,t){let n=Object.assign({blockQuote:!0,commentString:Ny.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function Py(e,t){if(t.tag){let s=e.filter(i=>i.tag===t.tag);if(s.length>0)return s.find(i=>i.format===t.format)??s[0]}let n,r;if(He.isScalar(t)){r=t.value;let s=e.filter(i=>i.identify?.(r));if(s.length>1){let i=s.filter(o=>o.test);i.length>0&&(s=i)}n=s.find(i=>i.format===t.format)??s.find(i=>!i.format)}else r=t,n=e.find(s=>s.nodeClass&&r instanceof s.nodeClass);if(!n){let s=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${s} value`)}return n}function Ty(e,t,{anchors:n,doc:r}){if(!r.directives)return"";let s=[],i=(He.isScalar(e)||He.isCollection(e))&&e.anchor;i&&jy.anchorIsValid(i)&&(n.add(i),s.push(`&${i}`));let o=e.tag??(t.default?null:t.tag);return o&&s.push(r.directives.tagString(o)),s.join(" ")}function Fy(e,t,n,r){if(He.isPair(e))return e.toString(t,n,r);if(He.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let s,i=He.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>s=c});s??(s=Py(t.doc.schema.tags,i));let o=Ty(i,s,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let a=typeof s.stringify=="function"?s.stringify(i,t,n,r):He.isScalar(i)?Iy.stringifyString(i,t,n,r):i.toString(t,n,r);return o?He.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
40
+ ${t.indent}${a}`:a}Wi.createStringifyContext=Dy;Wi.stringify=Fy});var Wd=C(Vd=>{"use strict";var Ne=x(),Kd=V(),Ud=An(),On=En();function Ly({key:e,value:t},n,r,s){let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=Ne.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ne.isCollection(e)||!Ne.isNode(e)&&typeof e=="object"){let b="With simple keys, collection cannot be used as a key value";throw new Error(b)}}let y=!d&&(!e||f&&t==null&&!n.inFlow||Ne.isCollection(e)||(Ne.isScalar(e)?e.type===Kd.Scalar.BLOCK_FOLDED||e.type===Kd.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!y&&(d||!i),indent:a+c});let g=!1,m=!1,h=Ud.stringify(e,n,()=>g=!0,()=>m=!0);if(!y&&!n.inFlow&&h.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");y=!0}if(n.inFlow){if(i||t==null)return g&&r&&r(),h===""?"?":y?`? ${h}`:h}else if(i&&!d||t==null&&y)return h=`? ${h}`,f&&!g?h+=On.lineComment(h,n.indent,l(f)):m&&s&&s(),h;g&&(f=null),y?(f&&(h+=On.lineComment(h,n.indent,l(f))),h=`? ${h}
41
+ ${a}:`):(h=`${h}:`,f&&(h+=On.lineComment(h,n.indent,l(f))));let w,v,k;Ne.isNode(t)?(w=!!t.spaceBefore,v=t.commentBefore,k=t.comment):(w=!1,v=null,k=null,t&&typeof t=="object"&&(t=o.createNode(t))),n.implicitKey=!1,!y&&!f&&Ne.isScalar(t)&&(n.indentAtStart=h.length+1),m=!1,!u&&c.length>=2&&!n.inFlow&&!y&&Ne.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let E=!1,S=Ud.stringify(t,n,()=>E=!0,()=>m=!0),R=" ";if(f||w||v){if(R=w?`
42
+ `:"",v){let b=l(v);R+=`
43
+ ${On.indentComment(b,n.indent)}`}S===""&&!n.inFlow?R===`
44
+ `&&k&&(R=`
45
45
 
46
- `):$+=`
47
- ${n.indent}`}else if(!g&&Ne.isCollection(t)){let E=S[0],R=S.indexOf(`
48
- `),j=R!==-1,D=n.inFlow??t.flow??t.items.length===0;if(j||!D){let N=!1;if(j&&(E==="&"||E==="!")){let P=S.indexOf(" ");E==="&"&&P!==-1&&P<R&&S[P+1]==="!"&&(P=S.indexOf(" ",P+1)),(P===-1||R<P)&&(N=!0)}N||($=`
46
+ `):R+=`
47
+ ${n.indent}`}else if(!y&&Ne.isCollection(t)){let b=S[0],$=S.indexOf(`
48
+ `),j=$!==-1,D=n.inFlow??t.flow??t.items.length===0;if(j||!D){let T=!1;if(j&&(b==="&"||b==="!")){let I=S.indexOf(" ");b==="&"&&I!==-1&&I<$&&S[I+1]==="!"&&(I=S.indexOf(" ",I+1)),(I===-1||$<I)&&(T=!0)}T||(R=`
49
49
  ${n.indent}`)}}else(S===""||S[0]===`
50
- `)&&($="");return h+=$+S,n.inFlow?b&&r&&r():k&&!b?h+=On.lineComment(h,n.indent,l(k)):m&&s&&s(),h}xd.stringifyPair=Cy});var Vi=C(Ui=>{"use strict";var _d=er("process");function jy(e,...t){e==="debug"&&console.log(...t)}function Ny(e,t){(e==="debug"||e==="warn")&&(typeof _d.emitWarning=="function"?_d.emitWarning(t):console.warn(t))}Ui.debug=jy;Ui.warn=Ny});var Zr=C(Xr=>{"use strict";var Qr=x(),qd=V(),Gr="<<",Hr={identify:e=>e===Gr||typeof e=="symbol"&&e.description===Gr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new qd.Scalar(Symbol(Gr)),{addToJSMap:zd}),stringify:()=>Gr},Iy=(e,t)=>(Hr.identify(t)||Qr.isScalar(t)&&(!t.type||t.type===qd.Scalar.PLAIN)&&Hr.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===Hr.tag&&n.default);function zd(e,t,n){let r=Bd(e,n);if(Qr.isSeq(r))for(let s of r.items)Wi(e,t,s);else if(Array.isArray(r))for(let s of r)Wi(e,t,s);else Wi(e,t,r)}function Wi(e,t,n){let r=Bd(e,n);if(!Qr.isMap(r))throw new Error("Merge sources must be maps or map aliases");let s=r.toJSON(null,e,Map);for(let[i,o]of s)t instanceof Map?t.has(i)||t.set(i,o):t instanceof Set?t.add(i):Object.prototype.hasOwnProperty.call(t,i)||Object.defineProperty(t,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Bd(e,t){return e&&Qr.isAlias(t)?t.resolve(e.doc,e):t}Xr.addMergeToJSMap=zd;Xr.isMergeKey=Iy;Xr.merge=Hr});var Yi=C(Vd=>{"use strict";var Dy=Vi(),Kd=Zr(),Ty=An(),Ud=x(),Ji=We();function Py(e,t,{key:n,value:r}){if(Ud.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(Kd.isMergeKey(e,n))Kd.addMergeToJSMap(e,t,r);else{let s=Ji.toJS(n,"",e);if(t instanceof Map)t.set(s,Ji.toJS(r,s,e));else if(t instanceof Set)t.add(s);else{let i=Ly(n,s,e),o=Ji.toJS(r,i,e);i in t?Object.defineProperty(t,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[i]=o}}return t}function Ly(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(Ud.isNode(e)&&n?.doc){let r=Ty.createStringifyContext(n.doc,{});r.anchors=new Set;for(let i of n.anchors.keys())r.anchors.add(i.anchor);r.inFlow=!0,r.inStringifyKey=!0;let s=e.toString(r);if(!n.mapKeyWarned){let i=JSON.stringify(s);i.length>40&&(i=i.substring(0,36)+'..."'),Dy.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return s}return JSON.stringify(t)}Vd.addPairToJSMap=Py});var He=C(Gi=>{"use strict";var Wd=bn(),Fy=Md(),xy=Yi(),es=x();function My(e,t,n){let r=Wd.createNode(e,void 0,n),s=Wd.createNode(t,void 0,n);return new ts(r,s)}var ts=class e{constructor(t,n=null){Object.defineProperty(this,es.NODE_TYPE,{value:es.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return es.isNode(n)&&(n=n.clone(t)),es.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return xy.addPairToJSMap(n,r,this)}toString(t,n,r){return t?.doc?Fy.stringifyPair(this,t,n,r):JSON.stringify(this)}};Gi.Pair=ts;Gi.createPair=My});var Hi=C(Yd=>{"use strict";var dt=x(),Jd=An(),ns=En();function _y(e,t,n){return(t.inFlow??e.flow?zy:qy)(e,t,n)}function qy({comment:e,items:t},n,{blockItemPrefix:r,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:i,type:null}),d=!1,f=[];for(let y=0;y<t.length;++y){let m=t[y],h=null;if(dt.isNode(m))!d&&m.spaceBefore&&f.push(""),rs(n,f,m.commentBefore,d),m.comment&&(h=m.comment);else if(dt.isPair(m)){let v=dt.isNode(m.key)?m.key:null;v&&(!d&&v.spaceBefore&&f.push(""),rs(n,f,v.commentBefore,d))}d=!1;let w=Jd.stringify(m,u,()=>h=null,()=>d=!0);h&&(w+=ns.lineComment(w,i,l(h))),d&&h&&(d=!1),f.push(r+w)}let g;if(f.length===0)g=s.start+s.end;else{g=f[0];for(let y=1;y<f.length;++y){let m=f[y];g+=m?`
50
+ `)&&(R="");return h+=R+S,n.inFlow?E&&r&&r():k&&!E?h+=On.lineComment(h,n.indent,l(k)):m&&s&&s(),h}Vd.stringifyPair=Ly});var Yi=C(Ji=>{"use strict";var Jd=er("process");function xy(e,...t){e==="debug"&&console.log(...t)}function My(e,t){(e==="debug"||e==="warn")&&(typeof Jd.emitWarning=="function"?Jd.emitWarning(t):console.warn(t))}Ji.debug=xy;Ji.warn=My});var ts=C(es=>{"use strict";var Zr=x(),Yd=V(),Qr="<<",Xr={identify:e=>e===Qr||typeof e=="symbol"&&e.description===Qr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Yd.Scalar(Symbol(Qr)),{addToJSMap:Gd}),stringify:()=>Qr},_y=(e,t)=>(Xr.identify(t)||Zr.isScalar(t)&&(!t.type||t.type===Yd.Scalar.PLAIN)&&Xr.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===Xr.tag&&n.default);function Gd(e,t,n){let r=Hd(e,n);if(Zr.isSeq(r))for(let s of r.items)Gi(e,t,s);else if(Array.isArray(r))for(let s of r)Gi(e,t,s);else Gi(e,t,r)}function Gi(e,t,n){let r=Hd(e,n);if(!Zr.isMap(r))throw new Error("Merge sources must be maps or map aliases");let s=r.toJSON(null,e,Map);for(let[i,o]of s)t instanceof Map?t.has(i)||t.set(i,o):t instanceof Set?t.add(i):Object.prototype.hasOwnProperty.call(t,i)||Object.defineProperty(t,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Hd(e,t){return e&&Zr.isAlias(t)?t.resolve(e.doc,e):t}es.addMergeToJSMap=Gd;es.isMergeKey=_y;es.merge=Xr});var Qi=C(Zd=>{"use strict";var qy=Yi(),Qd=ts(),zy=An(),Xd=x(),Hi=Je();function By(e,t,{key:n,value:r}){if(Xd.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(Qd.isMergeKey(e,n))Qd.addMergeToJSMap(e,t,r);else{let s=Hi.toJS(n,"",e);if(t instanceof Map)t.set(s,Hi.toJS(r,s,e));else if(t instanceof Set)t.add(s);else{let i=Ky(n,s,e),o=Hi.toJS(r,i,e);i in t?Object.defineProperty(t,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[i]=o}}return t}function Ky(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(Xd.isNode(e)&&n?.doc){let r=zy.createStringifyContext(n.doc,{});r.anchors=new Set;for(let i of n.anchors.keys())r.anchors.add(i.anchor);r.inFlow=!0,r.inStringifyKey=!0;let s=e.toString(r);if(!n.mapKeyWarned){let i=JSON.stringify(s);i.length>40&&(i=i.substring(0,36)+'..."'),qy.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return s}return JSON.stringify(t)}Zd.addPairToJSMap=By});var Qe=C(Xi=>{"use strict";var ef=bn(),Uy=Wd(),Vy=Qi(),ns=x();function Wy(e,t,n){let r=ef.createNode(e,void 0,n),s=ef.createNode(t,void 0,n);return new rs(r,s)}var rs=class e{constructor(t,n=null){Object.defineProperty(this,ns.NODE_TYPE,{value:ns.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return ns.isNode(n)&&(n=n.clone(t)),ns.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return Vy.addPairToJSMap(n,r,this)}toString(t,n,r){return t?.doc?Uy.stringifyPair(this,t,n,r):JSON.stringify(this)}};Xi.Pair=rs;Xi.createPair=Wy});var Zi=C(nf=>{"use strict";var pt=x(),tf=An(),ss=En();function Jy(e,t,n){return(t.inFlow??e.flow?Gy:Yy)(e,t,n)}function Yy({comment:e,items:t},n,{blockItemPrefix:r,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:i,type:null}),d=!1,f=[];for(let g=0;g<t.length;++g){let m=t[g],h=null;if(pt.isNode(m))!d&&m.spaceBefore&&f.push(""),is(n,f,m.commentBefore,d),m.comment&&(h=m.comment);else if(pt.isPair(m)){let v=pt.isNode(m.key)?m.key:null;v&&(!d&&v.spaceBefore&&f.push(""),is(n,f,v.commentBefore,d))}d=!1;let w=tf.stringify(m,u,()=>h=null,()=>d=!0);h&&(w+=ss.lineComment(w,i,l(h))),d&&h&&(d=!1),f.push(r+w)}let y;if(f.length===0)y=s.start+s.end;else{y=f[0];for(let g=1;g<f.length;++g){let m=f[g];y+=m?`
51
51
  ${c}${m}`:`
52
- `}}return e?(g+=`
53
- `+ns.indentComment(l(e),c),a&&a()):d&&o&&o(),g}function zy({items:e},t,{flowChars:n,itemIndent:r}){let{indent:s,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=t;r+=i;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let y=0;y<e.length;++y){let m=e[y],h=null;if(dt.isNode(m))m.spaceBefore&&d.push(""),rs(t,d,m.commentBefore,!1),m.comment&&(h=m.comment);else if(dt.isPair(m)){let v=dt.isNode(m.key)?m.key:null;v&&(v.spaceBefore&&d.push(""),rs(t,d,v.commentBefore,!1),v.comment&&(l=!0));let k=dt.isNode(m.value)?m.value:null;k?(k.comment&&(h=k.comment),k.commentBefore&&(l=!0)):m.value==null&&v?.comment&&(h=v.comment)}h&&(l=!0);let w=Jd.stringify(m,c,()=>h=null);l||(l=d.length>u||w.includes(`
54
- `)),y<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((v,k)=>v+k.length+2,2)+(w.length+2)>t.options.lineWidth)),l&&(w+=",")),h&&(w+=ns.lineComment(w,r,a(h))),d.push(w),u=d.length}let{start:f,end:g}=n;if(d.length===0)return f+g;if(!l){let y=d.reduce((m,h)=>m+h.length+2,2);l=t.options.lineWidth>0&&y>t.options.lineWidth}if(l){let y=f;for(let m of d)y+=m?`
52
+ `}}return e?(y+=`
53
+ `+ss.indentComment(l(e),c),a&&a()):d&&o&&o(),y}function Gy({items:e},t,{flowChars:n,itemIndent:r}){let{indent:s,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=t;r+=i;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let g=0;g<e.length;++g){let m=e[g],h=null;if(pt.isNode(m))m.spaceBefore&&d.push(""),is(t,d,m.commentBefore,!1),m.comment&&(h=m.comment);else if(pt.isPair(m)){let v=pt.isNode(m.key)?m.key:null;v&&(v.spaceBefore&&d.push(""),is(t,d,v.commentBefore,!1),v.comment&&(l=!0));let k=pt.isNode(m.value)?m.value:null;k?(k.comment&&(h=k.comment),k.commentBefore&&(l=!0)):m.value==null&&v?.comment&&(h=v.comment)}h&&(l=!0);let w=tf.stringify(m,c,()=>h=null);l||(l=d.length>u||w.includes(`
54
+ `)),g<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((v,k)=>v+k.length+2,2)+(w.length+2)>t.options.lineWidth)),l&&(w+=",")),h&&(w+=ss.lineComment(w,r,a(h))),d.push(w),u=d.length}let{start:f,end:y}=n;if(d.length===0)return f+y;if(!l){let g=d.reduce((m,h)=>m+h.length+2,2);l=t.options.lineWidth>0&&g>t.options.lineWidth}if(l){let g=f;for(let m of d)g+=m?`
55
55
  ${i}${s}${m}`:`
56
- `;return`${y}
57
- ${s}${g}`}else return`${f}${o}${d.join(" ")}${o}${g}`}function rs({indent:e,options:{commentString:t}},n,r,s){if(r&&s&&(r=r.replace(/^\n+/,"")),r){let i=ns.indentComment(t(r),e);n.push(i.trimStart())}}Yd.stringifyCollection=_y});var Xe=C(Xi=>{"use strict";var By=Hi(),Ky=Yi(),Uy=Kr(),Qe=x(),ss=He(),Vy=V();function Cn(e,t){let n=Qe.isScalar(t)?t.value:t;for(let r of e)if(Qe.isPair(r)&&(r.key===t||r.key===n||Qe.isScalar(r.key)&&r.key.value===n))return r}var Qi=class extends Uy.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Qe.MAP,t),this.items=[]}static from(t,n,r){let{keepUndefined:s,replacer:i}=r,o=new this(t),a=(c,l)=>{if(typeof i=="function")l=i.call(n,c,l);else if(Array.isArray(i)&&!i.includes(c))return;(l!==void 0||s)&&o.items.push(ss.createPair(c,l,r))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,n){let r;Qe.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new ss.Pair(t,t?.value):r=new ss.Pair(t.key,t.value);let s=Cn(this.items,r.key),i=this.schema?.sortMapEntries;if(s){if(!n)throw new Error(`Key ${r.key} already set`);Qe.isScalar(s.value)&&Vy.isScalarValue(r.value)?s.value.value=r.value:s.value=r.value}else if(i){let o=this.items.findIndex(a=>i(r,a)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let n=Cn(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let s=Cn(this.items,t)?.value;return(!n&&Qe.isScalar(s)?s.value:s)??void 0}has(t){return!!Cn(this.items,t)}set(t,n){this.add(new ss.Pair(t,n),!0)}toJSON(t,n,r){let s=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(s);for(let i of this.items)Ky.addPairToJSMap(n,s,i);return s}toString(t,n,r){if(!t)return JSON.stringify(this);for(let s of this.items)if(!Qe.isPair(s))throw new Error(`Map items must all be pairs; found ${JSON.stringify(s)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),By.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:n})}};Xi.YAMLMap=Qi;Xi.findPair=Cn});var Mt=C(Hd=>{"use strict";var Wy=x(),Gd=Xe(),Jy={collection:"map",default:!0,nodeClass:Gd.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Wy.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>Gd.YAMLMap.from(e,t,n)};Hd.map=Jy});var Ze=C(Qd=>{"use strict";var Yy=bn(),Gy=Hi(),Hy=Kr(),os=x(),Qy=V(),Xy=We(),Zi=class extends Hy.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(os.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=is(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let r=is(t);if(typeof r!="number")return;let s=this.items[r];return!n&&os.isScalar(s)?s.value:s}has(t){let n=is(t);return typeof n=="number"&&n<this.items.length}set(t,n){let r=is(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let s=this.items[r];os.isScalar(s)&&Qy.isScalarValue(n)?s.value=n:this.items[r]=n}toJSON(t,n){let r=[];n?.onCreate&&n.onCreate(r);let s=0;for(let i of this.items)r.push(Xy.toJS(i,String(s++),n));return r}toString(t,n,r){return t?Gy.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(t,n,r){let{replacer:s}=r,i=new this(t);if(n&&Symbol.iterator in Object(n)){let o=0;for(let a of n){if(typeof s=="function"){let c=n instanceof Set?a:String(o++);a=s.call(n,c,a)}i.items.push(Yy.createNode(a,void 0,r))}}return i}};function is(e){let t=os.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Qd.YAMLSeq=Zi});var _t=C(Zd=>{"use strict";var Zy=x(),Xd=Ze(),ew={collection:"seq",default:!0,nodeClass:Xd.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Zy.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>Xd.YAMLSeq.from(e,t,n)};Zd.seq=ew});var jn=C(ef=>{"use strict";var tw=$n(),nw={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),tw.stringifyString(e,t,n,r)}};ef.string=nw});var as=C(rf=>{"use strict";var tf=V(),nf={identify:e=>e==null,createNode:()=>new tf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new tf.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&nf.test.test(e)?e:t.options.nullStr};rf.nullTag=nf});var eo=C(of=>{"use strict";var rw=V(),sf={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new rw.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&sf.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?n.options.trueStr:n.options.falseStr}};of.boolTag=sf});var qt=C(af=>{"use strict";function sw({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r=="bigint")return String(r);let s=typeof r=="number"?r:Number(r);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let i=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(i)&&!i.includes("e")){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=t-(i.length-o-1);for(;a-- >0;)i+="0"}return i}af.stringifyNumber=sw});var no=C(cs=>{"use strict";var iw=V(),to=qt(),ow={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:to.stringifyNumber},aw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():to.stringifyNumber(e)}},cw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new iw.Scalar(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:to.stringifyNumber};cs.float=cw;cs.floatExp=aw;cs.floatNaN=ow});var so=C(us=>{"use strict";var cf=qt(),ls=e=>typeof e=="bigint"||Number.isInteger(e),ro=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function lf(e,t,n){let{value:r}=e;return ls(r)&&r>=0?n+r.toString(t):cf.stringifyNumber(e)}var lw={identify:e=>ls(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>ro(e,2,8,n),stringify:e=>lf(e,8,"0o")},uw={identify:ls,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>ro(e,0,10,n),stringify:cf.stringifyNumber},dw={identify:e=>ls(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>ro(e,2,16,n),stringify:e=>lf(e,16,"0x")};us.int=uw;us.intHex=dw;us.intOct=lw});var df=C(uf=>{"use strict";var fw=Mt(),pw=as(),hw=_t(),mw=jn(),gw=eo(),io=no(),oo=so(),yw=[fw.map,hw.seq,mw.string,pw.nullTag,gw.boolTag,oo.intOct,oo.int,oo.intHex,io.floatNaN,io.floatExp,io.float];uf.schema=yw});var hf=C(pf=>{"use strict";var ww=V(),vw=Mt(),kw=_t();function ff(e){return typeof e=="bigint"||Number.isInteger(e)}var ds=({value:e})=>JSON.stringify(e),bw=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:ds},{identify:e=>e==null,createNode:()=>new ww.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ds},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:ds},{identify:ff,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>ff(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:ds}],Ew={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Sw=[vw.map,kw.seq].concat(bw,Ew);pf.schema=Sw});var co=C(mf=>{"use strict";var Nn=er("buffer"),ao=V(),Rw=$n(),$w={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Nn.Buffer=="function")return Nn.Buffer.from(e,"base64");if(typeof atob=="function"){let n=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let s=0;s<n.length;++s)r[s]=n.charCodeAt(s);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},r,s,i){if(!n)return"";let o=n,a;if(typeof Nn.Buffer=="function")a=o instanceof Nn.Buffer?o.toString("base64"):Nn.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=ao.Scalar.BLOCK_LITERAL),t!==ao.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(a.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=a.substr(f,c);a=u.join(t===ao.Scalar.BLOCK_LITERAL?`
58
- `:" ")}return Rw.stringifyString({comment:e,type:t,value:a},r,s,i)}};mf.binary=$w});var hs=C(ps=>{"use strict";var fs=x(),lo=He(),Aw=V(),Ow=Ze();function gf(e,t){if(fs.isSeq(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!fs.isPair(r)){if(fs.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let s=r.items[0]||new lo.Pair(new Aw.Scalar(null));if(r.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${r.commentBefore}
56
+ `;return`${g}
57
+ ${s}${y}`}else return`${f}${o}${d.join(" ")}${o}${y}`}function is({indent:e,options:{commentString:t}},n,r,s){if(r&&s&&(r=r.replace(/^\n+/,"")),r){let i=ss.indentComment(t(r),e);n.push(i.trimStart())}}nf.stringifyCollection=Jy});var Ze=C(to=>{"use strict";var Hy=Zi(),Qy=Qi(),Xy=Vr(),Xe=x(),os=Qe(),Zy=V();function Cn(e,t){let n=Xe.isScalar(t)?t.value:t;for(let r of e)if(Xe.isPair(r)&&(r.key===t||r.key===n||Xe.isScalar(r.key)&&r.key.value===n))return r}var eo=class extends Xy.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Xe.MAP,t),this.items=[]}static from(t,n,r){let{keepUndefined:s,replacer:i}=r,o=new this(t),a=(c,l)=>{if(typeof i=="function")l=i.call(n,c,l);else if(Array.isArray(i)&&!i.includes(c))return;(l!==void 0||s)&&o.items.push(os.createPair(c,l,r))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,n){let r;Xe.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new os.Pair(t,t?.value):r=new os.Pair(t.key,t.value);let s=Cn(this.items,r.key),i=this.schema?.sortMapEntries;if(s){if(!n)throw new Error(`Key ${r.key} already set`);Xe.isScalar(s.value)&&Zy.isScalarValue(r.value)?s.value.value=r.value:s.value=r.value}else if(i){let o=this.items.findIndex(a=>i(r,a)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let n=Cn(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let s=Cn(this.items,t)?.value;return(!n&&Xe.isScalar(s)?s.value:s)??void 0}has(t){return!!Cn(this.items,t)}set(t,n){this.add(new os.Pair(t,n),!0)}toJSON(t,n,r){let s=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(s);for(let i of this.items)Qy.addPairToJSMap(n,s,i);return s}toString(t,n,r){if(!t)return JSON.stringify(this);for(let s of this.items)if(!Xe.isPair(s))throw new Error(`Map items must all be pairs; found ${JSON.stringify(s)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Hy.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:n})}};to.YAMLMap=eo;to.findPair=Cn});var qt=C(sf=>{"use strict";var ew=x(),rf=Ze(),tw={collection:"map",default:!0,nodeClass:rf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return ew.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>rf.YAMLMap.from(e,t,n)};sf.map=tw});var et=C(of=>{"use strict";var nw=bn(),rw=Zi(),sw=Vr(),cs=x(),iw=V(),ow=Je(),no=class extends sw.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(cs.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=as(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let r=as(t);if(typeof r!="number")return;let s=this.items[r];return!n&&cs.isScalar(s)?s.value:s}has(t){let n=as(t);return typeof n=="number"&&n<this.items.length}set(t,n){let r=as(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let s=this.items[r];cs.isScalar(s)&&iw.isScalarValue(n)?s.value=n:this.items[r]=n}toJSON(t,n){let r=[];n?.onCreate&&n.onCreate(r);let s=0;for(let i of this.items)r.push(ow.toJS(i,String(s++),n));return r}toString(t,n,r){return t?rw.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(t,n,r){let{replacer:s}=r,i=new this(t);if(n&&Symbol.iterator in Object(n)){let o=0;for(let a of n){if(typeof s=="function"){let c=n instanceof Set?a:String(o++);a=s.call(n,c,a)}i.items.push(nw.createNode(a,void 0,r))}}return i}};function as(e){let t=cs.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}of.YAMLSeq=no});var zt=C(cf=>{"use strict";var aw=x(),af=et(),cw={collection:"seq",default:!0,nodeClass:af.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return aw.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>af.YAMLSeq.from(e,t,n)};cf.seq=cw});var jn=C(lf=>{"use strict";var lw=$n(),uw={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),lw.stringifyString(e,t,n,r)}};lf.string=uw});var ls=C(ff=>{"use strict";var uf=V(),df={identify:e=>e==null,createNode:()=>new uf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new uf.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&df.test.test(e)?e:t.options.nullStr};ff.nullTag=df});var ro=C(hf=>{"use strict";var dw=V(),pf={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new dw.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&pf.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?n.options.trueStr:n.options.falseStr}};hf.boolTag=pf});var Bt=C(mf=>{"use strict";function fw({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r=="bigint")return String(r);let s=typeof r=="number"?r:Number(r);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let i=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(i)&&!i.includes("e")){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=t-(i.length-o-1);for(;a-- >0;)i+="0"}return i}mf.stringifyNumber=fw});var io=C(us=>{"use strict";var pw=V(),so=Bt(),hw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:so.stringifyNumber},mw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():so.stringifyNumber(e)}},gw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new pw.Scalar(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:so.stringifyNumber};us.float=gw;us.floatExp=mw;us.floatNaN=hw});var ao=C(fs=>{"use strict";var gf=Bt(),ds=e=>typeof e=="bigint"||Number.isInteger(e),oo=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function yf(e,t,n){let{value:r}=e;return ds(r)&&r>=0?n+r.toString(t):gf.stringifyNumber(e)}var yw={identify:e=>ds(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>oo(e,2,8,n),stringify:e=>yf(e,8,"0o")},ww={identify:ds,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>oo(e,0,10,n),stringify:gf.stringifyNumber},vw={identify:e=>ds(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>oo(e,2,16,n),stringify:e=>yf(e,16,"0x")};fs.int=ww;fs.intHex=vw;fs.intOct=yw});var vf=C(wf=>{"use strict";var kw=qt(),bw=ls(),Ew=zt(),Sw=jn(),Rw=ro(),co=io(),lo=ao(),$w=[kw.map,Ew.seq,Sw.string,bw.nullTag,Rw.boolTag,lo.intOct,lo.int,lo.intHex,co.floatNaN,co.floatExp,co.float];wf.schema=$w});var Ef=C(bf=>{"use strict";var Aw=V(),Ow=qt(),Cw=zt();function kf(e){return typeof e=="bigint"||Number.isInteger(e)}var ps=({value:e})=>JSON.stringify(e),jw=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:ps},{identify:e=>e==null,createNode:()=>new Aw.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ps},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:ps},{identify:kf,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>kf(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:ps}],Nw={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Iw=[Ow.map,Cw.seq].concat(jw,Nw);bf.schema=Iw});var fo=C(Sf=>{"use strict";var Nn=er("buffer"),uo=V(),Dw=$n(),Pw={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Nn.Buffer=="function")return Nn.Buffer.from(e,"base64");if(typeof atob=="function"){let n=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let s=0;s<n.length;++s)r[s]=n.charCodeAt(s);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},r,s,i){if(!n)return"";let o=n,a;if(typeof Nn.Buffer=="function")a=o instanceof Nn.Buffer?o.toString("base64"):Nn.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=uo.Scalar.BLOCK_LITERAL),t!==uo.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(a.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=a.substr(f,c);a=u.join(t===uo.Scalar.BLOCK_LITERAL?`
58
+ `:" ")}return Dw.stringifyString({comment:e,type:t,value:a},r,s,i)}};Sf.binary=Pw});var gs=C(ms=>{"use strict";var hs=x(),po=Qe(),Tw=V(),Fw=et();function Rf(e,t){if(hs.isSeq(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!hs.isPair(r)){if(hs.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let s=r.items[0]||new po.Pair(new Tw.Scalar(null));if(r.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${r.commentBefore}
59
59
  ${s.key.commentBefore}`:r.commentBefore),r.comment){let i=s.value??s.key;i.comment=i.comment?`${r.comment}
60
- ${i.comment}`:r.comment}r=s}e.items[n]=fs.isPair(r)?r:new lo.Pair(r)}}else t("Expected a sequence for this tag");return e}function yf(e,t,n){let{replacer:r}=n,s=new Ow.YAMLSeq(e);s.tag="tag:yaml.org,2002:pairs";let i=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(i++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;s.items.push(lo.createPair(a,c,n))}return s}var Cw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:gf,createNode:yf};ps.createPairs=yf;ps.pairs=Cw;ps.resolvePairs=gf});var po=C(fo=>{"use strict";var wf=x(),uo=We(),In=Xe(),jw=Ze(),vf=hs(),ft=class e extends jw.YAMLSeq{constructor(){super(),this.add=In.YAMLMap.prototype.add.bind(this),this.delete=In.YAMLMap.prototype.delete.bind(this),this.get=In.YAMLMap.prototype.get.bind(this),this.has=In.YAMLMap.prototype.has.bind(this),this.set=In.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,n){if(!n)return super.toJSON(t);let r=new Map;n?.onCreate&&n.onCreate(r);for(let s of this.items){let i,o;if(wf.isPair(s)?(i=uo.toJS(s.key,"",n),o=uo.toJS(s.value,i,n)):i=uo.toJS(s,"",n),r.has(i))throw new Error("Ordered maps must not include duplicate keys");r.set(i,o)}return r}static from(t,n,r){let s=vf.createPairs(t,n,r),i=new this;return i.items=s.items,i}};ft.tag="tag:yaml.org,2002:omap";var Nw={collection:"seq",identify:e=>e instanceof Map,nodeClass:ft,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=vf.resolvePairs(e,t),r=[];for(let{key:s}of n.items)wf.isScalar(s)&&(r.includes(s.value)?t(`Ordered maps must not include duplicate keys: ${s.value}`):r.push(s.value));return Object.assign(new ft,n)},createNode:(e,t,n)=>ft.from(e,t,n)};fo.YAMLOMap=ft;fo.omap=Nw});var Rf=C(ho=>{"use strict";var kf=V();function bf({value:e,source:t},n){return t&&(e?Ef:Sf).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Ef={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new kf.Scalar(!0),stringify:bf},Sf={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new kf.Scalar(!1),stringify:bf};ho.falseTag=Sf;ho.trueTag=Ef});var $f=C(ms=>{"use strict";var Iw=V(),mo=qt(),Dw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:mo.stringifyNumber},Tw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():mo.stringifyNumber(e)}},Pw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Iw.Scalar(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let r=e.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:mo.stringifyNumber};ms.float=Pw;ms.floatExp=Tw;ms.floatNaN=Dw});var Of=C(Tn=>{"use strict";var Af=qt(),Dn=e=>typeof e=="bigint"||Number.isInteger(e);function gs(e,t,n,{intAsBigInt:r}){let s=e[0];if((s==="-"||s==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return s==="-"?BigInt(-1)*o:o}let i=parseInt(e,n);return s==="-"?-1*i:i}function go(e,t,n){let{value:r}=e;if(Dn(r)){let s=r.toString(t);return r<0?"-"+n+s.substr(1):n+s}return Af.stringifyNumber(e)}var Lw={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>gs(e,2,2,n),stringify:e=>go(e,2,"0b")},Fw={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>gs(e,1,8,n),stringify:e=>go(e,8,"0")},xw={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>gs(e,0,10,n),stringify:Af.stringifyNumber},Mw={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>gs(e,2,16,n),stringify:e=>go(e,16,"0x")};Tn.int=xw;Tn.intBin=Lw;Tn.intHex=Mw;Tn.intOct=Fw});var wo=C(yo=>{"use strict";var vs=x(),ys=He(),ws=Xe(),pt=class e extends ws.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;vs.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new ys.Pair(t.key,null):n=new ys.Pair(t,null),ws.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let r=ws.findPair(this.items,t);return!n&&vs.isPair(r)?vs.isScalar(r.key)?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=ws.findPair(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new ys.Pair(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(t,n,r){let{replacer:s}=r,i=new this(t);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof s=="function"&&(o=s.call(n,o,o)),i.items.push(ys.createPair(o,null,r));return i}};pt.tag="tag:yaml.org,2002:set";var _w={collection:"map",identify:e=>e instanceof Set,nodeClass:pt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>pt.from(e,t,n),resolve(e,t){if(vs.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new pt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};yo.YAMLSet=pt;yo.set=_w});var ko=C(ks=>{"use strict";var qw=qt();function vo(e,t){let n=e[0],r=n==="-"||n==="+"?e.substring(1):e,s=o=>t?BigInt(o):Number(o),i=r.replace(/_/g,"").split(":").reduce((o,a)=>o*s(60)+s(a),s(0));return n==="-"?s(-1)*i:i}function Cf(e){let{value:t}=e,n=o=>o;if(typeof t=="bigint")n=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return qw.stringifyNumber(e);let r="";t<0&&(r="-",t*=n(-1));let s=n(60),i=[t%s];return t<60?i.unshift(0):(t=(t-i[0])/s,i.unshift(t%s),t>=60&&(t=(t-i[0])/s,i.unshift(t))),r+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var zw={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>vo(e,n),stringify:Cf},Bw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>vo(e,!1),stringify:Cf},jf={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(jf.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,s,i,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(n,r-1,s,i||0,o||0,a||0,c),u=t[8];if(u&&u!=="Z"){let d=vo(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};ks.floatTime=Bw;ks.intTime=zw;ks.timestamp=jf});var Df=C(If=>{"use strict";var Kw=Mt(),Uw=as(),Vw=_t(),Ww=jn(),Jw=co(),Nf=Rf(),bo=$f(),bs=Of(),Yw=Zr(),Gw=po(),Hw=hs(),Qw=wo(),Eo=ko(),Xw=[Kw.map,Vw.seq,Ww.string,Uw.nullTag,Nf.trueTag,Nf.falseTag,bs.intBin,bs.intOct,bs.int,bs.intHex,bo.floatNaN,bo.floatExp,bo.float,Jw.binary,Yw.merge,Gw.omap,Hw.pairs,Qw.set,Eo.intTime,Eo.floatTime,Eo.timestamp];If.schema=Xw});var Bf=C($o=>{"use strict";var Ff=Mt(),Zw=as(),xf=_t(),ev=jn(),tv=eo(),So=no(),Ro=so(),nv=df(),rv=hf(),Mf=co(),Pn=Zr(),_f=po(),qf=hs(),Tf=Df(),zf=wo(),Es=ko(),Pf=new Map([["core",nv.schema],["failsafe",[Ff.map,xf.seq,ev.string]],["json",rv.schema],["yaml11",Tf.schema],["yaml-1.1",Tf.schema]]),Lf={binary:Mf.binary,bool:tv.boolTag,float:So.float,floatExp:So.floatExp,floatNaN:So.floatNaN,floatTime:Es.floatTime,int:Ro.int,intHex:Ro.intHex,intOct:Ro.intOct,intTime:Es.intTime,map:Ff.map,merge:Pn.merge,null:Zw.nullTag,omap:_f.omap,pairs:qf.pairs,seq:xf.seq,set:zf.set,timestamp:Es.timestamp},sv={"tag:yaml.org,2002:binary":Mf.binary,"tag:yaml.org,2002:merge":Pn.merge,"tag:yaml.org,2002:omap":_f.omap,"tag:yaml.org,2002:pairs":qf.pairs,"tag:yaml.org,2002:set":zf.set,"tag:yaml.org,2002:timestamp":Es.timestamp};function iv(e,t,n){let r=Pf.get(t);if(r&&!e)return n&&!r.includes(Pn.merge)?r.concat(Pn.merge):r.slice();let s=r;if(!s)if(Array.isArray(e))s=[];else{let i=Array.from(Pf.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${i} or define customTags array`)}if(Array.isArray(e))for(let i of e)s=s.concat(i);else typeof e=="function"&&(s=e(s.slice()));return n&&(s=s.concat(Pn.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?Lf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Lf).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}$o.coreKnownTags=sv;$o.getTags=iv});var Co=C(Kf=>{"use strict";var Ao=x(),ov=Mt(),av=_t(),cv=jn(),Ss=Bf(),lv=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Oo=class e{constructor({compat:t,customTags:n,merge:r,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(t)?Ss.getTags(t,"compat"):t?Ss.getTags(null,t):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?Ss.coreKnownTags:{},this.tags=Ss.getTags(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,Ao.MAP,{value:ov.map}),Object.defineProperty(this,Ao.SCALAR,{value:cv.string}),Object.defineProperty(this,Ao.SEQ,{value:av.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?lv:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Kf.Schema=Oo});var Vf=C(Uf=>{"use strict";var uv=x(),jo=An(),Ln=En();function dv(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(n.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");let s=jo.createStringifyContext(e,t),{commentString:i}=s.options;if(e.commentBefore){n.length!==1&&n.unshift("");let c=i(e.commentBefore);n.unshift(Ln.indentComment(c,""))}let o=!1,a=null;if(e.contents){if(uv.isNode(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){let u=i(e.contents.commentBefore);n.push(Ln.indentComment(u,""))}s.forceBlockIndent=!!e.comment,a=e.contents.comment}let c=a?void 0:()=>o=!0,l=jo.stringify(e.contents,s,()=>a=null,c);a&&(l+=Ln.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(jo.stringify(e.contents,s));if(e.directives?.docEnd)if(e.comment){let c=i(e.comment);c.includes(`
61
- `)?(n.push("..."),n.push(Ln.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&n[n.length-1]!==""&&n.push(""),n.push(Ln.indentComment(i(c),"")))}return n.join(`
60
+ ${i.comment}`:r.comment}r=s}e.items[n]=hs.isPair(r)?r:new po.Pair(r)}}else t("Expected a sequence for this tag");return e}function $f(e,t,n){let{replacer:r}=n,s=new Fw.YAMLSeq(e);s.tag="tag:yaml.org,2002:pairs";let i=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(i++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;s.items.push(po.createPair(a,c,n))}return s}var Lw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Rf,createNode:$f};ms.createPairs=$f;ms.pairs=Lw;ms.resolvePairs=Rf});var go=C(mo=>{"use strict";var Af=x(),ho=Je(),In=Ze(),xw=et(),Of=gs(),ht=class e extends xw.YAMLSeq{constructor(){super(),this.add=In.YAMLMap.prototype.add.bind(this),this.delete=In.YAMLMap.prototype.delete.bind(this),this.get=In.YAMLMap.prototype.get.bind(this),this.has=In.YAMLMap.prototype.has.bind(this),this.set=In.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,n){if(!n)return super.toJSON(t);let r=new Map;n?.onCreate&&n.onCreate(r);for(let s of this.items){let i,o;if(Af.isPair(s)?(i=ho.toJS(s.key,"",n),o=ho.toJS(s.value,i,n)):i=ho.toJS(s,"",n),r.has(i))throw new Error("Ordered maps must not include duplicate keys");r.set(i,o)}return r}static from(t,n,r){let s=Of.createPairs(t,n,r),i=new this;return i.items=s.items,i}};ht.tag="tag:yaml.org,2002:omap";var Mw={collection:"seq",identify:e=>e instanceof Map,nodeClass:ht,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=Of.resolvePairs(e,t),r=[];for(let{key:s}of n.items)Af.isScalar(s)&&(r.includes(s.value)?t(`Ordered maps must not include duplicate keys: ${s.value}`):r.push(s.value));return Object.assign(new ht,n)},createNode:(e,t,n)=>ht.from(e,t,n)};mo.YAMLOMap=ht;mo.omap=Mw});var Df=C(yo=>{"use strict";var Cf=V();function jf({value:e,source:t},n){return t&&(e?Nf:If).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Nf={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Cf.Scalar(!0),stringify:jf},If={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Cf.Scalar(!1),stringify:jf};yo.falseTag=If;yo.trueTag=Nf});var Pf=C(ys=>{"use strict";var _w=V(),wo=Bt(),qw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:wo.stringifyNumber},zw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():wo.stringifyNumber(e)}},Bw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new _w.Scalar(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let r=e.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:wo.stringifyNumber};ys.float=Bw;ys.floatExp=zw;ys.floatNaN=qw});var Ff=C(Pn=>{"use strict";var Tf=Bt(),Dn=e=>typeof e=="bigint"||Number.isInteger(e);function ws(e,t,n,{intAsBigInt:r}){let s=e[0];if((s==="-"||s==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return s==="-"?BigInt(-1)*o:o}let i=parseInt(e,n);return s==="-"?-1*i:i}function vo(e,t,n){let{value:r}=e;if(Dn(r)){let s=r.toString(t);return r<0?"-"+n+s.substr(1):n+s}return Tf.stringifyNumber(e)}var Kw={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>ws(e,2,2,n),stringify:e=>vo(e,2,"0b")},Uw={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>ws(e,1,8,n),stringify:e=>vo(e,8,"0")},Vw={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>ws(e,0,10,n),stringify:Tf.stringifyNumber},Ww={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>ws(e,2,16,n),stringify:e=>vo(e,16,"0x")};Pn.int=Vw;Pn.intBin=Kw;Pn.intHex=Ww;Pn.intOct=Uw});var bo=C(ko=>{"use strict";var bs=x(),vs=Qe(),ks=Ze(),mt=class e extends ks.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;bs.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new vs.Pair(t.key,null):n=new vs.Pair(t,null),ks.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let r=ks.findPair(this.items,t);return!n&&bs.isPair(r)?bs.isScalar(r.key)?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=ks.findPair(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new vs.Pair(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(t,n,r){let{replacer:s}=r,i=new this(t);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof s=="function"&&(o=s.call(n,o,o)),i.items.push(vs.createPair(o,null,r));return i}};mt.tag="tag:yaml.org,2002:set";var Jw={collection:"map",identify:e=>e instanceof Set,nodeClass:mt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>mt.from(e,t,n),resolve(e,t){if(bs.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new mt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ko.YAMLSet=mt;ko.set=Jw});var So=C(Es=>{"use strict";var Yw=Bt();function Eo(e,t){let n=e[0],r=n==="-"||n==="+"?e.substring(1):e,s=o=>t?BigInt(o):Number(o),i=r.replace(/_/g,"").split(":").reduce((o,a)=>o*s(60)+s(a),s(0));return n==="-"?s(-1)*i:i}function Lf(e){let{value:t}=e,n=o=>o;if(typeof t=="bigint")n=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Yw.stringifyNumber(e);let r="";t<0&&(r="-",t*=n(-1));let s=n(60),i=[t%s];return t<60?i.unshift(0):(t=(t-i[0])/s,i.unshift(t%s),t>=60&&(t=(t-i[0])/s,i.unshift(t))),r+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Gw={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>Eo(e,n),stringify:Lf},Hw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>Eo(e,!1),stringify:Lf},xf={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(xf.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,s,i,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(n,r-1,s,i||0,o||0,a||0,c),u=t[8];if(u&&u!=="Z"){let d=Eo(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Es.floatTime=Hw;Es.intTime=Gw;Es.timestamp=xf});var qf=C(_f=>{"use strict";var Qw=qt(),Xw=ls(),Zw=zt(),ev=jn(),tv=fo(),Mf=Df(),Ro=Pf(),Ss=Ff(),nv=ts(),rv=go(),sv=gs(),iv=bo(),$o=So(),ov=[Qw.map,Zw.seq,ev.string,Xw.nullTag,Mf.trueTag,Mf.falseTag,Ss.intBin,Ss.intOct,Ss.int,Ss.intHex,Ro.floatNaN,Ro.floatExp,Ro.float,tv.binary,nv.merge,rv.omap,sv.pairs,iv.set,$o.intTime,$o.floatTime,$o.timestamp];_f.schema=ov});var Hf=C(Co=>{"use strict";var Uf=qt(),av=ls(),Vf=zt(),cv=jn(),lv=ro(),Ao=io(),Oo=ao(),uv=vf(),dv=Ef(),Wf=fo(),Tn=ts(),Jf=go(),Yf=gs(),zf=qf(),Gf=bo(),Rs=So(),Bf=new Map([["core",uv.schema],["failsafe",[Uf.map,Vf.seq,cv.string]],["json",dv.schema],["yaml11",zf.schema],["yaml-1.1",zf.schema]]),Kf={binary:Wf.binary,bool:lv.boolTag,float:Ao.float,floatExp:Ao.floatExp,floatNaN:Ao.floatNaN,floatTime:Rs.floatTime,int:Oo.int,intHex:Oo.intHex,intOct:Oo.intOct,intTime:Rs.intTime,map:Uf.map,merge:Tn.merge,null:av.nullTag,omap:Jf.omap,pairs:Yf.pairs,seq:Vf.seq,set:Gf.set,timestamp:Rs.timestamp},fv={"tag:yaml.org,2002:binary":Wf.binary,"tag:yaml.org,2002:merge":Tn.merge,"tag:yaml.org,2002:omap":Jf.omap,"tag:yaml.org,2002:pairs":Yf.pairs,"tag:yaml.org,2002:set":Gf.set,"tag:yaml.org,2002:timestamp":Rs.timestamp};function pv(e,t,n){let r=Bf.get(t);if(r&&!e)return n&&!r.includes(Tn.merge)?r.concat(Tn.merge):r.slice();let s=r;if(!s)if(Array.isArray(e))s=[];else{let i=Array.from(Bf.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${i} or define customTags array`)}if(Array.isArray(e))for(let i of e)s=s.concat(i);else typeof e=="function"&&(s=e(s.slice()));return n&&(s=s.concat(Tn.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?Kf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Kf).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}Co.coreKnownTags=fv;Co.getTags=pv});var Io=C(Qf=>{"use strict";var jo=x(),hv=qt(),mv=zt(),gv=jn(),$s=Hf(),yv=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,No=class e{constructor({compat:t,customTags:n,merge:r,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(t)?$s.getTags(t,"compat"):t?$s.getTags(null,t):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?$s.coreKnownTags:{},this.tags=$s.getTags(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,jo.MAP,{value:hv.map}),Object.defineProperty(this,jo.SCALAR,{value:gv.string}),Object.defineProperty(this,jo.SEQ,{value:mv.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?yv:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Qf.Schema=No});var Zf=C(Xf=>{"use strict";var wv=x(),Do=An(),Fn=En();function vv(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(n.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");let s=Do.createStringifyContext(e,t),{commentString:i}=s.options;if(e.commentBefore){n.length!==1&&n.unshift("");let c=i(e.commentBefore);n.unshift(Fn.indentComment(c,""))}let o=!1,a=null;if(e.contents){if(wv.isNode(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){let u=i(e.contents.commentBefore);n.push(Fn.indentComment(u,""))}s.forceBlockIndent=!!e.comment,a=e.contents.comment}let c=a?void 0:()=>o=!0,l=Do.stringify(e.contents,s,()=>a=null,c);a&&(l+=Fn.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(Do.stringify(e.contents,s));if(e.directives?.docEnd)if(e.comment){let c=i(e.comment);c.includes(`
61
+ `)?(n.push("..."),n.push(Fn.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&n[n.length-1]!==""&&n.push(""),n.push(Fn.indentComment(i(c),"")))}return n.join(`
62
62
  `)+`
63
- `}Uf.stringifyDocument=dv});var Fn=C(Wf=>{"use strict";var fv=kn(),zt=Kr(),fe=x(),pv=He(),hv=We(),mv=Co(),gv=Vf(),No=_r(),yv=Ti(),wv=bn(),Io=Di(),Do=class e{constructor(t,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,fe.NODE_TYPE,{value:fe.DOC});let s=null;typeof n=="function"||Array.isArray(n)?s=n:r===void 0&&n&&(r=n,n=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=i;let{version:o}=i;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Io.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,s,r)}clone(){let t=Object.create(e.prototype,{[fe.NODE_TYPE]:{value:fe.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=fe.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Bt(this.contents)&&this.contents.add(t)}addIn(t,n){Bt(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let r=No.anchorNames(this);t.anchor=!n||r.has(n)?No.findNewAnchor(n||"a",r):n}return new fv.Alias(t.anchor)}createNode(t,n,r){let s;if(typeof n=="function")t=n.call({"":t},"",t),s=n;else if(Array.isArray(n)){let h=v=>typeof v=="number"||v instanceof String||v instanceof Number,w=n.filter(h).map(String);w.length>0&&(n=n.concat(w)),s=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:g}=No.createNodeAnchors(this,o||"a"),y={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:g},m=wv.createNode(t,u,y);return a&&fe.isCollection(m)&&(m.flow=!0),f(),m}createPair(t,n,r={}){let s=this.createNode(t,null,r),i=this.createNode(n,null,r);return new pv.Pair(s,i)}delete(t){return Bt(this.contents)?this.contents.delete(t):!1}deleteIn(t){return zt.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Bt(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return fe.isCollection(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return zt.isEmptyPath(t)?!n&&fe.isScalar(this.contents)?this.contents.value:this.contents:fe.isCollection(this.contents)?this.contents.getIn(t,n):void 0}has(t){return fe.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return zt.isEmptyPath(t)?this.contents!==void 0:fe.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=zt.collectionFromPath(this.schema,[t],n):Bt(this.contents)&&this.contents.set(t,n)}setIn(t,n){zt.isEmptyPath(t)?this.contents=n:this.contents==null?this.contents=zt.collectionFromPath(this.schema,Array.from(t),n):Bt(this.contents)&&this.contents.setIn(t,n)}setSchema(t,n={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Io.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Io.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let s=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${s}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new mv.Schema(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:n,mapAsMap:r,maxAliasCount:s,onAnchor:i,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},c=hv.toJS(this.contents,n??"",a);if(typeof i=="function")for(let{count:l,res:u}of a.anchors.values())i(u,l);return typeof o=="function"?yv.applyReviver(o,{"":c},"",c):c}toJSON(t,n){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:n})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let n=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return gv.stringifyDocument(this,t)}};function Bt(e){if(fe.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Wf.Document=Do});var _n=C(Mn=>{"use strict";var xn=class extends Error{constructor(t,n,r,s){super(),this.name=t,this.code=r,this.message=s,this.pos=n}},To=class extends xn{constructor(t,n,r){super("YAMLParseError",t,n,r)}},Po=class extends xn{constructor(t,n,r){super("YAMLWarning",t,n,r)}},vv=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>t.linePos(a));let{line:r,col:s}=n.linePos[0];n.message+=` at line ${r}, column ${s}`;let i=s-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(o.substring(0,i))){let a=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
63
+ `}Xf.stringifyDocument=vv});var Ln=C(ep=>{"use strict";var kv=kn(),Kt=Vr(),fe=x(),bv=Qe(),Ev=Je(),Sv=Io(),Rv=Zf(),Po=zr(),$v=Li(),Av=bn(),To=Fi(),Fo=class e{constructor(t,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,fe.NODE_TYPE,{value:fe.DOC});let s=null;typeof n=="function"||Array.isArray(n)?s=n:r===void 0&&n&&(r=n,n=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=i;let{version:o}=i;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new To.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,s,r)}clone(){let t=Object.create(e.prototype,{[fe.NODE_TYPE]:{value:fe.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=fe.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Ut(this.contents)&&this.contents.add(t)}addIn(t,n){Ut(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let r=Po.anchorNames(this);t.anchor=!n||r.has(n)?Po.findNewAnchor(n||"a",r):n}return new kv.Alias(t.anchor)}createNode(t,n,r){let s;if(typeof n=="function")t=n.call({"":t},"",t),s=n;else if(Array.isArray(n)){let h=v=>typeof v=="number"||v instanceof String||v instanceof Number,w=n.filter(h).map(String);w.length>0&&(n=n.concat(w)),s=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:y}=Po.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:y},m=Av.createNode(t,u,g);return a&&fe.isCollection(m)&&(m.flow=!0),f(),m}createPair(t,n,r={}){let s=this.createNode(t,null,r),i=this.createNode(n,null,r);return new bv.Pair(s,i)}delete(t){return Ut(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Kt.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Ut(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return fe.isCollection(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return Kt.isEmptyPath(t)?!n&&fe.isScalar(this.contents)?this.contents.value:this.contents:fe.isCollection(this.contents)?this.contents.getIn(t,n):void 0}has(t){return fe.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Kt.isEmptyPath(t)?this.contents!==void 0:fe.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=Kt.collectionFromPath(this.schema,[t],n):Ut(this.contents)&&this.contents.set(t,n)}setIn(t,n){Kt.isEmptyPath(t)?this.contents=n:this.contents==null?this.contents=Kt.collectionFromPath(this.schema,Array.from(t),n):Ut(this.contents)&&this.contents.setIn(t,n)}setSchema(t,n={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new To.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new To.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let s=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${s}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new Sv.Schema(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:n,mapAsMap:r,maxAliasCount:s,onAnchor:i,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},c=Ev.toJS(this.contents,n??"",a);if(typeof i=="function")for(let{count:l,res:u}of a.anchors.values())i(u,l);return typeof o=="function"?$v.applyReviver(o,{"":c},"",c):c}toJSON(t,n){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:n})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let n=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Rv.stringifyDocument(this,t)}};function Ut(e){if(fe.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}ep.Document=Fo});var _n=C(Mn=>{"use strict";var xn=class extends Error{constructor(t,n,r,s){super(),this.name=t,this.code=r,this.message=s,this.pos=n}},Lo=class extends xn{constructor(t,n,r){super("YAMLParseError",t,n,r)}},xo=class extends xn{constructor(t,n,r){super("YAMLWarning",t,n,r)}},Ov=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>t.linePos(a));let{line:r,col:s}=n.linePos[0];n.message+=` at line ${r}, column ${s}`;let i=s-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(o.substring(0,i))){let a=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
64
64
  `),o=a+o}if(/[^ ]/.test(o)){let a=1,c=n.linePos[1];c?.line===r&&c.col>s&&(a=Math.max(1,Math.min(c.col-s,80-i)));let l=" ".repeat(i)+"^".repeat(a);n.message+=`:
65
65
 
66
66
  ${o}
67
67
  ${l}
68
- `}};Mn.YAMLError=xn;Mn.YAMLParseError=To;Mn.YAMLWarning=Po;Mn.prettifyError=vv});var qn=C(Jf=>{"use strict";function kv(e,{flow:t,indicator:n,next:r,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",f="",g=!1,y=!1,m=null,h=null,w=null,v=null,k=null,b=null,S=null;for(let R of e)switch(y&&(R.type!=="space"&&R.type!=="newline"&&R.type!=="comma"&&i(R.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),m&&(l&&R.type!=="comment"&&R.type!=="newline"&&i(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),R.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&R.source.includes(" ")&&(m=R),u=!0;break;case"comment":{u||i(R,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let j=R.source.substring(1)||" ";d?d+=f+j:d=j,f="",l=!1;break}case"newline":l?d?d+=R.source:(!b||n!=="seq-item-ind")&&(c=!0):f+=R.source,l=!0,g=!0,(h||w)&&(v=R),u=!0;break;case"anchor":h&&i(R,"MULTIPLE_ANCHORS","A node can have at most one anchor"),R.source.endsWith(":")&&i(R.offset+R.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=R,S??(S=R.offset),l=!1,u=!1,y=!0;break;case"tag":{w&&i(R,"MULTIPLE_TAGS","A node can have at most one tag"),w=R,S??(S=R.offset),l=!1,u=!1,y=!0;break}case n:(h||w)&&i(R,"BAD_PROP_ORDER",`Anchors and tags must be after the ${R.source} indicator`),b&&i(R,"UNEXPECTED_TOKEN",`Unexpected ${R.source} in ${t??"collection"}`),b=R,l=n==="seq-item-ind"||n==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&i(R,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=R,l=!1,u=!1;break}default:i(R,"UNEXPECTED_TOKEN",`Unexpected ${R.type} token`),l=!1,u=!1}let $=e[e.length-1],E=$?$.offset+$.source.length:s;return y&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&i(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&i(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:b,spaceBefore:c,comment:d,hasNewline:g,anchor:h,tag:w,newlineAfterProp:v,end:E,start:S??E}}Jf.resolveProps=kv});var Rs=C(Yf=>{"use strict";function Lo(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
69
- `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(Lo(t.key)||Lo(t.value))return!0}return!1;default:return!0}}Yf.containsNewline=Lo});var Fo=C(Gf=>{"use strict";var bv=Rs();function Ev(e,t,n){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&bv.containsNewline(t)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Gf.flowIndentCheck=Ev});var xo=C(Qf=>{"use strict";var Hf=x();function Sv(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let s=typeof r=="function"?r:(i,o)=>i===o||Hf.isScalar(i)&&Hf.isScalar(o)&&i.value===o.value;return t.some(i=>s(i.key,n))}Qf.mapIncludes=Sv});var rp=C(np=>{"use strict";var Xf=He(),Rv=Xe(),Zf=qn(),$v=Rs(),ep=Fo(),Av=xo(),tp="All mapping items must start at the same column";function Ov({composeNode:e,composeEmptyNode:t},n,r,s,i){let o=i?.nodeClass??Rv.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:g,value:y}=u,m=Zf.resolveProps(d,{indicator:"explicit-key-ind",next:f??g?.[0],offset:c,onError:s,parentIndent:r.indent,startOnNewline:!0}),h=!m.found;if(h){if(f&&(f.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&s(c,"BAD_INDENT",tp)),!m.anchor&&!m.tag&&!g){l=m.end,m.comment&&(a.comment?a.comment+=`
70
- `+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||$v.containsNewline(f))&&s(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&s(c,"BAD_INDENT",tp);n.atKey=!0;let w=m.end,v=f?e(n,f,m,s):t(n,w,d,null,m,s);n.schema.compat&&ep.flowIndentCheck(r.indent,f,s),n.atKey=!1,Av.mapIncludes(n,a.items,v)&&s(w,"DUPLICATE_KEY","Map keys must be unique");let k=Zf.resolveProps(g??[],{indicator:"map-value-ind",next:y,offset:v.range[2],onError:s,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){h&&(y?.type==="block-map"&&!k.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&m.start<k.found.offset-1024&&s(v.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let b=y?e(n,y,k,s):t(n,c,g,null,k,s);n.schema.compat&&ep.flowIndentCheck(r.indent,y,s),c=b.range[2];let S=new Xf.Pair(v,b);n.options.keepSourceTokens&&(S.srcToken=u),a.items.push(S)}else{h&&s(v.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(v.comment?v.comment+=`
71
- `+k.comment:v.comment=k.comment);let b=new Xf.Pair(v);n.options.keepSourceTokens&&(b.srcToken=u),a.items.push(b)}}return l&&l<c&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,c,l??c],a}np.resolveBlockMap=Ov});var ip=C(sp=>{"use strict";var Cv=Ze(),jv=qn(),Nv=Fo();function Iv({composeNode:e,composeEmptyNode:t},n,r,s,i){let o=i?.nodeClass??Cv.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,l=null;for(let{start:u,value:d}of r.items){let f=jv.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:s,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?s(f.end,"BAD_INDENT","All sequence items must start at the same column"):s(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let g=d?e(n,d,f,s):t(n,f.end,u,null,f,s);n.schema.compat&&Nv.flowIndentCheck(r.indent,d,s),c=g.range[2],a.items.push(g)}return a.range=[r.offset,c,l??c],a}sp.resolveBlockSeq=Iv});var Kt=C(op=>{"use strict";function Dv(e,t,n,r){let s="";if(e){let i=!1,o="";for(let a of e){let{source:c,type:l}=a;switch(l){case"space":i=!0;break;case"comment":{n&&!i&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";s?s+=o+u:s=u,o="";break}case"newline":s&&(o+=c),i=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:s,offset:t}}op.resolveEnd=Dv});var up=C(lp=>{"use strict";var Tv=x(),Pv=He(),ap=Xe(),Lv=Ze(),Fv=Kt(),cp=qn(),xv=Rs(),Mv=xo(),Mo="Block collections are not allowed within flow collections",_o=e=>e&&(e.type==="block-map"||e.type==="block-seq");function _v({composeNode:e,composeEmptyNode:t},n,r,s,i){let o=r.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?ap.YAMLMap:Lv.YAMLSeq),l=new c(n.schema);l.flow=!0;let u=n.atRoot;u&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let d=r.offset+r.start.source.length;for(let h=0;h<r.items.length;++h){let w=r.items[h],{start:v,key:k,sep:b,value:S}=w,$=cp.resolveProps(v,{flow:a,indicator:"explicit-key-ind",next:k??b?.[0],offset:d,onError:s,parentIndent:r.indent,startOnNewline:!1});if(!$.found){if(!$.anchor&&!$.tag&&!b&&!S){h===0&&$.comma?s($.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):h<r.items.length-1&&s($.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),$.comment&&(l.comment?l.comment+=`
72
- `+$.comment:l.comment=$.comment),d=$.end;continue}!o&&n.options.strict&&xv.containsNewline(k)&&s(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)$.comma&&s($.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if($.comma||s($.start,"MISSING_CHAR",`Missing , between ${a} items`),$.comment){let E="";e:for(let R of v)switch(R.type){case"comma":case"space":break;case"comment":E=R.source.substring(1);break e;default:break e}if(E){let R=l.items[l.items.length-1];Tv.isPair(R)&&(R=R.value??R.key),R.comment?R.comment+=`
73
- `+E:R.comment=E,$.comment=$.comment.substring(E.length+1)}}if(!o&&!b&&!$.found){let E=S?e(n,S,$,s):t(n,$.end,b,null,$,s);l.items.push(E),d=E.range[2],_o(S)&&s(E.range,"BLOCK_IN_FLOW",Mo)}else{n.atKey=!0;let E=$.end,R=k?e(n,k,$,s):t(n,E,v,null,$,s);_o(k)&&s(R.range,"BLOCK_IN_FLOW",Mo),n.atKey=!1;let j=cp.resolveProps(b??[],{flow:a,indicator:"map-value-ind",next:S,offset:R.range[2],onError:s,parentIndent:r.indent,startOnNewline:!1});if(j.found){if(!o&&!$.found&&n.options.strict){if(b)for(let P of b){if(P===j.found)break;if(P.type==="newline"){s(P,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}$.start<j.found.offset-1024&&s(j.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?s(S,"MISSING_CHAR",`Missing space after : in ${a}`):s(j.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let D=S?e(n,S,j,s):j.found?t(n,j.end,b,null,j,s):null;D?_o(S)&&s(D.range,"BLOCK_IN_FLOW",Mo):j.comment&&(R.comment?R.comment+=`
74
- `+j.comment:R.comment=j.comment);let N=new Pv.Pair(R,D);if(n.options.keepSourceTokens&&(N.srcToken=w),o){let P=l;Mv.mapIncludes(n,P.items,R)&&s(E,"DUPLICATE_KEY","Map keys must be unique"),P.items.push(N)}else{let P=new ap.YAMLMap(n.schema);P.flow=!0,P.items.push(N);let le=(D??R).range;P.range=[R.range[0],le[1],le[2]],l.items.push(P)}d=D?D.range[2]:j.end}}let f=o?"}":"]",[g,...y]=r.end,m=d;if(g?.source===f)m=g.offset+g.source.length;else{let h=a[0].toUpperCase()+a.substring(1),w=u?`${h} must end with a ${f}`:`${h} in block collection must be sufficiently indented and end with a ${f}`;s(d,u?"MISSING_CHAR":"BAD_INDENT",w),g&&g.source.length!==1&&y.unshift(g)}if(y.length>0){let h=Fv.resolveEnd(y,m,n.options.strict,s);h.comment&&(l.comment?l.comment+=`
75
- `+h.comment:l.comment=h.comment),l.range=[r.offset,m,h.offset]}else l.range=[r.offset,m,m];return l}lp.resolveFlowCollection=_v});var fp=C(dp=>{"use strict";var qv=x(),zv=V(),Bv=Xe(),Kv=Ze(),Uv=rp(),Vv=ip(),Wv=up();function qo(e,t,n,r,s,i){let o=n.type==="block-map"?Uv.resolveBlockMap(e,t,n,r,i):n.type==="block-seq"?Vv.resolveBlockSeq(e,t,n,r,i):Wv.resolveFlowCollection(e,t,n,r,i),a=o.constructor;return s==="!"||s===a.tagName?(o.tag=a.tagName,o):(s&&(o.tag=s),o)}function Jv(e,t,n,r,s){let i=r.tag,o=i?t.directives.tagName(i.source,f=>s(i,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:g}=r,y=f&&i?f.offset>i.offset?f:i:f??i;y&&(!g||g.offset<y.offset)&&s(y,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===Bv.YAMLMap.tagName&&a==="map"||o===Kv.YAMLSeq.tagName&&a==="seq")return qo(e,t,n,s,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===a);if(!c){let f=t.schema.knownTags[o];if(f?.collection===a)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?s(i,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),qo(e,t,n,s,o)}let l=qo(e,t,n,s,o,c),u=c.resolve?.(l,f=>s(i,"TAG_RESOLVE_FAILED",f),t.options)??l,d=qv.isNode(u)?u:new zv.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}dp.composeCollection=Jv});var Bo=C(pp=>{"use strict";var zo=V();function Yv(e,t,n){let r=t.offset,s=Gv(t,e.options.strict,n);if(!s)return{value:"",type:null,comment:"",range:[r,r,r]};let i=s.mode===">"?zo.Scalar.BLOCK_FOLDED:zo.Scalar.BLOCK_LITERAL,o=t.source?Hv(t.source):[],a=o.length;for(let m=o.length-1;m>=0;--m){let h=o[m][1];if(h===""||h==="\r")a=m;else break}if(a===0){let m=s.chomp==="+"&&o.length>0?`
76
- `.repeat(Math.max(1,o.length-1)):"",h=r+s.length;return t.source&&(h+=t.source.length),{value:m,type:i,comment:s.comment,range:[r,h,h]}}let c=t.indent+s.indent,l=t.offset+s.length,u=0;for(let m=0;m<a;++m){let[h,w]=o[m];if(w===""||w==="\r")s.indent===0&&h.length>c&&(c=h.length);else{h.length<c&&n(l+h.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(c=h.length),u=m,c===0&&!e.atRoot&&n(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=h.length+w.length+1}for(let m=o.length-1;m>=a;--m)o[m][0].length>c&&(a=m+1);let d="",f="",g=!1;for(let m=0;m<u;++m)d+=o[m][0].slice(c)+`
77
- `;for(let m=u;m<a;++m){let[h,w]=o[m];l+=h.length+w.length+1;let v=w[w.length-1]==="\r";if(v&&(w=w.slice(0,-1)),w&&h.length<c){let b=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;n(l-w.length-(v?2:1),"BAD_INDENT",b),h=""}i===zo.Scalar.BLOCK_LITERAL?(d+=f+h.slice(c)+w,f=`
68
+ `}};Mn.YAMLError=xn;Mn.YAMLParseError=Lo;Mn.YAMLWarning=xo;Mn.prettifyError=Ov});var qn=C(tp=>{"use strict";function Cv(e,{flow:t,indicator:n,next:r,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",f="",y=!1,g=!1,m=null,h=null,w=null,v=null,k=null,E=null,S=null;for(let $ of e)switch(g&&($.type!=="space"&&$.type!=="newline"&&$.type!=="comma"&&i($.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),m&&(l&&$.type!=="comment"&&$.type!=="newline"&&i(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),$.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&$.source.includes(" ")&&(m=$),u=!0;break;case"comment":{u||i($,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let j=$.source.substring(1)||" ";d?d+=f+j:d=j,f="",l=!1;break}case"newline":l?d?d+=$.source:(!E||n!=="seq-item-ind")&&(c=!0):f+=$.source,l=!0,y=!0,(h||w)&&(v=$),u=!0;break;case"anchor":h&&i($,"MULTIPLE_ANCHORS","A node can have at most one anchor"),$.source.endsWith(":")&&i($.offset+$.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=$,S??(S=$.offset),l=!1,u=!1,g=!0;break;case"tag":{w&&i($,"MULTIPLE_TAGS","A node can have at most one tag"),w=$,S??(S=$.offset),l=!1,u=!1,g=!0;break}case n:(h||w)&&i($,"BAD_PROP_ORDER",`Anchors and tags must be after the ${$.source} indicator`),E&&i($,"UNEXPECTED_TOKEN",`Unexpected ${$.source} in ${t??"collection"}`),E=$,l=n==="seq-item-ind"||n==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&i($,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=$,l=!1,u=!1;break}default:i($,"UNEXPECTED_TOKEN",`Unexpected ${$.type} token`),l=!1,u=!1}let R=e[e.length-1],b=R?R.offset+R.source.length:s;return g&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&i(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&i(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:E,spaceBefore:c,comment:d,hasNewline:y,anchor:h,tag:w,newlineAfterProp:v,end:b,start:S??b}}tp.resolveProps=Cv});var As=C(np=>{"use strict";function Mo(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
69
+ `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(Mo(t.key)||Mo(t.value))return!0}return!1;default:return!0}}np.containsNewline=Mo});var _o=C(rp=>{"use strict";var jv=As();function Nv(e,t,n){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&jv.containsNewline(t)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}rp.flowIndentCheck=Nv});var qo=C(ip=>{"use strict";var sp=x();function Iv(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let s=typeof r=="function"?r:(i,o)=>i===o||sp.isScalar(i)&&sp.isScalar(o)&&i.value===o.value;return t.some(i=>s(i.key,n))}ip.mapIncludes=Iv});var dp=C(up=>{"use strict";var op=Qe(),Dv=Ze(),ap=qn(),Pv=As(),cp=_o(),Tv=qo(),lp="All mapping items must start at the same column";function Fv({composeNode:e,composeEmptyNode:t},n,r,s,i){let o=i?.nodeClass??Dv.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:y,value:g}=u,m=ap.resolveProps(d,{indicator:"explicit-key-ind",next:f??y?.[0],offset:c,onError:s,parentIndent:r.indent,startOnNewline:!0}),h=!m.found;if(h){if(f&&(f.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&s(c,"BAD_INDENT",lp)),!m.anchor&&!m.tag&&!y){l=m.end,m.comment&&(a.comment?a.comment+=`
70
+ `+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||Pv.containsNewline(f))&&s(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&s(c,"BAD_INDENT",lp);n.atKey=!0;let w=m.end,v=f?e(n,f,m,s):t(n,w,d,null,m,s);n.schema.compat&&cp.flowIndentCheck(r.indent,f,s),n.atKey=!1,Tv.mapIncludes(n,a.items,v)&&s(w,"DUPLICATE_KEY","Map keys must be unique");let k=ap.resolveProps(y??[],{indicator:"map-value-ind",next:g,offset:v.range[2],onError:s,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){h&&(g?.type==="block-map"&&!k.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&m.start<k.found.offset-1024&&s(v.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let E=g?e(n,g,k,s):t(n,c,y,null,k,s);n.schema.compat&&cp.flowIndentCheck(r.indent,g,s),c=E.range[2];let S=new op.Pair(v,E);n.options.keepSourceTokens&&(S.srcToken=u),a.items.push(S)}else{h&&s(v.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(v.comment?v.comment+=`
71
+ `+k.comment:v.comment=k.comment);let E=new op.Pair(v);n.options.keepSourceTokens&&(E.srcToken=u),a.items.push(E)}}return l&&l<c&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,c,l??c],a}up.resolveBlockMap=Fv});var pp=C(fp=>{"use strict";var Lv=et(),xv=qn(),Mv=_o();function _v({composeNode:e,composeEmptyNode:t},n,r,s,i){let o=i?.nodeClass??Lv.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,l=null;for(let{start:u,value:d}of r.items){let f=xv.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:s,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?s(f.end,"BAD_INDENT","All sequence items must start at the same column"):s(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let y=d?e(n,d,f,s):t(n,f.end,u,null,f,s);n.schema.compat&&Mv.flowIndentCheck(r.indent,d,s),c=y.range[2],a.items.push(y)}return a.range=[r.offset,c,l??c],a}fp.resolveBlockSeq=_v});var Vt=C(hp=>{"use strict";function qv(e,t,n,r){let s="";if(e){let i=!1,o="";for(let a of e){let{source:c,type:l}=a;switch(l){case"space":i=!0;break;case"comment":{n&&!i&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";s?s+=o+u:s=u,o="";break}case"newline":s&&(o+=c),i=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:s,offset:t}}hp.resolveEnd=qv});var wp=C(yp=>{"use strict";var zv=x(),Bv=Qe(),mp=Ze(),Kv=et(),Uv=Vt(),gp=qn(),Vv=As(),Wv=qo(),zo="Block collections are not allowed within flow collections",Bo=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Jv({composeNode:e,composeEmptyNode:t},n,r,s,i){let o=r.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?mp.YAMLMap:Kv.YAMLSeq),l=new c(n.schema);l.flow=!0;let u=n.atRoot;u&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let d=r.offset+r.start.source.length;for(let h=0;h<r.items.length;++h){let w=r.items[h],{start:v,key:k,sep:E,value:S}=w,R=gp.resolveProps(v,{flow:a,indicator:"explicit-key-ind",next:k??E?.[0],offset:d,onError:s,parentIndent:r.indent,startOnNewline:!1});if(!R.found){if(!R.anchor&&!R.tag&&!E&&!S){h===0&&R.comma?s(R.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):h<r.items.length-1&&s(R.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),R.comment&&(l.comment?l.comment+=`
72
+ `+R.comment:l.comment=R.comment),d=R.end;continue}!o&&n.options.strict&&Vv.containsNewline(k)&&s(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)R.comma&&s(R.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(R.comma||s(R.start,"MISSING_CHAR",`Missing , between ${a} items`),R.comment){let b="";e:for(let $ of v)switch($.type){case"comma":case"space":break;case"comment":b=$.source.substring(1);break e;default:break e}if(b){let $=l.items[l.items.length-1];zv.isPair($)&&($=$.value??$.key),$.comment?$.comment+=`
73
+ `+b:$.comment=b,R.comment=R.comment.substring(b.length+1)}}if(!o&&!E&&!R.found){let b=S?e(n,S,R,s):t(n,R.end,E,null,R,s);l.items.push(b),d=b.range[2],Bo(S)&&s(b.range,"BLOCK_IN_FLOW",zo)}else{n.atKey=!0;let b=R.end,$=k?e(n,k,R,s):t(n,b,v,null,R,s);Bo(k)&&s($.range,"BLOCK_IN_FLOW",zo),n.atKey=!1;let j=gp.resolveProps(E??[],{flow:a,indicator:"map-value-ind",next:S,offset:$.range[2],onError:s,parentIndent:r.indent,startOnNewline:!1});if(j.found){if(!o&&!R.found&&n.options.strict){if(E)for(let I of E){if(I===j.found)break;if(I.type==="newline"){s(I,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}R.start<j.found.offset-1024&&s(j.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?s(S,"MISSING_CHAR",`Missing space after : in ${a}`):s(j.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let D=S?e(n,S,j,s):j.found?t(n,j.end,E,null,j,s):null;D?Bo(S)&&s(D.range,"BLOCK_IN_FLOW",zo):j.comment&&($.comment?$.comment+=`
74
+ `+j.comment:$.comment=j.comment);let T=new Bv.Pair($,D);if(n.options.keepSourceTokens&&(T.srcToken=w),o){let I=l;Wv.mapIncludes(n,I.items,$)&&s(b,"DUPLICATE_KEY","Map keys must be unique"),I.items.push(T)}else{let I=new mp.YAMLMap(n.schema);I.flow=!0,I.items.push(T);let H=(D??$).range;I.range=[$.range[0],H[1],H[2]],l.items.push(I)}d=D?D.range[2]:j.end}}let f=o?"}":"]",[y,...g]=r.end,m=d;if(y?.source===f)m=y.offset+y.source.length;else{let h=a[0].toUpperCase()+a.substring(1),w=u?`${h} must end with a ${f}`:`${h} in block collection must be sufficiently indented and end with a ${f}`;s(d,u?"MISSING_CHAR":"BAD_INDENT",w),y&&y.source.length!==1&&g.unshift(y)}if(g.length>0){let h=Uv.resolveEnd(g,m,n.options.strict,s);h.comment&&(l.comment?l.comment+=`
75
+ `+h.comment:l.comment=h.comment),l.range=[r.offset,m,h.offset]}else l.range=[r.offset,m,m];return l}yp.resolveFlowCollection=Jv});var kp=C(vp=>{"use strict";var Yv=x(),Gv=V(),Hv=Ze(),Qv=et(),Xv=dp(),Zv=pp(),ek=wp();function Ko(e,t,n,r,s,i){let o=n.type==="block-map"?Xv.resolveBlockMap(e,t,n,r,i):n.type==="block-seq"?Zv.resolveBlockSeq(e,t,n,r,i):ek.resolveFlowCollection(e,t,n,r,i),a=o.constructor;return s==="!"||s===a.tagName?(o.tag=a.tagName,o):(s&&(o.tag=s),o)}function tk(e,t,n,r,s){let i=r.tag,o=i?t.directives.tagName(i.source,f=>s(i,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:y}=r,g=f&&i?f.offset>i.offset?f:i:f??i;g&&(!y||y.offset<g.offset)&&s(g,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===Hv.YAMLMap.tagName&&a==="map"||o===Qv.YAMLSeq.tagName&&a==="seq")return Ko(e,t,n,s,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===a);if(!c){let f=t.schema.knownTags[o];if(f?.collection===a)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?s(i,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ko(e,t,n,s,o)}let l=Ko(e,t,n,s,o,c),u=c.resolve?.(l,f=>s(i,"TAG_RESOLVE_FAILED",f),t.options)??l,d=Yv.isNode(u)?u:new Gv.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}vp.composeCollection=tk});var Vo=C(bp=>{"use strict";var Uo=V();function nk(e,t,n){let r=t.offset,s=rk(t,e.options.strict,n);if(!s)return{value:"",type:null,comment:"",range:[r,r,r]};let i=s.mode===">"?Uo.Scalar.BLOCK_FOLDED:Uo.Scalar.BLOCK_LITERAL,o=t.source?sk(t.source):[],a=o.length;for(let m=o.length-1;m>=0;--m){let h=o[m][1];if(h===""||h==="\r")a=m;else break}if(a===0){let m=s.chomp==="+"&&o.length>0?`
76
+ `.repeat(Math.max(1,o.length-1)):"",h=r+s.length;return t.source&&(h+=t.source.length),{value:m,type:i,comment:s.comment,range:[r,h,h]}}let c=t.indent+s.indent,l=t.offset+s.length,u=0;for(let m=0;m<a;++m){let[h,w]=o[m];if(w===""||w==="\r")s.indent===0&&h.length>c&&(c=h.length);else{h.length<c&&n(l+h.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(c=h.length),u=m,c===0&&!e.atRoot&&n(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=h.length+w.length+1}for(let m=o.length-1;m>=a;--m)o[m][0].length>c&&(a=m+1);let d="",f="",y=!1;for(let m=0;m<u;++m)d+=o[m][0].slice(c)+`
77
+ `;for(let m=u;m<a;++m){let[h,w]=o[m];l+=h.length+w.length+1;let v=w[w.length-1]==="\r";if(v&&(w=w.slice(0,-1)),w&&h.length<c){let E=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;n(l-w.length-(v?2:1),"BAD_INDENT",E),h=""}i===Uo.Scalar.BLOCK_LITERAL?(d+=f+h.slice(c)+w,f=`
78
78
  `):h.length>c||w[0]===" "?(f===" "?f=`
79
- `:!g&&f===`
79
+ `:!y&&f===`
80
80
  `&&(f=`
81
81
 
82
82
  `),d+=f+h.slice(c)+w,f=`
83
- `,g=!0):w===""?f===`
83
+ `,y=!0):w===""?f===`
84
84
  `?d+=`
85
85
  `:f=`
86
- `:(d+=f+w,f=" ",g=!1)}switch(s.chomp){case"-":break;case"+":for(let m=a;m<o.length;++m)d+=`
86
+ `:(d+=f+w,f=" ",y=!1)}switch(s.chomp){case"-":break;case"+":for(let m=a;m<o.length;++m)d+=`
87
87
  `+o[m][0].slice(c);d[d.length-1]!==`
88
88
  `&&(d+=`
89
89
  `);break;default:d+=`
90
- `}let y=r+s.length+t.source.length;return{value:d,type:i,comment:s.comment,range:[r,y,y]}}function Gv({offset:e,props:t},n,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=t[0],i=s[0],o=0,a="",c=-1;for(let f=1;f<s.length;++f){let g=s[f];if(!a&&(g==="-"||g==="+"))a=g;else{let y=Number(g);!o&&y?o=y:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,u="",d=s.length;for(let f=1;f<t.length;++f){let g=t[f];switch(g.type){case"space":l=!0;case"newline":d+=g.source.length;break;case"comment":n&&!l&&r(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=g.source.length,u=g.source.substring(1);break;case"error":r(g,"UNEXPECTED_TOKEN",g.message),d+=g.source.length;break;default:{let y=`Unexpected token in block scalar header: ${g.type}`;r(g,"UNEXPECTED_TOKEN",y);let m=g.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:i,indent:o,chomp:a,comment:u,length:d}}function Hv(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let o=1;o<t.length;o+=2)i.push([t[o],t[o+1]]);return i}pp.resolveBlockScalar=Yv});var Uo=C(mp=>{"use strict";var Ko=V(),Qv=Kt();function Xv(e,t,n){let{offset:r,type:s,source:i,end:o}=e,a,c,l=(f,g,y)=>n(r+f,g,y);switch(s){case"scalar":a=Ko.Scalar.PLAIN,c=Zv(i,l);break;case"single-quoted-scalar":a=Ko.Scalar.QUOTE_SINGLE,c=ek(i,l);break;case"double-quoted-scalar":a=Ko.Scalar.QUOTE_DOUBLE,c=tk(i,l);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[r,r+i.length,r+i.length]}}let u=r+i.length,d=Qv.resolveEnd(o,u,t,n);return{value:c,type:a,comment:d.comment,range:[r,u,d.offset]}}function Zv(e,t){let n="";switch(e[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}return n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),hp(e)}function ek(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),hp(e.slice(1,-1)).replace(/''/g,"'")}function hp(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,s;try{r=new RegExp("(?<![ ])[ ]+$"),s=new RegExp("^[ ]+|(?<![ ])[ ]+$","g")}catch{r=/[ \t]+$/,s=/^[ \t]+|[ \t]+$/g}let i=n[1].replace(r,""),o=" ",a=t.lastIndex;for(;n=t.exec(e);){let l=n[1].replace(s,"");l===""?o===`
90
+ `}let g=r+s.length+t.source.length;return{value:d,type:i,comment:s.comment,range:[r,g,g]}}function rk({offset:e,props:t},n,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=t[0],i=s[0],o=0,a="",c=-1;for(let f=1;f<s.length;++f){let y=s[f];if(!a&&(y==="-"||y==="+"))a=y;else{let g=Number(y);!o&&g?o=g:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,u="",d=s.length;for(let f=1;f<t.length;++f){let y=t[f];switch(y.type){case"space":l=!0;case"newline":d+=y.source.length;break;case"comment":n&&!l&&r(y,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=y.source.length,u=y.source.substring(1);break;case"error":r(y,"UNEXPECTED_TOKEN",y.message),d+=y.source.length;break;default:{let g=`Unexpected token in block scalar header: ${y.type}`;r(y,"UNEXPECTED_TOKEN",g);let m=y.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:i,indent:o,chomp:a,comment:u,length:d}}function sk(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let o=1;o<t.length;o+=2)i.push([t[o],t[o+1]]);return i}bp.resolveBlockScalar=nk});var Jo=C(Sp=>{"use strict";var Wo=V(),ik=Vt();function ok(e,t,n){let{offset:r,type:s,source:i,end:o}=e,a,c,l=(f,y,g)=>n(r+f,y,g);switch(s){case"scalar":a=Wo.Scalar.PLAIN,c=ak(i,l);break;case"single-quoted-scalar":a=Wo.Scalar.QUOTE_SINGLE,c=ck(i,l);break;case"double-quoted-scalar":a=Wo.Scalar.QUOTE_DOUBLE,c=lk(i,l);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[r,r+i.length,r+i.length]}}let u=r+i.length,d=ik.resolveEnd(o,u,t,n);return{value:c,type:a,comment:d.comment,range:[r,u,d.offset]}}function ak(e,t){let n="";switch(e[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}return n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Ep(e)}function ck(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Ep(e.slice(1,-1)).replace(/''/g,"'")}function Ep(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,s;try{r=new RegExp("(?<![ ])[ ]+$"),s=new RegExp("^[ ]+|(?<![ ])[ ]+$","g")}catch{r=/[ \t]+$/,s=/^[ \t]+|[ \t]+$/g}let i=n[1].replace(r,""),o=" ",a=t.lastIndex;for(;n=t.exec(e);){let l=n[1].replace(s,"");l===""?o===`
91
91
  `?i+=o:o=`
92
- `:(i+=o+l,o=" "),a=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=a,n=c.exec(e),i+o+(n?.[1]??"")}function tk(e,t){let n="";for(let r=1;r<e.length-1;++r){let s=e[r];if(!(s==="\r"&&e[r+1]===`
92
+ `:(i+=o+l,o=" "),a=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=a,n=c.exec(e),i+o+(n?.[1]??"")}function lk(e,t){let n="";for(let r=1;r<e.length-1;++r){let s=e[r];if(!(s==="\r"&&e[r+1]===`
93
93
  `))if(s===`
94
- `){let{fold:i,offset:o}=nk(e,r);n+=i,r=o}else if(s==="\\"){let i=e[++r],o=rk[i];if(o)n+=o;else if(i===`
94
+ `){let{fold:i,offset:o}=uk(e,r);n+=i,r=o}else if(s==="\\"){let i=e[++r],o=dk[i];if(o)n+=o;else if(i===`
95
95
  `)for(i=e[r+1];i===" "||i===" ";)i=e[++r+1];else if(i==="\r"&&e[r+1]===`
96
- `)for(i=e[++r+1];i===" "||i===" ";)i=e[++r+1];else if(i==="x"||i==="u"||i==="U"){let a=i==="x"?2:i==="u"?4:8;n+=sk(e,r+1,a,t),r+=a}else{let a=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(s===" "||s===" "){let i=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
96
+ `)for(i=e[++r+1];i===" "||i===" ";)i=e[++r+1];else if(i==="x"||i==="u"||i==="U"){let a=i==="x"?2:i==="u"?4:8;n+=fk(e,r+1,a,t),r+=a}else{let a=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(s===" "||s===" "){let i=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
97
97
  `&&!(o==="\r"&&e[r+2]===`
98
- `)&&(n+=r>i?e.slice(i,r+1):s)}else n+=s}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function nk(e,t){let n="",r=e[t+1];for(;(r===" "||r===" "||r===`
98
+ `)&&(n+=r>i?e.slice(i,r+1):s)}else n+=s}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function uk(e,t){let n="",r=e[t+1];for(;(r===" "||r===" "||r===`
99
99
  `||r==="\r")&&!(r==="\r"&&e[t+2]!==`
100
100
  `);)r===`
101
101
  `&&(n+=`
102
- `),t+=1,r=e[t+1];return n||(n=" "),{fold:n,offset:t}}var rk={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
103
- `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function sk(e,t,n,r){let s=e.substr(t,n),o=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;try{return String.fromCodePoint(o)}catch{let a=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}mp.resolveFlowScalar=Xv});var wp=C(yp=>{"use strict";var ht=x(),gp=V(),ik=Bo(),ok=Uo();function ak(e,t,n,r){let{value:s,type:i,comment:o,range:a}=t.type==="block-scalar"?ik.resolveBlockScalar(e,t,r):ok.resolveFlowScalar(t,e.options.strict,r),c=n?e.directives.tagName(n.source,d=>r(n,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[ht.SCALAR]:c?l=ck(e.schema,s,c,n,r):t.type==="scalar"?l=lk(e,s,t,r):l=e.schema[ht.SCALAR];let u;try{let d=l.resolve(s,f=>r(n??t,"TAG_RESOLVE_FAILED",f),e.options);u=ht.isScalar(d)?d:new gp.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(n??t,"TAG_RESOLVE_FAILED",f),u=new gp.Scalar(s)}return u.range=a,u.source=s,i&&(u.type=i),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function ck(e,t,n,r,s){if(n==="!")return e[ht.SCALAR];let i=[];for(let a of e.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)i.push(a);else return a;for(let a of i)if(a.test?.test(t))return a;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(s(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[ht.SCALAR])}function lk({atKey:e,directives:t,schema:n},r,s,i){let o=n.tags.find(a=>(a.default===!0||e&&a.default==="key")&&a.test?.test(r))||n[ht.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(r))??n[ht.SCALAR];if(o.tag!==a.tag){let c=t.tagString(o.tag),l=t.tagString(a.tag),u=`Value may be parsed as either ${c} or ${l}`;i(s,"TAG_RESOLVE_FAILED",u,!0)}}return o}yp.composeScalar=ak});var kp=C(vp=>{"use strict";function uk(e,t,n){if(t){n??(n=t.length);for(let r=n-1;r>=0;--r){let s=t[r];switch(s.type){case"space":case"comment":case"newline":e-=s.source.length;continue}for(s=t[++r];s?.type==="space";)e+=s.source.length,s=t[++r];break}}return e}vp.emptyScalarPosition=uk});var Sp=C(Wo=>{"use strict";var dk=kn(),fk=x(),pk=fp(),bp=wp(),hk=Kt(),mk=kp(),gk={composeNode:Ep,composeEmptyNode:Vo};function Ep(e,t,n,r){let s=e.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=n,l,u=!0;switch(t.type){case"alias":l=yk(e,t,r),(a||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=bp.composeScalar(e,t,c,r),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=pk.composeCollection(gk,e,t,n,r),a&&(l.anchor=a.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Vo(e,t.offset,void 0,null,n,r)),a&&l.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&e.options.stringKeys&&(!fk.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Vo(e,t,n,r,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:mk.emptyScalarPosition(t,n,r),indent:-1,source:""},d=bp.composeScalar(e,u,a,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(d.spaceBefore=!0),i&&(d.comment=i,d.range[2]=c),d}function yk({options:e},{offset:t,source:n,end:r},s){let i=new dk.Alias(n.substring(1));i.source===""&&s(t,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&s(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+n.length,a=hk.resolveEnd(r,o,e.strict,s);return i.range=[t,o,a.offset],a.comment&&(i.comment=a.comment),i}Wo.composeEmptyNode=Vo;Wo.composeNode=Ep});var Ap=C($p=>{"use strict";var wk=Fn(),Rp=Sp(),vk=Kt(),kk=qn();function bk(e,t,{offset:n,start:r,value:s,end:i},o){let a=Object.assign({_directives:t},e),c=new wk.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=kk.resolveProps(r,{indicator:"doc-start",next:s??i?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?Rp.composeNode(l,s,u,o):Rp.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=vk.resolveEnd(i,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,d,f.offset],c}$p.composeDoc=bk});var Yo=C(jp=>{"use strict";var Ek=er("process"),Sk=Di(),Rk=Fn(),zn=_n(),Op=x(),$k=Ap(),Ak=Kt();function Bn(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n=="string"?n.length:1)]}function Cp(e){let t="",n=!1,r=!1;for(let s=0;s<e.length;++s){let i=e[s];switch(i[0]){case"#":t+=(t===""?"":r?`
102
+ `),t+=1,r=e[t+1];return n||(n=" "),{fold:n,offset:t}}var dk={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
103
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function fk(e,t,n,r){let s=e.substr(t,n),o=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;try{return String.fromCodePoint(o)}catch{let a=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}Sp.resolveFlowScalar=ok});var Ap=C($p=>{"use strict";var gt=x(),Rp=V(),pk=Vo(),hk=Jo();function mk(e,t,n,r){let{value:s,type:i,comment:o,range:a}=t.type==="block-scalar"?pk.resolveBlockScalar(e,t,r):hk.resolveFlowScalar(t,e.options.strict,r),c=n?e.directives.tagName(n.source,d=>r(n,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[gt.SCALAR]:c?l=gk(e.schema,s,c,n,r):t.type==="scalar"?l=yk(e,s,t,r):l=e.schema[gt.SCALAR];let u;try{let d=l.resolve(s,f=>r(n??t,"TAG_RESOLVE_FAILED",f),e.options);u=gt.isScalar(d)?d:new Rp.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(n??t,"TAG_RESOLVE_FAILED",f),u=new Rp.Scalar(s)}return u.range=a,u.source=s,i&&(u.type=i),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function gk(e,t,n,r,s){if(n==="!")return e[gt.SCALAR];let i=[];for(let a of e.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)i.push(a);else return a;for(let a of i)if(a.test?.test(t))return a;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(s(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[gt.SCALAR])}function yk({atKey:e,directives:t,schema:n},r,s,i){let o=n.tags.find(a=>(a.default===!0||e&&a.default==="key")&&a.test?.test(r))||n[gt.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(r))??n[gt.SCALAR];if(o.tag!==a.tag){let c=t.tagString(o.tag),l=t.tagString(a.tag),u=`Value may be parsed as either ${c} or ${l}`;i(s,"TAG_RESOLVE_FAILED",u,!0)}}return o}$p.composeScalar=mk});var Cp=C(Op=>{"use strict";function wk(e,t,n){if(t){n??(n=t.length);for(let r=n-1;r>=0;--r){let s=t[r];switch(s.type){case"space":case"comment":case"newline":e-=s.source.length;continue}for(s=t[++r];s?.type==="space";)e+=s.source.length,s=t[++r];break}}return e}Op.emptyScalarPosition=wk});var Ip=C(Go=>{"use strict";var vk=kn(),kk=x(),bk=kp(),jp=Ap(),Ek=Vt(),Sk=Cp(),Rk={composeNode:Np,composeEmptyNode:Yo};function Np(e,t,n,r){let s=e.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=n,l,u=!0;switch(t.type){case"alias":l=$k(e,t,r),(a||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=jp.composeScalar(e,t,c,r),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=bk.composeCollection(Rk,e,t,n,r),a&&(l.anchor=a.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Yo(e,t.offset,void 0,null,n,r)),a&&l.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&e.options.stringKeys&&(!kk.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Yo(e,t,n,r,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:Sk.emptyScalarPosition(t,n,r),indent:-1,source:""},d=jp.composeScalar(e,u,a,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(d.spaceBefore=!0),i&&(d.comment=i,d.range[2]=c),d}function $k({options:e},{offset:t,source:n,end:r},s){let i=new vk.Alias(n.substring(1));i.source===""&&s(t,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&s(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+n.length,a=Ek.resolveEnd(r,o,e.strict,s);return i.range=[t,o,a.offset],a.comment&&(i.comment=a.comment),i}Go.composeEmptyNode=Yo;Go.composeNode=Np});var Tp=C(Pp=>{"use strict";var Ak=Ln(),Dp=Ip(),Ok=Vt(),Ck=qn();function jk(e,t,{offset:n,start:r,value:s,end:i},o){let a=Object.assign({_directives:t},e),c=new Ak.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Ck.resolveProps(r,{indicator:"doc-start",next:s??i?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?Dp.composeNode(l,s,u,o):Dp.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=Ok.resolveEnd(i,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,d,f.offset],c}Pp.composeDoc=jk});var Qo=C(xp=>{"use strict";var Nk=er("process"),Ik=Fi(),Dk=Ln(),zn=_n(),Fp=x(),Pk=Tp(),Tk=Vt();function Bn(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n=="string"?n.length:1)]}function Lp(e){let t="",n=!1,r=!1;for(let s=0;s<e.length;++s){let i=e[s];switch(i[0]){case"#":t+=(t===""?"":r?`
104
104
 
105
105
  `:`
106
- `)+(i.substring(1)||" "),n=!0,r=!1;break;case"%":e[s+1]?.[0]!=="#"&&(s+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var Jo=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,s,i)=>{let o=Bn(n);i?this.warnings.push(new zn.YAMLWarning(o,r,s)):this.errors.push(new zn.YAMLParseError(o,r,s))},this.directives=new Sk.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:r,afterEmptyLine:s}=Cp(this.prelude);if(r){let i=t.contents;if(n)t.comment=t.comment?`${t.comment}
107
- ${r}`:r;else if(s||t.directives.docStart||!i)t.commentBefore=r;else if(Op.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];Op.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${r}
106
+ `)+(i.substring(1)||" "),n=!0,r=!1;break;case"%":e[s+1]?.[0]!=="#"&&(s+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var Ho=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,s,i)=>{let o=Bn(n);i?this.warnings.push(new zn.YAMLWarning(o,r,s)):this.errors.push(new zn.YAMLParseError(o,r,s))},this.directives=new Ik.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:r,afterEmptyLine:s}=Lp(this.prelude);if(r){let i=t.contents;if(n)t.comment=t.comment?`${t.comment}
107
+ ${r}`:r;else if(s||t.directives.docStart||!i)t.commentBefore=r;else if(Fp.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];Fp.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${r}
108
108
  ${a}`:r}else{let o=i.commentBefore;i.commentBefore=o?`${r}
109
- ${o}`:r}}if(n){for(let i=0;i<this.errors.length;++i)t.errors.push(this.errors[i]);for(let i=0;i<this.warnings.length;++i)t.warnings.push(this.warnings[i])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Cp(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,n=!1,r=-1){for(let s of t)yield*this.next(s);yield*this.end(n,r)}*next(t){switch(Ek.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(n,r,s)=>{let i=Bn(t);i[0]+=n,this.onError(i,"BAD_DIRECTIVE",r,s)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=$k.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let n=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new zn.YAMLParseError(Bn(t),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new zn.YAMLParseError(Bn(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=Ak.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
110
- ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new zn.YAMLParseError(Bn(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),s=new Rk.Document(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),s.range=[0,n,n],this.decorate(s,!1),yield s}}};jp.Composer=Jo});var Dp=C($s=>{"use strict";var Ok=Bo(),Ck=Uo(),jk=_n(),Np=$n();function Nk(e,t=!0,n){if(e){let r=(s,i,o)=>{let a=typeof s=="number"?s:Array.isArray(s)?s[0]:s.offset;if(n)n(a,i,o);else throw new jk.YAMLParseError([a,a+1],i,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Ck.resolveFlowScalar(e,t,r);case"block-scalar":return Ok.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function Ik(e,t){let{implicitKey:n=!1,indent:r,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=t,a=Np.stringifyString({type:o,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
109
+ ${o}`:r}}if(n){for(let i=0;i<this.errors.length;++i)t.errors.push(this.errors[i]);for(let i=0;i<this.warnings.length;++i)t.warnings.push(this.warnings[i])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Lp(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,n=!1,r=-1){for(let s of t)yield*this.next(s);yield*this.end(n,r)}*next(t){switch(Nk.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(n,r,s)=>{let i=Bn(t);i[0]+=n,this.onError(i,"BAD_DIRECTIVE",r,s)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=Pk.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let n=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new zn.YAMLParseError(Bn(t),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new zn.YAMLParseError(Bn(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=Tk.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
110
+ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new zn.YAMLParseError(Bn(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),s=new Dk.Document(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),s.range=[0,n,n],this.decorate(s,!1),yield s}}};xp.Composer=Ho});var qp=C(Os=>{"use strict";var Fk=Vo(),Lk=Jo(),xk=_n(),Mp=$n();function Mk(e,t=!0,n){if(e){let r=(s,i,o)=>{let a=typeof s=="number"?s:Array.isArray(s)?s[0]:s.offset;if(n)n(a,i,o);else throw new xk.YAMLParseError([a,a+1],i,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Lk.resolveFlowScalar(e,t,r);case"block-scalar":return Fk.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function _k(e,t){let{implicitKey:n=!1,indent:r,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=t,a=Mp.stringifyString({type:o,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
111
111
  `}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
112
112
  `),u=a.substring(0,l),d=a.substring(l+1)+`
113
- `,f=[{type:"block-scalar-header",offset:i,indent:r,source:u}];return Ip(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
114
- `}),{type:"block-scalar",offset:i,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:i,indent:r,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:r,source:a,end:c};default:return{type:"scalar",offset:i,indent:r,source:a,end:c}}}function Dk(e,t,n={}){let{afterKey:r=!1,implicitKey:s=!1,inFlow:i=!1,type:o}=n,a="indent"in e?e.indent:null;if(r&&typeof a=="number"&&(a+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Np.stringifyString({type:o,value:t},{implicitKey:s||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Tk(e,c);break;case'"':Go(e,c,"double-quoted-scalar");break;case"'":Go(e,c,"single-quoted-scalar");break;default:Go(e,c,"scalar")}}function Tk(e,t){let n=t.indexOf(`
113
+ `,f=[{type:"block-scalar-header",offset:i,indent:r,source:u}];return _p(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
114
+ `}),{type:"block-scalar",offset:i,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:i,indent:r,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:r,source:a,end:c};default:return{type:"scalar",offset:i,indent:r,source:a,end:c}}}function qk(e,t,n={}){let{afterKey:r=!1,implicitKey:s=!1,inFlow:i=!1,type:o}=n,a="indent"in e?e.indent:null;if(r&&typeof a=="number"&&(a+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Mp.stringifyString({type:o,value:t},{implicitKey:s||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":zk(e,c);break;case'"':Xo(e,c,"double-quoted-scalar");break;case"'":Xo(e,c,"single-quoted-scalar");break;default:Xo(e,c,"scalar")}}function zk(e,t){let n=t.indexOf(`
115
115
  `),r=t.substring(0,n),s=t.substring(n+1)+`
116
- `;if(e.type==="block-scalar"){let i=e.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=r,e.source=s}else{let{offset:i}=e,o="indent"in e?e.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:r}];Ip(a,"end"in e?e.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
117
- `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:a,source:s})}}function Ip(e,t){if(t)for(let n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function Go(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),s=t.length;e.props[0].type==="block-scalar-header"&&(s-=e.props[0].source.length);for(let i of r)i.offset+=s;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case"block-map":case"block-seq":{let s={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
118
- `};delete e.items,Object.assign(e,{type:n,source:t,end:[s]});break}default:{let r="indent"in e?e.indent:-1,s="end"in e&&Array.isArray(e.end)?e.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(e))i!=="type"&&i!=="offset"&&delete e[i];Object.assign(e,{type:n,indent:r,source:t,end:s})}}}$s.createScalarToken=Ik;$s.resolveAsScalar=Nk;$s.setScalarValue=Dk});var Pp=C(Tp=>{"use strict";var Pk=e=>"type"in e?Os(e):As(e);function Os(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=Os(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=As(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=As(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=As(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function As({start:e,key:t,sep:n,value:r}){let s="";for(let i of e)s+=i.source;if(t&&(s+=Os(t)),n)for(let i of n)s+=i.source;return r&&(s+=Os(r)),s}Tp.stringify=Pk});var Mp=C(xp=>{"use strict";var Ho=Symbol("break visit"),Lk=Symbol("skip children"),Lp=Symbol("remove item");function mt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Fp(Object.freeze([]),e,t)}mt.BREAK=Ho;mt.SKIP=Lk;mt.REMOVE=Lp;mt.itemAtPath=(e,t)=>{let n=e;for(let[r,s]of t){let i=n?.[r];if(i&&"items"in i)n=i.items[s];else return}return n};mt.parentCollection=(e,t)=>{let n=mt.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],s=n?.[r];if(s&&"items"in s)return s;throw new Error("Parent collection not found")};function Fp(e,t,n){let r=n(t,e);if(typeof r=="symbol")return r;for(let s of["key","value"]){let i=t[s];if(i&&"items"in i){for(let o=0;o<i.items.length;++o){let a=Fp(Object.freeze(e.concat([[s,o]])),i.items[o],n);if(typeof a=="number")o=a-1;else{if(a===Ho)return Ho;a===Lp&&(i.items.splice(o,1),o-=1)}}typeof r=="function"&&s==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}xp.visit=mt});var Cs=C(oe=>{"use strict";var Qo=Dp(),Fk=Pp(),xk=Mp(),Xo="\uFEFF",Zo="",ea="",ta="",Mk=e=>!!e&&"items"in e,_k=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function qk(e){switch(e){case Xo:return"<BOM>";case Zo:return"<DOC>";case ea:return"<FLOW_END>";case ta:return"<SCALAR>";default:return JSON.stringify(e)}}function zk(e){switch(e){case Xo:return"byte-order-mark";case Zo:return"doc-mode";case ea:return"flow-error-end";case ta:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
116
+ `;if(e.type==="block-scalar"){let i=e.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=r,e.source=s}else{let{offset:i}=e,o="indent"in e?e.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:r}];_p(a,"end"in e?e.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
117
+ `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:a,source:s})}}function _p(e,t){if(t)for(let n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function Xo(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),s=t.length;e.props[0].type==="block-scalar-header"&&(s-=e.props[0].source.length);for(let i of r)i.offset+=s;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case"block-map":case"block-seq":{let s={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
118
+ `};delete e.items,Object.assign(e,{type:n,source:t,end:[s]});break}default:{let r="indent"in e?e.indent:-1,s="end"in e&&Array.isArray(e.end)?e.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(e))i!=="type"&&i!=="offset"&&delete e[i];Object.assign(e,{type:n,indent:r,source:t,end:s})}}}Os.createScalarToken=_k;Os.resolveAsScalar=Mk;Os.setScalarValue=qk});var Bp=C(zp=>{"use strict";var Bk=e=>"type"in e?js(e):Cs(e);function js(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=js(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=Cs(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=Cs(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=Cs(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function Cs({start:e,key:t,sep:n,value:r}){let s="";for(let i of e)s+=i.source;if(t&&(s+=js(t)),n)for(let i of n)s+=i.source;return r&&(s+=js(r)),s}zp.stringify=Bk});var Wp=C(Vp=>{"use strict";var Zo=Symbol("break visit"),Kk=Symbol("skip children"),Kp=Symbol("remove item");function yt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Up(Object.freeze([]),e,t)}yt.BREAK=Zo;yt.SKIP=Kk;yt.REMOVE=Kp;yt.itemAtPath=(e,t)=>{let n=e;for(let[r,s]of t){let i=n?.[r];if(i&&"items"in i)n=i.items[s];else return}return n};yt.parentCollection=(e,t)=>{let n=yt.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],s=n?.[r];if(s&&"items"in s)return s;throw new Error("Parent collection not found")};function Up(e,t,n){let r=n(t,e);if(typeof r=="symbol")return r;for(let s of["key","value"]){let i=t[s];if(i&&"items"in i){for(let o=0;o<i.items.length;++o){let a=Up(Object.freeze(e.concat([[s,o]])),i.items[o],n);if(typeof a=="number")o=a-1;else{if(a===Zo)return Zo;a===Kp&&(i.items.splice(o,1),o-=1)}}typeof r=="function"&&s==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}Vp.visit=yt});var Ns=C(oe=>{"use strict";var ea=qp(),Uk=Bp(),Vk=Wp(),ta="\uFEFF",na="",ra="",sa="",Wk=e=>!!e&&"items"in e,Jk=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function Yk(e){switch(e){case ta:return"<BOM>";case na:return"<DOC>";case ra:return"<FLOW_END>";case sa:return"<SCALAR>";default:return JSON.stringify(e)}}function Gk(e){switch(e){case ta:return"byte-order-mark";case na:return"doc-mode";case ra:return"flow-error-end";case sa:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
119
119
  `:case`\r
120
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}oe.createScalarToken=Qo.createScalarToken;oe.resolveAsScalar=Qo.resolveAsScalar;oe.setScalarValue=Qo.setScalarValue;oe.stringify=Fk.stringify;oe.visit=xk.visit;oe.BOM=Xo;oe.DOCUMENT=Zo;oe.FLOW_END=ea;oe.SCALAR=ta;oe.isCollection=Mk;oe.isScalar=_k;oe.prettyToken=qk;oe.tokenType=zk});var sa=C(qp=>{"use strict";var Kn=Cs();function ve(e){switch(e){case void 0:case" ":case`
121
- `:case"\r":case" ":return!0;default:return!1}}var _p=new Set("0123456789ABCDEFabcdef"),Bk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),js=new Set(",[]{}"),Kk=new Set(` ,[]{}
122
- \r `),na=e=>!e||Kk.has(e),ra=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,n=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,n=this.buffer[t];for(;n===" "||n===" ";)n=this.buffer[++t];return!n||n==="#"||n===`
120
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}oe.createScalarToken=ea.createScalarToken;oe.resolveAsScalar=ea.resolveAsScalar;oe.setScalarValue=ea.setScalarValue;oe.stringify=Uk.stringify;oe.visit=Vk.visit;oe.BOM=ta;oe.DOCUMENT=na;oe.FLOW_END=ra;oe.SCALAR=sa;oe.isCollection=Wk;oe.isScalar=Jk;oe.prettyToken=Yk;oe.tokenType=Gk});var aa=C(Yp=>{"use strict";var Kn=Ns();function we(e){switch(e){case void 0:case" ":case`
121
+ `:case"\r":case" ":return!0;default:return!1}}var Jp=new Set("0123456789ABCDEFabcdef"),Hk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Is=new Set(",[]{}"),Qk=new Set(` ,[]{}
122
+ \r `),ia=e=>!e||Qk.has(e),oa=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,n=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,n=this.buffer[t];for(;n===" "||n===" ";)n=this.buffer[++t];return!n||n==="#"||n===`
123
123
  `?!0:n==="\r"?this.buffer[t+1]===`
124
124
  `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let n=this.buffer[t];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+t];if(n==="\r"){let s=this.buffer[r+t+1];if(s===`
125
125
  `||!s&&!this.atEnd)return t+r+1}return n===`
126
- `||r>=this.indentNext||!n&&!this.atEnd?t+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&ve(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
127
- `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Kn.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let n=t.length,r=t.indexOf("#");for(;r!==-1;){let i=t[r-1];if(i===" "||i===" "){n=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let i=t[n-1];if(i===" "||i===" ")n-=1;else break}let s=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-s),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-n),yield*this.pushNewline(),"stream"}return yield Kn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&ve(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!ve(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&ve(n)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(t[n]){case"#":yield*this.pushCount(t.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(na),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,n,r=-1;do t=yield*this.pushNewline(),t>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(t+n>0);let s=this.getLine();if(s===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&s[0]!=="#"||r===0&&(s.startsWith("---")||s.startsWith("..."))&&ve(s[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield Kn.FLOW_END,yield*this.parseLineStart();let i=0;for(;s[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),s[i]){case void 0:return"flow";case"#":return yield*this.pushCount(s.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(na),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||ve(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),n=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let i=0;for(;this.buffer[n-1-i]==="\\";)i+=1;if(i%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),s=r.indexOf(`
126
+ `||r>=this.indentNext||!n&&!this.atEnd?t+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&we(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
127
+ `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Kn.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let n=t.length,r=t.indexOf("#");for(;r!==-1;){let i=t[r-1];if(i===" "||i===" "){n=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let i=t[n-1];if(i===" "||i===" ")n-=1;else break}let s=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-s),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-n),yield*this.pushNewline(),"stream"}return yield Kn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&we(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!we(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&we(n)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(t[n]){case"#":yield*this.pushCount(t.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(ia),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,n,r=-1;do t=yield*this.pushNewline(),t>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(t+n>0);let s=this.getLine();if(s===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&s[0]!=="#"||r===0&&(s.startsWith("---")||s.startsWith("..."))&&we(s[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield Kn.FLOW_END,yield*this.parseLineStart();let i=0;for(;s[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),s[i]){case void 0:return"flow";case"#":return yield*this.pushCount(s.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(ia),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||we(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),n=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let i=0;for(;this.buffer[n-1-i]==="\\";)i+=1;if(i%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),s=r.indexOf(`
128
128
  `,this.pos);if(s!==-1){for(;s!==-1;){let i=this.continueScalar(s+1);if(i===-1)break;s=r.indexOf(`
129
- `,i)}s!==-1&&(n=s-(r[s-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let n=this.buffer[++t];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>ve(n)||n==="#")}*parseBlockScalar(){let t=this.pos-1,n=0,r;e:for(let i=this.pos;r=this.buffer[i];++i)switch(r){case" ":n+=1;break;case`
129
+ `,i)}s!==-1&&(n=s-(r[s-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let n=this.buffer[++t];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>we(n)||n==="#")}*parseBlockScalar(){let t=this.pos-1,n=0,r;e:for(let i=this.pos;r=this.buffer[i];++i)switch(r){case" ":n+=1;break;case`
130
130
  `:t=i,n=0;break;case"\r":{let o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
131
131
  `)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let i=this.continueScalar(t+1);if(i===-1)break;t=this.buffer.indexOf(`
132
132
  `,i)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let s=t+1;for(r=this.buffer[s];r===" ";)r=this.buffer[++s];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
133
133
  `;)r=this.buffer[++s];t=s-1}else if(!this.blockScalarKeep)do{let i=t-1,o=this.buffer[i];o==="\r"&&(o=this.buffer[--i]);let a=i;for(;o===" ";)o=this.buffer[--i];if(o===`
134
- `&&i>=this.pos&&i+1+n>a)t=i;else break}while(!0);return yield Kn.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,n=this.pos-1,r=this.pos-1,s;for(;s=this.buffer[++r];)if(s===":"){let i=this.buffer[r+1];if(ve(i)||t&&js.has(i))break;n=r}else if(ve(s)){let i=this.buffer[r+1];if(s==="\r"&&(i===`
134
+ `&&i>=this.pos&&i+1+n>a)t=i;else break}while(!0);return yield Kn.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,n=this.pos-1,r=this.pos-1,s;for(;s=this.buffer[++r];)if(s===":"){let i=this.buffer[r+1];if(we(i)||t&&Is.has(i))break;n=r}else if(we(s)){let i=this.buffer[r+1];if(s==="\r"&&(i===`
135
135
  `?(r+=1,s=`
136
- `,i=this.buffer[r+1]):n=r),i==="#"||t&&js.has(i))break;if(s===`
137
- `){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&js.has(s))break;n=r}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield Kn.SCALAR,yield*this.pushToIndex(n+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,n){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(na),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(ve(r)||n&&js.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,n=this.buffer[t];for(;!ve(n)&&n!==">";)n=this.buffer[++t];return yield*this.pushToIndex(n===">"?t+1:t,!1)}else{let t=this.pos+1,n=this.buffer[t];for(;n;)if(Bk.has(n))n=this.buffer[++t];else if(n==="%"&&_p.has(this.buffer[t+1])&&_p.has(this.buffer[t+2]))n=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
136
+ `,i=this.buffer[r+1]):n=r),i==="#"||t&&Is.has(i))break;if(s===`
137
+ `){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&Is.has(s))break;n=r}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield Kn.SCALAR,yield*this.pushToIndex(n+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,n){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(ia),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(we(r)||n&&Is.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,n=this.buffer[t];for(;!we(n)&&n!==">";)n=this.buffer[++t];return yield*this.pushToIndex(n===">"?t+1:t,!1)}else{let t=this.pos+1,n=this.buffer[t];for(;n;)if(Hk.has(n))n=this.buffer[++t];else if(n==="%"&&Jp.has(this.buffer[t+1])&&Jp.has(this.buffer[t+2]))n=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
138
138
  `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
139
- `?yield*this.pushCount(2):0}*pushSpaces(t){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||t&&r===" ");let s=n-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=n),s}*pushUntil(t){let n=this.pos,r=this.buffer[n];for(;!t(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};qp.Lexer=ra});var oa=C(zp=>{"use strict";var ia=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let n=0,r=this.lineStarts.length;for(;n<r;){let i=n+r>>1;this.lineStarts[i]<t?n=i+1:r=i}if(this.lineStarts[n]===t)return{line:n+1,col:1};if(n===0)return{line:0,col:t};let s=this.lineStarts[n-1];return{line:n,col:t-s+1}}}};zp.LineCounter=ia});var ca=C(Wp=>{"use strict";var Uk=er("process"),Bp=Cs(),Vk=sa();function et(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Kp(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Vp(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Ns(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Ut(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Is(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function Up(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!et(t.start,"explicit-key-ind")&&!et(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Vp(t.value)?t.value.end?Is(t.value.end,t.sep):t.value.end=t.sep:Is(t.start,t.sep),delete t.sep)}var aa=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Vk.Lexer,this.onNewLine=t}*parse(t,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,n))yield*this.next(r);n||(yield*this.end())}*next(t){if(this.source=t,Uk.env.LOG_TOKENS&&console.log("|",Bp.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let n=Bp.tokenType(t);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let n=t??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&Up(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let s=r.items[r.items.length-1];if(s.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(s.sep)s.value=n;else{Object.assign(s,{key:n,sep:[]}),this.onKeyLine=!s.explicitKey;return}break}case"block-seq":{let s=r.items[r.items.length-1];s.value?r.items.push({start:[],value:n}):s.value=n;break}case"flow-collection":{let s=r.items[r.items.length-1];!s||s.value?r.items.push({start:[],key:n,sep:[]}):s.sep?s.value=n:Object.assign(s,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let s=n.items[n.items.length-1];s&&!s.sep&&!s.value&&s.start.length>0&&Kp(s.start)===-1&&(n.indent===0||s.start.every(i=>i.type!=="comment"||i.indent<n.indent))&&(r.type==="document"?r.end=s.start:r.items.push({start:s.start}),n.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Kp(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let n=Ns(this.peek(2)),r=Ut(n),s;t.end?(s=t.end,s.push(this.sourceToken),delete t.end):s=[this.sourceToken];let i={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`
139
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||t&&r===" ");let s=n-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=n),s}*pushUntil(t){let n=this.pos,r=this.buffer[n];for(;!t(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};Yp.Lexer=oa});var la=C(Gp=>{"use strict";var ca=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let n=0,r=this.lineStarts.length;for(;n<r;){let i=n+r>>1;this.lineStarts[i]<t?n=i+1:r=i}if(this.lineStarts[n]===t)return{line:n+1,col:1};if(n===0)return{line:0,col:t};let s=this.lineStarts[n-1];return{line:n,col:t-s+1}}}};Gp.LineCounter=ca});var da=C(eh=>{"use strict";var Xk=er("process"),Hp=Ns(),Zk=aa();function tt(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Qp(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Zp(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Ds(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Wt(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Ps(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function Xp(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!tt(t.start,"explicit-key-ind")&&!tt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Zp(t.value)?t.value.end?Ps(t.value.end,t.sep):t.value.end=t.sep:Ps(t.start,t.sep),delete t.sep)}var ua=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Zk.Lexer,this.onNewLine=t}*parse(t,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,n))yield*this.next(r);n||(yield*this.end())}*next(t){if(this.source=t,Xk.env.LOG_TOKENS&&console.log("|",Hp.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let n=Hp.tokenType(t);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let n=t??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&Xp(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let s=r.items[r.items.length-1];if(s.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(s.sep)s.value=n;else{Object.assign(s,{key:n,sep:[]}),this.onKeyLine=!s.explicitKey;return}break}case"block-seq":{let s=r.items[r.items.length-1];s.value?r.items.push({start:[],value:n}):s.value=n;break}case"flow-collection":{let s=r.items[r.items.length-1];!s||s.value?r.items.push({start:[],key:n,sep:[]}):s.sep?s.value=n:Object.assign(s,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let s=n.items[n.items.length-1];s&&!s.sep&&!s.value&&s.start.length>0&&Qp(s.start)===-1&&(n.indent===0||s.start.every(i=>i.type!=="comment"||i.indent<n.indent))&&(r.type==="document"?r.end=s.start:r.items.push({start:s.start}),n.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Qp(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let n=Ds(this.peek(2)),r=Wt(n),s;t.end?(s=t.end,s.push(this.sourceToken),delete t.end):s=[this.sourceToken];let i={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`
140
140
  `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
141
- `,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,t.indent)){let s=t.items[t.items.length-2]?.value?.end;if(Array.isArray(s)){Is(s,n.start),s.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,s=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&n.sep&&!n.value){let o=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||n.value?(i.push(this.sourceToken),t.items.push({start:i}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):s||n.value?(i.push(this.sourceToken),t.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(et(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(Vp(n.key)&&!et(n.sep,"newline")){let o=Ut(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else i.length>0?n.sep=n.sep.concat(i,this.sourceToken):n.sep.push(this.sourceToken);else if(et(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=Ut(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||s?t.items.push({start:i,key:null,sep:[this.sourceToken]}):et(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);s||n.value?(t.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(o):(Object.assign(n,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!et(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,t.indent)){let s=t.items[t.items.length-2]?.value?.end;if(Array.isArray(s)){Is(s,n.start),s.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=t.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;n.value||et(n.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let n=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?t.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);!n||n.value?t.items.push({start:[],key:s,sep:[]}):n.sep?this.stack.push(s):Object.assign(n,{key:s,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let s=Ns(r),i=Ut(s);Up(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let n=this.source.indexOf(`
141
+ `,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,t.indent)){let s=t.items[t.items.length-2]?.value?.end;if(Array.isArray(s)){Ps(s,n.start),s.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,s=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&n.sep&&!n.value){let o=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||n.value?(i.push(this.sourceToken),t.items.push({start:i}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):s||n.value?(i.push(this.sourceToken),t.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(tt(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(Zp(n.key)&&!tt(n.sep,"newline")){let o=Wt(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else i.length>0?n.sep=n.sep.concat(i,this.sourceToken):n.sep.push(this.sourceToken);else if(tt(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=Wt(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||s?t.items.push({start:i,key:null,sep:[this.sourceToken]}):tt(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);s||n.value?(t.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(o):(Object.assign(n,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!tt(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,t.indent)){let s=t.items[t.items.length-2]?.value?.end;if(Array.isArray(s)){Ps(s,n.start),s.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=t.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;n.value||tt(n.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let n=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?t.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);!n||n.value?t.items.push({start:[],key:s,sep:[]}):n.sep?this.stack.push(s):Object.assign(n,{key:s,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let s=Ds(r),i=Wt(s);Xp(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let n=this.source.indexOf(`
142
142
  `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
143
- `,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Ns(t),r=Ut(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Ns(t),r=Ut(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Wp.Parser=aa});var Qp=C(Vn=>{"use strict";var Jp=Yo(),Wk=Fn(),Un=_n(),Jk=Vi(),Yk=x(),Gk=oa(),Yp=ca();function Gp(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Gk.LineCounter||null,prettyErrors:t}}function Hk(e,t={}){let{lineCounter:n,prettyErrors:r}=Gp(t),s=new Yp.Parser(n?.addNewLine),i=new Jp.Composer(t),o=Array.from(i.compose(s.parse(e)));if(r&&n)for(let a of o)a.errors.forEach(Un.prettifyError(e,n)),a.warnings.forEach(Un.prettifyError(e,n));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Hp(e,t={}){let{lineCounter:n,prettyErrors:r}=Gp(t),s=new Yp.Parser(n?.addNewLine),i=new Jp.Composer(t),o=null;for(let a of i.compose(s.parse(e),!0,e.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Un.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(o.errors.forEach(Un.prettifyError(e,n)),o.warnings.forEach(Un.prettifyError(e,n))),o}function Qk(e,t,n){let r;typeof t=="function"?r=t:n===void 0&&t&&typeof t=="object"&&(n=t);let s=Hp(e,n);if(!s)return null;if(s.warnings.forEach(i=>Jk.warn(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:r},n))}function Xk(e,t,n){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n=="string"&&(n=n.length),typeof n=="number"){let s=Math.round(n);n=s<1?void 0:s>8?{indent:8}:{indent:s}}if(e===void 0){let{keepUndefined:s}=n??t??{};if(!s)return}return Yk.isDocument(e)&&!r?e.toString(n):new Wk.Document(e,r,n).toString(n)}Vn.parse=Qk;Vn.parseAllDocuments=Hk;Vn.parseDocument=Hp;Vn.stringify=Xk});var Zp=C(_=>{"use strict";var Zk=Yo(),eb=Fn(),tb=Co(),la=_n(),nb=kn(),tt=x(),rb=He(),sb=V(),ib=Xe(),ob=Ze(),ab=Cs(),cb=sa(),lb=oa(),ub=ca(),Ds=Qp(),Xp=gn();_.Composer=Zk.Composer;_.Document=eb.Document;_.Schema=tb.Schema;_.YAMLError=la.YAMLError;_.YAMLParseError=la.YAMLParseError;_.YAMLWarning=la.YAMLWarning;_.Alias=nb.Alias;_.isAlias=tt.isAlias;_.isCollection=tt.isCollection;_.isDocument=tt.isDocument;_.isMap=tt.isMap;_.isNode=tt.isNode;_.isPair=tt.isPair;_.isScalar=tt.isScalar;_.isSeq=tt.isSeq;_.Pair=rb.Pair;_.Scalar=sb.Scalar;_.YAMLMap=ib.YAMLMap;_.YAMLSeq=ob.YAMLSeq;_.CST=ab;_.Lexer=cb.Lexer;_.LineCounter=lb.LineCounter;_.Parser=ub.Parser;_.parse=Ds.parse;_.parseAllDocuments=Ds.parseAllDocuments;_.parseDocument=Ds.parseDocument;_.stringify=Ds.stringify;_.visit=Xp.visit;_.visitAsync=Xp.visitAsync});import{existsSync as TE,mkdtempSync as PE,readFileSync as Gh,rmSync as LE,writeFileSync as Wh}from"node:fs";import{tmpdir as FE}from"node:os";import{dirname as Te,join as wt,resolve as _a}from"node:path";import{existsSync as Yn,readFileSync as Mb}from"node:fs";import{join as uh}from"node:path";import{join as Em}from"node:path";import{randomBytes as im,randomUUID as zc}from"node:crypto";import{mkdirSync as om,realpathSync as am,statSync as ur}from"node:fs";import{open as cm,readFile as lm,readdir as um,rename as dm,rm as ri}from"node:fs/promises";import{basename as ii,dirname as Ee,join as ge,resolve as dr}from"node:path";var fm=448,ci=384,li=30,pm=1440*6e4,si="state.json",hm=/^runs\/[a-z][a-z0-9-]{0,62}\/[1-9][0-9]{0,5}\.summary\.json$/,mm=/^runs\/[a-z][a-z0-9-]{0,62}\/[1-9][0-9]{0,5}\.summary\.removals\.json$/,gm=/^templates\/[a-z][a-z0-9-]{0,62}\.[1-9][0-9]{0,5}\.json$/,xc=/^(?:frozen|dataops)\/[a-z][a-z0-9-]{0,62}$/,L=class extends Error{constructor(n,r){super(r);this.code=n;this.name="EnvStateError"}code};function fr(e=process.env){return Ee(Ic("env",e))}function pr(e,t){let n=ui(e,t);if(n!==void 0)return`The journal directory ${dr(t)} is inside the repository ${n} that holds the file: the state, the run summaries and the templates of its runs would be committed with it, and they name the org\u2019s records by their ids. Point SANDFORGE_JOURNAL_DIR at a folder outside the repository \u2014 in CI, $RUNNER_TEMP/sandforge \u2014 and keep it between the jobs that apply and destroy, in a cache keyed by the org.`}function ui(e,t){let n;try{n=cr(Mc(e))}catch{return}return new Oe(n).isInsideRepo(Mc(t))?n:void 0}function Mc(e){let t=[],n=dr(e);for(;;)try{return ge(am(n),...t.reverse())}catch{let r=Ee(n);if(r===n)return dr(e);t.push(ii(n)),n=r}}function ae(e,t){return`runs/${_e(e)}/${mr(t)}.summary.json`}function di(e,t){return`runs/${_e(e)}/${mr(t)}.summary.removals.json`}function kt(e,t){return`templates/${_e(e)}.${mr(t)}.json`}function hr(e,t,n,r=zc()){return`env-${_e(e)}-${_e(t)}-${mr(n)}-${r}`}function _e(e){let t=Gt.safeParse(e);if(!t.success)throw new L("invalid",`Not a name of the file: "${e}"`);return t.data}function mr(e){if(!Number.isInteger(e)||e<1||e>999999)throw new L("invalid",`Not a run's rank: ${e}`);return e}function gr(e){return{version:1,env:_e(e.env),lineage:zc(),serial:0,sandforgeVersion:e.sandforgeVersion,updatedAt:(e.now??new Date).toISOString(),org:{organizationId:xe(e.org.organizationId),kind:e.org.kind,username:e.org.username,...e.org.alias!==void 0?{alias:e.org.alias}:{}},file:{digest:e.fileDigest},resources:{}}}function en(e){return(e?.runs.at(-1)?.n??0)+1}function tn(e,t){let n=e.resources[t.resource],r={...t.run,n:en(n),objects:[]};return wr(e,t.resource,{kind:t.kind,fingerprint:t.fingerprint,dependsOn:[...t.dependsOn],status:"applying",runs:[...n?.runs??[],r]})}function fi(e,t){let n=e.resources[t];if(n===void 0)throw new L("invalid",`The state holds no resource ${t} to take back`);return wr(e,t,{...n,status:"destroying"})}function yr(e,t,n){let r=e.resources[t];if(r===void 0)throw new L("invalid",`The state holds no resource ${t}`);let s=r.runs.map(i=>i.n===n?{...i,takenBack:!0}:i);return wr(e,t,{...r,runs:s})}function bt(e,t){let n=e.resources[t.resource];if(n===void 0)throw new L("invalid",`The state holds no resource ${t.resource}`);let r=[...n.runs],s=r.at(-1);if(t.run!==void 0){if(s===void 0)throw new L("invalid",`The resource ${t.resource} has no run to end`);r[r.length-1]={...s,...t.run}}return wr(e,t.resource,{...n,status:t.status,runs:r})}function wr(e,t,n){return{...e,resources:{...e.resources,[_e(t)]:n}}}function pi(e){if(e.org.kind==="scratch")return new Date(Date.parse(e.updatedAt)+li*pm).toISOString()}function vr(e){if(e.fileFolder!==null){let r=pr(e.fileFolder,e.journalDir);if(r!==void 0)return{refusal:r}}let t=new oi(e),n=Zt(t.root,e.uid??Bc);return n!==void 0?{refusal:n}:{store:t}}var oi=class{root;fileFolder;uid;renameFile;now;constructor(t){this.root=ge(dr(t.journalDir),"env"),this.fileFolder=t.fileFolder,this.uid=t.uid??Bc,this.renameFile=t.rename??((n,r)=>dm(n,r)),this.now=t.now??Date.now}folderOf(t,n){let r=_c(t);if(r===void 0)throw new L("invalid",`Not an Organization Id: "${t}"`);return ge(this.root,r,_e(n))}fileOf(t,n,r){if(!hm.test(r)&&!gm.test(r)&&!mm.test(r))throw new L("invalid",`Not a file of a state's folder: "${r}"`);return ge(this.folderOf(t,n),...r.split("/"))}async read(t,n){let r=this.folderOf(t,n),s=ge(r,si),i;try{i=await lm(s,"utf8")}catch(o){if(ai(o)==="ENOENT")return;throw o}return ym(i,s,r)}stateFileOf(t,n){return ge(this.folderOf(t,n),si)}async setAside(t,n){if(this.fileFolder===null)throw new L("invalid","The states were opened to be listed, not written");let r=this.stateFileOf(t,n),s=new Date(this.now()).toISOString().replace(/\.\d{3}Z$/,"").replace(/[-:]/g,"").replace("T","-"),i=`${r}.damaged-${s}`;for(let o=2;ur(i,{throwIfNoEntry:!1})!==void 0;o++)i=`${r}.damaged-${s}-${o}`;return await this.renameFile(r,i),i}async write(t,n){if(this.fileFolder===null)throw new L("invalid","The states were opened to be listed, not written");if(t.lineage!==n.lineage)throw new L("invalid","A state is written over its own lineage only");let r=this.folderOf(t.org.organizationId,t.env),s=await this.read(t.org.organizationId,t.env),i=s?.serial??0;if(i!==n.serial||s!==void 0&&s.lineage!==n.lineage){let a=s===void 0?"it is gone":s.lineage!==n.lineage?"it is another state, made since":`serial ${i}, not ${n.serial}`;throw new L("moved",`The state of ${t.env} on ${t.org.organizationId} changed since it was read (${a}): another apply or destroy ran, or a cache put back another state. Nothing was written: plan again.`)}let o=Ht.safeParse({...t,org:{...t.org,organizationId:xe(t.org.organizationId)},serial:n.serial+1,updatedAt:new Date(this.now()).toISOString()});if(!o.success)throw new L("invalid",`Not a state: ${o.error.message}`);for(let a of[Ee(r),r]){let c=Zt(a,this.uid);if(c!==void 0)throw new L("folder",c)}return await this.writeWhole(ge(r,si),`${JSON.stringify(o.data,null,2)}
144
- `),o.data}async update(t,n){return this.write(n(t),t)}async writeFile(t,n,r,s){if(this.fileFolder===null)throw new L("invalid","The states were opened to be listed, not written");let i=this.fileOf(t,n,r),o=this.folderOf(t,n);for(let a of[Ee(o),o,Ee(i)]){let c=Zt(a,this.uid);if(c!==void 0)throw new L("folder",c)}return await this.writeWhole(i,s),i}async prepareFile(t,n,r){if(this.fileFolder===null)throw new L("invalid","The states were opened to be listed, not written");let s=this.fileOf(t,n,r),i=this.folderOf(t,n);for(let o of[Ee(i),i,Ee(s)]){let a=Zt(o,this.uid);if(a!==void 0)throw new L("folder",a)}return s}async prepareFolder(t,n,r){if(this.fileFolder===null)throw new L("invalid","The states were opened to be listed, not written");if(!xc.test(r))throw new L("invalid",`Not a folder of a state's folder: "${r}"`);let s=this.folderOf(t,n),i=ge(s,...r.split("/"));for(let o of[Ee(s),s,Ee(i),i]){let a=Zt(o,this.uid);if(a!==void 0)throw new L("folder",a)}return i}sasOf(t,n,r){if(!xc.test(r))throw new L("invalid",`Not a folder of a state's folder: "${r}"`);return ge(this.folderOf(t,n),...r.split("/"))}async remove(t,n){let r=this.folderOf(t,n);return ur(r,{throwIfNoEntry:!1})===void 0?!1:(await ri(r,{recursive:!0,force:!0}),!0)}async list(){let t=[];for(let n of await qc(this.root))if(_c(n)===n)for(let r of await qc(ge(this.root,n))){if(!Gt.safeParse(r).success)continue;let s=ge(this.root,n,r);try{let i=await this.read(n,r);if(i===void 0)continue;let o=pi(i);t.push({organizationId:n,env:r,folder:s,state:i,...o!==void 0?{expiresAt:o}:{}})}catch(i){t.push({organizationId:n,env:r,folder:s,damaged:Kc(i)})}}return t}async sweep(){let t=this.now(),n=[];for(let{state:r,expiresAt:s,folder:i,organizationId:o,env:a}of await this.list())r===void 0||s===void 0||Date.parse(s)>t||(await ri(i,{recursive:!0,force:!0}),n.push({organizationId:o,env:a,...r.org.alias!==void 0?{alias:r.org.alias}:{},updatedAt:r.updatedAt,expiresAt:s}));return n}async writeWhole(t,n){let r=`${t}.${process.pid}-${im(4).toString("hex")}.tmp`,s=await cm(r,"wx",ci);try{try{await s.writeFile(n,"utf8"),await s.sync()}finally{await s.close()}await this.renameFile(r,t)}catch(i){throw await ri(r,{force:!0}),i}}};function ym(e,t,n){let r;try{r=JSON.parse(e)}catch{r=void 0}let s=Ht.safeParse(r);if(!s.success)throw new L("damaged",`The state ${t} does not read as a state of this SandForge, and is not used: a plan made from part of it would create again what the rest names. Run ${ue("env")} state recover: it sets this file aside and rebuilds the state from the run files beside it.`);let i=s.data;if(xe(i.org.organizationId)!==ii(Ee(n))||i.env!==ii(n))throw new L("otherOrg",`The state ${t} is of ${i.env} on ${i.org.organizationId}, not of the org and environment its folder names: it was copied or moved, and is not used. Put it back where it came from, or delete it.`);return i}function Bc(){return process.getuid?.()}function Zt(e,t){try{let n=ur(e,{throwIfNoEntry:!1});if(n!==void 0&&!n.isDirectory())return`${e} is not a folder.`;om(e,{recursive:!0,mode:fm});let r=t();return r!==void 0&&ur(e).uid!==r?`${e} belongs to another user, who can read the states kept there and replace them: point SANDFORGE_JOURNAL_DIR at a folder of your own.`:void 0}catch(n){return`${e} could not be made: ${Kc(n)}`}}function _c(e){try{return xe(e)}catch{return}}async function qc(e){try{return(await um(e,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name).sort()}catch(t){if(ai(t)==="ENOENT"||ai(t)==="ENOTDIR")return[];throw t}}function ai(e){return e?.code}function Kc(e){return e instanceof Error?e.message:String(e)}import{createHash as wm}from"node:crypto";function nn(e){return e.length===0?"the file":e.map((t,n)=>typeof t=="number"?`[${t}]`:/^[A-Za-z_][A-Za-z0-9_-]*$/.test(t)?`${n===0?"":"."}${t}`:`[${JSON.stringify(t)}]`).join("")}function T(e,t){let n=e[0]==="resources"&&typeof e[1]=="string"?e[1]:void 0;return{path:e,...n!==void 0?{resource:n}:{},message:t}}function Et(e){return JSON.stringify(hi(e))}function hi(e){if(Array.isArray(e))return e.map(hi);if(e===null||typeof e!="object")return e;let t=e;return Object.fromEntries(Object.keys(t).filter(n=>t[n]!==void 0).sort().map(n=>[n,hi(t[n])]))}function mi(e){return wm("sha256").update(e,"utf8").digest("hex")}var vm=200;function I(e,t){if(t===""||t.startsWith("-"))throw new Error(`${e} cannot be "${t}": a value that starts with "-" reads as a flag.`);return t}function Ce(e){return e.sweep===!0?["--sweep"]:[]}var qe=p.string().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),A=p.number().int().nonnegative(),St=p.object({objectApiName:p.string().min(1),planned:A,deleted:A,alreadyGone:A,keptChanged:A,keptDependents:A,refused:A,notVisible:A.optional(),notReached:A.optional(),heldBy:p.array(p.string()),reasons:p.array(p.string())}),km=p.object({objectApiName:p.string().min(1),planned:A,toDelete:A,alreadyGone:A,changedSince:A,keptChanged:A,changedBy:p.record(qe,A),undeletable:A,notVisible:A,unread:A,reasons:p.array(p.string())}),Rt=p.object({planned:A,objects:p.array(km),undeletable:p.array(p.object({objectApiName:p.string().min(1),records:A})).optional(),userNames:p.record(qe,p.string())});function ze(e,t,n){if(t===void 0||n?.length!==t.length)return[];let r=t.flatMap((s,i)=>{let o=n[i];return o!==void 0&&o!==""&&s!==""&&e.includes(s)?[o]:[]});return[...new Set(r)]}var bm=/^Nothing(?: was)? (?:written|deleted)\.?$/i;function Uc(e){return e.split(`
145
- `).map(t=>t.trim()).filter(t=>t!==""&&!bm.test(t)).at(-1)}var re=class extends Error{constructor(n,r,s,i){super(`${Pe(n)} did not answer ${r} (${s}): `+(i===""?"it printed nothing on stdout":`it printed ${JSON.stringify(i)}`));this.script=n;this.expected=r;this.reason=s;this.excerpt=i;this.name="StepAnswerError"}script;expected;reason;excerpt};function z(e,t,n,r){let s=r.trim().slice(0,vm),i;try{i=JSON.parse(r)}catch{throw new re(e,t,"not JSON",s)}let o=n.safeParse(i);if(!o.success){let a=o.error.issues[0],c=a?.path.join(".")||"the answer";throw new re(e,t,`${c}: ${a?.message??"refused"}`,s)}return o.data}var ce="sandforge-checkpoint";function ye(e){return Em(e,"checkpoints")}function Sm(e){return e==="scratch"?li:0}function rn(e,t){if(t==="before")return e.checkpoint?.before===!0?`${e.name} before`:void 0;let n=e.checkpoint?.after;return typeof n=="string"?n:void 0}function sn(e){return["--org",I("--org",e.org),"--store",I("--store",e.store)]}function kr(e){let{ignoreFields:t,maxTotal:n,excludeObjects:r}=e.checkpoint??{};return{...t!==void 0?{ignoreFields:t}:{},...n!==void 0?{maxTotal:n}:{},...r!==void 0?{excludeObjects:r}:{}}}function Vc(e){return[...(e.ignoreFields??[]).flatMap(t=>["--ignore-field",I("--ignore-field",t)]),...e.maxTotal!==void 0?["--max-total",String(e.maxTotal)]:[],...(e.excludeObjects??[]).flatMap(t=>["--exclude-object",I("--exclude-object",t)])]}function Wc(e){return["take",...sn(e),...Vc(e),"--estimate","--json"]}function Rm(e){return["take",...sn(e),"--name",I("--name",e.name),"--keep-days",String(e.keepDays),...Vc(e),"--json"]}function yi(e){if(e.code!=="TOO_MANY_RECORDS")return e;let t=e.message.indexOf(": pick fewer objects"),n=t===-1?e.message.replace(/\s*No record was read\.$/,""):e.message.slice(0,t);return{...e,message:`${n}: leave objects out with checkpoint.excludeObjects, or raise checkpoint.maxTotal in the file, ${Ya.toLocaleString("en-US")} at most. No record was read.`}}function Jc(e){return["preview",...sn(e),"--checkpoint",ot.parse(e.checkpoint),"--json"]}function wi(e){return["rewind",...sn(e),"--checkpoint",ot.parse(e.checkpoint),e.dryRun?"--dry-run":"--yes",...e.acceptAutomation?["--accept-automation"]:[],...e.acceptEmails===!0?["--accept-emails"]:[],...e.acceptNoUndo?["--accept-no-undo"]:[],...e.acceptUnseen===!0?["--accept-unseen"]:[],"--json"]}function $m(e){return["delete",...sn(e),"--checkpoint",ot.parse(e.checkpoint),"--yes","--json"]}var vi=p.object({code:p.string().min(1),message:p.string().min(1)}),on=p.object({refusal:vi}),Am=p.union([p.object({mode:p.string(),estimate:p.object({records:A,apiRequests:A,apiRequestsLeft:p.number(),seconds:p.number().nonnegative(),bytes:A}),refusal:vi.optional()}),on]),Om=p.union([p.object({checkpoint:p.object({checkpointId:ot,name:p.string().min(1),takenAt:p.string().min(1)})}),on]),Cm=p.union([p.object({checkpoint:p.object({id:ot,name:p.string().min(1),takenAt:p.string().min(1)}),toDelete:A,toGiveBack:A,toBringBack:A,toRecreate:A,differs:p.boolean(),diff:p.object({objects:p.array(p.object({objectApiName:p.string().min(1),lastChangedBy:p.record(p.string(),A),touched:A})),userNames:p.record(p.string(),p.string())}),refusal:vi.optional()}),on]),gi=p.object({planned:A,done:A,left:A}),jm=p.union([p.object({checkpoint:p.object({id:ot,name:p.string().min(1)}),rewindId:p.string().min(1),status:p.enum(["success","partial","unstable","failure","cancelled"]),deleted:gi,givenBack:gi,broughtBack:gi,undo:p.object({until:p.string().min(1)}).optional(),residual:p.array(p.object({object:p.string(),reason:p.string(),count:A}))}),on]),Nm=p.union([p.object({deleted:p.array(p.string()),kept:p.array(p.string())}),on]);function Im(e){return z(ce,"the estimate of a take",Am,e)}function Dm(e){return z(ce,"a take",Om,e)}function Yc(e){return z(ce,"a preview",Cm,e)}function Tm(e){return z(ce,"a rewind",jm,e)}function Pm(e){return z(ce,"a deletion",Nm,e)}function Lm(e){return e.stderr.trim().split(`
146
- `).map(t=>t.trim()).filter(Boolean).at(-1)??"it said nothing"}function $t(e,t){try{return{answer:t(e.stdout),raw:JSON.parse(e.stdout)}}catch(n){if(!(n instanceof re))throw n;return{unread:`exit ${e.code}: ${Lm(e)}`}}}function br(e,t,n){let r=[],s=rn(e,"before");s!==void 0&&n&&Fm(t)&&r.push({step:"before",name:s});let i=rn(e,"after");return i!==void 0&&(n||t?.checkpoints?.after===void 0)&&r.push({step:"after",name:i}),r}function Gc(e){return Object.values(e?.resources??{}).some(t=>t.status!=="destroyed")}function Fm(e){return e?.checkpoints?.before===void 0&&!Gc(e)}function Hc(e,t){return e.checkpoint?.before!==!0||t?.checkpoints?.before!==void 0?[]:Gc(t)?["checkpoint.before is taken before the first apply of an environment, and the org holds what an earlier apply wrote without one: it is not taken now, since a rewind to it would keep those records. Destroy the environment, then apply, to take it"]:[]}function Qc(e){let t=$t(e,Im);if("unread"in t)return t;let n=t.answer;if(!("estimate"in n))return{refusal:yi(n.refusal)};let{records:r,apiRequests:s,seconds:i,bytes:o}=n.estimate;return{estimate:{records:r,apiRequests:s,seconds:i,bytes:o},...n.refusal!==void 0?{refusal:yi(n.refusal)}:{}}}function Xc(e,t,n=0){return e.map(({step:r,name:s})=>t===void 0?{step:r,name:s,unread:"not read: --quick"}:"unread"in t?{step:r,name:s,unread:t.unread}:{step:r,name:s,..."estimate"in t?{estimate:r==="after"?{...t.estimate,records:t.estimate.records+n}:t.estimate}:{},...t.refusal!==void 0?{refusal:t.refusal}:{}})}var Er={before:"before the first write",after:"once applied"};function Zc(e){let t=e.filter(n=>n.refusal!==void 0);if(t.length!==0)return t.map(n=>`The checkpoint the file asks ${Er[n.step]}, '${n.name}', would be refused: ${n.refusal?.message??""}`).join(" ")+" Take checkpoint.before or checkpoint.after out of the file, or fix what refuses it."}function el(e){let t=0,n=[];for(let r of e)r.estimate!==void 0?t+=r.estimate.apiRequests:n.push(`the checkpoint ${Er[r.step]}, not estimated`);return{estimate:t,notCounted:n}}function tl(e,t){let n=$t(t,Yc);if("unread"in n)return{checkpoint:e,differs:!1,unread:n.unread};let r=n.answer;return"differs"in r?{checkpoint:e,differs:r.differs,toDelete:r.toDelete,toGiveBack:r.toGiveBack,toBringBack:r.toBringBack}:{checkpoint:e,differs:!1,unread:r.refusal.message}}var Se=e=>e.toLocaleString("en-US");function nl(e){let t=[];for(let r of e.checkpoints??[]){let s=`checkpoint ${Er[r.step]}: '${r.name}'`,{estimate:i}=r;i!==void 0?t.push(`${s}, about ${Se(i.records)} records, ${Se(i.apiRequests)} API requests, ${Se(Math.ceil(i.seconds))} s, ${at(i.bytes/(1024*1024))} MB on this machine`):t.push(`${s}, not estimated (${r.unread??"no estimate"})`),r.refusal!==void 0&&t.push(` refused: ${r.refusal.message}`)}let n=e.drift;if(n!==void 0){let r=`the whole org against the checkpoint after the last apply (${n.checkpoint})`;t.push(n.unread!==void 0?`${r}: not compared, ${n.unread}`:n.differs?`${r}: differs, ${Se(n.toDelete??0)} to delete \xB7 ${Se(n.toGiveBack??0)} to give back \xB7 ${Se(n.toBringBack??0)} to bring back`:`${r}: nothing differs among the objects and fields it compares`)}return t}async function ki(e,t,n){e.say(`checkpoint ${Er[t.step]}: taking '${t.name}'`);let r=await e.runner(ce,Rm({org:t.org.alias,store:ye(e.journalDir),name:t.name,keepDays:Sm(t.org.kind),...t.ignoreFields!==void 0?{ignoreFields:t.ignoreFields}:{},...t.maxTotal!==void 0?{maxTotal:t.maxTotal}:{},...t.excludeObjects!==void 0?{excludeObjects:t.excludeObjects}:{}}),n),s=$t(r,Dm),i="answer"in s?s.answer:void 0,o="raw"in s?s.raw:void 0;if(r.code===0&&i!==void 0&&"checkpoint"in i)return{result:{step:t.step,checkpoint:i.checkpoint.checkpointId,exitCode:r.code,answer:o},checkpoint:i.checkpoint.checkpointId};let a=i!==void 0&&"refusal"in i?`${i.refusal.code}: ${yi(i.refusal).message}`:"unread"in s?s.unread:`exit ${r.code}`;return{result:{step:t.step,exitCode:r.code===0?1:r.code,refusal:a.slice(0,4e3),...o!==void 0?{answer:o}:{}}}}async function At(e,t,n){e.say(`checkpoint ${t.checkpoint}: deleted from this machine, ${t.why}`);let r=await e.runner(ce,$m({org:t.org.alias,store:ye(e.journalDir),checkpoint:t.checkpoint}),n),s=$t(r,Pm),i="answer"in s?s.answer:void 0,o=i!==void 0&&"deleted"in i&&i.deleted.includes(t.checkpoint),a=i!==void 0&&"refusal"in i&&i.refusal.code==="NOT_FOUND";if(o||a)return{step:"delete",checkpoint:t.checkpoint,exitCode:0};let c=i!==void 0&&"refusal"in i?`${i.refusal.code}: ${i.refusal.message}`:i!==void 0&&"kept"in i?"kept: a take, a rewind or an undo of the org is running":"unread"in s?s.unread:`exit ${r.code}`;return e.say(` not deleted: ${c}`),{step:"delete",checkpoint:t.checkpoint,exitCode:r.code===0?1:r.code,refusal:c.slice(0,4e3)}}function Sr(e){let t=[];return e?.checkpoints?.after!==void 0&&t.push({step:"after",checkpoint:e.checkpoints.after}),e?.checkpoints?.before!==void 0&&t.push({step:"before",checkpoint:e.checkpoints.before}),t}function Be(e,t,n){let r={...e.checkpoints};n!==void 0?r[t]=n:delete r[t];let s={...e,checkpoints:r};return Object.keys(r).length===0&&delete s.checkpoints,s}function rl(e){let t=$t(e,Yc);if("unread"in t)return{refusal:t.unread};let n=t.answer;if(!("differs"in n))return{refusal:n.refusal.message};let r={};for(let s of n.diff.objects)for(let[i,o]of Object.entries(s.lastChangedBy)){let a=n.diff.userNames[i]??i;r[a]=(r[a]??0)+o}return{checkpoint:n.checkpoint,toDelete:n.toDelete,toGiveBack:n.toGiveBack,toBringBack:n.toBringBack,lastChangedBy:r,differs:n.differs,...n.refusal!==void 0?{refusal:n.refusal}:{}}}function Rr(e){return Object.entries(e).sort((t,n)=>n[1]-t[1]).map(([t,n])=>`${t} ${Se(n)}`).join(", ")}function sl(e,t,n){let r=`'${n.checkpoint.name}' (${n.checkpoint.id}), taken ${n.checkpoint.takenAt}`,s=[e==="reset"?`reset ${t} to the checkpoint taken after the last apply, ${r}:`:`destroy by rewinding ${t} to the checkpoint taken before the first apply, ${r}:`,` ${Se(n.toDelete)} to delete \xB7 ${Se(n.toGiveBack)} to give back \xB7 ${Se(n.toBringBack)} to bring back`+(n.differs?"":" \u2014 nothing differs: nothing to rewind")],i=Rr(n.lastChangedBy);return i!==""&&s.push(` last changed by: ${i}`),n.refusal!==void 0&&s.push(` refused: ${n.refusal.message}`),s}function il(e){let t=$t(e,Tm),n="answer"in t?t.answer:void 0,r="raw"in t?t.raw:void 0;if(n!==void 0&&"status"in n)return{exitCode:e.code,status:n.status,answer:r,done:{deleted:n.deleted.done,givenBack:n.givenBack.done,broughtBack:n.broughtBack.done,differing:n.residual.reduce((i,o)=>i+o.count,0)},...n.undo!==void 0?{undoUntil:n.undo.until}:{}};let s=n!==void 0&&"refusal"in n?n.refusal:{code:"UNREAD",message:"unread"in t?t.unread:`exit ${e.code}`};return{exitCode:e.code===0?1:e.code,status:e.code>=128?"cancelled":"failure",...r!==void 0?{answer:r}:{},refusal:s}}function ol(e,t){return e.deleted?{offered:!1,why:"the environment\u2019s checkpoints are deleted with it, the journal of this rewind among them: a destroy is undone by applying again"}:t.undoUntil===void 0?{offered:!1,why:t.status==="failure"||t.status==="cancelled"?"the checkpoint script offers no undo of a rewind that wrote nothing it can take back":"the checkpoint script offers none: the rewind wrote nothing"}:{offered:!0,until:new Date(Date.parse(t.undoUntil)).toISOString(),line:`${ue("checkpoint")} undo --org ${e.alias} --checkpoint ${e.checkpoint} --store ${ye(e.journalDir)}`}}function al(e){return e.offered?`undo it until ${e.until}, sooner if the recycle bin fills: ${e.line}`:`no undo: ${e.why}`}var $r="STATE_MOVED",cl="No flag lifts this: an environment is never applied to a production org.";function de(e,t){return e.length>=15&&t.length>=15&&e.slice(0,15)===t.slice(0,15)}function ll(e,t,n){if("unread"in t)return t.error!==void 0&&Za(t.error)!==void 0?{refusal:{code:"UNTYPED",message:rc(e,t.error,{tool:"sandforge env",action:"write",readOnly:"plan"}),exit:1}}:{refusal:{code:"PRODUCTION",message:`${e} did not say what org it is (${t.unread}), and an environment is applied to no org it cannot tell from a production one. Nothing was read or written. ${cl}`,exit:1}};if(sr(t)){let s=t.edition?`IsSandbox false, edition ${t.edition}`:"IsSandbox false, and no edition";return{refusal:{code:"PRODUCTION",message:`${e} is a production org (its Organization record says ${s}): an environment is applied to scratch orgs, Developer Edition orgs and the sandboxes its file lists. Nothing was read or written. ${cl}`,exit:1}}}let r=t.sandbox?n.scratch===!0?"scratch":"sandbox":"developer";return{target:{alias:e,organizationId:t.id,kind:r,username:n.username}}}var ul={scratch:"a scratch org",developer:"a Developer Edition org",sandbox:"a sandbox"};function dl(e,t){let n=t.organizationId;if(e.protect.some(r=>de(r,n)))return{code:"PROTECTED",message:`${t.alias} (${xe(n)}) is listed under targets.protect: the file refuses it whatever else it says. Nothing was read or written.`,exit:1};if(!e.kinds.includes(t.kind)){let r=t.kind==="sandbox"?" If it is a scratch org, the sf CLI did not say so: its display names no Dev Hub for it, as when the org was logged in with an auth URL alone. Log its Dev Hub in on this machine, or list the org as a sandbox.":"";return{code:"KIND",message:`${t.alias} is ${ul[t.kind]}, and the file's targets.kinds allows ${e.kinds.join(", ")}: add ${t.kind} to targets.kinds to apply it there. Nothing was read or written.${r}`,exit:1}}if(t.kind==="sandbox"&&!e.sandboxes.some(r=>de(r,n)))return{code:"NOT_LISTED",message:`${t.alias} is a sandbox, and its Organization Id ${xe(n)} is not listed under targets.sandboxes: nothing Salesforce says tells a sandbox that holds a client's records from a developer's, so each one the file writes to is listed, reviewed with the file. A refresh changes the Id: a sandbox listed before its refresh is listed again. Nothing was read or written. If it is a scratch org, the sf CLI did not say so: its display names no Dev Hub for it, as when the org was logged in with an auth URL alone.`,exit:1}}function Ke(e){return{code:e.code==="otherOrg"?"OTHER_ORG":"STATE_DAMAGED",message:`${e.message} Nothing was read or written in the org.`,exit:1}}function fl(e,t,n){if(!(e.env===t&&de(e.org.organizationId,n.organizationId)))return{code:"OTHER_ORG",message:`The state read for ${t} on ${n.alias} is of ${e.env} on ${e.org.organizationId}: a state of another org is never applied. Nothing was read or written.`,exit:1}}function pl(e,t,n,r=!1){let s=`this machine keeps no state of ${t} on ${e.alias}: records an earlier apply left there, from another machine or a cache that was not restored, cannot be told from the org\u2019s own, and would be created twice`+(r?`; it keeps runs of ${t} on ${e.alias}, and ${ue("env")} state recover rebuilds the state from them`:"");return e.kind==="scratch"||n?{warning:s}:{refusal:{code:"NO_STATE",message:`${s.charAt(0).toUpperCase()}${s.slice(1)}. On ${ul[e.kind]} that lives on, apply asks --accept-no-state to go ahead: restore the journal directory of the apply before it, or give the flag. Nothing was written.`,exit:1}}}function Ar(e,t){return t?{code:"STORE_IN_REPOSITORY",message:e,exit:2}:{code:"STORE",message:e,exit:1}}function Ue(e){return{code:"LOCKED",message:Rc(e),exit:1}}function an(e){return{code:"CHECKPOINT_ACT",message:`${e.charAt(0).toUpperCase()}${e.slice(1)}`,exit:1}}import{readFileSync as xm}from"node:fs";import{join as Mm}from"node:path";var U="sandforge-clone",gl=1e4,hl=1e6,_m=["inputMode","recordId","soqlQuery","templateId","aiPrompt","dryRun"];function qm(e){let[t]=e;return`SELECT Id FROM ${t?.object??""}${t?.where!==void 0?` WHERE ${t.where}`:""}`}function zm(e,t,n){let r=["resources",e,"template"],s=u=>({refusals:[T(r,u)]}),i;try{i=xm(Mm(n,t.file),"utf8")}catch(u){return s(`${t.file} cannot be read: ${u instanceof Error?u.message:String(u)}`)}if(i.length>hl)return s(`${t.file} is larger than ${hl} bytes`);let o;try{o=JSON.parse(i.replace(/^\uFEFF/,""))}catch{return s(`${t.file} is not JSON`)}let a=Array.isArray(o)?o:[o],c=a.find(u=>u!==null&&typeof u=="object"&&u.id===t.id);if(c===void 0){let u=a.map(d=>d!==null&&typeof d=="object"?d.id:"").filter(d=>typeof d=="string"&&d!=="");return s(`${t.file} holds no template "${t.id}"`+(u.length>0?`: it holds ${u.join(", ")}`:": it holds none"))}let l=Gs.safeParse(c);return l.success?{entry:l.data}:{refusals:l.error.issues.map(u=>T(r,`the template "${t.id}" of ${t.file} is refused by Forge's template schema at ${u.path.map(String).join(".")||"its top"}: ${u.message}`))}}function yl(e,t,n,r,s){let i=["resources",t],o=[];if(n.depth==="all")return{run:{source:n.source,wholeOrg:{anonymize:n.anonymize!==void 0,keepContactPoints:n.keepContactPoints===!0,...n.fit!==void 0?{fit:n.fit==="share"?{}:{withinMB:n.fit.withinMB}}:{}},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{},acceptAutomation:n.accept?.automation===!0,acceptRealData:n.accept?.realData===!0},warnings:o};let a;if(n.template!==void 0){let y=zm(t,n.template,r);if("refusals"in y)return y;a=y.entry}let c={...a?.config};for(let y of _m)delete c[y];if(n.tables!==void 0&&c.expandOrphanParents===!0)return{refusals:[T([...i,"template"],"the template brings orphan parents (expandOrphanParents), which go with a clone of one record: a clone of tables reads the parents its tables point at, named with them")]};a?.files!==void 0&&o.push(T([...i,"template"],"the template copies the files of the cloned records: an environment copies none, and the clone writes the records alone"));let l=n.depth??c.depth,u=(l??"custom")==="custom"?n.customDepth??c.customDepth:void 0;delete c.customDepth;let d=s.toISOString(),f={id:`env-${e}-${t}`,name:`${e}/${t}`,description:`The ${t} resource of the ${e} environment`,config:{anonymizePII:!1,skipEmpty:!0,batchSize:"auto",...c,...n.tables!==void 0?{inputMode:"soql",soqlQuery:qm(n.tables)}:{inputMode:"record",...n.record?.id!==void 0?{recordId:n.record.id}:{}},depth:l??"custom",...u!==void 0?{customDepth:u}:{},...n.maxNodes!==void 0?{maxNodes:n.maxNodes}:{},...n.keepContactPoints!==void 0?{keepContactPoints:n.keepContactPoints}:{},...n.anonymize!==void 0?{anonymizePII:!0}:{}},...n.anonymize!==void 0?{anonymization:structuredClone(n.anonymize)}:a?.anonymization!==void 0?{anonymization:structuredClone(a.anonymization)}:{},objectCount:0,recordCount:0,createdAt:d,lastUsedAt:d},g=Gs.safeParse(f);return g.success?{run:{source:n.source,template:g.data,...n.record!==void 0?{record:{...n.record}}:{},...n.tables!==void 0?{tables:n.tables.map(y=>({...y}))}:{},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{},acceptAutomation:n.accept?.automation===!0,acceptRealData:n.accept?.realData===!0},warnings:o}:{refusals:g.error.issues.map(y=>T(i,`the template it converts into is refused by Forge's template schema at ${y.path.map(String).join(".")||"its top"}: ${y.message}`))}}function wl(e){return e.tables!==void 0?e.tables.map(t=>({object:t.object})):e.record?.object!==void 0?[{object:e.record.object}]:[]}function vl(e){if(e.wholeOrg)return e.wholeOrg.anonymize;let t=e.template?.anonymization?.rules??{};return e.template?.config.anonymizePII===!0&&Object.values(t).some(n=>n!==void 0)}function Bm(e){return e.edition?`its Organization record says IsSandbox false, edition ${e.edition}`:"its Organization record says IsSandbox false, and no edition"}function Km(e,t,n){if(e.acceptRealData||vl(e))return;let r=e.template?.config.anonymizePII===!0?" Its anonymize sets a method for no category of personal field, so it does not count.":"";return`its source, ${t}, is a production org (${Bm(n)}): what it clones is real people\u2019s data, written as read into an org built for tests.${r} Give the resource anonymize \u2014 Forge\u2019s anonymization, a method for each category of personal field \u2014 or, reviewed in the file, accept: { realData: true }. Emails and phone numbers are neutralized either way, unless keepContactPoints: true`}function kl(e,t){let n=t.read;if(n===void 0||"refusal"in n||n.production!==!0)return[];let r=Object.entries(e.template?.anonymization?.rules??{}).filter(([,o])=>o!==void 0).map(([o,a])=>`${o} ${String(a)}`),s=vl(e)?e.wholeOrg?"anonymized, every personal field by its category\u2019s default method":`anonymized as its anonymize says (${r.join(", ")})`:"written as read, as the file accepts (accept: { realData: true })",i=e.wholeOrg?e.wholeOrg.keepContactPoints:e.template?.config.keepContactPoints===!0;return[`real data: its source, the ${t.role} org (${t.alias}), is a production org; what it clones is ${s}`,i?"contact points: written as read (keepContactPoints: true)":"contact points: neutralized before writing (emails under .invalid, phone numbers in a fictional range), as the clone does unless keepContactPoints"]}async function bl(e,t,n,r){let s=`the ${n} org (${r})`,i;try{i=await rr(e)}catch(d){return{refusal:`${s} could not be read: ${ml(d)}`}}let o=i.id,a=sr(i);if(a){let d=Km(t,s,i);if(d!==void 0)return{refusal:d}}let c={organizationId:o,...a?{production:!0}:{}},l=t.record;if(l?.object===void 0||l.where===void 0)return c;let u=`${l.object} WHERE ${l.where}`;try{let d=(await e.query(`SELECT Id FROM ${u} LIMIT 2`)).records;return d.length===1&&typeof d[0]?.Id=="string"?{...c,recordId:d[0].Id}:d.length===0?{refusal:`its record query finds no ${l.object} in ${s} (WHERE ${l.where}): a record named by a query is one its source answers with exactly one row`}:{refusal:`its record query finds ${(await e.query(`SELECT COUNT() FROM ${u}`)).totalSize} ${l.object} records in ${s} (WHERE ${l.where}), not one: narrow the where to one row, or name the record by its id`}}catch(d){return{refusal:`its record query could not be read in ${s}: ${ml(d)}`}}}function El(e,t){let n=t!==void 0&&"organizationId"in t?t:void 0;return{kind:"forge",kindVersion:1,source:n?.organizationId.slice(0,15)??null,record:e.record===void 0?null:(e.record.id??n?.recordId)?.slice(0,15)??{unread:e.record},tables:e.tables??null,config:e.template?.config??null,anonymization:e.template?.anonymization??null,...e.wholeOrg?{wholeOrg:e.wholeOrg}:{}}}function Sl(e){if(e.wholeOrg)return Um(e,e.wholeOrg);if(e.recordId===void 0&&(e.tables??[]).length===0)throw new Error("A forge resource clones a record or tables: its line names neither.");return["--source",I("--source",e.source),"--target",I("--target",e.target),...e.recordId!==void 0?["--record",I("--record",e.recordId)]:(e.tables??[]).flatMap(t=>["--object",I("--object",t.object),...t.where!==void 0?["--where",I("--where",t.where)]:[]]),"--template",I("--template",e.templateFile),"--max-total",String(e.maxTotal),"--skip-preflight",...e.acceptAutomation?["--accept-automation"]:[]]}function Um(e,t){return["--source",I("--source",e.source),"--target",I("--target",e.target),"--depth","all","--config",I("--config",e.templateFile),"--max-total",String(e.maxTotal),"--skip-preflight",t.anonymize?"--anonymize":"--no-anonymize",...t.keepContactPoints?["--keep-contact-points"]:[],...t.fit!==void 0?["--fit","share",...t.fit.withinMB!==void 0?["--fit-within",String(t.fit.withinMB)]:[]]:[],...e.acceptAutomation?["--accept-automation"]:[]]}function Rl(e){return[...Sl(e),"--dry-run","--json"]}function $l(e){return[...Sl(e),...e.wholeOrg?["--yes"]:[],"--summary",I("--summary",e.summary),"--json"]}function Al(e){return["--remove",I("--remove",e.summary),"--target",I("--target",e.target),...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[]]}function Ol(e){return[...Al(e),...Ce(e),"--json"]}function Cl(e){return[...Al(e),"--preview",...Ce(e),"--json"]}function jl(e){return["--verify",I("--verify",e.summary),"--target",I("--target",e.target),"--source",I("--source",e.source),"--json"]}var Vm=p.enum(["SingleEmail","DailyWorkflowEmails"]),Wm=p.object({tool:p.literal(U),version:p.literal(1),dryRun:p.literal(!0),result:p.object({wouldInsertCount:A,failedCount:A}),writePlan:p.object({totalRows:A,storageBytes:A,objects:p.array(p.object({objectApiName:p.string().min(1),rows:A,storageBytes:A,mayAdd:A.optional()})),emails:p.array(p.object({limit:Vm,emails:A})).optional()}).optional(),wouldBeRefused:p.array(p.string()).optional(),wouldBeRefusedCodes:p.array(p.string()).optional(),targetGaps:p.object({gaps:p.array(p.object({kind:p.string().min(1),severity:p.string().min(1),objectApiName:p.string().min(1),field:p.string().min(1).optional()}).loose())}).loose().optional()}),Jm=p.object({tool:p.literal(U),version:p.literal(1),dryRun:p.literal(!1),targetOrgId:qe.optional(),result:p.object({successCount:A,failedCount:A,createdByObject:p.array(p.object({objectApiName:p.string().min(1),sourceIds:p.array(qe)})),remapInJournal:p.literal(!0).optional(),createdCountByObject:p.array(p.object({objectApiName:p.string().min(1),created:A})).optional(),errors:p.array(p.object({objectApiName:p.string().min(1),failedCount:A,samples:p.array(p.unknown()).optional()}))}),running:p.literal(!0).optional(),interrupted:p.literal(!0).optional(),error:p.string().optional()}),Ym=p.object({tool:p.literal(U),version:p.literal(1),action:p.literal("remove"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),result:p.object({status:p.enum(["success","partial","failure","cancelled"]),planned:A,objects:p.array(St),sweep:p.object({status:p.string()}).loose().optional()}),elapsedMs:A}),Gm=p.object({tool:p.literal(U),version:p.literal(1),action:p.literal("remove-preview"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),preview:Rt,refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional(),notes:p.array(p.string()),elapsedMs:A}),Hm=p.object({tool:p.literal(U),version:p.literal(1),action:p.literal("verify"),result:p.object({verdict:p.enum(["verified","partial","unstable"]),attempts:A,objects:p.array(p.object({objectApiName:p.string().min(1),expected:A,present:A,deleted:A,notVisible:A,changed:A,linksChecked:A,linksBroken:A,error:p.string().optional()})),linksUnchecked:p.string().optional()})});function Nl(e,t){let n=new Set((t?.config.defaultValues??[]).map(s=>`${s.object}.${s.field}`.toLowerCase())),r=(e.targetGaps?.gaps??[]).filter(s=>s.severity==="blocking").flatMap(s=>{let i=s.field!==void 0?`${s.objectApiName}.${s.field}`:s.objectApiName;switch(s.kind){case"required_field_missing":return n.has(i.toLowerCase())?[]:[`${i}, which the org requires and the clone does not write`];case"object_not_createable":case"object_through_parent":return[`${i}, which the user it writes as may not create`];case"object_feature_off":return[`${i}, which a feature or licence the org has not turned on keeps closed`];case"api_budget":return["more API requests than the org has left today"];default:return[`${i} (${s.kind})`]}});if(r.length!==0)return`the org to fill would refuse its rows: ${r.join("; ")}. Give a field the org requires a value in the template's defaultValues (template: { file, id }), leave out an object its user may not create, or run it once the org has requests left`}function Il(e){return z(U,"the summary of a dry run",Wm,e)}function cn(e){return z(U,"the summary of a run",Jm,e)}function Dl(e){return z(U,"the outcome of a removal",Ym,e)}function Tl(e){return z(U,"the preview of a removal",Gm,e)}function Pl(e){return z(U,"a verification",Hm,e)}function Ll(e){let t=e.writePlan,n=(e.wouldBeRefused??[]).join(" "),r=ze(n,e.wouldBeRefused,e.wouldBeRefusedCodes),s=r.length>0?{refusalCodes:r}:{};if(t===void 0)return{objects:[],total:0,created:0,storageBytes:0,emails:[],refusal:n!==""?n:"the clone never came to count what it would write, and a run held to no count is held to nothing",...s};let i=e.result.wouldInsertCount===t.totalRows,o=n!==""?n:t.totalRows===0?"it would write nothing: the clone reads no record to write; look at its record or the conditions of its tables":void 0;return{objects:t.objects.map(a=>({object:a.objectApiName,wouldCreate:a.rows,...i?{}:{atMost:!0}})),total:t.totalRows,created:e.result.wouldInsertCount,storageBytes:t.storageBytes,emails:t.emails??[],...o!==void 0?{refusal:o,...s}:{}}}function Or(e){let n=((e.result.remapInJournal===!0?e.result.createdCountByObject:void 0)??e.result.createdByObject.map(r=>({objectApiName:r.objectApiName,created:r.sourceIds.length}))).map(r=>({object:r.objectApiName,created:r.created,refused:0,errors:[]}));for(let r of e.result.errors){if(r.failedCount===0)continue;let s=n.find(o=>o.object===r.objectApiName),i=`${r.failedCount} refused by the org`;s!==void 0?(s.refused+=r.failedCount,s.errors.push(i)):n.push({object:r.objectApiName,created:0,refused:r.failedCount,errors:[i]})}return{objects:n,created:e.result.successCount}}function Fl(e){let{result:t}=e;if(t.verdict==="unstable")return`no two of ${t.attempts} readings agreed: something still writes to the run's records; verify again once it is done`;let n=t.objects.flatMap(r=>{if(r.error!==void 0)return[`${r.objectApiName} not read (${r.error})`];let s=r.deleted+r.notVisible;return[...s>0?[`${r.objectApiName} ${s} of ${r.expected} not there`]:[],...r.linksBroken>0?[`${r.objectApiName} ${r.linksBroken} lookup(s) that do not hold`]:[]]});return n.length>0?n.join("; "):void 0}function ml(e){return e instanceof Error?e.message:String(e)}import{readFileSync as Ml}from"node:fs";import{join as _l}from"node:path";var Q="sandforge-frozen",xl=1e6,Qm=["sasDir","datasetDir"],Xm=["rootObject","excludedObjects","identityKeys","undeletableObjects","requiredLookupPlaceholders","requiredFieldDefaults","picklistRules","defaultPicklistRule","duplicateErrorPatterns"],ql=new Set(["NO_LOAD","ALREADY_REMOVED","NOTHING_TO_REMOVE"]);function zl(e,t,n){let r=["resources",e,"config"],s=f=>({refusals:[T(r,f)]}),i;try{i=Ml(_l(n,t.config),"utf8")}catch(f){return s(`${t.config} cannot be read: ${f instanceof Error?f.message:String(f)}`)}if(i.length>xl)return s(`${t.config} is larger than ${xl} bytes`);let o;try{o=JSON.parse(i.replace(/^\uFEFF/,""))}catch{return s(`${t.config} is not JSON: a Frozen configuration is the panel's, as JSON`)}let a=nr(o);if(a.length>0)return{refusals:a.map(({path:f,secret:g})=>T(r,`${t.config} holds a key shaped like a secret (${g}) at ${f.join(".")}: a load never reads the salt, and the configuration holds no secret. Take it out.`))};let c=cc.strict().safeParse(o);if(!c.success)return{refusals:c.error.issues.map(f=>T(r,`${t.config} is refused by Frozen's configuration schema at ${f.path.map(String).join(".")||"its top"}: ${f.message}`))};let l=[],u={...c.data},d=Qm.filter(f=>u[f]!==void 0);for(let f of d)delete u[f];return d.length>0&&l.push(T(r,`${t.config} gives ${d.join(" and ")}, which the environment sets: the loads are kept beside the state, and the dataset is the one the file pins`)),{run:{configFile:t.config,config:u,dataset:{...t.dataset}},warnings:l}}function Bl(e){return{kind:"frozen",kindVersion:1,dataset:{digest:e.dataset.digest,version:e.dataset.version},load:Object.fromEntries(Xm.map(t=>[t,e.config[t]??null]))}}function Kl(e,t){return{...e.config,sasDir:t.sasDir,datasetDir:t.datasetDir}}async function Ul(e,t){let n,r;try{n=await Tc(e),r=JSON.parse(Ml(_l(e,"manifest.json"),"utf8")).version}catch(s){return{refusal:`its dataset at ${e} cannot be read: ${s instanceof Error?s.message:String(s)}`}}return n!==t.digest?{refusal:`its dataset at ${e} has the digest ${n}, and the file pins ${t.digest}: it is not the dataset the file was reviewed with. Point the path at that one, or pin this digest once this dataset is reviewed`}:r!==t.version?{refusal:`its dataset at ${e} is version ${String(r)}, and the file pins version ${t.version}: pin the version its manifest says`}:{digest:n,version:t.version}}function ln(e,t){return[e,"--config",I("--config",t.configFile),"--target",I("--target",t.target)]}function Vl(e){return[...ln("load",e),...e.reload?["--reload"]:[],...e.reload&&e.goneFirst!==void 0?["--gone-first",I("--gone-first",e.goneFirst)]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],...e.store!==void 0?["--store",I("--store",e.store)]:[],"--dry-run","--json"]}function Wl(e){return[...ln("load",e),...e.reload?["--reload"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],"--max-total",String(e.maxTotal),"--yes","--json"]}function Jl(e){return[...ln("verify",e),"--json"]}function Yl(e){return[...ln("remove",e),...e.includeChanged===!0?["--include-changed"]:[],...Ce(e),...e.acceptAutomation===!0?["--accept-automation"]:[],"--yes","--json"]}function Gl(e){return[...ln("remove",e),...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],"--preview",...Ce(e),"--json"]}var Zm=p.object({type:p.string().min(1),payload:p.record(p.string(),p.unknown()).optional()}).loose(),un={tool:p.literal(Q),posted:p.array(Zm),dataset:p.object({dir:p.string().min(1),digest:p.string().min(1),version:p.string().optional()}).optional(),mapping:p.string().min(1).optional(),refusals:p.array(p.string()).optional(),refusalCodes:p.array(p.string()).optional(),ended:p.literal(!0).optional()},Hl=p.object({status:p.enum(["PASSED","PARTIAL","FAILED","UNSTABLE"]),objects:p.array(p.object({objectApiName:p.string().min(1),verdict:p.enum(["PASSED","FAILED"]),expected:A,found:A,notLoaded:A,orphans:A,missingKeys:A}))}),eg=p.object({...un,step:p.literal("load"),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:A,toInsert:A,toLink:A,notSent:A,toPurge:A,toDeactivate:A})).optional()}),tg=p.object({...un,step:p.literal("load"),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:A,inserted:A,reused:A,duplicates:A,failed:A})).optional(),verdict:Hl.optional()}),ng=p.object({...un,step:p.literal("verify"),verdict:Hl.optional()});function dn(e,t){return e.filter(n=>n.type===t).at(-1)?.payload}function fn(e){let t=e.find(s=>s.type.endsWith(":error"))?.payload;if(t===void 0)return;let n=typeof t.message=="string"?t.message:"refused",r=typeof t.code=="string"?t.code:void 0;return{message:n,...r!==void 0?{code:r}:{}}}var rg=p.object({...un,step:p.literal("remove")}).transform((e,t)=>{let n=fn(e.posted.filter(g=>g.type!=="frozen:remove:automation:error")),r={planned:0,objects:[],userNames:{}};if(n!==void 0&&!ql.has(n.code??""))return{tool:e.tool,preview:r,refusals:[n.message],...n.code!==void 0?{refusalCodes:[n.code]}:{},removalAlone:[]};let s=dn(e.posted,"frozen:remove:preview:response")?.preview;if(s===void 0)return{tool:e.tool,preview:r,refusals:[],removalAlone:[]};let i=Rt.extend({refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional()}).loose().safeParse(s);if(!i.success)return t.addIssue({code:"custom",message:`its preview: ${i.error.issues[0]?.message}`}),p.NEVER;let{refusals:o,refusalCodes:a,...c}=i.data,l=e.refusals??[],u=new Map(e.refusalCodes?.length===l.length?l.map((g,y)=>[g,e.refusalCodes?.[y]??""]):[]),d=l.filter(g=>!o.includes(g)),f=d.flatMap(g=>u.get(g)??[]);return{tool:e.tool,preview:c,refusals:o,...a?.length===o.length?{refusalCodes:a}:{},removalAlone:d,...f.length===d.length&&f.length>0?{removalAloneCodes:f}:{}}}),sg=p.object({...un,step:p.literal("remove"),status:p.string().optional()}).transform((e,t)=>{let n=fn(e.posted),r={tool:e.tool,result:{status:"success",planned:0,objects:[]}};if(n!==void 0)return ql.has(n.code??"")?r:(t.addIssue({code:"custom",message:`the removal was refused: ${n.message}`}),p.NEVER);let s=dn(e.posted,"frozen:remove:response")?.result;if(s===void 0)return r;let i=p.object({status:p.enum(["success","partial","failure","cancelled"]),objects:p.array(St.loose())}).loose().safeParse(s);return i.success?{tool:e.tool,result:{status:i.data.status,planned:i.data.objects.reduce((o,a)=>o+a.planned,0),objects:i.data.objects}}:(t.addIssue({code:"custom",message:`its result: ${i.error.issues[0]?.message}`}),p.NEVER)});function Ql(e){return z(Q,"the answer of a dry run",eg,e)}function Cr(e){return z(Q,"the answer of a load",tg,e)}function Xl(e){return z(Q,"a verification",ng,e)}function Zl(e){return z(Q,"the preview of a removal",rg,e)}function eu(e){return z(Q,"the outcome of a removal",sg,e)}function ig(e){let n=(Array.isArray(e?.removals)?e.removals:[]).flatMap(r=>{let s=r;return s.reason==="may-hold-masks"?[`${String(s.objectApiName)}.${String(s.field)} (${Number(s.affectedRecords??0)})`]:[]});return n.length>0?[`it would leave out, encrypted in the target, ${n.join(", ")}: the dataset's manifest does not say its extraction left out what it read masked, so they may hold masks such as ****1234`]:[]}function og(e){return(Array.isArray(e?.perObject)?e.perObject:[]).flatMap(n=>{let r=n,s=Number(r.picklistsRewritten??0),i=Number(r.fieldsDropped??0),o=[s>0?`${s} picklist value(s) a restricted picklist of the target refuses, rewritten by their rule`:"",i>0?`${i} field(s) the target lacks or takes no value of, dropped`:""].filter(Boolean);return o.length>0?[`${String(r.objectApiName)}: ${o.join(", ")}`]:[]})}function ag(e){let t=e?.emails?.counted;return Array.isArray(t)?t.flatMap(n=>{let{limit:r,emails:s}=n??{};return(r==="SingleEmail"||r==="DailyWorkflowEmails")&&typeof s=="number"?[{limit:r,emails:s}]:[]}):[]}function tu(e){let t=fn(e.posted),n=[...t!==void 0?[t.message]:[],...e.refusals??[]],r=e.objects??[],s=r.reduce((u,d)=>u+d.toInsert,0),i=dn(e.posted,"frozen:load:preview:response")?.plan,o=n.length>0?n.join(" "):e.objects===void 0?"the load never came to say what it would write, and a run held to no count is held to nothing":s===0?"it would insert nothing: every record of the dataset is one the org holds already, linked by its identity keys, or one the load does not send":void 0,a=[...ig(i),...og(i)],c=e.refusals??[],l=o!==void 0?ze(o,n,[...t!==void 0?[t.code??""]:[],...e.refusalCodes?.length===c.length?e.refusalCodes:c.map(()=>"")]):[];return{objects:r.map(u=>({object:u.objectApiName,wouldCreate:u.toInsert})),total:s,created:s,storageBytes:r.reduce((u,d)=>u+hc(d.objectApiName,{rows:d.toInsert}),0),emails:ag(i),...o!==void 0?{refusal:o}:{},...l.length>0?{refusalCodes:l}:{},...a.length>0?{notes:a}:{}}}function pn(e){let t=fn(e.posted),n=(e.objects??[]).map(r=>({object:r.objectApiName,created:r.inserted,refused:r.failed,errors:r.failed>0?[`${r.failed} refused by the org`]:[]}));return n.length===0&&t!==void 0?{objects:[],created:0,refusal:t.message}:{objects:n,created:n.reduce((r,s)=>r+s.created,0)}}function jr(e){let n=dn(e.posted,"frozen:load:response")?.report?.purge;if(n===void 0)return!1;let r=Object.values(n.leftUnrecorded??{}).reduce((s,i)=>s+i,0);return(n.failures??[]).length===0&&r===0}function nu(e){let t=dn(e.posted,"frozen:load:response")?.report;return[...Object.values(t?.purge?.deleted??{}),...Object.values(t?.purge?.deactivated??{})].some(r=>r>0)}function bi(e){if(e.status==="UNSTABLE")return{unstable:!0,short:"no two readings of the org agreed: something still writes to the load\u2019s records; verify again once it is done"};let t=e.objects.filter(n=>n.verdict==="FAILED").map(n=>{let r=[`${n.found} of ${n.expected} found`,n.orphans>0?`${n.orphans} orphan(s)`:"",n.missingKeys>0?`${n.missingKeys} key(s) missing`:"",n.notLoaded>0?`${n.notLoaded} not loaded`:""].filter(Boolean);return`${n.objectApiName} FAILED (${r.join(", ")})`});return t.length>0?{unstable:!1,short:t.join("; ")}:e.status!=="PASSED"?{unstable:!1,short:`its verdict is ${e.status}`}:{unstable:!1}}function ru(e){let t=fn(e.posted);if(e.verdict===void 0)return{unread:t?.message??"the verification gave no verdict"};let{short:n,unstable:r}=bi(e.verdict);return r?{unread:n??"no two readings agreed"}:{failed:n!==void 0?[n]:[]}}function Ve(e){return`frozen/${e}`}function Nr(e){return e!==void 0&&/^frozen\/[a-z][a-z0-9-]{0,62}$/.test(e)?e.slice(7):void 0}import{existsSync as Ei}from"node:fs";import{rm as cg}from"node:fs/promises";import{join as su}from"node:path";var se="sandforge-dataops",iu="snapshots.json";function ou(e){let t={},n=[];for(let[r,s]of Object.entries(e)){let i=ac.safeParse({name:r,rules:s.rules});if(!i.success){n.push(...i.error.issues.map(o=>T(["masking",r,...o.path],`refused by the rules the DataOps panel saves: ${o.message}`)));continue}t[r]={name:r,rules:s.rules}}return n.length>0?{refusals:n}:{sets:t}}function lg(e){let t=Zs.find(r=>r.id===e);if(t===void 0)return;let n=t.rules.flatMap(r=>{if(!Va(r.ruleType))return[];let s="config"in r?r.config:void 0;return[{fieldPattern:r.fieldPattern,ruleType:r.ruleType,...s!==void 0?{config:{...s}}:{}}]});return{name:t.name,rules:n}}function au(e,t,n){let r=["resources",e,"rules"],s,i;if(typeof t.rules=="string"){if(s=n[t.rules],i={set:t.rules},s===void 0)return{refusals:[T(r,`the rule set ${t.rules} is refused: see masking`)]}}else{let d=t.rules.template;if(s=lg(d),i={template:d},s===void 0)return{refusals:[T([...r,"template"],`there is no DataOps template "${d}" that ships: there is `+Zs.map(f=>f.id).join(", "))]}}let o=t.object;if(o!==void 0&&!Fc({id:s.name,name:s.name,rules:s.rules},o))return{refusals:[T(["resources",e,"object"],`${"set"in i?`the rule set ${i.set}`:`the template ${i.template}`} has no rule for ${o}: a run would mask nothing. Name an object its rules mask, or give it a rule for this one`)]};let a=[],c=`${(o??"").toLowerCase()}.`,l=new Map(s.rules.filter(d=>o!==void 0&&d.fieldPattern.toLowerCase().startsWith(c)).map(d=>[(d.fieldPattern.split(".")[1]??"").toLowerCase(),d.ruleType])),u=ug(t.where).filter(({field:d,empty:f})=>{let g=l.get(d.toLowerCase());return g!==void 0&&(!f||g==="nullify")}).map(({field:d})=>d);return u.length>0&&a.push(T(["resources",e,"where"],`its condition reads ${u.join(", ")}, which its rules write over: once masked, its records may no longer be those it selects, and a plan after reads them as gone. Select them by a field its rules leave as it is`)),{run:{source:i,rules:s,...o!==void 0?{object:o}:{},...t.where!==void 0?{where:t.where}:{},...t.accept?.automation===!0?{acceptAutomation:!0}:{}},warnings:a}}function ug(e){if(e===void 0)return[];let t=e.replace(/'(?:[^'\\]|\\.)*'/g,"''"),n=new Map;for(let r of t.matchAll(/\b([A-Za-z][A-Za-z0-9_]*)\s*(=|!=|<>|<=|>=|<|>|\s(?:NOT\s+)?(?:LIKE|IN|INCLUDES|EXCLUDES)\b)\s*(null\b)?/gi)){let s=r[1]??"";if(/^(?:AND|OR|NOT)$/i.test(s))continue;let i=/^(?:=|!=|<>)$/.test(r[2]??"")&&r[3]!==void 0;n.set(s,(n.get(s)??!0)&&i)}return[...n].map(([r,s])=>({field:r,empty:s}))}function cu(e){return{kind:"mask",kindVersion:1,rules:[...e.rules.rules].map(t=>({...t,fieldPattern:t.fieldPattern.toLowerCase()})).sort((t,n)=>Et(t).localeCompare(Et(n))),object:e.object??null,where:e.where??null}}function lu(e){if(e.object!==void 0)return[{object:e.object}];let t=[];for(let n of e.rules.rules){let r=n.fieldPattern.split(".")[0]??"";t.includes(r)||t.push(r)}return t.map(n=>({object:n}))}function uu(e){return{name:e.rules.name,rules:e.rules.rules}}function jt(e){return`dataops/${e}`}function du(e){let{run:t}=e;return["anonymize","--org",I("--org",e.target),...t.object!==void 0?["--object",I("--object",t.object)]:[],...t.where!==void 0?["--where",I("--where",t.where)]:[],..."template"in t.source?["--template",I("--template",t.source.template)]:["--rules",I("--rules",e.rulesFile)],"--store",I("--store",e.store),...t.acceptAutomation===!0?["--accept-automation"]:[]]}function fu(e){return[...du(e),"--dry-run","--json"]}function pu(e){return[...du(e),"--yes","--json"]}var dg=p.object({type:p.string().min(1),payload:p.record(p.string(),p.unknown()).optional()}).loose(),Ot=p.number().int().nonnegative(),hu={tool:p.literal(se),org:p.string().min(1),posted:p.array(dg)},fg=p.object({...hu,command:p.literal("dry-run")}),pg=p.object({...hu,command:p.literal("run")});function mu(e){return z(se,"the answer of a dry run",fg,e)}function Ir(e){return z(se,"the answer of a masking",pg,e)}function Ct(e,t){return e.filter(n=>n.type===t).at(-1)?.payload}function gu(e){let t=Ct(e,"dataops:error");if(t!==void 0)return typeof t.message=="string"?t.message:"refused"}var hg=p.object({objects:p.array(p.object({objectApiName:p.string().min(1),count:Ot.nullable()}).loose())}),mg=p.object({objects:p.array(p.object({objectApiName:p.string().min(1),fields:p.array(p.string()),error:p.string().optional(),notCovered:p.literal(!0).optional(),writeDenied:p.object({deniedFields:p.array(p.string())}).optional()}).loose()),fieldsNotFound:p.array(p.object({objectApiName:p.string(),fieldApiName:p.string()}))}),gg=p.object({emails:p.array(p.object({limit:p.enum(["SingleEmail","DailyWorkflowEmails"]),emails:Ot}).loose()),refusals:p.array(p.object({code:p.string(),message:p.string()}).loose())}).loose();function yu(e){let t=[],n=gu(e.posted);n!==void 0&&t.push(n);let r=hg.safeParse(Ct(e.posted,"dataops:anonymize:coverage:response")),s=mg.safeParse(Ct(e.posted,"dataops:anonymize:preview:response"));if(!r.success||!s.success)return n===void 0&&t.push("the masking never came to say what it would mask, and a run nobody counted is masked blind"),{objects:[],refusals:t,refusalCodes:t.map(()=>""),emails:[]};let i=gg.safeParse(Ct(e.posted,"dataops:automation:response")),o=r.data.objects.map(l=>({object:l.objectApiName,count:l.count}));for(let l of o)l.count===null&&t.push(`${l.object}: the org did not count the records it would mask`);for(let l of s.data.objects){l.error!==void 0?t.push(`${l.objectApiName}: not read: ${l.error}`):l.notCovered===!0&&t.push(`${l.objectApiName}: its rules mask no field the org shows this user: a run would mask nothing there`);let u=l.writeDenied?.deniedFields;u?.length===0&&t.push(ni(l.objectApiName));for(let d of u??[])t.push(ni(l.objectApiName,d))}for(let l of s.data.fieldsNotFound)t.push(ti(l.objectApiName,l.fieldApiName));let a=new Map;for(let l of i.success?i.data.refusals:[])t.push(l.message),a.set(l.message,l.code);let c=i.success?i.data.emails.map(({limit:l,emails:u})=>({limit:l,emails:u})):[];return{objects:o,refusals:t,refusalCodes:t.map(l=>a.get(l)??""),emails:c}}function wu(e){let t=yu(e),n=t.objects.map(i=>({object:i.object,wouldCreate:i.count??0})),r=t.refusals.length>0?t.refusals.join(" "):void 0,s=r!==void 0?ze(r,t.refusals,t.refusalCodes):[];return{objects:n,total:n.reduce((i,o)=>i+o.wouldCreate,0),created:0,storageBytes:0,emails:t.emails,...r!==void 0?{refusal:r}:{},...s.length>0?{refusalCodes:s}:{}}}var yg=p.object({status:p.string().optional(),objects:p.array(p.object({objectApiName:p.string().min(1),total:Ot,processed:Ot,failed:Ot,notMasked:Ot}).loose()).optional(),fieldsNotFound:p.array(p.object({objectApiName:p.string(),fieldApiName:p.string()})).optional(),snapshot:p.object({operationId:p.string().min(1).max(200)}).loose().optional(),message:p.string().optional(),errors:p.array(p.object({objectApiName:p.string(),message:p.string()})).optional()}).loose();function hn(e){let t=yg.safeParse(Ct(e.posted,"dataops:anonymize:response")??Ct(e.posted,"dataops:error")??{}),n=t.success?t.data:{},r=(n.objects??[]).map(o=>({object:o.objectApiName,masked:o.processed,refused:o.failed,notMasked:o.notMasked})),s=gu(e.posted),i=(n.fieldsNotFound??[]).map(o=>ti(o.objectApiName,o.fieldApiName));return{objects:r,...n.snapshot!==void 0?{snapshotId:n.snapshot.operationId}:{},...s!==void 0?{refusal:s}:{},...i.length>0?{short:i.join("; ")}:{}}}function vu(e,t){let n=yu(t),r=e.runs.at(-1),s=new Map((r?.objects??[]).map(a=>[a.objectApiName,a.masked??0]));if(n.refusals.length>0)return{objects:[],masked:0,unread:n.refusals.join(" ")};let i=[],o=[];for(let{object:a,count:c}of n.objects){let l=c??0,u=s.get(a)??0;o.push({object:a,present:Math.min(l,u),...l<u?{gone:u-l}:{}}),l>u?i.push(`${a} ${l} under its condition, ${u} masked: ${l-u} more, which hold their original values`):l<u&&i.push(`${a} ${l} under its condition, ${u} masked: ${u-l} gone`)}return{objects:o,masked:[...s.values()].reduce((a,c)=>a+c,0),...i.length>0?{drift:i.join("; ")}:{}}}function Si(e,t){return`${ue("dataops")} anonymize --org ${e.alias} --restore ${t} --store ${e.store??"<its store>"}`}function ku(e,t){return t.store??`${jt(e)} beside the state`}function bu(e,t){return[`masking is one-way: each run first takes a snapshot of the values it writes over, kept on this machine in ${ku(e,t)}, and destroy never puts them back: it deletes the snapshots. Putting them back is your own act, before a destroy: `+Si(t,"<the snapshot its run names>")]}function Eu(e){return e.runs.find(t=>t.takenBack!==!0)}function wg(e){let t=Eu(e);return t?.snapshotId!==void 0?`snapshot ${t.snapshotId}, run ${t.n}'s`:t!==void 0?`the snapshot run ${t.n} took`:"the snapshot its first run took"}function Ri(e){return`it masks again what its condition selects, the records it masked before a second time, and takes nothing back first: the values they held before any masking stay only in ${wg(e)}, which destroy deletes`}var Su={applying:"its last masking was stopped part way",partial:"its last masking left values as they were: records the org refused, or fields it does not show this user",failed:"its last masking failed",destroying:"a deletion of its snapshots was stopped part way"};function Ru(e){return`applied, and its condition selects the ${e} record(s) it masked, with the same rules: masked again they would only be masked twice`}function $u(e,t){return`its condition selects other records than it masked: ${t}. Left as they are: --replace ${e} or --replace-drifted masks them all again`}function $i(e,t,n,r){let s=Eu(n)?.snapshotId;return`${e==="destroy"?"taken back by destroy, which never unmasks":"in the state, gone from the file"}: its records stay masked, and its store, ${ku(t,r)}, is deleted from this machine with its snapshots, the only copy of the values they held. `+(s!==void 0?`To put back those they held before any masking, before this ${e}, as your own act: ${Si(r,s)}`:`Its snapshots are listed in its store: ${Si(r,"<snapshot>")} puts one back, before this ${e}, as your own act`)}async function Au(e){if(!Ei(e))return{snapshots:[]};let t=Ei(su(e,iu))?vc(su(e,iu)).getKeysByPrefix("backup:").map(n=>n.slice(7)).filter(n=>!n.includes(":")):[];if(await cg(e,{recursive:!0,force:!0}),Ei(e))throw new Error(`${e} is still there: delete it, it holds the values a masking wrote over`);return{snapshots:[...new Set(t)].sort()}}function Ou(e,t){let n=t.snapshots.length>0?`its snapshot${t.snapshots.length===1?"":"s"} ${t.snapshots.join(", ")}`:"no snapshot";return`${e}: its records stay masked \u2014 destroy never unmasks \u2014, and ${n}, the only copy of the values they held, deleted from this machine with its store`}var Y="sandforge-seed",vg="In the file: fit: share seeds the largest share of each count that fits, fit: { withinMB: <MB> } no more than that; or lower each object\u2019s count.";function Nu(e,t,n,r){let s=kg(e,t,n,r);if("refusal"in s)return{refusals:[s.refusal]};let i=Eg(t,n,s.run);return i.refusals.length>0?{refusals:i.refusals}:{run:s.run,warnings:i.warnings}}function kg(e,t,n,r){let s=r.toISOString(),i={id:`env-${e}-${t}`,name:`${e}/${t}`,description:`The ${t} resource of the ${e} environment`,version:1,tags:["sandforge-env"],createdAt:s,updatedAt:s},o,a=[];if(n.template!==void 0){let l=Qs.find(u=>u.id===n.template);if(l===void 0)return{refusal:T(["resources",t,"template"],`there is no built-in template "${n.template}": there is ${Qs.map(u=>u.id).join(", ")}`)};o={...i,strategy:l.strategy,objects:structuredClone(l.objects),...l.relations!==void 0?{relations:structuredClone(l.relations)}:{}}}else o={...i,strategy:"faker",objects:(n.objects??[]).map((l,u)=>({objectApiName:l.object,recordCount:l.count,fieldRules:structuredClone(l.fields??[]),excludedFields:[],insertOrder:u,batchSize:l.batchSize??200})),...n.relations!==void 0?{relations:n.relations.flatMap((l,u)=>{let d=l.parents.from;if(d===void 0)return[Cu(l)];let{childObject:f,lookupField:g,parentObject:y,distribution:m}=Cu(l);return a.push({at:u,relation:{childObject:f,lookupField:g,parentObject:y,distribution:m},from:d.split(".")[0]??d,...l.parents.limit!==void 0?{limit:l.parents.limit}:{}}),[]})}:{}};let c=Object.fromEntries((n.objects??[]).filter(l=>l.recordTypes!==void 0).map(l=>[l.object,[...new Set(l.recordTypes)]]));return{run:{template:o,...n.locale!==void 0?{locale:n.locale}:{},...n.seed!==void 0?{seed:n.seed}:{},...Object.keys(c).length>0?{recordTypes:c}:{},...n.fit!==void 0?{fit:n.fit==="share"?{}:{withinMB:n.fit.withinMB}}:{},acceptAutomation:n.accept?.automation===!0,...a.length>0?{draws:a}:{}}}}function bg(e){return e.object??e.from?.split(".")[1]??""}function Cu(e){let[t="",n=""]=e.lookup.split("."),r=e.parents.existing;return{childObject:t,lookupField:n,parentObject:bg(e.parents),parents:r===void 0?{kind:"generated"}:{kind:"existing",...r.where!==void 0?{where:r.where}:{},limit:r.limit},distribution:e.distribution}}function Iu(e){return{kind:"existing",limit:e.limit??tr.maxExistingParents}}function Du(e,t){let n=[...e.template.relations??[]],r=e.draws??[],s=[];for(let i=0;i<n.length+r.length;i++){let o=r.find(c=>c.at===i),a=o!==void 0?{...o.relation,parents:t(o)}:n.shift();a!==void 0&&s.push(a)}return s}function Ai(e,t,n){return(e.draws??[]).length===0?e.template:{...e.template,relations:Du(e,r=>{let s=t?.get(r.at);if(s!==void 0&&s.length>0)return{kind:"records",ids:[...s]};if(!n.standIns)throw new Error(`The relation on ${r.relation.childObject}.${r.relation.lookupField} draws its parents from ${r.from}, whose records are not known: plan again.`);return Iu(r)})}}var ju=Object.keys(Nc);function Eg(e,t,n){let r=["resources",e],s=Ai(n,void 0,{standIns:!0}),i=oc.safeParse(s);if(!i.success)return{refusals:i.error.issues.map(l=>T(Sg(r,t,l.path),l.message)),warnings:[]};let o=new Dc().validate(s),a=({field:l,message:u})=>T(Rg(r,t,s,l),u),c=n.locale!==void 0&&!ju.includes(n.locale)?[T([...r,"locale"],`the seed draws in ${ju.join(", ")}, not ${n.locale}: name one of them, or leave locale out to draw in the org\u2019s own`)]:[];return{refusals:[...o.errors.map(a),...c],warnings:o.warnings.map(a)}}function Sg(e,t,n){if(t.template!==void 0)return[...e,"template"];let[r,s,i,...o]=n;if(r==="objects"&&typeof s=="number"){let a=[...e,"objects",s];return i==="objectApiName"?[...a,"object"]:i==="recordCount"?[...a,"count"]:i==="fieldRules"?[...a,"fields",...o]:i===void 0?a:[...a,i]}if(r==="relations"&&typeof s=="number"){let a=[...e,"relations",s];return i==="childObject"||i==="lookupField"?[...a,"lookup"]:i==="parentObject"?[...a,"parents","object"]:i==="parents"?[...a,"parents","existing",...o]:i===void 0?a:[...a,i,...o]}return e}function Rg(e,t,n,r){if(t.template!==void 0)return[...e,"template"];let s=/^objects\[([^\]]+)\](?:\.fieldRules\[([^\]]+)\])?/.exec(r);if(s!==null){let o=n.objects.findIndex(l=>l.objectApiName===s[1]);if(o<0)return e;let a=s[2],c=a===void 0?-1:(n.objects[o]?.fieldRules??[]).findIndex(l=>l.fieldApiName===a);return c<0?[...e,"objects",o]:[...e,"objects",o,"fields",c]}let i=/^relations\[([^\]]+)\]/.exec(r);if(i!==null){let o=(n.relations??[]).findIndex(a=>`${a.childObject}.${a.lookupField}`===i[1]);return o<0?e:[...e,"relations",o]}return e}function Tu(e){let{template:t}=e;return{kind:"seed",kindVersion:1,strategy:t.strategy,objects:t.objects.map(n=>({objectApiName:n.objectApiName,recordCount:n.recordCount,recordTypeId:n.recordTypeId,fieldRules:n.fieldRules,excludedFields:n.excludedFields,insertOrder:n.insertOrder})),relations:t.relations??[],locale:e.locale??null,seed:e.seed??null,recordTypes:e.recordTypes??{},draws:e.draws,...e.fit!==void 0?{fit:e.fit}:{}}}function Pu(e){return e.template.objects.map(t=>({object:t.objectApiName,count:t.recordCount}))}function Lu(e){let{template:t}=e,n=Du(e,Iu),r=new Set(n.filter(s=>s.parents.kind==="existing").map(s=>s.childObject));for(let s=!0;s;){s=!1;for(let i of t.objects)r.has(i.objectApiName)||Ua(i,n).some(o=>r.has(o))&&(r.add(i.objectApiName),s=!0)}return new Map(t.objects.filter(s=>r.has(s.objectApiName)).map(s=>[s.objectApiName,s.recordCount]))}function Fu(e){return["--target",I("--target",e.target),"--template-file",I("--template-file",e.templateFile),"--run-id",I("--run-id",e.runId),...e.seed!==void 0?["--seed",String(e.seed)]:[],...e.locale!==void 0?["--locale",I("--locale",e.locale)]:[],...Object.entries(e.recordTypes??{}).flatMap(([t,n])=>["--record-type",I("--record-type",`${t}=${n.join(",")}`)]),...e.fit!==void 0?["--fit","share",...e.fit.withinMB!==void 0?["--fit-within",String(e.fit.withinMB)]:[]]:[]]}function xu(e){return[...Fu(e),"--json","--fail-on-partial"]}function Mu(e){return[...Fu(e),"--dry-run","--json"]}function _u(e){return[...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],...e.leaveUndeletable===!0?["--leave-undeletable"]:[]]}function qu(e){return["--remove",I("--remove",e.summary),"--target",I("--target",e.target),..._u(e),...Ce(e),"--json"]}function zu(e){return["--remove",I("--remove",e.summary),"--target",I("--target",e.target),"--preview",..._u(e),...Ce(e),"--json"]}var $g=p.object({limit:p.enum(["SingleEmail","DailyWorkflowEmails"]),emails:A,verdict:p.enum(["fits","exceeds","unread"]),remaining:p.number().int().optional(),max:p.number().int().optional(),unread:p.string().optional()}),Ag=p.object({checks:p.array($g),refusal:p.string().optional(),unknown:p.array(p.string()).optional()}),Og=p.object({records:A,given:A,refusal:p.string().optional()}),Cg=e=>p.object({objectApiName:p.string().min(1),recordsCreated:A,recordsFailed:A,createdIds:p.array(e),errors:p.array(p.string()),truncated:p.boolean().optional(),writtenByThePlatform:Og.optional()}),Bu=e=>p.object({templateId:p.string().optional(),operationId:p.string().min(1),status:p.enum(["success","partial","failure"]),cancelled:p.boolean().optional(),objectResults:p.array(Cg(e)),totalRecordsCreated:A,totalRecordsFailed:A}),Ku={tool:p.literal(Y),target:p.string().min(1),seed:p.number().int().nonnegative(),startedAt:p.string().min(1),finishedAt:p.string().min(1),notes:p.array(p.string()).optional(),emails:Ag,elapsedMs:A,interrupted:p.literal(!0).optional()},jg=p.object({...Ku,dryRun:p.literal(!1),targetOrgId:qe.optional(),result:Bu(qe),runFile:p.string().min(1).optional()}),Ng=p.object({bytes:A,verdict:p.enum(["fits","near","exceeds","unread"]),estimateMB:p.number().nonnegative(),maxMB:p.number().optional(),remainingMB:p.number().optional(),unread:p.string().optional(),refusal:p.string().optional()}),Ig=p.object({estimate:A,verdict:p.enum(["fits","near","exceeds","unread"]),max:p.number().int().optional(),remaining:p.number().int().optional(),unread:p.string().optional(),refusal:p.string().optional()}),Dg=p.object({...Ku,dryRun:p.literal(!0),storage:Ng,apiRequests:Ig,wouldBeRefused:p.array(p.string()).optional(),wouldBeRefusedCodes:p.array(p.string()).optional(),result:Bu(p.string())}),Tg=p.object({tool:p.literal(Y),action:p.literal("remove"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),result:p.object({status:p.enum(["success","partial","failure","cancelled"]),planned:A,objects:p.array(St),sweep:p.object({status:p.string()}).loose().optional()}),elapsedMs:A}),Pg=p.object({tool:p.literal(Y),action:p.literal("remove-preview"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),preview:Rt,refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional(),notes:p.array(p.string()),elapsedMs:A});function Nt(e){return z(Y,"the summary of a run",jg,e)}function Uu(e){return z(Y,"the summary of a dry run",Dg,e)}function Vu(e){return z(Y,"the preview of a removal",Pg,e)}function Wu(e){return z(Y,"the outcome of a removal",Tg,e)}var Ju="validation";function Yu(e,t){let n=e.result.objectResults,r=c=>{let l=ze(c,e.wouldBeRefused,e.wouldBeRefusedCodes);return l.length>0?{refusalCodes:l}:{}};if(e.result.status==="failure"&&n.length>0&&n.every(c=>c.objectApiName===Ju)){let c=n.flatMap(u=>u.errors),l=c.length>0?c.join(" "):"the seed refused its dry run";return{objects:[],total:0,created:0,apiRequests:e.apiRequests.estimate,storageBytes:0,emails:[],refusal:l,...r(l)}}let s=e.result.objectResults.map(c=>{let l=t?.get(c.objectApiName);return l!==void 0?{object:c.objectApiName,wouldCreate:Math.max(c.recordsCreated,l),atMost:!0}:{object:c.objectApiName,wouldCreate:c.recordsCreated}}),i=e.storage.refusal??e.apiRequests.refusal??e.emails.refusal,o=i!==void 0&&i===e.storage.refusal?`${i} ${vg}`:i,a=e.result.objectResults.flatMap(c=>c.writtenByThePlatform!==void 0?[Lg(c.objectApiName,c.writtenByThePlatform.records)]:[]);return{objects:s,total:e.result.totalRecordsCreated,created:e.result.totalRecordsCreated,apiRequests:e.apiRequests.estimate,storageBytes:e.storage.bytes,emails:e.emails.checks.map(c=>({limit:c.limit,emails:c.emails})),...o!==void 0&&i!==void 0?{refusal:o,...r(i)}:{},...a.length>0?{notes:a}:{}}}function Lg(e,t){return`${e}: ${t} record(s) linked to the contact role the platform writes with their opportunity, for its contact, not written: given the fields the seed generates for ${t===1?"it":"them"}`}function Dr(e){let t=e.result.objectResults;if(e.result.status==="failure"&&t.length>0&&t.every(n=>n.objectApiName===Ju)){let n=t.flatMap(r=>r.errors);return{objects:[],created:0,refusal:n.length>0?n.join(" "):"the seed refused its run before it wrote"}}return{objects:e.result.objectResults.map(n=>({object:n.objectApiName,created:n.recordsCreated,refused:n.recordsFailed,errors:n.errors})),created:e.result.totalRecordsCreated}}var Fg={seed:Y,forge:U,frozen:Q,mask:se};function xg(e){return e==="seed"||e==="forge"||e==="frozen"||e==="mask"}function Tr(e){if(!xg(e))throw new Error(`The state holds a resource of kind ${e}, which a later SandForge applies: this one applies seed, forge, frozen and mask resources, and takes back nothing of another kind.`);return Fg[e]}function Gu(e,t,n,r,s,i={}){switch(n.kind){case"seed":{let o=Nu(e,t,n,s);return"refusals"in o?o:{run:{kind:"seed",...o.run},warnings:o.warnings}}case"forge":{let o=yl(e,t,n,r,s);return"refusals"in o?o:{run:{kind:"forge",...o.run},warnings:o.warnings}}case"frozen":{let o=zl(t,n,r);return"refusals"in o?o:{run:{kind:"frozen",...o.run},warnings:o.warnings}}case"mask":{let o=au(t,n,i);return"refusals"in o?o:{run:{kind:"mask",...o.run},warnings:o.warnings}}}}function Hu(e){switch(e.kind){case"seed":return Tu(e.run);case"forge":return El(e.run,e.source.read);case"frozen":return Bl(e.run);case"mask":return cu(e.run)}}function It(e){switch(e.kind){case"seed":return Pu(e);case"forge":return wl(e);case"frozen":return[];case"mask":return lu(e)}}function lt(e){return e==="frozen"||e==="mask"}function Dt(e,t){switch(e.kind){case"seed":return Ai(e.run,t.drawn,{standIns:t.standIns===!0});case"forge":return e.run.template??{};case"frozen":{if(t.sasDir===void 0)throw new Error(`${e.name} is given no folder to keep its loads in: plan again.`);return Kl(e.run,{sasDir:t.sasDir,datasetDir:e.dataset.dir})}case"mask":return uu(e.run)}}function Qu(e,t){switch(e.kind){case"seed":{let n=e.run.seed??t.seed;return{script:Y,args:Mu({target:t.target,templateFile:t.templateFile,runId:t.runId,...n!==void 0?{seed:n}:{},...e.run.locale!==void 0?{locale:e.run.locale}:{},...e.run.recordTypes!==void 0?{recordTypes:e.run.recordTypes}:{},...e.run.fit!==void 0?{fit:e.run.fit}:{}})}}case"forge":return{script:U,args:Rl({...Zu(e),target:t.target,templateFile:t.templateFile,maxTotal:e.run.maxTotal??gl})};case"frozen":return{script:Q,args:Vl({configFile:t.templateFile,target:t.target,reload:t.replace===!0,acceptAutomation:t.acceptAutomation===!0,...t.storeFile!==void 0?{store:t.storeFile}:{},...t.goneFirstFile!==void 0?{goneFirst:t.goneFirstFile}:{}})};case"mask":return{script:se,args:fu({target:t.target,run:e.run,rulesFile:t.templateFile,store:Xu(e,t)})}}}function Xu(e,t){if(t.store===void 0)throw new Error(`${e.name} is given no store to keep its snapshots in: plan again.`);return t.store}function Zu(e){let{run:t,source:n}=e;if(t.wholeOrg)return{source:n.alias,wholeOrg:t.wholeOrg,acceptAutomation:t.acceptAutomation};if(t.tables!==void 0)return{source:n.alias,tables:t.tables,acceptAutomation:t.acceptAutomation};let r=n.read,s=t.record?.id??(r!==void 0&&"recordId"in r?r.recordId:void 0);if(s===void 0)throw new Error(`${e.name} names its record by a query its source has not answered: plan again.`);return{source:n.alias,recordId:s,acceptAutomation:t.acceptAutomation}}function ed(e,t){switch(e){case"seed":return Uu(t);case"forge":return Il(t);case"frozen":return Ql(t);case"mask":return mu(t)}}function Oi(e){return e.kind==="seed"?Lu(e.run):void 0}function td(e,t){return e.kind==="forge"&&t.tool===U?Nl(t,e.run.template):void 0}function Tt(e,t){switch(e.tool){case Y:return Yu(e,t);case U:return Ll(e);case Q:return tu(e);case se:return wu(e)}}function mn(e,t){switch(e.kind){case"seed":return{script:Y,args:xu({target:t.target,templateFile:t.templateFile,runId:t.runId,...t.seed!==void 0?{seed:t.seed}:{},...e.run.locale!==void 0?{locale:e.run.locale}:{},...e.run.recordTypes!==void 0?{recordTypes:e.run.recordTypes}:{},...e.run.fit!==void 0?{fit:e.run.fit}:{}})};case"forge":{if(t.maxTotal===void 0)throw new Error(`${e.name} has no count from its dry run to be held to: plan again.`);return{script:U,args:$l({...Zu(e),target:t.target,templateFile:t.templateFile,maxTotal:t.maxTotal,summary:t.summaryFile})}}case"frozen":{if(t.maxTotal===void 0)throw new Error(`${e.name} has no count from its dry run to be held to: plan again.`);return{script:Q,args:Wl({configFile:t.templateFile,target:t.target,reload:t.replace===!0,acceptAutomation:t.acceptAutomation===!0,maxTotal:t.maxTotal})}}case"mask":return{script:se,args:pu({target:t.target,run:e.run,rulesFile:t.templateFile,store:Xu(e,t)})}}}function Pr(e){throw new Error(`${Pe(e)} takes no run back: a masking is never undone, and its destroy deletes its store`)}function nd(e,t){let n=Tr(e),r=t.sweep===!0?{sweep:!0}:{},s={target:t.target,summary:t.subject,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,...r};switch(n){case Y:return{script:n,args:zu(s)};case U:return{script:n,args:Cl(s)};case Q:return{script:n,args:Gl({configFile:t.subject,target:t.target,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,...r})};case se:return Pr(n)}}function rd(e,t){let n=Tr(e);switch(n){case Y:return Vu(t);case U:return Tl(t);case Q:return Zl(t);case se:return Pr(n)}}function sd(e,t){if(e==="mask")return[];let n=[...t].reverse().filter(r=>r.takenBack!==!0);return e==="frozen"?n.slice(0,1):n}function id(e,t){if(e==="frozen")return{script:Q,args:Jl({configFile:t.subject,target:t.target})}}function od(e){return ru(Xl(e))}function ad(e,t){let n=Tr(e),r={target:t.target,summary:t.subject,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,sweep:t.sweep};switch(n){case Y:return{script:n,args:qu(r)};case U:return{script:n,args:Ol(r)};case Q:return{script:n,args:Yl({configFile:t.subject,target:t.target,includeChanged:t.includeChanged,sweep:t.sweep,acceptAutomation:t.acceptAutomation})};case se:return Pr(n)}}function cd(e,t){let n=Tr(e);switch(n){case Y:return Wu(t);case U:return Dl(t);case Q:return eu(t);case se:return Pr(n)}}function Ci(e){return e?.result.objects??[]}function ld(e,t){return e.kind==="mask"?bu(e.name,t):e.kind==="forge"?kl(e.run,e.source):[]}var nt=sm(Zp());import{isAbsolute as db,resolve as Wn}from"node:path";function da(e){return`${nn(e.path)}: ${e.message}`}var fb=100;function th(e){let t=e.startsWith("\uFEFF")?e.slice(1):e,n=(0,nt.parseDocument)(t,{version:"1.2",schema:"core",merge:!1,uniqueKeys:!1,prettyErrors:!0}),r=n.errors[0]??n.warnings[0];if(r)return{refusal:`The file does not read as YAML 1.2: ${r.message.split(`
147
- `)[0]}`};let s=ua(n.contents,[]);if(s!==void 0)return{refusal:`${nn(s.path)} holds the key "${s.key}" twice: a mapping holds each key once, and the second would replace the first unseen. Keep one.`};try{return{document:n.toJS({maxAliasCount:fb})}}catch(i){return{refusal:`The file does not read as YAML 1.2: ${i instanceof Error?i.message:String(i)}`}}}function ua(e,t){if((0,nt.isMap)(e)){let n=new Set;for(let r of e.items){let s=(0,nt.isScalar)(r.key)?String(r.key.value):String(r.key);if(n.has(s))return{path:t,key:s};n.add(s);let i=ua(r.value,[...t,s]);if(i)return i}}else if((0,nt.isSeq)(e))for(let[n,r]of e.items.entries()){let s=ua(r,[...t,n]);if(s)return s}}function pb(e){return e==="salt"?"a Frozen load never reads its salt, and DataOps templates carry no hash salt: leave it out":"org credentials stay with the sf CLI \u2014 log the org in with sf org login sfdx-url or sf org login jwt before the step, and name it in the file by its alias"}function Jn(e,t,n={}){let r=[...nr(e).map(({path:f,secret:g})=>T(f,`a key shaped like a secret (${g}). The file holds no secret: ${pb(g)}.`)),...Ha(e).filter(({path:f})=>!Ja(f)).map(({path:f})=>T(f,`{ env } stands in ${Wa.join(" and ")} alone: write this value in the file. A variable inside a query or a field value would let a CI variable into what is written.`))];if(r.length>0)return{refusals:r};let s=Ga.safeParse(e);if(!s.success)return{refusals:s.error.issues.map(f=>{let g=f.path,y=f.code==="invalid_key"?f.issues.map(m=>m.message):[];return T(g,y.join("; ")||f.message)})};let i=s.data,o=mb(i);if("refusals"in o)return o;let a=ou(i.masking);if("refusals"in a)return a;let c=[],l=[...hb(i)],u={};for(let[f,g]of Object.entries(i.resources)){let y=Gu(i.name,f,g,Wn(t),n.now??new Date,a.sets);if("refusals"in y){c.push(...y.refusals);continue}l.push(...y.warnings),u[f]=y.run}if(c.push(...gb(u)),c.length>0)return{refusals:c};let d=[];for(let[f,{alias:g}]of Object.entries(i.orgs))typeof g!="string"&&d.push({name:g.env,path:["orgs",f,"alias"],role:f});for(let[f,g]of Object.entries(i.resources))g.kind==="frozen"&&typeof g.dataset.path!="string"&&d.push({name:g.dataset.path.env,path:["resources",f,"dataset","path"],resource:f});return{checked:{file:i,folder:Wn(t),order:o.order,runs:u,variables:d,warnings:l}}}function hb(e){let t=new Set(Object.values(e.resources).flatMap(n=>n.kind==="mask"&&typeof n.rules=="string"?[n.rules]:[]));return Object.keys(e.masking).filter(n=>!t.has(n)).map(n=>T(["masking",n],"no mask resource names this rule set: nothing masks with it"))}function nh(e,t){return e.variables.filter(n=>(t[n.name]??"").trim()==="")}function rh(e,t){return t.kind!=="seed"?[]:(t.relations??[]).flatMap((n,r)=>{let s=n.parents.from?.split(".")[0];return s===void 0?[]:[{from:s,path:["resources",e,"relations",r,"parents","from"]}]})}function fa(e,t){return[...new Set([...t.dependsOn??[],...rh(e,t).map(({from:n})=>n)])]}function mb(e){let t=Object.keys(e.resources),n=[],r=new Map;for(let[a,c]of Object.entries(e.resources)){let l=[];for(let{from:u,path:d}of rh(a,c))u===a?n.push(T(d,`a relation draws its parents from the records another resource created: ${a}'s own are drawn by their object alone, without from`)):u in e.resources?l.includes(u)||l.push(u):n.push(T(d,`"${u}" is no resource of this file: name one of ${t.join(", ")}`));(c.dependsOn??[]).forEach((u,d)=>{let f=["resources",a,"dependsOn",d];u===a?n.push(T(f,`a resource does not depend on itself: take ${a} out of its dependsOn`)):u in e.resources?l.includes(u)||l.push(u):n.push(T(f,`"${u}" is no resource of this file: name one of ${t.join(", ")}`))}),r.set(a,l)}if(n.length>0)return{refusals:n};let s=yb(t,r);if(s!==void 0)return{refusals:[T(["resources",s[0]??""],`the resources depend on each other in a circle, ${s.join(" \u2192 ")}: no order applies them. Take one of them out of the dependsOn of the next, or out of what its relations draw their parents from.`)]};let i=[],o=new Set;for(;i.length<t.length;){let a=t.find(c=>!o.has(c)&&(r.get(c)??[]).every(l=>o.has(l)));if(a===void 0)break;i.push(a),o.add(a)}return{order:i}}function gb(e){let t=[];for(let[n,r]of Object.entries(e))if(r.kind==="seed")for(let s of r.draws??[]){let i=e[s.from];if(i?.kind==="mask"){t.push(T(["resources",n,"relations",s.at,"parents","from"],`${s.from} is a mask resource, which creates no record: a relation draws its parents from the records a seed, a forge or a frozen resource created`));continue}if(i?.kind!=="seed")continue;let o=It(i).map(({object:a})=>a);o.includes(s.relation.parentObject)||t.push(T(["resources",n,"relations",s.at,"parents","from"],`${s.from} writes no ${s.relation.parentObject} records: it writes ${o.join(", ")||"none"}`))}return t}function yb(e,t){let n=new Set,r=[],s=i=>{let o=r.indexOf(i);if(o>=0)return[...r.slice(o),i];if(!n.has(i)){r.push(i);for(let a of t.get(i)??[]){let c=s(a);if(c!==void 0)return c}r.pop(),n.add(i)}};for(let i of e){let o=s(i);if(o!==void 0)return o}}function pa(e,t){return mi(Et({...Hu(e),dependsOn:t}))}var eh=/^[^-\s][^\s]{0,199}$/;function ha(e,t,n={}){let r=Object.keys(e.file.orgs),s=[],i=n.aliases??{};for(let[d,f]of Object.entries(i))r.includes(d)?eh.test(f)||s.push(T(["orgs",d,"alias"],`--alias ${d}= gives no alias: one holds no space and does not start with "-"`)):s.push(T(["orgs"],`--alias names the role ${d}, which the file's orgs do not declare: `+(r.length>0?`its roles are ${r.join(", ")}`:"it declares none")));let o={};for(let[d,{alias:f}]of Object.entries(e.file.orgs)){let g=i[d];if(g!==void 0){o[d]=g;continue}if(typeof f=="string"){o[d]=f;continue}let y=(t[f.env]??"").trim();y===""?s.push(T(["orgs",d,"alias"],`the variable ${f.env} is not set: set it in the job's environment to the alias of the ${d} org, or give --alias ${d}=<alias>`)):eh.test(y)?o[d]=y:s.push(T(["orgs",d,"alias"],`the variable ${f.env} holds no alias: one holds no space and does not start with "-"`))}let a={};for(let[d,f]of Object.entries(e.file.resources)){if(f.kind!=="frozen")continue;let g=wb(d,f.dataset.path,t,e.folder);"refusal"in g?s.push(g.refusal):a[d]=g.dir}if(s.length>0)return{refusals:s};let c={},l=[];for(let d of e.order){let f=e.runs[d],g=e.file.resources[d];if(f===void 0||g===void 0)continue;let y=fa(d,g),m;if(f.kind==="seed"){let{kind:h,...w}=f;m={name:d,kind:h,dependsOn:y,fingerprint:"",run:w}}else if(f.kind==="mask"){let{kind:h,...w}=f;m={name:d,kind:h,dependsOn:y,fingerprint:"",run:w}}else if(f.kind==="frozen"){let{kind:h,...w}=f,v=n.datasets?.[d];m={name:d,kind:h,dependsOn:y,fingerprint:"",run:w,dataset:{dir:a[d]??"",...v!==void 0?{read:v}:{}}}}else{let{kind:h,...w}=f,v=n.sources?.[d];m={name:d,kind:h,dependsOn:y,fingerprint:"",run:w,source:{role:w.source,alias:o[w.source]??"",...v!==void 0?{read:v}:{}}}}m.fingerprint=pa(m,Object.fromEntries(y.map(h=>[h,c[h]]))),c[d]=m.fingerprint,l.push(m)}let u=mi(Et({...e.file,orgs:Object.fromEntries(Object.entries(o).map(([d,f])=>[d,{alias:f}]))}));return{resolved:{checked:e,orgs:o,resources:l,digest:u}}}function wb(e,t,n,r){let s=["resources",e,"dataset","path"],i;if(typeof t=="string")i=t;else{if(i=(n[t.env]??"").trim(),i==="")return{refusal:T(s,`the variable ${t.env} is not set: set it in the job's environment to the folder the dataset of ${e} was downloaded to`)};if(!db(i))return{refusal:T(s,`the variable ${t.env} holds ${i}, which is not a path from the root: give the folder of the dataset from the root`)}}let o;try{o=cr(r)}catch{o=void 0}return o!==void 0&&new Oe(o).isInsideRepo(Wn(i))?{refusal:T(s,`the dataset of ${e}, ${Wn(i)}, is inside the repository ${o} that holds the file: a frozen dataset is pseudonymized business data, and stays outside the project. Keep it where the pipeline downloads it, and name that folder.`)}:{dir:Wn(i)}}function sh(e,t,n,r={}){let s=Jn(e,t,r.now?{now:r.now}:{});return"refusals"in s?s:ha(s.checked,n,{...r.aliases?{aliases:r.aliases}:{},...r.sources?{sources:r.sources}:{},...r.datasets?{datasets:r.datasets}:{}})}var oh=new Set(["create","replace","delete"]),Ie=new Set(["create","replace"]);function wa(e){return oh.has(e.action)}function De(e){return Object.entries(e?.resources??{}).filter(([,t])=>t.status!=="destroyed")}function va(e,t){let n=[],r=new Set,s=new Set(e);for(;n.length<e.length;){let i=e.find(o=>!r.has(o)&&t(o).every(a=>!s.has(a)||r.has(a)||a===o))??e.find(o=>!r.has(o));if(i===void 0)break;n.push(i),r.add(i)}return n}function rt(e,t){let n=e?.resources??{};return va(t,r=>n[r]?.dependsOn??[]).reverse()}function vb(e,t){return t===void 0||t.differs||t.unread!==void 0?!1:[...e.objects.values()].every(n=>n.gone===0&&n.unread===0)}function ma(e){let t={objects:new Map,changedBy:new Map,refusals:[],removalAlone:[],codes:new Map,failed:[],verified:[]};for(let n of e){if("failed"in n){t.failed.push(`run ${n.n}: ${n.failed}`);continue}if("nothing"in n)continue;let r=n.refreshed;r!==void 0&&"unread"in r?t.failed.push(`run ${n.n}: its verification did not say (${r.unread})`):r!==void 0&&t.verified.push(...r.failed);let{preview:s}=n.preview;for(let i of s.objects){let o=t.objects.get(i.objectApiName)??{present:0,gone:0,changed:0,unread:0};o.present+=i.toDelete+i.keptChanged+i.undeletable,o.gone+=i.alreadyGone+i.notVisible,o.changed+=i.changedSince,o.unread+=i.unread,t.objects.set(i.objectApiName,o);for(let[a,c]of Object.entries(i.changedBy)){let l=s.userNames[a]??a;t.changedBy.set(l,(t.changedBy.get(l)??0)+c)}}for(let i of n.preview.refusals)t.refusals.includes(i)||t.refusals.push(i);if(ih(t.codes,n.preview.refusals,n.preview.refusalCodes),"removalAlone"in n.preview){t.removalAlone.push(...n.preview.removalAlone);let i="removalAloneCodes"in n.preview?n.preview.removalAloneCodes:void 0;ih(t.codes,n.preview.removalAlone,i)}}return t}function ih(e,t,n){n?.length===t.length&&t.forEach((r,s)=>e.set(r,n[s]??""))}function ka(e){return[...e.refusals,...e.removalAlone]}function ga(e,t=ka(e)){return[...new Set(t.flatMap(n=>e.codes.get(n)||[]))]}function Ps(e){return e.length>0?{refusalCodes:[...new Set(e)]}:{}}function ya(e){return[...e.objects].map(([t,n])=>({object:t,present:n.present,gone:n.gone,changed:n.changed}))}function kb(e){let t=[...e.objects].flatMap(([s,i])=>{let o=[i.gone>0?`${i.gone} gone`:"",i.changed>0?`${i.changed} changed`:"",i.unread>0?`${i.unread} not read`:""].filter(Boolean);return o.length>0?[`${s} ${o.join(", ")}`]:[]});if(e.verified.length>0&&t.push(`its verification: ${e.verified.join("; ")}`),t.length===0)return;let n=[...e.changedBy].sort((s,i)=>i[1]-s[1]),r=n.length>0?` (last changed by ${n.map(([s,i])=>`${s} ${i}`).join(", ")})`:"";return`${t.join("; ")}${r}`}var bb="its state was recovered from its run files, which do not say what it was applied from",Eb={applying:"its last run was stopped part way: what it wrote is taken back from its run file, then it runs again",partial:"its last run was partial: the org refused records of it, or kept some of its records",failed:"its last run failed",destroying:"a removal of it was stopped part way"};function Sb(e){if(e.kind==="frozen"){let n=e.dataset.read;return n===void 0?`its dataset at ${e.dataset.dir} was not read: plan again`:"refusal"in n?n.refusal:void 0}if(e.kind!=="forge")return;let t=e.source.read;return t===void 0?`its source, the ${e.source.role} org, was not read: plan again`:"refusal"in t?t.refusal:void 0}function ba(e){let{resolved:t,state:n,previews:r}=e,s=r===void 0,i=new Set(e.replace??[]),o=new Map(De(n)),a=new Set(t.resources.map(u=>u.name)),c=new Map;for(let u of t.resources){let d=o.get(u.name),f=Sb(u),g=u.kind;if(d===void 0){c.set(u.name,{resource:u.name,kind:g,action:"create",why:n?.resources[u.name]?.status==="destroyed"?"taken back by an earlier destroy: applied again":"not applied to this org yet",objects:[],...f!==void 0?{refusal:f}:{}});continue}let y=ma(r?.[u.name]??[]),m=[],h=pa(u,Object.fromEntries(u.dependsOn.map(j=>[j,n?.resources[j]?.fingerprint])));d.recovered===!0?m.push(bb):d.fingerprint!==u.fingerprint&&d.fingerprint!==h&&m.push("what it writes changed in the file since it was applied");let w=(g==="mask"?Su:Eb)[d.status];w!==void 0&&m.push(w);let v=u.dependsOn.filter(j=>{let D=c.get(j);return D!==void 0&&Ie.has(D.action)&&D.kind!=="mask"});if(v.length>0&&m.push(`the resources it depends on run again, with new records: ${v.join(", ")}`),i.has(u.name)&&m.push("--replace asks it"),g==="mask"){c.set(u.name,Rb(u.name,d,m,e,s));continue}let k=s?void 0:kb(y),b=k!==void 0&&vb(y,e.drift),S=b?void 0:k;m.length===0&&S!==void 0&&e.replaceDrifted===!0&&m.push(`its records drifted (${S}), and --replace-drifted asks it`);let $=ya(y),E=f??(y.refusals.length>0?`a removal of its runs would be refused now: ${y.refusals.join(" ")}`:y.failed.length>0?`what the org holds of it could not be read (${y.failed.join("; ")}): plan again`:void 0),R=f===void 0&&y.refusals.length>0?ga(y,y.refusals):[];if(m.length>0)c.set(u.name,{resource:u.name,kind:g,action:"replace",why:`replaced: ${m.join("; ")}`,objects:$,...E!==void 0?{refusal:E,...Ps(R)}:{}});else if(s)c.set(u.name,{resource:u.name,kind:g,action:"keep",why:"applied from the same file; what the org holds of it was not read (--quick)",objects:$,...f!==void 0?{refusal:f}:{}});else if(f!==void 0||y.failed.length>0)c.set(u.name,{resource:u.name,kind:g,action:"keep",why:"applied from the same file",objects:$,refusal:f??`what the org holds of it could not be read (${y.failed.join("; ")}): plan again`});else if(S!==void 0)c.set(u.name,{resource:u.name,kind:g,action:"drifted",why:`its records changed since it was applied: ${S}. Left as they are: --replace ${u.name} or --replace-drifted replaces it`,objects:$});else{let j=$.reduce((N,P)=>N+(P.present??0),0),D=$.reduce((N,P)=>N+(P.changed??0),0);c.set(u.name,{resource:u.name,kind:g,action:"keep",why:b?`applied, and the org holds its ${j} record(s) as the checkpoint taken after the apply holds them: ${D} written since hold their values again, as a reset gives them back`:`applied, and the org holds its ${j} record(s) as written`,objects:$})}}return[...rt(n,[...o.keys()].filter(u=>!a.has(u))).map(u=>{let d=o.get(u);if(d?.kind==="mask")return{resource:u,kind:"mask",action:"delete",why:$i("apply",u,d,Ea(e,u)),objects:ah(d)};let f=ma(r?.[u]??[]),g=ka(f),y=g.length>0?`a removal of its runs would be refused now: ${g.join(" ")}`:f.failed.length>0?`what the org holds of it could not be read (${f.failed.join("; ")}): plan again`:void 0;return{resource:u,kind:o.get(u)?.kind??"seed",action:"delete",why:"in the state, gone from the file: its records are taken back",objects:ya(f),...y!==void 0?{refusal:y,...Ps(g.length>0?ga(f):[])}:{}}}),...t.resources.flatMap(u=>c.get(u.name)??[])]}function Rb(e,t,n,r,s){let i=(c,l,u=[],d)=>({resource:e,kind:"mask",action:c,why:l,objects:u,...d!==void 0?{refusal:d}:{}});if(n.length>0)return i("replace",`replaced: ${n.join("; ")}; ${Ri(t)}`);if(s)return i("keep","applied from the same file; what the org holds of it was not read (--quick)");if(r.dryRuns===void 0)return i("keep","applied from the same file");let o=r.dryRuns[e];if(o===void 0)return i("keep","applied from the same file",[],"it was not dry-run: plan again");if("failed"in o||o.answer.tool!==se){let c="failed"in o?o.failed:`${Pe(o.answer.tool)} answered its dry run`;return i("keep","applied from the same file",[],`what the org holds of it could not be read (its dry run: ${c}): plan again`)}let a=vu(t,o.answer);return a.unread!==void 0?i("keep","applied from the same file",a.objects,`what the org holds of it could not be read: ${a.unread}`):a.drift===void 0?i("keep",Ru(a.masked),a.objects):r.replaceDrifted===!0?i("replace",`replaced: its condition selects other records than it masked (${a.drift}), and --replace-drifted asks it; ${Ri(t)}`,a.objects):i("drifted",$u(e,a.drift),a.objects)}function Ea(e,t){let n=e.maskStores?.[t],r=e.org??e.state?.org;return{alias:r?.alias??r?.organizationId??"<alias>",...n!==void 0?{store:n}:{}}}function ah(e){return(e.runs.at(-1)?.objects??[]).map(t=>({object:t.objectApiName,present:t.masked??0}))}function $b(e,t){let n=new Set(t.filter(i=>Ie.has(i.action)).map(i=>i.resource)),r=new Set(t.filter(i=>Ie.has(i.action)&&i.kind!=="mask").map(i=>i.resource)),s=new Map;for(let i of e.resources){if(!n.has(i.name))continue;let o=i.dependsOn.filter(a=>r.has(a));o.length>0&&s.set(i.name,o)}return s}function Ab(e,t){let n=e.map(r=>({...r}));for(let r of t.objects){let s={wouldCreate:r.wouldCreate,...r.atMost===!0?{atMost:!0}:{}},i=n.find(o=>o.object===r.object);i?Object.assign(i,s):n.push({object:r.object,...s})}return n}function Ob(e,t,n,r){let s=e.resources.find(c=>c.name===t),i=r&&s!==void 0?Oi(s):void 0,o=Tt(n,i),a=s!==void 0?td(s,n):void 0;return{count:a!==void 0&&o.refusal===void 0?{...o,refusal:a}:o}}function Cb(e,t){let n=e.resources.find(r=>r.name===t);return n!==void 0&&(Oi(n)?.size??0)>0}function jb(e,t,n){let r=e.resources.find(i=>i.name===t);if(r?.kind!=="seed")return[];let s=new Set((r.run.draws??[]).map(i=>i.from));return n.filter(i=>s.has(i))}function Sa(e){return e!==void 0&&"answer"in e?Tt(e.answer).total:void 0}function Nb(e,t){let n=[],{apiRequests:r,storage:s,emails:i}=e;r.leftToday!==void 0&&r.estimate>r.leftToday&&n.push(`The resources the plan writes take about ${r.estimate} API requests, and ${t} has ${r.leftToday} left today: the apply would stop part way. Apply once the org has requests to spare \u2014 the limit is counted over the last 24 hours \u2014 or write fewer records.`),s.left!==void 0&&s.bytes>s.left&&n.push(`The resources the plan writes take about ${at(s.bytes/1048576)} MB of data storage, and ${t} has ${at(s.left/1048576)} MB left: the org would refuse records part way. Write fewer records, or free storage first.`);for(let o of i)o.left!==void 0&&o.emails>o.left&&n.push(`The resources the plan writes make ${t} send ${o.emails} ${o.limit} emails, and it has ${o.left} left today: each resource alone may fit, the day does not. Apply the resources over two days, or keep the automation that sends them quiet.`);return n}function Ib(e,t,n,r,s){let i=s.estimate,o=0,a=new Map,c=[...s.notCounted];for(let f of e){if((f.action==="delete"||f.action==="replace")&&f.kind!=="mask"&&c.push(`the removal of the runs of ${f.resource}`),!Ie.has(f.action))continue;let g=t?.[f.resource];if(g===void 0||"failed"in g){c.push(`the run of ${f.resource}, not dry-run`);continue}let y=r.get(f.resource);y!==void 0&&f.kind!=="mask"&&c.push(`what ${f.resource} draws from the records ${y.join(", ")} writes first`);let m=Tt(g.answer);m.apiRequests===void 0?c.push(`the requests of the run of ${f.resource}, which its script does not estimate`):i+=m.apiRequests,o+=m.storageBytes;for(let{limit:h,emails:w}of m.emails)a.set(h,(a.get(h)??0)+w)}let l=n?.apiRequests,u=n?.storage,d=n?.emails;return{apiRequests:{estimate:i,...l!==void 0&&!("unread"in l)?{leftToday:l.remaining}:{},partial:c.length>0,...c.length>0?{notCounted:c}:{},...l!==void 0&&"unread"in l?{unread:l.unread}:{},...n===void 0?{unread:"not read: --quick"}:{}},storage:{bytes:o,...u!==void 0&&!("unread"in u)?{left:Math.floor(u.remainingMB*1048576)}:{},...u!==void 0&&"unread"in u?{unread:u.unread}:{},...n===void 0?{unread:"not read: --quick"}:{}},emails:[...a].map(([f,g])=>{let y=d!==void 0&&!("unread"in d)?d[f]?.remaining:void 0;return{limit:f,emails:g,...y!==void 0?{left:y}:{}}})}}function Ra(e){let t=e.previews===void 0,n=ba(e),r=$b(e.resolved,n),s=n.map(h=>{let w=h.objects,v,k=h.refusal,b=h.refusal!==void 0?h.refusalCodes??[]:[],S=Ie.has(h.action)?e.dryRuns?.[h.resource]:void 0,$=r.get(h.resource),E=$!==void 0&&Cb(e.resolved,h.resource),R=Ie.has(h.action)?e.draws?.[h.resource]:void 0;R!==void 0&&R.refusals.length>0&&(k??=R.refusals.join(" "));let j=[];if(S!==void 0&&"failed"in S)S.refused!==void 0&&k===void 0&&(k=`its own dry run says a real run would be refused: ${S.refused.message}`,b=[S.refused.code]),k??=`its dry run did not answer: ${S.failed}`;else if(S!==void 0){let O=Ob(e.resolved,h.resource,S.answer,$!==void 0);w=Ab(w,O.count),v={...O.count.apiRequests!==void 0?{apiRequests:O.count.apiRequests}:{},storageBytes:O.count.storageBytes,emails:O.count.emails};let q=O.count.refusal;q!==void 0&&k===void 0&&(k=`its own dry run says a real run would be refused: ${q}`,b=O.count.refusalCodes??[]),j=O.count.notes??[]}else Ie.has(h.action)&&!t&&(k??="it was not dry-run: plan again");let D=$!==void 0?jb(e.resolved,h.resource,$):[],N=$!==void 0&&S!==void 0&&h.kind==="mask"?`; its dry run read the org before ${$.join(", ")} writes: what they write under its condition it masks too, uncounted here`:$!==void 0&&S!==void 0&&E?D.length>0?`; it draws its parents from the records ${D.join(", ")} creates in this apply, which nobody knows before it runs: counted at most as the file gives it`:`; its dry run read the org before ${$.join(", ")} writes: what it draws from those records is counted at most as the file gives it`:"",P=`${h.why}${N}${j.length>0?`; ${j.join("; ")}`:""}`,le=e.resolved.resources.find(O=>O.name===h.resource),me=le!==void 0&&Ie.has(h.action)?ld(le,Ea(e,h.resource)):[];return{resource:h.resource,kind:h.kind,action:k!==void 0?"blocked":h.action,why:P,objects:w,...R!==void 0&&R.draws.length>0?{draws:R.draws}:{},...v!==void 0?{gates:v}:{},...k!==void 0?{refusal:k,...Ps(b)}:{},...me.length>0?{notes:me}:{}}}),i=e.resolved.checked.file,o=Xc(br(i,e.state,n.some(h=>oh.has(h.action))),t?void 0:e.checkpointEstimate??{unread:"not estimated"},s.filter(h=>Ie.has(h.action)&&h.kind!=="mask").flatMap(h=>h.objects).reduce((h,w)=>h+(w.wouldCreate??0),0)),a=Ib(n,e.dryRuns,e.budget,r,el(o)),c=e.org.alias??e.org.organizationId,l=Nb(a,c);if(l.length>0)for(let h of s)wa(h)&&(h.refusal=l.join(" "),h.action="blocked");let u=s.filter(h=>h.action==="blocked"),d=e.refusal??(l.length>0?`${l.join(" ")} Nothing was written.`:u.length>0?`${u.length===1?"A resource is":`${u.length} resources are`} blocked, and the apply refuses before its first write: ${u.map(h=>`${h.resource} (${h.refusal??h.why})`).join("; ")}`:void 0)??Zc(o),f=e.refusal!==void 0?[...e.refusalCodes??[]]:l.length>0?[]:u.length>0?u.flatMap(h=>h.refusalCodes??[]):o.flatMap(h=>h.refusal!==void 0?[h.refusal.code]:[]),g=[...e.warnings??[],...Hc(i,e.state)],y=h=>s.filter(w=>w.action===h).length,m=e.state;return{env:e.resolved.checked.file.name,org:e.org,state:m!==void 0?{found:!0,serial:m.serial}:{found:!1},actions:s,totals:{create:y("create"),keep:y("keep"),replace:y("replace"),delete:y("delete"),drifted:y("drifted"),blocked:y("blocked")},gates:a,...o.length>0?{checkpoints:o}:{},...e.drift!==void 0?{drift:e.drift}:{},...d!==void 0?{refusal:d,...Ps(f)}:{},...t?{quick:!0}:{},...g.length>0?{warnings:g}:{}}}function ch(e){let n=rt(e.state,De(e.state).map(([a])=>a)).map(a=>{let c=e.state?.resources[a];if(c?.kind==="mask")return{resource:a,kind:"mask",action:"delete",why:$i("destroy",a,c,Ea(e,a)),objects:ah(c)};let l=ma(e.previews?.[a]??[]),u=ka(l),d=u.length>0?`a removal of its runs would be refused now: ${u.join(" ")}`:l.failed.length>0?`what the org holds of it could not be read (${l.failed.join("; ")}): run destroy again`:void 0,f=u.length>0?ga(l):[];return{resource:a,kind:c?.kind??"seed",action:d!==void 0?"blocked":"delete",why:"taken back by destroy, into the recycle bin",objects:ya(l),...d!==void 0?{refusal:d}:{},...f.length>0?{refusalCodes:f}:{}}}),r=n.filter(a=>a.action==="blocked"),s=[...new Set(r.flatMap(a=>a.refusalCodes??[]))],i=n.filter(a=>a.kind!=="mask").map(a=>`the removal of the runs of ${a.resource}`),o=e.state;return{env:e.resolved.checked.file.name,org:e.org,state:o!==void 0?{found:!0,serial:o.serial}:{found:!1},actions:n,totals:{create:0,keep:0,replace:0,delete:n.length-r.length,drifted:0,blocked:r.length},gates:{apiRequests:{estimate:0,partial:i.length>0,...i.length>0?{notCounted:i}:{}},storage:{bytes:0},emails:[]},...r.length>0?{refusal:`${r.map(a=>`${a.resource}: ${a.refusal??""}`).join(" ")} Nothing was deleted.`,...s.length>0?{refusalCodes:s}:{}}:{},...e.previews===void 0?{quick:!0}:{},...e.warnings!==void 0&&e.warnings.length>0?{warnings:[...e.warnings]}:{}}}function $a(e){return e.actions.some(t=>t.action!=="keep"&&t.action!=="drifted")}function lh(e){let t=e.drift;if(t!==void 0&&(t.differs||t.unread!==void 0))return!0;let n=t!==void 0;return e.actions.some(r=>r.action==="drifted"||!(n&&r.action==="keep")&&r.objects.some(s=>(s.gone??0)>0||(s.changed??0)>0))}function Aa(e){let t=e.kind==="mask";return e.objects.map(n=>{let r=[n.wouldCreate!==void 0?`${n.atMost===!0?"at most ":""}${n.wouldCreate} `+(t?"to mask":"to write"):"",n.present!==void 0&&n.present>0?`${n.present} ${t?"masked":"in the org"}`:"",(n.gone??0)>0?`${n.gone} gone`:"",(n.changed??0)>0?`${n.changed} changed`:""].filter(Boolean);return r.length>0?`${n.object} ${r.join(", ")}`:""}).filter(Boolean).join("; ")}var Db={apply:"an apply now",destroy:"a destroy now"};function Ls(e,t="apply"){let n=[`plan of ${e.env} on ${e.org.alias??e.org.organizationId} (${e.org.kind}, ${e.org.organizationId})`,e.state.found?`state: kept on this machine, serial ${e.state.serial??0}`:"state: none on this machine"];for(let c of e.actions){let l=Aa(c);n.push(` ${c.action.padEnd(8)} ${c.resource}${l?` ${l}`:""}`),n.push(` ${c.why}`);for(let u of c.draws??[])n.push(` ${u.lookup} draws its parents from `+(u.parents!==void 0?`the ${u.parents} ${u.object} record(s) ${u.from} created`:`the ${u.object} records ${u.from} creates first`));for(let u of c.notes??[])n.push(` ${u}`);c.refusal!==void 0&&n.push(` refused: ${c.refusal}`)}let{totals:r}=e;n.push(`totals: ${r.create} to create, ${r.replace} to replace, ${r.delete} to delete, ${r.keep} kept, ${r.drifted} drifted, ${r.blocked} blocked`);let{apiRequests:s,storage:i,emails:o}=e.gates,a=(c,l)=>c!==void 0?`, ${c} left`:l!==void 0?` (left: ${l})`:"";n.push(`API requests: about ${s.estimate}`+a(s.leftToday?.toString(),s.unread)+(s.partial?`; not counted: ${(s.notCounted??[]).join(", ")}`:"")),n.push(`data storage: about ${at(i.bytes/1048576)} MB`+a(i.left!==void 0?`${at(i.left/1048576)} MB`:void 0,i.unread));for(let c of o)n.push(`emails (${c.limit}): ${c.emails}`+(c.left!==void 0?`, ${c.left} left today`:""));n.push(...nl(e));for(let c of e.warnings??[])n.push(`warning: ${c}`);return e.refusal!==void 0&&n.push(`${Db[t]} would be refused: ${e.refusal}`),n}import{existsSync as Oa,readFileSync as Ca}from"node:fs";import{join as Tb}from"node:path";function Fs(e){return e.slice(0,15)}function xs(e){let t=new Map,n=new Set;for(let{objectApiName:r,ids:s}of e){let i=t.get(r)??[];for(let o of s)n.has(Fs(o))||(n.add(Fs(o)),i.push(o));t.set(r,i)}return t}function Pb(e,t,n){let r=e.runId!==void 0?Tb(n.journalDir,Ae,`${e.runId}.ndjson`):void 0;if(r!==void 0&&Oa(r)){let o=fc(Ca(r,"utf8"));if(o!==void 0)return{created:xs(o.created)}}if(e.summary===void 0)return{refusal:"its run keeps no record of what it created"};let s=n.store.fileOf(t.organizationId,t.env,e.summary);if(!Oa(s))return{refusal:"its run keeps no record of what it created"};let i=Nt(Ca(s,"utf8"));return i.result.objectResults.some(o=>o.truncated===!0)?{refusal:"its summary names the first of the records it created alone, and its run file is gone"}:{created:xs(i.result.objectResults.map(o=>({objectApiName:o.objectApiName,ids:o.createdIds})))}}async function Lb(e,t,n){if(e.summary===void 0)return{refusal:"its run keeps no summary"};let r=n.store.fileOf(t.organizationId,t.env,e.summary);if(!Oa(r))return{refusal:"its run keeps no summary"};let s=await ar(r,Ca(r,"utf8"),t.target,ir(n.journalDir));if("refusal"in s)return{refusal:`its summary ${s.refusal}`};let{result:i}=s.summary,o=Xa({idRemapTable:i.remapTable,idRemapExisting:[...i.existingSourceIds,...i.updatedSourceIds],idRemapCreated:i.createdByObject});return{created:xs([...o].reverse().map(a=>({objectApiName:a.objectApiName,ids:[...a.ids].reverse()})))}}async function Fb(e,t,n){if(Nr(e.sas)===void 0||e.sas===void 0)return{refusal:"its run names no sas"};let r=n.store.sasOf(t.organizationId,t.env,e.sas),s=new Oe,i=(await Xt(r,s)).find(c=>Fs(c)===Fs(t.organizationId));if(i===void 0)return{refusal:"its sas holds no mapping of a load into this org"};let o=await new lr(r,{orgId:i,guard:s}).recorded();if(o?.created===void 0)return{refusal:"its sas holds no load that says which records it created"};let a=Pc(o);return{created:xs([...a].reverse().map(c=>({objectApiName:c.objectApiName,ids:[...c.ids].reverse()})))}}async function ja(e,t,n,r){let s=e?.resources[t];if(s===void 0||s.status==="destroyed")return{refusal:`${t} has not created its records in this org yet`};if(s.status!=="applied")return{refusal:`${t} is ${s.status}, not applied whole: apply it again first`};let i=s.runs.at(-1);if(i===void 0||i.takenBack===!0)return{refusal:`${t} holds no run whose records are in the org`};let o=await Na(i,n,r);return"refusal"in o?{refusal:`${t}: ${o.refusal}`}:o}async function Na(e,t,n){switch(e.script){case"sandforge-seed":return Pb(e,t,n);case"sandforge-clone":return Lb(e,t,n);case"sandforge-frozen":return Fb(e,t,n);default:return{refusal:`its records are kept by ${Pe(e.script)}, which this SandForge reads not`}}}function xb(e,t){let n=e.relation.parentObject,r=`${e.relation.childObject}.${e.relation.lookupField}`,s=[...t.get(n)??[]],i=tr.maxExistingParents;if(s.length===0){let o=[...t.keys()].filter(a=>(t.get(a)??[]).length>0);return{refusal:`the relation on ${r} draws its parents from the ${n} records ${e.from} created, and it created none: it created ${o.join(", ")||"no record"}`}}return e.limit!==void 0?{ids:s.slice(0,e.limit)}:s.length>i?{refusal:`the relation on ${r} draws its parents from the ${s.length} ${n} records ${e.from} created, more than the ${i} a relation's parents hold: give the relation a limit, and its parents are the first ${i} or fewer`}:{ids:s}}async function Ms(e,t,n,r,s){let i={ids:new Map,draws:[],refusals:[]};if(e.kind!=="seed")return i;let o=new Map;for(let a of e.run.draws??[]){let c={lookup:`${a.relation.childObject}.${a.relation.lookupField}`,from:a.from,object:a.relation.parentObject};if(n.has(a.from)){i.draws.push(c);continue}let l=o.get(a.from);if(l===void 0&&(l=await ja(t,a.from,r,s),o.set(a.from,l)),"refusal"in l){i.draws.push(c),i.refusals.push(`the relation on ${c.lookup} draws its parents from ${a.from}, whose records cannot be read: ${l.refusal}`);continue}let u=xb(a,l.created);if("refusal"in u){i.draws.push(c),i.refusals.push(u.refusal);continue}i.ids.set(a.at,u.ids),i.draws.push({...c,parents:u.ids.length})}return i}function pe(e){return sc.some(t=>be(t)===e)}function dh(e,t,n){let r=e===0||e===3||e===4||pe(e),s=t??(r?void 0:Uc(n));return s!==void 0&&s!==""?s.slice(0,4e3):void 0}function _b(e){return Ci(e).map(t=>{let n=[t.keptChanged>0?`${t.keptChanged} changed since the run, kept`:"",t.keptDependents>0?`${t.keptDependents} kept for records that stay (${t.heldBy.join(", ")||"records that stay"})`:"",t.refused>0?`${t.refused} refused`:"",(t.notVisible??0)>0?`${t.notVisible} not visible to the user`:"",(t.notReached??0)>0?`${t.notReached} not reached`:"",...t.reasons].filter(Boolean);return{object:t.objectApiName,created:0,refused:t.refused,deleted:t.deleted,kept:t.keptChanged+t.keptDependents+t.refused,...n.length>0?{reason:n.join("; ").slice(0,2e3)}:{}}})}function qb(e){return(e?.objects??[]).map(t=>({object:t.object,created:t.created,refused:t.refused,deleted:0,kept:0,...t.errors.length>0?{reason:t.errors.slice(0,5).join("; ").slice(0,2e3)}:{}}))}function zb(e){try{return typeof JSON.parse(e)?.refused?.code=="string"}catch{return!1}}function gt(e,t,n){if(!(t.trim()===""||zb(t)))try{return e(t)}catch(r){if(r instanceof re){n(` ${r.message}`);return}throw r}}function Ia(e,t,n){let r=Nr(e.sas);if(r!==void 0){let s=n.store.fileOf(t.organizationId,t.env,kt(r,e.n));return Yn(s)?s:void 0}if(e.summary!==void 0){let s=n.store.fileOf(t.organizationId,t.env,e.summary);if(Yn(s))return s}if(e.runId!==void 0&&Yn(uh(n.journalDir,Ae,`${e.runId}.ndjson`)))return e.runId}async function Da(e,t,n,r){let s={organizationId:t.org.organizationId,env:t.env},i=t.resources[n.resource];if(i===void 0)throw new L("invalid",`The state holds no resource ${n.resource} to take back`);if(i.kind==="mask")return Bb(e,t,n);let o=await e.store.update(t,u=>fi(u,n.resource)),a=[],c=!1,l=!1;for(let u of[...i.runs].reverse()){if(u.takenBack===!0)continue;let d=Ia(u,s,e);if(d===void 0)continue;e.say(`${n.resource}: taking back run ${u.n}`);let f=ad(i.kind,{target:n.target.alias,subject:d,includeChanged:n.includeChanged,acceptAutomation:n.acceptAutomation,sweep:n.sweep}),g=await e.runner(f.script,f.args,r),y=gt(b=>cd(i.kind,b),g.stdout,e.say),m=Ci(y).reduce((b,S)=>b+S.deleted,0);l||=y!==void 0?m>0:g.code!==1&&g.code!==2;let h=pe(g.code),w=g.code===0||g.code===3,v=h?"destroying":w?g.code===3?n.ends.left:n.ends.whole:i.status,k=dh(g.code,void 0,g.stderr);if(a.push({resource:n.resource,action:n.action,phase:"remove",run:u.n,script:f.script,exitCode:g.code,status:v,...u.summary!==void 0?{summary:u.summary}:{},objects:_b(y),...y!==void 0?{answer:y}:{},...k!==void 0?{refusal:k}:{}}),g.code===3&&(c=!0),g.code===0&&(o=await e.store.update(o,b=>yr(b,n.resource,u.n))),!w)return h||(o=await e.store.update(o,b=>bt(b,{resource:n.resource,status:i.status}))),{whole:!1,code:h?g.code:1,wrote:l,steps:a,state:o}}return o=await e.store.update(o,u=>bt(u,{resource:n.resource,status:c?n.ends.left:n.ends.whole})),{whole:!c,code:c?3:0,wrote:l,steps:a,state:o}}async function Bb(e,t,n){let r=t.resources[n.resource];if(r===void 0)throw new L("invalid",`The state holds no resource ${n.resource} to take back`);let s=await e.store.update(t,u=>fi(u,n.resource)),i=e.store.sasOf(t.org.organizationId,t.env,jt(n.resource)),o=r.runs.at(-1),a=(u,d,f)=>({resource:n.resource,action:n.action,phase:"remove",run:o?.n??1,script:"sandforge-dataops",exitCode:d,status:u,objects:(o?.objects??[]).map(g=>({object:g.objectApiName,created:0,refused:0,deleted:0,kept:0,masked:g.masked??0,reason:f}))});e.say(`${n.resource}: deleting its store ${i}`);let c;try{c=await Au(i)}catch(u){let d=u instanceof Error?u.message:String(u);return e.say(`${n.resource}: ${d}`),s=await e.store.update(s,f=>bt(f,{resource:n.resource,status:r.status})),{whole:!1,code:1,wrote:!1,steps:[a(r.status,1,d)],state:s}}e.say(Ou(n.resource,c));for(let u of r.runs)u.takenBack!==!0&&(s=await e.store.update(s,d=>yr(d,n.resource,u.n)));s=await e.store.update(s,u=>bt(u,{resource:n.resource,status:n.ends.whole}));let l=c.snapshots.length>0?`snapshot${c.snapshots.length===1?"":"s"} ${c.snapshots.join(", ")}`:"its store";return{whole:!0,code:0,wrote:!1,steps:[a(n.ends.whole,0,`left masked, as destroy leaves a masking; ${l} deleted`)],state:s}}var Kb=new Set(["sandforge-seed","sandforge-clone","sandforge-dataops","sandforge-frozen"]);function Vt(e,t){return t&&Kb.has(e.script)?{...e,args:[...e.args,"--accept-emails"]}:e}function Ub(e,t){let n=new Map(e.actions.map(o=>[o.resource,o])),r=new Set(De(t).map(([o])=>o)),s=rt(t,e.actions.filter(o=>(o.action==="delete"||o.action==="replace"&&!lt(o.kind))&&r.has(o.resource)).map(o=>o.resource)).map(o=>({phase:"remove",resource:o,action:n.get(o)?.action??"delete"})),i=e.actions.filter(o=>o.action==="create"||o.action==="replace").map(o=>({phase:"run",resource:o.resource,action:o.action}));return[...s,...i]}function fh(e,t,n){if(pe(e))return{status:"applying",counts:e,stops:!0};if(e===0&&t!==void 0){let r=t.created;return n!==void 0&&r!==n?{status:"partial",counts:3,stops:!1,short:`it created ${r} record(s) of the ${n} its dry run counted`}:{status:"applied",counts:0,stops:!1}}return e===3?{status:"partial",counts:3,stops:!1}:e===4?{status:"partial",counts:4,stops:!0}:{status:"failed",counts:1,stops:!0}}function Vb(e,t){return t===void 0?e:e.status==="partial"&&e.short===void 0&&"short"in t?t.short===void 0||t.unstable?e:{...e,short:`its verification found ${t.short}`}:e.status!=="applied"?e:"unread"in t?{...e,short:`not verified: ${t.unread}`}:t.unstable?{status:"partial",counts:4,stops:!0,short:`its verification is unstable: ${t.short??""}`}:t.short===void 0?e:{status:"partial",counts:3,stops:!1,short:`its verification found ${t.short}`}}async function Wb(e,t,n){let{resource:r,n:s,where:i,target:o,templateFile:a,dry:c,signal:l}=n,u=i.env,d=c!==void 0&&"answer"in c?c.answer:void 0,f=d===void 0||n.readTooEarly?void 0:Tt(d).created,g=await e.orgNow();if(r.kind==="seed"){let j=hr(u,r.name,s),D=r.run.seed??(d?.tool==="sandforge-seed"?d.seed:void 0),N=await e.store.update(t,Jt=>tn(Jt,{resource:r.name,kind:"seed",fingerprint:r.fingerprint,dependsOn:r.dependsOn,run:{script:"sandforge-seed",runId:j,...D!==void 0?{seed:D}:{},startedAt:g}})),P=Vt(mn(r,{target:o.alias,templateFile:a,runId:j,summaryFile:"",...D!==void 0?{seed:D}:{}}),n.acceptEmails),le=await e.runner(P.script,P.args,l),me=gt(Nt,le.stdout,e.say),O=me!==void 0?Dr(me):void 0,q=(O?.created??0)>0||Yn(uh(e.journalDir,Ae,`${j}.ndjson`)),te=me!==void 0?await e.store.writeFile(i.organizationId,u,ae(r.name,s),le.stdout).then(()=>ae(r.name,s)):void 0;return{state:N,script:P.script,code:le.code,...O!==void 0?{count:O}:{},...me!==void 0?{answer:me}:{},...te!==void 0?{summary:te}:{},wrote:q,...f!==void 0?{planned:f}:{},...O?.refusal!==void 0?{answered:O.refusal}:{},stderr:le.stderr}}if(r.kind==="frozen")return Jb(e,t,n,g,f);if(r.kind==="mask")return Yb(e,t,n,g);let y=ae(r.name,s),m=await e.store.prepareFile(i.organizationId,u,y),h=await e.store.update(t,j=>tn(j,{resource:r.name,kind:"forge",fingerprint:r.fingerprint,dependsOn:r.dependsOn,run:{script:"sandforge-clone",summary:y,startedAt:g}})),w=Sa(c),v=Vt(mn(r,{target:o.alias,templateFile:a,runId:"",summaryFile:m,...w!==void 0?{maxTotal:w}:{}}),n.acceptEmails),k=await e.runner(v.script,v.args,l),b=Yn(m)?Mb(m,"utf8"):void 0,S=gt(cn,b??"",e.say)??gt(cn,k.stdout,e.say),$=S!==void 0?Or(S):void 0,E=$!==void 0?$.created>0:b!==void 0,R;if(k.code===0&&b!==void 0&&($?.created??0)>0){e.say(`${r.name}: verifying run ${s}`);let j=await e.runner(v.script,jl({summary:m,target:o.alias,source:r.source.alias}),l),D=j.stdout.trim()===""?void 0:gt(Pl,j.stdout,e.say);if(D!==void 0){let N=Fl(D);R={unstable:D.result.verdict==="unstable",...N!==void 0?{short:N}:{}}}else j.code!==0&&(R={unread:`its verification ended ${j.code} without an answer`})}return{state:h,script:v.script,code:k.code,...$!==void 0?{count:$}:{},...S!==void 0?{answer:S}:{},...b!==void 0?{summary:y}:{},wrote:E,...f!==void 0?{planned:f}:{},...R!==void 0?{verified:R}:{},...S?.error!==void 0?{answered:S.error}:{},stderr:k.stderr}}async function Jb(e,t,n,r,s){let{resource:i,n:o,where:a,target:c,templateFile:l,dry:u,signal:d}=n,f=await e.store.update(t,$=>tn($,{resource:i.name,kind:"frozen",fingerprint:i.fingerprint,dependsOn:i.dependsOn,run:{script:"sandforge-frozen",sas:Ve(i.name),startedAt:r}})),g=Sa(u),y=Vt(mn(i,{target:c.alias,templateFile:l,runId:"",summaryFile:"",replace:n.replace,acceptAutomation:n.acceptAutomation,...g!==void 0?{maxTotal:g}:{}}),n.acceptEmails),m=await e.runner(y.script,y.args,d),h=gt(Cr,m.stdout,e.say),w=h!==void 0?pn(h):void 0;w?.refusal!==void 0&&e.say(`${i.name}: ${w.refusal}`);let v=h===void 0?pe(m.code):(w?.created??0)>0||nu(h),k=h!==void 0?await e.store.writeFile(a.organizationId,a.env,ae(i.name,o),m.stdout).then(()=>ae(i.name,o)):void 0,b=h?.verdict,S=b!==void 0?bi(b):m.code===0&&(w?.created??0)>0?{unread:"the load chained no verification"}:void 0;return{state:f,script:y.script,code:m.code,...w!==void 0?{count:w}:{},...h!==void 0?{answer:h}:{},...k!==void 0?{summary:k}:{},wrote:v,...s!==void 0?{planned:s}:{},...S!==void 0?{verified:S}:{},...n.replace&&h!==void 0&&jr(h)?{tookBackEarlier:!0}:{},...w?.refusal!==void 0?{answered:w.refusal}:{},stderr:m.stderr}}async function Yb(e,t,n,r){let{resource:s,n:i,where:o,target:a,templateFile:c,signal:l}=n,u=await e.store.update(t,v=>tn(v,{resource:s.name,kind:"mask",fingerprint:s.fingerprint,dependsOn:s.dependsOn,run:{script:"sandforge-dataops",startedAt:r}})),d=await e.store.prepareFolder(o.organizationId,o.env,jt(s.name)),f=Vt(mn(s,{target:a.alias,templateFile:c,runId:"",summaryFile:"",store:d}),n.acceptEmails),g=await e.runner(f.script,f.args,l),y=gt(Ir,g.stdout,e.say),m=y!==void 0?hn(y):void 0;m?.refusal!==void 0&&e.say(`${s.name}: ${m.refusal}`);let h=m!==void 0?m.objects.some(v=>v.masked>0):pe(g.code),w=y!==void 0?await e.store.writeFile(o.organizationId,o.env,ae(s.name,i),g.stdout).then(()=>ae(s.name,i)):void 0;return{state:u,script:f.script,code:g.code,...y!==void 0?{answer:y}:{},...w!==void 0?{summary:w}:{},wrote:h,...m!==void 0?{masking:m}:{},...m?.refusal!==void 0?{answered:m.refusal}:{},stderr:g.stderr}}function Gb(e,t){let n=fh(e,void 0,void 0);if(e!==0)return n;let r=(t?.objects??[]).reduce((s,i)=>s+i.notMasked,0);return t?.short!==void 0||r>0?{status:"partial",counts:3,stops:!1,short:t?.short??`${r} record(s) still hold their original values: the next apply masks them again`}:{status:"applied",counts:0,stops:!1}}function Hb(e){return(e?.objects??[]).map((t,n)=>({object:t.object,created:0,refused:t.refused,deleted:0,kept:0,masked:t.masked,...n===0&&e?.snapshotId!==void 0?{reason:`snapshot ${e.snapshotId} of the values it wrote over, taken first, kept on this machine until destroy deletes it`}:{}}))}async function Qb(e,t,n,r,s){if(n.kind==="frozen"){let o=await e.store.prepareFolder(r.organizationId,r.env,Ve(n.name));return{payload:Dt(n,{sasDir:o})}}if(n.kind!=="seed"||(n.run.draws??[]).length===0)return{payload:Dt(n,{})};let i=await Ms(n,t,new Set,{...r,target:s.alias},{store:e.store,journalDir:e.journalDir});return i.refusals.length>0?{refusal:i.refusals.join(" ")}:{payload:Dt(n,{drawn:i.ids})}}function qs(e){return e===0?"success":pe(e)?"cancelled":e===1?"failure":"partial"}async function ph(e,t){let{plan:n,target:r,resolved:s}=t,i=s.checked.file.name,o=(y,m=t.state,h=[])=>({result:{plan:n,steps:[],status:"failure",refusal:y,...h.length>0?{refusalCodes:[...h]}:{},state:{serial:m?.serial??0}},exitCode:1});if(n.refusal!==void 0)return o(n.refusal,t.state,n.refusalCodes);let a=Ub(n,t.state),c=n.checkpoints?.find(y=>y.step==="before"),l=n.checkpoints?.find(y=>y.step==="after");if(a.length===0&&l===void 0)return e.say("nothing to do: the org holds the environment as the file describes it"),{result:{plan:n,steps:[],status:"success",state:{serial:t.state?.serial??0}},exitCode:0};let u=Me(e.locksDir,r.organizationId,{operation:"apply",env:i,alias:r.alias},e.lockOptions);if("busy"in u){let y=Ue(u.busy);return o(y.message,t.state,[y.code])}let d=new AbortController,f,g=(e.onStop??Le)(y=>{f=y,e.say(`
148
- stopped by ${y}: the step under way stops before its next call to the org, and the state keeps what it wrote; apply again takes up from there`),d.abort()});try{let y;try{let O=await e.store.read(r.organizationId,i);if(O===void 0!=(t.state===void 0)||O!==void 0&&(O.serial!==t.state?.serial||O.lineage!==t.state.lineage))return o(`The state of ${i} on ${r.alias} changed since the plan (another apply or destroy ran, or a cache put back another state). Nothing was written: plan again.`,O,[$r]);y=O??gr({env:i,org:{organizationId:r.organizationId,kind:r.kind,username:r.username,alias:r.alias},fileDigest:s.digest,sandforgeVersion:e.sandforgeVersion})}catch(O){if(O instanceof L)return o(O.message,t.state,[Ke(O).code]);throw O}y={...y,file:{digest:s.digest},sandforgeVersion:e.sandforgeVersion};let m={organizationId:r.organizationId,env:i},h=[],w=[],v=[],k=new Map,b=!1,S,$=new Map(s.resources.map(O=>[O.name,O])),E=new Set,R=0,j=[],D={alias:r.alias,kind:r.kind},N=kr(s.checked.file);if(c!==void 0&&a.length>0){let O=await ki(e,{org:D,step:"before",name:c.name,...N},d.signal);if(j.push(O.result),O.checkpoint===void 0){let te=f!==void 0?be(f):pe(O.result.exitCode)?O.result.exitCode:1;return{result:{plan:n,steps:[],checkpoints:j,status:qs(te),refusal:`The checkpoint before the first write, '${c.name}', was not taken (${O.result.refusal??`exit ${O.result.exitCode}`}). Nothing was written.`,state:{serial:y.serial}},exitCode:te}}let q=O.checkpoint;y=await e.store.update(y,te=>Be(te,"before",q))}try{for(let O of a){if(R+=1,S!==void 0||f!==void 0){w.push({resource:O.resource,why:"the apply was stopped before it"});continue}let q=$.get(O.resource),te=(q?.dependsOn??[]).filter(ne=>k.has(ne));if(O.phase==="run"&&te.length>0){w.push({resource:O.resource,why:`it depends on ${te.map(ne=>`${ne} (${k.get(ne)??"not whole"})`).join(", ")}`});continue}let Jt=or(e.locksDir,r.organizationId,e.lockOptions);if(Jt!==void 0){e.say(an(Jt).message),v.push(1),w.push({resource:O.resource,why:an(Jt).message});break}if(O.phase==="remove"){let ne=t.acceptAutomation||s.checked.file.resources[O.resource]?.accept?.automation===!0,J=await Da(e,y,{resource:O.resource,action:O.action,target:r,includeChanged:!1,sweep:!1,acceptAutomation:ne,ends:{whole:"destroyed",left:"partial"}},d.signal);if(y=J.state,h.push(...J.steps),b||=J.wrote,pe(J.code)){S=J.code;continue}if(v.push(J.code),J.code!==0&&J.code!==3)break;continue}if(q===void 0)continue;let Yt=en(y.resources[O.resource]),Xn=await Qb(e,y,q,m,r);if("refusal"in Xn){e.say(`${O.resource}: not run, ${Xn.refusal}`),v.push(1),w.push({resource:O.resource,why:Xn.refusal}),k.set(O.resource,"not run");break}let tm=await e.store.writeFile(m.organizationId,i,kt(O.resource,Yt),`${JSON.stringify(Xn.payload,null,2)}
149
- `),nm=q.dependsOn.some(ne=>E.has(ne));e.say(`${O.resource}: run ${Yt} (${O.action})`);let B=await Wb(e,y,{resource:q,n:Yt,where:m,target:r,templateFile:tm,dry:t.dryRuns[O.resource],readTooEarly:nm,replace:O.action==="replace"&&lt(q.kind),acceptAutomation:t.acceptAutomation||s.checked.file.resources[O.resource]?.accept?.automation===!0,acceptEmails:t.acceptEmails===!0,signal:d.signal});y=B.state,b||=B.wrote,q.kind!=="mask"&&E.add(O.resource);let vt=B.masking,ke=q.kind==="mask"?Gb(B.code,vt):Vb(fh(B.code,B.count,B.planned),B.verified),rm=await e.orgNow();if(y=await e.store.update(y,ne=>bt(ne,{resource:O.resource,status:ke.status,run:{endedAt:rm,exitCode:B.code,objects:vt!==void 0?vt.objects.map(J=>({objectApiName:J.object,created:0,refused:J.refused,masked:J.masked})):(B.count?.objects??[]).map(J=>({objectApiName:J.object,created:J.created,refused:J.refused})),...B.summary!==void 0?{summary:B.summary}:{},...vt?.snapshotId!==void 0?{snapshotId:vt.snapshotId}:{}}})),B.tookBackEarlier===!0)for(let ne of y.resources[O.resource]?.runs??[])ne.n===Yt||ne.takenBack===!0||(y=await e.store.update(y,J=>yr(J,O.resource,ne.n)));let Zn=q.kind==="mask"?Hb(vt):qb(B.count),Ka=dh(B.code,B.answered,B.stderr);if(h.push({resource:O.resource,action:O.action,phase:"run",run:Yt,script:B.script,exitCode:B.code,status:ke.status,...B.summary!==void 0?{summary:B.summary}:{},objects:ke.short!==void 0&&Zn[0]!==void 0?[{...Zn[0],reason:ke.short},...Zn.slice(1)]:Zn,...B.answer!==void 0?{answer:B.answer}:{},...Ka!==void 0?{refusal:Ka}:{}}),ke.short!==void 0&&e.say(`${O.resource}: ${ke.short}`),pe(B.code)){S=B.code,e.say(q.kind==="mask"?`${O.resource}: its masking was stopped; the state keeps it applying, and its store the snapshot it took first: apply again masks what its condition selects`:`${O.resource}: its run was stopped; the state keeps it applying, and its ${q.kind==="forge"?"summary what it created":q.kind==="frozen"?"sas what it loaded":"run file what it wrote"}: apply again takes it back and runs it whole`);continue}if(v.push(ke.counts),ke.status!=="applied"&&k.set(O.resource,ke.status),ke.stops)break}}catch(O){let q=`the apply stopped on an error: ${O instanceof Error?O.message:String(O)}`;e.say(q),v.push(1);for(let te of a.slice(R))w.push({resource:te.resource,why:q})}let P=y.checkpoints?.after;if(b&&P!==void 0&&f===void 0){let O=await At(e,{org:D,checkpoint:P,why:"taken before this apply wrote"},d.signal);j.push(O),y=await e.store.update(y,q=>Be(q,"after",void 0))}let le=f===void 0&&S===void 0&&Qt(v)===0;if(l!==void 0&&le){let O=await ki(e,{org:D,step:"after",name:l.name,...N},d.signal);j.push(O.result);let q=O.checkpoint;q!==void 0?y=await e.store.update(y,te=>Be(te,"after",q)):pe(O.result.exitCode)?S=O.result.exitCode:(e.say(`the checkpoint once applied, '${l.name}', was not taken: reset has nothing to rewind to until an apply takes it, which the next one does`),v.push(1))}let me=f!==void 0?be(f):S!==void 0?S:(()=>{let O=Qt(v);return O===1&&b?3:O})();return{result:{plan:n,steps:h,...j.length>0?{checkpoints:j}:{},...w.length>0?{skipped:w}:{},status:qs(me),state:{serial:y.serial}},exitCode:me}}finally{g(),u.lock.release()}}function Xb(e){return e.map(t=>{let n=t.step==="delete"?`checkpoint ${t.checkpoint??""} deleted`:`checkpoint ${t.step==="before"?"before the first write":"once applied"}`;return t.exitCode!==0?` ${n}: exit ${t.exitCode}, ${t.step==="delete"?"kept":"not taken"}: ${t.refusal??""}`:t.step==="delete"?` ${n}`:` ${n}: exit 0, taken ${t.checkpoint??""}`})}function Ta(e,t){let n=[""];for(let r of e.steps){if(r.script==="sandforge-dataops"){let i=r.objects.map(o=>r.phase==="run"?`${o.object} ${o.masked??0} masked${o.refused>0?`, ${o.refused} refused`:""}`:`${o.object} ${o.masked??0} left masked`).join("; ");n.push(` ${r.resource} ${r.phase==="run"?`masking ${r.run}: exit ${r.exitCode}`:"store deleted"}, ${r.status}${i?` ${i}`:""}`),r.refusal!==void 0&&n.push(` ${r.refusal}`);for(let o of r.objects)o.reason!==void 0&&n.push(` ${o.object}: ${o.reason}`);continue}let s=r.objects.map(i=>r.phase==="run"?`${i.object} ${i.created} created${i.refused>0?`, ${i.refused} refused`:""}`:`${i.object} ${i.deleted} deleted${i.kept>0?`, ${i.kept} kept`:""}`).join("; ");n.push(` ${r.resource} ${r.phase==="run"?"run":"removal of run"} ${r.run}: exit ${r.exitCode}, ${r.status}${s?` ${s}`:""}`),r.refusal!==void 0&&n.push(` ${r.refusal}`);for(let i of r.objects)i.reason!==void 0&&n.push(` ${i.object}: ${i.reason}`)}for(let r of e.skipped??[])n.push(` ${r.resource}: not run, ${r.why}`);return n.push(...Xb(e.checkpoints??[])),e.refusal!==void 0&&n.push(`${t} refused: ${e.refusal}`),n.push(`${t}: ${e.status}; state serial ${e.state.serial}`),n}import{readFile as Hn,readdir as Zb,stat as eE}from"node:fs/promises";import{join as st}from"node:path";var tE={"sandforge-seed":"seed","sandforge-clone":"forge","sandforge-frozen":"frozen","sandforge-dataops":"mask"},nE=/^([1-9][0-9]{0,5})\.summary\.json$/,rE=/^([a-z][a-z0-9-]{0,62})\.([1-9][0-9]{0,5})\.json$/,sE=/^([a-z][a-z0-9-]{0,62})-([1-9][0-9]{0,5})-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,iE=/\.load-\d{1,16}\.ndjson$/,K=class extends Error{constructor(n,r){super(r);this.code=n;this.name="Refused"}code},X="Nothing was written.";async function it(e,t){try{return(await Zb(e,{withFileTypes:!0})).filter(r=>t?r.isDirectory():r.isFile()).map(r=>r.name).sort()}catch(n){let r=n?.code;if(r==="ENOENT"||r==="ENOTDIR")return[];throw n}}function Pa(e,t,n){let r=e.ranks.get(t);r===void 0&&(r=new Map,e.ranks.set(t,r));let s=r.get(n);return s===void 0&&(s={seedRuns:[]},r.set(n,s)),s}async function yh(e,t){let n=t.resolved.checked.file.name,r=t.target.organizationId,s=e.store.folderOf(r,n),i={ranks:new Map,frozen:new Set,dataops:new Set,unclaimed:[]},o=f=>Gt.safeParse(f).success;for(let f of(await it(st(s,"runs"),!0)).filter(o))for(let g of await it(st(s,"runs",f),!1)){let y=nE.exec(g)?.[1];y!==void 0&&(Pa(i,f,Number(y)).summary=ae(f,Number(y)))}for(let f of await it(st(s,"templates"),!1)){let g=rE.exec(f);g?.[1]===void 0||g[2]===void 0||!o(g[1])||(Pa(i,g[1],Number(g[2])).template=kt(g[1],Number(g[2])))}for(let f of(await it(st(s,"frozen"),!0)).filter(o))i.frozen.add(f);for(let f of(await it(st(s,"dataops"),!0)).filter(o))i.dataops.add(f);let a=new Set(t.resolved.resources.map(f=>f.name)),c=new Set([...i.ranks.keys(),...i.frozen,...i.dataops]),l=(await it(st(s,".."),!0)).filter(f=>f!==n&&f.startsWith(`${n}-`)),u=`env-${n}-`,d=uc(e.journalDir,Ae);for(let f of await it(st(e.journalDir,Ae),!1)){if(!f.endsWith(".ndjson")||!f.startsWith(u))continue;let g=f.slice(0,-7),y=sE.exec(g.slice(u.length));if(y?.[1]===void 0||y[2]===void 0)continue;let m=y[1],h=a.has(m)||c.has(m),w=l.find(b=>g.startsWith(`env-${b}-`));if(w!==void 0&&!h)continue;let v=st(e.journalDir,Ae,f),k=await d.get(g);if(k===void 0)throw new K("RUN_UNREAD",`The seed run file ${v} does not read as a run: a state rebuilt without it would leave what it created to nobody. Move it aside if it is not a run of ${n}. ${X}`);if(k.targetOrganizationId===void 0)throw new K("RUN_UNREAD",`The seed run file ${v} names no Organization Id: nothing tells whether it wrote to ${t.target.alias} or to another org. Move it aside if it is not a run of ${n} on ${t.target.alias}. ${X}`);if(de(k.targetOrganizationId,r)){if(w!==void 0)throw new K("RUN_UNCLAIMED",`The seed run file ${v} may be run ${y[2]} of ${m} of ${n}, or a run of ${w}, kept on this machine too: their names begin alike, and nothing tells them apart. Move it out of the folder while ${n} is recovered if it is ${w}'s. ${X}`);if(!h){i.unclaimed.push({file:v,resource:m,run:k});continue}Pa(i,m,Number(y[2])).seedRuns.push({runId:g,run:k})}}return i}async function zs(e,t){try{let n=await yh(e,t);return n.unclaimed.length>0||n.frozen.size>0||n.dataops.size>0||[...n.ranks.values()].some(r=>[...r.values()].some(s=>s.summary!==void 0||s.seedRuns.length>0))}catch(n){return n instanceof K}}function Gn(e){if(typeof e!="string")return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}async function wh(e){try{return(await eE(e)).mtime.toISOString()}catch{return}}async function oE(e){let t=o=>new K("RUN_UNREAD",`The summary ${e} does not read (${o}): a state rebuilt without it would leave what its run created to nobody. ${X}`),n;try{n=await Hn(e,"utf8")}catch(o){throw t(o instanceof Error?o.message:String(o))}let r;try{r=JSON.parse(n)}catch{throw t("not JSON")}let s=r?.tool,i=typeof s=="string"?tE[s]:void 0;try{if(i==="seed")return{kind:i,answer:Nt(n)};if(i==="frozen")return{kind:i,answer:Cr(n)};if(i==="mask")return{kind:i,answer:Ir(n)};if(i==="forge"){let o=r,a=Gn(o.finishedAt),c=typeof o.elapsedMs=="number"&&Number.isFinite(o.elapsedMs)&&o.elapsedMs>=0?o.elapsedMs:void 0;return{kind:i,answer:cn(n),...a!==void 0?{finishedAt:a}:{},...c!==void 0?{elapsedMs:c}:{}}}}catch(o){throw o instanceof re?t(o.message):o}throw t("it names no script of an environment")}function vh(e){return e.removal!==void 0&&ei(e).length===0}function aE(e){return e.interrupted===!0||e.result.cancelled===!0?"applying":e.result.status==="success"?"applied":e.result.status==="partial"?"partial":"failed"}function La(e){return e.map(t=>({objectApiName:t.object,created:t.created,refused:t.refused}))}function hh(e,t,n){if(!(t===void 0||de(t,n.target.organizationId)))throw new K("RUN_OTHER_ORG",`The summary ${e} is of a run that wrote to ${t}, not to ${n.target.alias} (${n.target.organizationId}): it was copied from another org's folder. Put it back where it came from. ${X}`)}async function cE(e,t,n,r,s,i){let o=t.resolved.checked.file.name,a=m=>e.store.fileOf(t.target.organizationId,o,m);if(s.seedRuns.length>1)throw new K("RUNS_CONFLICT",`Two seed runs are kept for run ${r} of ${n}: ${s.seedRuns.map(m=>m.runId).join(", ")}. One rank is one run: the state they come from cannot be told. ${X}`);let c=s.seedRuns[0],l=i?.kind==="seed"?i.answer:void 0,u=l?.result.operationId??c?.runId;if(l!==void 0&&c!==void 0&&l.result.operationId!==c.runId)throw new K("RUNS_CONFLICT",`The summary of run ${r} of ${n} is of the run ${l.result.operationId}, and the seed run file of that rank of ${c.runId}: one rank is one run. ${X}`);if(l!==void 0&&!l.result.operationId.startsWith(`env-${o}-${n}-${r}-`))throw new K("RUNS_CONFLICT",`The summary ${a(ae(n,r))} is of the run ${l.result.operationId}, which is not run ${r} of ${n}. ${X}`);let d=c!==void 0&&vh(c.run);if(l!==void 0&&!d){let m=await Hn(a(di(n,r)),"utf8").catch(()=>{}),h;try{h=m!==void 0?JSON.parse(m):void 0}catch{h=void 0}let w=h?.runId===l.result.operationId?dc(h):void 0;d=w!==void 0&&l.result.objectResults.every(v=>v.truncated!==!0)&&ei(bc({runId:l.result.operationId,targetOrgId:l.target,status:l.result.status,objectResults:l.result.objectResults},w)).length===0}let f=Gn(l?.startedAt)??Gn(c?.run.startedAt)??new Date(0).toISOString(),g=Gn(l!==void 0?l.finishedAt:c?.run.end?.at),y=l!==void 0?La(Dr(l).objects):(c?.run.created??[]).map(m=>({objectApiName:m.objectApiName,created:m.ids.length,refused:0}));return{run:{n:r,script:"sandforge-seed",...u!==void 0?{runId:u}:{},...s.summary!==void 0&&l!==void 0?{summary:s.summary}:{},...l!==void 0?{seed:l.seed}:{},startedAt:f,...g!==void 0?{endedAt:g}:{},objects:y,...d?{takenBack:!0}:{}},status:l!==void 0?aE(l):"applying"}}async function lE(e,t,n,r,s){let i=t.resolved.checked.file.name,o=ae(n,r),a=e.store.fileOf(t.target.organizationId,i,o),{answer:c}=s,l=!1,u=await Hn(e.store.fileOf(t.target.organizationId,i,di(n,r)),"utf8").catch(()=>{});if(u!==void 0){let m=await ar(a,await Hn(a,"utf8"),t.target.alias,ir(e.journalDir));if(!("refusal"in m)){let h=jc(u,Cc(Oc(m.summary)));l="earlier"in h&&h.earlier?.removalLeft?.length===0}}let d=c.running===!0||c.interrupted===!0?void 0:s.finishedAt,f=s.finishedAt??await wh(a)??new Date(0).toISOString(),g=new Date(Date.parse(f)-(s.elapsedMs??0)).toISOString(),y=c.running===!0||c.interrupted===!0?"applying":c.error!==void 0?"failed":c.result.failedCount>0?"partial":"applied";return{run:{n:r,script:"sandforge-clone",summary:o,startedAt:g,...d!==void 0?{endedAt:d}:{},objects:La(Or(c).objects),...l?{takenBack:!0}:{}},status:y}}async function mh(e,t,n){let r=t.resolved.checked.file.name,s=a=>a!==void 0?wh(e.store.fileOf(t.target.organizationId,r,a)):Promise.resolve(void 0),i=await s(n.template),o=await s(n.summary);return{startedAt:i??o??new Date(0).toISOString(),...o!==void 0?{endedAt:o}:{}}}async function uE(e,t){if((await it(e,!1)).some(i=>iE.test(i)))return!1;let n=new Oe,r=(await Xt(e,n)).find(i=>de(i,t));if(r===void 0)return!1;let s=await new lr(e,{orgId:r,guard:n}).recordedLoads();return s.length>0&&s.some(i=>i.removal!==void 0)&&s.every(i=>i.created!==void 0&&Lc(i).length===0)}async function dE(e,t){let n=(await Xt(e,new Oe)).filter(r=>!de(r,t.target.organizationId));if(n.length!==0)throw new K("RUN_OTHER_ORG",`The sas ${e} keeps loads into ${n.join(", ")}, not into ${t.target.alias} (${t.target.organizationId}): it was copied from another org's folder. Put it back where it came from. ${X}`)}function fE(e){let t=pn(e);return t.refusal!==void 0?"failed":t.objects.some(n=>n.refused>0)?"partial":e.verdict===void 0||e.verdict.status==="PASSED"?"applied":"partial"}function pE(e){let t=hn(e);return t.refusal!==void 0?"failed":t.short!==void 0||t.objects.some(n=>n.notMasked>0)?"partial":"applied"}function hE(e,t,n){let r=new Set;for(let s of n.values())r.add(s.kind);if(t.frozen.has(e)&&r.add("frozen"),t.dataops.has(e)&&r.add("mask"),[...t.ranks.get(e)?.values()??[]].some(s=>s.seedRuns.length>0)&&r.add("seed"),r.size>1)throw new K("RUNS_CONFLICT",`The run files of ${e} are of ${[...r].join(" and ")} runs: one resource is of one kind, and the state they come from cannot be told. ${X}`);return[...r][0]}async function mE(e,t,n,r){let s=t.resolved.checked.file.name,i=t.target.organizationId,o=n.ranks.get(r)??new Map,a=new Map;for(let[w,v]of o)v.summary!==void 0&&a.set(w,await oE(e.store.fileOf(i,s,v.summary)));let c=hE(r,n,a);if(c===void 0)return;for(let[w,v]of a){let k=e.store.fileOf(i,s,ae(r,w));v.kind==="seed"&&hh(k,v.answer.targetOrgId,t),v.kind==="forge"&&hh(k,v.answer.targetOrgId,t)}let l=[],u=[...o.keys()].sort((w,v)=>w-v);if(c==="seed")for(let w of u){let v=o.get(w);v===void 0||v.summary===void 0&&v.seedRuns.length===0||l.push(await cE(e,t,r,w,v,a.get(w)))}else if(c==="forge")for(let w of u){let v=a.get(w);v?.kind==="forge"&&l.push(await lE(e,t,r,w,v))}else if(c==="frozen"){let w=e.store.sasOf(i,s,Ve(r));await dE(w,t);let v=await uE(w,i);for(let k of u){let b=o.get(k),S=a.get(k);if(b?.template===void 0){if(S?.kind!=="frozen"||v)continue;throw new K("RUN_UNREAD",`Run ${k} of ${r} keeps its summary and not the payload its load was given, ${e.store.fileOf(i,s,kt(r,k))}, which its removal is run from: a state rebuilt without it would leave what the load created to nobody. ${X}`)}let $=S?.kind==="frozen"?S.answer:void 0;if(l.push({run:{n:k,script:"sandforge-frozen",sas:Ve(r),...$!==void 0&&b.summary!==void 0?{summary:b.summary}:{},...await mh(e,t,b),objects:$!==void 0?La(pn($).objects):[],...v?{takenBack:!0}:{}},status:$!==void 0?fE($):"applying"}),$!==void 0&&jr($))for(let E of l.slice(0,-1))E.run.takenBack=!0}}else{let w=!n.dataops.has(r);for(let v of u){let k=o.get(v),b=a.get(v);if(k===void 0)continue;let S=b?.kind==="mask"?b.answer:void 0;if(S===void 0&&w)continue;let $=S!==void 0?hn(S):void 0;l.push({run:{n:v,script:"sandforge-dataops",...S!==void 0&&k.summary!==void 0?{summary:k.summary}:{},...$?.snapshotId!==void 0?{snapshotId:$.snapshotId}:{},...await mh(e,t,k),objects:($?.objects??[]).map(E=>({objectApiName:E.object,created:0,refused:E.refused,masked:E.masked})),...w?{takenBack:!0}:{}},status:S!==void 0?pE(S):"applying"})}}if(l.length===0)return;let d=l.map(w=>w.run),f=l.at(-1),g=d.every(w=>w.takenBack===!0)?"destroyed":f?.run.takenBack===!0?"partial":f?.status??"applying",y=t.resolved.resources.find(w=>w.name===r),m=d.flatMap(w=>w.endedAt!==void 0?[w.endedAt]:[]).sort(),h=d.map(w=>w.startedAt).sort();return{name:r,state:{kind:c,fingerprint:Qa,dependsOn:y!==void 0?[...y.dependsOn]:[],status:g,runs:d,recovered:!0},firstStartedAt:h[0]??new Date(0).toISOString(),...m.length>0?{lastEndedAt:m.at(-1)}:{}}}async function gE(e,t,n){let r=t.resolved.checked.file,i=(await new pc({root:ye(e.journalDir),locksDir:e.locksDir}).list({organizationId:t.target.organizationId})).flatMap(d=>d.valid&&d.checkpoint!==void 0?[d.checkpoint]:[]),o=[],a={},c=`${r.name} before`,l=i.filter(d=>d.name===c&&Date.parse(d.takenAt)<=Date.parse(n.first));l.length===1&&l[0]!==void 0?a.before=l[0].checkpointId:rn(r,"before")===void 0&&l.length===0?o.push("checkpoint.before: the file asks none"):o.push(`checkpoint.before: ${l.length===0?"no":`${l.length}`} checkpoint(s) of this org named '${c}' taken before the first run: none is linked, and destroy --rewind has none to return to`);let u=rn(r,"after");if(u===void 0)o.push("checkpoint.after: the file asks none");else{let d=n.last,f=i.filter(g=>g.name===u&&d!==void 0&&Date.parse(g.readFrom)>=Date.parse(d));f.length===1&&f[0]!==void 0?a.after=f[0].checkpointId:o.push(`checkpoint.after: ${f.length===0?"no":`${f.length}`} checkpoint(s) of this org named '${u}' taken after the last run: none is linked, and reset has none to rewind to until an apply takes it`)}return{...a,notLinked:o}}function yE(e,t){let n=i=>{let o=/^(\d+)\.(\d+)\.(\d+)/.exec(i);return o?[Number(o[1]),Number(o[2]),Number(o[3])]:void 0},r=typeof e=="string"?n(e):void 0,s=n(t);if(r===void 0||s===void 0)return!1;for(let i=0;i<3;i++)if((r[i]??0)!==(s[i]??0))return(r[i]??0)>(s[i]??0);return!1}async function wE(e,t){let n=t.resolved.checked.file.name,{alias:r,organizationId:s}=t.target;try{let l=await e.store.read(s,n);if(l===void 0)return{damaged:!1};throw new K("STATE_KEPT",`This machine keeps a state of ${n} on ${r} that reads, serial ${l.serial}: state recover never writes over one, and plan reads it. ${X}`)}catch(l){if(!(l instanceof L))throw l;if(l.code!=="damaged"){let u=Ke(l);throw new K(u.code,u.message)}}let i=e.store.stateFileOf(s,n),o;try{o=JSON.parse(await Hn(i,"utf8"))}catch{o=void 0}let a=o,c=a?.version;if(typeof c=="number"&&c>1||yE(a?.sandforgeVersion,e.sandforgeVersion))throw new K("STATE_NEWER",`The state ${i} was written by a later SandForge (${String(a?.sandforgeVersion??`version ${String(c)}`)}; this one is ${e.sandforgeVersion}): update it, and plan again. ${X}`);return{damaged:!0}}async function kh(e,t){let n=t.resolved.checked.file.name,{target:r}=t,s=Me(e.locksDir,r.organizationId,{operation:"recover",env:n,alias:r.alias},e.lockOptions);if("busy"in s)return{refusal:Ue(s.busy)};try{let{damaged:i}=await wE(e,t),o=await yh(e,t),a=[];for(let k of[...o.ranks.keys(),...o.frozen,...o.dataops]){if(a.some(S=>S.name===k))continue;let b=await mE(e,t,o,k);b!==void 0&&a.push(b)}let c=[];for(let k of o.unclaimed){if(vh(k.run)){c.push(`${k.file}: a run of ${k.resource}, which neither the file nor the environment's folder has, taken back whole: passed over`);continue}throw new K("RUN_UNCLAIMED",`The seed run file ${k.file} is of a resource ${k.resource} that neither the file nor the environment's folder has: it may be another environment's, whose name begins as ${n} does. Move it out of the folder if it is, or put ${k.resource} back in the file. ${X}`)}if(a.length===0)throw new K("NO_RUNS",`This machine keeps no run of ${n} on ${r.alias}: there is nothing to rebuild a state from. If the org holds nothing of the environment, apply it with --accept-no-state. ${X}`);a.sort((k,b)=>Date.parse(k.firstStartedAt)-Date.parse(b.firstStartedAt)||k.name.localeCompare(b.name));let l=a[0]?.firstStartedAt??new Date(0).toISOString(),d=a.flatMap(k=>k.lastEndedAt!==void 0?[k.lastEndedAt]:[]).sort().at(-1),f=await gE(e,t,{first:l,...d!==void 0?{last:d}:{}}),y={...gr({env:n,org:{organizationId:r.organizationId,kind:r.kind,username:r.username,alias:r.alias},fileDigest:t.resolved.digest,sandforgeVersion:e.sandforgeVersion}),resources:Object.fromEntries(a.map(k=>[k.name,k.state])),...f.before!==void 0||f.after!==void 0?{checkpoints:{...f.before!==void 0?{before:f.before}:{},...f.after!==void 0?{after:f.after}:{}}}:{}},m=Ht.safeParse({...y,serial:1});if(!m.success){let k=m.error.issues[0];throw new K("RUN_UNREAD",`The run files of ${n} do not make a state (${k?.path.join(".")??""}: ${k?.message??"refused"}). ${X}`)}let h=i?await e.store.setAside(r.organizationId,n):void 0,w=await e.store.write(y,{serial:0,lineage:y.lineage}),v=new Set(t.resolved.resources.map(k=>k.name));return{state:w,result:{env:n,org:{organizationId:w.org.organizationId,kind:w.org.kind,alias:r.alias},state:{serial:w.serial,lineage:w.lineage},...h!==void 0?{setAside:h}:{},resources:Object.fromEntries(a.map(k=>[k.name,{kind:k.state.kind,status:k.state.status,runs:k.state.runs.map(b=>b.n),takenBack:k.state.runs.filter(b=>b.takenBack===!0).map(b=>b.n),inFile:v.has(k.name)}])),checkpoints:{...f.before!==void 0?{before:f.before}:{},...f.after!==void 0?{after:f.after}:{}},notLinked:[...f.notLinked,...c].slice(0,20)}}}catch(i){if(i instanceof K)return{refusal:{code:i.code,message:i.message,exit:1}};throw i}finally{s.lock.release()}}function gh(e){return`${e.length===1?"run":"runs"} ${e.join(", ")}`}function bh(e){let t=[`state of ${e.env} on ${e.org.alias??e.org.organizationId} rebuilt from its run files: serial ${e.state.serial}`],n=Math.max(...Object.keys(e.resources).map(r=>r.length));for(let[r,s]of Object.entries(e.resources)){let i=s.takenBack.length===0?"":s.takenBack.length===s.runs.length?", taken back":`; ${gh(s.takenBack)} taken back`;t.push(` ${r.padEnd(n)} ${s.kind}, ${s.status}: ${gh(s.runs)}${i}`+(s.inFile?"":"; gone from the file"))}e.checkpoints.before!==void 0&&t.push(` checkpoint.before: ${e.checkpoints.before}`),e.checkpoints.after!==void 0&&t.push(` checkpoint.after: ${e.checkpoints.after}`);for(let r of e.notLinked)t.push(` ${r}`);return e.setAside!==void 0&&t.push(`the state that did not read is kept, set aside: ${e.setAside}`),t.push("next: plan replaces each resource still in the org, whose run files do not say what it was applied from, and asks no --accept-no-state"),t}function vE(e){return rt(e,De(e).map(([t])=>t))}async function Eh(e,t){let{plan:n,target:r,resolved:s}=t,i=s.checked.file.name,o=(f,g=[])=>({result:{plan:n,steps:[],status:"failure",refusal:f,...g.length>0?{refusalCodes:[...g]}:{},state:{serial:t.state?.serial??0}},exitCode:1});if(t.state===void 0)return await zs(e,{resolved:s,target:r})?o(`This machine keeps no state of ${i} on ${r.alias}, but keeps runs of it: the records they wrote are still in the org, and destroy reaches only what a state names. "${ue("env")} state recover --file <file> --org ${r.alias}" rebuilds the state from them; then destroy again. Nothing was deleted.`,["NO_STATE"]):(e.say(`this machine keeps no state of ${i} on ${r.alias}, nor any run of it: nothing applied from here is left to take back. Records an apply from another machine or a CI job left are not known here: restore its journal directory (SANDFORGE_JOURNAL_DIR), then destroy again`),{result:{plan:n,steps:[],status:"success",state:{serial:0}},exitCode:0});if(n.refusal!==void 0)return o(n.refusal,n.refusalCodes);let a=vE(t.state),c=Me(e.locksDir,r.organizationId,{operation:"destroy",env:i,alias:r.alias},e.lockOptions);if("busy"in c){let f=Ue(c.busy);return o(f.message,[f.code])}let l=new AbortController,u,d=(e.onStop??Le)(f=>{u=f,e.say(`
150
- stopped by ${f}: the removal under way stops before its next call to the org; destroy again takes up from the state`),l.abort()});try{let f;try{let E=await e.store.read(r.organizationId,i);if(E===void 0||E.serial!==t.state.serial||E.lineage!==t.state.lineage)return o(`The state of ${i} on ${r.alias} changed since the plan of the destruction (another apply or destroy ran, or a cache put back another state). Nothing was deleted: run destroy again.`,[$r]);f=E}catch(E){if(E instanceof L)return o(E.message,[Ke(E).code]);throw E}let g=[],y=[],m=[],h=!1,w,v;for(let[E,R]of a.entries()){if(u!==void 0||w!==void 0){v??=E;break}let j=or(e.locksDir,r.organizationId,e.lockOptions);if(j!==void 0){e.say(an(j).message),m.push(1),v=E;break}let D=t.acceptAutomation||s.checked.file.resources[R]?.accept?.automation===!0,N=await Da(e,f,{resource:R,action:"delete",target:r,includeChanged:t.includeChanged,sweep:t.sweep,acceptAutomation:D,ends:{whole:"destroyed",left:"partial"}},l.signal);if(f=N.state,g.push(...N.steps),h||=N.wrote,pe(N.code)){w=N.code,v=E+1;break}if(m.push(N.code),N.code!==0&&N.code!==3){v=E+1;break}}for(let E of v!==void 0?a.slice(v):[])y.push({resource:E,why:u!==void 0||w!==void 0?"the destroy was stopped before it":"a removal before it was refused or failed: its records would be kept for it"});let k=Object.values(f.resources).every(E=>E.status==="destroyed"),b=[];if(k&&v===void 0){let E=Object.values(f.resources).some(R=>R.kind==="mask");e.say(`every record of ${i} is taken back from ${r.alias}${E?", and what it masked left masked":""}: the state keeps it as destroyed, and the next apply creates it again`);for(let{step:R,checkpoint:j}of Sr(f)){let D=await At(e,{org:{alias:r.alias,kind:r.kind},checkpoint:j,why:"the environment it was taken of is taken back"},l.signal);b.push(D),D.exitCode===0&&(f=await e.store.update(f,N=>Be(N,R,void 0)))}}let S=u!==void 0?be(u):w!==void 0?w:(()=>{let E=Qt(m);return E===1&&h?3:E})();return{result:{plan:n,steps:g,...b.length>0?{checkpoints:b}:{},...y.length>0?{skipped:y}:{},status:qs(S),state:{serial:f.serial}},exitCode:S}}finally{d(),c.lock.release()}}var kE="taken back by a destroy: none of the org's records is its",bE="taken back by a destroy, which deleted its store and left its records masked: a masking creates no record",Sh="a masking creates no record: it writes over those the org holds that its condition selects",EE={applying:"its last run was stopped part way",partial:"its last run was partial",failed:"its last run failed",destroying:"a removal of it was stopped part way"};function Rh(e){return`${EE[e]??e}: it names no record until it is applied whole \u2014 apply again`}function $h(e,t,n){let r=e.filter(i=>i.env===t&&(i.state?.org.alias===n||i.organizationId.slice(0,15)===n.slice(0,15)));if(r.length>1){let i=r.map(o=>`${o.organizationId}, written ${o.state?.updatedAt??"?"}`).join("; ");return{refusal:{code:"TWO_STATES",message:`${r.length} states of ${t} on this machine are of ${n}: ${i} \u2014 an alias reused for another org. Give --org the Organization Id of the one meant.`,exit:1}}}let[s]=r;return s===void 0?{refusal:{code:"NO_STATE",message:`This machine keeps no state of ${t} on ${n}: nothing was applied to it from here, or the journal directory of the apply was not restored. output reads the state alone, and reaches no org.`,exit:1}}:s.state===void 0?{refusal:{code:"STATE_DAMAGED",message:`${s.damaged??"The state does not read."} Nothing was read.`,exit:1}}:{state:s.state}}async function Ah(e,t){let n={organizationId:e.org.organizationId,env:e.env,target:e.org.alias??e.org.organizationId},r=va(Object.keys(e.resources),o=>e.resources[o]?.dependsOn??[]),s={},i=!0;for(let o of r){let a=e.resources[o];if(a===void 0)continue;let c=a.runs.at(-1),l={kind:a.kind,status:a.status,...c!==void 0?{run:c.n}:{},records:{}};if(a.status==="destroyed"){s[o]={...l,why:a.kind==="mask"?bE:kE};continue}if(a.status!=="applied"&&(i=!1),a.kind==="mask"){s[o]={...l,masked:Object.fromEntries((c?.objects??[]).map(d=>[d.objectApiName,d.masked??0])),...c?.snapshotId!==void 0?{snapshotId:c.snapshotId}:{},why:a.status==="applied"?Sh:`${Rh(a.status)}; ${Sh}`};continue}if(a.status!=="applied"){s[o]={...l,why:Rh(a.status)};continue}if(c===void 0||c.takenBack===!0){i=!1,s[o]={...l,why:"it holds no run whose records are in the org"};continue}let u=await Na(c,n,t);if("refusal"in u){i=!1,s[o]={...l,why:u.refusal};continue}s[o]={...l,records:Object.fromEntries(u.created)}}return{output:{env:e.env,org:{organizationId:e.org.organizationId,kind:e.org.kind,...e.org.alias!==void 0?{alias:e.org.alias}:{}},state:{serial:e.serial,updatedAt:e.updatedAt},resources:s},whole:i}}function Oh(e){let{org:t}=e,n=[`${e.env} on ${t.alias??t.organizationId} (${t.kind}, ${t.organizationId}): state serial ${e.state.serial}, written ${e.state.updatedAt}`];for(let[r,s]of Object.entries(e.resources)){n.push(` ${r} ${s.kind}, ${s.status}`+(s.run!==void 0?`, run ${s.run}`:""));for(let[i,o]of Object.entries(s.records))n.push(` ${i} ${o.length>0?o.join(" "):"none"}`);for(let[i,o]of Object.entries(s.masked??{}))n.push(` ${i} ${o} masked`);s.snapshotId!==void 0&&n.push(` snapshot ${s.snapshotId}, taken first`),s.why!==void 0&&n.push(` ${s.why}`)}return n}var Ch={reset:"after",destroy:"before"};function Fa(e,t){let n=Ch[e],r=t?.checkpoints?.[n];return r!==void 0?{step:n,checkpoint:r}:void 0}function xa(e){let t=e.resolved.checked.file.name,{alias:n}=e.target,r=a=>({code:"NO_CHECKPOINT",message:`${a} Nothing was written.`,exit:1}),s=e.verb==="reset"?"reset":"destroy --rewind",i=e.state;if(i===void 0)return r(`This machine keeps no state of ${t} on ${n}: ${s} rewinds the org to a checkpoint its state names. Restore the journal directory of the apply, or apply first.`);if(Fa(e.verb,i)===void 0)return r(e.verb==="reset"?`The state of ${t} on ${n} names no checkpoint taken after an apply: the file asks none (checkpoint.after), or the last apply did not take it. Apply with checkpoint.after in the file, then reset.`:`The state of ${t} on ${n} names no checkpoint taken before its first apply: the file asked none (checkpoint.before: true) when it was first applied. destroy without --rewind takes back what the environment wrote.`);let o=Object.entries(i.resources).filter(([,a])=>a.kind==="mask");if(e.verb==="destroy"&&o.length>0)return{code:"MASKED",message:`The state of ${t} on ${n} names mask resources (${o.map(([a])=>a).join(", ")}): the checkpoint taken before the first apply holds the values they wrote over, and a rewind to it would put them back into the org. destroy never unmasks: destroy without --rewind takes back what the environment wrote, and leaves its maskings as they are. Nothing was written.`,exit:1};if(e.verb==="reset"){let a=Object.entries(i.resources).filter(([,c])=>c.status!=="applied"&&c.status!=="destroyed");if(a.length>0)return r(`${a.map(([c,l])=>`${c} is ${l.status}`).join(", ")}: the last apply did not end whole, and the checkpoint taken after the apply before it no longer holds the environment the state names. Apply again, then reset.`)}}async function jh(e,t,n){let r=Fa(t.verb,t.state);if(r===void 0)return{refusal:"no checkpoint to rewind to"};e.say(`checkpoint ${r.checkpoint}: reading what a rewind to it would do`);let s=await e.runner(ce,wi({org:t.target.alias,store:ye(e.journalDir),checkpoint:r.checkpoint,dryRun:!0,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails,acceptNoUndo:t.acceptNoUndo,acceptUnseen:t.acceptUnseen}),n);return rl(s)}var yt=e=>e.toLocaleString("en-US");function Nh(e,t){let{alias:n}=e.target,r=`it deletes ${yt(t.toDelete)} record(s) created since, gives ${yt(t.toGiveBack)} their values back and brings ${yt(t.toBringBack)} back from the recycle bin \u2014 whoever made these changes`+(Rr(t.lastChangedBy)!==""?`, last changed by ${Rr(t.lastChangedBy)}`:"");return e.verb==="reset"?`Type ${n} to reset it to '${t.checkpoint.name}', as ${e.resolved.checked.file.name} was applied: ${r}:`:`Type ${n} to rewind it to before ${e.resolved.checked.file.name} was first applied: ${r}; the environment's checkpoints are then deleted, and this is not undone:`}function SE(e){return{...e,resources:Object.fromEntries(Object.entries(e.resources).map(([t,n])=>[t,{...n,status:"destroyed",runs:n.runs.map(r=>({...r,takenBack:!0}))}]))}}async function Ih(e,t,n){let{target:r,resolved:s,verb:i}=t,o=s.checked.file.name,a=Fa(i,t.state),c={env:o,org:{organizationId:r.organizationId,kind:r.kind,alias:r.alias},verb:i,checkpoint:{step:Ch[i],id:a?.checkpoint??"",...n!==void 0?{name:n.checkpoint.name,takenAt:new Date(n.checkpoint.takenAt).toISOString()}:{}},...n!==void 0?{preview:{toDelete:n.toDelete,toGiveBack:n.toGiveBack,toBringBack:n.toBringBack,lastChangedBy:n.lastChangedBy}}:{}},l=(h,w)=>({result:{...c,exitCode:1,status:"failure",undo:{offered:!1,why:"nothing was rewound"},refusal:h,state:{serial:w}},exitCode:1}),u=xa(t);if(u!==void 0||a===void 0||t.state===void 0)throw new Error(u?.message??"There is no checkpoint to rewind to.");let d=t.state,f=Me(e.locksDir,r.organizationId,{operation:i,env:o,alias:r.alias},e.lockOptions);if("busy"in f)return l(Ue(f.busy).message,d.serial);let g=new AbortController,y,m=(e.onStop??Le)(h=>{y=h,e.say(`
151
- stopped by ${h}: the rewind stops before its next call to the org, and leaves its journal: run this again to take it up`),g.abort()});try{let h;try{let E=await e.store.read(r.organizationId,o);if(E===void 0||E.serial!==d.serial||E.lineage!==d.lineage)return l(`The state of ${o} on ${r.alias} changed since it was read (another apply, destroy or reset ran, or a cache put back another state). Nothing was written: run this again.`,E?.serial??d.serial);h=E}catch(E){if(E instanceof L)return l(E.message,d.serial);throw E}e.say(`${i==="reset"?"reset":"destroy --rewind"}: rewinding ${r.alias} to checkpoint ${a.checkpoint}`);let w=await e.runner(ce,wi({org:r.alias,store:ye(e.journalDir),checkpoint:a.checkpoint,dryRun:!1,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails,acceptNoUndo:t.acceptNoUndo,acceptUnseen:t.acceptUnseen}),g.signal),v=il(w),k=y!==void 0?be(y):v.exitCode,b=[];if(i==="destroy"&&k===0){h=await e.store.update(h,SE);for(let{step:E,checkpoint:R}of Sr(h)){let j=await At(e,{org:{alias:r.alias,kind:r.kind},checkpoint:R,why:"the environment it was taken of is taken back"},g.signal);b.push(j),j.exitCode===0&&(h=await e.store.update(h,D=>Be(D,E,void 0)))}e.say(`every record of ${o} is taken back from ${r.alias}, with what anyone changed since its first apply: the state keeps it as destroyed, and the next apply creates it again`)}let S=ol({verb:i,alias:r.alias,checkpoint:a.checkpoint,journalDir:e.journalDir,deleted:b.length>0&&b.every(E=>E.exitCode===0)},v),$=v.refusal===void 0?void 0:v.refusal.code==="RECREATE"?`${v.refusal.message} ${i==="reset"?"reset":"destroy --rewind"} never makes records again with new Ids, which the state would no longer name: rewind with sandforge checkpoint itself, then apply again.`:v.refusal.message;return{result:{...c,exitCode:k,status:y!==void 0?"cancelled":v.status,...v.answer!==void 0?{answer:v.answer}:{},undo:S,...$!==void 0?{refusal:$.slice(0,8e3)}:{},...b.length>0?{deleted:b}:{},state:{serial:h.serial}},exitCode:k}}finally{m(),f.lock.release()}}function Dh(e){let t=e.verb==="reset"?"reset":"destroy --rewind",n=[""],r=e.answer;if(r?.deleted!==void 0){let s=(r.residual??[]).reduce((i,o)=>i+o.count,0);n.push(` rewind to ${e.checkpoint.id}: exit ${e.exitCode}, ${e.status} ${yt(r.deleted.done)} deleted, ${yt(r.givenBack?.done??0)} given back, ${yt(r.broughtBack?.done??0)} brought back`+(s>0?`, ${yt(s)} still differ`:""))}for(let s of e.deleted??[])n.push(s.exitCode===0?` checkpoint ${s.checkpoint??""} deleted`:` checkpoint ${s.checkpoint??""} kept: ${s.refusal??""}`);return e.refusal!==void 0&&n.push(`${t} refused: ${e.refusal}`),n.push(al(e.undo)),n.push(`${t}: ${e.status}; state serial ${e.state.serial}`),n}import{randomBytes as RE}from"node:crypto";import{existsSync as $E,readFileSync as AE,statSync as OE}from"node:fs";import{open as CE,rename as jE,rm as NE}from"node:fs/promises";import{dirname as IE,resolve as Ma}from"node:path";var Lh=1440*6e4;function Fh(e){let t={};for(let[n,r]of Object.entries(e.dryRuns))"answer"in r&&r.answer.tool===Y&&(t[n]=r.answer.seed);return Hs.parse({savedPlan:1,sandforgeVersion:e.sandforgeVersion,madeAt:e.madeAt,file:{digest:e.digest},state:e.state===void 0?{found:!1}:{found:!0,serial:e.state.serial,lineage:e.state.lineage},line:e.line,seeds:t,plan:e.plan})}function xh(e,t,n){let r=IE(Ma(t));if(!$E(r)||!OE(r).isDirectory())return{code:"BAD_LINE",message:`--out ${Ma(t)}: its folder ${r} is not there. Nothing was read.`,exit:2};if(n)return;let s=ui(e,t);if(s!==void 0)return{code:"PLAN_IN_REPOSITORY",message:`--out ${Ma(t)} is inside the repository ${s} that holds the file: a plan names the org by its Organization Id, its state, and the users who changed its records since, and committed with the project it would publish them. Keep it outside \u2014 in CI, in $RUNNER_TEMP, handed to the job that applies as an artifact \u2014 or give --out-in-repository for a folder of it that is never committed. Nothing was read.`,exit:2}}async function Mh(e,t){let n=`${e}.${RE(6).toString("hex")}.tmp`,r=await CE(n,"wx",ci);try{await r.writeFile(`${JSON.stringify(t,null,2)}
152
- `,"utf8"),await r.sync()}finally{await r.close()}try{await jE(n,e)}catch(s){throw await NE(n,{force:!0}),s}}function _h(e){let t=i=>({refusal:{code:"PLAN_UNREAD",message:`--plan ${e} ${i}. Nothing was read or written.`,exit:2}}),n;try{n=AE(e,"utf8")}catch(i){return t(`cannot be read: ${i instanceof Error?i.message:String(i)}`)}let r;try{r=JSON.parse(n)}catch{return t("is not JSON: it is no plan plan --out kept")}let s=Hs.safeParse(r);if(!s.success){let i=s.error.issues[0],o=i?.path.map(String).join(".")||"the plan";return t(`is no plan plan --out kept (${o}: ${i?.message??"refused"})`)}return{saved:s.data}}function Wt(e,t){return{code:"PLAN_STALE",message:`The plan kept in ${e} ${t}. Nothing was written: plan again.`.slice(0,8e3),exit:1}}function qh(e,t,n){if(e.plan.refusal!==void 0)return{code:"PLAN_REFUSED",message:`The plan kept in ${t} was refused when it was made: ${e.plan.refusal} Nothing was written: plan again.`.slice(0,8e3),exit:1};if(e.plan.quick===!0)return Wt(t,"was made with --quick, which counts nothing an apply is held to");if(e.sandforgeVersion!==n.sandforgeVersion)return Wt(t,`was made by SandForge ${e.sandforgeVersion}, and this one is ${n.sandforgeVersion}, which may read the file and the org otherwise`);if(n.now-Date.parse(e.madeAt)>Lh)return Wt(t,`was made at ${e.madeAt}, more than a day ago`)}function DE(e){return e.found?`the state at serial ${e.serial}`:"no state"}function zh(e,t,n){let r=e.plan.org;if(!de(r.organizationId,n.target.organizationId))return{code:"PLAN_OTHER_ORG",message:`The plan kept in ${t} was made for ${r.alias??r.organizationId} (${r.organizationId}), and ${n.target.alias} is ${n.target.organizationId}: a plan is applied to the org it was made for. Nothing was written.`,exit:1};if(e.file.digest!==n.digest)return Wt(t,"was made from another file: the file, or a variable or an alias it reads, changed since");let s=n.state,i=e.state;if(!(i.found===(s!==void 0)&&(!i.found||s!==void 0&&s.serial===i.serial&&s.lineage===i.lineage))){let a=s===void 0?"none":i.found&&s.lineage!==i.lineage?`at serial ${s.serial}, made again since`:`at serial ${s.serial}`;return Wt(t,`was made against ${DE(i)}, and the state is now ${a}: an apply or a destroy ran since, or a cache put back another state`)}}function Th(e){return JSON.stringify([e.kind,e.action,e.objects.map(t=>[t.object,t.wouldCreate,t.atMost,t.present,t.gone,t.changed]),(e.draws??[]).map(t=>[t.lookup,t.from,t.object,t.parents])])}function Ph(e){if(e===void 0)return"nothing of it";let t=Aa(e),n=(e.draws??[]).map(s=>s.parents!==void 0?`${s.lookup} under ${s.parents} ${s.object} record(s) of ${s.from}`:`${s.lookup} under the ${s.object} records ${s.from} creates first`).join(", "),r=[t,n].filter(Boolean).join("; ");return`${e.action}${r?` (${r})`:""}`}function Bs(e){let t=(e.checkpoints??[]).map(n=>`${n.step==="before"?"before the first write":"once applied"} '${n.name}'`+(n.refusal!==void 0?", refused":""));return t.length>0?t.join(", "):"none"}function Ks(e){let t=e.drift;return t===void 0?"not compared":t.unread!==void 0?"not read":t.differs?`differs, ${t.toDelete??0} to delete \xB7 ${t.toGiveBack??0} to give back \xB7 ${t.toBringBack??0} to bring back`:"nothing differs"}function Bh(e,t){let n=[],r=[...new Set([...e.actions,...t.actions].map(i=>i.resource))];for(let i of r){let o=e.actions.find(c=>c.resource===i),a=t.actions.find(c=>c.resource===i);o!==void 0&&a!==void 0&&Th(o)===Th(a)||n.push(`${i}: planned ${Ph(o)}, now ${Ph(a)}`)}let s=i=>i.actions.map(o=>o.resource).join(", ");return n.length===0&&s(e)!==s(t)&&n.push(`the order of the resources: planned ${s(e)}, now ${s(t)}`),Bs(e)!==Bs(t)&&n.push(`the checkpoints it takes: planned ${Bs(e)}, now ${Bs(t)}`),Ks(e)!==Ks(t)&&n.push(`the whole org against the checkpoint after the last apply: planned ${Ks(e)}, now ${Ks(t)}`),n}function Kh(e,t){return Wt(e,`is not what the org holds now, read again: ${t.join("; ")}`)}function Uh(e,t){let n=new Date(Date.parse(t.madeAt)+Lh).toISOString();return`plan kept in ${e}, for apply --plan until ${n}`}function Vh(e,t){return`the plan kept in ${e} at ${t.madeAt} holds: the org, its state, the file and every count are as it planned them`}var xE=`sandforge env \u2014 apply a sandforge.yaml to an org: the data an environment needs, declared in
143
+ `,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Ds(t),r=Wt(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Ds(t),r=Wt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};eh.Parser=ua});var ih=C(Vn=>{"use strict";var th=Qo(),eb=Ln(),Un=_n(),tb=Yi(),nb=x(),rb=la(),nh=da();function rh(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new rb.LineCounter||null,prettyErrors:t}}function sb(e,t={}){let{lineCounter:n,prettyErrors:r}=rh(t),s=new nh.Parser(n?.addNewLine),i=new th.Composer(t),o=Array.from(i.compose(s.parse(e)));if(r&&n)for(let a of o)a.errors.forEach(Un.prettifyError(e,n)),a.warnings.forEach(Un.prettifyError(e,n));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function sh(e,t={}){let{lineCounter:n,prettyErrors:r}=rh(t),s=new nh.Parser(n?.addNewLine),i=new th.Composer(t),o=null;for(let a of i.compose(s.parse(e),!0,e.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Un.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(o.errors.forEach(Un.prettifyError(e,n)),o.warnings.forEach(Un.prettifyError(e,n))),o}function ib(e,t,n){let r;typeof t=="function"?r=t:n===void 0&&t&&typeof t=="object"&&(n=t);let s=sh(e,n);if(!s)return null;if(s.warnings.forEach(i=>tb.warn(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:r},n))}function ob(e,t,n){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n=="string"&&(n=n.length),typeof n=="number"){let s=Math.round(n);n=s<1?void 0:s>8?{indent:8}:{indent:s}}if(e===void 0){let{keepUndefined:s}=n??t??{};if(!s)return}return nb.isDocument(e)&&!r?e.toString(n):new eb.Document(e,r,n).toString(n)}Vn.parse=ib;Vn.parseAllDocuments=sb;Vn.parseDocument=sh;Vn.stringify=ob});var ah=C(q=>{"use strict";var ab=Qo(),cb=Ln(),lb=Io(),fa=_n(),ub=kn(),nt=x(),db=Qe(),fb=V(),pb=Ze(),hb=et(),mb=Ns(),gb=aa(),yb=la(),wb=da(),Ts=ih(),oh=gn();q.Composer=ab.Composer;q.Document=cb.Document;q.Schema=lb.Schema;q.YAMLError=fa.YAMLError;q.YAMLParseError=fa.YAMLParseError;q.YAMLWarning=fa.YAMLWarning;q.Alias=ub.Alias;q.isAlias=nt.isAlias;q.isCollection=nt.isCollection;q.isDocument=nt.isDocument;q.isMap=nt.isMap;q.isNode=nt.isNode;q.isPair=nt.isPair;q.isScalar=nt.isScalar;q.isSeq=nt.isSeq;q.Pair=db.Pair;q.Scalar=fb.Scalar;q.YAMLMap=pb.YAMLMap;q.YAMLSeq=hb.YAMLSeq;q.CST=mb;q.Lexer=gb.Lexer;q.LineCounter=yb.LineCounter;q.Parser=wb.Parser;q.parse=Ts.parse;q.parseAllDocuments=Ts.parseAllDocuments;q.parseDocument=Ts.parseDocument;q.stringify=Ts.stringify;q.visit=oh.visit;q.visitAsync=oh.visitAsync});import{existsSync as BE,mkdtempSync as KE,readFileSync as rm,rmSync as UE,writeFileSync as em}from"node:fs";import{tmpdir as VE}from"node:os";import{dirname as Pe,join as kt,resolve as Ba}from"node:path";import{existsSync as Yn,readFileSync as Wb,rmSync as Jb}from"node:fs";import{join as wh}from"node:path";import{join as Nm}from"node:path";import{randomBytes as pm,randomUUID as Gc}from"node:crypto";import{mkdirSync as hm,realpathSync as mm,statSync as ur}from"node:fs";import{open as gm,readFile as ym,readdir as wm,rename as vm,rm as ii}from"node:fs/promises";import{basename as ai,dirname as Ee,join as me,resolve as dr}from"node:path";var km=448,ui=384,di=30,bm=1440*6e4,oi="state.json",Em=/^runs\/[a-z][a-z0-9-]{0,62}\/[1-9][0-9]{0,5}\.summary\.json$/,Sm=/^runs\/[a-z][a-z0-9-]{0,62}\/[1-9][0-9]{0,5}\.summary\.removals\.json$/,Rm=/^templates\/[a-z][a-z0-9-]{0,62}\.[1-9][0-9]{0,5}\.json$/,Vc=/^(?:frozen|dataops)\/[a-z][a-z0-9-]{0,62}$/,F=class extends Error{constructor(n,r){super(r);this.code=n;this.name="EnvStateError"}code};function fr(e=process.env){return Ee(_c("env",e))}function pr(e,t){let n=fi(e,t);if(n!==void 0)return`The journal directory ${dr(t)} is inside the repository ${n} that holds the file: the state, the run summaries and the templates of its runs would be committed with it, and they name the org\u2019s records by their ids. Point SANDFORGE_JOURNAL_DIR at a folder outside the repository \u2014 in CI, $RUNNER_TEMP/sandforge \u2014 and keep it between the jobs that apply and destroy, in a cache keyed by the org.`}function fi(e,t){let n;try{n=cr(Wc(e))}catch{return}return new Oe(n).isInsideRepo(Wc(t))?n:void 0}function Wc(e){let t=[],n=dr(e);for(;;)try{return me(mm(n),...t.reverse())}catch{let r=Ee(n);if(r===n)return dr(e);t.push(ai(n)),n=r}}function le(e,t){return`runs/${_e(e)}/${mr(t)}.summary.json`}function pi(e,t){return`runs/${_e(e)}/${mr(t)}.summary.removals.json`}function St(e,t){return`templates/${_e(e)}.${mr(t)}.json`}function hr(e,t,n,r=Gc()){return`env-${_e(e)}-${_e(t)}-${mr(n)}-${r}`}function _e(e){let t=Gt.safeParse(e);if(!t.success)throw new F("invalid",`Not a name of the file: "${e}"`);return t.data}function mr(e){if(!Number.isInteger(e)||e<1||e>999999)throw new F("invalid",`Not a run's rank: ${e}`);return e}function gr(e){return{version:1,env:_e(e.env),lineage:Gc(),serial:0,sandforgeVersion:e.sandforgeVersion,updatedAt:(e.now??new Date).toISOString(),org:{organizationId:xe(e.org.organizationId),kind:e.org.kind,username:e.org.username,...e.org.alias!==void 0?{alias:e.org.alias}:{}},file:{digest:e.fileDigest},resources:{}}}function en(e){return(e?.runs.at(-1)?.n??0)+1}function tn(e,t){let n=e.resources[t.resource],r={...t.run,n:en(n),objects:[]};return wr(e,t.resource,{kind:t.kind,fingerprint:t.fingerprint,dependsOn:[...t.dependsOn],status:"applying",runs:[...n?.runs??[],r]})}function hi(e,t){let n=e.resources[t];if(n===void 0)throw new F("invalid",`The state holds no resource ${t} to take back`);return wr(e,t,{...n,status:"destroying"})}function yr(e,t,n){let r=e.resources[t];if(r===void 0)throw new F("invalid",`The state holds no resource ${t}`);let s=r.runs.map(i=>i.n===n?{...i,takenBack:!0}:i);return wr(e,t,{...r,runs:s})}function Rt(e,t){let n=e.resources[t.resource];if(n===void 0)throw new F("invalid",`The state holds no resource ${t.resource}`);let r=[...n.runs],s=r.at(-1);if(t.run!==void 0){if(s===void 0)throw new F("invalid",`The resource ${t.resource} has no run to end`);r[r.length-1]={...s,...t.run}}return wr(e,t.resource,{...n,status:t.status,runs:r})}function wr(e,t,n){return{...e,resources:{...e.resources,[_e(t)]:n}}}function mi(e){if(e.org.kind==="scratch")return new Date(Date.parse(e.updatedAt)+di*bm).toISOString()}function vr(e){if(e.fileFolder!==null){let r=pr(e.fileFolder,e.journalDir);if(r!==void 0)return{refusal:r}}let t=new ci(e),n=Zt(t.root,e.uid??Hc);return n!==void 0?{refusal:n}:{store:t}}var ci=class{root;fileFolder;uid;renameFile;now;constructor(t){this.root=me(dr(t.journalDir),"env"),this.fileFolder=t.fileFolder,this.uid=t.uid??Hc,this.renameFile=t.rename??((n,r)=>vm(n,r)),this.now=t.now??Date.now}folderOf(t,n){let r=Jc(t);if(r===void 0)throw new F("invalid",`Not an Organization Id: "${t}"`);return me(this.root,r,_e(n))}fileOf(t,n,r){if(!Em.test(r)&&!Rm.test(r)&&!Sm.test(r))throw new F("invalid",`Not a file of a state's folder: "${r}"`);return me(this.folderOf(t,n),...r.split("/"))}async read(t,n){let r=this.folderOf(t,n),s=me(r,oi),i;try{i=await ym(s,"utf8")}catch(o){if(li(o)==="ENOENT")return;throw o}return $m(i,s,r)}stateFileOf(t,n){return me(this.folderOf(t,n),oi)}async setAside(t,n){if(this.fileFolder===null)throw new F("invalid","The states were opened to be listed, not written");let r=this.stateFileOf(t,n),s=new Date(this.now()).toISOString().replace(/\.\d{3}Z$/,"").replace(/[-:]/g,"").replace("T","-"),i=`${r}.damaged-${s}`;for(let o=2;ur(i,{throwIfNoEntry:!1})!==void 0;o++)i=`${r}.damaged-${s}-${o}`;return await this.renameFile(r,i),i}async write(t,n){if(this.fileFolder===null)throw new F("invalid","The states were opened to be listed, not written");if(t.lineage!==n.lineage)throw new F("invalid","A state is written over its own lineage only");let r=this.folderOf(t.org.organizationId,t.env),s=await this.read(t.org.organizationId,t.env),i=s?.serial??0;if(i!==n.serial||s!==void 0&&s.lineage!==n.lineage){let a=s===void 0?"it is gone":s.lineage!==n.lineage?"it is another state, made since":`serial ${i}, not ${n.serial}`;throw new F("moved",`The state of ${t.env} on ${t.org.organizationId} changed since it was read (${a}): another apply or destroy ran, or a cache put back another state. Nothing was written: plan again.`)}let o=Ht.safeParse({...t,org:{...t.org,organizationId:xe(t.org.organizationId)},serial:n.serial+1,updatedAt:new Date(this.now()).toISOString()});if(!o.success)throw new F("invalid",`Not a state: ${o.error.message}`);for(let a of[Ee(r),r]){let c=Zt(a,this.uid);if(c!==void 0)throw new F("folder",c)}return await this.writeWhole(me(r,oi),`${JSON.stringify(o.data,null,2)}
144
+ `),o.data}async update(t,n){return this.write(n(t),t)}async writeFile(t,n,r,s){if(this.fileFolder===null)throw new F("invalid","The states were opened to be listed, not written");let i=this.fileOf(t,n,r),o=this.folderOf(t,n);for(let a of[Ee(o),o,Ee(i)]){let c=Zt(a,this.uid);if(c!==void 0)throw new F("folder",c)}return await this.writeWhole(i,s),i}async prepareFile(t,n,r){if(this.fileFolder===null)throw new F("invalid","The states were opened to be listed, not written");let s=this.fileOf(t,n,r),i=this.folderOf(t,n);for(let o of[Ee(i),i,Ee(s)]){let a=Zt(o,this.uid);if(a!==void 0)throw new F("folder",a)}return s}async prepareFolder(t,n,r){if(this.fileFolder===null)throw new F("invalid","The states were opened to be listed, not written");if(!Vc.test(r))throw new F("invalid",`Not a folder of a state's folder: "${r}"`);let s=this.folderOf(t,n),i=me(s,...r.split("/"));for(let o of[Ee(s),s,Ee(i),i]){let a=Zt(o,this.uid);if(a!==void 0)throw new F("folder",a)}return i}sasOf(t,n,r){if(!Vc.test(r))throw new F("invalid",`Not a folder of a state's folder: "${r}"`);return me(this.folderOf(t,n),...r.split("/"))}async remove(t,n){let r=this.folderOf(t,n);return ur(r,{throwIfNoEntry:!1})===void 0?!1:(await ii(r,{recursive:!0,force:!0}),!0)}async list(){let t=[];for(let n of await Yc(this.root))if(Jc(n)===n)for(let r of await Yc(me(this.root,n))){if(!Gt.safeParse(r).success)continue;let s=me(this.root,n,r);try{let i=await this.read(n,r);if(i===void 0)continue;let o=mi(i);t.push({organizationId:n,env:r,folder:s,state:i,...o!==void 0?{expiresAt:o}:{}})}catch(i){t.push({organizationId:n,env:r,folder:s,damaged:Qc(i)})}}return t}async sweep(){let t=this.now(),n=[];for(let{state:r,expiresAt:s,folder:i,organizationId:o,env:a}of await this.list())r===void 0||s===void 0||Date.parse(s)>t||(await ii(i,{recursive:!0,force:!0}),n.push({organizationId:o,env:a,...r.org.alias!==void 0?{alias:r.org.alias}:{},updatedAt:r.updatedAt,expiresAt:s}));return n}async writeWhole(t,n){let r=`${t}.${process.pid}-${pm(4).toString("hex")}.tmp`,s=await gm(r,"wx",ui);try{try{await s.writeFile(n,"utf8"),await s.sync()}finally{await s.close()}await this.renameFile(r,t)}catch(i){throw await ii(r,{force:!0}),i}}};function $m(e,t,n){let r;try{r=JSON.parse(e)}catch{r=void 0}let s=Ht.safeParse(r);if(!s.success)throw new F("damaged",`The state ${t} does not read as a state of this SandForge, and is not used: a plan made from part of it would create again what the rest names. Run ${ce("env")} state recover: it sets this file aside and rebuilds the state from the run files beside it.`);let i=s.data;if(xe(i.org.organizationId)!==ai(Ee(n))||i.env!==ai(n))throw new F("otherOrg",`The state ${t} is of ${i.env} on ${i.org.organizationId}, not of the org and environment its folder names: it was copied or moved, and is not used. Put it back where it came from, or delete it.`);return i}function Hc(){return process.getuid?.()}function Zt(e,t){try{let n=ur(e,{throwIfNoEntry:!1});if(n!==void 0&&!n.isDirectory())return`${e} is not a folder.`;hm(e,{recursive:!0,mode:km});let r=t();return r!==void 0&&ur(e).uid!==r?`${e} belongs to another user, who can read the states kept there and replace them: point SANDFORGE_JOURNAL_DIR at a folder of your own.`:void 0}catch(n){return`${e} could not be made: ${Qc(n)}`}}function Jc(e){try{return xe(e)}catch{return}}async function Yc(e){try{return(await wm(e,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name).sort()}catch(t){if(li(t)==="ENOENT"||li(t)==="ENOTDIR")return[];throw t}}function li(e){return e?.code}function Qc(e){return e instanceof Error?e.message:String(e)}import{createHash as Am}from"node:crypto";function nn(e){return e.length===0?"the file":e.map((t,n)=>typeof t=="number"?`[${t}]`:/^[A-Za-z_][A-Za-z0-9_-]*$/.test(t)?`${n===0?"":"."}${t}`:`[${JSON.stringify(t)}]`).join("")}function P(e,t){let n=e[0]==="resources"&&typeof e[1]=="string"?e[1]:void 0;return{path:e,...n!==void 0?{resource:n}:{},message:t}}function $t(e){return JSON.stringify(gi(e))}function gi(e){if(Array.isArray(e))return e.map(gi);if(e===null||typeof e!="object")return e;let t=e;return Object.fromEntries(Object.keys(t).filter(n=>t[n]!==void 0).sort().map(n=>[n,gi(t[n])]))}function yi(e){return Am("sha256").update(e,"utf8").digest("hex")}var Om=200;function N(e,t){if(t===""||t.startsWith("-"))throw new Error(`${e} cannot be "${t}": a value that starts with "-" reads as a flag.`);return t}function Ce(e){return e.sweep===!0?["--sweep"]:[]}var qe=p.string().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),A=p.number().int().nonnegative(),At=p.object({objectApiName:p.string().min(1),planned:A,deleted:A,alreadyGone:A,keptChanged:A,keptDependents:A,refused:A,notVisible:A.optional(),notReached:A.optional(),heldBy:p.array(p.string()),reasons:p.array(p.string())}),Cm=p.object({objectApiName:p.string().min(1),planned:A,toDelete:A,alreadyGone:A,changedSince:A,keptChanged:A,changedBy:p.record(qe,A),undeletable:A,notVisible:A,unread:A,reasons:p.array(p.string())}),Ot=p.object({planned:A,objects:p.array(Cm),undeletable:p.array(p.object({objectApiName:p.string().min(1),records:A})).optional(),userNames:p.record(qe,p.string())});function ze(e,t,n){if(t===void 0||n?.length!==t.length)return[];let r=t.flatMap((s,i)=>{let o=n[i];return o!==void 0&&o!==""&&s!==""&&e.includes(s)?[o]:[]});return[...new Set(r)]}var jm=/^Nothing(?: was)? (?:written|deleted)\.?$/i;function Xc(e){return e.split(`
145
+ `).map(t=>t.trim()).filter(t=>t!==""&&!jm.test(t)).at(-1)}var re=class extends Error{constructor(n,r,s,i){super(`${Te(n)} did not answer ${r} (${s}): `+(i===""?"it printed nothing on stdout":`it printed ${JSON.stringify(i)}`));this.script=n;this.expected=r;this.reason=s;this.excerpt=i;this.name="StepAnswerError"}script;expected;reason;excerpt};function z(e,t,n,r){let s=r.trim().slice(0,Om),i;try{i=JSON.parse(r)}catch{throw new re(e,t,"not JSON",s)}let o=n.safeParse(i);if(!o.success){let a=o.error.issues[0],c=a?.path.join(".")||"the answer";throw new re(e,t,`${c}: ${a?.message??"refused"}`,s)}return o.data}var ue="sandforge-checkpoint";function ge(e){return Nm(e,"checkpoints")}function Im(e){return e==="scratch"?di:0}function rn(e,t){if(t==="before")return e.checkpoint?.before===!0?`${e.name} before`:void 0;let n=e.checkpoint?.after;return typeof n=="string"?n:void 0}function sn(e){return["--org",N("--org",e.org),"--store",N("--store",e.store)]}function kr(e){let{ignoreFields:t,maxTotal:n,excludeObjects:r}=e.checkpoint??{};return{...t!==void 0?{ignoreFields:t}:{},...n!==void 0?{maxTotal:n}:{},...r!==void 0?{excludeObjects:r}:{}}}function Zc(e){return[...(e.ignoreFields??[]).flatMap(t=>["--ignore-field",N("--ignore-field",t)]),...e.maxTotal!==void 0?["--max-total",String(e.maxTotal)]:[],...(e.excludeObjects??[]).flatMap(t=>["--exclude-object",N("--exclude-object",t)])]}function el(e){return["take",...sn(e),...Zc(e),"--estimate","--json"]}function Dm(e){return["take",...sn(e),"--name",N("--name",e.name),"--keep-days",String(e.keepDays),...Zc(e),"--json"]}function vi(e){if(e.code!=="TOO_MANY_RECORDS")return e;let t=e.message.indexOf(": pick fewer objects"),n=t===-1?e.message.replace(/\s*No record was read\.$/,""):e.message.slice(0,t);return{...e,message:`${n}: leave objects out with checkpoint.excludeObjects, or raise checkpoint.maxTotal in the file, ${Xa.toLocaleString("en-US")} at most. No record was read.`}}function tl(e){return["preview",...sn(e),"--checkpoint",ct.parse(e.checkpoint),"--json"]}function ki(e){return["rewind",...sn(e),"--checkpoint",ct.parse(e.checkpoint),e.dryRun?"--dry-run":"--yes",...e.acceptAutomation?["--accept-automation"]:[],...e.acceptEmails===!0?["--accept-emails"]:[],...e.acceptNoUndo?["--accept-no-undo"]:[],...e.acceptUnseen===!0?["--accept-unseen"]:[],"--json"]}function Pm(e){return["delete",...sn(e),"--checkpoint",ct.parse(e.checkpoint),"--yes","--json"]}var bi=p.object({code:p.string().min(1),message:p.string().min(1)}),on=p.object({refusal:bi}),Tm=p.union([p.object({mode:p.string(),estimate:p.object({records:A,apiRequests:A,apiRequestsLeft:p.number(),seconds:p.number().nonnegative(),bytes:A}),refusal:bi.optional()}),on]),Fm=p.union([p.object({checkpoint:p.object({checkpointId:ct,name:p.string().min(1),takenAt:p.string().min(1)})}),on]),Lm=p.union([p.object({checkpoint:p.object({id:ct,name:p.string().min(1),takenAt:p.string().min(1)}),toDelete:A,toGiveBack:A,toBringBack:A,toRecreate:A,differs:p.boolean(),diff:p.object({objects:p.array(p.object({objectApiName:p.string().min(1),lastChangedBy:p.record(p.string(),A),touched:A})),userNames:p.record(p.string(),p.string())}),refusal:bi.optional()}),on]),wi=p.object({planned:A,done:A,left:A}),xm=p.union([p.object({checkpoint:p.object({id:ct,name:p.string().min(1)}),rewindId:p.string().min(1),status:p.enum(["success","partial","unstable","failure","cancelled"]),deleted:wi,givenBack:wi,broughtBack:wi,undo:p.object({until:p.string().min(1)}).optional(),residual:p.array(p.object({object:p.string(),reason:p.string(),count:A}))}),on]),Mm=p.union([p.object({deleted:p.array(p.string()),kept:p.array(p.string())}),on]);function _m(e){return z(ue,"the estimate of a take",Tm,e)}function qm(e){return z(ue,"a take",Fm,e)}function nl(e){return z(ue,"a preview",Lm,e)}function zm(e){return z(ue,"a rewind",xm,e)}function Bm(e){return z(ue,"a deletion",Mm,e)}function Km(e){return e.stderr.trim().split(`
146
+ `).map(t=>t.trim()).filter(Boolean).at(-1)??"it said nothing"}function Ct(e,t){try{return{answer:t(e.stdout),raw:JSON.parse(e.stdout)}}catch(n){if(!(n instanceof re))throw n;return{unread:`exit ${e.code}: ${Km(e)}`}}}function br(e,t,n){let r=[],s=rn(e,"before");s!==void 0&&n&&Um(t)&&r.push({step:"before",name:s});let i=rn(e,"after");return i!==void 0&&(n||t?.checkpoints?.after===void 0)&&r.push({step:"after",name:i}),r}function rl(e){return Object.values(e?.resources??{}).some(t=>t.status!=="destroyed")}function Um(e){return e?.checkpoints?.before===void 0&&!rl(e)}function sl(e,t){return e.checkpoint?.before!==!0||t?.checkpoints?.before!==void 0?[]:rl(t)?["checkpoint.before is taken before the first apply of an environment, and the org holds what an earlier apply wrote without one: it is not taken now, since a rewind to it would keep those records. Destroy the environment, then apply, to take it"]:[]}function il(e){let t=Ct(e,_m);if("unread"in t)return t;let n=t.answer;if(!("estimate"in n))return{refusal:vi(n.refusal)};let{records:r,apiRequests:s,seconds:i,bytes:o}=n.estimate;return{estimate:{records:r,apiRequests:s,seconds:i,bytes:o},...n.refusal!==void 0?{refusal:vi(n.refusal)}:{}}}function ol(e,t,n=0){return e.map(({step:r,name:s})=>t===void 0?{step:r,name:s,unread:"not read: --quick"}:"unread"in t?{step:r,name:s,unread:t.unread}:{step:r,name:s,..."estimate"in t?{estimate:r==="after"?{...t.estimate,records:t.estimate.records+n}:t.estimate}:{},...t.refusal!==void 0?{refusal:t.refusal}:{}})}var Er={before:"before the first write",after:"once applied"};function al(e){let t=e.filter(n=>n.refusal!==void 0);if(t.length!==0)return t.map(n=>`The checkpoint the file asks ${Er[n.step]}, '${n.name}', would be refused: ${n.refusal?.message??""}`).join(" ")+" Take checkpoint.before or checkpoint.after out of the file, or fix what refuses it."}function cl(e){let t=0,n=[];for(let r of e)r.estimate!==void 0?t+=r.estimate.apiRequests:n.push(`the checkpoint ${Er[r.step]}, not estimated`);return{estimate:t,notCounted:n}}function ll(e,t){let n=Ct(t,nl);if("unread"in n)return{checkpoint:e,differs:!1,unread:n.unread};let r=n.answer;return"differs"in r?{checkpoint:e,differs:r.differs,toDelete:r.toDelete,toGiveBack:r.toGiveBack,toBringBack:r.toBringBack}:{checkpoint:e,differs:!1,unread:r.refusal.message}}var Se=e=>e.toLocaleString("en-US");function ul(e){let t=[];for(let r of e.checkpoints??[]){let s=`checkpoint ${Er[r.step]}: '${r.name}'`,{estimate:i}=r;i!==void 0?t.push(`${s}, about ${Se(i.records)} records, ${Se(i.apiRequests)} API requests, ${Se(Math.ceil(i.seconds))} s, ${lt(i.bytes/(1024*1024))} MB on this machine`):t.push(`${s}, not estimated (${r.unread??"no estimate"})`),r.refusal!==void 0&&t.push(` refused: ${r.refusal.message}`)}let n=e.drift;if(n!==void 0){let r=`the whole org against the checkpoint after the last apply (${n.checkpoint})`;t.push(n.unread!==void 0?`${r}: not compared, ${n.unread}`:n.differs?`${r}: differs, ${Se(n.toDelete??0)} to delete \xB7 ${Se(n.toGiveBack??0)} to give back \xB7 ${Se(n.toBringBack??0)} to bring back`:`${r}: nothing differs among the objects and fields it compares`)}return t}async function Ei(e,t,n){e.say(`checkpoint ${Er[t.step]}: taking '${t.name}'`);let r=await e.runner(ue,Dm({org:t.org.alias,store:ge(e.journalDir),name:t.name,keepDays:Im(t.org.kind),...t.ignoreFields!==void 0?{ignoreFields:t.ignoreFields}:{},...t.maxTotal!==void 0?{maxTotal:t.maxTotal}:{},...t.excludeObjects!==void 0?{excludeObjects:t.excludeObjects}:{}}),n),s=Ct(r,qm),i="answer"in s?s.answer:void 0,o="raw"in s?s.raw:void 0;if(r.code===0&&i!==void 0&&"checkpoint"in i)return{result:{step:t.step,checkpoint:i.checkpoint.checkpointId,exitCode:r.code,answer:o},checkpoint:i.checkpoint.checkpointId};let a=i!==void 0&&"refusal"in i?`${i.refusal.code}: ${vi(i.refusal).message}`:"unread"in s?s.unread:`exit ${r.code}`;return{result:{step:t.step,exitCode:r.code===0?1:r.code,refusal:a.slice(0,4e3),...o!==void 0?{answer:o}:{}}}}async function jt(e,t,n){e.say(`checkpoint ${t.checkpoint}: deleted from this machine, ${t.why}`);let r=await e.runner(ue,Pm({org:t.org.alias,store:ge(e.journalDir),checkpoint:t.checkpoint}),n),s=Ct(r,Bm),i="answer"in s?s.answer:void 0,o=i!==void 0&&"deleted"in i&&i.deleted.includes(t.checkpoint),a=i!==void 0&&"refusal"in i&&i.refusal.code==="NOT_FOUND";if(o||a)return{step:"delete",checkpoint:t.checkpoint,exitCode:0};let c=i!==void 0&&"refusal"in i?`${i.refusal.code}: ${i.refusal.message}`:i!==void 0&&"kept"in i?"kept: a take, a rewind or an undo of the org is running":"unread"in s?s.unread:`exit ${r.code}`;return e.say(` not deleted: ${c}`),{step:"delete",checkpoint:t.checkpoint,exitCode:r.code===0?1:r.code,refusal:c.slice(0,4e3)}}function Sr(e){let t=[];return e?.checkpoints?.after!==void 0&&t.push({step:"after",checkpoint:e.checkpoints.after}),e?.checkpoints?.before!==void 0&&t.push({step:"before",checkpoint:e.checkpoints.before}),t}function Be(e,t,n){let r={...e.checkpoints};n!==void 0?r[t]=n:delete r[t];let s={...e,checkpoints:r};return Object.keys(r).length===0&&delete s.checkpoints,s}function dl(e){let t=Ct(e,nl);if("unread"in t)return{refusal:t.unread};let n=t.answer;if(!("differs"in n))return{refusal:n.refusal.message};let r={};for(let s of n.diff.objects)for(let[i,o]of Object.entries(s.lastChangedBy)){let a=n.diff.userNames[i]??i;r[a]=(r[a]??0)+o}return{checkpoint:n.checkpoint,toDelete:n.toDelete,toGiveBack:n.toGiveBack,toBringBack:n.toBringBack,lastChangedBy:r,differs:n.differs,...n.refusal!==void 0?{refusal:n.refusal}:{}}}function Rr(e){return Object.entries(e).sort((t,n)=>n[1]-t[1]).map(([t,n])=>`${t} ${Se(n)}`).join(", ")}function fl(e,t,n){let r=`'${n.checkpoint.name}' (${n.checkpoint.id}), taken ${n.checkpoint.takenAt}`,s=[e==="reset"?`reset ${t} to the checkpoint taken after the last apply, ${r}:`:`destroy by rewinding ${t} to the checkpoint taken before the first apply, ${r}:`,` ${Se(n.toDelete)} to delete \xB7 ${Se(n.toGiveBack)} to give back \xB7 ${Se(n.toBringBack)} to bring back`+(n.differs?"":" \u2014 nothing differs: nothing to rewind")],i=Rr(n.lastChangedBy);return i!==""&&s.push(` last changed by: ${i}`),n.refusal!==void 0&&s.push(` refused: ${n.refusal.message}`),s}function pl(e){let t=Ct(e,zm),n="answer"in t?t.answer:void 0,r="raw"in t?t.raw:void 0;if(n!==void 0&&"status"in n)return{exitCode:e.code,status:n.status,answer:r,done:{deleted:n.deleted.done,givenBack:n.givenBack.done,broughtBack:n.broughtBack.done,differing:n.residual.reduce((i,o)=>i+o.count,0)},...n.undo!==void 0?{undoUntil:n.undo.until}:{}};let s=n!==void 0&&"refusal"in n?n.refusal:{code:"UNREAD",message:"unread"in t?t.unread:`exit ${e.code}`};return{exitCode:e.code===0?1:e.code,status:e.code>=128?"cancelled":"failure",...r!==void 0?{answer:r}:{},refusal:s}}function hl(e,t){return e.deleted?{offered:!1,why:"the environment\u2019s checkpoints are deleted with it, the journal of this rewind among them: a destroy is undone by applying again"}:t.undoUntil===void 0?{offered:!1,why:t.status==="failure"||t.status==="cancelled"?"the checkpoint script offers no undo of a rewind that wrote nothing it can take back":"the checkpoint script offers none: the rewind wrote nothing"}:{offered:!0,until:new Date(Date.parse(t.undoUntil)).toISOString(),line:`${ce("checkpoint")} undo --org ${e.alias} --checkpoint ${e.checkpoint} --store ${ge(e.journalDir)}`}}function ml(e){return e.offered?`undo it until ${e.until}, sooner if the recycle bin fills: ${e.line}`:`no undo: ${e.why}`}var $r="STATE_MOVED",gl="No flag lifts this: an environment is never applied to a production org.";function de(e,t){return e.length>=15&&t.length>=15&&e.slice(0,15)===t.slice(0,15)}function yl(e,t,n){if("unread"in t)return t.error!==void 0&&rc(t.error)!==void 0?{refusal:{code:"UNTYPED",message:ac(e,t.error,{tool:"sandforge env",action:"write",readOnly:"plan"}),exit:1}}:{refusal:{code:"PRODUCTION",message:`${e} did not say what org it is (${t.unread}), and an environment is applied to no org it cannot tell from a production one. Nothing was read or written. ${gl}`,exit:1}};if(sr(t)){let s=t.edition?`IsSandbox false, edition ${t.edition}`:"IsSandbox false, and no edition";return{refusal:{code:"PRODUCTION",message:`${e} is a production org (its Organization record says ${s}): an environment is applied to scratch orgs, Developer Edition orgs and the sandboxes its file lists. Nothing was read or written. ${gl}`,exit:1}}}let r=t.sandbox?n.scratch===!0?"scratch":"sandbox":"developer";return{target:{alias:e,organizationId:t.id,kind:r,username:n.username}}}var wl={scratch:"a scratch org",developer:"a Developer Edition org",sandbox:"a sandbox"};function vl(e,t){let n=t.organizationId;if(e.protect.some(r=>de(r,n)))return{code:"PROTECTED",message:`${t.alias} (${xe(n)}) is listed under targets.protect: the file refuses it whatever else it says. Nothing was read or written.`,exit:1};if(!e.kinds.includes(t.kind)){let r=t.kind==="sandbox"?" If it is a scratch org, the sf CLI did not say so: its display names no Dev Hub for it, as when the org was logged in with an auth URL alone. Log its Dev Hub in on this machine, or list the org as a sandbox.":"";return{code:"KIND",message:`${t.alias} is ${wl[t.kind]}, and the file's targets.kinds allows ${e.kinds.join(", ")}: add ${t.kind} to targets.kinds to apply it there. Nothing was read or written.${r}`,exit:1}}if(t.kind==="sandbox"&&!e.sandboxes.some(r=>de(r,n)))return{code:"NOT_LISTED",message:`${t.alias} is a sandbox, and its Organization Id ${xe(n)} is not listed under targets.sandboxes: nothing Salesforce says tells a sandbox that holds a client's records from a developer's, so each one the file writes to is listed, reviewed with the file. A refresh changes the Id: a sandbox listed before its refresh is listed again. Nothing was read or written. If it is a scratch org, the sf CLI did not say so: its display names no Dev Hub for it, as when the org was logged in with an auth URL alone.`,exit:1}}function Ke(e){return{code:e.code==="otherOrg"?"OTHER_ORG":"STATE_DAMAGED",message:`${e.message} Nothing was read or written in the org.`,exit:1}}function kl(e,t,n){if(!(e.env===t&&de(e.org.organizationId,n.organizationId)))return{code:"OTHER_ORG",message:`The state read for ${t} on ${n.alias} is of ${e.env} on ${e.org.organizationId}: a state of another org is never applied. Nothing was read or written.`,exit:1}}function bl(e,t,n,r=!1){let s=`this machine keeps no state of ${t} on ${e.alias}: records an earlier apply left there, from another machine or a cache that was not restored, cannot be told from the org\u2019s own, and would be created twice`+(r?`; it keeps runs of ${t} on ${e.alias}, and ${ce("env")} state recover rebuilds the state from them`:"");return e.kind==="scratch"||n?{warning:s}:{refusal:{code:"NO_STATE",message:`${s.charAt(0).toUpperCase()}${s.slice(1)}. On ${wl[e.kind]} that lives on, apply asks --accept-no-state to go ahead: restore the journal directory of the apply before it, or give the flag. Nothing was written.`,exit:1}}}function Ar(e,t){return t?{code:"STORE_IN_REPOSITORY",message:e,exit:2}:{code:"STORE",message:e,exit:1}}function Ue(e){return{code:"LOCKED",message:Dc(e),exit:1}}function an(e){return{code:"CHECKPOINT_ACT",message:`${e.charAt(0).toUpperCase()}${e.slice(1)}`,exit:1}}import{readFileSync as Vm}from"node:fs";import{join as Sl}from"node:path";var U="sandforge-clone",Rl=1e4,El=1e6,Wm=["inputMode","recordId","soqlQuery","queryScope","maxRoots","templateId","aiPrompt","dryRun"];function Jm(e){let[t]=e;return`SELECT Id FROM ${t?.object??""}${t?.where!==void 0?` WHERE ${t.where}`:""}`}function Ym(e,t,n){let r=["resources",e,"template"],s=u=>({refusals:[P(r,u)]}),i;try{i=Vm(Sl(n,t.file),"utf8")}catch(u){return s(`${t.file} cannot be read: ${u instanceof Error?u.message:String(u)}`)}if(i.length>El)return s(`${t.file} is larger than ${El} bytes`);let o;try{o=JSON.parse(i.replace(/^\uFEFF/,""))}catch{return s(`${t.file} is not JSON`)}let a=Array.isArray(o)?o:[o],c=a.find(u=>u!==null&&typeof u=="object"&&u.id===t.id);if(c===void 0){let u=a.map(d=>d!==null&&typeof d=="object"?d.id:"").filter(d=>typeof d=="string"&&d!=="");return s(`${t.file} holds no template "${t.id}"`+(u.length>0?`: it holds ${u.join(", ")}`:": it holds none"))}let l=Qs.safeParse(c);return l.success?{entry:l.data}:{refusals:l.error.issues.map(u=>P(r,`the template "${t.id}" of ${t.file} is refused by Forge's template schema at ${u.path.map(String).join(".")||"its top"}: ${u.message}`))}}function $l(e,t,n,r,s){let i=["resources",t],o=[];if(n.depth==="all")return{run:{source:n.source,wholeOrg:{anonymize:n.anonymize!==void 0,keepContactPoints:n.keepContactPoints===!0,...n.fit!==void 0?{fit:n.fit==="share"?{}:structuredClone(n.fit)}:{}},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{},acceptAutomation:n.accept?.automation===!0,acceptRealData:n.accept?.realData===!0},warnings:o};let a;if(n.template!==void 0){let g=Ym(t,n.template,r);if("refusals"in g)return g;a=g.entry}let c={...a?.config};for(let g of Wm)delete c[g];if(n.tables!==void 0&&c.expandOrphanParents===!0)return{refusals:[P([...i,"template"],"the template brings orphan parents (expandOrphanParents), which go with a clone of one record: a clone of tables reads the parents its tables point at, named with them")]};a?.files!==void 0&&o.push(P([...i,"template"],"the template copies the files of the cloned records: an environment copies none, and the clone writes the records alone"));let l=n.depth??c.depth,u=(l??"custom")==="custom"?n.customDepth??c.customDepth:void 0;delete c.customDepth;let d=s.toISOString(),f={id:`env-${e}-${t}`,name:`${e}/${t}`,description:`The ${t} resource of the ${e} environment`,config:{anonymizePII:!1,skipEmpty:!0,batchSize:"auto",...c,...n.tables!==void 0?{inputMode:"soql",soqlQuery:Jm(n.tables)}:{inputMode:"record",...n.record?.id!==void 0?{recordId:n.record.id}:{}},depth:l??"custom",...u!==void 0?{customDepth:u}:{},...n.maxNodes!==void 0?{maxNodes:n.maxNodes}:{},...n.keepContactPoints!==void 0?{keepContactPoints:n.keepContactPoints}:{},...n.anonymize!==void 0?{anonymizePII:!0}:{}},...n.anonymize!==void 0?{anonymization:structuredClone(n.anonymize)}:a?.anonymization!==void 0?{anonymization:structuredClone(a.anonymization)}:{},objectCount:0,recordCount:0,createdAt:d,lastUsedAt:d},y=Qs.safeParse(f);return y.success?{run:{source:n.source,template:y.data,...n.record!==void 0?{record:{...n.record}}:{},...n.records!==void 0?{records:{...n.records}}:{},...n.tables!==void 0?{tables:n.tables.map(g=>({...g}))}:{},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{},acceptAutomation:n.accept?.automation===!0,acceptRealData:n.accept?.realData===!0},warnings:o}:{refusals:y.error.issues.map(g=>P(i,`the template it converts into is refused by Forge's template schema at ${g.path.map(String).join(".")||"its top"}: ${g.message}`))}}function Al(e){return e.tables!==void 0?e.tables.map(t=>({object:t.object})):e.records!==void 0?[{object:e.records.object}]:e.record?.object!==void 0?[{object:e.record.object}]:[]}function Or(e){return wc(e.object,{...e.where!==void 0?{where:e.where}:{},...e.orderBy!==void 0?{orderBy:e.orderBy}:{},limit:e.limit},void 0,e.limit)}function Cr(e,t,n,r){let s=i=>i.replace(/[^A-Za-z0-9_-]/g,"-");return Sl(Oc(e),`env-${s(t.slice(0,15))}-${s(n)}-${s(r)}.json`)}function Ol(e){if(e.wholeOrg)return e.wholeOrg.anonymize;let t=e.template?.anonymization?.rules??{};return e.template?.config.anonymizePII===!0&&Object.values(t).some(n=>n!==void 0)}function Gm(e){return e.edition?`its Organization record says IsSandbox false, edition ${e.edition}`:"its Organization record says IsSandbox false, and no edition"}function Hm(e,t,n){if(e.acceptRealData||Ol(e))return;let r=e.template?.config.anonymizePII===!0?" Its anonymize sets a method for no category of personal field, so it does not count.":"";return`its source, ${t}, is a production org (${Gm(n)}): what it clones is real people\u2019s data, written as read into an org built for tests.${r} Give the resource anonymize \u2014 Forge\u2019s anonymization, a method for each category of personal field \u2014 or, reviewed in the file, accept: { realData: true }. Emails and phone numbers are neutralized either way, unless keepContactPoints: true`}function Cl(e,t){let n=t.read;if(n===void 0||"refusal"in n||n.production!==!0)return[];let r=Object.entries(e.template?.anonymization?.rules??{}).filter(([,o])=>o!==void 0).map(([o,a])=>`${o} ${String(a)}`),s=Ol(e)?e.wholeOrg?"anonymized, every personal field by its category\u2019s default method":`anonymized as its anonymize says (${r.join(", ")})`:"written as read, as the file accepts (accept: { realData: true })",i=e.wholeOrg?e.wholeOrg.keepContactPoints:e.template?.config.keepContactPoints===!0;return[`real data: its source, the ${t.role} org (${t.alias}), is a production org; what it clones is ${s}`,i?"contact points: written as read (keepContactPoints: true)":"contact points: neutralized before writing (emails under .invalid, phone numbers in a fictional range), as the clone does unless keepContactPoints"]}async function jl(e,t,n,r){let s=`the ${n} org (${r})`,i;try{i=await rr(e)}catch(d){return{refusal:`${s} could not be read: ${Si(d)}`}}let o=i.id,a=sr(i);if(a){let d=Hm(t,s,i);if(d!==void 0)return{refusal:d}}let c={organizationId:o,...a?{production:!0}:{}};if(t.records!==void 0){let{records:d}=t;try{let y=(await e.query(Or(d))).records.flatMap(g=>typeof g.Id=="string"?[g.Id]:[]);if(y.length===0){let g=d.where!==void 0?` WHERE ${d.where}`:"";return{refusal:`its records query chooses no ${d.object} in ${s}${g!==""?` (${g.trim()})`:""}: there is nothing to clone. Count what it chooses there with sf data query -o ${r} -q "SELECT COUNT() FROM ${d.object}${g}", and check its where`}}return{...c,roots:{count:y.length,sha256:vc(y)}}}catch(f){return{refusal:`its records query could not be read in ${s}: ${Si(f)}`}}}let l=t.record;if(l?.object===void 0||l.where===void 0)return c;let u=`${l.object} WHERE ${l.where}`;try{let d=(await e.query(`SELECT Id FROM ${u} LIMIT 2`)).records;return d.length===1&&typeof d[0]?.Id=="string"?{...c,recordId:d[0].Id}:d.length===0?{refusal:`its record query finds no ${l.object} in ${s} (WHERE ${l.where}): a record named by a query is one its source answers with exactly one row`}:{refusal:`its record query finds ${(await e.query(`SELECT COUNT() FROM ${u}`)).totalSize} ${l.object} records in ${s} (WHERE ${l.where}), not one: narrow the where to one row, or name the record by its id`}}catch(d){return{refusal:`its record query could not be read in ${s}: ${Si(d)}`}}}function Nl(e,t){let n=t!==void 0&&"organizationId"in t?t:void 0;return{kind:"forge",kindVersion:1,source:n?.organizationId.slice(0,15)??null,record:e.record===void 0?null:(e.record.id??n?.recordId)?.slice(0,15)??{unread:e.record},tables:e.tables??null,config:e.template?.config??null,anonymization:e.template?.anonymization??null,...e.wholeOrg?{wholeOrg:e.wholeOrg}:{},...e.records?{records:{...e.records,roots:n?.roots?.sha256??{unread:!0}}}:{}}}function Il(e){if(e.wholeOrg)return Qm(e,e.wholeOrg);if(e.recordId===void 0&&e.records===void 0&&(e.tables??[]).length===0)throw new Error("A forge resource clones a record, the records a query chooses or tables: its line names none.");return["--source",N("--source",e.source),"--target",N("--target",e.target),...e.recordId!==void 0?["--record",N("--record",e.recordId)]:e.records!==void 0?["--query",N("--query",Or(e.records)),"--max-roots",String(e.records.limit),...e.rootsPlanFile!==void 0?["--roots-plan",N("--roots-plan",e.rootsPlanFile)]:[]]:(e.tables??[]).flatMap(t=>["--object",N("--object",t.object),...t.where!==void 0?["--where",N("--where",t.where)]:[]]),"--template",N("--template",e.templateFile),"--max-total",String(e.maxTotal),"--skip-preflight",...e.acceptAutomation?["--accept-automation"]:[]]}function Qm(e,t){return["--source",N("--source",e.source),"--target",N("--target",e.target),"--depth","all","--config",N("--config",e.templateFile),"--max-total",String(e.maxTotal),"--skip-preflight",t.anonymize?"--anonymize":"--no-anonymize",...t.keepContactPoints?["--keep-contact-points"]:[],...t.fit!==void 0?["--fit","share",...Xm(t.fit)]:[],...e.acceptAutomation?["--accept-automation"]:[]]}function Xm(e){let t=e.window;return[...e.withinMB!==void 0?["--fit-within",String(e.withinMB)]:[],...e.seed!==void 0?["--fit-seed",String(e.seed)]:[],...e.draw!==void 0?["--fit-draw",e.draw]:[],...t!==void 0?["--fit-window",t.lastDays!==void 0?`${t.field}:${t.lastDays}d`:`${t.field}:${t.from??""}..${t.to??""}`]:[],...Object.entries(e.where??{}).flatMap(([n,r])=>["--fit-where",N("--fit-where",`${n}=${r}`)]),...(e.strata??[]).flatMap(n=>["--fit-strata",N("--fit-strata",n)])]}function Dl(e){return[...Il(e),"--dry-run","--json"]}function Pl(e){return[...Il(e),...e.wholeOrg?["--yes"]:[],"--summary",N("--summary",e.summary),"--json"]}function Tl(e){return["--remove",N("--remove",e.summary),"--target",N("--target",e.target),...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[]]}function Fl(e){return[...Tl(e),...Ce(e),"--json"]}function Ll(e){return[...Tl(e),"--preview",...Ce(e),"--json"]}function xl(e){return["--verify",N("--verify",e.summary),"--target",N("--target",e.target),"--source",N("--source",e.source),"--json"]}var Zm=p.enum(["SingleEmail","DailyWorkflowEmails"]),eg=p.object({tool:p.literal(U),version:p.literal(1),dryRun:p.literal(!0),result:p.object({wouldInsertCount:A,failedCount:A}),writePlan:p.object({totalRows:A,storageBytes:A,objects:p.array(p.object({objectApiName:p.string().min(1),rows:A,storageBytes:A,mayAdd:A.optional()})),emails:p.array(p.object({limit:Zm,emails:A})).optional()}).optional(),wouldBeRefused:p.array(p.string()).optional(),wouldBeRefusedCodes:p.array(p.string()).optional(),targetGaps:p.object({gaps:p.array(p.object({kind:p.string().min(1),severity:p.string().min(1),objectApiName:p.string().min(1),field:p.string().min(1).optional()}).loose())}).loose().optional()}),tg=p.object({tool:p.literal(U),version:p.literal(1),dryRun:p.literal(!1),targetOrgId:qe.optional(),result:p.object({successCount:A,failedCount:A,createdByObject:p.array(p.object({objectApiName:p.string().min(1),sourceIds:p.array(qe)})),remapInJournal:p.literal(!0).optional(),createdCountByObject:p.array(p.object({objectApiName:p.string().min(1),created:A})).optional(),errors:p.array(p.object({objectApiName:p.string().min(1),failedCount:A,samples:p.array(p.unknown()).optional()}))}),running:p.literal(!0).optional(),interrupted:p.literal(!0).optional(),error:p.string().optional()}),ng=p.object({tool:p.literal(U),version:p.literal(1),action:p.literal("remove"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),result:p.object({status:p.enum(["success","partial","failure","cancelled"]),planned:A,objects:p.array(At),sweep:p.object({status:p.string()}).loose().optional()}),elapsedMs:A}),rg=p.object({tool:p.literal(U),version:p.literal(1),action:p.literal("remove-preview"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),preview:Ot,refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional(),notes:p.array(p.string()),elapsedMs:A}),sg=p.object({tool:p.literal(U),version:p.literal(1),action:p.literal("verify"),result:p.object({verdict:p.enum(["verified","partial","unstable"]),attempts:A,objects:p.array(p.object({objectApiName:p.string().min(1),expected:A,present:A,deleted:A,notVisible:A,changed:A,linksChecked:A,linksBroken:A,error:p.string().optional()})),linksUnchecked:p.string().optional()})});function Ml(e,t){let n=new Set((t?.config.defaultValues??[]).map(s=>`${s.object}.${s.field}`.toLowerCase())),r=(e.targetGaps?.gaps??[]).filter(s=>s.severity==="blocking").flatMap(s=>{let i=s.field!==void 0?`${s.objectApiName}.${s.field}`:s.objectApiName;switch(s.kind){case"required_field_missing":return n.has(i.toLowerCase())?[]:[`${i}, which the org requires and the clone does not write`];case"object_not_createable":case"object_through_parent":return[`${i}, which the user it writes as may not create`];case"object_feature_off":return[`${i}, which a feature or licence the org has not turned on keeps closed`];case"api_budget":return["more API requests than the org has left today"];default:return[`${i} (${s.kind})`]}});if(r.length!==0)return`the org to fill would refuse its rows: ${r.join("; ")}. Give a field the org requires a value in the template's defaultValues (template: { file, id }), leave out an object its user may not create, or run it once the org has requests left`}function _l(e){return z(U,"the summary of a dry run",eg,e)}function cn(e){return z(U,"the summary of a run",tg,e)}function ql(e){return z(U,"the outcome of a removal",ng,e)}function zl(e){return z(U,"the preview of a removal",rg,e)}function Bl(e){return z(U,"a verification",sg,e)}function Kl(e){let t=e.writePlan,n=(e.wouldBeRefused??[]).join(" "),r=ze(n,e.wouldBeRefused,e.wouldBeRefusedCodes),s=r.length>0?{refusalCodes:r}:{};if(t===void 0)return{objects:[],total:0,created:0,storageBytes:0,emails:[],refusal:n!==""?n:"the clone never came to count what it would write, and a run held to no count is held to nothing",...s};let i=e.result.wouldInsertCount===t.totalRows,o=n!==""?n:t.totalRows===0?"it would write nothing: the clone reads no record to write; look at its record or the conditions of its tables":void 0;return{objects:t.objects.map(a=>({object:a.objectApiName,wouldCreate:a.rows,...i?{}:{atMost:!0}})),total:t.totalRows,created:e.result.wouldInsertCount,storageBytes:t.storageBytes,emails:t.emails??[],...o!==void 0?{refusal:o,...s}:{}}}function jr(e){let n=((e.result.remapInJournal===!0?e.result.createdCountByObject:void 0)??e.result.createdByObject.map(r=>({objectApiName:r.objectApiName,created:r.sourceIds.length}))).map(r=>({object:r.objectApiName,created:r.created,refused:0,errors:[]}));for(let r of e.result.errors){if(r.failedCount===0)continue;let s=n.find(o=>o.object===r.objectApiName),i=`${r.failedCount} refused by the org`;s!==void 0?(s.refused+=r.failedCount,s.errors.push(i)):n.push({object:r.objectApiName,created:0,refused:r.failedCount,errors:[i]})}return{objects:n,created:e.result.successCount}}function Ul(e){let{result:t}=e;if(t.verdict==="unstable")return`no two of ${t.attempts} readings agreed: something still writes to the run's records; verify again once it is done`;let n=t.objects.flatMap(r=>{if(r.error!==void 0)return[`${r.objectApiName} not read (${r.error})`];let s=r.deleted+r.notVisible;return[...s>0?[`${r.objectApiName} ${s} of ${r.expected} not there`]:[],...r.linksBroken>0?[`${r.objectApiName} ${r.linksBroken} lookup(s) that do not hold`]:[]]});return n.length>0?n.join("; "):void 0}function Si(e){return e instanceof Error?e.message:String(e)}import{readFileSync as Wl}from"node:fs";import{join as Jl}from"node:path";var X="sandforge-frozen",Vl=1e6,ig=["sasDir","datasetDir"],og=["rootObject","excludedObjects","identityKeys","undeletableObjects","requiredLookupPlaceholders","requiredFieldDefaults","picklistRules","defaultPicklistRule","duplicateErrorPatterns"],Yl=new Set(["NO_LOAD","ALREADY_REMOVED","NOTHING_TO_REMOVE"]);function Gl(e,t,n){let r=["resources",e,"config"],s=f=>({refusals:[P(r,f)]}),i;try{i=Wl(Jl(n,t.config),"utf8")}catch(f){return s(`${t.config} cannot be read: ${f instanceof Error?f.message:String(f)}`)}if(i.length>Vl)return s(`${t.config} is larger than ${Vl} bytes`);let o;try{o=JSON.parse(i.replace(/^\uFEFF/,""))}catch{return s(`${t.config} is not JSON: a Frozen configuration is the panel's, as JSON`)}let a=nr(o);if(a.length>0)return{refusals:a.map(({path:f,secret:y})=>P(r,`${t.config} holds a key shaped like a secret (${y}) at ${f.join(".")}: a load never reads the salt, and the configuration holds no secret. Take it out.`))};let c=fc.strict().safeParse(o);if(!c.success)return{refusals:c.error.issues.map(f=>P(r,`${t.config} is refused by Frozen's configuration schema at ${f.path.map(String).join(".")||"its top"}: ${f.message}`))};let l=[],u={...c.data},d=ig.filter(f=>u[f]!==void 0);for(let f of d)delete u[f];return d.length>0&&l.push(P(r,`${t.config} gives ${d.join(" and ")}, which the environment sets: the loads are kept beside the state, and the dataset is the one the file pins`)),{run:{configFile:t.config,config:u,dataset:{...t.dataset}},warnings:l}}function Hl(e){return{kind:"frozen",kindVersion:1,dataset:{digest:e.dataset.digest,version:e.dataset.version},load:Object.fromEntries(og.map(t=>[t,e.config[t]??null]))}}function Ql(e,t){return{...e.config,sasDir:t.sasDir,datasetDir:t.datasetDir}}async function Xl(e,t){let n,r;try{n=await Kc(e),r=JSON.parse(Wl(Jl(e,"manifest.json"),"utf8")).version}catch(s){return{refusal:`its dataset at ${e} cannot be read: ${s instanceof Error?s.message:String(s)}`}}return n!==t.digest?{refusal:`its dataset at ${e} has the digest ${n}, and the file pins ${t.digest}: it is not the dataset the file was reviewed with. Point the path at that one, or pin this digest once this dataset is reviewed`}:r!==t.version?{refusal:`its dataset at ${e} is version ${String(r)}, and the file pins version ${t.version}: pin the version its manifest says`}:{digest:n,version:t.version}}function ln(e,t){return[e,"--config",N("--config",t.configFile),"--target",N("--target",t.target)]}function Zl(e){return[...ln("load",e),...e.reload?["--reload"]:[],...e.reload&&e.goneFirst!==void 0?["--gone-first",N("--gone-first",e.goneFirst)]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],...e.store!==void 0?["--store",N("--store",e.store)]:[],"--dry-run","--json"]}function eu(e){return[...ln("load",e),...e.reload?["--reload"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],"--max-total",String(e.maxTotal),"--yes","--json"]}function tu(e){return[...ln("verify",e),"--json"]}function nu(e){return[...ln("remove",e),...e.includeChanged===!0?["--include-changed"]:[],...Ce(e),...e.acceptAutomation===!0?["--accept-automation"]:[],"--yes","--json"]}function ru(e){return[...ln("remove",e),...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],"--preview",...Ce(e),"--json"]}var ag=p.object({type:p.string().min(1),payload:p.record(p.string(),p.unknown()).optional()}).loose(),un={tool:p.literal(X),posted:p.array(ag),dataset:p.object({dir:p.string().min(1),digest:p.string().min(1),version:p.string().optional()}).optional(),mapping:p.string().min(1).optional(),refusals:p.array(p.string()).optional(),refusalCodes:p.array(p.string()).optional(),ended:p.literal(!0).optional()},su=p.object({status:p.enum(["PASSED","PARTIAL","FAILED","UNSTABLE"]),objects:p.array(p.object({objectApiName:p.string().min(1),verdict:p.enum(["PASSED","FAILED"]),expected:A,found:A,notLoaded:A,orphans:A,missingKeys:A}))}),cg=p.object({...un,step:p.literal("load"),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:A,toInsert:A,toLink:A,notSent:A,toPurge:A,toDeactivate:A})).optional()}),lg=p.object({...un,step:p.literal("load"),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:A,inserted:A,reused:A,duplicates:A,failed:A})).optional(),verdict:su.optional()}),ug=p.object({...un,step:p.literal("verify"),verdict:su.optional()});function dn(e,t){return e.filter(n=>n.type===t).at(-1)?.payload}function fn(e){let t=e.find(s=>s.type.endsWith(":error"))?.payload;if(t===void 0)return;let n=typeof t.message=="string"?t.message:"refused",r=typeof t.code=="string"?t.code:void 0;return{message:n,...r!==void 0?{code:r}:{}}}var dg=p.object({...un,step:p.literal("remove")}).transform((e,t)=>{let n=fn(e.posted.filter(y=>y.type!=="frozen:remove:automation:error")),r={planned:0,objects:[],userNames:{}};if(n!==void 0&&!Yl.has(n.code??""))return{tool:e.tool,preview:r,refusals:[n.message],...n.code!==void 0?{refusalCodes:[n.code]}:{},removalAlone:[]};let s=dn(e.posted,"frozen:remove:preview:response")?.preview;if(s===void 0)return{tool:e.tool,preview:r,refusals:[],removalAlone:[]};let i=Ot.extend({refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional()}).loose().safeParse(s);if(!i.success)return t.addIssue({code:"custom",message:`its preview: ${i.error.issues[0]?.message}`}),p.NEVER;let{refusals:o,refusalCodes:a,...c}=i.data,l=e.refusals??[],u=new Map(e.refusalCodes?.length===l.length?l.map((y,g)=>[y,e.refusalCodes?.[g]??""]):[]),d=l.filter(y=>!o.includes(y)),f=d.flatMap(y=>u.get(y)??[]);return{tool:e.tool,preview:c,refusals:o,...a?.length===o.length?{refusalCodes:a}:{},removalAlone:d,...f.length===d.length&&f.length>0?{removalAloneCodes:f}:{}}}),fg=p.object({...un,step:p.literal("remove"),status:p.string().optional()}).transform((e,t)=>{let n=fn(e.posted),r={tool:e.tool,result:{status:"success",planned:0,objects:[]}};if(n!==void 0)return Yl.has(n.code??"")?r:(t.addIssue({code:"custom",message:`the removal was refused: ${n.message}`}),p.NEVER);let s=dn(e.posted,"frozen:remove:response")?.result;if(s===void 0)return r;let i=p.object({status:p.enum(["success","partial","failure","cancelled"]),objects:p.array(At.loose())}).loose().safeParse(s);return i.success?{tool:e.tool,result:{status:i.data.status,planned:i.data.objects.reduce((o,a)=>o+a.planned,0),objects:i.data.objects}}:(t.addIssue({code:"custom",message:`its result: ${i.error.issues[0]?.message}`}),p.NEVER)});function iu(e){return z(X,"the answer of a dry run",cg,e)}function Nr(e){return z(X,"the answer of a load",lg,e)}function ou(e){return z(X,"a verification",ug,e)}function au(e){return z(X,"the preview of a removal",dg,e)}function cu(e){return z(X,"the outcome of a removal",fg,e)}function pg(e){let n=(Array.isArray(e?.removals)?e.removals:[]).flatMap(r=>{let s=r;return s.reason==="may-hold-masks"?[`${String(s.objectApiName)}.${String(s.field)} (${Number(s.affectedRecords??0)})`]:[]});return n.length>0?[`it would leave out, encrypted in the target, ${n.join(", ")}: the dataset's manifest does not say its extraction left out what it read masked, so they may hold masks such as ****1234`]:[]}function hg(e){return(Array.isArray(e?.perObject)?e.perObject:[]).flatMap(n=>{let r=n,s=Number(r.picklistsRewritten??0),i=Number(r.fieldsDropped??0),o=[s>0?`${s} picklist value(s) a restricted picklist of the target refuses, rewritten by their rule`:"",i>0?`${i} field(s) the target lacks or takes no value of, dropped`:""].filter(Boolean);return o.length>0?[`${String(r.objectApiName)}: ${o.join(", ")}`]:[]})}function mg(e){let t=e?.emails?.counted;return Array.isArray(t)?t.flatMap(n=>{let{limit:r,emails:s}=n??{};return(r==="SingleEmail"||r==="DailyWorkflowEmails")&&typeof s=="number"?[{limit:r,emails:s}]:[]}):[]}function lu(e){let t=fn(e.posted),n=[...t!==void 0?[t.message]:[],...e.refusals??[]],r=e.objects??[],s=r.reduce((u,d)=>u+d.toInsert,0),i=dn(e.posted,"frozen:load:preview:response")?.plan,o=n.length>0?n.join(" "):e.objects===void 0?"the load never came to say what it would write, and a run held to no count is held to nothing":s===0?"it would insert nothing: every record of the dataset is one the org holds already, linked by its identity keys, or one the load does not send":void 0,a=[...pg(i),...hg(i)],c=e.refusals??[],l=o!==void 0?ze(o,n,[...t!==void 0?[t.code??""]:[],...e.refusalCodes?.length===c.length?e.refusalCodes:c.map(()=>"")]):[];return{objects:r.map(u=>({object:u.objectApiName,wouldCreate:u.toInsert})),total:s,created:s,storageBytes:r.reduce((u,d)=>u+kc(d.objectApiName,{rows:d.toInsert}),0),emails:mg(i),...o!==void 0?{refusal:o}:{},...l.length>0?{refusalCodes:l}:{},...a.length>0?{notes:a}:{}}}function pn(e){let t=fn(e.posted),n=(e.objects??[]).map(r=>({object:r.objectApiName,created:r.inserted,refused:r.failed,errors:r.failed>0?[`${r.failed} refused by the org`]:[]}));return n.length===0&&t!==void 0?{objects:[],created:0,refusal:t.message}:{objects:n,created:n.reduce((r,s)=>r+s.created,0)}}function Ir(e){let n=dn(e.posted,"frozen:load:response")?.report?.purge;if(n===void 0)return!1;let r=Object.values(n.leftUnrecorded??{}).reduce((s,i)=>s+i,0);return(n.failures??[]).length===0&&r===0}function uu(e){let t=dn(e.posted,"frozen:load:response")?.report;return[...Object.values(t?.purge?.deleted??{}),...Object.values(t?.purge?.deactivated??{})].some(r=>r>0)}function Ri(e){if(e.status==="UNSTABLE")return{unstable:!0,short:"no two readings of the org agreed: something still writes to the load\u2019s records; verify again once it is done"};let t=e.objects.filter(n=>n.verdict==="FAILED").map(n=>{let r=[`${n.found} of ${n.expected} found`,n.orphans>0?`${n.orphans} orphan(s)`:"",n.missingKeys>0?`${n.missingKeys} key(s) missing`:"",n.notLoaded>0?`${n.notLoaded} not loaded`:""].filter(Boolean);return`${n.objectApiName} FAILED (${r.join(", ")})`});return t.length>0?{unstable:!1,short:t.join("; ")}:e.status!=="PASSED"?{unstable:!1,short:`its verdict is ${e.status}`}:{unstable:!1}}function du(e){let t=fn(e.posted);if(e.verdict===void 0)return{unread:t?.message??"the verification gave no verdict"};let{short:n,unstable:r}=Ri(e.verdict);return r?{unread:n??"no two readings agreed"}:{failed:n!==void 0?[n]:[]}}function Ve(e){return`frozen/${e}`}function Dr(e){return e!==void 0&&/^frozen\/[a-z][a-z0-9-]{0,62}$/.test(e)?e.slice(7):void 0}import{existsSync as $i}from"node:fs";import{rm as gg}from"node:fs/promises";import{join as fu}from"node:path";var se="sandforge-dataops",pu="snapshots.json";function hu(e){let t={},n=[];for(let[r,s]of Object.entries(e)){let i=dc.safeParse({name:r,rules:s.rules});if(!i.success){n.push(...i.error.issues.map(o=>P(["masking",r,...o.path],`refused by the rules the DataOps panel saves: ${o.message}`)));continue}t[r]={name:r,rules:s.rules}}return n.length>0?{refusals:n}:{sets:t}}function yg(e){let t=ti.find(r=>r.id===e);if(t===void 0)return;let n=t.rules.flatMap(r=>{if(!Ga(r.ruleType))return[];let s="config"in r?r.config:void 0;return[{fieldPattern:r.fieldPattern,ruleType:r.ruleType,...s!==void 0?{config:{...s}}:{}}]});return{name:t.name,rules:n}}function mu(e,t,n){let r=["resources",e,"rules"],s,i;if(typeof t.rules=="string"){if(s=n[t.rules],i={set:t.rules},s===void 0)return{refusals:[P(r,`the rule set ${t.rules} is refused: see masking`)]}}else{let d=t.rules.template;if(s=yg(d),i={template:d},s===void 0)return{refusals:[P([...r,"template"],`there is no DataOps template "${d}" that ships: there is `+ti.map(f=>f.id).join(", "))]}}let o=t.object;if(o!==void 0&&!Uc({id:s.name,name:s.name,rules:s.rules},o))return{refusals:[P(["resources",e,"object"],`${"set"in i?`the rule set ${i.set}`:`the template ${i.template}`} has no rule for ${o}: a run would mask nothing. Name an object its rules mask, or give it a rule for this one`)]};let a=[],c=`${(o??"").toLowerCase()}.`,l=new Map(s.rules.filter(d=>o!==void 0&&d.fieldPattern.toLowerCase().startsWith(c)).map(d=>[(d.fieldPattern.split(".")[1]??"").toLowerCase(),d.ruleType])),u=wg(t.where).filter(({field:d,empty:f})=>{let y=l.get(d.toLowerCase());return y!==void 0&&(!f||y==="nullify")}).map(({field:d})=>d);return u.length>0&&a.push(P(["resources",e,"where"],`its condition reads ${u.join(", ")}, which its rules write over: once masked, its records may no longer be those it selects, and a plan after reads them as gone. Select them by a field its rules leave as it is`)),{run:{source:i,rules:s,...o!==void 0?{object:o}:{},...t.where!==void 0?{where:t.where}:{},...t.accept?.automation===!0?{acceptAutomation:!0}:{},...t.slices===!0?{slices:!0}:{},...t.maxRecords!==void 0?{maxRecords:t.maxRecords}:{},...t.maxRequests!==void 0?{maxRequests:t.maxRequests}:{}},warnings:a}}function wg(e){if(e===void 0)return[];let t=e.replace(/'(?:[^'\\]|\\.)*'/g,"''"),n=new Map;for(let r of t.matchAll(/\b([A-Za-z][A-Za-z0-9_]*)\s*(=|!=|<>|<=|>=|<|>|\s(?:NOT\s+)?(?:LIKE|IN|INCLUDES|EXCLUDES)\b)\s*(null\b)?/gi)){let s=r[1]??"";if(/^(?:AND|OR|NOT)$/i.test(s))continue;let i=/^(?:=|!=|<>)$/.test(r[2]??"")&&r[3]!==void 0;n.set(s,(n.get(s)??!0)&&i)}return[...n].map(([r,s])=>({field:r,empty:s}))}function gu(e){return{kind:"mask",kindVersion:1,rules:[...e.rules.rules].map(t=>({...t,fieldPattern:t.fieldPattern.toLowerCase()})).sort((t,n)=>$t(t).localeCompare($t(n))),object:e.object??null,where:e.where??null}}function yu(e){if(e.object!==void 0)return[{object:e.object}];let t=[];for(let n of e.rules.rules){let r=n.fieldPattern.split(".")[0]??"";t.includes(r)||t.push(r)}return t.map(n=>({object:n}))}function wu(e){return{name:e.rules.name,rules:e.rules.rules}}function It(e){return`dataops/${e}`}function vu(e){let{run:t}=e;return["anonymize","--org",N("--org",e.target),...t.object!==void 0?["--object",N("--object",t.object)]:[],...t.where!==void 0?["--where",N("--where",t.where)]:[],..."template"in t.source?["--template",N("--template",t.source.template)]:["--rules",N("--rules",e.rulesFile)],"--store",N("--store",e.store),...t.acceptAutomation===!0?["--accept-automation"]:[],...t.slices===!0?["--slices"]:[],...t.maxRecords!==void 0?["--max-records",String(t.maxRecords)]:[],...t.maxRequests!==void 0?["--max-requests",String(t.maxRequests)]:[]]}function ku(e){return[...vu(e),"--dry-run","--json"]}function bu(e){return[...vu(e),"--yes","--json"]}var vg=p.object({type:p.string().min(1),payload:p.record(p.string(),p.unknown()).optional()}).loose(),We=p.number().int().nonnegative(),Eu={tool:p.literal(se),org:p.string().min(1),posted:p.array(vg)},kg=p.object({...Eu,command:p.literal("dry-run"),slices:p.literal(!0).optional()}),bg=p.object({...Eu,command:p.literal("run")});function Su(e){return z(se,"the answer of a dry run",kg,e)}function Pr(e){return z(se,"the answer of a masking",bg,e)}function Nt(e,t){return e.filter(n=>n.type===t).at(-1)?.payload}function Ru(e){let t=Nt(e,"dataops:error");if(t!==void 0)return typeof t.message=="string"?t.message:"refused"}var Eg=p.object({objects:p.array(p.object({objectApiName:p.string().min(1),count:We.nullable(),slicePlan:p.object({size:p.number().int().positive(),slices:p.number().int().positive()}).loose().optional()}).loose()),sliceSet:p.object({setId:p.string().min(1),done:We,total:We,savedAt:p.string(),state:p.string()}).loose().optional()}),Sg=p.object({objects:p.array(p.object({objectApiName:p.string().min(1),fields:p.array(p.string()),error:p.string().optional(),notCovered:p.literal(!0).optional(),writeDenied:p.object({deniedFields:p.array(p.string())}).optional()}).loose()),fieldsNotFound:p.array(p.object({objectApiName:p.string(),fieldApiName:p.string()}))}),Rg=p.object({emails:p.array(p.object({limit:p.enum(["SingleEmail","DailyWorkflowEmails"]),emails:We}).loose()),refusals:p.array(p.object({code:p.string(),message:p.string()}).loose())}).loose();function $u(e){let t=[],n=Ru(e.posted);n!==void 0&&t.push(n);let r=Eg.safeParse(Nt(e.posted,"dataops:anonymize:coverage:response")),s=Sg.safeParse(Nt(e.posted,"dataops:anonymize:preview:response"));if(!r.success||!s.success)return n===void 0&&t.push("the masking never came to say what it would mask, and a run nobody counted is masked blind"),{objects:[],refusals:t,refusalCodes:t.map(()=>""),emails:[]};let i=Rg.safeParse(Nt(e.posted,"dataops:automation:response")),o=r.data.objects.map(u=>({object:u.objectApiName,count:u.count}));for(let u of r.data.objects){let d=u.slicePlan;u.count===null&&!(e.slices===!0&&d!==void 0)&&t.push(`${u.objectApiName}: the org did not count the records it would mask`),e.slices!==!0&&d!==void 0&&(u.count??0)>d.size&&t.push(`${u.objectApiName} holds ${u.count??0} record(s), more than the ${d.size} a snapshot holds of one object: a run is refused and masks nothing (slices: true masks it in ${d.slices} slices, each backed up just before it is masked, or maxRecords takes up to ${Ya})`)}let a=r.data.sliceSet;a!==void 0&&a.state==="open"&&t.push(`a masking in slices of its rules stopped part way and is still open in its store (set ${a.setId}, ${a.done} of ${a.total} slice(s) masked, last moved ${a.savedAt}): a run is refused until it is resumed or given up, with ${ce("dataops")} anonymize and the resource's store, --resume or --abandon`);for(let u of s.data.objects){u.error!==void 0?t.push(`${u.objectApiName}: not read: ${u.error}`):u.notCovered===!0&&t.push(`${u.objectApiName}: its rules mask no field the org shows this user: a run would mask nothing there`);let d=u.writeDenied?.deniedFields;d?.length===0&&t.push(si(u.objectApiName));for(let f of d??[])t.push(si(u.objectApiName,f))}for(let u of s.data.fieldsNotFound)t.push(ri(u.objectApiName,u.fieldApiName));let c=new Map;for(let u of i.success?i.data.refusals:[])t.push(u.message),c.set(u.message,u.code);let l=i.success?i.data.emails.map(({limit:u,emails:d})=>({limit:u,emails:d})):[];return{objects:o,refusals:t,refusalCodes:t.map(u=>c.get(u)??""),emails:l}}function Au(e){let t=$u(e),n=t.objects.map(i=>({object:i.object,wouldCreate:i.count??0})),r=t.refusals.length>0?t.refusals.join(" "):void 0,s=r!==void 0?ze(r,t.refusals,t.refusalCodes):[];return{objects:n,total:n.reduce((i,o)=>i+o.wouldCreate,0),created:0,storageBytes:0,emails:t.emails,...r!==void 0?{refusal:r}:{},...s.length>0?{refusalCodes:s}:{}}}var $g=p.object({status:p.string().optional(),objects:p.array(p.object({objectApiName:p.string().min(1),total:We,processed:We,failed:We,notMasked:We}).loose()).optional(),fieldsNotFound:p.array(p.object({objectApiName:p.string(),fieldApiName:p.string()})).optional(),snapshot:p.object({operationId:p.string().min(1).max(200)}).loose().optional(),slices:p.object({setId:p.string().min(1).max(200)}).loose().optional(),message:p.string().optional(),errors:p.array(p.object({objectApiName:p.string(),message:p.string()})).optional()}).loose();function hn(e){let t=$g.safeParse(Nt(e.posted,"dataops:anonymize:response")??Nt(e.posted,"dataops:error")??{}),n=t.success?t.data:{},r=(n.objects??[]).map(a=>({object:a.objectApiName,masked:a.processed,refused:a.failed,notMasked:a.notMasked})),s=Ru(e.posted),i=(n.fieldsNotFound??[]).map(a=>ri(a.objectApiName,a.fieldApiName)),o=n.snapshot?.operationId??n.slices?.setId;return{objects:r,...o!==void 0?{snapshotId:o}:{},...s!==void 0?{refusal:s}:{},...i.length>0?{short:i.join("; ")}:{}}}function Ou(e,t){let n=$u(t),r=e.runs.at(-1),s=new Map((r?.objects??[]).map(a=>[a.objectApiName,a.masked??0]));if(n.refusals.length>0)return{objects:[],masked:0,unread:n.refusals.join(" ")};let i=[],o=[];for(let{object:a,count:c}of n.objects){let l=c??0,u=s.get(a)??0;o.push({object:a,present:Math.min(l,u),...l<u?{gone:u-l}:{}}),l>u?i.push(`${a} ${l} under its condition, ${u} masked: ${l-u} more, which hold their original values`):l<u&&i.push(`${a} ${l} under its condition, ${u} masked: ${u-l} gone`)}return{objects:o,masked:[...s.values()].reduce((a,c)=>a+c,0),...i.length>0?{drift:i.join("; ")}:{}}}function Ai(e,t){return`${ce("dataops")} anonymize --org ${e.alias} --restore ${t} --store ${e.store??"<its store>"}`}function Cu(e,t){return t.store??`${It(e)} beside the state`}function ju(e,t){return[`masking is one-way: each run first takes a snapshot of the values it writes over, kept on this machine in ${Cu(e,t)}, and destroy never puts them back: it deletes the snapshots. Putting them back is your own act, before a destroy: `+Ai(t,"<the snapshot its run names>")]}function Nu(e){return e.runs.find(t=>t.takenBack!==!0)}function Ag(e){let t=Nu(e);return t?.snapshotId!==void 0?`snapshot ${t.snapshotId}, run ${t.n}'s`:t!==void 0?`the snapshot run ${t.n} took`:"the snapshot its first run took"}function Oi(e){return`it masks again what its condition selects, the records it masked before a second time, and takes nothing back first: the values they held before any masking stay only in ${Ag(e)}, which destroy deletes`}var Iu={applying:"its last masking was stopped part way",partial:"its last masking left values as they were: records the org refused, or fields it does not show this user",failed:"its last masking failed",destroying:"a deletion of its snapshots was stopped part way"};function Du(e){return`applied, and its condition selects the ${e} record(s) it masked, with the same rules: masked again they would only be masked twice`}function Pu(e,t){return`its condition selects other records than it masked: ${t}. Left as they are: --replace ${e} or --replace-drifted masks them all again`}function Ci(e,t,n,r){let s=Nu(n)?.snapshotId;return`${e==="destroy"?"taken back by destroy, which never unmasks":"in the state, gone from the file"}: its records stay masked, and its store, ${Cu(t,r)}, is deleted from this machine with its snapshots, the only copy of the values they held. `+(s!==void 0?`To put back those they held before any masking, before this ${e}, as your own act: ${Ai(r,s)}`:`Its snapshots are listed in its store: ${Ai(r,"<snapshot>")} puts one back, before this ${e}, as your own act`)}async function Tu(e){if(!$i(e))return{snapshots:[]};let t=$i(fu(e,pu))?$c(fu(e,pu)).getKeysByPrefix("backup:").map(n=>n.slice(7)).filter(n=>!n.includes(":")):[];if(await gg(e,{recursive:!0,force:!0}),$i(e))throw new Error(`${e} is still there: delete it, it holds the values a masking wrote over`);return{snapshots:[...new Set(t)].sort()}}function Fu(e,t){let n=t.snapshots.length>0?`its snapshot${t.snapshots.length===1?"":"s"} ${t.snapshots.join(", ")}`:"no snapshot";return`${e}: its records stay masked \u2014 destroy never unmasks \u2014, and ${n}, the only copy of the values they held, deleted from this machine with its store`}var Y="sandforge-seed",Og="In the file: fit: share seeds the largest share of each count that fits, fit: { withinMB: <MB> } no more than that; or lower each object\u2019s count.";function Mu(e,t,n,r){let s=Cg(e,t,n,r);if("refusal"in s)return{refusals:[s.refusal]};let i=Ng(t,n,s.run);return i.refusals.length>0?{refusals:i.refusals}:{run:s.run,warnings:i.warnings}}function Cg(e,t,n,r){let s=r.toISOString(),i={id:`env-${e}-${t}`,name:`${e}/${t}`,description:`The ${t} resource of the ${e} environment`,version:1,tags:["sandforge-env"],createdAt:s,updatedAt:s},o,a=[];if(n.template!==void 0){let l=Zs.find(u=>u.id===n.template);if(l===void 0)return{refusal:P(["resources",t,"template"],`there is no built-in template "${n.template}": there is ${Zs.map(u=>u.id).join(", ")}`)};o={...i,strategy:l.strategy,objects:structuredClone(l.objects),...l.relations!==void 0?{relations:structuredClone(l.relations)}:{}}}else o={...i,strategy:"faker",objects:(n.objects??[]).map((l,u)=>({objectApiName:l.object,recordCount:l.count,fieldRules:structuredClone(l.fields??[]),excludedFields:[],insertOrder:u,batchSize:l.batchSize??200})),...n.relations!==void 0?{relations:n.relations.flatMap((l,u)=>{let d=l.parents.from;if(d===void 0)return[Lu(l)];let{childObject:f,lookupField:y,parentObject:g,distribution:m}=Lu(l);return a.push({at:u,relation:{childObject:f,lookupField:y,parentObject:g,distribution:m},from:d.split(".")[0]??d,...l.parents.limit!==void 0?{limit:l.parents.limit}:{}}),[]})}:{}};let c=Object.fromEntries((n.objects??[]).filter(l=>l.recordTypes!==void 0).map(l=>[l.object,[...new Set(l.recordTypes)]]));return{run:{template:o,...n.locale!==void 0?{locale:n.locale}:{},...n.seed!==void 0?{seed:n.seed}:{},...Object.keys(c).length>0?{recordTypes:c}:{},...n.fit!==void 0?{fit:n.fit==="share"?{}:{withinMB:n.fit.withinMB}}:{},acceptAutomation:n.accept?.automation===!0,...a.length>0?{draws:a}:{}}}}function jg(e){return e.object??e.from?.split(".")[1]??""}function Lu(e){let[t="",n=""]=e.lookup.split("."),r=e.parents.existing;return{childObject:t,lookupField:n,parentObject:jg(e.parents),parents:r===void 0?{kind:"generated"}:{kind:"existing",...r.where!==void 0?{where:r.where}:{},limit:r.limit},distribution:e.distribution}}function _u(e){return{kind:"existing",limit:e.limit??tr.maxExistingParents}}function qu(e,t){let n=[...e.template.relations??[]],r=e.draws??[],s=[];for(let i=0;i<n.length+r.length;i++){let o=r.find(c=>c.at===i),a=o!==void 0?{...o.relation,parents:t(o)}:n.shift();a!==void 0&&s.push(a)}return s}function ji(e,t,n){return(e.draws??[]).length===0?e.template:{...e.template,relations:qu(e,r=>{let s=t?.get(r.at);if(s!==void 0&&s.length>0)return{kind:"records",ids:[...s]};if(!n.standIns)throw new Error(`The relation on ${r.relation.childObject}.${r.relation.lookupField} draws its parents from ${r.from}, whose records are not known: plan again.`);return _u(r)})}}var xu=Object.keys(Mc);function Ng(e,t,n){let r=["resources",e],s=ji(n,void 0,{standIns:!0}),i=uc.safeParse(s);if(!i.success)return{refusals:i.error.issues.map(l=>P(Ig(r,t,l.path),l.message)),warnings:[]};let o=new qc().validate(s),a=({field:l,message:u})=>P(Dg(r,t,s,l),u),c=n.locale!==void 0&&!xu.includes(n.locale)?[P([...r,"locale"],`the seed draws in ${xu.join(", ")}, not ${n.locale}: name one of them, or leave locale out to draw in the org\u2019s own`)]:[];return{refusals:[...o.errors.map(a),...c],warnings:o.warnings.map(a)}}function Ig(e,t,n){if(t.template!==void 0)return[...e,"template"];let[r,s,i,...o]=n;if(r==="objects"&&typeof s=="number"){let a=[...e,"objects",s];return i==="objectApiName"?[...a,"object"]:i==="recordCount"?[...a,"count"]:i==="fieldRules"?[...a,"fields",...o]:i===void 0?a:[...a,i]}if(r==="relations"&&typeof s=="number"){let a=[...e,"relations",s];return i==="childObject"||i==="lookupField"?[...a,"lookup"]:i==="parentObject"?[...a,"parents","object"]:i==="parents"?[...a,"parents","existing",...o]:i===void 0?a:[...a,i,...o]}return e}function Dg(e,t,n,r){if(t.template!==void 0)return[...e,"template"];let s=/^objects\[([^\]]+)\](?:\.fieldRules\[([^\]]+)\])?/.exec(r);if(s!==null){let o=n.objects.findIndex(l=>l.objectApiName===s[1]);if(o<0)return e;let a=s[2],c=a===void 0?-1:(n.objects[o]?.fieldRules??[]).findIndex(l=>l.fieldApiName===a);return c<0?[...e,"objects",o]:[...e,"objects",o,"fields",c]}let i=/^relations\[([^\]]+)\]/.exec(r);if(i!==null){let o=(n.relations??[]).findIndex(a=>`${a.childObject}.${a.lookupField}`===i[1]);return o<0?e:[...e,"relations",o]}return e}function zu(e){let{template:t}=e;return{kind:"seed",kindVersion:1,strategy:t.strategy,objects:t.objects.map(n=>({objectApiName:n.objectApiName,recordCount:n.recordCount,recordTypeId:n.recordTypeId,fieldRules:n.fieldRules,excludedFields:n.excludedFields,insertOrder:n.insertOrder})),relations:t.relations??[],locale:e.locale??null,seed:e.seed??null,recordTypes:e.recordTypes??{},draws:e.draws,...e.fit!==void 0?{fit:e.fit}:{}}}function Bu(e){return e.template.objects.map(t=>({object:t.objectApiName,count:t.recordCount}))}function Ku(e){let{template:t}=e,n=qu(e,_u),r=new Set(n.filter(s=>s.parents.kind==="existing").map(s=>s.childObject));for(let s=!0;s;){s=!1;for(let i of t.objects)r.has(i.objectApiName)||Ja(i,n).some(o=>r.has(o))&&(r.add(i.objectApiName),s=!0)}return new Map(t.objects.filter(s=>r.has(s.objectApiName)).map(s=>[s.objectApiName,s.recordCount]))}function Uu(e){return["--target",N("--target",e.target),"--template-file",N("--template-file",e.templateFile),"--run-id",N("--run-id",e.runId),...e.seed!==void 0?["--seed",String(e.seed)]:[],...e.locale!==void 0?["--locale",N("--locale",e.locale)]:[],...Object.entries(e.recordTypes??{}).flatMap(([t,n])=>["--record-type",N("--record-type",`${t}=${n.join(",")}`)]),...e.fit!==void 0?["--fit","share",...e.fit.withinMB!==void 0?["--fit-within",String(e.fit.withinMB)]:[]]:[]]}function Vu(e){return[...Uu(e),"--json","--fail-on-partial"]}function Wu(e){return[...Uu(e),"--dry-run","--json"]}function Ju(e){return[...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],...e.leaveUndeletable===!0?["--leave-undeletable"]:[]]}function Yu(e){return["--remove",N("--remove",e.summary),"--target",N("--target",e.target),...Ju(e),...Ce(e),"--json"]}function Gu(e){return["--remove",N("--remove",e.summary),"--target",N("--target",e.target),"--preview",...Ju(e),...Ce(e),"--json"]}var Pg=p.object({limit:p.enum(["SingleEmail","DailyWorkflowEmails"]),emails:A,verdict:p.enum(["fits","exceeds","unread"]),remaining:p.number().int().optional(),max:p.number().int().optional(),unread:p.string().optional()}),Tg=p.object({checks:p.array(Pg),refusal:p.string().optional(),unknown:p.array(p.string()).optional()}),Fg=p.object({records:A,given:A,refusal:p.string().optional()}),Lg=e=>p.object({objectApiName:p.string().min(1),recordsCreated:A,recordsFailed:A,createdIds:p.array(e),errors:p.array(p.string()),truncated:p.boolean().optional(),writtenByThePlatform:Fg.optional()}),Hu=e=>p.object({templateId:p.string().optional(),operationId:p.string().min(1),status:p.enum(["success","partial","failure"]),cancelled:p.boolean().optional(),objectResults:p.array(Lg(e)),totalRecordsCreated:A,totalRecordsFailed:A}),Qu={tool:p.literal(Y),target:p.string().min(1),seed:p.number().int().nonnegative(),startedAt:p.string().min(1),finishedAt:p.string().min(1),notes:p.array(p.string()).optional(),emails:Tg,elapsedMs:A,interrupted:p.literal(!0).optional()},xg=p.object({...Qu,dryRun:p.literal(!1),targetOrgId:qe.optional(),result:Hu(qe),runFile:p.string().min(1).optional()}),Mg=p.object({bytes:A,verdict:p.enum(["fits","near","exceeds","unread"]),estimateMB:p.number().nonnegative(),maxMB:p.number().optional(),remainingMB:p.number().optional(),unread:p.string().optional(),refusal:p.string().optional()}),_g=p.object({estimate:A,verdict:p.enum(["fits","near","exceeds","unread"]),max:p.number().int().optional(),remaining:p.number().int().optional(),unread:p.string().optional(),refusal:p.string().optional()}),qg=p.object({...Qu,dryRun:p.literal(!0),storage:Mg,apiRequests:_g,wouldBeRefused:p.array(p.string()).optional(),wouldBeRefusedCodes:p.array(p.string()).optional(),result:Hu(p.string())}),zg=p.object({tool:p.literal(Y),action:p.literal("remove"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),result:p.object({status:p.enum(["success","partial","failure","cancelled"]),planned:A,objects:p.array(At),sweep:p.object({status:p.string()}).loose().optional()}),elapsedMs:A}),Bg=p.object({tool:p.literal(Y),action:p.literal("remove-preview"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),preview:Ot,refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional(),notes:p.array(p.string()),elapsedMs:A});function Dt(e){return z(Y,"the summary of a run",xg,e)}function Xu(e){return z(Y,"the summary of a dry run",qg,e)}function Zu(e){return z(Y,"the preview of a removal",Bg,e)}function ed(e){return z(Y,"the outcome of a removal",zg,e)}var td="validation";function nd(e,t){let n=e.result.objectResults,r=c=>{let l=ze(c,e.wouldBeRefused,e.wouldBeRefusedCodes);return l.length>0?{refusalCodes:l}:{}};if(e.result.status==="failure"&&n.length>0&&n.every(c=>c.objectApiName===td)){let c=n.flatMap(u=>u.errors),l=c.length>0?c.join(" "):"the seed refused its dry run";return{objects:[],total:0,created:0,apiRequests:e.apiRequests.estimate,storageBytes:0,emails:[],refusal:l,...r(l)}}let s=e.result.objectResults.map(c=>{let l=t?.get(c.objectApiName);return l!==void 0?{object:c.objectApiName,wouldCreate:Math.max(c.recordsCreated,l),atMost:!0}:{object:c.objectApiName,wouldCreate:c.recordsCreated}}),i=e.storage.refusal??e.apiRequests.refusal??e.emails.refusal,o=i!==void 0&&i===e.storage.refusal?`${i} ${Og}`:i,a=e.result.objectResults.flatMap(c=>c.writtenByThePlatform!==void 0?[Kg(c.objectApiName,c.writtenByThePlatform.records)]:[]);return{objects:s,total:e.result.totalRecordsCreated,created:e.result.totalRecordsCreated,apiRequests:e.apiRequests.estimate,storageBytes:e.storage.bytes,emails:e.emails.checks.map(c=>({limit:c.limit,emails:c.emails})),...o!==void 0&&i!==void 0?{refusal:o,...r(i)}:{},...a.length>0?{notes:a}:{}}}function Kg(e,t){return`${e}: ${t} record(s) linked to the contact role the platform writes with their opportunity, for its contact, not written: given the fields the seed generates for ${t===1?"it":"them"}`}function Tr(e){let t=e.result.objectResults;if(e.result.status==="failure"&&t.length>0&&t.every(n=>n.objectApiName===td)){let n=t.flatMap(r=>r.errors);return{objects:[],created:0,refusal:n.length>0?n.join(" "):"the seed refused its run before it wrote"}}return{objects:e.result.objectResults.map(n=>({object:n.objectApiName,created:n.recordsCreated,refused:n.recordsFailed,errors:n.errors})),created:e.result.totalRecordsCreated}}var Ug={seed:Y,forge:U,frozen:X,mask:se};function Vg(e){return e==="seed"||e==="forge"||e==="frozen"||e==="mask"}function Fr(e){if(!Vg(e))throw new Error(`The state holds a resource of kind ${e}, which a later SandForge applies: this one applies seed, forge, frozen and mask resources, and takes back nothing of another kind.`);return Ug[e]}function rd(e,t,n,r,s,i={}){switch(n.kind){case"seed":{let o=Mu(e,t,n,s);return"refusals"in o?o:{run:{kind:"seed",...o.run},warnings:o.warnings}}case"forge":{let o=$l(e,t,n,r,s);return"refusals"in o?o:{run:{kind:"forge",...o.run},warnings:o.warnings}}case"frozen":{let o=Gl(t,n,r);return"refusals"in o?o:{run:{kind:"frozen",...o.run},warnings:o.warnings}}case"mask":{let o=mu(t,n,i);return"refusals"in o?o:{run:{kind:"mask",...o.run},warnings:o.warnings}}}}function sd(e){switch(e.kind){case"seed":return zu(e.run);case"forge":return Nl(e.run,e.source.read);case"frozen":return Hl(e.run);case"mask":return gu(e.run)}}function Pt(e){switch(e.kind){case"seed":return Bu(e);case"forge":return Al(e);case"frozen":return[];case"mask":return yu(e)}}function dt(e){return e==="frozen"||e==="mask"}function Tt(e,t){switch(e.kind){case"seed":return ji(e.run,t.drawn,{standIns:t.standIns===!0});case"forge":return e.run.template??{};case"frozen":{if(t.sasDir===void 0)throw new Error(`${e.name} is given no folder to keep its loads in: plan again.`);return Ql(e.run,{sasDir:t.sasDir,datasetDir:e.dataset.dir})}case"mask":return wu(e.run)}}function id(e,t){switch(e.kind){case"seed":{let n=e.run.seed??t.seed;return{script:Y,args:Wu({target:t.target,templateFile:t.templateFile,runId:t.runId,...n!==void 0?{seed:n}:{},...e.run.locale!==void 0?{locale:e.run.locale}:{},...e.run.recordTypes!==void 0?{recordTypes:e.run.recordTypes}:{},...e.run.fit!==void 0?{fit:e.run.fit}:{}})}}case"forge":return{script:U,args:Dl({...ad(e),target:t.target,templateFile:t.templateFile,...t.rootsPlanFile!==void 0?{rootsPlanFile:t.rootsPlanFile}:{},maxTotal:e.run.maxTotal??Rl})};case"frozen":return{script:X,args:Zl({configFile:t.templateFile,target:t.target,reload:t.replace===!0,acceptAutomation:t.acceptAutomation===!0,...t.storeFile!==void 0?{store:t.storeFile}:{},...t.goneFirstFile!==void 0?{goneFirst:t.goneFirstFile}:{}})};case"mask":return{script:se,args:ku({target:t.target,run:e.run,rulesFile:t.templateFile,store:od(e,t)})}}}function od(e,t){if(t.store===void 0)throw new Error(`${e.name} is given no store to keep its snapshots in: plan again.`);return t.store}function ad(e){let{run:t,source:n}=e;if(t.wholeOrg)return{source:n.alias,wholeOrg:t.wholeOrg,acceptAutomation:t.acceptAutomation};if(t.tables!==void 0)return{source:n.alias,tables:t.tables,acceptAutomation:t.acceptAutomation};if(t.records!==void 0)return{source:n.alias,records:t.records,acceptAutomation:t.acceptAutomation};let r=n.read,s=t.record?.id??(r!==void 0&&"recordId"in r?r.recordId:void 0);if(s===void 0)throw new Error(`${e.name} names its record by a query its source has not answered: plan again.`);return{source:n.alias,recordId:s,acceptAutomation:t.acceptAutomation}}function cd(e,t){switch(e){case"seed":return Xu(t);case"forge":return _l(t);case"frozen":return iu(t);case"mask":return Su(t)}}function Ni(e){return e.kind==="seed"?Ku(e.run):void 0}function ld(e,t){return e.kind==="forge"&&t.tool===U?Ml(t,e.run.template):void 0}function Ft(e,t){switch(e.tool){case Y:return nd(e,t);case U:return Kl(e);case X:return lu(e);case se:return Au(e)}}function mn(e,t){switch(e.kind){case"seed":return{script:Y,args:Vu({target:t.target,templateFile:t.templateFile,runId:t.runId,...t.seed!==void 0?{seed:t.seed}:{},...e.run.locale!==void 0?{locale:e.run.locale}:{},...e.run.recordTypes!==void 0?{recordTypes:e.run.recordTypes}:{},...e.run.fit!==void 0?{fit:e.run.fit}:{}})};case"forge":{if(t.maxTotal===void 0)throw new Error(`${e.name} has no count from its dry run to be held to: plan again.`);return{script:U,args:Pl({...ad(e),target:t.target,templateFile:t.templateFile,...t.rootsPlanFile!==void 0?{rootsPlanFile:t.rootsPlanFile}:{},maxTotal:t.maxTotal,summary:t.summaryFile})}}case"frozen":{if(t.maxTotal===void 0)throw new Error(`${e.name} has no count from its dry run to be held to: plan again.`);return{script:X,args:eu({configFile:t.templateFile,target:t.target,reload:t.replace===!0,acceptAutomation:t.acceptAutomation===!0,maxTotal:t.maxTotal})}}case"mask":return{script:se,args:bu({target:t.target,run:e.run,rulesFile:t.templateFile,store:od(e,t)})}}}function Lr(e){throw new Error(`${Te(e)} takes no run back: a masking is never undone, and its destroy deletes its store`)}function ud(e,t){let n=Fr(e),r=t.sweep===!0?{sweep:!0}:{},s={target:t.target,summary:t.subject,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,...r};switch(n){case Y:return{script:n,args:Gu(s)};case U:return{script:n,args:Ll(s)};case X:return{script:n,args:ru({configFile:t.subject,target:t.target,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,...r})};case se:return Lr(n)}}function dd(e,t){let n=Fr(e);switch(n){case Y:return Zu(t);case U:return zl(t);case X:return au(t);case se:return Lr(n)}}function fd(e,t){if(e==="mask")return[];let n=[...t].reverse().filter(r=>r.takenBack!==!0);return e==="frozen"?n.slice(0,1):n}function pd(e,t){if(e==="frozen")return{script:X,args:tu({configFile:t.subject,target:t.target})}}function hd(e){return du(ou(e))}function md(e,t){let n=Fr(e),r={target:t.target,summary:t.subject,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,sweep:t.sweep};switch(n){case Y:return{script:n,args:Yu(r)};case U:return{script:n,args:Fl(r)};case X:return{script:n,args:nu({configFile:t.subject,target:t.target,includeChanged:t.includeChanged,sweep:t.sweep,acceptAutomation:t.acceptAutomation})};case se:return Lr(n)}}function gd(e,t){let n=Fr(e);switch(n){case Y:return ed(t);case U:return ql(t);case X:return cu(t);case se:return Lr(n)}}function Ii(e){return e?.result.objects??[]}function yd(e,t){return e.kind==="mask"?ju(e.name,t):e.kind==="forge"?Cl(e.run,e.source):[]}var rt=fm(ah());import{isAbsolute as vb,resolve as Wn}from"node:path";function ha(e){return`${nn(e.path)}: ${e.message}`}var kb=100;function lh(e){let t=e.startsWith("\uFEFF")?e.slice(1):e,n=(0,rt.parseDocument)(t,{version:"1.2",schema:"core",merge:!1,uniqueKeys:!1,prettyErrors:!0}),r=n.errors[0]??n.warnings[0];if(r)return{refusal:`The file does not read as YAML 1.2: ${r.message.split(`
147
+ `)[0]}`};let s=pa(n.contents,[]);if(s!==void 0)return{refusal:`${nn(s.path)} holds the key "${s.key}" twice: a mapping holds each key once, and the second would replace the first unseen. Keep one.`};try{return{document:n.toJS({maxAliasCount:kb})}}catch(i){return{refusal:`The file does not read as YAML 1.2: ${i instanceof Error?i.message:String(i)}`}}}function pa(e,t){if((0,rt.isMap)(e)){let n=new Set;for(let r of e.items){let s=(0,rt.isScalar)(r.key)?String(r.key.value):String(r.key);if(n.has(s))return{path:t,key:s};n.add(s);let i=pa(r.value,[...t,s]);if(i)return i}}else if((0,rt.isSeq)(e))for(let[n,r]of e.items.entries()){let s=pa(r,[...t,n]);if(s)return s}}function bb(e){return e==="salt"?"a Frozen load never reads its salt, and DataOps templates carry no hash salt: leave it out":"org credentials stay with the sf CLI \u2014 log the org in with sf org login sfdx-url or sf org login jwt before the step, and name it in the file by its alias"}function Jn(e,t,n={}){let r=[...nr(e).map(({path:f,secret:y})=>P(f,`a key shaped like a secret (${y}). The file holds no secret: ${bb(y)}.`)),...ec(e).filter(({path:f})=>!Qa(f)).map(({path:f})=>P(f,`{ env } stands in ${Ha.join(" and ")} alone: write this value in the file. A variable inside a query or a field value would let a CI variable into what is written.`))];if(r.length>0)return{refusals:r};let s=Za.safeParse(e);if(!s.success)return{refusals:s.error.issues.map(f=>{let y=f.path,g=f.code==="invalid_key"?f.issues.map(m=>m.message):[];return P(y,g.join("; ")||f.message)})};let i=s.data,o=Sb(i);if("refusals"in o)return o;let a=hu(i.masking);if("refusals"in a)return a;let c=[],l=[...Eb(i)],u={};for(let[f,y]of Object.entries(i.resources)){let g=rd(i.name,f,y,Wn(t),n.now??new Date,a.sets);if("refusals"in g){c.push(...g.refusals);continue}l.push(...g.warnings),u[f]=g.run}if(c.push(...Rb(u)),c.length>0)return{refusals:c};let d=[];for(let[f,{alias:y}]of Object.entries(i.orgs))typeof y!="string"&&d.push({name:y.env,path:["orgs",f,"alias"],role:f});for(let[f,y]of Object.entries(i.resources))y.kind==="frozen"&&typeof y.dataset.path!="string"&&d.push({name:y.dataset.path.env,path:["resources",f,"dataset","path"],resource:f});return{checked:{file:i,folder:Wn(t),order:o.order,runs:u,variables:d,warnings:l}}}function Eb(e){let t=new Set(Object.values(e.resources).flatMap(n=>n.kind==="mask"&&typeof n.rules=="string"?[n.rules]:[]));return Object.keys(e.masking).filter(n=>!t.has(n)).map(n=>P(["masking",n],"no mask resource names this rule set: nothing masks with it"))}function uh(e,t){return e.variables.filter(n=>(t[n.name]??"").trim()==="")}function dh(e,t){return t.kind!=="seed"?[]:(t.relations??[]).flatMap((n,r)=>{let s=n.parents.from?.split(".")[0];return s===void 0?[]:[{from:s,path:["resources",e,"relations",r,"parents","from"]}]})}function ma(e,t){return[...new Set([...t.dependsOn??[],...dh(e,t).map(({from:n})=>n)])]}function Sb(e){let t=Object.keys(e.resources),n=[],r=new Map;for(let[a,c]of Object.entries(e.resources)){let l=[];for(let{from:u,path:d}of dh(a,c))u===a?n.push(P(d,`a relation draws its parents from the records another resource created: ${a}'s own are drawn by their object alone, without from`)):u in e.resources?l.includes(u)||l.push(u):n.push(P(d,`"${u}" is no resource of this file: name one of ${t.join(", ")}`));(c.dependsOn??[]).forEach((u,d)=>{let f=["resources",a,"dependsOn",d];u===a?n.push(P(f,`a resource does not depend on itself: take ${a} out of its dependsOn`)):u in e.resources?l.includes(u)||l.push(u):n.push(P(f,`"${u}" is no resource of this file: name one of ${t.join(", ")}`))}),r.set(a,l)}if(n.length>0)return{refusals:n};let s=$b(t,r);if(s!==void 0)return{refusals:[P(["resources",s[0]??""],`the resources depend on each other in a circle, ${s.join(" \u2192 ")}: no order applies them. Take one of them out of the dependsOn of the next, or out of what its relations draw their parents from.`)]};let i=[],o=new Set;for(;i.length<t.length;){let a=t.find(c=>!o.has(c)&&(r.get(c)??[]).every(l=>o.has(l)));if(a===void 0)break;i.push(a),o.add(a)}return{order:i}}function Rb(e){let t=[];for(let[n,r]of Object.entries(e))if(r.kind==="seed")for(let s of r.draws??[]){let i=e[s.from];if(i?.kind==="mask"){t.push(P(["resources",n,"relations",s.at,"parents","from"],`${s.from} is a mask resource, which creates no record: a relation draws its parents from the records a seed, a forge or a frozen resource created`));continue}if(i?.kind!=="seed")continue;let o=Pt(i).map(({object:a})=>a);o.includes(s.relation.parentObject)||t.push(P(["resources",n,"relations",s.at,"parents","from"],`${s.from} writes no ${s.relation.parentObject} records: it writes ${o.join(", ")||"none"}`))}return t}function $b(e,t){let n=new Set,r=[],s=i=>{let o=r.indexOf(i);if(o>=0)return[...r.slice(o),i];if(!n.has(i)){r.push(i);for(let a of t.get(i)??[]){let c=s(a);if(c!==void 0)return c}r.pop(),n.add(i)}};for(let i of e){let o=s(i);if(o!==void 0)return o}}function ga(e,t){return yi($t({...sd(e),dependsOn:t}))}var ch=/^[^-\s][^\s]{0,199}$/;function ya(e,t,n={}){let r=Object.keys(e.file.orgs),s=[],i=n.aliases??{};for(let[d,f]of Object.entries(i))r.includes(d)?ch.test(f)||s.push(P(["orgs",d,"alias"],`--alias ${d}= gives no alias: one holds no space and does not start with "-"`)):s.push(P(["orgs"],`--alias names the role ${d}, which the file's orgs do not declare: `+(r.length>0?`its roles are ${r.join(", ")}`:"it declares none")));let o={};for(let[d,{alias:f}]of Object.entries(e.file.orgs)){let y=i[d];if(y!==void 0){o[d]=y;continue}if(typeof f=="string"){o[d]=f;continue}let g=(t[f.env]??"").trim();g===""?s.push(P(["orgs",d,"alias"],`the variable ${f.env} is not set: set it in the job's environment to the alias of the ${d} org, or give --alias ${d}=<alias>`)):ch.test(g)?o[d]=g:s.push(P(["orgs",d,"alias"],`the variable ${f.env} holds no alias: one holds no space and does not start with "-"`))}let a={};for(let[d,f]of Object.entries(e.file.resources)){if(f.kind!=="frozen")continue;let y=Ab(d,f.dataset.path,t,e.folder);"refusal"in y?s.push(y.refusal):a[d]=y.dir}if(s.length>0)return{refusals:s};let c={},l=[];for(let d of e.order){let f=e.runs[d],y=e.file.resources[d];if(f===void 0||y===void 0)continue;let g=ma(d,y),m;if(f.kind==="seed"){let{kind:h,...w}=f;m={name:d,kind:h,dependsOn:g,fingerprint:"",run:w}}else if(f.kind==="mask"){let{kind:h,...w}=f;m={name:d,kind:h,dependsOn:g,fingerprint:"",run:w}}else if(f.kind==="frozen"){let{kind:h,...w}=f,v=n.datasets?.[d];m={name:d,kind:h,dependsOn:g,fingerprint:"",run:w,dataset:{dir:a[d]??"",...v!==void 0?{read:v}:{}}}}else{let{kind:h,...w}=f,v=n.sources?.[d];m={name:d,kind:h,dependsOn:g,fingerprint:"",run:w,source:{role:w.source,alias:o[w.source]??"",...v!==void 0?{read:v}:{}}}}m.fingerprint=ga(m,Object.fromEntries(g.map(h=>[h,c[h]]))),c[d]=m.fingerprint,l.push(m)}let u=yi($t({...e.file,orgs:Object.fromEntries(Object.entries(o).map(([d,f])=>[d,{alias:f}]))}));return{resolved:{checked:e,orgs:o,resources:l,digest:u}}}function Ab(e,t,n,r){let s=["resources",e,"dataset","path"],i;if(typeof t=="string")i=t;else{if(i=(n[t.env]??"").trim(),i==="")return{refusal:P(s,`the variable ${t.env} is not set: set it in the job's environment to the folder the dataset of ${e} was downloaded to`)};if(!vb(i))return{refusal:P(s,`the variable ${t.env} holds ${i}, which is not a path from the root: give the folder of the dataset from the root`)}}let o;try{o=cr(r)}catch{o=void 0}return o!==void 0&&new Oe(o).isInsideRepo(Wn(i))?{refusal:P(s,`the dataset of ${e}, ${Wn(i)}, is inside the repository ${o} that holds the file: a frozen dataset is pseudonymized business data, and stays outside the project. Keep it where the pipeline downloads it, and name that folder.`)}:{dir:Wn(i)}}function fh(e,t,n,r={}){let s=Jn(e,t,r.now?{now:r.now}:{});return"refusals"in s?s:ya(s.checked,n,{...r.aliases?{aliases:r.aliases}:{},...r.sources?{sources:r.sources}:{},...r.datasets?{datasets:r.datasets}:{}})}var hh=new Set(["create","replace","delete"]),Ie=new Set(["create","replace"]);function ba(e){return hh.has(e.action)}function De(e){return Object.entries(e?.resources??{}).filter(([,t])=>t.status!=="destroyed")}function Ea(e,t){let n=[],r=new Set,s=new Set(e);for(;n.length<e.length;){let i=e.find(o=>!r.has(o)&&t(o).every(a=>!s.has(a)||r.has(a)||a===o))??e.find(o=>!r.has(o));if(i===void 0)break;n.push(i),r.add(i)}return n}function st(e,t){let n=e?.resources??{};return Ea(t,r=>n[r]?.dependsOn??[]).reverse()}function Ob(e,t){return t===void 0||t.differs||t.unread!==void 0?!1:[...e.objects.values()].every(n=>n.gone===0&&n.unread===0)}function wa(e){let t={objects:new Map,changedBy:new Map,refusals:[],removalAlone:[],codes:new Map,failed:[],verified:[]};for(let n of e){if("failed"in n){t.failed.push(`run ${n.n}: ${n.failed}`);continue}if("nothing"in n)continue;let r=n.refreshed;r!==void 0&&"unread"in r?t.failed.push(`run ${n.n}: its verification did not say (${r.unread})`):r!==void 0&&t.verified.push(...r.failed);let{preview:s}=n.preview;for(let i of s.objects){let o=t.objects.get(i.objectApiName)??{present:0,gone:0,changed:0,unread:0};o.present+=i.toDelete+i.keptChanged+i.undeletable,o.gone+=i.alreadyGone+i.notVisible,o.changed+=i.changedSince,o.unread+=i.unread,t.objects.set(i.objectApiName,o);for(let[a,c]of Object.entries(i.changedBy)){let l=s.userNames[a]??a;t.changedBy.set(l,(t.changedBy.get(l)??0)+c)}}for(let i of n.preview.refusals)t.refusals.includes(i)||t.refusals.push(i);if(ph(t.codes,n.preview.refusals,n.preview.refusalCodes),"removalAlone"in n.preview){t.removalAlone.push(...n.preview.removalAlone);let i="removalAloneCodes"in n.preview?n.preview.removalAloneCodes:void 0;ph(t.codes,n.preview.removalAlone,i)}}return t}function ph(e,t,n){n?.length===t.length&&t.forEach((r,s)=>e.set(r,n[s]??""))}function Sa(e){return[...e.refusals,...e.removalAlone]}function va(e,t=Sa(e)){return[...new Set(t.flatMap(n=>e.codes.get(n)||[]))]}function Ls(e){return e.length>0?{refusalCodes:[...new Set(e)]}:{}}function ka(e){return[...e.objects].map(([t,n])=>({object:t,present:n.present,gone:n.gone,changed:n.changed}))}function Cb(e){let t=[...e.objects].flatMap(([s,i])=>{let o=[i.gone>0?`${i.gone} gone`:"",i.changed>0?`${i.changed} changed`:"",i.unread>0?`${i.unread} not read`:""].filter(Boolean);return o.length>0?[`${s} ${o.join(", ")}`]:[]});if(e.verified.length>0&&t.push(`its verification: ${e.verified.join("; ")}`),t.length===0)return;let n=[...e.changedBy].sort((s,i)=>i[1]-s[1]),r=n.length>0?` (last changed by ${n.map(([s,i])=>`${s} ${i}`).join(", ")})`:"";return`${t.join("; ")}${r}`}var jb="its state was recovered from its run files, which do not say what it was applied from",Nb={applying:"its last run was stopped part way: what it wrote is taken back from its run file, then it runs again",partial:"its last run was partial: the org refused records of it, or kept some of its records",failed:"its last run failed",destroying:"a removal of it was stopped part way"};function Ib(e){if(e.kind==="frozen"){let n=e.dataset.read;return n===void 0?`its dataset at ${e.dataset.dir} was not read: plan again`:"refusal"in n?n.refusal:void 0}if(e.kind!=="forge")return;let t=e.source.read;return t===void 0?`its source, the ${e.source.role} org, was not read: plan again`:"refusal"in t?t.refusal:void 0}function Ra(e){let{resolved:t,state:n,previews:r}=e,s=r===void 0,i=new Set(e.replace??[]),o=new Map(De(n)),a=new Set(t.resources.map(u=>u.name)),c=new Map;for(let u of t.resources){let d=o.get(u.name),f=Ib(u),y=u.kind;if(d===void 0){c.set(u.name,{resource:u.name,kind:y,action:"create",why:n?.resources[u.name]?.status==="destroyed"?"taken back by an earlier destroy: applied again":"not applied to this org yet",objects:[],...f!==void 0?{refusal:f}:{}});continue}let g=wa(r?.[u.name]??[]),m=[],h=ga(u,Object.fromEntries(u.dependsOn.map(j=>[j,n?.resources[j]?.fingerprint])));d.recovered===!0?m.push(jb):d.fingerprint!==u.fingerprint&&d.fingerprint!==h&&m.push("what it writes changed in the file since it was applied");let w=(y==="mask"?Iu:Nb)[d.status];w!==void 0&&m.push(w);let v=u.dependsOn.filter(j=>{let D=c.get(j);return D!==void 0&&Ie.has(D.action)&&D.kind!=="mask"});if(v.length>0&&m.push(`the resources it depends on run again, with new records: ${v.join(", ")}`),i.has(u.name)&&m.push("--replace asks it"),y==="mask"){c.set(u.name,Db(u.name,d,m,e,s));continue}let k=s?void 0:Cb(g),E=k!==void 0&&Ob(g,e.drift),S=E?void 0:k;m.length===0&&S!==void 0&&e.replaceDrifted===!0&&m.push(`its records drifted (${S}), and --replace-drifted asks it`);let R=ka(g),b=f??(g.refusals.length>0?`a removal of its runs would be refused now: ${g.refusals.join(" ")}`:g.failed.length>0?`what the org holds of it could not be read (${g.failed.join("; ")}): plan again`:void 0),$=f===void 0&&g.refusals.length>0?va(g,g.refusals):[];if(m.length>0)c.set(u.name,{resource:u.name,kind:y,action:"replace",why:`replaced: ${m.join("; ")}`,objects:R,...b!==void 0?{refusal:b,...Ls($)}:{}});else if(s)c.set(u.name,{resource:u.name,kind:y,action:"keep",why:"applied from the same file; what the org holds of it was not read (--quick)",objects:R,...f!==void 0?{refusal:f}:{}});else if(f!==void 0||g.failed.length>0)c.set(u.name,{resource:u.name,kind:y,action:"keep",why:"applied from the same file",objects:R,refusal:f??`what the org holds of it could not be read (${g.failed.join("; ")}): plan again`});else if(S!==void 0)c.set(u.name,{resource:u.name,kind:y,action:"drifted",why:`its records changed since it was applied: ${S}. Left as they are: --replace ${u.name} or --replace-drifted replaces it`,objects:R});else{let j=R.reduce((T,I)=>T+(I.present??0),0),D=R.reduce((T,I)=>T+(I.changed??0),0);c.set(u.name,{resource:u.name,kind:y,action:"keep",why:E?`applied, and the org holds its ${j} record(s) as the checkpoint taken after the apply holds them: ${D} written since hold their values again, as a reset gives them back`:`applied, and the org holds its ${j} record(s) as written`,objects:R})}}return[...st(n,[...o.keys()].filter(u=>!a.has(u))).map(u=>{let d=o.get(u);if(d?.kind==="mask")return{resource:u,kind:"mask",action:"delete",why:Ci("apply",u,d,$a(e,u)),objects:mh(d)};let f=wa(r?.[u]??[]),y=Sa(f),g=y.length>0?`a removal of its runs would be refused now: ${y.join(" ")}`:f.failed.length>0?`what the org holds of it could not be read (${f.failed.join("; ")}): plan again`:void 0;return{resource:u,kind:o.get(u)?.kind??"seed",action:"delete",why:"in the state, gone from the file: its records are taken back",objects:ka(f),...g!==void 0?{refusal:g,...Ls(y.length>0?va(f):[])}:{}}}),...t.resources.flatMap(u=>c.get(u.name)??[])]}function Db(e,t,n,r,s){let i=(c,l,u=[],d)=>({resource:e,kind:"mask",action:c,why:l,objects:u,...d!==void 0?{refusal:d}:{}});if(n.length>0)return i("replace",`replaced: ${n.join("; ")}; ${Oi(t)}`);if(s)return i("keep","applied from the same file; what the org holds of it was not read (--quick)");if(r.dryRuns===void 0)return i("keep","applied from the same file");let o=r.dryRuns[e];if(o===void 0)return i("keep","applied from the same file",[],"it was not dry-run: plan again");if("failed"in o||o.answer.tool!==se){let c="failed"in o?o.failed:`${Te(o.answer.tool)} answered its dry run`;return i("keep","applied from the same file",[],`what the org holds of it could not be read (its dry run: ${c}): plan again`)}let a=Ou(t,o.answer);return a.unread!==void 0?i("keep","applied from the same file",a.objects,`what the org holds of it could not be read: ${a.unread}`):a.drift===void 0?i("keep",Du(a.masked),a.objects):r.replaceDrifted===!0?i("replace",`replaced: its condition selects other records than it masked (${a.drift}), and --replace-drifted asks it; ${Oi(t)}`,a.objects):i("drifted",Pu(e,a.drift),a.objects)}function $a(e,t){let n=e.maskStores?.[t],r=e.org??e.state?.org;return{alias:r?.alias??r?.organizationId??"<alias>",...n!==void 0?{store:n}:{}}}function mh(e){return(e.runs.at(-1)?.objects??[]).map(t=>({object:t.objectApiName,present:t.masked??0}))}function Pb(e,t){let n=new Set(t.filter(i=>Ie.has(i.action)).map(i=>i.resource)),r=new Set(t.filter(i=>Ie.has(i.action)&&i.kind!=="mask").map(i=>i.resource)),s=new Map;for(let i of e.resources){if(!n.has(i.name))continue;let o=i.dependsOn.filter(a=>r.has(a));o.length>0&&s.set(i.name,o)}return s}function Tb(e,t){let n=e.map(r=>({...r}));for(let r of t.objects){let s={wouldCreate:r.wouldCreate,...r.atMost===!0?{atMost:!0}:{}},i=n.find(o=>o.object===r.object);i?Object.assign(i,s):n.push({object:r.object,...s})}return n}function Fb(e,t,n,r){let s=e.resources.find(c=>c.name===t),i=r&&s!==void 0?Ni(s):void 0,o=Ft(n,i),a=s!==void 0?ld(s,n):void 0;return{count:a!==void 0&&o.refusal===void 0?{...o,refusal:a}:o}}function Lb(e,t){let n=e.resources.find(r=>r.name===t);return n!==void 0&&(Ni(n)?.size??0)>0}function xb(e,t,n){let r=e.resources.find(i=>i.name===t);if(r?.kind!=="seed")return[];let s=new Set((r.run.draws??[]).map(i=>i.from));return n.filter(i=>s.has(i))}function Aa(e){return e!==void 0&&"answer"in e?Ft(e.answer).total:void 0}function Mb(e,t){let n=[],{apiRequests:r,storage:s,emails:i}=e;r.leftToday!==void 0&&r.estimate>r.leftToday&&n.push(`The resources the plan writes take about ${r.estimate} API requests, and ${t} has ${r.leftToday} left today: the apply would stop part way. Apply once the org has requests to spare \u2014 the limit is counted over the last 24 hours \u2014 or write fewer records.`),s.left!==void 0&&s.bytes>s.left&&n.push(`The resources the plan writes take about ${lt(s.bytes/1048576)} MB of data storage, and ${t} has ${lt(s.left/1048576)} MB left: the org would refuse records part way. Write fewer records, or free storage first.`);for(let o of i)o.left!==void 0&&o.emails>o.left&&n.push(`The resources the plan writes make ${t} send ${o.emails} ${o.limit} emails, and it has ${o.left} left today: each resource alone may fit, the day does not. Apply the resources over two days, or keep the automation that sends them quiet.`);return n}function _b(e,t,n,r,s){let i=s.estimate,o=0,a=new Map,c=[...s.notCounted];for(let f of e){if((f.action==="delete"||f.action==="replace")&&f.kind!=="mask"&&c.push(`the removal of the runs of ${f.resource}`),!Ie.has(f.action))continue;let y=t?.[f.resource];if(y===void 0||"failed"in y){c.push(`the run of ${f.resource}, not dry-run`);continue}let g=r.get(f.resource);g!==void 0&&f.kind!=="mask"&&c.push(`what ${f.resource} draws from the records ${g.join(", ")} writes first`);let m=Ft(y.answer);m.apiRequests===void 0?c.push(`the requests of the run of ${f.resource}, which its script does not estimate`):i+=m.apiRequests,o+=m.storageBytes;for(let{limit:h,emails:w}of m.emails)a.set(h,(a.get(h)??0)+w)}let l=n?.apiRequests,u=n?.storage,d=n?.emails;return{apiRequests:{estimate:i,...l!==void 0&&!("unread"in l)?{leftToday:l.remaining}:{},partial:c.length>0,...c.length>0?{notCounted:c}:{},...l!==void 0&&"unread"in l?{unread:l.unread}:{},...n===void 0?{unread:"not read: --quick"}:{}},storage:{bytes:o,...u!==void 0&&!("unread"in u)?{left:Math.floor(u.remainingMB*1048576)}:{},...u!==void 0&&"unread"in u?{unread:u.unread}:{},...n===void 0?{unread:"not read: --quick"}:{}},emails:[...a].map(([f,y])=>{let g=d!==void 0&&!("unread"in d)?d[f]?.remaining:void 0;return{limit:f,emails:y,...g!==void 0?{left:g}:{}}})}}function Oa(e){let t=e.previews===void 0,n=Ra(e),r=Pb(e.resolved,n),s=n.map(h=>{let w=h.objects,v,k=h.refusal,E=h.refusal!==void 0?h.refusalCodes??[]:[],S=Ie.has(h.action)?e.dryRuns?.[h.resource]:void 0,R=r.get(h.resource),b=R!==void 0&&Lb(e.resolved,h.resource),$=Ie.has(h.action)?e.draws?.[h.resource]:void 0;$!==void 0&&$.refusals.length>0&&(k??=$.refusals.join(" "));let j=[];if(S!==void 0&&"failed"in S)S.refused!==void 0&&k===void 0&&(k=`its own dry run says a real run would be refused: ${S.refused.message}`,E=[S.refused.code]),k??=`its dry run did not answer: ${S.failed}`;else if(S!==void 0){let O=Fb(e.resolved,h.resource,S.answer,R!==void 0);w=Tb(w,O.count),v={...O.count.apiRequests!==void 0?{apiRequests:O.count.apiRequests}:{},storageBytes:O.count.storageBytes,emails:O.count.emails};let M=O.count.refusal;M!==void 0&&k===void 0&&(k=`its own dry run says a real run would be refused: ${M}`,E=O.count.refusalCodes??[]),j=O.count.notes??[]}else Ie.has(h.action)&&!t&&(k??="it was not dry-run: plan again");let D=R!==void 0?xb(e.resolved,h.resource,R):[],T=R!==void 0&&S!==void 0&&h.kind==="mask"?`; its dry run read the org before ${R.join(", ")} writes: what they write under its condition it masks too, uncounted here`:R!==void 0&&S!==void 0&&b?D.length>0?`; it draws its parents from the records ${D.join(", ")} creates in this apply, which nobody knows before it runs: counted at most as the file gives it`:`; its dry run read the org before ${R.join(", ")} writes: what it draws from those records is counted at most as the file gives it`:"",I=`${h.why}${T}${j.length>0?`; ${j.join("; ")}`:""}`,H=e.resolved.resources.find(O=>O.name===h.resource),ve=H!==void 0&&Ie.has(h.action)?yd(H,$a(e,h.resource)):[];return{resource:h.resource,kind:h.kind,action:k!==void 0?"blocked":h.action,why:I,objects:w,...$!==void 0&&$.draws.length>0?{draws:$.draws}:{},...v!==void 0?{gates:v}:{},...k!==void 0?{refusal:k,...Ls(E)}:{},...ve.length>0?{notes:ve}:{}}}),i=e.resolved.checked.file,o=ol(br(i,e.state,n.some(h=>hh.has(h.action))),t?void 0:e.checkpointEstimate??{unread:"not estimated"},s.filter(h=>Ie.has(h.action)&&h.kind!=="mask").flatMap(h=>h.objects).reduce((h,w)=>h+(w.wouldCreate??0),0)),a=_b(n,e.dryRuns,e.budget,r,cl(o)),c=e.org.alias??e.org.organizationId,l=Mb(a,c);if(l.length>0)for(let h of s)ba(h)&&(h.refusal=l.join(" "),h.action="blocked");let u=s.filter(h=>h.action==="blocked"),d=e.refusal??(l.length>0?`${l.join(" ")} Nothing was written.`:u.length>0?`${u.length===1?"A resource is":`${u.length} resources are`} blocked, and the apply refuses before its first write: ${u.map(h=>`${h.resource} (${h.refusal??h.why})`).join("; ")}`:void 0)??al(o),f=e.refusal!==void 0?[...e.refusalCodes??[]]:l.length>0?[]:u.length>0?u.flatMap(h=>h.refusalCodes??[]):o.flatMap(h=>h.refusal!==void 0?[h.refusal.code]:[]),y=[...e.warnings??[],...sl(i,e.state)],g=h=>s.filter(w=>w.action===h).length,m=e.state;return{env:e.resolved.checked.file.name,org:e.org,state:m!==void 0?{found:!0,serial:m.serial}:{found:!1},actions:s,totals:{create:g("create"),keep:g("keep"),replace:g("replace"),delete:g("delete"),drifted:g("drifted"),blocked:g("blocked")},gates:a,...o.length>0?{checkpoints:o}:{},...e.drift!==void 0?{drift:e.drift}:{},...d!==void 0?{refusal:d,...Ls(f)}:{},...t?{quick:!0}:{},...y.length>0?{warnings:y}:{}}}function gh(e){let n=st(e.state,De(e.state).map(([a])=>a)).map(a=>{let c=e.state?.resources[a];if(c?.kind==="mask")return{resource:a,kind:"mask",action:"delete",why:Ci("destroy",a,c,$a(e,a)),objects:mh(c)};let l=wa(e.previews?.[a]??[]),u=Sa(l),d=u.length>0?`a removal of its runs would be refused now: ${u.join(" ")}`:l.failed.length>0?`what the org holds of it could not be read (${l.failed.join("; ")}): run destroy again`:void 0,f=u.length>0?va(l):[];return{resource:a,kind:c?.kind??"seed",action:d!==void 0?"blocked":"delete",why:"taken back by destroy, into the recycle bin",objects:ka(l),...d!==void 0?{refusal:d}:{},...f.length>0?{refusalCodes:f}:{}}}),r=n.filter(a=>a.action==="blocked"),s=[...new Set(r.flatMap(a=>a.refusalCodes??[]))],i=n.filter(a=>a.kind!=="mask").map(a=>`the removal of the runs of ${a.resource}`),o=e.state;return{env:e.resolved.checked.file.name,org:e.org,state:o!==void 0?{found:!0,serial:o.serial}:{found:!1},actions:n,totals:{create:0,keep:0,replace:0,delete:n.length-r.length,drifted:0,blocked:r.length},gates:{apiRequests:{estimate:0,partial:i.length>0,...i.length>0?{notCounted:i}:{}},storage:{bytes:0},emails:[]},...r.length>0?{refusal:`${r.map(a=>`${a.resource}: ${a.refusal??""}`).join(" ")} Nothing was deleted.`,...s.length>0?{refusalCodes:s}:{}}:{},...e.previews===void 0?{quick:!0}:{},...e.warnings!==void 0&&e.warnings.length>0?{warnings:[...e.warnings]}:{}}}function Ca(e){return e.actions.some(t=>t.action!=="keep"&&t.action!=="drifted")}function yh(e){let t=e.drift;if(t!==void 0&&(t.differs||t.unread!==void 0))return!0;let n=t!==void 0;return e.actions.some(r=>r.action==="drifted"||!(n&&r.action==="keep")&&r.objects.some(s=>(s.gone??0)>0||(s.changed??0)>0))}function ja(e){let t=e.kind==="mask";return e.objects.map(n=>{let r=[n.wouldCreate!==void 0?`${n.atMost===!0?"at most ":""}${n.wouldCreate} `+(t?"to mask":"to write"):"",n.present!==void 0&&n.present>0?`${n.present} ${t?"masked":"in the org"}`:"",(n.gone??0)>0?`${n.gone} gone`:"",(n.changed??0)>0?`${n.changed} changed`:""].filter(Boolean);return r.length>0?`${n.object} ${r.join(", ")}`:""}).filter(Boolean).join("; ")}var qb={apply:"an apply now",destroy:"a destroy now"};function xs(e,t="apply"){let n=[`plan of ${e.env} on ${e.org.alias??e.org.organizationId} (${e.org.kind}, ${e.org.organizationId})`,e.state.found?`state: kept on this machine, serial ${e.state.serial??0}`:"state: none on this machine"];for(let c of e.actions){let l=ja(c);n.push(` ${c.action.padEnd(8)} ${c.resource}${l?` ${l}`:""}`),n.push(` ${c.why}`);for(let u of c.draws??[])n.push(` ${u.lookup} draws its parents from `+(u.parents!==void 0?`the ${u.parents} ${u.object} record(s) ${u.from} created`:`the ${u.object} records ${u.from} creates first`));for(let u of c.notes??[])n.push(` ${u}`);c.refusal!==void 0&&n.push(` refused: ${c.refusal}`)}let{totals:r}=e;n.push(`totals: ${r.create} to create, ${r.replace} to replace, ${r.delete} to delete, ${r.keep} kept, ${r.drifted} drifted, ${r.blocked} blocked`);let{apiRequests:s,storage:i,emails:o}=e.gates,a=(c,l)=>c!==void 0?`, ${c} left`:l!==void 0?` (left: ${l})`:"";n.push(`API requests: about ${s.estimate}`+a(s.leftToday?.toString(),s.unread)+(s.partial?`; not counted: ${(s.notCounted??[]).join(", ")}`:"")),n.push(`data storage: about ${lt(i.bytes/1048576)} MB`+a(i.left!==void 0?`${lt(i.left/1048576)} MB`:void 0,i.unread));for(let c of o)n.push(`emails (${c.limit}): ${c.emails}`+(c.left!==void 0?`, ${c.left} left today`:""));n.push(...ul(e));for(let c of e.warnings??[])n.push(`warning: ${c}`);return e.refusal!==void 0&&n.push(`${qb[t]} would be refused: ${e.refusal}`),n}import{existsSync as Na,readFileSync as Ia}from"node:fs";import{join as zb}from"node:path";function Ms(e){return e.slice(0,15)}function _s(e){let t=new Map,n=new Set;for(let{objectApiName:r,ids:s}of e){let i=t.get(r)??[];for(let o of s)n.has(Ms(o))||(n.add(Ms(o)),i.push(o));t.set(r,i)}return t}function Bb(e,t,n){let r=e.runId!==void 0?zb(n.journalDir,Ae,`${e.runId}.ndjson`):void 0;if(r!==void 0&&Na(r)){let o=gc(Ia(r,"utf8"));if(o!==void 0)return{created:_s(o.created)}}if(e.summary===void 0)return{refusal:"its run keeps no record of what it created"};let s=n.store.fileOf(t.organizationId,t.env,e.summary);if(!Na(s))return{refusal:"its run keeps no record of what it created"};let i=Dt(Ia(s,"utf8"));return i.result.objectResults.some(o=>o.truncated===!0)?{refusal:"its summary names the first of the records it created alone, and its run file is gone"}:{created:_s(i.result.objectResults.map(o=>({objectApiName:o.objectApiName,ids:o.createdIds})))}}async function Kb(e,t,n){if(e.summary===void 0)return{refusal:"its run keeps no summary"};let r=n.store.fileOf(t.organizationId,t.env,e.summary);if(!Na(r))return{refusal:"its run keeps no summary"};let s=await ar(r,Ia(r,"utf8"),t.target,ir(n.journalDir));if("refusal"in s)return{refusal:`its summary ${s.refusal}`};let{result:i}=s.summary,o=nc({idRemapTable:i.remapTable,idRemapExisting:[...i.existingSourceIds,...i.updatedSourceIds],idRemapCreated:i.createdByObject});return{created:_s([...o].reverse().map(a=>({objectApiName:a.objectApiName,ids:[...a.ids].reverse()})))}}async function Ub(e,t,n){if(Dr(e.sas)===void 0||e.sas===void 0)return{refusal:"its run names no sas"};let r=n.store.sasOf(t.organizationId,t.env,e.sas),s=new Oe,i=(await Xt(r,s)).find(c=>Ms(c)===Ms(t.organizationId));if(i===void 0)return{refusal:"its sas holds no mapping of a load into this org"};let o=await new lr(r,{orgId:i,guard:s}).recorded();if(o?.created===void 0)return{refusal:"its sas holds no load that says which records it created"};let a=zc(o);return{created:_s([...a].reverse().map(c=>({objectApiName:c.objectApiName,ids:[...c.ids].reverse()})))}}async function Da(e,t,n,r){let s=e?.resources[t];if(s===void 0||s.status==="destroyed")return{refusal:`${t} has not created its records in this org yet`};if(s.status!=="applied")return{refusal:`${t} is ${s.status}, not applied whole: apply it again first`};let i=s.runs.at(-1);if(i===void 0||i.takenBack===!0)return{refusal:`${t} holds no run whose records are in the org`};let o=await Pa(i,n,r);return"refusal"in o?{refusal:`${t}: ${o.refusal}`}:o}async function Pa(e,t,n){switch(e.script){case"sandforge-seed":return Bb(e,t,n);case"sandforge-clone":return Kb(e,t,n);case"sandforge-frozen":return Ub(e,t,n);default:return{refusal:`its records are kept by ${Te(e.script)}, which this SandForge reads not`}}}function Vb(e,t){let n=e.relation.parentObject,r=`${e.relation.childObject}.${e.relation.lookupField}`,s=[...t.get(n)??[]],i=tr.maxExistingParents;if(s.length===0){let o=[...t.keys()].filter(a=>(t.get(a)??[]).length>0);return{refusal:`the relation on ${r} draws its parents from the ${n} records ${e.from} created, and it created none: it created ${o.join(", ")||"no record"}`}}return e.limit!==void 0?{ids:s.slice(0,e.limit)}:s.length>i?{refusal:`the relation on ${r} draws its parents from the ${s.length} ${n} records ${e.from} created, more than the ${i} a relation's parents hold: give the relation a limit, and its parents are the first ${i} or fewer`}:{ids:s}}async function qs(e,t,n,r,s){let i={ids:new Map,draws:[],refusals:[]};if(e.kind!=="seed")return i;let o=new Map;for(let a of e.run.draws??[]){let c={lookup:`${a.relation.childObject}.${a.relation.lookupField}`,from:a.from,object:a.relation.parentObject};if(n.has(a.from)){i.draws.push(c);continue}let l=o.get(a.from);if(l===void 0&&(l=await Da(t,a.from,r,s),o.set(a.from,l)),"refusal"in l){i.draws.push(c),i.refusals.push(`the relation on ${c.lookup} draws its parents from ${a.from}, whose records cannot be read: ${l.refusal}`);continue}let u=Vb(a,l.created);if("refusal"in u){i.draws.push(c),i.refusals.push(u.refusal);continue}i.ids.set(a.at,u.ids),i.draws.push({...c,parents:u.ids.length})}return i}function pe(e){return cc.some(t=>be(t)===e)}function vh(e,t,n){let r=e===0||e===3||e===4||pe(e),s=t??(r?void 0:Xc(n));return s!==void 0&&s!==""?s.slice(0,4e3):void 0}function Yb(e){return Ii(e).map(t=>{let n=[t.keptChanged>0?`${t.keptChanged} changed since the run, kept`:"",t.keptDependents>0?`${t.keptDependents} kept for records that stay (${t.heldBy.join(", ")||"records that stay"})`:"",t.refused>0?`${t.refused} refused`:"",(t.notVisible??0)>0?`${t.notVisible} not visible to the user`:"",(t.notReached??0)>0?`${t.notReached} not reached`:"",...t.reasons].filter(Boolean);return{object:t.objectApiName,created:0,refused:t.refused,deleted:t.deleted,kept:t.keptChanged+t.keptDependents+t.refused,...n.length>0?{reason:n.join("; ").slice(0,2e3)}:{}}})}function Gb(e){return(e?.objects??[]).map(t=>({object:t.object,created:t.created,refused:t.refused,deleted:0,kept:0,...t.errors.length>0?{reason:t.errors.slice(0,5).join("; ").slice(0,2e3)}:{}}))}function Hb(e){try{return typeof JSON.parse(e)?.refused?.code=="string"}catch{return!1}}function wt(e,t,n){if(!(t.trim()===""||Hb(t)))try{return e(t)}catch(r){if(r instanceof re){n(` ${r.message}`);return}throw r}}function Ta(e,t,n){let r=Dr(e.sas);if(r!==void 0){let s=n.store.fileOf(t.organizationId,t.env,St(r,e.n));return Yn(s)?s:void 0}if(e.summary!==void 0){let s=n.store.fileOf(t.organizationId,t.env,e.summary);if(Yn(s))return s}if(e.runId!==void 0&&Yn(wh(n.journalDir,Ae,`${e.runId}.ndjson`)))return e.runId}async function Fa(e,t,n,r){let s={organizationId:t.org.organizationId,env:t.env},i=t.resources[n.resource];if(i===void 0)throw new F("invalid",`The state holds no resource ${n.resource} to take back`);if(i.kind==="mask")return Qb(e,t,n);let o=await e.store.update(t,u=>hi(u,n.resource)),a=[],c=!1,l=!1;for(let u of[...i.runs].reverse()){if(u.takenBack===!0)continue;let d=Ta(u,s,e);if(d===void 0)continue;e.say(`${n.resource}: taking back run ${u.n}`);let f=md(i.kind,{target:n.target.alias,subject:d,includeChanged:n.includeChanged,acceptAutomation:n.acceptAutomation,sweep:n.sweep}),y=await e.runner(f.script,f.args,r),g=wt(E=>gd(i.kind,E),y.stdout,e.say),m=Ii(g).reduce((E,S)=>E+S.deleted,0);l||=g!==void 0?m>0:y.code!==1&&y.code!==2;let h=pe(y.code),w=y.code===0||y.code===3,v=h?"destroying":w?y.code===3?n.ends.left:n.ends.whole:i.status,k=vh(y.code,void 0,y.stderr);if(a.push({resource:n.resource,action:n.action,phase:"remove",run:u.n,script:f.script,exitCode:y.code,status:v,...u.summary!==void 0?{summary:u.summary}:{},objects:Yb(g),...g!==void 0?{answer:g}:{},...k!==void 0?{refusal:k}:{}}),y.code===3&&(c=!0),y.code===0&&(o=await e.store.update(o,E=>yr(E,n.resource,u.n))),!w)return h||(o=await e.store.update(o,E=>Rt(E,{resource:n.resource,status:i.status}))),{whole:!1,code:h?y.code:1,wrote:l,steps:a,state:o}}return o=await e.store.update(o,u=>Rt(u,{resource:n.resource,status:c?n.ends.left:n.ends.whole})),{whole:!c,code:c?3:0,wrote:l,steps:a,state:o}}async function Qb(e,t,n){let r=t.resources[n.resource];if(r===void 0)throw new F("invalid",`The state holds no resource ${n.resource} to take back`);let s=await e.store.update(t,u=>hi(u,n.resource)),i=e.store.sasOf(t.org.organizationId,t.env,It(n.resource)),o=r.runs.at(-1),a=(u,d,f)=>({resource:n.resource,action:n.action,phase:"remove",run:o?.n??1,script:"sandforge-dataops",exitCode:d,status:u,objects:(o?.objects??[]).map(y=>({object:y.objectApiName,created:0,refused:0,deleted:0,kept:0,masked:y.masked??0,reason:f}))});e.say(`${n.resource}: deleting its store ${i}`);let c;try{c=await Tu(i)}catch(u){let d=u instanceof Error?u.message:String(u);return e.say(`${n.resource}: ${d}`),s=await e.store.update(s,f=>Rt(f,{resource:n.resource,status:r.status})),{whole:!1,code:1,wrote:!1,steps:[a(r.status,1,d)],state:s}}e.say(Fu(n.resource,c));for(let u of r.runs)u.takenBack!==!0&&(s=await e.store.update(s,d=>yr(d,n.resource,u.n)));s=await e.store.update(s,u=>Rt(u,{resource:n.resource,status:n.ends.whole}));let l=c.snapshots.length>0?`snapshot${c.snapshots.length===1?"":"s"} ${c.snapshots.join(", ")}`:"its store";return{whole:!0,code:0,wrote:!1,steps:[a(n.ends.whole,0,`left masked, as destroy leaves a masking; ${l} deleted`)],state:s}}var Xb=new Set(["sandforge-seed","sandforge-clone","sandforge-dataops","sandforge-frozen"]);function Jt(e,t){return t&&Xb.has(e.script)?{...e,args:[...e.args,"--accept-emails"]}:e}function Zb(e,t){let n=new Map(e.actions.map(o=>[o.resource,o])),r=new Set(De(t).map(([o])=>o)),s=st(t,e.actions.filter(o=>(o.action==="delete"||o.action==="replace"&&!dt(o.kind))&&r.has(o.resource)).map(o=>o.resource)).map(o=>({phase:"remove",resource:o,action:n.get(o)?.action??"delete"})),i=e.actions.filter(o=>o.action==="create"||o.action==="replace").map(o=>({phase:"run",resource:o.resource,action:o.action}));return[...s,...i]}function kh(e,t,n){if(pe(e))return{status:"applying",counts:e,stops:!0};if(e===0&&t!==void 0){let r=t.created;return n!==void 0&&r!==n?{status:"partial",counts:3,stops:!1,short:`it created ${r} record(s) of the ${n} its dry run counted`}:{status:"applied",counts:0,stops:!1}}return e===3?{status:"partial",counts:3,stops:!1}:e===4?{status:"partial",counts:4,stops:!0}:{status:"failed",counts:1,stops:!0}}function eE(e,t){return t===void 0?e:e.status==="partial"&&e.short===void 0&&"short"in t?t.short===void 0||t.unstable?e:{...e,short:`its verification found ${t.short}`}:e.status!=="applied"?e:"unread"in t?{...e,short:`not verified: ${t.unread}`}:t.unstable?{status:"partial",counts:4,stops:!0,short:`its verification is unstable: ${t.short??""}`}:t.short===void 0?e:{status:"partial",counts:3,stops:!1,short:`its verification found ${t.short}`}}async function tE(e,t,n){let{resource:r,n:s,where:i,target:o,templateFile:a,dry:c,signal:l}=n,u=i.env,d=c!==void 0&&"answer"in c?c.answer:void 0,f=d===void 0||n.readTooEarly?void 0:Ft(d).created,y=await e.orgNow();if(r.kind==="seed"){let D=hr(u,r.name,s),T=r.run.seed??(d?.tool==="sandforge-seed"?d.seed:void 0),I=await e.store.update(t,at=>tn(at,{resource:r.name,kind:"seed",fingerprint:r.fingerprint,dependsOn:r.dependsOn,run:{script:"sandforge-seed",runId:D,...T!==void 0?{seed:T}:{},startedAt:y}})),H=Jt(mn(r,{target:o.alias,templateFile:a,runId:D,summaryFile:"",...T!==void 0?{seed:T}:{}}),n.acceptEmails),ve=await e.runner(H.script,H.args,l),O=wt(Dt,ve.stdout,e.say),M=O!==void 0?Tr(O):void 0,ae=(M?.created??0)>0||Yn(wh(e.journalDir,Ae,`${D}.ndjson`)),bt=O!==void 0?await e.store.writeFile(i.organizationId,u,le(r.name,s),ve.stdout).then(()=>le(r.name,s)):void 0;return{state:I,script:H.script,code:ve.code,...M!==void 0?{count:M}:{},...O!==void 0?{answer:O}:{},...bt!==void 0?{summary:bt}:{},wrote:ae,...f!==void 0?{planned:f}:{},...M?.refusal!==void 0?{answered:M.refusal}:{},stderr:ve.stderr}}if(r.kind==="frozen")return nE(e,t,n,y,f);if(r.kind==="mask")return rE(e,t,n,y);let g=le(r.name,s),m=await e.store.prepareFile(i.organizationId,u,g),h=await e.store.update(t,D=>tn(D,{resource:r.name,kind:"forge",fingerprint:r.fingerprint,dependsOn:r.dependsOn,run:{script:"sandforge-clone",summary:g,startedAt:y}})),w=Aa(c),v=r.kind==="forge"&&r.run.records!==void 0?Cr(e.journalDir,i.organizationId,u,r.name):void 0,k=Jt(mn(r,{target:o.alias,templateFile:a,runId:"",summaryFile:m,...w!==void 0?{maxTotal:w}:{},...v!==void 0?{rootsPlanFile:v}:{}}),n.acceptEmails),E=await e.runner(k.script,k.args,l);v!==void 0&&Jb(v,{force:!0});let S=Yn(m)?Wb(m,"utf8"):void 0,R=wt(cn,S??"",e.say)??wt(cn,E.stdout,e.say),b=R!==void 0?jr(R):void 0,$=b!==void 0?b.created>0:S!==void 0,j;if(E.code===0&&S!==void 0&&(b?.created??0)>0){e.say(`${r.name}: verifying run ${s}`);let D=await e.runner(k.script,xl({summary:m,target:o.alias,source:r.source.alias}),l),T=D.stdout.trim()===""?void 0:wt(Bl,D.stdout,e.say);if(T!==void 0){let I=Ul(T);j={unstable:T.result.verdict==="unstable",...I!==void 0?{short:I}:{}}}else D.code!==0&&(j={unread:`its verification ended ${D.code} without an answer`})}return{state:h,script:k.script,code:E.code,...b!==void 0?{count:b}:{},...R!==void 0?{answer:R}:{},...S!==void 0?{summary:g}:{},wrote:$,...f!==void 0?{planned:f}:{},...j!==void 0?{verified:j}:{},...R?.error!==void 0?{answered:R.error}:{},stderr:E.stderr}}async function nE(e,t,n,r,s){let{resource:i,n:o,where:a,target:c,templateFile:l,dry:u,signal:d}=n,f=await e.store.update(t,R=>tn(R,{resource:i.name,kind:"frozen",fingerprint:i.fingerprint,dependsOn:i.dependsOn,run:{script:"sandforge-frozen",sas:Ve(i.name),startedAt:r}})),y=Aa(u),g=Jt(mn(i,{target:c.alias,templateFile:l,runId:"",summaryFile:"",replace:n.replace,acceptAutomation:n.acceptAutomation,...y!==void 0?{maxTotal:y}:{}}),n.acceptEmails),m=await e.runner(g.script,g.args,d),h=wt(Nr,m.stdout,e.say),w=h!==void 0?pn(h):void 0;w?.refusal!==void 0&&e.say(`${i.name}: ${w.refusal}`);let v=h===void 0?pe(m.code):(w?.created??0)>0||uu(h),k=h!==void 0?await e.store.writeFile(a.organizationId,a.env,le(i.name,o),m.stdout).then(()=>le(i.name,o)):void 0,E=h?.verdict,S=E!==void 0?Ri(E):m.code===0&&(w?.created??0)>0?{unread:"the load chained no verification"}:void 0;return{state:f,script:g.script,code:m.code,...w!==void 0?{count:w}:{},...h!==void 0?{answer:h}:{},...k!==void 0?{summary:k}:{},wrote:v,...s!==void 0?{planned:s}:{},...S!==void 0?{verified:S}:{},...n.replace&&h!==void 0&&Ir(h)?{tookBackEarlier:!0}:{},...w?.refusal!==void 0?{answered:w.refusal}:{},stderr:m.stderr}}async function rE(e,t,n,r){let{resource:s,n:i,where:o,target:a,templateFile:c,signal:l}=n,u=await e.store.update(t,v=>tn(v,{resource:s.name,kind:"mask",fingerprint:s.fingerprint,dependsOn:s.dependsOn,run:{script:"sandforge-dataops",startedAt:r}})),d=await e.store.prepareFolder(o.organizationId,o.env,It(s.name)),f=Jt(mn(s,{target:a.alias,templateFile:c,runId:"",summaryFile:"",store:d}),n.acceptEmails),y=await e.runner(f.script,f.args,l),g=wt(Pr,y.stdout,e.say),m=g!==void 0?hn(g):void 0;m?.refusal!==void 0&&e.say(`${s.name}: ${m.refusal}`);let h=m!==void 0?m.objects.some(v=>v.masked>0):pe(y.code),w=g!==void 0?await e.store.writeFile(o.organizationId,o.env,le(s.name,i),y.stdout).then(()=>le(s.name,i)):void 0;return{state:u,script:f.script,code:y.code,...g!==void 0?{answer:g}:{},...w!==void 0?{summary:w}:{},wrote:h,...m!==void 0?{masking:m}:{},...m?.refusal!==void 0?{answered:m.refusal}:{},stderr:y.stderr}}function sE(e,t){let n=kh(e,void 0,void 0);if(e!==0)return n;let r=(t?.objects??[]).reduce((s,i)=>s+i.notMasked,0);return t?.short!==void 0||r>0?{status:"partial",counts:3,stops:!1,short:t?.short??`${r} record(s) still hold their original values: the next apply masks them again`}:{status:"applied",counts:0,stops:!1}}function iE(e){return(e?.objects??[]).map((t,n)=>({object:t.object,created:0,refused:t.refused,deleted:0,kept:0,masked:t.masked,...n===0&&e?.snapshotId!==void 0?{reason:`snapshot ${e.snapshotId} of the values it wrote over, taken first, kept on this machine until destroy deletes it`}:{}}))}async function oE(e,t,n,r,s){if(n.kind==="frozen"){let o=await e.store.prepareFolder(r.organizationId,r.env,Ve(n.name));return{payload:Tt(n,{sasDir:o})}}if(n.kind!=="seed"||(n.run.draws??[]).length===0)return{payload:Tt(n,{})};let i=await qs(n,t,new Set,{...r,target:s.alias},{store:e.store,journalDir:e.journalDir});return i.refusals.length>0?{refusal:i.refusals.join(" ")}:{payload:Tt(n,{drawn:i.ids})}}function Bs(e){return e===0?"success":pe(e)?"cancelled":e===1?"failure":"partial"}async function bh(e,t){let{plan:n,target:r,resolved:s}=t,i=s.checked.file.name,o=(g,m=t.state,h=[])=>({result:{plan:n,steps:[],status:"failure",refusal:g,...h.length>0?{refusalCodes:[...h]}:{},state:{serial:m?.serial??0}},exitCode:1});if(n.refusal!==void 0)return o(n.refusal,t.state,n.refusalCodes);let a=Zb(n,t.state),c=n.checkpoints?.find(g=>g.step==="before"),l=n.checkpoints?.find(g=>g.step==="after");if(a.length===0&&l===void 0)return e.say("nothing to do: the org holds the environment as the file describes it"),{result:{plan:n,steps:[],status:"success",state:{serial:t.state?.serial??0}},exitCode:0};let u=Me(e.locksDir,r.organizationId,{operation:"apply",env:i,alias:r.alias},e.lockOptions);if("busy"in u){let g=Ue(u.busy);return o(g.message,t.state,[g.code])}let d=new AbortController,f,y=(e.onStop??Fe)(g=>{f=g,e.say(`
148
+ stopped by ${g}: the step under way stops before its next call to the org, and the state keeps what it wrote; apply again takes up from there`),d.abort()});try{let g;try{let O=await e.store.read(r.organizationId,i);if(O===void 0!=(t.state===void 0)||O!==void 0&&(O.serial!==t.state?.serial||O.lineage!==t.state.lineage))return o(`The state of ${i} on ${r.alias} changed since the plan (another apply or destroy ran, or a cache put back another state). Nothing was written: plan again.`,O,[$r]);g=O??gr({env:i,org:{organizationId:r.organizationId,kind:r.kind,username:r.username,alias:r.alias},fileDigest:s.digest,sandforgeVersion:e.sandforgeVersion})}catch(O){if(O instanceof F)return o(O.message,t.state,[Ke(O).code]);throw O}g={...g,file:{digest:s.digest},sandforgeVersion:e.sandforgeVersion};let m={organizationId:r.organizationId,env:i},h=[],w=[],v=[],k=new Map,E=!1,S,R=new Map(s.resources.map(O=>[O.name,O])),b=new Set,$=0,j=[],D={alias:r.alias,kind:r.kind},T=kr(s.checked.file);if(c!==void 0&&a.length>0){let O=await Ei(e,{org:D,step:"before",name:c.name,...T},d.signal);if(j.push(O.result),O.checkpoint===void 0){let ae=f!==void 0?be(f):pe(O.result.exitCode)?O.result.exitCode:1;return{result:{plan:n,steps:[],checkpoints:j,status:Bs(ae),refusal:`The checkpoint before the first write, '${c.name}', was not taken (${O.result.refusal??`exit ${O.result.exitCode}`}). Nothing was written.`,state:{serial:g.serial}},exitCode:ae}}let M=O.checkpoint;g=await e.store.update(g,ae=>Be(ae,"before",M))}try{for(let O of a){if($+=1,S!==void 0||f!==void 0){w.push({resource:O.resource,why:"the apply was stopped before it"});continue}let M=R.get(O.resource),ae=(M?.dependsOn??[]).filter(ne=>k.has(ne));if(O.phase==="run"&&ae.length>0){w.push({resource:O.resource,why:`it depends on ${ae.map(ne=>`${ne} (${k.get(ne)??"not whole"})`).join(", ")}`});continue}let bt=or(e.locksDir,r.organizationId,e.lockOptions);if(bt!==void 0){e.say(an(bt).message),v.push(1),w.push({resource:O.resource,why:an(bt).message});break}if(O.phase==="remove"){let ne=t.acceptAutomation||s.checked.file.resources[O.resource]?.accept?.automation===!0,J=await Fa(e,g,{resource:O.resource,action:O.action,target:r,includeChanged:!1,sweep:!1,acceptAutomation:ne,ends:{whole:"destroyed",left:"partial"}},d.signal);if(g=J.state,h.push(...J.steps),E||=J.wrote,pe(J.code)){S=J.code;continue}if(v.push(J.code),J.code!==0&&J.code!==3)break;continue}if(M===void 0)continue;let at=en(g.resources[O.resource]),Xn=await oE(e,g,M,m,r);if("refusal"in Xn){e.say(`${O.resource}: not run, ${Xn.refusal}`),v.push(1),w.push({resource:O.resource,why:Xn.refusal}),k.set(O.resource,"not run");break}let lm=await e.store.writeFile(m.organizationId,i,St(O.resource,at),`${JSON.stringify(Xn.payload,null,2)}
149
+ `),um=M.dependsOn.some(ne=>b.has(ne));e.say(`${O.resource}: run ${at} (${O.action})`);let B=await tE(e,g,{resource:M,n:at,where:m,target:r,templateFile:lm,dry:t.dryRuns[O.resource],readTooEarly:um,replace:O.action==="replace"&&dt(M.kind),acceptAutomation:t.acceptAutomation||s.checked.file.resources[O.resource]?.accept?.automation===!0,acceptEmails:t.acceptEmails===!0,signal:d.signal});g=B.state,E||=B.wrote,M.kind!=="mask"&&b.add(O.resource);let Et=B.masking,ke=M.kind==="mask"?sE(B.code,Et):eE(kh(B.code,B.count,B.planned),B.verified),dm=await e.orgNow();if(g=await e.store.update(g,ne=>Rt(ne,{resource:O.resource,status:ke.status,run:{endedAt:dm,exitCode:B.code,objects:Et!==void 0?Et.objects.map(J=>({objectApiName:J.object,created:0,refused:J.refused,masked:J.masked})):(B.count?.objects??[]).map(J=>({objectApiName:J.object,created:J.created,refused:J.refused})),...B.summary!==void 0?{summary:B.summary}:{},...Et?.snapshotId!==void 0?{snapshotId:Et.snapshotId}:{}}})),B.tookBackEarlier===!0)for(let ne of g.resources[O.resource]?.runs??[])ne.n===at||ne.takenBack===!0||(g=await e.store.update(g,J=>yr(J,O.resource,ne.n)));let Zn=M.kind==="mask"?iE(Et):Gb(B.count),Wa=vh(B.code,B.answered,B.stderr);if(h.push({resource:O.resource,action:O.action,phase:"run",run:at,script:B.script,exitCode:B.code,status:ke.status,...B.summary!==void 0?{summary:B.summary}:{},objects:ke.short!==void 0&&Zn[0]!==void 0?[{...Zn[0],reason:ke.short},...Zn.slice(1)]:Zn,...B.answer!==void 0?{answer:B.answer}:{},...Wa!==void 0?{refusal:Wa}:{}}),ke.short!==void 0&&e.say(`${O.resource}: ${ke.short}`),pe(B.code)){S=B.code,e.say(M.kind==="mask"?`${O.resource}: its masking was stopped; the state keeps it applying, and its store the snapshot it took first: apply again masks what its condition selects`:`${O.resource}: its run was stopped; the state keeps it applying, and its ${M.kind==="forge"?"summary what it created":M.kind==="frozen"?"sas what it loaded":"run file what it wrote"}: apply again takes it back and runs it whole`);continue}if(v.push(ke.counts),ke.status!=="applied"&&k.set(O.resource,ke.status),ke.stops)break}}catch(O){let M=`the apply stopped on an error: ${O instanceof Error?O.message:String(O)}`;e.say(M),v.push(1);for(let ae of a.slice($))w.push({resource:ae.resource,why:M})}let I=g.checkpoints?.after;if(E&&I!==void 0&&f===void 0){let O=await jt(e,{org:D,checkpoint:I,why:"taken before this apply wrote"},d.signal);j.push(O),g=await e.store.update(g,M=>Be(M,"after",void 0))}let H=f===void 0&&S===void 0&&Qt(v)===0;if(l!==void 0&&H){let O=await Ei(e,{org:D,step:"after",name:l.name,...T},d.signal);j.push(O.result);let M=O.checkpoint;M!==void 0?g=await e.store.update(g,ae=>Be(ae,"after",M)):pe(O.result.exitCode)?S=O.result.exitCode:(e.say(`the checkpoint once applied, '${l.name}', was not taken: reset has nothing to rewind to until an apply takes it, which the next one does`),v.push(1))}let ve=f!==void 0?be(f):S!==void 0?S:(()=>{let O=Qt(v);return O===1&&E?3:O})();return{result:{plan:n,steps:h,...j.length>0?{checkpoints:j}:{},...w.length>0?{skipped:w}:{},status:Bs(ve),state:{serial:g.serial}},exitCode:ve}}finally{y(),u.lock.release()}}function aE(e){return e.map(t=>{let n=t.step==="delete"?`checkpoint ${t.checkpoint??""} deleted`:`checkpoint ${t.step==="before"?"before the first write":"once applied"}`;return t.exitCode!==0?` ${n}: exit ${t.exitCode}, ${t.step==="delete"?"kept":"not taken"}: ${t.refusal??""}`:t.step==="delete"?` ${n}`:` ${n}: exit 0, taken ${t.checkpoint??""}`})}function La(e,t){let n=[""];for(let r of e.steps){if(r.script==="sandforge-dataops"){let i=r.objects.map(o=>r.phase==="run"?`${o.object} ${o.masked??0} masked${o.refused>0?`, ${o.refused} refused`:""}`:`${o.object} ${o.masked??0} left masked`).join("; ");n.push(` ${r.resource} ${r.phase==="run"?`masking ${r.run}: exit ${r.exitCode}`:"store deleted"}, ${r.status}${i?` ${i}`:""}`),r.refusal!==void 0&&n.push(` ${r.refusal}`);for(let o of r.objects)o.reason!==void 0&&n.push(` ${o.object}: ${o.reason}`);continue}let s=r.objects.map(i=>r.phase==="run"?`${i.object} ${i.created} created${i.refused>0?`, ${i.refused} refused`:""}`:`${i.object} ${i.deleted} deleted${i.kept>0?`, ${i.kept} kept`:""}`).join("; ");n.push(` ${r.resource} ${r.phase==="run"?"run":"removal of run"} ${r.run}: exit ${r.exitCode}, ${r.status}${s?` ${s}`:""}`),r.refusal!==void 0&&n.push(` ${r.refusal}`);for(let i of r.objects)i.reason!==void 0&&n.push(` ${i.object}: ${i.reason}`)}for(let r of e.skipped??[])n.push(` ${r.resource}: not run, ${r.why}`);return n.push(...aE(e.checkpoints??[])),e.refusal!==void 0&&n.push(`${t} refused: ${e.refusal}`),n.push(`${t}: ${e.status}; state serial ${e.state.serial}`),n}import{readFile as Hn,readdir as cE,stat as lE}from"node:fs/promises";import{join as it}from"node:path";var uE={"sandforge-seed":"seed","sandforge-clone":"forge","sandforge-frozen":"frozen","sandforge-dataops":"mask"},dE=/^([1-9][0-9]{0,5})\.summary\.json$/,fE=/^([a-z][a-z0-9-]{0,62})\.([1-9][0-9]{0,5})\.json$/,pE=/^([a-z][a-z0-9-]{0,62})-([1-9][0-9]{0,5})-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,hE=/\.load-\d{1,16}\.ndjson$/,K=class extends Error{constructor(n,r){super(r);this.code=n;this.name="Refused"}code},Z="Nothing was written.";async function ot(e,t){try{return(await cE(e,{withFileTypes:!0})).filter(r=>t?r.isDirectory():r.isFile()).map(r=>r.name).sort()}catch(n){let r=n?.code;if(r==="ENOENT"||r==="ENOTDIR")return[];throw n}}function xa(e,t,n){let r=e.ranks.get(t);r===void 0&&(r=new Map,e.ranks.set(t,r));let s=r.get(n);return s===void 0&&(s={seedRuns:[]},r.set(n,s)),s}async function $h(e,t){let n=t.resolved.checked.file.name,r=t.target.organizationId,s=e.store.folderOf(r,n),i={ranks:new Map,frozen:new Set,dataops:new Set,unclaimed:[]},o=f=>Gt.safeParse(f).success;for(let f of(await ot(it(s,"runs"),!0)).filter(o))for(let y of await ot(it(s,"runs",f),!1)){let g=dE.exec(y)?.[1];g!==void 0&&(xa(i,f,Number(g)).summary=le(f,Number(g)))}for(let f of await ot(it(s,"templates"),!1)){let y=fE.exec(f);y?.[1]===void 0||y[2]===void 0||!o(y[1])||(xa(i,y[1],Number(y[2])).template=St(y[1],Number(y[2])))}for(let f of(await ot(it(s,"frozen"),!0)).filter(o))i.frozen.add(f);for(let f of(await ot(it(s,"dataops"),!0)).filter(o))i.dataops.add(f);let a=new Set(t.resolved.resources.map(f=>f.name)),c=new Set([...i.ranks.keys(),...i.frozen,...i.dataops]),l=(await ot(it(s,".."),!0)).filter(f=>f!==n&&f.startsWith(`${n}-`)),u=`env-${n}-`,d=hc(e.journalDir,Ae);for(let f of await ot(it(e.journalDir,Ae),!1)){if(!f.endsWith(".ndjson")||!f.startsWith(u))continue;let y=f.slice(0,-7),g=pE.exec(y.slice(u.length));if(g?.[1]===void 0||g[2]===void 0)continue;let m=g[1],h=a.has(m)||c.has(m),w=l.find(E=>y.startsWith(`env-${E}-`));if(w!==void 0&&!h)continue;let v=it(e.journalDir,Ae,f),k=await d.get(y);if(k===void 0)throw new K("RUN_UNREAD",`The seed run file ${v} does not read as a run: a state rebuilt without it would leave what it created to nobody. Move it aside if it is not a run of ${n}. ${Z}`);if(k.targetOrganizationId===void 0)throw new K("RUN_UNREAD",`The seed run file ${v} names no Organization Id: nothing tells whether it wrote to ${t.target.alias} or to another org. Move it aside if it is not a run of ${n} on ${t.target.alias}. ${Z}`);if(de(k.targetOrganizationId,r)){if(w!==void 0)throw new K("RUN_UNCLAIMED",`The seed run file ${v} may be run ${g[2]} of ${m} of ${n}, or a run of ${w}, kept on this machine too: their names begin alike, and nothing tells them apart. Move it out of the folder while ${n} is recovered if it is ${w}'s. ${Z}`);if(!h){i.unclaimed.push({file:v,resource:m,run:k});continue}xa(i,m,Number(g[2])).seedRuns.push({runId:y,run:k})}}return i}async function Ks(e,t){try{let n=await $h(e,t);return n.unclaimed.length>0||n.frozen.size>0||n.dataops.size>0||[...n.ranks.values()].some(r=>[...r.values()].some(s=>s.summary!==void 0||s.seedRuns.length>0))}catch(n){return n instanceof K}}function Gn(e){if(typeof e!="string")return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}async function Ah(e){try{return(await lE(e)).mtime.toISOString()}catch{return}}async function mE(e){let t=o=>new K("RUN_UNREAD",`The summary ${e} does not read (${o}): a state rebuilt without it would leave what its run created to nobody. ${Z}`),n;try{n=await Hn(e,"utf8")}catch(o){throw t(o instanceof Error?o.message:String(o))}let r;try{r=JSON.parse(n)}catch{throw t("not JSON")}let s=r?.tool,i=typeof s=="string"?uE[s]:void 0;try{if(i==="seed")return{kind:i,answer:Dt(n)};if(i==="frozen")return{kind:i,answer:Nr(n)};if(i==="mask")return{kind:i,answer:Pr(n)};if(i==="forge"){let o=r,a=Gn(o.finishedAt),c=typeof o.elapsedMs=="number"&&Number.isFinite(o.elapsedMs)&&o.elapsedMs>=0?o.elapsedMs:void 0;return{kind:i,answer:cn(n),...a!==void 0?{finishedAt:a}:{},...c!==void 0?{elapsedMs:c}:{}}}}catch(o){throw o instanceof re?t(o.message):o}throw t("it names no script of an environment")}function Oh(e){return e.removal!==void 0&&ni(e).length===0}function gE(e){return e.interrupted===!0||e.result.cancelled===!0?"applying":e.result.status==="success"?"applied":e.result.status==="partial"?"partial":"failed"}function Ma(e){return e.map(t=>({objectApiName:t.object,created:t.created,refused:t.refused}))}function Eh(e,t,n){if(!(t===void 0||de(t,n.target.organizationId)))throw new K("RUN_OTHER_ORG",`The summary ${e} is of a run that wrote to ${t}, not to ${n.target.alias} (${n.target.organizationId}): it was copied from another org's folder. Put it back where it came from. ${Z}`)}async function yE(e,t,n,r,s,i){let o=t.resolved.checked.file.name,a=m=>e.store.fileOf(t.target.organizationId,o,m);if(s.seedRuns.length>1)throw new K("RUNS_CONFLICT",`Two seed runs are kept for run ${r} of ${n}: ${s.seedRuns.map(m=>m.runId).join(", ")}. One rank is one run: the state they come from cannot be told. ${Z}`);let c=s.seedRuns[0],l=i?.kind==="seed"?i.answer:void 0,u=l?.result.operationId??c?.runId;if(l!==void 0&&c!==void 0&&l.result.operationId!==c.runId)throw new K("RUNS_CONFLICT",`The summary of run ${r} of ${n} is of the run ${l.result.operationId}, and the seed run file of that rank of ${c.runId}: one rank is one run. ${Z}`);if(l!==void 0&&!l.result.operationId.startsWith(`env-${o}-${n}-${r}-`))throw new K("RUNS_CONFLICT",`The summary ${a(le(n,r))} is of the run ${l.result.operationId}, which is not run ${r} of ${n}. ${Z}`);let d=c!==void 0&&Oh(c.run);if(l!==void 0&&!d){let m=await Hn(a(pi(n,r)),"utf8").catch(()=>{}),h;try{h=m!==void 0?JSON.parse(m):void 0}catch{h=void 0}let w=h?.runId===l.result.operationId?mc(h):void 0;d=w!==void 0&&l.result.objectResults.every(v=>v.truncated!==!0)&&ni(jc({runId:l.result.operationId,targetOrgId:l.target,status:l.result.status,objectResults:l.result.objectResults},w)).length===0}let f=Gn(l?.startedAt)??Gn(c?.run.startedAt)??new Date(0).toISOString(),y=Gn(l!==void 0?l.finishedAt:c?.run.end?.at),g=l!==void 0?Ma(Tr(l).objects):(c?.run.created??[]).map(m=>({objectApiName:m.objectApiName,created:m.ids.length,refused:0}));return{run:{n:r,script:"sandforge-seed",...u!==void 0?{runId:u}:{},...s.summary!==void 0&&l!==void 0?{summary:s.summary}:{},...l!==void 0?{seed:l.seed}:{},startedAt:f,...y!==void 0?{endedAt:y}:{},objects:g,...d?{takenBack:!0}:{}},status:l!==void 0?gE(l):"applying"}}async function wE(e,t,n,r,s){let i=t.resolved.checked.file.name,o=le(n,r),a=e.store.fileOf(t.target.organizationId,i,o),{answer:c}=s,l=!1,u=await Hn(e.store.fileOf(t.target.organizationId,i,pi(n,r)),"utf8").catch(()=>{});if(u!==void 0){let m=await ar(a,await Hn(a,"utf8"),t.target.alias,ir(e.journalDir));if(!("refusal"in m)){let h=xc(u,Lc(Fc(m.summary)));l="earlier"in h&&h.earlier?.removalLeft?.length===0}}let d=c.running===!0||c.interrupted===!0?void 0:s.finishedAt,f=s.finishedAt??await Ah(a)??new Date(0).toISOString(),y=new Date(Date.parse(f)-(s.elapsedMs??0)).toISOString(),g=c.running===!0||c.interrupted===!0?"applying":c.error!==void 0?"failed":c.result.failedCount>0?"partial":"applied";return{run:{n:r,script:"sandforge-clone",summary:o,startedAt:y,...d!==void 0?{endedAt:d}:{},objects:Ma(jr(c).objects),...l?{takenBack:!0}:{}},status:g}}async function Sh(e,t,n){let r=t.resolved.checked.file.name,s=a=>a!==void 0?Ah(e.store.fileOf(t.target.organizationId,r,a)):Promise.resolve(void 0),i=await s(n.template),o=await s(n.summary);return{startedAt:i??o??new Date(0).toISOString(),...o!==void 0?{endedAt:o}:{}}}async function vE(e,t){if((await ot(e,!1)).some(i=>hE.test(i)))return!1;let n=new Oe,r=(await Xt(e,n)).find(i=>de(i,t));if(r===void 0)return!1;let s=await new lr(e,{orgId:r,guard:n}).recordedLoads();return s.length>0&&s.some(i=>i.removal!==void 0)&&s.every(i=>i.created!==void 0&&Bc(i).length===0)}async function kE(e,t){let n=(await Xt(e,new Oe)).filter(r=>!de(r,t.target.organizationId));if(n.length!==0)throw new K("RUN_OTHER_ORG",`The sas ${e} keeps loads into ${n.join(", ")}, not into ${t.target.alias} (${t.target.organizationId}): it was copied from another org's folder. Put it back where it came from. ${Z}`)}function bE(e){let t=pn(e);return t.refusal!==void 0?"failed":t.objects.some(n=>n.refused>0)?"partial":e.verdict===void 0||e.verdict.status==="PASSED"?"applied":"partial"}function EE(e){let t=hn(e);return t.refusal!==void 0?"failed":t.short!==void 0||t.objects.some(n=>n.notMasked>0)?"partial":"applied"}function SE(e,t,n){let r=new Set;for(let s of n.values())r.add(s.kind);if(t.frozen.has(e)&&r.add("frozen"),t.dataops.has(e)&&r.add("mask"),[...t.ranks.get(e)?.values()??[]].some(s=>s.seedRuns.length>0)&&r.add("seed"),r.size>1)throw new K("RUNS_CONFLICT",`The run files of ${e} are of ${[...r].join(" and ")} runs: one resource is of one kind, and the state they come from cannot be told. ${Z}`);return[...r][0]}async function RE(e,t,n,r){let s=t.resolved.checked.file.name,i=t.target.organizationId,o=n.ranks.get(r)??new Map,a=new Map;for(let[w,v]of o)v.summary!==void 0&&a.set(w,await mE(e.store.fileOf(i,s,v.summary)));let c=SE(r,n,a);if(c===void 0)return;for(let[w,v]of a){let k=e.store.fileOf(i,s,le(r,w));v.kind==="seed"&&Eh(k,v.answer.targetOrgId,t),v.kind==="forge"&&Eh(k,v.answer.targetOrgId,t)}let l=[],u=[...o.keys()].sort((w,v)=>w-v);if(c==="seed")for(let w of u){let v=o.get(w);v===void 0||v.summary===void 0&&v.seedRuns.length===0||l.push(await yE(e,t,r,w,v,a.get(w)))}else if(c==="forge")for(let w of u){let v=a.get(w);v?.kind==="forge"&&l.push(await wE(e,t,r,w,v))}else if(c==="frozen"){let w=e.store.sasOf(i,s,Ve(r));await kE(w,t);let v=await vE(w,i);for(let k of u){let E=o.get(k),S=a.get(k);if(E?.template===void 0){if(S?.kind!=="frozen"||v)continue;throw new K("RUN_UNREAD",`Run ${k} of ${r} keeps its summary and not the payload its load was given, ${e.store.fileOf(i,s,St(r,k))}, which its removal is run from: a state rebuilt without it would leave what the load created to nobody. ${Z}`)}let R=S?.kind==="frozen"?S.answer:void 0;if(l.push({run:{n:k,script:"sandforge-frozen",sas:Ve(r),...R!==void 0&&E.summary!==void 0?{summary:E.summary}:{},...await Sh(e,t,E),objects:R!==void 0?Ma(pn(R).objects):[],...v?{takenBack:!0}:{}},status:R!==void 0?bE(R):"applying"}),R!==void 0&&Ir(R))for(let b of l.slice(0,-1))b.run.takenBack=!0}}else{let w=!n.dataops.has(r);for(let v of u){let k=o.get(v),E=a.get(v);if(k===void 0)continue;let S=E?.kind==="mask"?E.answer:void 0;if(S===void 0&&w)continue;let R=S!==void 0?hn(S):void 0;l.push({run:{n:v,script:"sandforge-dataops",...S!==void 0&&k.summary!==void 0?{summary:k.summary}:{},...R?.snapshotId!==void 0?{snapshotId:R.snapshotId}:{},...await Sh(e,t,k),objects:(R?.objects??[]).map(b=>({objectApiName:b.object,created:0,refused:b.refused,masked:b.masked})),...w?{takenBack:!0}:{}},status:S!==void 0?EE(S):"applying"})}}if(l.length===0)return;let d=l.map(w=>w.run),f=l.at(-1),y=d.every(w=>w.takenBack===!0)?"destroyed":f?.run.takenBack===!0?"partial":f?.status??"applying",g=t.resolved.resources.find(w=>w.name===r),m=d.flatMap(w=>w.endedAt!==void 0?[w.endedAt]:[]).sort(),h=d.map(w=>w.startedAt).sort();return{name:r,state:{kind:c,fingerprint:tc,dependsOn:g!==void 0?[...g.dependsOn]:[],status:y,runs:d,recovered:!0},firstStartedAt:h[0]??new Date(0).toISOString(),...m.length>0?{lastEndedAt:m.at(-1)}:{}}}async function $E(e,t,n){let r=t.resolved.checked.file,i=(await new yc({root:ge(e.journalDir),locksDir:e.locksDir}).list({organizationId:t.target.organizationId})).flatMap(d=>d.valid&&d.checkpoint!==void 0?[d.checkpoint]:[]),o=[],a={},c=`${r.name} before`,l=i.filter(d=>d.name===c&&Date.parse(d.takenAt)<=Date.parse(n.first));l.length===1&&l[0]!==void 0?a.before=l[0].checkpointId:rn(r,"before")===void 0&&l.length===0?o.push("checkpoint.before: the file asks none"):o.push(`checkpoint.before: ${l.length===0?"no":`${l.length}`} checkpoint(s) of this org named '${c}' taken before the first run: none is linked, and destroy --rewind has none to return to`);let u=rn(r,"after");if(u===void 0)o.push("checkpoint.after: the file asks none");else{let d=n.last,f=i.filter(y=>y.name===u&&d!==void 0&&Date.parse(y.readFrom)>=Date.parse(d));f.length===1&&f[0]!==void 0?a.after=f[0].checkpointId:o.push(`checkpoint.after: ${f.length===0?"no":`${f.length}`} checkpoint(s) of this org named '${u}' taken after the last run: none is linked, and reset has none to rewind to until an apply takes it`)}return{...a,notLinked:o}}function AE(e,t){let n=i=>{let o=/^(\d+)\.(\d+)\.(\d+)/.exec(i);return o?[Number(o[1]),Number(o[2]),Number(o[3])]:void 0},r=typeof e=="string"?n(e):void 0,s=n(t);if(r===void 0||s===void 0)return!1;for(let i=0;i<3;i++)if((r[i]??0)!==(s[i]??0))return(r[i]??0)>(s[i]??0);return!1}async function OE(e,t){let n=t.resolved.checked.file.name,{alias:r,organizationId:s}=t.target;try{let l=await e.store.read(s,n);if(l===void 0)return{damaged:!1};throw new K("STATE_KEPT",`This machine keeps a state of ${n} on ${r} that reads, serial ${l.serial}: state recover never writes over one, and plan reads it. ${Z}`)}catch(l){if(!(l instanceof F))throw l;if(l.code!=="damaged"){let u=Ke(l);throw new K(u.code,u.message)}}let i=e.store.stateFileOf(s,n),o;try{o=JSON.parse(await Hn(i,"utf8"))}catch{o=void 0}let a=o,c=a?.version;if(typeof c=="number"&&c>1||AE(a?.sandforgeVersion,e.sandforgeVersion))throw new K("STATE_NEWER",`The state ${i} was written by a later SandForge (${String(a?.sandforgeVersion??`version ${String(c)}`)}; this one is ${e.sandforgeVersion}): update it, and plan again. ${Z}`);return{damaged:!0}}async function Ch(e,t){let n=t.resolved.checked.file.name,{target:r}=t,s=Me(e.locksDir,r.organizationId,{operation:"recover",env:n,alias:r.alias},e.lockOptions);if("busy"in s)return{refusal:Ue(s.busy)};try{let{damaged:i}=await OE(e,t),o=await $h(e,t),a=[];for(let k of[...o.ranks.keys(),...o.frozen,...o.dataops]){if(a.some(S=>S.name===k))continue;let E=await RE(e,t,o,k);E!==void 0&&a.push(E)}let c=[];for(let k of o.unclaimed){if(Oh(k.run)){c.push(`${k.file}: a run of ${k.resource}, which neither the file nor the environment's folder has, taken back whole: passed over`);continue}throw new K("RUN_UNCLAIMED",`The seed run file ${k.file} is of a resource ${k.resource} that neither the file nor the environment's folder has: it may be another environment's, whose name begins as ${n} does. Move it out of the folder if it is, or put ${k.resource} back in the file. ${Z}`)}if(a.length===0)throw new K("NO_RUNS",`This machine keeps no run of ${n} on ${r.alias}: there is nothing to rebuild a state from. If the org holds nothing of the environment, apply it with --accept-no-state. ${Z}`);a.sort((k,E)=>Date.parse(k.firstStartedAt)-Date.parse(E.firstStartedAt)||k.name.localeCompare(E.name));let l=a[0]?.firstStartedAt??new Date(0).toISOString(),d=a.flatMap(k=>k.lastEndedAt!==void 0?[k.lastEndedAt]:[]).sort().at(-1),f=await $E(e,t,{first:l,...d!==void 0?{last:d}:{}}),g={...gr({env:n,org:{organizationId:r.organizationId,kind:r.kind,username:r.username,alias:r.alias},fileDigest:t.resolved.digest,sandforgeVersion:e.sandforgeVersion}),resources:Object.fromEntries(a.map(k=>[k.name,k.state])),...f.before!==void 0||f.after!==void 0?{checkpoints:{...f.before!==void 0?{before:f.before}:{},...f.after!==void 0?{after:f.after}:{}}}:{}},m=Ht.safeParse({...g,serial:1});if(!m.success){let k=m.error.issues[0];throw new K("RUN_UNREAD",`The run files of ${n} do not make a state (${k?.path.join(".")??""}: ${k?.message??"refused"}). ${Z}`)}let h=i?await e.store.setAside(r.organizationId,n):void 0,w=await e.store.write(g,{serial:0,lineage:g.lineage}),v=new Set(t.resolved.resources.map(k=>k.name));return{state:w,result:{env:n,org:{organizationId:w.org.organizationId,kind:w.org.kind,alias:r.alias},state:{serial:w.serial,lineage:w.lineage},...h!==void 0?{setAside:h}:{},resources:Object.fromEntries(a.map(k=>[k.name,{kind:k.state.kind,status:k.state.status,runs:k.state.runs.map(E=>E.n),takenBack:k.state.runs.filter(E=>E.takenBack===!0).map(E=>E.n),inFile:v.has(k.name)}])),checkpoints:{...f.before!==void 0?{before:f.before}:{},...f.after!==void 0?{after:f.after}:{}},notLinked:[...f.notLinked,...c].slice(0,20)}}}catch(i){if(i instanceof K)return{refusal:{code:i.code,message:i.message,exit:1}};throw i}finally{s.lock.release()}}function Rh(e){return`${e.length===1?"run":"runs"} ${e.join(", ")}`}function jh(e){let t=[`state of ${e.env} on ${e.org.alias??e.org.organizationId} rebuilt from its run files: serial ${e.state.serial}`],n=Math.max(...Object.keys(e.resources).map(r=>r.length));for(let[r,s]of Object.entries(e.resources)){let i=s.takenBack.length===0?"":s.takenBack.length===s.runs.length?", taken back":`; ${Rh(s.takenBack)} taken back`;t.push(` ${r.padEnd(n)} ${s.kind}, ${s.status}: ${Rh(s.runs)}${i}`+(s.inFile?"":"; gone from the file"))}e.checkpoints.before!==void 0&&t.push(` checkpoint.before: ${e.checkpoints.before}`),e.checkpoints.after!==void 0&&t.push(` checkpoint.after: ${e.checkpoints.after}`);for(let r of e.notLinked)t.push(` ${r}`);return e.setAside!==void 0&&t.push(`the state that did not read is kept, set aside: ${e.setAside}`),t.push("next: plan replaces each resource still in the org, whose run files do not say what it was applied from, and asks no --accept-no-state"),t}function CE(e){return st(e,De(e).map(([t])=>t))}async function Nh(e,t){let{plan:n,target:r,resolved:s}=t,i=s.checked.file.name,o=(f,y=[])=>({result:{plan:n,steps:[],status:"failure",refusal:f,...y.length>0?{refusalCodes:[...y]}:{},state:{serial:t.state?.serial??0}},exitCode:1});if(t.state===void 0)return await Ks(e,{resolved:s,target:r})?o(`This machine keeps no state of ${i} on ${r.alias}, but keeps runs of it: the records they wrote are still in the org, and destroy reaches only what a state names. "${ce("env")} state recover --file <file> --org ${r.alias}" rebuilds the state from them; then destroy again. Nothing was deleted.`,["NO_STATE"]):(e.say(`this machine keeps no state of ${i} on ${r.alias}, nor any run of it: nothing applied from here is left to take back. Records an apply from another machine or a CI job left are not known here: restore its journal directory (SANDFORGE_JOURNAL_DIR), then destroy again`),{result:{plan:n,steps:[],status:"success",state:{serial:0}},exitCode:0});if(n.refusal!==void 0)return o(n.refusal,n.refusalCodes);let a=CE(t.state),c=Me(e.locksDir,r.organizationId,{operation:"destroy",env:i,alias:r.alias},e.lockOptions);if("busy"in c){let f=Ue(c.busy);return o(f.message,[f.code])}let l=new AbortController,u,d=(e.onStop??Fe)(f=>{u=f,e.say(`
150
+ stopped by ${f}: the removal under way stops before its next call to the org; destroy again takes up from the state`),l.abort()});try{let f;try{let b=await e.store.read(r.organizationId,i);if(b===void 0||b.serial!==t.state.serial||b.lineage!==t.state.lineage)return o(`The state of ${i} on ${r.alias} changed since the plan of the destruction (another apply or destroy ran, or a cache put back another state). Nothing was deleted: run destroy again.`,[$r]);f=b}catch(b){if(b instanceof F)return o(b.message,[Ke(b).code]);throw b}let y=[],g=[],m=[],h=!1,w,v;for(let[b,$]of a.entries()){if(u!==void 0||w!==void 0){v??=b;break}let j=or(e.locksDir,r.organizationId,e.lockOptions);if(j!==void 0){e.say(an(j).message),m.push(1),v=b;break}let D=t.acceptAutomation||s.checked.file.resources[$]?.accept?.automation===!0,T=await Fa(e,f,{resource:$,action:"delete",target:r,includeChanged:t.includeChanged,sweep:t.sweep,acceptAutomation:D,ends:{whole:"destroyed",left:"partial"}},l.signal);if(f=T.state,y.push(...T.steps),h||=T.wrote,pe(T.code)){w=T.code,v=b+1;break}if(m.push(T.code),T.code!==0&&T.code!==3){v=b+1;break}}for(let b of v!==void 0?a.slice(v):[])g.push({resource:b,why:u!==void 0||w!==void 0?"the destroy was stopped before it":"a removal before it was refused or failed: its records would be kept for it"});let k=Object.values(f.resources).every(b=>b.status==="destroyed"),E=[];if(k&&v===void 0){let b=Object.values(f.resources).some($=>$.kind==="mask");e.say(`every record of ${i} is taken back from ${r.alias}${b?", and what it masked left masked":""}: the state keeps it as destroyed, and the next apply creates it again`);for(let{step:$,checkpoint:j}of Sr(f)){let D=await jt(e,{org:{alias:r.alias,kind:r.kind},checkpoint:j,why:"the environment it was taken of is taken back"},l.signal);E.push(D),D.exitCode===0&&(f=await e.store.update(f,T=>Be(T,$,void 0)))}}let S=u!==void 0?be(u):w!==void 0?w:(()=>{let b=Qt(m);return b===1&&h?3:b})();return{result:{plan:n,steps:y,...E.length>0?{checkpoints:E}:{},...g.length>0?{skipped:g}:{},status:Bs(S),state:{serial:f.serial}},exitCode:S}}finally{d(),c.lock.release()}}var jE="taken back by a destroy: none of the org's records is its",NE="taken back by a destroy, which deleted its store and left its records masked: a masking creates no record",Ih="a masking creates no record: it writes over those the org holds that its condition selects",IE={applying:"its last run was stopped part way",partial:"its last run was partial",failed:"its last run failed",destroying:"a removal of it was stopped part way"};function Dh(e){return`${IE[e]??e}: it names no record until it is applied whole \u2014 apply again`}function Ph(e,t,n){let r=e.filter(i=>i.env===t&&(i.state?.org.alias===n||i.organizationId.slice(0,15)===n.slice(0,15)));if(r.length>1){let i=r.map(o=>`${o.organizationId}, written ${o.state?.updatedAt??"?"}`).join("; ");return{refusal:{code:"TWO_STATES",message:`${r.length} states of ${t} on this machine are of ${n}: ${i} \u2014 an alias reused for another org. Give --org the Organization Id of the one meant.`,exit:1}}}let[s]=r;return s===void 0?{refusal:{code:"NO_STATE",message:`This machine keeps no state of ${t} on ${n}: nothing was applied to it from here, or the journal directory of the apply was not restored. output reads the state alone, and reaches no org.`,exit:1}}:s.state===void 0?{refusal:{code:"STATE_DAMAGED",message:`${s.damaged??"The state does not read."} Nothing was read.`,exit:1}}:{state:s.state}}async function Th(e,t){let n={organizationId:e.org.organizationId,env:e.env,target:e.org.alias??e.org.organizationId},r=Ea(Object.keys(e.resources),o=>e.resources[o]?.dependsOn??[]),s={},i=!0;for(let o of r){let a=e.resources[o];if(a===void 0)continue;let c=a.runs.at(-1),l={kind:a.kind,status:a.status,...c!==void 0?{run:c.n}:{},records:{}};if(a.status==="destroyed"){s[o]={...l,why:a.kind==="mask"?NE:jE};continue}if(a.status!=="applied"&&(i=!1),a.kind==="mask"){s[o]={...l,masked:Object.fromEntries((c?.objects??[]).map(d=>[d.objectApiName,d.masked??0])),...c?.snapshotId!==void 0?{snapshotId:c.snapshotId}:{},why:a.status==="applied"?Ih:`${Dh(a.status)}; ${Ih}`};continue}if(a.status!=="applied"){s[o]={...l,why:Dh(a.status)};continue}if(c===void 0||c.takenBack===!0){i=!1,s[o]={...l,why:"it holds no run whose records are in the org"};continue}let u=await Pa(c,n,t);if("refusal"in u){i=!1,s[o]={...l,why:u.refusal};continue}s[o]={...l,records:Object.fromEntries(u.created)}}return{output:{env:e.env,org:{organizationId:e.org.organizationId,kind:e.org.kind,...e.org.alias!==void 0?{alias:e.org.alias}:{}},state:{serial:e.serial,updatedAt:e.updatedAt},resources:s},whole:i}}function Fh(e){let{org:t}=e,n=[`${e.env} on ${t.alias??t.organizationId} (${t.kind}, ${t.organizationId}): state serial ${e.state.serial}, written ${e.state.updatedAt}`];for(let[r,s]of Object.entries(e.resources)){n.push(` ${r} ${s.kind}, ${s.status}`+(s.run!==void 0?`, run ${s.run}`:""));for(let[i,o]of Object.entries(s.records))n.push(` ${i} ${o.length>0?o.join(" "):"none"}`);for(let[i,o]of Object.entries(s.masked??{}))n.push(` ${i} ${o} masked`);s.snapshotId!==void 0&&n.push(` snapshot ${s.snapshotId}, taken first`),s.why!==void 0&&n.push(` ${s.why}`)}return n}var Lh={reset:"after",destroy:"before"};function _a(e,t){let n=Lh[e],r=t?.checkpoints?.[n];return r!==void 0?{step:n,checkpoint:r}:void 0}function qa(e){let t=e.resolved.checked.file.name,{alias:n}=e.target,r=a=>({code:"NO_CHECKPOINT",message:`${a} Nothing was written.`,exit:1}),s=e.verb==="reset"?"reset":"destroy --rewind",i=e.state;if(i===void 0)return r(`This machine keeps no state of ${t} on ${n}: ${s} rewinds the org to a checkpoint its state names. Restore the journal directory of the apply, or apply first.`);if(_a(e.verb,i)===void 0)return r(e.verb==="reset"?`The state of ${t} on ${n} names no checkpoint taken after an apply: the file asks none (checkpoint.after), or the last apply did not take it. Apply with checkpoint.after in the file, then reset.`:`The state of ${t} on ${n} names no checkpoint taken before its first apply: the file asked none (checkpoint.before: true) when it was first applied. destroy without --rewind takes back what the environment wrote.`);let o=Object.entries(i.resources).filter(([,a])=>a.kind==="mask");if(e.verb==="destroy"&&o.length>0)return{code:"MASKED",message:`The state of ${t} on ${n} names mask resources (${o.map(([a])=>a).join(", ")}): the checkpoint taken before the first apply holds the values they wrote over, and a rewind to it would put them back into the org. destroy never unmasks: destroy without --rewind takes back what the environment wrote, and leaves its maskings as they are. Nothing was written.`,exit:1};if(e.verb==="reset"){let a=Object.entries(i.resources).filter(([,c])=>c.status!=="applied"&&c.status!=="destroyed");if(a.length>0)return r(`${a.map(([c,l])=>`${c} is ${l.status}`).join(", ")}: the last apply did not end whole, and the checkpoint taken after the apply before it no longer holds the environment the state names. Apply again, then reset.`)}}async function xh(e,t,n){let r=_a(t.verb,t.state);if(r===void 0)return{refusal:"no checkpoint to rewind to"};e.say(`checkpoint ${r.checkpoint}: reading what a rewind to it would do`);let s=await e.runner(ue,ki({org:t.target.alias,store:ge(e.journalDir),checkpoint:r.checkpoint,dryRun:!0,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails,acceptNoUndo:t.acceptNoUndo,acceptUnseen:t.acceptUnseen}),n);return dl(s)}var vt=e=>e.toLocaleString("en-US");function Mh(e,t){let{alias:n}=e.target,r=`it deletes ${vt(t.toDelete)} record(s) created since, gives ${vt(t.toGiveBack)} their values back and brings ${vt(t.toBringBack)} back from the recycle bin \u2014 whoever made these changes`+(Rr(t.lastChangedBy)!==""?`, last changed by ${Rr(t.lastChangedBy)}`:"");return e.verb==="reset"?`Type ${n} to reset it to '${t.checkpoint.name}', as ${e.resolved.checked.file.name} was applied: ${r}:`:`Type ${n} to rewind it to before ${e.resolved.checked.file.name} was first applied: ${r}; the environment's checkpoints are then deleted, and this is not undone:`}function DE(e){return{...e,resources:Object.fromEntries(Object.entries(e.resources).map(([t,n])=>[t,{...n,status:"destroyed",runs:n.runs.map(r=>({...r,takenBack:!0}))}]))}}async function _h(e,t,n){let{target:r,resolved:s,verb:i}=t,o=s.checked.file.name,a=_a(i,t.state),c={env:o,org:{organizationId:r.organizationId,kind:r.kind,alias:r.alias},verb:i,checkpoint:{step:Lh[i],id:a?.checkpoint??"",...n!==void 0?{name:n.checkpoint.name,takenAt:new Date(n.checkpoint.takenAt).toISOString()}:{}},...n!==void 0?{preview:{toDelete:n.toDelete,toGiveBack:n.toGiveBack,toBringBack:n.toBringBack,lastChangedBy:n.lastChangedBy}}:{}},l=(h,w)=>({result:{...c,exitCode:1,status:"failure",undo:{offered:!1,why:"nothing was rewound"},refusal:h,state:{serial:w}},exitCode:1}),u=qa(t);if(u!==void 0||a===void 0||t.state===void 0)throw new Error(u?.message??"There is no checkpoint to rewind to.");let d=t.state,f=Me(e.locksDir,r.organizationId,{operation:i,env:o,alias:r.alias},e.lockOptions);if("busy"in f)return l(Ue(f.busy).message,d.serial);let y=new AbortController,g,m=(e.onStop??Fe)(h=>{g=h,e.say(`
151
+ stopped by ${h}: the rewind stops before its next call to the org, and leaves its journal: run this again to take it up`),y.abort()});try{let h;try{let b=await e.store.read(r.organizationId,o);if(b===void 0||b.serial!==d.serial||b.lineage!==d.lineage)return l(`The state of ${o} on ${r.alias} changed since it was read (another apply, destroy or reset ran, or a cache put back another state). Nothing was written: run this again.`,b?.serial??d.serial);h=b}catch(b){if(b instanceof F)return l(b.message,d.serial);throw b}e.say(`${i==="reset"?"reset":"destroy --rewind"}: rewinding ${r.alias} to checkpoint ${a.checkpoint}`);let w=await e.runner(ue,ki({org:r.alias,store:ge(e.journalDir),checkpoint:a.checkpoint,dryRun:!1,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails,acceptNoUndo:t.acceptNoUndo,acceptUnseen:t.acceptUnseen}),y.signal),v=pl(w),k=g!==void 0?be(g):v.exitCode,E=[];if(i==="destroy"&&k===0){h=await e.store.update(h,DE);for(let{step:b,checkpoint:$}of Sr(h)){let j=await jt(e,{org:{alias:r.alias,kind:r.kind},checkpoint:$,why:"the environment it was taken of is taken back"},y.signal);E.push(j),j.exitCode===0&&(h=await e.store.update(h,D=>Be(D,b,void 0)))}e.say(`every record of ${o} is taken back from ${r.alias}, with what anyone changed since its first apply: the state keeps it as destroyed, and the next apply creates it again`)}let S=hl({verb:i,alias:r.alias,checkpoint:a.checkpoint,journalDir:e.journalDir,deleted:E.length>0&&E.every(b=>b.exitCode===0)},v),R=v.refusal===void 0?void 0:v.refusal.code==="RECREATE"?`${v.refusal.message} ${i==="reset"?"reset":"destroy --rewind"} never makes records again with new Ids, which the state would no longer name: rewind with sandforge checkpoint itself, then apply again.`:v.refusal.message;return{result:{...c,exitCode:k,status:g!==void 0?"cancelled":v.status,...v.answer!==void 0?{answer:v.answer}:{},undo:S,...R!==void 0?{refusal:R.slice(0,8e3)}:{},...E.length>0?{deleted:E}:{},state:{serial:h.serial}},exitCode:k}}finally{m(),f.lock.release()}}function qh(e){let t=e.verb==="reset"?"reset":"destroy --rewind",n=[""],r=e.answer;if(r?.deleted!==void 0){let s=(r.residual??[]).reduce((i,o)=>i+o.count,0);n.push(` rewind to ${e.checkpoint.id}: exit ${e.exitCode}, ${e.status} ${vt(r.deleted.done)} deleted, ${vt(r.givenBack?.done??0)} given back, ${vt(r.broughtBack?.done??0)} brought back`+(s>0?`, ${vt(s)} still differ`:""))}for(let s of e.deleted??[])n.push(s.exitCode===0?` checkpoint ${s.checkpoint??""} deleted`:` checkpoint ${s.checkpoint??""} kept: ${s.refusal??""}`);return e.refusal!==void 0&&n.push(`${t} refused: ${e.refusal}`),n.push(ml(e.undo)),n.push(`${t}: ${e.status}; state serial ${e.state.serial}`),n}import{randomBytes as PE}from"node:crypto";import{existsSync as TE,readFileSync as FE,statSync as LE}from"node:fs";import{open as xE,rename as ME,rm as _E}from"node:fs/promises";import{dirname as qE,resolve as za}from"node:path";var Kh=1440*6e4;function Uh(e){let t={};for(let[n,r]of Object.entries(e.dryRuns))"answer"in r&&r.answer.tool===Y&&(t[n]=r.answer.seed);return Xs.parse({savedPlan:1,sandforgeVersion:e.sandforgeVersion,madeAt:e.madeAt,file:{digest:e.digest},state:e.state===void 0?{found:!1}:{found:!0,serial:e.state.serial,lineage:e.state.lineage},line:e.line,seeds:t,plan:e.plan})}function Vh(e,t,n){let r=qE(za(t));if(!TE(r)||!LE(r).isDirectory())return{code:"BAD_LINE",message:`--out ${za(t)}: its folder ${r} is not there. Nothing was read.`,exit:2};if(n)return;let s=fi(e,t);if(s!==void 0)return{code:"PLAN_IN_REPOSITORY",message:`--out ${za(t)} is inside the repository ${s} that holds the file: a plan names the org by its Organization Id, its state, and the users who changed its records since, and committed with the project it would publish them. Keep it outside \u2014 in CI, in $RUNNER_TEMP, handed to the job that applies as an artifact \u2014 or give --out-in-repository for a folder of it that is never committed. Nothing was read.`,exit:2}}async function Wh(e,t){let n=`${e}.${PE(6).toString("hex")}.tmp`,r=await xE(n,"wx",ui);try{await r.writeFile(`${JSON.stringify(t,null,2)}
152
+ `,"utf8"),await r.sync()}finally{await r.close()}try{await ME(n,e)}catch(s){throw await _E(n,{force:!0}),s}}function Jh(e){let t=i=>({refusal:{code:"PLAN_UNREAD",message:`--plan ${e} ${i}. Nothing was read or written.`,exit:2}}),n;try{n=FE(e,"utf8")}catch(i){return t(`cannot be read: ${i instanceof Error?i.message:String(i)}`)}let r;try{r=JSON.parse(n)}catch{return t("is not JSON: it is no plan plan --out kept")}let s=Xs.safeParse(r);if(!s.success){let i=s.error.issues[0],o=i?.path.map(String).join(".")||"the plan";return t(`is no plan plan --out kept (${o}: ${i?.message??"refused"})`)}return{saved:s.data}}function Yt(e,t){return{code:"PLAN_STALE",message:`The plan kept in ${e} ${t}. Nothing was written: plan again.`.slice(0,8e3),exit:1}}function Yh(e,t,n){if(e.plan.refusal!==void 0)return{code:"PLAN_REFUSED",message:`The plan kept in ${t} was refused when it was made: ${e.plan.refusal} Nothing was written: plan again.`.slice(0,8e3),exit:1};if(e.plan.quick===!0)return Yt(t,"was made with --quick, which counts nothing an apply is held to");if(e.sandforgeVersion!==n.sandforgeVersion)return Yt(t,`was made by SandForge ${e.sandforgeVersion}, and this one is ${n.sandforgeVersion}, which may read the file and the org otherwise`);if(n.now-Date.parse(e.madeAt)>Kh)return Yt(t,`was made at ${e.madeAt}, more than a day ago`)}function zE(e){return e.found?`the state at serial ${e.serial}`:"no state"}function Gh(e,t,n){let r=e.plan.org;if(!de(r.organizationId,n.target.organizationId))return{code:"PLAN_OTHER_ORG",message:`The plan kept in ${t} was made for ${r.alias??r.organizationId} (${r.organizationId}), and ${n.target.alias} is ${n.target.organizationId}: a plan is applied to the org it was made for. Nothing was written.`,exit:1};if(e.file.digest!==n.digest)return Yt(t,"was made from another file: the file, or a variable or an alias it reads, changed since");let s=n.state,i=e.state;if(!(i.found===(s!==void 0)&&(!i.found||s!==void 0&&s.serial===i.serial&&s.lineage===i.lineage))){let a=s===void 0?"none":i.found&&s.lineage!==i.lineage?`at serial ${s.serial}, made again since`:`at serial ${s.serial}`;return Yt(t,`was made against ${zE(i)}, and the state is now ${a}: an apply or a destroy ran since, or a cache put back another state`)}}function zh(e){return JSON.stringify([e.kind,e.action,e.objects.map(t=>[t.object,t.wouldCreate,t.atMost,t.present,t.gone,t.changed]),(e.draws??[]).map(t=>[t.lookup,t.from,t.object,t.parents])])}function Bh(e){if(e===void 0)return"nothing of it";let t=ja(e),n=(e.draws??[]).map(s=>s.parents!==void 0?`${s.lookup} under ${s.parents} ${s.object} record(s) of ${s.from}`:`${s.lookup} under the ${s.object} records ${s.from} creates first`).join(", "),r=[t,n].filter(Boolean).join("; ");return`${e.action}${r?` (${r})`:""}`}function Us(e){let t=(e.checkpoints??[]).map(n=>`${n.step==="before"?"before the first write":"once applied"} '${n.name}'`+(n.refusal!==void 0?", refused":""));return t.length>0?t.join(", "):"none"}function Vs(e){let t=e.drift;return t===void 0?"not compared":t.unread!==void 0?"not read":t.differs?`differs, ${t.toDelete??0} to delete \xB7 ${t.toGiveBack??0} to give back \xB7 ${t.toBringBack??0} to bring back`:"nothing differs"}function Hh(e,t){let n=[],r=[...new Set([...e.actions,...t.actions].map(i=>i.resource))];for(let i of r){let o=e.actions.find(c=>c.resource===i),a=t.actions.find(c=>c.resource===i);o!==void 0&&a!==void 0&&zh(o)===zh(a)||n.push(`${i}: planned ${Bh(o)}, now ${Bh(a)}`)}let s=i=>i.actions.map(o=>o.resource).join(", ");return n.length===0&&s(e)!==s(t)&&n.push(`the order of the resources: planned ${s(e)}, now ${s(t)}`),Us(e)!==Us(t)&&n.push(`the checkpoints it takes: planned ${Us(e)}, now ${Us(t)}`),Vs(e)!==Vs(t)&&n.push(`the whole org against the checkpoint after the last apply: planned ${Vs(e)}, now ${Vs(t)}`),n}function Qh(e,t){return Yt(e,`is not what the org holds now, read again: ${t.join("; ")}`)}function Xh(e,t){let n=new Date(Date.parse(t.madeAt)+Kh).toISOString();return`plan kept in ${e}, for apply --plan until ${n}`}function Zh(e,t){return`the plan kept in ${e} at ${t.madeAt} holds: the org, its state, the file and every count are as it planned them`}var WE=`sandforge env \u2014 apply a sandforge.yaml to an org: the data an environment needs, declared in
153
153
  your repository, created, kept and taken back, without the editor.
154
154
 
155
155
  Usage:
@@ -342,14 +342,14 @@ output: a resource not applied whole, or whose records cannot be read); 4 unstab
342
342
  or a frozen load's verification found records still changing; reset and destroy --rewind: someone
343
343
  changed records during it); 130, 143, 129 Ctrl-C, SIGTERM or SIGHUP stopped it \u2014 run it again: it
344
344
  takes up from the state.
345
- `,ME=["validate","plan","apply","destroy","reset","state","output"],_E=e=>ME.includes(e),qE={validate:{words:1,switches:["--json"],values:["--file"]},plan:{words:1,switches:["--json","--fail-on-change","--fail-on-drift","--quick","--replace-drifted","--accept-automation","--accept-emails","--accept-no-state","--out-in-repository"],values:["--file","--org","--alias","--replace","--out"]},apply:{words:1,switches:["--json","--replace-drifted","--accept-automation","--accept-emails","--accept-no-state","--yes"],values:["--file","--org","--alias","--replace","--plan"]},destroy:{words:1,switches:["--json","--include-changed","--sweep","--accept-automation","--accept-emails","--rewind","--accept-no-undo","--accept-unseen","--yes"],values:["--file","--org","--alias"]},reset:{words:1,switches:["--json","--accept-automation","--accept-emails","--accept-no-undo","--accept-unseen","--yes"],values:["--file","--org","--alias"]},state:{words:1,switches:["--json"],values:["--org","--file"]},output:{words:1,switches:["--json"],values:["--org","--file"]}},zE={words:2,switches:["--json"],values:["--file","--org","--alias"]};function Hh(e,t){let n=e==="destroy"?"sandforge env":`sandforge env ${e}`;return t!==void 0&&t!==""?`${n}, relayed by ${t}`:n}function BE(e={},t="destroy"){let n=process.env[ct]?.trim();return wc({...e,relayedBy:Hh(t,n)})}function KE(e,t){return async(n,r,s)=>{let i=process.env[ct];process.env[ct]=t;try{return await e(n,r,s)}finally{i===void 0?delete process.env[ct]:process.env[ct]=i}}}function he(e){process.stderr.write(`${e} Run with --help.
346
- `),process.exit(2)}function UE(e,t=process.cwd()){let n=e.slice(2);(n.includes("--help")||n.includes("-h"))&&(process.stdout.write(xE),process.exit(0));let r=n[0];if(r===void 0||r.startsWith("-"))return he("Name the command first: validate, plan, apply, destroy, reset, state or output.");if(!_E(r))return he(`"${r}" is not a command of sandforge env: validate, plan, apply, destroy, reset, state or output. Nothing was run.`);let s=r==="state"&&n[1]==="recover";ec(n,s?zE:qE[r]);let i=y=>{let m=[];for(let h=1;h<n.length;h++)n[h]===y&&(m.push(n[h+1]??""),h++);return m},o=y=>{let m=i(y);return m.length>1&&he(`${y} is given ${m.length} times: give it once.`),m[0]},a={};for(let y of i("--alias")){let m=y.indexOf("="),h=m>0?y.slice(0,m):"",w=m>0?y.slice(m+1):"";(h===""||w==="")&&he(`--alias wants <role>=<alias>, as --alias uat=UAT-ORG, not "${y}".`),h in a&&he(`--alias gives the role ${h} twice: give it once.`),a[h]=w}let c=o("--org");(r==="plan"||r==="apply"||r==="destroy"||r==="reset"||r==="output"||s)&&c===void 0&&he(`${s?"state recover":r} needs --org, the sf CLI alias of the org.`);let l=o("--out");l!==void 0&&n.includes("--quick")&&he("--out keeps a plan for apply --plan, which a quick plan cannot be: it counts nothing an apply is held to."),l===void 0&&n.includes("--out-in-repository")&&he("--out-in-repository goes with --out: it says where the plan may be kept.");let u=o("--plan");if(u!==void 0){let m=["--replace","--replace-drifted","--accept-automation","--accept-emails","--accept-no-state"].filter(h=>n.includes(h));m.length>0&&he(`${m.join(" and ")}: --plan applies the plan with the switches plan --out was given, kept in it. Give them to plan --out, then apply that plan.`)}let d=n.includes("--rewind");if(d){let y=["--include-changed","--sweep"].filter(m=>n.includes(m));y.length>0&&he(`${y.join(" and ")} take back records by removal: --rewind takes the whole org back to the checkpoint before the first apply. Give one or the other.`)}else if(r==="destroy")for(let y of["--accept-emails","--accept-no-undo","--accept-unseen"])n.includes(y)&&he(`${y} goes with --rewind: a destroy by removal is no rewind.`);let f=o("--file"),g=i("--replace");return{command:r,recover:s,file:_a(t,f??"sandforge.yaml"),fileGiven:f!==void 0,...c!==void 0?{org:c}:{},aliases:a,json:n.includes("--json"),failOnChange:n.includes("--fail-on-change"),failOnDrift:n.includes("--fail-on-drift"),quick:n.includes("--quick"),replace:[...new Set(g)],replaceDrifted:n.includes("--replace-drifted"),acceptAutomation:n.includes("--accept-automation"),acceptEmails:n.includes("--accept-emails"),acceptNoState:n.includes("--accept-no-state"),includeChanged:n.includes("--include-changed"),sweep:n.includes("--sweep"),rewind:d,acceptNoUndo:n.includes("--accept-no-undo"),acceptUnseen:n.includes("--accept-unseen"),yes:n.includes("--yes"),...l!==void 0?{out:_a(t,l)}:{},outInRepository:n.includes("--out-in-repository"),...u!==void 0?{plan:_a(t,u)}:{}}}function Vs(){try{let e=JSON.parse(Gh(wt(__dirname,"..","package.json"),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}}var Z=class extends Error{constructor(n,r){super(n.refusal.message);this.answer=n;this.code=r;this.name="Stop"}answer;code};function ee(e){return new Z({refusal:{code:e.code,message:e.message}},e.exit)}function qa(e){return{path:nn(e.path),...e.resource!==void 0?{resource:e.resource}:{},message:e.message}}function Ys(e){let t;try{t=Gh(e,"utf8")}catch(r){throw new Z({refusal:{code:"FILE_UNREAD",message:`${e} cannot be read: ${r instanceof Error?r.message:String(r)}`}},2)}let n=th(t);if("refusal"in n)throw new Z({refusal:{code:"INVALID_FILE",message:`${e}: ${n.refusal}`}},2);return n.document}function Ws(e,t){return new Z({refusal:{code:"INVALID_FILE",message:`${e} does not validate:
347
- ${t.map(n=>` ${da(n)}`).join(`
348
- `)}`,issues:t.map(qa)}},2)}async function VE(e){let t,n={request:a=>t??=e.request(a)},r=a=>({unread:a instanceof Error?a.message:String(a)}),s=await mc(n).catch(r),i="unread"in s||s.dailyApiRequests===void 0?await gc(n).catch(r):s.dailyApiRequests,o=await yc(n).catch(r);return{apiRequests:i,storage:"unread"in s?s:{remainingMB:s.remainingMB,maxMB:s.maxMB},emails:o}}function WE(e,t){try{return ic(JSON.parse(e),t)}catch{return}}function za(e){return e.trim().split(`
349
- `).map(t=>t.trim()).filter(Boolean).at(-1)??"it said nothing"}function Qh(e){return`the state of ${e.env} on ${e.alias??e.organizationId} expired on ${e.expiresAt}, a month after its last write, as a scratch org does: deleted`}async function Qn(e,t,n){let r=Ys(e.file),s=sh(r,Te(e.file),process.env,{aliases:e.aliases});if("refusals"in s)throw Ws(e.file,s.refusals);let i=s.resolved,o=i.resources.map(E=>E.name);for(let E of e.replace)if(!o.includes(E))throw new Z({refusal:{code:"BAD_LINE",message:`--replace ${E} names no resource of the file: it has ${o.join(", ")}.`}},2);let a=t.journalDir??fr(),c=t.locksDir??Ec(),l=pr(Te(e.file),a),u=vr({journalDir:a,fileFolder:Te(e.file)});if("refusal"in u)throw ee(Ar(u.refusal,l!==void 0));let d=u.store;for(let E of await d.sweep())n(Qh(E));let f=e.org??"",g;try{g=await(t.reach??Xh)(f)}catch(E){throw new Z({refusal:{code:"NOT_CONNECTED",message:E instanceof Xs?E.message:`${f} could not be reached: ${E instanceof Error?E.message:String(E)}`}},1)}let y;try{y=await rr(g.conn)}catch(E){y={unread:E instanceof Error?E.message:String(E),error:E}}let m=ll(f,y,g.session);if("refusal"in m)throw ee(m.refusal);let h=m.target,w=dl(i.checked.file.targets,h);if(w!==void 0)throw ee(w);let v;try{v=e.recover?void 0:await d.read(h.organizationId,i.checked.file.name)}catch(E){throw E instanceof L?ee(Ke(E)):E}if(v!==void 0){let E=fl(v,i.checked.file.name,h);if(E!==void 0)throw ee(E)}let k=[],b,S=e.command==="plan"||e.command==="apply";if(v===void 0&&S){let E=await zs({store:d,journalDir:a},{resolved:i,target:h}),R=pl(h,i.checked.file.name,e.acceptNoState,E);"warning"in R?k.push(R.warning):b=R.refusal}let $=Sc(c,h.organizationId,t.lockOptions);if($!==void 0&&k.push(`${$c($)}: this plan may be out of date when it ends`),S){let E=await JE(i,h,t,n),R=await YE(i,n);if(Object.keys(E).length+Object.keys(R).length>0){let j=ha(i.checked,process.env,{aliases:e.aliases,sources:E,datasets:R});if("refusals"in j)throw Ws(e.file,j.refusals);i=j.resolved}}return{resolved:i,store:d,journalDir:a,locksDir:c,target:h,reached:g,state:v,warnings:k,...b!==void 0?{noState:b}:{},runner:t.runner!==void 0?KE(t.runner,Hh(e.command,process.env[ct]?.trim())):BE({},e.command)}}async function JE(e,t,n,r){let s=new Map,i={};for(let o of e.resources){if(o.kind!=="forge")continue;let{role:a,alias:c}=o.source;r(`${o.name}: reading its source, the ${a} org (${c})`);let l;try{let d=s.get(c);d===void 0&&(d=(n.reach??Xh)(c),s.set(c,d)),l=(await d).conn}catch(d){i[o.name]={refusal:d instanceof Xs?`the ${a} org: ${d.reason}`:`the ${a} org (${c}) could not be reached: ${d instanceof Error?d.message:String(d)}`};continue}let u=await bl(l,o.run,a,c);i[o.name]="organizationId"in u&&de(u.organizationId,t.organizationId)?{refusal:`its source, the ${a} org (${c}), is the org to fill: a clone reads one org and writes another`}:u}return i}async function YE(e,t){let n={};for(let r of e.resources)r.kind==="frozen"&&(t(`${r.name}: reading its dataset at ${r.dataset.dir}`),n[r.name]=await Ul(r.dataset.dir,r.run.dataset));return n}async function Xh(e){let t=await tc(e);return{session:t,conn:nc(t)}}async function Zh(e,t,n,r){let{state:s,resolved:i,target:o}=e,a={};if(s===void 0)return a;let c={organizationId:o.organizationId,env:i.checked.file.name},l=rt(s,De(s).map(([u])=>u));for(let u of l){let d=s.resources[u];if(d===void 0)continue;let f=t.acceptAutomation||i.checked.file.resources[u]?.accept?.automation===!0,g=[];for(let y of sd(d.kind,d.runs)){if(r.aborted)break;let m=Ia(y,c,e);if(m===void 0){g.push({n:y.n,nothing:!0});continue}n(`${u}: reading what the org holds of run ${y.n}`);let h=nd(d.kind,{target:o.alias,subject:m,includeChanged:t.includeChanged,acceptAutomation:f,...t.sweep===!0?{sweep:!0}:{}}),w=await e.runner(h.script,h.args,r),v;try{v={n:y.n,preview:rd(d.kind,w.stdout)}}catch(b){if(!(b instanceof re))throw b;g.push({n:y.n,failed:`exit ${w.code}: ${za(w.stderr)}`});continue}let k=t.refresh&&d.status==="applied"&&i.checked.file.resources[u]!==void 0?id(d.kind,{target:o.alias,subject:m}):void 0;if(k!==void 0&&!r.aborted){n(`${u}: verifying run ${y.n}`);let b=await e.runner(k.script,k.args,r);try{v={...v,refreshed:od(b.stdout)}}catch(S){if(!(S instanceof re))throw S;v={...v,refreshed:{unread:`exit ${b.code}: ${za(b.stderr)}`}}}}g.push(v)}a[u]=g}return a}async function GE(e,t){let{resolved:n,state:r,target:s,store:i,journalDir:o}=e,a={};for(let c of n.resources)t.has(c.name)&&(c.kind!=="seed"||(c.run.draws??[]).length===0||(a[c.name]=await Ms(c,r,t,{organizationId:s.organizationId,env:n.checked.file.name,target:s.alias},{store:i,journalDir:o})));return a}async function HE(e,t){let{resolved:n,state:r,target:s,store:i,journalDir:o}=e,a=new Set(De(r).map(([l])=>l)),c=[];for(let l of t){if(!(l.action==="delete"||l.action==="replace"&&!lt(l.kind))||!a.has(l.resource))continue;let d=await ja(r,l.resource,{organizationId:s.organizationId,env:n.checked.file.name,target:s.alias},{store:i,journalDir:o});if(!("refusal"in d))for(let f of d.created.values())c.push(...f)}return c}async function QE(e,t,n,r,s,i={},o=!1,a=!1){let{resolved:c,target:l,state:u,store:d}=e,f={},g=new Map(t.filter(h=>h.action==="create"||h.action==="replace"||h.kind==="mask"&&h.action==="keep").map(h=>[h.resource,h.action]));if(g.size===0)return f;let y=c.checked.file.name,m=PE(wt(FE(),"sandforge-env-plan-"));try{for(let h of c.resources){let w=g.get(h.name);if(w===void 0||s.aborted)continue;if(h.kind==="forge"){let N=h.source.read;if(N===void 0||"refusal"in N)continue}if(h.kind==="frozen"){let N=h.dataset.read;if(N===void 0||"refusal"in N)continue}let v=n[h.name];if(v!==void 0&&v.refusals.length>0)continue;let k=wt(m,`${h.name}.json`),b,S,$;if(h.kind==="frozen"){let N=d.sasOf(l.organizationId,y,Ve(h.name));if(S=TE(N)?N:wt(m,`${h.name}.sas`),S===N&&(b=wt(m,`${h.name}.cli-store.json`)),w==="replace"&&lt(h.kind)){let P=await HE(e,t);P.length>0&&($=wt(m,`${h.name}.gone-first.json`),Wh($,`${JSON.stringify(P)}
350
- `,{mode:384}))}}let E=Dt(h,{...v!==void 0?{drawn:v.ids}:{},standIns:!0,...S!==void 0?{sasDir:S}:{}});Wh(k,`${JSON.stringify(E,null,2)}
351
- `,{mode:384}),r(`${h.name}: dry run`);let R=i[h.name],j=Vt(Qu(h,{target:l.alias,templateFile:k,runId:hr(y,h.name,en(u?.resources[h.name])),replace:w==="replace"&&lt(h.kind),acceptAutomation:a||c.checked.file.resources[h.name]?.accept?.automation===!0,...R!==void 0?{seed:R}:{},...b!==void 0?{storeFile:b}:{},...$!==void 0?{goneFirstFile:$}:{},...h.kind==="mask"?{store:wt(m,`${h.name}.dataops`)}:{}}),o),D=await e.runner(j.script,j.args,s);try{f[h.name]={answer:ed(h.kind,D.stdout)}}catch(N){if(!(N instanceof re))throw N;let P=WE(D.stdout,j.script);f[h.name]={failed:`exit ${D.code}: ${za(D.stderr)}`,...P?{refused:P}:{}}}}}finally{LE(m,{recursive:!0,force:!0})}return f}async function Us(e,t,n){let r=new AbortController,s,i=(e.onStop??Le)(o=>{s=o,r.abort()});try{let o=await n(r.signal);if(s!==void 0)throw new Z({refusal:{code:"STOPPED",message:`stopped by ${s} while ${t}: nothing was written`}},be(s));return o}finally{i()}}function em(e){let{resolved:t,state:n,store:r,target:s}=e,i=new Set([...t.resources.filter(o=>o.kind==="mask").map(o=>o.name),...Object.entries(n?.resources??{}).filter(([,o])=>o.kind==="mask").map(([o])=>o)]);return Object.fromEntries([...i].map(o=>[o,r.sasOf(s.organizationId,t.checked.file.name,jt(o))]))}async function Jh(e,t,n,r,s={}){let i={organizationId:e.target.organizationId,kind:e.target.kind,alias:e.target.alias},o={resolved:e.resolved,org:i,state:e.state,replace:t.replace,replaceDrifted:t.replaceDrifted,warnings:e.warnings,maskStores:em(e),...e.noState!==void 0?{refusal:e.noState.message,refusalCodes:[e.noState.code]}:{}};if(t.quick)return{plan:Ra(o),dryRuns:{}};let a=await Zh(e,{includeChanged:!1,acceptAutomation:t.acceptAutomation,refresh:!0},n,r),c=await XE(e,n,r),l=ba({...o,previews:a,...c?{drift:c}:{}}),u=new Set(l.filter(m=>m.action==="create"||m.action==="replace").map(m=>m.resource)),d=await GE(e,u),f=await QE(e,l,d,n,r,s,t.acceptEmails,t.acceptAutomation),g=await VE(e.reached.conn),y=await ZE(e,l.some(wa),n,r);return{plan:Ra({...o,previews:a,dryRuns:f,budget:g,...c?{drift:c}:{},...y?{checkpointEstimate:y}:{},draws:Object.fromEntries(Object.entries(d).map(([m,h])=>[m,{draws:h.draws,refusals:h.refusals}]))}),dryRuns:f}}async function XE(e,t,n){let r=e.state?.checkpoints?.after;if(r===void 0||n.aborted)return;t(`checkpoint ${r}: comparing the whole org with it`);let s=await e.runner(ce,Jc({org:e.target.alias,store:ye(e.journalDir),checkpoint:r}),n);return tl(r,s)}async function ZE(e,t,n,r){let s=e.resolved.checked.file;if(br(s,e.state,t).length===0||r.aborted)return;n("checkpoint: estimating what a take of the org costs");let i=await e.runner(ce,Wc({org:e.target.alias,store:ye(e.journalDir),...kr(s)}),r);return Qc(i)}function eS(e,t){let n=lc(e,"sandforge-env"),r=!1;return async()=>{try{return await n.serverTime()}catch(s){return r||(r=!0,t(`the org did not say its time (${s instanceof Error?s.message:String(s)}): the state's spans are on this machine's clock`)),new Date().toISOString()}}}function tS(e){if(e.kind==="seed"){let s=It(e).map(o=>`${o.object} ${o.count??""}`).join(", "),i=(e.draws??[]).map(o=>`${o.relation.childObject}.${o.relation.lookupField} under the ${o.relation.parentObject} records ${o.from} created`);return i.length>0?`${s}; ${i.join(", ")}`:s}if(e.kind==="frozen"){let{path:s,version:i,digest:o}=e.dataset,a=typeof s=="string"?s:`$${s.env}`;return`the Frozen dataset ${i} at ${a} (${o.slice(0,19)}\u2026), as ${e.configFile} configures its load`}if(e.kind==="mask"){let s="set"in e.source?`the rule set ${e.source.set}`:`the template ${e.source.template}`;return`masks ${e.object!==void 0?`${e.object}${e.where!==void 0?` WHERE ${e.where}`:""}`:`every object its rules mask (${It(e).map(o=>o.object).join(", ")})`} with ${s}, ${e.rules.rules.length} rule(s)`}let t=(s,i)=>i!==void 0?`${s} WHERE ${i}`:s,n=e.wholeOrg?.fit,r=e.wholeOrg?n!==void 0?`a sample of the whole org that fits the org to fill${n.withinMB!==void 0?`, within ${n.withinMB} MB`:""}`:"the whole org":e.tables!==void 0?`tables ${e.tables.map(s=>t(s.object,s.where)).join(", ")}`:e.record?.id!==void 0?`record ${e.record.id}`:`the one record of ${t(e.record?.object??"",e.record?.where)}`;return`cloned from the ${e.source} org: ${r}`}function nS(e,t){let n=Ys(e.file),r=Jn(n,Te(e.file));if("refusals"in r){t(`${e.file} does not validate:`);for(let d of r.refusals)t(` ${da(d)}`);return{answer:{file:e.file,valid:!1,issues:r.refusals.map(qa),warnings:[]},code:2}}let{file:s,order:i,runs:o,variables:a}=r.checked,c=new Set(nh(r.checked,process.env).map(d=>d.name)),l=i.flatMap(d=>{let f=o[d],g=s.resources[d];return f===void 0?[]:[{name:d,kind:f.kind,dependsOn:g!==void 0?fa(d,g):[],...f.kind==="forge"?{source:f.source}:{},objects:It(f)}]}),u=r.checked.warnings.map(qa);t(`${e.file}: valid, the environment ${s.name}`);for(let d of l){let f=o[d.name];t(` ${d.name}: ${f!==void 0?tS(f):""}`+(d.dependsOn.length>0?`, after ${d.dependsOn.join(", ")}`:""))}for(let d of a){let f=d.role!==void 0?`the ${d.role} org`:`the dataset of ${d.resource??""}`;t(` variable ${d.name} (${f}): `+(c.has(d.name)?"not set in this shell":"set"))}for(let d of u)t(`warning: ${d.path}: ${d.message}`);return{answer:{file:e.file,valid:!0,env:s.name,resources:l,variables:a.map(d=>({name:d.name,...d.role!==void 0?{role:d.role}:{},...d.resource!==void 0?{resource:d.resource}:{},set:!c.has(d.name)})),issues:[],warnings:u},code:0}}function rS(e,t,n,r){if(n===void 0&&r===void 0)return`no state kept in ${e}`;let s=n!==void 0&&r!==void 0?`${n} on ${r}`:n??r??"",i=t===0?"":`, which keeps ${t===1?"1 other state":`${t} other states`}: "${ue("env")} state" lists ${t===1?"it":"them"}`;return`no state of ${s} is kept in ${e}${i}. A state kept in another folder is read with SANDFORGE_JOURNAL_DIR set as when it was written \u2014 in a CI job, a folder its cache restores.`}async function sS(e,t,n){let r=t.journalDir??fr(),s=vr({journalDir:r,fileFolder:null});if("refusal"in s)throw ee(Ar(s.refusal,!1));let i=await s.store.sweep(),o;if(e.fileGiven){let u=Jn(Ys(e.file),Te(e.file));if("refusals"in u)throw Ws(e.file,u.refusals);o=u.checked.file.name}let a=e.org,c=await s.store.list(),l=c.filter(u=>(o===void 0||u.env===o)&&(a===void 0||u.state?.org.alias===a||u.organizationId.slice(0,15)===a.slice(0,15)));for(let u of i)n(`expired and deleted: ${u.env} on ${u.alias??u.organizationId}`);l.length===0&&n(rS(s.store.root,c.length,o,a));for(let u of l){let d=u.state;if(d===void 0){n(`${u.env} on ${u.organizationId}: not used \u2014 ${u.damaged??""}`);continue}let f=Object.entries(d.resources).map(([g,y])=>`${g} ${y.status}`).join(", ");n(`${d.env} on ${d.org.alias??d.org.organizationId} (${d.org.kind}, ${d.org.organizationId}): serial ${d.serial}, written ${d.updatedAt}`+(u.expiresAt!==void 0?`, expires ${u.expiresAt}`:"")+(f?`; ${f}`:""))}return{journalDir:r,states:l.map(u=>{let d=u.state;if(d===void 0)return{env:u.env,organizationId:u.organizationId,damaged:u.damaged??"not used"};let f=pi(d);return{env:d.env,organizationId:d.org.organizationId,...d.org.alias!==void 0?{alias:d.org.alias}:{},kind:d.org.kind,serial:d.serial,resources:Object.fromEntries(Object.entries(d.resources).map(([g,y])=>[g,y.status])),updatedAt:d.updatedAt,...f!==void 0?{expiresAt:f}:{}}}),expired:i.map(u=>({env:u.env,organizationId:u.organizationId,...u.alias!==void 0?{alias:u.alias}:{},expiresAt:u.expiresAt}))}}async function iS(e,t,n){let r=Jn(Ys(e.file),Te(e.file));if("refusals"in r)throw Ws(e.file,r.refusals);let s=t.journalDir??fr(),i=pr(Te(e.file),s),o=vr({journalDir:s,fileFolder:Te(e.file)});if("refusal"in o)throw ee(Ar(o.refusal,i!==void 0));for(let u of await o.store.sweep())n(Qh(u));let a=$h(await o.store.list(),r.checked.file.name,e.org??"");if("refusal"in a)throw ee(a.refusal);let{output:c,whole:l}=await Ah(a.state,{store:o.store,journalDir:s});return{answer:c,code:l?0:3}}async function oS(e,t,n){let r=await Qn(e,t,n),s=await kh({store:r.store,journalDir:r.journalDir,locksDir:r.locksDir,sandforgeVersion:Vs(),...t.lockOptions!==void 0?{lockOptions:t.lockOptions}:{}},{resolved:r.resolved,target:r.target});if("refusal"in s)throw ee(s.refusal);for(let i of bh(s.result))n(i);return s.result}async function Ba(e,t,n,r){return e.yes||await(t.ask??(i=>kc(i)))(n)===e.org?!0:(r("Nothing was written: the alias typed is not the org\u2019s."),!1)}function Js(e,t,n){return{runner:e.runner,store:e.store,locksDir:e.locksDir,journalDir:e.journalDir,orgNow:eS(e.reached.conn,n),say:n,sandforgeVersion:Vs(),...t.onStop!==void 0?{onStop:t.onStop}:{},...t.lockOptions!==void 0?{lockOptions:t.lockOptions}:{}}}async function Yh(e,t,n,r,s){let i=await Qn(e,t,r),o={verb:n,resolved:i.resolved,target:i.target,state:i.state,acceptAutomation:e.acceptAutomation,acceptEmails:e.acceptEmails,acceptNoUndo:e.acceptNoUndo,acceptUnseen:e.acceptUnseen},a=xa(o);if(a!==void 0)throw ee(a);for(let u of i.warnings)r(`warning: ${u}`);let c;if(!e.yes){let u=await Us(t,"reading what a rewind would do",d=>jh(Js(i,t,r),o,d));if(!("differs"in u))throw new Z({refusal:{code:"REWIND_REFUSED",message:`${u.refusal} Nothing was written.`}},1);c=u;for(let d of sl(n,i.target.alias,u))r(d);if(u.refusal!==void 0)throw new Z({refusal:{code:u.refusal.code,message:u.refusal.message}},1);if(u.differs&&!await Ba(e,t,Nh(o,u),r))throw new Z({refusal:{code:"DECLINED",message:"Nothing was written."}},1)}let l=await Ih(Js(i,t,r),o,c);for(let u of Dh(l.result))r(u);s(l.result),Fe(l.exitCode)}async function aS(e=process.argv,t={}){let n=UE(e,t.cwd),r=i=>{process[n.json?"stderr":"stdout"].write(`${i}
345
+ `,JE=["validate","plan","apply","destroy","reset","state","output"],YE=e=>JE.includes(e),GE={validate:{words:1,switches:["--json"],values:["--file"]},plan:{words:1,switches:["--json","--fail-on-change","--fail-on-drift","--quick","--replace-drifted","--accept-automation","--accept-emails","--accept-no-state","--out-in-repository"],values:["--file","--org","--alias","--replace","--out"]},apply:{words:1,switches:["--json","--replace-drifted","--accept-automation","--accept-emails","--accept-no-state","--yes"],values:["--file","--org","--alias","--replace","--plan"]},destroy:{words:1,switches:["--json","--include-changed","--sweep","--accept-automation","--accept-emails","--rewind","--accept-no-undo","--accept-unseen","--yes"],values:["--file","--org","--alias"]},reset:{words:1,switches:["--json","--accept-automation","--accept-emails","--accept-no-undo","--accept-unseen","--yes"],values:["--file","--org","--alias"]},state:{words:1,switches:["--json"],values:["--org","--file"]},output:{words:1,switches:["--json"],values:["--org","--file"]}},HE={words:2,switches:["--json"],values:["--file","--org","--alias"]};function sm(e,t){let n=e==="destroy"?"sandforge env":`sandforge env ${e}`;return t!==void 0&&t!==""?`${n}, relayed by ${t}`:n}function QE(e={},t="destroy"){let n=process.env[ut]?.trim();return Rc({...e,relayedBy:sm(t,n)})}function XE(e,t){return async(n,r,s)=>{let i=process.env[ut];process.env[ut]=t;try{return await e(n,r,s)}finally{i===void 0?delete process.env[ut]:process.env[ut]=i}}}function he(e){process.stderr.write(`${e} Run with --help.
346
+ `),process.exit(2)}function ZE(e,t=process.cwd()){let n=e.slice(2);(n.includes("--help")||n.includes("-h"))&&(process.stdout.write(WE),process.exit(0));let r=n[0];if(r===void 0||r.startsWith("-"))return he("Name the command first: validate, plan, apply, destroy, reset, state or output.");if(!YE(r))return he(`"${r}" is not a command of sandforge env: validate, plan, apply, destroy, reset, state or output. Nothing was run.`);let s=r==="state"&&n[1]==="recover";sc(n,s?HE:GE[r]);let i=g=>{let m=[];for(let h=1;h<n.length;h++)n[h]===g&&(m.push(n[h+1]??""),h++);return m},o=g=>{let m=i(g);return m.length>1&&he(`${g} is given ${m.length} times: give it once.`),m[0]},a={};for(let g of i("--alias")){let m=g.indexOf("="),h=m>0?g.slice(0,m):"",w=m>0?g.slice(m+1):"";(h===""||w==="")&&he(`--alias wants <role>=<alias>, as --alias uat=UAT-ORG, not "${g}".`),h in a&&he(`--alias gives the role ${h} twice: give it once.`),a[h]=w}let c=o("--org");(r==="plan"||r==="apply"||r==="destroy"||r==="reset"||r==="output"||s)&&c===void 0&&he(`${s?"state recover":r} needs --org, the sf CLI alias of the org.`);let l=o("--out");l!==void 0&&n.includes("--quick")&&he("--out keeps a plan for apply --plan, which a quick plan cannot be: it counts nothing an apply is held to."),l===void 0&&n.includes("--out-in-repository")&&he("--out-in-repository goes with --out: it says where the plan may be kept.");let u=o("--plan");if(u!==void 0){let m=["--replace","--replace-drifted","--accept-automation","--accept-emails","--accept-no-state"].filter(h=>n.includes(h));m.length>0&&he(`${m.join(" and ")}: --plan applies the plan with the switches plan --out was given, kept in it. Give them to plan --out, then apply that plan.`)}let d=n.includes("--rewind");if(d){let g=["--include-changed","--sweep"].filter(m=>n.includes(m));g.length>0&&he(`${g.join(" and ")} take back records by removal: --rewind takes the whole org back to the checkpoint before the first apply. Give one or the other.`)}else if(r==="destroy")for(let g of["--accept-emails","--accept-no-undo","--accept-unseen"])n.includes(g)&&he(`${g} goes with --rewind: a destroy by removal is no rewind.`);let f=o("--file"),y=i("--replace");return{command:r,recover:s,file:Ba(t,f??"sandforge.yaml"),fileGiven:f!==void 0,...c!==void 0?{org:c}:{},aliases:a,json:n.includes("--json"),failOnChange:n.includes("--fail-on-change"),failOnDrift:n.includes("--fail-on-drift"),quick:n.includes("--quick"),replace:[...new Set(y)],replaceDrifted:n.includes("--replace-drifted"),acceptAutomation:n.includes("--accept-automation"),acceptEmails:n.includes("--accept-emails"),acceptNoState:n.includes("--accept-no-state"),includeChanged:n.includes("--include-changed"),sweep:n.includes("--sweep"),rewind:d,acceptNoUndo:n.includes("--accept-no-undo"),acceptUnseen:n.includes("--accept-unseen"),yes:n.includes("--yes"),...l!==void 0?{out:Ba(t,l)}:{},outInRepository:n.includes("--out-in-repository"),...u!==void 0?{plan:Ba(t,u)}:{}}}function Js(){try{let e=JSON.parse(rm(kt(__dirname,"..","package.json"),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}}var ee=class extends Error{constructor(n,r){super(n.refusal.message);this.answer=n;this.code=r;this.name="Stop"}answer;code};function te(e){return new ee({refusal:{code:e.code,message:e.message}},e.exit)}function Ka(e){return{path:nn(e.path),...e.resource!==void 0?{resource:e.resource}:{},message:e.message}}function Hs(e){let t;try{t=rm(e,"utf8")}catch(r){throw new ee({refusal:{code:"FILE_UNREAD",message:`${e} cannot be read: ${r instanceof Error?r.message:String(r)}`}},2)}let n=lh(t);if("refusal"in n)throw new ee({refusal:{code:"INVALID_FILE",message:`${e}: ${n.refusal}`}},2);return n.document}function Ys(e,t){return new ee({refusal:{code:"INVALID_FILE",message:`${e} does not validate:
347
+ ${t.map(n=>` ${ha(n)}`).join(`
348
+ `)}`,issues:t.map(Ka)}},2)}async function eS(e){let t,n={request:a=>t??=e.request(a)},r=a=>({unread:a instanceof Error?a.message:String(a)}),s=await bc(n).catch(r),i="unread"in s||s.dailyApiRequests===void 0?await Ec(n).catch(r):s.dailyApiRequests,o=await Sc(n).catch(r);return{apiRequests:i,storage:"unread"in s?s:{remainingMB:s.remainingMB,maxMB:s.maxMB},emails:o}}function tS(e,t){try{return lc(JSON.parse(e),t)}catch{return}}function Ua(e){return e.trim().split(`
349
+ `).map(t=>t.trim()).filter(Boolean).at(-1)??"it said nothing"}function im(e){return`the state of ${e.env} on ${e.alias??e.organizationId} expired on ${e.expiresAt}, a month after its last write, as a scratch org does: deleted`}async function Qn(e,t,n){let r=Hs(e.file),s=fh(r,Pe(e.file),process.env,{aliases:e.aliases});if("refusals"in s)throw Ys(e.file,s.refusals);let i=s.resolved,o=i.resources.map(b=>b.name);for(let b of e.replace)if(!o.includes(b))throw new ee({refusal:{code:"BAD_LINE",message:`--replace ${b} names no resource of the file: it has ${o.join(", ")}.`}},2);let a=t.journalDir??fr(),c=t.locksDir??Nc(),l=pr(Pe(e.file),a),u=vr({journalDir:a,fileFolder:Pe(e.file)});if("refusal"in u)throw te(Ar(u.refusal,l!==void 0));let d=u.store;for(let b of await d.sweep())n(im(b));let f=e.org??"",y;try{y=await(t.reach??om)(f)}catch(b){throw new ee({refusal:{code:"NOT_CONNECTED",message:b instanceof ei?b.message:`${f} could not be reached: ${b instanceof Error?b.message:String(b)}`}},1)}let g;try{g=await rr(y.conn)}catch(b){g={unread:b instanceof Error?b.message:String(b),error:b}}let m=yl(f,g,y.session);if("refusal"in m)throw te(m.refusal);let h=m.target,w=vl(i.checked.file.targets,h);if(w!==void 0)throw te(w);let v;try{v=e.recover?void 0:await d.read(h.organizationId,i.checked.file.name)}catch(b){throw b instanceof F?te(Ke(b)):b}if(v!==void 0){let b=kl(v,i.checked.file.name,h);if(b!==void 0)throw te(b)}let k=[],E,S=e.command==="plan"||e.command==="apply";if(v===void 0&&S){let b=await Ks({store:d,journalDir:a},{resolved:i,target:h}),$=bl(h,i.checked.file.name,e.acceptNoState,b);"warning"in $?k.push($.warning):E=$.refusal}let R=Ic(c,h.organizationId,t.lockOptions);if(R!==void 0&&k.push(`${Pc(R)}: this plan may be out of date when it ends`),S){let b=await nS(i,h,t,n),$=await rS(i,n);if(Object.keys(b).length+Object.keys($).length>0){let j=ya(i.checked,process.env,{aliases:e.aliases,sources:b,datasets:$});if("refusals"in j)throw Ys(e.file,j.refusals);i=j.resolved}}return{resolved:i,store:d,journalDir:a,locksDir:c,target:h,reached:y,state:v,warnings:k,...E!==void 0?{noState:E}:{},runner:t.runner!==void 0?XE(t.runner,sm(e.command,process.env[ut]?.trim())):QE({},e.command)}}async function nS(e,t,n,r){let s=new Map,i={};for(let o of e.resources){if(o.kind!=="forge")continue;let{role:a,alias:c}=o.source;r(`${o.name}: reading its source, the ${a} org (${c})`);let l;try{let d=s.get(c);d===void 0&&(d=(n.reach??om)(c),s.set(c,d)),l=(await d).conn}catch(d){i[o.name]={refusal:d instanceof ei?`the ${a} org: ${d.reason}`:`the ${a} org (${c}) could not be reached: ${d instanceof Error?d.message:String(d)}`};continue}let u=await jl(l,o.run,a,c);i[o.name]="organizationId"in u&&de(u.organizationId,t.organizationId)?{refusal:`its source, the ${a} org (${c}), is the org to fill: a clone reads one org and writes another`}:u}return i}async function rS(e,t){let n={};for(let r of e.resources)r.kind==="frozen"&&(t(`${r.name}: reading its dataset at ${r.dataset.dir}`),n[r.name]=await Xl(r.dataset.dir,r.run.dataset));return n}async function om(e){let t=await ic(e);return{session:t,conn:oc(t)}}async function am(e,t,n,r){let{state:s,resolved:i,target:o}=e,a={};if(s===void 0)return a;let c={organizationId:o.organizationId,env:i.checked.file.name},l=st(s,De(s).map(([u])=>u));for(let u of l){let d=s.resources[u];if(d===void 0)continue;let f=t.acceptAutomation||i.checked.file.resources[u]?.accept?.automation===!0,y=[];for(let g of fd(d.kind,d.runs)){if(r.aborted)break;let m=Ta(g,c,e);if(m===void 0){y.push({n:g.n,nothing:!0});continue}n(`${u}: reading what the org holds of run ${g.n}`);let h=ud(d.kind,{target:o.alias,subject:m,includeChanged:t.includeChanged,acceptAutomation:f,...t.sweep===!0?{sweep:!0}:{}}),w=await e.runner(h.script,h.args,r),v;try{v={n:g.n,preview:dd(d.kind,w.stdout)}}catch(E){if(!(E instanceof re))throw E;y.push({n:g.n,failed:`exit ${w.code}: ${Ua(w.stderr)}`});continue}let k=t.refresh&&d.status==="applied"&&i.checked.file.resources[u]!==void 0?pd(d.kind,{target:o.alias,subject:m}):void 0;if(k!==void 0&&!r.aborted){n(`${u}: verifying run ${g.n}`);let E=await e.runner(k.script,k.args,r);try{v={...v,refreshed:hd(E.stdout)}}catch(S){if(!(S instanceof re))throw S;v={...v,refreshed:{unread:`exit ${E.code}: ${Ua(E.stderr)}`}}}}y.push(v)}a[u]=y}return a}async function sS(e,t){let{resolved:n,state:r,target:s,store:i,journalDir:o}=e,a={};for(let c of n.resources)t.has(c.name)&&(c.kind!=="seed"||(c.run.draws??[]).length===0||(a[c.name]=await qs(c,r,t,{organizationId:s.organizationId,env:n.checked.file.name,target:s.alias},{store:i,journalDir:o})));return a}async function iS(e,t){let{resolved:n,state:r,target:s,store:i,journalDir:o}=e,a=new Set(De(r).map(([l])=>l)),c=[];for(let l of t){if(!(l.action==="delete"||l.action==="replace"&&!dt(l.kind))||!a.has(l.resource))continue;let d=await Da(r,l.resource,{organizationId:s.organizationId,env:n.checked.file.name,target:s.alias},{store:i,journalDir:o});if(!("refusal"in d))for(let f of d.created.values())c.push(...f)}return c}async function oS(e,t,n,r,s,i={},o=!1,a=!1){let{resolved:c,target:l,state:u,store:d}=e,f={},y=new Map(t.filter(h=>h.action==="create"||h.action==="replace"||h.kind==="mask"&&h.action==="keep").map(h=>[h.resource,h.action]));if(y.size===0)return f;let g=c.checked.file.name;await Cc(e.journalDir,new Date).catch(()=>0);let m=KE(kt(VE(),"sandforge-env-plan-"));try{for(let h of c.resources){let w=y.get(h.name);if(w===void 0||s.aborted)continue;if(h.kind==="forge"){let I=h.source.read;if(I===void 0||"refusal"in I)continue}if(h.kind==="frozen"){let I=h.dataset.read;if(I===void 0||"refusal"in I)continue}let v=n[h.name];if(v!==void 0&&v.refusals.length>0)continue;let k=kt(m,`${h.name}.json`),E=h.kind==="forge"&&h.run.records!==void 0?Cr(e.journalDir,l.organizationId,g,h.name):void 0,S,R,b;if(h.kind==="frozen"){let I=d.sasOf(l.organizationId,g,Ve(h.name));if(R=BE(I)?I:kt(m,`${h.name}.sas`),R===I&&(S=kt(m,`${h.name}.cli-store.json`)),w==="replace"&&dt(h.kind)){let H=await iS(e,t);H.length>0&&(b=kt(m,`${h.name}.gone-first.json`),em(b,`${JSON.stringify(H)}
350
+ `,{mode:384}))}}let $=Tt(h,{...v!==void 0?{drawn:v.ids}:{},standIns:!0,...R!==void 0?{sasDir:R}:{}});em(k,`${JSON.stringify($,null,2)}
351
+ `,{mode:384}),r(`${h.name}: dry run`);let j=i[h.name],D=Jt(id(h,{target:l.alias,templateFile:k,runId:hr(g,h.name,en(u?.resources[h.name])),replace:w==="replace"&&dt(h.kind),acceptAutomation:a||c.checked.file.resources[h.name]?.accept?.automation===!0,...j!==void 0?{seed:j}:{},...S!==void 0?{storeFile:S}:{},...b!==void 0?{goneFirstFile:b}:{},...E!==void 0?{rootsPlanFile:E}:{},...h.kind==="mask"?{store:kt(m,`${h.name}.dataops`)}:{}}),o),T=await e.runner(D.script,D.args,s);try{f[h.name]={answer:cd(h.kind,T.stdout)}}catch(I){if(!(I instanceof re))throw I;let H=tS(T.stdout,D.script);f[h.name]={failed:`exit ${T.code}: ${Ua(T.stderr)}`,...H?{refused:H}:{}}}}}finally{UE(m,{recursive:!0,force:!0})}return f}async function Ws(e,t,n){let r=new AbortController,s,i=(e.onStop??Fe)(o=>{s=o,r.abort()});try{let o=await n(r.signal);if(s!==void 0)throw new ee({refusal:{code:"STOPPED",message:`stopped by ${s} while ${t}: nothing was written`}},be(s));return o}finally{i()}}function cm(e){let{resolved:t,state:n,store:r,target:s}=e,i=new Set([...t.resources.filter(o=>o.kind==="mask").map(o=>o.name),...Object.entries(n?.resources??{}).filter(([,o])=>o.kind==="mask").map(([o])=>o)]);return Object.fromEntries([...i].map(o=>[o,r.sasOf(s.organizationId,t.checked.file.name,It(o))]))}async function tm(e,t,n,r,s={}){let i={organizationId:e.target.organizationId,kind:e.target.kind,alias:e.target.alias},o={resolved:e.resolved,org:i,state:e.state,replace:t.replace,replaceDrifted:t.replaceDrifted,warnings:e.warnings,maskStores:cm(e),...e.noState!==void 0?{refusal:e.noState.message,refusalCodes:[e.noState.code]}:{}};if(t.quick)return{plan:Oa(o),dryRuns:{}};let a=await am(e,{includeChanged:!1,acceptAutomation:t.acceptAutomation,refresh:!0},n,r),c=await aS(e,n,r),l=Ra({...o,previews:a,...c?{drift:c}:{}}),u=new Set(l.filter(m=>m.action==="create"||m.action==="replace").map(m=>m.resource)),d=await sS(e,u),f=await oS(e,l,d,n,r,s,t.acceptEmails,t.acceptAutomation),y=await eS(e.reached.conn),g=await cS(e,l.some(ba),n,r);return{plan:Oa({...o,previews:a,dryRuns:f,budget:y,...c?{drift:c}:{},...g?{checkpointEstimate:g}:{},draws:Object.fromEntries(Object.entries(d).map(([m,h])=>[m,{draws:h.draws,refusals:h.refusals}]))}),dryRuns:f}}async function aS(e,t,n){let r=e.state?.checkpoints?.after;if(r===void 0||n.aborted)return;t(`checkpoint ${r}: comparing the whole org with it`);let s=await e.runner(ue,tl({org:e.target.alias,store:ge(e.journalDir),checkpoint:r}),n);return ll(r,s)}async function cS(e,t,n,r){let s=e.resolved.checked.file;if(br(s,e.state,t).length===0||r.aborted)return;n("checkpoint: estimating what a take of the org costs");let i=await e.runner(ue,el({org:e.target.alias,store:ge(e.journalDir),...kr(s)}),r);return il(i)}function lS(e,t){let n=pc(e,"sandforge-env"),r=!1;return async()=>{try{return await n.serverTime()}catch(s){return r||(r=!0,t(`the org did not say its time (${s instanceof Error?s.message:String(s)}): the state's spans are on this machine's clock`)),new Date().toISOString()}}}function uS(e){if(e.kind==="seed"){let s=Pt(e).map(o=>`${o.object} ${o.count??""}`).join(", "),i=(e.draws??[]).map(o=>`${o.relation.childObject}.${o.relation.lookupField} under the ${o.relation.parentObject} records ${o.from} created`);return i.length>0?`${s}; ${i.join(", ")}`:s}if(e.kind==="frozen"){let{path:s,version:i,digest:o}=e.dataset,a=typeof s=="string"?s:`$${s.env}`;return`the Frozen dataset ${i} at ${a} (${o.slice(0,19)}\u2026), as ${e.configFile} configures its load`}if(e.kind==="mask"){let s="set"in e.source?`the rule set ${e.source.set}`:`the template ${e.source.template}`;return`masks ${e.object!==void 0?`${e.object}${e.where!==void 0?` WHERE ${e.where}`:""}`:`every object its rules mask (${Pt(e).map(o=>o.object).join(", ")})`} with ${s}, ${e.rules.rules.length} rule(s)`}let t=(s,i)=>i!==void 0?`${s} WHERE ${i}`:s,n=e.wholeOrg?.fit,r=e.wholeOrg?n!==void 0?`a sample of the whole org that fits the org to fill${n.withinMB!==void 0?`, within ${n.withinMB} MB`:""}`:"the whole org":e.tables!==void 0?`tables ${e.tables.map(s=>t(s.object,s.where)).join(", ")}`:e.records!==void 0?`the ${e.records.object} records ${Or(e.records)} chooses, with what each reaches`:e.record?.id!==void 0?`record ${e.record.id}`:`the one record of ${t(e.record?.object??"",e.record?.where)}`;return`cloned from the ${e.source} org: ${r}`}function dS(e,t){let n=Hs(e.file),r=Jn(n,Pe(e.file));if("refusals"in r){t(`${e.file} does not validate:`);for(let d of r.refusals)t(` ${ha(d)}`);return{answer:{file:e.file,valid:!1,issues:r.refusals.map(Ka),warnings:[]},code:2}}let{file:s,order:i,runs:o,variables:a}=r.checked,c=new Set(uh(r.checked,process.env).map(d=>d.name)),l=i.flatMap(d=>{let f=o[d],y=s.resources[d];return f===void 0?[]:[{name:d,kind:f.kind,dependsOn:y!==void 0?ma(d,y):[],...f.kind==="forge"?{source:f.source}:{},objects:Pt(f)}]}),u=r.checked.warnings.map(Ka);t(`${e.file}: valid, the environment ${s.name}`);for(let d of l){let f=o[d.name];t(` ${d.name}: ${f!==void 0?uS(f):""}`+(d.dependsOn.length>0?`, after ${d.dependsOn.join(", ")}`:""))}for(let d of a){let f=d.role!==void 0?`the ${d.role} org`:`the dataset of ${d.resource??""}`;t(` variable ${d.name} (${f}): `+(c.has(d.name)?"not set in this shell":"set"))}for(let d of u)t(`warning: ${d.path}: ${d.message}`);return{answer:{file:e.file,valid:!0,env:s.name,resources:l,variables:a.map(d=>({name:d.name,...d.role!==void 0?{role:d.role}:{},...d.resource!==void 0?{resource:d.resource}:{},set:!c.has(d.name)})),issues:[],warnings:u},code:0}}function fS(e,t,n,r){if(n===void 0&&r===void 0)return`no state kept in ${e}`;let s=n!==void 0&&r!==void 0?`${n} on ${r}`:n??r??"",i=t===0?"":`, which keeps ${t===1?"1 other state":`${t} other states`}: "${ce("env")} state" lists ${t===1?"it":"them"}`;return`no state of ${s} is kept in ${e}${i}. A state kept in another folder is read with SANDFORGE_JOURNAL_DIR set as when it was written \u2014 in a CI job, a folder its cache restores.`}async function pS(e,t,n){let r=t.journalDir??fr(),s=vr({journalDir:r,fileFolder:null});if("refusal"in s)throw te(Ar(s.refusal,!1));let i=await s.store.sweep(),o;if(e.fileGiven){let u=Jn(Hs(e.file),Pe(e.file));if("refusals"in u)throw Ys(e.file,u.refusals);o=u.checked.file.name}let a=e.org,c=await s.store.list(),l=c.filter(u=>(o===void 0||u.env===o)&&(a===void 0||u.state?.org.alias===a||u.organizationId.slice(0,15)===a.slice(0,15)));for(let u of i)n(`expired and deleted: ${u.env} on ${u.alias??u.organizationId}`);l.length===0&&n(fS(s.store.root,c.length,o,a));for(let u of l){let d=u.state;if(d===void 0){n(`${u.env} on ${u.organizationId}: not used \u2014 ${u.damaged??""}`);continue}let f=Object.entries(d.resources).map(([y,g])=>`${y} ${g.status}`).join(", ");n(`${d.env} on ${d.org.alias??d.org.organizationId} (${d.org.kind}, ${d.org.organizationId}): serial ${d.serial}, written ${d.updatedAt}`+(u.expiresAt!==void 0?`, expires ${u.expiresAt}`:"")+(f?`; ${f}`:""))}return{journalDir:r,states:l.map(u=>{let d=u.state;if(d===void 0)return{env:u.env,organizationId:u.organizationId,damaged:u.damaged??"not used"};let f=mi(d);return{env:d.env,organizationId:d.org.organizationId,...d.org.alias!==void 0?{alias:d.org.alias}:{},kind:d.org.kind,serial:d.serial,resources:Object.fromEntries(Object.entries(d.resources).map(([y,g])=>[y,g.status])),updatedAt:d.updatedAt,...f!==void 0?{expiresAt:f}:{}}}),expired:i.map(u=>({env:u.env,organizationId:u.organizationId,...u.alias!==void 0?{alias:u.alias}:{},expiresAt:u.expiresAt}))}}async function hS(e,t,n){let r=Jn(Hs(e.file),Pe(e.file));if("refusals"in r)throw Ys(e.file,r.refusals);let s=t.journalDir??fr(),i=pr(Pe(e.file),s),o=vr({journalDir:s,fileFolder:Pe(e.file)});if("refusal"in o)throw te(Ar(o.refusal,i!==void 0));for(let u of await o.store.sweep())n(im(u));let a=Ph(await o.store.list(),r.checked.file.name,e.org??"");if("refusal"in a)throw te(a.refusal);let{output:c,whole:l}=await Th(a.state,{store:o.store,journalDir:s});return{answer:c,code:l?0:3}}async function mS(e,t,n){let r=await Qn(e,t,n),s=await Ch({store:r.store,journalDir:r.journalDir,locksDir:r.locksDir,sandforgeVersion:Js(),...t.lockOptions!==void 0?{lockOptions:t.lockOptions}:{}},{resolved:r.resolved,target:r.target});if("refusal"in s)throw te(s.refusal);for(let i of jh(s.result))n(i);return s.result}async function Va(e,t,n,r){return e.yes||await(t.ask??(i=>Ac(i)))(n)===e.org?!0:(r("Nothing was written: the alias typed is not the org\u2019s."),!1)}function Gs(e,t,n){return{runner:e.runner,store:e.store,locksDir:e.locksDir,journalDir:e.journalDir,orgNow:lS(e.reached.conn,n),say:n,sandforgeVersion:Js(),...t.onStop!==void 0?{onStop:t.onStop}:{},...t.lockOptions!==void 0?{lockOptions:t.lockOptions}:{}}}async function nm(e,t,n,r,s){let i=await Qn(e,t,r),o={verb:n,resolved:i.resolved,target:i.target,state:i.state,acceptAutomation:e.acceptAutomation,acceptEmails:e.acceptEmails,acceptNoUndo:e.acceptNoUndo,acceptUnseen:e.acceptUnseen},a=qa(o);if(a!==void 0)throw te(a);for(let u of i.warnings)r(`warning: ${u}`);let c;if(!e.yes){let u=await Ws(t,"reading what a rewind would do",d=>xh(Gs(i,t,r),o,d));if(!("differs"in u))throw new ee({refusal:{code:"REWIND_REFUSED",message:`${u.refusal} Nothing was written.`}},1);c=u;for(let d of fl(n,i.target.alias,u))r(d);if(u.refusal!==void 0)throw new ee({refusal:{code:u.refusal.code,message:u.refusal.message}},1);if(u.differs&&!await Va(e,t,Mh(o,u),r))throw new ee({refusal:{code:"DECLINED",message:"Nothing was written."}},1)}let l=await _h(Gs(i,t,r),o,c);for(let u of qh(l.result))r(u);s(l.result),Le(l.exitCode)}async function gS(e=process.argv,t={}){let n=ZE(e,t.cwd),r=i=>{process[n.json?"stderr":"stdout"].write(`${i}
352
352
  `)},s=i=>{n.json&&process.stdout.write(`${JSON.stringify(i,null,2)}
353
- `)};try{switch(n.command){case"validate":{let{answer:i,code:o}=nS(n,r);s(i),Fe(o);return}case"state":{s(n.recover?await oS(n,t,r):await sS(n,t,r));return}case"output":{let{answer:i,code:o}=await iS(n,t,r);for(let a of Oh(i))r(a);s(i),Fe(o);return}case"plan":{if(n.out!==void 0){let u=xh(Te(n.file),n.out,n.outInRepository);if(u!==void 0)throw ee(u)}let i=await Qn(n,t,r),{plan:o,dryRuns:a}=await Us(t,"planning",u=>Jh(i,n,r,u));for(let u of Ls(o))r(u);if(n.out!==void 0){let u=Fh({plan:o,state:i.state,digest:i.resolved.digest,line:{replace:n.replace,replaceDrifted:n.replaceDrifted,acceptAutomation:n.acceptAutomation,...n.acceptEmails?{acceptEmails:!0}:{},acceptNoState:n.acceptNoState},dryRuns:a,sandforgeVersion:Vs(),madeAt:new Date().toISOString()});await Mh(n.out,u),r(Uh(n.out,u))}s(o);let c=n.failOnChange&&$a(o),l=n.failOnDrift&&lh(o);Fe(c||l?3:0);return}case"apply":{n.quick&&he("apply makes a whole plan: --quick is for plan alone.");let i,o=n;if(n.plan!==void 0){let f=_h(n.plan);if("refusal"in f)throw ee(f.refusal);i=f.saved;let g=qh(i,n.plan,{now:Date.now(),sandforgeVersion:Vs()});if(g!==void 0)throw ee(g);o={...n,...i.line}}let a=await Qn(o,t,r);if(i!==void 0&&n.plan!==void 0){let f=zh(i,n.plan,{target:a.target,digest:a.resolved.digest,state:a.state});if(f!==void 0)throw ee(f)}let{plan:c,dryRuns:l}=await Us(t,"planning",f=>Jh(a,o,r,f,i?.seeds));if(i!==void 0&&n.plan!==void 0){let f=Bh(i.plan,c);if(f.length>0)throw ee(Kh(n.plan,f))}for(let f of Ls(c))r(f);if(i!==void 0&&n.plan!==void 0&&r(Vh(n.plan,i)),c.refusal===void 0&&$a(c)&&!await Ba(n,t,`Type ${a.target.alias} to apply ${c.env} to it as planned:`,r))throw new Z({refusal:{code:"DECLINED",message:"Nothing was written."}},1);let d=await ph(Js(a,t,r),{plan:c,resolved:a.resolved,target:a.target,state:a.state,dryRuns:l,acceptAutomation:o.acceptAutomation,acceptEmails:o.acceptEmails});for(let f of Ta(d.result,"apply"))r(f);s(d.result),Fe(d.exitCode);return}case"reset":{await Yh(n,t,"reset",r,s);return}case"destroy":{if(n.rewind){await Yh(n,t,"destroy",r,s);return}let i=await Qn(n,t,r),o={organizationId:i.target.organizationId,kind:i.target.kind,alias:i.target.alias},a=await Us(t,"reading what the org holds",u=>Zh(i,{includeChanged:n.includeChanged,acceptAutomation:n.acceptAutomation,refresh:!1,sweep:n.sweep},r,u)),c=ch({resolved:i.resolved,org:o,state:i.state,previews:a,warnings:i.warnings,maskStores:em(i)});for(let u of Ls(c,"destroy"))r(u);if(c.refusal===void 0&&c.actions.length>0&&!await Ba(n,t,`Type ${i.target.alias} to take ${c.env} back from it`+(n.includeChanged?", the records changed since included \u2014 on a shared org, others\u2019 work:":":"),r))throw new Z({refusal:{code:"DECLINED",message:"Nothing was deleted."}},1);let l=await Eh(Js(i,t,r),{plan:c,resolved:i.resolved,target:i.target,state:i.state,includeChanged:n.includeChanged,sweep:n.sweep,acceptAutomation:n.acceptAutomation});for(let u of Ta(l.result,"destroy"))r(u);s(l.result),Fe(l.exitCode);return}}}catch(i){let o=i instanceof Z?i:new Z({refusal:{code:"FAILED",message:i instanceof Error?i.message:String(i)}},1);process.stderr.write(`${o.message}
354
- `),s(o.answer),Fe(o.code)}}process.argv[1]?.includes("sandforge-env")&&(Ac(),aS().then(()=>process.exit(process.exitCode??0)).catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
355
- `),process.exit(1)}));export{Hh as envRelayOf,BE as envStepRunner,aS as main,UE as parseArgs,VE as readBudget,KE as relayedRunner};
353
+ `)};try{switch(n.command){case"validate":{let{answer:i,code:o}=dS(n,r);s(i),Le(o);return}case"state":{s(n.recover?await mS(n,t,r):await pS(n,t,r));return}case"output":{let{answer:i,code:o}=await hS(n,t,r);for(let a of Fh(i))r(a);s(i),Le(o);return}case"plan":{if(n.out!==void 0){let u=Vh(Pe(n.file),n.out,n.outInRepository);if(u!==void 0)throw te(u)}let i=await Qn(n,t,r),{plan:o,dryRuns:a}=await Ws(t,"planning",u=>tm(i,n,r,u));for(let u of xs(o))r(u);if(n.out!==void 0){let u=Uh({plan:o,state:i.state,digest:i.resolved.digest,line:{replace:n.replace,replaceDrifted:n.replaceDrifted,acceptAutomation:n.acceptAutomation,...n.acceptEmails?{acceptEmails:!0}:{},acceptNoState:n.acceptNoState},dryRuns:a,sandforgeVersion:Js(),madeAt:new Date().toISOString()});await Wh(n.out,u),r(Xh(n.out,u))}s(o);let c=n.failOnChange&&Ca(o),l=n.failOnDrift&&yh(o);Le(c||l?3:0);return}case"apply":{n.quick&&he("apply makes a whole plan: --quick is for plan alone.");let i,o=n;if(n.plan!==void 0){let f=Jh(n.plan);if("refusal"in f)throw te(f.refusal);i=f.saved;let y=Yh(i,n.plan,{now:Date.now(),sandforgeVersion:Js()});if(y!==void 0)throw te(y);o={...n,...i.line}}let a=await Qn(o,t,r);if(i!==void 0&&n.plan!==void 0){let f=Gh(i,n.plan,{target:a.target,digest:a.resolved.digest,state:a.state});if(f!==void 0)throw te(f)}let{plan:c,dryRuns:l}=await Ws(t,"planning",f=>tm(a,o,r,f,i?.seeds));if(i!==void 0&&n.plan!==void 0){let f=Hh(i.plan,c);if(f.length>0)throw te(Qh(n.plan,f))}for(let f of xs(c))r(f);if(i!==void 0&&n.plan!==void 0&&r(Zh(n.plan,i)),c.refusal===void 0&&Ca(c)&&!await Va(n,t,`Type ${a.target.alias} to apply ${c.env} to it as planned:`,r))throw new ee({refusal:{code:"DECLINED",message:"Nothing was written."}},1);let d=await bh(Gs(a,t,r),{plan:c,resolved:a.resolved,target:a.target,state:a.state,dryRuns:l,acceptAutomation:o.acceptAutomation,acceptEmails:o.acceptEmails});for(let f of La(d.result,"apply"))r(f);s(d.result),Le(d.exitCode);return}case"reset":{await nm(n,t,"reset",r,s);return}case"destroy":{if(n.rewind){await nm(n,t,"destroy",r,s);return}let i=await Qn(n,t,r),o={organizationId:i.target.organizationId,kind:i.target.kind,alias:i.target.alias},a=await Ws(t,"reading what the org holds",u=>am(i,{includeChanged:n.includeChanged,acceptAutomation:n.acceptAutomation,refresh:!1,sweep:n.sweep},r,u)),c=gh({resolved:i.resolved,org:o,state:i.state,previews:a,warnings:i.warnings,maskStores:cm(i)});for(let u of xs(c,"destroy"))r(u);if(c.refusal===void 0&&c.actions.length>0&&!await Va(n,t,`Type ${i.target.alias} to take ${c.env} back from it`+(n.includeChanged?", the records changed since included \u2014 on a shared org, others\u2019 work:":":"),r))throw new ee({refusal:{code:"DECLINED",message:"Nothing was deleted."}},1);let l=await Nh(Gs(i,t,r),{plan:c,resolved:i.resolved,target:i.target,state:i.state,includeChanged:n.includeChanged,sweep:n.sweep,acceptAutomation:n.acceptAutomation});for(let u of La(l.result,"destroy"))r(u);s(l.result),Le(l.exitCode);return}}}catch(i){let o=i instanceof ee?i:new ee({refusal:{code:"FAILED",message:i instanceof Error?i.message:String(i)}},1);process.stderr.write(`${o.message}
354
+ `),s(o.answer),Le(o.code)}}process.argv[1]?.includes("sandforge-env")&&(Tc(),gS().then(()=>process.exit(process.exitCode??0)).catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
355
+ `),process.exit(1)}));export{sm as envRelayOf,QE as envStepRunner,gS as main,ZE as parseArgs,eS as readBudget,XE as relayedRunner};