@bkm016/basalt 0.1.29 → 0.1.31

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 (964) hide show
  1. package/README.md +3 -2
  2. package/chunk-04326385.js +39 -0
  3. package/chunk-0er07d2g.js +51 -0
  4. package/chunk-0ge4k9gq.js +2 -0
  5. package/chunk-11zc1b2w.js +3 -0
  6. package/chunk-12203fgm.js +2 -0
  7. package/chunk-194d4z7x.js +7 -0
  8. package/chunk-1apm7p2e.js +2 -0
  9. package/chunk-1t0yzkg7.js +4 -0
  10. package/chunk-2csz31nh.js +2 -0
  11. package/chunk-2rqpfv4h.js +3 -0
  12. package/chunk-39cfcar4.js +3 -0
  13. package/chunk-3gw871zb.js +2 -0
  14. package/chunk-4a5xttdp.js +3 -0
  15. package/chunk-4st5xeee.js +2 -0
  16. package/chunk-5h17n6g1.js +3 -0
  17. package/chunk-5rn18vrq.js +5 -0
  18. package/chunk-5tdnvdmz.js +2 -0
  19. package/chunk-6gzvp0f6.js +50 -0
  20. package/chunk-6qavr39k.js +2 -0
  21. package/chunk-6xn0r0dd.js +3 -0
  22. package/chunk-71pz02bd.js +8 -0
  23. package/chunk-7h76jrss.js +7 -0
  24. package/chunk-7hss4hs3.js +7 -0
  25. package/chunk-7vdq0wye.js +2 -0
  26. package/chunk-7w187ycz.js +10 -0
  27. package/chunk-81s7mvf2.js +16 -0
  28. package/chunk-8j8acxde.js +2 -0
  29. package/chunk-9nfz04yr.js +2 -0
  30. package/chunk-9nkb5q43.js +3 -0
  31. package/chunk-9zcfam20.js +2 -0
  32. package/chunk-a6zvmsbh.js +12 -0
  33. package/chunk-anr8aghq.js +59 -0
  34. package/chunk-av8zh9yp.js +2 -0
  35. package/chunk-bwv97dtf.js +2 -0
  36. package/chunk-cjy4rssa.js +10 -0
  37. package/chunk-dmdyqq1k.js +2 -0
  38. package/chunk-dzvq7vt6.js +2 -0
  39. package/chunk-ejrksf6g.js +3 -0
  40. package/chunk-erxka5vh.js +18 -0
  41. package/chunk-fc41dvhp.js +12 -0
  42. package/chunk-fdgrayj5.js +3 -0
  43. package/chunk-fsekbhqb.js +3 -0
  44. package/chunk-fwcqcecb.js +8 -0
  45. package/chunk-hhwnmhbb.js +2 -0
  46. package/chunk-jm2bn5mq.js +3 -0
  47. package/chunk-jm5j5jfy.js +3 -0
  48. package/chunk-jsvr3s4q.js +5 -0
  49. package/chunk-jwk5a5tk.js +25 -0
  50. package/chunk-khy3j5kp.js +63 -0
  51. package/chunk-mwc59w50.js +31 -0
  52. package/chunk-mypbpphn.js +3 -0
  53. package/chunk-ng5ncy65.js +2 -0
  54. package/chunk-nmvayfq3.js +3 -0
  55. package/chunk-nw4h0wm9.js +2 -0
  56. package/chunk-pxsgm6ff.js +2 -0
  57. package/chunk-r0gsb1qs.js +3 -0
  58. package/chunk-rbfpa63e.js +3 -0
  59. package/chunk-rsrh5dgx.js +2 -0
  60. package/chunk-s2pm97nk.js +286 -0
  61. package/chunk-s6tnmg6x.js +3 -0
  62. package/chunk-se548edt.js +20 -0
  63. package/chunk-tsdeeqb8.js +3 -0
  64. package/chunk-vnv3a6t2.js +3 -0
  65. package/chunk-vrsh8cx1.js +3 -0
  66. package/chunk-vx4v71t4.js +498 -0
  67. package/chunk-w3v8zahw.js +2 -0
  68. package/chunk-w6m8c4vf.js +11 -0
  69. package/chunk-wd7sj5cv.js +2 -0
  70. package/chunk-we8v9wkw.js +9 -0
  71. package/chunk-wvn68m5f.js +4058 -0
  72. package/chunk-x055cas0.js +5 -0
  73. package/chunk-x2ry671h.js +44 -0
  74. package/chunk-x5vrtxkj.js +3 -0
  75. package/chunk-xedzsj31.js +5 -0
  76. package/chunk-xp83v3zm.js +2 -0
  77. package/chunk-ykzm5g1b.js +25 -0
  78. package/chunk-yq2bwebb.js +3 -0
  79. package/chunk-yygcpnwc.js +3 -0
  80. package/chunk-zjf34acb.js +2 -0
  81. package/compiled.js +10 -10
  82. package/package.json +4 -1
  83. package/ui-test-worker.js +24 -24
  84. package/web/chunk-01mrggts.js +1 -0
  85. package/web/chunk-01mrggts.js.br +0 -0
  86. package/web/chunk-01mrggts.js.gz +0 -0
  87. package/web/chunk-0b25tje3.js +1 -0
  88. package/web/chunk-0b25tje3.js.br +0 -0
  89. package/web/chunk-0b25tje3.js.gz +0 -0
  90. package/web/chunk-0g46ww9d.js +1 -0
  91. package/web/chunk-0g46ww9d.js.br +0 -0
  92. package/web/chunk-0g46ww9d.js.gz +0 -0
  93. package/web/chunk-0grg8w51.js +200 -0
  94. package/web/chunk-0grg8w51.js.br +0 -0
  95. package/web/chunk-0grg8w51.js.gz +0 -0
  96. package/web/chunk-0qf3m69c.js +24 -0
  97. package/web/chunk-0qf3m69c.js.br +0 -0
  98. package/web/chunk-0qf3m69c.js.gz +0 -0
  99. package/web/chunk-14yejkcn.js +7 -0
  100. package/web/chunk-14yejkcn.js.br +0 -0
  101. package/web/chunk-14yejkcn.js.gz +0 -0
  102. package/web/chunk-1ffzwm6m.js +106 -0
  103. package/web/chunk-1ffzwm6m.js.br +0 -0
  104. package/web/chunk-1ffzwm6m.js.gz +0 -0
  105. package/web/chunk-1ncaw3hk.js +3 -0
  106. package/web/chunk-1ncaw3hk.js.br +0 -0
  107. package/web/chunk-1ncaw3hk.js.gz +0 -0
  108. package/web/chunk-1x2kh4he.js +1 -0
  109. package/web/chunk-1x2kh4he.js.br +0 -0
  110. package/web/chunk-1x2kh4he.js.gz +0 -0
  111. package/web/chunk-23atmwvk.js +2 -0
  112. package/web/chunk-23atmwvk.js.br +0 -0
  113. package/web/chunk-23atmwvk.js.gz +0 -0
  114. package/web/chunk-2gfgrjy6.js +142 -0
  115. package/web/chunk-2gfgrjy6.js.br +0 -0
  116. package/web/chunk-2gfgrjy6.js.gz +0 -0
  117. package/web/chunk-2ttatv42.js +2 -0
  118. package/web/chunk-2ttatv42.js.br +0 -0
  119. package/web/chunk-2ttatv42.js.gz +0 -0
  120. package/web/chunk-2vqn82nw.js +139 -0
  121. package/web/chunk-2vqn82nw.js.br +0 -0
  122. package/web/chunk-2vqn82nw.js.gz +0 -0
  123. package/web/chunk-2wzvn2ne.js +1 -0
  124. package/web/chunk-2wzvn2ne.js.br +0 -0
  125. package/web/chunk-2wzvn2ne.js.gz +0 -0
  126. package/web/chunk-3at8qbcv.js +89 -0
  127. package/web/chunk-3at8qbcv.js.br +0 -0
  128. package/web/chunk-3at8qbcv.js.gz +0 -0
  129. package/web/chunk-3b97pd97.js +120 -0
  130. package/web/chunk-3b97pd97.js.br +0 -0
  131. package/web/chunk-3b97pd97.js.gz +0 -0
  132. package/web/chunk-3q5j14ah.js +1 -0
  133. package/web/chunk-3q5j14ah.js.br +0 -0
  134. package/web/chunk-3q5j14ah.js.gz +0 -0
  135. package/web/chunk-45xqp3dn.js +1 -0
  136. package/web/chunk-45xqp3dn.js.br +0 -0
  137. package/web/chunk-45xqp3dn.js.gz +0 -0
  138. package/web/chunk-4fdgpye3.js +2 -0
  139. package/web/chunk-4fdgpye3.js.br +0 -0
  140. package/web/chunk-4fdgpye3.js.gz +0 -0
  141. package/web/chunk-4wpvkw6b.js +1141 -0
  142. package/web/chunk-4wpvkw6b.js.br +0 -0
  143. package/web/chunk-4wpvkw6b.js.gz +0 -0
  144. package/web/chunk-51m79xhr.js +2 -0
  145. package/web/chunk-51m79xhr.js.br +2 -0
  146. package/web/chunk-51m79xhr.js.gz +0 -0
  147. package/web/chunk-5c6q7asc.js +1 -0
  148. package/web/chunk-5c6q7asc.js.br +0 -0
  149. package/web/chunk-5c6q7asc.js.gz +0 -0
  150. package/web/chunk-5vbnqhs0.js +38 -0
  151. package/web/chunk-5vbnqhs0.js.br +0 -0
  152. package/web/chunk-5vbnqhs0.js.gz +0 -0
  153. package/web/chunk-688a15p4.js +2 -0
  154. package/web/chunk-688a15p4.js.br +0 -0
  155. package/web/chunk-688a15p4.js.gz +0 -0
  156. package/web/chunk-6f9btq4p.js +1 -0
  157. package/web/chunk-6f9btq4p.js.br +0 -0
  158. package/web/chunk-6f9btq4p.js.gz +0 -0
  159. package/web/chunk-6geede02.js +217 -0
  160. package/web/chunk-6geede02.js.br +0 -0
  161. package/web/chunk-6geede02.js.gz +0 -0
  162. package/web/chunk-6j37ynfq.js +1 -0
  163. package/web/chunk-6j37ynfq.js.br +0 -0
  164. package/web/chunk-6j37ynfq.js.gz +0 -0
  165. package/web/chunk-7j7btfha.js +292 -0
  166. package/web/chunk-7j7btfha.js.br +0 -0
  167. package/web/chunk-7j7btfha.js.gz +0 -0
  168. package/web/chunk-8299qcyc.js +1 -0
  169. package/web/chunk-8299qcyc.js.br +0 -0
  170. package/web/chunk-8299qcyc.js.gz +0 -0
  171. package/web/chunk-8mncz9c6.js +89 -0
  172. package/web/chunk-8mncz9c6.js.br +0 -0
  173. package/web/chunk-8mncz9c6.js.gz +0 -0
  174. package/web/chunk-8pygn7wf.js +1 -0
  175. package/web/chunk-8pygn7wf.js.br +0 -0
  176. package/web/chunk-8pygn7wf.js.gz +0 -0
  177. package/web/chunk-8ye62j8m.js +2 -0
  178. package/web/chunk-8ye62j8m.js.br +3 -0
  179. package/web/chunk-8ye62j8m.js.gz +0 -0
  180. package/web/chunk-982457hh.js +1 -0
  181. package/web/chunk-982457hh.js.br +2 -0
  182. package/web/chunk-982457hh.js.gz +0 -0
  183. package/web/chunk-9f9pp12b.js +1 -0
  184. package/web/chunk-9f9pp12b.js.br +0 -0
  185. package/web/chunk-9f9pp12b.js.gz +0 -0
  186. package/web/chunk-9j7v0e4v.js +2 -0
  187. package/web/chunk-9j7v0e4v.js.br +0 -0
  188. package/web/chunk-9j7v0e4v.js.gz +0 -0
  189. package/web/chunk-9k6d95ab.js +1 -0
  190. package/web/chunk-9k6d95ab.js.br +0 -0
  191. package/web/chunk-9k6d95ab.js.gz +0 -0
  192. package/web/chunk-9z4tf6fd.js +1 -0
  193. package/web/chunk-9z4tf6fd.js.br +0 -0
  194. package/web/chunk-9z4tf6fd.js.gz +0 -0
  195. package/web/chunk-a11ev6ff.js +1 -0
  196. package/web/chunk-a11ev6ff.js.br +0 -0
  197. package/web/chunk-a11ev6ff.js.gz +0 -0
  198. package/web/chunk-ayamka39.js +1 -0
  199. package/web/chunk-ayamka39.js.br +0 -0
  200. package/web/chunk-ayamka39.js.gz +0 -0
  201. package/web/chunk-b6k80wbw.js +1 -0
  202. package/web/chunk-b6k80wbw.js.br +0 -0
  203. package/web/chunk-b6k80wbw.js.gz +0 -0
  204. package/web/chunk-b6w2gmw0.js +2 -0
  205. package/web/chunk-b6w2gmw0.js.br +0 -0
  206. package/web/chunk-b6w2gmw0.js.gz +0 -0
  207. package/web/chunk-ba22js10.js +84 -0
  208. package/web/chunk-ba22js10.js.br +0 -0
  209. package/web/chunk-ba22js10.js.gz +0 -0
  210. package/web/chunk-bq7y294e.js +34 -0
  211. package/web/chunk-bq7y294e.js.br +0 -0
  212. package/web/chunk-bq7y294e.js.gz +0 -0
  213. package/web/chunk-bw9crrb4.js +1 -0
  214. package/web/chunk-bw9crrb4.js.br +0 -0
  215. package/web/chunk-bw9crrb4.js.gz +0 -0
  216. package/web/chunk-c0vc50pd.js +4 -0
  217. package/web/chunk-c0vc50pd.js.br +0 -0
  218. package/web/chunk-c0vc50pd.js.gz +0 -0
  219. package/web/chunk-c2vtzhbs.js +1 -0
  220. package/web/chunk-c2vtzhbs.js.br +0 -0
  221. package/web/chunk-c2vtzhbs.js.gz +0 -0
  222. package/web/chunk-cf9886tj.js +2 -0
  223. package/web/chunk-cf9886tj.js.br +0 -0
  224. package/web/chunk-cf9886tj.js.gz +0 -0
  225. package/web/chunk-cqf4fzk6.js +16 -0
  226. package/web/chunk-cqf4fzk6.js.br +0 -0
  227. package/web/chunk-cqf4fzk6.js.gz +0 -0
  228. package/web/chunk-ct9sq4ka.js +1 -0
  229. package/web/chunk-ct9sq4ka.js.br +0 -0
  230. package/web/chunk-ct9sq4ka.js.gz +0 -0
  231. package/web/chunk-cy60hc6q.js +2 -0
  232. package/web/chunk-cy60hc6q.js.br +0 -0
  233. package/web/chunk-cy60hc6q.js.gz +0 -0
  234. package/web/chunk-cygtgz2r.js +2 -0
  235. package/web/chunk-cygtgz2r.js.br +0 -0
  236. package/web/chunk-cygtgz2r.js.gz +0 -0
  237. package/web/chunk-dgf0f0er.js +214 -0
  238. package/web/chunk-dgf0f0er.js.br +0 -0
  239. package/web/chunk-dgf0f0er.js.gz +0 -0
  240. package/web/chunk-dscn4mpq.js +4 -0
  241. package/web/chunk-dscn4mpq.js.br +0 -0
  242. package/web/chunk-dscn4mpq.js.gz +0 -0
  243. package/web/chunk-e7683p83.js +1 -0
  244. package/web/chunk-e7683p83.js.br +0 -0
  245. package/web/chunk-e7683p83.js.gz +0 -0
  246. package/web/chunk-eanfvatc.js +1 -0
  247. package/web/chunk-eanfvatc.js.br +0 -0
  248. package/web/chunk-eanfvatc.js.gz +0 -0
  249. package/web/chunk-egfn5522.js +1 -0
  250. package/web/chunk-egfn5522.js.br +3 -0
  251. package/web/chunk-egfn5522.js.gz +0 -0
  252. package/web/chunk-ejk5ec5n.js +1 -0
  253. package/web/chunk-ejk5ec5n.js.br +0 -0
  254. package/web/chunk-ejk5ec5n.js.gz +0 -0
  255. package/web/chunk-en5n60qw.js +2 -0
  256. package/web/chunk-en5n60qw.js.br +0 -0
  257. package/web/chunk-en5n60qw.js.gz +0 -0
  258. package/web/chunk-fzffxer1.js +41 -0
  259. package/web/chunk-fzffxer1.js.br +0 -0
  260. package/web/chunk-fzffxer1.js.gz +0 -0
  261. package/web/chunk-g19dt2gr.js +55 -0
  262. package/web/chunk-g19dt2gr.js.br +0 -0
  263. package/web/chunk-g19dt2gr.js.gz +0 -0
  264. package/web/chunk-g6cj4czr.js +2 -0
  265. package/web/chunk-g6cj4czr.js.br +0 -0
  266. package/web/chunk-g6cj4czr.js.gz +0 -0
  267. package/web/chunk-gbv8v3z7.js +78 -0
  268. package/web/chunk-gbv8v3z7.js.br +0 -0
  269. package/web/chunk-gbv8v3z7.js.gz +0 -0
  270. package/web/chunk-h1w081tm.js +12 -0
  271. package/web/chunk-h1w081tm.js.br +0 -0
  272. package/web/chunk-h1w081tm.js.gz +0 -0
  273. package/web/chunk-h47k4j7f.js +1 -0
  274. package/web/chunk-h47k4j7f.js.br +0 -0
  275. package/web/chunk-h47k4j7f.js.gz +0 -0
  276. package/web/chunk-h87t8gsr.js +1 -0
  277. package/web/chunk-h87t8gsr.js.br +0 -0
  278. package/web/chunk-h87t8gsr.js.gz +0 -0
  279. package/web/chunk-haewrbm7.js +1 -0
  280. package/web/chunk-haewrbm7.js.br +0 -0
  281. package/web/chunk-haewrbm7.js.gz +0 -0
  282. package/web/chunk-hahz28y7.js +2 -0
  283. package/web/chunk-hahz28y7.js.br +0 -0
  284. package/web/chunk-hahz28y7.js.gz +0 -0
  285. package/web/chunk-hqz75fkz.js +1 -0
  286. package/web/chunk-hqz75fkz.js.br +0 -0
  287. package/web/chunk-hqz75fkz.js.gz +0 -0
  288. package/web/chunk-hr4fa514.js +2 -0
  289. package/web/chunk-hr4fa514.js.br +0 -0
  290. package/web/chunk-hr4fa514.js.gz +0 -0
  291. package/web/chunk-j7vtqbbc.js +1 -0
  292. package/web/chunk-j7vtqbbc.js.br +0 -0
  293. package/web/chunk-j7vtqbbc.js.gz +0 -0
  294. package/web/chunk-jt33d37t.js +1 -0
  295. package/web/chunk-jt33d37t.js.br +0 -0
  296. package/web/chunk-jt33d37t.js.gz +0 -0
  297. package/web/chunk-k3qt0rx5.js +2 -0
  298. package/web/chunk-k3qt0rx5.js.br +0 -0
  299. package/web/chunk-k3qt0rx5.js.gz +0 -0
  300. package/web/chunk-kgmw7sh4.js +1 -0
  301. package/web/chunk-kgmw7sh4.js.br +0 -0
  302. package/web/chunk-kgmw7sh4.js.gz +0 -0
  303. package/web/chunk-kjvk8prw.js +1 -0
  304. package/web/chunk-kjvk8prw.js.br +0 -0
  305. package/web/chunk-kjvk8prw.js.gz +0 -0
  306. package/web/chunk-kq7snx3t.js +1 -0
  307. package/web/chunk-kq7snx3t.js.br +0 -0
  308. package/web/chunk-kq7snx3t.js.gz +0 -0
  309. package/web/chunk-kvteqhz2.js +1 -0
  310. package/web/chunk-kvteqhz2.js.br +2 -0
  311. package/web/chunk-kvteqhz2.js.gz +0 -0
  312. package/web/chunk-kypct03a.js +169 -0
  313. package/web/chunk-kypct03a.js.br +0 -0
  314. package/web/chunk-kypct03a.js.gz +0 -0
  315. package/web/chunk-m4hz4v80.js +370 -0
  316. package/web/chunk-m4hz4v80.js.br +0 -0
  317. package/web/chunk-m4hz4v80.js.gz +0 -0
  318. package/web/chunk-m5k8jhya.js +40 -0
  319. package/web/chunk-m5k8jhya.js.br +0 -0
  320. package/web/chunk-m5k8jhya.js.gz +0 -0
  321. package/web/chunk-mfsdyw6v.js +2 -0
  322. package/web/chunk-mfsdyw6v.js.br +0 -0
  323. package/web/chunk-mfsdyw6v.js.gz +0 -0
  324. package/web/chunk-mr38k717.js +140 -0
  325. package/web/chunk-mr38k717.js.br +0 -0
  326. package/web/chunk-mr38k717.js.gz +0 -0
  327. package/web/chunk-mtcet6gc.js +2 -0
  328. package/web/chunk-mtcet6gc.js.br +0 -0
  329. package/web/chunk-mtcet6gc.js.gz +0 -0
  330. package/web/chunk-mtfv8gjh.js +291 -0
  331. package/web/chunk-mtfv8gjh.js.br +0 -0
  332. package/web/chunk-mtfv8gjh.js.gz +0 -0
  333. package/web/chunk-nnyjx4ef.js +1 -0
  334. package/web/chunk-nnyjx4ef.js.br +0 -0
  335. package/web/chunk-nnyjx4ef.js.gz +0 -0
  336. package/web/chunk-npn3fk69.js +1 -0
  337. package/web/chunk-npn3fk69.js.br +2 -0
  338. package/web/chunk-npn3fk69.js.gz +0 -0
  339. package/web/chunk-p2gdfpjs.js +2 -0
  340. package/web/chunk-p2gdfpjs.js.br +0 -0
  341. package/web/chunk-p2gdfpjs.js.gz +0 -0
  342. package/web/chunk-q0by2m1w.js +21 -0
  343. package/web/chunk-q0by2m1w.js.br +0 -0
  344. package/web/chunk-q0by2m1w.js.gz +0 -0
  345. package/web/chunk-q5hj3y5k.js +2 -0
  346. package/web/chunk-q5hj3y5k.js.br +0 -0
  347. package/web/chunk-q5hj3y5k.js.gz +0 -0
  348. package/web/chunk-q6k872kv.js +7 -0
  349. package/web/chunk-q6k872kv.js.br +0 -0
  350. package/web/chunk-q6k872kv.js.gz +0 -0
  351. package/web/chunk-q7krdwy7.js +332 -0
  352. package/web/chunk-q7krdwy7.js.br +0 -0
  353. package/web/chunk-q7krdwy7.js.gz +0 -0
  354. package/web/chunk-q7wbksg4.js +1 -0
  355. package/web/chunk-q7wbksg4.js.br +0 -0
  356. package/web/chunk-q7wbksg4.js.gz +0 -0
  357. package/web/chunk-qdxa0c4c.js +1 -0
  358. package/web/chunk-qdxa0c4c.js.br +0 -0
  359. package/web/chunk-qdxa0c4c.js.gz +0 -0
  360. package/web/chunk-r76we294.js +1 -0
  361. package/web/chunk-r76we294.js.br +0 -0
  362. package/web/chunk-r76we294.js.gz +0 -0
  363. package/web/chunk-r9m8jh7x.js +2 -0
  364. package/web/chunk-r9m8jh7x.js.br +0 -0
  365. package/web/chunk-r9m8jh7x.js.gz +0 -0
  366. package/web/chunk-rnhbck1h.js +99 -0
  367. package/web/chunk-rnhbck1h.js.br +0 -0
  368. package/web/chunk-rnhbck1h.js.gz +0 -0
  369. package/web/chunk-rxtzde6n.js +62 -0
  370. package/web/chunk-rxtzde6n.js.br +0 -0
  371. package/web/chunk-rxtzde6n.js.gz +0 -0
  372. package/web/chunk-ryds6qnb.js +2 -0
  373. package/web/chunk-ryds6qnb.js.br +0 -0
  374. package/web/chunk-ryds6qnb.js.gz +0 -0
  375. package/web/chunk-shc8bv2k.js +2 -0
  376. package/web/chunk-shc8bv2k.js.br +0 -0
  377. package/web/chunk-shc8bv2k.js.gz +0 -0
  378. package/web/chunk-stnwzrqv.js +98 -0
  379. package/web/chunk-stnwzrqv.js.br +0 -0
  380. package/web/chunk-stnwzrqv.js.gz +0 -0
  381. package/web/chunk-sy28z9pe.js +2 -0
  382. package/web/chunk-sy28z9pe.js.br +2 -0
  383. package/web/chunk-sy28z9pe.js.gz +0 -0
  384. package/web/chunk-t60hp0qs.js +36 -0
  385. package/web/chunk-t60hp0qs.js.br +0 -0
  386. package/web/chunk-t60hp0qs.js.gz +0 -0
  387. package/web/chunk-t9twwgfe.js +1 -0
  388. package/web/chunk-t9twwgfe.js.br +0 -0
  389. package/web/chunk-t9twwgfe.js.gz +0 -0
  390. package/web/chunk-tbgavq0t.js +2 -0
  391. package/web/chunk-tbgavq0t.js.br +0 -0
  392. package/web/chunk-tbgavq0t.js.gz +0 -0
  393. package/web/chunk-tjma3e4d.js +7 -0
  394. package/web/chunk-tjma3e4d.js.br +0 -0
  395. package/web/chunk-tjma3e4d.js.gz +0 -0
  396. package/web/chunk-tn39vbcz.js +2 -0
  397. package/web/chunk-tn39vbcz.js.br +0 -0
  398. package/web/chunk-tn39vbcz.js.gz +0 -0
  399. package/web/chunk-tv9rz73h.js +30 -0
  400. package/web/chunk-tv9rz73h.js.br +0 -0
  401. package/web/chunk-tv9rz73h.js.gz +0 -0
  402. package/web/chunk-twgzayjk.js +1 -0
  403. package/web/chunk-twgzayjk.js.br +0 -0
  404. package/web/chunk-twgzayjk.js.gz +0 -0
  405. package/web/chunk-tz4w2nh2.js +303 -0
  406. package/web/chunk-tz4w2nh2.js.br +0 -0
  407. package/web/chunk-tz4w2nh2.js.gz +0 -0
  408. package/web/chunk-v0egh6d3.js +1 -0
  409. package/web/chunk-v0egh6d3.js.br +0 -0
  410. package/web/chunk-v0egh6d3.js.gz +0 -0
  411. package/web/chunk-vcawg8d2.js +1 -0
  412. package/web/chunk-vcawg8d2.js.br +0 -0
  413. package/web/chunk-vcawg8d2.js.gz +0 -0
  414. package/web/chunk-vh8s2rek.js +1 -0
  415. package/web/chunk-vh8s2rek.js.br +2 -0
  416. package/web/chunk-vh8s2rek.js.gz +0 -0
  417. package/web/chunk-vns6bpqm.js +2 -0
  418. package/web/chunk-vns6bpqm.js.br +0 -0
  419. package/web/chunk-vns6bpqm.js.gz +0 -0
  420. package/web/chunk-vvbte0a5.css +1 -0
  421. package/web/chunk-vvbte0a5.css.br +0 -0
  422. package/web/chunk-vvbte0a5.css.gz +0 -0
  423. package/web/chunk-vxzw2t1r.js +1 -0
  424. package/web/chunk-vxzw2t1r.js.br +0 -0
  425. package/web/chunk-vxzw2t1r.js.gz +0 -0
  426. package/web/chunk-w40atygt.js +2 -0
  427. package/web/chunk-w40atygt.js.br +0 -0
  428. package/web/chunk-w40atygt.js.gz +0 -0
  429. package/web/chunk-w4bxgcwm.js +1 -0
  430. package/web/chunk-w4bxgcwm.js.br +0 -0
  431. package/web/chunk-w4bxgcwm.js.gz +0 -0
  432. package/web/chunk-w5t00pns.js +70 -0
  433. package/web/chunk-w5t00pns.js.br +0 -0
  434. package/web/chunk-w5t00pns.js.gz +0 -0
  435. package/web/chunk-wpmzdqba.js +324 -0
  436. package/web/chunk-wpmzdqba.js.br +0 -0
  437. package/web/chunk-wpmzdqba.js.gz +0 -0
  438. package/web/chunk-x9mexzav.js +2 -0
  439. package/web/chunk-x9mexzav.js.br +0 -0
  440. package/web/chunk-x9mexzav.js.gz +0 -0
  441. package/web/chunk-xc74f1nj.js +1 -0
  442. package/web/chunk-xc74f1nj.js.br +0 -0
  443. package/web/chunk-xc74f1nj.js.gz +0 -0
  444. package/web/chunk-xs4cyb71.js +1 -0
  445. package/web/chunk-xs4cyb71.js.br +0 -0
  446. package/web/chunk-xs4cyb71.js.gz +0 -0
  447. package/web/chunk-xthg4efe.js +1 -0
  448. package/web/chunk-xthg4efe.js.br +0 -0
  449. package/web/chunk-xthg4efe.js.gz +0 -0
  450. package/web/chunk-y48mj5d7.js +1 -0
  451. package/web/chunk-y48mj5d7.js.br +0 -0
  452. package/web/chunk-y48mj5d7.js.gz +0 -0
  453. package/web/chunk-yet0bbyh.js +1 -0
  454. package/web/chunk-yet0bbyh.js.br +0 -0
  455. package/web/chunk-yet0bbyh.js.gz +0 -0
  456. package/web/chunk-yzcxmqy3.js +1 -0
  457. package/web/chunk-yzcxmqy3.js.br +0 -0
  458. package/web/chunk-yzcxmqy3.js.gz +0 -0
  459. package/web/chunk-z2a9zwwx.js +24 -0
  460. package/web/chunk-z2a9zwwx.js.br +0 -0
  461. package/web/chunk-z2a9zwwx.js.gz +0 -0
  462. package/web/chunk-z8fgdsx5.js +1 -0
  463. package/web/chunk-z8fgdsx5.js.br +0 -0
  464. package/web/chunk-z8fgdsx5.js.gz +0 -0
  465. package/web/chunk-zeyw59b9.js +2 -0
  466. package/web/chunk-zeyw59b9.js.br +0 -0
  467. package/web/chunk-zeyw59b9.js.gz +0 -0
  468. package/web/chunk-zftk5ww7.js +8 -0
  469. package/web/chunk-zftk5ww7.js.br +0 -0
  470. package/web/chunk-zftk5ww7.js.gz +0 -0
  471. package/web/chunk-zmbp3phd.js +2 -0
  472. package/web/chunk-zmbp3phd.js.br +0 -0
  473. package/web/chunk-zmbp3phd.js.gz +0 -0
  474. package/web/chunk-zpxh70dj.js +1 -0
  475. package/web/chunk-zpxh70dj.js.br +0 -0
  476. package/web/chunk-zpxh70dj.js.gz +0 -0
  477. package/web/chunk-zqhdf12s.js +39 -0
  478. package/web/chunk-zqhdf12s.js.br +0 -0
  479. package/web/chunk-zqhdf12s.js.gz +0 -0
  480. package/web/chunk-zr2xst5w.js +1 -0
  481. package/web/chunk-zr2xst5w.js.br +0 -0
  482. package/web/chunk-zr2xst5w.js.gz +0 -0
  483. package/web/index.html +27 -2
  484. package/web/index.html.br +0 -0
  485. package/web/index.html.gz +0 -0
  486. package/web/sw.js +39 -24
  487. package/web/sw.js.br +0 -0
  488. package/web/sw.js.gz +0 -0
  489. package/worker.js +1 -1
  490. package/chunk-01fz0kzx.js +0 -2
  491. package/chunk-06k5mcmy.js +0 -4018
  492. package/chunk-14pg1g7b.js +0 -2
  493. package/chunk-1cvzbvsq.js +0 -2
  494. package/chunk-1pgj58dw.js +0 -20
  495. package/chunk-200cn72d.js +0 -16
  496. package/chunk-2nd8hvf3.js +0 -31
  497. package/chunk-39wsmkd7.js +0 -4
  498. package/chunk-54qc1d5t.js +0 -2
  499. package/chunk-59enxka6.js +0 -50
  500. package/chunk-5fs3331q.js +0 -3
  501. package/chunk-674kjaqz.js +0 -2
  502. package/chunk-6pqsx156.js +0 -12
  503. package/chunk-6rw1ex78.js +0 -2
  504. package/chunk-6vz0znf6.js +0 -8
  505. package/chunk-73z1fv3d.js +0 -9
  506. package/chunk-7dnq7g8f.js +0 -3
  507. package/chunk-7emc0sy7.js +0 -11
  508. package/chunk-7nsrfrmx.js +0 -2
  509. package/chunk-8hxsap9d.js +0 -5
  510. package/chunk-8kmtns4v.js +0 -5
  511. package/chunk-9dy56agy.js +0 -51
  512. package/chunk-9mt2k1a7.js +0 -5
  513. package/chunk-9sq7yxh7.js +0 -12
  514. package/chunk-9x1yprjh.js +0 -2
  515. package/chunk-a5k24aj6.js +0 -3
  516. package/chunk-ades3qy7.js +0 -10
  517. package/chunk-ag642nqs.js +0 -8
  518. package/chunk-aq6xkc1w.js +0 -3
  519. package/chunk-av3zmcd8.js +0 -3
  520. package/chunk-b1hdfsj4.js +0 -25
  521. package/chunk-b5448t3j.js +0 -2
  522. package/chunk-b6rvzkxg.js +0 -3
  523. package/chunk-b8acka7e.js +0 -2
  524. package/chunk-bh680te4.js +0 -2
  525. package/chunk-cb4rvanv.js +0 -2
  526. package/chunk-d6hcvbkh.js +0 -3
  527. package/chunk-dqxks09b.js +0 -3
  528. package/chunk-eg161ep9.js +0 -3
  529. package/chunk-et2s8y6a.js +0 -3
  530. package/chunk-exjytvzn.js +0 -2
  531. package/chunk-f6kg68bj.js +0 -3
  532. package/chunk-fcxdq1dy.js +0 -7
  533. package/chunk-fkjjadt4.js +0 -3
  534. package/chunk-fr1zvytp.js +0 -7
  535. package/chunk-fx3cc8nr.js +0 -3
  536. package/chunk-j01t6mnq.js +0 -3
  537. package/chunk-j24fq8ss.js +0 -2
  538. package/chunk-j55tyjct.js +0 -2
  539. package/chunk-jn0dhvkp.js +0 -2
  540. package/chunk-k9dw37w2.js +0 -3
  541. package/chunk-m6bm0739.js +0 -2
  542. package/chunk-mkfdzt82.js +0 -2
  543. package/chunk-nbm1tqvg.js +0 -3
  544. package/chunk-p5ga5as0.js +0 -25
  545. package/chunk-pmefr1ak.js +0 -490
  546. package/chunk-rf6t7zeb.js +0 -286
  547. package/chunk-s0ne3yb9.js +0 -2
  548. package/chunk-s8ybq82n.js +0 -5
  549. package/chunk-spv39wem.js +0 -7
  550. package/chunk-stgqqm7m.js +0 -59
  551. package/chunk-sykaz5bf.js +0 -18
  552. package/chunk-sz0jywpb.js +0 -39
  553. package/chunk-vcngwaee.js +0 -3
  554. package/chunk-vpvznxf4.js +0 -3
  555. package/chunk-vzh6e5f2.js +0 -2
  556. package/chunk-wkvrtjtc.js +0 -2
  557. package/chunk-wzd9b2qk.js +0 -2
  558. package/chunk-x1cva1gc.js +0 -2
  559. package/chunk-x83jcg3x.js +0 -3
  560. package/chunk-xdyee71m.js +0 -10
  561. package/chunk-xdygdssk.js +0 -3
  562. package/chunk-xjcg6cxc.js +0 -3
  563. package/chunk-xran6f0c.js +0 -2
  564. package/chunk-ymn1s2xs.js +0 -3
  565. package/chunk-ysqx0ye8.js +0 -2
  566. package/chunk-z58jafcm.js +0 -3
  567. package/chunk-zf1c6rj7.js +0 -63
  568. package/chunk-zgtahh10.js +0 -44
  569. package/web/chunk-0nt1mz09.js +0 -1
  570. package/web/chunk-0nt1mz09.js.br +0 -0
  571. package/web/chunk-0nt1mz09.js.gz +0 -0
  572. package/web/chunk-0yye7ex1.js +0 -1
  573. package/web/chunk-0yye7ex1.js.br +0 -0
  574. package/web/chunk-0yye7ex1.js.gz +0 -0
  575. package/web/chunk-1hmw1eaw.js +0 -1
  576. package/web/chunk-1hmw1eaw.js.br +0 -0
  577. package/web/chunk-1hmw1eaw.js.gz +0 -0
  578. package/web/chunk-20gcnbgn.js +0 -2
  579. package/web/chunk-20gcnbgn.js.br +0 -0
  580. package/web/chunk-20gcnbgn.js.gz +0 -0
  581. package/web/chunk-2nwvdqxm.js +0 -1
  582. package/web/chunk-2nwvdqxm.js.br +0 -0
  583. package/web/chunk-2nwvdqxm.js.gz +0 -0
  584. package/web/chunk-2wvgy7f4.js +0 -1
  585. package/web/chunk-2wvgy7f4.js.br +0 -0
  586. package/web/chunk-2wvgy7f4.js.gz +0 -0
  587. package/web/chunk-368znnfs.js +0 -1
  588. package/web/chunk-368znnfs.js.br +0 -0
  589. package/web/chunk-368znnfs.js.gz +0 -0
  590. package/web/chunk-3tx9tqfb.js +0 -291
  591. package/web/chunk-3tx9tqfb.js.br +0 -0
  592. package/web/chunk-3tx9tqfb.js.gz +0 -0
  593. package/web/chunk-414npx47.js +0 -1
  594. package/web/chunk-414npx47.js.br +0 -0
  595. package/web/chunk-414npx47.js.gz +0 -0
  596. package/web/chunk-46ht4dh6.js +0 -24
  597. package/web/chunk-46ht4dh6.js.br +0 -0
  598. package/web/chunk-46ht4dh6.js.gz +0 -0
  599. package/web/chunk-4c418rk9.js +0 -1
  600. package/web/chunk-4c418rk9.js.br +0 -2
  601. package/web/chunk-4c418rk9.js.gz +0 -0
  602. package/web/chunk-4p0sm8e7.js +0 -7
  603. package/web/chunk-4p0sm8e7.js.br +0 -0
  604. package/web/chunk-4p0sm8e7.js.gz +0 -0
  605. package/web/chunk-4zam960g.js +0 -1
  606. package/web/chunk-4zam960g.js.br +0 -0
  607. package/web/chunk-4zam960g.js.gz +0 -0
  608. package/web/chunk-5h63t21g.js +0 -1
  609. package/web/chunk-5h63t21g.js.br +0 -0
  610. package/web/chunk-5h63t21g.js.gz +0 -0
  611. package/web/chunk-5h7xm5mn.js +0 -1
  612. package/web/chunk-5h7xm5mn.js.br +0 -0
  613. package/web/chunk-5h7xm5mn.js.gz +0 -0
  614. package/web/chunk-6crex674.js +0 -89
  615. package/web/chunk-6crex674.js.br +0 -0
  616. package/web/chunk-6crex674.js.gz +0 -0
  617. package/web/chunk-6v031vc6.js +0 -21
  618. package/web/chunk-6v031vc6.js.br +0 -0
  619. package/web/chunk-6v031vc6.js.gz +0 -0
  620. package/web/chunk-782gfmtk.js +0 -38
  621. package/web/chunk-782gfmtk.js.br +0 -0
  622. package/web/chunk-782gfmtk.js.gz +0 -0
  623. package/web/chunk-7a6szg06.js +0 -2
  624. package/web/chunk-7a6szg06.js.br +0 -0
  625. package/web/chunk-7a6szg06.js.gz +0 -0
  626. package/web/chunk-7dvbxn34.js +0 -4
  627. package/web/chunk-7dvbxn34.js.br +0 -0
  628. package/web/chunk-7dvbxn34.js.gz +0 -0
  629. package/web/chunk-7g795nba.js +0 -1
  630. package/web/chunk-7g795nba.js.br +0 -2
  631. package/web/chunk-7g795nba.js.gz +0 -0
  632. package/web/chunk-8fymhvne.js +0 -1
  633. package/web/chunk-8fymhvne.js.br +0 -0
  634. package/web/chunk-8fymhvne.js.gz +0 -0
  635. package/web/chunk-8kcp1h63.js +0 -1
  636. package/web/chunk-8kcp1h63.js.br +0 -0
  637. package/web/chunk-8kcp1h63.js.gz +0 -0
  638. package/web/chunk-8vtr60yn.js +0 -2
  639. package/web/chunk-8vtr60yn.js.br +0 -0
  640. package/web/chunk-8vtr60yn.js.gz +0 -0
  641. package/web/chunk-8y14zggg.js +0 -2
  642. package/web/chunk-8y14zggg.js.br +0 -0
  643. package/web/chunk-8y14zggg.js.gz +0 -0
  644. package/web/chunk-8zg840m3.js +0 -1
  645. package/web/chunk-8zg840m3.js.br +0 -0
  646. package/web/chunk-8zg840m3.js.gz +0 -0
  647. package/web/chunk-940sc4ny.js +0 -7
  648. package/web/chunk-940sc4ny.js.br +0 -0
  649. package/web/chunk-940sc4ny.js.gz +0 -0
  650. package/web/chunk-94f4sz0m.js +0 -1
  651. package/web/chunk-94f4sz0m.js.br +0 -0
  652. package/web/chunk-94f4sz0m.js.gz +0 -0
  653. package/web/chunk-94jy9s3n.js +0 -55
  654. package/web/chunk-94jy9s3n.js.br +0 -0
  655. package/web/chunk-94jy9s3n.js.gz +0 -0
  656. package/web/chunk-97qfkg6n.js +0 -30
  657. package/web/chunk-97qfkg6n.js.br +0 -0
  658. package/web/chunk-97qfkg6n.js.gz +0 -0
  659. package/web/chunk-99c0h3v7.js +0 -1
  660. package/web/chunk-99c0h3v7.js.br +0 -0
  661. package/web/chunk-99c0h3v7.js.gz +0 -0
  662. package/web/chunk-99mgkmjb.js +0 -62
  663. package/web/chunk-99mgkmjb.js.br +0 -0
  664. package/web/chunk-99mgkmjb.js.gz +0 -0
  665. package/web/chunk-9afn27bs.js +0 -1
  666. package/web/chunk-9afn27bs.js.br +0 -2
  667. package/web/chunk-9afn27bs.js.gz +0 -0
  668. package/web/chunk-aan5qk6x.js +0 -1
  669. package/web/chunk-aan5qk6x.js.br +0 -0
  670. package/web/chunk-aan5qk6x.js.gz +0 -0
  671. package/web/chunk-aw4h94zp.js +0 -1
  672. package/web/chunk-aw4h94zp.js.br +0 -0
  673. package/web/chunk-aw4h94zp.js.gz +0 -0
  674. package/web/chunk-azdhgj11.js +0 -40
  675. package/web/chunk-azdhgj11.js.br +0 -0
  676. package/web/chunk-azdhgj11.js.gz +0 -0
  677. package/web/chunk-batey85v.js +0 -2
  678. package/web/chunk-batey85v.js.br +0 -0
  679. package/web/chunk-batey85v.js.gz +0 -0
  680. package/web/chunk-brbxfap5.js +0 -99
  681. package/web/chunk-brbxfap5.js.br +0 -0
  682. package/web/chunk-brbxfap5.js.gz +0 -0
  683. package/web/chunk-bxc8a663.js +0 -2
  684. package/web/chunk-bxc8a663.js.br +0 -0
  685. package/web/chunk-bxc8a663.js.gz +0 -0
  686. package/web/chunk-c2t7zyge.js +0 -169
  687. package/web/chunk-c2t7zyge.js.br +0 -0
  688. package/web/chunk-c2t7zyge.js.gz +0 -0
  689. package/web/chunk-c5bfa3rp.js +0 -1
  690. package/web/chunk-c5bfa3rp.js.br +0 -0
  691. package/web/chunk-c5bfa3rp.js.gz +0 -0
  692. package/web/chunk-c86a6am5.js +0 -2
  693. package/web/chunk-c86a6am5.js.br +0 -3
  694. package/web/chunk-c86a6am5.js.gz +0 -0
  695. package/web/chunk-d5n2yz4e.js +0 -2
  696. package/web/chunk-d5n2yz4e.js.br +0 -0
  697. package/web/chunk-d5n2yz4e.js.gz +0 -0
  698. package/web/chunk-dgtp38mj.js +0 -1
  699. package/web/chunk-dgtp38mj.js.br +0 -0
  700. package/web/chunk-dgtp38mj.js.gz +0 -0
  701. package/web/chunk-e4cwyn1g.js +0 -2
  702. package/web/chunk-e4cwyn1g.js.br +0 -0
  703. package/web/chunk-e4cwyn1g.js.gz +0 -0
  704. package/web/chunk-e4h4dg4y.js +0 -303
  705. package/web/chunk-e4h4dg4y.js.br +0 -0
  706. package/web/chunk-e4h4dg4y.js.gz +0 -0
  707. package/web/chunk-e5f8e2ta.js +0 -1
  708. package/web/chunk-e5f8e2ta.js.br +0 -0
  709. package/web/chunk-e5f8e2ta.js.gz +0 -0
  710. package/web/chunk-e7rwnv7e.js +0 -1
  711. package/web/chunk-e7rwnv7e.js.br +0 -0
  712. package/web/chunk-e7rwnv7e.js.gz +0 -0
  713. package/web/chunk-ef9tqrz4.js +0 -324
  714. package/web/chunk-ef9tqrz4.js.br +0 -0
  715. package/web/chunk-ef9tqrz4.js.gz +0 -0
  716. package/web/chunk-efjc9mga.js +0 -2
  717. package/web/chunk-efjc9mga.js.br +0 -0
  718. package/web/chunk-efjc9mga.js.gz +0 -0
  719. package/web/chunk-ekcnhcm0.js +0 -1
  720. package/web/chunk-ekcnhcm0.js.br +0 -0
  721. package/web/chunk-ekcnhcm0.js.gz +0 -0
  722. package/web/chunk-ekkdhece.js +0 -41
  723. package/web/chunk-ekkdhece.js.br +0 -0
  724. package/web/chunk-ekkdhece.js.gz +0 -0
  725. package/web/chunk-enbqe508.js +0 -36
  726. package/web/chunk-enbqe508.js.br +0 -0
  727. package/web/chunk-enbqe508.js.gz +0 -0
  728. package/web/chunk-ev517x0c.js +0 -1
  729. package/web/chunk-ev517x0c.js.br +0 -0
  730. package/web/chunk-ev517x0c.js.gz +0 -0
  731. package/web/chunk-ex47jeev.js +0 -1
  732. package/web/chunk-ex47jeev.js.br +0 -0
  733. package/web/chunk-ex47jeev.js.gz +0 -0
  734. package/web/chunk-f5wyg9zh.js +0 -2
  735. package/web/chunk-f5wyg9zh.js.br +0 -0
  736. package/web/chunk-f5wyg9zh.js.gz +0 -0
  737. package/web/chunk-ft9p7cr8.js +0 -8
  738. package/web/chunk-ft9p7cr8.js.br +0 -0
  739. package/web/chunk-ft9p7cr8.js.gz +0 -0
  740. package/web/chunk-ftdzs90e.js +0 -1
  741. package/web/chunk-ftdzs90e.js.br +0 -0
  742. package/web/chunk-ftdzs90e.js.gz +0 -0
  743. package/web/chunk-fybmc8p1.js +0 -1
  744. package/web/chunk-fybmc8p1.js.br +0 -0
  745. package/web/chunk-fybmc8p1.js.gz +0 -0
  746. package/web/chunk-g6e50kx0.js +0 -3
  747. package/web/chunk-g6e50kx0.js.br +0 -0
  748. package/web/chunk-g6e50kx0.js.gz +0 -0
  749. package/web/chunk-g6grehr5.css +0 -1
  750. package/web/chunk-g6grehr5.css.br +0 -0
  751. package/web/chunk-g6grehr5.css.gz +0 -0
  752. package/web/chunk-gbzfq3rg.js +0 -332
  753. package/web/chunk-gbzfq3rg.js.br +0 -0
  754. package/web/chunk-gbzfq3rg.js.gz +0 -0
  755. package/web/chunk-gsg8yq3m.js +0 -1
  756. package/web/chunk-gsg8yq3m.js.br +0 -0
  757. package/web/chunk-gsg8yq3m.js.gz +0 -0
  758. package/web/chunk-gvndjaan.js +0 -2
  759. package/web/chunk-gvndjaan.js.br +0 -0
  760. package/web/chunk-gvndjaan.js.gz +0 -0
  761. package/web/chunk-hgcgbxns.js +0 -1
  762. package/web/chunk-hgcgbxns.js.br +0 -0
  763. package/web/chunk-hgcgbxns.js.gz +0 -0
  764. package/web/chunk-hh8ck7sy.js +0 -2
  765. package/web/chunk-hh8ck7sy.js.br +0 -0
  766. package/web/chunk-hh8ck7sy.js.gz +0 -0
  767. package/web/chunk-hj18pw9f.js +0 -2
  768. package/web/chunk-hj18pw9f.js.br +0 -0
  769. package/web/chunk-hj18pw9f.js.gz +0 -0
  770. package/web/chunk-hk4jd2qq.js +0 -24
  771. package/web/chunk-hk4jd2qq.js.br +0 -0
  772. package/web/chunk-hk4jd2qq.js.gz +0 -0
  773. package/web/chunk-hrnx1576.js +0 -4
  774. package/web/chunk-hrnx1576.js.br +0 -0
  775. package/web/chunk-hrnx1576.js.gz +0 -0
  776. package/web/chunk-hzvff525.js +0 -2
  777. package/web/chunk-hzvff525.js.br +0 -0
  778. package/web/chunk-hzvff525.js.gz +0 -0
  779. package/web/chunk-j0ns5dyq.js +0 -120
  780. package/web/chunk-j0ns5dyq.js.br +0 -0
  781. package/web/chunk-j0ns5dyq.js.gz +0 -0
  782. package/web/chunk-j21a7pd1.js +0 -1
  783. package/web/chunk-j21a7pd1.js.br +0 -0
  784. package/web/chunk-j21a7pd1.js.gz +0 -0
  785. package/web/chunk-jbejy8k3.js +0 -1139
  786. package/web/chunk-jbejy8k3.js.br +0 -0
  787. package/web/chunk-jbejy8k3.js.gz +0 -0
  788. package/web/chunk-jeq99z4t.js +0 -70
  789. package/web/chunk-jeq99z4t.js.br +0 -0
  790. package/web/chunk-jeq99z4t.js.gz +0 -0
  791. package/web/chunk-jqq07zta.js +0 -1
  792. package/web/chunk-jqq07zta.js.br +0 -0
  793. package/web/chunk-jqq07zta.js.gz +0 -0
  794. package/web/chunk-k6m37v6k.js +0 -1
  795. package/web/chunk-k6m37v6k.js.br +0 -0
  796. package/web/chunk-k6m37v6k.js.gz +0 -0
  797. package/web/chunk-kajk2w5j.js +0 -217
  798. package/web/chunk-kajk2w5j.js.br +0 -0
  799. package/web/chunk-kajk2w5j.js.gz +0 -0
  800. package/web/chunk-kcrypnnf.js +0 -1
  801. package/web/chunk-kcrypnnf.js.br +0 -0
  802. package/web/chunk-kcrypnnf.js.gz +0 -0
  803. package/web/chunk-kyksv8an.js +0 -1
  804. package/web/chunk-kyksv8an.js.br +0 -2
  805. package/web/chunk-kyksv8an.js.gz +0 -0
  806. package/web/chunk-mkhcq6z6.js +0 -1
  807. package/web/chunk-mkhcq6z6.js.br +0 -0
  808. package/web/chunk-mkhcq6z6.js.gz +0 -0
  809. package/web/chunk-mqdvg55y.js +0 -2
  810. package/web/chunk-mqdvg55y.js.br +0 -0
  811. package/web/chunk-mqdvg55y.js.gz +0 -0
  812. package/web/chunk-mytypet0.js +0 -2
  813. package/web/chunk-mytypet0.js.br +0 -0
  814. package/web/chunk-mytypet0.js.gz +0 -0
  815. package/web/chunk-mzb086jr.js +0 -1
  816. package/web/chunk-mzb086jr.js.br +0 -0
  817. package/web/chunk-mzb086jr.js.gz +0 -0
  818. package/web/chunk-mzevfdmp.js +0 -1
  819. package/web/chunk-mzevfdmp.js.br +0 -0
  820. package/web/chunk-mzevfdmp.js.gz +0 -0
  821. package/web/chunk-n7c5sndg.js +0 -1
  822. package/web/chunk-n7c5sndg.js.br +0 -0
  823. package/web/chunk-n7c5sndg.js.gz +0 -0
  824. package/web/chunk-ned200k0.js +0 -84
  825. package/web/chunk-ned200k0.js.br +0 -0
  826. package/web/chunk-ned200k0.js.gz +0 -0
  827. package/web/chunk-ngcd5a3c.js +0 -1
  828. package/web/chunk-ngcd5a3c.js.br +0 -0
  829. package/web/chunk-ngcd5a3c.js.gz +0 -0
  830. package/web/chunk-ngsv0xfb.js +0 -1
  831. package/web/chunk-ngsv0xfb.js.br +0 -0
  832. package/web/chunk-ngsv0xfb.js.gz +0 -0
  833. package/web/chunk-nx14h1a6.js +0 -1
  834. package/web/chunk-nx14h1a6.js.br +0 -0
  835. package/web/chunk-nx14h1a6.js.gz +0 -0
  836. package/web/chunk-p3fv7nbz.js +0 -1
  837. package/web/chunk-p3fv7nbz.js.br +0 -0
  838. package/web/chunk-p3fv7nbz.js.gz +0 -0
  839. package/web/chunk-pktgtyf6.js +0 -1
  840. package/web/chunk-pktgtyf6.js.br +0 -0
  841. package/web/chunk-pktgtyf6.js.gz +0 -0
  842. package/web/chunk-pm504vps.js +0 -89
  843. package/web/chunk-pm504vps.js.br +0 -0
  844. package/web/chunk-pm504vps.js.gz +0 -0
  845. package/web/chunk-pnvkphs0.js +0 -12
  846. package/web/chunk-pnvkphs0.js.br +0 -0
  847. package/web/chunk-pnvkphs0.js.gz +0 -0
  848. package/web/chunk-ptvshaa0.js +0 -2
  849. package/web/chunk-ptvshaa0.js.br +0 -0
  850. package/web/chunk-ptvshaa0.js.gz +0 -0
  851. package/web/chunk-py4737sc.js +0 -39
  852. package/web/chunk-py4737sc.js.br +0 -0
  853. package/web/chunk-py4737sc.js.gz +0 -0
  854. package/web/chunk-pz5wcbdv.js +0 -139
  855. package/web/chunk-pz5wcbdv.js.br +0 -0
  856. package/web/chunk-pz5wcbdv.js.gz +0 -0
  857. package/web/chunk-q467b529.js +0 -1
  858. package/web/chunk-q467b529.js.br +0 -0
  859. package/web/chunk-q467b529.js.gz +0 -0
  860. package/web/chunk-qbvbfpx8.js +0 -1
  861. package/web/chunk-qbvbfpx8.js.br +0 -0
  862. package/web/chunk-qbvbfpx8.js.gz +0 -0
  863. package/web/chunk-qgfc4ptt.js +0 -7
  864. package/web/chunk-qgfc4ptt.js.br +0 -0
  865. package/web/chunk-qgfc4ptt.js.gz +0 -0
  866. package/web/chunk-qmmss130.js +0 -2
  867. package/web/chunk-qmmss130.js.br +0 -0
  868. package/web/chunk-qmmss130.js.gz +0 -0
  869. package/web/chunk-qqrzr444.js +0 -2
  870. package/web/chunk-qqrzr444.js.br +0 -0
  871. package/web/chunk-qqrzr444.js.gz +0 -0
  872. package/web/chunk-r2fjprkk.js +0 -1
  873. package/web/chunk-r2fjprkk.js.br +0 -0
  874. package/web/chunk-r2fjprkk.js.gz +0 -0
  875. package/web/chunk-rcn21n5e.js +0 -214
  876. package/web/chunk-rcn21n5e.js.br +0 -0
  877. package/web/chunk-rcn21n5e.js.gz +0 -0
  878. package/web/chunk-rj1rp0tc.js +0 -1
  879. package/web/chunk-rj1rp0tc.js.br +0 -0
  880. package/web/chunk-rj1rp0tc.js.gz +0 -0
  881. package/web/chunk-rpnw9xwe.js +0 -1
  882. package/web/chunk-rpnw9xwe.js.br +0 -0
  883. package/web/chunk-rpnw9xwe.js.gz +0 -0
  884. package/web/chunk-rv5h4d8w.js +0 -1
  885. package/web/chunk-rv5h4d8w.js.br +0 -0
  886. package/web/chunk-rv5h4d8w.js.gz +0 -0
  887. package/web/chunk-s00gxcxn.js +0 -2
  888. package/web/chunk-s00gxcxn.js.br +0 -0
  889. package/web/chunk-s00gxcxn.js.gz +0 -0
  890. package/web/chunk-s8e8gzvn.js +0 -16
  891. package/web/chunk-s8e8gzvn.js.br +0 -0
  892. package/web/chunk-s8e8gzvn.js.gz +0 -0
  893. package/web/chunk-sa57mndb.js +0 -1
  894. package/web/chunk-sa57mndb.js.br +0 -0
  895. package/web/chunk-sa57mndb.js.gz +0 -0
  896. package/web/chunk-sc90h9bd.js +0 -2
  897. package/web/chunk-sc90h9bd.js.br +0 -0
  898. package/web/chunk-sc90h9bd.js.gz +0 -0
  899. package/web/chunk-t44qa4yt.js +0 -200
  900. package/web/chunk-t44qa4yt.js.br +0 -0
  901. package/web/chunk-t44qa4yt.js.gz +0 -0
  902. package/web/chunk-t8b8cdak.js +0 -2
  903. package/web/chunk-t8b8cdak.js.br +0 -0
  904. package/web/chunk-t8b8cdak.js.gz +0 -0
  905. package/web/chunk-t9cgbcf2.js +0 -1
  906. package/web/chunk-t9cgbcf2.js.br +0 -0
  907. package/web/chunk-t9cgbcf2.js.gz +0 -0
  908. package/web/chunk-tk8kf0bf.js +0 -2
  909. package/web/chunk-tk8kf0bf.js.br +0 -0
  910. package/web/chunk-tk8kf0bf.js.gz +0 -0
  911. package/web/chunk-tntwwpyh.js +0 -2
  912. package/web/chunk-tntwwpyh.js.br +0 -0
  913. package/web/chunk-tntwwpyh.js.gz +0 -0
  914. package/web/chunk-tt3v857c.js +0 -106
  915. package/web/chunk-tt3v857c.js.br +0 -0
  916. package/web/chunk-tt3v857c.js.gz +0 -0
  917. package/web/chunk-vjnmqaam.js +0 -2
  918. package/web/chunk-vjnmqaam.js.br +0 -0
  919. package/web/chunk-vjnmqaam.js.gz +0 -0
  920. package/web/chunk-vndrjeyr.js +0 -2
  921. package/web/chunk-vndrjeyr.js.br +0 -0
  922. package/web/chunk-vndrjeyr.js.gz +0 -0
  923. package/web/chunk-vp5qf59s.js +0 -1
  924. package/web/chunk-vp5qf59s.js.br +0 -0
  925. package/web/chunk-vp5qf59s.js.gz +0 -0
  926. package/web/chunk-wdd9pasx.js +0 -1
  927. package/web/chunk-wdd9pasx.js.br +0 -0
  928. package/web/chunk-wdd9pasx.js.gz +0 -0
  929. package/web/chunk-wrax5wt5.js +0 -292
  930. package/web/chunk-wrax5wt5.js.br +0 -0
  931. package/web/chunk-wrax5wt5.js.gz +0 -0
  932. package/web/chunk-yarejzzs.js +0 -142
  933. package/web/chunk-yarejzzs.js.br +0 -0
  934. package/web/chunk-yarejzzs.js.gz +0 -0
  935. package/web/chunk-yg6ys554.js +0 -1
  936. package/web/chunk-yg6ys554.js.br +0 -0
  937. package/web/chunk-yg6ys554.js.gz +0 -0
  938. package/web/chunk-yq6xkb5w.js +0 -370
  939. package/web/chunk-yq6xkb5w.js.br +0 -0
  940. package/web/chunk-yq6xkb5w.js.gz +0 -0
  941. package/web/chunk-yw98mr7e.js +0 -2
  942. package/web/chunk-yw98mr7e.js.br +0 -0
  943. package/web/chunk-yw98mr7e.js.gz +0 -0
  944. package/web/chunk-z07kf12w.js +0 -78
  945. package/web/chunk-z07kf12w.js.br +0 -0
  946. package/web/chunk-z07kf12w.js.gz +0 -0
  947. package/web/chunk-z5sk390b.js +0 -2
  948. package/web/chunk-z5sk390b.js.br +0 -0
  949. package/web/chunk-z5sk390b.js.gz +0 -0
  950. package/web/chunk-zh2szkjy.js +0 -140
  951. package/web/chunk-zh2szkjy.js.br +0 -0
  952. package/web/chunk-zh2szkjy.js.gz +0 -0
  953. package/web/chunk-zrmm67mx.js +0 -34
  954. package/web/chunk-zrmm67mx.js.br +0 -0
  955. package/web/chunk-zrmm67mx.js.gz +0 -0
  956. package/web/chunk-zyfr25n1.js +0 -98
  957. package/web/chunk-zyfr25n1.js.br +0 -0
  958. package/web/chunk-zyfr25n1.js.gz +0 -0
  959. package/web/chunk-zykkmwba.js +0 -2
  960. package/web/chunk-zykkmwba.js.br +0 -0
  961. package/web/chunk-zykkmwba.js.gz +0 -0
  962. package/web/chunk-zzs4h31m.js +0 -2
  963. package/web/chunk-zzs4h31m.js.br +0 -0
  964. package/web/chunk-zzs4h31m.js.gz +0 -0
@@ -0,0 +1,25 @@
1
+ // @bun
2
+ import{Database as g}from"bun:sqlite";import{chmodSync as B,closeSync as H,existsSync as R,openSync as W,rmSync as G}from"fs";var V=2,X=2,ks="basalt-search.db",yt=0,Zt=1;function h(e){let t=new g(":memory:");try{for(let r of e)t.run(r);return!0}catch{return!1}finally{t.close()}}var T;function Ps(){if(T)return T;let e=h(["CREATE VIRTUAL TABLE f USING fts5(text)"]),t=e&&h(["CREATE VIRTUAL TABLE f USING fts5(text, tokenize='trigram')"]);return T={fts5:e,trigram:t,trigramDiacritics:t&&h(["CREATE VIRTUAL TABLE f USING fts5(text, tokenize='trigram remove_diacritics 1')"]),contentlessDelete:e&&h(["CREATE VIRTUAL TABLE f USING fts5(text, content='', contentless_delete=1)","INSERT INTO f (rowid, text) VALUES (1, 'probe')","DELETE FROM f WHERE rowid = 1"]),secureDelete:e&&h(["CREATE VIRTUAL TABLE f USING fts5(text)","INSERT INTO f (f, rank) VALUES ('secure-delete', 1)"])},T}function P(e){return{msg:e.trigram?"trigram":"unicode61",contentless:e.contentlessDelete}}function O(e){return JSON.stringify({schema:V,extractor:X,...e})}function k(e,t){return`text, ${e.contentless?"content='', contentless_delete=1, ":""}detail=full, tokenize="${t}"`}function Y(e,t,r){let n=r.msg==="trigram"?t.trigramDiacritics?"trigram remove_diacritics 1":"trigram":"unicode61 remove_diacritics 2";e.transaction(()=>{if(e.run("CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v) WITHOUT ROWID"),e.run(`CREATE TABLE IF NOT EXISTS doc (
3
+ id INTEGER PRIMARY KEY,
4
+ hash INTEGER NOT NULL UNIQUE,
5
+ refs INTEGER NOT NULL,
6
+ len INTEGER NOT NULL,
7
+ bulk INTEGER NOT NULL
8
+ )`),e.run(`CREATE TABLE IF NOT EXISTS ref (
9
+ session_id TEXT NOT NULL,
10
+ seq INTEGER NOT NULL,
11
+ part INTEGER NOT NULL,
12
+ doc INTEGER NOT NULL,
13
+ kind INTEGER NOT NULL,
14
+ tool TEXT,
15
+ err INTEGER NOT NULL DEFAULT 0,
16
+ model TEXT,
17
+ time INTEGER NOT NULL,
18
+ PRIMARY KEY (session_id, seq, part)
19
+ ) WITHOUT ROWID`),e.run("CREATE INDEX IF NOT EXISTS ref_doc ON ref(doc,time,kind,tool,err,model)"),e.run("CREATE INDEX IF NOT EXISTS ref_time ON ref(time,session_id,seq,part,doc,kind,tool,err,model)"),e.run("CREATE TABLE IF NOT EXISTS term (t TEXT PRIMARY KEY, n INTEGER NOT NULL) WITHOUT ROWID"),e.run("CREATE TABLE IF NOT EXISTS evicted (session_id TEXT PRIMARY KEY) WITHOUT ROWID"),e.run("CREATE TABLE IF NOT EXISTS backfill_todo (ord INTEGER PRIMARY KEY, session_id TEXT NOT NULL)"),e.run(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(${k(r,n)})`),e.run(`CREATE VIRTUAL TABLE IF NOT EXISTS fts_out USING fts5(${k(r,"unicode61 remove_diacritics 2")})`),e.run("CREATE VIRTUAL TABLE IF NOT EXISTS fts_vocab USING fts5vocab(fts, 'row')"),e.run("CREATE VIRTUAL TABLE IF NOT EXISTS fts_out_vocab USING fts5vocab(fts_out, 'row')"),t.secureDelete)e.run("INSERT INTO fts (fts, rank) VALUES ('secure-delete', 1)"),e.run("INSERT INTO fts_out (fts_out, rank) VALUES ('secure-delete', 1)");e.query("INSERT OR REPLACE INTO meta (k, v) VALUES ('fingerprint', ?)").run(O(r)),e.query("INSERT OR REPLACE INTO meta (k, v) VALUES ('layout', ?)").run(JSON.stringify(r))})()}function Ti(e){for(let t of["","-wal","-shm","-journal"])G(e+t,{force:!0})}function z(e){for(let t of["","-wal","-shm"])if(R(e+t))B(e+t,384)}function p(e,t){return e.query("SELECT v FROM main.meta WHERE k = ?").get(t)?.v??void 0}function d(e,t,r){e.query("INSERT OR REPLACE INTO main.meta (k, v) VALUES (?, ?)").run(t,r)}function _(e,t,r){let n=P(r),i=!1;if(R(e)){let o=!1;try{let a=new g(e);try{o=a.query("SELECT v FROM meta WHERE k = 'fingerprint'").get()?.v===O(n)}finally{a.close()}}catch{o=!1}if(!o)Ti(e),i=!0}if(!R(e))H(W(e,"a",384));let s=new g(e,{create:!0,strict:!0});return s.run("PRAGMA journal_mode = WAL"),s.run("PRAGMA synchronous = NORMAL"),s.run("PRAGMA busy_timeout = 5000"),Y(s,r,n),z(e),s.query("ATTACH ? AS store").run(t),{db:s,layout:n,reset:i}}function Cs(e,t){if(!R(e))return;let r;try{return r=new g(e,{readonly:!0,strict:!0}),r.run("PRAGMA busy_timeout = 5000"),r.query("ATTACH ? AS store").run(t),r.query("SELECT v FROM meta WHERE k = 'layout'").get(),r}catch{r?.close();return}}var D="backfill";function b(e){return e.query("SELECT sum((SELECT max(seq) FROM store.entries WHERE session_id = sessions.id)) AS n FROM store.sessions").get()?.n??0}function j(e){let t=p(e,D);return t?JSON.parse(t):void 0}function M(e,t){d(e,D,JSON.stringify(t))}class y{db;indexer;batch;todo;page;state;constructor(e,t,r=500){this.db=e;this.indexer=t;this.batch=r;this.todo=e.query("SELECT session_id FROM main.backfill_todo WHERE ord = ?"),this.page=e.query("SELECT seq, time, body FROM store.entries WHERE session_id = ? AND seq > ? ORDER BY seq LIMIT ?"),this.state=j(e)}get running(){return this.state?.state==="running"}begin(e){this.db.transaction(()=>{let t=this.db.query("SELECT max(id) AS id FROM store.search_queue").get()?.id??0;d(this.db,"queue_done",t),this.db.run("DELETE FROM main.backfill_todo"),this.db.run("INSERT INTO main.backfill_todo (ord, session_id) SELECT row_number() OVER (ORDER BY updated DESC, id), id FROM store.sessions");let r=this.db.query("SELECT count(*) AS n FROM main.backfill_todo").get()?.n??0,n=b(this.db);this.state={state:r?"running":"done",reason:e,ord:1,seq:-1,total:n,sessionsTotal:r,done:0,sessionsDone:0,startedAt:Date.now()},M(this.db,this.state)})()}step(e){let t=this.state;if(t?.state!=="running")return!1;let r={...t};return this.db.transaction(()=>{let n=this.batch;while(n>0&&r.state==="running"){let i=this.todo.get(r.ord)?.session_id;if(i===void 0){r.state="done",this.db.run("DELETE FROM main.backfill_todo");break}if(r.seq<0)this.indexer.reindex(i,0),r.seq=0;let s=this.page.all(i,r.seq,n);for(let o of s)if(this.indexer.indexRow(i,o.seq,o.time,o.body),r.seq=o.seq,r.done++,n--,performance.now()>e){n=0;break}if(n>0)r.ord++,r.seq=-1,r.sessionsDone++;if(performance.now()>e)break}M(this.db,r)})(),this.state=r,!0}}var $a=49152,ja=16384,q=64;function A(e){if(e.length<=65536)return e;return`${e.slice(0,49152)}
20
+ \u2026
21
+ ${e.slice(-16384)}`}var K=/[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]+/g,Z=/[A-Za-z][a-z0-9]*(?:[A-Z][a-z0-9]+)+|[A-Z]{2,}[a-z0-9]+[A-Za-z0-9]*/g,J=/([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])/g;function S(e){return e.replace(K,(t)=>{if(t.length===1)return` ${t} `;let r=[];for(let n=0;n<t.length-1;n++)r.push(t.slice(n,n+2));return` ${r.join(" ")} `}).replace(Z,(t)=>`${t} ${t.replace(J,"$1$3 $2$4")}`)}function w(e){return`${e} `}function er(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]+/g,"").normalize("NFC")}var Q=/[\p{L}\p{N}\p{Co}]+/gu;function Wa(e){return er(S(e)).match(Q)??[]}var Qe={user:1,assistant:2,thinking:3,tool_input:4,tool_output:5,error:6,extension:7,notice:8,attachment:9,title:10},ki=Object.fromEntries(Object.entries(Qe).map(([e,t])=>[t,e])),ee=1e4,te=-1,re=2048;function C(e){return e==="tool_output"||e==="attachment"||e==="thinking"||e==="tool_input"}function I(e,t=[],r=0){if(r>6)return t;if(typeof e==="string")t.push(e);else if(typeof e==="number"||typeof e==="boolean")t.push(String(e));else if(Array.isArray(e))for(let n of e)I(n,t,r+1);else if(e&&typeof e==="object")for(let n of Object.values(e))I(n,t,r+1);return t}function bt(e,t=!1){let r=[];switch(e.type){case"user":{if(typeof e.text==="string")r.push({part:0,kind:e.notices?"notice":"user",text:e.text});(Array.isArray(e.attachments)?e.attachments:[]).forEach((i,s)=>{let o=String(i?.name??""),a=i?.kind==="image"?o:`${o}
22
+ ${String(i?.data??"")}`;r.push({part:1+s,kind:"attachment",text:a})});break}case"notice_pending":if(typeof e.notice?.text==="string")r.push({part:0,kind:"notice",text:e.notice.text});break;case"assistant":{let n=typeof e.model==="string"?e.model:void 0;if((Array.isArray(e.parts)?e.parts:[]).forEach((s,o)=>{if(s?.type==="text"||s?.type==="thinking"){if(typeof s.text==="string")r.push({part:o,kind:s.type==="text"?"assistant":"thinking",text:s.text,model:n})}else if(s?.type==="tool_call"){let a=typeof s.name==="string"?s.name:void 0;if(r.push({part:o,kind:"tool_input",tool:a,model:n,text:[a??"",...I(s.input)].join(`
23
+ `)}),typeof s.output==="string")r.push({part:ee+o,kind:"tool_output",tool:a,model:n,text:s.output})}}),typeof e.error==="string")r.push({part:te,kind:"error",err:!0,model:n,text:e.error});break}case"tool_result":{let n=typeof e.name==="string"?e.name:void 0,i=typeof e.output==="string"?e.output:"",s=e.isError===!0;if(r.push({part:0,kind:"tool_output",tool:n,err:s,text:i}),s)r.push({part:1,kind:"error",tool:n,err:s,text:i.slice(0,re)});break}case"run":if("error"in e&&typeof e.error==="string")r.push({part:0,kind:"error",err:!0,text:e.error});break;case"extension":{let n=e.display;if(n&&typeof n.text==="string")r.push({part:0,kind:"extension",text:`${n.title??""}
24
+ ${n.text}`});break}}if(!t)for(let n of r)n.text=A(n.text);return r.filter((n)=>n.text.trim())}function v(e){return e.trim()?[{part:0,kind:"title",text:A(e)}]:[]}function ne(e,t){return BigInt.asIntN(64,Bun.hash.wyhash(`${e?"B":"M"}${t}`))}class x{db;layout;readEntry;readTitle;previousModel;selectRefs;deleteRefs;insertRef;findDoc;insertDoc;increment;decrement;docRefs;deleteDoc;insertMsg;insertOut;deleteMsg;deleteOut;stats={entries:0,fields:0,bytes:0,newDocs:0,newBytes:0};outChanges=0;constructor(e,t){this.db=e;this.layout=t;this.readEntry=e.query("SELECT time, body FROM store.entries WHERE session_id = ? AND seq = ?"),this.readTitle=e.query("SELECT title, created FROM store.sessions WHERE id = ?"),this.previousModel=e.query("SELECT json_extract(body, '$.model') AS model FROM store.entries WHERE session_id = ? AND seq < ? AND json_extract(body, '$.type') = 'assistant' ORDER BY seq DESC LIMIT 1"),this.selectRefs=e.query("SELECT doc FROM main.ref WHERE session_id = ? AND seq = ?"),this.deleteRefs=e.query("DELETE FROM main.ref WHERE session_id = ? AND seq = ?"),this.insertRef=e.query("INSERT INTO main.ref (session_id, seq, part, doc, kind, tool, err, model, time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"),this.findDoc=e.query("SELECT id FROM main.doc WHERE hash = ?"),this.insertDoc=e.query("INSERT INTO main.doc (hash, refs, len, bulk) VALUES (?, 1, ?, ?)"),this.increment=e.query("UPDATE main.doc SET refs = refs + 1 WHERE id = ?"),this.decrement=e.query("UPDATE main.doc SET refs = refs - 1 WHERE id = ?"),this.docRefs=e.query("SELECT refs, bulk FROM main.doc WHERE id = ?"),this.deleteDoc=e.query("DELETE FROM main.doc WHERE id = ?"),this.insertMsg=e.query("INSERT INTO main.fts (rowid, text) VALUES (?, ?)"),this.insertOut=e.query("INSERT INTO main.fts_out (rowid, text) VALUES (?, ?)"),this.deleteMsg=e.query("DELETE FROM main.fts WHERE rowid = ?"),this.deleteOut=e.query("DELETE FROM main.fts_out WHERE rowid = ?")}reindex(e,t){let r=0,n=[];if(t===0){let i=this.readTitle.get(e);if(i)r=i.created,n=v(i.title)}else{let i=this.readEntry.get(e,t);if(i)r=i.time,n=this.fields(e,t,i.body)}this.apply(e,t,r,n)}indexRow(e,t,r,n){this.apply(e,t,r,this.fields(e,t,n))}fields(e,t,r){let n;try{n=JSON.parse(r)}catch{return[]}if(!n||typeof n!=="object")return[];let i=bt(n);if(n.type==="tool_result"&&i.length){let s=this.previousModel.get(e,t)?.model??void 0;if(s)for(let o of i)o.model=s}return i}apply(e,t,r,n){let i=this.selectRefs.all(e,t);if(i.length)this.deleteRefs.run(e,t);this.stats.entries++;for(let s of n){let o=C(s.kind),a=ne(o,s.text);this.stats.fields++,this.stats.bytes+=s.text.length;let u=this.findDoc.get(a)?.id;if(u===void 0){if(u=Number(this.insertDoc.run(a,s.text.length,o?1:0).lastInsertRowid),o)this.insertOut.run(u,S(s.text)),this.outChanges++;else this.insertMsg.run(u,this.layout.msg==="trigram"?w(s.text):S(s.text));this.stats.newDocs++,this.stats.newBytes+=s.text.length}else this.increment.run(u);this.insertRef.run(e,t,s.part,u,Qe[s.kind],s.tool??null,s.err?1:0,s.model??null,r)}for(let{doc:s}of i)this.release(s)}release(e){this.decrement.run(e);let t=this.docRefs.get(e);if(!t||t.refs>0)return;if(this.deleteDoc.run(e),t.bulk)this.deleteOut.run(e),this.outChanges++;else this.deleteMsg.run(e)}}class N{db;page;clearRange;clearTail;upsert;constructor(e){this.db=e;this.page=e.query("SELECT term, doc FROM main.fts_out_vocab WHERE term > ? ORDER BY term LIMIT ?"),this.clearRange=e.query("DELETE FROM main.term WHERE t > ? AND t <= ?"),this.clearTail=e.query("DELETE FROM main.term WHERE t > ?"),this.upsert=e.query("INSERT OR REPLACE INTO main.term (t, n) VALUES (?, ?)")}step(e,t){let r=this.page.all(e,t),n=r.at(-1)?.term;if(r.length<t||n===void 0)this.clearTail.run(e);else this.clearRange.run(e,n);for(let{term:i,doc:s}of r)if(i.length<=q)this.upsert.run(i,s);return r.length<t?void 0:n}}var se=2000,ie=30000;class Ha{options;db;layout;reset;indexer;backfill;terms;queueRows;queueMax;sliceMs;backfillSliceMs;queueBatch;termRefreshMs;queueDone;termCursor;termStale;lastTermRefresh=Number.NEGATIVE_INFINITY;rateStart;estimate;closed=!1;constructor(e){this.options=e;let t=_(e.indexPath,e.storePath,e.features);if(this.db=t.db,this.layout=t.layout,this.reset=t.reset,this.sliceMs=e.sliceMs??20,this.backfillSliceMs=e.backfillSliceMs??200,this.queueBatch=e.queueBatch??200,this.termRefreshMs=e.termRefreshMs??60000,this.indexer=new x(this.db,this.layout),this.terms=new N(this.db),this.backfill=new y(this.db,this.indexer,e.batch??500),this.queueRows=this.db.query("SELECT id, session_id, seq FROM store.search_queue WHERE id > ? ORDER BY id LIMIT ?"),this.queueMax=this.db.query("SELECT max(id) AS id FROM store.search_queue"),!this.backfill.state)this.backfill.begin(this.reset?"rebuild":"initial");this.queueDone=Number(p(this.db,"queue_done")??0),this.termStale=Number(p(this.db,"term_stale")??0)===1}step(e){if(this.closed)return!1;if(this.drainQueue(e??performance.now()+this.sliceMs))return!0;if(this.backfill.running){this.rateStart??={time:performance.now(),done:this.backfill.state?.done??0};let t=this.indexer.outChanges;if(this.backfill.step(e??performance.now()+this.backfillSliceMs),this.markTerms(t),!this.backfill.running)this.lastTermRefresh=Number.NEGATIVE_INFINITY;return!0}return this.refreshTerms(e??performance.now()+this.sliceMs)}drain(){while(this.step());}drainQueue(e){let t=!1;return this.db.transaction(()=>{let r=this.queueRows.all(this.queueDone,this.queueBatch);if(!r.length)return;t=!0;let n=this.indexer.outChanges,i=new Set,s=this.queueDone;for(let o of r){let a=`${o.seq}\x00${o.session_id}`;if(!i.has(a))i.add(a),this.indexer.reindex(o.session_id,o.seq);if(s=o.id,performance.now()>e)break}d(this.db,"queue_done",s),this.markTerms(n),this.queueDone=s})(),t}markTerms(e){if(this.indexer.outChanges===e||this.termStale)return;this.termStale=!0,d(this.db,"term_stale",1)}refreshTerms(e){if(this.termCursor===void 0){if(!this.termStale||performance.now()-this.lastTermRefresh<this.termRefreshMs)return!1;this.termCursor="",this.termStale=!1,this.indexer.outChanges=0,d(this.db,"term_stale",0)}while(this.termCursor!==void 0&&performance.now()<=e){let t=this.termCursor;this.db.transaction(()=>{this.termCursor=this.terms.step(t,se)})()}if(this.termCursor===void 0)this.lastTermRefresh=performance.now();return!0}status(){let e=this.queueMax.get()?.id??this.queueDone,t=this.backfill.state,r;if(t?.state==="running"&&this.rateStart){let i=(performance.now()-this.rateStart.time)/1000,s=(t.done-this.rateStart.done)/i;if(i>0.5&&s>0)r=Math.max(0,Math.round(Math.max(0,t.total-t.done)/s))}let n=t?{state:t.state,reason:t.reason,total:t.total,done:t.done,sessionsTotal:t.sessionsTotal,sessionsDone:t.sessionsDone,startedAt:t.startedAt}:void 0;if(!this.estimate||performance.now()-this.estimate.time>ie)this.estimate={time:performance.now(),entries:b(this.db)};return{queueDone:this.queueDone,lag:Math.max(0,e-this.queueDone),entries:this.estimate.entries,...n?{backfill:n}:{},...r!==void 0?{etaSec:r}:{},layout:this.layout,reset:this.reset}}withIndex(e){return e(this.db)}close(){if(this.closed)return;this.closed=!0,this.db.close()}}var F=1000,oe=100;function ae(e){let t,r,n,i=!1,s=!1,o=0,a=[],u=(c)=>e.postMessage(c),f=(c)=>{if(s)return;if(n)clearTimeout(n);n=setTimeout(U,c)},L=()=>{if(!r||Atomics.load(r,yt)!==1)return;Atomics.store(r,Zt,1),Atomics.notify(r,Zt);while(Atomics.load(r,yt)===1)Atomics.wait(r,yt,1,1e4);Atomics.store(r,Zt,0)};function U(){if(n=void 0,s||!t)return;L();let c=!1;try{c=t.step()}catch(E){u({type:"error",message:E instanceof Error?E.message:String(E),fatal:!1}),i=!1,f(F);return}let l=performance.now();if(c){if(i=!0,l-o>=oe)o=l,u({type:"status",status:t.status()});f(0);return}i=!1,o=l;let m=t.status();u({type:"status",status:m});for(let E of a.splice(0))u({type:"flushed",id:E,status:m});f(F)}e.onmessage=(c)=>{let l=c.data;if(l.type==="init"){r=new Int32Array(l.flags);try{t=new Ha(l.options)}catch(m){u({type:"error",message:m instanceof Error?m.message:String(m),fatal:!0});return}u({type:"status",status:t.status()}),f(0)}else if(l.type==="dirty"){if(!i)f(0)}else if(l.type==="pause")L();else if(l.type==="flush"){if(a.push(l.id),!i)f(0)}else if(l.type==="stop"){if(s=!0,n)clearTimeout(n);t?.close(),u({type:"stopped"})}}}if(!Bun.isMainThread)ae(globalThis);
25
+ export{ks,yt,Zt,Ps,Ti,Cs,$a,ja,er,Wa,Qe,ki,bt,Ha};
@@ -0,0 +1,63 @@
1
+ // @bun
2
+ import{de,t,d,Dt,Ea,Yn,en,ys,Xn,Ca,Ra,Ia,vr,Ss,Ua,vs,yi}from"./chunk-x2ry671h.js";import{qr,mr,jn,ot,Et,b,ye,oi,Yr,br,ft,re}from"./chunk-vx4v71t4.js";import{Dr,Qi}from"./chunk-ykzm5g1b.js";import{Ee,Ao}from"./chunk-ejrksf6g.js";import{f,g,y,ca}from"./chunk-11zc1b2w.js";import{ae,Ge,m}from"./chunk-fc41dvhp.js";var Ne=new TextEncoder,Ue=new TextDecoder,fe=new TextDecoder("utf-8",{fatal:!0});function xr(...e){let r=e.reduce((o,{length:s})=>o+s,0),n=new Uint8Array(r),i=0;for(let o of e)n.set(o,i),i+=o.length;return n}var Pi=/[^\x00-\x7f]/;function me(e){if(typeof e=="string"&&e.length>=128){if(Pi.test(e))throw TypeError("non-ASCII string encountered in encode()");return Ne.encode(e)}let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);if(i>127)throw TypeError("non-ASCII string encountered in encode()");r[n]=i}return r}function Sr(e,r=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:r?"base64url":"base64"});if(r){if(e.includes("+")||e.includes("/"))throw TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let n=atob(e),i=new Uint8Array(n.length);for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o);return i}class z extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class oe extends z{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,r,n="unspecified",i="unspecified"){super(e,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}}class je extends z{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,r,n="unspecified",i="unspecified"){super(e,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}}class pt extends z{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class te extends z{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class B extends z{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class J extends z{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class Ae extends z{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class Te extends z{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r)}}class ht extends z{[Symbol.asyncIterator]=async function*(){};static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r)}}class mt extends z{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",r){super(e,r)}}class $e extends z{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}}var _i="The input to be decoded is not correctly encoded.";function pe(e){try{return Sr(typeof e=="string"?e:Ue.decode(e),!0)}catch(r){throw TypeError(_i,{cause:r})}}function V(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let r=Object.getPrototypeOf(e);return r===null||Object.getPrototypeOf(r)===null}function He(e){return V(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(V)}function Rr(...e){let r=new Set;for(let n of e)if(n)for(let i of Object.keys(n)){if(r.has(i))return!1;r.add(i)}return!0}function gt(e,r,n){try{return pe(e)}catch(i){throw new n(`Failed to base64url decode the ${r}`,{cause:i})}}function Ar(e,r,n){try{return me(e)}catch(i){throw new n(`The ${r} is not a valid base64url string`,{cause:i})}}function Tr(e,r,n){let i;try{i=JSON.parse(fe.decode(pe(e)))}catch(o){throw new r(n,{cause:o})}if(!V(i))throw new r(n);return i}var kr={__proto__:null,b64:!0};function Er(e,r){if(r!==void 0&&(!Array.isArray(r)||r.some((n)=>typeof n!="string")))throw TypeError(`"${e}" option must be an array of strings`);return r===void 0?void 0:new Set(r)}function Pr(e,r,n,i,o){if(o.crit!==void 0&&i?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!i||i.crit===void 0)return[];if(!Array.isArray(i.crit)||i.crit.length===0||i.crit.some((a)=>typeof a!="string"||a.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s=n===void 0?r:{__proto__:null,...n,...r};for(let a of i.crit){if(!(a in s))throw new te(`Extension Header Parameter "${a}" is not recognized`);if(!Object.hasOwn(o,a)||o[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(s[a]&&(!Object.hasOwn(i,a)||i[a]===void 0))throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return i.crit}function _r(e,r){if(r.includes("b64")){let n=e.b64;if(typeof n!="boolean")throw new B('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return n}return!0}var Ci=(e)=>e[Symbol.toStringTag],Mi=(e,r,n)=>{let{alg:i}=e;if(r.use!==void 0){let o=n==="sign"||n==="verify"?"sig":"enc";if(r.use!==o)throw TypeError(`Invalid key for this operation, its "use" must be "${o}" when present`)}if(r.alg!==void 0&&r.alg!==i)throw TypeError(`Invalid key for this operation, its "alg" must be "${i}" when present`);if(Array.isArray(r.key_ops)){let o=n==="encrypt"||n==="decrypt"?e.ops?.[n==="encrypt"?0:1]:n;if(o&&!r.key_ops.includes(o))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${o}" when present`)}};async function Mr(e,r,n){let{alg:i,secret:o}=e,s=n==="decrypt"||n==="sign";if(o&&r instanceof Uint8Array)return r;let a,c;if(V(r)){if(a=Ni(r),typeof a.kty!="string")throw Cr(i,r,o);if(!(o?a.kty==="oct"&&typeof a.k=="string":a.kty!=="oct"&&(s?a.kty==="AKP"&&typeof a.priv=="string"||typeof a.d=="string":a.d===void 0&&a.priv===void 0)))throw TypeError(o?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${s?"private":"public"} JWK`);if(Mi(e,a,n),a.kty==="oct")return pe(a.k);if(!Object.isFrozen(r)){let{key_ops:p}=r;Array.isArray(p)&&Object.freeze(p),Object.freeze(r)}}else{if(!qi(r))throw Cr(i,r,o);let p=o?"secret":s?"private":"public";if(r.type!==p&&(o||["secret","public","private"].includes(r.type)))throw TypeError(`${Ci(r)} instances must be of type "${p}" for the ${i} algorithm`);if(Lr(r))return r;if(c=r,c.type==="secret")return c.export()}yt||=new WeakMap;let u=r,l=yt.get(u);if(l?.[i])return l[i];if(l||yt.set(u,l={}),c&&typeof c.toCryptoKey=="function"){let p=c.type==="public",x=Li[c.asymmetricKeyDetails?.namedCurve],h=e.resolve?.({crv:x,asymmetricKeyType:c.asymmetricKeyType})??e.subtle;return l[i]=c.toCryptoKey(h,p,e.usages[p?0:1])}return a??=c.export({format:"jwk"}),a.alg=i,l[i]=await bt(e,a)}var yt,Li={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};var Lr=(e)=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Ii=(e)=>e?.[Symbol.toStringTag]==="KeyObject",qi=(e)=>Lr(e)||Ii(e);function Di(e,r,...n){if(n.length>2){let i=n.pop();e+=`one of type ${n.join(", ")}, or ${i}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return r==null?e+=` Received ${r}`:typeof r=="function"&&r.name?e+=` Received function ${r.name}`:typeof r=="object"&&r!=null&&r.constructor?.name&&(e+=` Received an instance of ${r.constructor.name}`),e}function Cr(e,r,n){let i=["CryptoKey","KeyObject","JSON Web Key"];return n&&i.push("Uint8Array"),TypeError(Di(`Key for the ${e} algorithm must be `,r,...i))}var Be=(e,r="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${r} must be ${e}`);function Oi(e,r){if(r&&!e.usages.includes(r))throw TypeError(`CryptoKey does not support this operation, its usages must include ${r}.`)}function Ir(e,r){let{modulusLength:n}=r.algorithm;if(typeof n!="number"||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function Wi(e,r,n){let i=e.algorithm;if(i.name!==r.name)throw Be(r.name);if(r.hash&&i.hash?.name!==r.hash)throw Be(r.hash,"algorithm.hash");if(r.namedCurve&&i.namedCurve!==r.namedCurve)throw Be(r.namedCurve,"algorithm.namedCurve");if(r.length!==void 0&&i.length!==r.length)throw Be(r.length,"algorithm.length");Oi(e,n)}function wt(e){return{__proto__:null,...e}}function Ni(e){let r=wt(e);if(r.ext!==void 0&&typeof r.ext!="boolean")throw TypeError('"ext" (Extractable) Parameter must be a boolean');if(r.key_ops!==void 0){let n=r.key_ops,i=Array.isArray(n)?[...n]:void 0;if(!i||i.some((o)=>typeof o!="string")||new Set(i).size!==i.length)throw TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');r.key_ops=i}return r}async function bt(e,r,n){if(!e.kty.includes(r.kty))throw new te('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let i=e.resolve?.({kty:r.kty,crv:r.crv})??e.subtle,o=!!(r.d||r.priv),s={...r,ext:n??r.ext};return s.kty!=="AKP"&&delete s.alg,delete s.use,crypto.subtle.importKey("jwk",s,i,s.ext??!o,r.key_ops??e.usages[o?1:0])}async function Or(e,r,n,i=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,r,i,[n])),Wi(e,r,n),e}function Wr(e){let r={__proto__:null};for(let n in e)r[n]={...e[n],alg:n};return r}var ke=[["verify"],["sign"]];function vt(e){let r={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:r,signing:r,usages:ke}}function ge(e,r){let n={name:r?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:n,signing:r?{...n,saltLength:r}:n,usages:ke,minRsaBits:2048}}function xt(e,r){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${r}`},usages:ke}}function Nr(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:ke}}function St(e){let r={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:r,signing:r,usages:ke}}var Rt=Wr({HS256:vt(256),HS384:vt(384),HS512:vt(512),RS256:ge(256),RS384:ge(384),RS512:ge(512),PS256:ge(256,32),PS384:ge(384,48),PS512:ge(512,64),ES256:xt("P-256",256),ES384:xt("P-384",384),ES512:xt("P-521",512),EdDSA:Nr(),Ed25519:Nr(),"ML-DSA-44":St(44),"ML-DSA-65":St(65),"ML-DSA-87":St(87)});function Ur(e){let r=typeof e=="string"?Rt[e]:void 0;if(!r)throw new te(`alg ${e} is not supported either by JOSE or your javascript runtime`);return r}function jr(e){return[e&&Er("algorithms",e.algorithms),e?.crit]}function Ui(e){return e===void 0?{}:Tr(e,B,"JWS Protected Header is invalid")}function ji(e){try{return me(e)}catch(r){throw new B("JWS Compact Serialization payload must use only ASCII characters",{cause:r})}}async function $i(e,r,n,i,o){let{protected:s,header:a,payload:c}=e,u=o??Ui(s);if(!Rr(u,a))throw new B("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let l={...u,...a},p=_r(u,Pr(B,kr,r[1],u,l)),{alg:x}=l;if(typeof x!="string"||!x)throw new B('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(r[0]&&!r[0].has(x))throw new pt('"alg" (Algorithm) Header Parameter value not allowed');if(p){if(typeof c!="string")throw new B("JWS Payload must be a string")}else if(typeof c!="string"&&!(c instanceof Uint8Array))throw new B("JWS Payload must be a string or an Uint8Array instance");let h=p||typeof c!="string"?c:i(c),w=!1;typeof n=="function"&&(n=await n(u,e),w=!0);let T=Ur(x),M=xr(s!==void 0?me(s):new Uint8Array,me("."),typeof h=="string"?r[2]??=Ar(h,"payload",B):h),E=gt(e.signature,"signature",B),D=await Mr(T,n,"verify"),L=await Or(D,T.subtle,"verify");T.minRsaBits&&Ir(T.alg,L);let N=!1;try{N=await crypto.subtle.verify(T.signing,L,E,M)}catch(G){throw new $e(void 0,{cause:G})}if(!N)throw new $e;let U={payload:typeof h=="string"?gt(h,"payload",B):h};return s!==void 0&&(U.protectedHeader=u),a!==void 0&&(U.unprotectedHeader=a),w?[{...U,key:D},p]:[U,p]}async function $r(e,r,n){if(e instanceof Uint8Array&&(e=Ue.decode(e)),typeof e!="string")throw new B("Compact JWS must be a string or Uint8Array");let{0:i,1:o,2:s,length:a}=e.split(".");if(a!==3)throw new B("Invalid Compact JWS");return $i({payload:o,protected:i,signature:s},r,n,ji)}var Hi=(e)=>Math.floor(e.getTime()/1000),Bi={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},zi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,we="check_failed";function At(){throw TypeError("Invalid time period format")}function Hr(e){typeof e!="string"&&At();let r=zi.exec(e);(!r||r[4]&&r[1])&&At();let n=parseFloat(r[2]),i=Math.round(n*Bi[r[3][0].toLowerCase()]);return Number.isFinite(i)||At(),r[1]==="-"||r[4]==="ago"?-i:i}function Tt(e,r){if(!Number.isFinite(r))throw TypeError(`Invalid ${e} input`);return r}var Br=(e)=>{let r=e.toLowerCase();return e.includes("/")?r:`application/${r}`},Ji=(e,r)=>typeof e=="string"?r.includes(e):Array.isArray(e)?r.some((n)=>e.includes(n)):!1;function kt(e,r,n=!1){let i=e[r];if(!(i===void 0&&!n)){if(typeof i!="number")throw new oe(`"${r}" claim must be a number`,e,r,"invalid");return i}}function Pt(e,r){throw new oe(`unexpected "${r}" claim value`,e,r,we)}function zr(e,r,n={}){let i;try{i=JSON.parse(fe.decode(r))}catch(L){throw new J("JWT Claims Set must be a top-level JSON object",{cause:L})}if(!V(i))throw new J("JWT Claims Set must be a top-level JSON object");let{typ:o}=n;if(o!==void 0&&(typeof e.typ!="string"||Br(e.typ)!==Br(o)))throw new oe('unexpected "typ" JWT header value',i,"typ",we);let{requiredClaims:s=[],issuer:a,subject:c,audience:u,maxTokenAge:l}=n,p=[...s];l!==void 0&&p.push("iat"),u!==void 0&&p.push("aud"),c!==void 0&&p.push("sub"),a!==void 0&&p.push("iss");for(let L of new Set(p.reverse()))if(!Object.hasOwn(i,L))throw new oe(`missing required "${L}" claim`,i,L,"missing");a!==void 0&&!(Array.isArray(a)?a:[a]).includes(i.iss)&&Pt(i,"iss"),c!==void 0&&i.sub!==c&&Pt(i,"sub"),u!==void 0&&!Ji(i.aud,typeof u=="string"?[u]:u)&&Pt(i,"aud");let{clockTolerance:x}=n,h=0;if(typeof x=="string")h=Hr(x);else if(x!==void 0){if(typeof x!="number")throw TypeError("Invalid clockTolerance option type");h=x}Tt("clockTolerance option",h);let{currentDate:w}=n,T=Tt("currentDate option",Hi(w===void 0?new Date:w)),M=kt(i,"iat",l!==void 0),E=kt(i,"nbf");if(E!==void 0&&E>T+h)throw new oe('"nbf" claim timestamp check failed',i,"nbf",we);let D=kt(i,"exp");if(D!==void 0&&D<=T-h)throw new je('"exp" claim timestamp check failed',i,"exp",we);if(l!==void 0){let L=T-M,N=Tt("maxTokenAge option",typeof l=="number"?l:Hr(l));if(L-h>N)throw new je('"iat" claim timestamp check failed (too far in the past)',i,"iat",we);if(L<-h)throw new oe('"iat" claim timestamp check failed (it should be in the past)',i,"iat",we)}return i}async function _t(e,r,n){let[i,o]=await $r(e,jr(n),r);if(!o)throw new J("JWTs MUST NOT use unencoded payload");let s=zr(i.protectedHeader,i.payload,n);return{...i,payload:s}}function Ki(e,r,n,i){let{kty:o,key_ops:s,ext:a,kid:c,alg:u,use:l,crv:p}=e;return(a===void 0||typeof a=="boolean")&&(s===void 0||Array.isArray(s)&&s.every((x,h)=>typeof x=="string"&&s.indexOf(x)===h)&&s.includes("verify"))&&r.kty.includes(o)&&(i===void 0||typeof i=="string"&&i===c)&&(u===void 0?o!=="AKP":n===u)&&(l===void 0||l==="sig")&&(!r.crv||p===r.crv)}async function Jr(e,r,n){let i=e.get(r)||e.set(r,{}).get(r),{alg:o}=n;if(i[o]===void 0){let s=bt(n,r,!0).then((a)=>{if(a.type!=="public")throw new Ae("JSON Web Key Set members must be public keys");return i[o]=a,a}).catch((a)=>{throw i[o]===s&&delete i[o],a});i[o]=s}return i[o]}function Ct(e){let r;try{r=structuredClone(e)}catch(o){throw new Ae("JSON Web Key Set malformed",{cause:o})}if(!He(r))throw new Ae("JSON Web Key Set malformed");let n=r.keys.map((o)=>{let s=wt(o);return Array.isArray(s.key_ops)&&(s.key_ops=[...s.key_ops]),s}),i=new WeakMap;return Object.defineProperty(async(o,s)=>{let{alg:a,kid:c}={...o,...s?.header},u=typeof a=="string"?Rt[a]:void 0;if(!u||u.secret)throw new te('Unsupported "alg" value for a JSON Web Key Set');let l=r.keys.filter((h,w)=>Ki(n[w],u,a,c)),{0:p,length:x}=l;if(!x)throw new Te;if(x!==1){let h=new ht;throw h[Symbol.asyncIterator]=async function*(){for(let w of l)try{yield await Jr(i,w,u)}catch{}},h}return Jr(i,p,u)},"jwks",{value:()=>structuredClone(r)})}function Gi(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var Mt;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Mt="jose/v6.2.13");var Gr=Symbol();async function Fi(e,r,n,i=fetch){let o=await i(e,{method:"GET",signal:n,redirect:"manual",headers:r}).catch((s)=>{throw s.name==="TimeoutError"?new mt(void 0,{cause:s}):s});if(o.status!==200)throw new z("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch(s){throw new z("Failed to parse the JSON Web Key Set HTTP response as JSON",{cause:s})}}var Fr=Symbol();function Pe(e,r){return Number.isFinite(e)&&Date.now()<e+r}function Kr(e,r,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e=="number"?e:r}function Lt(e,r){if(!(e instanceof URL))throw TypeError("url must be an instance of URL");let n=new URL(e.href).href,i=r??{},o=i.timeoutDuration;if(typeof o=="number"&&(!Number.isInteger(o)||o<0))throw TypeError('"timeoutDuration" option must be a non-negative integer');let s=typeof o=="number"?o:5000,a=Kr(i.cooldownDuration,30000,"cooldownDuration"),c=Kr(i.cacheMaxAge,600000,"cacheMaxAge"),u=new Headers(i.headers);Mt&&!u.has("User-Agent")&&u.set("User-Agent",Mt),u.has("accept")||u.set("accept","application/json, application/jwk-set+json");let l=i[Gr],p=i[Fr],x,h,w=0,T=0,M;if(p&&typeof p=="object"){let{uat:D,jwks:L}=p;Pe(D,c)&&He(L)&&(x=D,M=Ct(L))}let E=async()=>{if(h&&Gi()&&(h=void 0),!h){let D=++w,L=h=Fi(n,u,AbortSignal.timeout(s),l).then((N)=>{let U=Ct(N);if(D<=T)return;M=U;let G=Date.now();p&&(p.uat=G,p.jwks=N),x=G,T=D}).finally(()=>{h===L&&(h=void 0)})}await h};return Object.defineProperties(async(D,L)=>{(!M||!Pe(x,c))&&await E();try{return await M(D,L)}catch(N){if(N instanceof Te&&!Pe(x,a))return await E(),M(D,L);throw N}},{coolingDown:{get:()=>Pe(x,a),enumerable:!0},fresh:{get:()=>Pe(x,c),enumerable:!0},reload:{value:E,enumerable:!0},reloading:{get:()=>!!h,enumerable:!0},jwks:{value:()=>M?.jwks(),enumerable:!0}})}function It(e){if(typeof e!="string")throw new J("JWTs must use Compact JWS serialization, JWT must be a string");let{1:r,length:n}=e.split(".");if(n===5)throw new J("Only JWTs using Compact JWS serialization can be decoded");if(n!==3)throw new J("Invalid JWT");if(!r)throw new J("JWTs must contain a payload");let i;try{i=pe(r)}catch(s){throw new J("Failed to base64url decode the payload",{cause:s})}let o;try{o=JSON.parse(fe.decode(i))}catch(s){throw new J("Failed to parse the decoded payload as JSON",{cause:s})}if(!V(o))throw new J("Invalid JWT Claims Set");return o}var Vi=["cf-connecting-ip","cf-ray","x-forwarded-for","x-forwarded-host","forwarded","x-real-ip"],Xi="cf-access-jwt-assertion",Yi=/^https:\/\/([a-z0-9-]+(?:\.fed)?\.cloudflareaccess\.com)\//i;function _e(e){return e?Yi.exec(e)?.[1]?.toLowerCase():void 0}function Zi(e){return Vi.some((r)=>e.headers.has(r))}async function qt(e,r={}){let n=r.fetch??globalThis.fetch;try{let i=await n(`https://${e}/`,{redirect:"manual",signal:AbortSignal.timeout(1e4)});await i.body?.cancel();let o=_e(i.headers.get("location"));if(!o&&i.status>=400&&r.reportFailure)throw Error(`\u516C\u5171\u5730\u5740\u8FD4\u56DE HTTP ${i.status}`);return o}catch(i){if(r.reportFailure)throw i;return}}function Ot(e,r={}){let n=`https://${e.teamDomain}`,i=Lt(r.jwksURL??new URL(`${n}/cdn-cgi/access/certs`));return{async denies(o){if(!Zi(o))return!1;let s=o.headers.get(Xi);if(!s)return!0;try{return await _t(s,i,{issuer:n,audience:e.audience,algorithms:["RS256"],requiredClaims:["exp"]}),!1}catch{return!0}}}}import{timingSafeEqual as eo}from"crypto";import{chmodSync as to,existsSync as Vr,readFileSync as ro,writeFileSync as no}from"fs";import{join as io}from"path";var oo=600000,so=2592000000,ao=5,co=50,Qr=1024,uo=3600000,Nt="23456789ABCDEFGHJKMNPQRSTUVWXYZ";class ze{dataDir;now;devices;revocations=new Set;code="";expires=0;failures=new Map;codeFailures=0;lastSavedAt=0;constructor(e,r=Date.now){this.dataDir=e;this.now=r;let n=this.path,i=Vr(n)?JSON.parse(ro(n,"utf8")):[],o=this.now(),s=Array.isArray(i)?i.map((a)=>ho(a,o)).filter((a)=>a!==void 0):[];this.devices=po(s);while(this.tokenCount()>Qr)this.evictLeastRecentlyUsed();if(Vr(n))this.save();this.lastSavedAt=this.now(),this.rotate()}get path(){return io(this.dataDir,"devices.json")}pairingCode(){if(this.now()>=this.expires)this.rotate();return this.code}pairingExpires(){return this.expires}renewPairingCode(){return this.rotate(),this.code}pair(e,r,n="unknown"){if(this.now()>=this.expires)this.rotate();let i=this.failures.get(n);if(i&&i.blockedUntil>this.now())return;if(i)this.failures.delete(n);if(lo(e)!==this.code){let o=(i?.count??0)+1;if(this.failures.set(n,{count:o,blockedUntil:o>=ao?this.expires:0}),this.codeFailures++,this.codeFailures>=co)this.rotate();return}return this.rotate(),this.failures.delete(n),this.issue(r)}issue(e){let r=this.now();this.pruneExpired(r);let n=new Set;while(this.tokenCount()>=Qr){let u=this.evictLeastRecentlyUsed();if(!u)break;n.add(u)}let i=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url"),o={hash:Xr(i),created:r,lastSeen:r,expires:r+so},s=e.slice(0,100)||"device",a={id:crypto.randomUUID(),name:s,created:r,lastSeen:r,expires:o.expires,tokens:[o]};this.devices.push(a);let c=a.id;this.save();for(let u of n)for(let l of this.revocations)l(u);return{deviceID:c,token:i}}verify(e){if(!e)return;let r=this.now(),n=Buffer.from(Xr(e),"hex");for(let i of this.devices){let o=i.tokens.findIndex((a)=>{if(a.expires<=r)return!1;let c=Buffer.from(a.hash,"hex");return c.length===n.length&&eo(c,n)}),s=i.tokens[o];if(!s)continue;if(s.lastSeen=r,i.lastSeen=r,o>0)i.tokens.splice(o,1),i.tokens.unshift(s);if(r-this.lastSavedAt>=uo)this.save();return{id:i.id,name:i.name,created:i.created,lastSeen:i.lastSeen,expires:i.expires,token:s}}return}list(){return this.devices.filter((e)=>e.expires>this.now()).map((e)=>({id:e.id,name:e.name,created:e.created,lastSeen:e.lastSeen,expires:e.expires}))}onRevoke(e){return this.revocations.add(e),()=>{this.revocations.delete(e)}}revoke(e){let r=this.devices.length;if(this.devices=this.devices.filter((n)=>n.id!==e),this.devices.length===r)return!1;this.save();for(let n of this.revocations)n(e);return!0}pruneExpired(e){for(let r of this.devices)if(r.tokens=r.tokens.filter((n)=>n.expires>e),r.tokens.length>0)r.expires=Math.max(...r.tokens.map((n)=>n.expires));this.devices=this.devices.filter((r)=>r.tokens.length>0)}tokenCount(){return this.devices.reduce((e,r)=>e+r.tokens.length,0)}evictLeastRecentlyUsed(){let e,r;for(let i of this.devices)for(let o of i.tokens){let s=r&&(o.lastSeen<r.lastSeen||o.lastSeen===r.lastSeen&&o.created<=r.created);if(!r||s)e=i,r=o}if(!e||!r)return;let n=e.id;if(e.tokens=e.tokens.filter((i)=>i!==r),e.tokens.length===0)this.devices=this.devices.filter((i)=>i!==e);else e.expires=Math.max(...e.tokens.map((i)=>i.expires));return n}rotate(){let e=256-256%Nt.length,r="";while(r.length<8)for(let n of crypto.getRandomValues(new Uint8Array(16))){if(n>=e||r.length>=8)continue;r+=Nt[n%Nt.length]}this.code=r,this.expires=this.now()+oo,this.failures.clear(),this.codeFailures=0}save(){no(this.path,JSON.stringify(this.devices,null,2),{mode:384}),to(this.path,384),this.lastSavedAt=this.now()}}function lo(e){return e.toUpperCase().replace(/[^0-9A-Z]/g,"")}function Xr(e){return new Bun.CryptoHasher("sha256").update(e).digest("hex")}function po(e){let r=[...e].sort((i,o)=>o.lastSeen-i.lastSeen||o.created-i.created),n=new Map;for(let i of r){let o=n.get(i.id);if(!o){n.set(i.id,{...i,tokens:i.tokens.map((s)=>({...s}))});continue}for(let s of i.tokens){let a=o.tokens.find((c)=>c.hash===s.hash);if(!a)o.tokens.push({...s});else a.created=Math.min(a.created,s.created),a.lastSeen=Math.max(a.lastSeen,s.lastSeen),a.expires=Math.max(a.expires,s.expires)}o.created=Math.min(o.created,i.created),o.lastSeen=Math.max(o.lastSeen,i.lastSeen),o.expires=Math.max(o.expires,i.expires)}for(let i of n.values())i.tokens.sort((o,s)=>s.lastSeen-o.lastSeen||s.created-o.created);return Array.from(n.values())}function ho(e,r){if(typeof e!=="object"||e===null)return;let n=e;if(typeof n.id!=="string"||typeof n.name!=="string"||typeof n.created!=="number"||!Number.isFinite(n.created)||typeof n.lastSeen!=="number"||!Number.isFinite(n.lastSeen)||typeof n.expires!=="number"||!Number.isFinite(n.expires))return;let i=[];if(Array.isArray(n.tokens))for(let o of n.tokens){let s=fo(o,r);if(s&&!i.some((a)=>a.hash===s.hash))i.push(s)}if(typeof n.tokenHash==="string"&&n.expires>r){let o=[n.tokenHash];if(Array.isArray(n.tokenHashes)){for(let s of n.tokenHashes)if(typeof s==="string"&&s.length>0&&!o.includes(s))o.push(s)}for(let s of o){if(s.length===0||i.some((a)=>a.hash===s))continue;i.push({hash:s,created:n.created,lastSeen:n.lastSeen,expires:n.expires})}}if(i.length===0)return;return{id:n.id,name:n.name,created:n.created,lastSeen:Math.max(n.lastSeen,...i.map((o)=>o.lastSeen)),expires:Math.max(...i.map((o)=>o.expires)),tokens:i}}function fo(e,r){if(typeof e!=="object"||e===null)return;let n=e;if(typeof n.hash!=="string"||n.hash.length===0||typeof n.created!=="number"||!Number.isFinite(n.created)||typeof n.lastSeen!=="number"||!Number.isFinite(n.lastSeen)||typeof n.expires!=="number"||!Number.isFinite(n.expires)||n.expires<=r)return;return{hash:n.hash,created:n.created,lastSeen:n.lastSeen,expires:n.expires}}import{chmodSync as Zr,existsSync as mo,mkdirSync as go,readFileSync as yo,renameSync as wo,writeFileSync as bo}from"fs";import{join as xo}from"path";var k=()=>ae(()=>import("./chunk-7hss4hs3.js"));var Le=()=>ae(()=>import("./chunk-rbfpa63e.js"));var nn=300000,on=64000;class Tn{dataDir;models;proxy;path;builtin=new Map;config={providers:[]};constructor(e,r,n){this.dataDir=e;this.models=r;this.proxy=n;this.path=xo(e,"models.json");for(let i of r.getProviders())this.builtin.set(i.id,i)}async load(){if(!mo(this.path))return;let e=JSON.parse(yo(this.path,"utf8")),r=Array.isArray(e.providers)?e.providers:[];this.config={providers:[]};for(let n of r){if(!Po(n))continue;try{tn(n.id,n),this.config.providers.push(n),this.models.setProvider(this.createProvider(n))}catch{}}}list(){return this.config.providers.map(Ut)}async save(e,r){tn(e,r);let n=this.config.providers.find((c)=>c.id===e),i=r.apiKey?.trim()||n?.apiKey,s=en(r.models).length?r.models:ys(await rn(r.protocol,jt(r.baseUrl),i,this.proxy?.createFetch(br(e)))),a={id:e,name:r.name.trim(),protocol:r.protocol,baseUrl:jt(r.baseUrl),apiKey:i,models:s,defaultContextWindow:r.defaultContextWindow,defaultMaxTokens:r.defaultMaxTokens};return this.models.setProvider(this.createProvider(a)),this.config.providers=[...this.config.providers.filter((c)=>c.id!==e),a],await this.persist(),Ut(a)}async discover(e){let r=this.config.providers.find((a)=>a.id===e);if(!r)throw new t("no such model provider");let n=en(r.models),i=new Set(n.map((a)=>a.id)),s=(await rn(r.protocol,r.baseUrl,r.apiKey,this.proxy?.createFetch(br(e)))).filter((a)=>!i.has(a.id));return r.models=ys([...n,...s]),this.models.setProvider(this.createProvider(r)),await this.persist(),Ut(r)}async remove(e){if(!this.config.providers.some((i)=>i.id===e))return!1;let n=this.builtin.get(e);if(n)this.models.setProvider(n);else this.models.deleteProvider(e);return this.config.providers=this.config.providers.filter((i)=>i.id!==e),await this.persist(),!0}createProvider(e){let r=So(e.protocol),n=e.defaultContextWindow??nn,i=e.defaultMaxTokens??on,o=en(e.models).map((s)=>({id:s.id,name:s.name,api:e.protocol,provider:e.id,baseUrl:e.baseUrl,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},reasoning:Boolean(s.reasoning),contextWindow:s.contextWindow??n,maxTokens:s.maxTokens??i,...e.protocol==="openai-completions"||e.protocol==="openai-responses"?{compat:{supportsDeveloperRole:!1}}:{}}));return m({id:e.id,name:e.name,baseUrl:e.baseUrl,auth:{apiKey:{name:`${e.name} API key`,resolve:async()=>({auth:{apiKey:e.apiKey,baseUrl:e.baseUrl},source:e.apiKey?"Basalt settings":"configured endpoint"})}},models:o,api:r})}async persist(){go(this.dataDir,{recursive:!0});let e=`${this.path}.tmp-${process.pid}`;bo(e,`${JSON.stringify(this.config,null,2)}
3
+ `,{mode:384}),Zr(e,384),wo(e,this.path),Zr(this.path,384)}}function So(e){if(e==="openai-completions")return k();if(e==="openai-responses")return Le();return{stream:Dr,streamSimple:Qi}}function tn(e,r){if(!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(e))throw new t("provider id must be 1-64 letters, numbers, ., _, or -");if(typeof r.name!=="string"||!r.name.trim())throw new t("provider name is required");if(!sn(r.protocol))throw new t("unsupported model protocol");if(r.apiKey!==void 0&&typeof r.apiKey!=="string")throw new t("api key must be a string");if(typeof r.models!=="string")throw new t("models must be a string");if(r.defaultContextWindow!==void 0&&(typeof r.defaultContextWindow!=="number"||!Number.isFinite(r.defaultContextWindow)||r.defaultContextWindow<=0))throw new t("default context window must be a positive number");if(r.defaultMaxTokens!==void 0&&(typeof r.defaultMaxTokens!=="number"||!Number.isFinite(r.defaultMaxTokens)||r.defaultMaxTokens<=0))throw new t("default max tokens must be a positive number");jt(r.baseUrl);let n=en(r.models);if(n.length===0)return;let i=new Set;for(let o of n){if(!/^\S+$/.test(o.id)||i.has(o.id))throw new t("invalid model list");i.add(o.id)}}function Ut(e){let{defaultContextWindow:r,defaultMaxTokens:n}=e;return{id:e.id,name:e.name,protocol:e.protocol,baseUrl:e.baseUrl,apiKeyConfigured:Boolean(e.apiKey?.trim()),models:en(e.models).map((i)=>({...i,contextWindow:i.contextWindow??r??nn,maxTokens:i.maxTokens??n??on})),defaultContextWindow:r,defaultMaxTokens:n}}async function rn(e,r,n,i=fetch){let o=new Headers({accept:"application/json"});if(n)if(e==="anthropic-messages")o.set("x-api-key",n),o.set("anthropic-version","2023-06-01");else o.set("authorization",`Bearer ${n}`);let s;try{s=await i(Ro(r),{headers:o,signal:AbortSignal.timeout(1e4)})}catch{throw new t("\u81EA\u52A8\u83B7\u53D6\u6A21\u578B\u5931\u8D25\uFF1A\u65E0\u6CD5\u8FDE\u63A5\u6A21\u578B\u670D\u52A1")}if(!s.ok)throw new t(`\u81EA\u52A8\u83B7\u53D6\u6A21\u578B\u5931\u8D25\uFF1A\u670D\u52A1\u8FD4\u56DE HTTP ${s.status}`);let a;try{a=await s.json()}catch{throw new t("\u81EA\u52A8\u83B7\u53D6\u6A21\u578B\u5931\u8D25\uFF1A\u670D\u52A1\u8FD4\u56DE\u7684\u4E0D\u662F JSON")}let c=To(a);if(c.length===0)throw new t("\u81EA\u52A8\u83B7\u53D6\u6A21\u578B\u5931\u8D25\uFF1A\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6A21\u578B");return c}function Ro(e){let r=e.replace(/\/$/,"");return r.endsWith("/v1")?`${r}/models`:`${r}/v1/models`}function To(e){if(!e||typeof e!=="object")return[];let r=e,n=Array.isArray(r.data)?r.data:Array.isArray(r.models)?r.models:[],i=new Set,o=[];for(let s of n){let a=typeof s==="string"?{id:s.trim(),name:s.trim()}:ko(s);if(!a||!/^\S+$/.test(a.id)||i.has(a.id))continue;i.add(a.id),o.push(a)}return o}function ne(e){if(typeof e==="number"&&Number.isFinite(e)&&e>0)return Math.round(e);if(typeof e==="string"&&e.trim())return Yn(e);return}function ko(e){if(!e||typeof e!=="object")return;let r=e;if(typeof r.id!=="string"||!r.id.trim())return;let n=typeof r.display_name==="string"?r.display_name:typeof r.name==="string"?r.name:r.id,i=ne(r.context_window)??ne(r.context_length)??ne(r.max_context_length)??ne(r.context_window_tokens)??ne(r.top_provider?.context_length),o=ne(r.max_tokens)??ne(r.max_output_tokens)??ne(r.max_completion_tokens)??ne(r.top_provider?.max_completion_tokens),s={id:r.id.trim(),name:n.trim()||r.id.trim()};if(i!==void 0)s.contextWindow=i;if(o!==void 0)s.maxTokens=o;return s}function jt(e){if(typeof e!=="string")throw new t("base URL is required");let r;try{r=new URL(e.trim())}catch{throw new t("base URL must be a valid http or https URL")}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new t("base URL must use http or https");if(r.username||r.password||r.hash)throw new t("base URL cannot contain credentials or a fragment");return r.toString().replace(/\/$/,"")}function sn(e){return typeof e==="string"&&Ea.includes(e)}function Po(e){if(!e||typeof e!=="object")return!1;let r=e;return typeof r.id==="string"&&typeof r.name==="string"&&sn(r.protocol)&&typeof r.baseUrl==="string"&&typeof r.models==="string"&&(r.apiKey===void 0||typeof r.apiKey==="string")&&(r.defaultContextWindow===void 0||typeof r.defaultContextWindow==="number")&&(r.defaultMaxTokens===void 0||typeof r.defaultMaxTokens==="number")}import{closeSync as Co,existsSync as Mo,fsyncSync as Lo,mkdirSync as Io,openSync as qo,readFileSync as Do,renameSync as Oo,unlinkSync as Wo,writeFileSync as No}from"fs";import{networkInterfaces as Uo}from"os";import{join as jo}from"path";function za(e,r){if(r.host!==void 0){if(!Ee(r.host)&&!r.insecureHttp)throw Error("\u975E\u672C\u673A\u76D1\u542C\u5FC5\u987B\u663E\u5F0F\u4F20\u5165 --insecure-http\u3002");if(!Ee(r.host)&&!r.auth&&!r.allowRemoteNoAuth)throw Error("\u975E\u672C\u673A\u76D1\u542C\u4E0D\u80FD\u5173\u95ED\u8BA4\u8BC1\uFF0C\u9664\u975E\u663E\u5F0F\u4F20\u5165 --allow-remote-no-auth\u3002");return r.host}if(e.lanEnabled&&!r.auth)throw Error("\u5DF2\u5F00\u542F\u5C40\u57DF\u7F51\u8BBF\u95EE\uFF0C\u4E0D\u80FD\u4F7F\u7528 --no-auth\uFF1B\u8BF7\u542F\u7528\u8BA4\u8BC1\u6216\u7528 --host 127.0.0.1 \u4EC5\u76D1\u542C\u672C\u673A\u3002");return"127.0.0.1"}function an(e){if(!e||typeof e!=="object"||Array.isArray(e)||!("lanEnabled"in e)||typeof e.lanEnabled!=="boolean"||Object.keys(e).some((r)=>r!=="lanEnabled"))throw new t("\u7F51\u7EDC\u8BBE\u7F6E\u5FC5\u987B\u53EA\u5305\u542B\u5E03\u5C14\u503C lanEnabled");return{lanEnabled:e.lanEnabled}}function $o(e){let r=e.split(".").map(Number);if(r.length!==4||r.some((n)=>!Number.isInteger(n)||n<0||n>255))return!1;return r[0]===10||r[0]===172&&(r[1]??0)>=16&&(r[1]??0)<=31||r[0]===192&&r[1]===168}function Ce(e,r,n=Uo()){let i=[],o=new Set;for(let[s,a]of Object.entries(n))for(let c of a??[]){if(c.internal||c.family!=="IPv4"||!$o(c.address)||o.has(c.address))continue;if(e!=="0.0.0.0"&&e!==c.address)continue;o.add(c.address),i.push({interface:s,address:c.address,url:`http://${c.address}:${r}`})}return i}class Qs{dataDir;current={lanEnabled:!1};path;constructor(e){this.dataDir=e;this.path=jo(e,"network.json")}load(){if(!Mo(this.path))return;try{this.current=an(JSON.parse(Do(this.path,"utf8")))}catch(e){throw Error("\u8BFB\u53D6\u7F51\u7EDC\u914D\u7F6E\u5931\u8D25\uFF0C\u8BF7\u4FEE\u590D\u6570\u636E\u76EE\u5F55\u4E2D\u7684 network.json \u540E\u91CD\u8BD5",{cause:e})}}settings(){return{...this.current}}save(e,r){let n=an(e);r(n);let i=`${this.path}.tmp-${crypto.randomUUID()}`,o=!1;try{try{Io(this.dataDir,{recursive:!0});let s=qo(i,"wx",384);o=!0;try{No(s,`${JSON.stringify(n,null,2)}
4
+ `),Lo(s)}finally{Co(s)}Oo(i,this.path),o=!1}finally{if(o)Wo(i)}}catch(s){try{r(this.current)}catch(a){throw Error("\u4FDD\u5B58\u7F51\u7EDC\u914D\u7F6E\u5931\u8D25\uFF0C\u4E14\u76D1\u542C\u72B6\u6001\u56DE\u6EDA\u5931\u8D25\uFF1B\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u540E\u91CD\u542F\u670D\u52A1\u4EE5\u6062\u590D\u4E00\u81F4\u72B6\u6001",{cause:AggregateError([s,a])})}throw Error("\u4FDD\u5B58\u7F51\u7EDC\u914D\u7F6E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u7684\u53EF\u7528\u7A7A\u95F4\u548C\u5199\u5165\u6743\u9650\u540E\u91CD\u8BD5",{cause:s})}this.current=n}configuration(e){let r;if(!e.auth)r="\u670D\u52A1\u5668\u4EE5 --no-auth \u542F\u52A8\uFF0C\u8BF7\u542F\u7528\u8BBE\u5907\u8BA4\u8BC1\u540E\u518D\u914D\u7F6E\u5C40\u57DF\u7F51\u8BBF\u95EE\u3002";else if(e.hostOverride!==void 0)r="\u76D1\u542C\u5730\u5740\u7531\u663E\u5F0F --host \u53C2\u6570\u7BA1\u7406\uFF1B\u79FB\u9664\u8BE5\u53C2\u6570\u540E\u53EF\u5728\u8FD9\u91CC\u914D\u7F6E\u3002";let n=e.hostOverride!==void 0;return{settings:this.settings(),current:{port:e.port,remote:n?!Ee(e.host):e.lanActive},editable:r===void 0,disabledReason:r,addresses:n?Ce(e.host,e.port):e.addresses}}}var cn=()=>({classify:async(e,r,n)=>(await import("./chunk-xedzsj31.js")).classify(e,r,n)});var Je={"openai-decisions":{"classifier:gpt-6-luna":{type:"classifier",id:"gpt-6-luna",name:"GPT-6 Luna",api:"openai-decisions",provider:"openai",baseUrl:"https://api.openai.com/v1",input:["text","image"],cost:{input:0.1,output:0,cacheRead:0,cacheWrite:0,tiers:[{inputTokensAbove:272000,input:0.2,output:0,cacheRead:0,cacheWrite:0}]},contextWindow:922000}},"openai-responses":{"chat:gpt-4":{id:"gpt-4",name:"GPT-4",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text"],cost:{input:30,output:60,cacheRead:0,cacheWrite:0},contextWindow:8192,maxTokens:8192,compat:{supportsStrictMode:!0},type:"chat"},"chat:gpt-4-turbo":{id:"gpt-4-turbo",name:"GPT-4 Turbo",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:10,output:30,cacheRead:0,cacheWrite:0},contextWindow:128000,maxTokens:4096,compat:{supportsStrictMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-4.1":{id:"gpt-4.1",name:"GPT-4.1",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:2,output:8,cacheRead:0.5,cacheWrite:0},contextWindow:1047576,maxTokens:32768,compat:{supportsStrictMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-4.1-mini":{id:"gpt-4.1-mini",name:"GPT-4.1 mini",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:0.4,output:1.6,cacheRead:0.1,cacheWrite:0},contextWindow:1047576,maxTokens:32768,compat:{supportsStrictMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-4.1-nano":{id:"gpt-4.1-nano",name:"GPT-4.1 nano",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:0.1,output:0.4,cacheRead:0.025,cacheWrite:0},contextWindow:1047576,maxTokens:32768,compat:{supportsStrictMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-4o":{id:"gpt-4o",name:"GPT-4o",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:2.5,output:10,cacheRead:1.25,cacheWrite:0},contextWindow:128000,maxTokens:16384,compat:{supportsStrictMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-4o-2024-05-13":{id:"gpt-4o-2024-05-13",name:"GPT-4o (2024-05-13)",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:5,output:15,cacheRead:0,cacheWrite:0},contextWindow:128000,maxTokens:4096,compat:{supportsStrictMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-4o-2024-08-06":{id:"gpt-4o-2024-08-06",name:"GPT-4o (2024-08-06)",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:2.5,output:10,cacheRead:1.25,cacheWrite:0},contextWindow:128000,maxTokens:16384,compat:{supportsStrictMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-4o-2024-11-20":{id:"gpt-4o-2024-11-20",name:"GPT-4o (2024-11-20)",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:2.5,output:10,cacheRead:1.25,cacheWrite:0},contextWindow:128000,maxTokens:16384,compat:{supportsStrictMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-4o-mini":{id:"gpt-4o-mini",name:"GPT-4o mini",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:0.15,output:0.6,cacheRead:0.075,cacheWrite:0},contextWindow:128000,maxTokens:16384,compat:{supportsStrictMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5":{id:"gpt-5",name:"GPT-5",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:0.125,cacheWrite:0},contextWindow:400000,maxTokens:128000,thinkingLevelMap:{off:null,minimal:"minimal",low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5-chat-latest":{id:"gpt-5-chat-latest",name:"GPT-5 Chat Latest",api:"openai-responses",baseUrl:"https://api.openai.com/v1",provider:"openai",reasoning:!1,input:["text","image"],cost:{input:1.25,output:10,cacheRead:0.125,cacheWrite:0},contextWindow:128000,maxTokens:16384,thinkingLevelMap:{off:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5-mini":{id:"gpt-5-mini",name:"GPT-5 Mini",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:0.25,output:2,cacheRead:0.025,cacheWrite:0},contextWindow:400000,maxTokens:128000,thinkingLevelMap:{off:null,minimal:"minimal",low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5-nano":{id:"gpt-5-nano",name:"GPT-5 Nano",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:0.05,output:0.4,cacheRead:0.005,cacheWrite:0},contextWindow:400000,maxTokens:128000,thinkingLevelMap:{off:null,minimal:"minimal",low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5-pro":{id:"gpt-5-pro",name:"GPT-5 Pro",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:15,output:120,cacheRead:0,cacheWrite:0},contextWindow:400000,maxTokens:128000,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:"high",xhigh:null,max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.1":{id:"gpt-5.1",name:"GPT-5.1",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:0.125,cacheWrite:0},contextWindow:400000,maxTokens:128000,thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.2":{id:"gpt-5.2",name:"GPT-5.2",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:0.175,cacheWrite:0},contextWindow:400000,maxTokens:128000,thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.2-chat-latest":{id:"gpt-5.2-chat-latest",name:"GPT-5.2 Chat",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:0.175,cacheWrite:0},contextWindow:128000,maxTokens:16384,thinkingLevelMap:{off:null,minimal:null,low:null,medium:"medium",high:null,xhigh:"xhigh",max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.2-pro":{id:"gpt-5.2-pro",name:"GPT-5.2 Pro",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:21,output:168,cacheRead:0,cacheWrite:0},contextWindow:400000,maxTokens:128000,thinkingLevelMap:{off:null,minimal:null,low:null,medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.3-chat-latest":{id:"gpt-5.3-chat-latest",name:"GPT-5.3 Chat (latest)",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!1,input:["text","image"],cost:{input:1.75,output:14,cacheRead:0.175,cacheWrite:0},contextWindow:128000,maxTokens:16384,thinkingLevelMap:{off:null,xhigh:"xhigh"},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:0.175,cacheWrite:0},contextWindow:400000,maxTokens:128000,thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.3-codex-spark":{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:0.175,cacheWrite:0},contextWindow:128000,maxTokens:32000,thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4":{id:"gpt-5.4",name:"GPT-5.4",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:2.5,output:15,cacheRead:0.25,cacheWrite:0,tiers:[{inputTokensAbove:272000,input:5,output:22.5,cacheRead:0.5,cacheWrite:0}]},contextWindow:272000,maxTokens:128000,thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0,supportsAdditionalTools:!0,supportsToolSearch:!0,supportsMidConvoSystemMessages:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4-mini":{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:0.75,output:4.5,cacheRead:0.075,cacheWrite:0},contextWindow:400000,maxTokens:128000,thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0,supportsAdditionalTools:!0,supportsToolSearch:!0,supportsMidConvoSystemMessages:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4-nano":{id:"gpt-5.4-nano",name:"GPT-5.4 nano",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:0.2,output:1.25,cacheRead:0.02,cacheWrite:0},contextWindow:400000,maxTokens:128000,thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.4-pro":{id:"gpt-5.4-pro",name:"GPT-5.4 Pro",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:30,output:180,cacheRead:0,cacheWrite:0,tiers:[{inputTokensAbove:272000,input:60,output:270,cacheRead:0,cacheWrite:0}]},contextWindow:1050000,maxTokens:128000,thinkingLevelMap:{off:null,minimal:null,low:null,medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0,supportsAdditionalTools:!0,supportsToolSearch:!0,supportsMidConvoSystemMessages:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.5":{id:"gpt-5.5",name:"GPT-5.5",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:5,output:30,cacheRead:0.5,cacheWrite:0,tiers:[{inputTokensAbove:272000,input:10,output:45,cacheRead:1,cacheWrite:0}]},contextWindow:272000,maxTokens:128000,thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0,supportsAdditionalTools:!0,supportsToolSearch:!0,supportsMidConvoSystemMessages:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.5-pro":{id:"gpt-5.5-pro",name:"GPT-5.5 Pro",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:30,output:180,cacheRead:0,cacheWrite:0,tiers:[{inputTokensAbove:272000,input:60,output:270,cacheRead:0,cacheWrite:0}]},contextWindow:1050000,maxTokens:128000,thinkingLevelMap:{off:null,minimal:null,low:null,medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-luna":{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:0.2,output:1.2,cacheRead:0.02,cacheWrite:0.25,tiers:[{inputTokensAbove:272000,input:0.4,output:1.8,cacheRead:0.04,cacheWrite:0.5}]},contextWindow:272000,maxTokens:128000,thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0,supportsAdditionalTools:!0,supportsToolSearch:!0,supportsMidConvoSystemMessages:!0,supportsExplicitPromptCacheMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-sol":{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:0.4,cacheWrite:5,tiers:[{inputTokensAbove:272000,input:8,output:30,cacheRead:0.8,cacheWrite:10}]},contextWindow:272000,maxTokens:128000,thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0,supportsAdditionalTools:!0,supportsToolSearch:!0,supportsMidConvoSystemMessages:!0,supportsExplicitPromptCacheMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-5.6-terra":{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:0.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272000,input:4,output:18,cacheRead:0.4,cacheWrite:5}]},contextWindow:272000,maxTokens:128000,thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0,supportsAdditionalTools:!0,supportsToolSearch:!0,supportsMidConvoSystemMessages:!0,supportsExplicitPromptCacheMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-astra":{id:"gpt-6-astra",name:"GPT-6 Astra",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5,tiers:[{inputTokensAbove:272000,input:20,output:75,cacheRead:2,cacheWrite:25}]},contextWindow:272000,maxTokens:128000,thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0,supportsAdditionalTools:!0,supportsToolSearch:!0,supportsMidConvoSystemMessages:!0,supportsExplicitPromptCacheMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-luna":{id:"gpt-6-luna",name:"GPT-6 Luna",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:0.1,output:0.5,cacheRead:0.01,cacheWrite:0.125,tiers:[{inputTokensAbove:272000,input:0.2,output:0.75,cacheRead:0.02,cacheWrite:0.25}]},contextWindow:272000,maxTokens:128000,thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0,supportsAdditionalTools:!0,supportsToolSearch:!0,supportsMidConvoSystemMessages:!0,supportsExplicitPromptCacheMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6-sol":{id:"gpt-6-sol",name:"GPT-6 Sol",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:0.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272000,input:4,output:15,cacheRead:0.4,cacheWrite:5}]},contextWindow:272000,maxTokens:128000,thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0,supportsAdditionalTools:!0,supportsToolSearch:!0,supportsMidConvoSystemMessages:!0,supportsExplicitPromptCacheMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-6.1-sol":{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:0.1,cacheWrite:2.5,tiers:[{inputTokensAbove:272000,input:4,output:15,cacheRead:0.2,cacheWrite:5}]},contextWindow:272000,maxTokens:128000,thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsStrictMode:!0,supportsOpenAIGrammarTools:!0,supportsAdditionalTools:!0,supportsToolSearch:!0,supportsMidConvoSystemMessages:!0,supportsExplicitPromptCacheMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-daybreak-blue-latest":{id:"gpt-daybreak-blue-latest",name:"Daybreak Blue",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:0.4,cacheWrite:5,tiers:[{inputTokensAbove:272000,input:8,output:30,cacheRead:0.8,cacheWrite:10}]},contextWindow:1050000,maxTokens:128000,thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsStrictMode:!0,supportsExplicitPromptCacheMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-daybreak-red-latest":{id:"gpt-daybreak-red-latest",name:"Daybreak Red",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:12.5,output:75,cacheRead:1.25,cacheWrite:15.625},contextWindow:400000,maxTokens:128000,thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsStrictMode:!0,supportsExplicitPromptCacheMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:gpt-realtime-2.1":{id:"gpt-realtime-2.1",name:"GPT-Realtime-2.1",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:4,output:24,cacheRead:0.4,cacheWrite:0},contextWindow:128000,maxTokens:32000,thinkingLevelMap:{off:null,minimal:"minimal",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsStrictMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:o1":{id:"o1",name:"o1",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:15,output:60,cacheRead:7.5,cacheWrite:0},contextWindow:200000,maxTokens:1e5,thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsStrictMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:o1-pro":{id:"o1-pro",name:"o1-pro",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:150,output:600,cacheRead:0,cacheWrite:0},contextWindow:200000,maxTokens:1e5,thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsStrictMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:o3":{id:"o3",name:"o3",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:2,output:8,cacheRead:0.5,cacheWrite:0},contextWindow:200000,maxTokens:1e5,thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsStrictMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:o3-mini":{id:"o3-mini",name:"o3-mini",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:0.55,cacheWrite:0},contextWindow:200000,maxTokens:1e5,thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsStrictMode:!0},type:"chat"},"chat:o3-pro":{id:"o3-pro",name:"o3-pro",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:20,output:80,cacheRead:0,cacheWrite:0},contextWindow:200000,maxTokens:1e5,thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsStrictMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"},"chat:o4-mini":{id:"o4-mini",name:"o4-mini",api:"openai-responses",provider:"openai",baseUrl:"https://api.openai.com/v1",reasoning:!0,input:["text","image"],cost:{input:1.1,output:4.4,cacheRead:0.275,cacheWrite:0},contextWindow:200000,maxTokens:1e5,thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsStrictMode:!0},inputLimits:{maxRequestBytes:536870912,images:{maxPerRequest:1500,resize:{maxWidth:2000,maxHeight:2000,maxBytes:4718592,jpegQuality:80}}},type:"chat"}}};var un=f("openai",Je),wu=g("openai",Je),ln=y("openai",Je);function vo(){return m({id:"openai",name:"OpenAI",baseUrl:"https://api.openai.com/v1",auth:{apiKey:b("OpenAI API key",["OPENAI_API_KEY"]),oauth:ye({name:"OpenAI (ChatGPT subscription)",isSubscription:!0,loginLabel:"Sign in with ChatGPT",load:ca})},models:[...Object.values(un),...Object.values(ln)],filterAllModels:(e,r)=>r?.type==="oauth"?e.filter((n)=>!Ge(n,"classifier")):e,api:Le(),classifiers:{"openai-decisions":cn()}})}var Bo=2000,zo=1e4,dn="openai";function _o(){let e=vo(),r=e.auth.oauth;if(!r)throw Error("OpenAI SDK \u672A\u63D0\u4F9B ChatGPT \u8BA2\u9605\u767B\u5F55\uFF0C\u8BF7\u68C0\u67E5\u4F9D\u8D56\u5B89\u88C5");return m({id:Dt,name:"ChatGPT \u8BA2\u9605",baseUrl:e.baseUrl,auth:{oauth:r},models:e.getModels().filter((n)=>n.api==="openai-responses").map((n)=>({...n,provider:Dt})),api:e})}function Jo(e){if(typeof e!=="string")return;try{let r=It(e);for(let n of[r.name,r.preferred_username,r.email])if(typeof n==="string"&&n.trim())return n.trim()}catch{return}return}class kn{models;store;providerID;pending;transitions=Promise.resolve();closed=!1;lastError;constructor(e,r,n=Dt){this.models=e;this.store=r;this.providerID=n}async status(){let e=this.pending,r=e?{providerID:dn,connected:!1,pending:!0,authorizeURL:e.state.authorizeURL,instructions:e.state.instructions,awaitingInput:e.state.awaitingInput,error:e.state.error}:{providerID:dn,connected:!1,pending:!1,error:this.lastError};try{let n=await this.store.read(this.providerID),i=n?.type==="oauth",o=i?Jo(n.idToken):void 0;return{...r,connected:i,...o?{displayName:o}:{}}}catch(n){throw Error("\u8BFB\u53D6\u767B\u5F55\u51ED\u636E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u7684\u53EF\u7528\u7A7A\u95F4\u4E0E\u5199\u5165\u6743\u9650\u540E\u91CD\u8BD5",{cause:n})}}async start(e){let r=await this.transition(async()=>{if(this.closed)throw new t("\u767B\u5F55\u670D\u52A1\u6B63\u5728\u5173\u95ED");let i=this.models.getProvider(this.providerID);if(!i)throw new t("OpenAI provider is unavailable");let o=i.auth.oauth;if(!o)throw new t(`${i.name} does not support oauth login`);let s=this.pending;if(s)s.state.controller.abort(),await pn(s.done);let a=new AbortController,c=Promise.withResolvers(),u=Promise.withResolvers(),l={controller:a,signal:a.signal,awaitingInput:!1,closed:!1,authorizeReady:c.resolve},p={state:l,done:u.promise,ready:c.promise};this.pending=p,this.lastError=void 0;let x={signal:l.signal,prompt:(w)=>this.handlePrompt(l,w),notify:(w)=>this.handleEvent(l,w)};return(async()=>{let w=await o.login(x,{getDeviceId:()=>this.store.deviceId(),agentName:e});l.signal.throwIfAborted();try{await this.store.modify(this.providerID,async()=>w,{signal:l.signal})}catch(T){if(l.signal.aborted)throw T;throw Error("\u4FDD\u5B58\u767B\u5F55\u51ED\u636E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u7684\u53EF\u7528\u7A7A\u95F4\u4E0E\u5199\u5165\u6743\u9650\u540E\u91CD\u8BD5",{cause:T})}})().catch((w)=>{if(!l.signal.aborted)l.error=w instanceof Error?w.message:String(w)}).finally(()=>{if(l.closed=!0,l.cancelPrompt?.(new DOMException("\u767B\u5F55\u6D41\u7A0B\u5DF2\u7ED3\u675F","AbortError")),l.authorizeURL=void 0,l.instructions=void 0,this.pending===p)this.lastError=l.error,this.pending=void 0;u.resolve()}),p});await Ko(r);let n=await this.status();if(!n.pending&&n.error)throw new t(n.error);return n}transition(e){let r=this.transitions.then(e);return this.transitions=r.then(()=>{return},()=>{return}),r}async manualInput(e){let r=this.pending;if(!r)throw new t("\u6CA1\u6709\u8FDB\u884C\u4E2D\u7684\u767B\u5F55\u6D41\u7A0B");if(!r.state.awaitingInput||!r.state.resolvePrompt)throw new t("\u5F53\u524D\u767B\u5F55\u6D41\u7A0B\u4E0D\u63A5\u53D7\u624B\u52A8\u8F93\u5165");r.state.resolvePrompt(e)}abort(){let e=this.pending;if(!e)return;e.state.controller.abort()}logout(){return this.transition(async()=>{let e=this.pending;if(e)e.state.controller.abort(),await pn(e.done);await this.models.logout(this.providerID)})}async close(){this.closed=!0,await this.transitions;let e=this.pending;if(!e)return;e.state.controller.abort(),await e.done}handlePrompt(e,r){if(e.signal.aborted||e.closed)return Promise.reject(e.signal.reason??new DOMException("\u767B\u5F55\u6D41\u7A0B\u5DF2\u7ED3\u675F","AbortError"));if(r.signal?.aborted)return Promise.reject(r.signal.reason);if(r.type!=="manual_code"){let n=`\u767B\u5F55\u6D41\u7A0B\u8BF7\u6C42\u4E86\u4E0D\u652F\u6301\u7684\u4EA4\u4E92\u7C7B\u578B\uFF1A${r.type}`;return e.error=n,e.controller.abort(),Promise.reject(Error(n))}return e.awaitingInput=!0,e.instructions=r.message,new Promise((n,i)=>{let o=()=>{if(e.signal.removeEventListener("abort",a),r.signal?.removeEventListener("abort",c),e.resolvePrompt=void 0,e.cancelPrompt=void 0,e.awaitingInput=!1,e.instructions===r.message)e.instructions=void 0},s=(u)=>{o(),i(u)},a=()=>s(e.signal.reason),c=()=>s(r.signal?.reason);if(e.resolvePrompt=(u)=>{o(),n(u)},e.cancelPrompt=s,e.signal.addEventListener("abort",a,{once:!0}),r.signal?.addEventListener("abort",c,{once:!0}),e.signal.aborted)a();else if(r.signal?.aborted)c()})}handleEvent(e,r){if(e.signal.aborted||e.closed)return;if(r.type==="auth_url"){e.authorizeURL=r.url,e.instructions=r.instructions??e.instructions,e.authorizeReady();return}if(r.type==="progress"){e.instructions=r.message;return}if(r.type==="info")e.instructions=r.message}}async function pn(e){let r;try{await Promise.race([e,new Promise((n,i)=>{r=setTimeout(()=>i(new t("\u4E0A\u6B21\u767B\u5F55\u5C1A\u672A\u9000\u51FA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5")),Bo)})])}finally{clearTimeout(r)}}async function Ko(e){let r;try{await Promise.race([e.done,e.ready,new Promise((n)=>{r=setTimeout(n,zo)})])}finally{clearTimeout(r)}}import{chmodSync as ds,existsSync as ps,mkdirSync as hs,readFileSync as fs,writeFileSync as ms}from"fs";import{isIP as gs}from"net";import{join as Gt}from"path";import{chmodSync as Zo,existsSync as Me,mkdirSync as es,readFileSync as Jt,rmSync as ts,writeFileSync as fn}from"fs";import{join as Q}from"path";import{chmodSync as Go,existsSync as Fo,readFileSync as Vo,writeFileSync as Qo}from"fs";import{join as Xo}from"path";var Yo="https://api.cloudflare.com/client/v4",$t=/^[a-f0-9]{32}$/;class Ht{path;credentials;constructor(e){if(this.path=Xo(e,"cloudflare.json"),Fo(this.path)){let r=JSON.parse(Vo(this.path,"utf8"));if(r&&typeof r==="object"&&"token"in r&&typeof r.token==="string")this.credentials={token:r.token}}}async request(e,r="GET",n,i=this.credentials?.token){if(!i)throw new t("\u8BF7\u5148\u8FDE\u63A5 Cloudflare\uFF0C\u63D0\u4F9B\u7BA1\u7406\u4EE4\u724C");let o;try{o=await fetch(`${Yo}${e}`,{method:r,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},...n===void 0?{}:{body:JSON.stringify(n)},redirect:"error",signal:AbortSignal.timeout(20000)})}catch{throw new t("\u65E0\u6CD5\u8FDE\u63A5 Cloudflare API\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u540E\u91CD\u8BD5")}let s;try{s=await o.json()}catch{throw new t(`Cloudflare \u8FD4\u56DE\u4E86\u65E0\u6548\u54CD\u5E94\uFF08HTTP ${o.status}\uFF09\uFF0C\u8BF7\u91CD\u8BD5`)}if(!o.ok||!s.success){if(o.status===401||o.status===403)throw new t("Cloudflare \u6388\u6743\u4E0D\u8DB3\u6216\u4EE4\u724C\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u8FDE\u63A5\u5E76\u786E\u8BA4\u6240\u9700\u6743\u9650\u548C\u8D44\u6E90\u8303\u56F4");throw Object.assign(new t(`Cloudflare \u64CD\u4F5C\u5931\u8D25\uFF08HTTP ${o.status}\uFF09\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`),{upstreamStatus:o.status})}if(s.result===void 0)throw new t("Cloudflare \u8FD4\u56DE\u4E86\u4E0D\u5B8C\u6574\u7684\u54CD\u5E94\uFF0C\u8BF7\u91CD\u8BD5");return s.result}async list(e,r=this.credentials?.token){let n=[];for(let i=1;i<=100;i++){let o=await this.request(`${e}${e.includes("?")?"&":"?"}per_page=100&page=${i}`,"GET",void 0,r);if(!Array.isArray(o))throw new t("Cloudflare \u5217\u8868\u54CD\u5E94\u65E0\u6548");if(n.push(...o),o.length<100)return n}throw new t("Cloudflare \u8D44\u6E90\u8FC7\u591A\uFF0C\u8BF7\u7F29\u5C0F\u4EE4\u724C\u7684\u8D26\u53F7\u548C\u57DF\u540D\u8303\u56F4")}async connect(e){if(typeof e!=="string"||!/^[A-Za-z0-9_-]{20,256}$/.test(e))throw new t("\u8BF7\u5B8C\u6574\u7C98\u8D34 Cloudflare API Token\uFF0C\u4E0D\u662F\u96A7\u9053\u4EE4\u724C\u6216 Global API Key");let r=await this.list("/zones",e);if(!r.length)throw new t("\u4EE4\u724C\u65E0\u6CD5\u8BBF\u95EE\u4EFB\u4F55\u57DF\u540D\uFF0C\u8BF7\u6388\u4E88\u6240\u9009\u57DF\u540D\u7684 Zone Read \u548C DNS Edit \u6743\u9650");let n=new Set(r.map((i)=>i.account.id));for(let i of n){if(!$t.test(i))throw new t("Cloudflare \u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8D26\u53F7");await this.request(`/accounts/${i}/cfd_tunnel?per_page=1`,"GET",void 0,e),await this.request(`/accounts/${i}/access/apps?per_page=1`,"GET",void 0,e)}Qo(this.path,JSON.stringify({token:e}),{mode:384}),Go(this.path,384),this.credentials={token:e}}async zone(e){let n=(await this.list("/zones")).filter((i)=>e===i.name||e.endsWith(`.${i.name}`)).sort((i,o)=>o.name.length-i.name.length)[0];if(!n||!$t.test(n.id)||!$t.test(n.account.id))throw new t("\u8BE5\u57DF\u540D\u4E0D\u5728\u6388\u6743\u8303\u56F4\u5185\uFF0C\u8BF7\u68C0\u67E5\u57DF\u540D\u6216\u91CD\u65B0\u8FDE\u63A5 Cloudflare");return n}async application(e,r){let i=(await this.list(`/accounts/${e}/access/apps`)).filter((a)=>[a.domain,...(a.destinations??[]).map((u)=>u.uri)].filter((u)=>!!u).some((u)=>{let l=u.split("/")[0]??"";return l===r||l.startsWith("*.")&&r.endsWith(l.slice(1))}));if(i.length>1)throw new t("\u8BE5\u5730\u5740\u88AB\u591A\u4E2A Access \u5E94\u7528\u8986\u76D6\uFF0C\u65E0\u6CD5\u5B89\u5168\u5730\u7528\u5355\u4E2A\u5F00\u5173\u4FEE\u6539");let o=i[0];if(!o)return;let s=new Set([o.domain,...(o.destinations??[]).map((a)=>a.uri)].filter(Boolean));if(o.type!=="self_hosted"||s.size!==1||!s.has(r))throw new t("\u73B0\u6709 Access \u5E94\u7528\u5305\u542B\u5176\u4ED6\u57DF\u540D\u3001\u8DEF\u5F84\u6216\u901A\u914D\u89C4\u5219\uFF0C\u4E0D\u80FD\u5728\u6B64\u4FEE\u6539\u4EE5\u514D\u5F71\u54CD\u5176\u4ED6\u670D\u52A1");return o}async accessState(e){let r=await this.zone(e),n=await this.application(r.account.id,e);if(!n)return!1;return!(await this.list(`/accounts/${r.account.id}/access/apps/${n.id}/policies`)).some((o)=>o.decision==="bypass"&&!o.require?.length&&!o.exclude?.length&&Array.isArray(o.include)&&o.include.some((s)=>!!s&&typeof s==="object"&&("everyone"in s)))}async provision(e,r){let n=await this.zone(e);if((await this.list(`/zones/${n.id}/dns_records?name=${encodeURIComponent(e)}`)).length)throw new t("\u8BE5\u57DF\u540D\u5DF2\u6709 DNS \u8BB0\u5F55\uFF0C\u8BF7\u4F7F\u7528\u5C1A\u672A\u5360\u7528\u7684\u5B50\u57DF\u540D\uFF1B\u73B0\u6709 Basalt \u96A7\u9053\u53EF\u76F4\u63A5\u5F00\u5173");let o=n.account.id,s=await this.request(`/accounts/${o}/cfd_tunnel`,"POST",{name:`basalt-${crypto.randomUUID()}`,config_src:"cloudflare"});if(!s.id||!s.token)throw new t("Cloudflare \u672A\u8FD4\u56DE\u96A7\u9053\u51ED\u636E");try{await this.request(`/accounts/${o}/cfd_tunnel/${s.id}/configurations`,"PUT",{config:{ingress:[{hostname:e,service:`http://127.0.0.1:${r}`},{service:"http_status:404"}]}}),await this.request(`/zones/${n.id}/dns_records`,"POST",{type:"CNAME",proxied:!0,name:e,content:`${s.id}.cfargotunnel.com`})}catch(a){try{await this.request(`/accounts/${o}/cfd_tunnel/${s.id}`,"DELETE")}catch{throw new t("\u914D\u7F6E\u96A7\u9053\u5931\u8D25\uFF0C\u4E14\u65B0\u5EFA\u7A7A\u96A7\u9053\u6E05\u7406\u5931\u8D25\uFF1B\u8BF7\u91CD\u8BD5\u8FDE\u63A5\u6216\u68C0\u67E5 Cloudflare \u6388\u6743")}throw a}return{token:s.token,tunnelId:s.id}}async setAccess(e,r,n){let i=await this.zone(e),o=`/accounts/${i.account.id}/access`,s=await this.application(i.account.id,e);if(!r&&!s)return;if(r&&(!n||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)||n.length>254))throw new t("\u8BF7\u586B\u5199\u5141\u8BB8\u767B\u5F55\u7684\u90AE\u7BB1");if(!r&&s){let w=await this.list(`${o}/apps/${s.id}/policies`),T=w.find((M)=>M.name==="Basalt public access");await this.request(`${o}/apps/${s.id}/policies${T?`/${T.id}`:""}`,T?"PUT":"POST",{name:"Basalt public access",decision:"bypass",include:[{everyone:{}}],precedence:T?.precedence??Math.max(0,...w.map((M)=>M.precedence??0))+1});return}if(!r)return;let c=(await this.list(`${o}/identity_providers`)).find((w)=>w.type==="github");if(!c)throw new t("\u8D26\u53F7\u5C1A\u672A\u914D\u7F6E GitHub \u8EAB\u4EFD\u6E90\uFF0C\u9700\u8981\u5148\u63D0\u4F9B GitHub OAuth \u5E94\u7528\u6388\u6743\uFF1B\u4E0D\u4F1A\u4F7F\u7528\u90AE\u7BB1\u9A8C\u8BC1\u7801\u66FF\u4EE3");let u=s?await this.list(`${o}/apps/${s.id}/policies`):[];if(!(!s||s.name===`Basalt ${e}`))throw new t("\u6B64\u5E94\u7528\u7531\u5916\u90E8\u7BA1\u7406\uFF0C\u65E0\u6CD5\u4FDD\u8BC1 GitHub \u4E0E\u90AE\u7BB1\u53CC\u91CD\u9650\u5236\uFF0C\u5DF2\u4FDD\u7559\u539F\u914D\u7F6E\uFF1B\u8BF7\u4F7F\u7528\u65B0\u7684\u5B50\u57DF\u540D");if(u.some((w)=>w.decision==="bypass"&&w.name!=="Basalt public access"))throw new t("\u73B0\u6709\u5E94\u7528\u5305\u542B\u5916\u90E8\u7ED5\u8FC7\u7B56\u7565\uFF0C\u5DF2\u505C\u6B62\u5F00\u542F\uFF0C\u907F\u514D\u663E\u793A\u5F00\u542F\u5374\u4ECD\u516C\u5F00\u8BBF\u95EE");let p;try{p=await this.request(`${o}/organizations`)}catch(w){if(!(w instanceof Error)||!("upstreamStatus"in w)||w.upstreamStatus!==404)throw w;p=await this.request(`${o}/organizations`,"POST",{name:"Basalt"})}if(!s)s=await this.request(`${o}/apps`,"POST",{name:`Basalt ${e}`,domain:e,type:"self_hosted",session_duration:"24h",allowed_idps:[c.id],auto_redirect_to_identity:!0});await this.request(`${o}/apps/${s.id}`,"PUT",{name:s.name,domain:e,type:"self_hosted",session_duration:"24h",allowed_idps:[c.id],auto_redirect_to_identity:!0});let x=await this.list(`${o}/apps/${s.id}/policies`);if(x.some((w)=>!["Basalt public access","Basalt email access"].includes(w.name)))throw new t("\u5E94\u7528\u4E2D\u5B58\u5728\u5176\u4ED6\u7B56\u7565\uFF0C\u5DF2\u505C\u6B62\u4FEE\u6539\u4EE5\u4FDD\u7559\u539F\u6709\u8BBF\u95EE\u89C4\u5219");let h=x.find((w)=>w.name==="Basalt email access");await this.request(`${o}/apps/${s.id}/policies${h?`/${h.id}`:""}`,h?"PUT":"POST",{name:"Basalt email access",decision:"allow",include:[{email:{email:n}}],require:[{login_method:{id:c.id}}],precedence:h?.precedence??Math.max(0,...x.map((w)=>w.precedence??0))+1});for(let w of x.filter((T)=>T.name==="Basalt public access"))await this.request(`${o}/apps/${s.id}/policies/${w.id}`,"DELETE");if(!s.aud||!/^[a-z0-9-]+\.cloudflareaccess\.com$/.test(p.auth_domain))throw new t("\u4E91\u7AEF\u4FDD\u62A4\u5DF2\u914D\u7F6E\uFF0C\u4F46\u6821\u9A8C\u53C2\u6570\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u91CD\u8BD5\uFF1B\u5F53\u524D\u4FDD\u62A4\u4E0D\u4F1A\u81EA\u52A8\u653E\u5BBD");return{teamDomain:p.auth_domain,audience:s.aud}}}var rs=/https:\/\/dash\.cloudflare\.com\/argotunnel\S+/,ns=/Created tunnel \S+ with id ([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/,Bt=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,is=/^[a-z0-9-]+\.cloudflareaccess\.com$/,os=/^[A-Za-z0-9]{16,128}$/,ss=/^[A-Za-z0-9+/=_-]{20,4096}$/;class Wt{options;cloudflare;managementError;managedAccess;path;home;loginChild;loginState={state:"idle"};stored;process;accessAppsURLCache;state="off";error;connections=new Set;tail=[];startedAt=0;lastError;restartTimer;backoff;stopping=!1;metricsTimer;metricsAnswered=!1;accessInspection;constructor(e,r){this.options=r;this.cloudflare=new Ht(e),this.path=Q(e,"tunnel.json"),this.home=Q(e,"cloudflared"),this.backoff=r.backoffMs?.min??2000,this.stored=as(this.path)}access(){return this.stored?.access}publicURL(){return this.stored?`https://${this.stored.hostname}`:void 0}running(){return this.process!==void 0}status(){let e=this.accessAppsURL();return{configured:this.stored!==void 0,cloudflareConnected:this.cloudflare.credentials!==void 0,enabled:this.stored!==void 0&&this.stored.enabled!==!1,...this.managedAccess===void 0?{}:{managedAccess:this.managedAccess},...this.managementError?{managementError:this.managementError}:{},...this.stored?.accessEmail?{accessEmail:this.stored.accessEmail}:{},...this.stored?{hostname:this.stored.hostname,access:this.stored.access}:{},...e?{accessAppsURL:e}:{},hasToken:this.stored?.token!==void 0,...this.stored?{mode:this.stored.token===void 0?"local":"token"}:{},login:this.hasCert()?{state:"done"}:this.loginState,binary:this.binary()!==void 0,install:mn(),state:this.stored?this.state:"off",...this.visibleError()?{error:this.visibleError()}:{},localPort:this.options.localPort(),...this.stored?{publicURL:this.publicURL()}:{}}}inspectStatus(){let e=this.status(),r=e.hostname;if(!r)return e;let n=this.accessInspection;if(!n||n.hostname!==r)n={hostname:r,checkedAt:0,pending:!1,state:"checking"},this.accessInspection=n;if(!n.pending&&Date.now()-n.checkedAt>=30000){n.pending=!0;let i=n;qt(r,{reportFailure:!0}).then((o)=>{i.team=o,i.state=o?"login":"no-login",i.checkedAt=Date.now(),i.pending=!1},()=>{i.team=void 0,i.state="error",i.checkedAt=Date.now(),i.pending=!1})}return{...e,cloudAccessState:n.state,...n.team?{cloudAccessTeam:n.team}:{}}}binary(){return Kt(this.options.binary)}async save(e,r={}){let n=e.hostname?.trim().toLowerCase();if(!n||!Bt.test(n))throw new t("\u4E3B\u673A\u540D\u683C\u5F0F\u4E0D\u5BF9\uFF0C\u5E94\u5F62\u5982 basalt.example.com");let i=e.token?.trim(),o=i?Ua(i):this.stored?.token;if(i&&!o)throw new t("\u6CA1\u627E\u5230\u96A7\u9053\u4EE4\u724C\uFF08\u4EE5 eyJ \u5F00\u5934\uFF09\uFF0C\u8BF7\u4ECE Cloudflare \u9875\u9762\u5B8C\u6574\u590D\u5236");if(!o)throw new t("\u9700\u8981\u586B\u5199\u96A7\u9053\u4EE4\u724C");if(!ss.test(o))throw new t("\u96A7\u9053\u4EE4\u724C\u683C\u5F0F\u4E0D\u5BF9\uFF0C\u8BF7\u5B8C\u6574\u590D\u5236 Cloudflare \u91CC\u7684\u4EE4\u724C");let s=e.access===void 0?this.stored?.access:await this.resolveAccess(e.access??void 0,n);if(await this.stop(),this.stored={hostname:n,token:o,...s?{access:s}:{}},he(this.path,this.stored),r.start??!0)this.start();return this.status()}async connectCloudflare(e){return await this.cloudflare.connect(e),this.refreshManagement()}async refreshManagement(){if(this.managedAccess=void 0,this.managementError=void 0,this.cloudflare.credentials&&this.stored)try{this.managedAccess=await this.cloudflare.accessState(this.stored.hostname)}catch(e){this.managementError=e instanceof Error?e.message:"\u65E0\u6CD5\u8BFB\u53D6\u4E91\u7AEF\u914D\u7F6E"}return this.inspectStatus()}async configureManaged(e){if(typeof e.enabled!=="boolean")throw new t("\u96A7\u9053\u5F00\u5173\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C");if(!e.enabled){if(this.stored)this.stored.enabled=!1,he(this.path,this.stored);return await this.stop(),this.state="off",this.status()}let r=e.hostname?.trim().toLowerCase()??this.stored?.hostname;if(!r||!Bt.test(r))throw new t("\u8BF7\u586B\u5199\u6709\u6548\u7684\u57DF\u540D\uFF0C\u5982 basalt.example.com");if(this.stored?.hostname===r)return this.stored.enabled=!0,he(this.path,this.stored),this.start(),this.refreshManagement();if(this.stored&&(this.stored.access||await this.cloudflare.accessState(this.stored.hostname)))throw new t("\u8BF7\u5148\u5173\u95ED\u5F53\u524D\u57DF\u540D\u7684 Access \u4FDD\u62A4\uFF0C\u518D\u4FEE\u6539\u57DF\u540D");let n=await this.cloudflare.provision(r,this.options.localPort());return await this.stop(),this.stored={hostname:r,token:n.token,enabled:!0},he(this.path,this.stored),this.start(),this.refreshManagement()}async configureManagedAccess(e){if(typeof e.enabled!=="boolean")throw new t("Access \u5F00\u5173\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C");if(!this.stored)throw new t("\u8BF7\u5148\u914D\u7F6E\u96A7\u9053\u57DF\u540D");let r=e.email?.trim()||this.stored.accessEmail,n=await this.cloudflare.setAccess(this.stored.hostname,e.enabled,r);if(n)this.stored.access=n;else delete this.stored.access;if(r)this.stored.accessEmail=r;return he(this.path,this.stored),this.accessInspection=void 0,this.refreshManagement()}async remove(){return this.cancelLogin(),await this.stop(),ts(this.path,{force:!0}),this.stored=void 0,this.state="off",this.error=void 0,this.status()}hasCert(){return Me(Q(this.home,".cloudflared","cert.pem"))}accessAppsURL(){if(this.accessAppsURLCache)return this.accessAppsURLCache;try{let e=Jt(Q(this.home,".cloudflared","cert.pem"),"utf8"),r=JSON.parse(Buffer.from(e.replace(/-----[A-Z ]+-----/g,"").replace(/\s+/g,""),"base64").toString("utf8"));if(r&&typeof r==="object"&&"accountID"in r&&typeof r.accountID==="string")this.accessAppsURLCache=`https://dash.cloudflare.com/${r.accountID}/one/access-controls/apps`}catch{}return this.accessAppsURLCache}localEnv(){return Ke(this.home)}writeConfig(e,r){let n=Q(this.home,"config.yml");return fn(n,[`tunnel: ${e}`,`credentials-file: ${Q(this.home,".cloudflared",`${e}.json`)}`,"ingress:",` - hostname: ${r}`,` service: http://127.0.0.1:${this.options.localPort()}`," - service: http_status:404",""].join(`
5
+ `),{mode:384}),n}startLogin(){if(this.hasCert()||this.loginChild)return this.status();let e=this.binary();if(!e)throw new t(be());es(Q(this.home,".cloudflared"),{recursive:!0,mode:448});let r=Bun.spawn([e,"tunnel","login"],{env:this.localEnv(),stdin:"ignore",stdout:"pipe",stderr:"pipe",windowsHide:!0});this.loginChild=r,this.loginState={state:"waiting"};let n=[],i=async(o)=>{let s=new TextDecoder;try{for await(let a of o){let c=s.decode(a,{stream:!0});for(let l of c.split(`
6
+ `))if(l.trim())n.push(l.trim());let u=rs.exec(c)?.[0];if(u&&this.loginChild===r)this.loginState={state:"waiting",url:u}}}catch{}};return i(r.stdout),i(r.stderr),r.exited.then((o)=>{if(this.loginChild!==r)return;this.loginChild=void 0,this.loginState=o===0&&this.hasCert()?{state:"done"}:{state:"error",error:`\u6388\u6743\u6CA1\u6709\u5B8C\u6210\uFF1A${n.at(-1)??`cloudflared \u5DF2\u9000\u51FA\uFF08${o}\uFF09`}`}}),this.status()}cancelLogin(){let e=this.loginChild;return this.loginChild=void 0,this.loginState={state:"idle"},e?.kill(),this.status()}async provision(e){let r=e.hostname?.trim().toLowerCase();if(!r||!Bt.test(r))throw new t("\u4E3B\u673A\u540D\u683C\u5F0F\u4E0D\u5BF9\uFF0C\u5E94\u5F62\u5982 basalt.example.com");if(!this.hasCert())throw new t("\u8FD8\u6CA1\u6709\u8FDE\u63A5 Cloudflare\uFF0C\u8BF7\u5148\u5B8C\u6210\u6388\u6743");let n=await this.resolveAccess(e.access??void 0,r);await this.stop();let i=this.stored?.token===void 0&&this.stored?.hostname===r?this.stored.tunnelId:void 0;if(!i){let a=Q(this.home,"config.yml");if(Me(a)){let c=Jt(a,"utf8"),u=/^ {2}- hostname: (\S+)$/m.exec(c)?.[1],l=/^tunnel: ([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/m.exec(c)?.[1];if(u===r&&l&&Me(Q(this.home,".cloudflared",`${l}.json`)))i=l}}let o=i!==void 0;if(!i){let a=await this.run(["tunnel","create",`basalt-${crypto.randomUUID().slice(0,8)}`]);if(i=ns.exec(a.text)?.[1],a.code!==0||!i)throw new t(`\u521B\u5EFA\u96A7\u9053\u5931\u8D25\uFF1A${hn(a.text)}`)}let s=await this.run(["tunnel","route","dns",i,r]);if(s.code!==0){if(!o)await this.run(["tunnel","delete","-f",i]);throw new t(`\u7ED9 ${r} \u6DFB\u52A0\u57DF\u540D\u89E3\u6790\u5931\u8D25\uFF1A${hn(s.text)}\uFF08\u8BF7\u786E\u8BA4\u5B83\u5C5E\u4E8E\u4F60\u521A\u624D\u6388\u6743\u7684\u57DF\u540D\uFF0C\u4E14\u8FD8\u6CA1\u6709\u540C\u540D\u7684 DNS \u8BB0\u5F55\uFF09`)}return this.stored={hostname:r,tunnelId:i,...n?{access:n}:{}},he(this.path,this.stored),this.start(),this.status()}async setAccess(e){if(!this.stored)throw new t("\u8FD8\u6CA1\u6709\u914D\u7F6E\u8FDC\u7A0B\u8BBF\u95EE");let r=await this.resolveAccess(e??void 0,this.stored.hostname);if(this.stored={...this.stored,access:r},!r)delete this.stored.access;return he(this.path,this.stored),this.status()}async resolveAccess(e,r){if(!e)return;let n=e.teamDomain?.trim().toLowerCase(),i=e.audience?.trim();if(!os.test(i??""))throw new t("Audience \u6807\u7B7E\u683C\u5F0F\u4E0D\u5BF9\uFF0C\u8BF7\u5B8C\u6574\u590D\u5236");if(!n){let o=await qt(r);if(!o)throw new t(`\u6CA1\u68C0\u6D4B\u5230 ${r} \u4E0A\u7684 Access \u5E94\u7528\uFF0C\u8BF7\u5148\u5728 Cloudflare \u7ED9\u8BE5\u57DF\u540D\u5EFA\u597D\u5E94\u7528\uFF08\u6216\u624B\u52A8\u586B\u5199\u56E2\u961F\u57DF\u540D\uFF09`);return{teamDomain:o,audience:i}}if(!is.test(n))throw new t("\u56E2\u961F\u57DF\u540D\u5E94\u5F62\u5982 myteam.cloudflareaccess.com");return{teamDomain:n,audience:i}}async run(e){let r=this.binary();if(!r)throw new t(be());let n=Bun.spawn([r,...e],{env:this.localEnv(),stdin:"ignore",stdout:"pipe",stderr:"pipe",windowsHide:!0}),i=setTimeout(()=>n.kill(),60000);try{let[o,s,a]=await Promise.all([new Response(n.stdout).text(),new Response(n.stderr).text(),n.exited]);return{code:a,text:`${o}
7
+ ${s}`}}finally{clearTimeout(i)}}visibleError(){if(this.error)return this.error;if(this.state!=="starting"||!this.lastError)return;return Date.now()-this.startedAt>=(this.options.errorAfterMs??8000)?this.lastError:void 0}start(){if(!this.stored||this.stored.enabled===!1||this.process)return;this.stopping=!1,clearTimeout(this.restartTimer);let e=this.binary();if(!e){this.state="missing-binary",this.error=be();return}this.state="starting",this.error=void 0,this.connections.clear(),this.tail=[],this.startedAt=Date.now(),this.lastError=void 0;let{token:r,tunnelId:n,hostname:i}=this.stored,o=ls();this.metricsAnswered=!1;let s=["tunnel","--no-autoupdate","--metrics",`127.0.0.1:${o}`],a=r===void 0?this.localEnv():{...process.env,TUNNEL_TOKEN:r};if(r===void 0&&n)s.push("--config",this.writeConfig(n,i)),s.push("run",n);else s.push("run");let c;try{c=Bun.spawn([e,...s],{env:a,stdin:"ignore",stdout:"pipe",stderr:"pipe",windowsHide:!0})}catch(u){let l=u instanceof Error&&"code"in u&&u.code==="ENOENT";this.state=l?"missing-binary":"error",this.error=l?be():`\u65E0\u6CD5\u542F\u52A8 cloudflared\uFF1A${u instanceof Error?u.message:u}`;return}this.process=c,this.metricsTimer=setInterval(()=>void this.pollReady(o,c),this.options.readyPollMs??1000),this.pump(c.stdout,r),this.pump(c.stderr,r),c.exited.then((u)=>this.exited(c,u))}async stop(){this.stopping=!0,clearTimeout(this.restartTimer),clearInterval(this.metricsTimer);let e=this.process;if(!e)return;if(e.kill(),await Promise.race([e.exited,Bun.sleep(5000)]),this.process===e)e.kill("SIGKILL"),this.process=void 0;this.state="off",this.connections.clear()}exited(e,r){if(this.process!==e)return;if(clearInterval(this.metricsTimer),this.process=void 0,this.connections.clear(),this.stopping)return;this.state="error",this.error=cs(this.tail,r),this.restartTimer=setTimeout(()=>this.start(),this.backoff),this.backoff=Math.min(this.backoff*2,this.options.backoffMs?.max??30000)}async pollReady(e,r){try{let i=await(await fetch(`http://127.0.0.1:${e}/ready`,{signal:AbortSignal.timeout(800)})).json();if(this.process!==r||!i||typeof i!=="object"||!("readyConnections"in i))return;if(typeof i.readyConnections!=="number")return;if(this.metricsAnswered=!0,i.readyConnections>0)this.state="connected",this.error=void 0,this.lastError=void 0,this.backoff=this.options.backoffMs?.min??2000;else if(this.state==="connected")this.state="starting"}catch{}}async pump(e,r){let n=new TextDecoder,i="";try{for await(let o of e){i+=n.decode(o,{stream:!0});let s=i.split(`
8
+ `);i=s.pop()??"";for(let a of s)this.line(r?a.replaceAll(r,"***"):a)}}catch{}}line(e){let r=e.trim();if(!r)return;this.tail=[...this.tail,r].slice(-20);let n=us(r);if(n)this.lastError=n;let i=/connIndex=(\d+)/.exec(r)?.[1];if(this.metricsAnswered)return;if(i!==void 0&&r.includes("Registered tunnel connection"))this.connections.add(i),this.state="connected",this.error=void 0,this.lastError=void 0,this.backoff=this.options.backoffMs?.min??2000;else if(i!==void 0&&/Unregistered tunnel connection|Connection terminated/.test(r)){if(this.connections.delete(i),this.connections.size===0&&this.state==="connected")this.state="starting"}}}function as(e){if(!Me(e))return;try{let r=JSON.parse(Jt(e,"utf8"));if(!r||typeof r!=="object")return;let{hostname:n,token:i,tunnelId:o,access:s,enabled:a,accessEmail:c}=r;if(typeof n!=="string")return;let u={...s?.teamDomain&&s.audience?{access:s}:{},...typeof a==="boolean"?{enabled:a}:{},...typeof c==="string"?{accessEmail:c}:{}};if(typeof i==="string")return{hostname:n,token:i,...u};if(typeof o==="string")return{hostname:n,tunnelId:o,...u};return}catch{return}}function he(e,r){fn(e,JSON.stringify(r),{mode:384}),Zo(e,384)}function cs(e,r){let n=e.join(`
9
+ `);if(/Unauthorized|token is not valid/i.test(n))return"\u4EE4\u724C\u65E0\u6548\u6216\u5DF2\u88AB\u64A4\u9500\uFF0C\u8BF7\u5230 Cloudflare \u91CD\u65B0\u590D\u5236";let i=e.at(-1);return i?`cloudflared \u5DF2\u9000\u51FA\uFF08${r}\uFF09\uFF1A${i}`:`cloudflared \u5DF2\u9000\u51FA\uFF08${r}\uFF09`}var zt="https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/";function Kt(e){if(e)return Me(e)?e:void 0;let r=Bun.which("cloudflared");if(r)return r;if(process.platform!=="win32")return;let n=[process.env["ProgramFiles(x86)"],process.env.ProgramFiles].filter((i)=>i!==void 0).map((i)=>Q(i,"cloudflared"));return Bun.which("cloudflared",{PATH:n.join(";")})??void 0}function Ke(e){return{...process.env,HOME:e,USERPROFILE:e}}function mn(){if(process.platform==="darwin")return{command:"brew install cloudflared",url:zt};if(process.platform==="win32")return{command:"winget install --id Cloudflare.cloudflared",url:zt};return{url:zt}}function be(){let{command:e,url:r}=mn();return e?`\u6CA1\u627E\u5230 cloudflared\uFF0C\u8BF7\u5148\u5B89\u88C5\uFF1A${e}`:`\u6CA1\u627E\u5230 cloudflared\uFF0C\u8BF7\u6309\u5B98\u65B9\u6587\u6863\u5B89\u88C5\uFF1A${r}`}function us(e){let n=/\bERR\b\s+(.*)$/.exec(e)?.[1]?.replace(/\s+event=\d+$/,"").trim();if(!n)return;if(/^(Please try|\d\.\s|Run your|See GitHub|For example|https?:)/.test(n))return;return n.length>200?`${n.slice(0,200)}\u2026`:n}function ls(){let e=Bun.serve({port:0,hostname:"127.0.0.1",fetch:()=>new Response}),r=e.port;if(e.stop(!0),r===void 0)throw Error("no free port");return r}function hn(e){return e.split(`
10
+ `).map((n)=>n.replace(/^\d{4}-\d\d-\d\dT\S+\s+(ERR|INF|WRN)\s+/,"").trim()).filter(Boolean).at(-1)??"\u6CA1\u6709\u8F93\u51FA"}var yn=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,ws=/https:\/\/[^\s"'<>]+/,bs=30000,xs=300000,Rs=5000,As=new Set(["authorization",vs,"cookie","host","origin","referer","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),Ts=new Set(["set-cookie","connection","keep-alive","transfer-encoding"]);function se(e){if(!e)return!1;let r=e.trim();if(!yn.test(r))return!1;let n=r.split(".")[1];if(!n)return!1;try{let i=Buffer.from(n,"base64url").toString("utf8"),o=JSON.parse(i);if(!o||typeof o!=="object"||!("exp"in o)||typeof o.exp!=="number")return!1;return o.exp*1000>Date.now()+bs}catch{return!1}}function Ft(e,r=!1){let n;try{n=new URL(e.trim())}catch{throw new t("\u8FDC\u7A0B\u670D\u52A1\u5668\u5730\u5740\u683C\u5F0F\u65E0\u6548")}if(n.username||n.password)throw new t("\u8FDC\u7A0B\u670D\u52A1\u5668\u5730\u5740\u4E0D\u5141\u8BB8\u5305\u542B\u7528\u6237\u540D\u6216\u5BC6\u7801");if(n.protocol!=="https:"&&!(r&&n.protocol==="http:"))throw new t("\u8FDC\u7A0B Access \u4EE3\u7406\u4EC5\u652F\u6301 HTTPS \u670D\u52A1\u5668\u5730\u5740");if(!r&&Is(n.hostname))throw new t("\u4E0D\u5141\u8BB8\u4EE3\u7406\u672C\u673A\u56DE\u73AF\u6216\u79C1\u6709\u5185\u7F51\u5730\u5740");return n.origin}function ks(e,r=!1){let n;try{n=Buffer.from(e,"base64url").toString("utf8")}catch{throw new t("\u8FDC\u7A0B\u76EE\u6807\u7F16\u7801\u65E0\u6548")}return Ft(n,r)}class Fe{options;storePath;home;tokens=new Map;loginTasks=new Map;loginResults=new Map;lastCliLookup=new Map;constructor(e,r={}){this.options=r;this.storePath=Gt(e,"remote-access.json"),this.home=Gt(e,"cloudflared");for(let[n,i]of Object.entries(Ms(this.storePath)))if(se(i))this.tokens.set(n,i)}async status(e){let r=Ft(e,this.options.allowInsecureTarget),n=this.options.fetch??globalThis.fetch,i,o=!1;try{let a=await n(`${r}/api/info`,{redirect:"manual",signal:AbortSignal.timeout(8000)});await a.body?.cancel(),i=_e(a.headers.get("location")),o=i!==void 0}catch{}let s=await this.resolveToken(r);if(s&&o)try{let a=await n(`${r}/api/info`,{headers:{[yi]:s},redirect:"manual",signal:AbortSignal.timeout(8000)});if(await a.body?.cancel(),_e(a.headers.get("location")))this.deleteToken(r),s=void 0}catch{}return this.buildStatus(r,o,i,s!==void 0)}async startLogin(e){let r=Ft(e,this.options.allowInsecureTarget);if(await this.resolveToken(r))return this.loginResults.set(r,{state:"done"}),this.status(r);if(this.loginTasks.get(r))return this.buildStatus(r,!0,void 0,!1);let o=this.resolveCommand();if(!o)throw new t(be());hs(Gt(this.home,".cloudflared"),{recursive:!0,mode:448});let s=Bun.spawn([...o,"access","login","--no-verbose","--auto-close",r],{env:Ke(this.home),stdin:"ignore",stdout:"pipe",stderr:"pipe",windowsHide:!0}),a={child:s,state:{state:"waiting"}};this.loginTasks.set(r,a),this.loginResults.delete(r);let c,u=new Promise((w)=>{c=w}),l=setTimeout(()=>s.kill(),xs);l.unref?.();let p=(async()=>{let w=new TextDecoder,T="";try{for await(let M of s.stderr)if(T+=w.decode(M,{stream:!0}),!a.state.url){let E=ws.exec(T);if(E?.[0])a.state={state:"waiting",url:E[0]},c?.()}}catch{}return T})(),x=new Response(s.stdout).text().catch(()=>"");Promise.all([x,p,s.exited]).then(([w,T,M])=>{if(clearTimeout(l),this.loginTasks.get(r)===a)this.loginTasks.delete(r);let E=gn(w);if(M===0&&se(E)){this.saveToken(r,E),this.lastCliLookup.delete(r),this.loginResults.set(r,{state:"done"});return}let D=Cs(T)??`\u6388\u6743\u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF08${M}\uFF09`;this.loginResults.set(r,{state:"error",error:D})}),await Promise.race([u,s.exited,Bun.sleep(1500)]);let h=this.tokens.get(r);return this.buildStatus(r,!0,void 0,se(h))}async forward(e,r,n){let i=ks(e,this.options.allowInsecureTarget),o=Es(i,r),s=n.method.toUpperCase(),a=Ps(n.headers);if(!a.has(yi)){let E=await this.resolveToken(i);if(E)a.set(yi,E)}let c;if(s!=="GET"&&s!=="HEAD"){let E=await n.arrayBuffer();if(E.byteLength>0)c=E}let u=new AbortController,l=()=>u.abort();if(n.signal.aborted)u.abort();else n.signal.addEventListener("abort",l,{once:!0});let p=this.options.fetch??globalThis.fetch,x={method:s,headers:a,body:c,redirect:"manual",decompress:!1,signal:u.signal},h;try{h=await p(o.toString(),x)}catch(E){throw n.signal.removeEventListener("abort",l),E}if(h.status>=300&&h.status<400){n.signal.removeEventListener("abort",l),await h.body?.cancel();let E=_e(h.headers.get("location"));if(E)return this.deleteToken(i),{kind:"access_required",teamDomain:E};throw new t(`\u8FDC\u7A0B\u670D\u52A1\u5668\u8FD4\u56DE\u4E86\u9884\u671F\u5916\u7684\u91CD\u5B9A\u5411\uFF08HTTP ${h.status}\uFF09`)}let w=_s(h.headers);if(!h.body)return n.signal.removeEventListener("abort",l),{kind:"response",response:new Response(null,{status:h.status,statusText:h.statusText,headers:w})};let T=h.body.getReader(),M=new ReadableStream({async pull(E){try{let{done:D,value:L}=await T.read();if(D){n.signal.removeEventListener("abort",l),E.close();return}E.enqueue(L)}catch(D){throw n.signal.removeEventListener("abort",l),D}},cancel(E){return n.signal.removeEventListener("abort",l),u.abort(),T.cancel(E)}});return{kind:"response",response:new Response(M,{status:h.status,statusText:h.statusText,headers:w})}}async stop(){let e=[...this.loginTasks.values()];this.loginTasks.clear();for(let r of e)r.child.kill();await Promise.all(e.map((r)=>Promise.race([r.child.exited,Bun.sleep(1000)])))}buildStatus(e,r,n,i){let o=this.loginTasks.get(e),s=o?o.state:i?{state:"done"}:this.loginResults.get(e)??{state:"idle"};return{target:e,protected:r,...n?{teamDomain:n}:{},authenticated:i,binary:this.resolveCommand()!==void 0,login:s}}resolveCommand(){if(this.options.command&&this.options.command.length>0)return this.options.command;let e=Kt(this.options.binary);return e?[e]:void 0}async resolveToken(e){let r=this.tokens.get(e);if(se(r))return r;if(r)this.deleteToken(e);let n=this.resolveCommand();if(!n)return;let i=Date.now(),o=this.lastCliLookup.get(e)??0;if(i-o<Rs)return;this.lastCliLookup.set(e,i);try{let s=Bun.spawn([...n,"access","token",`--app=${e}`],{env:Ke(this.home),stdin:"ignore",stdout:"pipe",stderr:"ignore",windowsHide:!0}),a=setTimeout(()=>s.kill(),5000);a.unref?.();try{let[c,u]=await Promise.all([new Response(s.stdout).text(),s.exited]),l=gn(c);if(u===0&&se(l))return this.saveToken(e,l),l}finally{clearTimeout(a)}}catch{}return}saveToken(e,r){this.tokens.set(e,r),this.persist()}deleteToken(e){if(!this.tokens.delete(e))return;this.persist()}persist(){let e={};for(let[r,n]of this.tokens)if(se(n))e[r]=n;Ls(this.storePath,{tokens:e})}}function Es(e,r){if(!r.startsWith("/api/")&&r!=="/api"&&!r.startsWith("/api?"))throw new t("\u8FDC\u7A0B\u4EE3\u7406\u4EC5\u5141\u8BB8\u8BBF\u95EE /api/* \u8DEF\u5F84");let n=new URL(r,e);if(n.origin!==e||n.pathname!=="/api"&&!n.pathname.startsWith("/api/"))throw new t("\u8FDC\u7A0B\u4EE3\u7406\u8DEF\u5F84\u8D8A\u754C");return n}function Ps(e){let r=new Headers;e.forEach((i,o)=>{if(As.has(o.toLowerCase()))return;r.set(o,i)});let n=e.get(vs);if(n)r.set("authorization",n);return r}function _s(e){let r=new Headers;return e.forEach((n,i)=>{let o=i.toLowerCase();if(Ts.has(o)||o.startsWith("access-control-"))return;r.set(i,n)}),r}function gn(e){for(let r of e.split(/\r?\n/)){let n=r.trim();if(yn.test(n))return n}return}function Cs(e){return e.split(/\r?\n/).map((n)=>n.trim()).filter((n)=>n.length>0&&!n.startsWith("https://")).at(-1)}function Ms(e){if(!ps(e))return{};try{let r=JSON.parse(fs(e,"utf8"));if(!r||typeof r!=="object"||!("tokens"in r))return{};let n=r.tokens;if(!n||typeof n!=="object")return{};let i={};for(let[o,s]of Object.entries(n))if(typeof s==="string")i[o]=s;return i}catch{return{}}}function Ls(e,r){ms(e,JSON.stringify(r),{mode:384}),ds(e,384)}function Is(e){let r=e.toLowerCase().replace(/^\[|\]$/g,"");if(Ee(e)||r==="0.0.0.0"||r.endsWith(".localhost")||r.endsWith(".local"))return!0;let i=(r.startsWith("::ffff:")?r.slice(7):void 0)??r,o=gs(i);if(o===4){let s=i.split(".").map((u)=>Number(u)),a=s[0]??0,c=s[1]??0;return a===0||a===10||a===127||a===100&&c>=64&&c<=127||a===169&&c===254||a===172&&c>=16&&c<=31||a===192&&c===168}if(o===6)return i==="::"||i==="::1"||/^f[cd][0-9a-f]{0,2}:/i.test(i)||/^fe[89ab][0-9a-f]:/i.test(i);return!1}function Ie(e,r,n,i,o){let s=!0,a=new Map,c,u={id:crypto.randomUUID(),...r,sessions:n,subscriptions:n,send(l){if(!s)return;if(u.expires!==void 0&&Date.now()>=u.expires){u.close(4401,"authentication expired");return}i(l)},close(l,p){s=!1,e.connections.delete(u.id),o(l,p)},enqueue(l,p="connection"){let x=(a.get(p)??Promise.resolve()).then(async()=>{if(!s)throw new d("connection closed");await l()}),h=x.catch(()=>{});return a.set(p,h),h.then(()=>{if(a.get(p)===h)a.delete(p)}),x},dispose(){if(c)return c;s=!1,e.connections.delete(u.id);let l=[];for(let p of n){let x=e.get(p);if(x)l.push(e.plugins.notify("session.close",x,u))}return n.clear(),c=Promise.all(l).then(()=>{}),c}};return e.connections.set(u.id,u),u}async function ve(e,r,n){if(!e.connections.has(r.id))throw new d("connection closed");if(typeof n.sessionID!=="string"||!n.sessionID)throw new t("sessionID is required");if(n.type==="subscribe"){let i=e.get(n.sessionID);if(!i)throw new d("no such session");let o=e.store.truncationEpoch(i.id),s=n.after??0;if(!Number.isSafeInteger(s)||s<0||n.truncationEpoch!==void 0&&(!Number.isSafeInteger(n.truncationEpoch)||n.truncationEpoch<0))throw new t("invalid subscription cursor");let a=!r.subscriptions.has(i.id);if(r.subscriptions.add(i.id),a)await e.plugins.notify("session.open",i,r);let c=(n.truncationEpoch??0)!==o;if(c)r.send({type:"truncated",sessionID:i.id,after:0,truncationEpoch:o});let u=c?0:s,l=u===0&&n.tail&&Number.isSafeInteger(n.tail)&&n.tail>0?i.replayEntries(Math.min(n.tail,2000),!r.refImages):i.entries(u,void 0,!r.refImages),p=0,x=0;if(r.refImages)r.send({type:"replay_progress",sessionID:i.id,received:0,total:l.length});for(let[h,w]of l.entries()){if(!e.connections.has(r.id))return;if(e.store.truncationEpoch(i.id)!==o){r.close();return}if(r.send({type:"entry",sessionID:i.id,entry:w}),p+=Buffer.byteLength(JSON.stringify(w)),x++,h===0||p>=32768||x>=20||h===l.length-1){if(r.refImages)r.send({type:"replay_progress",sessionID:i.id,received:h+1,total:l.length});p=0,x=0,await new Promise((T)=>setImmediate(T)),await r.drained?.()}}if(r.send({type:"session",session:i.info(),truncationEpoch:o}),i.draft)r.send({type:"draft",sessionID:i.id,parts:i.draft});return}if(n.type==="unsubscribe"&&r.subscriptions.delete(n.sessionID)){let i=e.get(n.sessionID);if(i)await e.plugins.notify("session.close",i,r)}}import{constants as qs,createGzip as Ds}from"zlib";var Os=32,Vt=2097152,Ws=262144,Ns=20;class Ve{streams=new Map;async open(e){let r=e.runtime;if(e.index)await r.initialize();let n=Us(e.subscribe),i=this.streams,o,s,a;return new ReadableStream({start(c){let u=js(c,e.gzip,()=>o.close(1013,"client is too slow")),l=!1;a=(h=!1)=>{if(!l)l=!0,clearInterval(s),e.signal.removeEventListener("abort",x),i.delete(o.id),u.close(h);return o.dispose()};let p=(h)=>a(h).catch((w)=>console.error("SSE cleanup failed",w)),x=()=>p(!0);o=Ie(r,e.identity,new Set,(h)=>{let w=e.refImages&&h.type==="entry"?{...h,entry:r.store.refImages(h.entry)}:h;u.write(`data: ${JSON.stringify(w)}
11
+
12
+ `)},()=>p(!1)),o.refImages=e.refImages,o.drained=u.drained,i.set(o.id,o),s=setInterval(()=>u.write(`: ping
13
+
14
+ `),e.heartbeatMs??15000),e.signal.addEventListener("abort",x,{once:!0}),o.send({type:"welcome",server:e.server,connectionID:o.id,subscribed:n.map((h)=>h.sessionID),...e.index&&{index:{sessions:r.list(!0,{archive:"all"}),projects:r.projects(),plugins:r.plugins.list()}}});for(let h of n)o.enqueue(()=>ve(r,o,{...h,type:"subscribe"}),h.sessionID).catch((w)=>{if(w instanceof d&&r.get(h.sessionID)===void 0)o.send({type:"removed",kind:"session",id:h.sessionID});else o.send({type:"error",code:"bad_request",message:w instanceof Error?w.message:String(w)})});if(e.signal.aborted)x()},cancel(){return a(!0)}},{highWaterMark:Vt,size:(c)=>c?.byteLength??0})}async control(e,r,n,i){let o=this.streams.get(r);if(!o)return"not_found";if(o.deviceID!==n)return"forbidden";await o.enqueue(()=>ve(e,o,i),i.sessionID);return}}function Us(e){if(!e)return[];let r;try{r=JSON.parse(e)}catch{return[]}if(!Array.isArray(r))return[];return r.filter((n)=>typeof n?.sessionID==="string"&&n.sessionID!=="").slice(0,Os)}function js(e,r,n){let i=new TextEncoder,o=!1,s=0,a=()=>(o=!0,queueMicrotask(n),!1),c=(w)=>!o&&((e.desiredSize??0)+s>=w||a()),u=r?Ds():void 0,l=!0,p=()=>Vt-(e.desiredSize??0)+(u?.writableLength??0),x=async()=>{while(!o&&l&&p()>Ws)await Bun.sleep(Ns)};if(!u)return{drained:x,write:(w)=>{let T=i.encode(w);if(s=Math.max(s,T.byteLength),c(T.byteLength))e.enqueue(T)},close:(w)=>{if(l=!1,!w)e.close()}};let h=!1;return u.on("data",(w)=>{if(!l||!c(w.byteLength))return;try{e.enqueue(new Uint8Array(w))}catch{l=!1,u.destroy()}}),{drained:x,write(w){if(!l||u.writableEnded)return;if(s=Math.max(s,Buffer.byteLength(w)),!c(0))return;if(u.writableLength>Vt+s){a();return}if(u.write(w),h)return;h=!0,setImmediate(()=>{if(h=!1,l&&!u.writableEnded)u.flush(qs.Z_SYNC_FLUSH)})},close(w){if(w){l=!1,u.destroy();return}u.once("end",()=>{l=!1,e.close()}),u.end()}}}var $s=["connection","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"];function wn(e,r){let n=new URL(e),i=Number(n.port)+1e4,o=(c,u)=>{let l=new Headers(c.headers);if(u.startsWith("/api/"))return l;let p=l.get("host");if(p)l.set("x-forwarded-host",p);if(l.set("host",n.host),l.has("origin"))l.set("origin",n.origin);return l},s={hostname:"127.0.0.1",idleTimeout:0,async fetch(c,u){if(await r?.(c))return new Response(null,{status:403});let l=new URL(c.url),p;try{p=new URL(decodeURIComponent(l.pathname),n.origin).pathname}catch{return new Response("invalid path",{status:400})}let x=c.headers.get("upgrade")?.toLowerCase()==="websocket";if(p==="/_bun"||p.startsWith("/_bun/")||x&&!p.startsWith("/api/"))return new Response("not found",{status:404});let h=o(c,l.pathname),w=`${n.origin}${l.pathname}${l.search}`;if(c.headers.get("upgrade")?.toLowerCase()==="websocket"){for(let M of $s)h.delete(M);let T={url:w.replace(/^http/,"ws"),headers:h,pending:[]};if(u.upgrade(c,{data:T}))return;return new Response("expected websocket",{status:400})}return fetch(w,{method:c.method,headers:h,body:c.body,redirect:"manual",decompress:!1})},websocket:{open(c){let u=new WebSocket(c.data.url,{headers:Object.fromEntries(c.data.headers)});u.binaryType="arraybuffer",c.data.upstream=u,u.onopen=()=>{for(let l of c.data.pending.splice(0))u.send(l)},u.onmessage=(l)=>{c.send(l.data)},u.onclose=(l)=>{c.close(l.code===1005||l.code===1006?1011:l.code,l.reason)}},message(c,u){let l=c.data.upstream;if(l?.readyState===WebSocket.OPEN)l.send(u);else c.data.pending.push(u)},close(c,u,l){if(u===1000||u>=3000&&u<=4999)c.data.upstream?.close(u,l);else c.data.upstream?.close()}}},a;try{a=Bun.serve({...s,port:i<=65535?i:0})}catch{a=Bun.serve({...s,port:0})}return{port:a.port,stop(){a.stop(!0)}}}var Hs=["x-forwarded-for","x-forwarded-host","forwarded","cf-connecting-ip","x-real-ip"];function Qt(e){let r=e.headers.get("host");if(!r)return!1;try{return Ee(new URL(`http://${r}`).hostname)}catch{return!1}}function K(e,r){return Xt(e.requestIP(r))&&Qt(r)&&!Hs.some((n)=>r.headers.has(n))}function Xt(e){if(!e)return!1;return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}function S(e,r,n={}){return async(i)=>{let o=i.req.raw;if(await e.accessDenied?.(o))return new Response(null,{status:403});if(!e.allowed(o.headers.get("origin"),o))return A(i,"unauthorized","origin not allowed",403);if(!n.public&&e.authEnabled&&!e.internalRequest?.(o)&&!e.auth.verify(H(o)))return A(i,"unauthorized","missing or invalid token",401);if(n.localOnly&&!K(e,o))return A(i,"unauthorized","\u4EC5\u5141\u8BB8\u672C\u673A\u76F4\u8FDE\u7BA1\u7406",403);try{return await r(i)}catch(s){if(s instanceof ft)return A(i,"archived",s.message,409);if(s instanceof re)return A(i,"busy",s.message,409);if(s instanceof t)return A(i,"bad_request",s.message,400);if(s instanceof d)return A(i,"not_found",s.message,404);if(s instanceof SyntaxError)return A(i,"bad_request","invalid JSON",400);if(console.error(s),n.public)return A(i,"internal","internal server error",500);return A(i,"internal",s instanceof Error?s.message:String(s),500)}}}async function _(e){let r=await e.req.json();if(!r||typeof r!=="object"||Array.isArray(r))throw new t("expected a JSON object");return r}function I(e,r){let n=e.req.param(r);if(!n)throw new t(`${r} is required`);return n}function R(e,r,n=200){return Response.json(r,{status:n,headers:F(e)})}function A(e,r,n,i){return R(e,{error:{code:r,message:n}},i)}function Qe(e,r){let n=e.req.raw;if(!r.allowed(n.headers.get("origin"),n))return new Response(null,{status:403});let i=F(e);if(i.set("access-control-allow-methods","GET, POST, PUT, PATCH, DELETE, OPTIONS"),i.set("access-control-allow-headers",n.headers.get("access-control-request-headers")?.trim()||"authorization, content-type"),i.append("vary","access-control-request-headers"),i.set("access-control-max-age","600"),n.headers.get("access-control-request-private-network")==="true")i.set("access-control-allow-private-network","true");return new Response(null,{status:204,headers:i})}function H(e){return e.headers.get("authorization")?.replace(/^Bearer\s+/i,"")}function F(e){let r=new Headers,n=e.req.raw.headers.get("origin");if(n)r.set("access-control-allow-origin",n),r.set("vary","origin");return r}var Bs=2147483647;function Xe(e,r,n){let i=n.body;if(!i)return n;let o=i.getReader(),s=!1,a,c=()=>{},u=()=>{s=!0,clearTimeout(a),c()},l=new ReadableStream({start(p){let x=()=>{if(s)return;u(),p.close(),o.cancel("authentication ended").catch((w)=>console.error("\u5173\u95ED\u54CD\u5E94\u6D41\u5931\u8D25",w))},h=()=>{let w=r.token.expires-Date.now();if(w<=0){x();return}a=setTimeout(h,Math.min(w,Bs))};c=e.onRevoke((w)=>{if(w===r.id)x()}),h()},async pull(p){try{let{done:x,value:h}=await o.read();if(s)return;if(x){u(),p.close();return}p.enqueue(h)}catch(x){throw u(),x}},cancel(p){return u(),o.cancel(p)}});return new Response(l,{status:n.status,statusText:n.statusText,headers:n.headers})}var bn=Symbol();var vn=(e,r)=>new Response(e,{headers:{"Content-Type":r.replace(/^[^;]+/,(n)=>n.toLowerCase())}}).formData();var zs=1e4,Ye=(e)=>("headers"in e),Rn=async(e,r=Object.create(null))=>{let{all:n=!1,dot:i=!1}=r,o=(Ye(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();if(o==="multipart/form-data"||o==="application/x-www-form-urlencoded")return Js(e,{all:n,dot:i});return{}};async function Js(e,r){if(!Ye(e)&&e.bodyCache.formData)return xn(await e.bodyCache.formData,r);let n=Ye(e)?e.headers:e.raw.headers,i=await e.arrayBuffer(),o=vn(i,n.get("Content-Type")||"");if(!Ye(e))e.bodyCache.formData=o;let s=await o;if(s)return xn(s,r);return{}}function xn(e,r){let n=Object.create(null),i={count:0};if(e.forEach((o,s)=>{if(!(r.all||s.endsWith("[]")))n[s]=o;else Ks(n,s,o)}),r.dot)Object.entries(n).forEach(([o,s])=>{if(o.includes("."))Gs(n,o,s,i),delete n[o]});return n}var Ks=(e,r,n)=>{if(e[r]!==void 0)if(Array.isArray(e[r]))e[r].push(n);else e[r]=[e[r],n];else if(!r.endsWith("[]"))e[r]=n;else e[r]=[n]},Gs=(e,r,n,i)=>{if(/(?:^|\.)__proto__\./.test(r))return;let o=e,s=r.split(".",34);if(s.length>33)Sn();s.forEach((a,c)=>{if(c===s.length-1)o[a]=n;else{if(!o[a]||typeof o[a]!=="object"||Array.isArray(o[a])||o[a]instanceof File){if(i.count++>=zs)Sn();o[a]=Object.create(null)}o=o[a]}})},Sn=()=>{throw Error("Nesting limit exceeded")};var Zt=(e)=>{let r=e.split("/");if(r[0]==="")r.shift();return r},An=(e)=>{let{groups:r,path:n}=Fs(e),i=Zt(n);return Vs(i,r)},Fs=(e)=>{let r=[];return e=e.replace(/\{[^}]+\}/g,(n,i)=>{let o=`@${i}`;return r.push([o,n]),o}),{groups:r,path:e}},Vs=(e,r)=>{for(let n=r.length-1;n>=0;n--){let[i]=r[n];for(let o=e.length-1;o>=0;o--)if(e[o].includes(i)){e[o]=e[o].replace(i,r[n][1]);break}}return e},Ze={},En=(e,r)=>{if(e==="*")return"*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let i=`${e}#${r}`;if(!Ze[i])if(n[2])Ze[i]=r&&r[0]!==":"&&r[0]!=="*"?[i,n[1],new RegExp(`^${n[2]}(?=/${r})`)]:[e,n[1],new RegExp(`^${n[2]}$`)];else Ze[i]=[e,n[1],!0];return Ze[i]}return null},Pn=(e,r)=>{try{return r(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,(n)=>{try{return r(n)}catch{return n}})}},Xs=(e)=>Pn(e,decodeURI),er=(e)=>{let r=e.url,n=r.indexOf("/",r.indexOf(":")+4),i=n;for(;i<r.length;i++){let o=r.charCodeAt(i);if(o===37){let s=r.indexOf("?",i),a=r.indexOf("#",i),c=s===-1?a===-1?void 0:a:a===-1?s:Math.min(s,a),u=r.slice(n,c);return Xs(u.includes("%25")?u.replace(/%25/g,"%2525"):u)}else if(o===63||o===35)break}return r.slice(n,i)};var _n=(e)=>{let r=er(e);return r.length>1&&r.at(-1)==="/"?r.slice(0,-1):r},ce=(e,r,...n)=>{if(n.length)r=ce(r,...n);return`${e?.[0]==="/"?"":"/"}${e}${r==="/"?"":`${e?.at(-1)==="/"?"":"/"}${r?.[0]==="/"?r.slice(1):r}`}`},et=(e)=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let r=e.split("/"),n=[],i="";return r.forEach((o)=>{if(o!==""&&!/\:/.test(o))i+="/"+o;else if(/\:/.test(o))if(o.charCodeAt(o.length-1)===63){if(n.length===0&&i==="")n.push("/");else n.push(i);let s=o.slice(0,-1);i+="/"+s,n.push(i)}else i+="/"+o}),n.filter((o,s,a)=>a.indexOf(o)===s)},tt=(e)=>e.indexOf("%")!==-1?Pn(e,Ys):e,Yt=(e)=>{if(e.indexOf("+")!==-1)e=e.replace(/\+/g," ");return tt(e)},Cn=(e,r,n)=>{let i=e.indexOf("#",8);if(i!==-1)e=e.slice(0,i);let o;if(!n&&r&&r.indexOf("%")===-1&&r.indexOf("+")===-1){let c=e.indexOf("?",8);if(c===-1)return;if(!e.startsWith(r,c+1))c=e.indexOf(`&${r}`,c+1);while(c!==-1){let u=e.charCodeAt(c+r.length+1);if(u===61){let l=c+r.length+2,p=e.indexOf("&",l);return Yt(e.slice(l,p===-1?void 0:p))}else if(u==38||isNaN(u))return"";c=e.indexOf(`&${r}`,c+1)}if(o=/[%+]/.test(e),!o)return}let s=Object.create(null);o??=/[%+]/.test(e);let a=e.indexOf("?",8);while(a!==-1){let c=e.indexOf("&",a+1),u=e.indexOf("=",a);if(u>c&&c!==-1)u=-1;let l=e.slice(a+1,u===-1?c===-1?void 0:c:u);if(o)l=Yt(l);if(a=c,l==="")continue;let p;if(u===-1)p="";else if(p=e.slice(u+1,c===-1?void 0:c),o)p=Yt(p);if(n){if(!(s[l]&&Array.isArray(s[l])))s[l]=[];s[l].push(p)}else s[l]??=p}return r?s[r]:s},Mn=Cn,Ln=(e,r)=>Cn(e,r,!0),Ys=decodeURIComponent;var In=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,r="/",n=[[]]){this.raw=e,this.path=r,this.#e=n}param(e){return e?this.#r(e):this.#o()}#r(e){let r=this.#e[0][this.routeIndex]?.[1][e],n=this.#n(r);return n&&tt(n)}#o(){let e={},r=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let n of r){let i=this.#n(this.#e[0][this.routeIndex][1][n]);if(i!==void 0)e[n]=tt(i)}return e}#n(e){return this.#e[1]?this.#e[1][e]:e}query(e){return Mn(this.url,e)}queries(e){return Ln(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let r=Object.create(null);return this.raw.headers.forEach((n,i)=>{r[i]=n}),r}async parseBody(e){return Rn(this,e)}#i=(e)=>{let{bodyCache:r,raw:n}=this,i=r[e];if(i)return i;for(let o in r)return r[o].then((s)=>{if(o==="json")s=JSON.stringify(s);let a=o==="formData"?void 0:n.headers.get("content-type");return new Response(s,{headers:a?{"Content-Type":a}:void 0})[e]()});return r[e]=n[e]()};json(){return this.#i("text").then((e)=>JSON.parse(e))}text(){return this.#i("text")}arrayBuffer(){return this.#i("arrayBuffer")}bytes(){return this.#i("arrayBuffer").then((e)=>new Uint8Array(e))}blob(){return this.#i("blob")}formData(){return this.#i("formData")}addValidatedData(e,r){(this.#t??={})[e]=r}valid(e){return this.#t?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[bn](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var qn={Stringify:1,BeforeStream:2,Stream:3},Zs=(e,r)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=r,n};var tr=async(e,r,n,i,o)=>{if(typeof e==="object"&&!(e instanceof String)){if(!(e instanceof Promise))e=e.toString();if(e instanceof Promise)e=await e}let s=e.callbacks;if(!s?.length)return Promise.resolve(e);if(o)o[0]+=e;else o=[e];let a=Promise.all(s.map((c)=>c({phase:r,buffer:o,context:i}))).then((c)=>Promise.all(c.filter(Boolean).map((u)=>tr(u,r,!1,i,o))).then(()=>o[0]));if(n)return Zs(await a,s);else return a};var ea="text/plain; charset=UTF-8",rr=(e,r)=>({"Content-Type":e,...r}),qe=(e,r)=>new Response(e,r),nr=class{#t;#e;env={};#r;finalized=!1;error;#o;#n;#i;#l;#c;#u;#a;#d;#p;constructor(e,r){if(this.#t=e,r)this.#n=r.executionCtx,this.env=r.env,this.#u=r.notFoundHandler,this.#p=r.path,this.#d=r.matchResult}get req(){return this.#e??=new In(this.#t,this.#p,this.#d),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;else throw Error("This context has no ExecutionContext")}get res(){return this.#i||=qe(null,{headers:this.#a??=new Headers})}set res(e){if(this.#i&&e){e=qe(e.body,e);for(let[r,n]of this.#i.headers.entries()){if(r==="content-type")continue;if(r==="set-cookie"){let i=this.#i.headers.getSetCookie();e.headers.delete("set-cookie");for(let o of i)e.headers.append("set-cookie",o)}else e.headers.set(r,n)}}this.#i=e,this.finalized=!0}render=(...e)=>(this.#c??=(r)=>this.html(r),this.#c(...e));setLayout=(e)=>this.#l=e;getLayout=()=>this.#l;setRenderer=(e)=>{this.#c=e};header=(e,r,n)=>{if(this.finalized)this.#i=qe(this.#i.body,this.#i);let i=this.#i?this.#i.headers:this.#a??=new Headers;if(r===void 0)i.delete(e);else if(n?.append)i.append(e,r);else i.set(e,r)};status=(e)=>{this.#o=e};set=(e,r)=>{this.#r??=new Map,this.#r.set(e,r)};get=(e)=>this.#r?this.#r.get(e):void 0;get var(){if(!this.#r)return{};return Object.fromEntries(this.#r)}#s(e,r,n){let i=this.#i?new Headers(this.#i.headers):this.#a;if(typeof r==="object"&&r.headers){i??=new Headers;for(let[s,a]of new Headers(r.headers))if(s==="set-cookie")i.append(s,a);else i.set(s,a)}if(n){if(!i){let s=0;for(let a in n)if(++s>1||typeof n[a]!=="string"){i=new Headers;break}}if(i)for(let s in n){let a=n[s];if(typeof a==="string")i.set(s,a);else{i.delete(s);for(let c of a)i.append(s,c)}}}let o=typeof r==="number"?r:r?.status??this.#o;return qe(e,{status:o,headers:i??n})}newResponse=(...e)=>this.#s(...e);body=(e,r,n)=>this.#s(e,r,n);text=(e,r,n)=>!this.#a&&!this.#o&&!r&&!n&&!this.finalized?new Response(e):this.#s(e,r,rr(ea,n));json=(e,r,n)=>this.#s(JSON.stringify(e),r,rr("application/json",n));html=(e,r,n)=>{let i=(o)=>this.#s(o,r,rr("text/html; charset=UTF-8",n));return typeof e==="object"?tr(e,qn.Stringify,!1,{}).then(i):i(e)};redirect=(e,r)=>{let n=String(e);return this.header("Location",!/[^\x00-\xFF]/.test(n)?n:encodeURI(n)),this.newResponse(null,r??302)};notFound=()=>(this.#u??=()=>qe(),this.#u(this))};var ir=(e,r,n)=>(i,o)=>{let s=-1;return a(0);async function a(c){if(c<=s)throw Error("next() called multiple times");s=c;let u,l=!1,p;if(e[c])p=e[c][0][0],i.req.routeIndex=c;else p=c===e.length&&o||void 0;if(p)try{u=await p(i,()=>a(c+1))}catch(x){if(x instanceof Error&&r)i.error=x,u=await r(x,i),l=!0;else throw x}else if(i.finalized===!1&&n)u=await n(i);if(u&&(i.finalized===!1||l))i.res=u;return i}};var Dn=["get","post","put","delete","options","patch","query"],rt="Can not add a route since the matcher is already built.",nt=class extends Error{};var On="__COMPOSED_HANDLER";var ta=(e)=>e.text("404 Not Found",404),Wn=(e,r)=>{if("getResponse"in e){let n=e.getResponse();return r.newResponse(n.body,n)}return console.error(e),r.text("Internal Server Error",500)},Nn=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(r={}){[...Dn,"all"].forEach((o)=>{this[o]=(s,...a)=>{let c=o.toUpperCase();if(typeof s==="string")this.#t=s;else this.#o(c,this.#t,s);return a.forEach((u)=>{this.#o(c,this.#t,u)}),this}}),this.on=(o,s,...a)=>{for(let c of[s].flat()){this.#t=c;for(let u of[o].flat()){let l=u.toUpperCase();for(let p of a)this.#o(l,this.#t,p)}}return this},this.use=(o,...s)=>{if(typeof o==="string")this.#t=o;else this.#t="*",s.unshift(o);return s.forEach((a)=>{this.#o("ALL",this.#t,a)}),this};let{strict:n,...i}=r;Object.assign(this,i),this.getPath=n??!0?r.getPath??er:_n}#e(){let r=new e({router:this.router,getPath:this.getPath});return r.errorHandler=this.errorHandler,r.#r=this.#r,r.routes=this.routes,r}#r=ta;errorHandler=Wn;route(r,n){let i=this.basePath(r);return n.routes.map((o)=>{let s;if(n.errorHandler===Wn)s=o.handler;else s=async(a,c)=>(await ir([],n.errorHandler)(a,()=>o.handler(a,c))).res,s[On]=o.handler;i.#o(o.method,o.path,s,o.basePath)}),this}basePath(r){let n=this.#e();return n._basePath=ce(this._basePath,r),n}onError=(r)=>(this.errorHandler=r,this);notFound=(r)=>(this.#r=r,this);mount(r,n,i){let o,s;if(i)if(typeof i==="function")s=i;else if(s=i.optionHandler,i.replaceRequest===!1)o=(u)=>u;else o=i.replaceRequest;let a=s?(u)=>{let l=s(u);return Array.isArray(l)?l:[l]}:(u)=>{let l=void 0;try{l=u.executionCtx}catch{}return[u.env,l]};o||=(()=>{let u=ce(this._basePath,r),l=u==="/"?0:u.length;return(p)=>{let x=new URL(p.url);return x.pathname=this.getPath(p).slice(l)||"/",new Request(x,p)}})();let c=async(u,l)=>{let p=await n(o(u.req.raw),...a(u));if(p)return p;await l()};return this.#o("ALL",ce(r,"*"),c),this}#o(r,n,i,o){n=ce(this._basePath,n);let s={basePath:o!==void 0?ce(this._basePath,o):this._basePath,path:n,method:r,handler:i};this.router.add(r,n,[i,s]),this.routes.push(s)}#n(r,n){if(r instanceof Error)return this.errorHandler(r,n);throw r}#i(r,n,i,o){if(o==="HEAD")return(async()=>new Response(null,await this.#i(r,n,i,"GET")))();let s=this.getPath(r,{env:i}),a=this.router.match(o,s),c=new nr(r,{path:s,matchResult:a,env:i,executionCtx:n,notFoundHandler:this.#r});if(a[0].length===1){let l;try{l=a[0][0][0][0](c,async()=>{c.res=await this.#r(c)})}catch(p){return this.#n(p,c)}return l instanceof Promise?l.then((p)=>p||(c.finalized?c.res:this.#r(c))).catch((p)=>this.#n(p,c)):l??this.#r(c)}let u=ir(a[0],this.errorHandler,this.#r);return(async()=>{try{let l=await u(c);if(!l.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#n(l,c)}})()}fetch=(r,...n)=>this.#i(r,n[1],n[0],r.method);request=(r,n,i,o)=>{if(r instanceof Request)return this.fetch(n?new Request(r,n):r,i,o);return r=r.toString(),this.fetch(new Request(/^https?:\/\//.test(r)?r:`http://localhost${ce("/",r)}`,n),i,o)};fire=()=>{addEventListener("fetch",(r)=>{r.respondWith(this.#i(r.request,r,void 0,r.request.method))})}};var j=()=>Object.create(null);var it=[];function or(e,r){let n=this.buildAllMatchers(),i=(o,s)=>{let a=n[o]||n.ALL,c=a[2][s];if(c)return c;let u=s.match(a[0]);if(!u)return[[],it];let l=u.indexOf("",1);return[a[1][l],u]};return this.match=i,i(e,r)}var sr="[^/]+";var ar="(?:|/.*)",ue=Symbol(),Un=new Set(".\\+*[^]$()");function ra(e,r){if(e.length===1)return r.length===1?e<r?-1:1:-1;if(r.length===1)return 1;if(e===".*"||e==="(?:|/.*)")return r==="(?:|/.*)"?-1:1;else if(r===".*"||r==="(?:|/.*)")return-1;if(e==="[^/]+")return 1;else if(r==="[^/]+")return-1;return e.length===r.length?e<r?-1:1:r.length-e.length}var $n=class e{#t;#e;#r=j();insert(r,n,i,o,s){let a=this;for(let c=0,u=r.length;c<u;c++){let l=r[c],p=l.length===1?l==="*"?c===u-1?["","",".*"]:["","",sr]:null:l==="/*"?["","",ar]:l.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),x;if(p){let h=p[1],w=p[2]||"[^/]+";if(h&&p[2]){if(w===".*")throw ue;if(w=w.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(w))throw ue;if(w.length===1&&Un.has(w))throw ue}if(x=a.#r[w],!x){if(w!==".*"&&w!=="(?:|/.*)"){for(let T in a.#r)if((w.length>1||T.length>1)&&T!==".*"&&T!=="(?:|/.*)")throw ue}x=a.#r[w]=new e}if(h!=="")x.#e??=o.varIndex++,i.push([h,x.#e])}else if(x=a.#r[l],!x){for(let h in a.#r)if(h.length>1&&h!==".*"&&h!=="(?:|/.*)")throw ue;x=a.#r[l]=new e}a=x}if(a.#t!==void 0)throw ue;a.#t=s?-1:n}buildRegExpStr(){let r=Object.keys(this.#r).sort(ra).map((n)=>{let i=this.#r[n],o=i.buildRegExpStr();return o===""?"":(typeof i.#e==="number"?`(${n})@${i.#e}`:Un.has(n)?`\\${n}`:n)+o}).filter(Boolean);if(typeof this.#t==="number"&&this.#t!==-1)r.unshift(`#${this.#t}`);if(r.length===0)return"";if(r.length===1)return r[0];return"(?:"+r.join("|")+")"}};var cr=class{#t={varIndex:0};#e=new $n;#r=0;paths=j();insert(e,r){if(r){this.#e.insert(e.split(""),0,[],this.#t,!0);return}let n=[],i=[],o=e;for(let a=0;;){let c=!1;if(o=o.replace(/\{[^}]+\}/g,(u)=>{let l=`@\\${a}`;return i[a]=[l,u],a++,c=!0,l}),!c)break}let s=o.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let a=i.length-1;a>=0;a--){let[c]=i[a];for(let u=s.length-1;u>=0;u--)if(s[u].indexOf(c)!==-1){s[u]=s[u].replace(c,i[a][1]);break}}this.#e.insert(s,this.#r,n,this.#t,!1),this.paths[e]=[this.#r++,n]}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let r=0,n=[],i=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,a)=>{if(s!==void 0)return n[++r]=Number(s),"$()";if(a!==void 0)return i[Number(a)]=++r,"";return""}),[new RegExp(`^${e}`),n,i]}};var Hn=j();function Bn(e){return Hn[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(r,n)=>n?`\\${n}`:r==="/*"?ar:r==="*"?".*":`/:${sr}`)}$`)}function st(e,r){for(let n of Object.keys(e).sort((i,o)=>o.length-i.length))if(Bn(n).test(r))return[...e[n]]}var at=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={["ALL"]:j()},this.#e={["ALL"]:j()},this.#r={["ALL"]:new cr}}#o(e,r){try{this.#r[e].insert(r,!/\*|\/:/.test(r))}catch(n){throw n===ue?new nt(r):n}}add(e,r,n){let i=this.#t,o=this.#e;if(!i)throw Error(rt);if(!i[e]){this.#r[e]=new cr;for(let c of[i,o]){c[e]=j();for(let u in c.ALL)c[e][u]=[...c.ALL[u]],this.#o(e,u)}}if(r==="/*")r="*";let s=e==="ALL"?Object.keys(i):[e];if(/\*$/.test(r)){let c=Bn(r);for(let u of s)if(!i[u][r])this.#o(u,r),i[u][r]=st(i[u],r)||st(i.ALL,r)||[];for(let u of[i,o])for(let l of s)for(let p in u[l])c.test(p)&&u[l][p].push([n,r]);return}let a=et(r)||[r];for(let c of a)for(let u of s){if(!o[u][c])this.#o(u,c),o[u][c]=st(i[u],c)||st(i.ALL,c)||[];o[u][c].push([n,c])}}match=or;buildAllMatchers(){let e=j();for(let r of Object.keys(this.#e))e[r]=this.#n(r);return this.#t=this.#e=this.#r=void 0,Hn=j(),e}#n(e){let r=this.#t[e],n=this.#e[e],i=this.#r[e],o=j(),s=[],[a,c,u]=i.buildRegExp();for(let l of[r,n])for(let p in l){let x=l[p],h=i.paths[p];if(!h){o[p]=[x.map(([w])=>[w,j()]),it];continue}s[h[0]]=x.map(([w,T])=>[w,i.paths[T][1].reduceRight((M,[E],D)=>(M[E]=u[h[1][D][1]],M),j())])}return[a,c.map((l)=>s[l]),o]}};var zn=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,r,n){if(!this.#e)throw Error(rt);this.#e.push([e,r,n])}match(e,r){if(!this.#e)throw Error("Fatal error");let n=this.#t,i=this.#e,o=n.length,s=0,a;for(;s<o;s++){let c=n[s];try{for(let u=0,l=i.length;u<l;u++)c.add(...i[u]);a=c.match(e,r)}catch(u){if(u instanceof nt)continue;throw u}this.match=c.match.bind(c),this.#t=[c],this.#e=void 0;break}if(s===o)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,a}get activeRouter(){if(this.#e||this.#t.length!==1)throw Error("No active router has been determined yet.");return this.#t[0]}};var ur=j(),na=0,Jn=class e{#t=[];#e=j();#r=[];#o;#n=ur;insert(r,n,i){let o=this,s=An(n),a=new Set,c=0;for(let u of s){let l=s[++c],p=En(u,l)||(l===void 0&&u&&u.indexOf("*")===u.length-1?u:null),x=Array.isArray(p),h=x?p[0]:p||u,w=o.#e[h]||=new e;if(p&&!w.#o)w.#o=p,o.#r.push(w);if(o=w,x)a.add(p[1])}o.#t.push({[r]:{handler:i,possibleKeys:[...a],score:++na}})}#i(r,n,i,o,s){for(let a=0,c=n.#t.length;a<c;a++){let u=n.#t[a],l=u[i]||u.ALL;if(l){l.params=j(),r.push(l);for(let p=0,x=l.possibleKeys.length;p<x;p++){let h=l.possibleKeys[p];l.params[h]=s?.[h]&&!p?s[h]:o[h]??s?.[h]}}}}search(r,n){let i=[];this.#n=ur;let o=[this],s=Zt(n),a=[],c=s.length,u=null;for(let l=0;l<c;l++){let p=s[l],x=l===c-1,h=[];for(let T=0,M=o.length;T<M;T++){let E=o[T],D=E.#e[p];if(D)if(D.#n=E.#n,x){if(D.#e["*"])this.#i(i,D.#e["*"],r,E.#n);this.#i(i,D,r,E.#n)}else h.push(D);for(let L of E.#r){let N=L.#o,U=E.#n===ur?{}:{...E.#n};if(typeof N==="string"){if(N==="*"||p.startsWith(N.slice(0,-1))){if(this.#i(i,L,r,E.#n),N==="*")L.#n=U,h.push(L)}continue}let[,G,ie]=N;if(!p&&ie===!0)continue;if(ie!==!0){if(!u){u=[];let Se=n[0]==="/"?1:0;for(let X=0;X<c;X++)u[X]=Se,Se+=s[X].length+1}let xe=n.slice(u[l]),le=ie.exec(xe);if(le){if(U[G]=le[0],this.#i(i,L,r,E.#n,U),le[0].length===xe.length&&L.#e["*"])this.#i(i,L.#e["*"],r,E.#n,U);for(let Se in L.#e){L.#n=U;let X=le[0].match(/\//g)?.length??0;(a[X]||=[]).push(L);break}continue}}if(ie===!0||ie.test(p))if(U[G]=p,x){if(this.#i(i,L,r,U,E.#n),L.#e["*"])this.#i(i,L.#e["*"],r,U,E.#n)}else L.#n=U,h.push(L)}}let w=a.shift();o=w?h.concat(w):h}if(i[1])i.sort((l,p)=>l.score-p.score);return[i.map(({handler:l,params:p})=>[l,p])]}};var lr=class{name="TrieRouter";#t=new Jn;add(e,r,n){for(let i of et(r)||[r])this.#t.insert(e,i,n)}match(e,r){return this.#t.search(e,r)}};var q=class extends Nn{constructor(e={}){super(e);this.router=e.router??new zn({routers:[new at,new lr]})}};var Gn=(e)=>e===32||e===9||e===10||e===13,ct=(e,r)=>{while(r<e.length){if(!Gn(e.charCodeAt(r)))break;r++}return r},De=(e,r)=>{while(r>0){if(!Gn(e.charCodeAt(r-1)))break;r--}return r},Kn=(e,r)=>{while(r<e.length){let n=e.charCodeAt(r);if(n===59)return[r+1,!0];if(n===44)return[r+1,!1];r++}return[r,!1]},ia=(e,r)=>{let n=r,i=!1;while(n<e.length){let o=e.charCodeAt(n);if(i&&o===92)n++;else if(o===34)i=!i;else if(!i&&o===44)return n+1;n++}return n},oa=(e,r)=>{r=ct(e,r);let n=r,i,o,s=!1;while(n<e.length){let u=e.charCodeAt(n);if(u===61){i=e.slice(r,De(e,n)),n++;break}if(u===59)return[n+1,void 0,void 0,!0];if(u===44)return[n+1,void 0,void 0,!1];n++}if(i===void 0)return[n,void 0,void 0,!1];if(n=ct(e,n),e.charCodeAt(n)===61){let u=Kn(e,n+1);return[u[0],i,void 0,u[1]]}let a=!1,c=n;while(n<e.length){let u=e.charCodeAt(n);if(a&&u===92)n++;else if(u===34){if(a){let l=ct(e,n+1),p=e.charCodeAt(l);if(l<e.length&&!(p===59||p===44)){let x=Kn(e,l);return[x[0],i,void 0,x[1]]}if(o=e.slice(c+1,n),o.includes("\\"))o=o.replace(/\\(.)/g,"$1");if(p===44)return[l+1,i,o,!1];if(p===59)s=!0,l++;n=l;break}a=!0}else if(!a&&(u===59||u===44)){if(o=e.slice(c,De(e,n)),u===59)s=!0;n++;break}n++}return[n,i,o??e.slice(c,De(e,n)),s]},sa=(e,r)=>{let n={type:"",params:Object.create(null),q:1};r=ct(e,r);let i=r;while(i<e.length){let c=e.charCodeAt(i);if(c===59||c===44){if(n.type=e.slice(r,De(e,i)),i++,c===44)return[i,n.type?n:void 0];if(!n.type)return[ia(e,i),void 0];break}i++}if(!n.type)return n.type=e.slice(r,De(e,e.length)),[e.length,n.type?n:void 0];let o,s,a;while(i<e.length){if([i,o,s,a]=oa(e,i),o&&s)n.params[o]=s;if(!a)break}return[i,n]},Fn=(e)=>{if(!e)return[];let r=[],n=0,i,o=!1,s;while(n<e.length)if([n,i]=sa(e,n),i){if(i.q=aa(i.params.q??i.params.Q),r.push(i),s&&s.q<i.q)o=!0;s=i}if(o)r.sort((a,c)=>c.q-a.q);return r},aa=(e)=>{if(e===void 0)return 1;if(e==="")return 1;if(e==="NaN")return 0;let r=Number(e);if(Number.isNaN(r))return 1;if(r<0)return 0;if(r>1)return 1;return r};var Vn=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|msgpack|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|vnd\.msgpack|wasm|x-httpd-php|x-javascript|x-msgpack|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml|msgpack))(?:[;\s]|$)/i;var ua=["gzip","deflate"],la=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,da=(e,r)=>{if(e===void 0)return;let n=Fn(e),i=n.find((s)=>s.type==="*")?.q,o;for(let s of r){let a=n.find((u)=>u.type.toLowerCase()===s),c=a?a.q:i??0;if(c===1)return s;else if(c>0&&(!o||c>o.q))o={encoding:s,q:c}}return o?.encoding},pa=/(?:^|,)\s*accept-encoding\s*(?:,|$)/i,Qn=(e)=>{let r=e?.threshold??1024,n=e?.encoding?[e.encoding]:ua,i=e?.contentTypeFilter??Vn,o=typeof i==="function"?(s)=>{let a=s.headers.get("Content-Type");return a&&i(a)}:(s)=>{let a=s.headers.get("Content-Type");return a&&i.test(a)};return async function(a,c){await c();let u=a.res.headers.get("Content-Length");if(a.res.status===206||a.res.headers.has("Content-Encoding")||a.res.headers.has("Transfer-Encoding")||a.req.method==="HEAD"||u&&Number(u)<r||!o(a.res)||!ha(a.res))return;let l=a.res.headers.get("Vary");if(l!=="*"&&!(l&&pa.test(l)))a.header("Vary",l?`${l}, Accept-Encoding`:"Accept-Encoding");let p=a.req.header("Accept-Encoding"),x=da(p,n);if(!x||!a.res.body)return;let h=new CompressionStream(x);a.res=new Response(a.res.body.pipeThrough(h),a.res),a.res.headers.delete("Content-Length"),a.res.headers.set("Content-Encoding",x);let w=a.res.headers.get("ETag");if(w&&!w.startsWith("W/"))a.res.headers.set("ETag",`W/${w}`)}},ha=(e)=>{let r=e.headers.get("Cache-Control");return!r||!la.test(r)};import{timingSafeEqual as Zn}from"crypto";function ei(e){let r=new q,n=!1;return r.post("/pair",S(e,async(i)=>{let o=await _(i),s=i.req.raw,a=e.requestIP(s),c=Xt(a)&&e.tunnel?.running()?s.headers.get("cf-connecting-ip"):null,u=c?`tunnel:${c}`:a??"unknown",l=e.auth.pair(String(o.code??""),String(o.device??""),u);if(!l)return A(i,"unauthorized","invalid or expired pairing code",401);return R(i,l)},{public:!0})),r.post("/pair/approve",S(e,async(i)=>{let o=i.req.raw.headers.get("origin")??void 0;if(!o||!e.approveLocalPairing||!K(e,i.req.raw)||!e.allowed(o,i.req.raw,{wildcard:!1}))return A(i,"unauthorized","local approval not available",403);if(n)throw new re("local approval already in progress");let s=await _(i),a=String(s.device??"").trim()||"Browser";n=!0,e.disableTimeout?.(i.req.raw);try{if(!await e.approveLocalPairing({device:a,origin:o}))return A(i,"unauthorized","local approval rejected",403);if(i.req.raw.signal.aborted)return A(i,"unauthorized","local approval request was closed",403);return R(i,e.auth.issue(a))}finally{n=!1}},{public:!0})),r.post("/pair/code",S(e,(i)=>{let o=i.req.raw,s=e.cliSecret?Buffer.from(e.cliSecret):void 0,a=Buffer.from(H(o)??"");if(!s||o.headers.has("origin")||!K(e,o)||s.length!==a.length||!Zn(s,a))return A(i,"unauthorized","pairing code is only available to the local CLI",403);if(!e.authEnabled)return A(i,"bad_request","authentication is disabled, no pairing needed",400);let c=e.auth.renewPairingCode();return R(i,{code:c,expires:e.auth.pairingExpires()})},{public:!0})),r.post("/server/shutdown",S(e,(i)=>{let o=i.req.raw,s=e.cliSecret?Buffer.from(e.cliSecret):void 0,a=Buffer.from(H(o)??"");if(!s||o.headers.has("origin")||!K(e,o)||s.length!==a.length||!Zn(s,a))return A(i,"unauthorized","shutdown is only available to the local CLI",403);if(!e.shutdown)return A(i,"not_found","shutdown is unavailable",404);return e.shutdown(),R(i,{ok:!0})},{public:!0})),r.get("/pair/current",S(e,(i)=>{if(!e.authEnabled)return A(i,"bad_request","authentication is disabled, no pairing needed",400);let o=e.auth.pairingCode();return R(i,{code:o,expires:e.auth.pairingExpires()})},{localOnly:!0})),r.post("/pair/current",S(e,(i)=>{if(!e.authEnabled)return A(i,"bad_request","authentication is disabled, no pairing needed",400);let o=e.auth.renewPairingCode();return R(i,{code:o,expires:e.auth.pairingExpires()})},{localOnly:!0})),r.get("/devices",S(e,(i)=>{let o=e.auth.verify(H(i.req.raw))?.id;return R(i,e.auth.list().map((s)=>s.id===o?{...s,current:!0}:s))},{localOnly:!0})),r.delete("/devices/:id",S(e,(i)=>e.auth.revoke(I(i,"id"))?R(i,{ok:!0}):A(i,"not_found","no such device",404),{localOnly:!0})),r}function ti(e){let r=new q,n=new Ve,i=(o)=>e.authEnabled?e.auth.verify(H(o)):void 0;r.get("/events",S(e,async(o)=>{if(o.req.query("protocol")!==String(vr))return A(o,"protocol_mismatch",`server speaks protocol ${vr}`,400);let s=o.req.raw,a=i(s),c=/\bgzip\b/i.test(s.headers.get("accept-encoding")??""),u=await n.open({runtime:e.runtime,identity:{deviceID:a?.id,expires:a?.token.expires},server:{...e.info,localManagement:K(e,s)},index:o.req.query("index")==="1",subscribe:o.req.query("subscribe"),refImages:o.req.query("images")==="ref",gzip:c,heartbeatMs:e.heartbeatMs,signal:s.signal});e.disableTimeout?.(s);let l=F(o);if(l.set("content-type","text/event-stream"),l.set("cache-control","no-cache, no-transform"),l.set("x-accel-buffering","no"),c)l.set("content-encoding","gzip"),l.set("vary","accept-encoding");return new Response(u,{headers:l})}));for(let o of["subscribe","unsubscribe"])r.post(`/events/:connectionID/${o}`,S(e,async(s)=>{let a=await _(s),c=await n.control(e.runtime,I(s,"connectionID"),i(s.req.raw)?.id,{...a,type:o});if(c==="not_found")return A(s,"not_found","no such connection",404);if(c==="forbidden")return A(s,"unauthorized","connection belongs to another device",403);return new Response(null,{status:204,headers:F(s)})}));return r}function ri(e){let r=new q;return r.get("/folding/settings",S(e,(n)=>R(n,{digestModel:e.runtime.digestModel()}))),r.put("/folding/settings",S(e,async(n)=>{let i=await n.req.json();if(!i||typeof i!=="object"||!("digestModel"in i)||i.digestModel!==null&&typeof i.digestModel!=="string")return A(n,"bad_request","digestModel must be a model id or null",400);return R(n,{digestModel:e.runtime.setDigestModel(i.digestModel)})})),r}import{homedir as fa}from"os";import{resolve as dr}from"path";async function ii(e,r,n){if(!n){let i=dr(process.cwd());return ni(e.host(),dr(r?.trim()||i),"on the server",[{name:"\u5DE5\u4F5C\u533A",path:i},{name:"\u7528\u6237\u76EE\u5F55",path:dr(fa())}])}try{return await e.withSshHost(n,async(i)=>{let o=i.info.home,s=r?.trim()||"~",a=s==="~"||s.startsWith("~/")?o+s.slice(1):s,c=de(i).resolve(o,a);return await ni(i,c,`on ${n}`,[{name:"\u7528\u6237\u76EE\u5F55",path:o},{name:"\u6839\u76EE\u5F55",path:de(i).parse(o).root}])})}catch(i){throw new t(`cannot browse ${n}: ${i instanceof Error?i.message:i}`)}}async function ni(e,r,n,i){let o=await e.readdir(r).catch(()=>{throw new t(`${r} is not a readable directory ${n}`)}),s=de(e).dirname(r);return{path:r,parent:s===r?null:s,entries:o.filter((a)=>a.directory).map((a)=>({name:a.name,path:de(e).join(r,a.name)})).sort((a,c)=>a.name.localeCompare(c.name,void 0,{numeric:!0,sensitivity:"base"})),shortcuts:i.filter((a,c)=>i.findIndex((u)=>u.path===a.path)===c)}}import{globSync as ma,readFileSync as ga}from"fs";import{homedir as ya}from"os";import{isAbsolute as wa,join as pr}from"path";function si(e=ya()){let r=new Map;for(let n of ai(pr(e,".ssh","config"),e,new Set))r.set(n.name,n);for(let n of ba(pr(e,".ssh","known_hosts")))if(!r.has(n))r.set(n,{name:n,source:"known_hosts"});return[...r.values()]}function ai(e,r,n){if(n.has(e))return[];n.add(e);let i=[],o=[];for(let s of ci(e).split(`
15
+ `)){let a=/^\s*(\w+)\s*(?:=\s*|\s+)(.+?)\s*$/.exec(s);if(!a?.[1]||!a[2]||s.trimStart().startsWith("#"))continue;let c=a[1].toLowerCase(),u=a[2].split(/\s+/).map((l)=>l.replace(/^"|"$/g,""));if(c==="host")o=u.filter((l)=>!/[*?!]/.test(l)).map((l)=>({name:l,source:"config"})),i.push(...o);if(c==="match")o=[];if(c==="hostname")for(let l of o)l.hostname=u[0];if(c==="user")for(let l of o)l.user=u[0];if(c==="include")for(let l of u){let p=l.replace(/^~(?=\/|$)/,r),x=wa(p)?p:pr(r,".ssh",p);for(let h of ma(x).sort())i.push(...ai(h,r,n))}}return i}function ba(e){return ci(e).split(`
16
+ `).flatMap((r)=>r.startsWith("#")||r.startsWith("@")?[]:r.split(/\s/)[0]?.split(",")??[]).filter((r)=>r&&!r.startsWith("|")).map((r)=>r.replace(/^\[(.+)\]:\d+$/,"$1"))}function ci(e){try{return ga(e,"utf8")}catch{return""}}function ui(e){let r=new q;return r.get("/info",S(e,(n)=>{e.info.shell=e.runtime.serverShell();let i=e.authEnabled&&e.approveLocalPairing!==void 0&&K(e,n.req.raw);return R(n,{...!e.authEnabled||e.auth.verify(H(n.req.raw))?e.info:{name:e.info.name,auth:e.info.auth},localManagement:K(e,n.req.raw),...i?{localApproval:!0}:{}})},{public:!0})),r.get("/health",S(e,async(n)=>{if(!K(e,n.req.raw))return A(n,"unauthorized","loopback only",403);let{models:i}=await e.runtime.models(),o=i.filter((u)=>u.available===!0).length,s=e.runtime.list(!0),a=s.filter((u)=>u.status==="busy").length,c=0;for(let u of s)c+=e.runtime.get(u.id)?.runningTools??0;if(o===0)return R(n,{ready:!1,availableModels:o,busySessions:a,runningTools:c},503);return R(n,{ready:!0,availableModels:o,busySessions:a,runningTools:c})},{public:!0})),r.get("/server/autostart",S(e,(n)=>{if(!e.autostart)return A(n,"not_found","\u5F53\u524D\u670D\u52A1\u5165\u53E3\u4E0D\u652F\u6301\u767B\u5F55\u81EA\u542F",404);return R(n,e.autostart.status())})),r.put("/server/autostart",S(e,async(n)=>{if(!e.autostart)return A(n,"not_found","\u5F53\u524D\u670D\u52A1\u5165\u53E3\u4E0D\u652F\u6301\u767B\u5F55\u81EA\u542F",404);let i=await _(n);if(typeof i.enabled!=="boolean")return A(n,"bad_request","enabled \u5FC5\u987B\u662F\u5E03\u5C14\u503C",400);return R(n,e.autostart.set(i.enabled))})),r.post("/server/restart",S(e,(n)=>{if(!e.restart)return A(n,"not_found","\u5F53\u524D\u670D\u52A1\u5165\u53E3\u4E0D\u652F\u6301\u91CD\u542F",404);return e.restart(),R(n,{restarting:!0},202)})),r.patch("/server/shell",S(e,async(n)=>{let i=await _(n),o=e.runtime.setServerShell(i.shell);return e.info.shell=o,R(n,{shell:o})})),r.get("/models",S(e,async(n)=>R(n,await e.runtime.models()))),r.get("/directories",S(e,async(n)=>R(n,await ii(e.runtime,n.req.query("path"),n.req.query("remote"))),{public:!1})),r.get("/ssh/hosts",S(e,(n)=>R(n,si()),{public:!1})),r.get("/storage",S(e,(n)=>R(n,e.runtime.storage(n.req.query("detailed")==="true")))),r.post("/storage/compact",S(e,async(n)=>{let i=await _(n);return R(n,await e.runtime.compactStorage({checkpoint:i.checkpoint===!0,vacuum:i.vacuum===!0}))})),r}function li(e){let r=new q,n=e.modelProviders;if(!n)return r;return r.get("/model-providers",S(e,(i)=>R(i,n.list()))),r.put("/model-providers/:id",S(e,async(i)=>{let o=await n.save(I(i,"id"),await _(i));return R(i,o)})),r.post("/model-providers/:id/discover",S(e,async(i)=>R(i,await n.discover(I(i,"id"))))),r.delete("/model-providers/:id",S(e,async(i)=>await n.remove(I(i,"id"))?R(i,{ok:!0}):A(i,"not_found","no such model provider",404))),r}function di(e){let r=new q;return r.get("/server/network",S(e,(n)=>{if(!e.network)return A(n,"not_found","network settings unavailable",404);return R(n,e.network.manager.configuration(e.network.runtime()))},{localOnly:!0})),r.put("/server/network",S(e,async(n)=>{if(!e.network)return A(n,"not_found","network settings unavailable",404);let i=e.network.manager.configuration(e.network.runtime());if(!i.editable)return A(n,"unauthorized",i.disabledReason??"network settings are read-only",403);let o=await _(n),s=n.req.raw;if(!e.internalRequest?.(s)&&!e.auth.verify(H(s)))return A(n,"unauthorized","authentication expired or revoked",403);return e.network.save(o),R(n,e.network.manager.configuration(e.network.runtime()))},{localOnly:!0})),r}function pi(e){let r=new q;return r.get("/plugins",S(e,async(n)=>(await e.runtime.initialize(),R(n,e.runtime.plugins.list())))),r.post("/plugins/load",S(e,async(n)=>{let i=await _(n);if(typeof i.path!=="string"||!i.path||i.path.length>4096)throw new t("path must be a non-empty plugin file path");return await e.runtime.initialize(),await e.runtime.plugins.load(i.path),R(n,e.runtime.plugins.list())})),r.post("/plugins/:id/reload",S(e,async(n)=>(await e.runtime.initialize(),await e.runtime.plugins.reload(I(n,"id")),R(n,e.runtime.plugins.list())))),r.patch("/plugins/:id",S(e,async(n)=>{let i=await _(n);if(typeof i.enabled!=="boolean")throw new t("enabled must be a boolean");return await e.runtime.initialize(),await e.runtime.plugins.setEnabled(I(n,"id"),i.enabled),R(n,e.runtime.plugins.list())})),r.post("/plugins/:id/commands/:command",S(e,async(n)=>{await e.runtime.initialize();let i=await _(n);if(!Array.isArray(i.args)||i.args.length>100||i.args.some((o)=>typeof o!=="string"||o.length>1e5))throw new t("args must be an array of strings");return R(n,await e.runtime.plugins.command(I(n,"id"),I(n,"command"),i.args))})),r.get("/plugins/:id/web.js",S(e,async(n)=>{await e.runtime.initialize();let i=await e.runtime.plugins.webBundle(I(n,"id"));if(!i)return R(n,{error:"Plugin web bundle not found"},404);return new Response(i,{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-cache"}})})),r.get("/plugins/:id/web.css",S(e,async(n)=>{await e.runtime.initialize();let i=await e.runtime.plugins.webCSS(I(n,"id"));if(i===void 0)return new Response(null,{status:204});return new Response(i,{headers:{"Content-Type":"text/css; charset=utf-8","Cache-Control":"no-cache"}})})),r}function hi(e){let r=new q;return r.get("/projects",S(e,(n)=>R(n,e.runtime.projects()))),r.post("/projects",S(e,async(n)=>R(n,await e.runtime.createProject(await _(n))))),r.put("/projects/order",S(e,async(n)=>(e.runtime.reorderProjects((await _(n)).ids),R(n,{ok:!0})))),r.get("/projects/:id",S(e,(n)=>{let i=e.runtime.project(I(n,"id"));return i?R(n,i):A(n,"not_found","no such project",404)})),r.patch("/projects/:id",S(e,async(n)=>R(n,e.runtime.updateProject(I(n,"id"),await _(n))))),r.delete("/projects/:id",S(e,async(n)=>(await e.runtime.deleteProject(I(n,"id")),R(n,{ok:!0})))),r}function fi(e){let r=new q,n=e.providerAuth;if(!n)return r;return r.get("/provider-auth/openai",S(e,async(i)=>R(i,await n.status()))),r.post("/provider-auth/openai/login",S(e,async(i)=>{let o=await n.start("Basalt");return R(i,o)})),r.post("/provider-auth/openai/manual",S(e,async(i)=>{let o=await _(i);if(typeof o.url!=="string"||!o.url.trim())return A(i,"bad_request","url is required",400);return await n.manualInput(o.url),R(i,await n.status())})),r.post("/provider-auth/openai/logout",S(e,async(i)=>(await n.logout(),R(i,{ok:!0})))),r}function mi(e){let r=new q,n=e.proxy;if(!n)return r;let i=(o)=>{let s=e.proxyTargets?.()??[],a=new Set(s.map((c)=>c.id));for(let c of Object.keys(o.routes))if(!a.has(c))s.push({id:c,name:`\u672A\u542F\u7528\u7684\u7528\u9014\uFF1A${c}`});return{...o,targets:s}};return r.get("/proxy",S(e,(o)=>R(o,i(n.settings())))),r.put("/proxy",S(e,async(o)=>{let s=await _(o),a=o.req.raw;if(e.authEnabled&&!e.internalRequest?.(a)&&!e.auth.verify(H(a)))return A(o,"unauthorized","authentication expired or revoked",403);let c=n.save(s);return R(o,i(c))})),r}import{randomBytes as va}from"crypto";var xa=/^[A-Za-z0-9_-]{8,128}$/,Sa="/api/remote-access/proxy/";function gi(e){let r=new q;if(r.get("/access/handoff",S(e,(i)=>{let o=i.req.raw,s=Ta(i.req.query("origin"));if(!s)throw new t("\u7F3A\u5C11\u5408\u6CD5\u7684\u5DE5\u4F5C\u53F0 origin \u53C2\u6570");let a=i.req.query("state")?.trim()??"";if(!xa.test(a))throw new t("\u7F3A\u5C11\u5408\u6CD5\u7684 state \u53C2\u6570");let c=i.req.query("return_to"),u=c?ka(c,s):void 0;if(c&&!u)throw new t("return_to \u5FC5\u987B\u4E0E\u5DE5\u4F5C\u53F0 origin \u540C\u6E90");let l=e.allowed(s,o,{wildcard:!1}),p=e.authEnabled&&Ao(s);if(!l&&!p)return A(i,"unauthorized","origin not allowed",403);let x=o.headers.get("cf-access-jwt-assertion")?.trim()??Pa(o.headers.get("cookie"),"CF_Authorization");if(!se(x))return A(i,"bad_request","\u672A\u68C0\u6D4B\u5230\u6709\u6548\u7684 Cloudflare Access \u767B\u5F55\u51ED\u636E",400);let h={server:_a(o,e),state:a,token:x};return Ma(h,s,u,l)},{public:!0})),!e.remoteAccess)return r;let n=e.remoteAccess;return r.post("/remote-access/status",S(e,async(i)=>{let o=await _(i);if(typeof o.url!=="string"||!o.url.trim())throw new t("\u9700\u8981\u63D0\u4F9B\u8FDC\u7A0B\u670D\u52A1\u5668\u5730\u5740");return R(i,await n.status(o.url))},{localOnly:!0})),r.post("/remote-access/login",S(e,async(i)=>{let o=await _(i);if(typeof o.url!=="string"||!o.url.trim())throw new t("\u9700\u8981\u63D0\u4F9B\u8FDC\u7A0B\u670D\u52A1\u5668\u5730\u5740");return R(i,await n.startLogin(o.url))},{localOnly:!0})),r.all("/remote-access/proxy/:target/*",(i)=>{if(i.req.method==="OPTIONS")return Qe(i,e);return S(e,async(o)=>{let s=o.req.raw,a=I(o,"target"),c=Aa(s.url,a);e.disableTimeout?.(s);let u=await n.forward(a,c,s);if(u.kind==="access_required")return Response.json({error:{code:"access_required",message:"\u9700\u8981\u901A\u8FC7 Cloudflare Access \u767B\u5F55\u8BA4\u8BC1",...u.teamDomain?{details:{teamDomain:u.teamDomain}}:{}}},{status:403,headers:F(o)});let l=new Headers(u.response.headers);F(o).forEach((h,w)=>{l.set(w,h)});let p=new Response(u.response.body,{status:u.response.status,statusText:u.response.statusText,headers:l}),x=e.authEnabled?e.auth.verify(H(s)):void 0;return x?Xe(e.auth,x,p):p},{localOnly:!0})(i)}),r}function Aa(e,r){let n=new URL(e),i=`${Sa}${r}`;if(!n.pathname.startsWith(i))throw new t("\u65E0\u6548\u7684\u8FDC\u7A0B\u4EE3\u7406\u8BF7\u6C42\u8DEF\u5F84");return`${n.pathname.slice(i.length)}${n.search}`}function Ta(e){if(!e)return;try{let r=new URL(e);if(r.protocol!=="http:"&&r.protocol!=="https:")return;return r.origin}catch{return}}function ka(e,r){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.origin!==r)return;return n.hash="",n.toString()}catch{return}}function Pa(e,r){if(!e)return;for(let n of e.split(";")){let i=n.indexOf("=");if(i<=0)continue;if(n.slice(0,i).trim()!==r)continue;return n.slice(i+1).trim()}return}function _a(e,r){let n=r.tunnel?.publicURL();if(n)return n;let i=new URL(e.url),o=e.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase();return`${o==="https"||o==="http"?`${o}:`:e.headers.has("cf-connecting-ip")?"https:":i.protocol}//${i.host}`}function Ma(e,r,n,i){let o=va(16).toString("base64"),s=Buffer.from(JSON.stringify(e),"utf8").toString("base64url"),a=n?`${n}#access=${s}`:void 0,c=hr({type:"basalt:access-handoff",...e}),u=hr(r),l=hr(a??null),p=i?"true":"false",x=`<!doctype html>
17
+ <html lang="zh-CN">
18
+ <head>
19
+ <meta charset="utf-8">
20
+ <meta name="viewport" content="width=device-width,initial-scale=1">
21
+ <title>Basalt Access \u8BA4\u8BC1</title>
22
+ <style>
23
+ body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#111110;color:#e7e5e4;font-family:system-ui,-apple-system,sans-serif;padding:24px;box-sizing:border-box}
24
+ .card{max-width:380px;width:100%;border:1px solid #292524;border-radius:16px;background:#191817;padding:24px;text-align:center}
25
+ h1{font-size:16px;margin:0 0 8px;font-weight:600}
26
+ p{font-size:13px;line-height:1.6;color:#a8a29e;margin:0 0 18px;word-break:break-all}
27
+ button{appearance:none;border:0;border-radius:10px;background:#e7e5e4;color:#111110;font-size:13px;font-weight:600;padding:10px 18px;cursor:pointer;width:100%}
28
+ </style>
29
+ </head>
30
+ <body>
31
+ <div class="card">
32
+ <h1 id="title">${i?"\u8BA4\u8BC1\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u8FD4\u56DE\u5DE5\u4F5C\u53F0\u2026":"\u786E\u8BA4\u8FD4\u56DE\u5DE5\u4F5C\u53F0"}</h1>
33
+ <p id="desc">\u76EE\u6807\u5DE5\u4F5C\u53F0\uFF1A${La(r)}</p>
34
+ <button id="continue" type="button"${i?' style="display:none"':""}>\u7EE7\u7EED\u8FDE\u63A5</button>
35
+ </div>
36
+ <script nonce="${o}">
37
+ (function(){
38
+ var msg=${c};
39
+ var origin=${u};
40
+ var redirect=${l};
41
+ var btn=document.getElementById("continue");
42
+ function finish(){
43
+ if(window.opener&&!window.opener.closed){
44
+ window.opener.postMessage(msg,origin);
45
+ window.close();
46
+ document.getElementById("title").textContent="\u8BA4\u8BC1\u5DF2\u540C\u6B65\uFF0C\u53EF\u5173\u95ED\u6B64\u7A97\u53E3";
47
+ if(btn)btn.style.display="none";
48
+ return;
49
+ }
50
+ if(redirect){
51
+ window.location.replace(redirect);
52
+ return;
53
+ }
54
+ document.getElementById("title").textContent="\u5DF2\u5B8C\u6210 Cloudflare Access \u8BA4\u8BC1";
55
+ document.getElementById("desc").textContent="\u8BF7\u8FD4\u56DE\u539F\u5DE5\u4F5C\u53F0\u7A97\u53E3\u7EE7\u7EED\u8FDE\u63A5\u3002";
56
+ }
57
+ if(btn)btn.addEventListener("click",finish);
58
+ if(${p})finish();
59
+ })();
60
+ </script>
61
+ </body>
62
+ </html>`;return new Response(x,{status:200,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY","content-security-policy":`default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${o}'; frame-ancestors 'none'`}})}function hr(e){return JSON.stringify(e).replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function La(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}var qa=new Set(Xn);function Da(e){if(!e||typeof e!=="object"||Array.isArray(e))return!1;let r=e;if(typeof r.q!=="string"||r.q.length>4096)return!1;for(let n of["caseSensitive","wholeWord","deep"])if(r[n]!==void 0&&typeof r[n]!=="boolean")return!1;for(let[n,i]of[["mode",Ca],["sort",Ra],["group",Ia]])if(r[n]!==void 0&&!i.some((o)=>o===r[n]))return!1;if(r.limit!==void 0&&(typeof r.limit!=="number"||!Number.isInteger(r.limit)||r.limit<1||r.limit>200))return!1;if(r.cursor!==void 0&&(typeof r.cursor!=="string"||r.cursor.length>262144))return!1;if(r.filters!==void 0){if(!r.filters||typeof r.filters!=="object"||Array.isArray(r.filters))return!1;let n=r.filters;for(let i of["projectID","sessionID","fields","tools","model"]){let o=n[i];if(o!==void 0&&(!Array.isArray(o)||o.length>100||!o.every((s)=>typeof s==="string"&&s.length<=1024&&(i!=="fields"||qa.has(s)))))return!1}for(let i of["isError","archived","compacted"])if(n[i]!==void 0&&typeof n[i]!=="boolean")return!1;for(let i of["after","before"])if(n[i]!==void 0&&(typeof n[i]!=="number"||!Number.isFinite(n[i])))return!1}return!0}function wi(e){let r=new q,n=new Map,i=(o)=>{let s=Date.now(),a=e.requestConnection?.(o)??e.requestIP(o)??"local";for(let[u,l]of n)if(s-l.start>=1000)n.delete(u);let c=n.get(a)??{start:s,count:0};return c.count++,n.set(a,c),c.count>20};return r.get("/search/settings",S(e,(o)=>{let s=e.runtime.searchStatus();return R(o,{enabled:s.state!=="disabled",status:s})})),r.put("/search/settings",S(e,async(o)=>{let s=await o.req.json();if(!s||typeof s!=="object"||!("enabled"in s)||typeof s.enabled!=="boolean")return A(o,"bad_request","enabled must be a boolean",400);let a=await e.runtime.setSearchEnabled(s.enabled);return R(o,{enabled:a.state!=="disabled",status:a})})),r.post("/search/rebuild",S(e,async(o)=>{if(e.runtime.searchStatus().state==="disabled")return A(o,"bad_request","\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528",409);return await e.runtime.search.rebuild(),R(o,e.runtime.searchStatus())})),r.get("/search/status",S(e,(o)=>R(o,e.runtime.searchStatus()))),r.get("/search/suggest",S(e,(o)=>{if(i(o.req.raw))return R(o,{error:{code:"rate_limited",message:"too many searches"}},429);let s=o.req.query("q");if(s===void 0||s.length>4096)return A(o,"bad_request","q is required (maximum 4096 characters)",400);return R(o,{terms:jn(e.runtime.search,s)})})),r.post("/search",S(e,async(o)=>{if(i(o.req.raw))return R(o,{error:{code:"rate_limited",message:"too many searches"}},429);let s=await o.req.json();if(!Da(s))return A(o,"bad_request","invalid search request",400);if(s.cursor)try{qr(s,s.filters?.sessionID?.length===1?s.filters.sessionID[0]:void 0)}catch{return A(o,"bad_request","invalid search cursor",400)}let a=new AbortController,c=()=>a.abort(),u=o.req.raw.signal;if(u.addEventListener("abort",c,{once:!0}),u.aborted)a.abort();let l=new TextEncoder,p=!1,x=new ReadableStream({async start(w){if(a.signal.aborted){w.close(),u.removeEventListener("abort",c);return}let T=()=>{if(!p)w.close()};a.signal.addEventListener("abort",T,{once:!0});try{if(await mr(e.runtime,s,{signal:a.signal,sessionID:s.filters?.sessionID?.length===1?s.filters.sessionID[0]:void 0,onEvent(M){w.enqueue(l.encode(`${JSON.stringify(M)}
63
+ `))}}),!a.signal.aborted)w.close()}catch(M){if(!a.signal.aborted)w.error(M)}finally{a.signal.removeEventListener("abort",T),u.removeEventListener("abort",c)}},cancel(){p=!0,a.abort(),u.removeEventListener("abort",c)}}),h=new Headers(R(o,null).headers);return h.set("content-type","application/x-ndjson; charset=utf-8"),h.set("cache-control","no-store"),new Response(x,{headers:h})})),r}import{open as Wa,realpath as bi}from"fs/promises";import{isAbsolute as Na,relative as ja,resolve as $a}from"path";import Oa from"sharp";class fr{cached=new Map;pending=new Map;bytes=0;tail=Promise.resolve();get(e,r){let n=this.cached.get(e);if(n)return Promise.resolve(n);let i=this.pending.get(e);if(i)return i;if(this.pending.size>=16)return Promise.reject(Error("thumbnail queue full"));let o=this.tail.then(async()=>{let s=await Oa(r(),{limitInputPixels:40000000,pages:1}).autoOrient().resize({width:640,height:640,fit:"inside",withoutEnlargement:!0}).webp({quality:72,effort:2}).timeout({seconds:10}).toBuffer();while(this.bytes+s.byteLength>33554432){let a=this.cached.entries().next().value;if(!a)break;this.cached.delete(a[0]),this.bytes-=a[1].byteLength}return this.cached.set(e,s),this.bytes+=s.byteLength,s});return this.pending.set(e,o),this.tail=o.catch(()=>{return}),o.finally(()=>this.pending.delete(e)).catch(()=>{return}),o}}var Ha=150,Ba=(e)=>Ss.includes(e);function xi(e){let r=new q,n=new fr;return r.get("/sessions",S(e,(i)=>{let o=i.req.query("archive")??"active";if(!Ba(o))return A(i,"bad_request",`archive must be ${Ss.join(", ")}`,400);return R(i,e.runtime.list(i.req.query("includeChildren")==="true",{archive:o}))})),r.post("/sessions",S(e,async(i)=>{let o=await _(i),s=e.runtime.create({projectID:o.projectID,title:o.title,model:o.model,thinking:o.thinking});return await e.runtime.plugins.idle(),R(i,s.info())})),r.get("/sessions/:id",S(e,(i)=>{let o=e.runtime.get(I(i,"id"));return o?R(i,o.info()):A(i,"not_found","no such session",404)})),r.get("/sessions/:id/image",S(e,async(i)=>{let o=e.runtime.get(I(i,"id"));if(!o)return A(i,"not_found","no such session",404);let s=o.projectID?e.runtime.project(o.projectID):void 0;if(!s||s.remote)return A(i,"bad_request","\u56FE\u7247\u9700\u8981\u672C\u673A\u9879\u76EE\u4E0A\u4E0B\u6587",400);let a=i.req.query("path");if(!a||a.includes("\x00"))return A(i,"bad_request","\u56FE\u7247\u8DEF\u5F84\u65E0\u6548",400);let c=await bi(s.directory),u=$a(c,a),l=(p)=>{let x=ja(c,p);return x!==".."&&!x.startsWith("../")&&!x.startsWith("..\\")&&!Na(x)};if(!l(u))return A(i,"bad_request","\u56FE\u7247\u5FC5\u987B\u4F4D\u4E8E\u5F53\u524D\u9879\u76EE\u5185",400);try{let p=await bi(u);if(!l(p))return A(i,"bad_request","\u56FE\u7247\u5FC5\u987B\u4F4D\u4E8E\u5F53\u524D\u9879\u76EE\u5185",400);let x=await Wa(p,"r");try{let h=await x.stat();if(!h.isFile()||h.size>10485760)return A(i,"bad_request","\u53EA\u652F\u6301\u4E0D\u8D85\u8FC7 10 MB \u7684\u4F4D\u56FE\u6587\u4EF6",400);let w=await x.readFile(),T=Yr(w);if(!T)return A(i,"bad_request","\u4E0D\u652F\u6301\u7684\u56FE\u7247\u683C\u5F0F",400);let M=F(i);return M.set("content-type",T),M.set("cache-control","no-store"),M.set("x-content-type-options","nosniff"),new Response(w,{headers:M})}finally{await x.close()}}catch(p){if(p&&typeof p==="object"&&"code"in p&&["ENOENT","ENOTDIR","EACCES"].includes(String(p.code)))return A(i,"not_found","\u9879\u76EE\u56FE\u7247\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB",404);throw p}})),r.post("/sessions/:id/shell-approvals/:aid",S(e,async(i)=>{let o=e.runtime.get(I(i,"id"));if(!o)return A(i,"not_found","no such session",404);let s=await _(i);if(typeof s.approved!=="boolean")throw new t("approved must be a boolean");o.assertWritable();let a=oi(o,I(i,"aid"),s.approved);if(a==="unknown")return A(i,"not_found","\u6388\u6743\u8BF7\u6C42\u4E0D\u5B58\u5728\u6216\u5DF2\u5931\u6548",404);return R(i,{ok:!0,expired:a==="expired"})})),r.patch("/sessions/:id",S(e,async(i)=>{let o=e.runtime.get(I(i,"id"));if(!o)return A(i,"not_found","no such session",404);let s=await _(i);if("archived"in s){if(typeof s.archived!=="boolean"||Object.keys(s).length!==1)return A(i,"bad_request","archived must be a boolean and cannot be mixed with other fields",400);return R(i,e.runtime.setArchived(o.id,s.archived))}if(o.assertWritable(),s.title!==void 0&&typeof s.title!=="string")return A(i,"bad_request","title must be a string",400);if(s.model!==void 0)e.runtime.checkModel(s.model);if(s.thinking!==void 0&&s.thinking!==null&&typeof s.thinking!=="string")return A(i,"bad_request","thinking must be a string or null",400);if(s.title!==void 0)o.rename(s.title);if(s.model!==void 0)o.setModel(s.model);if(s.thinking!==void 0)o.setThinking(s.thinking);return R(i,o.info())})),r.delete("/sessions/:id",S(e,async(i)=>(await e.runtime.deleteSession(I(i,"id")),await e.runtime.plugins.idle(),R(i,{ok:!0})))),r.get("/sessions/:id/export",S(e,(i)=>{let o=I(i,"id"),s=e.runtime.exportSession(o),a=R(i,s);return a.headers.set("content-disposition",`attachment; filename="basalt-${o}.json"`),a})),r.post("/sessions/import",S(e,async(i)=>{let o=e.runtime.parseImport(await _(i)),s=e.runtime.importSession(o,{projectID:i.req.query("projectID")||void 0,model:i.req.query("model")||void 0});return await e.runtime.plugins.idle(),R(i,s.info())})),r.get("/sessions/:id/last-model-request",S(e,(i)=>{let o=e.runtime.get(I(i,"id"));if(!o)return A(i,"not_found","no such session",404);let s=o.lastModelRequest();return s?R(i,s):A(i,"not_found","\u8BE5\u4F1A\u8BDD\u5728\u672C\u8FDB\u7A0B\u5185\u8FD8\u6CA1\u6709\u53D1\u51FA\u8FC7\u6A21\u578B\u8BF7\u6C42\uFF08\u5FEB\u7167\u9A7B\u7559\u5185\u5B58\uFF0C\u91CD\u542F\u5373\u6E05\u7A7A\uFF09",404)})),r.get("/sessions/:id/last-model-response",S(e,(i)=>{let o=e.runtime.get(I(i,"id"));if(!o)return A(i,"not_found","no such session",404);let s=o.lastModelResponse();return s?R(i,s):A(i,"not_found","\u8BE5\u4F1A\u8BDD\u5728\u672C\u8FDB\u7A0B\u5185\u8FD8\u6CA1\u6709\u6536\u5230\u8FC7\u6A21\u578B\u54CD\u5E94\uFF08\u5FEB\u7167\u9A7B\u7559\u5185\u5B58\uFF0C\u91CD\u542F\u5373\u6E05\u7A7A\uFF09",404)})),r.get("/blobs/:hash",S(e,async(i)=>{let o=I(i,"hash"),s=/^[0-9a-f]{64}$/.test(o)?e.runtime.store.blob(o):void 0;if(!s)return A(i,"not_found","no such blob",404);let a=/^image\/(png|jpeg|gif|webp|avif|bmp)$/.test(s.mime),c=F(i),u=s.data,l=a?s.mime:"application/octet-stream";if(i.req.query("variant")==="thumbnail"){if(!a)return A(i,"bad_request","unsupported thumbnail format",400);try{u=new Uint8Array(await n.get(o,()=>s.data)),l="image/webp"}catch{return A(i,"bad_request","thumbnail unavailable; retry or open the original image",422)}}return c.set("content-type",l),c.set("cache-control","private, max-age=31536000, immutable"),c.set("x-content-type-options","nosniff"),c.set("content-security-policy","default-src 'none'; sandbox"),new Response(u,{headers:c})})),r.get("/sessions/:id/entries",S(e,(i)=>{let o=e.runtime.get(I(i,"id"));if(!o)return A(i,"not_found","no such session",404);let s=(h)=>Number(i.req.query(h)??Ha),a=i.req.query("images")!=="ref",c=i.req.query("around");if(c!==void 0){let h=Number(c),w=s("before"),T=s("after");if(![h,w,T].every(Number.isSafeInteger)||h<1||w<0||T<0)return A(i,"bad_request","invalid around/before/after",400);return R(i,o.entriesAround(h,Math.min(w,2000),Math.min(T,2000),a))}let u=i.req.query("from");if(u!==void 0){let h=Number(u),w=Number(i.req.query("limit")??300);if(!Number.isSafeInteger(h)||h<1||!Number.isSafeInteger(w)||w<1)return A(i,"bad_request","invalid from/limit",400);return R(i,o.entriesFrom(h,Math.min(w,2000),a))}let l=i.req.query("tail");if(l!==void 0){let h=Number(l);if(!Number.isSafeInteger(h)||h<1)return A(i,"bad_request","invalid tail",400);let w=e.runtime.store.truncationEpoch(o.id),T={entries:o.replayEntries(Math.min(h,2000),a),truncationEpoch:w};return R(i,T)}let p=i.req.query("before");if(p!==void 0){let h=Number(p),w=Number(i.req.query("limit")??300);if(!Number.isSafeInteger(h)||h<1||!Number.isSafeInteger(w)||w<1)return A(i,"bad_request","invalid before/limit",400);return R(i,o.entriesBefore(h,Math.min(w,2000),a))}let x=Number(i.req.query("after")??0);return R(i,o.entries(x,void 0,a))})),r.post("/sessions/:id/prompt",vi(e,!1)),r.post("/sessions/:id/steer",vi(e,!0)),r.post("/sessions/:id/unsteer",S(e,async(i)=>{let o=e.runtime.get(I(i,"id"));if(!o)return A(i,"not_found","no such session",404);let s=await _(i);if(!Number.isSafeInteger(s.seq)||s.seq<1)return A(i,"bad_request","invalid seq",400);if(!o.unsteer(s.seq))return A(i,"bad_request","\u5F15\u5BFC\u6D88\u606F\u5DF2\u9001\u8FBE\u6A21\u578B\u6216\u4E0D\u53EF\u64A4\u56DE",409);return R(i,{ok:!0})})),r.post("/sessions/:id/abort",S(e,(i)=>{let o=e.runtime.get(I(i,"id"));if(!o)return A(i,"not_found","no such session",404);return o.abort(),R(i,{ok:!0})})),r}function vi(e,r){return S(e,async(n)=>{let i=e.runtime.get(I(n,"id"));if(!i)return A(n,"not_found","no such session",404);i.assertWritable();let o=e.runtime.plugins.pin();try{let u=await o.invoke("session.input",{error:i.info().parentID?"Direct input to a managed session is unavailable":void 0},i);if(u.error)return A(n,"bad_request",u.error,400)}finally{await o.release()}let s=await _(n),a=typeof s.text==="string"?s.text:"";if(s.attachments!==void 0){if(!Array.isArray(s.attachments)||s.attachments.length>ot||!s.attachments.every(Et))return A(n,"bad_request","invalid attachments",400)}let c=s.attachments?.length?s.attachments:void 0;if(!a.trim()&&!c)return A(n,"bad_request","text is required",400);if(r||s.steer)i.steer(a,c);else i.prompt(a,c);return R(n,i.info())})}function Si(e){let r=new q;return r.get("/tool-loading",S(e,async(n)=>{await e.runtime.initialize();let i=n.req.query("sessionID"),o=i?e.runtime.get(i):void 0;if(i&&!o)throw new d("no such session");let s=o?await o.toolLoadingInfo():e.runtime.toolLoading.partition(e.runtime.tools.list());return R(n,{settings:e.runtime.toolLoading.settings(),tools:s})})),r.patch("/tool-loading",S(e,async(n)=>{let i=await _(n);try{return R(n,e.runtime.toolLoading.update(i))}catch(o){throw new t(o instanceof Error?o.message:"Invalid tool loading settings")}})),r}function Ri(e){let r=new q,n=e.tunnel;if(!n)return r;return r.get("/tunnel",S(e,(i)=>R(i,n.inspectStatus()),{localOnly:!0})),r.put("/tunnel",S(e,async(i)=>{if(!e.authEnabled)throw new t("\u5DF2\u7528 --no-auth \u5173\u95ED\u8BA4\u8BC1\uFF0C\u4E0D\u80FD\u5F00\u542F\u8FDC\u7A0B\u8BBF\u95EE");return R(i,await n.save(await _(i)))},{localOnly:!0})),r.put("/tunnel/cloudflare",S(e,async(i)=>{if(!e.authEnabled)throw new t("\u5173\u95ED\u8BA4\u8BC1\u65F6\u4E0D\u80FD\u8FDE\u63A5 Cloudflare");let o=await _(i);return R(i,await n.connectCloudflare(o.token))},{localOnly:!0})),r.post("/tunnel/refresh",S(e,async(i)=>R(i,await n.refreshManagement()),{localOnly:!0})),r.put("/tunnel/managed",S(e,async(i)=>{if(!e.authEnabled)throw new t("\u5173\u95ED\u8BA4\u8BC1\u65F6\u4E0D\u80FD\u4FEE\u6539\u8FDC\u7A0B\u8BBF\u95EE");return R(i,await n.configureManaged(await _(i)))},{localOnly:!0})),r.put("/tunnel/managed-access",S(e,async(i)=>{if(!e.authEnabled)throw new t("\u5173\u95ED\u8BA4\u8BC1\u65F6\u4E0D\u80FD\u4FEE\u6539\u8FDC\u7A0B\u8BBF\u95EE");return R(i,await n.configureManagedAccess(await _(i)))},{localOnly:!0})),r.post("/tunnel/login",S(e,(i)=>{if(!e.authEnabled)throw new t("\u5DF2\u7528 --no-auth \u5173\u95ED\u8BA4\u8BC1\uFF0C\u4E0D\u80FD\u5F00\u542F\u8FDC\u7A0B\u8BBF\u95EE");return R(i,n.startLogin())},{localOnly:!0})),r.delete("/tunnel/login",S(e,(i)=>R(i,n.cancelLogin()),{localOnly:!0})),r.post("/tunnel/provision",S(e,async(i)=>{if(!e.authEnabled)throw new t("\u5DF2\u7528 --no-auth \u5173\u95ED\u8BA4\u8BC1\uFF0C\u4E0D\u80FD\u5F00\u542F\u8FDC\u7A0B\u8BBF\u95EE");return R(i,await n.provision(await _(i)))},{localOnly:!0})),r.put("/tunnel/access",S(e,async(i)=>{let o=await _(i);return R(i,await n.setAccess(o.access??null))},{localOnly:!0})),r.delete("/tunnel",S(e,async(i)=>R(i,await n.remove()),{localOnly:!0})),r}function Ai(e){let r=new q,n=e.updates;if(!n)return r;return r.get("/update",S(e,(i)=>R(i,n.status()))),r.post("/update/check",S(e,async(i)=>R(i,await n.check()))),r.post("/update/apply",S(e,async(i)=>{if(!n.status().canApply)return A(i,"bad_request","this installation cannot update itself",400);return R(i,await n.apply())})),r}function Ti(e){let r=new WeakSet;e={...e,internalRequest:(o)=>r.has(o)};let n=new q;e.runtime.http={baseUrl:null,auth:e.authEnabled?"token":"none",async request(o){r.add(o);try{return await n.fetch(o)}finally{r.delete(o)}}};let i=Qn({contentTypeFilter:/^application\/json/});return n.use("/api/*",(o,s)=>r.has(o.req.raw)||o.req.path.startsWith("/api/remote-access/proxy/")?s():i(o,s)),n.route("/api",ui(e)),n.route("/api",ti(e)),n.route("/api",Si(e)),n.route("/api",li(e)),n.route("/api",di(e)),n.route("/api",fi(e)),n.route("/api",mi(e)),n.route("/api",Ai(e)),n.route("/api",Ri(e)),n.route("/api",gi(e)),n.route("/api",ei(e)),n.route("/api",hi(e)),n.route("/api",xi(e)),n.route("/api",pi(e)),n.route("/api",wi(e)),n.route("/api",ri(e)),n.all("/api/*",async(o)=>{if(o.req.method==="OPTIONS")return Qe(o,e);if(!e.runtime.plugins.hasRoute(o.req.raw)){if(await e.runtime.initialize(),!e.runtime.plugins.hasRoute(o.req.raw))return A(o,"not_found","not found",404)}let s=e.runtime.plugins.isPublicRoute(o.req.raw);return S(e,async(a)=>{await e.runtime.initialize();let c=await e.runtime.plugins.route(a.req.raw);if(!c)return A(a,"not_found","not found",404);let u=a.req.header("origin");if(u)c.headers.set("access-control-allow-origin",u),c.headers.set("vary","origin");let l=e.authEnabled&&!s?e.auth.verify(H(a.req.raw)):void 0;if(!l)return c;return Xe(e.auth,l,c)},{public:s})(o)}),n}var Ja=1e4,Ka=5000;function Eo(e){let{runtime:r}=e,n=new ze(e.dataDir),i=e.remoteAccess??new Fe(e.dataDir),o=e.network,s=new Set,a={name:"basalt",version:e.version,protocol:vr,auth:e.auth,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,shell:r.serverShell()},c=!e.auth&&Ee(e.host),u=(v,P,C={})=>{if(c&&!Qt(P))return!1;let O=new URL(P.url).hostname.toLowerCase(),W=e.tunnel?.publicURL(),Z=W?new URL(W).hostname.toLowerCase():void 0,ee=Ce("0.0.0.0",e.port).map((dt)=>dt.address);if(!Ee(O)&&O!==e.host.toLowerCase()&&O!==Z&&!ee.includes(O)&&!e.allowedHosts?.some((dt)=>dt.toLowerCase()===O))return!1;if(!v)return!0;let We=new URL(P.url);if(v===We.origin||Ga(v,We))return!0;if(e.tunnel?.publicURL()===v)return!0;if(e.auth&&C.wildcard!==!1&&Ao(v))return!0;return C.wildcard!==!1&&e.origins.includes("*")||e.origins.includes(v)},l,p=async(v)=>{let P=e.tunnel?.access();if(!P)return!1;let C=`${P.teamDomain}/${P.audience}`;if(l?.key!==C)l={key:C,value:Ot(P)};return l.value.denies(v)},x,h=!1,w=new Map,T=new WeakMap,M=Ti({runtime:r,auth:n,authEnabled:e.auth,info:a,allowed:u,requestIP:(v)=>(T.get(v)??x)?.requestIP(v)?.address,requestConnection:(v)=>{let P=(T.get(v)??x)?.requestIP(v);return P?`${P.address}:${P.port}`:void 0},modelProviders:e.modelProviders,network:o?{manager:o,runtime:()=>({host:e.host,port:x?.port??e.port,auth:e.auth,lanActive:h,addresses:Ce("0.0.0.0",x?.port??e.port).filter((v)=>w.has(v.address)),hostOverride:e.networkHostOverride}),save:(v)=>o.save(v,le)}:void 0,providerAuth:e.providerAuth,proxy:e.proxy,proxyTargets:e.proxyTargets,updates:e.updates,restart:e.restart,shutdown:e.shutdown,autostart:e.autostart,tunnel:e.tunnel,remoteAccess:i,accessDenied:p,approveLocalPairing:e.approveLocalPairing,cliSecret:e.cliSecret,disableTimeout:(v)=>(T.get(v)??x)?.timeout(v,0),heartbeatMs:e.heartbeatMs}),E=(v,P)=>{v.send(JSON.stringify(P))},D=r.subscribe((v)=>{if(v.type==="aborted")return;let P=v,C=v.type==="entry"||v.type==="draft"||v.type==="truncated"||v.type==="entry_removed"?v.sessionID:void 0,O=v.type==="entry"&&v.entry.type==="run"&&v.entry.state==="end"?{type:"run_end",sessionID:v.sessionID,entry:v.entry}:void 0;for(let W of r.connections.values()){if(!C||W.sessions.has(C))W.send(P);if(O)W.send(O)}}),L=async(v,P)=>{if(T.set(v,P),await p(v))return new Response(null,{status:403});if(!u(v.headers.get("origin"),v))return new Response("origin not allowed",{status:403});let C=new URL(v.url).pathname,O=C==="/api/ws"?void 0:r.plugins.websocket(C);if(C!=="/api/ws"&&!O)return new Response("not found",{status:404});let W=K({requestIP:(Z)=>P.requestIP(Z)?.address},v);if(P.upgrade(v,{data:{authed:!1,localManagement:W,subscriptions:new Set,pluginRoute:O}}))return;return new Response("expected websocket",{status:400})},N=e.web&&!e.development?Bun.serve({hostname:"127.0.0.1",port:0,development:!1,routes:{"/*":e.web},fetch:()=>new Response("not found",{status:404})}):void 0,U=Object.fromEntries(Object.entries(e.webStatic??{}).map(([v,P])=>[v,async(C)=>{if(await p(C))return new Response(null,{status:403});return P(C)}])),G={};if(N)G["/*"]=async(v)=>{if(await p(v))return new Response(null,{status:403});let P=new URL(v.url),C=new URL(N.url);return C.pathname=P.pathname,C.search=P.search,fetch(C,{method:v.method,headers:v.headers,redirect:"manual",decompress:!1})};else if(e.web)G["/*"]=e.web;let ie={hostname:e.host,...o&&e.networkHostOverride===void 0?{reusePort:!0}:{},...e.idleTimeout===void 0?{}:{idleTimeout:e.idleTimeout},development:e.development?{hmr:!0,console:!1}:!1,routes:{"/api/ws":L,"/api/*":(v,P)=>(T.set(v,P),v.headers.get("upgrade")?.toLowerCase()==="websocket"?L(v,P):M.fetch(v)),...U,...G},fetch(v,P){if(v.url.includes("/api/"))return T.set(v,P),M.fetch(v);return new Response("not found",{status:404})},websocket:{open(v){s.add(v),v.data.helloTimer=setTimeout(()=>{if(!v.data.authed)v.close(4401,"hello timeout")},Ja)},async close(v){clearTimeout(v.data.helloTimer),s.delete(v);try{await v.data.connection?.dispose()}finally{await v.data.pluginConnection?.close()}},async message(v,P){if(v.data.authed&&v.data.pluginConnection){if(v.data.expires!==void 0&&Date.now()>=v.data.expires){v.close(4401,"authentication expired");return}await v.data.pluginConnection.message(String(P));return}let C;try{if(C=JSON.parse(String(P)),!C||typeof C!=="object"||typeof C.type!=="string")throw Error("Invalid client message")}catch{if(E(v,{type:"error",code:"bad_request",message:"invalid JSON"}),!v.data.authed)v.close(4400,"invalid hello");return}if(C.type==="hello"){if(C.protocol!==vr){E(v,{type:"error",code:"protocol_mismatch",message:`server speaks protocol ${vr}, client ${C.protocol}`}),v.close(4400,"protocol mismatch");return}let W=e.auth?n.verify(C.token):void 0;if(e.auth&&!W){E(v,{type:"error",code:"unauthorized",message:"missing or invalid token"}),v.close(4401,"unauthorized");return}if(v.data.authed){v.close(4400,"already authenticated");return}if(clearTimeout(v.data.helloTimer),v.data.authed=!0,v.data.deviceID=W?.id,v.data.expires=W?.token.expires,v.data.connection=Ie(r,{deviceID:W?.id,expires:W?.token.expires},v.data.subscriptions,(Z)=>E(v,Z),(Z,ee)=>{v.data.authed=!1,v.close(Z,ee)}),E(v,{type:"welcome",server:{...a,localManagement:v.data.localManagement}}),v.data.pluginRoute){let Z={send(ee){if(v.data.expires!==void 0&&Date.now()>=v.data.expires){v.close(4401,"authentication expired");return}if(v.data.authed&&s.has(v))v.send(ee)},close(ee,We){v.close(ee,We)}};v.data.pluginConnection=v.data.pluginRoute.connect(Z);try{await v.data.pluginConnection.open()}catch(ee){console.error("\u63D2\u4EF6 WebSocket \u8FDE\u63A5\u521D\u59CB\u5316\u5931\u8D25\uFF1A",ee),v.close(1011,"plugin connection failed")}}return}if(!v.data.authed){v.close(4401,"hello first");return}if(v.data.expires!==void 0&&Date.now()>=v.data.expires){v.close(4401,"authentication expired");return}let O=v.data.connection;if(O&&(C.type==="subscribe"||C.type==="unsubscribe"))try{await O.enqueue(()=>ve(r,O,C),C.sessionID)}catch(W){if(!(W instanceof t)&&!(W instanceof d))throw W;O.send({type:"error",code:W instanceof d?"not_found":"bad_request",message:W.message})}}}};function xe(){if(!h||!x)return;let v=x.port??e.port,P=Ce("0.0.0.0",v),C=new Set(P.map((O)=>O.address));for(let[O,W]of w){if(C.has(O))continue;w.delete(O),Oe(W,!0)}for(let{address:O}of P){if(w.has(O))continue;let W=Bun.serve({...ie,hostname:O,port:v});w.set(O,W)}}function le(v){if(!v.lanEnabled){let C=[...w.values()];if(h=!1,w.clear(),C.length===0)return;for(let W of C)Oe(W,!1);setTimeout(()=>{for(let W of C)Oe(W,!0)},300).unref?.();return}if(!x)throw Error("\u672C\u673A\u670D\u52A1\u5C1A\u672A\u542F\u52A8\uFF0C\u65E0\u6CD5\u5F00\u542F\u5C40\u57DF\u7F51\u8BBF\u95EE\u3002");let P=!h;h=!0;try{xe()}catch(C){if(P){h=!1;for(let O of w.values())Oe(O,!0);w.clear()}throw Error("\u5F00\u542F\u5C40\u57DF\u7F51\u76D1\u542C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7AEF\u53E3\u5360\u7528\u548C\u7CFB\u7EDF\u7F51\u7EDC\u6743\u9650\u540E\u91CD\u8BD5\u3002",{cause:C})}}let Se=e.fallbackPort?100:1,X=e.port,gr;for(let v=0;v<Se;v++)try{x=Bun.serve({...ie,port:X});break}catch(P){gr=P;let C=P instanceof Error&&"code"in P&&P.code==="EADDRINUSE"||P instanceof Error&&P.message.includes("EADDRINUSE");if(e.fallbackPort&&C){X++;continue}throw N?.stop(!0),D(),P}if(!x)throw N?.stop(!0),D(),gr??Error(`Could not bind to any port starting from ${e.port}`);if(o?.settings().lanEnabled&&e.networkHostOverride===void 0)le(o.settings());let ki=n.onRevoke((v)=>{for(let P of r.connections.values())if(P.deviceID===v)P.close(4401,"authentication revoked")}),Ei=setInterval(()=>{for(let v of r.connections.values())if("expires"in v&&typeof v.expires==="number"&&Date.now()>=v.expires)v.close(4401,"authentication expired")},1000),yr=setInterval(()=>{try{xe()}catch(v){console.error("\u5237\u65B0\u5C40\u57DF\u7F51\u76D1\u542C\u5931\u8D25\uFF0C\u5C06\u5728\u4E0B\u4E00\u6B21\u5DE1\u68C0\u65F6\u91CD\u8BD5\uFF1A",v)}},Ka);yr.unref?.();let Y=e.host;if(Y==="0.0.0.0")Y="127.0.0.1";if(Y==="::")Y="::1";if(Y.includes(":")&&!Y.startsWith("["))Y=`[${Y}]`;let wr=`http://${Y}:${x.port}`,ut=r.http;if(ut)ut.baseUrl=wr;let lt=e.development&&e.tunnel?wn(wr,p):void 0,Re=new URL(x.url);if(Re.hostname==="0.0.0.0")Re.hostname="127.0.0.1";if(Re.hostname==="[::]")Re.hostname="[::1]";return{server:x,auth:n,url:Re.toString().replace(/\/$/,""),tunnelPort:lt?lt.port:x.port,async stop(){for(let v of w.values())Oe(v,!0);if(w.clear(),clearInterval(yr),await i.stop(),lt?.stop(),N?.stop(!0),r.http===ut)r.http=void 0;D(),ki(),clearInterval(Ei);for(let v of s)clearTimeout(v.data.helloTimer);for(let v of r.connections.values())v.close(1001,"server stopping");x.stop(!0),await r.plugins.idle()}}}function Oe(e,r){e.stop(r).catch((n)=>console.error("\u505C\u6B62\u5C40\u57DF\u7F51\u76D1\u542C\u5931\u8D25\uFF1A",n))}function Ga(e,r){try{let n=new URL(e);return n.protocol===r.protocol&&n.port===r.port&&Ee(n.hostname)&&Ee(r.hostname)}catch{return!1}}export{k,Le,Tn,za,Qs,vo,_o,kn,Wt,Eo};