@ghfs/cli 0.1.0 → 0.2.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 (349) hide show
  1. package/README.md +41 -1
  2. package/dist/cli.mjs +5718 -559
  3. package/dist/factory-UMSInaa_.mjs +1166 -0
  4. package/dist/index.d.mts +363 -2
  5. package/dist/index.mjs +1 -1
  6. package/dist/ui/200.html +1 -1
  7. package/dist/ui/404.html +1 -1
  8. package/dist/ui/_nuxt/2UxHyX5q.js +1 -0
  9. package/dist/ui/_nuxt/32ctXXKs.js +1 -0
  10. package/dist/ui/_nuxt/3e1v2bzS.js +1 -0
  11. package/dist/ui/_nuxt/3t-6YNGz.js +1 -0
  12. package/dist/ui/_nuxt/4A_iFExJ.js +1 -0
  13. package/dist/ui/_nuxt/5VeTt0Ye.js +1 -0
  14. package/dist/ui/_nuxt/5i3qLPDT.js +1 -0
  15. package/dist/ui/_nuxt/85-TOEBH.js +1 -0
  16. package/dist/ui/_nuxt/B0m2ddpp.js +1 -0
  17. package/dist/ui/_nuxt/B0tHio-l.js +1 -0
  18. package/dist/ui/_nuxt/B1dDrJ26.js +1 -0
  19. package/dist/ui/_nuxt/B1yitclQ.js +1 -0
  20. package/dist/ui/_nuxt/B5q1GTce.js +1 -0
  21. package/dist/ui/_nuxt/B6aJPvgy.js +1 -0
  22. package/dist/ui/_nuxt/B7c-h3xW.js +1 -0
  23. package/dist/ui/_nuxt/B7mTdjB0.js +1 -0
  24. package/dist/ui/_nuxt/BA47KaF1.js +1 -0
  25. package/dist/ui/_nuxt/BBf5iR-q.js +1 -0
  26. package/dist/ui/_nuxt/BBxLfTx_.js +1 -0
  27. package/dist/ui/_nuxt/BDEKrZIi.js +1 -0
  28. package/dist/ui/_nuxt/BEDo0Tqx.js +1 -0
  29. package/dist/ui/_nuxt/BERRCDM3.js +1 -0
  30. package/dist/ui/_nuxt/BETggiCN.js +1 -0
  31. package/dist/ui/_nuxt/BEwlwnbL.js +1 -0
  32. package/dist/ui/_nuxt/BFfxhgS-.js +1 -0
  33. package/dist/ui/_nuxt/BGJmEYvX.js +1 -0
  34. package/dist/ui/_nuxt/BH7IYjvW.js +1 -0
  35. package/dist/ui/_nuxt/BIGW1oBm.js +1 -0
  36. package/dist/ui/_nuxt/BIv1doCn.js +1 -0
  37. package/dist/ui/_nuxt/BJDFO7_C.js +1 -0
  38. package/dist/ui/_nuxt/BM1_JUlF.js +1 -0
  39. package/dist/ui/_nuxt/BMKCr1FU.js +1 -0
  40. package/dist/ui/_nuxt/BMWR74SV.js +1 -0
  41. package/dist/ui/_nuxt/BO53GVu8.js +1 -0
  42. package/dist/ui/_nuxt/BPQ3VLAy.js +1 -0
  43. package/dist/ui/_nuxt/BQ8w6xss.js +1 -0
  44. package/dist/ui/_nuxt/BRHolxvo.js +1 -0
  45. package/dist/ui/_nuxt/BRZ36xJF.js +1 -0
  46. package/dist/ui/_nuxt/BTJTHyun.js +1 -0
  47. package/dist/ui/_nuxt/BTifaqeh.js +1 -0
  48. package/dist/ui/_nuxt/BUtzH8cE.js +1 -0
  49. package/dist/ui/_nuxt/BUw7H-hv.js +1 -0
  50. package/dist/ui/_nuxt/BV7otONQ.js +1 -0
  51. package/dist/ui/_nuxt/BVQ-GDCI.js +1 -0
  52. package/dist/ui/_nuxt/BVkGXMyj.js +1 -0
  53. package/dist/ui/_nuxt/BWvSN4gD.js +1 -0
  54. package/dist/ui/_nuxt/BXkSAIEj.js +1 -0
  55. package/dist/ui/_nuxt/BYunw83y.js +1 -0
  56. package/dist/ui/_nuxt/BZvkOJ9d.js +1 -0
  57. package/dist/ui/_nuxt/B_m7g4N7.js +1 -0
  58. package/dist/ui/_nuxt/BcOcwvcX.js +1 -0
  59. package/dist/ui/_nuxt/BcVCzyr7.js +1 -0
  60. package/dist/ui/_nuxt/BcllPdc-.js +1 -0
  61. package/dist/ui/_nuxt/BdImnpbu.js +1 -0
  62. package/dist/ui/_nuxt/BdnUsdx6.js +1 -0
  63. package/dist/ui/_nuxt/BeJSdlF9.js +1 -0
  64. package/dist/ui/_nuxt/BfHTSMKl.js +1 -0
  65. package/dist/ui/_nuxt/BfSCyJF4.js +1 -0
  66. package/dist/ui/_nuxt/BfjtVDDH.js +1 -0
  67. package/dist/ui/_nuxt/BgDCqdQA.js +1 -0
  68. package/dist/ui/_nuxt/BhOHFoWU.js +1 -0
  69. package/dist/ui/_nuxt/BkioyH1T.js +1 -0
  70. package/dist/ui/_nuxt/Bkuqu6BP.js +1 -0
  71. package/dist/ui/_nuxt/BmXAJ9_W.js +1 -0
  72. package/dist/ui/_nuxt/Bmn6On1c.js +1 -0
  73. package/dist/ui/_nuxt/Bp6g37R7.js +1 -0
  74. package/dist/ui/_nuxt/BqNa2AkI.js +1 -0
  75. package/dist/ui/_nuxt/BqTXFGrv.js +1 -0
  76. package/dist/ui/_nuxt/BqYA7rlc.js +1 -0
  77. package/dist/ui/_nuxt/Br6cN0cg.js +1 -0
  78. package/dist/ui/_nuxt/BsS91CYL.js +1 -0
  79. package/dist/ui/_nuxt/BshV_Xbc.js +1 -0
  80. package/dist/ui/_nuxt/BspZqrRM.js +1 -0
  81. package/dist/ui/_nuxt/BtCnVYZw.js +1 -0
  82. package/dist/ui/_nuxt/BtOb2qkB.js +1 -0
  83. package/dist/ui/_nuxt/BthQWCQV.js +1 -0
  84. package/dist/ui/_nuxt/BtqSS_iP.js +1 -0
  85. package/dist/ui/_nuxt/Buea-lGh.js +1 -0
  86. package/dist/ui/_nuxt/BvOdM423.js +1 -0
  87. package/dist/ui/_nuxt/Bv_4Rxtq.js +1 -0
  88. package/dist/ui/_nuxt/BvzEVeQv.js +1 -0
  89. package/dist/ui/_nuxt/Bw305WKR.js +1 -0
  90. package/dist/ui/_nuxt/BxgE0vQu.js +1 -0
  91. package/dist/ui/_nuxt/BzJJZx-M.js +1 -0
  92. package/dist/ui/_nuxt/Bzq9aFVy.js +1 -0
  93. package/dist/ui/_nuxt/C-SQnVFl.js +1 -0
  94. package/dist/ui/_nuxt/C0HS_06l.js +1 -0
  95. package/dist/ui/_nuxt/C0hk2d4L.js +1 -0
  96. package/dist/ui/_nuxt/C151Ov-r.js +1 -0
  97. package/dist/ui/_nuxt/C27-OAKa.js +1 -0
  98. package/dist/ui/_nuxt/C2t-YnRu.js +1 -0
  99. package/dist/ui/_nuxt/C39BiMTA.js +1 -0
  100. package/dist/ui/_nuxt/C3B-1QV4.js +1 -0
  101. package/dist/ui/_nuxt/C3Wv6jpd.js +1 -0
  102. package/dist/ui/_nuxt/C3mMm8J8.js +1 -0
  103. package/dist/ui/_nuxt/C4EeE6gA.js +1 -0
  104. package/dist/ui/_nuxt/C4IJs8-o.js +1 -0
  105. package/dist/ui/_nuxt/C4gqWexZ.js +1 -0
  106. package/dist/ui/_nuxt/C5BYcBs_.js +1 -0
  107. package/dist/ui/_nuxt/C5YyOfLZ.js +1 -0
  108. package/dist/ui/_nuxt/C7zT0LnQ.js +1 -0
  109. package/dist/ui/_nuxt/C8M2exoo.js +1 -0
  110. package/dist/ui/_nuxt/C8lEn-DE.js +1 -0
  111. package/dist/ui/_nuxt/C98Dy4si.js +1 -0
  112. package/dist/ui/_nuxt/C9dUb6Cb.js +1 -0
  113. package/dist/ui/_nuxt/C9oPPf7i.js +1 -0
  114. package/dist/ui/_nuxt/C9tS-k6U.js +1 -0
  115. package/dist/ui/_nuxt/CAFt9gP4.js +1 -0
  116. package/dist/ui/_nuxt/CBaQQc7g.js +1 -0
  117. package/dist/ui/_nuxt/CDBrVQLm.js +1 -0
  118. package/dist/ui/_nuxt/CDVJQ6XC.js +1 -0
  119. package/dist/ui/_nuxt/CDx5xZoG.js +1 -0
  120. package/dist/ui/_nuxt/CEL-wOlO.js +1 -0
  121. package/dist/ui/_nuxt/CEu0bR-o.js +1 -0
  122. package/dist/ui/_nuxt/CFHQjOhq.js +1 -0
  123. package/dist/ui/_nuxt/CG6Dc4jp.js +1 -0
  124. package/dist/ui/_nuxt/CH1njM8p.js +1 -0
  125. package/dist/ui/_nuxt/CHLpvVh8.js +1 -0
  126. package/dist/ui/_nuxt/CHM0blh-.js +1 -0
  127. package/dist/ui/_nuxt/CJc9bBzg.js +1 -0
  128. package/dist/ui/_nuxt/CKIfxQSi.js +1 -0
  129. package/dist/ui/_nuxt/CLj8gQPS.js +1 -0
  130. package/dist/ui/_nuxt/CLxacb5B.js +1 -0
  131. package/dist/ui/_nuxt/CMTm3GFP.js +1 -0
  132. package/dist/ui/_nuxt/CO1LY3CK.js +1 -0
  133. package/dist/ui/_nuxt/COkxafJQ.js +1 -0
  134. package/dist/ui/_nuxt/COt5Ahok.js +1 -0
  135. package/dist/ui/_nuxt/CRqJ_cUM.js +1 -0
  136. package/dist/ui/_nuxt/CS3Unz2-.js +1 -0
  137. package/dist/ui/_nuxt/CSXwinHm.js +1 -0
  138. package/dist/ui/_nuxt/CTRr51gU.js +1 -0
  139. package/dist/ui/_nuxt/CUuTKBJd.js +1 -0
  140. package/dist/ui/_nuxt/CV3vykTa.js +1 -0
  141. package/dist/ui/_nuxt/CVO1_9PV.js +1 -0
  142. package/dist/ui/_nuxt/CVdnzihN.js +1 -0
  143. package/dist/ui/_nuxt/CXtECtnM.js +1 -0
  144. package/dist/ui/_nuxt/CXvaQtF9.js +1 -0
  145. package/dist/ui/_nuxt/CYsAdtH9.js +1 -0
  146. package/dist/ui/_nuxt/CafNBF8u.js +1 -0
  147. package/dist/ui/_nuxt/CbFg5uaA.js +1 -0
  148. package/dist/ui/_nuxt/CbfX1IO0.js +1 -0
  149. package/dist/ui/_nuxt/CcsQSqEB.js +1 -0
  150. package/dist/ui/_nuxt/CeAyd5Ju.js +1 -0
  151. package/dist/ui/_nuxt/CeZK1NFH.js +1 -0
  152. package/dist/ui/_nuxt/CenWIFCC.js +1 -0
  153. package/dist/ui/_nuxt/CfQXZHmo.js +1 -0
  154. package/dist/ui/_nuxt/Cg-RD9OK.js +1 -0
  155. package/dist/ui/_nuxt/ChMvpjG-.js +1 -0
  156. package/dist/ui/_nuxt/ChS_g7wu.js +1 -0
  157. package/dist/ui/_nuxt/ChgxH8nk.js +1 -0
  158. package/dist/ui/_nuxt/Cj5Yp3dK.js +1 -0
  159. package/dist/ui/_nuxt/CkByrt1z.js +1 -0
  160. package/dist/ui/_nuxt/CkXjmgJE.js +1 -0
  161. package/dist/ui/_nuxt/CklMAg4u.js +1 -0
  162. package/dist/ui/_nuxt/Cmh6b_Ma.js +1 -0
  163. package/dist/ui/_nuxt/CnnmHF94.js +1 -0
  164. package/dist/ui/_nuxt/CnsnAmq5.js +1 -0
  165. package/dist/ui/_nuxt/Co6uUVPk.js +1 -0
  166. package/dist/ui/_nuxt/CoDkCxhg.js +1 -0
  167. package/dist/ui/_nuxt/Cp-IABpG.js +1 -0
  168. package/dist/ui/_nuxt/Cp8Y5tLI.js +1 -0
  169. package/dist/ui/_nuxt/Cq5zzVJU.js +1 -0
  170. package/dist/ui/_nuxt/CquLrc37.js +1 -0
  171. package/dist/ui/_nuxt/CrQuFoFY.js +1 -0
  172. package/dist/ui/_nuxt/Cs0ovY-E.js +1 -0
  173. package/dist/ui/_nuxt/CsfeWuGM.js +1 -0
  174. package/dist/ui/_nuxt/Csfq5Kiy.js +1 -0
  175. package/dist/ui/_nuxt/CuPHTKiy.js +1 -0
  176. package/dist/ui/_nuxt/CufHLc7y.js +1 -0
  177. package/dist/ui/_nuxt/Cuk6v7N8.js +1 -0
  178. package/dist/ui/_nuxt/Cvjx9yec.js +1 -0
  179. package/dist/ui/_nuxt/CwoSXNpI.js +1 -0
  180. package/dist/ui/_nuxt/CxGSJlkm.js +1 -0
  181. package/dist/ui/_nuxt/CxbxFI8M.js +1 -0
  182. package/dist/ui/_nuxt/CyktbL80.js +1 -0
  183. package/dist/ui/_nuxt/CylS5w8V.js +1 -0
  184. package/dist/ui/_nuxt/Cz2AlsmD.js +1 -0
  185. package/dist/ui/_nuxt/CzTSHFRz.js +1 -0
  186. package/dist/ui/_nuxt/D-2ljcwZ.js +1 -0
  187. package/dist/ui/_nuxt/D0YGMca9.js +1 -0
  188. package/dist/ui/_nuxt/D0jeqgqx.js +1 -0
  189. package/dist/ui/_nuxt/D0r3Knsf.js +1 -0
  190. package/dist/ui/_nuxt/D17OF-Vu.js +1 -0
  191. package/dist/ui/_nuxt/D1j8_8rp.js +1 -0
  192. package/dist/ui/_nuxt/D2j5LXpq.js +1 -0
  193. package/dist/ui/_nuxt/D3apom_0.js +1 -0
  194. package/dist/ui/_nuxt/D3lLCCz7.js +1 -0
  195. package/dist/ui/_nuxt/D4_iv3hh.js +1 -0
  196. package/dist/ui/_nuxt/D4h5O-jR.js +1 -0
  197. package/dist/ui/_nuxt/D5-asLiD.js +1 -0
  198. package/dist/ui/_nuxt/D53aC0YG.js +1 -0
  199. package/dist/ui/_nuxt/D5KoaKCx.js +1 -0
  200. package/dist/ui/_nuxt/D7o27uSR.js +1 -0
  201. package/dist/ui/_nuxt/D7oLnXFd.js +1 -0
  202. package/dist/ui/_nuxt/D82EKSYY.js +1 -0
  203. package/dist/ui/_nuxt/D82vCrfD.js +1 -0
  204. package/dist/ui/_nuxt/D87Tk5Gz.js +1 -0
  205. package/dist/ui/_nuxt/D8l8udqQ.js +1 -0
  206. package/dist/ui/_nuxt/D93ZcfNL.js +1 -0
  207. package/dist/ui/_nuxt/D97Zzqfu.js +1 -0
  208. package/dist/ui/_nuxt/DAi9KRSo.js +1 -0
  209. package/dist/ui/_nuxt/DCJHYwE6.js +67 -0
  210. package/dist/ui/_nuxt/DFQXde-d.js +1 -0
  211. package/dist/ui/_nuxt/DFWUc33u.js +1 -0
  212. package/dist/ui/_nuxt/DFXneXwc.js +1 -0
  213. package/dist/ui/_nuxt/DGztddWO.js +1 -0
  214. package/dist/ui/_nuxt/DH5Ifo-i.js +1 -0
  215. package/dist/ui/_nuxt/DHCkPAjA.js +1 -0
  216. package/dist/ui/_nuxt/DHJKELXO.js +1 -0
  217. package/dist/ui/_nuxt/DHQR4-dF.js +1 -0
  218. package/dist/ui/_nuxt/DMk3OuwW.js +1 -0
  219. package/dist/ui/_nuxt/DMkUaiYH.js +1 -0
  220. package/dist/ui/_nuxt/DMzUqQB5.js +1 -0
  221. package/dist/ui/_nuxt/DQyhUUbL.js +1 -0
  222. package/dist/ui/_nuxt/DRcdqDVD.js +1 -0
  223. package/dist/ui/_nuxt/DRg8JJMk.js +1 -0
  224. package/dist/ui/_nuxt/DRje8inN.js +1 -0
  225. package/dist/ui/_nuxt/DRw_LuNl.js +1 -0
  226. package/dist/ui/_nuxt/DS2KJUFh.js +1 -0
  227. package/dist/ui/_nuxt/DSSpBswy.js +1 -0
  228. package/dist/ui/_nuxt/DSvCPggb.js +1 -0
  229. package/dist/ui/_nuxt/DT3CNIhV.js +1 -0
  230. package/dist/ui/_nuxt/DToHIG1N.js +1 -0
  231. package/dist/ui/_nuxt/DUszq2jm.js +1 -0
  232. package/dist/ui/_nuxt/DV7GczEv.js +1 -0
  233. package/dist/ui/_nuxt/DVFEvuxE.js +1 -0
  234. package/dist/ui/_nuxt/DVMEJ2y_.js +1 -0
  235. package/dist/ui/_nuxt/DVxCFoDh.js +1 -0
  236. package/dist/ui/_nuxt/{BXG6gk4R.js → DWbelWgw.js} +1 -1
  237. package/dist/ui/_nuxt/DWedfzmr.js +1 -0
  238. package/dist/ui/_nuxt/DWrx1Km3.js +1 -0
  239. package/dist/ui/_nuxt/DXbdFlpD.js +1 -0
  240. package/dist/ui/_nuxt/DXmwc3jG.js +1 -0
  241. package/dist/ui/_nuxt/DXvB9xmW.js +1 -0
  242. package/dist/ui/_nuxt/DYE7WIF3.js +1 -0
  243. package/dist/ui/_nuxt/DZ9PSxVF.js +1 -0
  244. package/dist/ui/_nuxt/DZxFcAj9.js +1 -0
  245. package/dist/ui/_nuxt/D_Q5rh1f.js +1 -0
  246. package/dist/ui/_nuxt/Da5cRb03.js +1 -0
  247. package/dist/ui/_nuxt/Dc-5oQ3p.js +1 -0
  248. package/dist/ui/_nuxt/Dc-i7Zfu.js +1 -0
  249. package/dist/ui/_nuxt/DcWK9jms.js +1 -0
  250. package/dist/ui/_nuxt/DcaNXYhu.js +1 -0
  251. package/dist/ui/_nuxt/Dd19v3D-.js +1 -0
  252. package/dist/ui/_nuxt/DdkO51Og.js +1 -0
  253. package/dist/ui/_nuxt/Ddv68eIx.js +1 -0
  254. package/dist/ui/_nuxt/Des-eS-w.js +1 -0
  255. package/dist/ui/_nuxt/Df2X-ZUM.js +1 -0
  256. package/dist/ui/_nuxt/Df6bDoY_.js +1 -0
  257. package/dist/ui/_nuxt/DfNjGIrv.js +1 -0
  258. package/dist/ui/_nuxt/DhaVEd23.js +1 -0
  259. package/dist/ui/_nuxt/DhaYTIfE.js +1 -0
  260. package/dist/ui/_nuxt/DiuiI0_S.js +1 -0
  261. package/dist/ui/_nuxt/DjAJT7YJ.js +1 -0
  262. package/dist/ui/_nuxt/DkFqJrB1.js +1 -0
  263. package/dist/ui/_nuxt/DkwncUOv.js +1 -0
  264. package/dist/ui/_nuxt/Dl1uYT3n.js +15 -0
  265. package/dist/ui/_nuxt/DnULxvSX.js +1 -0
  266. package/dist/ui/_nuxt/Dpen1YoG.js +1 -0
  267. package/dist/ui/_nuxt/Dph4kLrZ.js +1 -0
  268. package/dist/ui/_nuxt/DqQDbK_p.js +1 -0
  269. package/dist/ui/_nuxt/Dqspr-GT.js +1 -0
  270. package/dist/ui/_nuxt/DqwNpetd.js +1 -0
  271. package/dist/ui/_nuxt/DsOJ9woJ.js +1 -0
  272. package/dist/ui/_nuxt/Dsmy0J62.js +1 -0
  273. package/dist/ui/_nuxt/Dspwwk_N.js +1 -0
  274. package/dist/ui/_nuxt/Dx-B1_4e.js +1 -0
  275. package/dist/ui/_nuxt/DyxjwDmM.js +1 -0
  276. package/dist/ui/_nuxt/E3gJ1_iC.js +1 -0
  277. package/dist/ui/_nuxt/GsRaNv29.js +1 -0
  278. package/dist/ui/_nuxt/HgPamjhh.js +1 -0
  279. package/dist/ui/_nuxt/IF9eRakj.js +1 -0
  280. package/dist/ui/_nuxt/IeuSbFQv.js +1 -0
  281. package/dist/ui/_nuxt/KW6xsasC.js +1 -0
  282. package/dist/ui/_nuxt/L9t79GZl.js +1 -0
  283. package/dist/ui/_nuxt/LYj2JSs-.js +1 -0
  284. package/dist/ui/_nuxt/MRO5bC_T.js +1 -0
  285. package/dist/ui/_nuxt/MzD3tlZU.js +1 -0
  286. package/dist/ui/_nuxt/P80f7IUj.js +1 -0
  287. package/dist/ui/_nuxt/Pmp26Uib.js +1 -0
  288. package/dist/ui/_nuxt/Project.BMA756E4.css +1 -0
  289. package/dist/ui/_nuxt/QIJgUcNo.js +1 -0
  290. package/dist/ui/_nuxt/VOosw3JB.js +1 -0
  291. package/dist/ui/_nuxt/Ve4PFQV2.js +1 -0
  292. package/dist/ui/_nuxt/W70NOuRA.js +1 -0
  293. package/dist/ui/_nuxt/Yzrsuije.js +1 -0
  294. package/dist/ui/_nuxt/_H4v1dQx.js +1 -0
  295. package/dist/ui/_nuxt/_ykCGR6B.js +1 -0
  296. package/dist/ui/_nuxt/bCR0ucgS.js +1 -0
  297. package/dist/ui/_nuxt/bE4Kk8sk.js +1 -0
  298. package/dist/ui/_nuxt/bN70gL4F.js +1 -0
  299. package/dist/ui/_nuxt/builds/latest.json +1 -1
  300. package/dist/ui/_nuxt/builds/meta/283a6ae8-b1fa-4a56-aab5-927ed1779674.json +1 -0
  301. package/dist/ui/_nuxt/dwOrl1Do.js +1 -0
  302. package/dist/ui/_nuxt/e9S_qqu4.js +1 -0
  303. package/dist/ui/_nuxt/entry.DnCs62PI.css +1 -0
  304. package/dist/ui/_nuxt/error-404.CiGdHkfa.css +1 -0
  305. package/dist/ui/_nuxt/error-500.DrZuPeVU.css +1 -0
  306. package/dist/ui/_nuxt/fuZLfV_i.js +1 -0
  307. package/dist/ui/_nuxt/g9-lgVsj.js +1 -0
  308. package/dist/ui/_nuxt/gcz8RCvz.js +1 -0
  309. package/dist/ui/_nuxt/hJgmCMqR.js +1 -0
  310. package/dist/ui/_nuxt/hegEt444.js +1 -0
  311. package/dist/ui/_nuxt/index.C3E0NnSu.css +1 -0
  312. package/dist/ui/_nuxt/ivQhLDHX.js +11 -0
  313. package/dist/ui/_nuxt/k_qm7-4y.js +1 -0
  314. package/dist/ui/_nuxt/ka8bt-K2.js +153 -0
  315. package/dist/ui/_nuxt/lBpI9LM0.js +1 -0
  316. package/dist/ui/_nuxt/lXgVvXCa.js +1 -0
  317. package/dist/ui/_nuxt/mWjccvbQ.js +1 -0
  318. package/dist/ui/_nuxt/n2N0HUVH.js +1 -0
  319. package/dist/ui/_nuxt/qdsjHGoJ.js +1 -0
  320. package/dist/ui/_nuxt/rGO070M0.js +1 -0
  321. package/dist/ui/_nuxt/rZm6bMo-.js +1 -0
  322. package/dist/ui/_nuxt/rgL8RFrC.js +1 -0
  323. package/dist/ui/_nuxt/u5AG7uiY.js +1 -0
  324. package/dist/ui/_nuxt/uYugtg8r.js +1 -0
  325. package/dist/ui/_nuxt/vE_lwT2v.js +1 -0
  326. package/dist/ui/_nuxt/vGWfd6FD.js +1 -0
  327. package/dist/ui/_nuxt/wDzz0qaB.js +1 -0
  328. package/dist/ui/_nuxt/wEQ09or8.js +1 -0
  329. package/dist/ui/_nuxt/yv6CvBhz.js +1 -0
  330. package/dist/ui/_nuxt/zinMudAE.js +1 -0
  331. package/dist/ui/hub/index.html +1 -0
  332. package/dist/ui/hub/queue/index.html +1 -0
  333. package/dist/ui/hub/recent/index.html +1 -0
  334. package/dist/ui/index.html +1 -1
  335. package/dist/ui/queue/index.html +1 -0
  336. package/dist/ui/recent/index.html +1 -0
  337. package/package.json +27 -24
  338. package/skills/ghfs/SKILL.md +10 -0
  339. package/dist/factory-DypZ8oi9.mjs +0 -570
  340. package/dist/provider-BFJGpjCs.d.mts +0 -203
  341. package/dist/server/index.d.mts +0 -287
  342. package/dist/server/index.mjs +0 -2
  343. package/dist/server-n1FLF8Xo.mjs +0 -3331
  344. package/dist/ui/_nuxt/BMIwt_GL.js +0 -1
  345. package/dist/ui/_nuxt/DA9k4Rdg.js +0 -69
  346. package/dist/ui/_nuxt/builds/meta/64045338-3c37-4c7d-a0df-5b21000f8b0a.json +0 -1
  347. package/dist/ui/_nuxt/entry.B5oa46-c.css +0 -1
  348. package/dist/ui/_nuxt/error-404.CktHaldI.css +0 -1
  349. package/dist/ui/_nuxt/error-500.DVdbZfrj.css +0 -1
@@ -1,3331 +0,0 @@
1
- import { a as formatIssueNumber, n as normalizeReactions, t as createRepositoryProvider } from "./factory-DypZ8oi9.mjs";
2
- import { distDir } from "./dir.mjs";
3
- import process from "node:process";
4
- import { basename, dirname, isAbsolute, join, resolve } from "pathe";
5
- import { spawn } from "node:child_process";
6
- import { existsSync } from "node:fs";
7
- import { createJiti } from "jiti";
8
- import { access, mkdir, readFile, readdir, rename, rm, stat, watch, writeFile } from "node:fs/promises";
9
- import * as v from "valibot";
10
- import { parse, stringify } from "yaml";
11
- import { randomBytes } from "node:crypto";
12
- import { Buffer } from "node:buffer";
13
- import { createServer } from "node:http";
14
- import { createBirpc } from "birpc";
15
- import { getPort } from "get-port-please";
16
- import { createApp, createRouter, eventHandler, serveStatic, setResponseHeader, setResponseStatus, toNodeListener } from "h3";
17
- import { parse as parse$1, stringify as stringify$1 } from "structured-clone-es";
18
- import { WebSocketServer } from "ws";
19
- import { hash } from "ohash";
20
- //#region src/constants.ts
21
- const CONFIG_FILE_CANDIDATES = [
22
- "ghfs.config.ts",
23
- "ghfs.config.mts",
24
- "ghfs.config.mjs",
25
- "ghfs.config.js",
26
- "ghfs.config.cjs"
27
- ];
28
- const ISSUE_DIR_NAME = "issues";
29
- const PULL_DIR_NAME = "pulls";
30
- const CLOSED_DIR_NAME = "closed";
31
- const SYNC_STATE_FILE_NAME = ".sync.json";
32
- const ISSUES_INDEX_FILE_NAME = "issues.md";
33
- const PULLS_INDEX_FILE_NAME = "pulls.md";
34
- const REPO_SNAPSHOT_FILE_NAME = "repo.json";
35
- const EXECUTE_FILE_NAME = "execute.yml";
36
- const EXECUTE_MD_FILE_NAME = "execute.md";
37
- const EXECUTE_SCHEMA_RELATIVE_PATH = "schema/execute.schema.json";
38
- //#endregion
39
- //#region src/config/load.ts
40
- async function loadUserConfig(cwd) {
41
- const configPath = findConfigFile(cwd);
42
- if (!configPath) return { config: {} };
43
- return {
44
- path: configPath,
45
- config: extractUserConfig(await createJiti(resolve(cwd, "ghfs.config.ts"), { interopDefault: true }).import(configPath))
46
- };
47
- }
48
- function extractUserConfig(loaded) {
49
- if (!loaded || typeof loaded !== "object") return {};
50
- if ("default" in loaded) {
51
- const config = loaded.default;
52
- if (config && typeof config === "object") return config;
53
- return {};
54
- }
55
- return loaded;
56
- }
57
- async function resolveConfig(options = {}) {
58
- const cwd = options.cwd ?? process.cwd();
59
- const overrides = options.overrides ?? {};
60
- const { config: userConfig } = await loadUserConfig(cwd);
61
- const merged = mergeUserConfig(userConfig, overrides);
62
- const directory = merged.directory ?? ".ghfs";
63
- const configuredToken = merged.auth?.token?.trim() || "";
64
- const repo = merged.repo?.trim() || "";
65
- const issuesEnabled = merged.sync?.issues ?? true;
66
- const pullsEnabled = merged.sync?.pulls ?? true;
67
- const closedMode = merged.sync?.closed ?? false;
68
- const patchesMode = merged.sync?.patches ?? "open";
69
- return {
70
- cwd,
71
- repo,
72
- directory,
73
- auth: { token: configuredToken },
74
- sync: {
75
- issues: issuesEnabled,
76
- pulls: pullsEnabled,
77
- closed: closedMode,
78
- patches: patchesMode
79
- }
80
- };
81
- }
82
- function getStorageDirAbsolute(config) {
83
- return resolve(config.cwd, config.directory);
84
- }
85
- function getExecuteFile(config) {
86
- return join(config.directory, EXECUTE_FILE_NAME);
87
- }
88
- function findConfigFile(cwd) {
89
- for (const candidate of CONFIG_FILE_CANDIDATES) {
90
- const fullPath = resolve(cwd, candidate);
91
- if (existsSync(fullPath)) return fullPath;
92
- }
93
- }
94
- function mergeUserConfig(base, overrides) {
95
- return {
96
- ...base,
97
- ...overrides,
98
- auth: {
99
- ...base.auth,
100
- ...overrides.auth
101
- },
102
- sync: {
103
- ...base.sync,
104
- ...overrides.sync
105
- }
106
- };
107
- }
108
- //#endregion
109
- //#region src/utils/fs.ts
110
- async function pathExists(path) {
111
- try {
112
- await access(path);
113
- return true;
114
- } catch {
115
- return false;
116
- }
117
- }
118
- async function writeFileEnsured(path, content) {
119
- await mkdir(dirname(path), { recursive: true });
120
- await writeFile(path, content, "utf8");
121
- }
122
- async function removePath(path) {
123
- await rm(path, { force: true });
124
- }
125
- async function movePath(from, to) {
126
- await mkdir(dirname(to), { recursive: true });
127
- await rename(from, to);
128
- }
129
- async function removePatchIfExists(storageDirAbsolute, number) {
130
- const pullsDir = join(storageDirAbsolute, PULL_DIR_NAME);
131
- let entries;
132
- try {
133
- entries = await readdir(pullsDir, { withFileTypes: true });
134
- } catch {
135
- return 0;
136
- }
137
- const padded = String(number).padStart(5, "0");
138
- let removed = 0;
139
- for (const entry of entries) {
140
- if (!entry.isFile()) continue;
141
- const fileName = entry.name;
142
- const isLegacyPatch = fileName === `${number}.patch`;
143
- const isCurrentPatch = fileName.startsWith(`${padded}-`) && fileName.endsWith(".patch");
144
- if (!isLegacyPatch && !isCurrentPatch) continue;
145
- await removePath(join(pullsDir, fileName));
146
- removed += 1;
147
- }
148
- return removed;
149
- }
150
- //#endregion
151
- //#region src/execute/actions.ts
152
- const ACTIONS_SUPPORTED = [
153
- "close",
154
- "close-with-comment",
155
- "reopen",
156
- "set-title",
157
- "set-body",
158
- "add-comment",
159
- "add-labels",
160
- "remove-labels",
161
- "set-labels",
162
- "add-assignees",
163
- "remove-assignees",
164
- "set-assignees",
165
- "set-milestone",
166
- "clear-milestone",
167
- "lock",
168
- "unlock",
169
- "request-reviewers",
170
- "remove-reviewers",
171
- "mark-ready-for-review",
172
- "convert-to-draft"
173
- ];
174
- const ACTIONS_ALIAS_MAP = {
175
- "open": "reopen",
176
- "closes": "close",
177
- "close-comment": "close-with-comment",
178
- "comment-close": "close-with-comment",
179
- "close-and-comment": "close-with-comment",
180
- "comment-and-close": "close-with-comment",
181
- "label": "add-labels",
182
- "labels": "add-labels",
183
- "tag": "add-labels",
184
- "tags": "add-labels",
185
- "add-tag": "add-labels",
186
- "assign": "add-assignees",
187
- "assignee": "add-assignees",
188
- "assignees": "add-assignees",
189
- "body": "set-body",
190
- "title": "set-title",
191
- "retitle": "set-title",
192
- "ready": "mark-ready-for-review",
193
- "undraft": "mark-ready-for-review",
194
- "draft": "convert-to-draft",
195
- "comment": "add-comment"
196
- };
197
- const ACTIONS_COLOR_HEX = {
198
- "close": "#ef4444",
199
- "close-with-comment": "#fb7185",
200
- "reopen": "#22c55e",
201
- "set-title": "#3b82f6",
202
- "set-body": "#06b6d4",
203
- "add-comment": "#f97316",
204
- "add-labels": "#84cc16",
205
- "remove-labels": "#f43f5e",
206
- "set-labels": "#eab308",
207
- "add-assignees": "#10b981",
208
- "remove-assignees": "#fb7185",
209
- "set-assignees": "#0ea5e9",
210
- "set-milestone": "#6366f1",
211
- "clear-milestone": "#f59e0b",
212
- "lock": "#a855f7",
213
- "unlock": "#14b8a6",
214
- "request-reviewers": "#38bdf8",
215
- "remove-reviewers": "#e879f9",
216
- "mark-ready-for-review": "#34d399",
217
- "convert-to-draft": "#f472b6"
218
- };
219
- const ACTION_NAMES_SET = new Set(ACTIONS_SUPPORTED);
220
- const ACTION_ALIASES = Object.keys(ACTIONS_ALIAS_MAP);
221
- const ACTION_INPUTS = [...ACTIONS_SUPPORTED, ...ACTION_ALIASES];
222
- function resolveActionName(action) {
223
- const normalized = normalizeActionInput(action);
224
- if (!normalized) return void 0;
225
- if (ACTION_NAMES_SET.has(normalized)) return normalized;
226
- return ACTIONS_ALIAS_MAP[normalized];
227
- }
228
- function normalizeActionInput(action) {
229
- return action.trim().toLowerCase();
230
- }
231
- //#endregion
232
- //#region src/execute/schema.ts
233
- const executeSchema = {
234
- $id: "https://ghfs.dev/schema/execute.json",
235
- type: "array",
236
- items: {
237
- type: "object",
238
- additionalProperties: true,
239
- required: ["number", "action"],
240
- properties: {
241
- number: { type: "number" },
242
- action: {
243
- type: "string",
244
- enum: [...ACTION_INPUTS]
245
- },
246
- ifUnchangedSince: {
247
- type: "string",
248
- format: "date-time"
249
- },
250
- title: { type: "string" },
251
- body: { type: "string" },
252
- labels: {
253
- type: "array",
254
- items: { type: "string" }
255
- },
256
- assignees: {
257
- type: "array",
258
- items: { type: "string" }
259
- },
260
- milestone: { anyOf: [{ type: "string" }, { type: "number" }] },
261
- reviewers: {
262
- type: "array",
263
- items: { type: "string" }
264
- },
265
- reason: {
266
- type: "string",
267
- enum: [
268
- "resolved",
269
- "off-topic",
270
- "too heated",
271
- "too-heated",
272
- "spam"
273
- ]
274
- }
275
- }
276
- }
277
- };
278
- const EXECUTE_FILE_PLACEHOLDER = [
279
- `# yaml-language-server: $schema=./${EXECUTE_SCHEMA_RELATIVE_PATH}`,
280
- "# Add operations as YAML list items, then run: `ghfs execute`, examples:",
281
- "#",
282
- "# - action: close",
283
- "# number: 123",
284
- ""
285
- ].join("\n");
286
- const EXECUTE_MD_FILE_PLACEHOLDER = [
287
- "<!-- Add one action per line, then run: `ghfs execute`, examples: -->",
288
- "",
289
- "<!-- close #123 #124 -->",
290
- "<!-- label #123 bug, triage -->",
291
- "<!-- assign #123 antfu -->",
292
- "<!-- comment #123 \"Need more context\" -->",
293
- "<!-- close-comment #123 \"Closing as completed\" -->",
294
- "<!-- set-title #123 \"new title\" -->",
295
- "<!-- add-tag #123 foo, bar -->",
296
- ""
297
- ].join("\n");
298
- async function writeExecuteSchema(storageDirAbsolute) {
299
- const schemaPath = getExecuteSchemaPath(storageDirAbsolute);
300
- await mkdir(dirname(schemaPath), { recursive: true });
301
- await writeFile(schemaPath, `${JSON.stringify(executeSchema, null, 2)}\n`, "utf8");
302
- return schemaPath;
303
- }
304
- async function ensureExecuteArtifacts(executeFilePath) {
305
- const storageDirAbsolute = dirname(executeFilePath);
306
- const [schemaPath] = await Promise.all([
307
- ensureExecuteSchema(storageDirAbsolute),
308
- ensureExecuteFile(executeFilePath),
309
- ensureExecuteMdFile(storageDirAbsolute)
310
- ]);
311
- return {
312
- executeFilePath,
313
- schemaPath
314
- };
315
- }
316
- async function ensureExecuteSchema(storageDirAbsolute) {
317
- const schemaPath = getExecuteSchemaPath(storageDirAbsolute);
318
- if (await pathExists(schemaPath)) return schemaPath;
319
- return writeExecuteSchema(storageDirAbsolute);
320
- }
321
- async function ensureExecuteFile(executeFilePath) {
322
- if (await pathExists(executeFilePath)) return;
323
- await mkdir(dirname(executeFilePath), { recursive: true });
324
- await writeFile(executeFilePath, EXECUTE_FILE_PLACEHOLDER, "utf8");
325
- }
326
- async function ensureExecuteMdFile(storageDirAbsolute) {
327
- const executeMdPath = join(storageDirAbsolute, EXECUTE_MD_FILE_NAME);
328
- if (await pathExists(executeMdPath)) return;
329
- await mkdir(dirname(executeMdPath), { recursive: true });
330
- await writeFile(executeMdPath, EXECUTE_MD_FILE_PLACEHOLDER, "utf8");
331
- }
332
- function getExecuteSchemaPath(storageDirAbsolute) {
333
- return join(storageDirAbsolute, EXECUTE_SCHEMA_RELATIVE_PATH);
334
- }
335
- //#endregion
336
- //#region src/execute/validate.ts
337
- const executeOpSchema = v.looseObject({
338
- number: v.number(),
339
- action: v.string(),
340
- ifUnchangedSince: v.optional(v.string()),
341
- title: v.optional(v.string()),
342
- body: v.optional(v.string()),
343
- labels: v.optional(v.array(v.string())),
344
- assignees: v.optional(v.array(v.string())),
345
- milestone: v.optional(v.union([v.string(), v.number()])),
346
- reviewers: v.optional(v.array(v.string())),
347
- reason: v.optional(v.picklist([
348
- "resolved",
349
- "off-topic",
350
- "too heated",
351
- "too-heated",
352
- "spam"
353
- ]))
354
- });
355
- const executeFileSchema = v.array(executeOpSchema);
356
- async function readAndValidateExecuteFileWithSource(path) {
357
- const raw = await readFile(path, "utf8");
358
- let parsed;
359
- try {
360
- parsed = parse(raw || "[]") || [];
361
- } catch (error) {
362
- throw new Error(`Failed to parse execute YAML: ${error.message}`);
363
- }
364
- const parsedResult = v.safeParse(executeFileSchema, parsed);
365
- if (!parsedResult.success) {
366
- const message = parsedResult.issues.map((issue) => {
367
- const path = issue.path?.map((segment) => String(segment.key)).join(".");
368
- return `${path ? `${path}: ` : ""}${issue.message}`;
369
- }).join("; ");
370
- throw new Error(`Invalid execute file: ${message}`);
371
- }
372
- const { pending, sourceActions, actionErrors } = normalizeActionInputs(parsedResult.output);
373
- if (actionErrors.length) throw new Error(`Invalid execute file: ${actionErrors.join("; ")}`);
374
- const customErrors = validateExecuteRules(pending);
375
- if (customErrors.length) throw new Error(`Invalid execute file: ${customErrors.join("; ")}`);
376
- return {
377
- ops: pending,
378
- sourceActions
379
- };
380
- }
381
- async function writeExecuteFile(path, pending) {
382
- const content = stringify(pending);
383
- await mkdir(dirname(path), { recursive: true });
384
- await writeFile(path, content.endsWith("\n") ? content : `${content}\n`, "utf8");
385
- }
386
- function validateExecuteRules(pending) {
387
- const errors = [];
388
- for (const [index, op] of pending.entries()) {
389
- const key = `[${index}]`;
390
- errors.push(...validateOperationRules(key, op));
391
- }
392
- return errors;
393
- }
394
- function validateOperationRules(key, op) {
395
- const errors = [];
396
- if (!Number.isInteger(op.number) || op.number <= 0) errors.push(`${key}: number must be a positive integer`);
397
- switch (op.action) {
398
- case "set-title":
399
- if (!isNonEmptyString(op.title)) errors.push(`${key}: set-title requires title`);
400
- break;
401
- case "set-body":
402
- case "add-comment":
403
- case "close-with-comment":
404
- if (!isNonEmptyString(op.body)) errors.push(`${key}: ${op.action} requires body`);
405
- break;
406
- case "add-labels":
407
- case "remove-labels":
408
- case "set-labels":
409
- if (!isStringArray(op.labels)) errors.push(`${key}: ${op.action} requires labels[]`);
410
- break;
411
- case "add-assignees":
412
- case "remove-assignees":
413
- case "set-assignees":
414
- if (!isStringArray(op.assignees)) errors.push(`${key}: ${op.action} requires assignees[]`);
415
- break;
416
- case "set-milestone":
417
- if (!(typeof op.milestone === "string" || typeof op.milestone === "number")) errors.push(`${key}: set-milestone requires milestone`);
418
- break;
419
- case "request-reviewers":
420
- case "remove-reviewers":
421
- if (!isStringArray(op.reviewers)) errors.push(`${key}: ${op.action} requires reviewers[]`);
422
- break;
423
- default: break;
424
- }
425
- if (op.ifUnchangedSince && Number.isNaN(Date.parse(op.ifUnchangedSince))) errors.push(`${key}: ifUnchangedSince must be a valid datetime`);
426
- return errors;
427
- }
428
- function isNonEmptyString(value) {
429
- return typeof value === "string" && value.trim().length > 0;
430
- }
431
- function isStringArray(value) {
432
- return Array.isArray(value) && value.every((entry) => typeof entry === "string") && value.length > 0;
433
- }
434
- function normalizeActionInputs(pending) {
435
- const normalized = [];
436
- const sourceActions = [];
437
- const actionErrors = [];
438
- for (const [index, op] of pending.entries()) {
439
- const sourceAction = op.action;
440
- sourceActions.push(sourceAction);
441
- const action = resolveActionName(sourceAction);
442
- if (!action) {
443
- actionErrors.push(`[${index}]: unknown action: ${sourceAction}`);
444
- continue;
445
- }
446
- normalized.push({
447
- ...op,
448
- action
449
- });
450
- }
451
- return {
452
- pending: normalized,
453
- sourceActions,
454
- actionErrors
455
- };
456
- }
457
- //#endregion
458
- //#region src/execute/sources/execute-md.ts
459
- const MULTI_SIMPLE_ACTIONS = new Set([
460
- "close",
461
- "reopen",
462
- "clear-milestone",
463
- "unlock",
464
- "mark-ready-for-review",
465
- "convert-to-draft"
466
- ]);
467
- function parseExecuteMdLine(line) {
468
- const trimmed = line.trim();
469
- if (!trimmed || isCommentLine(trimmed)) return void 0;
470
- const tokens = tokenizeCommand(trimmed);
471
- if (!tokens) return {
472
- kind: "warning",
473
- message: "invalid quoted string syntax"
474
- };
475
- if (tokens.length === 0) return void 0;
476
- const [commandInput, ...args] = tokens;
477
- const command = resolveActionName(commandInput);
478
- if (!command) return {
479
- kind: "warning",
480
- message: `unrecognized action pattern: ${commandInput}`
481
- };
482
- if (command === "set-title") return parseSetTitle(args);
483
- if (command === "add-labels") return parseAddLabels(args, commandInput);
484
- if (command === "add-assignees") return parseAddAssignees(args, commandInput);
485
- if (command === "add-comment") return parseAddComment(args, commandInput);
486
- if (command === "close-with-comment") return parseCloseWithComment(args, commandInput);
487
- if (MULTI_SIMPLE_ACTIONS.has(command)) return parseMultiSimpleAction(command, args, commandInput);
488
- return {
489
- kind: "warning",
490
- message: `unrecognized action pattern: ${commandInput}`
491
- };
492
- }
493
- async function readExecuteMdFile(path) {
494
- if (!await pathExists(path)) return parseExecuteMd("");
495
- return parseExecuteMd(await readFile(path, "utf8"));
496
- }
497
- function parseExecuteMd(raw) {
498
- const lines = raw.split(/\r?\n/);
499
- const ops = [];
500
- const parsedLines = [];
501
- const warnings = [];
502
- let inHtmlCommentBlock = false;
503
- for (const [lineIndex, rawLine] of lines.entries()) {
504
- const trimmed = rawLine.trim();
505
- if (inHtmlCommentBlock) {
506
- parsedLines.push({
507
- kind: "raw",
508
- raw: rawLine
509
- });
510
- if (trimmed.includes("-->")) inHtmlCommentBlock = false;
511
- continue;
512
- }
513
- if (trimmed.startsWith("<!--")) {
514
- parsedLines.push({
515
- kind: "raw",
516
- raw: rawLine
517
- });
518
- if (!trimmed.includes("-->")) inHtmlCommentBlock = true;
519
- continue;
520
- }
521
- const parsed = parseExecuteMdLine(rawLine);
522
- if (!parsed) {
523
- parsedLines.push({
524
- kind: "raw",
525
- raw: rawLine
526
- });
527
- continue;
528
- }
529
- if (parsed.kind === "warning") {
530
- warnings.push(`execute-md line ${lineIndex + 1}: ${parsed.message}`);
531
- parsedLines.push({
532
- kind: "raw",
533
- raw: rawLine
534
- });
535
- continue;
536
- }
537
- if (parsed.kind === "single") {
538
- const opIndex = ops.length;
539
- ops.push(parsed.op);
540
- parsedLines.push({
541
- kind: "single",
542
- raw: rawLine,
543
- opIndex
544
- });
545
- continue;
546
- }
547
- const opIndexes = [];
548
- for (const number of parsed.numbers) {
549
- opIndexes.push(ops.length);
550
- ops.push({
551
- action: parsed.action,
552
- number
553
- });
554
- }
555
- parsedLines.push({
556
- kind: "multi",
557
- action: parsed.action,
558
- command: parsed.command,
559
- opIndexes
560
- });
561
- }
562
- return {
563
- ops,
564
- warnings,
565
- lines: parsedLines
566
- };
567
- }
568
- function stringifyExecuteMd(parsed, remainingOpIndexes) {
569
- const lines = [];
570
- for (const line of parsed.lines) {
571
- if (line.kind === "raw") {
572
- lines.push(line.raw);
573
- continue;
574
- }
575
- if (line.kind === "single") {
576
- if (remainingOpIndexes.has(line.opIndex)) lines.push(line.raw);
577
- continue;
578
- }
579
- const numbers = line.opIndexes.filter((index) => remainingOpIndexes.has(index)).map((index) => parsed.ops[index]?.number).filter((value) => typeof value === "number");
580
- if (numbers.length > 0) lines.push(`${line.command} ${numbers.map((number) => `#${number}`).join(" ")}`);
581
- }
582
- return `${lines.join("\n")}\n`;
583
- }
584
- function parseSetTitle(args) {
585
- if (args.length !== 2) return {
586
- kind: "warning",
587
- message: "set-title expects: set-title #<number> \"<title>\""
588
- };
589
- const number = parseIssueRef(args[0]);
590
- if (!number) return {
591
- kind: "warning",
592
- message: "set-title expects a single issue reference (#123)"
593
- };
594
- return {
595
- kind: "single",
596
- op: {
597
- action: "set-title",
598
- number,
599
- title: args[1]
600
- }
601
- };
602
- }
603
- function parseAddLabels(args, command) {
604
- if (args.length < 2) return {
605
- kind: "warning",
606
- message: `${command} expects: ${command} #<number> <label1, label2>`
607
- };
608
- const number = parseIssueRef(args[0]);
609
- if (!number) return {
610
- kind: "warning",
611
- message: `${command} expects a single issue reference (#123)`
612
- };
613
- const labels = args.slice(1).flatMap((value) => value.split(",")).map((value) => value.trim()).filter(Boolean);
614
- if (labels.length === 0) return {
615
- kind: "warning",
616
- message: `${command} requires at least one label`
617
- };
618
- return {
619
- kind: "single",
620
- op: {
621
- action: "add-labels",
622
- number,
623
- labels
624
- }
625
- };
626
- }
627
- function parseAddAssignees(args, command) {
628
- if (args.length < 2) return {
629
- kind: "warning",
630
- message: `${command} expects: ${command} #<number> <assignee1, assignee2>`
631
- };
632
- const number = parseIssueRef(args[0]);
633
- if (!number) return {
634
- kind: "warning",
635
- message: `${command} expects a single issue reference (#123)`
636
- };
637
- const assignees = args.slice(1).flatMap((value) => value.split(",")).map((value) => value.trim()).filter(Boolean);
638
- if (assignees.length === 0) return {
639
- kind: "warning",
640
- message: `${command} requires at least one assignee`
641
- };
642
- return {
643
- kind: "single",
644
- op: {
645
- action: "add-assignees",
646
- number,
647
- assignees
648
- }
649
- };
650
- }
651
- function parseAddComment(args, command) {
652
- if (args.length < 2) return {
653
- kind: "warning",
654
- message: `${command} expects: ${command} #<number> "<comment>"`
655
- };
656
- const number = parseIssueRef(args[0]);
657
- if (!number) return {
658
- kind: "warning",
659
- message: `${command} expects a single issue reference (#123)`
660
- };
661
- const body = args.slice(1).join(" ").trim();
662
- if (!body) return {
663
- kind: "warning",
664
- message: `${command} requires a non-empty comment`
665
- };
666
- return {
667
- kind: "single",
668
- op: {
669
- action: "add-comment",
670
- number,
671
- body
672
- }
673
- };
674
- }
675
- function parseCloseWithComment(args, command) {
676
- if (args.length < 2) return {
677
- kind: "warning",
678
- message: `${command} expects: ${command} #<number> "<comment>"`
679
- };
680
- const number = parseIssueRef(args[0]);
681
- if (!number) return {
682
- kind: "warning",
683
- message: `${command} expects a single issue reference (#123)`
684
- };
685
- const body = args.slice(1).join(" ").trim();
686
- if (!body) return {
687
- kind: "warning",
688
- message: `${command} requires a non-empty comment`
689
- };
690
- return {
691
- kind: "single",
692
- op: {
693
- action: "close-with-comment",
694
- number,
695
- body
696
- }
697
- };
698
- }
699
- function parseMultiSimpleAction(action, args, command) {
700
- const numbers = args.map(parseIssueRef);
701
- if (numbers.length === 0 || numbers.some((number) => !number)) return {
702
- kind: "warning",
703
- message: `${command} expects one or more issue references (#123 #456)`
704
- };
705
- return {
706
- kind: "multi",
707
- action,
708
- command,
709
- numbers
710
- };
711
- }
712
- function parseIssueRef(value) {
713
- const match = value.match(/^#(\d+)$/);
714
- if (!match) return void 0;
715
- const number = Number.parseInt(match[1], 10);
716
- if (!Number.isInteger(number) || number <= 0) return void 0;
717
- return number;
718
- }
719
- function tokenizeCommand(value) {
720
- const tokens = [];
721
- let index = 0;
722
- while (index < value.length) {
723
- while (index < value.length && /\s/.test(value[index])) index += 1;
724
- if (index >= value.length) break;
725
- if (value[index] === "\"") {
726
- index += 1;
727
- let token = "";
728
- let closed = false;
729
- while (index < value.length) {
730
- const char = value[index];
731
- if (char === "\\") {
732
- const next = value[index + 1];
733
- if (next === "\"" || next === "\\") {
734
- token += next;
735
- index += 2;
736
- continue;
737
- }
738
- }
739
- if (char === "\"") {
740
- closed = true;
741
- index += 1;
742
- break;
743
- }
744
- token += char;
745
- index += 1;
746
- }
747
- if (!closed) return void 0;
748
- tokens.push(token);
749
- continue;
750
- }
751
- const start = index;
752
- while (index < value.length && !/\s/.test(value[index])) index += 1;
753
- tokens.push(value.slice(start, index));
754
- }
755
- return tokens;
756
- }
757
- function isCommentLine(trimmed) {
758
- return trimmed.startsWith("#") || trimmed.startsWith("//") || trimmed.startsWith("<!--");
759
- }
760
- //#endregion
761
- //#region package.json
762
- var version = "0.1.0";
763
- //#endregion
764
- //#region src/meta.ts
765
- const GHFS_NAME = "ghfs";
766
- const GHFS_VERSION = version;
767
- //#endregion
768
- //#region src/sync/state.ts
769
- function getSyncStatePath(storageDirAbsolute) {
770
- return join(storageDirAbsolute, SYNC_STATE_FILE_NAME);
771
- }
772
- async function loadSyncState(storageDirAbsolute) {
773
- const path = getSyncStatePath(storageDirAbsolute);
774
- try {
775
- const raw = await readFile(path, "utf8");
776
- const parsed = JSON.parse(raw);
777
- if (parsed.version !== 2) return createEmptySyncState();
778
- return {
779
- version: 2,
780
- items: normalizeItems(parsed.items),
781
- executions: normalizeExecutions(parsed.executions),
782
- ghfsVersion: typeof parsed.ghfsVersion === "string" ? parsed.ghfsVersion : void 0,
783
- repo: parsed.repo,
784
- lastSyncedAt: parsed.lastSyncedAt,
785
- lastSince: parsed.lastSince,
786
- lastRepoUpdatedAt: parsed.lastRepoUpdatedAt,
787
- lastSyncRun: parsed.lastSyncRun
788
- };
789
- } catch {
790
- return createEmptySyncState();
791
- }
792
- }
793
- function normalizeItems(items) {
794
- if (!items) return {};
795
- if (typeof items !== "object" || Array.isArray(items)) return {};
796
- const normalizedItems = {};
797
- for (const [key, item] of Object.entries(items)) {
798
- const normalizedItem = normalizeItem(item);
799
- if (!normalizedItem) continue;
800
- normalizedItems[key] = normalizedItem;
801
- }
802
- return normalizedItems;
803
- }
804
- function normalizeExecutions(executions) {
805
- if (!Array.isArray(executions)) return [];
806
- return executions.map((execution) => {
807
- if (!execution || typeof execution !== "object") return execution;
808
- const typedExecution = execution;
809
- if (typedExecution.mode === "dry-run") return {
810
- ...typedExecution,
811
- mode: "report"
812
- };
813
- return typedExecution;
814
- });
815
- }
816
- async function saveSyncState(storageDirAbsolute, state) {
817
- await mkdir(storageDirAbsolute, { recursive: true });
818
- const normalizedState = {
819
- ...state,
820
- ghfsVersion: state.ghfsVersion ?? GHFS_VERSION
821
- };
822
- await writeFile(getSyncStatePath(storageDirAbsolute), `${JSON.stringify(normalizedState, null, 2)}\n`, "utf8");
823
- }
824
- function createEmptySyncState() {
825
- return {
826
- version: 2,
827
- items: {},
828
- executions: []
829
- };
830
- }
831
- function appendExecution(state, result, limit = 20) {
832
- const nextExecutions = [result, ...state.executions].slice(0, limit);
833
- return {
834
- ...state,
835
- executions: nextExecutions
836
- };
837
- }
838
- function normalizeItem(item) {
839
- if (!item || typeof item !== "object") return void 0;
840
- if (!item.lastUpdatedAt || !item.lastSyncedAt || !item.filePath) return void 0;
841
- if (!item.data || !item.data.item) return void 0;
842
- const comments = Array.isArray(item.data.comments) ? item.data.comments : [];
843
- const rawItem = item.data.item;
844
- return {
845
- ...item,
846
- data: {
847
- ...item.data,
848
- item: {
849
- ...rawItem,
850
- labels: Array.isArray(rawItem.labels) ? rawItem.labels.filter((v) => typeof v === "string") : [],
851
- assignees: Array.isArray(rawItem.assignees) ? rawItem.assignees.filter((v) => typeof v === "string") : [],
852
- reactions: normalizeReactions(rawItem.reactions)
853
- },
854
- comments: comments.filter((comment) => comment && typeof comment === "object").map((comment) => ({
855
- ...comment,
856
- reactions: normalizeReactions(comment.reactions)
857
- }))
858
- }
859
- };
860
- }
861
- //#endregion
862
- //#region src/execute/sources/per-item.ts
863
- async function loadPerItemSource(storageDir) {
864
- const syncState = await loadSyncState(storageDir);
865
- const ops = [];
866
- const warnings = [];
867
- const repo = syncState.repo;
868
- for (const tracked of Object.values(syncState.items)) {
869
- const markdownPath = join(storageDir, tracked.filePath);
870
- if (!await pathExists(markdownPath)) {
871
- warnings.push(`per-item: missing markdown for ${formatIssueNumber(tracked.number, { repo })} (${tracked.filePath})`);
872
- continue;
873
- }
874
- const frontmatter = parseFrontmatter(await readFile(markdownPath, "utf8"));
875
- if (!frontmatter) {
876
- warnings.push(`per-item: invalid or missing frontmatter for ${formatIssueNumber(tracked.number, { repo })}`);
877
- continue;
878
- }
879
- const trackedItem = tracked.data.item;
880
- const itemOps = computePerItemOps({
881
- number: tracked.number,
882
- current: {
883
- title: trackedItem.title,
884
- state: trackedItem.state,
885
- labels: trackedItem.labels,
886
- assignees: trackedItem.assignees,
887
- milestone: trackedItem.milestone
888
- },
889
- desired: frontmatter,
890
- updatedAt: trackedItem.updatedAt
891
- });
892
- ops.push(...itemOps);
893
- }
894
- return {
895
- ops,
896
- warnings
897
- };
898
- }
899
- function computePerItemOps(input) {
900
- const ops = [];
901
- const ifUnchangedSince = input.updatedAt;
902
- if (input.current.title !== input.desired.title) ops.push({
903
- action: "set-title",
904
- number: input.number,
905
- title: input.desired.title,
906
- ifUnchangedSince
907
- });
908
- if (input.current.state !== input.desired.state) ops.push({
909
- action: input.desired.state === "closed" ? "close" : "reopen",
910
- number: input.number,
911
- ifUnchangedSince
912
- });
913
- if (!sameStringSet(input.current.labels, input.desired.labels)) {
914
- const additions = diffStrings(input.desired.labels, input.current.labels);
915
- const deletions = diffStrings(input.current.labels, input.desired.labels);
916
- if (additions.length > 0 && deletions.length > 0) ops.push({
917
- action: "set-labels",
918
- number: input.number,
919
- labels: input.desired.labels,
920
- ifUnchangedSince
921
- });
922
- else if (additions.length > 0) ops.push({
923
- action: "add-labels",
924
- number: input.number,
925
- labels: additions,
926
- ifUnchangedSince
927
- });
928
- else if (deletions.length > 0) ops.push({
929
- action: "remove-labels",
930
- number: input.number,
931
- labels: deletions,
932
- ifUnchangedSince
933
- });
934
- }
935
- if (!sameStringSet(input.current.assignees, input.desired.assignees)) {
936
- if (input.desired.assignees.length > 0) ops.push({
937
- action: "set-assignees",
938
- number: input.number,
939
- assignees: input.desired.assignees,
940
- ifUnchangedSince
941
- });
942
- else if (input.current.assignees.length > 0) ops.push({
943
- action: "remove-assignees",
944
- number: input.number,
945
- assignees: input.current.assignees,
946
- ifUnchangedSince
947
- });
948
- }
949
- if (normalizeMilestone(input.current.milestone) !== normalizeMilestone(input.desired.milestone)) if (input.desired.milestone) ops.push({
950
- action: "set-milestone",
951
- number: input.number,
952
- milestone: input.desired.milestone,
953
- ifUnchangedSince
954
- });
955
- else ops.push({
956
- action: "clear-milestone",
957
- number: input.number,
958
- ifUnchangedSince
959
- });
960
- return ops;
961
- }
962
- function parseFrontmatter(raw) {
963
- const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
964
- if (!match) return void 0;
965
- let parsed;
966
- try {
967
- parsed = parse(match[1]);
968
- } catch {
969
- return;
970
- }
971
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
972
- const data = parsed;
973
- const title = typeof data.title === "string" && data.title.trim().length > 0 ? data.title.trim() : void 0;
974
- const state = data.state === "open" || data.state === "closed" ? data.state : void 0;
975
- if (!title || !state) return void 0;
976
- return {
977
- title,
978
- state,
979
- labels: normalizeStringArray(data.labels ?? data.tags),
980
- assignees: normalizeStringArray(data.assignees),
981
- milestone: normalizeMilestone(data.milestone)
982
- };
983
- }
984
- function normalizeStringArray(value) {
985
- if (!Array.isArray(value)) return [];
986
- const unique = /* @__PURE__ */ new Set();
987
- for (const entry of value) {
988
- if (typeof entry !== "string") continue;
989
- const normalized = entry.trim();
990
- if (!normalized) continue;
991
- unique.add(normalized);
992
- }
993
- return [...unique];
994
- }
995
- function sameStringSet(left, right) {
996
- if (left.length !== right.length) return false;
997
- const sortedLeft = [...left].sort();
998
- const sortedRight = [...right].sort();
999
- return sortedLeft.every((value, index) => value === sortedRight[index]);
1000
- }
1001
- function normalizeMilestone(value) {
1002
- if (typeof value !== "string") return null;
1003
- const normalized = value.trim();
1004
- return normalized.length > 0 ? normalized : null;
1005
- }
1006
- function diffStrings(source, target) {
1007
- const targetSet = new Set(target);
1008
- return source.filter((value) => !targetSet.has(value));
1009
- }
1010
- //#endregion
1011
- //#region src/execute/sources/index.ts
1012
- async function loadExecuteSources(executeFilePath) {
1013
- const storageDir = dirname(executeFilePath);
1014
- const executeMdPath = join(storageDir, EXECUTE_MD_FILE_NAME);
1015
- const yml = await readAndValidateExecuteFileWithSource(executeFilePath);
1016
- const ymlOps = yml.ops;
1017
- const executeMd = await readExecuteMdFile(executeMdPath);
1018
- const perItem = await loadPerItemSource(storageDir);
1019
- const mergedOps = [
1020
- ...ymlOps,
1021
- ...executeMd.ops,
1022
- ...perItem.ops
1023
- ];
1024
- const customErrors = validateExecuteRules(mergedOps);
1025
- if (customErrors.length) throw new Error(`Invalid execute file: ${customErrors.join("; ")}`);
1026
- return {
1027
- ops: mergedOps,
1028
- warnings: [...executeMd.warnings, ...perItem.warnings],
1029
- async writeRemaining(remainingIndexes) {
1030
- await writeExecuteFile(executeFilePath, ymlOps.map((op, index) => ({
1031
- op,
1032
- index
1033
- })).filter((item) => remainingIndexes.has(item.index)).map(({ op, index }) => ({
1034
- ...op,
1035
- action: yml.sourceActions[index] ?? op.action
1036
- })));
1037
- if (!await pathExists(executeMdPath)) return;
1038
- const mdOffset = ymlOps.length;
1039
- const mdRemaining = /* @__PURE__ */ new Set();
1040
- for (const index of remainingIndexes) if (index >= mdOffset) mdRemaining.add(index - mdOffset);
1041
- await writeFile(executeMdPath, stringifyExecuteMd(executeMd, mdRemaining), "utf-8");
1042
- }
1043
- };
1044
- }
1045
- //#endregion
1046
- //#region src/execute/index.ts
1047
- var ExecuteCancelledError = class extends Error {
1048
- constructor() {
1049
- super("Execution cancelled");
1050
- this.name = "ExecuteCancelledError";
1051
- }
1052
- };
1053
- function isExecuteCancelledError(error) {
1054
- return error instanceof ExecuteCancelledError;
1055
- }
1056
- async function executePendingChanges(options) {
1057
- try {
1058
- await ensureExecuteArtifacts(options.executeFilePath);
1059
- const sources = await loadExecuteSources(options.executeFilePath);
1060
- const allOps = sources.ops;
1061
- for (const warning of sources.warnings) options.onWarning?.(warning);
1062
- if (allOps.length === 0) return {
1063
- runId: createRunId(),
1064
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1065
- mode: "report",
1066
- repo: options.repo,
1067
- planned: 0,
1068
- applied: 0,
1069
- failed: 0,
1070
- details: []
1071
- };
1072
- const interactive = process.stdin.isTTY && !options.nonInteractive;
1073
- if (interactive && !options.prompts) throw new Error("Interactive execute prompts are unavailable. Use --non-interactive or provide prompts.");
1074
- const selected = Array.isArray(options.selectedIndexes) ? selectOperationsByIndexes(allOps, options.selectedIndexes) : interactive ? await selectOperations(allOps, options.prompts) : allOps.map((op, index) => ({
1075
- op,
1076
- index
1077
- }));
1078
- const runId = createRunId();
1079
- const createdAt = (/* @__PURE__ */ new Date()).toISOString();
1080
- const mode = options.apply ? "apply" : "report";
1081
- options.reporter?.onStart?.({
1082
- repo: options.repo,
1083
- mode,
1084
- planned: selected.length
1085
- });
1086
- if (selected.length === 0) {
1087
- const result = {
1088
- runId,
1089
- createdAt,
1090
- mode,
1091
- repo: options.repo,
1092
- planned: 0,
1093
- applied: 0,
1094
- failed: 0,
1095
- details: []
1096
- };
1097
- options.reporter?.onComplete?.({ result });
1098
- return result;
1099
- }
1100
- options.onPlan?.(selected.map((item) => item.op));
1101
- if (!options.apply) {
1102
- const result = {
1103
- runId,
1104
- createdAt,
1105
- mode: "report",
1106
- repo: options.repo,
1107
- planned: selected.length,
1108
- applied: 0,
1109
- failed: 0,
1110
- details: selected.map(({ op, index }) => ({
1111
- op: index + 1,
1112
- action: op.action,
1113
- number: op.number,
1114
- status: "planned",
1115
- message: describeExecutionAction(op.action, op.number)
1116
- }))
1117
- };
1118
- options.reporter?.onComplete?.({ result });
1119
- return result;
1120
- }
1121
- if (interactive) {
1122
- if (!await confirmApply(selected.length, options.prompts)) throw new ExecuteCancelledError();
1123
- }
1124
- const provider = options.provider ?? createRepositoryProvider({
1125
- token: options.token,
1126
- repo: options.repo
1127
- });
1128
- const details = [];
1129
- const appliedIndexes = /* @__PURE__ */ new Set();
1130
- let applied = 0;
1131
- let failed = 0;
1132
- for (const { op, index } of selected) try {
1133
- const target = await applyOperation(provider, op);
1134
- appliedIndexes.add(index);
1135
- await persistRemainingOps(sources.writeRemaining, allOps, appliedIndexes);
1136
- const detail = {
1137
- op: index + 1,
1138
- action: op.action,
1139
- number: op.number,
1140
- target,
1141
- status: "applied",
1142
- message: describeExecutionAction(op.action, op.number)
1143
- };
1144
- details.push(detail);
1145
- applied += 1;
1146
- options.reporter?.onProgress?.({
1147
- repo: options.repo,
1148
- mode: "apply",
1149
- planned: selected.length,
1150
- completed: details.length,
1151
- applied,
1152
- failed,
1153
- detail
1154
- });
1155
- } catch (error) {
1156
- failed += 1;
1157
- const detail = {
1158
- op: index + 1,
1159
- action: op.action,
1160
- number: op.number,
1161
- status: "failed",
1162
- message: error.message
1163
- };
1164
- details.push(detail);
1165
- options.reporter?.onProgress?.({
1166
- repo: options.repo,
1167
- mode: "apply",
1168
- planned: selected.length,
1169
- completed: details.length,
1170
- applied,
1171
- failed,
1172
- detail
1173
- });
1174
- if (!options.continueOnError) break;
1175
- }
1176
- const result = {
1177
- runId,
1178
- createdAt,
1179
- mode: "apply",
1180
- repo: options.repo,
1181
- planned: selected.length,
1182
- applied,
1183
- failed,
1184
- details
1185
- };
1186
- options.reporter?.onComplete?.({ result });
1187
- return result;
1188
- } catch (error) {
1189
- options.reporter?.onError?.({ error });
1190
- throw error;
1191
- }
1192
- }
1193
- async function persistRemainingOps(writeRemaining, allOps, appliedIndexes) {
1194
- const remainingIndexes = /* @__PURE__ */ new Set();
1195
- for (const [index] of allOps.entries()) if (!appliedIndexes.has(index)) remainingIndexes.add(index);
1196
- await writeRemaining(remainingIndexes);
1197
- }
1198
- async function applyOperation(provider, op) {
1199
- const item = await provider.fetchItemSnapshot(op.number);
1200
- const isPull = item.kind === "pull";
1201
- if (op.ifUnchangedSince) {
1202
- const remoteUpdatedAt = item.updatedAt;
1203
- if (remoteUpdatedAt && new Date(remoteUpdatedAt).getTime() > new Date(op.ifUnchangedSince).getTime()) throw new Error(`Operation conflict: remote updated_at=${remoteUpdatedAt}`);
1204
- }
1205
- switch (op.action) {
1206
- case "close":
1207
- await provider.actionClose(op.number);
1208
- break;
1209
- case "reopen":
1210
- await provider.actionReopen(op.number);
1211
- break;
1212
- case "set-title":
1213
- await provider.actionSetTitle(op.number, op.title);
1214
- break;
1215
- case "set-body":
1216
- await provider.actionSetBody(op.number, op.body);
1217
- break;
1218
- case "add-comment":
1219
- await provider.actionAddComment(op.number, op.body);
1220
- break;
1221
- case "close-with-comment":
1222
- await provider.actionAddComment(op.number, op.body);
1223
- await provider.actionClose(op.number);
1224
- break;
1225
- case "add-labels":
1226
- await provider.actionAddLabels(op.number, op.labels);
1227
- break;
1228
- case "remove-labels":
1229
- await provider.actionRemoveLabels(op.number, op.labels);
1230
- break;
1231
- case "set-labels":
1232
- await provider.actionSetLabels(op.number, op.labels);
1233
- break;
1234
- case "add-assignees":
1235
- await provider.actionAddAssignees(op.number, op.assignees);
1236
- break;
1237
- case "remove-assignees":
1238
- await provider.actionRemoveAssignees(op.number, op.assignees);
1239
- break;
1240
- case "set-assignees":
1241
- await provider.actionSetAssignees(op.number, op.assignees);
1242
- break;
1243
- case "set-milestone":
1244
- await provider.actionSetMilestone(op.number, op.milestone);
1245
- break;
1246
- case "clear-milestone":
1247
- await provider.actionClearMilestone(op.number);
1248
- break;
1249
- case "lock":
1250
- await provider.actionLock(op.number, op.reason);
1251
- break;
1252
- case "unlock":
1253
- await provider.actionUnlock(op.number);
1254
- break;
1255
- case "request-reviewers":
1256
- ensurePullAction(op.action, op.number, isPull);
1257
- await provider.actionRequestReviewers(op.number, op.reviewers);
1258
- break;
1259
- case "remove-reviewers":
1260
- ensurePullAction(op.action, op.number, isPull);
1261
- await provider.actionRemoveReviewers(op.number, op.reviewers);
1262
- break;
1263
- case "mark-ready-for-review":
1264
- ensurePullAction(op.action, op.number, isPull);
1265
- await provider.actionMarkReadyForReview(op.number);
1266
- break;
1267
- case "convert-to-draft":
1268
- ensurePullAction(op.action, op.number, isPull);
1269
- await provider.actionConvertToDraft(op.number);
1270
- break;
1271
- default: throw new Error(`Unsupported action: ${String(op.action)}`);
1272
- }
1273
- return item.kind;
1274
- }
1275
- function createRunId() {
1276
- return `run_${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:.TZ]/g, "")}_${Math.random().toString(36).slice(2, 7)}`;
1277
- }
1278
- async function selectOperations(ops, prompts) {
1279
- const selectedIndexes = await prompts.selectOperations(ops);
1280
- if (!selectedIndexes) throw new ExecuteCancelledError();
1281
- const selectedIndexesSet = new Set(selectedIndexes);
1282
- return ops.map((op, index) => ({
1283
- op,
1284
- index
1285
- })).filter((item) => selectedIndexesSet.has(item.index));
1286
- }
1287
- async function confirmApply(count, prompts) {
1288
- const result = await prompts.confirmApply(count);
1289
- if (result == null) return false;
1290
- return result;
1291
- }
1292
- function selectOperationsByIndexes(ops, selectedIndexes) {
1293
- const selectedSet = /* @__PURE__ */ new Set();
1294
- for (const index of selectedIndexes) if (Number.isInteger(index) && index >= 0 && index < ops.length) selectedSet.add(index);
1295
- return ops.map((op, index) => ({
1296
- op,
1297
- index
1298
- })).filter((item) => selectedSet.has(item.index));
1299
- }
1300
- function ensurePullAction(action, number, isPull) {
1301
- if (!isPull) throw new Error(`Action ${action} requires #${number} to be a pull request`);
1302
- }
1303
- function describeExecutionAction(action, number) {
1304
- return `${action} #${number}`;
1305
- }
1306
- //#endregion
1307
- //#region src/sync/execution-log.ts
1308
- async function appendExecutionResult(storageDirAbsolute, result) {
1309
- await saveSyncState(storageDirAbsolute, appendExecution(await loadSyncState(storageDirAbsolute), result));
1310
- }
1311
- //#endregion
1312
- //#region src/utils/sync.ts
1313
- function resolveSince(options, syncState) {
1314
- if (options.full) return void 0;
1315
- if (options.since) return options.since;
1316
- return syncState.lastSyncedAt;
1317
- }
1318
- function normalizeIssueNumbers(numbers) {
1319
- if (!numbers) return void 0;
1320
- return [...new Set(numbers.filter((number) => Number.isInteger(number) && number > 0))];
1321
- }
1322
- //#endregion
1323
- //#region src/sync/markdown.ts
1324
- const FIELDS_ALWAYS_KEEP = new Set(["labels", "assignees"]);
1325
- const FIELDS_ALWAYS_EXCLUDE = new Set(["repo", "kind"]);
1326
- const REACTION_FIELDS = [
1327
- {
1328
- key: "plusOne",
1329
- emoji: "👍"
1330
- },
1331
- {
1332
- key: "minusOne",
1333
- emoji: "👎"
1334
- },
1335
- {
1336
- key: "laugh",
1337
- emoji: "😄"
1338
- },
1339
- {
1340
- key: "hooray",
1341
- emoji: "🎉"
1342
- },
1343
- {
1344
- key: "confused",
1345
- emoji: "😕"
1346
- },
1347
- {
1348
- key: "heart",
1349
- emoji: "❤️"
1350
- },
1351
- {
1352
- key: "rocket",
1353
- emoji: "🚀"
1354
- },
1355
- {
1356
- key: "eyes",
1357
- emoji: "👀"
1358
- }
1359
- ];
1360
- function renderIssueMarkdown(input) {
1361
- const url = input.url || `https://github.com/${input.repo}/${input.kind === "pull" ? "pull" : "issues"}/${input.number}`;
1362
- const frontmatter = {
1363
- repo: input.repo,
1364
- number: input.number,
1365
- kind: input.kind,
1366
- url,
1367
- state: input.state,
1368
- title: input.title,
1369
- author: input.author,
1370
- labels: input.labels,
1371
- assignees: input.assignees,
1372
- milestone: input.milestone,
1373
- created_at: input.createdAt,
1374
- updated_at: input.updatedAt,
1375
- closed_at: input.closedAt,
1376
- last_synced_at: input.lastSyncedAt,
1377
- reactions: formatReactionsFrontmatter(input.reactions),
1378
- is_draft: input.pr?.isDraft,
1379
- merged: input.pr?.merged,
1380
- merged_at: input.pr?.mergedAt,
1381
- base_ref: input.pr?.baseRef,
1382
- head_ref: input.pr?.headRef,
1383
- reviewers_requested: input.pr?.requestedReviewers
1384
- };
1385
- const compactFrontmatter = Object.fromEntries(Object.entries(frontmatter).filter(([key, value]) => {
1386
- if (FIELDS_ALWAYS_EXCLUDE.has(key)) return false;
1387
- if (FIELDS_ALWAYS_KEEP.has(key)) return true;
1388
- if (value === void 0 || value === null || value === false) return false;
1389
- if (Array.isArray(value)) return value.length > 0;
1390
- return true;
1391
- }));
1392
- const sections = [
1393
- `# ${input.title}`,
1394
- "",
1395
- "## Description",
1396
- "",
1397
- input.body?.trim() || "_No description._"
1398
- ];
1399
- const bodyReactionsLine = formatReactionsLine(input.reactions);
1400
- if (bodyReactionsLine) {
1401
- sections.push("");
1402
- sections.push(bodyReactionsLine);
1403
- }
1404
- sections.push("");
1405
- sections.push("---");
1406
- sections.push("");
1407
- sections.push("## Comments");
1408
- sections.push("");
1409
- if (input.comments.length === 0) sections.push("_No comments._");
1410
- else for (const [index, comment] of input.comments.entries()) {
1411
- if (index > 0) {
1412
- sections.push("---");
1413
- sections.push("");
1414
- }
1415
- sections.push(`### @${comment.author} on ${comment.createdAt}`);
1416
- sections.push(`<!-- comment-id:${comment.id} updated:${comment.updatedAt} -->`);
1417
- sections.push("");
1418
- sections.push(comment.body?.trim() || "_No content._");
1419
- const reactionsLine = formatReactionsLine(comment.reactions);
1420
- if (reactionsLine) {
1421
- sections.push("");
1422
- sections.push(reactionsLine);
1423
- }
1424
- sections.push("");
1425
- }
1426
- return [
1427
- "---",
1428
- stringify(compactFrontmatter).trimEnd(),
1429
- "---",
1430
- "",
1431
- ...sections,
1432
- ""
1433
- ].join("\n");
1434
- }
1435
- function formatReactionsLine(reactions) {
1436
- const entries = getReactionEntries(reactions);
1437
- if (entries.length === 0) return void 0;
1438
- return `> ${entries.map((entry) => `\`${entry.emoji} ${entry.count}\``).join(" | ")}`;
1439
- }
1440
- function formatReactionsFrontmatter(reactions) {
1441
- const entries = getReactionEntries(reactions);
1442
- if (entries.length === 0) return void 0;
1443
- return Object.fromEntries(entries.map((entry) => [entry.emoji, entry.count]));
1444
- }
1445
- function getReactionEntries(reactions) {
1446
- const normalized = normalizeReactions(reactions);
1447
- return REACTION_FIELDS.map(({ key, emoji }) => {
1448
- const count = normalized[key];
1449
- if (!count) return void 0;
1450
- return {
1451
- emoji,
1452
- count
1453
- };
1454
- }).filter((entry) => Boolean(entry));
1455
- }
1456
- //#endregion
1457
- //#region src/utils/string.ts
1458
- function slugifyTitle(title, maxLength = 48) {
1459
- const normalized = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
1460
- if (!normalized) return "item";
1461
- return normalized.slice(0, maxLength).replace(/-+$/g, "") || "item";
1462
- }
1463
- //#endregion
1464
- //#region src/sync/paths.ts
1465
- const FILE_NUMBER_PAD_LENGTH = 5;
1466
- const MAX_SLUG_LENGTH = 48;
1467
- function getIssueMarkdownPath(storageDirAbsolute, number, state, title) {
1468
- const fileName = getItemFileName(number, title);
1469
- if (state === "closed") return join(storageDirAbsolute, ISSUE_DIR_NAME, CLOSED_DIR_NAME, fileName);
1470
- return join(storageDirAbsolute, ISSUE_DIR_NAME, fileName);
1471
- }
1472
- function getPullMarkdownPath(storageDirAbsolute, number, state, title) {
1473
- const fileName = getItemFileName(number, title);
1474
- if (state === "closed") return join(storageDirAbsolute, PULL_DIR_NAME, CLOSED_DIR_NAME, fileName);
1475
- return join(storageDirAbsolute, PULL_DIR_NAME, fileName);
1476
- }
1477
- function getItemMarkdownPath(storageDirAbsolute, kind, number, state, title) {
1478
- if (kind === "pull") return getPullMarkdownPath(storageDirAbsolute, number, state, title);
1479
- return getIssueMarkdownPath(storageDirAbsolute, number, state, title);
1480
- }
1481
- function getItemFileName(number, title) {
1482
- return `${String(number).padStart(FILE_NUMBER_PAD_LENGTH, "0")}-${slugifyTitle(title, MAX_SLUG_LENGTH)}.md`;
1483
- }
1484
- function getPrPatchPath(storageDirAbsolute, number, title) {
1485
- return join(storageDirAbsolute, PULL_DIR_NAME, getItemFileName(number, title).replace(/\.md$/, ".patch"));
1486
- }
1487
- //#endregion
1488
- //#region src/sync/sync-repository-utils.ts
1489
- function createCounters(scanned = 0, selected = 0) {
1490
- return {
1491
- scanned,
1492
- selected,
1493
- processed: 0,
1494
- skipped: 0,
1495
- written: 0,
1496
- moved: 0,
1497
- patchesWritten: 0,
1498
- patchesDeleted: 0
1499
- };
1500
- }
1501
- function addItemStats(counters, stats) {
1502
- counters.skipped += stats.skipped;
1503
- counters.written += stats.written;
1504
- counters.moved += stats.moved;
1505
- counters.patchesWritten += stats.patchesWritten;
1506
- counters.patchesDeleted += stats.patchesDeleted;
1507
- }
1508
- function shouldSyncKind(sync, kind) {
1509
- return kind === "issue" ? sync.issues : sync.pulls;
1510
- }
1511
- function shouldSyncIssue(sync, issue) {
1512
- return shouldSyncKind(sync, issue.kind);
1513
- }
1514
- function resolvePatchPlan(patchesMode, kind, state) {
1515
- if (kind !== "pull") return {
1516
- shouldWritePatch: false,
1517
- shouldDeletePatch: false
1518
- };
1519
- const shouldWritePatch = patchesMode === "all" || patchesMode === "open" && state === "open";
1520
- return {
1521
- shouldWritePatch,
1522
- shouldDeletePatch: !shouldWritePatch
1523
- };
1524
- }
1525
- function relativeToStorage(storageDirAbsolute, absolutePath) {
1526
- if (absolutePath.startsWith(storageDirAbsolute)) return absolutePath.slice(storageDirAbsolute.length + 1);
1527
- return basename(absolutePath);
1528
- }
1529
- //#endregion
1530
- //#region src/sync/sync-repository-storage.ts
1531
- async function resolveIssuePaths(storageDirAbsolute, kind, number, title, state, trackedFilePath) {
1532
- const closedPath = getItemMarkdownPath(storageDirAbsolute, kind, number, "closed", title);
1533
- const openPath = getItemMarkdownPath(storageDirAbsolute, kind, number, "open", title);
1534
- const hasClosedFile = await pathExists(closedPath);
1535
- const hasOpenFile = await pathExists(openPath);
1536
- const trackedPath = resolveTrackedPath(storageDirAbsolute, trackedFilePath);
1537
- const hasTrackedFile = trackedPath ? await pathExists(trackedPath) : false;
1538
- const targetPath = getItemMarkdownPath(storageDirAbsolute, kind, number, state, title);
1539
- const hasTargetFile = state === "open" ? hasOpenFile : hasClosedFile;
1540
- const matchedPaths = await findMatchedMarkdownPaths(storageDirAbsolute, kind, number, [
1541
- openPath,
1542
- closedPath,
1543
- trackedPath
1544
- ]);
1545
- return {
1546
- openPath,
1547
- closedPath,
1548
- targetPath,
1549
- patchPath: getPrPatchPath(storageDirAbsolute, number, title),
1550
- trackedPath,
1551
- hasOpenFile,
1552
- hasClosedFile,
1553
- hasTrackedFile,
1554
- matchedPaths,
1555
- hasLocalFile: hasOpenFile || hasClosedFile || hasTrackedFile || matchedPaths.length > 0,
1556
- hasTargetFile
1557
- };
1558
- }
1559
- async function moveMarkdownByState(paths, state) {
1560
- const sourcePath = resolveMoveSourcePath(paths, state);
1561
- if (!sourcePath) return 0;
1562
- if (sourcePath === paths.targetPath) return 0;
1563
- if (await pathExists(paths.targetPath)) return 0;
1564
- await movePath(sourcePath, paths.targetPath);
1565
- return 1;
1566
- }
1567
- function resolveMoveSourcePath(paths, state) {
1568
- if (paths.hasTrackedFile && paths.trackedPath && paths.trackedPath !== paths.targetPath) return paths.trackedPath;
1569
- if (state === "open" && paths.hasClosedFile && paths.closedPath !== paths.targetPath) return paths.closedPath;
1570
- if (state === "closed" && paths.hasOpenFile && paths.openPath !== paths.targetPath) return paths.openPath;
1571
- if (paths.hasOpenFile && paths.openPath !== paths.targetPath) return paths.openPath;
1572
- if (paths.hasClosedFile && paths.closedPath !== paths.targetPath) return paths.closedPath;
1573
- return paths.matchedPaths.find((path) => path !== paths.targetPath);
1574
- }
1575
- function getExistingMarkdownPaths(paths) {
1576
- const markdownPaths = /* @__PURE__ */ new Set();
1577
- if (paths.hasOpenFile) markdownPaths.add(paths.openPath);
1578
- if (paths.hasClosedFile) markdownPaths.add(paths.closedPath);
1579
- if (paths.hasTrackedFile && paths.trackedPath) markdownPaths.add(paths.trackedPath);
1580
- for (const matchedPath of paths.matchedPaths) markdownPaths.add(matchedPath);
1581
- return [...markdownPaths];
1582
- }
1583
- function resolveTrackedPath(storageDirAbsolute, trackedFilePath) {
1584
- if (!trackedFilePath) return void 0;
1585
- if (isAbsolute(trackedFilePath)) return trackedFilePath;
1586
- return join(storageDirAbsolute, trackedFilePath);
1587
- }
1588
- function resolveTrackedPathOrJoin(storageDirAbsolute, trackedFilePath) {
1589
- return resolveTrackedPath(storageDirAbsolute, trackedFilePath) ?? join(storageDirAbsolute, trackedFilePath);
1590
- }
1591
- async function findMatchedMarkdownPaths(storageDirAbsolute, kind, number, knownPaths) {
1592
- const matchedPaths = /* @__PURE__ */ new Set();
1593
- const knownPathSet = new Set(knownPaths.filter(Boolean));
1594
- const padded = String(number).padStart(5, "0");
1595
- const kindDir = kind === "issue" ? ISSUE_DIR_NAME : PULL_DIR_NAME;
1596
- for (const stateDir of ["", CLOSED_DIR_NAME]) {
1597
- const dir = stateDir ? join(storageDirAbsolute, kindDir, stateDir) : join(storageDirAbsolute, kindDir);
1598
- let files;
1599
- try {
1600
- files = await readdir(dir);
1601
- } catch {
1602
- continue;
1603
- }
1604
- for (const fileName of files) {
1605
- if (!fileName.startsWith(`${padded}-`) || !fileName.endsWith(".md")) continue;
1606
- const fullPath = join(dir, fileName);
1607
- if (!knownPathSet.has(fullPath)) matchedPaths.add(fullPath);
1608
- }
1609
- }
1610
- return [...matchedPaths];
1611
- }
1612
- function updateTrackedItem(context, number, kind, state, issueUpdatedAt, markdownPath, patchPath, data) {
1613
- context.syncState.items[String(number)] = {
1614
- number,
1615
- kind,
1616
- state,
1617
- lastUpdatedAt: issueUpdatedAt,
1618
- lastSyncedAt: context.syncedAt,
1619
- filePath: relativeToStorage(context.storageDirAbsolute, markdownPath),
1620
- patchPath: patchPath ? relativeToStorage(context.storageDirAbsolute, patchPath) : void 0,
1621
- data
1622
- };
1623
- }
1624
- async function pruneTrackedClosedItems(storageDirAbsolute, syncState, sync) {
1625
- if (sync.issues) await rm(join(storageDirAbsolute, ISSUE_DIR_NAME, CLOSED_DIR_NAME), {
1626
- recursive: true,
1627
- force: true
1628
- });
1629
- if (sync.pulls) await rm(join(storageDirAbsolute, PULL_DIR_NAME, CLOSED_DIR_NAME), {
1630
- recursive: true,
1631
- force: true
1632
- });
1633
- let patchesDeleted = 0;
1634
- for (const item of Object.values(syncState.items)) {
1635
- if (item.state !== "closed") continue;
1636
- if (!shouldSyncKind(sync, item.kind)) continue;
1637
- await removePath(resolveTrackedPathOrJoin(storageDirAbsolute, item.filePath));
1638
- if (item.kind === "pull") patchesDeleted += await removePatchIfExists(storageDirAbsolute, item.number);
1639
- delete syncState.items[String(item.number)];
1640
- }
1641
- return patchesDeleted;
1642
- }
1643
- async function pruneMissingOpenTrackedItems(storageDirAbsolute, syncState, openNumbers, sync) {
1644
- let patchesDeleted = 0;
1645
- for (const item of Object.values(syncState.items)) {
1646
- if (item.state !== "open") continue;
1647
- if (!shouldSyncKind(sync, item.kind)) continue;
1648
- if (openNumbers.has(item.number)) continue;
1649
- await removePath(resolveTrackedPathOrJoin(storageDirAbsolute, item.filePath));
1650
- if (item.kind === "pull") patchesDeleted += await removePatchIfExists(storageDirAbsolute, item.number);
1651
- delete syncState.items[String(item.number)];
1652
- }
1653
- return patchesDeleted;
1654
- }
1655
- //#endregion
1656
- //#region src/sync/sync-repository-item.ts
1657
- async function prepareIssueCandidateSync(context, issue) {
1658
- const number = issue.number;
1659
- const kind = issue.kind;
1660
- const state = issue.state;
1661
- const tracked = context.syncState.items[String(number)];
1662
- const paths = await resolveIssuePaths(context.storageDirAbsolute, kind, number, issue.title, state, tracked?.filePath);
1663
- const patchPlan = resolvePatchPlan(context.config.sync.patches, kind, state);
1664
- if (state === "closed" && context.config.sync.closed === false) {
1665
- delete context.syncState.items[String(number)];
1666
- return {
1667
- number,
1668
- kind,
1669
- state,
1670
- action: "remove",
1671
- paths,
1672
- patchPlan
1673
- };
1674
- }
1675
- if (state === "closed" && context.config.sync.closed === true && !paths.hasLocalFile) {
1676
- delete context.syncState.items[String(number)];
1677
- return {
1678
- number,
1679
- kind,
1680
- state,
1681
- action: "remove",
1682
- paths,
1683
- patchPlan
1684
- };
1685
- }
1686
- const hasCanonicalData = Boolean(tracked?.data && (kind !== "pull" || tracked.data.pull));
1687
- const shouldRefetch = !tracked || tracked.lastUpdatedAt !== issue.updatedAt || !hasCanonicalData;
1688
- const data = shouldRefetch ? await fetchCanonicalData(context, issue) : tracked.data;
1689
- updateTrackedItem(context, number, kind, state, issue.updatedAt, paths.targetPath, patchPlan.shouldWritePatch ? paths.patchPath : void 0, data);
1690
- return {
1691
- number,
1692
- kind,
1693
- state,
1694
- action: resolveSyncAction(shouldRefetch, paths, state),
1695
- paths,
1696
- patchPlan
1697
- };
1698
- }
1699
- async function materializePreparedIssue(context, candidate) {
1700
- const { number, kind, state, action, patchPlan, paths } = candidate;
1701
- if (action === "remove") {
1702
- for (const markdownPath of getExistingMarkdownPaths(paths)) await removePath(markdownPath);
1703
- let patchesDeleted = 0;
1704
- if (kind === "pull") patchesDeleted += await removePatchIfExists(context.storageDirAbsolute, number);
1705
- return {
1706
- kind,
1707
- action,
1708
- skipped: 0,
1709
- written: 0,
1710
- moved: 0,
1711
- patchesWritten: 0,
1712
- patchesDeleted
1713
- };
1714
- }
1715
- if (action === "skip") {
1716
- let patchesDeleted = 0;
1717
- if (patchPlan.shouldDeletePatch) patchesDeleted += await removePatchIfExists(context.storageDirAbsolute, number);
1718
- return {
1719
- kind,
1720
- action,
1721
- skipped: 1,
1722
- written: 0,
1723
- moved: 0,
1724
- patchesWritten: 0,
1725
- patchesDeleted
1726
- };
1727
- }
1728
- const tracked = context.syncState.items[String(number)];
1729
- if (!tracked) throw new Error(`Missing tracked canonical data for ${formatIssueNumber(number, {
1730
- repo: context.repoSlug,
1731
- kind
1732
- })}`);
1733
- const markdown = buildTrackedMarkdown(context, tracked);
1734
- const moved = await moveMarkdownByState(paths, state);
1735
- await writeFileEnsured(paths.targetPath, markdown);
1736
- const patchStats = await syncPatchByPlan(context, number, paths.patchPath, patchPlan);
1737
- return {
1738
- kind,
1739
- action,
1740
- skipped: 0,
1741
- written: 1,
1742
- moved,
1743
- patchesWritten: patchStats.patchesWritten,
1744
- patchesDeleted: patchStats.patchesDeleted
1745
- };
1746
- }
1747
- async function rematerializeTrackedMarkdown(context) {
1748
- let processed = 0;
1749
- let written = 0;
1750
- let moved = 0;
1751
- for (const tracked of Object.values(context.syncState.items)) {
1752
- const paths = await resolveIssuePaths(context.storageDirAbsolute, tracked.kind, tracked.number, tracked.data.item.title, tracked.state, tracked.filePath);
1753
- moved += await moveMarkdownByState(paths, tracked.state);
1754
- await writeFileEnsured(paths.targetPath, buildTrackedMarkdown(context, tracked));
1755
- tracked.filePath = relativeToStorage(context.storageDirAbsolute, paths.targetPath);
1756
- tracked.lastSyncedAt = context.syncedAt;
1757
- processed += 1;
1758
- written += 1;
1759
- }
1760
- return {
1761
- processed,
1762
- written,
1763
- moved
1764
- };
1765
- }
1766
- async function reconcileMarkdownFilesByScan(context) {
1767
- let written = 0;
1768
- let moved = 0;
1769
- const expectedPaths = /* @__PURE__ */ new Set();
1770
- for (const tracked of Object.values(context.syncState.items)) {
1771
- const paths = await resolveIssuePaths(context.storageDirAbsolute, tracked.kind, tracked.number, tracked.data.item.title, tracked.state, tracked.filePath);
1772
- expectedPaths.add(paths.targetPath);
1773
- const movedByState = !paths.hasTargetFile ? await moveMarkdownByState(paths, tracked.state) : 0;
1774
- let changed = movedByState > 0;
1775
- if (!await pathExists(paths.targetPath)) {
1776
- await writeFileEnsured(paths.targetPath, buildTrackedMarkdown(context, tracked));
1777
- written += 1;
1778
- changed = true;
1779
- }
1780
- tracked.filePath = relativeToStorage(context.storageDirAbsolute, paths.targetPath);
1781
- if (changed) tracked.lastSyncedAt = context.syncedAt;
1782
- moved += movedByState;
1783
- }
1784
- moved += await moveExtraMarkdownFilesToClosed(context.storageDirAbsolute, expectedPaths);
1785
- return {
1786
- written,
1787
- moved
1788
- };
1789
- }
1790
- function resolveSyncAction(shouldRefetch, paths, state) {
1791
- if (shouldRefetch) return "refetch";
1792
- if (paths.hasTargetFile) return "skip";
1793
- if (resolveMoveSourcePath(paths, state)) return "move";
1794
- return "create";
1795
- }
1796
- async function fetchCanonicalData(context, issue) {
1797
- return {
1798
- item: issue,
1799
- comments: await context.provider.fetchComments(issue.number),
1800
- pull: issue.kind === "pull" ? await context.provider.fetchPullMetadata(issue.number) : void 0
1801
- };
1802
- }
1803
- async function syncPatchByPlan(context, number, patchPath, patchPlan) {
1804
- let patchesWritten = 0;
1805
- let patchesDeleted = 0;
1806
- if (patchPlan.shouldWritePatch) {
1807
- const patch = await context.provider.fetchPullPatch(number);
1808
- await removePatchIfExists(context.storageDirAbsolute, number);
1809
- await writeFileEnsured(patchPath, patch);
1810
- patchesWritten += 1;
1811
- }
1812
- if (patchPlan.shouldDeletePatch) patchesDeleted += await removePatchIfExists(context.storageDirAbsolute, number);
1813
- return {
1814
- patchesWritten,
1815
- patchesDeleted
1816
- };
1817
- }
1818
- function buildTrackedMarkdown(context, tracked) {
1819
- return renderIssueMarkdown({
1820
- repo: context.repoSlug,
1821
- number: tracked.data.item.number,
1822
- kind: tracked.data.item.kind,
1823
- url: tracked.data.item.url,
1824
- state: tracked.data.item.state,
1825
- title: tracked.data.item.title,
1826
- body: tracked.data.item.body ?? "",
1827
- author: tracked.data.item.author ?? "unknown",
1828
- labels: tracked.data.item.labels,
1829
- assignees: tracked.data.item.assignees,
1830
- milestone: tracked.data.item.milestone,
1831
- createdAt: tracked.data.item.createdAt,
1832
- updatedAt: tracked.data.item.updatedAt,
1833
- closedAt: tracked.data.item.closedAt,
1834
- lastSyncedAt: context.syncedAt,
1835
- reactions: normalizeReactions(tracked.data.item.reactions),
1836
- comments: tracked.data.comments.map((comment) => ({
1837
- id: comment.id,
1838
- author: comment.author ?? "unknown",
1839
- body: comment.body ?? "",
1840
- createdAt: comment.createdAt,
1841
- updatedAt: comment.updatedAt,
1842
- reactions: normalizeReactions(comment.reactions)
1843
- })),
1844
- pr: tracked.data.pull
1845
- });
1846
- }
1847
- async function moveExtraMarkdownFilesToClosed(storageDirAbsolute, expectedPaths) {
1848
- let moved = 0;
1849
- moved += await moveOpenMarkdownFilesToClosed(join(storageDirAbsolute, ISSUE_DIR_NAME), expectedPaths);
1850
- moved += await moveOpenMarkdownFilesToClosed(join(storageDirAbsolute, PULL_DIR_NAME), expectedPaths);
1851
- return moved;
1852
- }
1853
- async function moveOpenMarkdownFilesToClosed(kindDirAbsolute, expectedPaths) {
1854
- let moved = 0;
1855
- const openFiles = await listOpenMarkdownFiles(kindDirAbsolute);
1856
- const closedDirAbsolute = join(kindDirAbsolute, CLOSED_DIR_NAME);
1857
- for (const markdownPath of openFiles) {
1858
- if (expectedPaths.has(markdownPath)) continue;
1859
- await movePath(markdownPath, await resolveUniqueClosedTarget(closedDirAbsolute, basename(markdownPath)));
1860
- moved += 1;
1861
- }
1862
- return moved;
1863
- }
1864
- async function listOpenMarkdownFiles(kindDirAbsolute) {
1865
- try {
1866
- return (await readdir(kindDirAbsolute, {
1867
- withFileTypes: true,
1868
- encoding: "utf8"
1869
- })).filter((entry) => entry.isFile() && entry.name.endsWith(".md")).map((entry) => join(kindDirAbsolute, entry.name));
1870
- } catch {
1871
- return [];
1872
- }
1873
- }
1874
- async function resolveUniqueClosedTarget(closedDirAbsolute, fileName) {
1875
- const baseName = fileName.replace(/\.md$/i, "");
1876
- let candidate = join(closedDirAbsolute, fileName);
1877
- let index = 1;
1878
- while (await pathExists(candidate)) {
1879
- candidate = join(closedDirAbsolute, `${baseName}-extra-${index}.md`);
1880
- index += 1;
1881
- }
1882
- return candidate;
1883
- }
1884
- //#endregion
1885
- //#region src/sync/sync-repository-provider.ts
1886
- async function fetchIssueCandidatesByPagination(context, since) {
1887
- const issues = [];
1888
- let scanned = 0;
1889
- const allOpenNumbers = context.config.sync.closed === false && !since ? /* @__PURE__ */ new Set() : void 0;
1890
- const state = context.config.sync.closed === false ? "open" : "all";
1891
- for await (const page of context.provider.paginateItems({
1892
- state,
1893
- since
1894
- })) for (const issue of page) {
1895
- if (!shouldSyncIssue(context.config.sync, issue)) continue;
1896
- scanned += 1;
1897
- issues.push(issue);
1898
- if (state === "open" && allOpenNumbers) allOpenNumbers.add(issue.number);
1899
- }
1900
- return {
1901
- issues,
1902
- scanned,
1903
- allOpenNumbers
1904
- };
1905
- }
1906
- async function fetchIssueCandidatesByNumbers(context, numbers) {
1907
- const issues = (await context.provider.fetchItemsByNumbers(numbers)).filter((issue) => shouldSyncIssue(context.config.sync, issue));
1908
- return {
1909
- issues,
1910
- scanned: issues.length
1911
- };
1912
- }
1913
- //#endregion
1914
- //#region src/utils/markdown.ts
1915
- function getTimestamp(value) {
1916
- const timestamp = Date.parse(value);
1917
- if (Number.isFinite(timestamp)) return timestamp;
1918
- return Number.NEGATIVE_INFINITY;
1919
- }
1920
- function renderRowsTable(rows) {
1921
- const lines = ["| Number | Title | Labels | Updated | File |", "| --- | --- | --- | --- | --- |"];
1922
- if (rows.length === 0) {
1923
- lines.push("| - | - | - | - | - |");
1924
- return lines;
1925
- }
1926
- for (const row of rows) {
1927
- const labels = row.labels.length ? row.labels.map((label) => `\`${escapeInlineCode(label)}\``).join(", ") : "-";
1928
- lines.push(`| #${row.number} | ${escapeTableCell(row.title)} | ${labels} | ${escapeTableCell(row.updatedAt)} | [${row.filePath}](${row.filePath}) |`);
1929
- }
1930
- return lines;
1931
- }
1932
- function escapeTableCell(value) {
1933
- return value.replace(/\r?\n/g, " ").replace(/\|/g, "\\|").trim() || "-";
1934
- }
1935
- function escapeInlineCode(value) {
1936
- return value.replace(/`/g, "\\`");
1937
- }
1938
- //#endregion
1939
- //#region src/sync/sync-repository-snapshot.ts
1940
- async function writeRepoSnapshot(context) {
1941
- const repoSnapshot = await buildRepoSnapshot(context);
1942
- await mkdir(context.storageDirAbsolute, { recursive: true });
1943
- await writeFile(join(context.storageDirAbsolute, REPO_SNAPSHOT_FILE_NAME), `${JSON.stringify(repoSnapshot, null, 2)}\n`, "utf8");
1944
- }
1945
- async function writeRepositoryIndexes(context) {
1946
- const [issuesMarkdown, pullsMarkdown] = await Promise.all([renderIndexMarkdown(context, "issue"), renderIndexMarkdown(context, "pull")]);
1947
- await mkdir(context.storageDirAbsolute, { recursive: true });
1948
- await Promise.all([writeFile(join(context.storageDirAbsolute, ISSUES_INDEX_FILE_NAME), issuesMarkdown, "utf8"), writeFile(join(context.storageDirAbsolute, PULLS_INDEX_FILE_NAME), pullsMarkdown, "utf8")]);
1949
- }
1950
- async function renderIndexMarkdown(context, kind) {
1951
- const rows = Object.values(context.syncState.items).filter((item) => item.kind === kind).map((item) => readIndexRow(item));
1952
- const openRows = sortRows(rows.filter((row) => row.state === "open"));
1953
- const closedRows = sortRows(rows.filter((row) => row.state === "closed"));
1954
- return [
1955
- `# ${kind === "issue" ? "Issues" : "Pull Requests"}`,
1956
- "",
1957
- `- repo: ${context.repoSlug}`,
1958
- `- synced_at: ${context.syncedAt}`,
1959
- `- total: ${rows.length}`,
1960
- `- open: ${openRows.length}`,
1961
- `- closed: ${closedRows.length}`,
1962
- "",
1963
- `## Open (${openRows.length})`,
1964
- "",
1965
- ...renderRowsTable(openRows),
1966
- "",
1967
- `## Closed (${closedRows.length})`,
1968
- "",
1969
- ...renderRowsTable(closedRows),
1970
- ""
1971
- ].join("\n");
1972
- }
1973
- function readIndexRow(item) {
1974
- return {
1975
- number: item.number,
1976
- state: item.state,
1977
- title: item.data.item.title,
1978
- labels: item.data.item.labels,
1979
- updatedAt: item.data.item.updatedAt,
1980
- filePath: item.filePath
1981
- };
1982
- }
1983
- function sortRows(rows) {
1984
- return [...rows].sort((left, right) => {
1985
- const updatedDiff = getTimestamp(right.updatedAt) - getTimestamp(left.updatedAt);
1986
- if (updatedDiff !== 0) return updatedDiff;
1987
- return right.number - left.number;
1988
- });
1989
- }
1990
- async function buildRepoSnapshot(context) {
1991
- const [repoResult, labelsResult, milestonesResult] = await Promise.all([
1992
- context.provider.fetchRepository(),
1993
- context.provider.fetchRepositoryLabels(),
1994
- context.provider.fetchRepositoryMilestones()
1995
- ]);
1996
- const repository = repoResult;
1997
- const labels = labelsResult.map((label) => ({
1998
- name: label.name,
1999
- color: label.color,
2000
- description: label.description ?? null,
2001
- default: Boolean(label.default)
2002
- })).sort((left, right) => left.name.localeCompare(right.name));
2003
- const milestones = milestonesResult.map((milestone) => ({
2004
- number: milestone.number,
2005
- title: milestone.title,
2006
- state: milestone.state,
2007
- description: milestone.description ?? null,
2008
- due_on: milestone.due_on,
2009
- open_issues: milestone.open_issues,
2010
- closed_issues: milestone.closed_issues,
2011
- created_at: milestone.created_at,
2012
- updated_at: milestone.updated_at,
2013
- closed_at: milestone.closed_at
2014
- })).sort((left, right) => left.number - right.number);
2015
- return {
2016
- repo: context.repoSlug,
2017
- synced_at: context.syncedAt,
2018
- repository: {
2019
- owner: repository.owner.login,
2020
- name: repository.name,
2021
- full_name: repository.full_name,
2022
- description: repository.description ?? null,
2023
- private: repository.private,
2024
- archived: repository.archived,
2025
- default_branch: repository.default_branch,
2026
- html_url: repository.html_url,
2027
- fork: repository.fork,
2028
- open_issues_count: repository.open_issues_count,
2029
- has_issues: repository.has_issues,
2030
- has_projects: repository.has_projects,
2031
- has_wiki: repository.has_wiki,
2032
- created_at: repository.created_at,
2033
- updated_at: repository.updated_at,
2034
- pushed_at: repository.pushed_at
2035
- },
2036
- labels,
2037
- milestones
2038
- };
2039
- }
2040
- //#endregion
2041
- //#region src/sync/sync-repository.ts
2042
- async function syncRepository(options) {
2043
- const reporter = options.reporter;
2044
- const startedAt = /* @__PURE__ */ new Date();
2045
- const startedAtIso = startedAt.toISOString();
2046
- const runId = createSyncRunId();
2047
- const provider = options.provider ?? createRepositoryProvider({
2048
- token: options.token,
2049
- repo: options.repo
2050
- });
2051
- const storageDirAbsolute = resolve(options.config.cwd, options.config.directory);
2052
- const targetNumbers = normalizeIssueNumbers(options.numbers);
2053
- const counters = createCounters();
2054
- const stageDurations = createStageDurations();
2055
- let errorReported = false;
2056
- reporter?.onStart?.({
2057
- repo: options.repo,
2058
- startedAt: startedAtIso,
2059
- numbersCount: targetNumbers?.length,
2060
- snapshot: cloneSnapshot(counters)
2061
- });
2062
- let context;
2063
- let since;
2064
- let repoUpdatedAt;
2065
- let candidates = {
2066
- issues: [],
2067
- scanned: 0
2068
- };
2069
- const preparedCandidates = [];
2070
- let updatedIssues = 0;
2071
- let updatedPulls = 0;
2072
- let ghfsVersionMismatch = false;
2073
- let previousGhfsVersion;
2074
- const runStage = async (stage, message, fn) => {
2075
- reporter?.onStageStart?.({
2076
- stage,
2077
- message,
2078
- snapshot: cloneSnapshot(counters)
2079
- });
2080
- const stageStartedAt = Date.now();
2081
- try {
2082
- const result = await fn();
2083
- const durationMs = Date.now() - stageStartedAt;
2084
- stageDurations[stage] = durationMs;
2085
- reporter?.onStageEnd?.({
2086
- stage,
2087
- message,
2088
- durationMs,
2089
- snapshot: cloneSnapshot(counters)
2090
- });
2091
- return result;
2092
- } catch (error) {
2093
- errorReported = true;
2094
- stageDurations[stage] = Date.now() - stageStartedAt;
2095
- reporter?.onError?.({
2096
- stage,
2097
- error,
2098
- snapshot: cloneSnapshot(counters)
2099
- });
2100
- throw error;
2101
- }
2102
- };
2103
- try {
2104
- let shouldEarlyReturn = false;
2105
- await runStage("metadata", "Fetch repository metadata", async () => {
2106
- const syncState = await loadSyncState(storageDirAbsolute);
2107
- since = targetNumbers ? void 0 : resolveSince(options, syncState);
2108
- const syncedAt = (/* @__PURE__ */ new Date()).toISOString();
2109
- context = {
2110
- provider,
2111
- repoSlug: options.repo,
2112
- storageDirAbsolute,
2113
- config: options.config,
2114
- syncState,
2115
- syncedAt,
2116
- totalIssues: 0,
2117
- totalPulls: 0
2118
- };
2119
- previousGhfsVersion = syncState.ghfsVersion;
2120
- ghfsVersionMismatch = syncState.ghfsVersion !== GHFS_VERSION;
2121
- if (targetNumbers) return;
2122
- repoUpdatedAt = (await provider.fetchRepository()).updated_at;
2123
- if (!options.full && syncState.lastRepoUpdatedAt && syncState.lastRepoUpdatedAt === repoUpdatedAt) shouldEarlyReturn = true;
2124
- reporter?.onStageUpdate?.({
2125
- stage: "metadata",
2126
- snapshot: cloneSnapshot(counters),
2127
- message: `since=${since ?? "(full)"} repoUpdatedAt=${repoUpdatedAt}`
2128
- });
2129
- });
2130
- assertContext(context);
2131
- const syncContext = context;
2132
- if (!shouldEarlyReturn) {
2133
- await runStage("pagination", "Pagination", async () => {
2134
- const paginatedSince = options.full ? void 0 : since;
2135
- candidates = targetNumbers ? await fetchIssueCandidatesByNumbers(syncContext, targetNumbers) : await fetchIssueCandidatesByPagination(syncContext, paginatedSince);
2136
- counters.scanned = candidates.scanned;
2137
- counters.selected = candidates.issues.length;
2138
- reporter?.onStageUpdate?.({
2139
- stage: "pagination",
2140
- snapshot: cloneSnapshot(counters),
2141
- message: `scanned=${counters.scanned} selected=${counters.selected}`
2142
- });
2143
- });
2144
- await runStage("fetch", "Fetch updated issues/PRs", async () => {
2145
- for (const issue of candidates.issues) {
2146
- const prepared = await prepareIssueCandidateSync(syncContext, issue);
2147
- preparedCandidates.push(prepared);
2148
- counters.processed += 1;
2149
- if (prepared.action === "refetch" || prepared.action === "create") if (prepared.kind === "issue") updatedIssues += 1;
2150
- else updatedPulls += 1;
2151
- reporter?.onStageUpdate?.({
2152
- stage: "fetch",
2153
- snapshot: cloneSnapshot(counters),
2154
- message: `${formatIssueNumber(issue.number, {
2155
- repo: options.repo,
2156
- kind: issue.kind
2157
- })} ${prepared.kind} ${prepared.action}`
2158
- });
2159
- }
2160
- });
2161
- syncContext.syncState.repo = options.repo;
2162
- if (!targetNumbers) {
2163
- syncContext.syncState.lastSyncedAt = syncContext.syncedAt;
2164
- syncContext.syncState.lastSince = since;
2165
- syncContext.syncState.lastRepoUpdatedAt = repoUpdatedAt;
2166
- }
2167
- await saveSyncState(syncContext.storageDirAbsolute, syncContext.syncState);
2168
- await runStage("materialize", "Materialize local files", async () => {
2169
- for (const prepared of preparedCandidates) addItemStats(counters, await materializePreparedIssue(syncContext, prepared));
2170
- });
2171
- await runStage("prune", "Prune stale local artifacts", async () => {
2172
- if (options.config.sync.closed === false) counters.patchesDeleted += await pruneTrackedClosedItems(syncContext.storageDirAbsolute, syncContext.syncState, options.config.sync);
2173
- if (!targetNumbers && options.config.sync.closed === false && candidates.allOpenNumbers) counters.patchesDeleted += await pruneMissingOpenTrackedItems(syncContext.storageDirAbsolute, syncContext.syncState, candidates.allOpenNumbers, options.config.sync);
2174
- reporter?.onStageUpdate?.({
2175
- stage: "prune",
2176
- snapshot: cloneSnapshot(counters),
2177
- message: `patchesDeleted=${counters.patchesDeleted}`
2178
- });
2179
- });
2180
- }
2181
- await runStage("save", "Save sync state", async () => {
2182
- if (ghfsVersionMismatch) {
2183
- const rematerialized = await rematerializeTrackedMarkdown(syncContext);
2184
- reporter?.onStageUpdate?.({
2185
- stage: "save",
2186
- snapshot: cloneSnapshot(counters),
2187
- message: `regenerated=${rematerialized.written} version=${previousGhfsVersion ?? "(none)"}->${GHFS_VERSION}`
2188
- });
2189
- }
2190
- const scanStats = await reconcileMarkdownFilesByScan(syncContext);
2191
- counters.written += scanStats.written;
2192
- counters.moved += scanStats.moved;
2193
- reporter?.onStageUpdate?.({
2194
- stage: "save",
2195
- snapshot: cloneSnapshot(counters),
2196
- message: `scan-fixed written=${scanStats.written} moved=${scanStats.moved}`
2197
- });
2198
- if (!shouldEarlyReturn) await writeRepoSnapshot(syncContext);
2199
- if (!shouldEarlyReturn || ghfsVersionMismatch) await writeRepositoryIndexes(syncContext);
2200
- syncContext.syncState.ghfsVersion = GHFS_VERSION;
2201
- await saveSyncState(syncContext.storageDirAbsolute, syncContext.syncState);
2202
- });
2203
- const totals = computeTotals(syncContext.syncState.items);
2204
- syncContext.totalIssues = totals.totalIssues;
2205
- syncContext.totalPulls = totals.totalPulls;
2206
- const finishedAt = /* @__PURE__ */ new Date();
2207
- const durationMs = Math.max(0, finishedAt.getTime() - startedAt.getTime());
2208
- const requestCount = provider.getRequestCount();
2209
- const summary = {
2210
- repo: options.repo,
2211
- since,
2212
- syncedAt: syncContext.syncedAt,
2213
- totalIssues: totals.totalIssues,
2214
- totalPulls: totals.totalPulls,
2215
- updatedIssues,
2216
- updatedPulls,
2217
- trackedItems: totals.trackedItems,
2218
- requestCount,
2219
- scanned: counters.scanned,
2220
- selected: counters.selected,
2221
- processed: counters.processed,
2222
- skipped: counters.skipped,
2223
- written: counters.written,
2224
- moved: counters.moved,
2225
- patchesWritten: counters.patchesWritten,
2226
- patchesDeleted: counters.patchesDeleted,
2227
- durationMs
2228
- };
2229
- syncContext.syncState.lastSyncRun = {
2230
- runId,
2231
- repo: options.repo,
2232
- startedAt: startedAtIso,
2233
- finishedAt: finishedAt.toISOString(),
2234
- durationMs,
2235
- requestCount,
2236
- since,
2237
- numbersCount: targetNumbers?.length,
2238
- counters: cloneSnapshot(counters),
2239
- stages: { ...stageDurations }
2240
- };
2241
- await saveSyncState(syncContext.storageDirAbsolute, syncContext.syncState);
2242
- reporter?.onComplete?.({
2243
- summary,
2244
- stages: { ...stageDurations }
2245
- });
2246
- return summary;
2247
- } catch (error) {
2248
- if (!errorReported) reporter?.onError?.({
2249
- error,
2250
- snapshot: cloneSnapshot(counters)
2251
- });
2252
- throw error;
2253
- }
2254
- }
2255
- function assertContext(context) {
2256
- if (!context) throw new Error("Sync context was not initialized");
2257
- }
2258
- function createSyncRunId() {
2259
- return `sync_${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:.TZ]/g, "")}_${randomBytes(3).toString("hex")}`;
2260
- }
2261
- function createStageDurations() {
2262
- return {
2263
- metadata: 0,
2264
- pagination: 0,
2265
- fetch: 0,
2266
- materialize: 0,
2267
- prune: 0,
2268
- save: 0
2269
- };
2270
- }
2271
- function cloneSnapshot(counters) {
2272
- return {
2273
- scanned: counters.scanned,
2274
- selected: counters.selected,
2275
- processed: counters.processed,
2276
- skipped: counters.skipped,
2277
- written: counters.written,
2278
- moved: counters.moved,
2279
- patchesWritten: counters.patchesWritten,
2280
- patchesDeleted: counters.patchesDeleted
2281
- };
2282
- }
2283
- function computeTotals(items) {
2284
- let totalIssues = 0;
2285
- let totalPulls = 0;
2286
- for (const item of Object.values(items)) if (item.kind === "issue") totalIssues += 1;
2287
- else totalPulls += 1;
2288
- return {
2289
- totalIssues,
2290
- totalPulls,
2291
- trackedItems: totalIssues + totalPulls
2292
- };
2293
- }
2294
- //#endregion
2295
- //#region src/server/poller.ts
2296
- function createRemotePoller(options) {
2297
- const intervalMs = options.intervalMs ?? 6e4;
2298
- let current = options.initial ?? {
2299
- downCount: 0,
2300
- checkedAt: (/* @__PURE__ */ new Date(0)).toISOString(),
2301
- stale: true,
2302
- message: "Not checked yet"
2303
- };
2304
- let stopped = false;
2305
- let timer;
2306
- let failures = 0;
2307
- let inFlight;
2308
- function setStatus(next) {
2309
- current = next;
2310
- options.onUpdate(current);
2311
- return current;
2312
- }
2313
- async function doCheck() {
2314
- const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
2315
- const since = options.getSince();
2316
- if (!since) return setStatus({
2317
- downCount: 0,
2318
- checkedAt,
2319
- stale: true,
2320
- message: "Not synced yet"
2321
- });
2322
- let provider;
2323
- try {
2324
- provider = await options.getProvider();
2325
- } catch (error) {
2326
- return setStatus({
2327
- downCount: current.downCount,
2328
- checkedAt,
2329
- stale: true,
2330
- message: error.message
2331
- });
2332
- }
2333
- if (!provider) return setStatus({
2334
- downCount: 0,
2335
- checkedAt,
2336
- stale: true,
2337
- message: "Missing GitHub token"
2338
- });
2339
- try {
2340
- const counts = await provider.countUpdatedSince(since);
2341
- failures = 0;
2342
- return setStatus({
2343
- downCount: counts.issues + counts.pulls,
2344
- checkedAt,
2345
- stale: false
2346
- });
2347
- } catch (error) {
2348
- failures += 1;
2349
- return setStatus({
2350
- downCount: current.downCount,
2351
- checkedAt,
2352
- stale: true,
2353
- message: error.message
2354
- });
2355
- }
2356
- }
2357
- async function check() {
2358
- if (inFlight) return inFlight;
2359
- inFlight = doCheck();
2360
- try {
2361
- return await inFlight;
2362
- } finally {
2363
- inFlight = void 0;
2364
- schedule();
2365
- }
2366
- }
2367
- function schedule() {
2368
- if (stopped) return;
2369
- if (timer) clearTimeout(timer);
2370
- const backoff = failures === 0 ? intervalMs : Math.min(intervalMs * 2 ** Math.min(failures, 4), intervalMs * 16);
2371
- timer = setTimeout(() => {
2372
- check().catch(() => {});
2373
- }, backoff);
2374
- }
2375
- timer = setTimeout(() => {
2376
- check().catch(() => {});
2377
- }, 2e3);
2378
- return {
2379
- getCurrent: () => current,
2380
- checkNow: check,
2381
- close: () => {
2382
- stopped = true;
2383
- if (timer) clearTimeout(timer);
2384
- }
2385
- };
2386
- }
2387
- //#endregion
2388
- //#region src/server/queue-builder.ts
2389
- async function buildQueueState(options) {
2390
- const { storageDirAbsolute, executeFilePath } = options;
2391
- const executeMdPath = join(storageDirAbsolute, EXECUTE_MD_FILE_NAME);
2392
- const [yml, md, perItem, syncState] = await Promise.all([
2393
- readYmlOps(executeFilePath),
2394
- readMdOps(executeMdPath),
2395
- loadPerItemSource(storageDirAbsolute),
2396
- loadSyncState(storageDirAbsolute)
2397
- ]);
2398
- const entries = [];
2399
- for (const [index, op] of yml.ops.entries()) entries.push(buildEntry(op, "execute.yml", index));
2400
- for (const [index, op] of md.ops.entries()) entries.push(buildEntry(op, "execute.md", index));
2401
- for (const [index, op] of perItem.ops.entries()) {
2402
- const filePath = syncState.items[String(op.number)]?.filePath;
2403
- entries.push(buildEntry(op, "per-item", index, filePath));
2404
- }
2405
- return {
2406
- entries,
2407
- warnings: [
2408
- ...yml.warnings,
2409
- ...md.warnings,
2410
- ...perItem.warnings
2411
- ],
2412
- upCount: entries.length
2413
- };
2414
- }
2415
- async function readYmlOps(path) {
2416
- if (!await pathExists(path)) return {
2417
- ops: [],
2418
- warnings: []
2419
- };
2420
- try {
2421
- return {
2422
- ops: (await readAndValidateExecuteFileWithSource(path)).ops,
2423
- warnings: []
2424
- };
2425
- } catch (error) {
2426
- return {
2427
- ops: [],
2428
- warnings: [`execute.yml: ${error.message}`]
2429
- };
2430
- }
2431
- }
2432
- async function readMdOps(path) {
2433
- const parsed = await readExecuteMdFile(path);
2434
- return {
2435
- ops: parsed.ops,
2436
- warnings: parsed.warnings
2437
- };
2438
- }
2439
- function buildEntry(op, source, index, filePath) {
2440
- return {
2441
- id: hash({
2442
- source,
2443
- index,
2444
- action: op.action,
2445
- number: op.number
2446
- }),
2447
- source,
2448
- index,
2449
- op,
2450
- filePath
2451
- };
2452
- }
2453
- //#endregion
2454
- //#region src/server/handlers/editor.ts
2455
- function createEditorHandler(ctx) {
2456
- return async function openInEditor(filePath) {
2457
- const absolute = isAbsolute(filePath) ? filePath : resolve(ctx.storageDirAbsolute, filePath);
2458
- const editor = process.env.EDITOR || process.env.VISUAL || "code";
2459
- return new Promise((resolvePromise, rejectPromise) => {
2460
- const child = spawn(editor, [absolute], {
2461
- stdio: "ignore",
2462
- detached: true
2463
- });
2464
- child.on("error", rejectPromise);
2465
- child.unref();
2466
- resolvePromise();
2467
- });
2468
- };
2469
- }
2470
- //#endregion
2471
- //#region src/server/handlers/execute.ts
2472
- function createExecuteHandler(ctx) {
2473
- let running = false;
2474
- return async function executeQueue(options) {
2475
- if (running) throw new Error("An execute is already in progress");
2476
- running = true;
2477
- try {
2478
- const token = await ctx.getToken();
2479
- const selectedIndexes = await resolveSelectedIndexes(ctx, options.entryIds);
2480
- ctx.broadcast.onExecuteStart({ planned: selectedIndexes?.length ?? -1 });
2481
- return await executePendingChanges({
2482
- config: ctx.config,
2483
- repo: ctx.repo,
2484
- token,
2485
- executeFilePath: ctx.executeFilePath,
2486
- apply: true,
2487
- nonInteractive: true,
2488
- continueOnError: options.continueOnError ?? true,
2489
- selectedIndexes,
2490
- reporter: {
2491
- onStart(event) {
2492
- ctx.broadcast.onExecuteStart({ planned: event.planned });
2493
- },
2494
- onProgress(event) {
2495
- ctx.broadcast.onExecuteProgress({
2496
- completed: event.completed,
2497
- planned: event.planned,
2498
- applied: event.applied,
2499
- failed: event.failed,
2500
- detail: event.detail
2501
- });
2502
- },
2503
- onComplete(event) {
2504
- ctx.broadcast.onExecuteComplete(event.result);
2505
- },
2506
- onError(event) {
2507
- const message = event.error instanceof Error ? event.error.message : String(event.error);
2508
- ctx.broadcast.onExecuteError(message);
2509
- }
2510
- }
2511
- });
2512
- } finally {
2513
- running = false;
2514
- }
2515
- };
2516
- }
2517
- async function resolveSelectedIndexes(ctx, entryIds) {
2518
- if (!entryIds || entryIds.length === 0) return void 0;
2519
- const queue = await buildQueueState({
2520
- storageDirAbsolute: ctx.storageDirAbsolute,
2521
- executeFilePath: ctx.executeFilePath
2522
- });
2523
- const ids = new Set(entryIds);
2524
- const indexes = [];
2525
- queue.entries.forEach((entry, globalIndex) => {
2526
- if (ids.has(entry.id)) indexes.push(globalIndex);
2527
- });
2528
- return indexes;
2529
- }
2530
- //#endregion
2531
- //#region src/execute/compress.ts
2532
- function createEmptyState() {
2533
- return {
2534
- title: null,
2535
- body: null,
2536
- stateChange: null,
2537
- extraComments: [],
2538
- labels: {
2539
- mode: "delta",
2540
- set: [],
2541
- add: [],
2542
- remove: []
2543
- },
2544
- assignees: {
2545
- mode: "delta",
2546
- set: [],
2547
- add: [],
2548
- remove: []
2549
- },
2550
- reviewers: {
2551
- add: [],
2552
- remove: []
2553
- },
2554
- milestone: null,
2555
- lock: null,
2556
- draft: null,
2557
- ifUnchangedSince: void 0
2558
- };
2559
- }
2560
- function addUnique(list, value) {
2561
- if (!list.includes(value)) list.push(value);
2562
- }
2563
- function removeFromList(list, value) {
2564
- const idx = list.indexOf(value);
2565
- if (idx >= 0) list.splice(idx, 1);
2566
- }
2567
- function mergeIfUnchangedSince(current, next) {
2568
- if (!next) return current;
2569
- if (!current) return next;
2570
- try {
2571
- return new Date(next).getTime() < new Date(current).getTime() ? next : current;
2572
- } catch {
2573
- return current;
2574
- }
2575
- }
2576
- function applyOp(state, op) {
2577
- state.ifUnchangedSince = mergeIfUnchangedSince(state.ifUnchangedSince, op.ifUnchangedSince);
2578
- switch (op.action) {
2579
- case "close": {
2580
- if (state.stateChange?.kind === "reopen") {
2581
- state.stateChange = null;
2582
- break;
2583
- }
2584
- const body = state.stateChange?.kind === "close" ? state.stateChange.body : void 0;
2585
- state.stateChange = body ? {
2586
- kind: "close",
2587
- body
2588
- } : { kind: "close" };
2589
- break;
2590
- }
2591
- case "reopen":
2592
- if (state.stateChange?.kind === "close") {
2593
- state.stateChange = null;
2594
- break;
2595
- }
2596
- state.stateChange = { kind: "reopen" };
2597
- break;
2598
- case "close-with-comment":
2599
- if (state.stateChange?.kind === "reopen") {
2600
- addUnique(state.extraComments, op.body);
2601
- state.stateChange = null;
2602
- break;
2603
- }
2604
- if (state.stateChange?.kind === "close" && state.stateChange.body && state.stateChange.body !== op.body) addUnique(state.extraComments, state.stateChange.body);
2605
- state.stateChange = {
2606
- kind: "close",
2607
- body: op.body
2608
- };
2609
- break;
2610
- case "set-title":
2611
- state.title = op.title;
2612
- break;
2613
- case "set-body":
2614
- state.body = op.body;
2615
- break;
2616
- case "add-comment":
2617
- if (state.stateChange?.kind === "close" && state.stateChange.body === op.body) break;
2618
- addUnique(state.extraComments, op.body);
2619
- break;
2620
- case "add-labels":
2621
- if (state.labels.mode === "set") for (const l of op.labels) addUnique(state.labels.set, l);
2622
- else for (const l of op.labels) if (state.labels.remove.includes(l)) removeFromList(state.labels.remove, l);
2623
- else addUnique(state.labels.add, l);
2624
- break;
2625
- case "remove-labels":
2626
- if (state.labels.mode === "set") state.labels.set = state.labels.set.filter((l) => !op.labels.includes(l));
2627
- else for (const l of op.labels) if (state.labels.add.includes(l)) removeFromList(state.labels.add, l);
2628
- else addUnique(state.labels.remove, l);
2629
- break;
2630
- case "set-labels":
2631
- state.labels = {
2632
- mode: "set",
2633
- set: [...op.labels],
2634
- add: [],
2635
- remove: []
2636
- };
2637
- break;
2638
- case "add-assignees":
2639
- if (state.assignees.mode === "set") for (const a of op.assignees) addUnique(state.assignees.set, a);
2640
- else for (const a of op.assignees) if (state.assignees.remove.includes(a)) removeFromList(state.assignees.remove, a);
2641
- else addUnique(state.assignees.add, a);
2642
- break;
2643
- case "remove-assignees":
2644
- if (state.assignees.mode === "set") state.assignees.set = state.assignees.set.filter((a) => !op.assignees.includes(a));
2645
- else for (const a of op.assignees) if (state.assignees.add.includes(a)) removeFromList(state.assignees.add, a);
2646
- else addUnique(state.assignees.remove, a);
2647
- break;
2648
- case "set-assignees":
2649
- state.assignees = {
2650
- mode: "set",
2651
- set: [...op.assignees],
2652
- add: [],
2653
- remove: []
2654
- };
2655
- break;
2656
- case "set-milestone":
2657
- state.milestone = { set: op.milestone };
2658
- break;
2659
- case "clear-milestone":
2660
- state.milestone = "clear";
2661
- break;
2662
- case "lock":
2663
- state.lock = {
2664
- lock: true,
2665
- reason: op.reason
2666
- };
2667
- break;
2668
- case "unlock":
2669
- state.lock = state.lock?.lock === true ? null : { lock: false };
2670
- break;
2671
- case "convert-to-draft":
2672
- state.draft = state.draft === "ready" ? null : "draft";
2673
- break;
2674
- case "mark-ready-for-review":
2675
- state.draft = state.draft === "draft" ? null : "ready";
2676
- break;
2677
- case "request-reviewers":
2678
- for (const r of op.reviewers) if (state.reviewers.remove.includes(r)) removeFromList(state.reviewers.remove, r);
2679
- else addUnique(state.reviewers.add, r);
2680
- break;
2681
- case "remove-reviewers":
2682
- for (const r of op.reviewers) if (state.reviewers.add.includes(r)) removeFromList(state.reviewers.add, r);
2683
- else addUnique(state.reviewers.remove, r);
2684
- break;
2685
- }
2686
- }
2687
- function emit(number, state) {
2688
- const ifUnchangedSince = state.ifUnchangedSince;
2689
- const withBase = (op) => ifUnchangedSince ? {
2690
- ...op,
2691
- ifUnchangedSince
2692
- } : op;
2693
- const out = [];
2694
- if (state.title != null) out.push(withBase({
2695
- action: "set-title",
2696
- number,
2697
- title: state.title
2698
- }));
2699
- if (state.body != null) out.push(withBase({
2700
- action: "set-body",
2701
- number,
2702
- body: state.body
2703
- }));
2704
- if (state.labels.mode === "set") out.push(withBase({
2705
- action: "set-labels",
2706
- number,
2707
- labels: [...state.labels.set]
2708
- }));
2709
- else {
2710
- if (state.labels.add.length) out.push(withBase({
2711
- action: "add-labels",
2712
- number,
2713
- labels: [...state.labels.add]
2714
- }));
2715
- if (state.labels.remove.length) out.push(withBase({
2716
- action: "remove-labels",
2717
- number,
2718
- labels: [...state.labels.remove]
2719
- }));
2720
- }
2721
- if (state.assignees.mode === "set") out.push(withBase({
2722
- action: "set-assignees",
2723
- number,
2724
- assignees: [...state.assignees.set]
2725
- }));
2726
- else {
2727
- if (state.assignees.add.length) out.push(withBase({
2728
- action: "add-assignees",
2729
- number,
2730
- assignees: [...state.assignees.add]
2731
- }));
2732
- if (state.assignees.remove.length) out.push(withBase({
2733
- action: "remove-assignees",
2734
- number,
2735
- assignees: [...state.assignees.remove]
2736
- }));
2737
- }
2738
- if (state.milestone === "clear") out.push(withBase({
2739
- action: "clear-milestone",
2740
- number
2741
- }));
2742
- else if (state.milestone && "set" in state.milestone) out.push(withBase({
2743
- action: "set-milestone",
2744
- number,
2745
- milestone: state.milestone.set
2746
- }));
2747
- if (state.reviewers.add.length) out.push(withBase({
2748
- action: "request-reviewers",
2749
- number,
2750
- reviewers: [...state.reviewers.add]
2751
- }));
2752
- if (state.reviewers.remove.length) out.push(withBase({
2753
- action: "remove-reviewers",
2754
- number,
2755
- reviewers: [...state.reviewers.remove]
2756
- }));
2757
- if (state.draft === "draft") out.push(withBase({
2758
- action: "convert-to-draft",
2759
- number
2760
- }));
2761
- else if (state.draft === "ready") out.push(withBase({
2762
- action: "mark-ready-for-review",
2763
- number
2764
- }));
2765
- for (const body of state.extraComments) out.push(withBase({
2766
- action: "add-comment",
2767
- number,
2768
- body
2769
- }));
2770
- if (state.stateChange?.kind === "close") if (state.stateChange.body != null) out.push(withBase({
2771
- action: "close-with-comment",
2772
- number,
2773
- body: state.stateChange.body
2774
- }));
2775
- else out.push(withBase({
2776
- action: "close",
2777
- number
2778
- }));
2779
- else if (state.stateChange?.kind === "reopen") out.push(withBase({
2780
- action: "reopen",
2781
- number
2782
- }));
2783
- if (state.lock?.lock === true) out.push(withBase({
2784
- action: "lock",
2785
- number,
2786
- ...state.lock.reason ? { reason: state.lock.reason } : {}
2787
- }));
2788
- else if (state.lock?.lock === false) out.push(withBase({
2789
- action: "unlock",
2790
- number
2791
- }));
2792
- return out;
2793
- }
2794
- /**
2795
- * Compress a list of pending ops by merging/cancelling redundant ones per-item.
2796
- *
2797
- * - `close` + `reopen` cancel each other.
2798
- * - `close-with-comment("a")` + `close-with-comment("b")` keeps "b" bundled and demotes "a" to a standalone add-comment.
2799
- * - `close-with-comment("a")` + `reopen` cancels entirely (the body is dropped — if users want to keep the comment they can add it explicitly).
2800
- * - Adjacent `add-labels` / `remove-labels` merge; overlapping pairs cancel out.
2801
- * - `set-title` / `set-body` / `set-labels` / `set-assignees` / `set-milestone` / `clear-milestone` follow last-write-wins.
2802
- * - `add-comment` bodies dedupe.
2803
- * - `lock`/`unlock` and `convert-to-draft`/`mark-ready-for-review` cancel when paired in that order.
2804
- * - `ifUnchangedSince` is preserved as the earliest (most conservative) value across ops in the group.
2805
- *
2806
- * Groups are emitted in the order their number first appeared in the input.
2807
- */
2808
- function compressOps(ops) {
2809
- const groups = /* @__PURE__ */ new Map();
2810
- let order = 0;
2811
- for (const op of ops) {
2812
- let entry = groups.get(op.number);
2813
- if (!entry) {
2814
- entry = {
2815
- order: order++,
2816
- list: []
2817
- };
2818
- groups.set(op.number, entry);
2819
- }
2820
- entry.list.push(op);
2821
- }
2822
- const sorted = [...groups.entries()].sort((a, b) => a[1].order - b[1].order);
2823
- const result = [];
2824
- for (const [number, { list }] of sorted) {
2825
- const state = createEmptyState();
2826
- for (const op of list) applyOp(state, op);
2827
- result.push(...emit(number, state));
2828
- }
2829
- return result;
2830
- }
2831
- //#endregion
2832
- //#region src/server/queue-writer.ts
2833
- async function addQueueOp(options, op) {
2834
- await ensureExecuteArtifacts(options.executeFilePath);
2835
- const next = compressOps([...(await readAndValidateExecuteFileWithSource(options.executeFilePath)).ops, op]);
2836
- await writeExecuteFile(options.executeFilePath, next);
2837
- return buildQueueState(options);
2838
- }
2839
- async function removeQueueOp(options, id) {
2840
- const entry = (await buildQueueState(options)).entries.find((e) => e.id === id);
2841
- if (!entry) throw new Error(`Queue entry not found: ${id}`);
2842
- if (entry.source === "per-item") throw new Error(`Cannot remove a per-item edit from the queue. Edit ${entry.filePath ?? "the markdown file"} directly to adjust it.`);
2843
- if (entry.source === "execute.yml") {
2844
- const next = (await readAndValidateExecuteFileWithSource(options.executeFilePath)).ops.filter((_, index) => index !== entry.index);
2845
- await writeExecuteFile(options.executeFilePath, next);
2846
- return buildQueueState(options);
2847
- }
2848
- const mdPath = join(options.storageDirAbsolute, EXECUTE_MD_FILE_NAME);
2849
- if (!await pathExists(mdPath)) throw new Error("execute.md not found; cannot remove op");
2850
- const parsed = await readExecuteMdFile(mdPath);
2851
- const remaining = /* @__PURE__ */ new Set();
2852
- for (let i = 0; i < parsed.ops.length; i += 1) if (i !== entry.index) remaining.add(i);
2853
- await writeFile(mdPath, stringifyExecuteMd(parsed, remaining), "utf-8");
2854
- return buildQueueState(options);
2855
- }
2856
- async function updateQueueOp(options, id, op) {
2857
- const entry = (await buildQueueState(options)).entries.find((e) => e.id === id);
2858
- if (!entry) throw new Error(`Queue entry not found: ${id}`);
2859
- if (entry.source !== "execute.yml") throw new Error(`Cannot edit ${entry.source} ops from the queue panel`);
2860
- const replaced = (await readAndValidateExecuteFileWithSource(options.executeFilePath)).ops.map((existing, index) => index === entry.index ? op : existing);
2861
- await writeExecuteFile(options.executeFilePath, compressOps(replaced));
2862
- return buildQueueState(options);
2863
- }
2864
- async function clearQueue(options) {
2865
- await ensureExecuteArtifacts(options.executeFilePath);
2866
- await writeExecuteFile(options.executeFilePath, []);
2867
- return buildQueueState(options);
2868
- }
2869
- //#endregion
2870
- //#region src/server/handlers/queue.ts
2871
- function createQueueHandlers(ctx) {
2872
- const options = {
2873
- storageDirAbsolute: ctx.storageDirAbsolute,
2874
- executeFilePath: ctx.executeFilePath
2875
- };
2876
- return {
2877
- addQueueOp: (op) => addQueueOp(options, op),
2878
- updateQueueOp: (id, op) => updateQueueOp(options, id, op),
2879
- removeQueueOp: (id) => removeQueueOp(options, id),
2880
- clearQueue: () => clearQueue(options)
2881
- };
2882
- }
2883
- //#endregion
2884
- //#region src/server/handlers/remote.ts
2885
- function createRemoteHandler(ctx) {
2886
- return async function checkRemote() {
2887
- return ctx.poller.checkNow();
2888
- };
2889
- }
2890
- //#endregion
2891
- //#region src/server/ui-state.ts
2892
- const UI_STATE_FILE = ".ui.json";
2893
- function createEmptyUiState() {
2894
- return { drafts: {} };
2895
- }
2896
- async function loadUiState(storageDirAbsolute) {
2897
- try {
2898
- const raw = await readFile(join(storageDirAbsolute, UI_STATE_FILE), "utf8");
2899
- const parsed = JSON.parse(raw);
2900
- const drafts = {};
2901
- if (parsed.drafts && typeof parsed.drafts === "object") {
2902
- for (const [key, value] of Object.entries(parsed.drafts)) if (typeof value === "string" && value.length > 0) drafts[key] = value;
2903
- }
2904
- return {
2905
- drafts,
2906
- listPaneSize: typeof parsed.listPaneSize === "number" ? parsed.listPaneSize : void 0
2907
- };
2908
- } catch {
2909
- return createEmptyUiState();
2910
- }
2911
- }
2912
- async function saveUiState(storageDirAbsolute, state) {
2913
- await mkdir(storageDirAbsolute, { recursive: true });
2914
- const clean = {
2915
- drafts: { ...state.drafts },
2916
- ...state.listPaneSize != null ? { listPaneSize: state.listPaneSize } : {}
2917
- };
2918
- await writeFile(join(storageDirAbsolute, UI_STATE_FILE), `${JSON.stringify(clean, null, 2)}\n`, "utf8");
2919
- }
2920
- //#endregion
2921
- //#region src/server/handlers/state.ts
2922
- function createStateHandlers(ctx) {
2923
- async function getRepoMeta() {
2924
- const syncState = await loadSyncState(ctx.storageDirAbsolute);
2925
- let hasToken = false;
2926
- try {
2927
- const token = await ctx.getToken();
2928
- hasToken = Boolean(token);
2929
- } catch {
2930
- hasToken = false;
2931
- }
2932
- return {
2933
- repo: ctx.repo,
2934
- storageDir: ctx.config.directory,
2935
- ghfsVersion: GHFS_VERSION,
2936
- lastSyncedAt: syncState.lastSyncedAt,
2937
- lastSince: syncState.lastSince,
2938
- hasToken
2939
- };
2940
- }
2941
- async function getSyncState() {
2942
- return loadSyncState(ctx.storageDirAbsolute);
2943
- }
2944
- async function getQueue() {
2945
- return buildQueueState({
2946
- storageDirAbsolute: ctx.storageDirAbsolute,
2947
- executeFilePath: ctx.executeFilePath
2948
- });
2949
- }
2950
- async function getInitialPayload() {
2951
- const [repo, syncState, queue, uiState] = await Promise.all([
2952
- getRepoMeta(),
2953
- getSyncState(),
2954
- getQueue(),
2955
- loadUiState(ctx.storageDirAbsolute)
2956
- ]);
2957
- return {
2958
- repo,
2959
- syncState,
2960
- queue,
2961
- remote: ctx.poller.getCurrent(),
2962
- recentExecutions: syncState.executions ?? [],
2963
- uiState
2964
- };
2965
- }
2966
- return {
2967
- getInitialPayload,
2968
- getSyncState,
2969
- getQueue,
2970
- getRepoMeta,
2971
- saveUiState: (state) => saveUiState(ctx.storageDirAbsolute, state)
2972
- };
2973
- }
2974
- //#endregion
2975
- //#region src/server/handlers/sync.ts
2976
- function createSyncHandler(ctx) {
2977
- let running = false;
2978
- return async function triggerSync(options) {
2979
- if (running) throw new Error("A sync is already in progress");
2980
- running = true;
2981
- try {
2982
- const token = await ctx.getToken();
2983
- return await syncRepository({
2984
- config: ctx.config,
2985
- repo: ctx.repo,
2986
- token,
2987
- full: options.full,
2988
- since: options.since,
2989
- numbers: options.numbers,
2990
- reporter: {
2991
- onStageStart(event) {
2992
- ctx.broadcast.onSyncStageStart({
2993
- stage: event.stage,
2994
- message: event.message
2995
- });
2996
- },
2997
- onStageUpdate(event) {
2998
- ctx.broadcast.onSyncProgress({
2999
- stage: event.stage,
3000
- message: event.message,
3001
- snapshot: event.snapshot
3002
- });
3003
- },
3004
- onStageEnd(event) {
3005
- ctx.broadcast.onSyncStageEnd({
3006
- stage: event.stage,
3007
- durationMs: event.durationMs
3008
- });
3009
- },
3010
- onComplete(event) {
3011
- ctx.broadcast.onSyncComplete(event.summary);
3012
- },
3013
- onError(event) {
3014
- const message = event.error instanceof Error ? event.error.message : String(event.error);
3015
- ctx.broadcast.onSyncError(message);
3016
- }
3017
- }
3018
- });
3019
- } finally {
3020
- running = false;
3021
- }
3022
- };
3023
- }
3024
- //#endregion
3025
- //#region src/server/rpc.ts
3026
- function createServerFunctions(ctx) {
3027
- const state = createStateHandlers(ctx);
3028
- const queue = createQueueHandlers(ctx);
3029
- return {
3030
- getInitialPayload: state.getInitialPayload,
3031
- getSyncState: state.getSyncState,
3032
- getQueue: state.getQueue,
3033
- getRepoMeta: state.getRepoMeta,
3034
- triggerSync: createSyncHandler(ctx),
3035
- executeQueue: createExecuteHandler(ctx),
3036
- addQueueOp: queue.addQueueOp,
3037
- updateQueueOp: queue.updateQueueOp,
3038
- removeQueueOp: queue.removeQueueOp,
3039
- clearQueue: queue.clearQueue,
3040
- checkRemote: createRemoteHandler(ctx),
3041
- openInEditor: createEditorHandler(ctx),
3042
- saveUiState: state.saveUiState
3043
- };
3044
- }
3045
- //#endregion
3046
- //#region src/server/static.ts
3047
- const MIME_TYPES = {
3048
- css: "text/css; charset=utf-8",
3049
- html: "text/html; charset=utf-8",
3050
- ico: "image/x-icon",
3051
- jpeg: "image/jpeg",
3052
- jpg: "image/jpeg",
3053
- js: "application/javascript; charset=utf-8",
3054
- json: "application/json; charset=utf-8",
3055
- map: "application/json; charset=utf-8",
3056
- mjs: "application/javascript; charset=utf-8",
3057
- png: "image/png",
3058
- svg: "image/svg+xml; charset=utf-8",
3059
- txt: "text/plain; charset=utf-8",
3060
- webp: "image/webp",
3061
- woff: "font/woff",
3062
- woff2: "font/woff2",
3063
- xml: "application/xml; charset=utf-8"
3064
- };
3065
- function mimeTypeFor(id) {
3066
- const dot = id.lastIndexOf(".");
3067
- if (dot < 0) return void 0;
3068
- return MIME_TYPES[id.slice(dot + 1).toLowerCase()];
3069
- }
3070
- async function createStaticHandler(staticDir) {
3071
- async function metaFor(id) {
3072
- let stats;
3073
- try {
3074
- stats = await stat(resolve(staticDir, `.${id}`));
3075
- } catch {
3076
- return;
3077
- }
3078
- if (!stats.isFile()) return void 0;
3079
- return {
3080
- mtime: stats.mtimeMs,
3081
- size: stats.size,
3082
- type: mimeTypeFor(id)
3083
- };
3084
- }
3085
- const spaFallback = await readFallback(staticDir);
3086
- return eventHandler(async (event) => {
3087
- if (await serveStatic(event, {
3088
- getContents: (id) => readFile(resolve(staticDir, `.${id}`)),
3089
- getMeta: (id) => metaFor(id),
3090
- indexNames: ["/index.html"],
3091
- fallthrough: true
3092
- }) !== false) return;
3093
- if (spaFallback) {
3094
- setResponseHeader(event, "content-type", "text/html; charset=utf-8");
3095
- return spaFallback;
3096
- }
3097
- setResponseHeader(event, "content-type", "text/plain; charset=utf-8");
3098
- return `ghfs UI assets not found at ${staticDir}. Run "pnpm build" first.\n`;
3099
- });
3100
- }
3101
- async function readFallback(staticDir) {
3102
- for (const name of ["200.html", "index.html"]) {
3103
- const candidate = resolve(staticDir, name);
3104
- if (await pathExists(candidate)) return readFile(candidate, "utf-8");
3105
- }
3106
- }
3107
- //#endregion
3108
- //#region src/server/watcher.ts
3109
- async function createGhfsWatcher(options) {
3110
- const { storageDirAbsolute, onSyncStateChange, onQueueChange } = options;
3111
- const debounceMs = options.debounceMs ?? 150;
3112
- await mkdir(storageDirAbsolute, { recursive: true });
3113
- let syncTimer;
3114
- let queueTimer;
3115
- const flushSync = () => {
3116
- syncTimer = void 0;
3117
- try {
3118
- onSyncStateChange();
3119
- } catch {}
3120
- };
3121
- const flushQueue = () => {
3122
- queueTimer = void 0;
3123
- try {
3124
- onQueueChange();
3125
- } catch {}
3126
- };
3127
- const scheduleSync = () => {
3128
- if (syncTimer) clearTimeout(syncTimer);
3129
- syncTimer = setTimeout(flushSync, debounceMs);
3130
- };
3131
- const scheduleQueue = () => {
3132
- if (queueTimer) clearTimeout(queueTimer);
3133
- queueTimer = setTimeout(flushQueue, debounceMs);
3134
- };
3135
- const controller = new AbortController();
3136
- const iterator = watch(storageDirAbsolute, {
3137
- recursive: true,
3138
- signal: controller.signal
3139
- });
3140
- const pump = async () => {
3141
- try {
3142
- for await (const event of iterator) {
3143
- const filename = event.filename ? event.filename.replace(/\\/g, "/") : "";
3144
- if (!filename) continue;
3145
- const basename = filename.split("/").pop() ?? "";
3146
- if (basename === ".sync.json") {
3147
- scheduleSync();
3148
- scheduleQueue();
3149
- continue;
3150
- }
3151
- if (basename === "execute.yml" || basename === "execute.md") {
3152
- scheduleQueue();
3153
- continue;
3154
- }
3155
- if (basename.endsWith(".md")) scheduleQueue();
3156
- }
3157
- } catch (error) {
3158
- if (error.name !== "AbortError") throw error;
3159
- }
3160
- };
3161
- pump();
3162
- return { close: async () => {
3163
- controller.abort();
3164
- if (syncTimer) clearTimeout(syncTimer);
3165
- if (queueTimer) clearTimeout(queueTimer);
3166
- } };
3167
- }
3168
- //#endregion
3169
- //#region src/server/index.ts
3170
- const EVENT_NAMES = [
3171
- "onSyncStageStart",
3172
- "onSyncProgress",
3173
- "onSyncStageEnd",
3174
- "onSyncComplete",
3175
- "onSyncError",
3176
- "onExecuteStart",
3177
- "onExecuteProgress",
3178
- "onExecuteComplete",
3179
- "onExecuteError",
3180
- "onSyncStateChange",
3181
- "onQueueChange",
3182
- "onRemoteStatusChange"
3183
- ];
3184
- async function createUiServer(options) {
3185
- const storageDirAbsolute = resolve(options.config.cwd, options.config.directory);
3186
- const executeFilePath = resolve(options.config.cwd, getExecuteFile(options.config));
3187
- let cachedToken = options.initialToken ?? "";
3188
- async function getToken() {
3189
- if (cachedToken) return cachedToken;
3190
- if (options.onRequestToken) {
3191
- cachedToken = await options.onRequestToken();
3192
- return cachedToken;
3193
- }
3194
- throw new Error("Missing GitHub token");
3195
- }
3196
- let cachedProvider;
3197
- async function getProvider() {
3198
- if (cachedProvider) return cachedProvider;
3199
- let token;
3200
- try {
3201
- token = await getToken();
3202
- } catch {
3203
- return null;
3204
- }
3205
- if (!token) return null;
3206
- cachedProvider = createRepositoryProvider({
3207
- token,
3208
- repo: options.repo
3209
- });
3210
- return cachedProvider;
3211
- }
3212
- let lastSyncedAt = (await loadSyncState(storageDirAbsolute)).lastSyncedAt;
3213
- const clients = /* @__PURE__ */ new Set();
3214
- const broadcast = createBroadcast(clients);
3215
- const poller = createRemotePoller({
3216
- intervalMs: options.pollerIntervalMs,
3217
- getProvider,
3218
- getSince: () => lastSyncedAt,
3219
- onUpdate: (status) => broadcast.onRemoteStatusChange(status)
3220
- });
3221
- const serverFunctions = createServerFunctions({
3222
- config: options.config,
3223
- repo: options.repo,
3224
- storageDirAbsolute,
3225
- executeFilePath,
3226
- getToken,
3227
- getProvider,
3228
- broadcast,
3229
- poller
3230
- });
3231
- const watcher = await createGhfsWatcher({
3232
- storageDirAbsolute,
3233
- onSyncStateChange: async () => {
3234
- const state = await loadSyncState(storageDirAbsolute);
3235
- lastSyncedAt = state.lastSyncedAt;
3236
- broadcast.onSyncStateChange(state);
3237
- },
3238
- onQueueChange: async () => {
3239
- const queue = await buildQueueState({
3240
- storageDirAbsolute,
3241
- executeFilePath
3242
- });
3243
- broadcast.onQueueChange(queue);
3244
- }
3245
- });
3246
- const app = createApp();
3247
- const router = createRouter();
3248
- router.get("/api/metadata.json", eventHandler(() => ({
3249
- repo: options.repo,
3250
- storageDir: options.config.directory,
3251
- ghfsVersion: GHFS_VERSION,
3252
- wsPath: "/__ws",
3253
- devMode: Boolean(options.devMode)
3254
- })));
3255
- app.use(router);
3256
- if (options.devMode) app.use("/", eventHandler((event) => {
3257
- setResponseStatus(event, 200);
3258
- setResponseHeader(event, "content-type", "text/plain; charset=utf-8");
3259
- return `ghfs ui dev mode — open http://localhost:7711 for the Vite-powered UI.\n`;
3260
- }));
3261
- else {
3262
- const staticDir = join(distDir, "ui");
3263
- app.use("/", await createStaticHandler(staticDir));
3264
- }
3265
- const port = await getPort({
3266
- port: options.port,
3267
- portRange: [options.port, options.port + 19],
3268
- host: options.host
3269
- });
3270
- const httpServer = createServer(toNodeListener(app));
3271
- const wss = new WebSocketServer({
3272
- server: httpServer,
3273
- path: "/__ws"
3274
- });
3275
- wss.on("connection", (socket) => {
3276
- const rpc = createBirpc(serverFunctions, {
3277
- post: (data) => socket.send(data),
3278
- on: (fn) => socket.on("message", (raw) => {
3279
- fn(rawToString(raw));
3280
- }),
3281
- serialize: (data) => stringify$1(data),
3282
- deserialize: (raw) => parse$1(rawToString(raw)),
3283
- timeout: 12e4,
3284
- eventNames: EVENT_NAMES
3285
- });
3286
- clients.add(rpc);
3287
- socket.on("close", () => {
3288
- clients.delete(rpc);
3289
- });
3290
- socket.on("error", () => {
3291
- clients.delete(rpc);
3292
- });
3293
- });
3294
- await new Promise((resolvePromise, rejectPromise) => {
3295
- httpServer.once("error", rejectPromise);
3296
- httpServer.listen(port, options.host, () => {
3297
- httpServer.off("error", rejectPromise);
3298
- resolvePromise();
3299
- });
3300
- });
3301
- return {
3302
- url: `http://${options.host === "0.0.0.0" ? "localhost" : options.host}:${port}`,
3303
- port,
3304
- host: options.host,
3305
- close: async () => {
3306
- poller.close();
3307
- await watcher.close();
3308
- await new Promise((resolveClose) => wss.close(() => resolveClose()));
3309
- await new Promise((resolveClose) => httpServer.close(() => resolveClose()));
3310
- }
3311
- };
3312
- }
3313
- function createBroadcast(clients) {
3314
- return new Proxy({}, { get(_, prop) {
3315
- if (typeof prop !== "string") return void 0;
3316
- return (...args) => {
3317
- for (const rpc of clients) try {
3318
- const fn = rpc[prop];
3319
- if (typeof fn === "function") fn(...args);
3320
- } catch {}
3321
- };
3322
- } });
3323
- }
3324
- function rawToString(raw) {
3325
- if (typeof raw === "string") return raw;
3326
- if (raw instanceof Uint8Array) return Buffer.from(raw).toString("utf-8");
3327
- if (Array.isArray(raw)) return Buffer.concat(raw).toString("utf-8");
3328
- return String(raw);
3329
- }
3330
- //#endregion
3331
- export { isExecuteCancelledError as a, GHFS_VERSION as c, pathExists as d, getExecuteFile as f, executePendingChanges as i, ensureExecuteArtifacts as l, resolveConfig as m, syncRepository as n, loadSyncState as o, getStorageDirAbsolute as p, appendExecutionResult as r, GHFS_NAME as s, createUiServer as t, ACTIONS_COLOR_HEX as u };