sandforge 1.85.0 → 1.86.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 (274) hide show
  1. package/README.md +1 -1
  2. package/lib/{chunk-THYQOG24.mjs → chunk-22L43JMK.mjs} +1 -1
  3. package/lib/{chunk-U4S27YRP.mjs → chunk-2LSGWTWX.mjs} +1 -1
  4. package/lib/{chunk-MRN72UEO.mjs → chunk-2YJJTQNC.mjs} +1 -1
  5. package/lib/chunk-34SMB5PA.mjs +10 -0
  6. package/lib/chunk-35B73566.mjs +7 -0
  7. package/lib/{chunk-YZKE6D3K.mjs → chunk-35IJ4WEU.mjs} +1 -1
  8. package/lib/chunk-3EHPAFKV.mjs +7 -0
  9. package/lib/{chunk-3OKDWZ32.mjs → chunk-3HAVVEXF.mjs} +1 -1
  10. package/lib/{chunk-32ZB5ICW.mjs → chunk-3I6FXFCN.mjs} +1 -1
  11. package/lib/{chunk-JFVY66BS.mjs → chunk-3KJCSYXY.mjs} +1 -1
  12. package/lib/{chunk-ULEYGOZU.mjs → chunk-3L6DVNCR.mjs} +1 -1
  13. package/lib/chunk-3LRFPGYZ.mjs +7 -0
  14. package/lib/{chunk-GHUA6OQQ.mjs → chunk-3MVWGL5A.mjs} +1 -1
  15. package/lib/{chunk-SF52ZSIV.mjs → chunk-4CSBZZAL.mjs} +1 -1
  16. package/lib/{chunk-FBYFCKPG.mjs → chunk-4NSXPONF.mjs} +1 -1
  17. package/lib/{chunk-A3QNSALB.mjs → chunk-4VLP6RHC.mjs} +1 -1
  18. package/lib/{chunk-TWYNQ2OO.mjs → chunk-4XROG5CT.mjs} +1 -1
  19. package/lib/chunk-54V4FVEY.mjs +7 -0
  20. package/lib/chunk-55OJJT2Q.mjs +7 -0
  21. package/lib/{chunk-JRI6A24G.mjs → chunk-5EHHQ5UX.mjs} +1 -1
  22. package/lib/{chunk-VPGX5Z5D.mjs → chunk-5JMQXHJ2.mjs} +1 -1
  23. package/lib/{chunk-CI2O7WBH.mjs → chunk-65AMXOQU.mjs} +1 -1
  24. package/lib/{chunk-5T3LFDJ5.mjs → chunk-6HHSAPIM.mjs} +1 -1
  25. package/lib/chunk-6KVBCFVS.mjs +7 -0
  26. package/lib/chunk-6NG7C2U3.mjs +476 -0
  27. package/lib/{chunk-F2424IKX.mjs → chunk-6ROL3KBM.mjs} +1 -1
  28. package/lib/{chunk-7ZYCRIHE.mjs → chunk-72AWCN7U.mjs} +1 -1
  29. package/lib/{chunk-MQLTEXB7.mjs → chunk-7KHA5UIQ.mjs} +1 -1
  30. package/lib/chunk-7O6EFNQS.mjs +10 -0
  31. package/lib/{chunk-73SLYGWD.mjs → chunk-A2CH2QGX.mjs} +1 -1
  32. package/lib/chunk-A2TXLAC3.mjs +276 -0
  33. package/lib/chunk-ALWVNR34.mjs +7 -0
  34. package/lib/{chunk-JBOGAUGH.mjs → chunk-ATBQIE2V.mjs} +1 -1
  35. package/lib/{chunk-C2MHMI7U.mjs → chunk-ATQML7ZK.mjs} +1 -1
  36. package/lib/chunk-AVY742BJ.mjs +7 -0
  37. package/lib/{chunk-VLAU5QQT.mjs → chunk-AXTB2HJS.mjs} +1 -1
  38. package/lib/chunk-BBZUGKBZ.mjs +10 -0
  39. package/lib/chunk-BIDXK7KA.mjs +7 -0
  40. package/lib/{chunk-KYLHS74X.mjs → chunk-BLMJ4WVI.mjs} +1 -1
  41. package/lib/{chunk-A7YP27GQ.mjs → chunk-BNHJCJJM.mjs} +1 -1
  42. package/lib/{chunk-ZDMSTL2L.mjs → chunk-BNPQEQXC.mjs} +1 -1
  43. package/lib/chunk-C5AUNG6T.mjs +37 -0
  44. package/lib/{chunk-LY6EPMIP.mjs → chunk-C5EQ7GFC.mjs} +1 -1
  45. package/lib/{chunk-LOO42EW5.mjs → chunk-C7CKDZMC.mjs} +62 -62
  46. package/lib/{chunk-ZP3WJGS3.mjs → chunk-CB4U22NR.mjs} +1 -1
  47. package/lib/chunk-CJAWKLAL.mjs +7 -0
  48. package/lib/chunk-CL75DEMQ.mjs +9 -0
  49. package/lib/{chunk-7L6FE5PP.mjs → chunk-CLUNF4FK.mjs} +1 -1
  50. package/lib/chunk-CSMGP53U.mjs +7 -0
  51. package/lib/{chunk-S6BMJSLD.mjs → chunk-CT324C7I.mjs} +1 -1
  52. package/lib/{chunk-YXOPKGDX.mjs → chunk-CZXDJXQP.mjs} +1 -1
  53. package/lib/{chunk-PGG4ULEW.mjs → chunk-D2X6U3MS.mjs} +1 -1
  54. package/lib/{chunk-FG4Y4ZVL.mjs → chunk-DAUX63UB.mjs} +1 -1
  55. package/lib/chunk-DB7JNALQ.mjs +10 -0
  56. package/lib/chunk-DDNCJVZ2.mjs +17 -0
  57. package/lib/{chunk-YGE4AUXG.mjs → chunk-DLSU66MY.mjs} +1 -1
  58. package/lib/{chunk-DCJBP3LE.mjs → chunk-DO6PSHQZ.mjs} +1 -1
  59. package/lib/{chunk-ROTDZKOE.mjs → chunk-DUBECLZV.mjs} +1 -1
  60. package/lib/{chunk-SES5HPBZ.mjs → chunk-DYHF6DNT.mjs} +1 -1
  61. package/lib/chunk-E5FSPXYH.mjs +930 -0
  62. package/lib/{chunk-QAXKUEJT.mjs → chunk-EGL3I3IX.mjs} +1 -1
  63. package/lib/chunk-EIYMQPMG.mjs +7 -0
  64. package/lib/{chunk-AX3YF7SC.mjs → chunk-EUIALBMX.mjs} +1 -1
  65. package/lib/{chunk-57QRXYAZ.mjs → chunk-FI3R5ZOQ.mjs} +1 -1
  66. package/lib/{chunk-FCZDWGQI.mjs → chunk-FM4QCTO7.mjs} +1 -1
  67. package/lib/{chunk-74HZ274R.mjs → chunk-FRSIEASH.mjs} +1 -1
  68. package/lib/{chunk-G6IYOZEH.mjs → chunk-FV6MOSHD.mjs} +1 -1
  69. package/lib/chunk-FYG47CNA.mjs +7 -0
  70. package/lib/chunk-GB6W4Q56.mjs +7 -0
  71. package/lib/chunk-GEV2DCMK.mjs +7 -0
  72. package/lib/{chunk-NZJXEULY.mjs → chunk-GFB2DNCB.mjs} +1 -1
  73. package/lib/chunk-GFGMGFSH.mjs +7 -0
  74. package/lib/{chunk-EFHDE7W4.mjs → chunk-GIFQXB2Q.mjs} +1 -1
  75. package/lib/{chunk-P6A22FMQ.mjs → chunk-GP5J3DGS.mjs} +1 -1
  76. package/lib/chunk-GQZEX7LH.mjs +231 -0
  77. package/lib/{chunk-BRN42U26.mjs → chunk-GYDTM62J.mjs} +1 -1
  78. package/lib/{chunk-GNCEHAJY.mjs → chunk-GYFIXUJG.mjs} +1 -1
  79. package/lib/chunk-GZW2GNFK.mjs +7 -0
  80. package/lib/chunk-H6BHWAX7.mjs +8 -0
  81. package/lib/{chunk-GUYEXPJ4.mjs → chunk-HDDJ3CVN.mjs} +1 -1
  82. package/lib/{chunk-3GATEVHC.mjs → chunk-HDWB4ZOG.mjs} +1 -1
  83. package/lib/chunk-HGVPBJR6.mjs +7 -0
  84. package/lib/{chunk-55VBV2WK.mjs → chunk-HLROVOR6.mjs} +1 -1
  85. package/lib/{chunk-HV3TDLFR.mjs → chunk-HUOR4M2L.mjs} +1 -1
  86. package/lib/chunk-HZCS6EED.mjs +8 -0
  87. package/lib/{chunk-WZX6VCIT.mjs → chunk-HZUI56KZ.mjs} +1 -1
  88. package/lib/chunk-IAB5H7WN.mjs +7 -0
  89. package/lib/{chunk-RY7WUJXH.mjs → chunk-IQ5UKRHU.mjs} +1 -1
  90. package/lib/{chunk-OUWR5M5G.mjs → chunk-IRQ4WANV.mjs} +1 -1
  91. package/lib/{chunk-F44EHXLI.mjs → chunk-IT3DGX37.mjs} +1 -1
  92. package/lib/chunk-J347SPU6.mjs +49 -0
  93. package/lib/{chunk-IZ2M2RGO.mjs → chunk-JANBNTR5.mjs} +1 -1
  94. package/lib/chunk-JFXQZPRY.mjs +9 -0
  95. package/lib/{chunk-VKA5OZBJ.mjs → chunk-JRLYWVF4.mjs} +1 -1
  96. package/lib/{chunk-FM5ESRH6.mjs → chunk-JSNMUTY6.mjs} +1 -1
  97. package/lib/chunk-JTNJKSAA.mjs +7 -0
  98. package/lib/{chunk-4D6OHSX3.mjs → chunk-JV2LAKWQ.mjs} +1 -1
  99. package/lib/{chunk-BY42YL4D.mjs → chunk-JV7K2ZHK.mjs} +1 -1
  100. package/lib/{chunk-A6IJUOLB.mjs → chunk-K4TQ7YHX.mjs} +1 -1
  101. package/lib/chunk-K5PUMHZU.mjs +7 -0
  102. package/lib/chunk-KH4KLCYG.mjs +7 -0
  103. package/lib/{chunk-FZF6FB65.mjs → chunk-KQVLZVOP.mjs} +1 -1
  104. package/lib/chunk-KWUS7UAV.mjs +19 -0
  105. package/lib/{chunk-2UUSF32M.mjs → chunk-L6G73FXM.mjs} +1 -1
  106. package/lib/{chunk-LUNGNCM3.mjs → chunk-LG466Q5H.mjs} +1 -1
  107. package/lib/{chunk-YTBM3TSW.mjs → chunk-LHNAR6FC.mjs} +1 -1
  108. package/lib/chunk-LT4GHEI2.mjs +7 -0
  109. package/lib/{chunk-P3OYE2FS.mjs → chunk-MR262Y3B.mjs} +1 -1
  110. package/lib/{chunk-TSTCHIBU.mjs → chunk-NCCHOV2N.mjs} +1 -1
  111. package/lib/chunk-NICRSGLS.mjs +7 -0
  112. package/lib/chunk-NV5QA2HY.mjs +7 -0
  113. package/lib/{chunk-6HAKOS6W.mjs → chunk-O3GIN5TU.mjs} +1 -1
  114. package/lib/chunk-O6FHK6NQ.mjs +13 -0
  115. package/lib/{chunk-OXIIKAUZ.mjs → chunk-O7YIEFG7.mjs} +1 -1
  116. package/lib/chunk-OCUVAA5E.mjs +7 -0
  117. package/lib/chunk-OLCS7JCT.mjs +14 -0
  118. package/lib/chunk-ON7Y63FK.mjs +9 -0
  119. package/lib/{chunk-K2WOT75I.mjs → chunk-OO2WY3UB.mjs} +1 -1
  120. package/lib/{chunk-3EOIAC2M.mjs → chunk-OT2NHL2V.mjs} +1 -1
  121. package/lib/{chunk-BK5SRDAD.mjs → chunk-P2M5ZXWU.mjs} +1 -1
  122. package/lib/{chunk-DCZYWMSA.mjs → chunk-P4YOHLZ4.mjs} +1 -1
  123. package/lib/chunk-PBHDPTT6.mjs +343 -0
  124. package/lib/chunk-PE7CHD2W.mjs +7 -0
  125. package/lib/{chunk-LU7M5URW.mjs → chunk-PIQ2I67B.mjs} +1 -1
  126. package/lib/chunk-PKYDNZJK.mjs +7 -0
  127. package/lib/chunk-PVZ72OOQ.mjs +7 -0
  128. package/lib/chunk-QACFTHJM.mjs +8 -0
  129. package/lib/{chunk-LNAZHI3J.mjs → chunk-QGVL5EW3.mjs} +1 -1
  130. package/lib/chunk-QHE2RUWX.mjs +7 -0
  131. package/lib/{chunk-4RNP65FV.mjs → chunk-RCW5BZNW.mjs} +1 -1
  132. package/lib/{chunk-OTKXTBTX.mjs → chunk-RJ6HHG7J.mjs} +1 -1
  133. package/lib/{chunk-IVDBVWKK.mjs → chunk-RPTEEI4R.mjs} +1 -1
  134. package/lib/chunk-RQW5S67A.mjs +7 -0
  135. package/lib/chunk-RTCMYMED.mjs +7 -0
  136. package/lib/chunk-RWVX7XSD.mjs +7 -0
  137. package/lib/{chunk-2UUS4IGB.mjs → chunk-RZOINFNL.mjs} +1 -1
  138. package/lib/chunk-SOOTWGMQ.mjs +7 -0
  139. package/lib/chunk-STQ2JMIZ.mjs +7 -0
  140. package/lib/{chunk-RC25QQVF.mjs → chunk-SUIPDW5O.mjs} +1 -1
  141. package/lib/{chunk-Z354SAEF.mjs → chunk-SZOJ7BEJ.mjs} +1 -1
  142. package/lib/{chunk-45375WT5.mjs → chunk-T542Z54E.mjs} +1 -1
  143. package/lib/chunk-TAN2CIRI.mjs +21 -0
  144. package/lib/{chunk-BGJBYDRW.mjs → chunk-TCNBINOG.mjs} +1 -1
  145. package/lib/chunk-TFDF3DBN.mjs +7 -0
  146. package/lib/{chunk-B5A4JHNN.mjs → chunk-TICZXC53.mjs} +1 -1
  147. package/lib/chunk-TLX45X5U.mjs +7 -0
  148. package/lib/{chunk-W6SLQZKQ.mjs → chunk-TMIV3IWH.mjs} +1 -1
  149. package/lib/chunk-TQ6HEJ73.mjs +11 -0
  150. package/lib/chunk-TTU5EQZ6.mjs +7 -0
  151. package/lib/chunk-TYUYPFDJ.mjs +7 -0
  152. package/lib/chunk-TZXYVMZC.mjs +7 -0
  153. package/lib/{chunk-4N425UJC.mjs → chunk-UCUFLFNK.mjs} +1 -1
  154. package/lib/chunk-UK3QLBHW.mjs +7 -0
  155. package/lib/{chunk-SKGAERV4.mjs → chunk-UM2B4GR7.mjs} +1 -1
  156. package/lib/chunk-UZFTTNOP.mjs +7 -0
  157. package/lib/chunk-V3AXSKSU.mjs +7 -0
  158. package/lib/chunk-VA6EEI6X.mjs +21 -0
  159. package/lib/{chunk-LSEM2BZH.mjs → chunk-VFKG2G37.mjs} +1 -1
  160. package/lib/chunk-VJNEW5MQ.mjs +7 -0
  161. package/lib/{chunk-EYFP3NA6.mjs → chunk-VKREON6Q.mjs} +1 -1
  162. package/lib/{chunk-TIVI2KGB.mjs → chunk-VNNDYPBL.mjs} +1 -1
  163. package/lib/{chunk-J3FJ3BWE.mjs → chunk-VRBETPHY.mjs} +1 -1
  164. package/lib/{chunk-UX4AOSMU.mjs → chunk-VT6P3X6R.mjs} +1 -1
  165. package/lib/{chunk-CUOWQMGW.mjs → chunk-VUTQY76O.mjs} +1 -1
  166. package/lib/chunk-WF5S4FW5.mjs +7 -0
  167. package/lib/{chunk-JHJDDQDE.mjs → chunk-WJGK6VGU.mjs} +1 -1
  168. package/lib/{chunk-IZREPWYQ.mjs → chunk-WJHMB3SL.mjs} +1 -1
  169. package/lib/{chunk-XZRON54U.mjs → chunk-WQCXOZEJ.mjs} +1 -1
  170. package/lib/{chunk-N2MXYD67.mjs → chunk-WVVFR4E3.mjs} +1 -1
  171. package/lib/{chunk-GG5I52UT.mjs → chunk-XBYXT74L.mjs} +1 -1
  172. package/lib/chunk-XJE3LJHP.mjs +7 -0
  173. package/lib/{chunk-3QCUSZIZ.mjs → chunk-XV4CVZYD.mjs} +1 -1
  174. package/lib/chunk-Y37ED7AS.mjs +7 -0
  175. package/lib/{chunk-MN3XBJPE.mjs → chunk-YGBNZYT4.mjs} +1 -1
  176. package/lib/{chunk-SBDF4AE5.mjs → chunk-YGTOX7IL.mjs} +1 -1
  177. package/lib/{chunk-SQM32AOQ.mjs → chunk-YJ27WHKR.mjs} +1 -1
  178. package/lib/chunk-YRULC27A.mjs +7 -0
  179. package/lib/{chunk-RMFU4BAL.mjs → chunk-YSVAHT4Q.mjs} +4 -4
  180. package/lib/chunk-YTOTMJTY.mjs +15 -0
  181. package/lib/{chunk-SU24AE3H.mjs → chunk-YZKZC62O.mjs} +1 -1
  182. package/lib/{chunk-LJNRN7MY.mjs → chunk-YZQN7BRB.mjs} +1 -1
  183. package/lib/{chunk-NMF55UBQ.mjs → chunk-Z5IUK2QO.mjs} +1 -1
  184. package/lib/{chunk-6ZWY36LK.mjs → chunk-ZEGSMW5A.mjs} +1 -1
  185. package/lib/{chunk-YV7JYHJP.mjs → chunk-ZIKLQZBG.mjs} +1 -1
  186. package/lib/chunk-ZVU7MD2S.mjs +7 -0
  187. package/lib/sandforge-autopilot.mjs +33 -27
  188. package/lib/sandforge-backup.mjs +19 -19
  189. package/lib/sandforge-checkpoint.mjs +1 -1
  190. package/lib/sandforge-cleanup.mjs +1 -1
  191. package/lib/sandforge-clone.mjs +1 -1
  192. package/lib/sandforge-compare.mjs +29 -16
  193. package/lib/sandforge-dataops.mjs +1 -1
  194. package/lib/sandforge-empty.mjs +11 -13
  195. package/lib/sandforge-env.mjs +105 -105
  196. package/lib/sandforge-frozen.mjs +1 -1
  197. package/lib/sandforge-mcp.mjs +2 -2
  198. package/lib/sandforge-monitor.mjs +1 -1
  199. package/lib/sandforge-pipeline.mjs +13 -13
  200. package/lib/sandforge-seed.mjs +1 -1
  201. package/lib/sandforge-sync.mjs +1 -1
  202. package/lib/sandforge-users.mjs +13 -15
  203. package/lib/sandforge.mjs +1 -1
  204. package/lib/sf/sandforge/dataops.mjs +2 -2
  205. package/lib/sfPlugin.mjs +1 -1
  206. package/oclif.manifest.json +1 -1
  207. package/package.json +1 -1
  208. package/lib/chunk-26EGXYZ4.mjs +0 -21
  209. package/lib/chunk-2JRVBXJL.mjs +0 -7
  210. package/lib/chunk-2METQHGG.mjs +0 -7
  211. package/lib/chunk-3XU7CEJQ.mjs +0 -7
  212. package/lib/chunk-4BQPAVMP.mjs +0 -14
  213. package/lib/chunk-4KMKOE77.mjs +0 -156
  214. package/lib/chunk-4RPA7Z52.mjs +0 -7
  215. package/lib/chunk-5C7LQXYS.mjs +0 -7
  216. package/lib/chunk-5EESNYE3.mjs +0 -8
  217. package/lib/chunk-6ZW6BLV5.mjs +0 -7
  218. package/lib/chunk-AAOMUI7S.mjs +0 -15
  219. package/lib/chunk-AIUAEBHR.mjs +0 -7
  220. package/lib/chunk-BD724WOH.mjs +0 -7
  221. package/lib/chunk-CRPLDXJU.mjs +0 -48
  222. package/lib/chunk-CSSOLHE3.mjs +0 -7
  223. package/lib/chunk-D63HEQ3B.mjs +0 -7
  224. package/lib/chunk-DN7YBILC.mjs +0 -21
  225. package/lib/chunk-DNE7JI3A.mjs +0 -11
  226. package/lib/chunk-EFHM2U4D.mjs +0 -7
  227. package/lib/chunk-EINEGS6E.mjs +0 -7
  228. package/lib/chunk-EM5EFMHA.mjs +0 -272
  229. package/lib/chunk-FH5UR35W.mjs +0 -7
  230. package/lib/chunk-FN7TOBJR.mjs +0 -7
  231. package/lib/chunk-HGJFATSI.mjs +0 -10
  232. package/lib/chunk-HOEE3PE5.mjs +0 -7
  233. package/lib/chunk-HV63UGL5.mjs +0 -7
  234. package/lib/chunk-JKFCGYJE.mjs +0 -7
  235. package/lib/chunk-KATBU46O.mjs +0 -7
  236. package/lib/chunk-LD34JNCC.mjs +0 -7
  237. package/lib/chunk-LPN4WYTP.mjs +0 -478
  238. package/lib/chunk-MAOUFJ47.mjs +0 -7
  239. package/lib/chunk-MB2DG66I.mjs +0 -13
  240. package/lib/chunk-NCASRA7L.mjs +0 -9
  241. package/lib/chunk-NEKNAILD.mjs +0 -7
  242. package/lib/chunk-NN2IO4WE.mjs +0 -7
  243. package/lib/chunk-O3ZQSWDN.mjs +0 -10
  244. package/lib/chunk-OFQOKSEW.mjs +0 -7
  245. package/lib/chunk-PP7PJXRJ.mjs +0 -341
  246. package/lib/chunk-PT2E2HFD.mjs +0 -7
  247. package/lib/chunk-PZBZ7MNC.mjs +0 -7
  248. package/lib/chunk-QBYK5XIT.mjs +0 -8
  249. package/lib/chunk-RFD6NPWJ.mjs +0 -8
  250. package/lib/chunk-RIIJJRGF.mjs +0 -7
  251. package/lib/chunk-RKTFFCNS.mjs +0 -7
  252. package/lib/chunk-RM5G4IP6.mjs +0 -19
  253. package/lib/chunk-RTPNK7OB.mjs +0 -7
  254. package/lib/chunk-RZXEO5IE.mjs +0 -7
  255. package/lib/chunk-SAHGDSZQ.mjs +0 -37
  256. package/lib/chunk-SRPWW4A2.mjs +0 -10
  257. package/lib/chunk-SVNSAHG3.mjs +0 -7
  258. package/lib/chunk-T63U4OZJ.mjs +0 -7
  259. package/lib/chunk-TE2W76II.mjs +0 -10
  260. package/lib/chunk-TEIBWMJM.mjs +0 -7
  261. package/lib/chunk-TFGJDZFE.mjs +0 -7
  262. package/lib/chunk-TG52WNGV.mjs +0 -10
  263. package/lib/chunk-TQONVFI3.mjs +0 -7
  264. package/lib/chunk-TW3N6W5Z.mjs +0 -7
  265. package/lib/chunk-UZMLPKW6.mjs +0 -7
  266. package/lib/chunk-WB2RIVO3.mjs +0 -7
  267. package/lib/chunk-WQO7RXEB.mjs +0 -926
  268. package/lib/chunk-X3MBY2RX.mjs +0 -7
  269. package/lib/chunk-XMJRXXUN.mjs +0 -7
  270. package/lib/chunk-YNMU5I7P.mjs +0 -7
  271. package/lib/chunk-YSQJKIO6.mjs +0 -7
  272. package/lib/chunk-YVVPJRZC.mjs +0 -7
  273. package/lib/chunk-ZLQHBI6V.mjs +0 -9
  274. package/lib/chunk-ZRUDYB7O.mjs +0 -7
@@ -4,154 +4,154 @@ 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 pn,b as Gu,d as Ir}from"./chunk-2UUSF32M.mjs";import"./chunk-N2MXYD67.mjs";import{a as se,b as Fo,c as Wu,d as Hu,e as Yu,f as Ju}from"./chunk-S6BMJSLD.mjs";import{f as Ku,g as Vu}from"./chunk-H33DVU3D.mjs";import{a as xo,b as Cr,c as Ne,d as Lo,e as kt}from"./chunk-ROTDZKOE.mjs";import{a as Ou,c as Je,d as ju,e as Cu,f as Iu,g as $r}from"./chunk-BY42YL4D.mjs";import{a as Fu}from"./chunk-FCZDWGQI.mjs";import{c as Xu,g as Mo}from"./chunk-YZKE6D3K.mjs";import"./chunk-EM5EFMHA.mjs";import"./chunk-PP7PJXRJ.mjs";import"./chunk-INIQ23K6.mjs";import"./chunk-RC25QQVF.mjs";import{a as Qu}from"./chunk-DN7YBILC.mjs";import"./chunk-VLAU5QQT.mjs";import{f as fn,g as jr,j as Bu}from"./chunk-TSTCHIBU.mjs";import{c as zu,d as qu}from"./chunk-U4S27YRP.mjs";import{m as Uu}from"./chunk-YTBM3TSW.mjs";import"./chunk-GG5I52UT.mjs";import{a as Or,d as Be}from"./chunk-UV74P4H2.mjs";import{i as Mu,k as _u}from"./chunk-SKGAERV4.mjs";import"./chunk-MRN72UEO.mjs";import"./chunk-A3QNSALB.mjs";import{f as xu}from"./chunk-FQGHL7GR.mjs";import"./chunk-TFGJDZFE.mjs";import"./chunk-G6IYOZEH.mjs";import"./chunk-45375WT5.mjs";import"./chunk-DCJBP3LE.mjs";import"./chunk-YV7JYHJP.mjs";import"./chunk-2JRVBXJL.mjs";import"./chunk-GMY5427L.mjs";import"./chunk-HV3TDLFR.mjs";import{b as eu}from"./chunk-NMF55UBQ.mjs";import{b as Zu,e as _o,f as zo}from"./chunk-4KMKOE77.mjs";import"./chunk-TW3N6W5Z.mjs";import"./chunk-5GBO4KD5.mjs";import{Hb as Nu,Ib as Tu,fb as Ar,ib as Pu}from"./chunk-WQO7RXEB.mjs";import"./chunk-RY7WUJXH.mjs";import{b as qe,c as Au}from"./chunk-UX4AOSMU.mjs";import"./chunk-UZMLPKW6.mjs";import{b as vt,c as bu}from"./chunk-2METQHGG.mjs";import{i as nu}from"./chunk-6FARZYMJ.mjs";import"./chunk-MQLTEXB7.mjs";import{a as No}from"./chunk-AAOMUI7S.mjs";import"./chunk-JHJDDQDE.mjs";import"./chunk-ULEYGOZU.mjs";import"./chunk-XCA5AONB.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-WB2RIVO3.mjs";import{b as Lu}from"./chunk-W6SLQZKQ.mjs";import{Wa as au,_ as ou,za as iu}from"./chunk-RIIJJRGF.mjs";import"./chunk-EYFP3NA6.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-LSEM2BZH.mjs";import"./chunk-ZLQHBI6V.mjs";import"./chunk-BOGNK4LV.mjs";import{b as Ru}from"./chunk-4BQPAVMP.mjs";import{a as tu,b as Pe,e as Ye}from"./chunk-RKTFFCNS.mjs";import{ia as Sr,n as Eu,pa as Su,ua as $u}from"./chunk-SAHGDSZQ.mjs";import"./chunk-32ZB5ICW.mjs";import"./chunk-TG52WNGV.mjs";import{M as uu}from"./chunk-CSSOLHE3.mjs";import"./chunk-HGJFATSI.mjs";import"./chunk-TEIBWMJM.mjs";import"./chunk-BWWQXU2B.mjs";import"./chunk-T63U4OZJ.mjs";import"./chunk-5EESNYE3.mjs";import"./chunk-QAXKUEJT.mjs";import"./chunk-JKFCGYJE.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-YDXMTWAT.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-EINEGS6E.mjs";import"./chunk-QIRO4HTE.mjs";import{h as du,l as lu,n as fu,p as To}from"./chunk-RM5G4IP6.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-B5A4JHNN.mjs";import"./chunk-YGE4AUXG.mjs";import"./chunk-C2MHMI7U.mjs";import"./chunk-RFD6NPWJ.mjs";import{I as pu,L as hu,M as mu,k as pe}from"./chunk-SF52ZSIV.mjs";import{a as B,b as De}from"./chunk-AL4C3GFT.mjs";import{d as cu}from"./chunk-P6A22FMQ.mjs";import"./chunk-5LFSFYFJ.mjs";import{a as Po,b as Xc,c as Zc}from"./chunk-XZRON54U.mjs";import"./chunk-3EOIAC2M.mjs";import"./chunk-AIUAEBHR.mjs";import{L as gu,Q as yu,Za as Rr,_b as ku,hb as wu,ib as vu,xc as wt}from"./chunk-O3ZQSWDN.mjs";import"./chunk-DNE7JI3A.mjs";import{a as br,b as Er,d as Gc}from"./chunk-CI2O7WBH.mjs";import"./chunk-5T3LFDJ5.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-AX3YF7SC.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-Q7TLC3I2.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-JBOGAUGH.mjs";import"./chunk-4N425UJC.mjs";import"./chunk-MS4FJDFD.mjs";import"./chunk-TWYNQ2OO.mjs";import{b as Qc,f as ze,g as ln,h as Du}from"./chunk-LCDPCUXS.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-FG4Y4ZVL.mjs";import"./chunk-Z354SAEF.mjs";import{f as ru,h as su}from"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-THYQOG24.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-ICIYL45C.mjs";import"./chunk-JFVY66BS.mjs";import"./chunk-GUYEXPJ4.mjs";import"./chunk-TUACWKIH.mjs";import{Ab as Wc,Bb as kr,Cb as Hc,Da as jo,Db as Yc,Eb as dn,Gb as Io,Ra as gt,bc as Do,cb as zc,e as yr,eb as qc,j as Mc,mb as Bc,ob as Uc,rb as wr,tb as yt,ub as vr,vb as un,vd as Jc,wb as Co,x as _c,xb as Kc,yb as Vc}from"./chunk-CRPLDXJU.mjs";import{A as p}from"./chunk-WZQEK4WT.mjs";import{a as gr,b as C,d as Ly}from"./chunk-NTOVCTRS.mjs";var z=C(ie=>{"use strict";var Ri=Symbol.for("yaml.alias"),Rp=Symbol.for("yaml.document"),cs=Symbol.for("yaml.map"),Sp=Symbol.for("yaml.pair"),Si=Symbol.for("yaml.scalar"),us=Symbol.for("yaml.seq"),Ke=Symbol.for("yaml.node.type"),zv=e=>!!e&&typeof e=="object"&&e[Ke]===Ri,qv=e=>!!e&&typeof e=="object"&&e[Ke]===Rp,Bv=e=>!!e&&typeof e=="object"&&e[Ke]===cs,Uv=e=>!!e&&typeof e=="object"&&e[Ke]===Sp,$p=e=>!!e&&typeof e=="object"&&e[Ke]===Si,Kv=e=>!!e&&typeof e=="object"&&e[Ke]===us;function Ap(e){if(e&&typeof e=="object")switch(e[Ke]){case cs:case us:return!0}return!1}function Vv(e){if(e&&typeof e=="object")switch(e[Ke]){case Ri:case cs:case Si:case us:return!0}return!1}var Wv=e=>($p(e)||Ap(e))&&!!e.anchor;ie.ALIAS=Ri;ie.DOC=Rp;ie.MAP=cs;ie.NODE_TYPE=Ke;ie.PAIR=Sp;ie.SCALAR=Si;ie.SEQ=us;ie.hasAnchor=Wv;ie.isAlias=zv;ie.isCollection=Ap;ie.isDocument=qv;ie.isMap=Bv;ie.isNode=Vv;ie.isPair=Uv;ie.isScalar=$p;ie.isSeq=Kv});var Dn=C($i=>{"use strict";var ee=z(),me=Symbol("break visit"),Op=Symbol("skip children"),Fe=Symbol("remove node");function ds(e,t){let n=jp(t);ee.isDocument(e)?Yt(null,e.contents,n,Object.freeze([e]))===Fe&&(e.contents=null):Yt(null,e,n,Object.freeze([]))}ds.BREAK=me;ds.SKIP=Op;ds.REMOVE=Fe;function Yt(e,t,n,r){let s=Cp(e,t,n,r);if(ee.isNode(s)||ee.isPair(s))return Ip(e,r,s),Yt(e,s,n,r);if(typeof s!="symbol"){if(ee.isCollection(t)){r=Object.freeze(r.concat(t));for(let o=0;o<t.items.length;++o){let i=Yt(o,t.items[o],n,r);if(typeof i=="number")o=i-1;else{if(i===me)return me;i===Fe&&(t.items.splice(o,1),o-=1)}}}else if(ee.isPair(t)){r=Object.freeze(r.concat(t));let o=Yt("key",t.key,n,r);if(o===me)return me;o===Fe&&(t.key=null);let i=Yt("value",t.value,n,r);if(i===me)return me;i===Fe&&(t.value=null)}}return s}async function ls(e,t){let n=jp(t);ee.isDocument(e)?await Jt(null,e.contents,n,Object.freeze([e]))===Fe&&(e.contents=null):await Jt(null,e,n,Object.freeze([]))}ls.BREAK=me;ls.SKIP=Op;ls.REMOVE=Fe;async function Jt(e,t,n,r){let s=await Cp(e,t,n,r);if(ee.isNode(s)||ee.isPair(s))return Ip(e,r,s),Jt(e,s,n,r);if(typeof s!="symbol"){if(ee.isCollection(t)){r=Object.freeze(r.concat(t));for(let o=0;o<t.items.length;++o){let i=await Jt(o,t.items[o],n,r);if(typeof i=="number")o=i-1;else{if(i===me)return me;i===Fe&&(t.items.splice(o,1),o-=1)}}}else if(ee.isPair(t)){r=Object.freeze(r.concat(t));let o=await Jt("key",t.key,n,r);if(o===me)return me;o===Fe&&(t.key=null);let i=await Jt("value",t.value,n,r);if(i===me)return me;i===Fe&&(t.value=null)}}return s}function jp(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 Cp(e,t,n,r){if(typeof n=="function")return n(e,t,r);if(ee.isMap(t))return n.Map?.(e,t,r);if(ee.isSeq(t))return n.Seq?.(e,t,r);if(ee.isPair(t))return n.Pair?.(e,t,r);if(ee.isScalar(t))return n.Scalar?.(e,t,r);if(ee.isAlias(t))return n.Alias?.(e,t,r)}function Ip(e,t,n){let r=t[t.length-1];if(ee.isCollection(r))r.items[e]=n;else if(ee.isPair(r))e==="key"?r.key=n:r.value=n;else if(ee.isDocument(r))r.contents=n;else{let s=ee.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}$i.visit=ds;$i.visitAsync=ls});var Ai=C(Pp=>{"use strict";var Dp=z(),Hv=Dn(),Yv={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Jv=e=>e.replace(/[!,[\]{}]/g,t=>Yv[t]),Pn=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[o,i]=r;return this.tags[o]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[o]=r;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let i=/^\d+\.\d+$/.test(o);return n(6,`Unsupported YAML version ${o}`,i),!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 i=t.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,s]=t.match(/^(.*!)([^!]*)$/s);s||n(`The ${t} tag has no suffix`);let o=this.tags[r];if(o)try{return o+decodeURIComponent(s)}catch(i){return n(String(i)),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+Jv(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&&Dp.isNode(t.contents)){let o={};Hv.visit(t.contents,(i,a)=>{Dp.isNode(a)&&a.tag&&(o[a.tag]=!0)}),s=Object.keys(o)}else s=[];for(let[o,i]of r)o==="!!"&&i==="tag:yaml.org,2002:"||(!t||s.some(a=>a.startsWith(i)))&&n.push(`%TAG ${o} ${i}`);return n.join(`
8
- `)}};Pn.defaultYaml={explicit:!1,version:"1.2"};Pn.defaultTags={"!!":"tag:yaml.org,2002:"};Pp.Directives=Pn});var fs=C(Nn=>{"use strict";var Np=z(),Gv=Dn();function Qv(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 Tp(e){let t=new Set;return Gv.visit(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function xp(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function Xv(e,t){let n=[],r=new Map,s=null;return{onAnchor:o=>{n.push(o),s??(s=Tp(e));let i=xp(t,s);return s.add(i),i},setAnchors:()=>{for(let o of n){let i=r.get(o);if(typeof i=="object"&&i.anchor&&(Np.isScalar(i.node)||Np.isCollection(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=o,a}}},sourceObjects:r}}Nn.anchorIsValid=Qv;Nn.anchorNames=Tp;Nn.createNodeAnchors=Xv;Nn.findNewAnchor=xp});var Oi=C(Lp=>{"use strict";function Tn(e,t,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let s=0,o=r.length;s<o;++s){let i=r[s],a=Tn(e,r,String(s),i);a===void 0?delete r[s]:a!==i&&(r[s]=a)}else if(r instanceof Map)for(let s of Array.from(r.keys())){let o=r.get(s),i=Tn(e,r,s,o);i===void 0?r.delete(s):i!==o&&r.set(s,i)}else if(r instanceof Set)for(let s of Array.from(r)){let o=Tn(e,r,s,s);o===void 0?r.delete(s):o!==s&&(r.delete(s),r.add(o))}else for(let[s,o]of Object.entries(r)){let i=Tn(e,r,s,o);i===void 0?delete r[s]:i!==o&&(r[s]=i)}return e.call(t,n,r)}Lp.applyReviver=Tn});var rt=C(Mp=>{"use strict";var Zv=z();function Fp(e,t,n){if(Array.isArray(e))return e.map((r,s)=>Fp(r,String(s),n));if(e&&typeof e.toJSON=="function"){if(!n||!Zv.hasAnchor(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=o=>{r.res=o,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}Mp.toJS=Fp});var ps=C(zp=>{"use strict";var ek=Oi(),_p=z(),tk=rt(),ji=class{constructor(t){Object.defineProperty(this,_p.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:o}={}){if(!_p.isDocument(t))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=tk.toJS(this,"",i);if(typeof s=="function")for(let{count:c,res:u}of i.anchors.values())s(u,c);return typeof o=="function"?ek.applyReviver(o,{"":a},"",a):a}};zp.NodeBase=ji});var xn=C(qp=>{"use strict";var nk=fs(),rk=Dn(),Gt=z(),sk=ps(),ok=rt(),Ci=class extends sk.NodeBase{constructor(t){super(Gt.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=[],rk.visit(t,{Node:(o,i)=>{(Gt.isAlias(i)||Gt.hasAnchor(i))&&r.push(i)}}),n&&(n.aliasResolveCache=r));let s;for(let o of r){if(o===this)break;o.anchor===this.source&&(s=o)}if(s&&n){let{anchors:o,doc:i,maxAliasCount:a}=n,c=o.get(s);if(c||(ok.toJS(s,null,n),c=o.get(s)),c?.res===void 0){let u="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(u)}if(a>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=hs(i,s,o)),c.count*c.aliasCount>a)){let u="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(u)}}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(nk.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(t.implicitKey)return`${s} `}return s}};function hs(e,t,n){if(Gt.isAlias(t)){let r=t.resolve(e),s=n&&r&&n.get(r);return s?s.count*s.aliasCount:0}else if(Gt.isCollection(t)){let r=0;for(let s of t.items){let o=hs(e,s,n);o>r&&(r=o)}return r}else if(Gt.isPair(t)){let r=hs(e,t.key,n),s=hs(e,t.value,n);return Math.max(r,s)}return 1}qp.Alias=Ci});var Q=C(Ii=>{"use strict";var ik=z(),ak=ps(),ck=rt(),uk=e=>!e||typeof e!="function"&&typeof e!="object",st=class extends ak.NodeBase{constructor(t){super(ik.SCALAR),this.value=t}toJSON(t,n){return n?.keep?this.value:ck.toJS(this.value,t,n)}toString(){return String(this.value)}};st.BLOCK_FOLDED="BLOCK_FOLDED";st.BLOCK_LITERAL="BLOCK_LITERAL";st.PLAIN="PLAIN";st.QUOTE_DOUBLE="QUOTE_DOUBLE";st.QUOTE_SINGLE="QUOTE_SINGLE";Ii.Scalar=st;Ii.isScalarValue=uk});var Ln=C(Up=>{"use strict";var dk=xn(),At=z(),Bp=Q(),lk="tag:yaml.org,2002:";function fk(e,t,n){if(t){let r=n.filter(o=>o.tag===t),s=r.find(o=>!o.format)??r[0];if(!s)throw new Error(`Tag ${t} not found`);return s}return n.find(r=>r.identify?.(e)&&!r.format)}function pk(e,t,n){if(At.isDocument(e)&&(e=e.contents),At.isNode(e))return e;if(At.isPair(e)){let l=n.schema[At.MAP].createNode?.(n.schema,null,n);return l.items.push(e),l}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:s,onTagObj:o,schema:i,sourceObjects:a}=n,c;if(r&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=s(e)),new dk.Alias(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=lk+t.slice(2));let u=fk(e,t,i.tags);if(!u){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let l=new Bp.Scalar(e);return c&&(c.node=l),l}u=e instanceof Map?i[At.MAP]:Symbol.iterator in Object(e)?i[At.SEQ]:i[At.MAP]}o&&(o(u),delete n.onTagObj);let d=u?.createNode?u.createNode(n.schema,e,n):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(n.schema,e,n):new Bp.Scalar(e);return t?d.tag=t:u.default||(d.tag=u.tag),c&&(c.node=d),d}Up.createNode=pk});var gs=C(ms=>{"use strict";var hk=Ln(),Me=z(),mk=ps();function Di(e,t,n){let r=n;for(let s=t.length-1;s>=0;--s){let o=t[s];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let i=[];i[o]=r,r=i}else r=new Map([[o,r]])}return hk.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 Kp=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Pi=class extends mk.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=>Me.isNode(r)||Me.isPair(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(Kp(t))this.add(n);else{let[r,...s]=t,o=this.get(r,!0);if(Me.isCollection(o))o.addIn(s,n);else if(o===void 0&&this.schema)this.set(r,Di(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(Me.isCollection(s))return s.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(t,n){let[r,...s]=t,o=this.get(r,!0);return s.length===0?!n&&Me.isScalar(o)?o.value:o:Me.isCollection(o)?o.getIn(s,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!Me.isPair(n))return!1;let r=n.value;return r==null||t&&Me.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 Me.isCollection(s)?s.hasIn(r):!1}setIn(t,n){let[r,...s]=t;if(s.length===0)this.set(r,n);else{let o=this.get(r,!0);if(Me.isCollection(o))o.setIn(s,n);else if(o===void 0&&this.schema)this.set(r,Di(this.schema,s,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`)}}};ms.Collection=Pi;ms.collectionFromPath=Di;ms.isEmptyPath=Kp});var Fn=C(ys=>{"use strict";var gk=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ni(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var yk=(e,t,n)=>e.endsWith(`
9
- `)?Ni(n,t):n.includes(`
7
+ import{a as se,b as Mo,c as Yu,d as Ju,e as Gu,f as Qu}from"./chunk-CT324C7I.mjs";import{a as hn,b as Xu,d as Dr}from"./chunk-L6G73FXM.mjs";import"./chunk-WVVFR4E3.mjs";import{f as Wu,g as Hu}from"./chunk-H33DVU3D.mjs";import{a as Lo,b as Ir,c as Ne,d as Fo,e as bt}from"./chunk-DUBECLZV.mjs";import{a as Iu,c as Qe,d as Du,e as Pu,f as Nu,g as Ar}from"./chunk-JV7K2ZHK.mjs";import{a as _u}from"./chunk-FM4QCTO7.mjs";import{c as ed,g as _o}from"./chunk-35IJ4WEU.mjs";import"./chunk-A2TXLAC3.mjs";import"./chunk-PBHDPTT6.mjs";import"./chunk-INIQ23K6.mjs";import"./chunk-SUIPDW5O.mjs";import{a as Zu}from"./chunk-TAN2CIRI.mjs";import"./chunk-AXTB2HJS.mjs";import{f as pn,g as Cr,j as Ku}from"./chunk-NCCHOV2N.mjs";import{c as Bu,d as Uu}from"./chunk-2LSGWTWX.mjs";import{m as Vu}from"./chunk-LHNAR6FC.mjs";import"./chunk-XBYXT74L.mjs";import{a as jr,d as Ue}from"./chunk-UV74P4H2.mjs";import{i as zu,k as qu}from"./chunk-UM2B4GR7.mjs";import"./chunk-2YJJTQNC.mjs";import"./chunk-4VLP6RHC.mjs";import"./chunk-WF5S4FW5.mjs";import"./chunk-FV6MOSHD.mjs";import"./chunk-T542Z54E.mjs";import"./chunk-DO6PSHQZ.mjs";import"./chunk-ZIKLQZBG.mjs";import"./chunk-FYG47CNA.mjs";import"./chunk-GMY5427L.mjs";import"./chunk-HUOR4M2L.mjs";import{b as tu}from"./chunk-Z5IUK2QO.mjs";import{b as td,d as nd,e as rd,g as zo,h as qo}from"./chunk-GQZEX7LH.mjs";import"./chunk-TLX45X5U.mjs";import"./chunk-5GBO4KD5.mjs";import{Jb as Lu,Kb as Fu,hb as Or,kb as xu}from"./chunk-E5FSPXYH.mjs";import"./chunk-IQ5UKRHU.mjs";import{b as Be,c as Cu}from"./chunk-VT6P3X6R.mjs";import"./chunk-ALWVNR34.mjs";import{b as kt,c as $u}from"./chunk-QHE2RUWX.mjs";import{i as su}from"./chunk-6FARZYMJ.mjs";import"./chunk-ON7Y63FK.mjs";import"./chunk-7KHA5UIQ.mjs";import{a as To,i as lu}from"./chunk-YTOTMJTY.mjs";import"./chunk-WJGK6VGU.mjs";import"./chunk-3L6DVNCR.mjs";import"./chunk-54V4FVEY.mjs";import"./chunk-XCA5AONB.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-TZXYVMZC.mjs";import{b as Mu}from"./chunk-TMIV3IWH.mjs";import{$ as cu,Aa as uu,Za as du}from"./chunk-CJAWKLAL.mjs";import"./chunk-PE7CHD2W.mjs";import"./chunk-VKREON6Q.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-VFKG2G37.mjs";import"./chunk-CL75DEMQ.mjs";import"./chunk-BOGNK4LV.mjs";import{c as nu,e as ru,f as Pe,k as Ge}from"./chunk-DDNCJVZ2.mjs";import{la as $r,n as Au,ta as Ou,ya as ju}from"./chunk-C5AUNG6T.mjs";import"./chunk-3I6FXFCN.mjs";import"./chunk-7O6EFNQS.mjs";import{M as fu}from"./chunk-3LRFPGYZ.mjs";import"./chunk-34SMB5PA.mjs";import"./chunk-GB6W4Q56.mjs";import"./chunk-AVY742BJ.mjs";import"./chunk-BWWQXU2B.mjs";import{h as pu,l as hu,n as mu,p as xo}from"./chunk-KWUS7UAV.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-HZCS6EED.mjs";import"./chunk-NV5QA2HY.mjs";import"./chunk-EGL3I3IX.mjs";import"./chunk-CSMGP53U.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-YDXMTWAT.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-35B73566.mjs";import{f as bu}from"./chunk-FQGHL7GR.mjs";import"./chunk-PVZ72OOQ.mjs";import"./chunk-QIRO4HTE.mjs";import"./chunk-TYUYPFDJ.mjs";import"./chunk-TICZXC53.mjs";import"./chunk-DLSU66MY.mjs";import"./chunk-ATQML7ZK.mjs";import"./chunk-H6BHWAX7.mjs";import{I as gu,L as yu,M as wu,k as pe}from"./chunk-4CSBZZAL.mjs";import{a as B,b as De,c as ze}from"./chunk-AL4C3GFT.mjs";import{d as au}from"./chunk-GP5J3DGS.mjs";import"./chunk-5LFSFYFJ.mjs";import{a as No,b as Zc,c as eu}from"./chunk-WQCXOZEJ.mjs";import"./chunk-OT2NHL2V.mjs";import"./chunk-ZVU7MD2S.mjs";import{Cc as vt,P as vu,U as ku,bb as Sr,dc as Su,mb as Eu,nb as Ru}from"./chunk-OLCS7JCT.mjs";import"./chunk-TQ6HEJ73.mjs";import{a as Er,b as Rr,d as Qc}from"./chunk-65AMXOQU.mjs";import"./chunk-6HHSAPIM.mjs";import"./chunk-K5PUMHZU.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-EUIALBMX.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-Q7TLC3I2.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-ATBQIE2V.mjs";import"./chunk-UCUFLFNK.mjs";import"./chunk-MS4FJDFD.mjs";import"./chunk-4XROG5CT.mjs";import{b as Xc,f as qe,g as fn,h as Tu}from"./chunk-LCDPCUXS.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-DAUX63UB.mjs";import"./chunk-SZOJ7BEJ.mjs";import{f as ou,h as iu}from"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-22L43JMK.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-ICIYL45C.mjs";import"./chunk-3KJCSYXY.mjs";import"./chunk-HDDJ3CVN.mjs";import{Ab as Vc,Bb as Wc,Db as Hc,Eb as br,Ed as Gc,Fb as Yc,Ga as Co,Gb as Jc,Hb as ln,Jb as Do,Ua as yt,e as wr,fb as qc,hb as Bc,ic as Po,j as _c,pb as Uc,rb as Kc,ub as vr,wb as wt,x as zc,xb as kr,yb as dn,zb as Io}from"./chunk-J347SPU6.mjs";import{A as p}from"./chunk-WZQEK4WT.mjs";import{a as yr,b as C,d as zy}from"./chunk-NTOVCTRS.mjs";var z=C(ie=>{"use strict";var Si=Symbol.for("yaml.alias"),Op=Symbol.for("yaml.document"),us=Symbol.for("yaml.map"),jp=Symbol.for("yaml.pair"),$i=Symbol.for("yaml.scalar"),ds=Symbol.for("yaml.seq"),We=Symbol.for("yaml.node.type"),Kv=e=>!!e&&typeof e=="object"&&e[We]===Si,Vv=e=>!!e&&typeof e=="object"&&e[We]===Op,Wv=e=>!!e&&typeof e=="object"&&e[We]===us,Hv=e=>!!e&&typeof e=="object"&&e[We]===jp,Cp=e=>!!e&&typeof e=="object"&&e[We]===$i,Yv=e=>!!e&&typeof e=="object"&&e[We]===ds;function Ip(e){if(e&&typeof e=="object")switch(e[We]){case us:case ds:return!0}return!1}function Jv(e){if(e&&typeof e=="object")switch(e[We]){case Si:case us:case $i:case ds:return!0}return!1}var Gv=e=>(Cp(e)||Ip(e))&&!!e.anchor;ie.ALIAS=Si;ie.DOC=Op;ie.MAP=us;ie.NODE_TYPE=We;ie.PAIR=jp;ie.SCALAR=$i;ie.SEQ=ds;ie.hasAnchor=Gv;ie.isAlias=Kv;ie.isCollection=Ip;ie.isDocument=Vv;ie.isMap=Wv;ie.isNode=Jv;ie.isPair=Hv;ie.isScalar=Cp;ie.isSeq=Yv});var Pn=C(Ai=>{"use strict";var ee=z(),me=Symbol("break visit"),Dp=Symbol("skip children"),Fe=Symbol("remove node");function ls(e,t){let n=Pp(t);ee.isDocument(e)?Jt(null,e.contents,n,Object.freeze([e]))===Fe&&(e.contents=null):Jt(null,e,n,Object.freeze([]))}ls.BREAK=me;ls.SKIP=Dp;ls.REMOVE=Fe;function Jt(e,t,n,r){let s=Np(e,t,n,r);if(ee.isNode(s)||ee.isPair(s))return Tp(e,r,s),Jt(e,s,n,r);if(typeof s!="symbol"){if(ee.isCollection(t)){r=Object.freeze(r.concat(t));for(let o=0;o<t.items.length;++o){let i=Jt(o,t.items[o],n,r);if(typeof i=="number")o=i-1;else{if(i===me)return me;i===Fe&&(t.items.splice(o,1),o-=1)}}}else if(ee.isPair(t)){r=Object.freeze(r.concat(t));let o=Jt("key",t.key,n,r);if(o===me)return me;o===Fe&&(t.key=null);let i=Jt("value",t.value,n,r);if(i===me)return me;i===Fe&&(t.value=null)}}return s}async function fs(e,t){let n=Pp(t);ee.isDocument(e)?await Gt(null,e.contents,n,Object.freeze([e]))===Fe&&(e.contents=null):await Gt(null,e,n,Object.freeze([]))}fs.BREAK=me;fs.SKIP=Dp;fs.REMOVE=Fe;async function Gt(e,t,n,r){let s=await Np(e,t,n,r);if(ee.isNode(s)||ee.isPair(s))return Tp(e,r,s),Gt(e,s,n,r);if(typeof s!="symbol"){if(ee.isCollection(t)){r=Object.freeze(r.concat(t));for(let o=0;o<t.items.length;++o){let i=await Gt(o,t.items[o],n,r);if(typeof i=="number")o=i-1;else{if(i===me)return me;i===Fe&&(t.items.splice(o,1),o-=1)}}}else if(ee.isPair(t)){r=Object.freeze(r.concat(t));let o=await Gt("key",t.key,n,r);if(o===me)return me;o===Fe&&(t.key=null);let i=await Gt("value",t.value,n,r);if(i===me)return me;i===Fe&&(t.value=null)}}return s}function Pp(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 Np(e,t,n,r){if(typeof n=="function")return n(e,t,r);if(ee.isMap(t))return n.Map?.(e,t,r);if(ee.isSeq(t))return n.Seq?.(e,t,r);if(ee.isPair(t))return n.Pair?.(e,t,r);if(ee.isScalar(t))return n.Scalar?.(e,t,r);if(ee.isAlias(t))return n.Alias?.(e,t,r)}function Tp(e,t,n){let r=t[t.length-1];if(ee.isCollection(r))r.items[e]=n;else if(ee.isPair(r))e==="key"?r.key=n:r.value=n;else if(ee.isDocument(r))r.contents=n;else{let s=ee.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}Ai.visit=ls;Ai.visitAsync=fs});var Oi=C(Lp=>{"use strict";var xp=z(),Qv=Pn(),Xv={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Zv=e=>e.replace(/[!,[\]{}]/g,t=>Xv[t]),Nn=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[o,i]=r;return this.tags[o]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[o]=r;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let i=/^\d+\.\d+$/.test(o);return n(6,`Unsupported YAML version ${o}`,i),!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 i=t.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,s]=t.match(/^(.*!)([^!]*)$/s);s||n(`The ${t} tag has no suffix`);let o=this.tags[r];if(o)try{return o+decodeURIComponent(s)}catch(i){return n(String(i)),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+Zv(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&&xp.isNode(t.contents)){let o={};Qv.visit(t.contents,(i,a)=>{xp.isNode(a)&&a.tag&&(o[a.tag]=!0)}),s=Object.keys(o)}else s=[];for(let[o,i]of r)o==="!!"&&i==="tag:yaml.org,2002:"||(!t||s.some(a=>a.startsWith(i)))&&n.push(`%TAG ${o} ${i}`);return n.join(`
8
+ `)}};Nn.defaultYaml={explicit:!1,version:"1.2"};Nn.defaultTags={"!!":"tag:yaml.org,2002:"};Lp.Directives=Nn});var ps=C(Tn=>{"use strict";var Fp=z(),ek=Pn();function tk(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 Mp(e){let t=new Set;return ek.visit(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function _p(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function nk(e,t){let n=[],r=new Map,s=null;return{onAnchor:o=>{n.push(o),s??(s=Mp(e));let i=_p(t,s);return s.add(i),i},setAnchors:()=>{for(let o of n){let i=r.get(o);if(typeof i=="object"&&i.anchor&&(Fp.isScalar(i.node)||Fp.isCollection(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=o,a}}},sourceObjects:r}}Tn.anchorIsValid=tk;Tn.anchorNames=Mp;Tn.createNodeAnchors=nk;Tn.findNewAnchor=_p});var ji=C(zp=>{"use strict";function xn(e,t,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let s=0,o=r.length;s<o;++s){let i=r[s],a=xn(e,r,String(s),i);a===void 0?delete r[s]:a!==i&&(r[s]=a)}else if(r instanceof Map)for(let s of Array.from(r.keys())){let o=r.get(s),i=xn(e,r,s,o);i===void 0?r.delete(s):i!==o&&r.set(s,i)}else if(r instanceof Set)for(let s of Array.from(r)){let o=xn(e,r,s,s);o===void 0?r.delete(s):o!==s&&(r.delete(s),r.add(o))}else for(let[s,o]of Object.entries(r)){let i=xn(e,r,s,o);i===void 0?delete r[s]:i!==o&&(r[s]=i)}return e.call(t,n,r)}zp.applyReviver=xn});var st=C(Bp=>{"use strict";var rk=z();function qp(e,t,n){if(Array.isArray(e))return e.map((r,s)=>qp(r,String(s),n));if(e&&typeof e.toJSON=="function"){if(!n||!rk.hasAnchor(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=o=>{r.res=o,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}Bp.toJS=qp});var hs=C(Kp=>{"use strict";var sk=ji(),Up=z(),ok=st(),Ci=class{constructor(t){Object.defineProperty(this,Up.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:o}={}){if(!Up.isDocument(t))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=ok.toJS(this,"",i);if(typeof s=="function")for(let{count:c,res:u}of i.anchors.values())s(u,c);return typeof o=="function"?sk.applyReviver(o,{"":a},"",a):a}};Kp.NodeBase=Ci});var Ln=C(Vp=>{"use strict";var ik=ps(),ak=Pn(),Qt=z(),ck=hs(),uk=st(),Ii=class extends ck.NodeBase{constructor(t){super(Qt.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=[],ak.visit(t,{Node:(o,i)=>{(Qt.isAlias(i)||Qt.hasAnchor(i))&&r.push(i)}}),n&&(n.aliasResolveCache=r));let s;for(let o of r){if(o===this)break;o.anchor===this.source&&(s=o)}if(s&&n){let{anchors:o,doc:i,maxAliasCount:a}=n,c=o.get(s);if(c||(uk.toJS(s,null,n),c=o.get(s)),c?.res===void 0){let u="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(u)}if(a>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=ms(i,s,o)),c.count*c.aliasCount>a)){let u="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(u)}}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(ik.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(t.implicitKey)return`${s} `}return s}};function ms(e,t,n){if(Qt.isAlias(t)){let r=t.resolve(e),s=n&&r&&n.get(r);return s?s.count*s.aliasCount:0}else if(Qt.isCollection(t)){let r=0;for(let s of t.items){let o=ms(e,s,n);o>r&&(r=o)}return r}else if(Qt.isPair(t)){let r=ms(e,t.key,n),s=ms(e,t.value,n);return Math.max(r,s)}return 1}Vp.Alias=Ii});var Q=C(Di=>{"use strict";var dk=z(),lk=hs(),fk=st(),pk=e=>!e||typeof e!="function"&&typeof e!="object",ot=class extends lk.NodeBase{constructor(t){super(dk.SCALAR),this.value=t}toJSON(t,n){return n?.keep?this.value:fk.toJS(this.value,t,n)}toString(){return String(this.value)}};ot.BLOCK_FOLDED="BLOCK_FOLDED";ot.BLOCK_LITERAL="BLOCK_LITERAL";ot.PLAIN="PLAIN";ot.QUOTE_DOUBLE="QUOTE_DOUBLE";ot.QUOTE_SINGLE="QUOTE_SINGLE";Di.Scalar=ot;Di.isScalarValue=pk});var Fn=C(Hp=>{"use strict";var hk=Ln(),Ot=z(),Wp=Q(),mk="tag:yaml.org,2002:";function gk(e,t,n){if(t){let r=n.filter(o=>o.tag===t),s=r.find(o=>!o.format)??r[0];if(!s)throw new Error(`Tag ${t} not found`);return s}return n.find(r=>r.identify?.(e)&&!r.format)}function yk(e,t,n){if(Ot.isDocument(e)&&(e=e.contents),Ot.isNode(e))return e;if(Ot.isPair(e)){let d=n.schema[Ot.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:o,schema:i,sourceObjects:a}=n,c;if(r&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=s(e)),new hk.Alias(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=mk+t.slice(2));let u=gk(e,t,i.tags);if(!u){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Wp.Scalar(e);return c&&(c.node=d),d}u=e instanceof Map?i[Ot.MAP]:Symbol.iterator in Object(e)?i[Ot.SEQ]:i[Ot.MAP]}o&&(o(u),delete n.onTagObj);let f=u?.createNode?u.createNode(n.schema,e,n):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(n.schema,e,n):new Wp.Scalar(e);return t?f.tag=t:u.default||(f.tag=u.tag),c&&(c.node=f),f}Hp.createNode=yk});var ys=C(gs=>{"use strict";var wk=Fn(),Me=z(),vk=hs();function Pi(e,t,n){let r=n;for(let s=t.length-1;s>=0;--s){let o=t[s];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let i=[];i[o]=r,r=i}else r=new Map([[o,r]])}return wk.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 Yp=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Ni=class extends vk.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=>Me.isNode(r)||Me.isPair(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(Yp(t))this.add(n);else{let[r,...s]=t,o=this.get(r,!0);if(Me.isCollection(o))o.addIn(s,n);else if(o===void 0&&this.schema)this.set(r,Pi(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(Me.isCollection(s))return s.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(t,n){let[r,...s]=t,o=this.get(r,!0);return s.length===0?!n&&Me.isScalar(o)?o.value:o:Me.isCollection(o)?o.getIn(s,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!Me.isPair(n))return!1;let r=n.value;return r==null||t&&Me.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 Me.isCollection(s)?s.hasIn(r):!1}setIn(t,n){let[r,...s]=t;if(s.length===0)this.set(r,n);else{let o=this.get(r,!0);if(Me.isCollection(o))o.setIn(s,n);else if(o===void 0&&this.schema)this.set(r,Pi(this.schema,s,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`)}}};gs.Collection=Ni;gs.collectionFromPath=Pi;gs.isEmptyPath=Yp});var Mn=C(ws=>{"use strict";var kk=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ti(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var bk=(e,t,n)=>e.endsWith(`
9
+ `)?Ti(n,t):n.includes(`
10
10
  `)?`
11
- `+Ni(n,t):(e.endsWith(" ")?"":" ")+n;ys.indentComment=Ni;ys.lineComment=yk;ys.stringifyComment=gk});var Wp=C(Mn=>{"use strict";var wk="flow",Ti="block",ws="quoted";function vk(e,t,n="flow",{indentAtStart:r,lineWidth:s=80,minContentWidth:o=20,onFold:i,onOverflow:a}={}){if(!s||s<0)return e;s<o&&(o=0);let c=Math.max(1+o,1+s-t.length);if(e.length<=c)return e;let u=[],d={},l=s-t.length;typeof r=="number"&&(r>s-Math.max(2,o)?u.push(0):l=s-r);let f,h,m=!1,g=-1,w=-1,y=-1;n===Ti&&(g=Vp(e,g,t.length),g!==-1&&(l=g+c));for(let b;b=e[g+=1];){if(n===ws&&b==="\\"){switch(w=g,e[g+1]){case"x":g+=3;break;case"u":g+=5;break;case"U":g+=9;break;default:g+=1}y=g}if(b===`
12
- `)n===Ti&&(g=Vp(e,g,t.length)),l=g+t.length+c,f=void 0;else{if(b===" "&&h&&h!==" "&&h!==`
11
+ `+Ti(n,t):(e.endsWith(" ")?"":" ")+n;ws.indentComment=Ti;ws.lineComment=bk;ws.stringifyComment=kk});var Gp=C(_n=>{"use strict";var Ek="flow",xi="block",vs="quoted";function Rk(e,t,n="flow",{indentAtStart:r,lineWidth:s=80,minContentWidth:o=20,onFold:i,onOverflow:a}={}){if(!s||s<0)return e;s<o&&(o=0);let c=Math.max(1+o,1+s-t.length);if(e.length<=c)return e;let u=[],f={},d=s-t.length;typeof r=="number"&&(r>s-Math.max(2,o)?u.push(0):d=s-r);let l,h,m=!1,g=-1,w=-1,y=-1;n===xi&&(g=Jp(e,g,t.length),g!==-1&&(d=g+c));for(let b;b=e[g+=1];){if(n===vs&&b==="\\"){switch(w=g,e[g+1]){case"x":g+=3;break;case"u":g+=5;break;case"U":g+=9;break;default:g+=1}y=g}if(b===`
12
+ `)n===xi&&(g=Jp(e,g,t.length)),d=g+t.length+c,l=void 0;else{if(b===" "&&h&&h!==" "&&h!==`
13
13
  `&&h!==" "){let k=e[g+1];k&&k!==" "&&k!==`
14
- `&&k!==" "&&(f=g)}if(g>=l)if(f)u.push(f),l=f+c,f=void 0;else if(n===ws){for(;h===" "||h===" ";)h=b,b=e[g+=1],m=!0;let k=g>y+1?g-2:w-1;if(d[k])return e;u.push(k),d[k]=!0,l=k+c,f=void 0}else m=!0}h=b}if(m&&a&&a(),u.length===0)return e;i&&i();let v=e.slice(0,u[0]);for(let b=0;b<u.length;++b){let k=u[b],E=u[b+1]||e.length;k===0?v=`
15
- ${t}${e.slice(0,E)}`:(n===ws&&d[k]&&(v+=`${e[k]}\\`),v+=`
16
- ${t}${e.slice(k+1,E)}`)}return v}function Vp(e,t,n){let r=t,s=t+1,o=e[s];for(;o===" "||o===" ";)if(t<s+n)o=e[++t];else{do o=e[++t];while(o&&o!==`
17
- `);r=t,s=t+1,o=e[s]}return r}Mn.FOLD_BLOCK=Ti;Mn.FOLD_FLOW=wk;Mn.FOLD_QUOTED=ws;Mn.foldFlowLines=vk});var zn=C(Hp=>{"use strict";var Se=Q(),ot=Wp(),ks=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),bs=e=>/^(%|---|\.\.\.)/m.test(e);function kk(e,t,n){if(!t||t<0)return!1;let r=t-n,s=e.length;if(s<=r)return!1;for(let o=0,i=0;o<s;++o)if(e[o]===`
18
- `){if(o-i>r)return!0;if(i=o+1,s-i<=r)return!1}return!0}function _n(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,s=t.options.doubleQuotedMinMultiLineLength,o=t.indent||(bs(e)?" ":""),i="",a=0;for(let c=0,u=n[c];u;u=n[++c])if(u===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(i+=n.slice(a,c)+"\\ ",c+=1,a=c,u="\\"),u==="\\")switch(n[c+1]){case"u":{i+=n.slice(a,c);let d=n.substr(c+2,4);switch(d){case"0000":i+="\\0";break;case"0007":i+="\\a";break;case"000b":i+="\\v";break;case"001b":i+="\\e";break;case"0085":i+="\\N";break;case"00a0":i+="\\_";break;case"2028":i+="\\L";break;case"2029":i+="\\P";break;default:d.substr(0,2)==="00"?i+="\\x"+d.substr(2):i+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(r||n[c+2]==='"'||n.length<s)c+=1;else{for(i+=n.slice(a,c)+`
14
+ `&&k!==" "&&(l=g)}if(g>=d)if(l)u.push(l),d=l+c,l=void 0;else if(n===vs){for(;h===" "||h===" ";)h=b,b=e[g+=1],m=!0;let k=g>y+1?g-2:w-1;if(f[k])return e;u.push(k),f[k]=!0,d=k+c,l=void 0}else m=!0}h=b}if(m&&a&&a(),u.length===0)return e;i&&i();let v=e.slice(0,u[0]);for(let b=0;b<u.length;++b){let k=u[b],E=u[b+1]||e.length;k===0?v=`
15
+ ${t}${e.slice(0,E)}`:(n===vs&&f[k]&&(v+=`${e[k]}\\`),v+=`
16
+ ${t}${e.slice(k+1,E)}`)}return v}function Jp(e,t,n){let r=t,s=t+1,o=e[s];for(;o===" "||o===" ";)if(t<s+n)o=e[++t];else{do o=e[++t];while(o&&o!==`
17
+ `);r=t,s=t+1,o=e[s]}return r}_n.FOLD_BLOCK=xi;_n.FOLD_FLOW=Ek;_n.FOLD_QUOTED=vs;_n.foldFlowLines=Rk});var qn=C(Qp=>{"use strict";var Se=Q(),it=Gp(),bs=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Es=e=>/^(%|---|\.\.\.)/m.test(e);function Sk(e,t,n){if(!t||t<0)return!1;let r=t-n,s=e.length;if(s<=r)return!1;for(let o=0,i=0;o<s;++o)if(e[o]===`
18
+ `){if(o-i>r)return!0;if(i=o+1,s-i<=r)return!1}return!0}function zn(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,s=t.options.doubleQuotedMinMultiLineLength,o=t.indent||(Es(e)?" ":""),i="",a=0;for(let c=0,u=n[c];u;u=n[++c])if(u===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(i+=n.slice(a,c)+"\\ ",c+=1,a=c,u="\\"),u==="\\")switch(n[c+1]){case"u":{i+=n.slice(a,c);let f=n.substr(c+2,4);switch(f){case"0000":i+="\\0";break;case"0007":i+="\\a";break;case"000b":i+="\\v";break;case"001b":i+="\\e";break;case"0085":i+="\\N";break;case"00a0":i+="\\_";break;case"2028":i+="\\L";break;case"2029":i+="\\P";break;default:f.substr(0,2)==="00"?i+="\\x"+f.substr(2):i+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(r||n[c+2]==='"'||n.length<s)c+=1;else{for(i+=n.slice(a,c)+`
19
19
 
20
20
  `;n[c+2]==="\\"&&n[c+3]==="n"&&n[c+4]!=='"';)i+=`
21
- `,c+=2;i+=o,n[c+2]===" "&&(i+="\\"),c+=1,a=c+1}break;default:c+=1}return i=a?i+n.slice(a):n,r?i:ot.foldFlowLines(i,o,ot.FOLD_QUOTED,ks(t,!1))}function xi(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
22
- `)||/[ \t]\n|\n[ \t]/.test(e))return _n(e,t);let n=t.indent||(bs(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
23
- ${n}`)+"'";return t.implicitKey?r:ot.foldFlowLines(r,n,ot.FOLD_FLOW,ks(t,!1))}function Qt(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=_n;else{let s=e.includes('"'),o=e.includes("'");s&&!o?r=xi:o&&!s?r=_n:r=n?xi:_n}return r(e,t)}var Li;try{Li=new RegExp(`(^|(?<!
21
+ `,c+=2;i+=o,n[c+2]===" "&&(i+="\\"),c+=1,a=c+1}break;default:c+=1}return i=a?i+n.slice(a):n,r?i:it.foldFlowLines(i,o,it.FOLD_QUOTED,bs(t,!1))}function Li(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
22
+ `)||/[ \t]\n|\n[ \t]/.test(e))return zn(e,t);let n=t.indent||(Es(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
23
+ ${n}`)+"'";return t.implicitKey?r:it.foldFlowLines(r,n,it.FOLD_FLOW,bs(t,!1))}function Xt(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=zn;else{let s=e.includes('"'),o=e.includes("'");s&&!o?r=Li:o&&!s?r=zn:r=n?Li:zn}return r(e,t)}var Fi;try{Fi=new RegExp(`(^|(?<!
24
24
  ))
25
25
  +(?!
26
- |$)`,"g")}catch{Li=/\n+(?!\n|$)/g}function vs({comment:e,type:t,value:n},r,s,o){let{blockQuote:i,commentString:a,lineWidth:c}=r.options;if(!i||/\n[\t ]+$/.test(n))return Qt(n,r);let u=r.indent||(r.forceBlockIndent||bs(n)?" ":""),d=i==="literal"?!0:i==="folded"||t===Se.Scalar.BLOCK_FOLDED?!1:t===Se.Scalar.BLOCK_LITERAL?!0:!kk(n,c,u.length);if(!n)return d?`|
26
+ |$)`,"g")}catch{Fi=/\n+(?!\n|$)/g}function ks({comment:e,type:t,value:n},r,s,o){let{blockQuote:i,commentString:a,lineWidth:c}=r.options;if(!i||/\n[\t ]+$/.test(n))return Xt(n,r);let u=r.indent||(r.forceBlockIndent||Es(n)?" ":""),f=i==="literal"?!0:i==="folded"||t===Se.Scalar.BLOCK_FOLDED?!1:t===Se.Scalar.BLOCK_LITERAL?!0:!Sk(n,c,u.length);if(!n)return f?`|
27
27
  `:`>
28
- `;let l,f;for(f=n.length;f>0;--f){let E=n[f-1];if(E!==`
29
- `&&E!==" "&&E!==" ")break}let h=n.substring(f),m=h.indexOf(`
30
- `);m===-1?l="-":n===h||m!==h.length-1?(l="+",o&&o()):l="",h&&(n=n.slice(0,-h.length),h[h.length-1]===`
31
- `&&(h=h.slice(0,-1)),h=h.replace(Li,`$&${u}`));let g=!1,w,y=-1;for(w=0;w<n.length;++w){let E=n[w];if(E===" ")g=!0;else if(E===`
32
- `)y=w;else break}let v=n.substring(0,y<w?y+1:w);v&&(n=n.substring(v.length),v=v.replace(/\n+/g,`$&${u}`));let k=(g?u?"2":"1":"")+l;if(e&&(k+=" "+a(e.replace(/ ?[\r\n]+/g," ")),s&&s()),!d){let E=n.replace(/\n+/g,`
33
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`),S=!1,$=ks(r,!0);i!=="folded"&&t!==Se.Scalar.BLOCK_FOLDED&&($.onOverflow=()=>{S=!0});let j=ot.foldFlowLines(`${v}${E}${h}`,u,ot.FOLD_BLOCK,$);if(!S)return`>${k}
28
+ `;let d,l;for(l=n.length;l>0;--l){let E=n[l-1];if(E!==`
29
+ `&&E!==" "&&E!==" ")break}let h=n.substring(l),m=h.indexOf(`
30
+ `);m===-1?d="-":n===h||m!==h.length-1?(d="+",o&&o()):d="",h&&(n=n.slice(0,-h.length),h[h.length-1]===`
31
+ `&&(h=h.slice(0,-1)),h=h.replace(Fi,`$&${u}`));let g=!1,w,y=-1;for(w=0;w<n.length;++w){let E=n[w];if(E===" ")g=!0;else if(E===`
32
+ `)y=w;else break}let v=n.substring(0,y<w?y+1:w);v&&(n=n.substring(v.length),v=v.replace(/\n+/g,`$&${u}`));let k=(g?u?"2":"1":"")+d;if(e&&(k+=" "+a(e.replace(/ ?[\r\n]+/g," ")),s&&s()),!f){let E=n.replace(/\n+/g,`
33
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`),S=!1,$=bs(r,!0);i!=="folded"&&t!==Se.Scalar.BLOCK_FOLDED&&($.onOverflow=()=>{S=!0});let j=it.foldFlowLines(`${v}${E}${h}`,u,it.FOLD_BLOCK,$);if(!S)return`>${k}
34
34
  ${u}${j}`}return n=n.replace(/\n+/g,`$&${u}`),`|${k}
35
- ${u}${v}${n}${h}`}function bk(e,t,n,r){let{type:s,value:o}=e,{actualString:i,implicitKey:a,indent:c,indentStep:u,inFlow:d}=t;if(a&&o.includes(`
36
- `)||d&&/[[\]{},]/.test(o))return Qt(o,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return a||d||!o.includes(`
37
- `)?Qt(o,t):vs(e,t,n,r);if(!a&&!d&&s!==Se.Scalar.PLAIN&&o.includes(`
38
- `))return vs(e,t,n,r);if(bs(o)){if(c==="")return t.forceBlockIndent=!0,vs(e,t,n,r);if(a&&c===u)return Qt(o,t)}let l=o.replace(/\n+/g,`$&
39
- ${c}`);if(i){let f=g=>g.default&&g.tag!=="tag:yaml.org,2002:str"&&g.test?.test(l),{compat:h,tags:m}=t.doc.schema;if(m.some(f)||h?.some(f))return Qt(o,t)}return a?l:ot.foldFlowLines(l,c,ot.FOLD_FLOW,ks(t,!1))}function Ek(e,t,n,r){let{implicitKey:s,inFlow:o}=t,i=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;a!==Se.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=Se.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case Se.Scalar.BLOCK_FOLDED:case Se.Scalar.BLOCK_LITERAL:return s||o?Qt(i.value,t):vs(i,t,n,r);case Se.Scalar.QUOTE_DOUBLE:return _n(i.value,t);case Se.Scalar.QUOTE_SINGLE:return xi(i.value,t);case Se.Scalar.PLAIN:return bk(i,t,n,r);default:return null}},u=c(a);if(u===null){let{defaultKeyType:d,defaultStringType:l}=t.options,f=s&&d||l;if(u=c(f),u===null)throw new Error(`Unsupported default string type ${f}`)}return u}Hp.stringifyString=Ek});var qn=C(Fi=>{"use strict";var Rk=fs(),it=z(),Sk=Fn(),$k=zn();function Ak(e,t){let n=Object.assign({blockQuote:!0,commentString:Sk.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 Ok(e,t){if(t.tag){let s=e.filter(o=>o.tag===t.tag);if(s.length>0)return s.find(o=>o.format===t.format)??s[0]}let n,r;if(it.isScalar(t)){r=t.value;let s=e.filter(o=>o.identify?.(r));if(s.length>1){let o=s.filter(i=>i.test);o.length>0&&(s=o)}n=s.find(o=>o.format===t.format)??s.find(o=>!o.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 jk(e,t,{anchors:n,doc:r}){if(!r.directives)return"";let s=[],o=(it.isScalar(e)||it.isCollection(e))&&e.anchor;o&&Rk.anchorIsValid(o)&&(n.add(o),s.push(`&${o}`));let i=e.tag??(t.default?null:t.tag);return i&&s.push(r.directives.tagString(i)),s.join(" ")}function Ck(e,t,n,r){if(it.isPair(e))return e.toString(t,n,r);if(it.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,o=it.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>s=c});s??(s=Ok(t.doc.schema.tags,o));let i=jk(o,s,t);i.length>0&&(t.indentAtStart=(t.indentAtStart??0)+i.length+1);let a=typeof s.stringify=="function"?s.stringify(o,t,n,r):it.isScalar(o)?$k.stringifyString(o,t,n,r):o.toString(t,n,r);return i?it.isScalar(o)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}
40
- ${t.indent}${a}`:a}Fi.createStringifyContext=Ak;Fi.stringify=Ck});var Qp=C(Gp=>{"use strict";var Ve=z(),Yp=Q(),Jp=qn(),Bn=Fn();function Ik({key:e,value:t},n,r,s){let{allNullValues:o,doc:i,indent:a,indentStep:c,options:{commentString:u,indentSeq:d,simpleKeys:l}}=n,f=Ve.isNode(e)&&e.comment||null;if(l){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ve.isCollection(e)||!Ve.isNode(e)&&typeof e=="object"){let $="With simple keys, collection cannot be used as a key value";throw new Error($)}}let h=!l&&(!e||f&&t==null&&!n.inFlow||Ve.isCollection(e)||(Ve.isScalar(e)?e.type===Yp.Scalar.BLOCK_FOLDED||e.type===Yp.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(l||!o),indent:a+c});let m=!1,g=!1,w=Jp.stringify(e,n,()=>m=!0,()=>g=!0);if(!h&&!n.inFlow&&w.length>1024){if(l)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(o||t==null)return m&&r&&r(),w===""?"?":h?`? ${w}`:w}else if(o&&!l||t==null&&h)return w=`? ${w}`,f&&!m?w+=Bn.lineComment(w,n.indent,u(f)):g&&s&&s(),w;m&&(f=null),h?(f&&(w+=Bn.lineComment(w,n.indent,u(f))),w=`? ${w}
41
- ${a}:`):(w=`${w}:`,f&&(w+=Bn.lineComment(w,n.indent,u(f))));let y,v,b;Ve.isNode(t)?(y=!!t.spaceBefore,v=t.commentBefore,b=t.comment):(y=!1,v=null,b=null,t&&typeof t=="object"&&(t=i.createNode(t))),n.implicitKey=!1,!h&&!f&&Ve.isScalar(t)&&(n.indentAtStart=w.length+1),g=!1,!d&&c.length>=2&&!n.inFlow&&!h&&Ve.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let k=!1,E=Jp.stringify(t,n,()=>k=!0,()=>g=!0),S=" ";if(f||y||v){if(S=y?`
35
+ ${u}${v}${n}${h}`}function $k(e,t,n,r){let{type:s,value:o}=e,{actualString:i,implicitKey:a,indent:c,indentStep:u,inFlow:f}=t;if(a&&o.includes(`
36
+ `)||f&&/[[\]{},]/.test(o))return Xt(o,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return a||f||!o.includes(`
37
+ `)?Xt(o,t):ks(e,t,n,r);if(!a&&!f&&s!==Se.Scalar.PLAIN&&o.includes(`
38
+ `))return ks(e,t,n,r);if(Es(o)){if(c==="")return t.forceBlockIndent=!0,ks(e,t,n,r);if(a&&c===u)return Xt(o,t)}let d=o.replace(/\n+/g,`$&
39
+ ${c}`);if(i){let l=g=>g.default&&g.tag!=="tag:yaml.org,2002:str"&&g.test?.test(d),{compat:h,tags:m}=t.doc.schema;if(m.some(l)||h?.some(l))return Xt(o,t)}return a?d:it.foldFlowLines(d,c,it.FOLD_FLOW,bs(t,!1))}function Ak(e,t,n,r){let{implicitKey:s,inFlow:o}=t,i=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;a!==Se.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=Se.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case Se.Scalar.BLOCK_FOLDED:case Se.Scalar.BLOCK_LITERAL:return s||o?Xt(i.value,t):ks(i,t,n,r);case Se.Scalar.QUOTE_DOUBLE:return zn(i.value,t);case Se.Scalar.QUOTE_SINGLE:return Li(i.value,t);case Se.Scalar.PLAIN:return $k(i,t,n,r);default:return null}},u=c(a);if(u===null){let{defaultKeyType:f,defaultStringType:d}=t.options,l=s&&f||d;if(u=c(l),u===null)throw new Error(`Unsupported default string type ${l}`)}return u}Qp.stringifyString=Ak});var Bn=C(Mi=>{"use strict";var Ok=ps(),at=z(),jk=Mn(),Ck=qn();function Ik(e,t){let n=Object.assign({blockQuote:!0,commentString:jk.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 Dk(e,t){if(t.tag){let s=e.filter(o=>o.tag===t.tag);if(s.length>0)return s.find(o=>o.format===t.format)??s[0]}let n,r;if(at.isScalar(t)){r=t.value;let s=e.filter(o=>o.identify?.(r));if(s.length>1){let o=s.filter(i=>i.test);o.length>0&&(s=o)}n=s.find(o=>o.format===t.format)??s.find(o=>!o.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 Pk(e,t,{anchors:n,doc:r}){if(!r.directives)return"";let s=[],o=(at.isScalar(e)||at.isCollection(e))&&e.anchor;o&&Ok.anchorIsValid(o)&&(n.add(o),s.push(`&${o}`));let i=e.tag??(t.default?null:t.tag);return i&&s.push(r.directives.tagString(i)),s.join(" ")}function Nk(e,t,n,r){if(at.isPair(e))return e.toString(t,n,r);if(at.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,o=at.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>s=c});s??(s=Dk(t.doc.schema.tags,o));let i=Pk(o,s,t);i.length>0&&(t.indentAtStart=(t.indentAtStart??0)+i.length+1);let a=typeof s.stringify=="function"?s.stringify(o,t,n,r):at.isScalar(o)?Ck.stringifyString(o,t,n,r):o.toString(t,n,r);return i?at.isScalar(o)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}
40
+ ${t.indent}${a}`:a}Mi.createStringifyContext=Ik;Mi.stringify=Nk});var th=C(eh=>{"use strict";var He=z(),Xp=Q(),Zp=Bn(),Un=Mn();function Tk({key:e,value:t},n,r,s){let{allNullValues:o,doc:i,indent:a,indentStep:c,options:{commentString:u,indentSeq:f,simpleKeys:d}}=n,l=He.isNode(e)&&e.comment||null;if(d){if(l)throw new Error("With simple keys, key nodes cannot have comments");if(He.isCollection(e)||!He.isNode(e)&&typeof e=="object"){let $="With simple keys, collection cannot be used as a key value";throw new Error($)}}let h=!d&&(!e||l&&t==null&&!n.inFlow||He.isCollection(e)||(He.isScalar(e)?e.type===Xp.Scalar.BLOCK_FOLDED||e.type===Xp.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(d||!o),indent:a+c});let m=!1,g=!1,w=Zp.stringify(e,n,()=>m=!0,()=>g=!0);if(!h&&!n.inFlow&&w.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(o||t==null)return m&&r&&r(),w===""?"?":h?`? ${w}`:w}else if(o&&!d||t==null&&h)return w=`? ${w}`,l&&!m?w+=Un.lineComment(w,n.indent,u(l)):g&&s&&s(),w;m&&(l=null),h?(l&&(w+=Un.lineComment(w,n.indent,u(l))),w=`? ${w}
41
+ ${a}:`):(w=`${w}:`,l&&(w+=Un.lineComment(w,n.indent,u(l))));let y,v,b;He.isNode(t)?(y=!!t.spaceBefore,v=t.commentBefore,b=t.comment):(y=!1,v=null,b=null,t&&typeof t=="object"&&(t=i.createNode(t))),n.implicitKey=!1,!h&&!l&&He.isScalar(t)&&(n.indentAtStart=w.length+1),g=!1,!f&&c.length>=2&&!n.inFlow&&!h&&He.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let k=!1,E=Zp.stringify(t,n,()=>k=!0,()=>g=!0),S=" ";if(l||y||v){if(S=y?`
42
42
  `:"",v){let $=u(v);S+=`
43
- ${Bn.indentComment($,n.indent)}`}E===""&&!n.inFlow?S===`
43
+ ${Un.indentComment($,n.indent)}`}E===""&&!n.inFlow?S===`
44
44
  `&&b&&(S=`
45
45
 
46
46
  `):S+=`
47
- ${n.indent}`}else if(!h&&Ve.isCollection(t)){let $=E[0],j=E.indexOf(`
47
+ ${n.indent}`}else if(!h&&He.isCollection(t)){let $=E[0],j=E.indexOf(`
48
48
  `),A=j!==-1,P=n.inFlow??t.flow??t.items.length===0;if(A||!P){let D=!1;if(A&&($==="&"||$==="!")){let x=E.indexOf(" ");$==="&"&&x!==-1&&x<j&&E[x+1]==="!"&&(x=E.indexOf(" ",x+1)),(x===-1||j<x)&&(D=!0)}D||(S=`
49
49
  ${n.indent}`)}}else(E===""||E[0]===`
50
- `)&&(S="");return w+=S+E,n.inFlow?k&&r&&r():b&&!k?w+=Bn.lineComment(w,n.indent,u(b)):g&&s&&s(),w}Gp.stringifyPair=Ik});var _i=C(Mi=>{"use strict";var Xp=gr("process");function Dk(e,...t){e==="debug"&&console.log(...t)}function Pk(e,t){(e==="debug"||e==="warn")&&(typeof Xp.emitWarning=="function"?Xp.emitWarning(t):console.warn(t))}Mi.debug=Dk;Mi.warn=Pk});var As=C($s=>{"use strict";var Ss=z(),Zp=Q(),Es="<<",Rs={identify:e=>e===Es||typeof e=="symbol"&&e.description===Es,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Zp.Scalar(Symbol(Es)),{addToJSMap:eh}),stringify:()=>Es},Nk=(e,t)=>(Rs.identify(t)||Ss.isScalar(t)&&(!t.type||t.type===Zp.Scalar.PLAIN)&&Rs.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===Rs.tag&&n.default);function eh(e,t,n){let r=th(e,n);if(Ss.isSeq(r))for(let s of r.items)zi(e,t,s);else if(Array.isArray(r))for(let s of r)zi(e,t,s);else zi(e,t,r)}function zi(e,t,n){let r=th(e,n);if(!Ss.isMap(r))throw new Error("Merge sources must be maps or map aliases");let s=r.toJSON(null,e,Map);for(let[o,i]of s)t instanceof Map?t.has(o)||t.set(o,i):t instanceof Set?t.add(o):Object.prototype.hasOwnProperty.call(t,o)||Object.defineProperty(t,o,{value:i,writable:!0,enumerable:!0,configurable:!0});return t}function th(e,t){return e&&Ss.isAlias(t)?t.resolve(e.doc,e):t}$s.addMergeToJSMap=eh;$s.isMergeKey=Nk;$s.merge=Rs});var Bi=C(sh=>{"use strict";var Tk=_i(),nh=As(),xk=qn(),rh=z(),qi=rt();function Lk(e,t,{key:n,value:r}){if(rh.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(nh.isMergeKey(e,n))nh.addMergeToJSMap(e,t,r);else{let s=qi.toJS(n,"",e);if(t instanceof Map)t.set(s,qi.toJS(r,s,e));else if(t instanceof Set)t.add(s);else{let o=Fk(n,s,e),i=qi.toJS(r,o,e);o in t?Object.defineProperty(t,o,{value:i,writable:!0,enumerable:!0,configurable:!0}):t[o]=i}}return t}function Fk(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(rh.isNode(e)&&n?.doc){let r=xk.createStringifyContext(n.doc,{});r.anchors=new Set;for(let o of n.anchors.keys())r.anchors.add(o.anchor);r.inFlow=!0,r.inStringifyKey=!0;let s=e.toString(r);if(!n.mapKeyWarned){let o=JSON.stringify(s);o.length>40&&(o=o.substring(0,36)+'..."'),Tk.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return s}return JSON.stringify(t)}sh.addPairToJSMap=Lk});var at=C(Ui=>{"use strict";var oh=Ln(),Mk=Qp(),_k=Bi(),Os=z();function zk(e,t,n){let r=oh.createNode(e,void 0,n),s=oh.createNode(t,void 0,n);return new js(r,s)}var js=class e{constructor(t,n=null){Object.defineProperty(this,Os.NODE_TYPE,{value:Os.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return Os.isNode(n)&&(n=n.clone(t)),Os.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return _k.addPairToJSMap(n,r,this)}toString(t,n,r){return t?.doc?Mk.stringifyPair(this,t,n,r):JSON.stringify(this)}};Ui.Pair=js;Ui.createPair=zk});var Ki=C(ah=>{"use strict";var Ot=z(),ih=qn(),Cs=Fn();function qk(e,t,n){return(t.inFlow??e.flow?Uk:Bk)(e,t,n)}function Bk({comment:e,items:t},n,{blockItemPrefix:r,flowChars:s,itemIndent:o,onChompKeep:i,onComment:a}){let{indent:c,options:{commentString:u}}=n,d=Object.assign({},n,{indent:o,type:null}),l=!1,f=[];for(let m=0;m<t.length;++m){let g=t[m],w=null;if(Ot.isNode(g))!l&&g.spaceBefore&&f.push(""),Is(n,f,g.commentBefore,l),g.comment&&(w=g.comment);else if(Ot.isPair(g)){let v=Ot.isNode(g.key)?g.key:null;v&&(!l&&v.spaceBefore&&f.push(""),Is(n,f,v.commentBefore,l))}l=!1;let y=ih.stringify(g,d,()=>w=null,()=>l=!0);w&&(y+=Cs.lineComment(y,o,u(w))),l&&w&&(l=!1),f.push(r+y)}let h;if(f.length===0)h=s.start+s.end;else{h=f[0];for(let m=1;m<f.length;++m){let g=f[m];h+=g?`
50
+ `)&&(S="");return w+=S+E,n.inFlow?k&&r&&r():b&&!k?w+=Un.lineComment(w,n.indent,u(b)):g&&s&&s(),w}eh.stringifyPair=Tk});var zi=C(_i=>{"use strict";var nh=yr("process");function xk(e,...t){e==="debug"&&console.log(...t)}function Lk(e,t){(e==="debug"||e==="warn")&&(typeof nh.emitWarning=="function"?nh.emitWarning(t):console.warn(t))}_i.debug=xk;_i.warn=Lk});var Os=C(As=>{"use strict";var $s=z(),rh=Q(),Rs="<<",Ss={identify:e=>e===Rs||typeof e=="symbol"&&e.description===Rs,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new rh.Scalar(Symbol(Rs)),{addToJSMap:sh}),stringify:()=>Rs},Fk=(e,t)=>(Ss.identify(t)||$s.isScalar(t)&&(!t.type||t.type===rh.Scalar.PLAIN)&&Ss.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===Ss.tag&&n.default);function sh(e,t,n){let r=oh(e,n);if($s.isSeq(r))for(let s of r.items)qi(e,t,s);else if(Array.isArray(r))for(let s of r)qi(e,t,s);else qi(e,t,r)}function qi(e,t,n){let r=oh(e,n);if(!$s.isMap(r))throw new Error("Merge sources must be maps or map aliases");let s=r.toJSON(null,e,Map);for(let[o,i]of s)t instanceof Map?t.has(o)||t.set(o,i):t instanceof Set?t.add(o):Object.prototype.hasOwnProperty.call(t,o)||Object.defineProperty(t,o,{value:i,writable:!0,enumerable:!0,configurable:!0});return t}function oh(e,t){return e&&$s.isAlias(t)?t.resolve(e.doc,e):t}As.addMergeToJSMap=sh;As.isMergeKey=Fk;As.merge=Ss});var Ui=C(ch=>{"use strict";var Mk=zi(),ih=Os(),_k=Bn(),ah=z(),Bi=st();function zk(e,t,{key:n,value:r}){if(ah.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(ih.isMergeKey(e,n))ih.addMergeToJSMap(e,t,r);else{let s=Bi.toJS(n,"",e);if(t instanceof Map)t.set(s,Bi.toJS(r,s,e));else if(t instanceof Set)t.add(s);else{let o=qk(n,s,e),i=Bi.toJS(r,o,e);o in t?Object.defineProperty(t,o,{value:i,writable:!0,enumerable:!0,configurable:!0}):t[o]=i}}return t}function qk(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(ah.isNode(e)&&n?.doc){let r=_k.createStringifyContext(n.doc,{});r.anchors=new Set;for(let o of n.anchors.keys())r.anchors.add(o.anchor);r.inFlow=!0,r.inStringifyKey=!0;let s=e.toString(r);if(!n.mapKeyWarned){let o=JSON.stringify(s);o.length>40&&(o=o.substring(0,36)+'..."'),Mk.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return s}return JSON.stringify(t)}ch.addPairToJSMap=zk});var ct=C(Ki=>{"use strict";var uh=Fn(),Bk=th(),Uk=Ui(),js=z();function Kk(e,t,n){let r=uh.createNode(e,void 0,n),s=uh.createNode(t,void 0,n);return new Cs(r,s)}var Cs=class e{constructor(t,n=null){Object.defineProperty(this,js.NODE_TYPE,{value:js.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return js.isNode(n)&&(n=n.clone(t)),js.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return Uk.addPairToJSMap(n,r,this)}toString(t,n,r){return t?.doc?Bk.stringifyPair(this,t,n,r):JSON.stringify(this)}};Ki.Pair=Cs;Ki.createPair=Kk});var Vi=C(lh=>{"use strict";var jt=z(),dh=Bn(),Is=Mn();function Vk(e,t,n){return(t.inFlow??e.flow?Hk:Wk)(e,t,n)}function Wk({comment:e,items:t},n,{blockItemPrefix:r,flowChars:s,itemIndent:o,onChompKeep:i,onComment:a}){let{indent:c,options:{commentString:u}}=n,f=Object.assign({},n,{indent:o,type:null}),d=!1,l=[];for(let m=0;m<t.length;++m){let g=t[m],w=null;if(jt.isNode(g))!d&&g.spaceBefore&&l.push(""),Ds(n,l,g.commentBefore,d),g.comment&&(w=g.comment);else if(jt.isPair(g)){let v=jt.isNode(g.key)?g.key:null;v&&(!d&&v.spaceBefore&&l.push(""),Ds(n,l,v.commentBefore,d))}d=!1;let y=dh.stringify(g,f,()=>w=null,()=>d=!0);w&&(y+=Is.lineComment(y,o,u(w))),d&&w&&(d=!1),l.push(r+y)}let h;if(l.length===0)h=s.start+s.end;else{h=l[0];for(let m=1;m<l.length;++m){let g=l[m];h+=g?`
51
51
  ${c}${g}`:`
52
52
  `}}return e?(h+=`
53
- `+Cs.indentComment(u(e),c),a&&a()):l&&i&&i(),h}function Uk({items:e},t,{flowChars:n,itemIndent:r}){let{indent:s,indentStep:o,flowCollectionPadding:i,options:{commentString:a}}=t;r+=o;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),u=!1,d=0,l=[];for(let m=0;m<e.length;++m){let g=e[m],w=null;if(Ot.isNode(g))g.spaceBefore&&l.push(""),Is(t,l,g.commentBefore,!1),g.comment&&(w=g.comment);else if(Ot.isPair(g)){let v=Ot.isNode(g.key)?g.key:null;v&&(v.spaceBefore&&l.push(""),Is(t,l,v.commentBefore,!1),v.comment&&(u=!0));let b=Ot.isNode(g.value)?g.value:null;b?(b.comment&&(w=b.comment),b.commentBefore&&(u=!0)):g.value==null&&v?.comment&&(w=v.comment)}w&&(u=!0);let y=ih.stringify(g,c,()=>w=null);u||(u=l.length>d||y.includes(`
54
- `)),m<e.length-1?y+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(u||(u=l.reduce((v,b)=>v+b.length+2,2)+(y.length+2)>t.options.lineWidth)),u&&(y+=",")),w&&(y+=Cs.lineComment(y,r,a(w))),l.push(y),d=l.length}let{start:f,end:h}=n;if(l.length===0)return f+h;if(!u){let m=l.reduce((g,w)=>g+w.length+2,2);u=t.options.lineWidth>0&&m>t.options.lineWidth}if(u){let m=f;for(let g of l)m+=g?`
53
+ `+Is.indentComment(u(e),c),a&&a()):d&&i&&i(),h}function Hk({items:e},t,{flowChars:n,itemIndent:r}){let{indent:s,indentStep:o,flowCollectionPadding:i,options:{commentString:a}}=t;r+=o;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),u=!1,f=0,d=[];for(let m=0;m<e.length;++m){let g=e[m],w=null;if(jt.isNode(g))g.spaceBefore&&d.push(""),Ds(t,d,g.commentBefore,!1),g.comment&&(w=g.comment);else if(jt.isPair(g)){let v=jt.isNode(g.key)?g.key:null;v&&(v.spaceBefore&&d.push(""),Ds(t,d,v.commentBefore,!1),v.comment&&(u=!0));let b=jt.isNode(g.value)?g.value:null;b?(b.comment&&(w=b.comment),b.commentBefore&&(u=!0)):g.value==null&&v?.comment&&(w=v.comment)}w&&(u=!0);let y=dh.stringify(g,c,()=>w=null);u||(u=d.length>f||y.includes(`
54
+ `)),m<e.length-1?y+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(u||(u=d.reduce((v,b)=>v+b.length+2,2)+(y.length+2)>t.options.lineWidth)),u&&(y+=",")),w&&(y+=Is.lineComment(y,r,a(w))),d.push(y),f=d.length}let{start:l,end:h}=n;if(d.length===0)return l+h;if(!u){let m=d.reduce((g,w)=>g+w.length+2,2);u=t.options.lineWidth>0&&m>t.options.lineWidth}if(u){let m=l;for(let g of d)m+=g?`
55
55
  ${o}${s}${g}`:`
56
56
  `;return`${m}
57
- ${s}${h}`}else return`${f}${i}${l.join(" ")}${i}${h}`}function Is({indent:e,options:{commentString:t}},n,r,s){if(r&&s&&(r=r.replace(/^\n+/,"")),r){let o=Cs.indentComment(t(r),e);n.push(o.trimStart())}}ah.stringifyCollection=qk});var ut=C(Wi=>{"use strict";var Kk=Ki(),Vk=Bi(),Wk=gs(),ct=z(),Ds=at(),Hk=Q();function Un(e,t){let n=ct.isScalar(t)?t.value:t;for(let r of e)if(ct.isPair(r)&&(r.key===t||r.key===n||ct.isScalar(r.key)&&r.key.value===n))return r}var Vi=class extends Wk.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(ct.MAP,t),this.items=[]}static from(t,n,r){let{keepUndefined:s,replacer:o}=r,i=new this(t),a=(c,u)=>{if(typeof o=="function")u=o.call(n,c,u);else if(Array.isArray(o)&&!o.includes(c))return;(u!==void 0||s)&&i.items.push(Ds.createPair(c,u,r))};if(n instanceof Map)for(let[c,u]of n)a(c,u);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof t.sortMapEntries=="function"&&i.items.sort(t.sortMapEntries),i}add(t,n){let r;ct.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Ds.Pair(t,t?.value):r=new Ds.Pair(t.key,t.value);let s=Un(this.items,r.key),o=this.schema?.sortMapEntries;if(s){if(!n)throw new Error(`Key ${r.key} already set`);ct.isScalar(s.value)&&Hk.isScalarValue(r.value)?s.value.value=r.value:s.value=r.value}else if(o){let i=this.items.findIndex(a=>o(r,a)<0);i===-1?this.items.push(r):this.items.splice(i,0,r)}else this.items.push(r)}delete(t){let n=Un(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let s=Un(this.items,t)?.value;return(!n&&ct.isScalar(s)?s.value:s)??void 0}has(t){return!!Un(this.items,t)}set(t,n){this.add(new Ds.Pair(t,n),!0)}toJSON(t,n,r){let s=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(s);for(let o of this.items)Vk.addPairToJSMap(n,s,o);return s}toString(t,n,r){if(!t)return JSON.stringify(this);for(let s of this.items)if(!ct.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})),Kk.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:n})}};Wi.YAMLMap=Vi;Wi.findPair=Un});var Xt=C(uh=>{"use strict";var Yk=z(),ch=ut(),Jk={collection:"map",default:!0,nodeClass:ch.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Yk.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>ch.YAMLMap.from(e,t,n)};uh.map=Jk});var dt=C(dh=>{"use strict";var Gk=Ln(),Qk=Ki(),Xk=gs(),Ns=z(),Zk=Q(),eb=rt(),Hi=class extends Xk.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Ns.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=Ps(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let r=Ps(t);if(typeof r!="number")return;let s=this.items[r];return!n&&Ns.isScalar(s)?s.value:s}has(t){let n=Ps(t);return typeof n=="number"&&n<this.items.length}set(t,n){let r=Ps(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let s=this.items[r];Ns.isScalar(s)&&Zk.isScalarValue(n)?s.value=n:this.items[r]=n}toJSON(t,n){let r=[];n?.onCreate&&n.onCreate(r);let s=0;for(let o of this.items)r.push(eb.toJS(o,String(s++),n));return r}toString(t,n,r){return t?Qk.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,o=new this(t);if(n&&Symbol.iterator in Object(n)){let i=0;for(let a of n){if(typeof s=="function"){let c=n instanceof Set?a:String(i++);a=s.call(n,c,a)}o.items.push(Gk.createNode(a,void 0,r))}}return o}};function Ps(e){let t=Ns.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}dh.YAMLSeq=Hi});var Zt=C(fh=>{"use strict";var tb=z(),lh=dt(),nb={collection:"seq",default:!0,nodeClass:lh.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return tb.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>lh.YAMLSeq.from(e,t,n)};fh.seq=nb});var Kn=C(ph=>{"use strict";var rb=zn(),sb={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),rb.stringifyString(e,t,n,r)}};ph.string=sb});var Ts=C(gh=>{"use strict";var hh=Q(),mh={identify:e=>e==null,createNode:()=>new hh.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new hh.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&mh.test.test(e)?e:t.options.nullStr};gh.nullTag=mh});var Yi=C(wh=>{"use strict";var ob=Q(),yh={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new ob.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&yh.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?n.options.trueStr:n.options.falseStr}};wh.boolTag=yh});var en=C(vh=>{"use strict";function ib({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 o=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(o)&&!o.includes("e")){let i=o.indexOf(".");i<0&&(i=o.length,o+=".");let a=t-(o.length-i-1);for(;a-- >0;)o+="0"}return o}vh.stringifyNumber=ib});var Gi=C(xs=>{"use strict";var ab=Q(),Ji=en(),cb={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:Ji.stringifyNumber},ub={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():Ji.stringifyNumber(e)}},db={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 ab.Scalar(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:Ji.stringifyNumber};xs.float=db;xs.floatExp=ub;xs.floatNaN=cb});var Xi=C(Fs=>{"use strict";var kh=en(),Ls=e=>typeof e=="bigint"||Number.isInteger(e),Qi=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function bh(e,t,n){let{value:r}=e;return Ls(r)&&r>=0?n+r.toString(t):kh.stringifyNumber(e)}var lb={identify:e=>Ls(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Qi(e,2,8,n),stringify:e=>bh(e,8,"0o")},fb={identify:Ls,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Qi(e,0,10,n),stringify:kh.stringifyNumber},pb={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)=>Qi(e,2,16,n),stringify:e=>bh(e,16,"0x")};Fs.int=fb;Fs.intHex=pb;Fs.intOct=lb});var Rh=C(Eh=>{"use strict";var hb=Xt(),mb=Ts(),gb=Zt(),yb=Kn(),wb=Yi(),Zi=Gi(),ea=Xi(),vb=[hb.map,gb.seq,yb.string,mb.nullTag,wb.boolTag,ea.intOct,ea.int,ea.intHex,Zi.floatNaN,Zi.floatExp,Zi.float];Eh.schema=vb});var Ah=C($h=>{"use strict";var kb=Q(),bb=Xt(),Eb=Zt();function Sh(e){return typeof e=="bigint"||Number.isInteger(e)}var Ms=({value:e})=>JSON.stringify(e),Rb=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Ms},{identify:e=>e==null,createNode:()=>new kb.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ms},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Ms},{identify:Sh,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})=>Sh(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:Ms}],Sb={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},$b=[bb.map,Eb.seq].concat(Rb,Sb);$h.schema=$b});var na=C(Oh=>{"use strict";var Vn=gr("buffer"),ta=Q(),Ab=zn(),Ob={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Vn.Buffer=="function")return Vn.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,o){if(!n)return"";let i=n,a;if(typeof Vn.Buffer=="function")a=i instanceof Vn.Buffer?i.toString("base64"):Vn.Buffer.from(i.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let u=0;u<i.length;++u)c+=String.fromCharCode(i[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=ta.Scalar.BLOCK_LITERAL),t!==ta.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),u=Math.ceil(a.length/c),d=new Array(u);for(let l=0,f=0;l<u;++l,f+=c)d[l]=a.substr(f,c);a=d.join(t===ta.Scalar.BLOCK_LITERAL?`
58
- `:" ")}return Ab.stringifyString({comment:e,type:t,value:a},r,s,o)}};Oh.binary=Ob});var qs=C(zs=>{"use strict";var _s=z(),ra=at(),jb=Q(),Cb=dt();function jh(e,t){if(_s.isSeq(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!_s.isPair(r)){if(_s.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let s=r.items[0]||new ra.Pair(new jb.Scalar(null));if(r.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${r.commentBefore}
57
+ ${s}${h}`}else return`${l}${i}${d.join(" ")}${i}${h}`}function Ds({indent:e,options:{commentString:t}},n,r,s){if(r&&s&&(r=r.replace(/^\n+/,"")),r){let o=Is.indentComment(t(r),e);n.push(o.trimStart())}}lh.stringifyCollection=Vk});var dt=C(Hi=>{"use strict";var Yk=Vi(),Jk=Ui(),Gk=ys(),ut=z(),Ps=ct(),Qk=Q();function Kn(e,t){let n=ut.isScalar(t)?t.value:t;for(let r of e)if(ut.isPair(r)&&(r.key===t||r.key===n||ut.isScalar(r.key)&&r.key.value===n))return r}var Wi=class extends Gk.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(ut.MAP,t),this.items=[]}static from(t,n,r){let{keepUndefined:s,replacer:o}=r,i=new this(t),a=(c,u)=>{if(typeof o=="function")u=o.call(n,c,u);else if(Array.isArray(o)&&!o.includes(c))return;(u!==void 0||s)&&i.items.push(Ps.createPair(c,u,r))};if(n instanceof Map)for(let[c,u]of n)a(c,u);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof t.sortMapEntries=="function"&&i.items.sort(t.sortMapEntries),i}add(t,n){let r;ut.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Ps.Pair(t,t?.value):r=new Ps.Pair(t.key,t.value);let s=Kn(this.items,r.key),o=this.schema?.sortMapEntries;if(s){if(!n)throw new Error(`Key ${r.key} already set`);ut.isScalar(s.value)&&Qk.isScalarValue(r.value)?s.value.value=r.value:s.value=r.value}else if(o){let i=this.items.findIndex(a=>o(r,a)<0);i===-1?this.items.push(r):this.items.splice(i,0,r)}else this.items.push(r)}delete(t){let n=Kn(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let s=Kn(this.items,t)?.value;return(!n&&ut.isScalar(s)?s.value:s)??void 0}has(t){return!!Kn(this.items,t)}set(t,n){this.add(new Ps.Pair(t,n),!0)}toJSON(t,n,r){let s=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(s);for(let o of this.items)Jk.addPairToJSMap(n,s,o);return s}toString(t,n,r){if(!t)return JSON.stringify(this);for(let s of this.items)if(!ut.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})),Yk.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:n})}};Hi.YAMLMap=Wi;Hi.findPair=Kn});var Zt=C(ph=>{"use strict";var Xk=z(),fh=dt(),Zk={collection:"map",default:!0,nodeClass:fh.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Xk.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>fh.YAMLMap.from(e,t,n)};ph.map=Zk});var lt=C(hh=>{"use strict";var eb=Fn(),tb=Vi(),nb=ys(),Ts=z(),rb=Q(),sb=st(),Yi=class extends nb.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Ts.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=Ns(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let r=Ns(t);if(typeof r!="number")return;let s=this.items[r];return!n&&Ts.isScalar(s)?s.value:s}has(t){let n=Ns(t);return typeof n=="number"&&n<this.items.length}set(t,n){let r=Ns(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let s=this.items[r];Ts.isScalar(s)&&rb.isScalarValue(n)?s.value=n:this.items[r]=n}toJSON(t,n){let r=[];n?.onCreate&&n.onCreate(r);let s=0;for(let o of this.items)r.push(sb.toJS(o,String(s++),n));return r}toString(t,n,r){return t?tb.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,o=new this(t);if(n&&Symbol.iterator in Object(n)){let i=0;for(let a of n){if(typeof s=="function"){let c=n instanceof Set?a:String(i++);a=s.call(n,c,a)}o.items.push(eb.createNode(a,void 0,r))}}return o}};function Ns(e){let t=Ts.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}hh.YAMLSeq=Yi});var en=C(gh=>{"use strict";var ob=z(),mh=lt(),ib={collection:"seq",default:!0,nodeClass:mh.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return ob.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>mh.YAMLSeq.from(e,t,n)};gh.seq=ib});var Vn=C(yh=>{"use strict";var ab=qn(),cb={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),ab.stringifyString(e,t,n,r)}};yh.string=cb});var xs=C(kh=>{"use strict";var wh=Q(),vh={identify:e=>e==null,createNode:()=>new wh.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new wh.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&vh.test.test(e)?e:t.options.nullStr};kh.nullTag=vh});var Ji=C(Eh=>{"use strict";var ub=Q(),bh={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new ub.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&bh.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?n.options.trueStr:n.options.falseStr}};Eh.boolTag=bh});var tn=C(Rh=>{"use strict";function db({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 o=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(o)&&!o.includes("e")){let i=o.indexOf(".");i<0&&(i=o.length,o+=".");let a=t-(o.length-i-1);for(;a-- >0;)o+="0"}return o}Rh.stringifyNumber=db});var Qi=C(Ls=>{"use strict";var lb=Q(),Gi=tn(),fb={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:Gi.stringifyNumber},pb={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():Gi.stringifyNumber(e)}},hb={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 lb.Scalar(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:Gi.stringifyNumber};Ls.float=hb;Ls.floatExp=pb;Ls.floatNaN=fb});var Zi=C(Ms=>{"use strict";var Sh=tn(),Fs=e=>typeof e=="bigint"||Number.isInteger(e),Xi=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function $h(e,t,n){let{value:r}=e;return Fs(r)&&r>=0?n+r.toString(t):Sh.stringifyNumber(e)}var mb={identify:e=>Fs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Xi(e,2,8,n),stringify:e=>$h(e,8,"0o")},gb={identify:Fs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Xi(e,0,10,n),stringify:Sh.stringifyNumber},yb={identify:e=>Fs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Xi(e,2,16,n),stringify:e=>$h(e,16,"0x")};Ms.int=gb;Ms.intHex=yb;Ms.intOct=mb});var Oh=C(Ah=>{"use strict";var wb=Zt(),vb=xs(),kb=en(),bb=Vn(),Eb=Ji(),ea=Qi(),ta=Zi(),Rb=[wb.map,kb.seq,bb.string,vb.nullTag,Eb.boolTag,ta.intOct,ta.int,ta.intHex,ea.floatNaN,ea.floatExp,ea.float];Ah.schema=Rb});var Ih=C(Ch=>{"use strict";var Sb=Q(),$b=Zt(),Ab=en();function jh(e){return typeof e=="bigint"||Number.isInteger(e)}var _s=({value:e})=>JSON.stringify(e),Ob=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:_s},{identify:e=>e==null,createNode:()=>new Sb.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:_s},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:_s},{identify:jh,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})=>jh(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:_s}],jb={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Cb=[$b.map,Ab.seq].concat(Ob,jb);Ch.schema=Cb});var ra=C(Dh=>{"use strict";var Wn=yr("buffer"),na=Q(),Ib=qn(),Db={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Wn.Buffer=="function")return Wn.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,o){if(!n)return"";let i=n,a;if(typeof Wn.Buffer=="function")a=i instanceof Wn.Buffer?i.toString("base64"):Wn.Buffer.from(i.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let u=0;u<i.length;++u)c+=String.fromCharCode(i[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=na.Scalar.BLOCK_LITERAL),t!==na.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),u=Math.ceil(a.length/c),f=new Array(u);for(let d=0,l=0;d<u;++d,l+=c)f[d]=a.substr(l,c);a=f.join(t===na.Scalar.BLOCK_LITERAL?`
58
+ `:" ")}return Ib.stringifyString({comment:e,type:t,value:a},r,s,o)}};Dh.binary=Db});var Bs=C(qs=>{"use strict";var zs=z(),sa=ct(),Pb=Q(),Nb=lt();function Ph(e,t){if(zs.isSeq(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!zs.isPair(r)){if(zs.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let s=r.items[0]||new sa.Pair(new Pb.Scalar(null));if(r.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${r.commentBefore}
59
59
  ${s.key.commentBefore}`:r.commentBefore),r.comment){let o=s.value??s.key;o.comment=o.comment?`${r.comment}
60
- ${o.comment}`:r.comment}r=s}e.items[n]=_s.isPair(r)?r:new ra.Pair(r)}}else t("Expected a sequence for this tag");return e}function Ch(e,t,n){let{replacer:r}=n,s=new Cb.YAMLSeq(e);s.tag="tag:yaml.org,2002:pairs";let o=0;if(t&&Symbol.iterator in Object(t))for(let i of t){typeof r=="function"&&(i=r.call(t,String(o++),i));let a,c;if(Array.isArray(i))if(i.length===2)a=i[0],c=i[1];else throw new TypeError(`Expected [key, value] tuple: ${i}`);else if(i&&i instanceof Object){let u=Object.keys(i);if(u.length===1)a=u[0],c=i[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=i;s.items.push(ra.createPair(a,c,n))}return s}var Ib={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:jh,createNode:Ch};zs.createPairs=Ch;zs.pairs=Ib;zs.resolvePairs=jh});var ia=C(oa=>{"use strict";var Ih=z(),sa=rt(),Wn=ut(),Db=dt(),Dh=qs(),jt=class e extends Db.YAMLSeq{constructor(){super(),this.add=Wn.YAMLMap.prototype.add.bind(this),this.delete=Wn.YAMLMap.prototype.delete.bind(this),this.get=Wn.YAMLMap.prototype.get.bind(this),this.has=Wn.YAMLMap.prototype.has.bind(this),this.set=Wn.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 o,i;if(Ih.isPair(s)?(o=sa.toJS(s.key,"",n),i=sa.toJS(s.value,o,n)):o=sa.toJS(s,"",n),r.has(o))throw new Error("Ordered maps must not include duplicate keys");r.set(o,i)}return r}static from(t,n,r){let s=Dh.createPairs(t,n,r),o=new this;return o.items=s.items,o}};jt.tag="tag:yaml.org,2002:omap";var Pb={collection:"seq",identify:e=>e instanceof Map,nodeClass:jt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=Dh.resolvePairs(e,t),r=[];for(let{key:s}of n.items)Ih.isScalar(s)&&(r.includes(s.value)?t(`Ordered maps must not include duplicate keys: ${s.value}`):r.push(s.value));return Object.assign(new jt,n)},createNode:(e,t,n)=>jt.from(e,t,n)};oa.YAMLOMap=jt;oa.omap=Pb});var Lh=C(aa=>{"use strict";var Ph=Q();function Nh({value:e,source:t},n){return t&&(e?Th:xh).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Th={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 Ph.Scalar(!0),stringify:Nh},xh={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 Ph.Scalar(!1),stringify:Nh};aa.falseTag=xh;aa.trueTag=Th});var Fh=C(Bs=>{"use strict";var Nb=Q(),ca=en(),Tb={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:ca.stringifyNumber},xb={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():ca.stringifyNumber(e)}},Lb={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 Nb.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:ca.stringifyNumber};Bs.float=Lb;Bs.floatExp=xb;Bs.floatNaN=Tb});var _h=C(Yn=>{"use strict";var Mh=en(),Hn=e=>typeof e=="bigint"||Number.isInteger(e);function Us(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 i=BigInt(e);return s==="-"?BigInt(-1)*i:i}let o=parseInt(e,n);return s==="-"?-1*o:o}function ua(e,t,n){let{value:r}=e;if(Hn(r)){let s=r.toString(t);return r<0?"-"+n+s.substr(1):n+s}return Mh.stringifyNumber(e)}var Fb={identify:Hn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Us(e,2,2,n),stringify:e=>ua(e,2,"0b")},Mb={identify:Hn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Us(e,1,8,n),stringify:e=>ua(e,8,"0")},_b={identify:Hn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Us(e,0,10,n),stringify:Mh.stringifyNumber},zb={identify:Hn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Us(e,2,16,n),stringify:e=>ua(e,16,"0x")};Yn.int=_b;Yn.intBin=Fb;Yn.intHex=zb;Yn.intOct=Mb});var la=C(da=>{"use strict";var Ws=z(),Ks=at(),Vs=ut(),Ct=class e extends Vs.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;Ws.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new Ks.Pair(t.key,null):n=new Ks.Pair(t,null),Vs.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let r=Vs.findPair(this.items,t);return!n&&Ws.isPair(r)?Ws.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=Vs.findPair(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new Ks.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,o=new this(t);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof s=="function"&&(i=s.call(n,i,i)),o.items.push(Ks.createPair(i,null,r));return o}};Ct.tag="tag:yaml.org,2002:set";var qb={collection:"map",identify:e=>e instanceof Set,nodeClass:Ct,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>Ct.from(e,t,n),resolve(e,t){if(Ws.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Ct,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};da.YAMLSet=Ct;da.set=qb});var pa=C(Hs=>{"use strict";var Bb=en();function fa(e,t){let n=e[0],r=n==="-"||n==="+"?e.substring(1):e,s=i=>t?BigInt(i):Number(i),o=r.replace(/_/g,"").split(":").reduce((i,a)=>i*s(60)+s(a),s(0));return n==="-"?s(-1)*o:o}function zh(e){let{value:t}=e,n=i=>i;if(typeof t=="bigint")n=i=>BigInt(i);else if(isNaN(t)||!isFinite(t))return Bb.stringifyNumber(e);let r="";t<0&&(r="-",t*=n(-1));let s=n(60),o=[t%s];return t<60?o.unshift(0):(t=(t-o[0])/s,o.unshift(t%s),t>=60&&(t=(t-o[0])/s,o.unshift(t))),r+o.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Ub={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})=>fa(e,n),stringify:zh},Kb={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=>fa(e,!1),stringify:zh},qh={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(qh.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,s,o,i,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,u=Date.UTC(n,r-1,s,o||0,i||0,a||0,c),d=t[8];if(d&&d!=="Z"){let l=fa(d,!1);Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Hs.floatTime=Kb;Hs.intTime=Ub;Hs.timestamp=qh});var Kh=C(Uh=>{"use strict";var Vb=Xt(),Wb=Ts(),Hb=Zt(),Yb=Kn(),Jb=na(),Bh=Lh(),ha=Fh(),Ys=_h(),Gb=As(),Qb=ia(),Xb=qs(),Zb=la(),ma=pa(),eE=[Vb.map,Hb.seq,Yb.string,Wb.nullTag,Bh.trueTag,Bh.falseTag,Ys.intBin,Ys.intOct,Ys.int,Ys.intHex,ha.floatNaN,ha.floatExp,ha.float,Jb.binary,Gb.merge,Qb.omap,Xb.pairs,Zb.set,ma.intTime,ma.floatTime,ma.timestamp];Uh.schema=eE});var em=C(wa=>{"use strict";var Yh=Xt(),tE=Ts(),Jh=Zt(),nE=Kn(),rE=Yi(),ga=Gi(),ya=Xi(),sE=Rh(),oE=Ah(),Gh=na(),Jn=As(),Qh=ia(),Xh=qs(),Vh=Kh(),Zh=la(),Js=pa(),Wh=new Map([["core",sE.schema],["failsafe",[Yh.map,Jh.seq,nE.string]],["json",oE.schema],["yaml11",Vh.schema],["yaml-1.1",Vh.schema]]),Hh={binary:Gh.binary,bool:rE.boolTag,float:ga.float,floatExp:ga.floatExp,floatNaN:ga.floatNaN,floatTime:Js.floatTime,int:ya.int,intHex:ya.intHex,intOct:ya.intOct,intTime:Js.intTime,map:Yh.map,merge:Jn.merge,null:tE.nullTag,omap:Qh.omap,pairs:Xh.pairs,seq:Jh.seq,set:Zh.set,timestamp:Js.timestamp},iE={"tag:yaml.org,2002:binary":Gh.binary,"tag:yaml.org,2002:merge":Jn.merge,"tag:yaml.org,2002:omap":Qh.omap,"tag:yaml.org,2002:pairs":Xh.pairs,"tag:yaml.org,2002:set":Zh.set,"tag:yaml.org,2002:timestamp":Js.timestamp};function aE(e,t,n){let r=Wh.get(t);if(r&&!e)return n&&!r.includes(Jn.merge)?r.concat(Jn.merge):r.slice();let s=r;if(!s)if(Array.isArray(e))s=[];else{let o=Array.from(Wh.keys()).filter(i=>i!=="yaml11").map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${o} or define customTags array`)}if(Array.isArray(e))for(let o of e)s=s.concat(o);else typeof e=="function"&&(s=e(s.slice()));return n&&(s=s.concat(Jn.merge)),s.reduce((o,i)=>{let a=typeof i=="string"?Hh[i]:i;if(!a){let c=JSON.stringify(i),u=Object.keys(Hh).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${u}`)}return o.includes(a)||o.push(a),o},[])}wa.coreKnownTags=iE;wa.getTags=aE});var ba=C(tm=>{"use strict";var va=z(),cE=Xt(),uE=Zt(),dE=Kn(),Gs=em(),lE=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,ka=class e{constructor({compat:t,customTags:n,merge:r,resolveKnownTags:s,schema:o,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(t)?Gs.getTags(t,"compat"):t?Gs.getTags(null,t):null,this.name=typeof o=="string"&&o||"core",this.knownTags=s?Gs.coreKnownTags:{},this.tags=Gs.getTags(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,va.MAP,{value:cE.map}),Object.defineProperty(this,va.SCALAR,{value:dE.string}),Object.defineProperty(this,va.SEQ,{value:uE.seq}),this.sortMapEntries=typeof i=="function"?i:i===!0?lE:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};tm.Schema=ka});var rm=C(nm=>{"use strict";var fE=z(),Ea=qn(),Gn=Fn();function pE(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=Ea.createStringifyContext(e,t),{commentString:o}=s.options;if(e.commentBefore){n.length!==1&&n.unshift("");let c=o(e.commentBefore);n.unshift(Gn.indentComment(c,""))}let i=!1,a=null;if(e.contents){if(fE.isNode(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){let d=o(e.contents.commentBefore);n.push(Gn.indentComment(d,""))}s.forceBlockIndent=!!e.comment,a=e.contents.comment}let c=a?void 0:()=>i=!0,u=Ea.stringify(e.contents,s,()=>a=null,c);a&&(u+=Gn.lineComment(u,"",o(a))),(u[0]==="|"||u[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${u}`:n.push(u)}else n.push(Ea.stringify(e.contents,s));if(e.directives?.docEnd)if(e.comment){let c=o(e.comment);c.includes(`
61
- `)?(n.push("..."),n.push(Gn.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=e.comment;c&&i&&(c=c.replace(/^\n+/,"")),c&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(Gn.indentComment(o(c),"")))}return n.join(`
60
+ ${o.comment}`:r.comment}r=s}e.items[n]=zs.isPair(r)?r:new sa.Pair(r)}}else t("Expected a sequence for this tag");return e}function Nh(e,t,n){let{replacer:r}=n,s=new Nb.YAMLSeq(e);s.tag="tag:yaml.org,2002:pairs";let o=0;if(t&&Symbol.iterator in Object(t))for(let i of t){typeof r=="function"&&(i=r.call(t,String(o++),i));let a,c;if(Array.isArray(i))if(i.length===2)a=i[0],c=i[1];else throw new TypeError(`Expected [key, value] tuple: ${i}`);else if(i&&i instanceof Object){let u=Object.keys(i);if(u.length===1)a=u[0],c=i[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=i;s.items.push(sa.createPair(a,c,n))}return s}var Tb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ph,createNode:Nh};qs.createPairs=Nh;qs.pairs=Tb;qs.resolvePairs=Ph});var aa=C(ia=>{"use strict";var Th=z(),oa=st(),Hn=dt(),xb=lt(),xh=Bs(),Ct=class e extends xb.YAMLSeq{constructor(){super(),this.add=Hn.YAMLMap.prototype.add.bind(this),this.delete=Hn.YAMLMap.prototype.delete.bind(this),this.get=Hn.YAMLMap.prototype.get.bind(this),this.has=Hn.YAMLMap.prototype.has.bind(this),this.set=Hn.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 o,i;if(Th.isPair(s)?(o=oa.toJS(s.key,"",n),i=oa.toJS(s.value,o,n)):o=oa.toJS(s,"",n),r.has(o))throw new Error("Ordered maps must not include duplicate keys");r.set(o,i)}return r}static from(t,n,r){let s=xh.createPairs(t,n,r),o=new this;return o.items=s.items,o}};Ct.tag="tag:yaml.org,2002:omap";var Lb={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ct,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=xh.resolvePairs(e,t),r=[];for(let{key:s}of n.items)Th.isScalar(s)&&(r.includes(s.value)?t(`Ordered maps must not include duplicate keys: ${s.value}`):r.push(s.value));return Object.assign(new Ct,n)},createNode:(e,t,n)=>Ct.from(e,t,n)};ia.YAMLOMap=Ct;ia.omap=Lb});var zh=C(ca=>{"use strict";var Lh=Q();function Fh({value:e,source:t},n){return t&&(e?Mh:_h).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Mh={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 Lh.Scalar(!0),stringify:Fh},_h={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 Lh.Scalar(!1),stringify:Fh};ca.falseTag=_h;ca.trueTag=Mh});var qh=C(Us=>{"use strict";var Fb=Q(),ua=tn(),Mb={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:ua.stringifyNumber},_b={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():ua.stringifyNumber(e)}},zb={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 Fb.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:ua.stringifyNumber};Us.float=zb;Us.floatExp=_b;Us.floatNaN=Mb});var Uh=C(Jn=>{"use strict";var Bh=tn(),Yn=e=>typeof e=="bigint"||Number.isInteger(e);function Ks(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 i=BigInt(e);return s==="-"?BigInt(-1)*i:i}let o=parseInt(e,n);return s==="-"?-1*o:o}function da(e,t,n){let{value:r}=e;if(Yn(r)){let s=r.toString(t);return r<0?"-"+n+s.substr(1):n+s}return Bh.stringifyNumber(e)}var qb={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Ks(e,2,2,n),stringify:e=>da(e,2,"0b")},Bb={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Ks(e,1,8,n),stringify:e=>da(e,8,"0")},Ub={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Ks(e,0,10,n),stringify:Bh.stringifyNumber},Kb={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Ks(e,2,16,n),stringify:e=>da(e,16,"0x")};Jn.int=Ub;Jn.intBin=qb;Jn.intHex=Kb;Jn.intOct=Bb});var fa=C(la=>{"use strict";var Hs=z(),Vs=ct(),Ws=dt(),It=class e extends Ws.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;Hs.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),Ws.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let r=Ws.findPair(this.items,t);return!n&&Hs.isPair(r)?Hs.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 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,o=new this(t);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof s=="function"&&(i=s.call(n,i,i)),o.items.push(Vs.createPair(i,null,r));return o}};It.tag="tag:yaml.org,2002:set";var Vb={collection:"map",identify:e=>e instanceof Set,nodeClass:It,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>It.from(e,t,n),resolve(e,t){if(Hs.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new It,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};la.YAMLSet=It;la.set=Vb});var ha=C(Ys=>{"use strict";var Wb=tn();function pa(e,t){let n=e[0],r=n==="-"||n==="+"?e.substring(1):e,s=i=>t?BigInt(i):Number(i),o=r.replace(/_/g,"").split(":").reduce((i,a)=>i*s(60)+s(a),s(0));return n==="-"?s(-1)*o:o}function Kh(e){let{value:t}=e,n=i=>i;if(typeof t=="bigint")n=i=>BigInt(i);else if(isNaN(t)||!isFinite(t))return Wb.stringifyNumber(e);let r="";t<0&&(r="-",t*=n(-1));let s=n(60),o=[t%s];return t<60?o.unshift(0):(t=(t-o[0])/s,o.unshift(t%s),t>=60&&(t=(t-o[0])/s,o.unshift(t))),r+o.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Hb={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})=>pa(e,n),stringify:Kh},Yb={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=>pa(e,!1),stringify:Kh},Vh={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(Vh.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,s,o,i,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,u=Date.UTC(n,r-1,s,o||0,i||0,a||0,c),f=t[8];if(f&&f!=="Z"){let d=pa(f,!1);Math.abs(d)<30&&(d*=60),u-=6e4*d}return new Date(u)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Ys.floatTime=Yb;Ys.intTime=Hb;Ys.timestamp=Vh});var Yh=C(Hh=>{"use strict";var Jb=Zt(),Gb=xs(),Qb=en(),Xb=Vn(),Zb=ra(),Wh=zh(),ma=qh(),Js=Uh(),eE=Os(),tE=aa(),nE=Bs(),rE=fa(),ga=ha(),sE=[Jb.map,Qb.seq,Xb.string,Gb.nullTag,Wh.trueTag,Wh.falseTag,Js.intBin,Js.intOct,Js.int,Js.intHex,ma.floatNaN,ma.floatExp,ma.float,Zb.binary,eE.merge,tE.omap,nE.pairs,rE.set,ga.intTime,ga.floatTime,ga.timestamp];Hh.schema=sE});var sm=C(va=>{"use strict";var Xh=Zt(),oE=xs(),Zh=en(),iE=Vn(),aE=Ji(),ya=Qi(),wa=Zi(),cE=Oh(),uE=Ih(),em=ra(),Gn=Os(),tm=aa(),nm=Bs(),Jh=Yh(),rm=fa(),Gs=ha(),Gh=new Map([["core",cE.schema],["failsafe",[Xh.map,Zh.seq,iE.string]],["json",uE.schema],["yaml11",Jh.schema],["yaml-1.1",Jh.schema]]),Qh={binary:em.binary,bool:aE.boolTag,float:ya.float,floatExp:ya.floatExp,floatNaN:ya.floatNaN,floatTime:Gs.floatTime,int:wa.int,intHex:wa.intHex,intOct:wa.intOct,intTime:Gs.intTime,map:Xh.map,merge:Gn.merge,null:oE.nullTag,omap:tm.omap,pairs:nm.pairs,seq:Zh.seq,set:rm.set,timestamp:Gs.timestamp},dE={"tag:yaml.org,2002:binary":em.binary,"tag:yaml.org,2002:merge":Gn.merge,"tag:yaml.org,2002:omap":tm.omap,"tag:yaml.org,2002:pairs":nm.pairs,"tag:yaml.org,2002:set":rm.set,"tag:yaml.org,2002:timestamp":Gs.timestamp};function lE(e,t,n){let r=Gh.get(t);if(r&&!e)return n&&!r.includes(Gn.merge)?r.concat(Gn.merge):r.slice();let s=r;if(!s)if(Array.isArray(e))s=[];else{let o=Array.from(Gh.keys()).filter(i=>i!=="yaml11").map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${o} or define customTags array`)}if(Array.isArray(e))for(let o of e)s=s.concat(o);else typeof e=="function"&&(s=e(s.slice()));return n&&(s=s.concat(Gn.merge)),s.reduce((o,i)=>{let a=typeof i=="string"?Qh[i]:i;if(!a){let c=JSON.stringify(i),u=Object.keys(Qh).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${u}`)}return o.includes(a)||o.push(a),o},[])}va.coreKnownTags=dE;va.getTags=lE});var Ea=C(om=>{"use strict";var ka=z(),fE=Zt(),pE=en(),hE=Vn(),Qs=sm(),mE=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,ba=class e{constructor({compat:t,customTags:n,merge:r,resolveKnownTags:s,schema:o,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(t)?Qs.getTags(t,"compat"):t?Qs.getTags(null,t):null,this.name=typeof o=="string"&&o||"core",this.knownTags=s?Qs.coreKnownTags:{},this.tags=Qs.getTags(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,ka.MAP,{value:fE.map}),Object.defineProperty(this,ka.SCALAR,{value:hE.string}),Object.defineProperty(this,ka.SEQ,{value:pE.seq}),this.sortMapEntries=typeof i=="function"?i:i===!0?mE:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};om.Schema=ba});var am=C(im=>{"use strict";var gE=z(),Ra=Bn(),Qn=Mn();function yE(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=Ra.createStringifyContext(e,t),{commentString:o}=s.options;if(e.commentBefore){n.length!==1&&n.unshift("");let c=o(e.commentBefore);n.unshift(Qn.indentComment(c,""))}let i=!1,a=null;if(e.contents){if(gE.isNode(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){let f=o(e.contents.commentBefore);n.push(Qn.indentComment(f,""))}s.forceBlockIndent=!!e.comment,a=e.contents.comment}let c=a?void 0:()=>i=!0,u=Ra.stringify(e.contents,s,()=>a=null,c);a&&(u+=Qn.lineComment(u,"",o(a))),(u[0]==="|"||u[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${u}`:n.push(u)}else n.push(Ra.stringify(e.contents,s));if(e.directives?.docEnd)if(e.comment){let c=o(e.comment);c.includes(`
61
+ `)?(n.push("..."),n.push(Qn.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=e.comment;c&&i&&(c=c.replace(/^\n+/,"")),c&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(Qn.indentComment(o(c),"")))}return n.join(`
62
62
  `)+`
63
- `}nm.stringifyDocument=pE});var Qn=C(sm=>{"use strict";var hE=xn(),tn=gs(),be=z(),mE=at(),gE=rt(),yE=ba(),wE=rm(),Ra=fs(),vE=Oi(),kE=Ln(),Sa=Ai(),$a=class e{constructor(t,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,be.NODE_TYPE,{value:be.DOC});let s=null;typeof n=="function"||Array.isArray(n)?s=n:r===void 0&&n&&(r=n,n=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=o;let{version:i}=o;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(i=this.directives.yaml.version)):this.directives=new Sa.Directives({version:i}),this.setSchema(i,r),this.contents=t===void 0?null:this.createNode(t,s,r)}clone(){let t=Object.create(e.prototype,{[be.NODE_TYPE]:{value:be.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=be.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){nn(this.contents)&&this.contents.add(t)}addIn(t,n){nn(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let r=Ra.anchorNames(this);t.anchor=!n||r.has(n)?Ra.findNewAnchor(n||"a",r):n}return new hE.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 w=v=>typeof v=="number"||v instanceof String||v instanceof Number,y=n.filter(w).map(String);y.length>0&&(n=n.concat(y)),s=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:o,anchorPrefix:i,flow:a,keepUndefined:c,onTagObj:u,tag:d}=r??{},{onAnchor:l,setAnchors:f,sourceObjects:h}=Ra.createNodeAnchors(this,i||"a"),m={aliasDuplicateObjects:o??!0,keepUndefined:c??!1,onAnchor:l,onTagObj:u,replacer:s,schema:this.schema,sourceObjects:h},g=kE.createNode(t,d,m);return a&&be.isCollection(g)&&(g.flow=!0),f(),g}createPair(t,n,r={}){let s=this.createNode(t,null,r),o=this.createNode(n,null,r);return new mE.Pair(s,o)}delete(t){return nn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return tn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):nn(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return be.isCollection(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return tn.isEmptyPath(t)?!n&&be.isScalar(this.contents)?this.contents.value:this.contents:be.isCollection(this.contents)?this.contents.getIn(t,n):void 0}has(t){return be.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return tn.isEmptyPath(t)?this.contents!==void 0:be.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=tn.collectionFromPath(this.schema,[t],n):nn(this.contents)&&this.contents.set(t,n)}setIn(t,n){tn.isEmptyPath(t)?this.contents=n:this.contents==null?this.contents=tn.collectionFromPath(this.schema,Array.from(t),n):nn(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 Sa.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 Sa.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 yE.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:o,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},c=gE.toJS(this.contents,n??"",a);if(typeof o=="function")for(let{count:u,res:d}of a.anchors.values())o(d,u);return typeof i=="function"?vE.applyReviver(i,{"":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 wE.stringifyDocument(this,t)}};function nn(e){if(be.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}sm.Document=$a});var er=C(Zn=>{"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}},Aa=class extends Xn{constructor(t,n,r){super("YAMLParseError",t,n,r)}},Oa=class extends Xn{constructor(t,n,r){super("YAMLWarning",t,n,r)}},bE=(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 o=s-1,i=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(o>=60&&i.length>80){let a=Math.min(o-39,i.length-79);i="\u2026"+i.substring(a),o-=a-1}if(i.length>80&&(i=i.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(i.substring(0,o))){let a=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
63
+ `}im.stringifyDocument=yE});var Xn=C(cm=>{"use strict";var wE=Ln(),nn=ys(),be=z(),vE=ct(),kE=st(),bE=Ea(),EE=am(),Sa=ps(),RE=ji(),SE=Fn(),$a=Oi(),Aa=class e{constructor(t,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,be.NODE_TYPE,{value:be.DOC});let s=null;typeof n=="function"||Array.isArray(n)?s=n:r===void 0&&n&&(r=n,n=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=o;let{version:i}=o;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(i=this.directives.yaml.version)):this.directives=new $a.Directives({version:i}),this.setSchema(i,r),this.contents=t===void 0?null:this.createNode(t,s,r)}clone(){let t=Object.create(e.prototype,{[be.NODE_TYPE]:{value:be.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=be.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){rn(this.contents)&&this.contents.add(t)}addIn(t,n){rn(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let r=Sa.anchorNames(this);t.anchor=!n||r.has(n)?Sa.findNewAnchor(n||"a",r):n}return new wE.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 w=v=>typeof v=="number"||v instanceof String||v instanceof Number,y=n.filter(w).map(String);y.length>0&&(n=n.concat(y)),s=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:o,anchorPrefix:i,flow:a,keepUndefined:c,onTagObj:u,tag:f}=r??{},{onAnchor:d,setAnchors:l,sourceObjects:h}=Sa.createNodeAnchors(this,i||"a"),m={aliasDuplicateObjects:o??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:u,replacer:s,schema:this.schema,sourceObjects:h},g=SE.createNode(t,f,m);return a&&be.isCollection(g)&&(g.flow=!0),l(),g}createPair(t,n,r={}){let s=this.createNode(t,null,r),o=this.createNode(n,null,r);return new vE.Pair(s,o)}delete(t){return rn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return nn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):rn(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return be.isCollection(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return nn.isEmptyPath(t)?!n&&be.isScalar(this.contents)?this.contents.value:this.contents:be.isCollection(this.contents)?this.contents.getIn(t,n):void 0}has(t){return be.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return nn.isEmptyPath(t)?this.contents!==void 0:be.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=nn.collectionFromPath(this.schema,[t],n):rn(this.contents)&&this.contents.set(t,n)}setIn(t,n){nn.isEmptyPath(t)?this.contents=n:this.contents==null?this.contents=nn.collectionFromPath(this.schema,Array.from(t),n):rn(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 $a.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 $a.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 bE.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:o,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},c=kE.toJS(this.contents,n??"",a);if(typeof o=="function")for(let{count:u,res:f}of a.anchors.values())o(f,u);return typeof i=="function"?RE.applyReviver(i,{"":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 EE.stringifyDocument(this,t)}};function rn(e){if(be.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}cm.Document=Aa});var tr=C(er=>{"use strict";var Zn=class extends Error{constructor(t,n,r,s){super(),this.name=t,this.code=r,this.message=s,this.pos=n}},Oa=class extends Zn{constructor(t,n,r){super("YAMLParseError",t,n,r)}},ja=class extends Zn{constructor(t,n,r){super("YAMLWarning",t,n,r)}},$E=(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 o=s-1,i=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(o>=60&&i.length>80){let a=Math.min(o-39,i.length-79);i="\u2026"+i.substring(a),o-=a-1}if(i.length>80&&(i=i.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(i.substring(0,o))){let a=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
64
64
  `),i=a+i}if(/[^ ]/.test(i)){let a=1,c=n.linePos[1];c?.line===r&&c.col>s&&(a=Math.max(1,Math.min(c.col-s,80-o)));let u=" ".repeat(o)+"^".repeat(a);n.message+=`:
65
65
 
66
66
  ${i}
67
67
  ${u}
68
- `}};Zn.YAMLError=Xn;Zn.YAMLParseError=Aa;Zn.YAMLWarning=Oa;Zn.prettifyError=bE});var tr=C(om=>{"use strict";function EE(e,{flow:t,indicator:n,next:r,offset:s,onError:o,parentIndent:i,startOnNewline:a}){let c=!1,u=a,d=a,l="",f="",h=!1,m=!1,g=null,w=null,y=null,v=null,b=null,k=null,E=null;for(let j of e)switch(m&&(j.type!=="space"&&j.type!=="newline"&&j.type!=="comma"&&o(j.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),g&&(u&&j.type!=="comment"&&j.type!=="newline"&&o(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),g=null),j.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&j.source.includes(" ")&&(g=j),d=!0;break;case"comment":{d||o(j,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let A=j.source.substring(1)||" ";l?l+=f+A:l=A,f="",u=!1;break}case"newline":u?l?l+=j.source:(!k||n!=="seq-item-ind")&&(c=!0):f+=j.source,u=!0,h=!0,(w||y)&&(v=j),d=!0;break;case"anchor":w&&o(j,"MULTIPLE_ANCHORS","A node can have at most one anchor"),j.source.endsWith(":")&&o(j.offset+j.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),w=j,E??(E=j.offset),u=!1,d=!1,m=!0;break;case"tag":{y&&o(j,"MULTIPLE_TAGS","A node can have at most one tag"),y=j,E??(E=j.offset),u=!1,d=!1,m=!0;break}case n:(w||y)&&o(j,"BAD_PROP_ORDER",`Anchors and tags must be after the ${j.source} indicator`),k&&o(j,"UNEXPECTED_TOKEN",`Unexpected ${j.source} in ${t??"collection"}`),k=j,u=n==="seq-item-ind"||n==="explicit-key-ind",d=!1;break;case"comma":if(t){b&&o(j,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),b=j,u=!1,d=!1;break}default:o(j,"UNEXPECTED_TOKEN",`Unexpected ${j.type} token`),u=!1,d=!1}let S=e[e.length-1],$=S?S.offset+S.source.length:s;return m&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&o(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g&&(u&&g.indent<=i||r?.type==="block-map"||r?.type==="block-seq")&&o(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:b,found:k,spaceBefore:c,comment:l,hasNewline:h,anchor:w,tag:y,newlineAfterProp:v,end:$,start:E??$}}om.resolveProps=EE});var Qs=C(im=>{"use strict";function ja(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(ja(t.key)||ja(t.value))return!0}return!1;default:return!0}}im.containsNewline=ja});var Ca=C(am=>{"use strict";var RE=Qs();function SE(e,t,n){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&RE.containsNewline(t)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}am.flowIndentCheck=SE});var Ia=C(um=>{"use strict";var cm=z();function $E(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let s=typeof r=="function"?r:(o,i)=>o===i||cm.isScalar(o)&&cm.isScalar(i)&&o.value===i.value;return t.some(o=>s(o.key,n))}um.mapIncludes=$E});var mm=C(hm=>{"use strict";var dm=at(),AE=ut(),lm=tr(),OE=Qs(),fm=Ca(),jE=Ia(),pm="All mapping items must start at the same column";function CE({composeNode:e,composeEmptyNode:t},n,r,s,o){let i=o?.nodeClass??AE.YAMLMap,a=new i(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,u=null;for(let d of r.items){let{start:l,key:f,sep:h,value:m}=d,g=lm.resolveProps(l,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:s,parentIndent:r.indent,startOnNewline:!0}),w=!g.found;if(w){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",pm)),!g.anchor&&!g.tag&&!h){u=g.end,g.comment&&(a.comment?a.comment+=`
70
- `+g.comment:a.comment=g.comment);continue}(g.newlineAfterProp||OE.containsNewline(f))&&s(f??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else g.found?.indent!==r.indent&&s(c,"BAD_INDENT",pm);n.atKey=!0;let y=g.end,v=f?e(n,f,g,s):t(n,y,l,null,g,s);n.schema.compat&&fm.flowIndentCheck(r.indent,f,s),n.atKey=!1,jE.mapIncludes(n,a.items,v)&&s(y,"DUPLICATE_KEY","Map keys must be unique");let b=lm.resolveProps(h??[],{indicator:"map-value-ind",next:m,offset:v.range[2],onError:s,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=b.end,b.found){w&&(m?.type==="block-map"&&!b.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&g.start<b.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 k=m?e(n,m,b,s):t(n,c,h,null,b,s);n.schema.compat&&fm.flowIndentCheck(r.indent,m,s),c=k.range[2];let E=new dm.Pair(v,k);n.options.keepSourceTokens&&(E.srcToken=d),a.items.push(E)}else{w&&s(v.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),b.comment&&(v.comment?v.comment+=`
71
- `+b.comment:v.comment=b.comment);let k=new dm.Pair(v);n.options.keepSourceTokens&&(k.srcToken=d),a.items.push(k)}}return u&&u<c&&s(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,c,u??c],a}hm.resolveBlockMap=CE});var ym=C(gm=>{"use strict";var IE=dt(),DE=tr(),PE=Ca();function NE({composeNode:e,composeEmptyNode:t},n,r,s,o){let i=o?.nodeClass??IE.YAMLSeq,a=new i(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,u=null;for(let{start:d,value:l}of r.items){let f=DE.resolveProps(d,{indicator:"seq-item-ind",next:l,offset:c,onError:s,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||l)l?.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{u=f.end,f.comment&&(a.comment=f.comment);continue}let h=l?e(n,l,f,s):t(n,f.end,d,null,f,s);n.schema.compat&&PE.flowIndentCheck(r.indent,l,s),c=h.range[2],a.items.push(h)}return a.range=[r.offset,c,u??c],a}gm.resolveBlockSeq=NE});var rn=C(wm=>{"use strict";function TE(e,t,n,r){let s="";if(e){let o=!1,i="";for(let a of e){let{source:c,type:u}=a;switch(u){case"space":o=!0;break;case"comment":{n&&!o&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";s?s+=i+d:s=d,i="";break}case"newline":s&&(i+=c),o=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}t+=c.length}}return{comment:s,offset:t}}wm.resolveEnd=TE});var Em=C(bm=>{"use strict";var xE=z(),LE=at(),vm=ut(),FE=dt(),ME=rn(),km=tr(),_E=Qs(),zE=Ia(),Da="Block collections are not allowed within flow collections",Pa=e=>e&&(e.type==="block-map"||e.type==="block-seq");function qE({composeNode:e,composeEmptyNode:t},n,r,s,o){let i=r.start.source==="{",a=i?"flow map":"flow sequence",c=o?.nodeClass??(i?vm.YAMLMap:FE.YAMLSeq),u=new c(n.schema);u.flow=!0;let d=n.atRoot;d&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let l=r.offset+r.start.source.length;for(let w=0;w<r.items.length;++w){let y=r.items[w],{start:v,key:b,sep:k,value:E}=y,S=km.resolveProps(v,{flow:a,indicator:"explicit-key-ind",next:b??k?.[0],offset:l,onError:s,parentIndent:r.indent,startOnNewline:!1});if(!S.found){if(!S.anchor&&!S.tag&&!k&&!E){w===0&&S.comma?s(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):w<r.items.length-1&&s(S.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),S.comment&&(u.comment?u.comment+=`
72
- `+S.comment:u.comment=S.comment),l=S.end;continue}!i&&n.options.strict&&_E.containsNewline(b)&&s(b,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(w===0)S.comma&&s(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(S.comma||s(S.start,"MISSING_CHAR",`Missing , between ${a} items`),S.comment){let $="";e:for(let j of v)switch(j.type){case"comma":case"space":break;case"comment":$=j.source.substring(1);break e;default:break e}if($){let j=u.items[u.items.length-1];xE.isPair(j)&&(j=j.value??j.key),j.comment?j.comment+=`
73
- `+$:j.comment=$,S.comment=S.comment.substring($.length+1)}}if(!i&&!k&&!S.found){let $=E?e(n,E,S,s):t(n,S.end,k,null,S,s);u.items.push($),l=$.range[2],Pa(E)&&s($.range,"BLOCK_IN_FLOW",Da)}else{n.atKey=!0;let $=S.end,j=b?e(n,b,S,s):t(n,$,v,null,S,s);Pa(b)&&s(j.range,"BLOCK_IN_FLOW",Da),n.atKey=!1;let A=km.resolveProps(k??[],{flow:a,indicator:"map-value-ind",next:E,offset:j.range[2],onError:s,parentIndent:r.indent,startOnNewline:!1});if(A.found){if(!i&&!S.found&&n.options.strict){if(k)for(let x of k){if(x===A.found)break;if(x.type==="newline"){s(x,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}S.start<A.found.offset-1024&&s(A.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?s(E,"MISSING_CHAR",`Missing space after : in ${a}`):s(A.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let P=E?e(n,E,A,s):A.found?t(n,A.end,k,null,A,s):null;P?Pa(E)&&s(P.range,"BLOCK_IN_FLOW",Da):A.comment&&(j.comment?j.comment+=`
74
- `+A.comment:j.comment=A.comment);let D=new LE.Pair(j,P);if(n.options.keepSourceTokens&&(D.srcToken=y),i){let x=u;zE.mapIncludes(n,x.items,j)&&s($,"DUPLICATE_KEY","Map keys must be unique"),x.items.push(D)}else{let x=new vm.YAMLMap(n.schema);x.flow=!0,x.items.push(D);let J=(P??j).range;x.range=[j.range[0],J[1],J[2]],u.items.push(x)}l=P?P.range[2]:A.end}}let f=i?"}":"]",[h,...m]=r.end,g=l;if(h?.source===f)g=h.offset+h.source.length;else{let w=a[0].toUpperCase()+a.substring(1),y=d?`${w} must end with a ${f}`:`${w} in block collection must be sufficiently indented and end with a ${f}`;s(l,d?"MISSING_CHAR":"BAD_INDENT",y),h&&h.source.length!==1&&m.unshift(h)}if(m.length>0){let w=ME.resolveEnd(m,g,n.options.strict,s);w.comment&&(u.comment?u.comment+=`
75
- `+w.comment:u.comment=w.comment),u.range=[r.offset,g,w.offset]}else u.range=[r.offset,g,g];return u}bm.resolveFlowCollection=qE});var Sm=C(Rm=>{"use strict";var BE=z(),UE=Q(),KE=ut(),VE=dt(),WE=mm(),HE=ym(),YE=Em();function Na(e,t,n,r,s,o){let i=n.type==="block-map"?WE.resolveBlockMap(e,t,n,r,o):n.type==="block-seq"?HE.resolveBlockSeq(e,t,n,r,o):YE.resolveFlowCollection(e,t,n,r,o),a=i.constructor;return s==="!"||s===a.tagName?(i.tag=a.tagName,i):(s&&(i.tag=s),i)}function JE(e,t,n,r,s){let o=r.tag,i=o?t.directives.tagName(o.source,f=>s(o,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=r,m=f&&o?f.offset>o.offset?f:o:f??o;m&&(!h||h.offset<m.offset)&&s(m,"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(!o||!i||i==="!"||i===KE.YAMLMap.tagName&&a==="map"||i===VE.YAMLSeq.tagName&&a==="seq")return Na(e,t,n,s,i);let c=t.schema.tags.find(f=>f.tag===i&&f.collection===a);if(!c){let f=t.schema.knownTags[i];if(f?.collection===a)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?s(o,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):s(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),Na(e,t,n,s,i)}let u=Na(e,t,n,s,i,c),d=c.resolve?.(u,f=>s(o,"TAG_RESOLVE_FAILED",f),t.options)??u,l=BE.isNode(d)?d:new UE.Scalar(d);return l.range=u.range,l.tag=i,c?.format&&(l.format=c.format),l}Rm.composeCollection=JE});var xa=C($m=>{"use strict";var Ta=Q();function GE(e,t,n){let r=t.offset,s=QE(t,e.options.strict,n);if(!s)return{value:"",type:null,comment:"",range:[r,r,r]};let o=s.mode===">"?Ta.Scalar.BLOCK_FOLDED:Ta.Scalar.BLOCK_LITERAL,i=t.source?XE(t.source):[],a=i.length;for(let g=i.length-1;g>=0;--g){let w=i[g][1];if(w===""||w==="\r")a=g;else break}if(a===0){let g=s.chomp==="+"&&i.length>0?`
76
- `.repeat(Math.max(1,i.length-1)):"",w=r+s.length;return t.source&&(w+=t.source.length),{value:g,type:o,comment:s.comment,range:[r,w,w]}}let c=t.indent+s.indent,u=t.offset+s.length,d=0;for(let g=0;g<a;++g){let[w,y]=i[g];if(y===""||y==="\r")s.indent===0&&w.length>c&&(c=w.length);else{w.length<c&&n(u+w.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(c=w.length),d=g,c===0&&!e.atRoot&&n(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=w.length+y.length+1}for(let g=i.length-1;g>=a;--g)i[g][0].length>c&&(a=g+1);let l="",f="",h=!1;for(let g=0;g<d;++g)l+=i[g][0].slice(c)+`
77
- `;for(let g=d;g<a;++g){let[w,y]=i[g];u+=w.length+y.length+1;let v=y[y.length-1]==="\r";if(v&&(y=y.slice(0,-1)),y&&w.length<c){let k=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;n(u-y.length-(v?2:1),"BAD_INDENT",k),w=""}o===Ta.Scalar.BLOCK_LITERAL?(l+=f+w.slice(c)+y,f=`
78
- `):w.length>c||y[0]===" "?(f===" "?f=`
79
- `:!h&&f===`
80
- `&&(f=`
68
+ `}};er.YAMLError=Zn;er.YAMLParseError=Oa;er.YAMLWarning=ja;er.prettifyError=$E});var nr=C(um=>{"use strict";function AE(e,{flow:t,indicator:n,next:r,offset:s,onError:o,parentIndent:i,startOnNewline:a}){let c=!1,u=a,f=a,d="",l="",h=!1,m=!1,g=null,w=null,y=null,v=null,b=null,k=null,E=null;for(let j of e)switch(m&&(j.type!=="space"&&j.type!=="newline"&&j.type!=="comma"&&o(j.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),g&&(u&&j.type!=="comment"&&j.type!=="newline"&&o(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),g=null),j.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&j.source.includes(" ")&&(g=j),f=!0;break;case"comment":{f||o(j,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let A=j.source.substring(1)||" ";d?d+=l+A:d=A,l="",u=!1;break}case"newline":u?d?d+=j.source:(!k||n!=="seq-item-ind")&&(c=!0):l+=j.source,u=!0,h=!0,(w||y)&&(v=j),f=!0;break;case"anchor":w&&o(j,"MULTIPLE_ANCHORS","A node can have at most one anchor"),j.source.endsWith(":")&&o(j.offset+j.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),w=j,E??(E=j.offset),u=!1,f=!1,m=!0;break;case"tag":{y&&o(j,"MULTIPLE_TAGS","A node can have at most one tag"),y=j,E??(E=j.offset),u=!1,f=!1,m=!0;break}case n:(w||y)&&o(j,"BAD_PROP_ORDER",`Anchors and tags must be after the ${j.source} indicator`),k&&o(j,"UNEXPECTED_TOKEN",`Unexpected ${j.source} in ${t??"collection"}`),k=j,u=n==="seq-item-ind"||n==="explicit-key-ind",f=!1;break;case"comma":if(t){b&&o(j,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),b=j,u=!1,f=!1;break}default:o(j,"UNEXPECTED_TOKEN",`Unexpected ${j.type} token`),u=!1,f=!1}let S=e[e.length-1],$=S?S.offset+S.source.length:s;return m&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&o(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g&&(u&&g.indent<=i||r?.type==="block-map"||r?.type==="block-seq")&&o(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:b,found:k,spaceBefore:c,comment:d,hasNewline:h,anchor:w,tag:y,newlineAfterProp:v,end:$,start:E??$}}um.resolveProps=AE});var Xs=C(dm=>{"use strict";function Ca(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(Ca(t.key)||Ca(t.value))return!0}return!1;default:return!0}}dm.containsNewline=Ca});var Ia=C(lm=>{"use strict";var OE=Xs();function jE(e,t,n){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&OE.containsNewline(t)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}lm.flowIndentCheck=jE});var Da=C(pm=>{"use strict";var fm=z();function CE(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let s=typeof r=="function"?r:(o,i)=>o===i||fm.isScalar(o)&&fm.isScalar(i)&&o.value===i.value;return t.some(o=>s(o.key,n))}pm.mapIncludes=CE});var vm=C(wm=>{"use strict";var hm=ct(),IE=dt(),mm=nr(),DE=Xs(),gm=Ia(),PE=Da(),ym="All mapping items must start at the same column";function NE({composeNode:e,composeEmptyNode:t},n,r,s,o){let i=o?.nodeClass??IE.YAMLMap,a=new i(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,u=null;for(let f of r.items){let{start:d,key:l,sep:h,value:m}=f,g=mm.resolveProps(d,{indicator:"explicit-key-ind",next:l??h?.[0],offset:c,onError:s,parentIndent:r.indent,startOnNewline:!0}),w=!g.found;if(w){if(l&&(l.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in l&&l.indent!==r.indent&&s(c,"BAD_INDENT",ym)),!g.anchor&&!g.tag&&!h){u=g.end,g.comment&&(a.comment?a.comment+=`
70
+ `+g.comment:a.comment=g.comment);continue}(g.newlineAfterProp||DE.containsNewline(l))&&s(l??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else g.found?.indent!==r.indent&&s(c,"BAD_INDENT",ym);n.atKey=!0;let y=g.end,v=l?e(n,l,g,s):t(n,y,d,null,g,s);n.schema.compat&&gm.flowIndentCheck(r.indent,l,s),n.atKey=!1,PE.mapIncludes(n,a.items,v)&&s(y,"DUPLICATE_KEY","Map keys must be unique");let b=mm.resolveProps(h??[],{indicator:"map-value-ind",next:m,offset:v.range[2],onError:s,parentIndent:r.indent,startOnNewline:!l||l.type==="block-scalar"});if(c=b.end,b.found){w&&(m?.type==="block-map"&&!b.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&g.start<b.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 k=m?e(n,m,b,s):t(n,c,h,null,b,s);n.schema.compat&&gm.flowIndentCheck(r.indent,m,s),c=k.range[2];let E=new hm.Pair(v,k);n.options.keepSourceTokens&&(E.srcToken=f),a.items.push(E)}else{w&&s(v.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),b.comment&&(v.comment?v.comment+=`
71
+ `+b.comment:v.comment=b.comment);let k=new hm.Pair(v);n.options.keepSourceTokens&&(k.srcToken=f),a.items.push(k)}}return u&&u<c&&s(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,c,u??c],a}wm.resolveBlockMap=NE});var bm=C(km=>{"use strict";var TE=lt(),xE=nr(),LE=Ia();function FE({composeNode:e,composeEmptyNode:t},n,r,s,o){let i=o?.nodeClass??TE.YAMLSeq,a=new i(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,u=null;for(let{start:f,value:d}of r.items){let l=xE.resolveProps(f,{indicator:"seq-item-ind",next:d,offset:c,onError:s,parentIndent:r.indent,startOnNewline:!0});if(!l.found)if(l.anchor||l.tag||d)d?.type==="block-seq"?s(l.end,"BAD_INDENT","All sequence items must start at the same column"):s(c,"MISSING_CHAR","Sequence item without - indicator");else{u=l.end,l.comment&&(a.comment=l.comment);continue}let h=d?e(n,d,l,s):t(n,l.end,f,null,l,s);n.schema.compat&&LE.flowIndentCheck(r.indent,d,s),c=h.range[2],a.items.push(h)}return a.range=[r.offset,c,u??c],a}km.resolveBlockSeq=FE});var sn=C(Em=>{"use strict";function ME(e,t,n,r){let s="";if(e){let o=!1,i="";for(let a of e){let{source:c,type:u}=a;switch(u){case"space":o=!0;break;case"comment":{n&&!o&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";s?s+=i+f:s=f,i="";break}case"newline":s&&(i+=c),o=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}t+=c.length}}return{comment:s,offset:t}}Em.resolveEnd=ME});var Am=C($m=>{"use strict";var _E=z(),zE=ct(),Rm=dt(),qE=lt(),BE=sn(),Sm=nr(),UE=Xs(),KE=Da(),Pa="Block collections are not allowed within flow collections",Na=e=>e&&(e.type==="block-map"||e.type==="block-seq");function VE({composeNode:e,composeEmptyNode:t},n,r,s,o){let i=r.start.source==="{",a=i?"flow map":"flow sequence",c=o?.nodeClass??(i?Rm.YAMLMap:qE.YAMLSeq),u=new c(n.schema);u.flow=!0;let f=n.atRoot;f&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let d=r.offset+r.start.source.length;for(let w=0;w<r.items.length;++w){let y=r.items[w],{start:v,key:b,sep:k,value:E}=y,S=Sm.resolveProps(v,{flow:a,indicator:"explicit-key-ind",next:b??k?.[0],offset:d,onError:s,parentIndent:r.indent,startOnNewline:!1});if(!S.found){if(!S.anchor&&!S.tag&&!k&&!E){w===0&&S.comma?s(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):w<r.items.length-1&&s(S.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),S.comment&&(u.comment?u.comment+=`
72
+ `+S.comment:u.comment=S.comment),d=S.end;continue}!i&&n.options.strict&&UE.containsNewline(b)&&s(b,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(w===0)S.comma&&s(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(S.comma||s(S.start,"MISSING_CHAR",`Missing , between ${a} items`),S.comment){let $="";e:for(let j of v)switch(j.type){case"comma":case"space":break;case"comment":$=j.source.substring(1);break e;default:break e}if($){let j=u.items[u.items.length-1];_E.isPair(j)&&(j=j.value??j.key),j.comment?j.comment+=`
73
+ `+$:j.comment=$,S.comment=S.comment.substring($.length+1)}}if(!i&&!k&&!S.found){let $=E?e(n,E,S,s):t(n,S.end,k,null,S,s);u.items.push($),d=$.range[2],Na(E)&&s($.range,"BLOCK_IN_FLOW",Pa)}else{n.atKey=!0;let $=S.end,j=b?e(n,b,S,s):t(n,$,v,null,S,s);Na(b)&&s(j.range,"BLOCK_IN_FLOW",Pa),n.atKey=!1;let A=Sm.resolveProps(k??[],{flow:a,indicator:"map-value-ind",next:E,offset:j.range[2],onError:s,parentIndent:r.indent,startOnNewline:!1});if(A.found){if(!i&&!S.found&&n.options.strict){if(k)for(let x of k){if(x===A.found)break;if(x.type==="newline"){s(x,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}S.start<A.found.offset-1024&&s(A.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?s(E,"MISSING_CHAR",`Missing space after : in ${a}`):s(A.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let P=E?e(n,E,A,s):A.found?t(n,A.end,k,null,A,s):null;P?Na(E)&&s(P.range,"BLOCK_IN_FLOW",Pa):A.comment&&(j.comment?j.comment+=`
74
+ `+A.comment:j.comment=A.comment);let D=new zE.Pair(j,P);if(n.options.keepSourceTokens&&(D.srcToken=y),i){let x=u;KE.mapIncludes(n,x.items,j)&&s($,"DUPLICATE_KEY","Map keys must be unique"),x.items.push(D)}else{let x=new Rm.YAMLMap(n.schema);x.flow=!0,x.items.push(D);let J=(P??j).range;x.range=[j.range[0],J[1],J[2]],u.items.push(x)}d=P?P.range[2]:A.end}}let l=i?"}":"]",[h,...m]=r.end,g=d;if(h?.source===l)g=h.offset+h.source.length;else{let w=a[0].toUpperCase()+a.substring(1),y=f?`${w} must end with a ${l}`:`${w} in block collection must be sufficiently indented and end with a ${l}`;s(d,f?"MISSING_CHAR":"BAD_INDENT",y),h&&h.source.length!==1&&m.unshift(h)}if(m.length>0){let w=BE.resolveEnd(m,g,n.options.strict,s);w.comment&&(u.comment?u.comment+=`
75
+ `+w.comment:u.comment=w.comment),u.range=[r.offset,g,w.offset]}else u.range=[r.offset,g,g];return u}$m.resolveFlowCollection=VE});var jm=C(Om=>{"use strict";var WE=z(),HE=Q(),YE=dt(),JE=lt(),GE=vm(),QE=bm(),XE=Am();function Ta(e,t,n,r,s,o){let i=n.type==="block-map"?GE.resolveBlockMap(e,t,n,r,o):n.type==="block-seq"?QE.resolveBlockSeq(e,t,n,r,o):XE.resolveFlowCollection(e,t,n,r,o),a=i.constructor;return s==="!"||s===a.tagName?(i.tag=a.tagName,i):(s&&(i.tag=s),i)}function ZE(e,t,n,r,s){let o=r.tag,i=o?t.directives.tagName(o.source,l=>s(o,"TAG_RESOLVE_FAILED",l)):null;if(n.type==="block-seq"){let{anchor:l,newlineAfterProp:h}=r,m=l&&o?l.offset>o.offset?l:o:l??o;m&&(!h||h.offset<m.offset)&&s(m,"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(!o||!i||i==="!"||i===YE.YAMLMap.tagName&&a==="map"||i===JE.YAMLSeq.tagName&&a==="seq")return Ta(e,t,n,s,i);let c=t.schema.tags.find(l=>l.tag===i&&l.collection===a);if(!c){let l=t.schema.knownTags[i];if(l?.collection===a)t.schema.tags.push(Object.assign({},l,{default:!1})),c=l;else return l?s(o,"BAD_COLLECTION_TYPE",`${l.tag} used for ${a} collection, but expects ${l.collection??"scalar"}`,!0):s(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),Ta(e,t,n,s,i)}let u=Ta(e,t,n,s,i,c),f=c.resolve?.(u,l=>s(o,"TAG_RESOLVE_FAILED",l),t.options)??u,d=WE.isNode(f)?f:new HE.Scalar(f);return d.range=u.range,d.tag=i,c?.format&&(d.format=c.format),d}Om.composeCollection=ZE});var La=C(Cm=>{"use strict";var xa=Q();function eR(e,t,n){let r=t.offset,s=tR(t,e.options.strict,n);if(!s)return{value:"",type:null,comment:"",range:[r,r,r]};let o=s.mode===">"?xa.Scalar.BLOCK_FOLDED:xa.Scalar.BLOCK_LITERAL,i=t.source?nR(t.source):[],a=i.length;for(let g=i.length-1;g>=0;--g){let w=i[g][1];if(w===""||w==="\r")a=g;else break}if(a===0){let g=s.chomp==="+"&&i.length>0?`
76
+ `.repeat(Math.max(1,i.length-1)):"",w=r+s.length;return t.source&&(w+=t.source.length),{value:g,type:o,comment:s.comment,range:[r,w,w]}}let c=t.indent+s.indent,u=t.offset+s.length,f=0;for(let g=0;g<a;++g){let[w,y]=i[g];if(y===""||y==="\r")s.indent===0&&w.length>c&&(c=w.length);else{w.length<c&&n(u+w.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(c=w.length),f=g,c===0&&!e.atRoot&&n(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=w.length+y.length+1}for(let g=i.length-1;g>=a;--g)i[g][0].length>c&&(a=g+1);let d="",l="",h=!1;for(let g=0;g<f;++g)d+=i[g][0].slice(c)+`
77
+ `;for(let g=f;g<a;++g){let[w,y]=i[g];u+=w.length+y.length+1;let v=y[y.length-1]==="\r";if(v&&(y=y.slice(0,-1)),y&&w.length<c){let k=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;n(u-y.length-(v?2:1),"BAD_INDENT",k),w=""}o===xa.Scalar.BLOCK_LITERAL?(d+=l+w.slice(c)+y,l=`
78
+ `):w.length>c||y[0]===" "?(l===" "?l=`
79
+ `:!h&&l===`
80
+ `&&(l=`
81
81
 
82
- `),l+=f+w.slice(c)+y,f=`
83
- `,h=!0):y===""?f===`
84
- `?l+=`
85
- `:f=`
86
- `:(l+=f+y,f=" ",h=!1)}switch(s.chomp){case"-":break;case"+":for(let g=a;g<i.length;++g)l+=`
87
- `+i[g][0].slice(c);l[l.length-1]!==`
88
- `&&(l+=`
89
- `);break;default:l+=`
90
- `}let m=r+s.length+t.source.length;return{value:l,type:o,comment:s.comment,range:[r,m,m]}}function QE({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],o=s[0],i=0,a="",c=-1;for(let f=1;f<s.length;++f){let h=s[f];if(!a&&(h==="-"||h==="+"))a=h;else{let m=Number(h);!i&&m?i=m:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let u=!1,d="",l=s.length;for(let f=1;f<t.length;++f){let h=t[f];switch(h.type){case"space":u=!0;case"newline":l+=h.source.length;break;case"comment":n&&!u&&r(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),l+=h.source.length,d=h.source.substring(1);break;case"error":r(h,"UNEXPECTED_TOKEN",h.message),l+=h.source.length;break;default:{let m=`Unexpected token in block scalar header: ${h.type}`;r(h,"UNEXPECTED_TOKEN",m);let g=h.source;g&&typeof g=="string"&&(l+=g.length)}}}return{mode:o,indent:i,chomp:a,comment:d,length:l}}function XE(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),o=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let i=1;i<t.length;i+=2)o.push([t[i],t[i+1]]);return o}$m.resolveBlockScalar=GE});var Fa=C(Om=>{"use strict";var La=Q(),ZE=rn();function eR(e,t,n){let{offset:r,type:s,source:o,end:i}=e,a,c,u=(f,h,m)=>n(r+f,h,m);switch(s){case"scalar":a=La.Scalar.PLAIN,c=tR(o,u);break;case"single-quoted-scalar":a=La.Scalar.QUOTE_SINGLE,c=nR(o,u);break;case"double-quoted-scalar":a=La.Scalar.QUOTE_DOUBLE,c=rR(o,u);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[r,r+o.length,r+o.length]}}let d=r+o.length,l=ZE.resolveEnd(i,d,t,n);return{value:c,type:a,comment:l.comment,range:[r,d,l.offset]}}function tR(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}`),Am(e)}function nR(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Am(e.slice(1,-1)).replace(/''/g,"'")}function Am(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 o=n[1].replace(r,""),i=" ",a=t.lastIndex;for(;n=t.exec(e);){let u=n[1].replace(s,"");u===""?i===`
82
+ `),d+=l+w.slice(c)+y,l=`
83
+ `,h=!0):y===""?l===`
84
+ `?d+=`
85
+ `:l=`
86
+ `:(d+=l+y,l=" ",h=!1)}switch(s.chomp){case"-":break;case"+":for(let g=a;g<i.length;++g)d+=`
87
+ `+i[g][0].slice(c);d[d.length-1]!==`
88
+ `&&(d+=`
89
+ `);break;default:d+=`
90
+ `}let m=r+s.length+t.source.length;return{value:d,type:o,comment:s.comment,range:[r,m,m]}}function tR({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],o=s[0],i=0,a="",c=-1;for(let l=1;l<s.length;++l){let h=s[l];if(!a&&(h==="-"||h==="+"))a=h;else{let m=Number(h);!i&&m?i=m:c===-1&&(c=e+l)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let u=!1,f="",d=s.length;for(let l=1;l<t.length;++l){let h=t[l];switch(h.type){case"space":u=!0;case"newline":d+=h.source.length;break;case"comment":n&&!u&&r(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=h.source.length,f=h.source.substring(1);break;case"error":r(h,"UNEXPECTED_TOKEN",h.message),d+=h.source.length;break;default:{let m=`Unexpected token in block scalar header: ${h.type}`;r(h,"UNEXPECTED_TOKEN",m);let g=h.source;g&&typeof g=="string"&&(d+=g.length)}}}return{mode:o,indent:i,chomp:a,comment:f,length:d}}function nR(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),o=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let i=1;i<t.length;i+=2)o.push([t[i],t[i+1]]);return o}Cm.resolveBlockScalar=eR});var Ma=C(Dm=>{"use strict";var Fa=Q(),rR=sn();function sR(e,t,n){let{offset:r,type:s,source:o,end:i}=e,a,c,u=(l,h,m)=>n(r+l,h,m);switch(s){case"scalar":a=Fa.Scalar.PLAIN,c=oR(o,u);break;case"single-quoted-scalar":a=Fa.Scalar.QUOTE_SINGLE,c=iR(o,u);break;case"double-quoted-scalar":a=Fa.Scalar.QUOTE_DOUBLE,c=aR(o,u);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[r,r+o.length,r+o.length]}}let f=r+o.length,d=rR.resolveEnd(i,f,t,n);return{value:c,type:a,comment:d.comment,range:[r,f,d.offset]}}function oR(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}`),Im(e)}function iR(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Im(e.slice(1,-1)).replace(/''/g,"'")}function Im(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 o=n[1].replace(r,""),i=" ",a=t.lastIndex;for(;n=t.exec(e);){let u=n[1].replace(s,"");u===""?i===`
91
91
  `?o+=i:i=`
92
- `:(o+=i+u,i=" "),a=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=a,n=c.exec(e),o+i+(n?.[1]??"")}function rR(e,t){let n="";for(let r=1;r<e.length-1;++r){let s=e[r];if(!(s==="\r"&&e[r+1]===`
92
+ `:(o+=i+u,i=" "),a=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=a,n=c.exec(e),o+i+(n?.[1]??"")}function aR(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:o,offset:i}=sR(e,r);n+=o,r=i}else if(s==="\\"){let o=e[++r],i=oR[o];if(i)n+=i;else if(o===`
94
+ `){let{fold:o,offset:i}=cR(e,r);n+=o,r=i}else if(s==="\\"){let o=e[++r],i=uR[o];if(i)n+=i;else if(o===`
95
95
  `)for(o=e[r+1];o===" "||o===" ";)o=e[++r+1];else if(o==="\r"&&e[r+1]===`
96
- `)for(o=e[++r+1];o===" "||o===" ";)o=e[++r+1];else if(o==="x"||o==="u"||o==="U"){let a=o==="x"?2:o==="u"?4:8;n+=iR(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 o=r,i=e[r+1];for(;i===" "||i===" ";)i=e[++r+1];i!==`
96
+ `)for(o=e[++r+1];o===" "||o===" ";)o=e[++r+1];else if(o==="x"||o==="u"||o==="U"){let a=o==="x"?2:o==="u"?4:8;n+=dR(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 o=r,i=e[r+1];for(;i===" "||i===" ";)i=e[++r+1];i!==`
97
97
  `&&!(i==="\r"&&e[r+2]===`
98
- `)&&(n+=r>o?e.slice(o,r+1):s)}else n+=s}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function sR(e,t){let n="",r=e[t+1];for(;(r===" "||r===" "||r===`
98
+ `)&&(n+=r>o?e.slice(o,r+1):s)}else n+=s}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function cR(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 oR={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 iR(e,t,n,r){let s=e.substr(t,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;try{return String.fromCodePoint(i)}catch{let a=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}Om.resolveFlowScalar=eR});var Im=C(Cm=>{"use strict";var It=z(),jm=Q(),aR=xa(),cR=Fa();function uR(e,t,n,r){let{value:s,type:o,comment:i,range:a}=t.type==="block-scalar"?aR.resolveBlockScalar(e,t,r):cR.resolveFlowScalar(t,e.options.strict,r),c=n?e.directives.tagName(n.source,l=>r(n,"TAG_RESOLVE_FAILED",l)):null,u;e.options.stringKeys&&e.atKey?u=e.schema[It.SCALAR]:c?u=dR(e.schema,s,c,n,r):t.type==="scalar"?u=lR(e,s,t,r):u=e.schema[It.SCALAR];let d;try{let l=u.resolve(s,f=>r(n??t,"TAG_RESOLVE_FAILED",f),e.options);d=It.isScalar(l)?l:new jm.Scalar(l)}catch(l){let f=l instanceof Error?l.message:String(l);r(n??t,"TAG_RESOLVE_FAILED",f),d=new jm.Scalar(s)}return d.range=a,d.source=s,o&&(d.type=o),c&&(d.tag=c),u.format&&(d.format=u.format),i&&(d.comment=i),d}function dR(e,t,n,r,s){if(n==="!")return e[It.SCALAR];let o=[];for(let a of e.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)o.push(a);else return a;for(let a of o)if(a.test?.test(t))return a;let i=e.knownTags[n];return i&&!i.collection?(e.tags.push(Object.assign({},i,{default:!1,test:void 0})),i):(s(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[It.SCALAR])}function lR({atKey:e,directives:t,schema:n},r,s,o){let i=n.tags.find(a=>(a.default===!0||e&&a.default==="key")&&a.test?.test(r))||n[It.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(r))??n[It.SCALAR];if(i.tag!==a.tag){let c=t.tagString(i.tag),u=t.tagString(a.tag),d=`Value may be parsed as either ${c} or ${u}`;o(s,"TAG_RESOLVE_FAILED",d,!0)}}return i}Cm.composeScalar=uR});var Pm=C(Dm=>{"use strict";function fR(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}Dm.emptyScalarPosition=fR});var xm=C(_a=>{"use strict";var pR=xn(),hR=z(),mR=Sm(),Nm=Im(),gR=rn(),yR=Pm(),wR={composeNode:Tm,composeEmptyNode:Ma};function Tm(e,t,n,r){let s=e.atKey,{spaceBefore:o,comment:i,anchor:a,tag:c}=n,u,d=!0;switch(t.type){case"alias":u=vR(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":u=Nm.composeScalar(e,t,c,r),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{u=mR.composeCollection(wR,e,t,n,r),a&&(u.anchor=a.source.substring(1))}catch(l){let f=l instanceof Error?l.message:String(l);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let l=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",l),d=!1}}return u??(u=Ma(e,t.offset,void 0,null,n,r)),a&&u.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&e.options.stringKeys&&(!hR.isScalar(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(u.spaceBefore=!0),i&&(t.type==="scalar"&&t.source===""?u.comment=i:u.commentBefore=i),e.options.keepSourceTokens&&d&&(u.srcToken=t),u}function Ma(e,t,n,r,{spaceBefore:s,comment:o,anchor:i,tag:a,end:c},u){let d={type:"scalar",offset:yR.emptyScalarPosition(t,n,r),indent:-1,source:""},l=Nm.composeScalar(e,d,a,u);return i&&(l.anchor=i.source.substring(1),l.anchor===""&&u(i,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(l.spaceBefore=!0),o&&(l.comment=o,l.range[2]=c),l}function vR({options:e},{offset:t,source:n,end:r},s){let o=new pR.Alias(n.substring(1));o.source===""&&s(t,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&s(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=t+n.length,a=gR.resolveEnd(r,i,e.strict,s);return o.range=[t,i,a.offset],a.comment&&(o.comment=a.comment),o}_a.composeEmptyNode=Ma;_a.composeNode=Tm});var Mm=C(Fm=>{"use strict";var kR=Qn(),Lm=xm(),bR=rn(),ER=tr();function RR(e,t,{offset:n,start:r,value:s,end:o},i){let a=Object.assign({_directives:t},e),c=new kR.Document(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=ER.resolveProps(r,{indicator:"doc-start",next:s??o?.[0],offset:n,onError:i,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!d.hasNewline&&i(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?Lm.composeNode(u,s,d,i):Lm.composeEmptyNode(u,d.end,r,null,d,i);let l=c.contents.range[2],f=bR.resolveEnd(o,l,!1,i);return f.comment&&(c.comment=f.comment),c.range=[n,l,f.offset],c}Fm.composeDoc=RR});var qa=C(qm=>{"use strict";var SR=gr("process"),$R=Ai(),AR=Qn(),nr=er(),_m=z(),OR=Mm(),jR=rn();function rr(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 zm(e){let t="",n=!1,r=!1;for(let s=0;s<e.length;++s){let o=e[s];switch(o[0]){case"#":t+=(t===""?"":r?`
102
+ `),t+=1,r=e[t+1];return n||(n=" "),{fold:n,offset:t}}var uR={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 dR(e,t,n,r){let s=e.substr(t,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;try{return String.fromCodePoint(i)}catch{let a=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}Dm.resolveFlowScalar=sR});var Tm=C(Nm=>{"use strict";var Dt=z(),Pm=Q(),lR=La(),fR=Ma();function pR(e,t,n,r){let{value:s,type:o,comment:i,range:a}=t.type==="block-scalar"?lR.resolveBlockScalar(e,t,r):fR.resolveFlowScalar(t,e.options.strict,r),c=n?e.directives.tagName(n.source,d=>r(n,"TAG_RESOLVE_FAILED",d)):null,u;e.options.stringKeys&&e.atKey?u=e.schema[Dt.SCALAR]:c?u=hR(e.schema,s,c,n,r):t.type==="scalar"?u=mR(e,s,t,r):u=e.schema[Dt.SCALAR];let f;try{let d=u.resolve(s,l=>r(n??t,"TAG_RESOLVE_FAILED",l),e.options);f=Dt.isScalar(d)?d:new Pm.Scalar(d)}catch(d){let l=d instanceof Error?d.message:String(d);r(n??t,"TAG_RESOLVE_FAILED",l),f=new Pm.Scalar(s)}return f.range=a,f.source=s,o&&(f.type=o),c&&(f.tag=c),u.format&&(f.format=u.format),i&&(f.comment=i),f}function hR(e,t,n,r,s){if(n==="!")return e[Dt.SCALAR];let o=[];for(let a of e.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)o.push(a);else return a;for(let a of o)if(a.test?.test(t))return a;let i=e.knownTags[n];return i&&!i.collection?(e.tags.push(Object.assign({},i,{default:!1,test:void 0})),i):(s(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[Dt.SCALAR])}function mR({atKey:e,directives:t,schema:n},r,s,o){let i=n.tags.find(a=>(a.default===!0||e&&a.default==="key")&&a.test?.test(r))||n[Dt.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(r))??n[Dt.SCALAR];if(i.tag!==a.tag){let c=t.tagString(i.tag),u=t.tagString(a.tag),f=`Value may be parsed as either ${c} or ${u}`;o(s,"TAG_RESOLVE_FAILED",f,!0)}}return i}Nm.composeScalar=pR});var Lm=C(xm=>{"use strict";function gR(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}xm.emptyScalarPosition=gR});var _m=C(za=>{"use strict";var yR=Ln(),wR=z(),vR=jm(),Fm=Tm(),kR=sn(),bR=Lm(),ER={composeNode:Mm,composeEmptyNode:_a};function Mm(e,t,n,r){let s=e.atKey,{spaceBefore:o,comment:i,anchor:a,tag:c}=n,u,f=!0;switch(t.type){case"alias":u=RR(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":u=Fm.composeScalar(e,t,c,r),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{u=vR.composeCollection(ER,e,t,n,r),a&&(u.anchor=a.source.substring(1))}catch(d){let l=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",l)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),f=!1}}return u??(u=_a(e,t.offset,void 0,null,n,r)),a&&u.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&e.options.stringKeys&&(!wR.isScalar(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(u.spaceBefore=!0),i&&(t.type==="scalar"&&t.source===""?u.comment=i:u.commentBefore=i),e.options.keepSourceTokens&&f&&(u.srcToken=t),u}function _a(e,t,n,r,{spaceBefore:s,comment:o,anchor:i,tag:a,end:c},u){let f={type:"scalar",offset:bR.emptyScalarPosition(t,n,r),indent:-1,source:""},d=Fm.composeScalar(e,f,a,u);return i&&(d.anchor=i.source.substring(1),d.anchor===""&&u(i,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(d.spaceBefore=!0),o&&(d.comment=o,d.range[2]=c),d}function RR({options:e},{offset:t,source:n,end:r},s){let o=new yR.Alias(n.substring(1));o.source===""&&s(t,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&s(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=t+n.length,a=kR.resolveEnd(r,i,e.strict,s);return o.range=[t,i,a.offset],a.comment&&(o.comment=a.comment),o}za.composeEmptyNode=_a;za.composeNode=Mm});var Bm=C(qm=>{"use strict";var SR=Xn(),zm=_m(),$R=sn(),AR=nr();function OR(e,t,{offset:n,start:r,value:s,end:o},i){let a=Object.assign({_directives:t},e),c=new SR.Document(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=AR.resolveProps(r,{indicator:"doc-start",next:s??o?.[0],offset:n,onError:i,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!f.hasNewline&&i(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?zm.composeNode(u,s,f,i):zm.composeEmptyNode(u,f.end,r,null,f,i);let d=c.contents.range[2],l=$R.resolveEnd(o,d,!1,i);return l.comment&&(c.comment=l.comment),c.range=[n,d,l.offset],c}qm.composeDoc=OR});var Ba=C(Vm=>{"use strict";var jR=yr("process"),CR=Oi(),IR=Xn(),rr=tr(),Um=z(),DR=Bm(),PR=sn();function sr(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 Km(e){let t="",n=!1,r=!1;for(let s=0;s<e.length;++s){let o=e[s];switch(o[0]){case"#":t+=(t===""?"":r?`
104
104
 
105
105
  `:`
106
- `)+(o.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 za=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,s,o)=>{let i=rr(n);o?this.warnings.push(new nr.YAMLWarning(i,r,s)):this.errors.push(new nr.YAMLParseError(i,r,s))},this.directives=new $R.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:r,afterEmptyLine:s}=zm(this.prelude);if(r){let o=t.contents;if(n)t.comment=t.comment?`${t.comment}
107
- ${r}`:r;else if(s||t.directives.docStart||!o)t.commentBefore=r;else if(_m.isCollection(o)&&!o.flow&&o.items.length>0){let i=o.items[0];_m.isPair(i)&&(i=i.key);let a=i.commentBefore;i.commentBefore=a?`${r}
106
+ `)+(o.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 qa=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,s,o)=>{let i=sr(n);o?this.warnings.push(new rr.YAMLWarning(i,r,s)):this.errors.push(new rr.YAMLParseError(i,r,s))},this.directives=new CR.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:r,afterEmptyLine:s}=Km(this.prelude);if(r){let o=t.contents;if(n)t.comment=t.comment?`${t.comment}
107
+ ${r}`:r;else if(s||t.directives.docStart||!o)t.commentBefore=r;else if(Um.isCollection(o)&&!o.flow&&o.items.length>0){let i=o.items[0];Um.isPair(i)&&(i=i.key);let a=i.commentBefore;i.commentBefore=a?`${r}
108
108
  ${a}`:r}else{let i=o.commentBefore;o.commentBefore=i?`${r}
109
- ${i}`:r}}if(n){for(let o=0;o<this.errors.length;++o)t.errors.push(this.errors[o]);for(let o=0;o<this.warnings.length;++o)t.warnings.push(this.warnings[o])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:zm(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(SR.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(n,r,s)=>{let o=rr(t);o[0]+=n,this.onError(o,"BAD_DIRECTIVE",r,s)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=OR.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 nr.YAMLParseError(rr(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 nr.YAMLParseError(rr(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=jR.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 nr.YAMLParseError(rr(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 AR.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}}};qm.Composer=za});var Km=C(Xs=>{"use strict";var CR=xa(),IR=Fa(),DR=er(),Bm=zn();function PR(e,t=!0,n){if(e){let r=(s,o,i)=>{let a=typeof s=="number"?s:Array.isArray(s)?s[0]:s.offset;if(n)n(a,o,i);else throw new DR.YAMLParseError([a,a+1],o,i)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return IR.resolveFlowScalar(e,t,r);case"block-scalar":return CR.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function NR(e,t){let{implicitKey:n=!1,indent:r,inFlow:s=!1,offset:o=-1,type:i="PLAIN"}=t,a=Bm.stringifyString({type:i,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
+ ${i}`:r}}if(n){for(let o=0;o<this.errors.length;++o)t.errors.push(this.errors[o]);for(let o=0;o<this.warnings.length;++o)t.warnings.push(this.warnings[o])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Km(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(jR.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(n,r,s)=>{let o=sr(t);o[0]+=n,this.onError(o,"BAD_DIRECTIVE",r,s)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=DR.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 rr.YAMLParseError(sr(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 rr.YAMLParseError(sr(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=PR.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 rr.YAMLParseError(sr(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 IR.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}}};Vm.Composer=qa});var Ym=C(Zs=>{"use strict";var NR=La(),TR=Ma(),xR=tr(),Wm=qn();function LR(e,t=!0,n){if(e){let r=(s,o,i)=>{let a=typeof s=="number"?s:Array.isArray(s)?s[0]:s.offset;if(n)n(a,o,i);else throw new xR.YAMLParseError([a,a+1],o,i)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return TR.resolveFlowScalar(e,t,r);case"block-scalar":return NR.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function FR(e,t){let{implicitKey:n=!1,indent:r,inFlow:s=!1,offset:o=-1,type:i="PLAIN"}=t,a=Wm.stringifyString({type:i,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 u=a.indexOf(`
112
- `),d=a.substring(0,u),l=a.substring(u+1)+`
113
- `,f=[{type:"block-scalar-header",offset:o,indent:r,source:d}];return Um(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
114
- `}),{type:"block-scalar",offset:o,indent:r,props:f,source:l}}case'"':return{type:"double-quoted-scalar",offset:o,indent:r,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:o,indent:r,source:a,end:c};default:return{type:"scalar",offset:o,indent:r,source:a,end:c}}}function TR(e,t,n={}){let{afterKey:r=!1,implicitKey:s=!1,inFlow:o=!1,type:i}=n,a="indent"in e?e.indent:null;if(r&&typeof a=="number"&&(a+=2),!i)switch(e.type){case"single-quoted-scalar":i="QUOTE_SINGLE";break;case"double-quoted-scalar":i="QUOTE_DOUBLE";break;case"block-scalar":{let u=e.props[0];if(u.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i=u.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:i="PLAIN"}let c=Bm.stringifyString({type:i,value:t},{implicitKey:s||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":xR(e,c);break;case'"':Ba(e,c,"double-quoted-scalar");break;case"'":Ba(e,c,"single-quoted-scalar");break;default:Ba(e,c,"scalar")}}function xR(e,t){let n=t.indexOf(`
112
+ `),f=a.substring(0,u),d=a.substring(u+1)+`
113
+ `,l=[{type:"block-scalar-header",offset:o,indent:r,source:f}];return Hm(l,c)||l.push({type:"newline",offset:-1,indent:r,source:`
114
+ `}),{type:"block-scalar",offset:o,indent:r,props:l,source:d}}case'"':return{type:"double-quoted-scalar",offset:o,indent:r,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:o,indent:r,source:a,end:c};default:return{type:"scalar",offset:o,indent:r,source:a,end:c}}}function MR(e,t,n={}){let{afterKey:r=!1,implicitKey:s=!1,inFlow:o=!1,type:i}=n,a="indent"in e?e.indent:null;if(r&&typeof a=="number"&&(a+=2),!i)switch(e.type){case"single-quoted-scalar":i="QUOTE_SINGLE";break;case"double-quoted-scalar":i="QUOTE_DOUBLE";break;case"block-scalar":{let u=e.props[0];if(u.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i=u.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:i="PLAIN"}let c=Wm.stringifyString({type:i,value:t},{implicitKey:s||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":_R(e,c);break;case'"':Ua(e,c,"double-quoted-scalar");break;case"'":Ua(e,c,"single-quoted-scalar");break;default:Ua(e,c,"scalar")}}function _R(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 o=e.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=r,e.source=s}else{let{offset:o}=e,i="indent"in e?e.indent:-1,a=[{type:"block-scalar-header",offset:o,indent:i,source:r}];Um(a,"end"in e?e.end:void 0)||a.push({type:"newline",offset:-1,indent:i,source:`
117
- `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:i,props:a,source:s})}}function Um(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 Ba(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 o of r)o.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(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(e))o!=="type"&&o!=="offset"&&delete e[o];Object.assign(e,{type:n,indent:r,source:t,end:s})}}}Xs.createScalarToken=NR;Xs.resolveAsScalar=PR;Xs.setScalarValue=TR});var Wm=C(Vm=>{"use strict";var LR=e=>"type"in e?eo(e):Zs(e);function eo(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=eo(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=Zs(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=Zs(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=Zs(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 Zs({start:e,key:t,sep:n,value:r}){let s="";for(let o of e)s+=o.source;if(t&&(s+=eo(t)),n)for(let o of n)s+=o.source;return r&&(s+=eo(r)),s}Vm.stringify=LR});var Gm=C(Jm=>{"use strict";var Ua=Symbol("break visit"),FR=Symbol("skip children"),Hm=Symbol("remove item");function Dt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Ym(Object.freeze([]),e,t)}Dt.BREAK=Ua;Dt.SKIP=FR;Dt.REMOVE=Hm;Dt.itemAtPath=(e,t)=>{let n=e;for(let[r,s]of t){let o=n?.[r];if(o&&"items"in o)n=o.items[s];else return}return n};Dt.parentCollection=(e,t)=>{let n=Dt.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 Ym(e,t,n){let r=n(t,e);if(typeof r=="symbol")return r;for(let s of["key","value"]){let o=t[s];if(o&&"items"in o){for(let i=0;i<o.items.length;++i){let a=Ym(Object.freeze(e.concat([[s,i]])),o.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Ua)return Ua;a===Hm&&(o.items.splice(i,1),i-=1)}}typeof r=="function"&&s==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}Jm.visit=Dt});var to=C(ge=>{"use strict";var Ka=Km(),MR=Wm(),_R=Gm(),Va="\uFEFF",Wa="",Ha="",Ya="",zR=e=>!!e&&"items"in e,qR=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function BR(e){switch(e){case Va:return"<BOM>";case Wa:return"<DOC>";case Ha:return"<FLOW_END>";case Ya:return"<SCALAR>";default:return JSON.stringify(e)}}function UR(e){switch(e){case Va:return"byte-order-mark";case Wa:return"doc-mode";case Ha:return"flow-error-end";case Ya:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
116
+ `;if(e.type==="block-scalar"){let o=e.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=r,e.source=s}else{let{offset:o}=e,i="indent"in e?e.indent:-1,a=[{type:"block-scalar-header",offset:o,indent:i,source:r}];Hm(a,"end"in e?e.end:void 0)||a.push({type:"newline",offset:-1,indent:i,source:`
117
+ `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:i,props:a,source:s})}}function Hm(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 Ua(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 o of r)o.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(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(e))o!=="type"&&o!=="offset"&&delete e[o];Object.assign(e,{type:n,indent:r,source:t,end:s})}}}Zs.createScalarToken=FR;Zs.resolveAsScalar=LR;Zs.setScalarValue=MR});var Gm=C(Jm=>{"use strict";var zR=e=>"type"in e?to(e):eo(e);function to(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=to(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=eo(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=eo(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=eo(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 eo({start:e,key:t,sep:n,value:r}){let s="";for(let o of e)s+=o.source;if(t&&(s+=to(t)),n)for(let o of n)s+=o.source;return r&&(s+=to(r)),s}Jm.stringify=zR});var eg=C(Zm=>{"use strict";var Ka=Symbol("break visit"),qR=Symbol("skip children"),Qm=Symbol("remove item");function Pt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Xm(Object.freeze([]),e,t)}Pt.BREAK=Ka;Pt.SKIP=qR;Pt.REMOVE=Qm;Pt.itemAtPath=(e,t)=>{let n=e;for(let[r,s]of t){let o=n?.[r];if(o&&"items"in o)n=o.items[s];else return}return n};Pt.parentCollection=(e,t)=>{let n=Pt.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 Xm(e,t,n){let r=n(t,e);if(typeof r=="symbol")return r;for(let s of["key","value"]){let o=t[s];if(o&&"items"in o){for(let i=0;i<o.items.length;++i){let a=Xm(Object.freeze(e.concat([[s,i]])),o.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Ka)return Ka;a===Qm&&(o.items.splice(i,1),i-=1)}}typeof r=="function"&&s==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}Zm.visit=Pt});var no=C(ge=>{"use strict";var Va=Ym(),BR=Gm(),UR=eg(),Wa="\uFEFF",Ha="",Ya="",Ja="",KR=e=>!!e&&"items"in e,VR=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function WR(e){switch(e){case Wa:return"<BOM>";case Ha:return"<DOC>";case Ya:return"<FLOW_END>";case Ja:return"<SCALAR>";default:return JSON.stringify(e)}}function HR(e){switch(e){case Wa:return"byte-order-mark";case Ha:return"doc-mode";case Ya:return"flow-error-end";case Ja: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}ge.createScalarToken=Ka.createScalarToken;ge.resolveAsScalar=Ka.resolveAsScalar;ge.setScalarValue=Ka.setScalarValue;ge.stringify=MR.stringify;ge.visit=_R.visit;ge.BOM=Va;ge.DOCUMENT=Wa;ge.FLOW_END=Ha;ge.SCALAR=Ya;ge.isCollection=zR;ge.isScalar=qR;ge.prettyToken=BR;ge.tokenType=UR});var Qa=C(Xm=>{"use strict";var sr=to();function $e(e){switch(e){case void 0:case" ":case`
121
- `:case"\r":case" ":return!0;default:return!1}}var Qm=new Set("0123456789ABCDEFabcdef"),KR=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),no=new Set(",[]{}"),VR=new Set(` ,[]{}
122
- \r `),Ja=e=>!e||VR.has(e),Ga=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}ge.createScalarToken=Va.createScalarToken;ge.resolveAsScalar=Va.resolveAsScalar;ge.setScalarValue=Va.setScalarValue;ge.stringify=BR.stringify;ge.visit=UR.visit;ge.BOM=Wa;ge.DOCUMENT=Ha;ge.FLOW_END=Ya;ge.SCALAR=Ja;ge.isCollection=KR;ge.isScalar=VR;ge.prettyToken=WR;ge.tokenType=HR});var Xa=C(ng=>{"use strict";var or=no();function $e(e){switch(e){case void 0:case" ":case`
121
+ `:case"\r":case" ":return!0;default:return!1}}var tg=new Set("0123456789ABCDEFabcdef"),YR=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ro=new Set(",[]{}"),JR=new Set(` ,[]{}
122
+ \r `),Ga=e=>!e||JR.has(e),Qa=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
126
  `||r>=this.indentNext||!n&&!this.atEnd?t+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&$e(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]===sr.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let n=t.length,r=t.indexOf("#");for(;r!==-1;){let o=t[r-1];if(o===" "||o===" "){n=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let o=t[n-1];if(o===" "||o===" ")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 sr.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==="...")&&$e(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&&!$e(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===":")&&$e(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(Ja),"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("..."))&&$e(s[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield sr.FLOW_END,yield*this.parseLineStart();let o=0;for(;s[o]===",";)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),s[o]){case void 0:return"flow";case"#":return yield*this.pushCount(s.length-o),"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(Ja),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||$e(i)||i===",")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 o=0;for(;this.buffer[n-1-o]==="\\";)o+=1;if(o%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),s=r.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]===or.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let n=t.length,r=t.indexOf("#");for(;r!==-1;){let o=t[r-1];if(o===" "||o===" "){n=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let o=t[n-1];if(o===" "||o===" ")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 or.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==="...")&&$e(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&&!$e(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===":")&&$e(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(Ga),"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("..."))&&$e(s[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield or.FLOW_END,yield*this.parseLineStart();let o=0;for(;s[o]===",";)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),s[o]){case void 0:return"flow";case"#":return yield*this.pushCount(s.length-o),"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(Ga),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||$e(i)||i===",")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 o=0;for(;this.buffer[n-1-o]==="\\";)o+=1;if(o%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 o=this.continueScalar(s+1);if(o===-1)break;s=r.indexOf(`
129
129
  `,o)}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=>$e(n)||n==="#")}*parseBlockScalar(){let t=this.pos-1,n=0,r;e:for(let o=this.pos;r=this.buffer[o];++o)switch(r){case" ":n+=1;break;case`
130
130
  `:t=o,n=0;break;case"\r":{let i=this.buffer[o+1];if(!i&&!this.atEnd)return this.setNext("block-scalar");if(i===`
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 o=this.continueScalar(t+1);if(o===-1)break;t=this.buffer.indexOf(`
132
132
  `,o)}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 o=t-1,i=this.buffer[o];i==="\r"&&(i=this.buffer[--o]);let a=o;for(;i===" ";)i=this.buffer[--o];if(i===`
134
- `&&o>=this.pos&&o+1+n>a)t=o;else break}while(!0);return yield sr.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 o=this.buffer[r+1];if($e(o)||t&&no.has(o))break;n=r}else if($e(s)){let o=this.buffer[r+1];if(s==="\r"&&(o===`
134
+ `&&o>=this.pos&&o+1+n>a)t=o;else break}while(!0);return yield or.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 o=this.buffer[r+1];if($e(o)||t&&ro.has(o))break;n=r}else if($e(s)){let o=this.buffer[r+1];if(s==="\r"&&(o===`
135
135
  `?(r+=1,s=`
136
- `,o=this.buffer[r+1]):n=r),o==="#"||t&&no.has(o))break;if(s===`
137
- `){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(t&&no.has(s))break;n=r}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield sr.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(Ja),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if($e(r)||n&&no.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(;!$e(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(KR.has(n))n=this.buffer[++t];else if(n==="%"&&Qm.has(this.buffer[t+1])&&Qm.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
+ `,o=this.buffer[r+1]):n=r),o==="#"||t&&ro.has(o))break;if(s===`
137
+ `){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(t&&ro.has(s))break;n=r}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield or.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(Ga),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if($e(r)||n&&ro.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(;!$e(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(YR.has(n))n=this.buffer[++t];else if(n==="%"&&tg.has(this.buffer[t+1])&&tg.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)}};Xm.Lexer=Ga});var Za=C(Zm=>{"use strict";var Xa=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 o=n+r>>1;this.lineStarts[o]<t?n=o+1:r=o}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}}}};Zm.LineCounter=Xa});var tc=C(sg=>{"use strict";var WR=gr("process"),eg=to(),HR=Qa();function lt(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function tg(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 rg(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 ro(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 sn(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 so(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 ng(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!lt(t.start,"explicit-key-ind")&&!lt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,rg(t.value)?t.value.end?so(t.value.end,t.sep):t.value.end=t.sep:so(t.start,t.sep),delete t.sep)}var ec=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 HR.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,WR.env.LOG_TOKENS&&console.log("|",eg.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let n=eg.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"&&ng(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&&tg(s.start)===-1&&(n.indent===0||s.start.every(o=>o.type!=="comment"||o.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":{tg(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=ro(this.peek(2)),r=sn(n),s;t.end?(s=t.end,s.push(this.sourceToken),delete t.end):s=[this.sourceToken];let o={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]=o}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)}};ng.Lexer=Qa});var ec=C(rg=>{"use strict";var Za=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 o=n+r>>1;this.lineStarts[o]<t?n=o+1:r=o}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}}}};rg.LineCounter=Za});var nc=C(cg=>{"use strict";var GR=yr("process"),sg=no(),QR=Xa();function ft(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function og(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 ag(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 so(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 on(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 oo(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 ig(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!ft(t.start,"explicit-key-ind")&&!ft(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,ag(t.value)?t.value.end?oo(t.value.end,t.sep):t.value.end=t.sep:oo(t.start,t.sep),delete t.sep)}var tc=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 QR.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,GR.env.LOG_TOKENS&&console.log("|",sg.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let n=sg.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"&&ig(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&&og(s.start)===-1&&(n.indent===0||s.start.every(o=>o.type!=="comment"||o.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":{og(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=so(this.peek(2)),r=on(n),s;t.end?(s=t.end,s.push(this.sourceToken),delete t.end):s=[this.sourceToken];let o={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]=o}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)){so(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",o=[];if(s&&n.sep&&!n.value){let i=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":i.push(a);break;case"space":break;case"comment":c.indent>t.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(o=n.sep.splice(i[1]))}switch(this.type){case"anchor":case"tag":s||n.value?(o.push(this.sourceToken),t.items.push({start:o}),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?(o.push(this.sourceToken),t.items.push({start:o,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(lt(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(rg(n.key)&&!lt(n.sep,"newline")){let i=sn(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:i,key:a,sep:c}]})}else o.length>0?n.sep=n.sep.concat(o,this.sourceToken):n.sep.push(this.sourceToken);else if(lt(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=sn(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||s?t.items.push({start:o,key:null,sep:[this.sourceToken]}):lt(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 i=this.flowScalar(this.type);s||n.value?(t.items.push({start:o,key:i,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(i):(Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(t);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!lt(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:o});this.stack.push(i);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)){so(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||lt(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=ro(r),o=sn(s);ng(t);let i=t.end.splice(1,t.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:o,key:t,sep:i}]};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)){oo(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",o=[];if(s&&n.sep&&!n.value){let i=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":i.push(a);break;case"space":break;case"comment":c.indent>t.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(o=n.sep.splice(i[1]))}switch(this.type){case"anchor":case"tag":s||n.value?(o.push(this.sourceToken),t.items.push({start:o}),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?(o.push(this.sourceToken),t.items.push({start:o,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(ft(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(ag(n.key)&&!ft(n.sep,"newline")){let i=on(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:i,key:a,sep:c}]})}else o.length>0?n.sep=n.sep.concat(o,this.sourceToken):n.sep.push(this.sourceToken);else if(ft(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=on(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||s?t.items.push({start:o,key:null,sep:[this.sourceToken]}):ft(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 i=this.flowScalar(this.type);s||n.value?(t.items.push({start:o,key:i,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(i):(Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(t);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!ft(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:o});this.stack.push(i);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)){oo(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||ft(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=so(r),o=on(s);ig(t);let i=t.end.splice(1,t.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:o,key:t,sep:i}]};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=ro(t),r=sn(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=ro(t),r=sn(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())}}};sg.Parser=ec});var ug=C(ir=>{"use strict";var og=qa(),YR=Qn(),or=er(),JR=_i(),GR=z(),QR=Za(),ig=tc();function ag(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new QR.LineCounter||null,prettyErrors:t}}function XR(e,t={}){let{lineCounter:n,prettyErrors:r}=ag(t),s=new ig.Parser(n?.addNewLine),o=new og.Composer(t),i=Array.from(o.compose(s.parse(e)));if(r&&n)for(let a of i)a.errors.forEach(or.prettifyError(e,n)),a.warnings.forEach(or.prettifyError(e,n));return i.length>0?i:Object.assign([],{empty:!0},o.streamInfo())}function cg(e,t={}){let{lineCounter:n,prettyErrors:r}=ag(t),s=new ig.Parser(n?.addNewLine),o=new og.Composer(t),i=null;for(let a of o.compose(s.parse(e),!0,e.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new or.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(or.prettifyError(e,n)),i.warnings.forEach(or.prettifyError(e,n))),i}function ZR(e,t,n){let r;typeof t=="function"?r=t:n===void 0&&t&&typeof t=="object"&&(n=t);let s=cg(e,n);if(!s)return null;if(s.warnings.forEach(o=>JR.warn(s.options.logLevel,o)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:r},n))}function eS(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 GR.isDocument(e)&&!r?e.toString(n):new YR.Document(e,r,n).toString(n)}ir.parse=ZR;ir.parseAllDocuments=XR;ir.parseDocument=cg;ir.stringify=eS});var lg=C(q=>{"use strict";var tS=qa(),nS=Qn(),rS=ba(),nc=er(),sS=xn(),ft=z(),oS=at(),iS=Q(),aS=ut(),cS=dt(),uS=to(),dS=Qa(),lS=Za(),fS=tc(),oo=ug(),dg=Dn();q.Composer=tS.Composer;q.Document=nS.Document;q.Schema=rS.Schema;q.YAMLError=nc.YAMLError;q.YAMLParseError=nc.YAMLParseError;q.YAMLWarning=nc.YAMLWarning;q.Alias=sS.Alias;q.isAlias=ft.isAlias;q.isCollection=ft.isCollection;q.isDocument=ft.isDocument;q.isMap=ft.isMap;q.isNode=ft.isNode;q.isPair=ft.isPair;q.isScalar=ft.isScalar;q.isSeq=ft.isSeq;q.Pair=oS.Pair;q.Scalar=iS.Scalar;q.YAMLMap=aS.YAMLMap;q.YAMLSeq=cS.YAMLSeq;q.CST=uS;q.Lexer=dS.Lexer;q.LineCounter=lS.LineCounter;q.Parser=fS.Parser;q.parse=oo.parse;q.parseAllDocuments=oo.parseAllDocuments;q.parseDocument=oo.parseDocument;q.stringify=oo.stringify;q.visit=dg.visit;q.visitAsync=dg.visitAsync});import{existsSync as $y,mkdtempSync as jA,readFileSync as Ay,rmSync as CA,statSync as IA,writeFileSync as by}from"node:fs";import{tmpdir as DA}from"node:os";import{dirname as je,join as Tt,resolve as Ro}from"node:path";import{existsSync as on,readFileSync as bc,readdirSync as HS,rmSync as YS}from"node:fs";import{join as mo}from"node:path";import{join as ew}from"node:path";import{randomBytes as Fy,randomUUID as nd}from"node:crypto";import{mkdirSync as My,realpathSync as _y,statSync as Dr}from"node:fs";import{open as zy,readFile as qy,readdir as By,rename as Uy,rm as qo}from"node:fs/promises";import{basename as Vo,dirname as Te,join as Re,resolve as Pr}from"node:path";var Ky=448,Yo=384,Jo=30,Vy=1440*6e4,Bo="state.json",Wy=/^runs\/[a-z][a-z0-9-]{0,62}\/[1-9][0-9]{0,5}\.summary\.json$/,Hy=/^runs\/[a-z][a-z0-9-]{0,62}\/[1-9][0-9]{0,5}\.summary\.removals\.json$/,Yy=/^templates\/[a-z][a-z0-9-]{0,62}\.[1-9][0-9]{0,5}\.json$/,ed=/^(?: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 Nr(e=process.env){return Te(Lu("env",e))}function Tr(e,t){let n=mn(e,t);if(n!==void 0)return`The journal directory ${Pr(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 mn(e,t){let n;try{n=Or(td(e))}catch{return}return new Be(n).isInsideRepo(td(t))?n:void 0}function td(e){let t=[],n=Pr(e);for(;;)try{return Re(_y(n),...t.reverse())}catch{let r=Te(n);if(r===n)return Pr(e);t.push(Vo(n)),n=r}}function oe(e,t){return`runs/${Ue(e)}/${Lr(t)}.summary.json`}function Go(e,t){return`runs/${Ue(e)}/${Lr(t)}.summary.removals.json`}function bt(e,t){return`templates/${Ue(e)}.${Lr(t)}.json`}function xr(e,t,n,r=nd()){return`env-${Ue(e)}-${Ue(t)}-${Lr(n)}-${r}`}function Ue(e){let t=un.safeParse(e);if(!t.success)throw new L("invalid",`Not a name of the file: "${e}"`);return t.data}function Lr(e){if(!Number.isInteger(e)||e<1||e>999999)throw new L("invalid",`Not a run's rank: ${e}`);return e}function Fr(e){return{version:1,env:Ue(e.env),lineage:nd(),serial:0,sandforgeVersion:e.sandforgeVersion,updatedAt:(e.now??new Date).toISOString(),org:{organizationId:pe(e.org.organizationId),kind:e.org.kind,username:e.org.username,...e.org.alias!==void 0?{alias:e.org.alias}:{},...e.org.host!==void 0?{host:e.org.host}:{}},file:{digest:e.fileDigest},resources:{}}}function rd(e,t){return t===void 0||e.org.host===t?e:{...e,org:{...e.org,host:t}}}function gn(e){return(e?.runs.at(-1)?.n??0)+1}function Et(e,t){let n=e.resources[t.resource],r={...t.run,n:gn(n),objects:[]};return Mr(e,t.resource,{kind:t.kind,fingerprint:t.fingerprint,dependsOn:[...t.dependsOn],status:"applying",runs:[...n?.runs??[],r]})}function Qo(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 Mr(e,t,{...n,status:"destroying"})}function yn(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(o=>o.n===n?{...o,takenBack:!0}:o);return Mr(e,t,{...r,runs:s})}function Lt(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 Mr(e,t.resource,{...n,status:t.status,runs:r})}function Mr(e,t,n){return{...e,resources:{...e.resources,[Ue(t)]:n}}}function Xo(e){if(e.org.kind==="scratch")return new Date(Date.parse(e.updatedAt)+Jo*Vy).toISOString()}function _r(e){if(e.fileFolder!==null){let r=Tr(e.fileFolder,e.journalDir);if(r!==void 0)return{refusal:r}}let t=new Wo(e),n=hn(t.root,e.uid??sd);return n!==void 0?{refusal:n}:{store:t}}var Wo=class{root;fileFolder;uid;renameFile;now;constructor(t){this.root=Re(Pr(t.journalDir),"env"),this.fileFolder=t.fileFolder,this.uid=t.uid??sd,this.renameFile=t.rename??((n,r)=>Uy(n,r)),this.now=t.now??Date.now}folderOf(t,n){let r=Uo(t);if(r===void 0)throw new L("invalid",`Not an Organization Id: "${t}"`);return Re(this.root,r,Ue(n))}fileOf(t,n,r){if(!Wy.test(r)&&!Yy.test(r)&&!Hy.test(r))throw new L("invalid",`Not a file of a state's folder: "${r}"`);return Re(this.folderOf(t,n),...r.split("/"))}async read(t,n){let r=this.folderOf(t,n),s=Re(r,Bo),o;try{o=await qy(s,"utf8")}catch(i){if(Ho(i)==="ENOENT")return;throw i}return Jy(o,s,r)}stateFileOf(t,n){return Re(this.folderOf(t,n),Bo)}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","-"),o=`${r}.damaged-${s}`;for(let i=2;Dr(o,{throwIfNoEntry:!1})!==void 0;i++)o=`${r}.damaged-${s}-${i}`;return await this.renameFile(r,o),o}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),o=s?.serial??0;if(o!==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 ${o}, 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 i=dn.safeParse({...t,org:{...t.org,organizationId:pe(t.org.organizationId)},serial:n.serial+1,updatedAt:new Date(this.now()).toISOString()});if(!i.success)throw new L("invalid",`Not a state: ${i.error.message}`);for(let a of[Te(r),r]){let c=hn(a,this.uid);if(c!==void 0)throw new L("folder",c)}return await this.writeWhole(Re(r,Bo),`${JSON.stringify(i.data,null,2)}
144
- `),i.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 o=this.fileOf(t,n,r),i=this.folderOf(t,n);for(let a of[Te(i),i,Te(o)]){let c=hn(a,this.uid);if(c!==void 0)throw new L("folder",c)}return await this.writeWhole(o,s),o}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),o=this.folderOf(t,n);for(let i of[Te(o),o,Te(s)]){let a=hn(i,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(!ed.test(r))throw new L("invalid",`Not a folder of a state's folder: "${r}"`);let s=this.folderOf(t,n),o=Re(s,...r.split("/"));for(let i of[Te(s),s,Te(o),o]){let a=hn(i,this.uid);if(a!==void 0)throw new L("folder",a)}return o}sasOf(t,n,r){if(!ed.test(r))throw new L("invalid",`Not a folder of a state's folder: "${r}"`);return Re(this.folderOf(t,n),...r.split("/"))}async remove(t,n){let r=this.folderOf(t,n);return Dr(r,{throwIfNoEntry:!1})===void 0?!1:(await qo(r,{recursive:!0,force:!0}),!0)}async refreshedOf(t,n){let r=Ue(n),s;for(let o of await Ko(this.root)){if(Uo(o)!==o)continue;let i;try{i=await this.read(o,r)}catch{continue}i?.org.host===void 0||!kt(i.org,t)||s!==void 0&&Date.parse(s.updatedAt)>=Date.parse(i.updatedAt)||(s={organizationId:i.org.organizationId,serial:i.serial,updatedAt:i.updatedAt,host:i.org.host,setAside:this.folderOf(o,r)})}return s}async list(){let t=[];for(let n of await Ko(this.root))if(Uo(n)===n)for(let r of await Ko(Re(this.root,n))){if(!un.safeParse(r).success)continue;let s=Re(this.root,n,r);try{let o=await this.read(n,r);if(o===void 0)continue;let i=Xo(o);t.push({organizationId:n,env:r,folder:s,state:o,...i!==void 0?{expiresAt:i}:{}})}catch(o){t.push({organizationId:n,env:r,folder:s,damaged:od(o)})}}return t}async sweep(){let t=this.now(),n=[];for(let{state:r,expiresAt:s,folder:o,organizationId:i,env:a}of await this.list())r===void 0||s===void 0||Date.parse(s)>t||(await qo(o,{recursive:!0,force:!0}),n.push({organizationId:i,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}-${Fy(4).toString("hex")}.tmp`,s=await zy(r,"wx",Yo);try{try{await s.writeFile(n,"utf8"),await s.sync()}finally{await s.close()}await this.renameFile(r,t)}catch(o){throw await qo(r,{force:!0}),o}}};function Jy(e,t,n){let r;try{r=JSON.parse(e)}catch{r=void 0}let s=dn.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 ${B("env")} state recover: it sets this file aside and rebuilds the state from the run files beside it.`);let o=s.data;if(pe(o.org.organizationId)!==Vo(Te(n))||o.env!==Vo(n))throw new L("otherOrg",`The state ${t} is of ${o.env} on ${o.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 o}function sd(){return process.getuid?.()}function hn(e,t){try{let n=Dr(e,{throwIfNoEntry:!1});if(n!==void 0&&!n.isDirectory())return`${e} is not a folder.`;My(e,{recursive:!0,mode:Ky});let r=t();return r!==void 0&&Dr(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: ${od(n)}`}}function Uo(e){try{return pe(e)}catch{return}}async function Ko(e){try{return(await By(e,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name).sort()}catch(t){if(Ho(t)==="ENOENT"||Ho(t)==="ENOTDIR")return[];throw t}}function Ho(e){return e?.code}function od(e){return e instanceof Error?e.message:String(e)}import{createHash as Gy}from"node:crypto";function wn(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 N(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 Ft(e){return JSON.stringify(Zo(e))}function Zo(e){if(Array.isArray(e))return e.map(Zo);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,Zo(t[n])]))}function ei(e){return Gy("sha256").update(e,"utf8").digest("hex")}var Qy=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 ve(e){return e.sweep===!0?["--sweep"]:[]}var Ge=p.string().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),R=p.number().int().nonnegative(),Qe=p.object({objectApiName:p.string().min(1),planned:R,deleted:R,alreadyGone:R,keptChanged:R,keptDependents:R,refused:R,notVisible:R.optional(),notReached:R.optional(),heldBy:p.array(p.string()),reasons:p.array(p.string())}),Xy=p.object({objectApiName:p.string().min(1),planned:R,toDelete:R,alreadyGone:R,changedSince:R,keptChanged:R,changedBy:p.record(Ge,R),undeletable:R,notVisible:R,unread:R,reasons:p.array(p.string())}),Mt=p.object({planned:R,objects:p.array(Xy),undeletable:p.array(p.object({objectApiName:p.string().min(1),records:R})).optional(),userNames:p.record(Ge,p.string())});function xe(e,t,n){if(t===void 0||n?.length!==t.length)return[];let r=t.flatMap((s,o)=>{let i=n[o];return i!==void 0&&i!==""&&s!==""&&e.includes(s)?[i]:[]});return[...new Set(r)]}var Zy=/^Nothing(?: was)? (?:written|deleted)\.?$/i;function id(e){return e.split(`
145
- `).map(t=>t.trim()).filter(t=>t!==""&&!Zy.test(t)).at(-1)}var ce=class extends Error{constructor(n,r,s,o){super(`${De(n)} did not answer ${r} (${s}): `+(o===""?"it printed nothing on stdout":`it printed ${JSON.stringify(o)}`));this.script=n;this.expected=r;this.reason=s;this.excerpt=o;this.name="StepAnswerError"}script;expected;reason;excerpt};function _(e,t,n,r){let s=r.trim().slice(0,Qy),o;try{o=JSON.parse(r)}catch{throw new ce(e,t,"not JSON",s)}let i=n.safeParse(o);if(!i.success){let a=i.error.issues[0],c=a?.path.join(".")||"the answer";throw new ce(e,t,`${c}: ${a?.message??"refused"}`,s)}return i.data}var ye="sandforge-checkpoint";function Z(e){return ew(e,"checkpoints")}function tw(e){return e==="scratch"?Jo:0}function vn(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 kn(e){return["--org",I("--org",e.org),"--store",I("--store",e.store)]}function zr(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 ad(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 cd(e){return["take",...kn(e),...ad(e),"--estimate","--json"]}function nw(e){return["take",...kn(e),"--name",I("--name",e.name),"--keep-days",String(e.keepDays),...ad(e),"--json"]}function ni(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, ${Vc.toLocaleString("en-US")} at most. No record was read.`}}function ud(e){return["preview",...kn(e),"--checkpoint",gt.parse(e.checkpoint),"--json"]}function ri(e){return["rewind",...kn(e),"--checkpoint",gt.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 rw(e){return["delete",...kn(e),"--checkpoint",gt.parse(e.checkpoint),"--yes","--json"]}var si=p.object({code:p.string().min(1),message:p.string().min(1)}),bn=p.object({refusal:si}),sw=p.union([p.object({mode:p.string(),estimate:p.object({records:R,apiRequests:R,apiRequestsLeft:p.number(),seconds:p.number().nonnegative(),bytes:R}),refusal:si.optional()}),bn]),ow=p.union([p.object({checkpoint:p.object({checkpointId:gt,name:p.string().min(1),takenAt:p.string().min(1)})}),bn]),iw=p.union([p.object({checkpoint:p.object({id:gt,name:p.string().min(1),takenAt:p.string().min(1)}),toDelete:R,toGiveBack:R,toBringBack:R,toRecreate:R,differs:p.boolean(),diff:p.object({objects:p.array(p.object({objectApiName:p.string().min(1),lastChangedBy:p.record(p.string(),R),touched:R})),userNames:p.record(p.string(),p.string())}),refusal:si.optional()}),bn]),ti=p.object({planned:R,done:R,left:R}),aw=p.union([p.object({checkpoint:p.object({id:gt,name:p.string().min(1)}),rewindId:p.string().min(1),status:p.enum(["success","partial","unstable","failure","cancelled"]),deleted:ti,givenBack:ti,broughtBack:ti,undo:p.object({until:p.string().min(1)}).optional(),residual:p.array(p.object({object:p.string(),reason:p.string(),count:R}))}),bn]),cw=p.union([p.object({deleted:p.array(p.string()),kept:p.array(p.string())}),bn]);function uw(e){return _(ye,"the estimate of a take",sw,e)}function dw(e){return _(ye,"a take",ow,e)}function dd(e){return _(ye,"a preview",iw,e)}function lw(e){return _(ye,"a rewind",aw,e)}function fw(e){return _(ye,"a deletion",cw,e)}function pw(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 ce))throw n;return{unread:`exit ${e.code}: ${pw(e)}`}}}function qr(e,t,n){let r=[],s=vn(e,"before");s!==void 0&&n&&hw(t)&&r.push({step:"before",name:s});let o=vn(e,"after");return o!==void 0&&(n||t?.checkpoints?.after===void 0)&&r.push({step:"after",name:o}),r}function ld(e){return Object.values(e?.resources??{}).some(t=>t.status!=="destroyed")}function hw(e){return e?.checkpoints?.before===void 0&&!ld(e)}function fd(e,t){return e.checkpoint?.before!==!0||t?.checkpoints?.before!==void 0?[]:ld(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 pd(e){let t=_t(e,uw);if("unread"in t)return t;let n=t.answer;if(!("estimate"in n))return{refusal:ni(n.refusal)};let{records:r,apiRequests:s,seconds:o,bytes:i}=n.estimate;return{estimate:{records:r,apiRequests:s,seconds:o,bytes:i},...n.refusal!==void 0?{refusal:ni(n.refusal)}:{}}}function hd(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 Br={before:"before the first write",after:"once applied"};function md(e){let t=e.filter(n=>n.refusal!==void 0);if(t.length!==0)return t.map(n=>`The checkpoint the file asks ${Br[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 gd(e){let t=0,n=[];for(let r of e)r.estimate!==void 0?t+=r.estimate.apiRequests:n.push(`the checkpoint ${Br[r.step]}, not estimated`);return{estimate:t,notCounted:n}}function yd(e,t){let n=_t(t,dd);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 Le=e=>e.toLocaleString("en-US");function wd(e){let t=[];for(let r of e.checkpoints??[]){let s=`checkpoint ${Br[r.step]}: '${r.name}'`,{estimate:o}=r;o!==void 0?t.push(`${s}, about ${Le(o.records)} records, ${Le(o.apiRequests)} API requests, ${Le(Math.ceil(o.seconds))} s, ${wt(o.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, ${Le(n.toDelete??0)} to delete \xB7 ${Le(n.toGiveBack??0)} to give back \xB7 ${Le(n.toBringBack??0)} to bring back`:`${r}: nothing differs among the objects and fields it compares`)}return t}async function oi(e,t,n){e.say(`checkpoint ${Br[t.step]}: taking '${t.name}'`);let r=await e.runner(ye,nw({org:t.org.alias,store:Z(e.journalDir),name:t.name,keepDays:tw(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,dw),o="answer"in s?s.answer:void 0,i="raw"in s?s.raw:void 0;if(r.code===0&&o!==void 0&&"checkpoint"in o)return{result:{step:t.step,checkpoint:o.checkpoint.checkpointId,exitCode:r.code,answer:i},checkpoint:o.checkpoint.checkpointId};let a=o!==void 0&&"refusal"in o?`${o.refusal.code}: ${ni(o.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),...i!==void 0?{answer:i}:{}}}}async function zt(e,t,n){e.say(`checkpoint ${t.checkpoint}: deleted from this machine, ${t.why}`);let r=await e.runner(ye,rw({org:t.org.alias,store:Z(e.journalDir),checkpoint:t.checkpoint}),n),s=_t(r,fw),o="answer"in s?s.answer:void 0,i=o!==void 0&&"deleted"in o&&o.deleted.includes(t.checkpoint),a=o!==void 0&&"refusal"in o&&o.refusal.code==="NOT_FOUND";if(i||a)return{step:"delete",checkpoint:t.checkpoint,exitCode:0};let c=o!==void 0&&"refusal"in o?`${o.refusal.code}: ${o.refusal.message}`:o!==void 0&&"kept"in o?"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 Ur(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 Xe(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 vd(e){let t=_t(e,dd);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[o,i]of Object.entries(s.lastChangedBy)){let a=n.diff.userNames[o]??o;r[a]=(r[a]??0)+i}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 Kr(e){return Object.entries(e).sort((t,n)=>n[1]-t[1]).map(([t,n])=>`${t} ${Le(n)}`).join(", ")}function kd(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}:`,` ${Le(n.toDelete)} to delete \xB7 ${Le(n.toGiveBack)} to give back \xB7 ${Le(n.toBringBack)} to bring back`+(n.differs?"":" \u2014 nothing differs: nothing to rewind")],o=Kr(n.lastChangedBy);return o!==""&&s.push(` last changed by: ${o}`),n.refusal!==void 0&&s.push(` refused: ${n.refusal.message}`),s}function bd(e){let t=_t(e,lw),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((o,i)=>o+i.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 Ed(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:`${B("checkpoint")} undo --org ${e.alias} --checkpoint ${e.checkpoint} --store ${Z(e.journalDir)}`}}function Rd(e){return e.offered?`undo it until ${e.until}, sooner if the recycle bin fills: ${e.line}`:`no undo: ${e.why}`}var Vr="STATE_MOVED",Sd="No flag lifts this: an environment is never applied to a production org.";function ke(e,t){return e.length>=15&&t.length>=15&&e.slice(0,15)===t.slice(0,15)}function $d(e,t,n){if("unread"in t)return t.error!==void 0&&Gc(t.error)!==void 0?{refusal:{code:"UNTYPED",message:eu(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. ${Sd}`,exit:1}};if(Er(t)){let o=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 ${o}): an environment is applied to scratch orgs, Developer Edition orgs and the sandboxes its file lists. Nothing was read or written. ${Sd}`,exit:1}}}let r=t.sandbox?n.scratch===!0?"scratch":"sandbox":"developer",s=xo(n.instanceUrl);return{target:{alias:e,organizationId:t.id,kind:r,username:n.username,...s!==void 0?{host:s}:{}}}}var Ad={scratch:"a scratch org",developer:"a Developer Edition org",sandbox:"a sandbox"};function ii(e,t){if(t.kind!=="sandbox")return;if(e.sandboxes.some(r=>typeof r=="string"&&ke(r,t.organizationId)))return{by:"organizationId"};let n=Ne(t.host);if(n!==void 0&&e.sandboxes.some(r=>typeof r!="string"&&r.myDomain===n))return{by:"myDomain",myDomain:n}}function Od(e){return e?"listed by its My Domain; its Organization Id changed since the last apply":"listed by its My Domain"}function mw(e,t){let n=t.organizationId,r=pe(n);if(e.protect.some(i=>typeof i=="string"&&ke(i,n)))return{code:"PROTECTED",message:`${t.alias} (${r}) is listed under targets.protect: the file refuses it whatever else it says. Nothing was read or written.`,exit:1};let s=e.protect.flatMap(i=>typeof i=="string"?[]:[i.myDomain]),o=s.find(i=>Lo(t.host,i));if(o!==void 0)return{code:"PROTECTED",message:`${t.alias} (${r}, on ${t.host??""}) is listed under targets.protect by its My Domain ${o}: the file refuses it whatever else it says. Nothing was read or written.`,exit:1};if(s.length>0&&t.kind==="sandbox"&&t.host===void 0){let i=s.length===1?`lists ${s.join(", ")} by its My Domain: whether it is that sandbox`:`lists ${s.join(", ")} by their My Domains: whether it is one of them`;return{code:"PROTECTED",message:`${t.alias} (${r}) is a sandbox the sf CLI reaches by no My Domain host, and targets.protect ${i} cannot be told, and a protected org is never let through on a guess. Nothing was read or written. Sign in to it by its My Domain's URL to have it told apart.`,exit:1}}}function gw(e,t){let n=pe(t.organizationId),r=Ne(t.host),s=e.sandboxes.some(c=>typeof c!="string"),o="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.",i=" 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.";if(r!==void 0)return{code:"NOT_LISTED",message:`${t.alias} is a sandbox, and its Organization Id ${n} is not listed under targets.sandboxes, nor its My Domain ${r}: ${o} A refresh changes the Id: a sandbox listed by it before its refresh is listed again, or listed by its My Domain, which a refresh keeps: { myDomain: ${r} }. Nothing was read or written.`,exit:1};let a=Cr(t.host)?` Its host, ${t.host??""}, is a scratch org's, which no My Domain lists: the sf CLI did not say it is one, its display naming 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.`:s?t.host===void 0?" The sf CLI reaches it by no My Domain host: no My Domain the file lists can name it.":` Its host, ${t.host}, is no sandbox's: no My Domain the file lists can name it.`:"";return{code:"NOT_LISTED",message:`${t.alias} is a sandbox, and its Organization Id ${n} is not listed under targets.sandboxes: ${o} A refresh changes the Id: a sandbox listed before its refresh is listed again.${a} Nothing was read or written.`+(Cr(t.host)?"":i),exit:1}}function jd(e,t){let n=mw(e,t);if(n!==void 0)return n;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 ${Ad[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"&&ii(e,t)===void 0)return gw(e,t)}function Ze(e){return{code:e.code==="otherOrg"?"OTHER_ORG":"STATE_DAMAGED",message:`${e.message} Nothing was read or written in the org.`,exit:1}}function Cd(e,t,n){if(!(e.env===t&&ke(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 Id(e,t,n,r=!1,s){if(s!==void 0&&!r&&kt({...s,kind:"sandbox"},e)){let{organizationId:i,serial:a,updatedAt:c,setAside:u}=s,d={organizationId:i,serial:a,updatedAt:c,setAside:u};return{warning:ai(e.alias,d),refreshed:d}}let o=`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 ${B("env")} state recover rebuilds the state from them`:"");return e.kind==="scratch"||n?{warning:o}:{refusal:{code:"NO_STATE",message:`${o.charAt(0).toUpperCase()}${o.slice(1)}. On ${Ad[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 ai(e,t){return`none for this Organization Id; ${e} was refreshed since the last apply, which this machine kept under ${t.organizationId} (serial ${t.serial}, ${t.updatedAt.slice(0,10)}): the refresh took what it held, and this apply starts anew. That state is set aside, kept: ${t.setAside}`}function Wr(e,t){return t?{code:"STORE_IN_REPOSITORY",message:e,exit:2}:{code:"STORE",message:e,exit:1}}function et(e){return{code:"LOCKED",message:Cu(e),exit:1}}function En(e){return{code:"CHECKPOINT_ACT",message:`${e.charAt(0).toUpperCase()}${e.slice(1)}`,exit:1}}import{readFileSync as yw}from"node:fs";import{join as Pd}from"node:path";var G="sandforge-clone",Nd=1e4,Dd=1e6,ww=["inputMode","recordId","soqlQuery","queryScope","maxRoots","templateId","aiPrompt","dryRun"];function vw(e){let[t]=e;return`SELECT Id FROM ${t?.object??""}${t?.where!==void 0?` WHERE ${t.where}`:""}`}function kw(e,t,n){let r=["resources",e,"template"],s=d=>({refusals:[N(r,d)]}),o;try{o=yw(Pd(n,t.file),"utf8")}catch(d){return s(`${t.file} cannot be read: ${d instanceof Error?d.message:String(d)}`)}if(o.length>Dd)return s(`${t.file} is larger than ${Dd} bytes`);let i;try{i=JSON.parse(o.replace(/^\uFEFF/,""))}catch{return s(`${t.file} is not JSON`)}let a=Array.isArray(i)?i:[i],c=a.find(d=>d!==null&&typeof d=="object"&&d.id===t.id);if(c===void 0){let d=a.map(l=>l!==null&&typeof l=="object"?l.id:"").filter(l=>typeof l=="string"&&l!=="");return s(`${t.file} holds no template "${t.id}"`+(d.length>0?`: it holds ${d.join(", ")}`:": it holds none"))}let u=jo.safeParse(c);return u.success?{entry:u.data}:{refusals:u.error.issues.map(d=>N(r,`the template "${t.id}" of ${t.file} is refused by Forge's template schema at ${d.path.map(String).join(".")||"its top"}: ${d.message}`))}}function Td(e,t,n,r,s){let o=["resources",t],i=[];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:i};let a;if(n.template!==void 0){let m=kw(t,n.template,r);if("refusals"in m)return m;a=m.entry}let c={...a?.config};for(let m of ww)delete c[m];if(n.tables!==void 0&&c.expandOrphanParents===!0)return{refusals:[N([...o,"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&&i.push(N([...o,"template"],"the template copies the files of the cloned records: an environment copies none, and the clone writes the records alone"));let u=n.depth??c.depth,d=(u??"custom")==="custom"?n.customDepth??c.customDepth:void 0;delete c.customDepth;let l=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:vw(n.tables)}:{inputMode:"record",...n.record?.id!==void 0?{recordId:n.record.id}:{}},depth:u??"custom",...d!==void 0?{customDepth:d}:{},...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:l,lastUsedAt:l},h=jo.safeParse(f);return h.success?{run:{source:n.source,template:h.data,...n.record!==void 0?{record:{...n.record}}:{},...n.records!==void 0?{records:{...n.records}}:{},...n.tables!==void 0?{tables:n.tables.map(m=>({...m}))}:{},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{},acceptAutomation:n.accept?.automation===!0,acceptRealData:n.accept?.realData===!0},warnings:i}:{refusals:h.error.issues.map(m=>N(o,`the template it converts into is refused by Forge's template schema at ${m.path.map(String).join(".")||"its top"}: ${m.message}`))}}function xd(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 Hr(e){return gu(e.object,{...e.where!==void 0?{where:e.where}:{},...e.orderBy!==void 0?{orderBy:e.orderBy}:{},limit:e.limit},void 0,e.limit)}function Yr(e,t,n,r){let s=o=>o.replace(/[^A-Za-z0-9_-]/g,"-");return Pd(Su(e),`env-${s(t.slice(0,15))}-${s(n)}-${s(r)}.json`)}function Ld(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 bw(e){return e.edition?`its Organization record says IsSandbox false, edition ${e.edition}`:"its Organization record says IsSandbox false, and no edition"}function Ew(e,t,n){if(e.acceptRealData||Ld(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 (${bw(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 Fd(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(([,i])=>i!==void 0).map(([i,a])=>`${i} ${String(a)}`),s=Ld(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 })",o=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}`,o?"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 Md(e,t,n,r){let s=`the ${n} org (${r})`,o;try{o=await br(e)}catch(l){return{refusal:`${s} could not be read: ${ci(l)}`}}let i=o.id,a=Er(o);if(a){let l=Ew(t,s,o);if(l!==void 0)return{refusal:l}}let c={organizationId:i,...a?{production:!0}:{}};if(t.records!==void 0){let{records:l}=t;try{let h=(await e.query(Hr(l))).records.flatMap(m=>typeof m.Id=="string"?[m.Id]:[]);if(h.length===0){let m=l.where!==void 0?` WHERE ${l.where}`:"";return{refusal:`its records query chooses no ${l.object} in ${s}${m!==""?` (${m.trim()})`:""}: there is nothing to clone. Count what it chooses there with sf data query -o ${r} -q "SELECT COUNT() FROM ${l.object}${m}", and check its where`}}return{...c,roots:{count:h.length,sha256:yu(h)}}}catch(f){return{refusal:`its records query could not be read in ${s}: ${ci(f)}`}}}let u=t.record;if(u?.object===void 0||u.where===void 0)return c;let d=`${u.object} WHERE ${u.where}`;try{let l=(await e.query(`SELECT Id FROM ${d} LIMIT 2`)).records;return l.length===1&&typeof l[0]?.Id=="string"?{...c,recordId:l[0].Id}:l.length===0?{refusal:`its record query finds no ${u.object} in ${s} (WHERE ${u.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 ${d}`)).totalSize} ${u.object} records in ${s} (WHERE ${u.where}), not one: narrow the where to one row, or name the record by its id`}}catch(l){return{refusal:`its record query could not be read in ${s}: ${ci(l)}`}}}function _d(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 zd(e){if(e.wholeOrg)return Rw(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",I("--source",e.source),"--target",I("--target",e.target),...e.recordId!==void 0?["--record",I("--record",e.recordId)]:e.records!==void 0?["--query",I("--query",Hr(e.records)),"--max-roots",String(e.records.limit),...e.rootsPlanFile!==void 0?["--roots-plan",I("--roots-plan",e.rootsPlanFile)]:[]]:(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 Rw(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",...Sw(t.fit)]:[],...e.acceptAutomation?["--accept-automation"]:[]]}function Sw(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",I("--fit-where",`${n}=${r}`)]),...(e.strata??[]).flatMap(n=>["--fit-strata",I("--fit-strata",n)])]}function qd(e){return[...zd(e),"--dry-run","--json"]}function Bd(e){return[...zd(e),...e.wholeOrg?["--yes"]:[],"--summary",I("--summary",e.summary),"--json"]}function Ud(e){return["--remove",I("--remove",e.summary),"--target",I("--target",e.target),...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[]]}function Kd(e){return[...Ud(e),...ve(e),"--json"]}function Vd(e){return[...Ud(e),"--preview",...ve(e),"--json"]}function Wd(e){return["--verify",I("--verify",e.summary),"--target",I("--target",e.target),"--source",I("--source",e.source),"--json"]}var $w=p.enum(["SingleEmail","DailyWorkflowEmails"]),Aw=p.object({tool:p.literal(G),version:p.literal(1),dryRun:p.literal(!0),result:p.object({wouldInsertCount:R,failedCount:R}),writePlan:p.object({totalRows:R,storageBytes:R,objects:p.array(p.object({objectApiName:p.string().min(1),rows:R,storageBytes:R,mayAdd:R.optional()})),emails:p.array(p.object({limit:$w,emails:R})).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()}),Ow=p.object({tool:p.literal(G),version:p.literal(1),dryRun:p.literal(!1),targetOrgId:Ge.optional(),result:p.object({successCount:R,failedCount:R,createdByObject:p.array(p.object({objectApiName:p.string().min(1),sourceIds:p.array(Ge)})),remapInJournal:p.literal(!0).optional(),createdCountByObject:p.array(p.object({objectApiName:p.string().min(1),created:R})).optional(),errors:p.array(p.object({objectApiName:p.string().min(1),failedCount:R,samples:p.array(p.unknown()).optional()}))}),running:p.literal(!0).optional(),interrupted:p.literal(!0).optional(),error:p.string().optional()}),jw=p.object({tool:p.literal(G),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:R,objects:p.array(Qe),sweep:p.object({status:p.string()}).loose().optional()}),elapsedMs:R}),Cw=p.object({tool:p.literal(G),version:p.literal(1),action:p.literal("remove-preview"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),preview:Mt,refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional(),notes:p.array(p.string()),elapsedMs:R}),Iw=p.object({tool:p.literal(G),version:p.literal(1),action:p.literal("verify"),result:p.object({verdict:p.enum(["verified","partial","unstable"]),attempts:R,objects:p.array(p.object({objectApiName:p.string().min(1),expected:R,present:R,deleted:R,notVisible:R,changed:R,linksChecked:R,linksBroken:R,error:p.string().optional()})),linksUnchecked:p.string().optional()})});function Hd(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 o=s.field!==void 0?`${s.objectApiName}.${s.field}`:s.objectApiName;switch(s.kind){case"required_field_missing":return n.has(o.toLowerCase())?[]:[`${o}, which the org requires and the clone does not write`];case"object_not_createable":case"object_through_parent":return[`${o}, which the user it writes as may not create`];case"object_feature_off":return[`${o}, 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[`${o} (${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 Yd(e){return _(G,"the summary of a dry run",Aw,e)}function Rn(e){return _(G,"the summary of a run",Ow,e)}function Jd(e){return _(G,"the outcome of a removal",jw,e)}function Gd(e){return _(G,"the preview of a removal",Cw,e)}function Qd(e){return _(G,"a verification",Iw,e)}function Xd(e){let t=e.writePlan,n=(e.wouldBeRefused??[]).join(" "),r=xe(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 o=e.result.wouldInsertCount===t.totalRows,i=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,...o?{}:{atMost:!0}})),total:t.totalRows,created:e.result.wouldInsertCount,storageBytes:t.storageBytes,emails:t.emails??[],...i!==void 0?{refusal:i,...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(i=>i.object===r.objectApiName),o=`${r.failedCount} refused by the org`;s!==void 0?(s.refused+=r.failedCount,s.errors.push(o)):n.push({object:r.objectApiName,created:0,refused:r.failedCount,errors:[o]})}return{objects:n,created:e.result.successCount}}function Zd(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 ci(e){return e instanceof Error?e.message:String(e)}import{readFileSync as tl}from"node:fs";import{join as nl}from"node:path";var ue="sandforge-frozen",el=1e6,Dw=["sasDir","datasetDir"],Pw=["rootObject","excludedObjects","identityKeys","undeletableObjects","requiredLookupPlaceholders","requiredFieldDefaults","picklistRules","defaultPicklistRule","duplicateErrorPatterns"],rl=new Set(["NO_LOAD","ALREADY_REMOVED","NOTHING_TO_REMOVE"]);function sl(e,t,n){let r=["resources",e,"config"],s=f=>({refusals:[N(r,f)]}),o;try{o=tl(nl(n,t.config),"utf8")}catch(f){return s(`${t.config} cannot be read: ${f instanceof Error?f.message:String(f)}`)}if(o.length>el)return s(`${t.config} is larger than ${el} bytes`);let i;try{i=JSON.parse(o.replace(/^\uFEFF/,""))}catch{return s(`${t.config} is not JSON: a Frozen configuration is the panel's, as JSON`)}let a=kr(i);if(a.length>0)return{refusals:a.map(({path:f,secret:h})=>N(r,`${t.config} holds a key shaped like a secret (${h}) at ${f.join(".")}: a load never reads the salt, and the configuration holds no secret. Take it out.`))};let c=au.strict().safeParse(i);if(!c.success)return{refusals:c.error.issues.map(f=>N(r,`${t.config} is refused by Frozen's configuration schema at ${f.path.map(String).join(".")||"its top"}: ${f.message}`))};let u=[],d={...c.data},l=Dw.filter(f=>d[f]!==void 0);for(let f of l)delete d[f];return l.length>0&&u.push(N(r,`${t.config} gives ${l.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:d,dataset:{...t.dataset}},warnings:u}}function ol(e){return{kind:"frozen",kindVersion:1,dataset:{digest:e.dataset.digest,version:e.dataset.version},load:Object.fromEntries(Pw.map(t=>[t,e.config[t]??null]))}}function il(e,t){return{...e.config,sasDir:t.sasDir,datasetDir:t.datasetDir}}async function al(e,t){let n,r;try{n=await Qu(e),r=JSON.parse(tl(nl(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 Sn(e,t){return[e,"--config",I("--config",t.configFile),"--target",I("--target",t.target)]}function cl(e){return[...Sn("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 ul(e){return[...Sn("load",e),...e.reload?["--reload"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],"--max-total",String(e.maxTotal),"--yes","--json"]}function dl(e){return[...Sn("verify",e),"--json"]}function ll(e){return[...Sn("remove",e),...e.includeChanged===!0?["--include-changed"]:[],...ve(e),...e.acceptAutomation===!0?["--accept-automation"]:[],"--yes","--json"]}function fl(e){return[...Sn("remove",e),...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],"--preview",...ve(e),"--json"]}var Nw=p.object({type:p.string().min(1),payload:p.record(p.string(),p.unknown()).optional()}).loose(),$n={tool:p.literal(ue),posted:p.array(Nw),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()},pl=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:R,found:R,notLoaded:R,orphans:R,missingKeys:R}))}),Tw=p.object({...$n,step:p.literal("load"),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:R,toInsert:R,toLink:R,notSent:R,toPurge:R,toDeactivate:R})).optional()}),xw=p.object({...$n,step:p.literal("load"),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:R,inserted:R,reused:R,duplicates:R,failed:R})).optional(),verdict:pl.optional()}),Lw=p.object({...$n,step:p.literal("verify"),verdict:pl.optional()});function An(e,t){return e.filter(n=>n.type===t).at(-1)?.payload}function On(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 Fw=p.object({...$n,step:p.literal("remove")}).transform((e,t)=>{let n=On(e.posted.filter(h=>h.type!=="frozen:remove:automation:error")),r={planned:0,objects:[],userNames:{}};if(n!==void 0&&!rl.has(n.code??""))return{tool:e.tool,preview:r,refusals:[n.message],...n.code!==void 0?{refusalCodes:[n.code]}:{},removalAlone:[]};let s=An(e.posted,"frozen:remove:preview:response")?.preview;if(s===void 0)return{tool:e.tool,preview:r,refusals:[],removalAlone:[]};let o=Mt.extend({refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional()}).loose().safeParse(s);if(!o.success)return t.addIssue({code:"custom",message:`its preview: ${o.error.issues[0]?.message}`}),p.NEVER;let{refusals:i,refusalCodes:a,...c}=o.data,u=e.refusals??[],d=new Map(e.refusalCodes?.length===u.length?u.map((h,m)=>[h,e.refusalCodes?.[m]??""]):[]),l=u.filter(h=>!i.includes(h)),f=l.flatMap(h=>d.get(h)??[]);return{tool:e.tool,preview:c,refusals:i,...a?.length===i.length?{refusalCodes:a}:{},removalAlone:l,...f.length===l.length&&f.length>0?{removalAloneCodes:f}:{}}}),Mw=p.object({...$n,step:p.literal("remove"),status:p.string().optional()}).transform((e,t)=>{let n=On(e.posted),r={tool:e.tool,result:{status:"success",planned:0,objects:[]}};if(n!==void 0)return rl.has(n.code??"")?r:(t.addIssue({code:"custom",message:`the removal was refused: ${n.message}`}),p.NEVER);let s=An(e.posted,"frozen:remove:response")?.result;if(s===void 0)return r;let o=p.object({status:p.enum(["success","partial","failure","cancelled"]),objects:p.array(Qe.loose())}).loose().safeParse(s);return o.success?{tool:e.tool,result:{status:o.data.status,planned:o.data.objects.reduce((i,a)=>i+a.planned,0),objects:o.data.objects}}:(t.addIssue({code:"custom",message:`its result: ${o.error.issues[0]?.message}`}),p.NEVER)});function hl(e){return _(ue,"the answer of a dry run",Tw,e)}function Gr(e){return _(ue,"the answer of a load",xw,e)}function ml(e){return _(ue,"a verification",Lw,e)}function gl(e){return _(ue,"the preview of a removal",Fw,e)}function yl(e){return _(ue,"the outcome of a removal",Mw,e)}function _w(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 zw(e){return(Array.isArray(e?.perObject)?e.perObject:[]).flatMap(n=>{let r=n,s=Number(r.picklistsRewritten??0),o=Number(r.fieldsDropped??0),i=[s>0?`${s} picklist value(s) a restricted picklist of the target refuses, rewritten by their rule`:"",o>0?`${o} field(s) the target lacks or takes no value of, dropped`:""].filter(Boolean);return i.length>0?[`${String(r.objectApiName)}: ${i.join(", ")}`]:[]})}function qw(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 wl(e){let t=On(e.posted),n=[...t!==void 0?[t.message]:[],...e.refusals??[]],r=e.objects??[],s=r.reduce((d,l)=>d+l.toInsert,0),o=An(e.posted,"frozen:load:preview:response")?.plan,i=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=[..._w(o),...zw(o)],c=e.refusals??[],u=i!==void 0?xe(i,n,[...t!==void 0?[t.code??""]:[],...e.refusalCodes?.length===c.length?e.refusalCodes:c.map(()=>"")]):[];return{objects:r.map(d=>({object:d.objectApiName,wouldCreate:d.toInsert})),total:s,created:s,storageBytes:r.reduce((d,l)=>d+Rr(l.objectApiName,{rows:l.toInsert}),0),emails:qw(o),...i!==void 0?{refusal:i}:{},...u.length>0?{refusalCodes:u}:{},...a.length>0?{notes:a}:{}}}function jn(e){let t=On(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 Qr(e){let n=An(e.posted,"frozen:load:response")?.report?.purge;if(n===void 0)return!1;let r=Object.values(n.leftUnrecorded??{}).reduce((s,o)=>s+o,0);return(n.failures??[]).length===0&&r===0}function vl(e){let t=An(e.posted,"frozen:load:response")?.report;return[...Object.values(t?.purge?.deleted??{}),...Object.values(t?.purge?.deactivated??{})].some(r=>r>0)}function ui(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 kl(e){let t=On(e.posted);if(e.verdict===void 0)return{unread:t?.message??"the verification gave no verdict"};let{short:n,unstable:r}=ui(e.verdict);return r?{unread:n??"no two readings agreed"}:{failed:n!==void 0?[n]:[]}}function tt(e){return`frozen/${e}`}function Xr(e){return e!==void 0&&/^frozen\/[a-z][a-z0-9-]{0,62}$/.test(e)?e.slice(7):void 0}import{existsSync as di}from"node:fs";import{rm as Bw}from"node:fs/promises";import{join as bl}from"node:path";var he="sandforge-dataops",El="snapshots.json";function Rl(e){let t={},n=[];for(let[r,s]of Object.entries(e)){let o=iu.safeParse({name:r,rules:s.rules});if(!o.success){n.push(...o.error.issues.map(i=>N(["masking",r,...i.path],`refused by the rules the DataOps panel saves: ${i.message}`)));continue}t[r]={name:r,rules:s.rules}}return n.length>0?{refusals:n}:{sets:t}}function Uw(e){let t=No.find(r=>r.id===e);if(t===void 0)return;let n=t.rules.flatMap(r=>{if(!qc(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 Sl(e,t,n){let r=["resources",e,"rules"],s,o;if(typeof t.rules=="string"){if(s=n[t.rules],o={set:t.rules},s===void 0)return{refusals:[N(r,`the rule set ${t.rules} is refused: see masking`)]}}else{let l=t.rules.template;if(s=Uw(l),o={template:l},s===void 0)return{refusals:[N([...r,"template"],`there is no DataOps template "${l}" that ships: there is `+No.map(f=>f.id).join(", "))]}}let i=t.object;if(i!==void 0&&!Zu({id:s.name,name:s.name,rules:s.rules},i))return{refusals:[N(["resources",e,"object"],`${"set"in o?`the rule set ${o.set}`:`the template ${o.template}`} has no rule for ${i}: a run would mask nothing. Name an object its rules mask, or give it a rule for this one`)]};let a=[],c=`${(i??"").toLowerCase()}.`,u=new Map(s.rules.filter(l=>i!==void 0&&l.fieldPattern.toLowerCase().startsWith(c)).map(l=>[(l.fieldPattern.split(".")[1]??"").toLowerCase(),l.ruleType])),d=Kw(t.where).filter(({field:l,empty:f})=>{let h=u.get(l.toLowerCase());return h!==void 0&&(!f||h==="nullify")}).map(({field:l})=>l);return d.length>0&&a.push(N(["resources",e,"where"],`its condition reads ${d.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:o,rules:s,...i!==void 0?{object:i}:{},...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 Kw(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 o=/^(?:=|!=|<>)$/.test(r[2]??"")&&r[3]!==void 0;n.set(s,(n.get(s)??!0)&&o)}return[...n].map(([r,s])=>({field:r,empty:s}))}function $l(e){return{kind:"mask",kindVersion:1,rules:[...e.rules.rules].map(t=>({...t,fieldPattern:t.fieldPattern.toLowerCase()})).sort((t,n)=>Ft(t).localeCompare(Ft(n))),object:e.object??null,where:e.where??null}}function Al(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 Ol(e){return{name:e.rules.name,rules:e.rules.rules}}function Bt(e){return`dataops/${e}`}function jl(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"]:[],...t.slices===!0?["--slices"]:[],...t.maxRecords!==void 0?["--max-records",String(t.maxRecords)]:[],...t.maxRequests!==void 0?["--max-requests",String(t.maxRequests)]:[]]}function Cl(e){return[...jl(e),"--dry-run","--json"]}function Il(e){return[...jl(e),"--yes","--json"]}var Vw=p.object({type:p.string().min(1),payload:p.record(p.string(),p.unknown()).optional()}).loose(),nt=p.number().int().nonnegative(),Dl={tool:p.literal(he),org:p.string().min(1),posted:p.array(Vw)},Ww=p.object({...Dl,command:p.literal("dry-run"),slices:p.literal(!0).optional()}),Hw=p.object({...Dl,command:p.literal("run")});function Pl(e){return _(he,"the answer of a dry run",Ww,e)}function Zr(e){return _(he,"the answer of a masking",Hw,e)}function qt(e,t){return e.filter(n=>n.type===t).at(-1)?.payload}function Nl(e){let t=qt(e,"dataops:error");if(t!==void 0)return typeof t.message=="string"?t.message:"refused"}var Yw=p.object({objects:p.array(p.object({objectApiName:p.string().min(1),count:nt.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:nt,total:nt,savedAt:p.string(),state:p.string()}).loose().optional()}),Jw=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()}))}),Gw=p.object({emails:p.array(p.object({limit:p.enum(["SingleEmail","DailyWorkflowEmails"]),emails:nt}).loose()),refusals:p.array(p.object({code:p.string(),message:p.string()}).loose())}).loose();function Tl(e){let t=[],n=Nl(e.posted);n!==void 0&&t.push(n);let r=Yw.safeParse(qt(e.posted,"dataops:anonymize:coverage:response")),s=Jw.safeParse(qt(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 o=Gw.safeParse(qt(e.posted,"dataops:automation:response")),i=r.data.objects.map(d=>({object:d.objectApiName,count:d.count}));for(let d of r.data.objects){let l=d.slicePlan;d.count===null&&!(e.slices===!0&&l!==void 0)&&t.push(`${d.objectApiName}: the org did not count the records it would mask`),e.slices!==!0&&l!==void 0&&(d.count??0)>l.size&&t.push(`${d.objectApiName} holds ${d.count??0} record(s), more than the ${l.size} a snapshot holds of one object: a run is refused and masks nothing (slices: true masks it in ${l.slices} slices, each backed up just before it is masked, or maxRecords takes up to ${_c})`)}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 ${B("dataops")} anonymize and the resource's store, --resume or --abandon`);for(let d of s.data.objects){d.error!==void 0?t.push(`${d.objectApiName}: not read: ${d.error}`):d.notCovered===!0&&t.push(`${d.objectApiName}: its rules mask no field the org shows this user: a run would mask nothing there`);let l=d.writeDenied?.deniedFields;l?.length===0&&t.push(zo(d.objectApiName));for(let f of l??[])t.push(zo(d.objectApiName,f))}for(let d of s.data.fieldsNotFound)t.push(_o(d.objectApiName,d.fieldApiName));let c=new Map;for(let d of o.success?o.data.refusals:[])t.push(d.message),c.set(d.message,d.code);let u=o.success?o.data.emails.map(({limit:d,emails:l})=>({limit:d,emails:l})):[];return{objects:i,refusals:t,refusalCodes:t.map(d=>c.get(d)??""),emails:u}}function xl(e){let t=Tl(e),n=t.objects.map(o=>({object:o.object,wouldCreate:o.count??0})),r=t.refusals.length>0?t.refusals.join(" "):void 0,s=r!==void 0?xe(r,t.refusals,t.refusalCodes):[];return{objects:n,total:n.reduce((o,i)=>o+i.wouldCreate,0),created:0,storageBytes:0,emails:t.emails,...r!==void 0?{refusal:r}:{},...s.length>0?{refusalCodes:s}:{}}}var Qw=p.object({status:p.string().optional(),objects:p.array(p.object({objectApiName:p.string().min(1),total:nt,processed:nt,failed:nt,notMasked:nt}).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 Cn(e){let t=Qw.safeParse(qt(e.posted,"dataops:anonymize:response")??qt(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=Nl(e.posted),o=(n.fieldsNotFound??[]).map(a=>_o(a.objectApiName,a.fieldApiName)),i=n.snapshot?.operationId??n.slices?.setId;return{objects:r,...i!==void 0?{snapshotId:i}:{},...s!==void 0?{refusal:s}:{},...o.length>0?{short:o.join("; ")}:{}}}var Xw=new Set(["frozen","replay"]);function Ll(e,t,n){let r=t?.resources[e]?.runs.at(-1)?.startedAt,s=n.indexOf(e);if(t===void 0||r===void 0||s<0)return[];let o=[];for(let i of n.slice(s+1)){let a=t.resources[i];if(a===void 0||a.status==="destroyed")continue;let c=a.runs.filter(u=>u.takenBack!==!0);for(let u of a.kind==="frozen"?c.slice(-1):c)Date.parse(u.startedAt)<Date.parse(r)||o.push({run:u,named:!Xw.has(a.kind)||u===c.at(-1)})}return o}function li(e,t,n){e.set(t,(e.get(t)??0)+n)}function pi(e,t,n,r){let s=new Map;for(let{run:o}of Ll(e,t,n))for(let i of o.objects)i.created>0&&li(s,i.objectApiName,i.created);return r===void 0?{theirs:s,unsure:new Map}:{theirs:new Map,unsure:s}}function Zw(e){return e.slice(0,15)}async function Fl(e,t,n,r,s){if(r===void 0)return pi(e,t,n,void 0);let o=u=>u.toLowerCase()===r.object.toLowerCase(),i=new Map,a=new Map;for(let{run:u,named:d}of Ll(e,t,n)){let l=d?await s.createdBy(u).catch(()=>{}):void 0,f=l!==void 0&&"created"in l?l.created:void 0;for(let h of u.objects)h.created<=0||f!==void 0&&o(h.objectApiName)||li(i,h.objectApiName,h.created);for(let[h,m]of f??[])if(o(h))for(let g of m)a.set(Zw(g),g)}let c=new Map;if(a.size===0)return{theirs:c,unsure:i};try{let u=su(r.object),d=ru(r.where),l=0;for(let f of cu([...a.values()]))l+=await s.count(`SELECT COUNT() FROM ${u} WHERE (${d}) AND Id IN (${f})`);c.set(r.object,l)}catch{li(i,r.object,a.size)}return{theirs:c,unsure:i}}function Ml(e,t,n={theirs:new Map,unsure:new Map}){let r=Tl(t),s=e.runs.at(-1),o=new Map((s?.objects??[]).map(u=>[u.objectApiName,u.masked??0]));if(r.refusals.length>0)return{objects:[],masked:0,unread:r.refusals.join(" ")};let i=[],a=[],c=0;for(let{object:u,count:d}of r.objects){let l=d??0,f=o.get(u)??0,h=Math.min(Math.max(0,l-f),n.theirs.get(u)??0);if(c+=h,a.push({object:u,present:Math.min(l,f),...l<f?{gone:f-l}:{}}),l-h>f){let m=h>0?`, ${h} created since by the resources applied after it`:"",g=n.unsure.get(u)??0,w=g>0?`, unless they are among the ${g} the resources applied after it created since, whose ids could not be counted under its condition`:"";i.push(`${u} ${l} under its condition, ${f} masked${m}: ${l-h-f} more, which hold their original values${w}`)}else l<f&&i.push(`${u} ${l} under its condition, ${f} masked: ${f-l} gone`)}return{objects:a,masked:[...o.values()].reduce((u,d)=>u+d,0),...c>0?{theirs:c}:{},...i.length>0?{drift:i.join("; ")}:{}}}function fi(e,t){return`${B("dataops")} anonymize --org ${e.alias} --restore ${t} --store ${e.store??"<its store>"}`}function _l(e,t){return t.store??`${Bt(e)} beside the state`}function zl(e,t){return[`masking is one-way: each run first takes a snapshot of the values it writes over, kept on this machine in ${_l(e,t)}, and destroy never puts them back: it deletes the snapshots. Putting them back is your own act, before a destroy: `+fi(t,"<the snapshot its run names>")]}function ql(e){return e.runs.find(t=>t.takenBack!==!0)}function ev(e){let t=ql(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 hi(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 ${ev(e)}, which destroy deletes`}var Bl={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 Ul(e,t=0){return`applied, and its condition selects the ${e} record(s) it masked, with the same rules${t>0?`, beside ${t} the resources applied after it created since`:""}: masked again they would only be masked twice`}function Kl(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 mi(e,t,n,r){let s=ql(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, ${_l(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: ${fi(r,s)}`:`Its snapshots are listed in its store: ${fi(r,"<snapshot>")} puts one back, before this ${e}, as your own act`)}async function Vl(e){if(!di(e))return{snapshots:[]};let t=di(bl(e,El))?Eu(bl(e,El)).getKeysByPrefix("backup:").map(n=>n.slice(7)).filter(n=>!n.includes(":")):[];if(await Bw(e,{recursive:!0,force:!0}),di(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 Wl(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`}import{existsSync as tv,readFileSync as nv}from"node:fs";import{isAbsolute as rv}from"node:path";var V="sandforge-checkpoint",gi="REPLAY_CHECKPOINT_NOT_FOUND",Gl=new Set(["NO_LOAD","ALREADY_REMOVED","NOTHING_TO_REMOVE"]);function Ql(e){return{owners:e.owners??"same",customSettings:e.customSettings===!0,mask:e.mask===!0,contactPoints:e.keepContactPoints===!0?"kept":"neutralized",objects:e.objects??[],excluded:e.excludeObjects??[],link:[]}}var sv={owners:"owners",customSettings:"customSettings",mask:"mask",contactPoints:"keepContactPoints",objects:"objects",excluded:"excludeObjects"};function Xl(e,t){let n={checkpoint:t.checkpoint,...t.from!==void 0?{from:t.from}:{},...t.objects!==void 0?{objects:t.objects}:{},...t.excludeObjects!==void 0?{excludeObjects:t.excludeObjects}:{},...t.owners!==void 0?{owners:t.owners}:{},...t.customSettings!==void 0?{customSettings:t.customSettings}:{},...t.mask!==void 0?{mask:t.mask}:{},...t.keepContactPoints!==void 0?{keepContactPoints:t.keepContactPoints}:{},...t.maxRecords!==void 0?{maxRecords:t.maxRecords}:{},...t.accept?.automation===!0?{acceptAutomation:!0}:{}},r=zc.safeParse(Ql(n));return r.success?{run:n,warnings:[]}:{refusals:r.error.issues.map(s=>{let[o,...i]=s.path,a=sv[String(o)]??String(o);return N(["resources",e,a,...i],`refused by the choices a replay takes: ${s.message}`)})}}function Hl(e){return e===void 0||e.length===0?null:[...new Set(e.map(t=>t.toLowerCase()))].sort()}function Zl(e){return(e.objects??[]).map(t=>({object:t}))}function ef(e,t,n){if(typeof t=="string")return{file:t};let r=["resources",e,"checkpoint","file"],s=(n[t.env]??"").trim();return s===""?{refusal:N(r,`the variable ${t.env} is not set: set it in the job's environment to the path of the checkpoint file ${e} replays`)}:rv(s)?{file:s}:{refusal:N(r,`the variable ${t.env} holds ${s}, which is not a path from the root: give the checkpoint file from the root`)}}function ov(e){return e.checkpoint!==void 0&&(e.valid||e.why==="refreshed"||e.why==="scratchExpired")}function Yl(e,t){return e.slice(0,15)===t.slice(0,15)}function iv(e){return[...e].sort((t,n)=>(n.checkpoint?.takenAt??"").localeCompare(t.checkpoint?.takenAt??""))[0]}function Jl(e){return{checkpointId:e.checkpointId,organizationId:e.organizationId,...e.checkpoint!==void 0?{name:e.checkpoint.name,takenAt:e.checkpoint.takenAt}:{}}}function av(e,t){return`take one before the next refresh: ${B("checkpoint")} take --org ${t} --name ${e}; or name an exported file: checkpoint: { file: \u2026, keyEnv: \u2026 }`}function cv(e,t,n,r){let{checkpoint:s}=e,o=n.filter(ov);if(s.id!==void 0){let d=o.filter(h=>h.checkpointId===s.id),l=[...new Set(d.map(h=>h.organizationId.slice(0,15)))],f=d[0];return f!==void 0&&l.length===1?Jl(f):l.length>1?{code:"AMBIGUOUS",refusal:`checkpoints of ${l.length} orgs have the id ${s.id} on this machine: name it by name with from, the org role it was taken of`}:{code:gi,refusal:`no checkpoint ${s.id} is kept on this machine: "${B("checkpoint")} list" names those it keeps`}}let i=s.name??"",a,c;if(t.from!==void 0){let d=t.from,l=o.filter(f=>{let h=f.checkpoint?.org;return h!==void 0&&(h.alias===d||h.username.toLowerCase()===d.toLowerCase())}).map(f=>f.organizationId);a=o.filter(f=>l.some(h=>Yl(h,f.organizationId))),c=`of ${d}`}else{let d={name:r.alias,organizationId:r.organizationId,...r.username!==void 0?{username:r.username}:{},...r.instanceUrl!==void 0?{instanceUrl:r.instanceUrl}:{}};a=o.filter(l=>l.checkpoint!==void 0&&!Yl(l.organizationId,r.organizationId)&&Uu(l.checkpoint.org,d)!==void 0),c=`of ${r.alias} before its refresh`}let u=iv(a.filter(d=>d.checkpoint?.name===i));return u!==void 0?Jl(u):{code:gi,refusal:`no checkpoint ${c} named '${i}' is kept on this machine: `+av(i,t.from??r.alias)}}async function tf(e,t,n,r){if(e.checkpoint.file!==void 0){if(t.file===void 0)return{code:gi,refusal:"its checkpoint file was not resolved"};let o=await(r.readHeader??Mu)(t.file);if("refusal"in o)return{code:o.refusal.code,refusal:o.refusal.message};let{header:i}=o.read;return{checkpointId:i.checkpointId,organizationId:i.organizationId,takenAt:i.takenAt}}let s=[];for(let o of[r.storeRoot,_u(r.storeRoot)]){if(!tv(o))continue;let i=hu({root:o,...r.locksDir!==void 0?{locksDir:r.locksDir}:{}});if("refusal"in i)return{code:"STORE_REFUSED",refusal:`the checkpoints kept in ${o} cannot be read: `+pu(i.refusal,o,"SANDFORGE_JOURNAL_DIR")};s.push(...await i.store.list())}return cv(e,t,s,n)}function nf(e,t){let n=t!==void 0&&"checkpointId"in t?t:void 0,r=Ql(e);return{kind:"replay",kindVersion:1,checkpoint:n!==void 0?{id:n.checkpointId,organizationId:n.organizationId.slice(0,15)}:{unread:e.checkpoint.id??(e.checkpoint.name!==void 0?{name:e.checkpoint.name,from:e.from??null}:"file")},owners:r.owners,customSettings:r.customSettings,mask:r.mask,contactPoints:r.contactPoints,objects:Hl(e.objects),excludeObjects:Hl(e.excludeObjects)}}function uv(e){let{run:t,place:n}=e;if(t.checkpoint.file!==void 0){if(n.file===void 0||t.checkpoint.keyEnv===void 0)throw new Error(`${e.name} names a checkpoint file that was not resolved: plan again.`);return["--file",I("--file",n.file),"--key-env",I("--key-env",t.checkpoint.keyEnv)]}let r=n.read;if(r!==void 0&&"checkpointId"in r)return["--checkpoint",I("--checkpoint",r.checkpointId),"--from",I("--from",r.organizationId)];if(t.checkpoint.id!==void 0)return["--checkpoint",I("--checkpoint",t.checkpoint.id)];throw new Error(`${e.name} names its checkpoint by a name this plan has not resolved: plan again.`)}function dv(e){return[...e.objects!==void 0&&e.objects.length>0?["--objects",I("--objects",e.objects.join(","))]:[],...(e.excludeObjects??[]).flatMap(t=>["--exclude-object",I("--exclude-object",t)]),...e.owners!==void 0?["--owners",e.owners]:[],...e.customSettings===!0?["--custom-settings"]:[],...e.mask===!0?["--mask"]:[],...e.keepContactPoints===!0?["--keep-contact-points"]:[]]}function rf(e){return["replay",...uv(e),"--target",I("--target",e.target),"--store",I("--store",e.store),...dv(e.run),...e.again?["--again"]:[],...e.acceptAutomation===!0||e.run.acceptAutomation===!0?["--accept-automation"]:[]]}function sf(e){return[...rf(e),...e.run.maxRecords!==void 0?["--max-records",String(e.run.maxRecords)]:[],"--dry-run","--json"]}function of(e){if(!Number.isInteger(e.maxRecords)||e.maxRecords<1)throw new Error(`${e.name} has no count from its dry run to be held to: plan again.`);return[...rf(e),"--max-records",String(e.maxRecords),"--yes","--json"]}function af(e){return["replay","--checkpoint",I("--checkpoint",e.replayed.checkpointId),"--from",I("--from",e.replayed.organizationId),"--target",I("--target",e.target),"--store",I("--store",e.store),"--remove",...e.includeChanged===!0?["--include-changed"]:[]]}function cf(e){return[...af(e),...ve(e),...e.acceptAutomation===!0?["--accept-automation"]:[],"--yes","--json"]}function uf(e){return[...af(e),"--preview",...ve(e),...e.acceptAutomation===!0?["--accept-automation"]:[],"--json"]}var lv=p.object({command:p.literal("replay"),checkpoint:p.object({id:p.string().min(1),organizationId:p.string().min(1)}).loose()}).loose();function es(e){let t;try{let n=lv.safeParse(JSON.parse(nv(e,"utf8")));t=n.success?n.data:void 0}catch{t=void 0}if(t===void 0)throw new Error(`${e} names no checkpoint a replay wrote from: the replay it is the summary of cannot be taken back from it.`);return{checkpointId:t.checkpoint.id,organizationId:t.checkpoint.organizationId}}var fv=p.object({code:p.string().min(1),message:p.string().min(1)}).loose(),yi={command:p.literal("replay"),checkpoint:p.object({id:p.string().min(1),name:p.string().optional(),organizationId:p.string().min(1),takenAt:p.string().optional()}).loose(),target:p.object({alias:p.string().min(1),organizationId:p.string().optional()}).loose(),refusals:p.array(p.string()).optional(),refusalCodes:p.array(p.string()).optional(),refused:fv.optional(),ended:p.literal(!0).optional(),exit:p.number().int()},df=p.object({records:p.object({toCreate:R}).loose(),owners:p.object({kept:R,toRunningUser:R}).loose().optional(),filesLeft:p.array(p.object({objectApiName:p.string()}).loose()),refused:p.array(p.object({object:p.string().min(1),records:R,reason:p.string().min(1),path:p.string().optional()}).loose()).optional(),requests:R}).loose(),pv=p.object({apiRequests:p.object({estimate:R}).loose()}).loose(),hv=p.object({...yi,action:p.literal("dryRun"),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:R,toInsert:R,toLink:R,notSent:R,toPurge:R}).loose()).optional(),plan:p.record(p.string(),p.unknown()).optional(),replay:df.optional()}),mv=p.object({...yi,action:p.literal("replay"),status:p.string().optional(),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:R,inserted:R,failed:R}).loose()).optional(),result:p.record(p.string(),p.unknown()).optional(),replay:df.optional()}),lf=p.object({...yi,action:p.literal("remove"),preview:p.literal(!0).optional(),objects:p.array(p.record(p.string(),p.unknown())).optional(),removal:p.record(p.string(),p.unknown()).optional()}),gv=p.object({objectApiName:p.string().min(1),planned:R,toDelete:R,alreadyGone:R,changedSince:R,keptChanged:R,undeletable:R,notVisible:R,unread:R}).loose(),yv=lf.transform((e,t)=>{let n={planned:0,objects:[],userNames:{}},r=e.refused;if(r!==void 0&&Gl.has(r.code))return{tool:V,preview:n,refusals:[],removalAlone:[]};let s=[...r!==void 0?[r.message]:[],...e.refusals??[]],o=e.refusalCodes??[],i=[...r!==void 0?[r.code]:[],...o.length===(e.refusals??[]).length?o:[]],a=p.array(gv).safeParse(e.objects??[]);if(!a.success)return t.addIssue({code:"custom",message:`its preview: ${a.error.issues[0]?.message}`}),p.NEVER;let c=a.data.map(u=>({objectApiName:u.objectApiName,planned:u.planned,toDelete:u.toDelete,alreadyGone:u.alreadyGone,changedSince:u.changedSince,keptChanged:u.keptChanged,changedBy:{},undeletable:u.undeletable,notVisible:u.notVisible,unread:u.unread,reasons:[]}));return{tool:V,preview:{planned:c.reduce((u,d)=>u+d.planned,0),objects:c,userNames:{}},refusals:s,...i.length===s.length&&i.length>0?{refusalCodes:i}:{},removalAlone:[]}}),wv=lf.transform((e,t)=>{let n={tool:V,result:{status:"success",planned:0,objects:[]}},r=e.refused;if(e.removal===void 0)return r===void 0||Gl.has(r.code)?n:(t.addIssue({code:"custom",message:`the removal was refused: ${r.message}`}),p.NEVER);let s=p.object({status:p.enum(["success","partial","failure","cancelled"]),objects:p.array(Qe.loose())}).loose().safeParse(e.removal);return s.success?{tool:V,result:{status:s.data.status,planned:s.data.objects.reduce((o,i)=>o+i.planned,0),objects:s.data.objects}}:(t.addIssue({code:"custom",message:`its result: ${s.error.issues[0]?.message}`}),p.NEVER)});function ff(e){let t=_(V,"the answer of a replay\u2019s dry run",hv,e);return{tool:V,...t}}function ts(e){return _(V,"the answer of a replay",mv,e)}function pf(e){return _(V,"the preview of a removal",yv,e)}function hf(e){return _(V,"the outcome of a removal",wv,e)}function vv(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 mf(e){let t=[...e.refused!==void 0?[e.refused.message]:[],...e.refusals??[]],n=e.objects??[],r=n.reduce((d,l)=>d+l.toInsert,0),s=t.length>0?t.join(" "):e.objects===void 0?"the replay never came to say what it would create, and a run held to no count is held to nothing":r===0?"it would create nothing: every record of the checkpoint is one the org holds already, linked, or one the replay leaves out":void 0,o=e.refusals??[],i=s!==void 0?xe(s,t,[...e.refused!==void 0?[e.refused.code]:[],...e.refusalCodes?.length===o.length?e.refusalCodes:o.map(()=>"")]):[],a=e.replay,c=[...a!==void 0&&a.filesLeft.length>0?[`${a.filesLeft.length} file(s) of the checkpoint are not replayed: a checkpoint keeps no file\u2019s content`]:[],...a?.owners!==void 0&&a.owners.toRunningUser>0?[`${a.owners.toRunningUser} record(s) go to the user connected: their owner is not an active user of the org`]:[],...gf(a).map(d=>`${d.object}: ${d.records} record(s) refused before anything is written, which leave a run partial \u2014 ${Mo(d)}`)],u=pv.safeParse(e.plan);return{objects:n.map(d=>({object:d.objectApiName,wouldCreate:d.toInsert})),total:r,created:r,...u.success?{apiRequests:u.data.apiRequests.estimate}:{},storageBytes:n.reduce((d,l)=>d+Rr(l.objectApiName,{rows:l.toInsert}),0),emails:vv(e.plan),...s!==void 0?{refusal:s}:{},...i.length>0?{refusalCodes:i}:{},...c.length>0?{notes:c}:{}}}function gf(e){return(e?.refused??[]).filter(t=>t.records>0)}function ns(e){let t=(e.objects??[]).map(n=>({object:n.objectApiName,created:n.inserted,refused:n.failed,errors:n.failed>0?[`${n.failed} refused by the org`]:[]}));if(t.length===0&&e.refused!==void 0)return{objects:[],created:0,refusal:e.refused.message};for(let n of gf(e.replay)){let r=`${n.records} refused before anything is written \u2014 ${Mo(n)}`,s=t.find(o=>o.object===n.object);s!==void 0?(s.refused+=n.records,s.errors.push(r)):t.push({object:n.object,created:0,refused:n.records,errors:[r]})}return{objects:t,created:t.reduce((n,r)=>n+r.created,0)}}function rs(e){let t=e.result?.purge;if(t===void 0)return!1;let n=Object.values(t.leftUnrecorded??{}).reduce((r,s)=>r+s,0);return(t.failures??[]).length===0&&n===0}var re="sandforge-seed",kv="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 vf(e,t,n,r){let s=bv(e,t,n,r);if("refusal"in s)return{refusals:[s.refusal]};let o=Rv(t,n,s.run);return o.refusals.length>0?{refusals:o.refusals}:{run:s.run,warnings:o.warnings}}function bv(e,t,n,r){let s=r.toISOString(),o={id:`env-${e}-${t}`,name:`${e}/${t}`,description:`The ${t} resource of the ${e} environment`,version:1,tags:["sandforge-env"],createdAt:s,updatedAt:s},i,a=[];if(n.template!==void 0){let u=Do.find(d=>d.id===n.template);if(u===void 0)return{refusal:N(["resources",t,"template"],`there is no built-in template "${n.template}": there is ${Do.map(d=>d.id).join(", ")}`)};i={...o,strategy:u.strategy,objects:structuredClone(u.objects),...u.relations!==void 0?{relations:structuredClone(u.relations)}:{}}}else i={...o,strategy:"faker",objects:(n.objects??[]).map((u,d)=>({objectApiName:u.object,recordCount:u.count,fieldRules:structuredClone(u.fields??[]),excludedFields:[],insertOrder:d,batchSize:u.batchSize??200})),...n.relations!==void 0?{relations:n.relations.flatMap((u,d)=>{let l=u.parents.from;if(l===void 0)return[yf(u)];let{childObject:f,lookupField:h,parentObject:m,distribution:g}=yf(u);return a.push({at:d,relation:{childObject:f,lookupField:h,parentObject:m,distribution:g},from:l.split(".")[0]??l,...u.parents.limit!==void 0?{limit:u.parents.limit}:{}}),[]})}:{}};let c=Object.fromEntries((n.objects??[]).filter(u=>u.recordTypes!==void 0).map(u=>[u.object,[...new Set(u.recordTypes)]]));return{run:{template:i,...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 Ev(e){return e.object??e.from?.split(".")[1]??""}function yf(e){let[t="",n=""]=e.lookup.split("."),r=e.parents.existing;return{childObject:t,lookupField:n,parentObject:Ev(e.parents),parents:r===void 0?{kind:"generated"}:{kind:"existing",...r.where!==void 0?{where:r.where}:{},limit:r.limit},distribution:e.distribution}}function kf(e){return{kind:"existing",limit:e.limit??yr.maxExistingParents}}function bf(e,t){let n=[...e.template.relations??[]],r=e.draws??[],s=[];for(let o=0;o<n.length+r.length;o++){let i=r.find(c=>c.at===o),a=i!==void 0?{...i.relation,parents:t(i)}:n.shift();a!==void 0&&s.push(a)}return s}function wi(e,t,n){return(e.draws??[]).length===0?e.template:{...e.template,relations:bf(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 kf(r)})}}var wf=Object.keys(xu);function Rv(e,t,n){let r=["resources",e],s=wi(n,void 0,{standIns:!0}),o=ou.safeParse(s);if(!o.success)return{refusals:o.error.issues.map(u=>N(Sv(r,t,u.path),u.message)),warnings:[]};let i=new Fu().validate(s),a=({field:u,message:d})=>N($v(r,t,s,u),d),c=n.locale!==void 0&&!wf.includes(n.locale)?[N([...r,"locale"],`the seed draws in ${wf.join(", ")}, not ${n.locale}: name one of them, or leave locale out to draw in the org\u2019s own`)]:[];return{refusals:[...i.errors.map(a),...c],warnings:i.warnings.map(a)}}function Sv(e,t,n){if(t.template!==void 0)return[...e,"template"];let[r,s,o,...i]=n;if(r==="objects"&&typeof s=="number"){let a=[...e,"objects",s];return o==="objectApiName"?[...a,"object"]:o==="recordCount"?[...a,"count"]:o==="fieldRules"?[...a,"fields",...i]:o===void 0?a:[...a,o]}if(r==="relations"&&typeof s=="number"){let a=[...e,"relations",s];return o==="childObject"||o==="lookupField"?[...a,"lookup"]:o==="parentObject"?[...a,"parents","object"]:o==="parents"?[...a,"parents","existing",...i]:o===void 0?a:[...a,o,...i]}return e}function $v(e,t,n,r){if(t.template!==void 0)return[...e,"template"];let s=/^objects\[([^\]]+)\](?:\.fieldRules\[([^\]]+)\])?/.exec(r);if(s!==null){let i=n.objects.findIndex(u=>u.objectApiName===s[1]);if(i<0)return e;let a=s[2],c=a===void 0?-1:(n.objects[i]?.fieldRules??[]).findIndex(u=>u.fieldApiName===a);return c<0?[...e,"objects",i]:[...e,"objects",i,"fields",c]}let o=/^relations\[([^\]]+)\]/.exec(r);if(o!==null){let i=(n.relations??[]).findIndex(a=>`${a.childObject}.${a.lookupField}`===o[1]);return i<0?e:[...e,"relations",i]}return e}function Ef(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 Rf(e){return e.template.objects.map(t=>({object:t.objectApiName,count:t.recordCount}))}function Sf(e){let{template:t}=e,n=bf(e,kf),r=new Set(n.filter(s=>s.parents.kind==="existing").map(s=>s.childObject));for(let s=!0;s;){s=!1;for(let o of t.objects)r.has(o.objectApiName)||Mc(o,n).some(i=>r.has(i))&&(r.add(o.objectApiName),s=!0)}return new Map(t.objects.filter(s=>r.has(s.objectApiName)).map(s=>[s.objectApiName,s.recordCount]))}function $f(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 Af(e){return[...$f(e),"--json","--fail-on-partial"]}function Of(e){return[...$f(e),"--dry-run","--json"]}function jf(e){return[...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],...e.leaveUndeletable===!0?["--leave-undeletable"]:[]]}function Cf(e){return["--remove",I("--remove",e.summary),"--target",I("--target",e.target),...jf(e),...ve(e),"--json"]}function If(e){return["--remove",I("--remove",e.summary),"--target",I("--target",e.target),"--preview",...jf(e),...ve(e),"--json"]}var Av=p.object({limit:p.enum(["SingleEmail","DailyWorkflowEmails"]),emails:R,verdict:p.enum(["fits","exceeds","unread"]),remaining:p.number().int().optional(),max:p.number().int().optional(),unread:p.string().optional()}),Ov=p.object({checks:p.array(Av),refusal:p.string().optional(),unknown:p.array(p.string()).optional()}),jv=p.object({records:R,given:R,refusal:p.string().optional()}),Cv=e=>p.object({objectApiName:p.string().min(1),recordsCreated:R,recordsFailed:R,createdIds:p.array(e),errors:p.array(p.string()),truncated:p.boolean().optional(),writtenByThePlatform:jv.optional()}),Df=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(Cv(e)),totalRecordsCreated:R,totalRecordsFailed:R}),Pf={tool:p.literal(re),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:Ov,elapsedMs:R,interrupted:p.literal(!0).optional()},Iv=p.object({...Pf,dryRun:p.literal(!1),targetOrgId:Ge.optional(),result:Df(Ge),runFile:p.string().min(1).optional()}),Dv=p.object({bytes:R,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()}),Pv=p.object({estimate:R,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()}),Nv=p.object({...Pf,dryRun:p.literal(!0),storage:Dv,apiRequests:Pv,wouldBeRefused:p.array(p.string()).optional(),wouldBeRefusedCodes:p.array(p.string()).optional(),result:Df(p.string())}),Tv=p.object({tool:p.literal(re),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:R,objects:p.array(Qe),sweep:p.object({status:p.string()}).loose().optional()}),elapsedMs:R}),xv=p.object({tool:p.literal(re),action:p.literal("remove-preview"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),preview:Mt,refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional(),notes:p.array(p.string()),elapsedMs:R});function Ut(e){return _(re,"the summary of a run",Iv,e)}function Nf(e){return _(re,"the summary of a dry run",Nv,e)}function Tf(e){return _(re,"the preview of a removal",xv,e)}function xf(e){return _(re,"the outcome of a removal",Tv,e)}var Lf="validation";function Ff(e,t){let n=e.result.objectResults,r=c=>{let u=xe(c,e.wouldBeRefused,e.wouldBeRefusedCodes);return u.length>0?{refusalCodes:u}:{}};if(e.result.status==="failure"&&n.length>0&&n.every(c=>c.objectApiName===Lf)){let c=n.flatMap(d=>d.errors),u=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:u,...r(u)}}let s=e.result.objectResults.map(c=>{let u=t?.get(c.objectApiName);return u!==void 0?{object:c.objectApiName,wouldCreate:Math.max(c.recordsCreated,u),atMost:!0}:{object:c.objectApiName,wouldCreate:c.recordsCreated}}),o=e.storage.refusal??e.apiRequests.refusal??e.emails.refusal,i=o!==void 0&&o===e.storage.refusal?`${o} ${kv}`:o,a=e.result.objectResults.flatMap(c=>c.writtenByThePlatform!==void 0?[Lv(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})),...i!==void 0&&o!==void 0?{refusal:i,...r(o)}:{},...a.length>0?{notes:a}:{}}}function Lv(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 ss(e){let t=e.result.objectResults;if(e.result.status==="failure"&&t.length>0&&t.every(n=>n.objectApiName===Lf)){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}}import{readFileSync as Fv}from"node:fs";var W="sandforge-users",_f=999999;function zf(e){return{run:{...e.defaults!==void 0?{defaults:e.defaults}:{},users:e.users,...e.accept?.automation===!0?{acceptAutomation:!0}:{}},warnings:[]}}function vi(e){return e===void 0||e.length===0?null:[...new Set(e.map(t=>t.toLowerCase()))].sort()}function qf(e){return{kind:"users",kindVersion:1,users:Uc(ki(e)).map(n=>({username:Bc(n.username),email:n.email??"keep",active:n.active??null,frozen:n.frozen??null,profile:n.profile??null,permissionSets:vi(n.permissionSets),permissionSetGroups:vi(n.permissionSetGroups),groups:vi(n.groups)})).sort((n,r)=>n.username<r.username?-1:n.username>r.username?1:0)}}function Bf(e){return[{object:"User",count:e.users.length}]}function ki(e){return{...e.defaults!==void 0?{defaults:e.defaults}:{},users:e.users}}function Uf(e,t){if(!Number.isInteger(t)||t<1||t>_f)throw new Error(`${e} takes the number of a run of sandforge users, not ${t}.`);return String(t)}function Kf(e,t){return[e,"--org",I("--org",t.target),"--config",I("--config",t.configFile),...t.replacesRun!==void 0?["--replaces",Uf("--replaces",t.replacesRun)]:[],...t.acceptUserEmails===!0?["--accept-user-emails"]:[],...t.acceptAutomation===!0?["--accept-automation"]:[]]}function Vf(e){return[...Kf("plan",e),"--json"]}function Wf(e){return[...Kf("apply",e),"--yes","--json"]}function Hf(e){return["remove","--org",I("--org",e.target),"--run",Uf("--run",e.run),...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],"--yes","--json"]}var Mv=p.object({run:p.number().int().positive().max(_f)}).loose();function In(e){try{let t=Mv.safeParse(JSON.parse(e));return t.success?t.data.run:void 0}catch{return}}function Yf(e){let t;try{t=Fv(e,"utf8")}catch(r){throw new Error(`${e} cannot be read (${r instanceof Error?r.message:String(r)}): the run of sandforge users it names cannot be taken back from it.`)}let n=In(t);if(n===void 0)throw new Error(`${e} names no run of sandforge users: the run it is the summary of cannot be taken back from it.`);return n}function Jf(e){let t=_(W,"the answer of a plan",wr,e);return{tool:W,...t}}function Kt(e){return _(W,"the answer of a run",yt,e)}function Mf(e){return e.what==="permissionSet"||e.what==="permissionSetGroup"?"PermissionSetAssignment":e.what==="group"?"GroupMember":void 0}function Gf(e){let t=_(W,"the outcome of a removal",vr,e),n=new Map,r=i=>{let a=n.get(i)??{deleted:0,refused:0,reasons:[]};return n.set(i,a),a},s=[];for(let i of t.users){for(let a of i.undone){let c=Mf(a);c!==void 0&&(r(c).deleted+=1)}for(let a of i.kept??[]){s.push({username:i.username,change:a.change,why:a.why});let c=Mf(a.change);if(c===void 0)continue;let u=r(c);u.refused+=1,u.reasons.push(`${i.username}: ${Rt(a.change)}: ${a.why}`)}}let o=[...n].map(([i,a])=>({objectApiName:i,planned:a.deleted+a.refused,deleted:a.deleted,alreadyGone:0,keptChanged:0,keptDependents:0,refused:a.refused,heldBy:[],reasons:a.reasons}));return{tool:W,result:{status:t.status,planned:o.reduce((i,a)=>i+a.planned,0),objects:o},undone:t.users.reduce((i,a)=>i+a.undone.length,0),kept:s,answer:t}}function Rt(e){switch(e.what){case"email":return"address asked back, awaiting its owner\u2019s confirmation";case"active":return e.to?"activated":"deactivated";case"frozen":return e.to?"frozen":"unfrozen";case"profile":return`profile ${e.to} in place of ${e.from}`;case"permissionSet":return`permission set ${e.name} ${e.to==="added"?"added":"taken back"}`;case"permissionSetGroup":return`permission set group ${e.name} ${e.to==="added"?"added":"taken back"}`;case"group":return`${e.type==="Queue"?"queue":"group"} ${e.name} `+(e.to==="added"?"joined":"left")}}function Qf(e){return e.users.filter(t=>t.changes.length>0)}function Xf(e){let t=Qf(e).length,n=e.refusals??[],r=n.length>0?n.map(i=>i.message).join(" "):void 0,s=[...new Set(n.map(i=>i.code))],o=(e.licenses??[]).filter(i=>i.toUse>0).map(i=>`${i.name}: ${i.used} of ${i.total} used, ${i.toUse} more taken by the activations and the profiles`);return{objects:[{object:"User",wouldCreate:t}],total:t,created:0,apiRequests:e.apiRequests,storageBytes:0,emails:[],emailsToPeople:e.emailsToPeople,...r!==void 0?{refusal:r}:{},...r!==void 0&&s.length>0?{refusalCodes:s}:{},...o.length>0?{notes:o}:{}}}function Zf(e){let t=e.refusals??[];if(t.length>0)return{objects:[],users:0,unread:t.map(o=>o.message).join(" ")};let n=Qf(e),r=e.users.length-n.length,s=n.map(o=>`${o.username} would be ${o.changes.map(Rt).join(", ")}`);return{objects:[{object:"User",present:r}],users:r,...s.length>0?{drift:s.join("; ")}:{}}}function ep(e){return`applied, and the org holds its ${e} user(s) as the last run left them`}function tp(e,t){return`its users changed since it was applied: ${t}. Left as they are: --replace ${e} or --replace-drifted sets them up again, converging from what the last run left`}function os(e){let t=e.users.filter(a=>(a.refused??[]).length>0),n=e.users.reduce((a,c)=>a+c.created.permissionSetAssignments.length,0),r=e.users.reduce((a,c)=>a+c.created.groupMembers.length,0),s=[{object:"User",created:0,refused:t.length,errors:t.flatMap(a=>(a.refused??[]).map(c=>`${a.username}: ${Rt(c.change)} refused, ${c.code}: ${c.message}`))},...n>0?[{object:"PermissionSetAssignment",created:n,refused:0,errors:[]}]:[],...r>0?[{object:"GroupMember",created:r,refused:0,errors:[]}]:[]],o=e.users.some(a=>a.done.length>0),i=e.refusals??[];return{objects:s,created:n+r,...!o&&i.length>0?{refusal:i.map(a=>a.message).join(" ")}:{}}}function np(e){return e.users.map(t=>({username:t.username,userId:t.userId}))}var rp={seed:re,forge:G,frozen:ue,mask:he,users:W,replay:V};function _v(e){return Object.prototype.hasOwnProperty.call(rp,e)}function is(e){if(!_v(e))throw new Error(`The state holds a resource of kind ${e}, which a later SandForge applies: this one applies seed, forge, frozen, mask, users and replay resources, and takes back nothing of another kind.`);return rp[e]}function sp(e,t,n,r,s,o={}){switch(n.kind){case"seed":{let i=vf(e,t,n,s);return"refusals"in i?i:{run:{kind:"seed",...i.run},warnings:i.warnings}}case"forge":{let i=Td(e,t,n,r,s);return"refusals"in i?i:{run:{kind:"forge",...i.run},warnings:i.warnings}}case"frozen":{let i=sl(t,n,r);return"refusals"in i?i:{run:{kind:"frozen",...i.run},warnings:i.warnings}}case"mask":{let i=Sl(t,n,o);return"refusals"in i?i:{run:{kind:"mask",...i.run},warnings:i.warnings}}case"users":{let i=zf(n);return{run:{kind:"users",...i.run},warnings:i.warnings}}case"replay":{let i=Xl(t,n);return"refusals"in i?i:{run:{kind:"replay",...i.run},warnings:i.warnings}}}}function op(e){switch(e.kind){case"seed":return Ef(e.run);case"forge":return _d(e.run,e.source.read);case"frozen":return ol(e.run);case"mask":return $l(e.run);case"users":return qf(e.run);case"replay":return nf(e.run,e.checkpoint.read)}}function Vt(e){switch(e.kind){case"seed":return Rf(e);case"forge":return xd(e);case"frozen":return[];case"mask":return Al(e);case"users":return Bf(e);case"replay":return Zl(e)}}function St(e){return e==="frozen"||e==="mask"||e==="users"||e==="replay"}function Wt(e,t){switch(e.kind){case"seed":return wi(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 il(e.run,{sasDir:t.sasDir,datasetDir:e.dataset.dir})}case"mask":return Ol(e.run);case"users":return ki(e.run);case"replay":return{}}}function ip(e,t){switch(e.kind){case"seed":{let n=e.run.seed??t.seed;return{script:re,args:Of({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:G,args:qd({...dp(e),target:t.target,templateFile:t.templateFile,...t.rootsPlanFile!==void 0?{rootsPlanFile:t.rootsPlanFile}:{},maxTotal:e.run.maxTotal??Nd})};case"frozen":return{script:ue,args:cl({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:he,args:Cl({target:t.target,run:e.run,rulesFile:t.templateFile,store:up(e,t)})};case"users":return{script:W,args:Vf(ap(e,t))};case"replay":return{script:V,args:sf({...cp(e,t),again:t.replace===!0})}}}function ap(e,t){return{target:t.target,configFile:t.templateFile,...t.replacesRun!==void 0?{replacesRun:t.replacesRun}:{},...t.acceptUserEmails===!0?{acceptUserEmails:!0}:{},...t.acceptAutomation===!0||e.run.acceptAutomation===!0?{acceptAutomation:!0}:{}}}function cp(e,t){if(t.checkpointStore===void 0)throw new Error(`${e.name} is given no store of checkpoints to replay from: plan again.`);return{name:e.name,run:e.run,place:e.checkpoint,target:t.target,store:t.checkpointStore,again:!1,...t.acceptAutomation===!0?{acceptAutomation:!0}:{}}}function up(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 dp(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 lp(e,t){switch(e){case"seed":return Nf(t);case"forge":return Yd(t);case"frozen":return hl(t);case"mask":return Pl(t);case"users":return Jf(t);case"replay":return ff(t)}}function bi(e){return e.kind==="seed"?Sf(e.run):void 0}function fp(e,t){return e.kind==="forge"&&t.tool===G?Hd(t,e.run.template):void 0}function Ht(e,t){switch(e.tool){case re:return Ff(e,t);case G:return Xd(e);case ue:return wl(e);case he:return xl(e);case W:return Xf(e);case V:return mf(e)}}function $t(e,t){switch(e.kind){case"seed":return{script:re,args:Af({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:G,args:Bd({...dp(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:ue,args:ul({configFile:t.templateFile,target:t.target,reload:t.replace===!0,acceptAutomation:t.acceptAutomation===!0,maxTotal:t.maxTotal})}}case"mask":return{script:he,args:Il({target:t.target,run:e.run,rulesFile:t.templateFile,store:up(e,t)})};case"users":return{script:W,args:Wf(ap(e,t))};case"replay":{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:V,args:of({...cp(e,t),again:t.replace===!0,maxRecords:t.maxTotal})}}}}function as(e){throw new Error(`${De(e)} takes no run back: a masking is never undone, and its destroy deletes its store`)}function pp(e){if(e.checkpointStore===void 0)throw new Error("a replay is given no store of checkpoints to take it back from: plan again.");return{replayed:es(e.subject),target:e.target,store:e.checkpointStore,includeChanged:e.includeChanged,acceptAutomation:e.acceptAutomation,...e.sweep===!0?{sweep:!0}:{}}}function hp(e){throw new Error(`${De(e)} previews no removal: its plan reads what the org holds of its users`)}function mp(e,t){let n=is(e),r=t.sweep===!0?{sweep:!0}:{},s={target:t.target,summary:t.subject,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,...r};switch(n){case re:return{script:n,args:If(s)};case G:return{script:n,args:Vd(s)};case ue:return{script:n,args:fl({configFile:t.subject,target:t.target,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,...r})};case he:return as(n);case W:return hp(n);case V:return{script:n,args:uf(pp(t))}}}function gp(e,t){let n=is(e);switch(n){case re:return Tf(t);case G:return Gd(t);case ue:return gl(t);case he:return as(n);case W:return hp(n);case V:return pf(t)}}function yp(e,t){if(e==="mask"||e==="users")return[];let n=[...t].reverse().filter(r=>r.takenBack!==!0);return e==="frozen"||e==="replay"?n.slice(0,1):n}function wp(e,t){if(e==="frozen")return{script:ue,args:dl({configFile:t.subject,target:t.target})}}function vp(e){return kl(ml(e))}function kp(e,t){let n=is(e),r={target:t.target,summary:t.subject,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,sweep:t.sweep};switch(n){case re:return{script:n,args:Cf(r)};case G:return{script:n,args:Kd(r)};case ue:return{script:n,args:ll({configFile:t.subject,target:t.target,includeChanged:t.includeChanged,sweep:t.sweep,acceptAutomation:t.acceptAutomation})};case he:return as(n);case W:return{script:n,args:Hf({target:t.target,run:Yf(t.subject),includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation})};case V:return{script:n,args:cf(pp(t))}}}function bp(e,t){let n=is(e);switch(n){case re:return xf(t);case G:return Jd(t);case ue:return yl(t);case he:return as(n);case W:return Gf(t);case V:return hf(t)}}function Ei(e){return e?.result.objects??[]}function Ep(e,t){return e.kind==="mask"?zl(e.name,t):e.kind==="forge"?Fd(e.run,e.source):[]}var pt=Ly(lg());import{isAbsolute as pS,resolve as ar}from"node:path";function sc(e){return`${wn(e.path)}: ${e.message}`}var hS=100;function pg(e){let t=e.startsWith("\uFEFF")?e.slice(1):e,n=(0,pt.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=rc(n.contents,[]);if(s!==void 0)return{refusal:`${wn(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:hS})}}catch(o){return{refusal:`The file does not read as YAML 1.2: ${o instanceof Error?o.message:String(o)}`}}}function rc(e,t){if((0,pt.isMap)(e)){let n=new Set;for(let r of e.items){let s=(0,pt.isScalar)(r.key)?String(r.key.value):String(r.key);if(n.has(s))return{path:t,key:s};n.add(s);let o=rc(r.value,[...t,s]);if(o)return o}}else if((0,pt.isSeq)(e))for(let[n,r]of e.items.entries()){let s=rc(r,[...t,n]);if(s)return s}}function mS(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 cr(e,t,n={}){let r=[...kr(e).map(({path:f,secret:h})=>N(f,`a key shaped like a secret (${h}). The file holds no secret: ${mS(h)}.`)),...Hc(e).filter(({path:f})=>!Kc(f)).map(({path:f})=>N(f,`{ env } stands in ${Co.slice(0,-1).join(", ")} and ${Co.at(-1)??""} 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=Wc.safeParse(e);if(!s.success)return{refusals:s.error.issues.map(f=>{let h=f.path,m=f.code==="invalid_key"?f.issues.map(g=>g.message):[];return N(h,m.join("; ")||f.message)})};let o=s.data,i=yS(o);if("refusals"in i)return i;let a=Rl(o.masking);if("refusals"in a)return a;let c=[],u=[...gS(o)],d={};for(let[f,h]of Object.entries(o.resources)){let m=sp(o.name,f,h,ar(t),n.now??new Date,a.sets);if("refusals"in m){c.push(...m.refusals);continue}u.push(...m.warnings),d[f]=m.run}if(c.push(...wS(d)),c.length>0)return{refusals:c};let l=[];for(let[f,{alias:h}]of Object.entries(o.orgs))typeof h!="string"&&l.push({name:h.env,path:["orgs",f,"alias"],role:f});for(let[f,h]of Object.entries(o.resources)){h.kind==="frozen"&&typeof h.dataset.path!="string"&&l.push({name:h.dataset.path.env,path:["resources",f,"dataset","path"],resource:f});let m=h.kind==="replay"?h.checkpoint.file:void 0;m!==void 0&&typeof m!="string"&&l.push({name:m.env,path:["resources",f,"checkpoint","file"],resource:f})}return{checked:{file:o,folder:ar(t),order:i.order,runs:d,variables:l,warnings:u}}}function gS(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=>N(["masking",n],"no mask resource names this rule set: nothing masks with it"))}function hg(e,t){return e.variables.filter(n=>(t[n.name]??"").trim()==="")}function mg(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 oc(e,t){return[...new Set([...t.kind==="users"?[]:t.dependsOn??[],...mg(e,t).map(({from:n})=>n)])]}function yS(e){let t=Object.keys(e.resources),n=[],r=new Map;for(let[u,d]of Object.entries(e.resources)){let l=[];for(let{from:h,path:m}of mg(u,d))h===u?n.push(N(m,`a relation draws its parents from the records another resource created: ${u}'s own are drawn by their object alone, without from`)):h in e.resources?l.includes(h)||l.push(h):n.push(N(m,`"${h}" is no resource of this file: name one of ${t.join(", ")}`));(d.kind==="users"?[]:d.dependsOn??[]).forEach((h,m)=>{let g=["resources",u,"dependsOn",m];h===u?n.push(N(g,`a resource does not depend on itself: take ${u} out of its dependsOn`)):h in e.resources?l.includes(h)||l.push(h):n.push(N(g,`"${h}" is no resource of this file: name one of ${t.join(", ")}`))}),r.set(u,l)}if(n.length>0)return{refusals:n};let s=vS(t,r);if(s!==void 0)return{refusals:[N(["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 o=t.filter(u=>e.resources[u]?.kind==="users"),i=[...o,...t.filter(u=>!o.includes(u))],a=[],c=new Set;for(;a.length<t.length;){let u=i.find(d=>!c.has(d)&&(r.get(d)??[]).every(l=>c.has(l)));if(u===void 0)break;a.push(u),c.add(u)}return{order:a}}function wS(e){let t=[];for(let[n,r]of Object.entries(e))if(r.kind==="seed")for(let s of r.draws??[]){let o=e[s.from];if(o?.kind==="mask"){t.push(N(["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, a frozen or a replay resource created`));continue}if(o?.kind!=="seed")continue;let i=Vt(o).map(({object:a})=>a);i.includes(s.relation.parentObject)||t.push(N(["resources",n,"relations",s.at,"parents","from"],`${s.from} writes no ${s.relation.parentObject} records: it writes ${i.join(", ")||"none"}`))}return t}function vS(e,t){let n=new Set,r=[],s=o=>{let i=r.indexOf(o);if(i>=0)return[...r.slice(i),o];if(!n.has(o)){r.push(o);for(let a of t.get(o)??[]){let c=s(a);if(c!==void 0)return c}r.pop(),n.add(o)}};for(let o of e){let i=s(o);if(i!==void 0)return i}}function ic(e,t){return ei(Ft({...op(e),dependsOn:t}))}var fg=/^[^-\s][^\s]{0,199}$/;function ac(e,t,n={}){let r=Object.keys(e.file.orgs),s=[],o=n.aliases??{};for(let[f,h]of Object.entries(o))r.includes(f)?fg.test(h)||s.push(N(["orgs",f,"alias"],`--alias ${f}= gives no alias: one holds no space and does not start with "-"`)):s.push(N(["orgs"],`--alias names the role ${f}, which the file's orgs do not declare: `+(r.length>0?`its roles are ${r.join(", ")}`:"it declares none")));let i={};for(let[f,{alias:h}]of Object.entries(e.file.orgs)){let m=o[f];if(m!==void 0){i[f]=m;continue}if(typeof h=="string"){i[f]=h;continue}let g=(t[h.env]??"").trim();g===""?s.push(N(["orgs",f,"alias"],`the variable ${h.env} is not set: set it in the job's environment to the alias of the ${f} org, or give --alias ${f}=<alias>`)):fg.test(g)?i[f]=g:s.push(N(["orgs",f,"alias"],`the variable ${h.env} holds no alias: one holds no space and does not start with "-"`))}let a={};for(let[f,h]of Object.entries(e.file.resources)){if(h.kind!=="frozen")continue;let m=kS(f,h.dataset.path,t,e.folder);"refusal"in m?s.push(m.refusal):a[f]=m.dir}let c={};for(let[f,h]of Object.entries(e.file.resources)){if(h.kind!=="replay"||h.checkpoint.file===void 0)continue;let m=ef(f,h.checkpoint.file,t);"refusal"in m?s.push(m.refusal):c[f]=m.file}if(s.length>0)return{refusals:s};let u={},d=[];for(let f of e.order){let h=e.runs[f],m=e.file.resources[f];if(h===void 0||m===void 0)continue;let g=oc(f,m),w;if(h.kind==="seed"){let{kind:y,...v}=h;w={name:f,kind:y,dependsOn:g,fingerprint:"",run:v}}else if(h.kind==="mask"){let{kind:y,...v}=h;w={name:f,kind:y,dependsOn:g,fingerprint:"",run:v}}else if(h.kind==="users"){let{kind:y,...v}=h;w={name:f,kind:y,dependsOn:g,fingerprint:"",run:v}}else if(h.kind==="replay"){let{kind:y,...v}=h,b=n.checkpoints?.[f],k=v.from!==void 0?i[v.from]:void 0,E=c[f];w={name:f,kind:y,dependsOn:g,fingerprint:"",run:v,checkpoint:{...k!==void 0?{from:k}:{},...E!==void 0?{file:E}:{},...b!==void 0?{read:b}:{}}}}else if(h.kind==="frozen"){let{kind:y,...v}=h,b=n.datasets?.[f];w={name:f,kind:y,dependsOn:g,fingerprint:"",run:v,dataset:{dir:a[f]??"",...b!==void 0?{read:b}:{}}}}else{let{kind:y,...v}=h,b=n.sources?.[f];w={name:f,kind:y,dependsOn:g,fingerprint:"",run:v,source:{role:v.source,alias:i[v.source]??"",...b!==void 0?{read:b}:{}}}}w.fingerprint=ic(w,Object.fromEntries(g.map(y=>[y,u[y]]))),u[f]=w.fingerprint,d.push(w)}let l=ei(Ft({...e.file,orgs:Object.fromEntries(Object.entries(i).map(([f,h])=>[f,{alias:h}]))}));return{resolved:{checked:e,orgs:i,resources:d,digest:l}}}function kS(e,t,n,r){let s=["resources",e,"dataset","path"],o;if(typeof t=="string")o=t;else{if(o=(n[t.env]??"").trim(),o==="")return{refusal:N(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(!pS(o))return{refusal:N(s,`the variable ${t.env} holds ${o}, which is not a path from the root: give the folder of the dataset from the root`)}}let i;try{i=Or(r)}catch{i=void 0}return i!==void 0&&new Be(i).isInsideRepo(ar(o))?{refusal:N(s,`the dataset of ${e}, ${ar(o)}, is inside the repository ${i} 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:ar(o)}}function gg(e,t,n,r={}){let s=cr(e,t,r.now?{now:r.now}:{});return"refusals"in s?s:ac(s.checked,n,{...r.aliases?{aliases:r.aliases}:{},...r.sources?{sources:r.sources}:{},...r.datasets?{datasets:r.datasets}:{},...r.checkpoints?{checkpoints:r.checkpoints}:{}})}var wg="USERS_EMAILS_NOT_ACCEPTED";function vg(e){if(e.tool!==W)return e;let t=e,n=(t.refusals??[]).filter(s=>s.code!==wg),r={...t};return delete r.refusals,n.length>0?{...r,refusals:n}:r}var kg=new Set(["create","replace","delete"]),Ae=new Set(["create","replace"]);function lc(e){return kg.has(e.action)}function _e(e){return Object.entries(e?.resources??{}).filter(([,t])=>t.status!=="destroyed")}function fc(e,t){let n=[],r=new Set,s=new Set(e);for(;n.length<e.length;){let o=e.find(i=>!r.has(i)&&t(i).every(a=>!s.has(a)||r.has(a)||a===i))??e.find(i=>!r.has(i));if(o===void 0)break;n.push(o),r.add(o)}return n}function ht(e,t){let n=e?.resources??{},r=fc(t,o=>n[o]?.dependsOn??[]).reverse(),s=o=>n[o]?.kind==="users";return[...r.filter(o=>!s(o)),...r.filter(s)]}function bS(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 cc(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 o of s.objects){let i=t.objects.get(o.objectApiName)??{present:0,gone:0,changed:0,unread:0};i.present+=o.toDelete+o.keptChanged+o.undeletable,i.gone+=o.alreadyGone+o.notVisible,i.changed+=o.changedSince,i.unread+=o.unread,t.objects.set(o.objectApiName,i);for(let[a,c]of Object.entries(o.changedBy)){let u=s.userNames[a]??a;t.changedBy.set(u,(t.changedBy.get(u)??0)+c)}}for(let o of n.preview.refusals)t.refusals.includes(o)||t.refusals.push(o);if(yg(t.codes,n.preview.refusals,n.preview.refusalCodes),"removalAlone"in n.preview){t.removalAlone.push(...n.preview.removalAlone);let o="removalAloneCodes"in n.preview?n.preview.removalAloneCodes:void 0;yg(t.codes,n.preview.removalAlone,o)}}return t}function yg(e,t,n){n?.length===t.length&&t.forEach((r,s)=>e.set(r,n[s]??""))}function pc(e){return[...e.refusals,...e.removalAlone]}function uc(e,t=pc(e)){return[...new Set(t.flatMap(n=>e.codes.get(n)||[]))]}function ao(e){return e.length>0?{refusalCodes:[...new Set(e)]}:{}}function dc(e){return[...e.objects].map(([t,n])=>({object:t,present:n.present,gone:n.gone,changed:n.changed}))}function ES(e){let t=[...e.objects].flatMap(([s,o])=>{let i=[o.gone>0?`${o.gone} gone`:"",o.changed>0?`${o.changed} changed`:"",o.unread>0?`${o.unread} not read`:""].filter(Boolean);return i.length>0?[`${s} ${i.join(", ")}`]:[]});if(e.verified.length>0&&t.push(`its verification: ${e.verified.join("; ")}`),t.length===0)return;let n=[...e.changedBy].sort((s,o)=>o[1]-s[1]),r=n.length>0?` (last changed by ${n.map(([s,o])=>`${s} ${o}`).join(", ")})`:"";return`${t.join("; ")}${r}`}var bg="taken back: the assignments and memberships the environment created deleted by id, each user put back as it was before; an address asked back stays, and no user is deleted",RS="its state was recovered from its run files, which do not say what it was applied from",SS={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"},$S={applying:"its last run was stopped part way: a run converges from what it left",partial:"its last run was partial: the org refused changes to its users",failed:"its last run failed",destroying:"a removal of it was stopped part way"};function AS(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==="replay"){let n=e.checkpoint.read;return n===void 0?"its checkpoint was not resolved: 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 hc(e){let{resolved:t,state:n,previews:r}=e,s=r===void 0,o=new Set(e.replace??[]),i=new Map(_e(n)),a=new Set(t.resources.map(d=>d.name)),c=new Map;for(let d of t.resources){let l=i.get(d.name),f=AS(d),h=d.kind;if(l===void 0){c.set(d.name,{resource:d.name,kind:h,action:"create",why:n?.resources[d.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 m=cc(r?.[d.name]??[]),g=[],w=ic(d,Object.fromEntries(d.dependsOn.map(A=>[A,n?.resources[A]?.fingerprint])));l.recovered===!0?g.push(RS):l.fingerprint!==d.fingerprint&&l.fingerprint!==w&&g.push("what it writes changed in the file since it was applied");let y=(h==="mask"?Bl:h==="users"?$S:SS)[l.status];y!==void 0&&g.push(y);let v=d.dependsOn.filter(A=>{let P=c.get(A);return P!==void 0&&Ae.has(P.action)&&P.kind!=="mask"});if(v.length>0&&g.push(`the resources it depends on run again, with new records: ${v.join(", ")}`),o.has(d.name)&&g.push("--replace asks it"),h==="mask"){c.set(d.name,OS(d.name,l,g,e,s));continue}if(h==="users"){c.set(d.name,jS(d.name,g,e,s));continue}let b=s?void 0:ES(m),k=b!==void 0&&bS(m,e.drift),E=k?void 0:b;g.length===0&&E!==void 0&&e.replaceDrifted===!0&&g.push(`its records drifted (${E}), and --replace-drifted asks it`);let S=dc(m),$=f??(m.refusals.length>0?`a removal of its runs would be refused now: ${m.refusals.join(" ")}`:m.failed.length>0?`what the org holds of it could not be read (${m.failed.join("; ")}): plan again`:void 0),j=f===void 0&&m.refusals.length>0?uc(m,m.refusals):[];if(g.length>0)c.set(d.name,{resource:d.name,kind:h,action:"replace",why:`replaced: ${g.join("; ")}`,objects:S,...$!==void 0?{refusal:$,...ao(j)}:{}});else if(s)c.set(d.name,{resource:d.name,kind:h,action:"keep",why:"applied from the same file; what the org holds of it was not read (--quick)",objects:S,...f!==void 0?{refusal:f}:{}});else if(f!==void 0||m.failed.length>0)c.set(d.name,{resource:d.name,kind:h,action:"keep",why:"applied from the same file",objects:S,refusal:f??`what the org holds of it could not be read (${m.failed.join("; ")}): plan again`});else if(E!==void 0)c.set(d.name,{resource:d.name,kind:h,action:"drifted",why:`its records changed since it was applied: ${E}. Left as they are: --replace ${d.name} or --replace-drifted replaces it`,objects:S});else{let A=S.reduce((D,x)=>D+(x.present??0),0),P=S.reduce((D,x)=>D+(x.changed??0),0);c.set(d.name,{resource:d.name,kind:h,action:"keep",why:k?`applied, and the org holds its ${A} record(s) as the checkpoint taken after the apply holds them: ${P} written since hold their values again, as a reset gives them back`:`applied, and the org holds its ${A} record(s) as written`,objects:S})}}return[...ht(n,[...i.keys()].filter(d=>!a.has(d))).map(d=>{let l=i.get(d);if(l?.kind==="mask")return{resource:d,kind:"mask",action:"delete",why:mi("apply",d,l,mc(e,d)),objects:Eg(l)};let f=cc(r?.[d]??[]),h=pc(f),m=h.length>0?`a removal of its runs would be refused now: ${h.join(" ")}`:f.failed.length>0?`what the org holds of it could not be read (${f.failed.join("; ")}): plan again`:void 0;return{resource:d,kind:i.get(d)?.kind??"seed",action:"delete",why:l?.kind==="users"?`in the state, gone from the file: ${bg}`:"in the state, gone from the file: its records are taken back",objects:dc(f),...m!==void 0?{refusal:m,...ao(h.length>0?uc(f):[])}:{}}}),...t.resources.flatMap(d=>c.get(d.name)??[])]}function OS(e,t,n,r,s){let o=(l,f,h=[],m)=>({resource:e,kind:"mask",action:l,why:f,objects:h,...m!==void 0?{refusal:m}:{}});if(n.length>0)return o("replace",`replaced: ${n.join("; ")}; ${hi(t)}`);if(s)return o("keep","applied from the same file; what the org holds of it was not read (--quick)");if(r.dryRuns===void 0)return o("keep","applied from the same file");let i=r.dryRuns[e];if(i===void 0)return o("keep","applied from the same file",[],"it was not dry-run: plan again");if("failed"in i||i.answer.tool!==he){let l="failed"in i?i.failed:`${De(i.answer.tool)} answered its dry run`;return o("keep","applied from the same file",[],`what the org holds of it could not be read (its dry run: ${l}): plan again`)}let a=r.resolved.resources.map(l=>l.name),c=r.resolved.resources.find(l=>l.name===e),u=c?.kind==="mask"?c.run.where:void 0,d=Ml(t,i.answer,r.maskCreatedAfter?.[e]??pi(e,r.state,a,u));return d.unread!==void 0?o("keep","applied from the same file",d.objects,`what the org holds of it could not be read: ${d.unread}`):d.drift===void 0?o("keep",Ul(d.masked,d.theirs),d.objects):r.replaceDrifted===!0?o("replace",`replaced: its condition selects other records than it masked (${d.drift}), and --replace-drifted asks it; ${hi(t)}`,d.objects):o("drifted",Kl(e,d.drift),d.objects)}function jS(e,t,n,r){let s=(u,d,l=[],f)=>({resource:e,kind:"users",action:u,why:d,objects:l,...f!==void 0?{refusal:f}:{}}),o=n.usersUnknown?.[e],i=o!==void 0?[...t,o]:t;if(t.length>0)return s("replace",`replaced: ${i.join("; ")}`);if(r)return s("keep","applied from the same file; no word on its users (--quick)");if(n.dryRuns===void 0)return s("keep","applied from the same file");let a=n.dryRuns[e];if(a===void 0)return s("keep","applied from the same file",[],"it was not dry-run: plan again");if("failed"in a||a.answer.tool!==W){let u="failed"in a?a.failed:`${De(a.answer.tool)} answered its plan`;return s("keep","applied from the same file",[],`what the org holds of its users could not be read (its plan: ${u}): plan again`)}let c=Zf(vg(a.answer));return c.unread!==void 0?s("keep","applied from the same file",c.objects,`what the org holds of its users could not be read: ${c.unread}`):c.drift===void 0?s("keep",ep(c.users),c.objects):n.replaceDrifted===!0?s("replace",`replaced: its users changed since it was applied (${c.drift}), and --replace-drifted asks it; a run converges from what the last one left`,c.objects):s("drifted",tp(e,c.drift),c.objects)}function mc(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 Eg(e){return(e.runs.at(-1)?.objects??[]).map(t=>({object:t.objectApiName,present:t.masked??0}))}function CS(e,t){let n=new Set(t.filter(o=>Ae.has(o.action)).map(o=>o.resource)),r=new Set(t.filter(o=>Ae.has(o.action)&&o.kind!=="mask").map(o=>o.resource)),s=new Map;for(let o of e.resources){if(!n.has(o.name))continue;let i=o.dependsOn.filter(a=>r.has(a));i.length>0&&s.set(o.name,i)}return s}function IS(e,t){let n=new Map(e.resources.map(o=>[o.name,o])),r=new Set,s=[...n.get(t)?.dependsOn??[]];for(;s.length>0;){let o=s.pop()??"";r.has(o)||o===t||(r.add(o),s.push(...n.get(o)?.dependsOn??[]))}return e.resources.filter(o=>o.kind==="replay"&&r.has(o.name)).map(o=>o.name)}function DS(e,t){if(t.kind!=="seed")return[];let n=IS(e,t.name);if(n.length===0)return[];let r=n.length===1;return[`it runs after the ${r?"replay":"replays"} ${n.join(", ")}: what it writes is added to the records the ${r?"replay puts":"replays put"} back from ${r?"the checkpoint":"their checkpoints"}, never in their place; leave it out of the file if the ${r?"checkpoint already holds":"checkpoints already hold"} the data it would seed`]}function PS(e,t){let n=e.map(r=>({...r}));for(let r of t.objects){let s={wouldCreate:r.wouldCreate,...r.atMost===!0?{atMost:!0}:{}},o=n.find(i=>i.object===r.object);o?Object.assign(o,s):n.push({object:r.object,...s})}return n}function NS(e,t,n,r){let s=e.resources.find(c=>c.name===t),o=r&&s!==void 0?bi(s):void 0,i=Ht(vg(n),o),a=s!==void 0?fp(s,n):void 0;return{count:a!==void 0&&i.refusal===void 0?{...i,refusal:a}:i}}function TS(e,t){let n=e.resources.find(r=>r.name===t);return n!==void 0&&(bi(n)?.size??0)>0}function xS(e,t,n){let r=e.resources.find(o=>o.name===t);if(r?.kind!=="seed")return[];let s=new Set((r.run.draws??[]).map(o=>o.from));return n.filter(o=>s.has(o))}function co(e){return e!==void 0&&"answer"in e?Ht(e.answer).total:void 0}function LS(e,t){let n=[],{apiRequests:r,storage:s,emails:o}=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 ${wt(s.bytes/1048576)} MB of data storage, and ${t} has ${wt(s.left/1048576)} MB left: the org would refuse records part way. Write fewer records, or free storage first.`);for(let i of o)i.left!==void 0&&i.emails>i.left&&n.push(`The resources the plan writes make ${t} send ${i.emails} ${i.limit} emails, and it has ${i.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 FS(e,t,n,r,s,o=!1){let i=s.estimate,a=0,c=new Map,u=[...s.notCounted],d;for(let m of e){if((m.action==="delete"||m.action==="replace")&&m.kind!=="mask"&&!(m.action==="replace"&&m.kind==="users")&&u.push(`the removal of the runs of ${m.resource}`),!Ae.has(m.action))continue;m.kind==="users"&&(d??=0);let g=t?.[m.resource];if(g===void 0||"failed"in g){u.push(`the run of ${m.resource}, not dry-run`);continue}let w=r.get(m.resource);w!==void 0&&m.kind!=="mask"&&u.push(`what ${m.resource} draws from the records ${w.join(", ")} writes first`);let y=Ht(g.answer);y.apiRequests===void 0?u.push(`the requests of the run of ${m.resource}, which its script does not estimate`):i+=y.apiRequests,a+=y.storageBytes;for(let{limit:v,emails:b}of y.emails)c.set(v,(c.get(v)??0)+b);y.emailsToPeople!==void 0&&(d=(d??0)+y.emailsToPeople)}let l=n?.apiRequests,f=n?.storage,h=n?.emails;return{apiRequests:{estimate:i,...l!==void 0&&!("unread"in l)?{leftToday:l.remaining}:{},partial:u.length>0,...u.length>0?{notCounted:u}:{},...l!==void 0&&"unread"in l?{unread:l.unread}:{},...n===void 0?{unread:"not read: --quick"}:{}},storage:{bytes:a,...f!==void 0&&!("unread"in f)?{left:Math.floor(f.remainingMB*1048576)}:{},...f!==void 0&&"unread"in f?{unread:f.unread}:{},...n===void 0?{unread:"not read: --quick"}:{}},emails:[...c].map(([m,g])=>{let w=h!==void 0&&!("unread"in h)?h[m]?.remaining:void 0;return{limit:m,emails:g,...w!==void 0?{left:w}:{}}}),...d!==void 0?{emailsToPeople:{count:d,accepted:o}}:{}}}function MS(e,t){let n=e.emailsToPeople;return n===void 0||n.count===0||n.accepted?void 0:`${t.flatMap(s=>{let o=s.gates?.emailsToPeople??0;return s.kind!=="users"||!Ae.has(s.action)||o===0?[]:[`${s.resource} has Salesforce email ${o} ${o===1?"person":"people"} (the confirmation of ${o===1?"an address":`${o} addresses`} asked back)`]}).join(", ")}, which only the line accepts: --accept-user-emails. Nothing was written.`}function gc(e){let t=e.previews===void 0,n=hc(e),r=CS(e.resolved,n),s=n.map(y=>{let v=y.objects,b,k=y.refusal,E=y.refusal!==void 0?y.refusalCodes??[]:[],S=Ae.has(y.action)?e.dryRuns?.[y.resource]:void 0,$=r.get(y.resource),j=$!==void 0&&TS(e.resolved,y.resource),A=Ae.has(y.action)?e.draws?.[y.resource]:void 0;A!==void 0&&A.refusals.length>0&&(k??=A.refusals.join(" "));let P=[],D=e.dryRuns?.[y.resource],x=y.kind==="users"&&D!==void 0&&"answer"in D&&D.answer.tool===W?D.answer.users:void 0;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 X=NS(e.resolved,y.resource,S.answer,$!==void 0);v=PS(v,X.count),b={...X.count.apiRequests!==void 0?{apiRequests:X.count.apiRequests}:{},storageBytes:X.count.storageBytes,emails:X.count.emails,...X.count.emailsToPeople!==void 0?{emailsToPeople:X.count.emailsToPeople}:{}};let Ce=X.count.refusal;Ce!==void 0&&k===void 0&&(k=`its own dry run says a real run would be refused: ${Ce}`,E=X.count.refusalCodes??[]),P=X.count.notes??[]}else Ae.has(y.action)&&!t&&(k??="it was not dry-run: plan again");let J=$!==void 0?xS(e.resolved,y.resource,$):[],U=$!==void 0&&S!==void 0&&y.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&&j?J.length>0?`; it draws its parents from the records ${J.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`:"",O=`${y.why}${U}${P.length>0?`; ${P.join("; ")}`:""}`,F=e.resolved.resources.find(X=>X.name===y.resource),ae=F!==void 0&&Ae.has(y.action)?[...Ep(F,mc(e,y.resource)),...DS(e.resolved,F)]:[];return{resource:y.resource,kind:y.kind,action:k!==void 0?"blocked":y.action,why:O,objects:v,...A!==void 0&&A.draws.length>0?{draws:A.draws}:{},...b!==void 0?{gates:b}:{},...k!==void 0?{refusal:k,...ao(E)}:{},...ae.length>0?{notes:ae}:{},...x!==void 0?{users:x}:{}}}),o=e.resolved.checked.file,i=hd(qr(o,e.state,n.some(y=>kg.has(y.action))),t?void 0:e.checkpointEstimate??{unread:"not estimated"},s.filter(y=>Ae.has(y.action)&&y.kind!=="mask").flatMap(y=>y.objects).reduce((y,v)=>y+(v.wouldCreate??0),0)),a=FS(n,e.dryRuns,e.budget,r,gd(i),e.acceptUserEmails===!0),c=e.org.alias??e.org.organizationId,u=LS(a,c);if(u.length>0)for(let y of s)lc(y)&&(y.refusal=u.join(" "),y.action="blocked");let d=s.filter(y=>y.action==="blocked"),l=MS(a,s),f=e.refusal??(u.length>0?`${u.join(" ")} Nothing was written.`:d.length>0?`${d.length===1?"A resource is":`${d.length} resources are`} blocked, and the apply refuses before its first write: ${d.map(y=>`${y.resource} (${y.refusal??y.why})`).join("; ")}`:void 0)??l??md(i),h=e.refusal!==void 0?[...e.refusalCodes??[]]:u.length>0?[]:d.length>0?d.flatMap(y=>y.refusalCodes??[]):l!==void 0?[wg]:i.flatMap(y=>y.refusal!==void 0?[y.refusal.code]:[]),m=[...e.warnings??[],...fd(o,e.state)],g=y=>s.filter(v=>v.action===y).length,w=e.state;return{env:e.resolved.checked.file.name,org:e.org,state:w!==void 0?{found:!0,serial:w.serial}:{found:!1,...e.refreshed!==void 0?{refreshed:e.refreshed}:{}},actions:s,totals:{create:g("create"),keep:g("keep"),replace:g("replace"),delete:g("delete"),drifted:g("drifted"),blocked:g("blocked")},gates:a,...i.length>0?{checkpoints:i}:{},...e.drift!==void 0?{drift:e.drift}:{},...f!==void 0?{refusal:f,...ao(h)}:{},...t?{quick:!0}:{},...m.length>0?{warnings:m}:{}}}function Rg(e){let n=ht(e.state,_e(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:mi("destroy",a,c,mc(e,a)),objects:Eg(c)};let u=cc(e.previews?.[a]??[]),d=pc(u),l=d.length>0?`a removal of its runs would be refused now: ${d.join(" ")}`:u.failed.length>0?`what the org holds of it could not be read (${u.failed.join("; ")}): run destroy again`:void 0,f=d.length>0?uc(u):[];return{resource:a,kind:c?.kind??"seed",action:l!==void 0?"blocked":"delete",why:c?.kind==="users"?`${bg}, after every other resource`:"taken back by destroy, into the recycle bin",objects:dc(u),...l!==void 0?{refusal:l}:{},...f.length>0?{refusalCodes:f}:{}}}),r=n.filter(a=>a.action==="blocked"),s=[...new Set(r.flatMap(a=>a.refusalCodes??[]))],o=n.filter(a=>a.kind!=="mask").map(a=>`the removal of the runs of ${a.resource}`),i=e.state;return{env:e.resolved.checked.file.name,org:e.org,state:i!==void 0?{found:!0,serial:i.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:o.length>0,...o.length>0?{notCounted:o}:{}},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 yc(e){return e.actions.some(t=>t.action!=="keep"&&t.action!=="drifted")}function Sg(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 wc(e){let t=e.kind==="mask",n=e.kind==="users";return e.objects.map(r=>{let s=[r.wouldCreate!==void 0?`${r.atMost===!0?"at most ":""}${r.wouldCreate} `+(t?"to mask":n?"to set up":"to write"):"",r.present!==void 0&&r.present>0?`${r.present} ${t?"masked":n?"set up":"in the org"}`:"",(r.gone??0)>0?`${r.gone} gone`:"",(r.changed??0)>0?`${r.changed} changed`:""].filter(Boolean);return s.length>0?`${r.object} ${s.join(", ")}`:""}).filter(Boolean).join("; ")}var _S={apply:"an apply now",destroy:"a destroy now"};function zS(e){if(e.kind!=="users"||!Ae.has(e.action)||e.users===void 0)return[];let t=e.users.map(s=>` ${s.username}: `+(s.changes.length>0?s.changes.map(Rt).join(", "):"as the file says already: nothing to do")),n=e.users.filter(s=>(s.emailsToPeople??0)>0),r=e.gates?.emailsToPeople??0;if(r>0){let s=n.map(o=>o.username).join(", ");t.push(r===1?` Salesforce sends 1 email to a person: the confirmation of ${s}'s address asked back, a system email, which leaves under System email only too`:` Salesforce sends ${r} emails to people: the confirmation of each address asked back (${s}), system emails, which leave under System email only too`)}return t}function uo(e,t="apply",n={}){let r=e.org.kind==="sandbox"?Ne(e.org.host):void 0,s=e.org.alias??e.org.organizationId,o=e.state.refreshed,i=[`plan of ${e.env} on ${s} (${e.org.kind}${r!==void 0?` ${r}`:""}, ${e.org.organizationId})`,e.state.found?`state: kept on this machine, serial ${e.state.serial??0}`:o!==void 0?`state: ${ai(s,o)}`:"state: none on this machine"];for(let h of e.actions){let m=wc(h);i.push(` ${h.action.padEnd(8)} ${h.resource}${m?` ${m}`:""}`),i.push(` ${h.why}`),i.push(...zS(h));for(let g of h.draws??[])i.push(` ${g.lookup} draws its parents from `+(g.parents!==void 0?`the ${g.parents} ${g.object} record(s) ${g.from} created`:`the ${g.object} records ${g.from} creates first`));for(let g of h.notes??[])i.push(` ${g}`);h.refusal!==void 0&&i.push(` refused: ${h.refusal}`)}let{totals:a}=e;i.push(`totals: ${a.create} to create, ${a.replace} to replace, ${a.delete} to delete, ${a.keep} kept, ${a.drifted} drifted, ${a.blocked} blocked`);let{apiRequests:c,storage:u,emails:d}=e.gates,l=(h,m)=>h!==void 0?`, ${h} left`:m!==void 0?` (left: ${m})`:"";i.push(`API requests: about ${c.estimate}`+l(c.leftToday?.toString(),c.unread)+(c.partial?`; not counted: ${(c.notCounted??[]).join(", ")}`:"")),i.push(`data storage: about ${wt(u.bytes/1048576)} MB`+l(u.left!==void 0?`${wt(u.left/1048576)} MB`:void 0,u.unread));for(let h of d)i.push(`emails (${h.limit}): ${h.emails}`+(h.left!==void 0?`, ${h.left} left today`:""));let f=e.gates.emailsToPeople;f!==void 0&&f.count>0&&i.push(`emails to people: ${f.count}, `+(f.accepted?"accepted by the line (--accept-user-emails)":"which the line accepts with --accept-user-emails")),i.push(...wd(e)),n.audits!==void 0&&i.push(n.audits);for(let h of e.warnings??[])i.push(`warning: ${h}`);return e.refusal!==void 0&&i.push(`${_S[t]} would be refused: ${e.refusal}`),i}import{existsSync as lo,readFileSync as vc}from"node:fs";import{join as qS}from"node:path";function fo(e){return e.slice(0,15)}function ur(e){let t=new Map,n=new Set;for(let{objectApiName:r,ids:s}of e){let o=t.get(r)??[];for(let i of s)n.has(fo(i))||(n.add(fo(i)),o.push(i));t.set(r,o)}return t}function BS(e,t,n){let r=e.runId!==void 0?qS(n.journalDir,qe,`${e.runId}.ndjson`):void 0;if(r!==void 0&&lo(r)){let i=fu(vc(r,"utf8"));if(i!==void 0)return{created:ur(i.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(!lo(s))return{refusal:"its run keeps no record of what it created"};let o=Ut(vc(s,"utf8"));return o.result.objectResults.some(i=>i.truncated===!0)?{refusal:"its summary names the first of the records it created alone, and its run file is gone"}:{created:ur(o.result.objectResults.map(i=>({objectApiName:i.objectApiName,ids:i.createdIds})))}}async function US(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(!lo(r))return{refusal:"its run keeps no summary"};let s=await Ar(r,vc(r,"utf8"),t.target,Sr(n.journalDir));if("refusal"in s)return{refusal:`its summary ${s.refusal}`};let{result:o}=s.summary,i=Jc({idRemapTable:o.remapTable,idRemapExisting:[...o.existingSourceIds,...o.updatedSourceIds],idRemapCreated:o.createdByObject});return{created:ur([...i].reverse().map(a=>({objectApiName:a.objectApiName,ids:[...a.ids].reverse()})))}}async function KS(e,t,n){if(Xr(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 Be,o=(await fn(r,s)).find(c=>fo(c)===fo(t.organizationId));if(o===void 0)return{refusal:"its sas holds no mapping of a load into this org"};let i=await new jr(r,{orgId:o,guard:s}).recorded();if(i?.created===void 0)return{refusal:"its sas holds no load that says which records it created"};let a=zu(i);return{created:ur([...a].reverse().map(c=>({objectApiName:c.objectApiName,ids:[...c.ids].reverse()})))}}async function VS(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(!lo(r))return{refusal:"its run keeps no summary"};let s;try{s=es(r)}catch{return{refusal:"its summary names no checkpoint a replay wrote from"}}let o;try{let i=new Bu({root:Xu(Z(n.journalDir),!0)});o=await i.createdBy(i.folderOf(s.organizationId,s.checkpointId),t.organizationId)}catch(i){return{refusal:`its replays cannot be read: ${i instanceof Error?i.message:String(i)}`}}return o===void 0?{refusal:`the store of checkpoints keeps no replay of ${s.checkpointId} into this org that says which records it created`}:{created:ur([...o].reverse().map(i=>({objectApiName:i.objectApiName,ids:[...i.ids].reverse()})))}}async function kc(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 o=s.runs.at(-1);if(o===void 0||o.takenBack===!0)return{refusal:`${t} holds no run whose records are in the org`};let i=await dr(o,n,r);return"refusal"in i?{refusal:`${t}: ${i.refusal}`}:i}async function dr(e,t,n){switch(e.script){case"sandforge-seed":return BS(e,t,n);case"sandforge-clone":return US(e,t,n);case"sandforge-frozen":return KS(e,t,n);case V:return VS(e,t,n);default:return{refusal:`its records are kept by ${De(e.script)}, which this SandForge reads not`}}}function WS(e,t){let n=e.relation.parentObject,r=`${e.relation.childObject}.${e.relation.lookupField}`,s=[...t.get(n)??[]],o=yr.maxExistingParents;if(s.length===0){let i=[...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 ${i.join(", ")||"no record"}`}}return e.limit!==void 0?{ids:s.slice(0,e.limit)}:s.length>o?{refusal:`the relation on ${r} draws its parents from the ${s.length} ${n} records ${e.from} created, more than the ${o} a relation's parents hold: give the relation a limit, and its parents are the first ${o} or fewer`}:{ids:s}}async function po(e,t,n,r,s){let o={ids:new Map,draws:[],refusals:[]};if(e.kind!=="seed")return o;let i=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)){o.draws.push(c);continue}let u=i.get(a.from);if(u===void 0&&(u=await kc(t,a.from,r,s),i.set(a.from,u)),"refusal"in u){o.draws.push(c),o.refusals.push(`the relation on ${c.lookup} draws its parents from ${a.from}, whose records cannot be read: ${u.refusal}`);continue}let d=WS(a,u.created);if("refusal"in d){o.draws.push(c),o.refusals.push(d.refusal);continue}o.ids.set(a.at,d.ids),o.draws.push({...c,parents:d.ids.length})}return o}function we(e){return tu.some(t=>Pe(t)===e)}function Og(e,t,n){let r=e===0||e===3||e===4||we(e),s=t??(r?void 0:id(n));return s!==void 0&&s!==""?s.slice(0,4e3):void 0}function JS(e){return Ei(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 GS(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 QS(e){try{return typeof JSON.parse(e)?.refused?.code=="string"}catch{return!1}}function We(e,t,n){if(!(t.trim()===""||QS(t)))try{return e(t)}catch(r){if(r instanceof ce){n(` ${r.message}`);return}throw r}}function Ec(e,t,n,r){let s=Xr(e.sas);if(s!==void 0){let o=n.store.fileOf(t.organizationId,t.env,bt(s,e.n));return on(o)?o:void 0}if(e.summary!==void 0){let o=n.store.fileOf(t.organizationId,t.env,e.summary);if(on(o))return o}if(e.runId!==void 0&&on(mo(n.journalDir,qe,`${e.runId}.ndjson`)))return e.runId;if(e.script===V&&r!==void 0){let o=n.store.fileOf(t.organizationId,t.env,bt(r,e.n));return on(o)?o:void 0}}var XS=/^run-([1-9]\d{0,5})\.json$/,ZS=6e4,e$=p.object({run:p.number().int().positive(),startedAt:p.string(),removals:p.array(p.object({status:p.string()}).loose()).optional()}).loose();function jg(e,t,n,r){let s=f=>{if(f===void 0)return;let h=r.store.fileOf(n.organizationId,n.env,f),m;try{m=bc(h,"utf8")}catch{return}let g=In(m);return g!==void 0?{run:g,file:h}:void 0},o=s(e.summary);if(o!==void 0)return o;let i=new Set(t.flatMap(f=>f.n===e.n?[]:[s(f.summary)?.run??0])),a=mo(r.journalDir,"users",pe(n.organizationId)),c;try{c=HS(a)}catch{c=[]}let u=Date.parse(e.startedAt)-ZS,d=c.flatMap(f=>{let h=Number(XS.exec(f)?.[1]??0);if(h===0||i.has(h))return[];let m=mo(a,f);try{let g=e$.safeParse(JSON.parse(bc(m,"utf8"))),w=g.success&&g.data.removals?.at(-1)?.status==="success";return g.success&&g.data.run===h&&!w&&Date.parse(g.data.startedAt)>=u?[{run:h,file:m}]:[]}catch{return[]}}),[l]=d;return l!==void 0&&d.length===1?{...l,adopted:!0}:d.length===0&&(e.exitCode===1||e.exitCode===2)?{none:!0}:{unknown:d.length===0?`its run ${e.n} stopped before it answered, and no run of ${B("users")} began on this machine after it was launched: which it was, nobody can say`:`its run ${e.n} stopped before it answered, and ${d.length} runs of ${B("users")} began on this machine after it was launched (${d.map(f=>f.run).join(", ")}): which is its, nobody can say. ${B("users")} remove --run <n> takes one back`}}function yo(e,t,n){let r;for(let s of[...e?.runs??[]].reverse()){if(s.takenBack===!0)continue;let o=jg(s,e?.runs??[],t,n);if("run"in o)return{run:o.run,...r!==void 0?{unknown:r}:{}};"unknown"in o&&(r??=o.unknown)}return r!==void 0?{unknown:r}:{}}async function Rc(e,t,n,r){let s={organizationId:t.org.organizationId,env:t.env},o=t.resources[n.resource];if(o===void 0)throw new L("invalid",`The state holds no resource ${n.resource} to take back`);if(o.kind==="mask")return t$(e,t,n);let i=await e.store.update(t,l=>Qo(l,n.resource)),a=[],c=!1,u=!1,d=!1;for(let l of[...o.runs].reverse()){if(l.takenBack===!0)continue;let f;if(o.kind==="users"){if(d){i=await e.store.update(i,S=>yn(S,n.resource,l.n));continue}let E=jg(l,o.runs,s,e);if("unknown"in E){e.say(`${n.resource}: run ${l.n} is not taken back: ${E.unknown}`),c=!0;continue}f="run"in E?E.file:void 0}else f=Ec(l,s,e,n.resource);if(f===void 0)continue;e.say(`${n.resource}: taking back run ${l.n}`);let h=kp(o.kind,{target:n.target.alias,subject:f,includeChanged:n.includeChanged,acceptAutomation:n.acceptAutomation,sweep:n.sweep,checkpointStore:Z(e.journalDir)}),m=await e.runner(h.script,h.args,r),g=We(E=>bp(o.kind,E),m.stdout,e.say),w=Ei(g).reduce((E,S)=>E+S.deleted,0);u||=g!==void 0?w>0:m.code!==1&&m.code!==2;let y=we(m.code),v=m.code===0||m.code===3,b=y?"destroying":v?m.code===3?n.ends.left:n.ends.whole:o.status,k=Og(m.code,void 0,m.stderr);if(a.push({resource:n.resource,action:n.action,phase:"remove",run:l.n,script:h.script,exitCode:m.code,status:b,...l.summary!==void 0?{summary:l.summary}:{},objects:JS(g),...g!==void 0?{answer:g}:{},...k!==void 0?{refusal:k}:{}}),m.code===3&&(c=!0),m.code===0)i=await e.store.update(i,E=>yn(E,n.resource,l.n)),d=o.kind==="users";else if(o.kind==="users"&&v)break;if(!v)return y||(i=await e.store.update(i,E=>Lt(E,{resource:n.resource,status:o.status}))),{whole:!1,code:y?m.code:1,wrote:u,steps:a,state:i}}return i=await e.store.update(i,l=>Lt(l,{resource:n.resource,status:c?n.ends.left:n.ends.whole})),{whole:!c,code:c?3:0,wrote:u,steps:a,state:i}}async function t$(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,d=>Qo(d,n.resource)),o=e.store.sasOf(t.org.organizationId,t.env,Bt(n.resource)),i=r.runs.at(-1),a=(d,l,f)=>({resource:n.resource,action:n.action,phase:"remove",run:i?.n??1,script:"sandforge-dataops",exitCode:l,status:d,objects:(i?.objects??[]).map(h=>({object:h.objectApiName,created:0,refused:0,deleted:0,kept:0,masked:h.masked??0,reason:f}))});e.say(`${n.resource}: deleting its store ${o}`);let c;try{c=await Vl(o)}catch(d){let l=d instanceof Error?d.message:String(d);return e.say(`${n.resource}: ${l}`),s=await e.store.update(s,f=>Lt(f,{resource:n.resource,status:r.status})),{whole:!1,code:1,wrote:!1,steps:[a(r.status,1,l)],state:s}}e.say(Wl(n.resource,c));for(let d of r.runs)d.takenBack!==!0&&(s=await e.store.update(s,l=>yn(l,n.resource,d.n)));s=await e.store.update(s,d=>Lt(d,{resource:n.resource,status:n.ends.whole}));let u=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; ${u} deleted`)],state:s}}var n$=new Set(["sandforge-seed","sandforge-clone","sandforge-dataops","sandforge-frozen","sandforge-users","sandforge-checkpoint"]);function mt(e,t){return t&&n$.has(e.script)?{...e,args:[...e.args,"--accept-emails"]}:e}function r$(e,t){let n=new Map(e.actions.map(i=>[i.resource,i])),r=new Set(_e(t).map(([i])=>i)),s=ht(t,e.actions.filter(i=>(i.action==="delete"||i.action==="replace"&&!St(i.kind))&&r.has(i.resource)).map(i=>i.resource)).map(i=>({phase:"remove",resource:i,action:n.get(i)?.action??"delete"})),o=e.actions.filter(i=>i.action==="create"||i.action==="replace").map(i=>({phase:"run",resource:i.resource,action:i.action}));return[...s,...o]}function Cg(e,t,n){if(we(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 s$(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 o$(e,t,n){let{resource:r,n:s,where:o,target:i,templateFile:a,dry:c,signal:u}=n,d=o.env,l=c!==void 0&&"answer"in c?c.answer:void 0,f=l===void 0||n.readTooEarly?void 0:Ht(l).created,h=await e.orgNow();if(r.kind==="seed"){let P=xr(d,r.name,s),D=r.run.seed??(l?.tool==="sandforge-seed"?l.seed:void 0),x=await e.store.update(t,Ce=>Et(Ce,{resource:r.name,kind:"seed",fingerprint:r.fingerprint,dependsOn:r.dependsOn,run:{script:"sandforge-seed",runId:P,...D!==void 0?{seed:D}:{},startedAt:h}})),J=mt($t(r,{target:i.alias,templateFile:a,runId:P,summaryFile:"",...D!==void 0?{seed:D}:{}}),n.acceptEmails),U=await e.runner(J.script,J.args,u),O=We(Ut,U.stdout,e.say),F=O!==void 0?ss(O):void 0,ae=(F?.created??0)>0||on(mo(e.journalDir,qe,`${P}.ndjson`)),X=O!==void 0?await e.store.writeFile(o.organizationId,d,oe(r.name,s),U.stdout).then(()=>oe(r.name,s)):void 0;return{state:x,script:J.script,code:U.code,...F!==void 0?{count:F}:{},...O!==void 0?{answer:O}:{},...X!==void 0?{summary:X}:{},wrote:ae,...f!==void 0?{planned:f}:{},...F?.refusal!==void 0?{answered:F.refusal}:{},stderr:U.stderr}}if(r.kind==="frozen")return i$(e,t,n,h,f);if(r.kind==="mask")return a$(e,t,n,h);if(r.kind==="users")return u$(e,t,n,h);if(r.kind==="replay")return d$(e,t,n,h,f);let m=oe(r.name,s),g=await e.store.prepareFile(o.organizationId,d,m),w=await e.store.update(t,P=>Et(P,{resource:r.name,kind:"forge",fingerprint:r.fingerprint,dependsOn:r.dependsOn,run:{script:"sandforge-clone",summary:m,startedAt:h}})),y=co(c),v=r.kind==="forge"&&r.run.records!==void 0?Yr(e.journalDir,o.organizationId,d,r.name):void 0,b=mt($t(r,{target:i.alias,templateFile:a,runId:"",summaryFile:g,...y!==void 0?{maxTotal:y}:{},...v!==void 0?{rootsPlanFile:v}:{}}),n.acceptEmails),k=await e.runner(b.script,b.args,u);v!==void 0&&YS(v,{force:!0});let E=on(g)?bc(g,"utf8"):void 0,S=We(Rn,E??"",e.say)??We(Rn,k.stdout,e.say),$=S!==void 0?Jr(S):void 0,j=$!==void 0?$.created>0:E!==void 0,A;if(k.code===0&&E!==void 0&&($?.created??0)>0){e.say(`${r.name}: verifying run ${s}`);let P=await e.runner(b.script,Wd({summary:g,target:i.alias,source:r.source.alias}),u),D=P.stdout.trim()===""?void 0:We(Qd,P.stdout,e.say);if(D!==void 0){let x=Zd(D);A={unstable:D.result.verdict==="unstable",...x!==void 0?{short:x}:{}}}else P.code!==0&&(A={unread:`its verification ended ${P.code} without an answer`})}return{state:w,script:b.script,code:k.code,...$!==void 0?{count:$}:{},...S!==void 0?{answer:S}:{},...E!==void 0?{summary:m}:{},wrote:j,...f!==void 0?{planned:f}:{},...A!==void 0?{verified:A}:{},...S?.error!==void 0?{answered:S.error}:{},stderr:k.stderr}}async function i$(e,t,n,r,s){let{resource:o,n:i,where:a,target:c,templateFile:u,dry:d,signal:l}=n,f=await e.store.update(t,S=>Et(S,{resource:o.name,kind:"frozen",fingerprint:o.fingerprint,dependsOn:o.dependsOn,run:{script:"sandforge-frozen",sas:tt(o.name),startedAt:r}})),h=co(d),m=mt($t(o,{target:c.alias,templateFile:u,runId:"",summaryFile:"",replace:n.replace,acceptAutomation:n.acceptAutomation,...h!==void 0?{maxTotal:h}:{}}),n.acceptEmails),g=await e.runner(m.script,m.args,l),w=We(Gr,g.stdout,e.say),y=w!==void 0?jn(w):void 0;y?.refusal!==void 0&&e.say(`${o.name}: ${y.refusal}`);let v=w===void 0?we(g.code):(y?.created??0)>0||vl(w),b=w!==void 0?await e.store.writeFile(a.organizationId,a.env,oe(o.name,i),g.stdout).then(()=>oe(o.name,i)):void 0,k=w?.verdict,E=k!==void 0?ui(k):g.code===0&&(y?.created??0)>0?{unread:"the load chained no verification"}:void 0;return{state:f,script:m.script,code:g.code,...y!==void 0?{count:y}:{},...w!==void 0?{answer:w}:{},...b!==void 0?{summary:b}:{},wrote:v,...s!==void 0?{planned:s}:{},...E!==void 0?{verified:E}:{},...n.replace&&w!==void 0&&Qr(w)?{tookBackEarlier:!0}:{},...y?.refusal!==void 0?{answered:y.refusal}:{},stderr:g.stderr}}async function a$(e,t,n,r){let{resource:s,n:o,where:i,target:a,templateFile:c,signal:u}=n,d=await e.store.update(t,v=>Et(v,{resource:s.name,kind:"mask",fingerprint:s.fingerprint,dependsOn:s.dependsOn,run:{script:"sandforge-dataops",startedAt:r}})),l=await e.store.prepareFolder(i.organizationId,i.env,Bt(s.name)),f=mt($t(s,{target:a.alias,templateFile:c,runId:"",summaryFile:"",store:l}),n.acceptEmails),h=await e.runner(f.script,f.args,u),m=We(Zr,h.stdout,e.say),g=m!==void 0?Cn(m):void 0;g?.refusal!==void 0&&e.say(`${s.name}: ${g.refusal}`);let w=g!==void 0?g.objects.some(v=>v.masked>0):we(h.code),y=m!==void 0?await e.store.writeFile(i.organizationId,i.env,oe(s.name,o),h.stdout).then(()=>oe(s.name,o)):void 0;return{state:d,script:f.script,code:h.code,...m!==void 0?{answer:m}:{},...y!==void 0?{summary:y}:{},wrote:w,...g!==void 0?{masking:g}:{},...g?.refusal!==void 0?{answered:g.refusal}:{},stderr:h.stderr}}function c$(e){let t;try{t=JSON.parse(e)}catch{return}if(yt.safeParse(t).success)return;let n=wr.safeParse(t);return n.success?(n.data.refusals??[]).map(r=>r.message):void 0}async function u$(e,t,n,r){let{resource:s,n:o,where:i,target:a,templateFile:c,signal:u}=n,d=await e.store.update(t,b=>Et(b,{resource:s.name,kind:"users",fingerprint:s.fingerprint,dependsOn:s.dependsOn,run:{script:W,startedAt:r}})),l=mt($t(s,{target:a.alias,templateFile:c,runId:"",summaryFile:"",acceptAutomation:n.acceptAutomation,acceptUserEmails:n.acceptUserEmails,...n.replacesRun!==void 0?{replacesRun:n.replacesRun}:{}}),n.acceptEmails),f=await e.runner(l.script,l.args,u),h=c$(f.stdout),m=h===void 0?We(Kt,f.stdout,e.say):void 0,g=m!==void 0?os(m):void 0,w=m!==void 0?m.users.some(b=>b.done.length>0):h===void 0&&f.code!==1&&f.code!==2,y=m!==void 0?await e.store.writeFile(i.organizationId,i.env,oe(s.name,o),f.stdout).then(()=>oe(s.name,o)):void 0,v=g?.refusal??(h!==void 0?h.join(" "):void 0);return{state:d,script:l.script,code:f.code,...g!==void 0?{count:g}:{},...m!==void 0?{answer:m}:{},...y!==void 0?{summary:y}:{},wrote:w,...n.replacesRun!==void 0&&m!==void 0?{tookBackEarlier:!0}:{},...v!==void 0&&v!==""?{answered:v}:{},stderr:f.stderr}}async function d$(e,t,n,r,s){let{resource:o,n:i,where:a,target:c,templateFile:u,dry:d,signal:l}=n,f=await e.store.update(t,k=>Et(k,{resource:o.name,kind:"replay",fingerprint:o.fingerprint,dependsOn:o.dependsOn,run:{script:V,startedAt:r}})),h=co(d),m=mt($t(o,{target:c.alias,templateFile:u,runId:"",summaryFile:"",replace:n.replace,acceptAutomation:n.acceptAutomation,checkpointStore:Z(e.journalDir),...h!==void 0?{maxTotal:h}:{}}),n.acceptEmails),g=await e.runner(m.script,m.args,l),w=We(ts,g.stdout,e.say),y=w!==void 0?ns(w):void 0,v=w!==void 0?(y?.created??0)>0:we(g.code),b=w!==void 0?await e.store.writeFile(a.organizationId,a.env,oe(o.name,i),g.stdout).then(()=>oe(o.name,i)):void 0;return{state:f,script:m.script,code:g.code,...y!==void 0?{count:y}:{},...w!==void 0?{answer:w}:{},...b!==void 0?{summary:b}:{},wrote:v,...s!==void 0?{planned:s}:{},...n.replace&&w!==void 0&&rs(w)?{tookBackEarlier:!0}:{},...y?.refusal!==void 0?{answered:y.refusal}:{},stderr:g.stderr}}function l$(e,t){let n=Cg(e,void 0,void 0);if(e!==0)return n;let r=(t?.objects??[]).reduce((s,o)=>s+o.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 f$(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 p$(e,t,n,r,s){if(n.kind==="frozen"){let i=await e.store.prepareFolder(r.organizationId,r.env,tt(n.name));return{payload:Wt(n,{sasDir:i})}}if(n.kind==="replay"){let i=n.checkpoint.read;return i===void 0||"refusal"in i?{refusal:i?.refusal??"its checkpoint was not resolved: plan again"}:{payload:{command:"replay",checkpoint:{id:i.checkpointId,organizationId:i.organizationId}}}}if(n.kind!=="seed"||(n.run.draws??[]).length===0)return{payload:Wt(n,{})};let o=await po(n,t,new Set,{...r,target:s.alias},{store:e.store,journalDir:e.journalDir});return o.refusals.length>0?{refusal:o.refusals.join(" ")}:{payload:Wt(n,{drawn:o.ids})}}function $g(e,t,n){let r=e;for(let s of t.actions){if(s.action!=="keep"&&s.action!=="drifted")continue;let o=r.resources[s.resource],i=n.get(s.resource)?.fingerprint;o===void 0||i===void 0||o.recovered===!0||o.status==="destroyed"||o.fingerprint===i||(r={...r,resources:{...r.resources,[s.resource]:{...o,fingerprint:i}}})}return r}function go(e){return e===0?"success":we(e)?"cancelled":e===1?"failure":"partial"}async function Ig(e,t){let{plan:n,target:r,resolved:s}=t,o=s.checked.file.name,i=(m,g=t.state,w=[])=>({result:{plan:n,steps:[],status:"failure",refusal:m,...w.length>0?{refusalCodes:[...w]}:{},state:{serial:g?.serial??0}},exitCode:1});if(n.refusal!==void 0)return i(n.refusal,t.state,n.refusalCodes);let a=r$(n,t.state),c=n.checkpoints?.find(m=>m.step==="before"),u=n.checkpoints?.find(m=>m.step==="after");if(a.length===0&&u===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 d=Je(e.locksDir,r.organizationId,{operation:"apply",env:o,alias:r.alias},e.lockOptions);if("busy"in d){let m=et(d.busy);return i(m.message,t.state,[m.code])}let l=new AbortController,f,h=(e.onStop??Ye)(m=>{f=m,e.say(`
148
- stopped by ${m}: 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`),l.abort()});try{let m;try{let O=await e.store.read(r.organizationId,o);if(O===void 0!=(t.state===void 0)||O!==void 0&&(O.serial!==t.state?.serial||O.lineage!==t.state.lineage))return i(`The state of ${o} 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,[Vr]);m=O??Fr({env:o,org:{organizationId:r.organizationId,kind:r.kind,username:r.username,alias:r.alias,...r.host!==void 0?{host:r.host}:{}},fileDigest:s.digest,sandforgeVersion:e.sandforgeVersion})}catch(O){if(O instanceof L)return i(O.message,t.state,[Ze(O).code]);throw O}m={...rd(m,r.host),file:{digest:s.digest},sandforgeVersion:e.sandforgeVersion};let g={organizationId:r.organizationId,env:o},w=[],y=[],v=[],b=new Map,k=!1,E,S=new Map(s.resources.map(O=>[O.name,O])),$=new Set,j=0,A=[],P={alias:r.alias,kind:r.kind},D=zr(s.checked.file);if(c!==void 0&&a.length>0){let O=await oi(e,{org:P,step:"before",name:c.name,...D},l.signal);if(A.push(O.result),O.checkpoint===void 0){let ae=f!==void 0?Pe(f):we(O.result.exitCode)?O.result.exitCode:1;return{result:{plan:n,steps:[],checkpoints:A,status:go(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:m.serial}},exitCode:ae}}let F=O.checkpoint;m=await e.store.update(m,ae=>Xe(ae,"before",F))}$g(m,n,S)!==m&&(m=await e.store.update(m,O=>$g(O,n,S)));try{for(let O of a){if(j+=1,E!==void 0||f!==void 0){y.push({resource:O.resource,why:"the apply was stopped before it"});continue}let F=S.get(O.resource),ae=(F?.dependsOn??[]).filter(fe=>b.has(fe));if(O.phase==="run"&&ae.length>0){y.push({resource:O.resource,why:`it depends on ${ae.map(fe=>`${fe} (${b.get(fe)??"not whole"})`).join(", ")}`});continue}let X=$r(e.locksDir,r.organizationId,e.lockOptions);if(X!==void 0){e.say(En(X).message),v.push(1),y.push({resource:O.resource,why:En(X).message});break}if(O.phase==="remove"){let fe=t.acceptAutomation||s.checked.file.resources[O.resource]?.accept?.automation===!0,ne=await Rc(e,m,{resource:O.resource,action:O.action,target:r,includeChanged:!1,sweep:!1,acceptAutomation:fe,ends:{whole:"destroyed",left:"partial"}},l.signal);if(m=ne.state,w.push(...ne.steps),k||=ne.wrote,we(ne.code)){E=ne.code;continue}if(v.push(ne.code),ne.code!==0&&ne.code!==3)break;continue}if(F===void 0)continue;let Ce=gn(m.resources[O.resource]),hr=await p$(e,m,F,g,r);if("refusal"in hr){e.say(`${O.resource}: not run, ${hr.refusal}`),v.push(1),y.push({resource:O.resource,why:hr.refusal}),b.set(O.resource,"not run");break}let Ny=await e.store.writeFile(g.organizationId,o,bt(O.resource,Ce),`${JSON.stringify(hr.payload,null,2)}
149
- `),Ty=F.dependsOn.some(fe=>$.has(fe)),Lc=F.kind==="users"&&O.action==="replace"?yo(m.resources[O.resource],g,e).run:void 0;e.say(`${O.resource}: run ${Ce} (${O.action})`);let K=await o$(e,m,{resource:F,n:Ce,where:g,target:r,templateFile:Ny,dry:t.dryRuns[O.resource],readTooEarly:Ty,replace:O.action==="replace"&&St(F.kind),acceptAutomation:t.acceptAutomation||s.checked.file.resources[O.resource]?.accept?.automation===!0,acceptEmails:t.acceptEmails===!0,acceptUserEmails:t.acceptUserEmails===!0,...Lc!==void 0?{replacesRun:Lc}:{},signal:l.signal});m=K.state,k||=K.wrote,F.kind!=="mask"&&$.add(O.resource);let xt=K.masking,Ie=F.kind==="mask"?l$(K.code,xt):s$(Cg(K.code,K.count,K.planned),K.verified),xy=await e.orgNow();if(m=await e.store.update(m,fe=>Lt(fe,{resource:O.resource,status:Ie.status,run:{endedAt:xy,exitCode:K.code,objects:xt!==void 0?xt.objects.map(ne=>({objectApiName:ne.object,created:0,refused:ne.refused,masked:ne.masked})):(K.count?.objects??[]).map(ne=>({objectApiName:ne.object,created:ne.created,refused:ne.refused})),...K.summary!==void 0?{summary:K.summary}:{},...xt?.snapshotId!==void 0?{snapshotId:xt.snapshotId}:{}}})),K.tookBackEarlier===!0)for(let fe of m.resources[O.resource]?.runs??[])fe.n===Ce||fe.takenBack===!0||(m=await e.store.update(m,ne=>yn(ne,O.resource,fe.n)));let mr=F.kind==="mask"?f$(xt):GS(K.count),Fc=Og(K.code,K.answered,K.stderr);if(w.push({resource:O.resource,action:O.action,phase:"run",run:Ce,script:K.script,exitCode:K.code,status:Ie.status,...K.summary!==void 0?{summary:K.summary}:{},objects:Ie.short!==void 0&&mr[0]!==void 0?[{...mr[0],reason:Ie.short},...mr.slice(1)]:mr,...K.answer!==void 0?{answer:K.answer}:{},...Fc!==void 0?{refusal:Fc}:{}}),Ie.short!==void 0&&e.say(`${O.resource}: ${Ie.short}`),we(K.code)){E=K.code,e.say(F.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`:F.kind==="users"?`${O.resource}: its run was stopped; the state keeps it applying, and the run file of sandforge users what it changed: apply again converges from it`:`${O.resource}: its run was stopped; the state keeps it applying, and its ${F.kind==="forge"?"summary what it created":F.kind==="frozen"?"sas what it loaded":F.kind==="replay"?"payload the checkpoint it replays":"run file what it wrote"}: apply again takes it back and runs it whole`);continue}if(v.push(Ie.counts),Ie.status!=="applied"&&b.set(O.resource,Ie.status),Ie.stops)break}}catch(O){let F=`the apply stopped on an error: ${O instanceof Error?O.message:String(O)}`;e.say(F),v.push(1);for(let ae of a.slice(j))y.push({resource:ae.resource,why:F})}let x=m.checkpoints?.after;if(k&&x!==void 0&&f===void 0){let O=await zt(e,{org:P,checkpoint:x,why:"taken before this apply wrote"},l.signal);A.push(O),m=await e.store.update(m,F=>Xe(F,"after",void 0))}let J=f===void 0&&E===void 0&&ln(v)===0;if(u!==void 0&&J){let O=await oi(e,{org:P,step:"after",name:u.name,...D},l.signal);A.push(O.result);let F=O.checkpoint;F!==void 0?m=await e.store.update(m,ae=>Xe(ae,"after",F)):we(O.result.exitCode)?E=O.result.exitCode:(e.say(`the checkpoint once applied, '${u.name}', was not taken: reset has nothing to rewind to until an apply takes it, which the next one does`),v.push(1))}let U=f!==void 0?Pe(f):E!==void 0?E:(()=>{let O=ln(v);return O===1&&k?3:O})();return{result:{plan:n,steps:w,...A.length>0?{checkpoints:A}:{},...y.length>0?{skipped:y}:{},status:go(U),state:{serial:m.serial}},exitCode:U}}finally{h(),d.lock.release()}}function h$(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??""}`})}var m$=72;function g$(e){let t=` ${e.resource} ${e.phase==="run"?"run":"removal of run"} ${e.run}: exit ${e.exitCode}, ${e.status}`;if(e.phase==="run"){let i=yt.safeParse(e.answer),a=[];if(i.success){let c=i.data.users.filter(d=>d.done.length>0).length,u=i.data.users.filter(d=>(d.refused??[]).length>0).length;a.push(`${t} User ${c} set up${u>0?`, ${u} refused`:""}`);for(let d of i.data.users)d.address==="awaiting"&&a.push(` ${d.username}: address awaiting its owner's confirmation \u2014 Salesforce sent the link to it; until it is clicked (${m$} h), the address stays .invalid`)}else a.push(t);e.refusal!==void 0&&a.push(` ${e.refusal}`);for(let c of e.objects)c.reason!==void 0&&a.push(` ${c.object}: ${c.reason}`);return a}let n=e.answer,s=[e.objects.map(i=>`${i.object} ${i.deleted} deleted`).join("; "),y$(n?.answer)].filter(Boolean),o=[`${t}${s.length>0?` ${s.join("; ")}`:""}`];e.refusal!==void 0&&o.push(` ${e.refusal}`);for(let i of Array.isArray(n?.kept)?n.kept:[])o.push(` ${i.username}: ${Rt(i.change)} kept, ${i.why}`);return o}var Ag=[["frozen","freeze(s)"],["active","activation(s)"],["profile","profile(s)"]];function y$(e){let t=vr.safeParse(e);if(!t.success)return"";let n=new Set(Ag.map(([o])=>o)),r=t.data.users.filter(o=>o.undone.some(i=>n.has(i.what)));if(r.length===0)return"";let s=Ag.flatMap(([o,i])=>{let a=r.reduce((c,u)=>c+u.undone.filter(d=>d.what===o).length,0);return a>0?[`${a} ${i}`]:[]});return`User ${r.length} put back: ${s.join(", ")}`}function w$(e){let t=e.objects.map(c=>`${c.object} ${c.created}`).join(", "),n=e.objects.reduce((c,u)=>c+u.refused,0),r=e.answer?.replay?.owners,s=typeof r?.kept=="number"?r.kept:void 0,o=typeof r?.toRunningUser=="number"?r.toRunningUser:void 0,i=(t!==""?`${t} created`:"")+(n>0?`, ${n} refused`:"")+(s!==void 0&&o!==void 0?`; ${s} records kept their owner, ${o} went to you`:""),a=[` ${e.resource} replay ${e.run}: exit ${e.exitCode}, ${e.status}`+(i!==""?` ${i}`:"")];e.refusal!==void 0&&a.push(` ${e.refusal}`);for(let c of e.objects)c.reason!==void 0&&a.push(` ${c.object}: ${c.reason}`);return a}function Sc(e,t,n=[]){let r=[""];for(let s of e.steps){if(s.script===W){r.push(...g$(s));continue}if(s.script===V&&s.phase==="run"){r.push(...w$(s));continue}if(s.script==="sandforge-dataops"){let i=s.objects.map(a=>s.phase==="run"?`${a.object} ${a.masked??0} masked${a.refused>0?`, ${a.refused} refused`:""}`:`${a.object} ${a.masked??0} left masked`).join("; ");r.push(` ${s.resource} ${s.phase==="run"?`masking ${s.run}: exit ${s.exitCode}`:"store deleted"}, ${s.status}${i?` ${i}`:""}`),s.refusal!==void 0&&r.push(` ${s.refusal}`);for(let a of s.objects)a.reason!==void 0&&r.push(` ${a.object}: ${a.reason}`);continue}let o=s.objects.map(i=>s.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("; ");r.push(` ${s.resource} ${s.phase==="run"?"run":"removal of run"} ${s.run}: exit ${s.exitCode}, ${s.status}${o?` ${o}`:""}`),s.refusal!==void 0&&r.push(` ${s.refusal}`);for(let i of s.objects)i.reason!==void 0&&r.push(` ${i.object}: ${i.reason}`)}for(let s of e.skipped??[])r.push(` ${s.resource}: not run, ${s.why}`);return r.push(...h$(e.checkpoints??[])),e.refusal!==void 0&&r.push(`${t} refused: ${e.refusal}`),r.push(...n),r.push(`${t}: ${e.status}; state serial ${e.state.serial}`),r}var Pg={words:1,switches:["--json","--save","--fail-on-findings"],values:["--file","--org","--alias"]},v$=2;function Ng(e){let t=[e.deliverability?"deliverability":void 0,e.schedules?"scheduled jobs":void 0,e.endpoints!==!1?"endpoints":void 0].filter(o=>o!==void 0),{fewest:n,most:r}=Gu(e),s=n===r?`${r}`:`${n} to ${r}`;return`audits after the apply: ${t.join(", ")}, about ${s} API requests`}function Dg(e){return e.replace(/\.\d{3}Z$/,"Z")}function k$(e){let t=Ne(e.host),n=e.kind==="sandbox"?t!==void 0?`sandbox ${t}`:"sandbox":e.kind==="scratch"?"scratch org":"Developer Edition org";return e.alias!==void 0?`${e.alias} (${n}, ${e.organizationId})`:`${e.organizationId} (${n})`}function b$(e){return e.unread!==void 0&&e.now===0&&e.jobs.length===0&&e.kept===0&&e.against===void 0}function $c(e,t){let n=[],r=`${e.apiRequests} API request${e.apiRequests===1?"":"s"}`;n.push(`audit of ${k$(e.org)}, ${Dg(e.at)}, ${r}`);let s=e.deliverability;s?.read==="closed"?n.push("deliverability: closed \u2014 System email only or No access: what runs there emails nobody. Which of the two, no API says."):s?.read==="open"?n.push("deliverability: open \u2014 All email: what runs there emails whoever its records name, the addresses copied from production's among them."):s?.unread!==void 0&&n.push(`deliverability: not read \u2014 ${s.unread}`);let o=e.schedules;if(o!==void 0&&b$(o))n.push(`scheduled jobs: not read \u2014 ${o.unread??""}`);else if(o!==void 0){let a=o.against,c=e.org.kind==="sandbox"?"this sandbox":"this org";if(a===void 0){let u=e.org.host??"its host";n.push(`scheduled jobs: ${o.now} now, nothing to compare them with: no inventory of ${u} is kept on this machine`)}else n.push(`scheduled jobs: ${o.now} now, against the inventory saved on ${a.savedAt.slice(0,10)} from ${a.organizationId}, `+(a.refreshed?`${c} before its refresh`:`${c}: no refresh since`));for(let u of o.jobs){let d=` ${u.status.padEnd(8)} `,l=f=>`${d}${u.name} (${u.type}) runs as ${u.owner??"a user not read"}, who is ${f}: its next run${u.nextFireTime!==void 0?`, ${Dg(u.nextFireTime)},`:""} fails`;if(u.status==="gone"){let f=u.cronExpression!==void 0?`${u.type}, ${u.cronExpression}`:u.type;n.push(`${d}${u.name} (${f}): `+(a?.refreshed===!0?"scheduled before the refresh, not since":`in the inventory of ${a?.savedAt.slice(0,10)??"?"}, not since`))}else u.status==="frozen"||u.status==="inactive"?n.push(l(u.status)):n.push(`${d}${u.name} (${u.type})`)}if(a!==void 0&&n.push(` ${"kept".padEnd(8)} ${o.kept}`),o.unread!==void 0&&n.push(` not read: ${o.unread}`),o.saved!==void 0)n.push(` inventory saved in ${o.saved}, to compare with after the next refresh`);else if(a===void 0){let u=e.org.alias??e.org.organizationId;n.push(` before the next refresh, keep one: ${B("env")} audit --file ${t.file} --org ${u} --save`)}}for(let a of t.notes??[])n.push(` ${a}`);let i=e.endpoints;if(i!==void 0){let a=i.productionHosts.join(", "),c=i.found.length===0;n.push(`endpoints that still name production (${a}):`+(c?i.unread!==void 0?" none among those read":" none":"")),i.notDeduced!==void 0&&n.push(` ${i.notDeduced}`);let u=h=>Math.max(...h.map(m=>m.length))+2,d=i.found.map(h=>Vu[h.source]),l=i.found.map(h=>h.name),f=i.found.map(h=>h.url);i.found.forEach((h,m)=>{n.push(` ${(d[m]??"").padEnd(u(d))}${(l[m]??"").padEnd(u(l))}${h.url.padEnd(u(f))}${Ku[h.why]}`)}),i.unread!==void 0&&n.push(` not read: ${i.unread}`)}return e.findings>0&&n.push("SandForge changes none of these: Setup, sf or your deployment put them right."),n}function E$(e,t){return e.saveFailed!==void 0?1:t&&e.result.findings>0?3:0}async function Tg(e,t){let n=pn(t.audits,"verb");if(n===void 0)throw new Error("env audit reads the deliverability at least");if(t.save&&!n.schedules)return{refusal:{code:"BAD_LINE",message:"--save keeps the scheduled jobs, which the file does not read (audits.schedules: false): take --save off the line, or the line off the file. Nothing was read."},exitCode:v$};let r=await Ir(e,{org:t.org,asked:n,save:t.save}),s=$c(r.result,{file:t.file,notes:r.notes});return{result:r.result,lines:s,exitCode:E$(r,t.failOnFindings)}}import{randomBytes as R$}from"node:crypto";import{mkdir as S$,open as $$,rename as A$,rm as O$}from"node:fs/promises";import{dirname as j$,join as C$,resolve as I$}from"node:path";var D$=448,P$=384,xg=72;function Ac(e){return e.map(([t,n])=>`${t} ${n}`).join(", ")}function Lg(e){switch(e.what){case"email":return"address asked back, awaiting its owner";case"active":return e.to?"activated":"deactivated";case"frozen":return e.to?"frozen":"unfrozen";case"profile":return`profile ${se(e.to)}`;case"permissionSet":return`${e.to==="added"?"permission set":"permission set taken off:"} ${se(e.name)}`;case"permissionSetGroup":return`${e.to==="added"?"permission set group":"permission set group taken off:"} ${se(e.name)}`;case"group":{let t=e.type==="Queue"?"queue":"public group";return`${e.to==="added"?t:`${t} taken off:`} ${se(e.name)}`}}}function N$(e){let t=yt.safeParse(e.answer);return t.success?t.data.users:void 0}function Mg(e,t){return e.steps.filter(n=>n.resource===t&&n.phase==="run").at(-1)}function _g(e){switch(e.status){case"applied":return"applied";case"partial":return"applied in part";case"failed":return"failed";default:return"stopped part way"}}function T$(e){let t=["## Access",""],n=[],r=new Date(Date.parse(e.at)+xg*36e5).toISOString(),s=e.run.plan.actions.filter(o=>o.kind==="users");s.length===0&&t.push("- No users resource: SandForge set up no user.");for(let o of s){let i=Mg(e.run,o.resource);if(i===void 0){t.push(`- ${se(o.resource)}: ${o.action==="keep"?"kept, as the last apply left its users":"not run"}.`);continue}let a=N$(i);if(a===void 0){t.push(`- ${se(o.resource)}: ${_g(i)}; what it did to each user does not read from its answer: ${B("env")} output names its users.`);continue}for(let c of a){let u=c.done.map(Lg),d=(c.refused??[]).map(f=>`${Lg(f.change)} refused (${f.code})`),l=[...u,...d];t.push(`- ${se(c.username)}: ${l.length>0?l.join("; "):"as the file says already"}.`),c.address==="awaiting"&&n.push(c.username)}}if(n.length>0){t.push("","### Addresses awaiting their owner","");for(let o of n)t.push(`- ${se(o)}: the address stays under \`.invalid\` until its owner follows the link Salesforce sent to it, by about ${Fo(r)} (${xg} hours).`)}return t.push("","SandForge resets no password: a user without one sets it by **Forgot your password?** on the sandbox's login page, once the address is theirs again."),t}function x$(e,t){let n=e.resources?.[t];if(n?.kind!=="mask")return;if(typeof n.rules!="string")return`the rules of the template ${se(n.rules.template)}`;let r=e.masking?.[n.rules];if(r===void 0)return;let s=[...new Set(r.rules.map(o=>o.fieldPattern))];return s.length>0?s.map(se).join(", "):void 0}function L$(e){let t=["## Data",""],n=e.run.plan.actions.filter(o=>o.kind!=="users");n.length===0&&t.push("- No data resource.");for(let o of n){let i=`${se(o.resource)} (${o.kind})`,a=Mg(e.run,o.resource);if(a===void 0){let u=e.run.skipped?.some(d=>d.resource===o.resource)===!0;t.push(`- ${i}: `+(o.action==="keep"?"kept, as applied before":o.action==="blocked"?"not applied: refused before it wrote":u?"not run: a resource it depends on did not end whole":"not run"));continue}let c=[_g(a)];if(o.kind==="mask"){let u=e.output?.resources[o.resource],d=u?.masked?Object.entries(u.masked):a.objects.flatMap(f=>f.masked!==void 0?[[f.object,f.masked]]:[]);d.length>0&&c.push(`masked ${Ac(d)}`);let l=x$(e,o.resource);l!==void 0&&c.push(`fields ${l}`),u?.snapshotId!==void 0&&c.push(`snapshot ${se(u.snapshotId)}, taken first`)}else{let u=a.objects.filter(f=>f.created>0);u.length>0&&c.push(`created ${Ac(u.map(f=>[f.object,f.created]))}`);let d=a.objects.filter(f=>f.refused>0);d.length>0&&c.push(`refused ${Ac(d.map(f=>[f.object,f.refused]))}`);let l=e.resources?.[o.resource];l?.kind==="replay"&&l.owners!==void 0&&c.push(l.owners==="same"?"owners kept as the checkpoint names them":"owned by the user the apply connected as")}t.push(`- ${i}: ${c.join("; ")}.`)}let r=e.run.checkpoints?.find(o=>o.step==="after"),s=e.run.plan.checkpoints?.find(o=>o.step==="after");if(r!==void 0||s!==void 0){t.push("","### Starting point","");let o=e.org.alias??e.org.organizationId;if(r?.checkpoint!==void 0){let i=s?.estimate!==void 0?`, about ${s.estimate.records} records`:"";t.push(`- Checkpoint ${s!==void 0?`${se(s.name)} `:""}${se(r.checkpoint)}${i}: the org as the testers get it.`,`- Back to it between two test runs: \`${B("env")} reset --file ${e.file} --org ${o}\``)}else t.push(`- The checkpoint ${s!==void 0?`${se(s.name)} `:""}was not taken${r!==void 0?` (exit ${r.exitCode})`:""}: no reset returns to this apply's end.`)}return t}function Fg(e){let t=e.org.alias??e.org.organizationId;return`\`${B("env")} audit --file ${e.file} --org ${t}\``}function F$(e){return Yu(e.run.audits,{endpoints:`${Fg(e)} lists those that still name production.`,schedules:`${Fg(e)} compares them with their inventory.`})}function zg(e){let{run:t,org:n}=e;return`${[Wu(t.plan.env,n),"","## Environment","",`- Environment: ${se(t.plan.env)}, state serial ${t.state.serial}.`,Hu(n),`- Applied: ${Fo(e.at)}, by SandForge ${e.sandforgeVersion}; it ended ${t.status}.`,"",...T$(e),"",...L$(e),"",...F$(e),"",...Ju()].join(`
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=so(t),r=on(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=so(t),r=on(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())}}};cg.Parser=tc});var pg=C(ar=>{"use strict";var ug=Ba(),XR=Xn(),ir=tr(),ZR=zi(),eS=z(),tS=ec(),dg=nc();function lg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new tS.LineCounter||null,prettyErrors:t}}function nS(e,t={}){let{lineCounter:n,prettyErrors:r}=lg(t),s=new dg.Parser(n?.addNewLine),o=new ug.Composer(t),i=Array.from(o.compose(s.parse(e)));if(r&&n)for(let a of i)a.errors.forEach(ir.prettifyError(e,n)),a.warnings.forEach(ir.prettifyError(e,n));return i.length>0?i:Object.assign([],{empty:!0},o.streamInfo())}function fg(e,t={}){let{lineCounter:n,prettyErrors:r}=lg(t),s=new dg.Parser(n?.addNewLine),o=new ug.Composer(t),i=null;for(let a of o.compose(s.parse(e),!0,e.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new ir.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(ir.prettifyError(e,n)),i.warnings.forEach(ir.prettifyError(e,n))),i}function rS(e,t,n){let r;typeof t=="function"?r=t:n===void 0&&t&&typeof t=="object"&&(n=t);let s=fg(e,n);if(!s)return null;if(s.warnings.forEach(o=>ZR.warn(s.options.logLevel,o)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:r},n))}function sS(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 eS.isDocument(e)&&!r?e.toString(n):new XR.Document(e,r,n).toString(n)}ar.parse=rS;ar.parseAllDocuments=nS;ar.parseDocument=fg;ar.stringify=sS});var mg=C(q=>{"use strict";var oS=Ba(),iS=Xn(),aS=Ea(),rc=tr(),cS=Ln(),pt=z(),uS=ct(),dS=Q(),lS=dt(),fS=lt(),pS=no(),hS=Xa(),mS=ec(),gS=nc(),io=pg(),hg=Pn();q.Composer=oS.Composer;q.Document=iS.Document;q.Schema=aS.Schema;q.YAMLError=rc.YAMLError;q.YAMLParseError=rc.YAMLParseError;q.YAMLWarning=rc.YAMLWarning;q.Alias=cS.Alias;q.isAlias=pt.isAlias;q.isCollection=pt.isCollection;q.isDocument=pt.isDocument;q.isMap=pt.isMap;q.isNode=pt.isNode;q.isPair=pt.isPair;q.isScalar=pt.isScalar;q.isSeq=pt.isSeq;q.Pair=uS.Pair;q.Scalar=dS.Scalar;q.YAMLMap=lS.YAMLMap;q.YAMLSeq=fS.YAMLSeq;q.CST=pS;q.Lexer=hS.Lexer;q.LineCounter=mS.LineCounter;q.Parser=gS.Parser;q.parse=io.parse;q.parseAllDocuments=io.parseAllDocuments;q.parseDocument=io.parseDocument;q.stringify=io.stringify;q.visit=hg.visit;q.visitAsync=hg.visitAsync});import{existsSync as Cy,mkdtempSync as PA,readFileSync as Iy,rmSync as NA,statSync as TA,writeFileSync as $y}from"node:fs";import{tmpdir as xA}from"node:os";import{dirname as je,join as xt,resolve as So}from"node:path";import{existsSync as an,readFileSync as Ec,readdirSync as QS,rmSync as XS}from"node:fs";import{join as go}from"node:path";import{join as sw}from"node:path";import{randomBytes as qy,randomUUID as id}from"node:crypto";import{mkdirSync as By,realpathSync as Uy,statSync as Pr}from"node:fs";import{open as Ky,readFile as Vy,readdir as Wy,rename as Hy,rm as Bo}from"node:fs/promises";import{basename as Wo,dirname as Te,join as Re,resolve as Nr}from"node:path";var Yy=448,Jo=384,Go=30,Jy=1440*6e4,Uo="state.json",Gy=/^runs\/[a-z][a-z0-9-]{0,62}\/[1-9][0-9]{0,5}\.summary\.json$/,Qy=/^runs\/[a-z][a-z0-9-]{0,62}\/[1-9][0-9]{0,5}\.summary\.removals\.json$/,Xy=/^templates\/[a-z][a-z0-9-]{0,62}\.[1-9][0-9]{0,5}\.json$/,sd=/^(?: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 Tr(e=process.env){return Te(Mu("env",e))}function xr(e,t){let n=gn(e,t);if(n!==void 0)return`The journal directory ${Nr(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 gn(e,t){let n;try{n=jr(od(e))}catch{return}return new Ue(n).isInsideRepo(od(t))?n:void 0}function od(e){let t=[],n=Nr(e);for(;;)try{return Re(Uy(n),...t.reverse())}catch{let r=Te(n);if(r===n)return Nr(e);t.push(Wo(n)),n=r}}function oe(e,t){return`runs/${Ke(e)}/${Fr(t)}.summary.json`}function Qo(e,t){return`runs/${Ke(e)}/${Fr(t)}.summary.removals.json`}function Et(e,t){return`templates/${Ke(e)}.${Fr(t)}.json`}function Lr(e,t,n,r=id()){return`env-${Ke(e)}-${Ke(t)}-${Fr(n)}-${r}`}function Ke(e){let t=dn.safeParse(e);if(!t.success)throw new L("invalid",`Not a name of the file: "${e}"`);return t.data}function Fr(e){if(!Number.isInteger(e)||e<1||e>999999)throw new L("invalid",`Not a run's rank: ${e}`);return e}function Mr(e){return{version:1,env:Ke(e.env),lineage:id(),serial:0,sandforgeVersion:e.sandforgeVersion,updatedAt:(e.now??new Date).toISOString(),org:{organizationId:pe(e.org.organizationId),kind:e.org.kind,username:e.org.username,...e.org.alias!==void 0?{alias:e.org.alias}:{},...e.org.host!==void 0?{host:e.org.host}:{}},file:{digest:e.fileDigest},resources:{}}}function ad(e,t){return t===void 0||e.org.host===t?e:{...e,org:{...e.org,host:t}}}function yn(e){return(e?.runs.at(-1)?.n??0)+1}function Rt(e,t){let n=e.resources[t.resource],r={...t.run,n:yn(n),objects:[]};return _r(e,t.resource,{kind:t.kind,fingerprint:t.fingerprint,dependsOn:[...t.dependsOn],status:"applying",runs:[...n?.runs??[],r]})}function Xo(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 _r(e,t,{...n,status:"destroying"})}function wn(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(o=>o.n===n?{...o,takenBack:!0}:o);return _r(e,t,{...r,runs:s})}function Ft(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 _r(e,t.resource,{...n,status:t.status,runs:r})}function _r(e,t,n){return{...e,resources:{...e.resources,[Ke(t)]:n}}}function Zo(e){if(e.org.kind==="scratch")return new Date(Date.parse(e.updatedAt)+Go*Jy).toISOString()}function zr(e){if(e.fileFolder!==null){let r=xr(e.fileFolder,e.journalDir);if(r!==void 0)return{refusal:r}}let t=new Ho(e),n=mn(t.root,e.uid??cd);return n!==void 0?{refusal:n}:{store:t}}var Ho=class{root;fileFolder;uid;renameFile;now;constructor(t){this.root=Re(Nr(t.journalDir),"env"),this.fileFolder=t.fileFolder,this.uid=t.uid??cd,this.renameFile=t.rename??((n,r)=>Hy(n,r)),this.now=t.now??Date.now}folderOf(t,n){let r=Ko(t);if(r===void 0)throw new L("invalid",`Not an Organization Id: "${t}"`);return Re(this.root,r,Ke(n))}fileOf(t,n,r){if(!Gy.test(r)&&!Xy.test(r)&&!Qy.test(r))throw new L("invalid",`Not a file of a state's folder: "${r}"`);return Re(this.folderOf(t,n),...r.split("/"))}async read(t,n){let r=this.folderOf(t,n),s=Re(r,Uo),o;try{o=await Vy(s,"utf8")}catch(i){if(Yo(i)==="ENOENT")return;throw i}return Zy(o,s,r)}stateFileOf(t,n){return Re(this.folderOf(t,n),Uo)}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","-"),o=`${r}.damaged-${s}`;for(let i=2;Pr(o,{throwIfNoEntry:!1})!==void 0;i++)o=`${r}.damaged-${s}-${i}`;return await this.renameFile(r,o),o}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),o=s?.serial??0;if(o!==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 ${o}, 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 i=ln.safeParse({...t,org:{...t.org,organizationId:pe(t.org.organizationId)},serial:n.serial+1,updatedAt:new Date(this.now()).toISOString()});if(!i.success)throw new L("invalid",`Not a state: ${i.error.message}`);for(let a of[Te(r),r]){let c=mn(a,this.uid);if(c!==void 0)throw new L("folder",c)}return await this.writeWhole(Re(r,Uo),`${JSON.stringify(i.data,null,2)}
144
+ `),i.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 o=this.fileOf(t,n,r),i=this.folderOf(t,n);for(let a of[Te(i),i,Te(o)]){let c=mn(a,this.uid);if(c!==void 0)throw new L("folder",c)}return await this.writeWhole(o,s),o}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),o=this.folderOf(t,n);for(let i of[Te(o),o,Te(s)]){let a=mn(i,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(!sd.test(r))throw new L("invalid",`Not a folder of a state's folder: "${r}"`);let s=this.folderOf(t,n),o=Re(s,...r.split("/"));for(let i of[Te(s),s,Te(o),o]){let a=mn(i,this.uid);if(a!==void 0)throw new L("folder",a)}return o}sasOf(t,n,r){if(!sd.test(r))throw new L("invalid",`Not a folder of a state's folder: "${r}"`);return Re(this.folderOf(t,n),...r.split("/"))}async remove(t,n){let r=this.folderOf(t,n);return Pr(r,{throwIfNoEntry:!1})===void 0?!1:(await Bo(r,{recursive:!0,force:!0}),!0)}async refreshedOf(t,n){let r=Ke(n),s;for(let o of await Vo(this.root)){if(Ko(o)!==o)continue;let i;try{i=await this.read(o,r)}catch{continue}i?.org.host===void 0||!bt(i.org,t)||s!==void 0&&Date.parse(s.updatedAt)>=Date.parse(i.updatedAt)||(s={organizationId:i.org.organizationId,serial:i.serial,updatedAt:i.updatedAt,host:i.org.host,setAside:this.folderOf(o,r)})}return s}async list(){let t=[];for(let n of await Vo(this.root))if(Ko(n)===n)for(let r of await Vo(Re(this.root,n))){if(!dn.safeParse(r).success)continue;let s=Re(this.root,n,r);try{let o=await this.read(n,r);if(o===void 0)continue;let i=Zo(o);t.push({organizationId:n,env:r,folder:s,state:o,...i!==void 0?{expiresAt:i}:{}})}catch(o){t.push({organizationId:n,env:r,folder:s,damaged:ud(o)})}}return t}async sweep(){let t=this.now(),n=[];for(let{state:r,expiresAt:s,folder:o,organizationId:i,env:a}of await this.list())r===void 0||s===void 0||Date.parse(s)>t||(await Bo(o,{recursive:!0,force:!0}),n.push({organizationId:i,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}-${qy(4).toString("hex")}.tmp`,s=await Ky(r,"wx",Jo);try{try{await s.writeFile(n,"utf8"),await s.sync()}finally{await s.close()}await this.renameFile(r,t)}catch(o){throw await Bo(r,{force:!0}),o}}};function Zy(e,t,n){let r;try{r=JSON.parse(e)}catch{r=void 0}let s=ln.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 ${B("env")} state recover: it sets this file aside and rebuilds the state from the run files beside it.`);let o=s.data;if(pe(o.org.organizationId)!==Wo(Te(n))||o.env!==Wo(n))throw new L("otherOrg",`The state ${t} is of ${o.env} on ${o.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 o}function cd(){return process.getuid?.()}function mn(e,t){try{let n=Pr(e,{throwIfNoEntry:!1});if(n!==void 0&&!n.isDirectory())return`${e} is not a folder.`;By(e,{recursive:!0,mode:Yy});let r=t();return r!==void 0&&Pr(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: ${ud(n)}`}}function Ko(e){try{return pe(e)}catch{return}}async function Vo(e){try{return(await Wy(e,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name).sort()}catch(t){if(Yo(t)==="ENOENT"||Yo(t)==="ENOTDIR")return[];throw t}}function Yo(e){return e?.code}function ud(e){return e instanceof Error?e.message:String(e)}import{createHash as ew}from"node:crypto";function vn(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 N(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 Mt(e){return JSON.stringify(ei(e))}function ei(e){if(Array.isArray(e))return e.map(ei);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,ei(t[n])]))}function ti(e){return ew("sha256").update(e,"utf8").digest("hex")}var tw=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 ve(e){return e.sweep===!0?["--sweep"]:[]}var Xe=p.string().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),R=p.number().int().nonnegative(),Ze=p.object({objectApiName:p.string().min(1),planned:R,deleted:R,alreadyGone:R,keptChanged:R,keptDependents:R,refused:R,notVisible:R.optional(),notReached:R.optional(),heldBy:p.array(p.string()),reasons:p.array(p.string())}),nw=p.object({objectApiName:p.string().min(1),planned:R,toDelete:R,alreadyGone:R,changedSince:R,keptChanged:R,changedBy:p.record(Xe,R),undeletable:R,notVisible:R,unread:R,reasons:p.array(p.string())}),_t=p.object({planned:R,objects:p.array(nw),undeletable:p.array(p.object({objectApiName:p.string().min(1),records:R})).optional(),userNames:p.record(Xe,p.string())});function xe(e,t,n){if(t===void 0||n?.length!==t.length)return[];let r=t.flatMap((s,o)=>{let i=n[o];return i!==void 0&&i!==""&&s!==""&&e.includes(s)?[i]:[]});return[...new Set(r)]}var rw=/^Nothing(?: was)? (?:written|deleted)\.?$/i;function dd(e){return e.split(`
145
+ `).map(t=>t.trim()).filter(t=>t!==""&&!rw.test(t)).at(-1)}var ce=class extends Error{constructor(n,r,s,o){super(`${De(n)} did not answer ${r} (${s}): `+(o===""?"it printed nothing on stdout":`it printed ${JSON.stringify(o)}`));this.script=n;this.expected=r;this.reason=s;this.excerpt=o;this.name="StepAnswerError"}script;expected;reason;excerpt};function _(e,t,n,r){let s=r.trim().slice(0,tw),o;try{o=JSON.parse(r)}catch{throw new ce(e,t,"not JSON",s)}let i=n.safeParse(o);if(!i.success){let a=i.error.issues[0],c=a?.path.join(".")||"the answer";throw new ce(e,t,`${c}: ${a?.message??"refused"}`,s)}return i.data}var ye="sandforge-checkpoint";function Z(e){return sw(e,"checkpoints")}function ow(e){return e==="scratch"?Go:0}function kn(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 bn(e){return["--org",I("--org",e.org),"--store",I("--store",e.store)]}function qr(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 ld(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 fd(e){return["take",...bn(e),...ld(e),"--estimate","--json"]}function iw(e){return["take",...bn(e),"--name",I("--name",e.name),"--keep-days",String(e.keepDays),...ld(e),"--json"]}function ri(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, ${Wc.toLocaleString("en-US")} at most. No record was read.`}}function pd(e){return["preview",...bn(e),"--checkpoint",yt.parse(e.checkpoint),"--json"]}function si(e){return["rewind",...bn(e),"--checkpoint",yt.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 aw(e){return["delete",...bn(e),"--checkpoint",yt.parse(e.checkpoint),"--yes","--json"]}var oi=p.object({code:p.string().min(1),message:p.string().min(1)}),En=p.object({refusal:oi}),cw=p.union([p.object({mode:p.string(),estimate:p.object({records:R,apiRequests:R,apiRequestsLeft:p.number(),seconds:p.number().nonnegative(),bytes:R}),refusal:oi.optional()}),En]),uw=p.union([p.object({checkpoint:p.object({checkpointId:yt,name:p.string().min(1),takenAt:p.string().min(1)})}),En]),dw=p.union([p.object({checkpoint:p.object({id:yt,name:p.string().min(1),takenAt:p.string().min(1)}),toDelete:R,toGiveBack:R,toBringBack:R,toRecreate:R,differs:p.boolean(),diff:p.object({objects:p.array(p.object({objectApiName:p.string().min(1),lastChangedBy:p.record(p.string(),R),touched:R})),userNames:p.record(p.string(),p.string())}),refusal:oi.optional()}),En]),ni=p.object({planned:R,done:R,left:R}),lw=p.union([p.object({checkpoint:p.object({id:yt,name:p.string().min(1)}),rewindId:p.string().min(1),status:p.enum(["success","partial","unstable","failure","cancelled"]),deleted:ni,givenBack:ni,broughtBack:ni,undo:p.object({until:p.string().min(1)}).optional(),residual:p.array(p.object({object:p.string(),reason:p.string(),count:R}))}),En]),fw=p.union([p.object({deleted:p.array(p.string()),kept:p.array(p.string())}),En]);function pw(e){return _(ye,"the estimate of a take",cw,e)}function hw(e){return _(ye,"a take",uw,e)}function hd(e){return _(ye,"a preview",dw,e)}function mw(e){return _(ye,"a rewind",lw,e)}function gw(e){return _(ye,"a deletion",fw,e)}function yw(e){return e.stderr.trim().split(`
146
+ `).map(t=>t.trim()).filter(Boolean).at(-1)??"it said nothing"}function zt(e,t){try{return{answer:t(e.stdout),raw:JSON.parse(e.stdout)}}catch(n){if(!(n instanceof ce))throw n;return{unread:`exit ${e.code}: ${yw(e)}`}}}function Br(e,t,n){let r=[],s=kn(e,"before");s!==void 0&&n&&ww(t)&&r.push({step:"before",name:s});let o=kn(e,"after");return o!==void 0&&(n||t?.checkpoints?.after===void 0)&&r.push({step:"after",name:o}),r}function md(e){return Object.values(e?.resources??{}).some(t=>t.status!=="destroyed")}function ww(e){return e?.checkpoints?.before===void 0&&!md(e)}function gd(e,t){return e.checkpoint?.before!==!0||t?.checkpoints?.before!==void 0?[]:md(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 yd(e){let t=zt(e,pw);if("unread"in t)return t;let n=t.answer;if(!("estimate"in n))return{refusal:ri(n.refusal)};let{records:r,apiRequests:s,seconds:o,bytes:i}=n.estimate;return{estimate:{records:r,apiRequests:s,seconds:o,bytes:i},...n.refusal!==void 0?{refusal:ri(n.refusal)}:{}}}function wd(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 Ur={before:"before the first write",after:"once applied"};function vd(e){let t=e.filter(n=>n.refusal!==void 0);if(t.length!==0)return t.map(n=>`The checkpoint the file asks ${Ur[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 kd(e){let t=0,n=[];for(let r of e)r.estimate!==void 0?t+=r.estimate.apiRequests:n.push(`the checkpoint ${Ur[r.step]}, not estimated`);return{estimate:t,notCounted:n}}function bd(e,t){let n=zt(t,hd);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 Le=e=>e.toLocaleString("en-US");function Ed(e){let t=[];for(let r of e.checkpoints??[]){let s=`checkpoint ${Ur[r.step]}: '${r.name}'`,{estimate:o}=r;o!==void 0?t.push(`${s}, about ${Le(o.records)} records, ${Le(o.apiRequests)} API requests, ${Le(Math.ceil(o.seconds))} s, ${vt(o.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, ${Le(n.toDelete??0)} to delete \xB7 ${Le(n.toGiveBack??0)} to give back \xB7 ${Le(n.toBringBack??0)} to bring back`:`${r}: nothing differs among the objects and fields it compares`)}return t}async function ii(e,t,n){e.say(`checkpoint ${Ur[t.step]}: taking '${t.name}'`);let r=await e.runner(ye,iw({org:t.org.alias,store:Z(e.journalDir),name:t.name,keepDays:ow(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=zt(r,hw),o="answer"in s?s.answer:void 0,i="raw"in s?s.raw:void 0;if(r.code===0&&o!==void 0&&"checkpoint"in o)return{result:{step:t.step,checkpoint:o.checkpoint.checkpointId,exitCode:r.code,answer:i},checkpoint:o.checkpoint.checkpointId};let a=o!==void 0&&"refusal"in o?`${o.refusal.code}: ${ri(o.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),...i!==void 0?{answer:i}:{}}}}async function qt(e,t,n){e.say(`checkpoint ${t.checkpoint}: deleted from this machine, ${t.why}`);let r=await e.runner(ye,aw({org:t.org.alias,store:Z(e.journalDir),checkpoint:t.checkpoint}),n),s=zt(r,gw),o="answer"in s?s.answer:void 0,i=o!==void 0&&"deleted"in o&&o.deleted.includes(t.checkpoint),a=o!==void 0&&"refusal"in o&&o.refusal.code==="NOT_FOUND";if(i||a)return{step:"delete",checkpoint:t.checkpoint,exitCode:0};let c=o!==void 0&&"refusal"in o?`${o.refusal.code}: ${o.refusal.message}`:o!==void 0&&"kept"in o?"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 Kr(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 et(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 Rd(e){let t=zt(e,hd);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[o,i]of Object.entries(s.lastChangedBy)){let a=n.diff.userNames[o]??o;r[a]=(r[a]??0)+i}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 Vr(e){return Object.entries(e).sort((t,n)=>n[1]-t[1]).map(([t,n])=>`${t} ${Le(n)}`).join(", ")}function Sd(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}:`,` ${Le(n.toDelete)} to delete \xB7 ${Le(n.toGiveBack)} to give back \xB7 ${Le(n.toBringBack)} to bring back`+(n.differs?"":" \u2014 nothing differs: nothing to rewind")],o=Vr(n.lastChangedBy);return o!==""&&s.push(` last changed by: ${o}`),n.refusal!==void 0&&s.push(` refused: ${n.refusal.message}`),s}function $d(e){let t=zt(e,mw),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((o,i)=>o+i.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 Ad(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:`${B("checkpoint")} undo --org ${e.alias} --checkpoint ${e.checkpoint} --store ${ze(Z(e.journalDir))}`}}function Od(e){return e.offered?`undo it until ${e.until}, sooner if the recycle bin fills: ${e.line}`:`no undo: ${e.why}`}var Wr="STATE_MOVED",jd="No flag lifts this: an environment is never applied to a production org.";function ke(e,t){return e.length>=15&&t.length>=15&&e.slice(0,15)===t.slice(0,15)}function Cd(e,t,n){if("unread"in t)return t.error!==void 0&&Qc(t.error)!==void 0?{refusal:{code:"UNTYPED",message:tu(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. ${jd}`,exit:1}};if(Rr(t)){let o=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 ${o}): an environment is applied to scratch orgs, Developer Edition orgs and the sandboxes its file lists. Nothing was read or written. ${jd}`,exit:1}}}let r=t.sandbox?n.scratch===!0?"scratch":"sandbox":"developer",s=Lo(n.instanceUrl);return{target:{alias:e,organizationId:t.id,kind:r,username:n.username,...s!==void 0?{host:s}:{}}}}var Id={scratch:"a scratch org",developer:"a Developer Edition org",sandbox:"a sandbox"};function ai(e,t){if(t.kind!=="sandbox")return;if(e.sandboxes.some(r=>typeof r=="string"&&ke(r,t.organizationId)))return{by:"organizationId"};let n=Ne(t.host);if(n!==void 0&&e.sandboxes.some(r=>typeof r!="string"&&r.myDomain===n))return{by:"myDomain",myDomain:n}}function Dd(e){return e?"listed by its My Domain; its Organization Id changed since the last apply":"listed by its My Domain"}function vw(e,t){let n=t.organizationId,r=pe(n);if(e.protect.some(i=>typeof i=="string"&&ke(i,n)))return{code:"PROTECTED",message:`${t.alias} (${r}) is listed under targets.protect: the file refuses it whatever else it says. Nothing was read or written.`,exit:1};let s=e.protect.flatMap(i=>typeof i=="string"?[]:[i.myDomain]),o=s.find(i=>Fo(t.host,i));if(o!==void 0)return{code:"PROTECTED",message:`${t.alias} (${r}, on ${t.host??""}) is listed under targets.protect by its My Domain ${o}: the file refuses it whatever else it says. Nothing was read or written.`,exit:1};if(s.length>0&&t.kind==="sandbox"&&t.host===void 0){let i=s.length===1?`lists ${s.join(", ")} by its My Domain: whether it is that sandbox`:`lists ${s.join(", ")} by their My Domains: whether it is one of them`;return{code:"PROTECTED",message:`${t.alias} (${r}) is a sandbox the sf CLI reaches by no My Domain host, and targets.protect ${i} cannot be told, and a protected org is never let through on a guess. Nothing was read or written. Sign in to it by its My Domain's URL to have it told apart.`,exit:1}}}function kw(e,t){let n=pe(t.organizationId),r=Ne(t.host),s=e.sandboxes.some(c=>typeof c!="string"),o="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.",i=" 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.";if(r!==void 0)return{code:"NOT_LISTED",message:`${t.alias} is a sandbox, and its Organization Id ${n} is not listed under targets.sandboxes, nor its My Domain ${r}: ${o} A refresh changes the Id: a sandbox listed by it before its refresh is listed again, or listed by its My Domain, which a refresh keeps: { myDomain: ${r} }. Nothing was read or written.`,exit:1};let a=Ir(t.host)?` Its host, ${t.host??""}, is a scratch org's, which no My Domain lists: the sf CLI did not say it is one, its display naming 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.`:s?t.host===void 0?" The sf CLI reaches it by no My Domain host: no My Domain the file lists can name it.":` Its host, ${t.host}, is no sandbox's: no My Domain the file lists can name it.`:"";return{code:"NOT_LISTED",message:`${t.alias} is a sandbox, and its Organization Id ${n} is not listed under targets.sandboxes: ${o} A refresh changes the Id: a sandbox listed before its refresh is listed again.${a} Nothing was read or written.`+(Ir(t.host)?"":i),exit:1}}function Pd(e,t){let n=vw(e,t);if(n!==void 0)return n;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 ${Id[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"&&ai(e,t)===void 0)return kw(e,t)}function tt(e){return{code:e.code==="otherOrg"?"OTHER_ORG":"STATE_DAMAGED",message:`${e.message} Nothing was read or written in the org.`,exit:1}}function Nd(e,t,n){if(!(e.env===t&&ke(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 Td(e,t,n,r=!1,s){if(s!==void 0&&!r&&bt({...s,kind:"sandbox"},e)){let{organizationId:i,serial:a,updatedAt:c,setAside:u}=s,f={organizationId:i,serial:a,updatedAt:c,setAside:u};return{warning:ci(e.alias,f),refreshed:f}}let o=`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 ${B("env")} state recover rebuilds the state from them`:"");return e.kind==="scratch"||n?{warning:o}:{refusal:{code:"NO_STATE",message:`${o.charAt(0).toUpperCase()}${o.slice(1)}. On ${Id[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 ci(e,t){return`none for this Organization Id; ${e} was refreshed since the last apply, which this machine kept under ${t.organizationId} (serial ${t.serial}, ${t.updatedAt.slice(0,10)}): the refresh took what it held, and this apply starts anew. That state is set aside, kept: ${t.setAside}`}function Hr(e,t){return t?{code:"STORE_IN_REPOSITORY",message:e,exit:2}:{code:"STORE",message:e,exit:1}}function nt(e){return{code:"LOCKED",message:Pu(e),exit:1}}function Rn(e){return{code:"CHECKPOINT_ACT",message:`${e.charAt(0).toUpperCase()}${e.slice(1)}`,exit:1}}import{readFileSync as bw}from"node:fs";import{join as Ld}from"node:path";var G="sandforge-clone",Fd=1e4,xd=1e6,Ew=["inputMode","recordId","soqlQuery","queryScope","maxRoots","templateId","aiPrompt","dryRun"];function Rw(e){let[t]=e;return`SELECT Id FROM ${t?.object??""}${t?.where!==void 0?` WHERE ${t.where}`:""}`}function Sw(e,t,n){let r=["resources",e,"template"],s=f=>({refusals:[N(r,f)]}),o;try{o=bw(Ld(n,t.file),"utf8")}catch(f){return s(`${t.file} cannot be read: ${f instanceof Error?f.message:String(f)}`)}if(o.length>xd)return s(`${t.file} is larger than ${xd} bytes`);let i;try{i=JSON.parse(o.replace(/^\uFEFF/,""))}catch{return s(`${t.file} is not JSON`)}let a=Array.isArray(i)?i:[i],c=a.find(f=>f!==null&&typeof f=="object"&&f.id===t.id);if(c===void 0){let f=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}"`+(f.length>0?`: it holds ${f.join(", ")}`:": it holds none"))}let u=Co.safeParse(c);return u.success?{entry:u.data}:{refusals:u.error.issues.map(f=>N(r,`the template "${t.id}" of ${t.file} is refused by Forge's template schema at ${f.path.map(String).join(".")||"its top"}: ${f.message}`))}}function Md(e,t,n,r,s){let o=["resources",t],i=[];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:i};let a;if(n.template!==void 0){let m=Sw(t,n.template,r);if("refusals"in m)return m;a=m.entry}let c={...a?.config};for(let m of Ew)delete c[m];if(n.tables!==void 0&&c.expandOrphanParents===!0)return{refusals:[N([...o,"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&&i.push(N([...o,"template"],"the template copies the files of the cloned records: an environment copies none, and the clone writes the records alone"));let u=n.depth??c.depth,f=(u??"custom")==="custom"?n.customDepth??c.customDepth:void 0;delete c.customDepth;let d=s.toISOString(),l={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:Rw(n.tables)}:{inputMode:"record",...n.record?.id!==void 0?{recordId:n.record.id}:{}},depth:u??"custom",...f!==void 0?{customDepth:f}:{},...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},h=Co.safeParse(l);return h.success?{run:{source:n.source,template:h.data,...n.record!==void 0?{record:{...n.record}}:{},...n.records!==void 0?{records:{...n.records}}:{},...n.tables!==void 0?{tables:n.tables.map(m=>({...m}))}:{},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{},acceptAutomation:n.accept?.automation===!0,acceptRealData:n.accept?.realData===!0},warnings:i}:{refusals:h.error.issues.map(m=>N(o,`the template it converts into is refused by Forge's template schema at ${m.path.map(String).join(".")||"its top"}: ${m.message}`))}}function _d(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 Yr(e){return vu(e.object,{...e.where!==void 0?{where:e.where}:{},...e.orderBy!==void 0?{orderBy:e.orderBy}:{},limit:e.limit},void 0,e.limit)}function Jr(e,t,n,r){let s=o=>o.replace(/[^A-Za-z0-9_-]/g,"-");return Ld(Ou(e),`env-${s(t.slice(0,15))}-${s(n)}-${s(r)}.json`)}function zd(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 $w(e){return e.edition?`its Organization record says IsSandbox false, edition ${e.edition}`:"its Organization record says IsSandbox false, and no edition"}function Aw(e,t,n){if(e.acceptRealData||zd(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 (${$w(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 qd(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(([,i])=>i!==void 0).map(([i,a])=>`${i} ${String(a)}`),s=zd(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 })",o=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}`,o?"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 Bd(e,t,n,r){let s=`the ${n} org (${r})`,o;try{o=await Er(e)}catch(d){return{refusal:`${s} could not be read: ${ui(d)}`}}let i=o.id,a=Rr(o);if(a){let d=Aw(t,s,o);if(d!==void 0)return{refusal:d}}let c={organizationId:i,...a?{production:!0}:{}};if(t.records!==void 0){let{records:d}=t;try{let h=(await e.query(Yr(d))).records.flatMap(m=>typeof m.Id=="string"?[m.Id]:[]);if(h.length===0){let m=d.where!==void 0?` WHERE ${d.where}`:"";return{refusal:`its records query chooses no ${d.object} in ${s}${m!==""?` (${m.trim()})`:""}: there is nothing to clone. Count what it chooses there with sf data query -o ${r} -q "SELECT COUNT() FROM ${d.object}${m}", and check its where`}}return{...c,roots:{count:h.length,sha256:ku(h)}}}catch(l){return{refusal:`its records query could not be read in ${s}: ${ui(l)}`}}}let u=t.record;if(u?.object===void 0||u.where===void 0)return c;let f=`${u.object} WHERE ${u.where}`;try{let d=(await e.query(`SELECT Id FROM ${f} 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 ${u.object} in ${s} (WHERE ${u.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 ${f}`)).totalSize} ${u.object} records in ${s} (WHERE ${u.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}: ${ui(d)}`}}}function Ud(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 Kd(e){if(e.wholeOrg)return Ow(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",I("--source",e.source),"--target",I("--target",e.target),...e.recordId!==void 0?["--record",I("--record",e.recordId)]:e.records!==void 0?["--query",I("--query",Yr(e.records)),"--max-roots",String(e.records.limit),...e.rootsPlanFile!==void 0?["--roots-plan",I("--roots-plan",e.rootsPlanFile)]:[]]:(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 Ow(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",...jw(t.fit)]:[],...e.acceptAutomation?["--accept-automation"]:[]]}function jw(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",I("--fit-where",`${n}=${r}`)]),...(e.strata??[]).flatMap(n=>["--fit-strata",I("--fit-strata",n)])]}function Vd(e){return[...Kd(e),"--dry-run","--json"]}function Wd(e){return[...Kd(e),...e.wholeOrg?["--yes"]:[],"--summary",I("--summary",e.summary),"--json"]}function Hd(e){return["--remove",I("--remove",e.summary),"--target",I("--target",e.target),...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[]]}function Yd(e){return[...Hd(e),...ve(e),"--json"]}function Jd(e){return[...Hd(e),"--preview",...ve(e),"--json"]}function Gd(e){return["--verify",I("--verify",e.summary),"--target",I("--target",e.target),"--source",I("--source",e.source),"--json"]}var Cw=p.enum(["SingleEmail","DailyWorkflowEmails"]),Iw=p.object({tool:p.literal(G),version:p.literal(1),dryRun:p.literal(!0),result:p.object({wouldInsertCount:R,failedCount:R}),writePlan:p.object({totalRows:R,storageBytes:R,objects:p.array(p.object({objectApiName:p.string().min(1),rows:R,storageBytes:R,mayAdd:R.optional()})),emails:p.array(p.object({limit:Cw,emails:R})).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()}),Dw=p.object({tool:p.literal(G),version:p.literal(1),dryRun:p.literal(!1),targetOrgId:Xe.optional(),result:p.object({successCount:R,failedCount:R,createdByObject:p.array(p.object({objectApiName:p.string().min(1),sourceIds:p.array(Xe)})),remapInJournal:p.literal(!0).optional(),createdCountByObject:p.array(p.object({objectApiName:p.string().min(1),created:R})).optional(),errors:p.array(p.object({objectApiName:p.string().min(1),failedCount:R,samples:p.array(p.unknown()).optional()}))}),running:p.literal(!0).optional(),interrupted:p.literal(!0).optional(),error:p.string().optional()}),Pw=p.object({tool:p.literal(G),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:R,objects:p.array(Ze),sweep:p.object({status:p.string()}).loose().optional()}),elapsedMs:R}),Nw=p.object({tool:p.literal(G),version:p.literal(1),action:p.literal("remove-preview"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),preview:_t,refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional(),notes:p.array(p.string()),elapsedMs:R}),Tw=p.object({tool:p.literal(G),version:p.literal(1),action:p.literal("verify"),result:p.object({verdict:p.enum(["verified","partial","unstable"]),attempts:R,objects:p.array(p.object({objectApiName:p.string().min(1),expected:R,present:R,deleted:R,notVisible:R,changed:R,linksChecked:R,linksBroken:R,error:p.string().optional()})),linksUnchecked:p.string().optional()})});function Qd(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 o=s.field!==void 0?`${s.objectApiName}.${s.field}`:s.objectApiName;switch(s.kind){case"required_field_missing":return n.has(o.toLowerCase())?[]:[`${o}, which the org requires and the clone does not write`];case"object_not_createable":case"object_through_parent":return[`${o}, which the user it writes as may not create`];case"object_feature_off":return[`${o}, 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[`${o} (${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 Xd(e){return _(G,"the summary of a dry run",Iw,e)}function Sn(e){return _(G,"the summary of a run",Dw,e)}function Zd(e){return _(G,"the outcome of a removal",Pw,e)}function el(e){return _(G,"the preview of a removal",Nw,e)}function tl(e){return _(G,"a verification",Tw,e)}function nl(e){let t=e.writePlan,n=(e.wouldBeRefused??[]).join(" "),r=xe(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 o=e.result.wouldInsertCount===t.totalRows,i=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,...o?{}:{atMost:!0}})),total:t.totalRows,created:e.result.wouldInsertCount,storageBytes:t.storageBytes,emails:t.emails??[],...i!==void 0?{refusal:i,...s}:{}}}function Gr(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(i=>i.object===r.objectApiName),o=`${r.failedCount} refused by the org`;s!==void 0?(s.refused+=r.failedCount,s.errors.push(o)):n.push({object:r.objectApiName,created:0,refused:r.failedCount,errors:[o]})}return{objects:n,created:e.result.successCount}}function rl(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 ui(e){return e instanceof Error?e.message:String(e)}import{readFileSync as ol}from"node:fs";import{join as il}from"node:path";var ue="sandforge-frozen",sl=1e6,xw=["sasDir","datasetDir"],Lw=["rootObject","excludedObjects","identityKeys","undeletableObjects","requiredLookupPlaceholders","requiredFieldDefaults","picklistRules","defaultPicklistRule","duplicateErrorPatterns"],al=new Set(["NO_LOAD","ALREADY_REMOVED","NOTHING_TO_REMOVE"]);function cl(e,t,n){let r=["resources",e,"config"],s=l=>({refusals:[N(r,l)]}),o;try{o=ol(il(n,t.config),"utf8")}catch(l){return s(`${t.config} cannot be read: ${l instanceof Error?l.message:String(l)}`)}if(o.length>sl)return s(`${t.config} is larger than ${sl} bytes`);let i;try{i=JSON.parse(o.replace(/^\uFEFF/,""))}catch{return s(`${t.config} is not JSON: a Frozen configuration is the panel's, as JSON`)}let a=br(i);if(a.length>0)return{refusals:a.map(({path:l,secret:h})=>N(r,`${t.config} holds a key shaped like a secret (${h}) at ${l.join(".")}: a load never reads the salt, and the configuration holds no secret. Take it out.`))};let c=du.strict().safeParse(i);if(!c.success)return{refusals:c.error.issues.map(l=>N(r,`${t.config} is refused by Frozen's configuration schema at ${l.path.map(String).join(".")||"its top"}: ${l.message}`))};let u=[],f={...c.data},d=xw.filter(l=>f[l]!==void 0);for(let l of d)delete f[l];return d.length>0&&u.push(N(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:f,dataset:{...t.dataset}},warnings:u}}function ul(e){return{kind:"frozen",kindVersion:1,dataset:{digest:e.dataset.digest,version:e.dataset.version},load:Object.fromEntries(Lw.map(t=>[t,e.config[t]??null]))}}function dl(e,t){return{...e.config,sasDir:t.sasDir,datasetDir:t.datasetDir}}async function ll(e,t){let n,r;try{n=await Zu(e),r=JSON.parse(ol(il(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 $n(e,t){return[e,"--config",I("--config",t.configFile),"--target",I("--target",t.target)]}function fl(e){return[...$n("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 pl(e){return[...$n("load",e),...e.reload?["--reload"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],"--max-total",String(e.maxTotal),"--yes","--json"]}function hl(e){return[...$n("verify",e),"--json"]}function ml(e){return[...$n("remove",e),...e.includeChanged===!0?["--include-changed"]:[],...ve(e),...e.acceptAutomation===!0?["--accept-automation"]:[],"--yes","--json"]}function gl(e){return[...$n("remove",e),...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],"--preview",...ve(e),"--json"]}var Fw=p.object({type:p.string().min(1),payload:p.record(p.string(),p.unknown()).optional()}).loose(),An={tool:p.literal(ue),posted:p.array(Fw),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()},yl=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:R,found:R,notLoaded:R,orphans:R,missingKeys:R}))}),Mw=p.object({...An,step:p.literal("load"),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:R,toInsert:R,toLink:R,notSent:R,toPurge:R,toDeactivate:R})).optional()}),_w=p.object({...An,step:p.literal("load"),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:R,inserted:R,reused:R,duplicates:R,failed:R})).optional(),verdict:yl.optional()}),zw=p.object({...An,step:p.literal("verify"),verdict:yl.optional()});function On(e,t){return e.filter(n=>n.type===t).at(-1)?.payload}function jn(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 qw=p.object({...An,step:p.literal("remove")}).transform((e,t)=>{let n=jn(e.posted.filter(h=>h.type!=="frozen:remove:automation:error")),r={planned:0,objects:[],userNames:{}};if(n!==void 0&&!al.has(n.code??""))return{tool:e.tool,preview:r,refusals:[n.message],...n.code!==void 0?{refusalCodes:[n.code]}:{},removalAlone:[]};let s=On(e.posted,"frozen:remove:preview:response")?.preview;if(s===void 0)return{tool:e.tool,preview:r,refusals:[],removalAlone:[]};let o=_t.extend({refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional()}).loose().safeParse(s);if(!o.success)return t.addIssue({code:"custom",message:`its preview: ${o.error.issues[0]?.message}`}),p.NEVER;let{refusals:i,refusalCodes:a,...c}=o.data,u=e.refusals??[],f=new Map(e.refusalCodes?.length===u.length?u.map((h,m)=>[h,e.refusalCodes?.[m]??""]):[]),d=u.filter(h=>!i.includes(h)),l=d.flatMap(h=>f.get(h)??[]);return{tool:e.tool,preview:c,refusals:i,...a?.length===i.length?{refusalCodes:a}:{},removalAlone:d,...l.length===d.length&&l.length>0?{removalAloneCodes:l}:{}}}),Bw=p.object({...An,step:p.literal("remove"),status:p.string().optional()}).transform((e,t)=>{let n=jn(e.posted),r={tool:e.tool,result:{status:"success",planned:0,objects:[]}};if(n!==void 0)return al.has(n.code??"")?r:(t.addIssue({code:"custom",message:`the removal was refused: ${n.message}`}),p.NEVER);let s=On(e.posted,"frozen:remove:response")?.result;if(s===void 0)return r;let o=p.object({status:p.enum(["success","partial","failure","cancelled"]),objects:p.array(Ze.loose())}).loose().safeParse(s);return o.success?{tool:e.tool,result:{status:o.data.status,planned:o.data.objects.reduce((i,a)=>i+a.planned,0),objects:o.data.objects}}:(t.addIssue({code:"custom",message:`its result: ${o.error.issues[0]?.message}`}),p.NEVER)});function wl(e){return _(ue,"the answer of a dry run",Mw,e)}function Qr(e){return _(ue,"the answer of a load",_w,e)}function vl(e){return _(ue,"a verification",zw,e)}function kl(e){return _(ue,"the preview of a removal",qw,e)}function bl(e){return _(ue,"the outcome of a removal",Bw,e)}function Uw(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 Kw(e){return(Array.isArray(e?.perObject)?e.perObject:[]).flatMap(n=>{let r=n,s=Number(r.picklistsRewritten??0),o=Number(r.fieldsDropped??0),i=[s>0?`${s} picklist value(s) a restricted picklist of the target refuses, rewritten by their rule`:"",o>0?`${o} field(s) the target lacks or takes no value of, dropped`:""].filter(Boolean);return i.length>0?[`${String(r.objectApiName)}: ${i.join(", ")}`]:[]})}function Vw(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 El(e){let t=jn(e.posted),n=[...t!==void 0?[t.message]:[],...e.refusals??[]],r=e.objects??[],s=r.reduce((f,d)=>f+d.toInsert,0),o=On(e.posted,"frozen:load:preview:response")?.plan,i=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=[...Uw(o),...Kw(o)],c=e.refusals??[],u=i!==void 0?xe(i,n,[...t!==void 0?[t.code??""]:[],...e.refusalCodes?.length===c.length?e.refusalCodes:c.map(()=>"")]):[];return{objects:r.map(f=>({object:f.objectApiName,wouldCreate:f.toInsert})),total:s,created:s,storageBytes:r.reduce((f,d)=>f+Sr(d.objectApiName,{rows:d.toInsert}),0),emails:Vw(o),...i!==void 0?{refusal:i}:{},...u.length>0?{refusalCodes:u}:{},...a.length>0?{notes:a}:{}}}function Cn(e){let t=jn(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 Xr(e){let n=On(e.posted,"frozen:load:response")?.report?.purge;if(n===void 0)return!1;let r=Object.values(n.leftUnrecorded??{}).reduce((s,o)=>s+o,0);return(n.failures??[]).length===0&&r===0}function Rl(e){let t=On(e.posted,"frozen:load:response")?.report;return[...Object.values(t?.purge?.deleted??{}),...Object.values(t?.purge?.deactivated??{})].some(r=>r>0)}function di(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 Sl(e){let t=jn(e.posted);if(e.verdict===void 0)return{unread:t?.message??"the verification gave no verdict"};let{short:n,unstable:r}=di(e.verdict);return r?{unread:n??"no two readings agreed"}:{failed:n!==void 0?[n]:[]}}function rt(e){return`frozen/${e}`}function Zr(e){return e!==void 0&&/^frozen\/[a-z][a-z0-9-]{0,62}$/.test(e)?e.slice(7):void 0}import{existsSync as li}from"node:fs";import{rm as Ww}from"node:fs/promises";import{join as $l}from"node:path";var he="sandforge-dataops",Al="snapshots.json";function Ol(e){let t={},n=[];for(let[r,s]of Object.entries(e)){let o=uu.safeParse({name:r,rules:s.rules});if(!o.success){n.push(...o.error.issues.map(i=>N(["masking",r,...i.path],`refused by the rules the DataOps panel saves: ${i.message}`)));continue}t[r]={name:r,rules:s.rules}}return n.length>0?{refusals:n}:{sets:t}}function Hw(e){let t=To.find(r=>r.id===e);if(t===void 0)return;let n=t.rules.flatMap(r=>{if(!Bc(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 jl(e,t,n){let r=["resources",e,"rules"],s,o;if(typeof t.rules=="string"){if(s=n[t.rules],o={set:t.rules},s===void 0)return{refusals:[N(r,`the rule set ${t.rules} is refused: see masking`)]}}else{let d=t.rules.template;if(s=Hw(d),o={template:d},s===void 0)return{refusals:[N([...r,"template"],`there is no DataOps template "${d}" that ships: there is `+To.map(l=>l.id).join(", "))]}}let i=t.object;if(i!==void 0&&!td({id:s.name,name:s.name,rules:s.rules},i))return{refusals:[N(["resources",e,"object"],`${"set"in o?`the rule set ${o.set}`:`the template ${o.template}`} has no rule for ${i}: a run would mask nothing. Name an object its rules mask, or give it a rule for this one`)]};let a=[],c=`${(i??"").toLowerCase()}.`,u=new Map(s.rules.filter(d=>i!==void 0&&d.fieldPattern.toLowerCase().startsWith(c)).map(d=>[(d.fieldPattern.split(".")[1]??"").toLowerCase(),d.ruleType])),f=Yw(t.where).filter(({field:d,empty:l})=>{let h=u.get(d.toLowerCase());return h!==void 0&&(!l||h==="nullify")}).map(({field:d})=>d);return f.length>0&&a.push(N(["resources",e,"where"],`its condition reads ${f.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:o,rules:s,...i!==void 0?{object:i}:{},...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}:{},...t.purgeHistory===!0?{purgeHistory:!0}:{}},warnings:a}}function Yw(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 o=/^(?:=|!=|<>)$/.test(r[2]??"")&&r[3]!==void 0;n.set(s,(n.get(s)??!0)&&o)}return[...n].map(([r,s])=>({field:r,empty:s}))}function Cl(e){return{kind:"mask",kindVersion:1,rules:[...e.rules.rules].map(t=>({...t,fieldPattern:t.fieldPattern.toLowerCase()})).sort((t,n)=>Mt(t).localeCompare(Mt(n))),object:e.object??null,where:e.where??null}}function Il(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 Dl(e){return{name:e.rules.name,rules:e.rules.rules}}function Ut(e){return`dataops/${e}`}function Pl(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"]:[],...t.slices===!0?["--slices"]:[],...t.maxRecords!==void 0?["--max-records",String(t.maxRecords)]:[],...t.maxRequests!==void 0?["--max-requests",String(t.maxRequests)]:[],...t.purgeHistory===!0?["--purge-history"]:[]]}function Nl(e){return[...Pl(e),"--dry-run","--json"]}function Tl(e){return[...Pl(e),"--yes","--json"]}var Jw=p.object({type:p.string().min(1),payload:p.record(p.string(),p.unknown()).optional()}).loose(),Ve=p.number().int().nonnegative(),xl={tool:p.literal(he),org:p.string().min(1),posted:p.array(Jw)},Gw=p.object({...xl,command:p.literal("dry-run"),slices:p.literal(!0).optional(),purgeHistory:p.literal(!0).optional()}),Qw=p.object({...xl,command:p.literal("run")});function Ll(e){return _(he,"the answer of a dry run",Gw,e)}function es(e){return _(he,"the answer of a masking",Qw,e)}function Bt(e,t){return e.filter(n=>n.type===t).at(-1)?.payload}function Fl(e){let t=Bt(e,"dataops:error");if(t!==void 0)return typeof t.message=="string"?t.message:"refused"}var Xw=p.object({objects:p.array(p.object({objectApiName:p.string().min(1),count:Ve.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:Ve,total:Ve,savedAt:p.string(),state:p.string()}).loose().optional(),history:p.array(p.object({objectApiName:p.string().min(1),historyObject:p.string(),trackedFields:p.array(p.string()),withoutValue:p.array(p.string()).optional(),rows:Ve.optional(),atLeast:p.literal(!0).optional(),deletable:p.boolean(),unread:p.string().optional()}).loose()).optional()}),Zw=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()}))}),ev=p.object({emails:p.array(p.object({limit:p.enum(["SingleEmail","DailyWorkflowEmails"]),emails:Ve}).loose()),refusals:p.array(p.object({code:p.string(),message:p.string()}).loose())}).loose();function Ml(e){let t=[],n=Fl(e.posted);n!==void 0&&t.push(n);let r=Xw.safeParse(Bt(e.posted,"dataops:anonymize:coverage:response")),s=Zw.safeParse(Bt(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:[],notes:[]};let o=ev.safeParse(Bt(e.posted,"dataops:automation:response")),i=r.data.objects.map(d=>({object:d.objectApiName,count:d.count}));for(let d of r.data.objects){let l=d.slicePlan;d.count===null&&!(e.slices===!0&&l!==void 0)&&t.push(`${d.objectApiName}: the org did not count the records it would mask`),e.slices!==!0&&l!==void 0&&(d.count??0)>l.size&&t.push(`${d.objectApiName} holds ${d.count??0} record(s), more than the ${l.size} a snapshot holds of one object: a run is refused and masks nothing (slices: true masks it in ${l.slices} slices, each backed up just before it is masked, or maxRecords takes up to ${zc})`)}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 ${B("dataops")} anonymize and the resource's store, --resume or --abandon`);for(let d of s.data.objects){d.error!==void 0?t.push(`${d.objectApiName}: not read: ${d.error}`):d.notCovered===!0&&t.push(`${d.objectApiName}: its rules mask no field the org shows this user: a run would mask nothing there`);let l=d.writeDenied?.deniedFields;l?.length===0&&t.push(qo(d.objectApiName));for(let h of l??[])t.push(qo(d.objectApiName,h))}for(let d of s.data.fieldsNotFound)t.push(zo(d.objectApiName,d.fieldApiName));let c=new Map,u=rd(r.data.history,e.purgeHistory===!0);u!==void 0&&(t.push(u),c.set(u,lu));for(let d of o.success?o.data.refusals:[])t.push(d.message),c.set(d.message,d.code);let f=o.success?o.data.emails.map(({limit:d,emails:l})=>({limit:d,emails:l})):[];return{objects:i,refusals:t,refusalCodes:t.map(d=>c.get(d)??""),emails:f,notes:nd(r.data.history,e.purgeHistory===!0).map(d=>d.trim())}}function _l(e){let t=Ml(e),n=t.objects.map(o=>({object:o.object,wouldCreate:o.count??0})),r=t.refusals.length>0?t.refusals.join(" "):void 0,s=r!==void 0?xe(r,t.refusals,t.refusalCodes):[];return{objects:n,total:n.reduce((o,i)=>o+i.wouldCreate,0),created:0,storageBytes:0,emails:t.emails,...r!==void 0?{refusal:r}:{},...s.length>0?{refusalCodes:s}:{},...t.notes.length>0?{notes:t.notes}:{}}}var tv=p.object({status:p.string().optional(),objects:p.array(p.object({objectApiName:p.string().min(1),total:Ve,processed:Ve,failed:Ve,notMasked:Ve}).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 In(e){let t=tv.safeParse(Bt(e.posted,"dataops:anonymize:response")??Bt(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=Fl(e.posted),o=(n.fieldsNotFound??[]).map(a=>zo(a.objectApiName,a.fieldApiName)),i=n.snapshot?.operationId??n.slices?.setId;return{objects:r,...i!==void 0?{snapshotId:i}:{},...s!==void 0?{refusal:s}:{},...o.length>0?{short:o.join("; ")}:{}}}var nv=new Set(["frozen","replay"]);function zl(e,t,n){let r=t?.resources[e]?.runs.at(-1)?.startedAt,s=n.indexOf(e);if(t===void 0||r===void 0||s<0)return[];let o=[];for(let i of n.slice(s+1)){let a=t.resources[i];if(a===void 0||a.status==="destroyed")continue;let c=a.runs.filter(u=>u.takenBack!==!0);for(let u of a.kind==="frozen"?c.slice(-1):c)Date.parse(u.startedAt)<Date.parse(r)||o.push({run:u,named:!nv.has(a.kind)||u===c.at(-1)})}return o}function fi(e,t,n){e.set(t,(e.get(t)??0)+n)}function hi(e,t,n,r){let s=new Map;for(let{run:o}of zl(e,t,n))for(let i of o.objects)i.created>0&&fi(s,i.objectApiName,i.created);return r===void 0?{theirs:s,unsure:new Map}:{theirs:new Map,unsure:s}}function rv(e){return e.slice(0,15)}async function ql(e,t,n,r,s){if(r===void 0)return hi(e,t,n,void 0);let o=u=>u.toLowerCase()===r.object.toLowerCase(),i=new Map,a=new Map;for(let{run:u,named:f}of zl(e,t,n)){let d=f?await s.createdBy(u).catch(()=>{}):void 0,l=d!==void 0&&"created"in d?d.created:void 0;for(let h of u.objects)h.created<=0||l!==void 0&&o(h.objectApiName)||fi(i,h.objectApiName,h.created);for(let[h,m]of l??[])if(o(h))for(let g of m)a.set(rv(g),g)}let c=new Map;if(a.size===0)return{theirs:c,unsure:i};try{let u=iu(r.object),f=ou(r.where),d=0;for(let l of au([...a.values()]))d+=await s.count(`SELECT COUNT() FROM ${u} WHERE (${f}) AND Id IN (${l})`);c.set(r.object,d)}catch{fi(i,r.object,a.size)}return{theirs:c,unsure:i}}function Bl(e,t,n={theirs:new Map,unsure:new Map}){let r=Ml(t),s=e.runs.at(-1),o=new Map((s?.objects??[]).map(u=>[u.objectApiName,u.masked??0]));if(r.refusals.length>0)return{objects:[],masked:0,unread:r.refusals.join(" ")};let i=[],a=[],c=0;for(let{object:u,count:f}of r.objects){let d=f??0,l=o.get(u)??0,h=Math.min(Math.max(0,d-l),n.theirs.get(u)??0);if(c+=h,a.push({object:u,present:Math.min(d,l),...d<l?{gone:l-d}:{}}),d-h>l){let m=h>0?`, ${h} created since by the resources applied after it`:"",g=n.unsure.get(u)??0,w=g>0?`, unless they are among the ${g} the resources applied after it created since, whose ids could not be counted under its condition`:"";i.push(`${u} ${d} under its condition, ${l} masked${m}: ${d-h-l} more, which hold their original values${w}`)}else d<l&&i.push(`${u} ${d} under its condition, ${l} masked: ${l-d} gone`)}return{objects:a,masked:[...o.values()].reduce((u,f)=>u+f,0),...c>0?{theirs:c}:{},...i.length>0?{drift:i.join("; ")}:{}}}function pi(e,t){return`${B("dataops")} anonymize --org ${e.alias} --restore ${t} --store ${e.store!==void 0?ze(e.store):"<its store>"}`}function Ul(e,t){return t.store??`${Ut(e)} beside the state`}function Kl(e,t){return[`masking is one-way: each run first takes a snapshot of the values it writes over, kept on this machine in ${Ul(e,t)}, and destroy never puts them back: it deletes the snapshots. Putting them back is your own act, before a destroy: `+pi(t,"<the snapshot its run names>")]}function Vl(e){return e.runs.find(t=>t.takenBack!==!0)}function sv(e){let t=Vl(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 mi(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 ${sv(e)}, which destroy deletes`}var Wl={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 Hl(e,t=0){return`applied, and its condition selects the ${e} record(s) it masked, with the same rules${t>0?`, beside ${t} the resources applied after it created since`:""}: masked again they would only be masked twice`}function Yl(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 gi(e,t,n,r){let s=Vl(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, ${Ul(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: ${pi(r,s)}`:`Its snapshots are listed in its store: ${pi(r,"<snapshot>")} puts one back, before this ${e}, as your own act`)}async function Jl(e){if(!li(e))return{snapshots:[]};let t=li($l(e,Al))?Au($l(e,Al)).getKeysByPrefix("backup:").map(n=>n.slice(7)).filter(n=>!n.includes(":")):[];if(await Ww(e,{recursive:!0,force:!0}),li(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 Gl(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`}import{existsSync as ov,readFileSync as iv}from"node:fs";import{isAbsolute as av}from"node:path";var V="sandforge-checkpoint",yi="REPLAY_CHECKPOINT_NOT_FOUND",ef=new Set(["NO_LOAD","ALREADY_REMOVED","NOTHING_TO_REMOVE"]);function tf(e){return{owners:e.owners??"same",customSettings:e.customSettings===!0,mask:e.mask===!0,contactPoints:e.keepContactPoints===!0?"kept":"neutralized",objects:e.objects??[],excluded:e.excludeObjects??[],link:[]}}var cv={owners:"owners",customSettings:"customSettings",mask:"mask",contactPoints:"keepContactPoints",objects:"objects",excluded:"excludeObjects"};function nf(e,t){let n={checkpoint:t.checkpoint,...t.from!==void 0?{from:t.from}:{},...t.objects!==void 0?{objects:t.objects}:{},...t.excludeObjects!==void 0?{excludeObjects:t.excludeObjects}:{},...t.owners!==void 0?{owners:t.owners}:{},...t.customSettings!==void 0?{customSettings:t.customSettings}:{},...t.mask!==void 0?{mask:t.mask}:{},...t.keepContactPoints!==void 0?{keepContactPoints:t.keepContactPoints}:{},...t.maxRecords!==void 0?{maxRecords:t.maxRecords}:{},...t.accept?.automation===!0?{acceptAutomation:!0}:{}},r=qc.safeParse(tf(n));return r.success?{run:n,warnings:[]}:{refusals:r.error.issues.map(s=>{let[o,...i]=s.path,a=cv[String(o)]??String(o);return N(["resources",e,a,...i],`refused by the choices a replay takes: ${s.message}`)})}}function Ql(e){return e===void 0||e.length===0?null:[...new Set(e.map(t=>t.toLowerCase()))].sort()}function rf(e){return(e.objects??[]).map(t=>({object:t}))}function sf(e,t,n){if(typeof t=="string")return{file:t};let r=["resources",e,"checkpoint","file"],s=(n[t.env]??"").trim();return s===""?{refusal:N(r,`the variable ${t.env} is not set: set it in the job's environment to the path of the checkpoint file ${e} replays`)}:av(s)?{file:s}:{refusal:N(r,`the variable ${t.env} holds ${s}, which is not a path from the root: give the checkpoint file from the root`)}}function uv(e){return e.checkpoint!==void 0&&(e.valid||e.why==="refreshed"||e.why==="scratchExpired")}function Xl(e,t){return e.slice(0,15)===t.slice(0,15)}function dv(e){return[...e].sort((t,n)=>(n.checkpoint?.takenAt??"").localeCompare(t.checkpoint?.takenAt??""))[0]}function Zl(e){return{checkpointId:e.checkpointId,organizationId:e.organizationId,...e.checkpoint!==void 0?{name:e.checkpoint.name,takenAt:e.checkpoint.takenAt}:{}}}function lv(e,t){return`take one before the next refresh: ${B("checkpoint")} take --org ${t} --name ${e}; or name an exported file: checkpoint: { file: \u2026, keyEnv: \u2026 }`}function fv(e,t,n,r){let{checkpoint:s}=e,o=n.filter(uv);if(s.id!==void 0){let f=o.filter(h=>h.checkpointId===s.id),d=[...new Set(f.map(h=>h.organizationId.slice(0,15)))],l=f[0];return l!==void 0&&d.length===1?Zl(l):d.length>1?{code:"AMBIGUOUS",refusal:`checkpoints of ${d.length} orgs have the id ${s.id} on this machine: name it by name with from, the org role it was taken of`}:{code:yi,refusal:`no checkpoint ${s.id} is kept on this machine: "${B("checkpoint")} list" names those it keeps`}}let i=s.name??"",a,c;if(t.from!==void 0){let f=t.from,d=o.filter(l=>{let h=l.checkpoint?.org;return h!==void 0&&(h.alias===f||h.username.toLowerCase()===f.toLowerCase())}).map(l=>l.organizationId);a=o.filter(l=>d.some(h=>Xl(h,l.organizationId))),c=`of ${f}`}else{let f={name:r.alias,organizationId:r.organizationId,...r.username!==void 0?{username:r.username}:{},...r.instanceUrl!==void 0?{instanceUrl:r.instanceUrl}:{}};a=o.filter(d=>d.checkpoint!==void 0&&!Xl(d.organizationId,r.organizationId)&&Vu(d.checkpoint.org,f)!==void 0),c=`of ${r.alias} before its refresh`}let u=dv(a.filter(f=>f.checkpoint?.name===i));return u!==void 0?Zl(u):{code:yi,refusal:`no checkpoint ${c} named '${i}' is kept on this machine: `+lv(i,t.from??r.alias)}}async function of(e,t,n,r){if(e.checkpoint.file!==void 0){if(t.file===void 0)return{code:yi,refusal:"its checkpoint file was not resolved"};let o=await(r.readHeader??zu)(t.file);if("refusal"in o)return{code:o.refusal.code,refusal:o.refusal.message};let{header:i}=o.read;return{checkpointId:i.checkpointId,organizationId:i.organizationId,takenAt:i.takenAt}}let s=[];for(let o of[r.storeRoot,qu(r.storeRoot)]){if(!ov(o))continue;let i=yu({root:o,...r.locksDir!==void 0?{locksDir:r.locksDir}:{}});if("refusal"in i)return{code:"STORE_REFUSED",refusal:`the checkpoints kept in ${o} cannot be read: `+gu(i.refusal,o,"SANDFORGE_JOURNAL_DIR")};s.push(...await i.store.list())}return fv(e,t,s,n)}function af(e,t){let n=t!==void 0&&"checkpointId"in t?t:void 0,r=tf(e);return{kind:"replay",kindVersion:1,checkpoint:n!==void 0?{id:n.checkpointId,organizationId:n.organizationId.slice(0,15)}:{unread:e.checkpoint.id??(e.checkpoint.name!==void 0?{name:e.checkpoint.name,from:e.from??null}:"file")},owners:r.owners,customSettings:r.customSettings,mask:r.mask,contactPoints:r.contactPoints,objects:Ql(e.objects),excludeObjects:Ql(e.excludeObjects)}}function pv(e){let{run:t,place:n}=e;if(t.checkpoint.file!==void 0){if(n.file===void 0||t.checkpoint.keyEnv===void 0)throw new Error(`${e.name} names a checkpoint file that was not resolved: plan again.`);return["--file",I("--file",n.file),"--key-env",I("--key-env",t.checkpoint.keyEnv)]}let r=n.read;if(r!==void 0&&"checkpointId"in r)return["--checkpoint",I("--checkpoint",r.checkpointId),"--from",I("--from",r.organizationId)];if(t.checkpoint.id!==void 0)return["--checkpoint",I("--checkpoint",t.checkpoint.id)];throw new Error(`${e.name} names its checkpoint by a name this plan has not resolved: plan again.`)}function hv(e){return[...e.objects!==void 0&&e.objects.length>0?["--objects",I("--objects",e.objects.join(","))]:[],...(e.excludeObjects??[]).flatMap(t=>["--exclude-object",I("--exclude-object",t)]),...e.owners!==void 0?["--owners",e.owners]:[],...e.customSettings===!0?["--custom-settings"]:[],...e.mask===!0?["--mask"]:[],...e.keepContactPoints===!0?["--keep-contact-points"]:[]]}function cf(e){return["replay",...pv(e),"--target",I("--target",e.target),"--store",I("--store",e.store),...hv(e.run),...e.again?["--again"]:[],...e.acceptAutomation===!0||e.run.acceptAutomation===!0?["--accept-automation"]:[]]}function uf(e){return[...cf(e),...e.run.maxRecords!==void 0?["--max-records",String(e.run.maxRecords)]:[],"--dry-run","--json"]}function df(e){if(!Number.isInteger(e.maxRecords)||e.maxRecords<1)throw new Error(`${e.name} has no count from its dry run to be held to: plan again.`);return[...cf(e),"--max-records",String(e.maxRecords),"--yes","--json"]}function lf(e){return["replay","--checkpoint",I("--checkpoint",e.replayed.checkpointId),"--from",I("--from",e.replayed.organizationId),"--target",I("--target",e.target),"--store",I("--store",e.store),"--remove",...e.includeChanged===!0?["--include-changed"]:[]]}function ff(e){return[...lf(e),...ve(e),...e.acceptAutomation===!0?["--accept-automation"]:[],"--yes","--json"]}function pf(e){return[...lf(e),"--preview",...ve(e),...e.acceptAutomation===!0?["--accept-automation"]:[],"--json"]}var mv=p.object({command:p.literal("replay"),checkpoint:p.object({id:p.string().min(1),organizationId:p.string().min(1)}).loose()}).loose();function ts(e){let t;try{let n=mv.safeParse(JSON.parse(iv(e,"utf8")));t=n.success?n.data:void 0}catch{t=void 0}if(t===void 0)throw new Error(`${e} names no checkpoint a replay wrote from: the replay it is the summary of cannot be taken back from it.`);return{checkpointId:t.checkpoint.id,organizationId:t.checkpoint.organizationId}}var gv=p.object({code:p.string().min(1),message:p.string().min(1)}).loose(),wi={command:p.literal("replay"),checkpoint:p.object({id:p.string().min(1),name:p.string().optional(),organizationId:p.string().min(1),takenAt:p.string().optional()}).loose(),target:p.object({alias:p.string().min(1),organizationId:p.string().optional()}).loose(),refusals:p.array(p.string()).optional(),refusalCodes:p.array(p.string()).optional(),refused:gv.optional(),ended:p.literal(!0).optional(),exit:p.number().int()},hf=p.object({records:p.object({toCreate:R}).loose(),owners:p.object({kept:R,toRunningUser:R}).loose().optional(),filesLeft:p.array(p.object({objectApiName:p.string()}).loose()),refused:p.array(p.object({object:p.string().min(1),records:R,reason:p.string().min(1),path:p.string().optional()}).loose()).optional(),requests:R}).loose(),yv=p.object({apiRequests:p.object({estimate:R}).loose()}).loose(),wv=p.object({...wi,action:p.literal("dryRun"),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:R,toInsert:R,toLink:R,notSent:R,toPurge:R}).loose()).optional(),plan:p.record(p.string(),p.unknown()).optional(),replay:hf.optional()}),vv=p.object({...wi,action:p.literal("replay"),status:p.string().optional(),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:R,inserted:R,failed:R}).loose()).optional(),result:p.record(p.string(),p.unknown()).optional(),replay:hf.optional()}),mf=p.object({...wi,action:p.literal("remove"),preview:p.literal(!0).optional(),objects:p.array(p.record(p.string(),p.unknown())).optional(),removal:p.record(p.string(),p.unknown()).optional()}),kv=p.object({objectApiName:p.string().min(1),planned:R,toDelete:R,alreadyGone:R,changedSince:R,keptChanged:R,undeletable:R,notVisible:R,unread:R}).loose(),bv=mf.transform((e,t)=>{let n={planned:0,objects:[],userNames:{}},r=e.refused;if(r!==void 0&&ef.has(r.code))return{tool:V,preview:n,refusals:[],removalAlone:[]};let s=[...r!==void 0?[r.message]:[],...e.refusals??[]],o=e.refusalCodes??[],i=[...r!==void 0?[r.code]:[],...o.length===(e.refusals??[]).length?o:[]],a=p.array(kv).safeParse(e.objects??[]);if(!a.success)return t.addIssue({code:"custom",message:`its preview: ${a.error.issues[0]?.message}`}),p.NEVER;let c=a.data.map(u=>({objectApiName:u.objectApiName,planned:u.planned,toDelete:u.toDelete,alreadyGone:u.alreadyGone,changedSince:u.changedSince,keptChanged:u.keptChanged,changedBy:{},undeletable:u.undeletable,notVisible:u.notVisible,unread:u.unread,reasons:[]}));return{tool:V,preview:{planned:c.reduce((u,f)=>u+f.planned,0),objects:c,userNames:{}},refusals:s,...i.length===s.length&&i.length>0?{refusalCodes:i}:{},removalAlone:[]}}),Ev=mf.transform((e,t)=>{let n={tool:V,result:{status:"success",planned:0,objects:[]}},r=e.refused;if(e.removal===void 0)return r===void 0||ef.has(r.code)?n:(t.addIssue({code:"custom",message:`the removal was refused: ${r.message}`}),p.NEVER);let s=p.object({status:p.enum(["success","partial","failure","cancelled"]),objects:p.array(Ze.loose())}).loose().safeParse(e.removal);return s.success?{tool:V,result:{status:s.data.status,planned:s.data.objects.reduce((o,i)=>o+i.planned,0),objects:s.data.objects}}:(t.addIssue({code:"custom",message:`its result: ${s.error.issues[0]?.message}`}),p.NEVER)});function gf(e){let t=_(V,"the answer of a replay\u2019s dry run",wv,e);return{tool:V,...t}}function ns(e){return _(V,"the answer of a replay",vv,e)}function yf(e){return _(V,"the preview of a removal",bv,e)}function wf(e){return _(V,"the outcome of a removal",Ev,e)}function Rv(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 vf(e){let t=[...e.refused!==void 0?[e.refused.message]:[],...e.refusals??[]],n=e.objects??[],r=n.reduce((f,d)=>f+d.toInsert,0),s=t.length>0?t.join(" "):e.objects===void 0?"the replay never came to say what it would create, and a run held to no count is held to nothing":r===0?"it would create nothing: every record of the checkpoint is one the org holds already, linked, or one the replay leaves out":void 0,o=e.refusals??[],i=s!==void 0?xe(s,t,[...e.refused!==void 0?[e.refused.code]:[],...e.refusalCodes?.length===o.length?e.refusalCodes:o.map(()=>"")]):[],a=e.replay,c=[...a!==void 0&&a.filesLeft.length>0?[`${a.filesLeft.length} file(s) of the checkpoint are not replayed: a checkpoint keeps no file\u2019s content`]:[],...a?.owners!==void 0&&a.owners.toRunningUser>0?[`${a.owners.toRunningUser} record(s) go to the user connected: their owner is not an active user of the org`]:[],...kf(a).map(f=>`${f.object}: ${f.records} record(s) refused before anything is written, which leave a run partial \u2014 ${_o(f)}`)],u=yv.safeParse(e.plan);return{objects:n.map(f=>({object:f.objectApiName,wouldCreate:f.toInsert})),total:r,created:r,...u.success?{apiRequests:u.data.apiRequests.estimate}:{},storageBytes:n.reduce((f,d)=>f+Sr(d.objectApiName,{rows:d.toInsert}),0),emails:Rv(e.plan),...s!==void 0?{refusal:s}:{},...i.length>0?{refusalCodes:i}:{},...c.length>0?{notes:c}:{}}}function kf(e){return(e?.refused??[]).filter(t=>t.records>0)}function rs(e){let t=(e.objects??[]).map(n=>({object:n.objectApiName,created:n.inserted,refused:n.failed,errors:n.failed>0?[`${n.failed} refused by the org`]:[]}));if(t.length===0&&e.refused!==void 0)return{objects:[],created:0,refusal:e.refused.message};for(let n of kf(e.replay)){let r=`${n.records} refused before anything is written \u2014 ${_o(n)}`,s=t.find(o=>o.object===n.object);s!==void 0?(s.refused+=n.records,s.errors.push(r)):t.push({object:n.object,created:0,refused:n.records,errors:[r]})}return{objects:t,created:t.reduce((n,r)=>n+r.created,0)}}function ss(e){let t=e.result?.purge;if(t===void 0)return!1;let n=Object.values(t.leftUnrecorded??{}).reduce((r,s)=>r+s,0);return(t.failures??[]).length===0&&n===0}var re="sandforge-seed",Sv="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 Rf(e,t,n,r){let s=$v(e,t,n,r);if("refusal"in s)return{refusals:[s.refusal]};let o=Ov(t,n,s.run);return o.refusals.length>0?{refusals:o.refusals}:{run:s.run,warnings:o.warnings}}function $v(e,t,n,r){let s=r.toISOString(),o={id:`env-${e}-${t}`,name:`${e}/${t}`,description:`The ${t} resource of the ${e} environment`,version:1,tags:["sandforge-env"],createdAt:s,updatedAt:s},i,a=[];if(n.template!==void 0){let u=Po.find(f=>f.id===n.template);if(u===void 0)return{refusal:N(["resources",t,"template"],`there is no built-in template "${n.template}": there is ${Po.map(f=>f.id).join(", ")}`)};i={...o,strategy:u.strategy,objects:structuredClone(u.objects),...u.relations!==void 0?{relations:structuredClone(u.relations)}:{}}}else i={...o,strategy:"faker",objects:(n.objects??[]).map((u,f)=>({objectApiName:u.object,recordCount:u.count,fieldRules:structuredClone(u.fields??[]),excludedFields:[],insertOrder:f,batchSize:u.batchSize??200})),...n.relations!==void 0?{relations:n.relations.flatMap((u,f)=>{let d=u.parents.from;if(d===void 0)return[bf(u)];let{childObject:l,lookupField:h,parentObject:m,distribution:g}=bf(u);return a.push({at:f,relation:{childObject:l,lookupField:h,parentObject:m,distribution:g},from:d.split(".")[0]??d,...u.parents.limit!==void 0?{limit:u.parents.limit}:{}}),[]})}:{}};let c=Object.fromEntries((n.objects??[]).filter(u=>u.recordTypes!==void 0).map(u=>[u.object,[...new Set(u.recordTypes)]]));return{run:{template:i,...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 Av(e){return e.object??e.from?.split(".")[1]??""}function bf(e){let[t="",n=""]=e.lookup.split("."),r=e.parents.existing;return{childObject:t,lookupField:n,parentObject:Av(e.parents),parents:r===void 0?{kind:"generated"}:{kind:"existing",...r.where!==void 0?{where:r.where}:{},limit:r.limit},distribution:e.distribution}}function Sf(e){return{kind:"existing",limit:e.limit??wr.maxExistingParents}}function $f(e,t){let n=[...e.template.relations??[]],r=e.draws??[],s=[];for(let o=0;o<n.length+r.length;o++){let i=r.find(c=>c.at===o),a=i!==void 0?{...i.relation,parents:t(i)}:n.shift();a!==void 0&&s.push(a)}return s}function vi(e,t,n){return(e.draws??[]).length===0?e.template:{...e.template,relations:$f(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 Sf(r)})}}var Ef=Object.keys(bu);function Ov(e,t,n){let r=["resources",e],s=vi(n,void 0,{standIns:!0}),o=cu.safeParse(s);if(!o.success)return{refusals:o.error.issues.map(u=>N(jv(r,t,u.path),u.message)),warnings:[]};let i=new _u().validate(s),a=({field:u,message:f})=>N(Cv(r,t,s,u),f),c=n.locale!==void 0&&!Ef.includes(n.locale)?[N([...r,"locale"],`the seed draws in ${Ef.join(", ")}, not ${n.locale}: name one of them, or leave locale out to draw in the org\u2019s own`)]:[];return{refusals:[...i.errors.map(a),...c],warnings:i.warnings.map(a)}}function jv(e,t,n){if(t.template!==void 0)return[...e,"template"];let[r,s,o,...i]=n;if(r==="objects"&&typeof s=="number"){let a=[...e,"objects",s];return o==="objectApiName"?[...a,"object"]:o==="recordCount"?[...a,"count"]:o==="fieldRules"?[...a,"fields",...i]:o===void 0?a:[...a,o]}if(r==="relations"&&typeof s=="number"){let a=[...e,"relations",s];return o==="childObject"||o==="lookupField"?[...a,"lookup"]:o==="parentObject"?[...a,"parents","object"]:o==="parents"?[...a,"parents","existing",...i]:o===void 0?a:[...a,o,...i]}return e}function Cv(e,t,n,r){if(t.template!==void 0)return[...e,"template"];let s=/^objects\[([^\]]+)\](?:\.fieldRules\[([^\]]+)\])?/.exec(r);if(s!==null){let i=n.objects.findIndex(u=>u.objectApiName===s[1]);if(i<0)return e;let a=s[2],c=a===void 0?-1:(n.objects[i]?.fieldRules??[]).findIndex(u=>u.fieldApiName===a);return c<0?[...e,"objects",i]:[...e,"objects",i,"fields",c]}let o=/^relations\[([^\]]+)\]/.exec(r);if(o!==null){let i=(n.relations??[]).findIndex(a=>`${a.childObject}.${a.lookupField}`===o[1]);return i<0?e:[...e,"relations",i]}return e}function Af(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 Of(e){return e.template.objects.map(t=>({object:t.objectApiName,count:t.recordCount}))}function jf(e){let{template:t}=e,n=$f(e,Sf),r=new Set(n.filter(s=>s.parents.kind==="existing").map(s=>s.childObject));for(let s=!0;s;){s=!1;for(let o of t.objects)r.has(o.objectApiName)||_c(o,n).some(i=>r.has(i))&&(r.add(o.objectApiName),s=!0)}return new Map(t.objects.filter(s=>r.has(s.objectApiName)).map(s=>[s.objectApiName,s.recordCount]))}function Cf(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 If(e){return[...Cf(e),"--json","--fail-on-partial"]}function Df(e){return[...Cf(e),"--dry-run","--json"]}function Pf(e){return[...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],...e.leaveUndeletable===!0?["--leave-undeletable"]:[]]}function Nf(e){return["--remove",I("--remove",e.summary),"--target",I("--target",e.target),...Pf(e),...ve(e),"--json"]}function Tf(e){return["--remove",I("--remove",e.summary),"--target",I("--target",e.target),"--preview",...Pf(e),...ve(e),"--json"]}var Iv=p.object({limit:p.enum(["SingleEmail","DailyWorkflowEmails"]),emails:R,verdict:p.enum(["fits","exceeds","unread"]),remaining:p.number().int().optional(),max:p.number().int().optional(),unread:p.string().optional()}),Dv=p.object({checks:p.array(Iv),refusal:p.string().optional(),unknown:p.array(p.string()).optional()}),Pv=p.object({records:R,given:R,refusal:p.string().optional()}),Nv=e=>p.object({objectApiName:p.string().min(1),recordsCreated:R,recordsFailed:R,createdIds:p.array(e),errors:p.array(p.string()),truncated:p.boolean().optional(),writtenByThePlatform:Pv.optional()}),xf=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(Nv(e)),totalRecordsCreated:R,totalRecordsFailed:R}),Lf={tool:p.literal(re),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:Dv,elapsedMs:R,interrupted:p.literal(!0).optional()},Tv=p.object({...Lf,dryRun:p.literal(!1),targetOrgId:Xe.optional(),result:xf(Xe),runFile:p.string().min(1).optional()}),xv=p.object({bytes:R,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()}),Lv=p.object({estimate:R,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()}),Fv=p.object({...Lf,dryRun:p.literal(!0),storage:xv,apiRequests:Lv,wouldBeRefused:p.array(p.string()).optional(),wouldBeRefusedCodes:p.array(p.string()).optional(),result:xf(p.string())}),Mv=p.object({tool:p.literal(re),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:R,objects:p.array(Ze),sweep:p.object({status:p.string()}).loose().optional()}),elapsedMs:R}),_v=p.object({tool:p.literal(re),action:p.literal("remove-preview"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),preview:_t,refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional(),notes:p.array(p.string()),elapsedMs:R});function Kt(e){return _(re,"the summary of a run",Tv,e)}function Ff(e){return _(re,"the summary of a dry run",Fv,e)}function Mf(e){return _(re,"the preview of a removal",_v,e)}function _f(e){return _(re,"the outcome of a removal",Mv,e)}var zf="validation";function qf(e,t){let n=e.result.objectResults,r=c=>{let u=xe(c,e.wouldBeRefused,e.wouldBeRefusedCodes);return u.length>0?{refusalCodes:u}:{}};if(e.result.status==="failure"&&n.length>0&&n.every(c=>c.objectApiName===zf)){let c=n.flatMap(f=>f.errors),u=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:u,...r(u)}}let s=e.result.objectResults.map(c=>{let u=t?.get(c.objectApiName);return u!==void 0?{object:c.objectApiName,wouldCreate:Math.max(c.recordsCreated,u),atMost:!0}:{object:c.objectApiName,wouldCreate:c.recordsCreated}}),o=e.storage.refusal??e.apiRequests.refusal??e.emails.refusal,i=o!==void 0&&o===e.storage.refusal?`${o} ${Sv}`:o,a=e.result.objectResults.flatMap(c=>c.writtenByThePlatform!==void 0?[zv(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})),...i!==void 0&&o!==void 0?{refusal:i,...r(o)}:{},...a.length>0?{notes:a}:{}}}function zv(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 os(e){let t=e.result.objectResults;if(e.result.status==="failure"&&t.length>0&&t.every(n=>n.objectApiName===zf)){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}}import{readFileSync as qv}from"node:fs";var W="sandforge-users",Uf=999999;function Kf(e){return{run:{...e.defaults!==void 0?{defaults:e.defaults}:{},users:e.users,...e.accept?.automation===!0?{acceptAutomation:!0}:{}},warnings:[]}}function ki(e){return e===void 0||e.length===0?null:[...new Set(e.map(t=>t.toLowerCase()))].sort()}function Vf(e){return{kind:"users",kindVersion:1,users:Kc(bi(e)).map(n=>({username:Uc(n.username),email:n.email??"keep",active:n.active??null,frozen:n.frozen??null,profile:n.profile??null,permissionSets:ki(n.permissionSets),permissionSetGroups:ki(n.permissionSetGroups),groups:ki(n.groups)})).sort((n,r)=>n.username<r.username?-1:n.username>r.username?1:0)}}function Wf(e){return[{object:"User",count:e.users.length}]}function bi(e){return{...e.defaults!==void 0?{defaults:e.defaults}:{},users:e.users}}function Hf(e,t){if(!Number.isInteger(t)||t<1||t>Uf)throw new Error(`${e} takes the number of a run of sandforge users, not ${t}.`);return String(t)}function Yf(e,t){return[e,"--org",I("--org",t.target),"--config",I("--config",t.configFile),...t.replacesRun!==void 0?["--replaces",Hf("--replaces",t.replacesRun)]:[],...t.acceptUserEmails===!0?["--accept-user-emails"]:[],...t.acceptAutomation===!0?["--accept-automation"]:[]]}function Jf(e){return[...Yf("plan",e),"--json"]}function Gf(e){return[...Yf("apply",e),"--yes","--json"]}function Qf(e){return["remove","--org",I("--org",e.target),"--run",Hf("--run",e.run),...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],"--yes","--json"]}var Bv=p.object({run:p.number().int().positive().max(Uf)}).loose();function Dn(e){try{let t=Bv.safeParse(JSON.parse(e));return t.success?t.data.run:void 0}catch{return}}function Xf(e){let t;try{t=qv(e,"utf8")}catch(r){throw new Error(`${e} cannot be read (${r instanceof Error?r.message:String(r)}): the run of sandforge users it names cannot be taken back from it.`)}let n=Dn(t);if(n===void 0)throw new Error(`${e} names no run of sandforge users: the run it is the summary of cannot be taken back from it.`);return n}function Zf(e){let t=_(W,"the answer of a plan",vr,e);return{tool:W,...t}}function Vt(e){return _(W,"the answer of a run",wt,e)}function Bf(e){return e.what==="permissionSet"||e.what==="permissionSetGroup"?"PermissionSetAssignment":e.what==="group"?"GroupMember":void 0}function ep(e){let t=_(W,"the outcome of a removal",kr,e),n=new Map,r=i=>{let a=n.get(i)??{deleted:0,refused:0,reasons:[]};return n.set(i,a),a},s=[];for(let i of t.users){for(let a of i.undone){let c=Bf(a);c!==void 0&&(r(c).deleted+=1)}for(let a of i.kept??[]){s.push({username:i.username,change:a.change,why:a.why});let c=Bf(a.change);if(c===void 0)continue;let u=r(c);u.refused+=1,u.reasons.push(`${i.username}: ${St(a.change)}: ${a.why}`)}}let o=[...n].map(([i,a])=>({objectApiName:i,planned:a.deleted+a.refused,deleted:a.deleted,alreadyGone:0,keptChanged:0,keptDependents:0,refused:a.refused,heldBy:[],reasons:a.reasons}));return{tool:W,result:{status:t.status,planned:o.reduce((i,a)=>i+a.planned,0),objects:o},undone:t.users.reduce((i,a)=>i+a.undone.length,0),kept:s,answer:t}}function St(e){switch(e.what){case"email":return"address asked back, awaiting its owner\u2019s confirmation";case"active":return e.to?"activated":"deactivated";case"frozen":return e.to?"frozen":"unfrozen";case"profile":return`profile ${e.to} in place of ${e.from}`;case"permissionSet":return`permission set ${e.name} ${e.to==="added"?"added":"taken back"}`;case"permissionSetGroup":return`permission set group ${e.name} ${e.to==="added"?"added":"taken back"}`;case"group":return`${e.type==="Queue"?"queue":"group"} ${e.name} `+(e.to==="added"?"joined":"left")}}function tp(e){return e.users.filter(t=>t.changes.length>0)}function np(e){let t=tp(e).length,n=e.refusals??[],r=n.length>0?n.map(i=>i.message).join(" "):void 0,s=[...new Set(n.map(i=>i.code))],o=(e.licenses??[]).filter(i=>i.toUse>0).map(i=>`${i.name}: ${i.used} of ${i.total} used, ${i.toUse} more taken by the activations and the profiles`);return{objects:[{object:"User",wouldCreate:t}],total:t,created:0,apiRequests:e.apiRequests,storageBytes:0,emails:[],emailsToPeople:e.emailsToPeople,...r!==void 0?{refusal:r}:{},...r!==void 0&&s.length>0?{refusalCodes:s}:{},...o.length>0?{notes:o}:{}}}function rp(e){let t=e.refusals??[];if(t.length>0)return{objects:[],users:0,unread:t.map(o=>o.message).join(" ")};let n=tp(e),r=e.users.length-n.length,s=n.map(o=>`${o.username} would be ${o.changes.map(St).join(", ")}`);return{objects:[{object:"User",present:r}],users:r,...s.length>0?{drift:s.join("; ")}:{}}}function sp(e){return`applied, and the org holds its ${e} user(s) as the last run left them`}function op(e,t){return`its users changed since it was applied: ${t}. Left as they are: --replace ${e} or --replace-drifted sets them up again, converging from what the last run left`}function is(e){let t=e.users.filter(a=>(a.refused??[]).length>0),n=e.users.reduce((a,c)=>a+c.created.permissionSetAssignments.length,0),r=e.users.reduce((a,c)=>a+c.created.groupMembers.length,0),s=[{object:"User",created:0,refused:t.length,errors:t.flatMap(a=>(a.refused??[]).map(c=>`${a.username}: ${St(c.change)} refused, ${c.code}: ${c.message}`))},...n>0?[{object:"PermissionSetAssignment",created:n,refused:0,errors:[]}]:[],...r>0?[{object:"GroupMember",created:r,refused:0,errors:[]}]:[]],o=e.users.some(a=>a.done.length>0),i=e.refusals??[];return{objects:s,created:n+r,...!o&&i.length>0?{refusal:i.map(a=>a.message).join(" ")}:{}}}function ip(e){return e.users.map(t=>({username:t.username,userId:t.userId}))}var ap={seed:re,forge:G,frozen:ue,mask:he,users:W,replay:V};function Uv(e){return Object.prototype.hasOwnProperty.call(ap,e)}function as(e){if(!Uv(e))throw new Error(`The state holds a resource of kind ${e}, which a later SandForge applies: this one applies seed, forge, frozen, mask, users and replay resources, and takes back nothing of another kind.`);return ap[e]}function cp(e,t,n,r,s,o={}){switch(n.kind){case"seed":{let i=Rf(e,t,n,s);return"refusals"in i?i:{run:{kind:"seed",...i.run},warnings:i.warnings}}case"forge":{let i=Md(e,t,n,r,s);return"refusals"in i?i:{run:{kind:"forge",...i.run},warnings:i.warnings}}case"frozen":{let i=cl(t,n,r);return"refusals"in i?i:{run:{kind:"frozen",...i.run},warnings:i.warnings}}case"mask":{let i=jl(t,n,o);return"refusals"in i?i:{run:{kind:"mask",...i.run},warnings:i.warnings}}case"users":{let i=Kf(n);return{run:{kind:"users",...i.run},warnings:i.warnings}}case"replay":{let i=nf(t,n);return"refusals"in i?i:{run:{kind:"replay",...i.run},warnings:i.warnings}}}}function up(e){switch(e.kind){case"seed":return Af(e.run);case"forge":return Ud(e.run,e.source.read);case"frozen":return ul(e.run);case"mask":return Cl(e.run);case"users":return Vf(e.run);case"replay":return af(e.run,e.checkpoint.read)}}function Wt(e){switch(e.kind){case"seed":return Of(e);case"forge":return _d(e);case"frozen":return[];case"mask":return Il(e);case"users":return Wf(e);case"replay":return rf(e)}}function $t(e){return e==="frozen"||e==="mask"||e==="users"||e==="replay"}function Ht(e,t){switch(e.kind){case"seed":return vi(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 dl(e.run,{sasDir:t.sasDir,datasetDir:e.dataset.dir})}case"mask":return Dl(e.run);case"users":return bi(e.run);case"replay":return{}}}function dp(e,t){switch(e.kind){case"seed":{let n=e.run.seed??t.seed;return{script:re,args:Df({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:G,args:Vd({...hp(e),target:t.target,templateFile:t.templateFile,...t.rootsPlanFile!==void 0?{rootsPlanFile:t.rootsPlanFile}:{},maxTotal:e.run.maxTotal??Fd})};case"frozen":return{script:ue,args:fl({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:he,args:Nl({target:t.target,run:e.run,rulesFile:t.templateFile,store:pp(e,t)})};case"users":return{script:W,args:Jf(lp(e,t))};case"replay":return{script:V,args:uf({...fp(e,t),again:t.replace===!0})}}}function lp(e,t){return{target:t.target,configFile:t.templateFile,...t.replacesRun!==void 0?{replacesRun:t.replacesRun}:{},...t.acceptUserEmails===!0?{acceptUserEmails:!0}:{},...t.acceptAutomation===!0||e.run.acceptAutomation===!0?{acceptAutomation:!0}:{}}}function fp(e,t){if(t.checkpointStore===void 0)throw new Error(`${e.name} is given no store of checkpoints to replay from: plan again.`);return{name:e.name,run:e.run,place:e.checkpoint,target:t.target,store:t.checkpointStore,again:!1,...t.acceptAutomation===!0?{acceptAutomation:!0}:{}}}function pp(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 hp(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 mp(e,t){switch(e){case"seed":return Ff(t);case"forge":return Xd(t);case"frozen":return wl(t);case"mask":return Ll(t);case"users":return Zf(t);case"replay":return gf(t)}}function Ei(e){return e.kind==="seed"?jf(e.run):void 0}function gp(e,t){return e.kind==="forge"&&t.tool===G?Qd(t,e.run.template):void 0}function Yt(e,t){switch(e.tool){case re:return qf(e,t);case G:return nl(e);case ue:return El(e);case he:return _l(e);case W:return np(e);case V:return vf(e)}}function At(e,t){switch(e.kind){case"seed":return{script:re,args:If({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:G,args:Wd({...hp(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:ue,args:pl({configFile:t.templateFile,target:t.target,reload:t.replace===!0,acceptAutomation:t.acceptAutomation===!0,maxTotal:t.maxTotal})}}case"mask":return{script:he,args:Tl({target:t.target,run:e.run,rulesFile:t.templateFile,store:pp(e,t)})};case"users":return{script:W,args:Gf(lp(e,t))};case"replay":{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:V,args:df({...fp(e,t),again:t.replace===!0,maxRecords:t.maxTotal})}}}}function cs(e){throw new Error(`${De(e)} takes no run back: a masking is never undone, and its destroy deletes its store`)}function yp(e){if(e.checkpointStore===void 0)throw new Error("a replay is given no store of checkpoints to take it back from: plan again.");return{replayed:ts(e.subject),target:e.target,store:e.checkpointStore,includeChanged:e.includeChanged,acceptAutomation:e.acceptAutomation,...e.sweep===!0?{sweep:!0}:{}}}function wp(e){throw new Error(`${De(e)} previews no removal: its plan reads what the org holds of its users`)}function vp(e,t){let n=as(e),r=t.sweep===!0?{sweep:!0}:{},s={target:t.target,summary:t.subject,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,...r};switch(n){case re:return{script:n,args:Tf(s)};case G:return{script:n,args:Jd(s)};case ue:return{script:n,args:gl({configFile:t.subject,target:t.target,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,...r})};case he:return cs(n);case W:return wp(n);case V:return{script:n,args:pf(yp(t))}}}function kp(e,t){let n=as(e);switch(n){case re:return Mf(t);case G:return el(t);case ue:return kl(t);case he:return cs(n);case W:return wp(n);case V:return yf(t)}}function bp(e,t){if(e==="mask"||e==="users")return[];let n=[...t].reverse().filter(r=>r.takenBack!==!0);return e==="frozen"||e==="replay"?n.slice(0,1):n}function Ep(e,t){if(e==="frozen")return{script:ue,args:hl({configFile:t.subject,target:t.target})}}function Rp(e){return Sl(vl(e))}function Sp(e,t){let n=as(e),r={target:t.target,summary:t.subject,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,sweep:t.sweep};switch(n){case re:return{script:n,args:Nf(r)};case G:return{script:n,args:Yd(r)};case ue:return{script:n,args:ml({configFile:t.subject,target:t.target,includeChanged:t.includeChanged,sweep:t.sweep,acceptAutomation:t.acceptAutomation})};case he:return cs(n);case W:return{script:n,args:Qf({target:t.target,run:Xf(t.subject),includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation})};case V:return{script:n,args:ff(yp(t))}}}function $p(e,t){let n=as(e);switch(n){case re:return _f(t);case G:return Zd(t);case ue:return bl(t);case he:return cs(n);case W:return ep(t);case V:return wf(t)}}function Ri(e){return e?.result.objects??[]}function Ap(e,t){return e.kind==="mask"?Kl(e.name,t):e.kind==="forge"?qd(e.run,e.source):[]}var ht=zy(mg());import{isAbsolute as yS,resolve as cr}from"node:path";function oc(e){return`${vn(e.path)}: ${e.message}`}var wS=100;function yg(e){let t=e.startsWith("\uFEFF")?e.slice(1):e,n=(0,ht.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=sc(n.contents,[]);if(s!==void 0)return{refusal:`${vn(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:wS})}}catch(o){return{refusal:`The file does not read as YAML 1.2: ${o instanceof Error?o.message:String(o)}`}}}function sc(e,t){if((0,ht.isMap)(e)){let n=new Set;for(let r of e.items){let s=(0,ht.isScalar)(r.key)?String(r.key.value):String(r.key);if(n.has(s))return{path:t,key:s};n.add(s);let o=sc(r.value,[...t,s]);if(o)return o}}else if((0,ht.isSeq)(e))for(let[n,r]of e.items.entries()){let s=sc(r,[...t,n]);if(s)return s}}function vS(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 ur(e,t,n={}){let r=[...br(e).map(({path:l,secret:h})=>N(l,`a key shaped like a secret (${h}). The file holds no secret: ${vS(h)}.`)),...Yc(e).filter(({path:l})=>!Vc(l)).map(({path:l})=>N(l,`{ env } stands in ${Io.slice(0,-1).join(", ")} and ${Io.at(-1)??""} 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=Hc.safeParse(e);if(!s.success)return{refusals:s.error.issues.map(l=>{let h=l.path,m=l.code==="invalid_key"?l.issues.map(g=>g.message):[];return N(h,m.join("; ")||l.message)})};let o=s.data,i=bS(o);if("refusals"in i)return i;let a=Ol(o.masking);if("refusals"in a)return a;let c=[],u=[...kS(o)],f={};for(let[l,h]of Object.entries(o.resources)){let m=cp(o.name,l,h,cr(t),n.now??new Date,a.sets);if("refusals"in m){c.push(...m.refusals);continue}u.push(...m.warnings),f[l]=m.run}if(c.push(...ES(f)),c.length>0)return{refusals:c};let d=[];for(let[l,{alias:h}]of Object.entries(o.orgs))typeof h!="string"&&d.push({name:h.env,path:["orgs",l,"alias"],role:l});for(let[l,h]of Object.entries(o.resources)){h.kind==="frozen"&&typeof h.dataset.path!="string"&&d.push({name:h.dataset.path.env,path:["resources",l,"dataset","path"],resource:l});let m=h.kind==="replay"?h.checkpoint.file:void 0;m!==void 0&&typeof m!="string"&&d.push({name:m.env,path:["resources",l,"checkpoint","file"],resource:l})}return{checked:{file:o,folder:cr(t),order:i.order,runs:f,variables:d,warnings:u}}}function kS(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=>N(["masking",n],"no mask resource names this rule set: nothing masks with it"))}function wg(e,t){return e.variables.filter(n=>(t[n.name]??"").trim()==="")}function vg(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 ic(e,t){return[...new Set([...t.kind==="users"?[]:t.dependsOn??[],...vg(e,t).map(({from:n})=>n)])]}function bS(e){let t=Object.keys(e.resources),n=[],r=new Map;for(let[u,f]of Object.entries(e.resources)){let d=[];for(let{from:h,path:m}of vg(u,f))h===u?n.push(N(m,`a relation draws its parents from the records another resource created: ${u}'s own are drawn by their object alone, without from`)):h in e.resources?d.includes(h)||d.push(h):n.push(N(m,`"${h}" is no resource of this file: name one of ${t.join(", ")}`));(f.kind==="users"?[]:f.dependsOn??[]).forEach((h,m)=>{let g=["resources",u,"dependsOn",m];h===u?n.push(N(g,`a resource does not depend on itself: take ${u} out of its dependsOn`)):h in e.resources?d.includes(h)||d.push(h):n.push(N(g,`"${h}" is no resource of this file: name one of ${t.join(", ")}`))}),r.set(u,d)}if(n.length>0)return{refusals:n};let s=RS(t,r);if(s!==void 0)return{refusals:[N(["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 o=t.filter(u=>e.resources[u]?.kind==="users"),i=[...o,...t.filter(u=>!o.includes(u))],a=[],c=new Set;for(;a.length<t.length;){let u=i.find(f=>!c.has(f)&&(r.get(f)??[]).every(d=>c.has(d)));if(u===void 0)break;a.push(u),c.add(u)}return{order:a}}function ES(e){let t=[];for(let[n,r]of Object.entries(e))if(r.kind==="seed")for(let s of r.draws??[]){let o=e[s.from];if(o?.kind==="mask"){t.push(N(["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, a frozen or a replay resource created`));continue}if(o?.kind!=="seed")continue;let i=Wt(o).map(({object:a})=>a);i.includes(s.relation.parentObject)||t.push(N(["resources",n,"relations",s.at,"parents","from"],`${s.from} writes no ${s.relation.parentObject} records: it writes ${i.join(", ")||"none"}`))}return t}function RS(e,t){let n=new Set,r=[],s=o=>{let i=r.indexOf(o);if(i>=0)return[...r.slice(i),o];if(!n.has(o)){r.push(o);for(let a of t.get(o)??[]){let c=s(a);if(c!==void 0)return c}r.pop(),n.add(o)}};for(let o of e){let i=s(o);if(i!==void 0)return i}}function ac(e,t){return ti(Mt({...up(e),dependsOn:t}))}var gg=/^[^-\s][^\s]{0,199}$/;function cc(e,t,n={}){let r=Object.keys(e.file.orgs),s=[],o=n.aliases??{};for(let[l,h]of Object.entries(o))r.includes(l)?gg.test(h)||s.push(N(["orgs",l,"alias"],`--alias ${l}= gives no alias: one holds no space and does not start with "-"`)):s.push(N(["orgs"],`--alias names the role ${l}, which the file's orgs do not declare: `+(r.length>0?`its roles are ${r.join(", ")}`:"it declares none")));let i={};for(let[l,{alias:h}]of Object.entries(e.file.orgs)){let m=o[l];if(m!==void 0){i[l]=m;continue}if(typeof h=="string"){i[l]=h;continue}let g=(t[h.env]??"").trim();g===""?s.push(N(["orgs",l,"alias"],`the variable ${h.env} is not set: set it in the job's environment to the alias of the ${l} org, or give --alias ${l}=<alias>`)):gg.test(g)?i[l]=g:s.push(N(["orgs",l,"alias"],`the variable ${h.env} holds no alias: one holds no space and does not start with "-"`))}let a={};for(let[l,h]of Object.entries(e.file.resources)){if(h.kind!=="frozen")continue;let m=SS(l,h.dataset.path,t,e.folder);"refusal"in m?s.push(m.refusal):a[l]=m.dir}let c={};for(let[l,h]of Object.entries(e.file.resources)){if(h.kind!=="replay"||h.checkpoint.file===void 0)continue;let m=sf(l,h.checkpoint.file,t);"refusal"in m?s.push(m.refusal):c[l]=m.file}if(s.length>0)return{refusals:s};let u={},f=[];for(let l of e.order){let h=e.runs[l],m=e.file.resources[l];if(h===void 0||m===void 0)continue;let g=ic(l,m),w;if(h.kind==="seed"){let{kind:y,...v}=h;w={name:l,kind:y,dependsOn:g,fingerprint:"",run:v}}else if(h.kind==="mask"){let{kind:y,...v}=h;w={name:l,kind:y,dependsOn:g,fingerprint:"",run:v}}else if(h.kind==="users"){let{kind:y,...v}=h;w={name:l,kind:y,dependsOn:g,fingerprint:"",run:v}}else if(h.kind==="replay"){let{kind:y,...v}=h,b=n.checkpoints?.[l],k=v.from!==void 0?i[v.from]:void 0,E=c[l];w={name:l,kind:y,dependsOn:g,fingerprint:"",run:v,checkpoint:{...k!==void 0?{from:k}:{},...E!==void 0?{file:E}:{},...b!==void 0?{read:b}:{}}}}else if(h.kind==="frozen"){let{kind:y,...v}=h,b=n.datasets?.[l];w={name:l,kind:y,dependsOn:g,fingerprint:"",run:v,dataset:{dir:a[l]??"",...b!==void 0?{read:b}:{}}}}else{let{kind:y,...v}=h,b=n.sources?.[l];w={name:l,kind:y,dependsOn:g,fingerprint:"",run:v,source:{role:v.source,alias:i[v.source]??"",...b!==void 0?{read:b}:{}}}}w.fingerprint=ac(w,Object.fromEntries(g.map(y=>[y,u[y]]))),u[l]=w.fingerprint,f.push(w)}let d=ti(Mt({...e.file,orgs:Object.fromEntries(Object.entries(i).map(([l,h])=>[l,{alias:h}]))}));return{resolved:{checked:e,orgs:i,resources:f,digest:d}}}function SS(e,t,n,r){let s=["resources",e,"dataset","path"],o;if(typeof t=="string")o=t;else{if(o=(n[t.env]??"").trim(),o==="")return{refusal:N(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(!yS(o))return{refusal:N(s,`the variable ${t.env} holds ${o}, which is not a path from the root: give the folder of the dataset from the root`)}}let i;try{i=jr(r)}catch{i=void 0}return i!==void 0&&new Ue(i).isInsideRepo(cr(o))?{refusal:N(s,`the dataset of ${e}, ${cr(o)}, is inside the repository ${i} 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:cr(o)}}function kg(e,t,n,r={}){let s=ur(e,t,r.now?{now:r.now}:{});return"refusals"in s?s:cc(s.checked,n,{...r.aliases?{aliases:r.aliases}:{},...r.sources?{sources:r.sources}:{},...r.datasets?{datasets:r.datasets}:{},...r.checkpoints?{checkpoints:r.checkpoints}:{}})}var Eg="USERS_EMAILS_NOT_ACCEPTED";function Rg(e){if(e.tool!==W)return e;let t=e,n=(t.refusals??[]).filter(s=>s.code!==Eg),r={...t};return delete r.refusals,n.length>0?{...r,refusals:n}:r}var Sg=new Set(["create","replace","delete"]),Ae=new Set(["create","replace"]);function fc(e){return Sg.has(e.action)}function _e(e){return Object.entries(e?.resources??{}).filter(([,t])=>t.status!=="destroyed")}function pc(e,t){let n=[],r=new Set,s=new Set(e);for(;n.length<e.length;){let o=e.find(i=>!r.has(i)&&t(i).every(a=>!s.has(a)||r.has(a)||a===i))??e.find(i=>!r.has(i));if(o===void 0)break;n.push(o),r.add(o)}return n}function mt(e,t){let n=e?.resources??{},r=pc(t,o=>n[o]?.dependsOn??[]).reverse(),s=o=>n[o]?.kind==="users";return[...r.filter(o=>!s(o)),...r.filter(s)]}function $S(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 uc(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 o of s.objects){let i=t.objects.get(o.objectApiName)??{present:0,gone:0,changed:0,unread:0};i.present+=o.toDelete+o.keptChanged+o.undeletable,i.gone+=o.alreadyGone+o.notVisible,i.changed+=o.changedSince,i.unread+=o.unread,t.objects.set(o.objectApiName,i);for(let[a,c]of Object.entries(o.changedBy)){let u=s.userNames[a]??a;t.changedBy.set(u,(t.changedBy.get(u)??0)+c)}}for(let o of n.preview.refusals)t.refusals.includes(o)||t.refusals.push(o);if(bg(t.codes,n.preview.refusals,n.preview.refusalCodes),"removalAlone"in n.preview){t.removalAlone.push(...n.preview.removalAlone);let o="removalAloneCodes"in n.preview?n.preview.removalAloneCodes:void 0;bg(t.codes,n.preview.removalAlone,o)}}return t}function bg(e,t,n){n?.length===t.length&&t.forEach((r,s)=>e.set(r,n[s]??""))}function hc(e){return[...e.refusals,...e.removalAlone]}function dc(e,t=hc(e)){return[...new Set(t.flatMap(n=>e.codes.get(n)||[]))]}function co(e){return e.length>0?{refusalCodes:[...new Set(e)]}:{}}function lc(e){return[...e.objects].map(([t,n])=>({object:t,present:n.present,gone:n.gone,changed:n.changed}))}function AS(e){let t=[...e.objects].flatMap(([s,o])=>{let i=[o.gone>0?`${o.gone} gone`:"",o.changed>0?`${o.changed} changed`:"",o.unread>0?`${o.unread} not read`:""].filter(Boolean);return i.length>0?[`${s} ${i.join(", ")}`]:[]});if(e.verified.length>0&&t.push(`its verification: ${e.verified.join("; ")}`),t.length===0)return;let n=[...e.changedBy].sort((s,o)=>o[1]-s[1]),r=n.length>0?` (last changed by ${n.map(([s,o])=>`${s} ${o}`).join(", ")})`:"";return`${t.join("; ")}${r}`}var $g="taken back: the assignments and memberships the environment created deleted by id, each user put back as it was before; an address asked back stays, and no user is deleted",OS="its state was recovered from its run files, which do not say what it was applied from",jS={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"},CS={applying:"its last run was stopped part way: a run converges from what it left",partial:"its last run was partial: the org refused changes to its users",failed:"its last run failed",destroying:"a removal of it was stopped part way"};function IS(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==="replay"){let n=e.checkpoint.read;return n===void 0?"its checkpoint was not resolved: 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 mc(e){let{resolved:t,state:n,previews:r}=e,s=r===void 0,o=new Set(e.replace??[]),i=new Map(_e(n)),a=new Set(t.resources.map(f=>f.name)),c=new Map;for(let f of t.resources){let d=i.get(f.name),l=IS(f),h=f.kind;if(d===void 0){c.set(f.name,{resource:f.name,kind:h,action:"create",why:n?.resources[f.name]?.status==="destroyed"?"taken back by an earlier destroy: applied again":"not applied to this org yet",objects:[],...l!==void 0?{refusal:l}:{}});continue}let m=uc(r?.[f.name]??[]),g=[],w=ac(f,Object.fromEntries(f.dependsOn.map(A=>[A,n?.resources[A]?.fingerprint])));d.recovered===!0?g.push(OS):d.fingerprint!==f.fingerprint&&d.fingerprint!==w&&g.push("what it writes changed in the file since it was applied");let y=(h==="mask"?Wl:h==="users"?CS:jS)[d.status];y!==void 0&&g.push(y);let v=f.dependsOn.filter(A=>{let P=c.get(A);return P!==void 0&&Ae.has(P.action)&&P.kind!=="mask"});if(v.length>0&&g.push(`the resources it depends on run again, with new records: ${v.join(", ")}`),o.has(f.name)&&g.push("--replace asks it"),h==="mask"){c.set(f.name,DS(f.name,d,g,e,s));continue}if(h==="users"){c.set(f.name,PS(f.name,g,e,s));continue}let b=s?void 0:AS(m),k=b!==void 0&&$S(m,e.drift),E=k?void 0:b;g.length===0&&E!==void 0&&e.replaceDrifted===!0&&g.push(`its records drifted (${E}), and --replace-drifted asks it`);let S=lc(m),$=l??(m.refusals.length>0?`a removal of its runs would be refused now: ${m.refusals.join(" ")}`:m.failed.length>0?`what the org holds of it could not be read (${m.failed.join("; ")}): plan again`:void 0),j=l===void 0&&m.refusals.length>0?dc(m,m.refusals):[];if(g.length>0)c.set(f.name,{resource:f.name,kind:h,action:"replace",why:`replaced: ${g.join("; ")}`,objects:S,...$!==void 0?{refusal:$,...co(j)}:{}});else if(s)c.set(f.name,{resource:f.name,kind:h,action:"keep",why:"applied from the same file; what the org holds of it was not read (--quick)",objects:S,...l!==void 0?{refusal:l}:{}});else if(l!==void 0||m.failed.length>0)c.set(f.name,{resource:f.name,kind:h,action:"keep",why:"applied from the same file",objects:S,refusal:l??`what the org holds of it could not be read (${m.failed.join("; ")}): plan again`});else if(E!==void 0)c.set(f.name,{resource:f.name,kind:h,action:"drifted",why:`its records changed since it was applied: ${E}. Left as they are: --replace ${f.name} or --replace-drifted replaces it`,objects:S});else{let A=S.reduce((D,x)=>D+(x.present??0),0),P=S.reduce((D,x)=>D+(x.changed??0),0);c.set(f.name,{resource:f.name,kind:h,action:"keep",why:k?`applied, and the org holds its ${A} record(s) as the checkpoint taken after the apply holds them: ${P} written since hold their values again, as a reset gives them back`:`applied, and the org holds its ${A} record(s) as written`,objects:S})}}return[...mt(n,[...i.keys()].filter(f=>!a.has(f))).map(f=>{let d=i.get(f);if(d?.kind==="mask")return{resource:f,kind:"mask",action:"delete",why:gi("apply",f,d,gc(e,f)),objects:Ag(d)};let l=uc(r?.[f]??[]),h=hc(l),m=h.length>0?`a removal of its runs would be refused now: ${h.join(" ")}`:l.failed.length>0?`what the org holds of it could not be read (${l.failed.join("; ")}): plan again`:void 0;return{resource:f,kind:i.get(f)?.kind??"seed",action:"delete",why:d?.kind==="users"?`in the state, gone from the file: ${$g}`:"in the state, gone from the file: its records are taken back",objects:lc(l),...m!==void 0?{refusal:m,...co(h.length>0?dc(l):[])}:{}}}),...t.resources.flatMap(f=>c.get(f.name)??[])]}function DS(e,t,n,r,s){let o=(d,l,h=[],m)=>({resource:e,kind:"mask",action:d,why:l,objects:h,...m!==void 0?{refusal:m}:{}});if(n.length>0)return o("replace",`replaced: ${n.join("; ")}; ${mi(t)}`);if(s)return o("keep","applied from the same file; what the org holds of it was not read (--quick)");if(r.dryRuns===void 0)return o("keep","applied from the same file");let i=r.dryRuns[e];if(i===void 0)return o("keep","applied from the same file",[],"it was not dry-run: plan again");if("failed"in i||i.answer.tool!==he){let d="failed"in i?i.failed:`${De(i.answer.tool)} answered its dry run`;return o("keep","applied from the same file",[],`what the org holds of it could not be read (its dry run: ${d}): plan again`)}let a=r.resolved.resources.map(d=>d.name),c=r.resolved.resources.find(d=>d.name===e),u=c?.kind==="mask"?c.run.where:void 0,f=Bl(t,i.answer,r.maskCreatedAfter?.[e]??hi(e,r.state,a,u));return f.unread!==void 0?o("keep","applied from the same file",f.objects,`what the org holds of it could not be read: ${f.unread}`):f.drift===void 0?o("keep",Hl(f.masked,f.theirs),f.objects):r.replaceDrifted===!0?o("replace",`replaced: its condition selects other records than it masked (${f.drift}), and --replace-drifted asks it; ${mi(t)}`,f.objects):o("drifted",Yl(e,f.drift),f.objects)}function PS(e,t,n,r){let s=(u,f,d=[],l)=>({resource:e,kind:"users",action:u,why:f,objects:d,...l!==void 0?{refusal:l}:{}}),o=n.usersUnknown?.[e],i=o!==void 0?[...t,o]:t;if(t.length>0)return s("replace",`replaced: ${i.join("; ")}`);if(r)return s("keep","applied from the same file; no word on its users (--quick)");if(n.dryRuns===void 0)return s("keep","applied from the same file");let a=n.dryRuns[e];if(a===void 0)return s("keep","applied from the same file",[],"it was not dry-run: plan again");if("failed"in a||a.answer.tool!==W){let u="failed"in a?a.failed:`${De(a.answer.tool)} answered its plan`;return s("keep","applied from the same file",[],`what the org holds of its users could not be read (its plan: ${u}): plan again`)}let c=rp(Rg(a.answer));return c.unread!==void 0?s("keep","applied from the same file",c.objects,`what the org holds of its users could not be read: ${c.unread}`):c.drift===void 0?s("keep",sp(c.users),c.objects):n.replaceDrifted===!0?s("replace",`replaced: its users changed since it was applied (${c.drift}), and --replace-drifted asks it; a run converges from what the last one left`,c.objects):s("drifted",op(e,c.drift),c.objects)}function gc(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 Ag(e){return(e.runs.at(-1)?.objects??[]).map(t=>({object:t.objectApiName,present:t.masked??0}))}function NS(e,t){let n=new Set(t.filter(o=>Ae.has(o.action)).map(o=>o.resource)),r=new Set(t.filter(o=>Ae.has(o.action)&&o.kind!=="mask").map(o=>o.resource)),s=new Map;for(let o of e.resources){if(!n.has(o.name))continue;let i=o.dependsOn.filter(a=>r.has(a));i.length>0&&s.set(o.name,i)}return s}function TS(e,t){let n=new Map(e.resources.map(o=>[o.name,o])),r=new Set,s=[...n.get(t)?.dependsOn??[]];for(;s.length>0;){let o=s.pop()??"";r.has(o)||o===t||(r.add(o),s.push(...n.get(o)?.dependsOn??[]))}return e.resources.filter(o=>o.kind==="replay"&&r.has(o.name)).map(o=>o.name)}function xS(e,t){if(t.kind!=="seed")return[];let n=TS(e,t.name);if(n.length===0)return[];let r=n.length===1;return[`it runs after the ${r?"replay":"replays"} ${n.join(", ")}: what it writes is added to the records the ${r?"replay puts":"replays put"} back from ${r?"the checkpoint":"their checkpoints"}, never in their place; leave it out of the file if the ${r?"checkpoint already holds":"checkpoints already hold"} the data it would seed`]}function LS(e,t){let n=e.map(r=>({...r}));for(let r of t.objects){let s={wouldCreate:r.wouldCreate,...r.atMost===!0?{atMost:!0}:{}},o=n.find(i=>i.object===r.object);o?Object.assign(o,s):n.push({object:r.object,...s})}return n}function FS(e,t,n,r){let s=e.resources.find(c=>c.name===t),o=r&&s!==void 0?Ei(s):void 0,i=Yt(Rg(n),o),a=s!==void 0?gp(s,n):void 0;return{count:a!==void 0&&i.refusal===void 0?{...i,refusal:a}:i}}function MS(e,t){let n=e.resources.find(r=>r.name===t);return n!==void 0&&(Ei(n)?.size??0)>0}function _S(e,t,n){let r=e.resources.find(o=>o.name===t);if(r?.kind!=="seed")return[];let s=new Set((r.run.draws??[]).map(o=>o.from));return n.filter(o=>s.has(o))}function uo(e){return e!==void 0&&"answer"in e?Yt(e.answer).total:void 0}function zS(e,t){let n=[],{apiRequests:r,storage:s,emails:o}=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 ${vt(s.bytes/1048576)} MB of data storage, and ${t} has ${vt(s.left/1048576)} MB left: the org would refuse records part way. Write fewer records, or free storage first.`);for(let i of o)i.left!==void 0&&i.emails>i.left&&n.push(`The resources the plan writes make ${t} send ${i.emails} ${i.limit} emails, and it has ${i.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 qS(e,t,n,r,s,o=!1){let i=s.estimate,a=0,c=new Map,u=[...s.notCounted],f;for(let m of e){if((m.action==="delete"||m.action==="replace")&&m.kind!=="mask"&&!(m.action==="replace"&&m.kind==="users")&&u.push(`the removal of the runs of ${m.resource}`),!Ae.has(m.action))continue;m.kind==="users"&&(f??=0);let g=t?.[m.resource];if(g===void 0||"failed"in g){u.push(`the run of ${m.resource}, not dry-run`);continue}let w=r.get(m.resource);w!==void 0&&m.kind!=="mask"&&u.push(`what ${m.resource} draws from the records ${w.join(", ")} writes first`);let y=Yt(g.answer);y.apiRequests===void 0?u.push(`the requests of the run of ${m.resource}, which its script does not estimate`):i+=y.apiRequests,a+=y.storageBytes;for(let{limit:v,emails:b}of y.emails)c.set(v,(c.get(v)??0)+b);y.emailsToPeople!==void 0&&(f=(f??0)+y.emailsToPeople)}let d=n?.apiRequests,l=n?.storage,h=n?.emails;return{apiRequests:{estimate:i,...d!==void 0&&!("unread"in d)?{leftToday:d.remaining}:{},partial:u.length>0,...u.length>0?{notCounted:u}:{},...d!==void 0&&"unread"in d?{unread:d.unread}:{},...n===void 0?{unread:"not read: --quick"}:{}},storage:{bytes:a,...l!==void 0&&!("unread"in l)?{left:Math.floor(l.remainingMB*1048576)}:{},...l!==void 0&&"unread"in l?{unread:l.unread}:{},...n===void 0?{unread:"not read: --quick"}:{}},emails:[...c].map(([m,g])=>{let w=h!==void 0&&!("unread"in h)?h[m]?.remaining:void 0;return{limit:m,emails:g,...w!==void 0?{left:w}:{}}}),...f!==void 0?{emailsToPeople:{count:f,accepted:o}}:{}}}function BS(e,t){let n=e.emailsToPeople;return n===void 0||n.count===0||n.accepted?void 0:`${t.flatMap(s=>{let o=s.gates?.emailsToPeople??0;return s.kind!=="users"||!Ae.has(s.action)||o===0?[]:[`${s.resource} has Salesforce email ${o} ${o===1?"person":"people"} (the confirmation of ${o===1?"an address":`${o} addresses`} asked back)`]}).join(", ")}, which only the line accepts: --accept-user-emails. Nothing was written.`}function yc(e){let t=e.previews===void 0,n=mc(e),r=NS(e.resolved,n),s=n.map(y=>{let v=y.objects,b,k=y.refusal,E=y.refusal!==void 0?y.refusalCodes??[]:[],S=Ae.has(y.action)?e.dryRuns?.[y.resource]:void 0,$=r.get(y.resource),j=$!==void 0&&MS(e.resolved,y.resource),A=Ae.has(y.action)?e.draws?.[y.resource]:void 0;A!==void 0&&A.refusals.length>0&&(k??=A.refusals.join(" "));let P=[],D=e.dryRuns?.[y.resource],x=y.kind==="users"&&D!==void 0&&"answer"in D&&D.answer.tool===W?D.answer.users:void 0;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 X=FS(e.resolved,y.resource,S.answer,$!==void 0);v=LS(v,X.count),b={...X.count.apiRequests!==void 0?{apiRequests:X.count.apiRequests}:{},storageBytes:X.count.storageBytes,emails:X.count.emails,...X.count.emailsToPeople!==void 0?{emailsToPeople:X.count.emailsToPeople}:{}};let Ce=X.count.refusal;Ce!==void 0&&k===void 0&&(k=`its own dry run says a real run would be refused: ${Ce}`,E=X.count.refusalCodes??[]),P=X.count.notes??[]}else Ae.has(y.action)&&!t&&(k??="it was not dry-run: plan again");let J=$!==void 0?_S(e.resolved,y.resource,$):[],U=$!==void 0&&S!==void 0&&y.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&&j?J.length>0?`; it draws its parents from the records ${J.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`:"",O=`${y.why}${U}${P.length>0?`; ${P.join("; ")}`:""}`,F=e.resolved.resources.find(X=>X.name===y.resource),ae=F!==void 0&&Ae.has(y.action)?[...Ap(F,gc(e,y.resource)),...xS(e.resolved,F)]:[];return{resource:y.resource,kind:y.kind,action:k!==void 0?"blocked":y.action,why:O,objects:v,...A!==void 0&&A.draws.length>0?{draws:A.draws}:{},...b!==void 0?{gates:b}:{},...k!==void 0?{refusal:k,...co(E)}:{},...ae.length>0?{notes:ae}:{},...x!==void 0?{users:x}:{}}}),o=e.resolved.checked.file,i=wd(Br(o,e.state,n.some(y=>Sg.has(y.action))),t?void 0:e.checkpointEstimate??{unread:"not estimated"},s.filter(y=>Ae.has(y.action)&&y.kind!=="mask").flatMap(y=>y.objects).reduce((y,v)=>y+(v.wouldCreate??0),0)),a=qS(n,e.dryRuns,e.budget,r,kd(i),e.acceptUserEmails===!0),c=e.org.alias??e.org.organizationId,u=zS(a,c);if(u.length>0)for(let y of s)fc(y)&&(y.refusal=u.join(" "),y.action="blocked");let f=s.filter(y=>y.action==="blocked"),d=BS(a,s),l=e.refusal??(u.length>0?`${u.join(" ")} Nothing was written.`:f.length>0?`${f.length===1?"A resource is":`${f.length} resources are`} blocked, and the apply refuses before its first write: ${f.map(y=>`${y.resource} (${y.refusal??y.why})`).join("; ")}`:void 0)??d??vd(i),h=e.refusal!==void 0?[...e.refusalCodes??[]]:u.length>0?[]:f.length>0?f.flatMap(y=>y.refusalCodes??[]):d!==void 0?[Eg]:i.flatMap(y=>y.refusal!==void 0?[y.refusal.code]:[]),m=[...e.warnings??[],...gd(o,e.state)],g=y=>s.filter(v=>v.action===y).length,w=e.state;return{env:e.resolved.checked.file.name,org:e.org,state:w!==void 0?{found:!0,serial:w.serial}:{found:!1,...e.refreshed!==void 0?{refreshed:e.refreshed}:{}},actions:s,totals:{create:g("create"),keep:g("keep"),replace:g("replace"),delete:g("delete"),drifted:g("drifted"),blocked:g("blocked")},gates:a,...i.length>0?{checkpoints:i}:{},...e.drift!==void 0?{drift:e.drift}:{},...l!==void 0?{refusal:l,...co(h)}:{},...t?{quick:!0}:{},...m.length>0?{warnings:m}:{}}}function Og(e){let n=mt(e.state,_e(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:gi("destroy",a,c,gc(e,a)),objects:Ag(c)};let u=uc(e.previews?.[a]??[]),f=hc(u),d=f.length>0?`a removal of its runs would be refused now: ${f.join(" ")}`:u.failed.length>0?`what the org holds of it could not be read (${u.failed.join("; ")}): run destroy again`:void 0,l=f.length>0?dc(u):[];return{resource:a,kind:c?.kind??"seed",action:d!==void 0?"blocked":"delete",why:c?.kind==="users"?`${$g}, after every other resource`:"taken back by destroy, into the recycle bin",objects:lc(u),...d!==void 0?{refusal:d}:{},...l.length>0?{refusalCodes:l}:{}}}),r=n.filter(a=>a.action==="blocked"),s=[...new Set(r.flatMap(a=>a.refusalCodes??[]))],o=n.filter(a=>a.kind!=="mask").map(a=>`the removal of the runs of ${a.resource}`),i=e.state;return{env:e.resolved.checked.file.name,org:e.org,state:i!==void 0?{found:!0,serial:i.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:o.length>0,...o.length>0?{notCounted:o}:{}},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 wc(e){return e.actions.some(t=>t.action!=="keep"&&t.action!=="drifted")}function jg(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 vc(e){let t=e.kind==="mask",n=e.kind==="users";return e.objects.map(r=>{let s=[r.wouldCreate!==void 0?`${r.atMost===!0?"at most ":""}${r.wouldCreate} `+(t?"to mask":n?"to set up":"to write"):"",r.present!==void 0&&r.present>0?`${r.present} ${t?"masked":n?"set up":"in the org"}`:"",(r.gone??0)>0?`${r.gone} gone`:"",(r.changed??0)>0?`${r.changed} changed`:""].filter(Boolean);return s.length>0?`${r.object} ${s.join(", ")}`:""}).filter(Boolean).join("; ")}var US={apply:"an apply now",destroy:"a destroy now"};function KS(e){if(e.kind!=="users"||!Ae.has(e.action)||e.users===void 0)return[];let t=e.users.map(s=>` ${s.username}: `+(s.changes.length>0?s.changes.map(St).join(", "):"as the file says already: nothing to do")),n=e.users.filter(s=>(s.emailsToPeople??0)>0),r=e.gates?.emailsToPeople??0;if(r>0){let s=n.map(o=>o.username).join(", ");t.push(r===1?` Salesforce sends 1 email to a person: the confirmation of ${s}'s address asked back, a system email, which leaves under System email only too`:` Salesforce sends ${r} emails to people: the confirmation of each address asked back (${s}), system emails, which leave under System email only too`)}return t}function lo(e,t="apply",n={}){let r=e.org.kind==="sandbox"?Ne(e.org.host):void 0,s=e.org.alias??e.org.organizationId,o=e.state.refreshed,i=[`plan of ${e.env} on ${s} (${e.org.kind}${r!==void 0?` ${r}`:""}, ${e.org.organizationId})`,e.state.found?`state: kept on this machine, serial ${e.state.serial??0}`:o!==void 0?`state: ${ci(s,o)}`:"state: none on this machine"];for(let h of e.actions){let m=vc(h);i.push(` ${h.action.padEnd(8)} ${h.resource}${m?` ${m}`:""}`),i.push(` ${h.why}`),i.push(...KS(h));for(let g of h.draws??[])i.push(` ${g.lookup} draws its parents from `+(g.parents!==void 0?`the ${g.parents} ${g.object} record(s) ${g.from} created`:`the ${g.object} records ${g.from} creates first`));for(let g of h.notes??[])i.push(` ${g}`);h.refusal!==void 0&&i.push(` refused: ${h.refusal}`)}let{totals:a}=e;i.push(`totals: ${a.create} to create, ${a.replace} to replace, ${a.delete} to delete, ${a.keep} kept, ${a.drifted} drifted, ${a.blocked} blocked`);let{apiRequests:c,storage:u,emails:f}=e.gates,d=(h,m)=>h!==void 0?`, ${h} left`:m!==void 0?` (left: ${m})`:"";i.push(`API requests: about ${c.estimate}`+d(c.leftToday?.toString(),c.unread)+(c.partial?`; not counted: ${(c.notCounted??[]).join(", ")}`:"")),i.push(`data storage: about ${vt(u.bytes/1048576)} MB`+d(u.left!==void 0?`${vt(u.left/1048576)} MB`:void 0,u.unread));for(let h of f)i.push(`emails (${h.limit}): ${h.emails}`+(h.left!==void 0?`, ${h.left} left today`:""));let l=e.gates.emailsToPeople;l!==void 0&&l.count>0&&i.push(`emails to people: ${l.count}, `+(l.accepted?"accepted by the line (--accept-user-emails)":"which the line accepts with --accept-user-emails")),i.push(...Ed(e)),n.audits!==void 0&&i.push(n.audits);for(let h of e.warnings??[])i.push(`warning: ${h}`);return e.refusal!==void 0&&i.push(`${US[t]} would be refused: ${e.refusal}`),i}import{existsSync as fo,readFileSync as kc}from"node:fs";import{join as VS}from"node:path";function po(e){return e.slice(0,15)}function dr(e){let t=new Map,n=new Set;for(let{objectApiName:r,ids:s}of e){let o=t.get(r)??[];for(let i of s)n.has(po(i))||(n.add(po(i)),o.push(i));t.set(r,o)}return t}function WS(e,t,n){let r=e.runId!==void 0?VS(n.journalDir,Be,`${e.runId}.ndjson`):void 0;if(r!==void 0&&fo(r)){let i=mu(kc(r,"utf8"));if(i!==void 0)return{created:dr(i.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(!fo(s))return{refusal:"its run keeps no record of what it created"};let o=Kt(kc(s,"utf8"));return o.result.objectResults.some(i=>i.truncated===!0)?{refusal:"its summary names the first of the records it created alone, and its run file is gone"}:{created:dr(o.result.objectResults.map(i=>({objectApiName:i.objectApiName,ids:i.createdIds})))}}async function HS(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(!fo(r))return{refusal:"its run keeps no summary"};let s=await Or(r,kc(r,"utf8"),t.target,$r(n.journalDir));if("refusal"in s)return{refusal:`its summary ${s.refusal}`};let{result:o}=s.summary,i=Gc({idRemapTable:o.remapTable,idRemapExisting:[...o.existingSourceIds,...o.updatedSourceIds],idRemapCreated:o.createdByObject});return{created:dr([...i].reverse().map(a=>({objectApiName:a.objectApiName,ids:[...a.ids].reverse()})))}}async function YS(e,t,n){if(Zr(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 Ue,o=(await pn(r,s)).find(c=>po(c)===po(t.organizationId));if(o===void 0)return{refusal:"its sas holds no mapping of a load into this org"};let i=await new Cr(r,{orgId:o,guard:s}).recorded();if(i?.created===void 0)return{refusal:"its sas holds no load that says which records it created"};let a=Bu(i);return{created:dr([...a].reverse().map(c=>({objectApiName:c.objectApiName,ids:[...c.ids].reverse()})))}}async function JS(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(!fo(r))return{refusal:"its run keeps no summary"};let s;try{s=ts(r)}catch{return{refusal:"its summary names no checkpoint a replay wrote from"}}let o;try{let i=new Ku({root:ed(Z(n.journalDir),!0)});o=await i.createdBy(i.folderOf(s.organizationId,s.checkpointId),t.organizationId)}catch(i){return{refusal:`its replays cannot be read: ${i instanceof Error?i.message:String(i)}`}}return o===void 0?{refusal:`the store of checkpoints keeps no replay of ${s.checkpointId} into this org that says which records it created`}:{created:dr([...o].reverse().map(i=>({objectApiName:i.objectApiName,ids:[...i.ids].reverse()})))}}async function bc(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 o=s.runs.at(-1);if(o===void 0||o.takenBack===!0)return{refusal:`${t} holds no run whose records are in the org`};let i=await lr(o,n,r);return"refusal"in i?{refusal:`${t}: ${i.refusal}`}:i}async function lr(e,t,n){switch(e.script){case"sandforge-seed":return WS(e,t,n);case"sandforge-clone":return HS(e,t,n);case"sandforge-frozen":return YS(e,t,n);case V:return JS(e,t,n);default:return{refusal:`its records are kept by ${De(e.script)}, which this SandForge reads not`}}}function GS(e,t){let n=e.relation.parentObject,r=`${e.relation.childObject}.${e.relation.lookupField}`,s=[...t.get(n)??[]],o=wr.maxExistingParents;if(s.length===0){let i=[...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 ${i.join(", ")||"no record"}`}}return e.limit!==void 0?{ids:s.slice(0,e.limit)}:s.length>o?{refusal:`the relation on ${r} draws its parents from the ${s.length} ${n} records ${e.from} created, more than the ${o} a relation's parents hold: give the relation a limit, and its parents are the first ${o} or fewer`}:{ids:s}}async function ho(e,t,n,r,s){let o={ids:new Map,draws:[],refusals:[]};if(e.kind!=="seed")return o;let i=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)){o.draws.push(c);continue}let u=i.get(a.from);if(u===void 0&&(u=await bc(t,a.from,r,s),i.set(a.from,u)),"refusal"in u){o.draws.push(c),o.refusals.push(`the relation on ${c.lookup} draws its parents from ${a.from}, whose records cannot be read: ${u.refusal}`);continue}let f=GS(a,u.created);if("refusal"in f){o.draws.push(c),o.refusals.push(f.refusal);continue}o.ids.set(a.at,f.ids),o.draws.push({...c,parents:f.ids.length})}return o}function we(e){return ru.some(t=>Pe(t)===e)}function Dg(e,t,n){let r=e===0||e===3||e===4||we(e),s=t??(r?void 0:dd(n));return s!==void 0&&s!==""?s.slice(0,4e3):void 0}function ZS(e){return Ri(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 e$(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 t$(e){try{return typeof JSON.parse(e)?.refused?.code=="string"}catch{return!1}}function Ye(e,t,n){if(!(t.trim()===""||t$(t)))try{return e(t)}catch(r){if(r instanceof ce){n(` ${r.message}`);return}throw r}}function Rc(e,t,n,r){let s=Zr(e.sas);if(s!==void 0){let o=n.store.fileOf(t.organizationId,t.env,Et(s,e.n));return an(o)?o:void 0}if(e.summary!==void 0){let o=n.store.fileOf(t.organizationId,t.env,e.summary);if(an(o))return o}if(e.runId!==void 0&&an(go(n.journalDir,Be,`${e.runId}.ndjson`)))return e.runId;if(e.script===V&&r!==void 0){let o=n.store.fileOf(t.organizationId,t.env,Et(r,e.n));return an(o)?o:void 0}}var n$=/^run-([1-9]\d{0,5})\.json$/,r$=6e4,s$=p.object({run:p.number().int().positive(),startedAt:p.string(),removals:p.array(p.object({status:p.string()}).loose()).optional()}).loose();function Pg(e,t,n,r){let s=l=>{if(l===void 0)return;let h=r.store.fileOf(n.organizationId,n.env,l),m;try{m=Ec(h,"utf8")}catch{return}let g=Dn(m);return g!==void 0?{run:g,file:h}:void 0},o=s(e.summary);if(o!==void 0)return o;let i=new Set(t.flatMap(l=>l.n===e.n?[]:[s(l.summary)?.run??0])),a=go(r.journalDir,"users",pe(n.organizationId)),c;try{c=QS(a)}catch{c=[]}let u=Date.parse(e.startedAt)-r$,f=c.flatMap(l=>{let h=Number(n$.exec(l)?.[1]??0);if(h===0||i.has(h))return[];let m=go(a,l);try{let g=s$.safeParse(JSON.parse(Ec(m,"utf8"))),w=g.success&&g.data.removals?.at(-1)?.status==="success";return g.success&&g.data.run===h&&!w&&Date.parse(g.data.startedAt)>=u?[{run:h,file:m}]:[]}catch{return[]}}),[d]=f;return d!==void 0&&f.length===1?{...d,adopted:!0}:f.length===0&&(e.exitCode===1||e.exitCode===2)?{none:!0}:{unknown:f.length===0?`its run ${e.n} stopped before it answered, and no run of ${B("users")} began on this machine after it was launched: which it was, nobody can say`:`its run ${e.n} stopped before it answered, and ${f.length} runs of ${B("users")} began on this machine after it was launched (${f.map(l=>l.run).join(", ")}): which is its, nobody can say. ${B("users")} remove --run <n> takes one back`}}function wo(e,t,n){let r;for(let s of[...e?.runs??[]].reverse()){if(s.takenBack===!0)continue;let o=Pg(s,e?.runs??[],t,n);if("run"in o)return{run:o.run,...r!==void 0?{unknown:r}:{}};"unknown"in o&&(r??=o.unknown)}return r!==void 0?{unknown:r}:{}}async function Sc(e,t,n,r){let s={organizationId:t.org.organizationId,env:t.env},o=t.resources[n.resource];if(o===void 0)throw new L("invalid",`The state holds no resource ${n.resource} to take back`);if(o.kind==="mask")return o$(e,t,n);let i=await e.store.update(t,d=>Xo(d,n.resource)),a=[],c=!1,u=!1,f=!1;for(let d of[...o.runs].reverse()){if(d.takenBack===!0)continue;let l;if(o.kind==="users"){if(f){i=await e.store.update(i,S=>wn(S,n.resource,d.n));continue}let E=Pg(d,o.runs,s,e);if("unknown"in E){e.say(`${n.resource}: run ${d.n} is not taken back: ${E.unknown}`),c=!0;continue}l="run"in E?E.file:void 0}else l=Rc(d,s,e,n.resource);if(l===void 0)continue;e.say(`${n.resource}: taking back run ${d.n}`);let h=Sp(o.kind,{target:n.target.alias,subject:l,includeChanged:n.includeChanged,acceptAutomation:n.acceptAutomation,sweep:n.sweep,checkpointStore:Z(e.journalDir)}),m=await e.runner(h.script,h.args,r),g=Ye(E=>$p(o.kind,E),m.stdout,e.say),w=Ri(g).reduce((E,S)=>E+S.deleted,0);u||=g!==void 0?w>0:m.code!==1&&m.code!==2;let y=we(m.code),v=m.code===0||m.code===3,b=y?"destroying":v?m.code===3?n.ends.left:n.ends.whole:o.status,k=Dg(m.code,void 0,m.stderr);if(a.push({resource:n.resource,action:n.action,phase:"remove",run:d.n,script:h.script,exitCode:m.code,status:b,...d.summary!==void 0?{summary:d.summary}:{},objects:ZS(g),...g!==void 0?{answer:g}:{},...k!==void 0?{refusal:k}:{}}),m.code===3&&(c=!0),m.code===0)i=await e.store.update(i,E=>wn(E,n.resource,d.n)),f=o.kind==="users";else if(o.kind==="users"&&v)break;if(!v)return y||(i=await e.store.update(i,E=>Ft(E,{resource:n.resource,status:o.status}))),{whole:!1,code:y?m.code:1,wrote:u,steps:a,state:i}}return i=await e.store.update(i,d=>Ft(d,{resource:n.resource,status:c?n.ends.left:n.ends.whole})),{whole:!c,code:c?3:0,wrote:u,steps:a,state:i}}async function o$(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,f=>Xo(f,n.resource)),o=e.store.sasOf(t.org.organizationId,t.env,Ut(n.resource)),i=r.runs.at(-1),a=(f,d,l)=>({resource:n.resource,action:n.action,phase:"remove",run:i?.n??1,script:"sandforge-dataops",exitCode:d,status:f,objects:(i?.objects??[]).map(h=>({object:h.objectApiName,created:0,refused:0,deleted:0,kept:0,masked:h.masked??0,reason:l}))});e.say(`${n.resource}: deleting its store ${o}`);let c;try{c=await Jl(o)}catch(f){let d=f instanceof Error?f.message:String(f);return e.say(`${n.resource}: ${d}`),s=await e.store.update(s,l=>Ft(l,{resource:n.resource,status:r.status})),{whole:!1,code:1,wrote:!1,steps:[a(r.status,1,d)],state:s}}e.say(Gl(n.resource,c));for(let f of r.runs)f.takenBack!==!0&&(s=await e.store.update(s,d=>wn(d,n.resource,f.n)));s=await e.store.update(s,f=>Ft(f,{resource:n.resource,status:n.ends.whole}));let u=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; ${u} deleted`)],state:s}}var i$=new Set(["sandforge-seed","sandforge-clone","sandforge-dataops","sandforge-frozen","sandforge-users","sandforge-checkpoint"]);function gt(e,t){return t&&i$.has(e.script)?{...e,args:[...e.args,"--accept-emails"]}:e}function a$(e,t){let n=new Map(e.actions.map(i=>[i.resource,i])),r=new Set(_e(t).map(([i])=>i)),s=mt(t,e.actions.filter(i=>(i.action==="delete"||i.action==="replace"&&!$t(i.kind))&&r.has(i.resource)).map(i=>i.resource)).map(i=>({phase:"remove",resource:i,action:n.get(i)?.action??"delete"})),o=e.actions.filter(i=>i.action==="create"||i.action==="replace").map(i=>({phase:"run",resource:i.resource,action:i.action}));return[...s,...o]}function Ng(e,t,n){if(we(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 c$(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 u$(e,t,n){let{resource:r,n:s,where:o,target:i,templateFile:a,dry:c,signal:u}=n,f=o.env,d=c!==void 0&&"answer"in c?c.answer:void 0,l=d===void 0||n.readTooEarly?void 0:Yt(d).created,h=await e.orgNow();if(r.kind==="seed"){let P=Lr(f,r.name,s),D=r.run.seed??(d?.tool==="sandforge-seed"?d.seed:void 0),x=await e.store.update(t,Ce=>Rt(Ce,{resource:r.name,kind:"seed",fingerprint:r.fingerprint,dependsOn:r.dependsOn,run:{script:"sandforge-seed",runId:P,...D!==void 0?{seed:D}:{},startedAt:h}})),J=gt(At(r,{target:i.alias,templateFile:a,runId:P,summaryFile:"",...D!==void 0?{seed:D}:{}}),n.acceptEmails),U=await e.runner(J.script,J.args,u),O=Ye(Kt,U.stdout,e.say),F=O!==void 0?os(O):void 0,ae=(F?.created??0)>0||an(go(e.journalDir,Be,`${P}.ndjson`)),X=O!==void 0?await e.store.writeFile(o.organizationId,f,oe(r.name,s),U.stdout).then(()=>oe(r.name,s)):void 0;return{state:x,script:J.script,code:U.code,...F!==void 0?{count:F}:{},...O!==void 0?{answer:O}:{},...X!==void 0?{summary:X}:{},wrote:ae,...l!==void 0?{planned:l}:{},...F?.refusal!==void 0?{answered:F.refusal}:{},stderr:U.stderr}}if(r.kind==="frozen")return d$(e,t,n,h,l);if(r.kind==="mask")return l$(e,t,n,h);if(r.kind==="users")return p$(e,t,n,h);if(r.kind==="replay")return h$(e,t,n,h,l);let m=oe(r.name,s),g=await e.store.prepareFile(o.organizationId,f,m),w=await e.store.update(t,P=>Rt(P,{resource:r.name,kind:"forge",fingerprint:r.fingerprint,dependsOn:r.dependsOn,run:{script:"sandforge-clone",summary:m,startedAt:h}})),y=uo(c),v=r.kind==="forge"&&r.run.records!==void 0?Jr(e.journalDir,o.organizationId,f,r.name):void 0,b=gt(At(r,{target:i.alias,templateFile:a,runId:"",summaryFile:g,...y!==void 0?{maxTotal:y}:{},...v!==void 0?{rootsPlanFile:v}:{}}),n.acceptEmails),k=await e.runner(b.script,b.args,u);v!==void 0&&XS(v,{force:!0});let E=an(g)?Ec(g,"utf8"):void 0,S=Ye(Sn,E??"",e.say)??Ye(Sn,k.stdout,e.say),$=S!==void 0?Gr(S):void 0,j=$!==void 0?$.created>0:E!==void 0,A;if(k.code===0&&E!==void 0&&($?.created??0)>0){e.say(`${r.name}: verifying run ${s}`);let P=await e.runner(b.script,Gd({summary:g,target:i.alias,source:r.source.alias}),u),D=P.stdout.trim()===""?void 0:Ye(tl,P.stdout,e.say);if(D!==void 0){let x=rl(D);A={unstable:D.result.verdict==="unstable",...x!==void 0?{short:x}:{}}}else P.code!==0&&(A={unread:`its verification ended ${P.code} without an answer`})}return{state:w,script:b.script,code:k.code,...$!==void 0?{count:$}:{},...S!==void 0?{answer:S}:{},...E!==void 0?{summary:m}:{},wrote:j,...l!==void 0?{planned:l}:{},...A!==void 0?{verified:A}:{},...S?.error!==void 0?{answered:S.error}:{},stderr:k.stderr}}async function d$(e,t,n,r,s){let{resource:o,n:i,where:a,target:c,templateFile:u,dry:f,signal:d}=n,l=await e.store.update(t,S=>Rt(S,{resource:o.name,kind:"frozen",fingerprint:o.fingerprint,dependsOn:o.dependsOn,run:{script:"sandforge-frozen",sas:rt(o.name),startedAt:r}})),h=uo(f),m=gt(At(o,{target:c.alias,templateFile:u,runId:"",summaryFile:"",replace:n.replace,acceptAutomation:n.acceptAutomation,...h!==void 0?{maxTotal:h}:{}}),n.acceptEmails),g=await e.runner(m.script,m.args,d),w=Ye(Qr,g.stdout,e.say),y=w!==void 0?Cn(w):void 0;y?.refusal!==void 0&&e.say(`${o.name}: ${y.refusal}`);let v=w===void 0?we(g.code):(y?.created??0)>0||Rl(w),b=w!==void 0?await e.store.writeFile(a.organizationId,a.env,oe(o.name,i),g.stdout).then(()=>oe(o.name,i)):void 0,k=w?.verdict,E=k!==void 0?di(k):g.code===0&&(y?.created??0)>0?{unread:"the load chained no verification"}:void 0;return{state:l,script:m.script,code:g.code,...y!==void 0?{count:y}:{},...w!==void 0?{answer:w}:{},...b!==void 0?{summary:b}:{},wrote:v,...s!==void 0?{planned:s}:{},...E!==void 0?{verified:E}:{},...n.replace&&w!==void 0&&Xr(w)?{tookBackEarlier:!0}:{},...y?.refusal!==void 0?{answered:y.refusal}:{},stderr:g.stderr}}async function l$(e,t,n,r){let{resource:s,n:o,where:i,target:a,templateFile:c,signal:u}=n,f=await e.store.update(t,v=>Rt(v,{resource:s.name,kind:"mask",fingerprint:s.fingerprint,dependsOn:s.dependsOn,run:{script:"sandforge-dataops",startedAt:r}})),d=await e.store.prepareFolder(i.organizationId,i.env,Ut(s.name)),l=gt(At(s,{target:a.alias,templateFile:c,runId:"",summaryFile:"",store:d}),n.acceptEmails),h=await e.runner(l.script,l.args,u),m=Ye(es,h.stdout,e.say),g=m!==void 0?In(m):void 0;g?.refusal!==void 0&&e.say(`${s.name}: ${g.refusal}`);let w=g!==void 0?g.objects.some(v=>v.masked>0):we(h.code),y=m!==void 0?await e.store.writeFile(i.organizationId,i.env,oe(s.name,o),h.stdout).then(()=>oe(s.name,o)):void 0;return{state:f,script:l.script,code:h.code,...m!==void 0?{answer:m}:{},...y!==void 0?{summary:y}:{},wrote:w,...g!==void 0?{masking:g}:{},...g?.refusal!==void 0?{answered:g.refusal}:{},stderr:h.stderr}}function f$(e){let t;try{t=JSON.parse(e)}catch{return}if(wt.safeParse(t).success)return;let n=vr.safeParse(t);return n.success?(n.data.refusals??[]).map(r=>r.message):void 0}async function p$(e,t,n,r){let{resource:s,n:o,where:i,target:a,templateFile:c,signal:u}=n,f=await e.store.update(t,b=>Rt(b,{resource:s.name,kind:"users",fingerprint:s.fingerprint,dependsOn:s.dependsOn,run:{script:W,startedAt:r}})),d=gt(At(s,{target:a.alias,templateFile:c,runId:"",summaryFile:"",acceptAutomation:n.acceptAutomation,acceptUserEmails:n.acceptUserEmails,...n.replacesRun!==void 0?{replacesRun:n.replacesRun}:{}}),n.acceptEmails),l=await e.runner(d.script,d.args,u),h=f$(l.stdout),m=h===void 0?Ye(Vt,l.stdout,e.say):void 0,g=m!==void 0?is(m):void 0,w=m!==void 0?m.users.some(b=>b.done.length>0):h===void 0&&l.code!==1&&l.code!==2,y=m!==void 0?await e.store.writeFile(i.organizationId,i.env,oe(s.name,o),l.stdout).then(()=>oe(s.name,o)):void 0,v=g?.refusal??(h!==void 0?h.join(" "):void 0);return{state:f,script:d.script,code:l.code,...g!==void 0?{count:g}:{},...m!==void 0?{answer:m}:{},...y!==void 0?{summary:y}:{},wrote:w,...n.replacesRun!==void 0&&m!==void 0?{tookBackEarlier:!0}:{},...v!==void 0&&v!==""?{answered:v}:{},stderr:l.stderr}}async function h$(e,t,n,r,s){let{resource:o,n:i,where:a,target:c,templateFile:u,dry:f,signal:d}=n,l=await e.store.update(t,k=>Rt(k,{resource:o.name,kind:"replay",fingerprint:o.fingerprint,dependsOn:o.dependsOn,run:{script:V,startedAt:r}})),h=uo(f),m=gt(At(o,{target:c.alias,templateFile:u,runId:"",summaryFile:"",replace:n.replace,acceptAutomation:n.acceptAutomation,checkpointStore:Z(e.journalDir),...h!==void 0?{maxTotal:h}:{}}),n.acceptEmails),g=await e.runner(m.script,m.args,d),w=Ye(ns,g.stdout,e.say),y=w!==void 0?rs(w):void 0,v=w!==void 0?(y?.created??0)>0:we(g.code),b=w!==void 0?await e.store.writeFile(a.organizationId,a.env,oe(o.name,i),g.stdout).then(()=>oe(o.name,i)):void 0;return{state:l,script:m.script,code:g.code,...y!==void 0?{count:y}:{},...w!==void 0?{answer:w}:{},...b!==void 0?{summary:b}:{},wrote:v,...s!==void 0?{planned:s}:{},...n.replace&&w!==void 0&&ss(w)?{tookBackEarlier:!0}:{},...y?.refusal!==void 0?{answered:y.refusal}:{},stderr:g.stderr}}function m$(e,t){let n=Ng(e,void 0,void 0);if(e!==0)return n;let r=(t?.objects??[]).reduce((s,o)=>s+o.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 g$(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 y$(e,t,n,r,s){if(n.kind==="frozen"){let i=await e.store.prepareFolder(r.organizationId,r.env,rt(n.name));return{payload:Ht(n,{sasDir:i})}}if(n.kind==="replay"){let i=n.checkpoint.read;return i===void 0||"refusal"in i?{refusal:i?.refusal??"its checkpoint was not resolved: plan again"}:{payload:{command:"replay",checkpoint:{id:i.checkpointId,organizationId:i.organizationId}}}}if(n.kind!=="seed"||(n.run.draws??[]).length===0)return{payload:Ht(n,{})};let o=await ho(n,t,new Set,{...r,target:s.alias},{store:e.store,journalDir:e.journalDir});return o.refusals.length>0?{refusal:o.refusals.join(" ")}:{payload:Ht(n,{drawn:o.ids})}}function Cg(e,t,n){let r=e;for(let s of t.actions){if(s.action!=="keep"&&s.action!=="drifted")continue;let o=r.resources[s.resource],i=n.get(s.resource)?.fingerprint;o===void 0||i===void 0||o.recovered===!0||o.status==="destroyed"||o.fingerprint===i||(r={...r,resources:{...r.resources,[s.resource]:{...o,fingerprint:i}}})}return r}function yo(e){return e===0?"success":we(e)?"cancelled":e===1?"failure":"partial"}async function Tg(e,t){let{plan:n,target:r,resolved:s}=t,o=s.checked.file.name,i=(m,g=t.state,w=[])=>({result:{plan:n,steps:[],status:"failure",refusal:m,...w.length>0?{refusalCodes:[...w]}:{},state:{serial:g?.serial??0}},exitCode:1});if(n.refusal!==void 0)return i(n.refusal,t.state,n.refusalCodes);let a=a$(n,t.state),c=n.checkpoints?.find(m=>m.step==="before"),u=n.checkpoints?.find(m=>m.step==="after");if(a.length===0&&u===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 f=Qe(e.locksDir,r.organizationId,{operation:"apply",env:o,alias:r.alias},e.lockOptions);if("busy"in f){let m=nt(f.busy);return i(m.message,t.state,[m.code])}let d=new AbortController,l,h=(e.onStop??Ge)(m=>{l=m,e.say(`
148
+ stopped by ${m}: 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 m;try{let O=await e.store.read(r.organizationId,o);if(O===void 0!=(t.state===void 0)||O!==void 0&&(O.serial!==t.state?.serial||O.lineage!==t.state.lineage))return i(`The state of ${o} 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,[Wr]);m=O??Mr({env:o,org:{organizationId:r.organizationId,kind:r.kind,username:r.username,alias:r.alias,...r.host!==void 0?{host:r.host}:{}},fileDigest:s.digest,sandforgeVersion:e.sandforgeVersion})}catch(O){if(O instanceof L)return i(O.message,t.state,[tt(O).code]);throw O}m={...ad(m,r.host),file:{digest:s.digest},sandforgeVersion:e.sandforgeVersion};let g={organizationId:r.organizationId,env:o},w=[],y=[],v=[],b=new Map,k=!1,E,S=new Map(s.resources.map(O=>[O.name,O])),$=new Set,j=0,A=[],P={alias:r.alias,kind:r.kind},D=qr(s.checked.file);if(c!==void 0&&a.length>0){let O=await ii(e,{org:P,step:"before",name:c.name,...D},d.signal);if(A.push(O.result),O.checkpoint===void 0){let ae=l!==void 0?Pe(l):we(O.result.exitCode)?O.result.exitCode:1;return{result:{plan:n,steps:[],checkpoints:A,status:yo(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:m.serial}},exitCode:ae}}let F=O.checkpoint;m=await e.store.update(m,ae=>et(ae,"before",F))}Cg(m,n,S)!==m&&(m=await e.store.update(m,O=>Cg(O,n,S)));try{for(let O of a){if(j+=1,E!==void 0||l!==void 0){y.push({resource:O.resource,why:"the apply was stopped before it"});continue}let F=S.get(O.resource),ae=(F?.dependsOn??[]).filter(fe=>b.has(fe));if(O.phase==="run"&&ae.length>0){y.push({resource:O.resource,why:`it depends on ${ae.map(fe=>`${fe} (${b.get(fe)??"not whole"})`).join(", ")}`});continue}let X=Ar(e.locksDir,r.organizationId,e.lockOptions);if(X!==void 0){e.say(Rn(X).message),v.push(1),y.push({resource:O.resource,why:Rn(X).message});break}if(O.phase==="remove"){let fe=t.acceptAutomation||s.checked.file.resources[O.resource]?.accept?.automation===!0,ne=await Sc(e,m,{resource:O.resource,action:O.action,target:r,includeChanged:!1,sweep:!1,acceptAutomation:fe,ends:{whole:"destroyed",left:"partial"}},d.signal);if(m=ne.state,w.push(...ne.steps),k||=ne.wrote,we(ne.code)){E=ne.code;continue}if(v.push(ne.code),ne.code!==0&&ne.code!==3)break;continue}if(F===void 0)continue;let Ce=yn(m.resources[O.resource]),mr=await y$(e,m,F,g,r);if("refusal"in mr){e.say(`${O.resource}: not run, ${mr.refusal}`),v.push(1),y.push({resource:O.resource,why:mr.refusal}),b.set(O.resource,"not run");break}let Fy=await e.store.writeFile(g.organizationId,o,Et(O.resource,Ce),`${JSON.stringify(mr.payload,null,2)}
149
+ `),My=F.dependsOn.some(fe=>$.has(fe)),Fc=F.kind==="users"&&O.action==="replace"?wo(m.resources[O.resource],g,e).run:void 0;e.say(`${O.resource}: run ${Ce} (${O.action})`);let K=await u$(e,m,{resource:F,n:Ce,where:g,target:r,templateFile:Fy,dry:t.dryRuns[O.resource],readTooEarly:My,replace:O.action==="replace"&&$t(F.kind),acceptAutomation:t.acceptAutomation||s.checked.file.resources[O.resource]?.accept?.automation===!0,acceptEmails:t.acceptEmails===!0,acceptUserEmails:t.acceptUserEmails===!0,...Fc!==void 0?{replacesRun:Fc}:{},signal:d.signal});m=K.state,k||=K.wrote,F.kind!=="mask"&&$.add(O.resource);let Lt=K.masking,Ie=F.kind==="mask"?m$(K.code,Lt):c$(Ng(K.code,K.count,K.planned),K.verified),_y=await e.orgNow();if(m=await e.store.update(m,fe=>Ft(fe,{resource:O.resource,status:Ie.status,run:{endedAt:_y,exitCode:K.code,objects:Lt!==void 0?Lt.objects.map(ne=>({objectApiName:ne.object,created:0,refused:ne.refused,masked:ne.masked})):(K.count?.objects??[]).map(ne=>({objectApiName:ne.object,created:ne.created,refused:ne.refused})),...K.summary!==void 0?{summary:K.summary}:{},...Lt?.snapshotId!==void 0?{snapshotId:Lt.snapshotId}:{}}})),K.tookBackEarlier===!0)for(let fe of m.resources[O.resource]?.runs??[])fe.n===Ce||fe.takenBack===!0||(m=await e.store.update(m,ne=>wn(ne,O.resource,fe.n)));let gr=F.kind==="mask"?g$(Lt):e$(K.count),Mc=Dg(K.code,K.answered,K.stderr);if(w.push({resource:O.resource,action:O.action,phase:"run",run:Ce,script:K.script,exitCode:K.code,status:Ie.status,...K.summary!==void 0?{summary:K.summary}:{},objects:Ie.short!==void 0&&gr[0]!==void 0?[{...gr[0],reason:Ie.short},...gr.slice(1)]:gr,...K.answer!==void 0?{answer:K.answer}:{},...Mc!==void 0?{refusal:Mc}:{}}),Ie.short!==void 0&&e.say(`${O.resource}: ${Ie.short}`),we(K.code)){E=K.code,e.say(F.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`:F.kind==="users"?`${O.resource}: its run was stopped; the state keeps it applying, and the run file of sandforge users what it changed: apply again converges from it`:`${O.resource}: its run was stopped; the state keeps it applying, and its ${F.kind==="forge"?"summary what it created":F.kind==="frozen"?"sas what it loaded":F.kind==="replay"?"payload the checkpoint it replays":"run file what it wrote"}: apply again takes it back and runs it whole`);continue}if(v.push(Ie.counts),Ie.status!=="applied"&&b.set(O.resource,Ie.status),Ie.stops)break}}catch(O){let F=`the apply stopped on an error: ${O instanceof Error?O.message:String(O)}`;e.say(F),v.push(1);for(let ae of a.slice(j))y.push({resource:ae.resource,why:F})}let x=m.checkpoints?.after;if(k&&x!==void 0&&l===void 0){let O=await qt(e,{org:P,checkpoint:x,why:"taken before this apply wrote"},d.signal);A.push(O),m=await e.store.update(m,F=>et(F,"after",void 0))}let J=l===void 0&&E===void 0&&fn(v)===0;if(u!==void 0&&J){let O=await ii(e,{org:P,step:"after",name:u.name,...D},d.signal);A.push(O.result);let F=O.checkpoint;F!==void 0?m=await e.store.update(m,ae=>et(ae,"after",F)):we(O.result.exitCode)?E=O.result.exitCode:(e.say(`the checkpoint once applied, '${u.name}', was not taken: reset has nothing to rewind to until an apply takes it, which the next one does`),v.push(1))}let U=l!==void 0?Pe(l):E!==void 0?E:(()=>{let O=fn(v);return O===1&&k?3:O})();return{result:{plan:n,steps:w,...A.length>0?{checkpoints:A}:{},...y.length>0?{skipped:y}:{},status:yo(U),state:{serial:m.serial}},exitCode:U}}finally{h(),f.lock.release()}}function w$(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??""}`})}var v$=72;function k$(e){let t=` ${e.resource} ${e.phase==="run"?"run":"removal of run"} ${e.run}: exit ${e.exitCode}, ${e.status}`;if(e.phase==="run"){let i=wt.safeParse(e.answer),a=[];if(i.success){let c=i.data.users.filter(f=>f.done.length>0).length,u=i.data.users.filter(f=>(f.refused??[]).length>0).length;a.push(`${t} User ${c} set up${u>0?`, ${u} refused`:""}`);for(let f of i.data.users)f.address==="awaiting"&&a.push(` ${f.username}: address awaiting its owner's confirmation \u2014 Salesforce sent the link to it; until it is clicked (${v$} h), the address stays .invalid`)}else a.push(t);e.refusal!==void 0&&a.push(` ${e.refusal}`);for(let c of e.objects)c.reason!==void 0&&a.push(` ${c.object}: ${c.reason}`);return a}let n=e.answer,s=[e.objects.map(i=>`${i.object} ${i.deleted} deleted`).join("; "),b$(n?.answer)].filter(Boolean),o=[`${t}${s.length>0?` ${s.join("; ")}`:""}`];e.refusal!==void 0&&o.push(` ${e.refusal}`);for(let i of Array.isArray(n?.kept)?n.kept:[])o.push(` ${i.username}: ${St(i.change)} kept, ${i.why}`);return o}var Ig=[["frozen","freeze(s)"],["active","activation(s)"],["profile","profile(s)"]];function b$(e){let t=kr.safeParse(e);if(!t.success)return"";let n=new Set(Ig.map(([o])=>o)),r=t.data.users.filter(o=>o.undone.some(i=>n.has(i.what)));if(r.length===0)return"";let s=Ig.flatMap(([o,i])=>{let a=r.reduce((c,u)=>c+u.undone.filter(f=>f.what===o).length,0);return a>0?[`${a} ${i}`]:[]});return`User ${r.length} put back: ${s.join(", ")}`}function E$(e){let t=e.objects.map(c=>`${c.object} ${c.created}`).join(", "),n=e.objects.reduce((c,u)=>c+u.refused,0),r=e.answer?.replay?.owners,s=typeof r?.kept=="number"?r.kept:void 0,o=typeof r?.toRunningUser=="number"?r.toRunningUser:void 0,i=(t!==""?`${t} created`:"")+(n>0?`, ${n} refused`:"")+(s!==void 0&&o!==void 0?`; ${s} records kept their owner, ${o} went to you`:""),a=[` ${e.resource} replay ${e.run}: exit ${e.exitCode}, ${e.status}`+(i!==""?` ${i}`:"")];e.refusal!==void 0&&a.push(` ${e.refusal}`);for(let c of e.objects)c.reason!==void 0&&a.push(` ${c.object}: ${c.reason}`);return a}function $c(e,t,n=[]){let r=[""];for(let s of e.steps){if(s.script===W){r.push(...k$(s));continue}if(s.script===V&&s.phase==="run"){r.push(...E$(s));continue}if(s.script==="sandforge-dataops"){let i=s.objects.map(a=>s.phase==="run"?`${a.object} ${a.masked??0} masked${a.refused>0?`, ${a.refused} refused`:""}`:`${a.object} ${a.masked??0} left masked`).join("; ");r.push(` ${s.resource} ${s.phase==="run"?`masking ${s.run}: exit ${s.exitCode}`:"store deleted"}, ${s.status}${i?` ${i}`:""}`),s.refusal!==void 0&&r.push(` ${s.refusal}`);for(let a of s.objects)a.reason!==void 0&&r.push(` ${a.object}: ${a.reason}`);continue}let o=s.objects.map(i=>s.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("; ");r.push(` ${s.resource} ${s.phase==="run"?"run":"removal of run"} ${s.run}: exit ${s.exitCode}, ${s.status}${o?` ${o}`:""}`),s.refusal!==void 0&&r.push(` ${s.refusal}`);for(let i of s.objects)i.reason!==void 0&&r.push(` ${i.object}: ${i.reason}`)}for(let s of e.skipped??[])r.push(` ${s.resource}: not run, ${s.why}`);return r.push(...w$(e.checkpoints??[])),e.refusal!==void 0&&r.push(`${t} refused: ${e.refusal}`),r.push(...n),r.push(`${t}: ${e.status}; state serial ${e.state.serial}`),r}var Lg={words:1,switches:["--json","--save","--fail-on-findings"],values:["--file","--org","--alias"]},R$=2;function Fg(e){let t=[e.deliverability?"deliverability":void 0,e.schedules?"scheduled jobs":void 0,e.endpoints!==!1?"endpoints":void 0].filter(o=>o!==void 0),{fewest:n,most:r}=Xu(e),s=n===r?`${r}`:`${n} to ${r}`;return`audits after the apply: ${t.join(", ")}, about ${s} API requests`}function xg(e){return e.replace(/\.\d{3}Z$/,"Z")}function S$(e){let t=Ne(e.host),n=e.kind==="sandbox"?t!==void 0?`sandbox ${t}`:"sandbox":e.kind==="scratch"?"scratch org":"Developer Edition org";return e.alias!==void 0?`${e.alias} (${n}, ${e.organizationId})`:`${e.organizationId} (${n})`}function $$(e){return e.unread!==void 0&&e.now===0&&e.jobs.length===0&&e.kept===0&&e.against===void 0}function Ac(e,t){let n=[],r=`${e.apiRequests} API request${e.apiRequests===1?"":"s"}`;n.push(`audit of ${S$(e.org)}, ${xg(e.at)}, ${r}`);let s=e.deliverability;s?.read==="closed"?n.push("deliverability: closed \u2014 System email only or No access: what runs there emails nobody. Which of the two, no API says."):s?.read==="open"?n.push("deliverability: open \u2014 All email: what runs there emails whoever its records name, the addresses copied from production's among them."):s?.unread!==void 0&&n.push(`deliverability: not read \u2014 ${s.unread}`);let o=e.schedules;if(o!==void 0&&$$(o))n.push(`scheduled jobs: not read \u2014 ${o.unread??""}`);else if(o!==void 0){let a=o.against,c=e.org.kind==="sandbox"?"this sandbox":"this org";if(a===void 0){let u=e.org.host??"its host";n.push(`scheduled jobs: ${o.now} now, nothing to compare them with: no inventory of ${u} is kept on this machine`)}else n.push(`scheduled jobs: ${o.now} now, against the inventory saved on ${a.savedAt.slice(0,10)} from ${a.organizationId}, `+(a.refreshed?`${c} before its refresh`:`${c}: no refresh since`));for(let u of o.jobs){let f=` ${u.status.padEnd(8)} `,d=l=>`${f}${u.name} (${u.type}) runs as ${u.owner??"a user not read"}, who is ${l}: its next run${u.nextFireTime!==void 0?`, ${xg(u.nextFireTime)},`:""} fails`;if(u.status==="gone"){let l=u.cronExpression!==void 0?`${u.type}, ${u.cronExpression}`:u.type;n.push(`${f}${u.name} (${l}): `+(a?.refreshed===!0?"scheduled before the refresh, not since":`in the inventory of ${a?.savedAt.slice(0,10)??"?"}, not since`))}else u.status==="frozen"||u.status==="inactive"?n.push(d(u.status)):n.push(`${f}${u.name} (${u.type})`)}if(a!==void 0&&n.push(` ${"kept".padEnd(8)} ${o.kept}`),o.unread!==void 0&&n.push(` not read: ${o.unread}`),o.saved!==void 0)n.push(` inventory saved in ${o.saved}, to compare with after the next refresh`);else if(a===void 0){let u=e.org.alias??e.org.organizationId;n.push(` before the next refresh, keep one: ${B("env")} audit --file ${ze(t.file)} --org ${u} --save`)}}for(let a of t.notes??[])n.push(` ${a}`);let i=e.endpoints;if(i!==void 0){let a=i.productionHosts.join(", "),c=i.found.length===0;n.push(`endpoints that still name production (${a}):`+(c?i.unread!==void 0?" none among those read":" none":"")),i.notDeduced!==void 0&&n.push(` ${i.notDeduced}`);let u=h=>Math.max(...h.map(m=>m.length))+2,f=i.found.map(h=>Hu[h.source]),d=i.found.map(h=>h.name),l=i.found.map(h=>h.url);i.found.forEach((h,m)=>{n.push(` ${(f[m]??"").padEnd(u(f))}${(d[m]??"").padEnd(u(d))}${h.url.padEnd(u(l))}${Wu[h.why]}`)}),i.unread!==void 0&&n.push(` not read: ${i.unread}`)}return e.findings>0&&n.push("SandForge changes none of these: Setup, sf or your deployment put them right."),n}function A$(e,t){return e.saveFailed!==void 0?1:t&&e.result.findings>0?3:0}async function Mg(e,t){let n=hn(t.audits,"verb");if(n===void 0)throw new Error("env audit reads the deliverability at least");if(t.save&&!n.schedules)return{refusal:{code:"BAD_LINE",message:"--save keeps the scheduled jobs, which the file does not read (audits.schedules: false): take --save off the line, or the line off the file. Nothing was read."},exitCode:R$};let r=await Dr(e,{org:t.org,asked:n,save:t.save}),s=Ac(r.result,{file:t.file,notes:r.notes});return{result:r.result,lines:s,exitCode:A$(r,t.failOnFindings)}}import{randomBytes as O$}from"node:crypto";import{mkdir as j$,open as C$,rename as I$,rm as D$}from"node:fs/promises";import{dirname as P$,join as N$,resolve as T$}from"node:path";var x$=448,L$=384,_g=72;function Oc(e){return e.map(([t,n])=>`${t} ${n}`).join(", ")}function zg(e){switch(e.what){case"email":return"address asked back, awaiting its owner";case"active":return e.to?"activated":"deactivated";case"frozen":return e.to?"frozen":"unfrozen";case"profile":return`profile ${se(e.to)}`;case"permissionSet":return`${e.to==="added"?"permission set":"permission set taken off:"} ${se(e.name)}`;case"permissionSetGroup":return`${e.to==="added"?"permission set group":"permission set group taken off:"} ${se(e.name)}`;case"group":{let t=e.type==="Queue"?"queue":"public group";return`${e.to==="added"?t:`${t} taken off:`} ${se(e.name)}`}}}function F$(e){let t=wt.safeParse(e.answer);return t.success?t.data.users:void 0}function Bg(e,t){return e.steps.filter(n=>n.resource===t&&n.phase==="run").at(-1)}function Ug(e){switch(e.status){case"applied":return"applied";case"partial":return"applied in part";case"failed":return"failed";default:return"stopped part way"}}function M$(e){let t=["## Access",""],n=[],r=new Date(Date.parse(e.at)+_g*36e5).toISOString(),s=e.run.plan.actions.filter(o=>o.kind==="users");s.length===0&&t.push("- No users resource: SandForge set up no user.");for(let o of s){let i=Bg(e.run,o.resource);if(i===void 0){t.push(`- ${se(o.resource)}: ${o.action==="keep"?"kept, as the last apply left its users":"not run"}.`);continue}let a=F$(i);if(a===void 0){t.push(`- ${se(o.resource)}: ${Ug(i)}; what it did to each user does not read from its answer: ${B("env")} output names its users.`);continue}for(let c of a){let u=c.done.map(zg),f=(c.refused??[]).map(l=>`${zg(l.change)} refused (${l.code})`),d=[...u,...f];t.push(`- ${se(c.username)}: ${d.length>0?d.join("; "):"as the file says already"}.`),c.address==="awaiting"&&n.push(c.username)}}if(n.length>0){t.push("","### Addresses awaiting their owner","");for(let o of n)t.push(`- ${se(o)}: the address stays under \`.invalid\` until its owner follows the link Salesforce sent to it, by about ${Mo(r)} (${_g} hours).`)}return t.push("","SandForge resets no password: a user without one sets it by **Forgot your password?** on the sandbox's login page, once the address is theirs again."),t}function _$(e,t){let n=e.resources?.[t];if(n?.kind!=="mask")return;if(typeof n.rules!="string")return`the rules of the template ${se(n.rules.template)}`;let r=e.masking?.[n.rules];if(r===void 0)return;let s=[...new Set(r.rules.map(o=>o.fieldPattern))];return s.length>0?s.map(se).join(", "):void 0}function z$(e){let t=["## Data",""],n=e.run.plan.actions.filter(o=>o.kind!=="users");n.length===0&&t.push("- No data resource.");for(let o of n){let i=`${se(o.resource)} (${o.kind})`,a=Bg(e.run,o.resource);if(a===void 0){let u=e.run.skipped?.some(f=>f.resource===o.resource)===!0;t.push(`- ${i}: `+(o.action==="keep"?"kept, as applied before":o.action==="blocked"?"not applied: refused before it wrote":u?"not run: a resource it depends on did not end whole":"not run"));continue}let c=[Ug(a)];if(o.kind==="mask"){let u=e.output?.resources[o.resource],f=u?.masked?Object.entries(u.masked):a.objects.flatMap(l=>l.masked!==void 0?[[l.object,l.masked]]:[]);f.length>0&&c.push(`masked ${Oc(f)}`);let d=_$(e,o.resource);d!==void 0&&c.push(`fields ${d}`),u?.snapshotId!==void 0&&c.push(`snapshot ${se(u.snapshotId)}, taken first`)}else{let u=a.objects.filter(l=>l.created>0);u.length>0&&c.push(`created ${Oc(u.map(l=>[l.object,l.created]))}`);let f=a.objects.filter(l=>l.refused>0);f.length>0&&c.push(`refused ${Oc(f.map(l=>[l.object,l.refused]))}`);let d=e.resources?.[o.resource];d?.kind==="replay"&&d.owners!==void 0&&c.push(d.owners==="same"?"owners kept as the checkpoint names them":"owned by the user the apply connected as")}t.push(`- ${i}: ${c.join("; ")}.`)}let r=e.run.checkpoints?.find(o=>o.step==="after"),s=e.run.plan.checkpoints?.find(o=>o.step==="after");if(r!==void 0||s!==void 0){t.push("","### Starting point","");let o=e.org.alias??e.org.organizationId;if(r?.checkpoint!==void 0){let i=s?.estimate!==void 0?`, about ${s.estimate.records} records`:"";t.push(`- Checkpoint ${s!==void 0?`${se(s.name)} `:""}${se(r.checkpoint)}${i}: the org as the testers get it.`,`- Back to it between two test runs: \`${B("env")} reset --file ${ze(e.file)} --org ${o}\``)}else t.push(`- The checkpoint ${s!==void 0?`${se(s.name)} `:""}was not taken${r!==void 0?` (exit ${r.exitCode})`:""}: no reset returns to this apply's end.`)}return t}function qg(e){let t=e.org.alias??e.org.organizationId;return`\`${B("env")} audit --file ${ze(e.file)} --org ${t}\``}function q$(e){return Gu(e.run.audits,{endpoints:`${qg(e)} lists those that still name production.`,schedules:`${qg(e)} compares them with their inventory.`})}function Kg(e){let{run:t,org:n}=e;return`${[Yu(t.plan.env,n),"","## Environment","",`- Environment: ${se(t.plan.env)}, state serial ${t.state.serial}.`,Ju(n),`- Applied: ${Mo(e.at)}, by SandForge ${e.sandforgeVersion}; it ended ${t.status}.`,"",...M$(e),"",...z$(e),"",...q$(e),"",...Qu()].join(`
150
150
  `)}
151
- `}function qg(e,t){if(!/^[a-z][a-z0-9-]{0,62}$/.test(t.env))throw new Error(`Not an environment's name: "${t.env}"`);let n=new Date(t.at).toISOString().replace(/[-:.]/g,"");return C$(I$(e),"handoff",t.env,`${n}-${pe(t.organizationId)}.md`)}async function Bg(e,t){await S$(j$(e),{recursive:!0,mode:D$});let n=`${e}.${process.pid}-${R$(4).toString("hex")}.tmp`,r=await $$(n,"wx",P$);try{try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await A$(n,e)}catch(s){throw await O$(n,{force:!0}),s}}import{readFile as Pt,readdir as M$,stat as _$}from"node:fs/promises";import{join as Oe}from"node:path";var z$={"sandforge-seed":"seed","sandforge-clone":"forge","sandforge-frozen":"frozen","sandforge-dataops":"mask"},q$=/^([1-9][0-9]{0,5})\.summary\.json$/,B$=/^([a-z][a-z0-9-]{0,62})\.([1-9][0-9]{0,5})\.json$/,U$=/^([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}$/,K$=/\.load-\d{1,16}\.ndjson$/,Y=class extends Error{constructor(n,r){super(r);this.code=n;this.name="Refused"}code},de="Nothing was written.";async function He(e,t){try{return(await M$(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 Oc(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 Kg(e,t){let n=t.resolved.checked.file.name,r=t.target.organizationId,s=e.store.folderOf(r,n),o={ranks:new Map,frozen:new Set,dataops:new Set,unclaimed:[]},i=f=>un.safeParse(f).success;for(let f of(await He(Oe(s,"runs"),!0)).filter(i))for(let h of await He(Oe(s,"runs",f),!1)){let m=q$.exec(h)?.[1];m!==void 0&&(Oc(o,f,Number(m)).summary=oe(f,Number(m)))}for(let f of await He(Oe(s,"templates"),!1)){let h=B$.exec(f);h?.[1]===void 0||h[2]===void 0||!i(h[1])||(Oc(o,h[1],Number(h[2])).template=bt(h[1],Number(h[2])))}for(let f of(await He(Oe(s,"frozen"),!0)).filter(i))o.frozen.add(f);for(let f of(await He(Oe(s,"dataops"),!0)).filter(i))o.dataops.add(f);let a=new Set(t.resolved.resources.map(f=>f.name)),c=new Set([...o.ranks.keys(),...o.frozen,...o.dataops]),u=(await He(Oe(s,".."),!0)).filter(f=>f!==n&&f.startsWith(`${n}-`)),d=`env-${n}-`,l=du(e.journalDir,qe);for(let f of await He(Oe(e.journalDir,qe),!1)){if(!f.endsWith(".ndjson")||!f.startsWith(d))continue;let h=f.slice(0,-7),m=U$.exec(h.slice(d.length));if(m?.[1]===void 0||m[2]===void 0)continue;let g=m[1],w=a.has(g)||c.has(g),y=u.find(k=>h.startsWith(`env-${k}-`));if(y!==void 0&&!w)continue;let v=Oe(e.journalDir,qe,f),b=await l.get(h);if(b===void 0)throw new Y("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}. ${de}`);if(b.targetOrganizationId===void 0)throw new Y("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}. ${de}`);if(ke(b.targetOrganizationId,r)){if(y!==void 0)throw new Y("RUN_UNCLAIMED",`The seed run file ${v} may be run ${m[2]} of ${g} of ${n}, or a run of ${y}, 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 ${y}'s. ${de}`);if(!w){o.unclaimed.push({file:v,resource:g,run:b});continue}Oc(o,g,Number(m[2])).seedRuns.push({runId:h,run:b})}}return o}async function ko(e,t){try{let n=await Kg(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 Y}}function V$(e){let t=e??{};return t.command==="replay"&&t.action==="replay"?"replay":typeof t.run=="number"&&Array.isArray(t.users)?"users":void 0}function lr(e){if(typeof e!="string")return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}async function Vg(e){try{return(await _$(e)).mtime.toISOString()}catch{return}}async function W$(e){let t=i=>new Y("RUN_UNREAD",`The summary ${e} does not read (${i}): a state rebuilt without it would leave what its run created to nobody. ${de}`),n;try{n=await Pt(e,"utf8")}catch(i){throw t(i instanceof Error?i.message:String(i))}let r;try{r=JSON.parse(n)}catch{throw t("not JSON")}let s=r?.tool,o=typeof s=="string"?z$[s]:V$(r);try{if(o==="users")return{kind:o,answer:Kt(n)};if(o==="replay")return{kind:o,answer:ts(n)};if(o==="seed")return{kind:o,answer:Ut(n)};if(o==="frozen")return{kind:o,answer:Gr(n)};if(o==="mask")return{kind:o,answer:Zr(n)};if(o==="forge"){let i=r,a=lr(i.finishedAt),c=typeof i.elapsedMs=="number"&&Number.isFinite(i.elapsedMs)&&i.elapsedMs>=0?i.elapsedMs:void 0;return{kind:o,answer:Rn(n),...a!==void 0?{finishedAt:a}:{},...c!==void 0?{elapsedMs:c}:{}}}}catch(i){throw i instanceof ce?t(i.message):i}throw t("it names no script of an environment")}function Wg(e){return e.removal!==void 0&&To(e).length===0}function H$(e){return e.interrupted===!0||e.result.cancelled===!0?"applying":e.result.status==="success"?"applied":e.result.status==="partial"?"partial":"failed"}function fr(e){return e.map(t=>({objectApiName:t.object,created:t.created,refused:t.refused}))}function wo(e,t,n){if(!(t===void 0||ke(t,n.target.organizationId)))throw new Y("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. ${de}`)}async function Y$(e,t,n,r,s,o){let i=t.resolved.checked.file.name,a=g=>e.store.fileOf(t.target.organizationId,i,g);if(s.seedRuns.length>1)throw new Y("RUNS_CONFLICT",`Two seed runs are kept for run ${r} of ${n}: ${s.seedRuns.map(g=>g.runId).join(", ")}. One rank is one run: the state they come from cannot be told. ${de}`);let c=s.seedRuns[0],u=o?.kind==="seed"?o.answer:void 0,d=u?.result.operationId??c?.runId;if(u!==void 0&&c!==void 0&&u.result.operationId!==c.runId)throw new Y("RUNS_CONFLICT",`The summary of run ${r} of ${n} is of the run ${u.result.operationId}, and the seed run file of that rank of ${c.runId}: one rank is one run. ${de}`);if(u!==void 0&&!u.result.operationId.startsWith(`env-${i}-${n}-${r}-`))throw new Y("RUNS_CONFLICT",`The summary ${a(oe(n,r))} is of the run ${u.result.operationId}, which is not run ${r} of ${n}. ${de}`);let l=c!==void 0&&Wg(c.run);if(u!==void 0&&!l){let g=await Pt(a(Go(n,r)),"utf8").catch(()=>{}),w;try{w=g!==void 0?JSON.parse(g):void 0}catch{w=void 0}let y=w?.runId===u.result.operationId?lu(w):void 0;l=y!==void 0&&u.result.objectResults.every(v=>v.truncated!==!0)&&To(Au({runId:u.result.operationId,targetOrgId:u.target,status:u.result.status,objectResults:u.result.objectResults},y)).length===0}let f=lr(u?.startedAt)??lr(c?.run.startedAt)??new Date(0).toISOString(),h=lr(u!==void 0?u.finishedAt:c?.run.end?.at),m=u!==void 0?fr(ss(u).objects):(c?.run.created??[]).map(g=>({objectApiName:g.objectApiName,created:g.ids.length,refused:0}));return{run:{n:r,script:"sandforge-seed",...d!==void 0?{runId:d}:{},...s.summary!==void 0&&u!==void 0?{summary:s.summary}:{},...u!==void 0?{seed:u.seed}:{},startedAt:f,...h!==void 0?{endedAt:h}:{},objects:m,...l?{takenBack:!0}:{}},status:u!==void 0?H$(u):"applying"}}async function J$(e,t,n,r,s){let o=t.resolved.checked.file.name,i=oe(n,r),a=e.store.fileOf(t.target.organizationId,o,i),{answer:c}=s,u=!1,d=await Pt(e.store.fileOf(t.target.organizationId,o,Go(n,r)),"utf8").catch(()=>{});if(d!==void 0){let g=await Ar(a,await Pt(a,"utf8"),t.target.alias,Sr(e.journalDir));if(!("refusal"in g)){let w=Tu(d,Nu(Pu(g.summary)));u="earlier"in w&&w.earlier?.removalLeft?.length===0}}let l=c.running===!0||c.interrupted===!0?void 0:s.finishedAt,f=s.finishedAt??await Vg(a)??new Date(0).toISOString(),h=new Date(Date.parse(f)-(s.elapsedMs??0)).toISOString(),m=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:i,startedAt:h,...l!==void 0?{endedAt:l}:{},objects:fr(Jr(c).objects),...u?{takenBack:!0}:{}},status:m}}async function vo(e,t,n){let r=t.resolved.checked.file.name,s=a=>a!==void 0?Vg(e.store.fileOf(t.target.organizationId,r,a)):Promise.resolve(void 0),o=await s(n.template),i=await s(n.summary);return{startedAt:o??i??new Date(0).toISOString(),...i!==void 0?{endedAt:i}:{}}}async function G$(e,t){if((await He(e,!1)).some(o=>K$.test(o)))return!1;let n=new Be,r=(await fn(e,n)).find(o=>ke(o,t));if(r===void 0)return!1;let s=await new jr(e,{orgId:r,guard:n}).recordedLoads();return s.length>0&&s.some(o=>o.removal!==void 0)&&s.every(o=>o.created!==void 0&&qu(o).length===0)}async function Q$(e,t){let n=(await fn(e,new Be)).filter(r=>!ke(r,t.target.organizationId));if(n.length!==0)throw new Y("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. ${de}`)}function X$(e){let t=jn(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 Z$(e){return e.status==="success"?"applied":e.status==="partial"?"partial":e.status==="cancelled"?"applying":"failed"}function eA(e){return e.exit===0?"applied":e.exit===3?"partial":"failed"}var tA=p.object({run:p.number().int().positive(),replaces:p.number().int().positive().optional(),startedAt:p.string().optional(),removals:p.array(p.object({status:p.string()}).loose()).optional()}).loose();function Hg(e,t){return Oe(e.journalDir,"users",pe(t.target.organizationId))}async function Yg(e,t,n){let r=await Pt(Oe(Hg(e,t),`run-${n}.json`),"utf8").catch(()=>{});if(r!==void 0)try{let s=tA.safeParse(JSON.parse(r));return!s.success||s.data.run!==n?void 0:{...s.data.replaces!==void 0?{replaces:s.data.replaces}:{},takenBackWhole:s.data.removals?.at(-1)?.status==="success"}}catch{return}}async function nA(e,t,n){let r=Hg(e,t),s=[];for(let o of await He(r,!1)){let i=Number(/^run-([1-9]\d{0,5})\.json$/.exec(o)?.[1]??0);i===0||n.has(i)||(await Yg(e,t,i))?.takenBackWhole===!0||s.push(`${Oe(r,o)}: run ${i} of ${B("users")}, which no summary names \u2014 a run of a users resource stopped before it answered, or one run alone: the state holds it not; ${B("users")} remove --org ${t.target.alias} --run ${i} takes it back`)}return s}async function rA(e,t,n){let r=t.resolved.checked.file.name,s=new Set;for(let o of n)if(o.state.kind==="users")for(let i of o.state.runs){if(i.summary===void 0)continue;let a=e.store.fileOf(t.target.organizationId,r,i.summary),c=await Pt(a,"utf8").catch(()=>{}),u=c!==void 0?In(c):void 0;u!==void 0&&s.add(u)}return s}function sA(e){let t=Cn(e);return t.refusal!==void 0?"failed":t.short!==void 0||t.objects.some(n=>n.notMasked>0)?"partial":"applied"}function oA(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 Y("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. ${de}`);return[...r][0]}async function iA(e,t,n,r){let s=t.resolved.checked.file.name,o=t.target.organizationId,i=n.ranks.get(r)??new Map,a=new Map;for(let[y,v]of i)v.summary!==void 0&&a.set(y,await W$(e.store.fileOf(o,s,v.summary)));let c=oA(r,n,a);if(c===void 0)return;for(let[y,v]of a){let b=e.store.fileOf(o,s,oe(r,y));v.kind==="seed"&&wo(b,v.answer.targetOrgId,t),v.kind==="forge"&&wo(b,v.answer.targetOrgId,t),v.kind==="users"&&wo(b,v.answer.org.organizationId,t),v.kind==="replay"&&wo(b,v.answer.target.organizationId,t)}let u=[],d=[...i.keys()].sort((y,v)=>y-v);if(c==="seed")for(let y of d){let v=i.get(y);v===void 0||v.summary===void 0&&v.seedRuns.length===0||u.push(await Y$(e,t,r,y,v,a.get(y)))}else if(c==="forge")for(let y of d){let v=a.get(y);v?.kind==="forge"&&u.push(await J$(e,t,r,y,v))}else if(c==="frozen"){let y=e.store.sasOf(o,s,tt(r));await Q$(y,t);let v=await G$(y,o);for(let b of d){let k=i.get(b),E=a.get(b);if(k?.template===void 0){if(E?.kind!=="frozen"||v)continue;throw new Y("RUN_UNREAD",`Run ${b} of ${r} keeps its summary and not the payload its load was given, ${e.store.fileOf(o,s,bt(r,b))}, which its removal is run from: a state rebuilt without it would leave what the load created to nobody. ${de}`)}let S=E?.kind==="frozen"?E.answer:void 0;if(u.push({run:{n:b,script:"sandforge-frozen",sas:tt(r),...S!==void 0&&k.summary!==void 0?{summary:k.summary}:{},...await vo(e,t,k),objects:S!==void 0?fr(jn(S).objects):[],...v?{takenBack:!0}:{}},status:S!==void 0?X$(S):"applying"}),S!==void 0&&Qr(S))for(let $ of u.slice(0,-1))$.run.takenBack=!0}}else if(c==="users")for(let y of d){let v=i.get(y),b=a.get(y);if(v?.summary===void 0||b?.kind!=="users")continue;let k=await Yg(e,t,b.answer.run);if(k?.replaces!==void 0)for(let E of u)E.users===k.replaces&&(E.run.takenBack=!0);u.push({run:{n:y,script:"sandforge-users",summary:v.summary,...await vo(e,t,v),objects:fr(os(b.answer).objects),...k?.takenBackWhole===!0?{takenBack:!0}:{}},status:Z$(b.answer),users:b.answer.run})}else if(c==="replay")for(let y of d){let v=i.get(y),b=a.get(y);if(!(v?.summary===void 0||b?.kind!=="replay")&&(u.push({run:{n:y,script:"sandforge-checkpoint",summary:v.summary,...await vo(e,t,v),objects:fr(ns(b.answer).objects)},status:eA(b.answer)}),rs(b.answer)))for(let k of u.slice(0,-1))k.run.takenBack=!0}else{let y=!n.dataops.has(r);for(let v of d){let b=i.get(v),k=a.get(v);if(b===void 0)continue;let E=k?.kind==="mask"?k.answer:void 0;if(E===void 0&&y)continue;let S=E!==void 0?Cn(E):void 0;u.push({run:{n:v,script:"sandforge-dataops",...E!==void 0&&b.summary!==void 0?{summary:b.summary}:{},...S?.snapshotId!==void 0?{snapshotId:S.snapshotId}:{},...await vo(e,t,b),objects:(S?.objects??[]).map($=>({objectApiName:$.object,created:0,refused:$.refused,masked:$.masked})),...y?{takenBack:!0}:{}},status:E!==void 0?sA(E):"applying"})}}if(u.length===0)return;let l=u.map(y=>y.run),f=u.at(-1),h=l.every(y=>y.takenBack===!0)?"destroyed":f?.run.takenBack===!0?"partial":f?.status??"applying",m=t.resolved.resources.find(y=>y.name===r),g=l.flatMap(y=>y.endedAt!==void 0?[y.endedAt]:[]).sort(),w=l.map(y=>y.startedAt).sort();return{name:r,state:{kind:c,fingerprint:Yc,dependsOn:m!==void 0?[...m.dependsOn]:[],status:h,runs:l,recovered:!0},firstStartedAt:w[0]??new Date(0).toISOString(),...g.length>0?{lastEndedAt:g.at(-1)}:{}}}async function aA(e,t,n){let r=t.resolved.checked.file,o=(await new mu({root:Z(e.journalDir),locksDir:e.locksDir}).list({organizationId:t.target.organizationId})).flatMap(l=>l.valid&&l.checkpoint!==void 0?[l.checkpoint]:[]),i=[],a={},c=`${r.name} before`,u=o.filter(l=>l.name===c&&Date.parse(l.takenAt)<=Date.parse(n.first));u.length===1&&u[0]!==void 0?a.before=u[0].checkpointId:vn(r,"before")===void 0&&u.length===0?i.push("checkpoint.before: the file asks none"):i.push(`checkpoint.before: ${u.length===0?"no":`${u.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 d=vn(r,"after");if(d===void 0)i.push("checkpoint.after: the file asks none");else{let l=n.last,f=o.filter(h=>h.name===d&&l!==void 0&&Date.parse(h.readFrom)>=Date.parse(l));f.length===1&&f[0]!==void 0?a.after=f[0].checkpointId:i.push(`checkpoint.after: ${f.length===0?"no":`${f.length}`} checkpoint(s) of this org named '${d}' taken after the last run: none is linked, and reset has none to rewind to until an apply takes it`)}return{...a,notLinked:i}}function cA(e,t){let n=o=>{let i=/^(\d+)\.(\d+)\.(\d+)/.exec(o);return i?[Number(i[1]),Number(i[2]),Number(i[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 o=0;o<3;o++)if((r[o]??0)!==(s[o]??0))return(r[o]??0)>(s[o]??0);return!1}async function uA(e,t){let n=t.resolved.checked.file.name,{alias:r,organizationId:s}=t.target;try{let u=await e.store.read(s,n);if(u===void 0)return{damaged:!1};throw new Y("STATE_KEPT",`This machine keeps a state of ${n} on ${r} that reads, serial ${u.serial}: state recover never writes over one, and plan reads it. ${de}`)}catch(u){if(!(u instanceof L))throw u;if(u.code!=="damaged"){let d=Ze(u);throw new Y(d.code,d.message)}}let o=e.store.stateFileOf(s,n),i;try{i=JSON.parse(await Pt(o,"utf8"))}catch{i=void 0}let a=i,c=a?.version;if(typeof c=="number"&&c>1||cA(a?.sandforgeVersion,e.sandforgeVersion))throw new Y("STATE_NEWER",`The state ${o} was written by a later SandForge (${String(a?.sandforgeVersion??`version ${String(c)}`)}; this one is ${e.sandforgeVersion}): update it, and plan again. ${de}`);return{damaged:!0}}async function Jg(e,t){let n=t.resolved.checked.file.name,{target:r}=t,s=Je(e.locksDir,r.organizationId,{operation:"recover",env:n,alias:r.alias},e.lockOptions);if("busy"in s)return{refusal:et(s.busy)};try{let{damaged:o}=await uA(e,t),i=await Kg(e,t),a=[];for(let k of[...i.ranks.keys(),...i.frozen,...i.dataops]){if(a.some(S=>S.name===k))continue;let E=await iA(e,t,i,k);E!==void 0&&a.push(E)}let c=[];for(let k of i.unclaimed){if(Wg(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 Y("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. ${de}`)}if(a.length===0)throw new Y("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. ${de}`);a.sort((k,E)=>Date.parse(k.firstStartedAt)-Date.parse(E.firstStartedAt)||k.name.localeCompare(E.name));let u=a[0]?.firstStartedAt??new Date(0).toISOString(),l=a.flatMap(k=>k.lastEndedAt!==void 0?[k.lastEndedAt]:[]).sort().at(-1),f=await aA(e,t,{first:u,...l!==void 0?{last:l}:{}}),h=a.some(k=>k.state.kind==="users")||t.resolved.resources.some(k=>k.kind==="users")?await nA(e,t,await rA(e,t,a)):[],g={...Fr({env:n,org:{organizationId:r.organizationId,kind:r.kind,username:r.username,alias:r.alias,...r.host!==void 0?{host:r.host}:{}},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}:{}}}:{}},w=dn.safeParse({...g,serial:1});if(!w.success){let k=w.error.issues[0];throw new Y("RUN_UNREAD",`The run files of ${n} do not make a state (${k?.path.join(".")??""}: ${k?.message??"refused"}). ${de}`)}let y=o?await e.store.setAside(r.organizationId,n):void 0,v=await e.store.write(g,{serial:0,lineage:g.lineage}),b=new Set(t.resolved.resources.map(k=>k.name));return{state:v,result:{env:n,org:{organizationId:v.org.organizationId,kind:v.org.kind,alias:r.alias},state:{serial:v.serial,lineage:v.lineage},...y!==void 0?{setAside:y}:{},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:b.has(k.name)}])),checkpoints:{...f.before!==void 0?{before:f.before}:{},...f.after!==void 0?{after:f.after}:{}},notLinked:[...f.notLinked,...c,...h].slice(0,20)}}}catch(o){if(o instanceof Y)return{refusal:{code:o.code,message:o.message,exit:1}};throw o}finally{s.lock.release()}}function Ug(e){return`${e.length===1?"run":"runs"} ${e.join(", ")}`}function Gg(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 o=s.takenBack.length===0?"":s.takenBack.length===s.runs.length?", taken back":`; ${Ug(s.takenBack)} taken back`;t.push(` ${r.padEnd(n)} ${s.kind}, ${s.status}: ${Ug(s.runs)}${o}`+(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 dA(e,t,n){let r=n.includes("users"),s=n.includes("mask")?", and what it masked left masked":"",o=": the state keeps it as destroyed";return r&&n.every(i=>i==="users"||i==="mask")?`${e} is taken back from ${t}, the assignments and memberships it created deleted and each user put back as it was, but for an address asked back${s}${o}, and the next apply sets them up again`:`every record of ${e} is taken back from ${t}${r?", each user put back as it was but for an address asked back":""}${s}${o}, and the next apply creates it again`}function lA(e){return ht(e,_e(e).map(([t])=>t))}async function Qg(e,t){let{plan:n,target:r,resolved:s}=t,o=s.checked.file.name,i=(f,h=[])=>({result:{plan:n,steps:[],status:"failure",refusal:f,...h.length>0?{refusalCodes:[...h]}:{},state:{serial:t.state?.serial??0}},exitCode:1});if(t.state===void 0)return await ko(e,{resolved:s,target:r})?i(`This machine keeps no state of ${o} 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. "${B("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 ${o} 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 i(n.refusal,n.refusalCodes);let a=lA(t.state),c=Je(e.locksDir,r.organizationId,{operation:"destroy",env:o,alias:r.alias},e.lockOptions);if("busy"in c){let f=et(c.busy);return i(f.message,[f.code])}let u=new AbortController,d,l=(e.onStop??Ye)(f=>{d=f,e.say(`
152
- stopped by ${f}: the removal under way stops before its next call to the org; destroy again takes up from the state`),u.abort()});try{let f;try{let $=await e.store.read(r.organizationId,o);if($===void 0||$.serial!==t.state.serial||$.lineage!==t.state.lineage)return i(`The state of ${o} 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.`,[Vr]);f=$}catch($){if($ instanceof L)return i($.message,[Ze($).code]);throw $}let h=[],m=[],g=[],w=!1,y,v;for(let[$,j]of a.entries()){if(d!==void 0||y!==void 0){v??=$;break}let A=$r(e.locksDir,r.organizationId,e.lockOptions);if(A!==void 0){e.say(En(A).message),g.push(1),v=$;break}let P=t.acceptAutomation||s.checked.file.resources[j]?.accept?.automation===!0,D=await Rc(e,f,{resource:j,action:"delete",target:r,includeChanged:t.includeChanged,sweep:t.sweep,acceptAutomation:P,ends:{whole:"destroyed",left:"partial"}},u.signal);if(f=D.state,h.push(...D.steps),w||=D.wrote,we(D.code)){y=D.code,v=$+1;break}if(g.push(D.code),D.code!==0&&D.code!==3){v=$+1;break}}for(let $ of v!==void 0?a.slice(v):[])m.push({resource:$,why:d!==void 0||y!==void 0?"the destroy was stopped before it":"a removal before it was refused or failed: its records would be kept for it"});let b=Object.values(f.resources).every($=>$.status==="destroyed"),k=[];if(b&&v===void 0){e.say(dA(o,r.alias,Object.values(f.resources).map($=>$.kind)));for(let{step:$,checkpoint:j}of Ur(f)){let A=await zt(e,{org:{alias:r.alias,kind:r.kind},checkpoint:j,why:"the environment it was taken of is taken back"},u.signal);k.push(A),A.exitCode===0&&(f=await e.store.update(f,P=>Xe(P,$,void 0)))}}let E=d!==void 0?Pe(d):y!==void 0?y:(()=>{let $=ln(g);return $===1&&w?3:$})();return{result:{plan:n,steps:h,...k.length>0?{checkpoints:k}:{},...m.length>0?{skipped:m}:{},status:go(E),state:{serial:f.serial}},exitCode:E}}finally{l(),c.lock.release()}}import{readFileSync as fA}from"node:fs";var pA="taken back by a destroy: none of the org's records is its",hA="taken back by a destroy, which deleted its store and left its records masked: a masking creates no record",Xg="a masking creates no record: it writes over those the org holds that its condition selects",Zg="a users resource creates no record of its own: it sets up users the org holds, named here";function mA(e,t,n){if(e?.summary===void 0)return{refusal:"its last run stopped before it answered: it names no user"};try{let r=fA(n.store.fileOf(t.organizationId,t.env,e.summary),"utf8");return{users:np(Kt(r))}}catch(r){if(r instanceof ce||r instanceof Error)return{refusal:`its last run's summary does not read: ${r.message}`};throw r}}var gA={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 jc(e){return`${gA[e]??e}: it names no record until it is applied whole \u2014 apply again`}function yA(e){let t=e.filter(i=>i.state!==void 0);if(t.length!==e.length)return;let n=i=>Date.parse(i.state.updatedAt),[r,...s]=[...t].sort((i,a)=>n(a)-n(i));return r===void 0?void 0:s.every(i=>n(i)<n(r)&&kt(i.state.org,r.state.org))?{current:r,before:s}:void 0}function ey(e,t,n){let r=t.state!==void 0?` (serial ${t.state.serial}, written ${t.state.updatedAt})`:"";return`${e}: the state of ${t.env} kept under ${t.organizationId}${r} is of this sandbox before its refresh, set aside: output reads the one kept under `+n.org.organizationId}function ty(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))),s=r.length>1?yA(r):void 0;if(s!==void 0)return{state:s.current.state,setAside:s.before};if(r.length>1){let i=r.map(a=>`${a.organizationId}, written ${a.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[o]=r;return o===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}}:o.state===void 0?{refusal:{code:"STATE_DAMAGED",message:`${o.damaged??"The state does not read."} Nothing was read.`,exit:1}}:{state:o.state}}async function Cc(e,t){let n={organizationId:e.org.organizationId,env:e.env,target:e.org.alias??e.org.organizationId},r=fc(Object.keys(e.resources),i=>e.resources[i]?.dependsOn??[]),s={},o=!0;for(let i of r){let a=e.resources[i];if(a===void 0)continue;let c=a.runs.at(-1),u={kind:a.kind,status:a.status,...c!==void 0?{run:c.n}:{},records:{}};if(a.status==="destroyed"){s[i]={...u,why:a.kind==="mask"?hA:pA};continue}if(a.status!=="applied"&&(o=!1),a.kind==="mask"){s[i]={...u,masked:Object.fromEntries((c?.objects??[]).map(l=>[l.objectApiName,l.masked??0])),...c?.snapshotId!==void 0?{snapshotId:c.snapshotId}:{},why:a.status==="applied"?Xg:`${jc(a.status)}; ${Xg}`};continue}if(a.kind==="users"){let l=[...a.runs].reverse().find(h=>h.takenBack!==!0),f=mA(l,n,t);"refusal"in f&&(o=!1),s[i]={...u,..."users"in f?{users:f.users}:{},why:"refusal"in f?f.refusal:a.status==="applied"?Zg:`${jc(a.status)}; ${Zg}`};continue}if(a.status!=="applied"){s[i]={...u,why:jc(a.status)};continue}if(c===void 0||c.takenBack===!0){o=!1,s[i]={...u,why:"it holds no run whose records are in the org"};continue}let d=await dr(c,n,t);if("refusal"in d){o=!1,s[i]={...u,why:d.refusal};continue}s[i]={...u,records:Object.fromEntries(d.created)}}return{output:{env:e.env,org:{organizationId:e.org.organizationId,kind:e.org.kind,...e.org.alias!==void 0?{alias:e.org.alias}:{},...e.org.host!==void 0?{host:e.org.host}:{}},state:{serial:e.serial,updatedAt:e.updatedAt},resources:s},whole:o}}function ny(e){let{org:t}=e,n=t.kind==="sandbox"?Ne(t.host):void 0,r=[`${e.env} on ${t.alias??t.organizationId} (${t.kind}${n!==void 0?` ${n}`:""}, ${t.organizationId}): state serial ${e.state.serial}, written ${e.state.updatedAt}`];for(let[s,o]of Object.entries(e.resources)){r.push(` ${s} ${o.kind}, ${o.status}`+(o.run!==void 0?`, run ${o.run}`:""));for(let[i,a]of Object.entries(o.records))r.push(` ${i} ${a.length>0?a.join(" "):"none"}`);for(let[i,a]of Object.entries(o.masked??{}))r.push(` ${i} ${a} masked`);for(let i of o.users??[])r.push(` User ${i.username} ${i.userId}`);o.snapshotId!==void 0&&r.push(` snapshot ${o.snapshotId}, taken first`),o.why!==void 0&&r.push(` ${o.why}`)}return r}var ry={reset:"after",destroy:"before"};function Ic(e,t){let n=ry[e],r=t?.checkpoints?.[n];return r!==void 0?{step:n,checkpoint:r}:void 0}function Dc(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",o=e.state;if(o===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(Ic(e.verb,o)===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 i=Object.entries(o.resources).filter(([,a])=>a.kind==="mask");if(e.verb==="destroy"&&i.length>0)return{code:"MASKED",message:`The state of ${t} on ${n} names mask resources (${i.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(o.resources).filter(([,c])=>c.status!=="applied"&&c.status!=="destroyed");if(a.length>0)return r(`${a.map(([c,u])=>`${c} is ${u.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 sy(e,t,n){let r=Ic(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(ye,ri({org:t.target.alias,store:Z(e.journalDir),checkpoint:r.checkpoint,dryRun:!0,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails,acceptNoUndo:t.acceptNoUndo,acceptUnseen:t.acceptUnseen}),n);return vd(s)}var Nt=e=>e.toLocaleString("en-US");function oy(e,t){let{alias:n}=e.target,r=`it deletes ${Nt(t.toDelete)} record(s) created since, gives ${Nt(t.toGiveBack)} their values back and brings ${Nt(t.toBringBack)} back from the recycle bin \u2014 whoever made these changes`+(Kr(t.lastChangedBy)!==""?`, last changed by ${Kr(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 wA(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 iy(e,t,n){let{target:r,resolved:s,verb:o}=t,i=s.checked.file.name,a=Ic(o,t.state),c={env:i,org:{organizationId:r.organizationId,kind:r.kind,alias:r.alias},verb:o,checkpoint:{step:ry[o],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}}:{}},u=(w,y)=>({result:{...c,exitCode:1,status:"failure",undo:{offered:!1,why:"nothing was rewound"},refusal:w,state:{serial:y}},exitCode:1}),d=Dc(t);if(d!==void 0||a===void 0||t.state===void 0)throw new Error(d?.message??"There is no checkpoint to rewind to.");let l=t.state,f=Je(e.locksDir,r.organizationId,{operation:o,env:i,alias:r.alias},e.lockOptions);if("busy"in f)return u(et(f.busy).message,l.serial);let h=new AbortController,m,g=(e.onStop??Ye)(w=>{m=w,e.say(`
153
- stopped by ${w}: the rewind stops before its next call to the org, and leaves its journal: run this again to take it up`),h.abort()});try{let w;try{let $=await e.store.read(r.organizationId,i);if($===void 0||$.serial!==l.serial||$.lineage!==l.lineage)return u(`The state of ${i} 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.`,$?.serial??l.serial);w=$}catch($){if($ instanceof L)return u($.message,l.serial);throw $}e.say(`${o==="reset"?"reset":"destroy --rewind"}: rewinding ${r.alias} to checkpoint ${a.checkpoint}`);let y=await e.runner(ye,ri({org:r.alias,store:Z(e.journalDir),checkpoint:a.checkpoint,dryRun:!1,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails,acceptNoUndo:t.acceptNoUndo,acceptUnseen:t.acceptUnseen}),h.signal),v=bd(y),b=m!==void 0?Pe(m):v.exitCode,k=[];if(o==="destroy"&&b===0){w=await e.store.update(w,wA);for(let{step:$,checkpoint:j}of Ur(w)){let A=await zt(e,{org:{alias:r.alias,kind:r.kind},checkpoint:j,why:"the environment it was taken of is taken back"},h.signal);k.push(A),A.exitCode===0&&(w=await e.store.update(w,P=>Xe(P,$,void 0)))}e.say(`every record of ${i} 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 E=Ed({verb:o,alias:r.alias,checkpoint:a.checkpoint,journalDir:e.journalDir,deleted:k.length>0&&k.every($=>$.exitCode===0)},v),S=v.refusal===void 0?void 0:v.refusal.code==="RECREATE"?`${v.refusal.message} ${o==="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:b,status:m!==void 0?"cancelled":v.status,...v.answer!==void 0?{answer:v.answer}:{},undo:E,...S!==void 0?{refusal:S.slice(0,8e3)}:{},...k.length>0?{deleted:k}:{},state:{serial:w.serial}},exitCode:b}}finally{g(),f.lock.release()}}function ay(e){let t=e.verb==="reset"?"reset":"destroy --rewind",n=[""],r=e.answer;if(r?.deleted!==void 0){let s=(r.residual??[]).reduce((o,i)=>o+i.count,0);n.push(` rewind to ${e.checkpoint.id}: exit ${e.exitCode}, ${e.status} ${Nt(r.deleted.done)} deleted, ${Nt(r.givenBack?.done??0)} given back, ${Nt(r.broughtBack?.done??0)} brought back`+(s>0?`, ${Nt(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(Rd(e.undo)),n.push(`${t}: ${e.status}; state serial ${e.state.serial}`),n}import{randomBytes as vA}from"node:crypto";import{existsSync as kA,readFileSync as bA,statSync as EA}from"node:fs";import{open as RA,rename as SA,rm as $A}from"node:fs/promises";import{dirname as AA,resolve as Pc}from"node:path";var dy=1440*6e4;function ly(e){let t={};for(let[o,i]of Object.entries(e.dryRuns))"answer"in i&&i.answer.tool===re&&(t[o]=i.answer.seed);let{host:n,...r}=e.plan.org,s=n!==void 0&&e.listedByMyDomain===!0?e.plan:{...e.plan,org:r};return Io.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:s})}function fy(e,t,n){let r=AA(Pc(t));if(!kA(r)||!EA(r).isDirectory())return{code:"BAD_LINE",message:`--out ${Pc(t)}: its folder ${r} is not there. Nothing was read.`,exit:2};if(n)return;let s=mn(e,t);if(s!==void 0)return{code:"PLAN_IN_REPOSITORY",message:`--out ${Pc(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 py(e,t){let n=`${e}.${vA(6).toString("hex")}.tmp`,r=await RA(n,"wx",Yo);try{await r.writeFile(`${JSON.stringify(t,null,2)}
154
- `,"utf8"),await r.sync()}finally{await r.close()}try{await SA(n,e)}catch(s){throw await $A(n,{force:!0}),s}}function hy(e){let t=o=>({refusal:{code:"PLAN_UNREAD",message:`--plan ${e} ${o}. Nothing was read or written.`,exit:2}}),n;try{n=bA(e,"utf8")}catch(o){return t(`cannot be read: ${o instanceof Error?o.message:String(o)}`)}let r;try{r=JSON.parse(n)}catch{return t("is not JSON: it is no plan plan --out kept")}let s=Io.safeParse(r);if(!s.success){let o=s.error.issues[0],i=o?.path.map(String).join(".")||"the plan";return t(`is no plan plan --out kept (${i}: ${o?.message??"refused"})`)}return{saved:s.data}}function an(e,t){return{code:"PLAN_STALE",message:`The plan kept in ${e} ${t}. Nothing was written: plan again.`.slice(0,8e3),exit:1}}function my(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 an(t,"was made with --quick, which counts nothing an apply is held to");if(e.sandforgeVersion!==n.sandforgeVersion)return an(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)>dy)return an(t,`was made at ${e.madeAt}, more than a day ago`)}function OA(e){return e.found?`the state at serial ${e.serial}`:"no state"}function gy(e,t,n){let r=e.plan.org;if(!ke(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(r.host!==void 0&&r.host!==n.target.host)return{code:"PLAN_OTHER_ORG",message:`The plan kept in ${t} was made for ${r.alias??r.organizationId} on ${r.host}, and ${n.target.alias} answers on ${n.target.host??"no My Domain host"}: a plan is applied to the org it was made for. Nothing was written.`,exit:1};if(e.file.digest!==n.digest)return an(t,"was made from another file: the file, or a variable or an alias it reads, changed since");let s=n.state,o=e.state;if(!(o.found===(s!==void 0)&&(!o.found||s!==void 0&&s.serial===o.serial&&s.lineage===o.lineage))){let a=s===void 0?"none":o.found&&s.lineage!==o.lineage?`at serial ${s.serial}, made again since`:`at serial ${s.serial}`;return an(t,`was made against ${OA(o)}, and the state is now ${a}: an apply or a destroy ran since, or a cache put back another state`)}}function cy(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 uy(e){if(e===void 0)return"nothing of it";let t=wc(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 bo(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 Eo(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 yy(e,t){let n=[],r=[...new Set([...e.actions,...t.actions].map(o=>o.resource))];for(let o of r){let i=e.actions.find(c=>c.resource===o),a=t.actions.find(c=>c.resource===o);i!==void 0&&a!==void 0&&cy(i)===cy(a)||n.push(`${o}: planned ${uy(i)}, now ${uy(a)}`)}let s=o=>o.actions.map(i=>i.resource).join(", ");return n.length===0&&s(e)!==s(t)&&n.push(`the order of the resources: planned ${s(e)}, now ${s(t)}`),bo(e)!==bo(t)&&n.push(`the checkpoints it takes: planned ${bo(e)}, now ${bo(t)}`),Eo(e)!==Eo(t)&&n.push(`the whole org against the checkpoint after the last apply: planned ${Eo(e)}, now ${Eo(t)}`),n}function wy(e,t){return an(e,`is not what the org holds now, read again: ${t.join("; ")}`)}function vy(e,t){let n=new Date(Date.parse(t.madeAt)+dy).toISOString();return`plan kept in ${e}, for apply --plan until ${n}`}function ky(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 PA=`sandforge env \u2014 apply a sandforge.yaml to an org: the data an environment needs, declared in
151
+ `}function Vg(e,t){if(!/^[a-z][a-z0-9-]{0,62}$/.test(t.env))throw new Error(`Not an environment's name: "${t.env}"`);let n=new Date(t.at).toISOString().replace(/[-:.]/g,"");return N$(T$(e),"handoff",t.env,`${n}-${pe(t.organizationId)}.md`)}async function Wg(e,t){await j$(P$(e),{recursive:!0,mode:x$});let n=`${e}.${process.pid}-${O$(4).toString("hex")}.tmp`,r=await C$(n,"wx",L$);try{try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await I$(n,e)}catch(s){throw await D$(n,{force:!0}),s}}import{readFile as Nt,readdir as B$,stat as U$}from"node:fs/promises";import{join as Oe}from"node:path";var K$={"sandforge-seed":"seed","sandforge-clone":"forge","sandforge-frozen":"frozen","sandforge-dataops":"mask"},V$=/^([1-9][0-9]{0,5})\.summary\.json$/,W$=/^([a-z][a-z0-9-]{0,62})\.([1-9][0-9]{0,5})\.json$/,H$=/^([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}$/,Y$=/\.load-\d{1,16}\.ndjson$/,Y=class extends Error{constructor(n,r){super(r);this.code=n;this.name="Refused"}code},de="Nothing was written.";async function Je(e,t){try{return(await B$(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 jc(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 Yg(e,t){let n=t.resolved.checked.file.name,r=t.target.organizationId,s=e.store.folderOf(r,n),o={ranks:new Map,frozen:new Set,dataops:new Set,unclaimed:[]},i=l=>dn.safeParse(l).success;for(let l of(await Je(Oe(s,"runs"),!0)).filter(i))for(let h of await Je(Oe(s,"runs",l),!1)){let m=V$.exec(h)?.[1];m!==void 0&&(jc(o,l,Number(m)).summary=oe(l,Number(m)))}for(let l of await Je(Oe(s,"templates"),!1)){let h=W$.exec(l);h?.[1]===void 0||h[2]===void 0||!i(h[1])||(jc(o,h[1],Number(h[2])).template=Et(h[1],Number(h[2])))}for(let l of(await Je(Oe(s,"frozen"),!0)).filter(i))o.frozen.add(l);for(let l of(await Je(Oe(s,"dataops"),!0)).filter(i))o.dataops.add(l);let a=new Set(t.resolved.resources.map(l=>l.name)),c=new Set([...o.ranks.keys(),...o.frozen,...o.dataops]),u=(await Je(Oe(s,".."),!0)).filter(l=>l!==n&&l.startsWith(`${n}-`)),f=`env-${n}-`,d=pu(e.journalDir,Be);for(let l of await Je(Oe(e.journalDir,Be),!1)){if(!l.endsWith(".ndjson")||!l.startsWith(f))continue;let h=l.slice(0,-7),m=H$.exec(h.slice(f.length));if(m?.[1]===void 0||m[2]===void 0)continue;let g=m[1],w=a.has(g)||c.has(g),y=u.find(k=>h.startsWith(`env-${k}-`));if(y!==void 0&&!w)continue;let v=Oe(e.journalDir,Be,l),b=await d.get(h);if(b===void 0)throw new Y("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}. ${de}`);if(b.targetOrganizationId===void 0)throw new Y("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}. ${de}`);if(ke(b.targetOrganizationId,r)){if(y!==void 0)throw new Y("RUN_UNCLAIMED",`The seed run file ${v} may be run ${m[2]} of ${g} of ${n}, or a run of ${y}, 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 ${y}'s. ${de}`);if(!w){o.unclaimed.push({file:v,resource:g,run:b});continue}jc(o,g,Number(m[2])).seedRuns.push({runId:h,run:b})}}return o}async function bo(e,t){try{let n=await Yg(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 Y}}function J$(e){let t=e??{};return t.command==="replay"&&t.action==="replay"?"replay":typeof t.run=="number"&&Array.isArray(t.users)?"users":void 0}function fr(e){if(typeof e!="string")return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}async function Jg(e){try{return(await U$(e)).mtime.toISOString()}catch{return}}async function G$(e){let t=i=>new Y("RUN_UNREAD",`The summary ${e} does not read (${i}): a state rebuilt without it would leave what its run created to nobody. ${de}`),n;try{n=await Nt(e,"utf8")}catch(i){throw t(i instanceof Error?i.message:String(i))}let r;try{r=JSON.parse(n)}catch{throw t("not JSON")}let s=r?.tool,o=typeof s=="string"?K$[s]:J$(r);try{if(o==="users")return{kind:o,answer:Vt(n)};if(o==="replay")return{kind:o,answer:ns(n)};if(o==="seed")return{kind:o,answer:Kt(n)};if(o==="frozen")return{kind:o,answer:Qr(n)};if(o==="mask")return{kind:o,answer:es(n)};if(o==="forge"){let i=r,a=fr(i.finishedAt),c=typeof i.elapsedMs=="number"&&Number.isFinite(i.elapsedMs)&&i.elapsedMs>=0?i.elapsedMs:void 0;return{kind:o,answer:Sn(n),...a!==void 0?{finishedAt:a}:{},...c!==void 0?{elapsedMs:c}:{}}}}catch(i){throw i instanceof ce?t(i.message):i}throw t("it names no script of an environment")}function Gg(e){return e.removal!==void 0&&xo(e).length===0}function Q$(e){return e.interrupted===!0||e.result.cancelled===!0?"applying":e.result.status==="success"?"applied":e.result.status==="partial"?"partial":"failed"}function pr(e){return e.map(t=>({objectApiName:t.object,created:t.created,refused:t.refused}))}function vo(e,t,n){if(!(t===void 0||ke(t,n.target.organizationId)))throw new Y("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. ${de}`)}async function X$(e,t,n,r,s,o){let i=t.resolved.checked.file.name,a=g=>e.store.fileOf(t.target.organizationId,i,g);if(s.seedRuns.length>1)throw new Y("RUNS_CONFLICT",`Two seed runs are kept for run ${r} of ${n}: ${s.seedRuns.map(g=>g.runId).join(", ")}. One rank is one run: the state they come from cannot be told. ${de}`);let c=s.seedRuns[0],u=o?.kind==="seed"?o.answer:void 0,f=u?.result.operationId??c?.runId;if(u!==void 0&&c!==void 0&&u.result.operationId!==c.runId)throw new Y("RUNS_CONFLICT",`The summary of run ${r} of ${n} is of the run ${u.result.operationId}, and the seed run file of that rank of ${c.runId}: one rank is one run. ${de}`);if(u!==void 0&&!u.result.operationId.startsWith(`env-${i}-${n}-${r}-`))throw new Y("RUNS_CONFLICT",`The summary ${a(oe(n,r))} is of the run ${u.result.operationId}, which is not run ${r} of ${n}. ${de}`);let d=c!==void 0&&Gg(c.run);if(u!==void 0&&!d){let g=await Nt(a(Qo(n,r)),"utf8").catch(()=>{}),w;try{w=g!==void 0?JSON.parse(g):void 0}catch{w=void 0}let y=w?.runId===u.result.operationId?hu(w):void 0;d=y!==void 0&&u.result.objectResults.every(v=>v.truncated!==!0)&&xo(Cu({runId:u.result.operationId,targetOrgId:u.target,status:u.result.status,objectResults:u.result.objectResults},y)).length===0}let l=fr(u?.startedAt)??fr(c?.run.startedAt)??new Date(0).toISOString(),h=fr(u!==void 0?u.finishedAt:c?.run.end?.at),m=u!==void 0?pr(os(u).objects):(c?.run.created??[]).map(g=>({objectApiName:g.objectApiName,created:g.ids.length,refused:0}));return{run:{n:r,script:"sandforge-seed",...f!==void 0?{runId:f}:{},...s.summary!==void 0&&u!==void 0?{summary:s.summary}:{},...u!==void 0?{seed:u.seed}:{},startedAt:l,...h!==void 0?{endedAt:h}:{},objects:m,...d?{takenBack:!0}:{}},status:u!==void 0?Q$(u):"applying"}}async function Z$(e,t,n,r,s){let o=t.resolved.checked.file.name,i=oe(n,r),a=e.store.fileOf(t.target.organizationId,o,i),{answer:c}=s,u=!1,f=await Nt(e.store.fileOf(t.target.organizationId,o,Qo(n,r)),"utf8").catch(()=>{});if(f!==void 0){let g=await Or(a,await Nt(a,"utf8"),t.target.alias,$r(e.journalDir));if(!("refusal"in g)){let w=Fu(f,Lu(xu(g.summary)));u="earlier"in w&&w.earlier?.removalLeft?.length===0}}let d=c.running===!0||c.interrupted===!0?void 0:s.finishedAt,l=s.finishedAt??await Jg(a)??new Date(0).toISOString(),h=new Date(Date.parse(l)-(s.elapsedMs??0)).toISOString(),m=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:i,startedAt:h,...d!==void 0?{endedAt:d}:{},objects:pr(Gr(c).objects),...u?{takenBack:!0}:{}},status:m}}async function ko(e,t,n){let r=t.resolved.checked.file.name,s=a=>a!==void 0?Jg(e.store.fileOf(t.target.organizationId,r,a)):Promise.resolve(void 0),o=await s(n.template),i=await s(n.summary);return{startedAt:o??i??new Date(0).toISOString(),...i!==void 0?{endedAt:i}:{}}}async function eA(e,t){if((await Je(e,!1)).some(o=>Y$.test(o)))return!1;let n=new Ue,r=(await pn(e,n)).find(o=>ke(o,t));if(r===void 0)return!1;let s=await new Cr(e,{orgId:r,guard:n}).recordedLoads();return s.length>0&&s.some(o=>o.removal!==void 0)&&s.every(o=>o.created!==void 0&&Uu(o).length===0)}async function tA(e,t){let n=(await pn(e,new Ue)).filter(r=>!ke(r,t.target.organizationId));if(n.length!==0)throw new Y("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. ${de}`)}function nA(e){let t=Cn(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 rA(e){return e.status==="success"?"applied":e.status==="partial"?"partial":e.status==="cancelled"?"applying":"failed"}function sA(e){return e.exit===0?"applied":e.exit===3?"partial":"failed"}var oA=p.object({run:p.number().int().positive(),replaces:p.number().int().positive().optional(),startedAt:p.string().optional(),removals:p.array(p.object({status:p.string()}).loose()).optional()}).loose();function Qg(e,t){return Oe(e.journalDir,"users",pe(t.target.organizationId))}async function Xg(e,t,n){let r=await Nt(Oe(Qg(e,t),`run-${n}.json`),"utf8").catch(()=>{});if(r!==void 0)try{let s=oA.safeParse(JSON.parse(r));return!s.success||s.data.run!==n?void 0:{...s.data.replaces!==void 0?{replaces:s.data.replaces}:{},takenBackWhole:s.data.removals?.at(-1)?.status==="success"}}catch{return}}async function iA(e,t,n){let r=Qg(e,t),s=[];for(let o of await Je(r,!1)){let i=Number(/^run-([1-9]\d{0,5})\.json$/.exec(o)?.[1]??0);i===0||n.has(i)||(await Xg(e,t,i))?.takenBackWhole===!0||s.push(`${Oe(r,o)}: run ${i} of ${B("users")}, which no summary names \u2014 a run of a users resource stopped before it answered, or one run alone: the state holds it not; ${B("users")} remove --org ${t.target.alias} --run ${i} takes it back`)}return s}async function aA(e,t,n){let r=t.resolved.checked.file.name,s=new Set;for(let o of n)if(o.state.kind==="users")for(let i of o.state.runs){if(i.summary===void 0)continue;let a=e.store.fileOf(t.target.organizationId,r,i.summary),c=await Nt(a,"utf8").catch(()=>{}),u=c!==void 0?Dn(c):void 0;u!==void 0&&s.add(u)}return s}function cA(e){let t=In(e);return t.refusal!==void 0?"failed":t.short!==void 0||t.objects.some(n=>n.notMasked>0)?"partial":"applied"}function uA(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 Y("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. ${de}`);return[...r][0]}async function dA(e,t,n,r){let s=t.resolved.checked.file.name,o=t.target.organizationId,i=n.ranks.get(r)??new Map,a=new Map;for(let[y,v]of i)v.summary!==void 0&&a.set(y,await G$(e.store.fileOf(o,s,v.summary)));let c=uA(r,n,a);if(c===void 0)return;for(let[y,v]of a){let b=e.store.fileOf(o,s,oe(r,y));v.kind==="seed"&&vo(b,v.answer.targetOrgId,t),v.kind==="forge"&&vo(b,v.answer.targetOrgId,t),v.kind==="users"&&vo(b,v.answer.org.organizationId,t),v.kind==="replay"&&vo(b,v.answer.target.organizationId,t)}let u=[],f=[...i.keys()].sort((y,v)=>y-v);if(c==="seed")for(let y of f){let v=i.get(y);v===void 0||v.summary===void 0&&v.seedRuns.length===0||u.push(await X$(e,t,r,y,v,a.get(y)))}else if(c==="forge")for(let y of f){let v=a.get(y);v?.kind==="forge"&&u.push(await Z$(e,t,r,y,v))}else if(c==="frozen"){let y=e.store.sasOf(o,s,rt(r));await tA(y,t);let v=await eA(y,o);for(let b of f){let k=i.get(b),E=a.get(b);if(k?.template===void 0){if(E?.kind!=="frozen"||v)continue;throw new Y("RUN_UNREAD",`Run ${b} of ${r} keeps its summary and not the payload its load was given, ${e.store.fileOf(o,s,Et(r,b))}, which its removal is run from: a state rebuilt without it would leave what the load created to nobody. ${de}`)}let S=E?.kind==="frozen"?E.answer:void 0;if(u.push({run:{n:b,script:"sandforge-frozen",sas:rt(r),...S!==void 0&&k.summary!==void 0?{summary:k.summary}:{},...await ko(e,t,k),objects:S!==void 0?pr(Cn(S).objects):[],...v?{takenBack:!0}:{}},status:S!==void 0?nA(S):"applying"}),S!==void 0&&Xr(S))for(let $ of u.slice(0,-1))$.run.takenBack=!0}}else if(c==="users")for(let y of f){let v=i.get(y),b=a.get(y);if(v?.summary===void 0||b?.kind!=="users")continue;let k=await Xg(e,t,b.answer.run);if(k?.replaces!==void 0)for(let E of u)E.users===k.replaces&&(E.run.takenBack=!0);u.push({run:{n:y,script:"sandforge-users",summary:v.summary,...await ko(e,t,v),objects:pr(is(b.answer).objects),...k?.takenBackWhole===!0?{takenBack:!0}:{}},status:rA(b.answer),users:b.answer.run})}else if(c==="replay")for(let y of f){let v=i.get(y),b=a.get(y);if(!(v?.summary===void 0||b?.kind!=="replay")&&(u.push({run:{n:y,script:"sandforge-checkpoint",summary:v.summary,...await ko(e,t,v),objects:pr(rs(b.answer).objects)},status:sA(b.answer)}),ss(b.answer)))for(let k of u.slice(0,-1))k.run.takenBack=!0}else{let y=!n.dataops.has(r);for(let v of f){let b=i.get(v),k=a.get(v);if(b===void 0)continue;let E=k?.kind==="mask"?k.answer:void 0;if(E===void 0&&y)continue;let S=E!==void 0?In(E):void 0;u.push({run:{n:v,script:"sandforge-dataops",...E!==void 0&&b.summary!==void 0?{summary:b.summary}:{},...S?.snapshotId!==void 0?{snapshotId:S.snapshotId}:{},...await ko(e,t,b),objects:(S?.objects??[]).map($=>({objectApiName:$.object,created:0,refused:$.refused,masked:$.masked})),...y?{takenBack:!0}:{}},status:E!==void 0?cA(E):"applying"})}}if(u.length===0)return;let d=u.map(y=>y.run),l=u.at(-1),h=d.every(y=>y.takenBack===!0)?"destroyed":l?.run.takenBack===!0?"partial":l?.status??"applying",m=t.resolved.resources.find(y=>y.name===r),g=d.flatMap(y=>y.endedAt!==void 0?[y.endedAt]:[]).sort(),w=d.map(y=>y.startedAt).sort();return{name:r,state:{kind:c,fingerprint:Jc,dependsOn:m!==void 0?[...m.dependsOn]:[],status:h,runs:d,recovered:!0},firstStartedAt:w[0]??new Date(0).toISOString(),...g.length>0?{lastEndedAt:g.at(-1)}:{}}}async function lA(e,t,n){let r=t.resolved.checked.file,o=(await new wu({root:Z(e.journalDir),locksDir:e.locksDir}).list({organizationId:t.target.organizationId})).flatMap(d=>d.valid&&d.checkpoint!==void 0?[d.checkpoint]:[]),i=[],a={},c=`${r.name} before`,u=o.filter(d=>d.name===c&&Date.parse(d.takenAt)<=Date.parse(n.first));u.length===1&&u[0]!==void 0?a.before=u[0].checkpointId:kn(r,"before")===void 0&&u.length===0?i.push("checkpoint.before: the file asks none"):i.push(`checkpoint.before: ${u.length===0?"no":`${u.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 f=kn(r,"after");if(f===void 0)i.push("checkpoint.after: the file asks none");else{let d=n.last,l=o.filter(h=>h.name===f&&d!==void 0&&Date.parse(h.readFrom)>=Date.parse(d));l.length===1&&l[0]!==void 0?a.after=l[0].checkpointId:i.push(`checkpoint.after: ${l.length===0?"no":`${l.length}`} checkpoint(s) of this org named '${f}' taken after the last run: none is linked, and reset has none to rewind to until an apply takes it`)}return{...a,notLinked:i}}function fA(e,t){let n=o=>{let i=/^(\d+)\.(\d+)\.(\d+)/.exec(o);return i?[Number(i[1]),Number(i[2]),Number(i[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 o=0;o<3;o++)if((r[o]??0)!==(s[o]??0))return(r[o]??0)>(s[o]??0);return!1}async function pA(e,t){let n=t.resolved.checked.file.name,{alias:r,organizationId:s}=t.target;try{let u=await e.store.read(s,n);if(u===void 0)return{damaged:!1};throw new Y("STATE_KEPT",`This machine keeps a state of ${n} on ${r} that reads, serial ${u.serial}: state recover never writes over one, and plan reads it. ${de}`)}catch(u){if(!(u instanceof L))throw u;if(u.code!=="damaged"){let f=tt(u);throw new Y(f.code,f.message)}}let o=e.store.stateFileOf(s,n),i;try{i=JSON.parse(await Nt(o,"utf8"))}catch{i=void 0}let a=i,c=a?.version;if(typeof c=="number"&&c>1||fA(a?.sandforgeVersion,e.sandforgeVersion))throw new Y("STATE_NEWER",`The state ${o} was written by a later SandForge (${String(a?.sandforgeVersion??`version ${String(c)}`)}; this one is ${e.sandforgeVersion}): update it, and plan again. ${de}`);return{damaged:!0}}async function Zg(e,t){let n=t.resolved.checked.file.name,{target:r}=t,s=Qe(e.locksDir,r.organizationId,{operation:"recover",env:n,alias:r.alias},e.lockOptions);if("busy"in s)return{refusal:nt(s.busy)};try{let{damaged:o}=await pA(e,t),i=await Yg(e,t),a=[];for(let k of[...i.ranks.keys(),...i.frozen,...i.dataops]){if(a.some(S=>S.name===k))continue;let E=await dA(e,t,i,k);E!==void 0&&a.push(E)}let c=[];for(let k of i.unclaimed){if(Gg(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 Y("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. ${de}`)}if(a.length===0)throw new Y("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. ${de}`);a.sort((k,E)=>Date.parse(k.firstStartedAt)-Date.parse(E.firstStartedAt)||k.name.localeCompare(E.name));let u=a[0]?.firstStartedAt??new Date(0).toISOString(),d=a.flatMap(k=>k.lastEndedAt!==void 0?[k.lastEndedAt]:[]).sort().at(-1),l=await lA(e,t,{first:u,...d!==void 0?{last:d}:{}}),h=a.some(k=>k.state.kind==="users")||t.resolved.resources.some(k=>k.kind==="users")?await iA(e,t,await aA(e,t,a)):[],g={...Mr({env:n,org:{organizationId:r.organizationId,kind:r.kind,username:r.username,alias:r.alias,...r.host!==void 0?{host:r.host}:{}},fileDigest:t.resolved.digest,sandforgeVersion:e.sandforgeVersion}),resources:Object.fromEntries(a.map(k=>[k.name,k.state])),...l.before!==void 0||l.after!==void 0?{checkpoints:{...l.before!==void 0?{before:l.before}:{},...l.after!==void 0?{after:l.after}:{}}}:{}},w=ln.safeParse({...g,serial:1});if(!w.success){let k=w.error.issues[0];throw new Y("RUN_UNREAD",`The run files of ${n} do not make a state (${k?.path.join(".")??""}: ${k?.message??"refused"}). ${de}`)}let y=o?await e.store.setAside(r.organizationId,n):void 0,v=await e.store.write(g,{serial:0,lineage:g.lineage}),b=new Set(t.resolved.resources.map(k=>k.name));return{state:v,result:{env:n,org:{organizationId:v.org.organizationId,kind:v.org.kind,alias:r.alias},state:{serial:v.serial,lineage:v.lineage},...y!==void 0?{setAside:y}:{},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:b.has(k.name)}])),checkpoints:{...l.before!==void 0?{before:l.before}:{},...l.after!==void 0?{after:l.after}:{}},notLinked:[...l.notLinked,...c,...h].slice(0,20)}}}catch(o){if(o instanceof Y)return{refusal:{code:o.code,message:o.message,exit:1}};throw o}finally{s.lock.release()}}function Hg(e){return`${e.length===1?"run":"runs"} ${e.join(", ")}`}function ey(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 o=s.takenBack.length===0?"":s.takenBack.length===s.runs.length?", taken back":`; ${Hg(s.takenBack)} taken back`;t.push(` ${r.padEnd(n)} ${s.kind}, ${s.status}: ${Hg(s.runs)}${o}`+(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 hA(e,t,n){let r=n.includes("users"),s=n.includes("mask")?", and what it masked left masked":"",o=": the state keeps it as destroyed";return r&&n.every(i=>i==="users"||i==="mask")?`${e} is taken back from ${t}, the assignments and memberships it created deleted and each user put back as it was, but for an address asked back${s}${o}, and the next apply sets them up again`:`every record of ${e} is taken back from ${t}${r?", each user put back as it was but for an address asked back":""}${s}${o}, and the next apply creates it again`}function mA(e){return mt(e,_e(e).map(([t])=>t))}async function ty(e,t){let{plan:n,target:r,resolved:s}=t,o=s.checked.file.name,i=(l,h=[])=>({result:{plan:n,steps:[],status:"failure",refusal:l,...h.length>0?{refusalCodes:[...h]}:{},state:{serial:t.state?.serial??0}},exitCode:1});if(t.state===void 0)return await bo(e,{resolved:s,target:r})?i(`This machine keeps no state of ${o} 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. "${B("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 ${o} 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 i(n.refusal,n.refusalCodes);let a=mA(t.state),c=Qe(e.locksDir,r.organizationId,{operation:"destroy",env:o,alias:r.alias},e.lockOptions);if("busy"in c){let l=nt(c.busy);return i(l.message,[l.code])}let u=new AbortController,f,d=(e.onStop??Ge)(l=>{f=l,e.say(`
152
+ stopped by ${l}: the removal under way stops before its next call to the org; destroy again takes up from the state`),u.abort()});try{let l;try{let $=await e.store.read(r.organizationId,o);if($===void 0||$.serial!==t.state.serial||$.lineage!==t.state.lineage)return i(`The state of ${o} 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.`,[Wr]);l=$}catch($){if($ instanceof L)return i($.message,[tt($).code]);throw $}let h=[],m=[],g=[],w=!1,y,v;for(let[$,j]of a.entries()){if(f!==void 0||y!==void 0){v??=$;break}let A=Ar(e.locksDir,r.organizationId,e.lockOptions);if(A!==void 0){e.say(Rn(A).message),g.push(1),v=$;break}let P=t.acceptAutomation||s.checked.file.resources[j]?.accept?.automation===!0,D=await Sc(e,l,{resource:j,action:"delete",target:r,includeChanged:t.includeChanged,sweep:t.sweep,acceptAutomation:P,ends:{whole:"destroyed",left:"partial"}},u.signal);if(l=D.state,h.push(...D.steps),w||=D.wrote,we(D.code)){y=D.code,v=$+1;break}if(g.push(D.code),D.code!==0&&D.code!==3){v=$+1;break}}for(let $ of v!==void 0?a.slice(v):[])m.push({resource:$,why:f!==void 0||y!==void 0?"the destroy was stopped before it":"a removal before it was refused or failed: its records would be kept for it"});let b=Object.values(l.resources).every($=>$.status==="destroyed"),k=[];if(b&&v===void 0){e.say(hA(o,r.alias,Object.values(l.resources).map($=>$.kind)));for(let{step:$,checkpoint:j}of Kr(l)){let A=await qt(e,{org:{alias:r.alias,kind:r.kind},checkpoint:j,why:"the environment it was taken of is taken back"},u.signal);k.push(A),A.exitCode===0&&(l=await e.store.update(l,P=>et(P,$,void 0)))}}let E=f!==void 0?Pe(f):y!==void 0?y:(()=>{let $=fn(g);return $===1&&w?3:$})();return{result:{plan:n,steps:h,...k.length>0?{checkpoints:k}:{},...m.length>0?{skipped:m}:{},status:yo(E),state:{serial:l.serial}},exitCode:E}}finally{d(),c.lock.release()}}import{readFileSync as gA}from"node:fs";var yA="taken back by a destroy: none of the org's records is its",wA="taken back by a destroy, which deleted its store and left its records masked: a masking creates no record",ny="a masking creates no record: it writes over those the org holds that its condition selects",ry="a users resource creates no record of its own: it sets up users the org holds, named here";function vA(e,t,n){if(e?.summary===void 0)return{refusal:"its last run stopped before it answered: it names no user"};try{let r=gA(n.store.fileOf(t.organizationId,t.env,e.summary),"utf8");return{users:ip(Vt(r))}}catch(r){if(r instanceof ce||r instanceof Error)return{refusal:`its last run's summary does not read: ${r.message}`};throw r}}var kA={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 Cc(e){return`${kA[e]??e}: it names no record until it is applied whole \u2014 apply again`}function bA(e){let t=e.filter(i=>i.state!==void 0);if(t.length!==e.length)return;let n=i=>Date.parse(i.state.updatedAt),[r,...s]=[...t].sort((i,a)=>n(a)-n(i));return r===void 0?void 0:s.every(i=>n(i)<n(r)&&bt(i.state.org,r.state.org))?{current:r,before:s}:void 0}function sy(e,t,n){let r=t.state!==void 0?` (serial ${t.state.serial}, written ${t.state.updatedAt})`:"";return`${e}: the state of ${t.env} kept under ${t.organizationId}${r} is of this sandbox before its refresh, set aside: output reads the one kept under `+n.org.organizationId}function oy(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))),s=r.length>1?bA(r):void 0;if(s!==void 0)return{state:s.current.state,setAside:s.before};if(r.length>1){let i=r.map(a=>`${a.organizationId}, written ${a.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[o]=r;return o===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}}:o.state===void 0?{refusal:{code:"STATE_DAMAGED",message:`${o.damaged??"The state does not read."} Nothing was read.`,exit:1}}:{state:o.state}}async function Ic(e,t){let n={organizationId:e.org.organizationId,env:e.env,target:e.org.alias??e.org.organizationId},r=pc(Object.keys(e.resources),i=>e.resources[i]?.dependsOn??[]),s={},o=!0;for(let i of r){let a=e.resources[i];if(a===void 0)continue;let c=a.runs.at(-1),u={kind:a.kind,status:a.status,...c!==void 0?{run:c.n}:{},records:{}};if(a.status==="destroyed"){s[i]={...u,why:a.kind==="mask"?wA:yA};continue}if(a.status!=="applied"&&(o=!1),a.kind==="mask"){s[i]={...u,masked:Object.fromEntries((c?.objects??[]).map(d=>[d.objectApiName,d.masked??0])),...c?.snapshotId!==void 0?{snapshotId:c.snapshotId}:{},why:a.status==="applied"?ny:`${Cc(a.status)}; ${ny}`};continue}if(a.kind==="users"){let d=[...a.runs].reverse().find(h=>h.takenBack!==!0),l=vA(d,n,t);"refusal"in l&&(o=!1),s[i]={...u,..."users"in l?{users:l.users}:{},why:"refusal"in l?l.refusal:a.status==="applied"?ry:`${Cc(a.status)}; ${ry}`};continue}if(a.status!=="applied"){s[i]={...u,why:Cc(a.status)};continue}if(c===void 0||c.takenBack===!0){o=!1,s[i]={...u,why:"it holds no run whose records are in the org"};continue}let f=await lr(c,n,t);if("refusal"in f){o=!1,s[i]={...u,why:f.refusal};continue}s[i]={...u,records:Object.fromEntries(f.created)}}return{output:{env:e.env,org:{organizationId:e.org.organizationId,kind:e.org.kind,...e.org.alias!==void 0?{alias:e.org.alias}:{},...e.org.host!==void 0?{host:e.org.host}:{}},state:{serial:e.serial,updatedAt:e.updatedAt},resources:s},whole:o}}function iy(e){let{org:t}=e,n=t.kind==="sandbox"?Ne(t.host):void 0,r=[`${e.env} on ${t.alias??t.organizationId} (${t.kind}${n!==void 0?` ${n}`:""}, ${t.organizationId}): state serial ${e.state.serial}, written ${e.state.updatedAt}`];for(let[s,o]of Object.entries(e.resources)){r.push(` ${s} ${o.kind}, ${o.status}`+(o.run!==void 0?`, run ${o.run}`:""));for(let[i,a]of Object.entries(o.records))r.push(` ${i} ${a.length>0?a.join(" "):"none"}`);for(let[i,a]of Object.entries(o.masked??{}))r.push(` ${i} ${a} masked`);for(let i of o.users??[])r.push(` User ${i.username} ${i.userId}`);o.snapshotId!==void 0&&r.push(` snapshot ${o.snapshotId}, taken first`),o.why!==void 0&&r.push(` ${o.why}`)}return r}var ay={reset:"after",destroy:"before"};function Dc(e,t){let n=ay[e],r=t?.checkpoints?.[n];return r!==void 0?{step:n,checkpoint:r}:void 0}function Pc(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",o=e.state;if(o===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(Dc(e.verb,o)===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 i=Object.entries(o.resources).filter(([,a])=>a.kind==="mask");if(e.verb==="destroy"&&i.length>0)return{code:"MASKED",message:`The state of ${t} on ${n} names mask resources (${i.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(o.resources).filter(([,c])=>c.status!=="applied"&&c.status!=="destroyed");if(a.length>0)return r(`${a.map(([c,u])=>`${c} is ${u.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 cy(e,t,n){let r=Dc(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(ye,si({org:t.target.alias,store:Z(e.journalDir),checkpoint:r.checkpoint,dryRun:!0,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails,acceptNoUndo:t.acceptNoUndo,acceptUnseen:t.acceptUnseen}),n);return Rd(s)}var Tt=e=>e.toLocaleString("en-US");function uy(e,t){let{alias:n}=e.target,r=`it deletes ${Tt(t.toDelete)} record(s) created since, gives ${Tt(t.toGiveBack)} their values back and brings ${Tt(t.toBringBack)} back from the recycle bin \u2014 whoever made these changes`+(Vr(t.lastChangedBy)!==""?`, last changed by ${Vr(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 EA(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 dy(e,t,n){let{target:r,resolved:s,verb:o}=t,i=s.checked.file.name,a=Dc(o,t.state),c={env:i,org:{organizationId:r.organizationId,kind:r.kind,alias:r.alias},verb:o,checkpoint:{step:ay[o],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}}:{}},u=(w,y)=>({result:{...c,exitCode:1,status:"failure",undo:{offered:!1,why:"nothing was rewound"},refusal:w,state:{serial:y}},exitCode:1}),f=Pc(t);if(f!==void 0||a===void 0||t.state===void 0)throw new Error(f?.message??"There is no checkpoint to rewind to.");let d=t.state,l=Qe(e.locksDir,r.organizationId,{operation:o,env:i,alias:r.alias},e.lockOptions);if("busy"in l)return u(nt(l.busy).message,d.serial);let h=new AbortController,m,g=(e.onStop??Ge)(w=>{m=w,e.say(`
153
+ stopped by ${w}: the rewind stops before its next call to the org, and leaves its journal: run this again to take it up`),h.abort()});try{let w;try{let $=await e.store.read(r.organizationId,i);if($===void 0||$.serial!==d.serial||$.lineage!==d.lineage)return u(`The state of ${i} 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.`,$?.serial??d.serial);w=$}catch($){if($ instanceof L)return u($.message,d.serial);throw $}e.say(`${o==="reset"?"reset":"destroy --rewind"}: rewinding ${r.alias} to checkpoint ${a.checkpoint}`);let y=await e.runner(ye,si({org:r.alias,store:Z(e.journalDir),checkpoint:a.checkpoint,dryRun:!1,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails,acceptNoUndo:t.acceptNoUndo,acceptUnseen:t.acceptUnseen}),h.signal),v=$d(y),b=m!==void 0?Pe(m):v.exitCode,k=[];if(o==="destroy"&&b===0){w=await e.store.update(w,EA);for(let{step:$,checkpoint:j}of Kr(w)){let A=await qt(e,{org:{alias:r.alias,kind:r.kind},checkpoint:j,why:"the environment it was taken of is taken back"},h.signal);k.push(A),A.exitCode===0&&(w=await e.store.update(w,P=>et(P,$,void 0)))}e.say(`every record of ${i} 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 E=Ad({verb:o,alias:r.alias,checkpoint:a.checkpoint,journalDir:e.journalDir,deleted:k.length>0&&k.every($=>$.exitCode===0)},v),S=v.refusal===void 0?void 0:v.refusal.code==="RECREATE"?`${v.refusal.message} ${o==="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:b,status:m!==void 0?"cancelled":v.status,...v.answer!==void 0?{answer:v.answer}:{},undo:E,...S!==void 0?{refusal:S.slice(0,8e3)}:{},...k.length>0?{deleted:k}:{},state:{serial:w.serial}},exitCode:b}}finally{g(),l.lock.release()}}function ly(e){let t=e.verb==="reset"?"reset":"destroy --rewind",n=[""],r=e.answer;if(r?.deleted!==void 0){let s=(r.residual??[]).reduce((o,i)=>o+i.count,0);n.push(` rewind to ${e.checkpoint.id}: exit ${e.exitCode}, ${e.status} ${Tt(r.deleted.done)} deleted, ${Tt(r.givenBack?.done??0)} given back, ${Tt(r.broughtBack?.done??0)} brought back`+(s>0?`, ${Tt(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(Od(e.undo)),n.push(`${t}: ${e.status}; state serial ${e.state.serial}`),n}import{randomBytes as RA}from"node:crypto";import{existsSync as SA,readFileSync as $A,statSync as AA}from"node:fs";import{open as OA,rename as jA,rm as CA}from"node:fs/promises";import{dirname as IA,resolve as Nc}from"node:path";var hy=1440*6e4;function my(e){let t={};for(let[o,i]of Object.entries(e.dryRuns))"answer"in i&&i.answer.tool===re&&(t[o]=i.answer.seed);let{host:n,...r}=e.plan.org,s=n!==void 0&&e.listedByMyDomain===!0?e.plan:{...e.plan,org:r};return Do.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:s})}function gy(e,t,n){let r=IA(Nc(t));if(!SA(r)||!AA(r).isDirectory())return{code:"BAD_LINE",message:`--out ${Nc(t)}: its folder ${r} is not there. Nothing was read.`,exit:2};if(n)return;let s=gn(e,t);if(s!==void 0)return{code:"PLAN_IN_REPOSITORY",message:`--out ${Nc(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 yy(e,t){let n=`${e}.${RA(6).toString("hex")}.tmp`,r=await OA(n,"wx",Jo);try{await r.writeFile(`${JSON.stringify(t,null,2)}
154
+ `,"utf8"),await r.sync()}finally{await r.close()}try{await jA(n,e)}catch(s){throw await CA(n,{force:!0}),s}}function wy(e){let t=o=>({refusal:{code:"PLAN_UNREAD",message:`--plan ${e} ${o}. Nothing was read or written.`,exit:2}}),n;try{n=$A(e,"utf8")}catch(o){return t(`cannot be read: ${o instanceof Error?o.message:String(o)}`)}let r;try{r=JSON.parse(n)}catch{return t("is not JSON: it is no plan plan --out kept")}let s=Do.safeParse(r);if(!s.success){let o=s.error.issues[0],i=o?.path.map(String).join(".")||"the plan";return t(`is no plan plan --out kept (${i}: ${o?.message??"refused"})`)}return{saved:s.data}}function cn(e,t){return{code:"PLAN_STALE",message:`The plan kept in ${e} ${t}. Nothing was written: plan again.`.slice(0,8e3),exit:1}}function vy(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 cn(t,"was made with --quick, which counts nothing an apply is held to");if(e.sandforgeVersion!==n.sandforgeVersion)return cn(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)>hy)return cn(t,`was made at ${e.madeAt}, more than a day ago`)}function DA(e){return e.found?`the state at serial ${e.serial}`:"no state"}function ky(e,t,n){let r=e.plan.org;if(!ke(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(r.host!==void 0&&r.host!==n.target.host)return{code:"PLAN_OTHER_ORG",message:`The plan kept in ${t} was made for ${r.alias??r.organizationId} on ${r.host}, and ${n.target.alias} answers on ${n.target.host??"no My Domain host"}: a plan is applied to the org it was made for. Nothing was written.`,exit:1};if(e.file.digest!==n.digest)return cn(t,"was made from another file: the file, or a variable or an alias it reads, changed since");let s=n.state,o=e.state;if(!(o.found===(s!==void 0)&&(!o.found||s!==void 0&&s.serial===o.serial&&s.lineage===o.lineage))){let a=s===void 0?"none":o.found&&s.lineage!==o.lineage?`at serial ${s.serial}, made again since`:`at serial ${s.serial}`;return cn(t,`was made against ${DA(o)}, and the state is now ${a}: an apply or a destroy ran since, or a cache put back another state`)}}function fy(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 py(e){if(e===void 0)return"nothing of it";let t=vc(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 Eo(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 Ro(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 by(e,t){let n=[],r=[...new Set([...e.actions,...t.actions].map(o=>o.resource))];for(let o of r){let i=e.actions.find(c=>c.resource===o),a=t.actions.find(c=>c.resource===o);i!==void 0&&a!==void 0&&fy(i)===fy(a)||n.push(`${o}: planned ${py(i)}, now ${py(a)}`)}let s=o=>o.actions.map(i=>i.resource).join(", ");return n.length===0&&s(e)!==s(t)&&n.push(`the order of the resources: planned ${s(e)}, now ${s(t)}`),Eo(e)!==Eo(t)&&n.push(`the checkpoints it takes: planned ${Eo(e)}, now ${Eo(t)}`),Ro(e)!==Ro(t)&&n.push(`the whole org against the checkpoint after the last apply: planned ${Ro(e)}, now ${Ro(t)}`),n}function Ey(e,t){return cn(e,`is not what the org holds now, read again: ${t.join("; ")}`)}function Ry(e,t){let n=new Date(Date.parse(t.madeAt)+hy).toISOString();return`plan kept in ${e}, for apply --plan until ${n}`}function Sy(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 LA=`sandforge env \u2014 apply a sandforge.yaml to an org: the data an environment needs, declared in
155
155
  your repository, created, kept and taken back, without the editor.
156
156
 
157
157
  Usage:
@@ -387,14 +387,14 @@ output: a resource not applied whole, or whose records cannot be read; audit wit
387
387
  or a frozen load's verification found records still changing; reset and destroy --rewind: someone
388
388
  changed records during it); 130, 143, 129 Ctrl-C, SIGTERM or SIGHUP stopped it \u2014 run it again: it
389
389
  takes up from the state.
390
- `,NA=["validate","plan","apply","destroy","reset","state","output","audit"],TA=e=>NA.includes(e),xA={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-user-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-user-emails","--accept-no-state","--out-in-repository","--yes"],values:["--file","--org","--alias","--replace","--plan","--handoff"]},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"]},audit:{words:Pg.words,switches:["--json","--save","--fail-on-findings"],values:["--file","--org","--alias"]}},LA={words:2,switches:["--json"],values:["--file","--org","--alias"]};function Oy(e,t){let n=e==="destroy"?"sandforge env":`sandforge env ${e}`;return t!==void 0&&t!==""?`${n}, relayed by ${t}`:n}function FA(e={},t="destroy"){let n=process.env[vt]?.trim();return bu({...e,relayedBy:Oy(t,n)})}function MA(e,t){return async(n,r,s)=>{let o=process.env[vt];process.env[vt]=t;try{return await e(n,r,s)}finally{o===void 0?delete process.env[vt]:process.env[vt]=o}}}function Ee(e){process.stderr.write(`${e} Run with --help.
391
- `),process.exit(2)}function _A(e,t=process.cwd()){let n=e.slice(2);(n.includes("--help")||n.includes("-h"))&&(process.stdout.write(PA),process.exit(0));let r=n[0];if(r===void 0||r.startsWith("-"))return Ee("Name the command first: validate, plan, apply, destroy, reset, state, output or audit.");if(!TA(r))return Ee(`"${r}" is not a command of sandforge env: validate, plan, apply, destroy, reset, state, output or audit. Nothing was run.`);let s=r==="state"&&n[1]==="recover";Qc(n,s?LA:xA[r]);let o=g=>{let w=[];for(let y=1;y<n.length;y++)n[y]===g&&(w.push(n[y+1]??""),y++);return w},i=g=>{let w=o(g);return w.length>1&&Ee(`${g} is given ${w.length} times: give it once.`),w[0]},a={};for(let g of o("--alias")){let w=g.indexOf("="),y=w>0?g.slice(0,w):"",v=w>0?g.slice(w+1):"";(y===""||v==="")&&Ee(`--alias wants <role>=<alias>, as --alias uat=UAT-ORG, not "${g}".`),y in a&&Ee(`--alias gives the role ${y} twice: give it once.`),a[y]=v}let c=i("--org");(r==="plan"||r==="apply"||r==="destroy"||r==="reset"||r==="output"||r==="audit"||s)&&c===void 0&&Ee(`${s?"state recover":r} needs --org, the sf CLI alias of the org.`);let u=i("--out");u!==void 0&&n.includes("--quick")&&Ee("--out keeps a plan for apply --plan, which a quick plan cannot be: it counts nothing an apply is held to.");let d=i("--handoff");u===void 0&&d===void 0&&n.includes("--out-in-repository")&&Ee(r==="apply"?"--out-in-repository goes with --handoff: it says where the note may be kept.":"--out-in-repository goes with --out: it says where the plan may be kept.");let l=i("--plan");if(l!==void 0){let w=["--replace","--replace-drifted","--accept-automation","--accept-emails","--accept-user-emails","--accept-no-state"].filter(y=>n.includes(y));w.length>0&&Ee(`${w.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 f=n.includes("--rewind");if(f){let g=["--include-changed","--sweep"].filter(w=>n.includes(w));g.length>0&&Ee(`${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)&&Ee(`${g} goes with --rewind: a destroy by removal is no rewind.`);let h=i("--file"),m=o("--replace");return{command:r,recover:s,file:Ro(t,h??"sandforge.yaml"),fileGiven:h!==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(m)],replaceDrifted:n.includes("--replace-drifted"),acceptAutomation:n.includes("--accept-automation"),acceptEmails:n.includes("--accept-emails"),acceptUserEmails:n.includes("--accept-user-emails"),acceptNoState:n.includes("--accept-no-state"),includeChanged:n.includes("--include-changed"),sweep:n.includes("--sweep"),rewind:f,acceptNoUndo:n.includes("--accept-no-undo"),acceptUnseen:n.includes("--accept-unseen"),yes:n.includes("--yes"),...u!==void 0?{out:Ro(t,u)}:{},outInRepository:n.includes("--out-in-repository"),...l!==void 0?{plan:Ro(t,l)}:{},...d!==void 0?{handoff:Ro(t,d)}:{},save:n.includes("--save"),failOnFindings:n.includes("--fail-on-findings")}}function pr(){try{let e=JSON.parse(Ay(Tt(__dirname,"..","package.json"),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}}var te=class extends Error{constructor(n,r){super(n.refusal.message);this.answer=n;this.code=r;this.name="Stop"}answer;code};function le(e){return new te({refusal:{code:e.code,message:e.message}},e.exit)}function Nc(e){return{path:wn(e.path),...e.resource!==void 0?{resource:e.resource}:{},message:e.message}}function Oo(e){let t;try{t=Ay(e,"utf8")}catch(r){throw new te({refusal:{code:"FILE_UNREAD",message:`${e} cannot be read: ${r instanceof Error?r.message:String(r)}`}},2)}let n=pg(t);if("refusal"in n)throw new te({refusal:{code:"INVALID_FILE",message:`${e}: ${n.refusal}`}},2);return n.document}function $o(e,t){return new te({refusal:{code:"INVALID_FILE",message:`${e} does not validate:
392
- ${t.map(n=>` ${sc(n)}`).join(`
393
- `)}`,issues:t.map(Nc)}},2)}async function zA(e){let t,n={request:a=>t??=e.request(a)},r=a=>({unread:a instanceof Error?a.message:String(a)}),s=await wu(n).catch(r),o="unread"in s||s.dailyApiRequests===void 0?await vu(n).catch(r):s.dailyApiRequests,i=await ku(n).catch(r);return{apiRequests:o,storage:"unread"in s?s:{remainingMB:s.remainingMB,maxMB:s.maxMB},emails:i}}function qA(e,t){try{return nu(JSON.parse(e),t)}catch{return}}function Tc(e){return e.trim().split(`
394
- `).map(t=>t.trim()).filter(Boolean).at(-1)??"it said nothing"}function jy(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 cn(e,t,n){let r=Oo(e.file),s=gg(r,je(e.file),process.env,{aliases:e.aliases});if("refusals"in s)throw $o(e.file,s.refusals);let o=s.resolved,i=o.resources.map(A=>A.name);for(let A of e.replace)if(!i.includes(A))throw new te({refusal:{code:"BAD_LINE",message:`--replace ${A} names no resource of the file: it has ${i.join(", ")}.`}},2);let a=t.journalDir??Nr(),c=t.locksDir??Ou(),u=Tr(je(e.file),a),d=_r({journalDir:a,fileFolder:je(e.file)});if("refusal"in d)throw le(Wr(d.refusal,u!==void 0));let l=d.store;for(let A of await l.sweep())n(jy(A));let f=e.org??"",h;try{h=await(t.reach??Cy)(f)}catch(A){throw new te({refusal:{code:"NOT_CONNECTED",message:A instanceof Po?A.message:`${f} could not be reached: ${A instanceof Error?A.message:String(A)}`}},1)}let m;try{m=await br(h.conn)}catch(A){m={unread:A instanceof Error?A.message:String(A),error:A}}let g=$d(f,m,h.session);if("refusal"in g)throw le(g.refusal);let w=g.target,y=jd(o.checked.file.targets,w);if(y!==void 0)throw le(y);let v;try{v=e.recover?void 0:await l.read(w.organizationId,o.checked.file.name)}catch(A){throw A instanceof L?le(Ze(A)):A}if(v!==void 0){let A=Cd(v,o.checked.file.name,w);if(A!==void 0)throw le(A)}let b=[],k,E,S=e.command==="plan"||e.command==="apply";if(v===void 0&&S){let A=await ko({store:l,journalDir:a},{resolved:o,target:w}),P=await l.refreshedOf(w,o.checked.file.name),D=Id(w,o.checked.file.name,e.acceptNoState,A,P);"refusal"in D?k=D.refusal:D.refreshed!==void 0?E=D.refreshed:b.push(D.warning)}let $=ii(o.checked.file.targets,w)?.by==="myDomain";S&&$&&b.push(`${w.alias}: ${Od(E!==void 0)}`);let j=ju(c,w.organizationId,t.lockOptions);if(j!==void 0&&b.push(`${Iu(j)}: this plan may be out of date when it ends`),S){let A=await BA(o,w,t,n),P=await UA(o,n),D=await KA(o,w,h,{journalDir:a,locksDir:c});if(Object.keys(A).length+Object.keys(P).length+Object.keys(D).length>0){let J=ac(o.checked,process.env,{aliases:e.aliases,sources:A,datasets:P,checkpoints:D});if("refusals"in J)throw $o(e.file,J.refusals);o=J.resolved}}return{resolved:o,store:l,journalDir:a,locksDir:c,target:w,reached:h,state:v,warnings:b,...k!==void 0?{noState:k}:{},...E!==void 0?{refreshed:E}:{},listedByMyDomain:$,runner:t.runner!==void 0?MA(t.runner,Oy(e.command,process.env[vt]?.trim())):FA({},e.command)}}async function BA(e,t,n,r){let s=new Map,o={};for(let i of e.resources){if(i.kind!=="forge")continue;let{role:a,alias:c}=i.source;r(`${i.name}: reading its source, the ${a} org (${c})`);let u;try{let l=s.get(c);l===void 0&&(l=(n.reach??Cy)(c),s.set(c,l)),u=(await l).conn}catch(l){o[i.name]={refusal:l instanceof Po?`the ${a} org: ${l.reason}`:`the ${a} org (${c}) could not be reached: ${l instanceof Error?l.message:String(l)}`};continue}let d=await Md(u,i.run,a,c);o[i.name]="organizationId"in d&&ke(d.organizationId,t.organizationId)?{refusal:`its source, the ${a} org (${c}), is the org to fill: a clone reads one org and writes another`}:d}return o}async function UA(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 al(r.dataset.dir,r.run.dataset));return n}async function KA(e,t,n,r){let s={};for(let o of e.resources)o.kind==="replay"&&(s[o.name]=await tf(o.run,o.checkpoint,{alias:t.alias,organizationId:t.organizationId,username:n.session.username,instanceUrl:n.session.instanceUrl},{storeRoot:Z(r.journalDir),locksDir:r.locksDir}).catch(i=>({code:"STORE_REFUSED",refusal:`its checkpoint could not be read: ${i instanceof Error?i.message:String(i)}`})));return s}async function Cy(e){let t=await Xc(e);return{session:t,conn:Zc(t)}}async function Iy(e,t,n,r){let{state:s,resolved:o,target:i}=e,a={};if(s===void 0)return a;let c={organizationId:i.organizationId,env:o.checked.file.name},u=ht(s,_e(s).map(([d])=>d));for(let d of u){let l=s.resources[d];if(l===void 0)continue;let f=t.acceptAutomation||o.checked.file.resources[d]?.accept?.automation===!0,h=[];for(let m of yp(l.kind,l.runs)){if(r.aborted)break;let g=Ec(m,c,e,d);if(g===void 0){h.push({n:m.n,nothing:!0});continue}n(`${d}: reading what the org holds of run ${m.n}`);let w=mp(l.kind,{target:i.alias,subject:g,includeChanged:t.includeChanged,acceptAutomation:f,checkpointStore:Z(e.journalDir),...t.sweep===!0?{sweep:!0}:{}}),y=await e.runner(w.script,w.args,r),v;try{v={n:m.n,preview:gp(l.kind,y.stdout)}}catch(k){if(!(k instanceof ce))throw k;h.push({n:m.n,failed:`exit ${y.code}: ${Tc(y.stderr)}`});continue}let b=t.refresh&&l.status==="applied"&&o.checked.file.resources[d]!==void 0?wp(l.kind,{target:i.alias,subject:g}):void 0;if(b!==void 0&&!r.aborted){n(`${d}: verifying run ${m.n}`);let k=await e.runner(b.script,b.args,r);try{v={...v,refreshed:vp(k.stdout)}}catch(E){if(!(E instanceof ce))throw E;v={...v,refreshed:{unread:`exit ${k.code}: ${Tc(k.stderr)}`}}}}h.push(v)}a[d]=h}return a}async function VA(e,t){let{resolved:n,state:r,target:s,store:o,journalDir:i}=e,a={};for(let c of n.resources)t.has(c.name)&&(c.kind!=="seed"||(c.run.draws??[]).length===0||(a[c.name]=await po(c,r,t,{organizationId:s.organizationId,env:n.checked.file.name,target:s.alias},{store:o,journalDir:i})));return a}async function WA(e,t){let{resolved:n,state:r,target:s,store:o,journalDir:i}=e,a=new Set(_e(r).map(([u])=>u)),c=[];for(let u of t){if(!(u.action==="delete"||u.action==="replace"&&!St(u.kind))||!a.has(u.resource))continue;let l=await kc(r,u.resource,{organizationId:s.organizationId,env:n.checked.file.name,target:s.alias},{store:o,journalDir:i});if(!("refusal"in l))for(let f of l.created.values())c.push(...f)}return c}async function HA(e,t,n,r,s,o={},i=!1,a=!1,c=!1){let{resolved:u,target:d,state:l,store:f}=e,h={},m=new Map(t.filter(y=>y.action==="create"||y.action==="replace"||(y.kind==="mask"||y.kind==="users")&&y.action==="keep").map(y=>[y.resource,y.action]));if(m.size===0)return h;let g=u.checked.file.name;await $u(e.journalDir,new Date).catch(()=>0);let w=jA(Tt(DA(),"sandforge-env-plan-"));try{for(let y of u.resources){let v=m.get(y.name);if(v===void 0||s.aborted)continue;if(y.kind==="forge"){let U=y.source.read;if(U===void 0||"refusal"in U)continue}if(y.kind==="frozen"){let U=y.dataset.read;if(U===void 0||"refusal"in U)continue}if(y.kind==="replay"){let U=y.checkpoint.read;if(U===void 0||"refusal"in U)continue}let b=n[y.name];if(b!==void 0&&b.refusals.length>0)continue;let k=Tt(w,`${y.name}.json`),E=y.kind==="forge"&&y.run.records!==void 0?Yr(e.journalDir,d.organizationId,g,y.name):void 0,S,$,j;if(y.kind==="frozen"){let U=f.sasOf(d.organizationId,g,tt(y.name));if($=$y(U)?U:Tt(w,`${y.name}.sas`),$===U&&(S=Tt(w,`${y.name}.cli-store.json`)),v==="replace"&&St(y.kind)){let O=await WA(e,t);O.length>0&&(j=Tt(w,`${y.name}.gone-first.json`),by(j,`${JSON.stringify(O)}
395
- `,{mode:384}))}}let A=Wt(y,{...b!==void 0?{drawn:b.ids}:{},standIns:!0,...$!==void 0?{sasDir:$}:{}});by(k,`${JSON.stringify(A,null,2)}
396
- `,{mode:384}),r(`${y.name}: dry run`);let P=o[y.name],D=y.kind==="users"&&v!=="create"?yo(l?.resources[y.name],{organizationId:d.organizationId,env:g},e).run:void 0,x=mt(ip(y,{target:d.alias,templateFile:k,runId:xr(g,y.name,gn(l?.resources[y.name])),replace:v==="replace"&&St(y.kind),acceptAutomation:a||u.checked.file.resources[y.name]?.accept?.automation===!0,...P!==void 0?{seed:P}:{},...S!==void 0?{storeFile:S}:{},...j!==void 0?{goneFirstFile:j}:{},...E!==void 0?{rootsPlanFile:E}:{},...y.kind==="mask"?{store:Tt(w,`${y.name}.dataops`)}:{},...D!==void 0?{replacesRun:D}:{},...c?{acceptUserEmails:!0}:{},checkpointStore:Z(e.journalDir)}),i),J=await e.runner(x.script,x.args,s);try{h[y.name]={answer:lp(y.kind,J.stdout)}}catch(U){if(!(U instanceof ce))throw U;let O=qA(J.stdout,x.script);h[y.name]={failed:`exit ${J.code}: ${Tc(J.stderr)}`,...O?{refused:O}:{}}}}}finally{CA(w,{recursive:!0,force:!0})}return h}async function So(e,t,n){let r=new AbortController,s,o=(e.onStop??Ye)(i=>{s=i,r.abort()});try{let i=await n(r.signal);if(s!==void 0)throw new te({refusal:{code:"STOPPED",message:`stopped by ${s} while ${t}: nothing was written`}},Pe(s));return i}finally{o()}}function Dy(e){let{resolved:t,state:n,store:r,target:s}=e,o=new Set([...t.resources.filter(i=>i.kind==="mask").map(i=>i.name),...Object.entries(n?.resources??{}).filter(([,i])=>i.kind==="mask").map(([i])=>i)]);return Object.fromEntries([...o].map(i=>[i,r.sasOf(s.organizationId,t.checked.file.name,Bt(i))]))}async function Ey(e,t,n,r,s={}){let o={organizationId:e.target.organizationId,kind:e.target.kind,alias:e.target.alias,...e.target.host!==void 0?{host:e.target.host}:{}},i=JA(e),a={resolved:e.resolved,org:o,state:e.state,replace:t.replace,replaceDrifted:t.replaceDrifted,warnings:e.warnings,maskStores:Dy(e),acceptUserEmails:t.acceptUserEmails,...Object.keys(i).length>0?{usersUnknown:i}:{},...e.refreshed!==void 0?{refreshed:e.refreshed}:{},...e.noState!==void 0?{refusal:e.noState.message,refusalCodes:[e.noState.code]}:{}};if(t.quick)return{plan:gc(a),dryRuns:{}};let c=await Iy(e,{includeChanged:!1,acceptAutomation:t.acceptAutomation,refresh:!0},n,r),u=await GA(e,n,r),d=hc({...a,previews:c,...u?{drift:u}:{}}),l=new Set(d.filter(y=>y.action==="create"||y.action==="replace").map(y=>y.resource)),f=await VA(e,l),h=await HA(e,d,f,n,r,s,t.acceptEmails,t.acceptAutomation,t.acceptUserEmails),m=await YA(e,d,h),g=await zA(e.reached.conn),w=await QA(e,d.some(lc),n,r);return{plan:gc({...a,previews:c,dryRuns:h,budget:g,...Object.keys(m).length>0?{maskCreatedAfter:m}:{},...u?{drift:u}:{},...w?{checkpointEstimate:w}:{},draws:Object.fromEntries(Object.entries(f).map(([y,v])=>[y,{draws:v.draws,refusals:v.refusals}]))}),dryRuns:h}}async function YA(e,t,n){let{resolved:r,state:s,target:o,store:i,journalDir:a,reached:c}=e,u=r.resources.map(f=>f.name),d={organizationId:o.organizationId,env:r.checked.file.name,target:o.alias},l={};for(let f of r.resources){if(f.kind!=="mask")continue;let{object:h,where:m}=f.run;if(h===void 0||m===void 0)continue;let g=t.find(y=>y.resource===f.name)?.action==="keep",w=n[f.name];!g||w===void 0||"failed"in w||(l[f.name]=await Fl(f.name,s,u,{object:h,where:m},{createdBy:y=>dr(y,d,{store:i,journalDir:a}),count:async y=>(await c.conn.query(y)).totalSize}))}return l}function JA(e){let{state:t,target:n,resolved:r}=e,s={organizationId:n.organizationId,env:r.checked.file.name},o={};for(let[i,a]of _e(t)){if(a.kind!=="users")continue;let c=yo(a,s,e).unknown;c!==void 0&&(o[i]=c)}return o}async function GA(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(ye,ud({org:e.target.alias,store:Z(e.journalDir),checkpoint:r}),n);return yd(r,s)}async function QA(e,t,n,r){let s=e.resolved.checked.file;if(qr(s,e.state,t).length===0||r.aborted)return;n("checkpoint: estimating what a take of the org costs");let o=await e.runner(ye,cd({org:e.target.alias,store:Z(e.journalDir),...zr(s)}),r);return pd(o)}function XA(e,t){let n=uu(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 ZA(e){if(e.kind==="seed"){let s=Vt(e).map(i=>`${i.object} ${i.count??""}`).join(", "),o=(e.draws??[]).map(i=>`${i.relation.childObject}.${i.relation.lookupField} under the ${i.relation.parentObject} records ${i.from} created`);return o.length>0?`${s}; ${o.join(", ")}`:s}if(e.kind==="frozen"){let{path:s,version:o,digest:i}=e.dataset,a=typeof s=="string"?s:`$${s.env}`;return`the Frozen dataset ${o} at ${a} (${i.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 (${Vt(e).map(i=>i.object).join(", ")})`} with ${s}, ${e.rules.rules.length} rule(s)`}if(e.kind==="users")return`User ${e.users.length}, applied first`;if(e.kind==="replay"){let{checkpoint:s}=e,o=s.file;return s.id!==void 0?`a replay of checkpoint ${s.id}`:s.name!==void 0?`a replay of the checkpoint named ${s.name}`+(e.from!==void 0?` of the ${e.from} org`:""):`a replay of the checkpoint file ${typeof o=="string"?o:`$${o?.env??""}`}`}let t=(s,o)=>o!==void 0?`${s} WHERE ${o}`: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 ${Hr(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 eO(e,t){let n=Oo(e.file),r=cr(n,je(e.file));if("refusals"in r){t(`${e.file} does not validate:`);for(let l of r.refusals)t(` ${sc(l)}`);return{answer:{file:e.file,valid:!1,issues:r.refusals.map(Nc),warnings:[]},code:2}}let{file:s,order:o,runs:i,variables:a}=r.checked,c=new Set(hg(r.checked,process.env).map(l=>l.name)),u=o.flatMap(l=>{let f=i[l],h=s.resources[l];return f===void 0?[]:[{name:l,kind:f.kind,dependsOn:h!==void 0?oc(l,h):[],...f.kind==="forge"?{source:f.source}:{},objects:Vt(f)}]}),d=r.checked.warnings.map(Nc);t(`${e.file}: valid, the environment ${s.name}`);for(let l of u){let f=i[l.name];t(` ${l.name}: ${f!==void 0?ZA(f):""}`+(l.dependsOn.length>0?`, after ${l.dependsOn.join(", ")}`:""))}for(let l of a){let f=l.role!==void 0?`the ${l.role} org`:l.path[2]==="checkpoint"?`the checkpoint file of ${l.resource??""}`:`the dataset of ${l.resource??""}`;t(` variable ${l.name} (${f}): `+(c.has(l.name)?"not set in this shell":"set"))}for(let l of d)t(`warning: ${l.path}: ${l.message}`);return{answer:{file:e.file,valid:!0,env:s.name,resources:u,variables:a.map(l=>({name:l.name,...l.role!==void 0?{role:l.role}:{},...l.resource!==void 0?{resource:l.resource}:{},set:!c.has(l.name)})),issues:[],warnings:d},code:0}}function tO(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??"",o=t===0?"":`, which keeps ${t===1?"1 other state":`${t} other states`}: "${B("env")} state" lists ${t===1?"it":"them"}`;return`no state of ${s} is kept in ${e}${o}. 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 nO(e,t,n){let r=t.journalDir??Nr(),s=_r({journalDir:r,fileFolder:null});if("refusal"in s)throw le(Wr(s.refusal,!1));let o=await s.store.sweep(),i;if(e.fileGiven){let d=cr(Oo(e.file),je(e.file));if("refusals"in d)throw $o(e.file,d.refusals);i=d.checked.file.name}let a=e.org,c=await s.store.list(),u=c.filter(d=>(i===void 0||d.env===i)&&(a===void 0||d.state?.org.alias===a||d.organizationId.slice(0,15)===a.slice(0,15)));for(let d of o)n(`expired and deleted: ${d.env} on ${d.alias??d.organizationId}`);u.length===0&&n(tO(s.store.root,c.length,i,a));for(let d of u){let l=d.state;if(l===void 0){n(`${d.env} on ${d.organizationId}: not used \u2014 ${d.damaged??""}`);continue}let f=Object.entries(l.resources).map(([h,m])=>`${h} ${m.status}`).join(", ");n(`${l.env} on ${l.org.alias??l.org.organizationId} (${l.org.kind}, ${l.org.organizationId}): serial ${l.serial}, written ${l.updatedAt}`+(d.expiresAt!==void 0?`, expires ${d.expiresAt}`:"")+(f?`; ${f}`:""))}return{journalDir:r,states:u.map(d=>{let l=d.state;if(l===void 0)return{env:d.env,organizationId:d.organizationId,damaged:d.damaged??"not used"};let f=Xo(l);return{env:l.env,organizationId:l.org.organizationId,...l.org.alias!==void 0?{alias:l.org.alias}:{},kind:l.org.kind,serial:l.serial,resources:Object.fromEntries(Object.entries(l.resources).map(([h,m])=>[h,m.status])),updatedAt:l.updatedAt,...f!==void 0?{expiresAt:f}:{}}}),expired:o.map(d=>({env:d.env,organizationId:d.organizationId,...d.alias!==void 0?{alias:d.alias}:{},expiresAt:d.expiresAt}))}}async function rO(e,t,n){let r=cr(Oo(e.file),je(e.file));if("refusals"in r)throw $o(e.file,r.refusals);let s=t.journalDir??Nr(),o=Tr(je(e.file),s),i=_r({journalDir:s,fileFolder:je(e.file)});if("refusal"in i)throw le(Wr(i.refusal,o!==void 0));for(let d of await i.store.sweep())n(jy(d));let a=ty(await i.store.list(),r.checked.file.name,e.org??"");if("refusal"in a)throw le(a.refusal);for(let d of a.setAside??[])n(ey(e.org??"",d,a.state));let{output:c,whole:u}=await Cc(a.state,{store:i.store,journalDir:s});return{answer:c,code:u?0:3}}async function sO(e,t,n){let r=await cn(e,t,n),s=await Jg({store:r.store,journalDir:r.journalDir,locksDir:r.locksDir,sandforgeVersion:pr(),...t.lockOptions!==void 0?{lockOptions:t.lockOptions}:{}},{resolved:r.resolved,target:r.target});if("refusal"in s)throw le(s.refusal);for(let o of Gg(s.result))n(o);return s.result}function Py(e){let{target:t}=e;return{organizationId:t.organizationId,kind:t.kind,alias:t.alias,...t.host!==void 0?{host:t.host}:{}}}function Ry(e){let t=e.checked.file.audits,n=pn(t,"apply"),r=t?.handoff===!0;return n!==void 0?`${Ng(n)}${r?"; then the handoff note":""}`:r?"after the apply: the handoff note, written on this machine":void 0}function oO(e){if(e.handoff===void 0)return;let t=je(e.handoff);if(!$y(t)||!IA(t).isDirectory())return new te({refusal:{code:"BAD_LINE",message:`--handoff ${e.handoff}: its folder ${t} is not there. Nothing was read.`}},2);if(e.outInRepository)return;let n=mn(je(e.file),e.handoff);if(n!==void 0)return new te({refusal:{code:"HANDOFF_IN_REPOSITORY",message:`--handoff ${e.handoff} is inside the repository ${n} that holds the file: the note names the org, its users by their usernames and what is left to do, and committed with the project it would publish them. Keep it outside \u2014 in CI, in $RUNNER_TEMP, kept as an artifact a short time \u2014 or give --out-in-repository for a folder of it that is never committed. Nothing was read.`}},2)}function iO(e){let t=(e.schedules?.jobs??[]).filter(o=>o.status!=="new").length,n=e.endpoints?.found.length??0,r=[e.deliverability?.unread!==void 0?"the deliverability":"",e.schedules?.unread!==void 0?"the scheduled jobs":"",e.endpoints?.unread!==void 0?"the endpoints":""].filter(Boolean),s=[t>0?`${t} scheduled job(s) no longer run`:"",n>0?`${n} endpoint(s) still name production`:"",e.deliverability?.read==="open"?"the org delivers all email":""].filter(Boolean);return`audits: ${s.length>0?`${s.join(", ")} (below)`:"nothing found"}`+(r.length>0?`; not read: ${r.join(", ")} (below)`:"")}async function aO(e,t,n,r){let s=e.resolved.checked.file,o=Py(e),i=[],a=[],c=n,u=pn(s.audits,"apply");if(u!==void 0){r("audits: reading the org, nothing written");try{let f=await Ir({transport:e.reached.conn,journalDir:e.journalDir},{org:o,asked:u});c={...c,audits:f.result},i.push(iO(f.result)),a.push(...$c(f.result,{file:t.file,notes:f.notes}))}catch(f){i.push(`audits: not read \u2014 ${f instanceof Error?f.message:String(f)}`)}}let d=new Date().toISOString(),l=t.handoff??(s.audits?.handoff===!0?qg(e.journalDir,{env:s.name,organizationId:e.target.organizationId,at:d}):void 0);if(l!==void 0)try{let f=await e.store.read(e.target.organizationId,s.name),h=f!==void 0?(await Cc(f,{store:e.store,journalDir:e.journalDir})).output:void 0,m=zg({run:c,org:o,file:t.file,at:d,sandforgeVersion:pr(),...h!==void 0?{output:h}:{},resources:s.resources,...s.masking!==void 0?{masking:s.masking}:{}});await Bg(l,m),c={...c,handoff:{path:l}},i.push(`handoff note: ${l}`)}catch(f){i.push(`handoff note: not written \u2014 ${f instanceof Error?f.message:String(f)}`)}return{result:c,before:i,after:a}}async function xc(e,t,n,r){return e.yes||await(t.ask??(o=>Ru(o)))(n)===e.org?!0:(r("Nothing was written: the alias typed is not the org\u2019s."),!1)}function Ao(e,t,n){return{runner:e.runner,store:e.store,locksDir:e.locksDir,journalDir:e.journalDir,orgNow:XA(e.reached.conn,n),say:n,sandforgeVersion:pr(),...t.onStop!==void 0?{onStop:t.onStop}:{},...t.lockOptions!==void 0?{lockOptions:t.lockOptions}:{}}}async function Sy(e,t,n,r,s){let o=await cn(e,t,r),i={verb:n,resolved:o.resolved,target:o.target,state:o.state,acceptAutomation:e.acceptAutomation,acceptEmails:e.acceptEmails,acceptNoUndo:e.acceptNoUndo,acceptUnseen:e.acceptUnseen},a=Dc(i);if(a!==void 0)throw le(a);for(let d of o.warnings)r(`warning: ${d}`);let c;if(!e.yes){let d=await So(t,"reading what a rewind would do",l=>sy(Ao(o,t,r),i,l));if(!("differs"in d))throw new te({refusal:{code:"REWIND_REFUSED",message:`${d.refusal} Nothing was written.`}},1);c=d;for(let l of kd(n,o.target.alias,d))r(l);if(d.refusal!==void 0)throw new te({refusal:{code:d.refusal.code,message:d.refusal.message}},1);if(d.differs&&!await xc(e,t,oy(i,d),r))throw new te({refusal:{code:"DECLINED",message:"Nothing was written."}},1)}let u=await iy(Ao(o,t,r),i,c);for(let d of ay(u.result))r(d);s(u.result),ze(u.exitCode)}async function cO(e=process.argv,t={}){let n=_A(e,t.cwd),r=o=>{process[n.json?"stderr":"stdout"].write(`${o}
390
+ `,FA=["validate","plan","apply","destroy","reset","state","output","audit"],MA=e=>FA.includes(e),_A={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-user-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-user-emails","--accept-no-state","--out-in-repository","--yes"],values:["--file","--org","--alias","--replace","--plan","--handoff"]},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"]},audit:{words:Lg.words,switches:["--json","--save","--fail-on-findings"],values:["--file","--org","--alias"]}},zA={words:2,switches:["--json"],values:["--file","--org","--alias"]};function Dy(e,t){let n=e==="destroy"?"sandforge env":`sandforge env ${e}`;return t!==void 0&&t!==""?`${n}, relayed by ${t}`:n}function qA(e={},t="destroy"){let n=process.env[kt]?.trim();return $u({...e,relayedBy:Dy(t,n)})}function BA(e,t){return async(n,r,s)=>{let o=process.env[kt];process.env[kt]=t;try{return await e(n,r,s)}finally{o===void 0?delete process.env[kt]:process.env[kt]=o}}}function Ee(e){process.stderr.write(`${e} Run with --help.
391
+ `),process.exit(2)}function UA(e,t=process.cwd()){let n=e.slice(2);(n.includes("--help")||n.includes("-h"))&&(process.stdout.write(LA),process.exit(0));let r=n[0];if(r===void 0||r.startsWith("-"))return Ee("Name the command first: validate, plan, apply, destroy, reset, state, output or audit.");if(!MA(r))return Ee(`"${r}" is not a command of sandforge env: validate, plan, apply, destroy, reset, state, output or audit. Nothing was run.`);let s=r==="state"&&n[1]==="recover";Xc(n,s?zA:_A[r]);let o=g=>{let w=[];for(let y=1;y<n.length;y++)n[y]===g&&(w.push(n[y+1]??""),y++);return w},i=g=>{let w=o(g);return w.length>1&&Ee(`${g} is given ${w.length} times: give it once.`),w[0]},a={};for(let g of o("--alias")){let w=g.indexOf("="),y=w>0?g.slice(0,w):"",v=w>0?g.slice(w+1):"";(y===""||v==="")&&Ee(`--alias wants <role>=<alias>, as --alias uat=UAT-ORG, not "${g}".`),y in a&&Ee(`--alias gives the role ${y} twice: give it once.`),a[y]=v}let c=i("--org");(r==="plan"||r==="apply"||r==="destroy"||r==="reset"||r==="output"||r==="audit"||s)&&c===void 0&&Ee(`${s?"state recover":r} needs --org, the sf CLI alias of the org.`);let u=i("--out");u!==void 0&&n.includes("--quick")&&Ee("--out keeps a plan for apply --plan, which a quick plan cannot be: it counts nothing an apply is held to.");let f=i("--handoff");u===void 0&&f===void 0&&n.includes("--out-in-repository")&&Ee(r==="apply"?"--out-in-repository goes with --handoff: it says where the note may be kept.":"--out-in-repository goes with --out: it says where the plan may be kept.");let d=i("--plan");if(d!==void 0){let w=["--replace","--replace-drifted","--accept-automation","--accept-emails","--accept-user-emails","--accept-no-state"].filter(y=>n.includes(y));w.length>0&&Ee(`${w.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 l=n.includes("--rewind");if(l){let g=["--include-changed","--sweep"].filter(w=>n.includes(w));g.length>0&&Ee(`${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)&&Ee(`${g} goes with --rewind: a destroy by removal is no rewind.`);let h=i("--file"),m=o("--replace");return{command:r,recover:s,file:So(t,h??"sandforge.yaml"),fileGiven:h!==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(m)],replaceDrifted:n.includes("--replace-drifted"),acceptAutomation:n.includes("--accept-automation"),acceptEmails:n.includes("--accept-emails"),acceptUserEmails:n.includes("--accept-user-emails"),acceptNoState:n.includes("--accept-no-state"),includeChanged:n.includes("--include-changed"),sweep:n.includes("--sweep"),rewind:l,acceptNoUndo:n.includes("--accept-no-undo"),acceptUnseen:n.includes("--accept-unseen"),yes:n.includes("--yes"),...u!==void 0?{out:So(t,u)}:{},outInRepository:n.includes("--out-in-repository"),...d!==void 0?{plan:So(t,d)}:{},...f!==void 0?{handoff:So(t,f)}:{},save:n.includes("--save"),failOnFindings:n.includes("--fail-on-findings")}}function hr(){try{let e=JSON.parse(Iy(xt(__dirname,"..","package.json"),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}}var te=class extends Error{constructor(n,r){super(n.refusal.message);this.answer=n;this.code=r;this.name="Stop"}answer;code};function le(e){return new te({refusal:{code:e.code,message:e.message}},e.exit)}function Tc(e){return{path:vn(e.path),...e.resource!==void 0?{resource:e.resource}:{},message:e.message}}function jo(e){let t;try{t=Iy(e,"utf8")}catch(r){throw new te({refusal:{code:"FILE_UNREAD",message:`${e} cannot be read: ${r instanceof Error?r.message:String(r)}`}},2)}let n=yg(t);if("refusal"in n)throw new te({refusal:{code:"INVALID_FILE",message:`${e}: ${n.refusal}`}},2);return n.document}function Ao(e,t){return new te({refusal:{code:"INVALID_FILE",message:`${e} does not validate:
392
+ ${t.map(n=>` ${oc(n)}`).join(`
393
+ `)}`,issues:t.map(Tc)}},2)}async function KA(e){let t,n={request:a=>t??=e.request(a)},r=a=>({unread:a instanceof Error?a.message:String(a)}),s=await Eu(n).catch(r),o="unread"in s||s.dailyApiRequests===void 0?await Ru(n).catch(r):s.dailyApiRequests,i=await Su(n).catch(r);return{apiRequests:o,storage:"unread"in s?s:{remainingMB:s.remainingMB,maxMB:s.maxMB},emails:i}}function VA(e,t){try{return su(JSON.parse(e),t)}catch{return}}function xc(e){return e.trim().split(`
394
+ `).map(t=>t.trim()).filter(Boolean).at(-1)??"it said nothing"}function Py(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 un(e,t,n){let r=jo(e.file),s=kg(r,je(e.file),process.env,{aliases:e.aliases});if("refusals"in s)throw Ao(e.file,s.refusals);let o=s.resolved,i=o.resources.map(A=>A.name);for(let A of e.replace)if(!i.includes(A))throw new te({refusal:{code:"BAD_LINE",message:`--replace ${A} names no resource of the file: it has ${i.join(", ")}.`}},2);let a=t.journalDir??Tr(),c=t.locksDir??Iu(),u=xr(je(e.file),a),f=zr({journalDir:a,fileFolder:je(e.file)});if("refusal"in f)throw le(Hr(f.refusal,u!==void 0));let d=f.store;for(let A of await d.sweep())n(Py(A));let l=e.org??"",h;try{h=await(t.reach??Ny)(l)}catch(A){throw new te({refusal:{code:"NOT_CONNECTED",message:A instanceof No?A.message:`${l} could not be reached: ${A instanceof Error?A.message:String(A)}`}},1)}let m;try{m=await Er(h.conn)}catch(A){m={unread:A instanceof Error?A.message:String(A),error:A}}let g=Cd(l,m,h.session);if("refusal"in g)throw le(g.refusal);let w=g.target,y=Pd(o.checked.file.targets,w);if(y!==void 0)throw le(y);let v;try{v=e.recover?void 0:await d.read(w.organizationId,o.checked.file.name)}catch(A){throw A instanceof L?le(tt(A)):A}if(v!==void 0){let A=Nd(v,o.checked.file.name,w);if(A!==void 0)throw le(A)}let b=[],k,E,S=e.command==="plan"||e.command==="apply";if(v===void 0&&S){let A=await bo({store:d,journalDir:a},{resolved:o,target:w}),P=await d.refreshedOf(w,o.checked.file.name),D=Td(w,o.checked.file.name,e.acceptNoState,A,P);"refusal"in D?k=D.refusal:D.refreshed!==void 0?E=D.refreshed:b.push(D.warning)}let $=ai(o.checked.file.targets,w)?.by==="myDomain";S&&$&&b.push(`${w.alias}: ${Dd(E!==void 0)}`);let j=Du(c,w.organizationId,t.lockOptions);if(j!==void 0&&b.push(`${Nu(j)}: this plan may be out of date when it ends`),S){let A=await WA(o,w,t,n),P=await HA(o,n),D=await YA(o,w,h,{journalDir:a,locksDir:c});if(Object.keys(A).length+Object.keys(P).length+Object.keys(D).length>0){let J=cc(o.checked,process.env,{aliases:e.aliases,sources:A,datasets:P,checkpoints:D});if("refusals"in J)throw Ao(e.file,J.refusals);o=J.resolved}}return{resolved:o,store:d,journalDir:a,locksDir:c,target:w,reached:h,state:v,warnings:b,...k!==void 0?{noState:k}:{},...E!==void 0?{refreshed:E}:{},listedByMyDomain:$,runner:t.runner!==void 0?BA(t.runner,Dy(e.command,process.env[kt]?.trim())):qA({},e.command)}}async function WA(e,t,n,r){let s=new Map,o={};for(let i of e.resources){if(i.kind!=="forge")continue;let{role:a,alias:c}=i.source;r(`${i.name}: reading its source, the ${a} org (${c})`);let u;try{let d=s.get(c);d===void 0&&(d=(n.reach??Ny)(c),s.set(c,d)),u=(await d).conn}catch(d){o[i.name]={refusal:d instanceof No?`the ${a} org: ${d.reason}`:`the ${a} org (${c}) could not be reached: ${d instanceof Error?d.message:String(d)}`};continue}let f=await Bd(u,i.run,a,c);o[i.name]="organizationId"in f&&ke(f.organizationId,t.organizationId)?{refusal:`its source, the ${a} org (${c}), is the org to fill: a clone reads one org and writes another`}:f}return o}async function HA(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 ll(r.dataset.dir,r.run.dataset));return n}async function YA(e,t,n,r){let s={};for(let o of e.resources)o.kind==="replay"&&(s[o.name]=await of(o.run,o.checkpoint,{alias:t.alias,organizationId:t.organizationId,username:n.session.username,instanceUrl:n.session.instanceUrl},{storeRoot:Z(r.journalDir),locksDir:r.locksDir}).catch(i=>({code:"STORE_REFUSED",refusal:`its checkpoint could not be read: ${i instanceof Error?i.message:String(i)}`})));return s}async function Ny(e){let t=await Zc(e);return{session:t,conn:eu(t)}}async function Ty(e,t,n,r){let{state:s,resolved:o,target:i}=e,a={};if(s===void 0)return a;let c={organizationId:i.organizationId,env:o.checked.file.name},u=mt(s,_e(s).map(([f])=>f));for(let f of u){let d=s.resources[f];if(d===void 0)continue;let l=t.acceptAutomation||o.checked.file.resources[f]?.accept?.automation===!0,h=[];for(let m of bp(d.kind,d.runs)){if(r.aborted)break;let g=Rc(m,c,e,f);if(g===void 0){h.push({n:m.n,nothing:!0});continue}n(`${f}: reading what the org holds of run ${m.n}`);let w=vp(d.kind,{target:i.alias,subject:g,includeChanged:t.includeChanged,acceptAutomation:l,checkpointStore:Z(e.journalDir),...t.sweep===!0?{sweep:!0}:{}}),y=await e.runner(w.script,w.args,r),v;try{v={n:m.n,preview:kp(d.kind,y.stdout)}}catch(k){if(!(k instanceof ce))throw k;h.push({n:m.n,failed:`exit ${y.code}: ${xc(y.stderr)}`});continue}let b=t.refresh&&d.status==="applied"&&o.checked.file.resources[f]!==void 0?Ep(d.kind,{target:i.alias,subject:g}):void 0;if(b!==void 0&&!r.aborted){n(`${f}: verifying run ${m.n}`);let k=await e.runner(b.script,b.args,r);try{v={...v,refreshed:Rp(k.stdout)}}catch(E){if(!(E instanceof ce))throw E;v={...v,refreshed:{unread:`exit ${k.code}: ${xc(k.stderr)}`}}}}h.push(v)}a[f]=h}return a}async function JA(e,t){let{resolved:n,state:r,target:s,store:o,journalDir:i}=e,a={};for(let c of n.resources)t.has(c.name)&&(c.kind!=="seed"||(c.run.draws??[]).length===0||(a[c.name]=await ho(c,r,t,{organizationId:s.organizationId,env:n.checked.file.name,target:s.alias},{store:o,journalDir:i})));return a}async function GA(e,t){let{resolved:n,state:r,target:s,store:o,journalDir:i}=e,a=new Set(_e(r).map(([u])=>u)),c=[];for(let u of t){if(!(u.action==="delete"||u.action==="replace"&&!$t(u.kind))||!a.has(u.resource))continue;let d=await bc(r,u.resource,{organizationId:s.organizationId,env:n.checked.file.name,target:s.alias},{store:o,journalDir:i});if(!("refusal"in d))for(let l of d.created.values())c.push(...l)}return c}async function QA(e,t,n,r,s,o={},i=!1,a=!1,c=!1){let{resolved:u,target:f,state:d,store:l}=e,h={},m=new Map(t.filter(y=>y.action==="create"||y.action==="replace"||(y.kind==="mask"||y.kind==="users")&&y.action==="keep").map(y=>[y.resource,y.action]));if(m.size===0)return h;let g=u.checked.file.name;await ju(e.journalDir,new Date).catch(()=>0);let w=PA(xt(xA(),"sandforge-env-plan-"));try{for(let y of u.resources){let v=m.get(y.name);if(v===void 0||s.aborted)continue;if(y.kind==="forge"){let U=y.source.read;if(U===void 0||"refusal"in U)continue}if(y.kind==="frozen"){let U=y.dataset.read;if(U===void 0||"refusal"in U)continue}if(y.kind==="replay"){let U=y.checkpoint.read;if(U===void 0||"refusal"in U)continue}let b=n[y.name];if(b!==void 0&&b.refusals.length>0)continue;let k=xt(w,`${y.name}.json`),E=y.kind==="forge"&&y.run.records!==void 0?Jr(e.journalDir,f.organizationId,g,y.name):void 0,S,$,j;if(y.kind==="frozen"){let U=l.sasOf(f.organizationId,g,rt(y.name));if($=Cy(U)?U:xt(w,`${y.name}.sas`),$===U&&(S=xt(w,`${y.name}.cli-store.json`)),v==="replace"&&$t(y.kind)){let O=await GA(e,t);O.length>0&&(j=xt(w,`${y.name}.gone-first.json`),$y(j,`${JSON.stringify(O)}
395
+ `,{mode:384}))}}let A=Ht(y,{...b!==void 0?{drawn:b.ids}:{},standIns:!0,...$!==void 0?{sasDir:$}:{}});$y(k,`${JSON.stringify(A,null,2)}
396
+ `,{mode:384}),r(`${y.name}: dry run`);let P=o[y.name],D=y.kind==="users"&&v!=="create"?wo(d?.resources[y.name],{organizationId:f.organizationId,env:g},e).run:void 0,x=gt(dp(y,{target:f.alias,templateFile:k,runId:Lr(g,y.name,yn(d?.resources[y.name])),replace:v==="replace"&&$t(y.kind),acceptAutomation:a||u.checked.file.resources[y.name]?.accept?.automation===!0,...P!==void 0?{seed:P}:{},...S!==void 0?{storeFile:S}:{},...j!==void 0?{goneFirstFile:j}:{},...E!==void 0?{rootsPlanFile:E}:{},...y.kind==="mask"?{store:xt(w,`${y.name}.dataops`)}:{},...D!==void 0?{replacesRun:D}:{},...c?{acceptUserEmails:!0}:{},checkpointStore:Z(e.journalDir)}),i),J=await e.runner(x.script,x.args,s);try{h[y.name]={answer:mp(y.kind,J.stdout)}}catch(U){if(!(U instanceof ce))throw U;let O=VA(J.stdout,x.script);h[y.name]={failed:`exit ${J.code}: ${xc(J.stderr)}`,...O?{refused:O}:{}}}}}finally{NA(w,{recursive:!0,force:!0})}return h}async function $o(e,t,n){let r=new AbortController,s,o=(e.onStop??Ge)(i=>{s=i,r.abort()});try{let i=await n(r.signal);if(s!==void 0)throw new te({refusal:{code:"STOPPED",message:`stopped by ${s} while ${t}: nothing was written`}},Pe(s));return i}finally{o()}}function xy(e){let{resolved:t,state:n,store:r,target:s}=e,o=new Set([...t.resources.filter(i=>i.kind==="mask").map(i=>i.name),...Object.entries(n?.resources??{}).filter(([,i])=>i.kind==="mask").map(([i])=>i)]);return Object.fromEntries([...o].map(i=>[i,r.sasOf(s.organizationId,t.checked.file.name,Ut(i))]))}async function Ay(e,t,n,r,s={}){let o={organizationId:e.target.organizationId,kind:e.target.kind,alias:e.target.alias,...e.target.host!==void 0?{host:e.target.host}:{}},i=ZA(e),a={resolved:e.resolved,org:o,state:e.state,replace:t.replace,replaceDrifted:t.replaceDrifted,warnings:e.warnings,maskStores:xy(e),acceptUserEmails:t.acceptUserEmails,...Object.keys(i).length>0?{usersUnknown:i}:{},...e.refreshed!==void 0?{refreshed:e.refreshed}:{},...e.noState!==void 0?{refusal:e.noState.message,refusalCodes:[e.noState.code]}:{}};if(t.quick)return{plan:yc(a),dryRuns:{}};let c=await Ty(e,{includeChanged:!1,acceptAutomation:t.acceptAutomation,refresh:!0},n,r),u=await eO(e,n,r),f=mc({...a,previews:c,...u?{drift:u}:{}}),d=new Set(f.filter(y=>y.action==="create"||y.action==="replace").map(y=>y.resource)),l=await JA(e,d),h=await QA(e,f,l,n,r,s,t.acceptEmails,t.acceptAutomation,t.acceptUserEmails),m=await XA(e,f,h),g=await KA(e.reached.conn),w=await tO(e,f.some(fc),n,r);return{plan:yc({...a,previews:c,dryRuns:h,budget:g,...Object.keys(m).length>0?{maskCreatedAfter:m}:{},...u?{drift:u}:{},...w?{checkpointEstimate:w}:{},draws:Object.fromEntries(Object.entries(l).map(([y,v])=>[y,{draws:v.draws,refusals:v.refusals}]))}),dryRuns:h}}async function XA(e,t,n){let{resolved:r,state:s,target:o,store:i,journalDir:a,reached:c}=e,u=r.resources.map(l=>l.name),f={organizationId:o.organizationId,env:r.checked.file.name,target:o.alias},d={};for(let l of r.resources){if(l.kind!=="mask")continue;let{object:h,where:m}=l.run;if(h===void 0||m===void 0)continue;let g=t.find(y=>y.resource===l.name)?.action==="keep",w=n[l.name];!g||w===void 0||"failed"in w||(d[l.name]=await ql(l.name,s,u,{object:h,where:m},{createdBy:y=>lr(y,f,{store:i,journalDir:a}),count:async y=>(await c.conn.query(y)).totalSize}))}return d}function ZA(e){let{state:t,target:n,resolved:r}=e,s={organizationId:n.organizationId,env:r.checked.file.name},o={};for(let[i,a]of _e(t)){if(a.kind!=="users")continue;let c=wo(a,s,e).unknown;c!==void 0&&(o[i]=c)}return o}async function eO(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(ye,pd({org:e.target.alias,store:Z(e.journalDir),checkpoint:r}),n);return bd(r,s)}async function tO(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 o=await e.runner(ye,fd({org:e.target.alias,store:Z(e.journalDir),...qr(s)}),r);return yd(o)}function nO(e,t){let n=fu(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 rO(e){if(e.kind==="seed"){let s=Wt(e).map(i=>`${i.object} ${i.count??""}`).join(", "),o=(e.draws??[]).map(i=>`${i.relation.childObject}.${i.relation.lookupField} under the ${i.relation.parentObject} records ${i.from} created`);return o.length>0?`${s}; ${o.join(", ")}`:s}if(e.kind==="frozen"){let{path:s,version:o,digest:i}=e.dataset,a=typeof s=="string"?s:`$${s.env}`;return`the Frozen dataset ${o} at ${a} (${i.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 (${Wt(e).map(i=>i.object).join(", ")})`} with ${s}, ${e.rules.rules.length} rule(s)`}if(e.kind==="users")return`User ${e.users.length}, applied first`;if(e.kind==="replay"){let{checkpoint:s}=e,o=s.file;return s.id!==void 0?`a replay of checkpoint ${s.id}`:s.name!==void 0?`a replay of the checkpoint named ${s.name}`+(e.from!==void 0?` of the ${e.from} org`:""):`a replay of the checkpoint file ${typeof o=="string"?o:`$${o?.env??""}`}`}let t=(s,o)=>o!==void 0?`${s} WHERE ${o}`: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 ${Yr(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 sO(e,t){let n=jo(e.file),r=ur(n,je(e.file));if("refusals"in r){t(`${e.file} does not validate:`);for(let d of r.refusals)t(` ${oc(d)}`);return{answer:{file:e.file,valid:!1,issues:r.refusals.map(Tc),warnings:[]},code:2}}let{file:s,order:o,runs:i,variables:a}=r.checked,c=new Set(wg(r.checked,process.env).map(d=>d.name)),u=o.flatMap(d=>{let l=i[d],h=s.resources[d];return l===void 0?[]:[{name:d,kind:l.kind,dependsOn:h!==void 0?ic(d,h):[],...l.kind==="forge"?{source:l.source}:{},objects:Wt(l)}]}),f=r.checked.warnings.map(Tc);t(`${e.file}: valid, the environment ${s.name}`);for(let d of u){let l=i[d.name];t(` ${d.name}: ${l!==void 0?rO(l):""}`+(d.dependsOn.length>0?`, after ${d.dependsOn.join(", ")}`:""))}for(let d of a){let l=d.role!==void 0?`the ${d.role} org`:d.path[2]==="checkpoint"?`the checkpoint file of ${d.resource??""}`:`the dataset of ${d.resource??""}`;t(` variable ${d.name} (${l}): `+(c.has(d.name)?"not set in this shell":"set"))}for(let d of f)t(`warning: ${d.path}: ${d.message}`);return{answer:{file:e.file,valid:!0,env:s.name,resources:u,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:f},code:0}}function oO(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??"",o=t===0?"":`, which keeps ${t===1?"1 other state":`${t} other states`}: "${B("env")} state" lists ${t===1?"it":"them"}`;return`no state of ${s} is kept in ${e}${o}. 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 iO(e,t,n){let r=t.journalDir??Tr(),s=zr({journalDir:r,fileFolder:null});if("refusal"in s)throw le(Hr(s.refusal,!1));let o=await s.store.sweep(),i;if(e.fileGiven){let f=ur(jo(e.file),je(e.file));if("refusals"in f)throw Ao(e.file,f.refusals);i=f.checked.file.name}let a=e.org,c=await s.store.list(),u=c.filter(f=>(i===void 0||f.env===i)&&(a===void 0||f.state?.org.alias===a||f.organizationId.slice(0,15)===a.slice(0,15)));for(let f of o)n(`expired and deleted: ${f.env} on ${f.alias??f.organizationId}`);u.length===0&&n(oO(s.store.root,c.length,i,a));for(let f of u){let d=f.state;if(d===void 0){n(`${f.env} on ${f.organizationId}: not used \u2014 ${f.damaged??""}`);continue}let l=Object.entries(d.resources).map(([h,m])=>`${h} ${m.status}`).join(", ");n(`${d.env} on ${d.org.alias??d.org.organizationId} (${d.org.kind}, ${d.org.organizationId}): serial ${d.serial}, written ${d.updatedAt}`+(f.expiresAt!==void 0?`, expires ${f.expiresAt}`:"")+(l?`; ${l}`:""))}return{journalDir:r,states:u.map(f=>{let d=f.state;if(d===void 0)return{env:f.env,organizationId:f.organizationId,damaged:f.damaged??"not used"};let l=Zo(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(([h,m])=>[h,m.status])),updatedAt:d.updatedAt,...l!==void 0?{expiresAt:l}:{}}}),expired:o.map(f=>({env:f.env,organizationId:f.organizationId,...f.alias!==void 0?{alias:f.alias}:{},expiresAt:f.expiresAt}))}}async function aO(e,t,n){let r=ur(jo(e.file),je(e.file));if("refusals"in r)throw Ao(e.file,r.refusals);let s=t.journalDir??Tr(),o=xr(je(e.file),s),i=zr({journalDir:s,fileFolder:je(e.file)});if("refusal"in i)throw le(Hr(i.refusal,o!==void 0));for(let f of await i.store.sweep())n(Py(f));let a=oy(await i.store.list(),r.checked.file.name,e.org??"");if("refusal"in a)throw le(a.refusal);for(let f of a.setAside??[])n(sy(e.org??"",f,a.state));let{output:c,whole:u}=await Ic(a.state,{store:i.store,journalDir:s});return{answer:c,code:u?0:3}}async function cO(e,t,n){let r=await un(e,t,n),s=await Zg({store:r.store,journalDir:r.journalDir,locksDir:r.locksDir,sandforgeVersion:hr(),...t.lockOptions!==void 0?{lockOptions:t.lockOptions}:{}},{resolved:r.resolved,target:r.target});if("refusal"in s)throw le(s.refusal);for(let o of ey(s.result))n(o);return s.result}function Ly(e){let{target:t}=e;return{organizationId:t.organizationId,kind:t.kind,alias:t.alias,...t.host!==void 0?{host:t.host}:{}}}function Oy(e){let t=e.checked.file.audits,n=hn(t,"apply"),r=t?.handoff===!0;return n!==void 0?`${Fg(n)}${r?"; then the handoff note":""}`:r?"after the apply: the handoff note, written on this machine":void 0}function uO(e){if(e.handoff===void 0)return;let t=je(e.handoff);if(!Cy(t)||!TA(t).isDirectory())return new te({refusal:{code:"BAD_LINE",message:`--handoff ${e.handoff}: its folder ${t} is not there. Nothing was read.`}},2);if(e.outInRepository)return;let n=gn(je(e.file),e.handoff);if(n!==void 0)return new te({refusal:{code:"HANDOFF_IN_REPOSITORY",message:`--handoff ${e.handoff} is inside the repository ${n} that holds the file: the note names the org, its users by their usernames and what is left to do, and committed with the project it would publish them. Keep it outside \u2014 in CI, in $RUNNER_TEMP, kept as an artifact a short time \u2014 or give --out-in-repository for a folder of it that is never committed. Nothing was read.`}},2)}function dO(e){let t=(e.schedules?.jobs??[]).filter(o=>o.status!=="new").length,n=e.endpoints?.found.length??0,r=[e.deliverability?.unread!==void 0?"the deliverability":"",e.schedules?.unread!==void 0?"the scheduled jobs":"",e.endpoints?.unread!==void 0?"the endpoints":""].filter(Boolean),s=[t>0?`${t} scheduled job(s) no longer run`:"",n>0?`${n} endpoint(s) still name production`:"",e.deliverability?.read==="open"?"the org delivers all email":""].filter(Boolean);return`audits: ${s.length>0?`${s.join(", ")} (below)`:"nothing found"}`+(r.length>0?`; not read: ${r.join(", ")} (below)`:"")}async function lO(e,t,n,r){let s=e.resolved.checked.file,o=Ly(e),i=[],a=[],c=n,u=hn(s.audits,"apply");if(u!==void 0){r("audits: reading the org, nothing written");try{let l=await Dr({transport:e.reached.conn,journalDir:e.journalDir},{org:o,asked:u});c={...c,audits:l.result},i.push(dO(l.result)),a.push(...Ac(l.result,{file:t.file,notes:l.notes}))}catch(l){i.push(`audits: not read \u2014 ${l instanceof Error?l.message:String(l)}`)}}let f=new Date().toISOString(),d=t.handoff??(s.audits?.handoff===!0?Vg(e.journalDir,{env:s.name,organizationId:e.target.organizationId,at:f}):void 0);if(d!==void 0)try{let l=await e.store.read(e.target.organizationId,s.name),h=l!==void 0?(await Ic(l,{store:e.store,journalDir:e.journalDir})).output:void 0,m=Kg({run:c,org:o,file:t.file,at:f,sandforgeVersion:hr(),...h!==void 0?{output:h}:{},resources:s.resources,...s.masking!==void 0?{masking:s.masking}:{}});await Wg(d,m),c={...c,handoff:{path:d}},i.push(`handoff note: ${d}`)}catch(l){i.push(`handoff note: not written \u2014 ${l instanceof Error?l.message:String(l)}`)}return{result:c,before:i,after:a}}async function Lc(e,t,n,r){return e.yes||await(t.ask??(o=>nu(o)))(n)===e.org?!0:(r("Nothing was written: the alias typed is not the org\u2019s."),!1)}function Oo(e,t,n){return{runner:e.runner,store:e.store,locksDir:e.locksDir,journalDir:e.journalDir,orgNow:nO(e.reached.conn,n),say:n,sandforgeVersion:hr(),...t.onStop!==void 0?{onStop:t.onStop}:{},...t.lockOptions!==void 0?{lockOptions:t.lockOptions}:{}}}async function jy(e,t,n,r,s){let o=await un(e,t,r),i={verb:n,resolved:o.resolved,target:o.target,state:o.state,acceptAutomation:e.acceptAutomation,acceptEmails:e.acceptEmails,acceptNoUndo:e.acceptNoUndo,acceptUnseen:e.acceptUnseen},a=Pc(i);if(a!==void 0)throw le(a);for(let f of o.warnings)r(`warning: ${f}`);let c;if(!e.yes){let f=await $o(t,"reading what a rewind would do",d=>cy(Oo(o,t,r),i,d));if(!("differs"in f))throw new te({refusal:{code:"REWIND_REFUSED",message:`${f.refusal} Nothing was written.`}},1);c=f;for(let d of Sd(n,o.target.alias,f))r(d);if(f.refusal!==void 0)throw new te({refusal:{code:f.refusal.code,message:f.refusal.message}},1);if(f.differs&&!await Lc(e,t,uy(i,f),r))throw new te({refusal:{code:"DECLINED",message:"Nothing was written."}},1)}let u=await dy(Oo(o,t,r),i,c);for(let f of ly(u.result))r(f);s(u.result),qe(u.exitCode)}async function fO(e=process.argv,t={}){let n=UA(e,t.cwd),r=o=>{process[n.json?"stderr":"stdout"].write(`${o}
397
397
  `)},s=o=>{n.json&&process.stdout.write(`${JSON.stringify(o,null,2)}
398
- `)};try{switch(n.command){case"validate":{let{answer:o,code:i}=eO(n,r);s(o),ze(i);return}case"state":{s(n.recover?await sO(n,t,r):await nO(n,t,r));return}case"output":{let{answer:o,code:i}=await rO(n,t,r);for(let a of ny(o))r(a);s(o),ze(i);return}case"plan":{if(n.out!==void 0){let l=fy(je(n.file),n.out,n.outInRepository);if(l!==void 0)throw le(l)}let o=await cn(n,t,r),{plan:i,dryRuns:a}=await So(t,"planning",l=>Ey(o,n,r,l)),c=Ry(o.resolved);for(let l of uo(i,"apply",c!==void 0?{audits:c}:{}))r(l);if(n.out!==void 0){let l=ly({plan:i,state:o.state,digest:o.resolved.digest,line:{replace:n.replace,replaceDrifted:n.replaceDrifted,acceptAutomation:n.acceptAutomation,...n.acceptEmails?{acceptEmails:!0}:{},acceptNoState:n.acceptNoState,...n.acceptUserEmails?{acceptUserEmails:!0}:{}},dryRuns:a,sandforgeVersion:pr(),madeAt:new Date().toISOString(),listedByMyDomain:o.listedByMyDomain});await py(n.out,l),r(vy(n.out,l))}s(i);let u=n.failOnChange&&yc(i),d=n.failOnDrift&&Sg(i);ze(u||d?3:0);return}case"apply":{n.quick&&Ee("apply makes a whole plan: --quick is for plan alone.");let o=oO(n);if(o!==void 0)throw o;let i,a=n;if(n.plan!==void 0){let w=hy(n.plan);if("refusal"in w)throw le(w.refusal);i=w.saved;let y=my(i,n.plan,{now:Date.now(),sandforgeVersion:pr()});if(y!==void 0)throw le(y);a={...n,...i.line,acceptEmails:i.line.acceptEmails===!0,acceptUserEmails:i.line.acceptUserEmails===!0}}let c=await cn(a,t,r);if(i!==void 0&&n.plan!==void 0){let w=gy(i,n.plan,{target:c.target,digest:c.resolved.digest,state:c.state});if(w!==void 0)throw le(w)}let{plan:u,dryRuns:d}=await So(t,"planning",w=>Ey(c,a,r,w,i?.seeds));if(i!==void 0&&n.plan!==void 0){let w=yy(i.plan,u);if(w.length>0)throw le(wy(n.plan,w))}let l=Ry(c.resolved);for(let w of uo(u,"apply",l!==void 0?{audits:l}:{}))r(w);if(i!==void 0&&n.plan!==void 0&&r(ky(n.plan,i)),u.refusal===void 0&&yc(u)&&!await xc(n,t,`Type ${c.target.alias} to apply ${u.env} to it as planned:`,r))throw new te({refusal:{code:"DECLINED",message:"Nothing was written."}},1);let h=await Ig(Ao(c,t,r),{plan:u,resolved:c.resolved,target:c.target,state:c.state,dryRuns:d,acceptAutomation:a.acceptAutomation,acceptEmails:a.acceptEmails,acceptUserEmails:a.acceptUserEmails}),g=(h.exitCode===0||h.exitCode===3)&&h.result.refusal===void 0?await aO(c,n,h.result,r):{result:h.result,before:[],after:[]};for(let w of Sc(g.result,"apply",g.before))r(w);for(let w of g.after)r(w);s(g.result),ze(h.exitCode);return}case"audit":{let o=await cn(n,t,r),i=await Tg({transport:o.reached.conn,journalDir:o.journalDir},{org:Py(o),audits:o.resolved.checked.file.audits,file:n.file,save:n.save,failOnFindings:n.failOnFindings});if("refusal"in i)throw new te({refusal:i.refusal},i.exitCode);for(let a of i.lines)r(a);s(i.result),ze(i.exitCode);return}case"reset":{await Sy(n,t,"reset",r,s);return}case"destroy":{if(n.rewind){await Sy(n,t,"destroy",r,s);return}let o=await cn(n,t,r),i={organizationId:o.target.organizationId,kind:o.target.kind,alias:o.target.alias,...o.target.host!==void 0?{host:o.target.host}:{}},a=await So(t,"reading what the org holds",d=>Iy(o,{includeChanged:n.includeChanged,acceptAutomation:n.acceptAutomation,refresh:!1,sweep:n.sweep},r,d)),c=Rg({resolved:o.resolved,org:i,state:o.state,previews:a,warnings:o.warnings,maskStores:Dy(o)});for(let d of uo(c,"destroy"))r(d);if(c.refusal===void 0&&c.actions.length>0&&!await xc(n,t,`Type ${o.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 te({refusal:{code:"DECLINED",message:"Nothing was deleted."}},1);let u=await Qg(Ao(o,t,r),{plan:c,resolved:o.resolved,target:o.target,state:o.state,includeChanged:n.includeChanged,sweep:n.sweep,acceptAutomation:n.acceptAutomation});for(let d of Sc(u.result,"destroy"))r(d);s(u.result),ze(u.exitCode);return}}}catch(o){let i=o instanceof te?o:new te({refusal:{code:"FAILED",message:o instanceof Error?o.message:String(o)}},1);process.stderr.write(`${i.message}
399
- `),s(i.answer),ze(i.code)}}process.argv[1]?.includes("sandforge-env")&&(Du(),cO().then(()=>process.exit(process.exitCode??0)).catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
400
- `),process.exit(1)}));export{Oy as envRelayOf,FA as envStepRunner,cO as main,_A as parseArgs,zA as readBudget,MA as relayedRunner};
398
+ `)};try{switch(n.command){case"validate":{let{answer:o,code:i}=sO(n,r);s(o),qe(i);return}case"state":{s(n.recover?await cO(n,t,r):await iO(n,t,r));return}case"output":{let{answer:o,code:i}=await aO(n,t,r);for(let a of iy(o))r(a);s(o),qe(i);return}case"plan":{if(n.out!==void 0){let d=gy(je(n.file),n.out,n.outInRepository);if(d!==void 0)throw le(d)}let o=await un(n,t,r),{plan:i,dryRuns:a}=await $o(t,"planning",d=>Ay(o,n,r,d)),c=Oy(o.resolved);for(let d of lo(i,"apply",c!==void 0?{audits:c}:{}))r(d);if(n.out!==void 0){let d=my({plan:i,state:o.state,digest:o.resolved.digest,line:{replace:n.replace,replaceDrifted:n.replaceDrifted,acceptAutomation:n.acceptAutomation,...n.acceptEmails?{acceptEmails:!0}:{},acceptNoState:n.acceptNoState,...n.acceptUserEmails?{acceptUserEmails:!0}:{}},dryRuns:a,sandforgeVersion:hr(),madeAt:new Date().toISOString(),listedByMyDomain:o.listedByMyDomain});await yy(n.out,d),r(Ry(n.out,d))}s(i);let u=n.failOnChange&&wc(i),f=n.failOnDrift&&jg(i);qe(u||f?3:0);return}case"apply":{n.quick&&Ee("apply makes a whole plan: --quick is for plan alone.");let o=uO(n);if(o!==void 0)throw o;let i,a=n;if(n.plan!==void 0){let w=wy(n.plan);if("refusal"in w)throw le(w.refusal);i=w.saved;let y=vy(i,n.plan,{now:Date.now(),sandforgeVersion:hr()});if(y!==void 0)throw le(y);a={...n,...i.line,acceptEmails:i.line.acceptEmails===!0,acceptUserEmails:i.line.acceptUserEmails===!0}}let c=await un(a,t,r);if(i!==void 0&&n.plan!==void 0){let w=ky(i,n.plan,{target:c.target,digest:c.resolved.digest,state:c.state});if(w!==void 0)throw le(w)}let{plan:u,dryRuns:f}=await $o(t,"planning",w=>Ay(c,a,r,w,i?.seeds));if(i!==void 0&&n.plan!==void 0){let w=by(i.plan,u);if(w.length>0)throw le(Ey(n.plan,w))}let d=Oy(c.resolved);for(let w of lo(u,"apply",d!==void 0?{audits:d}:{}))r(w);if(i!==void 0&&n.plan!==void 0&&r(Sy(n.plan,i)),u.refusal===void 0&&wc(u)&&!await Lc(n,t,`Type ${c.target.alias} to apply ${u.env} to it as planned:`,r))throw new te({refusal:{code:"DECLINED",message:"Nothing was written."}},1);let h=await Tg(Oo(c,t,r),{plan:u,resolved:c.resolved,target:c.target,state:c.state,dryRuns:f,acceptAutomation:a.acceptAutomation,acceptEmails:a.acceptEmails,acceptUserEmails:a.acceptUserEmails}),g=(h.exitCode===0||h.exitCode===3)&&h.result.refusal===void 0?await lO(c,n,h.result,r):{result:h.result,before:[],after:[]};for(let w of $c(g.result,"apply",g.before))r(w);for(let w of g.after)r(w);s(g.result),qe(h.exitCode);return}case"audit":{let o=await un(n,t,r),i=await Mg({transport:o.reached.conn,journalDir:o.journalDir},{org:Ly(o),audits:o.resolved.checked.file.audits,file:n.file,save:n.save,failOnFindings:n.failOnFindings});if("refusal"in i)throw new te({refusal:i.refusal},i.exitCode);for(let a of i.lines)r(a);s(i.result),qe(i.exitCode);return}case"reset":{await jy(n,t,"reset",r,s);return}case"destroy":{if(n.rewind){await jy(n,t,"destroy",r,s);return}let o=await un(n,t,r),i={organizationId:o.target.organizationId,kind:o.target.kind,alias:o.target.alias,...o.target.host!==void 0?{host:o.target.host}:{}},a=await $o(t,"reading what the org holds",f=>Ty(o,{includeChanged:n.includeChanged,acceptAutomation:n.acceptAutomation,refresh:!1,sweep:n.sweep},r,f)),c=Og({resolved:o.resolved,org:i,state:o.state,previews:a,warnings:o.warnings,maskStores:xy(o)});for(let f of lo(c,"destroy"))r(f);if(c.refusal===void 0&&c.actions.length>0&&!await Lc(n,t,`Type ${o.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 te({refusal:{code:"DECLINED",message:"Nothing was deleted."}},1);let u=await ty(Oo(o,t,r),{plan:c,resolved:o.resolved,target:o.target,state:o.state,includeChanged:n.includeChanged,sweep:n.sweep,acceptAutomation:n.acceptAutomation});for(let f of $c(u.result,"destroy"))r(f);s(u.result),qe(u.exitCode);return}}}catch(o){let i=o instanceof te?o:new te({refusal:{code:"FAILED",message:o instanceof Error?o.message:String(o)}},1);process.stderr.write(`${i.message}
399
+ `),s(i.answer),qe(i.code)}}process.argv[1]?.includes("sandforge-env")&&(Tu(),fO().then(()=>process.exit(process.exitCode??0)).catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
400
+ `),process.exit(1)}));export{Dy as envRelayOf,qA as envStepRunner,fO as main,UA as parseArgs,KA as readBudget,BA as relayedRunner};